summaryrefslogtreecommitdiff
path: root/src/portable/microchip/pic/dcd_pic.c
blob: 7e490905c1f88eec2b9934f60cc197102550b865 (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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
/*
 * SPDX-FileCopyrightText: Copyright (c) 2022 SudoMaker, Ltd.
 * SPDX-FileCopyrightText: Copyright (c) 2020 Koji Kitayama
 * SPDX-FileCopyrightText: Copyright (c) 2022 Ha Thach (tinyusb.org)
 * SPDX-License-Identifier: MIT
 *
 * This file is part of the TinyUSB stack.
 *
 * Author: Mike Yang (Reimu NotMoe) <[email protected]>
 * Based on usb_device.c - Copyright (c) 2015 Microchip Technology Inc.
 * Based on dcd_khci.c   - Copyright (c) 2020 Koji Kitayama
 */

#include "tusb_option.h"

#if CFG_TUD_ENABLED && \
    (CFG_TUSB_MCU == OPT_MCU_PIC32MX || CFG_TUSB_MCU == OPT_MCU_PIC32MM || \
     CFG_TUSB_MCU == OPT_MCU_PIC32MK || CFG_TUSB_MCU == OPT_MCU_PIC24 || \
     CFG_TUSB_MCU == OPT_MCU_DSPIC33)

#include <xc.h>

#include "device/dcd.h"


#if (CFG_TUSB_MCU == OPT_MCU_PIC32MX || CFG_TUSB_MCU == OPT_MCU_PIC32MM || CFG_TUSB_MCU == OPT_MCU_PIC32MK)

#define TU_PIC_INT_SIZE         4

#elif (CFG_TUSB_MCU == OPT_MCU_PIC24 || CFG_TUSB_MCU == OPT_MCU_DSPIC33)

#define TU_PIC_INT_SIZE         2

#else

#error Unsupportd PIC MCU

#endif


#if TU_PIC_INT_SIZE == 4

#ifndef KVA_TO_PA
#define KVA_TO_PA(kva)    ((uint32_t)(kva) & 0x1fffffff)
#endif

#ifndef PA_TO_KVA1
#define PA_TO_KVA1(pa)    ((uint32_t)(pa) | 0xA0000000)
#endif

#else

#ifndef KVA_TO_PA
#define KVA_TO_PA(kva)    (kva)
#endif

#ifndef PA_TO_KVA1
#define PA_TO_KVA1(pa)    (pa)
#endif

#endif


//--------------------------------------------------------------------+
// MACRO TYPEDEF CONSTANT ENUM DECLARATION
//--------------------------------------------------------------------+

enum {
  TOK_PID_OUT   = 0x1u,
  TOK_PID_IN    = 0x9u,
  TOK_PID_SETUP = 0xDu,
};

// The BDT is 8 bytes on 32bit PICs and 4 bytes on 8/16bit PICs
#if TU_PIC_INT_SIZE == 4
typedef struct TU_ATTR_PACKED
{
  union {
    uint32_t head;
    struct {
      union {
        struct {
          uint16_t           :  2;
          uint16_t tok_pid   :  4;
          uint16_t data      :  1;
          uint16_t own       :  1;
          uint16_t           :  8;
        };
        struct {
          uint16_t           :  2;
          uint16_t bdt_stall :  1;
          uint16_t dts       :  1;
          uint16_t ninc      :  1;
          uint16_t keep      :  1;
          uint16_t           : 10;
        };
      };
      uint16_t bc : 10;
      uint16_t    :  6;
    };
  };
  uint8_t *addr;
} buffer_descriptor_t;

TU_VERIFY_STATIC( sizeof(buffer_descriptor_t) == 8, "size is not correct" );
#else
typedef struct TU_ATTR_PACKED
{
  union {
    uint16_t head;

    struct {
      uint16_t           :  10;
      uint16_t tok_pid   :  4;
      uint16_t data      :  1;
      uint16_t own       :  1;
    };
    struct {
      uint16_t           :  10;
      uint16_t bdt_stall :  1;
      uint16_t dts       :  1;
      uint16_t ninc      :  1;
      uint16_t keep      :  1;
    };

    struct {
      uint16_t bc : 10;
      uint16_t    :  6;
    };
  };
  uint8_t *addr;
} buffer_descriptor_t;

TU_VERIFY_STATIC( sizeof(buffer_descriptor_t) == 4, "size is not correct" );
#endif


typedef struct TU_ATTR_PACKED
{
  union {
    uint32_t state;
    struct {
      uint32_t max_packet_size :11;
      uint32_t                 : 5;
      uint32_t odd             : 1;
      uint32_t                 :15;
    };
  };
  uint16_t length;
  uint16_t remaining;
} endpoint_state_t;

TU_VERIFY_STATIC( sizeof(endpoint_state_t) == 8, "size is not correct" );

typedef struct
{
  union {
    /* [#EP][OUT,IN][EVEN,ODD] */
    buffer_descriptor_t bdt[16][2][2];
#if TU_PIC_INT_SIZE == 4
    uint16_t            bda[256];
#else
    uint8_t            bda[256];
#endif
  };
  TU_ATTR_ALIGNED(4) union {
    endpoint_state_t endpoint[16][2];
    endpoint_state_t endpoint_unified[16 * 2];
  };
  uint8_t setup_packet[8];
  uint8_t addr;
} dcd_data_t;

//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
// BDT(Buffer Descriptor Table) must be 256-byte aligned
CFG_TUD_MEM_SECTION TU_ATTR_ALIGNED(512) volatile static dcd_data_t _dcd;

#if TU_PIC_INT_SIZE == 4
TU_VERIFY_STATIC( sizeof(_dcd.bdt) == 512, "size is not correct" );
#else
TU_VERIFY_STATIC( sizeof(_dcd.bdt) == 256, "size is not correct" );
#endif

#if TU_PIC_INT_SIZE == 4
typedef uint32_t ep_reg_t;
#elif TU_PIC_INT_SIZE == 2
typedef uint16_t ep_reg_t;
#endif

static inline volatile void *ep_addr(uint8_t rhport, uint8_t ep_num) {
#if CFG_TUSB_MCU == OPT_MCU_PIC32MK
  volatile void *ep_reg_base = rhport ? (&U2EP0) : (&U1EP0);
#else
  volatile void *ep_reg_base = &U1EP0;
#endif
#if TU_PIC_INT_SIZE == 4
  const size_t offset = 0x10;
#else
  const size_t offset = 0x2;
#endif
  return ep_reg_base + offset * ep_num;
}

static inline ep_reg_t ep_read(uint8_t rhport, uint8_t ep_num) {
  volatile ep_reg_t *ep = ep_addr(rhport, ep_num);
  return *ep;
}

static inline void ep_write(uint8_t rhport, uint8_t ep_num, ep_reg_t val) {
  volatile ep_reg_t *ep = ep_addr(rhport, ep_num);
  *ep = val;
}

static inline void ep_clear(uint8_t rhport, uint8_t ep_num, ep_reg_t val) {
#if TU_PIC_INT_SIZE == 4
  volatile ep_reg_t *ep_clr = (ep_addr(rhport, ep_num) + 0x4);
  *ep_clr = val;
#else
  ep_reg_t v = ep_read(rhport, ep_num);
  v &= ~val;
  ep_write(rhport, ep_num, v);
#endif
}

static inline void ep_set(uint8_t rhport, uint8_t ep_num, ep_reg_t val) {
#if TU_PIC_INT_SIZE == 4
  volatile ep_reg_t *ep_s = (ep_addr(rhport, ep_num) + 0x8);
  *ep_s = val;
#else
  ep_reg_t v = ep_read(rhport, ep_num);
  v |= val;
  ep_write(rhport, ep_num, v);
#endif
}

static inline void intr_enable(uint8_t rhport) {
#if CFG_TUSB_MCU == OPT_MCU_PIC32MM
  IEC0SET = _IEC0_USBIE_MASK;
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MX
  IEC1SET = _IEC1_USBIE_MASK;
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MK
  if (rhport == 0)
    IEC1SET = _IEC1_USB1IE_MASK;
  else
    IEC7SET = _IEC7_USB2IE_MASK;
#elif (CFG_TUSB_MCU == OPT_MCU_PIC24) || (CFG_TUSB_MCU == OPT_MCU_DSPIC33)
  IEC5bits.USB1IE = 1;
#endif
}

static inline void intr_disable(uint8_t rhport) {
#if CFG_TUSB_MCU == OPT_MCU_PIC32MM
  IEC0CLR = _IEC0_USBIE_MASK;
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MX
  IEC1CLR = _IEC1_USBIE_MASK;
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MK
  if (rhport == 0)
    IEC1CLR = _IEC1_USB1IE_MASK;
  else
    IEC7CLR = _IEC7_USB2IE_MASK;
#elif (CFG_TUSB_MCU == OPT_MCU_PIC24) || (CFG_TUSB_MCU == OPT_MCU_DSPIC33)
  IEC5bits.USB1IE = 0;
#endif
}

static inline int intr_is_enabled(uint8_t rhport) {
#if CFG_TUSB_MCU == OPT_MCU_PIC32MM
  return IEC0bits.USBIE;
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MX
  return IEC1bits.USBIE;
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MK
  if (rhport == 0)
    return IEC1bits.USB1IE;
  else
    return IEC7bits.USB2IE;
#elif (CFG_TUSB_MCU == OPT_MCU_PIC24) || (CFG_TUSB_MCU == OPT_MCU_DSPIC33)
  return IEC5bits.USB1IE;
#endif
}

static inline void intr_clear(uint8_t rhport) {
#if CFG_TUSB_MCU == OPT_MCU_PIC32MM
  IFS0CLR = _IFS0_USBIF_MASK;
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MX
  IFS1CLR = _IFS1_USBIF_MASK;
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MK
  if (rhport == 0)
    IFS1CLR = _IFS1_USB1IF_MASK;
  else
    IFS7CLR = _IFS7_USB2IF_MASK;
#elif (CFG_TUSB_MCU == OPT_MCU_PIC24) || (CFG_TUSB_MCU == OPT_MCU_DSPIC33)
  IFS5bits.USB1IF = 0;
#endif
}

static void prepare_next_setup_packet(uint8_t rhport)
{
  const unsigned out_odd = _dcd.endpoint[0][0].odd;
  const unsigned in_odd  = _dcd.endpoint[0][1].odd;

  // Abandon any previous control transfers that might have been using EP0.
  // Ordinarily, nothing actually needs abandoning, since the previous control
  // transfer would have completed successfully prior to the host sending the
  // next SETUP packet. However, in a timeout error case, or after an EP0
  // STALL event, one or more UOWN bits might still be set. If so, we should
  // clear the UOWN bits, so the EP0 IN/OUT endpoints are in a known inactive
  // state, ready for re-arming by the `dcd_edpt_xfer' function that will be
  // called next.

  _dcd.bdt[0][0][out_odd].data     = 0;
  _dcd.bdt[0][0][out_odd].own      = 0;
  _dcd.bdt[0][0][out_odd ^ 1].data = 1;
  _dcd.bdt[0][1][in_odd].data      = 1;
  _dcd.bdt[0][1][in_odd].own       = 0;
  _dcd.bdt[0][1][in_odd ^ 1].data  = 0;
  _dcd.bdt[0][1][in_odd ^ 1].own   = 0;
  dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_OUT),
          _dcd.setup_packet, sizeof(_dcd.setup_packet));
}

