1/*
2 * Copyright 2017, Data61
3 * Commonwealth Scientific and Industrial Research Organisation (CSIRO)
4 * ABN 41 687 119 230.
5 *
6 * This software may be distributed and modified according to the terms of
7 * the BSD 2-Clause license. Note that NO WARRANTY is provided.
8 * See "LICENSE_BSD2.txt" for details.
9 *
10 * @TAG(DATA61_BSD)
11 */
12
13#include <platsupport/i2c.h>
14#include <platsupport/mux.h>
15#include <platsupport/plat/mux.h>
16#include <platsupport/clock.h>
17#include <utils/util.h>
18#include "../../services.h"
19#include "../../arch/arm/clock.h"
20
21#include <string.h>
22
23#define IMX6_I2C_DEFAULT_FREQ (400 * KHZ)
24
25#define IMX6_I2C1_PADDR 0x021A0000
26#define IMX6_I2C2_PADDR 0x021A4000
27#define IMX6_I2C3_PADDR 0x021A8000
28
29#define IMX6_I2CX_SIZE  0x1000
30#define IMX6_I2C1_SIZE  IMX6_I2CX_SIZE
31#define IMX6_I2C2_SIZE  IMX6_I2CX_SIZE
32#define IMX6_I2C3_SIZE  IMX6_I2CX_SIZE
33
34struct imx6_i2c_regs {
35#define I2CADDR(x)         (((x) & 0xff) * BIT(0))
36#define I2CADDR_MASK       I2CADDR(0xff)
37    uint16_t address;
38    uint16_t res0;
39    /* Can't find a pattern here for the divider... May need a look up table */
40    uint16_t div;
41    uint16_t res1;
42#define I2CCON_ENABLE      BIT(7)
43#define I2CCON_IRQ_ENABLE  BIT(6)
44#define I2CCON_MASTER      BIT(5)
45#define I2CCON_TXEN        BIT(4)
46#define I2CCON_ACK_EN      BIT(3)
47#define I2CCON_RSTART      BIT(2)
48    uint16_t control;
49    uint16_t res2;
50#define I2CSTAT_XFER       BIT(7)
51#define I2CSTAT_IAAS       BIT(6)
52#define I2CSTAT_BUSY       BIT(5)
53#define I2CSTAT_ARBLOST    BIT(4)
54#define I2CSTAT_SLAVETX    BIT(2)
55#define I2CSTAT_IRQ_PEND   BIT(1)
56#define I2CSTAT_NAK        BIT(0)
57    uint16_t status;
58    uint16_t res3;
59#define I2CDATA(x)           (((x) & 0xff) * BIT(0))
60#define I2CDATA_MASK         I2CDATA(0xff)
61#define I2CDATA_READ(addr)   I2CDATA(((addr) & 0xfe) | 1)
62#define I2CDATA_WRITE(addr)  I2CDATA(((addr) & 0xfe) | 0)
63    uint16_t data;
64    uint16_t res4;
65};
66
67struct i2c_bus_priv {
68    volatile struct imx6_i2c_regs* regs;
69    char* rx_buf;
70    int rx_count;
71    int rx_len;
72    const char* tx_buf;
73    int tx_count;
74    int tx_len;
75    int mode_tx;
76
77    i2c_callback_fn cb;
78    void* token;
79
80    mux_feature_t mux;
81    enum clock_gate clk_gate;
82    struct clock clock;
83};
84
85/********************
86 *** I2C clocking ***
87 ********************/
88
89static struct i2c_bus_priv*
90i2c_clk_get_priv(clk_t* clk) {
91    return (struct i2c_bus_priv*)clk->priv;
92}
93
94/* Well this is annoying... Is there a magical algorigm that can be used to
95 * build this table? */
96static const int _i2c_div_map[64] = {
97    30,   32,   36,   42,   48,   52,   60,   72,   80,   88,  104,  128,  144,
98    160,  192,  240,  288,  320,  384,  480,  576,  640,  768,  960, 1152, 1280,
99    1536, 1920, 2304, 2560, 3072, 3840,   22,   24,   26,   28,   32,   36,   40,
100    44,   48,   56,   64,   72,   80,   96,  112,  128,  160,  192,  224,  256,
101    320,  384,  448,  512,  640,  768,  896, 1024, 1280, 1536, 1792, 2048
102};
103
104static int
105_i2c_prescale_decode(int div)
106{
107    int error = 0xffff;
108    int match;
109    int i;
110    /* By default, just choose the lowest frequency */
111    match = 0;
112    /* Scan for a prescaler which minimizes error */
113    for (i = 0; i < sizeof(_i2c_div_map) / sizeof(*_i2c_div_map); i++) {
114        int this_error;
115        this_error = _i2c_div_map[i] - div;
116        /* Absolute error value */
117        if (this_error < 0) {
118            this_error *= -1;
119        }
120        /* Update prescale value, early exit if exact match */
121        if (this_error == 0) {
122            return i;
123        } else if (this_error < error) {
124            error = this_error;
125            match = i;
126        }
127    }
128    return match;
129}
130
131static clk_t*
132_i2c_clk_init(clk_t* clk)
133{
134    struct i2c_bus_priv* dev = i2c_clk_get_priv(clk);
135    assert(dev != NULL);
136    if (clk->parent == NULL) {
137        clk_t* parent = clk_get_clock(clk->clk_sys, CLK_PERCLK);
138        assert(parent != NULL);
139        clk_register_child(parent, clk);
140    }
141    clk_set_freq(clk, IMX6_I2C_DEFAULT_FREQ);
142    clk_gate_enable(clk->clk_sys, dev->clk_gate, CLKGATE_ON);
143    return clk;
144}
145
146static freq_t
147_i2c_clk_get_freq(clk_t* clk)
148{
149    freq_t fin = clk_get_freq(clk->parent);
150    struct i2c_bus_priv* dev = i2c_clk_get_priv(clk);
151    int div = _i2c_div_map[dev->regs->div];
152    return fin / div;
153}
154
155static freq_t
156_i2c_clk_set_freq(clk_t* clk, freq_t hz)
157{
158    freq_t fin = clk_get_freq(clk->parent);
159    struct i2c_bus_priv* dev = i2c_clk_get_priv(clk);
160    uint32_t div = fin / hz;
161    assert((div > 22 && div <= 3840) || !"Parent calibration not implemented");
162    dev->regs->div = _i2c_prescale_decode(div);
163    return clk_get_freq(clk);
164}
165
166static void
167_i2c_clk_recal(clk_t* clk)
168{
169    assert(!"IMPLEMENT ME");
170}
171
172/***********************
173 **** Device config ****
174 ***********************/
175
176static struct i2c_bus_priv _i2c[NI2C] = {
177    {
178        .regs = NULL,
179        .mux = MUX_I2C1,
180        .clk_gate = i2c1_serial,
181        .clock = {
182            CLK_OPS_CUSTOM("I2C1", i2c_clk, &_i2c[0])
183        }
184    },
185    {
186        .regs = NULL,
187        .mux = MUX_I2C2,
188        .clk_gate = i2c2_serial,
189        .clock = {
190            CLK_OPS_CUSTOM("I2C2", i2c_clk, &_i2c[1])
191        }
192    },
193    {
194        .regs = NULL,
195        .mux = MUX_I2C3,
196        .clk_gate = i2c3_serial,
197        .clock = {
198            CLK_OPS_CUSTOM("I2C3", i2c_clk, &_i2c[2])
199        }
200    }
201};
202
203/******************
204 **** I2C Core ****
205 ******************/
206
207static inline struct i2c_bus_priv*
208i2c_bus_get_priv(i2c_bus_t* i2c_bus) {
209    return (struct i2c_bus_priv*)i2c_bus->priv;
210}
211
212static inline int
213busy(struct i2c_bus_priv* dev)
214{
215    return !!(dev->regs->status & I2CSTAT_BUSY);
216}
217
218static inline int
219irq_pending(struct i2c_bus_priv* dev)
220{
221    return !!(dev->regs->status & I2CSTAT_IRQ_PEND);
222}
223
224static inline void
225clear_pending(struct i2c_bus_priv* dev)
226{
227    dev->regs->status &= ~(I2CSTAT_IRQ_PEND);
228}
229
230static inline int
231acked(struct i2c_bus_priv* dev)
232{
233    return !(dev->regs->status & I2CSTAT_NAK);
234}
235
236static inline void
237master_stop(struct i2c_bus_priv* dev)
238{
239    /* Send stop signal */
240    dev->regs->control &= ~I2CCON_MASTER;
241    /* Wait for idle bus */
242    while (busy(dev));
243    /* Disable the bus */
244    dev->regs->control &= ~(I2CCON_MASTER | I2CCON_TXEN      |
245                            I2CCON_ENABLE | I2CCON_IRQ_ENABLE);
246}
247
248static void
249master_start(struct i2c_bus_priv* dev, char addr)
250{
251    /* Enable the bus */
252    dev->regs->control |= I2CCON_ENABLE | I2CCON_IRQ_ENABLE;
253    while (busy(dev));
254    /* Enter master TX mode */
255    dev->regs->control |= I2CCON_MASTER | I2CCON_TXEN;
256    while (!busy(dev));
257    clear_pending(dev);
258    /* Write slave address */
259    dev->regs->data = addr;
260}
261
262static void
263internal_slave_init(struct i2c_bus_priv* dev, char addr)
264{
265    dev->regs->address = addr;
266    /* Enable the bus */
267    dev->regs->control |= I2CCON_ENABLE | I2CCON_IRQ_ENABLE;
268    while (busy(dev));
269    /* Enter slave mode TX mode */
270    dev->regs->control &= ~I2CCON_MASTER;
271}
272
273static void
274imx6_i2c_handle_irq(i2c_bus_t* i2c_bus)
275{
276    struct i2c_bus_priv* dev;
277    dev = i2c_bus_get_priv(i2c_bus);
278    if (irq_pending(dev)) {
279        /* Clear IF */
280        clear_pending(dev);
281        /* Master Mode? */
282        if (dev->regs->control & I2CCON_MASTER) {
283            if (dev->regs->control & I2CCON_TXEN) {
284                /** Master TX **/
285                if (!acked(dev)) {
286                    /* RXAK != 0 */
287                    ZF_LOGD("NACK from slave");
288                    master_stop(dev);
289                } else if (dev->mode_tx && dev->tx_count == dev->tx_len) {
290                    /* Last byte transmitted successfully */
291                    master_stop(dev);
292                } else if (!dev->mode_tx) {
293                    /* End of address cycle for master RX */
294                    dev->regs->control &= ~I2CCON_TXEN;
295                    (void)dev->regs->data;
296                    dev->rx_count = 0;
297                } else {
298                    /* Write next byte */
299                    dev->regs->data = *dev->tx_buf++;
300                    dev->tx_count++;
301                }
302            } else {
303                /** Master RX **/
304                if (dev->rx_count < dev->rx_len) {
305                    if (dev->rx_count + 2 == dev->rx_len) {
306                        /* Second last byte to be read: Generate NACK */
307                        dev->regs->control |= I2CCON_ACK_EN;
308                    }
309                    if (dev->rx_count + 1 == dev->rx_len) {
310                        /* Last byte to be read: Generate stop */
311                        dev->regs->control &= ~I2CCON_MASTER;
312                    }
313                    *dev->rx_buf++ = dev->regs->data;
314                    dev->rx_count++;
315                    if (dev->rx_count == dev->rx_len) {
316                        /* Transfer complete */
317                        master_stop(dev);
318                    }
319                } else {
320                    ZF_LOGD("Master RX IRQ but RX complete!");
321                }
322            }
323        } else {
324            /* Slave mode */
325        }
326    }
327}
328
329static inline void
330master_txstart(struct i2c_bus_priv* dev, int slave)
331{
332    master_start(dev, I2CDATA_WRITE(slave));
333}
334
335static inline void
336master_rxstart(struct i2c_bus_priv* dev, int slave)
337{
338    master_start(dev, I2CDATA_READ(slave));
339}
340
341static int
342imx6_i2c_read(i2c_bus_t* i2c_bus, void* data, size_t len, UNUSED bool send_stop, i2c_callback_fn cb, void* token)
343{
344    ZF_LOGF("Not implemented");
345    return -1;
346}
347
348static int
349imx6_i2c_write(i2c_bus_t* i2c_bus, const void* data, size_t len, UNUSED bool send_stop, i2c_callback_fn cb, void* token)
350{
351    ZF_LOGF("Not implemented");
352    return -1;
353}
354
355static int
356imx6_i2c_master_stop(i2c_bus_t* i2c_bus)
357{
358    ZF_LOGF("Not implemented");
359    return -1;
360}
361
362static int
363imx6_i2c_start_write(i2c_slave_t* sl,
364                     const void* vdata, size_t len,
365                     UNUSED bool end_with_repeat_start,
366                     i2c_callback_fn cb, void* token)
367{
368    struct i2c_bus_priv* dev;
369
370    assert(sl != NULL && sl->bus != NULL);
371
372    dev = i2c_bus_get_priv(sl->bus);
373    ZF_LOGD("Writing %d bytes to slave@0x%02x", len, sl->address);
374    master_txstart(dev, sl->address);
375
376    dev->tx_count = 0;
377    dev->tx_buf = (const char*)vdata;
378    dev->tx_len = len;
379    dev->mode_tx = 1;
380    dev->cb = cb;
381    dev->token = token;
382
383    if (cb == NULL) {
384        while (busy(dev)) {
385            i2c_handle_irq(sl->bus);
386        }
387        return dev->tx_count;
388    } else {
389        return len;
390    }
391}
392
393static int
394imx6_i2c_start_read(i2c_slave_t* sl,
395                    void* vdata, size_t len,
396                    UNUSED bool end_with_repeat_start,
397                    i2c_callback_fn cb, void* token)
398{
399    struct i2c_bus_priv* dev;
400
401    assert(sl != NULL && sl->bus != NULL);
402
403    dev = i2c_bus_get_priv(sl->bus);
404    ZF_LOGD("Reading %d bytes from slave@0x%02x", len, sl->address);
405    if (sl->address == dev->regs->address) {
406        return -1;
407    }
408    master_rxstart(dev, sl->address);
409
410    dev->rx_count = -1;
411    dev->rx_buf = (char*)vdata;
412    dev->rx_len = len;
413    dev->mode_tx = 0;
414    dev->cb = cb;
415    dev->token = token;
416
417    if (cb == NULL) {
418        while (busy(dev)) {
419            i2c_handle_irq(sl->bus);
420        }
421        return dev->rx_count;
422    } else {
423        return len;
424    }
425}
426
427static int
428imx6_i2c_set_address(i2c_bus_t* i2c_bus, int addr)
429{
430    struct i2c_bus_priv* dev;
431    dev = i2c_bus_get_priv(i2c_bus);
432
433    internal_slave_init(dev, addr);
434    return 0;
435}
436
437void
438imx6_i2c_register_slave_event_handler(i2c_bus_t *bus,
439                                      i2c_aas_callback_fn cb, void *token)
440{
441    assert(bus != NULL);
442    bus->aas_cb = cb;
443    bus->aas_token = token;
444}
445
446static const uint32_t i2c_speed_freqs[] = {
447    [I2C_SLAVE_SPEED_STANDARD] = 100000,
448    [I2C_SLAVE_SPEED_FAST] = 400000,
449    [I2C_SLAVE_SPEED_FASTPLUS] = 1000000,
450    [I2C_SLAVE_SPEED_HIGHSPEED] = 3400000
451};
452
453static long
454imx6_i2c_set_speed(i2c_bus_t* i2c_bus, enum i2c_slave_speed speed)
455{
456    struct i2c_bus_priv* dev;
457
458    if (speed < I2C_SLAVE_SPEED_STANDARD || speed > I2C_SLAVE_SPEED_HIGHSPEED) {
459        ZF_LOGE("imx6: I2C: Unsupported speed %d.", speed);
460        return -1;
461    }
462
463    dev = i2c_bus_get_priv(i2c_bus);
464    /* "speed" is validated in the library code in arch_include/i2c.h. */
465    return clk_set_freq(&dev->clock, i2c_speed_freqs[speed]);
466}
467
468int
469imx6_i2c_slave_init(i2c_bus_t* i2c_bus, int address,
470                    enum i2c_slave_address_size address_size,
471                    enum i2c_slave_speed max_speed,
472                    uint32_t flags,
473                    i2c_slave_t* sl)
474{
475    assert(sl != NULL);
476
477    if (address_size == I2C_SLAVE_ADDR_7BIT) {
478        address = i2c_extract_address(address);
479    }
480
481    sl->address = address;
482    sl->address_size = address_size;
483    sl->max_speed = max_speed;
484    sl->i2c_opts = flags;
485    sl->bus = i2c_bus;
486
487    sl->slave_read      = &imx6_i2c_start_read;
488    sl->slave_write     = &imx6_i2c_start_write;
489
490    return 0;
491}
492
493int
494i2c_init(enum i2c_id id, ps_io_ops_t* io_ops, i2c_bus_t* i2c)
495{
496    struct i2c_bus_priv* dev = _i2c + id;
497    int err;
498    clk_t* i2c_clk;
499    /* Map memory */
500    ZF_LOGD("Mapping i2c %d\n", id);
501    switch (id) {
502    case I2C1:
503        MAP_IF_NULL(io_ops, IMX6_I2C1, dev->regs);
504        break;
505    case I2C2:
506        MAP_IF_NULL(io_ops, IMX6_I2C2, dev->regs);
507        break;
508    case I2C3:
509        MAP_IF_NULL(io_ops, IMX6_I2C3, dev->regs);
510        break;
511    default :
512        return -1;
513    }
514    /* Check that our memory was mapped */
515    if (dev->regs == NULL) {
516        return -2;
517    }
518
519    /* Configure MUX */
520    err = mux_feature_enable(&io_ops->mux_sys, dev->mux, MUX_DIR_NOT_A_GPIO);
521    if (err) {
522        assert(!"Failed to configure I2C mux");
523        return -1;
524    }
525
526    /* Init clock */
527    dev->clock.clk_sys = &io_ops->clock_sys;
528    i2c_clk = clk_init(&dev->clock);
529    if (i2c_clk == NULL) {
530        assert(!"Failed to initialise I2C clock");
531        return -1;
532    }
533    /* I2C setup */
534    dev->regs->control &= ~(I2CCON_ENABLE | I2CCON_TXEN);
535    dev->regs->address = 0x00;
536    dev->regs->control = I2CCON_ACK_EN;
537
538    i2c->read        = imx6_i2c_read;
539    i2c->write       = imx6_i2c_write;
540    i2c->set_speed   = imx6_i2c_set_speed;
541    i2c->set_self_slave_address = imx6_i2c_set_address;
542    i2c->register_slave_event_handler = imx6_i2c_register_slave_event_handler;
543    i2c->master_stop = imx6_i2c_master_stop;
544    i2c->handle_irq  = imx6_i2c_handle_irq;
545    i2c->priv        = (void*)dev;
546    i2c->slave_init  = imx6_i2c_slave_init;
547    return 0;
548}
549