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