+// Timeout for NAND operations in ms
+#define MT29F_TMOUT 100
+
+// NAND flash status codes
+#define MT29F_STATUS_READY BV(6)
+#define MT29F_STATUS_ERROR BV(0)
+
+// NAND flash commands
+#define MT29F_CMD_READ_1 0x00
+#define MT29F_CMD_READ_2 0x30
+#define MT29F_CMD_COPYBACK_READ_1 0x00
+#define MT29F_CMD_COPYBACK_READ_2 0x35
+#define MT29F_CMD_COPYBACK_PROGRAM_1 0x85
+#define MT29F_CMD_COPYBACK_PROGRAM_2 0x10
+#define MT29F_CMD_RANDOM_OUT 0x05
+#define MT29F_CMD_RANDOM_OUT_2 0xE0
+#define MT29F_CMD_RANDOM_IN 0x85
+#define MT29F_CMD_READID 0x90
+#define MT29F_CMD_WRITE_1 0x80
+#define MT29F_CMD_WRITE_2 0x10
+#define MT29F_CMD_ERASE_1 0x60
+#define MT29F_CMD_ERASE_2 0xD0
+#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
+
+
+/*
+ * 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 getAddrCycles(uint32_t page, size_t offset, uint32_t *cycle0, uint32_t *cycle1234)
+{
+ 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 nfcIsBusy(void)
+{
+ return HWREG(NFC_CMD_BASE_ADDR + NFC_CMD_NFCCMD) & 0x8000000;
+}
+
+INLINE bool isCmdDone(void)
+{
+ return SMC_SR & SMC_SR_CMDDONE;
+}
+
+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)
+{
+ 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;
+}
+