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