i2c-core-base.c 64 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
	/*
	 * 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
189
190
	 * for details. Note that we must honour tsu:sto, 4us, but lets use 5us
	 * here for simplicity.
191
	 */
192
	bri->set_scl(adap, scl);
193
	ndelay(RECOVERY_NDELAY);
194
	if (bri->set_sda)
195
196
		bri->set_sda(adap, scl);
	ndelay(RECOVERY_NDELAY / 2);
197

198
199
200
201
	/*
	 * By this time SCL is high, as we need to give 9 falling-rising edges
	 */
	while (i++ < RECOVERY_CLK_CNT * 2) {
202
		if (scl) {
203
204
205
206
207
208
209
210
211
			/* 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;
			}
		}

212
213
		scl = !scl;
		bri->set_scl(adap, scl);
214
		/* Creating STOP again, see above */
215
216
217
218
219
220
221
		if (scl)  {
			/* Honour minimum tsu:sto */
			ndelay(RECOVERY_NDELAY);
		} else {
			/* Honour minimum tf and thd:dat */
			ndelay(RECOVERY_NDELAY / 2);
		}
222
		if (bri->set_sda)
223
			bri->set_sda(adap, scl);
224
		ndelay(RECOVERY_NDELAY / 2);
225

226
		if (scl) {
227
			ret = i2c_generic_bus_free(adap);
228
229
230
			if (ret == 0)
				break;
		}
231
232
	}

233
234
235
236
	/* If we can't check bus status, assume recovery worked */
	if (ret == -EOPNOTSUPP)
		ret = 0;

237
	if (bri->unprepare_recovery)
238
		bri->unprepare_recovery(adap);
239
240
241

	return ret;
}
242
EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
243
244
245
246
247
248
249
250
251

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);
}
252
EXPORT_SYMBOL_GPL(i2c_recover_bus);
253

254
255
256
257
258
259
260
261
262
263
264
265
266
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;
	}

267
	if (bri->scl_gpiod && bri->recover_bus == i2c_generic_scl_recovery) {
268
269
		bri->get_scl = get_scl_gpio_value;
		bri->set_scl = set_scl_gpio_value;
270
		if (bri->sda_gpiod) {
271
			bri->get_sda = get_sda_gpio_value;
272
273
274
275
			/* FIXME: add proper flag instead of '0' once available */
			if (gpiod_get_direction(bri->sda_gpiod) == 0)
				bri->set_sda = set_sda_gpio_value;
		}
276
277
278
		return;
	}

279
	if (bri->recover_bus == i2c_generic_scl_recovery) {
280
281
282
283
284
		/* Generic SCL recovery */
		if (!bri->set_scl || !bri->get_scl) {
			err_str = "no {get|set}_scl() found";
			goto err;
		}
285
286
287
288
		if (!bri->set_sda && !bri->get_sda) {
			err_str = "either get_sda() or set_sda() needed";
			goto err;
		}
289
290
291
292
293
294
295
296
	}

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

297
298
299
300
301
302
303
304
305
306
307
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;

308
	irq = irq_create_mapping(adap->host_notify_domain, client->addr);
309
310
311
312

	return irq > 0 ? irq : -ENXIO;
}

313
static int i2c_device_probe(struct device *dev)
Linus Torvalds's avatar
Linus Torvalds committed
314
{
315
316
	struct i2c_client	*client = i2c_verify_client(dev);
	struct i2c_driver	*driver;
317
	int status;
David Brownell's avatar
David Brownell committed
318

319
320
321
	if (!client)
		return 0;

322
323
	driver = to_i2c_driver(dev->driver);

324
325
	client->irq = client->init_irq;

326
	if (!client->irq && !driver->disable_i2c_core_irq_mapping) {
327
328
		int irq = -ENOENT;

329
330
		if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
			dev_dbg(dev, "Using Host Notify IRQ\n");
331
332
			/* Keep adapter active when Host Notify is required */
			pm_runtime_get_sync(&client->adapter->dev);
333
334
			irq = i2c_smbus_host_notify_to_irq(client);
		} else if (dev->of_node) {
335
336
337
338
			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)) {
339
			irq = i2c_acpi_get_irq(client);
340
		}
