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 <linux/module.h>
31 #include <linux/kernel.h>
32 #include <linux/delay.h>
33 #include <linux/errno.h>
34 #include <linux/gpio.h>
35 #include <linux/slab.h>
36 #include <linux/i2c.h>
37 #include <linux/init.h>
38 #include <linux/idr.h>
39 #include <linux/mutex.h>
41 #include <linux/of_device.h>
42 #include <linux/of_irq.h>
43 #include <linux/clk/clk-conf.h>
44 #include <linux/completion.h>
45 #include <linux/hardirq.h>
46 #include <linux/irqflags.h>
47 #include <linux/rwsem.h>
48 #include <linux/pm_runtime.h>
49 #include <linux/pm_domain.h>
50 #include <linux/acpi.h>
51 #include <linux/jump_label.h>
52 #include <asm/uaccess.h>
53 #include <linux/err.h>
57 #define CREATE_TRACE_POINTS
58 #include <trace/events/i2c.h>
60 /* core_lock protects i2c_adapter_idr, and guarantees
61 that device detection, deletion of detected devices, and attach_adapter
62 calls are serialized */
63 static DEFINE_MUTEX(core_lock);
64 static DEFINE_IDR(i2c_adapter_idr);
66 static struct device_type i2c_client_type;
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;
71 void i2c_transfer_trace_reg(void)
73 static_key_slow_inc(&i2c_trace_msg);
76 void i2c_transfer_trace_unreg(void)
78 static_key_slow_dec(&i2c_trace_msg);
81 #if defined(CONFIG_ACPI)
82 struct acpi_i2c_handler_data {
83 struct acpi_connection_info info;
84 struct i2c_adapter *adapter;
97 static int acpi_i2c_add_resource(struct acpi_resource *ares, void *data)
99 struct i2c_board_info *info = data;
101 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
102 struct acpi_resource_i2c_serialbus *sb;
104 sb = &ares->data.i2c_serial_bus;
105 if (!info->addr && sb->type == ACPI_RESOURCE_SERIAL_TYPE_I2C) {
106 info->addr = sb->slave_address;
107 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
108 info->flags |= I2C_CLIENT_TEN;
110 } else if (info->irq < 0) {
113 if (acpi_dev_resource_interrupt(ares, 0, &r))
117 /* Tell the ACPI core to skip this resource */
121 static acpi_status acpi_i2c_add_device(acpi_handle handle, u32 level,
122 void *data, void **return_value)
124 struct i2c_adapter *adapter = data;
125 struct list_head resource_list;
126 struct i2c_board_info info;
127 struct acpi_device *adev;
130 if (acpi_bus_get_device(handle, &adev))
132 if (acpi_bus_get_status(adev) || !adev->status.present)
135 memset(&info, 0, sizeof(info));
136 info.fwnode = acpi_fwnode_handle(adev);
139 INIT_LIST_HEAD(&resource_list);
140 ret = acpi_dev_get_resources(adev, &resource_list,
141 acpi_i2c_add_resource, &info);
142 acpi_dev_free_resource_list(&resource_list);
144 if (ret < 0 || !info.addr)
147 adev->power.flags.ignore_parent = true;
148 strlcpy(info.type, dev_name(&adev->dev), sizeof(info.type));
149 if (!i2c_new_device(adapter, &info)) {
150 adev->power.flags.ignore_parent = false;
151 dev_err(&adapter->dev,
152 "failed to add I2C device %s from ACPI\n",
153 dev_name(&adev->dev));
160 * acpi_i2c_register_devices - enumerate I2C slave devices behind adapter
161 * @adap: pointer to adapter
163 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
164 * namespace. When a device is found it will be added to the Linux device
165 * model and bound to the corresponding ACPI handle.
167 static void acpi_i2c_register_devices(struct i2c_adapter *adap)
172 if (!adap->dev.parent)
175 handle = ACPI_HANDLE(adap->dev.parent);
179 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
180 acpi_i2c_add_device, NULL,
182 if (ACPI_FAILURE(status))
183 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
186 #else /* CONFIG_ACPI */
187 static inline void acpi_i2c_register_devices(struct i2c_adapter *adap) { }
188 #endif /* CONFIG_ACPI */
190 #ifdef CONFIG_ACPI_I2C_OPREGION
191 static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
192 u8 cmd, u8 *data, u8 data_len)
195 struct i2c_msg msgs[2];
199 buffer = kzalloc(data_len, GFP_KERNEL);
203 msgs[0].addr = client->addr;
204 msgs[0].flags = client->flags;
208 msgs[1].addr = client->addr;
209 msgs[1].flags = client->flags | I2C_M_RD;
210 msgs[1].len = data_len;
211 msgs[1].buf = buffer;
213 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
215 dev_err(&client->adapter->dev, "i2c read failed\n");
217 memcpy(data, buffer, data_len);
223 static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
224 u8 cmd, u8 *data, u8 data_len)
227 struct i2c_msg msgs[1];
231 buffer = kzalloc(data_len + 1, GFP_KERNEL);
236 memcpy(buffer + 1, data, data_len);
238 msgs[0].addr = client->addr;
239 msgs[0].flags = client->flags;
240 msgs[0].len = data_len + 1;
241 msgs[0].buf = buffer;
243 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
245 dev_err(&client->adapter->dev, "i2c write failed\n");
252 acpi_i2c_space_handler(u32 function, acpi_physical_address command,
253 u32 bits, u64 *value64,
254 void *handler_context, void *region_context)
256 struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
257 struct acpi_i2c_handler_data *data = handler_context;
258 struct acpi_connection_info *info = &data->info;
259 struct acpi_resource_i2c_serialbus *sb;
260 struct i2c_adapter *adapter = data->adapter;
261 struct i2c_client *client;
262 struct acpi_resource *ares;
263 u32 accessor_type = function >> 16;
264 u8 action = function & ACPI_IO_MASK;
268 ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
269 if (ACPI_FAILURE(ret))
272 client = kzalloc(sizeof(*client), GFP_KERNEL);
278 if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
279 ret = AE_BAD_PARAMETER;
283 sb = &ares->data.i2c_serial_bus;
284 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
285 ret = AE_BAD_PARAMETER;
289 client->adapter = adapter;
290 client->addr = sb->slave_address;
292 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
293 client->flags |= I2C_CLIENT_TEN;
295 switch (accessor_type) {
296 case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
297 if (action == ACPI_READ) {
298 status = i2c_smbus_read_byte(client);
304 status = i2c_smbus_write_byte(client, gsb->bdata);
308 case ACPI_GSB_ACCESS_ATTRIB_BYTE:
309 if (action == ACPI_READ) {
310 status = i2c_smbus_read_byte_data(client, command);
316 status = i2c_smbus_write_byte_data(client, command,
321 case ACPI_GSB_ACCESS_ATTRIB_WORD:
322 if (action == ACPI_READ) {
323 status = i2c_smbus_read_word_data(client, command);
329 status = i2c_smbus_write_word_data(client, command,
334 case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
335 if (action == ACPI_READ) {
336 status = i2c_smbus_read_block_data(client, command,
343 status = i2c_smbus_write_block_data(client, command,
344 gsb->len, gsb->data);
348 case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
349 if (action == ACPI_READ) {
350 status = acpi_gsb_i2c_read_bytes(client, command,
351 gsb->data, info->access_length);
355 status = acpi_gsb_i2c_write_bytes(client, command,
356 gsb->data, info->access_length);
361 pr_info("protocol(0x%02x) is not supported.\n", accessor_type);
362 ret = AE_BAD_PARAMETER;
366 gsb->status = status;
375 static int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
378 struct acpi_i2c_handler_data *data;
381 if (!adapter->dev.parent)
384 handle = ACPI_HANDLE(adapter->dev.parent);
389 data = kzalloc(sizeof(struct acpi_i2c_handler_data),
394 data->adapter = adapter;
395 status = acpi_bus_attach_private_data(handle, (void *)data);
396 if (ACPI_FAILURE(status)) {
401 status = acpi_install_address_space_handler(handle,
402 ACPI_ADR_SPACE_GSBUS,
403 &acpi_i2c_space_handler,
406 if (ACPI_FAILURE(status)) {
407 dev_err(&adapter->dev, "Error installing i2c space handler\n");
408 acpi_bus_detach_private_data(handle);
413 acpi_walk_dep_device_list(handle);
417 static void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
420 struct acpi_i2c_handler_data *data;
423 if (!adapter->dev.parent)
426 handle = ACPI_HANDLE(adapter->dev.parent);
431 acpi_remove_address_space_handler(handle,
432 ACPI_ADR_SPACE_GSBUS,
433 &acpi_i2c_space_handler);
435 status = acpi_bus_get_private_data(handle, (void **)&data);
436 if (ACPI_SUCCESS(status))
439 acpi_bus_detach_private_data(handle);
441 #else /* CONFIG_ACPI_I2C_OPREGION */
442 static inline void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
445 static inline int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
447 #endif /* CONFIG_ACPI_I2C_OPREGION */
449 /* ------------------------------------------------------------------------- */
451 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
452 const struct i2c_client *client)
454 while (id->name[0]) {
455 if (strcmp(client->name, id->name) == 0)
462 static int i2c_device_match(struct device *dev, struct device_driver *drv)
464 struct i2c_client *client = i2c_verify_client(dev);
465 struct i2c_driver *driver;
470 /* Attempt an OF style match */
471 if (of_driver_match_device(dev, drv))
474 /* Then ACPI style match */
475 if (acpi_driver_match_device(dev, drv))
478 driver = to_i2c_driver(drv);
479 /* match on an id table if there is one */
480 if (driver->id_table)
481 return i2c_match_id(driver->id_table, client) != NULL;
487 /* uevent helps with hotplug: modprobe -q $(MODALIAS) */
488 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
490 struct i2c_client *client = to_i2c_client(dev);
493 rc = acpi_device_uevent_modalias(dev, env);
497 if (add_uevent_var(env, "MODALIAS=%s%s",
498 I2C_MODULE_PREFIX, client->name))
500 dev_dbg(dev, "uevent\n");
504 /* i2c bus recovery routines */
505 static int get_scl_gpio_value(struct i2c_adapter *adap)
507 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
510 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
512 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
515 static int get_sda_gpio_value(struct i2c_adapter *adap)
517 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
520 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
522 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
523 struct device *dev = &adap->dev;
526 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
527 GPIOF_OUT_INIT_HIGH, "i2c-scl");
529 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
534 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
535 /* work without SDA polling */
536 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
545 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
547 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
550 gpio_free(bri->sda_gpio);
552 gpio_free(bri->scl_gpio);
556 * We are generating clock pulses. ndelay() determines durating of clk pulses.
557 * We will generate clock with rate 100 KHz and so duration of both clock levels
558 * is: delay in ns = (10^6 / 100) / 2
560 #define RECOVERY_NDELAY 5000
561 #define RECOVERY_CLK_CNT 9
563 static int i2c_generic_recovery(struct i2c_adapter *adap)
565 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
566 int i = 0, val = 1, ret = 0;
568 if (bri->prepare_recovery)
569 bri->prepare_recovery(adap);
572 * By this time SCL is high, as we need to give 9 falling-rising edges
574 while (i++ < RECOVERY_CLK_CNT * 2) {
576 /* Break if SDA is high */
577 if (bri->get_sda && bri->get_sda(adap))
579 /* SCL shouldn't be low here */
580 if (!bri->get_scl(adap)) {
582 "SCL is stuck low, exit recovery\n");
589 bri->set_scl(adap, val);
590 ndelay(RECOVERY_NDELAY);
593 if (bri->unprepare_recovery)
594 bri->unprepare_recovery(adap);
599 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
601 adap->bus_recovery_info->set_scl(adap, 1);
602 return i2c_generic_recovery(adap);
604 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
606 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
610 ret = i2c_get_gpios_for_recovery(adap);
614 ret = i2c_generic_recovery(adap);
615 i2c_put_gpios_for_recovery(adap);
619 EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
621 int i2c_recover_bus(struct i2c_adapter *adap)
623 if (!adap->bus_recovery_info)
626 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
627 return adap->bus_recovery_info->recover_bus(adap);
629 EXPORT_SYMBOL_GPL(i2c_recover_bus);
631 static int i2c_device_probe(struct device *dev)
633 struct i2c_client *client = i2c_verify_client(dev);
634 struct i2c_driver *driver;
640 if (!client->irq && dev->of_node) {
641 int irq = of_irq_get(dev->of_node, 0);
643 if (irq == -EPROBE_DEFER)
651 driver = to_i2c_driver(dev->driver);
652 if (!driver->probe || !driver->id_table)
655 if (!device_can_wakeup(&client->dev))
656 device_init_wakeup(&client->dev,
657 client->flags & I2C_CLIENT_WAKE);
658 dev_dbg(dev, "probe\n");
660 status = of_clk_set_defaults(dev->of_node, false);
664 status = dev_pm_domain_attach(&client->dev, true);
665 if (status != -EPROBE_DEFER) {
666 status = driver->probe(client, i2c_match_id(driver->id_table,
669 dev_pm_domain_detach(&client->dev, true);
675 static int i2c_device_remove(struct device *dev)
677 struct i2c_client *client = i2c_verify_client(dev);
678 struct i2c_driver *driver;
681 if (!client || !dev->driver)
684 driver = to_i2c_driver(dev->driver);
685 if (driver->remove) {
686 dev_dbg(dev, "remove\n");
687 status = driver->remove(client);
690 dev_pm_domain_detach(&client->dev, true);
694 static void i2c_device_shutdown(struct device *dev)
696 struct i2c_client *client = i2c_verify_client(dev);
697 struct i2c_driver *driver;
699 if (!client || !dev->driver)
701 driver = to_i2c_driver(dev->driver);
702 if (driver->shutdown)
703 driver->shutdown(client);
706 static void i2c_client_dev_release(struct device *dev)
708 kfree(to_i2c_client(dev));
712 show_name(struct device *dev, struct device_attribute *attr, char *buf)
714 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
715 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
717 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
720 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
722 struct i2c_client *client = to_i2c_client(dev);
725 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
729 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
731 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
733 static struct attribute *i2c_dev_attrs[] = {
735 /* modalias helps coldplug: modprobe $(cat .../modalias) */
736 &dev_attr_modalias.attr,
739 ATTRIBUTE_GROUPS(i2c_dev);
741 struct bus_type i2c_bus_type = {
743 .match = i2c_device_match,
744 .probe = i2c_device_probe,
745 .remove = i2c_device_remove,
746 .shutdown = i2c_device_shutdown,
748 EXPORT_SYMBOL_GPL(i2c_bus_type);
750 static struct device_type i2c_client_type = {
751 .groups = i2c_dev_groups,
752 .uevent = i2c_device_uevent,
753 .release = i2c_client_dev_release,
758 * i2c_verify_client - return parameter as i2c_client, or NULL
759 * @dev: device, probably from some driver model iterator
761 * When traversing the driver model tree, perhaps using driver model
762 * iterators like @device_for_each_child(), you can't assume very much
763 * about the nodes you find. Use this function to avoid oopses caused
764 * by wrongly treating some non-I2C device as an i2c_client.
766 struct i2c_client *i2c_verify_client(struct device *dev)
768 return (dev->type == &i2c_client_type)
772 EXPORT_SYMBOL(i2c_verify_client);
775 /* This is a permissive address validity check, I2C address map constraints
776 * are purposely not enforced, except for the general call address. */
777 static int i2c_check_client_addr_validity(const struct i2c_client *client)
779 if (client->flags & I2C_CLIENT_TEN) {
780 /* 10-bit address, all values are valid */
781 if (client->addr > 0x3ff)
784 /* 7-bit address, reject the general call address */
785 if (client->addr == 0x00 || client->addr > 0x7f)
791 /* And this is a strict address validity check, used when probing. If a
792 * device uses a reserved address, then it shouldn't be probed. 7-bit
793 * addressing is assumed, 10-bit address devices are rare and should be
794 * explicitly enumerated. */
795 static int i2c_check_addr_validity(unsigned short addr)
798 * Reserved addresses per I2C specification:
799 * 0x00 General call address / START byte
801 * 0x02 Reserved for different bus format
802 * 0x03 Reserved for future purposes
803 * 0x04-0x07 Hs-mode master code
804 * 0x78-0x7b 10-bit slave addressing
805 * 0x7c-0x7f Reserved for future purposes
807 if (addr < 0x08 || addr > 0x77)
812 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
814 struct i2c_client *client = i2c_verify_client(dev);
815 int addr = *(int *)addrp;
817 if (client && client->addr == addr)
822 /* walk up mux tree */
823 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
825 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
828 result = device_for_each_child(&adapter->dev, &addr,
829 __i2c_check_addr_busy);
831 if (!result && parent)
832 result = i2c_check_mux_parents(parent, addr);
837 /* recurse down mux tree */
838 static int i2c_check_mux_children(struct device *dev, void *addrp)
842 if (dev->type == &i2c_adapter_type)
843 result = device_for_each_child(dev, addrp,
844 i2c_check_mux_children);
846 result = __i2c_check_addr_busy(dev, addrp);
851 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
853 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
857 result = i2c_check_mux_parents(parent, addr);
860 result = device_for_each_child(&adapter->dev, &addr,
861 i2c_check_mux_children);
867 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
868 * @adapter: Target I2C bus segment
870 void i2c_lock_adapter(struct i2c_adapter *adapter)
872 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
875 i2c_lock_adapter(parent);
877 rt_mutex_lock(&adapter->bus_lock);
879 EXPORT_SYMBOL_GPL(i2c_lock_adapter);
882 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
883 * @adapter: Target I2C bus segment
885 static int i2c_trylock_adapter(struct i2c_adapter *adapter)
887 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
890 return i2c_trylock_adapter(parent);
892 return rt_mutex_trylock(&adapter->bus_lock);
896 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
897 * @adapter: Target I2C bus segment
899 void i2c_unlock_adapter(struct i2c_adapter *adapter)
901 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
904 i2c_unlock_adapter(parent);
906 rt_mutex_unlock(&adapter->bus_lock);
908 EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
910 static void i2c_dev_set_name(struct i2c_adapter *adap,
911 struct i2c_client *client)
913 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
916 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
920 /* For 10-bit clients, add an arbitrary offset to avoid collisions */
921 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
922 client->addr | ((client->flags & I2C_CLIENT_TEN)
927 * i2c_new_device - instantiate an i2c device
928 * @adap: the adapter managing the device
929 * @info: describes one I2C device; bus_num is ignored
932 * Create an i2c device. Binding is handled through driver model
933 * probe()/remove() methods. A driver may be bound to this device when we
934 * return from this function, or any later moment (e.g. maybe hotplugging will
935 * load the driver module). This call is not appropriate for use by mainboard
936 * initialization logic, which usually runs during an arch_initcall() long
937 * before any i2c_adapter could exist.
939 * This returns the new i2c client, which may be saved for later use with
940 * i2c_unregister_device(); or NULL to indicate an error.
943 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
945 struct i2c_client *client;
948 client = kzalloc(sizeof *client, GFP_KERNEL);
952 client->adapter = adap;
954 client->dev.platform_data = info->platform_data;
957 client->dev.archdata = *info->archdata;
959 client->flags = info->flags;
960 client->addr = info->addr;
961 client->irq = info->irq;
963 strlcpy(client->name, info->type, sizeof(client->name));
965 /* Check for address validity */
966 status = i2c_check_client_addr_validity(client);
968 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
969 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
973 /* Check for address business */
974 status = i2c_check_addr_busy(adap, client->addr);
978 client->dev.parent = &client->adapter->dev;
979 client->dev.bus = &i2c_bus_type;
980 client->dev.type = &i2c_client_type;
981 client->dev.of_node = info->of_node;
982 client->dev.fwnode = info->fwnode;
984 i2c_dev_set_name(adap, client);
985 status = device_register(&client->dev);
989 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
990 client->name, dev_name(&client->dev));
995 dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
996 "(%d)\n", client->name, client->addr, status);
1001 EXPORT_SYMBOL_GPL(i2c_new_device);
1005 * i2c_unregister_device - reverse effect of i2c_new_device()
1006 * @client: value returned from i2c_new_device()
1007 * Context: can sleep
1009 void i2c_unregister_device(struct i2c_client *client)
1011 device_unregister(&client->dev);
1013 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1016 static const struct i2c_device_id dummy_id[] = {
1021 static int dummy_probe(struct i2c_client *client,
1022 const struct i2c_device_id *id)
1027 static int dummy_remove(struct i2c_client *client)
1032 static struct i2c_driver dummy_driver = {
1033 .driver.name = "dummy",
1034 .probe = dummy_probe,
1035 .remove = dummy_remove,
1036 .id_table = dummy_id,
1040 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1041 * @adapter: the adapter managing the device
1042 * @address: seven bit address to be used
1043 * Context: can sleep
1045 * This returns an I2C client bound to the "dummy" driver, intended for use
1046 * with devices that consume multiple addresses. Examples of such chips
1047 * include various EEPROMS (like 24c04 and 24c08 models).
1049 * These dummy devices have two main uses. First, most I2C and SMBus calls
1050 * except i2c_transfer() need a client handle; the dummy will be that handle.
1051 * And second, this prevents the specified address from being bound to a
1054 * This returns the new i2c client, which should be saved for later use with
1055 * i2c_unregister_device(); or NULL to indicate an error.
1057 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1059 struct i2c_board_info info = {
1060 I2C_BOARD_INFO("dummy", address),
1063 return i2c_new_device(adapter, &info);
1065 EXPORT_SYMBOL_GPL(i2c_new_dummy);
1067 /* ------------------------------------------------------------------------- */
1069 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1071 static void i2c_adapter_dev_release(struct device *dev)
1073 struct i2c_adapter *adap = to_i2c_adapter(dev);
1074 complete(&adap->dev_released);
1078 * This function is only needed for mutex_lock_nested, so it is never
1079 * called unless locking correctness checking is enabled. Thus we
1080 * make it inline to avoid a compiler warning. That's what gcc ends up
1083 static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1085 unsigned int depth = 0;
1087 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1094 * Let users instantiate I2C devices through sysfs. This can be used when
1095 * platform initialization code doesn't contain the proper data for
1096 * whatever reason. Also useful for drivers that do device detection and
1097 * detection fails, either because the device uses an unexpected address,
1098 * or this is a compatible device with different ID register values.
1100 * Parameter checking may look overzealous, but we really don't want
1101 * the user to provide incorrect parameters.
1104 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1105 const char *buf, size_t count)
1107 struct i2c_adapter *adap = to_i2c_adapter(dev);
1108 struct i2c_board_info info;
1109 struct i2c_client *client;
1113 memset(&info, 0, sizeof(struct i2c_board_info));
1115 blank = strchr(buf, ' ');
1117 dev_err(dev, "%s: Missing parameters\n", "new_device");
1120 if (blank - buf > I2C_NAME_SIZE - 1) {
1121 dev_err(dev, "%s: Invalid device name\n", "new_device");
1124 memcpy(info.type, buf, blank - buf);
1126 /* Parse remaining parameters, reject extra parameters */
1127 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1129 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1132 if (res > 1 && end != '\n') {
1133 dev_err(dev, "%s: Extra parameters\n", "new_device");
1137 client = i2c_new_device(adap, &info);
1141 /* Keep track of the added device */
1142 mutex_lock(&adap->userspace_clients_lock);
1143 list_add_tail(&client->detected, &adap->userspace_clients);
1144 mutex_unlock(&adap->userspace_clients_lock);
1145 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1146 info.type, info.addr);
1150 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1153 * And of course let the users delete the devices they instantiated, if
1154 * they got it wrong. This interface can only be used to delete devices
1155 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1156 * don't delete devices to which some kernel code still has references.
1158 * Parameter checking may look overzealous, but we really don't want
1159 * the user to delete the wrong device.
1162 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1163 const char *buf, size_t count)
1165 struct i2c_adapter *adap = to_i2c_adapter(dev);
1166 struct i2c_client *client, *next;
1167 unsigned short addr;
1171 /* Parse parameters, reject extra parameters */
1172 res = sscanf(buf, "%hi%c", &addr, &end);
1174 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1177 if (res > 1 && end != '\n') {
1178 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1182 /* Make sure the device was added through sysfs */
1184 mutex_lock_nested(&adap->userspace_clients_lock,
1185 i2c_adapter_depth(adap));
1186 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1188 if (client->addr == addr) {
1189 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1190 "delete_device", client->name, client->addr);
1192 list_del(&client->detected);
1193 i2c_unregister_device(client);
1198 mutex_unlock(&adap->userspace_clients_lock);
1201 dev_err(dev, "%s: Can't find device in list\n",
1205 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1206 i2c_sysfs_delete_device);
1208 static struct attribute *i2c_adapter_attrs[] = {
1209 &dev_attr_name.attr,
1210 &dev_attr_new_device.attr,
1211 &dev_attr_delete_device.attr,
1214 ATTRIBUTE_GROUPS(i2c_adapter);
1216 struct device_type i2c_adapter_type = {
1217 .groups = i2c_adapter_groups,
1218 .release = i2c_adapter_dev_release,
1220 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1223 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1224 * @dev: device, probably from some driver model iterator
1226 * When traversing the driver model tree, perhaps using driver model
1227 * iterators like @device_for_each_child(), you can't assume very much
1228 * about the nodes you find. Use this function to avoid oopses caused
1229 * by wrongly treating some non-I2C device as an i2c_adapter.
1231 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1233 return (dev->type == &i2c_adapter_type)
1234 ? to_i2c_adapter(dev)
1237 EXPORT_SYMBOL(i2c_verify_adapter);
1239 #ifdef CONFIG_I2C_COMPAT
1240 static struct class_compat *i2c_adapter_compat_class;
1243 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1245 struct i2c_devinfo *devinfo;
1247 down_read(&__i2c_board_lock);
1248 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1249 if (devinfo->busnum == adapter->nr
1250 && !i2c_new_device(adapter,
1251 &devinfo->board_info))
1252 dev_err(&adapter->dev,
1253 "Can't create device at 0x%02x\n",
1254 devinfo->board_info.addr);
1256 up_read(&__i2c_board_lock);
1259 /* OF support code */
1261 #if IS_ENABLED(CONFIG_OF)
1262 static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1263 struct device_node *node)
1265 struct i2c_client *result;
1266 struct i2c_board_info info = {};
1267 struct dev_archdata dev_ad = {};
1271 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1273 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1274 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1276 return ERR_PTR(-EINVAL);
1279 addr = of_get_property(node, "reg", &len);
1280 if (!addr || (len < sizeof(*addr))) {
1281 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1283 return ERR_PTR(-EINVAL);
1286 info.addr = be32_to_cpup(addr);
1287 if (info.addr > (1 << 10) - 1) {
1288 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1289 info.addr, node->full_name);
1290 return ERR_PTR(-EINVAL);
1293 info.of_node = of_node_get(node);
1294 info.archdata = &dev_ad;
1296 if (of_get_property(node, "wakeup-source", NULL))
1297 info.flags |= I2C_CLIENT_WAKE;
1299 result = i2c_new_device(adap, &info);
1300 if (result == NULL) {
1301 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1304 return ERR_PTR(-EINVAL);
1309 static void of_i2c_register_devices(struct i2c_adapter *adap)
1311 struct device_node *node;
1313 /* Only register child devices if the adapter has a node pointer set */
1314 if (!adap->dev.of_node)
1317 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1319 for_each_available_child_of_node(adap->dev.of_node, node)
1320 of_i2c_register_device(adap, node);
1323 static int of_dev_node_match(struct device *dev, void *data)
1325 return dev->of_node == data;
1328 /* must call put_device() when done with returned i2c_client device */
1329 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1333 dev = bus_find_device(&i2c_bus_type, NULL, node,
1338 return i2c_verify_client(dev);
1340 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1342 /* must call put_device() when done with returned i2c_adapter device */
1343 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1347 dev = bus_find_device(&i2c_bus_type, NULL, node,
1352 return i2c_verify_adapter(dev);
1354 EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1356 static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1357 #endif /* CONFIG_OF */
1359 static int i2c_do_add_adapter(struct i2c_driver *driver,
1360 struct i2c_adapter *adap)
1362 /* Detect supported devices on that bus, and instantiate them */
1363 i2c_detect(adap, driver);
1365 /* Let legacy drivers scan this bus for matching devices */
1366 if (driver->attach_adapter) {
1367 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1368 driver->driver.name);
1369 dev_warn(&adap->dev, "Please use another way to instantiate "
1370 "your i2c_client\n");
1371 /* We ignore the return code; if it fails, too bad */
1372 driver->attach_adapter(adap);
1377 static int __process_new_adapter(struct device_driver *d, void *data)
1379 return i2c_do_add_adapter(to_i2c_driver(d), data);
1382 static int i2c_register_adapter(struct i2c_adapter *adap)
1386 /* Can't register until after driver model init */
1387 if (unlikely(WARN_ON(!i2c_bus_type.p))) {
1393 if (unlikely(adap->name[0] == '\0')) {
1394 pr_err("i2c-core: Attempt to register an adapter with "
1398 if (unlikely(!adap->algo)) {
1399 pr_err("i2c-core: Attempt to register adapter '%s' with "
1400 "no algo!\n", adap->name);
1404 rt_mutex_init(&adap->bus_lock);
1405 mutex_init(&adap->userspace_clients_lock);
1406 INIT_LIST_HEAD(&adap->userspace_clients);
1408 /* Set default timeout to 1 second if not already set */
1409 if (adap->timeout == 0)
1412 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1413 adap->dev.bus = &i2c_bus_type;
1414 adap->dev.type = &i2c_adapter_type;
1415 res = device_register(&adap->dev);
1419 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1421 pm_runtime_no_callbacks(&adap->dev);
1423 #ifdef CONFIG_I2C_COMPAT
1424 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1427 dev_warn(&adap->dev,
1428 "Failed to create compatibility class link\n");
1431 /* bus recovery specific initialization */
1432 if (adap->bus_recovery_info) {
1433 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
1435 if (!bri->recover_bus) {
1436 dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
1437 adap->bus_recovery_info = NULL;
1441 /* Generic GPIO recovery */
1442 if (bri->recover_bus == i2c_generic_gpio_recovery) {
1443 if (!gpio_is_valid(bri->scl_gpio)) {
1444 dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
1445 adap->bus_recovery_info = NULL;
1449 if (gpio_is_valid(bri->sda_gpio))
1450 bri->get_sda = get_sda_gpio_value;
1452 bri->get_sda = NULL;
1454 bri->get_scl = get_scl_gpio_value;
1455 bri->set_scl = set_scl_gpio_value;
1456 } else if (!bri->set_scl || !bri->get_scl) {
1457 /* Generic SCL recovery */
1458 dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
1459 adap->bus_recovery_info = NULL;
1464 /* create pre-declared device nodes */
1465 of_i2c_register_devices(adap);
1466 acpi_i2c_register_devices(adap);
1467 acpi_i2c_install_space_handler(adap);
1469 if (adap->nr < __i2c_first_dynamic_bus_num)
1470 i2c_scan_static_board_info(adap);
1472 /* Notify drivers */
1473 mutex_lock(&core_lock);
1474 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1475 mutex_unlock(&core_lock);
1480 mutex_lock(&core_lock);
1481 idr_remove(&i2c_adapter_idr, adap->nr);
1482 mutex_unlock(&core_lock);
1487 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1488 * @adap: the adapter to register (with adap->nr initialized)
1489 * Context: can sleep
1491 * See i2c_add_numbered_adapter() for details.
1493 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1497 mutex_lock(&core_lock);
1498 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1,
1500 mutex_unlock(&core_lock);
1502 return id == -ENOSPC ? -EBUSY : id;
1504 return i2c_register_adapter(adap);
1508 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1509 * @adapter: the adapter to add
1510 * Context: can sleep
1512 * This routine is used to declare an I2C adapter when its bus number
1513 * doesn't matter or when its bus number is specified by an dt alias.
1514 * Examples of bases when the bus number doesn't matter: I2C adapters
1515 * dynamically added by USB links or PCI plugin cards.
1517 * When this returns zero, a new bus number was allocated and stored
1518 * in adap->nr, and the specified adapter became available for clients.
1519 * Otherwise, a negative errno value is returned.
1521 int i2c_add_adapter(struct i2c_adapter *adapter)
1523 struct device *dev = &adapter->dev;
1527 id = of_alias_get_id(dev->of_node, "i2c");
1530 return __i2c_add_numbered_adapter(adapter);
1534 mutex_lock(&core_lock);
1535 id = idr_alloc(&i2c_adapter_idr, adapter,
1536 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1537 mutex_unlock(&core_lock);
1543 return i2c_register_adapter(adapter);
1545 EXPORT_SYMBOL(i2c_add_adapter);
1548 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1549 * @adap: the adapter to register (with adap->nr initialized)
1550 * Context: can sleep
1552 * This routine is used to declare an I2C adapter when its bus number
1553 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1554 * or otherwise built in to the system's mainboard, and where i2c_board_info
1555 * is used to properly configure I2C devices.
1557 * If the requested bus number is set to -1, then this function will behave
1558 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1560 * If no devices have pre-been declared for this bus, then be sure to
1561 * register the adapter before any dynamically allocated ones. Otherwise
1562 * the required bus ID may not be available.
1564 * When this returns zero, the specified adapter became available for
1565 * clients using the bus number provided in adap->nr. Also, the table
1566 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1567 * and the appropriate driver model device nodes are created. Otherwise, a
1568 * negative errno value is returned.
1570 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1572 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1573 return i2c_add_adapter(adap);
1575 return __i2c_add_numbered_adapter(adap);
1577 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1579 static void i2c_do_del_adapter(struct i2c_driver *driver,
1580 struct i2c_adapter *adapter)
1582 struct i2c_client *client, *_n;
1584 /* Remove the devices we created ourselves as the result of hardware
1585 * probing (using a driver's detect method) */
1586 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1587 if (client->adapter == adapter) {
1588 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1589 client->name, client->addr);
1590 list_del(&client->detected);
1591 i2c_unregister_device(client);
1596 static int __unregister_client(struct device *dev, void *dummy)
1598 struct i2c_client *client = i2c_verify_client(dev);
1599 if (client && strcmp(client->name, "dummy"))
1600 i2c_unregister_device(client);
1604 static int __unregister_dummy(struct device *dev, void *dummy)
1606 struct i2c_client *client = i2c_verify_client(dev);
1608 i2c_unregister_device(client);
1612 static int __process_removed_adapter(struct device_driver *d, void *data)
1614 i2c_do_del_adapter(to_i2c_driver(d), data);
1619 * i2c_del_adapter - unregister I2C adapter
1620 * @adap: the adapter being unregistered
1621 * Context: can sleep
1623 * This unregisters an I2C adapter which was previously registered
1624 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1626 void i2c_del_adapter(struct i2c_adapter *adap)
1628 struct i2c_adapter *found;
1629 struct i2c_client *client, *next;
1631 /* First make sure that this adapter was ever added */
1632 mutex_lock(&core_lock);
1633 found = idr_find(&i2c_adapter_idr, adap->nr);
1634 mutex_unlock(&core_lock);
1635 if (found != adap) {
1636 pr_debug("i2c-core: attempting to delete unregistered "
1637 "adapter [%s]\n", adap->name);
1641 acpi_i2c_remove_space_handler(adap);
1642 /* Tell drivers about this removal */
1643 mutex_lock(&core_lock);
1644 bus_for_each_drv(&i2c_bus_type, NULL, adap,
1645 __process_removed_adapter);
1646 mutex_unlock(&core_lock);
1648 /* Remove devices instantiated from sysfs */
1649 mutex_lock_nested(&adap->userspace_clients_lock,
1650 i2c_adapter_depth(adap));
1651 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1653 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1655 list_del(&client->detected);
1656 i2c_unregister_device(client);
1658 mutex_unlock(&adap->userspace_clients_lock);
1660 /* Detach any active clients. This can't fail, thus we do not
1661 * check the returned value. This is a two-pass process, because
1662 * we can't remove the dummy devices during the first pass: they
1663 * could have been instantiated by real devices wishing to clean
1664 * them up properly, so we give them a chance to do that first. */
1665 device_for_each_child(&adap->dev, NULL, __unregister_client);
1666 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1668 #ifdef CONFIG_I2C_COMPAT
1669 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1673 /* device name is gone after device_unregister */
1674 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1676 /* wait until all references to the device are gone
1678 * FIXME: This is old code and should ideally be replaced by an
1679 * alternative which results in decoupling the lifetime of the struct
1680 * device from the i2c_adapter, like spi or netdev do. Any solution
1681 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
1683 init_completion(&adap->dev_released);
1684 device_unregister(&adap->dev);
1685 wait_for_completion(&adap->dev_released);
1688 mutex_lock(&core_lock);
1689 idr_remove(&i2c_adapter_idr, adap->nr);
1690 mutex_unlock(&core_lock);
1692 /* Clear the device structure in case this adapter is ever going to be
1694 memset(&adap->dev, 0, sizeof(adap->dev));
1696 EXPORT_SYMBOL(i2c_del_adapter);
1698 /* ------------------------------------------------------------------------- */
1700 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1704 mutex_lock(&core_lock);
1705 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1706 mutex_unlock(&core_lock);
1710 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1712 static int __process_new_driver(struct device *dev, void *data)
1714 if (dev->type != &i2c_adapter_type)
1716 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1720 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1721 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1724 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1728 /* Can't register until after driver model init */
1729 if (unlikely(WARN_ON(!i2c_bus_type.p)))
1732 /* add the driver to the list of i2c drivers in the driver core */
1733 driver->driver.owner = owner;
1734 driver->driver.bus = &i2c_bus_type;
1736 /* When registration returns, the driver core
1737 * will have called probe() for all matching-but-unbound devices.
1739 res = driver_register(&driver->driver);
1743 pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
1745 INIT_LIST_HEAD(&driver->clients);
1746 /* Walk the adapters that are already present */
1747 i2c_for_each_dev(driver, __process_new_driver);
1751 EXPORT_SYMBOL(i2c_register_driver);
1753 static int __process_removed_driver(struct device *dev, void *data)
1755 if (dev->type == &i2c_adapter_type)
1756 i2c_do_del_adapter(data, to_i2c_adapter(dev));
1761 * i2c_del_driver - unregister I2C driver
1762 * @driver: the driver being unregistered
1763 * Context: can sleep
1765 void i2c_del_driver(struct i2c_driver *driver)
1767 i2c_for_each_dev(driver, __process_removed_driver);
1769 driver_unregister(&driver->driver);
1770 pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
1772 EXPORT_SYMBOL(i2c_del_driver);
1774 /* ------------------------------------------------------------------------- */
1777 * i2c_use_client - increments the reference count of the i2c client structure
1778 * @client: the client being referenced
1780 * Each live reference to a client should be refcounted. The driver model does
1781 * that automatically as part of driver binding, so that most drivers don't
1782 * need to do this explicitly: they hold a reference until they're unbound
1785 * A pointer to the client with the incremented reference counter is returned.
1787 struct i2c_client *i2c_use_client(struct i2c_client *client)
1789 if (client && get_device(&client->dev))
1793 EXPORT_SYMBOL(i2c_use_client);
1796 * i2c_release_client - release a use of the i2c client structure
1797 * @client: the client being no longer referenced
1799 * Must be called when a user of a client is finished with it.
1801 void i2c_release_client(struct i2c_client *client)
1804 put_device(&client->dev);
1806 EXPORT_SYMBOL(i2c_release_client);
1808 struct i2c_cmd_arg {
1813 static int i2c_cmd(struct device *dev, void *_arg)
1815 struct i2c_client *client = i2c_verify_client(dev);
1816 struct i2c_cmd_arg *arg = _arg;
1817 struct i2c_driver *driver;
1819 if (!client || !client->dev.driver)
1822 driver = to_i2c_driver(client->dev.driver);
1823 if (driver->command)
1824 driver->command(client, arg->cmd, arg->arg);
1828 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1830 struct i2c_cmd_arg cmd_arg;
1834 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1836 EXPORT_SYMBOL(i2c_clients_command);
1838 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
1839 static int of_i2c_notify(struct notifier_block *nb, unsigned long action,
1842 struct of_reconfig_data *rd = arg;
1843 struct i2c_adapter *adap;
1844 struct i2c_client *client;
1846 switch (of_reconfig_get_state_change(action, rd)) {
1847 case OF_RECONFIG_CHANGE_ADD:
1848 adap = of_find_i2c_adapter_by_node(rd->dn->parent);
1850 return NOTIFY_OK; /* not for us */
1852 client = of_i2c_register_device(adap, rd->dn);
1853 put_device(&adap->dev);
1855 if (IS_ERR(client)) {
1856 pr_err("%s: failed to create for '%s'\n",
1857 __func__, rd->dn->full_name);
1858 return notifier_from_errno(PTR_ERR(client));
1861 case OF_RECONFIG_CHANGE_REMOVE:
1862 /* find our device by node */
1863 client = of_find_i2c_device_by_node(rd->dn);
1865 return NOTIFY_OK; /* no? not meant for us */
1867 /* unregister takes one ref away */
1868 i2c_unregister_device(client);
1870 /* and put the reference of the find */
1871 put_device(&client->dev);
1877 static struct notifier_block i2c_of_notifier = {
1878 .notifier_call = of_i2c_notify,
1881 extern struct notifier_block i2c_of_notifier;
1882 #endif /* CONFIG_OF_DYNAMIC */
1884 static int __init i2c_init(void)
1888 retval = of_alias_get_highest_id("i2c");
1890 down_write(&__i2c_board_lock);
1891 if (retval >= __i2c_first_dynamic_bus_num)
1892 __i2c_first_dynamic_bus_num = retval + 1;
1893 up_write(&__i2c_board_lock);
1895 retval = bus_register(&i2c_bus_type);
1898 #ifdef CONFIG_I2C_COMPAT
1899 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1900 if (!i2c_adapter_compat_class) {
1905 retval = i2c_add_driver(&dummy_driver);
1909 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1910 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
1915 #ifdef CONFIG_I2C_COMPAT
1916 class_compat_unregister(i2c_adapter_compat_class);
1919 bus_unregister(&i2c_bus_type);
1923 static void __exit i2c_exit(void)
1925 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1926 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
1927 i2c_del_driver(&dummy_driver);
1928 #ifdef CONFIG_I2C_COMPAT
1929 class_compat_unregister(i2c_adapter_compat_class);
1931 bus_unregister(&i2c_bus_type);
1932 tracepoint_synchronize_unregister();
1935 /* We must initialize early, because some subsystems register i2c drivers
1936 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1938 postcore_initcall(i2c_init);
1939 module_exit(i2c_exit);
1941 /* ----------------------------------------------------
1942 * the functional interface to the i2c busses.
1943 * ----------------------------------------------------
1946 /* Check if val is exceeding the quirk IFF quirk is non 0 */
1947 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
1949 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
1951 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
1952 err_msg, msg->addr, msg->len,
1953 msg->flags & I2C_M_RD ? "read" : "write");
1957 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1959 const struct i2c_adapter_quirks *q = adap->quirks;
1960 int max_num = q->max_num_msgs, i;
1961 bool do_len_check = true;
1963 if (q->flags & I2C_AQ_COMB) {
1966 /* special checks for combined messages */
1968 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
1969 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
1971 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
1972 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
1974 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
1975 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
1977 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
1978 return i2c_quirk_error(adap, &msgs[0], "msg too long");
1980 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
1981 return i2c_quirk_error(adap, &msgs[1], "msg too long");
1983 do_len_check = false;
1987 if (i2c_quirk_exceeded(num, max_num))
1988 return i2c_quirk_error(adap, &msgs[0], "too many messages");
1990 for (i = 0; i < num; i++) {
1991 u16 len = msgs[i].len;
1993 if (msgs[i].flags & I2C_M_RD) {
1994 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
1995 return i2c_quirk_error(adap, &msgs[i], "msg too long");
1997 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
1998 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2006 * __i2c_transfer - unlocked flavor of i2c_transfer
2007 * @adap: Handle to I2C bus
2008 * @msgs: One or more messages to execute before STOP is issued to
2009 * terminate the operation; each message begins with a START.
2010 * @num: Number of messages to be executed.
2012 * Returns negative errno, else the number of messages executed.
2014 * Adapter lock must be held when calling this function. No debug logging
2015 * takes place. adap->algo->master_xfer existence isn't checked.
2017 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2019 unsigned long orig_jiffies;
2022 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2025 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2026 * enabled. This is an efficient way of keeping the for-loop from
2027 * being executed when not needed.
2029 if (static_key_false(&i2c_trace_msg)) {
2031 for (i = 0; i < num; i++)
2032 if (msgs[i].flags & I2C_M_RD)
2033 trace_i2c_read(adap, &msgs[i], i);
2035 trace_i2c_write(adap, &msgs[i], i);
2038 /* Retry automatically on arbitration loss */
2039 orig_jiffies = jiffies;
2040 for (ret = 0, try = 0; try <= adap->retries; try++) {
2041 ret = adap->algo->master_xfer(adap, msgs, num);
2044 if (time_after(jiffies, orig_jiffies + adap->timeout))
2048 if (static_key_false(&i2c_trace_msg)) {
2050 for (i = 0; i < ret; i++)
2051 if (msgs[i].flags & I2C_M_RD)
2052 trace_i2c_reply(adap, &msgs[i], i);
2053 trace_i2c_result(adap, i, ret);
2058 EXPORT_SYMBOL(__i2c_transfer);
2061 * i2c_transfer - execute a single or combined I2C message
2062 * @adap: Handle to I2C bus
2063 * @msgs: One or more messages to execute before STOP is issued to
2064 * terminate the operation; each message begins with a START.
2065 * @num: Number of messages to be executed.
2067 * Returns negative errno, else the number of messages executed.
2069 * Note that there is no requirement that each message be sent to
2070 * the same slave address, although that is the most common model.
2072 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2076 /* REVISIT the fault reporting model here is weak:
2078 * - When we get an error after receiving N bytes from a slave,
2079 * there is no way to report "N".
2081 * - When we get a NAK after transmitting N bytes to a slave,
2082 * there is no way to report "N" ... or to let the master
2083 * continue executing the rest of this combined message, if
2084 * that's the appropriate response.
2086 * - When for example "num" is two and we successfully complete
2087 * the first message but get an error part way through the
2088 * second, it's unclear whether that should be reported as
2089 * one (discarding status on the second message) or errno
2090 * (discarding status on the first one).
2093 if (adap->algo->master_xfer) {
2095 for (ret = 0; ret < num; ret++) {
2096 dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
2097 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
2098 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
2099 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2103 if (in_atomic() || irqs_disabled()) {
2104 ret = i2c_trylock_adapter(adap);
2106 /* I2C activity is ongoing. */
2109 i2c_lock_adapter(adap);
2112 ret = __i2c_transfer(adap, msgs, num);
2113 i2c_unlock_adapter(adap);
2117 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2121 EXPORT_SYMBOL(i2c_transfer);
2124 * i2c_master_send - issue a single I2C message in master transmit mode
2125 * @client: Handle to slave device
2126 * @buf: Data that will be written to the slave
2127 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2129 * Returns negative errno, or else the number of bytes written.
2131 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2134 struct i2c_adapter *adap = client->adapter;
2137 msg.addr = client->addr;
2138 msg.flags = client->flags & I2C_M_TEN;
2140 msg.buf = (char *)buf;
2142 ret = i2c_transfer(adap, &msg, 1);
2145 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2146 * transmitted, else error code.
2148 return (ret == 1) ? count : ret;
2150 EXPORT_SYMBOL(i2c_master_send);
2153 * i2c_master_recv - issue a single I2C message in master receive mode
2154 * @client: Handle to slave device
2155 * @buf: Where to store data read from slave
2156 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2158 * Returns negative errno, or else the number of bytes read.
2160 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2162 struct i2c_adapter *adap = client->adapter;
2166 msg.addr = client->addr;
2167 msg.flags = client->flags & I2C_M_TEN;
2168 msg.flags |= I2C_M_RD;
2172 ret = i2c_transfer(adap, &msg, 1);
2175 * If everything went ok (i.e. 1 msg received), return #bytes received,
2178 return (ret == 1) ? count : ret;
2180 EXPORT_SYMBOL(i2c_master_recv);
2182 /* ----------------------------------------------------
2183 * the i2c address scanning function
2184 * Will not work for 10-bit addresses!
2185 * ----------------------------------------------------
2189 * Legacy default probe function, mostly relevant for SMBus. The default
2190 * probe method is a quick write, but it is known to corrupt the 24RF08
2191 * EEPROMs due to a state machine bug, and could also irreversibly
2192 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2193 * we use a short byte read instead. Also, some bus drivers don't implement
2194 * quick write, so we fallback to a byte read in that case too.
2195 * On x86, there is another special case for FSC hardware monitoring chips,
2196 * which want regular byte reads (address 0x73.) Fortunately, these are the
2197 * only known chips using this I2C address on PC hardware.
2198 * Returns 1 if probe succeeded, 0 if not.
2200 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2203 union i2c_smbus_data dummy;
2206 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2207 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2208 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2209 I2C_SMBUS_BYTE_DATA, &dummy);
2212 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2213 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2214 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2215 I2C_SMBUS_QUICK, NULL);
2216 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2217 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2218 I2C_SMBUS_BYTE, &dummy);
2220 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2228 static int i2c_detect_address(struct i2c_client *temp_client,
2229 struct i2c_driver *driver)
2231 struct i2c_board_info info;
2232 struct i2c_adapter *adapter = temp_client->adapter;
2233 int addr = temp_client->addr;
2236 /* Make sure the address is valid */
2237 err = i2c_check_addr_validity(addr);
2239 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2244 /* Skip if already in use */
2245 if (i2c_check_addr_busy(adapter, addr))
2248 /* Make sure there is something at this address */
2249 if (!i2c_default_probe(adapter, addr))
2252 /* Finally call the custom detection function */
2253 memset(&info, 0, sizeof(struct i2c_board_info));
2255 err = driver->detect(temp_client, &info);
2257 /* -ENODEV is returned if the detection fails. We catch it
2258 here as this isn't an error. */
2259 return err == -ENODEV ? 0 : err;
2262 /* Consistency check */
2263 if (info.type[0] == '\0') {
2264 dev_err(&adapter->dev, "%s detection function provided "
2265 "no name for 0x%x\n", driver->driver.name,
2268 struct i2c_client *client;
2270 /* Detection succeeded, instantiate the device */
2271 if (adapter->class & I2C_CLASS_DEPRECATED)
2272 dev_warn(&adapter->dev,
2273 "This adapter will soon drop class based instantiation of devices. "
2274 "Please make sure client 0x%02x gets instantiated by other means. "
2275 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2278 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2279 info.type, info.addr);
2280 client = i2c_new_device(adapter, &info);
2282 list_add_tail(&client->detected, &driver->clients);
2284 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2285 info.type, info.addr);
2290 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2292 const unsigned short *address_list;
2293 struct i2c_client *temp_client;
2295 int adap_id = i2c_adapter_id(adapter);
2297 address_list = driver->address_list;
2298 if (!driver->detect || !address_list)
2301 /* Warn that the adapter lost class based instantiation */
2302 if (adapter->class == I2C_CLASS_DEPRECATED) {
2303 dev_dbg(&adapter->dev,
2304 "This adapter dropped support for I2C classes and "
2305 "won't auto-detect %s devices anymore. If you need it, check "
2306 "'Documentation/i2c/instantiating-devices' for alternatives.\n",
2307 driver->driver.name);
2311 /* Stop here if the classes do not match */
2312 if (!(adapter->class & driver->class))
2315 /* Set up a temporary client to help detect callback */
2316 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2319 temp_client->adapter = adapter;
2321 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2322 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
2323 "addr 0x%02x\n", adap_id, address_list[i]);
2324 temp_client->addr = address_list[i];
2325 err = i2c_detect_address(temp_client, driver);
2334 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2336 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2337 I2C_SMBUS_QUICK, NULL) >= 0;
2339 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2342 i2c_new_probed_device(struct i2c_adapter *adap,
2343 struct i2c_board_info *info,
2344 unsigned short const *addr_list,
2345 int (*probe)(struct i2c_adapter *, unsigned short addr))
2350 probe = i2c_default_probe;
2352 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2353 /* Check address validity */
2354 if (i2c_check_addr_validity(addr_list[i]) < 0) {
2355 dev_warn(&adap->dev, "Invalid 7-bit address "
2356 "0x%02x\n", addr_list[i]);
2360 /* Check address availability */
2361 if (i2c_check_addr_busy(adap, addr_list[i])) {
2362 dev_dbg(&adap->dev, "Address 0x%02x already in "
2363 "use, not probing\n", addr_list[i]);
2367 /* Test address responsiveness */
2368 if (probe(adap, addr_list[i]))
2372 if (addr_list[i] == I2C_CLIENT_END) {
2373 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2377 info->addr = addr_list[i];
2378 return i2c_new_device(adap, info);
2380 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2382 struct i2c_adapter *i2c_get_adapter(int nr)
2384 struct i2c_adapter *adapter;
2386 mutex_lock(&core_lock);
2387 adapter = idr_find(&i2c_adapter_idr, nr);
2388 if (adapter && !try_module_get(adapter->owner))
2391 mutex_unlock(&core_lock);
2394 EXPORT_SYMBOL(i2c_get_adapter);
2396 void i2c_put_adapter(struct i2c_adapter *adap)
2399 module_put(adap->owner);
2401 EXPORT_SYMBOL(i2c_put_adapter);
2403 /* The SMBus parts */
2405 #define POLY (0x1070U << 3)
2406 static u8 crc8(u16 data)
2410 for (i = 0; i < 8; i++) {
2415 return (u8)(data >> 8);
2418 /* Incremental CRC8 over count bytes in the array pointed to by p */
2419 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2423 for (i = 0; i < count; i++)
2424 crc = crc8((crc ^ p[i]) << 8);
2428 /* Assume a 7-bit address, which is reasonable for SMBus */
2429 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2431 /* The address will be sent first */
2432 u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
2433 pec = i2c_smbus_pec(pec, &addr, 1);
2435 /* The data buffer follows */
2436 return i2c_smbus_pec(pec, msg->buf, msg->len);
2439 /* Used for write only transactions */
2440 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2442 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2446 /* Return <0 on CRC error
2447 If there was a write before this read (most cases) we need to take the
2448 partial CRC from the write part into account.
2449 Note that this function does modify the message (we need to decrease the
2450 message length to hide the CRC byte from the caller). */
2451 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2453 u8 rpec = msg->buf[--msg->len];
2454 cpec = i2c_smbus_msg_pec(cpec, msg);
2457 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
2465 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2466 * @client: Handle to slave device
2468 * This executes the SMBus "receive byte" protocol, returning negative errno
2469 * else the byte received from the device.
2471 s32 i2c_smbus_read_byte(const struct i2c_client *client)
2473 union i2c_smbus_data data;
2476 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2478 I2C_SMBUS_BYTE, &data);
2479 return (status < 0) ? status : data.byte;
2481 EXPORT_SYMBOL(i2c_smbus_read_byte);
2484 * i2c_smbus_write_byte - SMBus "send byte" protocol
2485 * @client: Handle to slave device
2486 * @value: Byte to be sent
2488 * This executes the SMBus "send byte" protocol, returning negative errno
2489 * else zero on success.
2491 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2493 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2494 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2496 EXPORT_SYMBOL(i2c_smbus_write_byte);
2499 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2500 * @client: Handle to slave device
2501 * @command: Byte interpreted by slave
2503 * This executes the SMBus "read byte" protocol, returning negative errno
2504 * else a data byte received from the device.
2506 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2508 union i2c_smbus_data data;
2511 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2512 I2C_SMBUS_READ, command,
2513 I2C_SMBUS_BYTE_DATA, &data);
2514 return (status < 0) ? status : data.byte;
2516 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2519 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2520 * @client: Handle to slave device
2521 * @command: Byte interpreted by slave
2522 * @value: Byte being written
2524 * This executes the SMBus "write byte" protocol, returning negative errno
2525 * else zero on success.
2527 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
2530 union i2c_smbus_data data;
2532 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2533 I2C_SMBUS_WRITE, command,
2534 I2C_SMBUS_BYTE_DATA, &data);
2536 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
2539 * i2c_smbus_read_word_data - SMBus "read word" protocol
2540 * @client: Handle to slave device
2541 * @command: Byte interpreted by slave
2543 * This executes the SMBus "read word" protocol, returning negative errno
2544 * else a 16-bit unsigned "word" received from the device.
2546 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
2548 union i2c_smbus_data data;
2551 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2552 I2C_SMBUS_READ, command,
2553 I2C_SMBUS_WORD_DATA, &data);
2554 return (status < 0) ? status : data.word;
2556 EXPORT_SYMBOL(i2c_smbus_read_word_data);
2559 * i2c_smbus_write_word_data - SMBus "write word" protocol
2560 * @client: Handle to slave device
2561 * @command: Byte interpreted by slave
2562 * @value: 16-bit "word" being written
2564 * This executes the SMBus "write word" protocol, returning negative errno
2565 * else zero on success.
2567 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2570 union i2c_smbus_data data;
2572 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2573 I2C_SMBUS_WRITE, command,
2574 I2C_SMBUS_WORD_DATA, &data);
2576 EXPORT_SYMBOL(i2c_smbus_write_word_data);
2579 * i2c_smbus_read_block_data - SMBus "block read" protocol
2580 * @client: Handle to slave device
2581 * @command: Byte interpreted by slave
2582 * @values: Byte array into which data will be read; big enough to hold
2583 * the data returned by the slave. SMBus allows at most 32 bytes.
2585 * This executes the SMBus "block read" protocol, returning negative errno
2586 * else the number of data bytes in the slave's response.
2588 * Note that using this function requires that the client's adapter support
2589 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
2590 * support this; its emulation through I2C messaging relies on a specific
2591 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2593 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2596 union i2c_smbus_data data;
2599 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2600 I2C_SMBUS_READ, command,
2601 I2C_SMBUS_BLOCK_DATA, &data);
2605 memcpy(values, &data.block[1], data.block[0]);
2606 return data.block[0];
2608 EXPORT_SYMBOL(i2c_smbus_read_block_data);
2611 * i2c_smbus_write_block_data - SMBus "block write" protocol
2612 * @client: Handle to slave device
2613 * @command: Byte interpreted by slave
2614 * @length: Size of data block; SMBus allows at most 32 bytes
2615 * @values: Byte array which will be written.
2617 * This executes the SMBus "block write" protocol, returning negative errno
2618 * else zero on success.
2620 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2621 u8 length, const u8 *values)
2623 union i2c_smbus_data data;
2625 if (length > I2C_SMBUS_BLOCK_MAX)
2626 length = I2C_SMBUS_BLOCK_MAX;
2627 data.block[0] = length;
2628 memcpy(&data.block[1], values, length);
2629 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2630 I2C_SMBUS_WRITE, command,
2631 I2C_SMBUS_BLOCK_DATA, &data);
2633 EXPORT_SYMBOL(i2c_smbus_write_block_data);
2635 /* Returns the number of read bytes */
2636 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2637 u8 length, u8 *values)
2639 union i2c_smbus_data data;
2642 if (length > I2C_SMBUS_BLOCK_MAX)
2643 length = I2C_SMBUS_BLOCK_MAX;
2644 data.block[0] = length;
2645 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2646 I2C_SMBUS_READ, command,
2647 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2651 memcpy(values, &data.block[1], data.block[0]);
2652 return data.block[0];
2654 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2656 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2657 u8 length, const u8 *values)
2659 union i2c_smbus_data data;
2661 if (length > I2C_SMBUS_BLOCK_MAX)
2662 length = I2C_SMBUS_BLOCK_MAX;
2663 data.block[0] = length;
2664 memcpy(data.block + 1, values, length);
2665 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2666 I2C_SMBUS_WRITE, command,
2667 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2669 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2671 /* Simulate a SMBus command using the i2c protocol
2672 No checking of parameters is done! */
2673 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2674 unsigned short flags,
2675 char read_write, u8 command, int size,
2676 union i2c_smbus_data *data)
2678 /* So we need to generate a series of msgs. In the case of writing, we
2679 need to use only one message; when reading, we need two. We initialize
2680 most things with sane defaults, to keep the code below somewhat
2682 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2683 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2684 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2688 struct i2c_msg msg[2] = {
2696 .flags = flags | I2C_M_RD,
2702 msgbuf0[0] = command;
2704 case I2C_SMBUS_QUICK:
2706 /* Special case: The read/write field is used as data */
2707 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2711 case I2C_SMBUS_BYTE:
2712 if (read_write == I2C_SMBUS_READ) {
2713 /* Special case: only a read! */
2714 msg[0].flags = I2C_M_RD | flags;
2718 case I2C_SMBUS_BYTE_DATA:
2719 if (read_write == I2C_SMBUS_READ)
2723 msgbuf0[1] = data->byte;
2726 case I2C_SMBUS_WORD_DATA:
2727 if (read_write == I2C_SMBUS_READ)
2731 msgbuf0[1] = data->word & 0xff;
2732 msgbuf0[2] = data->word >> 8;
2735 case I2C_SMBUS_PROC_CALL:
2736 num = 2; /* Special case */
2737 read_write = I2C_SMBUS_READ;
2740 msgbuf0[1] = data->word & 0xff;
2741 msgbuf0[2] = data->word >> 8;
2743 case I2C_SMBUS_BLOCK_DATA:
2744 if (read_write == I2C_SMBUS_READ) {
2745 msg[1].flags |= I2C_M_RECV_LEN;
2746 msg[1].len = 1; /* block length will be added by
2747 the underlying bus driver */
2749 msg[0].len = data->block[0] + 2;
2750 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
2751 dev_err(&adapter->dev,
2752 "Invalid block write size %d\n",
2756 for (i = 1; i < msg[0].len; i++)
2757 msgbuf0[i] = data->block[i-1];
2760 case I2C_SMBUS_BLOCK_PROC_CALL:
2761 num = 2; /* Another special case */
2762 read_write = I2C_SMBUS_READ;
2763 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
2764 dev_err(&adapter->dev,
2765 "Invalid block write size %d\n",
2769 msg[0].len = data->block[0] + 2;
2770 for (i = 1; i < msg[0].len; i++)
2771 msgbuf0[i] = data->block[i-1];
2772 msg[1].flags |= I2C_M_RECV_LEN;
2773 msg[1].len = 1; /* block length will be added by
2774 the underlying bus driver */
2776 case I2C_SMBUS_I2C_BLOCK_DATA:
2777 if (read_write == I2C_SMBUS_READ) {
2778 msg[1].len = data->block[0];
2780 msg[0].len = data->block[0] + 1;
2781 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
2782 dev_err(&adapter->dev,
2783 "Invalid block write size %d\n",
2787 for (i = 1; i <= data->block[0]; i++)
2788 msgbuf0[i] = data->block[i];
2792 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
2796 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
2797 && size != I2C_SMBUS_I2C_BLOCK_DATA);
2799 /* Compute PEC if first message is a write */
2800 if (!(msg[0].flags & I2C_M_RD)) {
2801 if (num == 1) /* Write only */
2802 i2c_smbus_add_pec(&msg[0]);
2803 else /* Write followed by read */
2804 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
2806 /* Ask for PEC if last message is a read */
2807 if (msg[num-1].flags & I2C_M_RD)
2811 status = i2c_transfer(adapter, msg, num);
2815 /* Check PEC if last message is a read */
2816 if (i && (msg[num-1].flags & I2C_M_RD)) {
2817 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
2822 if (read_write == I2C_SMBUS_READ)
2824 case I2C_SMBUS_BYTE:
2825 data->byte = msgbuf0[0];
2827 case I2C_SMBUS_BYTE_DATA:
2828 data->byte = msgbuf1[0];
2830 case I2C_SMBUS_WORD_DATA:
2831 case I2C_SMBUS_PROC_CALL:
2832 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
2834 case I2C_SMBUS_I2C_BLOCK_DATA:
2835 for (i = 0; i < data->block[0]; i++)
2836 data->block[i+1] = msgbuf1[i];
2838 case I2C_SMBUS_BLOCK_DATA:
2839 case I2C_SMBUS_BLOCK_PROC_CALL:
2840 for (i = 0; i < msgbuf1[0] + 1; i++)
2841 data->block[i] = msgbuf1[i];
2848 * i2c_smbus_xfer - execute SMBus protocol operations
2849 * @adapter: Handle to I2C bus
2850 * @addr: Address of SMBus slave on that bus
2851 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
2852 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
2853 * @command: Byte interpreted by slave, for protocols which use such bytes
2854 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
2855 * @data: Data to be read or written
2857 * This executes an SMBus protocol operation, and returns a negative
2858 * errno code else zero on success.
2860 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
2861 char read_write, u8 command, int protocol,
2862 union i2c_smbus_data *data)
2864 unsigned long orig_jiffies;
2868 /* If enabled, the following two tracepoints are conditional on
2869 * read_write and protocol.
2871 trace_smbus_write(adapter, addr, flags, read_write,
2872 command, protocol, data);
2873 trace_smbus_read(adapter, addr, flags, read_write,
2876 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
2878 if (adapter->algo->smbus_xfer) {
2879 i2c_lock_adapter(adapter);
2881 /* Retry automatically on arbitration loss */
2882 orig_jiffies = jiffies;
2883 for (res = 0, try = 0; try <= adapter->retries; try++) {
2884 res = adapter->algo->smbus_xfer(adapter, addr, flags,
2885 read_write, command,
2889 if (time_after(jiffies,
2890 orig_jiffies + adapter->timeout))
2893 i2c_unlock_adapter(adapter);
2895 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
2898 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
2899 * implement native support for the SMBus operation.
2903 res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
2904 command, protocol, data);
2907 /* If enabled, the reply tracepoint is conditional on read_write. */
2908 trace_smbus_reply(adapter, addr, flags, read_write,
2909 command, protocol, data);
2910 trace_smbus_result(adapter, addr, flags, read_write,
2911 command, protocol, res);
2915 EXPORT_SYMBOL(i2c_smbus_xfer);
2917 #if IS_ENABLED(CONFIG_I2C_SLAVE)
2918 int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
2922 if (!client || !slave_cb) {
2923 WARN(1, "insufficent data\n");
2927 if (!(client->flags & I2C_CLIENT_TEN)) {
2928 /* Enforce stricter address checking */
2929 ret = i2c_check_addr_validity(client->addr);
2931 dev_err(&client->dev, "%s: invalid address\n", __func__);
2936 if (!client->adapter->algo->reg_slave) {
2937 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
2941 client->slave_cb = slave_cb;
2943 i2c_lock_adapter(client->adapter);
2944 ret = client->adapter->algo->reg_slave(client);
2945 i2c_unlock_adapter(client->adapter);
2948 client->slave_cb = NULL;
2949 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
2954 EXPORT_SYMBOL_GPL(i2c_slave_register);
2956 int i2c_slave_unregister(struct i2c_client *client)
2960 if (!client->adapter->algo->unreg_slave) {
2961 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
2965 i2c_lock_adapter(client->adapter);
2966 ret = client->adapter->algo->unreg_slave(client);
2967 i2c_unlock_adapter(client->adapter);
2970 client->slave_cb = NULL;
2972 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
2976 EXPORT_SYMBOL_GPL(i2c_slave_unregister);
2979 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2980 MODULE_DESCRIPTION("I2C-Bus main module");
2981 MODULE_LICENSE("GPL");