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