1 /*
2  * Copyright (c) 2014 Google, Inc
3  *
4  * SPDX-License-Identifier:	GPL-2.0+
5  */
6 
7 #include <common.h>
8 #include <dm.h>
9 #include <errno.h>
10 #include <i2c.h>
11 
12 static int cur_busnum __attribute__((section(".data")));
13 
14 static int i2c_compat_get_device(uint chip_addr, int alen,
15 				 struct udevice **devp)
16 {
17 	struct dm_i2c_chip *chip;
18 	int ret;
19 
20 	ret = i2c_get_chip_for_busnum(cur_busnum, chip_addr, alen, devp);
21 	if (ret)
22 		return ret;
23 	chip = dev_get_parent_platdata(*devp);
24 	if (chip->offset_len != alen) {
25 		printf("I2C chip %x: requested alen %d does not match chip offset_len %d\n",
26 		       chip_addr, alen, chip->offset_len);
27 		return -EADDRNOTAVAIL;
28 	}
29 
30 	return 0;
31 }
32 
33 int i2c_probe(uint8_t chip_addr)
34 {
35 	struct udevice *bus, *dev;
36 	int ret;
37 
38 	ret = uclass_get_device_by_seq(UCLASS_I2C, cur_busnum, &bus);
39 	if (ret) {
40 		debug("Cannot find I2C bus %d: err=%d\n", cur_busnum, ret);
41 		return ret;
42 	}
43 
44 	if (!bus)
45 		return -ENOENT;
46 
47 	return dm_i2c_probe(bus, chip_addr, 0, &dev);
48 }
49 
50 int i2c_read(uint8_t chip_addr, unsigned int addr, int alen, uint8_t *buffer,
51 	     int len)
52 {
53 	struct udevice *dev;
54 	int ret;
55 
56 	ret = i2c_compat_get_device(chip_addr, alen, &dev);
57 	if (ret)
58 		return ret;
59 
60 	return dm_i2c_read(dev, addr, buffer, len);
61 }
62 
63 int i2c_write(uint8_t chip_addr, unsigned int addr, int alen, uint8_t *buffer,
64 	      int len)
65 {
66 	struct udevice *dev;
67 	int ret;
68 
69 	ret = i2c_compat_get_device(chip_addr, alen, &dev);
70 	if (ret)
71 		return ret;
72 
73 	return dm_i2c_write(dev, addr, buffer, len);
74 }
75 
76 int i2c_get_bus_num_fdt(int node)
77 {
78 	struct udevice *bus;
79 	int ret;
80 
81 	ret = uclass_get_device_by_of_offset(UCLASS_I2C, node, &bus);
82 	if (ret)
83 		return ret;
84 
85 	return bus->seq;
86 }
87 
88 unsigned int i2c_get_bus_num(void)
89 {
90 	return cur_busnum;
91 }
92 
93 int i2c_set_bus_num(unsigned int bus)
94 {
95 	cur_busnum = bus;
96 
97 	return 0;
98 }
99 
100 void i2c_init(int speed, int slaveaddr)
101 {
102 	/* Nothing to do here - the init happens through driver model */
103 }
104 
105 void board_i2c_init(const void *blob)
106 {
107 	/* Nothing to do here - the init happens through driver model */
108 }
109 
110 uint8_t i2c_reg_read(uint8_t chip_addr, uint8_t offset)
111 {
112 	struct udevice *dev;
113 	int ret;
114 
115 	ret = i2c_compat_get_device(chip_addr, 1, &dev);
116 	if (ret)
117 		return 0xff;
118 	return dm_i2c_reg_read(dev, offset);
119 }
120 
121 void i2c_reg_write(uint8_t chip_addr, uint8_t offset, uint8_t val)
122 {
123 	struct udevice *dev;
124 	int ret;
125 
126 	ret = i2c_compat_get_device(chip_addr, 1, &dev);
127 	if (!ret)
128 		dm_i2c_reg_write(dev, offset, val);
129 }
130