i2c-core-base.c 65 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-or-later
2
3
4
5
6
7
8
9
10
/*
 * Linux I2C core
 *
 * Copyright (C) 1995-99 Simon G. Vogl
 *   With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>
 *   Mux support by Rodolfo Giometti <giometti@enneenne.com> and
 *   Michael Lawnick <michael.lawnick.ext@nsn.com>
 *
 * Copyright (C) 2013-2017 Wolfram Sang <wsa@the-dreams.de>
11
 */
Linus Torvalds's avatar
Linus Torvalds committed
12

Wolfram Sang's avatar
Wolfram Sang committed
13
14
#define pr_fmt(fmt) "i2c-core: " fmt

15
#include <dt-bindings/i2c/i2c.h>
Wolfram Sang's avatar
Wolfram Sang committed
16
17
18
#include <linux/acpi.h>
#include <linux/clk/clk-conf.h>
#include <linux/completion.h>
19
#include <linux/delay.h>
Wolfram Sang's avatar
Wolfram Sang committed
20
#include <linux/err.h>
Linus Torvalds's avatar
Linus Torvalds committed
21
#include <linux/errno.h>
22
#include <linux/gpio/consumer.h>
Linus Torvalds's avatar
Linus Torvalds committed
23
#include <linux/i2c.h>
24
#include <linux/i2c-smbus.h>
Linus Torvalds's avatar
Linus Torvalds committed
25
#include <linux/idr.h>
Wolfram Sang's avatar
Wolfram Sang committed
26
27
28
29
30
#include <linux/init.h>
#include <linux/irqflags.h>
#include <linux/jump_label.h>
#include <linux/kernel.h>
#include <linux/module.h>
31
#include <linux/mutex.h>
32
#include <linux/of_device.h>
Wolfram Sang's avatar
Wolfram Sang committed
33
#include <linux/of.h>
34
#include <linux/of_irq.h>
35
#include <linux/pm_domain.h>
Wolfram Sang's avatar
Wolfram Sang committed
36
#include <linux/pm_runtime.h>
37
#include <linux/pm_wakeirq.h>
38
#include <linux/property.h>
Wolfram Sang's avatar
Wolfram Sang committed
39
40
#include <linux/rwsem.h>
#include <linux/slab.h>
Linus Torvalds's avatar
Linus Torvalds committed
41

42
43
#include "i2c-core.h"

44
45
#define CREATE_TRACE_POINTS
#include <trace/events/i2c.h>
Linus Torvalds's avatar
Linus Torvalds committed
46

47
48
49
#define I2C_ADDR_OFFSET_TEN_BIT	0xa000
#define I2C_ADDR_OFFSET_SLAVE	0x1000

50
51
52
#define I2C_ADDR_7BITS_MAX	0x77
#define I2C_ADDR_7BITS_COUNT	(I2C_ADDR_7BITS_MAX + 1)

53
54
#define I2C_ADDR_DEVICE_ID	0x7c

55
56
/*
 * core_lock protects i2c_adapter_idr, and guarantees that device detection,
57
 * deletion of detected devices are serialized
58
 */
Jean Delvare's avatar
Jean Delvare committed
59
static DEFINE_MUTEX(core_lock);
Linus Torvalds's avatar
Linus Torvalds committed
60
61
static DEFINE_IDR(i2c_adapter_idr);

62
static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
63

64
static DEFINE_STATIC_KEY_FALSE(i2c_trace_msg_key);
65
static bool is_registered;
66

67
int i2c_transfer_trace_reg(void)
68
{
69
	static_branch_inc(&i2c_trace_msg_key);
70
	return 0;
71
72
73
74
}

void i2c_transfer_trace_unreg(void)
{
75
	static_branch_dec(&i2c_trace_msg_key);
76
77
}

78
const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
79
80
						const struct i2c_client *client)
{
81
82
83
	if (!(id && client))
		return NULL;

84
85
86
87
88
89
90
	while (id->name[0]) {
		if (strcmp(client->name, id->name) == 0)
			return id;
		id++;
	}
	return NULL;
}
91
EXPORT_SYMBOL_GPL(i2c_match_id);
92

Linus Torvalds's avatar
Linus Torvalds committed
93
94
static int i2c_device_match(struct device *dev, struct device_driver *drv)
{
95
96
97
	struct i2c_client	*client = i2c_verify_client(dev);
	struct i2c_driver	*driver;

David Brownell's avatar
David Brownell committed
98

99
	/* Attempt an OF style match */
100
	if (i2c_of_match_device(drv->of_match_table, client))
101
102
		return 1;

103
104
105
106
	/* Then ACPI style match */
	if (acpi_driver_match_device(dev, drv))
		return 1;

107
	driver = to_i2c_driver(drv);
108
109
110
111

	/* Finally an I2C match */
	if (i2c_match_id(driver->id_table, client))
		return 1;
112

113
	return 0;
Linus Torvalds's avatar
Linus Torvalds committed
114
115
}

