Prepare v2023.10
[platform/kernel/u-boot.git] / drivers / i2c / mvtwsi.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Driver for the TWSI (i2c) controller found on the Marvell
4  * orion5x and kirkwood SoC families.
5  *
6  * Author: Albert Aribaud <albert.u.boot@aribaud.net>
7  * Copyright (c) 2010 Albert Aribaud.
8  */
9
10 #include <common.h>
11 #include <i2c.h>
12 #include <log.h>
13 #include <asm/global_data.h>
14 #include <linux/delay.h>
15 #include <linux/errno.h>
16 #include <asm/io.h>
17 #include <linux/bitops.h>
18 #include <linux/compat.h>
19 #if CONFIG_IS_ENABLED(DM_I2C)
20 #include <clk.h>
21 #include <dm.h>
22 #include <reset.h>
23 #endif
24
25 DECLARE_GLOBAL_DATA_PTR;
26
27 /*
28  * Include a file that will provide CONFIG_I2C_MVTWSI_BASE*, and possibly other
29  * settings
30  */
31
32 #if !CONFIG_IS_ENABLED(DM_I2C)
33 #if defined(CONFIG_ARCH_ORION5X)
34 #include <asm/arch/orion5x.h>
35 #elif (defined(CONFIG_ARCH_KIRKWOOD) || defined(CONFIG_ARCH_MVEBU))
36 #include <asm/arch/soc.h>
37 #elif defined(CONFIG_ARCH_SUNXI)
38 #include <asm/arch/i2c.h>
39 #else
40 #error Driver mvtwsi not supported by SoC or board
41 #endif
42 #endif /* CONFIG_DM_I2C */
43
44 /*
45  * On SUNXI, we get CFG_SYS_TCLK from this include, so we want to
46  * always have it.
47  */
48 #if CONFIG_IS_ENABLED(DM_I2C) && defined(CONFIG_ARCH_SUNXI)
49 #include <asm/arch/i2c.h>
50 #endif
51
52 /*
53  * TWSI register structure
54  */
55
56 #ifdef CONFIG_ARCH_SUNXI
57
58 struct  mvtwsi_registers {
59         u32 slave_address;
60         u32 xtnd_slave_addr;
61         u32 data;
62         u32 control;
63         u32 status;
64         u32 baudrate;
65         u32 soft_reset;
66         u32 debug; /* Dummy field for build compatibility with mvebu */
67 };
68
69 #else
70
71 struct  mvtwsi_registers {
72         u32 slave_address;
73         u32 data;
74         u32 control;
75         union {
76                 u32 status;     /* When reading */
77                 u32 baudrate;   /* When writing */
78         };
79         u32 xtnd_slave_addr;
80         u32 reserved0[2];
81         u32 soft_reset;
82         u32 reserved1[27];
83         u32 debug;
84 };
85
86 #endif
87
88 #if CONFIG_IS_ENABLED(DM_I2C)
89 struct mvtwsi_i2c_dev {
90         /* TWSI Register base for the device */
91         struct mvtwsi_registers *base;
92         /* Number of the device (determined from cell-index property) */
93         int index;
94         /* The I2C slave address for the device */
95         u8 slaveadd;
96         /* The configured I2C speed in Hz */
97         uint speed;
98         /* The current length of a clock period (depending on speed) */
99         uint tick;
100 };
101 #endif /* CONFIG_DM_I2C */
102
103 /*
104  * enum mvtwsi_ctrl_register_fields - Bit masks for flags in the control
105  * register
106  */
107 enum mvtwsi_ctrl_register_fields {
108         /* Acknowledge bit */
109         MVTWSI_CONTROL_ACK      = 0x00000004,
110         /* Interrupt flag */
111         MVTWSI_CONTROL_IFLG     = 0x00000008,
112         /* Stop bit */
113         MVTWSI_CONTROL_STOP     = 0x00000010,
114         /* Start bit */
115         MVTWSI_CONTROL_START    = 0x00000020,
116         /* I2C enable */
117         MVTWSI_CONTROL_TWSIEN   = 0x00000040,
118         /* Interrupt enable */
119         MVTWSI_CONTROL_INTEN    = 0x00000080,
120 };
121
122 /*
123  * On sun6i and newer, IFLG is a write-clear bit, which is cleared by writing 1;
124  * on other platforms, it is a normal r/w bit, which is cleared by writing 0.
125  */
126
127 #if defined(CONFIG_SUNXI_GEN_SUN6I) || defined(CONFIG_SUN50I_GEN_H6)
128 #define MVTWSI_CONTROL_CLEAR_IFLG       0x00000008
129 #else
130 #define MVTWSI_CONTROL_CLEAR_IFLG       0x00000000
131 #endif
132
133 /*
134  * enum mvstwsi_status_values - Possible values of I2C controller's status
135  * register
136  *
137  * Only those statuses expected in normal master operation on
138  * non-10-bit-address devices are specified.
139  *
140  * Every status that's unexpected during normal operation (bus errors,
141  * arbitration losses, missing ACKs...) is passed back to the caller as an error
142  * code.
143  */
144 enum mvstwsi_status_values {
145         /* Protocol violation on bus; this is a terminal state */
146         MVTWSI_BUS_ERROR                = 0x00,
147         /* START condition transmitted */
148         MVTWSI_STATUS_START             = 0x08,
149         /* Repeated START condition transmitted */
150         MVTWSI_STATUS_REPEATED_START    = 0x10,
151         /* Address + write bit transmitted, ACK received */
152         MVTWSI_STATUS_ADDR_W_ACK        = 0x18,
153         /* Data transmitted, ACK received */
154         MVTWSI_STATUS_DATA_W_ACK        = 0x28,
155         /* Address + read bit transmitted, ACK received */
156         MVTWSI_STATUS_ADDR_R_ACK        = 0x40,
157         /* Address + read bit transmitted, ACK not received */
158         MVTWSI_STATUS_ADDR_R_NAK        = 0x48,
159         /* Data received, ACK transmitted */
160         MVTWSI_STATUS_DATA_R_ACK        = 0x50,
161         /* Data received, ACK not transmitted */
162         MVTWSI_STATUS_DATA_R_NAK        = 0x58,
163         /* No relevant status */
164         MVTWSI_STATUS_IDLE              = 0xF8,
165 };
166
167 /*
168  * enum mvstwsi_ack_flags - Determine whether a read byte should be
169  * acknowledged or not.
170  */
171 enum mvtwsi_ack_flags {
172         /* Send NAK after received byte */
173         MVTWSI_READ_NAK = 0,
174         /* Send ACK after received byte */
175         MVTWSI_READ_ACK = 1,
176 };
177
178 /*
179  * calc_tick() - Calculate the duration of a clock cycle from the I2C speed
180  *
181  * @speed:      The speed in Hz to calculate the clock cycle duration for.
182  * Return: The duration of a clock cycle in ns.
183  */
184 inline uint calc_tick(uint speed)
185 {
186         /* One tick = the duration of a period at the specified speed in ns (we
187          * add 100 ns to be on the safe side) */
188         return (1000000000u / speed) + 100;
189 }
190
191 #if !CONFIG_IS_ENABLED(DM_I2C)
192
193 /*
194  * twsi_get_base() - Get controller register base for specified adapter
195  *
196  * @adap:       Adapter to get the register base for.
197  * Return: Register base for the specified adapter.
198  */
199 static struct mvtwsi_registers *twsi_get_base(struct i2c_adapter *adap)
200 {
201         switch (adap->hwadapnr) {
202 #ifdef CFG_I2C_MVTWSI_BASE0
203         case 0:
204                 return (struct mvtwsi_registers *)CFG_I2C_MVTWSI_BASE0;
205 #endif
206 #ifdef CFG_I2C_MVTWSI_BASE1
207         case 1:
208                 return (struct mvtwsi_registers *)CFG_I2C_MVTWSI_BASE1;
209 #endif
210 #ifdef CFG_I2C_MVTWSI_BASE2
211         case 2:
212                 return (struct mvtwsi_registers *)CFG_I2C_MVTWSI_BASE2;
213 #endif
214 #ifdef CONFIG_I2C_MVTWSI_BASE3
215         case 3:
216                 return (struct mvtwsi_registers *)CONFIG_I2C_MVTWSI_BASE3;
217 #endif
218 #ifdef CONFIG_I2C_MVTWSI_BASE4
219         case 4:
220                 return (struct mvtwsi_registers *)CONFIG_I2C_MVTWSI_BASE4;
221 #endif
222 #ifdef CONFIG_I2C_MVTWSI_BASE5
223         case 5:
224                 return (struct mvtwsi_registers *)CONFIG_I2C_MVTWSI_BASE5;
225 #endif
226         default:
227                 printf("Missing mvtwsi controller %d base\n", adap->hwadapnr);
228                 break;
229         }
230
231         return NULL;
232 }
233 #endif
234
235 /*
236  * enum mvtwsi_error_class - types of I2C errors
237  */
238 enum mvtwsi_error_class {
239         /* The controller returned a different status than expected */
240         MVTWSI_ERROR_WRONG_STATUS       = 0x01,
241         /* The controller timed out */
242         MVTWSI_ERROR_TIMEOUT            = 0x02,
243 };
244
245 /*
246  * mvtwsi_error() - Build I2C return code from error information
247  *
248  * For debugging purposes, this function packs some information of an occurred
249  * error into a return code. These error codes are returned from I2C API
250  * functions (i2c_{read,write}, dm_i2c_{read,write}, etc.).
251  *
252  * @ec:         The error class of the error (enum mvtwsi_error_class).
253  * @lc:         The last value of the control register.
254  * @ls:         The last value of the status register.
255  * @es:         The expected value of the status register.
256  * Return: The generated error code.
257  */
258 inline uint mvtwsi_error(uint ec, uint lc, uint ls, uint es)
259 {
260         return ((ec << 24) & 0xFF000000)
261                | ((lc << 16) & 0x00FF0000)
262                | ((ls << 8) & 0x0000FF00)
263                | (es & 0xFF);
264 }
265
266 /*
267  * twsi_wait() - Wait for I2C bus interrupt flag and check status, or time out.
268  *
269  * Return: Zero if status is as expected, or a non-zero code if either a time
270  *         out occurred, or the status was not the expected one.
271  */
272 static int twsi_wait(struct mvtwsi_registers *twsi, int expected_status,
273                      uint tick)
274 {
275         int control, status;
276         int timeout = 1000;
277
278         do {
279                 control = readl(&twsi->control);
280                 if (control & MVTWSI_CONTROL_IFLG) {
281                         /*
282                          * On Armada 38x it seems that the controller works as
283                          * if it first set the MVTWSI_CONTROL_IFLAG in the
284                          * control register and only after that it changed the
285                          * status register.
286                          * This sometimes caused weird bugs which only appeared
287                          * on selected I2C speeds and even then only sometimes.
288                          * We therefore add here a simple ndealy(100), which
289                          * seems to fix this weird bug.
290                          */
291                         ndelay(100);
292                         status = readl(&twsi->status);
293                         if (status == expected_status)
294                                 return 0;
295                         else
296                                 return mvtwsi_error(
297                                         MVTWSI_ERROR_WRONG_STATUS,
298                                         control, status, expected_status);
299                 }
300                 ndelay(tick); /* One clock cycle */
301         } while (timeout--);
302         status = readl(&twsi->status);
303         return mvtwsi_error(MVTWSI_ERROR_TIMEOUT, control, status,
304                             expected_status);
305 }
306
307 /*
308  * twsi_start() - Assert a START condition on the bus.
309  *
310  * This function is used in both single I2C transactions and inside
311  * back-to-back transactions (repeated starts).
312  *
313  * @twsi:               The MVTWSI register structure to use.
314  * @expected_status:    The I2C bus status expected to be asserted after the
315  *                      operation completion.
316  * @tick:               The duration of a clock cycle at the current I2C speed.
317  * Return: Zero if status is as expected, or a non-zero code if either a time
318  *         out occurred or the status was not the expected one.
319  */
320 static int twsi_start(struct mvtwsi_registers *twsi, int expected_status,
321                       uint tick)
322 {
323         /* Assert START */
324         writel(MVTWSI_CONTROL_TWSIEN | MVTWSI_CONTROL_START |
325                MVTWSI_CONTROL_CLEAR_IFLG, &twsi->control);
326         /* Wait for controller to process START */
327         return twsi_wait(twsi, expected_status, tick);
328 }
329
330 /*
331  * twsi_send() - Send a byte on the I2C bus.
332  *
333  * The byte may be part of an address byte or data.
334  *
335  * @twsi:               The MVTWSI register structure to use.
336  * @byte:               The byte to send.
337  * @expected_status:    The I2C bus status expected to be asserted after the
338  *                      operation completion.
339  * @tick:               The duration of a clock cycle at the current I2C speed.
340  * Return: Zero if status is as expected, or a non-zero code if either a time
341  *         out occurred or the status was not the expected one.
342  */
343 static int twsi_send(struct mvtwsi_registers *twsi, u8 byte,
344                      int expected_status, uint tick)
345 {
346         /* Write byte to data register for sending */
347         writel(byte, &twsi->data);
348         /* Clear any pending interrupt -- that will cause sending */
349         writel(MVTWSI_CONTROL_TWSIEN | MVTWSI_CONTROL_CLEAR_IFLG,
350                &twsi->control);
351         /* Wait for controller to receive byte, and check ACK */
352         return twsi_wait(twsi, expected_status, tick);
353 }
354
355 /*
356  * twsi_recv() - Receive a byte on the I2C bus.
357  *
358  * The static variable mvtwsi_control_flags controls whether we ack or nak.
359  *
360  * @twsi:               The MVTWSI register structure to use.
361  * @byte:               The byte to send.
362  * @ack_flag:           Flag that determines whether the received byte should
363  *                      be acknowledged by the controller or not (sent ACK/NAK).
364  * @tick:               The duration of a clock cycle at the current I2C speed.
365  * Return: Zero if status is as expected, or a non-zero code if either a time
366  *         out occurred or the status was not the expected one.
367  */
368 static int twsi_recv(struct mvtwsi_registers *twsi, u8 *byte, int ack_flag,
369                      uint tick)
370 {
371         int expected_status, status, control;
372
373         /* Compute expected status based on passed ACK flag */
374         expected_status = ack_flag ? MVTWSI_STATUS_DATA_R_ACK :
375                           MVTWSI_STATUS_DATA_R_NAK;
376         /* Acknowledge *previous state*, and launch receive */
377         control = MVTWSI_CONTROL_TWSIEN;
378         control |= ack_flag == MVTWSI_READ_ACK ? MVTWSI_CONTROL_ACK : 0;
379         writel(control | MVTWSI_CONTROL_CLEAR_IFLG, &twsi->control);
380         /* Wait for controller to receive byte, and assert ACK or NAK */
381         status = twsi_wait(twsi, expected_status, tick);
382         /* If we did receive the expected byte, store it */
383         if (status == 0)
384                 *byte = readl(&twsi->data);
385         return status;
386 }
387
388 /*
389  * twsi_stop() - Assert a STOP condition on the bus.
390  *
391  * This function is also used to force the bus back to idle state (SDA =
392  * SCL = 1).
393  *
394  * @twsi:       The MVTWSI register structure to use.
395  * @tick:       The duration of a clock cycle at the current I2C speed.
396  * Return: Zero if the operation succeeded, or a non-zero code if a time out
397  *         occurred.
398  */
399 static int twsi_stop(struct mvtwsi_registers *twsi, uint tick)
400 {
401         int control, stop_status;
402         int status = 0;
403         int timeout = 1000;
404
405         /* Assert STOP */
406         control = MVTWSI_CONTROL_TWSIEN | MVTWSI_CONTROL_STOP;
407         writel(control | MVTWSI_CONTROL_CLEAR_IFLG, &twsi->control);
408         /* Wait for IDLE; IFLG won't rise, so we can't use twsi_wait() */
409         do {
410                 stop_status = readl(&twsi->status);
411                 if (stop_status == MVTWSI_STATUS_IDLE)
412                         break;
413                 ndelay(tick); /* One clock cycle */
414         } while (timeout--);
415         control = readl(&twsi->control);
416         if (stop_status != MVTWSI_STATUS_IDLE)
417                 status = mvtwsi_error(MVTWSI_ERROR_TIMEOUT,
418                                       control, status, MVTWSI_STATUS_IDLE);
419         return status;
420 }
421
422 /*
423  * twsi_calc_freq() - Compute I2C frequency depending on m and n parameters.
424  *
425  * @n:          Parameter 'n' for the frequency calculation algorithm.
426  * @m:          Parameter 'm' for the frequency calculation algorithm.
427  * Return: The I2C frequency corresponding to the passed m and n parameters.
428  */
429 static uint twsi_calc_freq(const int n, const int m)
430 {
431 #ifdef CONFIG_ARCH_SUNXI
432         return CFG_SYS_TCLK / (10 * (m + 1) * (1 << n));
433 #else
434         return CFG_SYS_TCLK / (10 * (m + 1) * (2 << n));
435 #endif
436 }
437
438 /*
439  * twsi_reset() - Reset the I2C controller.
440  *
441  * Resetting the controller also resets the baud rate and slave address, hence
442  * they must be re-established after the reset.
443  *
444  * @twsi:       The MVTWSI register structure to use.
445  */
446 static void twsi_reset(struct mvtwsi_registers *twsi)
447 {
448         /* Reset controller */
449         writel(0, &twsi->soft_reset);
450         /* Wait 2 ms -- this is what the Marvell LSP does */
451         udelay(20000);
452 }
453
454 /*
455  * __twsi_i2c_set_bus_speed() - Set the speed of the I2C controller.
456  *
457  * This function sets baud rate to the highest possible value that does not
458  * exceed the requested rate.
459  *
460  * @twsi:               The MVTWSI register structure to use.
461  * @requested_speed:    The desired frequency the controller should run at
462  *                      in Hz.
463  * Return: The actual frequency the controller was configured to.
464  */
465 static uint __twsi_i2c_set_bus_speed(struct mvtwsi_registers *twsi,
466                                      uint requested_speed)
467 {
468         uint tmp_speed, highest_speed, n, m;
469         uint baud = 0x44; /* Baud rate after controller reset */
470
471         highest_speed = 0;
472         /* Successively try m, n combinations, and use the combination
473          * resulting in the largest speed that's not above the requested
474          * speed */
475         for (n = 0; n < 8; n++) {
476                 for (m = 0; m < 16; m++) {
477                         tmp_speed = twsi_calc_freq(n, m);
478                         if ((tmp_speed <= requested_speed) &&
479                             (tmp_speed > highest_speed)) {
480                                 highest_speed = tmp_speed;
481                                 baud = (m << 3) | n;
482                         }
483                 }
484         }
485         writel(baud, &twsi->baudrate);
486
487         /* Wait for controller for one tick */
488 #if CONFIG_IS_ENABLED(DM_I2C)
489         ndelay(calc_tick(highest_speed));
490 #else
491         ndelay(10000);
492 #endif
493         return highest_speed;
494 }
495
496 /*
497  * __twsi_i2c_init() - Initialize the I2C controller.
498  *
499  * @twsi:               The MVTWSI register structure to use.
500  * @speed:              The initial frequency the controller should run at
501  *                      in Hz.
502  * @slaveadd:           The I2C address to be set for the I2C master.
503  * @actual_speed:       A output parameter that receives the actual frequency
504  *                      in Hz the controller was set to by the function.
505  * Return: Zero if the operation succeeded, or a non-zero code if a time out
506  *         occurred.
507  */
508 static void __twsi_i2c_init(struct mvtwsi_registers *twsi, int speed,
509                             int slaveadd, uint *actual_speed)
510 {
511         uint tmp_speed;
512
513         /* Reset controller */
514         twsi_reset(twsi);
515         /* Set speed */
516         tmp_speed = __twsi_i2c_set_bus_speed(twsi, speed);
517         if (actual_speed)
518                 *actual_speed = tmp_speed;
519         /* Set slave address; even though we don't use it */
520         writel(slaveadd, &twsi->slave_address);
521         writel(0, &twsi->xtnd_slave_addr);
522         /* Assert STOP, but don't care for the result */
523 #if CONFIG_IS_ENABLED(DM_I2C)
524         (void) twsi_stop(twsi, calc_tick(*actual_speed));
525 #else
526         (void) twsi_stop(twsi, 10000);
527 #endif
528 }
529
530 /*
531  * __twsi_i2c_reinit() - Reset and reinitialize the I2C controller.
532  *
533  * This function should be called to get the MVTWSI controller out of the
534  * "bus error" state. It saves and restores the baud and address registers.
535  *
536  * @twsi:       The MVTWSI register structure to use.
537  * @tick:       The duration of a clock cycle at the current I2C speed.
538  */
539 static void __twsi_i2c_reinit(struct mvtwsi_registers *twsi, uint tick)
540 {
541         uint baud;
542         uint slaveadd;
543
544         /* Save baud, address registers */
545         baud = readl(&twsi->baudrate);
546         slaveadd = readl(&twsi->slave_address);
547
548         /* Reset controller */
549         twsi_reset(twsi);
550
551         /* Restore baud, address registers */
552         writel(baud, &twsi->baudrate);
553         writel(slaveadd, &twsi->slave_address);
554         writel(0, &twsi->xtnd_slave_addr);
555
556         /* Assert STOP, but don't care for the result */
557         (void) twsi_stop(twsi, tick);
558 }
559
560 /*
561  * i2c_begin() - Start a I2C transaction.
562  *
563  * Begin a I2C transaction with a given expected start status and chip address.
564  * A START is asserted, and the address byte is sent to the I2C controller. The
565  * expected address status will be derived from the direction bit (bit 0) of
566  * the address byte.
567  *
568  * @twsi:                       The MVTWSI register structure to use.
569  * @expected_start_status:      The I2C status the controller is expected to
570  *                              assert after the address byte was sent.
571  * @addr:                       The address byte to be sent.
572  * @tick:                       The duration of a clock cycle at the current
573  *                              I2C speed.
574  * Return: Zero if the operation succeeded, or a non-zero code if a time out or
575  *         unexpected I2C status occurred.
576  */
577 static int i2c_begin(struct mvtwsi_registers *twsi, int expected_start_status,
578                      u8 addr, uint tick)
579 {
580         int status, expected_addr_status;
581
582         /* Compute the expected address status from the direction bit in
583          * the address byte */
584         if (addr & 1) /* Reading */
585                 expected_addr_status = MVTWSI_STATUS_ADDR_R_ACK;
586         else /* Writing */
587                 expected_addr_status = MVTWSI_STATUS_ADDR_W_ACK;
588         /* Assert START */
589         status = twsi_start(twsi, expected_start_status, tick);
590         /* Send out the address if the start went well */
591         if (status == 0)
592                 status = twsi_send(twsi, addr, expected_addr_status, tick);
593         /* Return 0, or the status of the first failure */
594         return status;
595 }
596
597 /*
598  * __twsi_i2c_probe_chip() - Probe the given I2C chip address.
599  *
600  * This function begins a I2C read transaction, does a dummy read and NAKs; if
601  * the procedure succeeds, the chip is considered to be present.
602  *
603  * @twsi:       The MVTWSI register structure to use.
604  * @chip:       The chip address to probe.
605  * @tick:       The duration of a clock cycle at the current I2C speed.
606  * Return: Zero if the operation succeeded, or a non-zero code if a time out or
607  *         unexpected I2C status occurred.
608  */
609 static int __twsi_i2c_probe_chip(struct mvtwsi_registers *twsi, uchar chip,
610                                  uint tick)
611 {
612         u8 dummy_byte;
613         int status;
614
615         /* Begin i2c read */
616         status = i2c_begin(twsi, MVTWSI_STATUS_START, (chip << 1) | 1, tick);
617         /* Dummy read was accepted: receive byte, but NAK it. */
618         if (status == 0)
619                 status = twsi_recv(twsi, &dummy_byte, MVTWSI_READ_NAK, tick);
620         /* Stop transaction */
621         twsi_stop(twsi, tick);
622         /* Return 0, or the status of the first failure */
623         return status;
624 }
625
626 /*
627  * __twsi_i2c_read() - Read data from a I2C chip.
628  *
629  * This function begins a I2C write transaction, and transmits the address
630  * bytes; then begins a I2C read transaction, and receives the data bytes.
631  *
632  * NOTE: Some devices want a stop right before the second start, while some
633  * will choke if it is there. Since deciding this is not yet supported in
634  * higher level APIs, we need to make a decision here, and for the moment that
635  * will be a repeated start without a preceding stop.
636  *
637  * @twsi:       The MVTWSI register structure to use.
638  * @chip:       The chip address to read from.
639  * @addr:       The address bytes to send.
640  * @alen:       The length of the address bytes in bytes.
641  * @data:       The buffer to receive the data read from the chip (has to have
642  *              a size of at least 'length' bytes).
643  * @length:     The amount of data to be read from the chip in bytes.
644  * @tick:       The duration of a clock cycle at the current I2C speed.
645  * Return: Zero if the operation succeeded, or a non-zero code if a time out or
646  *         unexpected I2C status occurred.
647  */
648 static int __twsi_i2c_read(struct mvtwsi_registers *twsi, uchar chip,
649                            u8 *addr, int alen, uchar *data, int length,
650                            uint tick)
651 {
652         int status = 0;
653         int stop_status;
654         int expected_start = MVTWSI_STATUS_START;
655
656         /* Check for (and clear) a bus error from a previous failed transaction
657          * or another master on the same bus */
658         if (readl(&twsi->status) == MVTWSI_BUS_ERROR)
659                 __twsi_i2c_reinit(twsi, tick);
660
661         if (alen > 0) {
662                 /* Begin i2c write to send the address bytes */
663                 status = i2c_begin(twsi, expected_start, (chip << 1), tick);
664                 /* Send address bytes */
665                 while ((status == 0) && alen--)
666                         status = twsi_send(twsi, addr[alen],
667                                            MVTWSI_STATUS_DATA_W_ACK, tick);
668                 /* Send repeated STARTs after the initial START */
669                 expected_start = MVTWSI_STATUS_REPEATED_START;
670         }
671         /* Begin i2c read to receive data bytes */
672         if (status == 0)
673                 status = i2c_begin(twsi, expected_start, (chip << 1) | 1, tick);
674         /* Receive actual data bytes; set NAK if we if we have nothing more to
675          * read */
676         while ((status == 0) && length--)
677                 status = twsi_recv(twsi, data++,
678                                    length > 0 ?
679                                    MVTWSI_READ_ACK : MVTWSI_READ_NAK, tick);
680         /* Stop transaction */
681         stop_status = twsi_stop(twsi, tick);
682         /* Return 0, or the status of the first failure */
683         return status != 0 ? status : stop_status;
684 }
685
686 /*
687  * __twsi_i2c_write() - Send data to a I2C chip.
688  *
689  * This function begins a I2C write transaction, and transmits the address
690  * bytes; then begins a new I2C write transaction, and sends the data bytes.
691  *
692  * @twsi:       The MVTWSI register structure to use.
693  * @chip:       The chip address to read from.
694  * @addr:       The address bytes to send.
695  * @alen:       The length of the address bytes in bytes.
696  * @data:       The buffer containing the data to be sent to the chip.
697  * @length:     The length of data to be sent to the chip in bytes.
698  * @tick:       The duration of a clock cycle at the current I2C speed.
699  * Return: Zero if the operation succeeded, or a non-zero code if a time out or
700  *         unexpected I2C status occurred.
701  */
702 static int __twsi_i2c_write(struct mvtwsi_registers *twsi, uchar chip,
703                             u8 *addr, int alen, uchar *data, int length,
704                             uint tick)
705 {
706         int status, stop_status;
707
708         /* Check for (and clear) a bus error from a previous failed transaction
709          * or another master on the same bus */
710         if (readl(&twsi->status) == MVTWSI_BUS_ERROR)
711                 __twsi_i2c_reinit(twsi, tick);
712
713         /* Begin i2c write to send first the address bytes, then the
714          * data bytes */
715         status = i2c_begin(twsi, MVTWSI_STATUS_START, (chip << 1), tick);
716         /* Send address bytes */
717         while ((status == 0) && (alen-- > 0))
718                 status = twsi_send(twsi, addr[alen], MVTWSI_STATUS_DATA_W_ACK,
719                                    tick);
720         /* Send data bytes */
721         while ((status == 0) && (length-- > 0))
722                 status = twsi_send(twsi, *(data++), MVTWSI_STATUS_DATA_W_ACK,
723                                    tick);
724         /* Stop transaction */
725         stop_status = twsi_stop(twsi, tick);
726         /* Return 0, or the status of the first failure */
727         return status != 0 ? status : stop_status;
728 }
729
730 #if !CONFIG_IS_ENABLED(DM_I2C)
731 static void twsi_i2c_init(struct i2c_adapter *adap, int speed,
732                           int slaveadd)
733 {
734         struct mvtwsi_registers *twsi = twsi_get_base(adap);
735         __twsi_i2c_init(twsi, speed, slaveadd, NULL);
736 }
737
738 static uint twsi_i2c_set_bus_speed(struct i2c_adapter *adap,
739                                    uint requested_speed)
740 {
741         struct mvtwsi_registers *twsi = twsi_get_base(adap);
742         __twsi_i2c_set_bus_speed(twsi, requested_speed);
743         return 0;
744 }
745
746 static int twsi_i2c_probe(struct i2c_adapter *adap, uchar chip)
747 {
748         struct mvtwsi_registers *twsi = twsi_get_base(adap);
749         return __twsi_i2c_probe_chip(twsi, chip, 10000);
750 }
751
752 static int twsi_i2c_read(struct i2c_adapter *adap, uchar chip, uint addr,
753                          int alen, uchar *data, int length)
754 {
755         struct mvtwsi_registers *twsi = twsi_get_base(adap);
756         u8 addr_bytes[4];
757
758         addr_bytes[0] = (addr >> 0) & 0xFF;
759         addr_bytes[1] = (addr >> 8) & 0xFF;
760         addr_bytes[2] = (addr >> 16) & 0xFF;
761         addr_bytes[3] = (addr >> 24) & 0xFF;
762
763         return __twsi_i2c_read(twsi, chip, addr_bytes, alen, data, length,
764                                10000);
765 }
766
767 static int twsi_i2c_write(struct i2c_adapter *adap, uchar chip, uint addr,
768                           int alen, uchar *data, int length)
769 {
770         struct mvtwsi_registers *twsi = twsi_get_base(adap);
771         u8 addr_bytes[4];
772
773         addr_bytes[0] = (addr >> 0) & 0xFF;
774         addr_bytes[1] = (addr >> 8) & 0xFF;
775         addr_bytes[2] = (addr >> 16) & 0xFF;
776         addr_bytes[3] = (addr >> 24) & 0xFF;
777
778         return __twsi_i2c_write(twsi, chip, addr_bytes, alen, data, length,
779                                 10000);
780 }
781
782 #ifdef CFG_I2C_MVTWSI_BASE0
783 U_BOOT_I2C_ADAP_COMPLETE(twsi0, twsi_i2c_init, twsi_i2c_probe,
784                          twsi_i2c_read, twsi_i2c_write,
785                          twsi_i2c_set_bus_speed,
786                          CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE, 0)
787 #endif
788 #ifdef CFG_I2C_MVTWSI_BASE1
789 U_BOOT_I2C_ADAP_COMPLETE(twsi1, twsi_i2c_init, twsi_i2c_probe,
790                          twsi_i2c_read, twsi_i2c_write,
791                          twsi_i2c_set_bus_speed,
792                          CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE, 1)
793
794 #endif
795 #ifdef CFG_I2C_MVTWSI_BASE2
796 U_BOOT_I2C_ADAP_COMPLETE(twsi2, twsi_i2c_init, twsi_i2c_probe,
797                          twsi_i2c_read, twsi_i2c_write,
798                          twsi_i2c_set_bus_speed,
799                          CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE, 2)
800
801 #endif
802 #ifdef CONFIG_I2C_MVTWSI_BASE3
803 U_BOOT_I2C_ADAP_COMPLETE(twsi3, twsi_i2c_init, twsi_i2c_probe,
804                          twsi_i2c_read, twsi_i2c_write,
805                          twsi_i2c_set_bus_speed,
806                          CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE, 3)
807
808 #endif
809 #ifdef CONFIG_I2C_MVTWSI_BASE4
810 U_BOOT_I2C_ADAP_COMPLETE(twsi4, twsi_i2c_init, twsi_i2c_probe,
811                          twsi_i2c_read, twsi_i2c_write,
812                          twsi_i2c_set_bus_speed,
813                          CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE, 4)
814
815 #endif
816 #ifdef CONFIG_I2C_MVTWSI_BASE5
817 U_BOOT_I2C_ADAP_COMPLETE(twsi5, twsi_i2c_init, twsi_i2c_probe,
818                          twsi_i2c_read, twsi_i2c_write,
819                          twsi_i2c_set_bus_speed,
820                          CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE, 5)
821
822 #endif
823 #else /* CONFIG_DM_I2C */
824
825 static int mvtwsi_i2c_probe_chip(struct udevice *bus, u32 chip_addr,
826                                  u32 chip_flags)
827 {
828         struct mvtwsi_i2c_dev *dev = dev_get_priv(bus);
829         return __twsi_i2c_probe_chip(dev->base, chip_addr, dev->tick);
830 }
831
832 static int mvtwsi_i2c_set_bus_speed(struct udevice *bus, uint speed)
833 {
834         struct mvtwsi_i2c_dev *dev = dev_get_priv(bus);
835
836         dev->speed = __twsi_i2c_set_bus_speed(dev->base, speed);
837         dev->tick = calc_tick(dev->speed);
838
839         return 0;
840 }
841
842 static int mvtwsi_i2c_of_to_plat(struct udevice *bus)
843 {
844         struct mvtwsi_i2c_dev *dev = dev_get_priv(bus);
845
846         dev->base = dev_read_addr_ptr(bus);
847
848         if (!dev->base)
849                 return -ENOMEM;
850
851         dev->index = fdtdec_get_int(gd->fdt_blob, dev_of_offset(bus),
852                                     "cell-index", -1);
853         dev->slaveadd = fdtdec_get_int(gd->fdt_blob, dev_of_offset(bus),
854                                        "u-boot,i2c-slave-addr", 0x0);
855         dev->speed = dev_read_u32_default(bus, "clock-frequency",
856                                           I2C_SPEED_STANDARD_RATE);
857
858         return 0;
859 }
860
861 static void twsi_disable_i2c_slave(struct mvtwsi_registers *twsi)
862 {
863         clrbits_le32(&twsi->debug, BIT(18));
864 }
865
866 static int mvtwsi_i2c_bind(struct udevice *bus)
867 {
868         struct mvtwsi_registers *twsi = dev_read_addr_ptr(bus);
869
870         /* Disable the hidden slave in i2c0 of these platforms */
871         if ((IS_ENABLED(CONFIG_ARMADA_38X) ||
872              IS_ENABLED(CONFIG_ARCH_KIRKWOOD) ||
873              IS_ENABLED(CONFIG_ARMADA_8K)) && !dev_seq(bus))
874                 twsi_disable_i2c_slave(twsi);
875
876         return 0;
877 }
878
879 static int mvtwsi_i2c_probe(struct udevice *bus)
880 {
881         struct mvtwsi_i2c_dev *dev = dev_get_priv(bus);
882         struct reset_ctl reset;
883         struct clk clk;
884         uint actual_speed;
885         int ret;
886
887         ret = reset_get_by_index(bus, 0, &reset);
888         if (!ret)
889                 reset_deassert(&reset);
890
891         ret = clk_get_by_index(bus, 0, &clk);
892         if (!ret)
893                 clk_enable(&clk);
894
895         __twsi_i2c_init(dev->base, dev->speed, dev->slaveadd, &actual_speed);
896         dev->speed = actual_speed;
897         dev->tick = calc_tick(dev->speed);
898         return 0;
899 }
900
901 static int mvtwsi_i2c_xfer(struct udevice *bus, struct i2c_msg *msg, int nmsgs)
902 {
903         struct mvtwsi_i2c_dev *dev = dev_get_priv(bus);
904         struct i2c_msg *dmsg, *omsg, dummy;
905         u8 *addr_buf_ptr;
906         u8 addr_buf[4];
907         int i;
908
909         memset(&dummy, 0, sizeof(struct i2c_msg));
910
911         /* We expect either two messages (one with an offset and one with the
912          * actual data) or one message (just data or offset/data combined) */
913         if (nmsgs > 2 || nmsgs == 0) {
914                 debug("%s: Only one or two messages are supported.", __func__);
915                 return -1;
916         }
917
918         omsg = nmsgs == 1 ? &dummy : msg;
919         dmsg = nmsgs == 1 ? msg : msg + 1;
920
921         /* We need to swap the register address if its size is > 1 */
922         addr_buf_ptr = &addr_buf[0];
923         for (i = omsg->len; i > 0; i--)
924                 *addr_buf_ptr++ = omsg->buf[i - 1];
925
926         if (dmsg->flags & I2C_M_RD)
927                 return __twsi_i2c_read(dev->base, dmsg->addr, addr_buf,
928                                        omsg->len, dmsg->buf, dmsg->len,
929                                        dev->tick);
930         else
931                 return __twsi_i2c_write(dev->base, dmsg->addr, addr_buf,
932                                         omsg->len, dmsg->buf, dmsg->len,
933                                         dev->tick);
934 }
935
936 static const struct dm_i2c_ops mvtwsi_i2c_ops = {
937         .xfer           = mvtwsi_i2c_xfer,
938         .probe_chip     = mvtwsi_i2c_probe_chip,
939         .set_bus_speed  = mvtwsi_i2c_set_bus_speed,
940 };
941
942 static const struct udevice_id mvtwsi_i2c_ids[] = {
943         { .compatible = "marvell,mv64xxx-i2c", },
944         { .compatible = "marvell,mv78230-i2c", },
945         { .compatible = "allwinner,sun4i-a10-i2c", },
946         { .compatible = "allwinner,sun6i-a31-i2c", },
947         { /* sentinel */ }
948 };
949
950 U_BOOT_DRIVER(i2c_mvtwsi) = {
951         .name = "i2c_mvtwsi",
952         .id = UCLASS_I2C,
953         .of_match = mvtwsi_i2c_ids,
954         .bind = mvtwsi_i2c_bind,
955         .probe = mvtwsi_i2c_probe,
956         .of_to_plat = mvtwsi_i2c_of_to_plat,
957         .priv_auto      = sizeof(struct mvtwsi_i2c_dev),
958         .ops = &mvtwsi_i2c_ops,
959 };
960 #endif /* CONFIG_DM_I2C */