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