116
static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
David Brownell's avatar
David Brownell committed
117
{
118
	struct i2c_client *client = to_i2c_client(dev);
119
120
	int rc;

121
122
123
124
	rc = of_device_uevent_modalias(dev, env);
	if (rc != -ENODEV)
		return rc;

125
126
127
	rc = acpi_device_uevent_modalias(dev, env);
	if (rc != -ENODEV)
		return rc;
David Brownell's avatar
David Brownell committed
128

129
	return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
David Brownell's avatar
David Brownell committed
130
131
}

132
133
134
/* i2c bus recovery routines */
static int get_scl_gpio_value(struct i2c_adapter *adap)
{
135
	return gpiod_get_value_cansleep(adap->bus_recovery_info->scl_gpiod);
136
137
138
139
}

static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
{
140
	gpiod_set_value_cansleep(adap->bus_recovery_info->scl_gpiod, val);
141
142
143
144
}

static int get_sda_gpio_value(struct i2c_adapter *adap)
{
145
	return gpiod_get_value_cansleep(adap->bus_recovery_info->sda_gpiod);
146
147
}

148
static void set_sda_gpio_value(struct i2c_adapter *adap, int val)
149
{
150
	gpiod_set_value_cansleep(adap->bus_recovery_info->sda_gpiod, val);
151
152
}

153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
static int i2c_generic_bus_free(struct i2c_adapter *adap)
{
	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
	int ret = -EOPNOTSUPP;

	if (bri->get_bus_free)
		ret = bri->get_bus_free(adap);
	else if (bri->get_sda)
		ret = bri->get_sda(adap);

	if (ret < 0)
		return ret;

	return ret ? 0 : -EBUSY;
}

169
170
171
172
173
174
175
176
/*
 * We are generating clock pulses. ndelay() determines durating of clk pulses.
 * We will generate clock with rate 100 KHz and so duration of both clock levels
 * is: delay in ns = (10^6 / 100) / 2
 */
#define RECOVERY_NDELAY		5000
#define RECOVERY_CLK_CNT	9

177
int i2c_generic_scl_recovery(struct i2c_adapter *adap)
178
179
{
	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
180
	int i = 0, scl = 1, ret = 0;
181
182

	if (bri->prepare_recovery)
183
		bri->prepare_recovery(adap);
184

185
186
187
188
189
190
	/*
	 * If we can set SDA, we will always create a STOP to ensure additional
	 * pulses will do no harm. This is achieved by letting SDA follow SCL
	 * half a cycle later. Check the 'incomplete_write_byte' fault injector
	 * for details.
	 */
191
	bri->set_scl(adap, scl);
192
	ndelay(RECOVERY_NDELAY / 2);
193
	if (bri->set_sda)
194
195
		bri->set_sda(adap, scl);
	ndelay(RECOVERY_NDELAY / 2);
196

197
198
199
200
	/*
	 * By this time SCL is high, as we need to give 9 falling-rising edges
	 */
	while (i++ < RECOVERY_CLK_CNT * 2) {
201
		if (scl) {
202
203
204
205
206
207
208
209
210
			/* SCL shouldn't be low here */
			if (!bri->get_scl(adap)) {
				dev_err(&adap->dev,
					"SCL is stuck low, exit recovery\n");
				ret = -EBUSY;
				break;
			}
		}

211
212
		scl = !scl;
		bri->set_scl(adap, scl);
213
		/* Creating STOP again, see above */
214
215
		ndelay(RECOVERY_NDELAY / 2);
		if (bri->set_sda)
216
			bri->set_sda(adap, scl);
217
		ndelay(RECOVERY_NDELAY / 2);
218

219
		if (scl) {
220
			ret = i2c_generic_bus_free(adap);
221
222
223
			if (ret == 0)
				break;
		}
224
225
	}

226
227
228
229
	/* If we can't check bus status, assume recovery worked */
	if (ret == -EOPNOTSUPP)
		ret = 0;

230
	if (bri->unprepare_recovery)
231
		bri->unprepare_recovery(adap);
232
233
234

	return ret;
}
235
EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
236
237
238
239
240
241
242
243
244

int i2c_recover_bus(struct i2c_adapter *adap)
{
	if (!adap->bus_recovery_info)
		return -EOPNOTSUPP;

	dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
	return adap->bus_recovery_info->recover_bus(adap);
}
245
EXPORT_SYMBOL_GPL(i2c_recover_bus);
246

247
248
249
250
251
252
253
254
255
256
257
258
259
static void i2c_init_recovery(struct i2c_adapter *adap)
{
	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
	char *err_str;

	if (!bri)
		return;

	if (!bri->recover_bus) {
		err_str = "no recover_bus() found";
		goto err;
	}

260
	if (bri->scl_gpiod && bri->recover_bus == i2c_generic_scl_recovery) {
261
262
		bri->get_scl = get_scl_gpio_value;
		bri->set_scl = set_scl_gpio_value;
263
		if (bri->sda_gpiod) {
264
			bri->get_sda = get_sda_gpio_value;
265
266
267
268
			/* FIXME: add proper flag instead of '0' once available */
			if (gpiod_get_direction(bri->sda_gpiod) == 0)
				bri->set_sda = set_sda_gpio_value;
		}
269
270
271
		return;
	}

272
	if (bri->recover_bus == i2c_generic_scl_recovery) {
273
274
275
276
277
		/* Generic SCL recovery */
		if (!bri->set_scl || !bri->get_scl) {
			err_str = "no {get|set}_scl() found";
			goto err;
		}
278
279
280
281
		if (!bri->set_sda && !bri->get_sda) {
			err_str = "either get_sda() or set_sda() needed";
			goto err;
		}
282
283
284
285
286
287
288
289
	}

	return;
 err:
	dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
	adap->bus_recovery_info = NULL;
}

