d6cc58abf3ff0b648b4e188a1e0797549c1d1eb0
[safe/jmp/linux-2.6] / drivers / i2c / i2c-core.c
1 /* i2c-core.c - a device driver for the iic-bus interface                    */
2 /* ------------------------------------------------------------------------- */
3 /*   Copyright (C) 1995-99 Simon G. Vogl
4
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.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
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 /* ------------------------------------------------------------------------- */
19
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> */
24
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/platform_device.h>
33 #include <linux/mutex.h>
34 #include <linux/completion.h>
35 #include <linux/hardirq.h>
36 #include <linux/irqflags.h>
37 #include <asm/uaccess.h>
38
39 #include "i2c-core.h"
40
41
42 static DEFINE_MUTEX(core_lock);
43 static DEFINE_IDR(i2c_adapter_idr);
44
45 #define is_newstyle_driver(d) ((d)->probe || (d)->remove)
46
47 /* ------------------------------------------------------------------------- */
48
49 static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
50                                                 const struct i2c_client *client)
51 {
52         while (id->name[0]) {
53                 if (strcmp(client->name, id->name) == 0)
54                         return id;
55                 id++;
56         }
57         return NULL;
58 }
59
60 static int i2c_device_match(struct device *dev, struct device_driver *drv)
61 {
62         struct i2c_client       *client = to_i2c_client(dev);
63         struct i2c_driver       *driver = to_i2c_driver(drv);
64
65         /* make legacy i2c drivers bypass driver model probing entirely;
66          * such drivers scan each i2c adapter/bus themselves.
67          */
68         if (!is_newstyle_driver(driver))
69                 return 0;
70
71         /* match on an id table if there is one */
72         if (driver->id_table)
73                 return i2c_match_id(driver->id_table, client) != NULL;
74
75         return 0;
76 }
77
78 #ifdef  CONFIG_HOTPLUG
79
80 /* uevent helps with hotplug: modprobe -q $(MODALIAS) */
81 static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
82 {
83         struct i2c_client       *client = to_i2c_client(dev);
84
85         /* by definition, legacy drivers can't hotplug */
86         if (dev->driver)
87                 return 0;
88
89         if (add_uevent_var(env, "MODALIAS=%s%s",
90                            I2C_MODULE_PREFIX, client->name))
91                 return -ENOMEM;
92         dev_dbg(dev, "uevent\n");
93         return 0;
94 }
95
96 #else
97 #define i2c_device_uevent       NULL
98 #endif  /* CONFIG_HOTPLUG */
99
100 static int i2c_device_probe(struct device *dev)
101 {
102         struct i2c_client       *client = to_i2c_client(dev);
103         struct i2c_driver       *driver = to_i2c_driver(dev->driver);
104         int status;
105
106         if (!driver->probe || !driver->id_table)
107                 return -ENODEV;
108         client->driver = driver;
109         dev_dbg(dev, "probe\n");
110
111         status = driver->probe(client, i2c_match_id(driver->id_table, client));
112         if (status)
113                 client->driver = NULL;
114         return status;
115 }
116
117 static int i2c_device_remove(struct device *dev)
118 {
119         struct i2c_client       *client = to_i2c_client(dev);
120         struct i2c_driver       *driver;
121         int                     status;
122
123         if (!dev->driver)
124                 return 0;
125
126         driver = to_i2c_driver(dev->driver);
127         if (driver->remove) {
128                 dev_dbg(dev, "remove\n");
129                 status = driver->remove(client);
130         } else {
131                 dev->driver = NULL;
132                 status = 0;
133         }
134         if (status == 0)
135                 client->driver = NULL;
136         return status;
137 }
138
139 static void i2c_device_shutdown(struct device *dev)
140 {
141         struct i2c_driver *driver;
142
143         if (!dev->driver)
144                 return;
145         driver = to_i2c_driver(dev->driver);
146         if (driver->shutdown)
147                 driver->shutdown(to_i2c_client(dev));
148 }
149
150 static int i2c_device_suspend(struct device * dev, pm_message_t mesg)
151 {
152         struct i2c_driver *driver;
153
154         if (!dev->driver)
155                 return 0;
156         driver = to_i2c_driver(dev->driver);
157         if (!driver->suspend)
158                 return 0;
159         return driver->suspend(to_i2c_client(dev), mesg);
160 }
161
162 static int i2c_device_resume(struct device * dev)
163 {
164         struct i2c_driver *driver;
165
166         if (!dev->driver)
167                 return 0;
168         driver = to_i2c_driver(dev->driver);
169         if (!driver->resume)
170                 return 0;
171         return driver->resume(to_i2c_client(dev));
172 }
173
174 static void i2c_client_release(struct device *dev)
175 {
176         struct i2c_client *client = to_i2c_client(dev);
177         complete(&client->released);
178 }
179
180 static void i2c_client_dev_release(struct device *dev)
181 {
182         kfree(to_i2c_client(dev));
183 }
184
185 static ssize_t show_client_name(struct device *dev, struct device_attribute *attr, char *buf)
186 {
187         struct i2c_client *client = to_i2c_client(dev);
188         return sprintf(buf, "%s\n", client->name);
189 }
190
191 static ssize_t show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
192 {
193         struct i2c_client *client = to_i2c_client(dev);
194         return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
195 }
196
197 static struct device_attribute i2c_dev_attrs[] = {
198         __ATTR(name, S_IRUGO, show_client_name, NULL),
199         /* modalias helps coldplug:  modprobe $(cat .../modalias) */
200         __ATTR(modalias, S_IRUGO, show_modalias, NULL),
201         { },
202 };
203
204 static struct bus_type i2c_bus_type = {
205         .name           = "i2c",
206         .dev_attrs      = i2c_dev_attrs,
207         .match          = i2c_device_match,
208         .uevent         = i2c_device_uevent,
209         .probe          = i2c_device_probe,
210         .remove         = i2c_device_remove,
211         .shutdown       = i2c_device_shutdown,
212         .suspend        = i2c_device_suspend,
213         .resume         = i2c_device_resume,
214 };
215
216
217 /**
218  * i2c_verify_client - return parameter as i2c_client, or NULL
219  * @dev: device, probably from some driver model iterator
220  *
221  * When traversing the driver model tree, perhaps using driver model
222  * iterators like @device_for_each_child(), you can't assume very much
223  * about the nodes you find.  Use this function to avoid oopses caused
224  * by wrongly treating some non-I2C device as an i2c_client.
225  */
226 struct i2c_client *i2c_verify_client(struct device *dev)
227 {
228         return (dev->bus == &i2c_bus_type)
229                         ? to_i2c_client(dev)
230                         : NULL;
231 }
232 EXPORT_SYMBOL(i2c_verify_client);
233
234
235 /**
236  * i2c_new_device - instantiate an i2c device for use with a new style driver
237  * @adap: the adapter managing the device
238  * @info: describes one I2C device; bus_num is ignored
239  * Context: can sleep
240  *
241  * Create a device to work with a new style i2c driver, where binding is
242  * handled through driver model probe()/remove() methods.  This call is not
243  * appropriate for use by mainboad initialization logic, which usually runs
244  * during an arch_initcall() long before any i2c_adapter could exist.
245  *
246  * This returns the new i2c client, which may be saved for later use with
247  * i2c_unregister_device(); or NULL to indicate an error.
248  */
249 struct i2c_client *
250 i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
251 {
252         struct i2c_client       *client;
253         int                     status;
254
255         client = kzalloc(sizeof *client, GFP_KERNEL);
256         if (!client)
257                 return NULL;
258
259         client->adapter = adap;
260
261         client->dev.platform_data = info->platform_data;
262         device_init_wakeup(&client->dev, info->flags & I2C_CLIENT_WAKE);
263
264         client->flags = info->flags & ~I2C_CLIENT_WAKE;
265         client->addr = info->addr;
266         client->irq = info->irq;
267
268         strlcpy(client->name, info->type, sizeof(client->name));
269
270         /* a new style driver may be bound to this device when we
271          * return from this function, or any later moment (e.g. maybe
272          * hotplugging will load the driver module).  and the device
273          * refcount model is the standard driver model one.
274          */
275         status = i2c_attach_client(client);
276         if (status < 0) {
277                 kfree(client);
278                 client = NULL;
279         }
280         return client;
281 }
282 EXPORT_SYMBOL_GPL(i2c_new_device);
283
284
285 /**
286  * i2c_unregister_device - reverse effect of i2c_new_device()
287  * @client: value returned from i2c_new_device()
288  * Context: can sleep
289  */
290 void i2c_unregister_device(struct i2c_client *client)
291 {
292         struct i2c_adapter      *adapter = client->adapter;
293         struct i2c_driver       *driver = client->driver;
294
295         if (driver && !is_newstyle_driver(driver)) {
296                 dev_err(&client->dev, "can't unregister devices "
297                         "with legacy drivers\n");
298                 WARN_ON(1);
299                 return;
300         }
301
302         mutex_lock(&adapter->clist_lock);
303         list_del(&client->list);
304         mutex_unlock(&adapter->clist_lock);
305
306         device_unregister(&client->dev);
307 }
308 EXPORT_SYMBOL_GPL(i2c_unregister_device);
309
310
311 static const struct i2c_device_id dummy_id[] = {
312         { "dummy", 0 },
313         { },
314 };
315
316 static int dummy_probe(struct i2c_client *client,
317                        const struct i2c_device_id *id)
318 {
319         return 0;
320 }
321
322 static int dummy_remove(struct i2c_client *client)
323 {
324         return 0;
325 }
326
327 static struct i2c_driver dummy_driver = {
328         .driver.name    = "dummy",
329         .probe          = dummy_probe,
330         .remove         = dummy_remove,
331         .id_table       = dummy_id,
332 };
333
334 /**
335  * i2c_new_dummy - return a new i2c device bound to a dummy driver
336  * @adapter: the adapter managing the device
337  * @address: seven bit address to be used
338  * Context: can sleep
339  *
340  * This returns an I2C client bound to the "dummy" driver, intended for use
341  * with devices that consume multiple addresses.  Examples of such chips
342  * include various EEPROMS (like 24c04 and 24c08 models).
343  *
344  * These dummy devices have two main uses.  First, most I2C and SMBus calls
345  * except i2c_transfer() need a client handle; the dummy will be that handle.
346  * And second, this prevents the specified address from being bound to a
347  * different driver.
348  *
349  * This returns the new i2c client, which should be saved for later use with
350  * i2c_unregister_device(); or NULL to indicate an error.
351  */
352 struct i2c_client *
353 i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
354 {
355         struct i2c_board_info info = {
356                 I2C_BOARD_INFO("dummy", address),
357         };
358
359         return i2c_new_device(adapter, &info);
360 }
361 EXPORT_SYMBOL_GPL(i2c_new_dummy);
362
363 /* ------------------------------------------------------------------------- */
364
365 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
366
367 static void i2c_adapter_dev_release(struct device *dev)
368 {
369         struct i2c_adapter *adap = to_i2c_adapter(dev);
370         complete(&adap->dev_released);
371 }
372
373 static ssize_t
374 show_adapter_name(struct device *dev, struct device_attribute *attr, char *buf)
375 {
376         struct i2c_adapter *adap = to_i2c_adapter(dev);
377         return sprintf(buf, "%s\n", adap->name);
378 }
379
380 static struct device_attribute i2c_adapter_attrs[] = {
381         __ATTR(name, S_IRUGO, show_adapter_name, NULL),
382         { },
383 };
384
385 static struct class i2c_adapter_class = {
386         .owner                  = THIS_MODULE,
387         .name                   = "i2c-adapter",
388         .dev_attrs              = i2c_adapter_attrs,
389 };
390
391 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
392 {
393         struct i2c_devinfo      *devinfo;
394
395         mutex_lock(&__i2c_board_lock);
396         list_for_each_entry(devinfo, &__i2c_board_list, list) {
397                 if (devinfo->busnum == adapter->nr
398                                 && !i2c_new_device(adapter,
399                                                 &devinfo->board_info))
400                         printk(KERN_ERR "i2c-core: can't create i2c%d-%04x\n",
401                                 i2c_adapter_id(adapter),
402                                 devinfo->board_info.addr);
403         }
404         mutex_unlock(&__i2c_board_lock);
405 }
406
407 static int i2c_do_add_adapter(struct device_driver *d, void *data)
408 {
409         struct i2c_driver *driver = to_i2c_driver(d);
410         struct i2c_adapter *adap = data;
411
412         if (driver->attach_adapter) {
413                 /* We ignore the return code; if it fails, too bad */
414                 driver->attach_adapter(adap);
415         }
416         return 0;
417 }
418
419 static int i2c_register_adapter(struct i2c_adapter *adap)
420 {
421         int res = 0, dummy;
422
423         mutex_init(&adap->bus_lock);
424         mutex_init(&adap->clist_lock);
425         INIT_LIST_HEAD(&adap->clients);
426
427         mutex_lock(&core_lock);
428
429         /* Add the adapter to the driver core.
430          * If the parent pointer is not set up,
431          * we add this adapter to the host bus.
432          */
433         if (adap->dev.parent == NULL) {
434                 adap->dev.parent = &platform_bus;
435                 pr_debug("I2C adapter driver [%s] forgot to specify "
436                          "physical device\n", adap->name);
437         }
438         sprintf(adap->dev.bus_id, "i2c-%d", adap->nr);
439         adap->dev.release = &i2c_adapter_dev_release;
440         adap->dev.class = &i2c_adapter_class;
441         res = device_register(&adap->dev);
442         if (res)
443                 goto out_list;
444
445         dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
446
447         /* create pre-declared device nodes for new-style drivers */
448         if (adap->nr < __i2c_first_dynamic_bus_num)
449                 i2c_scan_static_board_info(adap);
450
451         /* let legacy drivers scan this bus for matching devices */
452         dummy = bus_for_each_drv(&i2c_bus_type, NULL, adap,
453                                  i2c_do_add_adapter);
454
455 out_unlock:
456         mutex_unlock(&core_lock);
457         return res;
458
459 out_list:
460         idr_remove(&i2c_adapter_idr, adap->nr);
461         goto out_unlock;
462 }
463
464 /**
465  * i2c_add_adapter - declare i2c adapter, use dynamic bus number
466  * @adapter: the adapter to add
467  * Context: can sleep
468  *
469  * This routine is used to declare an I2C adapter when its bus number
470  * doesn't matter.  Examples: for I2C adapters dynamically added by
471  * USB links or PCI plugin cards.
472  *
473  * When this returns zero, a new bus number was allocated and stored
474  * in adap->nr, and the specified adapter became available for clients.
475  * Otherwise, a negative errno value is returned.
476  */
477 int i2c_add_adapter(struct i2c_adapter *adapter)
478 {
479         int     id, res = 0;
480
481 retry:
482         if (idr_pre_get(&i2c_adapter_idr, GFP_KERNEL) == 0)
483                 return -ENOMEM;
484
485         mutex_lock(&core_lock);
486         /* "above" here means "above or equal to", sigh */
487         res = idr_get_new_above(&i2c_adapter_idr, adapter,
488                                 __i2c_first_dynamic_bus_num, &id);
489         mutex_unlock(&core_lock);
490
491         if (res < 0) {
492                 if (res == -EAGAIN)
493                         goto retry;
494                 return res;
495         }
496
497         adapter->nr = id;
498         return i2c_register_adapter(adapter);
499 }
500 EXPORT_SYMBOL(i2c_add_adapter);
501
502 /**
503  * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
504  * @adap: the adapter to register (with adap->nr initialized)
505  * Context: can sleep
506  *
507  * This routine is used to declare an I2C adapter when its bus number
508  * matters.  For example, use it for I2C adapters from system-on-chip CPUs,
509  * or otherwise built in to the system's mainboard, and where i2c_board_info
510  * is used to properly configure I2C devices.
511  *
512  * If no devices have pre-been declared for this bus, then be sure to
513  * register the adapter before any dynamically allocated ones.  Otherwise
514  * the required bus ID may not be available.
515  *
516  * When this returns zero, the specified adapter became available for
517  * clients using the bus number provided in adap->nr.  Also, the table
518  * of I2C devices pre-declared using i2c_register_board_info() is scanned,
519  * and the appropriate driver model device nodes are created.  Otherwise, a
520  * negative errno value is returned.
521  */
522 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
523 {
524         int     id;
525         int     status;
526
527         if (adap->nr & ~MAX_ID_MASK)
528                 return -EINVAL;
529
530 retry:
531         if (idr_pre_get(&i2c_adapter_idr, GFP_KERNEL) == 0)
532                 return -ENOMEM;
533
534         mutex_lock(&core_lock);
535         /* "above" here means "above or equal to", sigh;
536          * we need the "equal to" result to force the result
537          */
538         status = idr_get_new_above(&i2c_adapter_idr, adap, adap->nr, &id);
539         if (status == 0 && id != adap->nr) {
540                 status = -EBUSY;
541                 idr_remove(&i2c_adapter_idr, id);
542         }
543         mutex_unlock(&core_lock);
544         if (status == -EAGAIN)
545                 goto retry;
546
547         if (status == 0)
548                 status = i2c_register_adapter(adap);
549         return status;
550 }
551 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
552
553 static int i2c_do_del_adapter(struct device_driver *d, void *data)
554 {
555         struct i2c_driver *driver = to_i2c_driver(d);
556         struct i2c_adapter *adapter = data;
557         int res;
558
559         if (!driver->detach_adapter)
560                 return 0;
561         res = driver->detach_adapter(adapter);
562         if (res)
563                 dev_err(&adapter->dev, "detach_adapter failed (%d) "
564                         "for driver [%s]\n", res, driver->driver.name);
565         return res;
566 }
567
568 /**
569  * i2c_del_adapter - unregister I2C adapter
570  * @adap: the adapter being unregistered
571  * Context: can sleep
572  *
573  * This unregisters an I2C adapter which was previously registered
574  * by @i2c_add_adapter or @i2c_add_numbered_adapter.
575  */
576 int i2c_del_adapter(struct i2c_adapter *adap)
577 {
578         struct i2c_client *client, *_n;
579         int res = 0;
580
581         mutex_lock(&core_lock);
582
583         /* First make sure that this adapter was ever added */
584         if (idr_find(&i2c_adapter_idr, adap->nr) != adap) {
585                 pr_debug("i2c-core: attempting to delete unregistered "
586                          "adapter [%s]\n", adap->name);
587                 res = -EINVAL;
588                 goto out_unlock;
589         }
590
591         /* Tell drivers about this removal */
592         res = bus_for_each_drv(&i2c_bus_type, NULL, adap,
593                                i2c_do_del_adapter);
594         if (res)
595                 goto out_unlock;
596
597         /* detach any active clients. This must be done first, because
598          * it can fail; in which case we give up. */
599         list_for_each_entry_safe(client, _n, &adap->clients, list) {
600                 struct i2c_driver       *driver;
601
602                 driver = client->driver;
603
604                 /* new style, follow standard driver model */
605                 if (!driver || is_newstyle_driver(driver)) {
606                         i2c_unregister_device(client);
607                         continue;
608                 }
609
610                 /* legacy drivers create and remove clients themselves */
611                 if ((res = driver->detach_client(client))) {
612                         dev_err(&adap->dev, "detach_client failed for client "
613                                 "[%s] at address 0x%02x\n", client->name,
614                                 client->addr);
615                         goto out_unlock;
616                 }
617         }
618
619         /* clean up the sysfs representation */
620         init_completion(&adap->dev_released);
621         device_unregister(&adap->dev);
622
623         /* wait for sysfs to drop all references */
624         wait_for_completion(&adap->dev_released);
625
626         /* free bus id */
627         idr_remove(&i2c_adapter_idr, adap->nr);
628
629         dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
630
631  out_unlock:
632         mutex_unlock(&core_lock);
633         return res;
634 }
635 EXPORT_SYMBOL(i2c_del_adapter);
636
637
638 /* ------------------------------------------------------------------------- */
639
640 static int __attach_adapter(struct device *dev, void *data)
641 {
642         struct i2c_adapter *adapter = to_i2c_adapter(dev);
643         struct i2c_driver *driver = data;
644
645         driver->attach_adapter(adapter);
646
647         return 0;
648 }
649
650 /*
651  * An i2c_driver is used with one or more i2c_client (device) nodes to access
652  * i2c slave chips, on a bus instance associated with some i2c_adapter.  There
653  * are two models for binding the driver to its device:  "new style" drivers
654  * follow the standard Linux driver model and just respond to probe() calls
655  * issued if the driver core sees they match(); "legacy" drivers create device
656  * nodes themselves.
657  */
658
659 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
660 {
661         int res;
662
663         /* new style driver methods can't mix with legacy ones */
664         if (is_newstyle_driver(driver)) {
665                 if (driver->attach_adapter || driver->detach_adapter
666                                 || driver->detach_client) {
667                         printk(KERN_WARNING
668                                         "i2c-core: driver [%s] is confused\n",
669                                         driver->driver.name);
670                         return -EINVAL;
671                 }
672         }
673
674         /* add the driver to the list of i2c drivers in the driver core */
675         driver->driver.owner = owner;
676         driver->driver.bus = &i2c_bus_type;
677
678         /* for new style drivers, when registration returns the driver core
679          * will have called probe() for all matching-but-unbound devices.
680          */
681         res = driver_register(&driver->driver);
682         if (res)
683                 return res;
684
685         mutex_lock(&core_lock);
686
687         pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
688
689         /* legacy drivers scan i2c busses directly */
690         if (driver->attach_adapter)
691                 class_for_each_device(&i2c_adapter_class, driver,
692                                       __attach_adapter);
693
694         mutex_unlock(&core_lock);
695         return 0;
696 }
697 EXPORT_SYMBOL(i2c_register_driver);
698
699 static int __detach_adapter(struct device *dev, void *data)
700 {
701         struct i2c_adapter *adapter = to_i2c_adapter(dev);
702         struct i2c_driver *driver = data;
703
704         /* Have a look at each adapter, if clients of this driver are still
705          * attached. If so, detach them to be able to kill the driver
706          * afterwards.
707          */
708         if (driver->detach_adapter) {
709                 if (driver->detach_adapter(adapter))
710                         dev_err(&adapter->dev,
711                                 "detach_adapter failed for driver [%s]\n",
712                                 driver->driver.name);
713         } else {
714                 struct i2c_client *client, *_n;
715
716                 list_for_each_entry_safe(client, _n, &adapter->clients, list) {
717                         if (client->driver != driver)
718                                 continue;
719                         dev_dbg(&adapter->dev,
720                                 "detaching client [%s] at 0x%02x\n",
721                                 client->name, client->addr);
722                         if (driver->detach_client(client))
723                                 dev_err(&adapter->dev, "detach_client "
724                                         "failed for client [%s] at 0x%02x\n",
725                                         client->name, client->addr);
726                 }
727         }
728
729         return 0;
730 }
731
732 /**
733  * i2c_del_driver - unregister I2C driver
734  * @driver: the driver being unregistered
735  * Context: can sleep
736  */
737 void i2c_del_driver(struct i2c_driver *driver)
738 {
739         mutex_lock(&core_lock);
740
741         /* legacy driver? */
742         if (!is_newstyle_driver(driver))
743                 class_for_each_device(&i2c_adapter_class, driver,
744                                       __detach_adapter);
745
746         driver_unregister(&driver->driver);
747         pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
748
749         mutex_unlock(&core_lock);
750 }
751 EXPORT_SYMBOL(i2c_del_driver);
752
753 /* ------------------------------------------------------------------------- */
754
755 static int __i2c_check_addr(struct device *dev, void *addrp)
756 {
757         struct i2c_client       *client = i2c_verify_client(dev);
758         int                     addr = *(int *)addrp;
759
760         if (client && client->addr == addr)
761                 return -EBUSY;
762         return 0;
763 }
764
765 static int i2c_check_addr(struct i2c_adapter *adapter, int addr)
766 {
767         return device_for_each_child(&adapter->dev, &addr, __i2c_check_addr);
768 }
769
770 int i2c_attach_client(struct i2c_client *client)
771 {
772         struct i2c_adapter *adapter = client->adapter;
773         int res = 0;
774
775         client->dev.parent = &client->adapter->dev;
776         client->dev.bus = &i2c_bus_type;
777
778         if (client->driver)
779                 client->dev.driver = &client->driver->driver;
780
781         if (client->driver && !is_newstyle_driver(client->driver)) {
782                 client->dev.release = i2c_client_release;
783                 client->dev.uevent_suppress = 1;
784         } else
785                 client->dev.release = i2c_client_dev_release;
786
787         snprintf(&client->dev.bus_id[0], sizeof(client->dev.bus_id),
788                 "%d-%04x", i2c_adapter_id(adapter), client->addr);
789         res = device_register(&client->dev);
790         if (res)
791                 goto out_err;
792
793         mutex_lock(&adapter->clist_lock);
794         list_add_tail(&client->list, &adapter->clients);
795         mutex_unlock(&adapter->clist_lock);
796
797         dev_dbg(&adapter->dev, "client [%s] registered with bus id %s\n",
798                 client->name, client->dev.bus_id);
799
800         if (adapter->client_register)  {
801                 if (adapter->client_register(client)) {
802                         dev_dbg(&adapter->dev, "client_register "
803                                 "failed for client [%s] at 0x%02x\n",
804                                 client->name, client->addr);
805                 }
806         }
807
808         return 0;
809
810 out_err:
811         dev_err(&adapter->dev, "Failed to attach i2c client %s at 0x%02x "
812                 "(%d)\n", client->name, client->addr, res);
813         return res;
814 }
815 EXPORT_SYMBOL(i2c_attach_client);
816
817 int i2c_detach_client(struct i2c_client *client)
818 {
819         struct i2c_adapter *adapter = client->adapter;
820         int res = 0;
821
822         if (adapter->client_unregister)  {
823                 res = adapter->client_unregister(client);
824                 if (res) {
825                         dev_err(&client->dev,
826                                 "client_unregister [%s] failed, "
827                                 "client not detached\n", client->name);
828                         goto out;
829                 }
830         }
831
832         mutex_lock(&adapter->clist_lock);
833         list_del(&client->list);
834         mutex_unlock(&adapter->clist_lock);
835
836         init_completion(&client->released);
837         device_unregister(&client->dev);
838         wait_for_completion(&client->released);
839
840  out:
841         return res;
842 }
843 EXPORT_SYMBOL(i2c_detach_client);
844
845 /**
846  * i2c_use_client - increments the reference count of the i2c client structure
847  * @client: the client being referenced
848  *
849  * Each live reference to a client should be refcounted. The driver model does
850  * that automatically as part of driver binding, so that most drivers don't
851  * need to do this explicitly: they hold a reference until they're unbound
852  * from the device.
853  *
854  * A pointer to the client with the incremented reference counter is returned.
855  */
856 struct i2c_client *i2c_use_client(struct i2c_client *client)
857 {
858         if (client && get_device(&client->dev))
859                 return client;
860         return NULL;
861 }
862 EXPORT_SYMBOL(i2c_use_client);
863
864 /**
865  * i2c_release_client - release a use of the i2c client structure
866  * @client: the client being no longer referenced
867  *
868  * Must be called when a user of a client is finished with it.
869  */
870 void i2c_release_client(struct i2c_client *client)
871 {
872         if (client)
873                 put_device(&client->dev);
874 }
875 EXPORT_SYMBOL(i2c_release_client);
876
877 struct i2c_cmd_arg {
878         unsigned        cmd;
879         void            *arg;
880 };
881
882 static int i2c_cmd(struct device *dev, void *_arg)
883 {
884         struct i2c_client       *client = i2c_verify_client(dev);
885         struct i2c_cmd_arg      *arg = _arg;
886
887         if (client && client->driver && client->driver->command)
888                 client->driver->command(client, arg->cmd, arg->arg);
889         return 0;
890 }
891
892 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
893 {
894         struct i2c_cmd_arg      cmd_arg;
895
896         cmd_arg.cmd = cmd;
897         cmd_arg.arg = arg;
898         device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
899 }
900 EXPORT_SYMBOL(i2c_clients_command);
901
902 static int __init i2c_init(void)
903 {
904         int retval;
905
906         retval = bus_register(&i2c_bus_type);
907         if (retval)
908                 return retval;
909         retval = class_register(&i2c_adapter_class);
910         if (retval)
911                 goto bus_err;
912         retval = i2c_add_driver(&dummy_driver);
913         if (retval)
914                 goto class_err;
915         return 0;
916
917 class_err:
918         class_unregister(&i2c_adapter_class);
919 bus_err:
920         bus_unregister(&i2c_bus_type);
921         return retval;
922 }
923
924 static void __exit i2c_exit(void)
925 {
926         i2c_del_driver(&dummy_driver);
927         class_unregister(&i2c_adapter_class);
928         bus_unregister(&i2c_bus_type);
929 }
930
931 subsys_initcall(i2c_init);
932 module_exit(i2c_exit);
933
934 /* ----------------------------------------------------
935  * the functional interface to the i2c busses.
936  * ----------------------------------------------------
937  */
938
939 /**
940  * i2c_transfer - execute a single or combined I2C message
941  * @adap: Handle to I2C bus
942  * @msgs: One or more messages to execute before STOP is issued to
943  *      terminate the operation; each message begins with a START.
944  * @num: Number of messages to be executed.
945  *
946  * Returns negative errno, else the number of messages executed.
947  *
948  * Note that there is no requirement that each message be sent to
949  * the same slave address, although that is the most common model.
950  */
951 int i2c_transfer(struct i2c_adapter * adap, struct i2c_msg *msgs, int num)
952 {
953         int ret;
954
955         /* REVISIT the fault reporting model here is weak:
956          *
957          *  - When we get an error after receiving N bytes from a slave,
958          *    there is no way to report "N".
959          *
960          *  - When we get a NAK after transmitting N bytes to a slave,
961          *    there is no way to report "N" ... or to let the master
962          *    continue executing the rest of this combined message, if
963          *    that's the appropriate response.
964          *
965          *  - When for example "num" is two and we successfully complete
966          *    the first message but get an error part way through the
967          *    second, it's unclear whether that should be reported as
968          *    one (discarding status on the second message) or errno
969          *    (discarding status on the first one).
970          */
971
972         if (adap->algo->master_xfer) {
973 #ifdef DEBUG
974                 for (ret = 0; ret < num; ret++) {
975                         dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
976                                 "len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
977                                 ? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
978                                 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
979                 }
980 #endif
981
982                 if (in_atomic() || irqs_disabled()) {
983                         ret = mutex_trylock(&adap->bus_lock);
984                         if (!ret)
985                                 /* I2C activity is ongoing. */
986                                 return -EAGAIN;
987                 } else {
988                         mutex_lock_nested(&adap->bus_lock, adap->level);
989                 }
990
991                 ret = adap->algo->master_xfer(adap,msgs,num);
992                 mutex_unlock(&adap->bus_lock);
993
994                 return ret;
995         } else {
996                 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
997                 return -EOPNOTSUPP;
998         }
999 }
1000 EXPORT_SYMBOL(i2c_transfer);
1001
1002 /**
1003  * i2c_master_send - issue a single I2C message in master transmit mode
1004  * @client: Handle to slave device
1005  * @buf: Data that will be written to the slave
1006  * @count: How many bytes to write
1007  *
1008  * Returns negative errno, or else the number of bytes written.
1009  */
1010 int i2c_master_send(struct i2c_client *client,const char *buf ,int count)
1011 {
1012         int ret;
1013         struct i2c_adapter *adap=client->adapter;
1014         struct i2c_msg msg;
1015
1016         msg.addr = client->addr;
1017         msg.flags = client->flags & I2C_M_TEN;
1018         msg.len = count;
1019         msg.buf = (char *)buf;
1020
1021         ret = i2c_transfer(adap, &msg, 1);
1022
1023         /* If everything went ok (i.e. 1 msg transmitted), return #bytes
1024            transmitted, else error code. */
1025         return (ret == 1) ? count : ret;
1026 }
1027 EXPORT_SYMBOL(i2c_master_send);
1028
1029 /**
1030  * i2c_master_recv - issue a single I2C message in master receive mode
1031  * @client: Handle to slave device
1032  * @buf: Where to store data read from slave
1033  * @count: How many bytes to read
1034  *
1035  * Returns negative errno, or else the number of bytes read.
1036  */
1037 int i2c_master_recv(struct i2c_client *client, char *buf ,int count)
1038 {
1039         struct i2c_adapter *adap=client->adapter;
1040         struct i2c_msg msg;
1041         int ret;
1042
1043         msg.addr = client->addr;
1044         msg.flags = client->flags & I2C_M_TEN;
1045         msg.flags |= I2C_M_RD;
1046         msg.len = count;
1047         msg.buf = buf;
1048
1049         ret = i2c_transfer(adap, &msg, 1);
1050
1051         /* If everything went ok (i.e. 1 msg transmitted), return #bytes
1052            transmitted, else error code. */
1053         return (ret == 1) ? count : ret;
1054 }
1055 EXPORT_SYMBOL(i2c_master_recv);
1056
1057 /* ----------------------------------------------------
1058  * the i2c address scanning function
1059  * Will not work for 10-bit addresses!
1060  * ----------------------------------------------------
1061  */
1062 static int i2c_probe_address(struct i2c_adapter *adapter, int addr, int kind,
1063                              int (*found_proc) (struct i2c_adapter *, int, int))
1064 {
1065         int err;
1066
1067         /* Make sure the address is valid */
1068         if (addr < 0x03 || addr > 0x77) {
1069                 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
1070                          addr);
1071                 return -EINVAL;
1072         }
1073
1074         /* Skip if already in use */
1075         if (i2c_check_addr(adapter, addr))
1076                 return 0;
1077
1078         /* Make sure there is something at this address, unless forced */
1079         if (kind < 0) {
1080                 if (i2c_smbus_xfer(adapter, addr, 0, 0, 0,
1081                                    I2C_SMBUS_QUICK, NULL) < 0)
1082                         return 0;
1083
1084                 /* prevent 24RF08 corruption */
1085                 if ((addr & ~0x0f) == 0x50)
1086                         i2c_smbus_xfer(adapter, addr, 0, 0, 0,
1087                                        I2C_SMBUS_QUICK, NULL);
1088         }
1089
1090         /* Finally call the custom detection function */
1091         err = found_proc(adapter, addr, kind);
1092         /* -ENODEV can be returned if there is a chip at the given address
1093            but it isn't supported by this chip driver. We catch it here as
1094            this isn't an error. */
1095         if (err == -ENODEV)
1096                 err = 0;
1097
1098         if (err)
1099                 dev_warn(&adapter->dev, "Client creation failed at 0x%x (%d)\n",
1100                          addr, err);
1101         return err;
1102 }
1103
1104 int i2c_probe(struct i2c_adapter *adapter,
1105               const struct i2c_client_address_data *address_data,
1106               int (*found_proc) (struct i2c_adapter *, int, int))
1107 {
1108         int i, err;
1109         int adap_id = i2c_adapter_id(adapter);
1110
1111         /* Force entries are done first, and are not affected by ignore
1112            entries */
1113         if (address_data->forces) {
1114                 const unsigned short * const *forces = address_data->forces;
1115                 int kind;
1116
1117                 for (kind = 0; forces[kind]; kind++) {
1118                         for (i = 0; forces[kind][i] != I2C_CLIENT_END;
1119                              i += 2) {
1120                                 if (forces[kind][i] == adap_id
1121                                  || forces[kind][i] == ANY_I2C_BUS) {
1122                                         dev_dbg(&adapter->dev, "found force "
1123                                                 "parameter for adapter %d, "
1124                                                 "addr 0x%02x, kind %d\n",
1125                                                 adap_id, forces[kind][i + 1],
1126                                                 kind);
1127                                         err = i2c_probe_address(adapter,
1128                                                 forces[kind][i + 1],
1129                                                 kind, found_proc);
1130                                         if (err)
1131                                                 return err;
1132                                 }
1133                         }
1134                 }
1135         }
1136
1137         /* Stop here if we can't use SMBUS_QUICK */
1138         if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_QUICK)) {
1139                 if (address_data->probe[0] == I2C_CLIENT_END
1140                  && address_data->normal_i2c[0] == I2C_CLIENT_END)
1141                         return 0;
1142
1143                 dev_warn(&adapter->dev, "SMBus Quick command not supported, "
1144                          "can't probe for chips\n");
1145                 return -EOPNOTSUPP;
1146         }
1147
1148         /* Probe entries are done second, and are not affected by ignore
1149            entries either */
1150         for (i = 0; address_data->probe[i] != I2C_CLIENT_END; i += 2) {
1151                 if (address_data->probe[i] == adap_id
1152                  || address_data->probe[i] == ANY_I2C_BUS) {
1153                         dev_dbg(&adapter->dev, "found probe parameter for "
1154                                 "adapter %d, addr 0x%02x\n", adap_id,
1155                                 address_data->probe[i + 1]);
1156                         err = i2c_probe_address(adapter,
1157                                                 address_data->probe[i + 1],
1158                                                 -1, found_proc);
1159                         if (err)
1160                                 return err;
1161                 }
1162         }
1163
1164         /* Normal entries are done last, unless shadowed by an ignore entry */
1165         for (i = 0; address_data->normal_i2c[i] != I2C_CLIENT_END; i += 1) {
1166                 int j, ignore;
1167
1168                 ignore = 0;
1169                 for (j = 0; address_data->ignore[j] != I2C_CLIENT_END;
1170                      j += 2) {
1171                         if ((address_data->ignore[j] == adap_id ||
1172                              address_data->ignore[j] == ANY_I2C_BUS)
1173                          && address_data->ignore[j + 1]
1174                             == address_data->normal_i2c[i]) {
1175                                 dev_dbg(&adapter->dev, "found ignore "
1176                                         "parameter for adapter %d, "
1177                                         "addr 0x%02x\n", adap_id,
1178                                         address_data->ignore[j + 1]);
1179                                 ignore = 1;
1180                                 break;
1181                         }
1182                 }
1183                 if (ignore)
1184                         continue;
1185
1186                 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
1187                         "addr 0x%02x\n", adap_id,
1188                         address_data->normal_i2c[i]);
1189                 err = i2c_probe_address(adapter, address_data->normal_i2c[i],
1190                                         -1, found_proc);
1191                 if (err)
1192                         return err;
1193         }
1194
1195         return 0;
1196 }
1197 EXPORT_SYMBOL(i2c_probe);
1198
1199 struct i2c_client *
1200 i2c_new_probed_device(struct i2c_adapter *adap,
1201                       struct i2c_board_info *info,
1202                       unsigned short const *addr_list)
1203 {
1204         int i;
1205
1206         /* Stop here if the bus doesn't support probing */
1207         if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE)) {
1208                 dev_err(&adap->dev, "Probing not supported\n");
1209                 return NULL;
1210         }
1211
1212         for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
1213                 /* Check address validity */
1214                 if (addr_list[i] < 0x03 || addr_list[i] > 0x77) {
1215                         dev_warn(&adap->dev, "Invalid 7-bit address "
1216                                  "0x%02x\n", addr_list[i]);
1217                         continue;
1218                 }
1219
1220                 /* Check address availability */
1221                 if (i2c_check_addr(adap, addr_list[i])) {
1222                         dev_dbg(&adap->dev, "Address 0x%02x already in "
1223                                 "use, not probing\n", addr_list[i]);
1224                         continue;
1225                 }
1226
1227                 /* Test address responsiveness
1228                    The default probe method is a quick write, but it is known
1229                    to corrupt the 24RF08 EEPROMs due to a state machine bug,
1230                    and could also irreversibly write-protect some EEPROMs, so
1231                    for address ranges 0x30-0x37 and 0x50-0x5f, we use a byte
1232                    read instead. Also, some bus drivers don't implement
1233                    quick write, so we fallback to a byte read it that case
1234                    too. */
1235                 if ((addr_list[i] & ~0x07) == 0x30
1236                  || (addr_list[i] & ~0x0f) == 0x50
1237                  || !i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK)) {
1238                         if (i2c_smbus_xfer(adap, addr_list[i], 0,
1239                                            I2C_SMBUS_READ, 0,
1240                                            I2C_SMBUS_BYTE, NULL) >= 0)
1241                                 break;
1242                 } else {
1243                         if (i2c_smbus_xfer(adap, addr_list[i], 0,
1244                                            I2C_SMBUS_WRITE, 0,
1245                                            I2C_SMBUS_QUICK, NULL) >= 0)
1246                                 break;
1247                 }
1248         }
1249
1250         if (addr_list[i] == I2C_CLIENT_END) {
1251                 dev_dbg(&adap->dev, "Probing failed, no device found\n");
1252                 return NULL;
1253         }
1254
1255         info->addr = addr_list[i];
1256         return i2c_new_device(adap, info);
1257 }
1258 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
1259
1260 struct i2c_adapter* i2c_get_adapter(int id)
1261 {
1262         struct i2c_adapter *adapter;
1263
1264         mutex_lock(&core_lock);
1265         adapter = (struct i2c_adapter *)idr_find(&i2c_adapter_idr, id);
1266         if (adapter && !try_module_get(adapter->owner))
1267                 adapter = NULL;
1268
1269         mutex_unlock(&core_lock);
1270         return adapter;
1271 }
1272 EXPORT_SYMBOL(i2c_get_adapter);
1273
1274 void i2c_put_adapter(struct i2c_adapter *adap)
1275 {
1276         module_put(adap->owner);
1277 }
1278 EXPORT_SYMBOL(i2c_put_adapter);
1279
1280 /* The SMBus parts */
1281
1282 #define POLY    (0x1070U << 3)
1283 static u8
1284 crc8(u16 data)
1285 {
1286         int i;
1287
1288         for(i = 0; i < 8; i++) {
1289                 if (data & 0x8000)
1290                         data = data ^ POLY;
1291                 data = data << 1;
1292         }
1293         return (u8)(data >> 8);
1294 }
1295
1296 /* Incremental CRC8 over count bytes in the array pointed to by p */
1297 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
1298 {
1299         int i;
1300
1301         for(i = 0; i < count; i++)
1302                 crc = crc8((crc ^ p[i]) << 8);
1303         return crc;
1304 }
1305
1306 /* Assume a 7-bit address, which is reasonable for SMBus */
1307 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
1308 {
1309         /* The address will be sent first */
1310         u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
1311         pec = i2c_smbus_pec(pec, &addr, 1);
1312
1313         /* The data buffer follows */
1314         return i2c_smbus_pec(pec, msg->buf, msg->len);
1315 }
1316
1317 /* Used for write only transactions */
1318 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
1319 {
1320         msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
1321         msg->len++;
1322 }
1323
1324 /* Return <0 on CRC error
1325    If there was a write before this read (most cases) we need to take the
1326    partial CRC from the write part into account.
1327    Note that this function does modify the message (we need to decrease the
1328    message length to hide the CRC byte from the caller). */
1329 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
1330 {
1331         u8 rpec = msg->buf[--msg->len];
1332         cpec = i2c_smbus_msg_pec(cpec, msg);
1333
1334         if (rpec != cpec) {
1335                 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
1336                         rpec, cpec);
1337                 return -EBADMSG;
1338         }
1339         return 0;
1340 }
1341
1342 /**
1343  * i2c_smbus_read_byte - SMBus "receive byte" protocol
1344  * @client: Handle to slave device
1345  *
1346  * This executes the SMBus "receive byte" protocol, returning negative errno
1347  * else the byte received from the device.
1348  */
1349 s32 i2c_smbus_read_byte(struct i2c_client *client)
1350 {
1351         union i2c_smbus_data data;
1352         int status;
1353
1354         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1355                                 I2C_SMBUS_READ, 0,
1356                                 I2C_SMBUS_BYTE, &data);
1357         return (status < 0) ? status : data.byte;
1358 }
1359 EXPORT_SYMBOL(i2c_smbus_read_byte);
1360
1361 /**
1362  * i2c_smbus_write_byte - SMBus "send byte" protocol
1363  * @client: Handle to slave device
1364  * @value: Byte to be sent
1365  *
1366  * This executes the SMBus "send byte" protocol, returning negative errno
1367  * else zero on success.
1368  */
1369 s32 i2c_smbus_write_byte(struct i2c_client *client, u8 value)
1370 {
1371         return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1372                               I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
1373 }
1374 EXPORT_SYMBOL(i2c_smbus_write_byte);
1375
1376 /**
1377  * i2c_smbus_read_byte_data - SMBus "read byte" protocol
1378  * @client: Handle to slave device
1379  * @command: Byte interpreted by slave
1380  *
1381  * This executes the SMBus "read byte" protocol, returning negative errno
1382  * else a data byte received from the device.
1383  */
1384 s32 i2c_smbus_read_byte_data(struct i2c_client *client, u8 command)
1385 {
1386         union i2c_smbus_data data;
1387         int status;
1388
1389         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1390                                 I2C_SMBUS_READ, command,
1391                                 I2C_SMBUS_BYTE_DATA, &data);
1392         return (status < 0) ? status : data.byte;
1393 }
1394 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
1395
1396 /**
1397  * i2c_smbus_write_byte_data - SMBus "write byte" protocol
1398  * @client: Handle to slave device
1399  * @command: Byte interpreted by slave
1400  * @value: Byte being written
1401  *
1402  * This executes the SMBus "write byte" protocol, returning negative errno
1403  * else zero on success.
1404  */
1405 s32 i2c_smbus_write_byte_data(struct i2c_client *client, u8 command, u8 value)
1406 {
1407         union i2c_smbus_data data;
1408         data.byte = value;
1409         return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1410                               I2C_SMBUS_WRITE,command,
1411                               I2C_SMBUS_BYTE_DATA,&data);
1412 }
1413 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
1414
1415 /**
1416  * i2c_smbus_read_word_data - SMBus "read word" protocol
1417  * @client: Handle to slave device
1418  * @command: Byte interpreted by slave
1419  *
1420  * This executes the SMBus "read word" protocol, returning negative errno
1421  * else a 16-bit unsigned "word" received from the device.
1422  */
1423 s32 i2c_smbus_read_word_data(struct i2c_client *client, u8 command)
1424 {
1425         union i2c_smbus_data data;
1426         int status;
1427
1428         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1429                                 I2C_SMBUS_READ, command,
1430                                 I2C_SMBUS_WORD_DATA, &data);
1431         return (status < 0) ? status : data.word;
1432 }
1433 EXPORT_SYMBOL(i2c_smbus_read_word_data);
1434
1435 /**
1436  * i2c_smbus_write_word_data - SMBus "write word" protocol
1437  * @client: Handle to slave device
1438  * @command: Byte interpreted by slave
1439  * @value: 16-bit "word" being written
1440  *
1441  * This executes the SMBus "write word" protocol, returning negative errno
1442  * else zero on success.
1443  */
1444 s32 i2c_smbus_write_word_data(struct i2c_client *client, u8 command, u16 value)
1445 {
1446         union i2c_smbus_data data;
1447         data.word = value;
1448         return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1449                               I2C_SMBUS_WRITE,command,
1450                               I2C_SMBUS_WORD_DATA,&data);
1451 }
1452 EXPORT_SYMBOL(i2c_smbus_write_word_data);
1453
1454 /**
1455  * i2c_smbus_read_block_data - SMBus "block read" protocol
1456  * @client: Handle to slave device
1457  * @command: Byte interpreted by slave
1458  * @values: Byte array into which data will be read; big enough to hold
1459  *      the data returned by the slave.  SMBus allows at most 32 bytes.
1460  *
1461  * This executes the SMBus "block read" protocol, returning negative errno
1462  * else the number of data bytes in the slave's response.
1463  *
1464  * Note that using this function requires that the client's adapter support
1465  * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality.  Not all adapter drivers
1466  * support this; its emulation through I2C messaging relies on a specific
1467  * mechanism (I2C_M_RECV_LEN) which may not be implemented.
1468  */
1469 s32 i2c_smbus_read_block_data(struct i2c_client *client, u8 command,
1470                               u8 *values)
1471 {
1472         union i2c_smbus_data data;
1473         int status;
1474
1475         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1476                                 I2C_SMBUS_READ, command,
1477                                 I2C_SMBUS_BLOCK_DATA, &data);
1478         if (status)
1479                 return status;
1480
1481         memcpy(values, &data.block[1], data.block[0]);
1482         return data.block[0];
1483 }
1484 EXPORT_SYMBOL(i2c_smbus_read_block_data);
1485
1486 /**
1487  * i2c_smbus_write_block_data - SMBus "block write" protocol
1488  * @client: Handle to slave device
1489  * @command: Byte interpreted by slave
1490  * @length: Size of data block; SMBus allows at most 32 bytes
1491  * @values: Byte array which will be written.
1492  *
1493  * This executes the SMBus "block write" protocol, returning negative errno
1494  * else zero on success.
1495  */
1496 s32 i2c_smbus_write_block_data(struct i2c_client *client, u8 command,
1497                                u8 length, const u8 *values)
1498 {
1499         union i2c_smbus_data data;
1500
1501         if (length > I2C_SMBUS_BLOCK_MAX)
1502                 length = I2C_SMBUS_BLOCK_MAX;
1503         data.block[0] = length;
1504         memcpy(&data.block[1], values, length);
1505         return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1506                               I2C_SMBUS_WRITE,command,
1507                               I2C_SMBUS_BLOCK_DATA,&data);
1508 }
1509 EXPORT_SYMBOL(i2c_smbus_write_block_data);
1510
1511 /* Returns the number of read bytes */
1512 s32 i2c_smbus_read_i2c_block_data(struct i2c_client *client, u8 command,
1513                                   u8 length, u8 *values)
1514 {
1515         union i2c_smbus_data data;
1516         int status;
1517
1518         if (length > I2C_SMBUS_BLOCK_MAX)
1519                 length = I2C_SMBUS_BLOCK_MAX;
1520         data.block[0] = length;
1521         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1522                                 I2C_SMBUS_READ, command,
1523                                 I2C_SMBUS_I2C_BLOCK_DATA, &data);
1524         if (status < 0)
1525                 return status;
1526
1527         memcpy(values, &data.block[1], data.block[0]);
1528         return data.block[0];
1529 }
1530 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
1531
1532 s32 i2c_smbus_write_i2c_block_data(struct i2c_client *client, u8 command,
1533                                    u8 length, const u8 *values)
1534 {
1535         union i2c_smbus_data data;
1536
1537         if (length > I2C_SMBUS_BLOCK_MAX)
1538                 length = I2C_SMBUS_BLOCK_MAX;
1539         data.block[0] = length;
1540         memcpy(data.block + 1, values, length);
1541         return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1542                               I2C_SMBUS_WRITE, command,
1543                               I2C_SMBUS_I2C_BLOCK_DATA, &data);
1544 }
1545 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
1546
1547 /* Simulate a SMBus command using the i2c protocol
1548    No checking of parameters is done!  */
1549 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter * adapter, u16 addr,
1550                                    unsigned short flags,
1551                                    char read_write, u8 command, int size,
1552                                    union i2c_smbus_data * data)
1553 {
1554         /* So we need to generate a series of msgs. In the case of writing, we
1555           need to use only one message; when reading, we need two. We initialize
1556           most things with sane defaults, to keep the code below somewhat
1557           simpler. */
1558         unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
1559         unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
1560         int num = read_write == I2C_SMBUS_READ?2:1;
1561         struct i2c_msg msg[2] = { { addr, flags, 1, msgbuf0 },
1562                                   { addr, flags | I2C_M_RD, 0, msgbuf1 }
1563                                 };
1564         int i;
1565         u8 partial_pec = 0;
1566         int status;
1567
1568         msgbuf0[0] = command;
1569         switch(size) {
1570         case I2C_SMBUS_QUICK:
1571                 msg[0].len = 0;
1572                 /* Special case: The read/write field is used as data */
1573                 msg[0].flags = flags | (read_write==I2C_SMBUS_READ)?I2C_M_RD:0;
1574                 num = 1;
1575                 break;
1576         case I2C_SMBUS_BYTE:
1577                 if (read_write == I2C_SMBUS_READ) {
1578                         /* Special case: only a read! */
1579                         msg[0].flags = I2C_M_RD | flags;
1580                         num = 1;
1581                 }
1582                 break;
1583         case I2C_SMBUS_BYTE_DATA:
1584                 if (read_write == I2C_SMBUS_READ)
1585                         msg[1].len = 1;
1586                 else {
1587                         msg[0].len = 2;
1588                         msgbuf0[1] = data->byte;
1589                 }
1590                 break;
1591         case I2C_SMBUS_WORD_DATA:
1592                 if (read_write == I2C_SMBUS_READ)
1593                         msg[1].len = 2;
1594                 else {
1595                         msg[0].len=3;
1596                         msgbuf0[1] = data->word & 0xff;
1597                         msgbuf0[2] = data->word >> 8;
1598                 }
1599                 break;
1600         case I2C_SMBUS_PROC_CALL:
1601                 num = 2; /* Special case */
1602                 read_write = I2C_SMBUS_READ;
1603                 msg[0].len = 3;
1604                 msg[1].len = 2;
1605                 msgbuf0[1] = data->word & 0xff;
1606                 msgbuf0[2] = data->word >> 8;
1607                 break;
1608         case I2C_SMBUS_BLOCK_DATA:
1609                 if (read_write == I2C_SMBUS_READ) {
1610                         msg[1].flags |= I2C_M_RECV_LEN;
1611                         msg[1].len = 1; /* block length will be added by
1612                                            the underlying bus driver */
1613                 } else {
1614                         msg[0].len = data->block[0] + 2;
1615                         if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
1616                                 dev_err(&adapter->dev,
1617                                         "Invalid block write size %d\n",
1618                                         data->block[0]);
1619                                 return -EINVAL;
1620                         }
1621                         for (i = 1; i < msg[0].len; i++)
1622                                 msgbuf0[i] = data->block[i-1];
1623                 }
1624                 break;
1625         case I2C_SMBUS_BLOCK_PROC_CALL:
1626                 num = 2; /* Another special case */
1627                 read_write = I2C_SMBUS_READ;
1628                 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
1629                         dev_err(&adapter->dev,
1630                                 "Invalid block write size %d\n",
1631                                 data->block[0]);
1632                         return -EINVAL;
1633                 }
1634                 msg[0].len = data->block[0] + 2;
1635                 for (i = 1; i < msg[0].len; i++)
1636                         msgbuf0[i] = data->block[i-1];
1637                 msg[1].flags |= I2C_M_RECV_LEN;
1638                 msg[1].len = 1; /* block length will be added by
1639                                    the underlying bus driver */
1640                 break;
1641         case I2C_SMBUS_I2C_BLOCK_DATA:
1642                 if (read_write == I2C_SMBUS_READ) {
1643                         msg[1].len = data->block[0];
1644                 } else {
1645                         msg[0].len = data->block[0] + 1;
1646                         if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
1647                                 dev_err(&adapter->dev,
1648                                         "Invalid block write size %d\n",
1649                                         data->block[0]);
1650                                 return -EINVAL;
1651                         }
1652                         for (i = 1; i <= data->block[0]; i++)
1653                                 msgbuf0[i] = data->block[i];
1654                 }
1655                 break;
1656         default:
1657                 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
1658                 return -EOPNOTSUPP;
1659         }
1660
1661         i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
1662                                       && size != I2C_SMBUS_I2C_BLOCK_DATA);
1663         if (i) {
1664                 /* Compute PEC if first message is a write */
1665                 if (!(msg[0].flags & I2C_M_RD)) {
1666                         if (num == 1) /* Write only */
1667                                 i2c_smbus_add_pec(&msg[0]);
1668                         else /* Write followed by read */
1669                                 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
1670                 }
1671                 /* Ask for PEC if last message is a read */
1672                 if (msg[num-1].flags & I2C_M_RD)
1673                         msg[num-1].len++;
1674         }
1675
1676         status = i2c_transfer(adapter, msg, num);
1677         if (status < 0)
1678                 return status;
1679
1680         /* Check PEC if last message is a read */
1681         if (i && (msg[num-1].flags & I2C_M_RD)) {
1682                 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
1683                 if (status < 0)
1684                         return status;
1685         }
1686
1687         if (read_write == I2C_SMBUS_READ)
1688                 switch(size) {
1689                         case I2C_SMBUS_BYTE:
1690                                 data->byte = msgbuf0[0];
1691                                 break;
1692                         case I2C_SMBUS_BYTE_DATA:
1693                                 data->byte = msgbuf1[0];
1694                                 break;
1695                         case I2C_SMBUS_WORD_DATA:
1696                         case I2C_SMBUS_PROC_CALL:
1697                                 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
1698                                 break;
1699                         case I2C_SMBUS_I2C_BLOCK_DATA:
1700                                 for (i = 0; i < data->block[0]; i++)
1701                                         data->block[i+1] = msgbuf1[i];
1702                                 break;
1703                         case I2C_SMBUS_BLOCK_DATA:
1704                         case I2C_SMBUS_BLOCK_PROC_CALL:
1705                                 for (i = 0; i < msgbuf1[0] + 1; i++)
1706                                         data->block[i] = msgbuf1[i];
1707                                 break;
1708                 }
1709         return 0;
1710 }
1711
1712 /**
1713  * i2c_smbus_xfer - execute SMBus protocol operations
1714  * @adapter: Handle to I2C bus
1715  * @addr: Address of SMBus slave on that bus
1716  * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
1717  * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
1718  * @command: Byte interpreted by slave, for protocols which use such bytes
1719  * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
1720  * @data: Data to be read or written
1721  *
1722  * This executes an SMBus protocol operation, and returns a negative
1723  * errno code else zero on success.
1724  */
1725 s32 i2c_smbus_xfer(struct i2c_adapter * adapter, u16 addr, unsigned short flags,
1726                    char read_write, u8 command, int protocol,
1727                    union i2c_smbus_data * data)
1728 {
1729         s32 res;
1730
1731         flags &= I2C_M_TEN | I2C_CLIENT_PEC;
1732
1733         if (adapter->algo->smbus_xfer) {
1734                 mutex_lock(&adapter->bus_lock);
1735                 res = adapter->algo->smbus_xfer(adapter,addr,flags,read_write,
1736                                                 command, protocol, data);
1737                 mutex_unlock(&adapter->bus_lock);
1738         } else
1739                 res = i2c_smbus_xfer_emulated(adapter,addr,flags,read_write,
1740                                               command, protocol, data);
1741
1742         return res;
1743 }
1744 EXPORT_SYMBOL(i2c_smbus_xfer);
1745
1746 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
1747 MODULE_DESCRIPTION("I2C-Bus main module");
1748 MODULE_LICENSE("GPL");