GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / i2c / busses / i2c-at91.c
1 /*
2  *  i2c Support for Atmel's AT91 Two-Wire Interface (TWI)
3  *
4  *  Copyright (C) 2011 Weinmann Medical GmbH
5  *  Author: Nikolaus Voss <n.voss@weinmann.de>
6  *
7  *  Evolved from original work by:
8  *  Copyright (C) 2004 Rick Bronson
9  *  Converted to 2.6 by Andrew Victor <andrew@sanpeople.com>
10  *
11  *  Borrowed heavily from original work by:
12  *  Copyright (C) 2000 Philip Edelbrock <phil@stimpy.netroedge.com>
13  *
14  *  This program is free software; you can redistribute it and/or modify
15  *  it under the terms of the GNU General Public License as published by
16  *  the Free Software Foundation; either version 2 of the License, or
17  *  (at your option) any later version.
18  */
19
20 #include <linux/clk.h>
21 #include <linux/completion.h>
22 #include <linux/dma-mapping.h>
23 #include <linux/dmaengine.h>
24 #include <linux/err.h>
25 #include <linux/i2c.h>
26 #include <linux/interrupt.h>
27 #include <linux/io.h>
28 #include <linux/module.h>
29 #include <linux/of.h>
30 #include <linux/of_device.h>
31 #include <linux/platform_device.h>
32 #include <linux/slab.h>
33 #include <linux/platform_data/dma-atmel.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/pinctrl/consumer.h>
36
37 #define DEFAULT_TWI_CLK_HZ              100000          /* max 400 Kbits/s */
38 #define AT91_I2C_TIMEOUT        msecs_to_jiffies(100)   /* transfer timeout */
39 #define AT91_I2C_DMA_THRESHOLD  8                       /* enable DMA if transfer size is bigger than this threshold */
40 #define AUTOSUSPEND_TIMEOUT             2000
41 #define AT91_I2C_MAX_ALT_CMD_DATA_SIZE  256
42
43 /* AT91 TWI register definitions */
44 #define AT91_TWI_CR             0x0000  /* Control Register */
45 #define AT91_TWI_START          BIT(0)  /* Send a Start Condition */
46 #define AT91_TWI_STOP           BIT(1)  /* Send a Stop Condition */
47 #define AT91_TWI_MSEN           BIT(2)  /* Master Transfer Enable */
48 #define AT91_TWI_MSDIS          BIT(3)  /* Master Transfer Disable */
49 #define AT91_TWI_SVEN           BIT(4)  /* Slave Transfer Enable */
50 #define AT91_TWI_SVDIS          BIT(5)  /* Slave Transfer Disable */
51 #define AT91_TWI_QUICK          BIT(6)  /* SMBus quick command */
52 #define AT91_TWI_SWRST          BIT(7)  /* Software Reset */
53 #define AT91_TWI_ACMEN          BIT(16) /* Alternative Command Mode Enable */
54 #define AT91_TWI_ACMDIS         BIT(17) /* Alternative Command Mode Disable */
55 #define AT91_TWI_THRCLR         BIT(24) /* Transmit Holding Register Clear */
56 #define AT91_TWI_RHRCLR         BIT(25) /* Receive Holding Register Clear */
57 #define AT91_TWI_LOCKCLR        BIT(26) /* Lock Clear */
58 #define AT91_TWI_FIFOEN         BIT(28) /* FIFO Enable */
59 #define AT91_TWI_FIFODIS        BIT(29) /* FIFO Disable */
60
61 #define AT91_TWI_MMR            0x0004  /* Master Mode Register */
62 #define AT91_TWI_IADRSZ_1       0x0100  /* Internal Device Address Size */
63 #define AT91_TWI_MREAD          BIT(12) /* Master Read Direction */
64
65 #define AT91_TWI_IADR           0x000c  /* Internal Address Register */
66
67 #define AT91_TWI_CWGR           0x0010  /* Clock Waveform Generator Reg */
68 #define AT91_TWI_CWGR_HOLD_MAX  0x1f
69 #define AT91_TWI_CWGR_HOLD(x)   (((x) & AT91_TWI_CWGR_HOLD_MAX) << 24)
70
71 #define AT91_TWI_SR             0x0020  /* Status Register */
72 #define AT91_TWI_TXCOMP         BIT(0)  /* Transmission Complete */
73 #define AT91_TWI_RXRDY          BIT(1)  /* Receive Holding Register Ready */
74 #define AT91_TWI_TXRDY          BIT(2)  /* Transmit Holding Register Ready */
75 #define AT91_TWI_OVRE           BIT(6)  /* Overrun Error */
76 #define AT91_TWI_UNRE           BIT(7)  /* Underrun Error */
77 #define AT91_TWI_NACK           BIT(8)  /* Not Acknowledged */
78 #define AT91_TWI_LOCK           BIT(23) /* TWI Lock due to Frame Errors */
79
80 #define AT91_TWI_INT_MASK \
81         (AT91_TWI_TXCOMP | AT91_TWI_RXRDY | AT91_TWI_TXRDY | AT91_TWI_NACK)
82
83 #define AT91_TWI_IER            0x0024  /* Interrupt Enable Register */
84 #define AT91_TWI_IDR            0x0028  /* Interrupt Disable Register */
85 #define AT91_TWI_IMR            0x002c  /* Interrupt Mask Register */
86 #define AT91_TWI_RHR            0x0030  /* Receive Holding Register */
87 #define AT91_TWI_THR            0x0034  /* Transmit Holding Register */
88
89 #define AT91_TWI_ACR            0x0040  /* Alternative Command Register */
90 #define AT91_TWI_ACR_DATAL(len) ((len) & 0xff)
91 #define AT91_TWI_ACR_DIR        BIT(8)
92
93 #define AT91_TWI_FMR            0x0050  /* FIFO Mode Register */
94 #define AT91_TWI_FMR_TXRDYM(mode)       (((mode) & 0x3) << 0)
95 #define AT91_TWI_FMR_TXRDYM_MASK        (0x3 << 0)
96 #define AT91_TWI_FMR_RXRDYM(mode)       (((mode) & 0x3) << 4)
97 #define AT91_TWI_FMR_RXRDYM_MASK        (0x3 << 4)
98 #define AT91_TWI_ONE_DATA       0x0
99 #define AT91_TWI_TWO_DATA       0x1
100 #define AT91_TWI_FOUR_DATA      0x2
101
102 #define AT91_TWI_FLR            0x0054  /* FIFO Level Register */
103
104 #define AT91_TWI_FSR            0x0060  /* FIFO Status Register */
105 #define AT91_TWI_FIER           0x0064  /* FIFO Interrupt Enable Register */
106 #define AT91_TWI_FIDR           0x0068  /* FIFO Interrupt Disable Register */
107 #define AT91_TWI_FIMR           0x006c  /* FIFO Interrupt Mask Register */
108
109 #define AT91_TWI_VER            0x00fc  /* Version Register */
110
111 struct at91_twi_pdata {
112         unsigned clk_max_div;
113         unsigned clk_offset;
114         bool has_unre_flag;
115         bool has_alt_cmd;
116         bool has_hold_field;
117         struct at_dma_slave dma_slave;
118 };
119
120 struct at91_twi_dma {
121         struct dma_chan *chan_rx;
122         struct dma_chan *chan_tx;
123         struct scatterlist sg[2];
124         struct dma_async_tx_descriptor *data_desc;
125         enum dma_data_direction direction;
126         bool buf_mapped;
127         bool xfer_in_progress;
128 };
129
130 struct at91_twi_dev {
131         struct device *dev;
132         void __iomem *base;
133         struct completion cmd_complete;
134         struct clk *clk;
135         u8 *buf;
136         size_t buf_len;
137         struct i2c_msg *msg;
138         int irq;
139         unsigned imr;
140         unsigned transfer_status;
141         struct i2c_adapter adapter;
142         unsigned twi_cwgr_reg;
143         struct at91_twi_pdata *pdata;
144         bool use_dma;
145         bool use_alt_cmd;
146         bool recv_len_abort;
147         u32 fifo_size;
148         struct at91_twi_dma dma;
149 };
150
151 static unsigned at91_twi_read(struct at91_twi_dev *dev, unsigned reg)
152 {
153         return readl_relaxed(dev->base + reg);
154 }
155
156 static void at91_twi_write(struct at91_twi_dev *dev, unsigned reg, unsigned val)
157 {
158         writel_relaxed(val, dev->base + reg);
159 }
160
161 static void at91_disable_twi_interrupts(struct at91_twi_dev *dev)
162 {
163         at91_twi_write(dev, AT91_TWI_IDR, AT91_TWI_INT_MASK);
164 }
165
166 static void at91_twi_irq_save(struct at91_twi_dev *dev)
167 {
168         dev->imr = at91_twi_read(dev, AT91_TWI_IMR) & AT91_TWI_INT_MASK;
169         at91_disable_twi_interrupts(dev);
170 }
171
172 static void at91_twi_irq_restore(struct at91_twi_dev *dev)
173 {
174         at91_twi_write(dev, AT91_TWI_IER, dev->imr);
175 }
176
177 static void at91_init_twi_bus(struct at91_twi_dev *dev)
178 {
179         at91_disable_twi_interrupts(dev);
180         at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_SWRST);
181         /* FIFO should be enabled immediately after the software reset */
182         if (dev->fifo_size)
183                 at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_FIFOEN);
184         at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_MSEN);
185         at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_SVDIS);
186         at91_twi_write(dev, AT91_TWI_CWGR, dev->twi_cwgr_reg);
187 }
188
189 /*
190  * Calculate symmetric clock as stated in datasheet:
191  * twi_clk = F_MAIN / (2 * (cdiv * (1 << ckdiv) + offset))
192  */
193 static void at91_calc_twi_clock(struct at91_twi_dev *dev, int twi_clk)
194 {
195         int ckdiv, cdiv, div, hold = 0;
196         struct at91_twi_pdata *pdata = dev->pdata;
197         int offset = pdata->clk_offset;
198         int max_ckdiv = pdata->clk_max_div;
199         u32 twd_hold_time_ns = 0;
200
201         div = max(0, (int)DIV_ROUND_UP(clk_get_rate(dev->clk),
202                                        2 * twi_clk) - offset);
203         ckdiv = fls(div >> 8);
204         cdiv = div >> ckdiv;
205
206         if (ckdiv > max_ckdiv) {
207                 dev_warn(dev->dev, "%d exceeds ckdiv max value which is %d.\n",
208                          ckdiv, max_ckdiv);
209                 ckdiv = max_ckdiv;
210                 cdiv = 255;
211         }
212
213         if (pdata->has_hold_field) {
214                 of_property_read_u32(dev->dev->of_node, "i2c-sda-hold-time-ns",
215                                      &twd_hold_time_ns);
216
217                 /*
218                  * hold time = HOLD + 3 x T_peripheral_clock
219                  * Use clk rate in kHz to prevent overflows when computing
220                  * hold.
221                  */
222                 hold = DIV_ROUND_UP(twd_hold_time_ns
223                                     * (clk_get_rate(dev->clk) / 1000), 1000000);
224                 hold -= 3;
225                 if (hold < 0)
226                         hold = 0;
227                 if (hold > AT91_TWI_CWGR_HOLD_MAX) {
228                         dev_warn(dev->dev,
229                                  "HOLD field set to its maximum value (%d instead of %d)\n",
230                                  AT91_TWI_CWGR_HOLD_MAX, hold);
231                         hold = AT91_TWI_CWGR_HOLD_MAX;
232                 }
233         }
234
235         dev->twi_cwgr_reg = (ckdiv << 16) | (cdiv << 8) | cdiv
236                             | AT91_TWI_CWGR_HOLD(hold);
237
238         dev_dbg(dev->dev, "cdiv %d ckdiv %d hold %d (%d ns)\n",
239                 cdiv, ckdiv, hold, twd_hold_time_ns);
240 }
241
242 static void at91_twi_dma_cleanup(struct at91_twi_dev *dev)
243 {
244         struct at91_twi_dma *dma = &dev->dma;
245
246         at91_twi_irq_save(dev);
247
248         if (dma->xfer_in_progress) {
249                 if (dma->direction == DMA_FROM_DEVICE)
250                         dmaengine_terminate_all(dma->chan_rx);
251                 else
252                         dmaengine_terminate_all(dma->chan_tx);
253                 dma->xfer_in_progress = false;
254         }
255         if (dma->buf_mapped) {
256                 dma_unmap_single(dev->dev, sg_dma_address(&dma->sg[0]),
257                                  dev->buf_len, dma->direction);
258                 dma->buf_mapped = false;
259         }
260
261         at91_twi_irq_restore(dev);
262 }
263
264 static void at91_twi_write_next_byte(struct at91_twi_dev *dev)
265 {
266         if (!dev->buf_len)
267                 return;
268
269         /* 8bit write works with and without FIFO */
270         writeb_relaxed(*dev->buf, dev->base + AT91_TWI_THR);
271
272         /* send stop when last byte has been written */
273         if (--dev->buf_len == 0) {
274                 if (!dev->use_alt_cmd)
275                         at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_STOP);
276                 at91_twi_write(dev, AT91_TWI_IDR, AT91_TWI_TXRDY);
277         }
278
279         dev_dbg(dev->dev, "wrote 0x%x, to go %zu\n", *dev->buf, dev->buf_len);
280
281         ++dev->buf;
282 }
283
284 static void at91_twi_write_data_dma_callback(void *data)
285 {
286         struct at91_twi_dev *dev = (struct at91_twi_dev *)data;
287
288         dma_unmap_single(dev->dev, sg_dma_address(&dev->dma.sg[0]),
289                          dev->buf_len, DMA_TO_DEVICE);
290
291         /*
292          * When this callback is called, THR/TX FIFO is likely not to be empty
293          * yet. So we have to wait for TXCOMP or NACK bits to be set into the
294          * Status Register to be sure that the STOP bit has been sent and the
295          * transfer is completed. The NACK interrupt has already been enabled,
296          * we just have to enable TXCOMP one.
297          */
298         at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_TXCOMP);
299         if (!dev->use_alt_cmd)
300                 at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_STOP);
301 }
302
303 static void at91_twi_write_data_dma(struct at91_twi_dev *dev)
304 {
305         dma_addr_t dma_addr;
306         struct dma_async_tx_descriptor *txdesc;
307         struct at91_twi_dma *dma = &dev->dma;
308         struct dma_chan *chan_tx = dma->chan_tx;
309         unsigned int sg_len = 1;
310
311         if (!dev->buf_len)
312                 return;
313
314         dma->direction = DMA_TO_DEVICE;
315
316         at91_twi_irq_save(dev);
317         dma_addr = dma_map_single(dev->dev, dev->buf, dev->buf_len,
318                                   DMA_TO_DEVICE);
319         if (dma_mapping_error(dev->dev, dma_addr)) {
320                 dev_err(dev->dev, "dma map failed\n");
321                 return;
322         }
323         dma->buf_mapped = true;
324         at91_twi_irq_restore(dev);
325
326         if (dev->fifo_size) {
327                 size_t part1_len, part2_len;
328                 struct scatterlist *sg;
329                 unsigned fifo_mr;
330
331                 sg_len = 0;
332
333                 part1_len = dev->buf_len & ~0x3;
334                 if (part1_len) {
335                         sg = &dma->sg[sg_len++];
336                         sg_dma_len(sg) = part1_len;
337                         sg_dma_address(sg) = dma_addr;
338                 }
339
340                 part2_len = dev->buf_len & 0x3;
341                 if (part2_len) {
342                         sg = &dma->sg[sg_len++];
343                         sg_dma_len(sg) = part2_len;
344                         sg_dma_address(sg) = dma_addr + part1_len;
345                 }
346
347                 /*
348                  * DMA controller is triggered when at least 4 data can be
349                  * written into the TX FIFO
350                  */
351                 fifo_mr = at91_twi_read(dev, AT91_TWI_FMR);
352                 fifo_mr &= ~AT91_TWI_FMR_TXRDYM_MASK;
353                 fifo_mr |= AT91_TWI_FMR_TXRDYM(AT91_TWI_FOUR_DATA);
354                 at91_twi_write(dev, AT91_TWI_FMR, fifo_mr);
355         } else {
356                 sg_dma_len(&dma->sg[0]) = dev->buf_len;
357                 sg_dma_address(&dma->sg[0]) = dma_addr;
358         }
359
360         txdesc = dmaengine_prep_slave_sg(chan_tx, dma->sg, sg_len,
361                                          DMA_MEM_TO_DEV,
362                                          DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
363         if (!txdesc) {
364                 dev_err(dev->dev, "dma prep slave sg failed\n");
365                 goto error;
366         }
367
368         txdesc->callback = at91_twi_write_data_dma_callback;
369         txdesc->callback_param = dev;
370
371         dma->xfer_in_progress = true;
372         dmaengine_submit(txdesc);
373         dma_async_issue_pending(chan_tx);
374
375         return;
376
377 error:
378         at91_twi_dma_cleanup(dev);
379 }
380
381 static void at91_twi_read_next_byte(struct at91_twi_dev *dev)
382 {
383         /*
384          * If we are in this case, it means there is garbage data in RHR, so
385          * delete them.
386          */
387         if (!dev->buf_len) {
388                 at91_twi_read(dev, AT91_TWI_RHR);
389                 return;
390         }
391
392         /* 8bit read works with and without FIFO */
393         *dev->buf = readb_relaxed(dev->base + AT91_TWI_RHR);
394         --dev->buf_len;
395
396         /* return if aborting, we only needed to read RHR to clear RXRDY*/
397         if (dev->recv_len_abort)
398                 return;
399
400         /* handle I2C_SMBUS_BLOCK_DATA */
401         if (unlikely(dev->msg->flags & I2C_M_RECV_LEN)) {
402                 /* ensure length byte is a valid value */
403                 if (*dev->buf <= I2C_SMBUS_BLOCK_MAX && *dev->buf > 0) {
404                         dev->msg->flags &= ~I2C_M_RECV_LEN;
405                         dev->buf_len += *dev->buf;
406                         dev->msg->len = dev->buf_len + 1;
407                         dev_dbg(dev->dev, "received block length %zu\n",
408                                          dev->buf_len);
409                 } else {
410                         /* abort and send the stop by reading one more byte */
411                         dev->recv_len_abort = true;
412                         dev->buf_len = 1;
413                 }
414         }
415
416         /* send stop if second but last byte has been read */
417         if (!dev->use_alt_cmd && dev->buf_len == 1)
418                 at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_STOP);
419
420         dev_dbg(dev->dev, "read 0x%x, to go %zu\n", *dev->buf, dev->buf_len);
421
422         ++dev->buf;
423 }
424
425 static void at91_twi_read_data_dma_callback(void *data)
426 {
427         struct at91_twi_dev *dev = (struct at91_twi_dev *)data;
428         unsigned ier = AT91_TWI_TXCOMP;
429
430         dma_unmap_single(dev->dev, sg_dma_address(&dev->dma.sg[0]),
431                          dev->buf_len, DMA_FROM_DEVICE);
432
433         if (!dev->use_alt_cmd) {
434                 /* The last two bytes have to be read without using dma */
435                 dev->buf += dev->buf_len - 2;
436                 dev->buf_len = 2;
437                 ier |= AT91_TWI_RXRDY;
438         }
439         at91_twi_write(dev, AT91_TWI_IER, ier);
440 }
441
442 static void at91_twi_read_data_dma(struct at91_twi_dev *dev)
443 {
444         dma_addr_t dma_addr;
445         struct dma_async_tx_descriptor *rxdesc;
446         struct at91_twi_dma *dma = &dev->dma;
447         struct dma_chan *chan_rx = dma->chan_rx;
448         size_t buf_len;
449
450         buf_len = (dev->use_alt_cmd) ? dev->buf_len : dev->buf_len - 2;
451         dma->direction = DMA_FROM_DEVICE;
452
453         /* Keep in mind that we won't use dma to read the last two bytes */
454         at91_twi_irq_save(dev);
455         dma_addr = dma_map_single(dev->dev, dev->buf, buf_len, DMA_FROM_DEVICE);
456         if (dma_mapping_error(dev->dev, dma_addr)) {
457                 dev_err(dev->dev, "dma map failed\n");
458                 return;
459         }
460         dma->buf_mapped = true;
461         at91_twi_irq_restore(dev);
462
463         if (dev->fifo_size && IS_ALIGNED(buf_len, 4)) {
464                 unsigned fifo_mr;
465
466                 /*
467                  * DMA controller is triggered when at least 4 data can be
468                  * read from the RX FIFO
469                  */
470                 fifo_mr = at91_twi_read(dev, AT91_TWI_FMR);
471                 fifo_mr &= ~AT91_TWI_FMR_RXRDYM_MASK;
472                 fifo_mr |= AT91_TWI_FMR_RXRDYM(AT91_TWI_FOUR_DATA);
473                 at91_twi_write(dev, AT91_TWI_FMR, fifo_mr);
474         }
475
476         sg_dma_len(&dma->sg[0]) = buf_len;
477         sg_dma_address(&dma->sg[0]) = dma_addr;
478
479         rxdesc = dmaengine_prep_slave_sg(chan_rx, dma->sg, 1, DMA_DEV_TO_MEM,
480                                          DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
481         if (!rxdesc) {
482                 dev_err(dev->dev, "dma prep slave sg failed\n");
483                 goto error;
484         }
485
486         rxdesc->callback = at91_twi_read_data_dma_callback;
487         rxdesc->callback_param = dev;
488
489         dma->xfer_in_progress = true;
490         dmaengine_submit(rxdesc);
491         dma_async_issue_pending(dma->chan_rx);
492
493         return;
494
495 error:
496         at91_twi_dma_cleanup(dev);
497 }
498
499 static irqreturn_t atmel_twi_interrupt(int irq, void *dev_id)
500 {
501         struct at91_twi_dev *dev = dev_id;
502         const unsigned status = at91_twi_read(dev, AT91_TWI_SR);
503         const unsigned irqstatus = status & at91_twi_read(dev, AT91_TWI_IMR);
504
505         if (!irqstatus)
506                 return IRQ_NONE;
507         /*
508          * In reception, the behavior of the twi device (before sama5d2) is
509          * weird. There is some magic about RXRDY flag! When a data has been
510          * almost received, the reception of a new one is anticipated if there
511          * is no stop command to send. That is the reason why ask for sending
512          * the stop command not on the last data but on the second last one.
513          *
514          * Unfortunately, we could still have the RXRDY flag set even if the
515          * transfer is done and we have read the last data. It might happen
516          * when the i2c slave device sends too quickly data after receiving the
517          * ack from the master. The data has been almost received before having
518          * the order to send stop. In this case, sending the stop command could
519          * cause a RXRDY interrupt with a TXCOMP one. It is better to manage
520          * the RXRDY interrupt first in order to not keep garbage data in the
521          * Receive Holding Register for the next transfer.
522          */
523         if (irqstatus & AT91_TWI_RXRDY) {
524                 /*
525                  * Read all available bytes at once by polling RXRDY usable w/
526                  * and w/o FIFO. With FIFO enabled we could also read RXFL and
527                  * avoid polling RXRDY.
528                  */
529                 do {
530                         at91_twi_read_next_byte(dev);
531                 } while (at91_twi_read(dev, AT91_TWI_SR) & AT91_TWI_RXRDY);
532         }
533
534         /*
535          * When a NACK condition is detected, the I2C controller sets the NACK,
536          * TXCOMP and TXRDY bits all together in the Status Register (SR).
537          *
538          * 1 - Handling NACK errors with CPU write transfer.
539          *
540          * In such case, we should not write the next byte into the Transmit
541          * Holding Register (THR) otherwise the I2C controller would start a new
542          * transfer and the I2C slave is likely to reply by another NACK.
543          *
544          * 2 - Handling NACK errors with DMA write transfer.
545          *
546          * By setting the TXRDY bit in the SR, the I2C controller also triggers
547          * the DMA controller to write the next data into the THR. Then the
548          * result depends on the hardware version of the I2C controller.
549          *
550          * 2a - Without support of the Alternative Command mode.
551          *
552          * This is the worst case: the DMA controller is triggered to write the
553          * next data into the THR, hence starting a new transfer: the I2C slave
554          * is likely to reply by another NACK.
555          * Concurrently, this interrupt handler is likely to be called to manage
556          * the first NACK before the I2C controller detects the second NACK and
557          * sets once again the NACK bit into the SR.
558          * When handling the first NACK, this interrupt handler disables the I2C
559          * controller interruptions, especially the NACK interrupt.
560          * Hence, the NACK bit is pending into the SR. This is why we should
561          * read the SR to clear all pending interrupts at the beginning of
562          * at91_do_twi_transfer() before actually starting a new transfer.
563          *
564          * 2b - With support of the Alternative Command mode.
565          *
566          * When a NACK condition is detected, the I2C controller also locks the
567          * THR (and sets the LOCK bit in the SR): even though the DMA controller
568          * is triggered by the TXRDY bit to write the next data into the THR,
569          * this data actually won't go on the I2C bus hence a second NACK is not
570          * generated.
571          */
572         if (irqstatus & (AT91_TWI_TXCOMP | AT91_TWI_NACK)) {
573                 at91_disable_twi_interrupts(dev);
574                 complete(&dev->cmd_complete);
575         } else if (irqstatus & AT91_TWI_TXRDY) {
576                 at91_twi_write_next_byte(dev);
577         }
578
579         /* catch error flags */
580         dev->transfer_status |= status;
581
582         return IRQ_HANDLED;
583 }
584
585 static int at91_do_twi_transfer(struct at91_twi_dev *dev)
586 {
587         int ret;
588         unsigned long time_left;
589         bool has_unre_flag = dev->pdata->has_unre_flag;
590         bool has_alt_cmd = dev->pdata->has_alt_cmd;
591
592         /*
593          * WARNING: the TXCOMP bit in the Status Register is NOT a clear on
594          * read flag but shows the state of the transmission at the time the
595          * Status Register is read. According to the programmer datasheet,
596          * TXCOMP is set when both holding register and internal shifter are
597          * empty and STOP condition has been sent.
598          * Consequently, we should enable NACK interrupt rather than TXCOMP to
599          * detect transmission failure.
600          * Indeed let's take the case of an i2c write command using DMA.
601          * Whenever the slave doesn't acknowledge a byte, the LOCK, NACK and
602          * TXCOMP bits are set together into the Status Register.
603          * LOCK is a clear on write bit, which is set to prevent the DMA
604          * controller from sending new data on the i2c bus after a NACK
605          * condition has happened. Once locked, this i2c peripheral stops
606          * triggering the DMA controller for new data but it is more than
607          * likely that a new DMA transaction is already in progress, writing
608          * into the Transmit Holding Register. Since the peripheral is locked,
609          * these new data won't be sent to the i2c bus but they will remain
610          * into the Transmit Holding Register, so TXCOMP bit is cleared.
611          * Then when the interrupt handler is called, the Status Register is
612          * read: the TXCOMP bit is clear but NACK bit is still set. The driver
613          * manage the error properly, without waiting for timeout.
614          * This case can be reproduced easyly when writing into an at24 eeprom.
615          *
616          * Besides, the TXCOMP bit is already set before the i2c transaction
617          * has been started. For read transactions, this bit is cleared when
618          * writing the START bit into the Control Register. So the
619          * corresponding interrupt can safely be enabled just after.
620          * However for write transactions managed by the CPU, we first write
621          * into THR, so TXCOMP is cleared. Then we can safely enable TXCOMP
622          * interrupt. If TXCOMP interrupt were enabled before writing into THR,
623          * the interrupt handler would be called immediately and the i2c command
624          * would be reported as completed.
625          * Also when a write transaction is managed by the DMA controller,
626          * enabling the TXCOMP interrupt in this function may lead to a race
627          * condition since we don't know whether the TXCOMP interrupt is enabled
628          * before or after the DMA has started to write into THR. So the TXCOMP
629          * interrupt is enabled later by at91_twi_write_data_dma_callback().
630          * Immediately after in that DMA callback, if the alternative command
631          * mode is not used, we still need to send the STOP condition manually
632          * writing the corresponding bit into the Control Register.
633          */
634
635         dev_dbg(dev->dev, "transfer: %s %zu bytes.\n",
636                 (dev->msg->flags & I2C_M_RD) ? "read" : "write", dev->buf_len);
637
638         reinit_completion(&dev->cmd_complete);
639         dev->transfer_status = 0;
640
641         /* Clear pending interrupts, such as NACK. */
642         at91_twi_read(dev, AT91_TWI_SR);
643
644         if (dev->fifo_size) {
645                 unsigned fifo_mr = at91_twi_read(dev, AT91_TWI_FMR);
646
647                 /* Reset FIFO mode register */
648                 fifo_mr &= ~(AT91_TWI_FMR_TXRDYM_MASK |
649                              AT91_TWI_FMR_RXRDYM_MASK);
650                 fifo_mr |= AT91_TWI_FMR_TXRDYM(AT91_TWI_ONE_DATA);
651                 fifo_mr |= AT91_TWI_FMR_RXRDYM(AT91_TWI_ONE_DATA);
652                 at91_twi_write(dev, AT91_TWI_FMR, fifo_mr);
653
654                 /* Flush FIFOs */
655                 at91_twi_write(dev, AT91_TWI_CR,
656                                AT91_TWI_THRCLR | AT91_TWI_RHRCLR);
657         }
658
659         if (!dev->buf_len) {
660                 at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_QUICK);
661                 at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_TXCOMP);
662         } else if (dev->msg->flags & I2C_M_RD) {
663                 unsigned start_flags = AT91_TWI_START;
664
665                 /* if only one byte is to be read, immediately stop transfer */
666                 if (!dev->use_alt_cmd && dev->buf_len <= 1 &&
667                     !(dev->msg->flags & I2C_M_RECV_LEN))
668                         start_flags |= AT91_TWI_STOP;
669                 at91_twi_write(dev, AT91_TWI_CR, start_flags);
670                 /*
671                  * When using dma without alternative command mode, the last
672                  * byte has to be read manually in order to not send the stop
673                  * command too late and then to receive extra data.
674                  * In practice, there are some issues if you use the dma to
675                  * read n-1 bytes because of latency.
676                  * Reading n-2 bytes with dma and the two last ones manually
677                  * seems to be the best solution.
678                  */
679                 if (dev->use_dma && (dev->buf_len > AT91_I2C_DMA_THRESHOLD)) {
680                         at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_NACK);
681                         at91_twi_read_data_dma(dev);
682                 } else {
683                         at91_twi_write(dev, AT91_TWI_IER,
684                                        AT91_TWI_TXCOMP |
685                                        AT91_TWI_NACK |
686                                        AT91_TWI_RXRDY);
687                 }
688         } else {
689                 if (dev->use_dma && (dev->buf_len > AT91_I2C_DMA_THRESHOLD)) {
690                         at91_twi_write(dev, AT91_TWI_IER, AT91_TWI_NACK);
691                         at91_twi_write_data_dma(dev);
692                 } else {
693                         at91_twi_write_next_byte(dev);
694                         at91_twi_write(dev, AT91_TWI_IER,
695                                        AT91_TWI_TXCOMP | AT91_TWI_NACK |
696                                        (dev->buf_len ? AT91_TWI_TXRDY : 0));
697                 }
698         }
699
700         time_left = wait_for_completion_timeout(&dev->cmd_complete,
701                                               dev->adapter.timeout);
702         if (time_left == 0) {
703                 dev->transfer_status |= at91_twi_read(dev, AT91_TWI_SR);
704                 dev_err(dev->dev, "controller timed out\n");
705                 at91_init_twi_bus(dev);
706                 ret = -ETIMEDOUT;
707                 goto error;
708         }
709         if (dev->transfer_status & AT91_TWI_NACK) {
710                 dev_dbg(dev->dev, "received nack\n");
711                 ret = -EREMOTEIO;
712                 goto error;
713         }
714         if (dev->transfer_status & AT91_TWI_OVRE) {
715                 dev_err(dev->dev, "overrun while reading\n");
716                 ret = -EIO;
717                 goto error;
718         }
719         if (has_unre_flag && dev->transfer_status & AT91_TWI_UNRE) {
720                 dev_err(dev->dev, "underrun while writing\n");
721                 ret = -EIO;
722                 goto error;
723         }
724         if ((has_alt_cmd || dev->fifo_size) &&
725             (dev->transfer_status & AT91_TWI_LOCK)) {
726                 dev_err(dev->dev, "tx locked\n");
727                 ret = -EIO;
728                 goto error;
729         }
730         if (dev->recv_len_abort) {
731                 dev_err(dev->dev, "invalid smbus block length recvd\n");
732                 ret = -EPROTO;
733                 goto error;
734         }
735
736         dev_dbg(dev->dev, "transfer complete\n");
737
738         return 0;
739
740 error:
741         /* first stop DMA transfer if still in progress */
742         at91_twi_dma_cleanup(dev);
743         /* then flush THR/FIFO and unlock TX if locked */
744         if ((has_alt_cmd || dev->fifo_size) &&
745             (dev->transfer_status & AT91_TWI_LOCK)) {
746                 dev_dbg(dev->dev, "unlock tx\n");
747                 at91_twi_write(dev, AT91_TWI_CR,
748                                AT91_TWI_THRCLR | AT91_TWI_LOCKCLR);
749         }
750         return ret;
751 }
752
753 static int at91_twi_xfer(struct i2c_adapter *adap, struct i2c_msg *msg, int num)
754 {
755         struct at91_twi_dev *dev = i2c_get_adapdata(adap);
756         int ret;
757         unsigned int_addr_flag = 0;
758         struct i2c_msg *m_start = msg;
759         bool is_read;
760         u8 *dma_buf = NULL;
761
762         dev_dbg(&adap->dev, "at91_xfer: processing %d messages:\n", num);
763
764         ret = pm_runtime_get_sync(dev->dev);
765         if (ret < 0)
766                 goto out;
767
768         if (num == 2) {
769                 int internal_address = 0;
770                 int i;
771
772                 /* 1st msg is put into the internal address, start with 2nd */
773                 m_start = &msg[1];
774                 for (i = 0; i < msg->len; ++i) {
775                         const unsigned addr = msg->buf[msg->len - 1 - i];
776
777                         internal_address |= addr << (8 * i);
778                         int_addr_flag += AT91_TWI_IADRSZ_1;
779                 }
780                 at91_twi_write(dev, AT91_TWI_IADR, internal_address);
781         }
782
783         dev->use_alt_cmd = false;
784         is_read = (m_start->flags & I2C_M_RD);
785         if (dev->pdata->has_alt_cmd) {
786                 if (m_start->len > 0 &&
787                     m_start->len < AT91_I2C_MAX_ALT_CMD_DATA_SIZE) {
788                         at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_ACMEN);
789                         at91_twi_write(dev, AT91_TWI_ACR,
790                                        AT91_TWI_ACR_DATAL(m_start->len) |
791                                        ((is_read) ? AT91_TWI_ACR_DIR : 0));
792                         dev->use_alt_cmd = true;
793                 } else {
794                         at91_twi_write(dev, AT91_TWI_CR, AT91_TWI_ACMDIS);
795                 }
796         }
797
798         at91_twi_write(dev, AT91_TWI_MMR,
799                        (m_start->addr << 16) |
800                        int_addr_flag |
801                        ((!dev->use_alt_cmd && is_read) ? AT91_TWI_MREAD : 0));
802
803         dev->buf_len = m_start->len;
804         dev->buf = m_start->buf;
805         dev->msg = m_start;
806         dev->recv_len_abort = false;
807
808         if (dev->use_dma) {
809                 dma_buf = i2c_get_dma_safe_msg_buf(m_start, 1);
810                 if (!dma_buf) {
811                         ret = -ENOMEM;
812                         goto out;
813                 }
814                 dev->buf = dma_buf;
815         }
816
817         ret = at91_do_twi_transfer(dev);
818         i2c_put_dma_safe_msg_buf(dma_buf, m_start, !ret);
819
820         ret = (ret < 0) ? ret : num;
821 out:
822         pm_runtime_mark_last_busy(dev->dev);
823         pm_runtime_put_autosuspend(dev->dev);
824
825         return ret;
826 }
827
828 /*
829  * The hardware can handle at most two messages concatenated by a
830  * repeated start via it's internal address feature.
831  */
832 static const struct i2c_adapter_quirks at91_twi_quirks = {
833         .flags = I2C_AQ_COMB | I2C_AQ_COMB_WRITE_FIRST | I2C_AQ_COMB_SAME_ADDR,
834         .max_comb_1st_msg_len = 3,
835 };
836
837 static u32 at91_twi_func(struct i2c_adapter *adapter)
838 {
839         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL
840                 | I2C_FUNC_SMBUS_READ_BLOCK_DATA;
841 }
842
843 static const struct i2c_algorithm at91_twi_algorithm = {
844         .master_xfer    = at91_twi_xfer,
845         .functionality  = at91_twi_func,
846 };
847
848 static struct at91_twi_pdata at91rm9200_config = {
849         .clk_max_div = 5,
850         .clk_offset = 3,
851         .has_unre_flag = true,
852         .has_alt_cmd = false,
853         .has_hold_field = false,
854 };
855
856 static struct at91_twi_pdata at91sam9261_config = {
857         .clk_max_div = 5,
858         .clk_offset = 4,
859         .has_unre_flag = false,
860         .has_alt_cmd = false,
861         .has_hold_field = false,
862 };
863
864 static struct at91_twi_pdata at91sam9260_config = {
865         .clk_max_div = 7,
866         .clk_offset = 4,
867         .has_unre_flag = false,
868         .has_alt_cmd = false,
869         .has_hold_field = false,
870 };
871
872 static struct at91_twi_pdata at91sam9g20_config = {
873         .clk_max_div = 7,
874         .clk_offset = 4,
875         .has_unre_flag = false,
876         .has_alt_cmd = false,
877         .has_hold_field = false,
878 };
879
880 static struct at91_twi_pdata at91sam9g10_config = {
881         .clk_max_div = 7,
882         .clk_offset = 4,
883         .has_unre_flag = false,
884         .has_alt_cmd = false,
885         .has_hold_field = false,
886 };
887
888 static const struct platform_device_id at91_twi_devtypes[] = {
889         {
890                 .name = "i2c-at91rm9200",
891                 .driver_data = (unsigned long) &at91rm9200_config,
892         }, {
893                 .name = "i2c-at91sam9261",
894                 .driver_data = (unsigned long) &at91sam9261_config,
895         }, {
896                 .name = "i2c-at91sam9260",
897                 .driver_data = (unsigned long) &at91sam9260_config,
898         }, {
899                 .name = "i2c-at91sam9g20",
900                 .driver_data = (unsigned long) &at91sam9g20_config,
901         }, {
902                 .name = "i2c-at91sam9g10",
903                 .driver_data = (unsigned long) &at91sam9g10_config,
904         }, {
905                 /* sentinel */
906         }
907 };
908
909 #if defined(CONFIG_OF)
910 static struct at91_twi_pdata at91sam9x5_config = {
911         .clk_max_div = 7,
912         .clk_offset = 4,
913         .has_unre_flag = false,
914         .has_alt_cmd = false,
915         .has_hold_field = false,
916 };
917
918 static struct at91_twi_pdata sama5d4_config = {
919         .clk_max_div = 7,
920         .clk_offset = 4,
921         .has_unre_flag = false,
922         .has_alt_cmd = false,
923         .has_hold_field = true,
924 };
925
926 static struct at91_twi_pdata sama5d2_config = {
927         .clk_max_div = 7,
928         .clk_offset = 3,
929         .has_unre_flag = true,
930         .has_alt_cmd = true,
931         .has_hold_field = true,
932 };
933
934 static const struct of_device_id atmel_twi_dt_ids[] = {
935         {
936                 .compatible = "atmel,at91rm9200-i2c",
937                 .data = &at91rm9200_config,
938         } , {
939                 .compatible = "atmel,at91sam9260-i2c",
940                 .data = &at91sam9260_config,
941         } , {
942                 .compatible = "atmel,at91sam9261-i2c",
943                 .data = &at91sam9261_config,
944         } , {
945                 .compatible = "atmel,at91sam9g20-i2c",
946                 .data = &at91sam9g20_config,
947         } , {
948                 .compatible = "atmel,at91sam9g10-i2c",
949                 .data = &at91sam9g10_config,
950         }, {
951                 .compatible = "atmel,at91sam9x5-i2c",
952                 .data = &at91sam9x5_config,
953         }, {
954                 .compatible = "atmel,sama5d4-i2c",
955                 .data = &sama5d4_config,
956         }, {
957                 .compatible = "atmel,sama5d2-i2c",
958                 .data = &sama5d2_config,
959         }, {
960                 /* sentinel */
961         }
962 };
963 MODULE_DEVICE_TABLE(of, atmel_twi_dt_ids);
964 #endif
965
966 static int at91_twi_configure_dma(struct at91_twi_dev *dev, u32 phy_addr)
967 {
968         int ret = 0;
969         struct dma_slave_config slave_config;
970         struct at91_twi_dma *dma = &dev->dma;
971         enum dma_slave_buswidth addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
972
973         /*
974          * The actual width of the access will be chosen in
975          * dmaengine_prep_slave_sg():
976          * for each buffer in the scatter-gather list, if its size is aligned
977          * to addr_width then addr_width accesses will be performed to transfer
978          * the buffer. On the other hand, if the buffer size is not aligned to
979          * addr_width then the buffer is transferred using single byte accesses.
980          * Please refer to the Atmel eXtended DMA controller driver.
981          * When FIFOs are used, the TXRDYM threshold can always be set to
982          * trigger the XDMAC when at least 4 data can be written into the TX
983          * FIFO, even if single byte accesses are performed.
984          * However the RXRDYM threshold must be set to fit the access width,
985          * deduced from buffer length, so the XDMAC is triggered properly to
986          * read data from the RX FIFO.
987          */
988         if (dev->fifo_size)
989                 addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
990
991         memset(&slave_config, 0, sizeof(slave_config));
992         slave_config.src_addr = (dma_addr_t)phy_addr + AT91_TWI_RHR;
993         slave_config.src_addr_width = addr_width;
994         slave_config.src_maxburst = 1;
995         slave_config.dst_addr = (dma_addr_t)phy_addr + AT91_TWI_THR;
996         slave_config.dst_addr_width = addr_width;
997         slave_config.dst_maxburst = 1;
998         slave_config.device_fc = false;
999
1000         dma->chan_tx = dma_request_slave_channel_reason(dev->dev, "tx");
1001         if (IS_ERR(dma->chan_tx)) {
1002                 ret = PTR_ERR(dma->chan_tx);
1003                 dma->chan_tx = NULL;
1004                 goto error;
1005         }
1006
1007         dma->chan_rx = dma_request_slave_channel_reason(dev->dev, "rx");
1008         if (IS_ERR(dma->chan_rx)) {
1009                 ret = PTR_ERR(dma->chan_rx);
1010                 dma->chan_rx = NULL;
1011                 goto error;
1012         }
1013
1014         slave_config.direction = DMA_MEM_TO_DEV;
1015         if (dmaengine_slave_config(dma->chan_tx, &slave_config)) {
1016                 dev_err(dev->dev, "failed to configure tx channel\n");
1017                 ret = -EINVAL;
1018                 goto error;
1019         }
1020
1021         slave_config.direction = DMA_DEV_TO_MEM;
1022         if (dmaengine_slave_config(dma->chan_rx, &slave_config)) {
1023                 dev_err(dev->dev, "failed to configure rx channel\n");
1024                 ret = -EINVAL;
1025                 goto error;
1026         }
1027
1028         sg_init_table(dma->sg, 2);
1029         dma->buf_mapped = false;
1030         dma->xfer_in_progress = false;
1031         dev->use_dma = true;
1032
1033         dev_info(dev->dev, "using %s (tx) and %s (rx) for DMA transfers\n",
1034                  dma_chan_name(dma->chan_tx), dma_chan_name(dma->chan_rx));
1035
1036         return ret;
1037
1038 error:
1039         if (ret != -EPROBE_DEFER)
1040                 dev_info(dev->dev, "can't get DMA channel, continue without DMA support\n");
1041         if (dma->chan_rx)
1042                 dma_release_channel(dma->chan_rx);
1043         if (dma->chan_tx)
1044                 dma_release_channel(dma->chan_tx);
1045         return ret;
1046 }
1047
1048 static struct at91_twi_pdata *at91_twi_get_driver_data(
1049                                         struct platform_device *pdev)
1050 {
1051         if (pdev->dev.of_node) {
1052                 const struct of_device_id *match;
1053                 match = of_match_node(atmel_twi_dt_ids, pdev->dev.of_node);
1054                 if (!match)
1055                         return NULL;
1056                 return (struct at91_twi_pdata *)match->data;
1057         }
1058         return (struct at91_twi_pdata *) platform_get_device_id(pdev)->driver_data;
1059 }
1060
1061 static int at91_twi_probe(struct platform_device *pdev)
1062 {
1063         struct at91_twi_dev *dev;
1064         struct resource *mem;
1065         int rc;
1066         u32 phy_addr;
1067         u32 bus_clk_rate;
1068
1069         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
1070         if (!dev)
1071                 return -ENOMEM;
1072         init_completion(&dev->cmd_complete);
1073         dev->dev = &pdev->dev;
1074
1075         mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1076         if (!mem)
1077                 return -ENODEV;
1078         phy_addr = mem->start;
1079
1080         dev->pdata = at91_twi_get_driver_data(pdev);
1081         if (!dev->pdata)
1082                 return -ENODEV;
1083
1084         dev->base = devm_ioremap_resource(&pdev->dev, mem);
1085         if (IS_ERR(dev->base))
1086                 return PTR_ERR(dev->base);
1087
1088         dev->irq = platform_get_irq(pdev, 0);
1089         if (dev->irq < 0)
1090                 return dev->irq;
1091
1092         rc = devm_request_irq(&pdev->dev, dev->irq, atmel_twi_interrupt, 0,
1093                          dev_name(dev->dev), dev);
1094         if (rc) {
1095                 dev_err(dev->dev, "Cannot get irq %d: %d\n", dev->irq, rc);
1096                 return rc;
1097         }
1098
1099         platform_set_drvdata(pdev, dev);
1100
1101         dev->clk = devm_clk_get(dev->dev, NULL);
1102         if (IS_ERR(dev->clk)) {
1103                 dev_err(dev->dev, "no clock defined\n");
1104                 return -ENODEV;
1105         }
1106         rc = clk_prepare_enable(dev->clk);
1107         if (rc)
1108                 return rc;
1109
1110         if (dev->dev->of_node) {
1111                 rc = at91_twi_configure_dma(dev, phy_addr);
1112                 if (rc == -EPROBE_DEFER) {
1113                         clk_disable_unprepare(dev->clk);
1114                         return rc;
1115                 }
1116         }
1117
1118         if (!of_property_read_u32(pdev->dev.of_node, "atmel,fifo-size",
1119                                   &dev->fifo_size)) {
1120                 dev_info(dev->dev, "Using FIFO (%u data)\n", dev->fifo_size);
1121         }
1122
1123         rc = of_property_read_u32(dev->dev->of_node, "clock-frequency",
1124                         &bus_clk_rate);
1125         if (rc)
1126                 bus_clk_rate = DEFAULT_TWI_CLK_HZ;
1127
1128         at91_calc_twi_clock(dev, bus_clk_rate);
1129         at91_init_twi_bus(dev);
1130
1131         snprintf(dev->adapter.name, sizeof(dev->adapter.name), "AT91");
1132         i2c_set_adapdata(&dev->adapter, dev);
1133         dev->adapter.owner = THIS_MODULE;
1134         dev->adapter.class = I2C_CLASS_DEPRECATED;
1135         dev->adapter.algo = &at91_twi_algorithm;
1136         dev->adapter.quirks = &at91_twi_quirks;
1137         dev->adapter.dev.parent = dev->dev;
1138         dev->adapter.nr = pdev->id;
1139         dev->adapter.timeout = AT91_I2C_TIMEOUT;
1140         dev->adapter.dev.of_node = pdev->dev.of_node;
1141
1142         pm_runtime_set_autosuspend_delay(dev->dev, AUTOSUSPEND_TIMEOUT);
1143         pm_runtime_use_autosuspend(dev->dev);
1144         pm_runtime_set_active(dev->dev);
1145         pm_runtime_enable(dev->dev);
1146
1147         rc = i2c_add_numbered_adapter(&dev->adapter);
1148         if (rc) {
1149                 clk_disable_unprepare(dev->clk);
1150
1151                 pm_runtime_disable(dev->dev);
1152                 pm_runtime_set_suspended(dev->dev);
1153
1154                 return rc;
1155         }
1156
1157         dev_info(dev->dev, "AT91 i2c bus driver (hw version: %#x).\n",
1158                  at91_twi_read(dev, AT91_TWI_VER));
1159         return 0;
1160 }
1161
1162 static int at91_twi_remove(struct platform_device *pdev)
1163 {
1164         struct at91_twi_dev *dev = platform_get_drvdata(pdev);
1165
1166         i2c_del_adapter(&dev->adapter);
1167         clk_disable_unprepare(dev->clk);
1168
1169         pm_runtime_disable(dev->dev);
1170         pm_runtime_set_suspended(dev->dev);
1171
1172         return 0;
1173 }
1174
1175 #ifdef CONFIG_PM
1176
1177 static int at91_twi_runtime_suspend(struct device *dev)
1178 {
1179         struct at91_twi_dev *twi_dev = dev_get_drvdata(dev);
1180
1181         clk_disable_unprepare(twi_dev->clk);
1182
1183         pinctrl_pm_select_sleep_state(dev);
1184
1185         return 0;
1186 }
1187
1188 static int at91_twi_runtime_resume(struct device *dev)
1189 {
1190         struct at91_twi_dev *twi_dev = dev_get_drvdata(dev);
1191
1192         pinctrl_pm_select_default_state(dev);
1193
1194         return clk_prepare_enable(twi_dev->clk);
1195 }
1196
1197 static int at91_twi_suspend_noirq(struct device *dev)
1198 {
1199         if (!pm_runtime_status_suspended(dev))
1200                 at91_twi_runtime_suspend(dev);
1201
1202         return 0;
1203 }
1204
1205 static int at91_twi_resume_noirq(struct device *dev)
1206 {
1207         struct at91_twi_dev *twi_dev = dev_get_drvdata(dev);
1208         int ret;
1209
1210         if (!pm_runtime_status_suspended(dev)) {
1211                 ret = at91_twi_runtime_resume(dev);
1212                 if (ret)
1213                         return ret;
1214         }
1215
1216         pm_runtime_mark_last_busy(dev);
1217         pm_request_autosuspend(dev);
1218
1219         at91_init_twi_bus(twi_dev);
1220
1221         return 0;
1222 }
1223
1224 static const struct dev_pm_ops at91_twi_pm = {
1225         .suspend_noirq  = at91_twi_suspend_noirq,
1226         .resume_noirq   = at91_twi_resume_noirq,
1227         .runtime_suspend        = at91_twi_runtime_suspend,
1228         .runtime_resume         = at91_twi_runtime_resume,
1229 };
1230
1231 #define at91_twi_pm_ops (&at91_twi_pm)
1232 #else
1233 #define at91_twi_pm_ops NULL
1234 #endif
1235
1236 static struct platform_driver at91_twi_driver = {
1237         .probe          = at91_twi_probe,
1238         .remove         = at91_twi_remove,
1239         .id_table       = at91_twi_devtypes,
1240         .driver         = {
1241                 .name   = "at91_i2c",
1242                 .of_match_table = of_match_ptr(atmel_twi_dt_ids),
1243                 .pm     = at91_twi_pm_ops,
1244         },
1245 };
1246
1247 static int __init at91_twi_init(void)
1248 {
1249         return platform_driver_register(&at91_twi_driver);
1250 }
1251
1252 static void __exit at91_twi_exit(void)
1253 {
1254         platform_driver_unregister(&at91_twi_driver);
1255 }
1256
1257 subsys_initcall(at91_twi_init);
1258 module_exit(at91_twi_exit);
1259
1260 MODULE_AUTHOR("Nikolaus Voss <n.voss@weinmann.de>");
1261 MODULE_DESCRIPTION("I2C (TWI) driver for Atmel AT91");
1262 MODULE_LICENSE("GPL");
1263 MODULE_ALIAS("platform:at91_i2c");