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);
141 static void chipReset(Nand *chip)
143 nand_sendCommand(chip, NAND_CMD_RESET, 0, 0, 0, 0);
144 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
148 static bool isOperationComplete(Nand *chip)
152 nand_sendCommand(chip, NAND_CMD_STATUS, 0, 0, 0, 0);
154 status = nand_getChipStatus(chip);
155 return (status & NAND_STATUS_READY) && !(status & NAND_STATUS_ERROR);
160 * Erase the whole block.
162 int nand_blockErase(Nand *chip, uint16_t block)
167 uint16_t remapped_block = chip->block_map[block];
168 if (block != remapped_block)
170 LOG_INFO("nand_blockErase: remapped block: blk %d->%d\n", block, remapped_block);
171 block = remapped_block;
174 getAddrCycles(PAGE(block), 0, &cycle0, &cycle1234);
176 nand_sendCommand(chip, NAND_CMD_ERASE_1, NAND_CMD_ERASE_2, 3, 0, cycle1234 >> 8);
178 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
180 if (!isOperationComplete(chip))
182 LOG_ERR("nand: error erasing block\n");
183 chip->status |= NAND_ERR_ERASE;
192 * Read Device ID and configuration codes.
194 bool nand_getDevId(Nand *chip, uint8_t dev_id[5])
196 nand_sendCommand(chip, NAND_CMD_READID, 0, 1, 0, 0);
198 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
199 if (!nand_waitTransferComplete(chip, CONFIG_NAND_TMOUT))
201 LOG_ERR("nand: getDevId timeout\n");
202 chip->status |= NAND_ERR_RD_TMOUT;
206 memcpy(dev_id, nand_dataBuffer(chip), sizeof(dev_id));
211 static bool nand_readPage(Nand *chip, uint32_t page, uint16_t offset)
216 //LOG_INFO("nand_readPage: page 0x%lx off 0x%x\n", page, offset);
218 getAddrCycles(page, offset, &cycle0, &cycle1234);
220 nand_sendCommand(chip, NAND_CMD_READ_1, NAND_CMD_READ_2, 5, cycle0, cycle1234);
222 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
223 if (!nand_waitTransferComplete(chip, CONFIG_NAND_TMOUT))
225 LOG_ERR("nand: read timeout\n");
226 chip->status |= NAND_ERR_RD_TMOUT;
235 * Read page data and ECC, checking for errors.
236 * TODO: fix errors with ECC when possible.
238 static bool nand_read(Nand *chip, uint32_t page, void *buf, uint16_t offset, uint16_t size)
240 struct RemapInfo remap_info;
241 uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
243 //LOG_INFO("nand_read: page=%ld, offset=%d, size=%d\n", page, offset, size);
245 if (page != remapped_page)
247 LOG_INFO("nand_read: remapped block: blk %d->%d, pg %ld->%ld\n",
248 BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
249 page = remapped_page;
252 if (!nand_readPage(chip, page, 0))
255 memcpy(buf, (char *)nand_dataBuffer(chip) + offset, size);
258 * Check for ECC hardware status only if a valid RemapInfo structure is found.
259 * That guarantees the page is written by us and a valid ECC is present.
261 memcpy(&remap_info, (char *)buf + NAND_REMAP_TAG_OFFSET, sizeof(remap_info));
262 if (remap_info.tag == NAND_REMAP_TAG && !nand_checkEcc(chip))
264 chip->status |= NAND_ERR_ECC;
273 * Write data stored in nand_dataBuffer() to a NAND page, starting at a given offset.
274 * Usually offset will be 0 to write data or CONFIG_NAND_DATA_SIZE to write the spare
277 static bool nand_writePage(Nand *chip, uint32_t page, uint16_t offset)
282 //LOG_INFO("nand_writePage: page 0x%lx off 0x%x\n", page, offset);
284 getAddrCycles(page, offset, &cycle0, &cycle1234);
286 nand_sendCommand(chip, NAND_CMD_WRITE_1, 0, 5, cycle0, cycle1234);
288 if (!nand_waitTransferComplete(chip, CONFIG_NAND_TMOUT))
290 LOG_ERR("nand: write timeout\n");
291 chip->status |= NAND_ERR_WR_TMOUT;
295 nand_sendCommand(chip, NAND_CMD_WRITE_2, 0, 0, 0, 0);
297 nand_waitReadyBusy(chip, CONFIG_NAND_TMOUT);
299 if (!isOperationComplete(chip))
301 LOG_ERR("nand: error writing page\n");
302 chip->status |= NAND_ERR_WRITE;
311 * Write data, ECC and remap block info.
313 * \param page the page to be written
314 * \parma original_page if different from page, it's the page that's being remapped
316 * Implementation note for SAM3 NFC controller:
317 * according to datasheet to get ECC computed by hardware is sufficient
318 * to write the main area. But it seems that in that way the last ECC_PR
319 * register is not generated. The workaround is to write data and dummy (ff)
320 * spare data in one write, at this point the last ECC_PR is correct and
321 * ECC data can be written in the spare area with a second program operation.
323 static bool nand_write(Nand *chip, uint32_t page, const void *buf, size_t size)
325 struct RemapInfo remap_info;
326 uint32_t *nand_buf = (uint32_t *)nand_dataBuffer(chip);
327 uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
329 ASSERT(size <= CONFIG_NAND_DATA_SIZE);
331 if (page != remapped_page)
332 LOG_INFO("nand_write: remapped block: blk %d->%d, pg %ld->%ld\n",
333 BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
336 memset(nand_buf, 0xff, NAND_PAGE_SIZE);
337 memcpy(nand_buf, buf, size);
338 if (!nand_writePage(chip, remapped_page, 0))
342 memset(nand_buf, 0xff, CONFIG_NAND_SPARE_SIZE);
343 nand_computeEcc(chip, buf, size, nand_buf, NAND_ECC_NWORDS);
346 remap_info.tag = NAND_REMAP_TAG;
347 remap_info.mapped_blk = BLOCK(page);
348 memcpy((char *)nand_buf + NAND_REMAP_TAG_OFFSET, &remap_info, sizeof(remap_info));
350 return nand_writePage(chip, remapped_page, CONFIG_NAND_DATA_SIZE);
355 * Check if the given block is marked bad: ONFI standard mandates
356 * that bad block are marked with "00" bytes on the spare area of the
357 * first page in block.
359 static bool blockIsGood(Nand *chip, uint16_t blk)
361 uint8_t *first_byte = (uint8_t *)nand_dataBuffer(chip);
364 // Check first byte in spare area of first page in block
365 nand_readPage(chip, PAGE(blk), CONFIG_NAND_DATA_SIZE);
366 good = *first_byte != 0;
369 LOG_INFO("nand: bad block %d\n", blk);
376 * Return the main partition block remapped on given block in the remap
377 * partition (dest_blk).
379 static int getBadBlockFromRemapBlock(Nand *chip, uint16_t dest_blk)
381 struct RemapInfo *remap_info = (struct RemapInfo *)nand_dataBuffer(chip);
383 if (!nand_readPage(chip, PAGE(dest_blk), CONFIG_NAND_DATA_SIZE + NAND_REMAP_TAG_OFFSET))
386 if (remap_info->tag == NAND_REMAP_TAG)
387 return remap_info->mapped_blk;
394 * Set a block remapping: src_blk (a block in main data partition) is remapped
395 * on dest_blk (block in reserved remapped blocks partition).
397 static bool setMapping(Nand *chip, uint32_t src_blk, uint32_t dest_blk)
399 struct RemapInfo *remap_info = (struct RemapInfo *)nand_dataBuffer(chip);
401 LOG_INFO("nand, setMapping(): src=%ld dst=%ld\n", src_blk, dest_blk);
403 if (!nand_readPage(chip, PAGE(dest_blk), CONFIG_NAND_DATA_SIZE + NAND_REMAP_TAG_OFFSET))
406 remap_info->tag = NAND_REMAP_TAG;
407 remap_info->mapped_blk = src_blk;
409 return nand_writePage(chip, PAGE(dest_blk), CONFIG_NAND_DATA_SIZE + NAND_REMAP_TAG_OFFSET);
414 * Get a new block from the remap partition to use as a substitute
417 static uint16_t getFreeRemapBlock(Nand *chip)
421 for (blk = chip->remap_start; blk < CONFIG_NAND_NUM_BLOCK; blk++)
423 if (blockIsGood(chip, blk))
425 chip->remap_start = blk + 1;
430 LOG_ERR("nand: reserved blocks for bad block remapping exhausted!\n");
436 * Check if NAND is initialized.
438 static bool chipIsMarked(Nand *chip)
440 return getBadBlockFromRemapBlock(chip, NAND_NUM_USER_BLOCKS) != -1;
445 * Initialize NAND (format). Scan NAND for factory marked bad blocks.
446 * All found bad blocks are remapped to the remap partition: each
447 * block in the remap partition used to remap bad blocks is marked.
449 static void initBlockMap(Nand *chip)
453 // Default is for each block to not be remapped
454 for (b = 0; b < CONFIG_NAND_NUM_BLOCK; b++)
455 chip->block_map[b] = b;
456 chip->remap_start = NAND_NUM_USER_BLOCKS;
458 if (chipIsMarked(chip))
460 LOG_INFO("nand: found initialized NAND, searching for remapped blocks\n");
462 // Scan for assigned blocks in remap area
463 for (b = last = NAND_NUM_USER_BLOCKS; b < CONFIG_NAND_NUM_BLOCK; b++)
465 int remapped_blk = getBadBlockFromRemapBlock(chip, b);
466 if (remapped_blk != -1 && remapped_blk != b)
468 LOG_INFO("nand: found remapped block %d->%d\n", remapped_blk, b);
469 chip->block_map[remapped_blk] = b;
473 chip->remap_start = last;
477 bool remapped_anything = false;
479 LOG_INFO("nand: found new NAND, searching for bad blocks\n");
481 for (b = 0; b < NAND_NUM_USER_BLOCKS; b++)
483 if (!blockIsGood(chip, b))
485 chip->block_map[b] = getFreeRemapBlock(chip);
486 setMapping(chip, b, chip->block_map[b]);
487 remapped_anything = true;
488 LOG_WARN("nand: found new bad block %d, remapped to %d\n", b, chip->block_map[b]);
493 * If no bad blocks are found (we're lucky!) write anyway a dummy
494 * remap to mark NAND and detect we already scanned it next time.
496 if (!remapped_anything)
498 setMapping(chip, NAND_NUM_USER_BLOCKS, NAND_NUM_USER_BLOCKS);
499 LOG_INFO("nand: no bad block founds, marked NAND\n");
506 * Reset bad blocks map and erase all blocks.
508 * \note DON'T USE on production chips: this function will try to erase
509 * factory marked bad blocks too.
511 void nand_format(Nand *chip)
515 for (b = 0; b < CONFIG_NAND_NUM_BLOCK; b++)
517 LOG_INFO("nand: erasing block %d\n", b);
518 chip->block_map[b] = b;
519 nand_blockErase(chip, b);
521 chip->remap_start = NAND_NUM_USER_BLOCKS;
527 * Create some bad blocks, erasing them and writing the bad block mark.
529 void nand_ruinSomeBlocks(Nand *chip)
531 int bads[] = { 7, 99, 555, 1003, 1004, 1432 };
534 LOG_INFO("nand: erasing mark\n");
535 nand_blockErase(chip, NAND_NUM_USER_BLOCKS);
537 for (i = 0; i < countof(bads); i++)
539 LOG_INFO("nand: erasing block %d\n", bads[i]);
540 nand_blockErase(chip, bads[i]);
542 LOG_INFO("nand: marking page %d as bad\n", PAGE(bads[i]));
543 memset(nand_dataBuffer(chip), 0, CONFIG_NAND_SPARE_SIZE);
544 nand_writePage(chip, PAGE(bads[i]), CONFIG_NAND_DATA_SIZE);
550 static bool commonInit(Nand *chip, struct Heap *heap, unsigned chip_select)
552 memset(chip, 0, sizeof(Nand));
554 DB(chip->fd.priv.type = KBT_NAND);
555 chip->fd.blk_size = NAND_BLOCK_SIZE;
556 chip->fd.blk_cnt = NAND_NUM_USER_BLOCKS;
558 chip->chip_select = chip_select;
559 chip->block_map = heap_allocmem(heap, CONFIG_NAND_NUM_BLOCK * sizeof(*chip->block_map));
560 if (!chip->block_map)
562 LOG_ERR("nand: error allocating block map\n");
574 /**************** Kblock interface ****************/
577 static size_t nand_writeDirect(struct KBlock *kblk, block_idx_t idx, const void *buf, size_t offset, size_t size)
579 ASSERT(offset <= NAND_BLOCK_SIZE);
580 ASSERT(offset % CONFIG_NAND_DATA_SIZE == 0);
581 ASSERT(size <= NAND_BLOCK_SIZE);
582 ASSERT(size % CONFIG_NAND_DATA_SIZE == 0);
584 LOG_INFO("nand_writeDirect: idx=%ld offset=%d size=%d\n", idx, offset, size);
586 nand_blockErase(NAND_CAST(kblk), idx);
588 while (offset < size)
590 uint32_t page = PAGE(idx) + (offset / CONFIG_NAND_DATA_SIZE);
592 if (!nand_write(NAND_CAST(kblk), page, buf, CONFIG_NAND_DATA_SIZE))
595 offset += CONFIG_NAND_DATA_SIZE;
596 buf = (const char *)buf + CONFIG_NAND_DATA_SIZE;
603 static size_t nand_readDirect(struct KBlock *kblk, block_idx_t idx, void *buf, size_t offset, size_t size)
610 ASSERT(offset < NAND_BLOCK_SIZE);
611 ASSERT(size <= NAND_BLOCK_SIZE);
613 LOG_INFO("nand_readDirect: idx=%ld offset=%d size=%d\n", idx, offset, size);
617 page = PAGE(idx) + (offset / CONFIG_NAND_DATA_SIZE);
618 read_offset = offset % CONFIG_NAND_DATA_SIZE;
619 read_size = MIN(size, CONFIG_NAND_DATA_SIZE - read_offset);
621 if (!nand_read(NAND_CAST(kblk), page, (char *)buf + nread, read_offset, read_size))
632 static int nand_error(struct KBlock *kblk)
634 Nand *chip = NAND_CAST(kblk);
639 static void nand_clearError(struct KBlock *kblk)
641 Nand *chip = NAND_CAST(kblk);
646 static const KBlockVTable nand_buffered_vt =
648 .readDirect = nand_readDirect,
649 .writeDirect = nand_writeDirect,
651 .readBuf = kblock_swReadBuf,
652 .writeBuf = kblock_swWriteBuf,
653 .load = kblock_swLoad,
654 .store = kblock_swStore,
657 .clearerr = nand_clearError,
660 static const KBlockVTable nand_unbuffered_vt =
662 .readDirect = nand_readDirect,
663 .writeDirect = nand_writeDirect,
666 .clearerr = nand_clearError,
671 * Initialize NAND kblock driver in buffered mode.
673 bool nand_init(Nand *chip, struct Heap *heap, unsigned chip_select)
675 if (!commonInit(chip, heap, chip_select))
678 chip->fd.priv.vt = &nand_buffered_vt;
679 chip->fd.priv.flags |= KB_BUFFERED;
681 chip->fd.priv.buf = heap_allocmem(heap, NAND_BLOCK_SIZE);
682 if (!chip->fd.priv.buf)
684 LOG_ERR("nand: error allocating block buffer\n");
688 // Load the first block in the cache
689 return nand_readDirect(&chip->fd, 0, chip->fd.priv.buf, 0, chip->fd.blk_size);
694 * Initialize NAND kblock driver in unbuffered mode.
696 bool nand_initUnbuffered(Nand *chip, struct Heap *heap, unsigned chip_select)
698 if (!commonInit(chip, heap, chip_select))
701 chip->fd.priv.vt = &nand_unbuffered_vt;