Merged from external project:
[bertos.git] / bertos / drv / dataflash.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  * \brief Function library for dataflash AT45DB family (implementation).
33  *
34  * \version $Id: dataflash.c 21658 2008-06-05 16:42:54Z asterix $
35  * \author Daniele Basile <asterix@develer.com>
36  * \author Francesco Sacchi <batt@develer.com>
37  */
38
39 #include "dataflash.h"
40
41 #include "cfg/cfg_dataflash.h"
42 #include <cfg/macros.h>
43 #include <cfg/debug.h>
44 #include <cfg/module.h>
45
46 // Define logging setting (for cfg/log.h module).
47 #define LOG_LEVEL   DATAFLASH_LOG_LEVEL
48 #define LOG_FORMAT  DATAFLASH_LOG_FORMAT
49 #include <cfg/log.h>
50
51 #include <drv/timer.h>
52
53 #include <kern/kfile.h>
54
55 #include <cpu/power.h> /* cpu_relax() */
56
57 #include <string.h>
58
59 /**
60  * Array used to describe dataflash memory devices currently supported.
61  */
62 static const DataflashInfo mem_info[] =
63 {
64         {
65                 /* AT45DB041B */
66                 .density_id = 0x07,
67                 .page_size = 264,
68                 .page_bits = 9,
69                 .page_cnt = 2048,
70                 .read_cmd = DFO_READ_FLASH_MEM_BYTE_B,
71         },
72         {
73                 /* AT45DB081D */
74                 .density_id = 0x09,
75                 .page_size = 264,
76                 .page_bits = 9,
77                 .page_cnt = 4096,
78                 .read_cmd = DFO_READ_FLASH_MEM_BYTE_D,
79         },
80         {
81                 /* AT45DB161D */
82                 .density_id = 0x0B,
83                 .page_size = 528,
84                 .page_bits = 10,
85                 .page_cnt = 4096,
86                 .read_cmd = DFO_READ_FLASH_MEM_BYTE_D,
87         },
88         {
89                 /* AT45DB642D */
90                 .density_id = 0x0F,
91                 .page_size = 1056,
92                 .page_bits = 11,
93                 .page_cnt = 8192,
94                 .read_cmd = DFO_READ_FLASH_MEM_BYTE_D,
95         },
96         /* Add other memories here */
97 };
98
99 STATIC_ASSERT(countof(mem_info) == DFT_CNT);
100
101 /**
102  * Macro that toggle CS of dataflash.
103  * \note This is equivalent to fd->setCS(false) immediately followed by fd->setCS(true).
104  */
105 INLINE void CS_TOGGLE(DataFlash *fd)
106 {
107         fd->setCS(false);
108         fd->setCS(true);
109 }
110
111 /**
112  * Send a generic command to dataflash memory.
113  * This function send only 4 byte: opcode, page address and
114  * byte address.
115  */
116 static void send_cmd(DataFlash *fd, dataflash_page_t page_addr, dataflash_offset_t byte_addr, DataFlashOpcode opcode)
117 {
118
119         /*
120          * Make sure to toggle CS signal in order,
121          * and reset dataflash command decoder.
122          */
123         CS_TOGGLE(fd);
124
125
126         /*
127          * To send one command to data flash memory, we send 4 byte.
128          * First byte is opcode command, second and third byte are
129          * page address, in last byte we write a byte page address.
130          * (see datasheet for more detail).
131          *
132          * \note Generally a default memory page size is more than 256 byte.
133          *  In this case we need for addressing a byte in one page more than
134          *  8 bit, so we put in fourth byte low part of address byte, and
135          *  hight part of address byte in third byte togheter low par of page
136          *  address.
137          *
138          */
139
140         /*
141          * Send opcode.
142          */
143         kfile_putc(opcode, fd->channel);
144
145         /*
146          *  Send page address.
147          */
148         kfile_putc((uint8_t)(page_addr >> (16 - mem_info[fd->dev].page_bits)), fd->channel);
149         kfile_putc((uint8_t)((page_addr << (mem_info[fd->dev].page_bits - 8)) + (byte_addr >> 8)), fd->channel);
150
151         /*
152          * Send byte page address.
153          */
154         kfile_putc((uint8_t)byte_addr, fd->channel);
155 }
156
157 /**
158  * Reset dataflash memory function.
159  *
160  * If \a fd->setReset function is not NULL,
161  * this function resets data flash memory
162  * with one pulse reset long about 10usec.
163  *
164  */
165 static void dataflash_reset(DataFlash *fd)
166 {
167         fd->setCS(false);
168
169         if (fd->setReset)
170         {
171                 fd->setReset(true);
172                 timer_delayHp(us_to_hptime(RESET_PULSE_WIDTH));
173                 fd->setReset(false);
174                 timer_delayHp(us_to_hptime(RESET_PULSE_WIDTH));
175         }
176 }
177
178
179 /**
180  * Read status register of dataflah memory.
181  */
182 static uint8_t dataflash_stat(DataFlash *fd)
183 {
184         /*
185          * Make sure to toggle CS signal
186          * and reset dataflash command decoder.
187          */
188         CS_TOGGLE(fd);
189         kfile_putc(DFO_READ_STATUS, fd->channel);
190         return kfile_getc(fd->channel);
191 }
192
193
194 /**
195  * Send one command to data flash memory, and
196  * return status register value.
197  *
198  */
199 static uint8_t dataflash_cmd(DataFlash *fd, dataflash_page_t page_addr, dataflash_offset_t byte_addr, DataFlashOpcode opcode)
200 {
201         uint8_t stat;
202
203         send_cmd(fd, page_addr, byte_addr, opcode);
204
205         CS_TOGGLE(fd);
206
207         /*
208          * We chech data flash memory state, and wait until busy-flag
209          * is high.
210          */
211         while (!(dataflash_stat(fd) & BUSY_BIT))
212                 cpu_relax();
213
214         stat = dataflash_stat(fd);
215
216         kfile_flush(fd->channel); // Flush channel
217         /*
218          * Data flash has completed a bus cycle, so disable CS.
219          */
220         fd->setCS(false);
221
222         return stat;
223 }
224
225 /**
226  * Read \a len bytes from main data flash memory or buffer data
227  * flash memory, and put it in \a *block.
228  */
229 static void dataflash_readBlock(DataFlash *fd, dataflash_page_t page_addr, dataflash_offset_t byte_addr, uint8_t *block, dataflash_size_t len)
230 {
231         DataFlashOpcode opcode = mem_info[fd->dev].read_cmd;
232         send_cmd(fd, page_addr, byte_addr, opcode);
233
234         if (opcode == DFO_READ_FLASH_MEM_BYTE_B)
235         {
236                 /*
237                  * Send 24 don't care bits.
238                  */
239                 uint8_t dummy[] = { 0, 0, 0 };
240                 kfile_write(fd->channel, dummy, sizeof(dummy));
241         }
242
243         kfile_putc(0, fd->channel); //Send 8 don't care bit.
244         kfile_read(fd->channel, block, len); //Read len bytes ad put in block buffer.
245         kfile_flush(fd->channel); // Flush channel
246         fd->setCS(false);
247 }
248
249
250 /**
251  * Write \a len bytes in dataflash memory buffer.
252  *
253  * \note Is not possible to write directly in dataflash main memory.
254  * To perform a write in main memory you must first write in dataflash buffer
255  * memory and then send a command to write the page in main memory.
256  */
257 static void dataflash_writeBlock(DataFlash *fd, dataflash_offset_t offset, const uint8_t *block, dataflash_size_t len)
258 {
259         ASSERT(offset + len <= mem_info[fd->dev].page_size);
260
261         send_cmd(fd, 0x00, offset, DFO_WRITE_BUFF1);
262
263         kfile_write(fd->channel, block, len); //Write len bytes.
264         kfile_flush(fd->channel); // Flush channel
265
266         fd->setCS(false);
267 }
268
269
270 /**
271  * Load selected page from dataflash memory to buffer.
272  */
273 static void dataflash_loadPage(DataFlash *fd, dataflash_page_t page_addr)
274 {
275         dataflash_cmd(fd, page_addr, 0x00, DFO_MOV_MEM_TO_BUFF1);
276 }
277
278 static size_t dataflash_disk_page_read(struct BattFsSuper *d, pgcnt_t page, pgaddr_t addr, void *buf, size_t len)
279 {
280         DataFlash *fd = DATAFLASH_CAST((KFile *)d->disk_ctx);
281         dataflash_readBlock(fd, page, addr, buf, len);
282         return len;
283 }
284
285 static bool dataflash_disk_page_load(struct BattFsSuper *d, pgcnt_t page)
286 {
287         DataFlash *fd = DATAFLASH_CAST((KFile *)d->disk_ctx);
288         dataflash_loadPage(fd, page);
289         return true;
290 }
291
292 static size_t dataflash_disk_buffer_write(struct BattFsSuper *d, pgaddr_t addr, const void *buf, size_t len)
293 {
294         DataFlash *fd = DATAFLASH_CAST((KFile *)d->disk_ctx);
295         dataflash_writeBlock(fd, addr, buf, len);
296         return true;
297 }
298
299 static size_t dataflash_disk_buffer_read(struct BattFsSuper *d, pgaddr_t addr, void *buf, size_t len)
300 {
301         DataFlash *fd = DATAFLASH_CAST((KFile *)d->disk_ctx);
302         ASSERT(addr + len <= mem_info[fd->dev].page_size);
303
304         CS_TOGGLE(fd);
305
306         kfile_putc(DFO_READ_BUFF1, fd->channel);
307
308         uint32_t byte_addr = addr;
309
310         kfile_putc((byte_addr >> 16) & 0xff, fd->channel);
311         kfile_putc((byte_addr >> 8) & 0xff, fd->channel);
312         kfile_putc((byte_addr & 0xff, fd->channel);
313
314         /* Send additional don't care byte to start read operation */
315         kfile_putc(0, fd->channel);
316
317         kfile_read(fd->channel, buf, len); //Read len bytes ad put in buffer.
318         kfile_flush(fd->channel); // Flush channel
319         fd->setCS(false);
320 }
321
322 static bool dataflash_disk_page_save(struct BattFsSuper *d, pgcnt_t page)
323 {
324         DataFlash *fd = DATAFLASH_CAST((KFile *)d->disk_ctx);
325         dataflash_cmd(fd, page, 0x00, DFO_WRITE_BUFF1_TO_MEM);
326         return true;
327 }
328
329 static bool dataflash_disk_page_erase(struct BattFsSuper *d, pgcnt_t page)
330 {
331         DataFlash *fd = DATAFLASH_CAST((KFile *)d->disk_ctx);
332         dataflash_cmd(fd, page, 0x00, DFO_ERASE_PAGE);
333         return true;
334 }
335
336 /**
337  * Flush select page (stored in buffer) in data flash main memory page.
338  */
339 static int dataflash_flush(KFile *_fd)
340 {
341         DataFlash *fd = DATAFLASH_CAST(_fd);
342         if (fd->page_dirty)
343         {
344                 dataflash_cmd(fd, fd->current_page, 0x00, DFO_WRITE_BUFF1_TO_MEM_E);
345
346                 fd->page_dirty = false;
347
348                 LOG_INFO("Flushing page {%ld}\n", fd->current_page);
349         }
350         return 0;
351 }
352
353 /* Kfile interface section */
354
355 /**
356  * Close file \a fd.
357  */
358 static int dataflash_close(struct KFile *_fd)
359 {
360         dataflash_flush(_fd);
361         LOG_INFO("Close.\n");
362         return 0;
363 }
364
365 /**
366  * Reopen dataflash file \a fd.
367  */
368 static KFile *dataflash_reopen(KFile *_fd)
369 {
370         DataFlash *fd = DATAFLASH_CAST(_fd);
371         dataflash_close(_fd);
372
373         fd->current_page = 0;
374         fd->fd.seek_pos = 0;
375
376         /* Load selected page from dataflash memory */
377         dataflash_loadPage(fd, fd->current_page);
378
379         LOG_INFO("Reopen.\n");
380         return &fd->fd;
381 }
382
383
384 /**
385  * Read in \a buf \a size bytes from dataflash memmory.
386  *
387  * \note For reading data flash memory, we
388  * check flag page_dirty, if is true (that mean
389  * we have written a byte in buffer memory) we
390  * flush current page in main memory and
391  * then read from memory, else we read byte
392  * directly from data flash main memory.
393  *
394  * \return the number of bytes read.
395  */
396 static size_t dataflash_read(struct KFile *_fd, void *buf, size_t size)
397 {
398         DataFlash *fd = DATAFLASH_CAST(_fd);
399
400         dataflash_offset_t byte_addr;
401         dataflash_page_t page_addr;
402         uint8_t *data = (uint8_t *)buf;
403
404
405         ASSERT(fd->fd.seek_pos + size <= (kfile_off_t)fd->fd.size);
406         size = MIN((kfile_off_t)size, fd->fd.size - fd->fd.seek_pos);
407
408         LOG_INFO("Reading at pos[%lu]\n", fd->fd.seek_pos);
409
410         /*
411          * We select page and offest from absolute address.
412          */
413         page_addr = fd->fd.seek_pos / mem_info[fd->dev].page_size;
414         byte_addr = fd->fd.seek_pos % mem_info[fd->dev].page_size;
415
416         LOG_INFO("[page-{%ld}, byte-{%ld}]\n", page_addr, byte_addr);
417
418         /*
419          * Flush current page in main memory if
420          * we had been written a byte in memory
421          */
422         dataflash_flush(&fd->fd);
423
424         /*
425          * Read byte in main page data flash memory.
426          */
427         dataflash_readBlock(fd, page_addr, byte_addr, data, size);
428
429         fd->fd.seek_pos += size;
430         LOG_INFO("Read %ld bytes\n", size);
431
432         return size;
433 }
434
435 /**
436  * Write \a _buf in dataflash memory
437  *
438  * \note For writing \a _buf in dataflash memory, we must
439  * first write in buffer data flash memory. At the end of write,
440  * we can put page in dataflash main memory.
441  * If we write in two contiguous pages, we put in main memory current
442  * page and then reload the page which we want to write.
443  *
444  * \return the number of bytes write.
445  */
446 static size_t dataflash_write(struct KFile *_fd, const void *_buf, size_t size)
447 {
448         DataFlash *fd = DATAFLASH_CAST(_fd);
449
450         dataflash_offset_t offset;
451         dataflash_page_t new_page;
452         size_t total_write = 0;
453
454         const uint8_t *data = (const uint8_t *) _buf;
455
456         ASSERT(fd->fd.seek_pos + size <= (kfile_off_t)fd->fd.size);
457         size = MIN((kfile_off_t)size, fd->fd.size - fd->fd.seek_pos);
458
459         LOG_INFO("Writing at pos[%lu]\n", fd->fd.seek_pos);
460
461         while (size)
462         {
463                 /*
464                 * We select page and offest from absolute address.
465                 */
466                 new_page = fd->fd.seek_pos / mem_info[fd->dev].page_size;
467                 offset = fd->fd.seek_pos % mem_info[fd->dev].page_size;
468
469
470                 size_t wr_len = MIN((dataflash_size_t)size, mem_info[fd->dev].page_size - offset);
471
472                 LOG_INFO("[page-{%ld}, byte-{%ld}]\n",new_page, offset);
473
474                 if (new_page != fd->current_page)
475                 {
476                         /* Flush current page in main memory*/
477                         dataflash_flush(&fd->fd);
478                         /* Load select page memory from data flash memory*/
479                         dataflash_loadPage(fd, new_page);
480
481                         fd->current_page = new_page;
482                         LOG_INFO(" >> Load page: {%ld}\n", new_page);
483                 }
484                 /*
485                 * Write byte in current page, and set true
486                 * page_dirty flag.
487                 */
488                 dataflash_writeBlock(fd, offset, data, wr_len);
489                 fd->page_dirty = true;
490
491                 data += wr_len;
492                 fd->fd.seek_pos += wr_len;
493                 size -= wr_len;
494                 total_write += wr_len;
495         }
496
497         LOG_INFO("written %lu bytes\n", total_write);
498         return total_write;
499 }
500
501 MOD_DEFINE(dataflash);
502
503 /**
504  * Dataflash init function.
505  * This function initialize \a fd with SPI channel \a ch and test if data flash memory
506  * density is the same specified by device \a dev.
507  * \a setCS is a callback used to set/reset CS line.
508  * \a setReset is a callback used to set/reset the dataflash (can be NULL if reset is unconnected)
509  * \return true if ok, false if memory density read from dataflash is not compliant with the
510  * configured one.
511  */
512 bool dataflash_init(DataFlash *fd, KFile *ch, DataflashType dev, dataflash_setCS_t *setCS, dataflash_setReset_t *setReset)
513 {
514         uint8_t stat;
515
516         MOD_CHECK(hw_dataflash);
517
518         ASSERT(fd);
519         ASSERT(ch);
520         ASSERT(setCS);
521         ASSERT(dev < DFT_CNT);
522
523         memset(fd, 0, sizeof(*fd));
524         DB(fd->fd._type = KFT_DATAFLASH);
525         fd->dev = dev;
526         fd->channel = ch;
527         fd->setReset = setReset;
528         fd->setCS = setCS;
529
530         // Setup data flash programming functions.
531         fd->fd.reopen = dataflash_reopen;
532         fd->fd.close = dataflash_close;
533         fd->fd.read = dataflash_read;
534         fd->fd.write = dataflash_write;
535         fd->fd.seek = kfile_genericSeek;
536         fd->fd.flush = dataflash_flush;
537
538         dataflash_reset(fd);
539         stat = dataflash_stat(fd);
540
541         /*
542          * 2,3,4,5 bits of 1 byte status register
543          * indicate a device density of dataflash memory
544          * (see datasheet for more detail.)
545          */
546         if (GET_ID_DESITY_DEVICE(stat) != mem_info[fd->dev].density_id)
547                 return false;
548
549         fd->current_page = 0;
550         fd->fd.seek_pos = 0;
551         fd->fd.size = mem_info[fd->dev].page_size * mem_info[fd->dev].page_cnt;
552
553         /* Load selected page from dataflash memory */
554         dataflash_loadPage(fd, fd->current_page);
555         MOD_INIT(dataflash);
556         return true;
557 }