]> Pileus Git - ~andy/linux/blob - drivers/i2c/i2c-core.c
i2c: Fix probing of FSC hardware monitoring chips
[~andy/linux] / drivers / i2c / i2c-core.c
1 /* i2c-core.c - a device driver for the iic-bus interface                    */
2 /* ------------------------------------------------------------------------- */
3 /*   Copyright (C) 1995-99 Simon G. Vogl
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                */
18 /* ------------------------------------------------------------------------- */
19
20 /* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>.
21    All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
22    SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com> and
23    Jean Delvare <khali@linux-fr.org> */
24
25 #include <linux/module.h>
26 #include <linux/kernel.h>
27 #include <linux/errno.h>
28 #include <linux/slab.h>
29 #include <linux/i2c.h>
30 #include <linux/init.h>
31 #include <linux/idr.h>
32 #include <linux/mutex.h>
33 #include <linux/completion.h>
34 #include <linux/hardirq.h>
35 #include <linux/irqflags.h>
36 #include <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 (addr == 0x73 && (adapter->class & I2C_CLASS_HWMON)) {
1268                 /* Special probe for FSC hwmon chips */
1269                 union i2c_smbus_data dummy;
1270
1271                 if (i2c_smbus_xfer(adapter, addr, 0, I2C_SMBUS_READ, 0,
1272                                    I2C_SMBUS_BYTE_DATA, &dummy) < 0)
1273                         return 0;
1274         } else {
1275                 if (i2c_smbus_xfer(adapter, addr, 0, I2C_SMBUS_WRITE, 0,
1276                                    I2C_SMBUS_QUICK, NULL) < 0)
1277                         return 0;
1278
1279                 /* Prevent 24RF08 corruption */
1280                 if ((addr & ~0x0f) == 0x50)
1281                         i2c_smbus_xfer(adapter, addr, 0, I2C_SMBUS_WRITE, 0,
1282                                        I2C_SMBUS_QUICK, NULL);
1283         }
1284
1285         /* Finally call the custom detection function */
1286         memset(&info, 0, sizeof(struct i2c_board_info));
1287         info.addr = addr;
1288         err = driver->detect(temp_client, &info);
1289         if (err) {
1290                 /* -ENODEV is returned if the detection fails. We catch it
1291                    here as this isn't an error. */
1292                 return err == -ENODEV ? 0 : err;
1293         }
1294
1295         /* Consistency check */
1296         if (info.type[0] == '\0') {
1297                 dev_err(&adapter->dev, "%s detection function provided "
1298                         "no name for 0x%x\n", driver->driver.name,
1299                         addr);
1300         } else {
1301                 struct i2c_client *client;
1302
1303                 /* Detection succeeded, instantiate the device */
1304                 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
1305                         info.type, info.addr);
1306                 client = i2c_new_device(adapter, &info);
1307                 if (client)
1308                         list_add_tail(&client->detected, &driver->clients);
1309                 else
1310                         dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
1311                                 info.type, info.addr);
1312         }
1313         return 0;
1314 }
1315
1316 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
1317 {
1318         const unsigned short *address_list;
1319         struct i2c_client *temp_client;
1320         int i, err = 0;
1321         int adap_id = i2c_adapter_id(adapter);
1322
1323         address_list = driver->address_list;
1324         if (!driver->detect || !address_list)
1325                 return 0;
1326
1327         /* Set up a temporary client to help detect callback */
1328         temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
1329         if (!temp_client)
1330                 return -ENOMEM;
1331         temp_client->adapter = adapter;
1332
1333         /* Stop here if the classes do not match */
1334         if (!(adapter->class & driver->class))
1335                 goto exit_free;
1336
1337         /* Stop here if we can't use SMBUS_QUICK */
1338         if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_QUICK)) {
1339                 if (address_list[0] == I2C_CLIENT_END)
1340                         goto exit_free;
1341
1342                 dev_warn(&adapter->dev, "SMBus Quick command not supported, "
1343                          "can't probe for chips\n");
1344                 err = -EOPNOTSUPP;
1345                 goto exit_free;
1346         }
1347
1348         for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
1349                 dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
1350                         "addr 0x%02x\n", adap_id, address_list[i]);
1351                 temp_client->addr = address_list[i];
1352                 err = i2c_detect_address(temp_client, driver);
1353                 if (err)
1354                         goto exit_free;
1355         }
1356
1357  exit_free:
1358         kfree(temp_client);
1359         return err;
1360 }
1361
1362 struct i2c_client *
1363 i2c_new_probed_device(struct i2c_adapter *adap,
1364                       struct i2c_board_info *info,
1365                       unsigned short const *addr_list)
1366 {
1367         int i;
1368
1369         /* Stop here if the bus doesn't support probing */
1370         if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE)) {
1371                 dev_err(&adap->dev, "Probing not supported\n");
1372                 return NULL;
1373         }
1374
1375         for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
1376                 /* Check address validity */
1377                 if (addr_list[i] < 0x03 || addr_list[i] > 0x77) {
1378                         dev_warn(&adap->dev, "Invalid 7-bit address "
1379                                  "0x%02x\n", addr_list[i]);
1380                         continue;
1381                 }
1382
1383                 /* Check address availability */
1384                 if (i2c_check_addr(adap, addr_list[i])) {
1385                         dev_dbg(&adap->dev, "Address 0x%02x already in "
1386                                 "use, not probing\n", addr_list[i]);
1387                         continue;
1388                 }
1389
1390                 /* Test address responsiveness
1391                    The default probe method is a quick write, but it is known
1392                    to corrupt the 24RF08 EEPROMs due to a state machine bug,
1393                    and could also irreversibly write-protect some EEPROMs, so
1394                    for address ranges 0x30-0x37 and 0x50-0x5f, we use a byte
1395                    read instead. Also, some bus drivers don't implement
1396                    quick write, so we fallback to a byte read it that case
1397                    too. */
1398                 if ((addr_list[i] & ~0x07) == 0x30
1399                  || (addr_list[i] & ~0x0f) == 0x50
1400                  || !i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK)) {
1401                         union i2c_smbus_data data;
1402
1403                         if (i2c_smbus_xfer(adap, addr_list[i], 0,
1404                                            I2C_SMBUS_READ, 0,
1405                                            I2C_SMBUS_BYTE, &data) >= 0)
1406                                 break;
1407                 } else {
1408                         if (i2c_smbus_xfer(adap, addr_list[i], 0,
1409                                            I2C_SMBUS_WRITE, 0,
1410                                            I2C_SMBUS_QUICK, NULL) >= 0)
1411                                 break;
1412                 }
1413         }
1414
1415         if (addr_list[i] == I2C_CLIENT_END) {
1416                 dev_dbg(&adap->dev, "Probing failed, no device found\n");
1417                 return NULL;
1418         }
1419
1420         info->addr = addr_list[i];
1421         return i2c_new_device(adap, info);
1422 }
1423 EXPORT_SYMBOL_GPL(i2c_new_probed_device);
1424
1425 struct i2c_adapter* i2c_get_adapter(int id)
1426 {
1427         struct i2c_adapter *adapter;
1428
1429         mutex_lock(&core_lock);
1430         adapter = idr_find(&i2c_adapter_idr, id);
1431         if (adapter && !try_module_get(adapter->owner))
1432                 adapter = NULL;
1433
1434         mutex_unlock(&core_lock);
1435         return adapter;
1436 }
1437 EXPORT_SYMBOL(i2c_get_adapter);
1438
1439 void i2c_put_adapter(struct i2c_adapter *adap)
1440 {
1441         module_put(adap->owner);
1442 }
1443 EXPORT_SYMBOL(i2c_put_adapter);
1444
1445 /* The SMBus parts */
1446
1447 #define POLY    (0x1070U << 3)
1448 static u8 crc8(u16 data)
1449 {
1450         int i;
1451
1452         for(i = 0; i < 8; i++) {
1453                 if (data & 0x8000)
1454                         data = data ^ POLY;
1455                 data = data << 1;
1456         }
1457         return (u8)(data >> 8);
1458 }
1459
1460 /* Incremental CRC8 over count bytes in the array pointed to by p */
1461 static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
1462 {
1463         int i;
1464
1465         for(i = 0; i < count; i++)
1466                 crc = crc8((crc ^ p[i]) << 8);
1467         return crc;
1468 }
1469
1470 /* Assume a 7-bit address, which is reasonable for SMBus */
1471 static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
1472 {
1473         /* The address will be sent first */
1474         u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
1475         pec = i2c_smbus_pec(pec, &addr, 1);
1476
1477         /* The data buffer follows */
1478         return i2c_smbus_pec(pec, msg->buf, msg->len);
1479 }
1480
1481 /* Used for write only transactions */
1482 static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
1483 {
1484         msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
1485         msg->len++;
1486 }
1487
1488 /* Return <0 on CRC error
1489    If there was a write before this read (most cases) we need to take the
1490    partial CRC from the write part into account.
1491    Note that this function does modify the message (we need to decrease the
1492    message length to hide the CRC byte from the caller). */
1493 static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
1494 {
1495         u8 rpec = msg->buf[--msg->len];
1496         cpec = i2c_smbus_msg_pec(cpec, msg);
1497
1498         if (rpec != cpec) {
1499                 pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
1500                         rpec, cpec);
1501                 return -EBADMSG;
1502         }
1503         return 0;
1504 }
1505
1506 /**
1507  * i2c_smbus_read_byte - SMBus "receive byte" protocol
1508  * @client: Handle to slave device
1509  *
1510  * This executes the SMBus "receive byte" protocol, returning negative errno
1511  * else the byte received from the device.
1512  */
1513 s32 i2c_smbus_read_byte(struct i2c_client *client)
1514 {
1515         union i2c_smbus_data data;
1516         int status;
1517
1518         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1519                                 I2C_SMBUS_READ, 0,
1520                                 I2C_SMBUS_BYTE, &data);
1521         return (status < 0) ? status : data.byte;
1522 }
1523 EXPORT_SYMBOL(i2c_smbus_read_byte);
1524
1525 /**
1526  * i2c_smbus_write_byte - SMBus "send byte" protocol
1527  * @client: Handle to slave device
1528  * @value: Byte to be sent
1529  *
1530  * This executes the SMBus "send byte" protocol, returning negative errno
1531  * else zero on success.
1532  */
1533 s32 i2c_smbus_write_byte(struct i2c_client *client, u8 value)
1534 {
1535         return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1536                               I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
1537 }
1538 EXPORT_SYMBOL(i2c_smbus_write_byte);
1539
1540 /**
1541  * i2c_smbus_read_byte_data - SMBus "read byte" protocol
1542  * @client: Handle to slave device
1543  * @command: Byte interpreted by slave
1544  *
1545  * This executes the SMBus "read byte" protocol, returning negative errno
1546  * else a data byte received from the device.
1547  */
1548 s32 i2c_smbus_read_byte_data(struct i2c_client *client, u8 command)
1549 {
1550         union i2c_smbus_data data;
1551         int status;
1552
1553         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1554                                 I2C_SMBUS_READ, command,
1555                                 I2C_SMBUS_BYTE_DATA, &data);
1556         return (status < 0) ? status : data.byte;
1557 }
1558 EXPORT_SYMBOL(i2c_smbus_read_byte_data);
1559
1560 /**
1561  * i2c_smbus_write_byte_data - SMBus "write byte" protocol
1562  * @client: Handle to slave device
1563  * @command: Byte interpreted by slave
1564  * @value: Byte being written
1565  *
1566  * This executes the SMBus "write byte" protocol, returning negative errno
1567  * else zero on success.
1568  */
1569 s32 i2c_smbus_write_byte_data(struct i2c_client *client, u8 command, u8 value)
1570 {
1571         union i2c_smbus_data data;
1572         data.byte = value;
1573         return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1574                               I2C_SMBUS_WRITE,command,
1575                               I2C_SMBUS_BYTE_DATA,&data);
1576 }
1577 EXPORT_SYMBOL(i2c_smbus_write_byte_data);
1578
1579 /**
1580  * i2c_smbus_read_word_data - SMBus "read word" protocol
1581  * @client: Handle to slave device
1582  * @command: Byte interpreted by slave
1583  *
1584  * This executes the SMBus "read word" protocol, returning negative errno
1585  * else a 16-bit unsigned "word" received from the device.
1586  */
1587 s32 i2c_smbus_read_word_data(struct i2c_client *client, u8 command)
1588 {
1589         union i2c_smbus_data data;
1590         int status;
1591
1592         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1593                                 I2C_SMBUS_READ, command,
1594                                 I2C_SMBUS_WORD_DATA, &data);
1595         return (status < 0) ? status : data.word;
1596 }
1597 EXPORT_SYMBOL(i2c_smbus_read_word_data);
1598
1599 /**
1600  * i2c_smbus_write_word_data - SMBus "write word" protocol
1601  * @client: Handle to slave device
1602  * @command: Byte interpreted by slave
1603  * @value: 16-bit "word" being written
1604  *
1605  * This executes the SMBus "write word" protocol, returning negative errno
1606  * else zero on success.
1607  */
1608 s32 i2c_smbus_write_word_data(struct i2c_client *client, u8 command, u16 value)
1609 {
1610         union i2c_smbus_data data;
1611         data.word = value;
1612         return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1613                               I2C_SMBUS_WRITE,command,
1614                               I2C_SMBUS_WORD_DATA,&data);
1615 }
1616 EXPORT_SYMBOL(i2c_smbus_write_word_data);
1617
1618 /**
1619  * i2c_smbus_process_call - SMBus "process call" protocol
1620  * @client: Handle to slave device
1621  * @command: Byte interpreted by slave
1622  * @value: 16-bit "word" being written
1623  *
1624  * This executes the SMBus "process call" protocol, returning negative errno
1625  * else a 16-bit unsigned "word" received from the device.
1626  */
1627 s32 i2c_smbus_process_call(struct i2c_client *client, u8 command, u16 value)
1628 {
1629         union i2c_smbus_data data;
1630         int status;
1631         data.word = value;
1632
1633         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1634                                 I2C_SMBUS_WRITE, command,
1635                                 I2C_SMBUS_PROC_CALL, &data);
1636         return (status < 0) ? status : data.word;
1637 }
1638 EXPORT_SYMBOL(i2c_smbus_process_call);
1639
1640 /**
1641  * i2c_smbus_read_block_data - SMBus "block read" protocol
1642  * @client: Handle to slave device
1643  * @command: Byte interpreted by slave
1644  * @values: Byte array into which data will be read; big enough to hold
1645  *      the data returned by the slave.  SMBus allows at most 32 bytes.
1646  *
1647  * This executes the SMBus "block read" protocol, returning negative errno
1648  * else the number of data bytes in the slave's response.
1649  *
1650  * Note that using this function requires that the client's adapter support
1651  * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality.  Not all adapter drivers
1652  * support this; its emulation through I2C messaging relies on a specific
1653  * mechanism (I2C_M_RECV_LEN) which may not be implemented.
1654  */
1655 s32 i2c_smbus_read_block_data(struct i2c_client *client, u8 command,
1656                               u8 *values)
1657 {
1658         union i2c_smbus_data data;
1659         int status;
1660
1661         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1662                                 I2C_SMBUS_READ, command,
1663                                 I2C_SMBUS_BLOCK_DATA, &data);
1664         if (status)
1665                 return status;
1666
1667         memcpy(values, &data.block[1], data.block[0]);
1668         return data.block[0];
1669 }
1670 EXPORT_SYMBOL(i2c_smbus_read_block_data);
1671
1672 /**
1673  * i2c_smbus_write_block_data - SMBus "block write" protocol
1674  * @client: Handle to slave device
1675  * @command: Byte interpreted by slave
1676  * @length: Size of data block; SMBus allows at most 32 bytes
1677  * @values: Byte array which will be written.
1678  *
1679  * This executes the SMBus "block write" protocol, returning negative errno
1680  * else zero on success.
1681  */
1682 s32 i2c_smbus_write_block_data(struct i2c_client *client, u8 command,
1683                                u8 length, const u8 *values)
1684 {
1685         union i2c_smbus_data data;
1686
1687         if (length > I2C_SMBUS_BLOCK_MAX)
1688                 length = I2C_SMBUS_BLOCK_MAX;
1689         data.block[0] = length;
1690         memcpy(&data.block[1], values, length);
1691         return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
1692                               I2C_SMBUS_WRITE,command,
1693                               I2C_SMBUS_BLOCK_DATA,&data);
1694 }
1695 EXPORT_SYMBOL(i2c_smbus_write_block_data);
1696
1697 /* Returns the number of read bytes */
1698 s32 i2c_smbus_read_i2c_block_data(struct i2c_client *client, u8 command,
1699                                   u8 length, u8 *values)
1700 {
1701         union i2c_smbus_data data;
1702         int status;
1703
1704         if (length > I2C_SMBUS_BLOCK_MAX)
1705                 length = I2C_SMBUS_BLOCK_MAX;
1706         data.block[0] = length;
1707         status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1708                                 I2C_SMBUS_READ, command,
1709                                 I2C_SMBUS_I2C_BLOCK_DATA, &data);
1710         if (status < 0)
1711                 return status;
1712
1713         memcpy(values, &data.block[1], data.block[0]);
1714         return data.block[0];
1715 }
1716 EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
1717
1718 s32 i2c_smbus_write_i2c_block_data(struct i2c_client *client, u8 command,
1719                                    u8 length, const u8 *values)
1720 {
1721         union i2c_smbus_data data;
1722
1723         if (length > I2C_SMBUS_BLOCK_MAX)
1724                 length = I2C_SMBUS_BLOCK_MAX;
1725         data.block[0] = length;
1726         memcpy(data.block + 1, values, length);
1727         return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
1728                               I2C_SMBUS_WRITE, command,
1729                               I2C_SMBUS_I2C_BLOCK_DATA, &data);
1730 }
1731 EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
1732
1733 /* Simulate a SMBus command using the i2c protocol
1734    No checking of parameters is done!  */
1735 static s32 i2c_smbus_xfer_emulated(struct i2c_adapter * adapter, u16 addr,
1736                                    unsigned short flags,
1737                                    char read_write, u8 command, int size,
1738                                    union i2c_smbus_data * data)
1739 {
1740         /* So we need to generate a series of msgs. In the case of writing, we
1741           need to use only one message; when reading, we need two. We initialize
1742           most things with sane defaults, to keep the code below somewhat
1743           simpler. */
1744         unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
1745         unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
1746         int num = read_write == I2C_SMBUS_READ?2:1;
1747         struct i2c_msg msg[2] = { { addr, flags, 1, msgbuf0 },
1748                                   { addr, flags | I2C_M_RD, 0, msgbuf1 }
1749                                 };
1750         int i;
1751         u8 partial_pec = 0;
1752         int status;
1753
1754         msgbuf0[0] = command;
1755         switch(size) {
1756         case I2C_SMBUS_QUICK:
1757                 msg[0].len = 0;
1758                 /* Special case: The read/write field is used as data */
1759                 msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
1760                                         I2C_M_RD : 0);
1761                 num = 1;
1762                 break;
1763         case I2C_SMBUS_BYTE:
1764                 if (read_write == I2C_SMBUS_READ) {
1765                         /* Special case: only a read! */
1766                         msg[0].flags = I2C_M_RD | flags;
1767                         num = 1;
1768                 }
1769                 break;
1770         case I2C_SMBUS_BYTE_DATA:
1771                 if (read_write == I2C_SMBUS_READ)
1772                         msg[1].len = 1;
1773                 else {
1774                         msg[0].len = 2;
1775                         msgbuf0[1] = data->byte;
1776                 }
1777                 break;
1778         case I2C_SMBUS_WORD_DATA:
1779                 if (read_write == I2C_SMBUS_READ)
1780                         msg[1].len = 2;
1781                 else {
1782                         msg[0].len=3;
1783                         msgbuf0[1] = data->word & 0xff;
1784                         msgbuf0[2] = data->word >> 8;
1785                 }
1786                 break;
1787         case I2C_SMBUS_PROC_CALL:
1788                 num = 2; /* Special case */
1789                 read_write = I2C_SMBUS_READ;
1790                 msg[0].len = 3;
1791                 msg[1].len = 2;
1792                 msgbuf0[1] = data->word & 0xff;
1793                 msgbuf0[2] = data->word >> 8;
1794                 break;
1795         case I2C_SMBUS_BLOCK_DATA:
1796                 if (read_write == I2C_SMBUS_READ) {
1797                         msg[1].flags |= I2C_M_RECV_LEN;
1798                         msg[1].len = 1; /* block length will be added by
1799                                            the underlying bus driver */
1800                 } else {
1801                         msg[0].len = data->block[0] + 2;
1802                         if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
1803                                 dev_err(&adapter->dev,
1804                                         "Invalid block write size %d\n",
1805                                         data->block[0]);
1806                                 return -EINVAL;
1807                         }
1808                         for (i = 1; i < msg[0].len; i++)
1809                                 msgbuf0[i] = data->block[i-1];
1810                 }
1811                 break;
1812         case I2C_SMBUS_BLOCK_PROC_CALL:
1813                 num = 2; /* Another special case */
1814                 read_write = I2C_SMBUS_READ;
1815                 if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
1816                         dev_err(&adapter->dev,
1817                                 "Invalid block write size %d\n",
1818                                 data->block[0]);
1819                         return -EINVAL;
1820                 }
1821                 msg[0].len = data->block[0] + 2;
1822                 for (i = 1; i < msg[0].len; i++)
1823                         msgbuf0[i] = data->block[i-1];
1824                 msg[1].flags |= I2C_M_RECV_LEN;
1825                 msg[1].len = 1; /* block length will be added by
1826                                    the underlying bus driver */
1827                 break;
1828         case I2C_SMBUS_I2C_BLOCK_DATA:
1829                 if (read_write == I2C_SMBUS_READ) {
1830                         msg[1].len = data->block[0];
1831                 } else {
1832                         msg[0].len = data->block[0] + 1;
1833                         if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
1834                                 dev_err(&adapter->dev,
1835                                         "Invalid block write size %d\n",
1836                                         data->block[0]);
1837                                 return -EINVAL;
1838                         }
1839                         for (i = 1; i <= data->block[0]; i++)
1840                                 msgbuf0[i] = data->block[i];
1841                 }
1842                 break;
1843         default:
1844                 dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
1845                 return -EOPNOTSUPP;
1846         }
1847
1848         i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
1849                                       && size != I2C_SMBUS_I2C_BLOCK_DATA);
1850         if (i) {
1851                 /* Compute PEC if first message is a write */
1852                 if (!(msg[0].flags & I2C_M_RD)) {
1853                         if (num == 1) /* Write only */
1854                                 i2c_smbus_add_pec(&msg[0]);
1855                         else /* Write followed by read */
1856                                 partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
1857                 }
1858                 /* Ask for PEC if last message is a read */
1859                 if (msg[num-1].flags & I2C_M_RD)
1860                         msg[num-1].len++;
1861         }
1862
1863         status = i2c_transfer(adapter, msg, num);
1864         if (status < 0)
1865                 return status;
1866
1867         /* Check PEC if last message is a read */
1868         if (i && (msg[num-1].flags & I2C_M_RD)) {
1869                 status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
1870                 if (status < 0)
1871                         return status;
1872         }
1873
1874         if (read_write == I2C_SMBUS_READ)
1875                 switch(size) {
1876                         case I2C_SMBUS_BYTE:
1877                                 data->byte = msgbuf0[0];
1878                                 break;
1879                         case I2C_SMBUS_BYTE_DATA:
1880                                 data->byte = msgbuf1[0];
1881                                 break;
1882                         case I2C_SMBUS_WORD_DATA:
1883                         case I2C_SMBUS_PROC_CALL:
1884                                 data->word = msgbuf1[0] | (msgbuf1[1] << 8);
1885                                 break;
1886                         case I2C_SMBUS_I2C_BLOCK_DATA:
1887                                 for (i = 0; i < data->block[0]; i++)
1888                                         data->block[i+1] = msgbuf1[i];
1889                                 break;
1890                         case I2C_SMBUS_BLOCK_DATA:
1891                         case I2C_SMBUS_BLOCK_PROC_CALL:
1892                                 for (i = 0; i < msgbuf1[0] + 1; i++)
1893                                         data->block[i] = msgbuf1[i];
1894                                 break;
1895                 }
1896         return 0;
1897 }
1898
1899 /**
1900  * i2c_smbus_xfer - execute SMBus protocol operations
1901  * @adapter: Handle to I2C bus
1902  * @addr: Address of SMBus slave on that bus
1903  * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
1904  * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
1905  * @command: Byte interpreted by slave, for protocols which use such bytes
1906  * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
1907  * @data: Data to be read or written
1908  *
1909  * This executes an SMBus protocol operation, and returns a negative
1910  * errno code else zero on success.
1911  */
1912 s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
1913                    char read_write, u8 command, int protocol,
1914                    union i2c_smbus_data *data)
1915 {
1916         unsigned long orig_jiffies;
1917         int try;
1918         s32 res;
1919
1920         flags &= I2C_M_TEN | I2C_CLIENT_PEC;
1921
1922         if (adapter->algo->smbus_xfer) {
1923                 rt_mutex_lock(&adapter->bus_lock);
1924
1925                 /* Retry automatically on arbitration loss */
1926                 orig_jiffies = jiffies;
1927                 for (res = 0, try = 0; try <= adapter->retries; try++) {
1928                         res = adapter->algo->smbus_xfer(adapter, addr, flags,
1929                                                         read_write, command,
1930                                                         protocol, data);
1931                         if (res != -EAGAIN)
1932                                 break;
1933                         if (time_after(jiffies,
1934                                        orig_jiffies + adapter->timeout))
1935                                 break;
1936                 }
1937                 rt_mutex_unlock(&adapter->bus_lock);
1938         } else
1939                 res = i2c_smbus_xfer_emulated(adapter,addr,flags,read_write,
1940                                               command, protocol, data);
1941
1942         return res;
1943 }
1944 EXPORT_SYMBOL(i2c_smbus_xfer);
1945
1946 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
1947 MODULE_DESCRIPTION("I2C-Bus main module");
1948 MODULE_LICENSE("GPL");