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 //-----------------------------------------------------------------------------
16 #include "fpgaloader.h"
17 #include "proxmark3.h"
23 extern void Dbprintf(const char *fmt
, ...);
25 // remember which version of the bitstream we have already downloaded to the FPGA
26 static int downloaded_bitstream
= FPGA_BITSTREAM_ERR
;
28 // this is where the bitstreams are located in memory:
29 extern uint8_t _binary_obj_fpga_all_bit_z_start
, _binary_obj_fpga_all_bit_z_end
;
31 static uint8_t *fpga_image_ptr
= NULL
;
32 static uint32_t uncompressed_bytes_cnt
;
34 static const uint8_t _bitparse_fixed_header
[] = {0x00, 0x09, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x00, 0x00, 0x01};
35 #define FPGA_BITSTREAM_FIXED_HEADER_SIZE sizeof(_bitparse_fixed_header)
36 #define OUTPUT_BUFFER_LEN 80
37 #define FPGA_INTERLEAVE_SIZE 288
39 //-----------------------------------------------------------------------------
40 // Set up the Serial Peripheral Interface as master
41 // Used to write the FPGA config word
42 // May also be used to write to other SPI attached devices like an LCD
43 //-----------------------------------------------------------------------------
44 void SetupSpi(int mode
)
46 // PA10 -> SPI_NCS2 chip select (LCD)
47 // PA11 -> SPI_NCS0 chip select (FPGA)
48 // PA12 -> SPI_MISO Master-In Slave-Out
49 // PA13 -> SPI_MOSI Master-Out Slave-In
50 // PA14 -> SPI_SPCK Serial Clock
52 // Disable PIO control of the following pins, allows use by the SPI peripheral
53 AT91C_BASE_PIOA
->PIO_PDR
=
60 AT91C_BASE_PIOA
->PIO_ASR
=
66 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_NCS2
;
68 //enable the SPI Peripheral clock
69 AT91C_BASE_PMC
->PMC_PCER
= (1<<AT91C_ID_SPI
);
71 AT91C_BASE_SPI
->SPI_CR
= AT91C_SPI_SPIEN
;
75 AT91C_BASE_SPI
->SPI_MR
=
76 ( 0 << 24) | // Delay between chip selects (take default: 6 MCK periods)
77 (14 << 16) | // Peripheral Chip Select (selects FPGA SPI_NCS0 or PA11)
78 ( 0 << 7) | // Local Loopback Disabled
79 ( 1 << 4) | // Mode Fault Detection disabled
80 ( 0 << 2) | // Chip selects connected directly to peripheral
81 ( 0 << 1) | // Fixed Peripheral Select
82 ( 1 << 0); // Master Mode
83 AT91C_BASE_SPI
->SPI_CSR
[0] =
84 ( 1 << 24) | // Delay between Consecutive Transfers (32 MCK periods)
85 ( 1 << 16) | // Delay Before SPCK (1 MCK period)
86 ( 6 << 8) | // Serial Clock Baud Rate (baudrate = MCK/6 = 24Mhz/6 = 4M baud
87 ( 8 << 4) | // Bits per Transfer (16 bits)
88 ( 0 << 3) | // Chip Select inactive after transfer
89 ( 1 << 1) | // Clock Phase data captured on leading edge, changes on following edge
90 ( 0 << 0); // Clock Polarity inactive state is logic 0
93 AT91C_BASE_SPI
->SPI_MR
=
94 ( 0 << 24) | // Delay between chip selects (take default: 6 MCK periods)
95 (11 << 16) | // Peripheral Chip Select (selects LCD SPI_NCS2 or PA10)
96 ( 0 << 7) | // Local Loopback Disabled
97 ( 1 << 4) | // Mode Fault Detection disabled
98 ( 0 << 2) | // Chip selects connected directly to peripheral
99 ( 0 << 1) | // Fixed Peripheral Select
100 ( 1 << 0); // Master Mode
101 AT91C_BASE_SPI
->SPI_CSR
[2] =
102 ( 1 << 24) | // Delay between Consecutive Transfers (32 MCK periods)
103 ( 1 << 16) | // Delay Before SPCK (1 MCK period)
104 ( 6 << 8) | // Serial Clock Baud Rate (baudrate = MCK/6 = 24Mhz/6 = 4M baud
105 ( 1 << 4) | // Bits per Transfer (9 bits)
106 ( 0 << 3) | // Chip Select inactive after transfer
107 ( 1 << 1) | // Clock Phase data captured on leading edge, changes on following edge
108 ( 0 << 0); // Clock Polarity inactive state is logic 0
110 default: // Disable SPI
111 AT91C_BASE_SPI
->SPI_CR
= AT91C_SPI_SPIDIS
;
116 //-----------------------------------------------------------------------------
117 // Set up the synchronous serial port, with the one set of options that we
118 // always use when we are talking to the FPGA. Both RX and TX are enabled.
119 //-----------------------------------------------------------------------------
120 void FpgaSetupSsc(void)
122 // First configure the GPIOs, and get ourselves a clock.
123 AT91C_BASE_PIOA
->PIO_ASR
=
128 AT91C_BASE_PIOA
->PIO_PDR
= GPIO_SSC_DOUT
;
130 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_SSC
);
132 // Now set up the SSC proper, starting from a known state.
133 AT91C_BASE_SSC
->SSC_CR
= AT91C_SSC_SWRST
;
135 // RX clock comes from TX clock, RX starts when TX starts, data changes
136 // on RX clock rising edge, sampled on falling edge
137 AT91C_BASE_SSC
->SSC_RCMR
= SSC_CLOCK_MODE_SELECT(1) | SSC_CLOCK_MODE_START(1);
139 // 8 bits per transfer, no loopback, MSB first, 1 transfer per sync
140 // pulse, no output sync
141 AT91C_BASE_SSC
->SSC_RFMR
= SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF
| SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
143 // clock comes from TK pin, no clock output, outputs change on falling
144 // edge of TK, sample on rising edge of TK, start on positive-going edge of sync
145 AT91C_BASE_SSC
->SSC_TCMR
= SSC_CLOCK_MODE_SELECT(2) | SSC_CLOCK_MODE_START(5);
147 // tx framing is the same as the rx framing
148 AT91C_BASE_SSC
->SSC_TFMR
= AT91C_BASE_SSC
->SSC_RFMR
;
150 AT91C_BASE_SSC
->SSC_CR
= AT91C_SSC_RXEN
| AT91C_SSC_TXEN
;
153 //-----------------------------------------------------------------------------
154 // Set up DMA to receive samples from the FPGA. We will use the PDC, with
155 // a single buffer as a circular buffer (so that we just chain back to
156 // ourselves, not to another buffer). The stuff to manipulate those buffers
157 // is in apps.h, because it should be inlined, for speed.
158 //-----------------------------------------------------------------------------
159 bool FpgaSetupSscDma(uint8_t *buf
, int len
)
161 if (buf
== NULL
) return false;
163 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
; // Disable DMA Transfer
164 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) buf
; // transfer to this memory address
165 AT91C_BASE_PDC_SSC
->PDC_RCR
= len
; // transfer this many bytes
166 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) buf
; // next transfer to same memory address
167 AT91C_BASE_PDC_SSC
->PDC_RNCR
= len
; // ... with same number of bytes
168 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTEN
; // go!
174 //----------------------------------------------------------------------------
175 // Uncompress (inflate) the FPGA data. Returns one decompressed byte with
177 //----------------------------------------------------------------------------
178 static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
180 if (fpga_image_ptr
== compressed_fpga_stream
->next_out
) { // need more data
181 compressed_fpga_stream
->next_out
= output_buffer
;
182 compressed_fpga_stream
->avail_out
= OUTPUT_BUFFER_LEN
;
183 fpga_image_ptr
= output_buffer
;
184 int res
= inflate(compressed_fpga_stream
, Z_SYNC_FLUSH
);
186 Dbprintf("inflate returned: %d, %s", res
, compressed_fpga_stream
->msg
);
192 uncompressed_bytes_cnt
++;
194 return *fpga_image_ptr
++;
197 //----------------------------------------------------------------------------
198 // Undo the interleaving of several FPGA config files. FPGA config files
199 // are combined into one big file:
200 // 288 bytes from FPGA file 1, followed by 288 bytes from FGPA file 2, etc.
201 //----------------------------------------------------------------------------
202 static int get_from_fpga_stream(int bitstream_version
, z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
204 while((uncompressed_bytes_cnt
/ FPGA_INTERLEAVE_SIZE
) % FPGA_BITSTREAM_MAX
!= (bitstream_version
- 1)) {
205 // skip undesired data belonging to other bitstream_versions
206 get_from_fpga_combined_stream(compressed_fpga_stream
, output_buffer
);
209 return get_from_fpga_combined_stream(compressed_fpga_stream
, output_buffer
);
214 static voidpf
fpga_inflate_malloc(voidpf opaque
, uInt items
, uInt size
)
216 return BigBuf_malloc(items
*size
);
220 static void fpga_inflate_free(voidpf opaque
, voidpf address
)
222 BigBuf_free(); BigBuf_Clear_ext(false);
226 //----------------------------------------------------------------------------
227 // Initialize decompression of the respective (HF or LF) FPGA stream
228 //----------------------------------------------------------------------------
229 static bool reset_fpga_stream(int bitstream_version
, z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
231 uint8_t header
[FPGA_BITSTREAM_FIXED_HEADER_SIZE
];
233 uncompressed_bytes_cnt
= 0;
235 // initialize z_stream structure for inflate:
236 compressed_fpga_stream
->next_in
= &_binary_obj_fpga_all_bit_z_start
;
237 compressed_fpga_stream
->avail_in
= &_binary_obj_fpga_all_bit_z_start
- &_binary_obj_fpga_all_bit_z_end
;
238 compressed_fpga_stream
->next_out
= output_buffer
;
239 compressed_fpga_stream
->avail_out
= OUTPUT_BUFFER_LEN
;
240 compressed_fpga_stream
->zalloc
= &fpga_inflate_malloc
;
241 compressed_fpga_stream
->zfree
= &fpga_inflate_free
;
243 inflateInit2(compressed_fpga_stream
, 0);
245 fpga_image_ptr
= output_buffer
;
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
);
251 // Check for a valid .bit file (starts with _bitparse_fixed_header)
252 if(memcmp(_bitparse_fixed_header
, header
, FPGA_BITSTREAM_FIXED_HEADER_SIZE
) == 0) {
260 static void DownloadFPGA_byte(unsigned char w
)
262 #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); }
273 // Download the fpga image starting at current stream position with length FpgaImageLen bytes
274 static void DownloadFPGA(int bitstream_version
, int FpgaImageLen
, z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
277 //Dbprintf("DownloadFPGA(len: %d)", FpgaImageLen);
281 AT91C_BASE_PIOA
->PIO_OER
= GPIO_FPGA_ON
;
282 AT91C_BASE_PIOA
->PIO_PER
= GPIO_FPGA_ON
;
283 HIGH(GPIO_FPGA_ON
); // ensure everything is powered on
289 // These pins are inputs
290 AT91C_BASE_PIOA
->PIO_ODR
=
293 // PIO controls the following pins
294 AT91C_BASE_PIOA
->PIO_PER
=
298 AT91C_BASE_PIOA
->PIO_PPUER
=
302 // setup initial logic state
303 HIGH(GPIO_FPGA_NPROGRAM
);
306 // These pins are outputs
307 AT91C_BASE_PIOA
->PIO_OER
=
312 // enter FPGA configuration mode
313 LOW(GPIO_FPGA_NPROGRAM
);
315 HIGH(GPIO_FPGA_NPROGRAM
);
318 // wait for FPGA ready to accept data signal
319 while ((i
) && ( !(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_FPGA_NINIT
) ) ) {
323 // crude error indicator, leave both red LEDs on and return
330 for(i
= 0; i
< FpgaImageLen
; i
++) {
331 int b
= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
333 Dbprintf("Error %d during FpgaDownload", b
);
336 DownloadFPGA_byte(b
);
339 // continue to clock FPGA until ready signal goes high
341 while ( (i
--) && ( !(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_FPGA_DONE
) ) ) {
342 HIGH(GPIO_FPGA_CCLK
);
345 // crude error indicator, leave both red LEDs on and return
355 /* Simple Xilinx .bit parser. The file starts with the fixed opaque byte sequence
356 * 00 09 0f f0 0f f0 0f f0 0f f0 00 00 01
357 * After that the format is 1 byte section type (ASCII character), 2 byte length
358 * (big endian), <length> bytes content. Except for section 'e' which has 4 bytes
361 static int bitparse_find_section(int bitstream_version
, char section_name
, unsigned int *section_length
, z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
364 #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section
365 uint16_t numbytes
= 0;
366 while(numbytes
< MAX_FPGA_BIT_STREAM_HEADER_SEARCH
) {
367 char current_name
= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
369 unsigned int current_length
= 0;
370 if(current_name
< 'a' || current_name
> 'e') {
371 /* Strange section name, abort */
375 switch(current_name
) {
377 /* Four byte length field */
378 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 24;
379 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 16;
381 default: /* Fall through, two byte length field */
382 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 8;
383 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 0;
387 if(current_name
!= 'e' && current_length
> 255) {
388 /* Maybe a parse error */
392 if(current_name
== section_name
) {
394 *section_length
= current_length
;
399 for (uint16_t i
= 0; i
< current_length
&& numbytes
< MAX_FPGA_BIT_STREAM_HEADER_SEARCH
; i
++) {
400 get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
409 //----------------------------------------------------------------------------
410 // Check which FPGA image is currently loaded (if any). If necessary
411 // decompress and load the correct (HF or LF) image to the FPGA
412 //----------------------------------------------------------------------------
413 void FpgaDownloadAndGo(int bitstream_version
)
415 z_stream compressed_fpga_stream
;
416 uint8_t output_buffer
[OUTPUT_BUFFER_LEN
] = {0x00};
418 // check whether or not the bitstream is already loaded
419 if (downloaded_bitstream
== bitstream_version
)
422 // make sure that we have enough memory to decompress
423 BigBuf_free(); BigBuf_Clear_ext(false);
425 if (!reset_fpga_stream(bitstream_version
, &compressed_fpga_stream
, output_buffer
)) {
429 unsigned int bitstream_length
;
430 if(bitparse_find_section(bitstream_version
, 'e', &bitstream_length
, &compressed_fpga_stream
, output_buffer
)) {
431 DownloadFPGA(bitstream_version
, bitstream_length
, &compressed_fpga_stream
, output_buffer
);
432 downloaded_bitstream
= bitstream_version
;
435 inflateEnd(&compressed_fpga_stream
);
437 // free eventually allocated BigBuf memory
438 BigBuf_free(); BigBuf_Clear_ext(false);
442 //-----------------------------------------------------------------------------
443 // Gather version information from FPGA image. Needs to decompress the begin
444 // of the respective (HF or LF) image.
445 // Note: decompression makes use of (i.e. overwrites) BigBuf[]. It is therefore
446 // advisable to call this only once and store the results for later use.
447 //-----------------------------------------------------------------------------
448 void FpgaGatherVersion(int bitstream_version
, char *dst
, int len
)
450 unsigned int fpga_info_len
;
451 char tempstr
[40] = {0x00};
452 z_stream compressed_fpga_stream
;
453 uint8_t output_buffer
[OUTPUT_BUFFER_LEN
] = {0x00};
457 // ensure that we can allocate enough memory for decompression:
458 BigBuf_free(); BigBuf_Clear_ext(false);
460 if (!reset_fpga_stream(bitstream_version
, &compressed_fpga_stream
, output_buffer
))
463 if(bitparse_find_section(bitstream_version
, 'a', &fpga_info_len
, &compressed_fpga_stream
, output_buffer
)) {
464 for (uint16_t i
= 0; i
< fpga_info_len
; i
++) {
465 char c
= (char)get_from_fpga_stream(bitstream_version
, &compressed_fpga_stream
, output_buffer
);
466 if (i
< sizeof(tempstr
)) {
470 if (!memcmp("fpga_lf", tempstr
, 7))
471 strncat(dst
, "LF ", len
-1);
472 else if (!memcmp("fpga_hf", tempstr
, 7))
473 strncat(dst
, "HF ", len
-1);
475 strncat(dst
, "FPGA image built", len
-1);
476 if(bitparse_find_section(bitstream_version
, 'b', &fpga_info_len
, &compressed_fpga_stream
, output_buffer
)) {
477 strncat(dst
, " for ", len
-1);
478 for (uint16_t i
= 0; i
< fpga_info_len
; i
++) {
479 char c
= (char)get_from_fpga_stream(bitstream_version
, &compressed_fpga_stream
, output_buffer
);
480 if (i
< sizeof(tempstr
)) {
484 strncat(dst
, tempstr
, len
-1);
486 if(bitparse_find_section(bitstream_version
, 'c', &fpga_info_len
, &compressed_fpga_stream
, output_buffer
)) {
487 strncat(dst
, " on ", len
-1);
488 for (uint16_t i
= 0; i
< fpga_info_len
; i
++) {
489 char c
= (char)get_from_fpga_stream(bitstream_version
, &compressed_fpga_stream
, output_buffer
);
490 if (i
< sizeof(tempstr
)) {
494 strncat(dst
, tempstr
, len
-1);
496 if(bitparse_find_section(bitstream_version
, 'd', &fpga_info_len
, &compressed_fpga_stream
, output_buffer
)) {
497 strncat(dst
, " at ", len
-1);
498 for (uint16_t i
= 0; i
< fpga_info_len
; i
++) {
499 char c
= (char)get_from_fpga_stream(bitstream_version
, &compressed_fpga_stream
, output_buffer
);
500 if (i
< sizeof(tempstr
)) {
504 strncat(dst
, tempstr
, len
-1);
507 strncat(dst
, "\n", len
-1);
509 inflateEnd(&compressed_fpga_stream
);
513 //-----------------------------------------------------------------------------
514 // Send a 16 bit command/data pair to the FPGA.
515 // The bit format is: C3 C2 C1 C0 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
516 // where C is the 4 bit command and D is the 12 bit data
517 //-----------------------------------------------------------------------------
518 void FpgaSendCommand(uint16_t cmd
, uint16_t v
)
520 SetupSpi(SPI_FPGA_MODE
);
521 while ((AT91C_BASE_SPI
->SPI_SR
& AT91C_SPI_TXEMPTY
) == 0); // wait for the transfer to complete
522 AT91C_BASE_SPI
->SPI_TDR
= AT91C_SPI_LASTXFER
| cmd
| v
; // send the data
524 //-----------------------------------------------------------------------------
525 // Write the FPGA setup word (that determines what mode the logic is in, read
526 // vs. clone vs. etc.). This is now a special case of FpgaSendCommand() to
527 // avoid changing this function's occurence everywhere in the source code.
528 //-----------------------------------------------------------------------------
529 void FpgaWriteConfWord(uint8_t v
)
531 FpgaSendCommand(FPGA_CMD_SET_CONFREG
, v
);
534 //-----------------------------------------------------------------------------
535 // Set up the CMOS switches that mux the ADC: four switches, independently
536 // closable, but should only close one at a time. Not an FPGA thing, but
537 // the samples from the ADC always flow through the FPGA.
538 //-----------------------------------------------------------------------------
539 void SetAdcMuxFor(uint32_t whichGpio
)
541 AT91C_BASE_PIOA
->PIO_OER
=
547 AT91C_BASE_PIOA
->PIO_PER
=
553 LOW(GPIO_MUXSEL_HIPKD
);
554 LOW(GPIO_MUXSEL_HIRAW
);
555 LOW(GPIO_MUXSEL_LORAW
);
556 LOW(GPIO_MUXSEL_LOPKD
);
561 void Fpga_print_status(void) {
563 switch(downloaded_bitstream
) {
564 case FPGA_BITSTREAM_HF
: Dbprintf(" mode....................HF"); break;
565 case FPGA_BITSTREAM_LF
: Dbprintf(" mode....................LF"); break;
566 default: Dbprintf(" mode....................%d", downloaded_bitstream
); break;
570 int FpgaGetCurrent() {
571 return downloaded_bitstream
;