4 * Copyright (C) 1995-99 Simon G. Vogl
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by the Free
13 * Software Foundation; either version 2 of the License, or (at your option)
16 * This program is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
21 #define pr_fmt(fmt) "i2c-core: " fmt
23 #include <dt-bindings/i2c/i2c.h>
24 #include <linux/acpi.h>
25 #include <linux/clk/clk-conf.h>
26 #include <linux/completion.h>
27 #include <linux/delay.h>
28 #include <linux/err.h>
29 #include <linux/errno.h>
30 #include <linux/gpio.h>
31 #include <linux/i2c.h>
32 #include <linux/idr.h>
33 #include <linux/init.h>
34 #include <linux/irqflags.h>
35 #include <linux/jump_label.h>
36 #include <linux/kernel.h>
37 #include <linux/module.h>
38 #include <linux/mutex.h>
39 #include <linux/of_device.h>
41 #include <linux/of_irq.h>
42 #include <linux/pm_domain.h>
43 #include <linux/pm_runtime.h>
44 #include <linux/pm_wakeirq.h>
45 #include <linux/property.h>
46 #include <linux/rwsem.h>
47 #include <linux/slab.h>
51 #define CREATE_TRACE_POINTS
52 #include <trace/events/i2c.h>
54 #define I2C_ADDR_OFFSET_TEN_BIT 0xa000
55 #define I2C_ADDR_OFFSET_SLAVE 0x1000
57 #define I2C_ADDR_7BITS_MAX 0x77
58 #define I2C_ADDR_7BITS_COUNT (I2C_ADDR_7BITS_MAX + 1)
61 * core_lock protects i2c_adapter_idr, and guarantees that device detection,
62 * deletion of detected devices, and attach_adapter calls are serialized
64 static DEFINE_MUTEX(core_lock);
65 static DEFINE_IDR(i2c_adapter_idr);
67 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
69 static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
70 static bool is_registered;
72 int i2c_transfer_trace_reg(void)
74 static_key_slow_inc(&i2c_trace_msg);
78 void i2c_transfer_trace_unreg(void)
80 static_key_slow_dec(&i2c_trace_msg);
83 const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
84 const struct i2c_client *client)
90 if (strcmp(client->name, id->name) == 0)
96 EXPORT_SYMBOL_GPL(i2c_match_id);
98 static int i2c_device_match(struct device *dev, struct device_driver *drv)
100 struct i2c_client *client = i2c_verify_client(dev);
101 struct i2c_driver *driver;
104 /* Attempt an OF style match */
105 if (i2c_of_match_device(drv->of_match_table, client))
108 /* Then ACPI style match */
109 if (acpi_driver_match_device(dev, drv))
112 driver = to_i2c_driver(drv);
114 /* Finally an I2C match */
115 if (i2c_match_id(driver->id_table, client))
121 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
123 struct i2c_client *client = to_i2c_client(dev);
126 rc = acpi_device_uevent_modalias(dev, env);
130 return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
133 /* i2c bus recovery routines */
134 static int get_scl_gpio_value(struct i2c_adapter *adap)
136 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
139 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
141 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
144 static int get_sda_gpio_value(struct i2c_adapter *adap)
146 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
149 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
151 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
152 struct device *dev = &adap->dev;
155 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
156 GPIOF_OUT_INIT_HIGH, "i2c-scl");
158 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
163 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
164 /* work without SDA polling */
165 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
174 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
176 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
179 gpio_free(bri->sda_gpio);
181 gpio_free(bri->scl_gpio);
185 * We are generating clock pulses. ndelay() determines durating of clk pulses.
186 * We will generate clock with rate 100 KHz and so duration of both clock levels
187 * is: delay in ns = (10^6 / 100) / 2
189 #define RECOVERY_NDELAY 5000
190 #define RECOVERY_CLK_CNT 9
192 static int i2c_generic_recovery(struct i2c_adapter *adap)
194 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
195 int i = 0, val = 1, ret = 0;
197 if (bri->prepare_recovery)
198 bri->prepare_recovery(adap);
200 bri->set_scl(adap, val);
201 ndelay(RECOVERY_NDELAY);
204 * By this time SCL is high, as we need to give 9 falling-rising edges
206 while (i++ < RECOVERY_CLK_CNT * 2) {
208 /* Break if SDA is high */
209 if (bri->get_sda && bri->get_sda(adap))
211 /* SCL shouldn't be low here */
212 if (!bri->get_scl(adap)) {
214 "SCL is stuck low, exit recovery\n");
221 bri->set_scl(adap, val);
222 ndelay(RECOVERY_NDELAY);
225 if (bri->unprepare_recovery)
226 bri->unprepare_recovery(adap);
231 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
233 return i2c_generic_recovery(adap);
235 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
237 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
241 ret = i2c_get_gpios_for_recovery(adap);
245 ret = i2c_generic_recovery(adap);
246 i2c_put_gpios_for_recovery(adap);
250 EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
252 int i2c_recover_bus(struct i2c_adapter *adap)
254 if (!adap->bus_recovery_info)
257 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
258 return adap->bus_recovery_info->recover_bus(adap);
260 EXPORT_SYMBOL_GPL(i2c_recover_bus);
262 static void i2c_init_recovery(struct i2c_adapter *adap)
264 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
270 if (!bri->recover_bus) {
271 err_str = "no recover_bus() found";
275 /* Generic GPIO recovery */
276 if (bri->recover_bus == i2c_generic_gpio_recovery) {
277 if (!gpio_is_valid(bri->scl_gpio)) {
278 err_str = "invalid SCL gpio";
282 if (gpio_is_valid(bri->sda_gpio))
283 bri->get_sda = get_sda_gpio_value;
287 bri->get_scl = get_scl_gpio_value;
288 bri->set_scl = set_scl_gpio_value;
289 } else if (bri->recover_bus == i2c_generic_scl_recovery) {
290 /* Generic SCL recovery */
291 if (!bri->set_scl || !bri->get_scl) {
292 err_str = "no {get|set}_scl() found";
299 dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
300 adap->bus_recovery_info = NULL;
303 static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
305 struct i2c_adapter *adap = client->adapter;
308 if (!adap->host_notify_domain)
311 if (client->flags & I2C_CLIENT_TEN)
314 irq = irq_find_mapping(adap->host_notify_domain, client->addr);
316 irq = irq_create_mapping(adap->host_notify_domain,
319 return irq > 0 ? irq : -ENXIO;
322 static int i2c_device_probe(struct device *dev)
324 struct i2c_client *client = i2c_verify_client(dev);
325 struct i2c_driver *driver;
331 driver = to_i2c_driver(dev->driver);
333 if (!client->irq && !driver->disable_i2c_core_irq_mapping) {
336 if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
337 dev_dbg(dev, "Using Host Notify IRQ\n");
338 irq = i2c_smbus_host_notify_to_irq(client);
339 } else if (dev->of_node) {
340 irq = of_irq_get_byname(dev->of_node, "irq");
341 if (irq == -EINVAL || irq == -ENODATA)
342 irq = of_irq_get(dev->of_node, 0);
343 } else if (ACPI_COMPANION(dev)) {
344 irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
346 if (irq == -EPROBE_DEFER)
356 * An I2C ID table is not mandatory, if and only if, a suitable Device
357 * Tree match table entry is supplied for the probing device.
359 if (!driver->id_table &&
360 !i2c_of_match_device(dev->driver->of_match_table, client))
363 if (client->flags & I2C_CLIENT_WAKE) {
364 int wakeirq = -ENOENT;
367 wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
368 if (wakeirq == -EPROBE_DEFER)
372 device_init_wakeup(&client->dev, true);
374 if (wakeirq > 0 && wakeirq != client->irq)
375 status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
376 else if (client->irq > 0)
377 status = dev_pm_set_wake_irq(dev, client->irq);
382 dev_warn(&client->dev, "failed to set up wakeup irq\n");
385 dev_dbg(dev, "probe\n");
387 status = of_clk_set_defaults(dev->of_node, false);
389 goto err_clear_wakeup_irq;
391 status = dev_pm_domain_attach(&client->dev, true);
392 if (status == -EPROBE_DEFER)
393 goto err_clear_wakeup_irq;
396 * When there are no more users of probe(),
397 * rename probe_new to probe.
399 if (driver->probe_new)
400 status = driver->probe_new(client);
401 else if (driver->probe)
402 status = driver->probe(client,
403 i2c_match_id(driver->id_table, client));
408 goto err_detach_pm_domain;
412 err_detach_pm_domain:
413 dev_pm_domain_detach(&client->dev, true);
414 err_clear_wakeup_irq:
415 dev_pm_clear_wake_irq(&client->dev);
416 device_init_wakeup(&client->dev, false);
420 static int i2c_device_remove(struct device *dev)
422 struct i2c_client *client = i2c_verify_client(dev);
423 struct i2c_driver *driver;
426 if (!client || !dev->driver)
429 driver = to_i2c_driver(dev->driver);
430 if (driver->remove) {
431 dev_dbg(dev, "remove\n");
432 status = driver->remove(client);
435 dev_pm_domain_detach(&client->dev, true);
437 dev_pm_clear_wake_irq(&client->dev);
438 device_init_wakeup(&client->dev, false);
443 static void i2c_device_shutdown(struct device *dev)
445 struct i2c_client *client = i2c_verify_client(dev);
446 struct i2c_driver *driver;
448 if (!client || !dev->driver)
450 driver = to_i2c_driver(dev->driver);
451 if (driver->shutdown)
452 driver->shutdown(client);
455 static void i2c_client_dev_release(struct device *dev)
457 kfree(to_i2c_client(dev));
461 show_name(struct device *dev, struct device_attribute *attr, char *buf)
463 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
464 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
466 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
469 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
471 struct i2c_client *client = to_i2c_client(dev);
474 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
478 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
480 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
482 static struct attribute *i2c_dev_attrs[] = {
484 /* modalias helps coldplug: modprobe $(cat .../modalias) */
485 &dev_attr_modalias.attr,
488 ATTRIBUTE_GROUPS(i2c_dev);
490 struct bus_type i2c_bus_type = {
492 .match = i2c_device_match,
493 .probe = i2c_device_probe,
494 .remove = i2c_device_remove,
495 .shutdown = i2c_device_shutdown,
497 EXPORT_SYMBOL_GPL(i2c_bus_type);
499 struct device_type i2c_client_type = {
500 .groups = i2c_dev_groups,
501 .uevent = i2c_device_uevent,
502 .release = i2c_client_dev_release,
504 EXPORT_SYMBOL_GPL(i2c_client_type);
508 * i2c_verify_client - return parameter as i2c_client, or NULL
509 * @dev: device, probably from some driver model iterator
511 * When traversing the driver model tree, perhaps using driver model
512 * iterators like @device_for_each_child(), you can't assume very much
513 * about the nodes you find. Use this function to avoid oopses caused
514 * by wrongly treating some non-I2C device as an i2c_client.
516 struct i2c_client *i2c_verify_client(struct device *dev)
518 return (dev->type == &i2c_client_type)
522 EXPORT_SYMBOL(i2c_verify_client);
525 /* Return a unique address which takes the flags of the client into account */
526 static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
528 unsigned short addr = client->addr;
530 /* For some client flags, add an arbitrary offset to avoid collisions */
531 if (client->flags & I2C_CLIENT_TEN)
532 addr |= I2C_ADDR_OFFSET_TEN_BIT;
534 if (client->flags & I2C_CLIENT_SLAVE)
535 addr |= I2C_ADDR_OFFSET_SLAVE;
540 /* This is a permissive address validity check, I2C address map constraints
541 * are purposely not enforced, except for the general call address. */
542 int i2c_check_addr_validity(unsigned addr, unsigned short flags)
544 if (flags & I2C_CLIENT_TEN) {
545 /* 10-bit address, all values are valid */
549 /* 7-bit address, reject the general call address */
550 if (addr == 0x00 || addr > 0x7f)
556 /* And this is a strict address validity check, used when probing. If a
557 * device uses a reserved address, then it shouldn't be probed. 7-bit
558 * addressing is assumed, 10-bit address devices are rare and should be
559 * explicitly enumerated. */
560 int i2c_check_7bit_addr_validity_strict(unsigned short addr)
563 * Reserved addresses per I2C specification:
564 * 0x00 General call address / START byte
566 * 0x02 Reserved for different bus format
567 * 0x03 Reserved for future purposes
568 * 0x04-0x07 Hs-mode master code
569 * 0x78-0x7b 10-bit slave addressing
570 * 0x7c-0x7f Reserved for future purposes
572 if (addr < 0x08 || addr > 0x77)
577 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
579 struct i2c_client *client = i2c_verify_client(dev);
580 int addr = *(int *)addrp;
582 if (client && i2c_encode_flags_to_addr(client) == addr)
587 /* walk up mux tree */
588 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
590 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
593 result = device_for_each_child(&adapter->dev, &addr,
594 __i2c_check_addr_busy);
596 if (!result && parent)
597 result = i2c_check_mux_parents(parent, addr);
602 /* recurse down mux tree */
603 static int i2c_check_mux_children(struct device *dev, void *addrp)
607 if (dev->type == &i2c_adapter_type)
608 result = device_for_each_child(dev, addrp,
609 i2c_check_mux_children);
611 result = __i2c_check_addr_busy(dev, addrp);
616 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
618 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
622 result = i2c_check_mux_parents(parent, addr);
625 result = device_for_each_child(&adapter->dev, &addr,
626 i2c_check_mux_children);
632 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
633 * @adapter: Target I2C bus segment
634 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
635 * locks only this branch in the adapter tree
637 static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
640 rt_mutex_lock(&adapter->bus_lock);
644 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
645 * @adapter: Target I2C bus segment
646 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
647 * trylocks only this branch in the adapter tree
649 static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
652 return rt_mutex_trylock(&adapter->bus_lock);
656 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
657 * @adapter: Target I2C bus segment
658 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
659 * unlocks only this branch in the adapter tree
661 static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
664 rt_mutex_unlock(&adapter->bus_lock);
667 static void i2c_dev_set_name(struct i2c_adapter *adap,
668 struct i2c_client *client)
670 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
673 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
677 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
678 i2c_encode_flags_to_addr(client));
681 static int i2c_dev_irq_from_resources(const struct resource *resources,
682 unsigned int num_resources)
684 struct irq_data *irqd;
687 for (i = 0; i < num_resources; i++) {
688 const struct resource *r = &resources[i];
690 if (resource_type(r) != IORESOURCE_IRQ)
693 if (r->flags & IORESOURCE_BITS) {
694 irqd = irq_get_irq_data(r->start);
698 irqd_set_trigger_type(irqd, r->flags & IORESOURCE_BITS);
708 * i2c_new_device - instantiate an i2c device
709 * @adap: the adapter managing the device
710 * @info: describes one I2C device; bus_num is ignored
713 * Create an i2c device. Binding is handled through driver model
714 * probe()/remove() methods. A driver may be bound to this device when we
715 * return from this function, or any later moment (e.g. maybe hotplugging will
716 * load the driver module). This call is not appropriate for use by mainboard
717 * initialization logic, which usually runs during an arch_initcall() long
718 * before any i2c_adapter could exist.
720 * This returns the new i2c client, which may be saved for later use with
721 * i2c_unregister_device(); or NULL to indicate an error.
724 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
726 struct i2c_client *client;
729 client = kzalloc(sizeof *client, GFP_KERNEL);
733 client->adapter = adap;
735 client->dev.platform_data = info->platform_data;
738 client->dev.archdata = *info->archdata;
740 client->flags = info->flags;
741 client->addr = info->addr;
743 client->irq = info->irq;
745 client->irq = i2c_dev_irq_from_resources(info->resources,
746 info->num_resources);
748 strlcpy(client->name, info->type, sizeof(client->name));
750 status = i2c_check_addr_validity(client->addr, client->flags);
752 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
753 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
757 /* Check for address business */
758 status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
762 client->dev.parent = &client->adapter->dev;
763 client->dev.bus = &i2c_bus_type;
764 client->dev.type = &i2c_client_type;
765 client->dev.of_node = info->of_node;
766 client->dev.fwnode = info->fwnode;
768 i2c_dev_set_name(adap, client);
770 if (info->properties) {
771 status = device_add_properties(&client->dev, info->properties);
774 "Failed to add properties to client %s: %d\n",
775 client->name, status);
780 status = device_register(&client->dev);
784 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
785 client->name, dev_name(&client->dev));
790 if (info->properties)
791 device_remove_properties(&client->dev);
794 "Failed to register i2c client %s at 0x%02x (%d)\n",
795 client->name, client->addr, status);
800 EXPORT_SYMBOL_GPL(i2c_new_device);
804 * i2c_unregister_device - reverse effect of i2c_new_device()
805 * @client: value returned from i2c_new_device()
808 void i2c_unregister_device(struct i2c_client *client)
810 if (client->dev.of_node)
811 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
812 if (ACPI_COMPANION(&client->dev))
813 acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
814 device_unregister(&client->dev);
816 EXPORT_SYMBOL_GPL(i2c_unregister_device);
819 static const struct i2c_device_id dummy_id[] = {
824 static int dummy_probe(struct i2c_client *client,
825 const struct i2c_device_id *id)
830 static int dummy_remove(struct i2c_client *client)
835 static struct i2c_driver dummy_driver = {
836 .driver.name = "dummy",
837 .probe = dummy_probe,
838 .remove = dummy_remove,
839 .id_table = dummy_id,
843 * i2c_new_dummy - return a new i2c device bound to a dummy driver
844 * @adapter: the adapter managing the device
845 * @address: seven bit address to be used
848 * This returns an I2C client bound to the "dummy" driver, intended for use
849 * with devices that consume multiple addresses. Examples of such chips
850 * include various EEPROMS (like 24c04 and 24c08 models).
852 * These dummy devices have two main uses. First, most I2C and SMBus calls
853 * except i2c_transfer() need a client handle; the dummy will be that handle.
854 * And second, this prevents the specified address from being bound to a
857 * This returns the new i2c client, which should be saved for later use with
858 * i2c_unregister_device(); or NULL to indicate an error.
860 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
862 struct i2c_board_info info = {
863 I2C_BOARD_INFO("dummy", address),
866 return i2c_new_device(adapter, &info);
868 EXPORT_SYMBOL_GPL(i2c_new_dummy);
871 * i2c_new_secondary_device - Helper to get the instantiated secondary address
872 * and create the associated device
873 * @client: Handle to the primary client
874 * @name: Handle to specify which secondary address to get
875 * @default_addr: Used as a fallback if no secondary address was specified
878 * I2C clients can be composed of multiple I2C slaves bound together in a single
879 * component. The I2C client driver then binds to the master I2C slave and needs
880 * to create I2C dummy clients to communicate with all the other slaves.
882 * This function creates and returns an I2C dummy client whose I2C address is
883 * retrieved from the platform firmware based on the given slave name. If no
884 * address is specified by the firmware default_addr is used.
886 * On DT-based platforms the address is retrieved from the "reg" property entry
887 * cell whose "reg-names" value matches the slave name.
889 * This returns the new i2c client, which should be saved for later use with
890 * i2c_unregister_device(); or NULL to indicate an error.
892 struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
896 struct device_node *np = client->dev.of_node;
897 u32 addr = default_addr;
901 i = of_property_match_string(np, "reg-names", name);
903 of_property_read_u32_index(np, "reg", i, &addr);
906 dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
907 return i2c_new_dummy(client->adapter, addr);
909 EXPORT_SYMBOL_GPL(i2c_new_secondary_device);
911 /* ------------------------------------------------------------------------- */
913 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
915 static void i2c_adapter_dev_release(struct device *dev)
917 struct i2c_adapter *adap = to_i2c_adapter(dev);
918 complete(&adap->dev_released);
921 unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
923 unsigned int depth = 0;
925 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
928 WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
929 "adapter depth exceeds lockdep subclass limit\n");
933 EXPORT_SYMBOL_GPL(i2c_adapter_depth);
936 * Let users instantiate I2C devices through sysfs. This can be used when
937 * platform initialization code doesn't contain the proper data for
938 * whatever reason. Also useful for drivers that do device detection and
939 * detection fails, either because the device uses an unexpected address,
940 * or this is a compatible device with different ID register values.
942 * Parameter checking may look overzealous, but we really don't want
943 * the user to provide incorrect parameters.
946 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
947 const char *buf, size_t count)
949 struct i2c_adapter *adap = to_i2c_adapter(dev);
950 struct i2c_board_info info;
951 struct i2c_client *client;
955 memset(&info, 0, sizeof(struct i2c_board_info));
957 blank = strchr(buf, ' ');
959 dev_err(dev, "%s: Missing parameters\n", "new_device");
962 if (blank - buf > I2C_NAME_SIZE - 1) {
963 dev_err(dev, "%s: Invalid device name\n", "new_device");
966 memcpy(info.type, buf, blank - buf);
968 /* Parse remaining parameters, reject extra parameters */
969 res = sscanf(++blank, "%hi%c", &info.addr, &end);
971 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
974 if (res > 1 && end != '\n') {
975 dev_err(dev, "%s: Extra parameters\n", "new_device");
979 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
980 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
981 info.flags |= I2C_CLIENT_TEN;
984 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
985 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
986 info.flags |= I2C_CLIENT_SLAVE;
989 client = i2c_new_device(adap, &info);
993 /* Keep track of the added device */
994 mutex_lock(&adap->userspace_clients_lock);
995 list_add_tail(&client->detected, &adap->userspace_clients);
996 mutex_unlock(&adap->userspace_clients_lock);
997 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
998 info.type, info.addr);
1002 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1005 * And of course let the users delete the devices they instantiated, if
1006 * they got it wrong. This interface can only be used to delete devices
1007 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1008 * don't delete devices to which some kernel code still has references.
1010 * Parameter checking may look overzealous, but we really don't want
1011 * the user to delete the wrong device.
1014 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1015 const char *buf, size_t count)
1017 struct i2c_adapter *adap = to_i2c_adapter(dev);
1018 struct i2c_client *client, *next;
1019 unsigned short addr;
1023 /* Parse parameters, reject extra parameters */
1024 res = sscanf(buf, "%hi%c", &addr, &end);
1026 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1029 if (res > 1 && end != '\n') {
1030 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1034 /* Make sure the device was added through sysfs */
1036 mutex_lock_nested(&adap->userspace_clients_lock,
1037 i2c_adapter_depth(adap));
1038 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1040 if (i2c_encode_flags_to_addr(client) == addr) {
1041 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1042 "delete_device", client->name, client->addr);
1044 list_del(&client->detected);
1045 i2c_unregister_device(client);
1050 mutex_unlock(&adap->userspace_clients_lock);
1053 dev_err(dev, "%s: Can't find device in list\n",
1057 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1058 i2c_sysfs_delete_device);
1060 static struct attribute *i2c_adapter_attrs[] = {
1061 &dev_attr_name.attr,
1062 &dev_attr_new_device.attr,
1063 &dev_attr_delete_device.attr,
1066 ATTRIBUTE_GROUPS(i2c_adapter);
1068 struct device_type i2c_adapter_type = {
1069 .groups = i2c_adapter_groups,
1070 .release = i2c_adapter_dev_release,
1072 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1075 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1076 * @dev: device, probably from some driver model iterator
1078 * When traversing the driver model tree, perhaps using driver model
1079 * iterators like @device_for_each_child(), you can't assume very much
1080 * about the nodes you find. Use this function to avoid oopses caused
1081 * by wrongly treating some non-I2C device as an i2c_adapter.
1083 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1085 return (dev->type == &i2c_adapter_type)
1086 ? to_i2c_adapter(dev)
1089 EXPORT_SYMBOL(i2c_verify_adapter);
1091 #ifdef CONFIG_I2C_COMPAT
1092 static struct class_compat *i2c_adapter_compat_class;
1095 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1097 struct i2c_devinfo *devinfo;
1099 down_read(&__i2c_board_lock);
1100 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1101 if (devinfo->busnum == adapter->nr
1102 && !i2c_new_device(adapter,
1103 &devinfo->board_info))
1104 dev_err(&adapter->dev,
1105 "Can't create device at 0x%02x\n",
1106 devinfo->board_info.addr);
1108 up_read(&__i2c_board_lock);
1111 static int i2c_do_add_adapter(struct i2c_driver *driver,
1112 struct i2c_adapter *adap)
1114 /* Detect supported devices on that bus, and instantiate them */
1115 i2c_detect(adap, driver);
1117 /* Let legacy drivers scan this bus for matching devices */
1118 if (driver->attach_adapter) {
1119 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1120 driver->driver.name);
1121 dev_warn(&adap->dev,
1122 "Please use another way to instantiate your i2c_client\n");
1123 /* We ignore the return code; if it fails, too bad */
1124 driver->attach_adapter(adap);
1129 static int __process_new_adapter(struct device_driver *d, void *data)
1131 return i2c_do_add_adapter(to_i2c_driver(d), data);
1134 static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1135 .lock_bus = i2c_adapter_lock_bus,
1136 .trylock_bus = i2c_adapter_trylock_bus,
1137 .unlock_bus = i2c_adapter_unlock_bus,
1140 static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
1142 struct irq_domain *domain = adap->host_notify_domain;
1143 irq_hw_number_t hwirq;
1148 for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
1149 irq_dispose_mapping(irq_find_mapping(domain, hwirq));
1151 irq_domain_remove(domain);
1152 adap->host_notify_domain = NULL;
1155 static int i2c_host_notify_irq_map(struct irq_domain *h,
1157 irq_hw_number_t hw_irq_num)
1159 irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
1164 static const struct irq_domain_ops i2c_host_notify_irq_ops = {
1165 .map = i2c_host_notify_irq_map,
1168 static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
1170 struct irq_domain *domain;
1172 if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
1175 domain = irq_domain_create_linear(adap->dev.fwnode,
1176 I2C_ADDR_7BITS_COUNT,
1177 &i2c_host_notify_irq_ops, adap);
1181 adap->host_notify_domain = domain;
1187 * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
1189 * @adap: the adapter
1190 * @addr: the I2C address of the notifying device
1191 * Context: can't sleep
1193 * Helper function to be called from an I2C bus driver's interrupt
1194 * handler. It will schedule the Host Notify IRQ.
1196 int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
1203 irq = irq_find_mapping(adap->host_notify_domain, addr);
1207 generic_handle_irq(irq);
1211 EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
1213 static int i2c_register_adapter(struct i2c_adapter *adap)
1217 /* Can't register until after driver model init */
1218 if (WARN_ON(!is_registered)) {
1224 if (WARN(!adap->name[0], "i2c adapter has no name"))
1228 pr_err("adapter '%s': no algo supplied!\n", adap->name);
1232 if (!adap->lock_ops)
1233 adap->lock_ops = &i2c_adapter_lock_ops;
1235 rt_mutex_init(&adap->bus_lock);
1236 rt_mutex_init(&adap->mux_lock);
1237 mutex_init(&adap->userspace_clients_lock);
1238 INIT_LIST_HEAD(&adap->userspace_clients);
1240 /* Set default timeout to 1 second if not already set */
1241 if (adap->timeout == 0)
1244 /* register soft irqs for Host Notify */
1245 res = i2c_setup_host_notify_irq_domain(adap);
1247 pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
1252 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1253 adap->dev.bus = &i2c_bus_type;
1254 adap->dev.type = &i2c_adapter_type;
1255 res = device_register(&adap->dev);
1257 pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
1261 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1263 pm_runtime_no_callbacks(&adap->dev);
1264 pm_suspend_ignore_children(&adap->dev, true);
1265 pm_runtime_enable(&adap->dev);
1267 #ifdef CONFIG_I2C_COMPAT
1268 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1271 dev_warn(&adap->dev,
1272 "Failed to create compatibility class link\n");
1275 i2c_init_recovery(adap);
1277 /* create pre-declared device nodes */
1278 of_i2c_register_devices(adap);
1279 i2c_acpi_register_devices(adap);
1280 i2c_acpi_install_space_handler(adap);
1282 if (adap->nr < __i2c_first_dynamic_bus_num)
1283 i2c_scan_static_board_info(adap);
1285 /* Notify drivers */
1286 mutex_lock(&core_lock);
1287 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1288 mutex_unlock(&core_lock);
1293 mutex_lock(&core_lock);
1294 idr_remove(&i2c_adapter_idr, adap->nr);
1295 mutex_unlock(&core_lock);
1300 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1301 * @adap: the adapter to register (with adap->nr initialized)
1302 * Context: can sleep
1304 * See i2c_add_numbered_adapter() for details.
1306 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1310 mutex_lock(&core_lock);
1311 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
1312 mutex_unlock(&core_lock);
1313 if (WARN(id < 0, "couldn't get idr"))
1314 return id == -ENOSPC ? -EBUSY : id;
1316 return i2c_register_adapter(adap);
1320 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1321 * @adapter: the adapter to add
1322 * Context: can sleep
1324 * This routine is used to declare an I2C adapter when its bus number
1325 * doesn't matter or when its bus number is specified by an dt alias.
1326 * Examples of bases when the bus number doesn't matter: I2C adapters
1327 * dynamically added by USB links or PCI plugin cards.
1329 * When this returns zero, a new bus number was allocated and stored
1330 * in adap->nr, and the specified adapter became available for clients.
1331 * Otherwise, a negative errno value is returned.
1333 int i2c_add_adapter(struct i2c_adapter *adapter)
1335 struct device *dev = &adapter->dev;
1339 id = of_alias_get_id(dev->of_node, "i2c");
1342 return __i2c_add_numbered_adapter(adapter);
1346 mutex_lock(&core_lock);
1347 id = idr_alloc(&i2c_adapter_idr, adapter,
1348 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1349 mutex_unlock(&core_lock);
1350 if (WARN(id < 0, "couldn't get idr"))
1355 return i2c_register_adapter(adapter);
1357 EXPORT_SYMBOL(i2c_add_adapter);
1360 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1361 * @adap: the adapter to register (with adap->nr initialized)
1362 * Context: can sleep
1364 * This routine is used to declare an I2C adapter when its bus number
1365 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1366 * or otherwise built in to the system's mainboard, and where i2c_board_info
1367 * is used to properly configure I2C devices.
1369 * If the requested bus number is set to -1, then this function will behave
1370 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1372 * If no devices have pre-been declared for this bus, then be sure to
1373 * register the adapter before any dynamically allocated ones. Otherwise
1374 * the required bus ID may not be available.
1376 * When this returns zero, the specified adapter became available for
1377 * clients using the bus number provided in adap->nr. Also, the table
1378 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1379 * and the appropriate driver model device nodes are created. Otherwise, a
1380 * negative errno value is returned.
1382 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1384 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1385 return i2c_add_adapter(adap);
1387 return __i2c_add_numbered_adapter(adap);
1389 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1391 static void i2c_do_del_adapter(struct i2c_driver *driver,
1392 struct i2c_adapter *adapter)
1394 struct i2c_client *client, *_n;
1396 /* Remove the devices we created ourselves as the result of hardware
1397 * probing (using a driver's detect method) */
1398 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1399 if (client->adapter == adapter) {
1400 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1401 client->name, client->addr);
1402 list_del(&client->detected);
1403 i2c_unregister_device(client);
1408 static int __unregister_client(struct device *dev, void *dummy)
1410 struct i2c_client *client = i2c_verify_client(dev);
1411 if (client && strcmp(client->name, "dummy"))
1412 i2c_unregister_device(client);
1416 static int __unregister_dummy(struct device *dev, void *dummy)
1418 struct i2c_client *client = i2c_verify_client(dev);
1420 i2c_unregister_device(client);
1424 static int __process_removed_adapter(struct device_driver *d, void *data)
1426 i2c_do_del_adapter(to_i2c_driver(d), data);
1431 * i2c_del_adapter - unregister I2C adapter
1432 * @adap: the adapter being unregistered
1433 * Context: can sleep
1435 * This unregisters an I2C adapter which was previously registered
1436 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1438 void i2c_del_adapter(struct i2c_adapter *adap)
1440 struct i2c_adapter *found;
1441 struct i2c_client *client, *next;
1443 /* First make sure that this adapter was ever added */
1444 mutex_lock(&core_lock);
1445 found = idr_find(&i2c_adapter_idr, adap->nr);
1446 mutex_unlock(&core_lock);
1447 if (found != adap) {
1448 pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
1452 i2c_acpi_remove_space_handler(adap);
1453 /* Tell drivers about this removal */
1454 mutex_lock(&core_lock);
1455 bus_for_each_drv(&i2c_bus_type, NULL, adap,
1456 __process_removed_adapter);
1457 mutex_unlock(&core_lock);
1459 /* Remove devices instantiated from sysfs */
1460 mutex_lock_nested(&adap->userspace_clients_lock,
1461 i2c_adapter_depth(adap));
1462 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1464 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1466 list_del(&client->detected);
1467 i2c_unregister_device(client);
1469 mutex_unlock(&adap->userspace_clients_lock);
1471 /* Detach any active clients. This can't fail, thus we do not
1472 * check the returned value. This is a two-pass process, because
1473 * we can't remove the dummy devices during the first pass: they
1474 * could have been instantiated by real devices wishing to clean
1475 * them up properly, so we give them a chance to do that first. */
1476 device_for_each_child(&adap->dev, NULL, __unregister_client);
1477 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1479 #ifdef CONFIG_I2C_COMPAT
1480 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1484 /* device name is gone after device_unregister */
1485 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1487 pm_runtime_disable(&adap->dev);
1489 i2c_host_notify_irq_teardown(adap);
1491 /* wait until all references to the device are gone
1493 * FIXME: This is old code and should ideally be replaced by an
1494 * alternative which results in decoupling the lifetime of the struct
1495 * device from the i2c_adapter, like spi or netdev do. Any solution
1496 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
1498 init_completion(&adap->dev_released);
1499 device_unregister(&adap->dev);
1500 wait_for_completion(&adap->dev_released);
1503 mutex_lock(&core_lock);
1504 idr_remove(&i2c_adapter_idr, adap->nr);
1505 mutex_unlock(&core_lock);
1507 /* Clear the device structure in case this adapter is ever going to be
1509 memset(&adap->dev, 0, sizeof(adap->dev));
1511 EXPORT_SYMBOL(i2c_del_adapter);
1514 * i2c_parse_fw_timings - get I2C related timing parameters from firmware
1515 * @dev: The device to scan for I2C timing properties
1516 * @t: the i2c_timings struct to be filled with values
1517 * @use_defaults: bool to use sane defaults derived from the I2C specification
1518 * when properties are not found, otherwise use 0
1520 * Scan the device for the generic I2C properties describing timing parameters
1521 * for the signal and fill the given struct with the results. If a property was
1522 * not found and use_defaults was true, then maximum timings are assumed which
1523 * are derived from the I2C specification. If use_defaults is not used, the
1524 * results will be 0, so drivers can apply their own defaults later. The latter
1525 * is mainly intended for avoiding regressions of existing drivers which want
1526 * to switch to this function. New drivers almost always should use the defaults.
1529 void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
1533 memset(t, 0, sizeof(*t));
1535 ret = device_property_read_u32(dev, "clock-frequency", &t->bus_freq_hz);
1536 if (ret && use_defaults)
1537 t->bus_freq_hz = 100000;
1539 ret = device_property_read_u32(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns);
1540 if (ret && use_defaults) {
1541 if (t->bus_freq_hz <= 100000)
1542 t->scl_rise_ns = 1000;
1543 else if (t->bus_freq_hz <= 400000)
1544 t->scl_rise_ns = 300;
1546 t->scl_rise_ns = 120;
1549 ret = device_property_read_u32(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns);
1550 if (ret && use_defaults) {
1551 if (t->bus_freq_hz <= 400000)
1552 t->scl_fall_ns = 300;
1554 t->scl_fall_ns = 120;
1557 device_property_read_u32(dev, "i2c-scl-internal-delay-ns", &t->scl_int_delay_ns);
1559 ret = device_property_read_u32(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns);
1560 if (ret && use_defaults)
1561 t->sda_fall_ns = t->scl_fall_ns;
1563 EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
1565 /* ------------------------------------------------------------------------- */
1567 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1571 mutex_lock(&core_lock);
1572 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1573 mutex_unlock(&core_lock);
1577 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1579 static int __process_new_driver(struct device *dev, void *data)
1581 if (dev->type != &i2c_adapter_type)
1583 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1587 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1588 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1591 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1595 /* Can't register until after driver model init */
1596 if (WARN_ON(!is_registered))
1599 /* add the driver to the list of i2c drivers in the driver core */
1600 driver->driver.owner = owner;
1601 driver->driver.bus = &i2c_bus_type;
1602 INIT_LIST_HEAD(&driver->clients);
1604 /* When registration returns, the driver core
1605 * will have called probe() for all matching-but-unbound devices.
1607 res = driver_register(&driver->driver);
1611 pr_debug("driver [%s] registered\n", driver->driver.name);
1613 /* Walk the adapters that are already present */
1614 i2c_for_each_dev(driver, __process_new_driver);
1618 EXPORT_SYMBOL(i2c_register_driver);
1620 static int __process_removed_driver(struct device *dev, void *data)
1622 if (dev->type == &i2c_adapter_type)
1623 i2c_do_del_adapter(data, to_i2c_adapter(dev));
1628 * i2c_del_driver - unregister I2C driver
1629 * @driver: the driver being unregistered
1630 * Context: can sleep
1632 void i2c_del_driver(struct i2c_driver *driver)
1634 i2c_for_each_dev(driver, __process_removed_driver);
1636 driver_unregister(&driver->driver);
1637 pr_debug("driver [%s] unregistered\n", driver->driver.name);
1639 EXPORT_SYMBOL(i2c_del_driver);
1641 /* ------------------------------------------------------------------------- */
1644 * i2c_use_client - increments the reference count of the i2c client structure
1645 * @client: the client being referenced
1647 * Each live reference to a client should be refcounted. The driver model does
1648 * that automatically as part of driver binding, so that most drivers don't
1649 * need to do this explicitly: they hold a reference until they're unbound
1652 * A pointer to the client with the incremented reference counter is returned.
1654 struct i2c_client *i2c_use_client(struct i2c_client *client)
1656 if (client && get_device(&client->dev))
1660 EXPORT_SYMBOL(i2c_use_client);
1663 * i2c_release_client - release a use of the i2c client structure
1664 * @client: the client being no longer referenced
1666 * Must be called when a user of a client is finished with it.
1668 void i2c_release_client(struct i2c_client *client)
1671 put_device(&client->dev);
1673 EXPORT_SYMBOL(i2c_release_client);
1675 struct i2c_cmd_arg {
1680 static int i2c_cmd(struct device *dev, void *_arg)
1682 struct i2c_client *client = i2c_verify_client(dev);
1683 struct i2c_cmd_arg *arg = _arg;
1684 struct i2c_driver *driver;
1686 if (!client || !client->dev.driver)
1689 driver = to_i2c_driver(client->dev.driver);
1690 if (driver->command)
1691 driver->command(client, arg->cmd, arg->arg);
1695 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1697 struct i2c_cmd_arg cmd_arg;
1701 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1703 EXPORT_SYMBOL(i2c_clients_command);
1705 static int __init i2c_init(void)
1709 retval = of_alias_get_highest_id("i2c");
1711 down_write(&__i2c_board_lock);
1712 if (retval >= __i2c_first_dynamic_bus_num)
1713 __i2c_first_dynamic_bus_num = retval + 1;
1714 up_write(&__i2c_board_lock);
1716 retval = bus_register(&i2c_bus_type);
1720 is_registered = true;
1722 #ifdef CONFIG_I2C_COMPAT
1723 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1724 if (!i2c_adapter_compat_class) {
1729 retval = i2c_add_driver(&dummy_driver);
1733 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1734 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
1735 if (IS_ENABLED(CONFIG_ACPI))
1736 WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
1741 #ifdef CONFIG_I2C_COMPAT
1742 class_compat_unregister(i2c_adapter_compat_class);
1745 is_registered = false;
1746 bus_unregister(&i2c_bus_type);
1750 static void __exit i2c_exit(void)
1752 if (IS_ENABLED(CONFIG_ACPI))
1753 WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
1754 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1755 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
1756 i2c_del_driver(&dummy_driver);
1757 #ifdef CONFIG_I2C_COMPAT
1758 class_compat_unregister(i2c_adapter_compat_class);
1760 bus_unregister(&i2c_bus_type);
1761 tracepoint_synchronize_unregister();
1764 /* We must initialize early, because some subsystems register i2c drivers
1765 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1767 postcore_initcall(i2c_init);
1768 module_exit(i2c_exit);
1770 /* ----------------------------------------------------
1771 * the functional interface to the i2c busses.
1772 * ----------------------------------------------------
1775 /* Check if val is exceeding the quirk IFF quirk is non 0 */
1776 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
1778 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
1780 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
1781 err_msg, msg->addr, msg->len,
1782 msg->flags & I2C_M_RD ? "read" : "write");
1786 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1788 const struct i2c_adapter_quirks *q = adap->quirks;
1789 int max_num = q->max_num_msgs, i;
1790 bool do_len_check = true;
1792 if (q->flags & I2C_AQ_COMB) {
1795 /* special checks for combined messages */
1797 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
1798 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
1800 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
1801 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
1803 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
1804 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
1806 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
1807 return i2c_quirk_error(adap, &msgs[0], "msg too long");
1809 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
1810 return i2c_quirk_error(adap, &msgs[1], "msg too long");
1812 do_len_check = false;
1816 if (i2c_quirk_exceeded(num, max_num))
1817 return i2c_quirk_error(adap, &msgs[0], "too many messages");
1819 for (i = 0; i < num; i++) {
1820 u16 len = msgs[i].len;
1822 if (msgs[i].flags & I2C_M_RD) {
1823 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
1824 return i2c_quirk_error(adap, &msgs[i], "msg too long");
1826 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
1827 return i2c_quirk_error(adap, &msgs[i], "msg too long");
1835 * __i2c_transfer - unlocked flavor of i2c_transfer
1836 * @adap: Handle to I2C bus
1837 * @msgs: One or more messages to execute before STOP is issued to
1838 * terminate the operation; each message begins with a START.
1839 * @num: Number of messages to be executed.
1841 * Returns negative errno, else the number of messages executed.
1843 * Adapter lock must be held when calling this function. No debug logging
1844 * takes place. adap->algo->master_xfer existence isn't checked.
1846 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1848 unsigned long orig_jiffies;
1851 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
1854 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
1855 * enabled. This is an efficient way of keeping the for-loop from
1856 * being executed when not needed.
1858 if (static_key_false(&i2c_trace_msg)) {
1860 for (i = 0; i < num; i++)
1861 if (msgs[i].flags & I2C_M_RD)
1862 trace_i2c_read(adap, &msgs[i], i);
1864 trace_i2c_write(adap, &msgs[i], i);
1867 /* Retry automatically on arbitration loss */
1868 orig_jiffies = jiffies;
1869 for (ret = 0, try = 0; try <= adap->retries; try++) {
1870 ret = adap->algo->master_xfer(adap, msgs, num);
1873 if (time_after(jiffies, orig_jiffies + adap->timeout))
1877 if (static_key_false(&i2c_trace_msg)) {
1879 for (i = 0; i < ret; i++)
1880 if (msgs[i].flags & I2C_M_RD)
1881 trace_i2c_reply(adap, &msgs[i], i);
1882 trace_i2c_result(adap, i, ret);
1887 EXPORT_SYMBOL(__i2c_transfer);
1890 * i2c_transfer - execute a single or combined I2C message
1891 * @adap: Handle to I2C bus
1892 * @msgs: One or more messages to execute before STOP is issued to
1893 * terminate the operation; each message begins with a START.
1894 * @num: Number of messages to be executed.
1896 * Returns negative errno, else the number of messages executed.
1898 * Note that there is no requirement that each message be sent to
1899 * the same slave address, although that is the most common model.
1901 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1905 /* REVISIT the fault reporting model here is weak:
1907 * - When we get an error after receiving N bytes from a slave,
1908 * there is no way to report "N".
1910 * - When we get a NAK after transmitting N bytes to a slave,
1911 * there is no way to report "N" ... or to let the master
1912 * continue executing the rest of this combined message, if
1913 * that's the appropriate response.
1915 * - When for example "num" is two and we successfully complete
1916 * the first message but get an error part way through the
1917 * second, it's unclear whether that should be reported as
1918 * one (discarding status on the second message) or errno
1919 * (discarding status on the first one).
1922 if (adap->algo->master_xfer) {
1924 for (ret = 0; ret < num; ret++) {
1926 "master_xfer[%d] %c, addr=0x%02x, len=%d%s\n",
1927 ret, (msgs[ret].flags & I2C_M_RD) ? 'R' : 'W',
1928 msgs[ret].addr, msgs[ret].len,
1929 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
1933 if (in_atomic() || irqs_disabled()) {
1934 ret = i2c_trylock_bus(adap, I2C_LOCK_SEGMENT);
1936 /* I2C activity is ongoing. */
1939 i2c_lock_bus(adap, I2C_LOCK_SEGMENT);
1942 ret = __i2c_transfer(adap, msgs, num);
1943 i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
1947 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
1951 EXPORT_SYMBOL(i2c_transfer);
1954 * i2c_master_send - issue a single I2C message in master transmit mode
1955 * @client: Handle to slave device
1956 * @buf: Data that will be written to the slave
1957 * @count: How many bytes to write, must be less than 64k since msg.len is u16
1959 * Returns negative errno, or else the number of bytes written.
1961 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
1964 struct i2c_adapter *adap = client->adapter;
1967 msg.addr = client->addr;
1968 msg.flags = client->flags & I2C_M_TEN;
1970 msg.buf = (char *)buf;
1972 ret = i2c_transfer(adap, &msg, 1);
1975 * If everything went ok (i.e. 1 msg transmitted), return #bytes
1976 * transmitted, else error code.
1978 return (ret == 1) ? count : ret;
1980 EXPORT_SYMBOL(i2c_master_send);
1983 * i2c_master_recv - issue a single I2C message in master receive mode
1984 * @client: Handle to slave device
1985 * @buf: Where to store data read from slave
1986 * @count: How many bytes to read, must be less than 64k since msg.len is u16
1988 * Returns negative errno, or else the number of bytes read.
1990 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
1992 struct i2c_adapter *adap = client->adapter;
1996 msg.addr = client->addr;
1997 msg.flags = client->flags & I2C_M_TEN;
1998 msg.flags |= I2C_M_RD;
2002 ret = i2c_transfer(adap, &msg, 1);
2005 * If everything went ok (i.e. 1 msg received), return #bytes received,
2008 return (ret == 1) ? count : ret;
2010 EXPORT_SYMBOL(i2c_master_recv);
2012 /* ----------------------------------------------------
2013 * the i2c address scanning function
2014 * Will not work for 10-bit addresses!
2015 * ----------------------------------------------------
2019 * Legacy default probe function, mostly relevant for SMBus. The default
2020 * probe method is a quick write, but it is known to corrupt the 24RF08
2021 * EEPROMs due to a state machine bug, and could also irreversibly
2022 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2023 * we use a short byte read instead. Also, some bus drivers don't implement
2024 * quick write, so we fallback to a byte read in that case too.
2025 * On x86, there is another special case for FSC hardware monitoring chips,
2026 * which want regular byte reads (address 0x73.) Fortunately, these are the
2027 * only known chips using this I2C address on PC hardware.
2028 * Returns 1 if probe succeeded, 0 if not.
2030 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2033 union i2c_smbus_data dummy;
2036 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2037 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2038 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2039 I2C_SMBUS_BYTE_DATA, &dummy);
2042 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2043 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2044 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2045 I2C_SMBUS_QUICK, NULL);
2046 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2047 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2048 I2C_SMBUS_BYTE, &dummy);
2050 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2058 static int i2c_detect_address(struct i2c_client *temp_client,
2059 struct i2c_driver *driver)
2061 struct i2c_board_info info;
2062 struct i2c_adapter *adapter = temp_client->adapter;
2063 int addr = temp_client->addr;
2066 /* Make sure the address is valid */
2067 err = i2c_check_7bit_addr_validity_strict(addr);
2069 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2074 /* Skip if already in use (7 bit, no need to encode flags) */
2075 if (i2c_check_addr_busy(adapter, addr))
2078 /* Make sure there is something at this address */
2079 if (!i2c_default_probe(adapter, addr))
2082 /* Finally call the custom detection function */
2083 memset(&info, 0, sizeof(struct i2c_board_info));
2085 err = driver->detect(temp_client, &info);
2087 /* -ENODEV is returned if the detection fails. We catch it
2088 here as this isn't an error. */
2089 return err == -ENODEV ? 0 : err;
2092 /* Consistency check */
2093 if (info.type[0] == '\0') {
2094 dev_err(&adapter->dev,
2095 "%s detection function provided no name for 0x%x\n",
2096 driver->driver.name, addr);
2098 struct i2c_client *client;
2100 /* Detection succeeded, instantiate the device */
2101 if (adapter->class & I2C_CLASS_DEPRECATED)
2102 dev_warn(&adapter->dev,
2103 "This adapter will soon drop class based instantiation of devices. "
2104 "Please make sure client 0x%02x gets instantiated by other means. "
2105 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2108 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2109 info.type, info.addr);
2110 client = i2c_new_device(adapter, &info);
2112 list_add_tail(&client->detected, &driver->clients);
2114 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2115 info.type, info.addr);
2120 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2122 const unsigned short *address_list;
2123 struct i2c_client *temp_client;
2125 int adap_id = i2c_adapter_id(adapter);
2127 address_list = driver->address_list;
2128 if (!driver->detect || !address_list)
2131 /* Warn that the adapter lost class based instantiation */
2132 if (adapter->class == I2C_CLASS_DEPRECATED) {
2133 dev_dbg(&adapter->dev,
2134 "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
2135 "If you need it, check 'Documentation/i2c/instantiating-devices' for alternatives.\n",
2136 driver->driver.name);
2140 /* Stop here if the classes do not match */
2141 if (!(adapter->class & driver->class))
2144 /* Set up a temporary client to help detect callback */
2145 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2148 temp_client->adapter = adapter;
2150 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2151 dev_dbg(&adapter->dev,
2152 "found normal entry for adapter %d, addr 0x%02x\n",
2153 adap_id, address_list[i]);
2154 temp_client->addr = address_list[i];
2155 err = i2c_detect_address(temp_client, driver);
2164 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2166 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2167 I2C_SMBUS_QUICK, NULL) >= 0;
2169 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2172 i2c_new_probed_device(struct i2c_adapter *adap,
2173 struct i2c_board_info *info,
2174 unsigned short const *addr_list,
2175 int (*probe)(struct i2c_adapter *, unsigned short addr))
2180 probe = i2c_default_probe;
2182 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2183 /* Check address validity */
2184 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2185 dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
2190 /* Check address availability (7 bit, no need to encode flags) */
2191 if (i2c_check_addr_busy(adap, addr_list[i])) {
2193 "Address 0x%02x already in use, not probing\n",
2198 /* Test address responsiveness */
2199 if (probe(adap, addr_list[i]))
2203 if (addr_list[i] == I2C_CLIENT_END) {
2204 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2208 info->addr = addr_list[i];
2209 return i2c_new_device(adap, info);
2211 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2213 struct i2c_adapter *i2c_get_adapter(int nr)
2215 struct i2c_adapter *adapter;
2217 mutex_lock(&core_lock);
2218 adapter = idr_find(&i2c_adapter_idr, nr);
2222 if (try_module_get(adapter->owner))
2223 get_device(&adapter->dev);
2228 mutex_unlock(&core_lock);
2231 EXPORT_SYMBOL(i2c_get_adapter);
2233 void i2c_put_adapter(struct i2c_adapter *adap)
2238 put_device(&adap->dev);
2239 module_put(adap->owner);
2241 EXPORT_SYMBOL(i2c_put_adapter);
2244 MODULE_DESCRIPTION("I2C-Bus main module");
2245 MODULE_LICENSE("GPL");