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