aboutsummaryrefslogtreecommitdiffstats
path: root/firmware/libcommon/source/mode_cardemu.c
blob: d5405c2e99fe6a0ea9b4ee72d00f76c583b6d836 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
/* card emulation mode
 *
 * (C) 2015-2017 by Harald Welte <laforge@gnumonks.org>
 * (C) 2018-2019 by sysmocom -s.f.m.c. GmbH, Author: Kevin Redon <kredon@sysmocom.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA
 */
#include "board.h"
#include "boardver_adc.h"
#include "simtrace.h"
#include "ringbuffer.h"
#include "card_emu.h"
#include "iso7816_3.h"
#include "utils.h"
#include <osmocom/core/linuxlist.h>
#include <osmocom/core/msgb.h>
#include "llist_irqsafe.h"
#include "usb_buf.h"
#include "simtrace_usb.h"
#include "simtrace_prot.h"
#include "sim_switch.h"

#define TRACE_ENTRY()	TRACE_DEBUG("%s entering\r\n", __func__)

#ifdef PINS_CARDSIM
static const Pin pins_cardsim[] = PINS_CARDSIM;
#endif

/* UART pins */
static const Pin pins_usim1[]	= {PINS_USIM1};
static const Pin pin_usim1_rst	= PIN_USIM1_nRST;
static const Pin pin_usim1_vcc	= PIN_USIM1_VCC;

#ifdef CARDEMU_SECOND_UART
static const Pin pins_usim2[]    = {PINS_USIM2};
static const Pin pin_usim2_rst	= PIN_USIM2_nRST;
static const Pin pin_usim2_vcc	= PIN_USIM2_VCC;
#endif

struct cardem_inst {
	unsigned int num;
	struct card_handle *ch;
	struct llist_head usb_out_queue;
	struct ringbuf rb;
	uint32_t wt; /*!< receiver waiting time to trigger timeout (0 to deactivate it) */
	uint32_t wt_remaining; /*!< remaining waiting time */
	bool wt_halfed; /*!< if at least half of the waiting time passed */
	struct Usart_info usart_info;
	int usb_pending_old;
	uint8_t ep_out;
	uint8_t ep_in;
	uint8_t ep_int;
	const Pin pin_io;
	const Pin pin_insert;
	uint32_t vcc_uv;
	uint32_t vcc_uv_last;
};

struct cardem_inst cardem_inst[] = {
	{
		.num = 0,
		.usart_info = 	{
			.base = USART1,
			.id = ID_USART1,
			.state = USART_RCV
		},
		.ep_out = SIMTRACE_CARDEM_USB_EP_USIM1_DATAOUT,
		.ep_in = SIMTRACE_CARDEM_USB_EP_USIM1_DATAIN,
		.ep_int = SIMTRACE_CARDEM_USB_EP_USIM1_INT,
		.pin_io = PIN_USIM1_IO,
#ifdef PIN_SET_USIM1_PRES
		.pin_insert = PIN_SET_USIM1_PRES,
#endif
	},
#ifdef CARDEMU_SECOND_UART
	{
		.num = 1,
		.usart_info = {
			.base = USART0,
			.id = ID_USART0,
			.state = USART_RCV
		},
		.ep_out = SIMTRACE_CARDEM_USB_EP_USIM2_DATAOUT,
		.ep_in = SIMTRACE_CARDEM_USB_EP_USIM2_DATAIN,
		.ep_int = SIMTRACE_CARDEM_USB_EP_USIM2_INT,
		.pin_io = PIN_USIM2_IO,
#ifdef PIN_SET_USIM2_PRES
		.pin_insert = PIN_SET_USIM2_PRES,
#endif
	},
#endif
};

static Usart *get_usart_by_chan(uint8_t uart_chan)
{
	if (uart_chan < ARRAY_SIZE(cardem_inst)) {
		return cardem_inst[uart_chan].usart_info.base;
	} else {
		return NULL;
	}
}

/***********************************************************************
 * Call-Backs from card_emu.c
 ***********************************************************************/

static void wait_tx_idle(Usart *usart)
{
	int i = 1;

	/* wait until last char has been fully transmitted */
	while ((usart->US_CSR & (US_CSR_TXEMPTY)) == 0) {
		if (!(i%1000000)) {
			TRACE_ERROR("s: %lx \r\n", usart->US_CSR);
		}
		i++;
	}
}

