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