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