290
291
292
293
294
295
296
297
298
299
300
static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
{
	struct i2c_adapter *adap = client->adapter;
	unsigned int irq;

	if (!adap->host_notify_domain)
		return -ENXIO;

	if (client->flags & I2C_CLIENT_TEN)
		return -EINVAL;

301
	irq = irq_create_mapping(adap->host_notify_domain, client->addr);
302
303
304
305

	return irq > 0 ? irq : -ENXIO;
}

306
static int i2c_device_probe(struct device *dev)
Linus Torvalds's avatar
Linus Torvalds committed
307
{
308
309
	struct i2c_client	*client = i2c_verify_client(dev);
	struct i2c_driver	*driver;
310
	int status;
David Brownell's avatar
David Brownell committed
311

312
313
314
	if (!client)
		return 0;

315
316
	driver = to_i2c_driver(dev->driver);

317
318
	client->irq = client->init_irq;

319
	if (!client->irq && !driver->disable_i2c_core_irq_mapping) {
320
321
		int irq = -ENOENT;

322
323
		if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
			dev_dbg(dev, "Using Host Notify IRQ\n");
324
325
			/* Keep adapter active when Host Notify is required */
			pm_runtime_get_sync(&client->adapter->dev);
326
327
			irq = i2c_smbus_host_notify_to_irq(client);
		} else if (dev->of_node) {
328
329
330
331
			irq = of_irq_get_byname(dev->of_node, "irq");
			if (irq == -EINVAL || irq == -ENODATA)
				irq = of_irq_get(dev->of_node, 0);
		} else if (ACPI_COMPANION(dev)) {
332
			irq = i2c_acpi_get_irq(client);
333
		}
334
		if (irq == -EPROBE_DEFER)
335
			return irq;
336

337
338
		if (irq < 0)
			irq = 0;
339
340
341
342

		client->irq = irq;
	}

343
	/*
344
345
	 * An I2C ID table is not mandatory, if and only if, a suitable OF
	 * or ACPI ID table is supplied for the probing device.
346
347
	 */
	if (!driver->id_table &&
348
	    !i2c_acpi_match_device(dev->driver->acpi_match_table, client) &&
349
	    !i2c_of_match_device(dev->driver->of_match_table, client))
David Brownell's avatar
David Brownell committed
350
		return -ENODEV;
351

352
	if (client->flags & I2C_CLIENT_WAKE) {
353
		int wakeirq;
354

355
356
357
		wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
		if (wakeirq == -EPROBE_DEFER)
			return wakeirq;
358
359
360
361
362
363

		device_init_wakeup(&client->dev, true);

		if (wakeirq > 0 && wakeirq != client->irq)
			status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
		else if (client->irq > 0)
364
			status = dev_pm_set_wake_irq(dev, client->irq);
365
366
367
368
		else
			status = 0;

		if (status)
369
			dev_warn(&client->dev, "failed to set up wakeup irq\n");
370
371
	}

David Brownell's avatar
David Brownell committed
372
	dev_dbg(dev, "probe\n");
373

374
375
	status = of_clk_set_defaults(dev->of_node, false);
	if (status < 0)
376
		goto err_clear_wakeup_irq;
377

378
	status = dev_pm_domain_attach(&client->dev, true);
379
	if (status)
380
381
		goto err_clear_wakeup_irq;

382
383
384
385
386
387
388
389
390
391
392
393
	/*
	 * When there are no more users of probe(),
	 * rename probe_new to probe.
	 */
	if (driver->probe_new)
		status = driver->probe_new(client);
	else if (driver->probe)
		status = driver->probe(client,
				       i2c_match_id(driver->id_table, client));
	else
		status = -EINVAL;

394
395
	if (status)
		goto err_detach_pm_domain;
396

397
398
399
400
401
402
403
	return 0;

err_detach_pm_domain:
	dev_pm_domain_detach(&client->dev, true);
err_clear_wakeup_irq:
	dev_pm_clear_wake_irq(&client->dev);
	device_init_wakeup(&client->dev, false);
404
	return status;
405
}
Linus Torvalds's avatar
Linus Torvalds committed
406

407
408
static int i2c_device_remove(struct device *dev)
{
409
	struct i2c_client	*client = i2c_verify_client(dev);
David Brownell's avatar
David Brownell committed
410
	struct i2c_driver	*driver;
411
	int status = 0;
David Brownell's avatar
David Brownell committed
412

413
	if (!client || !dev->driver)
David Brownell's avatar
David Brownell committed
414
415
416
417
418
419
420
		return 0;

	driver = to_i2c_driver(dev->driver);
	if (driver->remove) {
		dev_dbg(dev, "remove\n");
		status = driver->remove(client);
	}
421

422
	dev_pm_domain_detach(&client->dev, true);
423
424
425
426

	dev_pm_clear_wake_irq(&client->dev);
	device_init_wakeup(&client->dev, false);

427
	client->irq = 0;
428
429
	if (client->flags & I2C_CLIENT_HOST_NOTIFY)
		pm_runtime_put(&client->adapter->dev);
430

David Brownell's avatar
David Brownell committed
431
	return status;
Linus Torvalds's avatar
Linus Torvalds committed
432
433
}

