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