341
		if (irq == -EPROBE_DEFER)
342
			return irq;
343

344
345
		if (irq < 0)
			irq = 0;
346
347
348
349

		client->irq = irq;
	}

350
	/*
351
352
	 * An I2C ID table is not mandatory, if and only if, a suitable OF
	 * or ACPI ID table is supplied for the probing device.
353
354
	 */
	if (!driver->id_table &&
355
	    !i2c_acpi_match_device(dev->driver->acpi_match_table, client) &&
356
	    !i2c_of_match_device(dev->driver->of_match_table, client))
David Brownell's avatar
David Brownell committed
357
		return -ENODEV;
358

359
	if (client->flags & I2C_CLIENT_WAKE) {
360
		int wakeirq;
361

362
363
364
		wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
		if (wakeirq == -EPROBE_DEFER)
			return wakeirq;
365
366
367
368
369
370

		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)
371
			status = dev_pm_set_wake_irq(dev, client->irq);
372
373
374
375
		else
			status = 0;

		if (status)
376
			dev_warn(&client->dev, "failed to set up wakeup irq\n");
377
378
	}

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

381
382
	status = of_clk_set_defaults(dev->of_node, false);
	if (status < 0)
383
		goto err_clear_wakeup_irq;
384

385
	status = dev_pm_domain_attach(&client->dev, true);
386
	if (status)
387
388
		goto err_clear_wakeup_irq;

389
390
391
392
393
394
395
396
397
398
399
400
	/*
	 * 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;

401
402
	if (status)
		goto err_detach_pm_domain;
403

404
405
406
407
408
409
410
	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);
411
	return status;
412
}
Linus Torvalds's avatar
Linus Torvalds committed
413

414
415
static int i2c_device_remove(struct device *dev)
{
416
	struct i2c_client	*client = i2c_verify_client(dev);
David Brownell's avatar
David Brownell committed
417
	struct i2c_driver	*driver;
418
	int status = 0;
David Brownell's avatar
David Brownell committed
419

420
	if (!client || !dev->driver)
David Brownell's avatar
David Brownell committed
421
422
423
424
425
426
427
		return 0;

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

429
	dev_pm_domain_detach(&client->dev, true);
430
431
432
433

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

434
	client->irq = 0;
435
436
	if (client->flags & I2C_CLIENT_HOST_NOTIFY)
		pm_runtime_put(&client->adapter->dev);
437

David Brownell's avatar
David Brownell committed
438
	return status;
Linus Torvalds's avatar
Linus Torvalds committed
439
440
}

441
static void i2c_device_shutdown(struct device *dev)
Linus Torvalds's avatar
Linus Torvalds committed
442
{
443
	struct i2c_client *client = i2c_verify_client(dev);
444
445
	struct i2c_driver *driver;

446
	if (!client || !dev->driver)
447
448
449
		return;
	driver = to_i2c_driver(dev->driver);
	if (driver->shutdown)
450
		driver->shutdown(client);
Linus Torvalds's avatar
Linus Torvalds committed
451
452
}

453
454
455
456
457
static void i2c_client_dev_release(struct device *dev)
{
	kfree(to_i2c_client(dev));
}

Zhenwen Xu's avatar
Zhenwen Xu committed
458
static ssize_t
459
name_show(struct device *dev, struct device_attribute *attr, char *buf)
David Brownell's avatar
David Brownell committed
460
{
461
462
	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
463
}
464
static DEVICE_ATTR_RO(name);
David Brownell's avatar
David Brownell committed
465

Zhenwen Xu's avatar
Zhenwen Xu committed
466
static ssize_t
467
modalias_show(struct device *dev, struct device_attribute *attr, char *buf)
David Brownell's avatar
David Brownell committed
468
469
{
	struct i2c_client *client = to_i2c_client(dev);
470
471
	int len;

472
473
474
475
	len = of_device_modalias(dev, buf, PAGE_SIZE);
	if (len != -ENODEV)
		return len;

476
477
478
479
	len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
	if (len != -ENODEV)
		return len;

480
	return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
David Brownell's avatar
David Brownell committed
481
}
482
static DEVICE_ATTR_RO(modalias);
483
484
485

static struct attribute *i2c_dev_attrs[] = {
	&dev_attr_name.attr,
David Brownell's avatar
David Brownell committed
486
	/* modalias helps coldplug:  modprobe $(cat .../modalias) */