void card_emu_uart_wait_tx_idle(uint8_t uart_chan)
{
	Usart *usart = get_usart_by_chan(uart_chan);
	wait_tx_idle(usart);
}

/* call-back from card_emu.c to enable/disable transmit and/or receive */
void card_emu_uart_enable(uint8_t uart_chan, uint8_t rxtx)
{
	Usart *usart = get_usart_by_chan(uart_chan);
	switch (rxtx) {
	case ENABLE_TX:
		USART_DisableIt(usart, ~US_IER_TXRDY);
		/* as irritating as it is, we actually want to keep the
		 * receiver enabled during transmit */
		USART_SetReceiverEnabled(usart, 1);
		usart->US_CR = US_CR_RSTSTA | US_CR_RSTIT | US_CR_RSTNACK;
		USART_EnableIt(usart, US_IER_TXRDY | US_IER_TIMEOUT);
		USART_SetTransmitterEnabled(usart, 1);
		break;
	case ENABLE_RX:
		USART_DisableIt(usart, ~US_IER_RXRDY);
		/* as irritating as it is, we actually want to keep the
		 * transmitter enabled during receive */
		USART_SetTransmitterEnabled(usart, 1);
		wait_tx_idle(usart);
		usart->US_CR = US_CR_RSTSTA | US_CR_RSTIT | US_CR_RSTNACK;
		USART_EnableIt(usart, US_IER_RXRDY | US_IER_TIMEOUT);
		USART_SetReceiverEnabled(usart, 1);
		break;
	case 0:
	default:
		USART_SetTransmitterEnabled(usart, 0);
		USART_SetReceiverEnabled(usart, 0);
		USART_DisableIt(usart, 0xFFFFFFFF);
		usart->US_CR = US_CR_RSTSTA | US_CR_RSTIT | US_CR_RSTNACK;
		break;
	}
}

/* call-back from card_emu.c to transmit a byte */
int card_emu_uart_tx(uint8_t uart_chan, uint8_t byte)
{
	Usart *usart = get_usart_by_chan(uart_chan);
#if 0
	Usart_info *ui = &usart_info[uart_chan];
	ISO7816_SendChar(byte, ui);
#else
	int i = 1;
	while ((usart->US_CSR & (US_CSR_TXRDY)) == 0) {
		if (!(i%1000000)) {
			TRACE_ERROR("%u: s: %lx %02lX\r\n",
				uart_chan, usart->US_CSR,
				usart->US_RHR & 0xFF);
			usart->US_CR = US_CR_RSTTX;
			usart->US_CR = US_CR_RSTRX;
		}
		i++;
	}
	usart->US_THR = byte;
	//TRACE_ERROR("Sx%02x\r\n", byte);
#endif
	return 1;
}

/* FIXME: integrate this with actual irq handler */
static void usart_irq_rx(uint8_t inst_num)
{
	if (inst_num >= ARRAY_SIZE(cardem_inst)) {
		TRACE_ERROR("%u: UART channel out of bounds\r\n", inst_num);
		return;
	}
	Usart *usart = get_usart_by_chan(inst_num);
	struct cardem_inst *ci = &cardem_inst[inst_num];
	uint32_t csr;
	uint8_t byte = 0;

	csr = usart->US_CSR & usart->US_IMR; // save state/flags before they get changed

	if (csr & US_CSR_RXRDY) { // bytes has been received
		byte = (usart->US_RHR) & 0xFF; // ready out byte
		if (rbuf_write(&ci->rb, byte) < 0) // store byte in buffer
			TRACE_ERROR("rbuf overrun\r\n"); // error if could not store in buffer
	}

	if (csr & US_CSR_TXRDY) { // ready to transmit the next byte
		if (card_emu_tx_byte(ci->ch) == 0) // transmit next byte, and check if a byte is being transmitted
			USART_DisableIt(usart, US_IER_TXRDY); // stop the TX ready signal if not byte has been transmitted
	}

	if (csr & (US_CSR_OVRE | US_CSR_FRAME | US_CSR_PARE | US_CSR_NACK | (1 << 10))) { // error flag set
		usart->US_CR = US_CR_RSTSTA | US_CR_RSTIT | US_CR_RSTNACK; // reset UART state to clear flag
		TRACE_ERROR("%u USART error on 0x%x status: 0x%lx\n", ci->num, byte, csr); // warn user about error
	}

	// handle timeout
	if (csr & US_CSR_TIMEOUT) { // RX has been inactive for some time
		if (ci->wt_remaining <= (usart->US_RTOR & 0xffff)) { // waiting time has passed
			ci->wt_remaining = 0; // timeout reached (will stop the timer)
		} else {
			ci->wt_remaining -= (usart->US_RTOR & 0xffff); // be sure to subtract the actual timeout since the new might not have been set and reloaded yet
		}
		if (0 == ci->wt_remaining) {
			card_emu_wt_expired(ci->ch); // let the state know WT has expired
		} else if (ci->wt_remaining <= ci->wt / 2 && !ci->wt_halfed) {
			ci->wt_halfed = true;
			card_emu_wt_halfed(ci->ch); // let the state know WT has half expired
		}
		if (ci->wt_remaining > 0xffff) { // value exceeds the USART TO range
			usart->US_RTOR = 0xffff; // use the MAX
		} else {
			usart->US_RTOR = ci->wt_remaining;
		}
		usart->US_CR |= US_CR_STTTO; // clear timeout flag (and stop timeout until next character is received)
		usart->US_CR |= US_CR_RETTO; // restart the counter (it wt is 0, the timeout is not started)
	}
}

