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