1/* i2c-core.c - a device driver for the iic-bus interface		     */
2/* ------------------------------------------------------------------------- */
3/*   Copyright (C) 1995-99 Simon G. Vogl
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.			     */
14/* ------------------------------------------------------------------------- */
15
16/* With some changes from Ky��sti M��lkki <kmalkki@cc.hut.fi>.
17   All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
18   SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com> and
19   Jean Delvare <jdelvare@suse.de>
20   Mux support by Rodolfo Giometti <giometti@enneenne.com> and
21   Michael Lawnick <michael.lawnick.ext@nsn.com>
22   OF support is copyright (c) 2008 Jochen Friedrich <jochen@scram.de>
23   (based on a previous patch from Jon Smirl <jonsmirl@gmail.com>) and
24   (c) 2013  Wolfram Sang <wsa@the-dreams.de>
25   I2C ACPI code Copyright (C) 2014 Intel Corp
26   Author: Lan Tianyu <tianyu.lan@intel.com>
27   I2C slave support (c) 2014 by Wolfram Sang <wsa@sang-engineering.com>
28 */
29
30#include <dt-bindings/i2c/i2c.h>
31#include <linux/module.h>
32#include <linux/kernel.h>
33#include <linux/delay.h>
34#include <linux/errno.h>
35#include <linux/gpio.h>
36#include <linux/slab.h>
37#include <linux/i2c.h>
38#include <linux/init.h>
39#include <linux/idr.h>
40#include <linux/mutex.h>
41#include <linux/of.h>
42#include <linux/of_device.h>
43#include <linux/of_irq.h>
44#include <linux/clk/clk-conf.h>
45#include <linux/completion.h>
46#include <linux/hardirq.h>
47#include <linux/irqflags.h>
48#include <linux/rwsem.h>
49#include <linux/pm_runtime.h>
50#include <linux/pm_domain.h>
51#include <linux/pm_wakeirq.h>
52#include <linux/acpi.h>
53#include <linux/jump_label.h>
54#include <asm/uaccess.h>
55#include <linux/err.h>
56
57#include "i2c-core.h"
58
59#define CREATE_TRACE_POINTS
60#include <trace/events/i2c.h>
61
62#define I2C_ADDR_OFFSET_TEN_BIT	0xa000
63#define I2C_ADDR_OFFSET_SLAVE	0x1000
64
65/* core_lock protects i2c_adapter_idr, and guarantees
66   that device detection, deletion of detected devices, and attach_adapter
67   calls are serialized */
68static DEFINE_MUTEX(core_lock);
69static DEFINE_IDR(i2c_adapter_idr);
70
71static struct device_type i2c_client_type;
72static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
73
74static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
75
76void i2c_transfer_trace_reg(void)
77{
78	static_key_slow_inc(&i2c_trace_msg);
79}
80
81void i2c_transfer_trace_unreg(void)
82{
83	static_key_slow_dec(&i2c_trace_msg);
84}
85
86#if defined(CONFIG_ACPI)
87struct acpi_i2c_handler_data {
88	struct acpi_connection_info info;
89	struct i2c_adapter *adapter;
90};
91
92struct gsb_buffer {
93	u8	status;
94	u8	len;
95	union {
96		u16	wdata;
97		u8	bdata;
98		u8	data[0];
99	};
100} __packed;
101
102struct acpi_i2c_lookup {
103	struct i2c_board_info *info;
104	acpi_handle adapter_handle;
105	acpi_handle device_handle;
106};
107
108static int acpi_i2c_find_address(struct acpi_resource *ares, void *data)
109{
110	struct acpi_i2c_lookup *lookup = data;
111	struct i2c_board_info *info = lookup->info;
112	struct acpi_resource_i2c_serialbus *sb;
113	acpi_handle adapter_handle;
114	acpi_status status;
115
116	if (info->addr || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
117		return 1;
118
119	sb = &ares->data.i2c_serial_bus;
120	if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C)
121		return 1;
122
123	/*
124	 * Extract the ResourceSource and make sure that the handle matches
125	 * with the I2C adapter handle.
126	 */
127	status = acpi_get_handle(lookup->device_handle,
128				 sb->resource_source.string_ptr,
129				 &adapter_handle);
130	if (ACPI_SUCCESS(status) && adapter_handle == lookup->adapter_handle) {
131		info->addr = sb->slave_address;
132		if (sb->access_mode == ACPI_I2C_10BIT_MODE)
133			info->flags |= I2C_CLIENT_TEN;
134	}
135
136	return 1;
137}
138
139static acpi_status acpi_i2c_add_device(acpi_handle handle, u32 level,
140				       void *data, void **return_value)
141{
142	struct i2c_adapter *adapter = data;
143	struct list_head resource_list;
144	struct acpi_i2c_lookup lookup;
145	struct resource_entry *entry;
146	struct i2c_board_info info;
147	struct acpi_device *adev;
148	int ret;
149
150	if (acpi_bus_get_device(handle, &adev))
151		return AE_OK;
152	if (acpi_bus_get_status(adev) || !adev->status.present)
153		return AE_OK;
154
155	memset(&info, 0, sizeof(info));
156	info.fwnode = acpi_fwnode_handle(adev);
157
158	memset(&lookup, 0, sizeof(lookup));
159	lookup.adapter_handle = ACPI_HANDLE(&adapter->dev);
160	lookup.device_handle = handle;
161	lookup.info = &info;
162
163	/*
164	 * Look up for I2cSerialBus resource with ResourceSource that
165	 * matches with this adapter.
166	 */
167	INIT_LIST_HEAD(&resource_list);
168	ret = acpi_dev_get_resources(adev, &resource_list,
169				     acpi_i2c_find_address, &lookup);
170	acpi_dev_free_resource_list(&resource_list);
171
172	if (ret < 0 || !info.addr)
173		return AE_OK;
174
175	/* Then fill IRQ number if any */
176	ret = acpi_dev_get_resources(adev, &resource_list, NULL, NULL);
177	if (ret < 0)
178		return AE_OK;
179
180	resource_list_for_each_entry(entry, &resource_list) {
181		if (resource_type(entry->res) == IORESOURCE_IRQ) {
182			info.irq = entry->res->start;
183			break;
184		}
185	}
186
187	acpi_dev_free_resource_list(&resource_list);
188
189	adev->power.flags.ignore_parent = true;
190	strlcpy(info.type, dev_name(&adev->dev), sizeof(info.type));
191	if (!i2c_new_device(adapter, &info)) {
192		adev->power.flags.ignore_parent = false;
193		dev_err(&adapter->dev,
194			"failed to add I2C device %s from ACPI\n",
195			dev_name(&adev->dev));
196	}
197
198	return AE_OK;
199}
200
201#define ACPI_I2C_MAX_SCAN_DEPTH 32
202
203/**
204 * acpi_i2c_register_devices - enumerate I2C slave devices behind adapter
205 * @adap: pointer to adapter
206 *
207 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
208 * namespace. When a device is found it will be added to the Linux device
209 * model and bound to the corresponding ACPI handle.
210 */
211static void acpi_i2c_register_devices(struct i2c_adapter *adap)
212{
213	acpi_status status;
214
215	if (!has_acpi_companion(&adap->dev))
216		return;
217
218	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
219				     ACPI_I2C_MAX_SCAN_DEPTH,
220				     acpi_i2c_add_device, NULL,
221				     adap, NULL);
222	if (ACPI_FAILURE(status))
223		dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
224}
225
226#else /* CONFIG_ACPI */
227static inline void acpi_i2c_register_devices(struct i2c_adapter *adap) { }
228#endif /* CONFIG_ACPI */
229
230#ifdef CONFIG_ACPI_I2C_OPREGION
231static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
232		u8 cmd, u8 *data, u8 data_len)
233{
234
235	struct i2c_msg msgs[2];
236	int ret;
237	u8 *buffer;
238
239	buffer = kzalloc(data_len, GFP_KERNEL);
240	if (!buffer)
241		return AE_NO_MEMORY;
242
243	msgs[0].addr = client->addr;
244	msgs[0].flags = client->flags;
245	msgs[0].len = 1;
246	msgs[0].buf = &cmd;
247
248	msgs[1].addr = client->addr;
249	msgs[1].flags = client->flags | I2C_M_RD;
250	msgs[1].len = data_len;
251	msgs[1].buf = buffer;
252
253	ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
254	if (ret < 0)
255		dev_err(&client->adapter->dev, "i2c read failed\n");
256	else
257		memcpy(data, buffer, data_len);
258
259	kfree(buffer);
260	return ret;
261}
262
263static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
264		u8 cmd, u8 *data, u8 data_len)
265{
266
267	struct i2c_msg msgs[1];
268	u8 *buffer;
269	int ret = AE_OK;
270
271	buffer = kzalloc(data_len + 1, GFP_KERNEL);
272	if (!buffer)
273		return AE_NO_MEMORY;
274
275	buffer[0] = cmd;
276	memcpy(buffer + 1, data, data_len);
277
278	msgs[0].addr = client->addr;
279	msgs[0].flags = client->flags;
280	msgs[0].len = data_len + 1;
281	msgs[0].buf = buffer;
282
283	ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
284	if (ret < 0)
285		dev_err(&client->adapter->dev, "i2c write failed\n");
286
287	kfree(buffer);
288	return ret;
289}
290
291static acpi_status
292acpi_i2c_space_handler(u32 function, acpi_physical_address command,
293			u32 bits, u64 *value64,
294			void *handler_context, void *region_context)
295{
296	struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
297	struct acpi_i2c_handler_data *data = handler_context;
298	struct acpi_connection_info *info = &data->info;
299	struct acpi_resource_i2c_serialbus *sb;
300	struct i2c_adapter *adapter = data->adapter;
301	struct i2c_client *client;
302	struct acpi_resource *ares;
303	u32 accessor_type = function >> 16;
304	u8 action = function & ACPI_IO_MASK;
305	acpi_status ret;
306	int status;
307
308	ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
309	if (ACPI_FAILURE(ret))
310		return ret;
311
312	client = kzalloc(sizeof(*client), GFP_KERNEL);
313	if (!client) {
314		ret = AE_NO_MEMORY;
315		goto err;
316	}
317
318	if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
319		ret = AE_BAD_PARAMETER;
320		goto err;
321	}
322
323	sb = &ares->data.i2c_serial_bus;
324	if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
325		ret = AE_BAD_PARAMETER;
326		goto err;
327	}
328
329	client->adapter = adapter;
330	client->addr = sb->slave_address;
331
332	if (sb->access_mode == ACPI_I2C_10BIT_MODE)
333		client->flags |= I2C_CLIENT_TEN;
334
335	switch (accessor_type) {
336	case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
337		if (action == ACPI_READ) {
338			status = i2c_smbus_read_byte(client);
339			if (status >= 0) {
340				gsb->bdata = status;
341				status = 0;
342			}
343		} else {
344			status = i2c_smbus_write_byte(client, gsb->bdata);
345		}
346		break;
347
348	case ACPI_GSB_ACCESS_ATTRIB_BYTE:
349		if (action == ACPI_READ) {
350			status = i2c_smbus_read_byte_data(client, command);
351			if (status >= 0) {
352				gsb->bdata = status;
353				status = 0;
354			}
355		} else {
356			status = i2c_smbus_write_byte_data(client, command,
357					gsb->bdata);
358		}
359		break;
360
361	case ACPI_GSB_ACCESS_ATTRIB_WORD:
362		if (action == ACPI_READ) {
363			status = i2c_smbus_read_word_data(client, command);
364			if (status >= 0) {
365				gsb->wdata = status;
366				status = 0;
367			}
368		} else {
369			status = i2c_smbus_write_word_data(client, command,
370					gsb->wdata);
371		}
372		break;
373
374	case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
375		if (action == ACPI_READ) {
376			status = i2c_smbus_read_block_data(client, command,
377					gsb->data);
378			if (status >= 0) {
379				gsb->len = status;
380				status = 0;
381			}
382		} else {
383			status = i2c_smbus_write_block_data(client, command,
384					gsb->len, gsb->data);
385		}
386		break;
387
388	case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
389		if (action == ACPI_READ) {
390			status = acpi_gsb_i2c_read_bytes(client, command,
391					gsb->data, info->access_length);
392			if (status > 0)
393				status = 0;
394		} else {
395			status = acpi_gsb_i2c_write_bytes(client, command,
396					gsb->data, info->access_length);
397		}
398		break;
399
400	default:
401		pr_info("protocol(0x%02x) is not supported.\n", accessor_type);
402		ret = AE_BAD_PARAMETER;
403		goto err;
404	}
405
406	gsb->status = status;
407
408 err:
409	kfree(client);
410	ACPI_FREE(ares);
411	return ret;
412}
413
414
415static int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
416{
417	acpi_handle handle;
418	struct acpi_i2c_handler_data *data;
419	acpi_status status;
420
421	if (!adapter->dev.parent)
422		return -ENODEV;
423
424	handle = ACPI_HANDLE(adapter->dev.parent);
425
426	if (!handle)
427		return -ENODEV;
428
429	data = kzalloc(sizeof(struct acpi_i2c_handler_data),
430			    GFP_KERNEL);
431	if (!data)
432		return -ENOMEM;
433
434	data->adapter = adapter;
435	status = acpi_bus_attach_private_data(handle, (void *)data);
436	if (ACPI_FAILURE(status)) {
437		kfree(data);
438		return -ENOMEM;
439	}
440
441	status = acpi_install_address_space_handler(handle,
442				ACPI_ADR_SPACE_GSBUS,
443				&acpi_i2c_space_handler,
444				NULL,
445				data);
446	if (ACPI_FAILURE(status)) {
447		dev_err(&adapter->dev, "Error installing i2c space handler\n");
448		acpi_bus_detach_private_data(handle);
449		kfree(data);
450		return -ENOMEM;
451	}
452
453	acpi_walk_dep_device_list(handle);
454	return 0;
455}
456
457static void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
458{
459	acpi_handle handle;
460	struct acpi_i2c_handler_data *data;
461	acpi_status status;
462
463	if (!adapter->dev.parent)
464		return;
465
466	handle = ACPI_HANDLE(adapter->dev.parent);
467
468	if (!handle)
469		return;
470
471	acpi_remove_address_space_handler(handle,
472				ACPI_ADR_SPACE_GSBUS,
473				&acpi_i2c_space_handler);
474
475	status = acpi_bus_get_private_data(handle, (void **)&data);
476	if (ACPI_SUCCESS(status))
477		kfree(data);
478
479	acpi_bus_detach_private_data(handle);
480}
481#else /* CONFIG_ACPI_I2C_OPREGION */
482static inline void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
483{ }
484
485static inline int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
486{ return 0; }
487#endif /* CONFIG_ACPI_I2C_OPREGION */
488
489/* ------------------------------------------------------------------------- */
490
491static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
492						const struct i2c_client *client)
493{
494	while (id->name[0]) {
495		if (strcmp(client->name, id->name) == 0)
496			return id;
497		id++;
498	}
499	return NULL;
500}
501
502static int i2c_device_match(struct device *dev, struct device_driver *drv)
503{
504	struct i2c_client	*client = i2c_verify_client(dev);
505	struct i2c_driver	*driver;
506
507	if (!client)
508		return 0;
509
510	/* Attempt an OF style match */
511	if (of_driver_match_device(dev, drv))
512		return 1;
513
514	/* Then ACPI style match */
515	if (acpi_driver_match_device(dev, drv))
516		return 1;
517
518	driver = to_i2c_driver(drv);
519	/* match on an id table if there is one */
520	if (driver->id_table)
521		return i2c_match_id(driver->id_table, client) != NULL;
522
523	return 0;
524}
525
526
527/* uevent helps with hotplug: modprobe -q $(MODALIAS) */
528static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
529{
530	struct i2c_client	*client = to_i2c_client(dev);
531	int rc;
532
533	rc = acpi_device_uevent_modalias(dev, env);
534	if (rc != -ENODEV)
535		return rc;
536
537	if (add_uevent_var(env, "MODALIAS=%s%s",
538			   I2C_MODULE_PREFIX, client->name))
539		return -ENOMEM;
540	dev_dbg(dev, "uevent\n");
541	return 0;
542}
543
544/* i2c bus recovery routines */
545static int get_scl_gpio_value(struct i2c_adapter *adap)
546{
547	return gpio_get_value(adap->bus_recovery_info->scl_gpio);
548}
549
550static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
551{
552	gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
553}
554
555static int get_sda_gpio_value(struct i2c_adapter *adap)
556{
557	return gpio_get_value(adap->bus_recovery_info->sda_gpio);
558}
559
560static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
561{
562	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
563	struct device *dev = &adap->dev;
564	int ret = 0;
565
566	ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
567			GPIOF_OUT_INIT_HIGH, "i2c-scl");
568	if (ret) {
569		dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
570		return ret;
571	}
572
573	if (bri->get_sda) {
574		if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
575			/* work without SDA polling */
576			dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
577					bri->sda_gpio);
578			bri->get_sda = NULL;
579		}
580	}
581
582	return ret;
583}
584
585static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
586{
587	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
588
589	if (bri->get_sda)
590		gpio_free(bri->sda_gpio);
591
592	gpio_free(bri->scl_gpio);
593}
594
595/*
596 * We are generating clock pulses. ndelay() determines durating of clk pulses.
597 * We will generate clock with rate 100 KHz and so duration of both clock levels
598 * is: delay in ns = (10^6 / 100) / 2
599 */
600#define RECOVERY_NDELAY		5000
601#define RECOVERY_CLK_CNT	9
602
603static int i2c_generic_recovery(struct i2c_adapter *adap)
604{
605	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
606	int i = 0, val = 1, ret = 0;
607
608	if (bri->prepare_recovery)
609		bri->prepare_recovery(adap);
610
611	bri->set_scl(adap, val);
612	ndelay(RECOVERY_NDELAY);
613
614	/*
615	 * By this time SCL is high, as we need to give 9 falling-rising edges
616	 */
617	while (i++ < RECOVERY_CLK_CNT * 2) {
618		if (val) {
619			/* Break if SDA is high */
620			if (bri->get_sda && bri->get_sda(adap))
621					break;
622			/* SCL shouldn't be low here */
623			if (!bri->get_scl(adap)) {
624				dev_err(&adap->dev,
625					"SCL is stuck low, exit recovery\n");
626				ret = -EBUSY;
627				break;
628			}
629		}
630
631		val = !val;
632		bri->set_scl(adap, val);
633		ndelay(RECOVERY_NDELAY);
634	}
635
636	if (bri->unprepare_recovery)
637		bri->unprepare_recovery(adap);
638
639	return ret;
640}
641
642int i2c_generic_scl_recovery(struct i2c_adapter *adap)
643{
644	return i2c_generic_recovery(adap);
645}
646EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
647
648int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
649{
650	int ret;
651
652	ret = i2c_get_gpios_for_recovery(adap);
653	if (ret)
654		return ret;
655
656	ret = i2c_generic_recovery(adap);
657	i2c_put_gpios_for_recovery(adap);
658
659	return ret;
660}
661EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
662
663int i2c_recover_bus(struct i2c_adapter *adap)
664{
665	if (!adap->bus_recovery_info)
666		return -EOPNOTSUPP;
667
668	dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
669	return adap->bus_recovery_info->recover_bus(adap);
670}
671EXPORT_SYMBOL_GPL(i2c_recover_bus);
672
673static int i2c_device_probe(struct device *dev)
674{
675	struct i2c_client	*client = i2c_verify_client(dev);
676	struct i2c_driver	*driver;
677	int status;
678
679	if (!client)
680		return 0;
681
682	if (!client->irq) {
683		int irq = -ENOENT;
684
685		if (dev->of_node) {
686			irq = of_irq_get_byname(dev->of_node, "irq");
687			if (irq == -EINVAL || irq == -ENODATA)
688				irq = of_irq_get(dev->of_node, 0);
689		} else if (ACPI_COMPANION(dev)) {
690			irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
691		}
692		if (irq == -EPROBE_DEFER)
693			return irq;
694		if (irq < 0)
695			irq = 0;
696
697		client->irq = irq;
698	}
699
700	driver = to_i2c_driver(dev->driver);
701	if (!driver->probe || !driver->id_table)
702		return -ENODEV;
703
704	if (client->flags & I2C_CLIENT_WAKE) {
705		int wakeirq = -ENOENT;
706
707		if (dev->of_node) {
708			wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
709			if (wakeirq == -EPROBE_DEFER)
710				return wakeirq;
711		}
712
713		device_init_wakeup(&client->dev, true);
714
715		if (wakeirq > 0 && wakeirq != client->irq)
716			status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
717		else if (client->irq > 0)
718			status = dev_pm_set_wake_irq(dev, client->irq);
719		else
720			status = 0;
721
722		if (status)
723			dev_warn(&client->dev, "failed to set up wakeup irq");
724	}
725
726	dev_dbg(dev, "probe\n");
727
728	status = of_clk_set_defaults(dev->of_node, false);
729	if (status < 0)
730		goto err_clear_wakeup_irq;
731
732	status = dev_pm_domain_attach(&client->dev, true);
733	if (status == -EPROBE_DEFER)
734		goto err_clear_wakeup_irq;
735
736	status = driver->probe(client, i2c_match_id(driver->id_table, client));
737	if (status)
738		goto err_detach_pm_domain;
739
740	return 0;
741
742err_detach_pm_domain:
743	dev_pm_domain_detach(&client->dev, true);
744err_clear_wakeup_irq:
745	dev_pm_clear_wake_irq(&client->dev);
746	device_init_wakeup(&client->dev, false);
747	return status;
748}
749
750static int i2c_device_remove(struct device *dev)
751{
752	struct i2c_client	*client = i2c_verify_client(dev);
753	struct i2c_driver	*driver;
754	int status = 0;
755
756	if (!client || !dev->driver)
757		return 0;
758
759	driver = to_i2c_driver(dev->driver);
760	if (driver->remove) {
761		dev_dbg(dev, "remove\n");
762		status = driver->remove(client);
763	}
764
765	dev_pm_domain_detach(&client->dev, true);
766
767	dev_pm_clear_wake_irq(&client->dev);
768	device_init_wakeup(&client->dev, false);
769
770	return status;
771}
772
773static void i2c_device_shutdown(struct device *dev)
774{
775	struct i2c_client *client = i2c_verify_client(dev);
776	struct i2c_driver *driver;
777
778	if (!client || !dev->driver)
779		return;
780	driver = to_i2c_driver(dev->driver);
781	if (driver->shutdown)
782		driver->shutdown(client);
783}
784
785static void i2c_client_dev_release(struct device *dev)
786{
787	kfree(to_i2c_client(dev));
788}
789
790static ssize_t
791show_name(struct device *dev, struct device_attribute *attr, char *buf)
792{
793	return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
794		       to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
795}
796static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
797
798static ssize_t
799show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
800{
801	struct i2c_client *client = to_i2c_client(dev);
802	int len;
803
804	len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
805	if (len != -ENODEV)
806		return len;
807
808	return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
809}
810static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
811
812static struct attribute *i2c_dev_attrs[] = {
813	&dev_attr_name.attr,
814	/* modalias helps coldplug:  modprobe $(cat .../modalias) */
815	&dev_attr_modalias.attr,
816	NULL
817};
818ATTRIBUTE_GROUPS(i2c_dev);
819
820struct bus_type i2c_bus_type = {
821	.name		= "i2c",
822	.match		= i2c_device_match,
823	.probe		= i2c_device_probe,
824	.remove		= i2c_device_remove,
825	.shutdown	= i2c_device_shutdown,
826};
827EXPORT_SYMBOL_GPL(i2c_bus_type);
828
829static struct device_type i2c_client_type = {
830	.groups		= i2c_dev_groups,
831	.uevent		= i2c_device_uevent,
832	.release	= i2c_client_dev_release,
833};
834
835
836/**
837 * i2c_verify_client - return parameter as i2c_client, or NULL
838 * @dev: device, probably from some driver model iterator
839 *
840 * When traversing the driver model tree, perhaps using driver model
841 * iterators like @device_for_each_child(), you can't assume very much
842 * about the nodes you find.  Use this function to avoid oopses caused
843 * by wrongly treating some non-I2C device as an i2c_client.
844 */
845struct i2c_client *i2c_verify_client(struct device *dev)
846{
847	return (dev->type == &i2c_client_type)
848			? to_i2c_client(dev)
849			: NULL;
850}
851EXPORT_SYMBOL(i2c_verify_client);
852
853
854/* Return a unique address which takes the flags of the client into account */
855static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
856{
857	unsigned short addr = client->addr;
858
859	/* For some client flags, add an arbitrary offset to avoid collisions */
860	if (client->flags & I2C_CLIENT_TEN)
861		addr |= I2C_ADDR_OFFSET_TEN_BIT;
862
863	if (client->flags & I2C_CLIENT_SLAVE)
864		addr |= I2C_ADDR_OFFSET_SLAVE;
865
866	return addr;
867}
868
869/* This is a permissive address validity check, I2C address map constraints
870 * are purposely not enforced, except for the general call address. */
871static int i2c_check_addr_validity(unsigned addr, unsigned short flags)
872{
873	if (flags & I2C_CLIENT_TEN) {
874		/* 10-bit address, all values are valid */
875		if (addr > 0x3ff)
876			return -EINVAL;
877	} else {
878		/* 7-bit address, reject the general call address */
879		if (addr == 0x00 || addr > 0x7f)
880			return -EINVAL;
881	}
882	return 0;
883}
884
885/* And this is a strict address validity check, used when probing. If a
886 * device uses a reserved address, then it shouldn't be probed. 7-bit
887 * addressing is assumed, 10-bit address devices are rare and should be
888 * explicitly enumerated. */
889static int i2c_check_7bit_addr_validity_strict(unsigned short addr)
890{
891	/*
892	 * Reserved addresses per I2C specification:
893	 *  0x00       General call address / START byte
894	 *  0x01       CBUS address
895	 *  0x02       Reserved for different bus format
896	 *  0x03       Reserved for future purposes
897	 *  0x04-0x07  Hs-mode master code
898	 *  0x78-0x7b  10-bit slave addressing
899	 *  0x7c-0x7f  Reserved for future purposes
900	 */
901	if (addr < 0x08 || addr > 0x77)
902		return -EINVAL;
903	return 0;
904}
905
906static int __i2c_check_addr_busy(struct device *dev, void *addrp)
907{
908	struct i2c_client	*client = i2c_verify_client(dev);
909	int			addr = *(int *)addrp;
910
911	if (client && i2c_encode_flags_to_addr(client) == addr)
912		return -EBUSY;
913	return 0;
914}
915
916/* walk up mux tree */
917static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
918{
919	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
920	int result;
921
922	result = device_for_each_child(&adapter->dev, &addr,
923					__i2c_check_addr_busy);
924
925	if (!result && parent)
926		result = i2c_check_mux_parents(parent, addr);
927
928	return result;
929}
930
931/* recurse down mux tree */
932static int i2c_check_mux_children(struct device *dev, void *addrp)
933{
934	int result;
935
936	if (dev->type == &i2c_adapter_type)
937		result = device_for_each_child(dev, addrp,
938						i2c_check_mux_children);
939	else
940		result = __i2c_check_addr_busy(dev, addrp);
941
942	return result;
943}
944
945static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
946{
947	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
948	int result = 0;
949
950	if (parent)
951		result = i2c_check_mux_parents(parent, addr);
952
953	if (!result)
954		result = device_for_each_child(&adapter->dev, &addr,
955						i2c_check_mux_children);
956
957	return result;
958}
959
960/**
961 * i2c_lock_adapter - Get exclusive access to an I2C bus segment
962 * @adapter: Target I2C bus segment
963 */
964void i2c_lock_adapter(struct i2c_adapter *adapter)
965{
966	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
967
968	if (parent)
969		i2c_lock_adapter(parent);
970	else
971		rt_mutex_lock(&adapter->bus_lock);
972}
973EXPORT_SYMBOL_GPL(i2c_lock_adapter);
974
975/**
976 * i2c_trylock_adapter - Try to get exclusive access to an I2C bus segment
977 * @adapter: Target I2C bus segment
978 */
979static int i2c_trylock_adapter(struct i2c_adapter *adapter)
980{
981	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
982
983	if (parent)
984		return i2c_trylock_adapter(parent);
985	else
986		return rt_mutex_trylock(&adapter->bus_lock);
987}
988
989/**
990 * i2c_unlock_adapter - Release exclusive access to an I2C bus segment
991 * @adapter: Target I2C bus segment
992 */
993void i2c_unlock_adapter(struct i2c_adapter *adapter)
994{
995	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
996
997	if (parent)
998		i2c_unlock_adapter(parent);
999	else
1000		rt_mutex_unlock(&adapter->bus_lock);
1001}
1002EXPORT_SYMBOL_GPL(i2c_unlock_adapter);
1003
1004static void i2c_dev_set_name(struct i2c_adapter *adap,
1005			     struct i2c_client *client)
1006{
1007	struct acpi_device *adev = ACPI_COMPANION(&client->dev);
1008
1009	if (adev) {
1010		dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
1011		return;
1012	}
1013
1014	dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
1015		     i2c_encode_flags_to_addr(client));
1016}
1017
1018/**
1019 * i2c_new_device - instantiate an i2c device
1020 * @adap: the adapter managing the device
1021 * @info: describes one I2C device; bus_num is ignored
1022 * Context: can sleep
1023 *
1024 * Create an i2c device. Binding is handled through driver model
1025 * probe()/remove() methods.  A driver may be bound to this device when we
1026 * return from this function, or any later moment (e.g. maybe hotplugging will
1027 * load the driver module).  This call is not appropriate for use by mainboard
1028 * initialization logic, which usually runs during an arch_initcall() long
1029 * before any i2c_adapter could exist.
1030 *
1031 * This returns the new i2c client, which may be saved for later use with
1032 * i2c_unregister_device(); or NULL to indicate an error.
1033 */
1034struct i2c_client *
1035i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1036{
1037	struct i2c_client	*client;
1038	int			status;
1039
1040	client = kzalloc(sizeof *client, GFP_KERNEL);
1041	if (!client)
1042		return NULL;
1043
1044	client->adapter = adap;
1045
1046	client->dev.platform_data = info->platform_data;
1047
1048	if (info->archdata)
1049		client->dev.archdata = *info->archdata;
1050
1051	client->flags = info->flags;
1052	client->addr = info->addr;
1053	client->irq = info->irq;
1054
1055	strlcpy(client->name, info->type, sizeof(client->name));
1056
1057	status = i2c_check_addr_validity(client->addr, client->flags);
1058	if (status) {
1059		dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1060			client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1061		goto out_err_silent;
1062	}
1063
1064	/* Check for address business */
1065	status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
1066	if (status)
1067		goto out_err;
1068
1069	client->dev.parent = &client->adapter->dev;
1070	client->dev.bus = &i2c_bus_type;
1071	client->dev.type = &i2c_client_type;
1072	client->dev.of_node = info->of_node;
1073	client->dev.fwnode = info->fwnode;
1074
1075	i2c_dev_set_name(adap, client);
1076	status = device_register(&client->dev);
1077	if (status)
1078		goto out_err;
1079
1080	dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1081		client->name, dev_name(&client->dev));
1082
1083	return client;
1084
1085out_err:
1086	dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
1087		"(%d)\n", client->name, client->addr, status);
1088out_err_silent:
1089	kfree(client);
1090	return NULL;
1091}
1092EXPORT_SYMBOL_GPL(i2c_new_device);
1093
1094
1095/**
1096 * i2c_unregister_device - reverse effect of i2c_new_device()
1097 * @client: value returned from i2c_new_device()
1098 * Context: can sleep
1099 */
1100void i2c_unregister_device(struct i2c_client *client)
1101{
1102	if (client->dev.of_node)
1103		of_node_clear_flag(client->dev.of_node, OF_POPULATED);
1104	device_unregister(&client->dev);
1105}
1106EXPORT_SYMBOL_GPL(i2c_unregister_device);
1107
1108
1109static const struct i2c_device_id dummy_id[] = {
1110	{ "dummy", 0 },
1111	{ },
1112};
1113
1114static int dummy_probe(struct i2c_client *client,
1115		       const struct i2c_device_id *id)
1116{
1117	return 0;
1118}
1119
1120static int dummy_remove(struct i2c_client *client)
1121{
1122	return 0;
1123}
1124
1125static struct i2c_driver dummy_driver = {
1126	.driver.name	= "dummy",
1127	.probe		= dummy_probe,
1128	.remove		= dummy_remove,
1129	.id_table	= dummy_id,
1130};
1131
1132/**
1133 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1134 * @adapter: the adapter managing the device
1135 * @address: seven bit address to be used
1136 * Context: can sleep
1137 *
1138 * This returns an I2C client bound to the "dummy" driver, intended for use
1139 * with devices that consume multiple addresses.  Examples of such chips
1140 * include various EEPROMS (like 24c04 and 24c08 models).
1141 *
1142 * These dummy devices have two main uses.  First, most I2C and SMBus calls
1143 * except i2c_transfer() need a client handle; the dummy will be that handle.
1144 * And second, this prevents the specified address from being bound to a
1145 * different driver.
1146 *
1147 * This returns the new i2c client, which should be saved for later use with
1148 * i2c_unregister_device(); or NULL to indicate an error.
1149 */
1150struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1151{
1152	struct i2c_board_info info = {
1153		I2C_BOARD_INFO("dummy", address),
1154	};
1155
1156	return i2c_new_device(adapter, &info);
1157}
1158EXPORT_SYMBOL_GPL(i2c_new_dummy);
1159
1160/* ------------------------------------------------------------------------- */
1161
1162/* I2C bus adapters -- one roots each I2C or SMBUS segment */
1163
1164static void i2c_adapter_dev_release(struct device *dev)
1165{
1166	struct i2c_adapter *adap = to_i2c_adapter(dev);
1167	complete(&adap->dev_released);
1168}
1169
1170/*
1171 * This function is only needed for mutex_lock_nested, so it is never
1172 * called unless locking correctness checking is enabled. Thus we
1173 * make it inline to avoid a compiler warning. That's what gcc ends up
1174 * doing anyway.
1175 */
1176static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1177{
1178	unsigned int depth = 0;
1179
1180	while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1181		depth++;
1182
1183	return depth;
1184}
1185
1186/*
1187 * Let users instantiate I2C devices through sysfs. This can be used when
1188 * platform initialization code doesn't contain the proper data for
1189 * whatever reason. Also useful for drivers that do device detection and
1190 * detection fails, either because the device uses an unexpected address,
1191 * or this is a compatible device with different ID register values.
1192 *
1193 * Parameter checking may look overzealous, but we really don't want
1194 * the user to provide incorrect parameters.
1195 */
1196static ssize_t
1197i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1198		     const char *buf, size_t count)
1199{
1200	struct i2c_adapter *adap = to_i2c_adapter(dev);
1201	struct i2c_board_info info;
1202	struct i2c_client *client;
1203	char *blank, end;
1204	int res;
1205
1206	memset(&info, 0, sizeof(struct i2c_board_info));
1207
1208	blank = strchr(buf, ' ');
1209	if (!blank) {
1210		dev_err(dev, "%s: Missing parameters\n", "new_device");
1211		return -EINVAL;
1212	}
1213	if (blank - buf > I2C_NAME_SIZE - 1) {
1214		dev_err(dev, "%s: Invalid device name\n", "new_device");
1215		return -EINVAL;
1216	}
1217	memcpy(info.type, buf, blank - buf);
1218
1219	/* Parse remaining parameters, reject extra parameters */
1220	res = sscanf(++blank, "%hi%c", &info.addr, &end);
1221	if (res < 1) {
1222		dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1223		return -EINVAL;
1224	}
1225	if (res > 1  && end != '\n') {
1226		dev_err(dev, "%s: Extra parameters\n", "new_device");
1227		return -EINVAL;
1228	}
1229
1230	if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1231		info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1232		info.flags |= I2C_CLIENT_TEN;
1233	}
1234
1235	if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1236		info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1237		info.flags |= I2C_CLIENT_SLAVE;
1238	}
1239
1240	client = i2c_new_device(adap, &info);
1241	if (!client)
1242		return -EINVAL;
1243
1244	/* Keep track of the added device */
1245	mutex_lock(&adap->userspace_clients_lock);
1246	list_add_tail(&client->detected, &adap->userspace_clients);
1247	mutex_unlock(&adap->userspace_clients_lock);
1248	dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1249		 info.type, info.addr);
1250
1251	return count;
1252}
1253static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1254
1255/*
1256 * And of course let the users delete the devices they instantiated, if
1257 * they got it wrong. This interface can only be used to delete devices
1258 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1259 * don't delete devices to which some kernel code still has references.
1260 *
1261 * Parameter checking may look overzealous, but we really don't want
1262 * the user to delete the wrong device.
1263 */
1264static ssize_t
1265i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1266			const char *buf, size_t count)
1267{
1268	struct i2c_adapter *adap = to_i2c_adapter(dev);
1269	struct i2c_client *client, *next;
1270	unsigned short addr;
1271	char end;
1272	int res;
1273
1274	/* Parse parameters, reject extra parameters */
1275	res = sscanf(buf, "%hi%c", &addr, &end);
1276	if (res < 1) {
1277		dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1278		return -EINVAL;
1279	}
1280	if (res > 1  && end != '\n') {
1281		dev_err(dev, "%s: Extra parameters\n", "delete_device");
1282		return -EINVAL;
1283	}
1284
1285	/* Make sure the device was added through sysfs */
1286	res = -ENOENT;
1287	mutex_lock_nested(&adap->userspace_clients_lock,
1288			  i2c_adapter_depth(adap));
1289	list_for_each_entry_safe(client, next, &adap->userspace_clients,
1290				 detected) {
1291		if (i2c_encode_flags_to_addr(client) == addr) {
1292			dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1293				 "delete_device", client->name, client->addr);
1294
1295			list_del(&client->detected);
1296			i2c_unregister_device(client);
1297			res = count;
1298			break;
1299		}
1300	}
1301	mutex_unlock(&adap->userspace_clients_lock);
1302
1303	if (res < 0)
1304		dev_err(dev, "%s: Can't find device in list\n",
1305			"delete_device");
1306	return res;
1307}
1308static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1309				   i2c_sysfs_delete_device);
1310
1311static struct attribute *i2c_adapter_attrs[] = {
1312	&dev_attr_name.attr,
1313	&dev_attr_new_device.attr,
1314	&dev_attr_delete_device.attr,
1315	NULL
1316};
1317ATTRIBUTE_GROUPS(i2c_adapter);
1318
1319struct device_type i2c_adapter_type = {
1320	.groups		= i2c_adapter_groups,
1321	.release	= i2c_adapter_dev_release,
1322};
1323EXPORT_SYMBOL_GPL(i2c_adapter_type);
1324
1325/**
1326 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1327 * @dev: device, probably from some driver model iterator
1328 *
1329 * When traversing the driver model tree, perhaps using driver model
1330 * iterators like @device_for_each_child(), you can't assume very much
1331 * about the nodes you find.  Use this function to avoid oopses caused
1332 * by wrongly treating some non-I2C device as an i2c_adapter.
1333 */
1334struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1335{
1336	return (dev->type == &i2c_adapter_type)
1337			? to_i2c_adapter(dev)
1338			: NULL;
1339}
1340EXPORT_SYMBOL(i2c_verify_adapter);
1341
1342#ifdef CONFIG_I2C_COMPAT
1343static struct class_compat *i2c_adapter_compat_class;
1344#endif
1345
1346static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1347{
1348	struct i2c_devinfo	*devinfo;
1349
1350	down_read(&__i2c_board_lock);
1351	list_for_each_entry(devinfo, &__i2c_board_list, list) {
1352		if (devinfo->busnum == adapter->nr
1353				&& !i2c_new_device(adapter,
1354						&devinfo->board_info))
1355			dev_err(&adapter->dev,
1356				"Can't create device at 0x%02x\n",
1357				devinfo->board_info.addr);
1358	}
1359	up_read(&__i2c_board_lock);
1360}
1361
1362/* OF support code */
1363
1364#if IS_ENABLED(CONFIG_OF)
1365static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1366						 struct device_node *node)
1367{
1368	struct i2c_client *result;
1369	struct i2c_board_info info = {};
1370	struct dev_archdata dev_ad = {};
1371	const __be32 *addr_be;
1372	u32 addr;
1373	int len;
1374
1375	dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1376
1377	if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1378		dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1379			node->full_name);
1380		return ERR_PTR(-EINVAL);
1381	}
1382
1383	addr_be = of_get_property(node, "reg", &len);
1384	if (!addr_be || (len < sizeof(*addr_be))) {
1385		dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1386			node->full_name);
1387		return ERR_PTR(-EINVAL);
1388	}
1389
1390	addr = be32_to_cpup(addr_be);
1391	if (addr & I2C_TEN_BIT_ADDRESS) {
1392		addr &= ~I2C_TEN_BIT_ADDRESS;
1393		info.flags |= I2C_CLIENT_TEN;
1394	}
1395
1396	if (addr & I2C_OWN_SLAVE_ADDRESS) {
1397		addr &= ~I2C_OWN_SLAVE_ADDRESS;
1398		info.flags |= I2C_CLIENT_SLAVE;
1399	}
1400
1401	if (i2c_check_addr_validity(addr, info.flags)) {
1402		dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1403			info.addr, node->full_name);
1404		return ERR_PTR(-EINVAL);
1405	}
1406
1407	info.addr = addr;
1408	info.of_node = of_node_get(node);
1409	info.archdata = &dev_ad;
1410
1411	if (of_get_property(node, "wakeup-source", NULL))
1412		info.flags |= I2C_CLIENT_WAKE;
1413
1414	result = i2c_new_device(adap, &info);
1415	if (result == NULL) {
1416		dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1417			node->full_name);
1418		of_node_put(node);
1419		return ERR_PTR(-EINVAL);
1420	}
1421	return result;
1422}
1423
1424static void of_i2c_register_devices(struct i2c_adapter *adap)
1425{
1426	struct device_node *node;
1427
1428	/* Only register child devices if the adapter has a node pointer set */
1429	if (!adap->dev.of_node)
1430		return;
1431
1432	dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1433
1434	for_each_available_child_of_node(adap->dev.of_node, node) {
1435		if (of_node_test_and_set_flag(node, OF_POPULATED))
1436			continue;
1437		of_i2c_register_device(adap, node);
1438	}
1439}
1440
1441static int of_dev_node_match(struct device *dev, void *data)
1442{
1443	return dev->of_node == data;
1444}
1445
1446/* must call put_device() when done with returned i2c_client device */
1447struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1448{
1449	struct device *dev;
1450	struct i2c_client *client;
1451
1452	dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1453	if (!dev)
1454		return NULL;
1455
1456	client = i2c_verify_client(dev);
1457	if (!client)
1458		put_device(dev);
1459
1460	return client;
1461}
1462EXPORT_SYMBOL(of_find_i2c_device_by_node);
1463
1464/* must call put_device() when done with returned i2c_adapter device */
1465struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1466{
1467	struct device *dev;
1468	struct i2c_adapter *adapter;
1469
1470	dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1471	if (!dev)
1472		return NULL;
1473
1474	adapter = i2c_verify_adapter(dev);
1475	if (!adapter)
1476		put_device(dev);
1477
1478	return adapter;
1479}
1480EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1481
1482/* must call i2c_put_adapter() when done with returned i2c_adapter device */
1483struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1484{
1485	struct i2c_adapter *adapter;
1486
1487	adapter = of_find_i2c_adapter_by_node(node);
1488	if (!adapter)
1489		return NULL;
1490
1491	if (!try_module_get(adapter->owner)) {
1492		put_device(&adapter->dev);
1493		adapter = NULL;
1494	}
1495
1496	return adapter;
1497}
1498EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1499#else
1500static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1501#endif /* CONFIG_OF */
1502
1503static int i2c_do_add_adapter(struct i2c_driver *driver,
1504			      struct i2c_adapter *adap)
1505{
1506	/* Detect supported devices on that bus, and instantiate them */
1507	i2c_detect(adap, driver);
1508
1509	/* Let legacy drivers scan this bus for matching devices */
1510	if (driver->attach_adapter) {
1511		dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1512			 driver->driver.name);
1513		dev_warn(&adap->dev, "Please use another way to instantiate "
1514			 "your i2c_client\n");
1515		/* We ignore the return code; if it fails, too bad */
1516		driver->attach_adapter(adap);
1517	}
1518	return 0;
1519}
1520
1521static int __process_new_adapter(struct device_driver *d, void *data)
1522{
1523	return i2c_do_add_adapter(to_i2c_driver(d), data);
1524}
1525
1526static int i2c_register_adapter(struct i2c_adapter *adap)
1527{
1528	int res = 0;
1529
1530	/* Can't register until after driver model init */
1531	if (unlikely(WARN_ON(!i2c_bus_type.p))) {
1532		res = -EAGAIN;
1533		goto out_list;
1534	}
1535
1536	/* Sanity checks */
1537	if (unlikely(adap->name[0] == '\0')) {
1538		pr_err("i2c-core: Attempt to register an adapter with "
1539		       "no name!\n");
1540		return -EINVAL;
1541	}
1542	if (unlikely(!adap->algo)) {
1543		pr_err("i2c-core: Attempt to register adapter '%s' with "
1544		       "no algo!\n", adap->name);
1545		return -EINVAL;
1546	}
1547
1548	rt_mutex_init(&adap->bus_lock);
1549	mutex_init(&adap->userspace_clients_lock);
1550	INIT_LIST_HEAD(&adap->userspace_clients);
1551
1552	/* Set default timeout to 1 second if not already set */
1553	if (adap->timeout == 0)
1554		adap->timeout = HZ;
1555
1556	dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1557	adap->dev.bus = &i2c_bus_type;
1558	adap->dev.type = &i2c_adapter_type;
1559	res = device_register(&adap->dev);
1560	if (res)
1561		goto out_list;
1562
1563	dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1564
1565	pm_runtime_no_callbacks(&adap->dev);
1566
1567#ifdef CONFIG_I2C_COMPAT
1568	res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1569				       adap->dev.parent);
1570	if (res)
1571		dev_warn(&adap->dev,
1572			 "Failed to create compatibility class link\n");
1573#endif
1574
1575	/* bus recovery specific initialization */
1576	if (adap->bus_recovery_info) {
1577		struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
1578
1579		if (!bri->recover_bus) {
1580			dev_err(&adap->dev, "No recover_bus() found, not using recovery\n");
1581			adap->bus_recovery_info = NULL;
1582			goto exit_recovery;
1583		}
1584
1585		/* Generic GPIO recovery */
1586		if (bri->recover_bus == i2c_generic_gpio_recovery) {
1587			if (!gpio_is_valid(bri->scl_gpio)) {
1588				dev_err(&adap->dev, "Invalid SCL gpio, not using recovery\n");
1589				adap->bus_recovery_info = NULL;
1590				goto exit_recovery;
1591			}
1592
1593			if (gpio_is_valid(bri->sda_gpio))
1594				bri->get_sda = get_sda_gpio_value;
1595			else
1596				bri->get_sda = NULL;
1597
1598			bri->get_scl = get_scl_gpio_value;
1599			bri->set_scl = set_scl_gpio_value;
1600		} else if (!bri->set_scl || !bri->get_scl) {
1601			/* Generic SCL recovery */
1602			dev_err(&adap->dev, "No {get|set}_gpio() found, not using recovery\n");
1603			adap->bus_recovery_info = NULL;
1604		}
1605	}
1606
1607exit_recovery:
1608	/* create pre-declared device nodes */
1609	of_i2c_register_devices(adap);
1610	acpi_i2c_register_devices(adap);
1611	acpi_i2c_install_space_handler(adap);
1612
1613	if (adap->nr < __i2c_first_dynamic_bus_num)
1614		i2c_scan_static_board_info(adap);
1615
1616	/* Notify drivers */
1617	mutex_lock(&core_lock);
1618	bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1619	mutex_unlock(&core_lock);
1620
1621	return 0;
1622
1623out_list:
1624	mutex_lock(&core_lock);
1625	idr_remove(&i2c_adapter_idr, adap->nr);
1626	mutex_unlock(&core_lock);
1627	return res;
1628}
1629
1630/**
1631 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1632 * @adap: the adapter to register (with adap->nr initialized)
1633 * Context: can sleep
1634 *
1635 * See i2c_add_numbered_adapter() for details.
1636 */
1637static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1638{
1639	int	id;
1640
1641	mutex_lock(&core_lock);
1642	id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1,
1643		       GFP_KERNEL);
1644	mutex_unlock(&core_lock);
1645	if (id < 0)
1646		return id == -ENOSPC ? -EBUSY : id;
1647
1648	return i2c_register_adapter(adap);
1649}
1650
1651/**
1652 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1653 * @adapter: the adapter to add
1654 * Context: can sleep
1655 *
1656 * This routine is used to declare an I2C adapter when its bus number
1657 * doesn't matter or when its bus number is specified by an dt alias.
1658 * Examples of bases when the bus number doesn't matter: I2C adapters
1659 * dynamically added by USB links or PCI plugin cards.
1660 *
1661 * When this returns zero, a new bus number was allocated and stored
1662 * in adap->nr, and the specified adapter became available for clients.
1663 * Otherwise, a negative errno value is returned.
1664 */
1665int i2c_add_adapter(struct i2c_adapter *adapter)
1666{
1667	struct device *dev = &adapter->dev;
1668	int id;
1669
1670	if (dev->of_node) {
1671		id = of_alias_get_id(dev->of_node, "i2c");
1672		if (id >= 0) {
1673			adapter->nr = id;
1674			return __i2c_add_numbered_adapter(adapter);
1675		}
1676	}
1677
1678	mutex_lock(&core_lock);
1679	id = idr_alloc(&i2c_adapter_idr, adapter,
1680		       __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1681	mutex_unlock(&core_lock);
1682	if (id < 0)
1683		return id;
1684
1685	adapter->nr = id;
1686
1687	return i2c_register_adapter(adapter);
1688}
1689EXPORT_SYMBOL(i2c_add_adapter);
1690
1691/**
1692 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1693 * @adap: the adapter to register (with adap->nr initialized)
1694 * Context: can sleep
1695 *
1696 * This routine is used to declare an I2C adapter when its bus number
1697 * matters.  For example, use it for I2C adapters from system-on-chip CPUs,
1698 * or otherwise built in to the system's mainboard, and where i2c_board_info
1699 * is used to properly configure I2C devices.
1700 *
1701 * If the requested bus number is set to -1, then this function will behave
1702 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1703 *
1704 * If no devices have pre-been declared for this bus, then be sure to
1705 * register the adapter before any dynamically allocated ones.  Otherwise
1706 * the required bus ID may not be available.
1707 *
1708 * When this returns zero, the specified adapter became available for
1709 * clients using the bus number provided in adap->nr.  Also, the table
1710 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1711 * and the appropriate driver model device nodes are created.  Otherwise, a
1712 * negative errno value is returned.
1713 */
1714int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1715{
1716	if (adap->nr == -1) /* -1 means dynamically assign bus id */
1717		return i2c_add_adapter(adap);
1718
1719	return __i2c_add_numbered_adapter(adap);
1720}
1721EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1722
1723static void i2c_do_del_adapter(struct i2c_driver *driver,
1724			      struct i2c_adapter *adapter)
1725{
1726	struct i2c_client *client, *_n;
1727
1728	/* Remove the devices we created ourselves as the result of hardware
1729	 * probing (using a driver's detect method) */
1730	list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1731		if (client->adapter == adapter) {
1732			dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1733				client->name, client->addr);
1734			list_del(&client->detected);
1735			i2c_unregister_device(client);
1736		}
1737	}
1738}
1739
1740static int __unregister_client(struct device *dev, void *dummy)
1741{
1742	struct i2c_client *client = i2c_verify_client(dev);
1743	if (client && strcmp(client->name, "dummy"))
1744		i2c_unregister_device(client);
1745	return 0;
1746}
1747
1748static int __unregister_dummy(struct device *dev, void *dummy)
1749{
1750	struct i2c_client *client = i2c_verify_client(dev);
1751	if (client)
1752		i2c_unregister_device(client);
1753	return 0;
1754}
1755
1756static int __process_removed_adapter(struct device_driver *d, void *data)
1757{
1758	i2c_do_del_adapter(to_i2c_driver(d), data);
1759	return 0;
1760}
1761
1762/**
1763 * i2c_del_adapter - unregister I2C adapter
1764 * @adap: the adapter being unregistered
1765 * Context: can sleep
1766 *
1767 * This unregisters an I2C adapter which was previously registered
1768 * by @i2c_add_adapter or @i2c_add_numbered_adapter.
1769 */
1770void i2c_del_adapter(struct i2c_adapter *adap)
1771{
1772	struct i2c_adapter *found;
1773	struct i2c_client *client, *next;
1774
1775	/* First make sure that this adapter was ever added */
1776	mutex_lock(&core_lock);
1777	found = idr_find(&i2c_adapter_idr, adap->nr);
1778	mutex_unlock(&core_lock);
1779	if (found != adap) {
1780		pr_debug("i2c-core: attempting to delete unregistered "
1781			 "adapter [%s]\n", adap->name);
1782		return;
1783	}
1784
1785	acpi_i2c_remove_space_handler(adap);
1786	/* Tell drivers about this removal */
1787	mutex_lock(&core_lock);
1788	bus_for_each_drv(&i2c_bus_type, NULL, adap,
1789			       __process_removed_adapter);
1790	mutex_unlock(&core_lock);
1791
1792	/* Remove devices instantiated from sysfs */
1793	mutex_lock_nested(&adap->userspace_clients_lock,
1794			  i2c_adapter_depth(adap));
1795	list_for_each_entry_safe(client, next, &adap->userspace_clients,
1796				 detected) {
1797		dev_dbg(&adap->dev, "Removing %s at 0x%x\n", client->name,
1798			client->addr);
1799		list_del(&client->detected);
1800		i2c_unregister_device(client);
1801	}
1802	mutex_unlock(&adap->userspace_clients_lock);
1803
1804	/* Detach any active clients. This can't fail, thus we do not
1805	 * check the returned value. This is a two-pass process, because
1806	 * we can't remove the dummy devices during the first pass: they
1807	 * could have been instantiated by real devices wishing to clean
1808	 * them up properly, so we give them a chance to do that first. */
1809	device_for_each_child(&adap->dev, NULL, __unregister_client);
1810	device_for_each_child(&adap->dev, NULL, __unregister_dummy);
1811
1812#ifdef CONFIG_I2C_COMPAT
1813	class_compat_remove_link(i2c_adapter_compat_class, &adap->dev,
1814				 adap->dev.parent);
1815#endif
1816
1817	/* device name is gone after device_unregister */
1818	dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);
1819
1820	/* wait until all references to the device are gone
1821	 *
1822	 * FIXME: This is old code and should ideally be replaced by an
1823	 * alternative which results in decoupling the lifetime of the struct
1824	 * device from the i2c_adapter, like spi or netdev do. Any solution
1825	 * should be thoroughly tested with DEBUG_KOBJECT_RELEASE enabled!
1826	 */
1827	init_completion(&adap->dev_released);
1828	device_unregister(&adap->dev);
1829	wait_for_completion(&adap->dev_released);
1830
1831	/* free bus id */
1832	mutex_lock(&core_lock);
1833	idr_remove(&i2c_adapter_idr, adap->nr);
1834	mutex_unlock(&core_lock);
1835
1836	/* Clear the device structure in case this adapter is ever going to be
1837	   added again */
1838	memset(&adap->dev, 0, sizeof(adap->dev));
1839}
1840EXPORT_SYMBOL(i2c_del_adapter);
1841
1842/* ------------------------------------------------------------------------- */
1843
1844int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *))
1845{
1846	int res;
1847
1848	mutex_lock(&core_lock);
1849	res = bus_for_each_dev(&i2c_bus_type, NULL, data, fn);
1850	mutex_unlock(&core_lock);
1851
1852	return res;
1853}
1854EXPORT_SYMBOL_GPL(i2c_for_each_dev);
1855
1856static int __process_new_driver(struct device *dev, void *data)
1857{
1858	if (dev->type != &i2c_adapter_type)
1859		return 0;
1860	return i2c_do_add_adapter(data, to_i2c_adapter(dev));
1861}
1862
1863/*
1864 * An i2c_driver is used with one or more i2c_client (device) nodes to access
1865 * i2c slave chips, on a bus instance associated with some i2c_adapter.
1866 */
1867
1868int i2c_register_driver(struct module *owner, struct i2c_driver *driver)
1869{
1870	int res;
1871
1872	/* Can't register until after driver model init */
1873	if (unlikely(WARN_ON(!i2c_bus_type.p)))
1874		return -EAGAIN;
1875
1876	/* add the driver to the list of i2c drivers in the driver core */
1877	driver->driver.owner = owner;
1878	driver->driver.bus = &i2c_bus_type;
1879
1880	/* When registration returns, the driver core
1881	 * will have called probe() for all matching-but-unbound devices.
1882	 */
1883	res = driver_register(&driver->driver);
1884	if (res)
1885		return res;
1886
1887	pr_debug("i2c-core: driver [%s] registered\n", driver->driver.name);
1888
1889	INIT_LIST_HEAD(&driver->clients);
1890	/* Walk the adapters that are already present */
1891	i2c_for_each_dev(driver, __process_new_driver);
1892
1893	return 0;
1894}
1895EXPORT_SYMBOL(i2c_register_driver);
1896
1897static int __process_removed_driver(struct device *dev, void *data)
1898{
1899	if (dev->type == &i2c_adapter_type)
1900		i2c_do_del_adapter(data, to_i2c_adapter(dev));
1901	return 0;
1902}
1903
1904/**
1905 * i2c_del_driver - unregister I2C driver
1906 * @driver: the driver being unregistered
1907 * Context: can sleep
1908 */
1909void i2c_del_driver(struct i2c_driver *driver)
1910{
1911	i2c_for_each_dev(driver, __process_removed_driver);
1912
1913	driver_unregister(&driver->driver);
1914	pr_debug("i2c-core: driver [%s] unregistered\n", driver->driver.name);
1915}
1916EXPORT_SYMBOL(i2c_del_driver);
1917
1918/* ------------------------------------------------------------------------- */
1919
1920/**
1921 * i2c_use_client - increments the reference count of the i2c client structure
1922 * @client: the client being referenced
1923 *
1924 * Each live reference to a client should be refcounted. The driver model does
1925 * that automatically as part of driver binding, so that most drivers don't
1926 * need to do this explicitly: they hold a reference until they're unbound
1927 * from the device.
1928 *
1929 * A pointer to the client with the incremented reference counter is returned.
1930 */
1931struct i2c_client *i2c_use_client(struct i2c_client *client)
1932{
1933	if (client && get_device(&client->dev))
1934		return client;
1935	return NULL;
1936}
1937EXPORT_SYMBOL(i2c_use_client);
1938
1939/**
1940 * i2c_release_client - release a use of the i2c client structure
1941 * @client: the client being no longer referenced
1942 *
1943 * Must be called when a user of a client is finished with it.
1944 */
1945void i2c_release_client(struct i2c_client *client)
1946{
1947	if (client)
1948		put_device(&client->dev);
1949}
1950EXPORT_SYMBOL(i2c_release_client);
1951
1952struct i2c_cmd_arg {
1953	unsigned	cmd;
1954	void		*arg;
1955};
1956
1957static int i2c_cmd(struct device *dev, void *_arg)
1958{
1959	struct i2c_client	*client = i2c_verify_client(dev);
1960	struct i2c_cmd_arg	*arg = _arg;
1961	struct i2c_driver	*driver;
1962
1963	if (!client || !client->dev.driver)
1964		return 0;
1965
1966	driver = to_i2c_driver(client->dev.driver);
1967	if (driver->command)
1968		driver->command(client, arg->cmd, arg->arg);
1969	return 0;
1970}
1971
1972void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
1973{
1974	struct i2c_cmd_arg	cmd_arg;
1975
1976	cmd_arg.cmd = cmd;
1977	cmd_arg.arg = arg;
1978	device_for_each_child(&adap->dev, &cmd_arg, i2c_cmd);
1979}
1980EXPORT_SYMBOL(i2c_clients_command);
1981
1982#if IS_ENABLED(CONFIG_OF_DYNAMIC)
1983static int of_i2c_notify(struct notifier_block *nb, unsigned long action,
1984			 void *arg)
1985{
1986	struct of_reconfig_data *rd = arg;
1987	struct i2c_adapter *adap;
1988	struct i2c_client *client;
1989
1990	switch (of_reconfig_get_state_change(action, rd)) {
1991	case OF_RECONFIG_CHANGE_ADD:
1992		adap = of_find_i2c_adapter_by_node(rd->dn->parent);
1993		if (adap == NULL)
1994			return NOTIFY_OK;	/* not for us */
1995
1996		if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
1997			put_device(&adap->dev);
1998			return NOTIFY_OK;
1999		}
2000
2001		client = of_i2c_register_device(adap, rd->dn);
2002		put_device(&adap->dev);
2003
2004		if (IS_ERR(client)) {
2005			pr_err("%s: failed to create for '%s'\n",
2006					__func__, rd->dn->full_name);
2007			return notifier_from_errno(PTR_ERR(client));
2008		}
2009		break;
2010	case OF_RECONFIG_CHANGE_REMOVE:
2011		/* already depopulated? */
2012		if (!of_node_check_flag(rd->dn, OF_POPULATED))
2013			return NOTIFY_OK;
2014
2015		/* find our device by node */
2016		client = of_find_i2c_device_by_node(rd->dn);
2017		if (client == NULL)
2018			return NOTIFY_OK;	/* no? not meant for us */
2019
2020		/* unregister takes one ref away */
2021		i2c_unregister_device(client);
2022
2023		/* and put the reference of the find */
2024		put_device(&client->dev);
2025		break;
2026	}
2027
2028	return NOTIFY_OK;
2029}
2030static struct notifier_block i2c_of_notifier = {
2031	.notifier_call = of_i2c_notify,
2032};
2033#else
2034extern struct notifier_block i2c_of_notifier;
2035#endif /* CONFIG_OF_DYNAMIC */
2036
2037static int __init i2c_init(void)
2038{
2039	int retval;
2040
2041	retval = of_alias_get_highest_id("i2c");
2042
2043	down_write(&__i2c_board_lock);
2044	if (retval >= __i2c_first_dynamic_bus_num)
2045		__i2c_first_dynamic_bus_num = retval + 1;
2046	up_write(&__i2c_board_lock);
2047
2048	retval = bus_register(&i2c_bus_type);
2049	if (retval)
2050		return retval;
2051#ifdef CONFIG_I2C_COMPAT
2052	i2c_adapter_compat_class = class_compat_register("i2c-adapter");
2053	if (!i2c_adapter_compat_class) {
2054		retval = -ENOMEM;
2055		goto bus_err;
2056	}
2057#endif
2058	retval = i2c_add_driver(&dummy_driver);
2059	if (retval)
2060		goto class_err;
2061
2062	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2063		WARN_ON(of_reconfig_notifier_register(&i2c_of_notifier));
2064
2065	return 0;
2066
2067class_err:
2068#ifdef CONFIG_I2C_COMPAT
2069	class_compat_unregister(i2c_adapter_compat_class);
2070bus_err:
2071#endif
2072	bus_unregister(&i2c_bus_type);
2073	return retval;
2074}
2075
2076static void __exit i2c_exit(void)
2077{
2078	if (IS_ENABLED(CONFIG_OF_DYNAMIC))
2079		WARN_ON(of_reconfig_notifier_unregister(&i2c_of_notifier));
2080	i2c_del_driver(&dummy_driver);
2081#ifdef CONFIG_I2C_COMPAT
2082	class_compat_unregister(i2c_adapter_compat_class);
2083#endif
2084	bus_unregister(&i2c_bus_type);
2085	tracepoint_synchronize_unregister();
2086}
2087
2088/* We must initialize early, because some subsystems register i2c drivers
2089 * in subsys_initcall() code, but are linked (and initialized) before i2c.
2090 */
2091postcore_initcall(i2c_init);
2092module_exit(i2c_exit);
2093
2094/* ----------------------------------------------------
2095 * the functional interface to the i2c busses.
2096 * ----------------------------------------------------
2097 */
2098
2099/* Check if val is exceeding the quirk IFF quirk is non 0 */
2100#define i2c_quirk_exceeded(val, quirk) ((quirk) && ((val) > (quirk)))
2101
2102static int i2c_quirk_error(struct i2c_adapter *adap, struct i2c_msg *msg, char *err_msg)
2103{
2104	dev_err_ratelimited(&adap->dev, "adapter quirk: %s (addr 0x%04x, size %u, %s)\n",
2105			    err_msg, msg->addr, msg->len,
2106			    msg->flags & I2C_M_RD ? "read" : "write");
2107	return -EOPNOTSUPP;
2108}
2109
2110static int i2c_check_for_quirks(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2111{
2112	const struct i2c_adapter_quirks *q = adap->quirks;
2113	int max_num = q->max_num_msgs, i;
2114	bool do_len_check = true;
2115
2116	if (q->flags & I2C_AQ_COMB) {
2117		max_num = 2;
2118
2119		/* special checks for combined messages */
2120		if (num == 2) {
2121			if (q->flags & I2C_AQ_COMB_WRITE_FIRST && msgs[0].flags & I2C_M_RD)
2122				return i2c_quirk_error(adap, &msgs[0], "1st comb msg must be write");
2123
2124			if (q->flags & I2C_AQ_COMB_READ_SECOND && !(msgs[1].flags & I2C_M_RD))
2125				return i2c_quirk_error(adap, &msgs[1], "2nd comb msg must be read");
2126
2127			if (q->flags & I2C_AQ_COMB_SAME_ADDR && msgs[0].addr != msgs[1].addr)
2128				return i2c_quirk_error(adap, &msgs[0], "comb msg only to same addr");
2129
2130			if (i2c_quirk_exceeded(msgs[0].len, q->max_comb_1st_msg_len))
2131				return i2c_quirk_error(adap, &msgs[0], "msg too long");
2132
2133			if (i2c_quirk_exceeded(msgs[1].len, q->max_comb_2nd_msg_len))
2134				return i2c_quirk_error(adap, &msgs[1], "msg too long");
2135
2136			do_len_check = false;
2137		}
2138	}
2139
2140	if (i2c_quirk_exceeded(num, max_num))
2141		return i2c_quirk_error(adap, &msgs[0], "too many messages");
2142
2143	for (i = 0; i < num; i++) {
2144		u16 len = msgs[i].len;
2145
2146		if (msgs[i].flags & I2C_M_RD) {
2147			if (do_len_check && i2c_quirk_exceeded(len, q->max_read_len))
2148				return i2c_quirk_error(adap, &msgs[i], "msg too long");
2149		} else {
2150			if (do_len_check && i2c_quirk_exceeded(len, q->max_write_len))
2151				return i2c_quirk_error(adap, &msgs[i], "msg too long");
2152		}
2153	}
2154
2155	return 0;
2156}
2157
2158/**
2159 * __i2c_transfer - unlocked flavor of i2c_transfer
2160 * @adap: Handle to I2C bus
2161 * @msgs: One or more messages to execute before STOP is issued to
2162 *	terminate the operation; each message begins with a START.
2163 * @num: Number of messages to be executed.
2164 *
2165 * Returns negative errno, else the number of messages executed.
2166 *
2167 * Adapter lock must be held when calling this function. No debug logging
2168 * takes place. adap->algo->master_xfer existence isn't checked.
2169 */
2170int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2171{
2172	unsigned long orig_jiffies;
2173	int ret, try;
2174
2175	if (adap->quirks && i2c_check_for_quirks(adap, msgs, num))
2176		return -EOPNOTSUPP;
2177
2178	/* i2c_trace_msg gets enabled when tracepoint i2c_transfer gets
2179	 * enabled.  This is an efficient way of keeping the for-loop from
2180	 * being executed when not needed.
2181	 */
2182	if (static_key_false(&i2c_trace_msg)) {
2183		int i;
2184		for (i = 0; i < num; i++)
2185			if (msgs[i].flags & I2C_M_RD)
2186				trace_i2c_read(adap, &msgs[i], i);
2187			else
2188				trace_i2c_write(adap, &msgs[i], i);
2189	}
2190
2191	/* Retry automatically on arbitration loss */
2192	orig_jiffies = jiffies;
2193	for (ret = 0, try = 0; try <= adap->retries; try++) {
2194		ret = adap->algo->master_xfer(adap, msgs, num);
2195		if (ret != -EAGAIN)
2196			break;
2197		if (time_after(jiffies, orig_jiffies + adap->timeout))
2198			break;
2199	}
2200
2201	if (static_key_false(&i2c_trace_msg)) {
2202		int i;
2203		for (i = 0; i < ret; i++)
2204			if (msgs[i].flags & I2C_M_RD)
2205				trace_i2c_reply(adap, &msgs[i], i);
2206		trace_i2c_result(adap, i, ret);
2207	}
2208
2209	return ret;
2210}
2211EXPORT_SYMBOL(__i2c_transfer);
2212
2213/**
2214 * i2c_transfer - execute a single or combined I2C message
2215 * @adap: Handle to I2C bus
2216 * @msgs: One or more messages to execute before STOP is issued to
2217 *	terminate the operation; each message begins with a START.
2218 * @num: Number of messages to be executed.
2219 *
2220 * Returns negative errno, else the number of messages executed.
2221 *
2222 * Note that there is no requirement that each message be sent to
2223 * the same slave address, although that is the most common model.
2224 */
2225int i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num)
2226{
2227	int ret;
2228
2229	/* REVISIT the fault reporting model here is weak:
2230	 *
2231	 *  - When we get an error after receiving N bytes from a slave,
2232	 *    there is no way to report "N".
2233	 *
2234	 *  - When we get a NAK after transmitting N bytes to a slave,
2235	 *    there is no way to report "N" ... or to let the master
2236	 *    continue executing the rest of this combined message, if
2237	 *    that's the appropriate response.
2238	 *
2239	 *  - When for example "num" is two and we successfully complete
2240	 *    the first message but get an error part way through the
2241	 *    second, it's unclear whether that should be reported as
2242	 *    one (discarding status on the second message) or errno
2243	 *    (discarding status on the first one).
2244	 */
2245
2246	if (adap->algo->master_xfer) {
2247#ifdef DEBUG
2248		for (ret = 0; ret < num; ret++) {
2249			dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
2250				"len=%d%s\n", ret, (msgs[ret].flags & I2C_M_RD)
2251				? 'R' : 'W', msgs[ret].addr, msgs[ret].len,
2252				(msgs[ret].flags & I2C_M_RECV_LEN) ? "+" : "");
2253		}
2254#endif
2255
2256		if (in_atomic() || irqs_disabled()) {
2257			ret = i2c_trylock_adapter(adap);
2258			if (!ret)
2259				/* I2C activity is ongoing. */
2260				return -EAGAIN;
2261		} else {
2262			i2c_lock_adapter(adap);
2263		}
2264
2265		ret = __i2c_transfer(adap, msgs, num);
2266		i2c_unlock_adapter(adap);
2267
2268		return ret;
2269	} else {
2270		dev_dbg(&adap->dev, "I2C level transfers not supported\n");
2271		return -EOPNOTSUPP;
2272	}
2273}
2274EXPORT_SYMBOL(i2c_transfer);
2275
2276/**
2277 * i2c_master_send - issue a single I2C message in master transmit mode
2278 * @client: Handle to slave device
2279 * @buf: Data that will be written to the slave
2280 * @count: How many bytes to write, must be less than 64k since msg.len is u16
2281 *
2282 * Returns negative errno, or else the number of bytes written.
2283 */
2284int i2c_master_send(const struct i2c_client *client, const char *buf, int count)
2285{
2286	int ret;
2287	struct i2c_adapter *adap = client->adapter;
2288	struct i2c_msg msg;
2289
2290	msg.addr = client->addr;
2291	msg.flags = client->flags & I2C_M_TEN;
2292	msg.len = count;
2293	msg.buf = (char *)buf;
2294
2295	ret = i2c_transfer(adap, &msg, 1);
2296
2297	/*
2298	 * If everything went ok (i.e. 1 msg transmitted), return #bytes
2299	 * transmitted, else error code.
2300	 */
2301	return (ret == 1) ? count : ret;
2302}
2303EXPORT_SYMBOL(i2c_master_send);
2304
2305/**
2306 * i2c_master_recv - issue a single I2C message in master receive mode
2307 * @client: Handle to slave device
2308 * @buf: Where to store data read from slave
2309 * @count: How many bytes to read, must be less than 64k since msg.len is u16
2310 *
2311 * Returns negative errno, or else the number of bytes read.
2312 */
2313int i2c_master_recv(const struct i2c_client *client, char *buf, int count)
2314{
2315	struct i2c_adapter *adap = client->adapter;
2316	struct i2c_msg msg;
2317	int ret;
2318
2319	msg.addr = client->addr;
2320	msg.flags = client->flags & I2C_M_TEN;
2321	msg.flags |= I2C_M_RD;
2322	msg.len = count;
2323	msg.buf = buf;
2324
2325	ret = i2c_transfer(adap, &msg, 1);
2326
2327	/*
2328	 * If everything went ok (i.e. 1 msg received), return #bytes received,
2329	 * else error code.
2330	 */
2331	return (ret == 1) ? count : ret;
2332}
2333EXPORT_SYMBOL(i2c_master_recv);
2334
2335/* ----------------------------------------------------
2336 * the i2c address scanning function
2337 * Will not work for 10-bit addresses!
2338 * ----------------------------------------------------
2339 */
2340
2341/*
2342 * Legacy default probe function, mostly relevant for SMBus. The default
2343 * probe method is a quick write, but it is known to corrupt the 24RF08
2344 * EEPROMs due to a state machine bug, and could also irreversibly
2345 * write-protect some EEPROMs, so for address ranges 0x30-0x37 and 0x50-0x5f,
2346 * we use a short byte read instead. Also, some bus drivers don't implement
2347 * quick write, so we fallback to a byte read in that case too.
2348 * On x86, there is another special case for FSC hardware monitoring chips,
2349 * which want regular byte reads (address 0x73.) Fortunately, these are the
2350 * only known chips using this I2C address on PC hardware.
2351 * Returns 1 if probe succeeded, 0 if not.
2352 */
2353static int i2c_default_probe(struct i2c_adapter *adap, unsigned short addr)
2354{
2355	int err;
2356	union i2c_smbus_data dummy;
2357
2358#ifdef CONFIG_X86
2359	if (addr == 0x73 && (adap->class & I2C_CLASS_HWMON)
2360	 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE_DATA))
2361		err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2362				     I2C_SMBUS_BYTE_DATA, &dummy);
2363	else
2364#endif
2365	if (!((addr & ~0x07) == 0x30 || (addr & ~0x0f) == 0x50)
2366	 && i2c_check_functionality(adap, I2C_FUNC_SMBUS_QUICK))
2367		err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_WRITE, 0,
2368				     I2C_SMBUS_QUICK, NULL);
2369	else if (i2c_check_functionality(adap, I2C_FUNC_SMBUS_READ_BYTE))
2370		err = i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2371				     I2C_SMBUS_BYTE, &dummy);
2372	else {
2373		dev_warn(&adap->dev, "No suitable probing method supported for address 0x%02X\n",
2374			 addr);
2375		err = -EOPNOTSUPP;
2376	}
2377
2378	return err >= 0;
2379}
2380
2381static int i2c_detect_address(struct i2c_client *temp_client,
2382			      struct i2c_driver *driver)
2383{
2384	struct i2c_board_info info;
2385	struct i2c_adapter *adapter = temp_client->adapter;
2386	int addr = temp_client->addr;
2387	int err;
2388
2389	/* Make sure the address is valid */
2390	err = i2c_check_7bit_addr_validity_strict(addr);
2391	if (err) {
2392		dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
2393			 addr);
2394		return err;
2395	}
2396
2397	/* Skip if already in use (7 bit, no need to encode flags) */
2398	if (i2c_check_addr_busy(adapter, addr))
2399		return 0;
2400
2401	/* Make sure there is something at this address */
2402	if (!i2c_default_probe(adapter, addr))
2403		return 0;
2404
2405	/* Finally call the custom detection function */
2406	memset(&info, 0, sizeof(struct i2c_board_info));
2407	info.addr = addr;
2408	err = driver->detect(temp_client, &info);
2409	if (err) {
2410		/* -ENODEV is returned if the detection fails. We catch it
2411		   here as this isn't an error. */
2412		return err == -ENODEV ? 0 : err;
2413	}
2414
2415	/* Consistency check */
2416	if (info.type[0] == '\0') {
2417		dev_err(&adapter->dev, "%s detection function provided "
2418			"no name for 0x%x\n", driver->driver.name,
2419			addr);
2420	} else {
2421		struct i2c_client *client;
2422
2423		/* Detection succeeded, instantiate the device */
2424		if (adapter->class & I2C_CLASS_DEPRECATED)
2425			dev_warn(&adapter->dev,
2426				"This adapter will soon drop class based instantiation of devices. "
2427				"Please make sure client 0x%02x gets instantiated by other means. "
2428				"Check 'Documentation/i2c/instantiating-devices' for details.\n",
2429				info.addr);
2430
2431		dev_dbg(&adapter->dev, "Creating %s at 0x%02x\n",
2432			info.type, info.addr);
2433		client = i2c_new_device(adapter, &info);
2434		if (client)
2435			list_add_tail(&client->detected, &driver->clients);
2436		else
2437			dev_err(&adapter->dev, "Failed creating %s at 0x%02x\n",
2438				info.type, info.addr);
2439	}
2440	return 0;
2441}
2442
2443static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver)
2444{
2445	const unsigned short *address_list;
2446	struct i2c_client *temp_client;
2447	int i, err = 0;
2448	int adap_id = i2c_adapter_id(adapter);
2449
2450	address_list = driver->address_list;
2451	if (!driver->detect || !address_list)
2452		return 0;
2453
2454	/* Warn that the adapter lost class based instantiation */
2455	if (adapter->class == I2C_CLASS_DEPRECATED) {
2456		dev_dbg(&adapter->dev,
2457			"This adapter dropped support for I2C classes and "
2458			"won't auto-detect %s devices anymore. If you need it, check "
2459			"'Documentation/i2c/instantiating-devices' for alternatives.\n",
2460			driver->driver.name);
2461		return 0;
2462	}
2463
2464	/* Stop here if the classes do not match */
2465	if (!(adapter->class & driver->class))
2466		return 0;
2467
2468	/* Set up a temporary client to help detect callback */
2469	temp_client = kzalloc(sizeof(struct i2c_client), GFP_KERNEL);
2470	if (!temp_client)
2471		return -ENOMEM;
2472	temp_client->adapter = adapter;
2473
2474	for (i = 0; address_list[i] != I2C_CLIENT_END; i += 1) {
2475		dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
2476			"addr 0x%02x\n", adap_id, address_list[i]);
2477		temp_client->addr = address_list[i];
2478		err = i2c_detect_address(temp_client, driver);
2479		if (unlikely(err))
2480			break;
2481	}
2482
2483	kfree(temp_client);
2484	return err;
2485}
2486
2487int i2c_probe_func_quick_read(struct i2c_adapter *adap, unsigned short addr)
2488{
2489	return i2c_smbus_xfer(adap, addr, 0, I2C_SMBUS_READ, 0,
2490			      I2C_SMBUS_QUICK, NULL) >= 0;
2491}
2492EXPORT_SYMBOL_GPL(i2c_probe_func_quick_read);
2493
2494struct i2c_client *
2495i2c_new_probed_device(struct i2c_adapter *adap,
2496		      struct i2c_board_info *info,
2497		      unsigned short const *addr_list,
2498		      int (*probe)(struct i2c_adapter *, unsigned short addr))
2499{
2500	int i;
2501
2502	if (!probe)
2503		probe = i2c_default_probe;
2504
2505	for (i = 0; addr_list[i] != I2C_CLIENT_END; i++) {
2506		/* Check address validity */
2507		if (i2c_check_7bit_addr_validity_strict(addr_list[i]) < 0) {
2508			dev_warn(&adap->dev, "Invalid 7-bit address "
2509				 "0x%02x\n", addr_list[i]);
2510			continue;
2511		}
2512
2513		/* Check address availability (7 bit, no need to encode flags) */
2514		if (i2c_check_addr_busy(adap, addr_list[i])) {
2515			dev_dbg(&adap->dev, "Address 0x%02x already in "
2516				"use, not probing\n", addr_list[i]);
2517			continue;
2518		}
2519
2520		/* Test address responsiveness */
2521		if (probe(adap, addr_list[i]))
2522			break;
2523	}
2524
2525	if (addr_list[i] == I2C_CLIENT_END) {
2526		dev_dbg(&adap->dev, "Probing failed, no device found\n");
2527		return NULL;
2528	}
2529
2530	info->addr = addr_list[i];
2531	return i2c_new_device(adap, info);
2532}
2533EXPORT_SYMBOL_GPL(i2c_new_probed_device);
2534
2535struct i2c_adapter *i2c_get_adapter(int nr)
2536{
2537	struct i2c_adapter *adapter;
2538
2539	mutex_lock(&core_lock);
2540	adapter = idr_find(&i2c_adapter_idr, nr);
2541	if (!adapter)
2542		goto exit;
2543
2544	if (try_module_get(adapter->owner))
2545		get_device(&adapter->dev);
2546	else
2547		adapter = NULL;
2548
2549 exit:
2550	mutex_unlock(&core_lock);
2551	return adapter;
2552}
2553EXPORT_SYMBOL(i2c_get_adapter);
2554
2555void i2c_put_adapter(struct i2c_adapter *adap)
2556{
2557	if (!adap)
2558		return;
2559
2560	put_device(&adap->dev);
2561	module_put(adap->owner);
2562}
2563EXPORT_SYMBOL(i2c_put_adapter);
2564
2565/* The SMBus parts */
2566
2567#define POLY    (0x1070U << 3)
2568static u8 crc8(u16 data)
2569{
2570	int i;
2571
2572	for (i = 0; i < 8; i++) {
2573		if (data & 0x8000)
2574			data = data ^ POLY;
2575		data = data << 1;
2576	}
2577	return (u8)(data >> 8);
2578}
2579
2580/* Incremental CRC8 over count bytes in the array pointed to by p */
2581static u8 i2c_smbus_pec(u8 crc, u8 *p, size_t count)
2582{
2583	int i;
2584
2585	for (i = 0; i < count; i++)
2586		crc = crc8((crc ^ p[i]) << 8);
2587	return crc;
2588}
2589
2590/* Assume a 7-bit address, which is reasonable for SMBus */
2591static u8 i2c_smbus_msg_pec(u8 pec, struct i2c_msg *msg)
2592{
2593	/* The address will be sent first */
2594	u8 addr = (msg->addr << 1) | !!(msg->flags & I2C_M_RD);
2595	pec = i2c_smbus_pec(pec, &addr, 1);
2596
2597	/* The data buffer follows */
2598	return i2c_smbus_pec(pec, msg->buf, msg->len);
2599}
2600
2601/* Used for write only transactions */
2602static inline void i2c_smbus_add_pec(struct i2c_msg *msg)
2603{
2604	msg->buf[msg->len] = i2c_smbus_msg_pec(0, msg);
2605	msg->len++;
2606}
2607
2608/* Return <0 on CRC error
2609   If there was a write before this read (most cases) we need to take the
2610   partial CRC from the write part into account.
2611   Note that this function does modify the message (we need to decrease the
2612   message length to hide the CRC byte from the caller). */
2613static int i2c_smbus_check_pec(u8 cpec, struct i2c_msg *msg)
2614{
2615	u8 rpec = msg->buf[--msg->len];
2616	cpec = i2c_smbus_msg_pec(cpec, msg);
2617
2618	if (rpec != cpec) {
2619		pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
2620			rpec, cpec);
2621		return -EBADMSG;
2622	}
2623	return 0;
2624}
2625
2626/**
2627 * i2c_smbus_read_byte - SMBus "receive byte" protocol
2628 * @client: Handle to slave device
2629 *
2630 * This executes the SMBus "receive byte" protocol, returning negative errno
2631 * else the byte received from the device.
2632 */
2633s32 i2c_smbus_read_byte(const struct i2c_client *client)
2634{
2635	union i2c_smbus_data data;
2636	int status;
2637
2638	status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2639				I2C_SMBUS_READ, 0,
2640				I2C_SMBUS_BYTE, &data);
2641	return (status < 0) ? status : data.byte;
2642}
2643EXPORT_SYMBOL(i2c_smbus_read_byte);
2644
2645/**
2646 * i2c_smbus_write_byte - SMBus "send byte" protocol
2647 * @client: Handle to slave device
2648 * @value: Byte to be sent
2649 *
2650 * This executes the SMBus "send byte" protocol, returning negative errno
2651 * else zero on success.
2652 */
2653s32 i2c_smbus_write_byte(const struct i2c_client *client, u8 value)
2654{
2655	return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2656	                      I2C_SMBUS_WRITE, value, I2C_SMBUS_BYTE, NULL);
2657}
2658EXPORT_SYMBOL(i2c_smbus_write_byte);
2659
2660/**
2661 * i2c_smbus_read_byte_data - SMBus "read byte" protocol
2662 * @client: Handle to slave device
2663 * @command: Byte interpreted by slave
2664 *
2665 * This executes the SMBus "read byte" protocol, returning negative errno
2666 * else a data byte received from the device.
2667 */
2668s32 i2c_smbus_read_byte_data(const struct i2c_client *client, u8 command)
2669{
2670	union i2c_smbus_data data;
2671	int status;
2672
2673	status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2674				I2C_SMBUS_READ, command,
2675				I2C_SMBUS_BYTE_DATA, &data);
2676	return (status < 0) ? status : data.byte;
2677}
2678EXPORT_SYMBOL(i2c_smbus_read_byte_data);
2679
2680/**
2681 * i2c_smbus_write_byte_data - SMBus "write byte" protocol
2682 * @client: Handle to slave device
2683 * @command: Byte interpreted by slave
2684 * @value: Byte being written
2685 *
2686 * This executes the SMBus "write byte" protocol, returning negative errno
2687 * else zero on success.
2688 */
2689s32 i2c_smbus_write_byte_data(const struct i2c_client *client, u8 command,
2690			      u8 value)
2691{
2692	union i2c_smbus_data data;
2693	data.byte = value;
2694	return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2695			      I2C_SMBUS_WRITE, command,
2696			      I2C_SMBUS_BYTE_DATA, &data);
2697}
2698EXPORT_SYMBOL(i2c_smbus_write_byte_data);
2699
2700/**
2701 * i2c_smbus_read_word_data - SMBus "read word" protocol
2702 * @client: Handle to slave device
2703 * @command: Byte interpreted by slave
2704 *
2705 * This executes the SMBus "read word" protocol, returning negative errno
2706 * else a 16-bit unsigned "word" received from the device.
2707 */
2708s32 i2c_smbus_read_word_data(const struct i2c_client *client, u8 command)
2709{
2710	union i2c_smbus_data data;
2711	int status;
2712
2713	status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2714				I2C_SMBUS_READ, command,
2715				I2C_SMBUS_WORD_DATA, &data);
2716	return (status < 0) ? status : data.word;
2717}
2718EXPORT_SYMBOL(i2c_smbus_read_word_data);
2719
2720/**
2721 * i2c_smbus_write_word_data - SMBus "write word" protocol
2722 * @client: Handle to slave device
2723 * @command: Byte interpreted by slave
2724 * @value: 16-bit "word" being written
2725 *
2726 * This executes the SMBus "write word" protocol, returning negative errno
2727 * else zero on success.
2728 */
2729s32 i2c_smbus_write_word_data(const struct i2c_client *client, u8 command,
2730			      u16 value)
2731{
2732	union i2c_smbus_data data;
2733	data.word = value;
2734	return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2735			      I2C_SMBUS_WRITE, command,
2736			      I2C_SMBUS_WORD_DATA, &data);
2737}
2738EXPORT_SYMBOL(i2c_smbus_write_word_data);
2739
2740/**
2741 * i2c_smbus_read_block_data - SMBus "block read" protocol
2742 * @client: Handle to slave device
2743 * @command: Byte interpreted by slave
2744 * @values: Byte array into which data will be read; big enough to hold
2745 *	the data returned by the slave.  SMBus allows at most 32 bytes.
2746 *
2747 * This executes the SMBus "block read" protocol, returning negative errno
2748 * else the number of data bytes in the slave's response.
2749 *
2750 * Note that using this function requires that the client's adapter support
2751 * the I2C_FUNC_SMBUS_READ_BLOCK_DATA functionality.  Not all adapter drivers
2752 * support this; its emulation through I2C messaging relies on a specific
2753 * mechanism (I2C_M_RECV_LEN) which may not be implemented.
2754 */
2755s32 i2c_smbus_read_block_data(const struct i2c_client *client, u8 command,
2756			      u8 *values)
2757{
2758	union i2c_smbus_data data;
2759	int status;
2760
2761	status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2762				I2C_SMBUS_READ, command,
2763				I2C_SMBUS_BLOCK_DATA, &data);
2764	if (status)
2765		return status;
2766
2767	memcpy(values, &data.block[1], data.block[0]);
2768	return data.block[0];
2769}
2770EXPORT_SYMBOL(i2c_smbus_read_block_data);
2771
2772/**
2773 * i2c_smbus_write_block_data - SMBus "block write" protocol
2774 * @client: Handle to slave device
2775 * @command: Byte interpreted by slave
2776 * @length: Size of data block; SMBus allows at most 32 bytes
2777 * @values: Byte array which will be written.
2778 *
2779 * This executes the SMBus "block write" protocol, returning negative errno
2780 * else zero on success.
2781 */
2782s32 i2c_smbus_write_block_data(const struct i2c_client *client, u8 command,
2783			       u8 length, const u8 *values)
2784{
2785	union i2c_smbus_data data;
2786
2787	if (length > I2C_SMBUS_BLOCK_MAX)
2788		length = I2C_SMBUS_BLOCK_MAX;
2789	data.block[0] = length;
2790	memcpy(&data.block[1], values, length);
2791	return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2792			      I2C_SMBUS_WRITE, command,
2793			      I2C_SMBUS_BLOCK_DATA, &data);
2794}
2795EXPORT_SYMBOL(i2c_smbus_write_block_data);
2796
2797/* Returns the number of read bytes */
2798s32 i2c_smbus_read_i2c_block_data(const struct i2c_client *client, u8 command,
2799				  u8 length, u8 *values)
2800{
2801	union i2c_smbus_data data;
2802	int status;
2803
2804	if (length > I2C_SMBUS_BLOCK_MAX)
2805		length = I2C_SMBUS_BLOCK_MAX;
2806	data.block[0] = length;
2807	status = i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2808				I2C_SMBUS_READ, command,
2809				I2C_SMBUS_I2C_BLOCK_DATA, &data);
2810	if (status < 0)
2811		return status;
2812
2813	memcpy(values, &data.block[1], data.block[0]);
2814	return data.block[0];
2815}
2816EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);
2817
2818s32 i2c_smbus_write_i2c_block_data(const struct i2c_client *client, u8 command,
2819				   u8 length, const u8 *values)
2820{
2821	union i2c_smbus_data data;
2822
2823	if (length > I2C_SMBUS_BLOCK_MAX)
2824		length = I2C_SMBUS_BLOCK_MAX;
2825	data.block[0] = length;
2826	memcpy(data.block + 1, values, length);
2827	return i2c_smbus_xfer(client->adapter, client->addr, client->flags,
2828			      I2C_SMBUS_WRITE, command,
2829			      I2C_SMBUS_I2C_BLOCK_DATA, &data);
2830}
2831EXPORT_SYMBOL(i2c_smbus_write_i2c_block_data);
2832
2833/* Simulate a SMBus command using the i2c protocol
2834   No checking of parameters is done!  */
2835static s32 i2c_smbus_xfer_emulated(struct i2c_adapter *adapter, u16 addr,
2836				   unsigned short flags,
2837				   char read_write, u8 command, int size,
2838				   union i2c_smbus_data *data)
2839{
2840	/* So we need to generate a series of msgs. In the case of writing, we
2841	  need to use only one message; when reading, we need two. We initialize
2842	  most things with sane defaults, to keep the code below somewhat
2843	  simpler. */
2844	unsigned char msgbuf0[I2C_SMBUS_BLOCK_MAX+3];
2845	unsigned char msgbuf1[I2C_SMBUS_BLOCK_MAX+2];
2846	int num = read_write == I2C_SMBUS_READ ? 2 : 1;
2847	int i;
2848	u8 partial_pec = 0;
2849	int status;
2850	struct i2c_msg msg[2] = {
2851		{
2852			.addr = addr,
2853			.flags = flags,
2854			.len = 1,
2855			.buf = msgbuf0,
2856		}, {
2857			.addr = addr,
2858			.flags = flags | I2C_M_RD,
2859			.len = 0,
2860			.buf = msgbuf1,
2861		},
2862	};
2863
2864	msgbuf0[0] = command;
2865	switch (size) {
2866	case I2C_SMBUS_QUICK:
2867		msg[0].len = 0;
2868		/* Special case: The read/write field is used as data */
2869		msg[0].flags = flags | (read_write == I2C_SMBUS_READ ?
2870					I2C_M_RD : 0);
2871		num = 1;
2872		break;
2873	case I2C_SMBUS_BYTE:
2874		if (read_write == I2C_SMBUS_READ) {
2875			/* Special case: only a read! */
2876			msg[0].flags = I2C_M_RD | flags;
2877			num = 1;
2878		}
2879		break;
2880	case I2C_SMBUS_BYTE_DATA:
2881		if (read_write == I2C_SMBUS_READ)
2882			msg[1].len = 1;
2883		else {
2884			msg[0].len = 2;
2885			msgbuf0[1] = data->byte;
2886		}
2887		break;
2888	case I2C_SMBUS_WORD_DATA:
2889		if (read_write == I2C_SMBUS_READ)
2890			msg[1].len = 2;
2891		else {
2892			msg[0].len = 3;
2893			msgbuf0[1] = data->word & 0xff;
2894			msgbuf0[2] = data->word >> 8;
2895		}
2896		break;
2897	case I2C_SMBUS_PROC_CALL:
2898		num = 2; /* Special case */
2899		read_write = I2C_SMBUS_READ;
2900		msg[0].len = 3;
2901		msg[1].len = 2;
2902		msgbuf0[1] = data->word & 0xff;
2903		msgbuf0[2] = data->word >> 8;
2904		break;
2905	case I2C_SMBUS_BLOCK_DATA:
2906		if (read_write == I2C_SMBUS_READ) {
2907			msg[1].flags |= I2C_M_RECV_LEN;
2908			msg[1].len = 1; /* block length will be added by
2909					   the underlying bus driver */
2910		} else {
2911			msg[0].len = data->block[0] + 2;
2912			if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
2913				dev_err(&adapter->dev,
2914					"Invalid block write size %d\n",
2915					data->block[0]);
2916				return -EINVAL;
2917			}
2918			for (i = 1; i < msg[0].len; i++)
2919				msgbuf0[i] = data->block[i-1];
2920		}
2921		break;
2922	case I2C_SMBUS_BLOCK_PROC_CALL:
2923		num = 2; /* Another special case */
2924		read_write = I2C_SMBUS_READ;
2925		if (data->block[0] > I2C_SMBUS_BLOCK_MAX) {
2926			dev_err(&adapter->dev,
2927				"Invalid block write size %d\n",
2928				data->block[0]);
2929			return -EINVAL;
2930		}
2931		msg[0].len = data->block[0] + 2;
2932		for (i = 1; i < msg[0].len; i++)
2933			msgbuf0[i] = data->block[i-1];
2934		msg[1].flags |= I2C_M_RECV_LEN;
2935		msg[1].len = 1; /* block length will be added by
2936				   the underlying bus driver */
2937		break;
2938	case I2C_SMBUS_I2C_BLOCK_DATA:
2939		if (read_write == I2C_SMBUS_READ) {
2940			msg[1].len = data->block[0];
2941		} else {
2942			msg[0].len = data->block[0] + 1;
2943			if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 1) {
2944				dev_err(&adapter->dev,
2945					"Invalid block write size %d\n",
2946					data->block[0]);
2947				return -EINVAL;
2948			}
2949			for (i = 1; i <= data->block[0]; i++)
2950				msgbuf0[i] = data->block[i];
2951		}
2952		break;
2953	default:
2954		dev_err(&adapter->dev, "Unsupported transaction %d\n", size);
2955		return -EOPNOTSUPP;
2956	}
2957
2958	i = ((flags & I2C_CLIENT_PEC) && size != I2C_SMBUS_QUICK
2959				      && size != I2C_SMBUS_I2C_BLOCK_DATA);
2960	if (i) {
2961		/* Compute PEC if first message is a write */
2962		if (!(msg[0].flags & I2C_M_RD)) {
2963			if (num == 1) /* Write only */
2964				i2c_smbus_add_pec(&msg[0]);
2965			else /* Write followed by read */
2966				partial_pec = i2c_smbus_msg_pec(0, &msg[0]);
2967		}
2968		/* Ask for PEC if last message is a read */
2969		if (msg[num-1].flags & I2C_M_RD)
2970			msg[num-1].len++;
2971	}
2972
2973	status = i2c_transfer(adapter, msg, num);
2974	if (status < 0)
2975		return status;
2976
2977	/* Check PEC if last message is a read */
2978	if (i && (msg[num-1].flags & I2C_M_RD)) {
2979		status = i2c_smbus_check_pec(partial_pec, &msg[num-1]);
2980		if (status < 0)
2981			return status;
2982	}
2983
2984	if (read_write == I2C_SMBUS_READ)
2985		switch (size) {
2986		case I2C_SMBUS_BYTE:
2987			data->byte = msgbuf0[0];
2988			break;
2989		case I2C_SMBUS_BYTE_DATA:
2990			data->byte = msgbuf1[0];
2991			break;
2992		case I2C_SMBUS_WORD_DATA:
2993		case I2C_SMBUS_PROC_CALL:
2994			data->word = msgbuf1[0] | (msgbuf1[1] << 8);
2995			break;
2996		case I2C_SMBUS_I2C_BLOCK_DATA:
2997			for (i = 0; i < data->block[0]; i++)
2998				data->block[i+1] = msgbuf1[i];
2999			break;
3000		case I2C_SMBUS_BLOCK_DATA:
3001		case I2C_SMBUS_BLOCK_PROC_CALL:
3002			for (i = 0; i < msgbuf1[0] + 1; i++)
3003				data->block[i] = msgbuf1[i];
3004			break;
3005		}
3006	return 0;
3007}
3008
3009/**
3010 * i2c_smbus_xfer - execute SMBus protocol operations
3011 * @adapter: Handle to I2C bus
3012 * @addr: Address of SMBus slave on that bus
3013 * @flags: I2C_CLIENT_* flags (usually zero or I2C_CLIENT_PEC)
3014 * @read_write: I2C_SMBUS_READ or I2C_SMBUS_WRITE
3015 * @command: Byte interpreted by slave, for protocols which use such bytes
3016 * @protocol: SMBus protocol operation to execute, such as I2C_SMBUS_PROC_CALL
3017 * @data: Data to be read or written
3018 *
3019 * This executes an SMBus protocol operation, and returns a negative
3020 * errno code else zero on success.
3021 */
3022s32 i2c_smbus_xfer(struct i2c_adapter *adapter, u16 addr, unsigned short flags,
3023		   char read_write, u8 command, int protocol,
3024		   union i2c_smbus_data *data)
3025{
3026	unsigned long orig_jiffies;
3027	int try;
3028	s32 res;
3029
3030	/* If enabled, the following two tracepoints are conditional on
3031	 * read_write and protocol.
3032	 */
3033	trace_smbus_write(adapter, addr, flags, read_write,
3034			  command, protocol, data);
3035	trace_smbus_read(adapter, addr, flags, read_write,
3036			 command, protocol);
3037
3038	flags &= I2C_M_TEN | I2C_CLIENT_PEC | I2C_CLIENT_SCCB;
3039
3040	if (adapter->algo->smbus_xfer) {
3041		i2c_lock_adapter(adapter);
3042
3043		/* Retry automatically on arbitration loss */
3044		orig_jiffies = jiffies;
3045		for (res = 0, try = 0; try <= adapter->retries; try++) {
3046			res = adapter->algo->smbus_xfer(adapter, addr, flags,
3047							read_write, command,
3048							protocol, data);
3049			if (res != -EAGAIN)
3050				break;
3051			if (time_after(jiffies,
3052				       orig_jiffies + adapter->timeout))
3053				break;
3054		}
3055		i2c_unlock_adapter(adapter);
3056
3057		if (res != -EOPNOTSUPP || !adapter->algo->master_xfer)
3058			goto trace;
3059		/*
3060		 * Fall back to i2c_smbus_xfer_emulated if the adapter doesn't
3061		 * implement native support for the SMBus operation.
3062		 */
3063	}
3064
3065	res = i2c_smbus_xfer_emulated(adapter, addr, flags, read_write,
3066				      command, protocol, data);
3067
3068trace:
3069	/* If enabled, the reply tracepoint is conditional on read_write. */
3070	trace_smbus_reply(adapter, addr, flags, read_write,
3071			  command, protocol, data);
3072	trace_smbus_result(adapter, addr, flags, read_write,
3073			   command, protocol, res);
3074
3075	return res;
3076}
3077EXPORT_SYMBOL(i2c_smbus_xfer);
3078
3079/**
3080 * i2c_smbus_read_i2c_block_data_or_emulated - read block or emulate
3081 * @client: Handle to slave device
3082 * @command: Byte interpreted by slave
3083 * @length: Size of data block; SMBus allows at most I2C_SMBUS_BLOCK_MAX bytes
3084 * @values: Byte array into which data will be read; big enough to hold
3085 *	the data returned by the slave.  SMBus allows at most
3086 *	I2C_SMBUS_BLOCK_MAX bytes.
3087 *
3088 * This executes the SMBus "block read" protocol if supported by the adapter.
3089 * If block read is not supported, it emulates it using either word or byte
3090 * read protocols depending on availability.
3091 *
3092 * The addresses of the I2C slave device that are accessed with this function
3093 * must be mapped to a linear region, so that a block read will have the same
3094 * effect as a byte read. Before using this function you must double-check
3095 * if the I2C slave does support exchanging a block transfer with a byte
3096 * transfer.
3097 */
3098s32 i2c_smbus_read_i2c_block_data_or_emulated(const struct i2c_client *client,
3099					      u8 command, u8 length, u8 *values)
3100{
3101	u8 i = 0;
3102	int status;
3103
3104	if (length > I2C_SMBUS_BLOCK_MAX)
3105		length = I2C_SMBUS_BLOCK_MAX;
3106
3107	if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
3108		return i2c_smbus_read_i2c_block_data(client, command, length, values);
3109
3110	if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA))
3111		return -EOPNOTSUPP;
3112
3113	if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)) {
3114		while ((i + 2) <= length) {
3115			status = i2c_smbus_read_word_data(client, command + i);
3116			if (status < 0)
3117				return status;
3118			values[i] = status & 0xff;
3119			values[i + 1] = status >> 8;
3120			i += 2;
3121		}
3122	}
3123
3124	while (i < length) {
3125		status = i2c_smbus_read_byte_data(client, command + i);
3126		if (status < 0)
3127			return status;
3128		values[i] = status;
3129		i++;
3130	}
3131
3132	return i;
3133}
3134EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data_or_emulated);
3135
3136#if IS_ENABLED(CONFIG_I2C_SLAVE)
3137int i2c_slave_register(struct i2c_client *client, i2c_slave_cb_t slave_cb)
3138{
3139	int ret;
3140
3141	if (!client || !slave_cb) {
3142		WARN(1, "insufficent data\n");
3143		return -EINVAL;
3144	}
3145
3146	if (!(client->flags & I2C_CLIENT_SLAVE))
3147		dev_warn(&client->dev, "%s: client slave flag not set. You might see address collisions\n",
3148			 __func__);
3149
3150	if (!(client->flags & I2C_CLIENT_TEN)) {
3151		/* Enforce stricter address checking */
3152		ret = i2c_check_7bit_addr_validity_strict(client->addr);
3153		if (ret) {
3154			dev_err(&client->dev, "%s: invalid address\n", __func__);
3155			return ret;
3156		}
3157	}
3158
3159	if (!client->adapter->algo->reg_slave) {
3160		dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3161		return -EOPNOTSUPP;
3162	}
3163
3164	client->slave_cb = slave_cb;
3165
3166	i2c_lock_adapter(client->adapter);
3167	ret = client->adapter->algo->reg_slave(client);
3168	i2c_unlock_adapter(client->adapter);
3169
3170	if (ret) {
3171		client->slave_cb = NULL;
3172		dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3173	}
3174
3175	return ret;
3176}
3177EXPORT_SYMBOL_GPL(i2c_slave_register);
3178
3179int i2c_slave_unregister(struct i2c_client *client)
3180{
3181	int ret;
3182
3183	if (!client->adapter->algo->unreg_slave) {
3184		dev_err(&client->dev, "%s: not supported by adapter\n", __func__);
3185		return -EOPNOTSUPP;
3186	}
3187
3188	i2c_lock_adapter(client->adapter);
3189	ret = client->adapter->algo->unreg_slave(client);
3190	i2c_unlock_adapter(client->adapter);
3191
3192	if (ret == 0)
3193		client->slave_cb = NULL;
3194	else
3195		dev_err(&client->dev, "%s: adapter returned error %d\n", __func__, ret);
3196
3197	return ret;
3198}
3199EXPORT_SYMBOL_GPL(i2c_slave_unregister);
3200#endif
3201
3202MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
3203MODULE_DESCRIPTION("I2C-Bus main module");
3204MODULE_LICENSE("GPL");
3205