/*! ISR called for USART0 */
void mode_cardemu_usart0_irq(void)
{
	/* USART0 == Instance 1 == USIM 2 */
	usart_irq_rx(1);
}

/*! ISR called for USART1 */
void mode_cardemu_usart1_irq(void)
{
	/* USART1 == Instance 0 == USIM 1 */
	usart_irq_rx(0);
}

// call-back from card_emu.c to change UART baud rate

void card_emu_uart_update_fd(uint8_t uart_chan, uint16_t f, uint8_t d)
{
	Usart *usart = get_usart_by_chan(uart_chan); // get the USART based on the card handle
	if (NULL == usart) {
		TRACE_ERROR("%u: USART not found by chan\r\n", uart_chan);
		return;
	}
	if (!iso7816_3_valid_f(f)) {
		TRACE_ERROR("%u: invalid F: %u\r\n", uart_chan, f);
		return;
	}
	if (!iso7816_3_valid_d(d)) {
		TRACE_ERROR("%u: invalid D: %u\r\n", uart_chan, d);
		return;
	}

	uint16_t ratio = f / d;
	if (ratio > 0 && ratio < 2048) {
		/* make sure USART uses new F/D ratio */
		usart->US_CR |= US_CR_RXDIS | US_CR_RSTRX; // disable USART before changing baud rate
		usart->US_FIDI = (ratio & 0x7ff); // change baud rate (ratio)
		usart->US_CR |= US_CR_RXEN | US_CR_STTTO; // re-enable USART (and stop timeout)
		TRACE_INFO("%u: USART F/D set to %u/%u\r\n", uart_chan, f, d);
	} else {
		TRACE_ERROR("%u: USART could not set F/D to %u/%u\r\n", uart_chan, f, d);
		// TODO become unresponsive
	}
}

void card_emu_uart_update_wt(uint8_t uart_chan, uint32_t wt)
{
	if (uart_chan >= ARRAY_SIZE(cardem_inst)) {
		TRACE_ERROR("%u: UART channel out of bounds\r\n", uart_chan);
		return;
	}
	struct cardem_inst *ci = &cardem_inst[uart_chan];
	Usart *usart = get_usart_by_chan(uart_chan); // get the USART based on the card handle
	if (NULL == usart) {
		TRACE_ERROR("%u: USART not found by chan\r\n", uart_chan);
		return;
	}

	ci->wt = wt; // save value
	card_emu_uart_reset_wt(uart_chan); // reset and start timer
	TRACE_INFO("%u: USART WT set to %lu ETU\r\n", uart_chan, wt);
}

