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.
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 //-----------------------------------------------------------------------------
21 #include "proxmark3_arm.h"
27 /* here: use NCPS2 @ PA10: */
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);
46 bool FlashInit(void) {
47 FlashSetup(FLASHMEM_SPIBAUDRATE
);
51 if (Flash_CheckBusy(BUSY_TIMEOUT
)) {
59 void FlashSetup(uint32_t baudrate
) {
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
);
73 AT91C_BASE_PIOA
->PIO_PPUER
|= (GPIO_NCS0
| GPIO_MISO
| GPIO_MOSI
| GPIO_SPCK
| GPIO_NCS2
);
76 AT91C_BASE_PIOA
->PIO_ASR
|= (GPIO_NCS0
| GPIO_MISO
| GPIO_MOSI
| GPIO_SPCK
);
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
;
90 AT91C_BASE_SPI
->SPI_CR
= AT91C_SPI_SPIEN
;
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
109 if (baudrate
> FLASH_MINFAST
) {
110 baudrate
= FLASH_FASTBAUD
;
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
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
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) {
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;
174 AT91C_BASE_SPI
->SPI_CR
= AT91C_SPI_SPIDIS
;
176 if (g_dbglevel
> 3) Dbprintf("FlashStop");
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) {};
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
);
214 uint32_t _time
= GetCountUS();
216 if (g_dbglevel
> 3) Dbprintf("Checkbusy in...");
219 if (!(Flash_ReadStat1() & BUSY
)) {
222 } while ((GetCountUS() - _time
) < timeout
);
224 if (timeout
<= (GetCountUS() - _time
)) {
232 uint8_t Flash_ReadID(void) {
234 if (Flash_CheckBusy(BUSY_TIMEOUT
)) return 0;
236 // Manufacture ID / device ID
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
))
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
);
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
;
285 Flash_TransferAdresse(address
);
288 FlashSendByte(DUMMYBYTE
);
292 for (; i
< (len
- 1); i
++)
293 out
[i
] = FlashSendByte(0xFF);
295 out
[i
] = FlashSendLastByte(0xFF);
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
312 uint8_t cmd
= (FASTFLASH
) ? FASTREAD
: READDATA
;
315 Flash_TransferAdresse(address
);
318 FlashSendByte(DUMMYBYTE
);
322 for (; i
< (len
- 1); i
++)
323 out
[i
] = FlashSendByte(0xFF);
325 out
[i
] = FlashSendLastByte(0xFF);
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
339 // Max 256 bytes write
340 if (((address
& 0xFF) + len
) > 256) {
341 Dbprintf("Flash_WriteData 256 fail [ 0x%02x ] [ %u ]", (address
& 0xFF) + len
, len
);
346 if (((address
>> 16) & 0xFF) > MAX_BLOCKS
) {
347 Dbprintf("Flash_WriteData, block out-of-range");
352 if (g_dbglevel
> 3) Dbprintf("Flash_WriteData init fail");
356 Flash_CheckBusy(BUSY_TIMEOUT
);
360 FlashSendByte(PAGEPROG
);
361 FlashSendByte((address
>> 16) & 0xFF);
362 FlashSendByte((address
>> 8) & 0xFF);
363 FlashSendByte((address
>> 0) & 0xFF);
366 for (; i
< (len
- 1); i
++)
367 FlashSendByte(in
[i
]);
369 FlashSendLastByte(in
[i
]);
376 // length should never be zero
377 // Max 256 bytes write
379 uint16_t Flash_WriteDataCont(uint32_t address
, uint8_t *in
, uint16_t len
) {
384 if (((address
& 0xFF) + len
) > 256) {
385 Dbprintf("Flash_WriteDataCont 256 fail [ 0x%02x ] [ %u ]", (address
& 0xFF) + len
, len
);
389 if (((address
>> 16) & 0xFF) > MAX_BLOCKS
) {
390 Dbprintf("Flash_WriteDataCont, block out-of-range");
394 FlashSendByte(PAGEPROG
);
395 FlashSendByte((address
>> 16) & 0xFF);
396 FlashSendByte((address
>> 8) & 0xFF);
397 FlashSendByte((address
>> 0) & 0xFF);
400 for (; i
< (len
- 1); i
++)
401 FlashSendByte(in
[i
]);
403 FlashSendLastByte(in
[i
]);
407 // assumes valid start 256 based 00 address
409 uint16_t Flash_Write(uint32_t address
, uint8_t *in
, uint16_t len
) {
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
);
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
);
440 bool Flash_WipeMemoryPage(uint8_t page
) {
442 if (g_dbglevel
> 3) Dbprintf("Flash_WriteData init fail");
447 // Each block is 64Kb. One block erase takes 1s ( 1000ms )
449 Flash_Erase64k(page
);
450 Flash_CheckBusy(BUSY_TIMEOUT
);
454 // let spiffs check and update its info post flash erase
455 rdv40_spiffs_check();
458 // Wipes flash memory completely, fills with 0xFF
459 bool Flash_WipeMemory(void) {
461 if (g_dbglevel
> 3) Dbprintf("Flash_WriteData init fail");
466 // Each block is 64Kb. Four blocks
467 // one block erase takes 1s ( 1000ms )
470 Flash_CheckBusy(BUSY_TIMEOUT
);
473 Flash_CheckBusy(BUSY_TIMEOUT
);
476 Flash_CheckBusy(BUSY_TIMEOUT
);
479 Flash_CheckBusy(BUSY_TIMEOUT
);
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);
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");
512 FlashSendByte(BLOCK32ERASE);
513 FlashSendByte((address >> 16) & 0xFF);
514 FlashSendByte((address >> 8) & 0xFF);
515 FlashSendLastByte((address >> 0) & 0xFF);
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
);
535 FlashSendLastByte(0x00);
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);
551 DbpString(" Init.................... " _RED_("FAILED"));
554 DbpString(" Init.................... " _GREEN_("OK"));
556 uint8_t dev_id
= Flash_ReadID();
559 DbpString(" Memory size............. " _YELLOW_("2 mbits / 256 kb"));
562 DbpString(" Memory size..... ....... " _YELLOW_("1 mbits / 128 kb"));
565 DbpString(" Memory size............. " _YELLOW_("512 kbits / 64 kb"));
568 DbpString(" Device ID............... " _YELLOW_(" --> Unknown <--"));
572 uint8_t uid
[8] = {0, 0, 0, 0, 0, 0, 0, 0};
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]
582 void Flashmem_print_info(void) {
584 if (!FlashInit()) return;
586 DbpString(_CYAN_("Flash memory dictionary loaded"));
588 // load dictionary offsets.
592 Flash_CheckBusy(BUSY_TIMEOUT
);
593 uint16_t isok
= Flash_ReadDataCont(DEFAULT_MF_KEYS_OFFSET
, keysum
, 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);
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);
611 num
= ((keysum
[1] << 8) | keysum
[0]);
612 if (num
!= 0xFFFF && num
!= 0x0)
613 Dbprintf(" iClass.................. "_YELLOW_("%d")" keys", num
);