+/*
+ * 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
+ *
+ * Cycle I/O7 I/O6 I/O5 I/O4 I/O3 I/O2 I/O1 I/O0
+ * -------------------------------------------------------
+ * First CA7 CA6 CA5 CA4 CA3 CA2 CA1 CA0
+ * Second LOW LOW LOW LOW CA11 CA10 CA9 CA8
+ * Third BA7 BA6 PA5 PA4 PA3 PA2 PA1 PA0
+ * Fourth BA15 BA14 BA13 BA12 BA11 BA10 BA9 BA8
+ * Fifth LOW LOW LOW LOW LOW LOW LOW BA16
+ */
+static void mt29f_getAddrCycles(block_idx_t page, size_t offset, uint32_t *cycle0, uint32_t *cycle1234)
+{
+ uint32_t addr = (page * MT29F_PAGE_SIZE) + offset;
+
+ /*
+ * offset nibbles 77776666 55554444 33332222 11110000
+ * cycle1234 -------7 66665555 ----4444 33332222
+ * cycle0 11110000
+ */
+ *cycle0 = addr & 0xff;
+ *cycle1234 = ((addr >> 8) & 0x00000fff) | ((addr >> 4) & 0x01ff0000);
+}
+
+
+INLINE bool mt29f_isBusy(void)
+{
+ return HWREG(NFC_CMD_BASE_ADDR + NFC_CMD_NFCCMD) & 0x8000000;
+}
+
+INLINE bool mt29f_isCmdDone(void)
+{
+ return SMC_SR & SMC_SR_CMDDONE;
+}
+
+INLINE bool mt29f_isReadyBusy(void)
+{
+ return SMC_SR & SMC_SR_RB_EDGE0;
+}
+
+/*
+ * Wait for transfer to complete until timeout.
+ * If transfer completes return true, false in case of timeout.
+ */
+INLINE bool mt29f_waitTransferComplete(void)
+{
+ time_t start = timer_clock();
+
+ while (!(SMC_SR & SMC_SR_XFRDONE))
+ {
+ cpu_relax();
+ if (timer_clock() - start > MT29F_XFER_TMOUT)
+ return false;
+ }
+
+ kprintf("xfer ok!!\n");
+ return true;
+}
+
+
+/*
+ * Send command to NAND and wait for completion.
+ */
+static void mt29f_sendCommand(uint32_t cmd, uint32_t cycle0, uint32_t cycle1234)
+{
+ reg32_t *cmd_addr;
+
+ while (mt29f_isBusy());
+
+ SMC_ADDR = cycle0;
+
+ cmd_addr = (reg32_t *)(NFC_CMD_BASE_ADDR + cmd);
+ *cmd_addr = cycle1234;
+
+ while (!mt29f_isCmdDone());
+}
+
+
+static bool mt29f_isOperationComplete(void)
+{
+ uint8_t status;
+
+ mt29f_sendCommand(
+ NFC_CMD_NFCCMD | MT29F_CSID | NFC_CMD_ACYCLE_NONE |
+ MT29F_CMD_STATUS << 2, 0, 0);
+
+ status = (uint8_t)HWREG(MT29F_DATA_ADDR);
+ return (status & MT29F_STATUS_READY) && !(status & MT29F_STATUS_ERROR);
+}
+
+
+static void mt29f_reset(void)
+{
+ mt29f_sendCommand(
+ NFC_CMD_NFCCMD | MT29F_CSID | NFC_CMD_ACYCLE_NONE |
+ MT29F_CMD_RESET << 2,
+ 0, 0);
+
+ while (!mt29f_isReadyBusy());
+}
+
+
+/**
+ * Erase the whole block containing given page.
+ */
+int mt29f_blockErase(Mt29f *fls, block_idx_t page)
+{
+ uint32_t cycle0;
+ uint32_t cycle1234;
+
+ mt29f_getAddrCycles(page, 0, &cycle0, &cycle1234);
+
+ mt29f_sendCommand(
+ NFC_CMD_NFCCMD | MT29F_CSID | NFC_CMD_ACYCLE_THREE | NFC_CMD_VCMD2 |
+ (MT29F_CMD_ERASE_2 << 10) | (MT29F_CMD_ERASE_1 << 2),
+ 0, cycle1234);
+
+ while (!mt29f_isReadyBusy());
+
+ if (!mt29f_isOperationComplete())
+ {
+ LOG_ERR("mt29f: error erasing block\n");
+ fls->hw->status |= MT29F_ERR_ERASE;
+ return -1;
+ }
+
+ return 0;
+}
+
+