1 // SPDX-License-Identifier: GPL-2.0-or-later
5 * Copyright (C) 1995-99 Simon G. Vogl
6 * With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>
7 * Mux support by Rodolfo Giometti <giometti@enneenne.com> and
8 * Michael Lawnick <michael.lawnick.ext@nsn.com>
10 * Copyright (C) 2013-2017 Wolfram Sang <wsa@kernel.org>
13 #define pr_fmt(fmt) "i2c-core: " fmt
15 #include <dt-bindings/i2c/i2c.h>
16 #include <linux/acpi.h>
17 #include <linux/clk/clk-conf.h>
18 #include <linux/completion.h>
19 #include <linux/delay.h>
20 #include <linux/err.h>
21 #include <linux/errno.h>
22 #include <linux/gpio/consumer.h>
23 #include <linux/i2c.h>
24 #include <linux/i2c-smbus.h>
25 #include <linux/idr.h>
26 #include <linux/init.h>
27 #include <linux/interrupt.h>
28 #include <linux/irqflags.h>
29 #include <linux/jump_label.h>
30 #include <linux/kernel.h>
31 #include <linux/module.h>
32 #include <linux/mutex.h>
33 #include <linux/of_device.h>
35 #include <linux/of_irq.h>
36 #include <linux/pinctrl/consumer.h>
37 #include <linux/pm_domain.h>
38 #include <linux/pm_runtime.h>
39 #include <linux/pm_wakeirq.h>
40 #include <linux/property.h>
41 #include <linux/rwsem.h>
42 #include <linux/slab.h>
46 #define CREATE_TRACE_POINTS
47 #include <trace/events/i2c.h>
49 #define I2C_ADDR_OFFSET_TEN_BIT 0xa000
50 #define I2C_ADDR_OFFSET_SLAVE 0x1000
52 #define I2C_ADDR_7BITS_MAX 0x77
53 #define I2C_ADDR_7BITS_COUNT (I2C_ADDR_7BITS_MAX + 1)
55 #define I2C_ADDR_DEVICE_ID 0x7c
58 * core_lock protects i2c_adapter_idr, and guarantees that device detection,
59 * deletion of detected devices are serialized
61 static DEFINE_MUTEX(core_lock);
62 static DEFINE_IDR(i2c_adapter_idr);
64 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
66 static DEFINE_STATIC_KEY_FALSE(i2c_trace_msg_key);
67 static bool is_registered;
69 int i2c_transfer_trace_reg(void)
71 static_branch_inc(&i2c_trace_msg_key);
75 void i2c_transfer_trace_unreg(void)
77 static_branch_dec(&i2c_trace_msg_key);
80 const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
81 const struct i2c_client *client)
87 if (strcmp(client->name, id->name) == 0)
93 EXPORT_SYMBOL_GPL(i2c_match_id);
95 static int i2c_device_match(struct device *dev, struct device_driver *drv)
97 struct i2c_client *client = i2c_verify_client(dev);
98 struct i2c_driver *driver;
101 /* Attempt an OF style match */
102 if (i2c_of_match_device(drv->of_match_table, client))
105 /* Then ACPI style match */
106 if (acpi_driver_match_device(dev, drv))
109 driver = to_i2c_driver(drv);
111 /* Finally an I2C match */
112 if (i2c_match_id(driver->id_table, client))
118 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
120 struct i2c_client *client = to_i2c_client(dev);
123 rc = of_device_uevent_modalias(dev, env);
127 rc = acpi_device_uevent_modalias(dev, env);
131 return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
134 /* i2c bus recovery routines */
135 static int get_scl_gpio_value(struct i2c_adapter *adap)
137 return gpiod_get_value_cansleep(adap->bus_recovery_info->scl_gpiod);
140 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
142 gpiod_set_value_cansleep(adap->bus_recovery_info->scl_gpiod, val);
145 static int get_sda_gpio_value(struct i2c_adapter *adap)
147 return gpiod_get_value_cansleep(adap->bus_recovery_info->sda_gpiod);
150 static void set_sda_gpio_value(struct i2c_adapter *adap, int val)
152 gpiod_set_value_cansleep(adap->bus_recovery_info->sda_gpiod, val);
155 static int i2c_generic_bus_free(struct i2c_adapter *adap)
157 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
158 int ret = -EOPNOTSUPP;
160 if (bri->get_bus_free)
161 ret = bri->get_bus_free(adap);
162 else if (bri->get_sda)
163 ret = bri->get_sda(adap);
168 return ret ? 0 : -EBUSY;
172 * We are generating clock pulses. ndelay() determines durating of clk pulses.
173 * We will generate clock with rate 100 KHz and so duration of both clock levels
174 * is: delay in ns = (10^6 / 100) / 2
176 #define RECOVERY_NDELAY 5000
177 #define RECOVERY_CLK_CNT 9
179 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
181 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
182 int i = 0, scl = 1, ret = 0;
184 if (bri->prepare_recovery)
185 bri->prepare_recovery(adap);
187 pinctrl_select_state(bri->pinctrl, bri->pins_gpio);
190 * If we can set SDA, we will always create a STOP to ensure additional
191 * pulses will do no harm. This is achieved by letting SDA follow SCL
192 * half a cycle later. Check the 'incomplete_write_byte' fault injector
193 * for details. Note that we must honour tsu:sto, 4us, but lets use 5us
194 * here for simplicity.
196 bri->set_scl(adap, scl);
197 ndelay(RECOVERY_NDELAY);
199 bri->set_sda(adap, scl);
200 ndelay(RECOVERY_NDELAY / 2);
203 * By this time SCL is high, as we need to give 9 falling-rising edges
205 while (i++ < RECOVERY_CLK_CNT * 2) {
207 /* SCL shouldn't be low here */
208 if (!bri->get_scl(adap)) {
210 "SCL is stuck low, exit recovery\n");
217 bri->set_scl(adap, scl);
218 /* Creating STOP again, see above */
220 /* Honour minimum tsu:sto */
221 ndelay(RECOVERY_NDELAY);
223 /* Honour minimum tf and thd:dat */
224 ndelay(RECOVERY_NDELAY / 2);
227 bri->set_sda(adap, scl);
228 ndelay(RECOVERY_NDELAY / 2);
231 ret = i2c_generic_bus_free(adap);
237 /* If we can't check bus status, assume recovery worked */
238 if (ret == -EOPNOTSUPP)
241 if (bri->unprepare_recovery)
242 bri->unprepare_recovery(adap);
244 pinctrl_select_state(bri->pinctrl, bri->pins_default);
248 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
250 int i2c_recover_bus(struct i2c_adapter *adap)
252 if (!adap->bus_recovery_info)
255 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
256 return adap->bus_recovery_info->recover_bus(adap);
258 EXPORT_SYMBOL_GPL(i2c_recover_bus);
260 static void i2c_gpio_init_pinctrl_recovery(struct i2c_adapter *adap)
262 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
263 struct device *dev = &adap->dev;
264 struct pinctrl *p = bri->pinctrl;
267 * we can't change states without pinctrl, so remove the states if
271 bri->pins_default = NULL;
272 bri->pins_gpio = NULL;
276 if (!bri->pins_default) {
277 bri->pins_default = pinctrl_lookup_state(p,
278 PINCTRL_STATE_DEFAULT);
279 if (IS_ERR(bri->pins_default)) {
280 dev_dbg(dev, PINCTRL_STATE_DEFAULT " state not found for GPIO recovery\n");
281 bri->pins_default = NULL;
284 if (!bri->pins_gpio) {
285 bri->pins_gpio = pinctrl_lookup_state(p, "gpio");
286 if (IS_ERR(bri->pins_gpio))
287 bri->pins_gpio = pinctrl_lookup_state(p, "recovery");
289 if (IS_ERR(bri->pins_gpio)) {
290 dev_dbg(dev, "no gpio or recovery state found for GPIO recovery\n");
291 bri->pins_gpio = NULL;
295 /* for pinctrl state changes, we need all the information */
296 if (bri->pins_default && bri->pins_gpio) {
297 dev_info(dev, "using pinctrl states for GPIO recovery");
300 bri->pins_default = NULL;
301 bri->pins_gpio = NULL;
305 static int i2c_gpio_init_generic_recovery(struct i2c_adapter *adap)
307 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
308 struct device *dev = &adap->dev;
309 struct gpio_desc *gpiod;
313 * don't touch the recovery information if the driver is not using
314 * generic SCL recovery
316 if (bri->recover_bus && bri->recover_bus != i2c_generic_scl_recovery)
320 * pins might be taken as GPIO, so we should inform pinctrl about
321 * this and move the state to GPIO
324 pinctrl_select_state(bri->pinctrl, bri->pins_gpio);
327 * if there is incomplete or no recovery information, see if generic
328 * GPIO recovery is available
330 if (!bri->scl_gpiod) {
331 gpiod = devm_gpiod_get(dev, "scl", GPIOD_OUT_HIGH_OPEN_DRAIN);
332 if (PTR_ERR(gpiod) == -EPROBE_DEFER) {
334 goto cleanup_pinctrl_state;
336 if (!IS_ERR(gpiod)) {
337 bri->scl_gpiod = gpiod;
338 bri->recover_bus = i2c_generic_scl_recovery;
339 dev_info(dev, "using generic GPIOs for recovery\n");
343 /* SDA GPIOD line is optional, so we care about DEFER only */
344 if (!bri->sda_gpiod) {
346 * We have SCL. Pull SCL low and wait a bit so that SDA glitches
349 gpiod_direction_output(bri->scl_gpiod, 0);
351 gpiod = devm_gpiod_get(dev, "sda", GPIOD_IN);
353 /* Wait a bit in case of a SDA glitch, and then release SCL. */
355 gpiod_direction_output(bri->scl_gpiod, 1);
357 if (PTR_ERR(gpiod) == -EPROBE_DEFER) {
359 goto cleanup_pinctrl_state;
362 bri->sda_gpiod = gpiod;
365 cleanup_pinctrl_state:
366 /* change the state of the pins back to their default state */
368 pinctrl_select_state(bri->pinctrl, bri->pins_default);
373 static int i2c_gpio_init_recovery(struct i2c_adapter *adap)
375 i2c_gpio_init_pinctrl_recovery(adap);
376 return i2c_gpio_init_generic_recovery(adap);
379 static int i2c_init_recovery(struct i2c_adapter *adap)
381 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
382 char *err_str, *err_level = KERN_ERR;
387 if (i2c_gpio_init_recovery(adap) == -EPROBE_DEFER)
388 return -EPROBE_DEFER;
390 if (!bri->recover_bus) {
391 err_str = "no suitable method provided";
392 err_level = KERN_DEBUG;
396 if (bri->scl_gpiod && bri->recover_bus == i2c_generic_scl_recovery) {
397 bri->get_scl = get_scl_gpio_value;
398 bri->set_scl = set_scl_gpio_value;
399 if (bri->sda_gpiod) {
400 bri->get_sda = get_sda_gpio_value;
401 /* FIXME: add proper flag instead of '0' once available */
402 if (gpiod_get_direction(bri->sda_gpiod) == 0)
403 bri->set_sda = set_sda_gpio_value;
405 } else if (bri->recover_bus == i2c_generic_scl_recovery) {
406 /* Generic SCL recovery */
407 if (!bri->set_scl || !bri->get_scl) {
408 err_str = "no {get|set}_scl() found";
411 if (!bri->set_sda && !bri->get_sda) {
412 err_str = "either get_sda() or set_sda() needed";
419 dev_printk(err_level, &adap->dev, "Not using recovery: %s\n", err_str);
420 adap->bus_recovery_info = NULL;
425 static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
427 struct i2c_adapter *adap = client->adapter;
430 if (!adap->host_notify_domain)
433 if (client->flags & I2C_CLIENT_TEN)
436 irq = irq_create_mapping(adap->host_notify_domain, client->addr);
438 return irq > 0 ? irq : -ENXIO;
441 static int i2c_device_probe(struct device *dev)
443 struct i2c_client *client = i2c_verify_client(dev);
444 struct i2c_driver *driver;
450 client->irq = client->init_irq;
455 if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
456 dev_dbg(dev, "Using Host Notify IRQ\n");
457 /* Keep adapter active when Host Notify is required */
458 pm_runtime_get_sync(&client->adapter->dev);
459 irq = i2c_smbus_host_notify_to_irq(client);
460 } else if (dev->of_node) {
461 irq = of_irq_get_byname(dev->of_node, "irq");
462 if (irq == -EINVAL || irq == -ENODATA)
463 irq = of_irq_get(dev->of_node, 0);
464 } else if (ACPI_COMPANION(dev)) {
465 irq = i2c_acpi_get_irq(client);
467 if (irq == -EPROBE_DEFER) {
469 goto put_sync_adapter;
478 driver = to_i2c_driver(dev->driver);
481 * An I2C ID table is not mandatory, if and only if, a suitable OF
482 * or ACPI ID table is supplied for the probing device.
484 if (!driver->id_table &&
485 !acpi_driver_match_device(dev, dev->driver) &&
486 !i2c_of_match_device(dev->driver->of_match_table, client)) {
488 goto put_sync_adapter;
491 if (client->flags & I2C_CLIENT_WAKE) {
494 wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
495 if (wakeirq == -EPROBE_DEFER) {
497 goto put_sync_adapter;
500 device_init_wakeup(&client->dev, true);
502 if (wakeirq > 0 && wakeirq != client->irq)
503 status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
504 else if (client->irq > 0)
505 status = dev_pm_set_wake_irq(dev, client->irq);
510 dev_warn(&client->dev, "failed to set up wakeup irq\n");
513 dev_dbg(dev, "probe\n");
515 status = of_clk_set_defaults(dev->of_node, false);
517 goto err_clear_wakeup_irq;
519 status = dev_pm_domain_attach(&client->dev, true);
521 goto err_clear_wakeup_irq;
524 * When there are no more users of probe(),
525 * rename probe_new to probe.
527 if (driver->probe_new)
528 status = driver->probe_new(client);
529 else if (driver->probe)
530 status = driver->probe(client,
531 i2c_match_id(driver->id_table, client));
536 goto err_detach_pm_domain;
540 err_detach_pm_domain:
541 dev_pm_domain_detach(&client->dev, true);
542 err_clear_wakeup_irq:
543 dev_pm_clear_wake_irq(&client->dev);
544 device_init_wakeup(&client->dev, false);
546 if (client->flags & I2C_CLIENT_HOST_NOTIFY)
547 pm_runtime_put_sync(&client->adapter->dev);
552 static int i2c_device_remove(struct device *dev)
554 struct i2c_client *client = i2c_verify_client(dev);
555 struct i2c_driver *driver;
558 if (!client || !dev->driver)
561 driver = to_i2c_driver(dev->driver);
562 if (driver->remove) {
563 dev_dbg(dev, "remove\n");
564 status = driver->remove(client);
567 dev_pm_domain_detach(&client->dev, true);
569 dev_pm_clear_wake_irq(&client->dev);
570 device_init_wakeup(&client->dev, false);
573 if (client->flags & I2C_CLIENT_HOST_NOTIFY)
574 pm_runtime_put(&client->adapter->dev);
579 static void i2c_device_shutdown(struct device *dev)
581 struct i2c_client *client = i2c_verify_client(dev);
582 struct i2c_driver *driver;
584 if (!client || !dev->driver)
586 driver = to_i2c_driver(dev->driver);
587 if (driver->shutdown)
588 driver->shutdown(client);
589 else if (client->irq > 0)
590 disable_irq(client->irq);
593 static void i2c_client_dev_release(struct device *dev)
595 kfree(to_i2c_client(dev));
599 name_show(struct device *dev, struct device_attribute *attr, char *buf)
601 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
602 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
604 static DEVICE_ATTR_RO(name);
607 modalias_show(struct device *dev, struct device_attribute *attr, char *buf)
609 struct i2c_client *client = to_i2c_client(dev);
612 len = of_device_modalias(dev, buf, PAGE_SIZE);
616 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
620 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
622 static DEVICE_ATTR_RO(modalias);
624 static struct attribute *i2c_dev_attrs[] = {
626 /* modalias helps coldplug: modprobe $(cat .../modalias) */
627 &dev_attr_modalias.attr,
630 ATTRIBUTE_GROUPS(i2c_dev);
632 struct bus_type i2c_bus_type = {
634 .match = i2c_device_match,
635 .probe = i2c_device_probe,
636 .remove = i2c_device_remove,
637 .shutdown = i2c_device_shutdown,
639 EXPORT_SYMBOL_GPL(i2c_bus_type);
641 struct device_type i2c_client_type = {
642 .groups = i2c_dev_groups,
643 .uevent = i2c_device_uevent,
644 .release = i2c_client_dev_release,
646 EXPORT_SYMBOL_GPL(i2c_client_type);
650 * i2c_verify_client - return parameter as i2c_client, or NULL
651 * @dev: device, probably from some driver model iterator
653 * When traversing the driver model tree, perhaps using driver model
654 * iterators like @device_for_each_child(), you can't assume very much
655 * about the nodes you find. Use this function to avoid oopses caused
656 * by wrongly treating some non-I2C device as an i2c_client.
658 struct i2c_client *i2c_verify_client(struct device *dev)
660 return (dev->type == &i2c_client_type)
664 EXPORT_SYMBOL(i2c_verify_client);
667 /* Return a unique address which takes the flags of the client into account */
668 static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
670 unsigned short addr = client->addr;
672 /* For some client flags, add an arbitrary offset to avoid collisions */
673 if (client->flags & I2C_CLIENT_TEN)
674 addr |= I2C_ADDR_OFFSET_TEN_BIT;
676 if (client->flags & I2C_CLIENT_SLAVE)
677 addr |= I2C_ADDR_OFFSET_SLAVE;
682 /* This is a permissive address validity check, I2C address map constraints
683 * are purposely not enforced, except for the general call address. */
684 static int i2c_check_addr_validity(unsigned int addr, unsigned short flags)
686 if (flags & I2C_CLIENT_TEN) {
687 /* 10-bit address, all values are valid */
691 /* 7-bit address, reject the general call address */
692 if (addr == 0x00 || addr > 0x7f)
698 /* And this is a strict address validity check, used when probing. If a
699 * device uses a reserved address, then it shouldn't be probed. 7-bit
700 * addressing is assumed, 10-bit address devices are rare and should be
701 * explicitly enumerated. */
702 int i2c_check_7bit_addr_validity_strict(unsigned short addr)
705 * Reserved addresses per I2C specification:
706 * 0x00 General call address / START byte
708 * 0x02 Reserved for different bus format
709 * 0x03 Reserved for future purposes
710 * 0x04-0x07 Hs-mode master code
711 * 0x78-0x7b 10-bit slave addressing
712 * 0x7c-0x7f Reserved for future purposes
714 if (addr < 0x08 || addr > 0x77)
719 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
721 struct i2c_client *client = i2c_verify_client(dev);
722 int addr = *(int *)addrp;
724 if (client && i2c_encode_flags_to_addr(client) == addr)
729 /* walk up mux tree */
730 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
732 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
735 result = device_for_each_child(&adapter->dev, &addr,
736 __i2c_check_addr_busy);
738 if (!result && parent)
739 result = i2c_check_mux_parents(parent, addr);
744 /* recurse down mux tree */
745 static int i2c_check_mux_children(struct device *dev, void *addrp)
749 if (dev->type == &i2c_adapter_type)
750 result = device_for_each_child(dev, addrp,
751 i2c_check_mux_children);
753 result = __i2c_check_addr_busy(dev, addrp);
758 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
760 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
764 result = i2c_check_mux_parents(parent, addr);
767 result = device_for_each_child(&adapter->dev, &addr,
768 i2c_check_mux_children);
774 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
775 * @adapter: Target I2C bus segment
776 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
777 * locks only this branch in the adapter tree
779 static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
782 rt_mutex_lock_nested(&adapter->bus_lock, i2c_adapter_depth(adapter));
786 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
787 * @adapter: Target I2C bus segment
788 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
789 * trylocks only this branch in the adapter tree
791 static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
794 return rt_mutex_trylock(&adapter->bus_lock);
798 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
799 * @adapter: Target I2C bus segment
800 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
801 * unlocks only this branch in the adapter tree
803 static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
806 rt_mutex_unlock(&adapter->bus_lock);
809 static void i2c_dev_set_name(struct i2c_adapter *adap,
810 struct i2c_client *client,
811 struct i2c_board_info const *info)
813 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
815 if (info && info->dev_name) {
816 dev_set_name(&client->dev, "i2c-%s", info->dev_name);
821 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
825 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
826 i2c_encode_flags_to_addr(client));
829 int i2c_dev_irq_from_resources(const struct resource *resources,
830 unsigned int num_resources)
832 struct irq_data *irqd;
835 for (i = 0; i < num_resources; i++) {
836 const struct resource *r = &resources[i];
838 if (resource_type(r) != IORESOURCE_IRQ)
841 if (r->flags & IORESOURCE_BITS) {
842 irqd = irq_get_irq_data(r->start);
846 irqd_set_trigger_type(irqd, r->flags & IORESOURCE_BITS);
856 * i2c_new_client_device - instantiate an i2c device
857 * @adap: the adapter managing the device
858 * @info: describes one I2C device; bus_num is ignored
861 * Create an i2c device. Binding is handled through driver model
862 * probe()/remove() methods. A driver may be bound to this device when we
863 * return from this function, or any later moment (e.g. maybe hotplugging will
864 * load the driver module). This call is not appropriate for use by mainboard
865 * initialization logic, which usually runs during an arch_initcall() long
866 * before any i2c_adapter could exist.
868 * This returns the new i2c client, which may be saved for later use with
869 * i2c_unregister_device(); or an ERR_PTR to describe the error.
872 i2c_new_client_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
874 struct i2c_client *client;
877 client = kzalloc(sizeof *client, GFP_KERNEL);
879 return ERR_PTR(-ENOMEM);
881 client->adapter = adap;
883 client->dev.platform_data = info->platform_data;
884 client->flags = info->flags;
885 client->addr = info->addr;
887 client->init_irq = info->irq;
888 if (!client->init_irq)
889 client->init_irq = i2c_dev_irq_from_resources(info->resources,
890 info->num_resources);
892 strlcpy(client->name, info->type, sizeof(client->name));
894 status = i2c_check_addr_validity(client->addr, client->flags);
896 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
897 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
901 /* Check for address business */
902 status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
906 client->dev.parent = &client->adapter->dev;
907 client->dev.bus = &i2c_bus_type;
908 client->dev.type = &i2c_client_type;
909 client->dev.of_node = of_node_get(info->of_node);
910 client->dev.fwnode = info->fwnode;
912 i2c_dev_set_name(adap, client, info);
914 if (info->properties) {
915 status = device_add_properties(&client->dev, info->properties);
918 "Failed to add properties to client %s: %d\n",
919 client->name, status);
920 goto out_err_put_of_node;
924 status = device_register(&client->dev);
928 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
929 client->name, dev_name(&client->dev));
934 if (info->properties)
935 device_remove_properties(&client->dev);
937 of_node_put(info->of_node);
940 "Failed to register i2c client %s at 0x%02x (%d)\n",
941 client->name, client->addr, status);
944 return ERR_PTR(status);
946 EXPORT_SYMBOL_GPL(i2c_new_client_device);
949 * i2c_unregister_device - reverse effect of i2c_new_*_device()
950 * @client: value returned from i2c_new_*_device()
953 void i2c_unregister_device(struct i2c_client *client)
955 if (IS_ERR_OR_NULL(client))
958 if (client->dev.of_node) {
959 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
960 of_node_put(client->dev.of_node);
963 if (ACPI_COMPANION(&client->dev))
964 acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
965 device_unregister(&client->dev);
967 EXPORT_SYMBOL_GPL(i2c_unregister_device);
970 static const struct i2c_device_id dummy_id[] = {
975 static int dummy_probe(struct i2c_client *client,
976 const struct i2c_device_id *id)
981 static int dummy_remove(struct i2c_client *client)
986 static struct i2c_driver dummy_driver = {
987 .driver.name = "dummy",
988 .probe = dummy_probe,
989 .remove = dummy_remove,
990 .id_table = dummy_id,
994 * i2c_new_dummy_device - return a new i2c device bound to a dummy driver
995 * @adapter: the adapter managing the device
996 * @address: seven bit address to be used
999 * This returns an I2C client bound to the "dummy" driver, intended for use
1000 * with devices that consume multiple addresses. Examples of such chips
1001 * include various EEPROMS (like 24c04 and 24c08 models).
1003 * These dummy devices have two main uses. First, most I2C and SMBus calls
1004 * except i2c_transfer() need a client handle; the dummy will be that handle.
1005 * And second, this prevents the specified address from being bound to a
1008 * This returns the new i2c client, which should be saved for later use with
1009 * i2c_unregister_device(); or an ERR_PTR to describe the error.
1011 struct i2c_client *i2c_new_dummy_device(struct i2c_adapter *adapter, u16 address)
1013 struct i2c_board_info info = {
1014 I2C_BOARD_INFO("dummy", address),
1017 return i2c_new_client_device(adapter, &info);
1019 EXPORT_SYMBOL_GPL(i2c_new_dummy_device);
1021 struct i2c_dummy_devres {
1022 struct i2c_client *client;
1025 static void devm_i2c_release_dummy(struct device *dev, void *res)
1027 struct i2c_dummy_devres *this = res;
1029 i2c_unregister_device(this->client);
1033 * devm_i2c_new_dummy_device - return a new i2c device bound to a dummy driver
1034 * @dev: device the managed resource is bound to
1035 * @adapter: the adapter managing the device
1036 * @address: seven bit address to be used
1037 * Context: can sleep
1039 * This is the device-managed version of @i2c_new_dummy_device. It returns the
1040 * new i2c client or an ERR_PTR in case of an error.
1042 struct i2c_client *devm_i2c_new_dummy_device(struct device *dev,
1043 struct i2c_adapter *adapter,
1046 struct i2c_dummy_devres *dr;
1047 struct i2c_client *client;
1049 dr = devres_alloc(devm_i2c_release_dummy, sizeof(*dr), GFP_KERNEL);
1051 return ERR_PTR(-ENOMEM);
1053 client = i2c_new_dummy_device(adapter, address);
1054 if (IS_ERR(client)) {
1057 dr->client = client;
1058 devres_add(dev, dr);
1063 EXPORT_SYMBOL_GPL(devm_i2c_new_dummy_device);
1066 * i2c_new_ancillary_device - Helper to get the instantiated secondary address
1067 * and create the associated device
1068 * @client: Handle to the primary client
1069 * @name: Handle to specify which secondary address to get
1070 * @default_addr: Used as a fallback if no secondary address was specified
1071 * Context: can sleep
1073 * I2C clients can be composed of multiple I2C slaves bound together in a single
1074 * component. The I2C client driver then binds to the master I2C slave and needs
1075 * to create I2C dummy clients to communicate with all the other slaves.
1077 * This function creates and returns an I2C dummy client whose I2C address is
1078 * retrieved from the platform firmware based on the given slave name. If no
1079 * address is specified by the firmware default_addr is used.
1081 * On DT-based platforms the address is retrieved from the "reg" property entry
1082 * cell whose "reg-names" value matches the slave name.
1084 * This returns the new i2c client, which should be saved for later use with
1085 * i2c_unregister_device(); or an ERR_PTR to describe the error.
1087 struct i2c_client *i2c_new_ancillary_device(struct i2c_client *client,
1091 struct device_node *np = client->dev.of_node;
1092 u32 addr = default_addr;
1096 i = of_property_match_string(np, "reg-names", name);
1098 of_property_read_u32_index(np, "reg", i, &addr);
1101 dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1102 return i2c_new_dummy_device(client->adapter, addr);
1104 EXPORT_SYMBOL_GPL(i2c_new_ancillary_device);
1106 /* ------------------------------------------------------------------------- */
1108 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1110 static void i2c_adapter_dev_release(struct device *dev)
1112 struct i2c_adapter *adap = to_i2c_adapter(dev);
1113 complete(&adap->dev_released);
1116 unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1118 unsigned int depth = 0;
1120 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1123 WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
1124 "adapter depth exceeds lockdep subclass limit\n");
1128 EXPORT_SYMBOL_GPL(i2c_adapter_depth);
1131 * Let users instantiate I2C devices through sysfs. This can be used when
1132 * platform initialization code doesn't contain the proper data for
1133 * whatever reason. Also useful for drivers that do device detection and
1134 * detection fails, either because the device uses an unexpected address,
1135 * or this is a compatible device with different ID register values.
1137 * Parameter checking may look overzealous, but we really don't want
1138 * the user to provide incorrect parameters.
1141 new_device_store(struct device *dev, struct device_attribute *attr,
1142 const char *buf, size_t count)
1144 struct i2c_adapter *adap = to_i2c_adapter(dev);
1145 struct i2c_board_info info;
1146 struct i2c_client *client;
1150 memset(&info, 0, sizeof(struct i2c_board_info));
1152 blank = strchr(buf, ' ');
1154 dev_err(dev, "%s: Missing parameters\n", "new_device");
1157 if (blank - buf > I2C_NAME_SIZE - 1) {
1158 dev_err(dev, "%s: Invalid device name\n", "new_device");
1161 memcpy(info.type, buf, blank - buf);
1163 /* Parse remaining parameters, reject extra parameters */
1164 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1166 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1169 if (res > 1 && end != '\n') {
1170 dev_err(dev, "%s: Extra parameters\n", "new_device");
1174 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1175 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1176 info.flags |= I2C_CLIENT_TEN;
1179 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1180 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1181 info.flags |= I2C_CLIENT_SLAVE;
1184 client = i2c_new_client_device(adap, &info);
1186 return PTR_ERR(client);
1188 /* Keep track of the added device */
1189 mutex_lock(&adap->userspace_clients_lock);
1190 list_add_tail(&client->detected, &adap->userspace_clients);
1191 mutex_unlock(&adap->userspace_clients_lock);
1192 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1193 info.type, info.addr);
1197 static DEVICE_ATTR_WO(new_device);
1200 * And of course let the users delete the devices they instantiated, if
1201 * they got it wrong. This interface can only be used to delete devices
1202 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1203 * don't delete devices to which some kernel code still has references.
1205 * Parameter checking may look overzealous, but we really don't want
1206 * the user to delete the wrong device.
1209 delete_device_store(struct device *dev, struct device_attribute *attr,
1210 const char *buf, size_t count)
1212 struct i2c_adapter *adap = to_i2c_adapter(dev);
1213 struct i2c_client *client, *next;
1214 unsigned short addr;
1218 /* Parse parameters, reject extra parameters */
1219 res = sscanf(buf, "%hi%c", &addr, &end);
1221 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1224 if (res > 1 && end != '\n') {
1225 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1229 /* Make sure the device was added through sysfs */
1231 mutex_lock_nested(&adap->userspace_clients_lock,
1232 i2c_adapter_depth(adap));
1233 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1235 if (i2c_encode_flags_to_addr(client) == addr) {
1236 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1237 "delete_device", client->name, client->addr);
1239 list_del(&client->detected);
1240 i2c_unregister_device(client);
1245 mutex_unlock(&adap->userspace_clients_lock);
1248 dev_err(dev, "%s: Can't find device in list\n",
1252 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1253 delete_device_store);
1255 static struct attribute *i2c_adapter_attrs[] = {
1256 &dev_attr_name.attr,
1257 &dev_attr_new_device.attr,
1258 &dev_attr_delete_device.attr,
1261 ATTRIBUTE_GROUPS(i2c_adapter);
1263 struct device_type i2c_adapter_type = {
1264 .groups = i2c_adapter_groups,
1265 .release = i2c_adapter_dev_release,
1267 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1270 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1271 * @dev: device, probably from some driver model iterator
1273 * When traversing the driver model tree, perhaps using driver model
1274 * iterators like @device_for_each_child(), you can't assume very much
1275 * about the nodes you find. Use this function to avoid oopses caused
1276 * by wrongly treating some non-I2C device as an i2c_adapter.
1278 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1280 return (dev->type == &i2c_adapter_type)
1281 ? to_i2c_adapter(dev)
1284 EXPORT_SYMBOL(i2c_verify_adapter);
1286 #ifdef CONFIG_I2C_COMPAT
1287 static struct class_compat *i2c_adapter_compat_class;
1290 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1292 struct i2c_devinfo *devinfo;
1294 down_read(&__i2c_board_lock);
1295 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1296 if (devinfo->busnum == adapter->nr &&
1297 IS_ERR(i2c_new_client_device(adapter, &devinfo->board_info)))
1298 dev_err(&adapter->dev,
1299 "Can't create device at 0x%02x\n",
1300 devinfo->board_info.addr);
1302 up_read(&__i2c_board_lock);
1305 static int i2c_do_add_adapter(struct i2c_driver *driver,
1306 struct i2c_adapter *adap)
1308 /* Detect supported devices on that bus, and instantiate them */
1309 i2c_detect(adap, driver);
1314 static int __process_new_adapter(struct device_driver *d, void *data)
1316 return i2c_do_add_adapter(to_i2c_driver(d), data);
1319 static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1320 .lock_bus = i2c_adapter_lock_bus,
1321 .trylock_bus = i2c_adapter_trylock_bus,
1322 .unlock_bus = i2c_adapter_unlock_bus,
1325 static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
1327 struct irq_domain *domain = adap->host_notify_domain;
1328 irq_hw_number_t hwirq;
1333 for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
1334 irq_dispose_mapping(irq_find_mapping(domain, hwirq));
1336 irq_domain_remove(domain);
1337 adap->host_notify_domain = NULL;
1340 static int i2c_host_notify_irq_map(struct irq_domain *h,
1342 irq_hw_number_t hw_irq_num)
1344 irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
1349 static const struct irq_domain_ops i2c_host_notify_irq_ops = {
1350 .map = i2c_host_notify_irq_map,
1353 static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
1355 struct irq_domain *domain;
1357 if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
1360 domain = irq_domain_create_linear(adap->dev.parent->fwnode,
1361 I2C_ADDR_7BITS_COUNT,
1362 &i2c_host_notify_irq_ops, adap);
1366 adap->host_notify_domain = domain;
1372 * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
1374 * @adap: the adapter
1375 * @addr: the I2C address of the notifying device
1376 * Context: can't sleep
1378 * Helper function to be called from an I2C bus driver's interrupt
1379 * handler. It will schedule the Host Notify IRQ.
1381 int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
1388 irq = irq_find_mapping(adap->host_notify_domain, addr);
1392 generic_handle_irq(irq);
1396 EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
1398 static int i2c_register_adapter(struct i2c_adapter *adap)
1402 /* Can't register until after driver model init */
1403 if (WARN_ON(!is_registered)) {
1409 if (WARN(!adap->name[0], "i2c adapter has no name"))
1413 pr_err("adapter '%s': no algo supplied!\n", adap->name);
1417 if (!adap->lock_ops)
1418 adap->lock_ops = &i2c_adapter_lock_ops;
1420 adap->locked_flags = 0;
1421 rt_mutex_init(&adap->bus_lock);
1422 rt_mutex_init(&adap->mux_lock);
1423 mutex_init(&adap->userspace_clients_lock);
1424 INIT_LIST_HEAD(&adap->userspace_clients);
1426 /* Set default timeout to 1 second if not already set */
1427 if (adap->timeout == 0)
1430 /* register soft irqs for Host Notify */
1431 res = i2c_setup_host_notify_irq_domain(adap);
1433 pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
1438 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1439 adap->dev.bus = &i2c_bus_type;
1440 adap->dev.type = &i2c_adapter_type;
1441 res = device_register(&adap->dev);
1443 pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
1447 res = of_i2c_setup_smbus_alert(adap);
1451 pm_runtime_no_callbacks(&adap->dev);
1452 pm_suspend_ignore_children(&adap->dev, true);
1453 pm_runtime_enable(&adap->dev);
1455 res = i2c_init_recovery(adap);
1456 if (res == -EPROBE_DEFER)
1459 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1461 #ifdef CONFIG_I2C_COMPAT
1462 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1465 dev_warn(&adap->dev,
1466 "Failed to create compatibility class link\n");
1469 /* create pre-declared device nodes */
1470 of_i2c_register_devices(adap);
1471 i2c_acpi_install_space_handler(adap);
1472 i2c_acpi_register_devices(adap);
1474 if (adap->nr < __i2c_first_dynamic_bus_num)
1475 i2c_scan_static_board_info(adap);
1477 /* Notify drivers */
1478 mutex_lock(&core_lock);
1479 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1480 mutex_unlock(&core_lock);
1485 init_completion(&adap->dev_released);
1486 device_unregister(&adap->dev);
1487 wait_for_completion(&adap->dev_released);
1489 mutex_lock(&core_lock);
1490 idr_remove(&i2c_adapter_idr, adap->nr);
1491 mutex_unlock(&core_lock);
1496 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1497 * @adap: the adapter to register (with adap->nr initialized)
1498 * Context: can sleep
1500 * See i2c_add_numbered_adapter() for details.
1502 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1506 mutex_lock(&core_lock);
1507 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
1508 mutex_unlock(&core_lock);
1509 if (WARN(id < 0, "couldn't get idr"))
1510 return id == -ENOSPC ? -EBUSY : id;
1512 return i2c_register_adapter(adap);
1516 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1517 * @adapter: the adapter to add
1518 * Context: can sleep
1520 * This routine is used to declare an I2C adapter when its bus number
1521 * doesn't matter or when its bus number is specified by an dt alias.
1522 * Examples of bases when the bus number doesn't matter: I2C adapters
1523 * dynamically added by USB links or PCI plugin cards.
1525 * When this returns zero, a new bus number was allocated and stored
1526 * in adap->nr, and the specified adapter became available for clients.
1527 * Otherwise, a negative errno value is returned.
1529 int i2c_add_adapter(struct i2c_adapter *adapter)
1531 struct device *dev = &adapter->dev;
1535 id = of_alias_get_id(dev->of_node, "i2c");
1538 return __i2c_add_numbered_adapter(adapter);
1542 mutex_lock(&core_lock);
1543 id = idr_alloc(&i2c_adapter_idr, adapter,
1544 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1545 mutex_unlock(&core_lock);
1546 if (WARN(id < 0, "couldn't get idr"))
1551 return i2c_register_adapter(adapter);
1553 EXPORT_SYMBOL(i2c_add_adapter);
1556 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1557 * @adap: the adapter to register (with adap->nr initialized)
1558 * Context: can sleep
1560 * This routine is used to declare an I2C adapter when its bus number
1561 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1562 * or otherwise built in to the system's mainboard, and where i2c_board_info
1563 * is used to properly configure I2C devices.
1565 * If the requested bus number is set to -1, then this function will behave
1566 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1568 * If no devices have pre-been declared for this bus, then be sure to
1569 * register the adapter before any dynamically allocated ones. Otherwise
1570 * the required bus ID may not be available.
1572 * When this returns zero, the specified adapter became available for
1573 * clients using the bus number provided in adap->nr. Also, the table
1574 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1575 * and the appropriate driver model device nodes are created. Otherwise, a
1576 * negative errno value is returned.
1578 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1580 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1581 return i2c_add_adapter(adap);
1583 return __i2c_add_numbered_adapter(adap);
1585 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1587 static void i2c_do_del_adapter(struct i2c_driver *driver,
1588 struct i2c_adapter *adapter)
1590 struct i2c_client *client, *_n;
1592 /* Remove the devices we created ourselves as the result of hardware
1593 * probing (using a driver's detect method) */
1594 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1595 if (client->adapter == adapter) {
1596 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1597 client->name, client->addr);
1598 list_del(&client->detected);
1599 i2c_unregister_device(client);
1604 static int __unregister_client(struct device *dev, void *dummy)
1606 struct i2c_client *client = i2c_verify_client(dev);
1607 if (client && strcmp(client->name, "dummy"))
1608 i2c_unregister_device(client);
1612 static int __unregister_dummy(struct device *dev, void *dummy)
1614 struct i2c_client *client = i2c_verify_client(dev);
1615 i2c_unregister_device(client);
1619 static int __process_removed_adapter(struct device_driver *d, void *data)
1621 i2c_do_del_adapter(to_i2c_driver(d), data);
1626 * i2c_del_adapter - unregister I2C adapter
1627 * @adap: the adapter being unregistered
1628 * Context: can sleep
1630 * This unregisters an I2C adapter which was previously registered
1631 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1633 void i2c_del_adapter(struct i2c_adapter *adap)
1635 struct i2c_adapter *found;
1636 struct i2c_client *client, *next;
1638 /* First make sure that this adapter was ever added */
1639 mutex_lock(&core_lock);
1640 found = idr_find(&i2c_adapter_idr, adap->nr);
1641 mutex_unlock(&core_lock);
1642 if (found != adap) {
1643 pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
1647 i2c_acpi_remove_space_handler(adap);
1648 /* Tell drivers about this removal */
1649 mutex_lock(&core_lock);
1650 bus_for_each_drv(&i2c_bus_type, NULL, adap,
1651 __process_removed_adapter);
1652 mutex_unlock(&core_lock);
1654 /* Remove devices instantiated from sysfs */
1655 mutex_lock_nested(&adap->userspace_clients_lock,
1656 i2c_adapter_depth(adap));
1657 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1659 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1661 list_del(&client->detected);
1662 i2c_unregister_device(client);
1664 mutex_unlock(&adap->userspace_clients_lock);
1666 /* Detach any active clients. This can't fail, thus we do not
1667 * check the returned value. This is a two-pass process, because
1668 * we can't remove the dummy devices during the first pass: they
1669 * could have been instantiated by real devices wishing to clean
1670 * them up properly, so we give them a chance to do that first. */
1671 device_for_each_child(&adap->dev, NULL, __unregister_client);
1672 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1674 #ifdef CONFIG_I2C_COMPAT
1675 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1679 /* device name is gone after device_unregister */
1680 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1682 pm_runtime_disable(&adap->dev);
1684 i2c_host_notify_irq_teardown(adap);
1686 /* wait until all references to the device are gone
1688 * FIXME: This is old code and should ideally be replaced by an
1689 * alternative which results in decoupling the lifetime of the struct
1690 * device from the i2c_adapter, like spi or netdev do. Any solution
1691 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
1693 init_completion(&adap->dev_released);
1694 device_unregister(&adap->dev);
1695 wait_for_completion(&adap->dev_released);
1698 mutex_lock(&core_lock);
1699 idr_remove(&i2c_adapter_idr, adap->nr);
1700 mutex_unlock(&core_lock);
1702 /* Clear the device structure in case this adapter is ever going to be
1704 memset(&adap->dev, 0, sizeof(adap->dev));
1706 EXPORT_SYMBOL(i2c_del_adapter);
1708 static void i2c_parse_timing(struct device *dev, char *prop_name, u32 *cur_val_p,
1709 u32 def_val, bool use_def)
1713 ret = device_property_read_u32(dev, prop_name, cur_val_p);
1715 *cur_val_p = def_val;
1717 dev_dbg(dev, "%s: %u\n", prop_name, *cur_val_p);
1721 * i2c_parse_fw_timings - get I2C related timing parameters from firmware
1722 * @dev: The device to scan for I2C timing properties
1723 * @t: the i2c_timings struct to be filled with values
1724 * @use_defaults: bool to use sane defaults derived from the I2C specification
1725 * when properties are not found, otherwise don't update
1727 * Scan the device for the generic I2C properties describing timing parameters
1728 * for the signal and fill the given struct with the results. If a property was
1729 * not found and use_defaults was true, then maximum timings are assumed which
1730 * are derived from the I2C specification. If use_defaults is not used, the
1731 * results will be as before, so drivers can apply their own defaults before
1732 * calling this helper. The latter is mainly intended for avoiding regressions
1733 * of existing drivers which want to switch to this function. New drivers
1734 * almost always should use the defaults.
1736 void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
1738 bool u = use_defaults;
1741 i2c_parse_timing(dev, "clock-frequency", &t->bus_freq_hz,
1742 I2C_MAX_STANDARD_MODE_FREQ, u);
1744 d = t->bus_freq_hz <= I2C_MAX_STANDARD_MODE_FREQ ? 1000 :
1745 t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ ? 300 : 120;
1746 i2c_parse_timing(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns, d, u);
1748 d = t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ ? 300 : 120;
1749 i2c_parse_timing(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns, d, u);
1751 i2c_parse_timing(dev, "i2c-scl-internal-delay-ns",
1752 &t->scl_int_delay_ns, 0, u);
1753 i2c_parse_timing(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns,
1755 i2c_parse_timing(dev, "i2c-sda-hold-time-ns", &t->sda_hold_ns, 0, u);
1756 i2c_parse_timing(dev, "i2c-digital-filter-width-ns",
1757 &t->digital_filter_width_ns, 0, u);
1758 i2c_parse_timing(dev, "i2c-analog-filter-cutoff-frequency",
1759 &t->analog_filter_cutoff_freq_hz, 0, u);
1761 EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
1763 /* ------------------------------------------------------------------------- */
1765 int i2c_for_each_dev(void *data, int (*fn)(struct device *dev, void *data))
1769 mutex_lock(&core_lock);
1770 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1771 mutex_unlock(&core_lock);
1775 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1777 static int __process_new_driver(struct device *dev, void *data)
1779 if (dev->type != &i2c_adapter_type)
1781 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1785 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1786 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1789 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1793 /* Can't register until after driver model init */
1794 if (WARN_ON(!is_registered))
1797 /* add the driver to the list of i2c drivers in the driver core */
1798 driver->driver.owner = owner;
1799 driver->driver.bus = &i2c_bus_type;
1800 INIT_LIST_HEAD(&driver->clients);
1802 /* When registration returns, the driver core
1803 * will have called probe() for all matching-but-unbound devices.
1805 res = driver_register(&driver->driver);
1809 pr_debug("driver [%s] registered\n", driver->driver.name);
1811 /* Walk the adapters that are already present */
1812 i2c_for_each_dev(driver, __process_new_driver);
1816 EXPORT_SYMBOL(i2c_register_driver);
1818 static int __process_removed_driver(struct device *dev, void *data)
1820 if (dev->type == &i2c_adapter_type)
1821 i2c_do_del_adapter(data, to_i2c_adapter(dev));
1826 * i2c_del_driver - unregister I2C driver
1827 * @driver: the driver being unregistered
1828 * Context: can sleep
1830 void i2c_del_driver(struct i2c_driver *driver)
1832 i2c_for_each_dev(driver, __process_removed_driver);
1834 driver_unregister(&driver->driver);
1835 pr_debug("driver [%s] unregistered\n", driver->driver.name);
1837 EXPORT_SYMBOL(i2c_del_driver);
1839 /* ------------------------------------------------------------------------- */
1841 struct i2c_cmd_arg {
1846 static int i2c_cmd(struct device *dev, void *_arg)
1848 struct i2c_client *client = i2c_verify_client(dev);
1849 struct i2c_cmd_arg *arg = _arg;
1850 struct i2c_driver *driver;
1852 if (!client || !client->dev.driver)
1855 driver = to_i2c_driver(client->dev.driver);
1856 if (driver->command)
1857 driver->command(client, arg->cmd, arg->arg);
1861 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1863 struct i2c_cmd_arg cmd_arg;
1867 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1869 EXPORT_SYMBOL(i2c_clients_command);
1871 static int __init i2c_init(void)
1875 retval = of_alias_get_highest_id("i2c");
1877 down_write(&__i2c_board_lock);
1878 if (retval >= __i2c_first_dynamic_bus_num)
1879 __i2c_first_dynamic_bus_num = retval + 1;
1880 up_write(&__i2c_board_lock);
1882 retval = bus_register(&i2c_bus_type);
1886 is_registered = true;
1888 #ifdef CONFIG_I2C_COMPAT
1889 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1890 if (!i2c_adapter_compat_class) {
1895 retval = i2c_add_driver(&dummy_driver);
1899 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1900 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
1901 if (IS_ENABLED(CONFIG_ACPI))
1902 WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
1907 #ifdef CONFIG_I2C_COMPAT
1908 class_compat_unregister(i2c_adapter_compat_class);
1911 is_registered = false;
1912 bus_unregister(&i2c_bus_type);
1916 static void __exit i2c_exit(void)
1918 if (IS_ENABLED(CONFIG_ACPI))
1919 WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
1920 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1921 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
1922 i2c_del_driver(&dummy_driver);
1923 #ifdef CONFIG_I2C_COMPAT
1924 class_compat_unregister(i2c_adapter_compat_class);
1926 bus_unregister(&i2c_bus_type);
1927 tracepoint_synchronize_unregister();
1930 /* We must initialize early, because some subsystems register i2c drivers
1931 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1933 postcore_initcall(i2c_init);
1934 module_exit(i2c_exit);
1936 /* ----------------------------------------------------
1937 * the functional interface to the i2c busses.
1938 * ----------------------------------------------------
1941 /* Check if val is exceeding the quirk IFF quirk is non 0 */
1942 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
1944 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
1946 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
1947 err_msg, msg->addr, msg->len,
1948 msg->flags & I2C_M_RD ? "read" : "write");
1952 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1954 const struct i2c_adapter_quirks *q = adap->quirks;
1955 int max_num = q->max_num_msgs, i;
1956 bool do_len_check = true;
1958 if (q->flags & I2C_AQ_COMB) {
1961 /* special checks for combined messages */
1963 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
1964 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
1966 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
1967 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
1969 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
1970 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
1972 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
1973 return i2c_quirk_error(adap, &msgs[0], "msg too long");
1975 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
1976 return i2c_quirk_error(adap, &msgs[1], "msg too long");
1978 do_len_check = false;
1982 if (i2c_quirk_exceeded(num, max_num))
1983 return i2c_quirk_error(adap, &msgs[0], "too many messages");
1985 for (i = 0; i < num; i++) {
1986 u16 len = msgs[i].len;
1988 if (msgs[i].flags & I2C_M_RD) {
1989 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
1990 return i2c_quirk_error(adap, &msgs[i], "msg too long");
1992 if (q->flags & I2C_AQ_NO_ZERO_LEN_READ && len == 0)
1993 return i2c_quirk_error(adap, &msgs[i], "no zero length");
1995 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
1996 return i2c_quirk_error(adap, &msgs[i], "msg too long");
1998 if (q->flags & I2C_AQ_NO_ZERO_LEN_WRITE && len == 0)
1999 return i2c_quirk_error(adap, &msgs[i], "no zero length");
2007 * __i2c_transfer - unlocked flavor of i2c_transfer
2008 * @adap: Handle to I2C bus
2009 * @msgs: One or more messages to execute before STOP is issued to
2010 * terminate the operation; each message begins with a START.
2011 * @num: Number of messages to be executed.
2013 * Returns negative errno, else the number of messages executed.
2015 * Adapter lock must be held when calling this function. No debug logging
2016 * takes place. adap->algo->master_xfer existence isn't checked.
2018 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2020 unsigned long orig_jiffies;
2023 if (WARN_ON(!msgs || num < 1))
2026 ret = __i2c_check_suspended(adap);
2030 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2034 * i2c_trace_msg_key gets enabled when tracepoint i2c_transfer gets
2035 * enabled. This is an efficient way of keeping the for-loop from
2036 * being executed when not needed.
2038 if (static_branch_unlikely(&i2c_trace_msg_key)) {
2040 for (i = 0; i < num; i++)
2041 if (msgs[i].flags & I2C_M_RD)
2042 trace_i2c_read(adap, &msgs[i], i);
2044 trace_i2c_write(adap, &msgs[i], i);
2047 /* Retry automatically on arbitration loss */
2048 orig_jiffies = jiffies;
2049 for (ret = 0, try = 0; try <= adap->retries; try++) {
2050 if (i2c_in_atomic_xfer_mode() && adap->algo->master_xfer_atomic)
2051 ret = adap->algo->master_xfer_atomic(adap, msgs, num);
2053 ret = adap->algo->master_xfer(adap, msgs, num);
2057 if (time_after(jiffies, orig_jiffies + adap->timeout))
2061 if (static_branch_unlikely(&i2c_trace_msg_key)) {
2063 for (i = 0; i < ret; i++)
2064 if (msgs[i].flags & I2C_M_RD)
2065 trace_i2c_reply(adap, &msgs[i], i);
2066 trace_i2c_result(adap, num, ret);
2071 EXPORT_SYMBOL(__i2c_transfer);
2074 * i2c_transfer - execute a single or combined I2C message
2075 * @adap: Handle to I2C bus
2076 * @msgs: One or more messages to execute before STOP is issued to
2077 * terminate the operation; each message begins with a START.
2078 * @num: Number of messages to be executed.
2080 * Returns negative errno, else the number of messages executed.
2082 * Note that there is no requirement that each message be sent to
2083 * the same slave address, although that is the most common model.
2085 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2089 if (!adap->algo->master_xfer) {
2090 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2094 /* REVISIT the fault reporting model here is weak:
2096 * - When we get an error after receiving N bytes from a slave,
2097 * there is no way to report "N".
2099 * - When we get a NAK after transmitting N bytes to a slave,
2100 * there is no way to report "N" ... or to let the master
2101 * continue executing the rest of this combined message, if
2102 * that's the appropriate response.
2104 * - When for example "num" is two and we successfully complete
2105 * the first message but get an error part way through the
2106 * second, it's unclear whether that should be reported as
2107 * one (discarding status on the second message) or errno
2108 * (discarding status on the first one).
2110 ret = __i2c_lock_bus_helper(adap);
2114 ret = __i2c_transfer(adap, msgs, num);
2115 i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
2119 EXPORT_SYMBOL(i2c_transfer);
2122 * i2c_transfer_buffer_flags - issue a single I2C message transferring data
2124 * @client: Handle to slave device
2125 * @buf: Where the data is stored
2126 * @count: How many bytes to transfer, must be less than 64k since msg.len is u16
2127 * @flags: The flags to be used for the message, e.g. I2C_M_RD for reads
2129 * Returns negative errno, or else the number of bytes transferred.
2131 int i2c_transfer_buffer_flags(const struct i2c_client *client, char *buf,
2132 int count, u16 flags)
2135 struct i2c_msg msg = {
2136 .addr = client->addr,
2137 .flags = flags | (client->flags & I2C_M_TEN),
2142 ret = i2c_transfer(client->adapter, &msg, 1);
2145 * If everything went ok (i.e. 1 msg transferred), return #bytes
2146 * transferred, else error code.
2148 return (ret == 1) ? count : ret;
2150 EXPORT_SYMBOL(i2c_transfer_buffer_flags);
2153 * i2c_get_device_id - get manufacturer, part id and die revision of a device
2154 * @client: The device to query
2155 * @id: The queried information
2157 * Returns negative errno on error, zero on success.
2159 int i2c_get_device_id(const struct i2c_client *client,
2160 struct i2c_device_identity *id)
2162 struct i2c_adapter *adap = client->adapter;
2163 union i2c_smbus_data raw_id;
2166 if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
2169 raw_id.block[0] = 3;
2170 ret = i2c_smbus_xfer(adap, I2C_ADDR_DEVICE_ID, 0,
2171 I2C_SMBUS_READ, client->addr << 1,
2172 I2C_SMBUS_I2C_BLOCK_DATA, &raw_id);
2176 id->manufacturer_id = (raw_id.block[1] << 4) | (raw_id.block[2] >> 4);
2177 id->part_id = ((raw_id.block[2] & 0xf) << 5) | (raw_id.block[3] >> 3);
2178 id->die_revision = raw_id.block[3] & 0x7;
2181 EXPORT_SYMBOL_GPL(i2c_get_device_id);
2183 /* ----------------------------------------------------
2184 * the i2c address scanning function
2185 * Will not work for 10-bit addresses!
2186 * ----------------------------------------------------
2190 * Legacy default probe function, mostly relevant for SMBus. The default
2191 * probe method is a quick write, but it is known to corrupt the 24RF08
2192 * EEPROMs due to a state machine bug, and could also irreversibly
2193 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2194 * we use a short byte read instead. Also, some bus drivers don't implement
2195 * quick write, so we fallback to a byte read in that case too.
2196 * On x86, there is another special case for FSC hardware monitoring chips,
2197 * which want regular byte reads (address 0x73.) Fortunately, these are the
2198 * only known chips using this I2C address on PC hardware.
2199 * Returns 1 if probe succeeded, 0 if not.
2201 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2204 union i2c_smbus_data dummy;
2207 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2208 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2209 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2210 I2C_SMBUS_BYTE_DATA, &dummy);
2213 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2214 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2215 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2216 I2C_SMBUS_QUICK, NULL);
2217 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2218 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2219 I2C_SMBUS_BYTE, &dummy);
2221 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2229 static int i2c_detect_address(struct i2c_client *temp_client,
2230 struct i2c_driver *driver)
2232 struct i2c_board_info info;
2233 struct i2c_adapter *adapter = temp_client->adapter;
2234 int addr = temp_client->addr;
2237 /* Make sure the address is valid */
2238 err = i2c_check_7bit_addr_validity_strict(addr);
2240 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2245 /* Skip if already in use (7 bit, no need to encode flags) */
2246 if (i2c_check_addr_busy(adapter, addr))
2249 /* Make sure there is something at this address */
2250 if (!i2c_default_probe(adapter, addr))
2253 /* Finally call the custom detection function */
2254 memset(&info, 0, sizeof(struct i2c_board_info));
2256 err = driver->detect(temp_client, &info);
2258 /* -ENODEV is returned if the detection fails. We catch it
2259 here as this isn't an error. */
2260 return err == -ENODEV ? 0 : err;
2263 /* Consistency check */
2264 if (info.type[0] == '\0') {
2265 dev_err(&adapter->dev,
2266 "%s detection function provided no name for 0x%x\n",
2267 driver->driver.name, addr);
2269 struct i2c_client *client;
2271 /* Detection succeeded, instantiate the device */
2272 if (adapter->class & I2C_CLASS_DEPRECATED)
2273 dev_warn(&adapter->dev,
2274 "This adapter will soon drop class based instantiation of devices. "
2275 "Please make sure client 0x%02x gets instantiated by other means. "
2276 "Check 'Documentation/i2c/instantiating-devices.rst' for details.\n",
2279 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2280 info.type, info.addr);
2281 client = i2c_new_client_device(adapter, &info);
2282 if (!IS_ERR(client))
2283 list_add_tail(&client->detected, &driver->clients);
2285 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2286 info.type, info.addr);
2291 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2293 const unsigned short *address_list;
2294 struct i2c_client *temp_client;
2297 address_list = driver->address_list;
2298 if (!driver->detect || !address_list)
2301 /* Warn that the adapter lost class based instantiation */
2302 if (adapter->class == I2C_CLASS_DEPRECATED) {
2303 dev_dbg(&adapter->dev,
2304 "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
2305 "If you need it, check 'Documentation/i2c/instantiating-devices.rst' for alternatives.\n",
2306 driver->driver.name);
2310 /* Stop here if the classes do not match */
2311 if (!(adapter->class & driver->class))
2314 /* Set up a temporary client to help detect callback */
2315 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2318 temp_client->adapter = adapter;
2320 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2321 dev_dbg(&adapter->dev,
2322 "found normal entry for adapter %d, addr 0x%02x\n",
2323 i2c_adapter_id(adapter), address_list[i]);
2324 temp_client->addr = address_list[i];
2325 err = i2c_detect_address(temp_client, driver);
2334 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2336 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2337 I2C_SMBUS_QUICK, NULL) >= 0;
2339 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2342 i2c_new_scanned_device(struct i2c_adapter *adap,
2343 struct i2c_board_info *info,
2344 unsigned short const *addr_list,
2345 int (*probe)(struct i2c_adapter *adap, unsigned short addr))
2350 probe = i2c_default_probe;
2352 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2353 /* Check address validity */
2354 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2355 dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
2360 /* Check address availability (7 bit, no need to encode flags) */
2361 if (i2c_check_addr_busy(adap, addr_list[i])) {
2363 "Address 0x%02x already in use, not probing\n",
2368 /* Test address responsiveness */
2369 if (probe(adap, addr_list[i]))
2373 if (addr_list[i] == I2C_CLIENT_END) {
2374 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2375 return ERR_PTR(-ENODEV);
2378 info->addr = addr_list[i];
2379 return i2c_new_client_device(adap, info);
2381 EXPORT_SYMBOL_GPL(i2c_new_scanned_device);
2383 struct i2c_adapter *i2c_get_adapter(int nr)
2385 struct i2c_adapter *adapter;
2387 mutex_lock(&core_lock);
2388 adapter = idr_find(&i2c_adapter_idr, nr);
2392 if (try_module_get(adapter->owner))
2393 get_device(&adapter->dev);
2398 mutex_unlock(&core_lock);
2401 EXPORT_SYMBOL(i2c_get_adapter);
2403 void i2c_put_adapter(struct i2c_adapter *adap)
2408 module_put(adap->owner);
2409 /* Should be last, otherwise we risk use-after-free with 'adap' */
2410 put_device(&adap->dev);
2412 EXPORT_SYMBOL(i2c_put_adapter);
2415 * i2c_get_dma_safe_msg_buf() - get a DMA safe buffer for the given i2c_msg
2416 * @msg: the message to be checked
2417 * @threshold: the minimum number of bytes for which using DMA makes sense.
2418 * Should at least be 1.
2420 * Return: NULL if a DMA safe buffer was not obtained. Use msg->buf with PIO.
2421 * Or a valid pointer to be used with DMA. After use, release it by
2422 * calling i2c_put_dma_safe_msg_buf().
2424 * This function must only be called from process context!
2426 u8 *i2c_get_dma_safe_msg_buf(struct i2c_msg *msg, unsigned int threshold)
2428 /* also skip 0-length msgs for bogus thresholds of 0 */
2430 pr_debug("DMA buffer for addr=0x%02x with length 0 is bogus\n",
2432 if (msg->len < threshold || msg->len == 0)
2435 if (msg->flags & I2C_M_DMA_SAFE)
2438 pr_debug("using bounce buffer for addr=0x%02x, len=%d\n",
2439 msg->addr, msg->len);
2441 if (msg->flags & I2C_M_RD)
2442 return kzalloc(msg->len, GFP_KERNEL);
2444 return kmemdup(msg->buf, msg->len, GFP_KERNEL);
2446 EXPORT_SYMBOL_GPL(i2c_get_dma_safe_msg_buf);
2449 * i2c_put_dma_safe_msg_buf - release DMA safe buffer and sync with i2c_msg
2450 * @buf: the buffer obtained from i2c_get_dma_safe_msg_buf(). May be NULL.
2451 * @msg: the message which the buffer corresponds to
2452 * @xferred: bool saying if the message was transferred
2454 void i2c_put_dma_safe_msg_buf(u8 *buf, struct i2c_msg *msg, bool xferred)
2456 if (!buf || buf == msg->buf)
2459 if (xferred && msg->flags & I2C_M_RD)
2460 memcpy(msg->buf, buf, msg->len);
2464 EXPORT_SYMBOL_GPL(i2c_put_dma_safe_msg_buf);
2466 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2467 MODULE_DESCRIPTION("I2C-Bus main module");
2468 MODULE_LICENSE("GPL");