]> cvs.zerfleddert.de Git - proxmark3-svn/blob - armsrc/fpgaloader.c
Add Smartcard functions (RDV4.0) (#646)
[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 "fpgaloader.h"
14
15 #include <stdint.h>
16 #include <stddef.h>
17 #include <stdbool.h>
18 #include "apps.h"
19 #include "fpga.h"
20 #include "proxmark3.h"
21 #include "util.h"
22 #include "string.h"
23 #include "BigBuf.h"
24 #include "zlib.h"
25
26 // remember which version of the bitstream we have already downloaded to the FPGA
27 static int downloaded_bitstream = 0;
28
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;
31
32 static uint8_t *fpga_image_ptr = NULL;
33 static uint32_t uncompressed_bytes_cnt;
34
35 #define OUTPUT_BUFFER_LEN 80
36
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)
43 {
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
49
50 // Disable PIO control of the following pins, allows use by the SPI peripheral
51 AT91C_BASE_PIOA->PIO_PDR =
52 GPIO_NCS0 |
53 GPIO_NCS2 |
54 GPIO_MISO |
55 GPIO_MOSI |
56 GPIO_SPCK;
57
58 AT91C_BASE_PIOA->PIO_ASR =
59 GPIO_NCS0 |
60 GPIO_MISO |
61 GPIO_MOSI |
62 GPIO_SPCK;
63
64 AT91C_BASE_PIOA->PIO_BSR = GPIO_NCS2;
65
66 //enable the SPI Peripheral clock
67 AT91C_BASE_PMC->PMC_PCER = (1<<AT91C_ID_SPI);
68 // Enable SPI
69 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SPIEN;
70
71 switch (mode) {
72 case SPI_FPGA_MODE:
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
89 break;
90 case SPI_LCD_MODE:
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
107 break;
108 default: // Disable SPI
109 AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SPIDIS;
110 break;
111 }
112 }
113
114 //-----------------------------------------------------------------------------
115 // Set up the synchronous serial port, with the one set of options that we
116 // always use when we are talking to the FPGA. Both RX and TX are enabled.
117 //-----------------------------------------------------------------------------
118 void FpgaSetupSsc(void)
119 {
120 // First configure the GPIOs, and get ourselves a clock.
121 AT91C_BASE_PIOA->PIO_ASR =
122 GPIO_SSC_FRAME |
123 GPIO_SSC_DIN |
124 GPIO_SSC_DOUT |
125 GPIO_SSC_CLK;
126 AT91C_BASE_PIOA->PIO_PDR = GPIO_SSC_DOUT;
127
128 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_SSC);
129
130 // Now set up the SSC proper, starting from a known state.
131 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_SWRST;
132
133 // RX clock comes from TX clock, RX starts when TX starts, data changes
134 // on RX clock rising edge, sampled on falling edge
135 AT91C_BASE_SSC->SSC_RCMR = SSC_CLOCK_MODE_SELECT(1) | SSC_CLOCK_MODE_START(1);
136
137 // 8 bits per transfer, no loopback, MSB first, 1 transfer per sync
138 // pulse, no output sync
139 AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0);
140
141 // clock comes from TK pin, no clock output, outputs change on falling
142 // edge of TK, sample on rising edge of TK, start on positive-going edge of sync
143 AT91C_BASE_SSC->SSC_TCMR = SSC_CLOCK_MODE_SELECT(2) | SSC_CLOCK_MODE_START(5);
144
145 // tx framing is the same as the rx framing
146 AT91C_BASE_SSC->SSC_TFMR = AT91C_BASE_SSC->SSC_RFMR;
147
148 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_RXEN | AT91C_SSC_TXEN;
149 }
150
151 //-----------------------------------------------------------------------------
152 // Set up DMA to receive samples from the FPGA. We will use the PDC, with
153 // a single buffer as a circular buffer (so that we just chain back to
154 // ourselves, not to another buffer). The stuff to manipulate those buffers
155 // is in apps.h, because it should be inlined, for speed.
156 //-----------------------------------------------------------------------------
157 bool FpgaSetupSscDma(uint8_t *buf, int len)
158 {
159 if (buf == NULL) return false;
160
161 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; // Disable DMA Transfer
162 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) buf; // transfer to this memory address
163 AT91C_BASE_PDC_SSC->PDC_RCR = len; // transfer this many bytes
164 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) buf; // next transfer to same memory address
165 AT91C_BASE_PDC_SSC->PDC_RNCR = len; // ... with same number of bytes
166 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTEN; // go!
167
168 return true;
169 }
170
171
172 //----------------------------------------------------------------------------
173 // Uncompress (inflate) the FPGA data. Returns one decompressed byte with
174 // each call.
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 uncompressed_bytes_cnt++;
191
192 return *fpga_image_ptr++;
193 }
194
195 //----------------------------------------------------------------------------
196 // Undo the interleaving of several FPGA config files. FPGA config files
197 // are combined into one big file:
198 // 288 bytes from FPGA file 1, followed by 288 bytes from FGPA file 2, etc.
199 //----------------------------------------------------------------------------
200 static int get_from_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
201 {
202 while((uncompressed_bytes_cnt / FPGA_INTERLEAVE_SIZE) % fpga_bitstream_num != (bitstream_version - 1)) {
203 // skip undesired data belonging to other bitstream_versions
204 get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer);
205 }
206
207 return get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer);
208
209 }
210
211
212 static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size)
213 {
214 return BigBuf_malloc(items*size);
215 }
216
217
218 static void fpga_inflate_free(voidpf opaque, voidpf address)
219 {
220 BigBuf_free(); BigBuf_Clear_ext(false);
221 }
222
223
224 //----------------------------------------------------------------------------
225 // Initialize decompression of the respective (HF or LF) FPGA stream
226 //----------------------------------------------------------------------------
227 static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
228 {
229 uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE];
230
231 uncompressed_bytes_cnt = 0;
232
233 // initialize z_stream structure for inflate:
234 compressed_fpga_stream->next_in = &_binary_obj_fpga_all_bit_z_start;
235 compressed_fpga_stream->avail_in = &_binary_obj_fpga_all_bit_z_end - &_binary_obj_fpga_all_bit_z_start;
236 compressed_fpga_stream->next_out = output_buffer;
237 compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN;
238 compressed_fpga_stream->zalloc = &fpga_inflate_malloc;
239 compressed_fpga_stream->zfree = &fpga_inflate_free;
240
241 inflateInit2(compressed_fpga_stream, 0);
242
243 fpga_image_ptr = output_buffer;
244
245 for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) {
246 header[i] = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer);
247 }
248
249 // Check for a valid .bit file (starts with bitparse_fixed_header)
250 if(memcmp(bitparse_fixed_header, header, FPGA_BITSTREAM_FIXED_HEADER_SIZE) == 0) {
251 return true;
252 } else {
253 return false;
254 }
255 }
256
257
258 static void DownloadFPGA_byte(unsigned char w)
259 {
260 #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); }
261 SEND_BIT(7);
262 SEND_BIT(6);
263 SEND_BIT(5);
264 SEND_BIT(4);
265 SEND_BIT(3);
266 SEND_BIT(2);
267 SEND_BIT(1);
268 SEND_BIT(0);
269 }
270
271 // Download the fpga image starting at current stream position with length FpgaImageLen bytes
272 static void DownloadFPGA(int bitstream_version, int FpgaImageLen, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
273 {
274
275 //Dbprintf("DownloadFPGA(len: %d)", FpgaImageLen);
276
277 int i=0;
278
279 AT91C_BASE_PIOA->PIO_OER = GPIO_FPGA_ON;
280 AT91C_BASE_PIOA->PIO_PER = GPIO_FPGA_ON;
281 HIGH(GPIO_FPGA_ON); // ensure everything is powered on
282
283 SpinDelay(50);
284
285 LED_D_ON();
286
287 // These pins are inputs
288 AT91C_BASE_PIOA->PIO_ODR =
289 GPIO_FPGA_NINIT |
290 GPIO_FPGA_DONE;
291 // PIO controls the following pins
292 AT91C_BASE_PIOA->PIO_PER =
293 GPIO_FPGA_NINIT |
294 GPIO_FPGA_DONE;
295 // Enable pull-ups
296 AT91C_BASE_PIOA->PIO_PPUER =
297 GPIO_FPGA_NINIT |
298 GPIO_FPGA_DONE;
299
300 // setup initial logic state
301 HIGH(GPIO_FPGA_NPROGRAM);
302 LOW(GPIO_FPGA_CCLK);
303 LOW(GPIO_FPGA_DIN);
304 // These pins are outputs
305 AT91C_BASE_PIOA->PIO_OER =
306 GPIO_FPGA_NPROGRAM |
307 GPIO_FPGA_CCLK |
308 GPIO_FPGA_DIN;
309
310 // enter FPGA configuration mode
311 LOW(GPIO_FPGA_NPROGRAM);
312 SpinDelay(50);
313 HIGH(GPIO_FPGA_NPROGRAM);
314
315 i=100000;
316 // wait for FPGA ready to accept data signal
317 while ((i) && ( !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_FPGA_NINIT ) ) ) {
318 i--;
319 }
320
321 // crude error indicator, leave both red LEDs on and return
322 if (i==0){
323 LED_C_ON();
324 LED_D_ON();
325 return;
326 }
327
328 for(i = 0; i < FpgaImageLen; i++) {
329 int b = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer);
330 if (b < 0) {
331 Dbprintf("Error %d during FpgaDownload", b);
332 break;
333 }
334 DownloadFPGA_byte(b);
335 }
336
337 // continue to clock FPGA until ready signal goes high
338 i=100000;
339 while ( (i--) && ( !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_FPGA_DONE ) ) ) {
340 HIGH(GPIO_FPGA_CCLK);
341 LOW(GPIO_FPGA_CCLK);
342 }
343 // crude error indicator, leave both red LEDs on and return
344 if (i==0){
345 LED_C_ON();
346 LED_D_ON();
347 return;
348 }
349 LED_D_OFF();
350 }
351
352
353 /* Simple Xilinx .bit parser. The file starts with the fixed opaque byte sequence
354 * 00 09 0f f0 0f f0 0f f0 0f f0 00 00 01
355 * After that the format is 1 byte section type (ASCII character), 2 byte length
356 * (big endian), <length> bytes content. Except for section 'e' which has 4 bytes
357 * length.
358 */
359 static int bitparse_find_section(int bitstream_version, char section_name, unsigned int *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
360 {
361 int result = 0;
362 #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section
363 uint16_t numbytes = 0;
364 while(numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH) {
365 char current_name = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer);
366 numbytes++;
367 unsigned int current_length = 0;
368 if(current_name < 'a' || current_name > 'e') {
369 /* Strange section name, abort */
370 break;
371 }
372 current_length = 0;
373 switch(current_name) {
374 case 'e':
375 /* Four byte length field */
376 current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 24;
377 current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 16;
378 numbytes += 2;
379 default: /* Fall through, two byte length field */
380 current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 8;
381 current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 0;
382 numbytes += 2;
383 }
384
385 if(current_name != 'e' && current_length > 255) {
386 /* Maybe a parse error */
387 break;
388 }
389
390 if(current_name == section_name) {
391 /* Found it */
392 *section_length = current_length;
393 result = 1;
394 break;
395 }
396
397 for (uint16_t i = 0; i < current_length && numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH; i++) {
398 get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer);
399 numbytes++;
400 }
401 }
402
403 return result;
404 }
405
406
407 //----------------------------------------------------------------------------
408 // Check which FPGA image is currently loaded (if any). If necessary
409 // decompress and load the correct (HF or LF) image to the FPGA
410 //----------------------------------------------------------------------------
411 void FpgaDownloadAndGo(int bitstream_version)
412 {
413 z_stream compressed_fpga_stream;
414 uint8_t output_buffer[OUTPUT_BUFFER_LEN] = {0x00};
415
416 // check whether or not the bitstream is already loaded
417 if (downloaded_bitstream == bitstream_version)
418 return;
419
420 // make sure that we have enough memory to decompress
421 BigBuf_free(); BigBuf_Clear_ext(false);
422
423 if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) {
424 return;
425 }
426
427 unsigned int bitstream_length;
428 if (bitparse_find_section(bitstream_version, 'e', &bitstream_length, &compressed_fpga_stream, output_buffer)) {
429 DownloadFPGA(bitstream_version, bitstream_length, &compressed_fpga_stream, output_buffer);
430 downloaded_bitstream = bitstream_version;
431 }
432
433 inflateEnd(&compressed_fpga_stream);
434
435 // turn off antenna
436 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
437
438 // free eventually allocated BigBuf memory
439 BigBuf_free(); BigBuf_Clear_ext(false);
440 }
441
442
443 //-----------------------------------------------------------------------------
444 // Send a 16 bit command/data pair to the FPGA.
445 // The bit format is: C3 C2 C1 C0 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
446 // where C is the 4 bit command and D is the 12 bit data
447 //-----------------------------------------------------------------------------
448 void FpgaSendCommand(uint16_t cmd, uint16_t v)
449 {
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 }
454 //-----------------------------------------------------------------------------
455 // Write the FPGA setup word (that determines what mode the logic is in, read
456 // vs. clone vs. etc.). This is now a special case of FpgaSendCommand() to
457 // avoid changing this function's occurence everywhere in the source code.
458 //-----------------------------------------------------------------------------
459 void FpgaWriteConfWord(uint8_t v)
460 {
461 FpgaSendCommand(FPGA_CMD_SET_CONFREG, v);
462 }
463
464 //-----------------------------------------------------------------------------
465 // Set up the CMOS switches that mux the ADC: four switches, independently
466 // closable, but should only close one at a time. Not an FPGA thing, but
467 // the samples from the ADC always flow through the FPGA.
468 //-----------------------------------------------------------------------------
469 void SetAdcMuxFor(uint32_t whichGpio)
470 {
471 AT91C_BASE_PIOA->PIO_OER =
472 GPIO_MUXSEL_HIPKD |
473 GPIO_MUXSEL_LOPKD |
474 GPIO_MUXSEL_LORAW |
475 GPIO_MUXSEL_HIRAW;
476
477 AT91C_BASE_PIOA->PIO_PER =
478 GPIO_MUXSEL_HIPKD |
479 GPIO_MUXSEL_LOPKD |
480 GPIO_MUXSEL_LORAW |
481 GPIO_MUXSEL_HIRAW;
482
483 LOW(GPIO_MUXSEL_HIPKD);
484 LOW(GPIO_MUXSEL_HIRAW);
485 LOW(GPIO_MUXSEL_LORAW);
486 LOW(GPIO_MUXSEL_LOPKD);
487
488 HIGH(whichGpio);
489 }
490
491 void Fpga_print_status(void) {
492 Dbprintf("Currently loaded FPGA image:");
493 Dbprintf(" %s", fpga_version_information[downloaded_bitstream-1]);
494 }
495
496 int FpgaGetCurrent() {
497 return downloaded_bitstream;
498 }
Impressum, Datenschutz