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