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