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