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