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 <linux/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 #define I2C_ADDR_7BITS_MAX 0x77
69 #define I2C_ADDR_7BITS_COUNT (I2C_ADDR_7BITS_MAX + 1)
71 /* core_lock protects i2c_adapter_idr, and guarantees
72 that device detection, deletion of detected devices, and attach_adapter
73 calls are serialized */
74 static DEFINE_MUTEX(core_lock);
75 static DEFINE_IDR(i2c_adapter_idr);
77 static struct device_type i2c_client_type;
78 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
80 static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
81 static bool is_registered;
83 int i2c_transfer_trace_reg(void)
85 static_key_slow_inc(&i2c_trace_msg);
89 void i2c_transfer_trace_unreg(void)
91 static_key_slow_dec(&i2c_trace_msg);
94 #if defined(CONFIG_ACPI)
95 struct i2c_acpi_handler_data {
96 struct acpi_connection_info info;
97 struct i2c_adapter *adapter;
110 struct i2c_acpi_lookup {
111 struct i2c_board_info *info;
112 acpi_handle adapter_handle;
113 acpi_handle device_handle;
114 acpi_handle search_handle;
121 static int i2c_acpi_fill_info(struct acpi_resource *ares, void *data)
123 struct i2c_acpi_lookup *lookup = data;
124 struct i2c_board_info *info = lookup->info;
125 struct acpi_resource_i2c_serialbus *sb;
128 if (info->addr || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
131 sb = &ares->data.i2c_serial_bus;
132 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C)
135 if (lookup->index != -1 && lookup->n++ != lookup->index)
138 status = acpi_get_handle(lookup->device_handle,
139 sb->resource_source.string_ptr,
140 &lookup->adapter_handle);
141 if (!ACPI_SUCCESS(status))
144 info->addr = sb->slave_address;
145 lookup->speed = sb->connection_speed;
146 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
147 info->flags |= I2C_CLIENT_TEN;
152 static int i2c_acpi_do_lookup(struct acpi_device *adev,
153 struct i2c_acpi_lookup *lookup)
155 struct i2c_board_info *info = lookup->info;
156 struct list_head resource_list;
159 if (acpi_bus_get_status(adev) || !adev->status.present ||
160 acpi_device_enumerated(adev))
163 memset(info, 0, sizeof(*info));
164 lookup->device_handle = acpi_device_handle(adev);
166 /* Look up for I2cSerialBus resource */
167 INIT_LIST_HEAD(&resource_list);
168 ret = acpi_dev_get_resources(adev, &resource_list,
169 i2c_acpi_fill_info, lookup);
170 acpi_dev_free_resource_list(&resource_list);
172 if (ret < 0 || !info->addr)
178 static int i2c_acpi_get_info(struct acpi_device *adev,
179 struct i2c_board_info *info,
180 struct i2c_adapter *adapter,
181 acpi_handle *adapter_handle)
183 struct list_head resource_list;
184 struct resource_entry *entry;
185 struct i2c_acpi_lookup lookup;
188 memset(&lookup, 0, sizeof(lookup));
192 ret = i2c_acpi_do_lookup(adev, &lookup);
197 /* The adapter must match the one in I2cSerialBus() connector */
198 if (ACPI_HANDLE(&adapter->dev) != lookup.adapter_handle)
201 struct acpi_device *adapter_adev;
203 /* The adapter must be present */
204 if (acpi_bus_get_device(lookup.adapter_handle, &adapter_adev))
206 if (acpi_bus_get_status(adapter_adev) ||
207 !adapter_adev->status.present)
211 info->fwnode = acpi_fwnode_handle(adev);
213 *adapter_handle = lookup.adapter_handle;
215 /* Then fill IRQ number if any */
216 INIT_LIST_HEAD(&resource_list);
217 ret = acpi_dev_get_resources(adev, &resource_list, NULL, NULL);
221 resource_list_for_each_entry(entry, &resource_list) {
222 if (resource_type(entry->res) == IORESOURCE_IRQ) {
223 info->irq = entry->res->start;
228 acpi_dev_free_resource_list(&resource_list);
230 acpi_set_modalias(adev, dev_name(&adev->dev), info->type,
236 static void i2c_acpi_register_device(struct i2c_adapter *adapter,
237 struct acpi_device *adev,
238 struct i2c_board_info *info)
240 adev->power.flags.ignore_parent = true;
241 acpi_device_set_enumerated(adev);
243 if (!i2c_new_device(adapter, info)) {
244 adev->power.flags.ignore_parent = false;
245 dev_err(&adapter->dev,
246 "failed to add I2C device %s from ACPI\n",
247 dev_name(&adev->dev));
251 static acpi_status i2c_acpi_add_device(acpi_handle handle, u32 level,
252 void *data, void **return_value)
254 struct i2c_adapter *adapter = data;
255 struct acpi_device *adev;
256 struct i2c_board_info info;
258 if (acpi_bus_get_device(handle, &adev))
261 if (i2c_acpi_get_info(adev, &info, adapter, NULL))
264 i2c_acpi_register_device(adapter, adev, &info);
269 #define I2C_ACPI_MAX_SCAN_DEPTH 32
272 * i2c_acpi_register_devices - enumerate I2C slave devices behind adapter
273 * @adap: pointer to adapter
275 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
276 * namespace. When a device is found it will be added to the Linux device
277 * model and bound to the corresponding ACPI handle.
279 static void i2c_acpi_register_devices(struct i2c_adapter *adap)
283 if (!has_acpi_companion(&adap->dev))
286 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
287 I2C_ACPI_MAX_SCAN_DEPTH,
288 i2c_acpi_add_device, NULL,
290 if (ACPI_FAILURE(status))
291 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
294 static acpi_status i2c_acpi_lookup_speed(acpi_handle handle, u32 level,
295 void *data, void **return_value)
297 struct i2c_acpi_lookup *lookup = data;
298 struct acpi_device *adev;
300 if (acpi_bus_get_device(handle, &adev))
303 if (i2c_acpi_do_lookup(adev, lookup))
306 if (lookup->search_handle != lookup->adapter_handle)
309 if (lookup->speed <= lookup->min_speed)
310 lookup->min_speed = lookup->speed;
316 * i2c_acpi_find_bus_speed - find I2C bus speed from ACPI
317 * @dev: The device owning the bus
319 * Find the I2C bus speed by walking the ACPI namespace for all I2C slaves
320 * devices connected to this bus and use the speed of slowest device.
322 * Returns the speed in Hz or zero
324 u32 i2c_acpi_find_bus_speed(struct device *dev)
326 struct i2c_acpi_lookup lookup;
327 struct i2c_board_info dummy;
330 if (!has_acpi_companion(dev))
333 memset(&lookup, 0, sizeof(lookup));
334 lookup.search_handle = ACPI_HANDLE(dev);
335 lookup.min_speed = UINT_MAX;
336 lookup.info = &dummy;
339 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
340 I2C_ACPI_MAX_SCAN_DEPTH,
341 i2c_acpi_lookup_speed, NULL,
344 if (ACPI_FAILURE(status)) {
345 dev_warn(dev, "unable to find I2C bus speed from ACPI\n");
349 return lookup.min_speed != UINT_MAX ? lookup.min_speed : 0;
351 EXPORT_SYMBOL_GPL(i2c_acpi_find_bus_speed);
353 static int i2c_acpi_match_adapter(struct device *dev, void *data)
355 struct i2c_adapter *adapter = i2c_verify_adapter(dev);
360 return ACPI_HANDLE(dev) == (acpi_handle)data;
363 static int i2c_acpi_match_device(struct device *dev, void *data)
365 return ACPI_COMPANION(dev) == data;
368 static struct i2c_adapter *i2c_acpi_find_adapter_by_handle(acpi_handle handle)
372 dev = bus_find_device(&i2c_bus_type, NULL, handle,
373 i2c_acpi_match_adapter);
374 return dev ? i2c_verify_adapter(dev) : NULL;
377 static struct i2c_client *i2c_acpi_find_client_by_adev(struct acpi_device *adev)
381 dev = bus_find_device(&i2c_bus_type, NULL, adev, i2c_acpi_match_device);
382 return dev ? i2c_verify_client(dev) : NULL;
385 static int i2c_acpi_notify(struct notifier_block *nb, unsigned long value,
388 struct acpi_device *adev = arg;
389 struct i2c_board_info info;
390 acpi_handle adapter_handle;
391 struct i2c_adapter *adapter;
392 struct i2c_client *client;
395 case ACPI_RECONFIG_DEVICE_ADD:
396 if (i2c_acpi_get_info(adev, &info, NULL, &adapter_handle))
399 adapter = i2c_acpi_find_adapter_by_handle(adapter_handle);
403 i2c_acpi_register_device(adapter, adev, &info);
405 case ACPI_RECONFIG_DEVICE_REMOVE:
406 if (!acpi_device_enumerated(adev))
409 client = i2c_acpi_find_client_by_adev(adev);
413 i2c_unregister_device(client);
414 put_device(&client->dev);
421 static struct notifier_block i2c_acpi_notifier = {
422 .notifier_call = i2c_acpi_notify,
426 * i2c_acpi_new_device - Create i2c-client for the Nth I2cSerialBus resource
427 * @dev: Device owning the ACPI resources to get the client from
428 * @index: Index of ACPI resource to get
429 * @info: describes the I2C device; note this is modified (addr gets set)
432 * By default the i2c subsys creates an i2c-client for the first I2cSerialBus
433 * resource of an acpi_device, but some acpi_devices have multiple I2cSerialBus
434 * resources, in that case this function can be used to create an i2c-client
435 * for other I2cSerialBus resources in the Current Resource Settings table.
437 * Also see i2c_new_device, which this function calls to create the i2c-client.
439 * Returns a pointer to the new i2c-client, or NULL if the adapter is not found.
441 struct i2c_client *i2c_acpi_new_device(struct device *dev, int index,
442 struct i2c_board_info *info)
444 struct i2c_acpi_lookup lookup;
445 struct i2c_adapter *adapter;
446 struct acpi_device *adev;
447 LIST_HEAD(resource_list);
450 adev = ACPI_COMPANION(dev);
454 memset(&lookup, 0, sizeof(lookup));
456 lookup.device_handle = acpi_device_handle(adev);
457 lookup.index = index;
459 ret = acpi_dev_get_resources(adev, &resource_list,
460 i2c_acpi_fill_info, &lookup);
461 acpi_dev_free_resource_list(&resource_list);
463 if (ret < 0 || !info->addr)
466 adapter = i2c_acpi_find_adapter_by_handle(lookup.adapter_handle);
470 return i2c_new_device(adapter, info);
472 EXPORT_SYMBOL_GPL(i2c_acpi_new_device);
473 #else /* CONFIG_ACPI */
474 static inline void i2c_acpi_register_devices(struct i2c_adapter *adap) { }
475 extern struct notifier_block i2c_acpi_notifier;
476 #endif /* CONFIG_ACPI */
478 #ifdef CONFIG_ACPI_I2C_OPREGION
479 static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
480 u8 cmd, u8 *data, u8 data_len)
483 struct i2c_msg msgs[2];
487 buffer = kzalloc(data_len, GFP_KERNEL);
491 msgs[0].addr = client->addr;
492 msgs[0].flags = client->flags;
496 msgs[1].addr = client->addr;
497 msgs[1].flags = client->flags | I2C_M_RD;
498 msgs[1].len = data_len;
499 msgs[1].buf = buffer;
501 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
503 dev_err(&client->adapter->dev, "i2c read failed\n");
505 memcpy(data, buffer, data_len);
511 static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
512 u8 cmd, u8 *data, u8 data_len)
515 struct i2c_msg msgs[1];
519 buffer = kzalloc(data_len + 1, GFP_KERNEL);
524 memcpy(buffer + 1, data, data_len);
526 msgs[0].addr = client->addr;
527 msgs[0].flags = client->flags;
528 msgs[0].len = data_len + 1;
529 msgs[0].buf = buffer;
531 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
533 dev_err(&client->adapter->dev, "i2c write failed\n");
540 i2c_acpi_space_handler(u32 function, acpi_physical_address command,
541 u32 bits, u64 *value64,
542 void *handler_context, void *region_context)
544 struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
545 struct i2c_acpi_handler_data *data = handler_context;
546 struct acpi_connection_info *info = &data->info;
547 struct acpi_resource_i2c_serialbus *sb;
548 struct i2c_adapter *adapter = data->adapter;
549 struct i2c_client *client;
550 struct acpi_resource *ares;
551 u32 accessor_type = function >> 16;
552 u8 action = function & ACPI_IO_MASK;
556 ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
557 if (ACPI_FAILURE(ret))
560 client = kzalloc(sizeof(*client), GFP_KERNEL);
566 if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
567 ret = AE_BAD_PARAMETER;
571 sb = &ares->data.i2c_serial_bus;
572 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
573 ret = AE_BAD_PARAMETER;
577 client->adapter = adapter;
578 client->addr = sb->slave_address;
580 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
581 client->flags |= I2C_CLIENT_TEN;
583 switch (accessor_type) {
584 case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
585 if (action == ACPI_READ) {
586 status = i2c_smbus_read_byte(client);
592 status = i2c_smbus_write_byte(client, gsb->bdata);
596 case ACPI_GSB_ACCESS_ATTRIB_BYTE:
597 if (action == ACPI_READ) {
598 status = i2c_smbus_read_byte_data(client, command);
604 status = i2c_smbus_write_byte_data(client, command,
609 case ACPI_GSB_ACCESS_ATTRIB_WORD:
610 if (action == ACPI_READ) {
611 status = i2c_smbus_read_word_data(client, command);
617 status = i2c_smbus_write_word_data(client, command,
622 case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
623 if (action == ACPI_READ) {
624 status = i2c_smbus_read_block_data(client, command,
631 status = i2c_smbus_write_block_data(client, command,
632 gsb->len, gsb->data);
636 case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
637 if (action == ACPI_READ) {
638 status = acpi_gsb_i2c_read_bytes(client, command,
639 gsb->data, info->access_length);
643 status = acpi_gsb_i2c_write_bytes(client, command,
644 gsb->data, info->access_length);
649 dev_warn(&adapter->dev, "protocol 0x%02x not supported for client 0x%02x\n",
650 accessor_type, client->addr);
651 ret = AE_BAD_PARAMETER;
655 gsb->status = status;
664 static int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
667 struct i2c_acpi_handler_data *data;
670 if (!adapter->dev.parent)
673 handle = ACPI_HANDLE(adapter->dev.parent);
678 data = kzalloc(sizeof(struct i2c_acpi_handler_data),
683 data->adapter = adapter;
684 status = acpi_bus_attach_private_data(handle, (void *)data);
685 if (ACPI_FAILURE(status)) {
690 status = acpi_install_address_space_handler(handle,
691 ACPI_ADR_SPACE_GSBUS,
692 &i2c_acpi_space_handler,
695 if (ACPI_FAILURE(status)) {
696 dev_err(&adapter->dev, "Error installing i2c space handler\n");
697 acpi_bus_detach_private_data(handle);
702 acpi_walk_dep_device_list(handle);
706 static void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
709 struct i2c_acpi_handler_data *data;
712 if (!adapter->dev.parent)
715 handle = ACPI_HANDLE(adapter->dev.parent);
720 acpi_remove_address_space_handler(handle,
721 ACPI_ADR_SPACE_GSBUS,
722 &i2c_acpi_space_handler);
724 status = acpi_bus_get_private_data(handle, (void **)&data);
725 if (ACPI_SUCCESS(status))
728 acpi_bus_detach_private_data(handle);
730 #else /* CONFIG_ACPI_I2C_OPREGION */
731 static inline void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
734 static inline int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
736 #endif /* CONFIG_ACPI_I2C_OPREGION */
738 /* ------------------------------------------------------------------------- */
740 const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
741 const struct i2c_client *client)
746 while (id->name[0]) {
747 if (strcmp(client->name, id->name) == 0)
753 EXPORT_SYMBOL_GPL(i2c_match_id);
755 static int i2c_device_match(struct device *dev, struct device_driver *drv)
757 struct i2c_client *client = i2c_verify_client(dev);
758 struct i2c_driver *driver;
761 /* Attempt an OF style match */
762 if (i2c_of_match_device(drv->of_match_table, client))
765 /* Then ACPI style match */
766 if (acpi_driver_match_device(dev, drv))
769 driver = to_i2c_driver(drv);
771 /* Finally an I2C match */
772 if (i2c_match_id(driver->id_table, client))
778 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
780 struct i2c_client *client = to_i2c_client(dev);
783 rc = acpi_device_uevent_modalias(dev, env);
787 return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
790 /* i2c bus recovery routines */
791 static int get_scl_gpio_value(struct i2c_adapter *adap)
793 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
796 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
798 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
801 static int get_sda_gpio_value(struct i2c_adapter *adap)
803 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
806 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
808 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
809 struct device *dev = &adap->dev;
812 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
813 GPIOF_OUT_INIT_HIGH, "i2c-scl");
815 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
820 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
821 /* work without SDA polling */
822 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
831 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
833 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
836 gpio_free(bri->sda_gpio);
838 gpio_free(bri->scl_gpio);
842 * We are generating clock pulses. ndelay() determines durating of clk pulses.
843 * We will generate clock with rate 100 KHz and so duration of both clock levels
844 * is: delay in ns = (10^6 / 100) / 2
846 #define RECOVERY_NDELAY 5000
847 #define RECOVERY_CLK_CNT 9
849 static int i2c_generic_recovery(struct i2c_adapter *adap)
851 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
852 int i = 0, val = 1, ret = 0;
854 if (bri->prepare_recovery)
855 bri->prepare_recovery(adap);
857 bri->set_scl(adap, val);
858 ndelay(RECOVERY_NDELAY);
861 * By this time SCL is high, as we need to give 9 falling-rising edges
863 while (i++ < RECOVERY_CLK_CNT * 2) {
865 /* Break if SDA is high */
866 if (bri->get_sda && bri->get_sda(adap))
868 /* SCL shouldn't be low here */
869 if (!bri->get_scl(adap)) {
871 "SCL is stuck low, exit recovery\n");
878 bri->set_scl(adap, val);
879 ndelay(RECOVERY_NDELAY);
882 if (bri->unprepare_recovery)
883 bri->unprepare_recovery(adap);
888 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
890 return i2c_generic_recovery(adap);
892 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
894 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
898 ret = i2c_get_gpios_for_recovery(adap);
902 ret = i2c_generic_recovery(adap);
903 i2c_put_gpios_for_recovery(adap);
907 EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
909 int i2c_recover_bus(struct i2c_adapter *adap)
911 if (!adap->bus_recovery_info)
914 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
915 return adap->bus_recovery_info->recover_bus(adap);
917 EXPORT_SYMBOL_GPL(i2c_recover_bus);
919 static void i2c_init_recovery(struct i2c_adapter *adap)
921 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
927 if (!bri->recover_bus) {
928 err_str = "no recover_bus() found";
932 /* Generic GPIO recovery */
933 if (bri->recover_bus == i2c_generic_gpio_recovery) {
934 if (!gpio_is_valid(bri->scl_gpio)) {
935 err_str = "invalid SCL gpio";
939 if (gpio_is_valid(bri->sda_gpio))
940 bri->get_sda = get_sda_gpio_value;
944 bri->get_scl = get_scl_gpio_value;
945 bri->set_scl = set_scl_gpio_value;
946 } else if (bri->recover_bus == i2c_generic_scl_recovery) {
947 /* Generic SCL recovery */
948 if (!bri->set_scl || !bri->get_scl) {
949 err_str = "no {get|set}_scl() found";
956 dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
957 adap->bus_recovery_info = NULL;
960 static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
962 struct i2c_adapter *adap = client->adapter;
965 if (!adap->host_notify_domain)
968 if (client->flags & I2C_CLIENT_TEN)
971 irq = irq_find_mapping(adap->host_notify_domain, client->addr);
973 irq = irq_create_mapping(adap->host_notify_domain,
976 return irq > 0 ? irq : -ENXIO;
979 static int i2c_device_probe(struct device *dev)
981 struct i2c_client *client = i2c_verify_client(dev);
982 struct i2c_driver *driver;
988 driver = to_i2c_driver(dev->driver);
990 if (!client->irq && !driver->disable_i2c_core_irq_mapping) {
993 if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
994 dev_dbg(dev, "Using Host Notify IRQ\n");
995 irq = i2c_smbus_host_notify_to_irq(client);
996 } else if (dev->of_node) {
997 irq = of_irq_get_byname(dev->of_node, "irq");
998 if (irq == -EINVAL || irq == -ENODATA)
999 irq = of_irq_get(dev->of_node, 0);
1000 } else if (ACPI_COMPANION(dev)) {
1001 irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
1003 if (irq == -EPROBE_DEFER)
1013 * An I2C ID table is not mandatory, if and only if, a suitable Device
1014 * Tree match table entry is supplied for the probing device.
1016 if (!driver->id_table &&
1017 !i2c_of_match_device(dev->driver->of_match_table, client))
1020 if (client->flags & I2C_CLIENT_WAKE) {
1021 int wakeirq = -ENOENT;
1024 wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
1025 if (wakeirq == -EPROBE_DEFER)
1029 device_init_wakeup(&client->dev, true);
1031 if (wakeirq > 0 && wakeirq != client->irq)
1032 status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
1033 else if (client->irq > 0)
1034 status = dev_pm_set_wake_irq(dev, client->irq);
1039 dev_warn(&client->dev, "failed to set up wakeup irq\n");
1042 dev_dbg(dev, "probe\n");
1044 status = of_clk_set_defaults(dev->of_node, false);
1046 goto err_clear_wakeup_irq;
1048 status = dev_pm_domain_attach(&client->dev, true);
1049 if (status == -EPROBE_DEFER)
1050 goto err_clear_wakeup_irq;
1053 * When there are no more users of probe(),
1054 * rename probe_new to probe.
1056 if (driver->probe_new)
1057 status = driver->probe_new(client);
1058 else if (driver->probe)
1059 status = driver->probe(client,
1060 i2c_match_id(driver->id_table, client));
1065 goto err_detach_pm_domain;
1069 err_detach_pm_domain:
1070 dev_pm_domain_detach(&client->dev, true);
1071 err_clear_wakeup_irq:
1072 dev_pm_clear_wake_irq(&client->dev);
1073 device_init_wakeup(&client->dev, false);
1077 static int i2c_device_remove(struct device *dev)
1079 struct i2c_client *client = i2c_verify_client(dev);
1080 struct i2c_driver *driver;
1083 if (!client || !dev->driver)
1086 driver = to_i2c_driver(dev->driver);
1087 if (driver->remove) {
1088 dev_dbg(dev, "remove\n");
1089 status = driver->remove(client);
1092 dev_pm_domain_detach(&client->dev, true);
1094 dev_pm_clear_wake_irq(&client->dev);
1095 device_init_wakeup(&client->dev, false);
1100 static void i2c_device_shutdown(struct device *dev)
1102 struct i2c_client *client = i2c_verify_client(dev);
1103 struct i2c_driver *driver;
1105 if (!client || !dev->driver)
1107 driver = to_i2c_driver(dev->driver);
1108 if (driver->shutdown)
1109 driver->shutdown(client);
1112 static void i2c_client_dev_release(struct device *dev)
1114 kfree(to_i2c_client(dev));
1118 show_name(struct device *dev, struct device_attribute *attr, char *buf)
1120 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
1121 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
1123 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
1126 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
1128 struct i2c_client *client = to_i2c_client(dev);
1131 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
1135 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
1137 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
1139 static struct attribute *i2c_dev_attrs[] = {
1140 &dev_attr_name.attr,
1141 /* modalias helps coldplug: modprobe $(cat .../modalias) */
1142 &dev_attr_modalias.attr,
1145 ATTRIBUTE_GROUPS(i2c_dev);
1147 struct bus_type i2c_bus_type = {
1149 .match = i2c_device_match,
1150 .probe = i2c_device_probe,
1151 .remove = i2c_device_remove,
1152 .shutdown = i2c_device_shutdown,
1154 EXPORT_SYMBOL_GPL(i2c_bus_type);
1156 static struct device_type i2c_client_type = {
1157 .groups = i2c_dev_groups,
1158 .uevent = i2c_device_uevent,
1159 .release = i2c_client_dev_release,
1164 * i2c_verify_client - return parameter as i2c_client, or NULL
1165 * @dev: device, probably from some driver model iterator
1167 * When traversing the driver model tree, perhaps using driver model
1168 * iterators like @device_for_each_child(), you can't assume very much
1169 * about the nodes you find. Use this function to avoid oopses caused
1170 * by wrongly treating some non-I2C device as an i2c_client.
1172 struct i2c_client *i2c_verify_client(struct device *dev)
1174 return (dev->type == &i2c_client_type)
1175 ? to_i2c_client(dev)
1178 EXPORT_SYMBOL(i2c_verify_client);
1181 /* Return a unique address which takes the flags of the client into account */
1182 static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
1184 unsigned short addr = client->addr;
1186 /* For some client flags, add an arbitrary offset to avoid collisions */
1187 if (client->flags & I2C_CLIENT_TEN)
1188 addr |= I2C_ADDR_OFFSET_TEN_BIT;
1190 if (client->flags & I2C_CLIENT_SLAVE)
1191 addr |= I2C_ADDR_OFFSET_SLAVE;
1196 /* This is a permissive address validity check, I2C address map constraints
1197 * are purposely not enforced, except for the general call address. */
1198 static int i2c_check_addr_validity(unsigned addr, unsigned short flags)
1200 if (flags & I2C_CLIENT_TEN) {
1201 /* 10-bit address, all values are valid */
1205 /* 7-bit address, reject the general call address */
1206 if (addr == 0x00 || addr > 0x7f)
1212 /* And this is a strict address validity check, used when probing. If a
1213 * device uses a reserved address, then it shouldn't be probed. 7-bit
1214 * addressing is assumed, 10-bit address devices are rare and should be
1215 * explicitly enumerated. */
1216 static int i2c_check_7bit_addr_validity_strict(unsigned short addr)
1219 * Reserved addresses per I2C specification:
1220 * 0x00 General call address / START byte
1222 * 0x02 Reserved for different bus format
1223 * 0x03 Reserved for future purposes
1224 * 0x04-0x07 Hs-mode master code
1225 * 0x78-0x7b 10-bit slave addressing
1226 * 0x7c-0x7f Reserved for future purposes
1228 if (addr < 0x08 || addr > 0x77)
1233 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
1235 struct i2c_client *client = i2c_verify_client(dev);
1236 int addr = *(int *)addrp;
1238 if (client && i2c_encode_flags_to_addr(client) == addr)
1243 /* walk up mux tree */
1244 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
1246 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1249 result = device_for_each_child(&adapter->dev, &addr,
1250 __i2c_check_addr_busy);
1252 if (!result && parent)
1253 result = i2c_check_mux_parents(parent, addr);
1258 /* recurse down mux tree */
1259 static int i2c_check_mux_children(struct device *dev, void *addrp)
1263 if (dev->type == &i2c_adapter_type)
1264 result = device_for_each_child(dev, addrp,
1265 i2c_check_mux_children);
1267 result = __i2c_check_addr_busy(dev, addrp);
1272 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
1274 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1278 result = i2c_check_mux_parents(parent, addr);
1281 result = device_for_each_child(&adapter->dev, &addr,
1282 i2c_check_mux_children);
1288 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
1289 * @adapter: Target I2C bus segment
1290 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
1291 * locks only this branch in the adapter tree
1293 static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
1296 rt_mutex_lock(&adapter->bus_lock);
1300 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
1301 * @adapter: Target I2C bus segment
1302 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
1303 * trylocks only this branch in the adapter tree
1305 static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
1308 return rt_mutex_trylock(&adapter->bus_lock);
1312 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
1313 * @adapter: Target I2C bus segment
1314 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
1315 * unlocks only this branch in the adapter tree
1317 static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
1320 rt_mutex_unlock(&adapter->bus_lock);
1323 static void i2c_dev_set_name(struct i2c_adapter *adap,
1324 struct i2c_client *client)
1326 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
1329 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
1333 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
1334 i2c_encode_flags_to_addr(client));
1338 * i2c_new_device - instantiate an i2c device
1339 * @adap: the adapter managing the device
1340 * @info: describes one I2C device; bus_num is ignored
1341 * Context: can sleep
1343 * Create an i2c device. Binding is handled through driver model
1344 * probe()/remove() methods. A driver may be bound to this device when we
1345 * return from this function, or any later moment (e.g. maybe hotplugging will
1346 * load the driver module). This call is not appropriate for use by mainboard
1347 * initialization logic, which usually runs during an arch_initcall() long
1348 * before any i2c_adapter could exist.
1350 * This returns the new i2c client, which may be saved for later use with
1351 * i2c_unregister_device(); or NULL to indicate an error.
1354 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1356 struct i2c_client *client;
1359 client = kzalloc(sizeof *client, GFP_KERNEL);
1363 client->adapter = adap;
1365 client->dev.platform_data = info->platform_data;
1368 client->dev.archdata = *info->archdata;
1370 client->flags = info->flags;
1371 client->addr = info->addr;
1372 client->irq = info->irq;
1374 strlcpy(client->name, info->type, sizeof(client->name));
1376 status = i2c_check_addr_validity(client->addr, client->flags);
1378 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1379 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1380 goto out_err_silent;
1383 /* Check for address business */
1384 status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
1388 client->dev.parent = &client->adapter->dev;
1389 client->dev.bus = &i2c_bus_type;
1390 client->dev.type = &i2c_client_type;
1391 client->dev.of_node = info->of_node;
1392 client->dev.fwnode = info->fwnode;
1394 i2c_dev_set_name(adap, client);
1396 if (info->properties) {
1397 status = device_add_properties(&client->dev, info->properties);
1400 "Failed to add properties to client %s: %d\n",
1401 client->name, status);
1406 status = device_register(&client->dev);
1408 goto out_free_props;
1410 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1411 client->name, dev_name(&client->dev));
1416 if (info->properties)
1417 device_remove_properties(&client->dev);
1420 "Failed to register i2c client %s at 0x%02x (%d)\n",
1421 client->name, client->addr, status);
1426 EXPORT_SYMBOL_GPL(i2c_new_device);
1430 * i2c_unregister_device - reverse effect of i2c_new_device()
1431 * @client: value returned from i2c_new_device()
1432 * Context: can sleep
1434 void i2c_unregister_device(struct i2c_client *client)
1436 if (client->dev.of_node)
1437 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
1438 if (ACPI_COMPANION(&client->dev))
1439 acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
1440 device_unregister(&client->dev);
1442 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1445 static const struct i2c_device_id dummy_id[] = {
1450 static int dummy_probe(struct i2c_client *client,
1451 const struct i2c_device_id *id)
1456 static int dummy_remove(struct i2c_client *client)
1461 static struct i2c_driver dummy_driver = {
1462 .driver.name = "dummy",
1463 .probe = dummy_probe,
1464 .remove = dummy_remove,
1465 .id_table = dummy_id,
1469 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1470 * @adapter: the adapter managing the device
1471 * @address: seven bit address to be used
1472 * Context: can sleep
1474 * This returns an I2C client bound to the "dummy" driver, intended for use
1475 * with devices that consume multiple addresses. Examples of such chips
1476 * include various EEPROMS (like 24c04 and 24c08 models).
1478 * These dummy devices have two main uses. First, most I2C and SMBus calls
1479 * except i2c_transfer() need a client handle; the dummy will be that handle.
1480 * And second, this prevents the specified address from being bound to a
1483 * This returns the new i2c client, which should be saved for later use with
1484 * i2c_unregister_device(); or NULL to indicate an error.
1486 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1488 struct i2c_board_info info = {
1489 I2C_BOARD_INFO("dummy", address),
1492 return i2c_new_device(adapter, &info);
1494 EXPORT_SYMBOL_GPL(i2c_new_dummy);
1497 * i2c_new_secondary_device - Helper to get the instantiated secondary address
1498 * and create the associated device
1499 * @client: Handle to the primary client
1500 * @name: Handle to specify which secondary address to get
1501 * @default_addr: Used as a fallback if no secondary address was specified
1502 * Context: can sleep
1504 * I2C clients can be composed of multiple I2C slaves bound together in a single
1505 * component. The I2C client driver then binds to the master I2C slave and needs
1506 * to create I2C dummy clients to communicate with all the other slaves.
1508 * This function creates and returns an I2C dummy client whose I2C address is
1509 * retrieved from the platform firmware based on the given slave name. If no
1510 * address is specified by the firmware default_addr is used.
1512 * On DT-based platforms the address is retrieved from the "reg" property entry
1513 * cell whose "reg-names" value matches the slave name.
1515 * This returns the new i2c client, which should be saved for later use with
1516 * i2c_unregister_device(); or NULL to indicate an error.
1518 struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
1522 struct device_node *np = client->dev.of_node;
1523 u32 addr = default_addr;
1527 i = of_property_match_string(np, "reg-names", name);
1529 of_property_read_u32_index(np, "reg", i, &addr);
1532 dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1533 return i2c_new_dummy(client->adapter, addr);
1535 EXPORT_SYMBOL_GPL(i2c_new_secondary_device);
1537 /* ------------------------------------------------------------------------- */
1539 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1541 static void i2c_adapter_dev_release(struct device *dev)
1543 struct i2c_adapter *adap = to_i2c_adapter(dev);
1544 complete(&adap->dev_released);
1547 unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1549 unsigned int depth = 0;
1551 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1554 WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
1555 "adapter depth exceeds lockdep subclass limit\n");
1559 EXPORT_SYMBOL_GPL(i2c_adapter_depth);
1562 * Let users instantiate I2C devices through sysfs. This can be used when
1563 * platform initialization code doesn't contain the proper data for
1564 * whatever reason. Also useful for drivers that do device detection and
1565 * detection fails, either because the device uses an unexpected address,
1566 * or this is a compatible device with different ID register values.
1568 * Parameter checking may look overzealous, but we really don't want
1569 * the user to provide incorrect parameters.
1572 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1573 const char *buf, size_t count)
1575 struct i2c_adapter *adap = to_i2c_adapter(dev);
1576 struct i2c_board_info info;
1577 struct i2c_client *client;
1581 memset(&info, 0, sizeof(struct i2c_board_info));
1583 blank = strchr(buf, ' ');
1585 dev_err(dev, "%s: Missing parameters\n", "new_device");
1588 if (blank - buf > I2C_NAME_SIZE - 1) {
1589 dev_err(dev, "%s: Invalid device name\n", "new_device");
1592 memcpy(info.type, buf, blank - buf);
1594 /* Parse remaining parameters, reject extra parameters */
1595 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1597 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1600 if (res > 1 && end != '\n') {
1601 dev_err(dev, "%s: Extra parameters\n", "new_device");
1605 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1606 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1607 info.flags |= I2C_CLIENT_TEN;
1610 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1611 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1612 info.flags |= I2C_CLIENT_SLAVE;
1615 client = i2c_new_device(adap, &info);
1619 /* Keep track of the added device */
1620 mutex_lock(&adap->userspace_clients_lock);
1621 list_add_tail(&client->detected, &adap->userspace_clients);
1622 mutex_unlock(&adap->userspace_clients_lock);
1623 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1624 info.type, info.addr);
1628 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1631 * And of course let the users delete the devices they instantiated, if
1632 * they got it wrong. This interface can only be used to delete devices
1633 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1634 * don't delete devices to which some kernel code still has references.
1636 * Parameter checking may look overzealous, but we really don't want
1637 * the user to delete the wrong device.
1640 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1641 const char *buf, size_t count)
1643 struct i2c_adapter *adap = to_i2c_adapter(dev);
1644 struct i2c_client *client, *next;
1645 unsigned short addr;
1649 /* Parse parameters, reject extra parameters */
1650 res = sscanf(buf, "%hi%c", &addr, &end);
1652 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1655 if (res > 1 && end != '\n') {
1656 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1660 /* Make sure the device was added through sysfs */
1662 mutex_lock_nested(&adap->userspace_clients_lock,
1663 i2c_adapter_depth(adap));
1664 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1666 if (i2c_encode_flags_to_addr(client) == addr) {
1667 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1668 "delete_device", client->name, client->addr);
1670 list_del(&client->detected);
1671 i2c_unregister_device(client);
1676 mutex_unlock(&adap->userspace_clients_lock);
1679 dev_err(dev, "%s: Can't find device in list\n",
1683 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1684 i2c_sysfs_delete_device);
1686 static struct attribute *i2c_adapter_attrs[] = {
1687 &dev_attr_name.attr,
1688 &dev_attr_new_device.attr,
1689 &dev_attr_delete_device.attr,
1692 ATTRIBUTE_GROUPS(i2c_adapter);
1694 struct device_type i2c_adapter_type = {
1695 .groups = i2c_adapter_groups,
1696 .release = i2c_adapter_dev_release,
1698 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1701 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1702 * @dev: device, probably from some driver model iterator
1704 * When traversing the driver model tree, perhaps using driver model
1705 * iterators like @device_for_each_child(), you can't assume very much
1706 * about the nodes you find. Use this function to avoid oopses caused
1707 * by wrongly treating some non-I2C device as an i2c_adapter.
1709 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1711 return (dev->type == &i2c_adapter_type)
1712 ? to_i2c_adapter(dev)
1715 EXPORT_SYMBOL(i2c_verify_adapter);
1717 #ifdef CONFIG_I2C_COMPAT
1718 static struct class_compat *i2c_adapter_compat_class;
1721 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1723 struct i2c_devinfo *devinfo;
1725 down_read(&__i2c_board_lock);
1726 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1727 if (devinfo->busnum == adapter->nr
1728 && !i2c_new_device(adapter,
1729 &devinfo->board_info))
1730 dev_err(&adapter->dev,
1731 "Can't create device at 0x%02x\n",
1732 devinfo->board_info.addr);
1734 up_read(&__i2c_board_lock);
1737 /* OF support code */
1739 #if IS_ENABLED(CONFIG_OF)
1740 static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1741 struct device_node *node)
1743 struct i2c_client *result;
1744 struct i2c_board_info info = {};
1745 struct dev_archdata dev_ad = {};
1746 const __be32 *addr_be;
1750 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1752 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1753 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1755 return ERR_PTR(-EINVAL);
1758 addr_be = of_get_property(node, "reg", &len);
1759 if (!addr_be || (len < sizeof(*addr_be))) {
1760 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1762 return ERR_PTR(-EINVAL);
1765 addr = be32_to_cpup(addr_be);
1766 if (addr & I2C_TEN_BIT_ADDRESS) {
1767 addr &= ~I2C_TEN_BIT_ADDRESS;
1768 info.flags |= I2C_CLIENT_TEN;
1771 if (addr & I2C_OWN_SLAVE_ADDRESS) {
1772 addr &= ~I2C_OWN_SLAVE_ADDRESS;
1773 info.flags |= I2C_CLIENT_SLAVE;
1776 if (i2c_check_addr_validity(addr, info.flags)) {
1777 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1778 addr, node->full_name);
1779 return ERR_PTR(-EINVAL);
1783 info.of_node = of_node_get(node);
1784 info.archdata = &dev_ad;
1786 if (of_property_read_bool(node, "host-notify"))
1787 info.flags |= I2C_CLIENT_HOST_NOTIFY;
1789 if (of_get_property(node, "wakeup-source", NULL))
1790 info.flags |= I2C_CLIENT_WAKE;
1792 result = i2c_new_device(adap, &info);
1793 if (result == NULL) {
1794 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1797 return ERR_PTR(-EINVAL);
1802 static void of_i2c_register_devices(struct i2c_adapter *adap)
1804 struct device_node *bus, *node;
1805 struct i2c_client *client;
1807 /* Only register child devices if the adapter has a node pointer set */
1808 if (!adap->dev.of_node)
1811 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1813 bus = of_get_child_by_name(adap->dev.of_node, "i2c-bus");
1815 bus = of_node_get(adap->dev.of_node);
1817 for_each_available_child_of_node(bus, node) {
1818 if (of_node_test_and_set_flag(node, OF_POPULATED))
1821 client = of_i2c_register_device(adap, node);
1822 if (IS_ERR(client)) {
1823 dev_warn(&adap->dev,
1824 "Failed to create I2C device for %s\n",
1826 of_node_clear_flag(node, OF_POPULATED);
1833 static int of_dev_node_match(struct device *dev, void *data)
1835 return dev->of_node == data;
1838 /* must call put_device() when done with returned i2c_client device */
1839 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1842 struct i2c_client *client;
1844 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1848 client = i2c_verify_client(dev);
1854 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1856 /* must call put_device() when done with returned i2c_adapter device */
1857 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1860 struct i2c_adapter *adapter;
1862 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1866 adapter = i2c_verify_adapter(dev);
1872 EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1874 /* must call i2c_put_adapter() when done with returned i2c_adapter device */
1875 struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1877 struct i2c_adapter *adapter;
1879 adapter = of_find_i2c_adapter_by_node(node);
1883 if (!try_module_get(adapter->owner)) {
1884 put_device(&adapter->dev);
1890 EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1892 static const struct of_device_id*
1893 i2c_of_match_device_sysfs(const struct of_device_id *matches,
1894 struct i2c_client *client)
1898 for (; matches->compatible[0]; matches++) {
1900 * Adding devices through the i2c sysfs interface provides us
1901 * a string to match which may be compatible with the device
1902 * tree compatible strings, however with no actual of_node the
1903 * of_match_device() will not match
1905 if (sysfs_streq(client->name, matches->compatible))
1908 name = strchr(matches->compatible, ',');
1910 name = matches->compatible;
1914 if (sysfs_streq(client->name, name))
1921 const struct of_device_id
1922 *i2c_of_match_device(const struct of_device_id *matches,
1923 struct i2c_client *client)
1925 const struct of_device_id *match;
1927 if (!(client && matches))
1930 match = of_match_device(matches, &client->dev);
1934 return i2c_of_match_device_sysfs(matches, client);
1936 EXPORT_SYMBOL_GPL(i2c_of_match_device);
1938 static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1939 #endif /* CONFIG_OF */
1941 static int i2c_do_add_adapter(struct i2c_driver *driver,
1942 struct i2c_adapter *adap)
1944 /* Detect supported devices on that bus, and instantiate them */
1945 i2c_detect(adap, driver);
1947 /* Let legacy drivers scan this bus for matching devices */
1948 if (driver->attach_adapter) {
1949 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1950 driver->driver.name);
1951 dev_warn(&adap->dev,
1952 "Please use another way to instantiate your i2c_client\n");
1953 /* We ignore the return code; if it fails, too bad */
1954 driver->attach_adapter(adap);
1959 static int __process_new_adapter(struct device_driver *d, void *data)
1961 return i2c_do_add_adapter(to_i2c_driver(d), data);
1964 static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1965 .lock_bus = i2c_adapter_lock_bus,
1966 .trylock_bus = i2c_adapter_trylock_bus,
1967 .unlock_bus = i2c_adapter_unlock_bus,
1970 static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
1972 struct irq_domain *domain = adap->host_notify_domain;
1973 irq_hw_number_t hwirq;
1978 for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
1979 irq_dispose_mapping(irq_find_mapping(domain, hwirq));
1981 irq_domain_remove(domain);
1982 adap->host_notify_domain = NULL;
1985 static int i2c_host_notify_irq_map(struct irq_domain *h,
1987 irq_hw_number_t hw_irq_num)
1989 irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
1994 static const struct irq_domain_ops i2c_host_notify_irq_ops = {
1995 .map = i2c_host_notify_irq_map,
1998 static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
2000 struct irq_domain *domain;
2002 if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
2005 domain = irq_domain_create_linear(adap->dev.fwnode,
2006 I2C_ADDR_7BITS_COUNT,
2007 &i2c_host_notify_irq_ops, adap);
2011 adap->host_notify_domain = domain;
2017 * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
2019 * @adap: the adapter
2020 * @addr: the I2C address of the notifying device
2021 * Context: can't sleep
2023 * Helper function to be called from an I2C bus driver's interrupt
2024 * handler. It will schedule the Host Notify IRQ.
2026 int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
2033 irq = irq_find_mapping(adap->host_notify_domain, addr);
2037 generic_handle_irq(irq);
2041 EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
2043 static int i2c_register_adapter(struct i2c_adapter *adap)
2047 /* Can't register until after driver model init */
2048 if (WARN_ON(!is_registered)) {
2054 if (WARN(!adap->name[0], "i2c adapter has no name"))
2058 pr_err("adapter '%s': no algo supplied!\n", adap->name);
2062 if (!adap->lock_ops)
2063 adap->lock_ops = &i2c_adapter_lock_ops;
2065 rt_mutex_init(&adap->bus_lock);
2066 rt_mutex_init(&adap->mux_lock);
2067 mutex_init(&adap->userspace_clients_lock);
2068 INIT_LIST_HEAD(&adap->userspace_clients);
2070 /* Set default timeout to 1 second if not already set */
2071 if (adap->timeout == 0)
2074 /* register soft irqs for Host Notify */
2075 res = i2c_setup_host_notify_irq_domain(adap);
2077 pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
2082 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
2083 adap->dev.bus = &i2c_bus_type;
2084 adap->dev.type = &i2c_adapter_type;
2085 res = device_register(&adap->dev);
2087 pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
2091 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
2093 pm_runtime_no_callbacks(&adap->dev);
2094 pm_suspend_ignore_children(&adap->dev, true);
2095 pm_runtime_enable(&adap->dev);
2097 #ifdef CONFIG_I2C_COMPAT
2098 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
2101 dev_warn(&adap->dev,
2102 "Failed to create compatibility class link\n");
2105 i2c_init_recovery(adap);
2107 /* create pre-declared device nodes */
2108 of_i2c_register_devices(adap);
2109 i2c_acpi_register_devices(adap);
2110 i2c_acpi_install_space_handler(adap);
2112 if (adap->nr < __i2c_first_dynamic_bus_num)
2113 i2c_scan_static_board_info(adap);
2115 /* Notify drivers */
2116 mutex_lock(&core_lock);
2117 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
2118 mutex_unlock(&core_lock);
2123 mutex_lock(&core_lock);
2124 idr_remove(&i2c_adapter_idr, adap->nr);
2125 mutex_unlock(&core_lock);
2130 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
2131 * @adap: the adapter to register (with adap->nr initialized)
2132 * Context: can sleep
2134 * See i2c_add_numbered_adapter() for details.
2136 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
2140 mutex_lock(&core_lock);
2141 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
2142 mutex_unlock(&core_lock);
2143 if (WARN(id < 0, "couldn't get idr"))
2144 return id == -ENOSPC ? -EBUSY : id;
2146 return i2c_register_adapter(adap);
2150 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
2151 * @adapter: the adapter to add
2152 * Context: can sleep
2154 * This routine is used to declare an I2C adapter when its bus number
2155 * doesn't matter or when its bus number is specified by an dt alias.
2156 * Examples of bases when the bus number doesn't matter: I2C adapters
2157 * dynamically added by USB links or PCI plugin cards.
2159 * When this returns zero, a new bus number was allocated and stored
2160 * in adap->nr, and the specified adapter became available for clients.
2161 * Otherwise, a negative errno value is returned.
2163 int i2c_add_adapter(struct i2c_adapter *adapter)
2165 struct device *dev = &adapter->dev;
2169 id = of_alias_get_id(dev->of_node, "i2c");
2172 return __i2c_add_numbered_adapter(adapter);
2176 mutex_lock(&core_lock);
2177 id = idr_alloc(&i2c_adapter_idr, adapter,
2178 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
2179 mutex_unlock(&core_lock);
2180 if (WARN(id < 0, "couldn't get idr"))
2185 return i2c_register_adapter(adapter);
2187 EXPORT_SYMBOL(i2c_add_adapter);
2190 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
2191 * @adap: the adapter to register (with adap->nr initialized)
2192 * Context: can sleep
2194 * This routine is used to declare an I2C adapter when its bus number
2195 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
2196 * or otherwise built in to the system's mainboard, and where i2c_board_info
2197 * is used to properly configure I2C devices.
2199 * If the requested bus number is set to -1, then this function will behave
2200 * identically to i2c_add_adapter, and will dynamically assign a bus number.
2202 * If no devices have pre-been declared for this bus, then be sure to
2203 * register the adapter before any dynamically allocated ones. Otherwise
2204 * the required bus ID may not be available.
2206 * When this returns zero, the specified adapter became available for
2207 * clients using the bus number provided in adap->nr. Also, the table
2208 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
2209 * and the appropriate driver model device nodes are created. Otherwise, a
2210 * negative errno value is returned.
2212 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
2214 if (adap->nr == -1) /* -1 means dynamically assign bus id */
2215 return i2c_add_adapter(adap);
2217 return __i2c_add_numbered_adapter(adap);
2219 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
2221 static void i2c_do_del_adapter(struct i2c_driver *driver,
2222 struct i2c_adapter *adapter)
2224 struct i2c_client *client, *_n;
2226 /* Remove the devices we created ourselves as the result of hardware
2227 * probing (using a driver's detect method) */
2228 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
2229 if (client->adapter == adapter) {
2230 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
2231 client->name, client->addr);
2232 list_del(&client->detected);
2233 i2c_unregister_device(client);
2238 static int __unregister_client(struct device *dev, void *dummy)
2240 struct i2c_client *client = i2c_verify_client(dev);
2241 if (client && strcmp(client->name, "dummy"))
2242 i2c_unregister_device(client);
2246 static int __unregister_dummy(struct device *dev, void *dummy)
2248 struct i2c_client *client = i2c_verify_client(dev);
2250 i2c_unregister_device(client);
2254 static int __process_removed_adapter(struct device_driver *d, void *data)
2256 i2c_do_del_adapter(to_i2c_driver(d), data);
2261 * i2c_del_adapter - unregister I2C adapter
2262 * @adap: the adapter being unregistered
2263 * Context: can sleep
2265 * This unregisters an I2C adapter which was previously registered
2266 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
2268 void i2c_del_adapter(struct i2c_adapter *adap)
2270 struct i2c_adapter *found;
2271 struct i2c_client *client, *next;
2273 /* First make sure that this adapter was ever added */
2274 mutex_lock(&core_lock);
2275 found = idr_find(&i2c_adapter_idr, adap->nr);
2276 mutex_unlock(&core_lock);
2277 if (found != adap) {
2278 pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
2282 i2c_acpi_remove_space_handler(adap);
2283 /* Tell drivers about this removal */
2284 mutex_lock(&core_lock);
2285 bus_for_each_drv(&i2c_bus_type, NULL, adap,
2286 __process_removed_adapter);
2287 mutex_unlock(&core_lock);
2289 /* Remove devices instantiated from sysfs */
2290 mutex_lock_nested(&adap->userspace_clients_lock,
2291 i2c_adapter_depth(adap));
2292 list_for_each_entry_safe(client, next, &adap->userspace_clients,
2294 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
2296 list_del(&client->detected);
2297 i2c_unregister_device(client);
2299 mutex_unlock(&adap->userspace_clients_lock);
2301 /* Detach any active clients. This can't fail, thus we do not
2302 * check the returned value. This is a two-pass process, because
2303 * we can't remove the dummy devices during the first pass: they
2304 * could have been instantiated by real devices wishing to clean
2305 * them up properly, so we give them a chance to do that first. */
2306 device_for_each_child(&adap->dev, NULL, __unregister_client);
2307 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
2309 #ifdef CONFIG_I2C_COMPAT
2310 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
2314 /* device name is gone after device_unregister */
2315 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
2317 pm_runtime_disable(&adap->dev);
2319 i2c_host_notify_irq_teardown(adap);
2321 /* wait until all references to the device are gone
2323 * FIXME: This is old code and should ideally be replaced by an
2324 * alternative which results in decoupling the lifetime of the struct
2325 * device from the i2c_adapter, like spi or netdev do. Any solution
2326 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
2328 init_completion(&adap->dev_released);
2329 device_unregister(&adap->dev);
2330 wait_for_completion(&adap->dev_released);
2333 mutex_lock(&core_lock);
2334 idr_remove(&i2c_adapter_idr, adap->nr);
2335 mutex_unlock(&core_lock);
2337 /* Clear the device structure in case this adapter is ever going to be
2339 memset(&adap->dev, 0, sizeof(adap->dev));
2341 EXPORT_SYMBOL(i2c_del_adapter);
2344 * i2c_parse_fw_timings - get I2C related timing parameters from firmware
2345 * @dev: The device to scan for I2C timing properties
2346 * @t: the i2c_timings struct to be filled with values
2347 * @use_defaults: bool to use sane defaults derived from the I2C specification
2348 * when properties are not found, otherwise use 0
2350 * Scan the device for the generic I2C properties describing timing parameters
2351 * for the signal and fill the given struct with the results. If a property was
2352 * not found and use_defaults was true, then maximum timings are assumed which
2353 * are derived from the I2C specification. If use_defaults is not used, the
2354 * results will be 0, so drivers can apply their own defaults later. The latter
2355 * is mainly intended for avoiding regressions of existing drivers which want
2356 * to switch to this function. New drivers almost always should use the defaults.
2359 void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
2363 memset(t, 0, sizeof(*t));
2365 ret = device_property_read_u32(dev, "clock-frequency", &t->bus_freq_hz);
2366 if (ret && use_defaults)
2367 t->bus_freq_hz = 100000;
2369 ret = device_property_read_u32(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns);
2370 if (ret && use_defaults) {
2371 if (t->bus_freq_hz <= 100000)
2372 t->scl_rise_ns = 1000;
2373 else if (t->bus_freq_hz <= 400000)
2374 t->scl_rise_ns = 300;
2376 t->scl_rise_ns = 120;
2379 ret = device_property_read_u32(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns);
2380 if (ret && use_defaults) {
2381 if (t->bus_freq_hz <= 400000)
2382 t->scl_fall_ns = 300;
2384 t->scl_fall_ns = 120;
2387 device_property_read_u32(dev, "i2c-scl-internal-delay-ns", &t->scl_int_delay_ns);
2389 ret = device_property_read_u32(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns);
2390 if (ret && use_defaults)
2391 t->sda_fall_ns = t->scl_fall_ns;
2393 EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
2395 /* ------------------------------------------------------------------------- */
2397 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
2401 mutex_lock(&core_lock);
2402 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
2403 mutex_unlock(&core_lock);
2407 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
2409 static int __process_new_driver(struct device *dev, void *data)
2411 if (dev->type != &i2c_adapter_type)
2413 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
2417 * An i2c_driver is used with one or more i2c_client (device) nodes to access
2418 * i2c slave chips, on a bus instance associated with some i2c_adapter.
2421 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
2425 /* Can't register until after driver model init */
2426 if (WARN_ON(!is_registered))
2429 /* add the driver to the list of i2c drivers in the driver core */
2430 driver->driver.owner = owner;
2431 driver->driver.bus = &i2c_bus_type;
2432 INIT_LIST_HEAD(&driver->clients);
2434 /* When registration returns, the driver core
2435 * will have called probe() for all matching-but-unbound devices.
2437 res = driver_register(&driver->driver);
2441 pr_debug("driver [%s] registered\n", driver->driver.name);
2443 /* Walk the adapters that are already present */
2444 i2c_for_each_dev(driver, __process_new_driver);
2448 EXPORT_SYMBOL(i2c_register_driver);
2450 static int __process_removed_driver(struct device *dev, void *data)
2452 if (dev->type == &i2c_adapter_type)
2453 i2c_do_del_adapter(data, to_i2c_adapter(dev));
2458 * i2c_del_driver - unregister I2C driver
2459 * @driver: the driver being unregistered
2460 * Context: can sleep
2462 void i2c_del_driver(struct i2c_driver *driver)
2464 i2c_for_each_dev(driver, __process_removed_driver);
2466 driver_unregister(&driver->driver);
2467 pr_debug("driver [%s] unregistered\n", driver->driver.name);
2469 EXPORT_SYMBOL(i2c_del_driver);
2471 /* ------------------------------------------------------------------------- */
2474 * i2c_use_client - increments the reference count of the i2c client structure
2475 * @client: the client being referenced
2477 * Each live reference to a client should be refcounted. The driver model does
2478 * that automatically as part of driver binding, so that most drivers don't
2479 * need to do this explicitly: they hold a reference until they're unbound
2482 * A pointer to the client with the incremented reference counter is returned.
2484 struct i2c_client *i2c_use_client(struct i2c_client *client)
2486 if (client && get_device(&client->dev))
2490 EXPORT_SYMBOL(i2c_use_client);
2493 * i2c_release_client - release a use of the i2c client structure
2494 * @client: the client being no longer referenced
2496 * Must be called when a user of a client is finished with it.
2498 void i2c_release_client(struct i2c_client *client)
2501 put_device(&client->dev);
2503 EXPORT_SYMBOL(i2c_release_client);
2505 struct i2c_cmd_arg {
2510 static int i2c_cmd(struct device *dev, void *_arg)
2512 struct i2c_client *client = i2c_verify_client(dev);
2513 struct i2c_cmd_arg *arg = _arg;
2514 struct i2c_driver *driver;
2516 if (!client || !client->dev.driver)
2519 driver = to_i2c_driver(client->dev.driver);
2520 if (driver->command)
2521 driver->command(client, arg->cmd, arg->arg);
2525 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
2527 struct i2c_cmd_arg cmd_arg;
2531 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
2533 EXPORT_SYMBOL(i2c_clients_command);
2535 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
2536 static int of_i2c_notify(struct notifier_block *nb, unsigned long action,
2539 struct of_reconfig_data *rd = arg;
2540 struct i2c_adapter *adap;
2541 struct i2c_client *client;
2543 switch (of_reconfig_get_state_change(action, rd)) {
2544 case OF_RECONFIG_CHANGE_ADD:
2545 adap = of_find_i2c_adapter_by_node(rd->dn->parent);
2547 return NOTIFY_OK; /* not for us */
2549 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
2550 put_device(&adap->dev);
2554 client = of_i2c_register_device(adap, rd->dn);
2555 put_device(&adap->dev);
2557 if (IS_ERR(client)) {
2558 dev_err(&adap->dev, "failed to create client for '%s'\n",
2560 of_node_clear_flag(rd->dn, OF_POPULATED);
2561 return notifier_from_errno(PTR_ERR(client));
2564 case OF_RECONFIG_CHANGE_REMOVE:
2565 /* already depopulated? */
2566 if (!of_node_check_flag(rd->dn, OF_POPULATED))
2569 /* find our device by node */
2570 client = of_find_i2c_device_by_node(rd->dn);
2572 return NOTIFY_OK; /* no? not meant for us */
2574 /* unregister takes one ref away */
2575 i2c_unregister_device(client);
2577 /* and put the reference of the find */
2578 put_device(&client->dev);
2584 static struct notifier_block i2c_of_notifier = {
2585 .notifier_call = of_i2c_notify,
2588 extern struct notifier_block i2c_of_notifier;
2589 #endif /* CONFIG_OF_DYNAMIC */
2591 static int __init i2c_init(void)
2595 retval = of_alias_get_highest_id("i2c");
2597 down_write(&__i2c_board_lock);
2598 if (retval >= __i2c_first_dynamic_bus_num)
2599 __i2c_first_dynamic_bus_num = retval + 1;
2600 up_write(&__i2c_board_lock);
2602 retval = bus_register(&i2c_bus_type);
2606 is_registered = true;
2608 #ifdef CONFIG_I2C_COMPAT
2609 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
2610 if (!i2c_adapter_compat_class) {
2615 retval = i2c_add_driver(&dummy_driver);
2619 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2620 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
2621 if (IS_ENABLED(CONFIG_ACPI))
2622 WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
2627 #ifdef CONFIG_I2C_COMPAT
2628 class_compat_unregister(i2c_adapter_compat_class);
2631 is_registered = false;
2632 bus_unregister(&i2c_bus_type);
2636 static void __exit i2c_exit(void)
2638 if (IS_ENABLED(CONFIG_ACPI))
2639 WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
2640 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2641 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
2642 i2c_del_driver(&dummy_driver);
2643 #ifdef CONFIG_I2C_COMPAT
2644 class_compat_unregister(i2c_adapter_compat_class);
2646 bus_unregister(&i2c_bus_type);
2647 tracepoint_synchronize_unregister();
2650 /* We must initialize early, because some subsystems register i2c drivers
2651 * in subsys_initcall() code, but are linked (and initialized) before i2c.
2653 postcore_initcall(i2c_init);
2654 module_exit(i2c_exit);
2656 /* ----------------------------------------------------
2657 * the functional interface to the i2c busses.
2658 * ----------------------------------------------------
2661 /* Check if val is exceeding the quirk IFF quirk is non 0 */
2662 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2664 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2666 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2667 err_msg, msg->addr, msg->len,
2668 msg->flags & I2C_M_RD ? "read" : "write");
2672 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2674 const struct i2c_adapter_quirks *q = adap->quirks;
2675 int max_num = q->max_num_msgs, i;
2676 bool do_len_check = true;
2678 if (q->flags & I2C_AQ_COMB) {
2681 /* special checks for combined messages */
2683 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2684 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2686 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2687 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2689 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2690 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2692 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2693 return i2c_quirk_error(adap, &msgs[0], "msg too long");
2695 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2696 return i2c_quirk_error(adap, &msgs[1], "msg too long");
2698 do_len_check = false;
2702 if (i2c_quirk_exceeded(num, max_num))
2703 return i2c_quirk_error(adap, &msgs[0], "too many messages");
2705 for (i = 0; i < num; i++) {
2706 u16 len = msgs[i].len;
2708 if (msgs[i].flags & I2C_M_RD) {
2709 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2710 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2712 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2713 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2721 * __i2c_transfer - unlocked flavor of i2c_transfer
2722 * @adap: Handle to I2C bus
2723 * @msgs: One or more messages to execute before STOP is issued to
2724 * terminate the operation; each message begins with a START.
2725 * @num: Number of messages to be executed.
2727 * Returns negative errno, else the number of messages executed.
2729 * Adapter lock must be held when calling this function. No debug logging
2730 * takes place. adap->algo->master_xfer existence isn't checked.
2732 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2734 unsigned long orig_jiffies;
2737 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2740 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2741 * enabled. This is an efficient way of keeping the for-loop from
2742 * being executed when not needed.
2744 if (static_key_false(&i2c_trace_msg)) {
2746 for (i = 0; i < num; i++)
2747 if (msgs[i].flags & I2C_M_RD)
2748 trace_i2c_read(adap, &msgs[i], i);
2750 trace_i2c_write(adap, &msgs[i], i);
2753 /* Retry automatically on arbitration loss */
2754 orig_jiffies = jiffies;
2755 for (ret = 0, try = 0; try <= adap->retries; try++) {
2756 ret = adap->algo->master_xfer(adap, msgs, num);
2759 if (time_after(jiffies, orig_jiffies + adap->timeout))
2763 if (static_key_false(&i2c_trace_msg)) {
2765 for (i = 0; i < ret; i++)
2766 if (msgs[i].flags & I2C_M_RD)
2767 trace_i2c_reply(adap, &msgs[i], i);
2768 trace_i2c_result(adap, i, ret);
2773 EXPORT_SYMBOL(__i2c_transfer);
2776 * i2c_transfer - execute a single or combined I2C message
2777 * @adap: Handle to I2C bus
2778 * @msgs: One or more messages to execute before STOP is issued to
2779 * terminate the operation; each message begins with a START.
2780 * @num: Number of messages to be executed.
2782 * Returns negative errno, else the number of messages executed.
2784 * Note that there is no requirement that each message be sent to
2785 * the same slave address, although that is the most common model.
2787 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2791 /* REVISIT the fault reporting model here is weak:
2793 * - When we get an error after receiving N bytes from a slave,
2794 * there is no way to report "N".
2796 * - When we get a NAK after transmitting N bytes to a slave,
2797 * there is no way to report "N" ... or to let the master
2798 * continue executing the rest of this combined message, if
2799 * that's the appropriate response.
2801 * - When for example "num" is two and we successfully complete
2802 * the first message but get an error part way through the
2803 * second, it's unclear whether that should be reported as
2804 * one (discarding status on the second message) or errno
2805 * (discarding status on the first one).
2808 if (adap->algo->master_xfer) {
2810 for (ret = 0; ret < num; ret++) {
2812 "master_xfer[%d] %c, addr=0x%02x, len=%d%s\n",
2813 ret, (msgs[ret].flags & I2C_M_RD) ? 'R' : 'W',
2814 msgs[ret].addr, msgs[ret].len,
2815 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2819 if (in_atomic() || irqs_disabled()) {
2820 ret = i2c_trylock_bus(adap, I2C_LOCK_SEGMENT);
2822 /* I2C activity is ongoing. */
2825 i2c_lock_bus(adap, I2C_LOCK_SEGMENT);
2828 ret = __i2c_transfer(adap, msgs, num);
2829 i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
2833 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2837 EXPORT_SYMBOL(i2c_transfer);
2840 * i2c_master_send - issue a single I2C message in master transmit mode
2841 * @client: Handle to slave device
2842 * @buf: Data that will be written to the slave
2843 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2845 * Returns negative errno, or else the number of bytes written.
2847 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2850 struct i2c_adapter *adap = client->adapter;
2853 msg.addr = client->addr;
2854 msg.flags = client->flags & I2C_M_TEN;
2856 msg.buf = (char *)buf;
2858 ret = i2c_transfer(adap, &msg, 1);
2861 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2862 * transmitted, else error code.
2864 return (ret == 1) ? count : ret;
2866 EXPORT_SYMBOL(i2c_master_send);
2869 * i2c_master_recv - issue a single I2C message in master receive mode
2870 * @client: Handle to slave device
2871 * @buf: Where to store data read from slave
2872 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2874 * Returns negative errno, or else the number of bytes read.
2876 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2878 struct i2c_adapter *adap = client->adapter;
2882 msg.addr = client->addr;
2883 msg.flags = client->flags & I2C_M_TEN;
2884 msg.flags |= I2C_M_RD;
2888 ret = i2c_transfer(adap, &msg, 1);
2891 * If everything went ok (i.e. 1 msg received), return #bytes received,
2894 return (ret == 1) ? count : ret;
2896 EXPORT_SYMBOL(i2c_master_recv);
2898 /* ----------------------------------------------------
2899 * the i2c address scanning function
2900 * Will not work for 10-bit addresses!
2901 * ----------------------------------------------------
2905 * Legacy default probe function, mostly relevant for SMBus. The default
2906 * probe method is a quick write, but it is known to corrupt the 24RF08
2907 * EEPROMs due to a state machine bug, and could also irreversibly
2908 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2909 * we use a short byte read instead. Also, some bus drivers don't implement
2910 * quick write, so we fallback to a byte read in that case too.
2911 * On x86, there is another special case for FSC hardware monitoring chips,
2912 * which want regular byte reads (address 0x73.) Fortunately, these are the
2913 * only known chips using this I2C address on PC hardware.
2914 * Returns 1 if probe succeeded, 0 if not.
2916 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2919 union i2c_smbus_data dummy;
2922 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2923 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2924 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2925 I2C_SMBUS_BYTE_DATA, &dummy);
2928 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2929 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2930 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2931 I2C_SMBUS_QUICK, NULL);
2932 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2933 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2934 I2C_SMBUS_BYTE, &dummy);
2936 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2944 static int i2c_detect_address(struct i2c_client *temp_client,
2945 struct i2c_driver *driver)
2947 struct i2c_board_info info;
2948 struct i2c_adapter *adapter = temp_client->adapter;
2949 int addr = temp_client->addr;
2952 /* Make sure the address is valid */
2953 err = i2c_check_7bit_addr_validity_strict(addr);
2955 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2960 /* Skip if already in use (7 bit, no need to encode flags) */
2961 if (i2c_check_addr_busy(adapter, addr))
2964 /* Make sure there is something at this address */
2965 if (!i2c_default_probe(adapter, addr))
2968 /* Finally call the custom detection function */
2969 memset(&info, 0, sizeof(struct i2c_board_info));
2971 err = driver->detect(temp_client, &info);
2973 /* -ENODEV is returned if the detection fails. We catch it
2974 here as this isn't an error. */
2975 return err == -ENODEV ? 0 : err;
2978 /* Consistency check */
2979 if (info.type[0] == '\0') {
2980 dev_err(&adapter->dev,
2981 "%s detection function provided no name for 0x%x\n",
2982 driver->driver.name, addr);
2984 struct i2c_client *client;
2986 /* Detection succeeded, instantiate the device */
2987 if (adapter->class & I2C_CLASS_DEPRECATED)
2988 dev_warn(&adapter->dev,
2989 "This adapter will soon drop class based instantiation of devices. "
2990 "Please make sure client 0x%02x gets instantiated by other means. "
2991 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2994 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2995 info.type, info.addr);
2996 client = i2c_new_device(adapter, &info);
2998 list_add_tail(&client->detected, &driver->clients);
3000 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
3001 info.type, info.addr);
3006 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
3008 const unsigned short *address_list;
3009 struct i2c_client *temp_client;
3011 int adap_id = i2c_adapter_id(adapter);
3013 address_list = driver->address_list;
3014 if (!driver->detect || !address_list)
3017 /* Warn that the adapter lost class based instantiation */
3018 if (adapter->class == I2C_CLASS_DEPRECATED) {
3019 dev_dbg(&adapter->dev,
3020 "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
3021 "If you need it, check 'Documentation/i2c/instantiating-devices' for alternatives.\n",
3022 driver->driver.name);
3026 /* Stop here if the classes do not match */
3027 if (!(adapter->class & driver->class))
3030 /* Set up a temporary client to help detect callback */
3031 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
3034 temp_client->adapter = adapter;
3036 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
3037 dev_dbg(&adapter->dev,
3038 "found normal entry for adapter %d, addr 0x%02x\n",
3039 adap_id, address_list[i]);
3040 temp_client->addr = address_list[i];
3041 err = i2c_detect_address(temp_client, driver);
3050 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
3052 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
3053 I2C_SMBUS_QUICK, NULL) >= 0;
3055 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
3058 i2c_new_probed_device(struct i2c_adapter *adap,
3059 struct i2c_board_info *info,
3060 unsigned short const *addr_list,
3061 int (*probe)(struct i2c_adapter *, unsigned short addr))
3066 probe = i2c_default_probe;
3068 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
3069 /* Check address validity */
3070 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
3071 dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
3076 /* Check address availability (7 bit, no need to encode flags) */
3077 if (i2c_check_addr_busy(adap, addr_list[i])) {
3079 "Address 0x%02x already in use, not probing\n",
3084 /* Test address responsiveness */
3085 if (probe(adap, addr_list[i]))
3089 if (addr_list[i] == I2C_CLIENT_END) {
3090 dev_dbg(&adap->dev, "Probing failed, no device found\n");
3094 info->addr = addr_list[i];
3095 return i2c_new_device(adap, info);
3097 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
3099 struct i2c_adapter *i2c_get_adapter(int nr)
3101 struct i2c_adapter *adapter;
3103 mutex_lock(&core_lock);
3104 adapter = idr_find(&i2c_adapter_idr, nr);
3108 if (try_module_get(adapter->owner))
3109 get_device(&adapter->dev);
3114 mutex_unlock(&core_lock);
3117 EXPORT_SYMBOL(i2c_get_adapter);
3119 void i2c_put_adapter(struct i2c_adapter *adap)
3124 put_device(&adap->dev);
3125 module_put(adap->owner);
3127 EXPORT_SYMBOL(i2c_put_adapter);
3129 /* The SMBus parts */
3131 #define POLY (0x1070U << 3)
3132 static u8 crc8(u16 data)
3136 for (i = 0; i < 8; i++) {
3141 return (u8)(data >> 8);
3144 /* Incremental CRC8 over count bytes in the array pointed to by p */
3145 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
3149 for (i = 0; i < count; i++)
3150 crc = crc8((crc ^ p[i]) << 8);
3154 /* Assume a 7-bit address, which is reasonable for SMBus */
3155 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
3157 /* The address will be sent first */
3158 u8 addr = i2c_8bit_addr_from_msg(msg);
3159 pec = i2c_smbus_pec(pec, &addr, 1);
3161 /* The data buffer follows */
3162 return i2c_smbus_pec(pec, msg->buf, msg->len);
3165 /* Used for write only transactions */
3166 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
3168 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
3172 /* Return <0 on CRC error
3173 If there was a write before this read (most cases) we need to take the
3174 partial CRC from the write part into account.
3175 Note that this function does modify the message (we need to decrease the
3176 message length to hide the CRC byte from the caller). */
3177 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
3179 u8 rpec = msg->buf[--msg->len];
3180 cpec = i2c_smbus_msg_pec(cpec, msg);
3183 pr_debug("Bad PEC 0x%02x vs. 0x%02x\n",
3191 * i2c_smbus_read_byte - SMBus "receive byte" protocol
3192 * @client: Handle to slave device
3194 * This executes the SMBus "receive byte" protocol, returning negative errno
3195 * else the byte received from the device.
3197 s32 i2c_smbus_read_byte(const struct i2c_client *client)
3199 union i2c_smbus_data data;
3202 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3204 I2C_SMBUS_BYTE, &data);
3205 return (status < 0) ? status : data.byte;
3207 EXPORT_SYMBOL(i2c_smbus_read_byte);
3210 * i2c_smbus_write_byte - SMBus "send byte" protocol
3211 * @client: Handle to slave device
3212 * @value: Byte to be sent
3214 * This executes the SMBus "send byte" protocol, returning negative errno
3215 * else zero on success.
3217 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
3219 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3220 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
3222 EXPORT_SYMBOL(i2c_smbus_write_byte);
3225 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
3226 * @client: Handle to slave device
3227 * @command: Byte interpreted by slave
3229 * This executes the SMBus "read byte" protocol, returning negative errno
3230 * else a data byte received from the device.
3232 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
3234 union i2c_smbus_data data;
3237 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3238 I2C_SMBUS_READ, command,
3239 I2C_SMBUS_BYTE_DATA, &data);
3240 return (status < 0) ? status : data.byte;
3242 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
3245 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
3246 * @client: Handle to slave device
3247 * @command: Byte interpreted by slave
3248 * @value: Byte being written
3250 * This executes the SMBus "write byte" protocol, returning negative errno
3251 * else zero on success.
3253 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
3256 union i2c_smbus_data data;
3258 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3259 I2C_SMBUS_WRITE, command,
3260 I2C_SMBUS_BYTE_DATA, &data);
3262 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
3265 * i2c_smbus_read_word_data - SMBus "read word" protocol
3266 * @client: Handle to slave device
3267 * @command: Byte interpreted by slave
3269 * This executes the SMBus "read word" protocol, returning negative errno
3270 * else a 16-bit unsigned "word" received from the device.
3272 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
3274 union i2c_smbus_data data;
3277 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3278 I2C_SMBUS_READ, command,
3279 I2C_SMBUS_WORD_DATA, &data);
3280 return (status < 0) ? status : data.word;
3282 EXPORT_SYMBOL(i2c_smbus_read_word_data);
3285 * i2c_smbus_write_word_data - SMBus "write word" protocol
3286 * @client: Handle to slave device
3287 * @command: Byte interpreted by slave
3288 * @value: 16-bit "word" being written
3290 * This executes the SMBus "write word" protocol, returning negative errno
3291 * else zero on success.
3293 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
3296 union i2c_smbus_data data;
3298 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3299 I2C_SMBUS_WRITE, command,
3300 I2C_SMBUS_WORD_DATA, &data);
3302 EXPORT_SYMBOL(i2c_smbus_write_word_data);
3305 * i2c_smbus_read_block_data - SMBus "block read" protocol
3306 * @client: Handle to slave device
3307 * @command: Byte interpreted by slave
3308 * @values: Byte array into which data will be read; big enough to hold
3309 * the data returned by the slave. SMBus allows at most 32 bytes.
3311 * This executes the SMBus "block read" protocol, returning negative errno
3312 * else the number of data bytes in the slave's response.
3314 * Note that using this function requires that the client's adapter support
3315 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
3316 * support this; its emulation through I2C messaging relies on a specific
3317 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
3319 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
3322 union i2c_smbus_data data;
3325 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3326 I2C_SMBUS_READ, command,
3327 I2C_SMBUS_BLOCK_DATA, &data);
3331 memcpy(values, &data.block[1], data.block[0]);
3332 return data.block[0];
3334 EXPORT_SYMBOL(i2c_smbus_read_block_data);
3337 * i2c_smbus_write_block_data - SMBus "block write" protocol
3338 * @client: Handle to slave device
3339 * @command: Byte interpreted by slave
3340 * @length: Size of data block; SMBus allows at most 32 bytes
3341 * @values: Byte array which will be written.
3343 * This executes the SMBus "block write" protocol, returning negative errno
3344 * else zero on success.
3346 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
3347 u8 length, const u8 *values)
3349 union i2c_smbus_data data;
3351 if (length > I2C_SMBUS_BLOCK_MAX)
3352 length = I2C_SMBUS_BLOCK_MAX;
3353 data.block[0] = length;
3354 memcpy(&data.block[1], values, length);
3355 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3356 I2C_SMBUS_WRITE, command,
3357 I2C_SMBUS_BLOCK_DATA, &data);
3359 EXPORT_SYMBOL(i2c_smbus_write_block_data);
3361 /* Returns the number of read bytes */
3362 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
3363 u8 length, u8 *values)
3365 union i2c_smbus_data data;
3368 if (length > I2C_SMBUS_BLOCK_MAX)
3369 length = I2C_SMBUS_BLOCK_MAX;
3370 data.block[0] = length;
3371 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3372 I2C_SMBUS_READ, command,
3373 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3377 memcpy(values, &data.block[1], data.block[0]);
3378 return data.block[0];
3380 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
3382 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
3383 u8 length, const u8 *values)
3385 union i2c_smbus_data data;
3387 if (length > I2C_SMBUS_BLOCK_MAX)
3388 length = I2C_SMBUS_BLOCK_MAX;
3389 data.block[0] = length;
3390 memcpy(data.block + 1, values, length);
3391 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3392 I2C_SMBUS_WRITE, command,
3393 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3395 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
3397 /* Simulate a SMBus command using the i2c protocol
3398 No checking of parameters is done! */
3399 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
3400 unsigned short flags,
3401 char read_write, u8 command, int size,
3402 union i2c_smbus_data *data)
3404 /* So we need to generate a series of msgs. In the case of writing, we
3405 need to use only one message; when reading, we need two. We initialize
3406 most things with sane defaults, to keep the code below somewhat
3408 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
3409 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
3410 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
3414 struct i2c_msg msg[2] = {
3422 .flags = flags | I2C_M_RD,
3428 msgbuf0[0] = command;
3430 case I2C_SMBUS_QUICK:
3432 /* Special case: The read/write field is used as data */
3433 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
3437 case I2C_SMBUS_BYTE:
3438 if (read_write == I2C_SMBUS_READ) {
3439 /* Special case: only a read! */
3440 msg[0].flags = I2C_M_RD | flags;
3444 case I2C_SMBUS_BYTE_DATA:
3445 if (read_write == I2C_SMBUS_READ)
3449 msgbuf0[1] = data->byte;
3452 case I2C_SMBUS_WORD_DATA:
3453 if (read_write == I2C_SMBUS_READ)
3457 msgbuf0[1] = data->word & 0xff;
3458 msgbuf0[2] = data->word >> 8;
3461 case I2C_SMBUS_PROC_CALL:
3462 num = 2; /* Special case */
3463 read_write = I2C_SMBUS_READ;
3466 msgbuf0[1] = data->word & 0xff;
3467 msgbuf0[2] = data->word >> 8;
3469 case I2C_SMBUS_BLOCK_DATA:
3470 if (read_write == I2C_SMBUS_READ) {
3471 msg[1].flags |= I2C_M_RECV_LEN;
3472 msg[1].len = 1; /* block length will be added by
3473 the underlying bus driver */
3475 msg[0].len = data->block[0] + 2;
3476 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
3477 dev_err(&adapter->dev,
3478 "Invalid block write size %d\n",
3482 for (i = 1; i < msg[0].len; i++)
3483 msgbuf0[i] = data->block[i-1];
3486 case I2C_SMBUS_BLOCK_PROC_CALL:
3487 num = 2; /* Another special case */
3488 read_write = I2C_SMBUS_READ;
3489 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
3490 dev_err(&adapter->dev,
3491 "Invalid block write size %d\n",
3495 msg[0].len = data->block[0] + 2;
3496 for (i = 1; i < msg[0].len; i++)
3497 msgbuf0[i] = data->block[i-1];
3498 msg[1].flags |= I2C_M_RECV_LEN;
3499 msg[1].len = 1; /* block length will be added by
3500 the underlying bus driver */
3502 case I2C_SMBUS_I2C_BLOCK_DATA:
3503 if (read_write == I2C_SMBUS_READ) {
3504 msg[1].len = data->block[0];
3506 msg[0].len = data->block[0] + 1;
3507 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
3508 dev_err(&adapter->dev,
3509 "Invalid block write size %d\n",
3513 for (i = 1; i <= data->block[0]; i++)
3514 msgbuf0[i] = data->block[i];
3518 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
3522 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
3523 && size != I2C_SMBUS_I2C_BLOCK_DATA);
3525 /* Compute PEC if first message is a write */
3526 if (!(msg[0].flags & I2C_M_RD)) {
3527 if (num == 1) /* Write only */
3528 i2c_smbus_add_pec(&msg[0]);
3529 else /* Write followed by read */
3530 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
3532 /* Ask for PEC if last message is a read */
3533 if (msg[num-1].flags & I2C_M_RD)
3537 status = i2c_transfer(adapter, msg, num);
3541 /* Check PEC if last message is a read */
3542 if (i && (msg[num-1].flags & I2C_M_RD)) {
3543 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
3548 if (read_write == I2C_SMBUS_READ)
3550 case I2C_SMBUS_BYTE:
3551 data->byte = msgbuf0[0];
3553 case I2C_SMBUS_BYTE_DATA:
3554 data->byte = msgbuf1[0];
3556 case I2C_SMBUS_WORD_DATA:
3557 case I2C_SMBUS_PROC_CALL:
3558 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
3560 case I2C_SMBUS_I2C_BLOCK_DATA:
3561 for (i = 0; i < data->block[0]; i++)
3562 data->block[i+1] = msgbuf1[i];
3564 case I2C_SMBUS_BLOCK_DATA:
3565 case I2C_SMBUS_BLOCK_PROC_CALL:
3566 for (i = 0; i < msgbuf1[0] + 1; i++)
3567 data->block[i] = msgbuf1[i];
3574 * i2c_smbus_xfer - execute SMBus protocol operations
3575 * @adapter: Handle to I2C bus
3576 * @addr: Address of SMBus slave on that bus
3577 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
3578 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
3579 * @command: Byte interpreted by slave, for protocols which use such bytes
3580 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
3581 * @data: Data to be read or written
3583 * This executes an SMBus protocol operation, and returns a negative
3584 * errno code else zero on success.
3586 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
3587 char read_write, u8 command, int protocol,
3588 union i2c_smbus_data *data)
3590 unsigned long orig_jiffies;
3594 /* If enabled, the following two tracepoints are conditional on
3595 * read_write and protocol.
3597 trace_smbus_write(adapter, addr, flags, read_write,
3598 command, protocol, data);
3599 trace_smbus_read(adapter, addr, flags, read_write,
3602 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
3604 if (adapter->algo->smbus_xfer) {
3605 i2c_lock_bus(adapter, I2C_LOCK_SEGMENT);
3607 /* Retry automatically on arbitration loss */
3608 orig_jiffies = jiffies;
3609 for (res = 0, try = 0; try <= adapter->retries; try++) {
3610 res = adapter->algo->smbus_xfer(adapter, addr, flags,
3611 read_write, command,
3615 if (time_after(jiffies,
3616 orig_jiffies + adapter->timeout))
3619 i2c_unlock_bus(adapter, I2C_LOCK_SEGMENT);
3621 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
3624 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
3625 * implement native support for the SMBus operation.
3629 res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
3630 command, protocol, data);
3633 /* If enabled, the reply tracepoint is conditional on read_write. */
3634 trace_smbus_reply(adapter, addr, flags, read_write,
3635 command, protocol, data);
3636 trace_smbus_result(adapter, addr, flags, read_write,
3637 command, protocol, res);
3641 EXPORT_SYMBOL(i2c_smbus_xfer);
3644 * i2c_smbus_read_i2c_block_data_or_emulated - read block or emulate
3645 * @client: Handle to slave device
3646 * @command: Byte interpreted by slave
3647 * @length: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
3648 * @values: Byte array into which data will be read; big enough to hold
3649 * the data returned by the slave. SMBus allows at most
3650 * I2C_SMBUS_BLOCK_MAX bytes.
3652 * This executes the SMBus "block read" protocol if supported by the adapter.
3653 * If block read is not supported, it emulates it using either word or byte
3654 * read protocols depending on availability.
3656 * The addresses of the I2C slave device that are accessed with this function
3657 * must be mapped to a linear region, so that a block read will have the same
3658 * effect as a byte read. Before using this function you must double-check
3659 * if the I2C slave does support exchanging a block transfer with a byte
3662 s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client,
3663 u8 command, u8 length, u8 *values)
3668 if (length > I2C_SMBUS_BLOCK_MAX)
3669 length = I2C_SMBUS_BLOCK_MAX;
3671 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
3672 return i2c_smbus_read_i2c_block_data(client, command, length, values);
3674 if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA))
3677 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) {
3678 while ((i + 2) <= length) {
3679 status = i2c_smbus_read_word_data(client, command + i);
3682 values[i] = status & 0xff;
3683 values[i + 1] = status >> 8;
3688 while (i < length) {
3689 status = i2c_smbus_read_byte_data(client, command + i);
3698 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data_or_emulated);
3700 #if IS_ENABLED(CONFIG_I2C_SLAVE)
3701 int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
3705 if (!client || !slave_cb) {
3706 WARN(1, "insufficient data\n");
3710 if (!(client->flags & I2C_CLIENT_SLAVE))
3711 dev_warn(&client->dev, "%s: client slave flag not set. You might see address collisions\n",
3714 if (!(client->flags & I2C_CLIENT_TEN)) {
3715 /* Enforce stricter address checking */
3716 ret = i2c_check_7bit_addr_validity_strict(client->addr);
3718 dev_err(&client->dev, "%s: invalid address\n", __func__);
3723 if (!client->adapter->algo->reg_slave) {
3724 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3728 client->slave_cb = slave_cb;
3730 i2c_lock_adapter(client->adapter);
3731 ret = client->adapter->algo->reg_slave(client);
3732 i2c_unlock_adapter(client->adapter);
3735 client->slave_cb = NULL;
3736 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3741 EXPORT_SYMBOL_GPL(i2c_slave_register);
3743 int i2c_slave_unregister(struct i2c_client *client)
3747 if (!client->adapter->algo->unreg_slave) {
3748 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3752 i2c_lock_adapter(client->adapter);
3753 ret = client->adapter->algo->unreg_slave(client);
3754 i2c_unlock_adapter(client->adapter);
3757 client->slave_cb = NULL;
3759 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3763 EXPORT_SYMBOL_GPL(i2c_slave_unregister);
3766 * i2c_detect_slave_mode - detect operation mode
3767 * @dev: The device owning the bus
3769 * This checks the device nodes for an I2C slave by checking the address
3770 * used in the reg property. If the address match the I2C_OWN_SLAVE_ADDRESS
3771 * flag this means the device is configured to act as a I2C slave and it will
3772 * be listening at that address.
3774 * Returns true if an I2C own slave address is detected, otherwise returns
3777 bool i2c_detect_slave_mode(struct device *dev)
3779 if (IS_BUILTIN(CONFIG_OF) && dev->of_node) {
3780 struct device_node *child;
3783 for_each_child_of_node(dev->of_node, child) {
3784 of_property_read_u32(child, "reg", ®);
3785 if (reg & I2C_OWN_SLAVE_ADDRESS) {
3790 } else if (IS_BUILTIN(CONFIG_ACPI) && ACPI_HANDLE(dev)) {
3791 dev_dbg(dev, "ACPI slave is not supported yet\n");
3795 EXPORT_SYMBOL_GPL(i2c_detect_slave_mode);
3799 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
3800 MODULE_DESCRIPTION("I2C-Bus main module");
3801 MODULE_LICENSE("GPL");