GNU Linux-libre 4.14.290-gnu1
[releases.git] / drivers / i2c / busses / i2c-cadence.c
1 /*
2  * I2C bus driver for the Cadence I2C controller.
3  *
4  * Copyright (C) 2009 - 2014 Xilinx, Inc.
5  *
6  * This program is free software; you can redistribute it
7  * and/or modify it under the terms of the GNU General Public
8  * License as published by the Free Software Foundation;
9  * either version 2 of the License, or (at your option) any
10  * later version.
11  */
12
13 #include <linux/clk.h>
14 #include <linux/delay.h>
15 #include <linux/i2c.h>
16 #include <linux/interrupt.h>
17 #include <linux/io.h>
18 #include <linux/module.h>
19 #include <linux/platform_device.h>
20 #include <linux/of.h>
21 #include <linux/pm_runtime.h>
22
23 /* Register offsets for the I2C device. */
24 #define CDNS_I2C_CR_OFFSET              0x00 /* Control Register, RW */
25 #define CDNS_I2C_SR_OFFSET              0x04 /* Status Register, RO */
26 #define CDNS_I2C_ADDR_OFFSET            0x08 /* I2C Address Register, RW */
27 #define CDNS_I2C_DATA_OFFSET            0x0C /* I2C Data Register, RW */
28 #define CDNS_I2C_ISR_OFFSET             0x10 /* IRQ Status Register, RW */
29 #define CDNS_I2C_XFER_SIZE_OFFSET       0x14 /* Transfer Size Register, RW */
30 #define CDNS_I2C_TIME_OUT_OFFSET        0x1C /* Time Out Register, RW */
31 #define CDNS_I2C_IER_OFFSET             0x24 /* IRQ Enable Register, WO */
32 #define CDNS_I2C_IDR_OFFSET             0x28 /* IRQ Disable Register, WO */
33
34 /* Control Register Bit mask definitions */
35 #define CDNS_I2C_CR_HOLD                BIT(4) /* Hold Bus bit */
36 #define CDNS_I2C_CR_ACK_EN              BIT(3)
37 #define CDNS_I2C_CR_NEA                 BIT(2)
38 #define CDNS_I2C_CR_MS                  BIT(1)
39 /* Read or Write Master transfer 0 = Transmitter, 1 = Receiver */
40 #define CDNS_I2C_CR_RW                  BIT(0)
41 /* 1 = Auto init FIFO to zeroes */
42 #define CDNS_I2C_CR_CLR_FIFO            BIT(6)
43 #define CDNS_I2C_CR_DIVA_SHIFT          14
44 #define CDNS_I2C_CR_DIVA_MASK           (3 << CDNS_I2C_CR_DIVA_SHIFT)
45 #define CDNS_I2C_CR_DIVB_SHIFT          8
46 #define CDNS_I2C_CR_DIVB_MASK           (0x3f << CDNS_I2C_CR_DIVB_SHIFT)
47
48 /* Status Register Bit mask definitions */
49 #define CDNS_I2C_SR_BA          BIT(8)
50 #define CDNS_I2C_SR_RXDV        BIT(5)
51
52 /*
53  * I2C Address Register Bit mask definitions
54  * Normal addressing mode uses [6:0] bits. Extended addressing mode uses [9:0]
55  * bits. A write access to this register always initiates a transfer if the I2C
56  * is in master mode.
57  */
58 #define CDNS_I2C_ADDR_MASK      0x000003FF /* I2C Address Mask */
59
60 /*
61  * I2C Interrupt Registers Bit mask definitions
62  * All the four interrupt registers (Status/Mask/Enable/Disable) have the same
63  * bit definitions.
64  */
65 #define CDNS_I2C_IXR_ARB_LOST           BIT(9)
66 #define CDNS_I2C_IXR_RX_UNF             BIT(7)
67 #define CDNS_I2C_IXR_TX_OVF             BIT(6)
68 #define CDNS_I2C_IXR_RX_OVF             BIT(5)
69 #define CDNS_I2C_IXR_SLV_RDY            BIT(4)
70 #define CDNS_I2C_IXR_TO                 BIT(3)
71 #define CDNS_I2C_IXR_NACK               BIT(2)
72 #define CDNS_I2C_IXR_DATA               BIT(1)
73 #define CDNS_I2C_IXR_COMP               BIT(0)
74
75 #define CDNS_I2C_IXR_ALL_INTR_MASK      (CDNS_I2C_IXR_ARB_LOST | \
76                                          CDNS_I2C_IXR_RX_UNF | \
77                                          CDNS_I2C_IXR_TX_OVF | \
78                                          CDNS_I2C_IXR_RX_OVF | \
79                                          CDNS_I2C_IXR_SLV_RDY | \
80                                          CDNS_I2C_IXR_TO | \
81                                          CDNS_I2C_IXR_NACK | \
82                                          CDNS_I2C_IXR_DATA | \
83                                          CDNS_I2C_IXR_COMP)
84
85 #define CDNS_I2C_IXR_ERR_INTR_MASK      (CDNS_I2C_IXR_ARB_LOST | \
86                                          CDNS_I2C_IXR_RX_UNF | \
87                                          CDNS_I2C_IXR_TX_OVF | \
88                                          CDNS_I2C_IXR_RX_OVF | \
89                                          CDNS_I2C_IXR_NACK)
90
91 #define CDNS_I2C_ENABLED_INTR_MASK      (CDNS_I2C_IXR_ARB_LOST | \
92                                          CDNS_I2C_IXR_RX_UNF | \
93                                          CDNS_I2C_IXR_TX_OVF | \
94                                          CDNS_I2C_IXR_RX_OVF | \
95                                          CDNS_I2C_IXR_NACK | \
96                                          CDNS_I2C_IXR_DATA | \
97                                          CDNS_I2C_IXR_COMP)
98
99 #define CDNS_I2C_TIMEOUT                msecs_to_jiffies(1000)
100 /* timeout for pm runtime autosuspend */
101 #define CNDS_I2C_PM_TIMEOUT             1000    /* ms */
102
103 #define CDNS_I2C_FIFO_DEPTH             16
104 /* FIFO depth at which the DATA interrupt occurs */
105 #define CDNS_I2C_DATA_INTR_DEPTH        (CDNS_I2C_FIFO_DEPTH - 2)
106 #define CDNS_I2C_MAX_TRANSFER_SIZE      255
107 /* Transfer size in multiples of data interrupt depth */
108 #define CDNS_I2C_TRANSFER_SIZE  (CDNS_I2C_MAX_TRANSFER_SIZE - 3)
109
110 #define DRIVER_NAME             "cdns-i2c"
111
112 #define CDNS_I2C_SPEED_MAX      400000
113 #define CDNS_I2C_SPEED_DEFAULT  100000
114
115 #define CDNS_I2C_DIVA_MAX       4
116 #define CDNS_I2C_DIVB_MAX       64
117
118 #define CDNS_I2C_TIMEOUT_MAX    0xFF
119
120 #define CDNS_I2C_BROKEN_HOLD_BIT        BIT(0)
121
122 #define cdns_i2c_readreg(offset)       readl_relaxed(id->membase + offset)
123 #define cdns_i2c_writereg(val, offset) writel_relaxed(val, id->membase + offset)
124
125 /**
126  * struct cdns_i2c - I2C device private data structure
127  *
128  * @dev:                Pointer to device structure
129  * @membase:            Base address of the I2C device
130  * @adap:               I2C adapter instance
131  * @p_msg:              Message pointer
132  * @err_status:         Error status in Interrupt Status Register
133  * @xfer_done:          Transfer complete status
134  * @p_send_buf:         Pointer to transmit buffer
135  * @p_recv_buf:         Pointer to receive buffer
136  * @send_count:         Number of bytes still expected to send
137  * @recv_count:         Number of bytes still expected to receive
138  * @curr_recv_count:    Number of bytes to be received in current transfer
139  * @irq:                IRQ number
140  * @input_clk:          Input clock to I2C controller
141  * @i2c_clk:            Maximum I2C clock speed
142  * @bus_hold_flag:      Flag used in repeated start for clearing HOLD bit
143  * @clk:                Pointer to struct clk
144  * @clk_rate_change_nb: Notifier block for clock rate changes
145  * @quirks:             flag for broken hold bit usage in r1p10
146  */
147 struct cdns_i2c {
148         struct device           *dev;
149         void __iomem *membase;
150         struct i2c_adapter adap;
151         struct i2c_msg *p_msg;
152         int err_status;
153         struct completion xfer_done;
154         unsigned char *p_send_buf;
155         unsigned char *p_recv_buf;
156         unsigned int send_count;
157         unsigned int recv_count;
158         unsigned int curr_recv_count;
159         int irq;
160         unsigned long input_clk;
161         unsigned int i2c_clk;
162         unsigned int bus_hold_flag;
163         struct clk *clk;
164         struct notifier_block clk_rate_change_nb;
165         u32 quirks;
166 };
167
168 struct cdns_platform_data {
169         u32 quirks;
170 };
171
172 #define to_cdns_i2c(_nb)        container_of(_nb, struct cdns_i2c, \
173                                              clk_rate_change_nb)
174
175 /**
176  * cdns_i2c_clear_bus_hold - Clear bus hold bit
177  * @id: Pointer to driver data struct
178  *
179  * Helper to clear the controller's bus hold bit.
180  */
181 static void cdns_i2c_clear_bus_hold(struct cdns_i2c *id)
182 {
183         u32 reg = cdns_i2c_readreg(CDNS_I2C_CR_OFFSET);
184         if (reg & CDNS_I2C_CR_HOLD)
185                 cdns_i2c_writereg(reg & ~CDNS_I2C_CR_HOLD, CDNS_I2C_CR_OFFSET);
186 }
187
188 static inline bool cdns_is_holdquirk(struct cdns_i2c *id, bool hold_wrkaround)
189 {
190         return (hold_wrkaround &&
191                 (id->curr_recv_count == CDNS_I2C_FIFO_DEPTH + 1));
192 }
193
194 /**
195  * cdns_i2c_isr - Interrupt handler for the I2C device
196  * @irq:        irq number for the I2C device
197  * @ptr:        void pointer to cdns_i2c structure
198  *
199  * This function handles the data interrupt, transfer complete interrupt and
200  * the error interrupts of the I2C device.
201  *
202  * Return: IRQ_HANDLED always
203  */
204 static irqreturn_t cdns_i2c_isr(int irq, void *ptr)
205 {
206         unsigned int isr_status, avail_bytes;
207         unsigned int bytes_to_send;
208         bool updatetx;
209         struct cdns_i2c *id = ptr;
210         /* Signal completion only after everything is updated */
211         int done_flag = 0;
212         irqreturn_t status = IRQ_NONE;
213
214         isr_status = cdns_i2c_readreg(CDNS_I2C_ISR_OFFSET);
215         cdns_i2c_writereg(isr_status, CDNS_I2C_ISR_OFFSET);
216
217         /* Handling nack and arbitration lost interrupt */
218         if (isr_status & (CDNS_I2C_IXR_NACK | CDNS_I2C_IXR_ARB_LOST)) {
219                 done_flag = 1;
220                 status = IRQ_HANDLED;
221         }
222
223         /*
224          * Check if transfer size register needs to be updated again for a
225          * large data receive operation.
226          */
227         updatetx = id->recv_count > id->curr_recv_count;
228
229         /* When receiving, handle data interrupt and completion interrupt */
230         if (id->p_recv_buf &&
231             ((isr_status & CDNS_I2C_IXR_COMP) ||
232              (isr_status & CDNS_I2C_IXR_DATA))) {
233                 /* Read data if receive data valid is set */
234                 while (cdns_i2c_readreg(CDNS_I2C_SR_OFFSET) &
235                        CDNS_I2C_SR_RXDV) {
236                         /*
237                          * Clear hold bit that was set for FIFO control if
238                          * RX data left is less than FIFO depth, unless
239                          * repeated start is selected.
240                          */
241                         if ((id->recv_count < CDNS_I2C_FIFO_DEPTH) &&
242                             !id->bus_hold_flag)
243                                 cdns_i2c_clear_bus_hold(id);
244
245                         *(id->p_recv_buf)++ =
246                                 cdns_i2c_readreg(CDNS_I2C_DATA_OFFSET);
247                         id->recv_count--;
248                         id->curr_recv_count--;
249
250                         if (cdns_is_holdquirk(id, updatetx))
251                                 break;
252                 }
253
254                 /*
255                  * The controller sends NACK to the slave when transfer size
256                  * register reaches zero without considering the HOLD bit.
257                  * This workaround is implemented for large data transfers to
258                  * maintain transfer size non-zero while performing a large
259                  * receive operation.
260                  */
261                 if (cdns_is_holdquirk(id, updatetx)) {
262                         /* wait while fifo is full */
263                         while (cdns_i2c_readreg(CDNS_I2C_XFER_SIZE_OFFSET) !=
264                                (id->curr_recv_count - CDNS_I2C_FIFO_DEPTH))
265                                 ;
266
267                         /*
268                          * Check number of bytes to be received against maximum
269                          * transfer size and update register accordingly.
270                          */
271                         if (((int)(id->recv_count) - CDNS_I2C_FIFO_DEPTH) >
272                             CDNS_I2C_TRANSFER_SIZE) {
273                                 cdns_i2c_writereg(CDNS_I2C_TRANSFER_SIZE,
274                                                   CDNS_I2C_XFER_SIZE_OFFSET);
275                                 id->curr_recv_count = CDNS_I2C_TRANSFER_SIZE +
276                                                       CDNS_I2C_FIFO_DEPTH;
277                         } else {
278                                 cdns_i2c_writereg(id->recv_count -
279                                                   CDNS_I2C_FIFO_DEPTH,
280                                                   CDNS_I2C_XFER_SIZE_OFFSET);
281                                 id->curr_recv_count = id->recv_count;
282                         }
283                 }
284
285                 /* Clear hold (if not repeated start) and signal completion */
286                 if ((isr_status & CDNS_I2C_IXR_COMP) && !id->recv_count) {
287                         if (!id->bus_hold_flag)
288                                 cdns_i2c_clear_bus_hold(id);
289                         done_flag = 1;
290                 }
291
292                 status = IRQ_HANDLED;
293         }
294
295         /* When sending, handle transfer complete interrupt */
296         if ((isr_status & CDNS_I2C_IXR_COMP) && !id->p_recv_buf) {
297                 /*
298                  * If there is more data to be sent, calculate the
299                  * space available in FIFO and fill with that many bytes.
300                  */
301                 if (id->send_count) {
302                         avail_bytes = CDNS_I2C_FIFO_DEPTH -
303                             cdns_i2c_readreg(CDNS_I2C_XFER_SIZE_OFFSET);
304                         if (id->send_count > avail_bytes)
305                                 bytes_to_send = avail_bytes;
306                         else
307                                 bytes_to_send = id->send_count;
308
309                         while (bytes_to_send--) {
310                                 cdns_i2c_writereg(
311                                         (*(id->p_send_buf)++),
312                                          CDNS_I2C_DATA_OFFSET);
313                                 id->send_count--;
314                         }
315                 } else {
316                         /*
317                          * Signal the completion of transaction and
318                          * clear the hold bus bit if there are no
319                          * further messages to be processed.
320                          */
321                         done_flag = 1;
322                 }
323                 if (!id->send_count && !id->bus_hold_flag)
324                         cdns_i2c_clear_bus_hold(id);
325
326                 status = IRQ_HANDLED;
327         }
328
329         /* Update the status for errors */
330         id->err_status = isr_status & CDNS_I2C_IXR_ERR_INTR_MASK;
331         if (id->err_status)
332                 status = IRQ_HANDLED;
333
334         if (done_flag)
335                 complete(&id->xfer_done);
336
337         return status;
338 }
339
340 /**
341  * cdns_i2c_mrecv - Prepare and start a master receive operation
342  * @id:         pointer to the i2c device structure
343  */
344 static void cdns_i2c_mrecv(struct cdns_i2c *id)
345 {
346         unsigned int ctrl_reg;
347         unsigned int isr_status;
348
349         id->p_recv_buf = id->p_msg->buf;
350         id->recv_count = id->p_msg->len;
351
352         /* Put the controller in master receive mode and clear the FIFO */
353         ctrl_reg = cdns_i2c_readreg(CDNS_I2C_CR_OFFSET);
354         ctrl_reg |= CDNS_I2C_CR_RW | CDNS_I2C_CR_CLR_FIFO;
355
356         if (id->p_msg->flags & I2C_M_RECV_LEN)
357                 id->recv_count = I2C_SMBUS_BLOCK_MAX + 1;
358
359         id->curr_recv_count = id->recv_count;
360
361         /*
362          * Check for the message size against FIFO depth and set the
363          * 'hold bus' bit if it is greater than FIFO depth.
364          */
365         if (id->recv_count > CDNS_I2C_FIFO_DEPTH)
366                 ctrl_reg |= CDNS_I2C_CR_HOLD;
367
368         cdns_i2c_writereg(ctrl_reg, CDNS_I2C_CR_OFFSET);
369
370         /* Clear the interrupts in interrupt status register */
371         isr_status = cdns_i2c_readreg(CDNS_I2C_ISR_OFFSET);
372         cdns_i2c_writereg(isr_status, CDNS_I2C_ISR_OFFSET);
373
374         /*
375          * The no. of bytes to receive is checked against the limit of
376          * max transfer size. Set transfer size register with no of bytes
377          * receive if it is less than transfer size and transfer size if
378          * it is more. Enable the interrupts.
379          */
380         if (id->recv_count > CDNS_I2C_TRANSFER_SIZE) {
381                 cdns_i2c_writereg(CDNS_I2C_TRANSFER_SIZE,
382                                   CDNS_I2C_XFER_SIZE_OFFSET);
383                 id->curr_recv_count = CDNS_I2C_TRANSFER_SIZE;
384         } else {
385                 cdns_i2c_writereg(id->recv_count, CDNS_I2C_XFER_SIZE_OFFSET);
386         }
387
388         /* Set the slave address in address register - triggers operation */
389         cdns_i2c_writereg(id->p_msg->addr & CDNS_I2C_ADDR_MASK,
390                                                 CDNS_I2C_ADDR_OFFSET);
391         /* Clear the bus hold flag if bytes to receive is less than FIFO size */
392         if (!id->bus_hold_flag &&
393                 ((id->p_msg->flags & I2C_M_RECV_LEN) != I2C_M_RECV_LEN) &&
394                 (id->recv_count <= CDNS_I2C_FIFO_DEPTH))
395                         cdns_i2c_clear_bus_hold(id);
396         cdns_i2c_writereg(CDNS_I2C_ENABLED_INTR_MASK, CDNS_I2C_IER_OFFSET);
397 }
398
399 /**
400  * cdns_i2c_msend - Prepare and start a master send operation
401  * @id:         pointer to the i2c device
402  */
403 static void cdns_i2c_msend(struct cdns_i2c *id)
404 {
405         unsigned int avail_bytes;
406         unsigned int bytes_to_send;
407         unsigned int ctrl_reg;
408         unsigned int isr_status;
409
410         id->p_recv_buf = NULL;
411         id->p_send_buf = id->p_msg->buf;
412         id->send_count = id->p_msg->len;
413
414         /* Set the controller in Master transmit mode and clear the FIFO. */
415         ctrl_reg = cdns_i2c_readreg(CDNS_I2C_CR_OFFSET);
416         ctrl_reg &= ~CDNS_I2C_CR_RW;
417         ctrl_reg |= CDNS_I2C_CR_CLR_FIFO;
418
419         /*
420          * Check for the message size against FIFO depth and set the
421          * 'hold bus' bit if it is greater than FIFO depth.
422          */
423         if (id->send_count > CDNS_I2C_FIFO_DEPTH)
424                 ctrl_reg |= CDNS_I2C_CR_HOLD;
425         cdns_i2c_writereg(ctrl_reg, CDNS_I2C_CR_OFFSET);
426
427         /* Clear the interrupts in interrupt status register. */
428         isr_status = cdns_i2c_readreg(CDNS_I2C_ISR_OFFSET);
429         cdns_i2c_writereg(isr_status, CDNS_I2C_ISR_OFFSET);
430
431         /*
432          * Calculate the space available in FIFO. Check the message length
433          * against the space available, and fill the FIFO accordingly.
434          * Enable the interrupts.
435          */
436         avail_bytes = CDNS_I2C_FIFO_DEPTH -
437                                 cdns_i2c_readreg(CDNS_I2C_XFER_SIZE_OFFSET);
438
439         if (id->send_count > avail_bytes)
440                 bytes_to_send = avail_bytes;
441         else
442                 bytes_to_send = id->send_count;
443
444         while (bytes_to_send--) {
445                 cdns_i2c_writereg((*(id->p_send_buf)++), CDNS_I2C_DATA_OFFSET);
446                 id->send_count--;
447         }
448
449         /*
450          * Clear the bus hold flag if there is no more data
451          * and if it is the last message.
452          */
453         if (!id->bus_hold_flag && !id->send_count)
454                 cdns_i2c_clear_bus_hold(id);
455         /* Set the slave address in address register - triggers operation. */
456         cdns_i2c_writereg(id->p_msg->addr & CDNS_I2C_ADDR_MASK,
457                                                 CDNS_I2C_ADDR_OFFSET);
458
459         cdns_i2c_writereg(CDNS_I2C_ENABLED_INTR_MASK, CDNS_I2C_IER_OFFSET);
460 }
461
462 /**
463  * cdns_i2c_master_reset - Reset the interface
464  * @adap:       pointer to the i2c adapter driver instance
465  *
466  * This function cleanup the fifos, clear the hold bit and status
467  * and disable the interrupts.
468  */
469 static void cdns_i2c_master_reset(struct i2c_adapter *adap)
470 {
471         struct cdns_i2c *id = adap->algo_data;
472         u32 regval;
473
474         /* Disable the interrupts */
475         cdns_i2c_writereg(CDNS_I2C_IXR_ALL_INTR_MASK, CDNS_I2C_IDR_OFFSET);
476         /* Clear the hold bit and fifos */
477         regval = cdns_i2c_readreg(CDNS_I2C_CR_OFFSET);
478         regval &= ~CDNS_I2C_CR_HOLD;
479         regval |= CDNS_I2C_CR_CLR_FIFO;
480         cdns_i2c_writereg(regval, CDNS_I2C_CR_OFFSET);
481         /* Update the transfercount register to zero */
482         cdns_i2c_writereg(0, CDNS_I2C_XFER_SIZE_OFFSET);
483         /* Clear the interupt status register */
484         regval = cdns_i2c_readreg(CDNS_I2C_ISR_OFFSET);
485         cdns_i2c_writereg(regval, CDNS_I2C_ISR_OFFSET);
486         /* Clear the status register */
487         regval = cdns_i2c_readreg(CDNS_I2C_SR_OFFSET);
488         cdns_i2c_writereg(regval, CDNS_I2C_SR_OFFSET);
489 }
490
491 static int cdns_i2c_process_msg(struct cdns_i2c *id, struct i2c_msg *msg,
492                 struct i2c_adapter *adap)
493 {
494         unsigned long time_left, msg_timeout;
495         u32 reg;
496
497         id->p_msg = msg;
498         id->err_status = 0;
499         reinit_completion(&id->xfer_done);
500
501         /* Check for the TEN Bit mode on each msg */
502         reg = cdns_i2c_readreg(CDNS_I2C_CR_OFFSET);
503         if (msg->flags & I2C_M_TEN) {
504                 if (reg & CDNS_I2C_CR_NEA)
505                         cdns_i2c_writereg(reg & ~CDNS_I2C_CR_NEA,
506                                         CDNS_I2C_CR_OFFSET);
507         } else {
508                 if (!(reg & CDNS_I2C_CR_NEA))
509                         cdns_i2c_writereg(reg | CDNS_I2C_CR_NEA,
510                                         CDNS_I2C_CR_OFFSET);
511         }
512
513         /* Check for the R/W flag on each msg */
514         if (msg->flags & I2C_M_RD)
515                 cdns_i2c_mrecv(id);
516         else
517                 cdns_i2c_msend(id);
518
519         /* Minimal time to execute this message */
520         msg_timeout = msecs_to_jiffies((1000 * msg->len * BITS_PER_BYTE) / id->i2c_clk);
521         /* Plus some wiggle room */
522         msg_timeout += msecs_to_jiffies(500);
523
524         if (msg_timeout < adap->timeout)
525                 msg_timeout = adap->timeout;
526
527         /* Wait for the signal of completion */
528         time_left = wait_for_completion_timeout(&id->xfer_done, msg_timeout);
529         if (time_left == 0) {
530                 cdns_i2c_master_reset(adap);
531                 dev_err(id->adap.dev.parent,
532                                 "timeout waiting on completion\n");
533                 return -ETIMEDOUT;
534         }
535
536         cdns_i2c_writereg(CDNS_I2C_IXR_ALL_INTR_MASK,
537                           CDNS_I2C_IDR_OFFSET);
538
539         /* If it is bus arbitration error, try again */
540         if (id->err_status & CDNS_I2C_IXR_ARB_LOST)
541                 return -EAGAIN;
542
543         return 0;
544 }
545
546 /**
547  * cdns_i2c_master_xfer - The main i2c transfer function
548  * @adap:       pointer to the i2c adapter driver instance
549  * @msgs:       pointer to the i2c message structure
550  * @num:        the number of messages to transfer
551  *
552  * Initiates the send/recv activity based on the transfer message received.
553  *
554  * Return: number of msgs processed on success, negative error otherwise
555  */
556 static int cdns_i2c_master_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
557                                 int num)
558 {
559         int ret, count;
560         u32 reg;
561         struct cdns_i2c *id = adap->algo_data;
562         bool hold_quirk;
563
564         ret = pm_runtime_get_sync(id->dev);
565         if (ret < 0)
566                 return ret;
567         /* Check if the bus is free */
568         if (cdns_i2c_readreg(CDNS_I2C_SR_OFFSET) & CDNS_I2C_SR_BA) {
569                 ret = -EAGAIN;
570                 goto out;
571         }
572
573         hold_quirk = !!(id->quirks & CDNS_I2C_BROKEN_HOLD_BIT);
574         /*
575          * Set the flag to one when multiple messages are to be
576          * processed with a repeated start.
577          */
578         if (num > 1) {
579                 /*
580                  * This controller does not give completion interrupt after a
581                  * master receive message if HOLD bit is set (repeated start),
582                  * resulting in SW timeout. Hence, if a receive message is
583                  * followed by any other message, an error is returned
584                  * indicating that this sequence is not supported.
585                  */
586                 for (count = 0; (count < num - 1 && hold_quirk); count++) {
587                         if (msgs[count].flags & I2C_M_RD) {
588                                 dev_warn(adap->dev.parent,
589                                          "Can't do repeated start after a receive message\n");
590                                 ret = -EOPNOTSUPP;
591                                 goto out;
592                         }
593                 }
594                 id->bus_hold_flag = 1;
595                 reg = cdns_i2c_readreg(CDNS_I2C_CR_OFFSET);
596                 reg |= CDNS_I2C_CR_HOLD;
597                 cdns_i2c_writereg(reg, CDNS_I2C_CR_OFFSET);
598         } else {
599                 id->bus_hold_flag = 0;
600         }
601
602         /* Process the msg one by one */
603         for (count = 0; count < num; count++, msgs++) {
604                 if (count == (num - 1))
605                         id->bus_hold_flag = 0;
606
607                 ret = cdns_i2c_process_msg(id, msgs, adap);
608                 if (ret)
609                         goto out;
610
611                 /* Report the other error interrupts to application */
612                 if (id->err_status) {
613                         cdns_i2c_master_reset(adap);
614
615                         if (id->err_status & CDNS_I2C_IXR_NACK) {
616                                 ret = -ENXIO;
617                                 goto out;
618                         }
619                         ret = -EIO;
620                         goto out;
621                 }
622         }
623
624         ret = num;
625 out:
626         pm_runtime_mark_last_busy(id->dev);
627         pm_runtime_put_autosuspend(id->dev);
628         return ret;
629 }
630
631 /**
632  * cdns_i2c_func - Returns the supported features of the I2C driver
633  * @adap:       pointer to the i2c adapter structure
634  *
635  * Return: 32 bit value, each bit corresponding to a feature
636  */
637 static u32 cdns_i2c_func(struct i2c_adapter *adap)
638 {
639         return I2C_FUNC_I2C | I2C_FUNC_10BIT_ADDR |
640                 (I2C_FUNC_SMBUS_EMUL & ~I2C_FUNC_SMBUS_QUICK) |
641                 I2C_FUNC_SMBUS_BLOCK_DATA;
642 }
643
644 static const struct i2c_algorithm cdns_i2c_algo = {
645         .master_xfer    = cdns_i2c_master_xfer,
646         .functionality  = cdns_i2c_func,
647 };
648
649 /**
650  * cdns_i2c_calc_divs - Calculate clock dividers
651  * @f:          I2C clock frequency
652  * @input_clk:  Input clock frequency
653  * @a:          First divider (return value)
654  * @b:          Second divider (return value)
655  *
656  * f is used as input and output variable. As input it is used as target I2C
657  * frequency. On function exit f holds the actually resulting I2C frequency.
658  *
659  * Return: 0 on success, negative errno otherwise.
660  */
661 static int cdns_i2c_calc_divs(unsigned long *f, unsigned long input_clk,
662                 unsigned int *a, unsigned int *b)
663 {
664         unsigned long fscl = *f, best_fscl = *f, actual_fscl, temp;
665         unsigned int div_a, div_b, calc_div_a = 0, calc_div_b = 0;
666         unsigned int last_error, current_error;
667
668         /* calculate (divisor_a+1) x (divisor_b+1) */
669         temp = input_clk / (22 * fscl);
670
671         /*
672          * If the calculated value is negative or 0, the fscl input is out of
673          * range. Return error.
674          */
675         if (!temp || (temp > (CDNS_I2C_DIVA_MAX * CDNS_I2C_DIVB_MAX)))
676                 return -EINVAL;
677
678         last_error = -1;
679         for (div_a = 0; div_a < CDNS_I2C_DIVA_MAX; div_a++) {
680                 div_b = DIV_ROUND_UP(input_clk, 22 * fscl * (div_a + 1));
681
682                 if ((div_b < 1) || (div_b > CDNS_I2C_DIVB_MAX))
683                         continue;
684                 div_b--;
685
686                 actual_fscl = input_clk / (22 * (div_a + 1) * (div_b + 1));
687
688                 if (actual_fscl > fscl)
689                         continue;
690
691                 current_error = ((actual_fscl > fscl) ? (actual_fscl - fscl) :
692                                                         (fscl - actual_fscl));
693
694                 if (last_error > current_error) {
695                         calc_div_a = div_a;
696                         calc_div_b = div_b;
697                         best_fscl = actual_fscl;
698                         last_error = current_error;
699                 }
700         }
701
702         *a = calc_div_a;
703         *b = calc_div_b;
704         *f = best_fscl;
705
706         return 0;
707 }
708
709 /**
710  * cdns_i2c_setclk - This function sets the serial clock rate for the I2C device
711  * @clk_in:     I2C clock input frequency in Hz
712  * @id:         Pointer to the I2C device structure
713  *
714  * The device must be idle rather than busy transferring data before setting
715  * these device options.
716  * The data rate is set by values in the control register.
717  * The formula for determining the correct register values is
718  *      Fscl = Fpclk/(22 x (divisor_a+1) x (divisor_b+1))
719  * See the hardware data sheet for a full explanation of setting the serial
720  * clock rate. The clock can not be faster than the input clock divide by 22.
721  * The two most common clock rates are 100KHz and 400KHz.
722  *
723  * Return: 0 on success, negative error otherwise
724  */
725 static int cdns_i2c_setclk(unsigned long clk_in, struct cdns_i2c *id)
726 {
727         unsigned int div_a, div_b;
728         unsigned int ctrl_reg;
729         int ret = 0;
730         unsigned long fscl = id->i2c_clk;
731
732         ret = cdns_i2c_calc_divs(&fscl, clk_in, &div_a, &div_b);
733         if (ret)
734                 return ret;
735
736         ctrl_reg = cdns_i2c_readreg(CDNS_I2C_CR_OFFSET);
737         ctrl_reg &= ~(CDNS_I2C_CR_DIVA_MASK | CDNS_I2C_CR_DIVB_MASK);
738         ctrl_reg |= ((div_a << CDNS_I2C_CR_DIVA_SHIFT) |
739                         (div_b << CDNS_I2C_CR_DIVB_SHIFT));
740         cdns_i2c_writereg(ctrl_reg, CDNS_I2C_CR_OFFSET);
741
742         return 0;
743 }
744
745 /**
746  * cdns_i2c_clk_notifier_cb - Clock rate change callback
747  * @nb:         Pointer to notifier block
748  * @event:      Notification reason
749  * @data:       Pointer to notification data object
750  *
751  * This function is called when the cdns_i2c input clock frequency changes.
752  * The callback checks whether a valid bus frequency can be generated after the
753  * change. If so, the change is acknowledged, otherwise the change is aborted.
754  * New dividers are written to the HW in the pre- or post change notification
755  * depending on the scaling direction.
756  *
757  * Return:      NOTIFY_STOP if the rate change should be aborted, NOTIFY_OK
758  *              to acknowledge the change, NOTIFY_DONE if the notification is
759  *              considered irrelevant.
760  */
761 static int cdns_i2c_clk_notifier_cb(struct notifier_block *nb, unsigned long
762                 event, void *data)
763 {
764         struct clk_notifier_data *ndata = data;
765         struct cdns_i2c *id = to_cdns_i2c(nb);
766
767         if (pm_runtime_suspended(id->dev))
768                 return NOTIFY_OK;
769
770         switch (event) {
771         case PRE_RATE_CHANGE:
772         {
773                 unsigned long input_clk = ndata->new_rate;
774                 unsigned long fscl = id->i2c_clk;
775                 unsigned int div_a, div_b;
776                 int ret;
777
778                 ret = cdns_i2c_calc_divs(&fscl, input_clk, &div_a, &div_b);
779                 if (ret) {
780                         dev_warn(id->adap.dev.parent,
781                                         "clock rate change rejected\n");
782                         return NOTIFY_STOP;
783                 }
784
785                 /* scale up */
786                 if (ndata->new_rate > ndata->old_rate)
787                         cdns_i2c_setclk(ndata->new_rate, id);
788
789                 return NOTIFY_OK;
790         }
791         case POST_RATE_CHANGE:
792                 id->input_clk = ndata->new_rate;
793                 /* scale down */
794                 if (ndata->new_rate < ndata->old_rate)
795                         cdns_i2c_setclk(ndata->new_rate, id);
796                 return NOTIFY_OK;
797         case ABORT_RATE_CHANGE:
798                 /* scale up */
799                 if (ndata->new_rate > ndata->old_rate)
800                         cdns_i2c_setclk(ndata->old_rate, id);
801                 return NOTIFY_OK;
802         default:
803                 return NOTIFY_DONE;
804         }
805 }
806
807 /**
808  * cdns_i2c_runtime_suspend -  Runtime suspend method for the driver
809  * @dev:        Address of the platform_device structure
810  *
811  * Put the driver into low power mode.
812  *
813  * Return: 0 always
814  */
815 static int __maybe_unused cdns_i2c_runtime_suspend(struct device *dev)
816 {
817         struct cdns_i2c *xi2c = dev_get_drvdata(dev);
818
819         clk_disable(xi2c->clk);
820
821         return 0;
822 }
823
824 /**
825  * cdns_i2c_runtime_resume - Runtime resume
826  * @dev:        Address of the platform_device structure
827  *
828  * Runtime resume callback.
829  *
830  * Return: 0 on success and error value on error
831  */
832 static int __maybe_unused cdns_i2c_runtime_resume(struct device *dev)
833 {
834         struct cdns_i2c *xi2c = dev_get_drvdata(dev);
835         int ret;
836
837         ret = clk_enable(xi2c->clk);
838         if (ret) {
839                 dev_err(dev, "Cannot enable clock.\n");
840                 return ret;
841         }
842
843         return 0;
844 }
845
846 static const struct dev_pm_ops cdns_i2c_dev_pm_ops = {
847         SET_RUNTIME_PM_OPS(cdns_i2c_runtime_suspend,
848                            cdns_i2c_runtime_resume, NULL)
849 };
850
851 static const struct cdns_platform_data r1p10_i2c_def = {
852         .quirks = CDNS_I2C_BROKEN_HOLD_BIT,
853 };
854
855 static const struct of_device_id cdns_i2c_of_match[] = {
856         { .compatible = "cdns,i2c-r1p10", .data = &r1p10_i2c_def },
857         { .compatible = "cdns,i2c-r1p14",},
858         { /* end of table */ }
859 };
860 MODULE_DEVICE_TABLE(of, cdns_i2c_of_match);
861
862 /**
863  * cdns_i2c_probe - Platform registration call
864  * @pdev:       Handle to the platform device structure
865  *
866  * This function does all the memory allocation and registration for the i2c
867  * device. User can modify the address mode to 10 bit address mode using the
868  * ioctl call with option I2C_TENBIT.
869  *
870  * Return: 0 on success, negative error otherwise
871  */
872 static int cdns_i2c_probe(struct platform_device *pdev)
873 {
874         struct resource *r_mem;
875         struct cdns_i2c *id;
876         int ret;
877         const struct of_device_id *match;
878
879         id = devm_kzalloc(&pdev->dev, sizeof(*id), GFP_KERNEL);
880         if (!id)
881                 return -ENOMEM;
882
883         id->dev = &pdev->dev;
884         platform_set_drvdata(pdev, id);
885
886         match = of_match_node(cdns_i2c_of_match, pdev->dev.of_node);
887         if (match && match->data) {
888                 const struct cdns_platform_data *data = match->data;
889                 id->quirks = data->quirks;
890         }
891
892         r_mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
893         id->membase = devm_ioremap_resource(&pdev->dev, r_mem);
894         if (IS_ERR(id->membase))
895                 return PTR_ERR(id->membase);
896
897         ret = platform_get_irq(pdev, 0);
898         if (ret < 0)
899                 return ret;
900         id->irq = ret;
901
902         id->adap.owner = THIS_MODULE;
903         id->adap.dev.of_node = pdev->dev.of_node;
904         id->adap.algo = &cdns_i2c_algo;
905         id->adap.timeout = CDNS_I2C_TIMEOUT;
906         id->adap.retries = 3;           /* Default retry value. */
907         id->adap.algo_data = id;
908         id->adap.dev.parent = &pdev->dev;
909         init_completion(&id->xfer_done);
910         snprintf(id->adap.name, sizeof(id->adap.name),
911                  "Cadence I2C at %08lx", (unsigned long)r_mem->start);
912
913         id->clk = devm_clk_get(&pdev->dev, NULL);
914         if (IS_ERR(id->clk)) {
915                 dev_err(&pdev->dev, "input clock not found.\n");
916                 return PTR_ERR(id->clk);
917         }
918         ret = clk_prepare_enable(id->clk);
919         if (ret)
920                 dev_err(&pdev->dev, "Unable to enable clock.\n");
921
922         pm_runtime_enable(id->dev);
923         pm_runtime_set_autosuspend_delay(id->dev, CNDS_I2C_PM_TIMEOUT);
924         pm_runtime_use_autosuspend(id->dev);
925         pm_runtime_set_active(id->dev);
926
927         id->clk_rate_change_nb.notifier_call = cdns_i2c_clk_notifier_cb;
928         if (clk_notifier_register(id->clk, &id->clk_rate_change_nb))
929                 dev_warn(&pdev->dev, "Unable to register clock notifier.\n");
930         id->input_clk = clk_get_rate(id->clk);
931
932         ret = of_property_read_u32(pdev->dev.of_node, "clock-frequency",
933                         &id->i2c_clk);
934         if (ret || (id->i2c_clk > CDNS_I2C_SPEED_MAX))
935                 id->i2c_clk = CDNS_I2C_SPEED_DEFAULT;
936
937         cdns_i2c_writereg(CDNS_I2C_CR_ACK_EN | CDNS_I2C_CR_NEA | CDNS_I2C_CR_MS,
938                           CDNS_I2C_CR_OFFSET);
939
940         ret = cdns_i2c_setclk(id->input_clk, id);
941         if (ret) {
942                 dev_err(&pdev->dev, "invalid SCL clock: %u Hz\n", id->i2c_clk);
943                 ret = -EINVAL;
944                 goto err_clk_dis;
945         }
946
947         ret = devm_request_irq(&pdev->dev, id->irq, cdns_i2c_isr, 0,
948                                  DRIVER_NAME, id);
949         if (ret) {
950                 dev_err(&pdev->dev, "cannot get irq %d\n", id->irq);
951                 goto err_clk_dis;
952         }
953
954         /*
955          * Cadence I2C controller has a bug wherein it generates
956          * invalid read transaction after HW timeout in master receiver mode.
957          * HW timeout is not used by this driver and the interrupt is disabled.
958          * But the feature itself cannot be disabled. Hence maximum value
959          * is written to this register to reduce the chances of error.
960          */
961         cdns_i2c_writereg(CDNS_I2C_TIMEOUT_MAX, CDNS_I2C_TIME_OUT_OFFSET);
962
963         ret = i2c_add_adapter(&id->adap);
964         if (ret < 0)
965                 goto err_clk_dis;
966
967         dev_info(&pdev->dev, "%u kHz mmio %08lx irq %d\n",
968                  id->i2c_clk / 1000, (unsigned long)r_mem->start, id->irq);
969
970         return 0;
971
972 err_clk_dis:
973         clk_notifier_unregister(id->clk, &id->clk_rate_change_nb);
974         clk_disable_unprepare(id->clk);
975         pm_runtime_set_suspended(&pdev->dev);
976         pm_runtime_disable(&pdev->dev);
977         return ret;
978 }
979
980 /**
981  * cdns_i2c_remove - Unregister the device after releasing the resources
982  * @pdev:       Handle to the platform device structure
983  *
984  * This function frees all the resources allocated to the device.
985  *
986  * Return: 0 always
987  */
988 static int cdns_i2c_remove(struct platform_device *pdev)
989 {
990         struct cdns_i2c *id = platform_get_drvdata(pdev);
991
992         i2c_del_adapter(&id->adap);
993         clk_notifier_unregister(id->clk, &id->clk_rate_change_nb);
994         clk_disable_unprepare(id->clk);
995         pm_runtime_disable(&pdev->dev);
996
997         return 0;
998 }
999
1000 static struct platform_driver cdns_i2c_drv = {
1001         .driver = {
1002                 .name  = DRIVER_NAME,
1003                 .of_match_table = cdns_i2c_of_match,
1004                 .pm = &cdns_i2c_dev_pm_ops,
1005         },
1006         .probe  = cdns_i2c_probe,
1007         .remove = cdns_i2c_remove,
1008 };
1009
1010 module_platform_driver(cdns_i2c_drv);
1011
1012 MODULE_AUTHOR("Xilinx Inc.");
1013 MODULE_DESCRIPTION("Cadence I2C bus driver");
1014 MODULE_LICENSE("GPL");