434
static void i2c_device_shutdown(struct device *dev)
Linus Torvalds's avatar
Linus Torvalds committed
435
{
436
	struct i2c_client *client = i2c_verify_client(dev);
437
438
	struct i2c_driver *driver;

439
	if (!client || !dev->driver)
440
441
442
		return;
	driver = to_i2c_driver(dev->driver);
	if (driver->shutdown)
443
		driver->shutdown(client);
Linus Torvalds's avatar
Linus Torvalds committed
444
445
}

446
447
448
449
450
static void i2c_client_dev_release(struct device *dev)
{
	kfree(to_i2c_client(dev));
}

Zhenwen Xu's avatar
Zhenwen Xu committed
451
static ssize_t
452
show_name(struct device *dev, struct device_attribute *attr, char *buf)
David Brownell's avatar
David Brownell committed
453
{
454
455
	return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
		       to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
David Brownell's avatar
David Brownell committed
456
}
457
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
David Brownell's avatar
David Brownell committed
458

Zhenwen Xu's avatar
Zhenwen Xu committed
459
460
static ssize_t
show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
David Brownell's avatar
David Brownell committed
461
462
{
	struct i2c_client *client = to_i2c_client(dev);
463
464
	int len;

465
466
467
468
	len = of_device_modalias(dev, buf, PAGE_SIZE);
	if (len != -ENODEV)
		return len;

469
470
471
472
	len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
	if (len != -ENODEV)
		return len;

473
	return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
David Brownell's avatar
David Brownell committed
474
}
475
476
477
478
static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);

static struct attribute *i2c_dev_attrs[] = {
	&dev_attr_name.attr,
David Brownell's avatar
David Brownell committed
479
	/* modalias helps coldplug:  modprobe $(cat .../modalias) */
480
481
482
	&dev_attr_modalias.attr,
	NULL
};
483
ATTRIBUTE_GROUPS(i2c_dev);
484

485
struct bus_type i2c_bus_type = {
486
487
488
489
490
	.name		= "i2c",
	.match		= i2c_device_match,
	.probe		= i2c_device_probe,
	.remove		= i2c_device_remove,
	.shutdown	= i2c_device_shutdown,
491
};
492
EXPORT_SYMBOL_GPL(i2c_bus_type);
493

494
struct device_type i2c_client_type = {
495
	.groups		= i2c_dev_groups,
496
497
498
	.uevent		= i2c_device_uevent,
	.release	= i2c_client_dev_release,
};
499
EXPORT_SYMBOL_GPL(i2c_client_type);
500

501
502
503
504
505
506
507
508
509
510
511
512

/**
 * i2c_verify_client - return parameter as i2c_client, or NULL
 * @dev: device, probably from some driver model iterator
 *
 * When traversing the driver model tree, perhaps using driver model
 * iterators like @device_for_each_child(), you can't assume very much
 * about the nodes you find.  Use this function to avoid oopses caused
 * by wrongly treating some non-I2C device as an i2c_client.
 */
struct i2c_client *i2c_verify_client(struct device *dev)
{
513
	return (dev->type == &i2c_client_type)
514
515
516
517
518
519
			? to_i2c_client(dev)
			: NULL;
}
EXPORT_SYMBOL(i2c_verify_client);


520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
/* Return a unique address which takes the flags of the client into account */
static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
{
	unsigned short addr = client->addr;

	/* For some client flags, add an arbitrary offset to avoid collisions */
	if (client->flags & I2C_CLIENT_TEN)
		addr |= I2C_ADDR_OFFSET_TEN_BIT;

	if (client->flags & I2C_CLIENT_SLAVE)
		addr |= I2C_ADDR_OFFSET_SLAVE;

	return addr;
}

535
/* This is a permissive address validity check, I2C address map constraints
Lucas De Marchi's avatar
Lucas De Marchi committed
536
 * are purposely not enforced, except for the general call address. */
537
static int i2c_check_addr_validity(unsigned int addr, unsigned short flags)
538
{
539
	if (flags & I2C_CLIENT_TEN) {
540
		/* 10-bit address, all values are valid */
541
		if (addr > 0x3ff)
542
543
544
			return -EINVAL;
	} else {
		/* 7-bit address, reject the general call address */
545
		if (addr == 0x00 || addr > 0x7f)
546
547
548
549
550
			return -EINVAL;
	}
	return 0;
}

551
552
553
554
/* And this is a strict address validity check, used when probing. If a
 * device uses a reserved address, then it shouldn't be probed. 7-bit
 * addressing is assumed, 10-bit address devices are rare and should be
 * explicitly enumerated. */