static void process_stall(uint8_t rhport)
{
  for (int i = 0; i < 16; ++i) {
    unsigned const endpt = ep_read(rhport, i);

    if (endpt & _U1EP0_EPSTALL_MASK) {
      // prepare next setup if endpoint0
      if ( i == 0 ) prepare_next_setup_packet(rhport);

      // clear stall bit
      ep_clear(rhport, i, _U1EP0_EPSTALL_MASK);
    }
  }
}

static void process_tokdne(uint8_t rhport)
{
  ep_reg_t s = U1STAT;

  U1IR = _U1IR_TRNIF_MASK;

  uint8_t epnum = (s >> _U1STAT_ENDPT0_POSITION);
  uint8_t dir   = (s & _U1STAT_DIR_MASK) >> _U1STAT_DIR_POSITION;
  unsigned odd  = (s & _U1STAT_PPBI_MASK) ? 1 : 0;

  buffer_descriptor_t *bd = (buffer_descriptor_t *)&_dcd.bda[s];
  endpoint_state_t    *ep = &_dcd.endpoint_unified[s >> 3];

  /* fetch pid before discarded by the next steps */
  const unsigned pid = bd->tok_pid;

  /* reset values for a next transfer */
  bd->bdt_stall = 0;
  bd->dts       = 1;
  bd->ninc      = 0;
  bd->keep      = 0;
  /* update the odd variable to prepare for the next transfer */
  ep->odd       = odd ^ 1;
  if (pid == TOK_PID_SETUP) {
    dcd_event_setup_received(rhport, (uint8_t *)PA_TO_KVA1(bd->addr), true);
#if TU_PIC_INT_SIZE == 4
    U1CONCLR = _U1CON_PKTDIS_TOKBUSY_MASK;
#else
    U1CONbits.PKTDIS = 0;
#endif
    return;
  }

  const unsigned bc = bd->bc;
  const unsigned remaining = ep->remaining - bc;
  if (remaining && bc == ep->max_packet_size) {
    /* continue the transferring consecutive data */
    ep->remaining = remaining;
    const int next_remaining = remaining - ep->max_packet_size;
    if (next_remaining > 0) {
      /* prepare to the after next transfer */
      bd->addr += ep->max_packet_size * 2;
      bd->bc    = next_remaining > ep->max_packet_size ? ep->max_packet_size: next_remaining;
      bd->own   = 1; /* the own bit must set after addr */
    }
    return;
  }
  const unsigned length = ep->length;
  dcd_event_xfer_complete(rhport,
        tu_edpt_addr(epnum, dir),
        length - remaining, XFER_RESULT_SUCCESS, true);
  if (0 == epnum && 0 == length) {
    /* After completion a ZLP of control transfer,
     * it prepares for the next steup transfer. */
    if (_dcd.addr) {
      /* When the transfer was the SetAddress,
       * the device address should be updated here. */
      U1ADDR = _dcd.addr;
      _dcd.addr  = 0;
    }
    prepare_next_setup_packet(rhport);
  }
}

