xref: /linux/drivers/i2c/i2c-core-base.c (revision 78bb208b99e7d3314f670710fa9ee0a793682bca)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Linux I2C core
4  *
5  * Copyright (C) 1995-99 Simon G. Vogl
6  *   With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>
7  *   Mux support by Rodolfo Giometti <giometti@enneenne.com> and
8  *   Michael Lawnick <michael.lawnick.ext@nsn.com>
9  *
10  * Copyright (C) 2013-2017 Wolfram Sang <wsa@kernel.org>
11  */
12 
13 #define pr_fmt(fmt) "i2c-core: " fmt
14 
15 #include <dt-bindings/i2c/i2c.h>
16 #include <linux/acpi.h>
17 #include <linux/clk/clk-conf.h>
18 #include <linux/completion.h>
19 #include <linux/debugfs.h>
20 #include <linux/delay.h>
21 #include <linux/err.h>
22 #include <linux/errno.h>
23 #include <linux/gpio/consumer.h>
24 #include <linux/i2c.h>
25 #include <linux/i2c-smbus.h>
26 #include <linux/idr.h>
27 #include <linux/init.h>
28 #include <linux/interrupt.h>
29 #include <linux/irq.h>
30 #include <linux/jump_label.h>
31 #include <linux/kernel.h>
32 #include <linux/module.h>
33 #include <linux/mutex.h>
34 #include <linux/of_device.h>
35 #include <linux/of.h>
36 #include <linux/pinctrl/consumer.h>
37 #include <linux/pinctrl/devinfo.h>
38 #include <linux/pm_domain.h>
39 #include <linux/pm_runtime.h>
40 #include <linux/pm_wakeirq.h>
41 #include <linux/property.h>
42 #include <linux/rwsem.h>
43 #include <linux/slab.h>
44 #include <linux/string_choices.h>
45 
46 #include "i2c-core.h"
47 
48 #define CREATE_TRACE_POINTS
49 #include <trace/events/i2c.h>
50 
51 #define I2C_ADDR_OFFSET_TEN_BIT	0xa000
52 #define I2C_ADDR_OFFSET_SLAVE	0x1000
53 
54 #define I2C_ADDR_7BITS_MAX	0x77
55 #define I2C_ADDR_7BITS_COUNT	(I2C_ADDR_7BITS_MAX + 1)
56 
57 #define I2C_ADDR_DEVICE_ID	0x7c
58 
59 /*
60  * core_lock protects i2c_adapter_idr, and guarantees that device detection,
61  * deletion of detected devices are serialized
62  */
63 static DEFINE_MUTEX(core_lock);
64 static DEFINE_IDR(i2c_adapter_idr);
65 
66 static void i2c_deregister_clients(struct i2c_adapter *adap);
67 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
68 
69 static DEFINE_STATIC_KEY_FALSE(i2c_trace_msg_key);
70 static bool is_registered;
71 
72 static struct dentry *i2c_debugfs_root;
73 
i2c_transfer_trace_reg(void)74 int i2c_transfer_trace_reg(void)
75 {
76 	static_branch_inc(&i2c_trace_msg_key);
77 	return 0;
78 }
79 
i2c_transfer_trace_unreg(void)80 void i2c_transfer_trace_unreg(void)
81 {
82 	static_branch_dec(&i2c_trace_msg_key);
83 }
84 
i2c_freq_mode_string(u32 bus_freq_hz)85 const char *i2c_freq_mode_string(u32 bus_freq_hz)
86 {
87 	switch (bus_freq_hz) {
88 	case I2C_MAX_STANDARD_MODE_FREQ:
89 		return "Standard Mode (100 kHz)";
90 	case I2C_MAX_FAST_MODE_FREQ:
91 		return "Fast Mode (400 kHz)";
92 	case I2C_MAX_FAST_MODE_PLUS_FREQ:
93 		return "Fast Mode Plus (1.0 MHz)";
94 	case I2C_MAX_TURBO_MODE_FREQ:
95 		return "Turbo Mode (1.4 MHz)";
96 	case I2C_MAX_HIGH_SPEED_MODE_FREQ:
97 		return "High Speed Mode (3.4 MHz)";
98 	case I2C_MAX_ULTRA_FAST_MODE_FREQ:
99 		return "Ultra Fast Mode (5.0 MHz)";
100 	default:
101 		return "Unknown Mode";
102 	}
103 }
104 EXPORT_SYMBOL_GPL(i2c_freq_mode_string);
105 
i2c_match_id(const struct i2c_device_id * id,const struct i2c_client * client)106 const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
107 						const struct i2c_client *client)
108 {
109 	if (!(id && client))
110 		return NULL;
111 
112 	while (id->name[0]) {
113 		if (strcmp(client->name, id->name) == 0)
114 			return id;
115 		id++;
116 	}
117 	return NULL;
118 }
119 EXPORT_SYMBOL_GPL(i2c_match_id);
120 
i2c_get_match_data(const struct i2c_client * client)121 const void *i2c_get_match_data(const struct i2c_client *client)
122 {
123 	struct i2c_driver *driver = to_i2c_driver(client->dev.driver);
124 	const struct i2c_device_id *match;
125 	const void *data;
126 
127 	data = device_get_match_data(&client->dev);
128 	if (!data) {
129 		match = i2c_match_id(driver->id_table, client);
130 		if (!match)
131 			return NULL;
132 
133 		data = (const void *)match->driver_data;
134 	}
135 
136 	return data;
137 }
138 EXPORT_SYMBOL(i2c_get_match_data);
139 
i2c_device_match(struct device * dev,const struct device_driver * drv)140 static int i2c_device_match(struct device *dev, const struct device_driver *drv)
141 {
142 	struct i2c_client	*client = i2c_verify_client(dev);
143 	const struct i2c_driver	*driver;
144 
145 
146 	/* Attempt an OF style match */
147 	if (i2c_of_match_device(drv->of_match_table, client))
148 		return 1;
149 
150 	/* Then ACPI style match */
151 	if (acpi_driver_match_device(dev, drv))
152 		return 1;
153 
154 	driver = to_i2c_driver(drv);
155 
156 	/* Finally an I2C match */
157 	if (i2c_match_id(driver->id_table, client))
158 		return 1;
159 
160 	return 0;
161 }
162 
i2c_device_uevent(const struct device * dev,struct kobj_uevent_env * env)163 static int i2c_device_uevent(const struct device *dev, struct kobj_uevent_env *env)
164 {
165 	const struct i2c_client *client = to_i2c_client(dev);
166 	int rc;
167 
168 	rc = of_device_uevent_modalias(dev, env);
169 	if (rc != -ENODEV)
170 		return rc;
171 
172 	rc = acpi_device_uevent_modalias(dev, env);
173 	if (rc != -ENODEV)
174 		return rc;
175 
176 	return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
177 }
178 
179 /* i2c bus recovery routines */
get_scl_gpio_value(struct i2c_adapter * adap)180 static int get_scl_gpio_value(struct i2c_adapter *adap)
181 {
182 	return gpiod_get_value_cansleep(adap->bus_recovery_info->scl_gpiod);
183 }
184 
set_scl_gpio_value(struct i2c_adapter * adap,int val)185 static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
186 {
187 	gpiod_set_value_cansleep(adap->bus_recovery_info->scl_gpiod, val);
188 }
189 
get_sda_gpio_value(struct i2c_adapter * adap)190 static int get_sda_gpio_value(struct i2c_adapter *adap)
191 {
192 	return gpiod_get_value_cansleep(adap->bus_recovery_info->sda_gpiod);
193 }
194 
set_sda_gpio_value(struct i2c_adapter * adap,int val)195 static void set_sda_gpio_value(struct i2c_adapter *adap, int val)
196 {
197 	gpiod_set_value_cansleep(adap->bus_recovery_info->sda_gpiod, val);
198 }
199 
i2c_generic_bus_free(struct i2c_adapter * adap)200 static int i2c_generic_bus_free(struct i2c_adapter *adap)
201 {
202 	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
203 	int ret = -EOPNOTSUPP;
204 
205 	if (bri->get_bus_free)
206 		ret = bri->get_bus_free(adap);
207 	else if (bri->get_sda)
208 		ret = bri->get_sda(adap);
209 
210 	if (ret < 0)
211 		return ret;
212 
213 	return ret ? 0 : -EBUSY;
214 }
215 
216 /*
217  * We are generating clock pulses. ndelay() determines durating of clk pulses.
218  * We will generate clock with rate 100 KHz and so duration of both clock levels
219  * is: delay in ns = (10^6 / 100) / 2
220  */
221 #define RECOVERY_NDELAY		5000
222 #define RECOVERY_CLK_CNT	9
223 
i2c_generic_scl_recovery(struct i2c_adapter * adap)224 int i2c_generic_scl_recovery(struct i2c_adapter *adap)
225 {
226 	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
227 	int i = 0, scl = 1, ret = 0;
228 
229 	if (bri->prepare_recovery)
230 		bri->prepare_recovery(adap);
231 	if (bri->pinctrl)
232 		pinctrl_select_state(bri->pinctrl, bri->pins_gpio);
233 
234 	/*
235 	 * If we can set SDA, we will always create a STOP to ensure additional
236 	 * pulses will do no harm. This is achieved by letting SDA follow SCL
237 	 * half a cycle later. Check the 'incomplete_write_byte' fault injector
238 	 * for details. Note that we must honour tsu:sto, 4us, but lets use 5us
239 	 * here for simplicity.
240 	 */
241 	bri->set_scl(adap, scl);
242 	ndelay(RECOVERY_NDELAY);
243 	if (bri->set_sda)
244 		bri->set_sda(adap, scl);
245 	ndelay(RECOVERY_NDELAY / 2);
246 
247 	/*
248 	 * By this time SCL is high, as we need to give 9 falling-rising edges
249 	 */
250 	while (i++ < RECOVERY_CLK_CNT * 2) {
251 		if (scl) {
252 			/* SCL shouldn't be low here */
253 			if (!bri->get_scl(adap)) {
254 				dev_err(&adap->dev,
255 					"SCL is stuck low, exit recovery\n");
256 				ret = -EBUSY;
257 				break;
258 			}
259 		}
260 
261 		scl = !scl;
262 		bri->set_scl(adap, scl);
263 		/* Creating STOP again, see above */
264 		if (scl)  {
265 			/* Honour minimum tsu:sto */
266 			ndelay(RECOVERY_NDELAY);
267 		} else {
268 			/* Honour minimum tf and thd:dat */
269 			ndelay(RECOVERY_NDELAY / 2);
270 		}
271 		if (bri->set_sda)
272 			bri->set_sda(adap, scl);
273 		ndelay(RECOVERY_NDELAY / 2);
274 
275 		if (scl) {
276 			ret = i2c_generic_bus_free(adap);
277 			if (ret == 0)
278 				break;
279 		}
280 	}
281 
282 	/* If we can't check bus status, assume recovery worked */
283 	if (ret == -EOPNOTSUPP)
284 		ret = 0;
285 
286 	if (bri->unprepare_recovery)
287 		bri->unprepare_recovery(adap);
288 	if (bri->pinctrl)
289 		pinctrl_select_state(bri->pinctrl, bri->pins_default);
290 
291 	return ret;
292 }
293 EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
294 
i2c_recover_bus(struct i2c_adapter * adap)295 int i2c_recover_bus(struct i2c_adapter *adap)
296 {
297 	if (!adap->bus_recovery_info)
298 		return -EBUSY;
299 
300 	dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
301 	return adap->bus_recovery_info->recover_bus(adap);
302 }
303 EXPORT_SYMBOL_GPL(i2c_recover_bus);
304 
i2c_gpio_init_pinctrl_recovery(struct i2c_adapter * adap)305 static void i2c_gpio_init_pinctrl_recovery(struct i2c_adapter *adap)
306 {
307 	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
308 	struct device *dev = &adap->dev;
309 	struct pinctrl *p = bri->pinctrl ?: dev_pinctrl(dev->parent);
310 
311 	bri->pinctrl = p;
312 
313 	/*
314 	 * we can't change states without pinctrl, so remove the states if
315 	 * populated
316 	 */
317 	if (!p) {
318 		bri->pins_default = NULL;
319 		bri->pins_gpio = NULL;
320 		return;
321 	}
322 
323 	if (!bri->pins_default) {
324 		bri->pins_default = pinctrl_lookup_state(p,
325 							 PINCTRL_STATE_DEFAULT);
326 		if (IS_ERR(bri->pins_default)) {
327 			dev_dbg(dev, PINCTRL_STATE_DEFAULT " state not found for GPIO recovery\n");
328 			bri->pins_default = NULL;
329 		}
330 	}
331 	if (!bri->pins_gpio) {
332 		bri->pins_gpio = pinctrl_lookup_state(p, "gpio");
333 		if (IS_ERR(bri->pins_gpio))
334 			bri->pins_gpio = pinctrl_lookup_state(p, "recovery");
335 
336 		if (IS_ERR(bri->pins_gpio)) {
337 			dev_dbg(dev, "no gpio or recovery state found for GPIO recovery\n");
338 			bri->pins_gpio = NULL;
339 		}
340 	}
341 
342 	/* for pinctrl state changes, we need all the information */
343 	if (bri->pins_default && bri->pins_gpio) {
344 		dev_info(dev, "using pinctrl states for GPIO recovery");
345 	} else {
346 		bri->pinctrl = NULL;
347 		bri->pins_default = NULL;
348 		bri->pins_gpio = NULL;
349 	}
350 }
351 
i2c_gpio_init_generic_recovery(struct i2c_adapter * adap)352 static int i2c_gpio_init_generic_recovery(struct i2c_adapter *adap)
353 {
354 	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
355 	struct device *dev = &adap->dev;
356 	struct gpio_desc *gpiod;
357 	int ret = 0;
358 
359 	/*
360 	 * don't touch the recovery information if the driver is not using
361 	 * generic SCL recovery
362 	 */
363 	if (bri->recover_bus && bri->recover_bus != i2c_generic_scl_recovery)
364 		return 0;
365 
366 	/*
367 	 * pins might be taken as GPIO, so we should inform pinctrl about
368 	 * this and move the state to GPIO
369 	 */
370 	if (bri->pinctrl)
371 		pinctrl_select_state(bri->pinctrl, bri->pins_gpio);
372 
373 	/*
374 	 * if there is incomplete or no recovery information, see if generic
375 	 * GPIO recovery is available
376 	 */
377 	if (!bri->scl_gpiod) {
378 		gpiod = devm_gpiod_get(dev, "scl", GPIOD_OUT_HIGH_OPEN_DRAIN);
379 		if (PTR_ERR(gpiod) == -EPROBE_DEFER) {
380 			ret  = -EPROBE_DEFER;
381 			goto cleanup_pinctrl_state;
382 		}
383 		if (!IS_ERR(gpiod)) {
384 			bri->scl_gpiod = gpiod;
385 			bri->recover_bus = i2c_generic_scl_recovery;
386 			dev_info(dev, "using generic GPIOs for recovery\n");
387 		}
388 	}
389 
390 	/* SDA GPIOD line is optional, so we care about DEFER only */
391 	if (!bri->sda_gpiod) {
392 		/*
393 		 * We have SCL. Pull SCL low and wait a bit so that SDA glitches
394 		 * have no effect.
395 		 */
396 		gpiod_direction_output(bri->scl_gpiod, 0);
397 		udelay(10);
398 		gpiod = devm_gpiod_get(dev, "sda", GPIOD_IN);
399 
400 		/* Wait a bit in case of a SDA glitch, and then release SCL. */
401 		udelay(10);
402 		gpiod_direction_output(bri->scl_gpiod, 1);
403 
404 		if (PTR_ERR(gpiod) == -EPROBE_DEFER) {
405 			ret = -EPROBE_DEFER;
406 			goto cleanup_pinctrl_state;
407 		}
408 		if (!IS_ERR(gpiod))
409 			bri->sda_gpiod = gpiod;
410 	}
411 
412 cleanup_pinctrl_state:
413 	/* change the state of the pins back to their default state */
414 	if (bri->pinctrl)
415 		pinctrl_select_state(bri->pinctrl, bri->pins_default);
416 
417 	return ret;
418 }
419 
i2c_gpio_init_recovery(struct i2c_adapter * adap)420 static int i2c_gpio_init_recovery(struct i2c_adapter *adap)
421 {
422 	i2c_gpio_init_pinctrl_recovery(adap);
423 	return i2c_gpio_init_generic_recovery(adap);
424 }
425 
i2c_init_recovery(struct i2c_adapter * adap)426 static int i2c_init_recovery(struct i2c_adapter *adap)
427 {
428 	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
429 	bool is_error_level = true;
430 	char *err_str;
431 
432 	if (!bri)
433 		return 0;
434 
435 	if (i2c_gpio_init_recovery(adap) == -EPROBE_DEFER)
436 		return -EPROBE_DEFER;
437 
438 	if (!bri->recover_bus) {
439 		err_str = "no suitable method provided";
440 		is_error_level = false;
441 		goto err;
442 	}
443 
444 	if (bri->scl_gpiod && bri->recover_bus == i2c_generic_scl_recovery) {
445 		bri->get_scl = get_scl_gpio_value;
446 		bri->set_scl = set_scl_gpio_value;
447 		if (bri->sda_gpiod) {
448 			bri->get_sda = get_sda_gpio_value;
449 			if (gpiod_get_direction(bri->sda_gpiod) == GPIO_LINE_DIRECTION_OUT ||
450 			    gpiod_is_single_ended(bri->sda_gpiod))
451 				bri->set_sda = set_sda_gpio_value;
452 		}
453 	} else if (bri->recover_bus == i2c_generic_scl_recovery) {
454 		/* Generic SCL recovery */
455 		if (!bri->set_scl || !bri->get_scl) {
456 			err_str = "no {get|set}_scl() found";
457 			goto err;
458 		}
459 		if (!bri->set_sda && !bri->get_sda) {
460 			err_str = "either get_sda() or set_sda() needed";
461 			goto err;
462 		}
463 	}
464 
465 	return 0;
466  err:
467 	if (is_error_level)
468 		dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
469 	else
470 		dev_dbg(&adap->dev, "Not using recovery: %s\n", err_str);
471 	adap->bus_recovery_info = NULL;
472 
473 	return -EINVAL;
474 }
475 
i2c_smbus_host_notify_to_irq(const struct i2c_client * client)476 static int i2c_smbus_host_notify_to_irq(const struct i2c_client *client)
477 {
478 	struct i2c_adapter *adap = client->adapter;
479 	unsigned int irq;
480 
481 	if (!adap->host_notify_domain)
482 		return -ENXIO;
483 
484 	if (client->flags & I2C_CLIENT_TEN)
485 		return -EINVAL;
486 
487 	irq = irq_create_mapping(adap->host_notify_domain, client->addr);
488 
489 	return irq > 0 ? irq : -ENXIO;
490 }
491 
i2c_device_probe(struct device * dev)492 static int i2c_device_probe(struct device *dev)
493 {
494 	struct fwnode_handle	*fwnode = dev_fwnode(dev);
495 	struct i2c_client	*client = i2c_verify_client(dev);
496 	struct i2c_driver	*driver;
497 	bool do_power_on;
498 	int status;
499 
500 	if (!client)
501 		return 0;
502 
503 	client->irq = client->init_irq;
504 
505 	if (!client->irq) {
506 		int irq = -ENOENT;
507 
508 		if (client->flags & I2C_CLIENT_HOST_NOTIFY) {
509 			dev_dbg(dev, "Using Host Notify IRQ\n");
510 			/* Keep adapter active when Host Notify is required */
511 			pm_runtime_get_sync(&client->adapter->dev);
512 			irq = i2c_smbus_host_notify_to_irq(client);
513 		} else if (is_of_node(fwnode)) {
514 			irq = fwnode_irq_get_byname(fwnode, "irq");
515 			if (irq == -EINVAL || irq == -ENODATA)
516 				irq = fwnode_irq_get(fwnode, 0);
517 		} else if (is_acpi_device_node(fwnode)) {
518 			bool wake_capable;
519 
520 			irq = i2c_acpi_get_irq(client, &wake_capable);
521 			if (irq > 0 && wake_capable)
522 				client->flags |= I2C_CLIENT_WAKE;
523 		}
524 		if (irq == -EPROBE_DEFER) {
525 			status = dev_err_probe(dev, irq, "can't get irq\n");
526 			goto put_sync_adapter;
527 		}
528 
529 		if (irq < 0)
530 			irq = 0;
531 
532 		client->irq = irq;
533 	}
534 
535 	driver = to_i2c_driver(dev->driver);
536 
537 	/*
538 	 * An I2C ID table is not mandatory, if and only if, a suitable OF
539 	 * or ACPI ID table is supplied for the probing device.
540 	 */
541 	if (!driver->id_table &&
542 	    !acpi_driver_match_device(dev, dev->driver) &&
543 	    !i2c_of_match_device(dev->driver->of_match_table, client)) {
544 		status = -ENODEV;
545 		goto put_sync_adapter;
546 	}
547 
548 	if (client->flags & I2C_CLIENT_WAKE) {
549 		int wakeirq;
550 
551 		wakeirq = fwnode_irq_get_byname(fwnode, "wakeup");
552 		if (wakeirq == -EPROBE_DEFER) {
553 			status = dev_err_probe(dev, wakeirq, "can't get wakeirq\n");
554 			goto put_sync_adapter;
555 		}
556 
557 		device_init_wakeup(&client->dev, true);
558 
559 		if (wakeirq > 0 && wakeirq != client->irq)
560 			status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
561 		else if (client->irq > 0)
562 			status = dev_pm_set_wake_irq(dev, client->irq);
563 		else
564 			status = 0;
565 
566 		if (status)
567 			dev_warn(&client->dev, "failed to set up wakeup irq\n");
568 	}
569 
570 	dev_dbg(dev, "probe\n");
571 
572 	status = of_clk_set_defaults(to_of_node(fwnode), false);
573 	if (status < 0)
574 		goto err_clear_wakeup_irq;
575 
576 	do_power_on = !i2c_acpi_waive_d0_probe(dev);
577 	status = dev_pm_domain_attach(&client->dev, PD_FLAG_DETACH_POWER_OFF |
578 				      (do_power_on ? PD_FLAG_ATTACH_POWER_ON : 0));
579 	if (status)
580 		goto err_clear_wakeup_irq;
581 
582 	client->devres_group_id = devres_open_group(&client->dev, NULL,
583 						    GFP_KERNEL);
584 	if (!client->devres_group_id) {
585 		status = -ENOMEM;
586 		goto err_clear_wakeup_irq;
587 	}
588 
589 	client->debugfs = debugfs_create_dir(dev_name(&client->dev),
590 					     client->adapter->debugfs);
591 
592 	if (driver->probe)
593 		status = driver->probe(client);
594 	else
595 		status = -EINVAL;
596 
597 	/*
598 	 * Note that we are not closing the devres group opened above so
599 	 * even resources that were attached to the device after probe is
600 	 * run are released when i2c_device_remove() is executed. This is
601 	 * needed as some drivers would allocate additional resources,
602 	 * for example when updating firmware.
603 	 */
604 
605 	if (status)
606 		goto err_release_driver_resources;
607 
608 	return 0;
609 
610 err_release_driver_resources:
611 	debugfs_remove_recursive(client->debugfs);
612 	devres_release_group(&client->dev, client->devres_group_id);
613 err_clear_wakeup_irq:
614 	dev_pm_clear_wake_irq(&client->dev);
615 	device_init_wakeup(&client->dev, false);
616 put_sync_adapter:
617 	if (client->flags & I2C_CLIENT_HOST_NOTIFY)
618 		pm_runtime_put_sync(&client->adapter->dev);
619 
620 	return status;
621 }
622 
i2c_device_remove(struct device * dev)623 static void i2c_device_remove(struct device *dev)
624 {
625 	struct i2c_client	*client = to_i2c_client(dev);
626 	struct i2c_driver	*driver;
627 
628 	driver = to_i2c_driver(dev->driver);
629 	if (driver->remove) {
630 		dev_dbg(dev, "remove\n");
631 
632 		driver->remove(client);
633 	}
634 
635 	debugfs_remove_recursive(client->debugfs);
636 
637 	devres_release_group(&client->dev, client->devres_group_id);
638 
639 	dev_pm_clear_wake_irq(&client->dev);
640 	device_init_wakeup(&client->dev, false);
641 
642 	client->irq = 0;
643 	if (client->flags & I2C_CLIENT_HOST_NOTIFY)
644 		pm_runtime_put(&client->adapter->dev);
645 }
646 
i2c_device_shutdown(struct device * dev)647 static void i2c_device_shutdown(struct device *dev)
648 {
649 	struct i2c_client *client = i2c_verify_client(dev);
650 	struct i2c_driver *driver;
651 
652 	if (!client || !dev->driver)
653 		return;
654 	driver = to_i2c_driver(dev->driver);
655 	if (driver->shutdown)
656 		driver->shutdown(client);
657 	else if (client->irq > 0)
658 		disable_irq(client->irq);
659 }
660 
i2c_client_dev_release(struct device * dev)661 static void i2c_client_dev_release(struct device *dev)
662 {
663 	kfree(to_i2c_client(dev));
664 }
665 
666 static ssize_t
name_show(struct device * dev,struct device_attribute * attr,char * buf)667 name_show(struct device *dev, struct device_attribute *attr, char *buf)
668 {
669 	return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
670 		       to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
671 }
672 static DEVICE_ATTR_RO(name);
673 
674 static ssize_t
modalias_show(struct device * dev,struct device_attribute * attr,char * buf)675 modalias_show(struct device *dev, struct device_attribute *attr, char *buf)
676 {
677 	struct i2c_client *client = to_i2c_client(dev);
678 	int len;
679 
680 	len = of_device_modalias(dev, buf, PAGE_SIZE);
681 	if (len != -ENODEV)
682 		return len;
683 
684 	len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
685 	if (len != -ENODEV)
686 		return len;
687 
688 	return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
689 }
690 static DEVICE_ATTR_RO(modalias);
691 
692 static struct attribute *i2c_dev_attrs[] = {
693 	&dev_attr_name.attr,
694 	/* modalias helps coldplug:  modprobe $(cat .../modalias) */
695 	&dev_attr_modalias.attr,
696 	NULL
697 };
698 ATTRIBUTE_GROUPS(i2c_dev);
699 
700 const struct bus_type i2c_bus_type = {
701 	.name		= "i2c",
702 	.match		= i2c_device_match,
703 	.probe		= i2c_device_probe,
704 	.remove		= i2c_device_remove,
705 	.shutdown	= i2c_device_shutdown,
706 };
707 EXPORT_SYMBOL_GPL(i2c_bus_type);
708 
709 const struct device_type i2c_client_type = {
710 	.groups		= i2c_dev_groups,
711 	.uevent		= i2c_device_uevent,
712 	.release	= i2c_client_dev_release,
713 };
714 EXPORT_SYMBOL_GPL(i2c_client_type);
715 
716 
717 /**
718  * i2c_verify_client - return parameter as i2c_client, or NULL
719  * @dev: device, probably from some driver model iterator
720  *
721  * When traversing the driver model tree, perhaps using driver model
722  * iterators like @device_for_each_child(), you can't assume very much
723  * about the nodes you find.  Use this function to avoid oopses caused
724  * by wrongly treating some non-I2C device as an i2c_client.
725  */
i2c_verify_client(struct device * dev)726 struct i2c_client *i2c_verify_client(struct device *dev)
727 {
728 	return (dev->type == &i2c_client_type)
729 			? to_i2c_client(dev)
730 			: NULL;
731 }
732 EXPORT_SYMBOL(i2c_verify_client);
733 
734 
735 /* Return a unique address which takes the flags of the client into account */
i2c_encode_flags_to_addr(struct i2c_client * client)736 static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
737 {
738 	unsigned short addr = client->addr;
739 
740 	/* For some client flags, add an arbitrary offset to avoid collisions */
741 	if (client->flags & I2C_CLIENT_TEN)
742 		addr |= I2C_ADDR_OFFSET_TEN_BIT;
743 
744 	if (client->flags & I2C_CLIENT_SLAVE)
745 		addr |= I2C_ADDR_OFFSET_SLAVE;
746 
747 	return addr;
748 }
749 
750 /* This is a permissive address validity check, I2C address map constraints
751  * are purposely not enforced, except for the general call address. */
i2c_check_addr_validity(unsigned int addr,unsigned short flags)752 static int i2c_check_addr_validity(unsigned int addr, unsigned short flags)
753 {
754 	if (flags & I2C_CLIENT_TEN) {
755 		/* 10-bit address, all values are valid */
756 		if (addr > 0x3ff)
757 			return -EINVAL;
758 	} else {
759 		/* 7-bit address, reject the general call address */
760 		if (addr == 0x00 || addr > 0x7f)
761 			return -EINVAL;
762 	}
763 	return 0;
764 }
765 
766 /* And this is a strict address validity check, used when probing. If a
767  * device uses a reserved address, then it shouldn't be probed. 7-bit
768  * addressing is assumed, 10-bit address devices are rare and should be
769  * explicitly enumerated. */
i2c_check_7bit_addr_validity_strict(unsigned short addr)770 int i2c_check_7bit_addr_validity_strict(unsigned short addr)
771 {
772 	/*
773 	 * Reserved addresses per I2C specification:
774 	 *  0x00       General call address / START byte
775 	 *  0x01       CBUS address
776 	 *  0x02       Reserved for different bus format
777 	 *  0x03       Reserved for future purposes
778 	 *  0x04-0x07  Hs-mode master code
779 	 *  0x78-0x7b  10-bit slave addressing
780 	 *  0x7c-0x7f  Reserved for future purposes
781 	 */
782 	if (addr < 0x08 || addr > 0x77)
783 		return -EINVAL;
784 	return 0;
785 }
786 
__i2c_check_addr_busy(struct device * dev,void * addrp)787 static int __i2c_check_addr_busy(struct device *dev, void *addrp)
788 {
789 	struct i2c_client	*client = i2c_verify_client(dev);
790 	int			addr = *(int *)addrp;
791 
792 	if (client && i2c_encode_flags_to_addr(client) == addr)
793 		return -EBUSY;
794 	return 0;
795 }
796 
797 /* walk up mux tree */
i2c_check_mux_parents(struct i2c_adapter * adapter,int addr)798 static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
799 {
800 	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
801 	int result;
802 
803 	result = device_for_each_child(&adapter->dev, &addr,
804 					__i2c_check_addr_busy);
805 
806 	if (!result && parent)
807 		result = i2c_check_mux_parents(parent, addr);
808 
809 	return result;
810 }
811 
812 /* recurse down mux tree */
i2c_check_mux_children(struct device * dev,void * addrp)813 static int i2c_check_mux_children(struct device *dev, void *addrp)
814 {
815 	int result;
816 
817 	if (dev->type == &i2c_adapter_type)
818 		result = device_for_each_child(dev, addrp,
819 						i2c_check_mux_children);
820 	else
821 		result = __i2c_check_addr_busy(dev, addrp);
822 
823 	return result;
824 }
825 
i2c_check_addr_busy(struct i2c_adapter * adapter,int addr)826 static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
827 {
828 	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
829 	int result = 0;
830 
831 	if (parent)
832 		result = i2c_check_mux_parents(parent, addr);
833 
834 	if (!result)
835 		result = device_for_each_child(&adapter->dev, &addr,
836 						i2c_check_mux_children);
837 
838 	return result;
839 }
840 
841 /**
842  * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
843  * @adapter: Target I2C bus segment
844  * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
845  *	locks only this branch in the adapter tree
846  */
i2c_adapter_lock_bus(struct i2c_adapter * adapter,unsigned int flags)847 static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
848 				 unsigned int flags)
849 {
850 	rt_mutex_lock_nested(&adapter->bus_lock, i2c_adapter_depth(adapter));
851 }
852 
853 /**
854  * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
855  * @adapter: Target I2C bus segment
856  * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
857  *	trylocks only this branch in the adapter tree
858  */
i2c_adapter_trylock_bus(struct i2c_adapter * adapter,unsigned int flags)859 static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
860 				   unsigned int flags)
861 {
862 	return rt_mutex_trylock(&adapter->bus_lock);
863 }
864 
865 /**
866  * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
867  * @adapter: Target I2C bus segment
868  * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
869  *	unlocks only this branch in the adapter tree
870  */
i2c_adapter_unlock_bus(struct i2c_adapter * adapter,unsigned int flags)871 static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
872 				   unsigned int flags)
873 {
874 	rt_mutex_unlock(&adapter->bus_lock);
875 }
876 
i2c_dev_set_name(struct i2c_adapter * adap,struct i2c_client * client,struct i2c_board_info const * info)877 static void i2c_dev_set_name(struct i2c_adapter *adap,
878 			     struct i2c_client *client,
879 			     struct i2c_board_info const *info)
880 {
881 	struct acpi_device *adev = ACPI_COMPANION(&client->dev);
882 
883 	if (info && info->dev_name) {
884 		dev_set_name(&client->dev, "i2c-%s", info->dev_name);
885 		return;
886 	}
887 
888 	if (adev) {
889 		dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
890 		return;
891 	}
892 
893 	dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
894 		     i2c_encode_flags_to_addr(client));
895 }
896 
i2c_dev_irq_from_resources(const struct resource * resources,unsigned int num_resources)897 int i2c_dev_irq_from_resources(const struct resource *resources,
898 			       unsigned int num_resources)
899 {
900 	struct irq_data *irqd;
901 	int i;
902 
903 	for (i = 0; i < num_resources; i++) {
904 		const struct resource *r = &resources[i];
905 
906 		if (resource_type(r) != IORESOURCE_IRQ)
907 			continue;
908 
909 		if (r->flags & IORESOURCE_BITS) {
910 			irqd = irq_get_irq_data(r->start);
911 			if (!irqd)
912 				break;
913 
914 			irqd_set_trigger_type(irqd, r->flags & IORESOURCE_BITS);
915 		}
916 
917 		return r->start;
918 	}
919 
920 	return 0;
921 }
922 
923 /*
924  * Serialize device instantiation in case it can be instantiated explicitly
925  * and by auto-detection
926  */
i2c_lock_addr(struct i2c_adapter * adap,unsigned short addr,unsigned short flags)927 static int i2c_lock_addr(struct i2c_adapter *adap, unsigned short addr,
928 			 unsigned short flags)
929 {
930 	if (!(flags & I2C_CLIENT_TEN) &&
931 	    test_and_set_bit(addr, adap->addrs_in_instantiation))
932 		return -EBUSY;
933 
934 	return 0;
935 }
936 
i2c_unlock_addr(struct i2c_adapter * adap,unsigned short addr,unsigned short flags)937 static void i2c_unlock_addr(struct i2c_adapter *adap, unsigned short addr,
938 			    unsigned short flags)
939 {
940 	if (!(flags & I2C_CLIENT_TEN))
941 		clear_bit(addr, adap->addrs_in_instantiation);
942 }
943 
944 /**
945  * i2c_new_client_device - instantiate an i2c device
946  * @adap: the adapter managing the device
947  * @info: describes one I2C device; bus_num is ignored
948  * Context: can sleep
949  *
950  * Create an i2c device. Binding is handled through driver model
951  * probe()/remove() methods.  A driver may be bound to this device when we
952  * return from this function, or any later moment (e.g. maybe hotplugging will
953  * load the driver module).  This call is not appropriate for use by mainboard
954  * initialization logic, which usually runs during an arch_initcall() long
955  * before any i2c_adapter could exist.
956  *
957  * This returns the new i2c client, which may be saved for later use with
958  * i2c_unregister_device(); or an ERR_PTR to describe the error.
959  */
960 struct i2c_client *
i2c_new_client_device(struct i2c_adapter * adap,struct i2c_board_info const * info)961 i2c_new_client_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
962 {
963 	struct fwnode_handle *fwnode = info->fwnode;
964 	struct i2c_client *client;
965 	bool need_put = false;
966 	int status;
967 
968 	client = kzalloc_obj(*client);
969 	if (!client)
970 		return ERR_PTR(-ENOMEM);
971 
972 	client->adapter = adap;
973 
974 	client->dev.platform_data = info->platform_data;
975 	client->flags = info->flags;
976 	client->addr = info->addr;
977 
978 	client->init_irq = info->irq;
979 	if (!client->init_irq)
980 		client->init_irq = i2c_dev_irq_from_resources(info->resources,
981 							 info->num_resources);
982 
983 	strscpy(client->name, info->type, sizeof(client->name));
984 
985 	status = i2c_check_addr_validity(client->addr, client->flags);
986 	if (status) {
987 		dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
988 			client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
989 		goto out_err_silent;
990 	}
991 
992 	status = i2c_lock_addr(adap, client->addr, client->flags);
993 	if (status)
994 		goto out_err_silent;
995 
996 	/* Check for address business */
997 	status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
998 	if (status)
999 		goto out_err;
1000 
1001 	client->dev.parent = &client->adapter->dev;
1002 	client->dev.bus = &i2c_bus_type;
1003 	client->dev.type = &i2c_client_type;
1004 
1005 	device_enable_async_suspend(&client->dev);
1006 
1007 	device_set_node(&client->dev, fwnode_handle_get(fwnode));
1008 
1009 	if (info->swnode) {
1010 		status = device_add_software_node(&client->dev, info->swnode);
1011 		if (status) {
1012 			dev_err(&adap->dev,
1013 				"Failed to add software node to client %s: %d\n",
1014 				client->name, status);
1015 			goto out_err_put_fwnode;
1016 		}
1017 	}
1018 
1019 	i2c_dev_set_name(adap, client, info);
1020 	status = device_register(&client->dev);
1021 	if (status)
1022 		goto out_remove_swnode;
1023 
1024 	dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1025 		client->name, dev_name(&client->dev));
1026 
1027 	i2c_unlock_addr(adap, client->addr, client->flags);
1028 
1029 	return client;
1030 
1031 out_remove_swnode:
1032 	device_remove_software_node(&client->dev);
1033 	need_put = true;
1034 out_err_put_fwnode:
1035 	fwnode_handle_put(fwnode);
1036 out_err:
1037 	dev_err(&adap->dev,
1038 		"Failed to register i2c client %s at 0x%02x (%d)\n",
1039 		client->name, client->addr, status);
1040 	i2c_unlock_addr(adap, client->addr, client->flags);
1041 out_err_silent:
1042 	if (need_put)
1043 		put_device(&client->dev);
1044 	else
1045 		kfree(client);
1046 	return ERR_PTR(status);
1047 }
1048 EXPORT_SYMBOL_GPL(i2c_new_client_device);
1049 
1050 /**
1051  * i2c_unregister_device - reverse effect of i2c_new_*_device()
1052  * @client: value returned from i2c_new_*_device()
1053  * Context: can sleep
1054  */
i2c_unregister_device(struct i2c_client * client)1055 void i2c_unregister_device(struct i2c_client *client)
1056 {
1057 	struct fwnode_handle *fwnode;
1058 
1059 	if (IS_ERR_OR_NULL(client))
1060 		return;
1061 
1062 	fwnode = dev_fwnode(&client->dev);
1063 	if (is_of_node(fwnode))
1064 		of_node_clear_flag(to_of_node(fwnode), OF_POPULATED);
1065 	else if (is_acpi_device_node(fwnode))
1066 		acpi_device_clear_enumerated(to_acpi_device_node(fwnode));
1067 
1068 	/*
1069 	 * If the primary fwnode is a software node it is free-ed by
1070 	 * device_remove_software_node() below, avoid double-free.
1071 	 */
1072 	if (!is_software_node(fwnode))
1073 		fwnode_handle_put(fwnode);
1074 
1075 	device_remove_software_node(&client->dev);
1076 	device_unregister(&client->dev);
1077 }
1078 EXPORT_SYMBOL_GPL(i2c_unregister_device);
1079 
1080 /**
1081  * i2c_find_device_by_fwnode() - find an i2c_client for the fwnode
1082  * @fwnode: &struct fwnode_handle corresponding to the &struct i2c_client
1083  *
1084  * Look up and return the &struct i2c_client corresponding to the @fwnode.
1085  * If no client can be found, or @fwnode is NULL, this returns NULL.
1086  *
1087  * The user must call put_device(&client->dev) once done with the i2c client.
1088  */
i2c_find_device_by_fwnode(struct fwnode_handle * fwnode)1089 struct i2c_client *i2c_find_device_by_fwnode(struct fwnode_handle *fwnode)
1090 {
1091 	struct i2c_client *client;
1092 	struct device *dev;
1093 
1094 	if (IS_ERR_OR_NULL(fwnode))
1095 		return NULL;
1096 
1097 	dev = bus_find_device_by_fwnode(&i2c_bus_type, fwnode);
1098 	if (!dev)
1099 		return NULL;
1100 
1101 	client = i2c_verify_client(dev);
1102 	if (!client)
1103 		put_device(dev);
1104 
1105 	return client;
1106 }
1107 EXPORT_SYMBOL(i2c_find_device_by_fwnode);
1108 
1109 
1110 static const struct i2c_device_id dummy_id[] = {
1111 	{ .name = "dummy" },
1112 	{ .name = "smbus_host_notify" },
1113 	{ }
1114 };
1115 
dummy_probe(struct i2c_client * client)1116 static int dummy_probe(struct i2c_client *client)
1117 {
1118 	return 0;
1119 }
1120 
1121 static struct i2c_driver dummy_driver = {
1122 	.driver.name	= "dummy",
1123 	.probe		= dummy_probe,
1124 	.id_table	= dummy_id,
1125 };
1126 
1127 /**
1128  * i2c_new_dummy_device - return a new i2c device bound to a dummy driver
1129  * @adapter: the adapter managing the device
1130  * @address: seven bit address to be used
1131  * Context: can sleep
1132  *
1133  * This returns an I2C client bound to the "dummy" driver, intended for use
1134  * with devices that consume multiple addresses.  Examples of such chips
1135  * include various EEPROMS (like 24c04 and 24c08 models).
1136  *
1137  * These dummy devices have two main uses.  First, most I2C and SMBus calls
1138  * except i2c_transfer() need a client handle; the dummy will be that handle.
1139  * And second, this prevents the specified address from being bound to a
1140  * different driver.
1141  *
1142  * This returns the new i2c client, which should be saved for later use with
1143  * i2c_unregister_device(); or an ERR_PTR to describe the error.
1144  */
i2c_new_dummy_device(struct i2c_adapter * adapter,u16 address)1145 struct i2c_client *i2c_new_dummy_device(struct i2c_adapter *adapter, u16 address)
1146 {
1147 	struct i2c_board_info info = {
1148 		I2C_BOARD_INFO("dummy", address),
1149 	};
1150 
1151 	return i2c_new_client_device(adapter, &info);
1152 }
1153 EXPORT_SYMBOL_GPL(i2c_new_dummy_device);
1154 
devm_i2c_release_dummy(void * client)1155 static void devm_i2c_release_dummy(void *client)
1156 {
1157 	i2c_unregister_device(client);
1158 }
1159 
1160 /**
1161  * devm_i2c_new_dummy_device - return a new i2c device bound to a dummy driver
1162  * @dev: device the managed resource is bound to
1163  * @adapter: the adapter managing the device
1164  * @address: seven bit address to be used
1165  * Context: can sleep
1166  *
1167  * This is the device-managed version of @i2c_new_dummy_device. It returns the
1168  * new i2c client or an ERR_PTR in case of an error.
1169  */
devm_i2c_new_dummy_device(struct device * dev,struct i2c_adapter * adapter,u16 address)1170 struct i2c_client *devm_i2c_new_dummy_device(struct device *dev,
1171 					     struct i2c_adapter *adapter,
1172 					     u16 address)
1173 {
1174 	struct i2c_client *client;
1175 	int ret;
1176 
1177 	client = i2c_new_dummy_device(adapter, address);
1178 	if (IS_ERR(client))
1179 		return client;
1180 
1181 	ret = devm_add_action_or_reset(dev, devm_i2c_release_dummy, client);
1182 	if (ret)
1183 		return ERR_PTR(ret);
1184 
1185 	return client;
1186 }
1187 EXPORT_SYMBOL_GPL(devm_i2c_new_dummy_device);
1188 
1189 /**
1190  * i2c_new_ancillary_device - Helper to get the instantiated secondary address
1191  * and create the associated device
1192  * @client: Handle to the primary client
1193  * @name: Handle to specify which secondary address to get
1194  * @default_addr: Used as a fallback if no secondary address was specified
1195  * Context: can sleep
1196  *
1197  * I2C clients can be composed of multiple I2C slaves bound together in a single
1198  * component. The I2C client driver then binds to the master I2C slave and needs
1199  * to create I2C dummy clients to communicate with all the other slaves.
1200  *
1201  * This function creates and returns an I2C dummy client whose I2C address is
1202  * retrieved from the platform firmware based on the given slave name. If no
1203  * address is specified by the firmware default_addr is used.
1204  *
1205  * On DT-based platforms the address is retrieved from the "reg" property entry
1206  * cell whose "reg-names" value matches the slave name.
1207  *
1208  * This returns the new i2c client, which should be saved for later use with
1209  * i2c_unregister_device(); or an ERR_PTR to describe the error.
1210  */
i2c_new_ancillary_device(struct i2c_client * client,const char * name,u16 default_addr)1211 struct i2c_client *i2c_new_ancillary_device(struct i2c_client *client,
1212 						const char *name,
1213 						u16 default_addr)
1214 {
1215 	struct device_node *np = client->dev.of_node;
1216 	u32 addr = default_addr;
1217 	int i;
1218 
1219 	i = of_property_match_string(np, "reg-names", name);
1220 	if (i >= 0)
1221 		of_property_read_u32_index(np, "reg", i, &addr);
1222 
1223 	dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1224 	return i2c_new_dummy_device(client->adapter, addr);
1225 }
1226 EXPORT_SYMBOL_GPL(i2c_new_ancillary_device);
1227 
1228 /* ------------------------------------------------------------------------- */
1229 
1230 /* I2C bus adapters -- one roots each I2C or SMBUS segment */
1231 
i2c_adapter_dev_release(struct device * dev)1232 static void i2c_adapter_dev_release(struct device *dev)
1233 {
1234 	struct i2c_adapter *adap = to_i2c_adapter(dev);
1235 	complete(&adap->dev_released);
1236 }
1237 
i2c_adapter_depth(struct i2c_adapter * adapter)1238 unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1239 {
1240 	unsigned int depth = 0;
1241 	struct device *parent;
1242 
1243 	for (parent = adapter->dev.parent; parent; parent = parent->parent)
1244 		if (parent->type == &i2c_adapter_type)
1245 			depth++;
1246 
1247 	WARN_ONCE(depth >= MAX_LOCKDEP_SUBCLASSES,
1248 		  "adapter depth exceeds lockdep subclass limit\n");
1249 
1250 	return depth;
1251 }
1252 EXPORT_SYMBOL_GPL(i2c_adapter_depth);
1253 
1254 /*
1255  * Let users instantiate I2C devices through sysfs. This can be used when
1256  * platform initialization code doesn't contain the proper data for
1257  * whatever reason. Also useful for drivers that do device detection and
1258  * detection fails, either because the device uses an unexpected address,
1259  * or this is a compatible device with different ID register values.
1260  *
1261  * Parameter checking may look overzealous, but we really don't want
1262  * the user to provide incorrect parameters.
1263  */
1264 static ssize_t
new_device_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1265 new_device_store(struct device *dev, struct device_attribute *attr,
1266 		 const char *buf, size_t count)
1267 {
1268 	struct i2c_adapter *adap = to_i2c_adapter(dev);
1269 	struct i2c_board_info info;
1270 	struct i2c_client *client;
1271 	char *blank, end;
1272 	int res;
1273 
1274 	memset(&info, 0, sizeof(struct i2c_board_info));
1275 
1276 	blank = strchr(buf, ' ');
1277 	if (!blank) {
1278 		dev_err(dev, "%s: Missing parameters\n", "new_device");
1279 		return -EINVAL;
1280 	}
1281 	if (blank - buf > I2C_NAME_SIZE - 1) {
1282 		dev_err(dev, "%s: Invalid device name\n", "new_device");
1283 		return -EINVAL;
1284 	}
1285 	memcpy(info.type, buf, blank - buf);
1286 
1287 	/* Parse remaining parameters, reject extra parameters */
1288 	res = sscanf(++blank, "%hi%c", &info.addr, &end);
1289 	if (res < 1) {
1290 		dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1291 		return -EINVAL;
1292 	}
1293 	if (res > 1  && end != '\n') {
1294 		dev_err(dev, "%s: Extra parameters\n", "new_device");
1295 		return -EINVAL;
1296 	}
1297 
1298 	if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1299 		info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1300 		info.flags |= I2C_CLIENT_TEN;
1301 	}
1302 
1303 	if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1304 		info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1305 		info.flags |= I2C_CLIENT_SLAVE;
1306 	}
1307 
1308 	client = i2c_new_client_device(adap, &info);
1309 	if (IS_ERR(client))
1310 		return PTR_ERR(client);
1311 
1312 	/* Keep track of the added device */
1313 	mutex_lock(&adap->userspace_clients_lock);
1314 	list_add_tail(&client->detected, &adap->userspace_clients);
1315 	mutex_unlock(&adap->userspace_clients_lock);
1316 	dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1317 		 info.type, info.addr);
1318 
1319 	return count;
1320 }
1321 static DEVICE_ATTR_WO(new_device);
1322 
1323 /*
1324  * And of course let the users delete the devices they instantiated, if
1325  * they got it wrong. This interface can only be used to delete devices
1326  * instantiated by i2c_sysfs_new_device above. This guarantees that we
1327  * don't delete devices to which some kernel code still has references.
1328  *
1329  * Parameter checking may look overzealous, but we really don't want
1330  * the user to delete the wrong device.
1331  */
1332 static ssize_t
delete_device_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1333 delete_device_store(struct device *dev, struct device_attribute *attr,
1334 		    const char *buf, size_t count)
1335 {
1336 	struct i2c_adapter *adap = to_i2c_adapter(dev);
1337 	struct i2c_client *client, *next;
1338 	unsigned short addr;
1339 	char end;
1340 	int res;
1341 
1342 	/* Parse parameters, reject extra parameters */
1343 	res = sscanf(buf, "%hi%c", &addr, &end);
1344 	if (res < 1) {
1345 		dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1346 		return -EINVAL;
1347 	}
1348 	if (res > 1  && end != '\n') {
1349 		dev_err(dev, "%s: Extra parameters\n", "delete_device");
1350 		return -EINVAL;
1351 	}
1352 
1353 	/* Make sure the device was added through sysfs */
1354 	res = -ENOENT;
1355 	mutex_lock_nested(&adap->userspace_clients_lock,
1356 			  i2c_adapter_depth(adap));
1357 	list_for_each_entry_safe(client, next, &adap->userspace_clients,
1358 				 detected) {
1359 		if (i2c_encode_flags_to_addr(client) == addr) {
1360 			dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1361 				 "delete_device", client->name, client->addr);
1362 
1363 			list_del(&client->detected);
1364 			i2c_unregister_device(client);
1365 			res = count;
1366 			break;
1367 		}
1368 	}
1369 	mutex_unlock(&adap->userspace_clients_lock);
1370 
1371 	if (res < 0)
1372 		dev_err(dev, "%s: Can't find device in list\n",
1373 			"delete_device");
1374 	return res;
1375 }
1376 static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1377 				  delete_device_store);
1378 
1379 static struct attribute *i2c_adapter_attrs[] = {
1380 	&dev_attr_name.attr,
1381 	&dev_attr_new_device.attr,
1382 	&dev_attr_delete_device.attr,
1383 	NULL
1384 };
1385 ATTRIBUTE_GROUPS(i2c_adapter);
1386 
1387 const struct device_type i2c_adapter_type = {
1388 	.groups		= i2c_adapter_groups,
1389 	.release	= i2c_adapter_dev_release,
1390 };
1391 EXPORT_SYMBOL_GPL(i2c_adapter_type);
1392 
1393 /**
1394  * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1395  * @dev: device, probably from some driver model iterator
1396  *
1397  * When traversing the driver model tree, perhaps using driver model
1398  * iterators like @device_for_each_child(), you can't assume very much
1399  * about the nodes you find.  Use this function to avoid oopses caused
1400  * by wrongly treating some non-I2C device as an i2c_adapter.
1401  */
i2c_verify_adapter(struct device * dev)1402 struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1403 {
1404 	return (dev->type == &i2c_adapter_type)
1405 			? to_i2c_adapter(dev)
1406 			: NULL;
1407 }
1408 EXPORT_SYMBOL(i2c_verify_adapter);
1409 
i2c_scan_static_board_info(struct i2c_adapter * adapter)1410 static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1411 {
1412 	struct i2c_devinfo	*devinfo;
1413 
1414 	down_read(&__i2c_board_lock);
1415 	list_for_each_entry(devinfo, &__i2c_board_list, list) {
1416 		if (devinfo->busnum == adapter->nr &&
1417 		    IS_ERR(i2c_new_client_device(adapter, &devinfo->board_info)))
1418 			dev_err(&adapter->dev,
1419 				"Can't create device at 0x%02x\n",
1420 				devinfo->board_info.addr);
1421 	}
1422 	up_read(&__i2c_board_lock);
1423 }
1424 
i2c_do_add_adapter(struct i2c_driver * driver,struct i2c_adapter * adap)1425 static int i2c_do_add_adapter(struct i2c_driver *driver,
1426 			      struct i2c_adapter *adap)
1427 {
1428 	/* Detect supported devices on that bus, and instantiate them */
1429 	i2c_detect(adap, driver);
1430 
1431 	return 0;
1432 }
1433 
__process_new_adapter(struct device_driver * d,void * data)1434 static int __process_new_adapter(struct device_driver *d, void *data)
1435 {
1436 	return i2c_do_add_adapter(to_i2c_driver(d), data);
1437 }
1438 
1439 static const struct i2c_lock_operations i2c_adapter_lock_ops = {
1440 	.lock_bus =    i2c_adapter_lock_bus,
1441 	.trylock_bus = i2c_adapter_trylock_bus,
1442 	.unlock_bus =  i2c_adapter_unlock_bus,
1443 };
1444 
i2c_host_notify_irq_teardown(struct i2c_adapter * adap)1445 static void i2c_host_notify_irq_teardown(struct i2c_adapter *adap)
1446 {
1447 	struct irq_domain *domain = adap->host_notify_domain;
1448 	irq_hw_number_t hwirq;
1449 
1450 	if (!domain)
1451 		return;
1452 
1453 	for (hwirq = 0 ; hwirq < I2C_ADDR_7BITS_COUNT ; hwirq++)
1454 		irq_dispose_mapping(irq_find_mapping(domain, hwirq));
1455 
1456 	irq_domain_remove(domain);
1457 	adap->host_notify_domain = NULL;
1458 }
1459 
i2c_host_notify_irq_map(struct irq_domain * h,unsigned int virq,irq_hw_number_t hw_irq_num)1460 static int i2c_host_notify_irq_map(struct irq_domain *h,
1461 					  unsigned int virq,
1462 					  irq_hw_number_t hw_irq_num)
1463 {
1464 	irq_set_chip_and_handler(virq, &dummy_irq_chip, handle_simple_irq);
1465 
1466 	return 0;
1467 }
1468 
1469 static const struct irq_domain_ops i2c_host_notify_irq_ops = {
1470 	.map = i2c_host_notify_irq_map,
1471 };
1472 
i2c_setup_host_notify_irq_domain(struct i2c_adapter * adap)1473 static int i2c_setup_host_notify_irq_domain(struct i2c_adapter *adap)
1474 {
1475 	struct irq_domain *domain;
1476 
1477 	if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_HOST_NOTIFY))
1478 		return 0;
1479 
1480 	domain = irq_domain_create_linear(dev_fwnode(adap->dev.parent),
1481 					  I2C_ADDR_7BITS_COUNT,
1482 					  &i2c_host_notify_irq_ops, adap);
1483 	if (!domain)
1484 		return -ENOMEM;
1485 
1486 	adap->host_notify_domain = domain;
1487 
1488 	return 0;
1489 }
1490 
1491 /**
1492  * i2c_handle_smbus_host_notify - Forward a Host Notify event to the correct
1493  * I2C client.
1494  * @adap: the adapter
1495  * @addr: the I2C address of the notifying device
1496  * Context: can't sleep
1497  *
1498  * Helper function to be called from an I2C bus driver's interrupt
1499  * handler. It will schedule the Host Notify IRQ.
1500  */
i2c_handle_smbus_host_notify(struct i2c_adapter * adap,unsigned short addr)1501 int i2c_handle_smbus_host_notify(struct i2c_adapter *adap, unsigned short addr)
1502 {
1503 	int irq;
1504 
1505 	if (!adap)
1506 		return -EINVAL;
1507 
1508 	dev_dbg(&adap->dev, "Detected HostNotify from address 0x%02x", addr);
1509 
1510 	irq = irq_find_mapping(adap->host_notify_domain, addr);
1511 	if (irq <= 0)
1512 		return -ENXIO;
1513 
1514 	generic_handle_irq_safe(irq);
1515 
1516 	return 0;
1517 }
1518 EXPORT_SYMBOL_GPL(i2c_handle_smbus_host_notify);
1519 
i2c_allocate_adapter_id(struct i2c_adapter * adap)1520 static int i2c_allocate_adapter_id(struct i2c_adapter *adap)
1521 {
1522 	int id, start, end;
1523 
1524 	if (adap->nr == -1) {
1525 		start = __i2c_first_dynamic_bus_num;
1526 		end = 0;
1527 	} else {
1528 		start = adap->nr;
1529 		end = adap->nr + 1;
1530 	}
1531 
1532 	mutex_lock(&core_lock);
1533 	id = idr_alloc(&i2c_adapter_idr, NULL, start, end, GFP_KERNEL);
1534 	mutex_unlock(&core_lock);
1535 	if (id < 0) {
1536 		if (adap->nr != -1 && id == -ENOSPC)
1537 			id = -EBUSY;
1538 		pr_err("adapter '%s': failed to allocate id: %d\n", adap->name, id);
1539 		return id;
1540 	}
1541 
1542 	adap->nr = id;
1543 
1544 	return 0;
1545 }
1546 
i2c_register_adapter(struct i2c_adapter * adap)1547 static int i2c_register_adapter(struct i2c_adapter *adap)
1548 {
1549 	int res;
1550 
1551 	/* Can't register until after driver model init */
1552 	if (WARN_ON(!is_registered))
1553 		return -EAGAIN;
1554 
1555 	/* Sanity checks */
1556 	if (WARN(!adap->name[0], "i2c adapter has no name"))
1557 		return -EINVAL;
1558 
1559 	if (!adap->algo) {
1560 		pr_err("adapter '%s': no algo supplied!\n", adap->name);
1561 		return -EINVAL;
1562 	}
1563 
1564 	if (!adap->lock_ops)
1565 		adap->lock_ops = &i2c_adapter_lock_ops;
1566 
1567 	adap->locked_flags = 0;
1568 	rt_mutex_init(&adap->bus_lock);
1569 	rt_mutex_init(&adap->mux_lock);
1570 	mutex_init(&adap->userspace_clients_lock);
1571 	INIT_LIST_HEAD(&adap->userspace_clients);
1572 
1573 	/* Set default timeout to 1 second if not already set */
1574 	if (adap->timeout == 0)
1575 		adap->timeout = HZ;
1576 
1577 	/* register soft irqs for Host Notify */
1578 	res = i2c_setup_host_notify_irq_domain(adap);
1579 	if (res) {
1580 		pr_err("adapter '%s': can't create Host Notify IRQs (%d)\n",
1581 		       adap->name, res);
1582 		return res;
1583 	}
1584 
1585 	res = i2c_allocate_adapter_id(adap);
1586 	if (res)
1587 		goto err_remove_irq_domain;
1588 
1589 	res = dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1590 	if (res)
1591 		goto err_free_id;
1592 
1593 	adap->dev.bus = &i2c_bus_type;
1594 	adap->dev.type = &i2c_adapter_type;
1595 	device_initialize(&adap->dev);
1596 
1597 	res = i2c_init_recovery(adap);
1598 	if (res == -EPROBE_DEFER)
1599 		goto err_put_adap;
1600 
1601 	/*
1602 	 * This adapter can be used as a parent immediately after device_add(),
1603 	 * setup runtime-pm (especially ignore-children) before hand.
1604 	 */
1605 	device_enable_async_suspend(&adap->dev);
1606 	pm_runtime_no_callbacks(&adap->dev);
1607 	pm_suspend_ignore_children(&adap->dev, true);
1608 	pm_runtime_enable(&adap->dev);
1609 
1610 	adap->debugfs = debugfs_create_dir(dev_name(&adap->dev), i2c_debugfs_root);
1611 
1612 	mutex_lock(&core_lock);
1613 	idr_replace(&i2c_adapter_idr, adap, adap->nr);
1614 	mutex_unlock(&core_lock);
1615 
1616 	res = device_add(&adap->dev);
1617 	if (res) {
1618 		pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
1619 		goto err_replace_id;
1620 	}
1621 
1622 	res = i2c_setup_smbus_alert(adap);
1623 	if (res)
1624 		goto err_deregister_clients;
1625 
1626 	dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1627 
1628 	/* create pre-declared device nodes */
1629 	of_i2c_register_devices(adap);
1630 	i2c_acpi_install_space_handler(adap);
1631 	i2c_acpi_register_devices(adap);
1632 
1633 	if (adap->nr < __i2c_first_dynamic_bus_num)
1634 		i2c_scan_static_board_info(adap);
1635 
1636 	/* Notify drivers */
1637 	mutex_lock(&core_lock);
1638 	bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1639 	mutex_unlock(&core_lock);
1640 
1641 	return 0;
1642 
1643 err_deregister_clients:
1644 	i2c_deregister_clients(adap);
1645 	device_del(&adap->dev);
1646 err_replace_id:
1647 	mutex_lock(&core_lock);
1648 	idr_replace(&i2c_adapter_idr, NULL, adap->nr);
1649 	mutex_unlock(&core_lock);
1650 	debugfs_remove_recursive(adap->debugfs);
1651 	pm_runtime_disable(&adap->dev);
1652 err_put_adap:
1653 	init_completion(&adap->dev_released);
1654 	put_device(&adap->dev);
1655 	wait_for_completion(&adap->dev_released);
1656 err_free_id:
1657 	mutex_lock(&core_lock);
1658 	idr_remove(&i2c_adapter_idr, adap->nr);
1659 	mutex_unlock(&core_lock);
1660 err_remove_irq_domain:
1661 	i2c_host_notify_irq_teardown(adap);
1662 
1663 	return res;
1664 }
1665 
1666 /**
1667  * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1668  * @adapter: the adapter to add
1669  * Context: can sleep
1670  *
1671  * This routine is used to declare an I2C adapter when its bus number
1672  * doesn't matter or when its bus number is specified by an dt alias.
1673  * Examples of bases when the bus number doesn't matter: I2C adapters
1674  * dynamically added by USB links or PCI plugin cards.
1675  *
1676  * When this returns zero, a new bus number was allocated and stored
1677  * in adap->nr, and the specified adapter became available for clients.
1678  * Otherwise, a negative errno value is returned.
1679  */
i2c_add_adapter(struct i2c_adapter * adapter)1680 int i2c_add_adapter(struct i2c_adapter *adapter)
1681 {
1682 	struct device *dev = &adapter->dev;
1683 	int id;
1684 
1685 	id = of_alias_get_id(dev->of_node, "i2c");
1686 	if (id < 0)
1687 		id = -1;
1688 
1689 	adapter->nr = id;
1690 
1691 	return i2c_register_adapter(adapter);
1692 }
1693 EXPORT_SYMBOL(i2c_add_adapter);
1694 
1695 /**
1696  * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1697  * @adap: the adapter to register (with adap->nr initialized)
1698  * Context: can sleep
1699  *
1700  * This routine is used to declare an I2C adapter when its bus number
1701  * matters.  For example, use it for I2C adapters from system-on-chip CPUs,
1702  * or otherwise built in to the system's mainboard, and where i2c_board_info
1703  * is used to properly configure I2C devices.
1704  *
1705  * If the requested bus number is set to -1, then this function will behave
1706  * identically to i2c_add_adapter, and will dynamically assign a bus number.
1707  *
1708  * If no devices have pre-been declared for this bus, then be sure to
1709  * register the adapter before any dynamically allocated ones.  Otherwise
1710  * the required bus ID may not be available.
1711  *
1712  * When this returns zero, the specified adapter became available for
1713  * clients using the bus number provided in adap->nr.  Also, the table
1714  * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1715  * and the appropriate driver model device nodes are created.  Otherwise, a
1716  * negative errno value is returned.
1717  */
i2c_add_numbered_adapter(struct i2c_adapter * adap)1718 int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1719 {
1720 	if (adap->nr == -1) /* -1 means dynamically assign bus id */
1721 		return i2c_add_adapter(adap);
1722 
1723 	return i2c_register_adapter(adap);
1724 }
1725 EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1726 
i2c_do_del_adapter(struct i2c_driver * driver,struct i2c_adapter * adapter)1727 static void i2c_do_del_adapter(struct i2c_driver *driver,
1728 			      struct i2c_adapter *adapter)
1729 {
1730 	struct i2c_client *client, *_n;
1731 
1732 	/* Remove the devices we created ourselves as the result of hardware
1733 	 * probing (using a driver's detect method) */
1734 	list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1735 		if (client->adapter == adapter) {
1736 			dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1737 				client->name, client->addr);
1738 			list_del(&client->detected);
1739 			i2c_unregister_device(client);
1740 		}
1741 	}
1742 }
1743 
__unregister_client(struct device * dev,void * dummy)1744 static int __unregister_client(struct device *dev, void *dummy)
1745 {
1746 	struct i2c_client *client = i2c_verify_client(dev);
1747 	if (client && strcmp(client->name, "dummy"))
1748 		i2c_unregister_device(client);
1749 	return 0;
1750 }
1751 
__unregister_dummy(struct device * dev,void * dummy)1752 static int __unregister_dummy(struct device *dev, void *dummy)
1753 {
1754 	struct i2c_client *client = i2c_verify_client(dev);
1755 	i2c_unregister_device(client);
1756 	return 0;
1757 }
1758 
__process_removed_adapter(struct device_driver * d,void * data)1759 static int __process_removed_adapter(struct device_driver *d, void *data)
1760 {
1761 	i2c_do_del_adapter(to_i2c_driver(d), data);
1762 	return 0;
1763 }
1764 
i2c_deregister_clients(struct i2c_adapter * adap)1765 static void i2c_deregister_clients(struct i2c_adapter *adap)
1766 {
1767 	struct i2c_client *client, *next;
1768 
1769 	/* Tell drivers about this removal */
1770 	mutex_lock(&core_lock);
1771 	bus_for_each_drv(&i2c_bus_type, NULL, adap,
1772 			       __process_removed_adapter);
1773 	mutex_unlock(&core_lock);
1774 
1775 	/* Remove devices instantiated from sysfs */
1776 	mutex_lock_nested(&adap->userspace_clients_lock,
1777 			  i2c_adapter_depth(adap));
1778 	list_for_each_entry_safe(client, next, &adap->userspace_clients,
1779 				 detected) {
1780 		dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1781 			client->addr);
1782 		list_del(&client->detected);
1783 		i2c_unregister_device(client);
1784 	}
1785 	mutex_unlock(&adap->userspace_clients_lock);
1786 
1787 	/* Detach any active clients. This can't fail, thus we do not
1788 	 * check the returned value. This is a two-pass process, because
1789 	 * we can't remove the dummy devices during the first pass: they
1790 	 * could have been instantiated by real devices wishing to clean
1791 	 * them up properly, so we give them a chance to do that first. */
1792 	device_for_each_child(&adap->dev, NULL, __unregister_client);
1793 	device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1794 }
1795 
1796 /**
1797  * i2c_del_adapter - unregister I2C adapter
1798  * @adap: the adapter being unregistered
1799  * Context: can sleep
1800  *
1801  * This unregisters an I2C adapter which was previously registered
1802  * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1803  */
i2c_del_adapter(struct i2c_adapter * adap)1804 void i2c_del_adapter(struct i2c_adapter *adap)
1805 {
1806 	struct i2c_adapter *found;
1807 
1808 	/* First make sure that this adapter was ever added */
1809 	mutex_lock(&core_lock);
1810 	found = idr_find(&i2c_adapter_idr, adap->nr);
1811 	if (found == adap)
1812 		idr_replace(&i2c_adapter_idr, NULL, adap->nr);
1813 	mutex_unlock(&core_lock);
1814 	if (found != adap) {
1815 		pr_debug("attempting to delete unregistered adapter [%s]\n", adap->name);
1816 		return;
1817 	}
1818 
1819 	/*
1820 	 * This drains any in-flight writers, so all
1821 	 * clients will be caught by i2c_deregister_clients().
1822 	 */
1823 	device_remove_file(&adap->dev, &dev_attr_new_device);
1824 
1825 	i2c_acpi_remove_space_handler(adap);
1826 
1827 	i2c_deregister_clients(adap);
1828 
1829 	/* device name is gone after device_unregister */
1830 	dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1831 
1832 	pm_runtime_disable(&adap->dev);
1833 
1834 	i2c_host_notify_irq_teardown(adap);
1835 
1836 	debugfs_remove_recursive(adap->debugfs);
1837 
1838 	/* wait until all references to the device are gone
1839 	 *
1840 	 * FIXME: This is old code and should ideally be replaced by an
1841 	 * alternative which results in decoupling the lifetime of the struct
1842 	 * device from the i2c_adapter, like spi or netdev do. Any solution
1843 	 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
1844 	 */
1845 	init_completion(&adap->dev_released);
1846 	device_unregister(&adap->dev);
1847 	wait_for_completion(&adap->dev_released);
1848 
1849 	/* free bus id */
1850 	mutex_lock(&core_lock);
1851 	idr_remove(&i2c_adapter_idr, adap->nr);
1852 	mutex_unlock(&core_lock);
1853 
1854 	/* Clear the device structure in case this adapter is ever going to be
1855 	   added again */
1856 	memset(&adap->dev, 0, sizeof(adap->dev));
1857 }
1858 EXPORT_SYMBOL(i2c_del_adapter);
1859 
devm_i2c_del_adapter(void * adapter)1860 static void devm_i2c_del_adapter(void *adapter)
1861 {
1862 	i2c_del_adapter(adapter);
1863 }
1864 
1865 /**
1866  * devm_i2c_add_adapter - device-managed variant of i2c_add_adapter()
1867  * @dev: managing device for adding this I2C adapter
1868  * @adapter: the adapter to add
1869  * Context: can sleep
1870  *
1871  * Add adapter with dynamic bus number, same with i2c_add_adapter()
1872  * but the adapter will be auto deleted on driver detach.
1873  */
devm_i2c_add_adapter(struct device * dev,struct i2c_adapter * adapter)1874 int devm_i2c_add_adapter(struct device *dev, struct i2c_adapter *adapter)
1875 {
1876 	int ret;
1877 
1878 	ret = i2c_add_adapter(adapter);
1879 	if (ret)
1880 		return ret;
1881 
1882 	return devm_add_action_or_reset(dev, devm_i2c_del_adapter, adapter);
1883 }
1884 EXPORT_SYMBOL_GPL(devm_i2c_add_adapter);
1885 
i2c_dev_or_parent_fwnode_match(struct device * dev,const void * data)1886 static int i2c_dev_or_parent_fwnode_match(struct device *dev, const void *data)
1887 {
1888 	if (device_match_fwnode(dev, data))
1889 		return 1;
1890 
1891 	if (dev->parent && device_match_fwnode(dev->parent, data))
1892 		return 1;
1893 
1894 	return 0;
1895 }
1896 
1897 /**
1898  * i2c_find_adapter_by_fwnode() - find an i2c_adapter for the fwnode
1899  * @fwnode: &struct fwnode_handle corresponding to the &struct i2c_adapter
1900  *
1901  * Look up and return the &struct i2c_adapter corresponding to the @fwnode.
1902  * If no adapter can be found, or @fwnode is NULL, this returns NULL.
1903  *
1904  * The user must call put_device(&adapter->dev) once done with the i2c adapter.
1905  */
i2c_find_adapter_by_fwnode(struct fwnode_handle * fwnode)1906 struct i2c_adapter *i2c_find_adapter_by_fwnode(struct fwnode_handle *fwnode)
1907 {
1908 	struct i2c_adapter *adapter;
1909 	struct device *dev;
1910 
1911 	if (IS_ERR_OR_NULL(fwnode))
1912 		return NULL;
1913 
1914 	dev = bus_find_device(&i2c_bus_type, NULL, fwnode,
1915 			      i2c_dev_or_parent_fwnode_match);
1916 	if (!dev)
1917 		return NULL;
1918 
1919 	adapter = i2c_verify_adapter(dev);
1920 	if (!adapter)
1921 		put_device(dev);
1922 
1923 	return adapter;
1924 }
1925 EXPORT_SYMBOL(i2c_find_adapter_by_fwnode);
1926 
1927 /**
1928  * i2c_get_adapter_by_fwnode() - find an i2c_adapter for the fwnode
1929  * @fwnode: &struct fwnode_handle corresponding to the &struct i2c_adapter
1930  *
1931  * Look up and return the &struct i2c_adapter corresponding to the @fwnode,
1932  * and increment the adapter module's use count. If no adapter can be found,
1933  * or @fwnode is NULL, this returns NULL.
1934  *
1935  * The user must call i2c_put_adapter(adapter) once done with the i2c adapter.
1936  * Note that this is different from i2c_find_adapter_by_node().
1937  */
i2c_get_adapter_by_fwnode(struct fwnode_handle * fwnode)1938 struct i2c_adapter *i2c_get_adapter_by_fwnode(struct fwnode_handle *fwnode)
1939 {
1940 	struct i2c_adapter *adapter;
1941 
1942 	adapter = i2c_find_adapter_by_fwnode(fwnode);
1943 	if (!adapter)
1944 		return NULL;
1945 
1946 	if (!try_module_get(adapter->owner)) {
1947 		put_device(&adapter->dev);
1948 		adapter = NULL;
1949 	}
1950 
1951 	return adapter;
1952 }
1953 EXPORT_SYMBOL(i2c_get_adapter_by_fwnode);
1954 
i2c_parse_timing(struct device * dev,char * prop_name,u32 * cur_val_p,u32 def_val,bool use_def)1955 static void i2c_parse_timing(struct device *dev, char *prop_name, u32 *cur_val_p,
1956 			    u32 def_val, bool use_def)
1957 {
1958 	int ret;
1959 
1960 	ret = device_property_read_u32(dev, prop_name, cur_val_p);
1961 	if (ret && use_def)
1962 		*cur_val_p = def_val;
1963 
1964 	dev_dbg(dev, "%s: %u\n", prop_name, *cur_val_p);
1965 }
1966 
1967 /**
1968  * i2c_parse_fw_timings - get I2C related timing parameters from firmware
1969  * @dev: The device to scan for I2C timing properties
1970  * @t: the i2c_timings struct to be filled with values
1971  * @use_defaults: bool to use sane defaults derived from the I2C specification
1972  *		  when properties are not found, otherwise don't update
1973  *
1974  * Scan the device for the generic I2C properties describing timing parameters
1975  * for the signal and fill the given struct with the results. If a property was
1976  * not found and use_defaults was true, then maximum timings are assumed which
1977  * are derived from the I2C specification. If use_defaults is not used, the
1978  * results will be as before, so drivers can apply their own defaults before
1979  * calling this helper. The latter is mainly intended for avoiding regressions
1980  * of existing drivers which want to switch to this function. New drivers
1981  * almost always should use the defaults.
1982  */
i2c_parse_fw_timings(struct device * dev,struct i2c_timings * t,bool use_defaults)1983 void i2c_parse_fw_timings(struct device *dev, struct i2c_timings *t, bool use_defaults)
1984 {
1985 	bool u = use_defaults;
1986 	u32 d;
1987 
1988 	i2c_parse_timing(dev, "clock-frequency", &t->bus_freq_hz,
1989 			 I2C_MAX_STANDARD_MODE_FREQ, u);
1990 
1991 	d = t->bus_freq_hz <= I2C_MAX_STANDARD_MODE_FREQ ? 1000 :
1992 	    t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ ? 300 : 120;
1993 	i2c_parse_timing(dev, "i2c-scl-rising-time-ns", &t->scl_rise_ns, d, u);
1994 
1995 	d = t->bus_freq_hz <= I2C_MAX_FAST_MODE_FREQ ? 300 : 120;
1996 	i2c_parse_timing(dev, "i2c-scl-falling-time-ns", &t->scl_fall_ns, d, u);
1997 
1998 	i2c_parse_timing(dev, "i2c-scl-internal-delay-ns",
1999 			 &t->scl_int_delay_ns, 0, u);
2000 	i2c_parse_timing(dev, "i2c-sda-falling-time-ns", &t->sda_fall_ns,
2001 			 t->scl_fall_ns, u);
2002 	i2c_parse_timing(dev, "i2c-sda-hold-time-ns", &t->sda_hold_ns, 0, u);
2003 	i2c_parse_timing(dev, "i2c-digital-filter-width-ns",
2004 			 &t->digital_filter_width_ns, 0, u);
2005 	i2c_parse_timing(dev, "i2c-analog-filter-cutoff-frequency",
2006 			 &t->analog_filter_cutoff_freq_hz, 0, u);
2007 }
2008 EXPORT_SYMBOL_GPL(i2c_parse_fw_timings);
2009 
2010 /* ------------------------------------------------------------------------- */
2011 
i2c_for_each_dev(void * data,int (* fn)(struct device * dev,void * data))2012 int i2c_for_each_dev(void *data, int (*fn)(struct device *dev, void *data))
2013 {
2014 	int res;
2015 
2016 	mutex_lock(&core_lock);
2017 	res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
2018 	mutex_unlock(&core_lock);
2019 
2020 	return res;
2021 }
2022 EXPORT_SYMBOL_GPL(i2c_for_each_dev);
2023 
__process_new_driver(struct device * dev,void * data)2024 static int __process_new_driver(struct device *dev, void *data)
2025 {
2026 	if (dev->type != &i2c_adapter_type)
2027 		return 0;
2028 	return i2c_do_add_adapter(data, to_i2c_adapter(dev));
2029 }
2030 
2031 /*
2032  * An i2c_driver is used with one or more i2c_client (device) nodes to access
2033  * i2c slave chips, on a bus instance associated with some i2c_adapter.
2034  */
2035 
i2c_register_driver(struct module * owner,struct i2c_driver * driver)2036 int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
2037 {
2038 	int res;
2039 
2040 	/* Can't register until after driver model init */
2041 	if (WARN_ON(!is_registered))
2042 		return -EAGAIN;
2043 
2044 	/* add the driver to the list of i2c drivers in the driver core */
2045 	driver->driver.owner = owner;
2046 	driver->driver.bus = &i2c_bus_type;
2047 	INIT_LIST_HEAD(&driver->clients);
2048 
2049 	/* When registration returns, the driver core
2050 	 * will have called probe() for all matching-but-unbound devices.
2051 	 */
2052 	res = driver_register(&driver->driver);
2053 	if (res)
2054 		return res;
2055 
2056 	pr_debug("driver [%s] registered\n", driver->driver.name);
2057 
2058 	/* Walk the adapters that are already present */
2059 	i2c_for_each_dev(driver, __process_new_driver);
2060 
2061 	return 0;
2062 }
2063 EXPORT_SYMBOL(i2c_register_driver);
2064 
__process_removed_driver(struct device * dev,void * data)2065 static int __process_removed_driver(struct device *dev, void *data)
2066 {
2067 	if (dev->type == &i2c_adapter_type)
2068 		i2c_do_del_adapter(data, to_i2c_adapter(dev));
2069 	return 0;
2070 }
2071 
2072 /**
2073  * i2c_del_driver - unregister I2C driver
2074  * @driver: the driver being unregistered
2075  * Context: can sleep
2076  */
i2c_del_driver(struct i2c_driver * driver)2077 void i2c_del_driver(struct i2c_driver *driver)
2078 {
2079 	i2c_for_each_dev(driver, __process_removed_driver);
2080 
2081 	driver_unregister(&driver->driver);
2082 	pr_debug("driver [%s] unregistered\n", driver->driver.name);
2083 }
2084 EXPORT_SYMBOL(i2c_del_driver);
2085 
2086 /* ------------------------------------------------------------------------- */
2087 
2088 struct i2c_cmd_arg {
2089 	unsigned	cmd;
2090 	void		*arg;
2091 };
2092 
i2c_cmd(struct device * dev,void * _arg)2093 static int i2c_cmd(struct device *dev, void *_arg)
2094 {
2095 	struct i2c_client	*client = i2c_verify_client(dev);
2096 	struct i2c_cmd_arg	*arg = _arg;
2097 	struct i2c_driver	*driver;
2098 
2099 	if (!client || !client->dev.driver)
2100 		return 0;
2101 
2102 	driver = to_i2c_driver(client->dev.driver);
2103 	if (driver->command)
2104 		driver->command(client, arg->cmd, arg->arg);
2105 	return 0;
2106 }
2107 
i2c_clients_command(struct i2c_adapter * adap,unsigned int cmd,void * arg)2108 void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
2109 {
2110 	struct i2c_cmd_arg	cmd_arg;
2111 
2112 	cmd_arg.cmd = cmd;
2113 	cmd_arg.arg = arg;
2114 	device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
2115 }
2116 EXPORT_SYMBOL(i2c_clients_command);
2117 
i2c_init(void)2118 static int __init i2c_init(void)
2119 {
2120 	int retval;
2121 
2122 	retval = of_alias_get_highest_id("i2c");
2123 
2124 	down_write(&__i2c_board_lock);
2125 	if (retval >= __i2c_first_dynamic_bus_num)
2126 		__i2c_first_dynamic_bus_num = retval + 1;
2127 	up_write(&__i2c_board_lock);
2128 
2129 	retval = bus_register(&i2c_bus_type);
2130 	if (retval)
2131 		return retval;
2132 
2133 	is_registered = true;
2134 
2135 	i2c_debugfs_root = debugfs_create_dir("i2c", NULL);
2136 
2137 	retval = i2c_add_driver(&dummy_driver);
2138 	if (retval)
2139 		goto class_err;
2140 
2141 	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2142 		WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
2143 	if (IS_ENABLED(CONFIG_ACPI))
2144 		WARN_ON(acpi_reconfig_notifier_register(&i2c_acpi_notifier));
2145 
2146 	return 0;
2147 
2148 class_err:
2149 	is_registered = false;
2150 	bus_unregister(&i2c_bus_type);
2151 	return retval;
2152 }
2153 
i2c_exit(void)2154 static void __exit i2c_exit(void)
2155 {
2156 	if (IS_ENABLED(CONFIG_ACPI))
2157 		WARN_ON(acpi_reconfig_notifier_unregister(&i2c_acpi_notifier));
2158 	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2159 		WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
2160 	i2c_del_driver(&dummy_driver);
2161 	debugfs_remove_recursive(i2c_debugfs_root);
2162 	bus_unregister(&i2c_bus_type);
2163 	tracepoint_synchronize_unregister();
2164 }
2165 
2166 /* We must initialize early, because some subsystems register i2c drivers
2167  * in subsys_initcall() code, but are linked (and initialized) before i2c.
2168  */
2169 postcore_initcall(i2c_init);
2170 module_exit(i2c_exit);
2171 
2172 /* ----------------------------------------------------
2173  * the functional interface to the i2c busses.
2174  * ----------------------------------------------------
2175  */
2176 
2177 /* Check if val is exceeding the quirk IFF quirk is non 0 */
2178 #define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2179 
i2c_quirk_error(struct i2c_adapter * adap,struct i2c_msg * msg,char * err_msg)2180 static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2181 {
2182 	dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2183 			    err_msg, msg->addr, msg->len,
2184 			    str_read_write(msg->flags & I2C_M_RD));
2185 	return -EOPNOTSUPP;
2186 }
2187 
i2c_check_for_quirks(struct i2c_adapter * adap,struct i2c_msg * msgs,int num)2188 static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2189 {
2190 	const struct i2c_adapter_quirks *q = adap->quirks;
2191 	int max_num = q->max_num_msgs, i;
2192 	bool do_len_check = true;
2193 
2194 	if (q->flags & I2C_AQ_COMB) {
2195 		max_num = 2;
2196 
2197 		/* special checks for combined messages */
2198 		if (num == 2) {
2199 			if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2200 				return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2201 
2202 			if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2203 				return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2204 
2205 			if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2206 				return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2207 
2208 			if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2209 				return i2c_quirk_error(adap, &msgs[0], "msg too long");
2210 
2211 			if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2212 				return i2c_quirk_error(adap, &msgs[1], "msg too long");
2213 
2214 			do_len_check = false;
2215 		}
2216 	}
2217 
2218 	if (i2c_quirk_exceeded(num, max_num))
2219 		return i2c_quirk_error(adap, &msgs[0], "too many messages");
2220 
2221 	for (i = 0; i < num; i++) {
2222 		u16 len = msgs[i].len;
2223 
2224 		if (msgs[i].flags & I2C_M_RD) {
2225 			if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2226 				return i2c_quirk_error(adap, &msgs[i], "msg too long");
2227 
2228 			if (q->flags & I2C_AQ_NO_ZERO_LEN_READ && len == 0)
2229 				return i2c_quirk_error(adap, &msgs[i], "no zero length");
2230 		} else {
2231 			if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2232 				return i2c_quirk_error(adap, &msgs[i], "msg too long");
2233 
2234 			if (q->flags & I2C_AQ_NO_ZERO_LEN_WRITE && len == 0)
2235 				return i2c_quirk_error(adap, &msgs[i], "no zero length");
2236 		}
2237 	}
2238 
2239 	return 0;
2240 }
2241 
2242 /**
2243  * __i2c_transfer - unlocked flavor of i2c_transfer
2244  * @adap: Handle to I2C bus
2245  * @msgs: One or more messages to execute before STOP is issued to
2246  *	terminate the operation; each message begins with a START.
2247  * @num: Number of messages to be executed.
2248  *
2249  * Returns negative errno, else the number of messages executed.
2250  *
2251  * Adapter lock must be held when calling this function. No debug logging
2252  * takes place.
2253  */
__i2c_transfer(struct i2c_adapter * adap,struct i2c_msg * msgs,int num)2254 int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2255 {
2256 	unsigned long orig_jiffies;
2257 	int ret, try;
2258 
2259 	if (!adap->algo->master_xfer) {
2260 		dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2261 		return -EOPNOTSUPP;
2262 	}
2263 
2264 	if (WARN_ON(!msgs || num < 1))
2265 		return -EINVAL;
2266 
2267 	ret = __i2c_check_suspended(adap);
2268 	if (ret)
2269 		return ret;
2270 
2271 	if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2272 		return -EOPNOTSUPP;
2273 
2274 	/*
2275 	 * i2c_trace_msg_key gets enabled when tracepoint i2c_transfer gets
2276 	 * enabled.  This is an efficient way of keeping the for-loop from
2277 	 * being executed when not needed.
2278 	 */
2279 	if (static_branch_unlikely(&i2c_trace_msg_key)) {
2280 		int i;
2281 		for (i = 0; i < num; i++)
2282 			if (msgs[i].flags & I2C_M_RD)
2283 				trace_i2c_read(adap, &msgs[i], i);
2284 			else
2285 				trace_i2c_write(adap, &msgs[i], i);
2286 	}
2287 
2288 	/* Retry automatically on arbitration loss */
2289 	orig_jiffies = jiffies;
2290 	for (ret = 0, try = 0; try <= adap->retries; try++) {
2291 		if (i2c_in_atomic_xfer_mode() && adap->algo->master_xfer_atomic)
2292 			ret = adap->algo->master_xfer_atomic(adap, msgs, num);
2293 		else
2294 			ret = adap->algo->master_xfer(adap, msgs, num);
2295 
2296 		if (ret != -EAGAIN)
2297 			break;
2298 		if (time_after(jiffies, orig_jiffies + adap->timeout))
2299 			break;
2300 	}
2301 
2302 	if (static_branch_unlikely(&i2c_trace_msg_key)) {
2303 		int i;
2304 		for (i = 0; i < ret; i++)
2305 			if (msgs[i].flags & I2C_M_RD)
2306 				trace_i2c_reply(adap, &msgs[i], i);
2307 		trace_i2c_result(adap, num, ret);
2308 	}
2309 
2310 	return ret;
2311 }
2312 EXPORT_SYMBOL(__i2c_transfer);
2313 
2314 /**
2315  * i2c_transfer - execute a single or combined I2C message
2316  * @adap: Handle to I2C bus
2317  * @msgs: One or more messages to execute before STOP is issued to
2318  *	terminate the operation; each message begins with a START.
2319  * @num: Number of messages to be executed.
2320  *
2321  * Returns negative errno, else the number of messages executed.
2322  *
2323  * Note that there is no requirement that each message be sent to
2324  * the same slave address, although that is the most common model.
2325  */
i2c_transfer(struct i2c_adapter * adap,struct i2c_msg * msgs,int num)2326 int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2327 {
2328 	int ret;
2329 
2330 	/* REVISIT the fault reporting model here is weak:
2331 	 *
2332 	 *  - When we get an error after receiving N bytes from a slave,
2333 	 *    there is no way to report "N".
2334 	 *
2335 	 *  - When we get a NAK after transmitting N bytes to a slave,
2336 	 *    there is no way to report "N" ... or to let the master
2337 	 *    continue executing the rest of this combined message, if
2338 	 *    that's the appropriate response.
2339 	 *
2340 	 *  - When for example "num" is two and we successfully complete
2341 	 *    the first message but get an error part way through the
2342 	 *    second, it's unclear whether that should be reported as
2343 	 *    one (discarding status on the second message) or errno
2344 	 *    (discarding status on the first one).
2345 	 */
2346 	ret = __i2c_lock_bus_helper(adap);
2347 	if (ret)
2348 		return ret;
2349 
2350 	ret = __i2c_transfer(adap, msgs, num);
2351 	i2c_unlock_bus(adap, I2C_LOCK_SEGMENT);
2352 
2353 	return ret;
2354 }
2355 EXPORT_SYMBOL(i2c_transfer);
2356 
2357 /**
2358  * i2c_transfer_buffer_flags - issue a single I2C message transferring data
2359  *			       to/from a buffer
2360  * @client: Handle to slave device
2361  * @buf: Where the data is stored
2362  * @count: How many bytes to transfer, must be less than 64k since msg.len is u16
2363  * @flags: The flags to be used for the message, e.g. I2C_M_RD for reads
2364  *
2365  * Returns negative errno, or else the number of bytes transferred.
2366  */
i2c_transfer_buffer_flags(const struct i2c_client * client,char * buf,int count,u16 flags)2367 int i2c_transfer_buffer_flags(const struct i2c_client *client, char *buf,
2368 			      int count, u16 flags)
2369 {
2370 	int ret;
2371 	struct i2c_msg msg = {
2372 		.addr = client->addr,
2373 		.flags = flags | (client->flags & I2C_M_TEN),
2374 		.len = count,
2375 		.buf = buf,
2376 	};
2377 
2378 	ret = i2c_transfer(client->adapter, &msg, 1);
2379 
2380 	/*
2381 	 * If everything went ok (i.e. 1 msg transferred), return #bytes
2382 	 * transferred, else error code.
2383 	 */
2384 	return (ret == 1) ? count : ret;
2385 }
2386 EXPORT_SYMBOL(i2c_transfer_buffer_flags);
2387 
2388 /**
2389  * i2c_get_device_id - get manufacturer, part id and die revision of a device
2390  * @client: The device to query
2391  * @id: The queried information
2392  *
2393  * Returns negative errno on error, zero on success.
2394  */
i2c_get_device_id(const struct i2c_client * client,struct i2c_device_identity * id)2395 int i2c_get_device_id(const struct i2c_client *client,
2396 		      struct i2c_device_identity *id)
2397 {
2398 	struct i2c_adapter *adap = client->adapter;
2399 	union i2c_smbus_data raw_id;
2400 	int ret;
2401 
2402 	if (!i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
2403 		return -EOPNOTSUPP;
2404 
2405 	raw_id.block[0] = 3;
2406 	ret = i2c_smbus_xfer(adap, I2C_ADDR_DEVICE_ID, 0,
2407 			     I2C_SMBUS_READ, client->addr << 1,
2408 			     I2C_SMBUS_I2C_BLOCK_DATA, &raw_id);
2409 	if (ret)
2410 		return ret;
2411 
2412 	id->manufacturer_id = (raw_id.block[1] << 4) | (raw_id.block[2] >> 4);
2413 	id->part_id = ((raw_id.block[2] & 0xf) << 5) | (raw_id.block[3] >> 3);
2414 	id->die_revision = raw_id.block[3] & 0x7;
2415 	return 0;
2416 }
2417 EXPORT_SYMBOL_GPL(i2c_get_device_id);
2418 
2419 /**
2420  * i2c_client_get_device_id - get the driver match table entry of a device
2421  * @client: the device to query. The device must be bound to a driver
2422  *
2423  * Returns a pointer to the matching entry if found, NULL otherwise.
2424  */
i2c_client_get_device_id(const struct i2c_client * client)2425 const struct i2c_device_id *i2c_client_get_device_id(const struct i2c_client *client)
2426 {
2427 	const struct i2c_driver *drv = to_i2c_driver(client->dev.driver);
2428 
2429 	return i2c_match_id(drv->id_table, client);
2430 }
2431 EXPORT_SYMBOL_GPL(i2c_client_get_device_id);
2432 
2433 /* ----------------------------------------------------
2434  * the i2c address scanning function
2435  * Will not work for 10-bit addresses!
2436  * ----------------------------------------------------
2437  */
2438 
2439 /*
2440  * Legacy default probe function, mostly relevant for SMBus. The default
2441  * probe method is a quick write, but it is known to corrupt the 24RF08
2442  * EEPROMs due to a state machine bug, and could also irreversibly
2443  * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2444  * we use a short byte read instead. Also, some bus drivers don't implement
2445  * quick write, so we fallback to a byte read in that case too.
2446  * On x86, there is another special case for FSC hardware monitoring chips,
2447  * which want regular byte reads (address 0x73.) Fortunately, these are the
2448  * only known chips using this I2C address on PC hardware.
2449  * Returns 1 if probe succeeded, 0 if not.
2450  */
i2c_default_probe(struct i2c_adapter * adap,unsigned short addr)2451 static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2452 {
2453 	int err;
2454 	union i2c_smbus_data dummy;
2455 
2456 #ifdef CONFIG_X86
2457 	if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2458 	 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2459 		err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2460 				     I2C_SMBUS_BYTE_DATA, &dummy);
2461 	else
2462 #endif
2463 	if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2464 	 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2465 		err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2466 				     I2C_SMBUS_QUICK, NULL);
2467 	else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2468 		err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2469 				     I2C_SMBUS_BYTE, &dummy);
2470 	else {
2471 		dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2472 			 addr);
2473 		err = -EOPNOTSUPP;
2474 	}
2475 
2476 	return err >= 0;
2477 }
2478 
i2c_detect_address(struct i2c_client * temp_client,struct i2c_driver * driver)2479 static int i2c_detect_address(struct i2c_client *temp_client,
2480 			      struct i2c_driver *driver)
2481 {
2482 	struct i2c_board_info info;
2483 	struct i2c_adapter *adapter = temp_client->adapter;
2484 	int addr = temp_client->addr;
2485 	int err;
2486 
2487 	/* Make sure the address is valid */
2488 	err = i2c_check_7bit_addr_validity_strict(addr);
2489 	if (err) {
2490 		dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2491 			 addr);
2492 		return err;
2493 	}
2494 
2495 	/* Skip if already in use (7 bit, no need to encode flags) */
2496 	if (i2c_check_addr_busy(adapter, addr))
2497 		return 0;
2498 
2499 	/* Make sure there is something at this address */
2500 	if (!i2c_default_probe(adapter, addr))
2501 		return 0;
2502 
2503 	/* Finally call the custom detection function */
2504 	memset(&info, 0, sizeof(struct i2c_board_info));
2505 	info.addr = addr;
2506 	err = driver->detect(temp_client, &info);
2507 	if (err) {
2508 		/* -ENODEV is returned if the detection fails. We catch it
2509 		   here as this isn't an error. */
2510 		return err == -ENODEV ? 0 : err;
2511 	}
2512 
2513 	/* Consistency check */
2514 	if (info.type[0] == '\0') {
2515 		dev_err(&adapter->dev,
2516 			"%s detection function provided no name for 0x%x\n",
2517 			driver->driver.name, addr);
2518 	} else {
2519 		struct i2c_client *client;
2520 
2521 		/* Detection succeeded, instantiate the device */
2522 		if (adapter->class & I2C_CLASS_DEPRECATED)
2523 			dev_warn(&adapter->dev,
2524 				"This adapter will soon drop class based instantiation of devices. "
2525 				"Please make sure client 0x%02x gets instantiated by other means. "
2526 				"Check 'Documentation/i2c/instantiating-devices.rst' for details.\n",
2527 				info.addr);
2528 
2529 		dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2530 			info.type, info.addr);
2531 		client = i2c_new_client_device(adapter, &info);
2532 		if (!IS_ERR(client))
2533 			list_add_tail(&client->detected, &driver->clients);
2534 		else
2535 			dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2536 				info.type, info.addr);
2537 	}
2538 	return 0;
2539 }
2540 
i2c_detect(struct i2c_adapter * adapter,struct i2c_driver * driver)2541 static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2542 {
2543 	const unsigned short *address_list;
2544 	struct i2c_client *temp_client;
2545 	int i, err = 0;
2546 
2547 	address_list = driver->address_list;
2548 	if (!driver->detect || !address_list)
2549 		return 0;
2550 
2551 	/* Warn that the adapter lost class based instantiation */
2552 	if (adapter->class == I2C_CLASS_DEPRECATED) {
2553 		dev_dbg(&adapter->dev,
2554 			"This adapter dropped support for I2C classes and won't auto-detect %s devices anymore. "
2555 			"If you need it, check 'Documentation/i2c/instantiating-devices.rst' for alternatives.\n",
2556 			driver->driver.name);
2557 		return 0;
2558 	}
2559 
2560 	/* Stop here if the classes do not match */
2561 	if (!(adapter->class & driver->class))
2562 		return 0;
2563 
2564 	/* Set up a temporary client to help detect callback */
2565 	temp_client = kzalloc_obj(*temp_client);
2566 	if (!temp_client)
2567 		return -ENOMEM;
2568 
2569 	temp_client->adapter = adapter;
2570 
2571 	for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2572 		dev_dbg(&adapter->dev,
2573 			"found normal entry for adapter %d, addr 0x%02x\n",
2574 			i2c_adapter_id(adapter), address_list[i]);
2575 		temp_client->addr = address_list[i];
2576 		err = i2c_detect_address(temp_client, driver);
2577 		if (unlikely(err))
2578 			break;
2579 	}
2580 
2581 	kfree(temp_client);
2582 
2583 	return err;
2584 }
2585 
i2c_probe_func_quick_read(struct i2c_adapter * adap,unsigned short addr)2586 int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2587 {
2588 	return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2589 			      I2C_SMBUS_QUICK, NULL) >= 0;
2590 }
2591 EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2592 
2593 struct i2c_client *
i2c_new_scanned_device(struct i2c_adapter * adap,struct i2c_board_info * info,unsigned short const * addr_list,int (* probe)(struct i2c_adapter * adap,unsigned short addr))2594 i2c_new_scanned_device(struct i2c_adapter *adap,
2595 		       struct i2c_board_info *info,
2596 		       unsigned short const *addr_list,
2597 		       int (*probe)(struct i2c_adapter *adap, unsigned short addr))
2598 {
2599 	int i;
2600 
2601 	if (!probe)
2602 		probe = i2c_default_probe;
2603 
2604 	for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2605 		/* Check address validity */
2606 		if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2607 			dev_warn(&adap->dev, "Invalid 7-bit address 0x%02x\n",
2608 				 addr_list[i]);
2609 			continue;
2610 		}
2611 
2612 		/* Check address availability (7 bit, no need to encode flags) */
2613 		if (i2c_check_addr_busy(adap, addr_list[i])) {
2614 			dev_dbg(&adap->dev,
2615 				"Address 0x%02x already in use, not probing\n",
2616 				addr_list[i]);
2617 			continue;
2618 		}
2619 
2620 		/* Test address responsiveness */
2621 		if (probe(adap, addr_list[i]))
2622 			break;
2623 	}
2624 
2625 	if (addr_list[i] == I2C_CLIENT_END) {
2626 		dev_dbg(&adap->dev, "Probing failed, no device found\n");
2627 		return ERR_PTR(-ENODEV);
2628 	}
2629 
2630 	info->addr = addr_list[i];
2631 	return i2c_new_client_device(adap, info);
2632 }
2633 EXPORT_SYMBOL_GPL(i2c_new_scanned_device);
2634 
i2c_get_adapter(int nr)2635 struct i2c_adapter *i2c_get_adapter(int nr)
2636 {
2637 	struct i2c_adapter *adapter;
2638 
2639 	mutex_lock(&core_lock);
2640 	adapter = idr_find(&i2c_adapter_idr, nr);
2641 	if (!adapter)
2642 		goto exit;
2643 
2644 	if (try_module_get(adapter->owner))
2645 		get_device(&adapter->dev);
2646 	else
2647 		adapter = NULL;
2648 
2649  exit:
2650 	mutex_unlock(&core_lock);
2651 	return adapter;
2652 }
2653 EXPORT_SYMBOL(i2c_get_adapter);
2654 
i2c_put_adapter(struct i2c_adapter * adap)2655 void i2c_put_adapter(struct i2c_adapter *adap)
2656 {
2657 	if (!adap)
2658 		return;
2659 
2660 	module_put(adap->owner);
2661 	/* Should be last, otherwise we risk use-after-free with 'adap' */
2662 	put_device(&adap->dev);
2663 }
2664 EXPORT_SYMBOL(i2c_put_adapter);
2665 
2666 /**
2667  * i2c_get_dma_safe_msg_buf() - get a DMA safe buffer for the given i2c_msg
2668  * @msg: the message to be checked
2669  * @threshold: the minimum number of bytes for which using DMA makes sense.
2670  *	       Should at least be 1.
2671  *
2672  * Return: NULL if a DMA safe buffer was not obtained. Use msg->buf with PIO.
2673  *	   Or a valid pointer to be used with DMA. After use, release it by
2674  *	   calling i2c_put_dma_safe_msg_buf().
2675  *
2676  * This function must only be called from process context!
2677  */
i2c_get_dma_safe_msg_buf(struct i2c_msg * msg,unsigned int threshold)2678 u8 *i2c_get_dma_safe_msg_buf(struct i2c_msg *msg, unsigned int threshold)
2679 {
2680 	/* also skip 0-length msgs for bogus thresholds of 0 */
2681 	if (!threshold)
2682 		pr_debug("DMA buffer for addr=0x%02x with length 0 is bogus\n",
2683 			 msg->addr);
2684 	if (msg->len < threshold || msg->len == 0)
2685 		return NULL;
2686 
2687 	if (msg->flags & I2C_M_DMA_SAFE)
2688 		return msg->buf;
2689 
2690 	pr_debug("using bounce buffer for addr=0x%02x, len=%d\n",
2691 		 msg->addr, msg->len);
2692 
2693 	if (msg->flags & I2C_M_RD)
2694 		return kzalloc(msg->len, GFP_KERNEL);
2695 	else
2696 		return kmemdup(msg->buf, msg->len, GFP_KERNEL);
2697 }
2698 EXPORT_SYMBOL_GPL(i2c_get_dma_safe_msg_buf);
2699 
2700 /**
2701  * i2c_put_dma_safe_msg_buf - release DMA safe buffer and sync with i2c_msg
2702  * @buf: the buffer obtained from i2c_get_dma_safe_msg_buf(). May be NULL.
2703  * @msg: the message which the buffer corresponds to
2704  * @xferred: bool saying if the message was transferred
2705  */
i2c_put_dma_safe_msg_buf(u8 * buf,struct i2c_msg * msg,bool xferred)2706 void i2c_put_dma_safe_msg_buf(u8 *buf, struct i2c_msg *msg, bool xferred)
2707 {
2708 	if (!buf || buf == msg->buf)
2709 		return;
2710 
2711 	if (xferred && msg->flags & I2C_M_RD)
2712 		memcpy(msg->buf, buf, msg->len);
2713 
2714 	kfree(buf);
2715 }
2716 EXPORT_SYMBOL_GPL(i2c_put_dma_safe_msg_buf);
2717 
2718 MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
2719 MODULE_DESCRIPTION("I2C-Bus main module");
2720 MODULE_LICENSE("GPL");
2721