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