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