1 /* i2c-core.c - a device driver for the iic-bus interface */
2 /* ------------------------------------------------------------------------- */
3 /* Copyright (C) 1995-99 Simon G. Vogl
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details. */
14 /* ------------------------------------------------------------------------- */
16 /* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>.
17 All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
18 SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com> and
19 Jean Delvare <jdelvare@suse.de>
20 Mux support by Rodolfo Giometti <giometti@enneenne.com> and
21 Michael Lawnick <michael.lawnick.ext@nsn.com>
22 OF support is copyright (c) 2008 Jochen Friedrich <jochen@scram.de>
23 (based on a previous patch from Jon Smirl <jonsmirl@gmail.com>) and
24 (c) 2013 Wolfram Sang <wsa@the-dreams.de>
25 I2C ACPI code Copyright (C) 2014 Intel Corp
26 Author: Lan Tianyu <tianyu.lan@intel.com>
27 I2C slave support (c) 2014 by Wolfram Sang <wsa@sang-engineering.com>
30 #include <dt-bindings/i2c/i2c.h>
31 #include <linux/module.h>
32 #include <linux/kernel.h>
33 #include <linux/delay.h>
34 #include <linux/errno.h>
35 #include <linux/gpio.h>
36 #include <linux/slab.h>
37 #include <linux/i2c.h>
38 #include <linux/init.h>
39 #include <linux/idr.h>
40 #include <linux/mutex.h>
42 #include <linux/of_device.h>
43 #include <linux/of_irq.h>
44 #include <linux/clk/clk-conf.h>
45 #include <linux/completion.h>
46 #include <linux/hardirq.h>
47 #include <linux/irqflags.h>
48 #include <linux/rwsem.h>
49 #include <linux/pm_runtime.h>
50 #include <linux/pm_domain.h>
51 #include <linux/pm_wakeirq.h>
52 #include <linux/acpi.h>
53 #include <linux/jump_label.h>
54 #include <asm/uaccess.h>
55 #include <linux/err.h>
59 #define CREATE_TRACE_POINTS
60 #include <trace/events/i2c.h>
62 #define I2C_ADDR_OFFSET_TEN_BIT 0xa000
63 #define I2C_ADDR_OFFSET_SLAVE 0x1000
65 /* core_lock protects i2c_adapter_idr, and guarantees
66 that device detection, deletion of detected devices, and attach_adapter
67 calls are serialized */
68 static DEFINE_MUTEX(core_lock);
69 static DEFINE_IDR(i2c_adapter_idr);
71 static struct device_type i2c_client_type;
72 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
74 static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
76 void i2c_transfer_trace_reg(void)
78 static_key_slow_inc(&i2c_trace_msg);
81 void i2c_transfer_trace_unreg(void)
83 static_key_slow_dec(&i2c_trace_msg);
86 #if defined(CONFIG_ACPI)
87 struct acpi_i2c_handler_data {
88 struct acpi_connection_info info;
89 struct i2c_adapter *adapter;
102 static int acpi_i2c_add_resource(struct acpi_resource *ares, void *data)
104 struct i2c_board_info *info = data;
106 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
107 struct acpi_resource_i2c_serialbus *sb;
109 sb = &ares->data.i2c_serial_bus;
110 if (!info->addr && sb->type == ACPI_RESOURCE_SERIAL_TYPE_I2C) {
111 info->addr = sb->slave_address;
112 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
113 info->flags |= I2C_CLIENT_TEN;
115 } else if (!info->irq) {
118 if (acpi_dev_resource_interrupt(ares, 0, &r))
122 /* Tell the ACPI core to skip this resource */
126 static acpi_status acpi_i2c_add_device(acpi_handle handle, u32 level,
127 void *data, void **return_value)
129 struct i2c_adapter *adapter = data;
130 struct list_head resource_list;
131 struct i2c_board_info info;
132 struct acpi_device *adev;
135 if (acpi_bus_get_device(handle, &adev))
137 if (acpi_bus_get_status(adev) || !adev->status.present)
140 memset(&info, 0, sizeof(info));
141 info.fwnode = acpi_fwnode_handle(adev);
143 INIT_LIST_HEAD(&resource_list);
144 ret = acpi_dev_get_resources(adev, &resource_list,
145 acpi_i2c_add_resource, &info);
146 acpi_dev_free_resource_list(&resource_list);
148 if (ret < 0 || !info.addr)
151 adev->power.flags.ignore_parent = true;
152 strlcpy(info.type, dev_name(&adev->dev), sizeof(info.type));
153 if (!i2c_new_device(adapter, &info)) {
154 adev->power.flags.ignore_parent = false;
155 dev_err(&adapter->dev,
156 "failed to add I2C device %s from ACPI\n",
157 dev_name(&adev->dev));
164 * acpi_i2c_register_devices - enumerate I2C slave devices behind adapter
165 * @adap: pointer to adapter
167 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
168 * namespace. When a device is found it will be added to the Linux device
169 * model and bound to the corresponding ACPI handle.
171 static void acpi_i2c_register_devices(struct i2c_adapter *adap)
176 if (!adap->dev.parent)
179 handle = ACPI_HANDLE(adap->dev.parent);
183 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
184 acpi_i2c_add_device, NULL,
186 if (ACPI_FAILURE(status))
187 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
190 #else /* CONFIG_ACPI */
191 static inline void acpi_i2c_register_devices(struct i2c_adapter *adap) { }
192 #endif /* CONFIG_ACPI */
194 #ifdef CONFIG_ACPI_I2C_OPREGION
195 static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
196 u8 cmd, u8 *data, u8 data_len)
199 struct i2c_msg msgs[2];
203 buffer = kzalloc(data_len, GFP_KERNEL);
207 msgs[0].addr = client->addr;
208 msgs[0].flags = client->flags;
212 msgs[1].addr = client->addr;
213 msgs[1].flags = client->flags | I2C_M_RD;
214 msgs[1].len = data_len;
215 msgs[1].buf = buffer;
217 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
219 dev_err(&client->adapter->dev, "i2c read failed\n");
221 memcpy(data, buffer, data_len);
227 static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
228 u8 cmd, u8 *data, u8 data_len)
231 struct i2c_msg msgs[1];
235 buffer = kzalloc(data_len + 1, GFP_KERNEL);
240 memcpy(buffer + 1, data, data_len);
242 msgs[0].addr = client->addr;
243 msgs[0].flags = client->flags;
244 msgs[0].len = data_len + 1;
245 msgs[0].buf = buffer;
247 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
249 dev_err(&client->adapter->dev, "i2c write failed\n");
256 acpi_i2c_space_handler(u32 function, acpi_physical_address command,
257 u32 bits, u64 *value64,
258 void *handler_context, void *region_context)
260 struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
261 struct acpi_i2c_handler_data *data = handler_context;
262 struct acpi_connection_info *info = &data->info;
263 struct acpi_resource_i2c_serialbus *sb;
264 struct i2c_adapter *adapter = data->adapter;
265 struct i2c_client *client;
266 struct acpi_resource *ares;
267 u32 accessor_type = function >> 16;
268 u8 action = function & ACPI_IO_MASK;
272 ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
273 if (ACPI_FAILURE(ret))
276 client = kzalloc(sizeof(*client), GFP_KERNEL);
282 if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
283 ret = AE_BAD_PARAMETER;
287 sb = &ares->data.i2c_serial_bus;
288 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
289 ret = AE_BAD_PARAMETER;
293 client->adapter = adapter;
294 client->addr = sb->slave_address;
296 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
297 client->flags |= I2C_CLIENT_TEN;
299 switch (accessor_type) {
300 case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
301 if (action == ACPI_READ) {
302 status = i2c_smbus_read_byte(client);
308 status = i2c_smbus_write_byte(client, gsb->bdata);
312 case ACPI_GSB_ACCESS_ATTRIB_BYTE:
313 if (action == ACPI_READ) {
314 status = i2c_smbus_read_byte_data(client, command);
320 status = i2c_smbus_write_byte_data(client, command,
325 case ACPI_GSB_ACCESS_ATTRIB_WORD:
326 if (action == ACPI_READ) {
327 status = i2c_smbus_read_word_data(client, command);
333 status = i2c_smbus_write_word_data(client, command,
338 case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
339 if (action == ACPI_READ) {
340 status = i2c_smbus_read_block_data(client, command,
347 status = i2c_smbus_write_block_data(client, command,
348 gsb->len, gsb->data);
352 case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
353 if (action == ACPI_READ) {
354 status = acpi_gsb_i2c_read_bytes(client, command,
355 gsb->data, info->access_length);
359 status = acpi_gsb_i2c_write_bytes(client, command,
360 gsb->data, info->access_length);
365 pr_info("protocol(0x%02x) is not supported.\n", accessor_type);
366 ret = AE_BAD_PARAMETER;
370 gsb->status = status;
379 static int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
382 struct acpi_i2c_handler_data *data;
385 if (!adapter->dev.parent)
388 handle = ACPI_HANDLE(adapter->dev.parent);
393 data = kzalloc(sizeof(struct acpi_i2c_handler_data),
398 data->adapter = adapter;
399 status = acpi_bus_attach_private_data(handle, (void *)data);
400 if (ACPI_FAILURE(status)) {
405 status = acpi_install_address_space_handler(handle,
406 ACPI_ADR_SPACE_GSBUS,
407 &acpi_i2c_space_handler,
410 if (ACPI_FAILURE(status)) {
411 dev_err(&adapter->dev, "Error installing i2c space handler\n");
412 acpi_bus_detach_private_data(handle);
417 acpi_walk_dep_device_list(handle);
421 static void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
424 struct acpi_i2c_handler_data *data;
427 if (!adapter->dev.parent)
430 handle = ACPI_HANDLE(adapter->dev.parent);
435 acpi_remove_address_space_handler(handle,
436 ACPI_ADR_SPACE_GSBUS,
437 &acpi_i2c_space_handler);
439 status = acpi_bus_get_private_data(handle, (void **)&data);
440 if (ACPI_SUCCESS(status))
443 acpi_bus_detach_private_data(handle);
445 #else /* CONFIG_ACPI_I2C_OPREGION */
446 static inline void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
449 static inline int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
451 #endif /* CONFIG_ACPI_I2C_OPREGION */
453 /* ------------------------------------------------------------------------- */
455 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
456 const struct i2c_client *client)
458 while (id->name[0]) {
459 if (strcmp(client->name, id->name) == 0)
466 static int i2c_device_match(struct device *dev, struct device_driver *drv)
468 struct i2c_client *client = i2c_verify_client(dev);
469 struct i2c_driver *driver;
474 /* Attempt an OF style match */
475 if (of_driver_match_device(dev, drv))
478 /* Then ACPI style match */
479 if (acpi_driver_match_device(dev, drv))
482 driver = to_i2c_driver(drv);
483 /* match on an id table if there is one */
484 if (driver->id_table)
485 return i2c_match_id(driver->id_table, client) != NULL;
491 /* uevent helps with hotplug: modprobe -q $(MODALIAS) */
492 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
494 struct i2c_client *client = to_i2c_client(dev);
497 rc = acpi_device_uevent_modalias(dev, env);
501 if (add_uevent_var(env, "MODALIAS=%s%s",
502 I2C_MODULE_PREFIX, client->name))
504 dev_dbg(dev, "uevent\n");
508 /* i2c bus recovery routines */
509 static int get_scl_gpio_value(struct i2c_adapter *adap)
511 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
514 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
516 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
519 static int get_sda_gpio_value(struct i2c_adapter *adap)
521 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
524 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
526 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
527 struct device *dev = &adap->dev;
530 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
531 GPIOF_OUT_INIT_HIGH, "i2c-scl");
533 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
538 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
539 /* work without SDA polling */
540 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
549 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
551 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
554 gpio_free(bri->sda_gpio);
556 gpio_free(bri->scl_gpio);
560 * We are generating clock pulses. ndelay() determines durating of clk pulses.
561 * We will generate clock with rate 100 KHz and so duration of both clock levels
562 * is: delay in ns = (10^6 / 100) / 2
564 #define RECOVERY_NDELAY 5000
565 #define RECOVERY_CLK_CNT 9
567 static int i2c_generic_recovery(struct i2c_adapter *adap)
569 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
570 int i = 0, val = 1, ret = 0;
572 if (bri->prepare_recovery)
573 bri->prepare_recovery(adap);
575 bri->set_scl(adap, val);
576 ndelay(RECOVERY_NDELAY);
579 * By this time SCL is high, as we need to give 9 falling-rising edges
581 while (i++ < RECOVERY_CLK_CNT * 2) {
583 /* Break if SDA is high */
584 if (bri->get_sda && bri->get_sda(adap))
586 /* SCL shouldn't be low here */
587 if (!bri->get_scl(adap)) {
589 "SCL is stuck low, exit recovery\n");
596 bri->set_scl(adap, val);
597 ndelay(RECOVERY_NDELAY);
600 if (bri->unprepare_recovery)
601 bri->unprepare_recovery(adap);
606 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
608 return i2c_generic_recovery(adap);
610 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
612 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
616 ret = i2c_get_gpios_for_recovery(adap);
620 ret = i2c_generic_recovery(adap);
621 i2c_put_gpios_for_recovery(adap);
625 EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
627 int i2c_recover_bus(struct i2c_adapter *adap)
629 if (!adap->bus_recovery_info)
632 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
633 return adap->bus_recovery_info->recover_bus(adap);
635 EXPORT_SYMBOL_GPL(i2c_recover_bus);
637 static int i2c_device_probe(struct device *dev)
639 struct i2c_client *client = i2c_verify_client(dev);
640 struct i2c_driver *driver;
650 irq = of_irq_get_byname(dev->of_node, "irq");
651 if (irq == -EINVAL || irq == -ENODATA)
652 irq = of_irq_get(dev->of_node, 0);
653 } else if (ACPI_COMPANION(dev)) {
654 irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
656 if (irq == -EPROBE_DEFER)
664 driver = to_i2c_driver(dev->driver);
665 if (!driver->probe || !driver->id_table)
668 if (client->flags & I2C_CLIENT_WAKE) {
669 int wakeirq = -ENOENT;
672 wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
673 if (wakeirq == -EPROBE_DEFER)
677 device_init_wakeup(&client->dev, true);
679 if (wakeirq > 0 && wakeirq != client->irq)
680 status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
681 else if (client->irq > 0)
682 status = dev_pm_set_wake_irq(dev, wakeirq);
687 dev_warn(&client->dev, "failed to set up wakeup irq");
690 dev_dbg(dev, "probe\n");
692 status = of_clk_set_defaults(dev->of_node, false);
694 goto err_clear_wakeup_irq;
696 status = dev_pm_domain_attach(&client->dev, true);
697 if (status == -EPROBE_DEFER)
698 goto err_clear_wakeup_irq;
700 status = driver->probe(client, i2c_match_id(driver->id_table, client));
702 goto err_detach_pm_domain;
706 err_detach_pm_domain:
707 dev_pm_domain_detach(&client->dev, true);
708 err_clear_wakeup_irq:
709 dev_pm_clear_wake_irq(&client->dev);
710 device_init_wakeup(&client->dev, false);
714 static int i2c_device_remove(struct device *dev)
716 struct i2c_client *client = i2c_verify_client(dev);
717 struct i2c_driver *driver;
720 if (!client || !dev->driver)
723 driver = to_i2c_driver(dev->driver);
724 if (driver->remove) {
725 dev_dbg(dev, "remove\n");
726 status = driver->remove(client);
729 dev_pm_domain_detach(&client->dev, true);
731 dev_pm_clear_wake_irq(&client->dev);
732 device_init_wakeup(&client->dev, false);
737 static void i2c_device_shutdown(struct device *dev)
739 struct i2c_client *client = i2c_verify_client(dev);
740 struct i2c_driver *driver;
742 if (!client || !dev->driver)
744 driver = to_i2c_driver(dev->driver);
745 if (driver->shutdown)
746 driver->shutdown(client);
749 static void i2c_client_dev_release(struct device *dev)
751 kfree(to_i2c_client(dev));
755 show_name(struct device *dev, struct device_attribute *attr, char *buf)
757 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
758 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
760 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
763 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
765 struct i2c_client *client = to_i2c_client(dev);
768 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
772 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
774 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
776 static struct attribute *i2c_dev_attrs[] = {
778 /* modalias helps coldplug: modprobe $(cat .../modalias) */
779 &dev_attr_modalias.attr,
782 ATTRIBUTE_GROUPS(i2c_dev);
784 struct bus_type i2c_bus_type = {
786 .match = i2c_device_match,
787 .probe = i2c_device_probe,
788 .remove = i2c_device_remove,
789 .shutdown = i2c_device_shutdown,
791 EXPORT_SYMBOL_GPL(i2c_bus_type);
793 static struct device_type i2c_client_type = {
794 .groups = i2c_dev_groups,
795 .uevent = i2c_device_uevent,
796 .release = i2c_client_dev_release,
801 * i2c_verify_client - return parameter as i2c_client, or NULL
802 * @dev: device, probably from some driver model iterator
804 * When traversing the driver model tree, perhaps using driver model
805 * iterators like @device_for_each_child(), you can't assume very much
806 * about the nodes you find. Use this function to avoid oopses caused
807 * by wrongly treating some non-I2C device as an i2c_client.
809 struct i2c_client *i2c_verify_client(struct device *dev)
811 return (dev->type == &i2c_client_type)
815 EXPORT_SYMBOL(i2c_verify_client);
818 /* Return a unique address which takes the flags of the client into account */
819 static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
821 unsigned short addr = client->addr;
823 /* For some client flags, add an arbitrary offset to avoid collisions */
824 if (client->flags & I2C_CLIENT_TEN)
825 addr |= I2C_ADDR_OFFSET_TEN_BIT;
827 if (client->flags & I2C_CLIENT_SLAVE)
828 addr |= I2C_ADDR_OFFSET_SLAVE;
833 /* This is a permissive address validity check, I2C address map constraints
834 * are purposely not enforced, except for the general call address. */
835 static int i2c_check_addr_validity(unsigned addr, unsigned short flags)
837 if (flags & I2C_CLIENT_TEN) {
838 /* 10-bit address, all values are valid */
842 /* 7-bit address, reject the general call address */
843 if (addr == 0x00 || addr > 0x7f)
849 /* And this is a strict address validity check, used when probing. If a
850 * device uses a reserved address, then it shouldn't be probed. 7-bit
851 * addressing is assumed, 10-bit address devices are rare and should be
852 * explicitly enumerated. */
853 static int i2c_check_7bit_addr_validity_strict(unsigned short addr)
856 * Reserved addresses per I2C specification:
857 * 0x00 General call address / START byte
859 * 0x02 Reserved for different bus format
860 * 0x03 Reserved for future purposes
861 * 0x04-0x07 Hs-mode master code
862 * 0x78-0x7b 10-bit slave addressing
863 * 0x7c-0x7f Reserved for future purposes
865 if (addr < 0x08 || addr > 0x77)
870 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
872 struct i2c_client *client = i2c_verify_client(dev);
873 int addr = *(int *)addrp;
875 if (client && i2c_encode_flags_to_addr(client) == addr)
880 /* walk up mux tree */
881 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
883 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
886 result = device_for_each_child(&adapter->dev, &addr,
887 __i2c_check_addr_busy);
889 if (!result && parent)
890 result = i2c_check_mux_parents(parent, addr);
895 /* recurse down mux tree */
896 static int i2c_check_mux_children(struct device *dev, void *addrp)
900 if (dev->type == &i2c_adapter_type)
901 result = device_for_each_child(dev, addrp,
902 i2c_check_mux_children);
904 result = __i2c_check_addr_busy(dev, addrp);
909 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
911 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
915 result = i2c_check_mux_parents(parent, addr);
918 result = device_for_each_child(&adapter->dev, &addr,
919 i2c_check_mux_children);
925 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
926 * @adapter: Target I2C bus segment
928 void i2c_lock_adapter(struct i2c_adapter *adapter)
930 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
933 i2c_lock_adapter(parent);
935 rt_mutex_lock(&adapter->bus_lock);
937 EXPORT_SYMBOL_GPL(i2c_lock_adapter);
940 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
941 * @adapter: Target I2C bus segment
943 static int i2c_trylock_adapter(struct i2c_adapter *adapter)
945 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
948 return i2c_trylock_adapter(parent);
950 return rt_mutex_trylock(&adapter->bus_lock);
954 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
955 * @adapter: Target I2C bus segment
957 void i2c_unlock_adapter(struct i2c_adapter *adapter)
959 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
962 i2c_unlock_adapter(parent);
964 rt_mutex_unlock(&adapter->bus_lock);
966 EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
968 static void i2c_dev_set_name(struct i2c_adapter *adap,
969 struct i2c_client *client)
971 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
974 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
978 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
979 i2c_encode_flags_to_addr(client));
983 * i2c_new_device - instantiate an i2c device
984 * @adap: the adapter managing the device
985 * @info: describes one I2C device; bus_num is ignored
988 * Create an i2c device. Binding is handled through driver model
989 * probe()/remove() methods. A driver may be bound to this device when we
990 * return from this function, or any later moment (e.g. maybe hotplugging will
991 * load the driver module). This call is not appropriate for use by mainboard
992 * initialization logic, which usually runs during an arch_initcall() long
993 * before any i2c_adapter could exist.
995 * This returns the new i2c client, which may be saved for later use with
996 * i2c_unregister_device(); or NULL to indicate an error.
999 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1001 struct i2c_client *client;
1004 client = kzalloc(sizeof *client, GFP_KERNEL);
1008 client->adapter = adap;
1010 client->dev.platform_data = info->platform_data;
1013 client->dev.archdata = *info->archdata;
1015 client->flags = info->flags;
1016 client->addr = info->addr;
1017 client->irq = info->irq;
1019 strlcpy(client->name, info->type, sizeof(client->name));
1021 status = i2c_check_addr_validity(client->addr, client->flags);
1023 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1024 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1025 goto out_err_silent;
1028 /* Check for address business */
1029 status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
1033 client->dev.parent = &client->adapter->dev;
1034 client->dev.bus = &i2c_bus_type;
1035 client->dev.type = &i2c_client_type;
1036 client->dev.of_node = info->of_node;
1037 client->dev.fwnode = info->fwnode;
1039 i2c_dev_set_name(adap, client);
1040 status = device_register(&client->dev);
1044 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1045 client->name, dev_name(&client->dev));
1050 dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
1051 "(%d)\n", client->name, client->addr, status);
1056 EXPORT_SYMBOL_GPL(i2c_new_device);
1060 * i2c_unregister_device - reverse effect of i2c_new_device()
1061 * @client: value returned from i2c_new_device()
1062 * Context: can sleep
1064 void i2c_unregister_device(struct i2c_client *client)
1066 if (client->dev.of_node)
1067 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
1068 device_unregister(&client->dev);
1070 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1073 static const struct i2c_device_id dummy_id[] = {
1078 static int dummy_probe(struct i2c_client *client,
1079 const struct i2c_device_id *id)
1084 static int dummy_remove(struct i2c_client *client)
1089 static struct i2c_driver dummy_driver = {
1090 .driver.name = "dummy",
1091 .probe = dummy_probe,
1092 .remove = dummy_remove,
1093 .id_table = dummy_id,
1097 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1098 * @adapter: the adapter managing the device
1099 * @address: seven bit address to be used
1100 * Context: can sleep
1102 * This returns an I2C client bound to the "dummy" driver, intended for use
1103 * with devices that consume multiple addresses. Examples of such chips
1104 * include various EEPROMS (like 24c04 and 24c08 models).
1106 * These dummy devices have two main uses. First, most I2C and SMBus calls
1107 * except i2c_transfer() need a client handle; the dummy will be that handle.
1108 * And second, this prevents the specified address from being bound to a
1111 * This returns the new i2c client, which should be saved for later use with
1112 * i2c_unregister_device(); or NULL to indicate an error.
1114 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1116 struct i2c_board_info info = {
1117 I2C_BOARD_INFO("dummy", address),
1120 return i2c_new_device(adapter, &info);
1122 EXPORT_SYMBOL_GPL(i2c_new_dummy);
1124 /* ------------------------------------------------------------------------- */
1126 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1128 static void i2c_adapter_dev_release(struct device *dev)
1130 struct i2c_adapter *adap = to_i2c_adapter(dev);
1131 complete(&adap->dev_released);
1135 * This function is only needed for mutex_lock_nested, so it is never
1136 * called unless locking correctness checking is enabled. Thus we
1137 * make it inline to avoid a compiler warning. That's what gcc ends up
1140 static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1142 unsigned int depth = 0;
1144 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1151 * Let users instantiate I2C devices through sysfs. This can be used when
1152 * platform initialization code doesn't contain the proper data for
1153 * whatever reason. Also useful for drivers that do device detection and
1154 * detection fails, either because the device uses an unexpected address,
1155 * or this is a compatible device with different ID register values.
1157 * Parameter checking may look overzealous, but we really don't want
1158 * the user to provide incorrect parameters.
1161 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1162 const char *buf, size_t count)
1164 struct i2c_adapter *adap = to_i2c_adapter(dev);
1165 struct i2c_board_info info;
1166 struct i2c_client *client;
1170 memset(&info, 0, sizeof(struct i2c_board_info));
1172 blank = strchr(buf, ' ');
1174 dev_err(dev, "%s: Missing parameters\n", "new_device");
1177 if (blank - buf > I2C_NAME_SIZE - 1) {
1178 dev_err(dev, "%s: Invalid device name\n", "new_device");
1181 memcpy(info.type, buf, blank - buf);
1183 /* Parse remaining parameters, reject extra parameters */
1184 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1186 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1189 if (res > 1 && end != '\n') {
1190 dev_err(dev, "%s: Extra parameters\n", "new_device");
1194 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1195 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1196 info.flags |= I2C_CLIENT_TEN;
1199 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1200 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1201 info.flags |= I2C_CLIENT_SLAVE;
1204 client = i2c_new_device(adap, &info);
1208 /* Keep track of the added device */
1209 mutex_lock(&adap->userspace_clients_lock);
1210 list_add_tail(&client->detected, &adap->userspace_clients);
1211 mutex_unlock(&adap->userspace_clients_lock);
1212 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1213 info.type, info.addr);
1217 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1220 * And of course let the users delete the devices they instantiated, if
1221 * they got it wrong. This interface can only be used to delete devices
1222 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1223 * don't delete devices to which some kernel code still has references.
1225 * Parameter checking may look overzealous, but we really don't want
1226 * the user to delete the wrong device.
1229 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1230 const char *buf, size_t count)
1232 struct i2c_adapter *adap = to_i2c_adapter(dev);
1233 struct i2c_client *client, *next;
1234 unsigned short addr;
1238 /* Parse parameters, reject extra parameters */
1239 res = sscanf(buf, "%hi%c", &addr, &end);
1241 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1244 if (res > 1 && end != '\n') {
1245 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1249 /* Make sure the device was added through sysfs */
1251 mutex_lock_nested(&adap->userspace_clients_lock,
1252 i2c_adapter_depth(adap));
1253 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1255 if (i2c_encode_flags_to_addr(client) == addr) {
1256 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1257 "delete_device", client->name, client->addr);
1259 list_del(&client->detected);
1260 i2c_unregister_device(client);
1265 mutex_unlock(&adap->userspace_clients_lock);
1268 dev_err(dev, "%s: Can't find device in list\n",
1272 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1273 i2c_sysfs_delete_device);
1275 static struct attribute *i2c_adapter_attrs[] = {
1276 &dev_attr_name.attr,
1277 &dev_attr_new_device.attr,
1278 &dev_attr_delete_device.attr,
1281 ATTRIBUTE_GROUPS(i2c_adapter);
1283 struct device_type i2c_adapter_type = {
1284 .groups = i2c_adapter_groups,
1285 .release = i2c_adapter_dev_release,
1287 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1290 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1291 * @dev: device, probably from some driver model iterator
1293 * When traversing the driver model tree, perhaps using driver model
1294 * iterators like @device_for_each_child(), you can't assume very much
1295 * about the nodes you find. Use this function to avoid oopses caused
1296 * by wrongly treating some non-I2C device as an i2c_adapter.
1298 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1300 return (dev->type == &i2c_adapter_type)
1301 ? to_i2c_adapter(dev)
1304 EXPORT_SYMBOL(i2c_verify_adapter);
1306 #ifdef CONFIG_I2C_COMPAT
1307 static struct class_compat *i2c_adapter_compat_class;
1310 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1312 struct i2c_devinfo *devinfo;
1314 down_read(&__i2c_board_lock);
1315 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1316 if (devinfo->busnum == adapter->nr
1317 && !i2c_new_device(adapter,
1318 &devinfo->board_info))
1319 dev_err(&adapter->dev,
1320 "Can't create device at 0x%02x\n",
1321 devinfo->board_info.addr);
1323 up_read(&__i2c_board_lock);
1326 /* OF support code */
1328 #if IS_ENABLED(CONFIG_OF)
1329 static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1330 struct device_node *node)
1332 struct i2c_client *result;
1333 struct i2c_board_info info = {};
1334 struct dev_archdata dev_ad = {};
1335 const __be32 *addr_be;
1339 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1341 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1342 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1344 return ERR_PTR(-EINVAL);
1347 addr_be = of_get_property(node, "reg", &len);
1348 if (!addr_be || (len < sizeof(*addr_be))) {
1349 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1351 return ERR_PTR(-EINVAL);
1354 addr = be32_to_cpup(addr_be);
1355 if (addr & I2C_TEN_BIT_ADDRESS) {
1356 addr &= ~I2C_TEN_BIT_ADDRESS;
1357 info.flags |= I2C_CLIENT_TEN;
1360 if (addr & I2C_OWN_SLAVE_ADDRESS) {
1361 addr &= ~I2C_OWN_SLAVE_ADDRESS;
1362 info.flags |= I2C_CLIENT_SLAVE;
1365 if (i2c_check_addr_validity(addr, info.flags)) {
1366 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1367 info.addr, node->full_name);
1368 return ERR_PTR(-EINVAL);
1372 info.of_node = of_node_get(node);
1373 info.archdata = &dev_ad;
1375 if (of_get_property(node, "wakeup-source", NULL))
1376 info.flags |= I2C_CLIENT_WAKE;
1378 result = i2c_new_device(adap, &info);
1379 if (result == NULL) {
1380 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1383 return ERR_PTR(-EINVAL);
1388 static void of_i2c_register_devices(struct i2c_adapter *adap)
1390 struct device_node *node;
1392 /* Only register child devices if the adapter has a node pointer set */
1393 if (!adap->dev.of_node)
1396 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1398 for_each_available_child_of_node(adap->dev.of_node, node) {
1399 if (of_node_test_and_set_flag(node, OF_POPULATED))
1401 of_i2c_register_device(adap, node);
1405 static int of_dev_node_match(struct device *dev, void *data)
1407 return dev->of_node == data;
1410 /* must call put_device() when done with returned i2c_client device */
1411 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1414 struct i2c_client *client;
1416 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1420 client = i2c_verify_client(dev);
1426 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1428 /* must call put_device() when done with returned i2c_adapter device */
1429 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1432 struct i2c_adapter *adapter;
1434 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1438 adapter = i2c_verify_adapter(dev);
1444 EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1446 /* must call i2c_put_adapter() when done with returned i2c_adapter device */
1447 struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1449 struct i2c_adapter *adapter;
1451 adapter = of_find_i2c_adapter_by_node(node);
1455 if (!try_module_get(adapter->owner)) {
1456 put_device(&adapter->dev);
1462 EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1464 static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1465 #endif /* CONFIG_OF */
1467 static int i2c_do_add_adapter(struct i2c_driver *driver,
1468 struct i2c_adapter *adap)
1470 /* Detect supported devices on that bus, and instantiate them */
1471 i2c_detect(adap, driver);
1473 /* Let legacy drivers scan this bus for matching devices */
1474 if (driver->attach_adapter) {
1475 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1476 driver->driver.name);
1477 dev_warn(&adap->dev, "Please use another way to instantiate "
1478 "your i2c_client\n");
1479 /* We ignore the return code; if it fails, too bad */
1480 driver->attach_adapter(adap);
1485 static int __process_new_adapter(struct device_driver *d, void *data)
1487 return i2c_do_add_adapter(to_i2c_driver(d), data);
1490 static int i2c_register_adapter(struct i2c_adapter *adap)
1494 /* Can't register until after driver model init */
1495 if (unlikely(WARN_ON(!i2c_bus_type.p))) {
1501 if (unlikely(adap->name[0] == '\0')) {
1502 pr_err("i2c-core: Attempt to register an adapter with "
1506 if (unlikely(!adap->algo)) {
1507 pr_err("i2c-core: Attempt to register adapter '%s' with "
1508 "no algo!\n", adap->name);
1512 rt_mutex_init(&adap->bus_lock);
1513 mutex_init(&adap->userspace_clients_lock);
1514 INIT_LIST_HEAD(&adap->userspace_clients);
1516 /* Set default timeout to 1 second if not already set */
1517 if (adap->timeout == 0)
1520 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1521 adap->dev.bus = &i2c_bus_type;
1522 adap->dev.type = &i2c_adapter_type;
1523 res = device_register(&adap->dev);
1527 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1529 pm_runtime_no_callbacks(&adap->dev);
1531 #ifdef CONFIG_I2C_COMPAT
1532 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1535 dev_warn(&adap->dev,
1536 "Failed to create compatibility class link\n");
1539 /* bus recovery specific initialization */
1540 if (adap->bus_recovery_info) {
1541 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
1543 if (!bri->recover_bus) {
1544 dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
1545 adap->bus_recovery_info = NULL;
1549 /* Generic GPIO recovery */
1550 if (bri->recover_bus == i2c_generic_gpio_recovery) {
1551 if (!gpio_is_valid(bri->scl_gpio)) {
1552 dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
1553 adap->bus_recovery_info = NULL;
1557 if (gpio_is_valid(bri->sda_gpio))
1558 bri->get_sda = get_sda_gpio_value;
1560 bri->get_sda = NULL;
1562 bri->get_scl = get_scl_gpio_value;
1563 bri->set_scl = set_scl_gpio_value;
1564 } else if (!bri->set_scl || !bri->get_scl) {
1565 /* Generic SCL recovery */
1566 dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
1567 adap->bus_recovery_info = NULL;
1572 /* create pre-declared device nodes */
1573 of_i2c_register_devices(adap);
1574 acpi_i2c_register_devices(adap);
1575 acpi_i2c_install_space_handler(adap);
1577 if (adap->nr < __i2c_first_dynamic_bus_num)
1578 i2c_scan_static_board_info(adap);
1580 /* Notify drivers */
1581 mutex_lock(&core_lock);
1582 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1583 mutex_unlock(&core_lock);
1588 mutex_lock(&core_lock);
1589 idr_remove(&i2c_adapter_idr, adap->nr);
1590 mutex_unlock(&core_lock);
1595 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1596 * @adap: the adapter to register (with adap->nr initialized)
1597 * Context: can sleep
1599 * See i2c_add_numbered_adapter() for details.
1601 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1605 mutex_lock(&core_lock);
1606 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1,
1608 mutex_unlock(&core_lock);
1610 return id == -ENOSPC ? -EBUSY : id;
1612 return i2c_register_adapter(adap);
1616 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1617 * @adapter: the adapter to add
1618 * Context: can sleep
1620 * This routine is used to declare an I2C adapter when its bus number
1621 * doesn't matter or when its bus number is specified by an dt alias.
1622 * Examples of bases when the bus number doesn't matter: I2C adapters
1623 * dynamically added by USB links or PCI plugin cards.
1625 * When this returns zero, a new bus number was allocated and stored
1626 * in adap->nr, and the specified adapter became available for clients.
1627 * Otherwise, a negative errno value is returned.
1629 int i2c_add_adapter(struct i2c_adapter *adapter)
1631 struct device *dev = &adapter->dev;
1635 id = of_alias_get_id(dev->of_node, "i2c");
1638 return __i2c_add_numbered_adapter(adapter);
1642 mutex_lock(&core_lock);
1643 id = idr_alloc(&i2c_adapter_idr, adapter,
1644 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1645 mutex_unlock(&core_lock);
1651 return i2c_register_adapter(adapter);
1653 EXPORT_SYMBOL(i2c_add_adapter);
1656 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1657 * @adap: the adapter to register (with adap->nr initialized)
1658 * Context: can sleep
1660 * This routine is used to declare an I2C adapter when its bus number
1661 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1662 * or otherwise built in to the system's mainboard, and where i2c_board_info
1663 * is used to properly configure I2C devices.
1665 * If the requested bus number is set to -1, then this function will behave
1666 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1668 * If no devices have pre-been declared for this bus, then be sure to
1669 * register the adapter before any dynamically allocated ones. Otherwise
1670 * the required bus ID may not be available.
1672 * When this returns zero, the specified adapter became available for
1673 * clients using the bus number provided in adap->nr. Also, the table
1674 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1675 * and the appropriate driver model device nodes are created. Otherwise, a
1676 * negative errno value is returned.
1678 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1680 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1681 return i2c_add_adapter(adap);
1683 return __i2c_add_numbered_adapter(adap);
1685 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1687 static void i2c_do_del_adapter(struct i2c_driver *driver,
1688 struct i2c_adapter *adapter)
1690 struct i2c_client *client, *_n;
1692 /* Remove the devices we created ourselves as the result of hardware
1693 * probing (using a driver's detect method) */
1694 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1695 if (client->adapter == adapter) {
1696 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1697 client->name, client->addr);
1698 list_del(&client->detected);
1699 i2c_unregister_device(client);
1704 static int __unregister_client(struct device *dev, void *dummy)
1706 struct i2c_client *client = i2c_verify_client(dev);
1707 if (client && strcmp(client->name, "dummy"))
1708 i2c_unregister_device(client);
1712 static int __unregister_dummy(struct device *dev, void *dummy)
1714 struct i2c_client *client = i2c_verify_client(dev);
1716 i2c_unregister_device(client);
1720 static int __process_removed_adapter(struct device_driver *d, void *data)
1722 i2c_do_del_adapter(to_i2c_driver(d), data);
1727 * i2c_del_adapter - unregister I2C adapter
1728 * @adap: the adapter being unregistered
1729 * Context: can sleep
1731 * This unregisters an I2C adapter which was previously registered
1732 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1734 void i2c_del_adapter(struct i2c_adapter *adap)
1736 struct i2c_adapter *found;
1737 struct i2c_client *client, *next;
1739 /* First make sure that this adapter was ever added */
1740 mutex_lock(&core_lock);
1741 found = idr_find(&i2c_adapter_idr, adap->nr);
1742 mutex_unlock(&core_lock);
1743 if (found != adap) {
1744 pr_debug("i2c-core: attempting to delete unregistered "
1745 "adapter [%s]\n", adap->name);
1749 acpi_i2c_remove_space_handler(adap);
1750 /* Tell drivers about this removal */
1751 mutex_lock(&core_lock);
1752 bus_for_each_drv(&i2c_bus_type, NULL, adap,
1753 __process_removed_adapter);
1754 mutex_unlock(&core_lock);
1756 /* Remove devices instantiated from sysfs */
1757 mutex_lock_nested(&adap->userspace_clients_lock,
1758 i2c_adapter_depth(adap));
1759 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1761 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1763 list_del(&client->detected);
1764 i2c_unregister_device(client);
1766 mutex_unlock(&adap->userspace_clients_lock);
1768 /* Detach any active clients. This can't fail, thus we do not
1769 * check the returned value. This is a two-pass process, because
1770 * we can't remove the dummy devices during the first pass: they
1771 * could have been instantiated by real devices wishing to clean
1772 * them up properly, so we give them a chance to do that first. */
1773 device_for_each_child(&adap->dev, NULL, __unregister_client);
1774 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1776 #ifdef CONFIG_I2C_COMPAT
1777 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1781 /* device name is gone after device_unregister */
1782 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1784 /* wait until all references to the device are gone
1786 * FIXME: This is old code and should ideally be replaced by an
1787 * alternative which results in decoupling the lifetime of the struct
1788 * device from the i2c_adapter, like spi or netdev do. Any solution
1789 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
1791 init_completion(&adap->dev_released);
1792 device_unregister(&adap->dev);
1793 wait_for_completion(&adap->dev_released);
1796 mutex_lock(&core_lock);
1797 idr_remove(&i2c_adapter_idr, adap->nr);
1798 mutex_unlock(&core_lock);
1800 /* Clear the device structure in case this adapter is ever going to be
1802 memset(&adap->dev, 0, sizeof(adap->dev));
1804 EXPORT_SYMBOL(i2c_del_adapter);
1806 /* ------------------------------------------------------------------------- */
1808 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1812 mutex_lock(&core_lock);
1813 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1814 mutex_unlock(&core_lock);
1818 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1820 static int __process_new_driver(struct device *dev, void *data)
1822 if (dev->type != &i2c_adapter_type)
1824 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1828 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1829 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1832 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1836 /* Can't register until after driver model init */
1837 if (unlikely(WARN_ON(!i2c_bus_type.p)))
1840 /* add the driver to the list of i2c drivers in the driver core */
1841 driver->driver.owner = owner;
1842 driver->driver.bus = &i2c_bus_type;
1844 /* When registration returns, the driver core
1845 * will have called probe() for all matching-but-unbound devices.
1847 res = driver_register(&driver->driver);
1851 pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
1853 INIT_LIST_HEAD(&driver->clients);
1854 /* Walk the adapters that are already present */
1855 i2c_for_each_dev(driver, __process_new_driver);
1859 EXPORT_SYMBOL(i2c_register_driver);
1861 static int __process_removed_driver(struct device *dev, void *data)
1863 if (dev->type == &i2c_adapter_type)
1864 i2c_do_del_adapter(data, to_i2c_adapter(dev));
1869 * i2c_del_driver - unregister I2C driver
1870 * @driver: the driver being unregistered
1871 * Context: can sleep
1873 void i2c_del_driver(struct i2c_driver *driver)
1875 i2c_for_each_dev(driver, __process_removed_driver);
1877 driver_unregister(&driver->driver);
1878 pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
1880 EXPORT_SYMBOL(i2c_del_driver);
1882 /* ------------------------------------------------------------------------- */
1885 * i2c_use_client - increments the reference count of the i2c client structure
1886 * @client: the client being referenced
1888 * Each live reference to a client should be refcounted. The driver model does
1889 * that automatically as part of driver binding, so that most drivers don't
1890 * need to do this explicitly: they hold a reference until they're unbound
1893 * A pointer to the client with the incremented reference counter is returned.
1895 struct i2c_client *i2c_use_client(struct i2c_client *client)
1897 if (client && get_device(&client->dev))
1901 EXPORT_SYMBOL(i2c_use_client);
1904 * i2c_release_client - release a use of the i2c client structure
1905 * @client: the client being no longer referenced
1907 * Must be called when a user of a client is finished with it.
1909 void i2c_release_client(struct i2c_client *client)
1912 put_device(&client->dev);
1914 EXPORT_SYMBOL(i2c_release_client);
1916 struct i2c_cmd_arg {
1921 static int i2c_cmd(struct device *dev, void *_arg)
1923 struct i2c_client *client = i2c_verify_client(dev);
1924 struct i2c_cmd_arg *arg = _arg;
1925 struct i2c_driver *driver;
1927 if (!client || !client->dev.driver)
1930 driver = to_i2c_driver(client->dev.driver);
1931 if (driver->command)
1932 driver->command(client, arg->cmd, arg->arg);
1936 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1938 struct i2c_cmd_arg cmd_arg;
1942 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1944 EXPORT_SYMBOL(i2c_clients_command);
1946 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
1947 static int of_i2c_notify(struct notifier_block *nb, unsigned long action,
1950 struct of_reconfig_data *rd = arg;
1951 struct i2c_adapter *adap;
1952 struct i2c_client *client;
1954 switch (of_reconfig_get_state_change(action, rd)) {
1955 case OF_RECONFIG_CHANGE_ADD:
1956 adap = of_find_i2c_adapter_by_node(rd->dn->parent);
1958 return NOTIFY_OK; /* not for us */
1960 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
1961 put_device(&adap->dev);
1965 client = of_i2c_register_device(adap, rd->dn);
1966 put_device(&adap->dev);
1968 if (IS_ERR(client)) {
1969 pr_err("%s: failed to create for '%s'\n",
1970 __func__, rd->dn->full_name);
1971 return notifier_from_errno(PTR_ERR(client));
1974 case OF_RECONFIG_CHANGE_REMOVE:
1975 /* already depopulated? */
1976 if (!of_node_check_flag(rd->dn, OF_POPULATED))
1979 /* find our device by node */
1980 client = of_find_i2c_device_by_node(rd->dn);
1982 return NOTIFY_OK; /* no? not meant for us */
1984 /* unregister takes one ref away */
1985 i2c_unregister_device(client);
1987 /* and put the reference of the find */
1988 put_device(&client->dev);
1994 static struct notifier_block i2c_of_notifier = {
1995 .notifier_call = of_i2c_notify,
1998 extern struct notifier_block i2c_of_notifier;
1999 #endif /* CONFIG_OF_DYNAMIC */
2001 static int __init i2c_init(void)
2005 retval = of_alias_get_highest_id("i2c");
2007 down_write(&__i2c_board_lock);
2008 if (retval >= __i2c_first_dynamic_bus_num)
2009 __i2c_first_dynamic_bus_num = retval + 1;
2010 up_write(&__i2c_board_lock);
2012 retval = bus_register(&i2c_bus_type);
2015 #ifdef CONFIG_I2C_COMPAT
2016 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
2017 if (!i2c_adapter_compat_class) {
2022 retval = i2c_add_driver(&dummy_driver);
2026 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2027 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
2032 #ifdef CONFIG_I2C_COMPAT
2033 class_compat_unregister(i2c_adapter_compat_class);
2036 bus_unregister(&i2c_bus_type);
2040 static void __exit i2c_exit(void)
2042 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2043 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
2044 i2c_del_driver(&dummy_driver);
2045 #ifdef CONFIG_I2C_COMPAT
2046 class_compat_unregister(i2c_adapter_compat_class);
2048 bus_unregister(&i2c_bus_type);
2049 tracepoint_synchronize_unregister();
2052 /* We must initialize early, because some subsystems register i2c drivers
2053 * in subsys_initcall() code, but are linked (and initialized) before i2c.
2055 postcore_initcall(i2c_init);
2056 module_exit(i2c_exit);
2058 /* ----------------------------------------------------
2059 * the functional interface to the i2c busses.
2060 * ----------------------------------------------------
2063 /* Check if val is exceeding the quirk IFF quirk is non 0 */
2064 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2066 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2068 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2069 err_msg, msg->addr, msg->len,
2070 msg->flags & I2C_M_RD ? "read" : "write");
2074 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2076 const struct i2c_adapter_quirks *q = adap->quirks;
2077 int max_num = q->max_num_msgs, i;
2078 bool do_len_check = true;
2080 if (q->flags & I2C_AQ_COMB) {
2083 /* special checks for combined messages */
2085 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2086 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2088 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2089 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2091 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2092 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2094 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2095 return i2c_quirk_error(adap, &msgs[0], "msg too long");
2097 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2098 return i2c_quirk_error(adap, &msgs[1], "msg too long");
2100 do_len_check = false;
2104 if (i2c_quirk_exceeded(num, max_num))
2105 return i2c_quirk_error(adap, &msgs[0], "too many messages");
2107 for (i = 0; i < num; i++) {
2108 u16 len = msgs[i].len;
2110 if (msgs[i].flags & I2C_M_RD) {
2111 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2112 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2114 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2115 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2123 * __i2c_transfer - unlocked flavor of i2c_transfer
2124 * @adap: Handle to I2C bus
2125 * @msgs: One or more messages to execute before STOP is issued to
2126 * terminate the operation; each message begins with a START.
2127 * @num: Number of messages to be executed.
2129 * Returns negative errno, else the number of messages executed.
2131 * Adapter lock must be held when calling this function. No debug logging
2132 * takes place. adap->algo->master_xfer existence isn't checked.
2134 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2136 unsigned long orig_jiffies;
2139 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2142 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2143 * enabled. This is an efficient way of keeping the for-loop from
2144 * being executed when not needed.
2146 if (static_key_false(&i2c_trace_msg)) {
2148 for (i = 0; i < num; i++)
2149 if (msgs[i].flags & I2C_M_RD)
2150 trace_i2c_read(adap, &msgs[i], i);
2152 trace_i2c_write(adap, &msgs[i], i);
2155 /* Retry automatically on arbitration loss */
2156 orig_jiffies = jiffies;
2157 for (ret = 0, try = 0; try <= adap->retries; try++) {
2158 ret = adap->algo->master_xfer(adap, msgs, num);
2161 if (time_after(jiffies, orig_jiffies + adap->timeout))
2165 if (static_key_false(&i2c_trace_msg)) {
2167 for (i = 0; i < ret; i++)
2168 if (msgs[i].flags & I2C_M_RD)
2169 trace_i2c_reply(adap, &msgs[i], i);
2170 trace_i2c_result(adap, i, ret);
2175 EXPORT_SYMBOL(__i2c_transfer);
2178 * i2c_transfer - execute a single or combined I2C message
2179 * @adap: Handle to I2C bus
2180 * @msgs: One or more messages to execute before STOP is issued to
2181 * terminate the operation; each message begins with a START.
2182 * @num: Number of messages to be executed.
2184 * Returns negative errno, else the number of messages executed.
2186 * Note that there is no requirement that each message be sent to
2187 * the same slave address, although that is the most common model.
2189 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2193 /* REVISIT the fault reporting model here is weak:
2195 * - When we get an error after receiving N bytes from a slave,
2196 * there is no way to report "N".
2198 * - When we get a NAK after transmitting N bytes to a slave,
2199 * there is no way to report "N" ... or to let the master
2200 * continue executing the rest of this combined message, if
2201 * that's the appropriate response.
2203 * - When for example "num" is two and we successfully complete
2204 * the first message but get an error part way through the
2205 * second, it's unclear whether that should be reported as
2206 * one (discarding status on the second message) or errno
2207 * (discarding status on the first one).
2210 if (adap->algo->master_xfer) {
2212 for (ret = 0; ret < num; ret++) {
2213 dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
2214 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
2215 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
2216 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2220 if (in_atomic() || irqs_disabled()) {
2221 ret = i2c_trylock_adapter(adap);
2223 /* I2C activity is ongoing. */
2226 i2c_lock_adapter(adap);
2229 ret = __i2c_transfer(adap, msgs, num);
2230 i2c_unlock_adapter(adap);
2234 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2238 EXPORT_SYMBOL(i2c_transfer);
2241 * i2c_master_send - issue a single I2C message in master transmit mode
2242 * @client: Handle to slave device
2243 * @buf: Data that will be written to the slave
2244 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2246 * Returns negative errno, or else the number of bytes written.
2248 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2251 struct i2c_adapter *adap = client->adapter;
2254 msg.addr = client->addr;
2255 msg.flags = client->flags & I2C_M_TEN;
2257 msg.buf = (char *)buf;
2259 ret = i2c_transfer(adap, &msg, 1);
2262 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2263 * transmitted, else error code.
2265 return (ret == 1) ? count : ret;
2267 EXPORT_SYMBOL(i2c_master_send);
2270 * i2c_master_recv - issue a single I2C message in master receive mode
2271 * @client: Handle to slave device
2272 * @buf: Where to store data read from slave
2273 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2275 * Returns negative errno, or else the number of bytes read.
2277 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2279 struct i2c_adapter *adap = client->adapter;
2283 msg.addr = client->addr;
2284 msg.flags = client->flags & I2C_M_TEN;
2285 msg.flags |= I2C_M_RD;
2289 ret = i2c_transfer(adap, &msg, 1);
2292 * If everything went ok (i.e. 1 msg received), return #bytes received,
2295 return (ret == 1) ? count : ret;
2297 EXPORT_SYMBOL(i2c_master_recv);
2299 /* ----------------------------------------------------
2300 * the i2c address scanning function
2301 * Will not work for 10-bit addresses!
2302 * ----------------------------------------------------
2306 * Legacy default probe function, mostly relevant for SMBus. The default
2307 * probe method is a quick write, but it is known to corrupt the 24RF08
2308 * EEPROMs due to a state machine bug, and could also irreversibly
2309 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2310 * we use a short byte read instead. Also, some bus drivers don't implement
2311 * quick write, so we fallback to a byte read in that case too.
2312 * On x86, there is another special case for FSC hardware monitoring chips,
2313 * which want regular byte reads (address 0x73.) Fortunately, these are the
2314 * only known chips using this I2C address on PC hardware.
2315 * Returns 1 if probe succeeded, 0 if not.
2317 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2320 union i2c_smbus_data dummy;
2323 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2324 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2325 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2326 I2C_SMBUS_BYTE_DATA, &dummy);
2329 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2330 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2331 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2332 I2C_SMBUS_QUICK, NULL);
2333 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2334 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2335 I2C_SMBUS_BYTE, &dummy);
2337 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2345 static int i2c_detect_address(struct i2c_client *temp_client,
2346 struct i2c_driver *driver)
2348 struct i2c_board_info info;
2349 struct i2c_adapter *adapter = temp_client->adapter;
2350 int addr = temp_client->addr;
2353 /* Make sure the address is valid */
2354 err = i2c_check_7bit_addr_validity_strict(addr);
2356 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2361 /* Skip if already in use (7 bit, no need to encode flags) */
2362 if (i2c_check_addr_busy(adapter, addr))
2365 /* Make sure there is something at this address */
2366 if (!i2c_default_probe(adapter, addr))
2369 /* Finally call the custom detection function */
2370 memset(&info, 0, sizeof(struct i2c_board_info));
2372 err = driver->detect(temp_client, &info);
2374 /* -ENODEV is returned if the detection fails. We catch it
2375 here as this isn't an error. */
2376 return err == -ENODEV ? 0 : err;
2379 /* Consistency check */
2380 if (info.type[0] == '\0') {
2381 dev_err(&adapter->dev, "%s detection function provided "
2382 "no name for 0x%x\n", driver->driver.name,
2385 struct i2c_client *client;
2387 /* Detection succeeded, instantiate the device */
2388 if (adapter->class & I2C_CLASS_DEPRECATED)
2389 dev_warn(&adapter->dev,
2390 "This adapter will soon drop class based instantiation of devices. "
2391 "Please make sure client 0x%02x gets instantiated by other means. "
2392 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2395 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2396 info.type, info.addr);
2397 client = i2c_new_device(adapter, &info);
2399 list_add_tail(&client->detected, &driver->clients);
2401 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2402 info.type, info.addr);
2407 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2409 const unsigned short *address_list;
2410 struct i2c_client *temp_client;
2412 int adap_id = i2c_adapter_id(adapter);
2414 address_list = driver->address_list;
2415 if (!driver->detect || !address_list)
2418 /* Warn that the adapter lost class based instantiation */
2419 if (adapter->class == I2C_CLASS_DEPRECATED) {
2420 dev_dbg(&adapter->dev,
2421 "This adapter dropped support for I2C classes and "
2422 "won't auto-detect %s devices anymore. If you need it, check "
2423 "'Documentation/i2c/instantiating-devices' for alternatives.\n",
2424 driver->driver.name);
2428 /* Stop here if the classes do not match */
2429 if (!(adapter->class & driver->class))
2432 /* Set up a temporary client to help detect callback */
2433 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2436 temp_client->adapter = adapter;
2438 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2439 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
2440 "addr 0x%02x\n", adap_id, address_list[i]);
2441 temp_client->addr = address_list[i];
2442 err = i2c_detect_address(temp_client, driver);
2451 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2453 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2454 I2C_SMBUS_QUICK, NULL) >= 0;
2456 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2459 i2c_new_probed_device(struct i2c_adapter *adap,
2460 struct i2c_board_info *info,
2461 unsigned short const *addr_list,
2462 int (*probe)(struct i2c_adapter *, unsigned short addr))
2467 probe = i2c_default_probe;
2469 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2470 /* Check address validity */
2471 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2472 dev_warn(&adap->dev, "Invalid 7-bit address "
2473 "0x%02x\n", addr_list[i]);
2477 /* Check address availability (7 bit, no need to encode flags) */
2478 if (i2c_check_addr_busy(adap, addr_list[i])) {
2479 dev_dbg(&adap->dev, "Address 0x%02x already in "
2480 "use, not probing\n", addr_list[i]);
2484 /* Test address responsiveness */
2485 if (probe(adap, addr_list[i]))
2489 if (addr_list[i] == I2C_CLIENT_END) {
2490 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2494 info->addr = addr_list[i];
2495 return i2c_new_device(adap, info);
2497 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2499 struct i2c_adapter *i2c_get_adapter(int nr)
2501 struct i2c_adapter *adapter;
2503 mutex_lock(&core_lock);
2504 adapter = idr_find(&i2c_adapter_idr, nr);
2508 if (try_module_get(adapter->owner))
2509 get_device(&adapter->dev);
2514 mutex_unlock(&core_lock);
2517 EXPORT_SYMBOL(i2c_get_adapter);
2519 void i2c_put_adapter(struct i2c_adapter *adap)
2524 put_device(&adap->dev);
2525 module_put(adap->owner);
2527 EXPORT_SYMBOL(i2c_put_adapter);
2529 /* The SMBus parts */
2531 #define POLY (0x1070U << 3)
2532 static u8 crc8(u16 data)
2536 for (i = 0; i < 8; i++) {
2541 return (u8)(data >> 8);
2544 /* Incremental CRC8 over count bytes in the array pointed to by p */
2545 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2549 for (i = 0; i < count; i++)
2550 crc = crc8((crc ^ p[i]) << 8);
2554 /* Assume a 7-bit address, which is reasonable for SMBus */
2555 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2557 /* The address will be sent first */
2558 u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
2559 pec = i2c_smbus_pec(pec, &addr, 1);
2561 /* The data buffer follows */
2562 return i2c_smbus_pec(pec, msg->buf, msg->len);
2565 /* Used for write only transactions */
2566 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2568 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2572 /* Return <0 on CRC error
2573 If there was a write before this read (most cases) we need to take the
2574 partial CRC from the write part into account.
2575 Note that this function does modify the message (we need to decrease the
2576 message length to hide the CRC byte from the caller). */
2577 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2579 u8 rpec = msg->buf[--msg->len];
2580 cpec = i2c_smbus_msg_pec(cpec, msg);
2583 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
2591 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2592 * @client: Handle to slave device
2594 * This executes the SMBus "receive byte" protocol, returning negative errno
2595 * else the byte received from the device.
2597 s32 i2c_smbus_read_byte(const struct i2c_client *client)
2599 union i2c_smbus_data data;
2602 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2604 I2C_SMBUS_BYTE, &data);
2605 return (status < 0) ? status : data.byte;
2607 EXPORT_SYMBOL(i2c_smbus_read_byte);
2610 * i2c_smbus_write_byte - SMBus "send byte" protocol
2611 * @client: Handle to slave device
2612 * @value: Byte to be sent
2614 * This executes the SMBus "send byte" protocol, returning negative errno
2615 * else zero on success.
2617 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2619 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2620 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2622 EXPORT_SYMBOL(i2c_smbus_write_byte);
2625 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2626 * @client: Handle to slave device
2627 * @command: Byte interpreted by slave
2629 * This executes the SMBus "read byte" protocol, returning negative errno
2630 * else a data byte received from the device.
2632 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2634 union i2c_smbus_data data;
2637 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2638 I2C_SMBUS_READ, command,
2639 I2C_SMBUS_BYTE_DATA, &data);
2640 return (status < 0) ? status : data.byte;
2642 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2645 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2646 * @client: Handle to slave device
2647 * @command: Byte interpreted by slave
2648 * @value: Byte being written
2650 * This executes the SMBus "write byte" protocol, returning negative errno
2651 * else zero on success.
2653 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
2656 union i2c_smbus_data data;
2658 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2659 I2C_SMBUS_WRITE, command,
2660 I2C_SMBUS_BYTE_DATA, &data);
2662 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
2665 * i2c_smbus_read_word_data - SMBus "read word" protocol
2666 * @client: Handle to slave device
2667 * @command: Byte interpreted by slave
2669 * This executes the SMBus "read word" protocol, returning negative errno
2670 * else a 16-bit unsigned "word" received from the device.
2672 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
2674 union i2c_smbus_data data;
2677 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2678 I2C_SMBUS_READ, command,
2679 I2C_SMBUS_WORD_DATA, &data);
2680 return (status < 0) ? status : data.word;
2682 EXPORT_SYMBOL(i2c_smbus_read_word_data);
2685 * i2c_smbus_write_word_data - SMBus "write word" protocol
2686 * @client: Handle to slave device
2687 * @command: Byte interpreted by slave
2688 * @value: 16-bit "word" being written
2690 * This executes the SMBus "write word" protocol, returning negative errno
2691 * else zero on success.
2693 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2696 union i2c_smbus_data data;
2698 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2699 I2C_SMBUS_WRITE, command,
2700 I2C_SMBUS_WORD_DATA, &data);
2702 EXPORT_SYMBOL(i2c_smbus_write_word_data);
2705 * i2c_smbus_read_block_data - SMBus "block read" protocol
2706 * @client: Handle to slave device
2707 * @command: Byte interpreted by slave
2708 * @values: Byte array into which data will be read; big enough to hold
2709 * the data returned by the slave. SMBus allows at most 32 bytes.
2711 * This executes the SMBus "block read" protocol, returning negative errno
2712 * else the number of data bytes in the slave's response.
2714 * Note that using this function requires that the client's adapter support
2715 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
2716 * support this; its emulation through I2C messaging relies on a specific
2717 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2719 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2722 union i2c_smbus_data data;
2725 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2726 I2C_SMBUS_READ, command,
2727 I2C_SMBUS_BLOCK_DATA, &data);
2731 memcpy(values, &data.block[1], data.block[0]);
2732 return data.block[0];
2734 EXPORT_SYMBOL(i2c_smbus_read_block_data);
2737 * i2c_smbus_write_block_data - SMBus "block write" protocol
2738 * @client: Handle to slave device
2739 * @command: Byte interpreted by slave
2740 * @length: Size of data block; SMBus allows at most 32 bytes
2741 * @values: Byte array which will be written.
2743 * This executes the SMBus "block write" protocol, returning negative errno
2744 * else zero on success.
2746 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2747 u8 length, const u8 *values)
2749 union i2c_smbus_data data;
2751 if (length > I2C_SMBUS_BLOCK_MAX)
2752 length = I2C_SMBUS_BLOCK_MAX;
2753 data.block[0] = length;
2754 memcpy(&data.block[1], values, length);
2755 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2756 I2C_SMBUS_WRITE, command,
2757 I2C_SMBUS_BLOCK_DATA, &data);
2759 EXPORT_SYMBOL(i2c_smbus_write_block_data);
2761 /* Returns the number of read bytes */
2762 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2763 u8 length, u8 *values)
2765 union i2c_smbus_data data;
2768 if (length > I2C_SMBUS_BLOCK_MAX)
2769 length = I2C_SMBUS_BLOCK_MAX;
2770 data.block[0] = length;
2771 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2772 I2C_SMBUS_READ, command,
2773 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2777 memcpy(values, &data.block[1], data.block[0]);
2778 return data.block[0];
2780 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2782 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2783 u8 length, const u8 *values)
2785 union i2c_smbus_data data;
2787 if (length > I2C_SMBUS_BLOCK_MAX)
2788 length = I2C_SMBUS_BLOCK_MAX;
2789 data.block[0] = length;
2790 memcpy(data.block + 1, values, length);
2791 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2792 I2C_SMBUS_WRITE, command,
2793 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2795 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2797 /* Simulate a SMBus command using the i2c protocol
2798 No checking of parameters is done! */
2799 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2800 unsigned short flags,
2801 char read_write, u8 command, int size,
2802 union i2c_smbus_data *data)
2804 /* So we need to generate a series of msgs. In the case of writing, we
2805 need to use only one message; when reading, we need two. We initialize
2806 most things with sane defaults, to keep the code below somewhat
2808 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2809 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2810 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2814 struct i2c_msg msg[2] = {
2822 .flags = flags | I2C_M_RD,
2828 msgbuf0[0] = command;
2830 case I2C_SMBUS_QUICK:
2832 /* Special case: The read/write field is used as data */
2833 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2837 case I2C_SMBUS_BYTE:
2838 if (read_write == I2C_SMBUS_READ) {
2839 /* Special case: only a read! */
2840 msg[0].flags = I2C_M_RD | flags;
2844 case I2C_SMBUS_BYTE_DATA:
2845 if (read_write == I2C_SMBUS_READ)
2849 msgbuf0[1] = data->byte;
2852 case I2C_SMBUS_WORD_DATA:
2853 if (read_write == I2C_SMBUS_READ)
2857 msgbuf0[1] = data->word & 0xff;
2858 msgbuf0[2] = data->word >> 8;
2861 case I2C_SMBUS_PROC_CALL:
2862 num = 2; /* Special case */
2863 read_write = I2C_SMBUS_READ;
2866 msgbuf0[1] = data->word & 0xff;
2867 msgbuf0[2] = data->word >> 8;
2869 case I2C_SMBUS_BLOCK_DATA:
2870 if (read_write == I2C_SMBUS_READ) {
2871 msg[1].flags |= I2C_M_RECV_LEN;
2872 msg[1].len = 1; /* block length will be added by
2873 the underlying bus driver */
2875 msg[0].len = data->block[0] + 2;
2876 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
2877 dev_err(&adapter->dev,
2878 "Invalid block write size %d\n",
2882 for (i = 1; i < msg[0].len; i++)
2883 msgbuf0[i] = data->block[i-1];
2886 case I2C_SMBUS_BLOCK_PROC_CALL:
2887 num = 2; /* Another special case */
2888 read_write = I2C_SMBUS_READ;
2889 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
2890 dev_err(&adapter->dev,
2891 "Invalid block write size %d\n",
2895 msg[0].len = data->block[0] + 2;
2896 for (i = 1; i < msg[0].len; i++)
2897 msgbuf0[i] = data->block[i-1];
2898 msg[1].flags |= I2C_M_RECV_LEN;
2899 msg[1].len = 1; /* block length will be added by
2900 the underlying bus driver */
2902 case I2C_SMBUS_I2C_BLOCK_DATA:
2903 if (read_write == I2C_SMBUS_READ) {
2904 msg[1].len = data->block[0];
2906 msg[0].len = data->block[0] + 1;
2907 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
2908 dev_err(&adapter->dev,
2909 "Invalid block write size %d\n",
2913 for (i = 1; i <= data->block[0]; i++)
2914 msgbuf0[i] = data->block[i];
2918 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
2922 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
2923 && size != I2C_SMBUS_I2C_BLOCK_DATA);
2925 /* Compute PEC if first message is a write */
2926 if (!(msg[0].flags & I2C_M_RD)) {
2927 if (num == 1) /* Write only */
2928 i2c_smbus_add_pec(&msg[0]);
2929 else /* Write followed by read */
2930 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
2932 /* Ask for PEC if last message is a read */
2933 if (msg[num-1].flags & I2C_M_RD)
2937 status = i2c_transfer(adapter, msg, num);
2941 /* Check PEC if last message is a read */
2942 if (i && (msg[num-1].flags & I2C_M_RD)) {
2943 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
2948 if (read_write == I2C_SMBUS_READ)
2950 case I2C_SMBUS_BYTE:
2951 data->byte = msgbuf0[0];
2953 case I2C_SMBUS_BYTE_DATA:
2954 data->byte = msgbuf1[0];
2956 case I2C_SMBUS_WORD_DATA:
2957 case I2C_SMBUS_PROC_CALL:
2958 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
2960 case I2C_SMBUS_I2C_BLOCK_DATA:
2961 for (i = 0; i < data->block[0]; i++)
2962 data->block[i+1] = msgbuf1[i];
2964 case I2C_SMBUS_BLOCK_DATA:
2965 case I2C_SMBUS_BLOCK_PROC_CALL:
2966 for (i = 0; i < msgbuf1[0] + 1; i++)
2967 data->block[i] = msgbuf1[i];
2974 * i2c_smbus_xfer - execute SMBus protocol operations
2975 * @adapter: Handle to I2C bus
2976 * @addr: Address of SMBus slave on that bus
2977 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
2978 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
2979 * @command: Byte interpreted by slave, for protocols which use such bytes
2980 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
2981 * @data: Data to be read or written
2983 * This executes an SMBus protocol operation, and returns a negative
2984 * errno code else zero on success.
2986 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
2987 char read_write, u8 command, int protocol,
2988 union i2c_smbus_data *data)
2990 unsigned long orig_jiffies;
2994 /* If enabled, the following two tracepoints are conditional on
2995 * read_write and protocol.
2997 trace_smbus_write(adapter, addr, flags, read_write,
2998 command, protocol, data);
2999 trace_smbus_read(adapter, addr, flags, read_write,
3002 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
3004 if (adapter->algo->smbus_xfer) {
3005 i2c_lock_adapter(adapter);
3007 /* Retry automatically on arbitration loss */
3008 orig_jiffies = jiffies;
3009 for (res = 0, try = 0; try <= adapter->retries; try++) {
3010 res = adapter->algo->smbus_xfer(adapter, addr, flags,
3011 read_write, command,
3015 if (time_after(jiffies,
3016 orig_jiffies + adapter->timeout))
3019 i2c_unlock_adapter(adapter);
3021 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
3024 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
3025 * implement native support for the SMBus operation.
3029 res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
3030 command, protocol, data);
3033 /* If enabled, the reply tracepoint is conditional on read_write. */
3034 trace_smbus_reply(adapter, addr, flags, read_write,
3035 command, protocol, data);
3036 trace_smbus_result(adapter, addr, flags, read_write,
3037 command, protocol, res);
3041 EXPORT_SYMBOL(i2c_smbus_xfer);
3044 * i2c_smbus_read_i2c_block_data_or_emulated - read block or emulate
3045 * @client: Handle to slave device
3046 * @command: Byte interpreted by slave
3047 * @length: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
3048 * @values: Byte array into which data will be read; big enough to hold
3049 * the data returned by the slave. SMBus allows at most
3050 * I2C_SMBUS_BLOCK_MAX bytes.
3052 * This executes the SMBus "block read" protocol if supported by the adapter.
3053 * If block read is not supported, it emulates it using either word or byte
3054 * read protocols depending on availability.
3056 * The addresses of the I2C slave device that are accessed with this function
3057 * must be mapped to a linear region, so that a block read will have the same
3058 * effect as a byte read. Before using this function you must double-check
3059 * if the I2C slave does support exchanging a block transfer with a byte
3062 s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client,
3063 u8 command, u8 length, u8 *values)
3068 if (length > I2C_SMBUS_BLOCK_MAX)
3069 length = I2C_SMBUS_BLOCK_MAX;
3071 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
3072 return i2c_smbus_read_i2c_block_data(client, command, length, values);
3074 if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA))
3077 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) {
3078 while ((i + 2) <= length) {
3079 status = i2c_smbus_read_word_data(client, command + i);
3082 values[i] = status & 0xff;
3083 values[i + 1] = status >> 8;
3088 while (i < length) {
3089 status = i2c_smbus_read_byte_data(client, command + i);
3098 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data_or_emulated);
3100 #if IS_ENABLED(CONFIG_I2C_SLAVE)
3101 int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
3105 if (!client || !slave_cb) {
3106 WARN(1, "insufficent data\n");
3110 if (!(client->flags & I2C_CLIENT_SLAVE))
3111 dev_warn(&client->dev, "%s: client slave flag not set. You might see address collisions\n",
3114 if (!(client->flags & I2C_CLIENT_TEN)) {
3115 /* Enforce stricter address checking */
3116 ret = i2c_check_7bit_addr_validity_strict(client->addr);
3118 dev_err(&client->dev, "%s: invalid address\n", __func__);
3123 if (!client->adapter->algo->reg_slave) {
3124 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3128 client->slave_cb = slave_cb;
3130 i2c_lock_adapter(client->adapter);
3131 ret = client->adapter->algo->reg_slave(client);
3132 i2c_unlock_adapter(client->adapter);
3135 client->slave_cb = NULL;
3136 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3141 EXPORT_SYMBOL_GPL(i2c_slave_register);
3143 int i2c_slave_unregister(struct i2c_client *client)
3147 if (!client->adapter->algo->unreg_slave) {
3148 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3152 i2c_lock_adapter(client->adapter);
3153 ret = client->adapter->algo->unreg_slave(client);
3154 i2c_unlock_adapter(client->adapter);
3157 client->slave_cb = NULL;
3159 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3163 EXPORT_SYMBOL_GPL(i2c_slave_unregister);
3166 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
3167 MODULE_DESCRIPTION("I2C-Bus main module");
3168 MODULE_LICENSE("GPL");