mt29f nand: export formatting function and, if DEBUG active, function
[bertos.git] / bertos / cpu / cortex-m3 / drv / mt29f_sam3.c
index bd28a40547e2cfde2e9081037c66f8c89cadc607..a8a3dcb5d1db5c6bac9df7eaecde3d5b991007b3 100644 (file)
 
 #include <cfg/log.h>
 #include <cfg/macros.h>
-
 #include <io/sam3.h>
-#include <io/kblock.h>
-
 #include <drv/timer.h>
 #include <drv/mt29f.h>
-
+#include <struct/heap.h>
 #include <cpu/power.h> /* cpu_relax() */
 #include <cpu/types.h>
 
 #include <string.h> /* memcpy() */
 
+// Timeout for NAND operations in ms
+#define MT29F_TMOUT  100
 
 // NAND flash status codes
 #define MT29F_STATUS_READY             BV(6)
 #define MT29F_CMD_STATUS               0x70
 #define MT29F_CMD_RESET                0xFF
 
+// Addresses for sending command, addresses and data bytes to flash
+#define MT29F_CMD_ADDR    0x60400000
+#define MT29F_ADDR_ADDR   0x60200000
+#define MT29F_DATA_ADDR   0x60000000
+
+// Get chip select mask for command register
+#define MT29F_CSID(chip)  (((chip)->chip_select << NFC_CMD_CSID_SHIFT) & NFC_CMD_CSID_MASK)
+
+// Get block from page
+#define PAGE(blk)            ((blk) * MT29F_PAGES_PER_BLOCK)
 
-struct Mt29fHardware
+// Page from block and page in block
+#define BLOCK(page)          ((uint16_t)((page) / MT29F_PAGES_PER_BLOCK))
+#define PAGE_IN_BLOCK(page)  ((uint16_t)((page) % MT29F_PAGES_PER_BLOCK))
+
+
+/*
+ * Remap info written in the first page of each block
+ * used to remap bad blocks.
+ */
+struct RemapInfo
 {
-       int boh;
+       uint32_t tag;         // Magic number to detect valid info
+       uint16_t mapped_blk;  // Bad block the block containing this info is remapping
 };
 
 
 /*
- * Translate flash memory offset in the five address cycles format
- * needed by NAND.
+ * Translate flash page index plus a byte offset
+ * in the five address cycles format needed by NAND.
  *
  * Cycles in x8 mode as the MT29F2G08AAD
  * CA = column addr, PA = page addr, BA = block addr
@@ -101,93 +120,149 @@ struct Mt29fHardware
  * Fourth   BA15  BA14  BA13  BA12  BA11  BA10  BA9   BA8
  * Fifth    LOW   LOW   LOW   LOW   LOW   LOW   LOW   BA16
  */
-static void mt29f_getAddrCycles(size_t offset, uint32_t *cycle0, uint32_t *cycle1234)
+static void getAddrCycles(uint32_t page, uint16_t offset, uint32_t *cycle0, uint32_t *cycle1234)
 {
-       /*
-        * offset nibbles  77776666 55554444 33332222 11110000
-        * cycle1234       -------7 66665555 ----4444 33332222
-        * cycle0          11110000
-        */
-       *cycle0 = offset & 0xFF;
-       *cycle1234 = ((offset >> 8) & 0x00000fff) | ((offset >> 4) & 0x01ff0000);
+       ASSERT(offset < MT29F_PAGE_SIZE);
+
+       *cycle0 = offset & 0xff;
+       *cycle1234 = (page << 8) | ((offset >> 8) & 0xf);
+
+       //LOG_INFO("mt29f addr: %lx %lx\n", *cycle1234, *cycle0);
 }
 
 
-INLINE bool mt29f_isBusy(void)
+INLINE bool nfcIsBusy(void)
 {
        return HWREG(NFC_CMD_BASE_ADDR + NFC_CMD_NFCCMD) & 0x8000000;
 }
 
-INLINE bool mt29f_isCmdDone(void)
+
+/*
+ * Return true if SMC/NFC controller completed the last operations.
+ */
+INLINE bool isCmdDone(void)
 {
     return SMC_SR & SMC_SR_CMDDONE;
 }
 
