Merge pull request #11297 from SteveCEvans/baro_state
[betaflight.git] / src / main / drivers / flash_w25n01g.c
blobffd786c1c61164b89a497f0765576896f25f518f
1 /*
2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
8 * any later version.
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
20 * Author: jflyper
23 #include <stdbool.h>
24 #include <stdint.h>
26 #include "platform.h"
28 #ifdef USE_FLASH_W25N01G
30 #include "flash.h"
31 #include "flash_impl.h"
32 #include "flash_w25n01g.h"
33 #include "drivers/bus_spi.h"
34 #include "drivers/bus_quadspi.h"
35 #include "drivers/io.h"
36 #include "drivers/time.h"
38 // Device size parameters
39 #define W25N01G_PAGE_SIZE 2048
40 #define W25N01G_PAGES_PER_BLOCK 64
41 #define W25N01G_BLOCKS_PER_DIE 1024
43 // BB replacement area
44 #define W25N01G_BB_MARKER_BLOCKS 1
45 #define W25N01G_BB_REPLACEMENT_BLOCKS 20
46 #define W25N01G_BB_MANAGEMENT_BLOCKS (W25N01G_BB_REPLACEMENT_BLOCKS + W25N01G_BB_MARKER_BLOCKS)
47 // blocks are zero-based index
48 #define W25N01G_BB_REPLACEMENT_START_BLOCK (W25N01G_BLOCKS_PER_DIE - W25N01G_BB_REPLACEMENT_BLOCKS)
49 #define W25N01G_BB_MANAGEMENT_START_BLOCK (W25N01G_BLOCKS_PER_DIE - W25N01G_BB_MANAGEMENT_BLOCKS)
50 #define W25N01G_BB_MARKER_BLOCK (W25N01G_BB_REPLACEMENT_START_BLOCK - W25N01G_BB_MARKER_BLOCKS)
52 // Instructions
54 #define W25N01G_INSTRUCTION_RDID 0x9F
55 #define W25N01G_INSTRUCTION_DEVICE_RESET 0xFF
56 #define W25N01G_INSTRUCTION_READ_STATUS_REG 0x05
57 #define W25N01G_INSTRUCTION_READ_STATUS_ALTERNATE_REG 0x0F
58 #define W25N01G_INSTRUCTION_WRITE_STATUS_REG 0x01
59 #define W25N01G_INSTRUCTION_WRITE_STATUS_ALTERNATE_REG 0x1F
60 #define W25N01G_INSTRUCTION_WRITE_ENABLE 0x06
61 #define W25N01G_INSTRUCTION_DIE_SELECT 0xC2
62 #define W25N01G_INSTRUCTION_BLOCK_ERASE 0xD8
63 #define W25N01G_INSTRUCTION_READ_BBM_LUT 0xA5
64 #define W25N01G_INSTRUCTION_BB_MANAGEMENT 0xA1
65 #define W25N01G_INSTRUCTION_PROGRAM_DATA_LOAD 0x02
66 #define W25N01G_INSTRUCTION_RANDOM_PROGRAM_DATA_LOAD 0x84
67 #define W25N01G_INSTRUCTION_PROGRAM_EXECUTE 0x10
68 #define W25N01G_INSTRUCTION_PAGE_DATA_READ 0x13
69 #define W25N01G_INSTRUCTION_READ_DATA 0x03
70 #define W25N01G_INSTRUCTION_FAST_READ 0x1B
71 #define W25N01G_INSTRUCTION_FAST_READ_QUAD_OUTPUT 0x6B
73 // Config/status register addresses
74 #define W25N01G_PROT_REG 0xA0
75 #define W25N01G_CONF_REG 0xB0
76 #define W25N01G_STAT_REG 0xC0
78 // Bits in config/status register 1 (W25N01G_PROT_REG)
79 #define W25N01G_PROT_CLEAR (0)
80 #define W25N01G_PROT_SRP1_ENABLE (1 << 0)
81 #define W25N01G_PROT_WP_E_ENABLE (1 << 1)
82 #define W25N01G_PROT_TB_ENABLE (1 << 2)
83 #define W25N01G_PROT_PB0_ENABLE (1 << 3)
84 #define W25N01G_PROT_PB1_ENABLE (1 << 4)
85 #define W25N01G_PROT_PB2_ENABLE (1 << 5)
86 #define W25N01G_PROT_PB3_ENABLE (1 << 6)
87 #define W25N01G_PROT_SRP2_ENABLE (1 << 7)
89 // Bits in config/status register 2 (W25N01G_CONF_REG)
90 #define W25N01G_CONFIG_ECC_ENABLE (1 << 4)
91 #define W25N01G_CONFIG_BUFFER_READ_MODE (1 << 3)
93 // Bits in config/status register 3 (W25N01G_STATREG)
94 #define W25N01G_STATUS_BBM_LUT_FULL (1 << 6)
95 #define W25N01G_STATUS_FLAG_ECC_POS 4
96 #define W25N01G_STATUS_FLAG_ECC_MASK ((1 << 5)|(1 << 4))
97 #define W25N01G_STATUS_FLAG_ECC(status) (((status) & W25N01G_STATUS_FLAG_ECC_MASK) >> 4)
98 #define W25N01G_STATUS_PROGRAM_FAIL (1 << 3)
99 #define W25N01G_STATUS_ERASE_FAIL (1 << 2)
100 #define W25N01G_STATUS_FLAG_WRITE_ENABLED (1 << 1)
101 #define W25N01G_STATUS_FLAG_BUSY (1 << 0)
103 #define W25N01G_BBLUT_TABLE_ENTRY_COUNT 20
104 #define W25N01G_BBLUT_TABLE_ENTRY_SIZE 4 // in bytes
106 // Bits in LBA for BB LUT
107 #define W25N01G_BBLUT_STATUS_ENABLED (1 << 15)
108 #define W25N01G_BBLUT_STATUS_INVALID (1 << 14)
109 #define W25N01G_BBLUT_STATUS_MASK (W25N01G_BBLUT_STATUS_ENABLED | W25N01G_BBLUT_STATUS_INVALID)
111 // Some useful defs and macros
112 #define W25N01G_LINEAR_TO_COLUMN(laddr) ((laddr) % W25N01G_PAGE_SIZE)
113 #define W25N01G_LINEAR_TO_PAGE(laddr) ((laddr) / W25N01G_PAGE_SIZE)
114 #define W25N01G_LINEAR_TO_BLOCK(laddr) (W25N01G_LINEAR_TO_PAGE(laddr) / W25N01G_PAGES_PER_BLOCK)
115 #define W25N01G_BLOCK_TO_PAGE(block) ((block) * W25N01G_PAGES_PER_BLOCK)
116 #define W25N01G_BLOCK_TO_LINEAR(block) (W25N01G_BLOCK_TO_PAGE(block) * W25N01G_PAGE_SIZE)
118 // IMPORTANT: Timeout values are currently required to be set to the highest value required by any of the supported flash chips by this driver
120 // The timeout values (2ms minimum to avoid 1 tick advance in consecutive calls to millis).
121 #define W25N01G_TIMEOUT_PAGE_READ_MS 2 // tREmax = 60us (ECC enabled)
122 #define W25N01G_TIMEOUT_PAGE_PROGRAM_MS 2 // tPPmax = 700us
123 #define W25N01G_TIMEOUT_BLOCK_ERASE_MS 15 // tBEmax = 10ms
124 #define W25N01G_TIMEOUT_RESET_MS 500 // tRSTmax = 500ms
126 // Sizes (in bits)
127 #define W28N01G_STATUS_REGISTER_SIZE 8
128 #define W28N01G_STATUS_PAGE_ADDRESS_SIZE 16
129 #define W28N01G_STATUS_COLUMN_ADDRESS_SIZE 16
131 typedef struct bblut_s {
132 uint16_t pba;
133 uint16_t lba;
134 } bblut_t;
136 static bool w25n01g_waitForReady(flashDevice_t *fdevice);
138 static void w25n01g_setTimeout(flashDevice_t *fdevice, uint32_t timeoutMillis)
140 uint32_t now = millis();
141 fdevice->timeoutAt = now + timeoutMillis;
145 * Send the given command byte to the device.
147 static void w25n01g_performOneByteCommand(flashDeviceIO_t *io, uint8_t command)
149 if (io->mode == FLASHIO_SPI) {
150 extDevice_t *dev = io->handle.dev;
152 busSegment_t segments[] = {
153 {.u.buffers = {&command, NULL}, sizeof(command), true, NULL},
154 {.u.buffers = {NULL, NULL}, 0, true, NULL},
157 spiSequence(dev, &segments[0]);
159 // Block pending completion of SPI access
160 spiWait(dev);
162 #ifdef USE_QUADSPI
163 else if (io->mode == FLASHIO_QUADSPI) {
164 QUADSPI_TypeDef *quadSpi = io->handle.quadSpi;
165 quadSpiTransmit1LINE(quadSpi, command, 0, NULL, 0);
167 #endif
170 static void w25n01g_performCommandWithPageAddress(flashDeviceIO_t *io, uint8_t command, uint32_t pageAddress)
172 if (io->mode == FLASHIO_SPI) {
173 extDevice_t *dev = io->handle.dev;
175 uint8_t cmd[] = { command, 0, (pageAddress >> 8) & 0xff, (pageAddress >> 0) & 0xff};
177 busSegment_t segments[] = {
178 {.u.buffers = {cmd, NULL}, sizeof(cmd), true, NULL},
179 {.u.buffers = {NULL, NULL}, 0, true, NULL},
182 spiSequence(dev, &segments[0]);
184 // Block pending completion of SPI access
185 spiWait(dev);
187 #ifdef USE_QUADSPI
188 else if (io->mode == FLASHIO_QUADSPI) {
189 QUADSPI_TypeDef *quadSpi = io->handle.quadSpi;
191 quadSpiInstructionWithAddress1LINE(quadSpi, command, 0, pageAddress & 0xffff, W28N01G_STATUS_PAGE_ADDRESS_SIZE + 8);
193 #endif
196 static uint8_t w25n01g_readRegister(flashDeviceIO_t *io, uint8_t reg)
198 if (io->mode == FLASHIO_SPI) {
199 extDevice_t *dev = io->handle.dev;
201 uint8_t cmd[3] = { W25N01G_INSTRUCTION_READ_STATUS_REG, reg, 0 };
202 uint8_t in[3];
204 busSegment_t segments[] = {
205 {.u.buffers = {cmd, in}, sizeof(cmd), true, NULL},
206 {.u.buffers = {NULL, NULL}, 0, true, NULL},
209 // Ensure any prior DMA has completed before continuing
210 spiWait(dev);
212 spiSequence(dev, &segments[0]);
214 // Block pending completion of SPI access
215 spiWait(dev);
217 return in[2];
219 #ifdef USE_QUADSPI
220 else if (io->mode == FLASHIO_QUADSPI) {
222 QUADSPI_TypeDef *quadSpi = io->handle.quadSpi;
224 uint8_t in[1];
225 quadSpiReceiveWithAddress1LINE(quadSpi, W25N01G_INSTRUCTION_READ_STATUS_REG, 0, reg, W28N01G_STATUS_REGISTER_SIZE, in, sizeof(in));
227 return in[0];
229 #endif
230 return 0;
233 static void w25n01g_writeRegister(flashDeviceIO_t *io, uint8_t reg, uint8_t data)
235 if (io->mode == FLASHIO_SPI) {
236 extDevice_t *dev = io->handle.dev;
237 uint8_t cmd[3] = { W25N01G_INSTRUCTION_WRITE_STATUS_REG, reg, data };
239 busSegment_t segments[] = {
240 {.u.buffers = {cmd, NULL}, sizeof(cmd), true, NULL},
241 {.u.buffers = {NULL, NULL}, 0, true, NULL},
244 // Ensure any prior DMA has completed before continuing
245 spiWait(dev);
247 spiSequence(dev, &segments[0]);
249 // Block pending completion of SPI access
250 spiWait(dev);
252 #ifdef USE_QUADSPI
253 else if (io->mode == FLASHIO_QUADSPI) {
254 QUADSPI_TypeDef *quadSpi = io->handle.quadSpi;
256 quadSpiTransmitWithAddress1LINE(quadSpi, W25N01G_INSTRUCTION_WRITE_STATUS_REG, 0, reg, W28N01G_STATUS_REGISTER_SIZE, &data, 1);
258 #endif
262 static void w25n01g_deviceReset(flashDevice_t *fdevice)
264 flashDeviceIO_t *io = &fdevice->io;
266 w25n01g_performOneByteCommand(io, W25N01G_INSTRUCTION_DEVICE_RESET);
268 w25n01g_setTimeout(fdevice, W25N01G_TIMEOUT_RESET_MS);
269 w25n01g_waitForReady(fdevice);
271 // Protection for upper 1/32 (BP[3:0] = 0101, TB=0), WP-E on; to protect bad block replacement area
272 // DON'T DO THIS. This will prevent writes through the bblut as well.
273 // w25n01g_writeRegister(dev, W25N01G_PROT_REG, W25N01G_PROT_PB0_ENABLE|W25N01G_PROT_PB2_ENABLE|W25N01G_PROT_WP_E_ENABLE);
275 // No protection, WP-E off, WP-E prevents use of IO2
276 w25n01g_writeRegister(io, W25N01G_PROT_REG, W25N01G_PROT_CLEAR);
278 // Buffered read mode (BUF = 1), ECC enabled (ECC = 1)
279 w25n01g_writeRegister(io, W25N01G_CONF_REG, W25N01G_CONFIG_ECC_ENABLE|W25N01G_CONFIG_BUFFER_READ_MODE);
282 bool w25n01g_isReady(flashDevice_t *fdevice)
284 uint8_t status = w25n01g_readRegister(&fdevice->io, W25N01G_STAT_REG);
286 return ((status & W25N01G_STATUS_FLAG_BUSY) == 0);
289 static bool w25n01g_waitForReady(flashDevice_t *fdevice)
291 while (!w25n01g_isReady(fdevice)) {
292 uint32_t now = millis();
293 if (cmp32(now, fdevice->timeoutAt) >= 0) {
294 return false;
297 fdevice->timeoutAt = 0;
299 return true;
303 * The flash requires this write enable command to be sent before commands that would cause
304 * a write like program and erase.
306 static void w25n01g_writeEnable(flashDevice_t *fdevice)
308 w25n01g_performOneByteCommand(&fdevice->io, W25N01G_INSTRUCTION_WRITE_ENABLE);
310 // Assume that we're about to do some writing, so the device is just about to become busy
311 fdevice->couldBeBusy = true;
315 * Read chip identification and geometry information (into global `geometry`).
317 * Returns true if we get valid ident, false if something bad happened like there is no M25P16.
319 const flashVTable_t w25n01g_vTable;
321 static void w25n01g_deviceInit(flashDevice_t *flashdev);
323 bool w25n01g_detect(flashDevice_t *fdevice, uint32_t chipID)
325 switch (chipID) {
326 case JEDEC_ID_WINBOND_W25N01GV:
327 fdevice->geometry.sectors = 1024; // Blocks
328 fdevice->geometry.pagesPerSector = 64; // Pages/Blocks
329 fdevice->geometry.pageSize = 2048;
330 break;
332 default:
333 // Unsupported chip
334 fdevice->geometry.sectors = 0;
335 fdevice->geometry.pagesPerSector = 0;
337 fdevice->geometry.sectorSize = 0;
338 fdevice->geometry.totalSize = 0;
339 return false;
342 fdevice->geometry.flashType = FLASH_TYPE_NAND;
343 fdevice->geometry.sectorSize = fdevice->geometry.pagesPerSector * fdevice->geometry.pageSize;
344 fdevice->geometry.totalSize = fdevice->geometry.sectorSize * fdevice->geometry.sectors;
346 flashPartitionSet(FLASH_PARTITION_TYPE_BADBLOCK_MANAGEMENT,
347 W25N01G_BB_MANAGEMENT_START_BLOCK,
348 W25N01G_BB_MANAGEMENT_START_BLOCK + W25N01G_BB_MANAGEMENT_BLOCKS - 1);
350 fdevice->couldBeBusy = true; // Just for luck we'll assume the chip could be busy even though it isn't specced to be
352 w25n01g_deviceReset(fdevice);
354 // Upper 4MB (32 blocks * 128KB/block) will be used for bad block replacement area.
356 // Blocks in this area are only written through bad block LUT,
357 // and factory written bad block marker in unused blocks are retained.
359 // When a replacement block is required,
360 // (1) "Read BB LUT" command is used to obtain the last block mapped,
361 // (2) blocks after the last block is scanned for a good block,
362 // (3) the first good block is used for replacement, and the BB LUT is updated.
364 // There are only 20 BB LUT entries, and there are 32 replacement blocks.
365 // There will be a least chance of running out of replacement blocks.
366 // If it ever run out, the device becomes unusable.
368 w25n01g_deviceInit(fdevice);
370 fdevice->vTable = &w25n01g_vTable;
372 return true;
376 * Erase a sector full of bytes to all 1's at the given byte offset in the flash chip.
378 void w25n01g_eraseSector(flashDevice_t *fdevice, uint32_t address)
381 w25n01g_waitForReady(fdevice);
383 w25n01g_writeEnable(fdevice);
385 w25n01g_performCommandWithPageAddress(&fdevice->io, W25N01G_INSTRUCTION_BLOCK_ERASE, W25N01G_LINEAR_TO_PAGE(address));
387 w25n01g_setTimeout(fdevice, W25N01G_TIMEOUT_BLOCK_ERASE_MS);
391 // W25N01G does not support full chip erase.
392 // Call eraseSector repeatedly.
394 void w25n01g_eraseCompletely(flashDevice_t *fdevice)
396 for (uint32_t block = 0; block < fdevice->geometry.sectors; block++) {
397 w25n01g_eraseSector(fdevice, W25N01G_BLOCK_TO_LINEAR(block));
401 static void w25n01g_programDataLoad(flashDevice_t *fdevice, uint16_t columnAddress, const uint8_t *data, int length)
404 w25n01g_waitForReady(fdevice);
406 if (fdevice->io.mode == FLASHIO_SPI) {
407 extDevice_t *dev = fdevice->io.handle.dev;
408 uint8_t cmd[] = { W25N01G_INSTRUCTION_PROGRAM_DATA_LOAD, columnAddress >> 8, columnAddress & 0xff };
410 busSegment_t segments[] = {
411 {.u.buffers = {cmd, NULL}, sizeof(cmd), false, NULL},
412 {.u.buffers = {(uint8_t *)data, NULL}, length, true, NULL},
413 {.u.buffers = {NULL, NULL}, 0, true, NULL},
416 spiSequence(dev, &segments[0]);
418 // Block pending completion of SPI access
419 spiWait(dev);
421 #ifdef USE_QUADSPI
422 else if (fdevice->io.mode == FLASHIO_QUADSPI) {
423 QUADSPI_TypeDef *quadSpi = fdevice->io.handle.quadSpi;
425 quadSpiTransmitWithAddress1LINE(quadSpi, W25N01G_INSTRUCTION_PROGRAM_DATA_LOAD, 0, columnAddress, W28N01G_STATUS_COLUMN_ADDRESS_SIZE, data, length);
427 #endif
429 w25n01g_setTimeout(fdevice, W25N01G_TIMEOUT_PAGE_PROGRAM_MS);
432 static void w25n01g_randomProgramDataLoad(flashDevice_t *fdevice, uint16_t columnAddress, const uint8_t *data, int length)
434 uint8_t cmd[] = { W25N01G_INSTRUCTION_RANDOM_PROGRAM_DATA_LOAD, columnAddress >> 8, columnAddress & 0xff };
436 w25n01g_waitForReady(fdevice);
438 if (fdevice->io.mode == FLASHIO_SPI) {
439 extDevice_t *dev = fdevice->io.handle.dev;
441 busSegment_t segments[] = {
442 {.u.buffers = {cmd, NULL}, sizeof(cmd), false, NULL},
443 {.u.buffers = {(uint8_t *)data, NULL}, length, true, NULL},
444 {.u.buffers = {NULL, NULL}, 0, true, NULL},
447 spiSequence(dev, &segments[0]);
449 // Block pending completion of SPI access
450 spiWait(dev);
452 #ifdef USE_QUADSPI
453 else if (fdevice->io.mode == FLASHIO_QUADSPI) {
454 QUADSPI_TypeDef *quadSpi = fdevice->io.handle.quadSpi;
456 quadSpiTransmitWithAddress1LINE(quadSpi, W25N01G_INSTRUCTION_RANDOM_PROGRAM_DATA_LOAD, 0, columnAddress, W28N01G_STATUS_COLUMN_ADDRESS_SIZE, data, length);
458 #endif
460 w25n01g_setTimeout(fdevice, W25N01G_TIMEOUT_PAGE_PROGRAM_MS);
464 static void w25n01g_programExecute(flashDevice_t *fdevice, uint32_t pageAddress)
466 w25n01g_waitForReady(fdevice);
468 w25n01g_performCommandWithPageAddress(&fdevice->io, W25N01G_INSTRUCTION_PROGRAM_EXECUTE, pageAddress);
470 w25n01g_setTimeout(fdevice, W25N01G_TIMEOUT_PAGE_PROGRAM_MS);
474 // Writes are done in three steps:
475 // (1) Load internal data buffer with data to write
476 // - We use "Random Load Program Data", as "Load Program Data" resets unused data bytes in the buffer to 0xff.
477 // - Each "Random Load Program Data" instruction must be accompanied by at least a single data.
478 // - Each "Random Load Program Data" instruction terminates at the rising of CS.
479 // (2) Enable write
480 // (3) Issue "Execute Program"
484 flashfs page program behavior
485 - Single program never crosses page boundary.
486 - Except for this characteristic, it program arbitral size.
487 - Write address is, naturally, not a page boundary.
489 To cope with this behavior.
491 pageProgramBegin:
492 If buffer is dirty and programLoadAddress != address, then the last page is a partial write;
493 issue PAGE_PROGRAM_EXECUTE to flash buffer contents, clear dirty and record the address as programLoadAddress and programStartAddress.
494 Else do nothing.
496 pageProgramContinue:
497 Mark buffer as dirty.
498 If programLoadAddress is on page boundary, then issue PROGRAM_LOAD_DATA, else issue RANDOM_PROGRAM_LOAD_DATA.
499 Update programLoadAddress.
500 Optionally observe the programLoadAddress, and if it's on page boundary, issue PAGE_PROGRAM_EXECUTE.
502 pageProgramFinish:
503 Observe programLoadAddress. If it's on page boundary, issue PAGE_PROGRAM_EXECUTE and clear dirty, else just return.
504 If pageProgramContinue observes the page boundary, then do nothing(?).
507 static uint32_t programStartAddress;
508 static uint32_t programLoadAddress;
509 bool bufferDirty = false;
510 bool isProgramming = false;
512 void w25n01g_pageProgramBegin(flashDevice_t *fdevice, uint32_t address, void (*callback)(uint32_t length))
514 fdevice->callback = callback;
516 if (bufferDirty) {
517 if (address != programLoadAddress) {
518 w25n01g_waitForReady(fdevice);
520 isProgramming = false;
522 w25n01g_writeEnable(fdevice);
524 w25n01g_programExecute(fdevice, W25N01G_LINEAR_TO_PAGE(programStartAddress));
526 bufferDirty = false;
527 isProgramming = true;
529 } else {
530 programStartAddress = programLoadAddress = address;
534 uint32_t w25n01g_pageProgramContinue(flashDevice_t *fdevice, uint8_t const **buffers, uint32_t *bufferSizes, uint32_t bufferCount)
536 if (bufferCount < 1) {
537 fdevice->callback(0);
538 return 0;
541 w25n01g_waitForReady(fdevice);
543 w25n01g_writeEnable(fdevice);
545 isProgramming = false;
547 if (!bufferDirty) {
548 w25n01g_programDataLoad(fdevice, W25N01G_LINEAR_TO_COLUMN(programLoadAddress), buffers[0], bufferSizes[0]);
549 } else {
550 w25n01g_randomProgramDataLoad(fdevice, W25N01G_LINEAR_TO_COLUMN(programLoadAddress), buffers[0], bufferSizes[0]);
553 // XXX Test if write enable is reset after each data loading.
555 bufferDirty = true;
556 programLoadAddress += bufferSizes[0];
558 if (fdevice->callback) {
559 fdevice->callback(bufferSizes[0]);
562 return bufferSizes[0];
565 static uint32_t currentPage = UINT32_MAX;
567 void w25n01g_pageProgramFinish(flashDevice_t *fdevice)
569 if (bufferDirty && W25N01G_LINEAR_TO_COLUMN(programLoadAddress) == 0) {
571 currentPage = W25N01G_LINEAR_TO_PAGE(programStartAddress); // reset page to the page being written
573 w25n01g_programExecute(fdevice, W25N01G_LINEAR_TO_PAGE(programStartAddress));
575 bufferDirty = false;
576 isProgramming = true;
578 programStartAddress = programLoadAddress;
583 * Write bytes to a flash page. Address must not cross a page boundary.
585 * Bits can only be set to zero, not from zero back to one again. In order to set bits to 1, use the erase command.
587 * Length must be smaller than the page size.
589 * This will wait for the flash to become ready before writing begins.
591 * Datasheet indicates typical programming time is 0.8ms for 256 bytes, 0.2ms for 64 bytes, 0.05ms for 16 bytes.
592 * (Although the maximum possible write time is noted as 5ms).
594 * If you want to write multiple buffers (whose sum of sizes is still not more than the page size) then you can
595 * break this operation up into one beginProgram call, one or more continueProgram calls, and one finishProgram call.
598 void w25n01g_pageProgram(flashDevice_t *fdevice, uint32_t address, const uint8_t *data, uint32_t length, void (*callback)(uint32_t length))
600 w25n01g_pageProgramBegin(fdevice, address, callback);
601 w25n01g_pageProgramContinue(fdevice, &data, &length, 1);
602 w25n01g_pageProgramFinish(fdevice);
605 void w25n01g_flush(flashDevice_t *fdevice)
607 if (bufferDirty) {
608 currentPage = W25N01G_LINEAR_TO_PAGE(programStartAddress); // reset page to the page being written
610 w25n01g_programExecute(fdevice, W25N01G_LINEAR_TO_PAGE(programStartAddress));
612 bufferDirty = false;
613 isProgramming = true;
614 } else {
615 isProgramming = false;
619 void w25n01g_addError(uint32_t address, uint8_t code)
621 UNUSED(address);
622 UNUSED(code);
626 * Read `length` bytes into the provided `buffer` from the flash starting from the given `address` (which need not lie
627 * on a page boundary).
629 * Waits up to W25N01G_TIMEOUT_PAGE_READ_MS milliseconds for the flash to become ready before reading.
631 * The number of bytes actually read is returned, which can be zero if an error or timeout occurred.
634 // Continuous read mode (BUF = 0):
635 // (1) "Page Data Read" command is executed for the page pointed by address
636 // (2) "Read Data" command is executed for bytes not requested and data are discarded
637 // (3) "Read Data" command is executed and data are stored directly into caller's buffer
639 // Buffered read mode (BUF = 1), non-read ahead
640 // (1) If currentBufferPage != requested page, then issue PAGE_DATA_READ on requested page.
641 // (2) Compute transferLength as smaller of remaining length and requested length.
642 // (3) Issue READ_DATA on column address.
643 // (4) Return transferLength.
645 int w25n01g_readBytes(flashDevice_t *fdevice, uint32_t address, uint8_t *buffer, uint32_t length)
647 uint32_t targetPage = W25N01G_LINEAR_TO_PAGE(address);
649 if (currentPage != targetPage) {
650 if (!w25n01g_waitForReady(fdevice)) {
651 return 0;
654 currentPage = UINT32_MAX;
656 w25n01g_performCommandWithPageAddress(&fdevice->io, W25N01G_INSTRUCTION_PAGE_DATA_READ, targetPage);
658 w25n01g_setTimeout(fdevice, W25N01G_TIMEOUT_PAGE_READ_MS);
659 if (!w25n01g_waitForReady(fdevice)) {
660 return 0;
663 currentPage = targetPage;
666 uint32_t column = W25N01G_LINEAR_TO_COLUMN(address);
667 uint16_t transferLength;
669 if (length > W25N01G_PAGE_SIZE - column) {
670 transferLength = W25N01G_PAGE_SIZE - column;
671 } else {
672 transferLength = length;
675 if (fdevice->io.mode == FLASHIO_SPI) {
676 extDevice_t *dev = fdevice->io.handle.dev;
678 uint8_t cmd[4];
679 cmd[0] = W25N01G_INSTRUCTION_READ_DATA;
680 cmd[1] = (column >> 8) & 0xff;
681 cmd[2] = (column >> 0) & 0xff;
682 cmd[3] = 0;
684 busSegment_t segments[] = {
685 {.u.buffers = {cmd, NULL}, sizeof(cmd), false, NULL},
686 {.u.buffers = {NULL, buffer}, length, true, NULL},
687 {.u.buffers = {NULL, NULL}, 0, true, NULL},
690 spiSequence(dev, &segments[0]);
692 // Block pending completion of SPI access
693 spiWait(dev);
695 #ifdef USE_QUADSPI
696 else if (fdevice->io.mode == FLASHIO_QUADSPI) {
697 QUADSPI_TypeDef *quadSpi = fdevice->io.handle.quadSpi;
699 //quadSpiReceiveWithAddress1LINE(quadSpi, W25N01G_INSTRUCTION_READ_DATA, 8, column, W28N01G_STATUS_COLUMN_ADDRESS_SIZE, buffer, length);
700 quadSpiReceiveWithAddress4LINES(quadSpi, W25N01G_INSTRUCTION_FAST_READ_QUAD_OUTPUT, 8, column, W28N01G_STATUS_COLUMN_ADDRESS_SIZE, buffer, length);
702 #endif
704 // XXX Don't need this?
705 w25n01g_setTimeout(fdevice, W25N01G_TIMEOUT_PAGE_READ_MS);
706 if (!w25n01g_waitForReady(fdevice)) {
707 return 0;
710 // Check ECC
712 uint8_t statReg = w25n01g_readRegister(&fdevice->io, W25N01G_STAT_REG);
713 uint8_t eccCode = W25N01G_STATUS_FLAG_ECC(statReg);
715 switch (eccCode) {
716 case 0: // Successful read, no ECC correction
717 break;
718 case 1: // Successful read with ECC correction
719 case 2: // Uncorrectable ECC in a single page
720 case 3: // Uncorrectable ECC in multiple pages
721 w25n01g_addError(address, eccCode);
722 w25n01g_deviceReset(fdevice);
723 break;
726 return transferLength;
729 int w25n01g_readExtensionBytes(flashDevice_t *fdevice, uint32_t address, uint8_t *buffer, int length)
732 if (!w25n01g_waitForReady(fdevice)) {
733 return 0;
736 w25n01g_performCommandWithPageAddress(&fdevice->io, W25N01G_INSTRUCTION_PAGE_DATA_READ, W25N01G_LINEAR_TO_PAGE(address));
738 uint32_t column = 2048;
740 if (fdevice->io.mode == FLASHIO_SPI) {
741 extDevice_t *dev = fdevice->io.handle.dev;
743 uint8_t cmd[4];
744 cmd[0] = W25N01G_INSTRUCTION_READ_DATA;
745 cmd[1] = (column >> 8) & 0xff;
746 cmd[2] = (column >> 0) & 0xff;
747 cmd[3] = 0;
749 busSegment_t segments[] = {
750 {.u.buffers = {cmd, NULL}, sizeof(cmd), false, NULL},
751 {.u.buffers = {NULL, buffer}, length, true, NULL},
752 {.u.buffers = {NULL, NULL}, 0, true, NULL},
755 // Ensure any prior DMA has completed before continuing
756 spiWait(dev);
758 spiSequence(dev, &segments[0]);
760 // Block pending completion of SPI access
761 spiWait(dev);
764 #ifdef USE_QUADSPI
765 else if (fdevice->io.mode == FLASHIO_QUADSPI) {
766 QUADSPI_TypeDef *quadSpi = fdevice->io.handle.quadSpi;
768 quadSpiReceiveWithAddress1LINE(quadSpi, W25N01G_INSTRUCTION_READ_DATA, 8, column, W28N01G_STATUS_COLUMN_ADDRESS_SIZE, buffer, length);
770 #endif
772 w25n01g_setTimeout(fdevice, W25N01G_TIMEOUT_PAGE_READ_MS);
774 return length;
778 * Fetch information about the detected flash chip layout.
780 * Can be called before calling w25n01g_init() (the result would have totalSize = 0).
782 const flashGeometry_t* w25n01g_getGeometry(flashDevice_t *fdevice)
784 return &fdevice->geometry;
787 const flashVTable_t w25n01g_vTable = {
788 .isReady = w25n01g_isReady,
789 .waitForReady = w25n01g_waitForReady,
790 .eraseSector = w25n01g_eraseSector,
791 .eraseCompletely = w25n01g_eraseCompletely,
792 .pageProgramBegin = w25n01g_pageProgramBegin,
793 .pageProgramContinue = w25n01g_pageProgramContinue,
794 .pageProgramFinish = w25n01g_pageProgramFinish,
795 .pageProgram = w25n01g_pageProgram,
796 .flush = w25n01g_flush,
797 .readBytes = w25n01g_readBytes,
798 .getGeometry = w25n01g_getGeometry,
801 typedef volatile struct cb_context_s {
802 flashDevice_t *fdevice;
803 bblut_t *bblut;
804 int lutsize;
805 int lutindex;
806 } cb_context_t;
808 // Called in ISR context
809 // Read of BBLUT entry has just completed
810 busStatus_e w25n01g_readBBLUTCallback(uint32_t arg)
812 cb_context_t *cb_context = (cb_context_t *)arg;
813 flashDevice_t *fdevice = cb_context->fdevice;
814 uint8_t *rxData = fdevice->io.handle.dev->bus->curSegment->u.buffers.rxData;
817 cb_context->bblut->pba = (rxData[0] << 16)|rxData[1];
818 cb_context->bblut->lba = (rxData[2] << 16)|rxData[3];
820 if (++cb_context->lutindex < cb_context->lutsize) {
821 cb_context->bblut++;
822 return BUS_BUSY; // Repeat the operation
825 return BUS_READY; // All done
829 void w25n01g_readBBLUT(flashDevice_t *fdevice, bblut_t *bblut, int lutsize)
831 cb_context_t cb_context;
832 uint8_t in[4];
834 cb_context.fdevice = fdevice;
835 fdevice->callbackArg = (uint32_t)&cb_context;
837 if (fdevice->io.mode == FLASHIO_SPI) {
838 extDevice_t *dev = fdevice->io.handle.dev;
840 uint8_t cmd[4];
842 cmd[0] = W25N01G_INSTRUCTION_READ_BBM_LUT;
843 cmd[1] = 0;
845 cb_context.bblut = &bblut[0];
846 cb_context.lutsize = lutsize;
847 cb_context.lutindex = 0;
849 busSegment_t segments[] = {
850 {.u.buffers = {cmd, NULL}, sizeof(cmd), false, NULL},
851 {.u.buffers = {NULL, in}, sizeof(in), true, w25n01g_readBBLUTCallback},
852 {.u.buffers = {NULL, NULL}, 0, true, NULL},
855 spiSequence(dev, &segments[0]);
857 // Block pending completion of SPI access
858 spiWait(dev);
860 #ifdef USE_QUADSPI
861 else if (fdevice->io.mode == FLASHIO_QUADSPI) {
862 QUADSPI_TypeDef *quadSpi = fdevice->io.handle.quadSpi;
864 // Note: Using HAL QuadSPI there doesn't appear to be a way to send 2 bytes, then blocks of 4 bytes, while keeping the CS line LOW
865 // thus, we have to read the entire BBLUT in one go and process the result.
867 uint8_t bblutBuffer[W25N01G_BBLUT_TABLE_ENTRY_COUNT * W25N01G_BBLUT_TABLE_ENTRY_SIZE];
868 quadSpiReceive1LINE(quadSpi, W25N01G_INSTRUCTION_READ_BBM_LUT, 8, bblutBuffer, sizeof(bblutBuffer));
870 for (int i = 0, offset = 0 ; i < lutsize ; i++, offset += 4) {
871 if (i < W25N01G_BBLUT_TABLE_ENTRY_COUNT) {
872 bblut[i].pba = (in[offset + 0] << 16)|in[offset + 1];
873 bblut[i].lba = (in[offset + 2] << 16)|in[offset + 3];
877 #endif
880 void w25n01g_writeBBLUT(flashDevice_t *fdevice, uint16_t lba, uint16_t pba)
882 w25n01g_waitForReady(fdevice);
884 if (fdevice->io.mode == FLASHIO_SPI) {
885 extDevice_t *dev = fdevice->io.handle.dev;
887 uint8_t cmd[5] = { W25N01G_INSTRUCTION_BB_MANAGEMENT, lba >> 8, lba, pba >> 8, pba };
889 busSegment_t segments[] = {
890 {.u.buffers = {cmd, NULL}, sizeof(cmd), true, NULL},
891 {.u.buffers = {NULL, NULL}, 0, true, NULL},
894 // Ensure any prior DMA has completed before continuing
895 spiWait(dev);
897 spiSequence(dev, &segments[0]);
899 // Block pending completion of SPI access
900 spiWait(dev);
902 #ifdef USE_QUADSPI
903 else if (fdevice->io.mode == FLASHIO_QUADSPI) {
904 QUADSPI_TypeDef *quadSpi = fdevice->io.handle.quadSpi;
906 uint8_t data[4] = { lba >> 8, lba, pba >> 8, pba };
907 quadSpiInstructionWithData1LINE(quadSpi, W25N01G_INSTRUCTION_BB_MANAGEMENT, 0, data, sizeof(data));
909 #endif
911 w25n01g_setTimeout(fdevice, W25N01G_TIMEOUT_PAGE_PROGRAM_MS);
914 static void w25n01g_deviceInit(flashDevice_t *flashdev)
916 UNUSED(flashdev);
918 #endif