555
int i2c_check_7bit_addr_validity_strict(unsigned short addr)
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
{
	/*
	 * Reserved addresses per I2C specification:
	 *  0x00       General call address / START byte
	 *  0x01       CBUS address
	 *  0x02       Reserved for different bus format
	 *  0x03       Reserved for future purposes
	 *  0x04-0x07  Hs-mode master code
	 *  0x78-0x7b  10-bit slave addressing
	 *  0x7c-0x7f  Reserved for future purposes
	 */
	if (addr < 0x08 || addr > 0x77)
		return -EINVAL;
	return 0;
}

572
573
574
575
576
static int __i2c_check_addr_busy(struct device *dev, void *addrp)
{
	struct i2c_client	*client = i2c_verify_client(dev);
	int			addr = *(int *)addrp;

577
	if (client && i2c_encode_flags_to_addr(client) == addr)
578
579
580
581
		return -EBUSY;
	return 0;
}

582
583
584
/* walk up mux tree */
static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
{
585
	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
586
587
588
589
590
	int result;

	result = device_for_each_child(&adapter->dev, &addr,
					__i2c_check_addr_busy);

591
592
	if (!result && parent)
		result = i2c_check_mux_parents(parent, addr);
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610

	return result;
}

/* recurse down mux tree */
static int i2c_check_mux_children(struct device *dev, void *addrp)
{
	int result;

	if (dev->type == &i2c_adapter_type)
		result = device_for_each_child(dev, addrp,
						i2c_check_mux_children);
	else
		result = __i2c_check_addr_busy(dev, addrp);

	return result;
}

611
612
static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
{
613
	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
614
615
	int result = 0;

616
617
	if (parent)
		result = i2c_check_mux_parents(parent, addr);
618
619
620
621
622
623

	if (!result)
		result = device_for_each_child(&adapter->dev, &addr,
						i2c_check_mux_children);

	return result;
624
625
}

626
/**
627
 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
628
 * @adapter: Target I2C bus segment
629
630
 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
 *	locks only this branch in the adapter tree
631
 */
632
633
static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
				 unsigned int flags)
634
{
635
	rt_mutex_lock_nested(&adapter->bus_lock, i2c_adapter_depth(adapter));
636
637
638
}

/**
639
 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
640
 * @adapter: Target I2C bus segment
641
642
 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
 *	trylocks only this branch in the adapter tree
643
 */
644
645
static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
				   unsigned int flags)
646
{
647
	return rt_mutex_trylock(&adapter->bus_lock);
648
649
650
}

/**
651
 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
652
 * @adapter: Target I2C bus segment
653
654
 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
 *	unlocks only this branch in the adapter tree
655
 */
656
657
static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
				   unsigned int flags)
658
{
659
	rt_mutex_unlock(&adapter->bus_lock);
660
661
}

662
static void i2c_dev_set_name(struct i2c_adapter *adap,
663
664
			     struct i2c_client *client,
			     struct i2c_board_info const *info)
665
666
667
{
	struct acpi_device *adev = ACPI_COMPANION(&client->dev);

668
669
670
671
672
	if (info && info->dev_name) {
		dev_set_name(&client->dev, "i2c-%s", info->dev_name);
		return;
	}

673
674
675
676
677
678
	if (adev) {
		dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
		return;
	}

	dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
679
		     i2c_encode_flags_to_addr(client));
680
681
}

682
683
int i2c_dev_irq_from_resources(const struct resource *resources,
			       unsigned int num_resources)
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
{
	struct irq_data *irqd;
	int i;

	for (i = 0; i < num_resources; i++) {
		const struct resource *r = &resources[i];

		if (resource_type(r) != IORESOURCE_IRQ)
			continue;

		if (r->flags & IORESOURCE_BITS) {
			irqd = irq_get_irq_data(r->start);
			if (!irqd)
				break;

			irqd_set_trigger_type(irqd, r->flags & IORESOURCE_BITS);
		}

		return r->start;
	}

	return 0;
}

708
/**
709
 * i2c_new_client_device - instantiate an i2c device
710
711
 * @adap: the adapter managing the device
 * @info: describes one I2C device; bus_num is ignored
David Brownell's avatar
David Brownell committed
712
 * Context: can sleep
713
 *
714
715
716
717
718
719
 * Create an i2c device. Binding is handled through driver model
 * probe()/remove() methods.  A driver may be bound to this device when we
 * return from this function, or any later moment (e.g. maybe hotplugging will
 * load the driver module).  This call is not appropriate for use by mainboard
 * initialization logic, which usually runs during an arch_initcall() long
 * before any i2c_adapter could exist.
720
721
 *
 * This returns the new i2c client, which may be saved for later use with
722
 * i2c_unregister_device(); or an ERR_PTR to describe the error.
723
 */
