1 /* i2c-core.c - a device driver for the iic-bus interface */
2 /* ------------------------------------------------------------------------- */
3 /* Copyright (C) 1995-99 Simon G. Vogl
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details. */
14 /* ------------------------------------------------------------------------- */
16 /* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>.
17 All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
18 SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com> and
19 Jean Delvare <jdelvare@suse.de>
20 Mux support by Rodolfo Giometti <giometti@enneenne.com> and
21 Michael Lawnick <michael.lawnick.ext@nsn.com>
22 OF support is copyright (c) 2008 Jochen Friedrich <jochen@scram.de>
23 (based on a previous patch from Jon Smirl <jonsmirl@gmail.com>) and
24 (c) 2013 Wolfram Sang <wsa@the-dreams.de>
25 I2C ACPI code Copyright (C) 2014 Intel Corp
26 Author: Lan Tianyu <tianyu.lan@intel.com>
27 I2C slave support (c) 2014 by Wolfram Sang <wsa@sang-engineering.com>
30 #define pr_fmt(fmt) "i2c-core: " fmt
32 #include <dt-bindings/i2c/i2c.h>
33 #include <asm/uaccess.h>
34 #include <linux/acpi.h>
35 #include <linux/clk/clk-conf.h>
36 #include <linux/completion.h>
37 #include <linux/delay.h>
38 #include <linux/err.h>
39 #include <linux/errno.h>
40 #include <linux/gpio.h>
41 #include <linux/hardirq.h>
42 #include <linux/i2c.h>
43 #include <linux/idr.h>
44 #include <linux/init.h>
45 #include <linux/irqflags.h>
46 #include <linux/jump_label.h>
47 #include <linux/kernel.h>
48 #include <linux/module.h>
49 #include <linux/mutex.h>
50 #include <linux/of_device.h>
52 #include <linux/of_irq.h>
53 #include <linux/pm_domain.h>
54 #include <linux/pm_runtime.h>
55 #include <linux/pm_wakeirq.h>
56 #include <linux/property.h>
57 #include <linux/rwsem.h>
58 #include <linux/slab.h>
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/i2c.h>
65 #define I2C_ADDR_OFFSET_TEN_BIT 0xa000
66 #define I2C_ADDR_OFFSET_SLAVE 0x1000
68 /* core_lock protects i2c_adapter_idr, and guarantees
69 that device detection, deletion of detected devices, and attach_adapter
70 calls are serialized */
71 static DEFINE_MUTEX(core_lock);
72 static DEFINE_IDR(i2c_adapter_idr);
74 static struct device_type i2c_client_type;
75 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
77 static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
78 static bool is_registered;
80 void i2c_transfer_trace_reg(void)
82 static_key_slow_inc(&i2c_trace_msg);
85 void i2c_transfer_trace_unreg(void)
87 static_key_slow_dec(&i2c_trace_msg);
90 #if defined(CONFIG_ACPI)
91 struct i2c_acpi_handler_data {
92 struct acpi_connection_info info;
93 struct i2c_adapter *adapter;
106 struct i2c_acpi_lookup {
107 struct i2c_board_info *info;
108 acpi_handle adapter_handle;
109 acpi_handle device_handle;
110 acpi_handle search_handle;
115 static int i2c_acpi_fill_info(struct acpi_resource *ares, void *data)
117 struct i2c_acpi_lookup *lookup = data;
118 struct i2c_board_info *info = lookup->info;
119 struct acpi_resource_i2c_serialbus *sb;
122 if (info->addr || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
125 sb = &ares->data.i2c_serial_bus;
126 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C)
129 status = acpi_get_handle(lookup->device_handle,
130 sb->resource_source.string_ptr,
131 &lookup->adapter_handle);
132 if (!ACPI_SUCCESS(status))
135 info->addr = sb->slave_address;
136 lookup->speed = sb->connection_speed;
137 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
138 info->flags |= I2C_CLIENT_TEN;
143 static int i2c_acpi_do_lookup(struct acpi_device *adev,
144 struct i2c_acpi_lookup *lookup)
146 struct i2c_board_info *info = lookup->info;
147 struct list_head resource_list;
150 if (acpi_bus_get_status(adev) || !adev->status.present ||
151 acpi_device_enumerated(adev))
154 memset(info, 0, sizeof(*info));
155 lookup->device_handle = acpi_device_handle(adev);
157 /* Look up for I2cSerialBus resource */
158 INIT_LIST_HEAD(&resource_list);
159 ret = acpi_dev_get_resources(adev, &resource_list,
160 i2c_acpi_fill_info, lookup);
161 acpi_dev_free_resource_list(&resource_list);
163 if (ret < 0 || !info->addr)
169 static int i2c_acpi_get_info(struct acpi_device *adev,
170 struct i2c_board_info *info,
171 struct i2c_adapter *adapter,
172 acpi_handle *adapter_handle)
174 struct list_head resource_list;
175 struct resource_entry *entry;
176 struct i2c_acpi_lookup lookup;
179 memset(&lookup, 0, sizeof(lookup));
182 ret = i2c_acpi_do_lookup(adev, &lookup);
187 /* The adapter must match the one in I2cSerialBus() connector */
188 if (ACPI_HANDLE(&adapter->dev) != lookup.adapter_handle)
191 struct acpi_device *adapter_adev;
193 /* The adapter must be present */
194 if (acpi_bus_get_device(lookup.adapter_handle, &adapter_adev))
196 if (acpi_bus_get_status(adapter_adev) ||
197 !adapter_adev->status.present)
201 info->fwnode = acpi_fwnode_handle(adev);
203 *adapter_handle = lookup.adapter_handle;
205 /* Then fill IRQ number if any */
206 INIT_LIST_HEAD(&resource_list);
207 ret = acpi_dev_get_resources(adev, &resource_list, NULL, NULL);
211 resource_list_for_each_entry(entry, &resource_list) {
212 if (resource_type(entry->res) == IORESOURCE_IRQ) {
213 info->irq = entry->res->start;
218 acpi_dev_free_resource_list(&resource_list);
220 strlcpy(info->type, dev_name(&adev->dev), sizeof(info->type));
225 static void i2c_acpi_register_device(struct i2c_adapter *adapter,
226 struct acpi_device *adev,
227 struct i2c_board_info *info)
229 adev->power.flags.ignore_parent = true;
230 acpi_device_set_enumerated(adev);
232 if (!i2c_new_device(adapter, info)) {
233 adev->power.flags.ignore_parent = false;
234 dev_err(&adapter->dev,
235 "failed to add I2C device %s from ACPI\n",
236 dev_name(&adev->dev));
240 static acpi_status i2c_acpi_add_device(acpi_handle handle, u32 level,
241 void *data, void **return_value)
243 struct i2c_adapter *adapter = data;
244 struct acpi_device *adev;
245 struct i2c_board_info info;
247 if (acpi_bus_get_device(handle, &adev))
250 if (i2c_acpi_get_info(adev, &info, adapter, NULL))
253 i2c_acpi_register_device(adapter, adev, &info);
258 #define I2C_ACPI_MAX_SCAN_DEPTH 32
261 * i2c_acpi_register_devices - enumerate I2C slave devices behind adapter
262 * @adap: pointer to adapter
264 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
265 * namespace. When a device is found it will be added to the Linux device
266 * model and bound to the corresponding ACPI handle.
268 static void i2c_acpi_register_devices(struct i2c_adapter *adap)
272 if (!has_acpi_companion(&adap->dev))
275 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
276 I2C_ACPI_MAX_SCAN_DEPTH,
277 i2c_acpi_add_device, NULL,
279 if (ACPI_FAILURE(status))
280 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
283 static acpi_status i2c_acpi_lookup_speed(acpi_handle handle, u32 level,
284 void *data, void **return_value)
286 struct i2c_acpi_lookup *lookup = data;
287 struct acpi_device *adev;
289 if (acpi_bus_get_device(handle, &adev))
292 if (i2c_acpi_do_lookup(adev, lookup))
295 if (lookup->search_handle != lookup->adapter_handle)
298 if (lookup->speed <= lookup->min_speed)
299 lookup->min_speed = lookup->speed;
305 * i2c_acpi_find_bus_speed - find I2C bus speed from ACPI
306 * @dev: The device owning the bus
308 * Find the I2C bus speed by walking the ACPI namespace for all I2C slaves
309 * devices connected to this bus and use the speed of slowest device.
311 * Returns the speed in Hz or zero
313 u32 i2c_acpi_find_bus_speed(struct device *dev)
315 struct i2c_acpi_lookup lookup;
316 struct i2c_board_info dummy;
319 if (!has_acpi_companion(dev))
322 memset(&lookup, 0, sizeof(lookup));
323 lookup.search_handle = ACPI_HANDLE(dev);
324 lookup.min_speed = UINT_MAX;
325 lookup.info = &dummy;
327 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
328 I2C_ACPI_MAX_SCAN_DEPTH,
329 i2c_acpi_lookup_speed, NULL,
332 if (ACPI_FAILURE(status)) {
333 dev_warn(dev, "unable to find I2C bus speed from ACPI\n");
337 return lookup.min_speed != UINT_MAX ? lookup.min_speed : 0;
339 EXPORT_SYMBOL_GPL(i2c_acpi_find_bus_speed);
341 static int i2c_acpi_match_adapter(struct device *dev, void *data)
343 struct i2c_adapter *adapter = i2c_verify_adapter(dev);
348 return ACPI_HANDLE(dev) == (acpi_handle)data;
351 static int i2c_acpi_match_device(struct device *dev, void *data)
353 return ACPI_COMPANION(dev) == data;
356 static struct i2c_adapter *i2c_acpi_find_adapter_by_handle(acpi_handle handle)
360 dev = bus_find_device(&i2c_bus_type, NULL, handle,
361 i2c_acpi_match_adapter);
362 return dev ? i2c_verify_adapter(dev) : NULL;
365 static struct i2c_client *i2c_acpi_find_client_by_adev(struct acpi_device *adev)
369 dev = bus_find_device(&i2c_bus_type, NULL, adev, i2c_acpi_match_device);
370 return dev ? i2c_verify_client(dev) : NULL;
373 static int i2c_acpi_notify(struct notifier_block *nb, unsigned long value,
376 struct acpi_device *adev = arg;
377 struct i2c_board_info info;
378 acpi_handle adapter_handle;
379 struct i2c_adapter *adapter;
380 struct i2c_client *client;
383 case ACPI_RECONFIG_DEVICE_ADD:
384 if (i2c_acpi_get_info(adev, &info, NULL, &adapter_handle))
387 adapter = i2c_acpi_find_adapter_by_handle(adapter_handle);
391 i2c_acpi_register_device(adapter, adev, &info);
393 case ACPI_RECONFIG_DEVICE_REMOVE:
394 if (!acpi_device_enumerated(adev))
397 client = i2c_acpi_find_client_by_adev(adev);
401 i2c_unregister_device(client);
402 put_device(&client->dev);
409 static struct notifier_block i2c_acpi_notifier = {
410 .notifier_call = i2c_acpi_notify,
412 #else /* CONFIG_ACPI */
413 static inline void i2c_acpi_register_devices(struct i2c_adapter *adap) { }
414 extern struct notifier_block i2c_acpi_notifier;
415 #endif /* CONFIG_ACPI */
417 #ifdef CONFIG_ACPI_I2C_OPREGION
418 static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
419 u8 cmd, u8 *data, u8 data_len)
422 struct i2c_msg msgs[2];
426 buffer = kzalloc(data_len, GFP_KERNEL);
430 msgs[0].addr = client->addr;
431 msgs[0].flags = client->flags;
435 msgs[1].addr = client->addr;
436 msgs[1].flags = client->flags | I2C_M_RD;
437 msgs[1].len = data_len;
438 msgs[1].buf = buffer;
440 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
442 dev_err(&client->adapter->dev, "i2c read failed\n");
444 memcpy(data, buffer, data_len);
450 static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
451 u8 cmd, u8 *data, u8 data_len)
454 struct i2c_msg msgs[1];
458 buffer = kzalloc(data_len + 1, GFP_KERNEL);
463 memcpy(buffer + 1, data, data_len);
465 msgs[0].addr = client->addr;
466 msgs[0].flags = client->flags;
467 msgs[0].len = data_len + 1;
468 msgs[0].buf = buffer;
470 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
472 dev_err(&client->adapter->dev, "i2c write failed\n");
479 i2c_acpi_space_handler(u32 function, acpi_physical_address command,
480 u32 bits, u64 *value64,
481 void *handler_context, void *region_context)
483 struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
484 struct i2c_acpi_handler_data *data = handler_context;
485 struct acpi_connection_info *info = &data->info;
486 struct acpi_resource_i2c_serialbus *sb;
487 struct i2c_adapter *adapter = data->adapter;
488 struct i2c_client *client;
489 struct acpi_resource *ares;
490 u32 accessor_type = function >> 16;
491 u8 action = function & ACPI_IO_MASK;
495 ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
496 if (ACPI_FAILURE(ret))
499 client = kzalloc(sizeof(*client), GFP_KERNEL);
505 if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
506 ret = AE_BAD_PARAMETER;
510 sb = &ares->data.i2c_serial_bus;
511 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
512 ret = AE_BAD_PARAMETER;
516 client->adapter = adapter;
517 client->addr = sb->slave_address;
519 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
520 client->flags |= I2C_CLIENT_TEN;
522 switch (accessor_type) {
523 case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
524 if (action == ACPI_READ) {
525 status = i2c_smbus_read_byte(client);
531 status = i2c_smbus_write_byte(client, gsb->bdata);
535 case ACPI_GSB_ACCESS_ATTRIB_BYTE:
536 if (action == ACPI_READ) {
537 status = i2c_smbus_read_byte_data(client, command);
543 status = i2c_smbus_write_byte_data(client, command,
548 case ACPI_GSB_ACCESS_ATTRIB_WORD:
549 if (action == ACPI_READ) {
550 status = i2c_smbus_read_word_data(client, command);
556 status = i2c_smbus_write_word_data(client, command,
561 case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
562 if (action == ACPI_READ) {
563 status = i2c_smbus_read_block_data(client, command,
570 status = i2c_smbus_write_block_data(client, command,
571 gsb->len, gsb->data);
575 case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
576 if (action == ACPI_READ) {
577 status = acpi_gsb_i2c_read_bytes(client, command,
578 gsb->data, info->access_length);
582 status = acpi_gsb_i2c_write_bytes(client, command,
583 gsb->data, info->access_length);
588 dev_warn(&adapter->dev, "protocol 0x%02x not supported for client 0x%02x\n",
589 accessor_type, client->addr);
590 ret = AE_BAD_PARAMETER;
594 gsb->status = status;
603 static int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
606 struct i2c_acpi_handler_data *data;
609 if (!adapter->dev.parent)
612 handle = ACPI_HANDLE(adapter->dev.parent);
617 data = kzalloc(sizeof(struct i2c_acpi_handler_data),
622 data->adapter = adapter;
623 status = acpi_bus_attach_private_data(handle, (void *)data);
624 if (ACPI_FAILURE(status)) {
629 status = acpi_install_address_space_handler(handle,
630 ACPI_ADR_SPACE_GSBUS,
631 &i2c_acpi_space_handler,
634 if (ACPI_FAILURE(status)) {
635 dev_err(&adapter->dev, "Error installing i2c space handler\n");
636 acpi_bus_detach_private_data(handle);
641 acpi_walk_dep_device_list(handle);
645 static void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
648 struct i2c_acpi_handler_data *data;
651 if (!adapter->dev.parent)
654 handle = ACPI_HANDLE(adapter->dev.parent);
659 acpi_remove_address_space_handler(handle,
660 ACPI_ADR_SPACE_GSBUS,
661 &i2c_acpi_space_handler);
663 status = acpi_bus_get_private_data(handle, (void **)&data);
664 if (ACPI_SUCCESS(status))
667 acpi_bus_detach_private_data(handle);
669 #else /* CONFIG_ACPI_I2C_OPREGION */
670 static inline void i2c_acpi_remove_space_handler(struct i2c_adapter *adapter)
673 static inline int i2c_acpi_install_space_handler(struct i2c_adapter *adapter)
675 #endif /* CONFIG_ACPI_I2C_OPREGION */
677 /* ------------------------------------------------------------------------- */
679 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
680 const struct i2c_client *client)
685 while (id->name[0]) {
686 if (strcmp(client->name, id->name) == 0)
693 static int i2c_device_match(struct device *dev, struct device_driver *drv)
695 struct i2c_client *client = i2c_verify_client(dev);
696 struct i2c_driver *driver;
699 /* Attempt an OF style match */
700 if (of_driver_match_device(dev, drv))
703 /* Then ACPI style match */
704 if (acpi_driver_match_device(dev, drv))
707 driver = to_i2c_driver(drv);
709 /* Finally an I2C match */
710 if (i2c_match_id(driver->id_table, client))
716 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
718 struct i2c_client *client = to_i2c_client(dev);
721 rc = acpi_device_uevent_modalias(dev, env);
725 return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
728 /* i2c bus recovery routines */
729 static int get_scl_gpio_value(struct i2c_adapter *adap)
731 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
734 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
736 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
739 static int get_sda_gpio_value(struct i2c_adapter *adap)
741 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
744 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
746 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
747 struct device *dev = &adap->dev;
750 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
751 GPIOF_OUT_INIT_HIGH, "i2c-scl");
753 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
758 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
759 /* work without SDA polling */
760 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
769 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
771 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
774 gpio_free(bri->sda_gpio);
776 gpio_free(bri->scl_gpio);
780 * We are generating clock pulses. ndelay() determines durating of clk pulses.
781 * We will generate clock with rate 100 KHz and so duration of both clock levels
782 * is: delay in ns = (10^6 / 100) / 2
784 #define RECOVERY_NDELAY 5000
785 #define RECOVERY_CLK_CNT 9
787 static int i2c_generic_recovery(struct i2c_adapter *adap)
789 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
790 int i = 0, val = 1, ret = 0;
792 if (bri->prepare_recovery)
793 bri->prepare_recovery(adap);
795 bri->set_scl(adap, val);
796 ndelay(RECOVERY_NDELAY);
799 * By this time SCL is high, as we need to give 9 falling-rising edges
801 while (i++ < RECOVERY_CLK_CNT * 2) {
803 /* Break if SDA is high */
804 if (bri->get_sda && bri->get_sda(adap))
806 /* SCL shouldn't be low here */
807 if (!bri->get_scl(adap)) {
809 "SCL is stuck low, exit recovery\n");
816 bri->set_scl(adap, val);
817 ndelay(RECOVERY_NDELAY);
820 if (bri->unprepare_recovery)
821 bri->unprepare_recovery(adap);
826 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
828 return i2c_generic_recovery(adap);
830 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
832 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
836 ret = i2c_get_gpios_for_recovery(adap);
840 ret = i2c_generic_recovery(adap);
841 i2c_put_gpios_for_recovery(adap);
845 EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
847 int i2c_recover_bus(struct i2c_adapter *adap)
849 if (!adap->bus_recovery_info)
852 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
853 return adap->bus_recovery_info->recover_bus(adap);
855 EXPORT_SYMBOL_GPL(i2c_recover_bus);
857 static void i2c_init_recovery(struct i2c_adapter *adap)
859 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
865 if (!bri->recover_bus) {
866 err_str = "no recover_bus() found";
870 /* Generic GPIO recovery */
871 if (bri->recover_bus == i2c_generic_gpio_recovery) {
872 if (!gpio_is_valid(bri->scl_gpio)) {
873 err_str = "invalid SCL gpio";
877 if (gpio_is_valid(bri->sda_gpio))
878 bri->get_sda = get_sda_gpio_value;
882 bri->get_scl = get_scl_gpio_value;
883 bri->set_scl = set_scl_gpio_value;
884 } else if (bri->recover_bus == i2c_generic_scl_recovery) {
885 /* Generic SCL recovery */
886 if (!bri->set_scl || !bri->get_scl) {
887 err_str = "no {get|set}_scl() found";
894 dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
895 adap->bus_recovery_info = NULL;
898 static int i2c_device_probe(struct device *dev)
900 struct i2c_client *client = i2c_verify_client(dev);
901 struct i2c_driver *driver;
911 irq = of_irq_get_byname(dev->of_node, "irq");
912 if (irq == -EINVAL || irq == -ENODATA)
913 irq = of_irq_get(dev->of_node, 0);
914 } else if (ACPI_COMPANION(dev)) {
915 irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
917 if (irq == -EPROBE_DEFER)
925 driver = to_i2c_driver(dev->driver);
926 if (!driver->probe || !driver->id_table)
929 if (client->flags & I2C_CLIENT_WAKE) {
930 int wakeirq = -ENOENT;
933 wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
934 if (wakeirq == -EPROBE_DEFER)
938 device_init_wakeup(&client->dev, true);
940 if (wakeirq > 0 && wakeirq != client->irq)
941 status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
942 else if (client->irq > 0)
943 status = dev_pm_set_wake_irq(dev, client->irq);
948 dev_warn(&client->dev, "failed to set up wakeup irq\n");
951 dev_dbg(dev, "probe\n");
953 status = of_clk_set_defaults(dev->of_node, false);
955 goto err_clear_wakeup_irq;
957 status = dev_pm_domain_attach(&client->dev, true);
958 if (status == -EPROBE_DEFER)
959 goto err_clear_wakeup_irq;
961 status = driver->probe(client, i2c_match_id(driver->id_table, client));
963 goto err_detach_pm_domain;
967 err_detach_pm_domain:
968 dev_pm_domain_detach(&client->dev, true);
969 err_clear_wakeup_irq:
970 dev_pm_clear_wake_irq(&client->dev);
971 device_init_wakeup(&client->dev, false);
975 static int i2c_device_remove(struct device *dev)
977 struct i2c_client *client = i2c_verify_client(dev);
978 struct i2c_driver *driver;
981 if (!client || !dev->driver)
984 driver = to_i2c_driver(dev->driver);
985 if (driver->remove) {
986 dev_dbg(dev, "remove\n");
987 status = driver->remove(client);
990 dev_pm_domain_detach(&client->dev, true);
992 dev_pm_clear_wake_irq(&client->dev);
993 device_init_wakeup(&client->dev, false);
998 static void i2c_device_shutdown(struct device *dev)
1000 struct i2c_client *client = i2c_verify_client(dev);
1001 struct i2c_driver *driver;
1003 if (!client || !dev->driver)
1005 driver = to_i2c_driver(dev->driver);
1006 if (driver->shutdown)
1007 driver->shutdown(client);
1010 static void i2c_client_dev_release(struct device *dev)
1012 kfree(to_i2c_client(dev));
1016 show_name(struct device *dev, struct device_attribute *attr, char *buf)
1018 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
1019 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
1021 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
1024 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
1026 struct i2c_client *client = to_i2c_client(dev);
1029 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
1033 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
1035 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
1037 static struct attribute *i2c_dev_attrs[] = {
1038 &dev_attr_name.attr,
1039 /* modalias helps coldplug: modprobe $(cat .../modalias) */
1040 &dev_attr_modalias.attr,
1043 ATTRIBUTE_GROUPS(i2c_dev);
1045 struct bus_type i2c_bus_type = {
1047 .match = i2c_device_match,
1048 .probe = i2c_device_probe,
1049 .remove = i2c_device_remove,
1050 .shutdown = i2c_device_shutdown,
1052 EXPORT_SYMBOL_GPL(i2c_bus_type);
1054 static struct device_type i2c_client_type = {
1055 .groups = i2c_dev_groups,
1056 .uevent = i2c_device_uevent,
1057 .release = i2c_client_dev_release,
1062 * i2c_verify_client - return parameter as i2c_client, or NULL
1063 * @dev: device, probably from some driver model iterator
1065 * When traversing the driver model tree, perhaps using driver model
1066 * iterators like @device_for_each_child(), you can't assume very much
1067 * about the nodes you find. Use this function to avoid oopses caused
1068 * by wrongly treating some non-I2C device as an i2c_client.
1070 struct i2c_client *i2c_verify_client(struct device *dev)
1072 return (dev->type == &i2c_client_type)
1073 ? to_i2c_client(dev)
1076 EXPORT_SYMBOL(i2c_verify_client);
1079 /* Return a unique address which takes the flags of the client into account */
1080 static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
1082 unsigned short addr = client->addr;
1084 /* For some client flags, add an arbitrary offset to avoid collisions */
1085 if (client->flags & I2C_CLIENT_TEN)
1086 addr |= I2C_ADDR_OFFSET_TEN_BIT;
1088 if (client->flags & I2C_CLIENT_SLAVE)
1089 addr |= I2C_ADDR_OFFSET_SLAVE;
1094 /* This is a permissive address validity check, I2C address map constraints
1095 * are purposely not enforced, except for the general call address. */
1096 static int i2c_check_addr_validity(unsigned addr, unsigned short flags)
1098 if (flags & I2C_CLIENT_TEN) {
1099 /* 10-bit address, all values are valid */
1103 /* 7-bit address, reject the general call address */
1104 if (addr == 0x00 || addr > 0x7f)
1110 /* And this is a strict address validity check, used when probing. If a
1111 * device uses a reserved address, then it shouldn't be probed. 7-bit
1112 * addressing is assumed, 10-bit address devices are rare and should be
1113 * explicitly enumerated. */
1114 static int i2c_check_7bit_addr_validity_strict(unsigned short addr)
1117 * Reserved addresses per I2C specification:
1118 * 0x00 General call address / START byte
1120 * 0x02 Reserved for different bus format
1121 * 0x03 Reserved for future purposes
1122 * 0x04-0x07 Hs-mode master code
1123 * 0x78-0x7b 10-bit slave addressing
1124 * 0x7c-0x7f Reserved for future purposes
1126 if (addr < 0x08 || addr > 0x77)
1131 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
1133 struct i2c_client *client = i2c_verify_client(dev);
1134 int addr = *(int *)addrp;
1136 if (client && i2c_encode_flags_to_addr(client) == addr)
1141 /* walk up mux tree */
1142 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
1144 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1147 result = device_for_each_child(&adapter->dev, &addr,
1148 __i2c_check_addr_busy);
1150 if (!result && parent)
1151 result = i2c_check_mux_parents(parent, addr);
1156 /* recurse down mux tree */
1157 static int i2c_check_mux_children(struct device *dev, void *addrp)
1161 if (dev->type == &i2c_adapter_type)
1162 result = device_for_each_child(dev, addrp,
1163 i2c_check_mux_children);
1165 result = __i2c_check_addr_busy(dev, addrp);
1170 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
1172 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1176 result = i2c_check_mux_parents(parent, addr);
1179 result = device_for_each_child(&adapter->dev, &addr,
1180 i2c_check_mux_children);
1186 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
1187 * @adapter: Target I2C bus segment
1188 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
1189 * locks only this branch in the adapter tree
1191 static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
1194 rt_mutex_lock(&adapter->bus_lock);
1198 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
1199 * @adapter: Target I2C bus segment
1200 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
1201 * trylocks only this branch in the adapter tree
1203 static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
1206 return rt_mutex_trylock(&adapter->bus_lock);
1210 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
1211 * @adapter: Target I2C bus segment
1212 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
1213 * unlocks only this branch in the adapter tree
1215 static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
1218 rt_mutex_unlock(&adapter->bus_lock);
1221 static void i2c_dev_set_name(struct i2c_adapter *adap,
1222 struct i2c_client *client)
1224 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
1227 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
1231 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
1232 i2c_encode_flags_to_addr(client));
1236 * i2c_new_device - instantiate an i2c device
1237 * @adap: the adapter managing the device
1238 * @info: describes one I2C device; bus_num is ignored
1239 * Context: can sleep
1241 * Create an i2c device. Binding is handled through driver model
1242 * probe()/remove() methods. A driver may be bound to this device when we
1243 * return from this function, or any later moment (e.g. maybe hotplugging will
1244 * load the driver module). This call is not appropriate for use by mainboard
1245 * initialization logic, which usually runs during an arch_initcall() long
1246 * before any i2c_adapter could exist.
1248 * This returns the new i2c client, which may be saved for later use with
1249 * i2c_unregister_device(); or NULL to indicate an error.
1252 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1254 struct i2c_client *client;
1257 client = kzalloc(sizeof *client, GFP_KERNEL);
1261 client->adapter = adap;
1263 client->dev.platform_data = info->platform_data;
1266 client->dev.archdata = *info->archdata;
1268 client->flags = info->flags;
1269 client->addr = info->addr;
1270 client->irq = info->irq;
1272 strlcpy(client->name, info->type, sizeof(client->name));
1274 status = i2c_check_addr_validity(client->addr, client->flags);
1276 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1277 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1278 goto out_err_silent;
1281 /* Check for address business */
1282 status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
1286 client->dev.parent = &client->adapter->dev;
1287 client->dev.bus = &i2c_bus_type;
1288 client->dev.type = &i2c_client_type;
1289 client->dev.of_node = info->of_node;
1290 client->dev.fwnode = info->fwnode;
1292 i2c_dev_set_name(adap, client);
1293 status = device_register(&client->dev);
1297 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1298 client->name, dev_name(&client->dev));
1304 "Failed to register i2c client %s at 0x%02x (%d)\n",
1305 client->name, client->addr, status);
1310 EXPORT_SYMBOL_GPL(i2c_new_device);
1314 * i2c_unregister_device - reverse effect of i2c_new_device()
1315 * @client: value returned from i2c_new_device()
1316 * Context: can sleep
1318 void i2c_unregister_device(struct i2c_client *client)
1320 if (client->dev.of_node)
1321 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
1322 if (ACPI_COMPANION(&client->dev))
1323 acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
1324 device_unregister(&client->dev);
1326 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1329 static const struct i2c_device_id dummy_id[] = {
1334 static int dummy_probe(struct i2c_client *client,
1335 const struct i2c_device_id *id)
1340 static int dummy_remove(struct i2c_client *client)
1345 static struct i2c_driver dummy_driver = {
1346 .driver.name = "dummy",
1347 .probe = dummy_probe,
1348 .remove = dummy_remove,
1349 .id_table = dummy_id,
1353 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1354 * @adapter: the adapter managing the device
1355 * @address: seven bit address to be used
1356 * Context: can sleep
1358 * This returns an I2C client bound to the "dummy" driver, intended for use
1359 * with devices that consume multiple addresses. Examples of such chips
1360 * include various EEPROMS (like 24c04 and 24c08 models).
1362 * These dummy devices have two main uses. First, most I2C and SMBus calls
1363 * except i2c_transfer() need a client handle; the dummy will be that handle.
1364 * And second, this prevents the specified address from being bound to a
1367 * This returns the new i2c client, which should be saved for later use with
1368 * i2c_unregister_device(); or NULL to indicate an error.
1370 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1372 struct i2c_board_info info = {
1373 I2C_BOARD_INFO("dummy", address),
1376 return i2c_new_device(adapter, &info);
1378 EXPORT_SYMBOL_GPL(i2c_new_dummy);
1381 * i2c_new_secondary_device - Helper to get the instantiated secondary address
1382 * and create the associated device
1383 * @client: Handle to the primary client
1384 * @name: Handle to specify which secondary address to get
1385 * @default_addr: Used as a fallback if no secondary address was specified
1386 * Context: can sleep
1388 * I2C clients can be composed of multiple I2C slaves bound together in a single
1389 * component. The I2C client driver then binds to the master I2C slave and needs
1390 * to create I2C dummy clients to communicate with all the other slaves.
1392 * This function creates and returns an I2C dummy client whose I2C address is
1393 * retrieved from the platform firmware based on the given slave name. If no
1394 * address is specified by the firmware default_addr is used.
1396 * On DT-based platforms the address is retrieved from the "reg" property entry
1397 * cell whose "reg-names" value matches the slave name.
1399 * This returns the new i2c client, which should be saved for later use with
1400 * i2c_unregister_device(); or NULL to indicate an error.
1402 struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
1406 struct device_node *np = client->dev.of_node;
1407 u32 addr = default_addr;
1411 i = of_property_match_string(np, "reg-names", name);
1413 of_property_read_u32_index(np, "reg", i, &addr);
1416 dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1417 return i2c_new_dummy(client->adapter, addr);
1419 EXPORT_SYMBOL_GPL(i2c_new_secondary_device);
1421 /* ------------------------------------------------------------------------- */
1423 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1425 static void i2c_adapter_dev_release(struct device *dev)
1427 struct i2c_adapter *adap = to_i2c_adapter(dev);
1428 complete(&adap->dev_released);
1431 unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1433 unsigned int depth = 0;
1435 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1438 WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
1439 "adapter depth exceeds lockdep subclass limit\n");
1443 EXPORT_SYMBOL_GPL(i2c_adapter_depth);
1446 * Let users instantiate I2C devices through sysfs. This can be used when
1447 * platform initialization code doesn't contain the proper data for
1448 * whatever reason. Also useful for drivers that do device detection and
1449 * detection fails, either because the device uses an unexpected address,
1450 * or this is a compatible device with different ID register values.
1452 * Parameter checking may look overzealous, but we really don't want
1453 * the user to provide incorrect parameters.
1456 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1457 const char *buf, size_t count)
1459 struct i2c_adapter *adap = to_i2c_adapter(dev);
1460 struct i2c_board_info info;
1461 struct i2c_client *client;
1465 memset(&info, 0, sizeof(struct i2c_board_info));
1467 blank = strchr(buf, ' ');
1469 dev_err(dev, "%s: Missing parameters\n", "new_device");
1472 if (blank - buf > I2C_NAME_SIZE - 1) {
1473 dev_err(dev, "%s: Invalid device name\n", "new_device");
1476 memcpy(info.type, buf, blank - buf);
1478 /* Parse remaining parameters, reject extra parameters */
1479 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1481 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1484 if (res > 1 && end != '\n') {
1485 dev_err(dev, "%s: Extra parameters\n", "new_device");
1489 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1490 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1491 info.flags |= I2C_CLIENT_TEN;
1494 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1495 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1496 info.flags |= I2C_CLIENT_SLAVE;
1499 client = i2c_new_device(adap, &info);
1503 /* Keep track of the added device */
1504 mutex_lock(&adap->userspace_clients_lock);
1505 list_add_tail(&client->detected, &adap->userspace_clients);
1506 mutex_unlock(&adap->userspace_clients_lock);
1507 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1508 info.type, info.addr);
1512 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1515 * And of course let the users delete the devices they instantiated, if
1516 * they got it wrong. This interface can only be used to delete devices
1517 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1518 * don't delete devices to which some kernel code still has references.
1520 * Parameter checking may look overzealous, but we really don't want
1521 * the user to delete the wrong device.
1524 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1525 const char *buf, size_t count)
1527 struct i2c_adapter *adap = to_i2c_adapter(dev);
1528 struct i2c_client *client, *next;
1529 unsigned short addr;
1533 /* Parse parameters, reject extra parameters */
1534 res = sscanf(buf, "%hi%c", &addr, &end);
1536 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1539 if (res > 1 && end != '\n') {
1540 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1544 /* Make sure the device was added through sysfs */
1546 mutex_lock_nested(&adap->userspace_clients_lock,
1547 i2c_adapter_depth(adap));
1548 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1550 if (i2c_encode_flags_to_addr(client) == addr) {
1551 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1552 "delete_device", client->name, client->addr);
1554 list_del(&client->detected);
1555 i2c_unregister_device(client);
1560 mutex_unlock(&adap->userspace_clients_lock);
1563 dev_err(dev, "%s: Can't find device in list\n",
1567 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1568 i2c_sysfs_delete_device);
1570 static struct attribute *i2c_adapter_attrs[] = {
1571 &dev_attr_name.attr,
1572 &dev_attr_new_device.attr,
1573 &dev_attr_delete_device.attr,
1576 ATTRIBUTE_GROUPS(i2c_adapter);
1578 struct device_type i2c_adapter_type = {
1579 .groups = i2c_adapter_groups,
1580 .release = i2c_adapter_dev_release,
1582 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1585 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1586 * @dev: device, probably from some driver model iterator
1588 * When traversing the driver model tree, perhaps using driver model
1589 * iterators like @device_for_each_child(), you can't assume very much
1590 * about the nodes you find. Use this function to avoid oopses caused
1591 * by wrongly treating some non-I2C device as an i2c_adapter.
1593 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1595 return (dev->type == &i2c_adapter_type)
1596 ? to_i2c_adapter(dev)
1599 EXPORT_SYMBOL(i2c_verify_adapter);
1601 #ifdef CONFIG_I2C_COMPAT
1602 static struct class_compat *i2c_adapter_compat_class;
1605 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1607 struct i2c_devinfo *devinfo;
1609 down_read(&__i2c_board_lock);
1610 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1611 if (devinfo->busnum == adapter->nr
1612 && !i2c_new_device(adapter,
1613 &devinfo->board_info))
1614 dev_err(&adapter->dev,
1615 "Can't create device at 0x%02x\n",
1616 devinfo->board_info.addr);
1618 up_read(&__i2c_board_lock);
1621 /* OF support code */
1623 #if IS_ENABLED(CONFIG_OF)
1624 static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1625 struct device_node *node)
1627 struct i2c_client *result;
1628 struct i2c_board_info info = {};
1629 struct dev_archdata dev_ad = {};
1630 const __be32 *addr_be;
1634 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1636 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1637 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1639 return ERR_PTR(-EINVAL);
1642 addr_be = of_get_property(node, "reg", &len);
1643 if (!addr_be || (len < sizeof(*addr_be))) {
1644 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1646 return ERR_PTR(-EINVAL);
1649 addr = be32_to_cpup(addr_be);
1650 if (addr & I2C_TEN_BIT_ADDRESS) {
1651 addr &= ~I2C_TEN_BIT_ADDRESS;
1652 info.flags |= I2C_CLIENT_TEN;
1655 if (addr & I2C_OWN_SLAVE_ADDRESS) {
1656 addr &= ~I2C_OWN_SLAVE_ADDRESS;
1657 info.flags |= I2C_CLIENT_SLAVE;
1660 if (i2c_check_addr_validity(addr, info.flags)) {
1661 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1662 info.addr, node->full_name);
1663 return ERR_PTR(-EINVAL);
1667 info.of_node = of_node_get(node);
1668 info.archdata = &dev_ad;
1670 if (of_get_property(node, "wakeup-source", NULL))
1671 info.flags |= I2C_CLIENT_WAKE;
1673 result = i2c_new_device(adap, &info);
1674 if (result == NULL) {
1675 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1678 return ERR_PTR(-EINVAL);
1683 static void of_i2c_register_devices(struct i2c_adapter *adap)
1685 struct device_node *bus, *node;
1686 struct i2c_client *client;
1688 /* Only register child devices if the adapter has a node pointer set */
1689 if (!adap->dev.of_node)
1692 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1694 bus = of_get_child_by_name(adap->dev.of_node, "i2c-bus");
1696 bus = of_node_get(adap->dev.of_node);
1698 for_each_available_child_of_node(bus, node) {
1699 if (of_node_test_and_set_flag(node, OF_POPULATED))
1702 client = of_i2c_register_device(adap, node);
1703 if (IS_ERR(client)) {
1704 dev_warn(&adap->dev,
1705 "Failed to create I2C device for %s\n",
1707 of_node_clear_flag(node, OF_POPULATED);
1714 static int of_dev_node_match(struct device *dev, void *data)
1716 return dev->of_node == data;
1719 /* must call put_device() when done with returned i2c_client device */
1720 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1723 struct i2c_client *client;
1725 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1729 client = i2c_verify_client(dev);
1735 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1737 /* must call put_device() when done with returned i2c_adapter device */
1738 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1741 struct i2c_adapter *adapter;
1743 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1747 adapter = i2c_verify_adapter(dev);
1753 EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1755 /* must call i2c_put_adapter() when done with returned i2c_adapter device */
1756 struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1758 struct i2c_adapter *adapter;
1760 adapter = of_find_i2c_adapter_by_node(node);
1764 if (!try_module_get(adapter->owner)) {
1765 put_device(&adapter->dev);
1771 EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1773 static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1774 #endif /* CONFIG_OF */
1776 static int i2c_do_add_adapter(struct i2c_driver *driver,
1777 struct i2c_adapter *adap)
1779 /* Detect supported devices on that bus, and instantiate them */
1780 i2c_detect(adap, driver);
1782 /* Let legacy drivers scan this bus for matching devices */
1783 if (driver->attach_adapter) {
1784 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1785 driver->driver.name);
1786 dev_warn(&adap->dev,
1787 "Please use another way to instantiate your i2c_client\n");
1788 /* We ignore the return code; if it fails, too bad */
1789 driver->attach_adapter(adap);
1794 static int __process_new_adapter(struct device_driver *d, void *data)
1796 return i2c_do_add_adapter(to_i2c_driver(d), data);
1799 static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1800 .lock_bus = i2c_adapter_lock_bus,
1801 .trylock_bus = i2c_adapter_trylock_bus,
1802 .unlock_bus = i2c_adapter_unlock_bus,
1805 static int i2c_register_adapter(struct i2c_adapter *adap)
1809 /* Can't register until after driver model init */
1810 if (WARN_ON(!is_registered)) {
1816 if (WARN(!adap->name[0], "i2c adapter has no name"))
1820 pr_err("adapter '%s': no algo supplied!\n", adap->name);
1824 if (!adap->lock_ops)
1825 adap->lock_ops = &i2c_adapter_lock_ops;
1827 rt_mutex_init(&adap->bus_lock);
1828 rt_mutex_init(&adap->mux_lock);
1829 mutex_init(&adap->userspace_clients_lock);
1830 INIT_LIST_HEAD(&adap->userspace_clients);
1832 /* Set default timeout to 1 second if not already set */
1833 if (adap->timeout == 0)
1836 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1837 adap->dev.bus = &i2c_bus_type;
1838 adap->dev.type = &i2c_adapter_type;
1839 res = device_register(&adap->dev);
1841 pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
1845 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1847 pm_runtime_no_callbacks(&adap->dev);
1848 pm_suspend_ignore_children(&adap->dev, true);
1849 pm_runtime_enable(&adap->dev);
1851 #ifdef CONFIG_I2C_COMPAT
1852 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1855 dev_warn(&adap->dev,
1856 "Failed to create compatibility class link\n");
1859 i2c_init_recovery(adap);
1861 /* create pre-declared device nodes */
1862 of_i2c_register_devices(adap);
1863 i2c_acpi_register_devices(adap);
1864 i2c_acpi_install_space_handler(adap);
1866 if (adap->nr < __i2c_first_dynamic_bus_num)
1867 i2c_scan_static_board_info(adap);
1869 /* Notify drivers */
1870 mutex_lock(&core_lock);
1871 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1872 mutex_unlock(&core_lock);
1877 mutex_lock(&core_lock);
1878 idr_remove(&i2c_adapter_idr, adap->nr);
1879 mutex_unlock(&core_lock);
1884 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1885 * @adap: the adapter to register (with adap->nr initialized)
1886 * Context: can sleep
1888 * See i2c_add_numbered_adapter() for details.
1890 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1894 mutex_lock(&core_lock);
1895 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
1896 mutex_unlock(&core_lock);
1897 if (WARN(id < 0, "couldn't get idr"))
1898 return id == -ENOSPC ? -EBUSY : id;
1900 return i2c_register_adapter(adap);
1904 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1905 * @adapter: the adapter to add
1906 * Context: can sleep
1908 * This routine is used to declare an I2C adapter when its bus number
1909 * doesn't matter or when its bus number is specified by an dt alias.
1910 * Examples of bases when the bus number doesn't matter: I2C adapters
1911 * dynamically added by USB links or PCI plugin cards.
1913 * When this returns zero, a new bus number was allocated and stored
1914 * in adap->nr, and the specified adapter became available for clients.
1915 * Otherwise, a negative errno value is returned.
1917 int i2c_add_adapter(struct i2c_adapter *adapter)
1919 struct device *dev = &adapter->dev;
1923 id = of_alias_get_id(dev->of_node, "i2c");
1926 return __i2c_add_numbered_adapter(adapter);
1930 mutex_lock(&core_lock);
1931 id = idr_alloc(&i2c_adapter_idr, adapter,
1932 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1933 mutex_unlock(&core_lock);
1934 if (WARN(id < 0, "couldn't get idr"))
1939 return i2c_register_adapter(adapter);
1941 EXPORT_SYMBOL(i2c_add_adapter);
1944 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1945 * @adap: the adapter to register (with adap->nr initialized)
1946 * Context: can sleep
1948 * This routine is used to declare an I2C adapter when its bus number
1949 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1950 * or otherwise built in to the system's mainboard, and where i2c_board_info
1951 * is used to properly configure I2C devices.
1953 * If the requested bus number is set to -1, then this function will behave
1954 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1956 * If no devices have pre-been declared for this bus, then be sure to
1957 * register the adapter before any dynamically allocated ones. Otherwise
1958 * the required bus ID may not be available.
1960 * When this returns zero, the specified adapter became available for
1961 * clients using the bus number provided in adap->nr. Also, the table
1962 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1963 * and the appropriate driver model device nodes are created. Otherwise, a
1964 * negative errno value is returned.
1966 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1968 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1969 return i2c_add_adapter(adap);
1971 return __i2c_add_numbered_adapter(adap);
1973 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1975 static void i2c_do_del_adapter(struct i2c_driver *driver,
1976 struct i2c_adapter *adapter)
1978 struct i2c_client *client, *_n;
1980 /* Remove the devices we created ourselves as the result of hardware
1981 * probing (using a driver's detect method) */
1982 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1983 if (client->adapter == adapter) {
1984 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1985 client->name, client->addr);
1986 list_del(&client->detected);
1987 i2c_unregister_device(client);
1992 static int __unregister_client(struct device *dev, void *dummy)
1994 struct i2c_client *client = i2c_verify_client(dev);
1995 if (client && strcmp(client->name, "dummy"))
1996 i2c_unregister_device(client);
2000 static int __unregister_dummy(struct device *dev, void *dummy)
2002 struct i2c_client *client = i2c_verify_client(dev);
2004 i2c_unregister_device(client);
2008 static int __process_removed_adapter(struct device_driver *d, void *data)
2010 i2c_do_del_adapter(to_i2c_driver(d), data);
2015 * i2c_del_adapter - unregister I2C adapter
2016 * @adap: the adapter being unregistered
2017 * Context: can sleep
2019 * This unregisters an I2C adapter which was previously registered
2020 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
2022 void i2c_del_adapter(struct i2c_adapter *adap)
2024 struct i2c_adapter *found;
2025 struct i2c_client *client, *next;
2027 /* First make sure that this adapter was ever added */
2028 mutex_lock(&core_lock);
2029 found = idr_find(&i2c_adapter_idr, adap->nr);
2030 mutex_unlock(&core_lock);
2031 if (found != adap) {
2032 pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
2036 i2c_acpi_remove_space_handler(adap);
2037 /* Tell drivers about this removal */
2038 mutex_lock(&core_lock);
2039 bus_for_each_drv(&i2c_bus_type, NULL, adap,
2040 __process_removed_adapter);
2041 mutex_unlock(&core_lock);
2043 /* Remove devices instantiated from sysfs */
2044 mutex_lock_nested(&adap->userspace_clients_lock,
2045 i2c_adapter_depth(adap));
2046 list_for_each_entry_safe(client, next, &adap->userspace_clients,
2048 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
2050 list_del(&client->detected);
2051 i2c_unregister_device(client);
2053 mutex_unlock(&adap->userspace_clients_lock);
2055 /* Detach any active clients. This can't fail, thus we do not
2056 * check the returned value. This is a two-pass process, because
2057 * we can't remove the dummy devices during the first pass: they
2058 * could have been instantiated by real devices wishing to clean
2059 * them up properly, so we give them a chance to do that first. */
2060 device_for_each_child(&adap->dev, NULL, __unregister_client);
2061 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
2063 #ifdef CONFIG_I2C_COMPAT
2064 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
2068 /* device name is gone after device_unregister */
2069 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
2071 pm_runtime_disable(&adap->dev);
2073 /* wait until all references to the device are gone
2075 * FIXME: This is old code and should ideally be replaced by an
2076 * alternative which results in decoupling the lifetime of the struct
2077 * device from the i2c_adapter, like spi or netdev do. Any solution
2078 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
2080 init_completion(&adap->dev_released);
2081 device_unregister(&adap->dev);
2082 wait_for_completion(&adap->dev_released);
2085 mutex_lock(&core_lock);
2086 idr_remove(&i2c_adapter_idr, adap->nr);
2087 mutex_unlock(&core_lock);
2089 /* Clear the device structure in case this adapter is ever going to be
2091 memset(&adap->dev, 0, sizeof(adap->dev));
2093 EXPORT_SYMBOL(i2c_del_adapter);
2096 * i2c_parse_fw_timings - get I2C related timing parameters from firmware
2097 * @dev: The device to scan for I2C timing properties
2098 * @t: the i2c_timings struct to be filled with values
2099 * @use_defaults: bool to use sane defaults derived from the I2C specification
2100 * when properties are not found, otherwise use 0
2102 * Scan the device for the generic I2C properties describing timing parameters
2103 * for the signal and fill the given struct with the results. If a property was
2104 * not found and use_defaults was true, then maximum timings are assumed which
2105 * are derived from the I2C specification. If use_defaults is not used, the
2106 * results will be 0, so drivers can apply their own defaults later. The latter
2107 * is mainly intended for avoiding regressions of existing drivers which want
2108 * to switch to this function. New drivers almost always should use the defaults.
2111 void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
2115 memset(t, 0, sizeof(*t));
2117 ret = device_property_read_u32(dev, "clock-frequency", &t->bus_freq_hz);
2118 if (ret && use_defaults)
2119 t->bus_freq_hz = 100000;
2121 ret = device_property_read_u32(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns);
2122 if (ret && use_defaults) {
2123 if (t->bus_freq_hz <= 100000)
2124 t->scl_rise_ns = 1000;
2125 else if (t->bus_freq_hz <= 400000)
2126 t->scl_rise_ns = 300;
2128 t->scl_rise_ns = 120;
2131 ret = device_property_read_u32(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns);
2132 if (ret && use_defaults) {
2133 if (t->bus_freq_hz <= 400000)
2134 t->scl_fall_ns = 300;
2136 t->scl_fall_ns = 120;
2139 device_property_read_u32(dev, "i2c-scl-internal-delay-ns", &t->scl_int_delay_ns);
2141 ret = device_property_read_u32(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns);
2142 if (ret && use_defaults)
2143 t->sda_fall_ns = t->scl_fall_ns;
2145 EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
2147 /* ------------------------------------------------------------------------- */
2149 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
2153 mutex_lock(&core_lock);
2154 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
2155 mutex_unlock(&core_lock);
2159 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
2161 static int __process_new_driver(struct device *dev, void *data)
2163 if (dev->type != &i2c_adapter_type)
2165 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
2169 * An i2c_driver is used with one or more i2c_client (device) nodes to access
2170 * i2c slave chips, on a bus instance associated with some i2c_adapter.
2173 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
2177 /* Can't register until after driver model init */
2178 if (WARN_ON(!is_registered))
2181 /* add the driver to the list of i2c drivers in the driver core */
2182 driver->driver.owner = owner;
2183 driver->driver.bus = &i2c_bus_type;
2184 INIT_LIST_HEAD(&driver->clients);
2186 /* When registration returns, the driver core
2187 * will have called probe() for all matching-but-unbound devices.
2189 res = driver_register(&driver->driver);
2193 pr_debug("driver [%s] registered\n", driver->driver.name);
2195 /* Walk the adapters that are already present */
2196 i2c_for_each_dev(driver, __process_new_driver);
2200 EXPORT_SYMBOL(i2c_register_driver);
2202 static int __process_removed_driver(struct device *dev, void *data)
2204 if (dev->type == &i2c_adapter_type)
2205 i2c_do_del_adapter(data, to_i2c_adapter(dev));
2210 * i2c_del_driver - unregister I2C driver
2211 * @driver: the driver being unregistered
2212 * Context: can sleep
2214 void i2c_del_driver(struct i2c_driver *driver)
2216 i2c_for_each_dev(driver, __process_removed_driver);
2218 driver_unregister(&driver->driver);
2219 pr_debug("driver [%s] unregistered\n", driver->driver.name);
2221 EXPORT_SYMBOL(i2c_del_driver);
2223 /* ------------------------------------------------------------------------- */
2226 * i2c_use_client - increments the reference count of the i2c client structure
2227 * @client: the client being referenced
2229 * Each live reference to a client should be refcounted. The driver model does
2230 * that automatically as part of driver binding, so that most drivers don't
2231 * need to do this explicitly: they hold a reference until they're unbound
2234 * A pointer to the client with the incremented reference counter is returned.
2236 struct i2c_client *i2c_use_client(struct i2c_client *client)
2238 if (client && get_device(&client->dev))
2242 EXPORT_SYMBOL(i2c_use_client);
2245 * i2c_release_client - release a use of the i2c client structure
2246 * @client: the client being no longer referenced
2248 * Must be called when a user of a client is finished with it.
2250 void i2c_release_client(struct i2c_client *client)
2253 put_device(&client->dev);
2255 EXPORT_SYMBOL(i2c_release_client);
2257 struct i2c_cmd_arg {
2262 static int i2c_cmd(struct device *dev, void *_arg)
2264 struct i2c_client *client = i2c_verify_client(dev);
2265 struct i2c_cmd_arg *arg = _arg;
2266 struct i2c_driver *driver;
2268 if (!client || !client->dev.driver)
2271 driver = to_i2c_driver(client->dev.driver);
2272 if (driver->command)
2273 driver->command(client, arg->cmd, arg->arg);
2277 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
2279 struct i2c_cmd_arg cmd_arg;
2283 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
2285 EXPORT_SYMBOL(i2c_clients_command);
2287 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
2288 static int of_i2c_notify(struct notifier_block *nb, unsigned long action,
2291 struct of_reconfig_data *rd = arg;
2292 struct i2c_adapter *adap;
2293 struct i2c_client *client;
2295 switch (of_reconfig_get_state_change(action, rd)) {
2296 case OF_RECONFIG_CHANGE_ADD:
2297 adap = of_find_i2c_adapter_by_node(rd->dn->parent);
2299 return NOTIFY_OK; /* not for us */
2301 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
2302 put_device(&adap->dev);
2306 client = of_i2c_register_device(adap, rd->dn);
2307 put_device(&adap->dev);
2309 if (IS_ERR(client)) {
2310 dev_err(&adap->dev, "failed to create client for '%s'\n",
2312 of_node_clear_flag(rd->dn, OF_POPULATED);
2313 return notifier_from_errno(PTR_ERR(client));
2316 case OF_RECONFIG_CHANGE_REMOVE:
2317 /* already depopulated? */
2318 if (!of_node_check_flag(rd->dn, OF_POPULATED))
2321 /* find our device by node */
2322 client = of_find_i2c_device_by_node(rd->dn);
2324 return NOTIFY_OK; /* no? not meant for us */
2326 /* unregister takes one ref away */
2327 i2c_unregister_device(client);
2329 /* and put the reference of the find */
2330 put_device(&client->dev);
2336 static struct notifier_block i2c_of_notifier = {
2337 .notifier_call = of_i2c_notify,
2340 extern struct notifier_block i2c_of_notifier;
2341 #endif /* CONFIG_OF_DYNAMIC */
2343 static int __init i2c_init(void)
2347 retval = of_alias_get_highest_id("i2c");
2349 down_write(&__i2c_board_lock);
2350 if (retval >= __i2c_first_dynamic_bus_num)
2351 __i2c_first_dynamic_bus_num = retval + 1;
2352 up_write(&__i2c_board_lock);
2354 retval = bus_register(&i2c_bus_type);
2358 is_registered = true;
2360 #ifdef CONFIG_I2C_COMPAT
2361 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
2362 if (!i2c_adapter_compat_class) {
2367 retval = i2c_add_driver(&dummy_driver);
2371 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2372 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
2373 if (IS_ENABLED(CONFIG_ACPI))
2374 WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
2379 #ifdef CONFIG_I2C_COMPAT
2380 class_compat_unregister(i2c_adapter_compat_class);
2383 is_registered = false;
2384 bus_unregister(&i2c_bus_type);
2388 static void __exit i2c_exit(void)
2390 if (IS_ENABLED(CONFIG_ACPI))
2391 WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
2392 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2393 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
2394 i2c_del_driver(&dummy_driver);
2395 #ifdef CONFIG_I2C_COMPAT
2396 class_compat_unregister(i2c_adapter_compat_class);
2398 bus_unregister(&i2c_bus_type);
2399 tracepoint_synchronize_unregister();
2402 /* We must initialize early, because some subsystems register i2c drivers
2403 * in subsys_initcall() code, but are linked (and initialized) before i2c.
2405 postcore_initcall(i2c_init);
2406 module_exit(i2c_exit);
2408 /* ----------------------------------------------------
2409 * the functional interface to the i2c busses.
2410 * ----------------------------------------------------
2413 /* Check if val is exceeding the quirk IFF quirk is non 0 */
2414 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2416 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2418 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2419 err_msg, msg->addr, msg->len,
2420 msg->flags & I2C_M_RD ? "read" : "write");
2424 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2426 const struct i2c_adapter_quirks *q = adap->quirks;
2427 int max_num = q->max_num_msgs, i;
2428 bool do_len_check = true;
2430 if (q->flags & I2C_AQ_COMB) {
2433 /* special checks for combined messages */
2435 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2436 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2438 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2439 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2441 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2442 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2444 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2445 return i2c_quirk_error(adap, &msgs[0], "msg too long");
2447 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2448 return i2c_quirk_error(adap, &msgs[1], "msg too long");
2450 do_len_check = false;
2454 if (i2c_quirk_exceeded(num, max_num))
2455 return i2c_quirk_error(adap, &msgs[0], "too many messages");
2457 for (i = 0; i < num; i++) {
2458 u16 len = msgs[i].len;
2460 if (msgs[i].flags & I2C_M_RD) {
2461 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2462 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2464 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2465 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2473 * __i2c_transfer - unlocked flavor of i2c_transfer
2474 * @adap: Handle to I2C bus
2475 * @msgs: One or more messages to execute before STOP is issued to
2476 * terminate the operation; each message begins with a START.
2477 * @num: Number of messages to be executed.
2479 * Returns negative errno, else the number of messages executed.
2481 * Adapter lock must be held when calling this function. No debug logging
2482 * takes place. adap->algo->master_xfer existence isn't checked.
2484 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2486 unsigned long orig_jiffies;
2489 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2492 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2493 * enabled. This is an efficient way of keeping the for-loop from
2494 * being executed when not needed.
2496 if (static_key_false(&i2c_trace_msg)) {
2498 for (i = 0; i < num; i++)
2499 if (msgs[i].flags & I2C_M_RD)
2500 trace_i2c_read(adap, &msgs[i], i);
2502 trace_i2c_write(adap, &msgs[i], i);
2505 /* Retry automatically on arbitration loss */
2506 orig_jiffies = jiffies;
2507 for (ret = 0, try = 0; try <= adap->retries; try++) {
2508 ret = adap->algo->master_xfer(adap, msgs, num);
2511 if (time_after(jiffies, orig_jiffies + adap->timeout))
2515 if (static_key_false(&i2c_trace_msg)) {
2517 for (i = 0; i < ret; i++)
2518 if (msgs[i].flags & I2C_M_RD)
2519 trace_i2c_reply(adap, &msgs[i], i);
2520 trace_i2c_result(adap, i, ret);
2525 EXPORT_SYMBOL(__i2c_transfer);
2528 * i2c_transfer - execute a single or combined I2C message
2529 * @adap: Handle to I2C bus
2530 * @msgs: One or more messages to execute before STOP is issued to
2531 * terminate the operation; each message begins with a START.
2532 * @num: Number of messages to be executed.
2534 * Returns negative errno, else the number of messages executed.
2536 * Note that there is no requirement that each message be sent to
2537 * the same slave address, although that is the most common model.
2539 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2543 /* REVISIT the fault reporting model here is weak:
2545 * - When we get an error after receiving N bytes from a slave,
2546 * there is no way to report "N".
2548 * - When we get a NAK after transmitting N bytes to a slave,
2549 * there is no way to report "N" ... or to let the master
2550 * continue executing the rest of this combined message, if
2551 * that's the appropriate response.
2553 * - When for example "num" is two and we successfully complete
2554 * the first message but get an error part way through the
2555 * second, it's unclear whether that should be reported as
2556 * one (discarding status on the second message) or errno
2557 * (discarding status on the first one).
2560 if (adap->algo->master_xfer) {
2562 for (ret = 0; ret < num; ret++) {
2564 "master_xfer[%d] %c, addr=0x%02x, len=%d%s\n",
2565 ret, (msgs[ret].flags & I2C_M_RD) ? 'R' : 'W',
2566 msgs[ret].addr, msgs[ret].len,
2567 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2571 if (in_atomic() || irqs_disabled()) {
2572 ret = i2c_trylock_bus(adap, I2C_LOCK_SEGMENT);
2574 /* I2C activity is ongoing. */
2577 i2c_lock_bus(adap, I2C_LOCK_SEGMENT);
2580 ret = __i2c_transfer(adap, msgs, num);
2581 i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
2585 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2589 EXPORT_SYMBOL(i2c_transfer);
2592 * i2c_master_send - issue a single I2C message in master transmit mode
2593 * @client: Handle to slave device
2594 * @buf: Data that will be written to the slave
2595 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2597 * Returns negative errno, or else the number of bytes written.
2599 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2602 struct i2c_adapter *adap = client->adapter;
2605 msg.addr = client->addr;
2606 msg.flags = client->flags & I2C_M_TEN;
2608 msg.buf = (char *)buf;
2610 ret = i2c_transfer(adap, &msg, 1);
2613 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2614 * transmitted, else error code.
2616 return (ret == 1) ? count : ret;
2618 EXPORT_SYMBOL(i2c_master_send);
2621 * i2c_master_recv - issue a single I2C message in master receive mode
2622 * @client: Handle to slave device
2623 * @buf: Where to store data read from slave
2624 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2626 * Returns negative errno, or else the number of bytes read.
2628 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2630 struct i2c_adapter *adap = client->adapter;
2634 msg.addr = client->addr;
2635 msg.flags = client->flags & I2C_M_TEN;
2636 msg.flags |= I2C_M_RD;
2640 ret = i2c_transfer(adap, &msg, 1);
2643 * If everything went ok (i.e. 1 msg received), return #bytes received,
2646 return (ret == 1) ? count : ret;
2648 EXPORT_SYMBOL(i2c_master_recv);
2650 /* ----------------------------------------------------
2651 * the i2c address scanning function
2652 * Will not work for 10-bit addresses!
2653 * ----------------------------------------------------
2657 * Legacy default probe function, mostly relevant for SMBus. The default
2658 * probe method is a quick write, but it is known to corrupt the 24RF08
2659 * EEPROMs due to a state machine bug, and could also irreversibly
2660 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2661 * we use a short byte read instead. Also, some bus drivers don't implement
2662 * quick write, so we fallback to a byte read in that case too.
2663 * On x86, there is another special case for FSC hardware monitoring chips,
2664 * which want regular byte reads (address 0x73.) Fortunately, these are the
2665 * only known chips using this I2C address on PC hardware.
2666 * Returns 1 if probe succeeded, 0 if not.
2668 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2671 union i2c_smbus_data dummy;
2674 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2675 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2676 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2677 I2C_SMBUS_BYTE_DATA, &dummy);
2680 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2681 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2682 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2683 I2C_SMBUS_QUICK, NULL);
2684 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2685 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2686 I2C_SMBUS_BYTE, &dummy);
2688 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2696 static int i2c_detect_address(struct i2c_client *temp_client,
2697 struct i2c_driver *driver)
2699 struct i2c_board_info info;
2700 struct i2c_adapter *adapter = temp_client->adapter;
2701 int addr = temp_client->addr;
2704 /* Make sure the address is valid */
2705 err = i2c_check_7bit_addr_validity_strict(addr);
2707 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2712 /* Skip if already in use (7 bit, no need to encode flags) */
2713 if (i2c_check_addr_busy(adapter, addr))
2716 /* Make sure there is something at this address */
2717 if (!i2c_default_probe(adapter, addr))
2720 /* Finally call the custom detection function */
2721 memset(&info, 0, sizeof(struct i2c_board_info));
2723 err = driver->detect(temp_client, &info);
2725 /* -ENODEV is returned if the detection fails. We catch it
2726 here as this isn't an error. */
2727 return err == -ENODEV ? 0 : err;
2730 /* Consistency check */
2731 if (info.type[0] == '\0') {
2732 dev_err(&adapter->dev,
2733 "%s detection function provided no name for 0x%x\n",
2734 driver->driver.name, addr);
2736 struct i2c_client *client;
2738 /* Detection succeeded, instantiate the device */
2739 if (adapter->class & I2C_CLASS_DEPRECATED)
2740 dev_warn(&adapter->dev,
2741 "This adapter will soon drop class based instantiation of devices. "
2742 "Please make sure client 0x%02x gets instantiated by other means. "
2743 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2746 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2747 info.type, info.addr);
2748 client = i2c_new_device(adapter, &info);
2750 list_add_tail(&client->detected, &driver->clients);
2752 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2753 info.type, info.addr);
2758 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2760 const unsigned short *address_list;
2761 struct i2c_client *temp_client;
2763 int adap_id = i2c_adapter_id(adapter);
2765 address_list = driver->address_list;
2766 if (!driver->detect || !address_list)
2769 /* Warn that the adapter lost class based instantiation */
2770 if (adapter->class == I2C_CLASS_DEPRECATED) {
2771 dev_dbg(&adapter->dev,
2772 "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
2773 "If you need it, check 'Documentation/i2c/instantiating-devices' for alternatives.\n",
2774 driver->driver.name);
2778 /* Stop here if the classes do not match */
2779 if (!(adapter->class & driver->class))
2782 /* Set up a temporary client to help detect callback */
2783 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2786 temp_client->adapter = adapter;
2788 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2789 dev_dbg(&adapter->dev,
2790 "found normal entry for adapter %d, addr 0x%02x\n",
2791 adap_id, address_list[i]);
2792 temp_client->addr = address_list[i];
2793 err = i2c_detect_address(temp_client, driver);
2802 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2804 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2805 I2C_SMBUS_QUICK, NULL) >= 0;
2807 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2810 i2c_new_probed_device(struct i2c_adapter *adap,
2811 struct i2c_board_info *info,
2812 unsigned short const *addr_list,
2813 int (*probe)(struct i2c_adapter *, unsigned short addr))
2818 probe = i2c_default_probe;
2820 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2821 /* Check address validity */
2822 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2823 dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
2828 /* Check address availability (7 bit, no need to encode flags) */
2829 if (i2c_check_addr_busy(adap, addr_list[i])) {
2831 "Address 0x%02x already in use, not probing\n",
2836 /* Test address responsiveness */
2837 if (probe(adap, addr_list[i]))
2841 if (addr_list[i] == I2C_CLIENT_END) {
2842 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2846 info->addr = addr_list[i];
2847 return i2c_new_device(adap, info);
2849 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2851 struct i2c_adapter *i2c_get_adapter(int nr)
2853 struct i2c_adapter *adapter;
2855 mutex_lock(&core_lock);
2856 adapter = idr_find(&i2c_adapter_idr, nr);
2860 if (try_module_get(adapter->owner))
2861 get_device(&adapter->dev);
2866 mutex_unlock(&core_lock);
2869 EXPORT_SYMBOL(i2c_get_adapter);
2871 void i2c_put_adapter(struct i2c_adapter *adap)
2876 put_device(&adap->dev);
2877 module_put(adap->owner);
2879 EXPORT_SYMBOL(i2c_put_adapter);
2881 /* The SMBus parts */
2883 #define POLY (0x1070U << 3)
2884 static u8 crc8(u16 data)
2888 for (i = 0; i < 8; i++) {
2893 return (u8)(data >> 8);
2896 /* Incremental CRC8 over count bytes in the array pointed to by p */
2897 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2901 for (i = 0; i < count; i++)
2902 crc = crc8((crc ^ p[i]) << 8);
2906 /* Assume a 7-bit address, which is reasonable for SMBus */
2907 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2909 /* The address will be sent first */
2910 u8 addr = i2c_8bit_addr_from_msg(msg);
2911 pec = i2c_smbus_pec(pec, &addr, 1);
2913 /* The data buffer follows */
2914 return i2c_smbus_pec(pec, msg->buf, msg->len);
2917 /* Used for write only transactions */
2918 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2920 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2924 /* Return <0 on CRC error
2925 If there was a write before this read (most cases) we need to take the
2926 partial CRC from the write part into account.
2927 Note that this function does modify the message (we need to decrease the
2928 message length to hide the CRC byte from the caller). */
2929 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2931 u8 rpec = msg->buf[--msg->len];
2932 cpec = i2c_smbus_msg_pec(cpec, msg);
2935 pr_debug("Bad PEC 0x%02x vs. 0x%02x\n",
2943 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2944 * @client: Handle to slave device
2946 * This executes the SMBus "receive byte" protocol, returning negative errno
2947 * else the byte received from the device.
2949 s32 i2c_smbus_read_byte(const struct i2c_client *client)
2951 union i2c_smbus_data data;
2954 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2956 I2C_SMBUS_BYTE, &data);
2957 return (status < 0) ? status : data.byte;
2959 EXPORT_SYMBOL(i2c_smbus_read_byte);
2962 * i2c_smbus_write_byte - SMBus "send byte" protocol
2963 * @client: Handle to slave device
2964 * @value: Byte to be sent
2966 * This executes the SMBus "send byte" protocol, returning negative errno
2967 * else zero on success.
2969 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2971 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2972 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2974 EXPORT_SYMBOL(i2c_smbus_write_byte);
2977 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2978 * @client: Handle to slave device
2979 * @command: Byte interpreted by slave
2981 * This executes the SMBus "read byte" protocol, returning negative errno
2982 * else a data byte received from the device.
2984 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2986 union i2c_smbus_data data;
2989 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2990 I2C_SMBUS_READ, command,
2991 I2C_SMBUS_BYTE_DATA, &data);
2992 return (status < 0) ? status : data.byte;
2994 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2997 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2998 * @client: Handle to slave device
2999 * @command: Byte interpreted by slave
3000 * @value: Byte being written
3002 * This executes the SMBus "write byte" protocol, returning negative errno
3003 * else zero on success.
3005 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
3008 union i2c_smbus_data data;
3010 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3011 I2C_SMBUS_WRITE, command,
3012 I2C_SMBUS_BYTE_DATA, &data);
3014 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
3017 * i2c_smbus_read_word_data - SMBus "read word" protocol
3018 * @client: Handle to slave device
3019 * @command: Byte interpreted by slave
3021 * This executes the SMBus "read word" protocol, returning negative errno
3022 * else a 16-bit unsigned "word" received from the device.
3024 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
3026 union i2c_smbus_data data;
3029 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3030 I2C_SMBUS_READ, command,
3031 I2C_SMBUS_WORD_DATA, &data);
3032 return (status < 0) ? status : data.word;
3034 EXPORT_SYMBOL(i2c_smbus_read_word_data);
3037 * i2c_smbus_write_word_data - SMBus "write word" protocol
3038 * @client: Handle to slave device
3039 * @command: Byte interpreted by slave
3040 * @value: 16-bit "word" being written
3042 * This executes the SMBus "write word" protocol, returning negative errno
3043 * else zero on success.
3045 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
3048 union i2c_smbus_data data;
3050 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3051 I2C_SMBUS_WRITE, command,
3052 I2C_SMBUS_WORD_DATA, &data);
3054 EXPORT_SYMBOL(i2c_smbus_write_word_data);
3057 * i2c_smbus_read_block_data - SMBus "block read" protocol
3058 * @client: Handle to slave device
3059 * @command: Byte interpreted by slave
3060 * @values: Byte array into which data will be read; big enough to hold
3061 * the data returned by the slave. SMBus allows at most 32 bytes.
3063 * This executes the SMBus "block read" protocol, returning negative errno
3064 * else the number of data bytes in the slave's response.
3066 * Note that using this function requires that the client's adapter support
3067 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
3068 * support this; its emulation through I2C messaging relies on a specific
3069 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
3071 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
3074 union i2c_smbus_data data;
3077 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3078 I2C_SMBUS_READ, command,
3079 I2C_SMBUS_BLOCK_DATA, &data);
3083 memcpy(values, &data.block[1], data.block[0]);
3084 return data.block[0];
3086 EXPORT_SYMBOL(i2c_smbus_read_block_data);
3089 * i2c_smbus_write_block_data - SMBus "block write" protocol
3090 * @client: Handle to slave device
3091 * @command: Byte interpreted by slave
3092 * @length: Size of data block; SMBus allows at most 32 bytes
3093 * @values: Byte array which will be written.
3095 * This executes the SMBus "block write" protocol, returning negative errno
3096 * else zero on success.
3098 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
3099 u8 length, const u8 *values)
3101 union i2c_smbus_data data;
3103 if (length > I2C_SMBUS_BLOCK_MAX)
3104 length = I2C_SMBUS_BLOCK_MAX;
3105 data.block[0] = length;
3106 memcpy(&data.block[1], values, length);
3107 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3108 I2C_SMBUS_WRITE, command,
3109 I2C_SMBUS_BLOCK_DATA, &data);
3111 EXPORT_SYMBOL(i2c_smbus_write_block_data);
3113 /* Returns the number of read bytes */
3114 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
3115 u8 length, u8 *values)
3117 union i2c_smbus_data data;
3120 if (length > I2C_SMBUS_BLOCK_MAX)
3121 length = I2C_SMBUS_BLOCK_MAX;
3122 data.block[0] = length;
3123 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3124 I2C_SMBUS_READ, command,
3125 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3129 memcpy(values, &data.block[1], data.block[0]);
3130 return data.block[0];
3132 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
3134 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
3135 u8 length, const u8 *values)
3137 union i2c_smbus_data data;
3139 if (length > I2C_SMBUS_BLOCK_MAX)
3140 length = I2C_SMBUS_BLOCK_MAX;
3141 data.block[0] = length;
3142 memcpy(data.block + 1, values, length);
3143 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
3144 I2C_SMBUS_WRITE, command,
3145 I2C_SMBUS_I2C_BLOCK_DATA, &data);
3147 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
3149 /* Simulate a SMBus command using the i2c protocol
3150 No checking of parameters is done! */
3151 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
3152 unsigned short flags,
3153 char read_write, u8 command, int size,
3154 union i2c_smbus_data *data)
3156 /* So we need to generate a series of msgs. In the case of writing, we
3157 need to use only one message; when reading, we need two. We initialize
3158 most things with sane defaults, to keep the code below somewhat
3160 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
3161 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
3162 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
3166 struct i2c_msg msg[2] = {
3174 .flags = flags | I2C_M_RD,
3180 msgbuf0[0] = command;
3182 case I2C_SMBUS_QUICK:
3184 /* Special case: The read/write field is used as data */
3185 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
3189 case I2C_SMBUS_BYTE:
3190 if (read_write == I2C_SMBUS_READ) {
3191 /* Special case: only a read! */
3192 msg[0].flags = I2C_M_RD | flags;
3196 case I2C_SMBUS_BYTE_DATA:
3197 if (read_write == I2C_SMBUS_READ)
3201 msgbuf0[1] = data->byte;
3204 case I2C_SMBUS_WORD_DATA:
3205 if (read_write == I2C_SMBUS_READ)
3209 msgbuf0[1] = data->word & 0xff;
3210 msgbuf0[2] = data->word >> 8;
3213 case I2C_SMBUS_PROC_CALL:
3214 num = 2; /* Special case */
3215 read_write = I2C_SMBUS_READ;
3218 msgbuf0[1] = data->word & 0xff;
3219 msgbuf0[2] = data->word >> 8;
3221 case I2C_SMBUS_BLOCK_DATA:
3222 if (read_write == I2C_SMBUS_READ) {
3223 msg[1].flags |= I2C_M_RECV_LEN;
3224 msg[1].len = 1; /* block length will be added by
3225 the underlying bus driver */
3227 msg[0].len = data->block[0] + 2;
3228 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
3229 dev_err(&adapter->dev,
3230 "Invalid block write size %d\n",
3234 for (i = 1; i < msg[0].len; i++)
3235 msgbuf0[i] = data->block[i-1];
3238 case I2C_SMBUS_BLOCK_PROC_CALL:
3239 num = 2; /* Another special case */
3240 read_write = I2C_SMBUS_READ;
3241 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
3242 dev_err(&adapter->dev,
3243 "Invalid block write size %d\n",
3247 msg[0].len = data->block[0] + 2;
3248 for (i = 1; i < msg[0].len; i++)
3249 msgbuf0[i] = data->block[i-1];
3250 msg[1].flags |= I2C_M_RECV_LEN;
3251 msg[1].len = 1; /* block length will be added by
3252 the underlying bus driver */
3254 case I2C_SMBUS_I2C_BLOCK_DATA:
3255 if (read_write == I2C_SMBUS_READ) {
3256 msg[1].len = data->block[0];
3258 msg[0].len = data->block[0] + 1;
3259 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
3260 dev_err(&adapter->dev,
3261 "Invalid block write size %d\n",
3265 for (i = 1; i <= data->block[0]; i++)
3266 msgbuf0[i] = data->block[i];
3270 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
3274 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
3275 && size != I2C_SMBUS_I2C_BLOCK_DATA);
3277 /* Compute PEC if first message is a write */
3278 if (!(msg[0].flags & I2C_M_RD)) {
3279 if (num == 1) /* Write only */
3280 i2c_smbus_add_pec(&msg[0]);
3281 else /* Write followed by read */
3282 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
3284 /* Ask for PEC if last message is a read */
3285 if (msg[num-1].flags & I2C_M_RD)
3289 status = i2c_transfer(adapter, msg, num);
3293 /* Check PEC if last message is a read */
3294 if (i && (msg[num-1].flags & I2C_M_RD)) {
3295 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
3300 if (read_write == I2C_SMBUS_READ)
3302 case I2C_SMBUS_BYTE:
3303 data->byte = msgbuf0[0];
3305 case I2C_SMBUS_BYTE_DATA:
3306 data->byte = msgbuf1[0];
3308 case I2C_SMBUS_WORD_DATA:
3309 case I2C_SMBUS_PROC_CALL:
3310 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
3312 case I2C_SMBUS_I2C_BLOCK_DATA:
3313 for (i = 0; i < data->block[0]; i++)
3314 data->block[i+1] = msgbuf1[i];
3316 case I2C_SMBUS_BLOCK_DATA:
3317 case I2C_SMBUS_BLOCK_PROC_CALL:
3318 for (i = 0; i < msgbuf1[0] + 1; i++)
3319 data->block[i] = msgbuf1[i];
3326 * i2c_smbus_xfer - execute SMBus protocol operations
3327 * @adapter: Handle to I2C bus
3328 * @addr: Address of SMBus slave on that bus
3329 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
3330 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
3331 * @command: Byte interpreted by slave, for protocols which use such bytes
3332 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
3333 * @data: Data to be read or written
3335 * This executes an SMBus protocol operation, and returns a negative
3336 * errno code else zero on success.
3338 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
3339 char read_write, u8 command, int protocol,
3340 union i2c_smbus_data *data)
3342 unsigned long orig_jiffies;
3346 /* If enabled, the following two tracepoints are conditional on
3347 * read_write and protocol.
3349 trace_smbus_write(adapter, addr, flags, read_write,
3350 command, protocol, data);
3351 trace_smbus_read(adapter, addr, flags, read_write,
3354 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
3356 if (adapter->algo->smbus_xfer) {
3357 i2c_lock_bus(adapter, I2C_LOCK_SEGMENT);
3359 /* Retry automatically on arbitration loss */
3360 orig_jiffies = jiffies;
3361 for (res = 0, try = 0; try <= adapter->retries; try++) {
3362 res = adapter->algo->smbus_xfer(adapter, addr, flags,
3363 read_write, command,
3367 if (time_after(jiffies,
3368 orig_jiffies + adapter->timeout))
3371 i2c_unlock_bus(adapter, I2C_LOCK_SEGMENT);
3373 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
3376 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
3377 * implement native support for the SMBus operation.
3381 res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
3382 command, protocol, data);
3385 /* If enabled, the reply tracepoint is conditional on read_write. */
3386 trace_smbus_reply(adapter, addr, flags, read_write,
3387 command, protocol, data);
3388 trace_smbus_result(adapter, addr, flags, read_write,
3389 command, protocol, res);
3393 EXPORT_SYMBOL(i2c_smbus_xfer);
3396 * i2c_smbus_read_i2c_block_data_or_emulated - read block or emulate
3397 * @client: Handle to slave device
3398 * @command: Byte interpreted by slave
3399 * @length: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
3400 * @values: Byte array into which data will be read; big enough to hold
3401 * the data returned by the slave. SMBus allows at most
3402 * I2C_SMBUS_BLOCK_MAX bytes.
3404 * This executes the SMBus "block read" protocol if supported by the adapter.
3405 * If block read is not supported, it emulates it using either word or byte
3406 * read protocols depending on availability.
3408 * The addresses of the I2C slave device that are accessed with this function
3409 * must be mapped to a linear region, so that a block read will have the same
3410 * effect as a byte read. Before using this function you must double-check
3411 * if the I2C slave does support exchanging a block transfer with a byte
3414 s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client,
3415 u8 command, u8 length, u8 *values)
3420 if (length > I2C_SMBUS_BLOCK_MAX)
3421 length = I2C_SMBUS_BLOCK_MAX;
3423 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
3424 return i2c_smbus_read_i2c_block_data(client, command, length, values);
3426 if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA))
3429 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) {
3430 while ((i + 2) <= length) {
3431 status = i2c_smbus_read_word_data(client, command + i);
3434 values[i] = status & 0xff;
3435 values[i + 1] = status >> 8;
3440 while (i < length) {
3441 status = i2c_smbus_read_byte_data(client, command + i);
3450 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data_or_emulated);
3452 #if IS_ENABLED(CONFIG_I2C_SLAVE)
3453 int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
3457 if (!client || !slave_cb) {
3458 WARN(1, "insufficent data\n");
3462 if (!(client->flags & I2C_CLIENT_SLAVE))
3463 dev_warn(&client->dev, "%s: client slave flag not set. You might see address collisions\n",
3466 if (!(client->flags & I2C_CLIENT_TEN)) {
3467 /* Enforce stricter address checking */
3468 ret = i2c_check_7bit_addr_validity_strict(client->addr);
3470 dev_err(&client->dev, "%s: invalid address\n", __func__);
3475 if (!client->adapter->algo->reg_slave) {
3476 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3480 client->slave_cb = slave_cb;
3482 i2c_lock_adapter(client->adapter);
3483 ret = client->adapter->algo->reg_slave(client);
3484 i2c_unlock_adapter(client->adapter);
3487 client->slave_cb = NULL;
3488 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3493 EXPORT_SYMBOL_GPL(i2c_slave_register);
3495 int i2c_slave_unregister(struct i2c_client *client)
3499 if (!client->adapter->algo->unreg_slave) {
3500 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3504 i2c_lock_adapter(client->adapter);
3505 ret = client->adapter->algo->unreg_slave(client);
3506 i2c_unlock_adapter(client->adapter);
3509 client->slave_cb = NULL;
3511 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3515 EXPORT_SYMBOL_GPL(i2c_slave_unregister);
3518 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
3519 MODULE_DESCRIPTION("I2C-Bus main module");
3520 MODULE_LICENSE("GPL");