]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/legicrf.c
5ee4d667c926beed5c5ce05ab9289372152012cd
[proxmark3-svn] / armsrc / legicrf.c
1 //-----------------------------------------------------------------------------
2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // LEGIC RF simulation code
9 //-----------------------------------------------------------------------------
10
11 #include "legicrf.h"
12
13 static struct legic_frame {
14 int bits;
15 uint32_t data;
16 } current_frame;
17
18 static enum {
19 STATE_DISCON,
20 STATE_IV,
21 STATE_CON,
22 } legic_state;
23
24 static crc_t legic_crc;
25 static int legic_read_count;
26 static uint32_t legic_prng_bc;
27 static uint32_t legic_prng_iv;
28
29 static int legic_phase_drift;
30 static int legic_frame_drift;
31 static int legic_reqresp_drift;
32
33 int timestamp;
34
35 AT91PS_TC timer;
36 AT91PS_TC prng_timer;
37
38 static void setup_timer(void) {
39 /* Set up Timer 1 to use for measuring time between pulses. Since we're bit-banging
40 * this it won't be terribly accurate but should be good enough.
41 */
42 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
43 timer = AT91C_BASE_TC1;
44 timer->TC_CCR = AT91C_TC_CLKDIS;
45 timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK;
46 timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
47
48 /*
49 * Set up Timer 2 to use for measuring time between frames in
50 * tag simulation mode. Runs 4x faster as Timer 1
51 */
52 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC2);
53 prng_timer = AT91C_BASE_TC2;
54 prng_timer->TC_CCR = AT91C_TC_CLKDIS;
55 prng_timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV2_CLOCK;
56 prng_timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
57 }
58
59 /* At TIMER_CLOCK3 (MCK/32) */
60 #define RWD_TIME_1 150 /* RWD_TIME_PAUSE off, 80us on = 100us */
61 #define RWD_TIME_0 90 /* RWD_TIME_PAUSE off, 40us on = 60us */
62 #define RWD_TIME_PAUSE 30 /* 20us */
63 #define RWD_TIME_FUZZ 20 /* rather generous 13us, since the peak detector + hysteresis fuzz quite a bit */
64 #define TAG_TIME_BIT 150 /* 100us for every bit */
65 #define TAG_TIME_WAIT 490 /* time from RWD frame end to tag frame start, experimentally determined */
66
67 #define SIM_DIVISOR 586 /* prng_time/SIM_DIVISOR count prng needs to be forwared */
68 #define SIM_SHIFT 900 /* prng_time+SIM_SHIFT shift of delayed start */
69
70 #define SESSION_IV 0x55
71 #define OFFSET_LOG 1024
72
73 #define FUZZ_EQUAL(value, target, fuzz) ((value) > ((target)-(fuzz)) && (value) < ((target)+(fuzz)))
74
75 // ~ 258us + 100us*delay
76 #define WAIT_387 WAIT(387)
77 #define WAIT(delay) while(timer->TC_CV < (delay) );
78
79
80 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
81 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
82 #define LEGIC_CARD_MEMSIZE 1024
83 static uint8_t* cardmem;
84
85 /*
86 The new tracelog..
87 // Traceformat:
88 // 32 bits timestamp (little endian)
89 // 16 bits duration (little endian)
90 // 16 bits data length (little endian, Highest Bit used as readerToTag flag)
91 // y Bytes data
92 // x Bytes parity (one byte per 8 bytes data)
93 */
94
95 /* Generate Keystream */
96 static uint32_t get_key_stream(int skip, int count)
97 {
98 uint32_t key = 0;
99 int i;
100
101 // Use int to enlarge timer tc to 32bit
102 legic_prng_bc += prng_timer->TC_CV;
103
104 // reset the prng timer.
105 prng_timer->TC_CCR = AT91C_TC_SWTRG;
106 while(prng_timer->TC_CV > 1) ;
107
108 /* If skip == -1, forward prng time based */
109 if(skip == -1) {
110 i = (legic_prng_bc + SIM_SHIFT)/SIM_DIVISOR; /* Calculate Cycles based on timer */
111 i -= legic_prng_count(); /* substract cycles of finished frames */
112 i -= count; /* substract current frame length, rewind to beginning */
113 legic_prng_forward(i);
114 } else {
115 legic_prng_forward(skip);
116 }
117
118 i = (count == 6) ? -1 : legic_read_count;
119
120 /* Write Time Data into LOG */
121 // uint8_t *BigBuf = BigBuf_get_addr();
122 // BigBuf[OFFSET_LOG+128+i] = legic_prng_count();
123 // BigBuf[OFFSET_LOG+256+i*4] = (legic_prng_bc >> 0) & 0xff;
124 // BigBuf[OFFSET_LOG+256+i*4+1] = (legic_prng_bc >> 8) & 0xff;
125 // BigBuf[OFFSET_LOG+256+i*4+2] = (legic_prng_bc >>16) & 0xff;
126 // BigBuf[OFFSET_LOG+256+i*4+3] = (legic_prng_bc >>24) & 0xff;
127 // BigBuf[OFFSET_LOG+384+i] = count;
128
129 /* Generate KeyStream */
130 for(i=0; i<count; i++) {
131 key |= legic_prng_get_bit() << i;
132 legic_prng_forward(1);
133 }
134 return key;
135 }
136
137 /* Send a frame in tag mode, the FPGA must have been set up by
138 * LegicRfSimulate
139 */
140 static void frame_send_tag(uint16_t response, int bits, int crypt)
141 {
142 /* Bitbang the response */
143 AT91C_BASE_PIOA->PIO_CODR = GPIO_SSC_DOUT;
144 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
145 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
146
147 /* Use time to crypt frame */
148 if(crypt) {
149 legic_prng_forward(2); /* TAG_TIME_WAIT -> shift by 2 */
150 int key = 0;
151 for(int i = 0; i < bits; i++) {
152 key |= legic_prng_get_bit() << i;
153 legic_prng_forward(1);
154 }
155 response = response ^ key;
156 }
157
158 /* Wait for the frame start */
159 //while(timer->TC_CV < (TAG_TIME_WAIT - 30)) ;
160 WAIT( TAG_TIME_WAIT - 30)
161
162 uint8_t bit = 0;
163 for(int i = 0; i < bits; i++) {
164 int nextbit = timer->TC_CV + TAG_TIME_BIT;
165 bit = response & 1;
166 response >>= 1;
167
168 if (bit)
169 AT91C_BASE_PIOA->PIO_SODR = GPIO_SSC_DOUT;
170 else
171 AT91C_BASE_PIOA->PIO_CODR = GPIO_SSC_DOUT;
172
173 //while(timer->TC_CV < nextbit) ;
174 WAIT(nextbit)
175 }
176 AT91C_BASE_PIOA->PIO_CODR = GPIO_SSC_DOUT;
177 }
178
179 // Starts Clock and waits until its reset
180 static void ResetClock(void){
181 timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
182 while(timer->TC_CV > 1) ;
183 }
184
185 /* Send a frame in reader mode, the FPGA must have been set up by
186 * LegicRfReader
187 */
188 static void frame_send_rwd(uint32_t data, int bits){
189
190 ResetClock();
191 int starttime = 0, pause_end = 0, bit = 0, bit_end = 0;
192
193 for(int i = 0; i<bits; i++) {
194
195 starttime = timer->TC_CV;
196 pause_end = starttime + RWD_TIME_PAUSE;
197 bit = data & 1;
198 data >>= 1;
199
200 if(bit ^ legic_prng_get_bit())
201 bit_end = starttime + RWD_TIME_1;
202 else
203 bit_end = starttime + RWD_TIME_0;
204
205
206 /* RWD_TIME_PAUSE time off, then some time on, so that the complete bit time is
207 * RWD_TIME_x, where x is the bit to be transmitted */
208 AT91C_BASE_PIOA->PIO_CODR = GPIO_SSC_DOUT;
209
210 WAIT( pause_end )
211
212 AT91C_BASE_PIOA->PIO_SODR = GPIO_SSC_DOUT;
213
214 legic_prng_forward(1); /* bit duration is longest. use this time to forward the lfsr */
215
216 WAIT( bit_end )
217 }
218
219 /* One final pause to mark the end of the frame */
220 pause_end = timer->TC_CV + RWD_TIME_PAUSE;
221
222 AT91C_BASE_PIOA->PIO_CODR = GPIO_SSC_DOUT;
223
224 WAIT(pause_end)
225
226 AT91C_BASE_PIOA->PIO_SODR = GPIO_SSC_DOUT;
227
228 /* Reset the timer, to measure time until the start of the tag frame */
229 ResetClock();
230 }
231
232 /* Receive a frame from the card in reader emulation mode, the FPGA and
233 * timer must have been set up by LegicRfReader and frame_send_rwd.
234 *
235 * The LEGIC RF protocol from card to reader does not include explicit
236 * frame start/stop information or length information. The reader must
237 * know beforehand how many bits it wants to receive. (Notably: a card
238 * sending a stream of 0-bits is indistinguishable from no card present.)
239 *
240 * Receive methodology: There is a fancy correlator in hi_read_rx_xcorr, but
241 * I'm not smart enough to use it. Instead I have patched hi_read_tx to output
242 * the ADC signal with hysteresis on SSP_DIN. Bit-bang that signal and look
243 * for edges. Count the edges in each bit interval. If they are approximately
244 * 0 this was a 0-bit, if they are approximately equal to the number of edges
245 * expected for a 212kHz subcarrier, this was a 1-bit. For timing we use the
246 * timer that's still running from frame_send_rwd in order to get a synchronization
247 * with the frame that we just sent.
248 *
249 * FIXME: Because we're relying on the hysteresis to just do the right thing
250 * the range is severely reduced (and you'll probably also need a good antenna).
251 * So this should be fixed some time in the future for a proper receiver.
252 */
253 static void frame_receive_rwd(struct legic_frame * const f, int bits, int crypt)
254 {
255 uint32_t the_bit = 1; /* Use a bitmask to save on shifts */
256 uint32_t data = 0;
257 int i, old_level = 0, edges = 0;
258 int next_bit_at = TAG_TIME_WAIT;
259
260 if(bits > 32) bits = 32;
261
262 AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_DIN;
263 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DIN;
264
265 /* we have some time now, precompute the cipher
266 * since we cannot compute it on the fly while reading */
267 legic_prng_forward(2);
268
269 if(crypt) {
270 for(i=0; i<bits; i++) {
271 data |= legic_prng_get_bit() << i;
272 legic_prng_forward(1);
273 }
274 }
275
276 WAIT(next_bit_at)
277
278 next_bit_at += TAG_TIME_BIT;
279
280 for(i=0; i<bits; i++) {
281 edges = 0;
282 while(timer->TC_CV < next_bit_at) {
283 int level = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
284 if(level != old_level)
285 edges++;
286 old_level = level;
287 }
288 next_bit_at += TAG_TIME_BIT;
289
290 // We expect 42 edges
291 if(edges > 20 && edges < 60) {
292 data ^= the_bit;
293 }
294 the_bit <<= 1;
295 }
296
297 f->data = data;
298 f->bits = bits;
299
300 // Reset the timer, to synchronize the next frame
301 ResetClock();
302 }
303
304 static void frame_append_bit(struct legic_frame * const f, int bit) {
305 // Overflow, won't happen
306 if (f->bits >= 31) return;
307
308 f->data |= (bit << f->bits);
309 f->bits++;
310 }
311
312 static void frame_clean(struct legic_frame * const f) {
313 f->data = 0;
314 f->bits = 0;
315 }
316
317 // Setup pm3 as a Legic Reader
318 static uint32_t perform_setup_phase_rwd(int iv) {
319 /* Switch on carrier and let the tag charge for 1ms */
320 AT91C_BASE_PIOA->PIO_SODR = GPIO_SSC_DOUT;
321 SpinDelay(20); // was 1ms before.
322
323 /* no keystream yet */
324 legic_prng_init(0);
325
326 // IV
327 frame_send_rwd(iv, 7);
328 legic_prng_init(iv);
329
330 frame_clean(&current_frame);
331 frame_receive_rwd(&current_frame, 6, 1);
332
333 // we wait anyways
334 legic_prng_forward(3);
335
336 WAIT_387
337
338 frame_send_rwd(0x39, 6);
339
340 return current_frame.data;
341 }
342
343 static void LegicCommonInit(void) {
344
345 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
346 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
347 FpgaSetupSsc();
348 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX);
349
350 /* Bitbang the transmitter */
351 AT91C_BASE_PIOA->PIO_CODR = GPIO_SSC_DOUT;
352 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
353 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
354
355 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
356 cardmem = BigBuf_malloc(LEGIC_CARD_MEMSIZE);
357 memset(cardmem, 0x00, LEGIC_CARD_MEMSIZE);
358
359 clear_trace();
360 set_tracing(TRUE);
361
362 setup_timer();
363
364 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
365 }
366
367 /* Switch off carrier, make sure tag is reset */
368 static void switch_off_tag_rwd(void) {
369 AT91C_BASE_PIOA->PIO_CODR = GPIO_SSC_DOUT;
370 SpinDelay(10);
371 WDT_HIT();
372 }
373
374 /* calculate crc for a legic command */
375 static int LegicCRC(int byte_index, int value, int cmd_sz) {
376 crc_clear(&legic_crc);
377 crc_update(&legic_crc, 1, 1); /* CMD_READ */
378 crc_update(&legic_crc, byte_index, cmd_sz-1);
379 crc_update(&legic_crc, value, 8);
380 return crc_finish(&legic_crc);
381 }
382
383 int legic_read_byte(int byte_index, int cmd_sz) {
384
385 int byte = 0, calcCrc = 0, crc = 0;
386 int cmd = 1 | (byte_index << 1);
387
388 uint8_t cmdbytes[2] = {cmd && 0xff, (cmd >> 8 ) & 0xFF};
389 uint32_t starttime = timer->TC_CV, endtime = 0;
390
391 WAIT_387
392
393 // send
394 frame_send_rwd(cmd, cmd_sz);
395
396 // log
397 endtime = timer->TC_CV;
398 LogTrace(cmdbytes, 2, starttime, endtime, NULL, TRUE);
399
400 // clean
401 frame_clean(&current_frame);
402
403 starttime = timer->TC_CV;
404
405 // read
406 frame_receive_rwd(&current_frame, 12, 1);
407
408 // log
409 endtime = timer->TC_CV;
410 cmdbytes[0] = current_frame.data & 0xff;
411 cmdbytes[1] = (current_frame.data >> 8) & 0xFF;
412 LogTrace(cmdbytes, 2, starttime, endtime, NULL, FALSE);
413
414 byte = current_frame.data & 0xff;
415 calcCrc = LegicCRC(byte_index, byte, cmd_sz);
416 crc = (current_frame.data >> 8);
417
418 if( calcCrc != crc ) {
419 Dbprintf("!!! crc mismatch: expected %x but got %x !!!", calcCrc, crc);
420 return -1;
421 }
422
423 // we wait anyways
424 legic_prng_forward(4);
425 return byte;
426 }
427
428 /*
429 * - assemble a write_cmd_frame with crc and send it
430 * - wait until the tag sends back an ACK ('1' bit unencrypted)
431 * - forward the prng based on the timing
432 */
433 //int legic_write_byte(int byte, int addr, int addr_sz, int PrngCorrection) {
434 int legic_write_byte(int byte, int addr, int addr_sz) {
435
436 //do not write UID, CRC at offset 0-4.
437 if(addr <= 0x04) return 0;
438
439 // crc
440 crc_clear(&legic_crc);
441 crc_update(&legic_crc, 0, 1); /* CMD_WRITE */
442 crc_update(&legic_crc, addr, addr_sz);
443 crc_update(&legic_crc, byte, 8);
444 uint32_t crc = crc_finish(&legic_crc);
445
446 // send write command
447 uint32_t cmd = ((crc <<(addr_sz+1+8)) //CRC
448 |(byte <<(addr_sz+1)) //Data
449 |(addr <<1) //Address
450 |(0x00 <<0)); //CMD = W
451 uint32_t cmd_sz = addr_sz+1+8+4; //crc+data+cmd
452
453 legic_prng_forward(2); /* we wait anyways */
454
455 while(timer->TC_CV < 387) ; /* ~ 258us */
456
457 frame_send_rwd(cmd, cmd_sz);
458
459 // wllm-rbnt doesnt have these
460 // AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_DIN;
461 // AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DIN;
462
463 // wait for ack
464 int t, old_level = 0, edges = 0;
465 int next_bit_at = 0;
466
467 while(timer->TC_CV < 387) ; /* ~ 258us */
468
469 for( t = 0; t < 80; t++) {
470 edges = 0;
471 next_bit_at += TAG_TIME_BIT;
472 while(timer->TC_CV < next_bit_at) {
473 int level = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
474 if(level != old_level) {
475 edges++;
476 }
477 old_level = level;
478 }
479 if(edges > 20 && edges < 60) { /* expected are 42 edges */
480 int t = timer->TC_CV;
481 int c = t / TAG_TIME_BIT;
482
483 ResetClock();
484 legic_prng_forward(c);
485 return 0;
486 }
487 }
488
489 ResetClock();
490 return -1;
491 }
492
493 int LegicRfReader(int offset, int bytes, int iv) {
494
495 // ice_legic_setup();
496 // ice_legic_select_card();
497 // return 0;
498
499 int byte_index = 0, cmd_sz = 0, card_sz = 0;
500
501 iv = (iv <= 0 ) ? SESSION_IV : iv;
502
503 LegicCommonInit();
504
505 if ( MF_DBGLEVEL >= 2) DbpString("setting up legic card");
506
507 uint32_t tag_type = perform_setup_phase_rwd(iv);
508
509 //we lose to mutch time with dprintf
510 switch_off_tag_rwd();
511
512 switch(tag_type) {
513 case 0x0d:
514 if ( MF_DBGLEVEL >= 2) DbpString("MIM22 card found, reading card ...");
515 cmd_sz = 6;
516 card_sz = 22;
517 break;
518 case 0x1d:
519 if ( MF_DBGLEVEL >= 2) DbpString("MIM256 card found, reading card ...");
520 cmd_sz = 9;
521 card_sz = 256;
522 break;
523 case 0x3d:
524 if ( MF_DBGLEVEL >= 2) DbpString("MIM1024 card found, reading card ...");
525 cmd_sz = 11;
526 card_sz = 1024;
527 break;
528 default:
529 if ( MF_DBGLEVEL >= 1) Dbprintf("Unknown card format: %x",tag_type);
530 return -1;
531 }
532 if(bytes == -1)
533 bytes = card_sz;
534
535 if(bytes+offset >= card_sz)
536 bytes = card_sz - offset;
537
538 perform_setup_phase_rwd(iv);
539
540 legic_prng_forward(2);
541
542 LED_B_ON();
543 while(byte_index < bytes) {
544 int r = legic_read_byte(byte_index+offset, cmd_sz);
545 if(r == -1 || BUTTON_PRESS()) {
546 switch_off_tag_rwd();
547 LEDsoff();
548 if ( MF_DBGLEVEL >= 2) DbpString("operation aborted");
549 return -1;
550 }
551 cardmem[byte_index] = r;
552 WDT_HIT();
553 byte_index++;
554 }
555
556 switch_off_tag_rwd();
557 LEDsoff();
558
559 if ( MF_DBGLEVEL >= 1) Dbprintf("Card read, use 'hf legic decode' or");
560 if ( MF_DBGLEVEL >= 1) Dbprintf("'data hexsamples %d' to view results", (bytes+7) & ~7);
561 return 0;
562 }
563
564 /*int _LegicRfWriter(int offset, int bytes, int addr_sz, uint8_t *BigBuf, int RoundBruteforceValue) {
565 int byte_index=0;
566
567 LED_B_ON();
568 perform_setup_phase_rwd(SESSION_IV);
569 //legic_prng_forward(2);
570 while(byte_index < bytes) {
571 int r;
572
573 //check if the DCF should be changed
574 if ( (offset == 0x05) && (bytes == 0x02) ) {
575 //write DCF in reverse order (addr 0x06 before 0x05)
576 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
577 //legic_prng_forward(1);
578 if(r == 0) {
579 byte_index++;
580 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
581 }
582 //legic_prng_forward(1);
583 }
584 else {
585 r = legic_write_byte(BigBuf[byte_index+offset], byte_index+offset, addr_sz, RoundBruteforceValue);
586 }
587 if((r != 0) || BUTTON_PRESS()) {
588 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
589 switch_off_tag_rwd();
590 LED_B_OFF();
591 LED_C_OFF();
592 return -1;
593 }
594
595 WDT_HIT();
596 byte_index++;
597 if(byte_index & 0x10) LED_C_ON(); else LED_C_OFF();
598 }
599 LED_B_OFF();
600 LED_C_OFF();
601 DbpString("write successful");
602 return 0;
603 }*/
604
605 void LegicRfWriter(int offset, int bytes, int iv) {
606
607 int byte_index = 0, addr_sz = 0;
608
609 iv = (iv <=0 ) ? SESSION_IV : iv;
610
611 LegicCommonInit();
612
613 if ( MF_DBGLEVEL >= 2) DbpString("setting up legic card");
614
615 uint32_t tag_type = perform_setup_phase_rwd(iv);
616
617 switch_off_tag_rwd();
618
619 switch(tag_type) {
620 case 0x0d:
621 if(offset+bytes > 22) {
622 Dbprintf("Error: can not write to 0x%03.3x on MIM22", offset+bytes);
623 return;
624 }
625 addr_sz = 5;
626 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM22 card found, writing 0x%02.2x - 0x%02.2x ...", offset, offset+bytes);
627 break;
628 case 0x1d:
629 if(offset+bytes > 0x100) {
630 Dbprintf("Error: can not write to 0x%03.3x on MIM256", offset+bytes);
631 return;
632 }
633 addr_sz = 8;
634 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM256 card found, writing 0x%02.2x - 0x%02.2x ...", offset, offset+bytes);
635 break;
636 case 0x3d:
637 if(offset+bytes > 0x400) {
638 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", offset+bytes);
639 return;
640 }
641 addr_sz = 10;
642 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM1024 card found, writing 0x%03.3x - 0x%03.3x ...", offset, offset+bytes);
643 break;
644 default:
645 Dbprintf("No or unknown card found, aborting");
646 return;
647 }
648
649 LED_B_ON();
650 perform_setup_phase_rwd(iv);
651 while(byte_index < bytes) {
652 int r;
653
654 //check if the DCF should be changed
655 if ( ((byte_index+offset) == 0x05) && (bytes >= 0x02) ) {
656 //write DCF in reverse order (addr 0x06 before 0x05)
657 r = legic_write_byte(cardmem[(0x06-byte_index)], (0x06-byte_index), addr_sz);
658
659 // write second byte on success...
660 if(r == 0) {
661 byte_index++;
662 r = legic_write_byte(cardmem[(0x06-byte_index)], (0x06-byte_index), addr_sz);
663 }
664 }
665 else {
666 r = legic_write_byte(cardmem[byte_index+offset], byte_index+offset, addr_sz);
667 }
668
669 if((r != 0) || BUTTON_PRESS()) {
670 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
671 switch_off_tag_rwd();
672 LEDsoff();
673 return;
674 }
675
676 WDT_HIT();
677 byte_index++;
678 }
679 LEDsoff();
680 if ( MF_DBGLEVEL >= 1) DbpString("write successful");
681 }
682
683 void LegicRfRawWriter(int address, int byte, int iv) {
684
685 int byte_index = 0, addr_sz = 0;
686
687 iv = (iv <= 0) ? SESSION_IV : iv;
688
689 LegicCommonInit();
690
691 if ( MF_DBGLEVEL >= 2) DbpString("setting up legic card");
692
693 uint32_t tag_type = perform_setup_phase_rwd(iv);
694
695 switch_off_tag_rwd();
696
697 switch(tag_type) {
698 case 0x0d:
699 if(address > 22) {
700 Dbprintf("Error: can not write to 0x%03.3x on MIM22", address);
701 return;
702 }
703 addr_sz = 5;
704 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM22 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address, byte);
705 break;
706 case 0x1d:
707 if(address > 0x100) {
708 Dbprintf("Error: can not write to 0x%03.3x on MIM256", address);
709 return;
710 }
711 addr_sz = 8;
712 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM256 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address, byte);
713 break;
714 case 0x3d:
715 if(address > 0x400) {
716 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", address);
717 return;
718 }
719 addr_sz = 10;
720 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM1024 card found, writing at addr 0x%03.3x - value 0x%03.3x ...", address, byte);
721 break;
722 default:
723 Dbprintf("No or unknown card found, aborting");
724 return;
725 }
726
727 Dbprintf("integer value: %d address: %d addr_sz: %d", byte, address, addr_sz);
728 LED_B_ON();
729
730 perform_setup_phase_rwd(iv);
731 //legic_prng_forward(2);
732
733 int r = legic_write_byte(byte, address, addr_sz);
734
735 if((r != 0) || BUTTON_PRESS()) {
736 Dbprintf("operation aborted @ 0x%03.3x (%1d)", byte_index, r);
737 switch_off_tag_rwd();
738 LEDsoff();
739 return;
740 }
741
742 LEDsoff();
743 if ( MF_DBGLEVEL >= 1) DbpString("write successful");
744 }
745
746 /* Handle (whether to respond) a frame in tag mode
747 * Only called when simulating a tag.
748 */
749 static void frame_handle_tag(struct legic_frame const * const f)
750 {
751 uint8_t *BigBuf = BigBuf_get_addr();
752
753 /* First Part of Handshake (IV) */
754 if(f->bits == 7) {
755
756 LED_C_ON();
757
758 prng_timer->TC_CCR = AT91C_TC_SWTRG;
759 while(prng_timer->TC_CV > 1) ;
760
761 legic_prng_init(f->data);
762 frame_send_tag(0x3d, 6, 1); /* 0x3d^0x26 = 0x1b */
763 legic_state = STATE_IV;
764 legic_read_count = 0;
765 legic_prng_bc = 0;
766 legic_prng_iv = f->data;
767
768 /* TIMEOUT */
769 ResetClock();
770
771 //while(timer->TC_CV < 280);
772 WAIT(280)
773 return;
774 }
775
776 /* 0x19==??? */
777 if(legic_state == STATE_IV) {
778 int local_key = get_key_stream(3, 6);
779 int xored = 0x39 ^ local_key;
780 if((f->bits == 6) && (f->data == xored)) {
781 legic_state = STATE_CON;
782
783 /* TIMEOUT */
784 ResetClock();
785
786 //while(timer->TC_CV < 200);
787 WAIT(200)
788
789 return;
790 } else {
791 legic_state = STATE_DISCON;
792 LED_C_OFF();
793 Dbprintf("iv: %02x frame: %02x key: %02x xored: %02x", legic_prng_iv, f->data, local_key, xored);
794 return;
795 }
796 }
797
798 /* Read */
799 if(f->bits == 11) {
800 if(legic_state == STATE_CON) {
801 int key = get_key_stream(2, 11); //legic_phase_drift, 11);
802 int addr = f->data ^ key; addr = addr >> 1;
803 int data = BigBuf[addr];
804 int hash = LegicCRC(addr, data, 11) << 8;
805 BigBuf[OFFSET_LOG+legic_read_count] = (uint8_t)addr;
806 legic_read_count++;
807
808 //Dbprintf("Data:%03.3x, key:%03.3x, addr: %03.3x, read_c:%u", f->data, key, addr, read_c);
809 legic_prng_forward(legic_reqresp_drift);
810
811 frame_send_tag(hash | data, 12, 1);
812
813 /* TIMEOUT */
814 ResetClock();
815
816 legic_prng_forward(2);
817 //while(timer->TC_CV < 180);
818 WAIT(180)
819
820 return;
821 }
822 }
823
824 /* Write */
825 if(f->bits == 23) {
826 int key = get_key_stream(-1, 23); //legic_frame_drift, 23);
827 int addr = f->data ^ key; addr = addr >> 1; addr = addr & 0x3ff;
828 int data = f->data ^ key; data = data >> 11; data = data & 0xff;
829
830 /* write command */
831 legic_state = STATE_DISCON;
832 LED_C_OFF();
833 Dbprintf("write - addr: %x, data: %x", addr, data);
834 return;
835 }
836
837 if(legic_state != STATE_DISCON) {
838 Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f->bits, f->data, legic_state, legic_read_count);
839 int i;
840 Dbprintf("IV: %03.3x", legic_prng_iv);
841 for(i = 0; i<legic_read_count; i++) {
842 Dbprintf("Read Nb: %u, Addr: %u", i, BigBuf[OFFSET_LOG+i]);
843 }
844
845 for(i = -1; i<legic_read_count; i++) {
846 uint32_t t;
847 t = BigBuf[OFFSET_LOG+256+i*4];
848 t |= BigBuf[OFFSET_LOG+256+i*4+1] << 8;
849 t |= BigBuf[OFFSET_LOG+256+i*4+2] <<16;
850 t |= BigBuf[OFFSET_LOG+256+i*4+3] <<24;
851
852 Dbprintf("Cycles: %u, Frame Length: %u, Time: %u",
853 BigBuf[OFFSET_LOG+128+i],
854 BigBuf[OFFSET_LOG+384+i],
855 t);
856 }
857 }
858 legic_state = STATE_DISCON;
859 legic_read_count = 0;
860 SpinDelay(10);
861 LED_C_OFF();
862 return;
863 }
864
865 /* Read bit by bit untill full frame is received
866 * Call to process frame end answer
867 */
868 static void emit(int bit) {
869
870 switch (bit) {
871 case 1:
872 frame_append_bit(&current_frame, 1);
873 break;
874 case 0:
875 frame_append_bit(&current_frame, 0);
876 break;
877 default:
878 if(current_frame.bits <= 4) {
879 frame_clean(&current_frame);
880 } else {
881 frame_handle_tag(&current_frame);
882 frame_clean(&current_frame);
883 }
884 WDT_HIT();
885 break;
886 }
887 }
888
889 void LegicRfSimulate(int phase, int frame, int reqresp)
890 {
891 /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,
892 * modulation mode set to 212kHz subcarrier. We are getting the incoming raw
893 * envelope waveform on DIN and should send our response on DOUT.
894 *
895 * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll
896 * measure the time between two rising edges on DIN, and no encoding on the
897 * subcarrier from card to reader, so we'll just shift out our verbatim data
898 * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear,
899 * seems to be 300us-ish.
900 */
901
902 legic_phase_drift = phase;
903 legic_frame_drift = frame;
904 legic_reqresp_drift = reqresp;
905
906 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
907 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
908 FpgaSetupSsc();
909 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_212K);
910
911 /* Bitbang the receiver */
912 AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_DIN;
913 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DIN;
914
915 setup_timer();
916 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
917
918 int old_level = 0;
919 int active = 0;
920 legic_state = STATE_DISCON;
921
922 LED_B_ON();
923 DbpString("Starting Legic emulator, press button to end");
924
925 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
926 int level = !!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
927 int time = timer->TC_CV;
928
929 if(level != old_level) {
930 if(level == 1) {
931 timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
932
933 if (FUZZ_EQUAL(time, RWD_TIME_1, RWD_TIME_FUZZ)) {
934 /* 1 bit */
935 emit(1);
936 active = 1;
937 LED_A_ON();
938 } else if (FUZZ_EQUAL(time, RWD_TIME_0, RWD_TIME_FUZZ)) {
939 /* 0 bit */
940 emit(0);
941 active = 1;
942 LED_A_ON();
943 } else if (active) {
944 /* invalid */
945 emit(-1);
946 active = 0;
947 LED_A_OFF();
948 }
949 }
950 }
951
952 /* Frame end */
953 if(time >= (RWD_TIME_1+RWD_TIME_FUZZ) && active) {
954 emit(-1);
955 active = 0;
956 LED_A_OFF();
957 }
958
959 if(time >= (20*RWD_TIME_1) && (timer->TC_SR & AT91C_TC_CLKSTA)) {
960 timer->TC_CCR = AT91C_TC_CLKDIS;
961 }
962
963 old_level = level;
964 WDT_HIT();
965 }
966 if ( MF_DBGLEVEL >= 1) DbpString("Stopped");
967 LEDsoff();
968 }
969
970 //-----------------------------------------------------------------------------
971 //-----------------------------------------------------------------------------
972
973
974 //-----------------------------------------------------------------------------
975 // Code up a string of octets at layer 2 (including CRC, we don't generate
976 // that here) so that they can be transmitted to the reader. Doesn't transmit
977 // them yet, just leaves them ready to send in ToSend[].
978 //-----------------------------------------------------------------------------
979 // static void CodeLegicAsTag(const uint8_t *cmd, int len)
980 // {
981 // int i;
982
983 // ToSendReset();
984
985 // // Transmit a burst of ones, as the initial thing that lets the
986 // // reader get phase sync. This (TR1) must be > 80/fs, per spec,
987 // // but tag that I've tried (a Paypass) exceeds that by a fair bit,
988 // // so I will too.
989 // for(i = 0; i < 20; i++) {
990 // ToSendStuffBit(1);
991 // ToSendStuffBit(1);
992 // ToSendStuffBit(1);
993 // ToSendStuffBit(1);
994 // }
995
996 // // Send SOF.
997 // for(i = 0; i < 10; i++) {
998 // ToSendStuffBit(0);
999 // ToSendStuffBit(0);
1000 // ToSendStuffBit(0);
1001 // ToSendStuffBit(0);
1002 // }
1003 // for(i = 0; i < 2; i++) {
1004 // ToSendStuffBit(1);
1005 // ToSendStuffBit(1);
1006 // ToSendStuffBit(1);
1007 // ToSendStuffBit(1);
1008 // }
1009
1010 // for(i = 0; i < len; i++) {
1011 // int j;
1012 // uint8_t b = cmd[i];
1013
1014 // // Start bit
1015 // ToSendStuffBit(0);
1016 // ToSendStuffBit(0);
1017 // ToSendStuffBit(0);
1018 // ToSendStuffBit(0);
1019
1020 // // Data bits
1021 // for(j = 0; j < 8; j++) {
1022 // if(b & 1) {
1023 // ToSendStuffBit(1);
1024 // ToSendStuffBit(1);
1025 // ToSendStuffBit(1);
1026 // ToSendStuffBit(1);
1027 // } else {
1028 // ToSendStuffBit(0);
1029 // ToSendStuffBit(0);
1030 // ToSendStuffBit(0);
1031 // ToSendStuffBit(0);
1032 // }
1033 // b >>= 1;
1034 // }
1035
1036 // // Stop bit
1037 // ToSendStuffBit(1);
1038 // ToSendStuffBit(1);
1039 // ToSendStuffBit(1);
1040 // ToSendStuffBit(1);
1041 // }
1042
1043 // // Send EOF.
1044 // for(i = 0; i < 10; i++) {
1045 // ToSendStuffBit(0);
1046 // ToSendStuffBit(0);
1047 // ToSendStuffBit(0);
1048 // ToSendStuffBit(0);
1049 // }
1050 // for(i = 0; i < 2; i++) {
1051 // ToSendStuffBit(1);
1052 // ToSendStuffBit(1);
1053 // ToSendStuffBit(1);
1054 // ToSendStuffBit(1);
1055 // }
1056
1057 // // Convert from last byte pos to length
1058 // ToSendMax++;
1059 // }
1060
1061 //-----------------------------------------------------------------------------
1062 // The software UART that receives commands from the reader, and its state
1063 // variables.
1064 //-----------------------------------------------------------------------------
1065 static struct {
1066 enum {
1067 STATE_UNSYNCD,
1068 STATE_GOT_FALLING_EDGE_OF_SOF,
1069 STATE_AWAITING_START_BIT,
1070 STATE_RECEIVING_DATA
1071 } state;
1072 uint16_t shiftReg;
1073 int bitCnt;
1074 int byteCnt;
1075 int byteCntMax;
1076 int posCnt;
1077 uint8_t *output;
1078 } Uart;
1079
1080 /* Receive & handle a bit coming from the reader.
1081 *
1082 * This function is called 4 times per bit (every 2 subcarrier cycles).
1083 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1084 *
1085 * LED handling:
1086 * LED A -> ON once we have received the SOF and are expecting the rest.
1087 * LED A -> OFF once we have received EOF or are in error state or unsynced
1088 *
1089 * Returns: true if we received a EOF
1090 * false if we are still waiting for some more
1091 */
1092 // static RAMFUNC int HandleLegicUartBit(uint8_t bit)
1093 // {
1094 // switch(Uart.state) {
1095 // case STATE_UNSYNCD:
1096 // if(!bit) {
1097 // // we went low, so this could be the beginning of an SOF
1098 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
1099 // Uart.posCnt = 0;
1100 // Uart.bitCnt = 0;
1101 // }
1102 // break;
1103
1104 // case STATE_GOT_FALLING_EDGE_OF_SOF:
1105 // Uart.posCnt++;
1106 // if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
1107 // if(bit) {
1108 // if(Uart.bitCnt > 9) {
1109 // // we've seen enough consecutive
1110 // // zeros that it's a valid SOF
1111 // Uart.posCnt = 0;
1112 // Uart.byteCnt = 0;
1113 // Uart.state = STATE_AWAITING_START_BIT;
1114 // LED_A_ON(); // Indicate we got a valid SOF
1115 // } else {
1116 // // didn't stay down long enough
1117 // // before going high, error
1118 // Uart.state = STATE_UNSYNCD;
1119 // }
1120 // } else {
1121 // // do nothing, keep waiting
1122 // }
1123 // Uart.bitCnt++;
1124 // }
1125 // if(Uart.posCnt >= 4) Uart.posCnt = 0;
1126 // if(Uart.bitCnt > 12) {
1127 // // Give up if we see too many zeros without
1128 // // a one, too.
1129 // LED_A_OFF();
1130 // Uart.state = STATE_UNSYNCD;
1131 // }
1132 // break;
1133
1134 // case STATE_AWAITING_START_BIT:
1135 // Uart.posCnt++;
1136 // if(bit) {
1137 // if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
1138 // // stayed high for too long between
1139 // // characters, error
1140 // Uart.state = STATE_UNSYNCD;
1141 // }
1142 // } else {
1143 // // falling edge, this starts the data byte
1144 // Uart.posCnt = 0;
1145 // Uart.bitCnt = 0;
1146 // Uart.shiftReg = 0;
1147 // Uart.state = STATE_RECEIVING_DATA;
1148 // }
1149 // break;
1150
1151 // case STATE_RECEIVING_DATA:
1152 // Uart.posCnt++;
1153 // if(Uart.posCnt == 2) {
1154 // // time to sample a bit
1155 // Uart.shiftReg >>= 1;
1156 // if(bit) {
1157 // Uart.shiftReg |= 0x200;
1158 // }
1159 // Uart.bitCnt++;
1160 // }
1161 // if(Uart.posCnt >= 4) {
1162 // Uart.posCnt = 0;
1163 // }
1164 // if(Uart.bitCnt == 10) {
1165 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
1166 // {
1167 // // this is a data byte, with correct
1168 // // start and stop bits
1169 // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
1170 // Uart.byteCnt++;
1171
1172 // if(Uart.byteCnt >= Uart.byteCntMax) {
1173 // // Buffer overflowed, give up
1174 // LED_A_OFF();
1175 // Uart.state = STATE_UNSYNCD;
1176 // } else {
1177 // // so get the next byte now
1178 // Uart.posCnt = 0;
1179 // Uart.state = STATE_AWAITING_START_BIT;
1180 // }
1181 // } else if (Uart.shiftReg == 0x000) {
1182 // // this is an EOF byte
1183 // LED_A_OFF(); // Finished receiving
1184 // Uart.state = STATE_UNSYNCD;
1185 // if (Uart.byteCnt != 0) {
1186 // return TRUE;
1187 // }
1188 // } else {
1189 // // this is an error
1190 // LED_A_OFF();
1191 // Uart.state = STATE_UNSYNCD;
1192 // }
1193 // }
1194 // break;
1195
1196 // default:
1197 // LED_A_OFF();
1198 // Uart.state = STATE_UNSYNCD;
1199 // break;
1200 // }
1201
1202 // return FALSE;
1203 // }
1204
1205
1206 static void UartReset()
1207 {
1208 Uart.byteCntMax = MAX_FRAME_SIZE;
1209 Uart.state = STATE_UNSYNCD;
1210 Uart.byteCnt = 0;
1211 Uart.bitCnt = 0;
1212 Uart.posCnt = 0;
1213 memset(Uart.output, 0x00, MAX_FRAME_SIZE);
1214 }
1215
1216 // static void UartInit(uint8_t *data)
1217 // {
1218 // Uart.output = data;
1219 // UartReset();
1220 // }
1221
1222 //=============================================================================
1223 // An LEGIC reader. We take layer two commands, code them
1224 // appropriately, and then send them to the tag. We then listen for the
1225 // tag's response, which we leave in the buffer to be demodulated on the
1226 // PC side.
1227 //=============================================================================
1228
1229 static struct {
1230 enum {
1231 DEMOD_UNSYNCD,
1232 DEMOD_PHASE_REF_TRAINING,
1233 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
1234 DEMOD_GOT_FALLING_EDGE_OF_SOF,
1235 DEMOD_AWAITING_START_BIT,
1236 DEMOD_RECEIVING_DATA
1237 } state;
1238 int bitCount;
1239 int posCount;
1240 int thisBit;
1241 uint16_t shiftReg;
1242 uint8_t *output;
1243 int len;
1244 int sumI;
1245 int sumQ;
1246 } Demod;
1247
1248 /*
1249 * Handles reception of a bit from the tag
1250 *
1251 * This function is called 2 times per bit (every 4 subcarrier cycles).
1252 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1253 *
1254 * LED handling:
1255 * LED C -> ON once we have received the SOF and are expecting the rest.
1256 * LED C -> OFF once we have received EOF or are unsynced
1257 *
1258 * Returns: true if we received a EOF
1259 * false if we are still waiting for some more
1260 *
1261 */
1262
1263 #ifndef SUBCARRIER_DETECT_THRESHOLD
1264 # define SUBCARRIER_DETECT_THRESHOLD 8
1265 #endif
1266
1267 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
1268 #ifndef CHECK_FOR_SUBCARRIER
1269 # define CHECK_FOR_SUBCARRIER() { v = MAX(ai, aq) + MIN(halfci, halfcq); }
1270 #endif
1271
1272 // The soft decision on the bit uses an estimate of just the
1273 // quadrant of the reference angle, not the exact angle.
1274 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
1275 #define MAKE_SOFT_DECISION() { \
1276 if(Demod.sumI > 0) \
1277 v = ci; \
1278 else \
1279 v = -ci; \
1280 \
1281 if(Demod.sumQ > 0) \
1282 v += cq; \
1283 else \
1284 v -= cq; \
1285 \
1286 }
1287
1288 static RAMFUNC int HandleLegicSamplesDemod(int ci, int cq)
1289 {
1290 int v = 0;
1291 int ai = ABS(ci);
1292 int aq = ABS(cq);
1293 int halfci = (ai >> 1);
1294 int halfcq = (aq >> 1);
1295
1296 switch(Demod.state) {
1297 case DEMOD_UNSYNCD:
1298
1299 CHECK_FOR_SUBCARRIER()
1300
1301 if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
1302 Demod.state = DEMOD_PHASE_REF_TRAINING;
1303 Demod.sumI = ci;
1304 Demod.sumQ = cq;
1305 Demod.posCount = 1;
1306 }
1307 break;
1308
1309 case DEMOD_PHASE_REF_TRAINING:
1310 if(Demod.posCount < 8) {
1311
1312 CHECK_FOR_SUBCARRIER()
1313
1314 if (v > SUBCARRIER_DETECT_THRESHOLD) {
1315 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
1316 // note: synchronization time > 80 1/fs
1317 Demod.sumI += ci;
1318 Demod.sumQ += cq;
1319 ++Demod.posCount;
1320 } else {
1321 // subcarrier lost
1322 Demod.state = DEMOD_UNSYNCD;
1323 }
1324 } else {
1325 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
1326 }
1327 break;
1328
1329 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
1330
1331 MAKE_SOFT_DECISION()
1332
1333 //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq );
1334 // logic '0' detected
1335 if (v <= 0) {
1336
1337 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
1338
1339 // start of SOF sequence
1340 Demod.posCount = 0;
1341 } else {
1342 // maximum length of TR1 = 200 1/fs
1343 if(Demod.posCount > 25*2) Demod.state = DEMOD_UNSYNCD;
1344 }
1345 ++Demod.posCount;
1346 break;
1347
1348 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
1349 ++Demod.posCount;
1350
1351 MAKE_SOFT_DECISION()
1352
1353 if(v > 0) {
1354 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1355 if(Demod.posCount < 10*2) {
1356 Demod.state = DEMOD_UNSYNCD;
1357 } else {
1358 LED_C_ON(); // Got SOF
1359 Demod.state = DEMOD_AWAITING_START_BIT;
1360 Demod.posCount = 0;
1361 Demod.len = 0;
1362 }
1363 } else {
1364 // low phase of SOF too long (> 12 etu)
1365 if(Demod.posCount > 13*2) {
1366 Demod.state = DEMOD_UNSYNCD;
1367 LED_C_OFF();
1368 }
1369 }
1370 break;
1371
1372 case DEMOD_AWAITING_START_BIT:
1373 ++Demod.posCount;
1374
1375 MAKE_SOFT_DECISION()
1376
1377 if(v > 0) {
1378 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1379 if(Demod.posCount > 3*2) {
1380 Demod.state = DEMOD_UNSYNCD;
1381 LED_C_OFF();
1382 }
1383 } else {
1384 // start bit detected
1385 Demod.bitCount = 0;
1386 Demod.posCount = 1; // this was the first half
1387 Demod.thisBit = v;
1388 Demod.shiftReg = 0;
1389 Demod.state = DEMOD_RECEIVING_DATA;
1390 }
1391 break;
1392
1393 case DEMOD_RECEIVING_DATA:
1394
1395 MAKE_SOFT_DECISION()
1396
1397 if(Demod.posCount == 0) {
1398 // first half of bit
1399 Demod.thisBit = v;
1400 Demod.posCount = 1;
1401 } else {
1402 // second half of bit
1403 Demod.thisBit += v;
1404 Demod.shiftReg >>= 1;
1405 // logic '1'
1406 if(Demod.thisBit > 0)
1407 Demod.shiftReg |= 0x200;
1408
1409 ++Demod.bitCount;
1410
1411 if(Demod.bitCount == 10) {
1412
1413 uint16_t s = Demod.shiftReg;
1414
1415 if((s & 0x200) && !(s & 0x001)) {
1416 // stop bit == '1', start bit == '0'
1417 uint8_t b = (s >> 1);
1418 Demod.output[Demod.len] = b;
1419 ++Demod.len;
1420 Demod.state = DEMOD_AWAITING_START_BIT;
1421 } else {
1422 Demod.state = DEMOD_UNSYNCD;
1423 LED_C_OFF();
1424
1425 if(s == 0x000) {
1426 // This is EOF (start, stop and all data bits == '0'
1427 return TRUE;
1428 }
1429 }
1430 }
1431 Demod.posCount = 0;
1432 }
1433 break;
1434
1435 default:
1436 Demod.state = DEMOD_UNSYNCD;
1437 LED_C_OFF();
1438 break;
1439 }
1440 return FALSE;
1441 }
1442
1443 // Clear out the state of the "UART" that receives from the tag.
1444 static void DemodReset() {
1445 Demod.len = 0;
1446 Demod.state = DEMOD_UNSYNCD;
1447 Demod.posCount = 0;
1448 Demod.sumI = 0;
1449 Demod.sumQ = 0;
1450 Demod.bitCount = 0;
1451 Demod.thisBit = 0;
1452 Demod.shiftReg = 0;
1453 memset(Demod.output, 0x00, MAX_FRAME_SIZE);
1454 }
1455
1456 static void DemodInit(uint8_t *data) {
1457 Demod.output = data;
1458 DemodReset();
1459 }
1460
1461 /*
1462 * Demodulate the samples we received from the tag, also log to tracebuffer
1463 * quiet: set to 'TRUE' to disable debug output
1464 */
1465 #define LEGIC_DMA_BUFFER_SIZE 256
1466 static void GetSamplesForLegicDemod(int n, bool quiet)
1467 {
1468 int max = 0;
1469 bool gotFrame = FALSE;
1470 int lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1471 int ci, cq, samples = 0;
1472
1473 BigBuf_free();
1474
1475 // And put the FPGA in the appropriate mode
1476 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
1477
1478 // The response (tag -> reader) that we're receiving.
1479 // Set up the demodulator for tag -> reader responses.
1480 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1481
1482 // The DMA buffer, used to stream samples from the FPGA
1483 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE);
1484 int8_t *upTo = dmaBuf;
1485
1486 // Setup and start DMA.
1487 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, LEGIC_DMA_BUFFER_SIZE) ){
1488 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1489 return;
1490 }
1491
1492 // Signal field is ON with the appropriate LED:
1493 LED_D_ON();
1494 for(;;) {
1495 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
1496 if(behindBy > max) max = behindBy;
1497
1498 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (LEGIC_DMA_BUFFER_SIZE-1)) > 2) {
1499 ci = upTo[0];
1500 cq = upTo[1];
1501 upTo += 2;
1502 if(upTo >= dmaBuf + LEGIC_DMA_BUFFER_SIZE) {
1503 upTo = dmaBuf;
1504 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
1505 AT91C_BASE_PDC_SSC->PDC_RNCR = LEGIC_DMA_BUFFER_SIZE;
1506 }
1507 lastRxCounter -= 2;
1508 if(lastRxCounter <= 0)
1509 lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1510
1511 samples += 2;
1512
1513 gotFrame = HandleLegicSamplesDemod(ci , cq );
1514 if ( gotFrame )
1515 break;
1516 }
1517
1518 if(samples > n || gotFrame)
1519 break;
1520 }
1521
1522 FpgaDisableSscDma();
1523
1524 if (!quiet && Demod.len == 0) {
1525 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d",
1526 max,
1527 samples,
1528 gotFrame,
1529 Demod.len,
1530 Demod.sumI,
1531 Demod.sumQ
1532 );
1533 }
1534
1535 //Tracing
1536 if (Demod.len > 0) {
1537 uint8_t parity[MAX_PARITY_SIZE] = {0x00};
1538 LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE);
1539 }
1540 }
1541 //-----------------------------------------------------------------------------
1542 // Transmit the command (to the tag) that was placed in ToSend[].
1543 //-----------------------------------------------------------------------------
1544 static void TransmitForLegic(void)
1545 {
1546 int c;
1547
1548 FpgaSetupSsc();
1549
1550 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))
1551 AT91C_BASE_SSC->SSC_THR = 0xff;
1552
1553 // Signal field is ON with the appropriate Red LED
1554 LED_D_ON();
1555
1556 // Signal we are transmitting with the Green LED
1557 LED_B_ON();
1558 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1559
1560 for(c = 0; c < 10;) {
1561 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1562 AT91C_BASE_SSC->SSC_THR = 0xff;
1563 c++;
1564 }
1565 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1566 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1567 (void)r;
1568 }
1569 WDT_HIT();
1570 }
1571
1572 c = 0;
1573 for(;;) {
1574 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1575 AT91C_BASE_SSC->SSC_THR = ToSend[c];
1576 legic_prng_forward(1); // forward the lfsr
1577 c++;
1578 if(c >= ToSendMax) {
1579 break;
1580 }
1581 }
1582 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1583 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1584 (void)r;
1585 }
1586 WDT_HIT();
1587 }
1588 LED_B_OFF();
1589 }
1590
1591
1592 //-----------------------------------------------------------------------------
1593 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1594 // so that it is ready to transmit to the tag using TransmitForLegic().
1595 //-----------------------------------------------------------------------------
1596 static void CodeLegicBitsAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1597 {
1598 int i, j;
1599 uint8_t b;
1600
1601 ToSendReset();
1602
1603 // Send SOF
1604 for(i = 0; i < 7; i++)
1605 ToSendStuffBit(1);
1606
1607
1608 for(i = 0; i < cmdlen; i++) {
1609 // Start bit
1610 ToSendStuffBit(0);
1611
1612 // Data bits
1613 b = cmd[i];
1614 for(j = 0; j < bits; j++) {
1615 if(b & 1) {
1616 ToSendStuffBit(1);
1617 } else {
1618 ToSendStuffBit(0);
1619 }
1620 b >>= 1;
1621 }
1622 }
1623
1624 // Convert from last character reference to length
1625 ++ToSendMax;
1626 }
1627
1628 /**
1629 Convenience function to encode, transmit and trace Legic comms
1630 **/
1631 static void CodeAndTransmitLegicAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1632 {
1633 CodeLegicBitsAsReader(cmd, cmdlen, bits);
1634 TransmitForLegic();
1635 if (tracing) {
1636 uint8_t parity[1] = {0x00};
1637 LogTrace(cmd, cmdlen, 0, 0, parity, TRUE);
1638 }
1639 }
1640
1641 int ice_legic_select_card()
1642 {
1643 //int cmd_size=0, card_size=0;
1644 uint8_t wakeup[] = { 0x7F };
1645 uint8_t getid[] = {0x19};
1646
1647 legic_prng_init(SESSION_IV);
1648
1649 // first, wake up the tag, 7bits
1650 CodeAndTransmitLegicAsReader(wakeup, sizeof(wakeup), 7);
1651
1652 GetSamplesForLegicDemod(1000, TRUE);
1653
1654 // frame_clean(&current_frame);
1655 //frame_receive_rwd(&current_frame, 6, 1);
1656
1657 legic_prng_forward(1); /* we wait anyways */
1658
1659 //while(timer->TC_CV < 387) ; /* ~ 258us */
1660 //frame_send_rwd(0x19, 6);
1661 CodeAndTransmitLegicAsReader(getid, sizeof(getid), 8);
1662 GetSamplesForLegicDemod(1000, TRUE);
1663
1664 //if (Demod.len < 14) return 2;
1665 Dbprintf("CARD TYPE: %02x LEN: %d", Demod.output[0], Demod.len);
1666
1667 switch(Demod.output[0]) {
1668 case 0x1d:
1669 DbpString("MIM 256 card found");
1670 // cmd_size = 9;
1671 // card_size = 256;
1672 break;
1673 case 0x3d:
1674 DbpString("MIM 1024 card found");
1675 // cmd_size = 11;
1676 // card_size = 1024;
1677 break;
1678 default:
1679 return -1;
1680 }
1681
1682 // if(bytes == -1)
1683 // bytes = card_size;
1684
1685 // if(bytes + offset >= card_size)
1686 // bytes = card_size - offset;
1687
1688 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1689 set_tracing(FALSE);
1690 return 1;
1691 }
1692
1693 // Set up LEGIC communication
1694 void ice_legic_setup() {
1695
1696 // standard things.
1697 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1698 BigBuf_free(); BigBuf_Clear_ext(false);
1699 clear_trace();
1700 set_tracing(TRUE);
1701 DemodReset();
1702 UartReset();
1703
1704 // Set up the synchronous serial port
1705 FpgaSetupSsc();
1706
1707 // connect Demodulated Signal to ADC:
1708 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1709
1710 // Signal field is on with the appropriate LED
1711 LED_D_ON();
1712 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1713 SpinDelay(200);
1714 // Start the timer
1715 //StartCountSspClk();
1716
1717 // initalize CRC
1718 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
1719
1720 // initalize prng
1721 legic_prng_init(0);
1722 }
Impressum, Datenschutz