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 //-----------------------------------------------------------------------------
13 #include "fpgaloader.h"
20 #include "proxmark3.h"
26 // remember which version of the bitstream we have already downloaded to the FPGA
27 static int downloaded_bitstream
= 0;
29 // this is where the bitstreams are located in memory:
30 extern uint8_t _binary_obj_fpga_all_bit_z_start
, _binary_obj_fpga_all_bit_z_end
;
32 static uint8_t *fpga_image_ptr
= NULL
;
33 static uint32_t uncompressed_bytes_cnt
;
35 #define OUTPUT_BUFFER_LEN 80
37 //-----------------------------------------------------------------------------
38 // Set up the Serial Peripheral Interface as master
39 // Used to write the FPGA config word
40 // May also be used to write to other SPI attached devices like an LCD
41 //-----------------------------------------------------------------------------
42 void SetupSpi(int mode
)
44 // PA10 -> SPI_NCS2 chip select (LCD)
45 // PA11 -> SPI_NCS0 chip select (FPGA)
46 // PA12 -> SPI_MISO Master-In Slave-Out
47 // PA13 -> SPI_MOSI Master-Out Slave-In
48 // PA14 -> SPI_SPCK Serial Clock
50 // Disable PIO control of the following pins, allows use by the SPI peripheral
51 AT91C_BASE_PIOA
->PIO_PDR
=
58 AT91C_BASE_PIOA
->PIO_ASR
=
64 AT91C_BASE_PIOA
->PIO_BSR
= GPIO_NCS2
;
66 //enable the SPI Peripheral clock
67 AT91C_BASE_PMC
->PMC_PCER
= (1<<AT91C_ID_SPI
);
69 AT91C_BASE_SPI
->SPI_CR
= AT91C_SPI_SPIEN
;
73 AT91C_BASE_SPI
->SPI_MR
=
74 ( 0 << 24) | // Delay between chip selects (take default: 6 MCK periods)
75 (14 << 16) | // Peripheral Chip Select (selects FPGA SPI_NCS0 or PA11)
76 ( 0 << 7) | // Local Loopback Disabled
77 ( 1 << 4) | // Mode Fault Detection disabled
78 ( 0 << 2) | // Chip selects connected directly to peripheral
79 ( 0 << 1) | // Fixed Peripheral Select
80 ( 1 << 0); // Master Mode
81 AT91C_BASE_SPI
->SPI_CSR
[0] =
82 ( 1 << 24) | // Delay between Consecutive Transfers (32 MCK periods)
83 ( 1 << 16) | // Delay Before SPCK (1 MCK period)
84 ( 6 << 8) | // Serial Clock Baud Rate (baudrate = MCK/6 = 24Mhz/6 = 4M baud
85 ( 8 << 4) | // Bits per Transfer (16 bits)
86 ( 0 << 3) | // Chip Select inactive after transfer
87 ( 1 << 1) | // Clock Phase data captured on leading edge, changes on following edge
88 ( 0 << 0); // Clock Polarity inactive state is logic 0
91 AT91C_BASE_SPI
->SPI_MR
=
92 ( 0 << 24) | // Delay between chip selects (take default: 6 MCK periods)
93 (11 << 16) | // Peripheral Chip Select (selects LCD SPI_NCS2 or PA10)
94 ( 0 << 7) | // Local Loopback Disabled
95 ( 1 << 4) | // Mode Fault Detection disabled
96 ( 0 << 2) | // Chip selects connected directly to peripheral
97 ( 0 << 1) | // Fixed Peripheral Select
98 ( 1 << 0); // Master Mode
99 AT91C_BASE_SPI
->SPI_CSR
[2] =
100 ( 1 << 24) | // Delay between Consecutive Transfers (32 MCK periods)
101 ( 1 << 16) | // Delay Before SPCK (1 MCK period)
102 ( 6 << 8) | // Serial Clock Baud Rate (baudrate = MCK/6 = 24Mhz/6 = 4M baud
103 ( 1 << 4) | // Bits per Transfer (9 bits)
104 ( 0 << 3) | // Chip Select inactive after transfer
105 ( 1 << 1) | // Clock Phase data captured on leading edge, changes on following edge
106 ( 0 << 0); // Clock Polarity inactive state is logic 0
108 default: // Disable SPI
109 AT91C_BASE_SPI
->SPI_CR
= AT91C_SPI_SPIDIS
;
114 //-----------------------------------------------------------------------------
115 // Set up the synchronous serial port with the set of options that fits
116 // the FPGA mode. Both RX and TX are always enabled.
117 //-----------------------------------------------------------------------------
118 void FpgaSetupSsc(uint16_t FPGA_mode
) {
119 // First configure the GPIOs, and get ourselves a clock.
120 AT91C_BASE_PIOA
->PIO_ASR
=
125 AT91C_BASE_PIOA
->PIO_PDR
= GPIO_SSC_DOUT
;
127 AT91C_BASE_PMC
->PMC_PCER
= (1 << AT91C_ID_SSC
);
129 // Now set up the SSC proper, starting from a known state.
130 AT91C_BASE_SSC
->SSC_CR
= AT91C_SSC_SWRST
;
132 // RX clock comes from TX clock, RX starts on Transmit Start,
133 // data and frame signal is sampled on falling edge of RK
134 AT91C_BASE_SSC
->SSC_RCMR
= SSC_CLOCK_MODE_SELECT(1) | SSC_CLOCK_MODE_START(1);
136 // 8, 16 or 32 bits per transfer, no loopback, MSB first, 1 transfer per sync
137 // pulse, no output sync
138 if ((FPGA_mode
& FPGA_MAJOR_MODE_MASK
) == FPGA_MAJOR_MODE_HF_READER
&& FpgaGetCurrent() == FPGA_BITSTREAM_HF
) {
139 AT91C_BASE_SSC
->SSC_RFMR
= SSC_FRAME_MODE_BITS_IN_WORD(16) | AT91C_SSC_MSBF
| SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
141 AT91C_BASE_SSC
->SSC_RFMR
= SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF
| SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
144 // TX clock comes from TK pin, no clock output, outputs change on rising edge of TK,
145 // TF (frame sync) is sampled on falling edge of TK, start TX on rising edge of TF
146 AT91C_BASE_SSC
->SSC_TCMR
= SSC_CLOCK_MODE_SELECT(2) | SSC_CLOCK_MODE_START(5);
148 // tx framing is the same as the rx framing
149 AT91C_BASE_SSC
->SSC_TFMR
= AT91C_BASE_SSC
->SSC_RFMR
;
151 AT91C_BASE_SSC
->SSC_CR
= AT91C_SSC_RXEN
| AT91C_SSC_TXEN
;
154 //-----------------------------------------------------------------------------
155 // Set up DMA to receive samples from the FPGA. We will use the PDC, with
156 // a single buffer as a circular buffer (so that we just chain back to
157 // ourselves, not to another buffer). The stuff to manipulate those buffers
158 // is in apps.h, because it should be inlined, for speed.
159 //-----------------------------------------------------------------------------
160 bool FpgaSetupSscDma(uint8_t *buf
, uint16_t sample_count
) {
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
= sample_count
; // transfer this many samples
166 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) buf
; // next transfer to same memory address
167 AT91C_BASE_PDC_SSC
->PDC_RNCR
= sample_count
; // ... with same number of samples
168 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTEN
; // go!
173 //----------------------------------------------------------------------------
174 // Uncompress (inflate) the FPGA data. Returns one decompressed byte with
176 //----------------------------------------------------------------------------
177 static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
179 if (fpga_image_ptr
== compressed_fpga_stream
->next_out
) { // need more data
180 compressed_fpga_stream
->next_out
= output_buffer
;
181 compressed_fpga_stream
->avail_out
= OUTPUT_BUFFER_LEN
;
182 fpga_image_ptr
= output_buffer
;
183 int res
= inflate(compressed_fpga_stream
, Z_SYNC_FLUSH
);
185 Dbprintf("inflate returned: %d, %s", res
, compressed_fpga_stream
->msg
);
191 uncompressed_bytes_cnt
++;
193 return *fpga_image_ptr
++;
196 //----------------------------------------------------------------------------
197 // Undo the interleaving of several FPGA config files. FPGA config files
198 // are combined into one big file:
199 // 288 bytes from FPGA file 1, followed by 288 bytes from FGPA file 2, etc.
200 //----------------------------------------------------------------------------
201 static int get_from_fpga_stream(int bitstream_version
, z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
203 while((uncompressed_bytes_cnt
/ FPGA_INTERLEAVE_SIZE
) % fpga_bitstream_num
!= (bitstream_version
- 1)) {
204 // skip undesired data belonging to other bitstream_versions
205 get_from_fpga_combined_stream(compressed_fpga_stream
, output_buffer
);
208 return get_from_fpga_combined_stream(compressed_fpga_stream
, output_buffer
);
213 static voidpf
fpga_inflate_malloc(voidpf opaque
, uInt items
, uInt size
)
215 return BigBuf_malloc(items
*size
);
219 static void fpga_inflate_free(voidpf opaque
, voidpf address
)
221 BigBuf_free(); BigBuf_Clear_ext(false);
225 //----------------------------------------------------------------------------
226 // Initialize decompression of the respective (HF or LF) FPGA stream
227 //----------------------------------------------------------------------------
228 static bool reset_fpga_stream(int bitstream_version
, z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
230 uint8_t header
[FPGA_BITSTREAM_FIXED_HEADER_SIZE
];
232 uncompressed_bytes_cnt
= 0;
234 // initialize z_stream structure for inflate:
235 compressed_fpga_stream
->next_in
= &_binary_obj_fpga_all_bit_z_start
;
236 compressed_fpga_stream
->avail_in
= &_binary_obj_fpga_all_bit_z_end
- &_binary_obj_fpga_all_bit_z_start
;
237 compressed_fpga_stream
->next_out
= output_buffer
;
238 compressed_fpga_stream
->avail_out
= OUTPUT_BUFFER_LEN
;
239 compressed_fpga_stream
->zalloc
= &fpga_inflate_malloc
;
240 compressed_fpga_stream
->zfree
= &fpga_inflate_free
;
242 inflateInit2(compressed_fpga_stream
, 0);
244 fpga_image_ptr
= output_buffer
;
246 for (uint16_t i
= 0; i
< FPGA_BITSTREAM_FIXED_HEADER_SIZE
; i
++) {
247 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) {
259 static void DownloadFPGA_byte(unsigned char w
)
261 #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); }
272 // Download the fpga image starting at current stream position with length FpgaImageLen bytes
273 static void DownloadFPGA(int bitstream_version
, int FpgaImageLen
, z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
276 //Dbprintf("DownloadFPGA(len: %d)", FpgaImageLen);
280 AT91C_BASE_PIOA
->PIO_OER
= GPIO_FPGA_ON
;
281 AT91C_BASE_PIOA
->PIO_PER
= GPIO_FPGA_ON
;
282 HIGH(GPIO_FPGA_ON
); // ensure everything is powered on
288 // These pins are inputs
289 AT91C_BASE_PIOA
->PIO_ODR
=
292 // PIO controls the following pins
293 AT91C_BASE_PIOA
->PIO_PER
=
297 AT91C_BASE_PIOA
->PIO_PPUER
=
301 // setup initial logic state
302 HIGH(GPIO_FPGA_NPROGRAM
);
305 // These pins are outputs
306 AT91C_BASE_PIOA
->PIO_OER
=
311 // enter FPGA configuration mode
312 LOW(GPIO_FPGA_NPROGRAM
);
314 HIGH(GPIO_FPGA_NPROGRAM
);
317 // wait for FPGA ready to accept data signal
318 while ((i
) && ( !(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_FPGA_NINIT
) ) ) {
322 // crude error indicator, leave both red LEDs on and return
329 for(i
= 0; i
< FpgaImageLen
; i
++) {
330 int b
= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
332 Dbprintf("Error %d during FpgaDownload", b
);
335 DownloadFPGA_byte(b
);
338 // continue to clock FPGA until ready signal goes high
340 while ( (i
--) && ( !(AT91C_BASE_PIOA
->PIO_PDSR
& GPIO_FPGA_DONE
) ) ) {
341 HIGH(GPIO_FPGA_CCLK
);
344 // crude error indicator, leave both red LEDs on and return
354 /* Simple Xilinx .bit parser. The file starts with the fixed opaque byte sequence
355 * 00 09 0f f0 0f f0 0f f0 0f f0 00 00 01
356 * After that the format is 1 byte section type (ASCII character), 2 byte length
357 * (big endian), <length> bytes content. Except for section 'e' which has 4 bytes
360 static int bitparse_find_section(int bitstream_version
, char section_name
, unsigned int *section_length
, z_streamp compressed_fpga_stream
, uint8_t *output_buffer
)
363 #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section
364 uint16_t numbytes
= 0;
365 while(numbytes
< MAX_FPGA_BIT_STREAM_HEADER_SEARCH
) {
366 char current_name
= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
368 unsigned int current_length
= 0;
369 if(current_name
< 'a' || current_name
> 'e') {
370 /* Strange section name, abort */
374 switch(current_name
) {
376 /* Four byte length field */
377 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 24;
378 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 16;
380 default: /* Fall through, two byte length field */
381 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 8;
382 current_length
+= get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
) << 0;
386 if(current_name
!= 'e' && current_length
> 255) {
387 /* Maybe a parse error */
391 if(current_name
== section_name
) {
393 *section_length
= current_length
;
398 for (uint16_t i
= 0; i
< current_length
&& numbytes
< MAX_FPGA_BIT_STREAM_HEADER_SEARCH
; i
++) {
399 get_from_fpga_stream(bitstream_version
, compressed_fpga_stream
, output_buffer
);
408 //----------------------------------------------------------------------------
409 // Check which FPGA image is currently loaded (if any). If necessary
410 // decompress and load the correct (HF or LF) image to the FPGA
411 //----------------------------------------------------------------------------
412 void FpgaDownloadAndGo(int bitstream_version
)
414 z_stream compressed_fpga_stream
;
415 uint8_t output_buffer
[OUTPUT_BUFFER_LEN
] = {0x00};
417 // check whether or not the bitstream is already loaded
418 if (downloaded_bitstream
== bitstream_version
) {
423 // make sure that we have enough memory to decompress
424 BigBuf_free(); BigBuf_Clear_ext(false);
426 if (!reset_fpga_stream(bitstream_version
, &compressed_fpga_stream
, output_buffer
)) {
430 unsigned int bitstream_length
;
431 if (bitparse_find_section(bitstream_version
, 'e', &bitstream_length
, &compressed_fpga_stream
, output_buffer
)) {
432 DownloadFPGA(bitstream_version
, bitstream_length
, &compressed_fpga_stream
, output_buffer
);
433 downloaded_bitstream
= bitstream_version
;
436 inflateEnd(&compressed_fpga_stream
);
439 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
441 // free eventually allocated BigBuf memory
442 BigBuf_free(); BigBuf_Clear_ext(false);
446 //-----------------------------------------------------------------------------
447 // Send a 16 bit command/data pair to the FPGA.
448 // The bit format is: C3 C2 C1 C0 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
449 // where C is the 4 bit command and D is the 12 bit data
450 //-----------------------------------------------------------------------------
451 void FpgaSendCommand(uint16_t cmd
, uint16_t v
) {
452 SetupSpi(SPI_FPGA_MODE
);
453 AT91C_BASE_SPI
->SPI_TDR
= AT91C_SPI_LASTXFER
| cmd
| v
; // write the data to be sent
454 while ((AT91C_BASE_SPI
->SPI_SR
& AT91C_SPI_TXEMPTY
) == 0); // wait for the transfer to complete
457 //-----------------------------------------------------------------------------
458 // Write the FPGA setup word (that determines what mode the logic is in, read
459 // vs. clone vs. etc.). This is now a special case of FpgaSendCommand() to
460 // avoid changing this function's occurence everywhere in the source code.
461 //-----------------------------------------------------------------------------
462 void FpgaWriteConfWord(uint16_t v
) {
463 FpgaSendCommand(FPGA_CMD_SET_CONFREG
, v
);
466 //-----------------------------------------------------------------------------
467 // enable/disable FPGA internal tracing
468 //-----------------------------------------------------------------------------
469 void FpgaEnableTracing(void) {
470 FpgaSendCommand(FPGA_CMD_TRACE_ENABLE
, 1);
473 void FpgaDisableTracing(void) {
474 FpgaSendCommand(FPGA_CMD_TRACE_ENABLE
, 0);
477 //-----------------------------------------------------------------------------
478 // Set up the CMOS switches that mux the ADC: four switches, independently
479 // closable, but should only close one at a time. Not an FPGA thing, but
480 // the samples from the ADC always flow through the FPGA.
481 //-----------------------------------------------------------------------------
482 void SetAdcMuxFor(uint32_t whichGpio
)
484 AT91C_BASE_PIOA
->PIO_OER
=
490 AT91C_BASE_PIOA
->PIO_PER
=
496 LOW(GPIO_MUXSEL_HIPKD
);
497 LOW(GPIO_MUXSEL_HIRAW
);
498 LOW(GPIO_MUXSEL_LORAW
);
499 LOW(GPIO_MUXSEL_LOPKD
);
504 void Fpga_print_status(void) {
505 Dbprintf("Currently loaded FPGA image:");
506 Dbprintf(" %s", fpga_version_information
[downloaded_bitstream
-1]);
509 int FpgaGetCurrent() {
510 return downloaded_bitstream
;