static void process_bus_reset(uint8_t rhport)
{
#if TU_PIC_INT_SIZE == 4
  U1PWRCCLR = _U1PWRC_USUSPEND_MASK;
  U1CONSET = _U1CON_PPBRST_MASK;
#else
  U1PWRCbits.USUSPND = 0;
  U1CONbits.PPBRST = 1;
#endif
  U1ADDR = 0;

  U1IE = _U1IE_URSTIE_MASK | _U1IE_TRNIE_MASK | _U1IE_IDLEIE_MASK |
         _U1IE_UERRIE_MASK | _U1IE_STALLIE_MASK;

  U1EP0 = _U1EP0_EPHSHK_MASK | _U1EP0_EPRXEN_MASK | _U1EP0_EPTXEN_MASK;

  for (unsigned i = 1; i < 16; ++i) {
    ep_write(rhport, i, 0);
  }

  buffer_descriptor_t *bd = _dcd.bdt[0][0];
  for (unsigned i = 0; i < sizeof(_dcd.bdt)/sizeof(*bd); ++i, ++bd) {
    bd->head = 0;
  }
  const endpoint_state_t ep0 = {
    .max_packet_size = CFG_TUD_ENDPOINT0_SIZE,
    .odd             = 0,
    .length          = 0,
    .remaining       = 0,
  };
  _dcd.endpoint[0][0] = ep0;
  _dcd.endpoint[0][1] = ep0;
  tu_memclr(_dcd.endpoint[1], sizeof(_dcd.endpoint) - sizeof(_dcd.endpoint[0]));
  _dcd.addr = 0;
  prepare_next_setup_packet(rhport);
#if TU_PIC_INT_SIZE == 4
  U1CONCLR = _U1CON_PPBRST_MASK;
#else
  U1CONbits.PPBRST = 0;
#endif
  dcd_event_bus_reset(rhport, TUSB_SPEED_FULL, true);
}

