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