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 int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
79 static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
80 static bool is_registered;
82 int i2c_transfer_trace_reg(void)
84 static_key_slow_inc(&i2c_trace_msg);
88 void i2c_transfer_trace_unreg(void)
90 static_key_slow_dec(&i2c_trace_msg);
93 #if defined(CONFIG_ACPI)
94 struct i2c_acpi_handler_data {
95 struct acpi_connection_info info;
96 struct i2c_adapter *adapter;
109 struct i2c_acpi_lookup {
110 struct i2c_board_info *info;
111 acpi_handle adapter_handle;
112 acpi_handle device_handle;
113 acpi_handle search_handle;
120 static int i2c_acpi_fill_info(struct acpi_resource *ares, void *data)
122 struct i2c_acpi_lookup *lookup = data;
123 struct i2c_board_info *info = lookup->info;
124 struct acpi_resource_i2c_serialbus *sb;
127 if (info->addr || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
130 sb = &ares->data.i2c_serial_bus;
131 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C)
134 if (lookup->index != -1 && lookup->n++ != lookup->index)
137 status = acpi_get_handle(lookup->device_handle,
138 sb->resource_source.string_ptr,
139 &lookup->adapter_handle);
140 if (!ACPI_SUCCESS(status))
143 info->addr = sb->slave_address;
144 lookup->speed = sb->connection_speed;
145 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
146 info->flags |= I2C_CLIENT_TEN;
151 static int i2c_acpi_do_lookup(struct acpi_device *adev,
152 struct i2c_acpi_lookup *lookup)
154 struct i2c_board_info *info = lookup->info;
155 struct list_head resource_list;
158 if (acpi_bus_get_status(adev) || !adev->status.present ||
159 acpi_device_enumerated(adev))
162 memset(info, 0, sizeof(*info));
163 lookup->device_handle = acpi_device_handle(adev);
165 /* Look up for I2cSerialBus resource */
166 INIT_LIST_HEAD(&resource_list);
167 ret = acpi_dev_get_resources(adev, &resource_list,
168 i2c_acpi_fill_info, lookup);
169 acpi_dev_free_resource_list(&resource_list);
171 if (ret < 0 || !info->addr)
177 static int i2c_acpi_get_info(struct acpi_device *adev,
178 struct i2c_board_info *info,
179 struct i2c_adapter *adapter,
180 acpi_handle *adapter_handle)
182 struct list_head resource_list;
183 struct resource_entry *entry;
184 struct i2c_acpi_lookup lookup;
187 memset(&lookup, 0, sizeof(lookup));
191 ret = i2c_acpi_do_lookup(adev, &lookup);
196 /* The adapter must match the one in I2cSerialBus() connector */
197 if (ACPI_HANDLE(&adapter->dev) != lookup.adapter_handle)
200 struct acpi_device *adapter_adev;
202 /* The adapter must be present */
203 if (acpi_bus_get_device(lookup.adapter_handle, &adapter_adev))
205 if (acpi_bus_get_status(adapter_adev) ||
206 !adapter_adev->status.present)
210 info->fwnode = acpi_fwnode_handle(adev);
212 *adapter_handle = lookup.adapter_handle;
214 /* Then fill IRQ number if any */
215 INIT_LIST_HEAD(&resource_list);
216 ret = acpi_dev_get_resources(adev, &resource_list, NULL, NULL);
220 resource_list_for_each_entry(entry, &resource_list) {
221 if (resource_type(entry->res) == IORESOURCE_IRQ) {
222 info->irq = entry->res->start;
227 acpi_dev_free_resource_list(&resource_list);
229 acpi_set_modalias(adev, dev_name(&adev->dev), info->type,
235 static void i2c_acpi_register_device(struct i2c_adapter *adapter,
236 struct acpi_device *adev,
237 struct i2c_board_info *info)
239 adev->power.flags.ignore_parent = true;
240 acpi_device_set_enumerated(adev);
242 if (!i2c_new_device(adapter, info)) {
243 adev->power.flags.ignore_parent = false;
244 dev_err(&adapter->dev,
245 "failed to add I2C device %s from ACPI\n",
246 dev_name(&adev->dev));
250 static acpi_status i2c_acpi_add_device(acpi_handle handle, u32 level,
251 void *data, void **return_value)
253 struct i2c_adapter *adapter = data;
254 struct acpi_device *adev;
255 struct i2c_board_info info;
257 if (acpi_bus_get_device(handle, &adev))
260 if (i2c_acpi_get_info(adev, &info, adapter, NULL))
263 i2c_acpi_register_device(adapter, adev, &info);
268 #define I2C_ACPI_MAX_SCAN_DEPTH 32
271 * i2c_acpi_register_devices - enumerate I2C slave devices behind adapter
272 * @adap: pointer to adapter
274 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
275 * namespace. When a device is found it will be added to the Linux device
276 * model and bound to the corresponding ACPI handle.
278 static void i2c_acpi_register_devices(struct i2c_adapter *adap)
282 if (!has_acpi_companion(&adap->dev))
285 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
286 I2C_ACPI_MAX_SCAN_DEPTH,
287 i2c_acpi_add_device, NULL,
289 if (ACPI_FAILURE(status))
290 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
293 static acpi_status i2c_acpi_lookup_speed(acpi_handle handle, u32 level,
294 void *data, void **return_value)
296 struct i2c_acpi_lookup *lookup = data;
297 struct acpi_device *adev;
299 if (acpi_bus_get_device(handle, &adev))
302 if (i2c_acpi_do_lookup(adev, lookup))
305 if (lookup->search_handle != lookup->adapter_handle)
308 if (lookup->speed <= lookup->min_speed)
309 lookup->min_speed = lookup->speed;
315 * i2c_acpi_find_bus_speed - find I2C bus speed from ACPI
316 * @dev: The device owning the bus
318 * Find the I2C bus speed by walking the ACPI namespace for all I2C slaves
319 * devices connected to this bus and use the speed of slowest device.
321 * Returns the speed in Hz or zero
323 u32 i2c_acpi_find_bus_speed(struct device *dev)
325 struct i2c_acpi_lookup lookup;
326 struct i2c_board_info dummy;
329 if (!has_acpi_companion(dev))
332 memset(&lookup, 0, sizeof(lookup));
333 lookup.search_handle = ACPI_HANDLE(dev);
334 lookup.min_speed = UINT_MAX;
335 lookup.info = &dummy;
338 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
339 I2C_ACPI_MAX_SCAN_DEPTH,
340 i2c_acpi_lookup_speed, NULL,
343 if (ACPI_FAILURE(status)) {
344 dev_warn(dev, "unable to find I2C bus speed from ACPI\n");
348 return lookup.min_speed != UINT_MAX ? lookup.min_speed : 0;
350 EXPORT_SYMBOL_GPL(i2c_acpi_find_bus_speed);
352 static int i2c_acpi_match_adapter(struct device *dev, void *data)
354 struct i2c_adapter *adapter = i2c_verify_adapter(dev);
359 return ACPI_HANDLE(dev) == (acpi_handle)data;
362 static int i2c_acpi_match_device(struct device *dev, void *data)
364 return ACPI_COMPANION(dev) == data;
367 static struct i2c_adapter *i2c_acpi_find_adapter_by_handle(acpi_handle handle)
371 dev = bus_find_device(&i2c_bus_type, NULL, handle,
372 i2c_acpi_match_adapter);
373 return dev ? i2c_verify_adapter(dev) : NULL;
376 static struct i2c_client *i2c_acpi_find_client_by_adev(struct acpi_device *adev)
380 dev = bus_find_device(&i2c_bus_type, NULL, adev, i2c_acpi_match_device);
381 return dev ? i2c_verify_client(dev) : NULL;
384 static int i2c_acpi_notify(struct notifier_block *nb, unsigned long value,
387 struct acpi_device *adev = arg;
388 struct i2c_board_info info;
389 acpi_handle adapter_handle;
390 struct i2c_adapter *adapter;
391 struct i2c_client *client;
394 case ACPI_RECONFIG_DEVICE_ADD:
395 if (i2c_acpi_get_info(adev, &info, NULL, &adapter_handle))
398 adapter = i2c_acpi_find_adapter_by_handle(adapter_handle);
402 i2c_acpi_register_device(adapter, adev, &info);
404 case ACPI_RECONFIG_DEVICE_REMOVE:
405 if (!acpi_device_enumerated(adev))
408 client = i2c_acpi_find_client_by_adev(adev);
412 i2c_unregister_device(client);
413 put_device(&client->dev);
420 static struct notifier_block i2c_acpi_notifier = {
421 .notifier_call = i2c_acpi_notify,
425 * i2c_acpi_new_device - Create i2c-client for the Nth I2cSerialBus resource
426 * @dev: Device owning the ACPI resources to get the client from
427 * @index: Index of ACPI resource to get
428 * @info: describes the I2C device; note this is modified (addr gets set)
431 * By default the i2c subsys creates an i2c-client for the first I2cSerialBus
432 * resource of an acpi_device, but some acpi_devices have multiple I2cSerialBus
433 * resources, in that case this function can be used to create an i2c-client
434 * for other I2cSerialBus resources in the Current Resource Settings table.
436 * Also see i2c_new_device, which this function calls to create the i2c-client.
438 * Returns a pointer to the new i2c-client, or NULL if the adapter is not found.
440 struct i2c_client *i2c_acpi_new_device(struct device *dev, int index,
441 struct i2c_board_info *info)
443 struct i2c_acpi_lookup lookup;
444 struct i2c_adapter *adapter;
445 struct acpi_device *adev;
446 LIST_HEAD(resource_list);
449 adev = ACPI_COMPANION(dev);
453 memset(&lookup, 0, sizeof(lookup));
455 lookup.device_handle = acpi_device_handle(adev);
456 lookup.index = index;
458 ret = acpi_dev_get_resources(adev, &resource_list,
459 i2c_acpi_fill_info, &lookup);
460 acpi_dev_free_resource_list(&resource_list);
462 if (ret < 0 || !info->addr)
465 adapter = i2c_acpi_find_adapter_by_handle(lookup.adapter_handle);
469 return i2c_new_device(adapter, info);
471 EXPORT_SYMBOL_GPL(i2c_acpi_new_device);
472 #else /* CONFIG_ACPI */
473 static inline void i2c_acpi_register_devices(struct i2c_adapter *adap) { }
474 extern struct notifier_block i2c_acpi_notifier;
475 #endif /* CONFIG_ACPI */
477 #ifdef CONFIG_ACPI_I2C_OPREGION
478 static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
479 u8 cmd, u8 *data, u8 data_len)
482 struct i2c_msg msgs[2];
486 buffer = kzalloc(data_len, GFP_KERNEL);
490 msgs[0].addr = client->addr;
491 msgs[0].flags = client->flags;
495 msgs[1].addr = client->addr;
496 msgs[1].flags = client->flags | I2C_M_RD;
497 msgs[1].len = data_len;
498 msgs[1].buf = buffer;
500 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
502 dev_err(&client->adapter->dev, "i2c read failed\n");
504 memcpy(data, buffer, data_len);
510 static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
511 u8 cmd, u8 *data, u8 data_len)
514 struct i2c_msg msgs[1];
518 buffer = kzalloc(data_len + 1, GFP_KERNEL);
523 memcpy(buffer + 1, data, data_len);
525 msgs[0].addr = client->addr;
526 msgs[0].flags = client->flags;
527 msgs[0].len = data_len + 1;
528 msgs[0].buf = buffer;
530 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
532 dev_err(&client->adapter->dev, "i2c write failed\n");
539 i2c_acpi_space_handler(u32 function, acpi_physical_address command,
540 u32 bits, u64 *value64,
541 void *handler_context, void *region_context)
543 struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
544 struct i2c_acpi_handler_data *data = handler_context;
545 struct acpi_connection_info *info = &data->info;
546 struct acpi_resource_i2c_serialbus *sb;
547 struct i2c_adapter *adapter = data->adapter;
548 struct i2c_client *client;
549 struct acpi_resource *ares;
550 u32 accessor_type = function >> 16;
551 u8 action = function & ACPI_IO_MASK;
555 ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
556 if (ACPI_FAILURE(ret))
559 client = kzalloc(sizeof(*client), GFP_KERNEL);
565 if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
566 ret = AE_BAD_PARAMETER;
570 sb = &ares->data.i2c_serial_bus;
571 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
572 ret = AE_BAD_PARAMETER;
576 client->adapter = adapter;
577 client->addr = sb->slave_address;
579 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
580 client->flags |= I2C_CLIENT_TEN;
582 switch (accessor_type) {
583 case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
584 if (action == ACPI_READ) {
585 status = i2c_smbus_read_byte(client);
591 status = i2c_smbus_write_byte(client, gsb->bdata);
595 case ACPI_GSB_ACCESS_ATTRIB_BYTE:
596 if (action == ACPI_READ) {
597 status = i2c_smbus_read_byte_data(client, command);
603 status = i2c_smbus_write_byte_data(client, command,
608 case ACPI_GSB_ACCESS_ATTRIB_WORD:
609 if (action == ACPI_READ) {
610 status = i2c_smbus_read_word_data(client, command);
616 status = i2c_smbus_write_word_data(client, command,
621 case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
622 if (action == ACPI_READ) {
623 status = i2c_smbus_read_block_data(client, command,
630 status = i2c_smbus_write_block_data(client, command,
631 gsb->len, gsb->data);
635 case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
636 if (action == ACPI_READ) {
637 status = acpi_gsb_i2c_read_bytes(client, command,
638 gsb->data, info->access_length);
642 status = acpi_gsb_i2c_write_bytes(client, command,
643 gsb->data, info->access_length);
648 dev_warn(&adapter->dev, "protocol 0x%02x not supported for client 0x%02x\n",
649 accessor_type, client->addr);
650 ret = AE_BAD_PARAMETER;
654 gsb->status = status;
663 static int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
666 struct i2c_acpi_handler_data *data;
669 if (!adapter->dev.parent)
672 handle = ACPI_HANDLE(adapter->dev.parent);
677 data = kzalloc(sizeof(struct i2c_acpi_handler_data),
682 data->adapter = adapter;
683 status = acpi_bus_attach_private_data(handle, (void *)data);
684 if (ACPI_FAILURE(status)) {
689 status = acpi_install_address_space_handler(handle,
690 ACPI_ADR_SPACE_GSBUS,
691 &i2c_acpi_space_handler,
694 if (ACPI_FAILURE(status)) {
695 dev_err(&adapter->dev, "Error installing i2c space handler\n");
696 acpi_bus_detach_private_data(handle);
701 acpi_walk_dep_device_list(handle);
705 static void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
708 struct i2c_acpi_handler_data *data;
711 if (!adapter->dev.parent)
714 handle = ACPI_HANDLE(adapter->dev.parent);
719 acpi_remove_address_space_handler(handle,
720 ACPI_ADR_SPACE_GSBUS,
721 &i2c_acpi_space_handler);
723 status = acpi_bus_get_private_data(handle, (void **)&data);
724 if (ACPI_SUCCESS(status))
727 acpi_bus_detach_private_data(handle);
729 #else /* CONFIG_ACPI_I2C_OPREGION */
730 static inline void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
733 static inline int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
735 #endif /* CONFIG_ACPI_I2C_OPREGION */
737 /* ------------------------------------------------------------------------- */
739 const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
740 const struct i2c_client *client)
745 while (id->name[0]) {
746 if (strcmp(client->name, id->name) == 0)
752 EXPORT_SYMBOL_GPL(i2c_match_id);
754 static int i2c_device_match(struct device *dev, struct device_driver *drv)
756 struct i2c_client *client = i2c_verify_client(dev);
757 struct i2c_driver *driver;
760 /* Attempt an OF style match */
761 if (i2c_of_match_device(drv->of_match_table, client))
764 /* Then ACPI style match */
765 if (acpi_driver_match_device(dev, drv))
768 driver = to_i2c_driver(drv);
770 /* Finally an I2C match */
771 if (i2c_match_id(driver->id_table, client))
777 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
779 struct i2c_client *client = to_i2c_client(dev);
782 rc = acpi_device_uevent_modalias(dev, env);
786 return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
789 /* i2c bus recovery routines */
790 static int get_scl_gpio_value(struct i2c_adapter *adap)
792 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
795 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
797 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
800 static int get_sda_gpio_value(struct i2c_adapter *adap)
802 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
805 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
807 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
808 struct device *dev = &adap->dev;
811 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
812 GPIOF_OUT_INIT_HIGH, "i2c-scl");
814 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
819 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
820 /* work without SDA polling */
821 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
830 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
832 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
835 gpio_free(bri->sda_gpio);
837 gpio_free(bri->scl_gpio);
841 * We are generating clock pulses. ndelay() determines durating of clk pulses.
842 * We will generate clock with rate 100 KHz and so duration of both clock levels
843 * is: delay in ns = (10^6 / 100) / 2
845 #define RECOVERY_NDELAY 5000
846 #define RECOVERY_CLK_CNT 9
848 static int i2c_generic_recovery(struct i2c_adapter *adap)
850 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
851 int i = 0, val = 1, ret = 0;
853 if (bri->prepare_recovery)
854 bri->prepare_recovery(adap);
856 bri->set_scl(adap, val);
857 ndelay(RECOVERY_NDELAY);
860 * By this time SCL is high, as we need to give 9 falling-rising edges
862 while (i++ < RECOVERY_CLK_CNT * 2) {
864 /* Break if SDA is high */
865 if (bri->get_sda && bri->get_sda(adap))
867 /* SCL shouldn't be low here */
868 if (!bri->get_scl(adap)) {
870 "SCL is stuck low, exit recovery\n");
877 bri->set_scl(adap, val);
878 ndelay(RECOVERY_NDELAY);
881 if (bri->unprepare_recovery)
882 bri->unprepare_recovery(adap);
887 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
889 return i2c_generic_recovery(adap);
891 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
893 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
897 ret = i2c_get_gpios_for_recovery(adap);
901 ret = i2c_generic_recovery(adap);
902 i2c_put_gpios_for_recovery(adap);
906 EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
908 int i2c_recover_bus(struct i2c_adapter *adap)
910 if (!adap->bus_recovery_info)
913 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
914 return adap->bus_recovery_info->recover_bus(adap);
916 EXPORT_SYMBOL_GPL(i2c_recover_bus);
918 static void i2c_init_recovery(struct i2c_adapter *adap)
920 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
926 if (!bri->recover_bus) {
927 err_str = "no recover_bus() found";
931 /* Generic GPIO recovery */
932 if (bri->recover_bus == i2c_generic_gpio_recovery) {
933 if (!gpio_is_valid(bri->scl_gpio)) {
934 err_str = "invalid SCL gpio";
938 if (gpio_is_valid(bri->sda_gpio))
939 bri->get_sda = get_sda_gpio_value;
943 bri->get_scl = get_scl_gpio_value;
944 bri->set_scl = set_scl_gpio_value;
945 } else if (bri->recover_bus == i2c_generic_scl_recovery) {
946 /* Generic SCL recovery */
947 if (!bri->set_scl || !bri->get_scl) {
948 err_str = "no {get|set}_scl() found";
955 dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
956 adap->bus_recovery_info = NULL;
959 static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
961 struct i2c_adapter *adap = client->adapter;
964 if (!adap->host_notify_domain)
967 if (client->flags & I2C_CLIENT_TEN)
970 irq = irq_find_mapping(adap->host_notify_domain, client->addr);
972 irq = irq_create_mapping(adap->host_notify_domain,
975 return irq > 0 ? irq : -ENXIO;
978 static int i2c_device_probe(struct device *dev)
980 struct i2c_client *client = i2c_verify_client(dev);
981 struct i2c_driver *driver;
987 driver = to_i2c_driver(dev->driver);
989 if (!client->irq && !driver->disable_i2c_core_irq_mapping) {
992 if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
993 dev_dbg(dev, "Using Host Notify IRQ\n");
994 irq = i2c_smbus_host_notify_to_irq(client);
995 } else if (dev->of_node) {
996 irq = of_irq_get_byname(dev->of_node, "irq");
997 if (irq == -EINVAL || irq == -ENODATA)
998 irq = of_irq_get(dev->of_node, 0);
999 } else if (ACPI_COMPANION(dev)) {
1000 irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
1002 if (irq == -EPROBE_DEFER)
1012 * An I2C ID table is not mandatory, if and only if, a suitable Device
1013 * Tree match table entry is supplied for the probing device.
1015 if (!driver->id_table &&
1016 !i2c_of_match_device(dev->driver->of_match_table, client))
1019 if (client->flags & I2C_CLIENT_WAKE) {
1020 int wakeirq = -ENOENT;
1023 wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
1024 if (wakeirq == -EPROBE_DEFER)
1028 device_init_wakeup(&client->dev, true);
1030 if (wakeirq > 0 && wakeirq != client->irq)
1031 status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
1032 else if (client->irq > 0)
1033 status = dev_pm_set_wake_irq(dev, client->irq);
1038 dev_warn(&client->dev, "failed to set up wakeup irq\n");
1041 dev_dbg(dev, "probe\n");
1043 status = of_clk_set_defaults(dev->of_node, false);
1045 goto err_clear_wakeup_irq;
1047 status = dev_pm_domain_attach(&client->dev, true);
1048 if (status == -EPROBE_DEFER)
1049 goto err_clear_wakeup_irq;
1052 * When there are no more users of probe(),
1053 * rename probe_new to probe.
1055 if (driver->probe_new)
1056 status = driver->probe_new(client);
1057 else if (driver->probe)
1058 status = driver->probe(client,
1059 i2c_match_id(driver->id_table, client));
1064 goto err_detach_pm_domain;
1068 err_detach_pm_domain:
1069 dev_pm_domain_detach(&client->dev, true);
1070 err_clear_wakeup_irq:
1071 dev_pm_clear_wake_irq(&client->dev);
1072 device_init_wakeup(&client->dev, false);
1076 static int i2c_device_remove(struct device *dev)
1078 struct i2c_client *client = i2c_verify_client(dev);
1079 struct i2c_driver *driver;
1082 if (!client || !dev->driver)
1085 driver = to_i2c_driver(dev->driver);
1086 if (driver->remove) {
1087 dev_dbg(dev, "remove\n");
1088 status = driver->remove(client);
1091 dev_pm_domain_detach(&client->dev, true);
1093 dev_pm_clear_wake_irq(&client->dev);
1094 device_init_wakeup(&client->dev, false);
1099 static void i2c_device_shutdown(struct device *dev)
1101 struct i2c_client *client = i2c_verify_client(dev);
1102 struct i2c_driver *driver;
1104 if (!client || !dev->driver)
1106 driver = to_i2c_driver(dev->driver);
1107 if (driver->shutdown)
1108 driver->shutdown(client);
1111 static void i2c_client_dev_release(struct device *dev)
1113 kfree(to_i2c_client(dev));
1117 show_name(struct device *dev, struct device_attribute *attr, char *buf)
1119 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
1120 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
1122 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
1125 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
1127 struct i2c_client *client = to_i2c_client(dev);
1130 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
1134 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
1136 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
1138 static struct attribute *i2c_dev_attrs[] = {
1139 &dev_attr_name.attr,
1140 /* modalias helps coldplug: modprobe $(cat .../modalias) */
1141 &dev_attr_modalias.attr,
1144 ATTRIBUTE_GROUPS(i2c_dev);
1146 struct bus_type i2c_bus_type = {
1148 .match = i2c_device_match,
1149 .probe = i2c_device_probe,
1150 .remove = i2c_device_remove,
1151 .shutdown = i2c_device_shutdown,
1153 EXPORT_SYMBOL_GPL(i2c_bus_type);
1155 struct device_type i2c_client_type = {
1156 .groups = i2c_dev_groups,
1157 .uevent = i2c_device_uevent,
1158 .release = i2c_client_dev_release,
1160 EXPORT_SYMBOL_GPL(i2c_client_type);
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));
1337 static int i2c_dev_irq_from_resources(const struct resource *resources,
1338 unsigned int num_resources)
1340 struct irq_data *irqd;
1343 for (i = 0; i < num_resources; i++) {
1344 const struct resource *r = &resources[i];
1346 if (resource_type(r) != IORESOURCE_IRQ)
1349 if (r->flags & IORESOURCE_BITS) {
1350 irqd = irq_get_irq_data(r->start);
1354 irqd_set_trigger_type(irqd, r->flags & IORESOURCE_BITS);
1364 * i2c_new_device - instantiate an i2c device
1365 * @adap: the adapter managing the device
1366 * @info: describes one I2C device; bus_num is ignored
1367 * Context: can sleep
1369 * Create an i2c device. Binding is handled through driver model
1370 * probe()/remove() methods. A driver may be bound to this device when we
1371 * return from this function, or any later moment (e.g. maybe hotplugging will
1372 * load the driver module). This call is not appropriate for use by mainboard
1373 * initialization logic, which usually runs during an arch_initcall() long
1374 * before any i2c_adapter could exist.
1376 * This returns the new i2c client, which may be saved for later use with
1377 * i2c_unregister_device(); or NULL to indicate an error.
1380 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1382 struct i2c_client *client;
1385 client = kzalloc(sizeof *client, GFP_KERNEL);
1389 client->adapter = adap;
1391 client->dev.platform_data = info->platform_data;
1394 client->dev.archdata = *info->archdata;
1396 client->flags = info->flags;
1397 client->addr = info->addr;
1399 client->irq = info->irq;
1401 client->irq = i2c_dev_irq_from_resources(info->resources,
1402 info->num_resources);
1404 strlcpy(client->name, info->type, sizeof(client->name));
1406 status = i2c_check_addr_validity(client->addr, client->flags);
1408 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1409 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1410 goto out_err_silent;
1413 /* Check for address business */
1414 status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
1418 client->dev.parent = &client->adapter->dev;
1419 client->dev.bus = &i2c_bus_type;
1420 client->dev.type = &i2c_client_type;
1421 client->dev.of_node = info->of_node;
1422 client->dev.fwnode = info->fwnode;
1424 i2c_dev_set_name(adap, client);
1426 if (info->properties) {
1427 status = device_add_properties(&client->dev, info->properties);
1430 "Failed to add properties to client %s: %d\n",
1431 client->name, status);
1436 status = device_register(&client->dev);
1438 goto out_free_props;
1440 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1441 client->name, dev_name(&client->dev));
1446 if (info->properties)
1447 device_remove_properties(&client->dev);
1450 "Failed to register i2c client %s at 0x%02x (%d)\n",
1451 client->name, client->addr, status);
1456 EXPORT_SYMBOL_GPL(i2c_new_device);
1460 * i2c_unregister_device - reverse effect of i2c_new_device()
1461 * @client: value returned from i2c_new_device()
1462 * Context: can sleep
1464 void i2c_unregister_device(struct i2c_client *client)
1466 if (client->dev.of_node)
1467 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
1468 if (ACPI_COMPANION(&client->dev))
1469 acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
1470 device_unregister(&client->dev);
1472 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1475 static const struct i2c_device_id dummy_id[] = {
1480 static int dummy_probe(struct i2c_client *client,
1481 const struct i2c_device_id *id)
1486 static int dummy_remove(struct i2c_client *client)
1491 static struct i2c_driver dummy_driver = {
1492 .driver.name = "dummy",
1493 .probe = dummy_probe,
1494 .remove = dummy_remove,
1495 .id_table = dummy_id,
1499 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1500 * @adapter: the adapter managing the device
1501 * @address: seven bit address to be used
1502 * Context: can sleep
1504 * This returns an I2C client bound to the "dummy" driver, intended for use
1505 * with devices that consume multiple addresses. Examples of such chips
1506 * include various EEPROMS (like 24c04 and 24c08 models).
1508 * These dummy devices have two main uses. First, most I2C and SMBus calls
1509 * except i2c_transfer() need a client handle; the dummy will be that handle.
1510 * And second, this prevents the specified address from being bound to a
1513 * This returns the new i2c client, which should be saved for later use with
1514 * i2c_unregister_device(); or NULL to indicate an error.
1516 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1518 struct i2c_board_info info = {
1519 I2C_BOARD_INFO("dummy", address),
1522 return i2c_new_device(adapter, &info);
1524 EXPORT_SYMBOL_GPL(i2c_new_dummy);
1527 * i2c_new_secondary_device - Helper to get the instantiated secondary address
1528 * and create the associated device
1529 * @client: Handle to the primary client
1530 * @name: Handle to specify which secondary address to get
1531 * @default_addr: Used as a fallback if no secondary address was specified
1532 * Context: can sleep
1534 * I2C clients can be composed of multiple I2C slaves bound together in a single
1535 * component. The I2C client driver then binds to the master I2C slave and needs
1536 * to create I2C dummy clients to communicate with all the other slaves.
1538 * This function creates and returns an I2C dummy client whose I2C address is
1539 * retrieved from the platform firmware based on the given slave name. If no
1540 * address is specified by the firmware default_addr is used.
1542 * On DT-based platforms the address is retrieved from the "reg" property entry
1543 * cell whose "reg-names" value matches the slave name.
1545 * This returns the new i2c client, which should be saved for later use with
1546 * i2c_unregister_device(); or NULL to indicate an error.
1548 struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
1552 struct device_node *np = client->dev.of_node;
1553 u32 addr = default_addr;
1557 i = of_property_match_string(np, "reg-names", name);
1559 of_property_read_u32_index(np, "reg", i, &addr);
1562 dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1563 return i2c_new_dummy(client->adapter, addr);
1565 EXPORT_SYMBOL_GPL(i2c_new_secondary_device);
1567 /* ------------------------------------------------------------------------- */
1569 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1571 static void i2c_adapter_dev_release(struct device *dev)
1573 struct i2c_adapter *adap = to_i2c_adapter(dev);
1574 complete(&adap->dev_released);
1577 unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1579 unsigned int depth = 0;
1581 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1584 WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
1585 "adapter depth exceeds lockdep subclass limit\n");
1589 EXPORT_SYMBOL_GPL(i2c_adapter_depth);
1592 * Let users instantiate I2C devices through sysfs. This can be used when
1593 * platform initialization code doesn't contain the proper data for
1594 * whatever reason. Also useful for drivers that do device detection and
1595 * detection fails, either because the device uses an unexpected address,
1596 * or this is a compatible device with different ID register values.
1598 * Parameter checking may look overzealous, but we really don't want
1599 * the user to provide incorrect parameters.
1602 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1603 const char *buf, size_t count)
1605 struct i2c_adapter *adap = to_i2c_adapter(dev);
1606 struct i2c_board_info info;
1607 struct i2c_client *client;
1611 memset(&info, 0, sizeof(struct i2c_board_info));
1613 blank = strchr(buf, ' ');
1615 dev_err(dev, "%s: Missing parameters\n", "new_device");
1618 if (blank - buf > I2C_NAME_SIZE - 1) {
1619 dev_err(dev, "%s: Invalid device name\n", "new_device");
1622 memcpy(info.type, buf, blank - buf);
1624 /* Parse remaining parameters, reject extra parameters */
1625 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1627 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1630 if (res > 1 && end != '\n') {
1631 dev_err(dev, "%s: Extra parameters\n", "new_device");
1635 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1636 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1637 info.flags |= I2C_CLIENT_TEN;
1640 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1641 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1642 info.flags |= I2C_CLIENT_SLAVE;
1645 client = i2c_new_device(adap, &info);
1649 /* Keep track of the added device */
1650 mutex_lock(&adap->userspace_clients_lock);
1651 list_add_tail(&client->detected, &adap->userspace_clients);
1652 mutex_unlock(&adap->userspace_clients_lock);
1653 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1654 info.type, info.addr);
1658 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1661 * And of course let the users delete the devices they instantiated, if
1662 * they got it wrong. This interface can only be used to delete devices
1663 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1664 * don't delete devices to which some kernel code still has references.
1666 * Parameter checking may look overzealous, but we really don't want
1667 * the user to delete the wrong device.
1670 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1671 const char *buf, size_t count)
1673 struct i2c_adapter *adap = to_i2c_adapter(dev);
1674 struct i2c_client *client, *next;
1675 unsigned short addr;
1679 /* Parse parameters, reject extra parameters */
1680 res = sscanf(buf, "%hi%c", &addr, &end);
1682 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1685 if (res > 1 && end != '\n') {
1686 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1690 /* Make sure the device was added through sysfs */
1692 mutex_lock_nested(&adap->userspace_clients_lock,
1693 i2c_adapter_depth(adap));
1694 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1696 if (i2c_encode_flags_to_addr(client) == addr) {
1697 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1698 "delete_device", client->name, client->addr);
1700 list_del(&client->detected);
1701 i2c_unregister_device(client);
1706 mutex_unlock(&adap->userspace_clients_lock);
1709 dev_err(dev, "%s: Can't find device in list\n",
1713 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1714 i2c_sysfs_delete_device);
1716 static struct attribute *i2c_adapter_attrs[] = {
1717 &dev_attr_name.attr,
1718 &dev_attr_new_device.attr,
1719 &dev_attr_delete_device.attr,
1722 ATTRIBUTE_GROUPS(i2c_adapter);
1724 struct device_type i2c_adapter_type = {
1725 .groups = i2c_adapter_groups,
1726 .release = i2c_adapter_dev_release,
1728 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1731 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1732 * @dev: device, probably from some driver model iterator
1734 * When traversing the driver model tree, perhaps using driver model
1735 * iterators like @device_for_each_child(), you can't assume very much
1736 * about the nodes you find. Use this function to avoid oopses caused
1737 * by wrongly treating some non-I2C device as an i2c_adapter.
1739 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1741 return (dev->type == &i2c_adapter_type)
1742 ? to_i2c_adapter(dev)
1745 EXPORT_SYMBOL(i2c_verify_adapter);
1747 #ifdef CONFIG_I2C_COMPAT
1748 static struct class_compat *i2c_adapter_compat_class;
1751 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1753 struct i2c_devinfo *devinfo;
1755 down_read(&__i2c_board_lock);
1756 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1757 if (devinfo->busnum == adapter->nr
1758 && !i2c_new_device(adapter,
1759 &devinfo->board_info))
1760 dev_err(&adapter->dev,
1761 "Can't create device at 0x%02x\n",
1762 devinfo->board_info.addr);
1764 up_read(&__i2c_board_lock);
1767 /* OF support code */
1769 #if IS_ENABLED(CONFIG_OF)
1770 static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1771 struct device_node *node)
1773 struct i2c_client *result;
1774 struct i2c_board_info info = {};
1775 struct dev_archdata dev_ad = {};
1776 const __be32 *addr_be;
1780 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1782 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1783 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1785 return ERR_PTR(-EINVAL);
1788 addr_be = of_get_property(node, "reg", &len);
1789 if (!addr_be || (len < sizeof(*addr_be))) {
1790 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1792 return ERR_PTR(-EINVAL);
1795 addr = be32_to_cpup(addr_be);
1796 if (addr & I2C_TEN_BIT_ADDRESS) {
1797 addr &= ~I2C_TEN_BIT_ADDRESS;
1798 info.flags |= I2C_CLIENT_TEN;
1801 if (addr & I2C_OWN_SLAVE_ADDRESS) {
1802 addr &= ~I2C_OWN_SLAVE_ADDRESS;
1803 info.flags |= I2C_CLIENT_SLAVE;
1806 if (i2c_check_addr_validity(addr, info.flags)) {
1807 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1808 addr, node->full_name);
1809 return ERR_PTR(-EINVAL);
1813 info.of_node = of_node_get(node);
1814 info.archdata = &dev_ad;
1816 if (of_property_read_bool(node, "host-notify"))
1817 info.flags |= I2C_CLIENT_HOST_NOTIFY;
1819 if (of_get_property(node, "wakeup-source", NULL))
1820 info.flags |= I2C_CLIENT_WAKE;
1822 result = i2c_new_device(adap, &info);
1823 if (result == NULL) {
1824 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1827 return ERR_PTR(-EINVAL);
1832 static void of_i2c_register_devices(struct i2c_adapter *adap)
1834 struct device_node *bus, *node;
1835 struct i2c_client *client;
1837 /* Only register child devices if the adapter has a node pointer set */
1838 if (!adap->dev.of_node)
1841 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1843 bus = of_get_child_by_name(adap->dev.of_node, "i2c-bus");
1845 bus = of_node_get(adap->dev.of_node);
1847 for_each_available_child_of_node(bus, node) {
1848 if (of_node_test_and_set_flag(node, OF_POPULATED))
1851 client = of_i2c_register_device(adap, node);
1852 if (IS_ERR(client)) {
1853 dev_warn(&adap->dev,
1854 "Failed to create I2C device for %s\n",
1856 of_node_clear_flag(node, OF_POPULATED);
1863 static int of_dev_node_match(struct device *dev, void *data)
1865 return dev->of_node == data;
1868 /* must call put_device() when done with returned i2c_client device */
1869 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1872 struct i2c_client *client;
1874 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1878 client = i2c_verify_client(dev);
1884 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1886 /* must call put_device() when done with returned i2c_adapter device */
1887 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1890 struct i2c_adapter *adapter;
1892 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1896 adapter = i2c_verify_adapter(dev);
1902 EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1904 /* must call i2c_put_adapter() when done with returned i2c_adapter device */
1905 struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1907 struct i2c_adapter *adapter;
1909 adapter = of_find_i2c_adapter_by_node(node);
1913 if (!try_module_get(adapter->owner)) {
1914 put_device(&adapter->dev);
1920 EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1922 static const struct of_device_id*
1923 i2c_of_match_device_sysfs(const struct of_device_id *matches,
1924 struct i2c_client *client)
1928 for (; matches->compatible[0]; matches++) {
1930 * Adding devices through the i2c sysfs interface provides us
1931 * a string to match which may be compatible with the device
1932 * tree compatible strings, however with no actual of_node the
1933 * of_match_device() will not match
1935 if (sysfs_streq(client->name, matches->compatible))
1938 name = strchr(matches->compatible, ',');
1940 name = matches->compatible;
1944 if (sysfs_streq(client->name, name))
1951 const struct of_device_id
1952 *i2c_of_match_device(const struct of_device_id *matches,
1953 struct i2c_client *client)
1955 const struct of_device_id *match;
1957 if (!(client && matches))
1960 match = of_match_device(matches, &client->dev);
1964 return i2c_of_match_device_sysfs(matches, client);
1966 EXPORT_SYMBOL_GPL(i2c_of_match_device);
1968 static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1969 #endif /* CONFIG_OF */
1971 static int i2c_do_add_adapter(struct i2c_driver *driver,
1972 struct i2c_adapter *adap)
1974 /* Detect supported devices on that bus, and instantiate them */
1975 i2c_detect(adap, driver);
1977 /* Let legacy drivers scan this bus for matching devices */
1978 if (driver->attach_adapter) {
1979 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1980 driver->driver.name);
1981 dev_warn(&adap->dev,
1982 "Please use another way to instantiate your i2c_client\n");
1983 /* We ignore the return code; if it fails, too bad */
1984 driver->attach_adapter(adap);
1989 static int __process_new_adapter(struct device_driver *d, void *data)
1991 return i2c_do_add_adapter(to_i2c_driver(d), data);
1994 static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1995 .lock_bus = i2c_adapter_lock_bus,
1996 .trylock_bus = i2c_adapter_trylock_bus,
1997 .unlock_bus = i2c_adapter_unlock_bus,
2000 static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
2002 struct irq_domain *domain = adap->host_notify_domain;
2003 irq_hw_number_t hwirq;
2008 for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
2009 irq_dispose_mapping(irq_find_mapping(domain, hwirq));
2011 irq_domain_remove(domain);
2012 adap->host_notify_domain = NULL;
2015 static int i2c_host_notify_irq_map(struct irq_domain *h,
2017 irq_hw_number_t hw_irq_num)
2019 irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
2024 static const struct irq_domain_ops i2c_host_notify_irq_ops = {
2025 .map = i2c_host_notify_irq_map,
2028 static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
2030 struct irq_domain *domain;
2032 if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
2035 domain = irq_domain_create_linear(adap->dev.fwnode,
2036 I2C_ADDR_7BITS_COUNT,
2037 &i2c_host_notify_irq_ops, adap);
2041 adap->host_notify_domain = domain;
2047 * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
2049 * @adap: the adapter
2050 * @addr: the I2C address of the notifying device
2051 * Context: can't sleep
2053 * Helper function to be called from an I2C bus driver's interrupt
2054 * handler. It will schedule the Host Notify IRQ.
2056 int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
2063 irq = irq_find_mapping(adap->host_notify_domain, addr);
2067 generic_handle_irq(irq);
2071 EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
2073 static int i2c_register_adapter(struct i2c_adapter *adap)
2077 /* Can't register until after driver model init */
2078 if (WARN_ON(!is_registered)) {
2084 if (WARN(!adap->name[0], "i2c adapter has no name"))
2088 pr_err("adapter '%s': no algo supplied!\n", adap->name);
2092 if (!adap->lock_ops)
2093 adap->lock_ops = &i2c_adapter_lock_ops;
2095 rt_mutex_init(&adap->bus_lock);
2096 rt_mutex_init(&adap->mux_lock);
2097 mutex_init(&adap->userspace_clients_lock);
2098 INIT_LIST_HEAD(&adap->userspace_clients);
2100 /* Set default timeout to 1 second if not already set */
2101 if (adap->timeout == 0)
2104 /* register soft irqs for Host Notify */
2105 res = i2c_setup_host_notify_irq_domain(adap);
2107 pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
2112 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
2113 adap->dev.bus = &i2c_bus_type;
2114 adap->dev.type = &i2c_adapter_type;
2115 res = device_register(&adap->dev);
2117 pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
2121 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
2123 pm_runtime_no_callbacks(&adap->dev);
2124 pm_suspend_ignore_children(&adap->dev, true);
2125 pm_runtime_enable(&adap->dev);
2127 #ifdef CONFIG_I2C_COMPAT
2128 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
2131 dev_warn(&adap->dev,
2132 "Failed to create compatibility class link\n");
2135 i2c_init_recovery(adap);
2137 /* create pre-declared device nodes */
2138 of_i2c_register_devices(adap);
2139 i2c_acpi_register_devices(adap);
2140 i2c_acpi_install_space_handler(adap);
2142 if (adap->nr < __i2c_first_dynamic_bus_num)
2143 i2c_scan_static_board_info(adap);
2145 /* Notify drivers */
2146 mutex_lock(&core_lock);
2147 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
2148 mutex_unlock(&core_lock);
2153 mutex_lock(&core_lock);
2154 idr_remove(&i2c_adapter_idr, adap->nr);
2155 mutex_unlock(&core_lock);
2160 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
2161 * @adap: the adapter to register (with adap->nr initialized)
2162 * Context: can sleep
2164 * See i2c_add_numbered_adapter() for details.
2166 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
2170 mutex_lock(&core_lock);
2171 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
2172 mutex_unlock(&core_lock);
2173 if (WARN(id < 0, "couldn't get idr"))
2174 return id == -ENOSPC ? -EBUSY : id;
2176 return i2c_register_adapter(adap);
2180 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
2181 * @adapter: the adapter to add
2182 * Context: can sleep
2184 * This routine is used to declare an I2C adapter when its bus number
2185 * doesn't matter or when its bus number is specified by an dt alias.
2186 * Examples of bases when the bus number doesn't matter: I2C adapters
2187 * dynamically added by USB links or PCI plugin cards.
2189 * When this returns zero, a new bus number was allocated and stored
2190 * in adap->nr, and the specified adapter became available for clients.
2191 * Otherwise, a negative errno value is returned.
2193 int i2c_add_adapter(struct i2c_adapter *adapter)
2195 struct device *dev = &adapter->dev;
2199 id = of_alias_get_id(dev->of_node, "i2c");
2202 return __i2c_add_numbered_adapter(adapter);
2206 mutex_lock(&core_lock);
2207 id = idr_alloc(&i2c_adapter_idr, adapter,
2208 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
2209 mutex_unlock(&core_lock);
2210 if (WARN(id < 0, "couldn't get idr"))
2215 return i2c_register_adapter(adapter);
2217 EXPORT_SYMBOL(i2c_add_adapter);
2220 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
2221 * @adap: the adapter to register (with adap->nr initialized)
2222 * Context: can sleep
2224 * This routine is used to declare an I2C adapter when its bus number
2225 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
2226 * or otherwise built in to the system's mainboard, and where i2c_board_info
2227 * is used to properly configure I2C devices.
2229 * If the requested bus number is set to -1, then this function will behave
2230 * identically to i2c_add_adapter, and will dynamically assign a bus number.
2232 * If no devices have pre-been declared for this bus, then be sure to
2233 * register the adapter before any dynamically allocated ones. Otherwise
2234 * the required bus ID may not be available.
2236 * When this returns zero, the specified adapter became available for
2237 * clients using the bus number provided in adap->nr. Also, the table
2238 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
2239 * and the appropriate driver model device nodes are created. Otherwise, a
2240 * negative errno value is returned.
2242 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
2244 if (adap->nr == -1) /* -1 means dynamically assign bus id */
2245 return i2c_add_adapter(adap);
2247 return __i2c_add_numbered_adapter(adap);
2249 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
2251 static void i2c_do_del_adapter(struct i2c_driver *driver,
2252 struct i2c_adapter *adapter)
2254 struct i2c_client *client, *_n;
2256 /* Remove the devices we created ourselves as the result of hardware
2257 * probing (using a driver's detect method) */
2258 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
2259 if (client->adapter == adapter) {
2260 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
2261 client->name, client->addr);
2262 list_del(&client->detected);
2263 i2c_unregister_device(client);
2268 static int __unregister_client(struct device *dev, void *dummy)
2270 struct i2c_client *client = i2c_verify_client(dev);
2271 if (client && strcmp(client->name, "dummy"))
2272 i2c_unregister_device(client);
2276 static int __unregister_dummy(struct device *dev, void *dummy)
2278 struct i2c_client *client = i2c_verify_client(dev);
2280 i2c_unregister_device(client);
2284 static int __process_removed_adapter(struct device_driver *d, void *data)
2286 i2c_do_del_adapter(to_i2c_driver(d), data);
2291 * i2c_del_adapter - unregister I2C adapter
2292 * @adap: the adapter being unregistered
2293 * Context: can sleep
2295 * This unregisters an I2C adapter which was previously registered
2296 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
2298 void i2c_del_adapter(struct i2c_adapter *adap)
2300 struct i2c_adapter *found;
2301 struct i2c_client *client, *next;
2303 /* First make sure that this adapter was ever added */
2304 mutex_lock(&core_lock);
2305 found = idr_find(&i2c_adapter_idr, adap->nr);
2306 mutex_unlock(&core_lock);
2307 if (found != adap) {
2308 pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
2312 i2c_acpi_remove_space_handler(adap);
2313 /* Tell drivers about this removal */
2314 mutex_lock(&core_lock);
2315 bus_for_each_drv(&i2c_bus_type, NULL, adap,
2316 __process_removed_adapter);
2317 mutex_unlock(&core_lock);
2319 /* Remove devices instantiated from sysfs */
2320 mutex_lock_nested(&adap->userspace_clients_lock,
2321 i2c_adapter_depth(adap));
2322 list_for_each_entry_safe(client, next, &adap->userspace_clients,
2324 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
2326 list_del(&client->detected);
2327 i2c_unregister_device(client);
2329 mutex_unlock(&adap->userspace_clients_lock);
2331 /* Detach any active clients. This can't fail, thus we do not
2332 * check the returned value. This is a two-pass process, because
2333 * we can't remove the dummy devices during the first pass: they
2334 * could have been instantiated by real devices wishing to clean
2335 * them up properly, so we give them a chance to do that first. */
2336 device_for_each_child(&adap->dev, NULL, __unregister_client);
2337 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
2339 #ifdef CONFIG_I2C_COMPAT
2340 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
2344 /* device name is gone after device_unregister */
2345 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
2347 pm_runtime_disable(&adap->dev);
2349 i2c_host_notify_irq_teardown(adap);
2351 /* wait until all references to the device are gone
2353 * FIXME: This is old code and should ideally be replaced by an
2354 * alternative which results in decoupling the lifetime of the struct
2355 * device from the i2c_adapter, like spi or netdev do. Any solution
2356 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
2358 init_completion(&adap->dev_released);
2359 device_unregister(&adap->dev);
2360 wait_for_completion(&adap->dev_released);
2363 mutex_lock(&core_lock);
2364 idr_remove(&i2c_adapter_idr, adap->nr);
2365 mutex_unlock(&core_lock);
2367 /* Clear the device structure in case this adapter is ever going to be
2369 memset(&adap->dev, 0, sizeof(adap->dev));
2371 EXPORT_SYMBOL(i2c_del_adapter);
2374 * i2c_parse_fw_timings - get I2C related timing parameters from firmware
2375 * @dev: The device to scan for I2C timing properties
2376 * @t: the i2c_timings struct to be filled with values
2377 * @use_defaults: bool to use sane defaults derived from the I2C specification
2378 * when properties are not found, otherwise use 0
2380 * Scan the device for the generic I2C properties describing timing parameters
2381 * for the signal and fill the given struct with the results. If a property was
2382 * not found and use_defaults was true, then maximum timings are assumed which
2383 * are derived from the I2C specification. If use_defaults is not used, the
2384 * results will be 0, so drivers can apply their own defaults later. The latter
2385 * is mainly intended for avoiding regressions of existing drivers which want
2386 * to switch to this function. New drivers almost always should use the defaults.
2389 void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
2393 memset(t, 0, sizeof(*t));
2395 ret = device_property_read_u32(dev, "clock-frequency", &t->bus_freq_hz);
2396 if (ret && use_defaults)
2397 t->bus_freq_hz = 100000;
2399 ret = device_property_read_u32(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns);
2400 if (ret && use_defaults) {
2401 if (t->bus_freq_hz <= 100000)
2402 t->scl_rise_ns = 1000;
2403 else if (t->bus_freq_hz <= 400000)
2404 t->scl_rise_ns = 300;
2406 t->scl_rise_ns = 120;
2409 ret = device_property_read_u32(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns);
2410 if (ret && use_defaults) {
2411 if (t->bus_freq_hz <= 400000)
2412 t->scl_fall_ns = 300;
2414 t->scl_fall_ns = 120;
2417 device_property_read_u32(dev, "i2c-scl-internal-delay-ns", &t->scl_int_delay_ns);
2419 ret = device_property_read_u32(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns);
2420 if (ret && use_defaults)
2421 t->sda_fall_ns = t->scl_fall_ns;
2423 EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
2425 /* ------------------------------------------------------------------------- */
2427 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
2431 mutex_lock(&core_lock);
2432 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
2433 mutex_unlock(&core_lock);
2437 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
2439 static int __process_new_driver(struct device *dev, void *data)
2441 if (dev->type != &i2c_adapter_type)
2443 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
2447 * An i2c_driver is used with one or more i2c_client (device) nodes to access
2448 * i2c slave chips, on a bus instance associated with some i2c_adapter.
2451 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
2455 /* Can't register until after driver model init */
2456 if (WARN_ON(!is_registered))
2459 /* add the driver to the list of i2c drivers in the driver core */
2460 driver->driver.owner = owner;
2461 driver->driver.bus = &i2c_bus_type;
2462 INIT_LIST_HEAD(&driver->clients);
2464 /* When registration returns, the driver core
2465 * will have called probe() for all matching-but-unbound devices.
2467 res = driver_register(&driver->driver);
2471 pr_debug("driver [%s] registered\n", driver->driver.name);
2473 /* Walk the adapters that are already present */
2474 i2c_for_each_dev(driver, __process_new_driver);
2478 EXPORT_SYMBOL(i2c_register_driver);
2480 static int __process_removed_driver(struct device *dev, void *data)
2482 if (dev->type == &i2c_adapter_type)
2483 i2c_do_del_adapter(data, to_i2c_adapter(dev));
2488 * i2c_del_driver - unregister I2C driver
2489 * @driver: the driver being unregistered
2490 * Context: can sleep
2492 void i2c_del_driver(struct i2c_driver *driver)
2494 i2c_for_each_dev(driver, __process_removed_driver);
2496 driver_unregister(&driver->driver);
2497 pr_debug("driver [%s] unregistered\n", driver->driver.name);
2499 EXPORT_SYMBOL(i2c_del_driver);
2501 /* ------------------------------------------------------------------------- */
2504 * i2c_use_client - increments the reference count of the i2c client structure
2505 * @client: the client being referenced
2507 * Each live reference to a client should be refcounted. The driver model does
2508 * that automatically as part of driver binding, so that most drivers don't
2509 * need to do this explicitly: they hold a reference until they're unbound
2512 * A pointer to the client with the incremented reference counter is returned.
2514 struct i2c_client *i2c_use_client(struct i2c_client *client)
2516 if (client && get_device(&client->dev))
2520 EXPORT_SYMBOL(i2c_use_client);
2523 * i2c_release_client - release a use of the i2c client structure
2524 * @client: the client being no longer referenced
2526 * Must be called when a user of a client is finished with it.
2528 void i2c_release_client(struct i2c_client *client)
2531 put_device(&client->dev);
2533 EXPORT_SYMBOL(i2c_release_client);
2535 struct i2c_cmd_arg {
2540 static int i2c_cmd(struct device *dev, void *_arg)
2542 struct i2c_client *client = i2c_verify_client(dev);
2543 struct i2c_cmd_arg *arg = _arg;
2544 struct i2c_driver *driver;
2546 if (!client || !client->dev.driver)
2549 driver = to_i2c_driver(client->dev.driver);
2550 if (driver->command)
2551 driver->command(client, arg->cmd, arg->arg);
2555 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
2557 struct i2c_cmd_arg cmd_arg;
2561 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
2563 EXPORT_SYMBOL(i2c_clients_command);
2565 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
2566 static int of_i2c_notify(struct notifier_block *nb, unsigned long action,
2569 struct of_reconfig_data *rd = arg;
2570 struct i2c_adapter *adap;
2571 struct i2c_client *client;
2573 switch (of_reconfig_get_state_change(action, rd)) {
2574 case OF_RECONFIG_CHANGE_ADD:
2575 adap = of_find_i2c_adapter_by_node(rd->dn->parent);
2577 return NOTIFY_OK; /* not for us */
2579 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
2580 put_device(&adap->dev);
2584 client = of_i2c_register_device(adap, rd->dn);
2585 put_device(&adap->dev);
2587 if (IS_ERR(client)) {
2588 dev_err(&adap->dev, "failed to create client for '%s'\n",
2590 of_node_clear_flag(rd->dn, OF_POPULATED);
2591 return notifier_from_errno(PTR_ERR(client));
2594 case OF_RECONFIG_CHANGE_REMOVE:
2595 /* already depopulated? */
2596 if (!of_node_check_flag(rd->dn, OF_POPULATED))
2599 /* find our device by node */
2600 client = of_find_i2c_device_by_node(rd->dn);
2602 return NOTIFY_OK; /* no? not meant for us */
2604 /* unregister takes one ref away */
2605 i2c_unregister_device(client);
2607 /* and put the reference of the find */
2608 put_device(&client->dev);
2614 static struct notifier_block i2c_of_notifier = {
2615 .notifier_call = of_i2c_notify,
2618 extern struct notifier_block i2c_of_notifier;
2619 #endif /* CONFIG_OF_DYNAMIC */
2621 static int __init i2c_init(void)
2625 retval = of_alias_get_highest_id("i2c");
2627 down_write(&__i2c_board_lock);
2628 if (retval >= __i2c_first_dynamic_bus_num)
2629 __i2c_first_dynamic_bus_num = retval + 1;
2630 up_write(&__i2c_board_lock);
2632 retval = bus_register(&i2c_bus_type);
2636 is_registered = true;
2638 #ifdef CONFIG_I2C_COMPAT
2639 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
2640 if (!i2c_adapter_compat_class) {
2645 retval = i2c_add_driver(&dummy_driver);
2649 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2650 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
2651 if (IS_ENABLED(CONFIG_ACPI))
2652 WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
2657 #ifdef CONFIG_I2C_COMPAT
2658 class_compat_unregister(i2c_adapter_compat_class);
2661 is_registered = false;
2662 bus_unregister(&i2c_bus_type);
2666 static void __exit i2c_exit(void)
2668 if (IS_ENABLED(CONFIG_ACPI))
2669 WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
2670 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2671 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
2672 i2c_del_driver(&dummy_driver);
2673 #ifdef CONFIG_I2C_COMPAT
2674 class_compat_unregister(i2c_adapter_compat_class);
2676 bus_unregister(&i2c_bus_type);
2677 tracepoint_synchronize_unregister();
2680 /* We must initialize early, because some subsystems register i2c drivers
2681 * in subsys_initcall() code, but are linked (and initialized) before i2c.
2683 postcore_initcall(i2c_init);
2684 module_exit(i2c_exit);
2686 /* ----------------------------------------------------
2687 * the functional interface to the i2c busses.
2688 * ----------------------------------------------------
2691 /* Check if val is exceeding the quirk IFF quirk is non 0 */
2692 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2694 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2696 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2697 err_msg, msg->addr, msg->len,
2698 msg->flags & I2C_M_RD ? "read" : "write");
2702 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2704 const struct i2c_adapter_quirks *q = adap->quirks;
2705 int max_num = q->max_num_msgs, i;
2706 bool do_len_check = true;
2708 if (q->flags & I2C_AQ_COMB) {
2711 /* special checks for combined messages */
2713 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2714 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2716 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2717 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2719 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2720 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2722 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2723 return i2c_quirk_error(adap, &msgs[0], "msg too long");
2725 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2726 return i2c_quirk_error(adap, &msgs[1], "msg too long");
2728 do_len_check = false;
2732 if (i2c_quirk_exceeded(num, max_num))
2733 return i2c_quirk_error(adap, &msgs[0], "too many messages");
2735 for (i = 0; i < num; i++) {
2736 u16 len = msgs[i].len;
2738 if (msgs[i].flags & I2C_M_RD) {
2739 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2740 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2742 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2743 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2751 * __i2c_transfer - unlocked flavor of i2c_transfer
2752 * @adap: Handle to I2C bus
2753 * @msgs: One or more messages to execute before STOP is issued to
2754 * terminate the operation; each message begins with a START.
2755 * @num: Number of messages to be executed.
2757 * Returns negative errno, else the number of messages executed.
2759 * Adapter lock must be held when calling this function. No debug logging
2760 * takes place. adap->algo->master_xfer existence isn't checked.
2762 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2764 unsigned long orig_jiffies;
2767 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2770 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2771 * enabled. This is an efficient way of keeping the for-loop from
2772 * being executed when not needed.
2774 if (static_key_false(&i2c_trace_msg)) {
2776 for (i = 0; i < num; i++)
2777 if (msgs[i].flags & I2C_M_RD)
2778 trace_i2c_read(adap, &msgs[i], i);
2780 trace_i2c_write(adap, &msgs[i], i);
2783 /* Retry automatically on arbitration loss */
2784 orig_jiffies = jiffies;
2785 for (ret = 0, try = 0; try <= adap->retries; try++) {
2786 ret = adap->algo->master_xfer(adap, msgs, num);
2789 if (time_after(jiffies, orig_jiffies + adap->timeout))
2793 if (static_key_false(&i2c_trace_msg)) {
2795 for (i = 0; i < ret; i++)
2796 if (msgs[i].flags & I2C_M_RD)
2797 trace_i2c_reply(adap, &msgs[i], i);
2798 trace_i2c_result(adap, i, ret);
2803 EXPORT_SYMBOL(__i2c_transfer);
2806 * i2c_transfer - execute a single or combined I2C message
2807 * @adap: Handle to I2C bus
2808 * @msgs: One or more messages to execute before STOP is issued to
2809 * terminate the operation; each message begins with a START.
2810 * @num: Number of messages to be executed.
2812 * Returns negative errno, else the number of messages executed.
2814 * Note that there is no requirement that each message be sent to
2815 * the same slave address, although that is the most common model.
2817 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2821 /* REVISIT the fault reporting model here is weak:
2823 * - When we get an error after receiving N bytes from a slave,
2824 * there is no way to report "N".
2826 * - When we get a NAK after transmitting N bytes to a slave,
2827 * there is no way to report "N" ... or to let the master
2828 * continue executing the rest of this combined message, if
2829 * that's the appropriate response.
2831 * - When for example "num" is two and we successfully complete
2832 * the first message but get an error part way through the
2833 * second, it's unclear whether that should be reported as
2834 * one (discarding status on the second message) or errno
2835 * (discarding status on the first one).
2838 if (adap->algo->master_xfer) {
2840 for (ret = 0; ret < num; ret++) {
2842 "master_xfer[%d] %c, addr=0x%02x, len=%d%s\n",
2843 ret, (msgs[ret].flags & I2C_M_RD) ? 'R' : 'W',
2844 msgs[ret].addr, msgs[ret].len,
2845 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2849 if (in_atomic() || irqs_disabled()) {
2850 ret = i2c_trylock_bus(adap, I2C_LOCK_SEGMENT);
2852 /* I2C activity is ongoing. */
2855 i2c_lock_bus(adap, I2C_LOCK_SEGMENT);
2858 ret = __i2c_transfer(adap, msgs, num);
2859 i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
2863 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2867 EXPORT_SYMBOL(i2c_transfer);
2870 * i2c_master_send - issue a single I2C message in master transmit mode
2871 * @client: Handle to slave device
2872 * @buf: Data that will be written to the slave
2873 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2875 * Returns negative errno, or else the number of bytes written.
2877 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2880 struct i2c_adapter *adap = client->adapter;
2883 msg.addr = client->addr;
2884 msg.flags = client->flags & I2C_M_TEN;
2886 msg.buf = (char *)buf;
2888 ret = i2c_transfer(adap, &msg, 1);
2891 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2892 * transmitted, else error code.
2894 return (ret == 1) ? count : ret;
2896 EXPORT_SYMBOL(i2c_master_send);
2899 * i2c_master_recv - issue a single I2C message in master receive mode
2900 * @client: Handle to slave device
2901 * @buf: Where to store data read from slave
2902 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2904 * Returns negative errno, or else the number of bytes read.
2906 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2908 struct i2c_adapter *adap = client->adapter;
2912 msg.addr = client->addr;
2913 msg.flags = client->flags & I2C_M_TEN;
2914 msg.flags |= I2C_M_RD;
2918 ret = i2c_transfer(adap, &msg, 1);
2921 * If everything went ok (i.e. 1 msg received), return #bytes received,
2924 return (ret == 1) ? count : ret;
2926 EXPORT_SYMBOL(i2c_master_recv);
2928 /* ----------------------------------------------------
2929 * the i2c address scanning function
2930 * Will not work for 10-bit addresses!
2931 * ----------------------------------------------------
2935 * Legacy default probe function, mostly relevant for SMBus. The default
2936 * probe method is a quick write, but it is known to corrupt the 24RF08
2937 * EEPROMs due to a state machine bug, and could also irreversibly
2938 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2939 * we use a short byte read instead. Also, some bus drivers don't implement
2940 * quick write, so we fallback to a byte read in that case too.
2941 * On x86, there is another special case for FSC hardware monitoring chips,
2942 * which want regular byte reads (address 0x73.) Fortunately, these are the
2943 * only known chips using this I2C address on PC hardware.
2944 * Returns 1 if probe succeeded, 0 if not.
2946 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2949 union i2c_smbus_data dummy;
2952 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2953 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2954 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2955 I2C_SMBUS_BYTE_DATA, &dummy);
2958 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2959 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2960 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2961 I2C_SMBUS_QUICK, NULL);
2962 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2963 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2964 I2C_SMBUS_BYTE, &dummy);
2966 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2974 static int i2c_detect_address(struct i2c_client *temp_client,
2975 struct i2c_driver *driver)
2977 struct i2c_board_info info;
2978 struct i2c_adapter *adapter = temp_client->adapter;
2979 int addr = temp_client->addr;
2982 /* Make sure the address is valid */
2983 err = i2c_check_7bit_addr_validity_strict(addr);
2985 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2990 /* Skip if already in use (7 bit, no need to encode flags) */
2991 if (i2c_check_addr_busy(adapter, addr))
2994 /* Make sure there is something at this address */
2995 if (!i2c_default_probe(adapter, addr))
2998 /* Finally call the custom detection function */
2999 memset(&info, 0, sizeof(struct i2c_board_info));
3001 err = driver->detect(temp_client, &info);
3003 /* -ENODEV is returned if the detection fails. We catch it
3004 here as this isn't an error. */
3005 return err == -ENODEV ? 0 : err;
3008 /* Consistency check */
3009 if (info.type[0] == '\0') {
3010 dev_err(&adapter->dev,
3011 "%s detection function provided no name for 0x%x\n",
3012 driver->driver.name, addr);
3014 struct i2c_client *client;
3016 /* Detection succeeded, instantiate the device */
3017 if (adapter->class & I2C_CLASS_DEPRECATED)
3018 dev_warn(&adapter->dev,
3019 "This adapter will soon drop class based instantiation of devices. "
3020 "Please make sure client 0x%02x gets instantiated by other means. "
3021 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
3024 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
3025 info.type, info.addr);
3026 client = i2c_new_device(adapter, &info);
3028 list_add_tail(&client->detected, &driver->clients);
3030 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
3031 info.type, info.addr);
3036 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
3038 const unsigned short *address_list;
3039 struct i2c_client *temp_client;
3041 int adap_id = i2c_adapter_id(adapter);
3043 address_list = driver->address_list;
3044 if (!driver->detect || !address_list)
3047 /* Warn that the adapter lost class based instantiation */
3048 if (adapter->class == I2C_CLASS_DEPRECATED) {
3049 dev_dbg(&adapter->dev,
3050 "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
3051 "If you need it, check 'Documentation/i2c/instantiating-devices' for alternatives.\n",
3052 driver->driver.name);
3056 /* Stop here if the classes do not match */
3057 if (!(adapter->class & driver->class))
3060 /* Set up a temporary client to help detect callback */
3061 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
3064 temp_client->adapter = adapter;
3066 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
3067 dev_dbg(&adapter->dev,
3068 "found normal entry for adapter %d, addr 0x%02x\n",
3069 adap_id, address_list[i]);
3070 temp_client->addr = address_list[i];
3071 err = i2c_detect_address(temp_client, driver);
3080 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
3082 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
3083 I2C_SMBUS_QUICK, NULL) >= 0;
3085 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
3088 i2c_new_probed_device(struct i2c_adapter *adap,
3089 struct i2c_board_info *info,
3090 unsigned short const *addr_list,
3091 int (*probe)(struct i2c_adapter *, unsigned short addr))
3096 probe = i2c_default_probe;
3098 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
3099 /* Check address validity */
3100 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
3101 dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
3106 /* Check address availability (7 bit, no need to encode flags) */
3107 if (i2c_check_addr_busy(adap, addr_list[i])) {
3109 "Address 0x%02x already in use, not probing\n",
3114 /* Test address responsiveness */
3115 if (probe(adap, addr_list[i]))
3119 if (addr_list[i] == I2C_CLIENT_END) {
3120 dev_dbg(&adap->dev, "Probing failed, no device found\n");
3124 info->addr = addr_list[i];
3125 return i2c_new_device(adap, info);
3127 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
3129 struct i2c_adapter *i2c_get_adapter(int nr)
3131 struct i2c_adapter *adapter;
3133 mutex_lock(&core_lock);
3134 adapter = idr_find(&i2c_adapter_idr, nr);
3138 if (try_module_get(adapter->owner))
3139 get_device(&adapter->dev);
3144 mutex_unlock(&core_lock);
3147 EXPORT_SYMBOL(i2c_get_adapter);
3149 void i2c_put_adapter(struct i2c_adapter *adap)
3154 put_device(&adap->dev);
3155 module_put(adap->owner);
3157 EXPORT_SYMBOL(i2c_put_adapter);
3159 /* The SMBus parts */
3161 #define POLY (0x1070U << 3)
3162 static u8 crc8(u16 data)
3166 for (i = 0; i < 8; i++) {
3171 return (u8)(data >> 8);
3174 /* Incremental CRC8 over count bytes in the array pointed to by p */
3175 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
3179 for (i = 0; i < count; i++)
3180 crc = crc8((crc ^ p[i]) << 8);
3184 /* Assume a 7-bit address, which is reasonable for SMBus */
3185 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
3187 /* The address will be sent first */
3188 u8 addr = i2c_8bit_addr_from_msg(msg);
3189 pec = i2c_smbus_pec(pec, &addr, 1);
3191 /* The data buffer follows */
3192 return i2c_smbus_pec(pec, msg->buf, msg->len);
3195 /* Used for write only transactions */
3196 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
3198 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
3202 /* Return <0 on CRC error
3203 If there was a write before this read (most cases) we need to take the
3204 partial CRC from the write part into account.
3205 Note that this function does modify the message (we need to decrease the
3206 message length to hide the CRC byte from the caller). */
3207 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
3209 u8 rpec = msg->buf[--msg->len];
3210 cpec = i2c_smbus_msg_pec(cpec, msg);
3213 pr_debug("Bad PEC 0x%02x vs. 0x%02x\n",
3221 * i2c_smbus_read_byte - SMBus "receive byte" protocol
3222 * @client: Handle to slave device
3224 * This executes the SMBus "receive byte" protocol, returning negative errno
3225 * else the byte received from the device.
3227 s32 i2c_smbus_read_byte(const struct i2c_client *client)
3229 union i2c_smbus_data data;
3232 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3234 I2C_SMBUS_BYTE, &data);
3235 return (status < 0) ? status : data.byte;
3237 EXPORT_SYMBOL(i2c_smbus_read_byte);
3240 * i2c_smbus_write_byte - SMBus "send byte" protocol
3241 * @client: Handle to slave device
3242 * @value: Byte to be sent
3244 * This executes the SMBus "send byte" protocol, returning negative errno
3245 * else zero on success.
3247 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
3249 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3250 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
3252 EXPORT_SYMBOL(i2c_smbus_write_byte);
3255 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
3256 * @client: Handle to slave device
3257 * @command: Byte interpreted by slave
3259 * This executes the SMBus "read byte" protocol, returning negative errno
3260 * else a data byte received from the device.
3262 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
3264 union i2c_smbus_data data;
3267 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3268 I2C_SMBUS_READ, command,
3269 I2C_SMBUS_BYTE_DATA, &data);
3270 return (status < 0) ? status : data.byte;
3272 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
3275 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
3276 * @client: Handle to slave device
3277 * @command: Byte interpreted by slave
3278 * @value: Byte being written
3280 * This executes the SMBus "write byte" protocol, returning negative errno
3281 * else zero on success.
3283 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
3286 union i2c_smbus_data data;
3288 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3289 I2C_SMBUS_WRITE, command,
3290 I2C_SMBUS_BYTE_DATA, &data);
3292 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
3295 * i2c_smbus_read_word_data - SMBus "read word" protocol
3296 * @client: Handle to slave device
3297 * @command: Byte interpreted by slave
3299 * This executes the SMBus "read word" protocol, returning negative errno
3300 * else a 16-bit unsigned "word" received from the device.
3302 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
3304 union i2c_smbus_data data;
3307 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3308 I2C_SMBUS_READ, command,
3309 I2C_SMBUS_WORD_DATA, &data);
3310 return (status < 0) ? status : data.word;
3312 EXPORT_SYMBOL(i2c_smbus_read_word_data);
3315 * i2c_smbus_write_word_data - SMBus "write word" protocol
3316 * @client: Handle to slave device
3317 * @command: Byte interpreted by slave
3318 * @value: 16-bit "word" being written
3320 * This executes the SMBus "write word" protocol, returning negative errno
3321 * else zero on success.
3323 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
3326 union i2c_smbus_data data;
3328 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3329 I2C_SMBUS_WRITE, command,
3330 I2C_SMBUS_WORD_DATA, &data);
3332 EXPORT_SYMBOL(i2c_smbus_write_word_data);
3335 * i2c_smbus_read_block_data - SMBus "block read" protocol
3336 * @client: Handle to slave device
3337 * @command: Byte interpreted by slave
3338 * @values: Byte array into which data will be read; big enough to hold
3339 * the data returned by the slave. SMBus allows at most 32 bytes.
3341 * This executes the SMBus "block read" protocol, returning negative errno
3342 * else the number of data bytes in the slave's response.
3344 * Note that using this function requires that the client's adapter support
3345 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
3346 * support this; its emulation through I2C messaging relies on a specific
3347 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
3349 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
3352 union i2c_smbus_data data;
3355 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3356 I2C_SMBUS_READ, command,
3357 I2C_SMBUS_BLOCK_DATA, &data);
3361 memcpy(values, &data.block[1], data.block[0]);
3362 return data.block[0];
3364 EXPORT_SYMBOL(i2c_smbus_read_block_data);
3367 * i2c_smbus_write_block_data - SMBus "block write" protocol
3368 * @client: Handle to slave device
3369 * @command: Byte interpreted by slave
3370 * @length: Size of data block; SMBus allows at most 32 bytes
3371 * @values: Byte array which will be written.
3373 * This executes the SMBus "block write" protocol, returning negative errno
3374 * else zero on success.
3376 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
3377 u8 length, const u8 *values)
3379 union i2c_smbus_data data;
3381 if (length > I2C_SMBUS_BLOCK_MAX)
3382 length = I2C_SMBUS_BLOCK_MAX;
3383 data.block[0] = length;
3384 memcpy(&data.block[1], values, length);
3385 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3386 I2C_SMBUS_WRITE, command,
3387 I2C_SMBUS_BLOCK_DATA, &data);
3389 EXPORT_SYMBOL(i2c_smbus_write_block_data);
3391 /* Returns the number of read bytes */
3392 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
3393 u8 length, u8 *values)
3395 union i2c_smbus_data data;
3398 if (length > I2C_SMBUS_BLOCK_MAX)
3399 length = I2C_SMBUS_BLOCK_MAX;
3400 data.block[0] = length;
3401 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3402 I2C_SMBUS_READ, command,
3403 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3407 memcpy(values, &data.block[1], data.block[0]);
3408 return data.block[0];
3410 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
3412 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
3413 u8 length, const u8 *values)
3415 union i2c_smbus_data data;
3417 if (length > I2C_SMBUS_BLOCK_MAX)
3418 length = I2C_SMBUS_BLOCK_MAX;
3419 data.block[0] = length;
3420 memcpy(data.block + 1, values, length);
3421 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3422 I2C_SMBUS_WRITE, command,
3423 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3425 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
3427 /* Simulate a SMBus command using the i2c protocol
3428 No checking of parameters is done! */
3429 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
3430 unsigned short flags,
3431 char read_write, u8 command, int size,
3432 union i2c_smbus_data *data)
3434 /* So we need to generate a series of msgs. In the case of writing, we
3435 need to use only one message; when reading, we need two. We initialize
3436 most things with sane defaults, to keep the code below somewhat
3438 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
3439 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
3440 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
3444 struct i2c_msg msg[2] = {
3452 .flags = flags | I2C_M_RD,
3458 msgbuf0[0] = command;
3460 case I2C_SMBUS_QUICK:
3462 /* Special case: The read/write field is used as data */
3463 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
3467 case I2C_SMBUS_BYTE:
3468 if (read_write == I2C_SMBUS_READ) {
3469 /* Special case: only a read! */
3470 msg[0].flags = I2C_M_RD | flags;
3474 case I2C_SMBUS_BYTE_DATA:
3475 if (read_write == I2C_SMBUS_READ)
3479 msgbuf0[1] = data->byte;
3482 case I2C_SMBUS_WORD_DATA:
3483 if (read_write == I2C_SMBUS_READ)
3487 msgbuf0[1] = data->word & 0xff;
3488 msgbuf0[2] = data->word >> 8;
3491 case I2C_SMBUS_PROC_CALL:
3492 num = 2; /* Special case */
3493 read_write = I2C_SMBUS_READ;
3496 msgbuf0[1] = data->word & 0xff;
3497 msgbuf0[2] = data->word >> 8;
3499 case I2C_SMBUS_BLOCK_DATA:
3500 if (read_write == I2C_SMBUS_READ) {
3501 msg[1].flags |= I2C_M_RECV_LEN;
3502 msg[1].len = 1; /* block length will be added by
3503 the underlying bus driver */
3505 msg[0].len = data->block[0] + 2;
3506 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
3507 dev_err(&adapter->dev,
3508 "Invalid block write size %d\n",
3512 for (i = 1; i < msg[0].len; i++)
3513 msgbuf0[i] = data->block[i-1];
3516 case I2C_SMBUS_BLOCK_PROC_CALL:
3517 num = 2; /* Another special case */
3518 read_write = I2C_SMBUS_READ;
3519 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
3520 dev_err(&adapter->dev,
3521 "Invalid block write size %d\n",
3525 msg[0].len = data->block[0] + 2;
3526 for (i = 1; i < msg[0].len; i++)
3527 msgbuf0[i] = data->block[i-1];
3528 msg[1].flags |= I2C_M_RECV_LEN;
3529 msg[1].len = 1; /* block length will be added by
3530 the underlying bus driver */
3532 case I2C_SMBUS_I2C_BLOCK_DATA:
3533 if (read_write == I2C_SMBUS_READ) {
3534 msg[1].len = data->block[0];
3536 msg[0].len = data->block[0] + 1;
3537 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
3538 dev_err(&adapter->dev,
3539 "Invalid block write size %d\n",
3543 for (i = 1; i <= data->block[0]; i++)
3544 msgbuf0[i] = data->block[i];
3548 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
3552 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
3553 && size != I2C_SMBUS_I2C_BLOCK_DATA);
3555 /* Compute PEC if first message is a write */
3556 if (!(msg[0].flags & I2C_M_RD)) {
3557 if (num == 1) /* Write only */
3558 i2c_smbus_add_pec(&msg[0]);
3559 else /* Write followed by read */
3560 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
3562 /* Ask for PEC if last message is a read */
3563 if (msg[num-1].flags & I2C_M_RD)
3567 status = i2c_transfer(adapter, msg, num);
3571 /* Check PEC if last message is a read */
3572 if (i && (msg[num-1].flags & I2C_M_RD)) {
3573 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
3578 if (read_write == I2C_SMBUS_READ)
3580 case I2C_SMBUS_BYTE:
3581 data->byte = msgbuf0[0];
3583 case I2C_SMBUS_BYTE_DATA:
3584 data->byte = msgbuf1[0];
3586 case I2C_SMBUS_WORD_DATA:
3587 case I2C_SMBUS_PROC_CALL:
3588 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
3590 case I2C_SMBUS_I2C_BLOCK_DATA:
3591 for (i = 0; i < data->block[0]; i++)
3592 data->block[i+1] = msgbuf1[i];
3594 case I2C_SMBUS_BLOCK_DATA:
3595 case I2C_SMBUS_BLOCK_PROC_CALL:
3596 for (i = 0; i < msgbuf1[0] + 1; i++)
3597 data->block[i] = msgbuf1[i];
3604 * i2c_smbus_xfer - execute SMBus protocol operations
3605 * @adapter: Handle to I2C bus
3606 * @addr: Address of SMBus slave on that bus
3607 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
3608 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
3609 * @command: Byte interpreted by slave, for protocols which use such bytes
3610 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
3611 * @data: Data to be read or written
3613 * This executes an SMBus protocol operation, and returns a negative
3614 * errno code else zero on success.
3616 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
3617 char read_write, u8 command, int protocol,
3618 union i2c_smbus_data *data)
3620 unsigned long orig_jiffies;
3624 /* If enabled, the following two tracepoints are conditional on
3625 * read_write and protocol.
3627 trace_smbus_write(adapter, addr, flags, read_write,
3628 command, protocol, data);
3629 trace_smbus_read(adapter, addr, flags, read_write,
3632 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
3634 if (adapter->algo->smbus_xfer) {
3635 i2c_lock_bus(adapter, I2C_LOCK_SEGMENT);
3637 /* Retry automatically on arbitration loss */
3638 orig_jiffies = jiffies;
3639 for (res = 0, try = 0; try <= adapter->retries; try++) {
3640 res = adapter->algo->smbus_xfer(adapter, addr, flags,
3641 read_write, command,
3645 if (time_after(jiffies,
3646 orig_jiffies + adapter->timeout))
3649 i2c_unlock_bus(adapter, I2C_LOCK_SEGMENT);
3651 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
3654 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
3655 * implement native support for the SMBus operation.
3659 res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
3660 command, protocol, data);
3663 /* If enabled, the reply tracepoint is conditional on read_write. */
3664 trace_smbus_reply(adapter, addr, flags, read_write,
3665 command, protocol, data);
3666 trace_smbus_result(adapter, addr, flags, read_write,
3667 command, protocol, res);
3671 EXPORT_SYMBOL(i2c_smbus_xfer);
3674 * i2c_smbus_read_i2c_block_data_or_emulated - read block or emulate
3675 * @client: Handle to slave device
3676 * @command: Byte interpreted by slave
3677 * @length: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
3678 * @values: Byte array into which data will be read; big enough to hold
3679 * the data returned by the slave. SMBus allows at most
3680 * I2C_SMBUS_BLOCK_MAX bytes.
3682 * This executes the SMBus "block read" protocol if supported by the adapter.
3683 * If block read is not supported, it emulates it using either word or byte
3684 * read protocols depending on availability.
3686 * The addresses of the I2C slave device that are accessed with this function
3687 * must be mapped to a linear region, so that a block read will have the same
3688 * effect as a byte read. Before using this function you must double-check
3689 * if the I2C slave does support exchanging a block transfer with a byte
3692 s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client,
3693 u8 command, u8 length, u8 *values)
3698 if (length > I2C_SMBUS_BLOCK_MAX)
3699 length = I2C_SMBUS_BLOCK_MAX;
3701 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
3702 return i2c_smbus_read_i2c_block_data(client, command, length, values);
3704 if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA))
3707 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) {
3708 while ((i + 2) <= length) {
3709 status = i2c_smbus_read_word_data(client, command + i);
3712 values[i] = status & 0xff;
3713 values[i + 1] = status >> 8;
3718 while (i < length) {
3719 status = i2c_smbus_read_byte_data(client, command + i);
3728 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data_or_emulated);
3730 #if IS_ENABLED(CONFIG_I2C_SLAVE)
3731 int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
3735 if (!client || !slave_cb) {
3736 WARN(1, "insufficient data\n");
3740 if (!(client->flags & I2C_CLIENT_SLAVE))
3741 dev_warn(&client->dev, "%s: client slave flag not set. You might see address collisions\n",
3744 if (!(client->flags & I2C_CLIENT_TEN)) {
3745 /* Enforce stricter address checking */
3746 ret = i2c_check_7bit_addr_validity_strict(client->addr);
3748 dev_err(&client->dev, "%s: invalid address\n", __func__);
3753 if (!client->adapter->algo->reg_slave) {
3754 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3758 client->slave_cb = slave_cb;
3760 i2c_lock_adapter(client->adapter);
3761 ret = client->adapter->algo->reg_slave(client);
3762 i2c_unlock_adapter(client->adapter);
3765 client->slave_cb = NULL;
3766 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3771 EXPORT_SYMBOL_GPL(i2c_slave_register);
3773 int i2c_slave_unregister(struct i2c_client *client)
3777 if (!client->adapter->algo->unreg_slave) {
3778 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3782 i2c_lock_adapter(client->adapter);
3783 ret = client->adapter->algo->unreg_slave(client);
3784 i2c_unlock_adapter(client->adapter);
3787 client->slave_cb = NULL;
3789 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3793 EXPORT_SYMBOL_GPL(i2c_slave_unregister);
3796 * i2c_detect_slave_mode - detect operation mode
3797 * @dev: The device owning the bus
3799 * This checks the device nodes for an I2C slave by checking the address
3800 * used in the reg property. If the address match the I2C_OWN_SLAVE_ADDRESS
3801 * flag this means the device is configured to act as a I2C slave and it will
3802 * be listening at that address.
3804 * Returns true if an I2C own slave address is detected, otherwise returns
3807 bool i2c_detect_slave_mode(struct device *dev)
3809 if (IS_BUILTIN(CONFIG_OF) && dev->of_node) {
3810 struct device_node *child;
3813 for_each_child_of_node(dev->of_node, child) {
3814 of_property_read_u32(child, "reg", ®);
3815 if (reg & I2C_OWN_SLAVE_ADDRESS) {
3820 } else if (IS_BUILTIN(CONFIG_ACPI) && ACPI_HANDLE(dev)) {
3821 dev_dbg(dev, "ACPI slave is not supported yet\n");
3825 EXPORT_SYMBOL_GPL(i2c_detect_slave_mode);
3829 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
3830 MODULE_DESCRIPTION("I2C-Bus main module");
3831 MODULE_LICENSE("GPL");