static void process_bus_sleep(uint8_t rhport)
{
  // Enable resume & disable suspend interrupt
  dcd_event_bus_signal(rhport, DCD_EVENT_SUSPEND, true);
}

static void process_bus_resume(uint8_t rhport)
{
  // Enable suspend & disable resume interrupt
#if TU_PIC_INT_SIZE == 4
  U1PWRCCLR = _U1PWRC_USUSPEND_MASK;
  U1IECLR = _U1IE_RESUMEIE_MASK;
  U1IESET = _U1IE_IDLEIE_MASK;
#else
  U1PWRCbits.USUSPND = 0;
  U1IEbits.RESUMEIE = 0;
  U1IEbits.IDLEIE = 1;
#endif

  dcd_event_bus_signal(rhport, DCD_EVENT_RESUME, true);
}

/*------------------------------------------------------------------*/
/* Device API
 *------------------------------------------------------------------*/
bool dcd_init(uint8_t rhport, const tusb_rhport_init_t* rh_init) {
  (void) rh_init;
  intr_disable(rhport);
  intr_clear(rhport);

  tu_memclr(&_dcd, sizeof(_dcd));

#if TU_PIC_INT_SIZE == 4
  // The USBBUSY bit is present on PIC32s and we're required to check it
  // prior to powering on the USB peripheral (see DS61126F page 27)
  while (U1PWRCbits.USBBUSY);
  U1PWRCSET = _U1PWRC_USBPWR_MASK;
#else
  U1PWRCbits.USBPWR = 1;
#endif

#if TU_PIC_INT_SIZE == 4
  uint32_t bdt_phys = KVA_TO_PA((uintptr_t)_dcd.bdt);

  U1BDTP1 = (uint8_t)(bdt_phys >>  8);
  U1BDTP2 = (uint8_t)(bdt_phys >> 16);
  U1BDTP3 = (uint8_t)(bdt_phys >> 24);
#else
  U1BDTP1 = (uint8_t)((uint16_t)(void *)_dcd.bdt >> 8);

  U1CNFG1bits.PPB = 2;
#endif

  U1IE = _U1IE_URSTIE_MASK;

  dcd_connect(rhport);
  return true;
}

