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.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19 /* ------------------------------------------------------------------------- */
21 /* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>.
22 All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
23 SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com> and
24 Jean Delvare <khali@linux-fr.org>
25 Mux support by Rodolfo Giometti <giometti@enneenne.com> and
26 Michael Lawnick <michael.lawnick.ext@nsn.com> */
28 #include <linux/module.h>
29 #include <linux/kernel.h>
30 #include <linux/delay.h>
31 #include <linux/errno.h>
32 #include <linux/gpio.h>
33 #include <linux/slab.h>
34 #include <linux/i2c.h>
35 #include <linux/init.h>
36 #include <linux/idr.h>
37 #include <linux/mutex.h>
38 #include <linux/of_device.h>
39 #include <linux/completion.h>
40 #include <linux/hardirq.h>
41 #include <linux/irqflags.h>
42 #include <linux/rwsem.h>
43 #include <linux/pm_runtime.h>
44 #include <linux/acpi.h>
45 #include <asm/uaccess.h>
50 /* core_lock protects i2c_adapter_idr, and guarantees
51 that device detection, deletion of detected devices, and attach_adapter
52 calls are serialized */
53 static DEFINE_MUTEX(core_lock);
54 static DEFINE_IDR(i2c_adapter_idr);
56 static struct device_type i2c_client_type;
57 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
59 /* ------------------------------------------------------------------------- */
61 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
62 const struct i2c_client *client)
65 if (strcmp(client->name, id->name) == 0)
72 static int i2c_device_match(struct device *dev, struct device_driver *drv)
74 struct i2c_client *client = i2c_verify_client(dev);
75 struct i2c_driver *driver;
80 /* Attempt an OF style match */
81 if (of_driver_match_device(dev, drv))
84 /* Then ACPI style match */
85 if (acpi_driver_match_device(dev, drv))
88 driver = to_i2c_driver(drv);
89 /* match on an id table if there is one */
91 return i2c_match_id(driver->id_table, client) != NULL;
97 /* uevent helps with hotplug: modprobe -q $(MODALIAS) */
98 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
100 struct i2c_client *client = to_i2c_client(dev);
102 if (add_uevent_var(env, "MODALIAS=%s%s",
103 I2C_MODULE_PREFIX, client->name))
105 dev_dbg(dev, "uevent\n");
109 /* i2c bus recovery routines */
110 static int get_scl_gpio_value(struct i2c_adapter *adap)
112 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
115 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
117 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
120 static int get_sda_gpio_value(struct i2c_adapter *adap)
122 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
125 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
127 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
128 struct device *dev = &adap->dev;
131 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
132 GPIOF_OUT_INIT_HIGH, "i2c-scl");
134 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
139 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
140 /* work without SDA polling */
141 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
150 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
152 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
155 gpio_free(bri->sda_gpio);
157 gpio_free(bri->scl_gpio);
161 * We are generating clock pulses. ndelay() determines durating of clk pulses.
162 * We will generate clock with rate 100 KHz and so duration of both clock levels
163 * is: delay in ns = (10^6 / 100) / 2
165 #define RECOVERY_NDELAY 5000
166 #define RECOVERY_CLK_CNT 9
168 static int i2c_generic_recovery(struct i2c_adapter *adap)
170 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
171 int i = 0, val = 1, ret = 0;
173 if (bri->prepare_recovery)
174 bri->prepare_recovery(bri);
177 * By this time SCL is high, as we need to give 9 falling-rising edges
179 while (i++ < RECOVERY_CLK_CNT * 2) {
181 /* Break if SDA is high */
182 if (bri->get_sda && bri->get_sda(adap))
184 /* SCL shouldn't be low here */
185 if (!bri->get_scl(adap)) {
187 "SCL is stuck low, exit recovery\n");
194 bri->set_scl(adap, val);
195 ndelay(RECOVERY_NDELAY);
198 if (bri->unprepare_recovery)
199 bri->unprepare_recovery(bri);
204 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
206 adap->bus_recovery_info->set_scl(adap, 1);
207 return i2c_generic_recovery(adap);
210 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
214 ret = i2c_get_gpios_for_recovery(adap);
218 ret = i2c_generic_recovery(adap);
219 i2c_put_gpios_for_recovery(adap);
224 int i2c_recover_bus(struct i2c_adapter *adap)
226 if (!adap->bus_recovery_info)
229 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
230 return adap->bus_recovery_info->recover_bus(adap);
233 static int i2c_device_probe(struct device *dev)
235 struct i2c_client *client = i2c_verify_client(dev);
236 struct i2c_driver *driver;
242 driver = to_i2c_driver(dev->driver);
243 if (!driver->probe || !driver->id_table)
245 client->driver = driver;
246 if (!device_can_wakeup(&client->dev))
247 device_init_wakeup(&client->dev,
248 client->flags & I2C_CLIENT_WAKE);
249 dev_dbg(dev, "probe\n");
251 status = driver->probe(client, i2c_match_id(driver->id_table, client));
253 client->driver = NULL;
254 i2c_set_clientdata(client, NULL);
259 static int i2c_device_remove(struct device *dev)
261 struct i2c_client *client = i2c_verify_client(dev);
262 struct i2c_driver *driver;
265 if (!client || !dev->driver)
268 driver = to_i2c_driver(dev->driver);
269 if (driver->remove) {
270 dev_dbg(dev, "remove\n");
271 status = driver->remove(client);
277 client->driver = NULL;
278 i2c_set_clientdata(client, NULL);
283 static void i2c_device_shutdown(struct device *dev)
285 struct i2c_client *client = i2c_verify_client(dev);
286 struct i2c_driver *driver;
288 if (!client || !dev->driver)
290 driver = to_i2c_driver(dev->driver);
291 if (driver->shutdown)
292 driver->shutdown(client);
295 #ifdef CONFIG_PM_SLEEP
296 static int i2c_legacy_suspend(struct device *dev, pm_message_t mesg)
298 struct i2c_client *client = i2c_verify_client(dev);
299 struct i2c_driver *driver;
301 if (!client || !dev->driver)
303 driver = to_i2c_driver(dev->driver);
304 if (!driver->suspend)
306 return driver->suspend(client, mesg);
309 static int i2c_legacy_resume(struct device *dev)
311 struct i2c_client *client = i2c_verify_client(dev);
312 struct i2c_driver *driver;
314 if (!client || !dev->driver)
316 driver = to_i2c_driver(dev->driver);
319 return driver->resume(client);
322 static int i2c_device_pm_suspend(struct device *dev)
324 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
327 return pm_generic_suspend(dev);
329 return i2c_legacy_suspend(dev, PMSG_SUSPEND);
332 static int i2c_device_pm_resume(struct device *dev)
334 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
337 return pm_generic_resume(dev);
339 return i2c_legacy_resume(dev);
342 static int i2c_device_pm_freeze(struct device *dev)
344 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
347 return pm_generic_freeze(dev);
349 return i2c_legacy_suspend(dev, PMSG_FREEZE);
352 static int i2c_device_pm_thaw(struct device *dev)
354 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
357 return pm_generic_thaw(dev);
359 return i2c_legacy_resume(dev);
362 static int i2c_device_pm_poweroff(struct device *dev)
364 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
367 return pm_generic_poweroff(dev);
369 return i2c_legacy_suspend(dev, PMSG_HIBERNATE);
372 static int i2c_device_pm_restore(struct device *dev)
374 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
377 return pm_generic_restore(dev);
379 return i2c_legacy_resume(dev);
381 #else /* !CONFIG_PM_SLEEP */
382 #define i2c_device_pm_suspend NULL
383 #define i2c_device_pm_resume NULL
384 #define i2c_device_pm_freeze NULL
385 #define i2c_device_pm_thaw NULL
386 #define i2c_device_pm_poweroff NULL
387 #define i2c_device_pm_restore NULL
388 #endif /* !CONFIG_PM_SLEEP */
390 static void i2c_client_dev_release(struct device *dev)
392 kfree(to_i2c_client(dev));
396 show_name(struct device *dev, struct device_attribute *attr, char *buf)
398 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
399 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
403 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
405 struct i2c_client *client = to_i2c_client(dev);
406 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
409 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
410 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
412 static struct attribute *i2c_dev_attrs[] = {
414 /* modalias helps coldplug: modprobe $(cat .../modalias) */
415 &dev_attr_modalias.attr,
419 static struct attribute_group i2c_dev_attr_group = {
420 .attrs = i2c_dev_attrs,
423 static const struct attribute_group *i2c_dev_attr_groups[] = {
428 static const struct dev_pm_ops i2c_device_pm_ops = {
429 .suspend = i2c_device_pm_suspend,
430 .resume = i2c_device_pm_resume,
431 .freeze = i2c_device_pm_freeze,
432 .thaw = i2c_device_pm_thaw,
433 .poweroff = i2c_device_pm_poweroff,
434 .restore = i2c_device_pm_restore,
436 pm_generic_runtime_suspend,
437 pm_generic_runtime_resume,
442 struct bus_type i2c_bus_type = {
444 .match = i2c_device_match,
445 .probe = i2c_device_probe,
446 .remove = i2c_device_remove,
447 .shutdown = i2c_device_shutdown,
448 .pm = &i2c_device_pm_ops,
450 EXPORT_SYMBOL_GPL(i2c_bus_type);
452 static struct device_type i2c_client_type = {
453 .groups = i2c_dev_attr_groups,
454 .uevent = i2c_device_uevent,
455 .release = i2c_client_dev_release,
460 * i2c_verify_client - return parameter as i2c_client, or NULL
461 * @dev: device, probably from some driver model iterator
463 * When traversing the driver model tree, perhaps using driver model
464 * iterators like @device_for_each_child(), you can't assume very much
465 * about the nodes you find. Use this function to avoid oopses caused
466 * by wrongly treating some non-I2C device as an i2c_client.
468 struct i2c_client *i2c_verify_client(struct device *dev)
470 return (dev->type == &i2c_client_type)
474 EXPORT_SYMBOL(i2c_verify_client);
477 /* This is a permissive address validity check, I2C address map constraints
478 * are purposely not enforced, except for the general call address. */
479 static int i2c_check_client_addr_validity(const struct i2c_client *client)
481 if (client->flags & I2C_CLIENT_TEN) {
482 /* 10-bit address, all values are valid */
483 if (client->addr > 0x3ff)
486 /* 7-bit address, reject the general call address */
487 if (client->addr == 0x00 || client->addr > 0x7f)
493 /* And this is a strict address validity check, used when probing. If a
494 * device uses a reserved address, then it shouldn't be probed. 7-bit
495 * addressing is assumed, 10-bit address devices are rare and should be
496 * explicitly enumerated. */
497 static int i2c_check_addr_validity(unsigned short addr)
500 * Reserved addresses per I2C specification:
501 * 0x00 General call address / START byte
503 * 0x02 Reserved for different bus format
504 * 0x03 Reserved for future purposes
505 * 0x04-0x07 Hs-mode master code
506 * 0x78-0x7b 10-bit slave addressing
507 * 0x7c-0x7f Reserved for future purposes
509 if (addr < 0x08 || addr > 0x77)
514 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
516 struct i2c_client *client = i2c_verify_client(dev);
517 int addr = *(int *)addrp;
519 if (client && client->addr == addr)
524 /* walk up mux tree */
525 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
527 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
530 result = device_for_each_child(&adapter->dev, &addr,
531 __i2c_check_addr_busy);
533 if (!result && parent)
534 result = i2c_check_mux_parents(parent, addr);
539 /* recurse down mux tree */
540 static int i2c_check_mux_children(struct device *dev, void *addrp)
544 if (dev->type == &i2c_adapter_type)
545 result = device_for_each_child(dev, addrp,
546 i2c_check_mux_children);
548 result = __i2c_check_addr_busy(dev, addrp);
553 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
555 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
559 result = i2c_check_mux_parents(parent, addr);
562 result = device_for_each_child(&adapter->dev, &addr,
563 i2c_check_mux_children);
569 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
570 * @adapter: Target I2C bus segment
572 void i2c_lock_adapter(struct i2c_adapter *adapter)
574 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
577 i2c_lock_adapter(parent);
579 rt_mutex_lock(&adapter->bus_lock);
581 EXPORT_SYMBOL_GPL(i2c_lock_adapter);
584 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
585 * @adapter: Target I2C bus segment
587 static int i2c_trylock_adapter(struct i2c_adapter *adapter)
589 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
592 return i2c_trylock_adapter(parent);
594 return rt_mutex_trylock(&adapter->bus_lock);
598 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
599 * @adapter: Target I2C bus segment
601 void i2c_unlock_adapter(struct i2c_adapter *adapter)
603 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
606 i2c_unlock_adapter(parent);
608 rt_mutex_unlock(&adapter->bus_lock);
610 EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
613 * i2c_new_device - instantiate an i2c device
614 * @adap: the adapter managing the device
615 * @info: describes one I2C device; bus_num is ignored
618 * Create an i2c device. Binding is handled through driver model
619 * probe()/remove() methods. A driver may be bound to this device when we
620 * return from this function, or any later moment (e.g. maybe hotplugging will
621 * load the driver module). This call is not appropriate for use by mainboard
622 * initialization logic, which usually runs during an arch_initcall() long
623 * before any i2c_adapter could exist.
625 * This returns the new i2c client, which may be saved for later use with
626 * i2c_unregister_device(); or NULL to indicate an error.
629 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
631 struct i2c_client *client;
634 client = kzalloc(sizeof *client, GFP_KERNEL);
638 client->adapter = adap;
640 client->dev.platform_data = info->platform_data;
643 client->dev.archdata = *info->archdata;
645 client->flags = info->flags;
646 client->addr = info->addr;
647 client->irq = info->irq;
649 strlcpy(client->name, info->type, sizeof(client->name));
651 /* Check for address validity */
652 status = i2c_check_client_addr_validity(client);
654 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
655 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
659 /* Check for address business */
660 status = i2c_check_addr_busy(adap, client->addr);
664 client->dev.parent = &client->adapter->dev;
665 client->dev.bus = &i2c_bus_type;
666 client->dev.type = &i2c_client_type;
667 client->dev.of_node = info->of_node;
668 ACPI_HANDLE_SET(&client->dev, info->acpi_node.handle);
670 /* For 10-bit clients, add an arbitrary offset to avoid collisions */
671 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
672 client->addr | ((client->flags & I2C_CLIENT_TEN)
674 status = device_register(&client->dev);
678 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
679 client->name, dev_name(&client->dev));
684 dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
685 "(%d)\n", client->name, client->addr, status);
690 EXPORT_SYMBOL_GPL(i2c_new_device);
694 * i2c_unregister_device - reverse effect of i2c_new_device()
695 * @client: value returned from i2c_new_device()
698 void i2c_unregister_device(struct i2c_client *client)
700 device_unregister(&client->dev);
702 EXPORT_SYMBOL_GPL(i2c_unregister_device);
705 static const struct i2c_device_id dummy_id[] = {
710 static int dummy_probe(struct i2c_client *client,
711 const struct i2c_device_id *id)
716 static int dummy_remove(struct i2c_client *client)
721 static struct i2c_driver dummy_driver = {
722 .driver.name = "dummy",
723 .probe = dummy_probe,
724 .remove = dummy_remove,
725 .id_table = dummy_id,
729 * i2c_new_dummy - return a new i2c device bound to a dummy driver
730 * @adapter: the adapter managing the device
731 * @address: seven bit address to be used
734 * This returns an I2C client bound to the "dummy" driver, intended for use
735 * with devices that consume multiple addresses. Examples of such chips
736 * include various EEPROMS (like 24c04 and 24c08 models).
738 * These dummy devices have two main uses. First, most I2C and SMBus calls
739 * except i2c_transfer() need a client handle; the dummy will be that handle.
740 * And second, this prevents the specified address from being bound to a
743 * This returns the new i2c client, which should be saved for later use with
744 * i2c_unregister_device(); or NULL to indicate an error.
746 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
748 struct i2c_board_info info = {
749 I2C_BOARD_INFO("dummy", address),
752 return i2c_new_device(adapter, &info);
754 EXPORT_SYMBOL_GPL(i2c_new_dummy);
756 /* ------------------------------------------------------------------------- */
758 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
760 static void i2c_adapter_dev_release(struct device *dev)
762 struct i2c_adapter *adap = to_i2c_adapter(dev);
763 complete(&adap->dev_released);
767 * This function is only needed for mutex_lock_nested, so it is never
768 * called unless locking correctness checking is enabled. Thus we
769 * make it inline to avoid a compiler warning. That's what gcc ends up
772 static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
774 unsigned int depth = 0;
776 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
783 * Let users instantiate I2C devices through sysfs. This can be used when
784 * platform initialization code doesn't contain the proper data for
785 * whatever reason. Also useful for drivers that do device detection and
786 * detection fails, either because the device uses an unexpected address,
787 * or this is a compatible device with different ID register values.
789 * Parameter checking may look overzealous, but we really don't want
790 * the user to provide incorrect parameters.
793 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
794 const char *buf, size_t count)
796 struct i2c_adapter *adap = to_i2c_adapter(dev);
797 struct i2c_board_info info;
798 struct i2c_client *client;
802 memset(&info, 0, sizeof(struct i2c_board_info));
804 blank = strchr(buf, ' ');
806 dev_err(dev, "%s: Missing parameters\n", "new_device");
809 if (blank - buf > I2C_NAME_SIZE - 1) {
810 dev_err(dev, "%s: Invalid device name\n", "new_device");
813 memcpy(info.type, buf, blank - buf);
815 /* Parse remaining parameters, reject extra parameters */
816 res = sscanf(++blank, "%hi%c", &info.addr, &end);
818 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
821 if (res > 1 && end != '\n') {
822 dev_err(dev, "%s: Extra parameters\n", "new_device");
826 client = i2c_new_device(adap, &info);
830 /* Keep track of the added device */
831 mutex_lock(&adap->userspace_clients_lock);
832 list_add_tail(&client->detected, &adap->userspace_clients);
833 mutex_unlock(&adap->userspace_clients_lock);
834 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
835 info.type, info.addr);
841 * And of course let the users delete the devices they instantiated, if
842 * they got it wrong. This interface can only be used to delete devices
843 * instantiated by i2c_sysfs_new_device above. This guarantees that we
844 * don't delete devices to which some kernel code still has references.
846 * Parameter checking may look overzealous, but we really don't want
847 * the user to delete the wrong device.
850 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
851 const char *buf, size_t count)
853 struct i2c_adapter *adap = to_i2c_adapter(dev);
854 struct i2c_client *client, *next;
859 /* Parse parameters, reject extra parameters */
860 res = sscanf(buf, "%hi%c", &addr, &end);
862 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
865 if (res > 1 && end != '\n') {
866 dev_err(dev, "%s: Extra parameters\n", "delete_device");
870 /* Make sure the device was added through sysfs */
872 mutex_lock_nested(&adap->userspace_clients_lock,
873 i2c_adapter_depth(adap));
874 list_for_each_entry_safe(client, next, &adap->userspace_clients,
876 if (client->addr == addr) {
877 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
878 "delete_device", client->name, client->addr);
880 list_del(&client->detected);
881 i2c_unregister_device(client);
886 mutex_unlock(&adap->userspace_clients_lock);
889 dev_err(dev, "%s: Can't find device in list\n",
894 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
895 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
896 i2c_sysfs_delete_device);
898 static struct attribute *i2c_adapter_attrs[] = {
900 &dev_attr_new_device.attr,
901 &dev_attr_delete_device.attr,
905 static struct attribute_group i2c_adapter_attr_group = {
906 .attrs = i2c_adapter_attrs,
909 static const struct attribute_group *i2c_adapter_attr_groups[] = {
910 &i2c_adapter_attr_group,
914 struct device_type i2c_adapter_type = {
915 .groups = i2c_adapter_attr_groups,
916 .release = i2c_adapter_dev_release,
918 EXPORT_SYMBOL_GPL(i2c_adapter_type);
921 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
922 * @dev: device, probably from some driver model iterator
924 * When traversing the driver model tree, perhaps using driver model
925 * iterators like @device_for_each_child(), you can't assume very much
926 * about the nodes you find. Use this function to avoid oopses caused
927 * by wrongly treating some non-I2C device as an i2c_adapter.
929 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
931 return (dev->type == &i2c_adapter_type)
932 ? to_i2c_adapter(dev)
935 EXPORT_SYMBOL(i2c_verify_adapter);
937 #ifdef CONFIG_I2C_COMPAT
938 static struct class_compat *i2c_adapter_compat_class;
941 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
943 struct i2c_devinfo *devinfo;
945 down_read(&__i2c_board_lock);
946 list_for_each_entry(devinfo, &__i2c_board_list, list) {
947 if (devinfo->busnum == adapter->nr
948 && !i2c_new_device(adapter,
949 &devinfo->board_info))
950 dev_err(&adapter->dev,
951 "Can't create device at 0x%02x\n",
952 devinfo->board_info.addr);
954 up_read(&__i2c_board_lock);
957 static int i2c_do_add_adapter(struct i2c_driver *driver,
958 struct i2c_adapter *adap)
960 /* Detect supported devices on that bus, and instantiate them */
961 i2c_detect(adap, driver);
963 /* Let legacy drivers scan this bus for matching devices */
964 if (driver->attach_adapter) {
965 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
966 driver->driver.name);
967 dev_warn(&adap->dev, "Please use another way to instantiate "
968 "your i2c_client\n");
969 /* We ignore the return code; if it fails, too bad */
970 driver->attach_adapter(adap);
975 static int __process_new_adapter(struct device_driver *d, void *data)
977 return i2c_do_add_adapter(to_i2c_driver(d), data);
980 static int i2c_register_adapter(struct i2c_adapter *adap)
984 /* Can't register until after driver model init */
985 if (unlikely(WARN_ON(!i2c_bus_type.p))) {
991 if (unlikely(adap->name[0] == '\0')) {
992 pr_err("i2c-core: Attempt to register an adapter with "
996 if (unlikely(!adap->algo)) {
997 pr_err("i2c-core: Attempt to register adapter '%s' with "
998 "no algo!\n", adap->name);
1002 rt_mutex_init(&adap->bus_lock);
1003 mutex_init(&adap->userspace_clients_lock);
1004 INIT_LIST_HEAD(&adap->userspace_clients);
1006 /* Set default timeout to 1 second if not already set */
1007 if (adap->timeout == 0)
1010 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1011 adap->dev.bus = &i2c_bus_type;
1012 adap->dev.type = &i2c_adapter_type;
1013 res = device_register(&adap->dev);
1017 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1019 #ifdef CONFIG_I2C_COMPAT
1020 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1023 dev_warn(&adap->dev,
1024 "Failed to create compatibility class link\n");
1027 /* bus recovery specific initialization */
1028 if (adap->bus_recovery_info) {
1029 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
1031 if (!bri->recover_bus) {
1032 dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
1033 adap->bus_recovery_info = NULL;
1037 /* Generic GPIO recovery */
1038 if (bri->recover_bus == i2c_generic_gpio_recovery) {
1039 if (!gpio_is_valid(bri->scl_gpio)) {
1040 dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
1041 adap->bus_recovery_info = NULL;
1045 if (gpio_is_valid(bri->sda_gpio))
1046 bri->get_sda = get_sda_gpio_value;
1048 bri->get_sda = NULL;
1050 bri->get_scl = get_scl_gpio_value;
1051 bri->set_scl = set_scl_gpio_value;
1052 } else if (!bri->set_scl || !bri->get_scl) {
1053 /* Generic SCL recovery */
1054 dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
1055 adap->bus_recovery_info = NULL;
1060 /* create pre-declared device nodes */
1061 if (adap->nr < __i2c_first_dynamic_bus_num)
1062 i2c_scan_static_board_info(adap);
1064 /* Notify drivers */
1065 mutex_lock(&core_lock);
1066 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1067 mutex_unlock(&core_lock);
1072 mutex_lock(&core_lock);
1073 idr_remove(&i2c_adapter_idr, adap->nr);
1074 mutex_unlock(&core_lock);
1079 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1080 * @adap: the adapter to register (with adap->nr initialized)
1081 * Context: can sleep
1083 * See i2c_add_numbered_adapter() for details.
1085 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1089 mutex_lock(&core_lock);
1090 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1,
1092 mutex_unlock(&core_lock);
1094 return id == -ENOSPC ? -EBUSY : id;
1096 return i2c_register_adapter(adap);
1100 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1101 * @adapter: the adapter to add
1102 * Context: can sleep
1104 * This routine is used to declare an I2C adapter when its bus number
1105 * doesn't matter or when its bus number is specified by an dt alias.
1106 * Examples of bases when the bus number doesn't matter: I2C adapters
1107 * dynamically added by USB links or PCI plugin cards.
1109 * When this returns zero, a new bus number was allocated and stored
1110 * in adap->nr, and the specified adapter became available for clients.
1111 * Otherwise, a negative errno value is returned.
1113 int i2c_add_adapter(struct i2c_adapter *adapter)
1115 struct device *dev = &adapter->dev;
1119 id = of_alias_get_id(dev->of_node, "i2c");
1122 return __i2c_add_numbered_adapter(adapter);
1126 mutex_lock(&core_lock);
1127 id = idr_alloc(&i2c_adapter_idr, adapter,
1128 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1129 mutex_unlock(&core_lock);
1135 return i2c_register_adapter(adapter);
1137 EXPORT_SYMBOL(i2c_add_adapter);
1140 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1141 * @adap: the adapter to register (with adap->nr initialized)
1142 * Context: can sleep
1144 * This routine is used to declare an I2C adapter when its bus number
1145 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1146 * or otherwise built in to the system's mainboard, and where i2c_board_info
1147 * is used to properly configure I2C devices.
1149 * If the requested bus number is set to -1, then this function will behave
1150 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1152 * If no devices have pre-been declared for this bus, then be sure to
1153 * register the adapter before any dynamically allocated ones. Otherwise
1154 * the required bus ID may not be available.
1156 * When this returns zero, the specified adapter became available for
1157 * clients using the bus number provided in adap->nr. Also, the table
1158 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1159 * and the appropriate driver model device nodes are created. Otherwise, a
1160 * negative errno value is returned.
1162 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1164 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1165 return i2c_add_adapter(adap);
1167 return __i2c_add_numbered_adapter(adap);
1169 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1171 static void i2c_do_del_adapter(struct i2c_driver *driver,
1172 struct i2c_adapter *adapter)
1174 struct i2c_client *client, *_n;
1176 /* Remove the devices we created ourselves as the result of hardware
1177 * probing (using a driver's detect method) */
1178 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1179 if (client->adapter == adapter) {
1180 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1181 client->name, client->addr);
1182 list_del(&client->detected);
1183 i2c_unregister_device(client);
1188 static int __unregister_client(struct device *dev, void *dummy)
1190 struct i2c_client *client = i2c_verify_client(dev);
1191 if (client && strcmp(client->name, "dummy"))
1192 i2c_unregister_device(client);
1196 static int __unregister_dummy(struct device *dev, void *dummy)
1198 struct i2c_client *client = i2c_verify_client(dev);
1200 i2c_unregister_device(client);
1204 static int __process_removed_adapter(struct device_driver *d, void *data)
1206 i2c_do_del_adapter(to_i2c_driver(d), data);
1211 * i2c_del_adapter - unregister I2C adapter
1212 * @adap: the adapter being unregistered
1213 * Context: can sleep
1215 * This unregisters an I2C adapter which was previously registered
1216 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1218 void i2c_del_adapter(struct i2c_adapter *adap)
1220 struct i2c_adapter *found;
1221 struct i2c_client *client, *next;
1223 /* First make sure that this adapter was ever added */
1224 mutex_lock(&core_lock);
1225 found = idr_find(&i2c_adapter_idr, adap->nr);
1226 mutex_unlock(&core_lock);
1227 if (found != adap) {
1228 pr_debug("i2c-core: attempting to delete unregistered "
1229 "adapter [%s]\n", adap->name);
1233 /* Tell drivers about this removal */
1234 mutex_lock(&core_lock);
1235 bus_for_each_drv(&i2c_bus_type, NULL, adap,
1236 __process_removed_adapter);
1237 mutex_unlock(&core_lock);
1239 /* Remove devices instantiated from sysfs */
1240 mutex_lock_nested(&adap->userspace_clients_lock,
1241 i2c_adapter_depth(adap));
1242 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1244 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1246 list_del(&client->detected);
1247 i2c_unregister_device(client);
1249 mutex_unlock(&adap->userspace_clients_lock);
1251 /* Detach any active clients. This can't fail, thus we do not
1252 * check the returned value. This is a two-pass process, because
1253 * we can't remove the dummy devices during the first pass: they
1254 * could have been instantiated by real devices wishing to clean
1255 * them up properly, so we give them a chance to do that first. */
1256 device_for_each_child(&adap->dev, NULL, __unregister_client);
1257 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1259 #ifdef CONFIG_I2C_COMPAT
1260 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1264 /* device name is gone after device_unregister */
1265 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1267 /* clean up the sysfs representation */
1268 init_completion(&adap->dev_released);
1269 device_unregister(&adap->dev);
1271 /* wait for sysfs to drop all references */
1272 wait_for_completion(&adap->dev_released);
1275 mutex_lock(&core_lock);
1276 idr_remove(&i2c_adapter_idr, adap->nr);
1277 mutex_unlock(&core_lock);
1279 /* Clear the device structure in case this adapter is ever going to be
1281 memset(&adap->dev, 0, sizeof(adap->dev));
1283 EXPORT_SYMBOL(i2c_del_adapter);
1286 /* ------------------------------------------------------------------------- */
1288 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1292 mutex_lock(&core_lock);
1293 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1294 mutex_unlock(&core_lock);
1298 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1300 static int __process_new_driver(struct device *dev, void *data)
1302 if (dev->type != &i2c_adapter_type)
1304 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1308 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1309 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1312 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1316 /* Can't register until after driver model init */
1317 if (unlikely(WARN_ON(!i2c_bus_type.p)))
1320 /* add the driver to the list of i2c drivers in the driver core */
1321 driver->driver.owner = owner;
1322 driver->driver.bus = &i2c_bus_type;
1324 /* When registration returns, the driver core
1325 * will have called probe() for all matching-but-unbound devices.
1327 res = driver_register(&driver->driver);
1331 /* Drivers should switch to dev_pm_ops instead. */
1332 if (driver->suspend)
1333 pr_warn("i2c-core: driver [%s] using legacy suspend method\n",
1334 driver->driver.name);
1336 pr_warn("i2c-core: driver [%s] using legacy resume method\n",
1337 driver->driver.name);
1339 pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
1341 INIT_LIST_HEAD(&driver->clients);
1342 /* Walk the adapters that are already present */
1343 i2c_for_each_dev(driver, __process_new_driver);
1347 EXPORT_SYMBOL(i2c_register_driver);
1349 static int __process_removed_driver(struct device *dev, void *data)
1351 if (dev->type == &i2c_adapter_type)
1352 i2c_do_del_adapter(data, to_i2c_adapter(dev));
1357 * i2c_del_driver - unregister I2C driver
1358 * @driver: the driver being unregistered
1359 * Context: can sleep
1361 void i2c_del_driver(struct i2c_driver *driver)
1363 i2c_for_each_dev(driver, __process_removed_driver);
1365 driver_unregister(&driver->driver);
1366 pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
1368 EXPORT_SYMBOL(i2c_del_driver);
1370 /* ------------------------------------------------------------------------- */
1373 * i2c_use_client - increments the reference count of the i2c client structure
1374 * @client: the client being referenced
1376 * Each live reference to a client should be refcounted. The driver model does
1377 * that automatically as part of driver binding, so that most drivers don't
1378 * need to do this explicitly: they hold a reference until they're unbound
1381 * A pointer to the client with the incremented reference counter is returned.
1383 struct i2c_client *i2c_use_client(struct i2c_client *client)
1385 if (client && get_device(&client->dev))
1389 EXPORT_SYMBOL(i2c_use_client);
1392 * i2c_release_client - release a use of the i2c client structure
1393 * @client: the client being no longer referenced
1395 * Must be called when a user of a client is finished with it.
1397 void i2c_release_client(struct i2c_client *client)
1400 put_device(&client->dev);
1402 EXPORT_SYMBOL(i2c_release_client);
1404 struct i2c_cmd_arg {
1409 static int i2c_cmd(struct device *dev, void *_arg)
1411 struct i2c_client *client = i2c_verify_client(dev);
1412 struct i2c_cmd_arg *arg = _arg;
1414 if (client && client->driver && client->driver->command)
1415 client->driver->command(client, arg->cmd, arg->arg);
1419 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1421 struct i2c_cmd_arg cmd_arg;
1425 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1427 EXPORT_SYMBOL(i2c_clients_command);
1429 static int __init i2c_init(void)
1433 retval = bus_register(&i2c_bus_type);
1436 #ifdef CONFIG_I2C_COMPAT
1437 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1438 if (!i2c_adapter_compat_class) {
1443 retval = i2c_add_driver(&dummy_driver);
1449 #ifdef CONFIG_I2C_COMPAT
1450 class_compat_unregister(i2c_adapter_compat_class);
1453 bus_unregister(&i2c_bus_type);
1457 static void __exit i2c_exit(void)
1459 i2c_del_driver(&dummy_driver);
1460 #ifdef CONFIG_I2C_COMPAT
1461 class_compat_unregister(i2c_adapter_compat_class);
1463 bus_unregister(&i2c_bus_type);
1466 /* We must initialize early, because some subsystems register i2c drivers
1467 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1469 postcore_initcall(i2c_init);
1470 module_exit(i2c_exit);
1472 /* ----------------------------------------------------
1473 * the functional interface to the i2c busses.
1474 * ----------------------------------------------------
1478 * __i2c_transfer - unlocked flavor of i2c_transfer
1479 * @adap: Handle to I2C bus
1480 * @msgs: One or more messages to execute before STOP is issued to
1481 * terminate the operation; each message begins with a START.
1482 * @num: Number of messages to be executed.
1484 * Returns negative errno, else the number of messages executed.
1486 * Adapter lock must be held when calling this function. No debug logging
1487 * takes place. adap->algo->master_xfer existence isn't checked.
1489 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1491 unsigned long orig_jiffies;
1494 /* Retry automatically on arbitration loss */
1495 orig_jiffies = jiffies;
1496 for (ret = 0, try = 0; try <= adap->retries; try++) {
1497 ret = adap->algo->master_xfer(adap, msgs, num);
1500 if (time_after(jiffies, orig_jiffies + adap->timeout))
1506 EXPORT_SYMBOL(__i2c_transfer);
1509 * i2c_transfer - execute a single or combined I2C message
1510 * @adap: Handle to I2C bus
1511 * @msgs: One or more messages to execute before STOP is issued to
1512 * terminate the operation; each message begins with a START.
1513 * @num: Number of messages to be executed.
1515 * Returns negative errno, else the number of messages executed.
1517 * Note that there is no requirement that each message be sent to
1518 * the same slave address, although that is the most common model.
1520 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1524 /* REVISIT the fault reporting model here is weak:
1526 * - When we get an error after receiving N bytes from a slave,
1527 * there is no way to report "N".
1529 * - When we get a NAK after transmitting N bytes to a slave,
1530 * there is no way to report "N" ... or to let the master
1531 * continue executing the rest of this combined message, if
1532 * that's the appropriate response.
1534 * - When for example "num" is two and we successfully complete
1535 * the first message but get an error part way through the
1536 * second, it's unclear whether that should be reported as
1537 * one (discarding status on the second message) or errno
1538 * (discarding status on the first one).
1541 if (adap->algo->master_xfer) {
1543 for (ret = 0; ret < num; ret++) {
1544 dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
1545 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
1546 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
1547 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
1551 if (in_atomic() || irqs_disabled()) {
1552 ret = i2c_trylock_adapter(adap);
1554 /* I2C activity is ongoing. */
1557 i2c_lock_adapter(adap);
1560 ret = __i2c_transfer(adap, msgs, num);
1561 i2c_unlock_adapter(adap);
1565 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
1569 EXPORT_SYMBOL(i2c_transfer);
1572 * i2c_master_send - issue a single I2C message in master transmit mode
1573 * @client: Handle to slave device
1574 * @buf: Data that will be written to the slave
1575 * @count: How many bytes to write, must be less than 64k since msg.len is u16
1577 * Returns negative errno, or else the number of bytes written.
1579 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
1582 struct i2c_adapter *adap = client->adapter;
1585 msg.addr = client->addr;
1586 msg.flags = client->flags & I2C_M_TEN;
1588 msg.buf = (char *)buf;
1589 #ifdef CONFIG_I2C_ROCKCHIP_COMPAT
1590 msg.scl_rate = 100 * 1000;
1593 ret = i2c_transfer(adap, &msg, 1);
1596 * If everything went ok (i.e. 1 msg transmitted), return #bytes
1597 * transmitted, else error code.
1599 return (ret == 1) ? count : ret;
1601 EXPORT_SYMBOL(i2c_master_send);
1604 * i2c_master_recv - issue a single I2C message in master receive mode
1605 * @client: Handle to slave device
1606 * @buf: Where to store data read from slave
1607 * @count: How many bytes to read, must be less than 64k since msg.len is u16
1609 * Returns negative errno, or else the number of bytes read.
1611 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
1613 struct i2c_adapter *adap = client->adapter;
1617 msg.addr = client->addr;
1618 msg.flags = client->flags & I2C_M_TEN;
1619 msg.flags |= I2C_M_RD;
1622 #ifdef CONFIG_I2C_ROCKCHIP_COMPAT
1623 msg.scl_rate = 100 * 1000;
1626 ret = i2c_transfer(adap, &msg, 1);
1629 * If everything went ok (i.e. 1 msg received), return #bytes received,
1632 return (ret == 1) ? count : ret;
1634 EXPORT_SYMBOL(i2c_master_recv);
1636 /* ----------------------------------------------------
1637 * the i2c address scanning function
1638 * Will not work for 10-bit addresses!
1639 * ----------------------------------------------------
1643 * Legacy default probe function, mostly relevant for SMBus. The default
1644 * probe method is a quick write, but it is known to corrupt the 24RF08
1645 * EEPROMs due to a state machine bug, and could also irreversibly
1646 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
1647 * we use a short byte read instead. Also, some bus drivers don't implement
1648 * quick write, so we fallback to a byte read in that case too.
1649 * On x86, there is another special case for FSC hardware monitoring chips,
1650 * which want regular byte reads (address 0x73.) Fortunately, these are the
1651 * only known chips using this I2C address on PC hardware.
1652 * Returns 1 if probe succeeded, 0 if not.
1654 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
1657 union i2c_smbus_data dummy;
1660 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
1661 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
1662 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1663 I2C_SMBUS_BYTE_DATA, &dummy);
1666 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
1667 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
1668 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
1669 I2C_SMBUS_QUICK, NULL);
1670 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
1671 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1672 I2C_SMBUS_BYTE, &dummy);
1674 dev_warn(&adap->dev, "No suitable probing method supported\n");
1681 static int i2c_detect_address(struct i2c_client *temp_client,
1682 struct i2c_driver *driver)
1684 struct i2c_board_info info;
1685 struct i2c_adapter *adapter = temp_client->adapter;
1686 int addr = temp_client->addr;
1689 /* Make sure the address is valid */
1690 err = i2c_check_addr_validity(addr);
1692 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
1697 /* Skip if already in use */
1698 if (i2c_check_addr_busy(adapter, addr))
1701 /* Make sure there is something at this address */
1702 if (!i2c_default_probe(adapter, addr))
1705 /* Finally call the custom detection function */
1706 memset(&info, 0, sizeof(struct i2c_board_info));
1708 err = driver->detect(temp_client, &info);
1710 /* -ENODEV is returned if the detection fails. We catch it
1711 here as this isn't an error. */
1712 return err == -ENODEV ? 0 : err;
1715 /* Consistency check */
1716 if (info.type[0] == '\0') {
1717 dev_err(&adapter->dev, "%s detection function provided "
1718 "no name for 0x%x\n", driver->driver.name,
1721 struct i2c_client *client;
1723 /* Detection succeeded, instantiate the device */
1724 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
1725 info.type, info.addr);
1726 client = i2c_new_device(adapter, &info);
1728 list_add_tail(&client->detected, &driver->clients);
1730 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
1731 info.type, info.addr);
1736 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
1738 const unsigned short *address_list;
1739 struct i2c_client *temp_client;
1741 int adap_id = i2c_adapter_id(adapter);
1743 address_list = driver->address_list;
1744 if (!driver->detect || !address_list)
1747 /* Stop here if the classes do not match */
1748 if (!(adapter->class & driver->class))
1751 /* Set up a temporary client to help detect callback */
1752 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
1755 temp_client->adapter = adapter;
1757 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
1758 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
1759 "addr 0x%02x\n", adap_id, address_list[i]);
1760 temp_client->addr = address_list[i];
1761 err = i2c_detect_address(temp_client, driver);
1770 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
1772 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1773 I2C_SMBUS_QUICK, NULL) >= 0;
1775 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
1778 i2c_new_probed_device(struct i2c_adapter *adap,
1779 struct i2c_board_info *info,
1780 unsigned short const *addr_list,
1781 int (*probe)(struct i2c_adapter *, unsigned short addr))
1786 probe = i2c_default_probe;
1788 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
1789 /* Check address validity */
1790 if (i2c_check_addr_validity(addr_list[i]) < 0) {
1791 dev_warn(&adap->dev, "Invalid 7-bit address "
1792 "0x%02x\n", addr_list[i]);
1796 /* Check address availability */
1797 if (i2c_check_addr_busy(adap, addr_list[i])) {
1798 dev_dbg(&adap->dev, "Address 0x%02x already in "
1799 "use, not probing\n", addr_list[i]);
1803 /* Test address responsiveness */
1804 if (probe(adap, addr_list[i]))
1808 if (addr_list[i] == I2C_CLIENT_END) {
1809 dev_dbg(&adap->dev, "Probing failed, no device found\n");
1813 info->addr = addr_list[i];
1814 return i2c_new_device(adap, info);
1816 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
1818 struct i2c_adapter *i2c_get_adapter(int nr)
1820 struct i2c_adapter *adapter;
1822 mutex_lock(&core_lock);
1823 adapter = idr_find(&i2c_adapter_idr, nr);
1824 if (adapter && !try_module_get(adapter->owner))
1827 mutex_unlock(&core_lock);
1830 EXPORT_SYMBOL(i2c_get_adapter);
1832 void i2c_put_adapter(struct i2c_adapter *adap)
1834 module_put(adap->owner);
1836 EXPORT_SYMBOL(i2c_put_adapter);
1838 /* The SMBus parts */
1840 #define POLY (0x1070U << 3)
1841 static u8 crc8(u16 data)
1845 for (i = 0; i < 8; i++) {
1850 return (u8)(data >> 8);
1853 /* Incremental CRC8 over count bytes in the array pointed to by p */
1854 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
1858 for (i = 0; i < count; i++)
1859 crc = crc8((crc ^ p[i]) << 8);
1863 /* Assume a 7-bit address, which is reasonable for SMBus */
1864 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
1866 /* The address will be sent first */
1867 u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
1868 pec = i2c_smbus_pec(pec, &addr, 1);
1870 /* The data buffer follows */
1871 return i2c_smbus_pec(pec, msg->buf, msg->len);
1874 /* Used for write only transactions */
1875 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
1877 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
1881 /* Return <0 on CRC error
1882 If there was a write before this read (most cases) we need to take the
1883 partial CRC from the write part into account.
1884 Note that this function does modify the message (we need to decrease the
1885 message length to hide the CRC byte from the caller). */
1886 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
1888 u8 rpec = msg->buf[--msg->len];
1889 cpec = i2c_smbus_msg_pec(cpec, msg);
1892 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
1900 * i2c_smbus_read_byte - SMBus "receive byte" protocol
1901 * @client: Handle to slave device
1903 * This executes the SMBus "receive byte" protocol, returning negative errno
1904 * else the byte received from the device.
1906 s32 i2c_smbus_read_byte(const struct i2c_client *client)
1908 union i2c_smbus_data data;
1911 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1913 I2C_SMBUS_BYTE, &data);
1914 return (status < 0) ? status : data.byte;
1916 EXPORT_SYMBOL(i2c_smbus_read_byte);
1919 * i2c_smbus_write_byte - SMBus "send byte" protocol
1920 * @client: Handle to slave device
1921 * @value: Byte to be sent
1923 * This executes the SMBus "send byte" protocol, returning negative errno
1924 * else zero on success.
1926 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
1928 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1929 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
1931 EXPORT_SYMBOL(i2c_smbus_write_byte);
1934 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
1935 * @client: Handle to slave device
1936 * @command: Byte interpreted by slave
1938 * This executes the SMBus "read byte" protocol, returning negative errno
1939 * else a data byte received from the device.
1941 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
1943 union i2c_smbus_data data;
1946 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1947 I2C_SMBUS_READ, command,
1948 I2C_SMBUS_BYTE_DATA, &data);
1949 return (status < 0) ? status : data.byte;
1951 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
1954 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
1955 * @client: Handle to slave device
1956 * @command: Byte interpreted by slave
1957 * @value: Byte being written
1959 * This executes the SMBus "write byte" protocol, returning negative errno
1960 * else zero on success.
1962 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
1965 union i2c_smbus_data data;
1967 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1968 I2C_SMBUS_WRITE, command,
1969 I2C_SMBUS_BYTE_DATA, &data);
1971 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
1974 * i2c_smbus_read_word_data - SMBus "read word" protocol
1975 * @client: Handle to slave device
1976 * @command: Byte interpreted by slave
1978 * This executes the SMBus "read word" protocol, returning negative errno
1979 * else a 16-bit unsigned "word" received from the device.
1981 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
1983 union i2c_smbus_data data;
1986 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1987 I2C_SMBUS_READ, command,
1988 I2C_SMBUS_WORD_DATA, &data);
1989 return (status < 0) ? status : data.word;
1991 EXPORT_SYMBOL(i2c_smbus_read_word_data);
1994 * i2c_smbus_write_word_data - SMBus "write word" protocol
1995 * @client: Handle to slave device
1996 * @command: Byte interpreted by slave
1997 * @value: 16-bit "word" being written
1999 * This executes the SMBus "write word" protocol, returning negative errno
2000 * else zero on success.
2002 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2005 union i2c_smbus_data data;
2007 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2008 I2C_SMBUS_WRITE, command,
2009 I2C_SMBUS_WORD_DATA, &data);
2011 EXPORT_SYMBOL(i2c_smbus_write_word_data);
2014 * i2c_smbus_read_block_data - SMBus "block read" protocol
2015 * @client: Handle to slave device
2016 * @command: Byte interpreted by slave
2017 * @values: Byte array into which data will be read; big enough to hold
2018 * the data returned by the slave. SMBus allows at most 32 bytes.
2020 * This executes the SMBus "block read" protocol, returning negative errno
2021 * else the number of data bytes in the slave's response.
2023 * Note that using this function requires that the client's adapter support
2024 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
2025 * support this; its emulation through I2C messaging relies on a specific
2026 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2028 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2031 union i2c_smbus_data data;
2034 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2035 I2C_SMBUS_READ, command,
2036 I2C_SMBUS_BLOCK_DATA, &data);
2040 memcpy(values, &data.block[1], data.block[0]);
2041 return data.block[0];
2043 EXPORT_SYMBOL(i2c_smbus_read_block_data);
2046 * i2c_smbus_write_block_data - SMBus "block write" protocol
2047 * @client: Handle to slave device
2048 * @command: Byte interpreted by slave
2049 * @length: Size of data block; SMBus allows at most 32 bytes
2050 * @values: Byte array which will be written.
2052 * This executes the SMBus "block write" protocol, returning negative errno
2053 * else zero on success.
2055 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2056 u8 length, const u8 *values)
2058 union i2c_smbus_data data;
2060 if (length > I2C_SMBUS_BLOCK_MAX)
2061 length = I2C_SMBUS_BLOCK_MAX;
2062 data.block[0] = length;
2063 memcpy(&data.block[1], values, length);
2064 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2065 I2C_SMBUS_WRITE, command,
2066 I2C_SMBUS_BLOCK_DATA, &data);
2068 EXPORT_SYMBOL(i2c_smbus_write_block_data);
2070 /* Returns the number of read bytes */
2071 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2072 u8 length, u8 *values)
2074 union i2c_smbus_data data;
2077 if (length > I2C_SMBUS_BLOCK_MAX)
2078 length = I2C_SMBUS_BLOCK_MAX;
2079 data.block[0] = length;
2080 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2081 I2C_SMBUS_READ, command,
2082 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2086 memcpy(values, &data.block[1], data.block[0]);
2087 return data.block[0];
2089 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2091 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2092 u8 length, const u8 *values)
2094 union i2c_smbus_data data;
2096 if (length > I2C_SMBUS_BLOCK_MAX)
2097 length = I2C_SMBUS_BLOCK_MAX;
2098 data.block[0] = length;
2099 memcpy(data.block + 1, values, length);
2100 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2101 I2C_SMBUS_WRITE, command,
2102 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2104 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2106 /* Simulate a SMBus command using the i2c protocol
2107 No checking of parameters is done! */
2108 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2109 unsigned short flags,
2110 char read_write, u8 command, int size,
2111 union i2c_smbus_data *data)
2113 /* So we need to generate a series of msgs. In the case of writing, we
2114 need to use only one message; when reading, we need two. We initialize
2115 most things with sane defaults, to keep the code below somewhat
2117 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2118 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2119 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2123 struct i2c_msg msg[2] = {
2131 .flags = flags | I2C_M_RD,
2137 msgbuf0[0] = command;
2139 case I2C_SMBUS_QUICK:
2141 /* Special case: The read/write field is used as data */
2142 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2146 case I2C_SMBUS_BYTE:
2147 if (read_write == I2C_SMBUS_READ) {
2148 /* Special case: only a read! */
2149 msg[0].flags = I2C_M_RD | flags;
2153 case I2C_SMBUS_BYTE_DATA:
2154 if (read_write == I2C_SMBUS_READ)
2158 msgbuf0[1] = data->byte;
2161 case I2C_SMBUS_WORD_DATA:
2162 if (read_write == I2C_SMBUS_READ)
2166 msgbuf0[1] = data->word & 0xff;
2167 msgbuf0[2] = data->word >> 8;
2170 case I2C_SMBUS_PROC_CALL:
2171 num = 2; /* Special case */
2172 read_write = I2C_SMBUS_READ;
2175 msgbuf0[1] = data->word & 0xff;
2176 msgbuf0[2] = data->word >> 8;
2178 case I2C_SMBUS_BLOCK_DATA:
2179 if (read_write == I2C_SMBUS_READ) {
2180 msg[1].flags |= I2C_M_RECV_LEN;
2181 msg[1].len = 1; /* block length will be added by
2182 the underlying bus driver */
2184 msg[0].len = data->block[0] + 2;
2185 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
2186 dev_err(&adapter->dev,
2187 "Invalid block write size %d\n",
2191 for (i = 1; i < msg[0].len; i++)
2192 msgbuf0[i] = data->block[i-1];
2195 case I2C_SMBUS_BLOCK_PROC_CALL:
2196 num = 2; /* Another special case */
2197 read_write = I2C_SMBUS_READ;
2198 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
2199 dev_err(&adapter->dev,
2200 "Invalid block write size %d\n",
2204 msg[0].len = data->block[0] + 2;
2205 for (i = 1; i < msg[0].len; i++)
2206 msgbuf0[i] = data->block[i-1];
2207 msg[1].flags |= I2C_M_RECV_LEN;
2208 msg[1].len = 1; /* block length will be added by
2209 the underlying bus driver */
2211 case I2C_SMBUS_I2C_BLOCK_DATA:
2212 if (read_write == I2C_SMBUS_READ) {
2213 msg[1].len = data->block[0];
2215 msg[0].len = data->block[0] + 1;
2216 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
2217 dev_err(&adapter->dev,
2218 "Invalid block write size %d\n",
2222 for (i = 1; i <= data->block[0]; i++)
2223 msgbuf0[i] = data->block[i];
2227 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
2231 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
2232 && size != I2C_SMBUS_I2C_BLOCK_DATA);
2234 /* Compute PEC if first message is a write */
2235 if (!(msg[0].flags & I2C_M_RD)) {
2236 if (num == 1) /* Write only */
2237 i2c_smbus_add_pec(&msg[0]);
2238 else /* Write followed by read */
2239 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
2241 /* Ask for PEC if last message is a read */
2242 if (msg[num-1].flags & I2C_M_RD)
2246 status = i2c_transfer(adapter, msg, num);
2250 /* Check PEC if last message is a read */
2251 if (i && (msg[num-1].flags & I2C_M_RD)) {
2252 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
2257 if (read_write == I2C_SMBUS_READ)
2259 case I2C_SMBUS_BYTE:
2260 data->byte = msgbuf0[0];
2262 case I2C_SMBUS_BYTE_DATA:
2263 data->byte = msgbuf1[0];
2265 case I2C_SMBUS_WORD_DATA:
2266 case I2C_SMBUS_PROC_CALL:
2267 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
2269 case I2C_SMBUS_I2C_BLOCK_DATA:
2270 for (i = 0; i < data->block[0]; i++)
2271 data->block[i+1] = msgbuf1[i];
2273 case I2C_SMBUS_BLOCK_DATA:
2274 case I2C_SMBUS_BLOCK_PROC_CALL:
2275 for (i = 0; i < msgbuf1[0] + 1; i++)
2276 data->block[i] = msgbuf1[i];
2283 * i2c_smbus_xfer - execute SMBus protocol operations
2284 * @adapter: Handle to I2C bus
2285 * @addr: Address of SMBus slave on that bus
2286 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
2287 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
2288 * @command: Byte interpreted by slave, for protocols which use such bytes
2289 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
2290 * @data: Data to be read or written
2292 * This executes an SMBus protocol operation, and returns a negative
2293 * errno code else zero on success.
2295 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
2296 char read_write, u8 command, int protocol,
2297 union i2c_smbus_data *data)
2299 unsigned long orig_jiffies;
2303 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
2305 if (adapter->algo->smbus_xfer) {
2306 i2c_lock_adapter(adapter);
2308 /* Retry automatically on arbitration loss */
2309 orig_jiffies = jiffies;
2310 for (res = 0, try = 0; try <= adapter->retries; try++) {
2311 res = adapter->algo->smbus_xfer(adapter, addr, flags,
2312 read_write, command,
2316 if (time_after(jiffies,
2317 orig_jiffies + adapter->timeout))
2320 i2c_unlock_adapter(adapter);
2322 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
2325 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
2326 * implement native support for the SMBus operation.
2330 return i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
2331 command, protocol, data);
2333 EXPORT_SYMBOL(i2c_smbus_xfer);
2335 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2336 MODULE_DESCRIPTION("I2C-Bus main module");
2337 MODULE_LICENSE("GPL");