7240fccad00bd4601d109be524553131d7196cd2
[bertos.git] / bertos / drv / eeprom.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2003, 2004, 2005 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \brief Driver for the 24xx16 and 24xx256 I2C EEPROMS (implementation)
34  *
35  * \author Stefano Fedrigo <aleph@develer.com>
36  * \author Bernie Innocenti <bernie@codewiz.org>
37  */
38
39 #include "eeprom.h"
40
41 #warning TODO:Test and complete this module for arm platform.
42 #if !CPU_ARM
43
44 #include <cfg/macros.h>  // MIN()
45 #include <cfg/debug.h>
46 #include <cfg/module.h>  // MOD_CHECK()
47
48 #include <cpu/attr.h>
49 #include <drv/i2c.h>
50
51 #include <drv/wdt.h>
52
53 #include <cpu/byteorder.h> // cpu_to_be16()
54
55 #include <string.h>  // memset()
56
57 /**
58  * EEPROM ID code
59  */
60 #define EEPROM_ID  0xA0
61
62 /**
63  * This macros form the correct slave address for EEPROMs
64  */
65 #define EEPROM_ADDR(x) (EEPROM_ID | (((uint8_t)((x) & 0x07)) << 1))
66
67
68 /**
69  * Array used to describe EEPROM memory devices currently supported.
70  */
71 static const EepromInfo mem_info[] =
72 {
73         {
74                 /* 24XX16 */
75                 .has_dev_addr = false,
76                 .blk_size = 0x10,
77                 .e2_size = 0x800,
78         },
79         {
80                 /* 24XX256 */
81                 .has_dev_addr = true,
82                 .blk_size = 0x40,
83                 .e2_size = 0x8000,
84         },
85         {
86                 /* 24XX512 */
87                 .has_dev_addr = true,
88                 .blk_size = 0x80,
89                 .e2_size = 0x10000,
90         },
91         /* Add other memories here */
92 };
93
94 STATIC_ASSERT(countof(mem_info) == EEPROM_CNT);
95
96
97 /**
98  * Copy \a size bytes from buffer \a buf to
99  * eeprom.
100  */
101 static size_t eeprom_writeRaw(struct KFile *_fd, const void *buf, size_t size)
102 {
103         Eeprom *fd = EEPROM_CAST(_fd);
104         e2dev_addr_t dev_addr;
105         uint8_t addr_buf[2];
106         uint8_t addr_len;
107         size_t wr_len = 0;
108
109         e2blk_size_t blk_size = mem_info[fd->type].blk_size;
110
111         STATIC_ASSERT(countof(addr_buf) <= sizeof(e2addr_t));
112
113         /* clamp size to memory limit (otherwise may roll back) */
114         ASSERT(_fd->seek_pos + size <= (kfile_off_t)_fd->size);
115         size = MIN((kfile_off_t)size, _fd->size - _fd->seek_pos);
116
117         if (mem_info[fd->type].has_dev_addr)
118         {
119                 dev_addr = fd->addr;
120                 addr_len = 2;
121         }
122         else
123         {
124                 dev_addr = (e2dev_addr_t)((fd->fd.seek_pos >> 8) & 0x07);
125                 addr_len = 1;
126         }
127
128         while (size)
129         {
130                 /*
131                  * Split write in multiple sequential mode operations that
132                  * don't cross page boundaries.
133                  */
134                 size_t count = MIN(size, (size_t)(blk_size - (fd->fd.seek_pos & (blk_size - 1))));
135
136                 if (mem_info[fd->type].has_dev_addr)
137                 {
138                         addr_buf[0] = (fd->fd.seek_pos >> 8) & 0xFF;
139                         addr_buf[1] = (fd->fd.seek_pos & 0xFF);
140                 }
141                 else
142                 {
143                         dev_addr = (e2dev_addr_t)((fd->fd.seek_pos >> 8) & 0x07);
144                         addr_buf[0] = (fd->fd.seek_pos & 0xFF);
145                 }
146
147
148                 if (!(i2c_start_w(EEPROM_ADDR(dev_addr))
149                         && i2c_send(addr_buf, addr_len)
150                         && i2c_send(buf, count)))
151                 {
152                         i2c_stop();
153                         return wr_len;
154                 }
155
156                 i2c_stop();
157
158                 /* Update count and addr for next operation */
159                 size -= count;
160                 fd->fd.seek_pos += count;
161                 buf = ((const char *)buf) + count;
162                 wr_len += count;
163         }
164
165         return wr_len;
166 }
167
168 /**
169  * Copy \a size bytes from buffer \a _buf to
170  * eeprom.
171  * \note Writes are verified and if buffer content
172  *       is not matching we retry 5 times max.
173  */
174 static size_t eeprom_writeVerify(struct KFile *_fd, const void *_buf, size_t size)
175 {
176         Eeprom *fd = EEPROM_CAST(_fd);
177         int retries = 5;
178         size_t wr_len = 0;
179
180         while (retries--)
181         {
182                 wr_len = eeprom_writeRaw(_fd, _buf, size);
183                 /* rewind to verify what we have just written */
184                 kfile_seek(_fd, -(kfile_off_t)wr_len, KSM_SEEK_CUR);
185                 if (wr_len == size
186                  && eeprom_verify(fd, _buf, wr_len))
187                 {
188                         /* Forward to go after what we have written*/
189                         kfile_seek(_fd, wr_len, KSM_SEEK_CUR);
190                         return wr_len;
191                 }
192         }
193         return wr_len;
194 }
195
196
197 /**
198  * Copy \a size bytes
199  * from eeprom to RAM to buffer \a _buf.
200  *
201  * \return the number of bytes read.
202  */
203 static size_t eeprom_read(struct KFile *_fd, void *_buf, size_t size)
204 {
205         Eeprom *fd = EEPROM_CAST(_fd);
206         uint8_t addr_buf[2];
207         uint8_t addr_len;
208         size_t rd_len = 0;
209         uint8_t *buf = (uint8_t *)_buf;
210
211         STATIC_ASSERT(countof(addr_buf) <= sizeof(e2addr_t));
212
213         /* clamp size to memory limit (otherwise may roll back) */
214         ASSERT(_fd->seek_pos + size <= (kfile_off_t)_fd->size);
215         size = MIN((kfile_off_t)size, _fd->size - _fd->seek_pos);
216
217         e2dev_addr_t dev_addr;
218         if (mem_info[fd->type].has_dev_addr)
219         {
220                 dev_addr = fd->addr;
221                 addr_len = 2;
222                 addr_buf[0] = (fd->fd.seek_pos >> 8) & 0xFF;
223                 addr_buf[1] = (fd->fd.seek_pos & 0xFF);
224         }
225         else
226         {
227                 dev_addr = (e2dev_addr_t)((fd->fd.seek_pos >> 8) & 0x07);
228                 addr_len = 1;
229                 addr_buf[0] = (fd->fd.seek_pos & 0xFF);
230         }
231
232
233         if (!(i2c_start_w(EEPROM_ADDR(dev_addr))
234            && i2c_send(addr_buf, addr_len)
235            && i2c_start_r(EEPROM_ADDR(dev_addr))))
236         {
237                 i2c_stop();
238                 return 0;
239         }
240
241         while (size--)
242         {
243                 /*
244                  * The last byte read does not have an ACK
245                  * to stop communication.
246                  */
247                 int c = i2c_get(size);
248
249                 if (c == EOF)
250                         break;
251
252                 *buf++ = c;
253                 fd->fd.seek_pos++;
254                 rd_len++;
255         }
256
257         i2c_stop();
258         return rd_len;
259 }
260
261 /**
262  * Check that the contents of an EEPROM range
263  * match with a provided data buffer.
264  *
265  * \return true on success.
266  * \note Seek position of \a fd will not change.
267  */
268 bool eeprom_verify(Eeprom *fd, const void *buf, size_t count)
269 {
270         uint8_t verify_buf[16];
271         bool result = true;
272
273         /* Save seek position */
274         kfile_off_t prev_seek = fd->fd.seek_pos;
275
276         while (count && result)
277         {
278                 /* Split read in smaller pieces */
279                 size_t size = MIN(count, sizeof verify_buf);
280
281                 /* Read back buffer */
282                 if (eeprom_read(&fd->fd, verify_buf, size))
283                 {
284                         if (memcmp(buf, verify_buf, size) != 0)
285                         {
286                                 TRACEMSG("Data mismatch!");
287                                 result = false;
288                         }
289                 }
290                 else
291                 {
292                         TRACEMSG("Read error!");
293                         result = false;
294                 }
295
296                 /* Update count and addr for next operation */
297                 count -= size;
298                 buf = ((const char *)buf) + size;
299         }
300
301         /* Restore previous seek position */
302         fd->fd.seek_pos = prev_seek;
303         return result;
304 }
305
306 /**
307  * Erase specified part of eeprom, writing 0xFF.
308  *
309  * \a addr   starting address
310  * \a count  length of block to erase
311  * \note Seek position is unchanged.
312  * \return true if ok, false otherwise.
313  */
314 bool eeprom_erase(Eeprom *fd, e2addr_t addr, e2_size_t count)
315 {
316         e2blk_size_t blk_size = mem_info[fd->type].blk_size;
317         uint8_t buf[blk_size];
318         kfile_off_t prev_off = fd->fd.seek_pos;
319         bool res = true;
320         size_t size;
321
322         memset(buf, 0xFF, blk_size);
323
324
325         kfile_seek(&fd->fd, addr, KSM_SEEK_SET);
326
327         /*
328          * Optimization: this first write id used to realign
329          * current address to block boundaries.
330          */
331
332         wdt_reset();
333         size = MIN(count, (e2_size_t)(blk_size - (addr & (blk_size - 1))));
334         if (kfile_write(&fd->fd, buf, size) != size)
335         {
336                 fd->fd.seek_pos = prev_off;
337                 return false;
338         }
339         count -= size;
340
341         /* Clear all */
342         while (count)
343         {
344                 /* Long operation, reset watchdog */
345                 wdt_reset();
346
347                 size = MIN(count, (e2_size_t)sizeof buf);
348                 if (kfile_write(&fd->fd, buf, size) != size)
349                 {
350                         res = false;
351                         break;
352                 }
353
354                 count -= size;
355         }
356         fd->fd.seek_pos = prev_off;
357         return res;
358 }
359
360
361 /**
362  * Initialize EEPROM module.
363  * \a fd is the Kfile context.
364  * \a type is the eeprom device we want to initialize (\see EepromType)
365  * \a addr is the i2c devide address (usually pins A0, A1, A2).
366  * \a verify is true if you want that every write operation will be verified.
367  */
368 void eeprom_init(Eeprom *fd, EepromType type, e2dev_addr_t addr, bool verify)
369 {
370         MOD_CHECK(i2c);
371         ASSERT(type < EEPROM_CNT);
372
373         memset(fd, 0, sizeof(*fd));
374         DB(fd->fd._type = KFT_EEPROM);
375
376         fd->type = type;
377         fd->addr = addr;
378         fd->fd.size = mem_info[fd->type].e2_size;
379
380         // Setup eeprom programming functions.
381         fd->fd.read = eeprom_read;
382         if (verify)
383                 fd->fd.write = eeprom_writeVerify;
384         else
385                 fd->fd.write = eeprom_writeRaw;
386         fd->fd.close = kfile_genericClose;
387
388         fd->fd.seek = kfile_genericSeek;
389 }
390
391 #endif