bool dcd_deinit(uint8_t rhport)
{
  U1CON = 0;
  U1IE = 0;
  U1OTGIE = 0;
#if TU_PIC_INT_SIZE == 4
  U1PWRCCLR = _U1PWRC_USUSPEND_MASK | _U1PWRC_USBPWR_MASK;
#else
  U1PWRC &= ~(_U1PWRC_USUSPEND_MASK | _U1PWRC_USBPWR_MASK);
#endif
  return true;
}

void dcd_int_enable(uint8_t rhport)
{
  intr_enable(rhport);
}

void dcd_int_disable(uint8_t rhport)
{
  intr_disable(rhport);
}

void dcd_set_address(uint8_t rhport, uint8_t dev_addr)
{
  _dcd.addr = dev_addr & 0x7F;
  /* Response with status first before changing device address */
  dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0, false);
}

void dcd_remote_wakeup(uint8_t rhport)
{
#if TU_PIC_INT_SIZE == 4
  U1CONSET = _U1CON_RESUME_MASK;
#else
  U1CONbits.RESUME = 1;
#endif

  // FIXME: Assert RESUME signal correctly, requires device-specific handling
  // For now we use a hardcoded cycle-based delay which attempts to delay 10ms
  // at the most common CPU frequencies. On PIC32s we assume the loop body
  // takes 3 cycles. On 16-bit PICs we assume the XC16 compiler is in use and
  // use its `__delay_ms' function.

#if CFG_TUSB_MCU == OPT_MCU_PIC32MM
  uint32_t cnt = 24000000 / 1000 / 3;
  while (cnt--) asm volatile("nop");
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MX
  uint32_t cnt = 40000000 / 1000 / 3;
  while (cnt--) asm volatile("nop");
#elif CFG_TUSB_MCU == OPT_MCU_PIC32MK
  uint32_t cnt = 120000000 / 1000 / 3;
  while (cnt--) asm volatile("nop");
#else
  __delay_ms(10);
#endif

#if TU_PIC_INT_SIZE == 4
  U1CONCLR = _U1CON_RESUME_MASK;
#else
  U1CONbits.RESUME = 0;
#endif
}