724
struct i2c_client *
725
i2c_new_client_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
726
727
728
729
730
731
{
	struct i2c_client	*client;
	int			status;

	client = kzalloc(sizeof *client, GFP_KERNEL);
	if (!client)
732
		return ERR_PTR(-ENOMEM);
733
734
735
736

	client->adapter = adap;

	client->dev.platform_data = info->platform_data;
737
	client->flags = info->flags;
738
	client->addr = info->addr;
739

740
741
742
	client->init_irq = info->irq;
	if (!client->init_irq)
		client->init_irq = i2c_dev_irq_from_resources(info->resources,
743
							 info->num_resources);
744
745
746

	strlcpy(client->name, info->type, sizeof(client->name));

747
	status = i2c_check_addr_validity(client->addr, client->flags);
748
749
750
751
752
753
	if (status) {
		dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
			client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
		goto out_err_silent;
	}

754
	/* Check for address business */
755
	status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
756
757
758
759
760
	if (status)
		goto out_err;

	client->dev.parent = &client->adapter->dev;
	client->dev.bus = &i2c_bus_type;
761
	client->dev.type = &i2c_client_type;
762
	client->dev.of_node = of_node_get(info->of_node);
763
	client->dev.fwnode = info->fwnode;
764

765
	i2c_dev_set_name(adap, client, info);
766
767
768
769
770
771
772

	if (info->properties) {
		status = device_add_properties(&client->dev, info->properties);
		if (status) {
			dev_err(&adap->dev,
				"Failed to add properties to client %s: %d\n",
				client->name, status);
773
			goto out_err_put_of_node;
774
775
776
		}
	}

777
778
	status = device_register(&client->dev);
	if (status)
779
		goto out_free_props;
780
781
782
783

	dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
		client->name, dev_name(&client->dev));

784
	return client;
785

786
787
788
out_free_props:
	if (info->properties)
		device_remove_properties(&client->dev);
789
790
out_err_put_of_node:
	of_node_put(info->of_node);
791
out_err:
792
793
794
	dev_err(&adap->dev,
		"Failed to register i2c client %s at 0x%02x (%d)\n",
		client->name, client->addr, status);
795
out_err_silent:
796
	kfree(client);
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
	return ERR_PTR(status);
}
EXPORT_SYMBOL_GPL(i2c_new_client_device);

/**
 * i2c_new_device - instantiate an i2c device
 * @adap: the adapter managing the device
 * @info: describes one I2C device; bus_num is ignored
 * Context: can sleep
 *
 * This deprecated function has the same functionality as
 * @i2c_new_client_device, it just returns NULL instead of an ERR_PTR in case of
 * an error for compatibility with current I2C API. It will be removed once all
 * users are converted.
 *
 * This returns the new i2c client, which may be saved for later use with
 * i2c_unregister_device(); or NULL to indicate an error.
 */
struct i2c_client *
i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
{
	struct i2c_client *ret;

	ret = i2c_new_client_device(adap, info);
	return IS_ERR(ret) ? NULL : ret;
822
823
824
825
826
827
828
}
EXPORT_SYMBOL_GPL(i2c_new_device);


/**
 * i2c_unregister_device - reverse effect of i2c_new_device()
 * @client: value returned from i2c_new_device()
David Brownell's avatar
David Brownell committed
829
 * Context: can sleep
830
831
 */
void i2c_unregister_device(struct i2c_client *client)
David Brownell's avatar
David Brownell committed
832
{
833
834
	if (!client)
		return;
835
836

	if (client->dev.of_node) {
837
		of_node_clear_flag(client->dev.of_node, OF_POPULATED);
838
839
840
		of_node_put(client->dev.of_node);
	}

841
842
	if (ACPI_COMPANION(&client->dev))
		acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
David Brownell's avatar
David Brownell committed
843
844
	device_unregister(&client->dev);
}
845
EXPORT_SYMBOL_GPL(i2c_unregister_device);
David Brownell's avatar
David Brownell committed
846
847


848
849
850
851
852
static const struct i2c_device_id dummy_id[] = {
	{ "dummy", 0 },
	{ },
};

853
854
855
856
857
858
859
static int dummy_probe(struct i2c_client *client,
		       const struct i2c_device_id *id)
{
	return 0;
}

static int dummy_remove(struct i2c_client *client)
860
861
862
863
864
865
{
	return 0;
}

static struct i2c_driver dummy_driver = {
	.driver.name	= "dummy",
866
867
	.probe		= dummy_probe,
	.remove		= dummy_remove,
868
	.id_table	= dummy_id,
869
870
871
};

/**
872
 * i2c_new_dummy_device - return a new i2c device bound to a dummy driver
873
874
875
876
877
878
879
880
881
882
883
884
885
886
 * @adapter: the adapter managing the device
 * @address: seven bit address to be used
 * Context: can sleep
 *
 * This returns an I2C client bound to the "dummy" driver, intended for use
 * with devices that consume multiple addresses.  Examples of such chips
 * include various EEPROMS (like 24c04 and 24c08 models).
 *
 * These dummy devices have two main uses.  First, most I2C and SMBus calls
 * except i2c_transfer() need a client handle; the dummy will be that handle.
 * And second, this prevents the specified address from being bound to a
 * different driver.
 *
 * This returns the new i2c client, which should be saved for later use with
887
 * i2c_unregister_device(); or an ERR_PTR to describe the error.
888
 */
889
struct i2c_client *i2c_new_dummy_device(struct i2c_adapter *adapter, u16 address)
890
891
{
	struct i2c_board_info info = {
892
		I2C_BOARD_INFO("dummy", address),
893
894
	};

895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
	return i2c_new_client_device(adapter, &info);
}
EXPORT_SYMBOL_GPL(i2c_new_dummy_device);

