03f5109fde26c6c1451e3804c41f27f7826348e8
[bertos.git] / bertos / cpu / cortex-m3 / drv / mt29f_sam3.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 2011 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \brief Micron MT29F serial NAND driver for SAM3's static memory controller.
34  *
35  * \author Stefano Fedrigo <aleph@develer.com>
36  */
37
38 #include "mt29f_sam3.h"
39 #include "cfg/cfg_mt29f.h"
40
41 // Define log settings for cfg/log.h
42 #define LOG_LEVEL    CONFIG_MT29F_LOG_LEVEL
43 #define LOG_FORMAT   CONFIG_MT29F_LOG_FORMAT
44
45 #include <cfg/log.h>
46 #include <cfg/macros.h>
47 #include <io/sam3.h>
48 #include <drv/timer.h>
49 #include <drv/mt29f.h>
50 #include <struct/heap.h>
51 #include <cpu/power.h> /* cpu_relax() */
52 #include <cpu/types.h>
53
54 #include <string.h> /* memcpy() */
55
56 // Timeout for NAND operations in ms
57 #define MT29F_TMOUT  100
58
59 // NAND flash status codes
60 #define MT29F_STATUS_READY             BV(6)
61 #define MT29F_STATUS_ERROR             BV(0)
62
63 // NAND flash commands
64 #define MT29F_CMD_READ_1               0x00
65 #define MT29F_CMD_READ_2               0x30
66 #define MT29F_CMD_COPYBACK_READ_1      0x00
67 #define MT29F_CMD_COPYBACK_READ_2      0x35
68 #define MT29F_CMD_COPYBACK_PROGRAM_1   0x85
69 #define MT29F_CMD_COPYBACK_PROGRAM_2   0x10
70 #define MT29F_CMD_RANDOM_OUT           0x05
71 #define MT29F_CMD_RANDOM_OUT_2         0xE0
72 #define MT29F_CMD_RANDOM_IN            0x85
73 #define MT29F_CMD_READID               0x90
74 #define MT29F_CMD_WRITE_1              0x80
75 #define MT29F_CMD_WRITE_2              0x10
76 #define MT29F_CMD_ERASE_1              0x60
77 #define MT29F_CMD_ERASE_2              0xD0
78 #define MT29F_CMD_STATUS               0x70
79 #define MT29F_CMD_RESET                0xFF
80
81 // Addresses for sending command, addresses and data bytes to flash
82 #define MT29F_CMD_ADDR    0x60400000
83 #define MT29F_ADDR_ADDR   0x60200000
84 #define MT29F_DATA_ADDR   0x60000000
85
86 // Get chip select mask for command register
87 #define MT29F_CSID(chip)  (((chip)->chip_select << NFC_CMD_CSID_SHIFT) & NFC_CMD_CSID_MASK)
88
89 // Get block from page
90 #define PAGE(blk)            ((blk) * MT29F_PAGES_PER_BLOCK)
91
92 // Page from block and page in block
93 #define BLOCK(page)          ((uint16_t)((page) / MT29F_PAGES_PER_BLOCK))
94 #define PAGE_IN_BLOCK(page)  ((uint16_t)((page) % MT29F_PAGES_PER_BLOCK))
95
96
97 /*
98  * Remap info written in the first page of each block
99  * used to remap bad blocks.
100  */
101 struct RemapInfo
102 {
103         uint32_t tag;         // Magic number to detect valid info
104         uint16_t mapped_blk;  // Bad block the block containing this info is remapping
105 };
106
107
108 /*
109  * Translate flash page index plus a byte offset
110  * in the five address cycles format needed by NAND.
111  *
112  * Cycles in x8 mode as the MT29F2G08AAD
113  * CA = column addr, PA = page addr, BA = block addr
114  *
115  * Cycle    I/O7  I/O6  I/O5  I/O4  I/O3  I/O2  I/O1  I/O0
116  * -------------------------------------------------------
117  * First    CA7   CA6   CA5   CA4   CA3   CA2   CA1   CA0
118  * Second   LOW   LOW   LOW   LOW   CA11  CA10  CA9   CA8
119  * Third    BA7   BA6   PA5   PA4   PA3   PA2   PA1   PA0
120  * Fourth   BA15  BA14  BA13  BA12  BA11  BA10  BA9   BA8
121  * Fifth    LOW   LOW   LOW   LOW   LOW   LOW   LOW   BA16
122  */
123 static void getAddrCycles(uint32_t page, uint16_t offset, uint32_t *cycle0, uint32_t *cycle1234)
124 {
125         ASSERT(offset < MT29F_PAGE_SIZE);
126
127         *cycle0 = offset & 0xff;
128         *cycle1234 = (page << 8) | ((offset >> 8) & 0xf);
129
130         //LOG_INFO("mt29f addr: %lx %lx\n", *cycle1234, *cycle0);
131 }
132
133
134 INLINE bool nfcIsBusy(void)
135 {
136         return HWREG(NFC_CMD_BASE_ADDR + NFC_CMD_NFCCMD) & 0x8000000;
137 }
138
139
140 /*
141  * Return true if SMC/NFC controller completed the last operations.
142  */
143 INLINE bool isCmdDone(void)
144 {
145     return SMC_SR & SMC_SR_CMDDONE;
146 }
147
148
149 /*
150  * Wait for edge transition of READY/BUSY NAND
151  * signal.
152  * Return true for edge detection, false in case of timeout.
153  */
154 static bool waitReadyBusy(void)
155 {
156         time_t start = timer_clock();
157
158         while (!(SMC_SR & SMC_SR_RB_EDGE0))
159         {
160                 cpu_relax();
161                 if (timer_clock() - start > MT29F_TMOUT)
162                 {
163                         LOG_INFO("mt29f: R/B timeout\n");
164                         return false;
165                 }
166         }
167
168         return true;
169 }
170
171 /*
172  * Wait for transfer to complete until timeout.
173  * If transfer completes return true, false in case of timeout.
174  */
175 static bool waitTransferComplete(void)
176 {
177         time_t start = timer_clock();
178
179         while (!(SMC_SR & SMC_SR_XFRDONE))
180         {
181                 cpu_relax();
182                 if (timer_clock() - start > MT29F_TMOUT)
183                 {
184                         LOG_INFO("mt29f: xfer complete timeout\n");
185                         return false;
186                 }
187         }
188
189         return true;
190 }
191
192
193 /*
194  * Send command to NAND and wait for completion.
195  */
196 static void sendCommand(uint32_t cmd,
197                 int num_cycles, uint32_t cycle0, uint32_t cycle1234)
198 {
199         reg32_t *cmd_addr;
200
201         while (nfcIsBusy());
202
203         if (num_cycles == 5)
204                 SMC_ADDR = cycle0;
205
206         cmd_addr = (reg32_t *)(NFC_CMD_BASE_ADDR + cmd);
207         *cmd_addr = cycle1234;
208
209         while (!isCmdDone());
210 }
211
212
213 static bool isOperationComplete(Mt29f *chip)
214 {
215         uint8_t status;
216
217         sendCommand(MT29F_CSID(chip) |
218                 NFC_CMD_NFCCMD | NFC_CMD_ACYCLE_NONE |
219                 MT29F_CMD_STATUS << 2,
220                 0, 0, 0);
221
222         status = (uint8_t)HWREG(MT29F_DATA_ADDR);
223         return (status & MT29F_STATUS_READY) && !(status & MT29F_STATUS_ERROR);
224 }
225
226
227 static void chipReset(Mt29f *chip)
228 {
229         sendCommand(MT29F_CSID(chip) |
230                 NFC_CMD_NFCCMD | NFC_CMD_ACYCLE_NONE |
231                 MT29F_CMD_RESET << 2,
232                 0, 0, 0);
233
234         waitReadyBusy();
235 }
236
237
238 /**
239  * Erase the whole block.
240  */
241 int mt29f_blockErase(Mt29f *chip, uint16_t block)
242 {
243         uint32_t cycle0;
244         uint32_t cycle1234;
245
246         uint16_t remapped_block = chip->block_map[block];
247         if (block != remapped_block)
248         {
249                 LOG_INFO("mt29f_blockErase: remapped block: blk %d->%d\n", block, remapped_block);
250                 block = remapped_block;
251         }
252
253         getAddrCycles(PAGE(block), 0, &cycle0, &cycle1234);
254
255         sendCommand(MT29F_CSID(chip) |
256                 NFC_CMD_NFCCMD | NFC_CMD_ACYCLE_THREE | NFC_CMD_VCMD2 |
257                 (MT29F_CMD_ERASE_2 << 10) | (MT29F_CMD_ERASE_1 << 2),
258                 3, 0, cycle1234 >> 8);
259
260         waitReadyBusy();
261
262         if (!isOperationComplete(chip))
263         {
264                 LOG_ERR("mt29f: error erasing block\n");
265                 chip->status |= MT29F_ERR_ERASE;
266                 return -1;
267         }
268
269         return 0;
270 }
271
272
273 /**
274  * Read Device ID and configuration codes.
275  */
276 bool mt29f_getDevId(Mt29f *chip, uint8_t dev_id[5])
277 {
278         sendCommand(MT29F_CSID(chip) |
279                 NFC_CMD_NFCCMD | NFC_CMD_NFCEN | NFC_CMD_ACYCLE_ONE |
280                 MT29F_CMD_READID << 2,
281                 1, 0, 0);
282
283         waitReadyBusy();
284         if (!waitTransferComplete())
285         {
286                 LOG_ERR("mt29f: getDevId timeout\n");
287                 chip->status |= MT29F_ERR_RD_TMOUT;
288                 return false;
289         }
290
291         memcpy(dev_id, (void *)NFC_SRAM_BASE_ADDR, 5);
292         return true;
293 }
294
295
296 static bool checkEcc(Mt29f *chip)
297 {
298         struct RemapInfo *remap_info = (struct RemapInfo *)(NFC_SRAM_BASE_ADDR + MT29F_REMAP_TAG_OFFSET);
299
300         /*
301          * Check for ECC hardware status only if a valid RemapInfo structure is found.
302          * That guarantees we wrote the block and a valid ECC is present.
303          */
304         if (remap_info->tag == MT29F_REMAP_TAG)
305         {
306                 uint32_t sr1 = SMC_ECC_SR1;
307                 if (sr1)
308                 {
309                         LOG_INFO("ECC error, ECC_SR1=0x%lx\n", sr1);
310                         chip->status |= MT29F_ERR_ECC;
311                         return false;
312                 }
313         }
314
315         return true;
316 }
317
318
319 static bool mt29f_readPage(Mt29f *chip, uint32_t page, uint16_t offset)
320 {
321         uint32_t cycle0;
322         uint32_t cycle1234;
323
324         //LOG_INFO("mt29f_readPage: page 0x%lx off 0x%x\n", page, offset);
325
326         getAddrCycles(page, offset, &cycle0, &cycle1234);
327
328         sendCommand(MT29F_CSID(chip) |
329                 NFC_CMD_NFCCMD | NFC_CMD_NFCEN | NFC_CMD_ACYCLE_FIVE | NFC_CMD_VCMD2 |
330                 (MT29F_CMD_READ_2 << 10) | (MT29F_CMD_READ_1 << 2),
331                 5, cycle0, cycle1234);
332
333         waitReadyBusy();
334         if (!waitTransferComplete())
335         {
336                 LOG_ERR("mt29f: read timeout\n");
337                 chip->status |= MT29F_ERR_RD_TMOUT;
338                 return false;
339         }
340
341         return true;
342 }
343
344
345 /*
346  * Read page data and ECC, checking for errors.
347  * TODO: fix errors with ECC when possible.
348  */
349 static bool mt29f_read(Mt29f *chip, uint32_t page, void *buf, uint16_t offset, uint16_t size)
350 {
351         uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
352
353         //LOG_INFO("mt29f_read: page=%ld, offset=%d, size=%d\n", page, offset, size);
354
355         if (page != remapped_page)
356         {
357                 LOG_INFO("mt29f_read: remapped block: blk %d->%d, pg %ld->%ld\n",
358                                 BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
359                 page = remapped_page;
360         }
361
362         if (!mt29f_readPage(chip, page, 0))
363                 return false;
364
365         memcpy(buf, (void *)(NFC_SRAM_BASE_ADDR + offset), size);
366
367         return checkEcc(chip);
368 }
369
370
371 /*
372  * Write data in NFC SRAM buffer to a NAND page, starting at a given offset.
373  * Usually offset will be 0 to write data or MT29F_DATA_SIZE to write the spare
374  * area.
375  *
376  * According to datasheet to get ECC computed by hardware is sufficient
377  * to write the main area.  But it seems that in that way the last ECC_PR
378  * register is not generated.  The workaround is to write data and dummy (ff)
379  * spare data in one write, at this point the last ECC_PR is correct and
380  * ECC data can be written in the spare area with a second program operation.
381  */
382 static bool mt29f_writePage(Mt29f *chip, uint32_t page, uint16_t offset)
383 {
384         uint32_t cycle0;
385         uint32_t cycle1234;
386
387         //LOG_INFO("mt29f_writePage: page 0x%lx off 0x%x\n", page, offset);
388
389         getAddrCycles(page, offset, &cycle0, &cycle1234);
390
391         sendCommand(MT29F_CSID(chip) |
392                         NFC_CMD_NFCCMD | NFC_CMD_NFCWR | NFC_CMD_NFCEN | NFC_CMD_ACYCLE_FIVE |
393                         MT29F_CMD_WRITE_1 << 2,
394                         5, cycle0, cycle1234);
395
396         if (!waitTransferComplete())
397         {
398                 LOG_ERR("mt29f: write timeout\n");
399                 chip->status |= MT29F_ERR_WR_TMOUT;
400                 return false;
401         }
402
403         sendCommand(MT29F_CSID(chip) |
404                         NFC_CMD_NFCCMD | NFC_CMD_ACYCLE_NONE |
405                         MT29F_CMD_WRITE_2 << 2,
406                         0, 0, 0);
407
408         waitReadyBusy();
409
410         if (!isOperationComplete(chip))
411         {
412                 LOG_ERR("mt29f: error writing page\n");
413                 chip->status |= MT29F_ERR_WRITE;
414                 return false;
415         }
416
417         return true;
418 }
419
420
421 /*
422  * Write data in a page.
423  */
424 static bool mt29f_writePageData(Mt29f *chip, uint32_t page, const void *buf, uint16_t size)
425 {
426         ASSERT(size <= MT29F_DATA_SIZE);
427
428         memset((void *)NFC_SRAM_BASE_ADDR, 0xff, MT29F_PAGE_SIZE);
429         memcpy((void *)NFC_SRAM_BASE_ADDR, buf, size);
430
431         return mt29f_writePage(chip, page, 0);
432 }
433
434
435 /*
436  * Write the spare area in a page: ECC and remap block index.
437  * \param page           the page to be written
438  * \parma original_page  if different from page, it's the page that's being remapped
439  *
440  * ECC data are extracted from ECC_PRx registers and written
441  * in the page's spare area.
442  * For 2048 bytes pages and 1 ECC word each 256 bytes,
443  * 24 bytes of ECC data are stored.
444  */
445 static bool mt29f_writePageSpare(Mt29f *chip, uint32_t page, uint32_t original_page)
446 {
447         int i;
448         uint32_t *buf = (uint32_t *)NFC_SRAM_BASE_ADDR;
449         struct RemapInfo *remap_info = (struct RemapInfo *)(NFC_SRAM_BASE_ADDR + MT29F_REMAP_TAG_OFFSET);
450
451         memset((void *)NFC_SRAM_BASE_ADDR, 0xff, MT29F_SPARE_SIZE);
452
453         for (i = 0; i < MT29F_ECC_NWORDS; i++)
454                 buf[i] = *((reg32_t *)(SMC_BASE + SMC_ECC_PR0_OFF) + i);
455
456         // Write remap tag
457         remap_info->tag = MT29F_REMAP_TAG;
458         remap_info->mapped_blk = BLOCK(original_page);
459
460         return mt29f_writePage(chip, page, MT29F_DATA_SIZE);
461 }
462
463
464 static bool mt29f_write(Mt29f *chip, uint32_t page, const void *buf, uint16_t size)
465 {
466         uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
467
468         if (page != remapped_page)
469                 LOG_INFO("mt29f_write: remapped block: blk %d->%d, pg %ld->%ld\n",
470                                 BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
471
472         return
473                 mt29f_writePageData(chip, remapped_page, buf, size) &&
474                 mt29f_writePageSpare(chip, remapped_page, page);
475 }
476
477
478 /*
479  * Check if the given block is marked bad: ONFI standard mandates
480  * that bad block are marked with "00" bytes on the spare area of the
481  * first page in block.
482  */
483 static bool blockIsGood(Mt29f *chip, uint16_t blk)
484 {
485         uint8_t *first_byte = (uint8_t *)NFC_SRAM_BASE_ADDR;
486         bool good;
487
488         // Check first byte in spare area of first page in block
489         mt29f_readPage(chip, PAGE(blk), MT29F_DATA_SIZE);
490         good = *first_byte != 0;
491
492         if (!good)
493                 LOG_INFO("mt29f: bad block %d\n", blk);
494
495         return good;
496 }
497
498
499 /*
500  * Return the main partition block remapped on given block in the remap
501  * partition (dest_blk).
502  */
503 static int getBadBlockFromRemapBlock(Mt29f *chip, uint16_t dest_blk)
504 {
505         struct RemapInfo *remap_info = (struct RemapInfo *)NFC_SRAM_BASE_ADDR;
506
507         if (!mt29f_readPage(chip, PAGE(dest_blk), MT29F_DATA_SIZE + MT29F_REMAP_TAG_OFFSET))
508                 return -1;
509
510         if (remap_info->tag == MT29F_REMAP_TAG)
511                 return remap_info->mapped_blk;
512         else
513                 return -1;
514 }
515
516
517 /*
518  * Set a block remapping: src_blk (a block in main data partition) is remappend
519  * on dest_blk (block in reserved remapped blocks partition).
520  */
521 static bool setMapping(Mt29f *chip, uint32_t src_blk, uint32_t dest_blk)
522 {
523         struct RemapInfo *remap_info = (struct RemapInfo *)NFC_SRAM_BASE_ADDR;
524
525         LOG_INFO("mt29f, setMapping(): src=%ld dst=%ld\n", src_blk, dest_blk);
526
527         if (!mt29f_readPage(chip, PAGE(dest_blk), MT29F_DATA_SIZE + MT29F_REMAP_TAG_OFFSET))
528                 return false;
529
530         remap_info->tag = MT29F_REMAP_TAG;
531         remap_info->mapped_blk = src_blk;
532
533         return mt29f_writePage(chip, PAGE(dest_blk), MT29F_DATA_SIZE + MT29F_REMAP_TAG_OFFSET);
534 }
535
536
537 /*
538  * Get a new block from the remap partition to use as a substitute
539  * for a bad block.
540  */
541 static uint16_t getFreeRemapBlock(Mt29f *chip)
542 {
543         int blk;
544
545         for (blk = chip->remap_start; blk < MT29F_NUM_BLOCKS; blk++)
546         {
547                 if (blockIsGood(chip, blk))
548                 {
549                         chip->remap_start = blk + 1;
550                         return blk;
551                 }
552         }
553
554         LOG_ERR("mt29f: reserved blocks for bad block remapping exhausted!\n");
555         return 0;
556 }
557
558
559 /*
560  * Check if NAND is initialized.
561  */
562 static bool chipIsMarked(Mt29f *chip)
563 {
564         return getBadBlockFromRemapBlock(chip, MT29F_NUM_USER_BLOCKS) != -1;
565 }
566
567
568 /*
569  * Initialize NAND (format). Scan NAND for factory marked bad blocks.
570  * All bad blocks found are remapped to the remap partition: each
571  * block in the remap partition used to remap bad blocks is marked.
572  */
573 static void initBlockMap(Mt29f *chip)
574 {
575         int b, last;
576
577         // Default is for each block to not be remapped
578         for (b = 0; b < MT29F_NUM_BLOCKS; b++)
579                 chip->block_map[b] = b;
580         chip->remap_start = MT29F_NUM_USER_BLOCKS;
581
582         if (chipIsMarked(chip))
583         {
584                 LOG_INFO("mt29f: found initialized NAND, searching for remapped blocks\n");
585
586                 // Scan for assigned blocks in remap area
587                 for (b = last = MT29F_NUM_USER_BLOCKS; b < MT29F_NUM_BLOCKS; b++)
588                 {
589                         int remapped_blk = getBadBlockFromRemapBlock(chip, b);
590                         if (remapped_blk != -1 && remapped_blk != b)
591                         {
592                                 LOG_INFO("mt29f: found remapped block %d->%d\n", remapped_blk, b);
593                                 chip->block_map[remapped_blk] = b;
594                                 last = b + 1;
595                         }
596                 }
597                 chip->remap_start = last;
598         }
599         else
600         {
601                 bool remapped_anything = false;
602
603                 LOG_INFO("mt29f: found new NAND, searching for bad blocks\n");
604
605                 for (b = 0; b < MT29F_NUM_USER_BLOCKS; b++)
606                 {
607                         if (!blockIsGood(chip, b))
608                         {
609                                 chip->block_map[b] = getFreeRemapBlock(chip);
610                                 setMapping(chip, b, chip->block_map[b]);
611                                 remapped_anything = true;
612                                 LOG_INFO("mt29f: found new bad block %d, remapped to %d\n", b, chip->block_map[b]);
613                         }
614                 }
615
616                 /*
617              * If no bad blocks are found (we're lucky!) write a dummy
618                  * remap to mark NAND and detect we already scanned it next time.
619                  */
620                 if (!remapped_anything)
621                 {
622                         setMapping(chip, MT29F_NUM_USER_BLOCKS, MT29F_NUM_USER_BLOCKS);
623                         LOG_INFO("mt29f: no bad block founds, marked NAND\n");
624                 }
625         }
626 }
627
628
629 /**
630  * Reset bad blocks map and erase all blocks.
631  *
632  * \note DON'T USE on production chips: this function will try to erase
633  *       factory marked bad blocks too.
634  */
635 void mt29f_format(Mt29f *chip)
636 {
637         int b;
638
639         for (b = 0; b < MT29F_NUM_BLOCKS; b++)
640         {
641                 LOG_INFO("mt29f: erasing block %d\n", b);
642                 chip->block_map[b] = b;
643                 mt29f_blockErase(chip, b);
644         }
645         chip->remap_start = MT29F_NUM_USER_BLOCKS;
646 }
647
648 #ifdef _DEBUG
649
650 /*
651  * Create some bad blocks, erasing them and writing the bad block mark.
652  */
653 void mt29f_ruinSomeBlocks(Mt29f *chip)
654 {
655         int bads[] = { 7, 99, 555, 1003, 1004, 1432 };
656         unsigned i;
657
658         LOG_INFO("mt29f: erasing mark\n");
659         mt29f_blockErase(chip, MT29F_NUM_USER_BLOCKS);
660
661         for (i = 0; i < countof(bads); i++)
662         {
663                 LOG_INFO("mt29f: erasing block %d\n", bads[i]);
664                 mt29f_blockErase(chip, bads[i]);
665
666                 LOG_INFO("mt29f: marking page %d as bad\n", PAGE(bads[i]));
667                 memset((void *)NFC_SRAM_BASE_ADDR, 0, MT29F_SPARE_SIZE);
668                 mt29f_writePage(chip, PAGE(bads[i]), MT29F_DATA_SIZE);
669         }
670 }
671
672 #endif
673
674
675 static void initPio(void)
676 {
677         /*
678          * TODO: put following stuff in hw_ file dependent
679          * Parameters for MT29F8G08AAD
680          */
681         pmc_periphEnable(PIOA_ID);
682         pmc_periphEnable(PIOC_ID);
683         pmc_periphEnable(PIOD_ID);
684
685         PIO_PERIPH_SEL(PIOA_BASE, MT29F_PINS_PORTA, MT29F_PERIPH_PORTA);
686         PIOA_PDR = MT29F_PINS_PORTA;
687         PIOA_PUER = MT29F_PINS_PORTA;
688
689         PIO_PERIPH_SEL(PIOC_BASE, MT29F_PINS_PORTC, MT29F_PERIPH_PORTC);
690         PIOC_PDR = MT29F_PINS_PORTC;
691         PIOC_PUER = MT29F_PINS_PORTC;
692
693         PIO_PERIPH_SEL(PIOD_BASE, MT29F_PINS_PORTD, MT29F_PERIPH_PORTD);
694         PIOD_PDR = MT29F_PINS_PORTD;
695         PIOD_PUER = MT29F_PINS_PORTD;
696
697     pmc_periphEnable(SMC_SDRAMC_ID);
698 }
699
700
701 static void initSmc(void)
702 {
703     SMC_SETUP0 = SMC_SETUP_NWE_SETUP(0)
704                 | SMC_SETUP_NCS_WR_SETUP(0)
705                 | SMC_SETUP_NRD_SETUP(0)
706                 | SMC_SETUP_NCS_RD_SETUP(0);
707
708     SMC_PULSE0 = SMC_PULSE_NWE_PULSE(2)
709                 | SMC_PULSE_NCS_WR_PULSE(3)
710                 | SMC_PULSE_NRD_PULSE(2)
711                 | SMC_PULSE_NCS_RD_PULSE(3);
712
713     SMC_CYCLE0 = SMC_CYCLE_NWE_CYCLE(3)
714                 | SMC_CYCLE_NRD_CYCLE(3);
715
716     SMC_TIMINGS0 = SMC_TIMINGS_TCLR(1)
717                 | SMC_TIMINGS_TADL(6)
718                 | SMC_TIMINGS_TAR(4)
719                 | SMC_TIMINGS_TRR(2)
720                 | SMC_TIMINGS_TWB(9)
721                 | SMC_TIMINGS_RBNSEL(7)
722                 | SMC_TIMINGS_NFSEL;
723
724     SMC_MODE0 = SMC_MODE_READ_MODE
725                 | SMC_MODE_WRITE_MODE;
726
727         SMC_CFG = SMC_CFG_PAGESIZE_PS2048_64
728                 | SMC_CFG_EDGECTRL
729                 | SMC_CFG_DTOMUL_X1048576
730                 | SMC_CFG_DTOCYC(0xF)
731                 | SMC_CFG_WSPARE
732                 | SMC_CFG_RSPARE;
733
734         // Disable SMC interrupts, reset and enable NFC controller
735         SMC_IDR = ~0;
736         SMC_CTRL = 0;
737         SMC_CTRL = SMC_CTRL_NFCEN;
738
739         // Enable ECC, 1 ECC per 256 bytes
740         SMC_ECC_CTRL = SMC_ECC_CTRL_SWRST;
741         SMC_ECC_MD = SMC_ECC_MD_ECC_PAGESIZE_PS2048_64 | SMC_ECC_MD_TYPCORREC_C256B;
742 }
743
744
745 static bool commonInit(Mt29f *chip, struct Heap *heap, unsigned chip_select)
746 {
747         memset(chip, 0, sizeof(Mt29f));
748
749         DB(chip->fd.priv.type = KBT_NAND);
750         chip->fd.blk_size = MT29F_BLOCK_SIZE;
751         chip->fd.blk_cnt  = MT29F_NUM_USER_BLOCKS;
752
753         chip->chip_select = chip_select;
754         chip->block_map = heap_allocmem(heap, MT29F_NUM_BLOCKS * sizeof(*chip->block_map));
755         if (!chip->block_map)
756         {
757                 LOG_ERR("mt29f: error allocating block map\n");
758                 return false;
759         }
760
761         initPio();
762         initSmc();
763         chipReset(chip);
764         initBlockMap(chip);
765
766         return true;
767 }
768
769
770 /**************** Kblock interface ****************/
771
772
773 static size_t mt29f_writeDirect(struct KBlock *kblk, block_idx_t idx, const void *buf, size_t offset, size_t size)
774 {
775         ASSERT(offset <= MT29F_BLOCK_SIZE);
776         ASSERT(offset % MT29F_DATA_SIZE == 0);
777         ASSERT(size <= MT29F_BLOCK_SIZE);
778         ASSERT(size % MT29F_DATA_SIZE == 0);
779
780         //LOG_INFO("mt29f_writeDirect: idx=%ld offset=%d size=%d\n", idx, offset, size);
781
782         mt29f_blockErase(MT29F_CAST(kblk), idx);
783
784         while (offset < size)
785         {
786                 uint32_t page = PAGE(idx) + (offset / MT29F_DATA_SIZE);
787
788                 if (!mt29f_write(MT29F_CAST(kblk), page, buf, MT29F_DATA_SIZE))
789                         break;
790
791                 offset += MT29F_DATA_SIZE;
792                 buf = (const char *)buf + MT29F_DATA_SIZE;
793         }
794
795         return offset;
796 }
797
798
799 static size_t mt29f_readDirect(struct KBlock *kblk, block_idx_t idx, void *buf, size_t offset, size_t size)
800 {
801         uint32_t page;
802         size_t   read_size;
803         size_t   read_offset;
804         size_t   nread = 0;
805
806         ASSERT(offset < MT29F_BLOCK_SIZE);
807         ASSERT(size <= MT29F_BLOCK_SIZE);
808
809         //LOG_INFO("mt29f_readDirect: idx=%ld offset=%d size=%d\n", idx, offset, size);
810
811         while (nread < size)
812         {
813                 page        = PAGE(idx) + (offset / MT29F_DATA_SIZE);
814                 read_offset = offset % MT29F_DATA_SIZE;
815                 read_size   = MIN(size, MT29F_DATA_SIZE - read_offset);
816
817                 if (!mt29f_read(MT29F_CAST(kblk), page, (char *)buf + nread, read_offset, read_size))
818                         break;
819
820                 offset += read_size;
821                 nread  += read_size;
822         }
823
824         return nread;
825 }
826
827
828 static int mt29f_error(struct KBlock *kblk)
829 {
830         Mt29f *chip = MT29F_CAST(kblk);
831         return chip->status;
832 }
833
834
835 static void mt29f_clearError(struct KBlock *kblk)
836 {
837         Mt29f *chip = MT29F_CAST(kblk);
838         chip->status = 0;
839 }
840
841
842 static const KBlockVTable mt29f_buffered_vt =
843 {
844         .readDirect = mt29f_readDirect,
845         .writeDirect = mt29f_writeDirect,
846
847         .readBuf = kblock_swReadBuf,
848         .writeBuf = kblock_swWriteBuf,
849         .load = kblock_swLoad,
850         .store = kblock_swStore,
851
852         .error = mt29f_error,
853         .clearerr = mt29f_clearError,
854 };
855
856 static const KBlockVTable mt29f_unbuffered_vt =
857 {
858         .readDirect = mt29f_readDirect,
859         .writeDirect = mt29f_writeDirect,
860
861         .error = mt29f_error,
862         .clearerr = mt29f_clearError,
863 };
864
865
866 /**
867  * Initialize NAND kblock driver in buffered mode.
868  */
869 bool mt29f_init(Mt29f *chip, struct Heap *heap, unsigned chip_select)
870 {
871         if (!commonInit(chip, heap, chip_select))
872                 return false;
873
874         chip->fd.priv.vt = &mt29f_buffered_vt;
875         chip->fd.priv.flags |= KB_BUFFERED;
876
877         chip->fd.priv.buf = heap_allocmem(heap, MT29F_BLOCK_SIZE);
878         if (!chip->fd.priv.buf)
879         {
880                 LOG_ERR("mt29f: error allocating block buffer\n");
881                 return false;
882         }
883
884         // Load the first block in the cache
885         return mt29f_readDirect(&chip->fd, 0, chip->fd.priv.buf, 0, MT29F_DATA_SIZE);
886 }
887
888
889 /**
890  * Initialize NAND kblock driver in unbuffered mode.
891  */
892 bool mt29f_initUnbuffered(Mt29f *chip, struct Heap *heap, unsigned chip_select)
893 {
894         if (!commonInit(chip, heap, chip_select))
895                 return false;
896
897         chip->fd.priv.vt = &mt29f_unbuffered_vt;
898         return true;
899 }
900