Release v4.15864 - Radium
[RRG-proxmark3.git] / armsrc / flashmem.c
blob42654014343597d3b7f2551435132cac9d5aea20
1 //-----------------------------------------------------------------------------
2 // Borrowed initially from Arduino SPIFlash Library v.2.5.0
3 // Copyright (C) 2015 by Prajwal Bhattaram.
4 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
5 //
6 // This program 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 3 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 // See LICENSE.txt for the text of the license.
17 //-----------------------------------------------------------------------------
18 #include "flashmem.h"
19 #include "pmflash.h"
21 #include "proxmark3_arm.h"
22 #include "ticks.h"
23 #include "dbprint.h"
24 #include "string.h"
25 #include "spiffs.h"
27 /* here: use NCPS2 @ PA10: */
28 #define SPI_CSR_NUM 2
29 #define SPI_PCS(npcs) ((~(1 << (npcs)) & 0xF) << 16)
30 /// Calculates the value of the CSR SCBR field given the baudrate and MCK.
31 #define SPI_SCBR(baudrate, masterClock) ((uint32_t) ((masterClock) / (baudrate)) << 8)
32 /// Calculates the value of the CSR DLYBS field given the desired delay (in ns)
33 #define SPI_DLYBS(delay, masterClock) ((uint32_t) ((((masterClock) / 1000000) * (delay)) / 1000) << 16)
34 /// Calculates the value of the CSR DLYBCT field given the desired delay (in ns)
35 #define SPI_DLYBCT(delay, masterClock) ((uint32_t) ((((masterClock) / 1000000) * (delay)) / 32000) << 24)
37 static uint32_t FLASHMEM_SPIBAUDRATE = FLASH_BAUD;
38 #define FASTFLASH (FLASHMEM_SPIBAUDRATE > FLASH_MINFAST)
40 void FlashmemSetSpiBaudrate(uint32_t baudrate) {
41 FLASHMEM_SPIBAUDRATE = baudrate;
42 Dbprintf("Spi Baudrate : %dMHz", FLASHMEM_SPIBAUDRATE / 1000000);
45 // initialize
46 bool FlashInit(void) {
47 FlashSetup(FLASHMEM_SPIBAUDRATE);
49 StartTicks();
51 if (Flash_CheckBusy(BUSY_TIMEOUT)) {
52 StopTicks();
53 return false;
56 return true;
59 void FlashSetup(uint32_t baudrate) {
60 //WDT_DISABLE
61 AT91C_BASE_WDTC->WDTC_WDMR = AT91C_WDTC_WDDIS;
63 // PA10 -> SPI_NCS2 chip select (FLASHMEM)
64 // PA11 -> SPI_NCS0 chip select (FPGA)
65 // PA12 -> SPI_MISO Master-In Slave-Out
66 // PA13 -> SPI_MOSI Master-Out Slave-In
67 // PA14 -> SPI_SPCK Serial Clock
69 // Disable PIO control of the following pins, allows use by the SPI peripheral
70 AT91C_BASE_PIOA->PIO_PDR |= (GPIO_NCS0 | GPIO_MISO | GPIO_MOSI | GPIO_SPCK | GPIO_NCS2);
72 // Pull-up Enable
73 AT91C_BASE_PIOA->PIO_PPUER |= (GPIO_NCS0 | GPIO_MISO | GPIO_MOSI | GPIO_SPCK | GPIO_NCS2);
75 // Peripheral A
76 AT91C_BASE_PIOA->PIO_ASR |= (GPIO_NCS0 | GPIO_MISO | GPIO_MOSI | GPIO_SPCK);
78 // Peripheral B
79 AT91C_BASE_PIOA->PIO_BSR |= GPIO_NCS2;
81 //enable the SPI Peripheral clock
82 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_SPI);
85 //reset spi needs double SWRST, see atmel's errata on this case
86 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SWRST;
87 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SWRST;
89 // Enable SPI
90 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SPIEN;
92 // NPCS2 Mode 0
93 AT91C_BASE_SPI->SPI_MR =
94 (0 << 24) | // Delay between chip selects = DYLBCS/MCK BUT:
95 // If DLYBCS is less than or equal to six, six MCK periods
96 // will be inserted by default.
97 SPI_PCS(SPI_CSR_NUM) | // Peripheral Chip Select (selects SPI_NCS2 or PA10)
98 (0 << 7) | // Disable LLB (1=MOSI2MISO test mode)
99 (1 << 4) | // Disable ModeFault Protection
100 (0 << 3) | // makes spi operate at MCK (1 is MCK/2)
101 (0 << 2) | // Chip selects connected directly to peripheral
102 AT91C_SPI_PS_FIXED | // Fixed Peripheral Select
103 AT91C_SPI_MSTR; // Master Mode
105 uint8_t csaat = 1;
106 uint32_t dlybct = 0;
107 uint8_t ncpha = 1;
108 uint8_t cpol = 0;
109 if (baudrate > FLASH_MINFAST) {
110 baudrate = FLASH_FASTBAUD;
111 //csaat = 0;
112 dlybct = 1500;
113 ncpha = 0;
114 cpol = 0;
117 AT91C_BASE_SPI->SPI_CSR[2] =
118 SPI_DLYBCT(dlybct, MCK) | // Delay between Consecutive Transfers (32 MCK periods)
119 SPI_DLYBS(0, MCK) | // Delay Beforce SPCK CLock
120 SPI_SCBR(baudrate, MCK) | // SPI Baudrate Selection
121 AT91C_SPI_BITS_8 | // Bits per Transfer (8 bits)
122 //AT91C_SPI_CSAAT | // Chip Select inactive after transfer
123 // 40.4.6.2 SPI: Bad tx_ready Behavior when CSAAT = 1 and SCBR = 1
124 // If the SPI is programmed with CSAAT = 1, SCBR(baudrate) = 1 and two transfers are performed consecutively on
125 // the same slave with an IDLE state between them, the tx_ready signal does not rise after the second data has been
126 // transferred in the shifter. This can imply for example, that the second data is sent twice.
127 // COLIN :: For now we STILL use CSAAT=1 to avoid having to (de)assert NPCS manually via PIO lines and we deal with delay
128 (csaat << 3) |
129 /* Spi modes:
130 Mode CPOL CPHA NCPHA
131 0 0 0 1 clock normally low read on rising edge
132 1 0 1 0 clock normally low read on falling edge
133 2 1 0 1 clock normally high read on falling edge
134 3 1 1 0 clock normally high read on rising edge
135 However, page 512 of the AT91SAM7Sx datasheet say "Note that in SPI
136 master mode the ATSAM7S512/256/128/64/321/32 does not sample the data
137 (MISO) on the opposite edge where data clocks out (MOSI) but the same
138 edge is used as shown in Figure 36-3 and Figure 36-4." Figure 36-3
139 shows that CPOL=NCPHA=0 or CPOL=NCPHA=1 samples on the rising edge and
140 that the data changes sometime after the rising edge (about 2 ns). To
141 be consistent with normal SPI operation, it is probably safe to say
142 that the data changes on the falling edge and should be sampled on the
143 rising edge. Therefore, it appears that NCPHA should be treated the
144 same as CPHA. Thus:
145 Mode CPOL CPHA NCPHA
146 0 0 0 0 clock normally low read on rising edge
147 1 0 1 1 clock normally low read on falling edge
148 2 1 0 0 clock normally high read on falling edge
149 3 1 1 1 clock normally high read on rising edge
150 Update: for 24MHz, writing is more stable with ncpha=1, else bitflips occur.
152 (ncpha << 1) | // Clock Phase data captured on leading edge, changes on following edge
153 (cpol << 0); // Clock Polarity inactive state is logic 0
155 // read first, empty buffer
156 if (AT91C_BASE_SPI->SPI_RDR == 0) {};
159 void FlashStop(void) {
160 //Bof
161 //* Reset all the Chip Select register
162 AT91C_BASE_SPI->SPI_CSR[0] = 0;
163 AT91C_BASE_SPI->SPI_CSR[1] = 0;
164 AT91C_BASE_SPI->SPI_CSR[2] = 0;
165 AT91C_BASE_SPI->SPI_CSR[3] = 0;
167 // Reset the SPI mode
168 AT91C_BASE_SPI->SPI_MR = 0;
170 // Disable all interrupts
171 AT91C_BASE_SPI->SPI_IDR = 0xFFFFFFFF;
173 // SPI disable
174 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SPIDIS;
176 if (g_dbglevel > 3) Dbprintf("FlashStop");
178 StopTicks();
181 // send one byte over SPI
182 uint16_t FlashSendByte(uint32_t data) {
184 // wait until SPI is ready for transfer
185 //if you are checking for incoming data returned then the TXEMPTY flag is redundant
186 //while ((AT91C_BASE_SPI->SPI_SR & AT91C_SPI_TXEMPTY) == 0) {};
188 // send the data
189 AT91C_BASE_SPI->SPI_TDR = data;
191 //while ((AT91C_BASE_SPI->SPI_SR & AT91C_SPI_TDRE) == 0){};
193 // wait receive transfer is complete
194 while ((AT91C_BASE_SPI->SPI_SR & AT91C_SPI_RDRF) == 0) {};
196 // reading incoming data
197 return ((AT91C_BASE_SPI->SPI_RDR) & 0xFFFF);
200 // send last byte over SPI
201 uint16_t FlashSendLastByte(uint32_t data) {
202 return FlashSendByte(data | AT91C_SPI_LASTXFER);
205 // read state register 1
206 uint8_t Flash_ReadStat1(void) {
207 FlashSendByte(READSTAT1);
208 return FlashSendLastByte(0xFF);
211 bool Flash_CheckBusy(uint32_t timeout) {
212 WaitUS(WINBOND_WRITE_DELAY);
213 StartCountUS();
214 uint32_t _time = GetCountUS();
216 if (g_dbglevel > 3) Dbprintf("Checkbusy in...");
218 do {
219 if (!(Flash_ReadStat1() & BUSY)) {
220 return false;
222 } while ((GetCountUS() - _time) < timeout);
224 if (timeout <= (GetCountUS() - _time)) {
225 return true;
228 return false;
231 // read ID out
232 uint8_t Flash_ReadID(void) {
234 if (Flash_CheckBusy(BUSY_TIMEOUT)) return 0;
236 // Manufacture ID / device ID
237 FlashSendByte(ID);
238 FlashSendByte(0x00);
239 FlashSendByte(0x00);
240 FlashSendByte(0x00);
242 uint8_t man_id = FlashSendByte(0xFF);
243 uint8_t dev_id = FlashSendLastByte(0xFF);
245 if (g_dbglevel > 3) Dbprintf("Flash ReadID | Man ID %02x | Device ID %02x", man_id, dev_id);
247 if ((man_id == WINBOND_MANID) && (dev_id == WINBOND_DEVID))
248 return dev_id;
250 return 0;
253 // read unique id for chip.
254 void Flash_UniqueID(uint8_t *uid) {
256 if (Flash_CheckBusy(BUSY_TIMEOUT)) return;
258 // reading unique serial number
259 FlashSendByte(UNIQUE_ID);
260 FlashSendByte(0xFF);
261 FlashSendByte(0xFF);
262 FlashSendByte(0xFF);
263 FlashSendByte(0xFF);
265 uid[7] = FlashSendByte(0xFF);
266 uid[6] = FlashSendByte(0xFF);
267 uid[5] = FlashSendByte(0xFF);
268 uid[4] = FlashSendByte(0xFF);
269 uid[3] = FlashSendByte(0xFF);
270 uid[2] = FlashSendByte(0xFF);
271 uid[1] = FlashSendByte(0xFF);
272 uid[0] = FlashSendLastByte(0xFF);
275 uint16_t Flash_ReadData(uint32_t address, uint8_t *out, uint16_t len) {
277 if (!FlashInit()) return 0;
279 // length should never be zero
280 if (!len || Flash_CheckBusy(BUSY_TIMEOUT)) return 0;
282 uint8_t cmd = (FASTFLASH) ? FASTREAD : READDATA;
284 FlashSendByte(cmd);
285 Flash_TransferAdresse(address);
287 if (FASTFLASH) {
288 FlashSendByte(DUMMYBYTE);
291 uint16_t i = 0;
292 for (; i < (len - 1); i++)
293 out[i] = FlashSendByte(0xFF);
295 out[i] = FlashSendLastByte(0xFF);
296 FlashStop();
297 return len;
300 void Flash_TransferAdresse(uint32_t address) {
301 FlashSendByte((address >> 16) & 0xFF);
302 FlashSendByte((address >> 8) & 0xFF);
303 FlashSendByte((address >> 0) & 0xFF);
306 /* This ensures we can ReadData without having to cycle through initialization every time */
307 uint16_t Flash_ReadDataCont(uint32_t address, uint8_t *out, uint16_t len) {
309 // length should never be zero
310 if (!len) return 0;
312 uint8_t cmd = (FASTFLASH) ? FASTREAD : READDATA;
314 FlashSendByte(cmd);
315 Flash_TransferAdresse(address);
317 if (FASTFLASH) {
318 FlashSendByte(DUMMYBYTE);
321 uint16_t i = 0;
322 for (; i < (len - 1); i++)
323 out[i] = FlashSendByte(0xFF);
325 out[i] = FlashSendLastByte(0xFF);
326 return len;
330 ////////////////////////////////////////
331 // Write data can only program one page. A page has 256 bytes.
332 // if len > 256, it might wrap around and overwrite pos 0.
333 uint16_t Flash_WriteData(uint32_t address, uint8_t *in, uint16_t len) {
335 // length should never be zero
336 if (!len)
337 return 0;
339 // Max 256 bytes write
340 if (((address & 0xFF) + len) > 256) {
341 Dbprintf("Flash_WriteData 256 fail [ 0x%02x ] [ %u ]", (address & 0xFF) + len, len);
342 return 0;
345 // out-of-range
346 if (((address >> 16) & 0xFF) > MAX_BLOCKS) {
347 Dbprintf("Flash_WriteData, block out-of-range");
348 return 0;
351 if (!FlashInit()) {
352 if (g_dbglevel > 3) Dbprintf("Flash_WriteData init fail");
353 return 0;
356 Flash_CheckBusy(BUSY_TIMEOUT);
358 Flash_WriteEnable();
360 FlashSendByte(PAGEPROG);
361 FlashSendByte((address >> 16) & 0xFF);
362 FlashSendByte((address >> 8) & 0xFF);
363 FlashSendByte((address >> 0) & 0xFF);
365 uint16_t i = 0;
366 for (; i < (len - 1); i++)
367 FlashSendByte(in[i]);
369 FlashSendLastByte(in[i]);
371 FlashStop();
372 return len;
376 // length should never be zero
377 // Max 256 bytes write
378 // out-of-range
379 uint16_t Flash_WriteDataCont(uint32_t address, uint8_t *in, uint16_t len) {
381 if (!len)
382 return 0;
384 if (((address & 0xFF) + len) > 256) {
385 Dbprintf("Flash_WriteDataCont 256 fail [ 0x%02x ] [ %u ]", (address & 0xFF) + len, len);
386 return 0;
389 if (((address >> 16) & 0xFF) > MAX_BLOCKS) {
390 Dbprintf("Flash_WriteDataCont, block out-of-range");
391 return 0;
394 FlashSendByte(PAGEPROG);
395 FlashSendByte((address >> 16) & 0xFF);
396 FlashSendByte((address >> 8) & 0xFF);
397 FlashSendByte((address >> 0) & 0xFF);
399 uint16_t i = 0;
400 for (; i < (len - 1); i++)
401 FlashSendByte(in[i]);
403 FlashSendLastByte(in[i]);
404 return len;
407 // assumes valid start 256 based 00 address
409 uint16_t Flash_Write(uint32_t address, uint8_t *in, uint16_t len) {
411 bool isok;
412 uint16_t res, bytes_sent = 0, bytes_remaining = len;
413 uint8_t buf[FLASH_MEM_BLOCK_SIZE];
414 while (bytes_remaining > 0) {
416 Flash_CheckBusy(BUSY_TIMEOUT);
417 Flash_WriteEnable();
419 uint32_t bytes_in_packet = MIN(FLASH_MEM_BLOCK_SIZE, bytes_remaining);
421 memcpy(buf, in + bytes_sent, bytes_in_packet);
423 res = Flash_WriteDataCont(address + bytes_sent, buf, bytes_in_packet);
425 bytes_remaining -= bytes_in_packet;
426 bytes_sent += bytes_in_packet;
428 isok = (res == bytes_in_packet);
430 if (!isok)
431 goto out;
434 out:
435 FlashStop();
436 return len;
440 bool Flash_WipeMemoryPage(uint8_t page) {
441 if (!FlashInit()) {
442 if (g_dbglevel > 3) Dbprintf("Flash_WriteData init fail");
443 return false;
445 Flash_ReadStat1();
447 // Each block is 64Kb. One block erase takes 1s ( 1000ms )
448 Flash_WriteEnable();
449 Flash_Erase64k(page);
450 Flash_CheckBusy(BUSY_TIMEOUT);
452 FlashStop();
454 // let spiffs check and update its info post flash erase
455 rdv40_spiffs_check();
456 return true;
458 // Wipes flash memory completely, fills with 0xFF
459 bool Flash_WipeMemory(void) {
460 if (!FlashInit()) {
461 if (g_dbglevel > 3) Dbprintf("Flash_WriteData init fail");
462 return false;
464 Flash_ReadStat1();
466 // Each block is 64Kb. Four blocks
467 // one block erase takes 1s ( 1000ms )
468 Flash_WriteEnable();
469 Flash_Erase64k(0);
470 Flash_CheckBusy(BUSY_TIMEOUT);
471 Flash_WriteEnable();
472 Flash_Erase64k(1);
473 Flash_CheckBusy(BUSY_TIMEOUT);
474 Flash_WriteEnable();
475 Flash_Erase64k(2);
476 Flash_CheckBusy(BUSY_TIMEOUT);
477 Flash_WriteEnable();
478 Flash_Erase64k(3);
479 Flash_CheckBusy(BUSY_TIMEOUT);
481 FlashStop();
482 return true;
485 // enable the flash write
486 void Flash_WriteEnable(void) {
487 FlashSendLastByte(WRITEENABLE);
488 if (g_dbglevel > 3) Dbprintf("Flash Write enabled");
491 // erase 4K at one time
492 // execution time: 0.8ms / 800us
493 bool Flash_Erase4k(uint8_t block, uint8_t sector) {
495 if (block > MAX_BLOCKS || sector > MAX_SECTORS) return false;
497 FlashSendByte(SECTORERASE);
498 FlashSendByte(block);
499 FlashSendByte(sector << 4);
500 FlashSendLastByte(00);
501 return true;
505 // erase 32K at one time
506 // execution time: 0,3s / 300ms
507 bool Flash_Erase32k(uint32_t address) {
508 if (address & (32*1024 - 1)) {
509 if ( g_dbglevel > 1 ) Dbprintf("Flash_Erase32k : Address is not align at 4096");
510 return false;
512 FlashSendByte(BLOCK32ERASE);
513 FlashSendByte((address >> 16) & 0xFF);
514 FlashSendByte((address >> 8) & 0xFF);
515 FlashSendLastByte((address >> 0) & 0xFF);
516 return true;
520 // erase 64k at one time
521 // since a block is 64kb, and there is four blocks.
522 // we only need block number, as MSB
523 // execution time: 1s / 1000ms
524 // 0x00 00 00 -- 0x 00 FF FF == block 0
525 // 0x01 00 00 -- 0x 01 FF FF == block 1
526 // 0x02 00 00 -- 0x 02 FF FF == block 2
527 // 0x03 00 00 -- 0x 03 FF FF == block 3
528 bool Flash_Erase64k(uint8_t block) {
530 if (block > MAX_BLOCKS) return false;
532 FlashSendByte(BLOCK64ERASE);
533 FlashSendByte(block);
534 FlashSendByte(0x00);
535 FlashSendLastByte(0x00);
536 return true;
540 // Erase chip
541 void Flash_EraseChip(void) {
542 FlashSendLastByte(CHIPERASE);
546 void Flashmem_print_status(void) {
547 DbpString(_CYAN_("Flash memory"));
548 Dbprintf(" Baudrate................ " _GREEN_("%d MHz"), FLASHMEM_SPIBAUDRATE / 1000000);
550 if (!FlashInit()) {
551 DbpString(" Init.................... " _RED_("FAILED"));
552 return;
554 DbpString(" Init.................... " _GREEN_("OK"));
556 uint8_t dev_id = Flash_ReadID();
557 switch (dev_id) {
558 case 0x11 :
559 DbpString(" Memory size............. " _YELLOW_("2 mbits / 256 kb"));
560 break;
561 case 0x10 :
562 DbpString(" Memory size..... ....... " _YELLOW_("1 mbits / 128 kb"));
563 break;
564 case 0x05 :
565 DbpString(" Memory size............. " _YELLOW_("512 kbits / 64 kb"));
566 break;
567 default :
568 DbpString(" Device ID............... " _YELLOW_(" --> Unknown <--"));
569 break;
572 uint8_t uid[8] = {0, 0, 0, 0, 0, 0, 0, 0};
573 Flash_UniqueID(uid);
574 Dbprintf(" Unique ID............... 0x%02X%02X%02X%02X%02X%02X%02X%02X",
575 uid[7], uid[6], uid[5], uid[4],
576 uid[3], uid[2], uid[1], uid[0]
579 FlashStop();
582 void Flashmem_print_info(void) {
584 if (!FlashInit()) return;
586 DbpString(_CYAN_("Flash memory dictionary loaded"));
588 // load dictionary offsets.
589 uint8_t keysum[2];
590 uint16_t num;
592 Flash_CheckBusy(BUSY_TIMEOUT);
593 uint16_t isok = Flash_ReadDataCont(DEFAULT_MF_KEYS_OFFSET, keysum, 2);
594 if (isok == 2) {
595 num = ((keysum[1] << 8) | keysum[0]);
596 if (num != 0xFFFF && num != 0x0)
597 Dbprintf(" Mifare.................. "_YELLOW_("%d")" keys", num);
600 Flash_CheckBusy(BUSY_TIMEOUT);
601 isok = Flash_ReadDataCont(DEFAULT_T55XX_KEYS_OFFSET, keysum, 2);
602 if (isok == 2) {
603 num = ((keysum[1] << 8) | keysum[0]);
604 if (num != 0xFFFF && num != 0x0)
605 Dbprintf(" T55x7................... "_YELLOW_("%d")" keys", num);
608 Flash_CheckBusy(BUSY_TIMEOUT);
609 isok = Flash_ReadDataCont(DEFAULT_ICLASS_KEYS_OFFSET, keysum, 2);
610 if (isok == 2) {
611 num = ((keysum[1] << 8) | keysum[0]);
612 if (num != 0xFFFF && num != 0x0)
613 Dbprintf(" iClass.................. "_YELLOW_("%d")" keys", num);
616 FlashStop();