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