/**
 * i2c_new_dummy - return a new i2c device bound to a dummy driver
 * @adapter: the adapter managing the device
 * @address: seven bit address to be used
 * Context: can sleep
 *
 * This deprecated function has the same functionality as @i2c_new_dummy_device,
 * it just returns NULL instead of an ERR_PTR in case of an error for
 * compatibility with current I2C API. It will be removed once all users are
 * converted.
 *
 * This returns the new i2c client, which should be saved for later use with
 * i2c_unregister_device(); or NULL to indicate an error.
 */
struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
{
	struct i2c_client *ret;

	ret = i2c_new_dummy_device(adapter, address);
	return IS_ERR(ret) ? NULL : ret;
919
920
921
}
EXPORT_SYMBOL_GPL(i2c_new_dummy);

922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
struct i2c_dummy_devres {
	struct i2c_client *client;
};

static void devm_i2c_release_dummy(struct device *dev, void *res)
{
	struct i2c_dummy_devres *this = res;

	i2c_unregister_device(this->client);
}

/**
 * devm_i2c_new_dummy_device - return a new i2c device bound to a dummy driver
 * @dev: device the managed resource is bound to
 * @adapter: the adapter managing the device
 * @address: seven bit address to be used
 * Context: can sleep
 *
 * This is the device-managed version of @i2c_new_dummy_device. It returns the
 * new i2c client or an ERR_PTR in case of an error.
 */
struct i2c_client *devm_i2c_new_dummy_device(struct device *dev,
					     struct i2c_adapter *adapter,
					     u16 address)
{
	struct i2c_dummy_devres *dr;
	struct i2c_client *client;

	dr = devres_alloc(devm_i2c_release_dummy, sizeof(*dr), GFP_KERNEL);
	if (!dr)
		return ERR_PTR(-ENOMEM);

	client = i2c_new_dummy_device(adapter, address);
	if (IS_ERR(client)) {
		devres_free(dr);
	} else {
		dr->client = client;
		devres_add(dev, dr);
	}

	return client;
}
EXPORT_SYMBOL_GPL(devm_i2c_new_dummy_device);

966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
/**
 * i2c_new_secondary_device - Helper to get the instantiated secondary address
 * and create the associated device
 * @client: Handle to the primary client
 * @name: Handle to specify which secondary address to get
 * @default_addr: Used as a fallback if no secondary address was specified
 * Context: can sleep
 *
 * I2C clients can be composed of multiple I2C slaves bound together in a single
 * component. The I2C client driver then binds to the master I2C slave and needs
 * to create I2C dummy clients to communicate with all the other slaves.
 *
 * This function creates and returns an I2C dummy client whose I2C address is
 * retrieved from the platform firmware based on the given slave name. If no
 * address is specified by the firmware default_addr is used.
 *
 * On DT-based platforms the address is retrieved from the "reg" property entry
 * cell whose "reg-names" value matches the slave name.
 *
 * This returns the new i2c client, which should be saved for later use with
 * i2c_unregister_device(); or NULL to indicate an error.
 */
struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
						const char *name,
						u16 default_addr)
{
	struct device_node *np = client->dev.of_node;
	u32 addr = default_addr;
	int i;

	if (np) {
		i = of_property_match_string(np, "reg-names", name);
		if (i >= 0)
			of_property_read_u32_index(np, "reg", i, &addr);
	}

	dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
	return i2c_new_dummy(client->adapter, addr);
}
EXPORT_SYMBOL_GPL(i2c_new_secondary_device);

1007
1008
/* ------------------------------------------------------------------------- */

David Brownell's avatar
David Brownell committed
1009
1010
/* I2C bus adapters -- one roots each I2C or SMBUS segment */

Adrian Bunk's avatar
Adrian Bunk committed
1011
static void i2c_adapter_dev_release(struct device *dev)
Linus Torvalds's avatar
Linus Torvalds committed
1012
{
1013
	struct i2c_adapter *adap = to_i2c_adapter(dev);
Linus Torvalds's avatar
Linus Torvalds committed
1014
1015
1016
	complete(&adap->dev_released);
}

1017
unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1018
1019
1020
1021
1022
1023
{
	unsigned int depth = 0;

	while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
		depth++;

1024
1025
1026
	WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
		  "adapter depth exceeds lockdep subclass limit\n");

1027
1028
	return depth;
}
1029
EXPORT_SYMBOL_GPL(i2c_adapter_depth);
1030

1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
/*
 * Let users instantiate I2C devices through sysfs. This can be used when
 * platform initialization code doesn't contain the proper data for
 * whatever reason. Also useful for drivers that do device detection and
 * detection fails, either because the device uses an unexpected address,
 * or this is a compatible device with different ID register values.
 *
 * Parameter checking may look overzealous, but we really don't want
 * the user to provide incorrect parameters.
 */
