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