487
488
489
	&dev_attr_modalias.attr,
	NULL
};
490
ATTRIBUTE_GROUPS(i2c_dev);
491

492
struct bus_type i2c_bus_type = {
493
494
495
496
497
	.name		= "i2c",
	.match		= i2c_device_match,
	.probe		= i2c_device_probe,
	.remove		= i2c_device_remove,
	.shutdown	= i2c_device_shutdown,
498
};
499
EXPORT_SYMBOL_GPL(i2c_bus_type);
500

501
struct device_type i2c_client_type = {
502
	.groups		= i2c_dev_groups,
503
504
505
	.uevent		= i2c_device_uevent,
	.release	= i2c_client_dev_release,
};
506
EXPORT_SYMBOL_GPL(i2c_client_type);
507

508
509
510
511
512
513
514
515
516
517
518
519

/**
 * 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)
{
520
	return (dev->type == &i2c_client_type)
521
522
523
524
525
526
			? to_i2c_client(dev)
			: NULL;
}
EXPORT_SYMBOL(i2c_verify_client);


527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/* 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;
}

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

558
559
560
561
/* 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. */
562
int i2c_check_7bit_addr_validity_strict(unsigned short addr)
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
{
	/*
	 * 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;
}

579
580
581
582
583
static int __i2c_check_addr_busy(struct device *dev, void *addrp)
{
	struct i2c_client	*client = i2c_verify_client(dev);
	int			addr = *(int *)addrp;

584
	if (client && i2c_encode_flags_to_addr(client) == addr)
585
586
587
588
		return -EBUSY;
	return 0;
}

589
590
591
/* walk up mux tree */
static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
{
592
	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
593
594
595
596
597
	int result;

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

598
599
	if (!result && parent)
		result = i2c_check_mux_parents(parent, addr);
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617

	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;
}

618
619
static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
{
620
	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
621
622
	int result = 0;

623
624
	if (parent)
		result = i2c_check_mux_parents(parent, addr);
625
626
627
628
629
630

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

	return result;
631
632
}

633
/**
634
 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
635
 * @adapter: Target I2C bus segment
636
637
 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
 *	locks only this branch in the adapter tree
638
 */
639
640
static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
				 unsigned int flags)
641
{
642
	rt_mutex_lock_nested(&adapter->bus_lock, i2c_adapter_depth(adapter));
643
644
645
}

/**
646
 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
647
 * @adapter: Target I2C bus segment
648
649
 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
 *	trylocks only this branch in the adapter tree
650
 */
651
652
static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
				   unsigned int flags)
653
{
654
	return rt_mutex_trylock(&adapter->bus_lock);
655
656
657
}

/**
658
 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
659
 * @adapter: Target I2C bus segment
660
661
 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
 *	unlocks only this branch in the adapter tree
662
 */
663
664
static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
				   unsigned int flags)
665
{
666
	rt_mutex_unlock(&adapter->bus_lock);
667
668
}

669
static void i2c_dev_set_name(struct i2c_adapter *adap,
670
671
			     struct i2c_client *client,
			     struct i2c_board_info const *info)
672
673
674
{
	struct acpi_device *adev = ACPI_COMPANION(&client->dev);

675
676
677
678
679
	if (info && info->dev_name) {
		dev_set_name(&client->dev, "i2c-%s", info->dev_name);
		return;
	}

680
681
682
683
684
685
	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),
