Move avr drivers.
[bertos.git] / cpu / avr / drv / flash_avr.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 2007 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \brief Self programming routines.
34  *
35  * \version $Id$
36  * \author Francesco Sacchi <batt@develer.com>
37  * \author Daniele Basile <asterix@develer.com>
38  *
39  * This module implements a kfile-like access for Atmel avr
40  * internal flash.
41  * Internal flash writing access is controlled by BOOTSZ fuses, check
42  * datasheet for details.
43  */
44
45 #include "flash_avr.h"
46
47 #include <avr/io.h>
48 #include <avr/boot.h>
49 #include <avr/pgmspace.h>
50
51 #include <cfg/macros.h> // MIN()
52 #include <cfg/compiler.h>
53 #include <cfg/debug.h>
54 #include <cpu/cpu.h>
55
56 #include <drv/wdt.h>
57
58 #include <string.h>
59 #include <stdio.h>
60
61 typedef uint16_t avr_page_addr_t;
62 typedef uint16_t avr_page_t;
63
64 /**
65  * Temporary buffer cointaing data block to
66  * write on flash.
67  */
68 static uint8_t page_buf[SPM_PAGESIZE];
69
70 bool page_modified; /// Flag for checking if current page is modified.
71
72 /**
73  * Current buffered page.
74  */
75 static avr_page_t curr_page = 0;
76
77 /**
78  * Write current buffered page in flash memory (if modified).
79  * This function erase flash memory page before writing.
80  */
81 static void flash_avr_flush(void)
82 {
83         if (page_modified)
84         {
85                 kprintf("Flushing page %d\n", curr_page);
86
87                 boot_spm_busy_wait();  // Wait while the SPM instruction is busy.
88
89                 kprintf("Filling temparary page buffer...");
90                 /* Fill the temporary buffer of the AVR */
91                 for (avr_page_addr_t page_addr = 0; page_addr < SPM_PAGESIZE; page_addr += 2)
92                 {
93                         uint16_t word = ((uint16_t)page_buf[page_addr + 1] << 8) | page_buf[page_addr];
94
95                         ATOMIC(boot_page_fill(page_addr, word));
96                 }
97                 kprintf("Done.\n");
98
99                 wdt_reset();
100
101                 kprintf("Erasing page, addr %u...", curr_page * SPM_PAGESIZE);
102
103                 /* Page erase */
104                 ATOMIC(boot_page_erase(curr_page * SPM_PAGESIZE));
105
106                 /* Wait until the memory is erased. */
107                 boot_spm_busy_wait();
108
109                 kprintf("Done.\n");
110                 kprintf("Writing page, addr %u...", curr_page * SPM_PAGESIZE);
111
112                 /* Store buffer in flash page. */
113                 ATOMIC(boot_page_write(curr_page * SPM_PAGESIZE));
114                 boot_spm_busy_wait();  // Wait while the SPM instruction is busy.
115
116                 /*
117                 * Reenable RWW-section again. We need this if we want to jump back
118                 * to the application after bootloading.
119                 */
120                 ATOMIC(boot_rww_enable());
121
122                 page_modified = false;
123                 kprintf("Done.\n");
124         }
125 }
126
127
128 /**
129  * Check current page and if \a page is different, load it in
130  * temporary buffer.
131  */
132 static void flash_avr_loadPage(avr_page_t page)
133 {
134         if (page != curr_page)
135         {
136                 flash_avr_flush();
137                 // Load page
138                 memcpy_P(page_buf, (const char *)(page * SPM_PAGESIZE), SPM_PAGESIZE);
139                 curr_page = page;
140                 kprintf("Loaded page %d\n", curr_page);
141         }
142 }
143
144 /**
145  * Write program memory.
146  * Write \a size bytes from buffer \a _buf to file \a fd
147  * \note Write operations are buffered.
148  */
149 static size_t flash_avr_write(struct _KFile *fd, const void *_buf, size_t size)
150 {
151         const uint8_t *buf =(const uint8_t *)_buf;
152
153         avr_page_t page;
154         avr_page_addr_t page_addr;
155         size_t total_write = 0;
156
157         ASSERT(fd->seek_pos + size <= fd->size);
158         size = MIN((uint32_t)size, fd->size - fd->seek_pos);
159
160         kprintf("Writing at pos[%u]\n", fd->seek_pos);
161         while (size)
162         {
163                 page = fd->seek_pos / SPM_PAGESIZE;
164                 page_addr = fd->seek_pos % SPM_PAGESIZE;
165
166                 flash_avr_loadPage(page);
167
168                 size_t wr_len = MIN(size, SPM_PAGESIZE - page_addr);
169                 memcpy(page_buf + page_addr, buf, wr_len);
170                 page_modified = true;
171
172                 buf += wr_len;
173                 fd->seek_pos += wr_len;
174                 size -= wr_len;
175                 total_write += wr_len;
176         }
177         kprintf("written %u bytes\n", total_write);
178         return total_write;
179 }
180
181 /**
182  * Open flash file \a fd
183  * \a name and \a mode are unused, cause flash memory is
184  * threated like one file.
185  */
186 static bool flash_avr_open(struct _KFile *fd, UNUSED_ARG(const char *, name), UNUSED_ARG(int, mode))
187 {
188         curr_page = 0;
189         memcpy_P(page_buf, (const char *)(curr_page * SPM_PAGESIZE), SPM_PAGESIZE);
190
191         fd->seek_pos = 0;
192         fd->size = (uint16_t)(FLASHEND - CONFIG_BOOT_SIZE + 1);
193         page_modified = false;
194
195         kprintf("Flash file opened\n");
196         return true;
197 }
198
199 /**
200  * Close file \a fd
201  */
202 static bool flash_avr_close(UNUSED_ARG(struct _KFile *,fd))
203 {
204         flash_avr_flush();
205         kprintf("Flash file closed\n");
206         return true;
207 }
208
209 /**
210  * Move \a fd file seek position of \a offset bytes
211  * from current position.
212  */
213 static int32_t flash_avr_seek(struct _KFile *fd, int32_t offset, KSeekMode whence)
214 {
215         uint32_t seek_pos;
216
217         switch(whence)
218         {
219                 case KSM_SEEK_SET:
220                         seek_pos = 0;
221                         break;
222                 case KSM_SEEK_END:
223                         seek_pos = fd->size - 1;
224                         break;
225                 case KSM_SEEK_CUR:
226                         seek_pos = fd->seek_pos;
227                         break;
228                 default:
229                         ASSERT(0);
230                         return -1;
231                         break;
232         }
233
234         /* Bound check */
235         if (seek_pos + offset > fd->size)
236         {
237                 ASSERT(0);
238                 return -1;
239         }
240
241         fd->seek_pos = seek_pos + offset;
242         kprintf("Flash seek to [%u]\n", fd->seek_pos);
243
244         return fd->seek_pos;
245 }
246
247 /**
248  * Read from file \a fd \a size bytes and put it in buffer \a buf
249  * \return the number of bytes read.
250  */
251 static size_t flash_avr_read(struct _KFile *fd, void *buf, size_t size)
252 {
253         ASSERT(fd->seek_pos + size <= fd->size);
254         size = MIN((uint32_t)size, fd->size - fd->seek_pos);
255
256         kprintf("Reading at pos[%u]\n", fd->seek_pos);
257         // Flush current buffered page (if modified).
258         flash_avr_flush();
259
260         /*
261          * AVR pointers are 16 bits wide, this hack is needed to avoid
262          * compiler warning, cause fd->seek_pos is a 32bit offset.
263          */
264         const uint8_t *pgm_addr = (const uint8_t *)0;
265         pgm_addr += fd->seek_pos;
266
267         memcpy_P(buf, pgm_addr, size);
268         fd->seek_pos += size;
269         kprintf("Read %u bytes\n", size);
270         return size;
271 }
272
273 /**
274  * Init AVR flash read/write file.
275  */
276 void flash_avr_init(struct _KFile *fd)
277 {
278         // Set up flash programming functions.
279         fd->open = flash_avr_open;
280         fd->close = flash_avr_close;
281         fd->read = flash_avr_read;
282         fd->write = flash_avr_write;
283         fd->seek = flash_avr_seek;
284 }
285
286 #if CONFIG_TEST
287
288 #define TEST_SIZE 683
289 #define ONE_BYTE_TEST_ADDRESS 347
290
291 uint8_t test_buf[TEST_SIZE];
292 uint8_t save_buf[TEST_SIZE];
293
294 /**
295  * Program memory read/write subtest.
296  * Try to write/read in the same \a f file location \a _size bytes.
297  * \return true if all is ok, false otherwise
298  * \note Restore file position at exit (if no error)
299  * \note Test buffer \a buf must be filled with
300  * the following statement:
301  * <pre>
302  * buf[i] = i & 0xff
303  * </pre>
304  */
305 static bool flash_avr_rwTest(KFile *f, uint8_t *buf, size_t _size)
306 {
307         int32_t size = _size;
308         // Write test buffer
309         if (f->write(f, buf, size) != size)
310                 return false;
311         f->seek(f, -size, SEEK_CUR);
312
313         // Reset test buffer
314         memset(buf, 0, size);
315
316         // Read flash in test buffer
317         if (f->read(f, buf, size) != size)
318                 return false;
319         f->seek(f, -size, SEEK_CUR);
320
321         // Check test result
322         for (size_t i = 0; i < size; i++)
323                 if (buf[i] != (i & 0xff))
324                         return false;
325
326         return true;
327 }
328
329 /**
330  * Test for program memory read/write.
331  */
332 bool flash_avr_test(void)
333 {
334         KFile fd;
335
336         // Set up flash programming functions.
337         flash_avr_init(&fd);
338
339         // Fill in test buffer
340         for (int i = 0; i < TEST_SIZE; i++)
341                 test_buf[i] = (i & 0xff);
342
343         // Open flash
344         fd.open(&fd, NULL, 0);
345         // Save flash content (for later restore).
346         fd.read(&fd, save_buf, sizeof(save_buf));
347         // Seek to addr 0
348         if (fd.seek(&fd, 0, SEEK_SET) != 0)
349                 goto flash_avr_test_end;
350
351         // Test flash read/write to address 0..TEST_SIZE
352         if (!flash_avr_rwTest(&fd, test_buf, TEST_SIZE))
353                 goto flash_avr_test_end;
354
355         // One byte read/write test
356         fd.seek(&fd, ONE_BYTE_TEST_ADDRESS, SEEK_CUR); // Random address
357         if (!flash_avr_rwTest(&fd, test_buf, 1))
358                 goto flash_avr_test_end;
359         fd.seek(&fd, -(int32_t)ONE_BYTE_TEST_ADDRESS, SEEK_CUR);
360
361         // Restore old flash data
362         if (fd.write(&fd, save_buf, sizeof(test_buf)) != TEST_SIZE)
363                 goto flash_avr_test_end;
364         fd.seek(&fd, -TEST_SIZE, SEEK_CUR);
365
366         // Go to the Flash end
367         fd.seek(&fd, -TEST_SIZE, SEEK_END);
368         // Save flash content (for later restore).
369         fd.read(&fd, save_buf, sizeof(save_buf));
370         fd.seek(&fd, -TEST_SIZE, SEEK_CUR);
371
372         // Test flash read/write to address (FLASHEND - TEST_SIZE) ... FLASHEND
373         if (!flash_avr_rwTest(&fd, test_buf, TEST_SIZE))
374                 goto flash_avr_test_end;
375
376         // Go to half test size.
377         fd.seek(&fd, (TEST_SIZE / 2), SEEK_CUR);
378
379         // This test should FAIL, cause we try to write over file end.
380         kprintf("This test should fail.\n");
381         if (flash_avr_rwTest(&fd, test_buf, TEST_SIZE))
382                 goto flash_avr_test_end;
383
384         fd.seek(&fd, -TEST_SIZE, SEEK_CUR);
385         // Restore old flash data
386         fd.write(&fd, save_buf, TEST_SIZE);
387
388         fd.close(&fd);
389         return true;
390
391 flash_avr_test_end:
392         fd.close(&fd);
393         return false;
394 }
395
396 #endif