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