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