1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  i2c Support for Atmel's AT91 Two-Wire Interface (TWI)
4  *
5  *  Copyright (C) 2011 Weinmann Medical GmbH
6  *  Author: Nikolaus Voss <n.voss@weinmann.de>
7  *
8  *  Evolved from original work by:
9  *  Copyright (C) 2004 Rick Bronson
10  *  Converted to 2.6 by Andrew Victor <andrew@sanpeople.com>
11  *
12  *  Borrowed heavily from original work by:
13  *  Copyright (C) 2000 Philip Edelbrock <phil@stimpy.netroedge.com>
14  */
15 
16 #include <linux/clk.h>
17 #include <linux/completion.h>
18 #include <linux/dma-mapping.h>
19 #include <linux/dmaengine.h>
20 #include <linux/err.h>
21 #include <linux/i2c.h>
22 #include <linux/interrupt.h>
23 #include <linux/io.h>
24 #include <linux/of.h>
25 #include <linux/of_device.h>
26 #include <linux/platform_device.h>
27 #include <linux/platform_data/dma-atmel.h>
28 #include <linux/pm_runtime.h>
29 
30 #include "i2c-at91.h"
31 
32 void at91_init_twi_bus_master(struct at91_twi_dev *dev)
33 {
34 	/* FIFO should be enabled immediately after the software reset */
35 	if (dev->fifo_size)
36 		at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_FIFOEN);
37 	at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_MSEN);
38 	at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_SVDIS);
39 	at91_twi_write(dev, AT91_TWI_CWGR, dev->twi_cwgr_reg);
40 }
41 
42 /*
43  * Calculate symmetric clock as stated in datasheet:
44  * twi_clk = F_MAIN / (2 * (cdiv * (1 << ckdiv) + offset))
45  */
46 static void at91_calc_twi_clock(struct at91_twi_dev *dev)
47 {
48 	int ckdiv, cdiv, div, hold = 0;
49 	struct at91_twi_pdata *pdata = dev->pdata;
50 	int offset = pdata->clk_offset;
51 	int max_ckdiv = pdata->clk_max_div;
52 	struct i2c_timings timings, *t = &timings;
53 
54 	i2c_parse_fw_timings(dev->dev, t, true);
55 
56 	div = max(0, (int)DIV_ROUND_UP(clk_get_rate(dev->clk),
57 				       2 * t->bus_freq_hz) - offset);
58 	ckdiv = fls(div >> 8);
59 	cdiv = div >> ckdiv;
60 
61 	if (ckdiv > max_ckdiv) {
62 		dev_warn(dev->dev, "%d exceeds ckdiv max value which is %d.\n",
63 			 ckdiv, max_ckdiv);
64 		ckdiv = max_ckdiv;
65 		cdiv = 255;
66 	}
67 
68 	if (pdata->has_hold_field) {
69 		/*
70 		 * hold time = HOLD + 3 x T_peripheral_clock
71 		 * Use clk rate in kHz to prevent overflows when computing
72 		 * hold.
73 		 */
74 		hold = DIV_ROUND_UP(t->sda_hold_ns
75 				    * (clk_get_rate(dev->clk) / 1000), 1000000);
76 		hold -= 3;
77 		if (hold < 0)
78 			hold = 0;
79 		if (hold > AT91_TWI_CWGR_HOLD_MAX) {
80 			dev_warn(dev->dev,
81 				 "HOLD field set to its maximum value (%d instead of %d)\n",
82 				 AT91_TWI_CWGR_HOLD_MAX, hold);
83 			hold = AT91_TWI_CWGR_HOLD_MAX;
84 		}
85 	}
86 
87 	dev->twi_cwgr_reg = (ckdiv << 16) | (cdiv << 8) | cdiv
88 			    | AT91_TWI_CWGR_HOLD(hold);
89 
90 	dev_dbg(dev->dev, "cdiv %d ckdiv %d hold %d (%d ns)\n",
91 		cdiv, ckdiv, hold, t->sda_hold_ns);
92 }
93 
94 static void at91_twi_dma_cleanup(struct at91_twi_dev *dev)
95 {
96 	struct at91_twi_dma *dma = &dev->dma;
97 
98 	at91_twi_irq_save(dev);
99 
100 	if (dma->xfer_in_progress) {
101 		if (dma->direction == DMA_FROM_DEVICE)
102 			dmaengine_terminate_all(dma->chan_rx);
103 		else
104 			dmaengine_terminate_all(dma->chan_tx);
105 		dma->xfer_in_progress = false;
106 	}
107 	if (dma->buf_mapped) {
108 		dma_unmap_single(dev->dev, sg_dma_address(&dma->sg[0]),
109 				 dev->buf_len, dma->direction);
110 		dma->buf_mapped = false;
111 	}
112 
113 	at91_twi_irq_restore(dev);
114 }
115 
116 static void at91_twi_write_next_byte(struct at91_twi_dev *dev)
117 {
118 	if (!dev->buf_len)
119 		return;
120 
121 	/* 8bit write works with and without FIFO */
122 	writeb_relaxed(*dev->buf, dev->base + AT91_TWI_THR);
123 
124 	/* send stop when last byte has been written */
125 	if (--dev->buf_len == 0)
126 		if (!dev->use_alt_cmd)
127 			at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_STOP);
128 
129 	dev_dbg(dev->dev, "wrote 0x%x, to go %zu\n", *dev->buf, dev->buf_len);
130 
131 	++dev->buf;
132 }
133 
134 static void at91_twi_write_data_dma_callback(void *data)
135 {
136 	struct at91_twi_dev *dev = (struct at91_twi_dev *)data;
137 
138 	dma_unmap_single(dev->dev, sg_dma_address(&dev->dma.sg[0]),
139 			 dev->buf_len, DMA_TO_DEVICE);
140 
141 	/*
142 	 * When this callback is called, THR/TX FIFO is likely not to be empty
143 	 * yet. So we have to wait for TXCOMP or NACK bits to be set into the
144 	 * Status Register to be sure that the STOP bit has been sent and the
145 	 * transfer is completed. The NACK interrupt has already been enabled,
146 	 * we just have to enable TXCOMP one.
147 	 */
148 	at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_TXCOMP);
149 	if (!dev->use_alt_cmd)
150 		at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_STOP);
151 }
152 
153 static void at91_twi_write_data_dma(struct at91_twi_dev *dev)
154 {
155 	dma_addr_t dma_addr;
156 	struct dma_async_tx_descriptor *txdesc;
157 	struct at91_twi_dma *dma = &dev->dma;
158 	struct dma_chan *chan_tx = dma->chan_tx;
159 	unsigned int sg_len = 1;
160 
161 	if (!dev->buf_len)
162 		return;
163 
164 	dma->direction = DMA_TO_DEVICE;
165 
166 	at91_twi_irq_save(dev);
167 	dma_addr = dma_map_single(dev->dev, dev->buf, dev->buf_len,
168 				  DMA_TO_DEVICE);
169 	if (dma_mapping_error(dev->dev, dma_addr)) {
170 		dev_err(dev->dev, "dma map failed\n");
171 		return;
172 	}
173 	dma->buf_mapped = true;
174 	at91_twi_irq_restore(dev);
175 
176 	if (dev->fifo_size) {
177 		size_t part1_len, part2_len;
178 		struct scatterlist *sg;
179 		unsigned fifo_mr;
180 
181 		sg_len = 0;
182 
183 		part1_len = dev->buf_len & ~0x3;
184 		if (part1_len) {
185 			sg = &dma->sg[sg_len++];
186 			sg_dma_len(sg) = part1_len;
187 			sg_dma_address(sg) = dma_addr;
188 		}
189 
190 		part2_len = dev->buf_len & 0x3;
191 		if (part2_len) {
192 			sg = &dma->sg[sg_len++];
193 			sg_dma_len(sg) = part2_len;
194 			sg_dma_address(sg) = dma_addr + part1_len;
195 		}
196 
197 		/*
198 		 * DMA controller is triggered when at least 4 data can be
199 		 * written into the TX FIFO
200 		 */
201 		fifo_mr = at91_twi_read(dev, AT91_TWI_FMR);
202 		fifo_mr &= ~AT91_TWI_FMR_TXRDYM_MASK;
203 		fifo_mr |= AT91_TWI_FMR_TXRDYM(AT91_TWI_FOUR_DATA);
204 		at91_twi_write(dev, AT91_TWI_FMR, fifo_mr);
205 	} else {
206 		sg_dma_len(&dma->sg[0]) = dev->buf_len;
207 		sg_dma_address(&dma->sg[0]) = dma_addr;
208 	}
209 
210 	txdesc = dmaengine_prep_slave_sg(chan_tx, dma->sg, sg_len,
211 					 DMA_MEM_TO_DEV,
212 					 DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
213 	if (!txdesc) {
214 		dev_err(dev->dev, "dma prep slave sg failed\n");
215 		goto error;
216 	}
217 
218 	txdesc->callback = at91_twi_write_data_dma_callback;
219 	txdesc->callback_param = dev;
220 
221 	dma->xfer_in_progress = true;
222 	dmaengine_submit(txdesc);
223 	dma_async_issue_pending(chan_tx);
224 
225 	return;
226 
227 error:
228 	at91_twi_dma_cleanup(dev);
229 }
230 
231 static void at91_twi_read_next_byte(struct at91_twi_dev *dev)
232 {
233 	/*
234 	 * If we are in this case, it means there is garbage data in RHR, so
235 	 * delete them.
236 	 */
237 	if (!dev->buf_len) {
238 		at91_twi_read(dev, AT91_TWI_RHR);
239 		return;
240 	}
241 
242 	/* 8bit read works with and without FIFO */
243 	*dev->buf = readb_relaxed(dev->base + AT91_TWI_RHR);
244 	--dev->buf_len;
245 
246 	/* return if aborting, we only needed to read RHR to clear RXRDY*/
247 	if (dev->recv_len_abort)
248 		return;
249 
250 	/* handle I2C_SMBUS_BLOCK_DATA */
251 	if (unlikely(dev->msg->flags & I2C_M_RECV_LEN)) {
252 		/* ensure length byte is a valid value */
253 		if (*dev->buf <= I2C_SMBUS_BLOCK_MAX && *dev->buf > 0) {
254 			dev->msg->flags &= ~I2C_M_RECV_LEN;
255 			dev->buf_len += *dev->buf;
256 			dev->msg->len = dev->buf_len + 1;
257 			dev_dbg(dev->dev, "received block length %zu\n",
258 					 dev->buf_len);
259 		} else {
260 			/* abort and send the stop by reading one more byte */
261 			dev->recv_len_abort = true;
262 			dev->buf_len = 1;
263 		}
264 	}
265 
266 	/* send stop if second but last byte has been read */
267 	if (!dev->use_alt_cmd && dev->buf_len == 1)
268 		at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_STOP);
269 
270 	dev_dbg(dev->dev, "read 0x%x, to go %zu\n", *dev->buf, dev->buf_len);
271 
272 	++dev->buf;
273 }
274 
275 static void at91_twi_read_data_dma_callback(void *data)
276 {
277 	struct at91_twi_dev *dev = (struct at91_twi_dev *)data;
278 	unsigned ier = AT91_TWI_TXCOMP;
279 
280 	dma_unmap_single(dev->dev, sg_dma_address(&dev->dma.sg[0]),
281 			 dev->buf_len, DMA_FROM_DEVICE);
282 
283 	if (!dev->use_alt_cmd) {
284 		/* The last two bytes have to be read without using dma */
285 		dev->buf += dev->buf_len - 2;
286 		dev->buf_len = 2;
287 		ier |= AT91_TWI_RXRDY;
288 	}
289 	at91_twi_write(dev, AT91_TWI_IER, ier);
290 }
291 
292 static void at91_twi_read_data_dma(struct at91_twi_dev *dev)
293 {
294 	dma_addr_t dma_addr;
295 	struct dma_async_tx_descriptor *rxdesc;
296 	struct at91_twi_dma *dma = &dev->dma;
297 	struct dma_chan *chan_rx = dma->chan_rx;
298 	size_t buf_len;
299 
300 	buf_len = (dev->use_alt_cmd) ? dev->buf_len : dev->buf_len - 2;
301 	dma->direction = DMA_FROM_DEVICE;
302 
303 	/* Keep in mind that we won't use dma to read the last two bytes */
304 	at91_twi_irq_save(dev);
305 	dma_addr = dma_map_single(dev->dev, dev->buf, buf_len, DMA_FROM_DEVICE);
306 	if (dma_mapping_error(dev->dev, dma_addr)) {
307 		dev_err(dev->dev, "dma map failed\n");
308 		return;
309 	}
310 	dma->buf_mapped = true;
311 	at91_twi_irq_restore(dev);
312 
313 	if (dev->fifo_size && IS_ALIGNED(buf_len, 4)) {
314 		unsigned fifo_mr;
315 
316 		/*
317 		 * DMA controller is triggered when at least 4 data can be
318 		 * read from the RX FIFO
319 		 */
320 		fifo_mr = at91_twi_read(dev, AT91_TWI_FMR);
321 		fifo_mr &= ~AT91_TWI_FMR_RXRDYM_MASK;
322 		fifo_mr |= AT91_TWI_FMR_RXRDYM(AT91_TWI_FOUR_DATA);
323 		at91_twi_write(dev, AT91_TWI_FMR, fifo_mr);
324 	}
325 
326 	sg_dma_len(&dma->sg[0]) = buf_len;
327 	sg_dma_address(&dma->sg[0]) = dma_addr;
328 
329 	rxdesc = dmaengine_prep_slave_sg(chan_rx, dma->sg, 1, DMA_DEV_TO_MEM,
330 					 DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
331 	if (!rxdesc) {
332 		dev_err(dev->dev, "dma prep slave sg failed\n");
333 		goto error;
334 	}
335 
336 	rxdesc->callback = at91_twi_read_data_dma_callback;
337 	rxdesc->callback_param = dev;
338 
339 	dma->xfer_in_progress = true;
340 	dmaengine_submit(rxdesc);
341 	dma_async_issue_pending(dma->chan_rx);
342 
343 	return;
344 
345 error:
346 	at91_twi_dma_cleanup(dev);
347 }
348 
349 static irqreturn_t atmel_twi_interrupt(int irq, void *dev_id)
350 {
351 	struct at91_twi_dev *dev = dev_id;
352 	const unsigned status = at91_twi_read(dev, AT91_TWI_SR);
353 	const unsigned irqstatus = status & at91_twi_read(dev, AT91_TWI_IMR);
354 
355 	if (!irqstatus)
356 		return IRQ_NONE;
357 	/*
358 	 * In reception, the behavior of the twi device (before sama5d2) is
359 	 * weird. There is some magic about RXRDY flag! When a data has been
360 	 * almost received, the reception of a new one is anticipated if there
361 	 * is no stop command to send. That is the reason why ask for sending
362 	 * the stop command not on the last data but on the second last one.
363 	 *
364 	 * Unfortunately, we could still have the RXRDY flag set even if the
365 	 * transfer is done and we have read the last data. It might happen
366 	 * when the i2c slave device sends too quickly data after receiving the
367 	 * ack from the master. The data has been almost received before having
368 	 * the order to send stop. In this case, sending the stop command could
369 	 * cause a RXRDY interrupt with a TXCOMP one. It is better to manage
370 	 * the RXRDY interrupt first in order to not keep garbage data in the
371 	 * Receive Holding Register for the next transfer.
372 	 */
373 	if (irqstatus & AT91_TWI_RXRDY) {
374 		/*
375 		 * Read all available bytes at once by polling RXRDY usable w/
376 		 * and w/o FIFO. With FIFO enabled we could also read RXFL and
377 		 * avoid polling RXRDY.
378 		 */
379 		do {
380 			at91_twi_read_next_byte(dev);
381 		} while (at91_twi_read(dev, AT91_TWI_SR) & AT91_TWI_RXRDY);
382 	}
383 
384 	/*
385 	 * When a NACK condition is detected, the I2C controller sets the NACK,
386 	 * TXCOMP and TXRDY bits all together in the Status Register (SR).
387 	 *
388 	 * 1 - Handling NACK errors with CPU write transfer.
389 	 *
390 	 * In such case, we should not write the next byte into the Transmit
391 	 * Holding Register (THR) otherwise the I2C controller would start a new
392 	 * transfer and the I2C slave is likely to reply by another NACK.
393 	 *
394 	 * 2 - Handling NACK errors with DMA write transfer.
395 	 *
396 	 * By setting the TXRDY bit in the SR, the I2C controller also triggers
397 	 * the DMA controller to write the next data into the THR. Then the
398 	 * result depends on the hardware version of the I2C controller.
399 	 *
400 	 * 2a - Without support of the Alternative Command mode.
401 	 *
402 	 * This is the worst case: the DMA controller is triggered to write the
403 	 * next data into the THR, hence starting a new transfer: the I2C slave
404 	 * is likely to reply by another NACK.
405 	 * Concurrently, this interrupt handler is likely to be called to manage
406 	 * the first NACK before the I2C controller detects the second NACK and
407 	 * sets once again the NACK bit into the SR.
408 	 * When handling the first NACK, this interrupt handler disables the I2C
409 	 * controller interruptions, especially the NACK interrupt.
410 	 * Hence, the NACK bit is pending into the SR. This is why we should
411 	 * read the SR to clear all pending interrupts at the beginning of
412 	 * at91_do_twi_transfer() before actually starting a new transfer.
413 	 *
414 	 * 2b - With support of the Alternative Command mode.
415 	 *
416 	 * When a NACK condition is detected, the I2C controller also locks the
417 	 * THR (and sets the LOCK bit in the SR): even though the DMA controller
418 	 * is triggered by the TXRDY bit to write the next data into the THR,
419 	 * this data actually won't go on the I2C bus hence a second NACK is not
420 	 * generated.
421 	 */
422 	if (irqstatus & (AT91_TWI_TXCOMP | AT91_TWI_NACK)) {
423 		at91_disable_twi_interrupts(dev);
424 		complete(&dev->cmd_complete);
425 	} else if (irqstatus & AT91_TWI_TXRDY) {
426 		at91_twi_write_next_byte(dev);
427 	}
428 
429 	/* catch error flags */
430 	dev->transfer_status |= status;
431 
432 	return IRQ_HANDLED;
433 }
434 
435 static int at91_do_twi_transfer(struct at91_twi_dev *dev)
436 {
437 	int ret;
438 	unsigned long time_left;
439 	bool has_unre_flag = dev->pdata->has_unre_flag;
440 	bool has_alt_cmd = dev->pdata->has_alt_cmd;
441 
442 	/*
443 	 * WARNING: the TXCOMP bit in the Status Register is NOT a clear on
444 	 * read flag but shows the state of the transmission at the time the
445 	 * Status Register is read. According to the programmer datasheet,
446 	 * TXCOMP is set when both holding register and internal shifter are
447 	 * empty and STOP condition has been sent.
448 	 * Consequently, we should enable NACK interrupt rather than TXCOMP to
449 	 * detect transmission failure.
450 	 * Indeed let's take the case of an i2c write command using DMA.
451 	 * Whenever the slave doesn't acknowledge a byte, the LOCK, NACK and
452 	 * TXCOMP bits are set together into the Status Register.
453 	 * LOCK is a clear on write bit, which is set to prevent the DMA
454 	 * controller from sending new data on the i2c bus after a NACK
455 	 * condition has happened. Once locked, this i2c peripheral stops
456 	 * triggering the DMA controller for new data but it is more than
457 	 * likely that a new DMA transaction is already in progress, writing
458 	 * into the Transmit Holding Register. Since the peripheral is locked,
459 	 * these new data won't be sent to the i2c bus but they will remain
460 	 * into the Transmit Holding Register, so TXCOMP bit is cleared.
461 	 * Then when the interrupt handler is called, the Status Register is
462 	 * read: the TXCOMP bit is clear but NACK bit is still set. The driver
463 	 * manage the error properly, without waiting for timeout.
464 	 * This case can be reproduced easyly when writing into an at24 eeprom.
465 	 *
466 	 * Besides, the TXCOMP bit is already set before the i2c transaction
467 	 * has been started. For read transactions, this bit is cleared when
468 	 * writing the START bit into the Control Register. So the
469 	 * corresponding interrupt can safely be enabled just after.
470 	 * However for write transactions managed by the CPU, we first write
471 	 * into THR, so TXCOMP is cleared. Then we can safely enable TXCOMP
472 	 * interrupt. If TXCOMP interrupt were enabled before writing into THR,
473 	 * the interrupt handler would be called immediately and the i2c command
474 	 * would be reported as completed.
475 	 * Also when a write transaction is managed by the DMA controller,
476 	 * enabling the TXCOMP interrupt in this function may lead to a race
477 	 * condition since we don't know whether the TXCOMP interrupt is enabled
478 	 * before or after the DMA has started to write into THR. So the TXCOMP
479 	 * interrupt is enabled later by at91_twi_write_data_dma_callback().
480 	 * Immediately after in that DMA callback, if the alternative command
481 	 * mode is not used, we still need to send the STOP condition manually
482 	 * writing the corresponding bit into the Control Register.
483 	 */
484 
485 	dev_dbg(dev->dev, "transfer: %s %zu bytes.\n",
486 		(dev->msg->flags & I2C_M_RD) ? "read" : "write", dev->buf_len);
487 
488 	reinit_completion(&dev->cmd_complete);
489 	dev->transfer_status = 0;
490 
491 	/* Clear pending interrupts, such as NACK. */
492 	at91_twi_read(dev, AT91_TWI_SR);
493 
494 	if (dev->fifo_size) {
495 		unsigned fifo_mr = at91_twi_read(dev, AT91_TWI_FMR);
496 
497 		/* Reset FIFO mode register */
498 		fifo_mr &= ~(AT91_TWI_FMR_TXRDYM_MASK |
499 			     AT91_TWI_FMR_RXRDYM_MASK);
500 		fifo_mr |= AT91_TWI_FMR_TXRDYM(AT91_TWI_ONE_DATA);
501 		fifo_mr |= AT91_TWI_FMR_RXRDYM(AT91_TWI_ONE_DATA);
502 		at91_twi_write(dev, AT91_TWI_FMR, fifo_mr);
503 
504 		/* Flush FIFOs */
505 		at91_twi_write(dev, AT91_TWI_CR,
506 			       AT91_TWI_THRCLR | AT91_TWI_RHRCLR);
507 	}
508 
509 	if (!dev->buf_len) {
510 		at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_QUICK);
511 		at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_TXCOMP);
512 	} else if (dev->msg->flags & I2C_M_RD) {
513 		unsigned start_flags = AT91_TWI_START;
514 
515 		/* if only one byte is to be read, immediately stop transfer */
516 		if (!dev->use_alt_cmd && dev->buf_len <= 1 &&
517 		    !(dev->msg->flags & I2C_M_RECV_LEN))
518 			start_flags |= AT91_TWI_STOP;
519 		at91_twi_write(dev, AT91_TWI_CR, start_flags);
520 		/*
521 		 * When using dma without alternative command mode, the last
522 		 * byte has to be read manually in order to not send the stop
523 		 * command too late and then to receive extra data.
524 		 * In practice, there are some issues if you use the dma to
525 		 * read n-1 bytes because of latency.
526 		 * Reading n-2 bytes with dma and the two last ones manually
527 		 * seems to be the best solution.
528 		 */
529 		if (dev->use_dma && (dev->buf_len > AT91_I2C_DMA_THRESHOLD)) {
530 			at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_NACK);
531 			at91_twi_read_data_dma(dev);
532 		} else {
533 			at91_twi_write(dev, AT91_TWI_IER,
534 				       AT91_TWI_TXCOMP |
535 				       AT91_TWI_NACK |
536 				       AT91_TWI_RXRDY);
537 		}
538 	} else {
539 		if (dev->use_dma && (dev->buf_len > AT91_I2C_DMA_THRESHOLD)) {
540 			at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_NACK);
541 			at91_twi_write_data_dma(dev);
542 		} else {
543 			at91_twi_write_next_byte(dev);
544 			at91_twi_write(dev, AT91_TWI_IER,
545 				       AT91_TWI_TXCOMP |
546 				       AT91_TWI_NACK |
547 				       AT91_TWI_TXRDY);
548 		}
549 	}
550 
551 	time_left = wait_for_completion_timeout(&dev->cmd_complete,
552 					      dev->adapter.timeout);
553 	if (time_left == 0) {
554 		dev->transfer_status |= at91_twi_read(dev, AT91_TWI_SR);
555 		dev_err(dev->dev, "controller timed out\n");
556 		at91_init_twi_bus(dev);
557 		ret = -ETIMEDOUT;
558 		goto error;
559 	}
560 	if (dev->transfer_status & AT91_TWI_NACK) {
561 		dev_dbg(dev->dev, "received nack\n");
562 		ret = -EREMOTEIO;
563 		goto error;
564 	}
565 	if (dev->transfer_status & AT91_TWI_OVRE) {
566 		dev_err(dev->dev, "overrun while reading\n");
567 		ret = -EIO;
568 		goto error;
569 	}
570 	if (has_unre_flag && dev->transfer_status & AT91_TWI_UNRE) {
571 		dev_err(dev->dev, "underrun while writing\n");
572 		ret = -EIO;
573 		goto error;
574 	}
575 	if ((has_alt_cmd || dev->fifo_size) &&
576 	    (dev->transfer_status & AT91_TWI_LOCK)) {
577 		dev_err(dev->dev, "tx locked\n");
578 		ret = -EIO;
579 		goto error;
580 	}
581 	if (dev->recv_len_abort) {
582 		dev_err(dev->dev, "invalid smbus block length recvd\n");
583 		ret = -EPROTO;
584 		goto error;
585 	}
586 
587 	dev_dbg(dev->dev, "transfer complete\n");
588 
589 	return 0;
590 
591 error:
592 	/* first stop DMA transfer if still in progress */
593 	at91_twi_dma_cleanup(dev);
594 	/* then flush THR/FIFO and unlock TX if locked */
595 	if ((has_alt_cmd || dev->fifo_size) &&
596 	    (dev->transfer_status & AT91_TWI_LOCK)) {
597 		dev_dbg(dev->dev, "unlock tx\n");
598 		at91_twi_write(dev, AT91_TWI_CR,
599 			       AT91_TWI_THRCLR | AT91_TWI_LOCKCLR);
600 	}
601 	return ret;
602 }
603 
604 static int at91_twi_xfer(struct i2c_adapter *adap, struct i2c_msg *msg, int num)
605 {
606 	struct at91_twi_dev *dev = i2c_get_adapdata(adap);
607 	int ret;
608 	unsigned int_addr_flag = 0;
609 	struct i2c_msg *m_start = msg;
610 	bool is_read;
611 
612 	dev_dbg(&adap->dev, "at91_xfer: processing %d messages:\n", num);
613 
614 	ret = pm_runtime_get_sync(dev->dev);
615 	if (ret < 0)
616 		goto out;
617 
618 	if (num == 2) {
619 		int internal_address = 0;
620 		int i;
621 
622 		/* 1st msg is put into the internal address, start with 2nd */
623 		m_start = &msg[1];
624 		for (i = 0; i < msg->len; ++i) {
625 			const unsigned addr = msg->buf[msg->len - 1 - i];
626 
627 			internal_address |= addr << (8 * i);
628 			int_addr_flag += AT91_TWI_IADRSZ_1;
629 		}
630 		at91_twi_write(dev, AT91_TWI_IADR, internal_address);
631 	}
632 
633 	dev->use_alt_cmd = false;
634 	is_read = (m_start->flags & I2C_M_RD);
635 	if (dev->pdata->has_alt_cmd) {
636 		if (m_start->len > 0 &&
637 		    m_start->len < AT91_I2C_MAX_ALT_CMD_DATA_SIZE) {
638 			at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_ACMEN);
639 			at91_twi_write(dev, AT91_TWI_ACR,
640 				       AT91_TWI_ACR_DATAL(m_start->len) |
641 				       ((is_read) ? AT91_TWI_ACR_DIR : 0));
642 			dev->use_alt_cmd = true;
643 		} else {
644 			at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_ACMDIS);
645 		}
646 	}
647 
648 	at91_twi_write(dev, AT91_TWI_MMR,
649 		       (m_start->addr << 16) |
650 		       int_addr_flag |
651 		       ((!dev->use_alt_cmd && is_read) ? AT91_TWI_MREAD : 0));
652 
653 	dev->buf_len = m_start->len;
654 	dev->buf = m_start->buf;
655 	dev->msg = m_start;
656 	dev->recv_len_abort = false;
657 
658 	ret = at91_do_twi_transfer(dev);
659 
660 	ret = (ret < 0) ? ret : num;
661 out:
662 	pm_runtime_mark_last_busy(dev->dev);
663 	pm_runtime_put_autosuspend(dev->dev);
664 
665 	return ret;
666 }
667 
668 /*
669  * The hardware can handle at most two messages concatenated by a
670  * repeated start via it's internal address feature.
671  */
672 static const struct i2c_adapter_quirks at91_twi_quirks = {
673 	.flags = I2C_AQ_COMB | I2C_AQ_COMB_WRITE_FIRST | I2C_AQ_COMB_SAME_ADDR,
674 	.max_comb_1st_msg_len = 3,
675 };
676 
677 static u32 at91_twi_func(struct i2c_adapter *adapter)
678 {
679 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL
680 		| I2C_FUNC_SMBUS_READ_BLOCK_DATA;
681 }
682 
683 static const struct i2c_algorithm at91_twi_algorithm = {
684 	.master_xfer	= at91_twi_xfer,
685 	.functionality	= at91_twi_func,
686 };
687 
688 static int at91_twi_configure_dma(struct at91_twi_dev *dev, u32 phy_addr)
689 {
690 	int ret = 0;
691 	struct dma_slave_config slave_config;
692 	struct at91_twi_dma *dma = &dev->dma;
693 	enum dma_slave_buswidth addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
694 
695 	/*
696 	 * The actual width of the access will be chosen in
697 	 * dmaengine_prep_slave_sg():
698 	 * for each buffer in the scatter-gather list, if its size is aligned
699 	 * to addr_width then addr_width accesses will be performed to transfer
700 	 * the buffer. On the other hand, if the buffer size is not aligned to
701 	 * addr_width then the buffer is transferred using single byte accesses.
702 	 * Please refer to the Atmel eXtended DMA controller driver.
703 	 * When FIFOs are used, the TXRDYM threshold can always be set to
704 	 * trigger the XDMAC when at least 4 data can be written into the TX
705 	 * FIFO, even if single byte accesses are performed.
706 	 * However the RXRDYM threshold must be set to fit the access width,
707 	 * deduced from buffer length, so the XDMAC is triggered properly to
708 	 * read data from the RX FIFO.
709 	 */
710 	if (dev->fifo_size)
711 		addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
712 
713 	memset(&slave_config, 0, sizeof(slave_config));
714 	slave_config.src_addr = (dma_addr_t)phy_addr + AT91_TWI_RHR;
715 	slave_config.src_addr_width = addr_width;
716 	slave_config.src_maxburst = 1;
717 	slave_config.dst_addr = (dma_addr_t)phy_addr + AT91_TWI_THR;
718 	slave_config.dst_addr_width = addr_width;
719 	slave_config.dst_maxburst = 1;
720 	slave_config.device_fc = false;
721 
722 	dma->chan_tx = dma_request_slave_channel_reason(dev->dev, "tx");
723 	if (IS_ERR(dma->chan_tx)) {
724 		ret = PTR_ERR(dma->chan_tx);
725 		dma->chan_tx = NULL;
726 		goto error;
727 	}
728 
729 	dma->chan_rx = dma_request_slave_channel_reason(dev->dev, "rx");
730 	if (IS_ERR(dma->chan_rx)) {
731 		ret = PTR_ERR(dma->chan_rx);
732 		dma->chan_rx = NULL;
733 		goto error;
734 	}
735 
736 	slave_config.direction = DMA_MEM_TO_DEV;
737 	if (dmaengine_slave_config(dma->chan_tx, &slave_config)) {
738 		dev_err(dev->dev, "failed to configure tx channel\n");
739 		ret = -EINVAL;
740 		goto error;
741 	}
742 
743 	slave_config.direction = DMA_DEV_TO_MEM;
744 	if (dmaengine_slave_config(dma->chan_rx, &slave_config)) {
745 		dev_err(dev->dev, "failed to configure rx channel\n");
746 		ret = -EINVAL;
747 		goto error;
748 	}
749 
750 	sg_init_table(dma->sg, 2);
751 	dma->buf_mapped = false;
752 	dma->xfer_in_progress = false;
753 	dev->use_dma = true;
754 
755 	dev_info(dev->dev, "using %s (tx) and %s (rx) for DMA transfers\n",
756 		 dma_chan_name(dma->chan_tx), dma_chan_name(dma->chan_rx));
757 
758 	return ret;
759 
760 error:
761 	if (ret != -EPROBE_DEFER)
762 		dev_info(dev->dev, "can't get DMA channel, continue without DMA support\n");
763 	if (dma->chan_rx)
764 		dma_release_channel(dma->chan_rx);
765 	if (dma->chan_tx)
766 		dma_release_channel(dma->chan_tx);
767 	return ret;
768 }
769 
770 int at91_twi_probe_master(struct platform_device *pdev,
771 			  u32 phy_addr, struct at91_twi_dev *dev)
772 {
773 	int rc;
774 
775 	init_completion(&dev->cmd_complete);
776 
777 	rc = devm_request_irq(&pdev->dev, dev->irq, atmel_twi_interrupt, 0,
778 			      dev_name(dev->dev), dev);
779 	if (rc) {
780 		dev_err(dev->dev, "Cannot get irq %d: %d\n", dev->irq, rc);
781 		return rc;
782 	}
783 
784 	if (dev->dev->of_node) {
785 		rc = at91_twi_configure_dma(dev, phy_addr);
786 		if (rc == -EPROBE_DEFER)
787 			return rc;
788 	}
789 
790 	if (!of_property_read_u32(pdev->dev.of_node, "atmel,fifo-size",
791 				  &dev->fifo_size)) {
792 		dev_info(dev->dev, "Using FIFO (%u data)\n", dev->fifo_size);
793 	}
794 
795 	at91_calc_twi_clock(dev);
796 
797 	dev->adapter.algo = &at91_twi_algorithm;
798 	dev->adapter.quirks = &at91_twi_quirks;
799 
800 	return 0;
801 }
802