1 //----------------------------------------------------------------------------- 
   2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch> 
   5 // This code is licensed to you under the terms of the GNU GPL, version 2 or, 
   6 // at your option, any later version. See the LICENSE.txt file for the text of 
   8 //----------------------------------------------------------------------------- 
   9 // LEGIC RF simulation code 
  10 //----------------------------------------------------------------------------- 
  13 static struct legic_frame 
{ 
  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
; 
  29 static int      legic_phase_drift
; 
  30 static int      legic_frame_drift
; 
  31 static int      legic_reqresp_drift
; 
  37 static void setup_timer(void) { 
  38         // Set up Timer 1 to use for measuring time between pulses. Since we're bit-banging 
  39         // this it won't be terribly accurate but should be good enough. 
  41         AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1); 
  42         timer = AT91C_BASE_TC1; 
  43         timer->TC_CCR = AT91C_TC_CLKDIS; 
  44         timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK; 
  45         timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; 
  48     // Set up Timer 2 to use for measuring time between frames in  
  49     // tag simulation mode. Runs 4x faster as Timer 1 
  51     AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC2); 
  52     prng_timer = AT91C_BASE_TC2; 
  53     prng_timer->TC_CCR = AT91C_TC_CLKDIS; 
  54         prng_timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV2_CLOCK; 
  55     prng_timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; 
  58         AT91C_BASE_PMC->PMC_PCER |= (0x1 << 12) | (0x1 << 13) | (0x1 << 14); 
  59         AT91C_BASE_TCB->TCB_BMR = AT91C_TCB_TC0XC0S_NONE | AT91C_TCB_TC1XC1S_TIOA0 | AT91C_TCB_TC2XC2S_NONE; 
  62         AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; // timer disable 
  63         AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK | // MCK(48MHz)/32 -- tick=1.5mks 
  64                                                                 AT91C_TC_WAVE | AT91C_TC_WAVESEL_UP_AUTO | AT91C_TC_ACPA_CLEAR | 
  65                                                                 AT91C_TC_ACPC_SET | AT91C_TC_ASWTRG_SET; 
  66         AT91C_BASE_TC0->TC_RA = 1; 
  67         AT91C_BASE_TC0->TC_RC = 0xBFFF + 1; // 0xC000 
  71 // At TIMER_CLOCK3 (MCK/32) 
  72 // testing calculating in (us) microseconds. 
  73 #define RWD_TIME_1 120          // READER_TIME_PAUSE 20us off, 80us on = 100us  80 * 1.5 == 120ticks 
  74 #define RWD_TIME_0 60           // READER_TIME_PAUSE 20us off, 40us on = 60us   40 * 1.5 == 60ticks  
  75 #define RWD_TIME_PAUSE 30       // 20us == 20 * 1.5 == 30ticks */ 
  76 #define TAG_BIT_PERIOD 142      // 100us == 100 * 1.5 == 150ticks 
  77 #define TAG_FRAME_WAIT 495  // 330us from READER frame end to TAG frame start. 330 * 1.5 == 495 
  79 #define RWD_TIME_FUZZ 20   // rather generous 13us, since the peak detector + hysteresis fuzz quite a bit 
  81 #define SIM_DIVISOR  586   /* prng_time/SIM_DIVISOR count prng needs to be forwared */ 
  82 #define SIM_SHIFT    900   /* prng_time+SIM_SHIFT shift of delayed start */ 
  84 #define OFFSET_LOG 1024 
  86 #define FUZZ_EQUAL(value, target, fuzz) ((value) > ((target)-(fuzz)) && (value) < ((target)+(fuzz))) 
  89 # define SHORT_COIL      LOW(GPIO_SSC_DOUT); 
  92 # define OPEN_COIL      HIGH(GPIO_SSC_DOUT); 
  95 # define LINE_IN  AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DIN; 
  97 // Pause pulse,  off in 20us / 30ticks, 
  98 // ONE / ZERO bit pulse,   
  99 //    one == 80us / 120ticks 
 100 //    zero == 40us / 60ticks 
 102 # define COIL_PULSE(x) \ 
 105                 WaitTicks( (RWD_TIME_PAUSE) ); \ 
 111 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.  
 112 // Historically it used to be FREE_BUFFER_SIZE, which was 2744. 
 113 #define LEGIC_CARD_MEMSIZE 1024 
 114 static uint8_t* cardmem
