i2c: core: Add support for best effort block read emulation
[linux-2.6/btrfs-unstable.git] / drivers / i2c / i2c-core.c
blob98f6c75b1d18e4d685d381d6c1b43056b3c99452
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 #include <dt-bindings/i2c/i2c.h>
31 #include <linux/module.h>
32 #include <linux/kernel.h>
33 #include <linux/delay.h>
34 #include <linux/errno.h>
35 #include <linux/gpio.h>
36 #include <linux/slab.h>
37 #include <linux/i2c.h>
38 #include <linux/init.h>
39 #include <linux/idr.h>
40 #include <linux/mutex.h>
41 #include <linux/of.h>
42 #include <linux/of_device.h>
43 #include <linux/of_irq.h>
44 #include <linux/clk/clk-conf.h>
45 #include <linux/completion.h>
46 #include <linux/hardirq.h>
47 #include <linux/irqflags.h>
48 #include <linux/rwsem.h>
49 #include <linux/pm_runtime.h>
50 #include <linux/pm_domain.h>
51 #include <linux/acpi.h>
52 #include <linux/jump_label.h>
53 #include <asm/uaccess.h>
54 #include <linux/err.h>
56 #include "i2c-core.h"
58 #define CREATE_TRACE_POINTS
59 #include <trace/events/i2c.h>
61 #define I2C_ADDR_OFFSET_TEN_BIT 0xa000
62 #define I2C_ADDR_OFFSET_SLAVE 0x1000
64 /* core_lock protects i2c_adapter_idr, and guarantees
65 that device detection, deletion of detected devices, and attach_adapter
66 calls are serialized */
67 static DEFINE_MUTEX(core_lock);
68 static DEFINE_IDR(i2c_adapter_idr);
70 static struct device_type i2c_client_type;
71 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
73 static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
75 void i2c_transfer_trace_reg(void)
77 static_key_slow_inc(&i2c_trace_msg);
80 void i2c_transfer_trace_unreg(void)
82 static_key_slow_dec(&i2c_trace_msg);
85 #if defined(CONFIG_ACPI)
86 struct acpi_i2c_handler_data {
87 struct acpi_connection_info info;
88 struct i2c_adapter *adapter;
91 struct gsb_buffer {
92 u8 status;
93 u8 len;
94 union {
95 u16 wdata;
96 u8 bdata;
97 u8 data[0];
99 } __packed;
101 static int acpi_i2c_add_resource(struct acpi_resource *ares, void *data)
103 struct i2c_board_info *info = data;
105 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
106 struct acpi_resource_i2c_serialbus *sb;
108 sb = &ares->data.i2c_serial_bus;
109 if (!info->addr && sb->type == ACPI_RESOURCE_SERIAL_TYPE_I2C) {
110 info->addr = sb->slave_address;
111 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
112 info->flags |= I2C_CLIENT_TEN;
114 } else if (!info->irq) {
115 struct resource r;
117 if (acpi_dev_resource_interrupt(ares, 0, &r))
118 info->irq = r.start;
121 /* Tell the ACPI core to skip this resource */
122 return 1;
125 static acpi_status acpi_i2c_add_device(acpi_handle handle, u32 level,
126 void *data, void **return_value)
128 struct i2c_adapter *adapter = data;
129 struct list_head resource_list;
130 struct i2c_board_info info;
131 struct acpi_device *adev;
132 int ret;
134 if (acpi_bus_get_device(handle, &adev))
135 return AE_OK;
136 if (acpi_bus_get_status(adev) || !adev->status.present)
137 return AE_OK;
139 memset(&info, 0, sizeof(info));
140 info.fwnode = acpi_fwnode_handle(adev);
142 INIT_LIST_HEAD(&resource_list);
143 ret = acpi_dev_get_resources(adev, &resource_list,
144 acpi_i2c_add_resource, &info);
145 acpi_dev_free_resource_list(&resource_list);
147 if (ret < 0 || !info.addr)
148 return AE_OK;
150 adev->power.flags.ignore_parent = true;
151 strlcpy(info.type, dev_name(&adev->dev), sizeof(info.type));
152 if (!i2c_new_device(adapter, &info)) {
153 adev->power.flags.ignore_parent = false;
154 dev_err(&adapter->dev,
155 "failed to add I2C device %s from ACPI\n",
156 dev_name(&adev->dev));
159 return AE_OK;
163 * acpi_i2c_register_devices - enumerate I2C slave devices behind adapter
164 * @adap: pointer to adapter
166 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
167 * namespace. When a device is found it will be added to the Linux device
168 * model and bound to the corresponding ACPI handle.
170 static void acpi_i2c_register_devices(struct i2c_adapter *adap)
172 acpi_handle handle;
173 acpi_status status;
175 if (!adap->dev.parent)
176 return;
178 handle = ACPI_HANDLE(adap->dev.parent);
179 if (!handle)
180 return;
182 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
183 acpi_i2c_add_device, NULL,
184 adap, NULL);
185 if (ACPI_FAILURE(status))
186 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
189 #else /* CONFIG_ACPI */
190 static inline void acpi_i2c_register_devices(struct i2c_adapter *adap) { }
191 #endif /* CONFIG_ACPI */
193 #ifdef CONFIG_ACPI_I2C_OPREGION
194 static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
195 u8 cmd, u8 *data, u8 data_len)
198 struct i2c_msg msgs[2];
199 int ret;
200 u8 *buffer;
202 buffer = kzalloc(data_len, GFP_KERNEL);
203 if (!buffer)
204 return AE_NO_MEMORY;
206 msgs[0].addr = client->addr;
207 msgs[0].flags = client->flags;
208 msgs[0].len = 1;
209 msgs[0].buf = &cmd;
211 msgs[1].addr = client->addr;
212 msgs[1].flags = client->flags | I2C_M_RD;
213 msgs[1].len = data_len;
214 msgs[1].buf = buffer;
216 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
217 if (ret < 0)
218 dev_err(&client->adapter->dev, "i2c read failed\n");
219 else
220 memcpy(data, buffer, data_len);
222 kfree(buffer);
223 return ret;
226 static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
227 u8 cmd, u8 *data, u8 data_len)
230 struct i2c_msg msgs[1];
231 u8 *buffer;
232 int ret = AE_OK;
234 buffer = kzalloc(data_len + 1, GFP_KERNEL);
235 if (!buffer)
236 return AE_NO_MEMORY;
238 buffer[0] = cmd;
239 memcpy(buffer + 1, data, data_len);
241 msgs[0].addr = client->addr;
242 msgs[0].flags = client->flags;
243 msgs[0].len = data_len + 1;
244 msgs[0].buf = buffer;
246 ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
247 if (ret < 0)
248 dev_err(&client->adapter->dev, "i2c write failed\n");
250 kfree(buffer);
251 return ret;
254 static acpi_status
255 acpi_i2c_space_handler(u32 function, acpi_physical_address command,
256 u32 bits, u64 *value64,
257 void *handler_context, void *region_context)
259 struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
260 struct acpi_i2c_handler_data *data = handler_context;
261 struct acpi_connection_info *info = &data->info;
262 struct acpi_resource_i2c_serialbus *sb;
263 struct i2c_adapter *adapter = data->adapter;
264 struct i2c_client *client;
265 struct acpi_resource *ares;
266 u32 accessor_type = function >> 16;
267 u8 action = function & ACPI_IO_MASK;
268 acpi_status ret;
269 int status;
271 ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
272 if (ACPI_FAILURE(ret))
273 return ret;
275 client = kzalloc(sizeof(*client), GFP_KERNEL);
276 if (!client) {
277 ret = AE_NO_MEMORY;
278 goto err;
281 if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
282 ret = AE_BAD_PARAMETER;
283 goto err;
286 sb = &ares->data.i2c_serial_bus;
287 if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
288 ret = AE_BAD_PARAMETER;
289 goto err;
292 client->adapter = adapter;
293 client->addr = sb->slave_address;
295 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
296 client->flags |= I2C_CLIENT_TEN;
298 switch (accessor_type) {
299 case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
300 if (action == ACPI_READ) {
301 status = i2c_smbus_read_byte(client);
302 if (status >= 0) {
303 gsb->bdata = status;
304 status = 0;
306 } else {
307 status = i2c_smbus_write_byte(client, gsb->bdata);
309 break;
311 case ACPI_GSB_ACCESS_ATTRIB_BYTE:
312 if (action == ACPI_READ) {
313 status = i2c_smbus_read_byte_data(client, command);
314 if (status >= 0) {
315 gsb->bdata = status;
316 status = 0;
318 } else {
319 status = i2c_smbus_write_byte_data(client, command,
320 gsb->bdata);
322 break;
324 case ACPI_GSB_ACCESS_ATTRIB_WORD:
325 if (action == ACPI_READ) {
326 status = i2c_smbus_read_word_data(client, command);
327 if (status >= 0) {
328 gsb->wdata = status;
329 status = 0;
331 } else {
332 status = i2c_smbus_write_word_data(client, command,
333 gsb->wdata);
335 break;
337 case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
338 if (action == ACPI_READ) {
339 status = i2c_smbus_read_block_data(client, command,
340 gsb->data);
341 if (status >= 0) {
342 gsb->len = status;
343 status = 0;
345 } else {
346 status = i2c_smbus_write_block_data(client, command,
347 gsb->len, gsb->data);
349 break;
351 case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
352 if (action == ACPI_READ) {
353 status = acpi_gsb_i2c_read_bytes(client, command,
354 gsb->data, info->access_length);
355 if (status > 0)
356 status = 0;
357 } else {
358 status = acpi_gsb_i2c_write_bytes(client, command,
359 gsb->data, info->access_length);
361 break;
363 default:
364 pr_info("protocol(0x%02x) is not supported.\n", accessor_type);
365 ret = AE_BAD_PARAMETER;
366 goto err;
369 gsb->status = status;
371 err:
372 kfree(client);
373 ACPI_FREE(ares);
374 return ret;
378 static int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
380 acpi_handle handle;
381 struct acpi_i2c_handler_data *data;
382 acpi_status status;
384 if (!adapter->dev.parent)
385 return -ENODEV;
387 handle = ACPI_HANDLE(adapter->dev.parent);
389 if (!handle)
390 return -ENODEV;
392 data = kzalloc(sizeof(struct acpi_i2c_handler_data),
393 GFP_KERNEL);
394 if (!data)
395 return -ENOMEM;
397 data->adapter = adapter;
398 status = acpi_bus_attach_private_data(handle, (void *)data);
399 if (ACPI_FAILURE(status)) {
400 kfree(data);
401 return -ENOMEM;
404 status = acpi_install_address_space_handler(handle,
405 ACPI_ADR_SPACE_GSBUS,
406 &acpi_i2c_space_handler,
407 NULL,
408 data);
409 if (ACPI_FAILURE(status)) {
410 dev_err(&adapter->dev, "Error installing i2c space handler\n");
411 acpi_bus_detach_private_data(handle);
412 kfree(data);
413 return -ENOMEM;
416 acpi_walk_dep_device_list(handle);
417 return 0;
420 static void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
422 acpi_handle handle;
423 struct acpi_i2c_handler_data *data;
424 acpi_status status;
426 if (!adapter->dev.parent)
427 return;
429 handle = ACPI_HANDLE(adapter->dev.parent);
431 if (!handle)
432 return;
434 acpi_remove_address_space_handler(handle,
435 ACPI_ADR_SPACE_GSBUS,
436 &acpi_i2c_space_handler);
438 status = acpi_bus_get_private_data(handle, (void **)&data);
439 if (ACPI_SUCCESS(status))
440 kfree(data);
442 acpi_bus_detach_private_data(handle);
444 #else /* CONFIG_ACPI_I2C_OPREGION */
445 static inline void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
448 static inline int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
449 { return 0; }
450 #endif /* CONFIG_ACPI_I2C_OPREGION */
452 /* ------------------------------------------------------------------------- */
454 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
455 const struct i2c_client *client)
457 while (id->name[0]) {
458 if (strcmp(client->name, id->name) == 0)
459 return id;
460 id++;
462 return NULL;
465 static int i2c_device_match(struct device *dev, struct device_driver *drv)
467 struct i2c_client *client = i2c_verify_client(dev);
468 struct i2c_driver *driver;
470 if (!client)
471 return 0;
473 /* Attempt an OF style match */
474 if (of_driver_match_device(dev, drv))
475 return 1;
477 /* Then ACPI style match */
478 if (acpi_driver_match_device(dev, drv))
479 return 1;
481 driver = to_i2c_driver(drv);
482 /* match on an id table if there is one */
483 if (driver->id_table)
484 return i2c_match_id(driver->id_table, client) != NULL;
486 return 0;
490 /* uevent helps with hotplug: modprobe -q $(MODALIAS) */
491 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
493 struct i2c_client *client = to_i2c_client(dev);
494 int rc;
496 rc = acpi_device_uevent_modalias(dev, env);
497 if (rc != -ENODEV)
498 return rc;
500 if (add_uevent_var(env, "MODALIAS=%s%s",
501 I2C_MODULE_PREFIX, client->name))
502 return -ENOMEM;
503 dev_dbg(dev, "uevent\n");
504 return 0;
507 /* i2c bus recovery routines */
508 static int get_scl_gpio_value(struct i2c_adapter *adap)
510 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
513 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
515 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
518 static int get_sda_gpio_value(struct i2c_adapter *adap)
520 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
523 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
525 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
526 struct device *dev = &adap->dev;
527 int ret = 0;
529 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
530 GPIOF_OUT_INIT_HIGH, "i2c-scl");
531 if (ret) {
532 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
533 return ret;
536 if (bri->get_sda) {
537 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
538 /* work without SDA polling */
539 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
540 bri->sda_gpio);
541 bri->get_sda = NULL;
545 return ret;
548 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
550 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
552 if (bri->get_sda)
553 gpio_free(bri->sda_gpio);
555 gpio_free(bri->scl_gpio);
559 * We are generating clock pulses. ndelay() determines durating of clk pulses.
560 * We will generate clock with rate 100 KHz and so duration of both clock levels
561 * is: delay in ns = (10^6 / 100) / 2
563 #define RECOVERY_NDELAY 5000
564 #define RECOVERY_CLK_CNT 9
566 static int i2c_generic_recovery(struct i2c_adapter *adap)
568 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
569 int i = 0, val = 1, ret = 0;
571 if (bri->prepare_recovery)
572 bri->prepare_recovery(adap);
574 bri->set_scl(adap, val);
575 ndelay(RECOVERY_NDELAY);
578 * By this time SCL is high, as we need to give 9 falling-rising edges
580 while (i++ < RECOVERY_CLK_CNT * 2) {
581 if (val) {
582 /* Break if SDA is high */
583 if (bri->get_sda && bri->get_sda(adap))
584 break;
585 /* SCL shouldn't be low here */
586 if (!bri->get_scl(adap)) {
587 dev_err(&adap->dev,
588 "SCL is stuck low, exit recovery\n");
589 ret = -EBUSY;
590 break;
594 val = !val;
595 bri->set_scl(adap, val);
596 ndelay(RECOVERY_NDELAY);
599 if (bri->unprepare_recovery)
600 bri->unprepare_recovery(adap);
602 return ret;
605 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
607 return i2c_generic_recovery(adap);
609 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
611 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
613 int ret;
615 ret = i2c_get_gpios_for_recovery(adap);
616 if (ret)
617 return ret;
619 ret = i2c_generic_recovery(adap);
620 i2c_put_gpios_for_recovery(adap);
622 return ret;
624 EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
626 int i2c_recover_bus(struct i2c_adapter *adap)
628 if (!adap->bus_recovery_info)
629 return -EOPNOTSUPP;
631 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
632 return adap->bus_recovery_info->recover_bus(adap);
634 EXPORT_SYMBOL_GPL(i2c_recover_bus);
636 static int i2c_device_probe(struct device *dev)
638 struct i2c_client *client = i2c_verify_client(dev);
639 struct i2c_driver *driver;
640 int status;
642 if (!client)
643 return 0;
645 if (!client->irq) {
646 int irq = -ENOENT;
648 if (dev->of_node)
649 irq = of_irq_get(dev->of_node, 0);
650 else if (ACPI_COMPANION(dev))
651 irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
653 if (irq == -EPROBE_DEFER)
654 return irq;
655 if (irq < 0)
656 irq = 0;
658 client->irq = irq;
661 driver = to_i2c_driver(dev->driver);
662 if (!driver->probe || !driver->id_table)
663 return -ENODEV;
665 if (!device_can_wakeup(&client->dev))
666 device_init_wakeup(&client->dev,
667 client->flags & I2C_CLIENT_WAKE);
668 dev_dbg(dev, "probe\n");
670 status = of_clk_set_defaults(dev->of_node, false);
671 if (status < 0)
672 return status;
674 status = dev_pm_domain_attach(&client->dev, true);
675 if (status != -EPROBE_DEFER) {
676 status = driver->probe(client, i2c_match_id(driver->id_table,
677 client));
678 if (status)
679 dev_pm_domain_detach(&client->dev, true);
682 return status;
685 static int i2c_device_remove(struct device *dev)
687 struct i2c_client *client = i2c_verify_client(dev);
688 struct i2c_driver *driver;
689 int status = 0;
691 if (!client || !dev->driver)
692 return 0;
694 driver = to_i2c_driver(dev->driver);
695 if (driver->remove) {
696 dev_dbg(dev, "remove\n");
697 status = driver->remove(client);
700 dev_pm_domain_detach(&client->dev, true);
701 return status;
704 static void i2c_device_shutdown(struct device *dev)
706 struct i2c_client *client = i2c_verify_client(dev);
707 struct i2c_driver *driver;
709 if (!client || !dev->driver)
710 return;
711 driver = to_i2c_driver(dev->driver);
712 if (driver->shutdown)
713 driver->shutdown(client);
716 static void i2c_client_dev_release(struct device *dev)
718 kfree(to_i2c_client(dev));
721 static ssize_t
722 show_name(struct device *dev, struct device_attribute *attr, char *buf)
724 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
725 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
727 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
729 static ssize_t
730 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
732 struct i2c_client *client = to_i2c_client(dev);
733 int len;
735 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
736 if (len != -ENODEV)
737 return len;
739 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
741 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
743 static struct attribute *i2c_dev_attrs[] = {
744 &dev_attr_name.attr,
745 /* modalias helps coldplug: modprobe $(cat .../modalias) */
746 &dev_attr_modalias.attr,
747 NULL
749 ATTRIBUTE_GROUPS(i2c_dev);
751 struct bus_type i2c_bus_type = {
752 .name = "i2c",
753 .match = i2c_device_match,
754 .probe = i2c_device_probe,
755 .remove = i2c_device_remove,
756 .shutdown = i2c_device_shutdown,
758 EXPORT_SYMBOL_GPL(i2c_bus_type);
760 static struct device_type i2c_client_type = {
761 .groups = i2c_dev_groups,
762 .uevent = i2c_device_uevent,
763 .release = i2c_client_dev_release,
768 * i2c_verify_client - return parameter as i2c_client, or NULL
769 * @dev: device, probably from some driver model iterator
771 * When traversing the driver model tree, perhaps using driver model
772 * iterators like @device_for_each_child(), you can't assume very much
773 * about the nodes you find. Use this function to avoid oopses caused
774 * by wrongly treating some non-I2C device as an i2c_client.
776 struct i2c_client *i2c_verify_client(struct device *dev)
778 return (dev->type == &i2c_client_type)
779 ? to_i2c_client(dev)
780 : NULL;
782 EXPORT_SYMBOL(i2c_verify_client);
785 /* Return a unique address which takes the flags of the client into account */
786 static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
788 unsigned short addr = client->addr;
790 /* For some client flags, add an arbitrary offset to avoid collisions */
791 if (client->flags & I2C_CLIENT_TEN)
792 addr |= I2C_ADDR_OFFSET_TEN_BIT;
794 if (client->flags & I2C_CLIENT_SLAVE)
795 addr |= I2C_ADDR_OFFSET_SLAVE;
797 return addr;
800 /* This is a permissive address validity check, I2C address map constraints
801 * are purposely not enforced, except for the general call address. */
802 static int i2c_check_addr_validity(unsigned addr, unsigned short flags)
804 if (flags & I2C_CLIENT_TEN) {
805 /* 10-bit address, all values are valid */
806 if (addr > 0x3ff)
807 return -EINVAL;
808 } else {
809 /* 7-bit address, reject the general call address */
810 if (addr == 0x00 || addr > 0x7f)
811 return -EINVAL;
813 return 0;
816 /* And this is a strict address validity check, used when probing. If a
817 * device uses a reserved address, then it shouldn't be probed. 7-bit
818 * addressing is assumed, 10-bit address devices are rare and should be
819 * explicitly enumerated. */
820 static int i2c_check_7bit_addr_validity_strict(unsigned short addr)
823 * Reserved addresses per I2C specification:
824 * 0x00 General call address / START byte
825 * 0x01 CBUS address
826 * 0x02 Reserved for different bus format
827 * 0x03 Reserved for future purposes
828 * 0x04-0x07 Hs-mode master code
829 * 0x78-0x7b 10-bit slave addressing
830 * 0x7c-0x7f Reserved for future purposes
832 if (addr < 0x08 || addr > 0x77)
833 return -EINVAL;
834 return 0;
837 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
839 struct i2c_client *client = i2c_verify_client(dev);
840 int addr = *(int *)addrp;
842 if (client && i2c_encode_flags_to_addr(client) == addr)
843 return -EBUSY;
844 return 0;
847 /* walk up mux tree */
848 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
850 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
851 int result;
853 result = device_for_each_child(&adapter->dev, &addr,
854 __i2c_check_addr_busy);
856 if (!result && parent)
857 result = i2c_check_mux_parents(parent, addr);
859 return result;
862 /* recurse down mux tree */
863 static int i2c_check_mux_children(struct device *dev, void *addrp)
865 int result;
867 if (dev->type == &i2c_adapter_type)
868 result = device_for_each_child(dev, addrp,
869 i2c_check_mux_children);
870 else
871 result = __i2c_check_addr_busy(dev, addrp);
873 return result;
876 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
878 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
879 int result = 0;
881 if (parent)
882 result = i2c_check_mux_parents(parent, addr);
884 if (!result)
885 result = device_for_each_child(&adapter->dev, &addr,
886 i2c_check_mux_children);
888 return result;
892 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
893 * @adapter: Target I2C bus segment
895 void i2c_lock_adapter(struct i2c_adapter *adapter)
897 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
899 if (parent)
900 i2c_lock_adapter(parent);
901 else
902 rt_mutex_lock(&adapter->bus_lock);
904 EXPORT_SYMBOL_GPL(i2c_lock_adapter);
907 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
908 * @adapter: Target I2C bus segment
910 static int i2c_trylock_adapter(struct i2c_adapter *adapter)
912 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
914 if (parent)
915 return i2c_trylock_adapter(parent);
916 else
917 return rt_mutex_trylock(&adapter->bus_lock);
921 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
922 * @adapter: Target I2C bus segment
924 void i2c_unlock_adapter(struct i2c_adapter *adapter)
926 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
928 if (parent)
929 i2c_unlock_adapter(parent);
930 else
931 rt_mutex_unlock(&adapter->bus_lock);
933 EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
935 static void i2c_dev_set_name(struct i2c_adapter *adap,
936 struct i2c_client *client)
938 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
940 if (adev) {
941 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
942 return;
945 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
946 i2c_encode_flags_to_addr(client));
950 * i2c_new_device - instantiate an i2c device
951 * @adap: the adapter managing the device
952 * @info: describes one I2C device; bus_num is ignored
953 * Context: can sleep
955 * Create an i2c device. Binding is handled through driver model
956 * probe()/remove() methods. A driver may be bound to this device when we
957 * return from this function, or any later moment (e.g. maybe hotplugging will
958 * load the driver module). This call is not appropriate for use by mainboard
959 * initialization logic, which usually runs during an arch_initcall() long
960 * before any i2c_adapter could exist.
962 * This returns the new i2c client, which may be saved for later use with
963 * i2c_unregister_device(); or NULL to indicate an error.
965 struct i2c_client *
966 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
968 struct i2c_client *client;
969 int status;
971 client = kzalloc(sizeof *client, GFP_KERNEL);
972 if (!client)
973 return NULL;
975 client->adapter = adap;
977 client->dev.platform_data = info->platform_data;
979 if (info->archdata)
980 client->dev.archdata = *info->archdata;
982 client->flags = info->flags;
983 client->addr = info->addr;
984 client->irq = info->irq;
986 strlcpy(client->name, info->type, sizeof(client->name));
988 status = i2c_check_addr_validity(client->addr, client->flags);
989 if (status) {
990 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
991 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
992 goto out_err_silent;
995 /* Check for address business */
996 status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
997 if (status)
998 goto out_err;
1000 client->dev.parent = &client->adapter->dev;
1001 client->dev.bus = &i2c_bus_type;
1002 client->dev.type = &i2c_client_type;
1003 client->dev.of_node = info->of_node;
1004 client->dev.fwnode = info->fwnode;
1006 i2c_dev_set_name(adap, client);
1007 status = device_register(&client->dev);
1008 if (status)
1009 goto out_err;
1011 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1012 client->name, dev_name(&client->dev));
1014 return client;
1016 out_err:
1017 dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
1018 "(%d)\n", client->name, client->addr, status);
1019 out_err_silent:
1020 kfree(client);
1021 return NULL;
1023 EXPORT_SYMBOL_GPL(i2c_new_device);
1027 * i2c_unregister_device - reverse effect of i2c_new_device()
1028 * @client: value returned from i2c_new_device()
1029 * Context: can sleep
1031 void i2c_unregister_device(struct i2c_client *client)
1033 if (client->dev.of_node)
1034 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
1035 device_unregister(&client->dev);
1037 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1040 static const struct i2c_device_id dummy_id[] = {
1041 { "dummy", 0 },
1042 { },
1045 static int dummy_probe(struct i2c_client *client,
1046 const struct i2c_device_id *id)
1048 return 0;
1051 static int dummy_remove(struct i2c_client *client)
1053 return 0;
1056 static struct i2c_driver dummy_driver = {
1057 .driver.name = "dummy",
1058 .probe = dummy_probe,
1059 .remove = dummy_remove,
1060 .id_table = dummy_id,
1064 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1065 * @adapter: the adapter managing the device
1066 * @address: seven bit address to be used
1067 * Context: can sleep
1069 * This returns an I2C client bound to the "dummy" driver, intended for use
1070 * with devices that consume multiple addresses. Examples of such chips
1071 * include various EEPROMS (like 24c04 and 24c08 models).
1073 * These dummy devices have two main uses. First, most I2C and SMBus calls
1074 * except i2c_transfer() need a client handle; the dummy will be that handle.
1075 * And second, this prevents the specified address from being bound to a
1076 * different driver.
1078 * This returns the new i2c client, which should be saved for later use with
1079 * i2c_unregister_device(); or NULL to indicate an error.
1081 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1083 struct i2c_board_info info = {
1084 I2C_BOARD_INFO("dummy", address),
1087 return i2c_new_device(adapter, &info);
1089 EXPORT_SYMBOL_GPL(i2c_new_dummy);
1091 /* ------------------------------------------------------------------------- */
1093 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1095 static void i2c_adapter_dev_release(struct device *dev)
1097 struct i2c_adapter *adap = to_i2c_adapter(dev);
1098 complete(&adap->dev_released);
1102 * This function is only needed for mutex_lock_nested, so it is never
1103 * called unless locking correctness checking is enabled. Thus we
1104 * make it inline to avoid a compiler warning. That's what gcc ends up
1105 * doing anyway.
1107 static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1109 unsigned int depth = 0;
1111 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1112 depth++;
1114 return depth;
1118 * Let users instantiate I2C devices through sysfs. This can be used when
1119 * platform initialization code doesn't contain the proper data for
1120 * whatever reason. Also useful for drivers that do device detection and
1121 * detection fails, either because the device uses an unexpected address,
1122 * or this is a compatible device with different ID register values.
1124 * Parameter checking may look overzealous, but we really don't want
1125 * the user to provide incorrect parameters.
1127 static ssize_t
1128 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1129 const char *buf, size_t count)
1131 struct i2c_adapter *adap = to_i2c_adapter(dev);
1132 struct i2c_board_info info;
1133 struct i2c_client *client;
1134 char *blank, end;
1135 int res;
1137 memset(&info, 0, sizeof(struct i2c_board_info));
1139 blank = strchr(buf, ' ');
1140 if (!blank) {
1141 dev_err(dev, "%s: Missing parameters\n", "new_device");
1142 return -EINVAL;
1144 if (blank - buf > I2C_NAME_SIZE - 1) {
1145 dev_err(dev, "%s: Invalid device name\n", "new_device");
1146 return -EINVAL;
1148 memcpy(info.type, buf, blank - buf);
1150 /* Parse remaining parameters, reject extra parameters */
1151 res = sscanf(++blank, "%hi%c", &info.addr, &end);
1152 if (res < 1) {
1153 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1154 return -EINVAL;
1156 if (res > 1 && end != '\n') {
1157 dev_err(dev, "%s: Extra parameters\n", "new_device");
1158 return -EINVAL;
1161 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1162 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1163 info.flags |= I2C_CLIENT_TEN;
1166 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1167 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1168 info.flags |= I2C_CLIENT_SLAVE;
1171 client = i2c_new_device(adap, &info);
1172 if (!client)
1173 return -EINVAL;
1175 /* Keep track of the added device */
1176 mutex_lock(&adap->userspace_clients_lock);
1177 list_add_tail(&client->detected, &adap->userspace_clients);
1178 mutex_unlock(&adap->userspace_clients_lock);
1179 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1180 info.type, info.addr);
1182 return count;
1184 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1187 * And of course let the users delete the devices they instantiated, if
1188 * they got it wrong. This interface can only be used to delete devices
1189 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1190 * don't delete devices to which some kernel code still has references.
1192 * Parameter checking may look overzealous, but we really don't want
1193 * the user to delete the wrong device.
1195 static ssize_t
1196 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1197 const char *buf, size_t count)
1199 struct i2c_adapter *adap = to_i2c_adapter(dev);
1200 struct i2c_client *client, *next;
1201 unsigned short addr;
1202 char end;
1203 int res;
1205 /* Parse parameters, reject extra parameters */
1206 res = sscanf(buf, "%hi%c", &addr, &end);
1207 if (res < 1) {
1208 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1209 return -EINVAL;
1211 if (res > 1 && end != '\n') {
1212 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1213 return -EINVAL;
1216 /* Make sure the device was added through sysfs */
1217 res = -ENOENT;
1218 mutex_lock_nested(&adap->userspace_clients_lock,
1219 i2c_adapter_depth(adap));
1220 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1221 detected) {
1222 if (i2c_encode_flags_to_addr(client) == addr) {
1223 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1224 "delete_device", client->name, client->addr);
1226 list_del(&client->detected);
1227 i2c_unregister_device(client);
1228 res = count;
1229 break;
1232 mutex_unlock(&adap->userspace_clients_lock);
1234 if (res < 0)
1235 dev_err(dev, "%s: Can't find device in list\n",
1236 "delete_device");
1237 return res;
1239 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1240 i2c_sysfs_delete_device);
1242 static struct attribute *i2c_adapter_attrs[] = {
1243 &dev_attr_name.attr,
1244 &dev_attr_new_device.attr,
1245 &dev_attr_delete_device.attr,
1246 NULL
1248 ATTRIBUTE_GROUPS(i2c_adapter);
1250 struct device_type i2c_adapter_type = {
1251 .groups = i2c_adapter_groups,
1252 .release = i2c_adapter_dev_release,
1254 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1257 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1258 * @dev: device, probably from some driver model iterator
1260 * When traversing the driver model tree, perhaps using driver model
1261 * iterators like @device_for_each_child(), you can't assume very much
1262 * about the nodes you find. Use this function to avoid oopses caused
1263 * by wrongly treating some non-I2C device as an i2c_adapter.
1265 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1267 return (dev->type == &i2c_adapter_type)
1268 ? to_i2c_adapter(dev)
1269 : NULL;
1271 EXPORT_SYMBOL(i2c_verify_adapter);
1273 #ifdef CONFIG_I2C_COMPAT
1274 static struct class_compat *i2c_adapter_compat_class;
1275 #endif
1277 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1279 struct i2c_devinfo *devinfo;
1281 down_read(&__i2c_board_lock);
1282 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1283 if (devinfo->busnum == adapter->nr
1284 && !i2c_new_device(adapter,
1285 &devinfo->board_info))
1286 dev_err(&adapter->dev,
1287 "Can't create device at 0x%02x\n",
1288 devinfo->board_info.addr);
1290 up_read(&__i2c_board_lock);
1293 /* OF support code */
1295 #if IS_ENABLED(CONFIG_OF)
1296 static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1297 struct device_node *node)
1299 struct i2c_client *result;
1300 struct i2c_board_info info = {};
1301 struct dev_archdata dev_ad = {};
1302 const __be32 *addr_be;
1303 u32 addr;
1304 int len;
1306 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1308 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1309 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1310 node->full_name);
1311 return ERR_PTR(-EINVAL);
1314 addr_be = of_get_property(node, "reg", &len);
1315 if (!addr_be || (len < sizeof(*addr_be))) {
1316 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1317 node->full_name);
1318 return ERR_PTR(-EINVAL);
1321 addr = be32_to_cpup(addr_be);
1322 if (addr & I2C_TEN_BIT_ADDRESS) {
1323 addr &= ~I2C_TEN_BIT_ADDRESS;
1324 info.flags |= I2C_CLIENT_TEN;
1327 if (addr & I2C_OWN_SLAVE_ADDRESS) {
1328 addr &= ~I2C_OWN_SLAVE_ADDRESS;
1329 info.flags |= I2C_CLIENT_SLAVE;
1332 if (i2c_check_addr_validity(addr, info.flags)) {
1333 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1334 info.addr, node->full_name);
1335 return ERR_PTR(-EINVAL);
1338 info.addr = addr;
1339 info.of_node = of_node_get(node);
1340 info.archdata = &dev_ad;
1342 if (of_get_property(node, "wakeup-source", NULL))
1343 info.flags |= I2C_CLIENT_WAKE;
1345 result = i2c_new_device(adap, &info);
1346 if (result == NULL) {
1347 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1348 node->full_name);
1349 of_node_put(node);
1350 return ERR_PTR(-EINVAL);
1352 return result;
1355 static void of_i2c_register_devices(struct i2c_adapter *adap)
1357 struct device_node *node;
1359 /* Only register child devices if the adapter has a node pointer set */
1360 if (!adap->dev.of_node)
1361 return;
1363 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1365 for_each_available_child_of_node(adap->dev.of_node, node) {
1366 if (of_node_test_and_set_flag(node, OF_POPULATED))
1367 continue;
1368 of_i2c_register_device(adap, node);
1372 static int of_dev_node_match(struct device *dev, void *data)
1374 return dev->of_node == data;
1377 /* must call put_device() when done with returned i2c_client device */
1378 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1380 struct device *dev;
1381 struct i2c_client *client;
1383 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1384 if (!dev)
1385 return NULL;
1387 client = i2c_verify_client(dev);
1388 if (!client)
1389 put_device(dev);
1391 return client;
1393 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1395 /* must call put_device() when done with returned i2c_adapter device */
1396 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1398 struct device *dev;
1399 struct i2c_adapter *adapter;
1401 dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1402 if (!dev)
1403 return NULL;
1405 adapter = i2c_verify_adapter(dev);
1406 if (!adapter)
1407 put_device(dev);
1409 return adapter;
1411 EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1413 /* must call i2c_put_adapter() when done with returned i2c_adapter device */
1414 struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1416 struct i2c_adapter *adapter;
1418 adapter = of_find_i2c_adapter_by_node(node);
1419 if (!adapter)
1420 return NULL;
1422 if (!try_module_get(adapter->owner)) {
1423 put_device(&adapter->dev);
1424 adapter = NULL;
1427 return adapter;
1429 EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1430 #else
1431 static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1432 #endif /* CONFIG_OF */
1434 static int i2c_do_add_adapter(struct i2c_driver *driver,
1435 struct i2c_adapter *adap)
1437 /* Detect supported devices on that bus, and instantiate them */
1438 i2c_detect(adap, driver);
1440 /* Let legacy drivers scan this bus for matching devices */
1441 if (driver->attach_adapter) {
1442 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1443 driver->driver.name);
1444 dev_warn(&adap->dev, "Please use another way to instantiate "
1445 "your i2c_client\n");
1446 /* We ignore the return code; if it fails, too bad */
1447 driver->attach_adapter(adap);
1449 return 0;
1452 static int __process_new_adapter(struct device_driver *d, void *data)
1454 return i2c_do_add_adapter(to_i2c_driver(d), data);
1457 static int i2c_register_adapter(struct i2c_adapter *adap)
1459 int res = 0;
1461 /* Can't register until after driver model init */
1462 if (unlikely(WARN_ON(!i2c_bus_type.p))) {
1463 res = -EAGAIN;
1464 goto out_list;
1467 /* Sanity checks */
1468 if (unlikely(adap->name[0] == '\0')) {
1469 pr_err("i2c-core: Attempt to register an adapter with "
1470 "no name!\n");
1471 return -EINVAL;
1473 if (unlikely(!adap->algo)) {
1474 pr_err("i2c-core: Attempt to register adapter '%s' with "
1475 "no algo!\n", adap->name);
1476 return -EINVAL;
1479 rt_mutex_init(&adap->bus_lock);
1480 mutex_init(&adap->userspace_clients_lock);
1481 INIT_LIST_HEAD(&adap->userspace_clients);
1483 /* Set default timeout to 1 second if not already set */
1484 if (adap->timeout == 0)
1485 adap->timeout = HZ;
1487 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1488 adap->dev.bus = &i2c_bus_type;
1489 adap->dev.type = &i2c_adapter_type;
1490 res = device_register(&adap->dev);
1491 if (res)
1492 goto out_list;
1494 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1496 pm_runtime_no_callbacks(&adap->dev);
1498 #ifdef CONFIG_I2C_COMPAT
1499 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1500 adap->dev.parent);
1501 if (res)
1502 dev_warn(&adap->dev,
1503 "Failed to create compatibility class link\n");
1504 #endif
1506 /* bus recovery specific initialization */
1507 if (adap->bus_recovery_info) {
1508 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
1510 if (!bri->recover_bus) {
1511 dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
1512 adap->bus_recovery_info = NULL;
1513 goto exit_recovery;
1516 /* Generic GPIO recovery */
1517 if (bri->recover_bus == i2c_generic_gpio_recovery) {
1518 if (!gpio_is_valid(bri->scl_gpio)) {
1519 dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
1520 adap->bus_recovery_info = NULL;
1521 goto exit_recovery;
1524 if (gpio_is_valid(bri->sda_gpio))
1525 bri->get_sda = get_sda_gpio_value;
1526 else
1527 bri->get_sda = NULL;
1529 bri->get_scl = get_scl_gpio_value;
1530 bri->set_scl = set_scl_gpio_value;
1531 } else if (!bri->set_scl || !bri->get_scl) {
1532 /* Generic SCL recovery */
1533 dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
1534 adap->bus_recovery_info = NULL;
1538 exit_recovery:
1539 /* create pre-declared device nodes */
1540 of_i2c_register_devices(adap);
1541 acpi_i2c_register_devices(adap);
1542 acpi_i2c_install_space_handler(adap);
1544 if (adap->nr < __i2c_first_dynamic_bus_num)
1545 i2c_scan_static_board_info(adap);
1547 /* Notify drivers */
1548 mutex_lock(&core_lock);
1549 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1550 mutex_unlock(&core_lock);
1552 return 0;
1554 out_list:
1555 mutex_lock(&core_lock);
1556 idr_remove(&i2c_adapter_idr, adap->nr);
1557 mutex_unlock(&core_lock);
1558 return res;
1562 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1563 * @adap: the adapter to register (with adap->nr initialized)
1564 * Context: can sleep
1566 * See i2c_add_numbered_adapter() for details.
1568 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1570 int id;
1572 mutex_lock(&core_lock);
1573 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1,
1574 GFP_KERNEL);
1575 mutex_unlock(&core_lock);
1576 if (id < 0)
1577 return id == -ENOSPC ? -EBUSY : id;
1579 return i2c_register_adapter(adap);
1583 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1584 * @adapter: the adapter to add
1585 * Context: can sleep
1587 * This routine is used to declare an I2C adapter when its bus number
1588 * doesn't matter or when its bus number is specified by an dt alias.
1589 * Examples of bases when the bus number doesn't matter: I2C adapters
1590 * dynamically added by USB links or PCI plugin cards.
1592 * When this returns zero, a new bus number was allocated and stored
1593 * in adap->nr, and the specified adapter became available for clients.
1594 * Otherwise, a negative errno value is returned.
1596 int i2c_add_adapter(struct i2c_adapter *adapter)
1598 struct device *dev = &adapter->dev;
1599 int id;
1601 if (dev->of_node) {
1602 id = of_alias_get_id(dev->of_node, "i2c");
1603 if (id >= 0) {
1604 adapter->nr = id;
1605 return __i2c_add_numbered_adapter(adapter);
1609 mutex_lock(&core_lock);
1610 id = idr_alloc(&i2c_adapter_idr, adapter,
1611 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1612 mutex_unlock(&core_lock);
1613 if (id < 0)
1614 return id;
1616 adapter->nr = id;
1618 return i2c_register_adapter(adapter);
1620 EXPORT_SYMBOL(i2c_add_adapter);
1623 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1624 * @adap: the adapter to register (with adap->nr initialized)
1625 * Context: can sleep
1627 * This routine is used to declare an I2C adapter when its bus number
1628 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1629 * or otherwise built in to the system's mainboard, and where i2c_board_info
1630 * is used to properly configure I2C devices.
1632 * If the requested bus number is set to -1, then this function will behave
1633 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1635 * If no devices have pre-been declared for this bus, then be sure to
1636 * register the adapter before any dynamically allocated ones. Otherwise
1637 * the required bus ID may not be available.
1639 * When this returns zero, the specified adapter became available for
1640 * clients using the bus number provided in adap->nr. Also, the table
1641 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1642 * and the appropriate driver model device nodes are created. Otherwise, a
1643 * negative errno value is returned.
1645 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1647 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1648 return i2c_add_adapter(adap);
1650 return __i2c_add_numbered_adapter(adap);
1652 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1654 static void i2c_do_del_adapter(struct i2c_driver *driver,
1655 struct i2c_adapter *adapter)
1657 struct i2c_client *client, *_n;
1659 /* Remove the devices we created ourselves as the result of hardware
1660 * probing (using a driver's detect method) */
1661 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1662 if (client->adapter == adapter) {
1663 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1664 client->name, client->addr);
1665 list_del(&client->detected);
1666 i2c_unregister_device(client);
1671 static int __unregister_client(struct device *dev, void *dummy)
1673 struct i2c_client *client = i2c_verify_client(dev);
1674 if (client && strcmp(client->name, "dummy"))
1675 i2c_unregister_device(client);
1676 return 0;
1679 static int __unregister_dummy(struct device *dev, void *dummy)
1681 struct i2c_client *client = i2c_verify_client(dev);
1682 if (client)
1683 i2c_unregister_device(client);
1684 return 0;
1687 static int __process_removed_adapter(struct device_driver *d, void *data)
1689 i2c_do_del_adapter(to_i2c_driver(d), data);
1690 return 0;
1694 * i2c_del_adapter - unregister I2C adapter
1695 * @adap: the adapter being unregistered
1696 * Context: can sleep
1698 * This unregisters an I2C adapter which was previously registered
1699 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1701 void i2c_del_adapter(struct i2c_adapter *adap)
1703 struct i2c_adapter *found;
1704 struct i2c_client *client, *next;
1706 /* First make sure that this adapter was ever added */
1707 mutex_lock(&core_lock);
1708 found = idr_find(&i2c_adapter_idr, adap->nr);
1709 mutex_unlock(&core_lock);
1710 if (found != adap) {
1711 pr_debug("i2c-core: attempting to delete unregistered "
1712 "adapter [%s]\n", adap->name);
1713 return;
1716 acpi_i2c_remove_space_handler(adap);
1717 /* Tell drivers about this removal */
1718 mutex_lock(&core_lock);
1719 bus_for_each_drv(&i2c_bus_type, NULL, adap,
1720 __process_removed_adapter);
1721 mutex_unlock(&core_lock);
1723 /* Remove devices instantiated from sysfs */
1724 mutex_lock_nested(&adap->userspace_clients_lock,
1725 i2c_adapter_depth(adap));
1726 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1727 detected) {
1728 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1729 client->addr);
1730 list_del(&client->detected);
1731 i2c_unregister_device(client);
1733 mutex_unlock(&adap->userspace_clients_lock);
1735 /* Detach any active clients. This can't fail, thus we do not
1736 * check the returned value. This is a two-pass process, because
1737 * we can't remove the dummy devices during the first pass: they
1738 * could have been instantiated by real devices wishing to clean
1739 * them up properly, so we give them a chance to do that first. */
1740 device_for_each_child(&adap->dev, NULL, __unregister_client);
1741 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1743 #ifdef CONFIG_I2C_COMPAT
1744 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1745 adap->dev.parent);
1746 #endif
1748 /* device name is gone after device_unregister */
1749 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1751 /* wait until all references to the device are gone
1753 * FIXME: This is old code and should ideally be replaced by an
1754 * alternative which results in decoupling the lifetime of the struct
1755 * device from the i2c_adapter, like spi or netdev do. Any solution
1756 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
1758 init_completion(&adap->dev_released);
1759 device_unregister(&adap->dev);
1760 wait_for_completion(&adap->dev_released);
1762 /* free bus id */
1763 mutex_lock(&core_lock);
1764 idr_remove(&i2c_adapter_idr, adap->nr);
1765 mutex_unlock(&core_lock);
1767 /* Clear the device structure in case this adapter is ever going to be
1768 added again */
1769 memset(&adap->dev, 0, sizeof(adap->dev));
1771 EXPORT_SYMBOL(i2c_del_adapter);
1773 /* ------------------------------------------------------------------------- */
1775 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1777 int res;
1779 mutex_lock(&core_lock);
1780 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1781 mutex_unlock(&core_lock);
1783 return res;
1785 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1787 static int __process_new_driver(struct device *dev, void *data)
1789 if (dev->type != &i2c_adapter_type)
1790 return 0;
1791 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1795 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1796 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1799 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1801 int res;
1803 /* Can't register until after driver model init */
1804 if (unlikely(WARN_ON(!i2c_bus_type.p)))
1805 return -EAGAIN;
1807 /* add the driver to the list of i2c drivers in the driver core */
1808 driver->driver.owner = owner;
1809 driver->driver.bus = &i2c_bus_type;
1811 /* When registration returns, the driver core
1812 * will have called probe() for all matching-but-unbound devices.
1814 res = driver_register(&driver->driver);
1815 if (res)
1816 return res;
1818 pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
1820 INIT_LIST_HEAD(&driver->clients);
1821 /* Walk the adapters that are already present */
1822 i2c_for_each_dev(driver, __process_new_driver);
1824 return 0;
1826 EXPORT_SYMBOL(i2c_register_driver);
1828 static int __process_removed_driver(struct device *dev, void *data)
1830 if (dev->type == &i2c_adapter_type)
1831 i2c_do_del_adapter(data, to_i2c_adapter(dev));
1832 return 0;
1836 * i2c_del_driver - unregister I2C driver
1837 * @driver: the driver being unregistered
1838 * Context: can sleep
1840 void i2c_del_driver(struct i2c_driver *driver)
1842 i2c_for_each_dev(driver, __process_removed_driver);
1844 driver_unregister(&driver->driver);
1845 pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
1847 EXPORT_SYMBOL(i2c_del_driver);
1849 /* ------------------------------------------------------------------------- */
1852 * i2c_use_client - increments the reference count of the i2c client structure
1853 * @client: the client being referenced
1855 * Each live reference to a client should be refcounted. The driver model does
1856 * that automatically as part of driver binding, so that most drivers don't
1857 * need to do this explicitly: they hold a reference until they're unbound
1858 * from the device.
1860 * A pointer to the client with the incremented reference counter is returned.
1862 struct i2c_client *i2c_use_client(struct i2c_client *client)
1864 if (client && get_device(&client->dev))
1865 return client;
1866 return NULL;
1868 EXPORT_SYMBOL(i2c_use_client);
1871 * i2c_release_client - release a use of the i2c client structure
1872 * @client: the client being no longer referenced
1874 * Must be called when a user of a client is finished with it.
1876 void i2c_release_client(struct i2c_client *client)
1878 if (client)
1879 put_device(&client->dev);
1881 EXPORT_SYMBOL(i2c_release_client);
1883 struct i2c_cmd_arg {
1884 unsigned cmd;
1885 void *arg;
1888 static int i2c_cmd(struct device *dev, void *_arg)
1890 struct i2c_client *client = i2c_verify_client(dev);
1891 struct i2c_cmd_arg *arg = _arg;
1892 struct i2c_driver *driver;
1894 if (!client || !client->dev.driver)
1895 return 0;
1897 driver = to_i2c_driver(client->dev.driver);
1898 if (driver->command)
1899 driver->command(client, arg->cmd, arg->arg);
1900 return 0;
1903 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1905 struct i2c_cmd_arg cmd_arg;
1907 cmd_arg.cmd = cmd;
1908 cmd_arg.arg = arg;
1909 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1911 EXPORT_SYMBOL(i2c_clients_command);
1913 #if IS_ENABLED(CONFIG_OF_DYNAMIC)
1914 static int of_i2c_notify(struct notifier_block *nb, unsigned long action,
1915 void *arg)
1917 struct of_reconfig_data *rd = arg;
1918 struct i2c_adapter *adap;
1919 struct i2c_client *client;
1921 switch (of_reconfig_get_state_change(action, rd)) {
1922 case OF_RECONFIG_CHANGE_ADD:
1923 adap = of_find_i2c_adapter_by_node(rd->dn->parent);
1924 if (adap == NULL)
1925 return NOTIFY_OK; /* not for us */
1927 if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
1928 put_device(&adap->dev);
1929 return NOTIFY_OK;
1932 client = of_i2c_register_device(adap, rd->dn);
1933 put_device(&adap->dev);
1935 if (IS_ERR(client)) {
1936 pr_err("%s: failed to create for '%s'\n",
1937 __func__, rd->dn->full_name);
1938 return notifier_from_errno(PTR_ERR(client));
1940 break;
1941 case OF_RECONFIG_CHANGE_REMOVE:
1942 /* already depopulated? */
1943 if (!of_node_check_flag(rd->dn, OF_POPULATED))
1944 return NOTIFY_OK;
1946 /* find our device by node */
1947 client = of_find_i2c_device_by_node(rd->dn);
1948 if (client == NULL)
1949 return NOTIFY_OK; /* no? not meant for us */
1951 /* unregister takes one ref away */
1952 i2c_unregister_device(client);
1954 /* and put the reference of the find */
1955 put_device(&client->dev);
1956 break;
1959 return NOTIFY_OK;
1961 static struct notifier_block i2c_of_notifier = {
1962 .notifier_call = of_i2c_notify,
1964 #else
1965 extern struct notifier_block i2c_of_notifier;
1966 #endif /* CONFIG_OF_DYNAMIC */
1968 static int __init i2c_init(void)
1970 int retval;
1972 retval = of_alias_get_highest_id("i2c");
1974 down_write(&__i2c_board_lock);
1975 if (retval >= __i2c_first_dynamic_bus_num)
1976 __i2c_first_dynamic_bus_num = retval + 1;
1977 up_write(&__i2c_board_lock);
1979 retval = bus_register(&i2c_bus_type);
1980 if (retval)
1981 return retval;
1982 #ifdef CONFIG_I2C_COMPAT
1983 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1984 if (!i2c_adapter_compat_class) {
1985 retval = -ENOMEM;
1986 goto bus_err;
1988 #endif
1989 retval = i2c_add_driver(&dummy_driver);
1990 if (retval)
1991 goto class_err;
1993 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1994 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
1996 return 0;
1998 class_err:
1999 #ifdef CONFIG_I2C_COMPAT
2000 class_compat_unregister(i2c_adapter_compat_class);
2001 bus_err:
2002 #endif
2003 bus_unregister(&i2c_bus_type);
2004 return retval;
2007 static void __exit i2c_exit(void)
2009 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2010 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
2011 i2c_del_driver(&dummy_driver);
2012 #ifdef CONFIG_I2C_COMPAT
2013 class_compat_unregister(i2c_adapter_compat_class);
2014 #endif
2015 bus_unregister(&i2c_bus_type);
2016 tracepoint_synchronize_unregister();
2019 /* We must initialize early, because some subsystems register i2c drivers
2020 * in subsys_initcall() code, but are linked (and initialized) before i2c.
2022 postcore_initcall(i2c_init);
2023 module_exit(i2c_exit);
2025 /* ----------------------------------------------------
2026 * the functional interface to the i2c busses.
2027 * ----------------------------------------------------
2030 /* Check if val is exceeding the quirk IFF quirk is non 0 */
2031 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2033 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2035 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2036 err_msg, msg->addr, msg->len,
2037 msg->flags & I2C_M_RD ? "read" : "write");
2038 return -EOPNOTSUPP;
2041 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2043 const struct i2c_adapter_quirks *q = adap->quirks;
2044 int max_num = q->max_num_msgs, i;
2045 bool do_len_check = true;
2047 if (q->flags & I2C_AQ_COMB) {
2048 max_num = 2;
2050 /* special checks for combined messages */
2051 if (num == 2) {
2052 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2053 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2055 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2056 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2058 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2059 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2061 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2062 return i2c_quirk_error(adap, &msgs[0], "msg too long");
2064 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2065 return i2c_quirk_error(adap, &msgs[1], "msg too long");
2067 do_len_check = false;
2071 if (i2c_quirk_exceeded(num, max_num))
2072 return i2c_quirk_error(adap, &msgs[0], "too many messages");
2074 for (i = 0; i < num; i++) {
2075 u16 len = msgs[i].len;
2077 if (msgs[i].flags & I2C_M_RD) {
2078 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2079 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2080 } else {
2081 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2082 return i2c_quirk_error(adap, &msgs[i], "msg too long");
2086 return 0;
2090 * __i2c_transfer - unlocked flavor of i2c_transfer
2091 * @adap: Handle to I2C bus
2092 * @msgs: One or more messages to execute before STOP is issued to
2093 * terminate the operation; each message begins with a START.
2094 * @num: Number of messages to be executed.
2096 * Returns negative errno, else the number of messages executed.
2098 * Adapter lock must be held when calling this function. No debug logging
2099 * takes place. adap->algo->master_xfer existence isn't checked.
2101 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2103 unsigned long orig_jiffies;
2104 int ret, try;
2106 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2107 return -EOPNOTSUPP;
2109 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2110 * enabled. This is an efficient way of keeping the for-loop from
2111 * being executed when not needed.
2113 if (static_key_false(&i2c_trace_msg)) {
2114 int i;
2115 for (i = 0; i < num; i++)
2116 if (msgs[i].flags & I2C_M_RD)
2117 trace_i2c_read(adap, &msgs[i], i);
2118 else
2119 trace_i2c_write(adap, &msgs[i], i);
2122 /* Retry automatically on arbitration loss */
2123 orig_jiffies = jiffies;
2124 for (ret = 0, try = 0; try <= adap->retries; try++) {
2125 ret = adap->algo->master_xfer(adap, msgs, num);
2126 if (ret != -EAGAIN)
2127 break;
2128 if (time_after(jiffies, orig_jiffies + adap->timeout))
2129 break;
2132 if (static_key_false(&i2c_trace_msg)) {
2133 int i;
2134 for (i = 0; i < ret; i++)
2135 if (msgs[i].flags & I2C_M_RD)
2136 trace_i2c_reply(adap, &msgs[i], i);
2137 trace_i2c_result(adap, i, ret);
2140 return ret;
2142 EXPORT_SYMBOL(__i2c_transfer);
2145 * i2c_transfer - execute a single or combined I2C message
2146 * @adap: Handle to I2C bus
2147 * @msgs: One or more messages to execute before STOP is issued to
2148 * terminate the operation; each message begins with a START.
2149 * @num: Number of messages to be executed.
2151 * Returns negative errno, else the number of messages executed.
2153 * Note that there is no requirement that each message be sent to
2154 * the same slave address, although that is the most common model.
2156 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2158 int ret;
2160 /* REVISIT the fault reporting model here is weak:
2162 * - When we get an error after receiving N bytes from a slave,
2163 * there is no way to report "N".
2165 * - When we get a NAK after transmitting N bytes to a slave,
2166 * there is no way to report "N" ... or to let the master
2167 * continue executing the rest of this combined message, if
2168 * that's the appropriate response.
2170 * - When for example "num" is two and we successfully complete
2171 * the first message but get an error part way through the
2172 * second, it's unclear whether that should be reported as
2173 * one (discarding status on the second message) or errno
2174 * (discarding status on the first one).
2177 if (adap->algo->master_xfer) {
2178 #ifdef DEBUG
2179 for (ret = 0; ret < num; ret++) {
2180 dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
2181 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
2182 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
2183 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2185 #endif
2187 if (in_atomic() || irqs_disabled()) {
2188 ret = i2c_trylock_adapter(adap);
2189 if (!ret)
2190 /* I2C activity is ongoing. */
2191 return -EAGAIN;
2192 } else {
2193 i2c_lock_adapter(adap);
2196 ret = __i2c_transfer(adap, msgs, num);
2197 i2c_unlock_adapter(adap);
2199 return ret;
2200 } else {
2201 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2202 return -EOPNOTSUPP;
2205 EXPORT_SYMBOL(i2c_transfer);
2208 * i2c_master_send - issue a single I2C message in master transmit mode
2209 * @client: Handle to slave device
2210 * @buf: Data that will be written to the slave
2211 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2213 * Returns negative errno, or else the number of bytes written.
2215 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2217 int ret;
2218 struct i2c_adapter *adap = client->adapter;
2219 struct i2c_msg msg;
2221 msg.addr = client->addr;
2222 msg.flags = client->flags & I2C_M_TEN;
2223 msg.len = count;
2224 msg.buf = (char *)buf;
2226 ret = i2c_transfer(adap, &msg, 1);
2229 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2230 * transmitted, else error code.
2232 return (ret == 1) ? count : ret;
2234 EXPORT_SYMBOL(i2c_master_send);
2237 * i2c_master_recv - issue a single I2C message in master receive mode
2238 * @client: Handle to slave device
2239 * @buf: Where to store data read from slave
2240 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2242 * Returns negative errno, or else the number of bytes read.
2244 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2246 struct i2c_adapter *adap = client->adapter;
2247 struct i2c_msg msg;
2248 int ret;
2250 msg.addr = client->addr;
2251 msg.flags = client->flags & I2C_M_TEN;
2252 msg.flags |= I2C_M_RD;
2253 msg.len = count;
2254 msg.buf = buf;
2256 ret = i2c_transfer(adap, &msg, 1);
2259 * If everything went ok (i.e. 1 msg received), return #bytes received,
2260 * else error code.
2262 return (ret == 1) ? count : ret;
2264 EXPORT_SYMBOL(i2c_master_recv);
2266 /* ----------------------------------------------------
2267 * the i2c address scanning function
2268 * Will not work for 10-bit addresses!
2269 * ----------------------------------------------------
2273 * Legacy default probe function, mostly relevant for SMBus. The default
2274 * probe method is a quick write, but it is known to corrupt the 24RF08
2275 * EEPROMs due to a state machine bug, and could also irreversibly
2276 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2277 * we use a short byte read instead. Also, some bus drivers don't implement
2278 * quick write, so we fallback to a byte read in that case too.
2279 * On x86, there is another special case for FSC hardware monitoring chips,
2280 * which want regular byte reads (address 0x73.) Fortunately, these are the
2281 * only known chips using this I2C address on PC hardware.
2282 * Returns 1 if probe succeeded, 0 if not.
2284 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2286 int err;
2287 union i2c_smbus_data dummy;
2289 #ifdef CONFIG_X86
2290 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2291 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2292 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2293 I2C_SMBUS_BYTE_DATA, &dummy);
2294 else
2295 #endif
2296 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2297 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2298 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2299 I2C_SMBUS_QUICK, NULL);
2300 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2301 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2302 I2C_SMBUS_BYTE, &dummy);
2303 else {
2304 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2305 addr);
2306 err = -EOPNOTSUPP;
2309 return err >= 0;
2312 static int i2c_detect_address(struct i2c_client *temp_client,
2313 struct i2c_driver *driver)
2315 struct i2c_board_info info;
2316 struct i2c_adapter *adapter = temp_client->adapter;
2317 int addr = temp_client->addr;
2318 int err;
2320 /* Make sure the address is valid */
2321 err = i2c_check_7bit_addr_validity_strict(addr);
2322 if (err) {
2323 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2324 addr);
2325 return err;
2328 /* Skip if already in use (7 bit, no need to encode flags) */
2329 if (i2c_check_addr_busy(adapter, addr))
2330 return 0;
2332 /* Make sure there is something at this address */
2333 if (!i2c_default_probe(adapter, addr))
2334 return 0;
2336 /* Finally call the custom detection function */
2337 memset(&info, 0, sizeof(struct i2c_board_info));
2338 info.addr = addr;
2339 err = driver->detect(temp_client, &info);
2340 if (err) {
2341 /* -ENODEV is returned if the detection fails. We catch it
2342 here as this isn't an error. */
2343 return err == -ENODEV ? 0 : err;
2346 /* Consistency check */
2347 if (info.type[0] == '\0') {
2348 dev_err(&adapter->dev, "%s detection function provided "
2349 "no name for 0x%x\n", driver->driver.name,
2350 addr);
2351 } else {
2352 struct i2c_client *client;
2354 /* Detection succeeded, instantiate the device */
2355 if (adapter->class & I2C_CLASS_DEPRECATED)
2356 dev_warn(&adapter->dev,
2357 "This adapter will soon drop class based instantiation of devices. "
2358 "Please make sure client 0x%02x gets instantiated by other means. "
2359 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2360 info.addr);
2362 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2363 info.type, info.addr);
2364 client = i2c_new_device(adapter, &info);
2365 if (client)
2366 list_add_tail(&client->detected, &driver->clients);
2367 else
2368 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2369 info.type, info.addr);
2371 return 0;
2374 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2376 const unsigned short *address_list;
2377 struct i2c_client *temp_client;
2378 int i, err = 0;
2379 int adap_id = i2c_adapter_id(adapter);
2381 address_list = driver->address_list;
2382 if (!driver->detect || !address_list)
2383 return 0;
2385 /* Warn that the adapter lost class based instantiation */
2386 if (adapter->class == I2C_CLASS_DEPRECATED) {
2387 dev_dbg(&adapter->dev,
2388 "This adapter dropped support for I2C classes and "
2389 "won't auto-detect %s devices anymore. If you need it, check "
2390 "'Documentation/i2c/instantiating-devices' for alternatives.\n",
2391 driver->driver.name);
2392 return 0;
2395 /* Stop here if the classes do not match */
2396 if (!(adapter->class & driver->class))
2397 return 0;
2399 /* Set up a temporary client to help detect callback */
2400 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2401 if (!temp_client)
2402 return -ENOMEM;
2403 temp_client->adapter = adapter;
2405 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2406 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
2407 "addr 0x%02x\n", adap_id, address_list[i]);
2408 temp_client->addr = address_list[i];
2409 err = i2c_detect_address(temp_client, driver);
2410 if (unlikely(err))
2411 break;
2414 kfree(temp_client);
2415 return err;
2418 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2420 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2421 I2C_SMBUS_QUICK, NULL) >= 0;
2423 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2425 struct i2c_client *
2426 i2c_new_probed_device(struct i2c_adapter *adap,
2427 struct i2c_board_info *info,
2428 unsigned short const *addr_list,
2429 int (*probe)(struct i2c_adapter *, unsigned short addr))
2431 int i;
2433 if (!probe)
2434 probe = i2c_default_probe;
2436 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2437 /* Check address validity */
2438 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2439 dev_warn(&adap->dev, "Invalid 7-bit address "
2440 "0x%02x\n", addr_list[i]);
2441 continue;
2444 /* Check address availability (7 bit, no need to encode flags) */
2445 if (i2c_check_addr_busy(adap, addr_list[i])) {
2446 dev_dbg(&adap->dev, "Address 0x%02x already in "
2447 "use, not probing\n", addr_list[i]);
2448 continue;
2451 /* Test address responsiveness */
2452 if (probe(adap, addr_list[i]))
2453 break;
2456 if (addr_list[i] == I2C_CLIENT_END) {
2457 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2458 return NULL;
2461 info->addr = addr_list[i];
2462 return i2c_new_device(adap, info);
2464 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2466 struct i2c_adapter *i2c_get_adapter(int nr)
2468 struct i2c_adapter *adapter;
2470 mutex_lock(&core_lock);
2471 adapter = idr_find(&i2c_adapter_idr, nr);
2472 if (!adapter)
2473 goto exit;
2475 if (try_module_get(adapter->owner))
2476 get_device(&adapter->dev);
2477 else
2478 adapter = NULL;
2480 exit:
2481 mutex_unlock(&core_lock);
2482 return adapter;
2484 EXPORT_SYMBOL(i2c_get_adapter);
2486 void i2c_put_adapter(struct i2c_adapter *adap)
2488 if (!adap)
2489 return;
2491 put_device(&adap->dev);
2492 module_put(adap->owner);
2494 EXPORT_SYMBOL(i2c_put_adapter);
2496 /* The SMBus parts */
2498 #define POLY (0x1070U << 3)
2499 static u8 crc8(u16 data)
2501 int i;
2503 for (i = 0; i < 8; i++) {
2504 if (data & 0x8000)
2505 data = data ^ POLY;
2506 data = data << 1;
2508 return (u8)(data >> 8);
2511 /* Incremental CRC8 over count bytes in the array pointed to by p */
2512 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2514 int i;
2516 for (i = 0; i < count; i++)
2517 crc = crc8((crc ^ p[i]) << 8);
2518 return crc;
2521 /* Assume a 7-bit address, which is reasonable for SMBus */
2522 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2524 /* The address will be sent first */
2525 u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
2526 pec = i2c_smbus_pec(pec, &addr, 1);
2528 /* The data buffer follows */
2529 return i2c_smbus_pec(pec, msg->buf, msg->len);
2532 /* Used for write only transactions */
2533 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2535 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2536 msg->len++;
2539 /* Return <0 on CRC error
2540 If there was a write before this read (most cases) we need to take the
2541 partial CRC from the write part into account.
2542 Note that this function does modify the message (we need to decrease the
2543 message length to hide the CRC byte from the caller). */
2544 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2546 u8 rpec = msg->buf[--msg->len];
2547 cpec = i2c_smbus_msg_pec(cpec, msg);
2549 if (rpec != cpec) {
2550 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
2551 rpec, cpec);
2552 return -EBADMSG;
2554 return 0;
2558 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2559 * @client: Handle to slave device
2561 * This executes the SMBus "receive byte" protocol, returning negative errno
2562 * else the byte received from the device.
2564 s32 i2c_smbus_read_byte(const struct i2c_client *client)
2566 union i2c_smbus_data data;
2567 int status;
2569 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2570 I2C_SMBUS_READ, 0,
2571 I2C_SMBUS_BYTE, &data);
2572 return (status < 0) ? status : data.byte;
2574 EXPORT_SYMBOL(i2c_smbus_read_byte);
2577 * i2c_smbus_write_byte - SMBus "send byte" protocol
2578 * @client: Handle to slave device
2579 * @value: Byte to be sent
2581 * This executes the SMBus "send byte" protocol, returning negative errno
2582 * else zero on success.
2584 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2586 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2587 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2589 EXPORT_SYMBOL(i2c_smbus_write_byte);
2592 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2593 * @client: Handle to slave device
2594 * @command: Byte interpreted by slave
2596 * This executes the SMBus "read byte" protocol, returning negative errno
2597 * else a data byte received from the device.
2599 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2601 union i2c_smbus_data data;
2602 int status;
2604 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2605 I2C_SMBUS_READ, command,
2606 I2C_SMBUS_BYTE_DATA, &data);
2607 return (status < 0) ? status : data.byte;
2609 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2612 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2613 * @client: Handle to slave device
2614 * @command: Byte interpreted by slave
2615 * @value: Byte being written
2617 * This executes the SMBus "write byte" protocol, returning negative errno
2618 * else zero on success.
2620 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
2621 u8 value)
2623 union i2c_smbus_data data;
2624 data.byte = value;
2625 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2626 I2C_SMBUS_WRITE, command,
2627 I2C_SMBUS_BYTE_DATA, &data);
2629 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
2632 * i2c_smbus_read_word_data - SMBus "read word" protocol
2633 * @client: Handle to slave device
2634 * @command: Byte interpreted by slave
2636 * This executes the SMBus "read word" protocol, returning negative errno
2637 * else a 16-bit unsigned "word" received from the device.
2639 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
2641 union i2c_smbus_data data;
2642 int status;
2644 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2645 I2C_SMBUS_READ, command,
2646 I2C_SMBUS_WORD_DATA, &data);
2647 return (status < 0) ? status : data.word;
2649 EXPORT_SYMBOL(i2c_smbus_read_word_data);
2652 * i2c_smbus_write_word_data - SMBus "write word" protocol
2653 * @client: Handle to slave device
2654 * @command: Byte interpreted by slave
2655 * @value: 16-bit "word" being written
2657 * This executes the SMBus "write word" protocol, returning negative errno
2658 * else zero on success.
2660 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2661 u16 value)
2663 union i2c_smbus_data data;
2664 data.word = value;
2665 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2666 I2C_SMBUS_WRITE, command,
2667 I2C_SMBUS_WORD_DATA, &data);
2669 EXPORT_SYMBOL(i2c_smbus_write_word_data);
2672 * i2c_smbus_read_block_data - SMBus "block read" protocol
2673 * @client: Handle to slave device
2674 * @command: Byte interpreted by slave
2675 * @values: Byte array into which data will be read; big enough to hold
2676 * the data returned by the slave. SMBus allows at most 32 bytes.
2678 * This executes the SMBus "block read" protocol, returning negative errno
2679 * else the number of data bytes in the slave's response.
2681 * Note that using this function requires that the client's adapter support
2682 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
2683 * support this; its emulation through I2C messaging relies on a specific
2684 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2686 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2687 u8 *values)
2689 union i2c_smbus_data data;
2690 int status;
2692 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2693 I2C_SMBUS_READ, command,
2694 I2C_SMBUS_BLOCK_DATA, &data);
2695 if (status)
2696 return status;
2698 memcpy(values, &data.block[1], data.block[0]);
2699 return data.block[0];
2701 EXPORT_SYMBOL(i2c_smbus_read_block_data);
2704 * i2c_smbus_write_block_data - SMBus "block write" protocol
2705 * @client: Handle to slave device
2706 * @command: Byte interpreted by slave
2707 * @length: Size of data block; SMBus allows at most 32 bytes
2708 * @values: Byte array which will be written.
2710 * This executes the SMBus "block write" protocol, returning negative errno
2711 * else zero on success.
2713 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2714 u8 length, const u8 *values)
2716 union i2c_smbus_data data;
2718 if (length > I2C_SMBUS_BLOCK_MAX)
2719 length = I2C_SMBUS_BLOCK_MAX;
2720 data.block[0] = length;
2721 memcpy(&data.block[1], values, length);
2722 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2723 I2C_SMBUS_WRITE, command,
2724 I2C_SMBUS_BLOCK_DATA, &data);
2726 EXPORT_SYMBOL(i2c_smbus_write_block_data);
2728 /* Returns the number of read bytes */
2729 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2730 u8 length, u8 *values)
2732 union i2c_smbus_data data;
2733 int status;
2735 if (length > I2C_SMBUS_BLOCK_MAX)
2736 length = I2C_SMBUS_BLOCK_MAX;
2737 data.block[0] = length;
2738 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2739 I2C_SMBUS_READ, command,
2740 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2741 if (status < 0)
2742 return status;
2744 memcpy(values, &data.block[1], data.block[0]);
2745 return data.block[0];
2747 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2749 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2750 u8 length, const u8 *values)
2752 union i2c_smbus_data data;
2754 if (length > I2C_SMBUS_BLOCK_MAX)
2755 length = I2C_SMBUS_BLOCK_MAX;
2756 data.block[0] = length;
2757 memcpy(data.block + 1, values, length);
2758 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2759 I2C_SMBUS_WRITE, command,
2760 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2762 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2764 /* Simulate a SMBus command using the i2c protocol
2765 No checking of parameters is done! */
2766 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2767 unsigned short flags,
2768 char read_write, u8 command, int size,
2769 union i2c_smbus_data *data)
2771 /* So we need to generate a series of msgs. In the case of writing, we
2772 need to use only one message; when reading, we need two. We initialize
2773 most things with sane defaults, to keep the code below somewhat
2774 simpler. */
2775 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2776 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2777 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2778 int i;
2779 u8 partial_pec = 0;
2780 int status;
2781 struct i2c_msg msg[2] = {
2783 .addr = addr,
2784 .flags = flags,
2785 .len = 1,
2786 .buf = msgbuf0,
2787 }, {
2788 .addr = addr,
2789 .flags = flags | I2C_M_RD,
2790 .len = 0,
2791 .buf = msgbuf1,
2795 msgbuf0[0] = command;
2796 switch (size) {
2797 case I2C_SMBUS_QUICK:
2798 msg[0].len = 0;
2799 /* Special case: The read/write field is used as data */
2800 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2801 I2C_M_RD : 0);
2802 num = 1;
2803 break;
2804 case I2C_SMBUS_BYTE:
2805 if (read_write == I2C_SMBUS_READ) {
2806 /* Special case: only a read! */
2807 msg[0].flags = I2C_M_RD | flags;
2808 num = 1;
2810 break;
2811 case I2C_SMBUS_BYTE_DATA:
2812 if (read_write == I2C_SMBUS_READ)
2813 msg[1].len = 1;
2814 else {
2815 msg[0].len = 2;
2816 msgbuf0[1] = data->byte;
2818 break;
2819 case I2C_SMBUS_WORD_DATA:
2820 if (read_write == I2C_SMBUS_READ)
2821 msg[1].len = 2;
2822 else {
2823 msg[0].len = 3;
2824 msgbuf0[1] = data->word & 0xff;
2825 msgbuf0[2] = data->word >> 8;
2827 break;
2828 case I2C_SMBUS_PROC_CALL:
2829 num = 2; /* Special case */
2830 read_write = I2C_SMBUS_READ;
2831 msg[0].len = 3;
2832 msg[1].len = 2;
2833 msgbuf0[1] = data->word & 0xff;
2834 msgbuf0[2] = data->word >> 8;
2835 break;
2836 case I2C_SMBUS_BLOCK_DATA:
2837 if (read_write == I2C_SMBUS_READ) {
2838 msg[1].flags |= I2C_M_RECV_LEN;
2839 msg[1].len = 1; /* block length will be added by
2840 the underlying bus driver */
2841 } else {
2842 msg[0].len = data->block[0] + 2;
2843 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
2844 dev_err(&adapter->dev,
2845 "Invalid block write size %d\n",
2846 data->block[0]);
2847 return -EINVAL;
2849 for (i = 1; i < msg[0].len; i++)
2850 msgbuf0[i] = data->block[i-1];
2852 break;
2853 case I2C_SMBUS_BLOCK_PROC_CALL:
2854 num = 2; /* Another special case */
2855 read_write = I2C_SMBUS_READ;
2856 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
2857 dev_err(&adapter->dev,
2858 "Invalid block write size %d\n",
2859 data->block[0]);
2860 return -EINVAL;
2862 msg[0].len = data->block[0] + 2;
2863 for (i = 1; i < msg[0].len; i++)
2864 msgbuf0[i] = data->block[i-1];
2865 msg[1].flags |= I2C_M_RECV_LEN;
2866 msg[1].len = 1; /* block length will be added by
2867 the underlying bus driver */
2868 break;
2869 case I2C_SMBUS_I2C_BLOCK_DATA:
2870 if (read_write == I2C_SMBUS_READ) {
2871 msg[1].len = data->block[0];
2872 } else {
2873 msg[0].len = data->block[0] + 1;
2874 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
2875 dev_err(&adapter->dev,
2876 "Invalid block write size %d\n",
2877 data->block[0]);
2878 return -EINVAL;
2880 for (i = 1; i <= data->block[0]; i++)
2881 msgbuf0[i] = data->block[i];
2883 break;
2884 default:
2885 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
2886 return -EOPNOTSUPP;
2889 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
2890 && size != I2C_SMBUS_I2C_BLOCK_DATA);
2891 if (i) {
2892 /* Compute PEC if first message is a write */
2893 if (!(msg[0].flags & I2C_M_RD)) {
2894 if (num == 1) /* Write only */
2895 i2c_smbus_add_pec(&msg[0]);
2896 else /* Write followed by read */
2897 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
2899 /* Ask for PEC if last message is a read */
2900 if (msg[num-1].flags & I2C_M_RD)
2901 msg[num-1].len++;
2904 status = i2c_transfer(adapter, msg, num);
2905 if (status < 0)
2906 return status;
2908 /* Check PEC if last message is a read */
2909 if (i && (msg[num-1].flags & I2C_M_RD)) {
2910 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
2911 if (status < 0)
2912 return status;
2915 if (read_write == I2C_SMBUS_READ)
2916 switch (size) {
2917 case I2C_SMBUS_BYTE:
2918 data->byte = msgbuf0[0];
2919 break;
2920 case I2C_SMBUS_BYTE_DATA:
2921 data->byte = msgbuf1[0];
2922 break;
2923 case I2C_SMBUS_WORD_DATA:
2924 case I2C_SMBUS_PROC_CALL:
2925 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
2926 break;
2927 case I2C_SMBUS_I2C_BLOCK_DATA:
2928 for (i = 0; i < data->block[0]; i++)
2929 data->block[i+1] = msgbuf1[i];
2930 break;
2931 case I2C_SMBUS_BLOCK_DATA:
2932 case I2C_SMBUS_BLOCK_PROC_CALL:
2933 for (i = 0; i < msgbuf1[0] + 1; i++)
2934 data->block[i] = msgbuf1[i];
2935 break;
2937 return 0;
2941 * i2c_smbus_xfer - execute SMBus protocol operations
2942 * @adapter: Handle to I2C bus
2943 * @addr: Address of SMBus slave on that bus
2944 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
2945 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
2946 * @command: Byte interpreted by slave, for protocols which use such bytes
2947 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
2948 * @data: Data to be read or written
2950 * This executes an SMBus protocol operation, and returns a negative
2951 * errno code else zero on success.
2953 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
2954 char read_write, u8 command, int protocol,
2955 union i2c_smbus_data *data)
2957 unsigned long orig_jiffies;
2958 int try;
2959 s32 res;
2961 /* If enabled, the following two tracepoints are conditional on
2962 * read_write and protocol.
2964 trace_smbus_write(adapter, addr, flags, read_write,
2965 command, protocol, data);
2966 trace_smbus_read(adapter, addr, flags, read_write,
2967 command, protocol);
2969 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
2971 if (adapter->algo->smbus_xfer) {
2972 i2c_lock_adapter(adapter);
2974 /* Retry automatically on arbitration loss */
2975 orig_jiffies = jiffies;
2976 for (res = 0, try = 0; try <= adapter->retries; try++) {
2977 res = adapter->algo->smbus_xfer(adapter, addr, flags,
2978 read_write, command,
2979 protocol, data);
2980 if (res != -EAGAIN)
2981 break;
2982 if (time_after(jiffies,
2983 orig_jiffies + adapter->timeout))
2984 break;
2986 i2c_unlock_adapter(adapter);
2988 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
2989 goto trace;
2991 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
2992 * implement native support for the SMBus operation.
2996 res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
2997 command, protocol, data);
2999 trace:
3000 /* If enabled, the reply tracepoint is conditional on read_write. */
3001 trace_smbus_reply(adapter, addr, flags, read_write,
3002 command, protocol, data);
3003 trace_smbus_result(adapter, addr, flags, read_write,
3004 command, protocol, res);
3006 return res;
3008 EXPORT_SYMBOL(i2c_smbus_xfer);
3011 * i2c_smbus_read_i2c_block_data_or_emulated - read block or emulate
3012 * @client: Handle to slave device
3013 * @command: Byte interpreted by slave
3014 * @length: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
3015 * @values: Byte array into which data will be read; big enough to hold
3016 * the data returned by the slave. SMBus allows at most
3017 * I2C_SMBUS_BLOCK_MAX bytes.
3019 * This executes the SMBus "block read" protocol if supported by the adapter.
3020 * If block read is not supported, it emulates it using either word or byte
3021 * read protocols depending on availability.
3023 * The addresses of the I2C slave device that are accessed with this function
3024 * must be mapped to a linear region, so that a block read will have the same
3025 * effect as a byte read. Before using this function you must double-check
3026 * if the I2C slave does support exchanging a block transfer with a byte
3027 * transfer.
3029 s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client,
3030 u8 command, u8 length, u8 *values)
3032 u8 i = 0;
3033 int status;
3035 if (length > I2C_SMBUS_BLOCK_MAX)
3036 length = I2C_SMBUS_BLOCK_MAX;
3038 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
3039 return i2c_smbus_read_i2c_block_data(client, command, length, values);
3041 if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA))
3042 return -EOPNOTSUPP;
3044 if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) {
3045 while ((i + 2) <= length) {
3046 status = i2c_smbus_read_word_data(client, command + i);
3047 if (status < 0)
3048 return status;
3049 values[i] = status & 0xff;
3050 values[i + 1] = status >> 8;
3051 i += 2;
3055 while (i < length) {
3056 status = i2c_smbus_read_byte_data(client, command + i);
3057 if (status < 0)
3058 return status;
3059 values[i] = status;
3060 i++;
3063 return i;
3065 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data_or_emulated);
3067 #if IS_ENABLED(CONFIG_I2C_SLAVE)
3068 int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
3070 int ret;
3072 if (!client || !slave_cb) {
3073 WARN(1, "insufficent data\n");
3074 return -EINVAL;
3077 if (!(client->flags & I2C_CLIENT_SLAVE))
3078 dev_warn(&client->dev, "%s: client slave flag not set. You might see address collisions\n",
3079 __func__);
3081 if (!(client->flags & I2C_CLIENT_TEN)) {
3082 /* Enforce stricter address checking */
3083 ret = i2c_check_7bit_addr_validity_strict(client->addr);
3084 if (ret) {
3085 dev_err(&client->dev, "%s: invalid address\n", __func__);
3086 return ret;
3090 if (!client->adapter->algo->reg_slave) {
3091 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3092 return -EOPNOTSUPP;
3095 client->slave_cb = slave_cb;
3097 i2c_lock_adapter(client->adapter);
3098 ret = client->adapter->algo->reg_slave(client);
3099 i2c_unlock_adapter(client->adapter);
3101 if (ret) {
3102 client->slave_cb = NULL;
3103 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3106 return ret;
3108 EXPORT_SYMBOL_GPL(i2c_slave_register);
3110 int i2c_slave_unregister(struct i2c_client *client)
3112 int ret;
3114 if (!client->adapter->algo->unreg_slave) {
3115 dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3116 return -EOPNOTSUPP;
3119 i2c_lock_adapter(client->adapter);
3120 ret = client->adapter->algo->unreg_slave(client);
3121 i2c_unlock_adapter(client->adapter);
3123 if (ret == 0)
3124 client->slave_cb = NULL;
3125 else
3126 dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3128 return ret;
3130 EXPORT_SYMBOL_GPL(i2c_slave_unregister);
3131 #endif
3133 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
3134 MODULE_DESCRIPTION("I2C-Bus main module");
3135 MODULE_LICENSE("GPL");