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#pragma once
14
15#include <stdint.h>
16
17#include <utils/util.h>
18#include <platsupport/io.h>
19
20typedef struct i2c_bus i2c_bus_t;
21#include <platsupport/plat/i2c.h>
22
23/* For bit banged API */
24#include <platsupport/gpio.h>
25
26/***********
27 *** BUS ***
28 ***********/
29
30/* Make sure to remember to SHL these constants by 1 when passing them
31 * in as arguments to `i2c_slave_init()`, etc.
32 */
33/* General call must be sent out as a WRITE transaction. */
34#define I2C_ADDR_GENERAL_CALL           0
35/* Start byte must be sent out as a READ transaction. */
36#define I2C_ADDR_BITBANG_START_BYTE     I2C_ADDR_GENERAL_CALL,
37#define I2C_ADDR_CBUS                   1
38#define I2C_ADDR_HISPEED_MASTER         0x4
39/* Device-ID must be sent out first as a WRITE, then as a READ. */
40#define I2C_ADDR_DEVICE_ID              0x3C
41#define I2C_ADDR_10BIT                  0x38,
42
43/* Use this macro to check whether or not an i2cstat value is an error value */
44#define I2CSTAT_IS_ERROR(i2cstat)       ((i2cstat) < 0)
45/* Use this macro to check whether or not an i2cstat value is NOT an error value */
46#define I2CSTAT_OK(i2cstat)             (((i2cstat) == I2CSTAT_COMPLETE) || ((i2cstat) == I2CSTAT_LASTBYTE))
47/* Use this to check whether or not an i2c transfer has been fully completed successfully */
48#define I2CSTAT_COMPLETE(i2cstat)       ((i2cstat) == I2CSTAT_COMPLETE)
49
50enum i2c_stat {
51/// Transfer completed successfully
52    I2CSTAT_COMPLETE = 0,
53/// The last byte is about to be transfered. Call read/write if you wish to extend it.
54    I2CSTAT_LASTBYTE,
55/// Transfer was truncated or cancelled by the remote
56    I2CSTAT_INCOMPLETE = INT_MIN,
57/// A transfer error occurred
58    I2CSTAT_ERROR,
59/// The transfer was aborted by the user
60    I2CSTAT_CANCELLED,
61/// The slave sent NACK instead of ACK.
62    I2CSTAT_NACK,
63/// The slave lost its arbitration bid on the bus and the xfer must be retried.
64    I2CSTAT_ARBITRATION_LOST
65};
66
67enum i2c_mode {
68/// Idle
69    I2CMODE_IDLE,
70/// Receive mode
71    I2CMODE_RX,
72/// Transmit mode
73    I2CMODE_TX
74};
75
76enum i2c_slave_address_size {
77    I2C_SLAVE_ADDR_7BIT,
78    I2C_SLAVE_ADDR_10BIT,
79};
80
81enum i2c_slave_speed {
82    I2C_SLAVE_SPEED_STANDARD,
83    I2C_SLAVE_SPEED_FAST,
84    I2C_SLAVE_SPEED_FASTPLUS,
85    I2C_SLAVE_SPEED_HIGHSPEED
86};
87
88/** Values for i2c_slave_t::i2c_opts.
89 *
90 * Pass these values to i2c_slave_init()'s "i2c_opts" argument.
91 */
92/* If a slave device doesn't send ACK after each byte, set this flag in its
93 * slave data structure.
94 */
95#define I2C_SLAVE_OPTS_DEVICE_DOES_NOT_ACK     BIT(0)
96enum kvfmt {
97    BIG64    = -8,
98    BIG32    = -4,
99    BIG16    = -2,
100    BIG8     = -1,
101    STREAM   =  0,
102    LITTLE8  = +1,
103    LITTLE16 = +2,
104    LITTLE32 = +4,
105    LITTLE64 = +8
106};
107
108/* I2C addresses in the ranges 0x0-0x7 are reserved.
109 * I2C addresses in the ranges 0x78-0x7F are also reserved.
110 */
111#define I2C_VALID_ADDR_MIN      (0x8)
112#define I2C_VALID_ADDR_MAX      (0x78)
113
114static inline bool i2c_is_valid_address(uint8_t id)
115{
116    return id >= I2C_VALID_ADDR_MIN && id < I2C_VALID_ADDR_MAX;
117}
118
119static inline int i2c_extract_address(uint8_t id_with_rw_bit)
120{
121    return (id_with_rw_bit >> 1) & 0x7F;
122}
123
124/**
125 * This callback is called when the I2C bus is addressed as a slave. The application
126 * should respond by calling i2c_read or i2c_write with an appropriate transfer buffer
127 * depending on the reported i2c_mode.
128 */
129typedef void (*i2c_aas_callback_fn)(i2c_bus_t *bus, enum i2c_mode, void *token);
130/**
131 * This callback is called when a transfer needs attention.
132 * It will be called if the transfer is interrupted, just before the last byte is
133 * transferred, and also when the transfer has completed. The catalyse for the call
134 * to the callback is reported in i2c_stat.
135 * If the I2C buffer for the transfer is not contiguous, the I2CSTAT_LASTBYTE status
136 * can be used to replace the active transfer buffer and continue the transfer. To
137 * achieve this, simply call i2c_read or i2c_write with a new buffer when the
138 * I2CSTAT_LASTBYTE status callback is received. NOTE that in this case, the last byte
139 * of the original buffer will not take part in the transfer. The reason for this
140 * strange operation is due to the ACK policy of I2C transfers.
141 */
142typedef void (*i2c_callback_fn)(i2c_bus_t *bus, enum i2c_stat, size_t size, void *token);
143
144/** I2C slave controller handle structure.
145 *
146 * You should initialize one of these using i2c_slave_init() or
147 * for each slave controller you intend to communicate with
148 * on the bus.
149 *
150 * Then, use i2c_slave_read() and i2c_slave_write() calls on this handle
151 * structure to communicate with the desired slave controller.
152 */
153typedef struct i2c_slave i2c_slave_t;
154struct i2c_slave {
155    int (*slave_read)(i2c_slave_t *i2c_slave, void *data, size_t size,
156                      bool end_with_repeat_start,
157                      i2c_callback_fn cb, void *token);
158    int (*slave_write)(i2c_slave_t *i2c_slave, const void *data, size_t size,
159                       bool end_with_repeat_start,
160                       i2c_callback_fn cb, void *token);
161
162    i2c_bus_t *bus;
163    int        address;
164    enum i2c_slave_address_size address_size;
165    enum i2c_slave_speed        max_speed;
166    /* This "i2c_opts" member is not meant to be managed directly by the caller,
167     * but it is set internally by the driver based on the "i2c_opts" argument
168     * passed to "i2c_slave_init()".
169     *
170     * Please see the documentation for i2c_slave_init() to understand this
171     * member.
172     */
173    uint32_t   i2c_opts;
174};
175
176/** I2C master controller handle structure.
177 *
178 * You should initialize one of these for each controller you intend to use in
179 * master mode on the bus.
180 */
181struct i2c_bus {
182    /* Master mode functions: To be used when the controller is in master
183     * mode.
184     *
185     * To read and write from/to a target slave in master mode, please see the
186     * i2c_slave_t related API functions further down below.
187     *
188     * You must initialize an i2c_slave_t structure for each slave using the
189     * i2c_slave_init() API function if you will be communicating with slave
190     * devices.
191     *
192     * If you will be using the controller in slave mode, you should register
193     * a slave mode event handler to receive notifications of slave mode events.
194     */
195    int (*slave_init)(i2c_bus_t *i2c_bus, int address,
196                      enum i2c_slave_address_size address_size,
197                      enum i2c_slave_speed max_speed,
198                      uint32_t i2c_opts,
199                      i2c_slave_t *i2c_slave);
200
201    long (*set_speed)(i2c_bus_t *bus, enum i2c_slave_speed speed);
202    /* Bus clear operation, for when the slave holds SDA line low. */
203    int (*master_stop)(i2c_bus_t *bus);
204    void (*set_hsmode_master_address)(i2c_bus_t *bus, int addr);
205    /* Slave mode functions: To be used when the controller is in slave mode. */
206    int (*read)(i2c_bus_t *bus, void *buf, size_t size, bool end_with_repeat_start,
207                i2c_callback_fn cb, void *token);
208    int (*write)(i2c_bus_t *bus, const void *buf, size_t size, bool end_with_repeat_start,
209                 i2c_callback_fn cb, void *token);
210    void (*register_slave_event_handler)(i2c_bus_t *bus,
211                                         i2c_aas_callback_fn cb, void *token);
212
213    int (*set_self_slave_address)(i2c_bus_t *bus, int addr);
214    enum i2c_mode(*probe_aas)(i2c_bus_t *bus);
215
216    void (*handle_irq)(i2c_bus_t *bus);
217
218    i2c_callback_fn cb;
219    void *token;
220    i2c_aas_callback_fn aas_cb;
221    void *aas_token;
222    void *priv;
223};
224
225struct i2c_bb {
226    gpio_id_t scl;
227    gpio_id_t sda;
228    int speed;
229    gpio_sys_t *gpio_sys;
230};
231
232/**
233 * Initialise an I2C bus
234 * @param[in]  id      The id of the I2C bus to initialise
235 * @param[in]  io_ops  A structure providing operations which this device
236 *                     may perform for intialisation.
237 * @param[out] i2c_bus A handle to the i2c bus driver for future calls
238 * @return             0 on success
239 */
240int i2c_init(enum i2c_id id, ps_io_ops_t *io_ops, i2c_bus_t *i2c_bus);
241
242/**
243 * Initialise a bit-banged I2C bus
244 * @param[in]  gpio_sys  A handle to a gpio subsystem. This handle must be valid while the bus is in use
245 * @param[in]  scl       The GPIO ID of the SCL pin
246 * @param[in]  sda       The GPIO ID of the SDA pin
247 * @param[out] i2c_bb    A bit-banged i2c structure to populate. This caller is responsible for managing the memory
248 *                       for this structure. The memory must be valid while the bus is in use.
249 * @param[out] i2c_bus   A generic I2C bus structure to populate
250 * @return               0 on success
251 */
252int i2c_bb_init(gpio_sys_t *gpio_sys, gpio_id_t scl, gpio_id_t sda, struct i2c_bb *i2c_bb, struct i2c_bus *i2c_bus);
253
254/** Initialise an I2C slave device for "stream" reading and writing.
255 *
256 * This is the standard mode of use.
257 * There are functions also provided below for treating I2C slaves as key-value
258 * stores.
259 *
260 * @param[in]  i2c_bus   A handle to the I2C bus that the device resides on
261 * @param[in]  address   The chip address of the slave device. The RW bit of
262 *                       the address should be set to 0.
263 * @param[in]  address_size The I2C hardware address bitlength: 7 or 10 bits.
264 * @param[in]  max_speed    The maximum speed usable with the target slave
265 *                          device. Device speed is one of: Standard, FM, FM+
266 *                          and HS.
267 * @param[out] i2c_slave A handle to an i2c slave device structure to initialise
268 * @return               0 on success
269 *
270 * Values for i2c_slave_t::i2c_opts are #defined below.
271 *
272 * Pass these values to i2c_slave_init()'s "i2c_opts" argument.
273 */
274/* If a slave device doesn't send ACK after each byte, set this flag in its
275 * slave data structure.
276 */
277#define I2C_SLAVE_OPTS_DEVICE_DOES_NOT_ACK     BIT(0)
278
279int i2c_slave_init(i2c_bus_t *i2c_bus, int address,
280                   enum i2c_slave_address_size address_size,
281                   enum i2c_slave_speed max_speed,
282                   uint32_t i2c_opts,
283                   i2c_slave_t *i2c_slave);
284
285typedef struct i2c_kvslave_ {
286    i2c_slave_t *slave;
287    enum kvfmt data_fmt;
288    enum kvfmt address_fmt;
289} i2c_kvslave_t;
290
291/** Initialize an I2C slave device for key-value reading and writing.
292 *
293 * This function and its accompanying library API (i2c_kvslave_read(),
294 * i2c_kvslave_write()) act as a *wrapper* around an already previously
295 * initialized instance of an i2c_slave_t.
296 *
297 * @param[in]  i2c_slave The I2C bus that this device resides on
298 * @param[in]  asize   The address size in bytes
299 *                     Positive values indicate LITTLE_ENDIAN while
300 *                     negative values indicate BIG_ENDIAN.
301 * @param[in]  dsize   The data word size in bytes
302 *                     Positive values indicate LITTLE_ENDIAN while
303 *                     negative values indicate BIG_ENDIAN.
304 * @param[out] i2c_kvslave A slave device structure to initialise
305 * @return             0 on success
306 */
307int i2c_kvslave_init(i2c_slave_t *i2c_slave,
308                     enum kvfmt asize, enum kvfmt dsize,
309                     i2c_kvslave_t *i2c_kvslave);
310
311/**
312 * Set the speed of the I2C bus
313 * @param[in] i2c_bus  A handle to an I2C bus
314 * @param[in] speed    One of the values in i2c_slave_speed: std, fast, fast+,
315 *                     HS.
316 * @return             The actual speed set
317 */
318static inline long i2c_set_speed(i2c_bus_t *i2c_bus, enum i2c_slave_speed speed)
319{
320    ZF_LOGF_IF(!i2c_bus, "Handle to I2C controller not supplied!");
321    ZF_LOGF_IF(!i2c_bus->set_speed, "Unimplemented!");
322    return i2c_bus->set_speed(i2c_bus, speed);
323}
324
325/**
326 * Signal an IRQ event to an I2C bus.
327 * @param[in] i2c_bus The I2C bus that triggered the IRQ
328 */
329static inline void i2c_handle_irq(i2c_bus_t *i2c_bus)
330{
331    ZF_LOGF_IF(!i2c_bus, "Handle to I2C controller not supplied!");
332    ZF_LOGF_IF(!i2c_bus->handle_irq, "Unimplemented!");
333    i2c_bus->handle_irq(i2c_bus);
334}
335
336/** Registers an event handler for slave event notifications.
337 *
338 * Such notifications are usually a mode change from read to write, or from
339 * write to read when the remote master decides to request such a change.
340 *
341 * See i2c_aas_callback_fb above.
342 * @param[in] bus       Initialized I2C bus controller handle.
343 * @param[in] cb        Callback which will be called when there is an I2C event
344 *                      to notify the client application of.
345 * @param[in] token     Client-specific data that the driver returns unchanged.
346 */
347static inline void i2c_register_slave_event_handler(i2c_bus_t *bus,
348                                                    i2c_aas_callback_fn cb, void *token)
349{
350    ZF_LOGF_IF(!bus, "Handle to I2C controller not supplied!");
351    ZF_LOGF_IF(!bus->register_slave_event_handler, "Unimplemented!");
352    bus->register_slave_event_handler(bus, cb, token);
353}
354
355/** Assign slave mode address to the I2C controller.
356 *
357 * Assign an address to the I2C controller which it should respond to when
358 * acting as a slave.
359 *
360 * This function should probably use the I2C General Call procedure, and then
361 * program the new I2C address using some platform-specific configuration,
362 * perhaps via firmware or GPIO.
363 *
364 * @param[in] i2c_bus   A handle to an i2c bus driver
365 * @param[in] addr      The address to assign to this bus. The RW bit of
366 *                      the address should be set to 0.
367 * @return              0 on success
368 */
369static inline int i2c_set_self_slave_address(i2c_bus_t *bus, int addr)
370{
371    ZF_LOGF_IF(!bus, "Handle to I2C controller not supplied!");
372    ZF_LOGF_IF(!bus->set_self_slave_address, "Unimplemented!");
373    ZF_LOGF_IF(!i2c_is_valid_address(i2c_extract_address(addr)), "I2C address "
374               "input is invalid!");
375
376    return bus->set_self_slave_address(bus, addr);
377}
378
379/**
380 * Set the I2C controller's 3-bit master address for high-speed mode. If you
381 * set the speed of the bus to high-speed mode, you should also call this
382 * function to set the HS-master address of the I2C controller.
383 *
384 * @param[in] i2c_bus   A handle to an i2c bus driver
385 * @param[in] addr      The address to assign to this bus. The RW bit of
386 *                      the address should be set to 0.
387 * @param[in] aas_cb    A callback function to call when the slave is addressed
388 * @param[in] aas_token A token to pass, unmodified to the provided callback function
389 */
390static inline void i2c_set_hsmode_master_address(i2c_bus_t *i2c_bus, int addr)
391{
392    ZF_LOGF_IF(!i2c_bus, "Handle to I2C controller not supplied!");
393    ZF_LOGF_IF(!i2c_bus->set_hsmode_master_address, "Unimplemented!");
394    return i2c_bus->set_hsmode_master_address(i2c_bus, addr);
395}
396
397/*** Slave mode ***/
398
399/**
400 * While operating as a slave, read from a remote I2C master
401 * @param[in] i2c_bus A handle to an i2c bus driver
402 * @param[in] data    A address to store the recieved data
403 * @param[in] size    The number of bytes to read
404 * @param[in] cb      A callback to call when the transfer has finished.
405 * @param[in] token   A token to pass unmodified to the registered callback
406 * @return            The number of bytes read
407 */
408static inline int i2c_read(i2c_bus_t *i2c_bus, void *data, size_t size,
409                           bool end_with_repeat_start,
410                           i2c_callback_fn cb, void *token)
411{
412    ZF_LOGF_IF(!i2c_bus, "Handle to I2C controller not supplied!");
413    ZF_LOGF_IF(!i2c_bus->read, "Unimplemented!");
414    return i2c_bus->read(i2c_bus, data, size, end_with_repeat_start, cb, token);
415}
416
417/**
418 * While operating as a slave, write to a remote I2C master
419 * @param[in] i2c_bus A handle to an i2c bus driver
420 * @param[in] data    The address of the data to send
421 * @param[in] size    The number of bytes to send
422 * @param[in] cb      A callback to call when the transfer has finished.
423 * @param[in] token   A token to pass unmodified to the registered callback
424 * @return            The number of bytes sent
425 */
426static inline int i2c_write(i2c_bus_t *i2c_bus, const void *data, size_t size,
427                            bool end_with_repeat_start,
428                            i2c_callback_fn cb, void *token)
429{
430    ZF_LOGF_IF(!i2c_bus, "Handle to I2C controller not supplied!");
431    ZF_LOGF_IF(!i2c_bus->write, "Unimplemented!");
432    return i2c_bus->write(i2c_bus, data, size, end_with_repeat_start, cb, token);
433}
434
435/**
436 * Determine if the I2C bus received the assigned slave address
437 * This function should only be used in polling mode and should be considered to
438 * be edge triggered (mode is only reported at the beginning of a slave transfer).
439 * @param[in] i2c_bus  A handle to the bus to probe
440 * @return             The mode in which the bus was addressed, or I2CMODE_IDLE if
441 *                     the bus was not addressed in the last byte received.
442 */
443static inline enum i2c_mode i2c_probe_aas(i2c_bus_t *i2c_bus)
444{
445    ZF_LOGF_IF(!i2c_bus, "Handle to I2C controller not supplied!");
446    ZF_LOGF_IF(!i2c_bus->probe_aas, "Unimplmented!");
447    return i2c_bus->probe_aas(i2c_bus);
448}
449
450/**
451 * Scan a bus for devices
452 * @param[in]  i2c_bus The I2C bus to scan
453 * @param[in]  start   The address at which to begin the scan.
454 *                     The RW bit of the address should be set to 0.
455 * @param[out] addr    On success, and when the value passed is not NULL,
456 *                     This
457 * @param[in]  naddr   The maximum number of addresses to return. This
458 *                     should be equal to the number of elements in the addr
459 *                     array.
460 * @return             -1 on failure, otherwise, returns the number of addresses
461 *                     that were entered into the addr array.
462 *                     If the return value equals @ref(naddr), one should
463 *                     repeat the call with @ref(start) adjusted appropraitly.
464 */
465int i2c_scan(i2c_bus_t *i2c_bus, int start, int *addr, int naddr);
466
467
468
469/*****************************
470 *** Slave controller APIs ***
471 *****************************/
472
473/**** Key-Value device ****/
474
475/**
476 * Read registers from a register map I2C slave device
477 * The endianess, word size and address size will be considered for the
478 * transfer. Note that this function accepts the number of registers as
479 * an argument rather than the number of bytes. Note also that the data
480 * argument has no type, but is expected to have a type that matches the
481 * word size (ie, int8_t[], int16_t[], int32_t[] or int64_t[])
482 * @param[in] i2c_slave  A handle to a I2C slave device to read from
483 * @param[in] start      The register address to begin reading from
484 * @param[in] data       The address at which to store the read data
485 * @param[in] nregs      The number of registers to read
486 * @return               The actual number of bytes read
487 */
488int i2c_kvslave_read(i2c_kvslave_t *i2c_kvslave, uint64_t start, void *data, int nregs);
489
490/**
491 * Write registers to a register map I2C slave device
492 * The endianess, word size and address size will be considered for the
493 * transfer. Note that this function accepts the number of registers as
494 * an argument rather than the number of bytes. Note also that the data
495 * argument has no type, but is expected to have a type that matches the
496 * word size (ie, int8_t[], int16_t[], int32_t[] or int64_t[])
497 * @param[in] i2c_slave  A handle to a I2C slave device to read from
498 * @param[in] start      The register address to begin reading from
499 * @param[in] data       An address whcih provides the data to be written
500 * @param[in] nregs      The number of registers to write
501 * @return               The actual number of bytes read
502 */
503int i2c_kvslave_write(i2c_kvslave_t *i2c_kvslave, uint64_t start, const void *data, int nregs);
504
505
506/**** Streaming device ****/
507
508/**
509 * Read from a streaming slave device
510 * @param[in] i2c_slave  A handle to the I2C slave device to read from
511 * @param[in] data       A address to read the data to
512 * @param[in] size       The number of bytes to read
513 * @param[in] cb         The callback which is called when write is complete
514 * @param[in] token      The token that the callback returns
515 * @return               The actual number of registers read
516 */
517static inline int i2c_slave_read(i2c_slave_t *i2c_slave, void *data, size_t size,
518                                 bool end_with_repeat_start,
519                                 i2c_callback_fn cb, void *token)
520{
521    ZF_LOGF_IF(!i2c_slave, "Handle to I2C slave info not supplied!");
522    ZF_LOGF_IF(!i2c_slave->bus, "I2C slave's parent bus not filled out!");
523    ZF_LOGF_IF(!i2c_slave->slave_read, "Unimplemented!");
524    return i2c_slave->slave_read(i2c_slave, data, size, end_with_repeat_start,
525                                 cb, token);
526}
527
528/**
529 * Write to a streaming slave device
530 * @param[in] i2c_slave  A handle to the I2C slave device to write to
531 * @param[in] data       The address of the data to be written
532 * @param[in] size       The number of bytes to write
533 * @param[in] cb         The callback which is called when write is complete
534 * @param[in] token      The token that the callback returns
535 * @return               The actual number of registers written
536 */
537static inline int i2c_slave_write(i2c_slave_t *i2c_slave, const void *data, int size,
538                                  bool end_with_repeat_start,
539                                  i2c_callback_fn cb, void *token)
540{
541    ZF_LOGF_IF(!i2c_slave, "Handle to I2C slave info not supplied!");
542    ZF_LOGF_IF(!i2c_slave->bus, "I2C slave's parent bus not filled out!");
543    ZF_LOGF_IF(!i2c_slave->slave_write, "Unimplemented!");
544    return i2c_slave->slave_write(i2c_slave, data, size, end_with_repeat_start,
545                                  cb, token);
546}
547
548
549static inline void i2c_handle_irq_wrapper(void *data, ps_irq_acknowledge_fn_t ack, void *ack_data)
550{
551    assert(data);
552
553    i2c_bus_t *bus = data;
554    i2c_handle_irq(bus);
555
556    int UNUSED error = ack(ack_data);
557    assert(!error);
558}
559