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