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