PageRenderTime 114ms CodeModel.GetById 12ms app.highlight 85ms RepoModel.GetById 2ms app.codeStats 0ms

/drivers/i2c/i2c-core.c

http://github.com/mirrors/linux
C | 3409 lines | 2286 code | 523 blank | 600 comment | 439 complexity | d25163411f21d600ab4a7d548aa78732 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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#define pr_fmt(fmt) "i2c-core: " fmt
  31
  32#include <dt-bindings/i2c/i2c.h>
  33#include <asm/uaccess.h>
  34#include <linux/acpi.h>
  35#include <linux/clk/clk-conf.h>
  36#include <linux/completion.h>
  37#include <linux/delay.h>
  38#include <linux/err.h>
  39#include <linux/errno.h>
  40#include <linux/gpio.h>
  41#include <linux/hardirq.h>
  42#include <linux/i2c.h>
  43#include <linux/idr.h>
  44#include <linux/init.h>
  45#include <linux/irqflags.h>
  46#include <linux/jump_label.h>
  47#include <linux/kernel.h>
  48#include <linux/module.h>
  49#include <linux/mutex.h>
  50#include <linux/of_device.h>
  51#include <linux/of.h>
  52#include <linux/of_irq.h>
  53#include <linux/pm_domain.h>
  54#include <linux/pm_runtime.h>
  55#include <linux/pm_wakeirq.h>
  56#include <linux/property.h>
  57#include <linux/rwsem.h>
  58#include <linux/slab.h>
  59
  60#include "i2c-core.h"
  61
  62#define CREATE_TRACE_POINTS
  63#include <trace/events/i2c.h>
  64
  65#define I2C_ADDR_OFFSET_TEN_BIT	0xa000
  66#define I2C_ADDR_OFFSET_SLAVE	0x1000
  67
  68/* core_lock protects i2c_adapter_idr, and guarantees
  69   that device detection, deletion of detected devices, and attach_adapter
  70   calls are serialized */
  71static DEFINE_MUTEX(core_lock);
  72static DEFINE_IDR(i2c_adapter_idr);
  73
  74static struct device_type i2c_client_type;
  75static int i2c_detect(struct i2c_adapter *adapter, struct i2c_driver *driver);
  76
  77static struct static_key i2c_trace_msg = STATIC_KEY_INIT_FALSE;
  78static bool is_registered;
  79
  80void i2c_transfer_trace_reg(void)
  81{
  82	static_key_slow_inc(&i2c_trace_msg);
  83}
  84
  85void i2c_transfer_trace_unreg(void)
  86{
  87	static_key_slow_dec(&i2c_trace_msg);
  88}
  89
  90#if defined(CONFIG_ACPI)
  91struct acpi_i2c_handler_data {
  92	struct acpi_connection_info info;
  93	struct i2c_adapter *adapter;
  94};
  95
  96struct gsb_buffer {
  97	u8	status;
  98	u8	len;
  99	union {
 100		u16	wdata;
 101		u8	bdata;
 102		u8	data[0];
 103	};
 104} __packed;
 105
 106struct acpi_i2c_lookup {
 107	struct i2c_board_info *info;
 108	acpi_handle adapter_handle;
 109	acpi_handle device_handle;
 110};
 111
 112static int acpi_i2c_fill_info(struct acpi_resource *ares, void *data)
 113{
 114	struct acpi_i2c_lookup *lookup = data;
 115	struct i2c_board_info *info = lookup->info;
 116	struct acpi_resource_i2c_serialbus *sb;
 117	acpi_status status;
 118
 119	if (info->addr || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
 120		return 1;
 121
 122	sb = &ares->data.i2c_serial_bus;
 123	if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C)
 124		return 1;
 125
 126	status = acpi_get_handle(lookup->device_handle,
 127				 sb->resource_source.string_ptr,
 128				 &lookup->adapter_handle);
 129	if (!ACPI_SUCCESS(status))
 130		return 1;
 131
 132	info->addr = sb->slave_address;
 133	if (sb->access_mode == ACPI_I2C_10BIT_MODE)
 134		info->flags |= I2C_CLIENT_TEN;
 135
 136	return 1;
 137}
 138
 139static int acpi_i2c_get_info(struct acpi_device *adev,
 140			     struct i2c_board_info *info,
 141			     acpi_handle *adapter_handle)
 142{
 143	struct list_head resource_list;
 144	struct resource_entry *entry;
 145	struct acpi_i2c_lookup lookup;
 146	int ret;
 147
 148	if (acpi_bus_get_status(adev) || !adev->status.present ||
 149	    acpi_device_enumerated(adev))
 150		return -EINVAL;
 151
 152	memset(info, 0, sizeof(*info));
 153	info->fwnode = acpi_fwnode_handle(adev);
 154
 155	memset(&lookup, 0, sizeof(lookup));
 156	lookup.device_handle = acpi_device_handle(adev);
 157	lookup.info = info;
 158
 159	/* Look up for I2cSerialBus resource */
 160	INIT_LIST_HEAD(&resource_list);
 161	ret = acpi_dev_get_resources(adev, &resource_list,
 162				     acpi_i2c_fill_info, &lookup);
 163	acpi_dev_free_resource_list(&resource_list);
 164
 165	if (ret < 0 || !info->addr)
 166		return -EINVAL;
 167
 168	*adapter_handle = lookup.adapter_handle;
 169
 170	/* Then fill IRQ number if any */
 171	ret = acpi_dev_get_resources(adev, &resource_list, NULL, NULL);
 172	if (ret < 0)
 173		return -EINVAL;
 174
 175	resource_list_for_each_entry(entry, &resource_list) {
 176		if (resource_type(entry->res) == IORESOURCE_IRQ) {
 177			info->irq = entry->res->start;
 178			break;
 179		}
 180	}
 181
 182	acpi_dev_free_resource_list(&resource_list);
 183
 184	strlcpy(info->type, dev_name(&adev->dev), sizeof(info->type));
 185
 186	return 0;
 187}
 188
 189static void acpi_i2c_register_device(struct i2c_adapter *adapter,
 190				     struct acpi_device *adev,
 191				     struct i2c_board_info *info)
 192{
 193	adev->power.flags.ignore_parent = true;
 194	acpi_device_set_enumerated(adev);
 195
 196	if (!i2c_new_device(adapter, info)) {
 197		adev->power.flags.ignore_parent = false;
 198		dev_err(&adapter->dev,
 199			"failed to add I2C device %s from ACPI\n",
 200			dev_name(&adev->dev));
 201	}
 202}
 203
 204static acpi_status acpi_i2c_add_device(acpi_handle handle, u32 level,
 205				       void *data, void **return_value)
 206{
 207	struct i2c_adapter *adapter = data;
 208	struct acpi_device *adev;
 209	acpi_handle adapter_handle;
 210	struct i2c_board_info info;
 211
 212	if (acpi_bus_get_device(handle, &adev))
 213		return AE_OK;
 214
 215	if (acpi_i2c_get_info(adev, &info, &adapter_handle))
 216		return AE_OK;
 217
 218	if (adapter_handle != ACPI_HANDLE(&adapter->dev))
 219		return AE_OK;
 220
 221	acpi_i2c_register_device(adapter, adev, &info);
 222
 223	return AE_OK;
 224}
 225
 226#define ACPI_I2C_MAX_SCAN_DEPTH 32
 227
 228/**
 229 * acpi_i2c_register_devices - enumerate I2C slave devices behind adapter
 230 * @adap: pointer to adapter
 231 *
 232 * Enumerate all I2C slave devices behind this adapter by walking the ACPI
 233 * namespace. When a device is found it will be added to the Linux device
 234 * model and bound to the corresponding ACPI handle.
 235 */
 236static void acpi_i2c_register_devices(struct i2c_adapter *adap)
 237{
 238	acpi_status status;
 239
 240	if (!has_acpi_companion(&adap->dev))
 241		return;
 242
 243	status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
 244				     ACPI_I2C_MAX_SCAN_DEPTH,
 245				     acpi_i2c_add_device, NULL,
 246				     adap, NULL);
 247	if (ACPI_FAILURE(status))
 248		dev_warn(&adap->dev, "failed to enumerate I2C slaves\n");
 249}
 250
 251static int acpi_i2c_match_adapter(struct device *dev, void *data)
 252{
 253	struct i2c_adapter *adapter = i2c_verify_adapter(dev);
 254
 255	if (!adapter)
 256		return 0;
 257
 258	return ACPI_HANDLE(dev) == (acpi_handle)data;
 259}
 260
 261static int acpi_i2c_match_device(struct device *dev, void *data)
 262{
 263	return ACPI_COMPANION(dev) == data;
 264}
 265
 266static struct i2c_adapter *acpi_i2c_find_adapter_by_handle(acpi_handle handle)
 267{
 268	struct device *dev;
 269
 270	dev = bus_find_device(&i2c_bus_type, NULL, handle,
 271			      acpi_i2c_match_adapter);
 272	return dev ? i2c_verify_adapter(dev) : NULL;
 273}
 274
 275static struct i2c_client *acpi_i2c_find_client_by_adev(struct acpi_device *adev)
 276{
 277	struct device *dev;
 278
 279	dev = bus_find_device(&i2c_bus_type, NULL, adev, acpi_i2c_match_device);
 280	return dev ? i2c_verify_client(dev) : NULL;
 281}
 282
 283static int acpi_i2c_notify(struct notifier_block *nb, unsigned long value,
 284			   void *arg)
 285{
 286	struct acpi_device *adev = arg;
 287	struct i2c_board_info info;
 288	acpi_handle adapter_handle;
 289	struct i2c_adapter *adapter;
 290	struct i2c_client *client;
 291
 292	switch (value) {
 293	case ACPI_RECONFIG_DEVICE_ADD:
 294		if (acpi_i2c_get_info(adev, &info, &adapter_handle))
 295			break;
 296
 297		adapter = acpi_i2c_find_adapter_by_handle(adapter_handle);
 298		if (!adapter)
 299			break;
 300
 301		acpi_i2c_register_device(adapter, adev, &info);
 302		break;
 303	case ACPI_RECONFIG_DEVICE_REMOVE:
 304		if (!acpi_device_enumerated(adev))
 305			break;
 306
 307		client = acpi_i2c_find_client_by_adev(adev);
 308		if (!client)
 309			break;
 310
 311		i2c_unregister_device(client);
 312		put_device(&client->dev);
 313		break;
 314	}
 315
 316	return NOTIFY_OK;
 317}
 318
 319static struct notifier_block i2c_acpi_notifier = {
 320	.notifier_call = acpi_i2c_notify,
 321};
 322#else /* CONFIG_ACPI */
 323static inline void acpi_i2c_register_devices(struct i2c_adapter *adap) { }
 324extern struct notifier_block i2c_acpi_notifier;
 325#endif /* CONFIG_ACPI */
 326
 327#ifdef CONFIG_ACPI_I2C_OPREGION
 328static int acpi_gsb_i2c_read_bytes(struct i2c_client *client,
 329		u8 cmd, u8 *data, u8 data_len)
 330{
 331
 332	struct i2c_msg msgs[2];
 333	int ret;
 334	u8 *buffer;
 335
 336	buffer = kzalloc(data_len, GFP_KERNEL);
 337	if (!buffer)
 338		return AE_NO_MEMORY;
 339
 340	msgs[0].addr = client->addr;
 341	msgs[0].flags = client->flags;
 342	msgs[0].len = 1;
 343	msgs[0].buf = &cmd;
 344
 345	msgs[1].addr = client->addr;
 346	msgs[1].flags = client->flags | I2C_M_RD;
 347	msgs[1].len = data_len;
 348	msgs[1].buf = buffer;
 349
 350	ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
 351	if (ret < 0)
 352		dev_err(&client->adapter->dev, "i2c read failed\n");
 353	else
 354		memcpy(data, buffer, data_len);
 355
 356	kfree(buffer);
 357	return ret;
 358}
 359
 360static int acpi_gsb_i2c_write_bytes(struct i2c_client *client,
 361		u8 cmd, u8 *data, u8 data_len)
 362{
 363
 364	struct i2c_msg msgs[1];
 365	u8 *buffer;
 366	int ret = AE_OK;
 367
 368	buffer = kzalloc(data_len + 1, GFP_KERNEL);
 369	if (!buffer)
 370		return AE_NO_MEMORY;
 371
 372	buffer[0] = cmd;
 373	memcpy(buffer + 1, data, data_len);
 374
 375	msgs[0].addr = client->addr;
 376	msgs[0].flags = client->flags;
 377	msgs[0].len = data_len + 1;
 378	msgs[0].buf = buffer;
 379
 380	ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
 381	if (ret < 0)
 382		dev_err(&client->adapter->dev, "i2c write failed\n");
 383
 384	kfree(buffer);
 385	return ret;
 386}
 387
 388static acpi_status
 389acpi_i2c_space_handler(u32 function, acpi_physical_address command,
 390			u32 bits, u64 *value64,
 391			void *handler_context, void *region_context)
 392{
 393	struct gsb_buffer *gsb = (struct gsb_buffer *)value64;
 394	struct acpi_i2c_handler_data *data = handler_context;
 395	struct acpi_connection_info *info = &data->info;
 396	struct acpi_resource_i2c_serialbus *sb;
 397	struct i2c_adapter *adapter = data->adapter;
 398	struct i2c_client *client;
 399	struct acpi_resource *ares;
 400	u32 accessor_type = function >> 16;
 401	u8 action = function & ACPI_IO_MASK;
 402	acpi_status ret;
 403	int status;
 404
 405	ret = acpi_buffer_to_resource(info->connection, info->length, &ares);
 406	if (ACPI_FAILURE(ret))
 407		return ret;
 408
 409	client = kzalloc(sizeof(*client), GFP_KERNEL);
 410	if (!client) {
 411		ret = AE_NO_MEMORY;
 412		goto err;
 413	}
 414
 415	if (!value64 || ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS) {
 416		ret = AE_BAD_PARAMETER;
 417		goto err;
 418	}
 419
 420	sb = &ares->data.i2c_serial_bus;
 421	if (sb->type != ACPI_RESOURCE_SERIAL_TYPE_I2C) {
 422		ret = AE_BAD_PARAMETER;
 423		goto err;
 424	}
 425
 426	client->adapter = adapter;
 427	client->addr = sb->slave_address;
 428
 429	if (sb->access_mode == ACPI_I2C_10BIT_MODE)
 430		client->flags |= I2C_CLIENT_TEN;
 431
 432	switch (accessor_type) {
 433	case ACPI_GSB_ACCESS_ATTRIB_SEND_RCV:
 434		if (action == ACPI_READ) {
 435			status = i2c_smbus_read_byte(client);
 436			if (status >= 0) {
 437				gsb->bdata = status;
 438				status = 0;
 439			}
 440		} else {
 441			status = i2c_smbus_write_byte(client, gsb->bdata);
 442		}
 443		break;
 444
 445	case ACPI_GSB_ACCESS_ATTRIB_BYTE:
 446		if (action == ACPI_READ) {
 447			status = i2c_smbus_read_byte_data(client, command);
 448			if (status >= 0) {
 449				gsb->bdata = status;
 450				status = 0;
 451			}
 452		} else {
 453			status = i2c_smbus_write_byte_data(client, command,
 454					gsb->bdata);
 455		}
 456		break;
 457
 458	case ACPI_GSB_ACCESS_ATTRIB_WORD:
 459		if (action == ACPI_READ) {
 460			status = i2c_smbus_read_word_data(client, command);
 461			if (status >= 0) {
 462				gsb->wdata = status;
 463				status = 0;
 464			}
 465		} else {
 466			status = i2c_smbus_write_word_data(client, command,
 467					gsb->wdata);
 468		}
 469		break;
 470
 471	case ACPI_GSB_ACCESS_ATTRIB_BLOCK:
 472		if (action == ACPI_READ) {
 473			status = i2c_smbus_read_block_data(client, command,
 474					gsb->data);
 475			if (status >= 0) {
 476				gsb->len = status;
 477				status = 0;
 478			}
 479		} else {
 480			status = i2c_smbus_write_block_data(client, command,
 481					gsb->len, gsb->data);
 482		}
 483		break;
 484
 485	case ACPI_GSB_ACCESS_ATTRIB_MULTIBYTE:
 486		if (action == ACPI_READ) {
 487			status = acpi_gsb_i2c_read_bytes(client, command,
 488					gsb->data, info->access_length);
 489			if (status > 0)
 490				status = 0;
 491		} else {
 492			status = acpi_gsb_i2c_write_bytes(client, command,
 493					gsb->data, info->access_length);
 494		}
 495		break;
 496
 497	default:
 498		dev_warn(&adapter->dev, "protocol 0x%02x not supported for client 0x%02x\n",
 499			 accessor_type, client->addr);
 500		ret = AE_BAD_PARAMETER;
 501		goto err;
 502	}
 503
 504	gsb->status = status;
 505
 506 err:
 507	kfree(client);
 508	ACPI_FREE(ares);
 509	return ret;
 510}
 511
 512
 513static int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
 514{
 515	acpi_handle handle;
 516	struct acpi_i2c_handler_data *data;
 517	acpi_status status;
 518
 519	if (!adapter->dev.parent)
 520		return -ENODEV;
 521
 522	handle = ACPI_HANDLE(adapter->dev.parent);
 523
 524	if (!handle)
 525		return -ENODEV;
 526
 527	data = kzalloc(sizeof(struct acpi_i2c_handler_data),
 528			    GFP_KERNEL);
 529	if (!data)
 530		return -ENOMEM;
 531
 532	data->adapter = adapter;
 533	status = acpi_bus_attach_private_data(handle, (void *)data);
 534	if (ACPI_FAILURE(status)) {
 535		kfree(data);
 536		return -ENOMEM;
 537	}
 538
 539	status = acpi_install_address_space_handler(handle,
 540				ACPI_ADR_SPACE_GSBUS,
 541				&acpi_i2c_space_handler,
 542				NULL,
 543				data);
 544	if (ACPI_FAILURE(status)) {
 545		dev_err(&adapter->dev, "Error installing i2c space handler\n");
 546		acpi_bus_detach_private_data(handle);
 547		kfree(data);
 548		return -ENOMEM;
 549	}
 550
 551	acpi_walk_dep_device_list(handle);
 552	return 0;
 553}
 554
 555static void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
 556{
 557	acpi_handle handle;
 558	struct acpi_i2c_handler_data *data;
 559	acpi_status status;
 560
 561	if (!adapter->dev.parent)
 562		return;
 563
 564	handle = ACPI_HANDLE(adapter->dev.parent);
 565
 566	if (!handle)
 567		return;
 568
 569	acpi_remove_address_space_handler(handle,
 570				ACPI_ADR_SPACE_GSBUS,
 571				&acpi_i2c_space_handler);
 572
 573	status = acpi_bus_get_private_data(handle, (void **)&data);
 574	if (ACPI_SUCCESS(status))
 575		kfree(data);
 576
 577	acpi_bus_detach_private_data(handle);
 578}
 579#else /* CONFIG_ACPI_I2C_OPREGION */
 580static inline void acpi_i2c_remove_space_handler(struct i2c_adapter *adapter)
 581{ }
 582
 583static inline int acpi_i2c_install_space_handler(struct i2c_adapter *adapter)
 584{ return 0; }
 585#endif /* CONFIG_ACPI_I2C_OPREGION */
 586
 587/* ------------------------------------------------------------------------- */
 588
 589static const struct i2c_device_id *i2c_match_id(const struct i2c_device_id *id,
 590						const struct i2c_client *client)
 591{
 592	while (id->name[0]) {
 593		if (strcmp(client->name, id->name) == 0)
 594			return id;
 595		id++;
 596	}
 597	return NULL;
 598}
 599
 600static int i2c_device_match(struct device *dev, struct device_driver *drv)
 601{
 602	struct i2c_client	*client = i2c_verify_client(dev);
 603	struct i2c_driver	*driver;
 604
 605	if (!client)
 606		return 0;
 607
 608	/* Attempt an OF style match */
 609	if (of_driver_match_device(dev, drv))
 610		return 1;
 611
 612	/* Then ACPI style match */
 613	if (acpi_driver_match_device(dev, drv))
 614		return 1;
 615
 616	driver = to_i2c_driver(drv);
 617	/* match on an id table if there is one */
 618	if (driver->id_table)
 619		return i2c_match_id(driver->id_table, client) != NULL;
 620
 621	return 0;
 622}
 623
 624static int i2c_device_uevent(struct device *dev, struct kobj_uevent_env *env)
 625{
 626	struct i2c_client *client = to_i2c_client(dev);
 627	int rc;
 628
 629	rc = acpi_device_uevent_modalias(dev, env);
 630	if (rc != -ENODEV)
 631		return rc;
 632
 633	return add_uevent_var(env, "MODALIAS=%s%s", I2C_MODULE_PREFIX, client->name);
 634}
 635
 636/* i2c bus recovery routines */
 637static int get_scl_gpio_value(struct i2c_adapter *adap)
 638{
 639	return gpio_get_value(adap->bus_recovery_info->scl_gpio);
 640}
 641
 642static void set_scl_gpio_value(struct i2c_adapter *adap, int val)
 643{
 644	gpio_set_value(adap->bus_recovery_info->scl_gpio, val);
 645}
 646
 647static int get_sda_gpio_value(struct i2c_adapter *adap)
 648{
 649	return gpio_get_value(adap->bus_recovery_info->sda_gpio);
 650}
 651
 652static int i2c_get_gpios_for_recovery(struct i2c_adapter *adap)
 653{
 654	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 655	struct device *dev = &adap->dev;
 656	int ret = 0;
 657
 658	ret = gpio_request_one(bri->scl_gpio, GPIOF_OPEN_DRAIN |
 659			GPIOF_OUT_INIT_HIGH, "i2c-scl");
 660	if (ret) {
 661		dev_warn(dev, "Can't get SCL gpio: %d\n", bri->scl_gpio);
 662		return ret;
 663	}
 664
 665	if (bri->get_sda) {
 666		if (gpio_request_one(bri->sda_gpio, GPIOF_IN, "i2c-sda")) {
 667			/* work without SDA polling */
 668			dev_warn(dev, "Can't get SDA gpio: %d. Not using SDA polling\n",
 669					bri->sda_gpio);
 670			bri->get_sda = NULL;
 671		}
 672	}
 673
 674	return ret;
 675}
 676
 677static void i2c_put_gpios_for_recovery(struct i2c_adapter *adap)
 678{
 679	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 680
 681	if (bri->get_sda)
 682		gpio_free(bri->sda_gpio);
 683
 684	gpio_free(bri->scl_gpio);
 685}
 686
 687/*
 688 * We are generating clock pulses. ndelay() determines durating of clk pulses.
 689 * We will generate clock with rate 100 KHz and so duration of both clock levels
 690 * is: delay in ns = (10^6 / 100) / 2
 691 */
 692#define RECOVERY_NDELAY		5000
 693#define RECOVERY_CLK_CNT	9
 694
 695static int i2c_generic_recovery(struct i2c_adapter *adap)
 696{
 697	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 698	int i = 0, val = 1, ret = 0;
 699
 700	if (bri->prepare_recovery)
 701		bri->prepare_recovery(adap);
 702
 703	bri->set_scl(adap, val);
 704	ndelay(RECOVERY_NDELAY);
 705
 706	/*
 707	 * By this time SCL is high, as we need to give 9 falling-rising edges
 708	 */
 709	while (i++ < RECOVERY_CLK_CNT * 2) {
 710		if (val) {
 711			/* Break if SDA is high */
 712			if (bri->get_sda && bri->get_sda(adap))
 713					break;
 714			/* SCL shouldn't be low here */
 715			if (!bri->get_scl(adap)) {
 716				dev_err(&adap->dev,
 717					"SCL is stuck low, exit recovery\n");
 718				ret = -EBUSY;
 719				break;
 720			}
 721		}
 722
 723		val = !val;
 724		bri->set_scl(adap, val);
 725		ndelay(RECOVERY_NDELAY);
 726	}
 727
 728	if (bri->unprepare_recovery)
 729		bri->unprepare_recovery(adap);
 730
 731	return ret;
 732}
 733
 734int i2c_generic_scl_recovery(struct i2c_adapter *adap)
 735{
 736	return i2c_generic_recovery(adap);
 737}
 738EXPORT_SYMBOL_GPL(i2c_generic_scl_recovery);
 739
 740int i2c_generic_gpio_recovery(struct i2c_adapter *adap)
 741{
 742	int ret;
 743
 744	ret = i2c_get_gpios_for_recovery(adap);
 745	if (ret)
 746		return ret;
 747
 748	ret = i2c_generic_recovery(adap);
 749	i2c_put_gpios_for_recovery(adap);
 750
 751	return ret;
 752}
 753EXPORT_SYMBOL_GPL(i2c_generic_gpio_recovery);
 754
 755int i2c_recover_bus(struct i2c_adapter *adap)
 756{
 757	if (!adap->bus_recovery_info)
 758		return -EOPNOTSUPP;
 759
 760	dev_dbg(&adap->dev, "Trying i2c bus recovery\n");
 761	return adap->bus_recovery_info->recover_bus(adap);
 762}
 763EXPORT_SYMBOL_GPL(i2c_recover_bus);
 764
 765static void i2c_init_recovery(struct i2c_adapter *adap)
 766{
 767	struct i2c_bus_recovery_info *bri = adap->bus_recovery_info;
 768	char *err_str;
 769
 770	if (!bri)
 771		return;
 772
 773	if (!bri->recover_bus) {
 774		err_str = "no recover_bus() found";
 775		goto err;
 776	}
 777
 778	/* Generic GPIO recovery */
 779	if (bri->recover_bus == i2c_generic_gpio_recovery) {
 780		if (!gpio_is_valid(bri->scl_gpio)) {
 781			err_str = "invalid SCL gpio";
 782			goto err;
 783		}
 784
 785		if (gpio_is_valid(bri->sda_gpio))
 786			bri->get_sda = get_sda_gpio_value;
 787		else
 788			bri->get_sda = NULL;
 789
 790		bri->get_scl = get_scl_gpio_value;
 791		bri->set_scl = set_scl_gpio_value;
 792	} else if (bri->recover_bus == i2c_generic_scl_recovery) {
 793		/* Generic SCL recovery */
 794		if (!bri->set_scl || !bri->get_scl) {
 795			err_str = "no {get|set}_scl() found";
 796			goto err;
 797		}
 798	}
 799
 800	return;
 801 err:
 802	dev_err(&adap->dev, "Not using recovery: %s\n", err_str);
 803	adap->bus_recovery_info = NULL;
 804}
 805
 806static int i2c_device_probe(struct device *dev)
 807{
 808	struct i2c_client	*client = i2c_verify_client(dev);
 809	struct i2c_driver	*driver;
 810	int status;
 811
 812	if (!client)
 813		return 0;
 814
 815	if (!client->irq) {
 816		int irq = -ENOENT;
 817
 818		if (dev->of_node) {
 819			irq = of_irq_get_byname(dev->of_node, "irq");
 820			if (irq == -EINVAL || irq == -ENODATA)
 821				irq = of_irq_get(dev->of_node, 0);
 822		} else if (ACPI_COMPANION(dev)) {
 823			irq = acpi_dev_gpio_irq_get(ACPI_COMPANION(dev), 0);
 824		}
 825		if (irq == -EPROBE_DEFER)
 826			return irq;
 827		if (irq < 0)
 828			irq = 0;
 829
 830		client->irq = irq;
 831	}
 832
 833	driver = to_i2c_driver(dev->driver);
 834	if (!driver->probe || !driver->id_table)
 835		return -ENODEV;
 836
 837	if (client->flags & I2C_CLIENT_WAKE) {
 838		int wakeirq = -ENOENT;
 839
 840		if (dev->of_node) {
 841			wakeirq = of_irq_get_byname(dev->of_node, "wakeup");
 842			if (wakeirq == -EPROBE_DEFER)
 843				return wakeirq;
 844		}
 845
 846		device_init_wakeup(&client->dev, true);
 847
 848		if (wakeirq > 0 && wakeirq != client->irq)
 849			status = dev_pm_set_dedicated_wake_irq(dev, wakeirq);
 850		else if (client->irq > 0)
 851			status = dev_pm_set_wake_irq(dev, client->irq);
 852		else
 853			status = 0;
 854
 855		if (status)
 856			dev_warn(&client->dev, "failed to set up wakeup irq");
 857	}
 858
 859	dev_dbg(dev, "probe\n");
 860
 861	status = of_clk_set_defaults(dev->of_node, false);
 862	if (status < 0)
 863		goto err_clear_wakeup_irq;
 864
 865	status = dev_pm_domain_attach(&client->dev, true);
 866	if (status == -EPROBE_DEFER)
 867		goto err_clear_wakeup_irq;
 868
 869	status = driver->probe(client, i2c_match_id(driver->id_table, client));
 870	if (status)
 871		goto err_detach_pm_domain;
 872
 873	return 0;
 874
 875err_detach_pm_domain:
 876	dev_pm_domain_detach(&client->dev, true);
 877err_clear_wakeup_irq:
 878	dev_pm_clear_wake_irq(&client->dev);
 879	device_init_wakeup(&client->dev, false);
 880	return status;
 881}
 882
 883static int i2c_device_remove(struct device *dev)
 884{
 885	struct i2c_client	*client = i2c_verify_client(dev);
 886	struct i2c_driver	*driver;
 887	int status = 0;
 888
 889	if (!client || !dev->driver)
 890		return 0;
 891
 892	driver = to_i2c_driver(dev->driver);
 893	if (driver->remove) {
 894		dev_dbg(dev, "remove\n");
 895		status = driver->remove(client);
 896	}
 897
 898	dev_pm_domain_detach(&client->dev, true);
 899
 900	dev_pm_clear_wake_irq(&client->dev);
 901	device_init_wakeup(&client->dev, false);
 902
 903	return status;
 904}
 905
 906static void i2c_device_shutdown(struct device *dev)
 907{
 908	struct i2c_client *client = i2c_verify_client(dev);
 909	struct i2c_driver *driver;
 910
 911	if (!client || !dev->driver)
 912		return;
 913	driver = to_i2c_driver(dev->driver);
 914	if (driver->shutdown)
 915		driver->shutdown(client);
 916}
 917
 918static void i2c_client_dev_release(struct device *dev)
 919{
 920	kfree(to_i2c_client(dev));
 921}
 922
 923static ssize_t
 924show_name(struct device *dev, struct device_attribute *attr, char *buf)
 925{
 926	return sprintf(buf, "%s\n", dev->type == &i2c_client_type ?
 927		       to_i2c_client(dev)->name : to_i2c_adapter(dev)->name);
 928}
 929static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
 930
 931static ssize_t
 932show_modalias(struct device *dev, struct device_attribute *attr, char *buf)
 933{
 934	struct i2c_client *client = to_i2c_client(dev);
 935	int len;
 936
 937	len = acpi_device_modalias(dev, buf, PAGE_SIZE -1);
 938	if (len != -ENODEV)
 939		return len;
 940
 941	return sprintf(buf, "%s%s\n", I2C_MODULE_PREFIX, client->name);
 942}
 943static DEVICE_ATTR(modalias, S_IRUGO, show_modalias, NULL);
 944
 945static struct attribute *i2c_dev_attrs[] = {
 946	&dev_attr_name.attr,
 947	/* modalias helps coldplug:  modprobe $(cat .../modalias) */
 948	&dev_attr_modalias.attr,
 949	NULL
 950};
 951ATTRIBUTE_GROUPS(i2c_dev);
 952
 953struct bus_type i2c_bus_type = {
 954	.name		= "i2c",
 955	.match		= i2c_device_match,
 956	.probe		= i2c_device_probe,
 957	.remove		= i2c_device_remove,
 958	.shutdown	= i2c_device_shutdown,
 959};
 960EXPORT_SYMBOL_GPL(i2c_bus_type);
 961
 962static struct device_type i2c_client_type = {
 963	.groups		= i2c_dev_groups,
 964	.uevent		= i2c_device_uevent,
 965	.release	= i2c_client_dev_release,
 966};
 967
 968
 969/**
 970 * i2c_verify_client - return parameter as i2c_client, or NULL
 971 * @dev: device, probably from some driver model iterator
 972 *
 973 * When traversing the driver model tree, perhaps using driver model
 974 * iterators like @device_for_each_child(), you can't assume very much
 975 * about the nodes you find.  Use this function to avoid oopses caused
 976 * by wrongly treating some non-I2C device as an i2c_client.
 977 */
 978struct i2c_client *i2c_verify_client(struct device *dev)
 979{
 980	return (dev->type == &i2c_client_type)
 981			? to_i2c_client(dev)
 982			: NULL;
 983}
 984EXPORT_SYMBOL(i2c_verify_client);
 985
 986
 987/* Return a unique address which takes the flags of the client into account */
 988static unsigned short i2c_encode_flags_to_addr(struct i2c_client *client)
 989{
 990	unsigned short addr = client->addr;
 991
 992	/* For some client flags, add an arbitrary offset to avoid collisions */
 993	if (client->flags & I2C_CLIENT_TEN)
 994		addr |= I2C_ADDR_OFFSET_TEN_BIT;
 995
 996	if (client->flags & I2C_CLIENT_SLAVE)
 997		addr |= I2C_ADDR_OFFSET_SLAVE;
 998
 999	return addr;
1000}
1001
1002/* This is a permissive address validity check, I2C address map constraints
1003 * are purposely not enforced, except for the general call address. */
1004static int i2c_check_addr_validity(unsigned addr, unsigned short flags)
1005{
1006	if (flags & I2C_CLIENT_TEN) {
1007		/* 10-bit address, all values are valid */
1008		if (addr > 0x3ff)
1009			return -EINVAL;
1010	} else {
1011		/* 7-bit address, reject the general call address */
1012		if (addr == 0x00 || addr > 0x7f)
1013			return -EINVAL;
1014	}
1015	return 0;
1016}
1017
1018/* And this is a strict address validity check, used when probing. If a
1019 * device uses a reserved address, then it shouldn't be probed. 7-bit
1020 * addressing is assumed, 10-bit address devices are rare and should be
1021 * explicitly enumerated. */
1022static int i2c_check_7bit_addr_validity_strict(unsigned short addr)
1023{
1024	/*
1025	 * Reserved addresses per I2C specification:
1026	 *  0x00       General call address / START byte
1027	 *  0x01       CBUS address
1028	 *  0x02       Reserved for different bus format
1029	 *  0x03       Reserved for future purposes
1030	 *  0x04-0x07  Hs-mode master code
1031	 *  0x78-0x7b  10-bit slave addressing
1032	 *  0x7c-0x7f  Reserved for future purposes
1033	 */
1034	if (addr < 0x08 || addr > 0x77)
1035		return -EINVAL;
1036	return 0;
1037}
1038
1039static int __i2c_check_addr_busy(struct device *dev, void *addrp)
1040{
1041	struct i2c_client	*client = i2c_verify_client(dev);
1042	int			addr = *(int *)addrp;
1043
1044	if (client && i2c_encode_flags_to_addr(client) == addr)
1045		return -EBUSY;
1046	return 0;
1047}
1048
1049/* walk up mux tree */
1050static int i2c_check_mux_parents(struct i2c_adapter *adapter, int addr)
1051{
1052	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1053	int result;
1054
1055	result = device_for_each_child(&adapter->dev, &addr,
1056					__i2c_check_addr_busy);
1057
1058	if (!result && parent)
1059		result = i2c_check_mux_parents(parent, addr);
1060
1061	return result;
1062}
1063
1064/* recurse down mux tree */
1065static int i2c_check_mux_children(struct device *dev, void *addrp)
1066{
1067	int result;
1068
1069	if (dev->type == &i2c_adapter_type)
1070		result = device_for_each_child(dev, addrp,
1071						i2c_check_mux_children);
1072	else
1073		result = __i2c_check_addr_busy(dev, addrp);
1074
1075	return result;
1076}
1077
1078static int i2c_check_addr_busy(struct i2c_adapter *adapter, int addr)
1079{
1080	struct i2c_adapter *parent = i2c_parent_is_i2c_adapter(adapter);
1081	int result = 0;
1082
1083	if (parent)
1084		result = i2c_check_mux_parents(parent, addr);
1085
1086	if (!result)
1087		result = device_for_each_child(&adapter->dev, &addr,
1088						i2c_check_mux_children);
1089
1090	return result;
1091}
1092
1093/**
1094 * i2c_adapter_lock_bus - Get exclusive access to an I2C bus segment
1095 * @adapter: Target I2C bus segment
1096 * @flags: I2C_LOCK_ROOT_ADAPTER locks the root i2c adapter, I2C_LOCK_SEGMENT
1097 *	locks only this branch in the adapter tree
1098 */
1099static void i2c_adapter_lock_bus(struct i2c_adapter *adapter,
1100				 unsigned int flags)
1101{
1102	rt_mutex_lock(&adapter->bus_lock);
1103}
1104
1105/**
1106 * i2c_adapter_trylock_bus - Try to get exclusive access to an I2C bus segment
1107 * @adapter: Target I2C bus segment
1108 * @flags: I2C_LOCK_ROOT_ADAPTER trylocks the root i2c adapter, I2C_LOCK_SEGMENT
1109 *	trylocks only this branch in the adapter tree
1110 */
1111static int i2c_adapter_trylock_bus(struct i2c_adapter *adapter,
1112				   unsigned int flags)
1113{
1114	return rt_mutex_trylock(&adapter->bus_lock);
1115}
1116
1117/**
1118 * i2c_adapter_unlock_bus - Release exclusive access to an I2C bus segment
1119 * @adapter: Target I2C bus segment
1120 * @flags: I2C_LOCK_ROOT_ADAPTER unlocks the root i2c adapter, I2C_LOCK_SEGMENT
1121 *	unlocks only this branch in the adapter tree
1122 */
1123static void i2c_adapter_unlock_bus(struct i2c_adapter *adapter,
1124				   unsigned int flags)
1125{
1126	rt_mutex_unlock(&adapter->bus_lock);
1127}
1128
1129static void i2c_dev_set_name(struct i2c_adapter *adap,
1130			     struct i2c_client *client)
1131{
1132	struct acpi_device *adev = ACPI_COMPANION(&client->dev);
1133
1134	if (adev) {
1135		dev_set_name(&client->dev, "i2c-%s", acpi_dev_name(adev));
1136		return;
1137	}
1138
1139	dev_set_name(&client->dev, "%d-%04x", i2c_adapter_id(adap),
1140		     i2c_encode_flags_to_addr(client));
1141}
1142
1143/**
1144 * i2c_new_device - instantiate an i2c device
1145 * @adap: the adapter managing the device
1146 * @info: describes one I2C device; bus_num is ignored
1147 * Context: can sleep
1148 *
1149 * Create an i2c device. Binding is handled through driver model
1150 * probe()/remove() methods.  A driver may be bound to this device when we
1151 * return from this function, or any later moment (e.g. maybe hotplugging will
1152 * load the driver module).  This call is not appropriate for use by mainboard
1153 * initialization logic, which usually runs during an arch_initcall() long
1154 * before any i2c_adapter could exist.
1155 *
1156 * This returns the new i2c client, which may be saved for later use with
1157 * i2c_unregister_device(); or NULL to indicate an error.
1158 */
1159struct i2c_client *
1160i2c_new_device(struct i2c_adapter *adap, struct i2c_board_info const *info)
1161{
1162	struct i2c_client	*client;
1163	int			status;
1164
1165	client = kzalloc(sizeof *client, GFP_KERNEL);
1166	if (!client)
1167		return NULL;
1168
1169	client->adapter = adap;
1170
1171	client->dev.platform_data = info->platform_data;
1172
1173	if (info->archdata)
1174		client->dev.archdata = *info->archdata;
1175
1176	client->flags = info->flags;
1177	client->addr = info->addr;
1178	client->irq = info->irq;
1179
1180	strlcpy(client->name, info->type, sizeof(client->name));
1181
1182	status = i2c_check_addr_validity(client->addr, client->flags);
1183	if (status) {
1184		dev_err(&adap->dev, "Invalid %d-bit I2C address 0x%02hx\n",
1185			client->flags & I2C_CLIENT_TEN ? 10 : 7, client->addr);
1186		goto out_err_silent;
1187	}
1188
1189	/* Check for address business */
1190	status = i2c_check_addr_busy(adap, i2c_encode_flags_to_addr(client));
1191	if (status)
1192		goto out_err;
1193
1194	client->dev.parent = &client->adapter->dev;
1195	client->dev.bus = &i2c_bus_type;
1196	client->dev.type = &i2c_client_type;
1197	client->dev.of_node = info->of_node;
1198	client->dev.fwnode = info->fwnode;
1199
1200	i2c_dev_set_name(adap, client);
1201	status = device_register(&client->dev);
1202	if (status)
1203		goto out_err;
1204
1205	dev_dbg(&adap->dev, "client [%s] registered with bus id %s\n",
1206		client->name, dev_name(&client->dev));
1207
1208	return client;
1209
1210out_err:
1211	dev_err(&adap->dev, "Failed to register i2c client %s at 0x%02x "
1212		"(%d)\n", client->name, client->addr, status);
1213out_err_silent:
1214	kfree(client);
1215	return NULL;
1216}
1217EXPORT_SYMBOL_GPL(i2c_new_device);
1218
1219
1220/**
1221 * i2c_unregister_device - reverse effect of i2c_new_device()
1222 * @client: value returned from i2c_new_device()
1223 * Context: can sleep
1224 */
1225void i2c_unregister_device(struct i2c_client *client)
1226{
1227	if (client->dev.of_node)
1228		of_node_clear_flag(client->dev.of_node, OF_POPULATED);
1229	if (ACPI_COMPANION(&client->dev))
1230		acpi_device_clear_enumerated(ACPI_COMPANION(&client->dev));
1231	device_unregister(&client->dev);
1232}
1233EXPORT_SYMBOL_GPL(i2c_unregister_device);
1234
1235
1236static const struct i2c_device_id dummy_id[] = {
1237	{ "dummy", 0 },
1238	{ },
1239};
1240
1241static int dummy_probe(struct i2c_client *client,
1242		       const struct i2c_device_id *id)
1243{
1244	return 0;
1245}
1246
1247static int dummy_remove(struct i2c_client *client)
1248{
1249	return 0;
1250}
1251
1252static struct i2c_driver dummy_driver = {
1253	.driver.name	= "dummy",
1254	.probe		= dummy_probe,
1255	.remove		= dummy_remove,
1256	.id_table	= dummy_id,
1257};
1258
1259/**
1260 * i2c_new_dummy - return a new i2c device bound to a dummy driver
1261 * @adapter: the adapter managing the device
1262 * @address: seven bit address to be used
1263 * Context: can sleep
1264 *
1265 * This returns an I2C client bound to the "dummy" driver, intended for use
1266 * with devices that consume multiple addresses.  Examples of such chips
1267 * include various EEPROMS (like 24c04 and 24c08 models).
1268 *
1269 * These dummy devices have two main uses.  First, most I2C and SMBus calls
1270 * except i2c_transfer() need a client handle; the dummy will be that handle.
1271 * And second, this prevents the specified address from being bound to a
1272 * different driver.
1273 *
1274 * This returns the new i2c client, which should be saved for later use with
1275 * i2c_unregister_device(); or NULL to indicate an error.
1276 */
1277struct i2c_client *i2c_new_dummy(struct i2c_adapter *adapter, u16 address)
1278{
1279	struct i2c_board_info info = {
1280		I2C_BOARD_INFO("dummy", address),
1281	};
1282
1283	return i2c_new_device(adapter, &info);
1284}
1285EXPORT_SYMBOL_GPL(i2c_new_dummy);
1286
1287/**
1288 * i2c_new_secondary_device - Helper to get the instantiated secondary address
1289 * and create the associated device
1290 * @client: Handle to the primary client
1291 * @name: Handle to specify which secondary address to get
1292 * @default_addr: Used as a fallback if no secondary address was specified
1293 * Context: can sleep
1294 *
1295 * I2C clients can be composed of multiple I2C slaves bound together in a single
1296 * component. The I2C client driver then binds to the master I2C slave and needs
1297 * to create I2C dummy clients to communicate with all the other slaves.
1298 *
1299 * This function creates and returns an I2C dummy client whose I2C address is
1300 * retrieved from the platform firmware based on the given slave name. If no
1301 * address is specified by the firmware default_addr is used.
1302 *
1303 * On DT-based platforms the address is retrieved from the "reg" property entry
1304 * cell whose "reg-names" value matches the slave name.
1305 *
1306 * This returns the new i2c client, which should be saved for later use with
1307 * i2c_unregister_device(); or NULL to indicate an error.
1308 */
1309struct i2c_client *i2c_new_secondary_device(struct i2c_client *client,
1310						const char *name,
1311						u16 default_addr)
1312{
1313	struct device_node *np = client->dev.of_node;
1314	u32 addr = default_addr;
1315	int i;
1316
1317	if (np) {
1318		i = of_property_match_string(np, "reg-names", name);
1319		if (i >= 0)
1320			of_property_read_u32_index(np, "reg", i, &addr);
1321	}
1322
1323	dev_dbg(&client->adapter->dev, "Address for %s : 0x%x\n", name, addr);
1324	return i2c_new_dummy(client->adapter, addr);
1325}
1326EXPORT_SYMBOL_GPL(i2c_new_secondary_device);
1327
1328/* ------------------------------------------------------------------------- */
1329
1330/* I2C bus adapters -- one roots each I2C or SMBUS segment */
1331
1332static void i2c_adapter_dev_release(struct device *dev)
1333{
1334	struct i2c_adapter *adap = to_i2c_adapter(dev);
1335	complete(&adap->dev_released);
1336}
1337
1338/*
1339 * This function is only needed for mutex_lock_nested, so it is never
1340 * called unless locking correctness checking is enabled. Thus we
1341 * make it inline to avoid a compiler warning. That's what gcc ends up
1342 * doing anyway.
1343 */
1344static inline unsigned int i2c_adapter_depth(struct i2c_adapter *adapter)
1345{
1346	unsigned int depth = 0;
1347
1348	while ((adapter = i2c_parent_is_i2c_adapter(adapter)))
1349		depth++;
1350
1351	return depth;
1352}
1353
1354/*
1355 * Let users instantiate I2C devices through sysfs. This can be used when
1356 * platform initialization code doesn't contain the proper data for
1357 * whatever reason. Also useful for drivers that do device detection and
1358 * detection fails, either because the device uses an unexpected address,
1359 * or this is a compatible device with different ID register values.
1360 *
1361 * Parameter checking may look overzealous, but we really don't want
1362 * the user to provide incorrect parameters.
1363 */
1364static ssize_t
1365i2c_sysfs_new_device(struct device *dev, struct device_attribute *attr,
1366		     const char *buf, size_t count)
1367{
1368	struct i2c_adapter *adap = to_i2c_adapter(dev);
1369	struct i2c_board_info info;
1370	struct i2c_client *client;
1371	char *blank, end;
1372	int res;
1373
1374	memset(&info, 0, sizeof(struct i2c_board_info));
1375
1376	blank = strchr(buf, ' ');
1377	if (!blank) {
1378		dev_err(dev, "%s: Missing parameters\n", "new_device");
1379		return -EINVAL;
1380	}
1381	if (blank - buf > I2C_NAME_SIZE - 1) {
1382		dev_err(dev, "%s: Invalid device name\n", "new_device");
1383		return -EINVAL;
1384	}
1385	memcpy(info.type, buf, blank - buf);
1386
1387	/* Parse remaining parameters, reject extra parameters */
1388	res = sscanf(++blank, "%hi%c", &info.addr, &end);
1389	if (res < 1) {
1390		dev_err(dev, "%s: Can't parse I2C address\n", "new_device");
1391		return -EINVAL;
1392	}
1393	if (res > 1  && end != '\n') {
1394		dev_err(dev, "%s: Extra parameters\n", "new_device");
1395		return -EINVAL;
1396	}
1397
1398	if ((info.addr & I2C_ADDR_OFFSET_TEN_BIT) == I2C_ADDR_OFFSET_TEN_BIT) {
1399		info.addr &= ~I2C_ADDR_OFFSET_TEN_BIT;
1400		info.flags |= I2C_CLIENT_TEN;
1401	}
1402
1403	if (info.addr & I2C_ADDR_OFFSET_SLAVE) {
1404		info.addr &= ~I2C_ADDR_OFFSET_SLAVE;
1405		info.flags |= I2C_CLIENT_SLAVE;
1406	}
1407
1408	client = i2c_new_device(adap, &info);
1409	if (!client)
1410		return -EINVAL;
1411
1412	/* Keep track of the added device */
1413	mutex_lock(&adap->userspace_clients_lock);
1414	list_add_tail(&client->detected, &adap->userspace_clients);
1415	mutex_unlock(&adap->userspace_clients_lock);
1416	dev_info(dev, "%s: Instantiated device %s at 0x%02hx\n", "new_device",
1417		 info.type, info.addr);
1418
1419	return count;
1420}
1421static DEVICE_ATTR(new_device, S_IWUSR, NULL, i2c_sysfs_new_device);
1422
1423/*
1424 * And of course let the users delete the devices they instantiated, if
1425 * they got it wrong. This interface can only be used to delete devices
1426 * instantiated by i2c_sysfs_new_device above. This guarantees that we
1427 * don't delete devices to which some kernel code still has references.
1428 *
1429 * Parameter checking may look overzealous, but we really don't want
1430 * the user to delete the wrong device.
1431 */
1432static ssize_t
1433i2c_sysfs_delete_device(struct device *dev, struct device_attribute *attr,
1434			const char *buf, size_t count)
1435{
1436	struct i2c_adapter *adap = to_i2c_adapter(dev);
1437	struct i2c_client *client, *next;
1438	unsigned short addr;
1439	char end;
1440	int res;
1441
1442	/* Parse parameters, reject extra parameters */
1443	res = sscanf(buf, "%hi%c", &addr, &end);
1444	if (res < 1) {
1445		dev_err(dev, "%s: Can't parse I2C address\n", "delete_device");
1446		return -EINVAL;
1447	}
1448	if (res > 1  && end != '\n') {
1449		dev_err(dev, "%s: Extra parameters\n", "delete_device");
1450		return -EINVAL;
1451	}
1452
1453	/* Make sure the device was added through sysfs */
1454	res = -ENOENT;
1455	mutex_lock_nested(&adap->userspace_clients_lock,
1456			  i2c_adapter_depth(adap));
1457	list_for_each_entry_safe(client, next, &adap->userspace_clients,
1458				 detected) {
1459		if (i2c_encode_flags_to_addr(client) == addr) {
1460			dev_info(dev, "%s: Deleting device %s at 0x%02hx\n",
1461				 "delete_device", client->name, client->addr);
1462
1463			list_del(&client->detected);
1464			i2c_unregister_device(client);
1465			res = count;
1466			break;
1467		}
1468	}
1469	mutex_unlock(&adap->userspace_clients_lock);
1470
1471	if (res < 0)
1472		dev_err(dev, "%s: Can't find device in list\n",
1473			"delete_device");
1474	return res;
1475}
1476static DEVICE_ATTR_IGNORE_LOCKDEP(delete_device, S_IWUSR, NULL,
1477				   i2c_sysfs_delete_device);
1478
1479static struct attribute *i2c_adapter_attrs[] = {
1480	&dev_attr_name.attr,
1481	&dev_attr_new_device.attr,
1482	&dev_attr_delete_device.attr,
1483	NULL
1484};
1485ATTRIBUTE_GROUPS(i2c_adapter);
1486
1487struct device_type i2c_adapter_type = {
1488	.groups		= i2c_adapter_groups,
1489	.release	= i2c_adapter_dev_release,
1490};
1491EXPORT_SYMBOL_GPL(i2c_adapter_type);
1492
1493/**
1494 * i2c_verify_adapter - return parameter as i2c_adapter or NULL
1495 * @dev: device, probably from some driver model iterator
1496 *
1497 * When traversing the driver model tree, perhaps using driver model
1498 * iterators like @device_for_each_child(), you can't assume very much
1499 * about the nodes you find.  Use this function to avoid oopses caused
1500 * by wrongly treating some non-I2C device as an i2c_adapter.
1501 */
1502struct i2c_adapter *i2c_verify_adapter(struct device *dev)
1503{
1504	return (dev->type == &i2c_adapter_type)
1505			? to_i2c_adapter(dev)
1506			: NULL;
1507}
1508EXPORT_SYMBOL(i2c_verify_adapter);
1509
1510#ifdef CONFIG_I2C_COMPAT
1511static struct class_compat *i2c_adapter_compat_class;
1512#endif
1513
1514static void i2c_scan_static_board_info(struct i2c_adapter *adapter)
1515{
1516	struct i2c_devinfo	*devinfo;
1517
1518	down_read(&__i2c_board_lock);
1519	list_for_each_entry(devinfo, &__i2c_board_list, list) {
1520		if (devinfo->busnum == adapter->nr
1521				&& !i2c_new_device(adapter,
1522						&devinfo->board_info))
1523			dev_err(&adapter->dev,
1524				"Can't create device at 0x%02x\n",
1525				devinfo->board_info.addr);
1526	}
1527	up_read(&__i2c_board_lock);
1528}
1529
1530/* OF support code */
1531
1532#if IS_ENABLED(CONFIG_OF)
1533static struct i2c_client *of_i2c_register_device(struct i2c_adapter *adap,
1534						 struct device_node *node)
1535{
1536	struct i2c_client *result;
1537	struct i2c_board_info info = {};
1538	struct dev_archdata dev_ad = {};
1539	const __be32 *addr_be;
1540	u32 addr;
1541	int len;
1542
1543	dev_dbg(&adap->dev, "of_i2c: register %s\n", node->full_name);
1544
1545	if (of_modalias_node(node, info.type, sizeof(info.type)) < 0) {
1546		dev_err(&adap->dev, "of_i2c: modalias failure on %s\n",
1547			node->full_name);
1548		return ERR_PTR(-EINVAL);
1549	}
1550
1551	addr_be = of_get_property(node, "reg", &len);
1552	if (!addr_be || (len < sizeof(*addr_be))) {
1553		dev_err(&adap->dev, "of_i2c: invalid reg on %s\n",
1554			node->full_name);
1555		return ERR_PTR(-EINVAL);
1556	}
1557
1558	addr = be32_to_cpup(addr_be);
1559	if (addr & I2C_TEN_BIT_ADDRESS) {
1560		addr &= ~I2C_TEN_BIT_ADDRESS;
1561		info.flags |= I2C_CLIENT_TEN;
1562	}
1563
1564	if (addr & I2C_OWN_SLAVE_ADDRESS) {
1565		addr &= ~I2C_OWN_SLAVE_ADDRESS;
1566		info.flags |= I2C_CLIENT_SLAVE;
1567	}
1568
1569	if (i2c_check_addr_validity(addr, info.flags)) {
1570		dev_err(&adap->dev, "of_i2c: invalid addr=%x on %s\n",
1571			info.addr, node->full_name);
1572		return ERR_PTR(-EINVAL);
1573	}
1574
1575	info.addr = addr;
1576	info.of_node = of_node_get(node);
1577	info.archdata = &dev_ad;
1578
1579	if (of_get_property(node, "wakeup-source", NULL))
1580		info.flags |= I2C_CLIENT_WAKE;
1581
1582	result = i2c_new_device(adap, &info);
1583	if (result == NULL) {
1584		dev_err(&adap->dev, "of_i2c: Failure registering %s\n",
1585			node->full_name);
1586		of_node_put(node);
1587		return ERR_PTR(-EINVAL);
1588	}
1589	return result;
1590}
1591
1592static void of_i2c_register_devices(struct i2c_adapter *adap)
1593{
1594	struct device_node *node;
1595
1596	/* Only register child devices if the adapter has a node pointer set */
1597	if (!adap->dev.of_node)
1598		return;
1599
1600	dev_dbg(&adap->dev, "of_i2c: walking child nodes\n");
1601
1602	for_each_available_child_of_node(adap->dev.of_node, node) {
1603		if (of_node_test_and_set_flag(node, OF_POPULATED))
1604			continue;
1605		of_i2c_register_device(adap, node);
1606	}
1607}
1608
1609static int of_dev_node_match(struct device *dev, void *data)
1610{
1611	return dev->of_node == data;
1612}
1613
1614/* must call put_device() when done with returned i2c_client device */
1615struct i2c_client *of_find_i2c_device_by_node(struct device_node *node)
1616{
1617	struct device *dev;
1618	struct i2c_client *client;
1619
1620	dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1621	if (!dev)
1622		return NULL;
1623
1624	client = i2c_verify_client(dev);
1625	if (!client)
1626		put_device(dev);
1627
1628	return client;
1629}
1630EXPORT_SYMBOL(of_find_i2c_device_by_node);
1631
1632/* must call put_device() when done with returned i2c_adapter device */
1633struct i2c_adapter *of_find_i2c_adapter_by_node(struct device_node *node)
1634{
1635	struct device *dev;
1636	struct i2c_adapter *adapter;
1637
1638	dev = bus_find_device(&i2c_bus_type, NULL, node, of_dev_node_match);
1639	if (!dev)
1640		return NULL;
1641
1642	adapter = i2c_verify_adapter(dev);
1643	if (!adapter)
1644		put_device(dev);
1645
1646	return adapter;
1647}
1648EXPORT_SYMBOL(of_find_i2c_adapter_by_node);
1649
1650/* must call i2c_put_adapter() when done with returned i2c_adapter device */
1651struct i2c_adapter *of_get_i2c_adapter_by_node(struct device_node *node)
1652{
1653	struct i2c_adapter *adapter;
1654
1655	adapter = of_find_i2c_adapter_by_node(node);
1656	if (!adapter)
1657		return NULL;
1658
1659	if (!try_module_get(adapter->owner)) {
1660		put_device(&adapter->dev);
1661		adapter = NULL;
1662	}
1663
1664	return adapter;
1665}
1666EXPORT_SYMBOL(of_get_i2c_adapter_by_node);
1667#else
1668static void of_i2c_register_devices(struct i2c_adapter *adap) { }
1669#endif /* CONFIG_OF */
1670
1671static int i2c_do_add_adapter(struct i2c_driver *driver,
1672			      struct i2c_adapter *adap)
1673{
1674	/* Detect supported devices on that bus, and instantiate them */
1675	i2c_detect(adap, driver);
1676
1677	/* Let legacy drivers scan this bus for matching devices */
1678	if (driver->attach_adapter) {
1679		dev_warn(&adap->dev, "%s: attach_adapter method is deprecated\n",
1680			 driver->driver.name);
1681		dev_warn(&adap->dev, "Please use another way to instantiate "
1682			 "your i2c_client\n");
1683		/* We ignore the return code; if it fails, too bad */
1684		driver->attach_adapter(adap);
1685	}
1686	return 0;
1687}
1688
1689static int __process_new_adapter(struct device_driver *d, void *data)
1690{
1691	return i2c_do_add_adapter(to_i2c_driver(d), data);
1692}
1693
1694static int i2c_register_adapter(struct i2c_adapter *adap)
1695{
1696	int res = -EINVAL;
1697
1698	/* Can't register until after driver model init */
1699	if (WARN_ON(!is_registered)) {
1700		res = -EAGAIN;
1701		goto out_list;
1702	}
1703
1704	/* Sanity checks */
1705	if (WARN(!adap->name[0], "i2c adapter has no name"))
1706		goto out_list;
1707
1708	if (!adap->algo) {
1709		pr_err("adapter '%s': no algo supplied!\n", adap->name);
1710		goto out_list;
1711	}
1712
1713	if (!adap->lock_bus) {
1714		adap->lock_bus = i2c_adapter_lock_bus;
1715		adap->trylock_bus = i2c_adapter_trylock_bus;
1716		adap->unlock_bus = i2c_adapter_unlock_bus;
1717	}
1718
1719	rt_mutex_init(&adap->bus_lock);
1720	rt_mutex_init(&adap->mux_lock);
1721	mutex_init(&adap->userspace_clients_lock);
1722	INIT_LIST_HEAD(&adap->userspace_clients);
1723
1724	/* Set default timeout to 1 second if not already set */
1725	if (adap->timeout == 0)
1726		adap->timeout = HZ;
1727
1728	dev_set_name(&adap->dev, "i2c-%d", adap->nr);
1729	adap->dev.bus = &i2c_bus_type;
1730	adap->dev.type = &i2c_adapter_type;
1731	res = device_register(&adap->dev);
1732	if (res) {
1733		pr_err("adapter '%s': can't register device (%d)\n", adap->name, res);
1734		goto out_list;
1735	}
1736
1737	dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);
1738
1739	pm_runtime_no_callbacks(&adap->dev);
1740	pm_suspend_ignore_children(&adap->dev, true);
1741	pm_runtime_enable(&adap->dev);
1742
1743#ifdef CONFIG_I2C_COMPAT
1744	res = class_compat_create_link(i2c_adapter_compat_class, &adap->dev,
1745				       adap->dev.parent);
1746	if (res)
1747		dev_warn(&adap->dev,
1748			 "Failed to create compatibility class link\n");
1749#endif
1750
1751	i2c_init_recovery(adap);
1752
1753	/* create pre-declared device nodes */
1754	of_i2c_register_devices(adap);
1755	acpi_i2c_register_devices(adap);
1756	acpi_i2c_install_space_handler(adap);
1757
1758	if (adap->nr < __i2c_first_dynamic_bus_num)
1759		i2c_scan_static_board_info(adap);
1760
1761	/* Notify drivers */
1762	mutex_lock(&core_lock);
1763	bus_for_each_drv(&i2c_bus_type, NULL, adap, __process_new_adapter);
1764	mutex_unlock(&core_lock);
1765
1766	return 0;
1767
1768out_list:
1769	mutex_lock(&core_lock);
1770	idr_remove(&i2c_adapter_idr, adap->nr);
1771	mutex_unlock(&core_lock);
1772	return res;
1773}
1774
1775/**
1776 * __i2c_add_numbered_adapter - i2c_add_numbered_adapter where nr is never -1
1777 * @adap: the adapter to register (with adap->nr initialized)
1778 * Context: can sleep
1779 *
1780 * See i2c_add_numbered_adapter() for details.
1781 */
1782static int __i2c_add_numbered_adapter(struct i2c_adapter *adap)
1783{
1784	int id;
1785
1786	mutex_lock(&core_lock);
1787	id = idr_alloc(&i2c_adapter_idr, adap, adap->nr, adap->nr + 1, GFP_KERNEL);
1788	mutex_unlock(&core_lock);
1789	if (WARN(id < 0, "couldn't get idr"))
1790		return id == -ENOSPC ? -EBUSY : id;
1791
1792	return i2c_register_adapter(adap);
1793}
1794
1795/**
1796 * i2c_add_adapter - declare i2c adapter, use dynamic bus number
1797 * @adapter: the adapter to add
1798 * Context: can sleep
1799 *
1800 * This routine is used to declare an I2C adapter when its bus number
1801 * doesn't matter or when its bus number is specified by an dt alias.
1802 * Examples of bases when the bus number doesn't matter: I2C adapters
1803 * dynamically added by USB links or PCI plugin cards.
1804 *
1805 * When this returns zero, a new bus number was allocated and stored
1806 * in adap->nr, and the specified adapter became available for clients.
1807 * Otherwise, a negative errno value is returned.
1808 */
1809int i2c_add_adapter(struct i2c_adapter *adapter)
1810{
1811	struct device *dev = &adapter->dev;
1812	int id;
1813
1814	if (dev->of_node) {
1815		id = of_alias_get_id(dev->of_node, "i2c");
1816		if (id >= 0) {
1817			adapter->nr = id;
1818			return __i2c_add_numbered_adapter(adapter);
1819		}
1820	}
1821
1822	mutex_lock(&core_lock);
1823	id = idr_alloc(&i2c_adapter_idr, adapter,
1824		       __i2c_first_dynamic_bus_num, 0, GFP_KERNEL);
1825	mutex_unlock(&core_lock);
1826	if (WARN(id < 0, "couldn't get idr"))
1827		return id;
1828
1829	adapter->nr = id;
1830
1831	return i2c_register_adapter(adapter);
1832}
1833EXPORT_SYMBOL(i2c_add_adapter);
1834
1835/**
1836 * i2c_add_numbered_adapter - declare i2c adapter, use static bus number
1837 * @adap: the adapter to register (with adap->nr initialized)
1838 * Context: can sleep
1839 *
1840 * This routine is used to declare an I2C adapter when its bus number
1841 * matters.  For example, use it for I2C adapters from system-on-chip CPUs,
1842 * or otherwise built in to the system's mainboard, and where i2c_board_info
1843 * is used to properly configure I2C devices.
1844 *
1845 * If the requested bus number is set to -1, then this function will behave
1846 * identically to i2c_add_adapter, and will dynamically assign a bus number.
1847 *
1848 * If no devices have pre-been declared for this bus, then be sure to
1849 * register the adapter before any dynamically allocated ones.  Otherwise
1850 * the required bus ID may not be available.
1851 *
1852 * When this returns zero, the specified adapter became available for
1853 * clients using the bus number provided in adap->nr.  Also, the table
1854 * of I2C devices pre-declared using i2c_register_board_info() is scanned,
1855 * and the appropriate driver model device nodes are created.  Otherwise, a
1856 * negative errno value is returned.
1857 */
1858int i2c_add_numbered_adapter(struct i2c_adapter *adap)
1859{
1860	if (adap->nr == -1) /* -1 means dynamically assign bus id */
1861		return i2c_add_adapter(adap);
1862
1863	return __i2c_add_numbered_adapter(adap);
1864}
1865EXPORT_SYMBOL_GPL(i2c_add_numbered_adapter);
1866
1867static void i2c_do_del_adapter(struct i2c_driver *driver,
1868			      struct i2c_adapter *adapter)
1869{
1870	struct i2c_client *client, *_n;
1871
1872	/* Remove the devices we created ourselves as the result of hardware
1873	 * probing (using a driver's detect method) */
1874	list_for_each_entry_safe(client, _n, &driver->clients, detected) {
1875		if (client->adapter == adapter) {
1876			dev_dbg(&adapter->dev, "Removing %s at 0x%x\n",
1877				client->name, client->addr);
1878			list_del(&client->detected);
1879			i2c_unregister_device(client);
1880		}
1881	}
1882}
1883
1884static int __unregister_client(struct device *dev, void *dummy)
1885{
1886	struct i2c_client *client = i2c_verify_client(dev);
1887	if (client && strcmp(client->name, "dummy"))
1888		i2c_unregister_device(client);
1889	return 0;
1890}
1891
1892static int __unregister_dummy(struct device *dev, void *dummy)
1893{
1894	struct i2c_client *client = i2c_verify_client(dev);
1895	if (client)
1896		i2c_unregister_device(client);
1897	return 0;
1898}
1899
1900static int __process_removed_adapter(struct device_driver *d, void *data)
1901{
1902	i2c_do_del_adapter(to_i2c_driver(d), data);
1903	return 0;
1904}
1905
1906/**
1907 * i2c_del_adapter - unregister I2C adapter
1908 * @adap: the adapter being unregis…

Large files files are truncated, but you can click here to view the full file