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 and detach_adapter 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;
98 /* uevent helps with hotplug: modprobe -q $(MODALIAS) */
99 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
101 struct i2c_client *client = to_i2c_client(dev);
103 if (add_uevent_var(env, "MODALIAS=%s%s",
104 I2C_MODULE_PREFIX, client->name))
106 dev_dbg(dev, "uevent\n");
111 #define i2c_device_uevent NULL
112 #endif /* CONFIG_HOTPLUG */
114 /* i2c bus recovery routines */
115 static int get_scl_gpio_value(struct i2c_adapter *adap)
117 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
120 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
122 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
125 static int get_sda_gpio_value(struct i2c_adapter *adap)
127 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
130 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
132 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
133 struct device *dev = &adap->dev;
136 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
137 GPIOF_OUT_INIT_HIGH, "i2c-scl");
139 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
144 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
145 /* work without SDA polling */
146 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
155 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
157 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
160 gpio_free(bri->sda_gpio);
162 gpio_free(bri->scl_gpio);
166 * We are generating clock pulses. ndelay() determines durating of clk pulses.
167 * We will generate clock with rate 100 KHz and so duration of both clock levels
168 * is: delay in ns = (10^6 / 100) / 2
170 #define RECOVERY_NDELAY 5000
171 #define RECOVERY_CLK_CNT 9
173 static int i2c_generic_recovery(struct i2c_adapter *adap)
175 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
176 int i = 0, val = 1, ret = 0;
178 if (bri->prepare_recovery)
179 bri->prepare_recovery(bri);
182 * By this time SCL is high, as we need to give 9 falling-rising edges
184 while (i++ < RECOVERY_CLK_CNT * 2) {
186 /* Break if SDA is high */
187 if (bri->get_sda && bri->get_sda(adap))
189 /* SCL shouldn't be low here */
190 if (!bri->get_scl(adap)) {
192 "SCL is stuck low, exit recovery\n");
199 bri->set_scl(adap, val);
200 ndelay(RECOVERY_NDELAY);
203 if (bri->unprepare_recovery)
204 bri->unprepare_recovery(bri);
209 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
211 adap->bus_recovery_info->set_scl(adap, 1);
212 return i2c_generic_recovery(adap);
215 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
219 ret = i2c_get_gpios_for_recovery(adap);
223 ret = i2c_generic_recovery(adap);
224 i2c_put_gpios_for_recovery(adap);
229 int i2c_recover_bus(struct i2c_adapter *adap)
231 if (!adap->bus_recovery_info)
234 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
235 return adap->bus_recovery_info->recover_bus(adap);
238 static int i2c_device_probe(struct device *dev)
240 struct i2c_client *client = i2c_verify_client(dev);
241 struct i2c_driver *driver;
247 driver = to_i2c_driver(dev->driver);
248 if (!driver->probe || !driver->id_table)
250 client->driver = driver;
251 if (!device_can_wakeup(&client->dev))
252 device_init_wakeup(&client->dev,
253 client->flags & I2C_CLIENT_WAKE);
254 dev_dbg(dev, "probe\n");
256 status = driver->probe(client, i2c_match_id(driver->id_table, client));
258 client->driver = NULL;
259 i2c_set_clientdata(client, NULL);
264 static int i2c_device_remove(struct device *dev)
266 struct i2c_client *client = i2c_verify_client(dev);
267 struct i2c_driver *driver;
270 if (!client || !dev->driver)
273 driver = to_i2c_driver(dev->driver);
274 if (driver->remove) {
275 dev_dbg(dev, "remove\n");
276 status = driver->remove(client);
282 client->driver = NULL;
283 i2c_set_clientdata(client, NULL);
288 static void i2c_device_shutdown(struct device *dev)
290 struct i2c_client *client = i2c_verify_client(dev);
291 struct i2c_driver *driver;
293 if (!client || !dev->driver)
295 driver = to_i2c_driver(dev->driver);
296 if (driver->shutdown)
297 driver->shutdown(client);
300 #ifdef CONFIG_PM_SLEEP
301 static int i2c_legacy_suspend(struct device *dev, pm_message_t mesg)
303 struct i2c_client *client = i2c_verify_client(dev);
304 struct i2c_driver *driver;
306 if (!client || !dev->driver)
308 driver = to_i2c_driver(dev->driver);
309 if (!driver->suspend)
311 return driver->suspend(client, mesg);
314 static int i2c_legacy_resume(struct device *dev)
316 struct i2c_client *client = i2c_verify_client(dev);
317 struct i2c_driver *driver;
319 if (!client || !dev->driver)
321 driver = to_i2c_driver(dev->driver);
324 return driver->resume(client);
327 static int i2c_device_pm_suspend(struct device *dev)
329 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
332 return pm_generic_suspend(dev);
334 return i2c_legacy_suspend(dev, PMSG_SUSPEND);
337 static int i2c_device_pm_resume(struct device *dev)
339 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
342 return pm_generic_resume(dev);
344 return i2c_legacy_resume(dev);
347 static int i2c_device_pm_freeze(struct device *dev)
349 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
352 return pm_generic_freeze(dev);
354 return i2c_legacy_suspend(dev, PMSG_FREEZE);
357 static int i2c_device_pm_thaw(struct device *dev)
359 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
362 return pm_generic_thaw(dev);
364 return i2c_legacy_resume(dev);
367 static int i2c_device_pm_poweroff(struct device *dev)
369 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
372 return pm_generic_poweroff(dev);
374 return i2c_legacy_suspend(dev, PMSG_HIBERNATE);
377 static int i2c_device_pm_restore(struct device *dev)
379 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
382 return pm_generic_restore(dev);
384 return i2c_legacy_resume(dev);
386 #else /* !CONFIG_PM_SLEEP */
387 #define i2c_device_pm_suspend NULL
388 #define i2c_device_pm_resume NULL
389 #define i2c_device_pm_freeze NULL
390 #define i2c_device_pm_thaw NULL
391 #define i2c_device_pm_poweroff NULL
392 #define i2c_device_pm_restore NULL
393 #endif /* !CONFIG_PM_SLEEP */
395 static void i2c_client_dev_release(struct device *dev)
397 kfree(to_i2c_client(dev));
401 show_name(struct device *dev, struct device_attribute *attr, char *buf)
403 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
404 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
408 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
410 struct i2c_client *client = to_i2c_client(dev);
411 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
414 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
415 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
417 static struct attribute *i2c_dev_attrs[] = {
419 /* modalias helps coldplug: modprobe $(cat .../modalias) */
420 &dev_attr_modalias.attr,
424 static struct attribute_group i2c_dev_attr_group = {
425 .attrs = i2c_dev_attrs,
428 static const struct attribute_group *i2c_dev_attr_groups[] = {
433 static const struct dev_pm_ops i2c_device_pm_ops = {
434 .suspend = i2c_device_pm_suspend,
435 .resume = i2c_device_pm_resume,
436 .freeze = i2c_device_pm_freeze,
437 .thaw = i2c_device_pm_thaw,
438 .poweroff = i2c_device_pm_poweroff,
439 .restore = i2c_device_pm_restore,
441 pm_generic_runtime_suspend,
442 pm_generic_runtime_resume,
443 pm_generic_runtime_idle
447 struct bus_type i2c_bus_type = {
449 .match = i2c_device_match,
450 .probe = i2c_device_probe,
451 .remove = i2c_device_remove,
452 .shutdown = i2c_device_shutdown,
453 .pm = &i2c_device_pm_ops,
455 EXPORT_SYMBOL_GPL(i2c_bus_type);
457 static struct device_type i2c_client_type = {
458 .groups = i2c_dev_attr_groups,
459 .uevent = i2c_device_uevent,
460 .release = i2c_client_dev_release,
465 * i2c_verify_client - return parameter as i2c_client, or NULL
466 * @dev: device, probably from some driver model iterator
468 * When traversing the driver model tree, perhaps using driver model
469 * iterators like @device_for_each_child(), you can't assume very much
470 * about the nodes you find. Use this function to avoid oopses caused
471 * by wrongly treating some non-I2C device as an i2c_client.
473 struct i2c_client *i2c_verify_client(struct device *dev)
475 return (dev->type == &i2c_client_type)
479 EXPORT_SYMBOL(i2c_verify_client);
482 /* This is a permissive address validity check, I2C address map constraints
483 * are purposely not enforced, except for the general call address. */
484 static int i2c_check_client_addr_validity(const struct i2c_client *client)
486 if (client->flags & I2C_CLIENT_TEN) {
487 /* 10-bit address, all values are valid */
488 if (client->addr > 0x3ff)
491 /* 7-bit address, reject the general call address */
492 if (client->addr == 0x00 || client->addr > 0x7f)
498 /* And this is a strict address validity check, used when probing. If a
499 * device uses a reserved address, then it shouldn't be probed. 7-bit
500 * addressing is assumed, 10-bit address devices are rare and should be
501 * explicitly enumerated. */
502 static int i2c_check_addr_validity(unsigned short addr)
505 * Reserved addresses per I2C specification:
506 * 0x00 General call address / START byte
508 * 0x02 Reserved for different bus format
509 * 0x03 Reserved for future purposes
510 * 0x04-0x07 Hs-mode master code
511 * 0x78-0x7b 10-bit slave addressing
512 * 0x7c-0x7f Reserved for future purposes
514 if (addr < 0x08 || addr > 0x77)
519 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
521 struct i2c_client *client = i2c_verify_client(dev);
522 int addr = *(int *)addrp;
524 if (client && client->addr == addr)
529 /* walk up mux tree */
530 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
532 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
535 result = device_for_each_child(&adapter->dev, &addr,
536 __i2c_check_addr_busy);
538 if (!result && parent)
539 result = i2c_check_mux_parents(parent, addr);
544 /* recurse down mux tree */
545 static int i2c_check_mux_children(struct device *dev, void *addrp)
549 if (dev->type == &i2c_adapter_type)
550 result = device_for_each_child(dev, addrp,
551 i2c_check_mux_children);
553 result = __i2c_check_addr_busy(dev, addrp);
558 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
560 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
564 result = i2c_check_mux_parents(parent, addr);
567 result = device_for_each_child(&adapter->dev, &addr,
568 i2c_check_mux_children);
574 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
575 * @adapter: Target I2C bus segment
577 void i2c_lock_adapter(struct i2c_adapter *adapter)
579 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
582 i2c_lock_adapter(parent);
584 rt_mutex_lock(&adapter->bus_lock);
586 EXPORT_SYMBOL_GPL(i2c_lock_adapter);
589 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
590 * @adapter: Target I2C bus segment
592 static int i2c_trylock_adapter(struct i2c_adapter *adapter)
594 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
597 return i2c_trylock_adapter(parent);
599 return rt_mutex_trylock(&adapter->bus_lock);
603 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
604 * @adapter: Target I2C bus segment
606 void i2c_unlock_adapter(struct i2c_adapter *adapter)
608 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
611 i2c_unlock_adapter(parent);
613 rt_mutex_unlock(&adapter->bus_lock);
615 EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
618 * i2c_new_device - instantiate an i2c device
619 * @adap: the adapter managing the device
620 * @info: describes one I2C device; bus_num is ignored
623 * Create an i2c device. Binding is handled through driver model
624 * probe()/remove() methods. A driver may be bound to this device when we
625 * return from this function, or any later moment (e.g. maybe hotplugging will
626 * load the driver module). This call is not appropriate for use by mainboard
627 * initialization logic, which usually runs during an arch_initcall() long
628 * before any i2c_adapter could exist.
630 * This returns the new i2c client, which may be saved for later use with
631 * i2c_unregister_device(); or NULL to indicate an error.
634 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
636 struct i2c_client *client;
639 client = kzalloc(sizeof *client, GFP_KERNEL);
643 client->adapter = adap;
645 client->dev.platform_data = info->platform_data;
648 client->dev.archdata = *info->archdata;
650 client->flags = info->flags;
651 client->addr = info->addr;
652 client->irq = info->irq;
654 strlcpy(client->name, info->type, sizeof(client->name));
656 /* Check for address validity */
657 status = i2c_check_client_addr_validity(client);
659 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
660 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
664 /* Check for address business */
665 status = i2c_check_addr_busy(adap, client->addr);
669 client->dev.parent = &client->adapter->dev;
670 client->dev.bus = &i2c_bus_type;
671 client->dev.type = &i2c_client_type;
672 client->dev.of_node = info->of_node;
673 ACPI_HANDLE_SET(&client->dev, info->acpi_node.handle);
675 /* For 10-bit clients, add an arbitrary offset to avoid collisions */
676 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
677 client->addr | ((client->flags & I2C_CLIENT_TEN)
679 status = device_register(&client->dev);
683 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
684 client->name, dev_name(&client->dev));
689 dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
690 "(%d)\n", client->name, client->addr, status);
695 EXPORT_SYMBOL_GPL(i2c_new_device);
699 * i2c_unregister_device - reverse effect of i2c_new_device()
700 * @client: value returned from i2c_new_device()
703 void i2c_unregister_device(struct i2c_client *client)
705 device_unregister(&client->dev);
707 EXPORT_SYMBOL_GPL(i2c_unregister_device);
710 static const struct i2c_device_id dummy_id[] = {
715 static int dummy_probe(struct i2c_client *client,
716 const struct i2c_device_id *id)
721 static int dummy_remove(struct i2c_client *client)
726 static struct i2c_driver dummy_driver = {
727 .driver.name = "dummy",
728 .probe = dummy_probe,
729 .remove = dummy_remove,
730 .id_table = dummy_id,
734 * i2c_new_dummy - return a new i2c device bound to a dummy driver
735 * @adapter: the adapter managing the device
736 * @address: seven bit address to be used
739 * This returns an I2C client bound to the "dummy" driver, intended for use
740 * with devices that consume multiple addresses. Examples of such chips
741 * include various EEPROMS (like 24c04 and 24c08 models).
743 * These dummy devices have two main uses. First, most I2C and SMBus calls
744 * except i2c_transfer() need a client handle; the dummy will be that handle.
745 * And second, this prevents the specified address from being bound to a
748 * This returns the new i2c client, which should be saved for later use with
749 * i2c_unregister_device(); or NULL to indicate an error.
751 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
753 struct i2c_board_info info = {
754 I2C_BOARD_INFO("dummy", address),
757 return i2c_new_device(adapter, &info);
759 EXPORT_SYMBOL_GPL(i2c_new_dummy);
761 /* ------------------------------------------------------------------------- */
763 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
765 static void i2c_adapter_dev_release(struct device *dev)
767 struct i2c_adapter *adap = to_i2c_adapter(dev);
768 complete(&adap->dev_released);
772 * This function is only needed for mutex_lock_nested, so it is never
773 * called unless locking correctness checking is enabled. Thus we
774 * make it inline to avoid a compiler warning. That's what gcc ends up
777 static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
779 unsigned int depth = 0;
781 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
788 * Let users instantiate I2C devices through sysfs. This can be used when
789 * platform initialization code doesn't contain the proper data for
790 * whatever reason. Also useful for drivers that do device detection and
791 * detection fails, either because the device uses an unexpected address,
792 * or this is a compatible device with different ID register values.
794 * Parameter checking may look overzealous, but we really don't want
795 * the user to provide incorrect parameters.
798 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
799 const char *buf, size_t count)
801 struct i2c_adapter *adap = to_i2c_adapter(dev);
802 struct i2c_board_info info;
803 struct i2c_client *client;
807 memset(&info, 0, sizeof(struct i2c_board_info));
809 blank = strchr(buf, ' ');
811 dev_err(dev, "%s: Missing parameters\n", "new_device");
814 if (blank - buf > I2C_NAME_SIZE - 1) {
815 dev_err(dev, "%s: Invalid device name\n", "new_device");
818 memcpy(info.type, buf, blank - buf);
820 /* Parse remaining parameters, reject extra parameters */
821 res = sscanf(++blank, "%hi%c", &info.addr, &end);
823 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
826 if (res > 1 && end != '\n') {
827 dev_err(dev, "%s: Extra parameters\n", "new_device");
831 client = i2c_new_device(adap, &info);
835 /* Keep track of the added device */
836 mutex_lock(&adap->userspace_clients_lock);
837 list_add_tail(&client->detected, &adap->userspace_clients);
838 mutex_unlock(&adap->userspace_clients_lock);
839 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
840 info.type, info.addr);
846 * And of course let the users delete the devices they instantiated, if
847 * they got it wrong. This interface can only be used to delete devices
848 * instantiated by i2c_sysfs_new_device above. This guarantees that we
849 * don't delete devices to which some kernel code still has references.
851 * Parameter checking may look overzealous, but we really don't want
852 * the user to delete the wrong device.
855 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
856 const char *buf, size_t count)
858 struct i2c_adapter *adap = to_i2c_adapter(dev);
859 struct i2c_client *client, *next;
864 /* Parse parameters, reject extra parameters */
865 res = sscanf(buf, "%hi%c", &addr, &end);
867 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
870 if (res > 1 && end != '\n') {
871 dev_err(dev, "%s: Extra parameters\n", "delete_device");
875 /* Make sure the device was added through sysfs */
877 mutex_lock_nested(&adap->userspace_clients_lock,
878 i2c_adapter_depth(adap));
879 list_for_each_entry_safe(client, next, &adap->userspace_clients,
881 if (client->addr == addr) {
882 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
883 "delete_device", client->name, client->addr);
885 list_del(&client->detected);
886 i2c_unregister_device(client);
891 mutex_unlock(&adap->userspace_clients_lock);
894 dev_err(dev, "%s: Can't find device in list\n",
899 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
900 static DEVICE_ATTR(delete_device, S_IWUSR, NULL, i2c_sysfs_delete_device);
902 static struct attribute *i2c_adapter_attrs[] = {
904 &dev_attr_new_device.attr,
905 &dev_attr_delete_device.attr,
909 static struct attribute_group i2c_adapter_attr_group = {
910 .attrs = i2c_adapter_attrs,
913 static const struct attribute_group *i2c_adapter_attr_groups[] = {
914 &i2c_adapter_attr_group,
918 struct device_type i2c_adapter_type = {
919 .groups = i2c_adapter_attr_groups,
920 .release = i2c_adapter_dev_release,
922 EXPORT_SYMBOL_GPL(i2c_adapter_type);
925 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
926 * @dev: device, probably from some driver model iterator
928 * When traversing the driver model tree, perhaps using driver model
929 * iterators like @device_for_each_child(), you can't assume very much
930 * about the nodes you find. Use this function to avoid oopses caused
931 * by wrongly treating some non-I2C device as an i2c_adapter.
933 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
935 return (dev->type == &i2c_adapter_type)
936 ? to_i2c_adapter(dev)
939 EXPORT_SYMBOL(i2c_verify_adapter);
941 #ifdef CONFIG_I2C_COMPAT
942 static struct class_compat *i2c_adapter_compat_class;
945 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
947 struct i2c_devinfo *devinfo;
949 down_read(&__i2c_board_lock);
950 list_for_each_entry(devinfo, &__i2c_board_list, list) {
951 if (devinfo->busnum == adapter->nr
952 && !i2c_new_device(adapter,
953 &devinfo->board_info))
954 dev_err(&adapter->dev,
955 "Can't create device at 0x%02x\n",
956 devinfo->board_info.addr);
958 up_read(&__i2c_board_lock);
961 static int i2c_do_add_adapter(struct i2c_driver *driver,
962 struct i2c_adapter *adap)
964 /* Detect supported devices on that bus, and instantiate them */
965 i2c_detect(adap, driver);
967 /* Let legacy drivers scan this bus for matching devices */
968 if (driver->attach_adapter) {
969 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
970 driver->driver.name);
971 dev_warn(&adap->dev, "Please use another way to instantiate "
972 "your i2c_client\n");
973 /* We ignore the return code; if it fails, too bad */
974 driver->attach_adapter(adap);
979 static int __process_new_adapter(struct device_driver *d, void *data)
981 return i2c_do_add_adapter(to_i2c_driver(d), data);
984 static int i2c_register_adapter(struct i2c_adapter *adap)
988 /* Can't register until after driver model init */
989 if (unlikely(WARN_ON(!i2c_bus_type.p))) {
995 if (unlikely(adap->name[0] == '\0')) {
996 pr_err("i2c-core: Attempt to register an adapter with "
1000 if (unlikely(!adap->algo)) {
1001 pr_err("i2c-core: Attempt to register adapter '%s' with "
1002 "no algo!\n", adap->name);
1006 rt_mutex_init(&adap->bus_lock);
1007 mutex_init(&adap->userspace_clients_lock);
1008 INIT_LIST_HEAD(&adap->userspace_clients);
1010 /* Set default timeout to 1 second if not already set */
1011 if (adap->timeout == 0)
1014 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1015 adap->dev.bus = &i2c_bus_type;
1016 adap->dev.type = &i2c_adapter_type;
1017 res = device_register(&adap->dev);
1021 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1023 #ifdef CONFIG_I2C_COMPAT
1024 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1027 dev_warn(&adap->dev,
1028 "Failed to create compatibility class link\n");
1031 /* bus recovery specific initialization */
1032 if (adap->bus_recovery_info) {
1033 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
1035 if (!bri->recover_bus) {
1036 dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
1037 adap->bus_recovery_info = NULL;
1041 /* Generic GPIO recovery */
1042 if (bri->recover_bus == i2c_generic_gpio_recovery) {
1043 if (!gpio_is_valid(bri->scl_gpio)) {
1044 dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
1045 adap->bus_recovery_info = NULL;
1049 if (gpio_is_valid(bri->sda_gpio))
1050 bri->get_sda = get_sda_gpio_value;
1052 bri->get_sda = NULL;
1054 bri->get_scl = get_scl_gpio_value;
1055 bri->set_scl = set_scl_gpio_value;
1056 } else if (!bri->set_scl || !bri->get_scl) {
1057 /* Generic SCL recovery */
1058 dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
1059 adap->bus_recovery_info = NULL;
1064 /* create pre-declared device nodes */
1065 if (adap->nr < __i2c_first_dynamic_bus_num)
1066 i2c_scan_static_board_info(adap);
1068 /* Notify drivers */
1069 mutex_lock(&core_lock);
1070 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1071 mutex_unlock(&core_lock);
1076 mutex_lock(&core_lock);
1077 idr_remove(&i2c_adapter_idr, adap->nr);
1078 mutex_unlock(&core_lock);
1083 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1084 * @adap: the adapter to register (with adap->nr initialized)
1085 * Context: can sleep
1087 * See i2c_add_numbered_adapter() for details.
1089 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1093 mutex_lock(&core_lock);
1094 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1,
1096 mutex_unlock(&core_lock);
1098 return id == -ENOSPC ? -EBUSY : id;
1100 return i2c_register_adapter(adap);
1104 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1105 * @adapter: the adapter to add
1106 * Context: can sleep
1108 * This routine is used to declare an I2C adapter when its bus number
1109 * doesn't matter or when its bus number is specified by an dt alias.
1110 * Examples of bases when the bus number doesn't matter: I2C adapters
1111 * dynamically added by USB links or PCI plugin cards.
1113 * When this returns zero, a new bus number was allocated and stored
1114 * in adap->nr, and the specified adapter became available for clients.
1115 * Otherwise, a negative errno value is returned.
1117 int i2c_add_adapter(struct i2c_adapter *adapter)
1119 struct device *dev = &adapter->dev;
1123 id = of_alias_get_id(dev->of_node, "i2c");
1126 return __i2c_add_numbered_adapter(adapter);
1130 mutex_lock(&core_lock);
1131 id = idr_alloc(&i2c_adapter_idr, adapter,
1132 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1133 mutex_unlock(&core_lock);
1139 return i2c_register_adapter(adapter);
1141 EXPORT_SYMBOL(i2c_add_adapter);
1144 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1145 * @adap: the adapter to register (with adap->nr initialized)
1146 * Context: can sleep
1148 * This routine is used to declare an I2C adapter when its bus number
1149 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1150 * or otherwise built in to the system's mainboard, and where i2c_board_info
1151 * is used to properly configure I2C devices.
1153 * If the requested bus number is set to -1, then this function will behave
1154 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1156 * If no devices have pre-been declared for this bus, then be sure to
1157 * register the adapter before any dynamically allocated ones. Otherwise
1158 * the required bus ID may not be available.
1160 * When this returns zero, the specified adapter became available for
1161 * clients using the bus number provided in adap->nr. Also, the table
1162 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1163 * and the appropriate driver model device nodes are created. Otherwise, a
1164 * negative errno value is returned.
1166 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1168 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1169 return i2c_add_adapter(adap);
1171 return __i2c_add_numbered_adapter(adap);
1173 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1175 static int i2c_do_del_adapter(struct i2c_driver *driver,
1176 struct i2c_adapter *adapter)
1178 struct i2c_client *client, *_n;
1181 /* Remove the devices we created ourselves as the result of hardware
1182 * probing (using a driver's detect method) */
1183 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1184 if (client->adapter == adapter) {
1185 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1186 client->name, client->addr);
1187 list_del(&client->detected);
1188 i2c_unregister_device(client);
1192 if (!driver->detach_adapter)
1194 dev_warn(&adapter->dev, "%s: detach_adapter method is deprecated\n",
1195 driver->driver.name);
1196 res = driver->detach_adapter(adapter);
1198 dev_err(&adapter->dev, "detach_adapter failed (%d) "
1199 "for driver [%s]\n", res, driver->driver.name);
1203 static int __unregister_client(struct device *dev, void *dummy)
1205 struct i2c_client *client = i2c_verify_client(dev);
1206 if (client && strcmp(client->name, "dummy"))
1207 i2c_unregister_device(client);
1211 static int __unregister_dummy(struct device *dev, void *dummy)
1213 struct i2c_client *client = i2c_verify_client(dev);
1215 i2c_unregister_device(client);
1219 static int __process_removed_adapter(struct device_driver *d, void *data)
1221 return i2c_do_del_adapter(to_i2c_driver(d), data);
1225 * i2c_del_adapter - unregister I2C adapter
1226 * @adap: the adapter being unregistered
1227 * Context: can sleep
1229 * This unregisters an I2C adapter which was previously registered
1230 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1232 int i2c_del_adapter(struct i2c_adapter *adap)
1235 struct i2c_adapter *found;
1236 struct i2c_client *client, *next;
1238 /* First make sure that this adapter was ever added */
1239 mutex_lock(&core_lock);
1240 found = idr_find(&i2c_adapter_idr, adap->nr);
1241 mutex_unlock(&core_lock);
1242 if (found != adap) {
1243 pr_debug("i2c-core: attempting to delete unregistered "
1244 "adapter [%s]\n", adap->name);
1248 /* Tell drivers about this removal */
1249 mutex_lock(&core_lock);
1250 res = bus_for_each_drv(&i2c_bus_type, NULL, adap,
1251 __process_removed_adapter);
1252 mutex_unlock(&core_lock);
1256 /* Remove devices instantiated from sysfs */
1257 mutex_lock_nested(&adap->userspace_clients_lock,
1258 i2c_adapter_depth(adap));
1259 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1261 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1263 list_del(&client->detected);
1264 i2c_unregister_device(client);
1266 mutex_unlock(&adap->userspace_clients_lock);
1268 /* Detach any active clients. This can't fail, thus we do not
1269 * check the returned value. This is a two-pass process, because
1270 * we can't remove the dummy devices during the first pass: they
1271 * could have been instantiated by real devices wishing to clean
1272 * them up properly, so we give them a chance to do that first. */
1273 res = device_for_each_child(&adap->dev, NULL, __unregister_client);
1274 res = device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1276 #ifdef CONFIG_I2C_COMPAT
1277 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1281 /* device name is gone after device_unregister */
1282 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1284 /* clean up the sysfs representation */
1285 init_completion(&adap->dev_released);
1286 device_unregister(&adap->dev);
1288 /* wait for sysfs to drop all references */
1289 wait_for_completion(&adap->dev_released);
1292 mutex_lock(&core_lock);
1293 idr_remove(&i2c_adapter_idr, adap->nr);
1294 mutex_unlock(&core_lock);
1296 /* Clear the device structure in case this adapter is ever going to be
1298 memset(&adap->dev, 0, sizeof(adap->dev));
1302 EXPORT_SYMBOL(i2c_del_adapter);
1305 /* ------------------------------------------------------------------------- */
1307 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1311 mutex_lock(&core_lock);
1312 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1313 mutex_unlock(&core_lock);
1317 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1319 static int __process_new_driver(struct device *dev, void *data)
1321 if (dev->type != &i2c_adapter_type)
1323 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1327 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1328 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1331 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1335 /* Can't register until after driver model init */
1336 if (unlikely(WARN_ON(!i2c_bus_type.p)))
1339 /* add the driver to the list of i2c drivers in the driver core */
1340 driver->driver.owner = owner;
1341 driver->driver.bus = &i2c_bus_type;
1343 /* When registration returns, the driver core
1344 * will have called probe() for all matching-but-unbound devices.
1346 res = driver_register(&driver->driver);
1350 /* Drivers should switch to dev_pm_ops instead. */
1351 if (driver->suspend)
1352 pr_warn("i2c-core: driver [%s] using legacy suspend method\n",
1353 driver->driver.name);
1355 pr_warn("i2c-core: driver [%s] using legacy resume method\n",
1356 driver->driver.name);
1358 pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
1360 INIT_LIST_HEAD(&driver->clients);
1361 /* Walk the adapters that are already present */
1362 i2c_for_each_dev(driver, __process_new_driver);
1366 EXPORT_SYMBOL(i2c_register_driver);
1368 static int __process_removed_driver(struct device *dev, void *data)
1370 if (dev->type != &i2c_adapter_type)
1372 return i2c_do_del_adapter(data, to_i2c_adapter(dev));
1376 * i2c_del_driver - unregister I2C driver
1377 * @driver: the driver being unregistered
1378 * Context: can sleep
1380 void i2c_del_driver(struct i2c_driver *driver)
1382 i2c_for_each_dev(driver, __process_removed_driver);
1384 driver_unregister(&driver->driver);
1385 pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
1387 EXPORT_SYMBOL(i2c_del_driver);
1389 /* ------------------------------------------------------------------------- */
1392 * i2c_use_client - increments the reference count of the i2c client structure
1393 * @client: the client being referenced
1395 * Each live reference to a client should be refcounted. The driver model does
1396 * that automatically as part of driver binding, so that most drivers don't
1397 * need to do this explicitly: they hold a reference until they're unbound
1400 * A pointer to the client with the incremented reference counter is returned.
1402 struct i2c_client *i2c_use_client(struct i2c_client *client)
1404 if (client && get_device(&client->dev))
1408 EXPORT_SYMBOL(i2c_use_client);
1411 * i2c_release_client - release a use of the i2c client structure
1412 * @client: the client being no longer referenced
1414 * Must be called when a user of a client is finished with it.
1416 void i2c_release_client(struct i2c_client *client)
1419 put_device(&client->dev);
1421 EXPORT_SYMBOL(i2c_release_client);
1423 struct i2c_cmd_arg {
1428 static int i2c_cmd(struct device *dev, void *_arg)
1430 struct i2c_client *client = i2c_verify_client(dev);
1431 struct i2c_cmd_arg *arg = _arg;
1433 if (client && client->driver && client->driver->command)
1434 client->driver->command(client, arg->cmd, arg->arg);
1438 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1440 struct i2c_cmd_arg cmd_arg;
1444 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1446 EXPORT_SYMBOL(i2c_clients_command);
1448 static int __init i2c_init(void)
1452 retval = bus_register(&i2c_bus_type);
1455 #ifdef CONFIG_I2C_COMPAT
1456 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1457 if (!i2c_adapter_compat_class) {
1462 retval = i2c_add_driver(&dummy_driver);
1468 #ifdef CONFIG_I2C_COMPAT
1469 class_compat_unregister(i2c_adapter_compat_class);
1472 bus_unregister(&i2c_bus_type);
1476 static void __exit i2c_exit(void)
1478 i2c_del_driver(&dummy_driver);
1479 #ifdef CONFIG_I2C_COMPAT
1480 class_compat_unregister(i2c_adapter_compat_class);
1482 bus_unregister(&i2c_bus_type);
1485 /* We must initialize early, because some subsystems register i2c drivers
1486 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1488 postcore_initcall(i2c_init);
1489 module_exit(i2c_exit);
1491 /* ----------------------------------------------------
1492 * the functional interface to the i2c busses.
1493 * ----------------------------------------------------
1497 * __i2c_transfer - unlocked flavor of i2c_transfer
1498 * @adap: Handle to I2C bus
1499 * @msgs: One or more messages to execute before STOP is issued to
1500 * terminate the operation; each message begins with a START.
1501 * @num: Number of messages to be executed.
1503 * Returns negative errno, else the number of messages executed.
1505 * Adapter lock must be held when calling this function. No debug logging
1506 * takes place. adap->algo->master_xfer existence isn't checked.
1508 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1510 unsigned long orig_jiffies;
1513 /* Retry automatically on arbitration loss */
1514 orig_jiffies = jiffies;
1515 for (ret = 0, try = 0; try <= adap->retries; try++) {
1516 ret = adap->algo->master_xfer(adap, msgs, num);
1519 if (time_after(jiffies, orig_jiffies + adap->timeout))
1525 EXPORT_SYMBOL(__i2c_transfer);
1528 * i2c_transfer - execute a single or combined I2C message
1529 * @adap: Handle to I2C bus
1530 * @msgs: One or more messages to execute before STOP is issued to
1531 * terminate the operation; each message begins with a START.
1532 * @num: Number of messages to be executed.
1534 * Returns negative errno, else the number of messages executed.
1536 * Note that there is no requirement that each message be sent to
1537 * the same slave address, although that is the most common model.
1539 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1543 /* REVISIT the fault reporting model here is weak:
1545 * - When we get an error after receiving N bytes from a slave,
1546 * there is no way to report "N".
1548 * - When we get a NAK after transmitting N bytes to a slave,
1549 * there is no way to report "N" ... or to let the master
1550 * continue executing the rest of this combined message, if
1551 * that's the appropriate response.
1553 * - When for example "num" is two and we successfully complete
1554 * the first message but get an error part way through the
1555 * second, it's unclear whether that should be reported as
1556 * one (discarding status on the second message) or errno
1557 * (discarding status on the first one).
1560 if (adap->algo->master_xfer) {
1562 for (ret = 0; ret < num; ret++) {
1563 dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
1564 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
1565 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
1566 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
1570 if (in_atomic() || irqs_disabled()) {
1571 ret = i2c_trylock_adapter(adap);
1573 /* I2C activity is ongoing. */
1576 i2c_lock_adapter(adap);
1579 ret = __i2c_transfer(adap, msgs, num);
1580 i2c_unlock_adapter(adap);
1584 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
1588 EXPORT_SYMBOL(i2c_transfer);
1591 * i2c_master_send - issue a single I2C message in master transmit mode
1592 * @client: Handle to slave device
1593 * @buf: Data that will be written to the slave
1594 * @count: How many bytes to write, must be less than 64k since msg.len is u16
1596 * Returns negative errno, or else the number of bytes written.
1598 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
1601 struct i2c_adapter *adap = client->adapter;
1604 msg.addr = client->addr;
1605 msg.flags = client->flags & I2C_M_TEN;
1607 msg.buf = (char *)buf;
1609 ret = i2c_transfer(adap, &msg, 1);
1612 * If everything went ok (i.e. 1 msg transmitted), return #bytes
1613 * transmitted, else error code.
1615 return (ret == 1) ? count : ret;
1617 EXPORT_SYMBOL(i2c_master_send);
1620 * i2c_master_recv - issue a single I2C message in master receive mode
1621 * @client: Handle to slave device
1622 * @buf: Where to store data read from slave
1623 * @count: How many bytes to read, must be less than 64k since msg.len is u16
1625 * Returns negative errno, or else the number of bytes read.
1627 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
1629 struct i2c_adapter *adap = client->adapter;
1633 msg.addr = client->addr;
1634 msg.flags = client->flags & I2C_M_TEN;
1635 msg.flags |= I2C_M_RD;
1639 ret = i2c_transfer(adap, &msg, 1);
1642 * If everything went ok (i.e. 1 msg received), return #bytes received,
1645 return (ret == 1) ? count : ret;
1647 EXPORT_SYMBOL(i2c_master_recv);
1649 /* ----------------------------------------------------
1650 * the i2c address scanning function
1651 * Will not work for 10-bit addresses!
1652 * ----------------------------------------------------
1656 * Legacy default probe function, mostly relevant for SMBus. The default
1657 * probe method is a quick write, but it is known to corrupt the 24RF08
1658 * EEPROMs due to a state machine bug, and could also irreversibly
1659 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
1660 * we use a short byte read instead. Also, some bus drivers don't implement
1661 * quick write, so we fallback to a byte read in that case too.
1662 * On x86, there is another special case for FSC hardware monitoring chips,
1663 * which want regular byte reads (address 0x73.) Fortunately, these are the
1664 * only known chips using this I2C address on PC hardware.
1665 * Returns 1 if probe succeeded, 0 if not.
1667 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
1670 union i2c_smbus_data dummy;
1673 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
1674 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
1675 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1676 I2C_SMBUS_BYTE_DATA, &dummy);
1679 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
1680 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
1681 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
1682 I2C_SMBUS_QUICK, NULL);
1683 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
1684 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1685 I2C_SMBUS_BYTE, &dummy);
1687 dev_warn(&adap->dev, "No suitable probing method supported\n");
1694 static int i2c_detect_address(struct i2c_client *temp_client,
1695 struct i2c_driver *driver)
1697 struct i2c_board_info info;
1698 struct i2c_adapter *adapter = temp_client->adapter;
1699 int addr = temp_client->addr;
1702 /* Make sure the address is valid */
1703 err = i2c_check_addr_validity(addr);
1705 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
1710 /* Skip if already in use */
1711 if (i2c_check_addr_busy(adapter, addr))
1714 /* Make sure there is something at this address */
1715 if (!i2c_default_probe(adapter, addr))
1718 /* Finally call the custom detection function */
1719 memset(&info, 0, sizeof(struct i2c_board_info));
1721 err = driver->detect(temp_client, &info);
1723 /* -ENODEV is returned if the detection fails. We catch it
1724 here as this isn't an error. */
1725 return err == -ENODEV ? 0 : err;
1728 /* Consistency check */
1729 if (info.type[0] == '\0') {
1730 dev_err(&adapter->dev, "%s detection function provided "
1731 "no name for 0x%x\n", driver->driver.name,
1734 struct i2c_client *client;
1736 /* Detection succeeded, instantiate the device */
1737 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
1738 info.type, info.addr);
1739 client = i2c_new_device(adapter, &info);
1741 list_add_tail(&client->detected, &driver->clients);
1743 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
1744 info.type, info.addr);
1749 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
1751 const unsigned short *address_list;
1752 struct i2c_client *temp_client;
1754 int adap_id = i2c_adapter_id(adapter);
1756 address_list = driver->address_list;
1757 if (!driver->detect || !address_list)
1760 /* Stop here if the classes do not match */
1761 if (!(adapter->class & driver->class))
1764 /* Set up a temporary client to help detect callback */
1765 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
1768 temp_client->adapter = adapter;
1770 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
1771 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
1772 "addr 0x%02x\n", adap_id, address_list[i]);
1773 temp_client->addr = address_list[i];
1774 err = i2c_detect_address(temp_client, driver);
1783 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
1785 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1786 I2C_SMBUS_QUICK, NULL) >= 0;
1788 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
1791 i2c_new_probed_device(struct i2c_adapter *adap,
1792 struct i2c_board_info *info,
1793 unsigned short const *addr_list,
1794 int (*probe)(struct i2c_adapter *, unsigned short addr))
1799 probe = i2c_default_probe;
1801 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
1802 /* Check address validity */
1803 if (i2c_check_addr_validity(addr_list[i]) < 0) {
1804 dev_warn(&adap->dev, "Invalid 7-bit address "
1805 "0x%02x\n", addr_list[i]);
1809 /* Check address availability */
1810 if (i2c_check_addr_busy(adap, addr_list[i])) {
1811 dev_dbg(&adap->dev, "Address 0x%02x already in "
1812 "use, not probing\n", addr_list[i]);
1816 /* Test address responsiveness */
1817 if (probe(adap, addr_list[i]))
1821 if (addr_list[i] == I2C_CLIENT_END) {
1822 dev_dbg(&adap->dev, "Probing failed, no device found\n");
1826 info->addr = addr_list[i];
1827 return i2c_new_device(adap, info);
1829 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
1831 struct i2c_adapter *i2c_get_adapter(int nr)
1833 struct i2c_adapter *adapter;
1835 mutex_lock(&core_lock);
1836 adapter = idr_find(&i2c_adapter_idr, nr);
1837 if (adapter && !try_module_get(adapter->owner))
1840 mutex_unlock(&core_lock);
1843 EXPORT_SYMBOL(i2c_get_adapter);
1845 void i2c_put_adapter(struct i2c_adapter *adap)
1847 module_put(adap->owner);
1849 EXPORT_SYMBOL(i2c_put_adapter);
1851 /* The SMBus parts */
1853 #define POLY (0x1070U << 3)
1854 static u8 crc8(u16 data)
1858 for (i = 0; i < 8; i++) {
1863 return (u8)(data >> 8);
1866 /* Incremental CRC8 over count bytes in the array pointed to by p */
1867 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
1871 for (i = 0; i < count; i++)
1872 crc = crc8((crc ^ p[i]) << 8);
1876 /* Assume a 7-bit address, which is reasonable for SMBus */
1877 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
1879 /* The address will be sent first */
1880 u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
1881 pec = i2c_smbus_pec(pec, &addr, 1);
1883 /* The data buffer follows */
1884 return i2c_smbus_pec(pec, msg->buf, msg->len);
1887 /* Used for write only transactions */
1888 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
1890 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
1894 /* Return <0 on CRC error
1895 If there was a write before this read (most cases) we need to take the
1896 partial CRC from the write part into account.
1897 Note that this function does modify the message (we need to decrease the
1898 message length to hide the CRC byte from the caller). */
1899 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
1901 u8 rpec = msg->buf[--msg->len];
1902 cpec = i2c_smbus_msg_pec(cpec, msg);
1905 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
1913 * i2c_smbus_read_byte - SMBus "receive byte" protocol
1914 * @client: Handle to slave device
1916 * This executes the SMBus "receive byte" protocol, returning negative errno
1917 * else the byte received from the device.
1919 s32 i2c_smbus_read_byte(const struct i2c_client *client)
1921 union i2c_smbus_data data;
1924 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1926 I2C_SMBUS_BYTE, &data);
1927 return (status < 0) ? status : data.byte;
1929 EXPORT_SYMBOL(i2c_smbus_read_byte);
1932 * i2c_smbus_write_byte - SMBus "send byte" protocol
1933 * @client: Handle to slave device
1934 * @value: Byte to be sent
1936 * This executes the SMBus "send byte" protocol, returning negative errno
1937 * else zero on success.
1939 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
1941 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1942 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
1944 EXPORT_SYMBOL(i2c_smbus_write_byte);
1947 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
1948 * @client: Handle to slave device
1949 * @command: Byte interpreted by slave
1951 * This executes the SMBus "read byte" protocol, returning negative errno
1952 * else a data byte received from the device.
1954 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
1956 union i2c_smbus_data data;
1959 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1960 I2C_SMBUS_READ, command,
1961 I2C_SMBUS_BYTE_DATA, &data);
1962 return (status < 0) ? status : data.byte;
1964 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
1967 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
1968 * @client: Handle to slave device
1969 * @command: Byte interpreted by slave
1970 * @value: Byte being written
1972 * This executes the SMBus "write byte" protocol, returning negative errno
1973 * else zero on success.
1975 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
1978 union i2c_smbus_data data;
1980 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1981 I2C_SMBUS_WRITE, command,
1982 I2C_SMBUS_BYTE_DATA, &data);
1984 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
1987 * i2c_smbus_read_word_data - SMBus "read word" protocol
1988 * @client: Handle to slave device
1989 * @command: Byte interpreted by slave
1991 * This executes the SMBus "read word" protocol, returning negative errno
1992 * else a 16-bit unsigned "word" received from the device.
1994 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
1996 union i2c_smbus_data data;
1999 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2000 I2C_SMBUS_READ, command,
2001 I2C_SMBUS_WORD_DATA, &data);
2002 return (status < 0) ? status : data.word;
2004 EXPORT_SYMBOL(i2c_smbus_read_word_data);
2007 * i2c_smbus_write_word_data - SMBus "write word" protocol
2008 * @client: Handle to slave device
2009 * @command: Byte interpreted by slave
2010 * @value: 16-bit "word" being written
2012 * This executes the SMBus "write word" protocol, returning negative errno
2013 * else zero on success.
2015 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2018 union i2c_smbus_data data;
2020 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2021 I2C_SMBUS_WRITE, command,
2022 I2C_SMBUS_WORD_DATA, &data);
2024 EXPORT_SYMBOL(i2c_smbus_write_word_data);
2027 * i2c_smbus_read_block_data - SMBus "block read" protocol
2028 * @client: Handle to slave device
2029 * @command: Byte interpreted by slave
2030 * @values: Byte array into which data will be read; big enough to hold
2031 * the data returned by the slave. SMBus allows at most 32 bytes.
2033 * This executes the SMBus "block read" protocol, returning negative errno
2034 * else the number of data bytes in the slave's response.
2036 * Note that using this function requires that the client's adapter support
2037 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
2038 * support this; its emulation through I2C messaging relies on a specific
2039 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2041 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2044 union i2c_smbus_data data;
2047 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2048 I2C_SMBUS_READ, command,
2049 I2C_SMBUS_BLOCK_DATA, &data);
2053 memcpy(values, &data.block[1], data.block[0]);
2054 return data.block[0];
2056 EXPORT_SYMBOL(i2c_smbus_read_block_data);
2059 * i2c_smbus_write_block_data - SMBus "block write" protocol
2060 * @client: Handle to slave device
2061 * @command: Byte interpreted by slave
2062 * @length: Size of data block; SMBus allows at most 32 bytes
2063 * @values: Byte array which will be written.
2065 * This executes the SMBus "block write" protocol, returning negative errno
2066 * else zero on success.
2068 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2069 u8 length, const u8 *values)
2071 union i2c_smbus_data data;
2073 if (length > I2C_SMBUS_BLOCK_MAX)
2074 length = I2C_SMBUS_BLOCK_MAX;
2075 data.block[0] = length;
2076 memcpy(&data.block[1], values, length);
2077 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2078 I2C_SMBUS_WRITE, command,
2079 I2C_SMBUS_BLOCK_DATA, &data);
2081 EXPORT_SYMBOL(i2c_smbus_write_block_data);
2083 /* Returns the number of read bytes */
2084 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2085 u8 length, u8 *values)
2087 union i2c_smbus_data data;
2090 if (length > I2C_SMBUS_BLOCK_MAX)
2091 length = I2C_SMBUS_BLOCK_MAX;
2092 data.block[0] = length;
2093 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2094 I2C_SMBUS_READ, command,
2095 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2099 memcpy(values, &data.block[1], data.block[0]);
2100 return data.block[0];
2102 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2104 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2105 u8 length, const u8 *values)
2107 union i2c_smbus_data data;
2109 if (length > I2C_SMBUS_BLOCK_MAX)
2110 length = I2C_SMBUS_BLOCK_MAX;
2111 data.block[0] = length;
2112 memcpy(data.block + 1, values, length);
2113 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2114 I2C_SMBUS_WRITE, command,
2115 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2117 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2119 /* Simulate a SMBus command using the i2c protocol
2120 No checking of parameters is done! */
2121 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2122 unsigned short flags,
2123 char read_write, u8 command, int size,
2124 union i2c_smbus_data *data)
2126 /* So we need to generate a series of msgs. In the case of writing, we
2127 need to use only one message; when reading, we need two. We initialize
2128 most things with sane defaults, to keep the code below somewhat
2130 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2131 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2132 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2136 struct i2c_msg msg[2] = {
2144 .flags = flags | I2C_M_RD,
2150 msgbuf0[0] = command;
2152 case I2C_SMBUS_QUICK:
2154 /* Special case: The read/write field is used as data */
2155 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2159 case I2C_SMBUS_BYTE:
2160 if (read_write == I2C_SMBUS_READ) {
2161 /* Special case: only a read! */
2162 msg[0].flags = I2C_M_RD | flags;
2166 case I2C_SMBUS_BYTE_DATA:
2167 if (read_write == I2C_SMBUS_READ)
2171 msgbuf0[1] = data->byte;
2174 case I2C_SMBUS_WORD_DATA:
2175 if (read_write == I2C_SMBUS_READ)
2179 msgbuf0[1] = data->word & 0xff;
2180 msgbuf0[2] = data->word >> 8;
2183 case I2C_SMBUS_PROC_CALL:
2184 num = 2; /* Special case */
2185 read_write = I2C_SMBUS_READ;
2188 msgbuf0[1] = data->word & 0xff;
2189 msgbuf0[2] = data->word >> 8;
2191 case I2C_SMBUS_BLOCK_DATA:
2192 if (read_write == I2C_SMBUS_READ) {
2193 msg[1].flags |= I2C_M_RECV_LEN;
2194 msg[1].len = 1; /* block length will be added by
2195 the underlying bus driver */
2197 msg[0].len = data->block[0] + 2;
2198 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
2199 dev_err(&adapter->dev,
2200 "Invalid block write size %d\n",
2204 for (i = 1; i < msg[0].len; i++)
2205 msgbuf0[i] = data->block[i-1];
2208 case I2C_SMBUS_BLOCK_PROC_CALL:
2209 num = 2; /* Another special case */
2210 read_write = I2C_SMBUS_READ;
2211 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
2212 dev_err(&adapter->dev,
2213 "Invalid block write size %d\n",
2217 msg[0].len = data->block[0] + 2;
2218 for (i = 1; i < msg[0].len; i++)
2219 msgbuf0[i] = data->block[i-1];
2220 msg[1].flags |= I2C_M_RECV_LEN;
2221 msg[1].len = 1; /* block length will be added by
2222 the underlying bus driver */
2224 case I2C_SMBUS_I2C_BLOCK_DATA:
2225 if (read_write == I2C_SMBUS_READ) {
2226 msg[1].len = data->block[0];
2228 msg[0].len = data->block[0] + 1;
2229 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
2230 dev_err(&adapter->dev,
2231 "Invalid block write size %d\n",
2235 for (i = 1; i <= data->block[0]; i++)
2236 msgbuf0[i] = data->block[i];
2240 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
2244 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
2245 && size != I2C_SMBUS_I2C_BLOCK_DATA);
2247 /* Compute PEC if first message is a write */
2248 if (!(msg[0].flags & I2C_M_RD)) {
2249 if (num == 1) /* Write only */
2250 i2c_smbus_add_pec(&msg[0]);
2251 else /* Write followed by read */
2252 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
2254 /* Ask for PEC if last message is a read */
2255 if (msg[num-1].flags & I2C_M_RD)
2259 status = i2c_transfer(adapter, msg, num);
2263 /* Check PEC if last message is a read */
2264 if (i && (msg[num-1].flags & I2C_M_RD)) {
2265 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
2270 if (read_write == I2C_SMBUS_READ)
2272 case I2C_SMBUS_BYTE:
2273 data->byte = msgbuf0[0];
2275 case I2C_SMBUS_BYTE_DATA:
2276 data->byte = msgbuf1[0];
2278 case I2C_SMBUS_WORD_DATA:
2279 case I2C_SMBUS_PROC_CALL:
2280 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
2282 case I2C_SMBUS_I2C_BLOCK_DATA:
2283 for (i = 0; i < data->block[0]; i++)
2284 data->block[i+1] = msgbuf1[i];
2286 case I2C_SMBUS_BLOCK_DATA:
2287 case I2C_SMBUS_BLOCK_PROC_CALL:
2288 for (i = 0; i < msgbuf1[0] + 1; i++)
2289 data->block[i] = msgbuf1[i];
2296 * i2c_smbus_xfer - execute SMBus protocol operations
2297 * @adapter: Handle to I2C bus
2298 * @addr: Address of SMBus slave on that bus
2299 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
2300 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
2301 * @command: Byte interpreted by slave, for protocols which use such bytes
2302 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
2303 * @data: Data to be read or written
2305 * This executes an SMBus protocol operation, and returns a negative
2306 * errno code else zero on success.
2308 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
2309 char read_write, u8 command, int protocol,
2310 union i2c_smbus_data *data)
2312 unsigned long orig_jiffies;
2316 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
2318 if (adapter->algo->smbus_xfer) {
2319 i2c_lock_adapter(adapter);
2321 /* Retry automatically on arbitration loss */
2322 orig_jiffies = jiffies;
2323 for (res = 0, try = 0; try <= adapter->retries; try++) {
2324 res = adapter->algo->smbus_xfer(adapter, addr, flags,
2325 read_write, command,
2329 if (time_after(jiffies,
2330 orig_jiffies + adapter->timeout))
2333 i2c_unlock_adapter(adapter);
2335 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
2338 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
2339 * implement native support for the SMBus operation.
2343 return i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
2344 command, protocol, data);
2346 EXPORT_SYMBOL(i2c_smbus_xfer);
2348 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2349 MODULE_DESCRIPTION("I2C-Bus main module");
2350 MODULE_LICENSE("GPL");