fpga_compress: interleave (combine) fpga_lf.bit and fpga_hf.bit before compression.
[proxmark3-svn] / armsrc / fpgaloader.c
1 //-----------------------------------------------------------------------------
2 // Jonathan Westhues, April 2006
3 // iZsh <izsh at fail0verflow.com>, 2014
4 //
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
7 // the license.
8 //-----------------------------------------------------------------------------
9 // Routines to load the FPGA image, and then to configure the FPGA's major
10 // mode once it is configured.
11 //-----------------------------------------------------------------------------
12
13 #include <stdint.h>
14 #include <stddef.h>
15 #include <stdbool.h>
16 #include "fpgaloader.h"
17 #include "proxmark3.h"
18 #include "util.h"
19 #include "string.h"
20 #include "BigBuf.h"
21 #include "zlib.h"
22
23 extern void Dbprintf(const char *fmt, ...);
24
25 // remember which version of the bitstream we have already downloaded to the FPGA
26 static int downloaded_bitstream = FPGA_BITSTREAM_ERR;
27
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;
30
31 static uint8_t *fpga_image_ptr = NULL;
32 static uint32_t uncompressed_bytes_cnt;
33
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
38
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)
45 {
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
51
52 // Disable PIO control of the following pins, allows use by the SPI peripheral
53 AT91C_BASE_PIOA->PIO_PDR =
54 GPIO_NCS0 |
55 GPIO_NCS2 |
56 GPIO_MISO |
57 GPIO_MOSI |
58 GPIO_SPCK;
59
60 AT91C_BASE_PIOA->PIO_ASR =
61 GPIO_NCS0 |
62 GPIO_MISO |
63 GPIO_MOSI |
64 GPIO_SPCK;
65
66 AT91C_BASE_PIOA->PIO_BSR = GPIO_NCS2;
67
68 //enable the SPI Peripheral clock
69 AT91C_BASE_PMC->PMC_PCER = (1<<AT91C_ID_SPI);
70 // Enable SPI
71 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SPIEN;
72
73 switch (mode) {
74 case SPI_FPGA_MODE:
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
91 break;
92 case SPI_LCD_MODE:
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
109 break;
110 default: // Disable SPI
111 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SPIDIS;
112 break;
113 }
114 }
115
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)
121 {
122 // First configure the GPIOs, and get ourselves a clock.
123 AT91C_BASE_PIOA->PIO_ASR =
124 GPIO_SSC_FRAME |
125 GPIO_SSC_DIN |
126 GPIO_SSC_DOUT |
127 GPIO_SSC_CLK;
128 AT91C_BASE_PIOA->PIO_PDR = GPIO_SSC_DOUT;
129
130 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_SSC);
131
132 // Now set up the SSC proper, starting from a known state.
133 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_SWRST;
134
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);
138
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);
142
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);
146
147 // tx framing is the same as the rx framing
148 AT91C_BASE_SSC->SSC_TFMR = AT91C_BASE_SSC->SSC_RFMR;
149
150 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_RXEN | AT91C_SSC_TXEN;
151 }
152
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)
160 {
161 if (buf == NULL) {
162 return false;
163 }
164
165 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; // Disable DMA Transfer
166 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) buf; // transfer to this memory address
167 AT91C_BASE_PDC_SSC->PDC_RCR = len; // transfer this many bytes
168 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) buf; // next transfer to same memory address
169 AT91C_BASE_PDC_SSC->PDC_RNCR = len; // ... with same number of bytes
170 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTEN; // go!
171
172 return true;
173 }
174
175
176 static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer)
177 {
178 if (fpga_image_ptr == compressed_fpga_stream->next_out) { // need more data
179 compressed_fpga_stream->next_out = output_buffer;
180 compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN;
181 fpga_image_ptr = output_buffer;
182 int res = inflate(compressed_fpga_stream, Z_SYNC_FLUSH);
183 if (res != Z_OK) {
184 Dbprintf("inflate returned: %d, %s", res, compressed_fpga_stream->msg);
185 }
186 if (res < 0) {
187 return res;
188 }
189 }
190
191 uncompressed_bytes_cnt++;
192
193 return *fpga_image_ptr++;
194 }
195
196
197 static int get_from_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
198 {
199 while((uncompressed_bytes_cnt / FPGA_INTERLEAVE_SIZE) % FPGA_BITSTREAM_MAX != (bitstream_version - 1)) {
200 // skip undesired data belonging to other bitstream_versions
201 get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer);
202 }
203
204 return get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer);
205
206 }
207
208
209 static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size)
210 {
211 Dbprintf("zlib requested %d bytes", items*size);
212 return BigBuf_malloc(items*size);
213 }
214
215
216 static void fpga_inflate_free(voidpf opaque, voidpf address)
217 {
218 Dbprintf("zlib frees memory");
219 BigBuf_free_keep_EM();
220 }
221
222
223 static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
224 {
225 uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE];
226
227 uncompressed_bytes_cnt = 0;
228
229 // initialize z_stream structure for inflate:
230 compressed_fpga_stream->next_in = &_binary_obj_fpga_all_bit_z_start;
231 compressed_fpga_stream->avail_in = &_binary_obj_fpga_all_bit_z_start - &_binary_obj_fpga_all_bit_z_end;
232 compressed_fpga_stream->next_out = output_buffer;
233 compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN;
234 compressed_fpga_stream->zalloc = &fpga_inflate_malloc;
235 compressed_fpga_stream->zfree = &fpga_inflate_free;
236
237 inflateInit2(compressed_fpga_stream, 15);
238
239 fpga_image_ptr = output_buffer;
240
241 for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) {
242 header[i] = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer);
243 }
244
245 // Check for a valid .bit file (starts with _bitparse_fixed_header)
246 if(memcmp(_bitparse_fixed_header, header, FPGA_BITSTREAM_FIXED_HEADER_SIZE) == 0) {
247 return true;
248 } else {
249 return false;
250 }
251 }
252
253
254 static void DownloadFPGA_byte(unsigned char w)
255 {
256 #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); }
257 SEND_BIT(7);
258 SEND_BIT(6);
259 SEND_BIT(5);
260 SEND_BIT(4);
261 SEND_BIT(3);
262 SEND_BIT(2);
263 SEND_BIT(1);
264 SEND_BIT(0);
265 }
266
267 // Download the fpga image starting at current stream position with length FpgaImageLen bytes
268 static void DownloadFPGA(int bitstream_version, int FpgaImageLen, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
269 {
270
271 Dbprintf("DownloadFPGA(len: %d)", FpgaImageLen);
272
273 int i=0;
274
275 AT91C_BASE_PIOA->PIO_OER = GPIO_FPGA_ON;
276 AT91C_BASE_PIOA->PIO_PER = GPIO_FPGA_ON;
277 HIGH(GPIO_FPGA_ON); // ensure everything is powered on
278
279 SpinDelay(50);
280
281 LED_D_ON();
282
283 // These pins are inputs
284 AT91C_BASE_PIOA->PIO_ODR =
285 GPIO_FPGA_NINIT |
286 GPIO_FPGA_DONE;
287 // PIO controls the following pins
288 AT91C_BASE_PIOA->PIO_PER =
289 GPIO_FPGA_NINIT |
290 GPIO_FPGA_DONE;
291 // Enable pull-ups
292 AT91C_BASE_PIOA->PIO_PPUER =
293 GPIO_FPGA_NINIT |
294 GPIO_FPGA_DONE;
295
296 // setup initial logic state
297 HIGH(GPIO_FPGA_NPROGRAM);
298 LOW(GPIO_FPGA_CCLK);
299 LOW(GPIO_FPGA_DIN);
300 // These pins are outputs
301 AT91C_BASE_PIOA->PIO_OER =
302 GPIO_FPGA_NPROGRAM |
303 GPIO_FPGA_CCLK |
304 GPIO_FPGA_DIN;
305
306 // enter FPGA configuration mode
307 LOW(GPIO_FPGA_NPROGRAM);
308 SpinDelay(50);
309 HIGH(GPIO_FPGA_NPROGRAM);
310
311 i=100000;
312 // wait for FPGA ready to accept data signal
313 while ((i) && ( !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_FPGA_NINIT ) ) ) {
314 i--;
315 }
316
317 // crude error indicator, leave both red LEDs on and return
318 if (i==0){
319 LED_C_ON();
320 LED_D_ON();
321 return;
322 }
323
324 for(i = 0; i < FpgaImageLen; i++) {
325 int b = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer);
326 if (b < 0) {
327 Dbprintf("Error %d during FpgaDownload", b);
328 break;
329 }
330 DownloadFPGA_byte(b);
331 }
332
333 Dbprintf("%d bytes loaded into FPGA", i);
334
335 // continue to clock FPGA until ready signal goes high
336 i=100000;
337 while ( (i--) && ( !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_FPGA_DONE ) ) ) {
338 HIGH(GPIO_FPGA_CCLK);
339 LOW(GPIO_FPGA_CCLK);
340 }
341 // crude error indicator, leave both red LEDs on and return
342 if (i==0){
343 LED_C_ON();
344 LED_D_ON();
345 return;
346 }
347 LED_D_OFF();
348 }
349
350
351 /* Simple Xilinx .bit parser. The file starts with the fixed opaque byte sequence
352 * 00 09 0f f0 0f f0 0f f0 0f f0 00 00 01
353 * After that the format is 1 byte section type (ASCII character), 2 byte length
354 * (big endian), <length> bytes content. Except for section 'e' which has 4 bytes
355 * length.
356 */
357 static int bitparse_find_section(int bitstream_version, char section_name, unsigned int *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
358 {
359 int result = 0;
360 #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section
361 uint16_t numbytes = 0;
362 while(numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH) {
363 char current_name = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer);
364 numbytes++;
365 unsigned int current_length = 0;
366 if(current_name < 'a' || current_name > 'e') {
367 /* Strange section name, abort */
368 break;
369 }
370 current_length = 0;
371 switch(current_name) {
372 case 'e':
373 /* Four byte length field */
374 current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 24;
375 current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 16;
376 numbytes += 2;
377 default: /* Fall through, two byte length field */
378 current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 8;
379 current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 0;
380 numbytes += 2;
381 }
382
383 if(current_name != 'e' && current_length > 255) {
384 /* Maybe a parse error */
385 break;
386 }
387
388 if(current_name == section_name) {
389 /* Found it */
390 *section_length = current_length;
391 result = 1;
392 break;
393 }
394
395 for (uint16_t i = 0; i < current_length && numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH; i++) {
396 get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer);
397 numbytes++;
398 }
399 }
400
401 return result;
402 }
403
404
405 //-----------------------------------------------------------------------------
406 // Find out which FPGA image format is stored in flash, then call DownloadFPGA
407 // with the right parameters to download the image
408 //-----------------------------------------------------------------------------
409 void FpgaDownloadAndGo(int bitstream_version)
410 {
411 z_stream compressed_fpga_stream;
412 uint8_t output_buffer[OUTPUT_BUFFER_LEN];
413
414 // check whether or not the bitstream is already loaded
415 if (downloaded_bitstream == bitstream_version)
416 return;
417
418 if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) {
419 return;
420 }
421
422 unsigned int bitstream_length;
423 if(bitparse_find_section(bitstream_version, 'e', &bitstream_length, &compressed_fpga_stream, output_buffer)) {
424 DownloadFPGA(bitstream_version, bitstream_length, &compressed_fpga_stream, output_buffer);
425 downloaded_bitstream = bitstream_version;
426 }
427
428 inflateEnd(&compressed_fpga_stream);
429
430 }
431
432
433 void FpgaGatherVersion(int bitstream_version, char *dst, int len)
434 {
435 unsigned int fpga_info_len;
436 char tempstr[40];
437 z_stream compressed_fpga_stream;
438 uint8_t output_buffer[OUTPUT_BUFFER_LEN];
439
440 dst[0] = '\0';
441
442 if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) {
443 return;
444 }
445
446 if(bitparse_find_section(bitstream_version, 'a', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
447 for (uint16_t i = 0; i < fpga_info_len; i++) {
448 char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer);
449 if (i < sizeof(tempstr)) {
450 tempstr[i] = c;
451 }
452 }
453 if (!memcmp("fpga_lf", tempstr, 7))
454 strncat(dst, "LF ", len-1);
455 else if (!memcmp("fpga_hf", tempstr, 7))
456 strncat(dst, "HF ", len-1);
457 }
458 strncat(dst, "FPGA image built", len-1);
459 if(bitparse_find_section(bitstream_version, 'b', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
460 strncat(dst, " for ", len-1);
461 for (uint16_t i = 0; i < fpga_info_len; i++) {
462 char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer);
463 if (i < sizeof(tempstr)) {
464 tempstr[i] = c;
465 }
466 }
467 strncat(dst, tempstr, len-1);
468 }
469 if(bitparse_find_section(bitstream_version, 'c', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
470 strncat(dst, " on ", len-1);
471 for (uint16_t i = 0; i < fpga_info_len; i++) {
472 char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer);
473 if (i < sizeof(tempstr)) {
474 tempstr[i] = c;
475 }
476 }
477 strncat(dst, tempstr, len-1);
478 }
479 if(bitparse_find_section(bitstream_version, 'd', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
480 strncat(dst, " at ", len-1);
481 for (uint16_t i = 0; i < fpga_info_len; i++) {
482 char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer);
483 if (i < sizeof(tempstr)) {
484 tempstr[i] = c;
485 }
486 }
487 strncat(dst, tempstr, len-1);
488 }
489
490 inflateEnd(&compressed_fpga_stream);
491
492 }
493
494
495 //-----------------------------------------------------------------------------
496 // Send a 16 bit command/data pair to the FPGA.
497 // The bit format is: C3 C2 C1 C0 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
498 // where C is the 4 bit command and D is the 12 bit data
499 //-----------------------------------------------------------------------------
500 void FpgaSendCommand(uint16_t cmd, uint16_t v)
501 {
502 SetupSpi(SPI_FPGA_MODE);
503 while ((AT91C_BASE_SPI->SPI_SR & AT91C_SPI_TXEMPTY) == 0); // wait for the transfer to complete
504 AT91C_BASE_SPI->SPI_TDR = AT91C_SPI_LASTXFER | cmd | v; // send the data
505 }
506 //-----------------------------------------------------------------------------
507 // Write the FPGA setup word (that determines what mode the logic is in, read
508 // vs. clone vs. etc.). This is now a special case of FpgaSendCommand() to
509 // avoid changing this function's occurence everywhere in the source code.
510 //-----------------------------------------------------------------------------
511 void FpgaWriteConfWord(uint8_t v)
512 {
513 FpgaSendCommand(FPGA_CMD_SET_CONFREG, v);
514 }
515
516 //-----------------------------------------------------------------------------
517 // Set up the CMOS switches that mux the ADC: four switches, independently
518 // closable, but should only close one at a time. Not an FPGA thing, but
519 // the samples from the ADC always flow through the FPGA.
520 //-----------------------------------------------------------------------------
521 void SetAdcMuxFor(uint32_t whichGpio)
522 {
523 AT91C_BASE_PIOA->PIO_OER =
524 GPIO_MUXSEL_HIPKD |
525 GPIO_MUXSEL_LOPKD |
526 GPIO_MUXSEL_LORAW |
527 GPIO_MUXSEL_HIRAW;
528
529 AT91C_BASE_PIOA->PIO_PER =
530 GPIO_MUXSEL_HIPKD |
531 GPIO_MUXSEL_LOPKD |
532 GPIO_MUXSEL_LORAW |
533 GPIO_MUXSEL_HIRAW;
534
535 LOW(GPIO_MUXSEL_HIPKD);
536 LOW(GPIO_MUXSEL_HIRAW);
537 LOW(GPIO_MUXSEL_LORAW);
538 LOW(GPIO_MUXSEL_LOPKD);
539
540 HIGH(whichGpio);
541 }
Impressum, Datenschutz