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 #define pr_fmt(fmt) "i2c-core: " fmt
32 #include <dt-bindings/i2c/i2c.h>
33 #include <asm/uaccess.h>
34 #include <linux/acpi.h>
35 #include <linux/clk/clk-conf.h>
36 #include <linux/completion.h>
37 #include <linux/delay.h>
38 #include <linux/err.h>
39 #include <linux/errno.h>
40 #include <linux/gpio.h>
41 #include <linux/hardirq.h>
42 #include <linux/i2c.h>
43 #include <linux/idr.h>
44 #include <linux/init.h>
45 #include <linux/irqflags.h>
46 #include <linux/jump_label.h>
47 #include <linux/kernel.h>
48 #include <linux/module.h>
49 #include <linux/mutex.h>
50 #include <linux/of_device.h>
52 #include <linux/of_irq.h>
53 #include <linux/pm_domain.h>
54 #include <linux/pm_runtime.h>
55 #include <linux/pm_wakeirq.h>
56 #include <linux/property.h>
57 #include <linux/rwsem.h>
58 #include <linux/slab.h>
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/i2c.h>
65 #define I2C_ADDR_OFFSET_TEN_BIT 0xa000
66 #define I2C_ADDR_OFFSET_SLAVE 0x1000
68 /* core_lock protects i2c_adapter_idr, and guarantees
69 that device detection, deletion of detected devices, and attach_adapter
70 calls are serialized */
71 static DEFINE_MUTEX(core_lock);
72 static DEFINE_IDR(i2c_adapter_idr);
74 static struct device_type i2c_client_type;
75 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
77 static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
78 static bool is_registered;
80 void i2c_transfer_trace_reg(void)
82 static_key_slow_inc(&i2c_trace_msg);
85 void i2c_transfer_trace_unreg(void)
87 static_key_slow_dec(&i2c_trace_msg);
90 #if defined(CONFIG_ACPI)
91 struct i2c_acpi_handler_data {
92 struct acpi_connection_info info;
93 struct i2c_adapter *adapter;
106 struct i2c_acpi_lookup {
107 struct i2c_board_info *info;
108 acpi_handle adapter_handle;
109 acpi_handle device_handle;
110 acpi_handle search_handle;
115 static int i2c_acpi_fill_info(struct acpi_resource *ares, void *data)
117 struct i2c_acpi_lookup *lookup = data;
118 struct i2c_board_info *info = lookup->info;
119 struct acpi_resource_i2c_serialbus *sb;
122 if (info->addr || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
125 sb = &ares->data.i2c_serial_bus;
126 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C)
129 status = acpi_get_handle(lookup->device_handle,
130 sb->resource_source.string_ptr,
131 &lookup->adapter_handle);
132 if (!ACPI_SUCCESS(status))
135 info->addr = sb->slave_address;
136 lookup->speed = sb->connection_speed;
137 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
138 info->flags |= I2C_CLIENT_TEN;
143 static int i2c_acpi_do_lookup(struct acpi_device *adev,
144 struct i2c_acpi_lookup *lookup)
146 struct i2c_board_info *info = lookup->info;
147 struct list_head resource_list;
150 if (acpi_bus_get_status(adev) || !adev->status.present ||
151 acpi_device_enumerated(adev))
154 memset(info, 0, sizeof(*info));
155 lookup->device_handle = acpi_device_handle(adev);
157 /* Look up for I2cSerialBus resource */
158 INIT_LIST_HEAD(&resource_list);
159 ret = acpi_dev_get_resources(adev, &resource_list,
160 i2c_acpi_fill_info, lookup);
161 acpi_dev_free_resource_list(&resource_list);
163 if (ret < 0 || !info->addr)
169 static int i2c_acpi_get_info(struct acpi_device *adev,
170 struct i2c_board_info *info,
171 acpi_handle *adapter_handle)
173 struct list_head resource_list;
174 struct resource_entry *entry;
175 struct i2c_acpi_lookup lookup;
178 memset(&lookup, 0, sizeof(lookup));
181 ret = i2c_acpi_do_lookup(adev, &lookup);
185 info->fwnode = acpi_fwnode_handle(adev);
186 *adapter_handle = lookup.adapter_handle;
188 /* Then fill IRQ number if any */
189 INIT_LIST_HEAD(&resource_list);
190 ret = acpi_dev_get_resources(adev, &resource_list, NULL, NULL);
194 resource_list_for_each_entry(entry, &resource_list) {
195 if (resource_type(entry->res) == IORESOURCE_IRQ) {
196 info->irq = entry->res->start;
201 acpi_dev_free_resource_list(&resource_list);
203 strlcpy(info->type, dev_name(&adev->dev), sizeof(info->type));
208 static void i2c_acpi_register_device(struct i2c_adapter *adapter,
209 struct acpi_device *adev,
210 struct i2c_board_info *info)
212 adev->power.flags.ignore_parent = true;
213 acpi_device_set_enumerated(adev);
215 if (!i2c_new_device(adapter, info)) {
216 adev->power.flags.ignore_parent = false;
217 dev_err(&adapter->dev,
218 "failed to add I2C device %s from ACPI\n",
219 dev_name(&adev->dev));
223 static acpi_status i2c_acpi_add_device(acpi_handle handle, u32 level,
224 void *data, void **return_value)
226 struct i2c_adapter *adapter = data;
227 struct acpi_device *adev;
228 acpi_handle adapter_handle;
229 struct i2c_board_info info;
231 if (acpi_bus_get_device(handle, &adev))
234 if (i2c_acpi_get_info(adev, &info, &adapter_handle))
237 if (adapter_handle != ACPI_HANDLE(&adapter->dev))
240 i2c_acpi_register_device(adapter, adev, &info);
245 #define I2C_ACPI_MAX_SCAN_DEPTH 32
248 * i2c_acpi_register_devices - enumerate I2C slave devices behind adapter
249 * @adap: pointer to adapter
251 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
252 * namespace. When a device is found it will be added to the Linux device
253 * model and bound to the corresponding ACPI handle.
255 static void i2c_acpi_register_devices(struct i2c_adapter *adap)
259 if (!has_acpi_companion(&adap->dev))
262 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
263 I2C_ACPI_MAX_SCAN_DEPTH,
264 i2c_acpi_add_device, NULL,
266 if (ACPI_FAILURE(status))
267 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
270 static acpi_status i2c_acpi_lookup_speed(acpi_handle handle, u32 level,
271 void *data, void **return_value)
273 struct i2c_acpi_lookup *lookup = data;
274 struct acpi_device *adev;
276 if (acpi_bus_get_device(handle, &adev))
279 if (i2c_acpi_do_lookup(adev, lookup))
282 if (lookup->search_handle != lookup->adapter_handle)
285 if (lookup->speed <= lookup->min_speed)
286 lookup->min_speed = lookup->speed;
292 * i2c_acpi_find_bus_speed - find I2C bus speed from ACPI
293 * @dev: The device owning the bus
295 * Find the I2C bus speed by walking the ACPI namespace for all I2C slaves
296 * devices connected to this bus and use the speed of slowest device.
298 * Returns the speed in Hz or zero
300 u32 i2c_acpi_find_bus_speed(struct device *dev)
302 struct i2c_acpi_lookup lookup;
303 struct i2c_board_info dummy;
306 if (!has_acpi_companion(dev))
309 memset(&lookup, 0, sizeof(lookup));
310 lookup.search_handle = ACPI_HANDLE(dev);
311 lookup.min_speed = UINT_MAX;
312 lookup.info = &dummy;
314 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
315 I2C_ACPI_MAX_SCAN_DEPTH,
316 i2c_acpi_lookup_speed, NULL,
319 if (ACPI_FAILURE(status)) {
320 dev_warn(dev, "unable to find I2C bus speed from ACPI\n");
324 return lookup.min_speed != UINT_MAX ? lookup.min_speed : 0;
326 EXPORT_SYMBOL_GPL(i2c_acpi_find_bus_speed);
328 static int i2c_acpi_match_adapter(struct device *dev, void *data)
330 struct i2c_adapter *adapter = i2c_verify_adapter(dev);
335 return ACPI_HANDLE(dev) == (acpi_handle)data;
338 static int i2c_acpi_match_device(struct device *dev, void *data)
340 return ACPI_COMPANION(dev) == data;
343 static struct i2c_adapter *i2c_acpi_find_adapter_by_handle(acpi_handle handle)
347 dev = bus_find_device(&i2c_bus_type, NULL, handle,
348 i2c_acpi_match_adapter);
349 return dev ? i2c_verify_adapter(dev) : NULL;
352 static struct i2c_client *i2c_acpi_find_client_by_adev(struct acpi_device *adev)
356 dev = bus_find_device(&i2c_bus_type, NULL, adev, i2c_acpi_match_device);
357 return dev ? i2c_verify_client(dev) : NULL;
360 static int i2c_acpi_notify(struct notifier_block *nb, unsigned long value,
363 struct acpi_device *adev = arg;
364 struct i2c_board_info info;
365 acpi_handle adapter_handle;
366 struct i2c_adapter *adapter;
367 struct i2c_client *client;
370 case ACPI_RECONFIG_DEVICE_ADD:
371 if (i2c_acpi_get_info(adev, &info, &adapter_handle))
374 adapter = i2c_acpi_find_adapter_by_handle(adapter_handle);
378 i2c_acpi_register_device(adapter, adev, &info);
380 case ACPI_RECONFIG_DEVICE_REMOVE:
381 if (!acpi_device_enumerated(adev))
384 client = i2c_acpi_find_client_by_adev(adev);
388 i2c_unregister_device(client);
389 put_device(&client->dev);
396 static struct notifier_block i2c_acpi_notifier = {
397 .notifier_call = i2c_acpi_notify,
399 #else /* CONFIG_ACPI */
400 static inline void i2c_acpi_register_devices(struct i2c_adapter *adap) { }
401 extern struct notifier_block i2c_acpi_notifier;
402 #endif /* CONFIG_ACPI */
404 #ifdef CONFIG_ACPI_I2C_OPREGION
405 static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
406 u8 cmd, u8 *data, u8 data_len)
409 struct i2c_msg msgs[2];
413 buffer = kzalloc(data_len, GFP_KERNEL);
417 msgs[0].addr = client->addr;
418 msgs[0].flags = client->flags;
422 msgs[1].addr = client->addr;
423 msgs[1].flags = client->flags | I2C_M_RD;
424 msgs[1].len = data_len;
425 msgs[1].buf = buffer;
427 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
429 dev_err(&client->adapter->dev, "i2c read failed\n");
431 memcpy(data, buffer, data_len);
437 static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
438 u8 cmd, u8 *data, u8 data_len)
441 struct i2c_msg msgs[1];
445 buffer = kzalloc(data_len + 1, GFP_KERNEL);
450 memcpy(buffer + 1, data, data_len);
452 msgs[0].addr = client->addr;
453 msgs[0].flags = client->flags;
454 msgs[0].len = data_len + 1;
455 msgs[0].buf = buffer;
457 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
459 dev_err(&client->adapter->dev, "i2c write failed\n");
466 i2c_acpi_space_handler(u32 function, acpi_physical_address command,
467 u32 bits, u64 *value64,
468 void *handler_context, void *region_context)
470 struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
471 struct i2c_acpi_handler_data *data = handler_context;
472 struct acpi_connection_info *info = &data->info;
473 struct acpi_resource_i2c_serialbus *sb;
474 struct i2c_adapter *adapter = data->adapter;
475 struct i2c_client *client;
476 struct acpi_resource *ares;
477 u32 accessor_type = function >> 16;
478 u8 action = function & ACPI_IO_MASK;
482 ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
483 if (ACPI_FAILURE(ret))
486 client = kzalloc(sizeof(*client), GFP_KERNEL);
492 if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
493 ret = AE_BAD_PARAMETER;
497 sb = &ares->data.i2c_serial_bus;
498 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
499 ret = AE_BAD_PARAMETER;
503 client->adapter = adapter;
504 client->addr = sb->slave_address;
506 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
507 client->flags |= I2C_CLIENT_TEN;
509 switch (accessor_type) {
510 case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
511 if (action == ACPI_READ) {
512 status = i2c_smbus_read_byte(client);
518 status = i2c_smbus_write_byte(client, gsb->bdata);
522 case ACPI_GSB_ACCESS_ATTRIB_BYTE:
523 if (action == ACPI_READ) {
524 status = i2c_smbus_read_byte_data(client, command);
530 status = i2c_smbus_write_byte_data(client, command,
535 case ACPI_GSB_ACCESS_ATTRIB_WORD:
536 if (action == ACPI_READ) {
537 status = i2c_smbus_read_word_data(client, command);
543 status = i2c_smbus_write_word_data(client, command,
548 case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
549 if (action == ACPI_READ) {
550 status = i2c_smbus_read_block_data(client, command,
557 status = i2c_smbus_write_block_data(client, command,
558 gsb->len, gsb->data);
562 case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
563 if (action == ACPI_READ) {
564 status = acpi_gsb_i2c_read_bytes(client, command,
565 gsb->data, info->access_length);
569 status = acpi_gsb_i2c_write_bytes(client, command,
570 gsb->data, info->access_length);
575 dev_warn(&adapter->dev, "protocol 0x%02x not supported for client 0x%02x\n",
576 accessor_type, client->addr);
577 ret = AE_BAD_PARAMETER;
581 gsb->status = status;
590 static int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
593 struct i2c_acpi_handler_data *data;
596 if (!adapter->dev.parent)
599 handle = ACPI_HANDLE(adapter->dev.parent);
604 data = kzalloc(sizeof(struct i2c_acpi_handler_data),
609 data->adapter = adapter;
610 status = acpi_bus_attach_private_data(handle, (void *)data);
611 if (ACPI_FAILURE(status)) {
616 status = acpi_install_address_space_handler(handle,
617 ACPI_ADR_SPACE_GSBUS,
618 &i2c_acpi_space_handler,
621 if (ACPI_FAILURE(status)) {
622 dev_err(&adapter->dev, "Error installing i2c space handler\n");
623 acpi_bus_detach_private_data(handle);
628 acpi_walk_dep_device_list(handle);
632 static void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
635 struct i2c_acpi_handler_data *data;
638 if (!adapter->dev.parent)
641 handle = ACPI_HANDLE(adapter->dev.parent);
646 acpi_remove_address_space_handler(handle,
647 ACPI_ADR_SPACE_GSBUS,
648 &i2c_acpi_space_handler);
650 status = acpi_bus_get_private_data(handle, (void **)&data);
651 if (ACPI_SUCCESS(status))
654 acpi_bus_detach_private_data(handle);
656 #else /* CONFIG_ACPI_I2C_OPREGION */
657 static inline void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
660 static inline int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
662 #endif /* CONFIG_ACPI_I2C_OPREGION */
664 /* ------------------------------------------------------------------------- */
666 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
667 const struct i2c_client *client)
669 while (id->name[0]) {
670 if (strcmp(client->name, id->name) == 0)
677 static int i2c_device_match(struct device *dev, struct device_driver *drv)
679 struct i2c_client *client = i2c_verify_client(dev);
680 struct i2c_driver *driver;
685 /* Attempt an OF style match */
686 if (of_driver_match_device(dev, drv))
689 /* Then ACPI style match */
690 if (acpi_driver_match_device(dev, drv))
693 driver = to_i2c_driver(drv);
694 /* match on an id table if there is one */
695 if (driver->id_table)
696 return i2c_match_id(driver->id_table, client) != NULL;
701 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
703 struct i2c_client *client = to_i2c_client(dev);
706 rc = acpi_device_uevent_modalias(dev, env);
710 return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
713 /* i2c bus recovery routines */
714 static int get_scl_gpio_value(struct i2c_adapter *adap)
716 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
719 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
721 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
724 static int get_sda_gpio_value(struct i2c_adapter *adap)
726 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
729 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
731 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
732 struct device *dev = &adap->dev;
735 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
736 GPIOF_OUT_INIT_HIGH, "i2c-scl");
738 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
743 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
744 /* work without SDA polling */
745 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
754 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
756 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
759 gpio_free(bri->sda_gpio);
761 gpio_free(bri->scl_gpio);
765 * We are generating clock pulses. ndelay() determines durating of clk pulses.
766 * We will generate clock with rate 100 KHz and so duration of both clock levels
767 * is: delay in ns = (10^6 / 100) / 2
769 #define RECOVERY_NDELAY 5000
770 #define RECOVERY_CLK_CNT 9
772 static int i2c_generic_recovery(struct i2c_adapter *adap)
774 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
775 int i = 0, val = 1, ret = 0;
777 if (bri->prepare_recovery)
778 bri->prepare_recovery(adap);
780 bri->set_scl(adap, val);
781 ndelay(RECOVERY_NDELAY);
784 * By this time SCL is high, as we need to give 9 falling-rising edges
786 while (i++ < RECOVERY_CLK_CNT * 2) {
788 /* Break if SDA is high */
789 if (bri->get_sda && bri->get_sda(adap))
791 /* SCL shouldn't be low here */
792 if (!bri->get_scl(adap)) {
794 "SCL is stuck low, exit recovery\n");
801 bri->set_scl(adap, val);
802 ndelay(RECOVERY_NDELAY);
805 if (bri->unprepare_recovery)
806 bri->unprepare_recovery(adap);
811 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
813 return i2c_generic_recovery(adap);
815 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
817 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
821 ret = i2c_get_gpios_for_recovery(adap);
825 ret = i2c_generic_recovery(adap);
826 i2c_put_gpios_for_recovery(adap);
830 EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
832 int i2c_recover_bus(struct i2c_adapter *adap)
834 if (!adap->bus_recovery_info)
837 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
838 return adap->bus_recovery_info->recover_bus(adap);
840 EXPORT_SYMBOL_GPL(i2c_recover_bus);
842 static void i2c_init_recovery(struct i2c_adapter *adap)
844 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
850 if (!bri->recover_bus) {
851 err_str = "no recover_bus() found";
855 /* Generic GPIO recovery */
856 if (bri->recover_bus == i2c_generic_gpio_recovery) {
857 if (!gpio_is_valid(bri->scl_gpio)) {
858 err_str = "invalid SCL gpio";
862 if (gpio_is_valid(bri->sda_gpio))
863 bri->get_sda = get_sda_gpio_value;
867 bri->get_scl = get_scl_gpio_value;
868 bri->set_scl = set_scl_gpio_value;
869 } else if (bri->recover_bus == i2c_generic_scl_recovery) {
870 /* Generic SCL recovery */
871 if (!bri->set_scl || !bri->get_scl) {
872 err_str = "no {get|set}_scl() found";
879 dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
880 adap->bus_recovery_info = NULL;
883 static int i2c_device_probe(struct device *dev)
885 struct i2c_client *client = i2c_verify_client(dev);
886 struct i2c_driver *driver;
896 irq = of_irq_get_byname(dev->of_node, "irq");
897 if (irq == -EINVAL || irq == -ENODATA)
898 irq = of_irq_get(dev->of_node, 0);
899 } else if (ACPI_COMPANION(dev)) {
900 irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
902 if (irq == -EPROBE_DEFER)
910 driver = to_i2c_driver(dev->driver);
911 if (!driver->probe || !driver->id_table)
914 if (client->flags & I2C_CLIENT_WAKE) {
915 int wakeirq = -ENOENT;
918 wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
919 if (wakeirq == -EPROBE_DEFER)
923 device_init_wakeup(&client->dev, true);
925 if (wakeirq > 0 && wakeirq != client->irq)
926 status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
927 else if (client->irq > 0)
928 status = dev_pm_set_wake_irq(dev, client->irq);
933 dev_warn(&client->dev, "failed to set up wakeup irq\n");
936 dev_dbg(dev, "probe\n");
938 status = of_clk_set_defaults(dev->of_node, false);
940 goto err_clear_wakeup_irq;
942 status = dev_pm_domain_attach(&client->dev, true);
943 if (status == -EPROBE_DEFER)
944 goto err_clear_wakeup_irq;
946 status = driver->probe(client, i2c_match_id(driver->id_table, client));
948 goto err_detach_pm_domain;
952 err_detach_pm_domain:
953 dev_pm_domain_detach(&client->dev, true);
954 err_clear_wakeup_irq:
955 dev_pm_clear_wake_irq(&client->dev);
956 device_init_wakeup(&client->dev, false);
960 static int i2c_device_remove(struct device *dev)
962 struct i2c_client *client = i2c_verify_client(dev);
963 struct i2c_driver *driver;
966 if (!client || !dev->driver)
969 driver = to_i2c_driver(dev->driver);
970 if (driver->remove) {
971 dev_dbg(dev, "remove\n");
972 status = driver->remove(client);
975 dev_pm_domain_detach(&client->dev, true);
977 dev_pm_clear_wake_irq(&client->dev);
978 device_init_wakeup(&client->dev, false);
983 static void i2c_device_shutdown(struct device *dev)
985 struct i2c_client *client = i2c_verify_client(dev);
986 struct i2c_driver *driver;
988 if (!client || !dev->driver)
990 driver = to_i2c_driver(dev->driver);
991 if (driver->shutdown)
992 driver->shutdown(client);
995 static void i2c_client_dev_release(struct device *dev)
997 kfree(to_i2c_client(dev));
1001 show_name(struct device *dev, struct device_attribute *attr, char *buf)
1003 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
1004 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
1006 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
1009 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
1011 struct i2c_client *client = to_i2c_client(dev);
1014 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
1018 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
1020 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
1022 static struct attribute *i2c_dev_attrs[] = {
1023 &dev_attr_name.attr,
1024 /* modalias helps coldplug: modprobe $(cat .../modalias) */
1025 &dev_attr_modalias.attr,
1028 ATTRIBUTE_GROUPS(i2c_dev);
1030 struct bus_type i2c_bus_type = {
1032 .match = i2c_device_match,
1033 .probe = i2c_device_probe,
1034 .remove = i2c_device_remove,
1035 .shutdown = i2c_device_shutdown,
1037 EXPORT_SYMBOL_GPL(i2c_bus_type);
1039 static struct device_type i2c_client_type = {
1040 .groups = i2c_dev_groups,
1041 .uevent = i2c_device_uevent,
1042 .release = i2c_client_dev_release,
1047 * i2c_verify_client - return parameter as i2c_client, or NULL
1048 * @dev: device, probably from some driver model iterator
1050 * When traversing the driver model tree, perhaps using driver model
1051 * iterators like @device_for_each_child(), you can't assume very much
1052 * about the nodes you find. Use this function to avoid oopses caused
1053 * by wrongly treating some non-I2C device as an i2c_client.
1055 struct i2c_client *i2c_verify_client(struct device *dev)
1057 return (dev->type == &i2c_client_type)
1058 ? to_i2c_client(dev)
1061 EXPORT_SYMBOL(i2c_verify_client);
1064 /* Return a unique address which takes the flags of the client into account */
1065 static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
1067 unsigned short addr = client->addr;
1069 /* For some client flags, add an arbitrary offset to avoid collisions */
1070 if (client->flags & I2C_CLIENT_TEN)
1071 addr |= I2C_ADDR_OFFSET_TEN_BIT;
1073 if (client->flags & I2C_CLIENT_SLAVE)
1074 addr |= I2C_ADDR_OFFSET_SLAVE;
1079 /* This is a permissive address validity check, I2C address map constraints
1080 * are purposely not enforced, except for the general call address. */
1081 static int i2c_check_addr_validity(unsigned addr, unsigned short flags)
1083 if (flags & I2C_CLIENT_TEN) {
1084 /* 10-bit address, all values are valid */
1088 /* 7-bit address, reject the general call address */
1089 if (addr == 0x00 || addr > 0x7f)
1095 /* And this is a strict address validity check, used when probing. If a
1096 * device uses a reserved address, then it shouldn't be probed. 7-bit
1097 * addressing is assumed, 10-bit address devices are rare and should be
1098 * explicitly enumerated. */
1099 static int i2c_check_7bit_addr_validity_strict(unsigned short addr)
1102 * Reserved addresses per I2C specification:
1103 * 0x00 General call address / START byte
1105 * 0x02 Reserved for different bus format
1106 * 0x03 Reserved for future purposes
1107 * 0x04-0x07 Hs-mode master code
1108 * 0x78-0x7b 10-bit slave addressing
1109 * 0x7c-0x7f Reserved for future purposes
1111 if (addr < 0x08 || addr > 0x77)
1116 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
1118 struct i2c_client *client = i2c_verify_client(dev);
1119 int addr = *(int *)addrp;
1121 if (client && i2c_encode_flags_to_addr(client) == addr)
1126 /* walk up mux tree */
1127 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
1129 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1132 result = device_for_each_child(&adapter->dev, &addr,
1133 __i2c_check_addr_busy);
1135 if (!result && parent)
1136 result = i2c_check_mux_parents(parent, addr);
1141 /* recurse down mux tree */
1142 static int i2c_check_mux_children(struct device *dev, void *addrp)
1146 if (dev->type == &i2c_adapter_type)
1147 result = device_for_each_child(dev, addrp,
1148 i2c_check_mux_children);
1150 result = __i2c_check_addr_busy(dev, addrp);
1155 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
1157 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1161 result = i2c_check_mux_parents(parent, addr);
1164 result = device_for_each_child(&adapter->dev, &addr,
1165 i2c_check_mux_children);
1171 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
1172 * @adapter: Target I2C bus segment
1173 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
1174 * locks only this branch in the adapter tree
1176 static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
1179 rt_mutex_lock(&adapter->bus_lock);
1183 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
1184 * @adapter: Target I2C bus segment
1185 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
1186 * trylocks only this branch in the adapter tree
1188 static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
1191 return rt_mutex_trylock(&adapter->bus_lock);
1195 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
1196 * @adapter: Target I2C bus segment
1197 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
1198 * unlocks only this branch in the adapter tree
1200 static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
1203 rt_mutex_unlock(&adapter->bus_lock);
1206 static void i2c_dev_set_name(struct i2c_adapter *adap,
1207 struct i2c_client *client)
1209 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
1212 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
1216 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
1217 i2c_encode_flags_to_addr(client));
1221 * i2c_new_device - instantiate an i2c device
1222 * @adap: the adapter managing the device
1223 * @info: describes one I2C device; bus_num is ignored
1224 * Context: can sleep
1226 * Create an i2c device. Binding is handled through driver model
1227 * probe()/remove() methods. A driver may be bound to this device when we
1228 * return from this function, or any later moment (e.g. maybe hotplugging will
1229 * load the driver module). This call is not appropriate for use by mainboard
1230 * initialization logic, which usually runs during an arch_initcall() long
1231 * before any i2c_adapter could exist.
1233 * This returns the new i2c client, which may be saved for later use with
1234 * i2c_unregister_device(); or NULL to indicate an error.
1237 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1239 struct i2c_client *client;
1242 client = kzalloc(sizeof *client, GFP_KERNEL);
1246 client->adapter = adap;
1248 client->dev.platform_data = info->platform_data;
1251 client->dev.archdata = *info->archdata;
1253 client->flags = info->flags;
1254 client->addr = info->addr;
1255 client->irq = info->irq;
1257 strlcpy(client->name, info->type, sizeof(client->name));
1259 status = i2c_check_addr_validity(client->addr, client->flags);
1261 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1262 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1263 goto out_err_silent;
1266 /* Check for address business */
1267 status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
1271 client->dev.parent = &client->adapter->dev;
1272 client->dev.bus = &i2c_bus_type;
1273 client->dev.type = &i2c_client_type;
1274 client->dev.of_node = info->of_node;
1275 client->dev.fwnode = info->fwnode;
1277 i2c_dev_set_name(adap, client);
1278 status = device_register(&client->dev);
1282 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1283 client->name, dev_name(&client->dev));
1289 "Failed to register i2c client %s at 0x%02x (%d)\n",
1290 client->name, client->addr, status);
1295 EXPORT_SYMBOL_GPL(i2c_new_device);
1299 * i2c_unregister_device - reverse effect of i2c_new_device()
1300 * @client: value returned from i2c_new_device()
1301 * Context: can sleep
1303 void i2c_unregister_device(struct i2c_client *client)
1305 if (client->dev.of_node)
1306 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
1307 if (ACPI_COMPANION(&client->dev))
1308 acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
1309 device_unregister(&client->dev);
1311 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1314 static const struct i2c_device_id dummy_id[] = {
1319 static int dummy_probe(struct i2c_client *client,
1320 const struct i2c_device_id *id)
1325 static int dummy_remove(struct i2c_client *client)
1330 static struct i2c_driver dummy_driver = {
1331 .driver.name = "dummy",
1332 .probe = dummy_probe,
1333 .remove = dummy_remove,
1334 .id_table = dummy_id,
1338 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1339 * @adapter: the adapter managing the device
1340 * @address: seven bit address to be used
1341 * Context: can sleep
1343 * This returns an I2C client bound to the "dummy" driver, intended for use
1344 * with devices that consume multiple addresses. Examples of such chips
1345 * include various EEPROMS (like 24c04 and 24c08 models).
1347 * These dummy devices have two main uses. First, most I2C and SMBus calls
1348 * except i2c_transfer() need a client handle; the dummy will be that handle.
1349 * And second, this prevents the specified address from being bound to a
1352 * This returns the new i2c client, which should be saved for later use with
1353 * i2c_unregister_device(); or NULL to indicate an error.
1355 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1357 struct i2c_board_info info = {
1358 I2C_BOARD_INFO("dummy", address),
1361 return i2c_new_device(adapter, &info);
1363 EXPORT_SYMBOL_GPL(i2c_new_dummy);
1366 * i2c_new_secondary_device - Helper to get the instantiated secondary address
1367 * and create the associated device
1368 * @client: Handle to the primary client
1369 * @name: Handle to specify which secondary address to get
1370 * @default_addr: Used as a fallback if no secondary address was specified
1371 * Context: can sleep
1373 * I2C clients can be composed of multiple I2C slaves bound together in a single
1374 * component. The I2C client driver then binds to the master I2C slave and needs
1375 * to create I2C dummy clients to communicate with all the other slaves.
1377 * This function creates and returns an I2C dummy client whose I2C address is
1378 * retrieved from the platform firmware based on the given slave name. If no
1379 * address is specified by the firmware default_addr is used.
1381 * On DT-based platforms the address is retrieved from the "reg" property entry
1382 * cell whose "reg-names" value matches the slave name.
1384 * This returns the new i2c client, which should be saved for later use with
1385 * i2c_unregister_device(); or NULL to indicate an error.
1387 struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
1391 struct device_node *np = client->dev.of_node;
1392 u32 addr = default_addr;
1396 i = of_property_match_string(np, "reg-names", name);
1398 of_property_read_u32_index(np, "reg", i, &addr);
1401 dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1402 return i2c_new_dummy(client->adapter, addr);
1404 EXPORT_SYMBOL_GPL(i2c_new_secondary_device);
1406 /* ------------------------------------------------------------------------- */
1408 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1410 static void i2c_adapter_dev_release(struct device *dev)
1412 struct i2c_adapter *adap = to_i2c_adapter(dev);
1413 complete(&adap->dev_released);
1417 * This function is only needed for mutex_lock_nested, so it is never
1418 * called unless locking correctness checking is enabled. Thus we
1419 * make it inline to avoid a compiler warning. That's what gcc ends up
1422 static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1424 unsigned int depth = 0;
1426 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1433 * Let users instantiate I2C devices through sysfs. This can be used when
1434 * platform initialization code doesn't contain the proper data for
1435 * whatever reason. Also useful for drivers that do device detection and
1436 * detection fails, either because the device uses an unexpected address,
1437 * or this is a compatible device with different ID register values.
1439 * Parameter checking may look overzealous, but we really don't want
1440 * the user to provide incorrect parameters.
1443 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1444 const char *buf, size_t count)
1446 struct i2c_adapter *adap = to_i2c_adapter(dev);
1447 struct i2c_board_info info;
1448 struct i2c_client *client;
1452 memset(&info, 0, sizeof(struct i2c_board_info));
1454 blank = strchr(buf, ' ');
1456 dev_err(dev, "%s: Missing parameters\n", "new_device");
1459 if (blank - buf > I2C_NAME_SIZE - 1) {
1460 dev_err(dev, "%s: Invalid device name\n", "new_device");
1463 memcpy(info.type, buf, blank - buf);
1465 /* Parse remaining parameters, reject extra parameters */
1466 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1468 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1471 if (res > 1 && end != '\n') {
1472 dev_err(dev, "%s: Extra parameters\n", "new_device");
1476 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1477 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1478 info.flags |= I2C_CLIENT_TEN;
1481 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1482 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1483 info.flags |= I2C_CLIENT_SLAVE;
1486 client = i2c_new_device(adap, &info);
1490 /* Keep track of the added device */
1491 mutex_lock(&adap->userspace_clients_lock);
1492 list_add_tail(&client->detected, &adap->userspace_clients);
1493 mutex_unlock(&adap->userspace_clients_lock);
1494 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1495 info.type, info.addr);
1499 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1502 * And of course let the users delete the devices they instantiated, if
1503 * they got it wrong. This interface can only be used to delete devices
1504 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1505 * don't delete devices to which some kernel code still has references.
1507 * Parameter checking may look overzealous, but we really don't want
1508 * the user to delete the wrong device.
1511 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1512 const char *buf, size_t count)
1514 struct i2c_adapter *adap = to_i2c_adapter(dev);
1515 struct i2c_client *client, *next;
1516 unsigned short addr;
1520 /* Parse parameters, reject extra parameters */
1521 res = sscanf(buf, "%hi%c", &addr, &end);
1523 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1526 if (res > 1 && end != '\n') {
1527 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1531 /* Make sure the device was added through sysfs */
1533 mutex_lock_nested(&adap->userspace_clients_lock,
1534 i2c_adapter_depth(adap));
1535 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1537 if (i2c_encode_flags_to_addr(client) == addr) {
1538 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1539 "delete_device", client->name, client->addr);
1541 list_del(&client->detected);
1542 i2c_unregister_device(client);
1547 mutex_unlock(&adap->userspace_clients_lock);
1550 dev_err(dev, "%s: Can't find device in list\n",
1554 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1555 i2c_sysfs_delete_device);
1557 static struct attribute *i2c_adapter_attrs[] = {
1558 &dev_attr_name.attr,
1559 &dev_attr_new_device.attr,
1560 &dev_attr_delete_device.attr,
1563 ATTRIBUTE_GROUPS(i2c_adapter);
1565 struct device_type i2c_adapter_type = {
1566 .groups = i2c_adapter_groups,
1567 .release = i2c_adapter_dev_release,
1569 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1572 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1573 * @dev: device, probably from some driver model iterator
1575 * When traversing the driver model tree, perhaps using driver model
1576 * iterators like @device_for_each_child(), you can't assume very much
1577 * about the nodes you find. Use this function to avoid oopses caused
1578 * by wrongly treating some non-I2C device as an i2c_adapter.
1580 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1582 return (dev->type == &i2c_adapter_type)
1583 ? to_i2c_adapter(dev)
1586 EXPORT_SYMBOL(i2c_verify_adapter);
1588 #ifdef CONFIG_I2C_COMPAT
1589 static struct class_compat *i2c_adapter_compat_class;
1592 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1594 struct i2c_devinfo *devinfo;
1596 down_read(&__i2c_board_lock);
1597 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1598 if (devinfo->busnum == adapter->nr
1599 && !i2c_new_device(adapter,
1600 &devinfo->board_info))
1601 dev_err(&adapter->dev,
1602 "Can't create device at 0x%02x\n",
1603 devinfo->board_info.addr);
1605 up_read(&__i2c_board_lock);
1608 /* OF support code */
1610 #if IS_ENABLED(CONFIG_OF)
1611 static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1612 struct device_node *node)
1614 struct i2c_client *result;
1615 struct i2c_board_info info = {};
1616 struct dev_archdata dev_ad = {};
1617 const __be32 *addr_be;
1621 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1623 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1624 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1626 return ERR_PTR(-EINVAL);
1629 addr_be = of_get_property(node, "reg", &len);
1630 if (!addr_be || (len < sizeof(*addr_be))) {
1631 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1633 return ERR_PTR(-EINVAL);
1636 addr = be32_to_cpup(addr_be);
1637 if (addr & I2C_TEN_BIT_ADDRESS) {
1638 addr &= ~I2C_TEN_BIT_ADDRESS;
1639 info.flags |= I2C_CLIENT_TEN;
1642 if (addr & I2C_OWN_SLAVE_ADDRESS) {
1643 addr &= ~I2C_OWN_SLAVE_ADDRESS;
1644 info.flags |= I2C_CLIENT_SLAVE;
1647 if (i2c_check_addr_validity(addr, info.flags)) {
1648 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1649 info.addr, node->full_name);
1650 return ERR_PTR(-EINVAL);
1654 info.of_node = of_node_get(node);
1655 info.archdata = &dev_ad;
1657 if (of_get_property(node, "wakeup-source", NULL))
1658 info.flags |= I2C_CLIENT_WAKE;
1660 result = i2c_new_device(adap, &info);
1661 if (result == NULL) {
1662 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1665 return ERR_PTR(-EINVAL);
1670 static void of_i2c_register_devices(struct i2c_adapter *adap)
1672 struct device_node *node;
1674 /* Only register child devices if the adapter has a node pointer set */
1675 if (!adap->dev.of_node)
1678 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1680 for_each_available_child_of_node(adap->dev.of_node, node) {
1681 if (of_node_test_and_set_flag(node, OF_POPULATED))
1683 of_i2c_register_device(adap, node);
1687 static int of_dev_node_match(struct device *dev, void *data)
1689 return dev->of_node == data;
1692 /* must call put_device() when done with returned i2c_client device */
1693 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1696 struct i2c_client *client;
1698 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1702 client = i2c_verify_client(dev);
1708 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1710 /* must call put_device() when done with returned i2c_adapter device */
1711 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1714 struct i2c_adapter *adapter;
1716 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1720 adapter = i2c_verify_adapter(dev);
1726 EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1728 /* must call i2c_put_adapter() when done with returned i2c_adapter device */
1729 struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1731 struct i2c_adapter *adapter;
1733 adapter = of_find_i2c_adapter_by_node(node);
1737 if (!try_module_get(adapter->owner)) {
1738 put_device(&adapter->dev);
1744 EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1746 static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1747 #endif /* CONFIG_OF */
1749 static int i2c_do_add_adapter(struct i2c_driver *driver,
1750 struct i2c_adapter *adap)
1752 /* Detect supported devices on that bus, and instantiate them */
1753 i2c_detect(adap, driver);
1755 /* Let legacy drivers scan this bus for matching devices */
1756 if (driver->attach_adapter) {
1757 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1758 driver->driver.name);
1759 dev_warn(&adap->dev,
1760 "Please use another way to instantiate your i2c_client\n");
1761 /* We ignore the return code; if it fails, too bad */
1762 driver->attach_adapter(adap);
1767 static int __process_new_adapter(struct device_driver *d, void *data)
1769 return i2c_do_add_adapter(to_i2c_driver(d), data);
1772 static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1773 .lock_bus = i2c_adapter_lock_bus,
1774 .trylock_bus = i2c_adapter_trylock_bus,
1775 .unlock_bus = i2c_adapter_unlock_bus,
1778 static int i2c_register_adapter(struct i2c_adapter *adap)
1782 /* Can't register until after driver model init */
1783 if (WARN_ON(!is_registered)) {
1789 if (WARN(!adap->name[0], "i2c adapter has no name"))
1793 pr_err("adapter '%s': no algo supplied!\n", adap->name);
1797 if (!adap->lock_ops)
1798 adap->lock_ops = &i2c_adapter_lock_ops;
1800 rt_mutex_init(&adap->bus_lock);
1801 rt_mutex_init(&adap->mux_lock);
1802 mutex_init(&adap->userspace_clients_lock);
1803 INIT_LIST_HEAD(&adap->userspace_clients);
1805 /* Set default timeout to 1 second if not already set */
1806 if (adap->timeout == 0)
1809 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1810 adap->dev.bus = &i2c_bus_type;
1811 adap->dev.type = &i2c_adapter_type;
1812 res = device_register(&adap->dev);
1814 pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
1818 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1820 pm_runtime_no_callbacks(&adap->dev);
1821 pm_suspend_ignore_children(&adap->dev, true);
1822 pm_runtime_enable(&adap->dev);
1824 #ifdef CONFIG_I2C_COMPAT
1825 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1828 dev_warn(&adap->dev,
1829 "Failed to create compatibility class link\n");
1832 i2c_init_recovery(adap);
1834 /* create pre-declared device nodes */
1835 of_i2c_register_devices(adap);
1836 i2c_acpi_register_devices(adap);
1837 i2c_acpi_install_space_handler(adap);
1839 if (adap->nr < __i2c_first_dynamic_bus_num)
1840 i2c_scan_static_board_info(adap);
1842 /* Notify drivers */
1843 mutex_lock(&core_lock);
1844 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1845 mutex_unlock(&core_lock);
1850 mutex_lock(&core_lock);
1851 idr_remove(&i2c_adapter_idr, adap->nr);
1852 mutex_unlock(&core_lock);
1857 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1858 * @adap: the adapter to register (with adap->nr initialized)
1859 * Context: can sleep
1861 * See i2c_add_numbered_adapter() for details.
1863 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1867 mutex_lock(&core_lock);
1868 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
1869 mutex_unlock(&core_lock);
1870 if (WARN(id < 0, "couldn't get idr"))
1871 return id == -ENOSPC ? -EBUSY : id;
1873 return i2c_register_adapter(adap);
1877 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1878 * @adapter: the adapter to add
1879 * Context: can sleep
1881 * This routine is used to declare an I2C adapter when its bus number
1882 * doesn't matter or when its bus number is specified by an dt alias.
1883 * Examples of bases when the bus number doesn't matter: I2C adapters
1884 * dynamically added by USB links or PCI plugin cards.
1886 * When this returns zero, a new bus number was allocated and stored
1887 * in adap->nr, and the specified adapter became available for clients.
1888 * Otherwise, a negative errno value is returned.
1890 int i2c_add_adapter(struct i2c_adapter *adapter)
1892 struct device *dev = &adapter->dev;
1896 id = of_alias_get_id(dev->of_node, "i2c");
1899 return __i2c_add_numbered_adapter(adapter);
1903 mutex_lock(&core_lock);
1904 id = idr_alloc(&i2c_adapter_idr, adapter,
1905 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1906 mutex_unlock(&core_lock);
1907 if (WARN(id < 0, "couldn't get idr"))
1912 return i2c_register_adapter(adapter);
1914 EXPORT_SYMBOL(i2c_add_adapter);
1917 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1918 * @adap: the adapter to register (with adap->nr initialized)
1919 * Context: can sleep
1921 * This routine is used to declare an I2C adapter when its bus number
1922 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1923 * or otherwise built in to the system's mainboard, and where i2c_board_info
1924 * is used to properly configure I2C devices.
1926 * If the requested bus number is set to -1, then this function will behave
1927 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1929 * If no devices have pre-been declared for this bus, then be sure to
1930 * register the adapter before any dynamically allocated ones. Otherwise
1931 * the required bus ID may not be available.
1933 * When this returns zero, the specified adapter became available for
1934 * clients using the bus number provided in adap->nr. Also, the table
1935 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1936 * and the appropriate driver model device nodes are created. Otherwise, a
1937 * negative errno value is returned.
1939 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1941 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1942 return i2c_add_adapter(adap);
1944 return __i2c_add_numbered_adapter(adap);
1946 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1948 static void i2c_do_del_adapter(struct i2c_driver *driver,
1949 struct i2c_adapter *adapter)
1951 struct i2c_client *client, *_n;
1953 /* Remove the devices we created ourselves as the result of hardware
1954 * probing (using a driver's detect method) */
1955 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1956 if (client->adapter == adapter) {
1957 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1958 client->name, client->addr);
1959 list_del(&client->detected);
1960 i2c_unregister_device(client);
1965 static int __unregister_client(struct device *dev, void *dummy)
1967 struct i2c_client *client = i2c_verify_client(dev);
1968 if (client && strcmp(client->name, "dummy"))
1969 i2c_unregister_device(client);
1973 static int __unregister_dummy(struct device *dev, void *dummy)
1975 struct i2c_client *client = i2c_verify_client(dev);
1977 i2c_unregister_device(client);
1981 static int __process_removed_adapter(struct device_driver *d, void *data)
1983 i2c_do_del_adapter(to_i2c_driver(d), data);
1988 * i2c_del_adapter - unregister I2C adapter
1989 * @adap: the adapter being unregistered
1990 * Context: can sleep
1992 * This unregisters an I2C adapter which was previously registered
1993 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1995 void i2c_del_adapter(struct i2c_adapter *adap)
1997 struct i2c_adapter *found;
1998 struct i2c_client *client, *next;
2000 /* First make sure that this adapter was ever added */
2001 mutex_lock(&core_lock);
2002 found = idr_find(&i2c_adapter_idr, adap->nr);
2003 mutex_unlock(&core_lock);
2004 if (found != adap) {
2005 pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
2009 i2c_acpi_remove_space_handler(adap);
2010 /* Tell drivers about this removal */
2011 mutex_lock(&core_lock);
2012 bus_for_each_drv(&i2c_bus_type, NULL, adap,
2013 __process_removed_adapter);
2014 mutex_unlock(&core_lock);
2016 /* Remove devices instantiated from sysfs */
2017 mutex_lock_nested(&adap->userspace_clients_lock,
2018 i2c_adapter_depth(adap));
2019 list_for_each_entry_safe(client, next, &adap->userspace_clients,
2021 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
2023 list_del(&client->detected);
2024 i2c_unregister_device(client);
2026 mutex_unlock(&adap->userspace_clients_lock);
2028 /* Detach any active clients. This can't fail, thus we do not
2029 * check the returned value. This is a two-pass process, because
2030 * we can't remove the dummy devices during the first pass: they
2031 * could have been instantiated by real devices wishing to clean
2032 * them up properly, so we give them a chance to do that first. */
2033 device_for_each_child(&adap->dev, NULL, __unregister_client);
2034 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
2036 #ifdef CONFIG_I2C_COMPAT
2037 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
2041 /* device name is gone after device_unregister */
2042 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
2044 pm_runtime_disable(&adap->dev);
2046 /* wait until all references to the device are gone
2048 * FIXME: This is old code and should ideally be replaced by an
2049 * alternative which results in decoupling the lifetime of the struct
2050 * device from the i2c_adapter, like spi or netdev do. Any solution
2051 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
2053 init_completion(&adap->dev_released);
2054 device_unregister(&adap->dev);
2055 wait_for_completion(&adap->dev_released);
2058 mutex_lock(&core_lock);
2059 idr_remove(&i2c_adapter_idr, adap->nr);
2060 mutex_unlock(&core_lock);
2062 /* Clear the device structure in case this adapter is ever going to be
2064 memset(&adap->dev, 0, sizeof(adap->dev));
2066 EXPORT_SYMBOL(i2c_del_adapter);
2069 * i2c_parse_fw_timings - get I2C related timing parameters from firmware
2070 * @dev: The device to scan for I2C timing properties
2071 * @t: the i2c_timings struct to be filled with values
2072 * @use_defaults: bool to use sane defaults derived from the I2C specification
2073 * when properties are not found, otherwise use 0
2075 * Scan the device for the generic I2C properties describing timing parameters
2076 * for the signal and fill the given struct with the results. If a property was
2077 * not found and use_defaults was true, then maximum timings are assumed which
2078 * are derived from the I2C specification. If use_defaults is not used, the
2079 * results will be 0, so drivers can apply their own defaults later. The latter
2080 * is mainly intended for avoiding regressions of existing drivers which want
2081 * to switch to this function. New drivers almost always should use the defaults.
2084 void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
2088 memset(t, 0, sizeof(*t));
2090 ret = device_property_read_u32(dev, "clock-frequency", &t->bus_freq_hz);
2091 if (ret && use_defaults)
2092 t->bus_freq_hz = 100000;
2094 ret = device_property_read_u32(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns);
2095 if (ret && use_defaults) {
2096 if (t->bus_freq_hz <= 100000)
2097 t->scl_rise_ns = 1000;
2098 else if (t->bus_freq_hz <= 400000)
2099 t->scl_rise_ns = 300;
2101 t->scl_rise_ns = 120;
2104 ret = device_property_read_u32(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns);
2105 if (ret && use_defaults) {
2106 if (t->bus_freq_hz <= 400000)
2107 t->scl_fall_ns = 300;
2109 t->scl_fall_ns = 120;
2112 device_property_read_u32(dev, "i2c-scl-internal-delay-ns", &t->scl_int_delay_ns);
2114 ret = device_property_read_u32(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns);
2115 if (ret && use_defaults)
2116 t->sda_fall_ns = t->scl_fall_ns;
2118 EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
2120 /* ------------------------------------------------------------------------- */
2122 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
2126 mutex_lock(&core_lock);
2127 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
2128 mutex_unlock(&core_lock);
2132 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
2134 static int __process_new_driver(struct device *dev, void *data)
2136 if (dev->type != &i2c_adapter_type)
2138 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
2142 * An i2c_driver is used with one or more i2c_client (device) nodes to access
2143 * i2c slave chips, on a bus instance associated with some i2c_adapter.
2146 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
2150 /* Can't register until after driver model init */
2151 if (WARN_ON(!is_registered))
2154 /* add the driver to the list of i2c drivers in the driver core */
2155 driver->driver.owner = owner;
2156 driver->driver.bus = &i2c_bus_type;
2158 /* When registration returns, the driver core
2159 * will have called probe() for all matching-but-unbound devices.
2161 res = driver_register(&driver->driver);
2165 pr_debug("driver [%s] registered\n", driver->driver.name);
2167 INIT_LIST_HEAD(&driver->clients);
2168 /* Walk the adapters that are already present */
2169 i2c_for_each_dev(driver, __process_new_driver);
2173 EXPORT_SYMBOL(i2c_register_driver);
2175 static int __process_removed_driver(struct device *dev, void *data)
2177 if (dev->type == &i2c_adapter_type)
2178 i2c_do_del_adapter(data, to_i2c_adapter(dev));
2183 * i2c_del_driver - unregister I2C driver
2184 * @driver: the driver being unregistered
2185 * Context: can sleep
2187 void i2c_del_driver(struct i2c_driver *driver)
2189 i2c_for_each_dev(driver, __process_removed_driver);
2191 driver_unregister(&driver->driver);
2192 pr_debug("driver [%s] unregistered\n", driver->driver.name);
2194 EXPORT_SYMBOL(i2c_del_driver);
2196 /* ------------------------------------------------------------------------- */
2199 * i2c_use_client - increments the reference count of the i2c client structure
2200 * @client: the client being referenced
2202 * Each live reference to a client should be refcounted. The driver model does
2203 * that automatically as part of driver binding, so that most drivers don't
2204 * need to do this explicitly: they hold a reference until they're unbound
2207 * A pointer to the client with the incremented reference counter is returned.
2209 struct i2c_client *i2c_use_client(struct i2c_client *client)
2211 if (client && get_device(&client->dev))
2215 EXPORT_SYMBOL(i2c_use_client);
2218 * i2c_release_client - release a use of the i2c client structure
2219 * @client: the client being no longer referenced
2221 * Must be called when a user of a client is finished with it.
2223 void i2c_release_client(struct i2c_client *client)
2226 put_device(&client->dev);
2228 EXPORT_SYMBOL(i2c_release_client);
2230 struct i2c_cmd_arg {
2235 static int i2c_cmd(struct device *dev, void *_arg)
2237 struct i2c_client *client = i2c_verify_client(dev);
2238 struct i2c_cmd_arg *arg = _arg;
2239 struct i2c_driver *driver;
2241 if (!client || !client->dev.driver)
2244 driver = to_i2c_driver(client->dev.driver);
2245 if (driver->command)
2246 driver->command(client, arg->cmd, arg->arg);
2250 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
2252 struct i2c_cmd_arg cmd_arg;
2256 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
2258 EXPORT_SYMBOL(i2c_clients_command);
2260 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
2261 static int of_i2c_notify(struct notifier_block *nb, unsigned long action,
2264 struct of_reconfig_data *rd = arg;
2265 struct i2c_adapter *adap;
2266 struct i2c_client *client;
2268 switch (of_reconfig_get_state_change(action, rd)) {
2269 case OF_RECONFIG_CHANGE_ADD:
2270 adap = of_find_i2c_adapter_by_node(rd->dn->parent);
2272 return NOTIFY_OK; /* not for us */
2274 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
2275 put_device(&adap->dev);
2279 client = of_i2c_register_device(adap, rd->dn);
2280 put_device(&adap->dev);
2282 if (IS_ERR(client)) {
2283 dev_err(&adap->dev, "failed to create client for '%s'\n",
2285 return notifier_from_errno(PTR_ERR(client));
2288 case OF_RECONFIG_CHANGE_REMOVE:
2289 /* already depopulated? */
2290 if (!of_node_check_flag(rd->dn, OF_POPULATED))
2293 /* find our device by node */
2294 client = of_find_i2c_device_by_node(rd->dn);
2296 return NOTIFY_OK; /* no? not meant for us */
2298 /* unregister takes one ref away */
2299 i2c_unregister_device(client);
2301 /* and put the reference of the find */
2302 put_device(&client->dev);
2308 static struct notifier_block i2c_of_notifier = {
2309 .notifier_call = of_i2c_notify,
2312 extern struct notifier_block i2c_of_notifier;
2313 #endif /* CONFIG_OF_DYNAMIC */
2315 static int __init i2c_init(void)
2319 retval = of_alias_get_highest_id("i2c");
2321 down_write(&__i2c_board_lock);
2322 if (retval >= __i2c_first_dynamic_bus_num)
2323 __i2c_first_dynamic_bus_num = retval + 1;
2324 up_write(&__i2c_board_lock);
2326 retval = bus_register(&i2c_bus_type);
2330 is_registered = true;
2332 #ifdef CONFIG_I2C_COMPAT
2333 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
2334 if (!i2c_adapter_compat_class) {
2339 retval = i2c_add_driver(&dummy_driver);
2343 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2344 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
2345 if (IS_ENABLED(CONFIG_ACPI))
2346 WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
2351 #ifdef CONFIG_I2C_COMPAT
2352 class_compat_unregister(i2c_adapter_compat_class);
2355 is_registered = false;
2356 bus_unregister(&i2c_bus_type);
2360 static void __exit i2c_exit(void)
2362 if (IS_ENABLED(CONFIG_ACPI))
2363 WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
2364 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2365 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
2366 i2c_del_driver(&dummy_driver);
2367 #ifdef CONFIG_I2C_COMPAT
2368 class_compat_unregister(i2c_adapter_compat_class);
2370 bus_unregister(&i2c_bus_type);
2371 tracepoint_synchronize_unregister();
2374 /* We must initialize early, because some subsystems register i2c drivers
2375 * in subsys_initcall() code, but are linked (and initialized) before i2c.
2377 postcore_initcall(i2c_init);
2378 module_exit(i2c_exit);
2380 /* ----------------------------------------------------
2381 * the functional interface to the i2c busses.
2382 * ----------------------------------------------------
2385 /* Check if val is exceeding the quirk IFF quirk is non 0 */
2386 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2388 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2390 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2391 err_msg, msg->addr, msg->len,
2392 msg->flags & I2C_M_RD ? "read" : "write");
2396 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2398 const struct i2c_adapter_quirks *q = adap->quirks;
2399 int max_num = q->max_num_msgs, i;
2400 bool do_len_check = true;
2402 if (q->flags & I2C_AQ_COMB) {
2405 /* special checks for combined messages */
2407 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2408 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2410 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2411 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2413 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2414 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2416 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2417 return i2c_quirk_error(adap, &msgs[0], "msg too long");
2419 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2420 return i2c_quirk_error(adap, &msgs[1], "msg too long");
2422 do_len_check = false;
2426 if (i2c_quirk_exceeded(num, max_num))
2427 return i2c_quirk_error(adap, &msgs[0], "too many messages");
2429 for (i = 0; i < num; i++) {
2430 u16 len = msgs[i].len;
2432 if (msgs[i].flags & I2C_M_RD) {
2433 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2434 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2436 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2437 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2445 * __i2c_transfer - unlocked flavor of i2c_transfer
2446 * @adap: Handle to I2C bus
2447 * @msgs: One or more messages to execute before STOP is issued to
2448 * terminate the operation; each message begins with a START.
2449 * @num: Number of messages to be executed.
2451 * Returns negative errno, else the number of messages executed.
2453 * Adapter lock must be held when calling this function. No debug logging
2454 * takes place. adap->algo->master_xfer existence isn't checked.
2456 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2458 unsigned long orig_jiffies;
2461 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2464 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2465 * enabled. This is an efficient way of keeping the for-loop from
2466 * being executed when not needed.
2468 if (static_key_false(&i2c_trace_msg)) {
2470 for (i = 0; i < num; i++)
2471 if (msgs[i].flags & I2C_M_RD)
2472 trace_i2c_read(adap, &msgs[i], i);
2474 trace_i2c_write(adap, &msgs[i], i);
2477 /* Retry automatically on arbitration loss */
2478 orig_jiffies = jiffies;
2479 for (ret = 0, try = 0; try <= adap->retries; try++) {
2480 ret = adap->algo->master_xfer(adap, msgs, num);
2483 if (time_after(jiffies, orig_jiffies + adap->timeout))
2487 if (static_key_false(&i2c_trace_msg)) {
2489 for (i = 0; i < ret; i++)
2490 if (msgs[i].flags & I2C_M_RD)
2491 trace_i2c_reply(adap, &msgs[i], i);
2492 trace_i2c_result(adap, i, ret);
2497 EXPORT_SYMBOL(__i2c_transfer);
2500 * i2c_transfer - execute a single or combined I2C message
2501 * @adap: Handle to I2C bus
2502 * @msgs: One or more messages to execute before STOP is issued to
2503 * terminate the operation; each message begins with a START.
2504 * @num: Number of messages to be executed.
2506 * Returns negative errno, else the number of messages executed.
2508 * Note that there is no requirement that each message be sent to
2509 * the same slave address, although that is the most common model.
2511 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2515 /* REVISIT the fault reporting model here is weak:
2517 * - When we get an error after receiving N bytes from a slave,
2518 * there is no way to report "N".
2520 * - When we get a NAK after transmitting N bytes to a slave,
2521 * there is no way to report "N" ... or to let the master
2522 * continue executing the rest of this combined message, if
2523 * that's the appropriate response.
2525 * - When for example "num" is two and we successfully complete
2526 * the first message but get an error part way through the
2527 * second, it's unclear whether that should be reported as
2528 * one (discarding status on the second message) or errno
2529 * (discarding status on the first one).
2532 if (adap->algo->master_xfer) {
2534 for (ret = 0; ret < num; ret++) {
2536 "master_xfer[%d] %c, addr=0x%02x, len=%d%s\n",
2537 ret, (msgs[ret].flags & I2C_M_RD) ? 'R' : 'W',
2538 msgs[ret].addr, msgs[ret].len,
2539 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2543 if (in_atomic() || irqs_disabled()) {
2544 ret = i2c_trylock_bus(adap, I2C_LOCK_SEGMENT);
2546 /* I2C activity is ongoing. */
2549 i2c_lock_bus(adap, I2C_LOCK_SEGMENT);
2552 ret = __i2c_transfer(adap, msgs, num);
2553 i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
2557 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2561 EXPORT_SYMBOL(i2c_transfer);
2564 * i2c_master_send - issue a single I2C message in master transmit mode
2565 * @client: Handle to slave device
2566 * @buf: Data that will be written to the slave
2567 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2569 * Returns negative errno, or else the number of bytes written.
2571 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2574 struct i2c_adapter *adap = client->adapter;
2577 msg.addr = client->addr;
2578 msg.flags = client->flags & I2C_M_TEN;
2580 msg.buf = (char *)buf;
2582 ret = i2c_transfer(adap, &msg, 1);
2585 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2586 * transmitted, else error code.
2588 return (ret == 1) ? count : ret;
2590 EXPORT_SYMBOL(i2c_master_send);
2593 * i2c_master_recv - issue a single I2C message in master receive mode
2594 * @client: Handle to slave device
2595 * @buf: Where to store data read from slave
2596 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2598 * Returns negative errno, or else the number of bytes read.
2600 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2602 struct i2c_adapter *adap = client->adapter;
2606 msg.addr = client->addr;
2607 msg.flags = client->flags & I2C_M_TEN;
2608 msg.flags |= I2C_M_RD;
2612 ret = i2c_transfer(adap, &msg, 1);
2615 * If everything went ok (i.e. 1 msg received), return #bytes received,
2618 return (ret == 1) ? count : ret;
2620 EXPORT_SYMBOL(i2c_master_recv);
2622 /* ----------------------------------------------------
2623 * the i2c address scanning function
2624 * Will not work for 10-bit addresses!
2625 * ----------------------------------------------------
2629 * Legacy default probe function, mostly relevant for SMBus. The default
2630 * probe method is a quick write, but it is known to corrupt the 24RF08
2631 * EEPROMs due to a state machine bug, and could also irreversibly
2632 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2633 * we use a short byte read instead. Also, some bus drivers don't implement
2634 * quick write, so we fallback to a byte read in that case too.
2635 * On x86, there is another special case for FSC hardware monitoring chips,
2636 * which want regular byte reads (address 0x73.) Fortunately, these are the
2637 * only known chips using this I2C address on PC hardware.
2638 * Returns 1 if probe succeeded, 0 if not.
2640 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2643 union i2c_smbus_data dummy;
2646 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2647 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2648 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2649 I2C_SMBUS_BYTE_DATA, &dummy);
2652 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2653 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2654 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2655 I2C_SMBUS_QUICK, NULL);
2656 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2657 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2658 I2C_SMBUS_BYTE, &dummy);
2660 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2668 static int i2c_detect_address(struct i2c_client *temp_client,
2669 struct i2c_driver *driver)
2671 struct i2c_board_info info;
2672 struct i2c_adapter *adapter = temp_client->adapter;
2673 int addr = temp_client->addr;
2676 /* Make sure the address is valid */
2677 err = i2c_check_7bit_addr_validity_strict(addr);
2679 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2684 /* Skip if already in use (7 bit, no need to encode flags) */
2685 if (i2c_check_addr_busy(adapter, addr))
2688 /* Make sure there is something at this address */
2689 if (!i2c_default_probe(adapter, addr))
2692 /* Finally call the custom detection function */
2693 memset(&info, 0, sizeof(struct i2c_board_info));
2695 err = driver->detect(temp_client, &info);
2697 /* -ENODEV is returned if the detection fails. We catch it
2698 here as this isn't an error. */
2699 return err == -ENODEV ? 0 : err;
2702 /* Consistency check */
2703 if (info.type[0] == '\0') {
2704 dev_err(&adapter->dev,
2705 "%s detection function provided no name for 0x%x\n",
2706 driver->driver.name, addr);
2708 struct i2c_client *client;
2710 /* Detection succeeded, instantiate the device */
2711 if (adapter->class & I2C_CLASS_DEPRECATED)
2712 dev_warn(&adapter->dev,
2713 "This adapter will soon drop class based instantiation of devices. "
2714 "Please make sure client 0x%02x gets instantiated by other means. "
2715 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2718 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2719 info.type, info.addr);
2720 client = i2c_new_device(adapter, &info);
2722 list_add_tail(&client->detected, &driver->clients);
2724 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2725 info.type, info.addr);
2730 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2732 const unsigned short *address_list;
2733 struct i2c_client *temp_client;
2735 int adap_id = i2c_adapter_id(adapter);
2737 address_list = driver->address_list;
2738 if (!driver->detect || !address_list)
2741 /* Warn that the adapter lost class based instantiation */
2742 if (adapter->class == I2C_CLASS_DEPRECATED) {
2743 dev_dbg(&adapter->dev,
2744 "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
2745 "If you need it, check 'Documentation/i2c/instantiating-devices' for alternatives.\n",
2746 driver->driver.name);
2750 /* Stop here if the classes do not match */
2751 if (!(adapter->class & driver->class))
2754 /* Set up a temporary client to help detect callback */
2755 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2758 temp_client->adapter = adapter;
2760 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2761 dev_dbg(&adapter->dev,
2762 "found normal entry for adapter %d, addr 0x%02x\n",
2763 adap_id, address_list[i]);
2764 temp_client->addr = address_list[i];
2765 err = i2c_detect_address(temp_client, driver);
2774 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2776 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2777 I2C_SMBUS_QUICK, NULL) >= 0;
2779 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2782 i2c_new_probed_device(struct i2c_adapter *adap,
2783 struct i2c_board_info *info,
2784 unsigned short const *addr_list,
2785 int (*probe)(struct i2c_adapter *, unsigned short addr))
2790 probe = i2c_default_probe;
2792 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2793 /* Check address validity */
2794 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2795 dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
2800 /* Check address availability (7 bit, no need to encode flags) */
2801 if (i2c_check_addr_busy(adap, addr_list[i])) {
2803 "Address 0x%02x already in use, not probing\n",
2808 /* Test address responsiveness */
2809 if (probe(adap, addr_list[i]))
2813 if (addr_list[i] == I2C_CLIENT_END) {
2814 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2818 info->addr = addr_list[i];
2819 return i2c_new_device(adap, info);
2821 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2823 struct i2c_adapter *i2c_get_adapter(int nr)
2825 struct i2c_adapter *adapter;
2827 mutex_lock(&core_lock);
2828 adapter = idr_find(&i2c_adapter_idr, nr);
2832 if (try_module_get(adapter->owner))
2833 get_device(&adapter->dev);
2838 mutex_unlock(&core_lock);
2841 EXPORT_SYMBOL(i2c_get_adapter);
2843 void i2c_put_adapter(struct i2c_adapter *adap)
2848 put_device(&adap->dev);
2849 module_put(adap->owner);
2851 EXPORT_SYMBOL(i2c_put_adapter);
2853 /* The SMBus parts */
2855 #define POLY (0x1070U << 3)
2856 static u8 crc8(u16 data)
2860 for (i = 0; i < 8; i++) {
2865 return (u8)(data >> 8);
2868 /* Incremental CRC8 over count bytes in the array pointed to by p */
2869 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2873 for (i = 0; i < count; i++)
2874 crc = crc8((crc ^ p[i]) << 8);
2878 /* Assume a 7-bit address, which is reasonable for SMBus */
2879 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2881 /* The address will be sent first */
2882 u8 addr = i2c_8bit_addr_from_msg(msg);
2883 pec = i2c_smbus_pec(pec, &addr, 1);
2885 /* The data buffer follows */
2886 return i2c_smbus_pec(pec, msg->buf, msg->len);
2889 /* Used for write only transactions */
2890 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2892 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2896 /* Return <0 on CRC error
2897 If there was a write before this read (most cases) we need to take the
2898 partial CRC from the write part into account.
2899 Note that this function does modify the message (we need to decrease the
2900 message length to hide the CRC byte from the caller). */
2901 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2903 u8 rpec = msg->buf[--msg->len];
2904 cpec = i2c_smbus_msg_pec(cpec, msg);
2907 pr_debug("Bad PEC 0x%02x vs. 0x%02x\n",
2915 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2916 * @client: Handle to slave device
2918 * This executes the SMBus "receive byte" protocol, returning negative errno
2919 * else the byte received from the device.
2921 s32 i2c_smbus_read_byte(const struct i2c_client *client)
2923 union i2c_smbus_data data;
2926 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2928 I2C_SMBUS_BYTE, &data);
2929 return (status < 0) ? status : data.byte;
2931 EXPORT_SYMBOL(i2c_smbus_read_byte);
2934 * i2c_smbus_write_byte - SMBus "send byte" protocol
2935 * @client: Handle to slave device
2936 * @value: Byte to be sent
2938 * This executes the SMBus "send byte" protocol, returning negative errno
2939 * else zero on success.
2941 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2943 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2944 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2946 EXPORT_SYMBOL(i2c_smbus_write_byte);
2949 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2950 * @client: Handle to slave device
2951 * @command: Byte interpreted by slave
2953 * This executes the SMBus "read byte" protocol, returning negative errno
2954 * else a data byte received from the device.
2956 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2958 union i2c_smbus_data data;
2961 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2962 I2C_SMBUS_READ, command,
2963 I2C_SMBUS_BYTE_DATA, &data);
2964 return (status < 0) ? status : data.byte;
2966 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2969 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2970 * @client: Handle to slave device
2971 * @command: Byte interpreted by slave
2972 * @value: Byte being written
2974 * This executes the SMBus "write byte" protocol, returning negative errno
2975 * else zero on success.
2977 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
2980 union i2c_smbus_data data;
2982 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2983 I2C_SMBUS_WRITE, command,
2984 I2C_SMBUS_BYTE_DATA, &data);
2986 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
2989 * i2c_smbus_read_word_data - SMBus "read word" protocol
2990 * @client: Handle to slave device
2991 * @command: Byte interpreted by slave
2993 * This executes the SMBus "read word" protocol, returning negative errno
2994 * else a 16-bit unsigned "word" received from the device.
2996 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
2998 union i2c_smbus_data data;
3001 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3002 I2C_SMBUS_READ, command,
3003 I2C_SMBUS_WORD_DATA, &data);
3004 return (status < 0) ? status : data.word;
3006 EXPORT_SYMBOL(i2c_smbus_read_word_data);
3009 * i2c_smbus_write_word_data - SMBus "write word" protocol
3010 * @client: Handle to slave device
3011 * @command: Byte interpreted by slave
3012 * @value: 16-bit "word" being written
3014 * This executes the SMBus "write word" protocol, returning negative errno
3015 * else zero on success.
3017 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
3020 union i2c_smbus_data data;
3022 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3023 I2C_SMBUS_WRITE, command,
3024 I2C_SMBUS_WORD_DATA, &data);
3026 EXPORT_SYMBOL(i2c_smbus_write_word_data);
3029 * i2c_smbus_read_block_data - SMBus "block read" protocol
3030 * @client: Handle to slave device
3031 * @command: Byte interpreted by slave
3032 * @values: Byte array into which data will be read; big enough to hold
3033 * the data returned by the slave. SMBus allows at most 32 bytes.
3035 * This executes the SMBus "block read" protocol, returning negative errno
3036 * else the number of data bytes in the slave's response.
3038 * Note that using this function requires that the client's adapter support
3039 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
3040 * support this; its emulation through I2C messaging relies on a specific
3041 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
3043 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
3046 union i2c_smbus_data data;
3049 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3050 I2C_SMBUS_READ, command,
3051 I2C_SMBUS_BLOCK_DATA, &data);
3055 memcpy(values, &data.block[1], data.block[0]);
3056 return data.block[0];
3058 EXPORT_SYMBOL(i2c_smbus_read_block_data);
3061 * i2c_smbus_write_block_data - SMBus "block write" protocol
3062 * @client: Handle to slave device
3063 * @command: Byte interpreted by slave
3064 * @length: Size of data block; SMBus allows at most 32 bytes
3065 * @values: Byte array which will be written.
3067 * This executes the SMBus "block write" protocol, returning negative errno
3068 * else zero on success.
3070 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
3071 u8 length, const u8 *values)
3073 union i2c_smbus_data data;
3075 if (length > I2C_SMBUS_BLOCK_MAX)
3076 length = I2C_SMBUS_BLOCK_MAX;
3077 data.block[0] = length;
3078 memcpy(&data.block[1], values, length);
3079 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3080 I2C_SMBUS_WRITE, command,
3081 I2C_SMBUS_BLOCK_DATA, &data);
3083 EXPORT_SYMBOL(i2c_smbus_write_block_data);
3085 /* Returns the number of read bytes */
3086 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
3087 u8 length, u8 *values)
3089 union i2c_smbus_data data;
3092 if (length > I2C_SMBUS_BLOCK_MAX)
3093 length = I2C_SMBUS_BLOCK_MAX;
3094 data.block[0] = length;
3095 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3096 I2C_SMBUS_READ, command,
3097 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3101 memcpy(values, &data.block[1], data.block[0]);
3102 return data.block[0];
3104 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
3106 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
3107 u8 length, const u8 *values)
3109 union i2c_smbus_data data;
3111 if (length > I2C_SMBUS_BLOCK_MAX)
3112 length = I2C_SMBUS_BLOCK_MAX;
3113 data.block[0] = length;
3114 memcpy(data.block + 1, values, length);
3115 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3116 I2C_SMBUS_WRITE, command,
3117 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3119 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
3121 /* Simulate a SMBus command using the i2c protocol
3122 No checking of parameters is done! */
3123 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
3124 unsigned short flags,
3125 char read_write, u8 command, int size,
3126 union i2c_smbus_data *data)
3128 /* So we need to generate a series of msgs. In the case of writing, we
3129 need to use only one message; when reading, we need two. We initialize
3130 most things with sane defaults, to keep the code below somewhat
3132 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
3133 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
3134 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
3138 struct i2c_msg msg[2] = {
3146 .flags = flags | I2C_M_RD,
3152 msgbuf0[0] = command;
3154 case I2C_SMBUS_QUICK:
3156 /* Special case: The read/write field is used as data */
3157 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
3161 case I2C_SMBUS_BYTE:
3162 if (read_write == I2C_SMBUS_READ) {
3163 /* Special case: only a read! */
3164 msg[0].flags = I2C_M_RD | flags;
3168 case I2C_SMBUS_BYTE_DATA:
3169 if (read_write == I2C_SMBUS_READ)
3173 msgbuf0[1] = data->byte;
3176 case I2C_SMBUS_WORD_DATA:
3177 if (read_write == I2C_SMBUS_READ)
3181 msgbuf0[1] = data->word & 0xff;
3182 msgbuf0[2] = data->word >> 8;
3185 case I2C_SMBUS_PROC_CALL:
3186 num = 2; /* Special case */
3187 read_write = I2C_SMBUS_READ;
3190 msgbuf0[1] = data->word & 0xff;
3191 msgbuf0[2] = data->word >> 8;
3193 case I2C_SMBUS_BLOCK_DATA:
3194 if (read_write == I2C_SMBUS_READ) {
3195 msg[1].flags |= I2C_M_RECV_LEN;
3196 msg[1].len = 1; /* block length will be added by
3197 the underlying bus driver */
3199 msg[0].len = data->block[0] + 2;
3200 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
3201 dev_err(&adapter->dev,
3202 "Invalid block write size %d\n",
3206 for (i = 1; i < msg[0].len; i++)
3207 msgbuf0[i] = data->block[i-1];
3210 case I2C_SMBUS_BLOCK_PROC_CALL:
3211 num = 2; /* Another special case */
3212 read_write = I2C_SMBUS_READ;
3213 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
3214 dev_err(&adapter->dev,
3215 "Invalid block write size %d\n",
3219 msg[0].len = data->block[0] + 2;
3220 for (i = 1; i < msg[0].len; i++)
3221 msgbuf0[i] = data->block[i-1];
3222 msg[1].flags |= I2C_M_RECV_LEN;
3223 msg[1].len = 1; /* block length will be added by
3224 the underlying bus driver */
3226 case I2C_SMBUS_I2C_BLOCK_DATA:
3227 if (read_write == I2C_SMBUS_READ) {
3228 msg[1].len = data->block[0];
3230 msg[0].len = data->block[0] + 1;
3231 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
3232 dev_err(&adapter->dev,
3233 "Invalid block write size %d\n",
3237 for (i = 1; i <= data->block[0]; i++)
3238 msgbuf0[i] = data->block[i];
3242 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
3246 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
3247 && size != I2C_SMBUS_I2C_BLOCK_DATA);
3249 /* Compute PEC if first message is a write */
3250 if (!(msg[0].flags & I2C_M_RD)) {
3251 if (num == 1) /* Write only */
3252 i2c_smbus_add_pec(&msg[0]);
3253 else /* Write followed by read */
3254 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
3256 /* Ask for PEC if last message is a read */
3257 if (msg[num-1].flags & I2C_M_RD)
3261 status = i2c_transfer(adapter, msg, num);
3265 /* Check PEC if last message is a read */
3266 if (i && (msg[num-1].flags & I2C_M_RD)) {
3267 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
3272 if (read_write == I2C_SMBUS_READ)
3274 case I2C_SMBUS_BYTE:
3275 data->byte = msgbuf0[0];
3277 case I2C_SMBUS_BYTE_DATA:
3278 data->byte = msgbuf1[0];
3280 case I2C_SMBUS_WORD_DATA:
3281 case I2C_SMBUS_PROC_CALL:
3282 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
3284 case I2C_SMBUS_I2C_BLOCK_DATA:
3285 for (i = 0; i < data->block[0]; i++)
3286 data->block[i+1] = msgbuf1[i];
3288 case I2C_SMBUS_BLOCK_DATA:
3289 case I2C_SMBUS_BLOCK_PROC_CALL:
3290 for (i = 0; i < msgbuf1[0] + 1; i++)
3291 data->block[i] = msgbuf1[i];
3298 * i2c_smbus_xfer - execute SMBus protocol operations
3299 * @adapter: Handle to I2C bus
3300 * @addr: Address of SMBus slave on that bus
3301 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
3302 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
3303 * @command: Byte interpreted by slave, for protocols which use such bytes
3304 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
3305 * @data: Data to be read or written
3307 * This executes an SMBus protocol operation, and returns a negative
3308 * errno code else zero on success.
3310 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
3311 char read_write, u8 command, int protocol,
3312 union i2c_smbus_data *data)
3314 unsigned long orig_jiffies;
3318 /* If enabled, the following two tracepoints are conditional on
3319 * read_write and protocol.
3321 trace_smbus_write(adapter, addr, flags, read_write,
3322 command, protocol, data);
3323 trace_smbus_read(adapter, addr, flags, read_write,
3326 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
3328 if (adapter->algo->smbus_xfer) {
3329 i2c_lock_bus(adapter, I2C_LOCK_SEGMENT);
3331 /* Retry automatically on arbitration loss */
3332 orig_jiffies = jiffies;
3333 for (res = 0, try = 0; try <= adapter->retries; try++) {
3334 res = adapter->algo->smbus_xfer(adapter, addr, flags,
3335 read_write, command,
3339 if (time_after(jiffies,
3340 orig_jiffies + adapter->timeout))
3343 i2c_unlock_bus(adapter, I2C_LOCK_SEGMENT);
3345 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
3348 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
3349 * implement native support for the SMBus operation.
3353 res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
3354 command, protocol, data);
3357 /* If enabled, the reply tracepoint is conditional on read_write. */
3358 trace_smbus_reply(adapter, addr, flags, read_write,
3359 command, protocol, data);
3360 trace_smbus_result(adapter, addr, flags, read_write,
3361 command, protocol, res);
3365 EXPORT_SYMBOL(i2c_smbus_xfer);
3368 * i2c_smbus_read_i2c_block_data_or_emulated - read block or emulate
3369 * @client: Handle to slave device
3370 * @command: Byte interpreted by slave
3371 * @length: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
3372 * @values: Byte array into which data will be read; big enough to hold
3373 * the data returned by the slave. SMBus allows at most
3374 * I2C_SMBUS_BLOCK_MAX bytes.
3376 * This executes the SMBus "block read" protocol if supported by the adapter.
3377 * If block read is not supported, it emulates it using either word or byte
3378 * read protocols depending on availability.
3380 * The addresses of the I2C slave device that are accessed with this function
3381 * must be mapped to a linear region, so that a block read will have the same
3382 * effect as a byte read. Before using this function you must double-check
3383 * if the I2C slave does support exchanging a block transfer with a byte
3386 s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client,
3387 u8 command, u8 length, u8 *values)
3392 if (length > I2C_SMBUS_BLOCK_MAX)
3393 length = I2C_SMBUS_BLOCK_MAX;
3395 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
3396 return i2c_smbus_read_i2c_block_data(client, command, length, values);
3398 if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA))
3401 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) {
3402 while ((i + 2) <= length) {
3403 status = i2c_smbus_read_word_data(client, command + i);
3406 values[i] = status & 0xff;
3407 values[i + 1] = status >> 8;
3412 while (i < length) {
3413 status = i2c_smbus_read_byte_data(client, command + i);
3422 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data_or_emulated);
3424 #if IS_ENABLED(CONFIG_I2C_SLAVE)
3425 int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
3429 if (!client || !slave_cb) {
3430 WARN(1, "insufficent data\n");
3434 if (!(client->flags & I2C_CLIENT_SLAVE))
3435 dev_warn(&client->dev, "%s: client slave flag not set. You might see address collisions\n",
3438 if (!(client->flags & I2C_CLIENT_TEN)) {
3439 /* Enforce stricter address checking */
3440 ret = i2c_check_7bit_addr_validity_strict(client->addr);
3442 dev_err(&client->dev, "%s: invalid address\n", __func__);
3447 if (!client->adapter->algo->reg_slave) {
3448 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3452 client->slave_cb = slave_cb;
3454 i2c_lock_adapter(client->adapter);
3455 ret = client->adapter->algo->reg_slave(client);
3456 i2c_unlock_adapter(client->adapter);
3459 client->slave_cb = NULL;
3460 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3465 EXPORT_SYMBOL_GPL(i2c_slave_register);
3467 int i2c_slave_unregister(struct i2c_client *client)
3471 if (!client->adapter->algo->unreg_slave) {
3472 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3476 i2c_lock_adapter(client->adapter);
3477 ret = client->adapter->algo->unreg_slave(client);
3478 i2c_unlock_adapter(client->adapter);
3481 client->slave_cb = NULL;
3483 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3487 EXPORT_SYMBOL_GPL(i2c_slave_unregister);
3490 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
3491 MODULE_DESCRIPTION("I2C-Bus main module");
3492 MODULE_LICENSE("GPL");