]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - drivers/i2c/i2c-core-base.c
x86/speculation/mds: Add mitigation control for MDS
[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;
e0638fa4
LW
824
825 if (client->dev.of_node) {
4f001fd3 826 of_node_clear_flag(client->dev.of_node, OF_POPULATED);
e0638fa4
LW
827 of_node_put(client->dev.of_node);
828 }
829
525e6fab
OP
830 if (ACPI_COMPANION(&client->dev))
831 acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
a1d9e6e4
DB
832 device_unregister(&client->dev);
833}
9c1600ed 834EXPORT_SYMBOL_GPL(i2c_unregister_device);
a1d9e6e4
DB
835
836
60b129d7
JD
837static const struct i2c_device_id dummy_id[] = {
838 { "dummy", 0 },
839 { },
840};
841
d2653e92
JD
842static int dummy_probe(struct i2c_client *client,
843 const struct i2c_device_id *id)
844{
845 return 0;
846}
847
848static int dummy_remove(struct i2c_client *client)
e9f1373b
DB
849{
850 return 0;
851}
852
853static struct i2c_driver dummy_driver = {
854 .driver.name = "dummy",
d2653e92
JD
855 .probe = dummy_probe,
856 .remove = dummy_remove,
60b129d7 857 .id_table = dummy_id,
e9f1373b
DB
858};
859
860/**
861 * i2c_new_dummy - return a new i2c device bound to a dummy driver
862 * @adapter: the adapter managing the device
863 * @address: seven bit address to be used
e9f1373b
DB
864 * Context: can sleep
865 *
866 * This returns an I2C client bound to the "dummy" driver, intended for use
867 * with devices that consume multiple addresses. Examples of such chips
868 * include various EEPROMS (like 24c04 and 24c08 models).
869 *
870 * These dummy devices have two main uses. First, most I2C and SMBus calls
871 * except i2c_transfer() need a client handle; the dummy will be that handle.
872 * And second, this prevents the specified address from being bound to a
873 * different driver.
874 *
875 * This returns the new i2c client, which should be saved for later use with
876 * i2c_unregister_device(); or NULL to indicate an error.
877 */
09b8ce0a 878struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
e9f1373b
DB
879{
880 struct i2c_board_info info = {
60b129d7 881 I2C_BOARD_INFO("dummy", address),
e9f1373b
DB
882 };
883
e9f1373b
DB
884 return i2c_new_device(adapter, &info);
885}
886EXPORT_SYMBOL_GPL(i2c_new_dummy);
887
0f614d83
JMH
888/**
889 * i2c_new_secondary_device - Helper to get the instantiated secondary address
890 * and create the associated device
891 * @client: Handle to the primary client
892 * @name: Handle to specify which secondary address to get
893 * @default_addr: Used as a fallback if no secondary address was specified
894 * Context: can sleep
895 *
896 * I2C clients can be composed of multiple I2C slaves bound together in a single
897 * component. The I2C client driver then binds to the master I2C slave and needs
898 * to create I2C dummy clients to communicate with all the other slaves.
899 *
900 * This function creates and returns an I2C dummy client whose I2C address is
901 * retrieved from the platform firmware based on the given slave name. If no
902 * address is specified by the firmware default_addr is used.
903 *
904 * On DT-based platforms the address is retrieved from the "reg" property entry
905 * cell whose "reg-names" value matches the slave name.
906 *
907 * This returns the new i2c client, which should be saved for later use with
908 * i2c_unregister_device(); or NULL to indicate an error.
909 */
910struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
911 const char *name,
912 u16 default_addr)
913{
914 struct device_node *np = client->dev.of_node;
915 u32 addr = default_addr;
916 int i;
917
918 if (np) {
919 i = of_property_match_string(np, "reg-names", name);
920 if (i >= 0)
921 of_property_read_u32_index(np, "reg", i, &addr);
922 }
923
924 dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
925 return i2c_new_dummy(client->adapter, addr);
926}
927EXPORT_SYMBOL_GPL(i2c_new_secondary_device);
928
f37dd80a
DB
929/* ------------------------------------------------------------------------- */
930
16ffadfc
DB
931/* I2C bus adapters -- one roots each I2C or SMBUS segment */
932
83eaaed0 933static void i2c_adapter_dev_release(struct device *dev)
1da177e4 934{
ef2c8321 935 struct i2c_adapter *adap = to_i2c_adapter(dev);
1da177e4
LT
936 complete(&adap->dev_released);
937}
938
8dd1fe15 939unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
390946b1
JD
940{
941 unsigned int depth = 0;
942
943 while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
944 depth++;
945
2771dc34
BG
946 WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
947 "adapter depth exceeds lockdep subclass limit\n");
948
390946b1
JD
949 return depth;
950}
8dd1fe15 951EXPORT_SYMBOL_GPL(i2c_adapter_depth);
390946b1 952
99cd8e25
JD
953/*
954 * Let users instantiate I2C devices through sysfs. This can be used when
955 * platform initialization code doesn't contain the proper data for
956 * whatever reason. Also useful for drivers that do device detection and
957 * detection fails, either because the device uses an unexpected address,
958 * or this is a compatible device with different ID register values.
959 *
960 * Parameter checking may look overzealous, but we really don't want
961 * the user to provide incorrect parameters.
962 */
963static ssize_t
964i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
965 const char *buf, size_t count)
966{
967 struct i2c_adapter *adap = to_i2c_adapter(dev);
968 struct i2c_board_info info;
969 struct i2c_client *client;
970 char *blank, end;
971 int res;
972
99cd8e25
JD
973 memset(&info, 0, sizeof(struct i2c_board_info));
974
975 blank = strchr(buf, ' ');
976 if (!blank) {
977 dev_err(dev, "%s: Missing parameters\n", "new_device");
978 return -EINVAL;
979 }
980 if (blank - buf > I2C_NAME_SIZE - 1) {
981 dev_err(dev, "%s: Invalid device name\n", "new_device");
982 return -EINVAL;
983 }
984 memcpy(info.type, buf, blank - buf);
985
986 /* Parse remaining parameters, reject extra parameters */
987 res = sscanf(++blank, "%hi%c", &info.addr, &end);
988 if (res < 1) {
989 dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
990 return -EINVAL;
991 }
992 if (res > 1 && end != '\n') {
993 dev_err(dev, "%s: Extra parameters\n", "new_device");
994 return -EINVAL;
995 }
996
cfa0327b
WS
997 if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
998 info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
999 info.flags |= I2C_CLIENT_TEN;
1000 }
1001
1002 if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1003 info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1004 info.flags |= I2C_CLIENT_SLAVE;
1005 }
1006
99cd8e25
JD
1007 client = i2c_new_device(adap, &info);
1008 if (!client)
3a89db5f 1009 return -EINVAL;
99cd8e25
JD
1010
1011 /* Keep track of the added device */
dafc50d1 1012 mutex_lock(&adap->userspace_clients_lock);
6629dcff 1013 list_add_tail(&client->detected, &adap->userspace_clients);
dafc50d1 1014 mutex_unlock(&adap->userspace_clients_lock);
99cd8e25
JD
1015 dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1016 info.type, info.addr);
1017
1018 return count;
1019}
a5eb71b2 1020static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
99cd8e25
JD
1021
1022/*
1023 * And of course let the users delete the devices they instantiated, if
1024 * they got it wrong. This interface can only be used to delete devices
1025 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1026 * don't delete devices to which some kernel code still has references.
1027 *
1028 * Parameter checking may look overzealous, but we really don't want
1029 * the user to delete the wrong device.
1030 */
1031static ssize_t
1032i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1033 const char *buf, size_t count)
1034{
1035 struct i2c_adapter *adap = to_i2c_adapter(dev);
1036 struct i2c_client *client, *next;
1037 unsigned short addr;
1038 char end;
1039 int res;
1040
1041 /* Parse parameters, reject extra parameters */
1042 res = sscanf(buf, "%hi%c", &addr, &end);
1043 if (res < 1) {
1044 dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1045 return -EINVAL;
1046 }
1047 if (res > 1 && end != '\n') {
1048 dev_err(dev, "%s: Extra parameters\n", "delete_device");
1049 return -EINVAL;
1050 }
1051
1052 /* Make sure the device was added through sysfs */
1053 res = -ENOENT;
390946b1
JD
1054 mutex_lock_nested(&adap->userspace_clients_lock,
1055 i2c_adapter_depth(adap));
6629dcff
JD
1056 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1057 detected) {
cfa0327b 1058 if (i2c_encode_flags_to_addr(client) == addr) {
99cd8e25
JD
1059 dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1060 "delete_device", client->name, client->addr);
1061
1062 list_del(&client->detected);
1063 i2c_unregister_device(client);
1064 res = count;
1065 break;
1066 }
1067 }
dafc50d1 1068 mutex_unlock(&adap->userspace_clients_lock);
99cd8e25
JD
1069
1070 if (res < 0)
1071 dev_err(dev, "%s: Can't find device in list\n",
1072 "delete_device");
1073 return res;
1074}
e9b526fe
AS
1075static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1076 i2c_sysfs_delete_device);
4f8cf824
JD
1077
1078static struct attribute *i2c_adapter_attrs[] = {
1079 &dev_attr_name.attr,
1080 &dev_attr_new_device.attr,
1081 &dev_attr_delete_device.attr,
1082 NULL
1083};
a5eb71b2 1084ATTRIBUTE_GROUPS(i2c_adapter);
b119dc3f 1085
0826374b 1086struct device_type i2c_adapter_type = {
a5eb71b2 1087 .groups = i2c_adapter_groups,
4f8cf824 1088 .release = i2c_adapter_dev_release,
1da177e4 1089};
0826374b 1090EXPORT_SYMBOL_GPL(i2c_adapter_type);
1da177e4 1091
643dd09e
SW
1092/**
1093 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1094 * @dev: device, probably from some driver model iterator
1095 *
1096 * When traversing the driver model tree, perhaps using driver model
1097 * iterators like @device_for_each_child(), you can't assume very much
1098 * about the nodes you find. Use this function to avoid oopses caused
1099 * by wrongly treating some non-I2C device as an i2c_adapter.
1100 */
1101struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1102{
1103 return (dev->type == &i2c_adapter_type)
1104 ? to_i2c_adapter(dev)
1105 : NULL;
1106}
1107EXPORT_SYMBOL(i2c_verify_adapter);
1108
2bb5095a
JD
1109#ifdef CONFIG_I2C_COMPAT
1110static struct class_compat *i2c_adapter_compat_class;
1111#endif
1112
9c1600ed
DB
1113static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1114{
1115 struct i2c_devinfo *devinfo;
1116
f18c41da 1117 down_read(&__i2c_board_lock);
9c1600ed
DB
1118 list_for_each_entry(devinfo, &__i2c_board_list, list) {
1119 if (devinfo->busnum == adapter->nr
1120 && !i2c_new_device(adapter,
1121 &devinfo->board_info))
09b8ce0a
ZX
1122 dev_err(&adapter->dev,
1123 "Can't create device at 0x%02x\n",
9c1600ed
DB
1124 devinfo->board_info.addr);
1125 }
f18c41da 1126 up_read(&__i2c_board_lock);
9c1600ed
DB
1127}
1128
69b0089a
JD
1129static int i2c_do_add_adapter(struct i2c_driver *driver,
1130 struct i2c_adapter *adap)
026526f5 1131{
4735c98f
JD
1132 /* Detect supported devices on that bus, and instantiate them */
1133 i2c_detect(adap, driver);
1134
1135 /* Let legacy drivers scan this bus for matching devices */
026526f5 1136 if (driver->attach_adapter) {
a920ff41
JD
1137 dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1138 driver->driver.name);
b93d3d37
AS
1139 dev_warn(&adap->dev,
1140 "Please use another way to instantiate your i2c_client\n");
026526f5
JD
1141 /* We ignore the return code; if it fails, too bad */
1142 driver->attach_adapter(adap);
1143 }
1144 return 0;
1145}
1146
69b0089a
JD
1147static int __process_new_adapter(struct device_driver *d, void *data)
1148{
1149 return i2c_do_add_adapter(to_i2c_driver(d), data);
1150}
1151
d1ed7985
PR
1152static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1153 .lock_bus = i2c_adapter_lock_bus,
1154 .trylock_bus = i2c_adapter_trylock_bus,
1155 .unlock_bus = i2c_adapter_unlock_bus,
1156};
1157
4d5538f5
BT
1158static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
1159{
1160 struct irq_domain *domain = adap->host_notify_domain;
1161 irq_hw_number_t hwirq;
1162
1163 if (!domain)
1164 return;
1165
1166 for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
1167 irq_dispose_mapping(irq_find_mapping(domain, hwirq));
1168
1169 irq_domain_remove(domain);
1170 adap->host_notify_domain = NULL;
1171}
1172
1173static int i2c_host_notify_irq_map(struct irq_domain *h,
1174 unsigned int virq,
1175 irq_hw_number_t hw_irq_num)
1176{
1177 irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
1178
1179 return 0;
1180}
1181
1182static const struct irq_domain_ops i2c_host_notify_irq_ops = {
1183 .map = i2c_host_notify_irq_map,
1184};
1185
1186static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
1187{
1188 struct irq_domain *domain;
1189
1190 if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
1191 return 0;
1192
1193 domain = irq_domain_create_linear(adap->dev.fwnode,
1194 I2C_ADDR_7BITS_COUNT,
1195 &i2c_host_notify_irq_ops, adap);
1196 if (!domain)
1197 return -ENOMEM;
1198
1199 adap->host_notify_domain = domain;
1200
1201 return 0;
1202}
1203
1204/**
1205 * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
1206 * I2C client.
1207 * @adap: the adapter
1208 * @addr: the I2C address of the notifying device
1209 * Context: can't sleep
1210 *
1211 * Helper function to be called from an I2C bus driver's interrupt
1212 * handler. It will schedule the Host Notify IRQ.
1213 */
1214int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
1215{
1216 int irq;
1217
1218 if (!adap)
1219 return -EINVAL;
1220
1221 irq = irq_find_mapping(adap->host_notify_domain, addr);
1222 if (irq <= 0)
1223 return -ENXIO;
1224
1225 generic_handle_irq(irq);
1226
1227 return 0;
1228}
1229EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
1230
6e13e641 1231static int i2c_register_adapter(struct i2c_adapter *adap)
1da177e4 1232{
ce0dffaf 1233 int res = -EINVAL;
1da177e4 1234
1d0b19c9 1235 /* Can't register until after driver model init */
95026658 1236 if (WARN_ON(!is_registered)) {
35fc37f8
JD
1237 res = -EAGAIN;
1238 goto out_list;
1239 }
1d0b19c9 1240
2236baa7 1241 /* Sanity checks */
8ddfe410 1242 if (WARN(!adap->name[0], "i2c adapter has no name"))
ce0dffaf 1243 goto out_list;
8ddfe410
WS
1244
1245 if (!adap->algo) {
44239a5a 1246 pr_err("adapter '%s': no algo supplied!\n", adap->name);
ce0dffaf 1247 goto out_list;
2236baa7
JD
1248 }
1249
d1ed7985
PR
1250 if (!adap->lock_ops)
1251 adap->lock_ops = &i2c_adapter_lock_ops;
8320f495 1252
194684e5 1253 rt_mutex_init(&adap->bus_lock);
6ef91fcc 1254 rt_mutex_init(&adap->mux_lock);
dafc50d1 1255 mutex_init(&adap->userspace_clients_lock);
6629dcff 1256 INIT_LIST_HEAD(&adap->userspace_clients);
1da177e4 1257
8fcfef6e
JD
1258 /* Set default timeout to 1 second if not already set */
1259 if (adap->timeout == 0)
1260 adap->timeout = HZ;
1261
4d5538f5
BT
1262 /* register soft irqs for Host Notify */
1263 res = i2c_setup_host_notify_irq_domain(adap);
1264 if (res) {
1265 pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
1266 adap->name, res);
1267 goto out_list;
1268 }
1269
27d9c183 1270 dev_set_name(&adap->dev, "i2c-%d", adap->nr);
4f8cf824
JD
1271 adap->dev.bus = &i2c_bus_type;
1272 adap->dev.type = &i2c_adapter_type;
b119c6c9 1273 res = device_register(&adap->dev);
8ddfe410 1274 if (res) {
44239a5a 1275 pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
b119c6c9 1276 goto out_list;
8ddfe410 1277 }
1da177e4 1278
f8756c67
PR
1279 res = of_i2c_setup_smbus_alert(adap);
1280 if (res)
1281 goto out_reg;
1282
b6d7b3d1
JD
1283 dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1284
6ada5c1e 1285 pm_runtime_no_callbacks(&adap->dev);
04f59143 1286 pm_suspend_ignore_children(&adap->dev, true);
9f924169 1287 pm_runtime_enable(&adap->dev);
6ada5c1e 1288
2bb5095a
JD
1289#ifdef CONFIG_I2C_COMPAT
1290 res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1291 adap->dev.parent);
1292 if (res)
1293 dev_warn(&adap->dev,
1294 "Failed to create compatibility class link\n");
1295#endif
1296
d3b11d83 1297 i2c_init_recovery(adap);
5f9296ba 1298
729d6dd5 1299 /* create pre-declared device nodes */
687b81d0 1300 of_i2c_register_devices(adap);
aec809fc
JN
1301 i2c_acpi_register_devices(adap);
1302 i2c_acpi_install_space_handler(adap);
687b81d0 1303
6e13e641
DB
1304 if (adap->nr < __i2c_first_dynamic_bus_num)
1305 i2c_scan_static_board_info(adap);
1306
4735c98f 1307 /* Notify drivers */
35fc37f8 1308 mutex_lock(&core_lock);
d6703281 1309 bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
caada32a 1310 mutex_unlock(&core_lock);
35fc37f8
JD
1311
1312 return 0;
b119c6c9 1313
f8756c67
PR
1314out_reg:
1315 init_completion(&adap->dev_released);
1316 device_unregister(&adap->dev);
1317 wait_for_completion(&adap->dev_released);
b119c6c9 1318out_list:
35fc37f8 1319 mutex_lock(&core_lock);
b119c6c9 1320 idr_remove(&i2c_adapter_idr, adap->nr);
35fc37f8
JD
1321 mutex_unlock(&core_lock);
1322 return res;
1da177e4
LT
1323}
1324
ee5c2744
DA
1325/**
1326 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1327 * @adap: the adapter to register (with adap->nr initialized)
1328 * Context: can sleep
1329 *
1330 * See i2c_add_numbered_adapter() for details.
1331 */
1332static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1333{
84d0b617 1334 int id;
ee5c2744
DA
1335
1336 mutex_lock(&core_lock);
84d0b617 1337 id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
ee5c2744 1338 mutex_unlock(&core_lock);
84d0b617 1339 if (WARN(id < 0, "couldn't get idr"))
ee5c2744
DA
1340 return id == -ENOSPC ? -EBUSY : id;
1341
1342 return i2c_register_adapter(adap);
1343}
1344
6e13e641
DB
1345/**
1346 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1347 * @adapter: the adapter to add
d64f73be 1348 * Context: can sleep
6e13e641
DB
1349 *
1350 * This routine is used to declare an I2C adapter when its bus number
ee5c2744
DA
1351 * doesn't matter or when its bus number is specified by an dt alias.
1352 * Examples of bases when the bus number doesn't matter: I2C adapters
1353 * dynamically added by USB links or PCI plugin cards.
6e13e641
DB
1354 *
1355 * When this returns zero, a new bus number was allocated and stored
1356 * in adap->nr, and the specified adapter became available for clients.
1357 * Otherwise, a negative errno value is returned.
1358 */
1359int i2c_add_adapter(struct i2c_adapter *adapter)
1360{
ee5c2744 1361 struct device *dev = &adapter->dev;
4ae42b0f 1362 int id;
6e13e641 1363
ee5c2744
DA
1364 if (dev->of_node) {
1365 id = of_alias_get_id(dev->of_node, "i2c");
1366 if (id >= 0) {
1367 adapter->nr = id;
1368 return __i2c_add_numbered_adapter(adapter);
1369 }
1370 }
1371
caada32a 1372 mutex_lock(&core_lock);
4ae42b0f
TH
1373 id = idr_alloc(&i2c_adapter_idr, adapter,
1374 __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
caada32a 1375 mutex_unlock(&core_lock);
84d0b617 1376 if (WARN(id < 0, "couldn't get idr"))
4ae42b0f 1377 return id;
6e13e641
DB
1378
1379 adapter->nr = id;
4ae42b0f 1380
6e13e641
DB
1381 return i2c_register_adapter(adapter);
1382}
1383EXPORT_SYMBOL(i2c_add_adapter);
1384
1385/**
1386 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1387 * @adap: the adapter to register (with adap->nr initialized)
d64f73be 1388 * Context: can sleep
6e13e641
DB
1389 *
1390 * This routine is used to declare an I2C adapter when its bus number
8c07e46f
RD
1391 * matters. For example, use it for I2C adapters from system-on-chip CPUs,
1392 * or otherwise built in to the system's mainboard, and where i2c_board_info
6e13e641
DB
1393 * is used to properly configure I2C devices.
1394 *
488bf314
GL
1395 * If the requested bus number is set to -1, then this function will behave
1396 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1397 *
6e13e641
DB
1398 * If no devices have pre-been declared for this bus, then be sure to
1399 * register the adapter before any dynamically allocated ones. Otherwise
1400 * the required bus ID may not be available.
1401 *
1402 * When this returns zero, the specified adapter became available for
1403 * clients using the bus number provided in adap->nr. Also, the table
1404 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1405 * and the appropriate driver model device nodes are created. Otherwise, a
1406 * negative errno value is returned.
1407 */
1408int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1409{
488bf314
GL
1410 if (adap->nr == -1) /* -1 means dynamically assign bus id */
1411 return i2c_add_adapter(adap);
6e13e641 1412
ee5c2744 1413 return __i2c_add_numbered_adapter(adap);
6e13e641
DB
1414}
1415EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1416
19baba4c 1417static void i2c_do_del_adapter(struct i2c_driver *driver,
69b0089a 1418 struct i2c_adapter *adapter)
026526f5 1419{
4735c98f 1420 struct i2c_client *client, *_n;
026526f5 1421
acec211c
JD
1422 /* Remove the devices we created ourselves as the result of hardware
1423 * probing (using a driver's detect method) */
4735c98f
JD
1424 list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1425 if (client->adapter == adapter) {
1426 dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1427 client->name, client->addr);
1428 list_del(&client->detected);
1429 i2c_unregister_device(client);
1430 }
1431 }
026526f5
JD
1432}
1433
e549c2b5 1434static int __unregister_client(struct device *dev, void *dummy)
5219bf88
JD
1435{
1436 struct i2c_client *client = i2c_verify_client(dev);
1437 if (client && strcmp(client->name, "dummy"))
1438 i2c_unregister_device(client);
1439 return 0;
1440}
1441
1442static int __unregister_dummy(struct device *dev, void *dummy)
e549c2b5
JD
1443{
1444 struct i2c_client *client = i2c_verify_client(dev);
7b43dd19 1445 i2c_unregister_device(client);
e549c2b5
JD
1446 return 0;
1447}
1448
69b0089a
JD
1449static int __process_removed_adapter(struct device_driver *d, void *data)
1450{
19baba4c
LPC
1451 i2c_do_del_adapter(to_i2c_driver(d), data);
1452 return 0;
69b0089a
JD
1453}
1454
d64f73be
DB
1455/**
1456 * i2c_del_adapter - unregister I2C adapter
1457 * @adap: the adapter being unregistered
1458 * Context: can sleep
1459 *
1460 * This unregisters an I2C adapter which was previously registered
1461 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1462 */
71546300 1463void i2c_del_adapter(struct i2c_adapter *adap)
1da177e4 1464{
35fc37f8 1465 struct i2c_adapter *found;
bbd2d9c9 1466 struct i2c_client *client, *next;
1da177e4
LT
1467
1468 /* First make sure that this adapter was ever added */
35fc37f8
JD
1469 mutex_lock(&core_lock);
1470 found = idr_find(&i2c_adapter_idr, adap->nr);
1471 mutex_unlock(&core_lock);
1472 if (found != adap) {
44239a5a 1473 pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
71546300 1474 return;
1da177e4
LT
1475 }
1476
aec809fc 1477 i2c_acpi_remove_space_handler(adap);
026526f5 1478 /* Tell drivers about this removal */
35fc37f8 1479 mutex_lock(&core_lock);
19baba4c 1480 bus_for_each_drv(&i2c_bus_type, NULL, adap,
69b0089a 1481 __process_removed_adapter);
35fc37f8 1482 mutex_unlock(&core_lock);
1da177e4 1483
bbd2d9c9 1484 /* Remove devices instantiated from sysfs */
390946b1
JD
1485 mutex_lock_nested(&adap->userspace_clients_lock,
1486 i2c_adapter_depth(adap));
6629dcff
JD
1487 list_for_each_entry_safe(client, next, &adap->userspace_clients,
1488 detected) {
1489 dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1490 client->addr);
1491 list_del(&client->detected);
1492 i2c_unregister_device(client);
bbd2d9c9 1493 }
dafc50d1 1494 mutex_unlock(&adap->userspace_clients_lock);
bbd2d9c9 1495
e549c2b5 1496 /* Detach any active clients. This can't fail, thus we do not
5219bf88
JD
1497 * check the returned value. This is a two-pass process, because
1498 * we can't remove the dummy devices during the first pass: they
1499 * could have been instantiated by real devices wishing to clean
1500 * them up properly, so we give them a chance to do that first. */
19baba4c
LPC
1501 device_for_each_child(&adap->dev, NULL, __unregister_client);
1502 device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1da177e4 1503
2bb5095a
JD
1504#ifdef CONFIG_I2C_COMPAT
1505 class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1506 adap->dev.parent);
1507#endif
1508
c5567521
TLSC
1509 /* device name is gone after device_unregister */
1510 dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1511
9f924169
WS
1512 pm_runtime_disable(&adap->dev);
1513
4d5538f5
BT
1514 i2c_host_notify_irq_teardown(adap);
1515
26680ee2
WS
1516 /* wait until all references to the device are gone
1517 *
1518 * FIXME: This is old code and should ideally be replaced by an
1519 * alternative which results in decoupling the lifetime of the struct
1520 * device from the i2c_adapter, like spi or netdev do. Any solution
95cc1e3d 1521 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
26680ee2 1522 */
1da177e4 1523 init_completion(&adap->dev_released);
1da177e4 1524 device_unregister(&adap->dev);
1da177e4 1525 wait_for_completion(&adap->dev_released);
1da177e4 1526
6e13e641 1527 /* free bus id */
35fc37f8 1528 mutex_lock(&core_lock);
1da177e4 1529 idr_remove(&i2c_adapter_idr, adap->nr);
35fc37f8 1530 mutex_unlock(&core_lock);
1da177e4 1531
bd4bc3db
JD
1532 /* Clear the device structure in case this adapter is ever going to be
1533 added again */
1534 memset(&adap->dev, 0, sizeof(adap->dev));
1da177e4 1535}
c0564606 1536EXPORT_SYMBOL(i2c_del_adapter);
1da177e4 1537
54177ccf
WS
1538/**
1539 * i2c_parse_fw_timings - get I2C related timing parameters from firmware
1540 * @dev: The device to scan for I2C timing properties
1541 * @t: the i2c_timings struct to be filled with values
1542 * @use_defaults: bool to use sane defaults derived from the I2C specification
1543 * when properties are not found, otherwise use 0
1544 *
1545 * Scan the device for the generic I2C properties describing timing parameters
1546 * for the signal and fill the given struct with the results. If a property was
1547 * not found and use_defaults was true, then maximum timings are assumed which
1548 * are derived from the I2C specification. If use_defaults is not used, the
1549 * results will be 0, so drivers can apply their own defaults later. The latter
1550 * is mainly intended for avoiding regressions of existing drivers which want
1551 * to switch to this function. New drivers almost always should use the defaults.
1552 */
1553
1554void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
1555{
1556 int ret;
1557
1558 memset(t, 0, sizeof(*t));
1559
1560 ret = device_property_read_u32(dev, "clock-frequency", &t->bus_freq_hz);
1561 if (ret && use_defaults)
1562 t->bus_freq_hz = 100000;
1563
1564 ret = device_property_read_u32(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns);
1565 if (ret && use_defaults) {
1566 if (t->bus_freq_hz <= 100000)
1567 t->scl_rise_ns = 1000;
1568 else if (t->bus_freq_hz <= 400000)
1569 t->scl_rise_ns = 300;
1570 else
1571 t->scl_rise_ns = 120;
1572 }
1573
1574 ret = device_property_read_u32(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns);
1575 if (ret && use_defaults) {
1576 if (t->bus_freq_hz <= 400000)
1577 t->scl_fall_ns = 300;
1578 else
1579 t->scl_fall_ns = 120;
1580 }
1581
1582 device_property_read_u32(dev, "i2c-scl-internal-delay-ns", &t->scl_int_delay_ns);
1583
1584 ret = device_property_read_u32(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns);
1585 if (ret && use_defaults)
1586 t->sda_fall_ns = t->scl_fall_ns;
1587}
1588EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
1589
7b4fbc50
DB
1590/* ------------------------------------------------------------------------- */
1591
7ae31482
JD
1592int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1593{
1594 int res;
1595
1596 mutex_lock(&core_lock);
1597 res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1598 mutex_unlock(&core_lock);
1599
1600 return res;
1601}
1602EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1603
69b0089a 1604static int __process_new_driver(struct device *dev, void *data)
7f101a97 1605{
4f8cf824
JD
1606 if (dev->type != &i2c_adapter_type)
1607 return 0;
69b0089a 1608 return i2c_do_add_adapter(data, to_i2c_adapter(dev));
7f101a97
DY
1609}
1610
7b4fbc50
DB
1611/*
1612 * An i2c_driver is used with one or more i2c_client (device) nodes to access
729d6dd5 1613 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1da177e4
LT
1614 */
1615
de59cf9e 1616int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1da177e4 1617{
7eebcb7c 1618 int res;
1da177e4 1619
1d0b19c9 1620 /* Can't register until after driver model init */
95026658 1621 if (WARN_ON(!is_registered))
1d0b19c9
DB
1622 return -EAGAIN;
1623
1da177e4 1624 /* add the driver to the list of i2c drivers in the driver core */
de59cf9e 1625 driver->driver.owner = owner;
1da177e4 1626 driver->driver.bus = &i2c_bus_type;
147b36d5 1627 INIT_LIST_HEAD(&driver->clients);
1da177e4 1628
729d6dd5 1629 /* When registration returns, the driver core
6e13e641
DB
1630 * will have called probe() for all matching-but-unbound devices.
1631 */
1da177e4
LT
1632 res = driver_register(&driver->driver);
1633 if (res)
7eebcb7c 1634 return res;
438d6c2c 1635
44239a5a 1636 pr_debug("driver [%s] registered\n", driver->driver.name);
1da177e4 1637
4735c98f 1638 /* Walk the adapters that are already present */
7ae31482 1639 i2c_for_each_dev(driver, __process_new_driver);
35fc37f8 1640
7f101a97
DY
1641 return 0;
1642}
1643EXPORT_SYMBOL(i2c_register_driver);
1644
69b0089a 1645static int __process_removed_driver(struct device *dev, void *data)
7f101a97 1646{
19baba4c
LPC
1647 if (dev->type == &i2c_adapter_type)
1648 i2c_do_del_adapter(data, to_i2c_adapter(dev));
1649 return 0;
1da177e4
LT
1650}
1651
a1d9e6e4
DB
1652/**
1653 * i2c_del_driver - unregister I2C driver
1654 * @driver: the driver being unregistered
d64f73be 1655 * Context: can sleep
a1d9e6e4 1656 */
b3e82096 1657void i2c_del_driver(struct i2c_driver *driver)
1da177e4 1658{
7ae31482 1659 i2c_for_each_dev(driver, __process_removed_driver);
1da177e4
LT
1660
1661 driver_unregister(&driver->driver);
44239a5a 1662 pr_debug("driver [%s] unregistered\n", driver->driver.name);
1da177e4 1663}
c0564606 1664EXPORT_SYMBOL(i2c_del_driver);
1da177e4 1665
7b4fbc50
DB
1666/* ------------------------------------------------------------------------- */
1667
e48d3319
JD
1668/**
1669 * i2c_use_client - increments the reference count of the i2c client structure
1670 * @client: the client being referenced
1671 *
1672 * Each live reference to a client should be refcounted. The driver model does
1673 * that automatically as part of driver binding, so that most drivers don't
1674 * need to do this explicitly: they hold a reference until they're unbound
1675 * from the device.
1676 *
1677 * A pointer to the client with the incremented reference counter is returned.
1678 */
1679struct i2c_client *i2c_use_client(struct i2c_client *client)
1da177e4 1680{
6ea438ec
DB
1681 if (client && get_device(&client->dev))
1682 return client;
1683 return NULL;
1da177e4 1684}
c0564606 1685EXPORT_SYMBOL(i2c_use_client);
1da177e4 1686
e48d3319
JD
1687/**
1688 * i2c_release_client - release a use of the i2c client structure
1689 * @client: the client being no longer referenced
1690 *
1691 * Must be called when a user of a client is finished with it.
1692 */
1693void i2c_release_client(struct i2c_client *client)
1da177e4 1694{
6ea438ec
DB
1695 if (client)
1696 put_device(&client->dev);
1da177e4 1697}
c0564606 1698EXPORT_SYMBOL(i2c_release_client);
1da177e4 1699
9b766b81
DB
1700struct i2c_cmd_arg {
1701 unsigned cmd;
1702 void *arg;
1703};
1704
1705static int i2c_cmd(struct device *dev, void *_arg)
1706{
1707 struct i2c_client *client = i2c_verify_client(dev);
1708 struct i2c_cmd_arg *arg = _arg;
0acc2b32
LPC
1709 struct i2c_driver *driver;
1710
1711 if (!client || !client->dev.driver)
1712 return 0;
9b766b81 1713
0acc2b32
LPC
1714 driver = to_i2c_driver(client->dev.driver);
1715 if (driver->command)
1716 driver->command(client, arg->cmd, arg->arg);
9b766b81
DB
1717 return 0;
1718}
1719
1da177e4
LT
1720void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1721{
9b766b81 1722 struct i2c_cmd_arg cmd_arg;
1da177e4 1723
9b766b81
DB
1724 cmd_arg.cmd = cmd;
1725 cmd_arg.arg = arg;
1726 device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1da177e4 1727}
c0564606 1728EXPORT_SYMBOL(i2c_clients_command);
1da177e4
LT
1729
1730static int __init i2c_init(void)
1731{
1732 int retval;
1733
03bde7c3
WS
1734 retval = of_alias_get_highest_id("i2c");
1735
1736 down_write(&__i2c_board_lock);
1737 if (retval >= __i2c_first_dynamic_bus_num)
1738 __i2c_first_dynamic_bus_num = retval + 1;
1739 up_write(&__i2c_board_lock);
1740
1da177e4 1741 retval = bus_register(&i2c_bus_type);
1da177e4
LT
1742 if (retval)
1743 return retval;
b980a26d
WS
1744
1745 is_registered = true;
1746
2bb5095a
JD
1747#ifdef CONFIG_I2C_COMPAT
1748 i2c_adapter_compat_class = class_compat_register("i2c-adapter");
1749 if (!i2c_adapter_compat_class) {
1750 retval = -ENOMEM;
1751 goto bus_err;
1752 }
1753#endif
e9f1373b
DB
1754 retval = i2c_add_driver(&dummy_driver);
1755 if (retval)
2bb5095a 1756 goto class_err;
ea7513bb
PA
1757
1758 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1759 WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
525e6fab
OP
1760 if (IS_ENABLED(CONFIG_ACPI))
1761 WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
ea7513bb 1762
e9f1373b
DB
1763 return 0;
1764
2bb5095a
JD
1765class_err:
1766#ifdef CONFIG_I2C_COMPAT
1767 class_compat_unregister(i2c_adapter_compat_class);
e9f1373b 1768bus_err:
2bb5095a 1769#endif
b980a26d 1770 is_registered = false;
e9f1373b
DB
1771 bus_unregister(&i2c_bus_type);
1772 return retval;
1da177e4
LT
1773}
1774
1775static void __exit i2c_exit(void)
1776{
525e6fab
OP
1777 if (IS_ENABLED(CONFIG_ACPI))
1778 WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
ea7513bb
PA
1779 if (IS_ENABLED(CONFIG_OF_DYNAMIC))
1780 WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
e9f1373b 1781 i2c_del_driver(&dummy_driver);
2bb5095a
JD
1782#ifdef CONFIG_I2C_COMPAT
1783 class_compat_unregister(i2c_adapter_compat_class);
1784#endif
1da177e4 1785 bus_unregister(&i2c_bus_type);
d9a83d62 1786 tracepoint_synchronize_unregister();
1da177e4
LT
1787}
1788
a10f9e7c
DB
1789/* We must initialize early, because some subsystems register i2c drivers
1790 * in subsys_initcall() code, but are linked (and initialized) before i2c.
1791 */
1792postcore_initcall(i2c_init);
1da177e4
LT
1793module_exit(i2c_exit);
1794
1795/* ----------------------------------------------------
1796 * the functional interface to the i2c busses.
1797 * ----------------------------------------------------
1798 */
1799
b7f62584
WS
1800/* Check if val is exceeding the quirk IFF quirk is non 0 */
1801#define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
1802
1803static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
1804{
1805 dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
1806 err_msg, msg->addr, msg->len,
1807 msg->flags & I2C_M_RD ? "read" : "write");
1808 return -EOPNOTSUPP;
1809}
1810
1811static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1812{
1813 const struct i2c_adapter_quirks *q = adap->quirks;
1814 int max_num = q->max_num_msgs, i;
1815 bool do_len_check = true;
1816
1817 if (q->flags & I2C_AQ_COMB) {
1818 max_num = 2;
1819
1820 /* special checks for combined messages */
1821 if (num == 2) {
1822 if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
1823 return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
1824
1825 if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
1826 return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
1827
1828 if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
1829 return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
1830
1831 if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
1832 return i2c_quirk_error(adap, &msgs[0], "msg too long");
1833
1834 if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
1835 return i2c_quirk_error(adap, &msgs[1], "msg too long");
1836
1837 do_len_check = false;
1838 }
1839 }
1840
1841 if (i2c_quirk_exceeded(num, max_num))
1842 return i2c_quirk_error(adap, &msgs[0], "too many messages");
1843
1844 for (i = 0; i < num; i++) {
1845 u16 len = msgs[i].len;
1846
1847 if (msgs[i].flags & I2C_M_RD) {
1848 if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
1849 return i2c_quirk_error(adap, &msgs[i], "msg too long");
1850 } else {
1851 if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
1852 return i2c_quirk_error(adap, &msgs[i], "msg too long");
1853 }
1854 }
1855
1856 return 0;
1857}
1858
b37d2a3a
JD
1859/**
1860 * __i2c_transfer - unlocked flavor of i2c_transfer
1861 * @adap: Handle to I2C bus
1862 * @msgs: One or more messages to execute before STOP is issued to
1863 * terminate the operation; each message begins with a START.
1864 * @num: Number of messages to be executed.
1865 *
1866 * Returns negative errno, else the number of messages executed.
1867 *
1868 * Adapter lock must be held when calling this function. No debug logging
1869 * takes place. adap->algo->master_xfer existence isn't checked.
1870 */
1871int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1872{
1873 unsigned long orig_jiffies;
1874 int ret, try;
1875
b7f62584
WS
1876 if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
1877 return -EOPNOTSUPP;
1878
d9a83d62
DH
1879 /* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
1880 * enabled. This is an efficient way of keeping the for-loop from
1881 * being executed when not needed.
1882 */
1883 if (static_key_false(&i2c_trace_msg)) {
1884 int i;
1885 for (i = 0; i < num; i++)
1886 if (msgs[i].flags & I2C_M_RD)
1887 trace_i2c_read(adap, &msgs[i], i);
1888 else
1889 trace_i2c_write(adap, &msgs[i], i);
1890 }
1891
b37d2a3a
JD
1892 /* Retry automatically on arbitration loss */
1893 orig_jiffies = jiffies;
1894 for (ret = 0, try = 0; try <= adap->retries; try++) {
1895 ret = adap->algo->master_xfer(adap, msgs, num);
1896 if (ret != -EAGAIN)
1897 break;
1898 if (time_after(jiffies, orig_jiffies + adap->timeout))
1899 break;
1900 }
1901
d9a83d62
DH
1902 if (static_key_false(&i2c_trace_msg)) {
1903 int i;
1904 for (i = 0; i < ret; i++)
1905 if (msgs[i].flags & I2C_M_RD)
1906 trace_i2c_reply(adap, &msgs[i], i);
1907 trace_i2c_result(adap, i, ret);
1908 }
1909
b37d2a3a
JD
1910 return ret;
1911}
1912EXPORT_SYMBOL(__i2c_transfer);
1913
a1cdedac
DB
1914/**
1915 * i2c_transfer - execute a single or combined I2C message
1916 * @adap: Handle to I2C bus
1917 * @msgs: One or more messages to execute before STOP is issued to
1918 * terminate the operation; each message begins with a START.
1919 * @num: Number of messages to be executed.
1920 *
1921 * Returns negative errno, else the number of messages executed.
1922 *
1923 * Note that there is no requirement that each message be sent to
1924 * the same slave address, although that is the most common model.
1925 */
09b8ce0a 1926int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
1da177e4 1927{
b37d2a3a 1928 int ret;
1da177e4 1929
a1cdedac
DB
1930 /* REVISIT the fault reporting model here is weak:
1931 *
1932 * - When we get an error after receiving N bytes from a slave,
1933 * there is no way to report "N".
1934 *
1935 * - When we get a NAK after transmitting N bytes to a slave,
1936 * there is no way to report "N" ... or to let the master
1937 * continue executing the rest of this combined message, if
1938 * that's the appropriate response.
1939 *
1940 * - When for example "num" is two and we successfully complete
1941 * the first message but get an error part way through the
1942 * second, it's unclear whether that should be reported as
1943 * one (discarding status on the second message) or errno
1944 * (discarding status on the first one).
1945 */
1946
1da177e4
LT
1947 if (adap->algo->master_xfer) {
1948#ifdef DEBUG
1949 for (ret = 0; ret < num; ret++) {
b93d3d37
AS
1950 dev_dbg(&adap->dev,
1951 "master_xfer[%d] %c, addr=0x%02x, len=%d%s\n",
1952 ret, (msgs[ret].flags & I2C_M_RD) ? 'R' : 'W',
1953 msgs[ret].addr, msgs[ret].len,
209d27c3 1954 (msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
1da177e4
LT
1955 }
1956#endif
1957
cea443a8 1958 if (in_atomic() || irqs_disabled()) {
fb79e09a 1959 ret = i2c_trylock_bus(adap, I2C_LOCK_SEGMENT);
cea443a8
MR
1960 if (!ret)
1961 /* I2C activity is ongoing. */
1962 return -EAGAIN;
1963 } else {
8320f495 1964 i2c_lock_bus(adap, I2C_LOCK_SEGMENT);
cea443a8
MR
1965 }
1966
b37d2a3a 1967 ret = __i2c_transfer(adap, msgs, num);
8320f495 1968 i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
1da177e4
LT
1969
1970 return ret;
1971 } else {
1972 dev_dbg(&adap->dev, "I2C level transfers not supported\n");
24a5bb7b 1973 return -EOPNOTSUPP;
1da177e4
LT
1974 }
1975}
c0564606 1976EXPORT_SYMBOL(i2c_transfer);
1da177e4 1977
a1cdedac
DB
1978/**
1979 * i2c_master_send - issue a single I2C message in master transmit mode
1980 * @client: Handle to slave device
1981 * @buf: Data that will be written to the slave
0c43ea54 1982 * @count: How many bytes to write, must be less than 64k since msg.len is u16
a1cdedac
DB
1983 *
1984 * Returns negative errno, or else the number of bytes written.
1985 */
0cc43a18 1986int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
1da177e4
LT
1987{
1988 int ret;
7225acf4 1989 struct i2c_adapter *adap = client->adapter;
1da177e4
LT
1990 struct i2c_msg msg;
1991
815f55f2
JD
1992 msg.addr = client->addr;
1993 msg.flags = client->flags & I2C_M_TEN;
1994 msg.len = count;
1995 msg.buf = (char *)buf;
438d6c2c 1996
815f55f2 1997 ret = i2c_transfer(adap, &msg, 1);
1da177e4 1998
834aa6f3
WS
1999 /*
2000 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2001 * transmitted, else error code.
2002 */
815f55f2 2003 return (ret == 1) ? count : ret;
1da177e4 2004}
c0564606 2005EXPORT_SYMBOL(i2c_master_send);
1da177e4 2006
a1cdedac
DB
2007/**
2008 * i2c_master_recv - issue a single I2C message in master receive mode
2009 * @client: Handle to slave device
2010 * @buf: Where to store data read from slave
0c43ea54 2011 * @count: How many bytes to read, must be less than 64k since msg.len is u16
a1cdedac
DB
2012 *
2013 * Returns negative errno, or else the number of bytes read.
2014 */
0cc43a18 2015int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
1da177e4 2016{
7225acf4 2017 struct i2c_adapter *adap = client->adapter;
1da177e4
LT
2018 struct i2c_msg msg;
2019 int ret;
815f55f2
JD
2020
2021 msg.addr = client->addr;
2022 msg.flags = client->flags & I2C_M_TEN;
2023 msg.flags |= I2C_M_RD;
2024 msg.len = count;
2025 msg.buf = buf;
2026
2027 ret = i2c_transfer(adap, &msg, 1);
2028
834aa6f3
WS
2029 /*
2030 * If everything went ok (i.e. 1 msg received), return #bytes received,
2031 * else error code.
2032 */
815f55f2 2033 return (ret == 1) ? count : ret;
1da177e4 2034}
c0564606 2035EXPORT_SYMBOL(i2c_master_recv);
1da177e4 2036
1da177e4
LT
2037/* ----------------------------------------------------
2038 * the i2c address scanning function
2039 * Will not work for 10-bit addresses!
2040 * ----------------------------------------------------
2041 */
1da177e4 2042
63e4e802
JD
2043/*
2044 * Legacy default probe function, mostly relevant for SMBus. The default
2045 * probe method is a quick write, but it is known to corrupt the 24RF08
2046 * EEPROMs due to a state machine bug, and could also irreversibly
2047 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2048 * we use a short byte read instead. Also, some bus drivers don't implement
2049 * quick write, so we fallback to a byte read in that case too.
2050 * On x86, there is another special case for FSC hardware monitoring chips,
2051 * which want regular byte reads (address 0x73.) Fortunately, these are the
2052 * only known chips using this I2C address on PC hardware.
2053 * Returns 1 if probe succeeded, 0 if not.
2054 */
2055static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2056{
2057 int err;
2058 union i2c_smbus_data dummy;
2059
2060#ifdef CONFIG_X86
2061 if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2062 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2063 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2064 I2C_SMBUS_BYTE_DATA, &dummy);
2065 else
2066#endif
8031d79b
JD
2067 if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2068 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
63e4e802
JD
2069 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2070 I2C_SMBUS_QUICK, NULL);
8031d79b
JD
2071 else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2072 err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2073 I2C_SMBUS_BYTE, &dummy);
2074 else {
d63a9e85
AL
2075 dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2076 addr);
8031d79b
JD
2077 err = -EOPNOTSUPP;
2078 }
63e4e802
JD
2079
2080 return err >= 0;
2081}
2082
ccfbbd08 2083static int i2c_detect_address(struct i2c_client *temp_client,
4735c98f
JD
2084 struct i2c_driver *driver)
2085{
2086 struct i2c_board_info info;
2087 struct i2c_adapter *adapter = temp_client->adapter;
2088 int addr = temp_client->addr;
2089 int err;
2090
2091 /* Make sure the address is valid */
66be6056 2092 err = i2c_check_7bit_addr_validity_strict(addr);
656b8761 2093 if (err) {
4735c98f
JD
2094 dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2095 addr);
656b8761 2096 return err;
4735c98f
JD
2097 }
2098
9bccc70a 2099 /* Skip if already in use (7 bit, no need to encode flags) */
3b5f794b 2100 if (i2c_check_addr_busy(adapter, addr))
4735c98f
JD
2101 return 0;
2102
ccfbbd08 2103 /* Make sure there is something at this address */
63e4e802
JD
2104 if (!i2c_default_probe(adapter, addr))
2105 return 0;
4735c98f
JD
2106
2107 /* Finally call the custom detection function */
2108 memset(&info, 0, sizeof(struct i2c_board_info));
2109 info.addr = addr;
310ec792 2110 err = driver->detect(temp_client, &info);
4735c98f
JD
2111 if (err) {
2112 /* -ENODEV is returned if the detection fails. We catch it
2113 here as this isn't an error. */
2114 return err == -ENODEV ? 0 : err;
2115 }
2116
2117 /* Consistency check */
2118 if (info.type[0] == '\0') {
b93d3d37
AS
2119 dev_err(&adapter->dev,
2120 "%s detection function provided no name for 0x%x\n",
2121 driver->driver.name, addr);
4735c98f
JD
2122 } else {
2123 struct i2c_client *client;
2124
2125 /* Detection succeeded, instantiate the device */
0c176170
WS
2126 if (adapter->class & I2C_CLASS_DEPRECATED)
2127 dev_warn(&adapter->dev,
2128 "This adapter will soon drop class based instantiation of devices. "
2129 "Please make sure client 0x%02x gets instantiated by other means. "
2130 "Check 'Documentation/i2c/instantiating-devices' for details.\n",
2131 info.addr);
2132
4735c98f
JD
2133 dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2134 info.type, info.addr);
2135 client = i2c_new_device(adapter, &info);
2136 if (client)
2137 list_add_tail(&client->detected, &driver->clients);
2138 else
2139 dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2140 info.type, info.addr);
2141 }
2142 return 0;
2143}
2144
2145static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2146{
c3813d6a 2147 const unsigned short *address_list;
4735c98f
JD
2148 struct i2c_client *temp_client;
2149 int i, err = 0;
2150 int adap_id = i2c_adapter_id(adapter);
2151
c3813d6a
JD
2152 address_list = driver->address_list;
2153 if (!driver->detect || !address_list)
4735c98f
JD
2154 return 0;
2155
45552272
WS
2156 /* Warn that the adapter lost class based instantiation */
2157 if (adapter->class == I2C_CLASS_DEPRECATED) {
2158 dev_dbg(&adapter->dev,
b93d3d37
AS
2159 "This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
2160 "If you need it, check 'Documentation/i2c/instantiating-devices' for alternatives.\n",
45552272
WS
2161 driver->driver.name);
2162 return 0;
2163 }
2164
51b54ba9
JD
2165 /* Stop here if the classes do not match */
2166 if (!(adapter->class & driver->class))
2167 return 0;
2168
4735c98f
JD
2169 /* Set up a temporary client to help detect callback */
2170 temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2171 if (!temp_client)
2172 return -ENOMEM;
2173 temp_client->adapter = adapter;
2174
c3813d6a 2175 for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
b93d3d37
AS
2176 dev_dbg(&adapter->dev,
2177 "found normal entry for adapter %d, addr 0x%02x\n",
2178 adap_id, address_list[i]);
c3813d6a 2179 temp_client->addr = address_list[i];
ccfbbd08 2180 err = i2c_detect_address(temp_client, driver);
51b54ba9
JD
2181 if (unlikely(err))
2182 break;
4735c98f
JD
2183 }
2184
4735c98f
JD
2185 kfree(temp_client);
2186 return err;
2187}
2188
d44f19d5
JD
2189int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2190{
2191 return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2192 I2C_SMBUS_QUICK, NULL) >= 0;
2193}
2194EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2195
12b5053a
JD
2196struct i2c_client *
2197i2c_new_probed_device(struct i2c_adapter *adap,
2198 struct i2c_board_info *info,
9a94241a
JD
2199 unsigned short const *addr_list,
2200 int (*probe)(struct i2c_adapter *, unsigned short addr))
12b5053a
JD
2201{
2202 int i;
2203
8031d79b 2204 if (!probe)
9a94241a 2205 probe = i2c_default_probe;
12b5053a 2206
12b5053a
JD
2207 for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2208 /* Check address validity */
66be6056 2209 if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
b93d3d37
AS
2210 dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
2211 addr_list[i]);
12b5053a
JD
2212 continue;
2213 }
2214
9bccc70a 2215 /* Check address availability (7 bit, no need to encode flags) */
3b5f794b 2216 if (i2c_check_addr_busy(adap, addr_list[i])) {
b93d3d37
AS
2217 dev_dbg(&adap->dev,
2218 "Address 0x%02x already in use, not probing\n",
2219 addr_list[i]);
12b5053a
JD
2220 continue;
2221 }
2222
63e4e802 2223 /* Test address responsiveness */
9a94241a 2224 if (probe(adap, addr_list[i]))
63e4e802 2225 break;
12b5053a 2226 }
12b5053a
JD
2227
2228 if (addr_list[i] == I2C_CLIENT_END) {
2229 dev_dbg(&adap->dev, "Probing failed, no device found\n");
2230 return NULL;
2231 }
2232
2233 info->addr = addr_list[i];
2234 return i2c_new_device(adap, info);
2235}
2236EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2237
d735b34d 2238struct i2c_adapter *i2c_get_adapter(int nr)
1da177e4 2239{
1da177e4 2240 struct i2c_adapter *adapter;
438d6c2c 2241
caada32a 2242 mutex_lock(&core_lock);
d735b34d 2243 adapter = idr_find(&i2c_adapter_idr, nr);
611e12ea
VZ
2244 if (!adapter)
2245 goto exit;
2246
2247 if (try_module_get(adapter->owner))
2248 get_device(&adapter->dev);
2249 else
a0920e10
MH
2250 adapter = NULL;
2251
611e12ea 2252 exit:
caada32a 2253 mutex_unlock(&core_lock);
a0920e10 2254 return adapter;
1da177e4 2255}
c0564606 2256EXPORT_SYMBOL(i2c_get_adapter);
1da177e4
LT
2257
2258void i2c_put_adapter(struct i2c_adapter *adap)
2259{
611e12ea
VZ
2260 if (!adap)
2261 return;
2262
2263 put_device(&adap->dev);
2264 module_put(adap->owner);
1da177e4 2265}
c0564606 2266EXPORT_SYMBOL(i2c_put_adapter);
1da177e4 2267
1da177e4
LT
2268MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2269MODULE_DESCRIPTION("I2C-Bus main module");
2270MODULE_LICENSE("GPL");