i2c: Convert i2c clients to a device type
[linux-2.6/libata-dev.git] / drivers / i2c / i2c-core.c
blobf236b34296ee7b9eb9d561ede4eac76c9f660d2e
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., 675 Mass Ave, Cambridge, MA 02139, USA. */
18 /* ------------------------------------------------------------------------- */
20 /* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>.
21 All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
22 SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com> and
23 Jean Delvare <khali@linux-fr.org> */
25 #include <linux/module.h>
26 #include <linux/kernel.h>
27 #include <linux/errno.h>
28 #include <linux/slab.h>
29 #include <linux/i2c.h>
30 #include <linux/init.h>
31 #include <linux/idr.h>
32 #include <linux/mutex.h>
33 #include <linux/completion.h>
34 #include <linux/hardirq.h>
35 #include <linux/irqflags.h>
36 #include <linux/rwsem.h>
37 #include <asm/uaccess.h>
39 #include "i2c-core.h"
42 /* core_lock protects i2c_adapter_idr, userspace_devices, and guarantees
43 that device detection, deletion of detected devices, and attach_adapter
44 and detach_adapter calls are serialized */
45 static DEFINE_MUTEX(core_lock);
46 static DEFINE_IDR(i2c_adapter_idr);
47 static LIST_HEAD(userspace_devices);
49 static int i2c_check_addr(struct i2c_adapter *adapter, int addr);
50 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
52 /* ------------------------------------------------------------------------- */
54 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
55 const struct i2c_client *client)
57 while (id->name[0]) {
58 if (strcmp(client->name, id->name) == 0)
59 return id;
60 id++;
62 return NULL;
65 static int i2c_device_match(struct device *dev, struct device_driver *drv)
67 struct i2c_client *client = i2c_verify_client(dev);
68 struct i2c_driver *driver;
70 if (!client)
71 return 0;
73 driver = to_i2c_driver(drv);
74 /* match on an id table if there is one */
75 if (driver->id_table)
76 return i2c_match_id(driver->id_table, client) != NULL;
78 return 0;
81 #ifdef CONFIG_HOTPLUG
83 /* uevent helps with hotplug: modprobe -q $(MODALIAS) */
84 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
86 struct i2c_client *client = to_i2c_client(dev);
88 if (add_uevent_var(env, "MODALIAS=%s%s",
89 I2C_MODULE_PREFIX, client->name))
90 return -ENOMEM;
91 dev_dbg(dev, "uevent\n");
92 return 0;
95 #else
96 #define i2c_device_uevent NULL
97 #endif /* CONFIG_HOTPLUG */
99 static int i2c_device_probe(struct device *dev)
101 struct i2c_client *client = i2c_verify_client(dev);
102 struct i2c_driver *driver;
103 int status;
105 if (!client)
106 return 0;
108 driver = to_i2c_driver(dev->driver);
109 if (!driver->probe || !driver->id_table)
110 return -ENODEV;
111 client->driver = driver;
112 if (!device_can_wakeup(&client->dev))
113 device_init_wakeup(&client->dev,
114 client->flags & I2C_CLIENT_WAKE);
115 dev_dbg(dev, "probe\n");
117 status = driver->probe(client, i2c_match_id(driver->id_table, client));
118 if (status)
119 client->driver = NULL;
120 return status;
123 static int i2c_device_remove(struct device *dev)
125 struct i2c_client *client = i2c_verify_client(dev);
126 struct i2c_driver *driver;
127 int status;
129 if (!client || !dev->driver)
130 return 0;
132 driver = to_i2c_driver(dev->driver);
133 if (driver->remove) {
134 dev_dbg(dev, "remove\n");
135 status = driver->remove(client);
136 } else {
137 dev->driver = NULL;
138 status = 0;
140 if (status == 0)
141 client->driver = NULL;
142 return status;
145 static void i2c_device_shutdown(struct device *dev)
147 struct i2c_client *client = i2c_verify_client(dev);
148 struct i2c_driver *driver;
150 if (!client || !dev->driver)
151 return;
152 driver = to_i2c_driver(dev->driver);
153 if (driver->shutdown)
154 driver->shutdown(client);
157 static int i2c_device_suspend(struct device *dev, pm_message_t mesg)
159 struct i2c_client *client = i2c_verify_client(dev);
160 struct i2c_driver *driver;
162 if (!client || !dev->driver)
163 return 0;
164 driver = to_i2c_driver(dev->driver);
165 if (!driver->suspend)
166 return 0;
167 return driver->suspend(client, mesg);
170 static int i2c_device_resume(struct device *dev)
172 struct i2c_client *client = i2c_verify_client(dev);
173 struct i2c_driver *driver;
175 if (!client || !dev->driver)
176 return 0;
177 driver = to_i2c_driver(dev->driver);
178 if (!driver->resume)
179 return 0;
180 return driver->resume(client);
183 static void i2c_client_dev_release(struct device *dev)
185 kfree(to_i2c_client(dev));
188 static ssize_t
189 show_client_name(struct device *dev, struct device_attribute *attr, char *buf)
191 struct i2c_client *client = to_i2c_client(dev);
192 return sprintf(buf, "%s\n", client->name);
195 static ssize_t
196 show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
198 struct i2c_client *client = to_i2c_client(dev);
199 return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
202 static DEVICE_ATTR(name, S_IRUGO, show_client_name, NULL);
203 static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
205 static struct attribute *i2c_dev_attrs[] = {
206 &dev_attr_name.attr,
207 /* modalias helps coldplug: modprobe $(cat .../modalias) */
208 &dev_attr_modalias.attr,
209 NULL
212 static struct attribute_group i2c_dev_attr_group = {
213 .attrs = i2c_dev_attrs,
216 static const struct attribute_group *i2c_dev_attr_groups[] = {
217 &i2c_dev_attr_group,
218 NULL
221 struct bus_type i2c_bus_type = {
222 .name = "i2c",
223 .match = i2c_device_match,
224 .probe = i2c_device_probe,
225 .remove = i2c_device_remove,
226 .shutdown = i2c_device_shutdown,
227 .suspend = i2c_device_suspend,
228 .resume = i2c_device_resume,
230 EXPORT_SYMBOL_GPL(i2c_bus_type);
232 static struct device_type i2c_client_type = {
233 .groups = i2c_dev_attr_groups,
234 .uevent = i2c_device_uevent,
235 .release = i2c_client_dev_release,
240 * i2c_verify_client - return parameter as i2c_client, or NULL
241 * @dev: device, probably from some driver model iterator
243 * When traversing the driver model tree, perhaps using driver model
244 * iterators like @device_for_each_child(), you can't assume very much
245 * about the nodes you find. Use this function to avoid oopses caused
246 * by wrongly treating some non-I2C device as an i2c_client.
248 struct i2c_client *i2c_verify_client(struct device *dev)
250 return (dev->type == &i2c_client_type)
251 ? to_i2c_client(dev)
252 : NULL;
254 EXPORT_SYMBOL(i2c_verify_client);
258 * i2c_new_device - instantiate an i2c device
259 * @adap: the adapter managing the device
260 * @info: describes one I2C device; bus_num is ignored
261 * Context: can sleep
263 * Create an i2c device. Binding is handled through driver model
264 * probe()/remove() methods. A driver may be bound to this device when we
265 * return from this function, or any later moment (e.g. maybe hotplugging will
266 * load the driver module). This call is not appropriate for use by mainboard
267 * initialization logic, which usually runs during an arch_initcall() long
268 * before any i2c_adapter could exist.
270 * This returns the new i2c client, which may be saved for later use with
271 * i2c_unregister_device(); or NULL to indicate an error.
273 struct i2c_client *
274 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
276 struct i2c_client *client;
277 int status;
279 client = kzalloc(sizeof *client, GFP_KERNEL);
280 if (!client)
281 return NULL;
283 client->adapter = adap;
285 client->dev.platform_data = info->platform_data;
287 if (info->archdata)
288 client->dev.archdata = *info->archdata;
290 client->flags = info->flags;
291 client->addr = info->addr;
292 client->irq = info->irq;
294 strlcpy(client->name, info->type, sizeof(client->name));
296 /* Check for address business */
297 status = i2c_check_addr(adap, client->addr);
298 if (status)
299 goto out_err;
301 client->dev.parent = &client->adapter->dev;
302 client->dev.bus = &i2c_bus_type;
303 client->dev.type = &i2c_client_type;
305 dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
306 client->addr);
307 status = device_register(&client->dev);
308 if (status)
309 goto out_err;
311 dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
312 client->name, dev_name(&client->dev));
314 return client;
316 out_err:
317 dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
318 "(%d)\n", client->name, client->addr, status);
319 kfree(client);
320 return NULL;
322 EXPORT_SYMBOL_GPL(i2c_new_device);
326 * i2c_unregister_device - reverse effect of i2c_new_device()
327 * @client: value returned from i2c_new_device()
328 * Context: can sleep
330 void i2c_unregister_device(struct i2c_client *client)
332 device_unregister(&client->dev);
334 EXPORT_SYMBOL_GPL(i2c_unregister_device);
337 static const struct i2c_device_id dummy_id[] = {
338 { "dummy", 0 },
339 { },
342 static int dummy_probe(struct i2c_client *client,
343 const struct i2c_device_id *id)
345 return 0;
348 static int dummy_remove(struct i2c_client *client)
350 return 0;
353 static struct i2c_driver dummy_driver = {
354 .driver.name = "dummy",
355 .probe = dummy_probe,
356 .remove = dummy_remove,
357 .id_table = dummy_id,
361 * i2c_new_dummy - return a new i2c device bound to a dummy driver
362 * @adapter: the adapter managing the device
363 * @address: seven bit address to be used
364 * Context: can sleep
366 * This returns an I2C client bound to the "dummy" driver, intended for use
367 * with devices that consume multiple addresses. Examples of such chips
368 * include various EEPROMS (like 24c04 and 24c08 models).
370 * These dummy devices have two main uses. First, most I2C and SMBus calls
371 * except i2c_transfer() need a client handle; the dummy will be that handle.
372 * And second, this prevents the specified address from being bound to a
373 * different driver.
375 * This returns the new i2c client, which should be saved for later use with
376 * i2c_unregister_device(); or NULL to indicate an error.
378 struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
380 struct i2c_board_info info = {
381 I2C_BOARD_INFO("dummy", address),
384 return i2c_new_device(adapter, &info);
386 EXPORT_SYMBOL_GPL(i2c_new_dummy);
388 /* ------------------------------------------------------------------------- */
390 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
392 static void i2c_adapter_dev_release(struct device *dev)
394 struct i2c_adapter *adap = to_i2c_adapter(dev);
395 complete(&adap->dev_released);
398 static ssize_t
399 show_adapter_name(struct device *dev, struct device_attribute *attr, char *buf)
401 struct i2c_adapter *adap = to_i2c_adapter(dev);
402 return sprintf(buf, "%s\n", adap->name);
406 * Let users instantiate I2C devices through sysfs. This can be used when
407 * platform initialization code doesn't contain the proper data for
408 * whatever reason. Also useful for drivers that do device detection and
409 * detection fails, either because the device uses an unexpected address,
410 * or this is a compatible device with different ID register values.
412 * Parameter checking may look overzealous, but we really don't want
413 * the user to provide incorrect parameters.
415 static ssize_t
416 i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
417 const char *buf, size_t count)
419 struct i2c_adapter *adap = to_i2c_adapter(dev);
420 struct i2c_board_info info;
421 struct i2c_client *client;
422 char *blank, end;
423 int res;
425 dev_warn(dev, "The new_device interface is still experimental "
426 "and may change in a near future\n");
427 memset(&info, 0, sizeof(struct i2c_board_info));
429 blank = strchr(buf, ' ');
430 if (!blank) {
431 dev_err(dev, "%s: Missing parameters\n", "new_device");
432 return -EINVAL;
434 if (blank - buf > I2C_NAME_SIZE - 1) {
435 dev_err(dev, "%s: Invalid device name\n", "new_device");
436 return -EINVAL;
438 memcpy(info.type, buf, blank - buf);
440 /* Parse remaining parameters, reject extra parameters */
441 res = sscanf(++blank, "%hi%c", &info.addr, &end);
442 if (res < 1) {
443 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
444 return -EINVAL;
446 if (res > 1 && end != '\n') {
447 dev_err(dev, "%s: Extra parameters\n", "new_device");
448 return -EINVAL;
451 if (info.addr < 0x03 || info.addr > 0x77) {
452 dev_err(dev, "%s: Invalid I2C address 0x%hx\n", "new_device",
453 info.addr);
454 return -EINVAL;
457 client = i2c_new_device(adap, &info);
458 if (!client)
459 return -EEXIST;
461 /* Keep track of the added device */
462 mutex_lock(&core_lock);
463 list_add_tail(&client->detected, &userspace_devices);
464 mutex_unlock(&core_lock);
465 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
466 info.type, info.addr);
468 return count;
472 * And of course let the users delete the devices they instantiated, if
473 * they got it wrong. This interface can only be used to delete devices
474 * instantiated by i2c_sysfs_new_device above. This guarantees that we
475 * don't delete devices to which some kernel code still has references.
477 * Parameter checking may look overzealous, but we really don't want
478 * the user to delete the wrong device.
480 static ssize_t
481 i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
482 const char *buf, size_t count)
484 struct i2c_adapter *adap = to_i2c_adapter(dev);
485 struct i2c_client *client, *next;
486 unsigned short addr;
487 char end;
488 int res;
490 /* Parse parameters, reject extra parameters */
491 res = sscanf(buf, "%hi%c", &addr, &end);
492 if (res < 1) {
493 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
494 return -EINVAL;
496 if (res > 1 && end != '\n') {
497 dev_err(dev, "%s: Extra parameters\n", "delete_device");
498 return -EINVAL;
501 /* Make sure the device was added through sysfs */
502 res = -ENOENT;
503 mutex_lock(&core_lock);
504 list_for_each_entry_safe(client, next, &userspace_devices, detected) {
505 if (client->addr == addr && client->adapter == adap) {
506 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
507 "delete_device", client->name, client->addr);
509 list_del(&client->detected);
510 i2c_unregister_device(client);
511 res = count;
512 break;
515 mutex_unlock(&core_lock);
517 if (res < 0)
518 dev_err(dev, "%s: Can't find device in list\n",
519 "delete_device");
520 return res;
523 static struct device_attribute i2c_adapter_attrs[] = {
524 __ATTR(name, S_IRUGO, show_adapter_name, NULL),
525 __ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device),
526 __ATTR(delete_device, S_IWUSR, NULL, i2c_sysfs_delete_device),
527 { },
530 static struct class i2c_adapter_class = {
531 .owner = THIS_MODULE,
532 .name = "i2c-adapter",
533 .dev_attrs = i2c_adapter_attrs,
536 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
538 struct i2c_devinfo *devinfo;
540 down_read(&__i2c_board_lock);
541 list_for_each_entry(devinfo, &__i2c_board_list, list) {
542 if (devinfo->busnum == adapter->nr
543 && !i2c_new_device(adapter,
544 &devinfo->board_info))
545 dev_err(&adapter->dev,
546 "Can't create device at 0x%02x\n",
547 devinfo->board_info.addr);
549 up_read(&__i2c_board_lock);
552 static int i2c_do_add_adapter(struct device_driver *d, void *data)
554 struct i2c_driver *driver = to_i2c_driver(d);
555 struct i2c_adapter *adap = data;
557 /* Detect supported devices on that bus, and instantiate them */
558 i2c_detect(adap, driver);
560 /* Let legacy drivers scan this bus for matching devices */
561 if (driver->attach_adapter) {
562 /* We ignore the return code; if it fails, too bad */
563 driver->attach_adapter(adap);
565 return 0;
568 static int i2c_register_adapter(struct i2c_adapter *adap)
570 int res = 0, dummy;
572 /* Can't register until after driver model init */
573 if (unlikely(WARN_ON(!i2c_bus_type.p))) {
574 res = -EAGAIN;
575 goto out_list;
578 mutex_init(&adap->bus_lock);
580 /* Set default timeout to 1 second if not already set */
581 if (adap->timeout == 0)
582 adap->timeout = HZ;
584 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
585 adap->dev.release = &i2c_adapter_dev_release;
586 adap->dev.class = &i2c_adapter_class;
587 res = device_register(&adap->dev);
588 if (res)
589 goto out_list;
591 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
593 /* create pre-declared device nodes */
594 if (adap->nr < __i2c_first_dynamic_bus_num)
595 i2c_scan_static_board_info(adap);
597 /* Notify drivers */
598 mutex_lock(&core_lock);
599 dummy = bus_for_each_drv(&i2c_bus_type, NULL, adap,
600 i2c_do_add_adapter);
601 mutex_unlock(&core_lock);
603 return 0;
605 out_list:
606 mutex_lock(&core_lock);
607 idr_remove(&i2c_adapter_idr, adap->nr);
608 mutex_unlock(&core_lock);
609 return res;
613 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
614 * @adapter: the adapter to add
615 * Context: can sleep
617 * This routine is used to declare an I2C adapter when its bus number
618 * doesn't matter. Examples: for I2C adapters dynamically added by
619 * USB links or PCI plugin cards.
621 * When this returns zero, a new bus number was allocated and stored
622 * in adap->nr, and the specified adapter became available for clients.
623 * Otherwise, a negative errno value is returned.
625 int i2c_add_adapter(struct i2c_adapter *adapter)
627 int id, res = 0;
629 retry:
630 if (idr_pre_get(&i2c_adapter_idr, GFP_KERNEL) == 0)
631 return -ENOMEM;
633 mutex_lock(&core_lock);
634 /* "above" here means "above or equal to", sigh */
635 res = idr_get_new_above(&i2c_adapter_idr, adapter,
636 __i2c_first_dynamic_bus_num, &id);
637 mutex_unlock(&core_lock);
639 if (res < 0) {
640 if (res == -EAGAIN)
641 goto retry;
642 return res;
645 adapter->nr = id;
646 return i2c_register_adapter(adapter);
648 EXPORT_SYMBOL(i2c_add_adapter);
651 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
652 * @adap: the adapter to register (with adap->nr initialized)
653 * Context: can sleep
655 * This routine is used to declare an I2C adapter when its bus number
656 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
657 * or otherwise built in to the system's mainboard, and where i2c_board_info
658 * is used to properly configure I2C devices.
660 * If no devices have pre-been declared for this bus, then be sure to
661 * register the adapter before any dynamically allocated ones. Otherwise
662 * the required bus ID may not be available.
664 * When this returns zero, the specified adapter became available for
665 * clients using the bus number provided in adap->nr. Also, the table
666 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
667 * and the appropriate driver model device nodes are created. Otherwise, a
668 * negative errno value is returned.
670 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
672 int id;
673 int status;
675 if (adap->nr & ~MAX_ID_MASK)
676 return -EINVAL;
678 retry:
679 if (idr_pre_get(&i2c_adapter_idr, GFP_KERNEL) == 0)
680 return -ENOMEM;
682 mutex_lock(&core_lock);
683 /* "above" here means "above or equal to", sigh;
684 * we need the "equal to" result to force the result
686 status = idr_get_new_above(&i2c_adapter_idr, adap, adap->nr, &id);
687 if (status == 0 && id != adap->nr) {
688 status = -EBUSY;
689 idr_remove(&i2c_adapter_idr, id);
691 mutex_unlock(&core_lock);
692 if (status == -EAGAIN)
693 goto retry;
695 if (status == 0)
696 status = i2c_register_adapter(adap);
697 return status;
699 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
701 static int i2c_do_del_adapter(struct device_driver *d, void *data)
703 struct i2c_driver *driver = to_i2c_driver(d);
704 struct i2c_adapter *adapter = data;
705 struct i2c_client *client, *_n;
706 int res;
708 /* Remove the devices we created ourselves as the result of hardware
709 * probing (using a driver's detect method) */
710 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
711 if (client->adapter == adapter) {
712 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
713 client->name, client->addr);
714 list_del(&client->detected);
715 i2c_unregister_device(client);
719 if (!driver->detach_adapter)
720 return 0;
721 res = driver->detach_adapter(adapter);
722 if (res)
723 dev_err(&adapter->dev, "detach_adapter failed (%d) "
724 "for driver [%s]\n", res, driver->driver.name);
725 return res;
728 static int __unregister_client(struct device *dev, void *dummy)
730 struct i2c_client *client = i2c_verify_client(dev);
731 if (client)
732 i2c_unregister_device(client);
733 return 0;
737 * i2c_del_adapter - unregister I2C adapter
738 * @adap: the adapter being unregistered
739 * Context: can sleep
741 * This unregisters an I2C adapter which was previously registered
742 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
744 int i2c_del_adapter(struct i2c_adapter *adap)
746 int res = 0;
747 struct i2c_adapter *found;
749 /* First make sure that this adapter was ever added */
750 mutex_lock(&core_lock);
751 found = idr_find(&i2c_adapter_idr, adap->nr);
752 mutex_unlock(&core_lock);
753 if (found != adap) {
754 pr_debug("i2c-core: attempting to delete unregistered "
755 "adapter [%s]\n", adap->name);
756 return -EINVAL;
759 /* Tell drivers about this removal */
760 mutex_lock(&core_lock);
761 res = bus_for_each_drv(&i2c_bus_type, NULL, adap,
762 i2c_do_del_adapter);
763 mutex_unlock(&core_lock);
764 if (res)
765 return res;
767 /* Detach any active clients. This can't fail, thus we do not
768 checking the returned value. */
769 res = device_for_each_child(&adap->dev, NULL, __unregister_client);
771 /* clean up the sysfs representation */
772 init_completion(&adap->dev_released);
773 device_unregister(&adap->dev);
775 /* wait for sysfs to drop all references */
776 wait_for_completion(&adap->dev_released);
778 /* free bus id */
779 mutex_lock(&core_lock);
780 idr_remove(&i2c_adapter_idr, adap->nr);
781 mutex_unlock(&core_lock);
783 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
785 /* Clear the device structure in case this adapter is ever going to be
786 added again */
787 memset(&adap->dev, 0, sizeof(adap->dev));
789 return 0;
791 EXPORT_SYMBOL(i2c_del_adapter);
794 /* ------------------------------------------------------------------------- */
796 static int __attach_adapter(struct device *dev, void *data)
798 struct i2c_adapter *adapter = to_i2c_adapter(dev);
799 struct i2c_driver *driver = data;
801 i2c_detect(adapter, driver);
803 /* Legacy drivers scan i2c busses directly */
804 if (driver->attach_adapter)
805 driver->attach_adapter(adapter);
807 return 0;
811 * An i2c_driver is used with one or more i2c_client (device) nodes to access
812 * i2c slave chips, on a bus instance associated with some i2c_adapter.
815 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
817 int res;
819 /* Can't register until after driver model init */
820 if (unlikely(WARN_ON(!i2c_bus_type.p)))
821 return -EAGAIN;
823 /* add the driver to the list of i2c drivers in the driver core */
824 driver->driver.owner = owner;
825 driver->driver.bus = &i2c_bus_type;
827 /* When registration returns, the driver core
828 * will have called probe() for all matching-but-unbound devices.
830 res = driver_register(&driver->driver);
831 if (res)
832 return res;
834 pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
836 INIT_LIST_HEAD(&driver->clients);
837 /* Walk the adapters that are already present */
838 mutex_lock(&core_lock);
839 class_for_each_device(&i2c_adapter_class, NULL, driver,
840 __attach_adapter);
841 mutex_unlock(&core_lock);
843 return 0;
845 EXPORT_SYMBOL(i2c_register_driver);
847 static int __detach_adapter(struct device *dev, void *data)
849 struct i2c_adapter *adapter = to_i2c_adapter(dev);
850 struct i2c_driver *driver = data;
851 struct i2c_client *client, *_n;
853 /* Remove the devices we created ourselves as the result of hardware
854 * probing (using a driver's detect method) */
855 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
856 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
857 client->name, client->addr);
858 list_del(&client->detected);
859 i2c_unregister_device(client);
862 if (driver->detach_adapter) {
863 if (driver->detach_adapter(adapter))
864 dev_err(&adapter->dev,
865 "detach_adapter failed for driver [%s]\n",
866 driver->driver.name);
869 return 0;
873 * i2c_del_driver - unregister I2C driver
874 * @driver: the driver being unregistered
875 * Context: can sleep
877 void i2c_del_driver(struct i2c_driver *driver)
879 mutex_lock(&core_lock);
880 class_for_each_device(&i2c_adapter_class, NULL, driver,
881 __detach_adapter);
882 mutex_unlock(&core_lock);
884 driver_unregister(&driver->driver);
885 pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
887 EXPORT_SYMBOL(i2c_del_driver);
889 /* ------------------------------------------------------------------------- */
891 static int __i2c_check_addr(struct device *dev, void *addrp)
893 struct i2c_client *client = i2c_verify_client(dev);
894 int addr = *(int *)addrp;
896 if (client && client->addr == addr)
897 return -EBUSY;
898 return 0;
901 static int i2c_check_addr(struct i2c_adapter *adapter, int addr)
903 return device_for_each_child(&adapter->dev, &addr, __i2c_check_addr);
907 * i2c_use_client - increments the reference count of the i2c client structure
908 * @client: the client being referenced
910 * Each live reference to a client should be refcounted. The driver model does
911 * that automatically as part of driver binding, so that most drivers don't
912 * need to do this explicitly: they hold a reference until they're unbound
913 * from the device.
915 * A pointer to the client with the incremented reference counter is returned.
917 struct i2c_client *i2c_use_client(struct i2c_client *client)
919 if (client && get_device(&client->dev))
920 return client;
921 return NULL;
923 EXPORT_SYMBOL(i2c_use_client);
926 * i2c_release_client - release a use of the i2c client structure
927 * @client: the client being no longer referenced
929 * Must be called when a user of a client is finished with it.
931 void i2c_release_client(struct i2c_client *client)
933 if (client)
934 put_device(&client->dev);
936 EXPORT_SYMBOL(i2c_release_client);
938 struct i2c_cmd_arg {
939 unsigned cmd;
940 void *arg;
943 static int i2c_cmd(struct device *dev, void *_arg)
945 struct i2c_client *client = i2c_verify_client(dev);
946 struct i2c_cmd_arg *arg = _arg;
948 if (client && client->driver && client->driver->command)
949 client->driver->command(client, arg->cmd, arg->arg);
950 return 0;
953 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
955 struct i2c_cmd_arg cmd_arg;
957 cmd_arg.cmd = cmd;
958 cmd_arg.arg = arg;
959 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
961 EXPORT_SYMBOL(i2c_clients_command);
963 static int __init i2c_init(void)
965 int retval;
967 retval = bus_register(&i2c_bus_type);
968 if (retval)
969 return retval;
970 retval = class_register(&i2c_adapter_class);
971 if (retval)
972 goto bus_err;
973 retval = i2c_add_driver(&dummy_driver);
974 if (retval)
975 goto class_err;
976 return 0;
978 class_err:
979 class_unregister(&i2c_adapter_class);
980 bus_err:
981 bus_unregister(&i2c_bus_type);
982 return retval;
985 static void __exit i2c_exit(void)
987 i2c_del_driver(&dummy_driver);
988 class_unregister(&i2c_adapter_class);
989 bus_unregister(&i2c_bus_type);
992 /* We must initialize early, because some subsystems register i2c drivers
993 * in subsys_initcall() code, but are linked (and initialized) before i2c.
995 postcore_initcall(i2c_init);
996 module_exit(i2c_exit);
998 /* ----------------------------------------------------
999 * the functional interface to the i2c busses.
1000 * ----------------------------------------------------
1004 * i2c_transfer - execute a single or combined I2C message
1005 * @adap: Handle to I2C bus
1006 * @msgs: One or more messages to execute before STOP is issued to
1007 * terminate the operation; each message begins with a START.
1008 * @num: Number of messages to be executed.
1010 * Returns negative errno, else the number of messages executed.
1012 * Note that there is no requirement that each message be sent to
1013 * the same slave address, although that is the most common model.
1015 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1017 unsigned long orig_jiffies;
1018 int ret, try;
1020 /* REVISIT the fault reporting model here is weak:
1022 * - When we get an error after receiving N bytes from a slave,
1023 * there is no way to report "N".
1025 * - When we get a NAK after transmitting N bytes to a slave,
1026 * there is no way to report "N" ... or to let the master
1027 * continue executing the rest of this combined message, if
1028 * that's the appropriate response.
1030 * - When for example "num" is two and we successfully complete
1031 * the first message but get an error part way through the
1032 * second, it's unclear whether that should be reported as
1033 * one (discarding status on the second message) or errno
1034 * (discarding status on the first one).
1037 if (adap->algo->master_xfer) {
1038 #ifdef DEBUG
1039 for (ret = 0; ret < num; ret++) {
1040 dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
1041 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
1042 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
1043 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
1045 #endif
1047 if (in_atomic() || irqs_disabled()) {
1048 ret = mutex_trylock(&adap->bus_lock);
1049 if (!ret)
1050 /* I2C activity is ongoing. */
1051 return -EAGAIN;
1052 } else {
1053 mutex_lock_nested(&adap->bus_lock, adap->level);
1056 /* Retry automatically on arbitration loss */
1057 orig_jiffies = jiffies;
1058 for (ret = 0, try = 0; try <= adap->retries; try++) {
1059 ret = adap->algo->master_xfer(adap, msgs, num);
1060 if (ret != -EAGAIN)
1061 break;
1062 if (time_after(jiffies, orig_jiffies + adap->timeout))
1063 break;
1065 mutex_unlock(&adap->bus_lock);
1067 return ret;
1068 } else {
1069 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
1070 return -EOPNOTSUPP;
1073 EXPORT_SYMBOL(i2c_transfer);
1076 * i2c_master_send - issue a single I2C message in master transmit mode
1077 * @client: Handle to slave device
1078 * @buf: Data that will be written to the slave
1079 * @count: How many bytes to write
1081 * Returns negative errno, or else the number of bytes written.
1083 int i2c_master_send(struct i2c_client *client,const char *buf ,int count)
1085 int ret;
1086 struct i2c_adapter *adap=client->adapter;
1087 struct i2c_msg msg;
1089 msg.addr = client->addr;
1090 msg.flags = client->flags & I2C_M_TEN;
1091 msg.len = count;
1092 msg.buf = (char *)buf;
1094 ret = i2c_transfer(adap, &msg, 1);
1096 /* If everything went ok (i.e. 1 msg transmitted), return #bytes
1097 transmitted, else error code. */
1098 return (ret == 1) ? count : ret;
1100 EXPORT_SYMBOL(i2c_master_send);
1103 * i2c_master_recv - issue a single I2C message in master receive mode
1104 * @client: Handle to slave device
1105 * @buf: Where to store data read from slave
1106 * @count: How many bytes to read
1108 * Returns negative errno, or else the number of bytes read.
1110 int i2c_master_recv(struct i2c_client *client, char *buf ,int count)
1112 struct i2c_adapter *adap=client->adapter;
1113 struct i2c_msg msg;
1114 int ret;
1116 msg.addr = client->addr;
1117 msg.flags = client->flags & I2C_M_TEN;
1118 msg.flags |= I2C_M_RD;
1119 msg.len = count;
1120 msg.buf = buf;
1122 ret = i2c_transfer(adap, &msg, 1);
1124 /* If everything went ok (i.e. 1 msg transmitted), return #bytes
1125 transmitted, else error code. */
1126 return (ret == 1) ? count : ret;
1128 EXPORT_SYMBOL(i2c_master_recv);
1130 /* ----------------------------------------------------
1131 * the i2c address scanning function
1132 * Will not work for 10-bit addresses!
1133 * ----------------------------------------------------
1136 static int i2c_detect_address(struct i2c_client *temp_client, int kind,
1137 struct i2c_driver *driver)
1139 struct i2c_board_info info;
1140 struct i2c_adapter *adapter = temp_client->adapter;
1141 int addr = temp_client->addr;
1142 int err;
1144 /* Make sure the address is valid */
1145 if (addr < 0x03 || addr > 0x77) {
1146 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
1147 addr);
1148 return -EINVAL;
1151 /* Skip if already in use */
1152 if (i2c_check_addr(adapter, addr))
1153 return 0;
1155 /* Make sure there is something at this address, unless forced */
1156 if (kind < 0) {
1157 if (i2c_smbus_xfer(adapter, addr, 0, 0, 0,
1158 I2C_SMBUS_QUICK, NULL) < 0)
1159 return 0;
1161 /* prevent 24RF08 corruption */
1162 if ((addr & ~0x0f) == 0x50)
1163 i2c_smbus_xfer(adapter, addr, 0, 0, 0,
1164 I2C_SMBUS_QUICK, NULL);
1167 /* Finally call the custom detection function */
1168 memset(&info, 0, sizeof(struct i2c_board_info));
1169 info.addr = addr;
1170 err = driver->detect(temp_client, kind, &info);
1171 if (err) {
1172 /* -ENODEV is returned if the detection fails. We catch it
1173 here as this isn't an error. */
1174 return err == -ENODEV ? 0 : err;
1177 /* Consistency check */
1178 if (info.type[0] == '\0') {
1179 dev_err(&adapter->dev, "%s detection function provided "
1180 "no name for 0x%x\n", driver->driver.name,
1181 addr);
1182 } else {
1183 struct i2c_client *client;
1185 /* Detection succeeded, instantiate the device */
1186 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
1187 info.type, info.addr);
1188 client = i2c_new_device(adapter, &info);
1189 if (client)
1190 list_add_tail(&client->detected, &driver->clients);
1191 else
1192 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
1193 info.type, info.addr);
1195 return 0;
1198 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
1200 const struct i2c_client_address_data *address_data;
1201 struct i2c_client *temp_client;
1202 int i, err = 0;
1203 int adap_id = i2c_adapter_id(adapter);
1205 address_data = driver->address_data;
1206 if (!driver->detect || !address_data)
1207 return 0;
1209 /* Set up a temporary client to help detect callback */
1210 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
1211 if (!temp_client)
1212 return -ENOMEM;
1213 temp_client->adapter = adapter;
1215 /* Force entries are done first, and are not affected by ignore
1216 entries */
1217 if (address_data->forces) {
1218 const unsigned short * const *forces = address_data->forces;
1219 int kind;
1221 for (kind = 0; forces[kind]; kind++) {
1222 for (i = 0; forces[kind][i] != I2C_CLIENT_END;
1223 i += 2) {
1224 if (forces[kind][i] == adap_id
1225 || forces[kind][i] == ANY_I2C_BUS) {
1226 dev_dbg(&adapter->dev, "found force "
1227 "parameter for adapter %d, "
1228 "addr 0x%02x, kind %d\n",
1229 adap_id, forces[kind][i + 1],
1230 kind);
1231 temp_client->addr = forces[kind][i + 1];
1232 err = i2c_detect_address(temp_client,
1233 kind, driver);
1234 if (err)
1235 goto exit_free;
1241 /* Stop here if the classes do not match */
1242 if (!(adapter->class & driver->class))
1243 goto exit_free;
1245 /* Stop here if we can't use SMBUS_QUICK */
1246 if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_QUICK)) {
1247 if (address_data->probe[0] == I2C_CLIENT_END
1248 && address_data->normal_i2c[0] == I2C_CLIENT_END)
1249 goto exit_free;
1251 dev_warn(&adapter->dev, "SMBus Quick command not supported, "
1252 "can't probe for chips\n");
1253 err = -EOPNOTSUPP;
1254 goto exit_free;
1257 /* Probe entries are done second, and are not affected by ignore
1258 entries either */
1259 for (i = 0; address_data->probe[i] != I2C_CLIENT_END; i += 2) {
1260 if (address_data->probe[i] == adap_id
1261 || address_data->probe[i] == ANY_I2C_BUS) {
1262 dev_dbg(&adapter->dev, "found probe parameter for "
1263 "adapter %d, addr 0x%02x\n", adap_id,
1264 address_data->probe[i + 1]);
1265 temp_client->addr = address_data->probe[i + 1];
1266 err = i2c_detect_address(temp_client, -1, driver);
1267 if (err)
1268 goto exit_free;
1272 /* Normal entries are done last, unless shadowed by an ignore entry */
1273 for (i = 0; address_data->normal_i2c[i] != I2C_CLIENT_END; i += 1) {
1274 int j, ignore;
1276 ignore = 0;
1277 for (j = 0; address_data->ignore[j] != I2C_CLIENT_END;
1278 j += 2) {
1279 if ((address_data->ignore[j] == adap_id ||
1280 address_data->ignore[j] == ANY_I2C_BUS)
1281 && address_data->ignore[j + 1]
1282 == address_data->normal_i2c[i]) {
1283 dev_dbg(&adapter->dev, "found ignore "
1284 "parameter for adapter %d, "
1285 "addr 0x%02x\n", adap_id,
1286 address_data->ignore[j + 1]);
1287 ignore = 1;
1288 break;
1291 if (ignore)
1292 continue;
1294 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
1295 "addr 0x%02x\n", adap_id,
1296 address_data->normal_i2c[i]);
1297 temp_client->addr = address_data->normal_i2c[i];
1298 err = i2c_detect_address(temp_client, -1, driver);
1299 if (err)
1300 goto exit_free;
1303 exit_free:
1304 kfree(temp_client);
1305 return err;
1308 struct i2c_client *
1309 i2c_new_probed_device(struct i2c_adapter *adap,
1310 struct i2c_board_info *info,
1311 unsigned short const *addr_list)
1313 int i;
1315 /* Stop here if the bus doesn't support probing */
1316 if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE)) {
1317 dev_err(&adap->dev, "Probing not supported\n");
1318 return NULL;
1321 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
1322 /* Check address validity */
1323 if (addr_list[i] < 0x03 || addr_list[i] > 0x77) {
1324 dev_warn(&adap->dev, "Invalid 7-bit address "
1325 "0x%02x\n", addr_list[i]);
1326 continue;
1329 /* Check address availability */
1330 if (i2c_check_addr(adap, addr_list[i])) {
1331 dev_dbg(&adap->dev, "Address 0x%02x already in "
1332 "use, not probing\n", addr_list[i]);
1333 continue;
1336 /* Test address responsiveness
1337 The default probe method is a quick write, but it is known
1338 to corrupt the 24RF08 EEPROMs due to a state machine bug,
1339 and could also irreversibly write-protect some EEPROMs, so
1340 for address ranges 0x30-0x37 and 0x50-0x5f, we use a byte
1341 read instead. Also, some bus drivers don't implement
1342 quick write, so we fallback to a byte read it that case
1343 too. */
1344 if ((addr_list[i] & ~0x07) == 0x30
1345 || (addr_list[i] & ~0x0f) == 0x50
1346 || !i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK)) {
1347 union i2c_smbus_data data;
1349 if (i2c_smbus_xfer(adap, addr_list[i], 0,
1350 I2C_SMBUS_READ, 0,
1351 I2C_SMBUS_BYTE, &data) >= 0)
1352 break;
1353 } else {
1354 if (i2c_smbus_xfer(adap, addr_list[i], 0,
1355 I2C_SMBUS_WRITE, 0,
1356 I2C_SMBUS_QUICK, NULL) >= 0)
1357 break;
1361 if (addr_list[i] == I2C_CLIENT_END) {
1362 dev_dbg(&adap->dev, "Probing failed, no device found\n");
1363 return NULL;
1366 info->addr = addr_list[i];
1367 return i2c_new_device(adap, info);
1369 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
1371 struct i2c_adapter* i2c_get_adapter(int id)
1373 struct i2c_adapter *adapter;
1375 mutex_lock(&core_lock);
1376 adapter = idr_find(&i2c_adapter_idr, id);
1377 if (adapter && !try_module_get(adapter->owner))
1378 adapter = NULL;
1380 mutex_unlock(&core_lock);
1381 return adapter;
1383 EXPORT_SYMBOL(i2c_get_adapter);
1385 void i2c_put_adapter(struct i2c_adapter *adap)
1387 module_put(adap->owner);
1389 EXPORT_SYMBOL(i2c_put_adapter);
1391 /* The SMBus parts */
1393 #define POLY (0x1070U << 3)
1394 static u8 crc8(u16 data)
1396 int i;
1398 for(i = 0; i < 8; i++) {
1399 if (data & 0x8000)
1400 data = data ^ POLY;
1401 data = data << 1;
1403 return (u8)(data >> 8);
1406 /* Incremental CRC8 over count bytes in the array pointed to by p */
1407 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
1409 int i;
1411 for(i = 0; i < count; i++)
1412 crc = crc8((crc ^ p[i]) << 8);
1413 return crc;
1416 /* Assume a 7-bit address, which is reasonable for SMBus */
1417 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
1419 /* The address will be sent first */
1420 u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
1421 pec = i2c_smbus_pec(pec, &addr, 1);
1423 /* The data buffer follows */
1424 return i2c_smbus_pec(pec, msg->buf, msg->len);
1427 /* Used for write only transactions */
1428 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
1430 msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
1431 msg->len++;
1434 /* Return <0 on CRC error
1435 If there was a write before this read (most cases) we need to take the
1436 partial CRC from the write part into account.
1437 Note that this function does modify the message (we need to decrease the
1438 message length to hide the CRC byte from the caller). */
1439 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
1441 u8 rpec = msg->buf[--msg->len];
1442 cpec = i2c_smbus_msg_pec(cpec, msg);
1444 if (rpec != cpec) {
1445 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
1446 rpec, cpec);
1447 return -EBADMSG;
1449 return 0;
1453 * i2c_smbus_read_byte - SMBus "receive byte" protocol
1454 * @client: Handle to slave device
1456 * This executes the SMBus "receive byte" protocol, returning negative errno
1457 * else the byte received from the device.
1459 s32 i2c_smbus_read_byte(struct i2c_client *client)
1461 union i2c_smbus_data data;
1462 int status;
1464 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1465 I2C_SMBUS_READ, 0,
1466 I2C_SMBUS_BYTE, &data);
1467 return (status < 0) ? status : data.byte;
1469 EXPORT_SYMBOL(i2c_smbus_read_byte);
1472 * i2c_smbus_write_byte - SMBus "send byte" protocol
1473 * @client: Handle to slave device
1474 * @value: Byte to be sent
1476 * This executes the SMBus "send byte" protocol, returning negative errno
1477 * else zero on success.
1479 s32 i2c_smbus_write_byte(struct i2c_client *client, u8 value)
1481 return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1482 I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
1484 EXPORT_SYMBOL(i2c_smbus_write_byte);
1487 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
1488 * @client: Handle to slave device
1489 * @command: Byte interpreted by slave
1491 * This executes the SMBus "read byte" protocol, returning negative errno
1492 * else a data byte received from the device.
1494 s32 i2c_smbus_read_byte_data(struct i2c_client *client, u8 command)
1496 union i2c_smbus_data data;
1497 int status;
1499 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1500 I2C_SMBUS_READ, command,
1501 I2C_SMBUS_BYTE_DATA, &data);
1502 return (status < 0) ? status : data.byte;
1504 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
1507 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
1508 * @client: Handle to slave device
1509 * @command: Byte interpreted by slave
1510 * @value: Byte being written
1512 * This executes the SMBus "write byte" protocol, returning negative errno
1513 * else zero on success.
1515 s32 i2c_smbus_write_byte_data(struct i2c_client *client, u8 command, u8 value)
1517 union i2c_smbus_data data;
1518 data.byte = value;
1519 return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1520 I2C_SMBUS_WRITE,command,
1521 I2C_SMBUS_BYTE_DATA,&data);
1523 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
1526 * i2c_smbus_read_word_data - SMBus "read word" protocol
1527 * @client: Handle to slave device
1528 * @command: Byte interpreted by slave
1530 * This executes the SMBus "read word" protocol, returning negative errno
1531 * else a 16-bit unsigned "word" received from the device.
1533 s32 i2c_smbus_read_word_data(struct i2c_client *client, u8 command)
1535 union i2c_smbus_data data;
1536 int status;
1538 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1539 I2C_SMBUS_READ, command,
1540 I2C_SMBUS_WORD_DATA, &data);
1541 return (status < 0) ? status : data.word;
1543 EXPORT_SYMBOL(i2c_smbus_read_word_data);
1546 * i2c_smbus_write_word_data - SMBus "write word" protocol
1547 * @client: Handle to slave device
1548 * @command: Byte interpreted by slave
1549 * @value: 16-bit "word" being written
1551 * This executes the SMBus "write word" protocol, returning negative errno
1552 * else zero on success.
1554 s32 i2c_smbus_write_word_data(struct i2c_client *client, u8 command, u16 value)
1556 union i2c_smbus_data data;
1557 data.word = value;
1558 return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1559 I2C_SMBUS_WRITE,command,
1560 I2C_SMBUS_WORD_DATA,&data);
1562 EXPORT_SYMBOL(i2c_smbus_write_word_data);
1565 * i2c_smbus_process_call - SMBus "process call" protocol
1566 * @client: Handle to slave device
1567 * @command: Byte interpreted by slave
1568 * @value: 16-bit "word" being written
1570 * This executes the SMBus "process call" protocol, returning negative errno
1571 * else a 16-bit unsigned "word" received from the device.
1573 s32 i2c_smbus_process_call(struct i2c_client *client, u8 command, u16 value)
1575 union i2c_smbus_data data;
1576 int status;
1577 data.word = value;
1579 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1580 I2C_SMBUS_WRITE, command,
1581 I2C_SMBUS_PROC_CALL, &data);
1582 return (status < 0) ? status : data.word;
1584 EXPORT_SYMBOL(i2c_smbus_process_call);
1587 * i2c_smbus_read_block_data - SMBus "block read" protocol
1588 * @client: Handle to slave device
1589 * @command: Byte interpreted by slave
1590 * @values: Byte array into which data will be read; big enough to hold
1591 * the data returned by the slave. SMBus allows at most 32 bytes.
1593 * This executes the SMBus "block read" protocol, returning negative errno
1594 * else the number of data bytes in the slave's response.
1596 * Note that using this function requires that the client's adapter support
1597 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality. Not all adapter drivers
1598 * support this; its emulation through I2C messaging relies on a specific
1599 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
1601 s32 i2c_smbus_read_block_data(struct i2c_client *client, u8 command,
1602 u8 *values)
1604 union i2c_smbus_data data;
1605 int status;
1607 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1608 I2C_SMBUS_READ, command,
1609 I2C_SMBUS_BLOCK_DATA, &data);
1610 if (status)
1611 return status;
1613 memcpy(values, &data.block[1], data.block[0]);
1614 return data.block[0];
1616 EXPORT_SYMBOL(i2c_smbus_read_block_data);
1619 * i2c_smbus_write_block_data - SMBus "block write" protocol
1620 * @client: Handle to slave device
1621 * @command: Byte interpreted by slave
1622 * @length: Size of data block; SMBus allows at most 32 bytes
1623 * @values: Byte array which will be written.
1625 * This executes the SMBus "block write" protocol, returning negative errno
1626 * else zero on success.
1628 s32 i2c_smbus_write_block_data(struct i2c_client *client, u8 command,
1629 u8 length, const u8 *values)
1631 union i2c_smbus_data data;
1633 if (length > I2C_SMBUS_BLOCK_MAX)
1634 length = I2C_SMBUS_BLOCK_MAX;
1635 data.block[0] = length;
1636 memcpy(&data.block[1], values, length);
1637 return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1638 I2C_SMBUS_WRITE,command,
1639 I2C_SMBUS_BLOCK_DATA,&data);
1641 EXPORT_SYMBOL(i2c_smbus_write_block_data);
1643 /* Returns the number of read bytes */
1644 s32 i2c_smbus_read_i2c_block_data(struct i2c_client *client, u8 command,
1645 u8 length, u8 *values)
1647 union i2c_smbus_data data;
1648 int status;
1650 if (length > I2C_SMBUS_BLOCK_MAX)
1651 length = I2C_SMBUS_BLOCK_MAX;
1652 data.block[0] = length;
1653 status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1654 I2C_SMBUS_READ, command,
1655 I2C_SMBUS_I2C_BLOCK_DATA, &data);
1656 if (status < 0)
1657 return status;
1659 memcpy(values, &data.block[1], data.block[0]);
1660 return data.block[0];
1662 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
1664 s32 i2c_smbus_write_i2c_block_data(struct i2c_client *client, u8 command,
1665 u8 length, const u8 *values)
1667 union i2c_smbus_data data;
1669 if (length > I2C_SMBUS_BLOCK_MAX)
1670 length = I2C_SMBUS_BLOCK_MAX;
1671 data.block[0] = length;
1672 memcpy(data.block + 1, values, length);
1673 return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1674 I2C_SMBUS_WRITE, command,
1675 I2C_SMBUS_I2C_BLOCK_DATA, &data);
1677 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
1679 /* Simulate a SMBus command using the i2c protocol
1680 No checking of parameters is done! */
1681 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter * adapter, u16 addr,
1682 unsigned short flags,
1683 char read_write, u8 command, int size,
1684 union i2c_smbus_data * data)
1686 /* So we need to generate a series of msgs. In the case of writing, we
1687 need to use only one message; when reading, we need two. We initialize
1688 most things with sane defaults, to keep the code below somewhat
1689 simpler. */
1690 unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
1691 unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
1692 int num = read_write == I2C_SMBUS_READ?2:1;
1693 struct i2c_msg msg[2] = { { addr, flags, 1, msgbuf0 },
1694 { addr, flags | I2C_M_RD, 0, msgbuf1 }
1696 int i;
1697 u8 partial_pec = 0;
1698 int status;
1700 msgbuf0[0] = command;
1701 switch(size) {
1702 case I2C_SMBUS_QUICK:
1703 msg[0].len = 0;
1704 /* Special case: The read/write field is used as data */
1705 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
1706 I2C_M_RD : 0);
1707 num = 1;
1708 break;
1709 case I2C_SMBUS_BYTE:
1710 if (read_write == I2C_SMBUS_READ) {
1711 /* Special case: only a read! */
1712 msg[0].flags = I2C_M_RD | flags;
1713 num = 1;
1715 break;
1716 case I2C_SMBUS_BYTE_DATA:
1717 if (read_write == I2C_SMBUS_READ)
1718 msg[1].len = 1;
1719 else {
1720 msg[0].len = 2;
1721 msgbuf0[1] = data->byte;
1723 break;
1724 case I2C_SMBUS_WORD_DATA:
1725 if (read_write == I2C_SMBUS_READ)
1726 msg[1].len = 2;
1727 else {
1728 msg[0].len=3;
1729 msgbuf0[1] = data->word & 0xff;
1730 msgbuf0[2] = data->word >> 8;
1732 break;
1733 case I2C_SMBUS_PROC_CALL:
1734 num = 2; /* Special case */
1735 read_write = I2C_SMBUS_READ;
1736 msg[0].len = 3;
1737 msg[1].len = 2;
1738 msgbuf0[1] = data->word & 0xff;
1739 msgbuf0[2] = data->word >> 8;
1740 break;
1741 case I2C_SMBUS_BLOCK_DATA:
1742 if (read_write == I2C_SMBUS_READ) {
1743 msg[1].flags |= I2C_M_RECV_LEN;
1744 msg[1].len = 1; /* block length will be added by
1745 the underlying bus driver */
1746 } else {
1747 msg[0].len = data->block[0] + 2;
1748 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
1749 dev_err(&adapter->dev,
1750 "Invalid block write size %d\n",
1751 data->block[0]);
1752 return -EINVAL;
1754 for (i = 1; i < msg[0].len; i++)
1755 msgbuf0[i] = data->block[i-1];
1757 break;
1758 case I2C_SMBUS_BLOCK_PROC_CALL:
1759 num = 2; /* Another special case */
1760 read_write = I2C_SMBUS_READ;
1761 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
1762 dev_err(&adapter->dev,
1763 "Invalid block write size %d\n",
1764 data->block[0]);
1765 return -EINVAL;
1767 msg[0].len = data->block[0] + 2;
1768 for (i = 1; i < msg[0].len; i++)
1769 msgbuf0[i] = data->block[i-1];
1770 msg[1].flags |= I2C_M_RECV_LEN;
1771 msg[1].len = 1; /* block length will be added by
1772 the underlying bus driver */
1773 break;
1774 case I2C_SMBUS_I2C_BLOCK_DATA:
1775 if (read_write == I2C_SMBUS_READ) {
1776 msg[1].len = data->block[0];
1777 } else {
1778 msg[0].len = data->block[0] + 1;
1779 if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
1780 dev_err(&adapter->dev,
1781 "Invalid block write size %d\n",
1782 data->block[0]);
1783 return -EINVAL;
1785 for (i = 1; i <= data->block[0]; i++)
1786 msgbuf0[i] = data->block[i];
1788 break;
1789 default:
1790 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
1791 return -EOPNOTSUPP;
1794 i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
1795 && size != I2C_SMBUS_I2C_BLOCK_DATA);
1796 if (i) {
1797 /* Compute PEC if first message is a write */
1798 if (!(msg[0].flags & I2C_M_RD)) {
1799 if (num == 1) /* Write only */
1800 i2c_smbus_add_pec(&msg[0]);
1801 else /* Write followed by read */
1802 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
1804 /* Ask for PEC if last message is a read */
1805 if (msg[num-1].flags & I2C_M_RD)
1806 msg[num-1].len++;
1809 status = i2c_transfer(adapter, msg, num);
1810 if (status < 0)
1811 return status;
1813 /* Check PEC if last message is a read */
1814 if (i && (msg[num-1].flags & I2C_M_RD)) {
1815 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
1816 if (status < 0)
1817 return status;
1820 if (read_write == I2C_SMBUS_READ)
1821 switch(size) {
1822 case I2C_SMBUS_BYTE:
1823 data->byte = msgbuf0[0];
1824 break;
1825 case I2C_SMBUS_BYTE_DATA:
1826 data->byte = msgbuf1[0];
1827 break;
1828 case I2C_SMBUS_WORD_DATA:
1829 case I2C_SMBUS_PROC_CALL:
1830 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
1831 break;
1832 case I2C_SMBUS_I2C_BLOCK_DATA:
1833 for (i = 0; i < data->block[0]; i++)
1834 data->block[i+1] = msgbuf1[i];
1835 break;
1836 case I2C_SMBUS_BLOCK_DATA:
1837 case I2C_SMBUS_BLOCK_PROC_CALL:
1838 for (i = 0; i < msgbuf1[0] + 1; i++)
1839 data->block[i] = msgbuf1[i];
1840 break;
1842 return 0;
1846 * i2c_smbus_xfer - execute SMBus protocol operations
1847 * @adapter: Handle to I2C bus
1848 * @addr: Address of SMBus slave on that bus
1849 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
1850 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
1851 * @command: Byte interpreted by slave, for protocols which use such bytes
1852 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
1853 * @data: Data to be read or written
1855 * This executes an SMBus protocol operation, and returns a negative
1856 * errno code else zero on success.
1858 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
1859 char read_write, u8 command, int protocol,
1860 union i2c_smbus_data *data)
1862 unsigned long orig_jiffies;
1863 int try;
1864 s32 res;
1866 flags &= I2C_M_TEN | I2C_CLIENT_PEC;
1868 if (adapter->algo->smbus_xfer) {
1869 mutex_lock(&adapter->bus_lock);
1871 /* Retry automatically on arbitration loss */
1872 orig_jiffies = jiffies;
1873 for (res = 0, try = 0; try <= adapter->retries; try++) {
1874 res = adapter->algo->smbus_xfer(adapter, addr, flags,
1875 read_write, command,
1876 protocol, data);
1877 if (res != -EAGAIN)
1878 break;
1879 if (time_after(jiffies,
1880 orig_jiffies + adapter->timeout))
1881 break;
1883 mutex_unlock(&adapter->bus_lock);
1884 } else
1885 res = i2c_smbus_xfer_emulated(adapter,addr,flags,read_write,
1886 command, protocol, data);
1888 return res;
1890 EXPORT_SYMBOL(i2c_smbus_xfer);
1892 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
1893 MODULE_DESCRIPTION("I2C-Bus main module");
1894 MODULE_LICENSE("GPL");