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