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