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