GNU Linux-libre 4.14.266-gnu1
[releases.git] / drivers / i2c / busses / i2c-rcar.c
1 /*
2  * Driver for the Renesas R-Car I2C unit
3  *
4  * Copyright (C) 2014-15 Wolfram Sang <wsa@sang-engineering.com>
5  * Copyright (C) 2011-2015 Renesas Electronics Corporation
6  *
7  * Copyright (C) 2012-14 Renesas Solutions Corp.
8  * Kuninori Morimoto <kuninori.morimoto.gx@renesas.com>
9  *
10  * This file is based on the drivers/i2c/busses/i2c-sh7760.c
11  * (c) 2005-2008 MSC Vertriebsges.m.b.H, Manuel Lauss <mlau@msc-ge.com>
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; version 2 of the License.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  */
22 #include <linux/clk.h>
23 #include <linux/delay.h>
24 #include <linux/dmaengine.h>
25 #include <linux/dma-mapping.h>
26 #include <linux/err.h>
27 #include <linux/interrupt.h>
28 #include <linux/io.h>
29 #include <linux/i2c.h>
30 #include <linux/kernel.h>
31 #include <linux/module.h>
32 #include <linux/of_device.h>
33 #include <linux/platform_device.h>
34 #include <linux/pm_runtime.h>
35 #include <linux/reset.h>
36 #include <linux/slab.h>
37
38 /* register offsets */
39 #define ICSCR   0x00    /* slave ctrl */
40 #define ICMCR   0x04    /* master ctrl */
41 #define ICSSR   0x08    /* slave status */
42 #define ICMSR   0x0C    /* master status */
43 #define ICSIER  0x10    /* slave irq enable */
44 #define ICMIER  0x14    /* master irq enable */
45 #define ICCCR   0x18    /* clock dividers */
46 #define ICSAR   0x1C    /* slave address */
47 #define ICMAR   0x20    /* master address */
48 #define ICRXTX  0x24    /* data port */
49 #define ICDMAER 0x3c    /* DMA enable */
50 #define ICFBSCR 0x38    /* first bit setup cycle */
51
52 /* ICSCR */
53 #define SDBS    (1 << 3)        /* slave data buffer select */
54 #define SIE     (1 << 2)        /* slave interface enable */
55 #define GCAE    (1 << 1)        /* general call address enable */
56 #define FNA     (1 << 0)        /* forced non acknowledgment */
57
58 /* ICMCR */
59 #define MDBS    (1 << 7)        /* non-fifo mode switch */
60 #define FSCL    (1 << 6)        /* override SCL pin */
61 #define FSDA    (1 << 5)        /* override SDA pin */
62 #define OBPC    (1 << 4)        /* override pins */
63 #define MIE     (1 << 3)        /* master if enable */
64 #define TSBE    (1 << 2)
65 #define FSB     (1 << 1)        /* force stop bit */
66 #define ESG     (1 << 0)        /* en startbit gen */
67
68 /* ICSSR (also for ICSIER) */
69 #define GCAR    (1 << 6)        /* general call received */
70 #define STM     (1 << 5)        /* slave transmit mode */
71 #define SSR     (1 << 4)        /* stop received */
72 #define SDE     (1 << 3)        /* slave data empty */
73 #define SDT     (1 << 2)        /* slave data transmitted */
74 #define SDR     (1 << 1)        /* slave data received */
75 #define SAR     (1 << 0)        /* slave addr received */
76
77 /* ICMSR (also for ICMIE) */
78 #define MNR     (1 << 6)        /* nack received */
79 #define MAL     (1 << 5)        /* arbitration lost */
80 #define MST     (1 << 4)        /* sent a stop */
81 #define MDE     (1 << 3)
82 #define MDT     (1 << 2)
83 #define MDR     (1 << 1)
84 #define MAT     (1 << 0)        /* slave addr xfer done */
85
86 /* ICDMAER */
87 #define RSDMAE  (1 << 3)        /* DMA Slave Received Enable */
88 #define TSDMAE  (1 << 2)        /* DMA Slave Transmitted Enable */
89 #define RMDMAE  (1 << 1)        /* DMA Master Received Enable */
90 #define TMDMAE  (1 << 0)        /* DMA Master Transmitted Enable */
91
92 /* ICFBSCR */
93 #define TCYC06  0x04            /*  6*Tcyc delay 1st bit between SDA and SCL */
94 #define TCYC17  0x0f            /* 17*Tcyc delay 1st bit between SDA and SCL */
95
96
97 #define RCAR_BUS_PHASE_START    (MDBS | MIE | ESG)
98 #define RCAR_BUS_PHASE_DATA     (MDBS | MIE)
99 #define RCAR_BUS_MASK_DATA      (~(ESG | FSB) & 0xFF)
100 #define RCAR_BUS_PHASE_STOP     (MDBS | MIE | FSB)
101
102 #define RCAR_IRQ_SEND   (MNR | MAL | MST | MAT | MDE)
103 #define RCAR_IRQ_RECV   (MNR | MAL | MST | MAT | MDR)
104 #define RCAR_IRQ_STOP   (MST)
105
106 #define RCAR_IRQ_ACK_SEND       (~(MAT | MDE) & 0xFF)
107 #define RCAR_IRQ_ACK_RECV       (~(MAT | MDR) & 0xFF)
108
109 #define ID_LAST_MSG     (1 << 0)
110 #define ID_FIRST_MSG    (1 << 1)
111 #define ID_DONE         (1 << 2)
112 #define ID_ARBLOST      (1 << 3)
113 #define ID_NACK         (1 << 4)
114 /* persistent flags */
115 #define ID_P_NO_RXDMA   (1 << 30) /* HW forbids RXDMA sometimes */
116 #define ID_P_PM_BLOCKED (1 << 31)
117 #define ID_P_MASK       (ID_P_PM_BLOCKED | ID_P_NO_RXDMA)
118
119 enum rcar_i2c_type {
120         I2C_RCAR_GEN1,
121         I2C_RCAR_GEN2,
122         I2C_RCAR_GEN3,
123 };
124
125 struct rcar_i2c_priv {
126         void __iomem *io;
127         struct i2c_adapter adap;
128         struct i2c_msg *msg;
129         int msgs_left;
130         struct clk *clk;
131
132         wait_queue_head_t wait;
133
134         int pos;
135         u32 icccr;
136         u32 flags;
137         enum rcar_i2c_type devtype;
138         struct i2c_client *slave;
139
140         struct resource *res;
141         struct dma_chan *dma_tx;
142         struct dma_chan *dma_rx;
143         struct scatterlist sg;
144         enum dma_data_direction dma_direction;
145
146         struct reset_control *rstc;
147         int irq;
148 };
149
150 #define rcar_i2c_priv_to_dev(p)         ((p)->adap.dev.parent)
151 #define rcar_i2c_is_recv(p)             ((p)->msg->flags & I2C_M_RD)
152
153 #define LOOP_TIMEOUT    1024
154
155
156 static void rcar_i2c_write(struct rcar_i2c_priv *priv, int reg, u32 val)
157 {
158         writel(val, priv->io + reg);
159 }
160
161 static u32 rcar_i2c_read(struct rcar_i2c_priv *priv, int reg)
162 {
163         return readl(priv->io + reg);
164 }
165
166 static void rcar_i2c_init(struct rcar_i2c_priv *priv)
167 {
168         /* reset master mode */
169         rcar_i2c_write(priv, ICMIER, 0);
170         rcar_i2c_write(priv, ICMCR, MDBS);
171         rcar_i2c_write(priv, ICMSR, 0);
172         /* start clock */
173         rcar_i2c_write(priv, ICCCR, priv->icccr);
174 }
175
176 static int rcar_i2c_bus_barrier(struct rcar_i2c_priv *priv)
177 {
178         int i;
179
180         for (i = 0; i < LOOP_TIMEOUT; i++) {
181                 /* make sure that bus is not busy */
182                 if (!(rcar_i2c_read(priv, ICMCR) & FSDA))
183                         return 0;
184                 udelay(1);
185         }
186
187         return -EBUSY;
188 }
189
190 static int rcar_i2c_clock_calculate(struct rcar_i2c_priv *priv, struct i2c_timings *t)
191 {
192         u32 scgd, cdf, round, ick, sum, scl, cdf_width;
193         unsigned long rate;
194         struct device *dev = rcar_i2c_priv_to_dev(priv);
195
196         /* Fall back to previously used values if not supplied */
197         t->bus_freq_hz = t->bus_freq_hz ?: 100000;
198         t->scl_fall_ns = t->scl_fall_ns ?: 35;
199         t->scl_rise_ns = t->scl_rise_ns ?: 200;
200         t->scl_int_delay_ns = t->scl_int_delay_ns ?: 50;
201
202         switch (priv->devtype) {
203         case I2C_RCAR_GEN1:
204                 cdf_width = 2;
205                 break;
206         case I2C_RCAR_GEN2:
207         case I2C_RCAR_GEN3:
208                 cdf_width = 3;
209                 break;
210         default:
211                 dev_err(dev, "device type error\n");
212                 return -EIO;
213         }
214
215         /*
216          * calculate SCL clock
217          * see
218          *      ICCCR
219          *
220          * ick  = clkp / (1 + CDF)
221          * SCL  = ick / (20 + SCGD * 8 + F[(ticf + tr + intd) * ick])
222          *
223          * ick  : I2C internal clock < 20 MHz
224          * ticf : I2C SCL falling time
225          * tr   : I2C SCL rising  time
226          * intd : LSI internal delay
227          * clkp : peripheral_clk
228          * F[]  : integer up-valuation
229          */
230         rate = clk_get_rate(priv->clk);
231         cdf = rate / 20000000;
232         if (cdf >= 1U << cdf_width) {
233                 dev_err(dev, "Input clock %lu too high\n", rate);
234                 return -EIO;
235         }
236         ick = rate / (cdf + 1);
237
238         /*
239          * it is impossible to calculate large scale
240          * number on u32. separate it
241          *
242          * F[(ticf + tr + intd) * ick] with sum = (ticf + tr + intd)
243          *  = F[sum * ick / 1000000000]
244          *  = F[(ick / 1000000) * sum / 1000]
245          */
246         sum = t->scl_fall_ns + t->scl_rise_ns + t->scl_int_delay_ns;
247         round = (ick + 500000) / 1000000 * sum;
248         round = (round + 500) / 1000;
249
250         /*
251          * SCL  = ick / (20 + SCGD * 8 + F[(ticf + tr + intd) * ick])
252          *
253          * Calculation result (= SCL) should be less than
254          * bus_speed for hardware safety
255          *
256          * We could use something along the lines of
257          *      div = ick / (bus_speed + 1) + 1;
258          *      scgd = (div - 20 - round + 7) / 8;
259          *      scl = ick / (20 + (scgd * 8) + round);
260          * (not fully verified) but that would get pretty involved
261          */
262         for (scgd = 0; scgd < 0x40; scgd++) {
263                 scl = ick / (20 + (scgd * 8) + round);
264                 if (scl <= t->bus_freq_hz)
265                         goto scgd_find;
266         }
267         dev_err(dev, "it is impossible to calculate best SCL\n");
268         return -EIO;
269
270 scgd_find:
271         dev_dbg(dev, "clk %d/%d(%lu), round %u, CDF:0x%x, SCGD: 0x%x\n",
272                 scl, t->bus_freq_hz, clk_get_rate(priv->clk), round, cdf, scgd);
273
274         /* keep icccr value */
275         priv->icccr = scgd << cdf_width | cdf;
276
277         return 0;
278 }
279
280 static void rcar_i2c_prepare_msg(struct rcar_i2c_priv *priv)
281 {
282         int read = !!rcar_i2c_is_recv(priv);
283
284         priv->pos = 0;
285         if (priv->msgs_left == 1)
286                 priv->flags |= ID_LAST_MSG;
287
288         rcar_i2c_write(priv, ICMAR, (priv->msg->addr << 1) | read);
289         /*
290          * We don't have a testcase but the HW engineers say that the write order
291          * of ICMSR and ICMCR depends on whether we issue START or REP_START. Since
292          * it didn't cause a drawback for me, let's rather be safe than sorry.
293          */
294         if (priv->flags & ID_FIRST_MSG) {
295                 rcar_i2c_write(priv, ICMSR, 0);
296                 rcar_i2c_write(priv, ICMCR, RCAR_BUS_PHASE_START);
297         } else {
298                 rcar_i2c_write(priv, ICMCR, RCAR_BUS_PHASE_START);
299                 rcar_i2c_write(priv, ICMSR, 0);
300         }
301         rcar_i2c_write(priv, ICMIER, read ? RCAR_IRQ_RECV : RCAR_IRQ_SEND);
302 }
303
304 static void rcar_i2c_next_msg(struct rcar_i2c_priv *priv)
305 {
306         priv->msg++;
307         priv->msgs_left--;
308         priv->flags &= ID_P_MASK;
309         rcar_i2c_prepare_msg(priv);
310 }
311
312 /*
313  *              interrupt functions
314  */
315 static void rcar_i2c_dma_unmap(struct rcar_i2c_priv *priv)
316 {
317         struct dma_chan *chan = priv->dma_direction == DMA_FROM_DEVICE
318                 ? priv->dma_rx : priv->dma_tx;
319
320         /* Disable DMA Master Received/Transmitted */
321         rcar_i2c_write(priv, ICDMAER, 0);
322
323         /* Reset default delay */
324         rcar_i2c_write(priv, ICFBSCR, TCYC06);
325
326         dma_unmap_single(chan->device->dev, sg_dma_address(&priv->sg),
327                          sg_dma_len(&priv->sg), priv->dma_direction);
328
329         /* Gen3 can only do one RXDMA per transfer and we just completed it */
330         if (priv->devtype == I2C_RCAR_GEN3 &&
331             priv->dma_direction == DMA_FROM_DEVICE)
332                 priv->flags |= ID_P_NO_RXDMA;
333
334         priv->dma_direction = DMA_NONE;
335 }
336
337 static void rcar_i2c_cleanup_dma(struct rcar_i2c_priv *priv)
338 {
339         if (priv->dma_direction == DMA_NONE)
340                 return;
341         else if (priv->dma_direction == DMA_FROM_DEVICE)
342                 dmaengine_terminate_all(priv->dma_rx);
343         else if (priv->dma_direction == DMA_TO_DEVICE)
344                 dmaengine_terminate_all(priv->dma_tx);
345
346         rcar_i2c_dma_unmap(priv);
347 }
348
349 static void rcar_i2c_dma_callback(void *data)
350 {
351         struct rcar_i2c_priv *priv = data;
352
353         priv->pos += sg_dma_len(&priv->sg);
354
355         rcar_i2c_dma_unmap(priv);
356 }
357
358 static void rcar_i2c_dma(struct rcar_i2c_priv *priv)
359 {
360         struct device *dev = rcar_i2c_priv_to_dev(priv);
361         struct i2c_msg *msg = priv->msg;
362         bool read = msg->flags & I2C_M_RD;
363         enum dma_data_direction dir = read ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
364         struct dma_chan *chan = read ? priv->dma_rx : priv->dma_tx;
365         struct dma_async_tx_descriptor *txdesc;
366         dma_addr_t dma_addr;
367         dma_cookie_t cookie;
368         unsigned char *buf;
369         int len;
370
371         /* Do various checks to see if DMA is feasible at all */
372         if (IS_ERR(chan) || msg->len < 8 ||
373             (read && priv->flags & ID_P_NO_RXDMA))
374                 return;
375
376         if (read) {
377                 /*
378                  * The last two bytes needs to be fetched using PIO in
379                  * order for the STOP phase to work.
380                  */
381                 buf = priv->msg->buf;
382                 len = priv->msg->len - 2;
383         } else {
384                 /*
385                  * First byte in message was sent using PIO.
386                  */
387                 buf = priv->msg->buf + 1;
388                 len = priv->msg->len - 1;
389         }
390
391         dma_addr = dma_map_single(chan->device->dev, buf, len, dir);
392         if (dma_mapping_error(chan->device->dev, dma_addr)) {
393                 dev_dbg(dev, "dma map failed, using PIO\n");
394                 return;
395         }
396
397         sg_dma_len(&priv->sg) = len;
398         sg_dma_address(&priv->sg) = dma_addr;
399
400         priv->dma_direction = dir;
401
402         txdesc = dmaengine_prep_slave_sg(chan, &priv->sg, 1,
403                                          read ? DMA_DEV_TO_MEM : DMA_MEM_TO_DEV,
404                                          DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
405         if (!txdesc) {
406                 dev_dbg(dev, "dma prep slave sg failed, using PIO\n");
407                 rcar_i2c_cleanup_dma(priv);
408                 return;
409         }
410
411         txdesc->callback = rcar_i2c_dma_callback;
412         txdesc->callback_param = priv;
413
414         cookie = dmaengine_submit(txdesc);
415         if (dma_submit_error(cookie)) {
416                 dev_dbg(dev, "submitting dma failed, using PIO\n");
417                 rcar_i2c_cleanup_dma(priv);
418                 return;
419         }
420
421         /* Set delay for DMA operations */
422         rcar_i2c_write(priv, ICFBSCR, TCYC17);
423
424         /* Enable DMA Master Received/Transmitted */
425         if (read)
426                 rcar_i2c_write(priv, ICDMAER, RMDMAE);
427         else
428                 rcar_i2c_write(priv, ICDMAER, TMDMAE);
429
430         dma_async_issue_pending(chan);
431 }
432
433 static void rcar_i2c_irq_send(struct rcar_i2c_priv *priv, u32 msr)
434 {
435         struct i2c_msg *msg = priv->msg;
436
437         /* FIXME: sometimes, unknown interrupt happened. Do nothing */
438         if (!(msr & MDE))
439                 return;
440
441         if (priv->pos < msg->len) {
442                 /*
443                  * Prepare next data to ICRXTX register.
444                  * This data will go to _SHIFT_ register.
445                  *
446                  *    *
447                  * [ICRXTX] -> [SHIFT] -> [I2C bus]
448                  */
449                 rcar_i2c_write(priv, ICRXTX, msg->buf[priv->pos]);
450                 priv->pos++;
451
452                 /*
453                  * Try to use DMA to transmit the rest of the data if
454                  * address transfer pashe just finished.
455                  */
456                 if (msr & MAT)
457                         rcar_i2c_dma(priv);
458         } else {
459                 /*
460                  * The last data was pushed to ICRXTX on _PREV_ empty irq.
461                  * It is on _SHIFT_ register, and will sent to I2C bus.
462                  *
463                  *                *
464                  * [ICRXTX] -> [SHIFT] -> [I2C bus]
465                  */
466
467                 if (priv->flags & ID_LAST_MSG) {
468                         /*
469                          * If current msg is the _LAST_ msg,
470                          * prepare stop condition here.
471                          * ID_DONE will be set on STOP irq.
472                          */
473                         rcar_i2c_write(priv, ICMCR, RCAR_BUS_PHASE_STOP);
474                 } else {
475                         rcar_i2c_next_msg(priv);
476                         return;
477                 }
478         }
479
480         rcar_i2c_write(priv, ICMSR, RCAR_IRQ_ACK_SEND);
481 }
482
483 static void rcar_i2c_irq_recv(struct rcar_i2c_priv *priv, u32 msr)
484 {
485         struct i2c_msg *msg = priv->msg;
486
487         /* FIXME: sometimes, unknown interrupt happened. Do nothing */
488         if (!(msr & MDR))
489                 return;
490
491         if (msr & MAT) {
492                 /*
493                  * Address transfer phase finished, but no data at this point.
494                  * Try to use DMA to receive data.
495                  */
496                 rcar_i2c_dma(priv);
497         } else if (priv->pos < msg->len) {
498                 /* get received data */
499                 msg->buf[priv->pos] = rcar_i2c_read(priv, ICRXTX);
500                 priv->pos++;
501         }
502
503         /*
504          * If next received data is the _LAST_, go to STOP phase. Might be
505          * overwritten by REP START when setting up a new msg. Not elegant
506          * but the only stable sequence for REP START I have found so far.
507          */
508         if (priv->pos + 1 >= msg->len)
509                 rcar_i2c_write(priv, ICMCR, RCAR_BUS_PHASE_STOP);
510
511         if (priv->pos == msg->len && !(priv->flags & ID_LAST_MSG))
512                 rcar_i2c_next_msg(priv);
513         else
514                 rcar_i2c_write(priv, ICMSR, RCAR_IRQ_ACK_RECV);
515 }
516
517 static bool rcar_i2c_slave_irq(struct rcar_i2c_priv *priv)
518 {
519         u32 ssr_raw, ssr_filtered;
520         u8 value;
521
522         ssr_raw = rcar_i2c_read(priv, ICSSR) & 0xff;
523         ssr_filtered = ssr_raw & rcar_i2c_read(priv, ICSIER);
524
525         if (!ssr_filtered)
526                 return false;
527
528         /* address detected */
529         if (ssr_filtered & SAR) {
530                 /* read or write request */
531                 if (ssr_raw & STM) {
532                         i2c_slave_event(priv->slave, I2C_SLAVE_READ_REQUESTED, &value);
533                         rcar_i2c_write(priv, ICRXTX, value);
534                         rcar_i2c_write(priv, ICSIER, SDE | SSR | SAR);
535                 } else {
536                         i2c_slave_event(priv->slave, I2C_SLAVE_WRITE_REQUESTED, &value);
537                         rcar_i2c_read(priv, ICRXTX);    /* dummy read */
538                         rcar_i2c_write(priv, ICSIER, SDR | SSR | SAR);
539                 }
540
541                 /* Clear SSR, too, because of old STOPs to other clients than us */
542                 rcar_i2c_write(priv, ICSSR, ~(SAR | SSR) & 0xff);
543         }
544
545         /* master sent stop */
546         if (ssr_filtered & SSR) {
547                 i2c_slave_event(priv->slave, I2C_SLAVE_STOP, &value);
548                 rcar_i2c_write(priv, ICSCR, SIE | SDBS); /* clear our NACK */
549                 rcar_i2c_write(priv, ICSIER, SAR);
550                 rcar_i2c_write(priv, ICSSR, ~SSR & 0xff);
551         }
552
553         /* master wants to write to us */
554         if (ssr_filtered & SDR) {
555                 int ret;
556
557                 value = rcar_i2c_read(priv, ICRXTX);
558                 ret = i2c_slave_event(priv->slave, I2C_SLAVE_WRITE_RECEIVED, &value);
559                 /* Send NACK in case of error */
560                 rcar_i2c_write(priv, ICSCR, SIE | SDBS | (ret < 0 ? FNA : 0));
561                 rcar_i2c_write(priv, ICSSR, ~SDR & 0xff);
562         }
563
564         /* master wants to read from us */
565         if (ssr_filtered & SDE) {
566                 i2c_slave_event(priv->slave, I2C_SLAVE_READ_PROCESSED, &value);
567                 rcar_i2c_write(priv, ICRXTX, value);
568                 rcar_i2c_write(priv, ICSSR, ~SDE & 0xff);
569         }
570
571         return true;
572 }
573
574 static irqreturn_t rcar_i2c_irq(int irq, void *ptr)
575 {
576         struct rcar_i2c_priv *priv = ptr;
577         u32 msr, val;
578
579         /* Clear START or STOP as soon as we can */
580         val = rcar_i2c_read(priv, ICMCR);
581         rcar_i2c_write(priv, ICMCR, val & RCAR_BUS_MASK_DATA);
582
583         msr = rcar_i2c_read(priv, ICMSR);
584
585         /* Only handle interrupts that are currently enabled */
586         msr &= rcar_i2c_read(priv, ICMIER);
587         if (!msr) {
588                 if (rcar_i2c_slave_irq(priv))
589                         return IRQ_HANDLED;
590
591                 return IRQ_NONE;
592         }
593
594         /* Arbitration lost */
595         if (msr & MAL) {
596                 priv->flags |= ID_DONE | ID_ARBLOST;
597                 goto out;
598         }
599
600         /* Nack */
601         if (msr & MNR) {
602                 /* HW automatically sends STOP after received NACK */
603                 rcar_i2c_write(priv, ICMIER, RCAR_IRQ_STOP);
604                 priv->flags |= ID_NACK;
605                 goto out;
606         }
607
608         /* Stop */
609         if (msr & MST) {
610                 priv->msgs_left--; /* The last message also made it */
611                 priv->flags |= ID_DONE;
612                 goto out;
613         }
614
615         if (rcar_i2c_is_recv(priv))
616                 rcar_i2c_irq_recv(priv, msr);
617         else
618                 rcar_i2c_irq_send(priv, msr);
619
620 out:
621         if (priv->flags & ID_DONE) {
622                 rcar_i2c_write(priv, ICMIER, 0);
623                 rcar_i2c_write(priv, ICMSR, 0);
624                 wake_up(&priv->wait);
625         }
626
627         return IRQ_HANDLED;
628 }
629
630 static struct dma_chan *rcar_i2c_request_dma_chan(struct device *dev,
631                                         enum dma_transfer_direction dir,
632                                         dma_addr_t port_addr)
633 {
634         struct dma_chan *chan;
635         struct dma_slave_config cfg;
636         char *chan_name = dir == DMA_MEM_TO_DEV ? "tx" : "rx";
637         int ret;
638
639         chan = dma_request_chan(dev, chan_name);
640         if (IS_ERR(chan)) {
641                 dev_dbg(dev, "request_channel failed for %s (%ld)\n",
642                         chan_name, PTR_ERR(chan));
643                 return chan;
644         }
645
646         memset(&cfg, 0, sizeof(cfg));
647         cfg.direction = dir;
648         if (dir == DMA_MEM_TO_DEV) {
649                 cfg.dst_addr = port_addr;
650                 cfg.dst_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
651         } else {
652                 cfg.src_addr = port_addr;
653                 cfg.src_addr_width = DMA_SLAVE_BUSWIDTH_1_BYTE;
654         }
655
656         ret = dmaengine_slave_config(chan, &cfg);
657         if (ret) {
658                 dev_dbg(dev, "slave_config failed for %s (%d)\n",
659                         chan_name, ret);
660                 dma_release_channel(chan);
661                 return ERR_PTR(ret);
662         }
663
664         dev_dbg(dev, "got DMA channel for %s\n", chan_name);
665         return chan;
666 }
667
668 static void rcar_i2c_request_dma(struct rcar_i2c_priv *priv,
669                                  struct i2c_msg *msg)
670 {
671         struct device *dev = rcar_i2c_priv_to_dev(priv);
672         bool read;
673         struct dma_chan *chan;
674         enum dma_transfer_direction dir;
675
676         read = msg->flags & I2C_M_RD;
677
678         chan = read ? priv->dma_rx : priv->dma_tx;
679         if (PTR_ERR(chan) != -EPROBE_DEFER)
680                 return;
681
682         dir = read ? DMA_DEV_TO_MEM : DMA_MEM_TO_DEV;
683         chan = rcar_i2c_request_dma_chan(dev, dir, priv->res->start + ICRXTX);
684
685         if (read)
686                 priv->dma_rx = chan;
687         else
688                 priv->dma_tx = chan;
689 }
690
691 static void rcar_i2c_release_dma(struct rcar_i2c_priv *priv)
692 {
693         if (!IS_ERR(priv->dma_tx)) {
694                 dma_release_channel(priv->dma_tx);
695                 priv->dma_tx = ERR_PTR(-EPROBE_DEFER);
696         }
697
698         if (!IS_ERR(priv->dma_rx)) {
699                 dma_release_channel(priv->dma_rx);
700                 priv->dma_rx = ERR_PTR(-EPROBE_DEFER);
701         }
702 }
703
704 /* I2C is a special case, we need to poll the status of a reset */
705 static int rcar_i2c_do_reset(struct rcar_i2c_priv *priv)
706 {
707         int i, ret;
708
709         ret = reset_control_reset(priv->rstc);
710         if (ret)
711                 return ret;
712
713         for (i = 0; i < LOOP_TIMEOUT; i++) {
714                 ret = reset_control_status(priv->rstc);
715                 if (ret == 0)
716                         return 0;
717                 udelay(1);
718         }
719
720         return -ETIMEDOUT;
721 }
722
723 static int rcar_i2c_master_xfer(struct i2c_adapter *adap,
724                                 struct i2c_msg *msgs,
725                                 int num)
726 {
727         struct rcar_i2c_priv *priv = i2c_get_adapdata(adap);
728         struct device *dev = rcar_i2c_priv_to_dev(priv);
729         int i, ret;
730         long time_left;
731
732         pm_runtime_get_sync(dev);
733
734         /* Gen3 needs a reset before allowing RXDMA once */
735         if (priv->devtype == I2C_RCAR_GEN3) {
736                 priv->flags |= ID_P_NO_RXDMA;
737                 if (!IS_ERR(priv->rstc)) {
738                         ret = rcar_i2c_do_reset(priv);
739                         if (ret == 0)
740                                 priv->flags &= ~ID_P_NO_RXDMA;
741                 }
742         }
743
744         rcar_i2c_init(priv);
745
746         ret = rcar_i2c_bus_barrier(priv);
747         if (ret < 0)
748                 goto out;
749
750         for (i = 0; i < num; i++) {
751                 /* This HW can't send STOP after address phase */
752                 if (msgs[i].len == 0) {
753                         ret = -EOPNOTSUPP;
754                         goto out;
755                 }
756                 rcar_i2c_request_dma(priv, msgs + i);
757         }
758
759         /* init first message */
760         priv->msg = msgs;
761         priv->msgs_left = num;
762         priv->flags = (priv->flags & ID_P_MASK) | ID_FIRST_MSG;
763         rcar_i2c_prepare_msg(priv);
764
765         time_left = wait_event_timeout(priv->wait, priv->flags & ID_DONE,
766                                      num * adap->timeout);
767
768         /* cleanup DMA if it couldn't complete properly due to an error */
769         if (priv->dma_direction != DMA_NONE)
770                 rcar_i2c_cleanup_dma(priv);
771
772         if (!time_left) {
773                 rcar_i2c_init(priv);
774                 ret = -ETIMEDOUT;
775         } else if (priv->flags & ID_NACK) {
776                 ret = -ENXIO;
777         } else if (priv->flags & ID_ARBLOST) {
778                 ret = -EAGAIN;
779         } else {
780                 ret = num - priv->msgs_left; /* The number of transfer */
781         }
782 out:
783         pm_runtime_put(dev);
784
785         if (ret < 0 && ret != -ENXIO)
786                 dev_err(dev, "error %d : %x\n", ret, priv->flags);
787
788         return ret;
789 }
790
791 static int rcar_reg_slave(struct i2c_client *slave)
792 {
793         struct rcar_i2c_priv *priv = i2c_get_adapdata(slave->adapter);
794
795         if (priv->slave)
796                 return -EBUSY;
797
798         if (slave->flags & I2C_CLIENT_TEN)
799                 return -EAFNOSUPPORT;
800
801         /* Keep device active for slave address detection logic */
802         pm_runtime_get_sync(rcar_i2c_priv_to_dev(priv));
803
804         priv->slave = slave;
805         rcar_i2c_write(priv, ICSAR, slave->addr);
806         rcar_i2c_write(priv, ICSSR, 0);
807         rcar_i2c_write(priv, ICSIER, SAR);
808         rcar_i2c_write(priv, ICSCR, SIE | SDBS);
809
810         return 0;
811 }
812
813 static int rcar_unreg_slave(struct i2c_client *slave)
814 {
815         struct rcar_i2c_priv *priv = i2c_get_adapdata(slave->adapter);
816
817         WARN_ON(!priv->slave);
818
819         /* ensure no irq is running before clearing ptr */
820         disable_irq(priv->irq);
821         rcar_i2c_write(priv, ICSIER, 0);
822         rcar_i2c_write(priv, ICSSR, 0);
823         enable_irq(priv->irq);
824         rcar_i2c_write(priv, ICSCR, SDBS);
825         rcar_i2c_write(priv, ICSAR, 0); /* Gen2: must be 0 if not using slave */
826
827         priv->slave = NULL;
828
829         pm_runtime_put(rcar_i2c_priv_to_dev(priv));
830
831         return 0;
832 }
833
834 static u32 rcar_i2c_func(struct i2c_adapter *adap)
835 {
836         /*
837          * This HW can't do:
838          * I2C_SMBUS_QUICK (setting FSB during START didn't work)
839          * I2C_M_NOSTART (automatically sends address after START)
840          * I2C_M_IGNORE_NAK (automatically sends STOP after NAK)
841          */
842         return I2C_FUNC_I2C | I2C_FUNC_SLAVE |
843                 (I2C_FUNC_SMBUS_EMUL & ~I2C_FUNC_SMBUS_QUICK);
844 }
845
846 static const struct i2c_algorithm rcar_i2c_algo = {
847         .master_xfer    = rcar_i2c_master_xfer,
848         .functionality  = rcar_i2c_func,
849         .reg_slave      = rcar_reg_slave,
850         .unreg_slave    = rcar_unreg_slave,
851 };
852
853 static const struct of_device_id rcar_i2c_dt_ids[] = {
854         { .compatible = "renesas,i2c-r8a7778", .data = (void *)I2C_RCAR_GEN1 },
855         { .compatible = "renesas,i2c-r8a7779", .data = (void *)I2C_RCAR_GEN1 },
856         { .compatible = "renesas,i2c-r8a7790", .data = (void *)I2C_RCAR_GEN2 },
857         { .compatible = "renesas,i2c-r8a7791", .data = (void *)I2C_RCAR_GEN2 },
858         { .compatible = "renesas,i2c-r8a7792", .data = (void *)I2C_RCAR_GEN2 },
859         { .compatible = "renesas,i2c-r8a7793", .data = (void *)I2C_RCAR_GEN2 },
860         { .compatible = "renesas,i2c-r8a7794", .data = (void *)I2C_RCAR_GEN2 },
861         { .compatible = "renesas,i2c-r8a7795", .data = (void *)I2C_RCAR_GEN3 },
862         { .compatible = "renesas,i2c-r8a7796", .data = (void *)I2C_RCAR_GEN3 },
863         { .compatible = "renesas,i2c-rcar", .data = (void *)I2C_RCAR_GEN1 },    /* Deprecated */
864         { .compatible = "renesas,rcar-gen1-i2c", .data = (void *)I2C_RCAR_GEN1 },
865         { .compatible = "renesas,rcar-gen2-i2c", .data = (void *)I2C_RCAR_GEN2 },
866         { .compatible = "renesas,rcar-gen3-i2c", .data = (void *)I2C_RCAR_GEN3 },
867         {},
868 };
869 MODULE_DEVICE_TABLE(of, rcar_i2c_dt_ids);
870
871 static int rcar_i2c_probe(struct platform_device *pdev)
872 {
873         struct rcar_i2c_priv *priv;
874         struct i2c_adapter *adap;
875         struct device *dev = &pdev->dev;
876         struct i2c_timings i2c_t;
877         int ret;
878
879         priv = devm_kzalloc(dev, sizeof(struct rcar_i2c_priv), GFP_KERNEL);
880         if (!priv)
881                 return -ENOMEM;
882
883         priv->clk = devm_clk_get(dev, NULL);
884         if (IS_ERR(priv->clk)) {
885                 dev_err(dev, "cannot get clock\n");
886                 return PTR_ERR(priv->clk);
887         }
888
889         priv->res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
890
891         priv->io = devm_ioremap_resource(dev, priv->res);
892         if (IS_ERR(priv->io))
893                 return PTR_ERR(priv->io);
894
895         priv->devtype = (enum rcar_i2c_type)of_device_get_match_data(dev);
896         init_waitqueue_head(&priv->wait);
897
898         adap = &priv->adap;
899         adap->nr = pdev->id;
900         adap->algo = &rcar_i2c_algo;
901         adap->class = I2C_CLASS_DEPRECATED;
902         adap->retries = 3;
903         adap->dev.parent = dev;
904         adap->dev.of_node = dev->of_node;
905         i2c_set_adapdata(adap, priv);
906         strlcpy(adap->name, pdev->name, sizeof(adap->name));
907
908         i2c_parse_fw_timings(dev, &i2c_t, false);
909
910         /* Init DMA */
911         sg_init_table(&priv->sg, 1);
912         priv->dma_direction = DMA_NONE;
913         priv->dma_rx = priv->dma_tx = ERR_PTR(-EPROBE_DEFER);
914
915         /* Activate device for clock calculation */
916         pm_runtime_enable(dev);
917         pm_runtime_get_sync(dev);
918         ret = rcar_i2c_clock_calculate(priv, &i2c_t);
919         if (ret < 0)
920                 goto out_pm_put;
921
922         rcar_i2c_write(priv, ICSAR, 0); /* Gen2: must be 0 if not using slave */
923
924         if (priv->devtype == I2C_RCAR_GEN3) {
925                 priv->rstc = devm_reset_control_get_exclusive(&pdev->dev, NULL);
926                 if (!IS_ERR(priv->rstc)) {
927                         ret = reset_control_status(priv->rstc);
928                         if (ret < 0)
929                                 priv->rstc = ERR_PTR(-ENOTSUPP);
930                 }
931         }
932
933         /* Stay always active when multi-master to keep arbitration working */
934         if (of_property_read_bool(dev->of_node, "multi-master"))
935                 priv->flags |= ID_P_PM_BLOCKED;
936         else
937                 pm_runtime_put(dev);
938
939
940         priv->irq = platform_get_irq(pdev, 0);
941         ret = devm_request_irq(dev, priv->irq, rcar_i2c_irq, 0, dev_name(dev), priv);
942         if (ret < 0) {
943                 dev_err(dev, "cannot get irq %d\n", priv->irq);
944                 goto out_pm_disable;
945         }
946
947         platform_set_drvdata(pdev, priv);
948
949         ret = i2c_add_numbered_adapter(adap);
950         if (ret < 0)
951                 goto out_pm_disable;
952
953         dev_info(dev, "probed\n");
954
955         return 0;
956
957  out_pm_put:
958         pm_runtime_put(dev);
959  out_pm_disable:
960         pm_runtime_disable(dev);
961         return ret;
962 }
963
964 static int rcar_i2c_remove(struct platform_device *pdev)
965 {
966         struct rcar_i2c_priv *priv = platform_get_drvdata(pdev);
967         struct device *dev = &pdev->dev;
968
969         i2c_del_adapter(&priv->adap);
970         rcar_i2c_release_dma(priv);
971         if (priv->flags & ID_P_PM_BLOCKED)
972                 pm_runtime_put(dev);
973         pm_runtime_disable(dev);
974
975         return 0;
976 }
977
978 static struct platform_driver rcar_i2c_driver = {
979         .driver = {
980                 .name   = "i2c-rcar",
981                 .of_match_table = rcar_i2c_dt_ids,
982         },
983         .probe          = rcar_i2c_probe,
984         .remove         = rcar_i2c_remove,
985 };
986
987 module_platform_driver(rcar_i2c_driver);
988
989 MODULE_LICENSE("GPL v2");
990 MODULE_DESCRIPTION("Renesas R-Car I2C bus driver");
991 MODULE_AUTHOR("Kuninori Morimoto <kuninori.morimoto.gx@renesas.com>");