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