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