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