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