void card_emu_uart_reset_wt(uint8_t uart_chan)
{
	if (uart_chan >= ARRAY_SIZE(cardem_inst)) {
		TRACE_ERROR("%u: UART channel out of bounds\r\n", uart_chan);
		return;
	}
	struct cardem_inst *ci = &cardem_inst[uart_chan];
	Usart *usart = get_usart_by_chan(uart_chan); // get the USART based on the card handle
	if (NULL == usart) {
		TRACE_ERROR("%u: USART not found by chan\r\n", uart_chan);
		return;
	}

	ci->wt_remaining = ci->wt; // reload WT value
	ci->wt_halfed = false; // reset half expired
	if (ci->wt_remaining > 0xffff) { // value exceeds the USART TO range
		usart->US_RTOR = 0xffff; // use the MAX
	} else {
		usart->US_RTOR = ci->wt_remaining;
	}
	usart->US_CR |= US_CR_RETTO; // restart the counter (if wt is 0, the timeout is not started)
}

void card_emu_uart_io_set(uint8_t uart_chan, bool set)
{
	if (uart_chan >= ARRAY_SIZE(cardem_inst)) {
		TRACE_ERROR("%u: UART channel out of bounds\r\n", uart_chan);
		return;
	}
	struct cardem_inst *ci = &cardem_inst[uart_chan];
	if (set) {
		PIO_Set(&ci->pin_io);
	} else {
		PIO_Clear(&ci->pin_io);
	}
}

/* call-back from card_emu.c to force a USART interrupt */
void card_emu_uart_interrupt(uint8_t uart_chan)
{
	Usart *usart = get_usart_by_chan(uart_chan);
	if (!usart) {
		return;
	}
	if (USART0 == usart) {
		NVIC_SetPendingIRQ(USART0_IRQn);
	} else if (USART1 == usart) {
		NVIC_SetPendingIRQ(USART1_IRQn);
	}
}

/***********************************************************************
 * ADC for VCC voltage detection
 ***********************************************************************/

#ifdef DETECT_VCC_BY_ADC

static int adc_triggered = 0;
static int adc_sam3s_reva_errata = 0;

static int card_vcc_adc_init(void)
{
	uint32_t chip_arch = CHIPID->CHIPID_CIDR & CHIPID_CIDR_ARCH_Msk;
	uint32_t chip_ver = CHIPID->CHIPID_CIDR & CHIPID_CIDR_VERSION_Msk;

	PMC_EnablePeripheral(ID_ADC);

	ADC->ADC_CR |= ADC_CR_SWRST;
	if (chip_ver == 0 &&
	    (chip_arch == CHIPID_CIDR_ARCH_SAM3SxA ||
	     chip_arch == CHIPID_CIDR_ARCH_SAM3SxB ||
	     chip_arch == CHIPID_CIDR_ARCH_SAM3SxC)) {
		TRACE_INFO("Enabling Rev.A ADC Errata work-around\r\n");
		adc_sam3s_reva_errata = 1;
	}

	if (adc_sam3s_reva_errata) {
		/* Errata Work-Around to clear EOCx flags */
		volatile uint32_t foo;
		int i;
		for (i = 0; i < 16; i++)
			foo = ADC->ADC_CDR[i];
	}

	/* Initialize ADC for AD7 / AD6, fADC=48/24=2MHz */
	ADC->ADC_MR = ADC_MR_TRGEN_DIS | ADC_MR_LOWRES_BITS_12 |
		      ADC_MR_SLEEP_NORMAL | ADC_MR_FWUP_OFF |
		      ADC_MR_FREERUN_OFF | ADC_MR_PRESCAL(23) |
		      ADC_MR_STARTUP_SUT8 | ADC_MR_SETTLING(3) |
		      ADC_MR_ANACH_NONE | ADC_MR_TRACKTIM(4) |
		      ADC_MR_TRANSFER(1) | ADC_MR_USEQ_NUM_ORDER;
	/* enable AD6 + AD7 channels */
	ADC->ADC_CHER = ADC_CHER_CH7;
	ADC->ADC_IER = ADC_IER_EOC7;
#ifdef CARDEMU_SECOND_UART
	ADC->ADC_CHER |= ADC_CHER_CH6;
	ADC->ADC_IER |= ADC_IER_EOC6;
#endif
	NVIC_EnableIRQ(ADC_IRQn);
	ADC->ADC_CR |= ADC_CR_START;

	return 0;
}

#define VCC_UV_THRESH_1V8	1500000
#define VCC_UV_THRESH_3V	2800000