void dcd_connect(uint8_t rhport)
{
  while (!U1CONbits.USBEN) {
#if TU_PIC_INT_SIZE == 4
    U1CONSET = _U1CON_USBEN_SOFEN_MASK;
#else
    U1CONbits.USBEN = 1;
#endif
  }
}

void dcd_disconnect(uint8_t rhport)
{
  U1CON = 0;
}

void dcd_sof_enable(uint8_t rhport, bool en)
{
  (void) rhport;
  (void) en;
}

//--------------------------------------------------------------------+
// Endpoint API
//--------------------------------------------------------------------+
bool dcd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * ep_desc)
{
  const unsigned ep_addr  = ep_desc->bEndpointAddress;
  const unsigned epn      = tu_edpt_number(ep_addr);
  const unsigned dir      = tu_edpt_dir(ep_addr);
  const unsigned xfer     = ep_desc->bmAttributes.xfer;
  endpoint_state_t *ep    = &_dcd.endpoint[epn][dir];
  const unsigned odd      = ep->odd;
  buffer_descriptor_t *bd = _dcd.bdt[epn][dir];

  /* No support for control transfer */
  TU_ASSERT(epn && (xfer != TUSB_XFER_CONTROL));

  ep->max_packet_size = tu_edpt_packet_size(ep_desc);


  unsigned val = _U1EP0_EPCONDIS_MASK;
  val |= (xfer != TUSB_XFER_ISOCHRONOUS) ? _U1EP0_EPHSHK_MASK : 0;
  val |= dir ? _U1EP0_EPTXEN_MASK : _U1EP0_EPRXEN_MASK;

  ep_reg_t tmp = ep_read(rhport, epn);
  tmp |= val;
  ep_write(rhport, epn, tmp);

  if (xfer != TUSB_XFER_ISOCHRONOUS) {
    bd[odd].dts      = 1;
    bd[odd].data     = 0;
    bd[odd ^ 1].dts  = 1;
    bd[odd ^ 1].data = 1;
  }

  return true;
}

void dcd_edpt_close_all(uint8_t rhport)
{
  const unsigned ie = intr_is_enabled(rhport);
  intr_disable(rhport);

  for (unsigned i = 1; i < 16; ++i) {
    ep_write(rhport, i, 0);
  }

  if (ie) intr_enable(rhport);

  buffer_descriptor_t *bd = _dcd.bdt[1][0];
  for (unsigned i = 2; i < sizeof(_dcd.bdt)/sizeof(*bd); ++i, ++bd) {
    bd->head = 0;
  }
  endpoint_state_t *ep = &_dcd.endpoint[1][0];
  for (unsigned i = 2; i < sizeof(_dcd.endpoint)/sizeof(*ep); ++i, ++ep) {
    /* Clear except the odd */
    ep->max_packet_size = 0;
    ep->length          = 0;
    ep->remaining       = 0;
  }
}

