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