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