1 //-----------------------------------------------------------------------------
2 // Jonathan Westhues, April 2006
3 // iZsh <izsh at fail0verflow.com>, 2014
5 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
6 // at your option, any later version. See the LICENSE.txt file for the text of
8 //-----------------------------------------------------------------------------
9 // Routines to load the FPGA image, and then to configure the FPGA's major
10 // mode once it is configured.
11 //-----------------------------------------------------------------------------
12 #include "fpgaloader.h"
14 #include "proxmark3_arm.h"
23 #include "lz4.h" // uncompress
25 typedef struct lz4_stream_s
{
26 LZ4_streamDecode_t
*lz4StreamDecode
;
31 typedef lz4_stream
*lz4_streamp
;
33 // remember which version of the bitstream we have already downloaded to the FPGA
34 static int downloaded_bitstream
= 0;
36 // this is where the bitstreams are located in memory:
37 extern uint32_t _binary_obj_fpga_all_bit_z_start
[], _binary_obj_fpga_all_bit_z_end
[];
39 static uint8_t *fpga_image_ptr
= NULL
;
40 static uint32_t uncompressed_bytes_cnt
;
42 //-----------------------------------------------------------------------------
43 // Set up the Serial Peripheral Interface as master
44 // Used to write the FPGA config word
45 // May also be used to write to other SPI attached devices like an LCD
46 //-----------------------------------------------------------------------------
47 static void DisableSpi(void) {
48 //* Reset all the Chip Select register
49 AT91C_BASE_SPI
->SPI_CSR
[0] = 0;
50 AT91C_BASE_SPI
->SPI_CSR
[1] = 0;
51 AT91C_BASE_SPI
->SPI_CSR
[2] = 0;
52 AT91C_BASE_SPI
->SPI_CSR
[3] = 0;
55 AT91C_BASE_SPI
->SPI_MR
= 0;
57 // Disable all interrupts
58 AT91C_BASE_SPI
->SPI_IDR
= 0xFFFFFFFF;
61 AT91C_BASE_SPI
->SPI_CR
= AT91C_SPI_SPIDIS
;
64 void SetupSpi(int mode
) {
65 // PA1 -> SPI_NCS3 chip select (MEM)
66 // PA10 -> SPI_NCS2 chip select (LCD)
67 // PA11 -> SPI_NCS0 chip select (FPGA)
68 // PA12 -> SPI_MISO Master-In Slave-Out
69 // PA13 -> SPI_MOSI Master-Out Slave-In
70 // PA14 -> SPI_SPCK Serial Clock
72 // Disable PIO control of the following pins, allows use by the SPI peripheral
73 AT91C_BASE_PIOA
->PIO_PDR
= GPIO_NCS0
| GPIO_MISO
| GPIO_MOSI
| GPIO_SPCK
;
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
);
84 AT91C_BASE_SPI
->SPI_CR
= AT91C_SPI_SPIEN
;
88 AT91C_BASE_SPI
->SPI_MR
=
89 (0 << 24) | // Delay between chip selects (take default: 6 MCK periods)
90 (0xE << 16) | // Peripheral Chip Select (selects FPGA SPI_NCS0 or PA11)
91 (0 << 7) | // Local Loopback Disabled
92 AT91C_SPI_MODFDIS
| // Mode Fault Detection disabled
93 (0 << 2) | // Chip selects connected directly to peripheral
94 AT91C_SPI_PS_FIXED
| // Fixed Peripheral Select
95 AT91C_SPI_MSTR
; // Master Mode
97 AT91C_BASE_SPI
->SPI_CSR
[0] =
98 (1 << 24) | // Delay between Consecutive Transfers (32 MCK periods)
99 (1 << 16) | // Delay Before SPCK (1 MCK period)
100 (6 << 8) | // Serial Clock Baud Rate (baudrate = MCK/6 = 24MHz/6 = 4M baud
101 AT91C_SPI_BITS_16
| // Bits per Transfer (16 bits)
102 (0 << 3) | // Chip Select inactive after transfer
103 AT91C_SPI_NCPHA
| // Clock Phase data captured on leading edge, changes on following edge
104 (0 << 0); // Clock Polarity inactive state is logic 0
108 AT91C_BASE_SPI->SPI_MR =
109 ( 0 << 24) | // Delay between chip selects (take default: 6 MCK periods)
110 (0xB << 16) | // Peripheral Chip Select (selects LCD SPI_NCS2 or PA10)
111 ( 0 << 7) | // Local Loopback Disabled
112 ( 1 << 4) | // Mode Fault Detection disabled
113 ( 0 << 2) | // Chip selects connected directly to peripheral
114 ( 0 << 1) | // Fixed Peripheral Select
115 ( 1 << 0); // Master Mode
117 AT91C_BASE_SPI->SPI_CSR[2] =
118 ( 1 << 24) | // Delay between Consecutive Transfers (32 MCK periods)
119 ( 1 << 16) | // Delay Before SPCK (1 MCK period)
120 ( 6 << 8) | // Serial Clock Baud Rate (baudrate = MCK/6 = 24MHz/6 = 4M baud
121 AT91C_SPI_BITS_9 | // Bits per Transfer (9 bits)
122 ( 0 << 3) | // Chip Select inactive after transfer
123 ( 1 << 1) | // Clock Phase data captured on leading edge, changes on following edge
124 ( 0 << 0); // Clock Polarity inactive state is logic 0
133 //-----------------------------------------------------------------------------
134 // Set up the synchronous serial port with the set of options that fits
135 // the FPGA mode. Both RX and TX are always enabled.
136 //-----------------------------------------------------------------------------
137 void FpgaSetupSsc(uint16_t fpga_mode
) {
138 // First configure the GPIOs, and get ourselves a clock.
139 AT91C_BASE_PIOA
->PIO_ASR
=
144 AT91C_BASE_PIOA
->PIO_PDR
= GPIO_SSC_DOUT
;
146 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_SSC
);
148 // Now set up the SSC proper, starting from a known state.
149 AT91C_BASE_SSC
->SSC_CR
= AT91C_SSC_SWRST
;
151 // RX clock comes from TX clock, RX starts on Transmit Start,
152 // data and frame signal is sampled on falling edge of RK
153 AT91C_BASE_SSC
->SSC_RCMR
= SSC_CLOCK_MODE_SELECT(1) | SSC_CLOCK_MODE_START(1);
155 // 8, 16 or 32 bits per transfer, no loopback, MSB first, 1 transfer per sync
156 // pulse, no output sync
157 if ((fpga_mode
& FPGA_MAJOR_MODE_MASK
) == FPGA_MAJOR_MODE_HF_READER
&& FpgaGetCurrent() == FPGA_BITSTREAM_HF
) {
158 AT91C_BASE_SSC
->SSC_RFMR
= SSC_FRAME_MODE_BITS_IN_WORD(16) | AT91C_SSC_MSBF
| SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
160 AT91C_BASE_SSC
->SSC_RFMR
= SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF
| SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
163 // TX clock comes from TK pin, no clock output, outputs change on rising edge of TK,
164 // TF (frame sync) is sampled on falling edge of TK, start TX on rising edge of TF
165 AT91C_BASE_SSC
->SSC_TCMR
= SSC_CLOCK_MODE_SELECT(2) | SSC_CLOCK_MODE_START(5);
167 // tx framing is the same as the rx framing
168 AT91C_BASE_SSC
->SSC_TFMR
= AT91C_BASE_SSC
->SSC_RFMR
;
170 AT91C_BASE_SSC
->SSC_CR
= AT91C_SSC_RXEN
| AT91C_SSC_TXEN
;
173 //-----------------------------------------------------------------------------
174 // Set up DMA to receive samples from the FPGA. We will use the PDC, with
175 // a single buffer as a circular buffer (so that we just chain back to
176 // ourselves, not to another buffer).
177 //-----------------------------------------------------------------------------
178 bool FpgaSetupSscDma(uint8_t *buf
, uint16_t len
) {
179 if (buf
== NULL
) return false;
182 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) buf
; // transfer to this memory address
183 AT91C_BASE_PDC_SSC
->PDC_RCR
= len
; // transfer this many bytes
184 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) buf
; // next transfer to same memory address
185 AT91C_BASE_PDC_SSC
->PDC_RNCR
= len
; // ... with same number of bytes
190 //----------------------------------------------------------------------------
191 // Uncompress (inflate) the FPGA data. Returns one decompressed byte with each call.
192 //----------------------------------------------------------------------------
193 static int get_from_fpga_combined_stream(lz4_streamp compressed_fpga_stream
, uint8_t *output_buffer
) {
194 if (fpga_image_ptr
== output_buffer
+ FPGA_RING_BUFFER_BYTES
) { // need more data
195 fpga_image_ptr
= output_buffer
;
197 memcpy(&cmp_bytes
, compressed_fpga_stream
->next_in
, sizeof(int));
198 compressed_fpga_stream
->next_in
+= 4;
199 compressed_fpga_stream
->avail_in
-= cmp_bytes
+ 4;
200 int res
= LZ4_decompress_safe_continue(compressed_fpga_stream
->lz4StreamDecode
,
201 compressed_fpga_stream
->next_in
,
202 (char *)output_buffer
,
204 FPGA_RING_BUFFER_BYTES
);
206 Dbprintf("inflate returned: %d", res
);
209 compressed_fpga_stream
->next_in
+= cmp_bytes
;
211 uncompressed_bytes_cnt
++;
212 return *fpga_image_ptr
++;
215 //----------------------------------------------------------------------------
216 // Undo the interleaving of several FPGA config files. FPGA config files
217 // are combined into one big file:
218 // 288 bytes from FPGA file 1, followed by 288 bytes from FGPA file 2, etc.
219 //----------------------------------------------------------------------------
220 static int get_from_fpga_stream(int bitstream_version
, lz4_streamp compressed_fpga_stream
, uint8_t *output_buffer
) {
221 while ((uncompressed_bytes_cnt
/ FPGA_INTERLEAVE_SIZE
) % g_fpga_bitstream_num
!= (bitstream_version
- 1)) {
222 // skip undesired data belonging to other bitstream_versions
223 get_from_fpga_combined_stream(compressed_fpga_stream
, output_buffer
);
226 return get_from_fpga_combined_stream(compressed_fpga_stream
, output_buffer
);
229 //----------------------------------------------------------------------------
230 // Initialize decompression of the respective (HF or LF) FPGA stream
231 //----------------------------------------------------------------------------
232 static bool reset_fpga_stream(int bitstream_version
, lz4_streamp compressed_fpga_stream
, uint8_t *output_buffer
) {
233 uint8_t header
[FPGA_BITSTREAM_FIXED_HEADER_SIZE
];
235 uncompressed_bytes_cnt
= 0;
237 // initialize z_stream structure for inflate:
238 compressed_fpga_stream
->next_in
= (char *)_binary_obj_fpga_all_bit_z_start
;
239 compressed_fpga_stream
->avail_in
= (uint32_t)_binary_obj_fpga_all_bit_z_end
- (uint32_t)_binary_obj_fpga_all_bit_z_start
;
241 int res
= LZ4_setStreamDecode(compressed_fpga_stream
->lz4StreamDecode
, NULL
, 0);
245 fpga_image_ptr
= output_buffer
+ FPGA_RING_BUFFER_BYTES
;
247 for (uint16_t i
= 0; i
< FPGA_BITSTREAM_FIXED_HEADER_SIZE
; i
++)
248 header
[i
] = get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
250 // Check for a valid .bit file (starts with bitparse_fixed_header)
251 if (memcmp(bitparse_fixed_header
, header
, FPGA_BITSTREAM_FIXED_HEADER_SIZE
) == 0)
257 static void DownloadFPGA_byte(uint8_t w
) {
258 #define SEND_BIT(x) { if(w & (1<<x) ) HIGH(GPIO_FPGA_DIN); else LOW(GPIO_FPGA_DIN); HIGH(GPIO_FPGA_CCLK); LOW(GPIO_FPGA_CCLK); }
269 // Download the fpga image starting at current stream position with length FpgaImageLen bytes
270 static void DownloadFPGA(int bitstream_version
, int FpgaImageLen
, lz4_streamp compressed_fpga_stream
, uint8_t *output_buffer
) {
273 AT91C_BASE_PIOA
->PIO_OER
= GPIO_FPGA_ON
;
274 AT91C_BASE_PIOA
->PIO_PER
= GPIO_FPGA_ON
;
275 HIGH(GPIO_FPGA_ON
); // ensure everything is powered on
281 // These pins are inputs
282 AT91C_BASE_PIOA
->PIO_ODR
=
285 // PIO controls the following pins
286 AT91C_BASE_PIOA
->PIO_PER
=
290 AT91C_BASE_PIOA
->PIO_PPUER
=
294 // setup initial logic state
295 HIGH(GPIO_FPGA_NPROGRAM
);
298 // These pins are outputs
299 AT91C_BASE_PIOA
->PIO_OER
=
304 // enter FPGA configuration mode
305 LOW(GPIO_FPGA_NPROGRAM
);
307 HIGH(GPIO_FPGA_NPROGRAM
);
310 // wait for FPGA ready to accept data signal
311 while ((i
) && (!(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_FPGA_NINIT
))) {
315 // crude error indicator, leave both red LEDs on and return
322 for (i
= 0; i
< FpgaImageLen
; i
++) {
323 int b
= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
325 Dbprintf("Error %d during FpgaDownload", b
);
328 DownloadFPGA_byte(b
);
331 // continue to clock FPGA until ready signal goes high
333 while ((i
--) && (!(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_FPGA_DONE
))) {
334 HIGH(GPIO_FPGA_CCLK
);
337 // crude error indicator, leave both red LEDs on and return
346 /* Simple Xilinx .bit parser. The file starts with the fixed opaque byte sequence
347 * 00 09 0f f0 0f f0 0f f0 0f f0 00 00 01
348 * After that the format is 1 byte section type (ASCII character), 2 byte length
349 * (big endian), <length> bytes content. Except for section 'e' which has 4 bytes
352 static int bitparse_find_section(int bitstream_version
, char section_name
, uint32_t *section_length
, lz4_streamp compressed_fpga_stream
, uint8_t *output_buffer
) {
354 #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section
357 uint16_t numbytes
= 0;
358 while (numbytes
< MAX_FPGA_BIT_STREAM_HEADER_SEARCH
) {
359 char current_name
= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
361 uint32_t current_length
= 0;
362 if (current_name
< 'a' || current_name
> 'e') {
363 /* Strange section name, abort */
367 switch (current_name
) {
369 /* Four byte length field */
370 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 24;
371 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 16;
373 default: /* Fall through, two byte length field */
374 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 8;
375 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 0;
379 if (current_name
!= 'e' && current_length
> 255) {
380 /* Maybe a parse error */
384 if (current_name
== section_name
) {
386 *section_length
= current_length
;
391 for (uint16_t i
= 0; i
< current_length
&& numbytes
< MAX_FPGA_BIT_STREAM_HEADER_SEARCH
; i
++) {
392 get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
399 //----------------------------------------------------------------------------
400 // Check which FPGA image is currently loaded (if any). If necessary
401 // decompress and load the correct (HF or LF) image to the FPGA
402 //----------------------------------------------------------------------------
403 void FpgaDownloadAndGo(int bitstream_version
) {
405 // check whether or not the bitstream is already loaded
406 if (downloaded_bitstream
== bitstream_version
) {
411 // Send waiting time extension request as this will take a while
414 bool verbose
= (DBGLEVEL
> 3);
416 // make sure that we have enough memory to decompress
418 BigBuf_Clear_ext(verbose
);
420 lz4_stream compressed_fpga_stream
;
421 LZ4_streamDecode_t lz4StreamDecode_body
= {{ 0 }};
422 compressed_fpga_stream
.lz4StreamDecode
= &lz4StreamDecode_body
;
423 uint8_t *output_buffer
= BigBuf_malloc(FPGA_RING_BUFFER_BYTES
);
425 if (!reset_fpga_stream(bitstream_version
, &compressed_fpga_stream
, output_buffer
))
428 uint32_t bitstream_length
;
429 if (bitparse_find_section(bitstream_version
, 'e', &bitstream_length
, &compressed_fpga_stream
, output_buffer
)) {
430 DownloadFPGA(bitstream_version
, bitstream_length
, &compressed_fpga_stream
, output_buffer
);
431 downloaded_bitstream
= bitstream_version
;
435 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
437 // free eventually allocated BigBuf memory
439 BigBuf_Clear_ext(false);
442 //-----------------------------------------------------------------------------
443 // Send a 16 bit command/data pair to the FPGA.
444 // The bit format is: C3 C2 C1 C0 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
445 // where C is the 4 bit command and D is the 12 bit data
447 // @params cmd and v gets OR:ED over each other. Take careful note of overlapping bits.
448 //-----------------------------------------------------------------------------
449 void FpgaSendCommand(uint16_t cmd
, uint16_t v
) {
450 SetupSpi(SPI_FPGA_MODE
);
451 while ((AT91C_BASE_SPI
->SPI_SR
& AT91C_SPI_TXEMPTY
) == 0); // wait for the transfer to complete
452 AT91C_BASE_SPI
->SPI_TDR
= AT91C_SPI_LASTXFER
| cmd
| v
; // send the data
453 while (!(AT91C_BASE_SPI
->SPI_SR
& AT91C_SPI_RDRF
)) {}; // wait till transfer is complete
455 //-----------------------------------------------------------------------------
456 // Write the FPGA setup word (that determines what mode the logic is in, read
457 // vs. clone vs. etc.). This is now a special case of FpgaSendCommand() to
458 // avoid changing this function's occurence everywhere in the source code.
459 //-----------------------------------------------------------------------------
460 void FpgaWriteConfWord(uint16_t v
) {
461 FpgaSendCommand(FPGA_CMD_SET_CONFREG
, v
);
464 //-----------------------------------------------------------------------------
465 // enable/disable FPGA internal tracing
466 //-----------------------------------------------------------------------------
467 void FpgaEnableTracing(void) {
468 FpgaSendCommand(FPGA_CMD_TRACE_ENABLE
, 1);
471 void FpgaDisableTracing(void) {
472 FpgaSendCommand(FPGA_CMD_TRACE_ENABLE
, 0);
475 //-----------------------------------------------------------------------------
476 // Set up the CMOS switches that mux the ADC: four switches, independently
477 // closable, but should only close one at a time. Not an FPGA thing, but
478 // the samples from the ADC always flow through the FPGA.
479 //-----------------------------------------------------------------------------
480 void SetAdcMuxFor(uint32_t whichGpio
) {
482 #ifndef WITH_FPC_USART
483 // When compiled without FPC USART support
484 AT91C_BASE_PIOA
->PIO_OER
=
490 AT91C_BASE_PIOA
->PIO_PER
=
496 LOW(GPIO_MUXSEL_HIPKD
);
497 LOW(GPIO_MUXSEL_LOPKD
);
498 LOW(GPIO_MUXSEL_HIRAW
);
499 LOW(GPIO_MUXSEL_LORAW
);
502 if ((whichGpio
== GPIO_MUXSEL_LORAW
) || (whichGpio
== GPIO_MUXSEL_HIRAW
))
504 // FPC USART uses HIRAW/LOWRAW pins, so they are excluded here.
505 AT91C_BASE_PIOA
->PIO_OER
= GPIO_MUXSEL_HIPKD
| GPIO_MUXSEL_LOPKD
;
506 AT91C_BASE_PIOA
->PIO_PER
= GPIO_MUXSEL_HIPKD
| GPIO_MUXSEL_LOPKD
;
507 LOW(GPIO_MUXSEL_HIPKD
);
508 LOW(GPIO_MUXSEL_LOPKD
);
514 void Fpga_print_status(void) {
515 DbpString(_CYAN_("Current FPGA image"));
516 Dbprintf(" mode....................%s", g_fpga_version_information
[downloaded_bitstream
- 1]);
519 int FpgaGetCurrent(void) {
520 return downloaded_bitstream
;
523 // Turns off the antenna,
525 // if HF, Disable SSC DMA
526 // turn off trace and leds off.
527 void switch_off(void) {
529 Dbprintf("switch_off");
531 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
532 if (downloaded_bitstream
== FPGA_BITSTREAM_HF
) {