PM / sleep: Asynchronous threads for suspend_noirq
[linux/fpc-iii.git] / drivers / i2c / i2c-core.c
blob5fb80b8962a2ad7d8e78dcee01df68cb639d3602
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,
18 MA 02110-1301 USA. */
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 <jdelvare@suse.de>
25 Mux support by Rodolfo Giometti <giometti@enneenne.com> and
26 Michael Lawnick <michael.lawnick.ext@nsn.com>
27 OF support is copyright (c) 2008 Jochen Friedrich <jochen@scram.de>
28 (based on a previous patch from Jon Smirl <jonsmirl@gmail.com>) and
29 (c) 2013 Wolfram Sang <wsa@the-dreams.de>
32 #include <linux/module.h>
33 #include <linux/kernel.h>
34 #include <linux/delay.h>
35 #include <linux/errno.h>
36 #include <linux/gpio.h>
37 #include <linux/slab.h>
38 #include <linux/i2c.h>
39 #include <linux/init.h>
40 #include <linux/idr.h>
41 #include <linux/mutex.h>
42 #include <linux/of.h>
43 #include <linux/of_device.h>
44 #include <linux/of_irq.h>
45 #include <linux/completion.h>
46 #include <linux/hardirq.h>
47 #include <linux/irqflags.h>
48 #include <linux/rwsem.h>
49 #include <linux/pm_runtime.h>
50 #include <linux/acpi.h>
51 #include <asm/uaccess.h>
53 #include "i2c-core.h"
56 /* core_lock protects i2c_adapter_idr, and guarantees
57 that device detection, deletion of detected devices, and attach_adapter
58 calls are serialized */
59 static DEFINE_MUTEX(core_lock);
60 static DEFINE_IDR(i2c_adapter_idr);
62 static struct device_type i2c_client_type;
63 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
65 /* ------------------------------------------------------------------------- */
67 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
68 const struct i2c_client *client)
70 while (id->name[0]) {
71 if (strcmp(client->name, id->name) == 0)
72 return id;
73 id++;
75 return NULL;
78 static int i2c_device_match(struct device *dev, struct device_driver *drv)
80 struct i2c_client *client = i2c_verify_client(dev);
81 struct i2c_driver *driver;
83 if (!client)
84 return 0;
86 /* Attempt an OF style match */
87 if (of_driver_match_device(dev, drv))
88 return 1;
90 /* Then ACPI style match */
91 if (acpi_driver_match_device(dev, drv))
92 return 1;
94 driver = to_i2c_driver(drv);
95 /* match on an id table if there is one */
96 if (driver->id_table)
97 return i2c_match_id(driver->id_table, client) != NULL;
99 return 0;
103 /* uevent helps with hotplug: modprobe -q $(MODALIAS) */
104 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
106 struct i2c_client *client = to_i2c_client(dev);
107 int rc;
109 rc = acpi_device_uevent_modalias(dev, env);
110 if (rc != -ENODEV)
111 return rc;
113 if (add_uevent_var(env, "MODALIAS=%s%s",
114 I2C_MODULE_PREFIX, client->name))
115 return -ENOMEM;
116 dev_dbg(dev, "uevent\n");
117 return 0;
120 /* i2c bus recovery routines */
121 static int get_scl_gpio_value(struct i2c_adapter *adap)
123 return gpio_get_value(adap->bus_recovery_info->scl_gpio);
126 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
128 gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
131 static int get_sda_gpio_value(struct i2c_adapter *adap)
133 return gpio_get_value(adap->bus_recovery_info->sda_gpio);
136 static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
138 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
139 struct device *dev = &adap->dev;
140 int ret = 0;
142 ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
143 GPIOF_OUT_INIT_HIGH, "i2c-scl");
144 if (ret) {
145 dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
146 return ret;
149 if (bri->get_sda) {
150 if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
151 /* work without SDA polling */
152 dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
153 bri->sda_gpio);
154 bri->get_sda = NULL;
158 return ret;
161 static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
163 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
165 if (bri->get_sda)
166 gpio_free(bri->sda_gpio);
168 gpio_free(bri->scl_gpio);
172 * We are generating clock pulses. ndelay() determines durating of clk pulses.
173 * We will generate clock with rate 100 KHz and so duration of both clock levels
174 * is: delay in ns = (10^6 / 100) / 2
176 #define RECOVERY_NDELAY 5000
177 #define RECOVERY_CLK_CNT 9
179 static int i2c_generic_recovery(struct i2c_adapter *adap)
181 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
182 int i = 0, val = 1, ret = 0;
184 if (bri->prepare_recovery)
185 bri->prepare_recovery(bri);
188 * By this time SCL is high, as we need to give 9 falling-rising edges
190 while (i++ < RECOVERY_CLK_CNT * 2) {
191 if (val) {
192 /* Break if SDA is high */
193 if (bri->get_sda && bri->get_sda(adap))
194 break;
195 /* SCL shouldn't be low here */
196 if (!bri->get_scl(adap)) {
197 dev_err(&adap->dev,
198 "SCL is stuck low, exit recovery\n");
199 ret = -EBUSY;
200 break;
204 val = !val;
205 bri->set_scl(adap, val);
206 ndelay(RECOVERY_NDELAY);
209 if (bri->unprepare_recovery)
210 bri->unprepare_recovery(bri);
212 return ret;
215 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
217 adap->bus_recovery_info->set_scl(adap, 1);
218 return i2c_generic_recovery(adap);
221 int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
223 int ret;
225 ret = i2c_get_gpios_for_recovery(adap);
226 if (ret)
227 return ret;
229 ret = i2c_generic_recovery(adap);
230 i2c_put_gpios_for_recovery(adap);
232 return ret;
235 int i2c_recover_bus(struct i2c_adapter *adap)
237 if (!adap->bus_recovery_info)
238 return -EOPNOTSUPP;
240 dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
241 return adap->bus_recovery_info->recover_bus(adap);
244 static int i2c_device_probe(struct device *dev)
246 struct i2c_client *client = i2c_verify_client(dev);
247 struct i2c_driver *driver;
248 int status;
250 if (!client)
251 return 0;
253 driver = to_i2c_driver(dev->driver);
254 if (!driver->probe || !driver->id_table)
255 return -ENODEV;
257 if (!device_can_wakeup(&client->dev))
258 device_init_wakeup(&client->dev,
259 client->flags & I2C_CLIENT_WAKE);
260 dev_dbg(dev, "probe\n");
262 acpi_dev_pm_attach(&client->dev, true);
263 status = driver->probe(client, i2c_match_id(driver->id_table, client));
264 if (status)
265 acpi_dev_pm_detach(&client->dev, true);
267 return status;
270 static int i2c_device_remove(struct device *dev)
272 struct i2c_client *client = i2c_verify_client(dev);
273 struct i2c_driver *driver;
274 int status = 0;
276 if (!client || !dev->driver)
277 return 0;
279 driver = to_i2c_driver(dev->driver);
280 if (driver->remove) {
281 dev_dbg(dev, "remove\n");
282 status = driver->remove(client);
285 acpi_dev_pm_detach(&client->dev, true);
286 return status;
289 static void i2c_device_shutdown(struct device *dev)
291 struct i2c_client *client = i2c_verify_client(dev);
292 struct i2c_driver *driver;
294 if (!client || !dev->driver)
295 return;
296 driver = to_i2c_driver(dev->driver);
297 if (driver->shutdown)
298 driver->shutdown(client);
301 #ifdef CONFIG_PM_SLEEP
302 static int i2c_legacy_suspend(struct device *dev, pm_message_t mesg)
304 struct i2c_client *client = i2c_verify_client(dev);
305 struct i2c_driver *driver;
307 if (!client || !dev->driver)
308 return 0;
309 driver = to_i2c_driver(dev->driver);
310 if (!driver->suspend)
311 return 0;
312 return driver->suspend(client, mesg);
315 static int i2c_legacy_resume(struct device *dev)
317 struct i2c_client *client = i2c_verify_client(dev);
318 struct i2c_driver *driver;
320 if (!client || !dev->driver)
321 return 0;
322 driver = to_i2c_driver(dev->driver);
323 if (!driver->resume)
324 return 0;
325 return driver->resume(client);
328 static int i2c_device_pm_suspend(struct device *dev)
330 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
332 if (pm)
333 return pm_generic_suspend(dev);
334 else
335 return i2c_legacy_suspend(dev, PMSG_SUSPEND);
338 static int i2c_device_pm_resume(struct device *dev)
340 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
342 if (pm)
343 return pm_generic_resume(dev);
344 else
345 return i2c_legacy_resume(dev);
348 static int i2c_device_pm_freeze(struct device *dev)
350 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
352 if (pm)
353 return pm_generic_freeze(dev);
354 else
355 return i2c_legacy_suspend(dev, PMSG_FREEZE);
358 static int i2c_device_pm_thaw(struct device *dev)
360 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
362 if (pm)
363 return pm_generic_thaw(dev);
364 else
365 return i2c_legacy_resume(dev);
368 static int i2c_device_pm_poweroff(struct device *dev)
370 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
372 if (pm)
373 return pm_generic_poweroff(dev);
374 else
375 return i2c_legacy_suspend(dev, PMSG_HIBERNATE);
378 static int i2c_device_pm_restore(struct device *dev)
380 const struct dev_pm_ops *pm = dev->driver ? dev->driver->pm : NULL;
382 if (pm)
383 return pm_generic_restore(dev);
384 else
385 return i2c_legacy_resume(dev);
387 #else /* !CONFIG_PM_SLEEP */
388 #define i2c_device_pm_suspend NULL
389 #define i2c_device_pm_resume NULL
390 #define i2c_device_pm_freeze NULL
391 #define i2c_device_pm_thaw NULL
392 #define i2c_device_pm_poweroff NULL
393 #define i2c_device_pm_restore NULL
394 #endif /* !CONFIG_PM_SLEEP */
396 static void i2c_client_dev_release(struct device *dev)
398 kfree(to_i2c_client(dev));
401 static ssize_t
402 show_name(struct device *dev, struct device_attribute *attr, char *buf)
404 return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
405 to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
408 static ssize_t
409 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
411 struct i2c_client *client = to_i2c_client(dev);
412 int len;
414 len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
415 if (len != -ENODEV)
416 return len;
418 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
421 static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
422 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
424 static struct attribute *i2c_dev_attrs[] = {
425 &dev_attr_name.attr,
426 /* modalias helps coldplug: modprobe $(cat .../modalias) */
427 &dev_attr_modalias.attr,
428 NULL
431 static struct attribute_group i2c_dev_attr_group = {
432 .attrs = i2c_dev_attrs,
435 static const struct attribute_group *i2c_dev_attr_groups[] = {
436 &i2c_dev_attr_group,
437 NULL
440 static const struct dev_pm_ops i2c_device_pm_ops = {
441 .suspend = i2c_device_pm_suspend,
442 .resume = i2c_device_pm_resume,
443 .freeze = i2c_device_pm_freeze,
444 .thaw = i2c_device_pm_thaw,
445 .poweroff = i2c_device_pm_poweroff,
446 .restore = i2c_device_pm_restore,
447 SET_RUNTIME_PM_OPS(
448 pm_generic_runtime_suspend,
449 pm_generic_runtime_resume,
450 NULL
454 struct bus_type i2c_bus_type = {
455 .name = "i2c",
456 .match = i2c_device_match,
457 .probe = i2c_device_probe,
458 .remove = i2c_device_remove,
459 .shutdown = i2c_device_shutdown,
460 .pm = &i2c_device_pm_ops,
462 EXPORT_SYMBOL_GPL(i2c_bus_type);
464 static struct device_type i2c_client_type = {
465 .groups = i2c_dev_attr_groups,
466 .uevent = i2c_device_uevent,
467 .release = i2c_client_dev_release,
472 * i2c_verify_client - return parameter as i2c_client, or NULL
473 * @dev: device, probably from some driver model iterator
475 * When traversing the driver model tree, perhaps using driver model
476 * iterators like @device_for_each_child(), you can't assume very much
477 * about the nodes you find. Use this function to avoid oopses caused
478 * by wrongly treating some non-I2C device as an i2c_client.
480 struct i2c_client *i2c_verify_client(struct device *dev)
482 return (dev->type == &i2c_client_type)
483 ? to_i2c_client(dev)
484 : NULL;
486 EXPORT_SYMBOL(i2c_verify_client);
489 /* This is a permissive address validity check, I2C address map constraints
490 * are purposely not enforced, except for the general call address. */
491 static int i2c_check_client_addr_validity(const struct i2c_client *client)
493 if (client->flags & I2C_CLIENT_TEN) {
494 /* 10-bit address, all values are valid */
495 if (client->addr > 0x3ff)
496 return -EINVAL;
497 } else {
498 /* 7-bit address, reject the general call address */
499 if (client->addr == 0x00 || client->addr > 0x7f)
500 return -EINVAL;
502 return 0;
505 /* And this is a strict address validity check, used when probing. If a
506 * device uses a reserved address, then it shouldn't be probed. 7-bit
507 * addressing is assumed, 10-bit address devices are rare and should be
508 * explicitly enumerated. */
509 static int i2c_check_addr_validity(unsigned short addr)
512 * Reserved addresses per I2C specification:
513 * 0x00 General call address / START byte
514 * 0x01 CBUS address
515 * 0x02 Reserved for different bus format
516 * 0x03 Reserved for future purposes
517 * 0x04-0x07 Hs-mode master code
518 * 0x78-0x7b 10-bit slave addressing
519 * 0x7c-0x7f Reserved for future purposes
521 if (addr < 0x08 || addr > 0x77)
522 return -EINVAL;
523 return 0;
526 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
528 struct i2c_client *client = i2c_verify_client(dev);
529 int addr = *(int *)addrp;
531 if (client && client->addr == addr)
532 return -EBUSY;
533 return 0;
536 /* walk up mux tree */
537 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
539 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
540 int result;
542 result = device_for_each_child(&adapter->dev, &addr,
543 __i2c_check_addr_busy);
545 if (!result && parent)
546 result = i2c_check_mux_parents(parent, addr);
548 return result;
551 /* recurse down mux tree */
552 static int i2c_check_mux_children(struct device *dev, void *addrp)
554 int result;
556 if (dev->type == &i2c_adapter_type)
557 result = device_for_each_child(dev, addrp,
558 i2c_check_mux_children);
559 else
560 result = __i2c_check_addr_busy(dev, addrp);
562 return result;
565 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
567 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
568 int result = 0;
570 if (parent)
571 result = i2c_check_mux_parents(parent, addr);
573 if (!result)
574 result = device_for_each_child(&adapter->dev, &addr,
575 i2c_check_mux_children);
577 return result;
581 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
582 * @adapter: Target I2C bus segment
584 void i2c_lock_adapter(struct i2c_adapter *adapter)
586 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
588 if (parent)
589 i2c_lock_adapter(parent);
590 else
591 rt_mutex_lock(&adapter->bus_lock);
593 EXPORT_SYMBOL_GPL(i2c_lock_adapter);
596 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
597 * @adapter: Target I2C bus segment
599 static int i2c_trylock_adapter(struct i2c_adapter *adapter)
601 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
603 if (parent)
604 return i2c_trylock_adapter(parent);
605 else
606 return rt_mutex_trylock(&adapter->bus_lock);
610 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
611 * @adapter: Target I2C bus segment
613 void i2c_unlock_adapter(struct i2c_adapter *adapter)
615 struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
617 if (parent)
618 i2c_unlock_adapter(parent);
619 else
620 rt_mutex_unlock(&adapter->bus_lock);
622 EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
624 static void i2c_dev_set_name(struct i2c_adapter *adap,
625 struct i2c_client *client)
627 struct acpi_device *adev = ACPI_COMPANION(&client->dev);
629 if (adev) {
630 dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
631 return;
634 /* For 10-bit clients, add an arbitrary offset to avoid collisions */
635 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
636 client->addr | ((client->flags & I2C_CLIENT_TEN)
637 ? 0xa000 : 0));
641 * i2c_new_device - instantiate an i2c device
642 * @adap: the adapter managing the device
643 * @info: describes one I2C device; bus_num is ignored
644 * Context: can sleep
646 * Create an i2c device. Binding is handled through driver model
647 * probe()/remove() methods. A driver may be bound to this device when we
648 * return from this function, or any later moment (e.g. maybe hotplugging will
649 * load the driver module). This call is not appropriate for use by mainboard
650 * initialization logic, which usually runs during an arch_initcall() long
651 * before any i2c_adapter could exist.
653 * This returns the new i2c client, which may be saved for later use with
654 * i2c_unregister_device(); or NULL to indicate an error.
656 struct i2c_client *
657 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
659 struct i2c_client *client;
660 int status;
662 client = kzalloc(sizeof *client, GFP_KERNEL);
663 if (!client)
664 return NULL;
666 client->adapter = adap;
668 client->dev.platform_data = info->platform_data;
670 if (info->archdata)
671 client->dev.archdata = *info->archdata;
673 client->flags = info->flags;
674 client->addr = info->addr;
675 client->irq = info->irq;
677 strlcpy(client->name, info->type, sizeof(client->name));
679 /* Check for address validity */
680 status = i2c_check_client_addr_validity(client);
681 if (status) {
682 dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
683 client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
684 goto out_err_silent;
687 /* Check for address business */
688 status = i2c_check_addr_busy(adap, client->addr);
689 if (status)
690 goto out_err;
692 client->dev.parent = &client->adapter->dev;
693 client->dev.bus = &i2c_bus_type;
694 client->dev.type = &i2c_client_type;
695 client->dev.of_node = info->of_node;
696 ACPI_COMPANION_SET(&client->dev, info->acpi_node.companion);
698 i2c_dev_set_name(adap, client);
699 status = device_register(&client->dev);
700 if (status)
701 goto out_err;
703 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
704 client->name, dev_name(&client->dev));
706 return client;
708 out_err:
709 dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
710 "(%d)\n", client->name, client->addr, status);
711 out_err_silent:
712 kfree(client);
713 return NULL;
715 EXPORT_SYMBOL_GPL(i2c_new_device);
719 * i2c_unregister_device - reverse effect of i2c_new_device()
720 * @client: value returned from i2c_new_device()
721 * Context: can sleep
723 void i2c_unregister_device(struct i2c_client *client)
725 device_unregister(&client->dev);
727 EXPORT_SYMBOL_GPL(i2c_unregister_device);
730 static const struct i2c_device_id dummy_id[] = {
731 { "dummy", 0 },
732 { },
735 static int dummy_probe(struct i2c_client *client,
736 const struct i2c_device_id *id)
738 return 0;
741 static int dummy_remove(struct i2c_client *client)
743 return 0;
746 static struct i2c_driver dummy_driver = {
747 .driver.name = "dummy",
748 .probe = dummy_probe,
749 .remove = dummy_remove,
750 .id_table = dummy_id,
754 * i2c_new_dummy - return a new i2c device bound to a dummy driver
755 * @adapter: the adapter managing the device
756 * @address: seven bit address to be used
757 * Context: can sleep
759 * This returns an I2C client bound to the "dummy" driver, intended for use
760 * with devices that consume multiple addresses. Examples of such chips
761 * include various EEPROMS (like 24c04 and 24c08 models).
763 * These dummy devices have two main uses. First, most I2C and SMBus calls
764 * except i2c_transfer() need a client handle; the dummy will be that handle.
765 * And second, this prevents the specified address from being bound to a
766 * different driver.
768 * This returns the new i2c client, which should be saved for later use with
769 * i2c_unregister_device(); or NULL to indicate an error.
771 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
773 struct i2c_board_info info = {
774 I2C_BOARD_INFO("dummy", address),
777 return i2c_new_device(adapter, &info);
779 EXPORT_SYMBOL_GPL(i2c_new_dummy);
781 /* ------------------------------------------------------------------------- */
783 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
785 static void i2c_adapter_dev_release(struct device *dev)
787 struct i2c_adapter *adap = to_i2c_adapter(dev);
788 complete(&adap->dev_released);
792 * This function is only needed for mutex_lock_nested, so it is never
793 * called unless locking correctness checking is enabled. Thus we
794 * make it inline to avoid a compiler warning. That's what gcc ends up
795 * doing anyway.
797 static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
799 unsigned int depth = 0;
801 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
802 depth++;
804 return depth;
808 * Let users instantiate I2C devices through sysfs. This can be used when
809 * platform initialization code doesn't contain the proper data for
810 * whatever reason. Also useful for drivers that do device detection and
811 * detection fails, either because the device uses an unexpected address,
812 * or this is a compatible device with different ID register values.
814 * Parameter checking may look overzealous, but we really don't want
815 * the user to provide incorrect parameters.
817 static ssize_t
818 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
819 const char *buf, size_t count)
821 struct i2c_adapter *adap = to_i2c_adapter(dev);
822 struct i2c_board_info info;
823 struct i2c_client *client;
824 char *blank, end;
825 int res;
827 memset(&info, 0, sizeof(struct i2c_board_info));
829 blank = strchr(buf, ' ');
830 if (!blank) {
831 dev_err(dev, "%s: Missing parameters\n", "new_device");
832 return -EINVAL;
834 if (blank - buf > I2C_NAME_SIZE - 1) {
835 dev_err(dev, "%s: Invalid device name\n", "new_device");
836 return -EINVAL;
838 memcpy(info.type, buf, blank - buf);
840 /* Parse remaining parameters, reject extra parameters */
841 res = sscanf(++blank, "%hi%c", &info.addr, &end);
842 if (res < 1) {
843 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
844 return -EINVAL;
846 if (res > 1 && end != '\n') {
847 dev_err(dev, "%s: Extra parameters\n", "new_device");
848 return -EINVAL;
851 client = i2c_new_device(adap, &info);
852 if (!client)
853 return -EINVAL;
855 /* Keep track of the added device */
856 mutex_lock(&adap->userspace_clients_lock);
857 list_add_tail(&client->detected, &adap->userspace_clients);
858 mutex_unlock(&adap->userspace_clients_lock);
859 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
860 info.type, info.addr);
862 return count;
866 * And of course let the users delete the devices they instantiated, if
867 * they got it wrong. This interface can only be used to delete devices
868 * instantiated by i2c_sysfs_new_device above. This guarantees that we
869 * don't delete devices to which some kernel code still has references.
871 * Parameter checking may look overzealous, but we really don't want
872 * the user to delete the wrong device.
874 static ssize_t
875 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
876 const char *buf, size_t count)
878 struct i2c_adapter *adap = to_i2c_adapter(dev);
879 struct i2c_client *client, *next;
880 unsigned short addr;
881 char end;
882 int res;
884 /* Parse parameters, reject extra parameters */
885 res = sscanf(buf, "%hi%c", &addr, &end);
886 if (res < 1) {
887 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
888 return -EINVAL;
890 if (res > 1 && end != '\n') {
891 dev_err(dev, "%s: Extra parameters\n", "delete_device");
892 return -EINVAL;
895 /* Make sure the device was added through sysfs */
896 res = -ENOENT;
897 mutex_lock_nested(&adap->userspace_clients_lock,
898 i2c_adapter_depth(adap));
899 list_for_each_entry_safe(client, next, &adap->userspace_clients,
900 detected) {
901 if (client->addr == addr) {
902 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
903 "delete_device", client->name, client->addr);
905 list_del(&client->detected);
906 i2c_unregister_device(client);
907 res = count;
908 break;
911 mutex_unlock(&adap->userspace_clients_lock);
913 if (res < 0)
914 dev_err(dev, "%s: Can't find device in list\n",
915 "delete_device");
916 return res;
919 static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
920 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
921 i2c_sysfs_delete_device);
923 static struct attribute *i2c_adapter_attrs[] = {
924 &dev_attr_name.attr,
925 &dev_attr_new_device.attr,
926 &dev_attr_delete_device.attr,
927 NULL
930 static struct attribute_group i2c_adapter_attr_group = {
931 .attrs = i2c_adapter_attrs,
934 static const struct attribute_group *i2c_adapter_attr_groups[] = {
935 &i2c_adapter_attr_group,
936 NULL
939 struct device_type i2c_adapter_type = {
940 .groups = i2c_adapter_attr_groups,
941 .release = i2c_adapter_dev_release,
943 EXPORT_SYMBOL_GPL(i2c_adapter_type);
946 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
947 * @dev: device, probably from some driver model iterator
949 * When traversing the driver model tree, perhaps using driver model
950 * iterators like @device_for_each_child(), you can't assume very much
951 * about the nodes you find. Use this function to avoid oopses caused
952 * by wrongly treating some non-I2C device as an i2c_adapter.
954 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
956 return (dev->type == &i2c_adapter_type)
957 ? to_i2c_adapter(dev)
958 : NULL;
960 EXPORT_SYMBOL(i2c_verify_adapter);
962 #ifdef CONFIG_I2C_COMPAT
963 static struct class_compat *i2c_adapter_compat_class;
964 #endif
966 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
968 struct i2c_devinfo *devinfo;
970 down_read(&__i2c_board_lock);
971 list_for_each_entry(devinfo, &__i2c_board_list, list) {
972 if (devinfo->busnum == adapter->nr
973 && !i2c_new_device(adapter,
974 &devinfo->board_info))
975 dev_err(&adapter->dev,
976 "Can't create device at 0x%02x\n",
977 devinfo->board_info.addr);
979 up_read(&__i2c_board_lock);
982 /* OF support code */
984 #if IS_ENABLED(CONFIG_OF)
985 static void of_i2c_register_devices(struct i2c_adapter *adap)
987 void *result;
988 struct device_node *node;
990 /* Only register child devices if the adapter has a node pointer set */
991 if (!adap->dev.of_node)
992 return;
994 dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
996 for_each_available_child_of_node(adap->dev.of_node, node) {
997 struct i2c_board_info info = {};
998 struct dev_archdata dev_ad = {};
999 const __be32 *addr;
1000 int len;
1002 dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1004 if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1005 dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1006 node->full_name);
1007 continue;
1010 addr = of_get_property(node, "reg", &len);
1011 if (!addr || (len < sizeof(int))) {
1012 dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1013 node->full_name);
1014 continue;
1017 info.addr = be32_to_cpup(addr);
1018 if (info.addr > (1 << 10) - 1) {
1019 dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1020 info.addr, node->full_name);
1021 continue;
1024 info.irq = irq_of_parse_and_map(node, 0);
1025 info.of_node = of_node_get(node);
1026 info.archdata = &dev_ad;
1028 if (of_get_property(node, "wakeup-source", NULL))
1029 info.flags |= I2C_CLIENT_WAKE;
1031 request_module("%s%s", I2C_MODULE_PREFIX, info.type);
1033 result = i2c_new_device(adap, &info);
1034 if (result == NULL) {
1035 dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1036 node->full_name);
1037 of_node_put(node);
1038 irq_dispose_mapping(info.irq);
1039 continue;
1044 static int of_dev_node_match(struct device *dev, void *data)
1046 return dev->of_node == data;
1049 /* must call put_device() when done with returned i2c_client device */
1050 struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1052 struct device *dev;
1054 dev = bus_find_device(&i2c_bus_type, NULL, node,
1055 of_dev_node_match);
1056 if (!dev)
1057 return NULL;
1059 return i2c_verify_client(dev);
1061 EXPORT_SYMBOL(of_find_i2c_device_by_node);
1063 /* must call put_device() when done with returned i2c_adapter device */
1064 struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1066 struct device *dev;
1068 dev = bus_find_device(&i2c_bus_type, NULL, node,
1069 of_dev_node_match);
1070 if (!dev)
1071 return NULL;
1073 return i2c_verify_adapter(dev);
1075 EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1076 #else
1077 static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1078 #endif /* CONFIG_OF */
1080 /* ACPI support code */
1082 #if IS_ENABLED(CONFIG_ACPI)
1083 static int acpi_i2c_add_resource(struct acpi_resource *ares, void *data)
1085 struct i2c_board_info *info = data;
1087 if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
1088 struct acpi_resource_i2c_serialbus *sb;
1090 sb = &ares->data.i2c_serial_bus;
1091 if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_I2C) {
1092 info->addr = sb->slave_address;
1093 if (sb->access_mode == ACPI_I2C_10BIT_MODE)
1094 info->flags |= I2C_CLIENT_TEN;
1096 } else if (info->irq < 0) {
1097 struct resource r;
1099 if (acpi_dev_resource_interrupt(ares, 0, &r))
1100 info->irq = r.start;
1103 /* Tell the ACPI core to skip this resource */
1104 return 1;
1107 static acpi_status acpi_i2c_add_device(acpi_handle handle, u32 level,
1108 void *data, void **return_value)
1110 struct i2c_adapter *adapter = data;
1111 struct list_head resource_list;
1112 struct i2c_board_info info;
1113 struct acpi_device *adev;
1114 int ret;
1116 if (acpi_bus_get_device(handle, &adev))
1117 return AE_OK;
1118 if (acpi_bus_get_status(adev) || !adev->status.present)
1119 return AE_OK;
1121 memset(&info, 0, sizeof(info));
1122 info.acpi_node.companion = adev;
1123 info.irq = -1;
1125 INIT_LIST_HEAD(&resource_list);
1126 ret = acpi_dev_get_resources(adev, &resource_list,
1127 acpi_i2c_add_resource, &info);
1128 acpi_dev_free_resource_list(&resource_list);
1130 if (ret < 0 || !info.addr)
1131 return AE_OK;
1133 adev->power.flags.ignore_parent = true;
1134 strlcpy(info.type, dev_name(&adev->dev), sizeof(info.type));
1135 if (!i2c_new_device(adapter, &info)) {
1136 adev->power.flags.ignore_parent = false;
1137 dev_err(&adapter->dev,
1138 "failed to add I2C device %s from ACPI\n",
1139 dev_name(&adev->dev));
1142 return AE_OK;
1146 * acpi_i2c_register_devices - enumerate I2C slave devices behind adapter
1147 * @adap: pointer to adapter
1149 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
1150 * namespace. When a device is found it will be added to the Linux device
1151 * model and bound to the corresponding ACPI handle.
1153 static void acpi_i2c_register_devices(struct i2c_adapter *adap)
1155 acpi_handle handle;
1156 acpi_status status;
1158 if (!adap->dev.parent)
1159 return;
1161 handle = ACPI_HANDLE(adap->dev.parent);
1162 if (!handle)
1163 return;
1165 status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
1166 acpi_i2c_add_device, NULL,
1167 adap, NULL);
1168 if (ACPI_FAILURE(status))
1169 dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
1171 #else
1172 static inline void acpi_i2c_register_devices(struct i2c_adapter *adap) {}
1173 #endif /* CONFIG_ACPI */
1175 static int i2c_do_add_adapter(struct i2c_driver *driver,
1176 struct i2c_adapter *adap)
1178 /* Detect supported devices on that bus, and instantiate them */
1179 i2c_detect(adap, driver);
1181 /* Let legacy drivers scan this bus for matching devices */
1182 if (driver->attach_adapter) {
1183 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1184 driver->driver.name);
1185 dev_warn(&adap->dev, "Please use another way to instantiate "
1186 "your i2c_client\n");
1187 /* We ignore the return code; if it fails, too bad */
1188 driver->attach_adapter(adap);
1190 return 0;
1193 static int __process_new_adapter(struct device_driver *d, void *data)
1195 return i2c_do_add_adapter(to_i2c_driver(d), data);
1198 static int i2c_register_adapter(struct i2c_adapter *adap)
1200 int res = 0;
1202 /* Can't register until after driver model init */
1203 if (unlikely(WARN_ON(!i2c_bus_type.p))) {
1204 res = -EAGAIN;
1205 goto out_list;
1208 /* Sanity checks */
1209 if (unlikely(adap->name[0] == '\0')) {
1210 pr_err("i2c-core: Attempt to register an adapter with "
1211 "no name!\n");
1212 return -EINVAL;
1214 if (unlikely(!adap->algo)) {
1215 pr_err("i2c-core: Attempt to register adapter '%s' with "
1216 "no algo!\n", adap->name);
1217 return -EINVAL;
1220 rt_mutex_init(&adap->bus_lock);
1221 mutex_init(&adap->userspace_clients_lock);
1222 INIT_LIST_HEAD(&adap->userspace_clients);
1224 /* Set default timeout to 1 second if not already set */
1225 if (adap->timeout == 0)
1226 adap->timeout = HZ;
1228 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1229 adap->dev.bus = &i2c_bus_type;
1230 adap->dev.type = &i2c_adapter_type;
1231 res = device_register(&adap->dev);
1232 if (res)
1233 goto out_list;
1235 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1237 #ifdef CONFIG_I2C_COMPAT
1238 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1239 adap->dev.parent);
1240 if (res)
1241 dev_warn(&adap->dev,
1242 "Failed to create compatibility class link\n");
1243 #endif
1245 /* bus recovery specific initialization */
1246 if (adap->bus_recovery_info) {
1247 struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
1249 if (!bri->recover_bus) {
1250 dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
1251 adap->bus_recovery_info = NULL;
1252 goto exit_recovery;
1255 /* Generic GPIO recovery */
1256 if (bri->recover_bus == i2c_generic_gpio_recovery) {
1257 if (!gpio_is_valid(bri->scl_gpio)) {
1258 dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
1259 adap->bus_recovery_info = NULL;
1260 goto exit_recovery;
1263 if (gpio_is_valid(bri->sda_gpio))
1264 bri->get_sda = get_sda_gpio_value;
1265 else
1266 bri->get_sda = NULL;
1268 bri->get_scl = get_scl_gpio_value;
1269 bri->set_scl = set_scl_gpio_value;
1270 } else if (!bri->set_scl || !bri->get_scl) {
1271 /* Generic SCL recovery */
1272 dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
1273 adap->bus_recovery_info = NULL;
1277 exit_recovery:
1278 /* create pre-declared device nodes */
1279 of_i2c_register_devices(adap);
1280 acpi_i2c_register_devices(adap);
1282 if (adap->nr < __i2c_first_dynamic_bus_num)
1283 i2c_scan_static_board_info(adap);
1285 /* Notify drivers */
1286 mutex_lock(&core_lock);
1287 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1288 mutex_unlock(&core_lock);
1290 return 0;
1292 out_list:
1293 mutex_lock(&core_lock);
1294 idr_remove(&i2c_adapter_idr, adap->nr);
1295 mutex_unlock(&core_lock);
1296 return res;
1300 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1301 * @adap: the adapter to register (with adap->nr initialized)
1302 * Context: can sleep
1304 * See i2c_add_numbered_adapter() for details.
1306 static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1308 int id;
1310 mutex_lock(&core_lock);
1311 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1,
1312 GFP_KERNEL);
1313 mutex_unlock(&core_lock);
1314 if (id < 0)
1315 return id == -ENOSPC ? -EBUSY : id;
1317 return i2c_register_adapter(adap);
1321 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1322 * @adapter: the adapter to add
1323 * Context: can sleep
1325 * This routine is used to declare an I2C adapter when its bus number
1326 * doesn't matter or when its bus number is specified by an dt alias.
1327 * Examples of bases when the bus number doesn't matter: I2C adapters
1328 * dynamically added by USB links or PCI plugin cards.
1330 * When this returns zero, a new bus number was allocated and stored
1331 * in adap->nr, and the specified adapter became available for clients.
1332 * Otherwise, a negative errno value is returned.
1334 int i2c_add_adapter(struct i2c_adapter *adapter)
1336 struct device *dev = &adapter->dev;
1337 int id;
1339 if (dev->of_node) {
1340 id = of_alias_get_id(dev->of_node, "i2c");
1341 if (id >= 0) {
1342 adapter->nr = id;
1343 return __i2c_add_numbered_adapter(adapter);
1347 mutex_lock(&core_lock);
1348 id = idr_alloc(&i2c_adapter_idr, adapter,
1349 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1350 mutex_unlock(&core_lock);
1351 if (id < 0)
1352 return id;
1354 adapter->nr = id;
1356 return i2c_register_adapter(adapter);
1358 EXPORT_SYMBOL(i2c_add_adapter);
1361 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1362 * @adap: the adapter to register (with adap->nr initialized)
1363 * Context: can sleep
1365 * This routine is used to declare an I2C adapter when its bus number
1366 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1367 * or otherwise built in to the system's mainboard, and where i2c_board_info
1368 * is used to properly configure I2C devices.
1370 * If the requested bus number is set to -1, then this function will behave
1371 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1373 * If no devices have pre-been declared for this bus, then be sure to
1374 * register the adapter before any dynamically allocated ones. Otherwise
1375 * the required bus ID may not be available.
1377 * When this returns zero, the specified adapter became available for
1378 * clients using the bus number provided in adap->nr. Also, the table
1379 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1380 * and the appropriate driver model device nodes are created. Otherwise, a
1381 * negative errno value is returned.
1383 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1385 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1386 return i2c_add_adapter(adap);
1388 return __i2c_add_numbered_adapter(adap);
1390 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1392 static void i2c_do_del_adapter(struct i2c_driver *driver,
1393 struct i2c_adapter *adapter)
1395 struct i2c_client *client, *_n;
1397 /* Remove the devices we created ourselves as the result of hardware
1398 * probing (using a driver's detect method) */
1399 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1400 if (client->adapter == adapter) {
1401 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1402 client->name, client->addr);
1403 list_del(&client->detected);
1404 i2c_unregister_device(client);
1409 static int __unregister_client(struct device *dev, void *dummy)
1411 struct i2c_client *client = i2c_verify_client(dev);
1412 if (client && strcmp(client->name, "dummy"))
1413 i2c_unregister_device(client);
1414 return 0;
1417 static int __unregister_dummy(struct device *dev, void *dummy)
1419 struct i2c_client *client = i2c_verify_client(dev);
1420 if (client)
1421 i2c_unregister_device(client);
1422 return 0;
1425 static int __process_removed_adapter(struct device_driver *d, void *data)
1427 i2c_do_del_adapter(to_i2c_driver(d), data);
1428 return 0;
1432 * i2c_del_adapter - unregister I2C adapter
1433 * @adap: the adapter being unregistered
1434 * Context: can sleep
1436 * This unregisters an I2C adapter which was previously registered
1437 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1439 void i2c_del_adapter(struct i2c_adapter *adap)
1441 struct i2c_adapter *found;
1442 struct i2c_client *client, *next;
1444 /* First make sure that this adapter was ever added */
1445 mutex_lock(&core_lock);
1446 found = idr_find(&i2c_adapter_idr, adap->nr);
1447 mutex_unlock(&core_lock);
1448 if (found != adap) {
1449 pr_debug("i2c-core: attempting to delete unregistered "
1450 "adapter [%s]\n", adap->name);
1451 return;
1454 /* Tell drivers about this removal */
1455 mutex_lock(&core_lock);
1456 bus_for_each_drv(&i2c_bus_type, NULL, adap,
1457 __process_removed_adapter);
1458 mutex_unlock(&core_lock);
1460 /* Remove devices instantiated from sysfs */
1461 mutex_lock_nested(&adap->userspace_clients_lock,
1462 i2c_adapter_depth(adap));
1463 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1464 detected) {
1465 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1466 client->addr);
1467 list_del(&client->detected);
1468 i2c_unregister_device(client);
1470 mutex_unlock(&adap->userspace_clients_lock);
1472 /* Detach any active clients. This can't fail, thus we do not
1473 * check the returned value. This is a two-pass process, because
1474 * we can't remove the dummy devices during the first pass: they
1475 * could have been instantiated by real devices wishing to clean
1476 * them up properly, so we give them a chance to do that first. */
1477 device_for_each_child(&adap->dev, NULL, __unregister_client);
1478 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1480 #ifdef CONFIG_I2C_COMPAT
1481 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1482 adap->dev.parent);
1483 #endif
1485 /* device name is gone after device_unregister */
1486 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1488 /* clean up the sysfs representation */
1489 init_completion(&adap->dev_released);
1490 device_unregister(&adap->dev);
1492 /* wait for sysfs to drop all references */
1493 wait_for_completion(&adap->dev_released);
1495 /* free bus id */
1496 mutex_lock(&core_lock);
1497 idr_remove(&i2c_adapter_idr, adap->nr);
1498 mutex_unlock(&core_lock);
1500 /* Clear the device structure in case this adapter is ever going to be
1501 added again */
1502 memset(&adap->dev, 0, sizeof(adap->dev));
1504 EXPORT_SYMBOL(i2c_del_adapter);
1506 /* ------------------------------------------------------------------------- */
1508 int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1510 int res;
1512 mutex_lock(&core_lock);
1513 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1514 mutex_unlock(&core_lock);
1516 return res;
1518 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1520 static int __process_new_driver(struct device *dev, void *data)
1522 if (dev->type != &i2c_adapter_type)
1523 return 0;
1524 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1528 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1529 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1532 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1534 int res;
1536 /* Can't register until after driver model init */
1537 if (unlikely(WARN_ON(!i2c_bus_type.p)))
1538 return -EAGAIN;
1540 /* add the driver to the list of i2c drivers in the driver core */
1541 driver->driver.owner = owner;
1542 driver->driver.bus = &i2c_bus_type;
1544 /* When registration returns, the driver core
1545 * will have called probe() for all matching-but-unbound devices.
1547 res = driver_register(&driver->driver);
1548 if (res)
1549 return res;
1551 /* Drivers should switch to dev_pm_ops instead. */
1552 if (driver->suspend)
1553 pr_warn("i2c-core: driver [%s] using legacy suspend method\n",
1554 driver->driver.name);
1555 if (driver->resume)
1556 pr_warn("i2c-core: driver [%s] using legacy resume method\n",
1557 driver->driver.name);
1559 pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
1561 INIT_LIST_HEAD(&driver->clients);
1562 /* Walk the adapters that are already present */
1563 i2c_for_each_dev(driver, __process_new_driver);
1565 return 0;
1567 EXPORT_SYMBOL(i2c_register_driver);
1569 static int __process_removed_driver(struct device *dev, void *data)
1571 if (dev->type == &i2c_adapter_type)
1572 i2c_do_del_adapter(data, to_i2c_adapter(dev));
1573 return 0;
1577 * i2c_del_driver - unregister I2C driver
1578 * @driver: the driver being unregistered
1579 * Context: can sleep
1581 void i2c_del_driver(struct i2c_driver *driver)
1583 i2c_for_each_dev(driver, __process_removed_driver);
1585 driver_unregister(&driver->driver);
1586 pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
1588 EXPORT_SYMBOL(i2c_del_driver);
1590 /* ------------------------------------------------------------------------- */
1593 * i2c_use_client - increments the reference count of the i2c client structure
1594 * @client: the client being referenced
1596 * Each live reference to a client should be refcounted. The driver model does
1597 * that automatically as part of driver binding, so that most drivers don't
1598 * need to do this explicitly: they hold a reference until they're unbound
1599 * from the device.
1601 * A pointer to the client with the incremented reference counter is returned.
1603 struct i2c_client *i2c_use_client(struct i2c_client *client)
1605 if (client && get_device(&client->dev))
1606 return client;
1607 return NULL;
1609 EXPORT_SYMBOL(i2c_use_client);
1612 * i2c_release_client - release a use of the i2c client structure
1613 * @client: the client being no longer referenced
1615 * Must be called when a user of a client is finished with it.
1617 void i2c_release_client(struct i2c_client *client)
1619 if (client)
1620 put_device(&client->dev);
1622 EXPORT_SYMBOL(i2c_release_client);
1624 struct i2c_cmd_arg {
1625 unsigned cmd;
1626 void *arg;
1629 static int i2c_cmd(struct device *dev, void *_arg)
1631 struct i2c_client *client = i2c_verify_client(dev);
1632 struct i2c_cmd_arg *arg = _arg;
1633 struct i2c_driver *driver;
1635 if (!client || !client->dev.driver)
1636 return 0;
1638 driver = to_i2c_driver(client->dev.driver);
1639 if (driver->command)
1640 driver->command(client, arg->cmd, arg->arg);
1641 return 0;
1644 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1646 struct i2c_cmd_arg cmd_arg;
1648 cmd_arg.cmd = cmd;
1649 cmd_arg.arg = arg;
1650 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1652 EXPORT_SYMBOL(i2c_clients_command);
1654 static int __init i2c_init(void)
1656 int retval;
1658 retval = bus_register(&i2c_bus_type);
1659 if (retval)
1660 return retval;
1661 #ifdef CONFIG_I2C_COMPAT
1662 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1663 if (!i2c_adapter_compat_class) {
1664 retval = -ENOMEM;
1665 goto bus_err;
1667 #endif
1668 retval = i2c_add_driver(&dummy_driver);
1669 if (retval)
1670 goto class_err;
1671 return 0;
1673 class_err:
1674 #ifdef CONFIG_I2C_COMPAT
1675 class_compat_unregister(i2c_adapter_compat_class);
1676 bus_err:
1677 #endif
1678 bus_unregister(&i2c_bus_type);
1679 return retval;
1682 static void __exit i2c_exit(void)
1684 i2c_del_driver(&dummy_driver);
1685 #ifdef CONFIG_I2C_COMPAT
1686 class_compat_unregister(i2c_adapter_compat_class);
1687 #endif
1688 bus_unregister(&i2c_bus_type);
1691 /* We must initialize early, because some subsystems register i2c drivers
1692 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1694 postcore_initcall(i2c_init);
1695 module_exit(i2c_exit);
1697 /* ----------------------------------------------------
1698 * the functional interface to the i2c busses.
1699 * ----------------------------------------------------
1703 * __i2c_transfer - unlocked flavor of i2c_transfer
1704 * @adap: Handle to I2C bus
1705 * @msgs: One or more messages to execute before STOP is issued to
1706 * terminate the operation; each message begins with a START.
1707 * @num: Number of messages to be executed.
1709 * Returns negative errno, else the number of messages executed.
1711 * Adapter lock must be held when calling this function. No debug logging
1712 * takes place. adap->algo->master_xfer existence isn't checked.
1714 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1716 unsigned long orig_jiffies;
1717 int ret, try;
1719 /* Retry automatically on arbitration loss */
1720 orig_jiffies = jiffies;
1721 for (ret = 0, try = 0; try <= adap->retries; try++) {
1722 ret = adap->algo->master_xfer(adap, msgs, num);
1723 if (ret != -EAGAIN)
1724 break;
1725 if (time_after(jiffies, orig_jiffies + adap->timeout))
1726 break;
1729 return ret;
1731 EXPORT_SYMBOL(__i2c_transfer);
1734 * i2c_transfer - execute a single or combined I2C message
1735 * @adap: Handle to I2C bus
1736 * @msgs: One or more messages to execute before STOP is issued to
1737 * terminate the operation; each message begins with a START.
1738 * @num: Number of messages to be executed.
1740 * Returns negative errno, else the number of messages executed.
1742 * Note that there is no requirement that each message be sent to
1743 * the same slave address, although that is the most common model.
1745 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1747 int ret;
1749 /* REVISIT the fault reporting model here is weak:
1751 * - When we get an error after receiving N bytes from a slave,
1752 * there is no way to report "N".
1754 * - When we get a NAK after transmitting N bytes to a slave,
1755 * there is no way to report "N" ... or to let the master
1756 * continue executing the rest of this combined message, if
1757 * that's the appropriate response.
1759 * - When for example "num" is two and we successfully complete
1760 * the first message but get an error part way through the
1761 * second, it's unclear whether that should be reported as
1762 * one (discarding status on the second message) or errno
1763 * (discarding status on the first one).
1766 if (adap->algo->master_xfer) {
1767 #ifdef DEBUG
1768 for (ret = 0; ret < num; ret++) {
1769 dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
1770 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
1771 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
1772 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
1774 #endif
1776 if (in_atomic() || irqs_disabled()) {
1777 ret = i2c_trylock_adapter(adap);
1778 if (!ret)
1779 /* I2C activity is ongoing. */
1780 return -EAGAIN;
1781 } else {
1782 i2c_lock_adapter(adap);
1785 ret = __i2c_transfer(adap, msgs, num);
1786 i2c_unlock_adapter(adap);
1788 return ret;
1789 } else {
1790 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
1791 return -EOPNOTSUPP;
1794 EXPORT_SYMBOL(i2c_transfer);
1797 * i2c_master_send - issue a single I2C message in master transmit mode
1798 * @client: Handle to slave device
1799 * @buf: Data that will be written to the slave
1800 * @count: How many bytes to write, must be less than 64k since msg.len is u16
1802 * Returns negative errno, or else the number of bytes written.
1804 int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
1806 int ret;
1807 struct i2c_adapter *adap = client->adapter;
1808 struct i2c_msg msg;
1810 msg.addr = client->addr;
1811 msg.flags = client->flags & I2C_M_TEN;
1812 msg.len = count;
1813 msg.buf = (char *)buf;
1815 ret = i2c_transfer(adap, &msg, 1);
1818 * If everything went ok (i.e. 1 msg transmitted), return #bytes
1819 * transmitted, else error code.
1821 return (ret == 1) ? count : ret;
1823 EXPORT_SYMBOL(i2c_master_send);
1826 * i2c_master_recv - issue a single I2C message in master receive mode
1827 * @client: Handle to slave device
1828 * @buf: Where to store data read from slave
1829 * @count: How many bytes to read, must be less than 64k since msg.len is u16
1831 * Returns negative errno, or else the number of bytes read.
1833 int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
1835 struct i2c_adapter *adap = client->adapter;
1836 struct i2c_msg msg;
1837 int ret;
1839 msg.addr = client->addr;
1840 msg.flags = client->flags & I2C_M_TEN;
1841 msg.flags |= I2C_M_RD;
1842 msg.len = count;
1843 msg.buf = buf;
1845 ret = i2c_transfer(adap, &msg, 1);
1848 * If everything went ok (i.e. 1 msg received), return #bytes received,
1849 * else error code.
1851 return (ret == 1) ? count : ret;
1853 EXPORT_SYMBOL(i2c_master_recv);
1855 /* ----------------------------------------------------
1856 * the i2c address scanning function
1857 * Will not work for 10-bit addresses!
1858 * ----------------------------------------------------
1862 * Legacy default probe function, mostly relevant for SMBus. The default
1863 * probe method is a quick write, but it is known to corrupt the 24RF08
1864 * EEPROMs due to a state machine bug, and could also irreversibly
1865 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
1866 * we use a short byte read instead. Also, some bus drivers don't implement
1867 * quick write, so we fallback to a byte read in that case too.
1868 * On x86, there is another special case for FSC hardware monitoring chips,
1869 * which want regular byte reads (address 0x73.) Fortunately, these are the
1870 * only known chips using this I2C address on PC hardware.
1871 * Returns 1 if probe succeeded, 0 if not.
1873 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
1875 int err;
1876 union i2c_smbus_data dummy;
1878 #ifdef CONFIG_X86
1879 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
1880 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
1881 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1882 I2C_SMBUS_BYTE_DATA, &dummy);
1883 else
1884 #endif
1885 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
1886 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
1887 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
1888 I2C_SMBUS_QUICK, NULL);
1889 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
1890 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1891 I2C_SMBUS_BYTE, &dummy);
1892 else {
1893 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
1894 addr);
1895 err = -EOPNOTSUPP;
1898 return err >= 0;
1901 static int i2c_detect_address(struct i2c_client *temp_client,
1902 struct i2c_driver *driver)
1904 struct i2c_board_info info;
1905 struct i2c_adapter *adapter = temp_client->adapter;
1906 int addr = temp_client->addr;
1907 int err;
1909 /* Make sure the address is valid */
1910 err = i2c_check_addr_validity(addr);
1911 if (err) {
1912 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
1913 addr);
1914 return err;
1917 /* Skip if already in use */
1918 if (i2c_check_addr_busy(adapter, addr))
1919 return 0;
1921 /* Make sure there is something at this address */
1922 if (!i2c_default_probe(adapter, addr))
1923 return 0;
1925 /* Finally call the custom detection function */
1926 memset(&info, 0, sizeof(struct i2c_board_info));
1927 info.addr = addr;
1928 err = driver->detect(temp_client, &info);
1929 if (err) {
1930 /* -ENODEV is returned if the detection fails. We catch it
1931 here as this isn't an error. */
1932 return err == -ENODEV ? 0 : err;
1935 /* Consistency check */
1936 if (info.type[0] == '\0') {
1937 dev_err(&adapter->dev, "%s detection function provided "
1938 "no name for 0x%x\n", driver->driver.name,
1939 addr);
1940 } else {
1941 struct i2c_client *client;
1943 /* Detection succeeded, instantiate the device */
1944 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
1945 info.type, info.addr);
1946 client = i2c_new_device(adapter, &info);
1947 if (client)
1948 list_add_tail(&client->detected, &driver->clients);
1949 else
1950 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
1951 info.type, info.addr);
1953 return 0;
1956 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
1958 const unsigned short *address_list;
1959 struct i2c_client *temp_client;
1960 int i, err = 0;
1961 int adap_id = i2c_adapter_id(adapter);
1963 address_list = driver->address_list;
1964 if (!driver->detect || !address_list)
1965 return 0;
1967 /* Stop here if the classes do not match */
1968 if (!(adapter->class & driver->class))
1969 return 0;
1971 /* Set up a temporary client to help detect callback */
1972 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
1973 if (!temp_client)
1974 return -ENOMEM;
1975 temp_client->adapter = adapter;
1977 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
1978 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
1979 "addr 0x%02x\n", adap_id, address_list[i]);
1980 temp_client->addr = address_list[i];
1981 err = i2c_detect_address(temp_client, driver);
1982 if (unlikely(err))
1983 break;
1986 kfree(temp_client);
1987 return err;
1990 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
1992 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
1993 I2C_SMBUS_QUICK, NULL) >= 0;
1995 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
1997 struct i2c_client *
1998 i2c_new_probed_device(struct i2c_adapter *adap,
1999 struct i2c_board_info *info,
2000 unsigned short const *addr_list,
2001 int (*probe)(struct i2c_adapter *, unsigned short addr))
2003 int i;
2005 if (!probe)
2006 probe = i2c_default_probe;
2008 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2009 /* Check address validity */
2010 if (i2c_check_addr_validity(addr_list[i]) < 0) {
2011 dev_warn(&adap->dev, "Invalid 7-bit address "
2012 "0x%02x\n", addr_list[i]);
2013 continue;
2016 /* Check address availability */
2017 if (i2c_check_addr_busy(adap, addr_list[i])) {
2018 dev_dbg(&adap->dev, "Address 0x%02x already in "
2019 "use, not probing\n", addr_list[i]);
2020 continue;
2023 /* Test address responsiveness */
2024 if (probe(adap, addr_list[i]))
2025 break;
2028 if (addr_list[i] == I2C_CLIENT_END) {
2029 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2030 return NULL;
2033 info->addr = addr_list[i];
2034 return i2c_new_device(adap, info);
2036 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2038 struct i2c_adapter *i2c_get_adapter(int nr)
2040 struct i2c_adapter *adapter;
2042 mutex_lock(&core_lock);
2043 adapter = idr_find(&i2c_adapter_idr, nr);
2044 if (adapter && !try_module_get(adapter->owner))
2045 adapter = NULL;
2047 mutex_unlock(&core_lock);
2048 return adapter;
2050 EXPORT_SYMBOL(i2c_get_adapter);
2052 void i2c_put_adapter(struct i2c_adapter *adap)
2054 if (adap)
2055 module_put(adap->owner);
2057 EXPORT_SYMBOL(i2c_put_adapter);
2059 /* The SMBus parts */
2061 #define POLY (0x1070U << 3)
2062 static u8 crc8(u16 data)
2064 int i;
2066 for (i = 0; i < 8; i++) {
2067 if (data & 0x8000)
2068 data = data ^ POLY;
2069 data = data << 1;
2071 return (u8)(data >> 8);
2074 /* Incremental CRC8 over count bytes in the array pointed to by p */
2075 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2077 int i;
2079 for (i = 0; i < count; i++)
2080 crc = crc8((crc ^ p[i]) << 8);
2081 return crc;
2084 /* Assume a 7-bit address, which is reasonable for SMBus */
2085 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2087 /* The address will be sent first */
2088 u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
2089 pec = i2c_smbus_pec(pec, &addr, 1);
2091 /* The data buffer follows */
2092 return i2c_smbus_pec(pec, msg->buf, msg->len);
2095 /* Used for write only transactions */
2096 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2098 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2099 msg->len++;
2102 /* Return <0 on CRC error
2103 If there was a write before this read (most cases) we need to take the
2104 partial CRC from the write part into account.
2105 Note that this function does modify the message (we need to decrease the
2106 message length to hide the CRC byte from the caller). */
2107 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2109 u8 rpec = msg->buf[--msg->len];
2110 cpec = i2c_smbus_msg_pec(cpec, msg);
2112 if (rpec != cpec) {
2113 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
2114 rpec, cpec);
2115 return -EBADMSG;
2117 return 0;
2121 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2122 * @client: Handle to slave device
2124 * This executes the SMBus "receive byte" protocol, returning negative errno
2125 * else the byte received from the device.
2127 s32 i2c_smbus_read_byte(const struct i2c_client *client)
2129 union i2c_smbus_data data;
2130 int status;
2132 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2133 I2C_SMBUS_READ, 0,
2134 I2C_SMBUS_BYTE, &data);
2135 return (status < 0) ? status : data.byte;
2137 EXPORT_SYMBOL(i2c_smbus_read_byte);
2140 * i2c_smbus_write_byte - SMBus "send byte" protocol
2141 * @client: Handle to slave device
2142 * @value: Byte to be sent
2144 * This executes the SMBus "send byte" protocol, returning negative errno
2145 * else zero on success.
2147 s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2149 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2150 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2152 EXPORT_SYMBOL(i2c_smbus_write_byte);
2155 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2156 * @client: Handle to slave device
2157 * @command: Byte interpreted by slave
2159 * This executes the SMBus "read byte" protocol, returning negative errno
2160 * else a data byte received from the device.
2162 s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2164 union i2c_smbus_data data;
2165 int status;
2167 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2168 I2C_SMBUS_READ, command,
2169 I2C_SMBUS_BYTE_DATA, &data);
2170 return (status < 0) ? status : data.byte;
2172 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2175 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2176 * @client: Handle to slave device
2177 * @command: Byte interpreted by slave
2178 * @value: Byte being written
2180 * This executes the SMBus "write byte" protocol, returning negative errno
2181 * else zero on success.
2183 s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
2184 u8 value)
2186 union i2c_smbus_data data;
2187 data.byte = value;
2188 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2189 I2C_SMBUS_WRITE, command,
2190 I2C_SMBUS_BYTE_DATA, &data);
2192 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
2195 * i2c_smbus_read_word_data - SMBus "read word" protocol
2196 * @client: Handle to slave device
2197 * @command: Byte interpreted by slave
2199 * This executes the SMBus "read word" protocol, returning negative errno
2200 * else a 16-bit unsigned "word" received from the device.
2202 s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
2204 union i2c_smbus_data data;
2205 int status;
2207 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2208 I2C_SMBUS_READ, command,
2209 I2C_SMBUS_WORD_DATA, &data);
2210 return (status < 0) ? status : data.word;
2212 EXPORT_SYMBOL(i2c_smbus_read_word_data);
2215 * i2c_smbus_write_word_data - SMBus "write word" protocol
2216 * @client: Handle to slave device
2217 * @command: Byte interpreted by slave
2218 * @value: 16-bit "word" being written
2220 * This executes the SMBus "write word" protocol, returning negative errno
2221 * else zero on success.
2223 s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2224 u16 value)
2226 union i2c_smbus_data data;
2227 data.word = value;
2228 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2229 I2C_SMBUS_WRITE, command,
2230 I2C_SMBUS_WORD_DATA, &data);
2232 EXPORT_SYMBOL(i2c_smbus_write_word_data);
2235 * i2c_smbus_read_block_data - SMBus "block read" protocol
2236 * @client: Handle to slave device
2237 * @command: Byte interpreted by slave
2238 * @values: Byte array into which data will be read; big enough to hold
2239 * the data returned by the slave. SMBus allows at most 32 bytes.
2241 * This executes the SMBus "block read" protocol, returning negative errno
2242 * else the number of data bytes in the slave's response.
2244 * Note that using this function requires that the client's adapter support
2245 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
2246 * support this; its emulation through I2C messaging relies on a specific
2247 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2249 s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2250 u8 *values)
2252 union i2c_smbus_data data;
2253 int status;
2255 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2256 I2C_SMBUS_READ, command,
2257 I2C_SMBUS_BLOCK_DATA, &data);
2258 if (status)
2259 return status;
2261 memcpy(values, &data.block[1], data.block[0]);
2262 return data.block[0];
2264 EXPORT_SYMBOL(i2c_smbus_read_block_data);
2267 * i2c_smbus_write_block_data - SMBus "block write" protocol
2268 * @client: Handle to slave device
2269 * @command: Byte interpreted by slave
2270 * @length: Size of data block; SMBus allows at most 32 bytes
2271 * @values: Byte array which will be written.
2273 * This executes the SMBus "block write" protocol, returning negative errno
2274 * else zero on success.
2276 s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2277 u8 length, const u8 *values)
2279 union i2c_smbus_data data;
2281 if (length > I2C_SMBUS_BLOCK_MAX)
2282 length = I2C_SMBUS_BLOCK_MAX;
2283 data.block[0] = length;
2284 memcpy(&data.block[1], values, length);
2285 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2286 I2C_SMBUS_WRITE, command,
2287 I2C_SMBUS_BLOCK_DATA, &data);
2289 EXPORT_SYMBOL(i2c_smbus_write_block_data);
2291 /* Returns the number of read bytes */
2292 s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2293 u8 length, u8 *values)
2295 union i2c_smbus_data data;
2296 int status;
2298 if (length > I2C_SMBUS_BLOCK_MAX)
2299 length = I2C_SMBUS_BLOCK_MAX;
2300 data.block[0] = length;
2301 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2302 I2C_SMBUS_READ, command,
2303 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2304 if (status < 0)
2305 return status;
2307 memcpy(values, &data.block[1], data.block[0]);
2308 return data.block[0];
2310 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2312 s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2313 u8 length, const u8 *values)
2315 union i2c_smbus_data data;
2317 if (length > I2C_SMBUS_BLOCK_MAX)
2318 length = I2C_SMBUS_BLOCK_MAX;
2319 data.block[0] = length;
2320 memcpy(data.block + 1, values, length);
2321 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2322 I2C_SMBUS_WRITE, command,
2323 I2C_SMBUS_I2C_BLOCK_DATA, &data);
2325 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2327 /* Simulate a SMBus command using the i2c protocol
2328 No checking of parameters is done! */
2329 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2330 unsigned short flags,
2331 char read_write, u8 command, int size,
2332 union i2c_smbus_data *data)
2334 /* So we need to generate a series of msgs. In the case of writing, we
2335 need to use only one message; when reading, we need two. We initialize
2336 most things with sane defaults, to keep the code below somewhat
2337 simpler. */
2338 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2339 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2340 int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2341 int i;
2342 u8 partial_pec = 0;
2343 int status;
2344 struct i2c_msg msg[2] = {
2346 .addr = addr,
2347 .flags = flags,
2348 .len = 1,
2349 .buf = msgbuf0,
2350 }, {
2351 .addr = addr,
2352 .flags = flags | I2C_M_RD,
2353 .len = 0,
2354 .buf = msgbuf1,
2358 msgbuf0[0] = command;
2359 switch (size) {
2360 case I2C_SMBUS_QUICK:
2361 msg[0].len = 0;
2362 /* Special case: The read/write field is used as data */
2363 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2364 I2C_M_RD : 0);
2365 num = 1;
2366 break;
2367 case I2C_SMBUS_BYTE:
2368 if (read_write == I2C_SMBUS_READ) {
2369 /* Special case: only a read! */
2370 msg[0].flags = I2C_M_RD | flags;
2371 num = 1;
2373 break;
2374 case I2C_SMBUS_BYTE_DATA:
2375 if (read_write == I2C_SMBUS_READ)
2376 msg[1].len = 1;
2377 else {
2378 msg[0].len = 2;
2379 msgbuf0[1] = data->byte;
2381 break;
2382 case I2C_SMBUS_WORD_DATA:
2383 if (read_write == I2C_SMBUS_READ)
2384 msg[1].len = 2;
2385 else {
2386 msg[0].len = 3;
2387 msgbuf0[1] = data->word & 0xff;
2388 msgbuf0[2] = data->word >> 8;
2390 break;
2391 case I2C_SMBUS_PROC_CALL:
2392 num = 2; /* Special case */
2393 read_write = I2C_SMBUS_READ;
2394 msg[0].len = 3;
2395 msg[1].len = 2;
2396 msgbuf0[1] = data->word & 0xff;
2397 msgbuf0[2] = data->word >> 8;
2398 break;
2399 case I2C_SMBUS_BLOCK_DATA:
2400 if (read_write == I2C_SMBUS_READ) {
2401 msg[1].flags |= I2C_M_RECV_LEN;
2402 msg[1].len = 1; /* block length will be added by
2403 the underlying bus driver */
2404 } else {
2405 msg[0].len = data->block[0] + 2;
2406 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
2407 dev_err(&adapter->dev,
2408 "Invalid block write size %d\n",
2409 data->block[0]);
2410 return -EINVAL;
2412 for (i = 1; i < msg[0].len; i++)
2413 msgbuf0[i] = data->block[i-1];
2415 break;
2416 case I2C_SMBUS_BLOCK_PROC_CALL:
2417 num = 2; /* Another special case */
2418 read_write = I2C_SMBUS_READ;
2419 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
2420 dev_err(&adapter->dev,
2421 "Invalid block write size %d\n",
2422 data->block[0]);
2423 return -EINVAL;
2425 msg[0].len = data->block[0] + 2;
2426 for (i = 1; i < msg[0].len; i++)
2427 msgbuf0[i] = data->block[i-1];
2428 msg[1].flags |= I2C_M_RECV_LEN;
2429 msg[1].len = 1; /* block length will be added by
2430 the underlying bus driver */
2431 break;
2432 case I2C_SMBUS_I2C_BLOCK_DATA:
2433 if (read_write == I2C_SMBUS_READ) {
2434 msg[1].len = data->block[0];
2435 } else {
2436 msg[0].len = data->block[0] + 1;
2437 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
2438 dev_err(&adapter->dev,
2439 "Invalid block write size %d\n",
2440 data->block[0]);
2441 return -EINVAL;
2443 for (i = 1; i <= data->block[0]; i++)
2444 msgbuf0[i] = data->block[i];
2446 break;
2447 default:
2448 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
2449 return -EOPNOTSUPP;
2452 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
2453 && size != I2C_SMBUS_I2C_BLOCK_DATA);
2454 if (i) {
2455 /* Compute PEC if first message is a write */
2456 if (!(msg[0].flags & I2C_M_RD)) {
2457 if (num == 1) /* Write only */
2458 i2c_smbus_add_pec(&msg[0]);
2459 else /* Write followed by read */
2460 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
2462 /* Ask for PEC if last message is a read */
2463 if (msg[num-1].flags & I2C_M_RD)
2464 msg[num-1].len++;
2467 status = i2c_transfer(adapter, msg, num);
2468 if (status < 0)
2469 return status;
2471 /* Check PEC if last message is a read */
2472 if (i && (msg[num-1].flags & I2C_M_RD)) {
2473 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
2474 if (status < 0)
2475 return status;
2478 if (read_write == I2C_SMBUS_READ)
2479 switch (size) {
2480 case I2C_SMBUS_BYTE:
2481 data->byte = msgbuf0[0];
2482 break;
2483 case I2C_SMBUS_BYTE_DATA:
2484 data->byte = msgbuf1[0];
2485 break;
2486 case I2C_SMBUS_WORD_DATA:
2487 case I2C_SMBUS_PROC_CALL:
2488 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
2489 break;
2490 case I2C_SMBUS_I2C_BLOCK_DATA:
2491 for (i = 0; i < data->block[0]; i++)
2492 data->block[i+1] = msgbuf1[i];
2493 break;
2494 case I2C_SMBUS_BLOCK_DATA:
2495 case I2C_SMBUS_BLOCK_PROC_CALL:
2496 for (i = 0; i < msgbuf1[0] + 1; i++)
2497 data->block[i] = msgbuf1[i];
2498 break;
2500 return 0;
2504 * i2c_smbus_xfer - execute SMBus protocol operations
2505 * @adapter: Handle to I2C bus
2506 * @addr: Address of SMBus slave on that bus
2507 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
2508 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
2509 * @command: Byte interpreted by slave, for protocols which use such bytes
2510 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
2511 * @data: Data to be read or written
2513 * This executes an SMBus protocol operation, and returns a negative
2514 * errno code else zero on success.
2516 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
2517 char read_write, u8 command, int protocol,
2518 union i2c_smbus_data *data)
2520 unsigned long orig_jiffies;
2521 int try;
2522 s32 res;
2524 flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
2526 if (adapter->algo->smbus_xfer) {
2527 i2c_lock_adapter(adapter);
2529 /* Retry automatically on arbitration loss */
2530 orig_jiffies = jiffies;
2531 for (res = 0, try = 0; try <= adapter->retries; try++) {
2532 res = adapter->algo->smbus_xfer(adapter, addr, flags,
2533 read_write, command,
2534 protocol, data);
2535 if (res != -EAGAIN)
2536 break;
2537 if (time_after(jiffies,
2538 orig_jiffies + adapter->timeout))
2539 break;
2541 i2c_unlock_adapter(adapter);
2543 if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
2544 return res;
2546 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
2547 * implement native support for the SMBus operation.
2551 return i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
2552 command, protocol, data);
2554 EXPORT_SYMBOL(i2c_smbus_xfer);
2556 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2557 MODULE_DESCRIPTION("I2C-Bus main module");
2558 MODULE_LICENSE("GPL");