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