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