DISABLE_IRQSAVE/ENABLE_IRQRESTORE: Convert to IRQ_SAVE_DISABLE/IRQ_RESTORE.
[bertos.git] / drv / eeprom.c
1 /*!
2  * \file
3  * <!--
4  * Copyright 2003, 2004 Develer S.r.l. (http://www.develer.com/)
5  * This file is part of DevLib - See devlib/README for information.
6  * -->
7  *
8  * \brief Driver for the 24xx16 and 24xx256 I2C EEPROMS (implementation)
9  *
10  * \note This implementation is AVR specific.
11  *
12  * \version $Id$
13  * \author Stefano Fedrigo <aleph@develer.com>
14  * \author Bernardo Innocenti <bernie@develer.com>
15  */
16
17 /*#*
18  *#* $Log$
19  *#* Revision 1.14  2004/12/13 12:07:06  bernie
20  *#* DISABLE_IRQSAVE/ENABLE_IRQRESTORE: Convert to IRQ_SAVE_DISABLE/IRQ_RESTORE.
21  *#*
22  *#* Revision 1.13  2004/11/16 20:58:51  bernie
23  *#* Add write verify.
24  *#*
25  *#* Revision 1.12  2004/11/02 17:50:01  bernie
26  *#* CONFIG_EEPROM_VERIFY: New config option.
27  *#*
28  *#* Revision 1.11  2004/10/26 08:35:31  bernie
29  *#* Reset watchdog for long operations.
30  *#*
31  *#* Revision 1.10  2004/09/20 03:31:22  bernie
32  *#* Sanitize for C++.
33  *#*
34  *#* Revision 1.9  2004/09/14 21:03:46  bernie
35  *#* Use debug.h instead of kdebug.h.
36  *#*
37  *#* Revision 1.8  2004/08/25 14:12:08  rasky
38  *#* Aggiornato il comment block dei log RCS
39  *#*
40  *#* Revision 1.7  2004/08/24 16:48:40  bernie
41  *#* Note reason for including <macros.h>
42  *#*
43  *#* Revision 1.6  2004/08/24 14:27:20  bernie
44  *#* Doxygen fix.
45  *#*
46  *#* Revision 1.5  2004/08/24 13:46:48  bernie
47  *#* Include <macros.h>.
48  *#*
49  *#* Revision 1.4  2004/08/10 06:57:22  bernie
50  *#* eeprom_erase(): New function.
51  *#*
52  *#* Revision 1.3  2004/07/29 22:57:09  bernie
53  *#* Add 24LC16 support.
54  *#*
55  *#* Revision 1.2  2004/07/22 01:24:43  bernie
56  *#* Document AVR dependency.
57  *#*
58  *#* Revision 1.1  2004/07/20 17:11:18  bernie
59  *#* Import into DevLib.
60  *#*
61  *#*/
62
63 #include "eeprom.h"
64
65 #include <drv/wdt.h>
66 #include <mware/byteorder.h> /* cpu_to_be16() */
67 #include <debug.h>
68 #include <hw.h>
69 #include <cpu.h>     // IRQ_SAVE_DISABLE(), IRQ_RESTORE()
70 #include <config.h>  // CONFIG_EEPROM_VERIFY
71 #include <macros.h>  // MIN()
72
73 #include <string.h>  // memset()
74
75 #include <avr/twi.h>
76
77 // Configuration sanity checks
78 #if !defined(CONFIG_EEPROM_VERIFY) || (CONFIG_EEPROM_VERIFY != 0 && CONFIG_EEPROM_VERIFY != 1)
79         #error CONFIG_EEPROM_VERIFY must be defined to either 0 or 1
80 #endif
81
82
83 /* Wait for TWINT flag set: bus is ready */
84 #define WAIT_TWI_READY  do {} while (!(TWCR & BV(TWINT)))
85
86 /*! \name EEPROM control codes */
87 /*@{*/
88 #define SLA_W  0xA0
89 #define SLA_R  0xA1
90 /*@}*/
91
92
93 /*!
94  * Send START condition on the bus.
95  *
96  * \return true on success, false otherwise.
97  */
98 static bool twi_start(void)
99 {
100         TWCR = BV(TWINT) | BV(TWSTA) | BV(TWEN);
101         WAIT_TWI_READY;
102
103         if (TW_STATUS == TW_START || TW_STATUS == TW_REP_START)
104                 return true;
105
106         DB(kprintf("!TW_(REP)START: %x\n", TWSR);)
107         return false;
108 }
109
110
111 /*!
112  * Send START condition and select slave for write.
113  *
114  * \return true on success, false otherwise.
115  */
116 static bool twi_start_w(uint8_t slave_addr)
117 {
118         ASSERT(slave_addr < 8);
119
120         /*
121          * Loop on the select write sequence: when the eeprom is busy
122          * writing previously sent data it will reply to the SLA_W
123          * control byte with a NACK.  In this case, we must
124          * keep trying until the eeprom responds with an ACK.
125          */
126         while (twi_start())
127         {
128                 TWDR = SLA_W | (slave_addr << 1);
129                 TWCR = BV(TWINT) | BV(TWEN);
130                 WAIT_TWI_READY;
131
132                 if (TW_STATUS == TW_MT_SLA_ACK)
133                         return true;
134                 else if (TW_STATUS != TW_MT_SLA_NACK)
135                 {
136                         DB(kprintf("!TW_MT_SLA_(N)ACK: %x\n", TWSR);)
137                         break;
138                 }
139         }
140
141         return false;
142 }
143
144
145 /*!
146  * Send START condition and select slave for read.
147  *
148  * \return true on success, false otherwise.
149  */
150 static bool twi_start_r(uint8_t slave_addr)
151 {
152         ASSERT(slave_addr < 8);
153
154         if (twi_start())
155         {
156                 TWDR = SLA_R | (slave_addr << 1);
157                 TWCR = BV(TWINT) | BV(TWEN);
158                 WAIT_TWI_READY;
159
160                 if (TW_STATUS == TW_MR_SLA_ACK)
161                         return true;
162
163                 DB(kprintf("!TW_MR_SLA_ACK: %x\n", TWSR);)
164         }
165
166         return false;
167 }
168
169
170 /*!
171  * Send STOP condition.
172  */
173 static void twi_stop(void)
174 {
175         TWCR = BV(TWINT) | BV(TWEN) | BV(TWSTO);
176 }
177
178
179 /*!
180  * Send a sequence of bytes in master transmitter mode
181  * to the selected slave device through the TWI bus.
182  *
183  * \return true on success, false on error.
184  */
185 static bool twi_send(const void *_buf, size_t count)
186 {
187         const uint8_t *buf = (const uint8_t *)_buf;
188
189         while (count--)
190         {
191                 TWDR = *buf++;
192                 TWCR = BV(TWINT) | BV(TWEN);
193                 WAIT_TWI_READY;
194                 if (TW_STATUS != TW_MT_DATA_ACK)
195                 {
196                         DB(kprintf("!TW_MT_DATA_ACK: %x\n", TWSR);)
197                         return false;
198                 }
199         }
200
201         return true;
202 }
203
204
205 /*!
206  * Receive a sequence of one or more bytes from the
207  * selected slave device in master receive mode through
208  * the TWI bus.
209  *
210  * Received data is placed in \c buf.
211  *
212  * \return true on success, false on error
213  */
214 static bool twi_recv(void *_buf, size_t count)
215 {
216         uint8_t *buf = (uint8_t *)_buf;
217
218         /*
219          * When reading the last byte the TWEA bit is not
220          * set, and the eeprom should answer with NACK
221          */
222         while (count--)
223         {
224                 TWCR = BV(TWINT) | BV(TWEN) | (count ? BV(TWEA) : 0);
225                 WAIT_TWI_READY;
226
227                 if (count)
228                 {
229                         if (TW_STATUS != TW_MR_DATA_ACK)
230                         {
231                                 DB(kprintf("!TW_MR_DATA_ACK: %x\n", TWSR);)
232                                 return false;
233                         }
234                 }
235                 else
236                 {
237                         if (TW_STATUS != TW_MR_DATA_NACK)
238                         {
239                                 DB(kprintf("!TW_MR_DATA_NACK: %x\n", TWSR);)
240                                 return false;
241                         }
242                 }
243                 *buf++ = TWDR;
244         }
245
246         return true;
247 }
248
249 /*!
250  * Copy \c count bytes from buffer \c buf to
251  * eeprom at address \c addr.
252  */
253 static bool eeprom_writeRaw(e2addr_t addr, const void *buf, size_t count)
254 {
255         bool result = true;
256         ASSERT(addr + count <= EEPROM_SIZE);
257
258         while (count && result)
259         {
260                 /*
261                  * Split write in multiple sequential mode operations that
262                  * don't cross page boundaries.
263                  */
264                 size_t size =
265                         MIN(count, (size_t)(EEPROM_BLKSIZE - (addr & (EEPROM_BLKSIZE - 1))));
266
267         #if CONFIG_EEPROM_TYPE == EEPROM_24XX16
268                 /*
269                  * The 24LC16 uses the slave address as a 3-bit
270                  * block address.
271                  */
272                 uint8_t blk_addr = (uint8_t)((addr >> 8) & 0x07);
273                 uint8_t blk_offs = (uint8_t)addr;
274
275                 result =
276                         twi_start_w(blk_addr)
277                         && twi_send(&blk_offs, sizeof blk_offs)
278                         && twi_send(buf, size);
279
280         #elif CONFIG_EEPROM_TYPE == EEPROM_24XX256
281
282                 // 24LC256 wants big-endian addresses
283                 uint16_t addr_be = cpu_to_be16(addr);
284
285                 result =
286                         twi_start_w(0)
287                         && twi_send((uint8_t *)&addr_be, sizeof addr_be)
288                         && twi_send(buf, size);
289
290         #else
291                 #error Unknown device type
292         #endif
293
294                 twi_stop();
295
296                 // DEBUG
297                 //kprintf("addr=%d, count=%d, size=%d, *#?=%d\n",
298                 //      addr, count, size,
299                 //      (EEPROM_BLKSIZE - (addr & (EEPROM_BLKSIZE - 1)))
300                 //);
301
302                 /* Update count and addr for next operation */
303                 count -= size;
304                 addr += size;
305                 buf = ((const char *)buf) + size;
306         }
307
308         if (!result)
309                 TRACEMSG("Write error!");
310         return result;
311 }
312
313
314 #if CONFIG_EEPROM_VERIFY
315 /*!
316  * Check that the contents of an EEPROM range
317  * match with a provided data buffer.
318  *
319  * \return true on success.
320  */
321 static bool eeprom_verify(e2addr_t addr, const void *buf, size_t count)
322 {
323         uint8_t verify_buf[16];
324         bool result = true;
325
326         while (count && result)
327         {
328                 /* Split read in smaller pieces */
329                 size_t size = MIN(count, sizeof verify_buf);
330
331                 /* Read back buffer */
332                 if (eeprom_read(addr, verify_buf, size))
333                 {
334                         if (memcmp(buf, verify_buf, size) != 0)
335                         {
336                                 TRACEMSG("Data mismatch!");
337                                 result = false;
338                         }
339                 }
340                 else
341                 {
342                         TRACEMSG("Read error!");
343                         result = false;
344                 }
345
346                 /* Update count and addr for next operation */
347                 count -= size;
348                 addr += size;
349                 buf = ((const char *)buf) + size;
350         }
351
352         return result;
353 }
354 #endif /* CONFIG_EEPROM_VERIFY */
355
356
357 bool eeprom_write(e2addr_t addr, const void *buf, size_t count)
358 {
359 #if CONFIG_EEPROM_VERIFY
360         int retries = 5;
361
362         while (retries--)
363                 if (eeprom_writeRaw(addr, buf, count)
364                                 && eeprom_verify(addr, buf, count))
365                         return true;
366
367         return false;
368
369 #else /* !CONFIG_EEPROM_VERIFY */
370         return eeprom_writeRaw(addr, buf, count);
371 #endif /* !CONFIG_EEPROM_VERIFY */
372 }
373
374
375 /*!
376  * Copy \c count bytes at address \c addr
377  * from eeprom to RAM to buffer \c buf.
378  *
379  * \return true on success.
380  */
381 bool eeprom_read(e2addr_t addr, void *buf, size_t count)
382 {
383         ASSERT(addr + count <= EEPROM_SIZE);
384
385 #if CONFIG_EEPROM_TYPE == EEPROM_24XX16
386         /*
387          * The 24LC16 uses the slave address as a 3-bit
388          * block address.
389          */
390         uint8_t blk_addr = (uint8_t)((addr >> 8) & 0x07);
391         uint8_t blk_offs = (uint8_t)addr;
392
393         bool res =
394                 twi_start_w(blk_addr)
395                 && twi_send(&blk_offs, sizeof blk_offs)
396                 && twi_start_r(blk_addr)
397                 && twi_recv(buf, count);
398
399 #elif CONFIG_EEPROM_TYPE == EEPROM_24XX256
400
401         // 24LC256 wants big-endian addresses
402         addr = cpu_to_be16(addr);
403
404         bool res =
405                 twi_start_w(0)
406                 && twi_send((uint8_t *)&addr, sizeof(addr))
407                 && twi_start_r(0)
408                 && twi_recv(buf, count);
409 #else
410         #error Unknown device type
411 #endif
412
413         twi_stop();
414
415         if (!res)
416                 TRACEMSG("Read error!");
417         return res;
418 }
419
420
421 /*!
422  * Write a single character \a c at address \a addr.
423  */
424 bool eeprom_write_char(e2addr_t addr, char c)
425 {
426         return eeprom_write(addr, &c, 1);
427 }
428
429
430 /*!
431  * Read a single character at address \a addr.
432  *
433  * \return the requested character or -1 in case of failure.
434  */
435 int eeprom_read_char(e2addr_t addr)
436 {
437         char c;
438
439         if (eeprom_read(addr, &c, 1))
440                 return c;
441         else
442                 return -1;
443 }
444
445
446 /*!
447  * Erase specified part of eeprom, writing 0xFF.
448  *
449  * \param addr   starting address
450  * \param count  length of block to erase
451  */
452 void eeprom_erase(e2addr_t addr, size_t count)
453 {
454         uint8_t buf[EEPROM_BLKSIZE];
455         memset(buf, 0xFF, sizeof buf);
456
457         // Clear all but struct hw_info at start of eeprom
458         while (count)
459         {
460                 // Long operation, reset watchdog
461                 wdt_reset();
462
463                 size_t size = MIN(count, sizeof buf);
464                 eeprom_write(addr, buf, size);
465                 addr += size;
466                 count -= size;
467         }
468 }
469
470
471 /*!
472  * Initialize TWI module.
473  */
474 void eeprom_init(void)
475 {
476         cpuflags_t flags;
477         IRQ_SAVE_DISABLE(flags);
478
479         /*
480          * This is pretty useless according to AVR's datasheet,
481          * but it helps us driving the TWI data lines on boards
482          * where the bus pull-up resistors are missing.  This is
483          * probably due to some unwanted interaction between the
484          * port pin and the TWI lines.
485          */
486 #if defined(__AVR_ATmega64__)
487         PORTD |= BV(PD0) | BV(PD1);
488         DDRD |= BV(PD0) | BV(PD1);
489 #elif defined(__AVR_ATmega8__)
490         PORTC |= BV(PC4) | BV(PC5);
491         DDRC |= BV(PC4) | BV(PC5);
492 #else
493         #error Unsupported architecture
494 #endif
495
496         /*
497          * Set speed:
498          * F = CLOCK_FREQ / (16 + 2*TWBR * 4^TWPS)
499          */
500         #define TWI_FREQ  100000  /* ~100 kHz */
501         #define TWI_PRESC 1       /* 4 ^ TWPS */
502
503         TWBR = (CLOCK_FREQ / (2 * TWI_FREQ * TWI_PRESC)) - (8 / TWI_PRESC);
504         TWSR = 0;
505         TWCR = BV(TWEN);
506
507         IRQ_RESTORE(flags);
508 }
509
510
511 #ifdef _DEBUG
512
513 #include <string.h>
514
515 void eeprom_test(void)
516 {
517         static const char magic[14] = "Humpty Dumpty";
518         char buf[sizeof magic];
519         size_t i;
520
521         // Write something to EEPROM using unaligned sequential writes
522         for (i = 0; i < 42; ++i)
523                 eeprom_write(i * sizeof magic, magic, sizeof magic);
524
525         // Read back with single-byte reads
526         for (i = 0; i < 42 * sizeof magic; ++i)
527         {
528                 eeprom_read(i, buf, 1);
529                 kprintf("EEPROM byte read: %c (%d)\n", buf[0], buf[0]);
530                 ASSERT(buf[0] == magic[i % sizeof magic]);
531         }
532
533         // Read back again using sequential reads
534         for (i = 0; i < 42; ++i)
535         {
536                 memset(buf, 0, sizeof buf);
537                 eeprom_read(i * sizeof magic, buf, sizeof magic);
538                 kprintf("EEPROM seq read @ 0x%x: '%s'\n", i * sizeof magic, buf);
539                 ASSERT(memcmp(buf, magic, sizeof magic) == 0);
540         }
541 }
542
543 #endif // _DEBUG