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