void dcd_edpt_close(uint8_t rhport, uint8_t ep_addr)
{
  const unsigned epn      = tu_edpt_number(ep_addr);
  const unsigned dir      = tu_edpt_dir(ep_addr);
  endpoint_state_t *ep    = &_dcd.endpoint[epn][dir];
  buffer_descriptor_t *bd = _dcd.bdt[epn][dir];
  const unsigned msk      = dir ? _U1EP0_EPTXEN_MASK : _U1EP0_EPRXEN_MASK;
  const unsigned ie       = intr_is_enabled(rhport);

  intr_disable(rhport);

  ep_clear(rhport, epn, msk);

  ep->max_packet_size = 0;
  ep->length          = 0;
  ep->remaining       = 0;
  bd[0].head          = 0;
  bd[1].head          = 0;

  if (ie) intr_enable(rhport);
}

#if 0
bool dcd_edpt_iso_alloc(uint8_t rhport, uint8_t ep_addr, uint16_t largest_packet_size) {
  (void) rhport;
  (void) ep_addr;
  (void) largest_packet_size;
  return false;
}

bool dcd_edpt_iso_activate(uint8_t rhport, tusb_desc_endpoint_t const * desc_ep) {
  (void) rhport;
  (void) desc_ep;
  return false;
}
#endif

bool dcd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes, bool is_isr)
{
  (void) is_isr;

  const unsigned epn      = tu_edpt_number(ep_addr);
  const unsigned dir      = tu_edpt_dir(ep_addr);
  endpoint_state_t    *ep = &_dcd.endpoint[epn][dir];
  buffer_descriptor_t *bd = &_dcd.bdt[epn][dir][ep->odd];
  TU_ASSERT(0 == bd->own);

  const unsigned ie       = intr_is_enabled(rhport);

  intr_disable(rhport);

  ep->length    = total_bytes;
  ep->remaining = total_bytes;

  const unsigned mps = ep->max_packet_size;
  if (total_bytes > mps) {
    buffer_descriptor_t *next = ep->odd ? bd - 1: bd + 1;
    /* When total_bytes is greater than the max packet size,
     * it prepares to the next transfer to avoid NAK in advance. */
    next->bc   = total_bytes >= 2 * mps ? mps: total_bytes - mps;
    next->addr = (uint8_t *)KVA_TO_PA(buffer + mps);
    next->own  = 1;
  }
  bd->bc   = total_bytes >= mps ? mps: total_bytes;
  bd->addr = (uint8_t *)KVA_TO_PA(buffer);
  bd->own  = 1; /* This bit must be set last */

  if (ie) intr_enable(rhport);

  return true;
}

void dcd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
  (void) rhport;
  const unsigned epn = tu_edpt_number(ep_addr);

  if (0 == epn) {
    ep_set(rhport, epn, _U1EP0_EPSTALL_MASK);
  } else {
    const unsigned dir      = tu_edpt_dir(ep_addr);
    const unsigned odd      = _dcd.endpoint[epn][dir].odd;
    buffer_descriptor_t *bd = &_dcd.bdt[epn][dir][odd];
    TU_ASSERT(0 == bd->own,);

    const unsigned ie       = intr_is_enabled(rhport);

    intr_disable(rhport);

    bd->bdt_stall = 1;
    bd->own       = 1; /* This bit must be set last */

    if (ie) intr_enable(rhport);
  }
}

