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