686
		     i2c_encode_flags_to_addr(client));
687
688
}

689
690
int i2c_dev_irq_from_resources(const struct resource *resources,
			       unsigned int num_resources)
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
{
	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;
}

715
/**
716
 * i2c_new_client_device - instantiate an i2c device
717
718
 * @adap: the adapter managing the device
 * @info: describes one I2C device; bus_num is ignored
David Brownell's avatar
David Brownell committed
719
 * Context: can sleep
720
 *
721
722
723
724
725
726
 * 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.
727
728
 *
 * This returns the new i2c client, which may be saved for later use with
729
 * i2c_unregister_device(); or an ERR_PTR to describe the error.
730
 */
731
struct i2c_client *
732
i2c_new_client_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
733
734
735
736
737
738
{
	struct i2c_client	*client;
	int			status;

	client = kzalloc(sizeof *client, GFP_KERNEL);
	if (!client)
739
		return ERR_PTR(-ENOMEM);
740
741
742
743

	client->adapter = adap;

	client->dev.platform_data = info->platform_data;
744
	client->flags = info->flags;
745
	client->addr = info->addr;
746

747
748
749
	client->init_irq = info->irq;
	if (!client->init_irq)
		client->init_irq = i2c_dev_irq_from_resources(info->resources,
750
							 info->num_resources);
751
752
753

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

754
	status = i2c_check_addr_validity(client->addr, client->flags);
755
756
757
758
759
760
	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;
	}

761
	/* Check for address business */
762
	status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
763
764
765
766
767
	if (status)
		goto out_err;

	client->dev.parent = &client->adapter->dev;
	client->dev.bus = &i2c_bus_type;
768
	client->dev.type = &i2c_client_type;
769
	client->dev.of_node = of_node_get(info->of_node);
770
	client->dev.fwnode = info->fwnode;
771

772
	i2c_dev_set_name(adap, client, info);
773
774
775
776
777
778
779

	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);
780
			goto out_err_put_of_node;
781
782
783
		}
	}

784
785
	status = device_register(&client->dev);
	if (status)
786
		goto out_free_props;
787
788
789
790

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

791
	return client;
792

793
794
795
out_free_props:
	if (info->properties)
		device_remove_properties(&client->dev);
796
797
out_err_put_of_node:
	of_node_put(info->of_node);
798
out_err:
799
800
801
	dev_err(&adap->dev,
		"Failed to register i2c client %s at 0x%02x (%d)\n",
		client->name, client->addr, status);
802
out_err_silent:
803
	kfree(client);
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
	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;
829
830
831
832
833
}
EXPORT_SYMBOL_GPL(i2c_new_device);


/**
834
835
 * i2c_unregister_device - reverse effect of i2c_new_*_device()
 * @client: value returned from i2c_new_*_device()
David Brownell's avatar
David Brownell committed
836
 * Context: can sleep
837
838
 */
void i2c_unregister_device(struct i2c_client *client)
David Brownell's avatar
David Brownell committed
839
{
840
	if (IS_ERR_OR_NULL(client))
841
		return;
842
843

	if (client->dev.of_node) {
844
		of_node_clear_flag(client->dev.of_node, OF_POPULATED);
845
846
847
		of_node_put(client->dev.of_node);
	}

848
849
	if (ACPI_COMPANION(&client->dev))
		acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
David Brownell's avatar
David Brownell committed
850
851
	device_unregister(&client->dev);
}
852
EXPORT_SYMBOL_GPL(i2c_unregister_device);
David Brownell's avatar
David Brownell committed
853
854


855
856
857
858
859
static const struct i2c_device_id dummy_id[] = {
	{ "dummy", 0 },
	{ },
};

860
861
862
863
864
865
866
static int dummy_probe(struct i2c_client *client,
		       const struct i2c_device_id *id)
{
	return 0;
}

static int dummy_remove(struct i2c_client *client)
867
868
869
870
871
872
{
	return 0;
}

