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