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