; 
 116 static void frame_append_bit(struct legic_frame 
* const f
, uint8_t bit
) { 
 117         // Overflow, won't happen 
 118    if (f
->bits 
>= 31) return; 
 120    f
->data 
|= (bit 
<< f
->bits
); 
 124 static void frame_clean(struct legic_frame 
* const f
) { 
 129 // Prng works when waiting in 99.1us cycles. 
 130 // and while sending/receiving in bit frames (100, 60) 
 131 /*static void CalibratePrng( uint32_t time){ 
 132         // Calculate Cycles based on timer 100us 
 133         uint32_t i =  (time - sendFrameStop) / 100 ; 
 135         // substract cycles of finished frames 
 136         int k =  i - legic_prng_count()+1;  
 138         // substract current frame length, rewind to beginning 
 140                 legic_prng_forward(k); 
 144 /* Generate Keystream */ 
 145 uint32_t get_key_stream(int skip
, int count
) { 
 149         // Use int to enlarge timer tc to 32bit 
 150         legic_prng_bc 
+= prng_timer
->TC_CV
; 
 152         // reset the prng timer. 
 154         /* If skip == -1, forward prng time based */ 
 156                 i  
= (legic_prng_bc 
+ SIM_SHIFT
)/SIM_DIVISOR
; /* Calculate Cycles based on timer */ 
 157                 i 
-= legic_prng_count(); /* substract cycles of finished frames */ 
 158                 i 
-= count
; /* substract current frame length, rewind to beginning */ 
 159                 legic_prng_forward(i
); 
 161                 legic_prng_forward(skip
); 
 164         i 
= (count 
== 6) ? -1 : legic_read_count
; 
 166         /* Generate KeyStream */ 
 167         return legic_prng_get_bits(count
); 
 170 /* Send a frame in tag mode, the FPGA must have been set up by 
 173 void frame_send_tag(uint16_t response
, uint8_t bits
) { 
 177         /* Bitbang the response */ 
 179         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
 180         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
 182          /* TAG_FRAME_WAIT -> shift by 2 */ 
 183         legic_prng_forward(3); 
 184         response 
^= legic_prng_get_bits(bits
); 
 186         /* Wait for the frame start */ 
 187         WaitTicks( TAG_FRAME_WAIT 
); 
 189         for (; mask 
< BITMASK(bits
); mask 
<<= 1) {       
 194                 WaitTicks(TAG_BIT_PERIOD
); 
 199 /* Send a frame in reader mode, the FPGA must have been set up by 
 202 void frame_sendAsReader(uint32_t data
, uint8_t bits
){ 
 204         uint32_t starttime 
= GET_TICKS
, send 
= 0, mask 
= 1; 
 206         // xor lsfr onto data. 
 207         send 
= data 
^ legic_prng_get_bits(bits
); 
 209         for (; mask 
< BITMASK(bits
); mask 
<<= 1) {       
 211                         COIL_PULSE(RWD_TIME_1
) 
 213                         COIL_PULSE(RWD_TIME_0
) 
 216         // Final pause to mark the end of the frame 
 220         uint8_t cmdbytes
[] = {bits
, BYTEx(data
,0), BYTEx(data
,1), BYTEx(data
,2), BYTEx(send
,0), BYTEx(send
,1), BYTEx(send
,2)}; 
 221         LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, GET_TICKS
, NULL
, TRUE
); 
 224 /* Receive a frame from the card in reader emulation mode, the FPGA and 
 225  * timer must have been set up by LegicRfReader and frame_sendAsReader. 
 227  * The LEGIC RF protocol from card to reader does not include explicit 
 228  * frame start/stop information or length information. The reader must 
 229  * know beforehand how many bits it wants to receive. (Notably: a card 
 230  * sending a stream of 0-bits is indistinguishable from no card present.) 
 232  * Receive methodology: There is a fancy correlator in hi_read_rx_xcorr, but 
 233  * I'm not smart enough to use it. Instead I have patched hi_read_tx to output 
 234  * the ADC signal with hysteresis on SSP_DIN. Bit-bang that signal and look 
 235  * for edges. Count the edges in each bit interval. If they are approximately 
 236  * 0 this was a 0-bit, if they are approximately equal to the number of edges 
 237  * expected for a 212kHz subcarrier, this was a 1-bit. For timing we use the 
 238  * timer that's still running from frame_sendAsReader in order to get a synchronization 
 239  * with the frame that we just sent. 
 241  * FIXME: Because we're relying on the hysteresis to just do the right thing 
 242  * the range is severely reduced (and you'll probably also need a good antenna). 
 243  * So this should be fixed some time in the future for a proper receiver. 
 245 static void frame_receiveAsReader(struct legic_frame 
* const f
, uint8_t bits
) { 
 247         if ( bits 
> 32 ) return; 
 249         uint8_t i 
= bits
, edges 
= 0;     
 250         uint32_t the_bit 
= 1, next_bit_at 
= 0, data 
= 0; 
 251         uint32_t old_level 
= 0; 
 252         volatile uint32_t level 
= 0; 
 256         // calibrate the prng. 
 257         legic_prng_forward(2); 
 258         data 
= legic_prng_get_bits(bits
); 
 260         //FIXED time between sending frame and now listening frame. 330us 
 261         uint32_t starttime 
= GET_TICKS
; 
 262         // its about 9+9 ticks delay from end-send to here. 
 265         next_bit_at 
= GET_TICKS 
+ TAG_BIT_PERIOD
; 
 269                 while  ( GET_TICKS 
< next_bit_at
) { 
 271                         level 
= (AT91C_BASE_PIOA
->PIO_PDSR 
& GPIO_SSC_DIN
); 
 273                         if (level 
!= old_level
) 
 279                 next_bit_at 
+= TAG_BIT_PERIOD
; 
 281                 // We expect 42 edges (ONE) 
 293         uint8_t cmdbytes
[] = {bits
,     BYTEx(data
, 0), BYTEx(data
, 1)}; 
 294         LogTrace(cmdbytes
, sizeof(cmdbytes
), starttime
, GET_TICKS
, NULL
, FALSE
); 
 297 // Setup pm3 as a Legic Reader 
 298 static uint32_t setup_phase_reader(uint8_t iv
) { 
 300         // Switch on carrier and let the tag charge for 1ms 
 310         frame_sendAsReader(iv
, 7); 
 312         // Now both tag and reader has same IV. Prng can start. 
 315         frame_receiveAsReader(¤t_frame
, 6); 
 317         // 292us (438t) - fixed delay before sending ack. 
 318         // minus log and stuff 100tick? 
 320         legic_prng_forward(3);  
 322         // Send obsfuscated acknowledgment frame. 
 323         // 0x19 = 0x18 MIM22, 0x01 LSB READCMD  
 324         // 0x39 = 0x38 MIM256, MIM1024 0x01 LSB READCMD  
 325         switch ( current_frame
.data  
) { 
 326                 case 0x0D: frame_sendAsReader(0x19, 6); break; 
 328                 case 0x3D: frame_sendAsReader(0x39, 6); break; 
 332         legic_prng_forward(2); 
 333         return current_frame
.data
; 
 336 void LegicCommonInit(bool clear_mem
) { 
 338         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 339         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
); 
 340         SetAdcMuxFor(GPIO_MUXSEL_HIPKD
); 
 342         /* Bitbang the transmitter */ 
 344         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_SSC_DOUT
; 
 345         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DOUT
; 
 346         AT91C_BASE_PIOA
->PIO_ODR 
= GPIO_SSC_DIN
; 
 348         // reserve a cardmem,  meaning we can use the tracelog function in bigbuff easier. 
 349         cardmem 
= BigBuf_get_EM_addr(); 
 351                 memset(cardmem
, 0x00, LEGIC_CARD_MEMSIZE
); 
 355         crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0); 
 360 // Switch off carrier, make sure tag is reset 
 361 static void switch_off_tag_rwd(void) { 
 367 // calculate crc4 for a legic READ command  
 368 static uint32_t legic4Crc(uint8_t cmd
, uint16_t byte_index
, uint8_t value
, uint8_t cmd_sz
) { 
 369         crc_clear(&legic_crc
);   
 370         uint32_t temp 
=  (value 
<< cmd_sz
) | (byte_index 
<< 1) | cmd
; 
 371         crc_update(&legic_crc
, temp
, cmd_sz 
+ 8 ); 
 372         return crc_finish(&legic_crc
); 
 375 int legic_read_byte( uint16_t index
, uint8_t cmd_sz
) { 
 377         uint8_t byte
, crc
, calcCrc 
= 0; 
 378         uint32_t cmd 
= (index 
<< 1) | LEGIC_READ
; 
 380         // 90ticks = 60us (should be 100us but crc calc takes time.) 
 381         //WaitTicks(330); // 330ticks prng(4) - works 
 382         WaitTicks(240); // 240ticks prng(3) - works 
 384         frame_sendAsReader(cmd
, cmd_sz
); 
 385         frame_receiveAsReader(¤t_frame
, 12); 
 388         byte 
= BYTEx(current_frame
.data
, 0); 
 389         crc 
= BYTEx(current_frame
.data
, 1); 
 390         calcCrc 
= legic4Crc(LEGIC_READ
, index
, byte
, cmd_sz
); 
 392         if( calcCrc 
!= crc 
) { 
 393                 Dbprintf("!!! crc mismatch: %x != %x !!!",  calcCrc
, crc
); 
 397         legic_prng_forward(3); 
 402  * - assemble a write_cmd_frame with crc and send it 
 403  * - wait until the tag sends back an ACK ('1' bit unencrypted) 
 404  * - forward the prng based on the timing 
 406 bool legic_write_byte(uint16_t index
, uint8_t byte
, uint8_t addr_sz
) { 
 411         uint8_t cmd_sz 
= addr_sz
+1+8+4; //crc+data+cmd; 
 412         uint32_t steps 
= 0, next_bit_at
, start
, crc
, old_level 
= 0; 
 414         crc 
= legic4Crc(LEGIC_WRITE
, index
, byte
, addr_sz
+1); 
 416         // send write command 
 417         uint32_t cmd 
= LEGIC_WRITE
; 
 418         cmd 
|= index 
<< 1;                        // index 
 419         cmd 
|= byte  
<< (addr_sz
+1);  // Data    
 420         cmd     
|= (crc 
& 0xF ) << (addr_sz
+1+8);       // CRC 
 424         frame_sendAsReader(cmd
, cmd_sz
); 
 430         // ACK,  - one single "1" bit after 3.6ms 
 431         // 3.6ms = 3600us * 1.5 = 5400ticks. 
 434         next_bit_at 
= GET_TICKS 
+ TAG_BIT_PERIOD
; 
 439         while ( GET_TICKS 
< next_bit_at
) { 
 441             volatile uint32_t level 
= (AT91C_BASE_PIOA
->PIO_PDSR 
& GPIO_SSC_DIN
); 
 443                         if (level 
!= old_level
) 
 449                 next_bit_at 
+= TAG_BIT_PERIOD
; 
 451                 // We expect 42 edges (ONE) 
 453                         steps 
= ( (GET_TICKS 
- start
) / TAG_BIT_PERIOD
);                         
 454                         legic_prng_forward(steps
); 
 461         legic_prng_forward(1); 
 463         uint8_t cmdbytes
[] = {1, isOK
, BYTEx(steps
, 0), BYTEx(steps
, 1) }; 
 464         LogTrace(cmdbytes
, sizeof(cmdbytes
), start
, GET_TICKS
, NULL
, FALSE
); 
 468 int LegicRfReader(uint16_t offset
, uint16_t len
, uint8_t iv
) { 
 472         legic_card_select_t card
; 
 474         LegicCommonInit(TRUE
); 
 476         if ( legic_select_card_iv(&card
, iv
) ) { 
 481         if (len 
+ offset 
> card
.cardsize
) 
 482                 len 
= card
.cardsize 
- offset
; 
 486                 int r 
= legic_read_byte(offset 
+ i
, card
.cmdsize
); 
 488                 if (r 
== -1 || BUTTON_PRESS()) {                         
 489                 if ( MF_DBGLEVEL 
>= 2) DbpString("operation aborted"); 
 499         switch_off_tag_rwd(); 
 501         cmd_send(CMD_ACK
, isOK
, len
, 0, cardmem
, len
); 
 505 void LegicRfWriter(uint16_t offset
, uint16_t len
, uint8_t iv
, uint8_t *data
) { 
 508         uint8_t isOK 
= 1, msg 
= 0; 
 509         legic_card_select_t card
; 
 511         // uid NOT is writeable. 
 512         if ( offset 
<= LOWERLIMIT 
) { 
 517         LegicCommonInit(TRUE
); 
 519         if ( legic_select_card_iv(&card
, iv
) ) { 
 525         if ( len 
+ offset 
> card
.cardsize
) 
 526                 len 
= card
.cardsize 
- offset
; 
 531                 if ( !legic_write_byte( len 
+ offset
, data
[len
], card
.addrsize
) ) { 
 532                         Dbprintf("operation failed | %02X | %02X | %02X", len 
+ offset
, len
, data
[len
] ); 
 539         cmd_send(CMD_ACK
, isOK
, msg
,0,0,0); 
 540         switch_off_tag_rwd(); 
 544 int legic_select_card_iv(legic_card_select_t 
*p_card
, uint8_t iv
){ 
 546         if ( p_card 
== NULL 
) return 1; 
 548         p_card
->tagtype 
= setup_phase_reader(iv
); 
 550         switch(p_card
->tagtype
) { 
 553                         p_card
->addrsize 
= 5; 
 554                         p_card
->cardsize 
= 22; 
 558                         p_card
->addrsize 
= 8; 
 559                         p_card
->cardsize 
= 256; 
 562             p_card
->cmdsize 
= 11; 
 563                         p_card
->addrsize 
= 10; 
 564                         p_card
->cardsize 
= 1024; 
 568                         p_card
->addrsize 
= 0; 
 569                         p_card
->cardsize 
= 0; 
 574 int legic_select_card(legic_card_select_t 
*p_card
){ 
 575         return legic_select_card_iv(p_card
, 0x01); 
 578 //----------------------------------------------------------------------------- 
 579 // Work with emulator memory 
 581 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not 
 582 // involved in dealing with emulator memory. But if it is called later, it might 
 583 // destroy the Emulator Memory. 
 584 //----------------------------------------------------------------------------- 
 586 // arg1 = num of bytes 
 587 void LegicEMemSet(uint32_t arg0
, uint32_t arg1
, uint8_t *data
) { 
 588         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 589         legic_emlset_mem(data
, arg0
, arg1
); 
 592 // arg1 = num of bytes 
 593 void LegicEMemGet(uint32_t arg0
, uint32_t arg1
) { 
 594         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 595         uint8_t buf
[USB_CMD_DATA_SIZE
] = {0x00}; 
 596         legic_emlget_mem(buf
, arg0
, arg1
); 
 598         cmd_send(CMD_ACK
, arg0
, arg1
, 0, buf
, USB_CMD_DATA_SIZE
); 
 601 void legic_emlset_mem(uint8_t *data
, int offset
, int numofbytes
) { 
 602         cardmem 
= BigBuf_get_EM_addr(); 
 603         memcpy(cardmem 
+ offset
, data
, numofbytes
); 
 605 void legic_emlget_mem(uint8_t *data
, int offset
, int numofbytes
) { 
 606         cardmem 
= BigBuf_get_EM_addr(); 
 607         memcpy(data
, cardmem 
+ offset
, numofbytes
); 
 610 void LegicRfInfo(void){ 
 614         uint8_t buf
[sizeof(legic_card_select_t
)] = {0x00}; 
 615         legic_card_select_t 
*card 
= (legic_card_select_t
*) buf
; 
 617         LegicCommonInit(FALSE
); 
 619         if ( legic_select_card(card
) ) { 
 620                 cmd_send(CMD_ACK
,0,0,0,0,0); 
 625         for ( uint8_t i 
= 0; i 
< sizeof(card
->uid
); ++i
) { 
 626                 r 
= legic_read_byte(i
, card
->cmdsize
); 
 628                         cmd_send(CMD_ACK
,0,0,0,0,0); 
 631                 card
->uid
[i
] = r 
& 0xFF; 
 635         r 
= legic_read_byte(4, card
->cmdsize
); 
 636         uint32_t calc_mcc 
=  CRC8Legic(card
->uid
, 4);; 
 637         if ( r 
!= calc_mcc
) { 
 638                 cmd_send(CMD_ACK
,0,0,0,0,0); 
 643         cmd_send(CMD_ACK
, 1, 0, 0, buf
, sizeof(legic_card_select_t
)); 
 646         switch_off_tag_rwd(); 
 650 /* Handle (whether to respond) a frame in tag mode 
 651  * Only called when simulating a tag. 
 653 static void frame_handle_tag(struct legic_frame 
const * const f
) 
 656         //uint8_t cmdbytes[] = {bits,   BYTEx(data, 0), BYTEx(data, 1)}; 
 657         //LogTrace(cmdbytes, sizeof(cmdbytes), starttime, GET_TICKS, NULL, FALSE); 
 658         Dbprintf("ICE: enter frame_handle_tag: %02x ", f
->bits
); 
 660         /* First Part of Handshake (IV) */ 
 666                 //ResetTimer(prng_timer); 
 670                 legic_prng_init(f
->data
); 
 672                 Dbprintf("ICE: IV: %02x ", f
->data
); 
 674                 // We should have three tagtypes with three different answers. 
 675                 legic_prng_forward(2); 
 676                 //frame_send_tag(0x3d, 6); /* MIM1024 0x3d^0x26 = 0x1B */ 
 677                 frame_send_tag(0x1d, 6); // MIM256 
 679                 legic_state 
= STATE_IV
; 
 680                 legic_read_count 
= 0; 
 682                 legic_prng_iv 
= f
->data
; 
 691    if(legic_state 
== STATE_IV
) { 
 692       uint32_t local_key 
= get_key_stream(3, 6); 
 693       int xored 
= 0x39 ^ local_key
; 
 694       if((f
->bits 
== 6) && (f
->data 
== xored
)) { 
 695          legic_state 
= STATE_CON
; 
 704          legic_state 
= STATE_DISCON
; 
 706          Dbprintf("iv: %02x frame: %02x key: %02x xored: %02x", legic_prng_iv
, f
->data
, local_key
, xored
); 
 713       if(legic_state 
== STATE_CON
) { 
 714          uint32_t key 
= get_key_stream(2, 11); //legic_phase_drift, 11); 
 715          uint16_t addr 
= f
->data 
^ key
;  
 717          uint8_t data 
= cardmem
[addr
]; 
 719          uint32_t crc 
= legic4Crc(LEGIC_READ
, addr
, data
, 11) << 8; 
 721          //legic_read_count++; 
 722          //legic_prng_forward(legic_reqresp_drift); 
 724          frame_send_tag(crc 
| data
, 12); 
 726          legic_prng_forward(2); 
 733    if (f
->bits 
== 23 || f
->bits 
== 21 ) { 
 734       uint32_t key  
= get_key_stream(-1, 23); //legic_frame_drift, 23); 
 735       uint16_t addr 
= f
->data 
^ key
;  
 738       uint32_t data 
= f
->data 
^ key
;  
 742           cardmem
[addr
] = data
; 
 744       legic_state 
= STATE_DISCON
; 
 746       Dbprintf("write - addr: %x, data: %x", addr
, data
); 
 747           // should send a ACK after 3.6ms  
 751    if(legic_state 
!= STATE_DISCON
) { 
 752       Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f
->bits
, f
->data
, legic_state
, legic_read_count
); 
 753       Dbprintf("IV: %03.3x", legic_prng_iv
); 
 756         legic_state 
= STATE_DISCON
;  
 757         legic_read_count 
= 0; 
 763 /* Read bit by bit untill full frame is received 
 764  * Call to process frame end answer 
 766 static void emit(int bit
) { 
 768         Dbprintf("ICE: enter emit:"); 
 771                         frame_append_bit(¤t_frame
, 1); 
 774                         frame_append_bit(¤t_frame
, 0); 
 777                         if(current_frame
.bits 
<= 4) { 
 778                                 frame_clean(¤t_frame
); 
 780                                 frame_handle_tag(¤t_frame
); 
 781                                 frame_clean(¤t_frame
); 
 788 void LegicRfSimulate(int phase
, int frame
, int reqresp
) 
 790   /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,  
 791    * modulation mode set to 212kHz subcarrier. We are getting the incoming raw 
 792    * envelope waveform on DIN and should send our response on DOUT. 
 794    * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll 
 795    * measure the time between two rising edges on DIN, and no encoding on the 
 796    * subcarrier from card to reader, so we'll just shift out our verbatim data 
 797    * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear, 
 801         int old_level 
= 0, active 
= 0; 
 802         volatile uint32_t level 
= 0; 
 804         legic_state 
= STATE_DISCON
; 
 805         legic_phase_drift 
= phase
; 
 806         legic_frame_drift 
= frame
; 
 807         legic_reqresp_drift 
= reqresp
; 
 809         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 811         /* to get the stream of bits from FPGA in sim mode.*/ 
 812         SetAdcMuxFor(GPIO_MUXSEL_HIPKD
); 
 814         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR 
| FPGA_HF_SIMULATOR_MODULATE_212K
); 
 816         /* Bitbang the receiver */ 
 818         AT91C_BASE_PIOA
->PIO_ODR 
= GPIO_SSC_DIN
; 
 819         AT91C_BASE_PIOA
->PIO_PER 
= GPIO_SSC_DIN
; 
 821         // need a way to determine which tagtype we are simulating 
 823         // hook up emulator memory   
 824         cardmem 
= BigBuf_get_EM_addr(); 
 829         crc_init(&legic_crc
, 4, 0x19 >> 1, 0x5, 0); 
 834         DbpString("Starting Legic emulator, press button to end"); 
 836         while(!BUTTON_PRESS() && !usb_poll_validate_length()) { 
 838                 level 
= !!(AT91C_BASE_PIOA
->PIO_PDSR 
& GPIO_SSC_DIN
); 
 840                 uint32_t time 
= GET_TICKS
; 
 842                 if (level 
!= old_level
) { 
 848                                 if (FUZZ_EQUAL(time
, RWD_TIME_1
, RWD_TIME_FUZZ
)) { 
 853                                 } else if (FUZZ_EQUAL(time
, RWD_TIME_0
, RWD_TIME_FUZZ
)) { 
 868                 if(time 
>= (RWD_TIME_1 
+ RWD_TIME_FUZZ
) && active
) { 
 875                 * Disable the counter, Then wait for the clock to acknowledge the 
 876                 * shutdown in its status register. Reading the SR has the 
 877                 * side-effect of clearing any pending state in there. 
 879                 //if(time >= (20*RWD_TIME_1) && (timer->TC_SR & AT91C_TC_CLKSTA)) 
 880                 //if(time >= (20 * RWD_TIME_1) ) 
 888         DbpString("LEGIC Prime emulator stopped"); 
 889         switch_off_tag_rwd(); 
 891         cmd_send(CMD_ACK
, 1, 0, 0, 0, 0); 
 894 //----------------------------------------------------------------------------- 
 895 // Code up a string of octets at layer 2 (including CRC, we don't generate 
 896 // that here) so that they can be transmitted to the reader. Doesn't transmit 
 897 // them yet, just leaves them ready to send in ToSend[]. 
 898 //----------------------------------------------------------------------------- 
 899 // static void CodeLegicAsTag(const uint8_t *cmd, int len) 
 905         // // Transmit a burst of ones, as the initial thing that lets the 
 906         // // reader get phase sync. This (TR1) must be > 80/fs, per spec, 
 907         // // but tag that I've tried (a Paypass) exceeds that by a fair bit, 
 909         // for(i = 0; i < 20; i++) { 
 910                 // ToSendStuffBit(1); 
 911                 // ToSendStuffBit(1); 
 912                 // ToSendStuffBit(1); 
 913                 // ToSendStuffBit(1); 
 917         // for(i = 0; i < 10; i++) { 
 918                 // ToSendStuffBit(0); 
 919                 // ToSendStuffBit(0); 
 920                 // ToSendStuffBit(0); 
 921                 // ToSendStuffBit(0); 
 923         // for(i = 0; i < 2; i++) { 
 924                 // ToSendStuffBit(1); 
 925                 // ToSendStuffBit(1); 
 926                 // ToSendStuffBit(1); 
 927                 // ToSendStuffBit(1); 
 930         // for(i = 0; i < len; i++) { 
 932                 // uint8_t b = cmd[i]; 
 935                 // ToSendStuffBit(0); 
 936                 // ToSendStuffBit(0); 
 937                 // ToSendStuffBit(0); 
 938                 // ToSendStuffBit(0); 
 941                 // for(j = 0; j < 8; j++) { 
 943                                 // ToSendStuffBit(1); 
 944                                 // ToSendStuffBit(1); 
 945                                 // ToSendStuffBit(1); 
 946                                 // ToSendStuffBit(1); 
 948                                 // ToSendStuffBit(0); 
 949                                 // ToSendStuffBit(0); 
 950                                 // ToSendStuffBit(0); 
 951                                 // ToSendStuffBit(0); 
 957                 // ToSendStuffBit(1); 
 958                 // ToSendStuffBit(1); 
 959                 // ToSendStuffBit(1); 
 960                 // ToSendStuffBit(1); 
 964         // for(i = 0; i < 10; i++) { 
 965                 // ToSendStuffBit(0); 
 966                 // ToSendStuffBit(0); 
 967                 // ToSendStuffBit(0); 
 968                 // ToSendStuffBit(0); 
 970         // for(i = 0; i < 2; i++) { 
 971                 // ToSendStuffBit(1); 
 972                 // ToSendStuffBit(1); 
 973                 // ToSendStuffBit(1); 
 974                 // ToSendStuffBit(1); 
 977         // // Convert from last byte pos to length 
 981 //----------------------------------------------------------------------------- 
 982 // The software UART that receives commands from the reader, and its state 
 984 //----------------------------------------------------------------------------- 
 989                 STATE_GOT_FALLING_EDGE_OF_SOF, 
 990                 STATE_AWAITING_START_BIT, 
1001 /* Receive & handle a bit coming from the reader. 
1003  * This function is called 4 times per bit (every 2 subcarrier cycles). 
1004  * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us 
1007  * LED A -> ON once we have received the SOF and are expecting the rest. 
1008  * LED A -> OFF once we have received EOF or are in error state or unsynced 
1010  * Returns: true if we received a EOF 
1011  *          false if we are still waiting for some more 
1013 // static RAMFUNC int HandleLegicUartBit(uint8_t bit) 
1015         // switch(Uart.state) { 
1016                 // case STATE_UNSYNCD: 
1018                                 // // we went low, so this could be the beginning of an SOF 
1019                                 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF; 
1025                 // case STATE_GOT_FALLING_EDGE_OF_SOF: 
1027                         // if(Uart.posCnt == 2) {       // sample every 4 1/fs in the middle of a bit 
1029                                         // if(Uart.bitCnt > 9) { 
1030                                                 // // we've seen enough consecutive 
1031                                                 // // zeros that it's a valid SOF 
1033                                                 // Uart.byteCnt = 0; 
1034                                                 // Uart.state = STATE_AWAITING_START_BIT; 
1035                                                 // LED_A_ON(); // Indicate we got a valid SOF 
1037                                                 // // didn't stay down long enough 
1038                                                 // // before going high, error 
1039                                                 // Uart.state = STATE_UNSYNCD; 
1042                                         // // do nothing, keep waiting 
1046                         // if(Uart.posCnt >= 4) Uart.posCnt = 0; 
1047                         // if(Uart.bitCnt > 12) { 
1048                                 // // Give up if we see too many zeros without 
1051                                 // Uart.state = STATE_UNSYNCD; 
1055                 // case STATE_AWAITING_START_BIT: 
1058                                 // if(Uart.posCnt > 50/2) {     // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs 
1059                                         // // stayed high for too long between 
1060                                         // // characters, error 
1061                                         // Uart.state = STATE_UNSYNCD; 
1064                                 // // falling edge, this starts the data byte 
1067                                 // Uart.shiftReg = 0; 
1068                                 // Uart.state = STATE_RECEIVING_DATA; 
1072                 // case STATE_RECEIVING_DATA: 
1074                         // if(Uart.posCnt == 2) { 
1075                                 // // time to sample a bit 
1076                                 // Uart.shiftReg >>= 1; 
1078                                         // Uart.shiftReg |= 0x200; 
1082                         // if(Uart.posCnt >= 4) { 
1085                         // if(Uart.bitCnt == 10) { 
1086                                 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001)) 
1088                                         // // this is a data byte, with correct 
1089                                         // // start and stop bits 
1090                                         // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff; 
1093                                         // if(Uart.byteCnt >= Uart.byteCntMax) { 
1094                                                 // // Buffer overflowed, give up 
1096                                                 // Uart.state = STATE_UNSYNCD; 
1098                                                 // // so get the next byte now 
1100                                                 // Uart.state = STATE_AWAITING_START_BIT; 
1102                                 // } else if (Uart.shiftReg == 0x000) { 
1103                                         // // this is an EOF byte 
1104                                         // LED_A_OFF(); // Finished receiving 
1105                                         // Uart.state = STATE_UNSYNCD; 
1106                                         // if (Uart.byteCnt != 0) { 
1110                                         // // this is an error 
1112                                         // Uart.state = STATE_UNSYNCD; 
1119                         // Uart.state = STATE_UNSYNCD; 
1127 static void UartReset() { 
1128         Uart.byteCntMax = 3; 
1129         Uart.state = STATE_UNSYNCD; 
1133         memset(Uart.output, 0x00, 3); 
1136 // static void UartInit(uint8_t *data) { 
1137         // Uart.output = data; 
1141 //============================================================================= 
1142 // An LEGIC reader. We take layer two commands, code them 
1143 // appropriately, and then send them to the tag. We then listen for the 
1144 // tag's response, which we leave in the buffer to be demodulated on the 
1146 //============================================================================= 
1151                 DEMOD_PHASE_REF_TRAINING, 
1152                 DEMOD_AWAITING_FALLING_EDGE_OF_SOF, 
1153                 DEMOD_GOT_FALLING_EDGE_OF_SOF, 
1154                 DEMOD_AWAITING_START_BIT, 
1155                 DEMOD_RECEIVING_DATA 
1168  * Handles reception of a bit from the tag 
1170  * This function is called 2 times per bit (every 4 subcarrier cycles). 
1171  * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us 
1174  * LED C -> ON once we have received the SOF and are expecting the rest. 
1175  * LED C -> OFF once we have received EOF or are unsynced 
1177  * Returns: true if we received a EOF 
1178  *          false if we are still waiting for some more 
1183 static RAMFUNC int HandleLegicSamplesDemod(int ci, int cq) 
1188         int halfci = (ai >> 1); 
1189         int halfcq = (aq >> 1); 
1191         switch(Demod.state) { 
1194                         CHECK_FOR_SUBCARRIER() 
1196                         if(v > SUBCARRIER_DETECT_THRESHOLD) {   // subcarrier detected 
1197                                 Demod.state = DEMOD_PHASE_REF_TRAINING; 
1204                 case DEMOD_PHASE_REF_TRAINING: 
1205                         if(Demod.posCount < 8) { 
1207                                 CHECK_FOR_SUBCARRIER() 
1209                                 if (v > SUBCARRIER_DETECT_THRESHOLD) { 
1210                                         // set the reference phase (will code a logic '1') by averaging over 32 1/fs. 
1211                                         // note: synchronization time > 80 1/fs 
1217                                         Demod.state = DEMOD_UNSYNCD; 
1220                                 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF; 
1224                 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF: 
1226                         MAKE_SOFT_DECISION() 
1228                         //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq ); 
1229                         // logic '0' detected 
1232                                 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF; 
1234                                 // start of SOF sequence 
1237                                 // maximum length of TR1 = 200 1/fs 
1238                                 if(Demod.posCount > 25*2) Demod.state = DEMOD_UNSYNCD; 
1243                 case DEMOD_GOT_FALLING_EDGE_OF_SOF: 
1246                         MAKE_SOFT_DECISION() 
1249                                 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges 
1250                                 if(Demod.posCount < 10*2) {  
1251                                         Demod.state = DEMOD_UNSYNCD; 
1253                                         LED_C_ON(); // Got SOF 
1254                                         Demod.state = DEMOD_AWAITING_START_BIT; 
1259                                 // low phase of SOF too long (> 12 etu) 
1260                                 if(Demod.posCount > 13*2) {  
1261                                         Demod.state = DEMOD_UNSYNCD; 
1267                 case DEMOD_AWAITING_START_BIT: 
1270                         MAKE_SOFT_DECISION() 
1273                                 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs 
1274                                 if(Demod.posCount > 3*2) {  
1275                                         Demod.state = DEMOD_UNSYNCD; 
1279                                 // start bit detected 
1281                                 Demod.posCount = 1;                             // this was the first half 
1284                                 Demod.state = DEMOD_RECEIVING_DATA; 
1288                 case DEMOD_RECEIVING_DATA: 
1290                         MAKE_SOFT_DECISION() 
1292                         if(Demod.posCount == 0) { 
1293                                 // first half of bit 
1297                                 // second half of bit 
1299                                 Demod.shiftReg >>= 1; 
1301                                 if(Demod.thisBit > 0)  
1302                                         Demod.shiftReg |= 0x200; 
1306                                 if(Demod.bitCount == 10) { 
1308                                         uint16_t s = Demod.shiftReg; 
1310                                         if((s & 0x200) && !(s & 0x001)) {  
1311                                                 // stop bit == '1', start bit == '0' 
1312                                                 uint8_t b = (s >> 1); 
1313                                                 Demod.output[Demod.len] = b; 
1315                                                 Demod.state = DEMOD_AWAITING_START_BIT; 
1317                                                 Demod.state = DEMOD_UNSYNCD; 
1321                                                         // This is EOF (start, stop and all data bits == '0' 
1331                         Demod.state = DEMOD_UNSYNCD; 
1339 // Clear out the state of the "UART" that receives from the tag. 
1340 static void DemodReset() { 
1342         Demod.state = DEMOD_UNSYNCD; 
1349         memset(Demod.output, 0x00, 3); 
1352 static void DemodInit(uint8_t *data) { 
1353         Demod.output = data; 
1359  *  Demodulate the samples we received from the tag, also log to tracebuffer 
1360  *  quiet: set to 'TRUE' to disable debug output 
1364  #define LEGIC_DMA_BUFFER_SIZE 256 
1366  static void GetSamplesForLegicDemod(int n, bool quiet) 
1369         bool gotFrame = FALSE; 
1370         int lastRxCounter = LEGIC_DMA_BUFFER_SIZE; 
1371         int     ci, cq, samples = 0; 
1375         // And put the FPGA in the appropriate mode 
1376         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ); 
1378         // The response (tag -> reader) that we're receiving. 
1379         // Set up the demodulator for tag -> reader responses. 
1380         DemodInit(BigBuf_malloc(MAX_FRAME_SIZE)); 
1382         // The DMA buffer, used to stream samples from the FPGA 
1383         int8_t *dmaBuf = (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE); 
1384         int8_t *upTo = dmaBuf; 
1386         // Setup and start DMA. 
1387         if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, LEGIC_DMA_BUFFER_SIZE) ){ 
1388                 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");  
1392         // Signal field is ON with the appropriate LED: 
1395                 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR; 
1396                 if(behindBy > max) max = behindBy; 
1398                 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (LEGIC_DMA_BUFFER_SIZE-1)) > 2) { 
1402                         if(upTo >= dmaBuf + LEGIC_DMA_BUFFER_SIZE) { 
1404                                 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo; 
1405                                 AT91C_BASE_PDC_SSC->PDC_RNCR = LEGIC_DMA_BUFFER_SIZE; 
1408                         if(lastRxCounter <= 0) 
1409                                 lastRxCounter = LEGIC_DMA_BUFFER_SIZE; 
1413                         gotFrame = HandleLegicSamplesDemod(ci , cq ); 
1418                 if(samples > n || gotFrame) 
1422         FpgaDisableSscDma(); 
1424         if (!quiet && Demod.len == 0) { 
1425                 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d", 
1436         if (Demod.len > 0) { 
1437                 uint8_t parity[MAX_PARITY_SIZE] = {0x00}; 
1438                 LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE); 
1444 //----------------------------------------------------------------------------- 
1445 // Transmit the command (to the tag) that was placed in ToSend[]. 
1446 //----------------------------------------------------------------------------- 
1448 static void TransmitForLegic(void) 
1454         while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) 
1455                 AT91C_BASE_SSC->SSC_THR = 0xff; 
1457         // Signal field is ON with the appropriate Red LED 
1460         // Signal we are transmitting with the Green LED 
1462         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); 
1464         for(c = 0; c < 10;) { 
1465                 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { 
1466                         AT91C_BASE_SSC->SSC_THR = 0xff; 
1469                 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { 
1470                         volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR; 
1478                 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { 
1479                         AT91C_BASE_SSC->SSC_THR = ToSend[c]; 
1480                         legic_prng_forward(1); // forward the lfsr  
1482                         if(c >= ToSendMax) { 
1486                 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { 
1487                         volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR; 
1496 //----------------------------------------------------------------------------- 
1497 // Code a layer 2 command (string of octets, including CRC) into ToSend[], 
1498 // so that it is ready to transmit to the tag using TransmitForLegic(). 
1499 //----------------------------------------------------------------------------- 
1501 static void CodeLegicBitsAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits) 
1509         for(i = 0; i < 7; i++) 
1513         for(i = 0; i < cmdlen; i++) { 
1519                 for(j = 0; j < bits; j++) { 
1529         // Convert from last character reference to length 
1534   Convenience function to encode, transmit and trace Legic comms 
1537   static void CodeAndTransmitLegicAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits) 
1539         CodeLegicBitsAsReader(cmd, cmdlen, bits); 
1542                 uint8_t parity[1] = {0x00}; 
1543                 LogTrace(cmd, cmdlen, 0, 0, parity, TRUE); 
1548 // Set up LEGIC communication 
1550 void ice_legic_setup() { 
1553         FpgaDownloadAndGo(FPGA_BITSTREAM_HF); 
1554         BigBuf_free(); BigBuf_Clear_ext(false); 
1560         // Set up the synchronous serial port 
1563         // connect Demodulated Signal to ADC: 
1564         SetAdcMuxFor(GPIO_MUXSEL_HIPKD); 
1566         // Signal field is on with the appropriate LED 
1568         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); 
1571         //StartCountSspClk(); 
1574         crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);