4 * This file is part of BeRTOS.
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.
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.
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
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.
29 * Copyright 2011 Develer S.r.l. (http://www.develer.com/)
32 * \brief ONFI 1.0 compliant NAND kblock driver
34 * Defective blocks are remapped in a reserved area of configurable size
35 * at the bottom of the NAND.
36 * At the moment there is no wear-leveling block translation: kblock's blocks
37 * are mapped directly on NAND erase blocks: when a (k)block is written the
38 * corresponding erase block is erased and all pages within are rewritten.
39 * Partial write is not possible: it's recommended to use buffered mode.
41 * The driver needs to format the NAND before use. If the initialization code
42 * detects a fresh memory it does a bad block scan and a formatting.
43 * Format info isn't stored in NAND in a global structure: each block has its
44 * info written in the spare area of its first page. These info contais a tag
45 * to detect formatted blocks and an index for bad block remapping (struct
48 * The ECC for each page is written in the spare area too.
50 * Works only in 8 bit data mode and NAND parameters are not
51 * detected at run-time, but hand-configured in cfg_nand.h.
53 * Heap is needed to allocate the tipically large buffer necessary
54 * to erase and write a block.
56 * \author Stefano Fedrigo <aleph@develer.com>
63 #include <struct/heap.h>
64 #include <string.h> // memset
68 * Remap info written in the first page of each block.
70 * This structure is used in blocks of the reserved area to store
71 * which block the block containing the structure is remapping.
72 * It's stored in all other blocks too to mark a formatted block.
73 * In this case the member mapped_blk has non meaning.
77 uint32_t tag; // Magic number to detect valid info
78 uint16_t mapped_blk; // Bad block the block containing this info is remapping
81 // Where RemapInfo is stored in the spare area
82 #define NAND_REMAP_TAG_OFFSET (CONFIG_NAND_SPARE_SIZE - sizeof(struct RemapInfo))
84 // Fixed tag to detect RemapInfo
85 #define NAND_REMAP_TAG 0x3e10c8ed
88 * Number of ECC words computed for a page.
90 * For 2048 bytes pages and 1 ECC word each 256 bytes,
91 * 24 bytes of ECC data are stored.
93 #define NAND_ECC_NWORDS (CONFIG_NAND_DATA_SIZE / 256)
95 // Total page size (user data + spare) in bytes
96 #define NAND_PAGE_SIZE (CONFIG_NAND_DATA_SIZE + CONFIG_NAND_SPARE_SIZE)
98 // Erase block size in bytes
99 #define NAND_BLOCK_SIZE (CONFIG_NAND_DATA_SIZE * CONFIG_NAND_PAGES_PER_BLOCK)
101 // Number of usable blocks, and index of first remapping block
102 #define NAND_NUM_USER_BLOCKS (CONFIG_NAND_NUM_BLOCK - CONFIG_NAND_NUM_REMAP_BLOCKS)
104 // ONFI NAND status codes
105 #define NAND_STATUS_READY BV(6)
106 #define NAND_STATUS_ERROR BV(0)
109 // Get block from page
110 #define PAGE(blk) ((blk) * CONFIG_NAND_PAGES_PER_BLOCK)
112 // Page from block and page in block
113 #define BLOCK(page) ((uint16_t)((page) / CONFIG_NAND_PAGES_PER_BLOCK))
114 #define PAGE_IN_BLOCK(page) ((uint16_t)((page) % CONFIG_NAND_PAGES_PER_BLOCK))
118 * Translate page index plus a byte offset
119 * in the five address cycles format needed by NAND.
122 * CA = column addr, PA = page addr, BA = block addr
124 * Cycle I/O7 I/O6 I/O5 I/O4 I/O3 I/O2 I/O1 I/O0
125 * -------------------------------------------------------
126 * First CA7 CA6 CA5 CA4 CA3 CA2 CA1 CA0
127 * Second LOW LOW LOW LOW CA11 CA10 CA9 CA8
128 * Third BA7 BA6 PA5 PA4 PA3 PA2 PA1 PA0
129 * Fourth BA15 BA14 BA13 BA12 BA11 BA10 BA9 BA8
130 * Fifth LOW LOW LOW LOW LOW LOW LOW BA16
132 static void getAddrCycles(uint32_t page, uint16_t offset, uint32_t *cycle0, uint32_t *cycle1234)
134 ASSERT(offset < NAND_PAGE_SIZE);
136 *cycle0 = offset & 0xff;
137 *cycle1234 = (page << 8) | ((offset >> 8) & 0xf);
139 //LOG_INFO("nand addr: %lx %lx\n", *cycle1234, *cycle0);
143 static void chipReset(Nand *chip)
145 nand_sendCommand(chip, NAND_CMD_RESET, 0, 0, 0, 0);
146 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
150 static bool isOperationComplete(Nand *chip)
154 nand_sendCommand(chip, NAND_CMD_STATUS, 0, 0, 0, 0);
156 status = nand_getChipStatus(chip);
157 return (status & NAND_STATUS_READY) && !(status & NAND_STATUS_ERROR);
162 * Erase the whole block.
164 int nand_blockErase(Nand *chip, uint16_t block)
169 uint16_t remapped_block = chip->block_map[block];
170 if (block != remapped_block)
172 LOG_INFO("nand_blockErase: remapped block: blk %d->%d\n", block, remapped_block);
173 block = remapped_block;
176 getAddrCycles(PAGE(block), 0, &cycle0, &cycle1234);
178 nand_sendCommand(chip, NAND_CMD_ERASE_1, NAND_CMD_ERASE_2, 3, 0, cycle1234 >> 8);
180 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
182 if (!isOperationComplete(chip))
184 LOG_ERR("nand: error erasing block\n");
185 chip->status |= NAND_ERR_ERASE;
194 * Read Device ID and configuration codes.
196 bool nand_getDevId(Nand *chip, uint8_t dev_id[5])
198 nand_sendCommand(chip, NAND_CMD_READID, 0, 1, 0, 0);
200 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
201 if (!nand_waitTransferComplete(chip, CONFIG_NAND_TMOUT))
203 LOG_ERR("nand: getDevId timeout\n");
204 chip->status |= NAND_ERR_RD_TMOUT;
208 memcpy(dev_id, nand_dataBuffer(chip), sizeof(dev_id));
213 static bool nand_readPage(Nand *chip, uint32_t page, uint16_t offset)
218 //LOG_INFO("nand_readPage: page 0x%lx off 0x%x\n", page, offset);
220 getAddrCycles(page, offset, &cycle0, &cycle1234);
222 nand_sendCommand(chip, NAND_CMD_READ_1, NAND_CMD_READ_2, 5, cycle0, cycle1234);
224 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
225 if (!nand_waitTransferComplete(chip, CONFIG_NAND_TMOUT))
227 LOG_ERR("nand: read timeout\n");
228 chip->status |= NAND_ERR_RD_TMOUT;
237 * Read page data and ECC, checking for errors.
238 * TODO: fix errors with ECC when possible.
240 static bool nand_read(Nand *chip, uint32_t page, void *buf, uint16_t offset, uint16_t size)
242 struct RemapInfo remap_info;
243 uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
245 //LOG_INFO("nand_read: page=%ld, offset=%d, size=%d\n", page, offset, size);
247 if (page != remapped_page)
249 LOG_INFO("nand_read: remapped block: blk %d->%d, pg %ld->%ld\n",
250 BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
251 page = remapped_page;
254 if (!nand_readPage(chip, page, 0))
257 memcpy(buf, (char *)nand_dataBuffer(chip) + offset, size);
260 * Check for ECC hardware status only if a valid RemapInfo structure is found.
261 * That guarantees the page is written by us and a valid ECC is present.
263 memcpy(&remap_info, (char *)buf + NAND_REMAP_TAG_OFFSET, sizeof(remap_info));
264 if (remap_info.tag == NAND_REMAP_TAG && !nand_checkEcc(chip))
266 chip->status |= NAND_ERR_ECC;
275 * Write data stored in nand_dataBuffer() to a NAND page, starting at a given offset.
276 * Usually offset will be 0 to write data or CONFIG_NAND_DATA_SIZE to write the spare
279 static bool nand_writePage(Nand *chip, uint32_t page, uint16_t offset)
284 //LOG_INFO("nand_writePage: page 0x%lx off 0x%x\n", page, offset);
286 getAddrCycles(page, offset, &cycle0, &cycle1234);
288 nand_sendCommand(chip, NAND_CMD_WRITE_1, 0, 5, cycle0, cycle1234);
290 if (!nand_waitTransferComplete(chip, CONFIG_NAND_TMOUT))
292 LOG_ERR("nand: write timeout\n");
293 chip->status |= NAND_ERR_WR_TMOUT;
297 nand_sendCommand(chip, NAND_CMD_WRITE_2, 0, 0, 0, 0);
299 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
301 if (!isOperationComplete(chip))
303 LOG_ERR("nand: error writing page\n");
304 chip->status |= NAND_ERR_WRITE;
313 * Write data, ECC and remap block info.
315 * \param page the page to be written
316 * \parma original_page if different from page, it's the page that's being remapped
318 * Implementation note for SAM3 NFC controller:
319 * according to datasheet to get ECC computed by hardware is sufficient
320 * to write the main area. But it seems that in that way the last ECC_PR
321 * register is not generated. The workaround is to write data and dummy (ff)
322 * spare data in one write, at this point the last ECC_PR is correct and
323 * ECC data can be written in the spare area with a second program operation.
325 static bool nand_write(Nand *chip, uint32_t page, const void *buf, size_t size)
327 struct RemapInfo remap_info;
328 uint32_t *nand_buf = (uint32_t *)nand_dataBuffer(chip);
329 uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
331 ASSERT(size <= CONFIG_NAND_DATA_SIZE);
333 if (page != remapped_page)
334 LOG_INFO("nand_write: remapped block: blk %d->%d, pg %ld->%ld\n",
335 BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
338 memset(nand_buf, 0xff, NAND_PAGE_SIZE);
339 memcpy(nand_buf, buf, size);
340 if (!nand_writePage(chip, remapped_page, 0))
344 memset(nand_buf, 0xff, CONFIG_NAND_SPARE_SIZE);
345 nand_computeEcc(chip, buf, size, nand_buf, NAND_ECC_NWORDS);
348 remap_info.tag = NAND_REMAP_TAG;
349 remap_info.mapped_blk = BLOCK(page);
350 memcpy((char *)nand_buf + NAND_REMAP_TAG_OFFSET, &remap_info, sizeof(remap_info));
352 return nand_writePage(chip, remapped_page, CONFIG_NAND_DATA_SIZE);
357 * Check if the given block is marked bad: ONFI standard mandates
358 * that bad block are marked with "00" bytes on the spare area of the
359 * first page in block.
361 static bool blockIsGood(Nand *chip, uint16_t blk)
363 uint8_t *first_byte = (uint8_t *)nand_dataBuffer(chip);
366 // Check first byte in spare area of first page in block
367 nand_readPage(chip, PAGE(blk), CONFIG_NAND_DATA_SIZE);
368 good = *first_byte != 0;
371 LOG_INFO("nand: bad block %d\n", blk);
378 * Return the main partition block remapped on given block in the remap
379 * partition (dest_blk).
381 static int getBadBlockFromRemapBlock(Nand *chip, uint16_t dest_blk)
383 struct RemapInfo *remap_info = (struct RemapInfo *)nand_dataBuffer(chip);
385 if (!nand_readPage(chip, PAGE(dest_blk), CONFIG_NAND_DATA_SIZE + NAND_REMAP_TAG_OFFSET))
388 if (remap_info->tag == NAND_REMAP_TAG)
389 return remap_info->mapped_blk;
396 * Set a block remapping: src_blk (a block in main data partition) is remapped
397 * on dest_blk (block in reserved remapped blocks partition).
399 static bool setMapping(Nand *chip, uint32_t src_blk, uint32_t dest_blk)
401 struct RemapInfo *remap_info = (struct RemapInfo *)nand_dataBuffer(chip);
403 LOG_INFO("nand, setMapping(): src=%ld dst=%ld\n", src_blk, dest_blk);
405 if (!nand_readPage(chip, PAGE(dest_blk), CONFIG_NAND_DATA_SIZE + NAND_REMAP_TAG_OFFSET))
408 remap_info->tag = NAND_REMAP_TAG;
409 remap_info->mapped_blk = src_blk;
411 return nand_writePage(chip, PAGE(dest_blk), CONFIG_NAND_DATA_SIZE + NAND_REMAP_TAG_OFFSET);
416 * Get a new block from the remap partition to use as a substitute
419 static uint16_t getFreeRemapBlock(Nand *chip)
423 for (blk = chip->remap_start; blk < CONFIG_NAND_NUM_BLOCK; blk++)
425 if (blockIsGood(chip, blk))
427 chip->remap_start = blk + 1;
432 LOG_ERR("nand: reserved blocks for bad block remapping exhausted!\n");
438 * Check if NAND is initialized.
440 static bool chipIsMarked(Nand *chip)
442 return getBadBlockFromRemapBlock(chip, NAND_NUM_USER_BLOCKS) != -1;
447 * Initialize NAND (format). Scan NAND for factory marked bad blocks.
448 * All found bad blocks are remapped to the remap partition: each
449 * block in the remap partition used to remap bad blocks is marked.
451 static void initBlockMap(Nand *chip)
455 // Default is for each block to not be remapped
456 for (b = 0; b < CONFIG_NAND_NUM_BLOCK; b++)
457 chip->block_map[b] = b;
458 chip->remap_start = NAND_NUM_USER_BLOCKS;
460 if (chipIsMarked(chip))
462 LOG_INFO("nand: found initialized NAND, searching for remapped blocks\n");
464 // Scan for assigned blocks in remap area
465 for (b = last = NAND_NUM_USER_BLOCKS; b < CONFIG_NAND_NUM_BLOCK; b++)
467 int remapped_blk = getBadBlockFromRemapBlock(chip, b);
468 if (remapped_blk != -1 && remapped_blk != b)
470 LOG_INFO("nand: found remapped block %d->%d\n", remapped_blk, b);
471 chip->block_map[remapped_blk] = b;
475 chip->remap_start = last;
479 bool remapped_anything = false;
481 LOG_INFO("nand: found new NAND, searching for bad blocks\n");
483 for (b = 0; b < NAND_NUM_USER_BLOCKS; b++)
485 if (!blockIsGood(chip, b))
487 chip->block_map[b] = getFreeRemapBlock(chip);
488 setMapping(chip, b, chip->block_map[b]);
489 remapped_anything = true;
490 LOG_INFO("nand: found new bad block %d, remapped to %d\n", b, chip->block_map[b]);
495 * If no bad blocks are found (we're lucky!) write anyway a dummy
496 * remap to mark NAND and detect we already scanned it next time.
498 if (!remapped_anything)
500 setMapping(chip, NAND_NUM_USER_BLOCKS, NAND_NUM_USER_BLOCKS);
501 LOG_INFO("nand: no bad block founds, marked NAND\n");
508 * Reset bad blocks map and erase all blocks.
510 * \note DON'T USE on production chips: this function will try to erase
511 * factory marked bad blocks too.
513 void nand_format(Nand *chip)
517 for (b = 0; b < CONFIG_NAND_NUM_BLOCK; b++)
519 LOG_INFO("nand: erasing block %d\n", b);
520 chip->block_map[b] = b;
521 nand_blockErase(chip, b);
523 chip->remap_start = NAND_NUM_USER_BLOCKS;
529 * Create some bad blocks, erasing them and writing the bad block mark.
531 void nand_ruinSomeBlocks(Nand *chip)
533 int bads[] = { 7, 99, 555, 1003, 1004, 1432 };
536 LOG_INFO("nand: erasing mark\n");
537 nand_blockErase(chip, NAND_NUM_USER_BLOCKS);
539 for (i = 0; i < countof(bads); i++)
541 LOG_INFO("nand: erasing block %d\n", bads[i]);
542 nand_blockErase(chip, bads[i]);
544 LOG_INFO("nand: marking page %d as bad\n", PAGE(bads[i]));
545 memset(nand_dataBuffer(chip), 0, CONFIG_NAND_SPARE_SIZE);
546 nand_writePage(chip, PAGE(bads[i]), CONFIG_NAND_DATA_SIZE);
552 static bool commonInit(Nand *chip, struct Heap *heap, unsigned chip_select)
554 memset(chip, 0, sizeof(Nand));
556 DB(chip->fd.priv.type = KBT_NAND);
557 chip->fd.blk_size = NAND_BLOCK_SIZE;
558 chip->fd.blk_cnt = NAND_NUM_USER_BLOCKS;
560 chip->chip_select = chip_select;
561 chip->block_map = heap_allocmem(heap, CONFIG_NAND_NUM_BLOCK * sizeof(*chip->block_map));
562 if (!chip->block_map)
564 LOG_ERR("nand: error allocating block map\n");
576 /**************** Kblock interface ****************/
579 static size_t nand_writeDirect(struct KBlock *kblk, block_idx_t idx, const void *buf, size_t offset, size_t size)
581 ASSERT(offset <= NAND_BLOCK_SIZE);
582 ASSERT(offset % CONFIG_NAND_DATA_SIZE == 0);
583 ASSERT(size <= NAND_BLOCK_SIZE);
584 ASSERT(size % CONFIG_NAND_DATA_SIZE == 0);
586 //LOG_INFO("nand_writeDirect: idx=%ld offset=%d size=%d\n", idx, offset, size);
588 nand_blockErase(NAND_CAST(kblk), idx);
590 while (offset < size)
592 uint32_t page = PAGE(idx) + (offset / CONFIG_NAND_DATA_SIZE);
594 if (!nand_write(NAND_CAST(kblk), page, buf, CONFIG_NAND_DATA_SIZE))
597 offset += CONFIG_NAND_DATA_SIZE;
598 buf = (const char *)buf + CONFIG_NAND_DATA_SIZE;
605 static size_t nand_readDirect(struct KBlock *kblk, block_idx_t idx, void *buf, size_t offset, size_t size)
612 ASSERT(offset < NAND_BLOCK_SIZE);
613 ASSERT(size <= NAND_BLOCK_SIZE);
615 //LOG_INFO("nand_readDirect: idx=%ld offset=%d size=%d\n", idx, offset, size);
619 page = PAGE(idx) + (offset / CONFIG_NAND_DATA_SIZE);
620 read_offset = offset % CONFIG_NAND_DATA_SIZE;
621 read_size = MIN(size, CONFIG_NAND_DATA_SIZE - read_offset);
623 if (!nand_read(NAND_CAST(kblk), page, (char *)buf + nread, read_offset, read_size))
634 static int nand_error(struct KBlock *kblk)
636 Nand *chip = NAND_CAST(kblk);
641 static void nand_clearError(struct KBlock *kblk)
643 Nand *chip = NAND_CAST(kblk);
648 static const KBlockVTable nand_buffered_vt =
650 .readDirect = nand_readDirect,
651 .writeDirect = nand_writeDirect,
653 .readBuf = kblock_swReadBuf,
654 .writeBuf = kblock_swWriteBuf,
655 .load = kblock_swLoad,
656 .store = kblock_swStore,
659 .clearerr = nand_clearError,
662 static const KBlockVTable nand_unbuffered_vt =
664 .readDirect = nand_readDirect,
665 .writeDirect = nand_writeDirect,
668 .clearerr = nand_clearError,
673 * Initialize NAND kblock driver in buffered mode.
675 bool nand_init(Nand *chip, struct Heap *heap, unsigned chip_select)
677 if (!commonInit(chip, heap, chip_select))
680 chip->fd.priv.vt = &nand_buffered_vt;
681 chip->fd.priv.flags |= KB_BUFFERED;
683 chip->fd.priv.buf = heap_allocmem(heap, NAND_BLOCK_SIZE);
684 if (!chip->fd.priv.buf)
686 LOG_ERR("nand: error allocating block buffer\n");
690 // Load the first block in the cache
691 return nand_readDirect(&chip->fd, 0, chip->fd.priv.buf, 0, chip->fd.blk_size);
696 * Initialize NAND kblock driver in unbuffered mode.
698 bool nand_initUnbuffered(Nand *chip, struct Heap *heap, unsigned chip_select)
700 if (!commonInit(chip, heap, chip_select))
703 chip->fd.priv.vt = &nand_unbuffered_vt;