1 /*
2  * Copyright (c) 2017 Piotr Mienkowski
3  * Copyright (c) 2023 Gerson Fernando Budke
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #define DT_DRV_COMPAT atmel_sam_i2c_twihs
9 
10 /** @file
11  * @brief I2C bus (TWIHS) driver for Atmel SAM MCU family.
12  *
13  * Only I2C Master Mode with 7 bit addressing is currently supported.
14  */
15 
16 
17 #include <errno.h>
18 #include <zephyr/sys/__assert.h>
19 #include <zephyr/kernel.h>
20 #include <zephyr/device.h>
21 #include <zephyr/init.h>
22 #include <soc.h>
23 #include <zephyr/drivers/i2c.h>
24 #include <zephyr/drivers/pinctrl.h>
25 #include <zephyr/drivers/clock_control/atmel_sam_pmc.h>
26 
27 #define LOG_LEVEL CONFIG_I2C_LOG_LEVEL
28 #include <zephyr/logging/log.h>
29 #include <zephyr/irq.h>
30 LOG_MODULE_REGISTER(i2c_sam_twihs);
31 
32 #include "i2c-priv.h"
33 
34 /** I2C bus speed [Hz] in Standard Mode */
35 #define BUS_SPEED_STANDARD_HZ         100000U
36 /** I2C bus speed [Hz] in Fast Mode */
37 #define BUS_SPEED_FAST_HZ             400000U
38 /** I2C bus speed [Hz] in High Speed Mode */
39 #define BUS_SPEED_HIGH_HZ            3400000U
40 /* Maximum value of Clock Divider (CKDIV) */
41 #define CKDIV_MAX                          7
42 
43 /* Device constant configuration parameters */
44 struct i2c_sam_twihs_dev_cfg {
45 	Twihs *regs;
46 	void (*irq_config)(void);
47 	uint32_t bitrate;
48 	const struct atmel_sam_pmc_config clock_cfg;
49 	const struct pinctrl_dev_config *pcfg;
50 	uint8_t irq_id;
51 };
52 
53 struct twihs_msg {
54 	/* Buffer containing data to read or write */
55 	uint8_t *buf;
56 	/* Length of the buffer */
57 	uint32_t len;
58 	/* Index of the next byte to be read/written from/to the buffer */
59 	uint32_t idx;
60 	/* Value of TWIHS_SR at the end of the message */
61 	uint32_t twihs_sr;
62 	/* Transfer flags as defined in the i2c.h file */
63 	uint8_t flags;
64 };
65 
66 /* Device run time data */
67 struct i2c_sam_twihs_dev_data {
68 	struct k_sem sem;
69 	struct twihs_msg msg;
70 };
71 
i2c_clk_set(Twihs * const twihs,uint32_t speed)72 static int i2c_clk_set(Twihs *const twihs, uint32_t speed)
73 {
74 	uint32_t ck_div = 0U;
75 	uint32_t cl_div;
76 	bool div_completed = false;
77 
78 	/*  From the datasheet "TWIHS Clock Waveform Generator Register"
79 	 *  T_low = ( ( CLDIV × 2^CKDIV ) + 3 ) × T_MCK
80 	 */
81 	while (!div_completed) {
82 		cl_div =   ((SOC_ATMEL_SAM_MCK_FREQ_HZ / (speed * 2U)) - 3)
83 			 / (1 << ck_div);
84 
85 		if (cl_div <= 255U) {
86 			div_completed = true;
87 		} else {
88 			ck_div++;
89 		}
90 	}
91 
92 	if (ck_div > CKDIV_MAX) {
93 		LOG_ERR("Failed to configure I2C clock");
94 		return -EIO;
95 	}
96 
97 	/* Set I2C bus clock duty cycle to 50% */
98 	twihs->TWIHS_CWGR = TWIHS_CWGR_CLDIV(cl_div) | TWIHS_CWGR_CHDIV(cl_div)
99 			    | TWIHS_CWGR_CKDIV(ck_div);
100 
101 	return 0;
102 }
103 
i2c_sam_twihs_configure(const struct device * dev,uint32_t config)104 static int i2c_sam_twihs_configure(const struct device *dev, uint32_t config)
105 {
106 	const struct i2c_sam_twihs_dev_cfg *const dev_cfg = dev->config;
107 	Twihs *const twihs = dev_cfg->regs;
108 	uint32_t bitrate;
109 	int ret;
110 
111 	if (!(config & I2C_MODE_CONTROLLER)) {
112 		LOG_ERR("Master Mode is not enabled");
113 		return -EIO;
114 	}
115 
116 	if (config & I2C_ADDR_10_BITS) {
117 		LOG_ERR("I2C 10-bit addressing is currently not supported");
118 		LOG_ERR("Please submit a patch");
119 		return -EIO;
120 	}
121 
122 	/* Configure clock */
123 	switch (I2C_SPEED_GET(config)) {
124 	case I2C_SPEED_STANDARD:
125 		bitrate = BUS_SPEED_STANDARD_HZ;
126 		break;
127 	case I2C_SPEED_FAST:
128 		bitrate = BUS_SPEED_FAST_HZ;
129 		break;
130 	default:
131 		LOG_ERR("Unsupported I2C speed value");
132 		return -EIO;
133 	}
134 
135 	/* Setup clock waveform */
136 	ret = i2c_clk_set(twihs, bitrate);
137 	if (ret < 0) {
138 		return ret;
139 	}
140 
141 	/* Disable Slave Mode */
142 	twihs->TWIHS_CR = TWIHS_CR_SVDIS;
143 
144 	/* Enable Master Mode */
145 	twihs->TWIHS_CR = TWIHS_CR_MSEN;
146 
147 	return 0;
148 }
149 
write_msg_start(Twihs * const twihs,struct twihs_msg * msg,uint8_t daddr)150 static void write_msg_start(Twihs *const twihs, struct twihs_msg *msg,
151 			    uint8_t daddr)
152 {
153 	/* Set slave address. */
154 	twihs->TWIHS_MMR = TWIHS_MMR_DADR(daddr);
155 
156 	/* Write first data byte on I2C bus */
157 	twihs->TWIHS_THR = msg->buf[msg->idx++];
158 
159 	/* Enable Transmit Ready and Transmission Completed interrupts */
160 	twihs->TWIHS_IER = TWIHS_IER_TXRDY | TWIHS_IER_TXCOMP | TWIHS_IER_NACK;
161 }
162 
read_msg_start(Twihs * const twihs,struct twihs_msg * msg,uint8_t daddr)163 static void read_msg_start(Twihs *const twihs, struct twihs_msg *msg,
164 			   uint8_t daddr)
165 {
166 	uint32_t twihs_cr_stop;
167 
168 	/* Set slave address and number of internal address bytes */
169 	twihs->TWIHS_MMR = TWIHS_MMR_MREAD | TWIHS_MMR_DADR(daddr);
170 
171 	/* Enable Receive Ready and Transmission Completed interrupts */
172 	twihs->TWIHS_IER = TWIHS_IER_RXRDY | TWIHS_IER_TXCOMP | TWIHS_IER_NACK;
173 
174 	/* In single data byte read the START and STOP must both be set */
175 	twihs_cr_stop = (msg->len == 1U) ? TWIHS_CR_STOP : 0;
176 	/* Start the transfer by sending START condition */
177 	twihs->TWIHS_CR = TWIHS_CR_START | twihs_cr_stop;
178 }
179 
i2c_sam_twihs_transfer(const struct device * dev,struct i2c_msg * msgs,uint8_t num_msgs,uint16_t addr)180 static int i2c_sam_twihs_transfer(const struct device *dev,
181 				  struct i2c_msg *msgs,
182 				  uint8_t num_msgs, uint16_t addr)
183 {
184 	const struct i2c_sam_twihs_dev_cfg *const dev_cfg = dev->config;
185 	struct i2c_sam_twihs_dev_data *const dev_data = dev->data;
186 	Twihs *const twihs = dev_cfg->regs;
187 
188 	__ASSERT_NO_MSG(msgs);
189 	if (!num_msgs) {
190 		return 0;
191 	}
192 
193 	/* Clear pending interrupts, such as NACK. */
194 	(void)twihs->TWIHS_SR;
195 
196 	/* Set number of internal address bytes to 0, not used. */
197 	twihs->TWIHS_IADR = 0;
198 
199 	for (int i = 0; i < num_msgs; i++) {
200 		dev_data->msg.buf = msgs[i].buf;
201 		dev_data->msg.len = msgs[i].len;
202 		dev_data->msg.idx = 0U;
203 		dev_data->msg.twihs_sr = 0U;
204 		dev_data->msg.flags = msgs[i].flags;
205 		if ((msgs[i].flags & I2C_MSG_RW_MASK) == I2C_MSG_READ) {
206 			read_msg_start(twihs, &dev_data->msg, addr);
207 		} else {
208 			write_msg_start(twihs, &dev_data->msg, addr);
209 		}
210 		/* Wait for the transfer to complete */
211 		k_sem_take(&dev_data->sem, K_FOREVER);
212 
213 		if (dev_data->msg.twihs_sr > 0) {
214 			/* Something went wrong */
215 			return -EIO;
216 		}
217 	}
218 
219 	return 0;
220 }
221 
i2c_sam_twihs_isr(const struct device * dev)222 static void i2c_sam_twihs_isr(const struct device *dev)
223 {
224 	const struct i2c_sam_twihs_dev_cfg *const dev_cfg = dev->config;
225 	struct i2c_sam_twihs_dev_data *const dev_data = dev->data;
226 	Twihs *const twihs = dev_cfg->regs;
227 	struct twihs_msg *msg = &dev_data->msg;
228 	uint32_t isr_status;
229 
230 	/* Retrieve interrupt status */
231 	isr_status = twihs->TWIHS_SR & twihs->TWIHS_IMR;
232 
233 	/* Not Acknowledged */
234 	if (isr_status & TWIHS_SR_NACK) {
235 		msg->twihs_sr = isr_status;
236 		goto tx_comp;
237 	}
238 
239 	/* Byte received */
240 	if (isr_status & TWIHS_SR_RXRDY) {
241 
242 		msg->buf[msg->idx++] = twihs->TWIHS_RHR;
243 
244 		if (msg->idx == msg->len - 1U) {
245 			/* Send STOP condition */
246 			twihs->TWIHS_CR = TWIHS_CR_STOP;
247 		}
248 	}
249 
250 	/* Byte sent */
251 	if (isr_status & TWIHS_SR_TXRDY) {
252 		if (msg->idx == msg->len) {
253 			if (msg->flags & I2C_MSG_STOP) {
254 				/* Send STOP condition */
255 				twihs->TWIHS_CR = TWIHS_CR_STOP;
256 				/* Disable Transmit Ready interrupt */
257 				twihs->TWIHS_IDR = TWIHS_IDR_TXRDY;
258 			} else {
259 				/* Transmission completed */
260 				goto tx_comp;
261 			}
262 		} else {
263 			twihs->TWIHS_THR = msg->buf[msg->idx++];
264 		}
265 	}
266 
267 	/* Transmission completed */
268 	if (isr_status & TWIHS_SR_TXCOMP) {
269 		goto tx_comp;
270 	}
271 
272 	return;
273 
274 tx_comp:
275 	/* Disable all enabled interrupts */
276 	twihs->TWIHS_IDR = twihs->TWIHS_IMR;
277 	/* We are done */
278 	k_sem_give(&dev_data->sem);
279 }
280 
i2c_sam_twihs_initialize(const struct device * dev)281 static int i2c_sam_twihs_initialize(const struct device *dev)
282 {
283 	const struct i2c_sam_twihs_dev_cfg *const dev_cfg = dev->config;
284 	struct i2c_sam_twihs_dev_data *const dev_data = dev->data;
285 	Twihs *const twihs = dev_cfg->regs;
286 	uint32_t bitrate_cfg;
287 	int ret;
288 
289 	/* Configure interrupts */
290 	dev_cfg->irq_config();
291 
292 	/* Initialize semaphore */
293 	k_sem_init(&dev_data->sem, 0, 1);
294 
295 	/* Connect pins to the peripheral */
296 	ret = pinctrl_apply_state(dev_cfg->pcfg, PINCTRL_STATE_DEFAULT);
297 	if (ret < 0) {
298 		return ret;
299 	}
300 
301 	/* Enable TWIHS clock in PMC */
302 	(void)clock_control_on(SAM_DT_PMC_CONTROLLER,
303 			       (clock_control_subsys_t)&dev_cfg->clock_cfg);
304 
305 	/* Reset the module */
306 	twihs->TWIHS_CR = TWIHS_CR_SWRST;
307 
308 	bitrate_cfg = i2c_map_dt_bitrate(dev_cfg->bitrate);
309 
310 	ret = i2c_sam_twihs_configure(dev, I2C_MODE_CONTROLLER | bitrate_cfg);
311 	if (ret < 0) {
312 		LOG_ERR("Failed to initialize %s device", dev->name);
313 		return ret;
314 	}
315 
316 	/* Enable module's IRQ */
317 	irq_enable(dev_cfg->irq_id);
318 
319 	LOG_INF("Device %s initialized", dev->name);
320 
321 	return 0;
322 }
323 
324 static const struct i2c_driver_api i2c_sam_twihs_driver_api = {
325 	.configure = i2c_sam_twihs_configure,
326 	.transfer = i2c_sam_twihs_transfer,
327 };
328 
329 #define I2C_TWIHS_SAM_INIT(n)						\
330 	PINCTRL_DT_INST_DEFINE(n);					\
331 	static void i2c##n##_sam_irq_config(void)			\
332 	{								\
333 		IRQ_CONNECT(DT_INST_IRQN(n), DT_INST_IRQ(n, priority),	\
334 			    i2c_sam_twihs_isr,				\
335 			    DEVICE_DT_INST_GET(n), 0);			\
336 	}								\
337 									\
338 	static const struct i2c_sam_twihs_dev_cfg i2c##n##_sam_config = {\
339 		.regs = (Twihs *)DT_INST_REG_ADDR(n),			\
340 		.irq_config = i2c##n##_sam_irq_config,			\
341 		.clock_cfg = SAM_DT_INST_CLOCK_PMC_CFG(n),		\
342 		.irq_id = DT_INST_IRQN(n),				\
343 		.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(n),		\
344 		.bitrate = DT_INST_PROP(n, clock_frequency),		\
345 	};								\
346 									\
347 	static struct i2c_sam_twihs_dev_data i2c##n##_sam_data;		\
348 									\
349 	I2C_DEVICE_DT_INST_DEFINE(n, i2c_sam_twihs_initialize,	\
350 			    NULL,					\
351 			    &i2c##n##_sam_data, &i2c##n##_sam_config,	\
352 			    POST_KERNEL, CONFIG_I2C_INIT_PRIORITY,	\
353 			    &i2c_sam_twihs_driver_api);
354 
355 DT_INST_FOREACH_STATUS_OKAY(I2C_TWIHS_SAM_INIT)
356