-INLINE uint8_t mt29f_isReadyBusy(void)
+
+/*
+ * Wait for edge transition of READY/BUSY NAND
+ * signal.
+ * Return true for edge detection, false in case of timeout.
+ */
+static bool waitReadyBusy(void)
+{
+       time_t start = timer_clock();
+
+       while (!(SMC_SR & SMC_SR_RB_EDGE0))
+       {
+               cpu_relax();
+               if (timer_clock() - start > MT29F_TMOUT)
+               {
+                       LOG_INFO("mt29f: R/B timeout\n");
+                       return false;
+               }
+       }
+
+       return true;
+}
+
+/*
+ * Wait for transfer to complete until timeout.
+ * If transfer completes return true, false in case of timeout.
+ */
+static bool waitTransferComplete(void)
 {
-    return SMC_SR & SMC_SR_RB_EDGE0;
+       time_t start = timer_clock();
+
+       while (!(SMC_SR & SMC_SR_XFRDONE))
+       {
+               cpu_relax();
+               if (timer_clock() - start > MT29F_TMOUT)
+               {
+                       LOG_INFO("mt29f: xfer complete timeout\n");
+                       return false;
+               }
+       }
+
+       return true;
 }
 
 
 /*
  * Send command to NAND and wait for completion.
  */
-static void mt29f_sendCommand(uint32_t cmd, uint32_t cycle0, uint32_t cycle1234)
+static void sendCommand(uint32_t cmd,
+               int num_cycles, uint32_t cycle0, uint32_t cycle1234)
 {
        reg32_t *cmd_addr;
 
-       while (mt29f_isBusy());
+       while (nfcIsBusy());
 
-       SMC_ADDR = cycle0;
+       if (num_cycles == 5)
+               SMC_ADDR = cycle0;
 
        cmd_addr = (reg32_t *)(NFC_CMD_BASE_ADDR + cmd);
        *cmd_addr = cycle1234;
 
-       while (!mt29f_isCmdDone());
+       while (!isCmdDone());
 }
 
 
-static bool mt29f_isOperationComplete(void)
+static bool isOperationComplete(Mt29f *chip)
 {
        uint8_t status;
 
-       mt29f_sendCommand(
-               NFC_CMD_NFCCMD | MT29F_CSID | NFC_CMD_ACYCLE_NONE |
-               MT29F_CMD_STATUS << 2, 0, 0);
+       sendCommand(MT29F_CSID(chip) |
+               NFC_CMD_NFCCMD | NFC_CMD_ACYCLE_NONE |
+               MT29F_CMD_STATUS << 2,
+               0, 0, 0);
 
        status = (uint8_t)HWREG(MT29F_DATA_ADDR);
        return (status & MT29F_STATUS_READY) && !(status & MT29F_STATUS_ERROR);
 }
 
 
