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