static void process_vcc_adc(struct cardem_inst *ci)
{
	if (ci->vcc_uv >= VCC_UV_THRESH_3V &&
	    ci->vcc_uv_last < VCC_UV_THRESH_3V) {
		card_emu_io_statechg(ci->ch, CARD_IO_VCC, 1);
		/* FIXME do this for real */
		card_emu_io_statechg(ci->ch, CARD_IO_CLK, 1);
	} else if (ci->vcc_uv < VCC_UV_THRESH_3V &&
		 ci->vcc_uv_last >= VCC_UV_THRESH_3V) {
		/* FIXME do this for real */
		card_emu_io_statechg(ci->ch, CARD_IO_CLK, 0);
		card_emu_io_statechg(ci->ch, CARD_IO_VCC, 0);
	}
	ci->vcc_uv_last = ci->vcc_uv;
}

void ADC_IrqHandler(void)
{
#ifdef CARDEMU_SECOND_UART
	if (ADC->ADC_ISR & ADC_ISR_EOC6) {
		uint16_t val = ADC->ADC_CDR[6] & 0xFFF;
		cardem_inst[1].vcc_uv = adc2uv(val);
		process_vcc_adc(&cardem_inst[1]);
		if (adc_sam3s_reva_errata) {
			/* Errata: START doesn't start a conversion
			 * sequence, but only a single conversion */
			ADC->ADC_CR |= ADC_CR_START;
		}
	}
#endif

	if (ADC->ADC_ISR & ADC_ISR_EOC7) {
		uint16_t val = ADC->ADC_CDR[7] & 0xFFF;
		cardem_inst[0].vcc_uv = adc2uv(val);
		process_vcc_adc(&cardem_inst[0]);
		ADC->ADC_CR |= ADC_CR_START;
	}
}
#endif /* DETECT_VCC_BY_ADC */

/***********************************************************************
 * Core USB  / main loop integration
 ***********************************************************************/

static void usim1_rst_irqhandler(const Pin *pPin)
{
	int active = PIO_Get(&pin_usim1_rst) ? 0 : 1;
	card_emu_io_statechg(cardem_inst[0].ch, CARD_IO_RST, active);
}

#ifndef DETECT_VCC_BY_ADC
static void usim1_vcc_irqhandler(const Pin *pPin)
{
	int active = PIO_Get(&pin_usim1_vcc) ? 1 : 0;
	card_emu_io_statechg(cardem_inst[0].ch, CARD_IO_VCC, active);
	/* FIXME readers enable clock after providing power and before releasing reset, but we should check it */
	card_emu_io_statechg(cardem_inst[0].ch, CARD_IO_CLK, active);
}
#endif /* !DETECT_VCC_BY_ADC */

#ifdef CARDEMU_SECOND_UART
static void usim2_rst_irqhandler(const Pin *pPin)
{
	int active = PIO_Get(&pin_usim2_rst) ? 0 : 1;
	card_emu_io_statechg(cardem_inst[1].ch, CARD_IO_RST, active);
}

#ifndef DETECT_VCC_BY_ADC
static void usim2_vcc_irqhandler(const Pin *pPin)
{
	int active = PIO_Get(&pin_usim2_vcc) ? 1 : 0;
	card_emu_io_statechg(cardem_inst[1].ch, CARD_IO_VCC, active);
	/* FIXME readers enable clock after providing power and before releasing reset, but we should check it */
	card_emu_io_statechg(cardem_inst[1].ch, CARD_IO_CLK, active);
}
#endif /* !DETECT_VCC_BY_ADC */
#endif /* CARDEMU_SECOND_UART */

/* executed once at system boot for each config */
void mode_cardemu_configure(void)
{
	TRACE_ENTRY();
}

