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