1 /* i2c-core.c - a device driver for the iic-bus interface */
2 /* ------------------------------------------------------------------------- */
3 /* Copyright (C) 1995-99 Simon G. Vogl
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details. */
14 /* ------------------------------------------------------------------------- */
16 /* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>.
17 All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
18 SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com> and
19 Jean Delvare <jdelvare@suse.de>
20 Mux support by Rodolfo Giometti <giometti@enneenne.com> and
21 Michael Lawnick <michael.lawnick.ext@nsn.com>
22 OF support is copyright (c) 2008 Jochen Friedrich <jochen@scram.de>
23 (based on a previous patch from Jon Smirl <jonsmirl@gmail.com>) and
24 (c) 2013 Wolfram Sang <wsa@the-dreams.de>
25 I2C ACPI code Copyright (C) 2014 Intel Corp
26 Author: Lan Tianyu <tianyu.lan@intel.com>
27 I2C slave support (c) 2014 by Wolfram Sang <wsa@sang-engineering.com>
30 #define pr_fmt(fmt) "i2c-core: " fmt
32 #include <dt-bindings/i2c/i2c.h>
33 #include <linux/uaccess.h>
34 #include <linux/acpi.h>
35 #include <linux/clk/clk-conf.h>
36 #include <linux/completion.h>
37 #include <linux/delay.h>
38 #include <linux/err.h>
39 #include <linux/errno.h>
40 #include <linux/gpio.h>
41 #include <linux/hardirq.h>
42 #include <linux/i2c.h>
43 #include <linux/idr.h>
44 #include <linux/init.h>
45 #include <linux/irqflags.h>
46 #include <linux/jump_label.h>
47 #include <linux/kernel.h>
48 #include <linux/module.h>
49 #include <linux/mutex.h>
50 #include <linux/of_device.h>
52 #include <linux/of_irq.h>
53 #include <linux/pm_domain.h>
54 #include <linux/pm_runtime.h>
55 #include <linux/pm_wakeirq.h>
56 #include <linux/property.h>
57 #include <linux/rwsem.h>
58 #include <linux/slab.h>
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/i2c.h>
65 #define I2C_ADDR_OFFSET_TEN_BIT 0xa000
66 #define I2C_ADDR_OFFSET_SLAVE 0x1000
68 #define I2C_ADDR_7BITS_MAX 0x77
69 #define I2C_ADDR_7BITS_COUNT (I2C_ADDR_7BITS_MAX + 1)
71 /* core_lock protects i2c_adapter_idr, and guarantees
72 that device detection, deletion of detected devices, and attach_adapter
73 calls are serialized */
74 static DEFINE_MUTEX(core_lock);
75 static DEFINE_IDR(i2c_adapter_idr);
77 static struct device_type i2c_client_type;
78 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
80 static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
81 static bool is_registered;
83 int i2c_transfer_trace_reg(void)
85 static_key_slow_inc(&i2c_trace_msg);
89 void i2c_transfer_trace_unreg(void)
91 static_key_slow_dec(&i2c_trace_msg);
94 #if defined(CONFIG_ACPI)
95 struct i2c_acpi_handler_data {
96 struct acpi_connection_info info;
97 struct i2c_adapter *adapter;
110 struct i2c_acpi_lookup {
111 struct i2c_board_info *info;
112 acpi_handle adapter_handle;
113 acpi_handle device_handle;
114 acpi_handle search_handle;
121 static int i2c_acpi_fill_info(struct acpi_resource *ares, void *data)
123 struct i2c_acpi_lookup *lookup = data;
124 struct i2c_board_info *info = lookup->info;
125 struct acpi_resource_i2c_serialbus *sb;
128 if (info->addr || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
131 sb = &ares->data.i2c_serial_bus;
132 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C)
135 if (lookup->index != -1 && lookup->n++ != lookup->index)
138 status = acpi_get_handle(lookup->device_handle,
139 sb->resource_source.string_ptr,
140 &lookup->adapter_handle);
141 if (!ACPI_SUCCESS(status))
144 info->addr = sb->slave_address;
145 lookup->speed = sb->connection_speed;
146 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
147 info->flags |= I2C_CLIENT_TEN;
152 static int i2c_acpi_do_lookup(struct acpi_device *adev,
153 struct i2c_acpi_lookup *lookup)
155 struct i2c_board_info *info = lookup->info;
156 struct list_head resource_list;
159 if (acpi_bus_get_status(adev) || !adev->status.present ||
160 acpi_device_enumerated(adev))
163 memset(info, 0, sizeof(*info));
164 lookup->device_handle = acpi_device_handle(adev);
166 /* Look up for I2cSerialBus resource */
167 INIT_LIST_HEAD(&resource_list);
168 ret = acpi_dev_get_resources(adev, &resource_list,
169 i2c_acpi_fill_info, lookup);
170 acpi_dev_free_resource_list(&resource_list);
172 if (ret < 0 || !info->addr)
178 static int i2c_acpi_get_info(struct acpi_device *adev,
179 struct i2c_board_info *info,
180 struct i2c_adapter *adapter,
181 acpi_handle *adapter_handle)
183 struct list_head resource_list;
184 struct resource_entry *entry;
185 struct i2c_acpi_lookup lookup;
188 memset(&lookup, 0, sizeof(lookup));
192 ret = i2c_acpi_do_lookup(adev, &lookup);
197 /* The adapter must match the one in I2cSerialBus() connector */
198 if (ACPI_HANDLE(&adapter->dev) != lookup.adapter_handle)
201 struct acpi_device *adapter_adev;
203 /* The adapter must be present */
204 if (acpi_bus_get_device(lookup.adapter_handle, &adapter_adev))
206 if (acpi_bus_get_status(adapter_adev) ||
207 !adapter_adev->status.present)
211 info->fwnode = acpi_fwnode_handle(adev);
213 *adapter_handle = lookup.adapter_handle;
215 /* Then fill IRQ number if any */
216 INIT_LIST_HEAD(&resource_list);
217 ret = acpi_dev_get_resources(adev, &resource_list, NULL, NULL);
221 resource_list_for_each_entry(entry, &resource_list) {
222 if (resource_type(entry->res) == IORESOURCE_IRQ) {
223 info->irq = entry->res->start;
228 acpi_dev_free_resource_list(&resource_list);
230 acpi_set_modalias(adev, dev_name(&adev->dev), info->type,
236 static void i2c_acpi_register_device(struct i2c_adapter *adapter,
237 struct acpi_device *adev,
238 struct i2c_board_info *info)
240 adev->power.flags.ignore_parent = true;
241 acpi_device_set_enumerated(adev);
243 if (!i2c_new_device(adapter, info)) {
244 adev->power.flags.ignore_parent = false;
245 dev_err(&adapter->dev,
246 "failed to add I2C device %s from ACPI\n",
247 dev_name(&adev->dev));
251 static acpi_status i2c_acpi_add_device(acpi_handle handle, u32 level,
252 void *data, void **return_value)
254 struct i2c_adapter *adapter = data;
255 struct acpi_device *adev;
256 struct i2c_board_info info;
258 if (acpi_bus_get_device(handle, &adev))
261 if (i2c_acpi_get_info(adev, &info, adapter, NULL))
264 i2c_acpi_register_device(adapter, adev, &info);
269 #define I2C_ACPI_MAX_SCAN_DEPTH 32
272 * i2c_acpi_register_devices - enumerate I2C slave devices behind adapter
273 * @adap: pointer to adapter
275 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
276 * namespace. When a device is found it will be added to the Linux device
277 * model and bound to the corresponding ACPI handle.
279 static void i2c_acpi_register_devices(struct i2c_adapter *adap)
283 if (!has_acpi_companion(&adap->dev))
286 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
287 I2C_ACPI_MAX_SCAN_DEPTH,
288 i2c_acpi_add_device, NULL,
290 if (ACPI_FAILURE(status))
291 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
294 static acpi_status i2c_acpi_lookup_speed(acpi_handle handle, u32 level,
295 void *data, void **return_value)
297 struct i2c_acpi_lookup *lookup = data;
298 struct acpi_device *adev;
300 if (acpi_bus_get_device(handle, &adev))
303 if (i2c_acpi_do_lookup(adev, lookup))
306 if (lookup->search_handle != lookup->adapter_handle)
309 if (lookup->speed <= lookup->min_speed)
310 lookup->min_speed = lookup->speed;
316 * i2c_acpi_find_bus_speed - find I2C bus speed from ACPI
317 * @dev: The device owning the bus
319 * Find the I2C bus speed by walking the ACPI namespace for all I2C slaves
320 * devices connected to this bus and use the speed of slowest device.
322 * Returns the speed in Hz or zero
324 u32 i2c_acpi_find_bus_speed(struct device *dev)
326 struct i2c_acpi_lookup lookup;
327 struct i2c_board_info dummy;
330 if (!has_acpi_companion(dev))
333 memset(&lookup, 0, sizeof(lookup));
334 lookup.search_handle = ACPI_HANDLE(dev);
335 lookup.min_speed = UINT_MAX;
336 lookup.info = &dummy;
339 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
340 I2C_ACPI_MAX_SCAN_DEPTH,
341 i2c_acpi_lookup_speed, NULL,
344 if (ACPI_FAILURE(status)) {
345 dev_warn(dev, "unable to find I2C bus speed from ACPI\n");
349 return lookup.min_speed != UINT_MAX ? lookup.min_speed : 0;
351 EXPORT_SYMBOL_GPL(i2c_acpi_find_bus_speed);
353 static int i2c_acpi_match_adapter(struct device *dev, void *data)
355 struct i2c_adapter *adapter = i2c_verify_adapter(dev);
360 return ACPI_HANDLE(dev) == (acpi_handle)data;
363 static int i2c_acpi_match_device(struct device *dev, void *data)
365 return ACPI_COMPANION(dev) == data;
368 static struct i2c_adapter *i2c_acpi_find_adapter_by_handle(acpi_handle handle)
372 dev = bus_find_device(&i2c_bus_type, NULL, handle,
373 i2c_acpi_match_adapter);
374 return dev ? i2c_verify_adapter(dev) : NULL;
377 static struct i2c_client *i2c_acpi_find_client_by_adev(struct acpi_device *adev)
381 dev = bus_find_device(&i2c_bus_type, NULL, adev, i2c_acpi_match_device);
382 return dev ? i2c_verify_client(dev) : NULL;
385 static int i2c_acpi_notify(struct notifier_block *nb, unsigned long value,
388 struct acpi_device *adev = arg;
389 struct i2c_board_info info;
390 acpi_handle adapter_handle;
391 struct i2c_adapter *adapter;
392 struct i2c_client *client;
395 case ACPI_RECONFIG_DEVICE_ADD:
396 if (i2c_acpi_get_info(adev, &info, NULL, &adapter_handle))
399 adapter = i2c_acpi_find_adapter_by_handle(adapter_handle);
403 i2c_acpi_register_device(adapter, adev, &info);
405 case ACPI_RECONFIG_DEVICE_REMOVE:
406 if (!acpi_device_enumerated(adev))
409 client = i2c_acpi_find_client_by_adev(adev);
413 i2c_unregister_device(client);
414 put_device(&client->dev);
421 static struct notifier_block i2c_acpi_notifier = {
422 .notifier_call = i2c_acpi_notify,
424 #else /* CONFIG_ACPI */
425 static inline void i2c_acpi_register_devices(struct i2c_adapter *adap) { }
426 extern struct notifier_block i2c_acpi_notifier;
427 #endif /* CONFIG_ACPI */
429 #ifdef CONFIG_ACPI_I2C_OPREGION
430 static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
431 u8 cmd, u8 *data, u8 data_len)
434 struct i2c_msg msgs[2];
438 buffer = kzalloc(data_len, GFP_KERNEL);
442 msgs[0].addr = client->addr;
443 msgs[0].flags = client->flags;
447 msgs[1].addr = client->addr;
448 msgs[1].flags = client->flags | I2C_M_RD;
449 msgs[1].len = data_len;
450 msgs[1].buf = buffer;
452 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
454 dev_err(&client->adapter->dev, "i2c read failed\n");
456 memcpy(data, buffer, data_len);
462 static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
463 u8 cmd, u8 *data, u8 data_len)
466 struct i2c_msg msgs[1];
470 buffer = kzalloc(data_len + 1, GFP_KERNEL);
475 memcpy(buffer + 1, data, data_len);
477 msgs[0].addr = client->addr;
478 msgs[0].flags = client->flags;
479 msgs[0].len = data_len + 1;
480 msgs[0].buf = buffer;
482 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
484 dev_err(&client->adapter->dev, "i2c write failed\n");
491 i2c_acpi_space_handler(u32 function, acpi_physical_address command,
492 u32 bits, u64 *value64,
493 void *handler_context, void *region_context)
495 struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
496 struct i2c_acpi_handler_data *data = handler_context;
497 struct acpi_connection_info *info = &data->info;
498 struct acpi_resource_i2c_serialbus *sb;
499 struct i2c_adapter *adapter = data->adapter;
500 struct i2c_client *client;
501 struct acpi_resource *ares;
502 u32 accessor_type = function >> 16;
503 u8 action = function & ACPI_IO_MASK;
507 ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
508 if (ACPI_FAILURE(ret))
511 client = kzalloc(sizeof(*client), GFP_KERNEL);
517 if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
518 ret = AE_BAD_PARAMETER;
522 sb = &ares->data.i2c_serial_bus;
523 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
524 ret = AE_BAD_PARAMETER;
528 client->adapter = adapter;
529 client->addr = sb->slave_address;
531 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
532 client->flags |= I2C_CLIENT_TEN;
534 switch (accessor_type) {
535 case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
536 if (action == ACPI_READ) {
537 status = i2c_smbus_read_byte(client);
543 status = i2c_smbus_write_byte(client, gsb->bdata);
547 case ACPI_GSB_ACCESS_ATTRIB_BYTE:
548 if (action == ACPI_READ) {
549 status = i2c_smbus_read_byte_data(client, command);
555 status = i2c_smbus_write_byte_data(client, command,
560 case ACPI_GSB_ACCESS_ATTRIB_WORD:
561 if (action == ACPI_READ) {
562 status = i2c_smbus_read_word_data(client, command);
568 status = i2c_smbus_write_word_data(client, command,
573 case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
574 if (action == ACPI_READ) {
575 status = i2c_smbus_read_block_data(client, command,
582 status = i2c_smbus_write_block_data(client, command,
583 gsb->len, gsb->data);
587 case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
588 if (action == ACPI_READ) {
589 status = acpi_gsb_i2c_read_bytes(client, command,
590 gsb->data, info->access_length);
594 status = acpi_gsb_i2c_write_bytes(client, command,
595 gsb->data, info->access_length);
600 dev_warn(&adapter->dev, "protocol 0x%02x not supported for client 0x%02x\n",
601 accessor_type, client->addr);
602 ret = AE_BAD_PARAMETER;
606 gsb->status = status;
615 static int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
618 struct i2c_acpi_handler_data *data;
621 if (!adapter->dev.parent)
624 handle = ACPI_HANDLE(adapter->dev.parent);
629 data = kzalloc(sizeof(struct i2c_acpi_handler_data),
634 data->adapter = adapter;
635 status = acpi_bus_attach_private_data(handle, (void *)data);
636 if (ACPI_FAILURE(status)) {
641 status = acpi_install_address_space_handler(handle,
642 ACPI_ADR_SPACE_GSBUS,
643 &i2c_acpi_space_handler,
646 if (ACPI_FAILURE(status)) {
647 dev_err(&adapter->dev, "Error installing i2c space handler\n");
648 acpi_bus_detach_private_data(handle);
653 acpi_walk_dep_device_list(handle);
657 static void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
660 struct i2c_acpi_handler_data *data;
663 if (!adapter->dev.parent)
666 handle = ACPI_HANDLE(adapter->dev.parent);
671 acpi_remove_address_space_handler(handle,
672 ACPI_ADR_SPACE_GSBUS,
673 &i2c_acpi_space_handler);
675 status = acpi_bus_get_private_data(handle, (void **)&data);
676 if (ACPI_SUCCESS(status))
679 acpi_bus_detach_private_data(handle);
681 #else /* CONFIG_ACPI_I2C_OPREGION */
682 static inline void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
685 static inline int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
687 #endif /* CONFIG_ACPI_I2C_OPREGION */
689 /* ------------------------------------------------------------------------- */
691 const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
692 const struct i2c_client *client)
697 while (id->name[0]) {
698 if (strcmp(client->name, id->name) == 0)
704 EXPORT_SYMBOL_GPL(i2c_match_id);
706 static int i2c_device_match(struct device *dev, struct device_driver *drv)
708 struct i2c_client *client = i2c_verify_client(dev);
709 struct i2c_driver *driver;
712 /* Attempt an OF style match */
713 if (i2c_of_match_device(drv->of_match_table, client))
716 /* Then ACPI style match */
717 if (acpi_driver_match_device(dev, drv))
720 driver = to_i2c_driver(drv);
722 /* Finally an I2C match */
723 if (i2c_match_id(driver->id_table, client))
729 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
731 struct i2c_client *client = to_i2c_client(dev);
734 rc = acpi_device_uevent_modalias(dev, env);
738 return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
741 /* i2c bus recovery routines */
742 static int get_scl_gpio_value(struct i2c_adapter *adap)
744 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
747 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
749 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
752 static int get_sda_gpio_value(struct i2c_adapter *adap)
754 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
757 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
759 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
760 struct device *dev = &adap->dev;
763 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
764 GPIOF_OUT_INIT_HIGH, "i2c-scl");
766 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
771 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
772 /* work without SDA polling */
773 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
782 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
784 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
787 gpio_free(bri->sda_gpio);
789 gpio_free(bri->scl_gpio);
793 * We are generating clock pulses. ndelay() determines durating of clk pulses.
794 * We will generate clock with rate 100 KHz and so duration of both clock levels
795 * is: delay in ns = (10^6 / 100) / 2
797 #define RECOVERY_NDELAY 5000
798 #define RECOVERY_CLK_CNT 9
800 static int i2c_generic_recovery(struct i2c_adapter *adap)
802 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
803 int i = 0, val = 1, ret = 0;
805 if (bri->prepare_recovery)
806 bri->prepare_recovery(adap);
808 bri->set_scl(adap, val);
809 ndelay(RECOVERY_NDELAY);
812 * By this time SCL is high, as we need to give 9 falling-rising edges
814 while (i++ < RECOVERY_CLK_CNT * 2) {
816 /* Break if SDA is high */
817 if (bri->get_sda && bri->get_sda(adap))
819 /* SCL shouldn't be low here */
820 if (!bri->get_scl(adap)) {
822 "SCL is stuck low, exit recovery\n");
829 bri->set_scl(adap, val);
830 ndelay(RECOVERY_NDELAY);
833 if (bri->unprepare_recovery)
834 bri->unprepare_recovery(adap);
839 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
841 return i2c_generic_recovery(adap);
843 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
845 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
849 ret = i2c_get_gpios_for_recovery(adap);
853 ret = i2c_generic_recovery(adap);
854 i2c_put_gpios_for_recovery(adap);
858 EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
860 int i2c_recover_bus(struct i2c_adapter *adap)
862 if (!adap->bus_recovery_info)
865 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
866 return adap->bus_recovery_info->recover_bus(adap);
868 EXPORT_SYMBOL_GPL(i2c_recover_bus);
870 static void i2c_init_recovery(struct i2c_adapter *adap)
872 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
878 if (!bri->recover_bus) {
879 err_str = "no recover_bus() found";
883 /* Generic GPIO recovery */
884 if (bri->recover_bus == i2c_generic_gpio_recovery) {
885 if (!gpio_is_valid(bri->scl_gpio)) {
886 err_str = "invalid SCL gpio";
890 if (gpio_is_valid(bri->sda_gpio))
891 bri->get_sda = get_sda_gpio_value;
895 bri->get_scl = get_scl_gpio_value;
896 bri->set_scl = set_scl_gpio_value;
897 } else if (bri->recover_bus == i2c_generic_scl_recovery) {
898 /* Generic SCL recovery */
899 if (!bri->set_scl || !bri->get_scl) {
900 err_str = "no {get|set}_scl() found";
907 dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
908 adap->bus_recovery_info = NULL;
911 static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
913 struct i2c_adapter *adap = client->adapter;
916 if (!adap->host_notify_domain)
919 if (client->flags & I2C_CLIENT_TEN)
922 irq = irq_find_mapping(adap->host_notify_domain, client->addr);
924 irq = irq_create_mapping(adap->host_notify_domain,
927 return irq > 0 ? irq : -ENXIO;
930 static int i2c_device_probe(struct device *dev)
932 struct i2c_client *client = i2c_verify_client(dev);
933 struct i2c_driver *driver;
942 if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
943 dev_dbg(dev, "Using Host Notify IRQ\n");
944 irq = i2c_smbus_host_notify_to_irq(client);
945 } else if (dev->of_node) {
946 irq = of_irq_get_byname(dev->of_node, "irq");
947 if (irq == -EINVAL || irq == -ENODATA)
948 irq = of_irq_get(dev->of_node, 0);
949 } else if (ACPI_COMPANION(dev)) {
950 irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
952 if (irq == -EPROBE_DEFER)
961 driver = to_i2c_driver(dev->driver);
964 * An I2C ID table is not mandatory, if and only if, a suitable Device
965 * Tree match table entry is supplied for the probing device.
967 if (!driver->id_table &&
968 !i2c_of_match_device(dev->driver->of_match_table, client))
971 if (client->flags & I2C_CLIENT_WAKE) {
972 int wakeirq = -ENOENT;
975 wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
976 if (wakeirq == -EPROBE_DEFER)
980 device_init_wakeup(&client->dev, true);
982 if (wakeirq > 0 && wakeirq != client->irq)
983 status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
984 else if (client->irq > 0)
985 status = dev_pm_set_wake_irq(dev, client->irq);
990 dev_warn(&client->dev, "failed to set up wakeup irq\n");
993 dev_dbg(dev, "probe\n");
995 status = of_clk_set_defaults(dev->of_node, false);
997 goto err_clear_wakeup_irq;
999 status = dev_pm_domain_attach(&client->dev, true);
1000 if (status == -EPROBE_DEFER)
1001 goto err_clear_wakeup_irq;
1004 * When there are no more users of probe(),
1005 * rename probe_new to probe.
1007 if (driver->probe_new)
1008 status = driver->probe_new(client);
1009 else if (driver->probe)
1010 status = driver->probe(client,
1011 i2c_match_id(driver->id_table, client));
1016 goto err_detach_pm_domain;
1020 err_detach_pm_domain:
1021 dev_pm_domain_detach(&client->dev, true);
1022 err_clear_wakeup_irq:
1023 dev_pm_clear_wake_irq(&client->dev);
1024 device_init_wakeup(&client->dev, false);
1028 static int i2c_device_remove(struct device *dev)
1030 struct i2c_client *client = i2c_verify_client(dev);
1031 struct i2c_driver *driver;
1034 if (!client || !dev->driver)
1037 driver = to_i2c_driver(dev->driver);
1038 if (driver->remove) {
1039 dev_dbg(dev, "remove\n");
1040 status = driver->remove(client);
1043 dev_pm_domain_detach(&client->dev, true);
1045 dev_pm_clear_wake_irq(&client->dev);
1046 device_init_wakeup(&client->dev, false);
1051 static void i2c_device_shutdown(struct device *dev)
1053 struct i2c_client *client = i2c_verify_client(dev);
1054 struct i2c_driver *driver;
1056 if (!client || !dev->driver)
1058 driver = to_i2c_driver(dev->driver);
1059 if (driver->shutdown)
1060 driver->shutdown(client);
1063 static void i2c_client_dev_release(struct device *dev)
1065 kfree(to_i2c_client(dev));
1069 show_name(struct device *dev, struct device_attribute *attr, char *buf)
1071 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
1072 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
1074 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
1077 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
1079 struct i2c_client *client = to_i2c_client(dev);
1082 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
1086 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
1088 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
1090 static struct attribute *i2c_dev_attrs[] = {
1091 &dev_attr_name.attr,
1092 /* modalias helps coldplug: modprobe $(cat .../modalias) */
1093 &dev_attr_modalias.attr,
1096 ATTRIBUTE_GROUPS(i2c_dev);
1098 struct bus_type i2c_bus_type = {
1100 .match = i2c_device_match,
1101 .probe = i2c_device_probe,
1102 .remove = i2c_device_remove,
1103 .shutdown = i2c_device_shutdown,
1105 EXPORT_SYMBOL_GPL(i2c_bus_type);
1107 static struct device_type i2c_client_type = {
1108 .groups = i2c_dev_groups,
1109 .uevent = i2c_device_uevent,
1110 .release = i2c_client_dev_release,
1115 * i2c_verify_client - return parameter as i2c_client, or NULL
1116 * @dev: device, probably from some driver model iterator
1118 * When traversing the driver model tree, perhaps using driver model
1119 * iterators like @device_for_each_child(), you can't assume very much
1120 * about the nodes you find. Use this function to avoid oopses caused
1121 * by wrongly treating some non-I2C device as an i2c_client.
1123 struct i2c_client *i2c_verify_client(struct device *dev)
1125 return (dev->type == &i2c_client_type)
1126 ? to_i2c_client(dev)
1129 EXPORT_SYMBOL(i2c_verify_client);
1132 /* Return a unique address which takes the flags of the client into account */
1133 static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
1135 unsigned short addr = client->addr;
1137 /* For some client flags, add an arbitrary offset to avoid collisions */
1138 if (client->flags & I2C_CLIENT_TEN)
1139 addr |= I2C_ADDR_OFFSET_TEN_BIT;
1141 if (client->flags & I2C_CLIENT_SLAVE)
1142 addr |= I2C_ADDR_OFFSET_SLAVE;
1147 /* This is a permissive address validity check, I2C address map constraints
1148 * are purposely not enforced, except for the general call address. */
1149 static int i2c_check_addr_validity(unsigned addr, unsigned short flags)
1151 if (flags & I2C_CLIENT_TEN) {
1152 /* 10-bit address, all values are valid */
1156 /* 7-bit address, reject the general call address */
1157 if (addr == 0x00 || addr > 0x7f)
1163 /* And this is a strict address validity check, used when probing. If a
1164 * device uses a reserved address, then it shouldn't be probed. 7-bit
1165 * addressing is assumed, 10-bit address devices are rare and should be
1166 * explicitly enumerated. */
1167 static int i2c_check_7bit_addr_validity_strict(unsigned short addr)
1170 * Reserved addresses per I2C specification:
1171 * 0x00 General call address / START byte
1173 * 0x02 Reserved for different bus format
1174 * 0x03 Reserved for future purposes
1175 * 0x04-0x07 Hs-mode master code
1176 * 0x78-0x7b 10-bit slave addressing
1177 * 0x7c-0x7f Reserved for future purposes
1179 if (addr < 0x08 || addr > 0x77)
1184 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
1186 struct i2c_client *client = i2c_verify_client(dev);
1187 int addr = *(int *)addrp;
1189 if (client && i2c_encode_flags_to_addr(client) == addr)
1194 /* walk up mux tree */
1195 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
1197 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1200 result = device_for_each_child(&adapter->dev, &addr,
1201 __i2c_check_addr_busy);
1203 if (!result && parent)
1204 result = i2c_check_mux_parents(parent, addr);
1209 /* recurse down mux tree */
1210 static int i2c_check_mux_children(struct device *dev, void *addrp)
1214 if (dev->type == &i2c_adapter_type)
1215 result = device_for_each_child(dev, addrp,
1216 i2c_check_mux_children);
1218 result = __i2c_check_addr_busy(dev, addrp);
1223 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
1225 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1229 result = i2c_check_mux_parents(parent, addr);
1232 result = device_for_each_child(&adapter->dev, &addr,
1233 i2c_check_mux_children);
1239 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
1240 * @adapter: Target I2C bus segment
1241 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
1242 * locks only this branch in the adapter tree
1244 static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
1247 rt_mutex_lock(&adapter->bus_lock);
1251 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
1252 * @adapter: Target I2C bus segment
1253 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
1254 * trylocks only this branch in the adapter tree
1256 static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
1259 return rt_mutex_trylock(&adapter->bus_lock);
1263 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
1264 * @adapter: Target I2C bus segment
1265 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
1266 * unlocks only this branch in the adapter tree
1268 static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
1271 rt_mutex_unlock(&adapter->bus_lock);
1274 static void i2c_dev_set_name(struct i2c_adapter *adap,
1275 struct i2c_client *client)
1277 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
1280 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
1284 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
1285 i2c_encode_flags_to_addr(client));
1289 * i2c_new_device - instantiate an i2c device
1290 * @adap: the adapter managing the device
1291 * @info: describes one I2C device; bus_num is ignored
1292 * Context: can sleep
1294 * Create an i2c device. Binding is handled through driver model
1295 * probe()/remove() methods. A driver may be bound to this device when we
1296 * return from this function, or any later moment (e.g. maybe hotplugging will
1297 * load the driver module). This call is not appropriate for use by mainboard
1298 * initialization logic, which usually runs during an arch_initcall() long
1299 * before any i2c_adapter could exist.
1301 * This returns the new i2c client, which may be saved for later use with
1302 * i2c_unregister_device(); or NULL to indicate an error.
1305 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1307 struct i2c_client *client;
1310 client = kzalloc(sizeof *client, GFP_KERNEL);
1314 client->adapter = adap;
1316 client->dev.platform_data = info->platform_data;
1319 client->dev.archdata = *info->archdata;
1321 client->flags = info->flags;
1322 client->addr = info->addr;
1323 client->irq = info->irq;
1325 strlcpy(client->name, info->type, sizeof(client->name));
1327 status = i2c_check_addr_validity(client->addr, client->flags);
1329 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1330 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1331 goto out_err_silent;
1334 /* Check for address business */
1335 status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
1339 client->dev.parent = &client->adapter->dev;
1340 client->dev.bus = &i2c_bus_type;
1341 client->dev.type = &i2c_client_type;
1342 client->dev.of_node = info->of_node;
1343 client->dev.fwnode = info->fwnode;
1345 i2c_dev_set_name(adap, client);
1347 if (info->properties) {
1348 status = device_add_properties(&client->dev, info->properties);
1351 "Failed to add properties to client %s: %d\n",
1352 client->name, status);
1357 status = device_register(&client->dev);
1359 goto out_free_props;
1361 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1362 client->name, dev_name(&client->dev));
1367 if (info->properties)
1368 device_remove_properties(&client->dev);
1371 "Failed to register i2c client %s at 0x%02x (%d)\n",
1372 client->name, client->addr, status);
1377 EXPORT_SYMBOL_GPL(i2c_new_device);
1381 * i2c_unregister_device - reverse effect of i2c_new_device()
1382 * @client: value returned from i2c_new_device()
1383 * Context: can sleep
1385 void i2c_unregister_device(struct i2c_client *client)
1387 if (client->dev.of_node)
1388 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
1389 if (ACPI_COMPANION(&client->dev))
1390 acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
1391 device_unregister(&client->dev);
1393 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1396 static const struct i2c_device_id dummy_id[] = {
1401 static int dummy_probe(struct i2c_client *client,
1402 const struct i2c_device_id *id)
1407 static int dummy_remove(struct i2c_client *client)
1412 static struct i2c_driver dummy_driver = {
1413 .driver.name = "dummy",
1414 .probe = dummy_probe,
1415 .remove = dummy_remove,
1416 .id_table = dummy_id,
1420 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1421 * @adapter: the adapter managing the device
1422 * @address: seven bit address to be used
1423 * Context: can sleep
1425 * This returns an I2C client bound to the "dummy" driver, intended for use
1426 * with devices that consume multiple addresses. Examples of such chips
1427 * include various EEPROMS (like 24c04 and 24c08 models).
1429 * These dummy devices have two main uses. First, most I2C and SMBus calls
1430 * except i2c_transfer() need a client handle; the dummy will be that handle.
1431 * And second, this prevents the specified address from being bound to a
1434 * This returns the new i2c client, which should be saved for later use with
1435 * i2c_unregister_device(); or NULL to indicate an error.
1437 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1439 struct i2c_board_info info = {
1440 I2C_BOARD_INFO("dummy", address),
1443 return i2c_new_device(adapter, &info);
1445 EXPORT_SYMBOL_GPL(i2c_new_dummy);
1448 * i2c_new_secondary_device - Helper to get the instantiated secondary address
1449 * and create the associated device
1450 * @client: Handle to the primary client
1451 * @name: Handle to specify which secondary address to get
1452 * @default_addr: Used as a fallback if no secondary address was specified
1453 * Context: can sleep
1455 * I2C clients can be composed of multiple I2C slaves bound together in a single
1456 * component. The I2C client driver then binds to the master I2C slave and needs
1457 * to create I2C dummy clients to communicate with all the other slaves.
1459 * This function creates and returns an I2C dummy client whose I2C address is
1460 * retrieved from the platform firmware based on the given slave name. If no
1461 * address is specified by the firmware default_addr is used.
1463 * On DT-based platforms the address is retrieved from the "reg" property entry
1464 * cell whose "reg-names" value matches the slave name.
1466 * This returns the new i2c client, which should be saved for later use with
1467 * i2c_unregister_device(); or NULL to indicate an error.
1469 struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
1473 struct device_node *np = client->dev.of_node;
1474 u32 addr = default_addr;
1478 i = of_property_match_string(np, "reg-names", name);
1480 of_property_read_u32_index(np, "reg", i, &addr);
1483 dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1484 return i2c_new_dummy(client->adapter, addr);
1486 EXPORT_SYMBOL_GPL(i2c_new_secondary_device);
1488 /* ------------------------------------------------------------------------- */
1490 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1492 static void i2c_adapter_dev_release(struct device *dev)
1494 struct i2c_adapter *adap = to_i2c_adapter(dev);
1495 complete(&adap->dev_released);
1498 unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1500 unsigned int depth = 0;
1502 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1505 WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
1506 "adapter depth exceeds lockdep subclass limit\n");
1510 EXPORT_SYMBOL_GPL(i2c_adapter_depth);
1513 * Let users instantiate I2C devices through sysfs. This can be used when
1514 * platform initialization code doesn't contain the proper data for
1515 * whatever reason. Also useful for drivers that do device detection and
1516 * detection fails, either because the device uses an unexpected address,
1517 * or this is a compatible device with different ID register values.
1519 * Parameter checking may look overzealous, but we really don't want
1520 * the user to provide incorrect parameters.
1523 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1524 const char *buf, size_t count)
1526 struct i2c_adapter *adap = to_i2c_adapter(dev);
1527 struct i2c_board_info info;
1528 struct i2c_client *client;
1532 memset(&info, 0, sizeof(struct i2c_board_info));
1534 blank = strchr(buf, ' ');
1536 dev_err(dev, "%s: Missing parameters\n", "new_device");
1539 if (blank - buf > I2C_NAME_SIZE - 1) {
1540 dev_err(dev, "%s: Invalid device name\n", "new_device");
1543 memcpy(info.type, buf, blank - buf);
1545 /* Parse remaining parameters, reject extra parameters */
1546 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1548 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1551 if (res > 1 && end != '\n') {
1552 dev_err(dev, "%s: Extra parameters\n", "new_device");
1556 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1557 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1558 info.flags |= I2C_CLIENT_TEN;
1561 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1562 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1563 info.flags |= I2C_CLIENT_SLAVE;
1566 client = i2c_new_device(adap, &info);
1570 /* Keep track of the added device */
1571 mutex_lock(&adap->userspace_clients_lock);
1572 list_add_tail(&client->detected, &adap->userspace_clients);
1573 mutex_unlock(&adap->userspace_clients_lock);
1574 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1575 info.type, info.addr);
1579 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1582 * And of course let the users delete the devices they instantiated, if
1583 * they got it wrong. This interface can only be used to delete devices
1584 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1585 * don't delete devices to which some kernel code still has references.
1587 * Parameter checking may look overzealous, but we really don't want
1588 * the user to delete the wrong device.
1591 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1592 const char *buf, size_t count)
1594 struct i2c_adapter *adap = to_i2c_adapter(dev);
1595 struct i2c_client *client, *next;
1596 unsigned short addr;
1600 /* Parse parameters, reject extra parameters */
1601 res = sscanf(buf, "%hi%c", &addr, &end);
1603 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1606 if (res > 1 && end != '\n') {
1607 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1611 /* Make sure the device was added through sysfs */
1613 mutex_lock_nested(&adap->userspace_clients_lock,
1614 i2c_adapter_depth(adap));
1615 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1617 if (i2c_encode_flags_to_addr(client) == addr) {
1618 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1619 "delete_device", client->name, client->addr);
1621 list_del(&client->detected);
1622 i2c_unregister_device(client);
1627 mutex_unlock(&adap->userspace_clients_lock);
1630 dev_err(dev, "%s: Can't find device in list\n",
1634 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1635 i2c_sysfs_delete_device);
1637 static struct attribute *i2c_adapter_attrs[] = {
1638 &dev_attr_name.attr,
1639 &dev_attr_new_device.attr,
1640 &dev_attr_delete_device.attr,
1643 ATTRIBUTE_GROUPS(i2c_adapter);
1645 struct device_type i2c_adapter_type = {
1646 .groups = i2c_adapter_groups,
1647 .release = i2c_adapter_dev_release,
1649 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1652 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1653 * @dev: device, probably from some driver model iterator
1655 * When traversing the driver model tree, perhaps using driver model
1656 * iterators like @device_for_each_child(), you can't assume very much
1657 * about the nodes you find. Use this function to avoid oopses caused
1658 * by wrongly treating some non-I2C device as an i2c_adapter.
1660 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1662 return (dev->type == &i2c_adapter_type)
1663 ? to_i2c_adapter(dev)
1666 EXPORT_SYMBOL(i2c_verify_adapter);
1668 #ifdef CONFIG_I2C_COMPAT
1669 static struct class_compat *i2c_adapter_compat_class;
1672 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1674 struct i2c_devinfo *devinfo;
1676 down_read(&__i2c_board_lock);
1677 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1678 if (devinfo->busnum == adapter->nr
1679 && !i2c_new_device(adapter,
1680 &devinfo->board_info))
1681 dev_err(&adapter->dev,
1682 "Can't create device at 0x%02x\n",
1683 devinfo->board_info.addr);
1685 up_read(&__i2c_board_lock);
1688 /* OF support code */
1690 #if IS_ENABLED(CONFIG_OF)
1691 static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1692 struct device_node *node)
1694 struct i2c_client *result;
1695 struct i2c_board_info info = {};
1696 struct dev_archdata dev_ad = {};
1697 const __be32 *addr_be;
1701 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1703 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1704 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1706 return ERR_PTR(-EINVAL);
1709 addr_be = of_get_property(node, "reg", &len);
1710 if (!addr_be || (len < sizeof(*addr_be))) {
1711 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1713 return ERR_PTR(-EINVAL);
1716 addr = be32_to_cpup(addr_be);
1717 if (addr & I2C_TEN_BIT_ADDRESS) {
1718 addr &= ~I2C_TEN_BIT_ADDRESS;
1719 info.flags |= I2C_CLIENT_TEN;
1722 if (addr & I2C_OWN_SLAVE_ADDRESS) {
1723 addr &= ~I2C_OWN_SLAVE_ADDRESS;
1724 info.flags |= I2C_CLIENT_SLAVE;
1727 if (i2c_check_addr_validity(addr, info.flags)) {
1728 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1729 addr, node->full_name);
1730 return ERR_PTR(-EINVAL);
1734 info.of_node = of_node_get(node);
1735 info.archdata = &dev_ad;
1737 if (of_property_read_bool(node, "host-notify"))
1738 info.flags |= I2C_CLIENT_HOST_NOTIFY;
1740 if (of_get_property(node, "wakeup-source", NULL))
1741 info.flags |= I2C_CLIENT_WAKE;
1743 result = i2c_new_device(adap, &info);
1744 if (result == NULL) {
1745 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1748 return ERR_PTR(-EINVAL);
1753 static void of_i2c_register_devices(struct i2c_adapter *adap)
1755 struct device_node *bus, *node;
1756 struct i2c_client *client;
1758 /* Only register child devices if the adapter has a node pointer set */
1759 if (!adap->dev.of_node)
1762 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1764 bus = of_get_child_by_name(adap->dev.of_node, "i2c-bus");
1766 bus = of_node_get(adap->dev.of_node);
1768 for_each_available_child_of_node(bus, node) {
1769 if (of_node_test_and_set_flag(node, OF_POPULATED))
1772 client = of_i2c_register_device(adap, node);
1773 if (IS_ERR(client)) {
1774 dev_warn(&adap->dev,
1775 "Failed to create I2C device for %s\n",
1777 of_node_clear_flag(node, OF_POPULATED);
1784 static int of_dev_node_match(struct device *dev, void *data)
1786 return dev->of_node == data;
1789 /* must call put_device() when done with returned i2c_client device */
1790 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1793 struct i2c_client *client;
1795 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1799 client = i2c_verify_client(dev);
1805 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1807 /* must call put_device() when done with returned i2c_adapter device */
1808 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1811 struct i2c_adapter *adapter;
1813 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1817 adapter = i2c_verify_adapter(dev);
1823 EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1825 /* must call i2c_put_adapter() when done with returned i2c_adapter device */
1826 struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1828 struct i2c_adapter *adapter;
1830 adapter = of_find_i2c_adapter_by_node(node);
1834 if (!try_module_get(adapter->owner)) {
1835 put_device(&adapter->dev);
1841 EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1843 static const struct of_device_id*
1844 i2c_of_match_device_sysfs(const struct of_device_id *matches,
1845 struct i2c_client *client)
1849 for (; matches->compatible[0]; matches++) {
1851 * Adding devices through the i2c sysfs interface provides us
1852 * a string to match which may be compatible with the device
1853 * tree compatible strings, however with no actual of_node the
1854 * of_match_device() will not match
1856 if (sysfs_streq(client->name, matches->compatible))
1859 name = strchr(matches->compatible, ',');
1861 name = matches->compatible;
1865 if (sysfs_streq(client->name, name))
1872 const struct of_device_id
1873 *i2c_of_match_device(const struct of_device_id *matches,
1874 struct i2c_client *client)
1876 const struct of_device_id *match;
1878 if (!(client && matches))
1881 match = of_match_device(matches, &client->dev);
1885 return i2c_of_match_device_sysfs(matches, client);
1887 EXPORT_SYMBOL_GPL(i2c_of_match_device);
1889 static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1890 #endif /* CONFIG_OF */
1892 static int i2c_do_add_adapter(struct i2c_driver *driver,
1893 struct i2c_adapter *adap)
1895 /* Detect supported devices on that bus, and instantiate them */
1896 i2c_detect(adap, driver);
1898 /* Let legacy drivers scan this bus for matching devices */
1899 if (driver->attach_adapter) {
1900 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1901 driver->driver.name);
1902 dev_warn(&adap->dev,
1903 "Please use another way to instantiate your i2c_client\n");
1904 /* We ignore the return code; if it fails, too bad */
1905 driver->attach_adapter(adap);
1910 static int __process_new_adapter(struct device_driver *d, void *data)
1912 return i2c_do_add_adapter(to_i2c_driver(d), data);
1915 static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1916 .lock_bus = i2c_adapter_lock_bus,
1917 .trylock_bus = i2c_adapter_trylock_bus,
1918 .unlock_bus = i2c_adapter_unlock_bus,
1921 static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
1923 struct irq_domain *domain = adap->host_notify_domain;
1924 irq_hw_number_t hwirq;
1929 for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
1930 irq_dispose_mapping(irq_find_mapping(domain, hwirq));
1932 irq_domain_remove(domain);
1933 adap->host_notify_domain = NULL;
1936 static int i2c_host_notify_irq_map(struct irq_domain *h,
1938 irq_hw_number_t hw_irq_num)
1940 irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
1945 static const struct irq_domain_ops i2c_host_notify_irq_ops = {
1946 .map = i2c_host_notify_irq_map,
1949 static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
1951 struct irq_domain *domain;
1953 if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
1956 domain = irq_domain_create_linear(adap->dev.fwnode,
1957 I2C_ADDR_7BITS_COUNT,
1958 &i2c_host_notify_irq_ops, adap);
1962 adap->host_notify_domain = domain;
1968 * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
1970 * @adap: the adapter
1971 * @addr: the I2C address of the notifying device
1972 * Context: can't sleep
1974 * Helper function to be called from an I2C bus driver's interrupt
1975 * handler. It will schedule the Host Notify IRQ.
1977 int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
1984 irq = irq_find_mapping(adap->host_notify_domain, addr);
1988 generic_handle_irq(irq);
1992 EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
1994 static int i2c_register_adapter(struct i2c_adapter *adap)
1998 /* Can't register until after driver model init */
1999 if (WARN_ON(!is_registered)) {
2005 if (WARN(!adap->name[0], "i2c adapter has no name"))
2009 pr_err("adapter '%s': no algo supplied!\n", adap->name);
2013 if (!adap->lock_ops)
2014 adap->lock_ops = &i2c_adapter_lock_ops;
2016 rt_mutex_init(&adap->bus_lock);
2017 rt_mutex_init(&adap->mux_lock);
2018 mutex_init(&adap->userspace_clients_lock);
2019 INIT_LIST_HEAD(&adap->userspace_clients);
2021 /* Set default timeout to 1 second if not already set */
2022 if (adap->timeout == 0)
2025 /* register soft irqs for Host Notify */
2026 res = i2c_setup_host_notify_irq_domain(adap);
2028 pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
2033 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
2034 adap->dev.bus = &i2c_bus_type;
2035 adap->dev.type = &i2c_adapter_type;
2036 res = device_register(&adap->dev);
2038 pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
2042 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
2044 pm_runtime_no_callbacks(&adap->dev);
2045 pm_suspend_ignore_children(&adap->dev, true);
2046 pm_runtime_enable(&adap->dev);
2048 #ifdef CONFIG_I2C_COMPAT
2049 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
2052 dev_warn(&adap->dev,
2053 "Failed to create compatibility class link\n");
2056 i2c_init_recovery(adap);
2058 /* create pre-declared device nodes */
2059 of_i2c_register_devices(adap);
2060 i2c_acpi_register_devices(adap);
2061 i2c_acpi_install_space_handler(adap);
2063 if (adap->nr < __i2c_first_dynamic_bus_num)
2064 i2c_scan_static_board_info(adap);
2066 /* Notify drivers */
2067 mutex_lock(&core_lock);
2068 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
2069 mutex_unlock(&core_lock);
2074 mutex_lock(&core_lock);
2075 idr_remove(&i2c_adapter_idr, adap->nr);
2076 mutex_unlock(&core_lock);
2081 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
2082 * @adap: the adapter to register (with adap->nr initialized)
2083 * Context: can sleep
2085 * See i2c_add_numbered_adapter() for details.
2087 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
2091 mutex_lock(&core_lock);
2092 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
2093 mutex_unlock(&core_lock);
2094 if (WARN(id < 0, "couldn't get idr"))
2095 return id == -ENOSPC ? -EBUSY : id;
2097 return i2c_register_adapter(adap);
2101 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
2102 * @adapter: the adapter to add
2103 * Context: can sleep
2105 * This routine is used to declare an I2C adapter when its bus number
2106 * doesn't matter or when its bus number is specified by an dt alias.
2107 * Examples of bases when the bus number doesn't matter: I2C adapters
2108 * dynamically added by USB links or PCI plugin cards.
2110 * When this returns zero, a new bus number was allocated and stored
2111 * in adap->nr, and the specified adapter became available for clients.
2112 * Otherwise, a negative errno value is returned.
2114 int i2c_add_adapter(struct i2c_adapter *adapter)
2116 struct device *dev = &adapter->dev;
2120 id = of_alias_get_id(dev->of_node, "i2c");
2123 return __i2c_add_numbered_adapter(adapter);
2127 mutex_lock(&core_lock);
2128 id = idr_alloc(&i2c_adapter_idr, adapter,
2129 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
2130 mutex_unlock(&core_lock);
2131 if (WARN(id < 0, "couldn't get idr"))
2136 return i2c_register_adapter(adapter);
2138 EXPORT_SYMBOL(i2c_add_adapter);
2141 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
2142 * @adap: the adapter to register (with adap->nr initialized)
2143 * Context: can sleep
2145 * This routine is used to declare an I2C adapter when its bus number
2146 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
2147 * or otherwise built in to the system's mainboard, and where i2c_board_info
2148 * is used to properly configure I2C devices.
2150 * If the requested bus number is set to -1, then this function will behave
2151 * identically to i2c_add_adapter, and will dynamically assign a bus number.
2153 * If no devices have pre-been declared for this bus, then be sure to
2154 * register the adapter before any dynamically allocated ones. Otherwise
2155 * the required bus ID may not be available.
2157 * When this returns zero, the specified adapter became available for
2158 * clients using the bus number provided in adap->nr. Also, the table
2159 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
2160 * and the appropriate driver model device nodes are created. Otherwise, a
2161 * negative errno value is returned.
2163 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
2165 if (adap->nr == -1) /* -1 means dynamically assign bus id */
2166 return i2c_add_adapter(adap);
2168 return __i2c_add_numbered_adapter(adap);
2170 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
2172 static void i2c_do_del_adapter(struct i2c_driver *driver,
2173 struct i2c_adapter *adapter)
2175 struct i2c_client *client, *_n;
2177 /* Remove the devices we created ourselves as the result of hardware
2178 * probing (using a driver's detect method) */
2179 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
2180 if (client->adapter == adapter) {
2181 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
2182 client->name, client->addr);
2183 list_del(&client->detected);
2184 i2c_unregister_device(client);
2189 static int __unregister_client(struct device *dev, void *dummy)
2191 struct i2c_client *client = i2c_verify_client(dev);
2192 if (client && strcmp(client->name, "dummy"))
2193 i2c_unregister_device(client);
2197 static int __unregister_dummy(struct device *dev, void *dummy)
2199 struct i2c_client *client = i2c_verify_client(dev);
2201 i2c_unregister_device(client);
2205 static int __process_removed_adapter(struct device_driver *d, void *data)
2207 i2c_do_del_adapter(to_i2c_driver(d), data);
2212 * i2c_del_adapter - unregister I2C adapter
2213 * @adap: the adapter being unregistered
2214 * Context: can sleep
2216 * This unregisters an I2C adapter which was previously registered
2217 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
2219 void i2c_del_adapter(struct i2c_adapter *adap)
2221 struct i2c_adapter *found;
2222 struct i2c_client *client, *next;
2224 /* First make sure that this adapter was ever added */
2225 mutex_lock(&core_lock);
2226 found = idr_find(&i2c_adapter_idr, adap->nr);
2227 mutex_unlock(&core_lock);
2228 if (found != adap) {
2229 pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
2233 i2c_acpi_remove_space_handler(adap);
2234 /* Tell drivers about this removal */
2235 mutex_lock(&core_lock);
2236 bus_for_each_drv(&i2c_bus_type, NULL, adap,
2237 __process_removed_adapter);
2238 mutex_unlock(&core_lock);
2240 /* Remove devices instantiated from sysfs */
2241 mutex_lock_nested(&adap->userspace_clients_lock,
2242 i2c_adapter_depth(adap));
2243 list_for_each_entry_safe(client, next, &adap->userspace_clients,
2245 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
2247 list_del(&client->detected);
2248 i2c_unregister_device(client);
2250 mutex_unlock(&adap->userspace_clients_lock);
2252 /* Detach any active clients. This can't fail, thus we do not
2253 * check the returned value. This is a two-pass process, because
2254 * we can't remove the dummy devices during the first pass: they
2255 * could have been instantiated by real devices wishing to clean
2256 * them up properly, so we give them a chance to do that first. */
2257 device_for_each_child(&adap->dev, NULL, __unregister_client);
2258 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
2260 #ifdef CONFIG_I2C_COMPAT
2261 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
2265 /* device name is gone after device_unregister */
2266 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
2268 pm_runtime_disable(&adap->dev);
2270 i2c_host_notify_irq_teardown(adap);
2272 /* wait until all references to the device are gone
2274 * FIXME: This is old code and should ideally be replaced by an
2275 * alternative which results in decoupling the lifetime of the struct
2276 * device from the i2c_adapter, like spi or netdev do. Any solution
2277 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
2279 init_completion(&adap->dev_released);
2280 device_unregister(&adap->dev);
2281 wait_for_completion(&adap->dev_released);
2284 mutex_lock(&core_lock);
2285 idr_remove(&i2c_adapter_idr, adap->nr);
2286 mutex_unlock(&core_lock);
2288 /* Clear the device structure in case this adapter is ever going to be
2290 memset(&adap->dev, 0, sizeof(adap->dev));
2292 EXPORT_SYMBOL(i2c_del_adapter);
2295 * i2c_parse_fw_timings - get I2C related timing parameters from firmware
2296 * @dev: The device to scan for I2C timing properties
2297 * @t: the i2c_timings struct to be filled with values
2298 * @use_defaults: bool to use sane defaults derived from the I2C specification
2299 * when properties are not found, otherwise use 0
2301 * Scan the device for the generic I2C properties describing timing parameters
2302 * for the signal and fill the given struct with the results. If a property was
2303 * not found and use_defaults was true, then maximum timings are assumed which
2304 * are derived from the I2C specification. If use_defaults is not used, the
2305 * results will be 0, so drivers can apply their own defaults later. The latter
2306 * is mainly intended for avoiding regressions of existing drivers which want
2307 * to switch to this function. New drivers almost always should use the defaults.
2310 void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
2314 memset(t, 0, sizeof(*t));
2316 ret = device_property_read_u32(dev, "clock-frequency", &t->bus_freq_hz);
2317 if (ret && use_defaults)
2318 t->bus_freq_hz = 100000;
2320 ret = device_property_read_u32(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns);
2321 if (ret && use_defaults) {
2322 if (t->bus_freq_hz <= 100000)
2323 t->scl_rise_ns = 1000;
2324 else if (t->bus_freq_hz <= 400000)
2325 t->scl_rise_ns = 300;
2327 t->scl_rise_ns = 120;
2330 ret = device_property_read_u32(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns);
2331 if (ret && use_defaults) {
2332 if (t->bus_freq_hz <= 400000)
2333 t->scl_fall_ns = 300;
2335 t->scl_fall_ns = 120;
2338 device_property_read_u32(dev, "i2c-scl-internal-delay-ns", &t->scl_int_delay_ns);
2340 ret = device_property_read_u32(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns);
2341 if (ret && use_defaults)
2342 t->sda_fall_ns = t->scl_fall_ns;
2344 EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
2346 /* ------------------------------------------------------------------------- */
2348 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
2352 mutex_lock(&core_lock);
2353 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
2354 mutex_unlock(&core_lock);
2358 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
2360 static int __process_new_driver(struct device *dev, void *data)
2362 if (dev->type != &i2c_adapter_type)
2364 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
2368 * An i2c_driver is used with one or more i2c_client (device) nodes to access
2369 * i2c slave chips, on a bus instance associated with some i2c_adapter.
2372 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
2376 /* Can't register until after driver model init */
2377 if (WARN_ON(!is_registered))
2380 /* add the driver to the list of i2c drivers in the driver core */
2381 driver->driver.owner = owner;
2382 driver->driver.bus = &i2c_bus_type;
2383 INIT_LIST_HEAD(&driver->clients);
2385 /* When registration returns, the driver core
2386 * will have called probe() for all matching-but-unbound devices.
2388 res = driver_register(&driver->driver);
2392 pr_debug("driver [%s] registered\n", driver->driver.name);
2394 /* Walk the adapters that are already present */
2395 i2c_for_each_dev(driver, __process_new_driver);
2399 EXPORT_SYMBOL(i2c_register_driver);
2401 static int __process_removed_driver(struct device *dev, void *data)
2403 if (dev->type == &i2c_adapter_type)
2404 i2c_do_del_adapter(data, to_i2c_adapter(dev));
2409 * i2c_del_driver - unregister I2C driver
2410 * @driver: the driver being unregistered
2411 * Context: can sleep
2413 void i2c_del_driver(struct i2c_driver *driver)
2415 i2c_for_each_dev(driver, __process_removed_driver);
2417 driver_unregister(&driver->driver);
2418 pr_debug("driver [%s] unregistered\n", driver->driver.name);
2420 EXPORT_SYMBOL(i2c_del_driver);
2422 /* ------------------------------------------------------------------------- */
2425 * i2c_use_client - increments the reference count of the i2c client structure
2426 * @client: the client being referenced
2428 * Each live reference to a client should be refcounted. The driver model does
2429 * that automatically as part of driver binding, so that most drivers don't
2430 * need to do this explicitly: they hold a reference until they're unbound
2433 * A pointer to the client with the incremented reference counter is returned.
2435 struct i2c_client *i2c_use_client(struct i2c_client *client)
2437 if (client && get_device(&client->dev))
2441 EXPORT_SYMBOL(i2c_use_client);
2444 * i2c_release_client - release a use of the i2c client structure
2445 * @client: the client being no longer referenced
2447 * Must be called when a user of a client is finished with it.
2449 void i2c_release_client(struct i2c_client *client)
2452 put_device(&client->dev);
2454 EXPORT_SYMBOL(i2c_release_client);
2456 struct i2c_cmd_arg {
2461 static int i2c_cmd(struct device *dev, void *_arg)
2463 struct i2c_client *client = i2c_verify_client(dev);
2464 struct i2c_cmd_arg *arg = _arg;
2465 struct i2c_driver *driver;
2467 if (!client || !client->dev.driver)
2470 driver = to_i2c_driver(client->dev.driver);
2471 if (driver->command)
2472 driver->command(client, arg->cmd, arg->arg);
2476 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
2478 struct i2c_cmd_arg cmd_arg;
2482 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
2484 EXPORT_SYMBOL(i2c_clients_command);
2486 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
2487 static int of_i2c_notify(struct notifier_block *nb, unsigned long action,
2490 struct of_reconfig_data *rd = arg;
2491 struct i2c_adapter *adap;
2492 struct i2c_client *client;
2494 switch (of_reconfig_get_state_change(action, rd)) {
2495 case OF_RECONFIG_CHANGE_ADD:
2496 adap = of_find_i2c_adapter_by_node(rd->dn->parent);
2498 return NOTIFY_OK; /* not for us */
2500 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
2501 put_device(&adap->dev);
2505 client = of_i2c_register_device(adap, rd->dn);
2506 put_device(&adap->dev);
2508 if (IS_ERR(client)) {
2509 dev_err(&adap->dev, "failed to create client for '%s'\n",
2511 of_node_clear_flag(rd->dn, OF_POPULATED);
2512 return notifier_from_errno(PTR_ERR(client));
2515 case OF_RECONFIG_CHANGE_REMOVE:
2516 /* already depopulated? */
2517 if (!of_node_check_flag(rd->dn, OF_POPULATED))
2520 /* find our device by node */
2521 client = of_find_i2c_device_by_node(rd->dn);
2523 return NOTIFY_OK; /* no? not meant for us */
2525 /* unregister takes one ref away */
2526 i2c_unregister_device(client);
2528 /* and put the reference of the find */
2529 put_device(&client->dev);
2535 static struct notifier_block i2c_of_notifier = {
2536 .notifier_call = of_i2c_notify,
2539 extern struct notifier_block i2c_of_notifier;
2540 #endif /* CONFIG_OF_DYNAMIC */
2542 static int __init i2c_init(void)
2546 retval = of_alias_get_highest_id("i2c");
2548 down_write(&__i2c_board_lock);
2549 if (retval >= __i2c_first_dynamic_bus_num)
2550 __i2c_first_dynamic_bus_num = retval + 1;
2551 up_write(&__i2c_board_lock);
2553 retval = bus_register(&i2c_bus_type);
2557 is_registered = true;
2559 #ifdef CONFIG_I2C_COMPAT
2560 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
2561 if (!i2c_adapter_compat_class) {
2566 retval = i2c_add_driver(&dummy_driver);
2570 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2571 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
2572 if (IS_ENABLED(CONFIG_ACPI))
2573 WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
2578 #ifdef CONFIG_I2C_COMPAT
2579 class_compat_unregister(i2c_adapter_compat_class);
2582 is_registered = false;
2583 bus_unregister(&i2c_bus_type);
2587 static void __exit i2c_exit(void)
2589 if (IS_ENABLED(CONFIG_ACPI))
2590 WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
2591 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2592 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
2593 i2c_del_driver(&dummy_driver);
2594 #ifdef CONFIG_I2C_COMPAT
2595 class_compat_unregister(i2c_adapter_compat_class);
2597 bus_unregister(&i2c_bus_type);
2598 tracepoint_synchronize_unregister();
2601 /* We must initialize early, because some subsystems register i2c drivers
2602 * in subsys_initcall() code, but are linked (and initialized) before i2c.
2604 postcore_initcall(i2c_init);
2605 module_exit(i2c_exit);
2607 /* ----------------------------------------------------
2608 * the functional interface to the i2c busses.
2609 * ----------------------------------------------------
2612 /* Check if val is exceeding the quirk IFF quirk is non 0 */
2613 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2615 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2617 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2618 err_msg, msg->addr, msg->len,
2619 msg->flags & I2C_M_RD ? "read" : "write");
2623 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2625 const struct i2c_adapter_quirks *q = adap->quirks;
2626 int max_num = q->max_num_msgs, i;
2627 bool do_len_check = true;
2629 if (q->flags & I2C_AQ_COMB) {
2632 /* special checks for combined messages */
2634 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2635 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2637 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2638 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2640 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2641 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2643 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2644 return i2c_quirk_error(adap, &msgs[0], "msg too long");
2646 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2647 return i2c_quirk_error(adap, &msgs[1], "msg too long");
2649 do_len_check = false;
2653 if (i2c_quirk_exceeded(num, max_num))
2654 return i2c_quirk_error(adap, &msgs[0], "too many messages");
2656 for (i = 0; i < num; i++) {
2657 u16 len = msgs[i].len;
2659 if (msgs[i].flags & I2C_M_RD) {
2660 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2661 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2663 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2664 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2672 * __i2c_transfer - unlocked flavor of i2c_transfer
2673 * @adap: Handle to I2C bus
2674 * @msgs: One or more messages to execute before STOP is issued to
2675 * terminate the operation; each message begins with a START.
2676 * @num: Number of messages to be executed.
2678 * Returns negative errno, else the number of messages executed.
2680 * Adapter lock must be held when calling this function. No debug logging
2681 * takes place. adap->algo->master_xfer existence isn't checked.
2683 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2685 unsigned long orig_jiffies;
2688 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2691 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2692 * enabled. This is an efficient way of keeping the for-loop from
2693 * being executed when not needed.
2695 if (static_key_false(&i2c_trace_msg)) {
2697 for (i = 0; i < num; i++)
2698 if (msgs[i].flags & I2C_M_RD)
2699 trace_i2c_read(adap, &msgs[i], i);
2701 trace_i2c_write(adap, &msgs[i], i);
2704 /* Retry automatically on arbitration loss */
2705 orig_jiffies = jiffies;
2706 for (ret = 0, try = 0; try <= adap->retries; try++) {
2707 ret = adap->algo->master_xfer(adap, msgs, num);
2710 if (time_after(jiffies, orig_jiffies + adap->timeout))
2714 if (static_key_false(&i2c_trace_msg)) {
2716 for (i = 0; i < ret; i++)
2717 if (msgs[i].flags & I2C_M_RD)
2718 trace_i2c_reply(adap, &msgs[i], i);
2719 trace_i2c_result(adap, i, ret);
2724 EXPORT_SYMBOL(__i2c_transfer);
2727 * i2c_transfer - execute a single or combined I2C message
2728 * @adap: Handle to I2C bus
2729 * @msgs: One or more messages to execute before STOP is issued to
2730 * terminate the operation; each message begins with a START.
2731 * @num: Number of messages to be executed.
2733 * Returns negative errno, else the number of messages executed.
2735 * Note that there is no requirement that each message be sent to
2736 * the same slave address, although that is the most common model.
2738 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2742 /* REVISIT the fault reporting model here is weak:
2744 * - When we get an error after receiving N bytes from a slave,
2745 * there is no way to report "N".
2747 * - When we get a NAK after transmitting N bytes to a slave,
2748 * there is no way to report "N" ... or to let the master
2749 * continue executing the rest of this combined message, if
2750 * that's the appropriate response.
2752 * - When for example "num" is two and we successfully complete
2753 * the first message but get an error part way through the
2754 * second, it's unclear whether that should be reported as
2755 * one (discarding status on the second message) or errno
2756 * (discarding status on the first one).
2759 if (adap->algo->master_xfer) {
2761 for (ret = 0; ret < num; ret++) {
2763 "master_xfer[%d] %c, addr=0x%02x, len=%d%s\n",
2764 ret, (msgs[ret].flags & I2C_M_RD) ? 'R' : 'W',
2765 msgs[ret].addr, msgs[ret].len,
2766 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2770 if (in_atomic() || irqs_disabled()) {
2771 ret = i2c_trylock_bus(adap, I2C_LOCK_SEGMENT);
2773 /* I2C activity is ongoing. */
2776 i2c_lock_bus(adap, I2C_LOCK_SEGMENT);
2779 ret = __i2c_transfer(adap, msgs, num);
2780 i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
2784 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2788 EXPORT_SYMBOL(i2c_transfer);
2791 * i2c_master_send - issue a single I2C message in master transmit mode
2792 * @client: Handle to slave device
2793 * @buf: Data that will be written to the slave
2794 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2796 * Returns negative errno, or else the number of bytes written.
2798 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2801 struct i2c_adapter *adap = client->adapter;
2804 msg.addr = client->addr;
2805 msg.flags = client->flags & I2C_M_TEN;
2807 msg.buf = (char *)buf;
2809 ret = i2c_transfer(adap, &msg, 1);
2812 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2813 * transmitted, else error code.
2815 return (ret == 1) ? count : ret;
2817 EXPORT_SYMBOL(i2c_master_send);
2820 * i2c_master_recv - issue a single I2C message in master receive mode
2821 * @client: Handle to slave device
2822 * @buf: Where to store data read from slave
2823 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2825 * Returns negative errno, or else the number of bytes read.
2827 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2829 struct i2c_adapter *adap = client->adapter;
2833 msg.addr = client->addr;
2834 msg.flags = client->flags & I2C_M_TEN;
2835 msg.flags |= I2C_M_RD;
2839 ret = i2c_transfer(adap, &msg, 1);
2842 * If everything went ok (i.e. 1 msg received), return #bytes received,
2845 return (ret == 1) ? count : ret;
2847 EXPORT_SYMBOL(i2c_master_recv);
2849 /* ----------------------------------------------------
2850 * the i2c address scanning function
2851 * Will not work for 10-bit addresses!
2852 * ----------------------------------------------------
2856 * Legacy default probe function, mostly relevant for SMBus. The default
2857 * probe method is a quick write, but it is known to corrupt the 24RF08
2858 * EEPROMs due to a state machine bug, and could also irreversibly
2859 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2860 * we use a short byte read instead. Also, some bus drivers don't implement
2861 * quick write, so we fallback to a byte read in that case too.
2862 * On x86, there is another special case for FSC hardware monitoring chips,
2863 * which want regular byte reads (address 0x73.) Fortunately, these are the
2864 * only known chips using this I2C address on PC hardware.
2865 * Returns 1 if probe succeeded, 0 if not.
2867 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2870 union i2c_smbus_data dummy;
2873 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2874 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2875 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2876 I2C_SMBUS_BYTE_DATA, &dummy);
2879 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2880 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2881 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2882 I2C_SMBUS_QUICK, NULL);
2883 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2884 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2885 I2C_SMBUS_BYTE, &dummy);
2887 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2895 static int i2c_detect_address(struct i2c_client *temp_client,
2896 struct i2c_driver *driver)
2898 struct i2c_board_info info;
2899 struct i2c_adapter *adapter = temp_client->adapter;
2900 int addr = temp_client->addr;
2903 /* Make sure the address is valid */
2904 err = i2c_check_7bit_addr_validity_strict(addr);
2906 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2911 /* Skip if already in use (7 bit, no need to encode flags) */
2912 if (i2c_check_addr_busy(adapter, addr))
2915 /* Make sure there is something at this address */
2916 if (!i2c_default_probe(adapter, addr))
2919 /* Finally call the custom detection function */
2920 memset(&info, 0, sizeof(struct i2c_board_info));
2922 err = driver->detect(temp_client, &info);
2924 /* -ENODEV is returned if the detection fails. We catch it
2925 here as this isn't an error. */
2926 return err == -ENODEV ? 0 : err;
2929 /* Consistency check */
2930 if (info.type[0] == '\0') {
2931 dev_err(&adapter->dev,
2932 "%s detection function provided no name for 0x%x\n",
2933 driver->driver.name, addr);
2935 struct i2c_client *client;
2937 /* Detection succeeded, instantiate the device */
2938 if (adapter->class & I2C_CLASS_DEPRECATED)
2939 dev_warn(&adapter->dev,
2940 "This adapter will soon drop class based instantiation of devices. "
2941 "Please make sure client 0x%02x gets instantiated by other means. "
2942 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2945 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2946 info.type, info.addr);
2947 client = i2c_new_device(adapter, &info);
2949 list_add_tail(&client->detected, &driver->clients);
2951 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2952 info.type, info.addr);
2957 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2959 const unsigned short *address_list;
2960 struct i2c_client *temp_client;
2962 int adap_id = i2c_adapter_id(adapter);
2964 address_list = driver->address_list;
2965 if (!driver->detect || !address_list)
2968 /* Warn that the adapter lost class based instantiation */
2969 if (adapter->class == I2C_CLASS_DEPRECATED) {
2970 dev_dbg(&adapter->dev,
2971 "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
2972 "If you need it, check 'Documentation/i2c/instantiating-devices' for alternatives.\n",
2973 driver->driver.name);
2977 /* Stop here if the classes do not match */
2978 if (!(adapter->class & driver->class))
2981 /* Set up a temporary client to help detect callback */
2982 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2985 temp_client->adapter = adapter;
2987 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2988 dev_dbg(&adapter->dev,
2989 "found normal entry for adapter %d, addr 0x%02x\n",
2990 adap_id, address_list[i]);
2991 temp_client->addr = address_list[i];
2992 err = i2c_detect_address(temp_client, driver);
3001 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
3003 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
3004 I2C_SMBUS_QUICK, NULL) >= 0;
3006 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
3009 i2c_new_probed_device(struct i2c_adapter *adap,
3010 struct i2c_board_info *info,
3011 unsigned short const *addr_list,
3012 int (*probe)(struct i2c_adapter *, unsigned short addr))
3017 probe = i2c_default_probe;
3019 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
3020 /* Check address validity */
3021 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
3022 dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
3027 /* Check address availability (7 bit, no need to encode flags) */
3028 if (i2c_check_addr_busy(adap, addr_list[i])) {
3030 "Address 0x%02x already in use, not probing\n",
3035 /* Test address responsiveness */
3036 if (probe(adap, addr_list[i]))
3040 if (addr_list[i] == I2C_CLIENT_END) {
3041 dev_dbg(&adap->dev, "Probing failed, no device found\n");
3045 info->addr = addr_list[i];
3046 return i2c_new_device(adap, info);
3048 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
3050 struct i2c_adapter *i2c_get_adapter(int nr)
3052 struct i2c_adapter *adapter;
3054 mutex_lock(&core_lock);
3055 adapter = idr_find(&i2c_adapter_idr, nr);
3059 if (try_module_get(adapter->owner))
3060 get_device(&adapter->dev);
3065 mutex_unlock(&core_lock);
3068 EXPORT_SYMBOL(i2c_get_adapter);
3070 void i2c_put_adapter(struct i2c_adapter *adap)
3075 put_device(&adap->dev);
3076 module_put(adap->owner);
3078 EXPORT_SYMBOL(i2c_put_adapter);
3080 /* The SMBus parts */
3082 #define POLY (0x1070U << 3)
3083 static u8 crc8(u16 data)
3087 for (i = 0; i < 8; i++) {
3092 return (u8)(data >> 8);
3095 /* Incremental CRC8 over count bytes in the array pointed to by p */
3096 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
3100 for (i = 0; i < count; i++)
3101 crc = crc8((crc ^ p[i]) << 8);
3105 /* Assume a 7-bit address, which is reasonable for SMBus */
3106 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
3108 /* The address will be sent first */
3109 u8 addr = i2c_8bit_addr_from_msg(msg);
3110 pec = i2c_smbus_pec(pec, &addr, 1);
3112 /* The data buffer follows */
3113 return i2c_smbus_pec(pec, msg->buf, msg->len);
3116 /* Used for write only transactions */
3117 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
3119 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
3123 /* Return <0 on CRC error
3124 If there was a write before this read (most cases) we need to take the
3125 partial CRC from the write part into account.
3126 Note that this function does modify the message (we need to decrease the
3127 message length to hide the CRC byte from the caller). */
3128 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
3130 u8 rpec = msg->buf[--msg->len];
3131 cpec = i2c_smbus_msg_pec(cpec, msg);
3134 pr_debug("Bad PEC 0x%02x vs. 0x%02x\n",
3142 * i2c_smbus_read_byte - SMBus "receive byte" protocol
3143 * @client: Handle to slave device
3145 * This executes the SMBus "receive byte" protocol, returning negative errno
3146 * else the byte received from the device.
3148 s32 i2c_smbus_read_byte(const struct i2c_client *client)
3150 union i2c_smbus_data data;
3153 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3155 I2C_SMBUS_BYTE, &data);
3156 return (status < 0) ? status : data.byte;
3158 EXPORT_SYMBOL(i2c_smbus_read_byte);
3161 * i2c_smbus_write_byte - SMBus "send byte" protocol
3162 * @client: Handle to slave device
3163 * @value: Byte to be sent
3165 * This executes the SMBus "send byte" protocol, returning negative errno
3166 * else zero on success.
3168 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
3170 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3171 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
3173 EXPORT_SYMBOL(i2c_smbus_write_byte);
3176 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
3177 * @client: Handle to slave device
3178 * @command: Byte interpreted by slave
3180 * This executes the SMBus "read byte" protocol, returning negative errno
3181 * else a data byte received from the device.
3183 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
3185 union i2c_smbus_data data;
3188 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3189 I2C_SMBUS_READ, command,
3190 I2C_SMBUS_BYTE_DATA, &data);
3191 return (status < 0) ? status : data.byte;
3193 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
3196 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
3197 * @client: Handle to slave device
3198 * @command: Byte interpreted by slave
3199 * @value: Byte being written
3201 * This executes the SMBus "write byte" protocol, returning negative errno
3202 * else zero on success.
3204 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
3207 union i2c_smbus_data data;
3209 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3210 I2C_SMBUS_WRITE, command,
3211 I2C_SMBUS_BYTE_DATA, &data);
3213 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
3216 * i2c_smbus_read_word_data - SMBus "read word" protocol
3217 * @client: Handle to slave device
3218 * @command: Byte interpreted by slave
3220 * This executes the SMBus "read word" protocol, returning negative errno
3221 * else a 16-bit unsigned "word" received from the device.
3223 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
3225 union i2c_smbus_data data;
3228 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3229 I2C_SMBUS_READ, command,
3230 I2C_SMBUS_WORD_DATA, &data);
3231 return (status < 0) ? status : data.word;
3233 EXPORT_SYMBOL(i2c_smbus_read_word_data);
3236 * i2c_smbus_write_word_data - SMBus "write word" protocol
3237 * @client: Handle to slave device
3238 * @command: Byte interpreted by slave
3239 * @value: 16-bit "word" being written
3241 * This executes the SMBus "write word" protocol, returning negative errno
3242 * else zero on success.
3244 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
3247 union i2c_smbus_data data;
3249 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3250 I2C_SMBUS_WRITE, command,
3251 I2C_SMBUS_WORD_DATA, &data);
3253 EXPORT_SYMBOL(i2c_smbus_write_word_data);
3256 * i2c_smbus_read_block_data - SMBus "block read" protocol
3257 * @client: Handle to slave device
3258 * @command: Byte interpreted by slave
3259 * @values: Byte array into which data will be read; big enough to hold
3260 * the data returned by the slave. SMBus allows at most 32 bytes.
3262 * This executes the SMBus "block read" protocol, returning negative errno
3263 * else the number of data bytes in the slave's response.
3265 * Note that using this function requires that the client's adapter support
3266 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
3267 * support this; its emulation through I2C messaging relies on a specific
3268 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
3270 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
3273 union i2c_smbus_data data;
3276 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3277 I2C_SMBUS_READ, command,
3278 I2C_SMBUS_BLOCK_DATA, &data);
3282 memcpy(values, &data.block[1], data.block[0]);
3283 return data.block[0];
3285 EXPORT_SYMBOL(i2c_smbus_read_block_data);
3288 * i2c_smbus_write_block_data - SMBus "block write" protocol
3289 * @client: Handle to slave device
3290 * @command: Byte interpreted by slave
3291 * @length: Size of data block; SMBus allows at most 32 bytes
3292 * @values: Byte array which will be written.
3294 * This executes the SMBus "block write" protocol, returning negative errno
3295 * else zero on success.
3297 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
3298 u8 length, const u8 *values)
3300 union i2c_smbus_data data;
3302 if (length > I2C_SMBUS_BLOCK_MAX)
3303 length = I2C_SMBUS_BLOCK_MAX;
3304 data.block[0] = length;
3305 memcpy(&data.block[1], values, length);
3306 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3307 I2C_SMBUS_WRITE, command,
3308 I2C_SMBUS_BLOCK_DATA, &data);
3310 EXPORT_SYMBOL(i2c_smbus_write_block_data);
3312 /* Returns the number of read bytes */
3313 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
3314 u8 length, u8 *values)
3316 union i2c_smbus_data data;
3319 if (length > I2C_SMBUS_BLOCK_MAX)
3320 length = I2C_SMBUS_BLOCK_MAX;
3321 data.block[0] = length;
3322 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3323 I2C_SMBUS_READ, command,
3324 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3328 memcpy(values, &data.block[1], data.block[0]);
3329 return data.block[0];
3331 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
3333 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
3334 u8 length, const u8 *values)
3336 union i2c_smbus_data data;
3338 if (length > I2C_SMBUS_BLOCK_MAX)
3339 length = I2C_SMBUS_BLOCK_MAX;
3340 data.block[0] = length;
3341 memcpy(data.block + 1, values, length);
3342 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3343 I2C_SMBUS_WRITE, command,
3344 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3346 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
3348 /* Simulate a SMBus command using the i2c protocol
3349 No checking of parameters is done! */
3350 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
3351 unsigned short flags,
3352 char read_write, u8 command, int size,
3353 union i2c_smbus_data *data)
3355 /* So we need to generate a series of msgs. In the case of writing, we
3356 need to use only one message; when reading, we need two. We initialize
3357 most things with sane defaults, to keep the code below somewhat
3359 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
3360 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
3361 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
3365 struct i2c_msg msg[2] = {
3373 .flags = flags | I2C_M_RD,
3379 msgbuf0[0] = command;
3381 case I2C_SMBUS_QUICK:
3383 /* Special case: The read/write field is used as data */
3384 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
3388 case I2C_SMBUS_BYTE:
3389 if (read_write == I2C_SMBUS_READ) {
3390 /* Special case: only a read! */
3391 msg[0].flags = I2C_M_RD | flags;
3395 case I2C_SMBUS_BYTE_DATA:
3396 if (read_write == I2C_SMBUS_READ)
3400 msgbuf0[1] = data->byte;
3403 case I2C_SMBUS_WORD_DATA:
3404 if (read_write == I2C_SMBUS_READ)
3408 msgbuf0[1] = data->word & 0xff;
3409 msgbuf0[2] = data->word >> 8;
3412 case I2C_SMBUS_PROC_CALL:
3413 num = 2; /* Special case */
3414 read_write = I2C_SMBUS_READ;
3417 msgbuf0[1] = data->word & 0xff;
3418 msgbuf0[2] = data->word >> 8;
3420 case I2C_SMBUS_BLOCK_DATA:
3421 if (read_write == I2C_SMBUS_READ) {
3422 msg[1].flags |= I2C_M_RECV_LEN;
3423 msg[1].len = 1; /* block length will be added by
3424 the underlying bus driver */
3426 msg[0].len = data->block[0] + 2;
3427 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
3428 dev_err(&adapter->dev,
3429 "Invalid block write size %d\n",
3433 for (i = 1; i < msg[0].len; i++)
3434 msgbuf0[i] = data->block[i-1];
3437 case I2C_SMBUS_BLOCK_PROC_CALL:
3438 num = 2; /* Another special case */
3439 read_write = I2C_SMBUS_READ;
3440 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
3441 dev_err(&adapter->dev,
3442 "Invalid block write size %d\n",
3446 msg[0].len = data->block[0] + 2;
3447 for (i = 1; i < msg[0].len; i++)
3448 msgbuf0[i] = data->block[i-1];
3449 msg[1].flags |= I2C_M_RECV_LEN;
3450 msg[1].len = 1; /* block length will be added by
3451 the underlying bus driver */
3453 case I2C_SMBUS_I2C_BLOCK_DATA:
3454 if (read_write == I2C_SMBUS_READ) {
3455 msg[1].len = data->block[0];
3457 msg[0].len = data->block[0] + 1;
3458 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
3459 dev_err(&adapter->dev,
3460 "Invalid block write size %d\n",
3464 for (i = 1; i <= data->block[0]; i++)
3465 msgbuf0[i] = data->block[i];
3469 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
3473 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
3474 && size != I2C_SMBUS_I2C_BLOCK_DATA);
3476 /* Compute PEC if first message is a write */
3477 if (!(msg[0].flags & I2C_M_RD)) {
3478 if (num == 1) /* Write only */
3479 i2c_smbus_add_pec(&msg[0]);
3480 else /* Write followed by read */
3481 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
3483 /* Ask for PEC if last message is a read */
3484 if (msg[num-1].flags & I2C_M_RD)
3488 status = i2c_transfer(adapter, msg, num);
3492 /* Check PEC if last message is a read */
3493 if (i && (msg[num-1].flags & I2C_M_RD)) {
3494 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
3499 if (read_write == I2C_SMBUS_READ)
3501 case I2C_SMBUS_BYTE:
3502 data->byte = msgbuf0[0];
3504 case I2C_SMBUS_BYTE_DATA:
3505 data->byte = msgbuf1[0];
3507 case I2C_SMBUS_WORD_DATA:
3508 case I2C_SMBUS_PROC_CALL:
3509 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
3511 case I2C_SMBUS_I2C_BLOCK_DATA:
3512 for (i = 0; i < data->block[0]; i++)
3513 data->block[i+1] = msgbuf1[i];
3515 case I2C_SMBUS_BLOCK_DATA:
3516 case I2C_SMBUS_BLOCK_PROC_CALL:
3517 for (i = 0; i < msgbuf1[0] + 1; i++)
3518 data->block[i] = msgbuf1[i];
3525 * i2c_smbus_xfer - execute SMBus protocol operations
3526 * @adapter: Handle to I2C bus
3527 * @addr: Address of SMBus slave on that bus
3528 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
3529 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
3530 * @command: Byte interpreted by slave, for protocols which use such bytes
3531 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
3532 * @data: Data to be read or written
3534 * This executes an SMBus protocol operation, and returns a negative
3535 * errno code else zero on success.
3537 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
3538 char read_write, u8 command, int protocol,
3539 union i2c_smbus_data *data)
3541 unsigned long orig_jiffies;
3545 /* If enabled, the following two tracepoints are conditional on
3546 * read_write and protocol.
3548 trace_smbus_write(adapter, addr, flags, read_write,
3549 command, protocol, data);
3550 trace_smbus_read(adapter, addr, flags, read_write,
3553 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
3555 if (adapter->algo->smbus_xfer) {
3556 i2c_lock_bus(adapter, I2C_LOCK_SEGMENT);
3558 /* Retry automatically on arbitration loss */
3559 orig_jiffies = jiffies;
3560 for (res = 0, try = 0; try <= adapter->retries; try++) {
3561 res = adapter->algo->smbus_xfer(adapter, addr, flags,
3562 read_write, command,
3566 if (time_after(jiffies,
3567 orig_jiffies + adapter->timeout))
3570 i2c_unlock_bus(adapter, I2C_LOCK_SEGMENT);
3572 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
3575 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
3576 * implement native support for the SMBus operation.
3580 res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
3581 command, protocol, data);
3584 /* If enabled, the reply tracepoint is conditional on read_write. */
3585 trace_smbus_reply(adapter, addr, flags, read_write,
3586 command, protocol, data);
3587 trace_smbus_result(adapter, addr, flags, read_write,
3588 command, protocol, res);
3592 EXPORT_SYMBOL(i2c_smbus_xfer);
3595 * i2c_smbus_read_i2c_block_data_or_emulated - read block or emulate
3596 * @client: Handle to slave device
3597 * @command: Byte interpreted by slave
3598 * @length: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
3599 * @values: Byte array into which data will be read; big enough to hold
3600 * the data returned by the slave. SMBus allows at most
3601 * I2C_SMBUS_BLOCK_MAX bytes.
3603 * This executes the SMBus "block read" protocol if supported by the adapter.
3604 * If block read is not supported, it emulates it using either word or byte
3605 * read protocols depending on availability.
3607 * The addresses of the I2C slave device that are accessed with this function
3608 * must be mapped to a linear region, so that a block read will have the same
3609 * effect as a byte read. Before using this function you must double-check
3610 * if the I2C slave does support exchanging a block transfer with a byte
3613 s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client,
3614 u8 command, u8 length, u8 *values)
3619 if (length > I2C_SMBUS_BLOCK_MAX)
3620 length = I2C_SMBUS_BLOCK_MAX;
3622 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
3623 return i2c_smbus_read_i2c_block_data(client, command, length, values);
3625 if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA))
3628 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) {
3629 while ((i + 2) <= length) {
3630 status = i2c_smbus_read_word_data(client, command + i);
3633 values[i] = status & 0xff;
3634 values[i + 1] = status >> 8;
3639 while (i < length) {
3640 status = i2c_smbus_read_byte_data(client, command + i);
3649 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data_or_emulated);
3651 #if IS_ENABLED(CONFIG_I2C_SLAVE)
3652 int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
3656 if (!client || !slave_cb) {
3657 WARN(1, "insufficient data\n");
3661 if (!(client->flags & I2C_CLIENT_SLAVE))
3662 dev_warn(&client->dev, "%s: client slave flag not set. You might see address collisions\n",
3665 if (!(client->flags & I2C_CLIENT_TEN)) {
3666 /* Enforce stricter address checking */
3667 ret = i2c_check_7bit_addr_validity_strict(client->addr);
3669 dev_err(&client->dev, "%s: invalid address\n", __func__);
3674 if (!client->adapter->algo->reg_slave) {
3675 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3679 client->slave_cb = slave_cb;
3681 i2c_lock_adapter(client->adapter);
3682 ret = client->adapter->algo->reg_slave(client);
3683 i2c_unlock_adapter(client->adapter);
3686 client->slave_cb = NULL;
3687 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3692 EXPORT_SYMBOL_GPL(i2c_slave_register);
3694 int i2c_slave_unregister(struct i2c_client *client)
3698 if (!client->adapter->algo->unreg_slave) {
3699 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3703 i2c_lock_adapter(client->adapter);
3704 ret = client->adapter->algo->unreg_slave(client);
3705 i2c_unlock_adapter(client->adapter);
3708 client->slave_cb = NULL;
3710 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3714 EXPORT_SYMBOL_GPL(i2c_slave_unregister);
3717 * i2c_detect_slave_mode - detect operation mode
3718 * @dev: The device owning the bus
3720 * This checks the device nodes for an I2C slave by checking the address
3721 * used in the reg property. If the address match the I2C_OWN_SLAVE_ADDRESS
3722 * flag this means the device is configured to act as a I2C slave and it will
3723 * be listening at that address.
3725 * Returns true if an I2C own slave address is detected, otherwise returns
3728 bool i2c_detect_slave_mode(struct device *dev)
3730 if (IS_BUILTIN(CONFIG_OF) && dev->of_node) {
3731 struct device_node *child;
3734 for_each_child_of_node(dev->of_node, child) {
3735 of_property_read_u32(child, "reg", ®);
3736 if (reg & I2C_OWN_SLAVE_ADDRESS) {
3741 } else if (IS_BUILTIN(CONFIG_ACPI) && ACPI_HANDLE(dev)) {
3742 dev_dbg(dev, "ACPI slave is not supported yet\n");
3746 EXPORT_SYMBOL_GPL(i2c_detect_slave_mode);
3750 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
3751 MODULE_DESCRIPTION("I2C-Bus main module");
3752 MODULE_LICENSE("GPL");