e6a10279c10d8ce57f0cdac001a0c952b74b115f
[bertos.git] / bertos / drv / nand.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 * \brief Micron MT29F serial NAND driver
33 *
34 * This module allows read/write access to Micron MT29F serial
35 * NANDs.
36 *
37 * \author Stefano Fedrigo <aleph@develer.com>
38 */
39
40 #include "mt29f.h"
41
42 #include <cfg/log.h>
43 #include <struct/heap.h>
44 #include <string.h> // memset
45
46
47 /*
48  * Remap info written in the first page of each block
49  * used to remap bad blocks.
50  */
51 struct RemapInfo
52 {
53         uint32_t tag;         // Magic number to detect valid info
54         uint16_t mapped_blk;  // Bad block the block containing this info is remapping
55 };
56
57 #define MT29F_REMAP_TAG_OFFSET  (CONFIG_MT29F_SPARE_SIZE - sizeof(struct RemapInfo))
58 #define MT29F_REMAP_TAG         0x3e10c8ed
59
60 #define MT29F_ECC_NWORDS        (CONFIG_MT29F_DATA_SIZE / 256)
61
62 // NAND flash status codes
63 #define MT29F_STATUS_READY  BV(6)
64 #define MT29F_STATUS_ERROR  BV(0)
65
66
67 /*
68  * Translate flash page index plus a byte offset
69  * in the five address cycles format needed by NAND.
70  *
71  * Cycles in x8 mode as the MT29F2G08AAD
72  * CA = column addr, PA = page addr, BA = block addr
73  *
74  * Cycle    I/O7  I/O6  I/O5  I/O4  I/O3  I/O2  I/O1  I/O0
75  * -------------------------------------------------------
76  * First    CA7   CA6   CA5   CA4   CA3   CA2   CA1   CA0
77  * Second   LOW   LOW   LOW   LOW   CA11  CA10  CA9   CA8
78  * Third    BA7   BA6   PA5   PA4   PA3   PA2   PA1   PA0
79  * Fourth   BA15  BA14  BA13  BA12  BA11  BA10  BA9   BA8
80  * Fifth    LOW   LOW   LOW   LOW   LOW   LOW   LOW   BA16
81  */
82 static void getAddrCycles(uint32_t page, uint16_t offset, uint32_t *cycle0, uint32_t *cycle1234)
83 {
84         ASSERT(offset < MT29F_PAGE_SIZE);
85
86         *cycle0 = offset & 0xff;
87         *cycle1234 = (page << 8) | ((offset >> 8) & 0xf);
88
89         //LOG_INFO("mt29f addr: %lx %lx\n", *cycle1234, *cycle0);
90 }
91
92
93 static void chipReset(Mt29f *chip)
94 {
95         mt29f_sendCommand(chip, MT29F_CMD_RESET, 0, 0, 0, 0);
96         mt29f_waitReadyBusy(chip, CONFIG_MT29F_TMOUT);
97 }
98
99
100 static bool isOperationComplete(Mt29f *chip)
101 {
102         uint8_t status;
103
104         mt29f_sendCommand(chip, MT29F_CMD_STATUS, 0, 0, 0, 0);
105
106         status = mt29f_getChipStatus(chip);
107         return (status & MT29F_STATUS_READY) && !(status & MT29F_STATUS_ERROR);
108 }
109
110
111 /**
112  * Erase the whole block.
113  */
114 int mt29f_blockErase(Mt29f *chip, uint16_t block)
115 {
116         uint32_t cycle0;
117         uint32_t cycle1234;
118
119         uint16_t remapped_block = chip->block_map[block];
120         if (block != remapped_block)
121         {
122                 LOG_INFO("mt29f_blockErase: remapped block: blk %d->%d\n", block, remapped_block);
123                 block = remapped_block;
124         }
125
126         getAddrCycles(PAGE(block), 0, &cycle0, &cycle1234);
127
128         mt29f_sendCommand(chip, MT29F_CMD_ERASE_1, MT29F_CMD_ERASE_2, 3, 0, cycle1234 >> 8);
129
130         mt29f_waitReadyBusy(chip, CONFIG_MT29F_TMOUT);
131
132         if (!isOperationComplete(chip))
133         {
134                 LOG_ERR("mt29f: error erasing block\n");
135                 chip->status |= MT29F_ERR_ERASE;
136                 return -1;
137         }
138
139         return 0;
140 }
141
142
143 /**
144  * Read Device ID and configuration codes.
145  */
146 bool mt29f_getDevId(Mt29f *chip, uint8_t dev_id[5])
147 {
148         mt29f_sendCommand(chip, MT29F_CMD_READID, 0, 1, 0, 0);
149
150         mt29f_waitReadyBusy(chip, CONFIG_MT29F_TMOUT);
151         if (!mt29f_waitTransferComplete(chip, CONFIG_MT29F_TMOUT))
152         {
153                 LOG_ERR("mt29f: getDevId timeout\n");
154                 chip->status |= MT29F_ERR_RD_TMOUT;
155                 return false;
156         }
157
158         memcpy(dev_id, mt29f_dataBuffer(chip), sizeof(dev_id));
159         return true;
160 }
161
162
163 static bool mt29f_readPage(Mt29f *chip, uint32_t page, uint16_t offset)
164 {
165         uint32_t cycle0;
166         uint32_t cycle1234;
167
168         //LOG_INFO("mt29f_readPage: page 0x%lx off 0x%x\n", page, offset);
169
170         getAddrCycles(page, offset, &cycle0, &cycle1234);
171
172         mt29f_sendCommand(chip, MT29F_CMD_READ_1, MT29F_CMD_READ_2, 5, cycle0, cycle1234);
173
174         mt29f_waitReadyBusy(chip, CONFIG_MT29F_TMOUT);
175         if (!mt29f_waitTransferComplete(chip, CONFIG_MT29F_TMOUT))
176         {
177                 LOG_ERR("mt29f: read timeout\n");
178                 chip->status |= MT29F_ERR_RD_TMOUT;
179                 return false;
180         }
181
182         return true;
183 }
184
185
186 /*
187  * Read page data and ECC, checking for errors.
188  * TODO: fix errors with ECC when possible.
189  */
190 static bool mt29f_read(Mt29f *chip, uint32_t page, void *buf, uint16_t offset, uint16_t size)
191 {
192         struct RemapInfo remap_info;
193         uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
194
195         //LOG_INFO("mt29f_read: page=%ld, offset=%d, size=%d\n", page, offset, size);
196
197         if (page != remapped_page)
198         {
199                 LOG_INFO("mt29f_read: remapped block: blk %d->%d, pg %ld->%ld\n",
200                                 BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
201                 page = remapped_page;
202         }
203
204         if (!mt29f_readPage(chip, page, 0))
205                 return false;
206
207         memcpy(buf, (char *)mt29f_dataBuffer(chip) + offset, size);
208
209         /*
210          * Check for ECC hardware status only if a valid RemapInfo structure is found.
211          * That guarantees the page is written by us and a valid ECC is present.
212          */
213         memcpy(&remap_info, (char *)buf + MT29F_REMAP_TAG_OFFSET, sizeof(remap_info));
214         if (remap_info.tag == MT29F_REMAP_TAG)
215                 return mt29f_checkEcc(chip);
216         else
217                 return true;
218 }
219
220
221 /*
222  * Write data in NFC SRAM buffer to a NAND page, starting at a given offset.
223  * Usually offset will be 0 to write data or CONFIG_MT29F_DATA_SIZE to write the spare
224  * area.
225  *
226  * According to datasheet to get ECC computed by hardware is sufficient
227  * to write the main area.  But it seems that in that way the last ECC_PR
228  * register is not generated.  The workaround is to write data and dummy (ff)
229  * spare data in one write, at this point the last ECC_PR is correct and
230  * ECC data can be written in the spare area with a second program operation.
231  */
232 static bool mt29f_writePage(Mt29f *chip, uint32_t page, uint16_t offset)
233 {
234         uint32_t cycle0;
235         uint32_t cycle1234;
236
237         //LOG_INFO("mt29f_writePage: page 0x%lx off 0x%x\n", page, offset);
238
239         getAddrCycles(page, offset, &cycle0, &cycle1234);
240
241         mt29f_sendCommand(chip, MT29F_CMD_WRITE_1, 0, 5, cycle0, cycle1234);
242
243         if (!mt29f_waitTransferComplete(chip, CONFIG_MT29F_TMOUT))
244         {
245                 LOG_ERR("mt29f: write timeout\n");
246                 chip->status |= MT29F_ERR_WR_TMOUT;
247                 return false;
248         }
249
250         mt29f_sendCommand(chip, MT29F_CMD_WRITE_2, 0, 0, 0, 0);
251
252         mt29f_waitReadyBusy(chip, CONFIG_MT29F_TMOUT);
253
254         if (!isOperationComplete(chip))
255         {
256                 LOG_ERR("mt29f: error writing page\n");
257                 chip->status |= MT29F_ERR_WRITE;
258                 return false;
259         }
260
261         return true;
262 }
263
264
265 /*
266  * Write data, ECC and remap block info.
267  *
268  * \param page           the page to be written
269  * \parma original_page  if different from page, it's the page that's being remapped
270  *
271  * ECC data are extracted from ECC_PRx registers and written
272  * in the page's spare area.
273  * For 2048 bytes pages and 1 ECC word each 256 bytes,
274  * 24 bytes of ECC data are stored.
275  */
276 static bool mt29f_write(Mt29f *chip, uint32_t page, const void *buf, size_t size)
277 {
278         struct RemapInfo remap_info;
279         uint32_t *nand_buf = (uint32_t *)mt29f_dataBuffer(chip);
280         uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
281
282         ASSERT(size <= CONFIG_MT29F_DATA_SIZE);
283
284         if (page != remapped_page)
285                 LOG_INFO("mt29f_write: remapped block: blk %d->%d, pg %ld->%ld\n",
286                                 BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
287
288         // Data
289         memset(nand_buf, 0xff, MT29F_PAGE_SIZE);
290         memcpy(nand_buf, buf, size);
291         if (!mt29f_writePage(chip, remapped_page, 0))
292                 return false;
293
294         // ECC
295         memset(nand_buf, 0xff, CONFIG_MT29F_SPARE_SIZE);
296         mt29f_computeEcc(chip, buf, size, nand_buf, MT29F_ECC_NWORDS);
297
298         // Remap info
299         remap_info.tag = MT29F_REMAP_TAG;
300         remap_info.mapped_blk = BLOCK(page);
301         memcpy((char *)nand_buf + MT29F_REMAP_TAG_OFFSET, &remap_info, sizeof(remap_info));
302
303         return mt29f_writePage(chip, remapped_page, CONFIG_MT29F_DATA_SIZE);
304 }
305
306
307 /*
308  * Check if the given block is marked bad: ONFI standard mandates
309  * that bad block are marked with "00" bytes on the spare area of the
310  * first page in block.
311  */
312 static bool blockIsGood(Mt29f *chip, uint16_t blk)
313 {
314         uint8_t *first_byte = (uint8_t *)mt29f_dataBuffer(chip);
315         bool good;
316
317         // Check first byte in spare area of first page in block
318         mt29f_readPage(chip, PAGE(blk), CONFIG_MT29F_DATA_SIZE);
319         good = *first_byte != 0;
320
321         if (!good)
322                 LOG_INFO("mt29f: bad block %d\n", blk);
323
324         return good;
325 }
326
327
328 /*
329  * Return the main partition block remapped on given block in the remap
330  * partition (dest_blk).
331  */
332 static int getBadBlockFromRemapBlock(Mt29f *chip, uint16_t dest_blk)
333 {
334         struct RemapInfo *remap_info = (struct RemapInfo *)mt29f_dataBuffer(chip);
335
336         if (!mt29f_readPage(chip, PAGE(dest_blk), CONFIG_MT29F_DATA_SIZE + MT29F_REMAP_TAG_OFFSET))
337                 return -1;
338
339         if (remap_info->tag == MT29F_REMAP_TAG)
340                 return remap_info->mapped_blk;
341         else
342                 return -1;
343 }
344
345
346 /*
347  * Set a block remapping: src_blk (a block in main data partition) is remappend
348  * on dest_blk (block in reserved remapped blocks partition).
349  */
350 static bool setMapping(Mt29f *chip, uint32_t src_blk, uint32_t dest_blk)
351 {
352         struct RemapInfo *remap_info = (struct RemapInfo *)mt29f_dataBuffer(chip);
353
354         LOG_INFO("mt29f, setMapping(): src=%ld dst=%ld\n", src_blk, dest_blk);
355
356         if (!mt29f_readPage(chip, PAGE(dest_blk), CONFIG_MT29F_DATA_SIZE + MT29F_REMAP_TAG_OFFSET))
357                 return false;
358
359         remap_info->tag = MT29F_REMAP_TAG;
360         remap_info->mapped_blk = src_blk;
361
362         return mt29f_writePage(chip, PAGE(dest_blk), CONFIG_MT29F_DATA_SIZE + MT29F_REMAP_TAG_OFFSET);
363 }
364
365
366 /*
367  * Get a new block from the remap partition to use as a substitute
368  * for a bad block.
369  */
370 static uint16_t getFreeRemapBlock(Mt29f *chip)
371 {
372         int blk;
373
374         for (blk = chip->remap_start; blk < CONFIG_MT29F_NUM_BLOCK; blk++)
375         {
376                 if (blockIsGood(chip, blk))
377                 {
378                         chip->remap_start = blk + 1;
379                         return blk;
380                 }
381         }
382
383         LOG_ERR("mt29f: reserved blocks for bad block remapping exhausted!\n");
384         return 0;
385 }
386
387
388 /*
389  * Check if NAND is initialized.
390  */
391 static bool chipIsMarked(Mt29f *chip)
392 {
393         return getBadBlockFromRemapBlock(chip, MT29F_NUM_USER_BLOCKS) != -1;
394 }
395
396
397 /*
398  * Initialize NAND (format). Scan NAND for factory marked bad blocks.
399  * All bad blocks found are remapped to the remap partition: each
400  * block in the remap partition used to remap bad blocks is marked.
401  */
402 static void initBlockMap(Mt29f *chip)
403 {
404         int b, last;
405
406         // Default is for each block to not be remapped
407         for (b = 0; b < CONFIG_MT29F_NUM_BLOCK; b++)
408                 chip->block_map[b] = b;
409         chip->remap_start = MT29F_NUM_USER_BLOCKS;
410
411         if (chipIsMarked(chip))
412         {
413                 LOG_INFO("mt29f: found initialized NAND, searching for remapped blocks\n");
414
415                 // Scan for assigned blocks in remap area
416                 for (b = last = MT29F_NUM_USER_BLOCKS; b < CONFIG_MT29F_NUM_BLOCK; b++)
417                 {
418                         int remapped_blk = getBadBlockFromRemapBlock(chip, b);
419                         if (remapped_blk != -1 && remapped_blk != b)
420                         {
421                                 LOG_INFO("mt29f: found remapped block %d->%d\n", remapped_blk, b);
422                                 chip->block_map[remapped_blk] = b;
423                                 last = b + 1;
424                         }
425                 }
426                 chip->remap_start = last;
427         }
428         else
429         {
430                 bool remapped_anything = false;
431
432                 LOG_INFO("mt29f: found new NAND, searching for bad blocks\n");
433
434                 for (b = 0; b < MT29F_NUM_USER_BLOCKS; b++)
435                 {
436                         if (!blockIsGood(chip, b))
437                         {
438                                 chip->block_map[b] = getFreeRemapBlock(chip);
439                                 setMapping(chip, b, chip->block_map[b]);
440                                 remapped_anything = true;
441                                 LOG_INFO("mt29f: found new bad block %d, remapped to %d\n", b, chip->block_map[b]);
442                         }
443                 }
444
445                 /*
446              * If no bad blocks are found (we're lucky!) write a dummy
447                  * remap to mark NAND and detect we already scanned it next time.
448                  */
449                 if (!remapped_anything)
450                 {
451                         setMapping(chip, MT29F_NUM_USER_BLOCKS, MT29F_NUM_USER_BLOCKS);
452                         LOG_INFO("mt29f: no bad block founds, marked NAND\n");
453                 }
454         }
455 }
456
457
458 /**
459  * Reset bad blocks map and erase all blocks.
460  *
461  * \note DON'T USE on production chips: this function will try to erase
462  *       factory marked bad blocks too.
463  */
464 void mt29f_format(Mt29f *chip)
465 {
466         int b;
467
468         for (b = 0; b < CONFIG_MT29F_NUM_BLOCK; b++)
469         {
470                 LOG_INFO("mt29f: erasing block %d\n", b);
471                 chip->block_map[b] = b;
472                 mt29f_blockErase(chip, b);
473         }
474         chip->remap_start = MT29F_NUM_USER_BLOCKS;
475 }
476
477 #ifdef _DEBUG
478
479 /*
480  * Create some bad blocks, erasing them and writing the bad block mark.
481  */
482 void mt29f_ruinSomeBlocks(Mt29f *chip)
483 {
484         int bads[] = { 7, 99, 555, 1003, 1004, 1432 };
485         unsigned i;
486
487         LOG_INFO("mt29f: erasing mark\n");
488         mt29f_blockErase(chip, MT29F_NUM_USER_BLOCKS);
489
490         for (i = 0; i < countof(bads); i++)
491         {
492                 LOG_INFO("mt29f: erasing block %d\n", bads[i]);
493                 mt29f_blockErase(chip, bads[i]);
494
495                 LOG_INFO("mt29f: marking page %d as bad\n", PAGE(bads[i]));
496                 memset(mt29f_dataBuffer(chip), 0, CONFIG_MT29F_SPARE_SIZE);
497                 mt29f_writePage(chip, PAGE(bads[i]), CONFIG_MT29F_DATA_SIZE);
498         }
499 }
500
501 #endif
502
503 static bool commonInit(Mt29f *chip, struct Heap *heap, unsigned chip_select)
504 {
505         memset(chip, 0, sizeof(Mt29f));
506
507         DB(chip->fd.priv.type = KBT_NAND);
508         chip->fd.blk_size = MT29F_BLOCK_SIZE;
509         chip->fd.blk_cnt  = MT29F_NUM_USER_BLOCKS;
510
511         chip->chip_select = chip_select;
512         chip->block_map = heap_allocmem(heap, CONFIG_MT29F_NUM_BLOCK * sizeof(*chip->block_map));
513         if (!chip->block_map)
514         {
515                 LOG_ERR("mt29f: error allocating block map\n");
516                 return false;
517         }
518
519         mt29f_hwInit(chip);
520         chipReset(chip);
521         initBlockMap(chip);
522
523         return true;
524 }
525
526
527 /**************** Kblock interface ****************/
528
529
530 static size_t mt29f_writeDirect(struct KBlock *kblk, block_idx_t idx, const void *buf, size_t offset, size_t size)
531 {
532         ASSERT(offset <= MT29F_BLOCK_SIZE);
533         ASSERT(offset % CONFIG_MT29F_DATA_SIZE == 0);
534         ASSERT(size <= MT29F_BLOCK_SIZE);
535         ASSERT(size % CONFIG_MT29F_DATA_SIZE == 0);
536
537         //LOG_INFO("mt29f_writeDirect: idx=%ld offset=%d size=%d\n", idx, offset, size);
538
539         mt29f_blockErase(MT29F_CAST(kblk), idx);
540
541         while (offset < size)
542         {
543                 uint32_t page = PAGE(idx) + (offset / CONFIG_MT29F_DATA_SIZE);
544
545                 if (!mt29f_write(MT29F_CAST(kblk), page, buf, CONFIG_MT29F_DATA_SIZE))
546                         break;
547
548                 offset += CONFIG_MT29F_DATA_SIZE;
549                 buf = (const char *)buf + CONFIG_MT29F_DATA_SIZE;
550         }
551
552         return offset;
553 }
554
555
556 static size_t mt29f_readDirect(struct KBlock *kblk, block_idx_t idx, void *buf, size_t offset, size_t size)
557 {
558         uint32_t page;
559         size_t   read_size;
560         size_t   read_offset;
561         size_t   nread = 0;
562
563         ASSERT(offset < MT29F_BLOCK_SIZE);
564         ASSERT(size <= MT29F_BLOCK_SIZE);
565
566         //LOG_INFO("mt29f_readDirect: idx=%ld offset=%d size=%d\n", idx, offset, size);
567
568         while (nread < size)
569         {
570                 page        = PAGE(idx) + (offset / CONFIG_MT29F_DATA_SIZE);
571                 read_offset = offset % CONFIG_MT29F_DATA_SIZE;
572                 read_size   = MIN(size, CONFIG_MT29F_DATA_SIZE - read_offset);
573
574                 if (!mt29f_read(MT29F_CAST(kblk), page, (char *)buf + nread, read_offset, read_size))
575                         break;
576
577                 offset += read_size;
578                 nread  += read_size;
579         }
580
581         return nread;
582 }
583
584
585 static int mt29f_error(struct KBlock *kblk)
586 {
587         Mt29f *chip = MT29F_CAST(kblk);
588         return chip->status;
589 }
590
591
592 static void mt29f_clearError(struct KBlock *kblk)
593 {
594         Mt29f *chip = MT29F_CAST(kblk);
595         chip->status = 0;
596 }
597
598
599 static const KBlockVTable mt29f_buffered_vt =
600 {
601         .readDirect = mt29f_readDirect,
602         .writeDirect = mt29f_writeDirect,
603
604         .readBuf = kblock_swReadBuf,
605         .writeBuf = kblock_swWriteBuf,
606         .load = kblock_swLoad,
607         .store = kblock_swStore,
608
609         .error = mt29f_error,
610         .clearerr = mt29f_clearError,
611 };
612
613 static const KBlockVTable mt29f_unbuffered_vt =
614 {
615         .readDirect = mt29f_readDirect,
616         .writeDirect = mt29f_writeDirect,
617
618         .error = mt29f_error,
619         .clearerr = mt29f_clearError,
620 };
621
622
623 /**
624  * Initialize NAND kblock driver in buffered mode.
625  */
626 bool mt29f_init(Mt29f *chip, struct Heap *heap, unsigned chip_select)
627 {
628         if (!commonInit(chip, heap, chip_select))
629                 return false;
630
631         chip->fd.priv.vt = &mt29f_buffered_vt;
632         chip->fd.priv.flags |= KB_BUFFERED;
633
634         chip->fd.priv.buf = heap_allocmem(heap, MT29F_BLOCK_SIZE);
635         if (!chip->fd.priv.buf)
636         {
637                 LOG_ERR("mt29f: error allocating block buffer\n");
638                 return false;
639         }
640
641         // Load the first block in the cache
642         return mt29f_readDirect(&chip->fd, 0, chip->fd.priv.buf, 0, chip->fd.blk_size);
643 }
644
645
646 /**
647  * Initialize NAND kblock driver in unbuffered mode.
648  */
649 bool mt29f_initUnbuffered(Mt29f *chip, struct Heap *heap, unsigned chip_select)
650 {
651         if (!commonInit(chip, heap, chip_select))
652                 return false;
653
654         chip->fd.priv.vt = &mt29f_unbuffered_vt;
655         return true;
656 }
657