/* called if config is activated */
void mode_cardemu_init(void)
{
	int i;

	TRACE_ENTRY();

#ifdef PINS_PWR_CARDEMU
	// enable power on required peripherals, else disable
	Pin pins_pwr_cardemu[] = { PINS_PWR_CARDEMU };
	PIO_Configure(pins_pwr_cardemu, PIO_LISTSIZE(pins_pwr_cardemu));
#endif /* PINS_PWR_CARDEMU */
#ifdef PINS_CARDSIM
	PIO_Configure(pins_cardsim, PIO_LISTSIZE(pins_cardsim));
#endif
	// ADC channel 6 and 7 are used to measure VCC (else they are grounded)
	ADC->ADC_CHER |= ADC_CHER_CH6 | ADC_CHER_CH7; // enable the ADC channels to put them in high impedance (else they leak current)
#ifdef DETECT_VCC_BY_ADC
	card_vcc_adc_init(); // configure the ADC to measure VCC
#endif /* DETECT_VCC_BY_ADC */
	// TODO pull SIMtrace board SIM lines low, else they can leak current back to VCC

	INIT_LLIST_HEAD(&cardem_inst[0].usb_out_queue);
	rbuf_reset(&cardem_inst[0].rb);
	PIO_Configure(pins_usim1, PIO_LISTSIZE(pins_usim1));
	ISO7816_Init(&cardem_inst[0].usart_info, CLK_SLAVE); // configure USART as ISO-7816 slave (e.g. card)
	cardem_inst[0].usart_info.base->US_RTOR = 0; // don't use receive timeout timer for now
	USART_EnableIt(cardem_inst[0].usart_info.base, US_IER_RXRDY | US_IER_TIMEOUT); // enable interrupts to indicate when data has been received or timeout occurred
	NVIC_EnableIRQ(USART1_IRQn); // enable interrupt requests for the USART peripheral
	PIO_ConfigureIt(&pin_usim1_rst, usim1_rst_irqhandler); // register ISR to handle reset signal change
	PIO_EnableIt(&pin_usim1_rst); // enable interrupt for reset pin change
#ifndef DETECT_VCC_BY_ADC
	PIO_ConfigureIt(&pin_usim1_vcc, usim1_vcc_irqhandler); // register ISR to handle VCC signal change
	PIO_EnableIt(&pin_usim1_vcc); // enable interrupt for VCC pin change
#endif /* DETECT_VCC_BY_ADC */
	cardem_inst[0].ch = card_emu_init(0, 2, 0, SIMTRACE_CARDEM_USB_EP_USIM1_DATAIN, SIMTRACE_CARDEM_USB_EP_USIM1_INT);
	sim_switch_use_physical(0, 1);
#ifndef DETECT_VCC_BY_ADC
	usim1_vcc_irqhandler(NULL); // check VCC/CLK state
#endif
	usim1_rst_irqhandler(NULL); // force RST state

#ifdef CARDEMU_SECOND_UART
	INIT_LLIST_HEAD(&cardem_inst[1].usb_out_queue);
	rbuf_reset(&cardem_inst[1].rb);
	PIO_Configure(pins_usim2, PIO_LISTSIZE(pins_usim2));
	ISO7816_Init(&cardem_inst[1].usart_info, CLK_SLAVE);
	// TODO enable timeout
	NVIC_EnableIRQ(USART0_IRQn);
	PIO_ConfigureIt(&pin_usim2_rst, usim2_rst_irqhandler);
	PIO_EnableIt(&pin_usim2_rst);
#ifndef DETECT_VCC_BY_ADC
	PIO_ConfigureIt(&pin_usim2_vcc, usim2_vcc_irqhandler);
	PIO_EnableIt(&pin_usim2_vcc);
#endif /* DETECT_VCC_BY_ADC */
	cardem_inst[1].ch = card_emu_init(1, 0, 1, SIMTRACE_CARDEM_USB_EP_USIM2_DATAIN, SIMTRACE_CARDEM_USB_EP_USIM2_INT);
	sim_switch_use_physical(1, 1);
	// TODO check rst and vcc
#endif /* CARDEMU_SECOND_UART */

}

/* called if config is deactivated */
void mode_cardemu_exit(void)
{
	TRACE_ENTRY();

	/* FIXME: stop tc_fdt */
	/* FIXME: release all msg, unlink them from any queue */

	PIO_DisableIt(&pin_usim1_rst);
	PIO_DisableIt(&pin_usim1_vcc);

	NVIC_DisableIRQ(USART1_IRQn);
	USART_SetTransmitterEnabled(USART1, 0);
	USART_SetReceiverEnabled(USART1, 0);

#ifdef CARDEMU_SECOND_UART
	PIO_DisableIt(&pin_usim2_rst);
	PIO_DisableIt(&pin_usim2_vcc);

	NVIC_DisableIRQ(USART0_IRQn);
	USART_SetTransmitterEnabled(USART0, 0);
	USART_SetReceiverEnabled(USART0, 0);
#endif
}

