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