Remove the PIO config from the clkout_on() function.
[dtplug] / drivers / i2c.c
1 /****************************************************************************
2  *   drivers/i2c.c
3  *
4  *
5  * Copyright 2012 Nathael Pajani <nathael.pajani@ed3l.fr>
6  *
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  *
21  *************************************************************************** */
24 /**************************************************************************** */
25 /*                      I2C                                                   */
26 /**************************************************************************** */
28 /* I2C driver for the I2C bus integrated module of the LPC176x.
29  * Refer to LPC176x documentation (UM10360.pdf) for more information.
30  */
32 #include <stdint.h>
34 #include "core/lpc_regs_17xx.h"
35 #include "core/lpc_core_cm3.h"
36 #include "core/system.h"
37 #include "lib/string.h"
38 #include "drivers/i2c.h"
41 /*
42  * I2C Bus structure
43  *
44  * clock : current i2c clock.
45  * state : global state of the i2c engine.
46  * master_status : status returned by i2c block as found in "status" register.
47  *
48  * repeated_start_restart : This buffer, if used, must have the SAME size as out_buff.
49  *           Then, instead of simply moving to the next byte, the corresponding condition
50  *           will be executed : I2C_CONT, I2C_DO_REPEATED_START, I2C_DO_STOP_START or I2C_STOP.
51  * restart_after_addr : Can be used instead of repeated_start_restart buffer to perform a
52  *           single repeated start or stop/start sequence after first adress got sent.
53  * restart_after_data : Can be used instead of repeated_start_restart buffer to perform a
54  *           single repeated start or stop/start sequence after given data byte.
55  */
56 struct i2c_bus {
57         struct lpc_i2c* regs;
58         uint8_t irq;
59         uint8_t pclk_bit;
60         uint32_t power_bit;
61         uint32_t clock;
62         volatile uint32_t state;
63         volatile uint32_t master_status;
64         volatile uint32_t slave_status;
65         volatile uint32_t timeout;
67         volatile const char* out_buff;
68         volatile const char* repeated_start_restart;
69         volatile uint32_t write_length;
70         volatile uint32_t write_index;
71         volatile uint32_t restart_after_addr;
72         volatile uint32_t restart_after_data;
74         volatile char* in_buff;
75         volatile uint32_t read_length;
76         volatile uint32_t read_index;
77 };
80 /* FIXME : Handle multiple I2C busses ! */
81 static struct i2c_bus i2c_buses[3] = {
82         {
83                 .regs = (struct lpc_i2c*)LPC_I2C0,
84                 .irq = I2C0_IRQ,
85                 .power_bit = LPC_I2C0_POWER_ON,
86                 .pclk_bit = LPC_I2C0_PCLK,
87                 .state = I2C_OK,
88         },
89         {
90                 .regs = (struct lpc_i2c*)LPC_I2C1,
91                 .irq = I2C1_IRQ,
92                 .power_bit = LPC_I2C1_POWER_ON,
93                 .pclk_bit = LPC_I2C1_PCLK,
94                 .state = I2C_OK,
95         },
96         {
97                 .regs = (struct lpc_i2c*)LPC_I2C2,
98                 .irq = I2C2_IRQ,
99                 .power_bit = LPC_I2C2_POWER_ON,
100                 .pclk_bit = LPC_I2C2_PCLK,
101                 .state = I2C_OK,
102         },
103 };
106 /* FIXME : Should add a field "what to do on addr NACK" to i2c_bus structure, and use
107    it with the timeout to create a retry mechanism */
108 /* FIXME : For case 58 ... What would be the use of a restart ?? perform periodic reads ? */
109 /* FIXME : Implement Slave when arbitration lost ? */
113 /* I2C Interrupt handler */
114 /* Actual version will stop on NACKs */
115 /* See LPC1764 user's manual UM10360 on page 457 (19.9.5) for details on I2C State machine */
116 void I2C_Handler(struct i2c_bus* i2c)
118         uint8_t status;
120         i2c->timeout = 0;
122         /* this handler deals with master read and master write only */
123         status = (i2c->regs->status & 0xFF);
124         i2c->master_status = status; /* Store current status */
126         /* I2C State Machine ! */
127         switch (status) {
129         /* All modes */
130                 case 0x00: /* Bus Error. Enter not addressed Slave mode and release bus. */
131                         i2c->regs->ctrl_set = (I2C_ASSERT_ACK | I2C_STOP_FLAG);
132                         i2c->state = I2C_BUS_ERROR;
133                         break;
134                 case 0x08:  /* A START condition has been transmitted. */
135                         i2c->write_index = 0;
136                         if (i2c->write_length != 0) {
137                                 /* Send Slave Address (SLA)
138                                  * Depending on R/W bit, Master Receive or master Transmit mode will be enterred. */
139                                 i2c->regs->data = i2c->out_buff[i2c->write_index++];
140                                 i2c->regs->ctrl_clear = I2C_START_FLAG;
141                         } else {
142                                 i2c->regs->ctrl_clear = I2C_START_FLAG;
143                                 i2c->regs->ctrl_set = I2C_STOP_FLAG;
144                                 i2c->state = I2C_NO_DATA;
145                         }
146                         break;
147                 case 0x10:  /* A repeated START has been transmitted. */
148                         /* Setting read_index to 0 is usefull only if next data byte is
149                          *    Slave Address + Read (SLA + R), but it's OK if we perform a write too, and
150                          *    is necessary for read with a null data length used to probe for devices.
151                          */
152                         i2c->read_index = 0;
153                         /* Send Slave Address and Read/Write bit (SLA + R/W)
154                          * Depending on R/W bit, Master Receive or master Transmit mode will be enterred. */
155                         i2c->regs->data = i2c->out_buff[i2c->write_index++];
156                         /* FIXME : Shouldn't this be done only in receiver mode (SLA + R) ? */
157                         i2c->regs->ctrl_clear = I2C_START_FLAG;
158                         break;
159                 case 0x38: /* Arbitration lost. We don't deal with multiple master situation */
160                         /* FIXME : We have two option :
161                          *  - do nothing, which will release the bus. Will lead to "Not Addressed Slave" state.
162                          *      This options allows handling of multiple master topologies.
163                          *  - Set start flag, and a start condition will be transmitted when bus becomes free.
164                          */
165                         /* We choose to do nothing, we ARE the true master after all ! */
166                         i2c->state = I2C_ARBITRATION_LOST;
167                         break;
169         /* Master Transmitter Mode Only */
170                 case 0x18:  /* Address + Write transmitted and ACK'ed */
171                         if (i2c->write_length == 1) { /* Nothing more to send, we must stop. */
172                                 /* This one is used to probe devices, or wait for completion */
173                                 i2c->regs->ctrl_set = I2C_STOP_FLAG;
174                                 i2c->state = I2C_NO_DATA;
175                         } else {
176                                 uint32_t condition = i2c->restart_after_addr;
177                                 if (i2c->repeated_start_restart)
178                                         condition = i2c->repeated_start_restart[i2c->write_index - 1];
179                                 switch (condition) {
180                                         case I2C_CONT: /* Send next data byte */
181                                                 i2c->regs->data = i2c->out_buff[i2c->write_index++];
182                                                 break;
183                                         case I2C_DO_REPEATED_START: /* Send repeated start condition */
184                                                 i2c->regs->ctrl_set = I2C_START_FLAG;
185                                                 break;
186                                         case I2C_DO_STOP_START: /* Send STOP / START condition */
187                                                 i2c->regs->ctrl_set = I2C_STOP_FLAG | I2C_START_FLAG;
188                                                 break;
189                                         case I2C_STOP: /* Send STOP condition */
190                                                 i2c->regs->ctrl_set = I2C_STOP_FLAG;
191                                                 i2c->state = I2C_NO_DATA;
192                                                 break;
193                                 }
194                                 if (i2c->restart_after_addr)
195                                         i2c->restart_after_addr = 0; /* This one must be defused once used */
196                         }
197                         break;
198                 case 0x20:  /* NACK on Address + Write (SLA + W) */
199                 case 0x30:  /* NACK on Data byte */
200                         /* FIXME : We have three other options : Resend / Repeated START / STOP + START
201                          *     If I'm right, Resend would require moving write_index back and using same data
202                          *     Repeated START ? ignore the NACK and move to reading data ?
203                          *     STOP + START ? Start over ? write_index will be set to 0 in I2C_STARTED case (0x08)
204                          * Sending a STOP condition will end transactions and let the driver take the decision.
205                          */
206                         i2c->regs->ctrl_set = I2C_STOP_FLAG;
207                         i2c->state = I2C_NACK;
208                         break;
209                 case 0x28: /* Data byte has been transmitted and ACK received */
210                         if (i2c->write_index < i2c->write_length) {
211                                 /* More to write, but what do we do ? */
212                                 uint32_t condition = I2C_CONT;
213                                 if (i2c->restart_after_data == i2c->write_index)
214                                         condition = I2C_DO_REPEATED_START;
215                                 else if (i2c->repeated_start_restart)
216                                         condition = i2c->repeated_start_restart[i2c->write_index - 1];
217                                 switch (condition) {
218                                         case I2C_CONT: /* Send next data byte */
219                                                 i2c->regs->data = i2c->out_buff[i2c->write_index++];
220                                                 break;
221                                         case I2C_DO_REPEATED_START: /* Send repeated start condition */
222                                                 i2c->regs->ctrl_set = I2C_START_FLAG;
223                                                 break;
224                                         case I2C_DO_STOP_START: /* Send STOP / START condition */
225                                                 i2c->regs->ctrl_set = I2C_STOP_FLAG | I2C_START_FLAG;
226                                                 break;
227                                         case I2C_STOP: /* Send STOP condition */
228                                                 /* Hey, why sending a STOP and terminate communication if we are not at
229                                                  * the end of the write buffer ?? */
230                                                 i2c->regs->ctrl_set = I2C_STOP_FLAG;
231                                                 i2c->state = I2C_OK;
232                                                 break;
233                                 }
234                         } else {
235                                 if (i2c->read_length != 0) { /* Anything to read ? */
236                                         i2c->regs->ctrl_set = I2C_START_FLAG;
237                                 } else {
238                                         i2c->regs->ctrl_set = I2C_STOP_FLAG;
239                                         i2c->state = I2C_OK;
240                                 }
241                         }
242                         break;
244         /* Master Receiver Mode Only */
245                 case 0x40:  /* Address + Read transmitted and ACK'ed */
246                         if ((i2c->read_index + 1) < i2c->read_length) {
247                                 /* Will go to State 0x50 (assert ACK after data is received) */
248                                 i2c->regs->ctrl_set = I2C_ASSERT_ACK;
249                         } else {
250                                 /* Will go to State 0x58 (NACK after data is received) */
251                                 i2c->regs->ctrl_clear = I2C_ASSERT_ACK;
252                         }
253                         break;
255                 case 0x48:  /* NACK on Address + Read (SLA + R) */
256                         /* FIXME : We have two other options : Repeated START / STOP + START */
257                         i2c->regs->ctrl_set = I2C_STOP_FLAG;
258                         i2c->state = I2C_NACK;
259                         break;
261                 case 0x50: /* Data byte has been received and ACK sent */
262                         i2c->in_buff[i2c->read_index++] = i2c->regs->data;
263                         if ((i2c->read_index + 1) < i2c->read_length) {
264                                 /* assert ACK after data is received, requesting next Data from slave */
265                                 i2c->regs->ctrl_set = I2C_ASSERT_ACK;
266                         } else {
267                                 /* Assert NACK on last byte, telling the slave to stop transmitting data
268                                    and release the I2C Bus */
269                                 i2c->regs->ctrl_clear = I2C_ASSERT_ACK;
270                         }
271                         break;
273                 case 0x58: /* Data byte has been received and NACK "sent" */
274                         /* This tells the slave it was the last byte. We should be done. */
275                         i2c->in_buff[i2c->read_index++] = i2c->regs->data;
276                         /* FIXME : We have two other options : Repeated START or STOP + START,
277                          *    but what for ? periodic reads ? */
278                         i2c->regs->ctrl_set = I2C_STOP_FLAG;
279                         i2c->state = I2C_OK;
280                         break;
282                 default:
283                         i2c->state = I2C_ERROR_UNKNOWN;
284                         break;
285         }
287         /* Clear interrupt flag. This has to be done last. */
288         i2c->regs->ctrl_clear = I2C_INTR_FLAG;
289         return;
292 void I2C_0_Handler(void)
294         I2C_Handler(&(i2c_buses[0]));
296 void I2C_1_Handler(void)
298         I2C_Handler(&(i2c_buses[1]));
300 void I2C_2_Handler(void)
302         I2C_Handler(&(i2c_buses[2]));
306 /***************************************************************************** */
307 /*                        I2C access                                           */
308 /***************************************************************************** */
309 static int i2c_perform_data_transfer(struct i2c_bus* i2c)
311         int ret = 0;
313         /* Start the process */
314         i2c->state = I2C_BUSY;
315         i2c->regs->ctrl_set = I2C_START_FLAG;
316         /* Wait for process completion */
317         do {} while (i2c->state == I2C_BUSY);  /* FIXME : OS should schedule here */
319         /* Handle returned state (errors or OK) */
320         switch (i2c->state) {
321                 case I2C_OK:
322                 case I2C_NO_DATA:
323                         /* Return 0 : success */
324                         break;
325                 case I2C_NACK:
326                         ret = -EREMOTEIO;
327                         break;
328                 case I2C_ARBITRATION_LOST:
329                         ret = -EBUSY;
330                         break;
331                 case I2C_BUS_ERROR: /* This one is bad ... */
332                 case I2C_ERROR_UNKNOWN:
333                 default:
334                         ret = -EIO;
335                         break;
336         }
338         /* Force device to release the bus :
339          *    send a START followed by a STOP (initiate transmission with nul write_length) */
340         i2c->state = I2C_BUSY;
341         i2c->write_length = 0;
342         i2c->regs->ctrl_set = I2C_START_FLAG;
343         do {} while (i2c->state == I2C_BUSY); /* FIXME : OS should schedule here */
344         i2c->state = I2C_OK;
346         return ret;
349 /* Read
350  * Performs a non-blocking read on the module's i2c bus.
351  *   bus_num : I2C bus number to use.
352  *   cmd_buf : buffer containing all control byte to be sent on the i2c bus
353  *   cmd_size : size of the cmd_buf command buffer
354  *   ctrl_buf : buffer containing action to be done after sending, like repeated START conditions
355  *         if not NULL, ctrl_buf has the same size as cmd_buf
356  *   inbuff : the buffer where read data will be put. May be NULL if count is 0.
357  *   count : the number of bytes to be read.
358  * RETURN VALUE
359  *   Upon successfull completion, returns the number of bytes read. On error, returns a negative
360  *   integer equivalent to errors from glibc.
361  *   -EBADFD : Device not initialized (-77)
362  *   -EBUSY : Device or ressource Busy or Arbitration lost (-16)
363  *   -EAGAIN : Device already in use (-11)
364  *   -EINVAL : Invalid argument (no cmd_buf, or no inbuff when count > 0) (-22)
365  *   -EREMOTEIO : Device did not acknowledge (-121)
366  *   -EIO : Bad one: Illegal start or stop, or illegal state in i2c state machine (-5)
367  */
368 int i2c_read(uint8_t bus_num, const void *cmd_buf, size_t cmd_size, const void* ctrl_buf, void* inbuff, size_t count)
370         int ret = 0;
371         struct i2c_bus* i2c = NULL;
373         if (bus_num >= NB_I2C_BUSSES) {
374                 return -EINVAL;
375         }
376         i2c = &(i2c_buses[bus_num]);
378         /* Checks */
379         if (i2c->clock == 0)
380                 return -EBADFD;
381         if (cmd_buf == NULL)
382                 return -EINVAL;
383         if ((inbuff == NULL) && (count > 0))
384                 return -EINVAL;
386         if (i2c->state == I2C_BUSY) {
387                 return -EBUSY;
388         }
389         if (i2c->state != I2C_OK) {
390                 /* What should we do ??? someone failed to reset status ? */
391         }
393         /* Set up mod_i2c for read operation */
394         /* command (write) buffer */
395         i2c->out_buff = cmd_buf;
396         i2c->write_length = cmd_size;
397         /* control buffer, if any. Note that it's the only way to control
398          *   operations on modules i2C bus to simplify the interface */
399         i2c->repeated_start_restart = ctrl_buf;
400         i2c->restart_after_addr = I2C_CONT;
401         i2c->restart_after_data = 0;
402         /* read buffer */
403         i2c->in_buff = inbuff;
404         i2c->read_length = count;
405         i2c->read_index = 0;
407         ret = i2c_perform_data_transfer(i2c);
408         if (ret == 0) {
409                 return i2c->read_index;
410         } else {
411                 return ret;
412         }
415 /* Write
416  * Performs a non-blocking write on the module's i2c bus.
417  *   bus_num : I2C bus number to use.
418  *   buf : buffer containing all byte to be sent on the i2c bus,
419  *         including conrtol bytes (address, offsets, ...)
420  *   count : the number of bytes to be sent, including address bytes and so on.
421  *   ctrl_buf : buffer containing action to be done after sending, like repeated START conditions
422  *         FIXME : note that STOP + START conditions are not allowed, the STOP would lead to sending
423  *         the first bytes of buf, creating an infinite loop.
424  * RETURN VALUE
425  *   Upon successfull completion, returns the number of bytes written. On error, returns a negative
426  *   integer equivalent to errors from glibc.
427  *   -EBADFD : Device not initialized
428  *   -EBUSY : Device or ressource Busy or Arbitration lost
429  *   -EAGAIN : Device already in use
430  *   -EINVAL : Invalid argument (buf)
431  *   -EREMOTEIO : Device did not acknowledge
432  *   -EIO : Bad one: Illegal start or stop, or illegal state in i2c state machine
433  */
434 int i2c_write(uint8_t bus_num, const void *buf, size_t count, const void* ctrl_buf)
436         int ret = 0;
437         struct i2c_bus* i2c = NULL;
439         if (bus_num >= NB_I2C_BUSSES) {
440                 return -EINVAL;
441         }
442         i2c = &(i2c_buses[bus_num]);
444         /* Checks */
445         if (i2c->clock == 0)
446                 return -EBADFD;
447         if (buf == NULL)
448                 return -EINVAL;
450         if (i2c->state == I2C_BUSY) {
451                 return -EBUSY;
452         }
453         if (i2c->state != I2C_OK) {
454                 /* What should we do ??? someone failed to reset status ? */
455         }
457         /* Clear read information to prevent entering master receiver states */
458         i2c->read_length = 0;
459         i2c->in_buff = NULL;
460         i2c->state = I2C_BUSY;
461         /* Set up mod_i2c for write operation */
462         i2c->out_buff = buf;
463         i2c->write_length = count;
464         /* control buffer, if any. Note that it's the only way to control
465          *   operations on modules i2C bus to simplify the interface */
466         i2c->restart_after_addr = I2C_CONT;
467         i2c->repeated_start_restart = ctrl_buf;
468         i2c->restart_after_data = 0;
470         ret = i2c_perform_data_transfer(i2c);
471         if (ret == 0) {
472                 return count;
473         } else {
474                 return ret;
475         }
480 /***************************************************************************** */
481 /*                I2C Init                                                     */
482 /***************************************************************************** */
483 static void i2c_clock_on(struct i2c_bus* i2c)
485         uint32_t main_clock = get_main_clock();
486         uint32_t scl_clk = 0;
488         /* Setup I2C clock */
489         scl_clk = (main_clock / i2c->clock);
490         i2c->regs->clk_duty_high = (scl_clk / 2);
491         i2c->regs->clk_duty_low = (scl_clk - i2c->regs->clk_duty_high);
494 /* I2C on / off
495  *   bus_num : I2C bus number to use.
496  *   i2c_clk_freq : I2C clock freqeuncy in Hz
497  */
498 int i2c_on(uint8_t bus_num, uint32_t i2c_clk_freq)
500         struct i2c_bus* i2c = NULL;
502         if (bus_num >= NB_I2C_BUSSES) {
503                 return -EINVAL;
504         }
505         i2c = &(i2c_buses[bus_num]);
507         NVIC_DisableIRQ(i2c->irq);
508         /* Power on I2C block */
509         subsystem_power(i2c->power_bit, 1);
510         
511         /* Set CCLK divider for PCLK */
512         set_subsystem_clk_divider(i2c->pclk_bit, LPC_PCLK_CCLK);
513         /* Set clock */
514         i2c->clock = i2c_clk_freq;
515         i2c_clock_on(i2c);
516         /* Enable I2C */
517         /* FIXME: if enabling slave functions, add I2C_ASSERT_ACK flag */
518         i2c->regs->ctrl_set = (I2C_ENABLE_FLAG);
519         /* And enable interrupts */
520         NVIC_EnableIRQ(i2c->irq);
522         return 0;
525 int i2c_off(uint8_t bus_num)
527         struct i2c_bus* i2c = NULL;
529         if (bus_num >= NB_I2C_BUSSES) {
530                 return -EINVAL;
531         }
532         i2c = &(i2c_buses[bus_num]);
533         
534         NVIC_DisableIRQ(i2c->irq);
535         subsystem_power(i2c->power_bit, 0);
536         i2c->clock = 0;
538         return 0;
541 /* Allow system to propagate main clock */
542 void i2c_clock_update(void)
544         int i = 0;
546         for (i = 0; i < NB_I2C_BUSSES; i++) {
547                 if (i2c_buses[i].clock != 0) {
548                 /* FIXME : we should stop I2C transfers, disable I2C interrupts and stop I2C clock. */
549                         i2c_clock_on(&(i2c_buses[i]));
550                 }
551         }