/* handle a single USB command as received from the USB host */
static void dispatch_usb_command_generic(struct msgb *msg, struct cardem_inst *ci)
{
	struct simtrace_msg_hdr *hdr;

	hdr = (struct simtrace_msg_hdr *) msg->l1h;
	switch (hdr->msg_type) {
	case SIMTRACE_CMD_BD_BOARD_INFO:
		break;
	default:
		break;
	}
	usb_buf_free(msg);
}

/* handle a single USB command as received from the USB host */
static void dispatch_usb_command_cardem(struct msgb *msg, struct cardem_inst *ci)
{
	struct simtrace_msg_hdr *hdr;
	struct cardemu_usb_msg_set_atr *atr;
	struct cardemu_usb_msg_cardinsert *cardins;
	struct llist_head *queue;

	hdr = (struct simtrace_msg_hdr *) msg->l1h;
	switch (hdr->msg_type) {
	case SIMTRACE_MSGT_DT_CEMU_TX_DATA:
		queue = card_emu_get_uart_tx_queue(ci->ch);
		llist_add_tail(&msg->list, queue);
		card_emu_have_new_uart_tx(ci->ch);
		break;
	case SIMTRACE_MSGT_DT_CEMU_SET_ATR:
		atr = (struct cardemu_usb_msg_set_atr *) msg->l2h;
		card_emu_set_atr(ci->ch, atr->atr, atr->atr_len);
		usb_buf_free(msg);
		break;
	case SIMTRACE_MSGT_DT_CEMU_CARDINSERT:
		cardins = (struct cardemu_usb_msg_cardinsert *) msg->l2h;
		if (!ci->pin_insert.pio) {
			TRACE_INFO("%u: skipping unsupported card_insert to %s\r\n",
				   ci->num, cardins->card_insert ? "INSERTED" : "REMOVED");
			break;
		}
		TRACE_INFO("%u: set card_insert to %s\r\n", ci->num,
			   cardins->card_insert ? "INSERTED" : "REMOVED");
		if (cardins->card_insert)
			PIO_Set(&ci->pin_insert);
		else
			PIO_Clear(&ci->pin_insert);
		usb_buf_free(msg);
		break;
	case SIMTRACE_MSGT_BD_CEMU_STATUS:
		card_emu_report_status(ci->ch);
		usb_buf_free(msg);
		break;
	case SIMTRACE_MSGT_BD_CEMU_STATS:
	default:
		/* FIXME: Send Error */
		usb_buf_free(msg);
		break;
	}
}

#ifdef PINS_PERST
#include "wwan_perst.h"
#endif

static int usb_command_modem_reset(struct msgb *msg, struct cardem_inst *ci)
{
	struct st_modem_reset *mr = (struct st_modem_reset *) msg->l2h;

	if (msgb_l2len(msg) < sizeof(*mr))
		return -1;

	switch (mr->asserted) {
#ifdef PINS_PERST
	case 0:
		wwan_perst_set(ci->num, 0);
		break;
	case 1:
		wwan_perst_set(ci->num, 1);
		break;
	case 2:
		wwan_perst_do_reset_pulse(ci->num, mr->pulse_duration_msec);
		break;
#endif
	default:
		return -1;
	}

	return 0;
}

static int usb_command_sim_select(struct msgb *msg, struct cardem_inst *ci)
{
	struct st_modem_sim_select *mss = (struct st_modem_sim_select *) msg->l2h;

	if (msgb_l2len(msg) < sizeof(*mss))
		return -1;

	if (mss->remote_sim)
		sim_switch_use_physical(ci->num, 0);
	else
		sim_switch_use_physical(ci->num, 1);

	return 0;
}

/* handle a single USB command as received from the USB host */
static void dispatch_usb_command_modem(struct msgb *msg, struct cardem_inst *ci)
{
	struct simtrace_msg_hdr *hdr;

	hdr = (struct simtrace_msg_hdr *) msg->l1h;
	switch (hdr->msg_type) {
	case SIMTRACE_MSGT_DT_MODEM_RESET:
		usb_command_modem_reset(msg, ci);
		break;
	case SIMTRACE_MSGT_DT_MODEM_SIM_SELECT:
		usb_command_sim_select(msg, ci);
		break;
	case SIMTRACE_MSGT_BD_MODEM_STATUS:
		break;
	default:
		break;
	}
	usb_buf_free(msg);
}

