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>
29 #include <linux/module.h>
30 #include <linux/kernel.h>
31 #include <linux/delay.h>
32 #include <linux/errno.h>
33 #include <linux/gpio.h>
34 #include <linux/slab.h>
35 #include <linux/i2c.h>
36 #include <linux/init.h>
37 #include <linux/idr.h>
38 #include <linux/mutex.h>
40 #include <linux/of_device.h>
41 #include <linux/of_irq.h>
42 #include <linux/clk/clk-conf.h>
43 #include <linux/completion.h>
44 #include <linux/hardirq.h>
45 #include <linux/irqflags.h>
46 #include <linux/rwsem.h>
47 #include <linux/pm_runtime.h>
48 #include <linux/pm_domain.h>
49 #include <linux/acpi.h>
50 #include <linux/jump_label.h>
51 #include <asm/uaccess.h>
55 #define CREATE_TRACE_POINTS
56 #include <trace/events/i2c.h>
58 /* core_lock protects i2c_adapter_idr, and guarantees
59 that device detection, deletion of detected devices, and attach_adapter
60 calls are serialized */
61 static DEFINE_MUTEX(core_lock);
62 static DEFINE_IDR(i2c_adapter_idr);
64 static struct device_type i2c_client_type;
65 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
67 static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
69 void i2c_transfer_trace_reg(void)
71 static_key_slow_inc(&i2c_trace_msg);
74 void i2c_transfer_trace_unreg(void)
76 static_key_slow_dec(&i2c_trace_msg);
79 #if defined(CONFIG_ACPI)
80 struct acpi_i2c_handler_data {
81 struct acpi_connection_info info;
82 struct i2c_adapter *adapter;
95 static int acpi_i2c_add_resource(struct acpi_resource *ares, void *data)
97 struct i2c_board_info *info = data;
99 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
100 struct acpi_resource_i2c_serialbus *sb;
102 sb = &ares->data.i2c_serial_bus;
103 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_I2C) {
104 info->addr = sb->slave_address;
105 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
106 info->flags |= I2C_CLIENT_TEN;
108 } else if (info->irq < 0) {
111 if (acpi_dev_resource_interrupt(ares, 0, &r))
115 /* Tell the ACPI core to skip this resource */
119 static acpi_status acpi_i2c_add_device(acpi_handle handle, u32 level,
120 void *data, void **return_value)
122 struct i2c_adapter *adapter = data;
123 struct list_head resource_list;
124 struct i2c_board_info info;
125 struct acpi_device *adev;
128 if (acpi_bus_get_device(handle, &adev))
130 if (acpi_bus_get_status(adev) || !adev->status.present)
133 memset(&info, 0, sizeof(info));
134 info.acpi_node.companion = adev;
137 INIT_LIST_HEAD(&resource_list);
138 ret = acpi_dev_get_resources(adev, &resource_list,
139 acpi_i2c_add_resource, &info);
140 acpi_dev_free_resource_list(&resource_list);
142 if (ret < 0 || !info.addr)
145 adev->power.flags.ignore_parent = true;
146 strlcpy(info.type, dev_name(&adev->dev), sizeof(info.type));
147 if (!i2c_new_device(adapter, &info)) {
148 adev->power.flags.ignore_parent = false;
149 dev_err(&adapter->dev,
150 "failed to add I2C device %s from ACPI\n",
151 dev_name(&adev->dev));
158 * acpi_i2c_register_devices - enumerate I2C slave devices behind adapter
159 * @adap: pointer to adapter
161 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
162 * namespace. When a device is found it will be added to the Linux device
163 * model and bound to the corresponding ACPI handle.
165 static void acpi_i2c_register_devices(struct i2c_adapter *adap)
170 if (!adap->dev.parent)
173 handle = ACPI_HANDLE(adap->dev.parent);
177 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
178 acpi_i2c_add_device, NULL,
180 if (ACPI_FAILURE(status))
181 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
184 #else /* CONFIG_ACPI */
185 static inline void acpi_i2c_register_devices(struct i2c_adapter *adap) { }
186 #endif /* CONFIG_ACPI */
188 #ifdef CONFIG_ACPI_I2C_OPREGION
189 static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
190 u8 cmd, u8 *data, u8 data_len)
193 struct i2c_msg msgs[2];
197 buffer = kzalloc(data_len, GFP_KERNEL);
201 msgs[0].addr = client->addr;
202 msgs[0].flags = client->flags;
206 msgs[1].addr = client->addr;
207 msgs[1].flags = client->flags | I2C_M_RD;
208 msgs[1].len = data_len;
209 msgs[1].buf = buffer;
211 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
213 dev_err(&client->adapter->dev, "i2c read failed\n");
215 memcpy(data, buffer, data_len);
221 static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
222 u8 cmd, u8 *data, u8 data_len)
225 struct i2c_msg msgs[1];
229 buffer = kzalloc(data_len + 1, GFP_KERNEL);
234 memcpy(buffer + 1, data, data_len);
236 msgs[0].addr = client->addr;
237 msgs[0].flags = client->flags;
238 msgs[0].len = data_len + 1;
239 msgs[0].buf = buffer;
241 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
243 dev_err(&client->adapter->dev, "i2c write failed\n");
250 acpi_i2c_space_handler(u32 function, acpi_physical_address command,
251 u32 bits, u64 *value64,
252 void *handler_context, void *region_context)
254 struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
255 struct acpi_i2c_handler_data *data = handler_context;
256 struct acpi_connection_info *info = &data->info;
257 struct acpi_resource_i2c_serialbus *sb;
258 struct i2c_adapter *adapter = data->adapter;
259 struct i2c_client client;
260 struct acpi_resource *ares;
261 u32 accessor_type = function >> 16;
262 u8 action = function & ACPI_IO_MASK;
263 acpi_status ret = AE_OK;
266 ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
267 if (ACPI_FAILURE(ret))
270 if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
271 ret = AE_BAD_PARAMETER;
275 sb = &ares->data.i2c_serial_bus;
276 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
277 ret = AE_BAD_PARAMETER;
281 memset(&client, 0, sizeof(client));
282 client.adapter = adapter;
283 client.addr = sb->slave_address;
286 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
287 client.flags |= I2C_CLIENT_TEN;
289 switch (accessor_type) {
290 case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
291 if (action == ACPI_READ) {
292 status = i2c_smbus_read_byte(&client);
298 status = i2c_smbus_write_byte(&client, gsb->bdata);
302 case ACPI_GSB_ACCESS_ATTRIB_BYTE:
303 if (action == ACPI_READ) {
304 status = i2c_smbus_read_byte_data(&client, command);
310 status = i2c_smbus_write_byte_data(&client, command,
315 case ACPI_GSB_ACCESS_ATTRIB_WORD:
316 if (action == ACPI_READ) {
317 status = i2c_smbus_read_word_data(&client, command);
323 status = i2c_smbus_write_word_data(&client, command,
328 case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
329 if (action == ACPI_READ) {
330 status = i2c_smbus_read_block_data(&client, command,
337 status = i2c_smbus_write_block_data(&client, command,
338 gsb->len, gsb->data);
342 case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
343 if (action == ACPI_READ) {
344 status = acpi_gsb_i2c_read_bytes(&client, command,
345 gsb->data, info->access_length);
349 status = acpi_gsb_i2c_write_bytes(&client, command,
350 gsb->data, info->access_length);
355 pr_info("protocol(0x%02x) is not supported.\n", accessor_type);
356 ret = AE_BAD_PARAMETER;
360 gsb->status = status;
368 static int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
371 struct acpi_i2c_handler_data *data;
374 if (!adapter->dev.parent)
377 handle = ACPI_HANDLE(adapter->dev.parent);
382 data = kzalloc(sizeof(struct acpi_i2c_handler_data),
387 data->adapter = adapter;
388 status = acpi_bus_attach_private_data(handle, (void *)data);
389 if (ACPI_FAILURE(status)) {
394 status = acpi_install_address_space_handler(handle,
395 ACPI_ADR_SPACE_GSBUS,
396 &acpi_i2c_space_handler,
399 if (ACPI_FAILURE(status)) {
400 dev_err(&adapter->dev, "Error installing i2c space handler\n");
401 acpi_bus_detach_private_data(handle);
406 acpi_walk_dep_device_list(handle);
410 static void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
413 struct acpi_i2c_handler_data *data;
416 if (!adapter->dev.parent)
419 handle = ACPI_HANDLE(adapter->dev.parent);
424 acpi_remove_address_space_handler(handle,
425 ACPI_ADR_SPACE_GSBUS,
426 &acpi_i2c_space_handler);
428 status = acpi_bus_get_private_data(handle, (void **)&data);
429 if (ACPI_SUCCESS(status))
432 acpi_bus_detach_private_data(handle);
434 #else /* CONFIG_ACPI_I2C_OPREGION */
435 static inline void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
438 static inline int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
440 #endif /* CONFIG_ACPI_I2C_OPREGION */
442 /* ------------------------------------------------------------------------- */
444 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
445 const struct i2c_client *client)
447 while (id->name[0]) {
448 if (strcmp(client->name, id->name) == 0)
455 static int i2c_device_match(struct device *dev, struct device_driver *drv)
457 struct i2c_client *client = i2c_verify_client(dev);
458 struct i2c_driver *driver;
463 /* Attempt an OF style match */
464 if (of_driver_match_device(dev, drv))
467 /* Then ACPI style match */
468 if (acpi_driver_match_device(dev, drv))
471 driver = to_i2c_driver(drv);
472 /* match on an id table if there is one */
473 if (driver->id_table)
474 return i2c_match_id(driver->id_table, client) != NULL;
480 /* uevent helps with hotplug: modprobe -q $(MODALIAS) */
481 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
483 struct i2c_client *client = to_i2c_client(dev);
486 rc = acpi_device_uevent_modalias(dev, env);
490 if (add_uevent_var(env, "MODALIAS=%s%s",
491 I2C_MODULE_PREFIX, client->name))
493 dev_dbg(dev, "uevent\n");
497 /* i2c bus recovery routines */
498 static int get_scl_gpio_value(struct i2c_adapter *adap)
500 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
503 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
505 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
508 static int get_sda_gpio_value(struct i2c_adapter *adap)
510 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
513 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
515 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
516 struct device *dev = &adap->dev;
519 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
520 GPIOF_OUT_INIT_HIGH, "i2c-scl");
522 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
527 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
528 /* work without SDA polling */
529 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
538 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
540 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
543 gpio_free(bri->sda_gpio);
545 gpio_free(bri->scl_gpio);
549 * We are generating clock pulses. ndelay() determines durating of clk pulses.
550 * We will generate clock with rate 100 KHz and so duration of both clock levels
551 * is: delay in ns = (10^6 / 100) / 2
553 #define RECOVERY_NDELAY 5000
554 #define RECOVERY_CLK_CNT 9
556 static int i2c_generic_recovery(struct i2c_adapter *adap)
558 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
559 int i = 0, val = 1, ret = 0;
561 if (bri->prepare_recovery)
562 bri->prepare_recovery(bri);
565 * By this time SCL is high, as we need to give 9 falling-rising edges
567 while (i++ < RECOVERY_CLK_CNT * 2) {
569 /* Break if SDA is high */
570 if (bri->get_sda && bri->get_sda(adap))
572 /* SCL shouldn't be low here */
573 if (!bri->get_scl(adap)) {
575 "SCL is stuck low, exit recovery\n");
582 bri->set_scl(adap, val);
583 ndelay(RECOVERY_NDELAY);
586 if (bri->unprepare_recovery)
587 bri->unprepare_recovery(bri);
592 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
594 adap->bus_recovery_info->set_scl(adap, 1);
595 return i2c_generic_recovery(adap);
598 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
602 ret = i2c_get_gpios_for_recovery(adap);
606 ret = i2c_generic_recovery(adap);
607 i2c_put_gpios_for_recovery(adap);
612 int i2c_recover_bus(struct i2c_adapter *adap)
614 if (!adap->bus_recovery_info)
617 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
618 return adap->bus_recovery_info->recover_bus(adap);
621 static int i2c_device_probe(struct device *dev)
623 struct i2c_client *client = i2c_verify_client(dev);
624 struct i2c_driver *driver;
630 driver = to_i2c_driver(dev->driver);
631 if (!driver->probe || !driver->id_table)
634 if (!device_can_wakeup(&client->dev))
635 device_init_wakeup(&client->dev,
636 client->flags & I2C_CLIENT_WAKE);
637 dev_dbg(dev, "probe\n");
639 status = of_clk_set_defaults(dev->of_node, false);
643 status = dev_pm_domain_attach(&client->dev, true);
644 if (status != -EPROBE_DEFER) {
645 status = driver->probe(client, i2c_match_id(driver->id_table,
648 dev_pm_domain_detach(&client->dev, true);
654 static int i2c_device_remove(struct device *dev)
656 struct i2c_client *client = i2c_verify_client(dev);
657 struct i2c_driver *driver;
660 if (!client || !dev->driver)
663 driver = to_i2c_driver(dev->driver);
664 if (driver->remove) {
665 dev_dbg(dev, "remove\n");
666 status = driver->remove(client);
670 irq_dispose_mapping(client->irq);
672 dev_pm_domain_detach(&client->dev, true);
676 static void i2c_device_shutdown(struct device *dev)
678 struct i2c_client *client = i2c_verify_client(dev);
679 struct i2c_driver *driver;
681 if (!client || !dev->driver)
683 driver = to_i2c_driver(dev->driver);
684 if (driver->shutdown)
685 driver->shutdown(client);
688 #ifdef CONFIG_PM_SLEEP
689 static int i2c_legacy_suspend(struct device *dev, pm_message_t mesg)
691 struct i2c_client *client = i2c_verify_client(dev);
692 struct i2c_driver *driver;
694 if (!client || !dev->driver)
696 driver = to_i2c_driver(dev->driver);
697 if (!driver->suspend)
699 return driver->suspend(client, mesg);
702 static int i2c_legacy_resume(struct device *dev)
704 struct i2c_client *client = i2c_verify_client(dev);
705 struct i2c_driver *driver;
707 if (!client || !dev->driver)
709 driver = to_i2c_driver(dev->driver);
712 return driver->resume(client);
715 static int i2c_device_pm_suspend(struct device *dev)
717 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
720 return pm_generic_suspend(dev);
722 return i2c_legacy_suspend(dev, PMSG_SUSPEND);
725 static int i2c_device_pm_resume(struct device *dev)
727 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
730 return pm_generic_resume(dev);
732 return i2c_legacy_resume(dev);
735 static int i2c_device_pm_freeze(struct device *dev)
737 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
740 return pm_generic_freeze(dev);
742 return i2c_legacy_suspend(dev, PMSG_FREEZE);
745 static int i2c_device_pm_thaw(struct device *dev)
747 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
750 return pm_generic_thaw(dev);
752 return i2c_legacy_resume(dev);
755 static int i2c_device_pm_poweroff(struct device *dev)
757 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
760 return pm_generic_poweroff(dev);
762 return i2c_legacy_suspend(dev, PMSG_HIBERNATE);
765 static int i2c_device_pm_restore(struct device *dev)
767 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
770 return pm_generic_restore(dev);
772 return i2c_legacy_resume(dev);
774 #else /* !CONFIG_PM_SLEEP */
775 #define i2c_device_pm_suspend NULL
776 #define i2c_device_pm_resume NULL
777 #define i2c_device_pm_freeze NULL
778 #define i2c_device_pm_thaw NULL
779 #define i2c_device_pm_poweroff NULL
780 #define i2c_device_pm_restore NULL
781 #endif /* !CONFIG_PM_SLEEP */
783 static void i2c_client_dev_release(struct device *dev)
785 kfree(to_i2c_client(dev));
789 show_name(struct device *dev, struct device_attribute *attr, char *buf)
791 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
792 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
796 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
798 struct i2c_client *client = to_i2c_client(dev);
801 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
805 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
808 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
809 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
811 static struct attribute *i2c_dev_attrs[] = {
813 /* modalias helps coldplug: modprobe $(cat .../modalias) */
814 &dev_attr_modalias.attr,
818 static struct attribute_group i2c_dev_attr_group = {
819 .attrs = i2c_dev_attrs,
822 static const struct attribute_group *i2c_dev_attr_groups[] = {
827 static const struct dev_pm_ops i2c_device_pm_ops = {
828 .suspend = i2c_device_pm_suspend,
829 .resume = i2c_device_pm_resume,
830 .freeze = i2c_device_pm_freeze,
831 .thaw = i2c_device_pm_thaw,
832 .poweroff = i2c_device_pm_poweroff,
833 .restore = i2c_device_pm_restore,
835 pm_generic_runtime_suspend,
836 pm_generic_runtime_resume,
841 struct bus_type i2c_bus_type = {
843 .match = i2c_device_match,
844 .probe = i2c_device_probe,
845 .remove = i2c_device_remove,
846 .shutdown = i2c_device_shutdown,
847 .pm = &i2c_device_pm_ops,
849 EXPORT_SYMBOL_GPL(i2c_bus_type);
851 static struct device_type i2c_client_type = {
852 .groups = i2c_dev_attr_groups,
853 .uevent = i2c_device_uevent,
854 .release = i2c_client_dev_release,
859 * i2c_verify_client - return parameter as i2c_client, or NULL
860 * @dev: device, probably from some driver model iterator
862 * When traversing the driver model tree, perhaps using driver model
863 * iterators like @device_for_each_child(), you can't assume very much
864 * about the nodes you find. Use this function to avoid oopses caused
865 * by wrongly treating some non-I2C device as an i2c_client.
867 struct i2c_client *i2c_verify_client(struct device *dev)
869 return (dev->type == &i2c_client_type)
873 EXPORT_SYMBOL(i2c_verify_client);
876 /* This is a permissive address validity check, I2C address map constraints
877 * are purposely not enforced, except for the general call address. */
878 static int i2c_check_client_addr_validity(const struct i2c_client *client)
880 if (client->flags & I2C_CLIENT_TEN) {
881 /* 10-bit address, all values are valid */
882 if (client->addr > 0x3ff)
885 /* 7-bit address, reject the general call address */
886 if (client->addr == 0x00 || client->addr > 0x7f)
892 /* And this is a strict address validity check, used when probing. If a
893 * device uses a reserved address, then it shouldn't be probed. 7-bit
894 * addressing is assumed, 10-bit address devices are rare and should be
895 * explicitly enumerated. */
896 static int i2c_check_addr_validity(unsigned short addr)
899 * Reserved addresses per I2C specification:
900 * 0x00 General call address / START byte
902 * 0x02 Reserved for different bus format
903 * 0x03 Reserved for future purposes
904 * 0x04-0x07 Hs-mode master code
905 * 0x78-0x7b 10-bit slave addressing
906 * 0x7c-0x7f Reserved for future purposes
908 if (addr < 0x08 || addr > 0x77)
913 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
915 struct i2c_client *client = i2c_verify_client(dev);
916 int addr = *(int *)addrp;
918 if (client && client->addr == addr)
923 /* walk up mux tree */
924 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
926 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
929 result = device_for_each_child(&adapter->dev, &addr,
930 __i2c_check_addr_busy);
932 if (!result && parent)
933 result = i2c_check_mux_parents(parent, addr);
938 /* recurse down mux tree */
939 static int i2c_check_mux_children(struct device *dev, void *addrp)
943 if (dev->type == &i2c_adapter_type)
944 result = device_for_each_child(dev, addrp,
945 i2c_check_mux_children);
947 result = __i2c_check_addr_busy(dev, addrp);
952 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
954 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
958 result = i2c_check_mux_parents(parent, addr);
961 result = device_for_each_child(&adapter->dev, &addr,
962 i2c_check_mux_children);
968 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
969 * @adapter: Target I2C bus segment
971 void i2c_lock_adapter(struct i2c_adapter *adapter)
973 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
976 i2c_lock_adapter(parent);
978 rt_mutex_lock(&adapter->bus_lock);
980 EXPORT_SYMBOL_GPL(i2c_lock_adapter);
983 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
984 * @adapter: Target I2C bus segment
986 static int i2c_trylock_adapter(struct i2c_adapter *adapter)
988 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
991 return i2c_trylock_adapter(parent);
993 return rt_mutex_trylock(&adapter->bus_lock);
997 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
998 * @adapter: Target I2C bus segment
1000 void i2c_unlock_adapter(struct i2c_adapter *adapter)
1002 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1005 i2c_unlock_adapter(parent);
1007 rt_mutex_unlock(&adapter->bus_lock);
1009 EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
1011 static void i2c_dev_set_name(struct i2c_adapter *adap,
1012 struct i2c_client *client)
1014 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
1017 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
1021 /* For 10-bit clients, add an arbitrary offset to avoid collisions */
1022 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
1023 client->addr | ((client->flags & I2C_CLIENT_TEN)
1028 * i2c_new_device - instantiate an i2c device
1029 * @adap: the adapter managing the device
1030 * @info: describes one I2C device; bus_num is ignored
1031 * Context: can sleep
1033 * Create an i2c device. Binding is handled through driver model
1034 * probe()/remove() methods. A driver may be bound to this device when we
1035 * return from this function, or any later moment (e.g. maybe hotplugging will
1036 * load the driver module). This call is not appropriate for use by mainboard
1037 * initialization logic, which usually runs during an arch_initcall() long
1038 * before any i2c_adapter could exist.
1040 * This returns the new i2c client, which may be saved for later use with
1041 * i2c_unregister_device(); or NULL to indicate an error.
1044 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1046 struct i2c_client *client;
1049 client = kzalloc(sizeof *client, GFP_KERNEL);
1053 client->adapter = adap;
1055 client->dev.platform_data = info->platform_data;
1058 client->dev.archdata = *info->archdata;
1060 client->flags = info->flags;
1061 client->addr = info->addr;
1062 client->irq = info->irq;
1064 strlcpy(client->name, info->type, sizeof(client->name));
1066 /* Check for address validity */
1067 status = i2c_check_client_addr_validity(client);
1069 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1070 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1071 goto out_err_silent;
1074 /* Check for address business */
1075 status = i2c_check_addr_busy(adap, client->addr);
1079 client->dev.parent = &client->adapter->dev;
1080 client->dev.bus = &i2c_bus_type;
1081 client->dev.type = &i2c_client_type;
1082 client->dev.of_node = info->of_node;
1083 ACPI_COMPANION_SET(&client->dev, info->acpi_node.companion);
1085 i2c_dev_set_name(adap, client);
1086 status = device_register(&client->dev);
1090 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1091 client->name, dev_name(&client->dev));
1096 dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
1097 "(%d)\n", client->name, client->addr, status);
1102 EXPORT_SYMBOL_GPL(i2c_new_device);
1106 * i2c_unregister_device - reverse effect of i2c_new_device()
1107 * @client: value returned from i2c_new_device()
1108 * Context: can sleep
1110 void i2c_unregister_device(struct i2c_client *client)
1112 device_unregister(&client->dev);
1114 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1117 static const struct i2c_device_id dummy_id[] = {
1122 static int dummy_probe(struct i2c_client *client,
1123 const struct i2c_device_id *id)
1128 static int dummy_remove(struct i2c_client *client)
1133 static struct i2c_driver dummy_driver = {
1134 .driver.name = "dummy",
1135 .probe = dummy_probe,
1136 .remove = dummy_remove,
1137 .id_table = dummy_id,
1141 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1142 * @adapter: the adapter managing the device
1143 * @address: seven bit address to be used
1144 * Context: can sleep
1146 * This returns an I2C client bound to the "dummy" driver, intended for use
1147 * with devices that consume multiple addresses. Examples of such chips
1148 * include various EEPROMS (like 24c04 and 24c08 models).
1150 * These dummy devices have two main uses. First, most I2C and SMBus calls
1151 * except i2c_transfer() need a client handle; the dummy will be that handle.
1152 * And second, this prevents the specified address from being bound to a
1155 * This returns the new i2c client, which should be saved for later use with
1156 * i2c_unregister_device(); or NULL to indicate an error.
1158 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1160 struct i2c_board_info info = {
1161 I2C_BOARD_INFO("dummy", address),
1164 return i2c_new_device(adapter, &info);
1166 EXPORT_SYMBOL_GPL(i2c_new_dummy);
1168 /* ------------------------------------------------------------------------- */
1170 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1172 static void i2c_adapter_dev_release(struct device *dev)
1174 struct i2c_adapter *adap = to_i2c_adapter(dev);
1175 complete(&adap->dev_released);
1179 * This function is only needed for mutex_lock_nested, so it is never
1180 * called unless locking correctness checking is enabled. Thus we
1181 * make it inline to avoid a compiler warning. That's what gcc ends up
1184 static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1186 unsigned int depth = 0;
1188 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1195 * Let users instantiate I2C devices through sysfs. This can be used when
1196 * platform initialization code doesn't contain the proper data for
1197 * whatever reason. Also useful for drivers that do device detection and
1198 * detection fails, either because the device uses an unexpected address,
1199 * or this is a compatible device with different ID register values.
1201 * Parameter checking may look overzealous, but we really don't want
1202 * the user to provide incorrect parameters.
1205 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1206 const char *buf, size_t count)
1208 struct i2c_adapter *adap = to_i2c_adapter(dev);
1209 struct i2c_board_info info;
1210 struct i2c_client *client;
1214 memset(&info, 0, sizeof(struct i2c_board_info));
1216 blank = strchr(buf, ' ');
1218 dev_err(dev, "%s: Missing parameters\n", "new_device");
1221 if (blank - buf > I2C_NAME_SIZE - 1) {
1222 dev_err(dev, "%s: Invalid device name\n", "new_device");
1225 memcpy(info.type, buf, blank - buf);
1227 /* Parse remaining parameters, reject extra parameters */
1228 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1230 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1233 if (res > 1 && end != '\n') {
1234 dev_err(dev, "%s: Extra parameters\n", "new_device");
1238 client = i2c_new_device(adap, &info);
1242 /* Keep track of the added device */
1243 mutex_lock(&adap->userspace_clients_lock);
1244 list_add_tail(&client->detected, &adap->userspace_clients);
1245 mutex_unlock(&adap->userspace_clients_lock);
1246 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1247 info.type, info.addr);
1253 * And of course let the users delete the devices they instantiated, if
1254 * they got it wrong. This interface can only be used to delete devices
1255 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1256 * don't delete devices to which some kernel code still has references.
1258 * Parameter checking may look overzealous, but we really don't want
1259 * the user to delete the wrong device.
1262 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1263 const char *buf, size_t count)
1265 struct i2c_adapter *adap = to_i2c_adapter(dev);
1266 struct i2c_client *client, *next;
1267 unsigned short addr;
1271 /* Parse parameters, reject extra parameters */
1272 res = sscanf(buf, "%hi%c", &addr, &end);
1274 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1277 if (res > 1 && end != '\n') {
1278 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1282 /* Make sure the device was added through sysfs */
1284 mutex_lock_nested(&adap->userspace_clients_lock,
1285 i2c_adapter_depth(adap));
1286 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1288 if (client->addr == addr) {
1289 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1290 "delete_device", client->name, client->addr);
1292 list_del(&client->detected);
1293 i2c_unregister_device(client);
1298 mutex_unlock(&adap->userspace_clients_lock);
1301 dev_err(dev, "%s: Can't find device in list\n",
1306 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1307 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1308 i2c_sysfs_delete_device);
1310 static struct attribute *i2c_adapter_attrs[] = {
1311 &dev_attr_name.attr,
1312 &dev_attr_new_device.attr,
1313 &dev_attr_delete_device.attr,
1317 static struct attribute_group i2c_adapter_attr_group = {
1318 .attrs = i2c_adapter_attrs,
1321 static const struct attribute_group *i2c_adapter_attr_groups[] = {
1322 &i2c_adapter_attr_group,
1326 struct device_type i2c_adapter_type = {
1327 .groups = i2c_adapter_attr_groups,
1328 .release = i2c_adapter_dev_release,
1330 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1333 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1334 * @dev: device, probably from some driver model iterator
1336 * When traversing the driver model tree, perhaps using driver model
1337 * iterators like @device_for_each_child(), you can't assume very much
1338 * about the nodes you find. Use this function to avoid oopses caused
1339 * by wrongly treating some non-I2C device as an i2c_adapter.
1341 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1343 return (dev->type == &i2c_adapter_type)
1344 ? to_i2c_adapter(dev)
1347 EXPORT_SYMBOL(i2c_verify_adapter);
1349 #ifdef CONFIG_I2C_COMPAT
1350 static struct class_compat *i2c_adapter_compat_class;
1353 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1355 struct i2c_devinfo *devinfo;
1357 down_read(&__i2c_board_lock);
1358 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1359 if (devinfo->busnum == adapter->nr
1360 && !i2c_new_device(adapter,
1361 &devinfo->board_info))
1362 dev_err(&adapter->dev,
1363 "Can't create device at 0x%02x\n",
1364 devinfo->board_info.addr);
1366 up_read(&__i2c_board_lock);
1369 /* OF support code */
1371 #if IS_ENABLED(CONFIG_OF)
1372 static void of_i2c_register_devices(struct i2c_adapter *adap)
1375 struct device_node *node;
1377 /* Only register child devices if the adapter has a node pointer set */
1378 if (!adap->dev.of_node)
1381 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1383 for_each_available_child_of_node(adap->dev.of_node, node) {
1384 struct i2c_board_info info = {};
1385 struct dev_archdata dev_ad = {};
1389 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1391 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1392 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1397 addr = of_get_property(node, "reg", &len);
1398 if (!addr || (len < sizeof(int))) {
1399 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1404 info.addr = be32_to_cpup(addr);
1405 if (info.addr > (1 << 10) - 1) {
1406 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1407 info.addr, node->full_name);
1411 info.irq = irq_of_parse_and_map(node, 0);
1412 info.of_node = of_node_get(node);
1413 info.archdata = &dev_ad;
1415 if (of_get_property(node, "wakeup-source", NULL))
1416 info.flags |= I2C_CLIENT_WAKE;
1418 request_module("%s%s", I2C_MODULE_PREFIX, info.type);
1420 result = i2c_new_device(adap, &info);
1421 if (result == NULL) {
1422 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1425 irq_dispose_mapping(info.irq);
1431 static int of_dev_node_match(struct device *dev, void *data)
1433 return dev->of_node == data;
1436 /* must call put_device() when done with returned i2c_client device */
1437 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1441 dev = bus_find_device(&i2c_bus_type, NULL, node,
1446 return i2c_verify_client(dev);
1448 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1450 /* must call put_device() when done with returned i2c_adapter device */
1451 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1455 dev = bus_find_device(&i2c_bus_type, NULL, node,
1460 return i2c_verify_adapter(dev);
1462 EXPORT_SYMBOL(of_find_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 #ifdef CONFIG_I2C_COMPAT
1530 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1533 dev_warn(&adap->dev,
1534 "Failed to create compatibility class link\n");
1537 /* bus recovery specific initialization */
1538 if (adap->bus_recovery_info) {
1539 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
1541 if (!bri->recover_bus) {
1542 dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
1543 adap->bus_recovery_info = NULL;
1547 /* Generic GPIO recovery */
1548 if (bri->recover_bus == i2c_generic_gpio_recovery) {
1549 if (!gpio_is_valid(bri->scl_gpio)) {
1550 dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
1551 adap->bus_recovery_info = NULL;
1555 if (gpio_is_valid(bri->sda_gpio))
1556 bri->get_sda = get_sda_gpio_value;
1558 bri->get_sda = NULL;
1560 bri->get_scl = get_scl_gpio_value;
1561 bri->set_scl = set_scl_gpio_value;
1562 } else if (!bri->set_scl || !bri->get_scl) {
1563 /* Generic SCL recovery */
1564 dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
1565 adap->bus_recovery_info = NULL;
1570 /* create pre-declared device nodes */
1571 of_i2c_register_devices(adap);
1572 acpi_i2c_register_devices(adap);
1573 acpi_i2c_install_space_handler(adap);
1575 if (adap->nr < __i2c_first_dynamic_bus_num)
1576 i2c_scan_static_board_info(adap);
1578 /* Notify drivers */
1579 mutex_lock(&core_lock);
1580 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1581 mutex_unlock(&core_lock);
1586 mutex_lock(&core_lock);
1587 idr_remove(&i2c_adapter_idr, adap->nr);
1588 mutex_unlock(&core_lock);
1593 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1594 * @adap: the adapter to register (with adap->nr initialized)
1595 * Context: can sleep
1597 * See i2c_add_numbered_adapter() for details.
1599 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1603 mutex_lock(&core_lock);
1604 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1,
1606 mutex_unlock(&core_lock);
1608 return id == -ENOSPC ? -EBUSY : id;
1610 return i2c_register_adapter(adap);
1614 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1615 * @adapter: the adapter to add
1616 * Context: can sleep
1618 * This routine is used to declare an I2C adapter when its bus number
1619 * doesn't matter or when its bus number is specified by an dt alias.
1620 * Examples of bases when the bus number doesn't matter: I2C adapters
1621 * dynamically added by USB links or PCI plugin cards.
1623 * When this returns zero, a new bus number was allocated and stored
1624 * in adap->nr, and the specified adapter became available for clients.
1625 * Otherwise, a negative errno value is returned.
1627 int i2c_add_adapter(struct i2c_adapter *adapter)
1629 struct device *dev = &adapter->dev;
1633 id = of_alias_get_id(dev->of_node, "i2c");
1636 return __i2c_add_numbered_adapter(adapter);
1640 mutex_lock(&core_lock);
1641 id = idr_alloc(&i2c_adapter_idr, adapter,
1642 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1643 mutex_unlock(&core_lock);
1649 return i2c_register_adapter(adapter);
1651 EXPORT_SYMBOL(i2c_add_adapter);
1654 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1655 * @adap: the adapter to register (with adap->nr initialized)
1656 * Context: can sleep
1658 * This routine is used to declare an I2C adapter when its bus number
1659 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1660 * or otherwise built in to the system's mainboard, and where i2c_board_info
1661 * is used to properly configure I2C devices.
1663 * If the requested bus number is set to -1, then this function will behave
1664 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1666 * If no devices have pre-been declared for this bus, then be sure to
1667 * register the adapter before any dynamically allocated ones. Otherwise
1668 * the required bus ID may not be available.
1670 * When this returns zero, the specified adapter became available for
1671 * clients using the bus number provided in adap->nr. Also, the table
1672 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1673 * and the appropriate driver model device nodes are created. Otherwise, a
1674 * negative errno value is returned.
1676 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1678 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1679 return i2c_add_adapter(adap);
1681 return __i2c_add_numbered_adapter(adap);
1683 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1685 static void i2c_do_del_adapter(struct i2c_driver *driver,
1686 struct i2c_adapter *adapter)
1688 struct i2c_client *client, *_n;
1690 /* Remove the devices we created ourselves as the result of hardware
1691 * probing (using a driver's detect method) */
1692 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1693 if (client->adapter == adapter) {
1694 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1695 client->name, client->addr);
1696 list_del(&client->detected);
1697 i2c_unregister_device(client);
1702 static int __unregister_client(struct device *dev, void *dummy)
1704 struct i2c_client *client = i2c_verify_client(dev);
1705 if (client && strcmp(client->name, "dummy"))
1706 i2c_unregister_device(client);
1710 static int __unregister_dummy(struct device *dev, void *dummy)
1712 struct i2c_client *client = i2c_verify_client(dev);
1714 i2c_unregister_device(client);
1718 static int __process_removed_adapter(struct device_driver *d, void *data)
1720 i2c_do_del_adapter(to_i2c_driver(d), data);
1725 * i2c_del_adapter - unregister I2C adapter
1726 * @adap: the adapter being unregistered
1727 * Context: can sleep
1729 * This unregisters an I2C adapter which was previously registered
1730 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1732 void i2c_del_adapter(struct i2c_adapter *adap)
1734 struct i2c_adapter *found;
1735 struct i2c_client *client, *next;
1737 /* First make sure that this adapter was ever added */
1738 mutex_lock(&core_lock);
1739 found = idr_find(&i2c_adapter_idr, adap->nr);
1740 mutex_unlock(&core_lock);
1741 if (found != adap) {
1742 pr_debug("i2c-core: attempting to delete unregistered "
1743 "adapter [%s]\n", adap->name);
1747 acpi_i2c_remove_space_handler(adap);
1748 /* Tell drivers about this removal */
1749 mutex_lock(&core_lock);
1750 bus_for_each_drv(&i2c_bus_type, NULL, adap,
1751 __process_removed_adapter);
1752 mutex_unlock(&core_lock);
1754 /* Remove devices instantiated from sysfs */
1755 mutex_lock_nested(&adap->userspace_clients_lock,
1756 i2c_adapter_depth(adap));
1757 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1759 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1761 list_del(&client->detected);
1762 i2c_unregister_device(client);
1764 mutex_unlock(&adap->userspace_clients_lock);
1766 /* Detach any active clients. This can't fail, thus we do not
1767 * check the returned value. This is a two-pass process, because
1768 * we can't remove the dummy devices during the first pass: they
1769 * could have been instantiated by real devices wishing to clean
1770 * them up properly, so we give them a chance to do that first. */
1771 device_for_each_child(&adap->dev, NULL, __unregister_client);
1772 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1774 #ifdef CONFIG_I2C_COMPAT
1775 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1779 /* device name is gone after device_unregister */
1780 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1782 /* clean up the sysfs representation */
1783 init_completion(&adap->dev_released);
1784 device_unregister(&adap->dev);
1786 /* wait for sysfs to drop all references */
1787 wait_for_completion(&adap->dev_released);
1790 mutex_lock(&core_lock);
1791 idr_remove(&i2c_adapter_idr, adap->nr);
1792 mutex_unlock(&core_lock);
1794 /* Clear the device structure in case this adapter is ever going to be
1796 memset(&adap->dev, 0, sizeof(adap->dev));
1798 EXPORT_SYMBOL(i2c_del_adapter);
1800 /* ------------------------------------------------------------------------- */
1802 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1806 mutex_lock(&core_lock);
1807 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1808 mutex_unlock(&core_lock);
1812 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1814 static int __process_new_driver(struct device *dev, void *data)
1816 if (dev->type != &i2c_adapter_type)
1818 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1822 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1823 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1826 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1830 /* Can't register until after driver model init */
1831 if (unlikely(WARN_ON(!i2c_bus_type.p)))
1834 /* add the driver to the list of i2c drivers in the driver core */
1835 driver->driver.owner = owner;
1836 driver->driver.bus = &i2c_bus_type;
1838 /* When registration returns, the driver core
1839 * will have called probe() for all matching-but-unbound devices.
1841 res = driver_register(&driver->driver);
1845 /* Drivers should switch to dev_pm_ops instead. */
1846 if (driver->suspend)
1847 pr_warn("i2c-core: driver [%s] using legacy suspend method\n",
1848 driver->driver.name);
1850 pr_warn("i2c-core: driver [%s] using legacy resume method\n",
1851 driver->driver.name);
1853 pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
1855 INIT_LIST_HEAD(&driver->clients);
1856 /* Walk the adapters that are already present */
1857 i2c_for_each_dev(driver, __process_new_driver);
1861 EXPORT_SYMBOL(i2c_register_driver);
1863 static int __process_removed_driver(struct device *dev, void *data)
1865 if (dev->type == &i2c_adapter_type)
1866 i2c_do_del_adapter(data, to_i2c_adapter(dev));
1871 * i2c_del_driver - unregister I2C driver
1872 * @driver: the driver being unregistered
1873 * Context: can sleep
1875 void i2c_del_driver(struct i2c_driver *driver)
1877 i2c_for_each_dev(driver, __process_removed_driver);
1879 driver_unregister(&driver->driver);
1880 pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
1882 EXPORT_SYMBOL(i2c_del_driver);
1884 /* ------------------------------------------------------------------------- */
1887 * i2c_use_client - increments the reference count of the i2c client structure
1888 * @client: the client being referenced
1890 * Each live reference to a client should be refcounted. The driver model does
1891 * that automatically as part of driver binding, so that most drivers don't
1892 * need to do this explicitly: they hold a reference until they're unbound
1895 * A pointer to the client with the incremented reference counter is returned.
1897 struct i2c_client *i2c_use_client(struct i2c_client *client)
1899 if (client && get_device(&client->dev))
1903 EXPORT_SYMBOL(i2c_use_client);
1906 * i2c_release_client - release a use of the i2c client structure
1907 * @client: the client being no longer referenced
1909 * Must be called when a user of a client is finished with it.
1911 void i2c_release_client(struct i2c_client *client)
1914 put_device(&client->dev);
1916 EXPORT_SYMBOL(i2c_release_client);
1918 struct i2c_cmd_arg {
1923 static int i2c_cmd(struct device *dev, void *_arg)
1925 struct i2c_client *client = i2c_verify_client(dev);
1926 struct i2c_cmd_arg *arg = _arg;
1927 struct i2c_driver *driver;
1929 if (!client || !client->dev.driver)
1932 driver = to_i2c_driver(client->dev.driver);
1933 if (driver->command)
1934 driver->command(client, arg->cmd, arg->arg);
1938 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1940 struct i2c_cmd_arg cmd_arg;
1944 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1946 EXPORT_SYMBOL(i2c_clients_command);
1948 static int __init i2c_init(void)
1952 retval = bus_register(&i2c_bus_type);
1955 #ifdef CONFIG_I2C_COMPAT
1956 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1957 if (!i2c_adapter_compat_class) {
1962 retval = i2c_add_driver(&dummy_driver);
1968 #ifdef CONFIG_I2C_COMPAT
1969 class_compat_unregister(i2c_adapter_compat_class);
1972 bus_unregister(&i2c_bus_type);
1976 static void __exit i2c_exit(void)
1978 i2c_del_driver(&dummy_driver);
1979 #ifdef CONFIG_I2C_COMPAT
1980 class_compat_unregister(i2c_adapter_compat_class);
1982 bus_unregister(&i2c_bus_type);
1983 tracepoint_synchronize_unregister();
1986 /* We must initialize early, because some subsystems register i2c drivers
1987 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1989 postcore_initcall(i2c_init);
1990 module_exit(i2c_exit);
1992 /* ----------------------------------------------------
1993 * the functional interface to the i2c busses.
1994 * ----------------------------------------------------
1998 * __i2c_transfer - unlocked flavor of i2c_transfer
1999 * @adap: Handle to I2C bus
2000 * @msgs: One or more messages to execute before STOP is issued to
2001 * terminate the operation; each message begins with a START.
2002 * @num: Number of messages to be executed.
2004 * Returns negative errno, else the number of messages executed.
2006 * Adapter lock must be held when calling this function. No debug logging
2007 * takes place. adap->algo->master_xfer existence isn't checked.
2009 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2011 unsigned long orig_jiffies;
2014 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2015 * enabled. This is an efficient way of keeping the for-loop from
2016 * being executed when not needed.
2018 if (static_key_false(&i2c_trace_msg)) {
2020 for (i = 0; i < num; i++)
2021 if (msgs[i].flags & I2C_M_RD)
2022 trace_i2c_read(adap, &msgs[i], i);
2024 trace_i2c_write(adap, &msgs[i], i);
2027 /* Retry automatically on arbitration loss */
2028 orig_jiffies = jiffies;
2029 for (ret = 0, try = 0; try <= adap->retries; try++) {
2030 ret = adap->algo->master_xfer(adap, msgs, num);
2033 if (time_after(jiffies, orig_jiffies + adap->timeout))
2037 if (static_key_false(&i2c_trace_msg)) {
2039 for (i = 0; i < ret; i++)
2040 if (msgs[i].flags & I2C_M_RD)
2041 trace_i2c_reply(adap, &msgs[i], i);
2042 trace_i2c_result(adap, i, ret);
2047 EXPORT_SYMBOL(__i2c_transfer);
2050 * i2c_transfer - execute a single or combined I2C message
2051 * @adap: Handle to I2C bus
2052 * @msgs: One or more messages to execute before STOP is issued to
2053 * terminate the operation; each message begins with a START.
2054 * @num: Number of messages to be executed.
2056 * Returns negative errno, else the number of messages executed.
2058 * Note that there is no requirement that each message be sent to
2059 * the same slave address, although that is the most common model.
2061 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2065 /* REVISIT the fault reporting model here is weak:
2067 * - When we get an error after receiving N bytes from a slave,
2068 * there is no way to report "N".
2070 * - When we get a NAK after transmitting N bytes to a slave,
2071 * there is no way to report "N" ... or to let the master
2072 * continue executing the rest of this combined message, if
2073 * that's the appropriate response.
2075 * - When for example "num" is two and we successfully complete
2076 * the first message but get an error part way through the
2077 * second, it's unclear whether that should be reported as
2078 * one (discarding status on the second message) or errno
2079 * (discarding status on the first one).
2082 if (adap->algo->master_xfer) {
2084 for (ret = 0; ret < num; ret++) {
2085 dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
2086 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
2087 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
2088 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2092 if (in_atomic() || irqs_disabled()) {
2093 ret = i2c_trylock_adapter(adap);
2095 /* I2C activity is ongoing. */
2098 i2c_lock_adapter(adap);
2101 ret = __i2c_transfer(adap, msgs, num);
2102 i2c_unlock_adapter(adap);
2106 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2110 EXPORT_SYMBOL(i2c_transfer);
2113 * i2c_master_send - issue a single I2C message in master transmit mode
2114 * @client: Handle to slave device
2115 * @buf: Data that will be written to the slave
2116 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2118 * Returns negative errno, or else the number of bytes written.
2120 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2123 struct i2c_adapter *adap = client->adapter;
2126 msg.addr = client->addr;
2127 msg.flags = client->flags & I2C_M_TEN;
2129 msg.buf = (char *)buf;
2131 ret = i2c_transfer(adap, &msg, 1);
2134 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2135 * transmitted, else error code.
2137 return (ret == 1) ? count : ret;
2139 EXPORT_SYMBOL(i2c_master_send);
2142 * i2c_master_recv - issue a single I2C message in master receive mode
2143 * @client: Handle to slave device
2144 * @buf: Where to store data read from slave
2145 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2147 * Returns negative errno, or else the number of bytes read.
2149 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2151 struct i2c_adapter *adap = client->adapter;
2155 msg.addr = client->addr;
2156 msg.flags = client->flags & I2C_M_TEN;
2157 msg.flags |= I2C_M_RD;
2161 ret = i2c_transfer(adap, &msg, 1);
2164 * If everything went ok (i.e. 1 msg received), return #bytes received,
2167 return (ret == 1) ? count : ret;
2169 EXPORT_SYMBOL(i2c_master_recv);
2171 /* ----------------------------------------------------
2172 * the i2c address scanning function
2173 * Will not work for 10-bit addresses!
2174 * ----------------------------------------------------
2178 * Legacy default probe function, mostly relevant for SMBus. The default
2179 * probe method is a quick write, but it is known to corrupt the 24RF08
2180 * EEPROMs due to a state machine bug, and could also irreversibly
2181 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2182 * we use a short byte read instead. Also, some bus drivers don't implement
2183 * quick write, so we fallback to a byte read in that case too.
2184 * On x86, there is another special case for FSC hardware monitoring chips,
2185 * which want regular byte reads (address 0x73.) Fortunately, these are the
2186 * only known chips using this I2C address on PC hardware.
2187 * Returns 1 if probe succeeded, 0 if not.
2189 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2192 union i2c_smbus_data dummy;
2195 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2196 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2197 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2198 I2C_SMBUS_BYTE_DATA, &dummy);
2201 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2202 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2203 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2204 I2C_SMBUS_QUICK, NULL);
2205 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2206 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2207 I2C_SMBUS_BYTE, &dummy);
2209 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2217 static int i2c_detect_address(struct i2c_client *temp_client,
2218 struct i2c_driver *driver)
2220 struct i2c_board_info info;
2221 struct i2c_adapter *adapter = temp_client->adapter;
2222 int addr = temp_client->addr;
2225 /* Make sure the address is valid */
2226 err = i2c_check_addr_validity(addr);
2228 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2233 /* Skip if already in use */
2234 if (i2c_check_addr_busy(adapter, addr))
2237 /* Make sure there is something at this address */
2238 if (!i2c_default_probe(adapter, addr))
2241 /* Finally call the custom detection function */
2242 memset(&info, 0, sizeof(struct i2c_board_info));
2244 err = driver->detect(temp_client, &info);
2246 /* -ENODEV is returned if the detection fails. We catch it
2247 here as this isn't an error. */
2248 return err == -ENODEV ? 0 : err;
2251 /* Consistency check */
2252 if (info.type[0] == '\0') {
2253 dev_err(&adapter->dev, "%s detection function provided "
2254 "no name for 0x%x\n", driver->driver.name,
2257 struct i2c_client *client;
2259 /* Detection succeeded, instantiate the device */
2260 if (adapter->class & I2C_CLASS_DEPRECATED)
2261 dev_warn(&adapter->dev,
2262 "This adapter will soon drop class based instantiation of devices. "
2263 "Please make sure client 0x%02x gets instantiated by other means. "
2264 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2267 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2268 info.type, info.addr);
2269 client = i2c_new_device(adapter, &info);
2271 list_add_tail(&client->detected, &driver->clients);
2273 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2274 info.type, info.addr);
2279 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2281 const unsigned short *address_list;
2282 struct i2c_client *temp_client;
2284 int adap_id = i2c_adapter_id(adapter);
2286 address_list = driver->address_list;
2287 if (!driver->detect || !address_list)
2290 /* Warn that the adapter lost class based instantiation */
2291 if (adapter->class == I2C_CLASS_DEPRECATED) {
2292 dev_dbg(&adapter->dev,
2293 "This adapter dropped support for I2C classes and "
2294 "won't auto-detect %s devices anymore. If you need it, check "
2295 "'Documentation/i2c/instantiating-devices' for alternatives.\n",
2296 driver->driver.name);
2300 /* Stop here if the classes do not match */
2301 if (!(adapter->class & driver->class))
2304 /* Set up a temporary client to help detect callback */
2305 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2308 temp_client->adapter = adapter;
2310 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2311 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
2312 "addr 0x%02x\n", adap_id, address_list[i]);
2313 temp_client->addr = address_list[i];
2314 err = i2c_detect_address(temp_client, driver);
2323 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2325 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2326 I2C_SMBUS_QUICK, NULL) >= 0;
2328 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2331 i2c_new_probed_device(struct i2c_adapter *adap,
2332 struct i2c_board_info *info,
2333 unsigned short const *addr_list,
2334 int (*probe)(struct i2c_adapter *, unsigned short addr))
2339 probe = i2c_default_probe;
2341 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2342 /* Check address validity */
2343 if (i2c_check_addr_validity(addr_list[i]) < 0) {
2344 dev_warn(&adap->dev, "Invalid 7-bit address "
2345 "0x%02x\n", addr_list[i]);
2349 /* Check address availability */
2350 if (i2c_check_addr_busy(adap, addr_list[i])) {
2351 dev_dbg(&adap->dev, "Address 0x%02x already in "
2352 "use, not probing\n", addr_list[i]);
2356 /* Test address responsiveness */
2357 if (probe(adap, addr_list[i]))
2361 if (addr_list[i] == I2C_CLIENT_END) {
2362 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2366 info->addr = addr_list[i];
2367 return i2c_new_device(adap, info);
2369 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2371 struct i2c_adapter *i2c_get_adapter(int nr)
2373 struct i2c_adapter *adapter;
2375 mutex_lock(&core_lock);
2376 adapter = idr_find(&i2c_adapter_idr, nr);
2377 if (adapter && !try_module_get(adapter->owner))
2380 mutex_unlock(&core_lock);
2383 EXPORT_SYMBOL(i2c_get_adapter);
2385 void i2c_put_adapter(struct i2c_adapter *adap)
2388 module_put(adap->owner);
2390 EXPORT_SYMBOL(i2c_put_adapter);
2392 /* The SMBus parts */
2394 #define POLY (0x1070U << 3)
2395 static u8 crc8(u16 data)
2399 for (i = 0; i < 8; i++) {
2404 return (u8)(data >> 8);
2407 /* Incremental CRC8 over count bytes in the array pointed to by p */
2408 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2412 for (i = 0; i < count; i++)
2413 crc = crc8((crc ^ p[i]) << 8);
2417 /* Assume a 7-bit address, which is reasonable for SMBus */
2418 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2420 /* The address will be sent first */
2421 u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
2422 pec = i2c_smbus_pec(pec, &addr, 1);
2424 /* The data buffer follows */
2425 return i2c_smbus_pec(pec, msg->buf, msg->len);
2428 /* Used for write only transactions */
2429 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2431 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2435 /* Return <0 on CRC error
2436 If there was a write before this read (most cases) we need to take the
2437 partial CRC from the write part into account.
2438 Note that this function does modify the message (we need to decrease the
2439 message length to hide the CRC byte from the caller). */
2440 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2442 u8 rpec = msg->buf[--msg->len];
2443 cpec = i2c_smbus_msg_pec(cpec, msg);
2446 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
2454 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2455 * @client: Handle to slave device
2457 * This executes the SMBus "receive byte" protocol, returning negative errno
2458 * else the byte received from the device.
2460 s32 i2c_smbus_read_byte(const struct i2c_client *client)
2462 union i2c_smbus_data data;
2465 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2467 I2C_SMBUS_BYTE, &data);
2468 return (status < 0) ? status : data.byte;
2470 EXPORT_SYMBOL(i2c_smbus_read_byte);
2473 * i2c_smbus_write_byte - SMBus "send byte" protocol
2474 * @client: Handle to slave device
2475 * @value: Byte to be sent
2477 * This executes the SMBus "send byte" protocol, returning negative errno
2478 * else zero on success.
2480 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2482 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2483 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2485 EXPORT_SYMBOL(i2c_smbus_write_byte);
2488 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2489 * @client: Handle to slave device
2490 * @command: Byte interpreted by slave
2492 * This executes the SMBus "read byte" protocol, returning negative errno
2493 * else a data byte received from the device.
2495 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2497 union i2c_smbus_data data;
2500 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2501 I2C_SMBUS_READ, command,
2502 I2C_SMBUS_BYTE_DATA, &data);
2503 return (status < 0) ? status : data.byte;
2505 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2508 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2509 * @client: Handle to slave device
2510 * @command: Byte interpreted by slave
2511 * @value: Byte being written
2513 * This executes the SMBus "write byte" protocol, returning negative errno
2514 * else zero on success.
2516 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
2519 union i2c_smbus_data data;
2521 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2522 I2C_SMBUS_WRITE, command,
2523 I2C_SMBUS_BYTE_DATA, &data);
2525 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
2528 * i2c_smbus_read_word_data - SMBus "read word" protocol
2529 * @client: Handle to slave device
2530 * @command: Byte interpreted by slave
2532 * This executes the SMBus "read word" protocol, returning negative errno
2533 * else a 16-bit unsigned "word" received from the device.
2535 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
2537 union i2c_smbus_data data;
2540 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2541 I2C_SMBUS_READ, command,
2542 I2C_SMBUS_WORD_DATA, &data);
2543 return (status < 0) ? status : data.word;
2545 EXPORT_SYMBOL(i2c_smbus_read_word_data);
2548 * i2c_smbus_write_word_data - SMBus "write word" protocol
2549 * @client: Handle to slave device
2550 * @command: Byte interpreted by slave
2551 * @value: 16-bit "word" being written
2553 * This executes the SMBus "write word" protocol, returning negative errno
2554 * else zero on success.
2556 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2559 union i2c_smbus_data data;
2561 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2562 I2C_SMBUS_WRITE, command,
2563 I2C_SMBUS_WORD_DATA, &data);
2565 EXPORT_SYMBOL(i2c_smbus_write_word_data);
2568 * i2c_smbus_read_block_data - SMBus "block read" protocol
2569 * @client: Handle to slave device
2570 * @command: Byte interpreted by slave
2571 * @values: Byte array into which data will be read; big enough to hold
2572 * the data returned by the slave. SMBus allows at most 32 bytes.
2574 * This executes the SMBus "block read" protocol, returning negative errno
2575 * else the number of data bytes in the slave's response.
2577 * Note that using this function requires that the client's adapter support
2578 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
2579 * support this; its emulation through I2C messaging relies on a specific
2580 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2582 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2585 union i2c_smbus_data data;
2588 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2589 I2C_SMBUS_READ, command,
2590 I2C_SMBUS_BLOCK_DATA, &data);
2594 memcpy(values, &data.block[1], data.block[0]);
2595 return data.block[0];
2597 EXPORT_SYMBOL(i2c_smbus_read_block_data);
2600 * i2c_smbus_write_block_data - SMBus "block write" protocol
2601 * @client: Handle to slave device
2602 * @command: Byte interpreted by slave
2603 * @length: Size of data block; SMBus allows at most 32 bytes
2604 * @values: Byte array which will be written.
2606 * This executes the SMBus "block write" protocol, returning negative errno
2607 * else zero on success.
2609 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2610 u8 length, const u8 *values)
2612 union i2c_smbus_data data;
2614 if (length > I2C_SMBUS_BLOCK_MAX)
2615 length = I2C_SMBUS_BLOCK_MAX;
2616 data.block[0] = length;
2617 memcpy(&data.block[1], values, length);
2618 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2619 I2C_SMBUS_WRITE, command,
2620 I2C_SMBUS_BLOCK_DATA, &data);
2622 EXPORT_SYMBOL(i2c_smbus_write_block_data);
2624 /* Returns the number of read bytes */
2625 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2626 u8 length, u8 *values)
2628 union i2c_smbus_data data;
2631 if (length > I2C_SMBUS_BLOCK_MAX)
2632 length = I2C_SMBUS_BLOCK_MAX;
2633 data.block[0] = length;
2634 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2635 I2C_SMBUS_READ, command,
2636 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2640 memcpy(values, &data.block[1], data.block[0]);
2641 return data.block[0];
2643 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2645 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2646 u8 length, const u8 *values)
2648 union i2c_smbus_data data;
2650 if (length > I2C_SMBUS_BLOCK_MAX)
2651 length = I2C_SMBUS_BLOCK_MAX;
2652 data.block[0] = length;
2653 memcpy(data.block + 1, values, length);
2654 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2655 I2C_SMBUS_WRITE, command,
2656 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2658 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2660 /* Simulate a SMBus command using the i2c protocol
2661 No checking of parameters is done! */
2662 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2663 unsigned short flags,
2664 char read_write, u8 command, int size,
2665 union i2c_smbus_data *data)
2667 /* So we need to generate a series of msgs. In the case of writing, we
2668 need to use only one message; when reading, we need two. We initialize
2669 most things with sane defaults, to keep the code below somewhat
2671 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2672 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2673 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2677 struct i2c_msg msg[2] = {
2685 .flags = flags | I2C_M_RD,
2691 msgbuf0[0] = command;
2693 case I2C_SMBUS_QUICK:
2695 /* Special case: The read/write field is used as data */
2696 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2700 case I2C_SMBUS_BYTE:
2701 if (read_write == I2C_SMBUS_READ) {
2702 /* Special case: only a read! */
2703 msg[0].flags = I2C_M_RD | flags;
2707 case I2C_SMBUS_BYTE_DATA:
2708 if (read_write == I2C_SMBUS_READ)
2712 msgbuf0[1] = data->byte;
2715 case I2C_SMBUS_WORD_DATA:
2716 if (read_write == I2C_SMBUS_READ)
2720 msgbuf0[1] = data->word & 0xff;
2721 msgbuf0[2] = data->word >> 8;
2724 case I2C_SMBUS_PROC_CALL:
2725 num = 2; /* Special case */
2726 read_write = I2C_SMBUS_READ;
2729 msgbuf0[1] = data->word & 0xff;
2730 msgbuf0[2] = data->word >> 8;
2732 case I2C_SMBUS_BLOCK_DATA:
2733 if (read_write == I2C_SMBUS_READ) {
2734 msg[1].flags |= I2C_M_RECV_LEN;
2735 msg[1].len = 1; /* block length will be added by
2736 the underlying bus driver */
2738 msg[0].len = data->block[0] + 2;
2739 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
2740 dev_err(&adapter->dev,
2741 "Invalid block write size %d\n",
2745 for (i = 1; i < msg[0].len; i++)
2746 msgbuf0[i] = data->block[i-1];
2749 case I2C_SMBUS_BLOCK_PROC_CALL:
2750 num = 2; /* Another special case */
2751 read_write = I2C_SMBUS_READ;
2752 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
2753 dev_err(&adapter->dev,
2754 "Invalid block write size %d\n",
2758 msg[0].len = data->block[0] + 2;
2759 for (i = 1; i < msg[0].len; i++)
2760 msgbuf0[i] = data->block[i-1];
2761 msg[1].flags |= I2C_M_RECV_LEN;
2762 msg[1].len = 1; /* block length will be added by
2763 the underlying bus driver */
2765 case I2C_SMBUS_I2C_BLOCK_DATA:
2766 if (read_write == I2C_SMBUS_READ) {
2767 msg[1].len = data->block[0];
2769 msg[0].len = data->block[0] + 1;
2770 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
2771 dev_err(&adapter->dev,
2772 "Invalid block write size %d\n",
2776 for (i = 1; i <= data->block[0]; i++)
2777 msgbuf0[i] = data->block[i];
2781 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
2785 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
2786 && size != I2C_SMBUS_I2C_BLOCK_DATA);
2788 /* Compute PEC if first message is a write */
2789 if (!(msg[0].flags & I2C_M_RD)) {
2790 if (num == 1) /* Write only */
2791 i2c_smbus_add_pec(&msg[0]);
2792 else /* Write followed by read */
2793 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
2795 /* Ask for PEC if last message is a read */
2796 if (msg[num-1].flags & I2C_M_RD)
2800 status = i2c_transfer(adapter, msg, num);
2804 /* Check PEC if last message is a read */
2805 if (i && (msg[num-1].flags & I2C_M_RD)) {
2806 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
2811 if (read_write == I2C_SMBUS_READ)
2813 case I2C_SMBUS_BYTE:
2814 data->byte = msgbuf0[0];
2816 case I2C_SMBUS_BYTE_DATA:
2817 data->byte = msgbuf1[0];
2819 case I2C_SMBUS_WORD_DATA:
2820 case I2C_SMBUS_PROC_CALL:
2821 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
2823 case I2C_SMBUS_I2C_BLOCK_DATA:
2824 for (i = 0; i < data->block[0]; i++)
2825 data->block[i+1] = msgbuf1[i];
2827 case I2C_SMBUS_BLOCK_DATA:
2828 case I2C_SMBUS_BLOCK_PROC_CALL:
2829 for (i = 0; i < msgbuf1[0] + 1; i++)
2830 data->block[i] = msgbuf1[i];
2837 * i2c_smbus_xfer - execute SMBus protocol operations
2838 * @adapter: Handle to I2C bus
2839 * @addr: Address of SMBus slave on that bus
2840 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
2841 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
2842 * @command: Byte interpreted by slave, for protocols which use such bytes
2843 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
2844 * @data: Data to be read or written
2846 * This executes an SMBus protocol operation, and returns a negative
2847 * errno code else zero on success.
2849 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
2850 char read_write, u8 command, int protocol,
2851 union i2c_smbus_data *data)
2853 unsigned long orig_jiffies;
2857 /* If enabled, the following two tracepoints are conditional on
2858 * read_write and protocol.
2860 trace_smbus_write(adapter, addr, flags, read_write,
2861 command, protocol, data);
2862 trace_smbus_read(adapter, addr, flags, read_write,
2865 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
2867 if (adapter->algo->smbus_xfer) {
2868 i2c_lock_adapter(adapter);
2870 /* Retry automatically on arbitration loss */
2871 orig_jiffies = jiffies;
2872 for (res = 0, try = 0; try <= adapter->retries; try++) {
2873 res = adapter->algo->smbus_xfer(adapter, addr, flags,
2874 read_write, command,
2878 if (time_after(jiffies,
2879 orig_jiffies + adapter->timeout))
2882 i2c_unlock_adapter(adapter);
2884 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
2887 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
2888 * implement native support for the SMBus operation.
2892 res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
2893 command, protocol, data);
2896 /* If enabled, the reply tracepoint is conditional on read_write. */
2897 trace_smbus_reply(adapter, addr, flags, read_write,
2898 command, protocol, data);
2899 trace_smbus_result(adapter, addr, flags, read_write,
2900 command, protocol, res);
2904 EXPORT_SYMBOL(i2c_smbus_xfer);
2906 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2907 MODULE_DESCRIPTION("I2C-Bus main module");
2908 MODULE_LICENSE("GPL");