-#if 0 //reset
-       mt29f_sendCommand(
-                       NFC_CMD_NFCCMD | MT29F_CSID | NFC_CMD_ACYCLE_NONE |
-                       MT29F_CMD_RESET << 2,
-                       0,                                     /* Dummy address cylce 1,2,3,4.*/
-                       0                                      /* Dummy address cylce 0.*/
-#endif
+static void chipReset(Mt29f *chip)
+{
+       sendCommand(MT29F_CSID(chip) |
+               NFC_CMD_NFCCMD | NFC_CMD_ACYCLE_NONE |
+               MT29F_CMD_RESET << 2,
+               0, 0, 0);
+
+       waitReadyBusy();
+}
+
 
 /**
- * Erase block at given offset.
+ * Erase the whole block.
  */
-int mt29f_blockErase(Mt29f *fls, size_t blk_offset)
+int mt29f_blockErase(Mt29f *chip, uint16_t block)
 {
        uint32_t cycle0;
        uint32_t cycle1234;
 
-       mt29f_getAddrCycles(blk_offset, &cycle0, &cycle1234);
+       uint16_t remapped_block = chip->block_map[block];
+       if (block != remapped_block)
+       {
+               LOG_INFO("mt29f_blockErase: remapped block: blk %d->%d\n", block, remapped_block);
+               block = remapped_block;
+       }
 
-       mt29f_sendCommand(
-               NFC_CMD_NFCCMD | MT29F_CSID | NFC_CMD_ACYCLE_THREE | NFC_CMD_VCMD2 |
+       getAddrCycles(PAGE(block), 0, &cycle0, &cycle1234);
+
+       sendCommand(MT29F_CSID(chip) |
+               NFC_CMD_NFCCMD | NFC_CMD_ACYCLE_THREE | NFC_CMD_VCMD2 |
                (MT29F_CMD_ERASE_2 << 10) | (MT29F_CMD_ERASE_1 << 2),
-               cycle1234, 0);
+               3, 0, cycle1234 >> 8);
 
-       while (!mt29f_isReadyBusy());
+       waitReadyBusy();
 
-       if (!mt29f_isOperationComplete())
+       if (!isOperationComplete(chip))
        {
                LOG_ERR("mt29f: error erasing block\n");
+               chip->status |= MT29F_ERR_ERASE;
                return -1;
        }
 
@@ -195,72 +270,410 @@ int mt29f_blockErase(Mt29f *fls, size_t blk_offset)
 }
 
 
-static size_t mt29f_readDirect(struct KBlock *blk, block_idx_t idx, void *buf, size_t offset, size_t size)
+/**
+ * Read Device ID and configuration codes.
+ */
+bool mt29f_getDevId(Mt29f *chip, uint8_t dev_id[5])
 {
+       sendCommand(MT29F_CSID(chip) |
+               NFC_CMD_NFCCMD | NFC_CMD_NFCEN | NFC_CMD_ACYCLE_ONE |
+               MT29F_CMD_READID << 2,
+               1, 0, 0);
+
+       waitReadyBusy();
+       if (!waitTransferComplete())
+       {
+               LOG_ERR("mt29f: getDevId timeout\n");
+               chip->status |= MT29F_ERR_RD_TMOUT;
+               return false;
+       }
+
+       memcpy(dev_id, (void *)NFC_SRAM_BASE_ADDR, 5);
+       return true;
 }
 
 
-static size_t mt29f_writeDirect(struct KBlock *blk, block_idx_t idx, const void *_buf, size_t offset, size_t size)
+static bool checkEcc(Mt29f *chip)
 {
+       struct RemapInfo *remap_info = (struct RemapInfo *)(NFC_SRAM_BASE_ADDR + MT29F_REMAP_TAG_OFFSET);
+
+       /*
+        * Check for ECC hardware status only if a valid RemapInfo structure is found.
+        * That guarantees we wrote the block and a valid ECC is present.
+        */
+       if (remap_info->tag == MT29F_REMAP_TAG)
+       {
+               uint32_t sr1 = SMC_ECC_SR1;
+               if (sr1)
+               {
+                       LOG_INFO("ECC error, ECC_SR1=0x%lx\n", sr1);
+                       chip->status |= MT29F_ERR_ECC;
+                       return false;
+               }
+       }
+
+       return true;
 }
 
 
-static int mt29f_error(struct KBlock *blk)
+static bool mt29f_readPage(Mt29f *chip, uint32_t page, uint16_t offset)
 {
-       Mt29f *fls = FLASH_CAST(blk);
+       uint32_t cycle0;
+       uint32_t cycle1234;
+
+       //LOG_INFO("mt29f_readPage: page 0x%lx off 0x%x\n", page, offset);
+
+       getAddrCycles(page, offset, &cycle0, &cycle1234);
+
+       sendCommand(MT29F_CSID(chip) |
+               NFC_CMD_NFCCMD | NFC_CMD_NFCEN | NFC_CMD_ACYCLE_FIVE | NFC_CMD_VCMD2 |
+               (MT29F_CMD_READ_2 << 10) | (MT29F_CMD_READ_1 << 2),
+               5, cycle0, cycle1234);
+
+       waitReadyBusy();
+       if (!waitTransferComplete())
+       {
+               LOG_ERR("mt29f: read timeout\n");
+               chip->status |= MT29F_ERR_RD_TMOUT;
+               return false;
+       }
+
+       return true;
 }
 
 
-static void mt29f_clearerror(struct KBlock *blk)
+/*
+ * Read page data and ECC, checking for errors.
+ * TODO: fix errors with ECC when possible.
+ */
+static bool mt29f_read(Mt29f *chip, uint32_t page, void *buf, uint16_t size)
 {
-       Mt29f *fls = FLASH_CAST(blk);
+       uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
+
+       if (page != remapped_page)
+       {
+               LOG_INFO("mt29f_read: remapped block: blk %d->%d, pg %ld->%ld\n",
+                               BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
+               page = remapped_page;
+       }
+
+       if (!mt29f_readPage(chip, page, 0))
+               return false;
+
+       memcpy(buf, (void *)NFC_SRAM_BASE_ADDR, size);
+
+       return checkEcc(chip);
 }
 
 
-static const KBlockVTable mt29f_buffered_vt =
+/*
+ * Write data in NFC SRAM buffer to a NAND page, starting at a given offset.
+ * Usually offset will be 0 to write data or MT29F_DATA_SIZE to write the spare
+ * area.
+ *
+ * According to datasheet to get ECC computed by hardware is sufficient
+ * to write the main area.  But it seems that in that way the last ECC_PR
+ * register is not generated.  The workaround is to write data and dummy (ff)
+ * spare data in one write, at this point the last ECC_PR is correct and
+ * ECC data can be written in the spare area with a second program operation.
+ */
+static bool mt29f_writePage(Mt29f *chip, uint32_t page, uint16_t offset)
 {
-       .readDirect = mt29f_readDirect,
-       .writeDirect = mt29f_writeDirect,
+       uint32_t cycle0;
+       uint32_t cycle1234;
 
-       .readBuf = kblock_swReadBuf,
-       .writeBuf = kblock_swWriteBuf,
-       .load = kblock_swLoad,
-       .store = kblock_swStore,
+       //LOG_INFO("mt29f_writePage: page 0x%lx off 0x%x\n", page, offset);
 
-       .close = kblock_swClose,
+       getAddrCycles(page, offset, &cycle0, &cycle1234);
 
-       .error = mt29f_error,
-       .clearerr = mt29f_clearerror,
-};
+       sendCommand(MT29F_CSID(chip) |
+                       NFC_CMD_NFCCMD | NFC_CMD_NFCWR | NFC_CMD_NFCEN | NFC_CMD_ACYCLE_FIVE |
+                       MT29F_CMD_WRITE_1 << 2,
+                       5, cycle0, cycle1234);
+
+       if (!waitTransferComplete())
+       {
+               LOG_ERR("mt29f: write timeout\n");
+               chip->status |= MT29F_ERR_WR_TMOUT;
+               return false;
+       }
 
+       sendCommand(MT29F_CSID(chip) |
+                       NFC_CMD_NFCCMD | NFC_CMD_ACYCLE_NONE |
+                       MT29F_CMD_WRITE_2 << 2,
+                       0, 0, 0);
 
-static const KBlockVTable mt29f_unbuffered_vt =
+       waitReadyBusy();
+
+       if (!isOperationComplete(chip))
+       {
+               LOG_ERR("mt29f: error writing page\n");
+               chip->status |= MT29F_ERR_WRITE;
+               return false;
+       }
+
+       return true;
+}
+
+
+/*
+ * Write data in a page.
+ */
+static bool mt29f_writePageData(Mt29f *chip, uint32_t page, const void *buf, uint16_t size)
 {
-       .readDirect = mt29f_readDirect,
-       .writeDirect = mt29f_writeDirect,
+       ASSERT(size <= MT29F_DATA_SIZE);
 
-       .close = kblock_swClose,
+       memset((void *)NFC_SRAM_BASE_ADDR, 0xff, MT29F_PAGE_SIZE);
+       memcpy((void *)NFC_SRAM_BASE_ADDR, buf, size);
 
-       .error = mt29f_error,
-       .clearerr = mt29f_clearerror,
-};
+       return mt29f_writePage(chip, page, 0);
+}
 
 
-static struct Mt29fHardware mt29f_hw;
+/*
+ * Write the spare area in a page: ECC and remap block index.
+ * \param page           the page to be written
+ * \parma original_page  if different from page, it's the page that's being remapped
+ *
+ * ECC data are extracted from ECC_PRx registers and written
+ * in the page's spare area.
+ * For 2048 bytes pages and 1 ECC word each 256 bytes,
+ * 24 bytes of ECC data are stored.
+ */
+static bool mt29f_writePageSpare(Mt29f *chip, uint32_t page, uint32_t original_page)
+{
+       int i;
+       uint32_t *buf = (uint32_t *)NFC_SRAM_BASE_ADDR;
+       struct RemapInfo *remap_info = (struct RemapInfo *)(NFC_SRAM_BASE_ADDR + MT29F_REMAP_TAG_OFFSET);
+
+       memset((void *)NFC_SRAM_BASE_ADDR, 0xff, MT29F_SPARE_SIZE);
+
+       for (i = 0; i < MT29F_ECC_NWORDS; i++)
+               buf[i] = *((reg32_t *)(SMC_BASE + SMC_ECC_PR0_OFF) + i);
 
+       // Write remap tag
+       remap_info->tag = MT29F_REMAP_TAG;
+       remap_info->mapped_blk = BLOCK(original_page);
 
-static void common_init(Mt29f *fls)
+       return mt29f_writePage(chip, page, MT29F_DATA_SIZE);
+}
+
+
+static bool mt29f_write(Mt29f *chip, uint32_t page, const void *buf, uint16_t size)
 {
-       memset(fls, 0, sizeof(*fls));
-       DB(fls->blk.priv.type = KBT_MT29F);
+       uint32_t remapped_page = PAGE(chip->block_map[BLOCK(page)]) + PAGE_IN_BLOCK(page);
+
+       if (page != remapped_page)
+               LOG_INFO("mt29f_write: remapped block: blk %d->%d, pg %ld->%ld\n",
+                               BLOCK(page), chip->block_map[BLOCK(page)], page, remapped_page);
+
+       return
+               mt29f_writePageData(chip, remapped_page, buf, size) &&
+               mt29f_writePageSpare(chip, remapped_page, page);
+}
+
+
+/*
+ * Check if the given block is marked bad: ONFI standard mandates
+ * that bad block are marked with "00" bytes on the spare area of the
+ * first page in block.
+ */
+static bool blockIsGood(Mt29f *chip, uint16_t blk)
+{
+       uint8_t *first_byte = (uint8_t *)NFC_SRAM_BASE_ADDR;
+       bool good;
+
+       // Check first byte in spare area of first page in block
+       mt29f_readPage(chip, PAGE(blk), MT29F_DATA_SIZE);
+       good = *first_byte != 0;
 
-       fls->hw = &mt29f_hw;
+       if (!good)
+               LOG_INFO("mt29f: bad block %d\n", blk);
 
-       fls->blk.blk_size = MT29F_PAGE_SIZE;
-       fls->blk.blk_cnt =  MT29F_SIZE / MT29F_PAGE_SIZE;
+       return good;
+}
+
+
+/*
+ * Return the main partition block remapped on given block in the remap
+ * partition (dest_blk).
+ */
+static int getBadBlockFromRemapBlock(Mt29f *chip, uint16_t dest_blk)
+{
+       struct RemapInfo *remap_info = (struct RemapInfo *)NFC_SRAM_BASE_ADDR;
+
+       if (!mt29f_readPage(chip, PAGE(dest_blk), MT29F_DATA_SIZE + MT29F_REMAP_TAG_OFFSET))
+               return -1;
+
+       if (remap_info->tag == MT29F_REMAP_TAG)
+               return remap_info->mapped_blk;
+       else
+               return -1;
+}
+
+
+/*
+ * Set a block remapping: src_blk (a block in main data partition) is remappend
+ * on dest_blk (block in reserved remapped blocks partition).
+ */
+static bool setMapping(Mt29f *chip, uint32_t src_blk, uint32_t dest_blk)
+{
+       struct RemapInfo *remap_info = (struct RemapInfo *)NFC_SRAM_BASE_ADDR;
 
+       LOG_INFO("mt29f, setMapping(): src=%ld dst=%ld\n", src_blk, dest_blk);
+
+       if (!mt29f_readPage(chip, PAGE(dest_blk), MT29F_DATA_SIZE + MT29F_REMAP_TAG_OFFSET))
+               return false;
+
+       remap_info->tag = MT29F_REMAP_TAG;
+       remap_info->mapped_blk = src_blk;
+
+       return mt29f_writePage(chip, PAGE(dest_blk), MT29F_DATA_SIZE + MT29F_REMAP_TAG_OFFSET);
+}
+
+
+/*
+ * Get a new block from the remap partition to use as a substitute
+ * for a bad block.
+ */
+static uint16_t getFreeRemapBlock(Mt29f *chip)
+{
+       int blk;
+
+       for (blk = chip->remap_start; blk < MT29F_NUM_BLOCKS; blk++)
+       {
+               if (blockIsGood(chip, blk))
+               {
+                       chip->remap_start = blk + 1;
+                       return blk;
+               }
+       }
+
+       LOG_ERR("mt29f: reserved blocks for bad block remapping exhausted!\n");
+       return 0;
+}
+
+
+/*
+ * Check if NAND is initialized.
+ */
+static bool chipIsMarked(Mt29f *chip)
+{
+       return getBadBlockFromRemapBlock(chip, MT29F_NUM_USER_BLOCKS) != -1;
+}
+
+
+/*
+ * Initialize NAND (format). Scan NAND for factory marked bad blocks.
+ * All bad blocks found are remapped to the remap partition: each
+ * block in the remap partition used to remap bad blocks is marked.
+ */
+static void initBlockMap(Mt29f *chip)
+{
+       int b, last;
+
+       // Default is for each block to not be remapped
+       for (b = 0; b < MT29F_NUM_BLOCKS; b++)
+               chip->block_map[b] = b;
+       chip->remap_start = MT29F_NUM_USER_BLOCKS;
+
+       if (chipIsMarked(chip))
+       {
+               LOG_INFO("mt29f: found initialized NAND, searching for remapped blocks\n");
+
+               // Scan for assigned blocks in remap area
+               for (b = last = MT29F_NUM_USER_BLOCKS; b < MT29F_NUM_BLOCKS; b++)
+               {
+                       int remapped_blk = getBadBlockFromRemapBlock(chip, b);
+                       if (remapped_blk != -1 && remapped_blk != b)
+                       {
+                               LOG_INFO("mt29f: found remapped block %d->%d\n", remapped_blk, b);
+                               chip->block_map[remapped_blk] = b;
+                               last = b + 1;
+                       }
+               }
+               chip->remap_start = last;
+       }
+       else
+       {
+               bool remapped_anything = false;
+
+               LOG_INFO("mt29f: found new NAND, searching for bad blocks\n");
+
+               for (b = 0; b < MT29F_NUM_USER_BLOCKS; b++)
+               {
+                       if (!blockIsGood(chip, b))
+                       {
+                               chip->block_map[b] = getFreeRemapBlock(chip);
+                               setMapping(chip, b, chip->block_map[b]);
+                               remapped_anything = true;
+                               LOG_INFO("mt29f: found new bad block %d, remapped to %d\n", b, chip->block_map[b]);
+                       }
+               }
+
+               /*
+            * If no bad blocks are found (we're lucky!) write a dummy
+                * remap to mark NAND and detect we already scanned it next time.
+                */
+               if (!remapped_anything)
+               {
+                       setMapping(chip, MT29F_NUM_USER_BLOCKS, MT29F_NUM_USER_BLOCKS);
+                       LOG_INFO("mt29f: no bad block founds, marked NAND\n");
+               }
+       }
+}
+
+
+/**
+ * Reset bad blocks map and erase all blocks.
+ *
+ * \note DON'T USE on production chips: this function will try to erase
+ *       factory marked bad blocks too.
+ */
+void mt29f_format(Mt29f *chip)
+{
+       int b;
+
+       for (b = 0; b < MT29F_NUM_BLOCKS; b++)
+       {
+               LOG_INFO("mt29f: erasing block %d\n", b);
+               chip->block_map[b] = b;
+               mt29f_blockErase(chip, b);
+       }
+       chip->remap_start = MT29F_NUM_USER_BLOCKS;
+}
+
+#ifdef _DEBUG
+
+/*
+ * Create some bad blocks, erasing them and writing the bad block mark.
+ */
+void mt29f_ruinSomeBlocks(Mt29f *chip)
+{
+       int bads[] = { 7, 99, 555, 1003, 1004, 1432 };
+       unsigned i;
+
+       LOG_INFO("mt29f: erasing mark\n");
+       mt29f_blockErase(chip, MT29F_NUM_USER_BLOCKS);
+
+       for (i = 0; i < countof(bads); i++)
+       {
+               LOG_INFO("mt29f: erasing block %d\n", bads[i]);
+               mt29f_blockErase(chip, bads[i]);
+
+               LOG_INFO("mt29f: marking page %d as bad\n", PAGE(bads[i]));
+               memset((void *)NFC_SRAM_BASE_ADDR, 0, MT29F_SPARE_SIZE);
+               mt29f_writePage(chip, PAGE(bads[i]), MT29F_DATA_SIZE);
+       }
+}
+
+#endif
+
+
+static void initPio(void)
+{
        /*
-        * TODO: put following stuff in hw_ file dependent (and configurable cs?)
+        * TODO: put following stuff in hw_ file dependent
         * Parameters for MT29F8G08AAD
         */
        pmc_periphEnable(PIOA_ID);
@@ -280,7 +693,11 @@ static void common_init(Mt29f *fls)
        PIOD_PUER = MT29F_PINS_PORTD;
 
     pmc_periphEnable(SMC_SDRAMC_ID);
+}
+
 