static struct i2c_driver dummy_driver = {
	.driver.name	= "dummy",
873
874
	.probe		= dummy_probe,
	.remove		= dummy_remove,
875
	.id_table	= dummy_id,
876
877
878
};

/**
879
 * i2c_new_dummy_device - return a new i2c device bound to a dummy driver
880
881
882
883
884
885
886
887
888
889
890
891
892
893
 * @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
894
 * i2c_unregister_device(); or an ERR_PTR to describe the error.
895
 */
896
struct i2c_client *i2c_new_dummy_device(struct i2c_adapter *adapter, u16 address)
897
898
{
	struct i2c_board_info info = {
899
		I2C_BOARD_INFO("dummy", address),
900
901
	};

902
903
904
905
	return i2c_new_client_device(adapter, &info);
}
EXPORT_SYMBOL_GPL(i2c_new_dummy_device);

906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
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
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);

950
/**
951
 * i2c_new_ancillary_device - Helper to get the instantiated secondary address
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
 * 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
970
 * i2c_unregister_device(); or an ERR_PTR to describe the error.
971
 */
972
struct i2c_client *i2c_new_ancillary_device(struct i2c_client *client,
973
974
975
976
977
978
979
980
981
982
983
984
985
986
						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);
987
	return i2c_new_dummy_device(client->adapter, addr);
988
}
989
EXPORT_SYMBOL_GPL(i2c_new_ancillary_device);
990

991
992
/* ------------------------------------------------------------------------- */

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

Adrian Bunk's avatar
Adrian Bunk committed
995
static void i2c_adapter_dev_release(struct device *dev)
Linus Torvalds's avatar
Linus Torvalds committed
996
{
997
	struct i2c_adapter *adap = to_i2c_adapter(dev);
Linus Torvalds's avatar
Linus Torvalds committed
998
999
1000
	complete(&adap->dev_released);
}

1001
unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1002
1003
1004
1005
1006
1007
{
	unsigned int depth = 0;

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

1008
1009
1010
	WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
		  "adapter depth exceeds lockdep subclass limit\n");

1011
1012
	return depth;
}
1013
EXPORT_SYMBOL_GPL(i2c_adapter_depth);
1014

1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
/*
 * 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
1026
1027
new_device_store(struct device *dev, struct device_attribute *attr,
		 const char *buf, size_t count)
1028
1029
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
{
	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;
	}

1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
	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;
	}

1069
1070
1071
	client = i2c_new_client_device(adap, &info);
	if (IS_ERR(client))
		return PTR_ERR(client);
1072
1073

	/* Keep track of the added device */
1074
	mutex_lock(&adap->userspace_clients_lock);
1075
	list_add_tail(&client->detected, &adap->userspace_clients);
1076
	mutex_unlock(&adap->userspace_clients_lock);
1077
1078
1079
1080
1081
	dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
		 info.type, info.addr);

	return count;
}
1082
static DEVICE_ATTR_WO(new_device);
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093

/*
 * 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
1094
1095
delete_device_store(struct device *dev, struct device_attribute *attr,
		    const char *buf, size_t count)
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
{
	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;
1116
1117
	mutex_lock_nested(&adap->userspace_clients_lock,
			  i2c_adapter_depth(adap));
1118
1119
	list_for_each_entry_safe(client, next, &adap->userspace_clients,
				 detected) {
1120
		if (i2c_encode_flags_to_addr(client) == addr) {
1121
1122
1123
1124
1125
1126
1127
1128
1129
			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;
		}
	}
1130
	mutex_unlock(&adap->userspace_clients_lock);
1131
1132
1133
1134
1135
1136

	if (res < 0)
		dev_err(dev, "%s: Can't find device in list\n",
			"delete_device");
	return res;
}
1137
static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1138
				  delete_device_store);
1139
1140
1141
1142
1143
1144
1145

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

1148
struct device_type i2c_adapter_type = {
Wolfram Sang's avatar