void dcd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
  const unsigned epn      = tu_edpt_number(ep_addr);
  TU_VERIFY(epn,);
  const unsigned dir      = tu_edpt_dir(ep_addr);
  const unsigned odd      = _dcd.endpoint[epn][dir].odd;
  buffer_descriptor_t *bd = _dcd.bdt[epn][dir];
  TU_VERIFY(bd[odd].own,);

  const unsigned ie       = intr_is_enabled(rhport);

  intr_disable(rhport);

  bd[odd].own = 0;

  // clear stall
  bd[odd].bdt_stall  = 0;

  // Reset data toggle
  bd[odd    ].data = 0;
  bd[odd ^ 1].data = 1;

  // We already cleared this in ISR, but just clear it here to be safe
  const unsigned endpt = ep_read(rhport, epn);
  if (endpt & _U1EP0_EPSTALL_MASK) {
    ep_clear(rhport, endpt, _U1EP0_EPSTALL_MASK);
  }

  if (ie) intr_enable(rhport);
}

//--------------------------------------------------------------------+
// ISR
//--------------------------------------------------------------------+
void dcd_int_handler(uint8_t rhport)
{
  uint32_t is, msk;

  // Part 1 - "USB interrupts"
  is = U1IR;
  msk = U1IE;

  U1IR = is & ~msk;
  is &= msk;

  if (is & _U1IR_UERRIF_MASK) {
    uint32_t es = U1EIR;
    U1EIR = es;
    U1IR = is; /* discard any pending events */
  }

  if (is & _U1IR_URSTIF_MASK) {
    U1IR = is; /* discard any pending events */
    process_bus_reset(rhport);
  }

  if (is & _U1IR_IDLEIF_MASK) {
    // Note Host usually has extra delay after bus reset (without SOF), which could falsely
    // detected as Sleep event. Though usbd has debouncing logic so we are good

    /*
     * NOTE: Do not clear U1OTGIRbits.ACTVIF here!
     * Reason:
     * ACTVIF is only generated once an IDLEIF has been generated.
     * This is a 1:1 ratio interrupt generation.
     * For every IDLEIF, there will be only one ACTVIF regardless of
     * the number of subsequent bus transitions.
     *
     * If the ACTIF is cleared here, a problem could occur when:
     * [       IDLE       ][bus activity ->
     * <--- 3 ms ----->     ^
     *                ^     ACTVIF=1
     *                IDLEIF=1
     *  #           #           #           #   (#=Program polling flags)
     *                          ^
     *                          This polling loop will see both
     *                          IDLEIF=1 and ACTVIF=1.
     *                          However, the program services IDLEIF first
     *                          because ACTIVIE=0.
     *                          If this routine clears the only ACTIVIF,
     *                          then it can never get out of the suspend
     *                          mode.
     */
    U1OTGIESET = _U1OTGIE_ACTVIE_MASK;
    U1IR = _U1IR_IDLEIF_MASK;
    process_bus_sleep(rhport);
  }

  if (is & _U1IR_SOFIF_MASK) {
    U1IR = _U1IR_SOFIF_MASK;
    dcd_event_bus_signal(rhport, DCD_EVENT_SOF, true);
  }

  if (is & _U1IR_STALLIF_MASK) {
    process_stall(rhport);
    U1IR = _U1IR_STALLIF_MASK;
  }

  if (is & _U1IR_TRNIF_MASK) {
    process_tokdne(rhport);
  }

  // Part 2 - "USB OTG interrupts"
  is = U1OTGIR;
  msk = U1OTGIE;

  U1OTGIR = is & ~msk;
  is &= msk;

  if (is & _U1OTGIR_ACTVIF_MASK) {
#if TU_PIC_INT_SIZE == 4
    U1OTGIECLR = _U1OTGIE_ACTVIE_MASK;
#else
    U1OTGIE &= ~_U1OTGIE_ACTVIE_MASK;
#endif
    U1OTGIR = _U1OTGIR_ACTVIF_MASK;
    process_bus_resume(rhport);
  }

  intr_clear(rhport);
}
#endif