1 //----------------------------------------------------------------------------- 
   2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch> 
   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 
   7 //----------------------------------------------------------------------------- 
   8 // LEGIC RF simulation code 
   9 //----------------------------------------------------------------------------- 
  11 #include "proxmark3.h" 
  17 #include "legic_prng.h" 
  20 static struct legic_frame 
{ 
  31 static crc_t    legic_crc
; 
  32 static int      legic_read_count
; 
  33 static uint32_t legic_prng_bc
; 
  34 static uint32_t legic_prng_iv
; 
  36 static int      legic_phase_drift
; 
  37 static int      legic_frame_drift
; 
  38 static int      legic_reqresp_drift
; 
  43 static void setup_timer(void) 
  45         /* Set up Timer 1 to use for measuring time between pulses. Since we're bit-banging 
  46          * this it won't be terribly accurate but should be good enough. 
  48         AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC1
); 
  49         timer 
= AT91C_BASE_TC1
; 
  50         timer
->TC_CCR 
= AT91C_TC_CLKDIS
; 
  51         timer
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV3_CLOCK
; 
  52         timer
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
  55      * Set up Timer 2 to use for measuring time between frames in  
  56      * tag simulation mode. Runs 4x faster as Timer 1 
  58     AT91C_BASE_PMC
->PMC_PCER 
= (1 << AT91C_ID_TC2
); 
  59     prng_timer 
= AT91C_BASE_TC2
; 
  60     prng_timer
->TC_CCR 
= AT91C_TC_CLKDIS
; 
  61         prng_timer
->TC_CMR 
= AT91C_TC_CLKS_TIMER_DIV2_CLOCK
; 
  62     prng_timer
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
  65 /* At TIMER_CLOCK3 (MCK/32) */ 
  66 #define RWD_TIME_1 150     /* RWD_TIME_PAUSE off, 80us on = 100us */ 
  67 #define RWD_TIME_0 90      /* RWD_TIME_PAUSE off, 40us on = 60us */ 
  68 #define RWD_TIME_PAUSE 30  /* 20us */ 
  69 #define RWD_TIME_FUZZ 20   /* rather generous 13us, since the peak detector + hysteresis fuzz quite a bit */ 
  70 #define TAG_TIME_BIT 150   /* 100us for every bit */ 
  71 #define TAG_TIME_WAIT 490  /* time from RWD frame end to tag frame start, experimentally determined */ 
  73 #define SIM_DIVISOR  586   /* prng_time/SIM_DIVISOR count prng needs to be forwared */ 
  74 #define SIM_SHIFT    900   /* prng_time+SIM_SHIFT shift of delayed start */ 
  76 #define SESSION_IV 0x55 
  77 #define OFFSET_LOG 1024 
  79 #define FUZZ_EQUAL(value, target, fuzz) ((value) > ((target)-(fuzz)) && (value) < ((target)+(fuzz))) 
  81 /* Generate Keystream */ 
  82 static uint32_t get_key_stream(int skip
, int count
) 
  84         uint32_t key
=0; int i
; 
  86         /* Use int to enlarge timer tc to 32bit */ 
  87         legic_prng_bc 
+= prng_timer
->TC_CV
; 
  88         prng_timer
->TC_CCR 
= AT91C_TC_SWTRG
; 
  90         /* If skip == -1, forward prng time based */ 
  92                 i  
= (legic_prng_bc
+SIM_SHIFT
)/SIM_DIVISOR
; /* Calculate Cycles based on timer */ 
  93                 i 
-= legic_prng_count(); /* substract cycles of finished frames */ 
  94                 i 
-= count
; /* substract current frame length, rewidn to bedinning */ 
  95                 legic_prng_forward(i
); 
  97                 legic_prng_forward(skip
); 
 100         /* Write Time Data into LOG */ 
 101         uint8_t *BigBuf 
= BigBuf_get_addr(); 
 102         i 
= (count 
== 6) ? -1 : legic_read_count
; 
 104         BigBuf
[OFFSET_LOG
+128+i
] = legic_prng_count(); 
 105         BigBuf
[OFFSET_LOG
+256+i
*4]   = (legic_prng_bc 
>> 0) & 0xff; 
 106         BigBuf
[OFFSET_LOG
+256+i
*4+1] = (legic_prng_bc 
>> 8) & 0xff; 
 107         BigBuf
[OFFSET_LOG
+256+i
*4+2] = (legic_prng_bc 
>>16) & 0xff; 
 108         BigBuf
[OFFSET_LOG
+256+i
*4+3] = (legic_prng_bc 
>>24) & 0xff; 
 109         BigBuf
[OFFSET_LOG
+384+i
] = count
; 
 111         /* Generate KeyStream */ 
 112         for(i
=0; i
<count
; i
++) { 
 113                 key 
|= legic_prng_get_bit() << i
; 
 114                 legic_prng_forward(1); 
 119 /* Send a frame in tag mode, the FPGA must have been set up by 
 122 static void frame_send_tag(uint16_t response
, int bits
, int crypt
) 
 124    /* Bitbang the response */ 
 125    AT91C_BASE_PIOA
->PIO_CODR 
= GPIO_SSC_DOUT
; 
 126    AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
 127    AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
 129    /* Use time to crypt frame */ 
 131       legic_prng_forward(2); /* TAG_TIME_WAIT -> shift by 2 */ 
 133       for(i
=0; i
<bits
; i
++) { 
 134          key 
|= legic_prng_get_bit() << i
; 
 135          legic_prng_forward(1); 
 137       //Dbprintf("key = 0x%x", key); 
 138       response 
= response 
^ key
; 
 141    /* Wait for the frame start */ 
 142    while(timer
->TC_CV 
< (TAG_TIME_WAIT 
- 30)) ; 
 145    for(i
=0; i
<bits
; i
++) { 
 146       int nextbit 
= timer
->TC_CV 
+ TAG_TIME_BIT
; 
 147       int bit 
= response 
& 1; 
 148       response 
= response 
>> 1; 
 150          AT91C_BASE_PIOA
->PIO_SODR 
= GPIO_SSC_DOUT
; 
 152          AT91C_BASE_PIOA
->PIO_CODR 
= GPIO_SSC_DOUT
; 
 154       while(timer
->TC_CV 
< nextbit
) ; 
 156    AT91C_BASE_PIOA
->PIO_CODR 
= GPIO_SSC_DOUT
; 
 159 /* Send a frame in reader mode, the FPGA must have been set up by 
 162 static void frame_send_rwd(uint32_t data
, int bits
) 
 165         timer
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
 166         while(timer
->TC_CV 
> 1) ; /* Wait till the clock has reset */ 
 169         for(i
=0; i
<bits
; i
++) { 
 170                 int starttime 
= timer
->TC_CV
; 
 171                 int pause_end 
= starttime 
+ RWD_TIME_PAUSE
, bit_end
; 
 175                 if(bit 
^ legic_prng_get_bit()) 
 176                         bit_end 
= starttime 
+ RWD_TIME_1
; 
 178                         bit_end 
= starttime 
+ RWD_TIME_0
; 
 181                 /* RWD_TIME_PAUSE time off, then some time on, so that the complete bit time is 
 182                  * RWD_TIME_x, where x is the bit to be transmitted */ 
 183                 AT91C_BASE_PIOA
->PIO_CODR 
= GPIO_SSC_DOUT
; 
 184                 while(timer
->TC_CV 
< pause_end
) ; 
 185                 AT91C_BASE_PIOA
->PIO_SODR 
= GPIO_SSC_DOUT
; 
 186                 legic_prng_forward(1); /* bit duration is longest. use this time to forward the lfsr */ 
 188                 while(timer
->TC_CV 
< bit_end
); 
 191         /* One final pause to mark the end of the frame */ 
 192         int pause_end 
= timer
->TC_CV 
+ RWD_TIME_PAUSE
; 
 193         AT91C_BASE_PIOA
->PIO_CODR 
= GPIO_SSC_DOUT
; 
 194         while(timer
->TC_CV 
< pause_end
) ; 
 195         AT91C_BASE_PIOA
->PIO_SODR 
= GPIO_SSC_DOUT
; 
 198         /* Reset the timer, to measure time until the start of the tag frame */ 
 199         timer
->TC_CCR 
= AT91C_TC_SWTRG
; 
 200         while(timer
->TC_CV 
> 1) ; /* Wait till the clock has reset */ 
 203 /* Receive a frame from the card in reader emulation mode, the FPGA and 
 204  * timer must have been set up by LegicRfReader and frame_send_rwd. 
 206  * The LEGIC RF protocol from card to reader does not include explicit 
 207  * frame start/stop information or length information. The reader must 
 208  * know beforehand how many bits it wants to receive. (Notably: a card 
 209  * sending a stream of 0-bits is indistinguishable from no card present.) 
 211  * Receive methodology: There is a fancy correlator in hi_read_rx_xcorr, but 
 212  * I'm not smart enough to use it. Instead I have patched hi_read_tx to output 
 213  * the ADC signal with hysteresis on SSP_DIN. Bit-bang that signal and look 
 214  * for edges. Count the edges in each bit interval. If they are approximately 
 215  * 0 this was a 0-bit, if they are approximately equal to the number of edges 
 216  * expected for a 212kHz subcarrier, this was a 1-bit. For timing we use the 
 217  * timer that's still running from frame_send_rwd in order to get a synchronization 
 218  * with the frame that we just sent. 
 220  * FIXME: Because we're relying on the hysteresis to just do the right thing 
 221  * the range is severely reduced (and you'll probably also need a good antenna). 
 222  * So this should be fixed some time in the future for a proper receiver. 
 224 static void frame_receive_rwd(struct legic_frame 
* const f
, int bits
, int crypt
) 
 226         uint32_t the_bit 
= 1;  /* Use a bitmask to save on shifts */ 
 228         int i
, old_level
=0, edges
=0; 
 229         int next_bit_at 
= TAG_TIME_WAIT
; 
 235         AT91C_BASE_PIOA
->PIO_ODR 
= GPIO_SSC_DIN
; 
 236         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DIN
; 
 238         /* we have some time now, precompute the cipher 
 239      * since we cannot compute it on the fly while reading */ 
 240         legic_prng_forward(2); 
 243                 for(i
=0; i
<bits
; i
++) { 
 244                         data 
|= legic_prng_get_bit() << i
; 
 245                         legic_prng_forward(1); 
 249         while(timer
->TC_CV 
< next_bit_at
) ; 
 251         next_bit_at 
+= TAG_TIME_BIT
; 
 253         for(i
=0; i
<bits
; i
++) { 
 255                 while(timer
->TC_CV 
< next_bit_at
) { 
 256                         int level 
= (AT91C_BASE_PIOA
->PIO_PDSR 
& GPIO_SSC_DIN
); 
 257                         if(level 
!= old_level
) 
 261                 next_bit_at 
+= TAG_TIME_BIT
; 
 263                 if(edges 
> 20 && edges 
< 60) { /* expected are 42 edges */ 
 272         /* Reset the timer, to synchronize the next frame */ 
 273         timer
->TC_CCR 
= AT91C_TC_SWTRG
; 
 274         while(timer
->TC_CV 
> 1) ; /* Wait till the clock has reset */ 
 277 static void frame_append_bit(struct legic_frame 
* const f
, int bit
) 
 280        return; /* Overflow, won't happen */ 
 282    f
->data 
|= (bit 
<< f
->bits
); 
 286 static void frame_clean(struct legic_frame 
* const f
) 
 292 static uint32_t perform_setup_phase_rwd(int iv
) 
 295         /* Switch on carrier and let the tag charge for 1ms */ 
 296         AT91C_BASE_PIOA
->PIO_SODR 
= GPIO_SSC_DOUT
; 
 299         legic_prng_init(0); /* no keystream yet */ 
 300         frame_send_rwd(iv
, 7); 
 303         frame_clean(¤t_frame
); 
 304         frame_receive_rwd(¤t_frame
, 6, 1); 
 305         legic_prng_forward(1); /* we wait anyways */ 
 306         while(timer
->TC_CV 
< 387) ; /* ~ 258us */ 
 307         frame_send_rwd(0x19, 6); 
 309         return current_frame
.data
; 
 312 static void LegicCommonInit(void) { 
 313         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 314         SetAdcMuxFor(GPIO_MUXSEL_HIPKD
); 
 316         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
); 
 318         /* Bitbang the transmitter */ 
 319         AT91C_BASE_PIOA
->PIO_CODR 
= GPIO_SSC_DOUT
; 
 320         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
 321         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
 325         crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0); 
 328 /* Switch off carrier, make sure tag is reset */ 
 329 static void switch_off_tag_rwd(void) 
 331         AT91C_BASE_PIOA
->PIO_CODR 
= GPIO_SSC_DOUT
; 
 335 /* calculate crc for a legic command */ 
 336 static int LegicCRC(int byte_index
, int value
, int cmd_sz
) { 
 337         crc_clear(&legic_crc
); 
 338         crc_update(&legic_crc
, 1, 1); /* CMD_READ */ 
 339         crc_update(&legic_crc
, byte_index
, cmd_sz
-1); 
 340         crc_update(&legic_crc
, value
, 8); 
 341         return crc_finish(&legic_crc
); 
 344 int legic_read_byte(int byte_index
, int cmd_sz
) { 
 347         legic_prng_forward(4); /* we wait anyways */ 
 348         while(timer
->TC_CV 
< 387) ; /* ~ 258us + 100us*delay */ 
 350         frame_send_rwd(1 | (byte_index 
<< 1), cmd_sz
); 
 351         frame_clean(¤t_frame
); 
 353         frame_receive_rwd(¤t_frame
, 12, 1); 
 355         byte 
= current_frame
.data 
& 0xff; 
 357         if( LegicCRC(byte_index
, byte
, cmd_sz
) != (current_frame
.data 
>> 8) ) { 
 358                 Dbprintf("!!! crc mismatch: expected %x but got %x !!!",  
 359                         LegicCRC(byte_index
, current_frame
.data 
& 0xff, cmd_sz
), 
 360                         current_frame
.data 
>> 8); 
 367 /* legic_write_byte() is not included, however it's trivial to implement 
 368  * and here are some hints on what remains to be done: 
 370  *  * assemble a write_cmd_frame with crc and send it 
 371  *  * wait until the tag sends back an ACK ('1' bit unencrypted) 
 372  *  * forward the prng based on the timing 
 374 //int legic_write_byte(int byte, int addr, int addr_sz, int PrngCorrection) { 
 375 int legic_write_byte(int byte
, int addr
, int addr_sz
) { 
 376     //do not write UID, CRC 
 380         //== send write command ============================== 
 381         crc_clear(&legic_crc
); 
 382         crc_update(&legic_crc
, 0, 1); /* CMD_WRITE */ 
 383         crc_update(&legic_crc
, addr
, addr_sz
); 
 384         crc_update(&legic_crc
, byte
, 8); 
 386         uint32_t crc 
= crc_finish(&legic_crc
); 
 387         uint32_t cmd 
= ((crc     
<<(addr_sz
+1+8)) //CRC 
 388                    |(byte    
<<(addr_sz
+1))   //Data 
 389                    |(addr    
<<1)             //Address 
 390                    |(0x00    <<0));           //CMD = W 
 391     uint32_t cmd_sz 
= addr_sz
+1+8+4;          //crc+data+cmd 
 393     legic_prng_forward(4); /* we wait anyways */ 
 394     while(timer
->TC_CV 
< 387) ; /* ~ 258us */ 
 395         frame_send_rwd(cmd
, cmd_sz
); 
 397         AT91C_BASE_PIOA
->PIO_ODR 
= GPIO_SSC_DIN
; 
 398         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DIN
; 
 400         //== wait for ack ==================================== 
 401     int t
, old_level
=0, edges
=0; 
 403         while(timer
->TC_CV 
< 387) ; /* ~ 258us */ 
 404     for(t
=0; t
<80; t
++) { 
 406                 next_bit_at 
+= TAG_TIME_BIT
; 
 407         while(timer
->TC_CV 
< next_bit_at
) { 
 408             int level 
= (AT91C_BASE_PIOA
->PIO_PDSR 
& GPIO_SSC_DIN
); 
 409             if(level 
!= old_level
) { 
 414         if(edges 
> 20 && edges 
< 60) { /* expected are 42 edges */ 
 415                         int t 
= timer
->TC_CV
; 
 416                         int c 
= t
/TAG_TIME_BIT
; 
 417                         timer
->TC_CCR 
= AT91C_TC_SWTRG
; 
 418                         while(timer
->TC_CV 
> 1) ; /* Wait till the clock has reset */ 
 419                         legic_prng_forward(c
-1); 
 423     timer
->TC_CCR 
= AT91C_TC_SWTRG
; 
 424     while(timer
->TC_CV 
> 1) ; /* Wait till the clock has reset */ 
 428 int LegicRfReader(int offset
, int bytes
) { 
 430         // ice_legic_setup(); 
 431         // ice_legic_select_card(); 
 434         int byte_index
=0, cmd_sz
=0, card_sz
=0; 
 438         uint8_t *BigBuf 
= BigBuf_get_addr(); 
 439         memset(BigBuf
, 0, 1024); 
 441         DbpString("setting up legic card"); 
 442         uint32_t tag_type 
= perform_setup_phase_rwd(SESSION_IV
); 
 443         switch_off_tag_rwd(); //we lose to mutch time with dprintf 
 446                         DbpString("MIM22 card found, reading card ..."); 
 451                         DbpString("MIM256 card found, reading card ..."); 
 456                         DbpString("MIM1024 card found, reading card ..."); 
 461                         Dbprintf("Unknown card format: %x",tag_type
); 
 467         if(bytes
+offset 
>= card_sz
) 
 468                 bytes 
= card_sz
-offset
; 
 470         perform_setup_phase_rwd(SESSION_IV
); 
 473         while(byte_index 
< bytes
) { 
 474                 int r 
= legic_read_byte(byte_index
+offset
, cmd_sz
); 
 475                 if(r 
== -1 ||BUTTON_PRESS()) { 
 476                 DbpString("operation aborted"); 
 477                         switch_off_tag_rwd(); 
 482                 BigBuf
[byte_index
] = r
; 
 485                 if (byte_index 
& 0x10) LED_C_ON(); else LED_C_OFF(); 
 489         switch_off_tag_rwd(); 
 490         Dbprintf("Card read, use 'hf legic decode' or"); 
 491     Dbprintf("'data hexsamples %d' to view results", (bytes
+7) & ~7); 
 495 /*int _LegicRfWriter(int bytes, int offset, int addr_sz, uint8_t *BigBuf, int RoundBruteforceValue) { 
 499         perform_setup_phase_rwd(SESSION_IV); 
 500     //legic_prng_forward(2); 
 501         while(byte_index < bytes) { 
 504                 //check if the DCF should be changed 
 505                 if ( (offset == 0x05) && (bytes == 0x02) ) { 
 506                         //write DCF in reverse order (addr 0x06 before 0x05) 
 507                         r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue); 
 508                         //legic_prng_forward(1); 
 511                                 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue); 
 513                         //legic_prng_forward(1); 
 516                         r = legic_write_byte(BigBuf[byte_index+offset], byte_index+offset, addr_sz, RoundBruteforceValue); 
 518                 if((r != 0) || BUTTON_PRESS()) { 
 519                         Dbprintf("operation aborted @ 0x%03.3x", byte_index); 
 520         switch_off_tag_rwd(); 
 528         if(byte_index & 0x10) LED_C_ON(); else LED_C_OFF(); 
 532     DbpString("write successful"); 
 536 void LegicRfWriter(int bytes
, int offset
) { 
 537         int byte_index
=0, addr_sz
=0; 
 538         uint8_t *BigBuf 
= BigBuf_get_addr(); 
 542         DbpString("setting up legic card"); 
 543         uint32_t tag_type 
= perform_setup_phase_rwd(SESSION_IV
); 
 544         switch_off_tag_rwd(); 
 547                         if(offset
+bytes 
> 22) { 
 548                                 Dbprintf("Error: can not write to 0x%03.3x on MIM22", offset
+bytes
); 
 552                         Dbprintf("MIM22 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+bytes
); 
 555                         if(offset
+bytes 
> 0x100) { 
 556                                 Dbprintf("Error: can not write to 0x%03.3x on MIM256", offset
+bytes
); 
 560                         Dbprintf("MIM256 card found, writing 0x%02.2x - 0x%02.2x ...", offset
, offset
+bytes
); 
 563                         if(offset
+bytes 
> 0x400) { 
 564                         Dbprintf("Error: can not write to 0x%03.3x on MIM1024", offset
+bytes
); 
 568                         Dbprintf("MIM1024 card found, writing 0x%03.3x - 0x%03.3x ...", offset
, offset
+bytes
); 
 571                         Dbprintf("No or unknown card found, aborting"); 
 577         perform_setup_phase_rwd(SESSION_IV
); 
 579         while(byte_index 
< bytes
) { 
 582                 //check if the DCF should be changed 
 583                 if ( ((byte_index
+offset
) == 0x05) && (bytes 
>= 0x02) ) { 
 584                         //write DCF in reverse order (addr 0x06 before 0x05) 
 585                         r 
= legic_write_byte(BigBuf
[(0x06-byte_index
)], (0x06-byte_index
), addr_sz
); 
 587                         // write second byte on success... 
 590                                 r 
= legic_write_byte(BigBuf
[(0x06-byte_index
)], (0x06-byte_index
), addr_sz
); 
 594                         r 
= legic_write_byte(BigBuf
[byte_index
+offset
], byte_index
+offset
, addr_sz
); 
 596                 if((r 
!= 0) || BUTTON_PRESS()) { 
 597                         Dbprintf("operation aborted @ 0x%03.3x", byte_index
); 
 598                         switch_off_tag_rwd(); 
 606         if(byte_index 
& 0x10) LED_C_ON(); else LED_C_OFF(); 
 610     DbpString("write successful"); 
 612         for(byte_index 
= -2; byte_index 
< 200; byte_index
++) 
 614                 Dbprintf("+ Try RndValue %d...", byte_index
); 
 615                 if(_LegicRfWriter(bytes
, offset
, addr_sz
, BigBuf
, byte_index
) == 0) 
 622 void LegicRfRawWriter(int offset
, int byte
) { 
 623         int byte_index
=0, addr_sz
=0; 
 627         DbpString("setting up legic card"); 
 628         uint32_t tag_type 
= perform_setup_phase_rwd(SESSION_IV
); 
 629         switch_off_tag_rwd(); 
 633                                 Dbprintf("Error: can not write to 0x%03.3x on MIM22", offset
); 
 637                         Dbprintf("MIM22 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", offset
, byte
); 
 641                                 Dbprintf("Error: can not write to 0x%03.3x on MIM256", offset
); 
 645                         Dbprintf("MIM256 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", offset
, byte
); 
 649                         Dbprintf("Error: can not write to 0x%03.3x on MIM1024", offset
); 
 653                         Dbprintf("MIM1024 card found, writing at addr 0x%03.3x - value 0x%03.3x ...", offset
, byte
); 
 656                         Dbprintf("No or unknown card found, aborting"); 
 659         Dbprintf("integer value: %d offset: %d  addr_sz: %d", byte
, offset
, addr_sz
); 
 661         perform_setup_phase_rwd(SESSION_IV
); 
 662     //legic_prng_forward(2); 
 664         int r 
= legic_write_byte(byte
, offset
, addr_sz
); 
 666         if((r 
!= 0) || BUTTON_PRESS()) { 
 667                 Dbprintf("operation aborted @ 0x%03.3x (%1d)", byte_index
, r
); 
 668                 switch_off_tag_rwd(); 
 675         if(byte_index 
& 0x10) LED_C_ON(); else LED_C_OFF(); 
 679     DbpString("write successful"); 
 684 /* Handle (whether to respond) a frame in tag mode */ 
 685 static void frame_handle_tag(struct legic_frame 
const * const f
) 
 687         uint8_t *BigBuf 
= BigBuf_get_addr(); 
 689    /* First Part of Handshake (IV) */ 
 691      if(f
->data 
== SESSION_IV
) { 
 693         prng_timer
->TC_CCR 
= AT91C_TC_SWTRG
; 
 694         legic_prng_init(f
->data
); 
 695         frame_send_tag(0x3d, 6, 1); /* 0x3d^0x26 = 0x1b */ 
 696         legic_state 
= STATE_IV
; 
 697         legic_read_count 
= 0; 
 699         legic_prng_iv 
= f
->data
; 
 702         timer
->TC_CCR 
= AT91C_TC_SWTRG
; 
 703         while(timer
->TC_CV 
> 1); 
 704         while(timer
->TC_CV 
< 280); 
 706       } else if((prng_timer
->TC_CV 
% 50) > 40) { 
 707         legic_prng_init(f
->data
); 
 708         frame_send_tag(0x3d, 6, 1); 
 715    if(legic_state 
== STATE_IV
) { 
 716       if((f
->bits 
== 6) && (f
->data 
== (0x19 ^ get_key_stream(1, 6)))) { 
 717          legic_state 
= STATE_CON
; 
 720          timer
->TC_CCR 
= AT91C_TC_SWTRG
; 
 721          while(timer
->TC_CV 
> 1); 
 722          while(timer
->TC_CV 
< 200); 
 725          legic_state 
= STATE_DISCON
; 
 727          Dbprintf("0x19 - Frame: %03.3x", f
->data
); 
 734       if(legic_state 
== STATE_CON
) { 
 735          int key   
= get_key_stream(-1, 11); //legic_phase_drift, 11); 
 736          int addr  
= f
->data 
^ key
; addr 
= addr 
>> 1; 
 737          int data 
= BigBuf
[addr
]; 
 738          int hash 
= LegicCRC(addr
, data
, 11) << 8; 
 739          BigBuf
[OFFSET_LOG
+legic_read_count
] = (uint8_t)addr
; 
 742          //Dbprintf("Data:%03.3x, key:%03.3x, addr: %03.3x, read_c:%u", f->data, key, addr, read_c); 
 743          legic_prng_forward(legic_reqresp_drift
); 
 745          frame_send_tag(hash 
| data
, 12, 1); 
 748          timer
->TC_CCR 
= AT91C_TC_SWTRG
; 
 749          while(timer
->TC_CV 
> 1); 
 750          legic_prng_forward(legic_frame_drift
); 
 751          while(timer
->TC_CV 
< 180); 
 758       int key   
= get_key_stream(-1, 23); //legic_frame_drift, 23); 
 759       int addr  
= f
->data 
^ key
; addr 
= addr 
>> 1; addr 
= addr 
& 0x3ff; 
 760       int data  
= f
->data 
^ key
; data 
= data 
>> 11; data 
= data 
& 0xff; 
 763       legic_state 
= STATE_DISCON
; 
 765       Dbprintf("write - addr: %x, data: %x", addr
, data
); 
 769    if(legic_state 
!= STATE_DISCON
) { 
 770       Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f
->bits
, f
->data
, legic_state
, legic_read_count
); 
 772       Dbprintf("IV: %03.3x", legic_prng_iv
); 
 773       for(i 
= 0; i
<legic_read_count
; i
++) { 
 774          Dbprintf("Read Nb: %u, Addr: %u", i
, BigBuf
[OFFSET_LOG
+i
]); 
 777       for(i 
= -1; i
<legic_read_count
; i
++) { 
 779          t  
= BigBuf
[OFFSET_LOG
+256+i
*4]; 
 780          t 
|= BigBuf
[OFFSET_LOG
+256+i
*4+1] << 8; 
 781          t 
|= BigBuf
[OFFSET_LOG
+256+i
*4+2] <<16; 
 782          t 
|= BigBuf
[OFFSET_LOG
+256+i
*4+3] <<24; 
 784          Dbprintf("Cycles: %u, Frame Length: %u, Time: %u",  
 785             BigBuf
[OFFSET_LOG
+128+i
], 
 786             BigBuf
[OFFSET_LOG
+384+i
], 
 790    legic_state 
= STATE_DISCON
;  
 791    legic_read_count 
= 0; 
 797 /* Read bit by bit untill full frame is received 
 798  * Call to process frame end answer 
 800 static void emit(int bit
) 
 803      if(current_frame
.bits 
<= 4) { 
 804         frame_clean(¤t_frame
); 
 806         frame_handle_tag(¤t_frame
); 
 807         frame_clean(¤t_frame
); 
 810   } else if(bit 
== 0) { 
 811     frame_append_bit(¤t_frame
, 0); 
 812   } else if(bit 
== 1) { 
 813     frame_append_bit(¤t_frame
, 1); 
 817 void LegicRfSimulate(int phase
, int frame
, int reqresp
) 
 819   /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,  
 820    * modulation mode set to 212kHz subcarrier. We are getting the incoming raw 
 821    * envelope waveform on DIN and should send our response on DOUT. 
 823    * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll 
 824    * measure the time between two rising edges on DIN, and no encoding on the 
 825    * subcarrier from card to reader, so we'll just shift out our verbatim data 
 826    * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear, 
 827    * seems to be 300us-ish. 
 832       for(i
=0; i
<=reqresp
; i
++) { 
 833          legic_prng_init(SESSION_IV
); 
 834          Dbprintf("i=%u, key 0x%3.3x", i
, get_key_stream(i
, frame
)); 
 839    legic_phase_drift 
= phase
; 
 840    legic_frame_drift 
= frame
; 
 841    legic_reqresp_drift 
= reqresp
; 
 843    FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 844    SetAdcMuxFor(GPIO_MUXSEL_HIPKD
); 
 846    FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR 
| FPGA_HF_SIMULATOR_MODULATE_212K
); 
 848    /* Bitbang the receiver */ 
 849    AT91C_BASE_PIOA
->PIO_ODR 
= GPIO_SSC_DIN
; 
 850    AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DIN
; 
 853    crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0); 
 857    legic_state 
= STATE_DISCON
; 
 860    DbpString("Starting Legic emulator, press button to end"); 
 861    while(!BUTTON_PRESS() && !usb_poll_validate_length()) { 
 862       int level 
= !!(AT91C_BASE_PIOA
->PIO_PDSR 
& GPIO_SSC_DIN
); 
 863       int time 
= timer
->TC_CV
; 
 865       if(level 
!= old_level
) { 
 867             timer
->TC_CCR 
= AT91C_TC_CLKEN 
| AT91C_TC_SWTRG
; 
 868             if(FUZZ_EQUAL(time
, RWD_TIME_1
, RWD_TIME_FUZZ
)) { 
 873             } else if(FUZZ_EQUAL(time
, RWD_TIME_0
, RWD_TIME_FUZZ
)) { 
 887       if(time 
>= (RWD_TIME_1
+RWD_TIME_FUZZ
) && active
) { 
 894       if(time 
>= (20*RWD_TIME_1
) && (timer
->TC_SR 
& AT91C_TC_CLKSTA
)) { 
 895          timer
->TC_CCR 
= AT91C_TC_CLKDIS
; 
 901    DbpString("Stopped"); 
 908 //----------------------------------------------------------------------------- 
 909 //----------------------------------------------------------------------------- 
 912 //----------------------------------------------------------------------------- 
 913 // Code up a string of octets at layer 2 (including CRC, we don't generate 
 914 // that here) so that they can be transmitted to the reader. Doesn't transmit 
 915 // them yet, just leaves them ready to send in ToSend[]. 
 916 //----------------------------------------------------------------------------- 
 917 // static void CodeLegicAsTag(const uint8_t *cmd, int len) 
 923         // // Transmit a burst of ones, as the initial thing that lets the 
 924         // // reader get phase sync. This (TR1) must be > 80/fs, per spec, 
 925         // // but tag that I've tried (a Paypass) exceeds that by a fair bit, 
 927         // for(i = 0; i < 20; i++) { 
 928                 // ToSendStuffBit(1); 
 929                 // ToSendStuffBit(1); 
 930                 // ToSendStuffBit(1); 
 931                 // ToSendStuffBit(1); 
 935         // for(i = 0; i < 10; i++) { 
 936                 // ToSendStuffBit(0); 
 937                 // ToSendStuffBit(0); 
 938                 // ToSendStuffBit(0); 
 939                 // ToSendStuffBit(0); 
 941         // for(i = 0; i < 2; i++) { 
 942                 // ToSendStuffBit(1); 
 943                 // ToSendStuffBit(1); 
 944                 // ToSendStuffBit(1); 
 945                 // ToSendStuffBit(1); 
 948         // for(i = 0; i < len; i++) { 
 950                 // uint8_t b = cmd[i]; 
 953                 // ToSendStuffBit(0); 
 954                 // ToSendStuffBit(0); 
 955                 // ToSendStuffBit(0); 
 956                 // ToSendStuffBit(0); 
 959                 // for(j = 0; j < 8; j++) { 
 961                                 // ToSendStuffBit(1); 
 962                                 // ToSendStuffBit(1); 
 963                                 // ToSendStuffBit(1); 
 964                                 // ToSendStuffBit(1); 
 966                                 // ToSendStuffBit(0); 
 967                                 // ToSendStuffBit(0); 
 968                                 // ToSendStuffBit(0); 
 969                                 // ToSendStuffBit(0); 
 975                 // ToSendStuffBit(1); 
 976                 // ToSendStuffBit(1); 
 977                 // ToSendStuffBit(1); 
 978                 // ToSendStuffBit(1); 
 982         // for(i = 0; i < 10; i++) { 
 983                 // ToSendStuffBit(0); 
 984                 // ToSendStuffBit(0); 
 985                 // ToSendStuffBit(0); 
 986                 // ToSendStuffBit(0); 
 988         // for(i = 0; i < 2; i++) { 
 989                 // ToSendStuffBit(1); 
 990                 // ToSendStuffBit(1); 
 991                 // ToSendStuffBit(1); 
 992                 // ToSendStuffBit(1); 
 995         // // Convert from last byte pos to length 
 999 //----------------------------------------------------------------------------- 
1000 // The software UART that receives commands from the reader, and its state 
1002 //----------------------------------------------------------------------------- 
1006                 STATE_GOT_FALLING_EDGE_OF_SOF
, 
1007                 STATE_AWAITING_START_BIT
, 
1008                 STATE_RECEIVING_DATA
 
1018 /* Receive & handle a bit coming from the reader. 
1020  * This function is called 4 times per bit (every 2 subcarrier cycles). 
1021  * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us 
1024  * LED A -> ON once we have received the SOF and are expecting the rest. 
1025  * LED A -> OFF once we have received EOF or are in error state or unsynced 
1027  * Returns: true if we received a EOF 
1028  *          false if we are still waiting for some more 
1030 // static RAMFUNC int HandleLegicUartBit(uint8_t bit) 
1032         // switch(Uart.state) { 
1033                 // case STATE_UNSYNCD: 
1035                                 // // we went low, so this could be the beginning of an SOF 
1036                                 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF; 
1042                 // case STATE_GOT_FALLING_EDGE_OF_SOF: 
1044                         // if(Uart.posCnt == 2) {       // sample every 4 1/fs in the middle of a bit 
1046                                         // if(Uart.bitCnt > 9) { 
1047                                                 // // we've seen enough consecutive 
1048                                                 // // zeros that it's a valid SOF 
1050                                                 // Uart.byteCnt = 0; 
1051                                                 // Uart.state = STATE_AWAITING_START_BIT; 
1052                                                 // LED_A_ON(); // Indicate we got a valid SOF 
1054                                                 // // didn't stay down long enough 
1055                                                 // // before going high, error 
1056                                                 // Uart.state = STATE_UNSYNCD; 
1059                                         // // do nothing, keep waiting 
1063                         // if(Uart.posCnt >= 4) Uart.posCnt = 0; 
1064                         // if(Uart.bitCnt > 12) { 
1065                                 // // Give up if we see too many zeros without 
1068                                 // Uart.state = STATE_UNSYNCD; 
1072                 // case STATE_AWAITING_START_BIT: 
1075                                 // if(Uart.posCnt > 50/2) {     // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs 
1076                                         // // stayed high for too long between 
1077                                         // // characters, error 
1078                                         // Uart.state = STATE_UNSYNCD; 
1081                                 // // falling edge, this starts the data byte 
1084                                 // Uart.shiftReg = 0; 
1085                                 // Uart.state = STATE_RECEIVING_DATA; 
1089                 // case STATE_RECEIVING_DATA: 
1091                         // if(Uart.posCnt == 2) { 
1092                                 // // time to sample a bit 
1093                                 // Uart.shiftReg >>= 1; 
1095                                         // Uart.shiftReg |= 0x200; 
1099                         // if(Uart.posCnt >= 4) { 
1102                         // if(Uart.bitCnt == 10) { 
1103                                 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001)) 
1105                                         // // this is a data byte, with correct 
1106                                         // // start and stop bits 
1107                                         // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff; 
1110                                         // if(Uart.byteCnt >= Uart.byteCntMax) { 
1111                                                 // // Buffer overflowed, give up 
1113                                                 // Uart.state = STATE_UNSYNCD; 
1115                                                 // // so get the next byte now 
1117                                                 // Uart.state = STATE_AWAITING_START_BIT; 
1119                                 // } else if (Uart.shiftReg == 0x000) { 
1120                                         // // this is an EOF byte 
1121                                         // LED_A_OFF(); // Finished receiving 
1122                                         // Uart.state = STATE_UNSYNCD; 
1123                                         // if (Uart.byteCnt != 0) { 
1127                                         // // this is an error 
1129                                         // Uart.state = STATE_UNSYNCD; 
1136                         // Uart.state = STATE_UNSYNCD; 
1144 static void UartReset() 
1146         Uart
.byteCntMax 
= MAX_FRAME_SIZE
; 
1147         Uart
.state 
= STATE_UNSYNCD
; 
1151         memset(Uart
.output
, 0x00, MAX_FRAME_SIZE
); 
1154 // static void UartInit(uint8_t *data) 
1156         // Uart.output = data; 
1160 //============================================================================= 
1161 // An LEGIC reader. We take layer two commands, code them 
1162 // appropriately, and then send them to the tag. We then listen for the 
1163 // tag's response, which we leave in the buffer to be demodulated on the 
1165 //============================================================================= 
1170                 DEMOD_PHASE_REF_TRAINING
, 
1171                 DEMOD_AWAITING_FALLING_EDGE_OF_SOF
, 
1172                 DEMOD_GOT_FALLING_EDGE_OF_SOF
, 
1173                 DEMOD_AWAITING_START_BIT
, 
1174                 DEMOD_RECEIVING_DATA
 
1187  * Handles reception of a bit from the tag 
1189  * This function is called 2 times per bit (every 4 subcarrier cycles). 
1190  * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us 
1193  * LED C -> ON once we have received the SOF and are expecting the rest. 
1194  * LED C -> OFF once we have received EOF or are unsynced 
1196  * Returns: true if we received a EOF 
1197  *          false if we are still waiting for some more 
1201  #ifndef SUBCARRIER_DETECT_THRESHOLD 
1202  # define SUBCARRIER_DETECT_THRESHOLD   8 
1205  // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq))) 
1206 #ifndef CHECK_FOR_SUBCARRIER 
1207 # define CHECK_FOR_SUBCARRIER() { v = MAX(ai, aq) + MIN(halfci, halfcq); } 
1210 // The soft decision on the bit uses an estimate of just the 
1211 // quadrant of the reference angle, not the exact angle. 
1212 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq))) 
1213 #define MAKE_SOFT_DECISION() { \ 
1214                 if(Demod.sumI > 0) \ 
1219                 if(Demod.sumQ > 0) \ 
1226 static RAMFUNC 
int HandleLegicSamplesDemod(int ci
, int cq
) 
1231         int halfci 
= (ai 
>> 1); 
1232         int halfcq 
= (aq 
>> 1); 
1234         switch(Demod
.state
) { 
1237                         CHECK_FOR_SUBCARRIER() 
1239                         if(v 
> SUBCARRIER_DETECT_THRESHOLD
) {   // subcarrier detected 
1240                                 Demod
.state 
= DEMOD_PHASE_REF_TRAINING
; 
1247                 case DEMOD_PHASE_REF_TRAINING
: 
1248                         if(Demod
.posCount 
< 8) { 
1250                                 CHECK_FOR_SUBCARRIER() 
1252                                 if (v 
> SUBCARRIER_DETECT_THRESHOLD
) { 
1253                                         // set the reference phase (will code a logic '1') by averaging over 32 1/fs. 
1254                                         // note: synchronization time > 80 1/fs 
1260                                         Demod
.state 
= DEMOD_UNSYNCD
; 
1263                                 Demod
.state 
= DEMOD_AWAITING_FALLING_EDGE_OF_SOF
; 
1267                 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF
: 
1269                         MAKE_SOFT_DECISION() 
1271                         //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq ); 
1272                         // logic '0' detected 
1275                                 Demod
.state 
= DEMOD_GOT_FALLING_EDGE_OF_SOF
; 
1277                                 // start of SOF sequence 
1280                                 // maximum length of TR1 = 200 1/fs 
1281                                 if(Demod
.posCount 
> 25*2) Demod
.state 
= DEMOD_UNSYNCD
; 
1286                 case DEMOD_GOT_FALLING_EDGE_OF_SOF
: 
1289                         MAKE_SOFT_DECISION() 
1292                                 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges 
1293                                 if(Demod
.posCount 
< 10*2) {  
1294                                         Demod
.state 
= DEMOD_UNSYNCD
; 
1296                                         LED_C_ON(); // Got SOF 
1297                                         Demod
.state 
= DEMOD_AWAITING_START_BIT
; 
1302                                 // low phase of SOF too long (> 12 etu) 
1303                                 if(Demod
.posCount 
> 13*2) {  
1304                                         Demod
.state 
= DEMOD_UNSYNCD
; 
1310                 case DEMOD_AWAITING_START_BIT
: 
1313                         MAKE_SOFT_DECISION() 
1316                                 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs 
1317                                 if(Demod
.posCount 
> 3*2) {  
1318                                         Demod
.state 
= DEMOD_UNSYNCD
; 
1322                                 // start bit detected 
1324                                 Demod
.posCount 
= 1;                             // this was the first half 
1327                                 Demod
.state 
= DEMOD_RECEIVING_DATA
; 
1331                 case DEMOD_RECEIVING_DATA
: 
1333                         MAKE_SOFT_DECISION() 
1335                         if(Demod
.posCount 
== 0) { 
1336                                 // first half of bit 
1340                                 // second half of bit 
1342                                 Demod
.shiftReg 
>>= 1; 
1344                                 if(Demod
.thisBit 
> 0)  
1345                                         Demod
.shiftReg 
|= 0x200; 
1349                                 if(Demod
.bitCount 
== 10) { 
1351                                         uint16_t s 
= Demod
.shiftReg
; 
1353                                         if((s 
& 0x200) && !(s 
& 0x001)) {  
1354                                                 // stop bit == '1', start bit == '0' 
1355                                                 uint8_t b 
= (s 
>> 1); 
1356                                                 Demod
.output
[Demod
.len
] = b
; 
1358                                                 Demod
.state 
= DEMOD_AWAITING_START_BIT
; 
1360                                                 Demod
.state 
= DEMOD_UNSYNCD
; 
1364                                                         // This is EOF (start, stop and all data bits == '0' 
1374                         Demod
.state 
= DEMOD_UNSYNCD
; 
1381 // Clear out the state of the "UART" that receives from the tag. 
1382 static void DemodReset() { 
1384         Demod
.state 
= DEMOD_UNSYNCD
; 
1391         memset(Demod
.output
, 0x00, MAX_FRAME_SIZE
); 
1394 static void DemodInit(uint8_t *data
) { 
1395         Demod
.output 
= data
; 
1400  *  Demodulate the samples we received from the tag, also log to tracebuffer 
1401  *  quiet: set to 'TRUE' to disable debug output 
1403  #define LEGIC_DMA_BUFFER_SIZE 256 
1404 static void GetSamplesForLegicDemod(int n
, bool quiet
) 
1407         bool gotFrame 
= FALSE
; 
1408         int lastRxCounter 
= LEGIC_DMA_BUFFER_SIZE
; 
1409         int     ci
, cq
, samples 
= 0; 
1413         // And put the FPGA in the appropriate mode 
1414         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR 
| FPGA_HF_READER_RX_XCORR_QUARTER_FREQ
); 
1416         // The response (tag -> reader) that we're receiving. 
1417         // Set up the demodulator for tag -> reader responses. 
1418         DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
)); 
1420         // The DMA buffer, used to stream samples from the FPGA 
1421         int8_t *dmaBuf 
= (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE
); 
1422         int8_t *upTo 
= dmaBuf
; 
1424         // Setup and start DMA. 
1425         if ( !FpgaSetupSscDma((uint8_t*) dmaBuf
, LEGIC_DMA_BUFFER_SIZE
) ){ 
1426                 if (MF_DBGLEVEL 
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");  
1430         // Signal field is ON with the appropriate LED: 
1433                 int behindBy 
= lastRxCounter 
- AT91C_BASE_PDC_SSC
->PDC_RCR
; 
1434                 if(behindBy 
> max
) max 
= behindBy
; 
1436                 while(((lastRxCounter
-AT91C_BASE_PDC_SSC
->PDC_RCR
) & (LEGIC_DMA_BUFFER_SIZE
-1)) > 2) { 
1440                         if(upTo 
>= dmaBuf 
+ LEGIC_DMA_BUFFER_SIZE
) { 
1442                                 AT91C_BASE_PDC_SSC
->PDC_RNPR 
= (uint32_t) upTo
; 
1443                                 AT91C_BASE_PDC_SSC
->PDC_RNCR 
= LEGIC_DMA_BUFFER_SIZE
; 
1446                         if(lastRxCounter 
<= 0) 
1447                                 lastRxCounter 
= LEGIC_DMA_BUFFER_SIZE
; 
1451                         gotFrame 
= HandleLegicSamplesDemod(ci 
, cq 
); 
1456                 if(samples 
> n 
|| gotFrame
) 
1460         FpgaDisableSscDma(); 
1462         if (!quiet 
&& Demod
.len 
== 0) { 
1463                 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d", 
1474         if (Demod
.len 
> 0) { 
1475                 uint8_t parity
[MAX_PARITY_SIZE
] = {0x00}; 
1476                 LogTrace(Demod
.output
, Demod
.len
, 0, 0, parity
, FALSE
); 
1479 //----------------------------------------------------------------------------- 
1480 // Transmit the command (to the tag) that was placed in ToSend[]. 
1481 //----------------------------------------------------------------------------- 
1482 static void TransmitForLegic(void) 
1488         while(AT91C_BASE_SSC
->SSC_SR 
& (AT91C_SSC_TXRDY
)) 
1489                 AT91C_BASE_SSC
->SSC_THR 
= 0xff; 
1491         // Signal field is ON with the appropriate Red LED 
1494         // Signal we are transmitting with the Green LED 
1496         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX 
| FPGA_HF_READER_TX_SHALLOW_MOD
); 
1498         for(c 
= 0; c 
< 10;) { 
1499                 if(AT91C_BASE_SSC
->SSC_SR 
& (AT91C_SSC_TXRDY
)) { 
1500                         AT91C_BASE_SSC
->SSC_THR 
= 0xff; 
1503                 if(AT91C_BASE_SSC
->SSC_SR 
& (AT91C_SSC_RXRDY
)) { 
1504                         volatile uint32_t r 
= AT91C_BASE_SSC
->SSC_RHR
; 
1512                 if(AT91C_BASE_SSC
->SSC_SR 
& (AT91C_SSC_TXRDY
)) { 
1513                         AT91C_BASE_SSC
->SSC_THR 
= ToSend
[c
]; 
1514                         legic_prng_forward(1); // forward the lfsr  
1516                         if(c 
>= ToSendMax
) { 
1520                 if(AT91C_BASE_SSC
->SSC_SR 
& (AT91C_SSC_RXRDY
)) { 
1521                         volatile uint32_t r 
= AT91C_BASE_SSC
->SSC_RHR
; 
1530 //----------------------------------------------------------------------------- 
1531 // Code a layer 2 command (string of octets, including CRC) into ToSend[], 
1532 // so that it is ready to transmit to the tag using TransmitForLegic(). 
1533 //----------------------------------------------------------------------------- 
1534 static void CodeLegicBitsAsReader(const uint8_t *cmd
, int bits
) 
1542         for(i 
= 0; i 
< 7; i
++) { 
1546         for(i 
= 0; i 
< bits
; i
++) { 
1552                 for(j 
= 0; j 
< 8; j
++) { 
1562         // Convert from last character reference to length 
1567   Convenience function to encode, transmit and trace Legic comms 
1569 static void CodeAndTransmitLegicAsReader(const uint8_t *cmd
, int bits
) 
1571         CodeLegicBitsAsReader(cmd
, bits
); 
1574                 uint8_t parity
[1] = {0x00}; 
1575                 LogTrace(cmd
, bits
, 0, 0, parity
, TRUE
); 
1579 int ice_legic_select_card() 
1581         //int cmd_size=0, card_size=0; 
1582         uint8_t wakeup
[] = { 0x7F}; 
1583         uint8_t getid
[] = {0x19}; 
1585         legic_prng_init(SESSION_IV
); 
1587         // first, wake up the tag, 7bits 
1588         CodeAndTransmitLegicAsReader(wakeup
, 7); 
1590         GetSamplesForLegicDemod(1000, TRUE
); 
1592         // frame_clean(¤t_frame); 
1593         //frame_receive_rwd(¤t_frame, 6, 1); 
1595         legic_prng_forward(1); /* we wait anyways */ 
1597         //while(timer->TC_CV < 387) ; /* ~ 258us */ 
1598         //frame_send_rwd(0x19, 6); 
1599         CodeAndTransmitLegicAsReader(getid
, sizeof(getid
)); 
1600         GetSamplesForLegicDemod(1000, TRUE
); 
1602         //if (Demod.len < 14) return 2;  
1603         Dbprintf("CARD TYPE: %02x  LEN: %d", Demod
.output
[0], Demod
.len
); 
1605         switch(Demod
.output
[0]) { 
1607                         DbpString("MIM 256 card found"); 
1612                         DbpString("MIM 1024 card found"); 
1614                         // card_size = 1024; 
1621                 // bytes = card_size; 
1623         // if(bytes + offset >= card_size) 
1624                 // bytes = card_size - offset;   
1626         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1631 // Set up LEGIC communication 
1632 void ice_legic_setup() { 
1635         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
1636         BigBuf_free(); BigBuf_Clear_ext(false); 
1642         // Set up the synchronous serial port 
1645         // connect Demodulated Signal to ADC: 
1646         SetAdcMuxFor(GPIO_MUXSEL_HIPKD
); 
1648         // Signal field is on with the appropriate LED 
1650         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX 
| FPGA_HF_READER_TX_SHALLOW_MOD
); 
1653         //StartCountSspClk(); 
1656         crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0);