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