+static void initSmc(void)
+{
     SMC_SETUP0 = SMC_SETUP_NWE_SETUP(0)
                | SMC_SETUP_NCS_WR_SETUP(0)
                | SMC_SETUP_NRD_SETUP(0)
@@ -304,25 +721,168 @@ static void common_init(Mt29f *fls)
 
     SMC_MODE0 = SMC_MODE_READ_MODE
                | SMC_MODE_WRITE_MODE;
+
+       SMC_CFG = SMC_CFG_PAGESIZE_PS2048_64
+               | SMC_CFG_EDGECTRL
+               | SMC_CFG_DTOMUL_X1048576
+               | SMC_CFG_DTOCYC(0xF)
+               | SMC_CFG_WSPARE
+               | SMC_CFG_RSPARE;
+
+       // Disable SMC interrupts, reset and enable NFC controller
+       SMC_IDR = ~0;
+       SMC_CTRL = 0;
+       SMC_CTRL = SMC_CTRL_NFCEN;
+
+       // Enable ECC, 1 ECC per 256 bytes
+       SMC_ECC_CTRL = SMC_ECC_CTRL_SWRST;
+       SMC_ECC_MD = SMC_ECC_MD_ECC_PAGESIZE_PS2048_64 | SMC_ECC_MD_TYPCORREC_C256B;
+}
+
+
+static bool commonInit(Mt29f *chip, struct Heap *heap, unsigned chip_select)
+{
+       memset(chip, 0, sizeof(Mt29f));
+
+       DB(chip->fd.priv.type = KBT_NAND);
+       chip->fd.blk_size = MT29F_BLOCK_SIZE;
+       chip->fd.blk_cnt  = MT29F_NUM_USER_BLOCKS;
+
+       chip->chip_select = chip_select;
+       chip->block_map = heap_allocmem(heap, MT29F_NUM_BLOCKS * sizeof(*chip->block_map));
+       if (!chip->block_map)
+       {
+               LOG_ERR("mt29f: error allocating block map\n");
+               return false;
+       }
+
+       initPio();
+       initSmc();
+       chipReset(chip);
+       initBlockMap(chip);
+
+       return true;
+}
+
+
+/**************** Kblock interface ****************/
+
+
+static size_t mt29f_writeDirect(struct KBlock *kblk, block_idx_t idx, const void *buf, size_t offset, size_t size)
+{
+       ASSERT(offset <= MT29F_BLOCK_SIZE);
+       ASSERT(offset % MT29F_DATA_SIZE == 0);
+       ASSERT(size <= MT29F_BLOCK_SIZE);
+       ASSERT(size % MT29F_DATA_SIZE == 0);
+
+       LOG_INFO("mt29f_writeDirect: blk=%ld\n", idx);
+
+       mt29f_blockErase(MT29F_CAST(kblk), idx);
+
+       while (offset < size)
+       {
+               uint32_t page = PAGE(idx) + (offset / MT29F_DATA_SIZE);
+
+               if (!mt29f_write(MT29F_CAST(kblk), page, buf, MT29F_DATA_SIZE))
+                       break;
+
+               offset += MT29F_DATA_SIZE;
+               buf = (const char *)buf + MT29F_DATA_SIZE;
+       }
+
+       return offset;
 }
 
 
