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