/* handle a single USB command as received from the USB host */
static void dispatch_usb_command(struct msgb *msg, struct cardem_inst *ci)
{
	struct simtrace_msg_hdr *sh = (struct simtrace_msg_hdr *) msg->l1h;

	if (msgb_length(msg) < sizeof(*sh)) {
		/* FIXME: Error */
		usb_buf_free(msg);
		return;
	}
	msg->l2h = msg->l1h + sizeof(*sh);

	switch (sh->msg_class) {
	case SIMTRACE_MSGC_GENERIC:
		dispatch_usb_command_generic(msg, ci);
		break;
	case SIMTRACE_MSGC_CARDEM:
		dispatch_usb_command_cardem(msg, ci);
		break;
	case SIMTRACE_MSGC_MODEM:
		/* FIXME: Find out why this fails if used for !=
		 * MSGC_MODEM ?!? */
		dispatch_usb_command_modem(msg, ci);
		break;
	default:
		/* FIXME: Send Error */
		usb_buf_free(msg);
		break;
	}
}

static void dispatch_received_msg(struct msgb *msg, struct cardem_inst *ci)
{
	struct msgb *segm;
	struct simtrace_msg_hdr *mh;

	/* check if we have multiple concatenated commands in
	 * one message.  USB endpoints are streams that don't
	 * preserve the message boundaries */
	mh = (struct simtrace_msg_hdr *) msg->data;
	if (mh->msg_len == msgb_length(msg)) {
		/* fast path: only one message in buffer */
		dispatch_usb_command(msg, ci);
		return;
	}

	/* slow path: iterate over list of messages, allocating one new
	 * reqe_ctx per segment */
	while (1) {
		mh = (struct simtrace_msg_hdr *) msg->data;

		segm = usb_buf_alloc(ci->ep_out);
		if (!segm) {
			TRACE_ERROR("%u: ENOMEM during msg segmentation\r\n",
				    ci->num);
			break;
		}

		if (mh->msg_len > msgb_length(msg)) {
			TRACE_ERROR("%u: Unexpected large message (%u bytes)\n",
					ci->num, mh->msg_len);
			usb_buf_free(segm);
		} else {
			uint8_t *cur = msgb_put(segm, mh->msg_len);
			segm->l1h = segm->head;
			memcpy(cur, mh, mh->msg_len);
			dispatch_usb_command(segm, ci);
		}
		/* pull this message */
		msgb_pull(msg, mh->msg_len);
		/* abort if we're done */
		if (msgb_length(msg) <= 0)
			break;
	}

	usb_buf_free(msg);
}

/* iterate over the queue of incoming USB commands and dispatch/execute
 * them */
static void process_any_usb_commands(struct llist_head *main_q,
				     struct cardem_inst *ci)
{
	struct llist_head *lh;
	struct msgb *msg;
	int i;

	/* limit the number of iterations to 10, to ensure we don't get
	 * stuck here without returning to main loop processing */
	for (i = 0; i < 10; i++) {
		/* de-queue the list head in an irq-safe way */
		lh = llist_head_dequeue_irqsafe(main_q);
		if (!lh)
			break;
		msg = llist_entry(lh, struct msgb, list);
		dispatch_received_msg(msg, ci);
	}
}

/* main loop function, called repeatedly */
void mode_cardemu_run(void)
{
	struct llist_head *queue;
	unsigned int i;

	for (i = 0; i < ARRAY_SIZE(cardem_inst); i++) {
		struct cardem_inst *ci = &cardem_inst[i];

		/* drain the ring buffer from UART into card_emu */
		while (1) {
			__disable_irq();
			if (rbuf_is_empty(&ci->rb)) {
				__enable_irq();
				break;
			}
			uint8_t byte = rbuf_read(&ci->rb);
			__enable_irq();
			card_emu_process_rx_byte(ci->ch, byte);
			//TRACE_ERROR("%uRx%02x\r\n", i, byte);
		}

		/* first try to send any pending messages on IRQ */
		usb_refill_to_host(ci->ep_int);

		/* then try to send any pending messages on IN */
		usb_refill_to_host(ci->ep_in);

		/* ensure we can handle incoming USB messages from the
		 * host */
		usb_refill_from_host(ci->ep_out);
		queue = usb_get_queue(ci->ep_out);
		process_any_usb_commands(queue, ci);
	}
}