-void mt29f_hw_init(Mt29f *fls)
+static size_t mt29f_readDirect(struct KBlock *kblk, block_idx_t idx, void *buf, size_t offset, size_t size)
 {
-       common_init(fls);
-       fls->blk.priv.vt = &mt29f_buffered_vt;
-       fls->blk.priv.flags |= KB_BUFFERED | KB_PARTIAL_WRITE;
-       fls->blk.priv.buf = (void *)NFC_CMD_BASE_ADDR;
+       ASSERT(offset <= MT29F_BLOCK_SIZE);
+       ASSERT(offset % MT29F_DATA_SIZE == 0);
+       ASSERT(size <= MT29F_BLOCK_SIZE);
+       ASSERT(size % MT29F_DATA_SIZE == 0);
+
+       LOG_INFO("mt29f_readDirect: blk=%ld\n", idx);
+
+       while (offset < size)
+       {
+               uint32_t page = PAGE(idx) + (offset / MT29F_DATA_SIZE);
+
+               if (!mt29f_read(MT29F_CAST(kblk), page, buf, MT29F_DATA_SIZE))
+                       break;
+
+               offset += MT29F_DATA_SIZE;
+               buf = (char *)buf + MT29F_DATA_SIZE;
+       }
+
+       return offset;
+}
+
+
+static int mt29f_error(struct KBlock *kblk)
+{
+       Mt29f *chip = MT29F_CAST(kblk);
+       return chip->status;
+}
+
+
+static void mt29f_clearError(struct KBlock *kblk)
+{
+       Mt29f *chip = MT29F_CAST(kblk);
+       chip->status = 0;
+}
+
+
+static const KBlockVTable mt29f_buffered_vt =
+{
+       .readDirect = mt29f_readDirect,
+       .writeDirect = mt29f_writeDirect,
+
+       .readBuf = kblock_swReadBuf,
+       .writeBuf = kblock_swWriteBuf,
+       .load = kblock_swLoad,
+       .store = kblock_swStore,
+
+       .error = mt29f_error,
+       .clearerr = mt29f_clearError,
+};
+
+static const KBlockVTable mt29f_unbuffered_vt =
+{
+       .readDirect = mt29f_readDirect,
+       .writeDirect = mt29f_writeDirect,
+
+       .error = mt29f_error,
+       .clearerr = mt29f_clearError,
+};
+
+
+bool mt29f_init(Mt29f *chip, struct Heap *heap, unsigned chip_select)
+{
+       if (!commonInit(chip, heap, chip_select))
+               return false;
+
+       chip->fd.priv.vt = &mt29f_buffered_vt;
+       chip->fd.priv.flags |= KB_BUFFERED;
+
+       chip->fd.priv.buf = heap_allocmem(heap, MT29F_BLOCK_SIZE);
+       if (!chip->fd.priv.buf)
+       {
+               LOG_ERR("mt29f: error allocating block buffer\n");
+               return false;
+       }
 
        // Load the first block in the cache
-       void *start = 0x0;
-       memcpy(fls->blk.priv.buf, start, fls->blk.blk_size);
+       return mt29f_readDirect(&chip->fd, 0, chip->fd.priv.buf, 0, MT29F_DATA_SIZE);
 }
 
 
-void mt29f_hw_initUnbuffered(Mt29f *fls)
+bool mt29f_initUnbuffered(Mt29f *chip, struct Heap *heap, unsigned chip_select)
 {
-       common_init(fls);
-       fls->blk.priv.vt = &mt29f_unbuffered_vt;
+       if (!commonInit(chip, heap, chip_select))
+               return false;
+
+       chip->fd.priv.vt = &mt29f_unbuffered_vt;
+       return true;
 }
 
+