static ssize_t
i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
		     const char *buf, size_t count)
{
	struct i2c_adapter *adap = to_i2c_adapter(dev);
	struct i2c_board_info info;
	struct i2c_client *client;
	char *blank, end;
	int res;

	memset(&info, 0, sizeof(struct i2c_board_info));

	blank = strchr(buf, ' ');
	if (!blank) {
		dev_err(dev, "%s: Missing parameters\n", "new_device");
		return -EINVAL;
	}
	if (blank - buf > I2C_NAME_SIZE - 1) {
		dev_err(dev, "%s: Invalid device name\n", "new_device");
		return -EINVAL;
	}
	memcpy(info.type, buf, blank - buf);

	/* Parse remaining parameters, reject extra parameters */
	res = sscanf(++blank, "%hi%c", &info.addr, &end);
	if (res < 1) {
		dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
		return -EINVAL;
	}
	if (res > 1  && end != '\n') {
		dev_err(dev, "%s: Extra parameters\n", "new_device");
		return -EINVAL;
	}

1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
	if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
		info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
		info.flags |= I2C_CLIENT_TEN;
	}

	if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
		info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
		info.flags |= I2C_CLIENT_SLAVE;
	}

1085
1086
1087
	client = i2c_new_client_device(adap, &info);
	if (IS_ERR(client))
		return PTR_ERR(client);
1088
1089

	/* Keep track of the added device */
1090
	mutex_lock(&adap->userspace_clients_lock);
1091
	list_add_tail(&client->detected, &adap->userspace_clients);
1092
	mutex_unlock(&adap->userspace_clients_lock);
1093
1094
1095
1096
1097
	dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
		 info.type, info.addr);

	return count;
}
1098
static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131

/*
 * And of course let the users delete the devices they instantiated, if
 * they got it wrong. This interface can only be used to delete devices
 * instantiated by i2c_sysfs_new_device above. This guarantees that we
 * don't delete devices to which some kernel code still has references.
 *
 * Parameter checking may look overzealous, but we really don't want
 * the user to delete the wrong device.
 */
static ssize_t
i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
			const char *buf, size_t count)
{
	struct i2c_adapter *adap = to_i2c_adapter(dev);
	struct i2c_client *client, *next;
	unsigned short addr;
	char end;
	int res;

	/* Parse parameters, reject extra parameters */
	res = sscanf(buf, "%hi%c", &addr, &end);
	if (res < 1) {
		dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
		return -EINVAL;
	}
	if (res > 1  && end != '\n') {
		dev_err(dev, "%s: Extra parameters\n", "delete_device");
		return -EINVAL;
	}

	/* Make sure the device was added through sysfs */
	res = -ENOENT;
1132
1133
	mutex_lock_nested(&adap->userspace_clients_lock,
			  i2c_adapter_depth(adap));
1134
1135
	list_for_each_entry_safe(client, next, &adap->userspace_clients,
				 detected) {
1136
		if (i2c_encode_flags_to_addr(client) == addr) {
1137
1138
1139
1140
1141
1142
1143
1144
1145
			dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
				 "delete_device", client->name, client->addr);

			list_del(&client->detected);
			i2c_unregister_device(client);
			res = count;
			break;
		}
	}
1146
	mutex_unlock(&adap->userspace_clients_lock);
1147
1148
1149
1150
1151
1152

	if (res < 0)
		dev_err(dev, "%s: Can't find device in list\n",
			"delete_device");
	return res;
}
1153
1154
static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
				   i2c_sysfs_delete_device);
1155
1156
1157
1158
1159
1160
1161

static struct attribute *i2c_adapter_attrs[] = {
	&dev_attr_name.attr,
	&dev_attr_new_device.attr,
	&dev_attr_delete_device.attr,
	NULL
};
1162
ATTRIBUTE_GROUPS(i2c_adapter);
1163

1164
struct device_type i2c_adapter_type = {
1165
	.groups		= i2c_adapter_groups,
1166
	.release	= i2c_adapter_dev_release,
Linus Torvalds's avatar
Linus Torvalds committed
1167
};
1168
EXPORT_SYMBOL_GPL(i2c_adapter_type);
Linus Torvalds's avatar
Linus Torvalds committed
1169

1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
/**
 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
 * @dev: device, probably from some driver model iterator
 *
 * When traversing the driver model tree, perhaps using driver model
 * iterators like @device_for_each_child(), you can't assume very much
 * about the nodes you find.  Use this function to avoid oopses caused
 * by wrongly treating some non-I2C device as an i2c_adapter.
 */
struct i2c_adapter *i2c_verify_adapter(struct device *dev)
{
	return (dev->type == &i2c_adapter_type)
			? to_i2c_adapter(dev)
			: NULL;
}
EXPORT_SYMBOL(i2c_verify_adapter);

1187
1188
1189
1190
#ifdef CONFIG_I2C_COMPAT
static struct class_compat *i2c_adapter_compat_class;
#endif

1191
1192
1193
1194
static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
{
	struct i2c_devinfo	*devinfo;

1195
	down_read(&__i2c_board_lock);
1196
1197
1198
1199
	list_for_each_entry(devinfo, &__i2c_board_list, list) {
		if (devinfo->busnum == adapter->nr
				&& !i2c_new_device(adapter,
						&devinfo->board_info))
Zhenwen Xu's avatar
Zhenwen Xu committed