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