-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
USBCore.cpp
1815 lines (1629 loc) · 56 KB
/
USBCore.cpp
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file USBCore.cpp
* @author Daniel Starke
* @copyright Copyright 2020-2022 Daniel Starke
* @date 2020-05-21
* @version 2023-09-25
*
* Control Endpoint:
* @verbatim
* Host Device
* | |
* +----------->| |
* | .----------------. EP:OUT .----------------.
* | | |---------->| |
* | | | SETUP | |
* | | Request | | Response |
* | | | EP:IN | |
* | | |<----------| |
* | '----------------' DATA '----------------'
* | | (optional) |
* | +---------+ +-----------+
* | | | | |
* | | v v |
* | | .----------------. .----------------. |
* | | | | EP:OUT | | |
* | | | Settings |---------->| Applied | |
* | | | | DATA | | |
* | | '----------------' '----------------' |
* | | | | |
* | +---------+ +-----------+
* | | |
* | | v
* | | .----------------.
* | | EP:IN | |
* | |<-------------------| Transaction |
* | | zero-length-packet| complete |
* +------------+ '----------------'
* @endverbatim
*
* Settings are replied by the device depending on the request type.
* Settings may be sent to the device depending on the request type.
*
* @remarks IN endpoints transfer data from device to host
* @remarks OUT endpoints transfer data from host to device
* @remarks HAL_PCD_EP_Receive() and HAL_PCD_EP_Transmit() are the STM32 HAL function to handle USB data packet transfers, not byte data transfer.
* That means that both transmit exactly one USB data packet at a time and need to be called again for the next one. The size may be less than
* USB_EP_SIZE for HAL_PCD_EP_Transmit() but not for HAL_PCD_EP_Receive(). Providing a buffer less than USB_EP_SIZE for HAL_PCD_EP_Receive() may
* result in a buffer overrun. I.e. data after the buffer will be overwritten. Hence, the reception procedure requires 3 buffer: the device internal
* dedicated reception buffer, the internal packet reception buffer and the FIFO to the upper Arduino API layer.
* @remarks PMA memory is 32 bit aligned in general and 32 byte aligned for the packet buffers. Each 32 bit contain 16 bit of data. Each endpoint is
* handled using four 16 bit values. That means 16 byte of data (32 byte in memory) are necessary for each endpoint (including IN and OUT). Hence, for
* an MCU with 512 byte PMA memory (e.g. STM32F103, see UM0424) the highest endpoint number is 4 using 64 byte buffer per endpoint. USB CDC + HID is
* not possible in this configuration.
* @remarks HAL PCD handles endpoint transmission states in internal structures for IN and OUT that all contain the fields xfer_count, xfer_buff and
* xfer_len. Handling of these fields is not consistent between the various STM32 series and HAL versions which makes it impossible to rely on those
* to save some memory. The internal variables bytesPendingEp and bufferPtrEp are introduces instead.
* @see https://higaski.at/custom-class-for-stm32-usb-device-library/
* @see https://www.st.com/resource/en/user_manual/dm00108129-stm32cube-usb-device-library-stmicroelectronics.pdf
* @remarks Note bug for PMA handling in STM32F1 https://community.st.com/s/question/0D50X00009XkXLz
* @remarks USB HS is currently not supported.
*/
#include "Arduino.h"
#include "PluggableUSB.h"
#include "scdinternal/fifo.h"
#include "scdinternal/macro.h"
#ifdef USBCON
#ifndef USB_IRQ_PRIO
#error Please define USB_IRQ_PRIO in board.hpp.
#endif
#ifndef USB_IRQ_SUBPRIO
#error Please define USB_IRQ_SUBPRIO in board.hpp.
#endif
/* ensure that there is no macro remapping enforced for shared interrupt routines */
#undef USB_LP_CAN1_RX0_IRQHandler
#undef USB_LP_CAN1_RX0_IRQHandler
#ifndef USB_PRODUCT
/* if no product is provided, use USB IO Board */
#define USB_PRODUCT "USB IO Board"
#endif
#ifndef USB_MANUFACTURER
#if USB_VID == 0x2341
#define USB_MANUFACTURER "Arduino LLC"
#elif USB_VID == 0x0483
#define USB_MANUFACTURER "STMicroelectronics"
#else
/* fallback if no manufacturer name was provided */
#define USB_MANUFACTURER "Unknown"
#endif
#endif /* not USB_MANUFACTURER */
#ifndef PCD_EP_TYPE_CTRL
#define PCD_EP_TYPE_CTRL EP_TYPE_CTRL
#endif
#ifndef PCD_EP_TYPE_ISOC
#define PCD_EP_TYPE_ISOC EP_TYPE_ISOC
#endif
#ifndef PCD_EP_TYPE_BULK
#define PCD_EP_TYPE_BULK EP_TYPE_BULK
#endif
#ifndef PCD_EP_TYPE_INTR
#define PCD_EP_TYPE_INTR EP_TYPE_INTR
#endif
#ifndef USB_RX_SIZE
/** optimal memory/speed trace-off for USB FS was measured at USB_EP_SIZE * 2, maximum speed at USB_EP_SIZE * 3 for STM32F401 */
#define USB_RX_SIZE (USB_EP_SIZE * 2)
#endif /* USB_RX_SIZE */
#ifndef USB_TX_SIZE
/** optimal memory/speed trade-off for USB FS was measured at USB_EP_SIZE * 4 for STM32F401 */
#define USB_TX_SIZE (USB_EP_SIZE * 2)
#endif /* USB_TX_SIZE */
#if USB_RX_SIZE < (USB_EP_SIZE * 2)
#error USB_RX_SIZE needs to be at least 2 * USB_EP_SIZE.
#endif
#if USB_TX_SIZE < (USB_EP_SIZE * 2) || (USB_TX_SIZE % USB_EP_SIZE) != 0
#error USB_TX_SIZE needs to be a multiple of USB_EP_SIZE and at least 2 * USB_EP_SIZE.
#endif
/**
* @macro USB_TX_TRANSACTIONAL
* USB_TX_TRANSACTIONAL is defined in board.hpp if the used STM32Cube library handles
* multi-packet USB transactions with a single HAL_PCD_DataInStageCallback() call.
* Usually, the USB device will not enumerate properly if this is set incorrectly.
*/
#ifdef USB_TX_TRANSACTIONAL
#define USB_IO_TX_CHUNK(len) (len)
#else /* not USB_TX_TRANSACTIONAL */
#define USB_IO_TX_CHUNK(len) min(USB_EP_SIZE, (len))
#endif /* not USB_TX_TRANSACTIONAL */
#define DEVICE_CLASS 0xEF
#define DEVICE_SUB_CLASS 0x02
#define DEVICE_PROTOCOL 0x01
#define DEVICE_VERSION 0x100
/* Timeout for sends and receives. */
#define USB_WFI_TIMEOUT_MS 1000
#define USB_IO_TIMEOUT_MS 70
#define PP_CAT(x, y) x##y
#ifdef __thumb__
#define INST_TYPE uint16_t
#else
#define INST_TYPE uint32_t
#endif
/* timeout enabled wait to avoid deadlocks; timeout is only a rough estimation here */
#define USB_BUSY_WAIT_UNTIL(cond) [&]() -> bool { \
const uint32_t _instCount = reinterpret_cast<const INST_TYPE *>(&&PP_CAT(_jmp_end_, __LINE__)) - reinterpret_cast<const INST_TYPE *>(&&PP_CAT(_jmp_start_, __LINE__)); \
uint32_t _timeout = microsecondsToClockCycles(USB_IO_TIMEOUT_MS * 1000) / _instCount; /* we assume that each instruction takes one cycle */ \
PP_CAT(_jmp_start_, __LINE__): \
if ( !! (cond) ) return true; \
if (_timeout == 0) goto PP_CAT(_jmp_end_, __LINE__); \
_timeout--; \
goto PP_CAT(_jmp_start_, __LINE__); \
PP_CAT(_jmp_end_, __LINE__): \
return false; \
}()
/** STM32 HAL specific variable needed in usbFrameNumber(). */
extern uint32_t USBx_BASE;
extern const uint16_t STRING_LANGUAGE[];
extern const uint8_t STRING_PRODUCT[];
extern const uint8_t STRING_MANUFACTURER[];
extern const DeviceDescriptor USB_DeviceDescriptorIAD;
const DeviceDescriptor USB_DeviceDescriptorIAD = D_DEVICE(
DEVICE_CLASS, DEVICE_SUB_CLASS, DEVICE_PROTOCOL, USB_EP_SIZE,
USB_VID, USB_PID, DEVICE_VERSION,
IMANUFACTURER, IPRODUCT, ISERIAL,
1
);
const uint16_t STRING_LANGUAGE[2] = {(3 << 8) | (2 + 2), 0x0409 /* English */};
const uint8_t STRING_PRODUCT[] = USB_PRODUCT;
const uint8_t STRING_MANUFACTURER[] = USB_MANUFACTURER;
/* filled in PluggableUSB_::plug() */
uint8_t _usbEndpoints[USB_ENDPOINTS] = {
USB_ENDPOINT_TYPE_CONTROL | USB_ENDPOINT_IN(0) | USB_ENDPOINT_OUT(0),
0 /*, ... all zero */
};
namespace {
struct _UsbRxBuffer {
enum { PacketSize = USB_EP_SIZE };
typedef _FifoClass<USB_RX_SIZE - PacketSize> FifoType;
uint8_t packet[PacketSize]; /**< packet reception buffers */
FifoType fifo; /**< FIFO to upper layer */
};
struct _UsbTxBuffer {
typedef _BlockFifoClass<USB_TX_SIZE, USB_EP_SIZE> FifoType;
FifoType fifo; /**< FIFO to PHY */
volatile bool commitLock; /**< true if no commits are allowed from ISR */
};
void * _usbBuf[USB_ENDPOINTS] = {NULL}; /* index + 1 = endpoint number */
uint8_t _usbCtrlRecvBuf[64]; /* holds data from the host associated to a class interface setup request */
bool isRemoteWakeUpEnabled = false;
bool isEndpointHalt = false;
uint8_t ctrlStatBuf[2];
volatile uint16_t txPendingEp = 0; /* IN endpoints */
volatile uint16_t rxPendingEp = 0; /* OUT endpoints */
volatile uint32_t bytesPendingEp[USB_ENDPOINTS + 1]; /* for each endpoint; two for control */
uint8_t * bufferPtrEp[USB_ENDPOINTS + 1]; /* for each endpoint; two for control */
} /* anonymous namespace */
volatile uint8_t _usbConfiguration = 0;
volatile uint8_t _usbSetInterface = 0;
bool _dry_run = false;
bool _pack_message = false;
uint16_t _pack_size = 0;
uint8_t _pack_buffer[256];
PCD_HandleTypeDef hPcdUsb[1];
#ifdef PCD_SNG_BUF
/* C++ SFINAE for handling the absence of HAL_PCDEx_PMAConfig() as a NOP */
DEF_NO_FN_ARGS_WRAPPER(HAL_StatusTypeDef, HAL_PCDEx_PMAConfig_Wrapper, HAL_PCDEx_PMAConfig, HAL_OK, PCD_HandleTypeDef *, uint16_t, uint16_t, uint32_t)
#endif /* PCD_SNG_BUF */
/* C++ SFINAE for handling the absence of HAL_PCDEx_SetTxFiFo() and HAL_PCDEx_SetRxFiFo() as a NOP */
DEF_NO_FN_ARGS_WRAPPER(HAL_StatusTypeDef, HAL_PCDEx_SetTxFiFo_Wrapper, HAL_PCDEx_SetTxFiFo, HAL_OK, PCD_HandleTypeDef *, uint8_t, uint16_t)
DEF_NO_FN_ARGS_WRAPPER(HAL_StatusTypeDef, HAL_PCDEx_SetRxFiFo_Wrapper, HAL_PCDEx_SetRxFiFo, HAL_OK, PCD_HandleTypeDef *, uint16_t)
/**
* Calls the given functor or lambda for each available FS USB IRQn.
*
* @param[in] fn - functor or lamba to call (accepting one parameter of type IRQn_Type)
*/
template <typename Fn>
static void usbCallForEachIrqNum(Fn && fn) {
#define CALL_FOR_IRQ_NUM(x) CALL_FOR_EXISTING_FIELD(fn, IRQn_Type, x)
CALL_FOR_IRQ_NUM(OTG_FS_EP1_IN_IRQn);
CALL_FOR_IRQ_NUM(OTG_FS_EP1_OUT_IRQn);
CALL_FOR_IRQ_NUM(OTG_FS_IRQn);
CALL_FOR_IRQ_NUM(OTG_FS_WKUP_IRQn);
CALL_FOR_IRQ_NUM(OTG_IRQn);
CALL_FOR_IRQ_NUM(USBWakeUp_IRQn);
CALL_FOR_IRQ_NUM(USBWakeUp_RMP_IRQn);
CALL_FOR_IRQ_NUM(USB_FS_IRQn);
CALL_FOR_IRQ_NUM(USB_FS_WKUP_IRQn);
CALL_FOR_IRQ_NUM(USB_IRQn);
CALL_FOR_IRQ_NUM(USB_LP_CAN1_RX0_IRQn);
CALL_FOR_IRQ_NUM(USB_LP_CAN_RX0_IRQn);
CALL_FOR_IRQ_NUM(USB_LP_IRQn);
#undef CALL_FOR_IRQ_NUM
}
/**
* Enables all interrupts for USB FS.
*/
static inline void usbNvicEnable() {
usbCallForEachIrqNum([] (const IRQn_Type irqNum) -> void {
HAL_NVIC_EnableIRQ(irqNum);
});
}
/**
* Disables all interrupts for USB FS.
*/
static inline void usbNvicDisable() {
usbCallForEachIrqNum([] (const IRQn_Type irqNum) -> void {
HAL_NVIC_DisableIRQ(irqNum);
});
}
/**
* Sets the priority of all interrupts for USB FS.
*/
static inline void usbNvicSetPriority() {
usbCallForEachIrqNum([] (const IRQn_Type irqNum) -> void {
HAL_NVIC_SetPriority(irqNum, USB_IRQ_PRIO, USB_IRQ_SUBPRIO);
});
}
/**
* Returns the lowest priority (i.e. highest value) of all USB FS interrupts.
*
* @return lowest USB FS interrupt priority
*/
static inline uint32_t usbNvicGetLowestPriority() {
uint32_t res = 0;
usbCallForEachIrqNum([&res] (const IRQn_Type irqNum) {
const uint32_t prio = NVIC_GetPriority(irqNum);
if (prio > res) res = prio;
});
return res;
}
/**
* Returns the associated reception buffer for the given endpoint number.
*
* @param[in] epNum - endpoint number (>0)
* @return RX buffer or NULL
*/
static _UsbRxBuffer * usbRxBuffer(const uint8_t epNum) {
const uint8_t config = _usbEndpoints[epNum];
if ((config & USB_ENDPOINT_DIRECTION_MASK) != USB_ENDPOINT_OUT(0)) return NULL;
return reinterpret_cast<_UsbRxBuffer *>(_usbBuf[epNum - 1]);
}
/**
* Returns the associated transmission buffer for the given endpoint number.
*
* @param[in] epNum - endpoint number (>0)
* @return TX buffer or NULL
*/
static _UsbTxBuffer * usbTxBuffer(const uint8_t epNum) {
const uint8_t config = _usbEndpoints[epNum];
if ((config & USB_ENDPOINT_DIRECTION_MASK) != USB_ENDPOINT_IN(0)) return NULL;
return reinterpret_cast<_UsbTxBuffer *>(_usbBuf[epNum - 1]);
}
/**
* Deletes all allocated reception and transmission buffers.
*/
static void usbDeleteBuffers() {
for (uint8_t i = 0; i < (sizeof(_usbBuf) / sizeof(*_usbBuf)); i++) {
if (_usbBuf[i] != NULL) {
const uint8_t config = _usbEndpoints[i + 1];
if ((config & USB_ENDPOINT_DIRECTION_MASK) == USB_ENDPOINT_OUT(0)) {
delete usbRxBuffer(uint8_t(i + 1));
} else {
delete usbTxBuffer(uint8_t(i + 1));
}
}
_usbBuf[i] = NULL;
}
}
/**
* Returns the current USB frame number.
*
* @return USB frame number
*/
static uint32_t usbFrameNumber() {
#ifdef USB_OTG_DSTS_FNSOF
USB_OTG_GlobalTypeDef * USBx __attribute__((unused)) = hPcdUsb->Instance;
return uint32_t((USBx_DEVICE->DSTS & USB_OTG_DSTS_FNSOF_Msk) >> USB_OTG_DSTS_FNSOF_Pos);
#else
return uint32_t(hPcdUsb->Instance->FNR & USB_FNR_FN);
#endif
}
/**
* Sends data on the given endpoint. The operation blocks if there is still
* a previous data transmission ongoing. Else returns immediately if blocking is false.
*
* @param[in] ep - endpoint
* @param[in] data - data buffer
* @param[in] len - data length
* @param[in] blocking - block until all data was transferred
* @return true on success, else false on timeout
* @remarks The passed buffer needs to be valid until the data has been successfully transmitted.
*/
static bool sendOrBlock(const uint8_t ep, const void * data, const uint32_t len, const bool blocking = false) {
const uint8_t epNum = uint8_t(ep & 0xF);
const uint8_t epIdx = uint8_t(epNum + 1);
const uint16_t epMask = uint16_t(1 << uint16_t(epNum));
if ( blocking ) {
/* wait until last operation completed */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
if ( ! USB_BUSY_WAIT_UNTIL((txPendingEp & epMask) == 0) ) return false;
#pragma GCC diagnostic pop
} else if ((txPendingEp & epMask) != 0) {
return false;
}
txPendingEp |= epMask; /* mark as pending */
bufferPtrEp[epIdx] = const_cast<uint8_t *>(static_cast<const uint8_t *>(data));
bytesPendingEp[epIdx] = len;
HAL_PCD_EP_Transmit(hPcdUsb, ep, bufferPtrEp[epIdx], USB_IO_TX_CHUNK(len));
if ( blocking ) {
/* wait until the transmission completed */
const uint32_t startTime = millis();
while ((txPendingEp & epMask) != 0) {
__WFI();
if (uint32_t(millis() - startTime) >= USB_WFI_TIMEOUT_MS) break;
}
}
return true;
}
/**
* Triggers the transmission of a non-control endpoint by pushing the buffered
* data from its FIFO to the send routine. The function shall only be called if
* data can be transmitted (i.e. no pending data for that endpoint).
*
* @param[in] buf - output buffers
* @param[in] epNum - endpoint number
* @param[in] allowEmpty - true if empty packets are allowed, else false
*/
static void usbTriggerSend(_UsbTxBuffer & buf, const uint8_t epNum, const bool allowEmpty) {
uint32_t blockSize;
const uint8_t * blockPtr = buf.fifo.peek(blockSize);
if (blockPtr == NULL) return;
/* must disable interrupt to prevent handle lock contention */
usbNvicDisable();
__DMB(); __DSB(); __ISB(); /* data and instruction barrier */
#if USB_TX_SIZE >= (USB_EP_SIZE * 4) && defined(USB_TX_TRANSACTIONAL)
const _UsbTxBuffer::FifoType::IndexType nextTail = _UsbTxBuffer::FifoType::IndexType(buf.fifo.tail + 1);
if (blockSize >= USB_EP_SIZE && nextTail < _UsbTxBuffer::FifoType::Count && nextTail != buf.fifo.head) {
/* queue two blocks at once */
sendOrBlock(USB_ENDPOINT_IN(epNum), blockPtr, blockSize + buf.fifo.size[nextTail]);
} else
#endif
if (blockSize > 0) {
sendOrBlock(USB_ENDPOINT_IN(epNum), blockPtr, blockSize);
} else if ( allowEmpty ) {
sendOrBlock(USB_ENDPOINT_IN(epNum), NULL, 0);
}
/* enable interrupt */
usbNvicSetPriority();
usbNvicEnable();
}
/**
* Send data to an endpoint. Block until the transmission finished.
* This function is needed to handle flags that may get passed together
* with the endpoint in `USB_Send()`.
*
* @param[in] flags - `TRANSFER_ZERO`, `TRANSFER_RELEASE` and/or `TRANSFER_PGM`
* @param[in] ep - endpoint number
* @param[in] data - data buffer
* @param[in] len - data length
* @return bytes transmitted
*/
static uint32_t sendHelper(const uint8_t flags, const uint32_t ep, const void * data, uint32_t len) {
if ( ! _usbConfiguration ) return uint32_t(-1);
const uint8_t epNum = uint8_t(ep & 0xF);
if (usbTxBuffer(epNum) == NULL) {
if ( ! sendOrBlock(USB_ENDPOINT_IN(ep), data, len, true) ) return 0;
} else {
_UsbTxBuffer & buf = *usbTxBuffer(epNum);
bool canWait = false;
const bool zlp = (len == 0);
const bool interruptsEnabled = ((__get_PRIMASK() & 0x1) == 0);
const uint16_t epMask = uint16_t(1 << uint16_t(epNum));
if ( interruptsEnabled ) {
const uint32_t irqExecutionNumber = SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk;
if (irqExecutionNumber == 0 || NVIC_GetPriority(IRQn_Type(irqExecutionNumber - 16)) > usbNvicGetLowestPriority()) {
/* USB interrupt is enabled and we were not called from an interrupt with higher priority */
canWait = true;
}
}
/* write data to queue */
buf.commitLock = true;
if ( canWait ) {
/* wait until space is available and add to queue */
__DMB(); __DSB(); __ISB(); /* data and instruction barrier */
const uint8_t * dataBuf = reinterpret_cast<const uint8_t *>(data);
for (uint32_t i = 0; i < len; dataBuf++, i++) {
const uint32_t startTime = millis();
while ( ! buf.fifo.push(((flags & TRANSFER_ZERO) == 0) ? *dataBuf : 0) ) {
if ((txPendingEp & epMask) == 0) {
/* trigger send in case something clogged up */
usbTriggerSend(buf, epNum, false);
break;
}
__WFI();
if (uint32_t(millis() - startTime) >= USB_WFI_TIMEOUT_MS) {
/* interface got stuck -> reattach it */
USBDevice.detach();
USBDevice.attach();
return i;
}
}
}
if ((flags & TRANSFER_RELEASE) != 0) {
const uint32_t startTime = millis();
while ( ! buf.fifo.commitBlock() ) {
if ((txPendingEp & epMask) == 0) {
/* trigger send in case something clogged up */
usbTriggerSend(buf, epNum, false);
break;
}
__WFI();
if (uint32_t(millis() - startTime) >= USB_WFI_TIMEOUT_MS) {
/* interface got stuck -> reattach it */
USBDevice.detach();
USBDevice.attach();
return len;
}
}
}
} else {
/* add to queue or fail if no space is available, because there is currently no chance to get data out */
if (( ! buf.fifo.full() ) || (flags & TRANSFER_RELEASE) == 0) {
uint32_t written;
if ((flags & TRANSFER_ZERO) == 0) {
written = buf.fifo.write(reinterpret_cast<const uint8_t *>(data), len);
if (written < len && (txPendingEp & epMask) == 0) {
usbTriggerSend(buf, epNum, false);
written += buf.fifo.write(reinterpret_cast<const uint8_t *>(data) + written, uint32_t(len - written));
}
} else {
/* write only zero bytes */
for (written = 0; written < len && buf.fifo.push(0); written++);
if (written < len && (txPendingEp & epMask) == 0) {
usbTriggerSend(buf, epNum, false);
for (; written < len && buf.fifo.push(0); written++);
}
}
if ((flags & TRANSFER_RELEASE) != 0) {
buf.fifo.commitBlock();
}
len = written;
} else {
/* TRANSFER_RELEASE was requested but no free block is available to handle this */
len = 0;
}
}
buf.commitLock = false;
/* the interrupt routine may send out the queued data at this point */
__DMB(); __DSB(); __ISB(); /* data and instruction barrier */
if ((txPendingEp & epMask) != 0) return len;
if ((flags & TRANSFER_RELEASE) != 0 || zlp) {
/* start endpoint transmission from idle state */
usbTriggerSend(buf, epNum, zlp);
}
}
return len;
}
/**
* Receives data on the given endpoint. The operation fails if there is still
* a previous data reception ongoing. It may be set blocking until completion.
*
* @param[in] ep - endpoint
* @param[out] data - data buffer
* @param[in] len - buffer size
* @param[in] blocking - block until all data was received
* @return true on success (not necessary completion), else false
* @remarks The passed buffer needs to be valid until the data has been successfully received.
*/
static bool recvOrFail(const uint8_t ep, void * data, const uint32_t len, const bool blocking = false) {
const uint8_t epNum = uint8_t(ep & 0xF);
const uint8_t epIdx = (epNum == 0) ? 0 : uint8_t(epNum + 1);
const uint16_t epMask = uint16_t(1 << uint16_t(epNum));
if ( blocking ) {
/* wait until last operation completed */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
if ( ! USB_BUSY_WAIT_UNTIL((rxPendingEp & epMask) == 0) ) return false;
#pragma GCC diagnostic pop
} else if ((rxPendingEp & epMask) != 0) {
return false;
}
rxPendingEp |= epMask; /* mark as pending */
bytesPendingEp[epIdx] = len;
HAL_PCD_EP_Receive(hPcdUsb, ep, reinterpret_cast<uint8_t *>(data), len);
if ( blocking ) {
/* wait until the reception completed */
const uint32_t startTime = millis();
while ((rxPendingEp & epMask) != 0) {
__WFI();
if (uint32_t(millis() - startTime) >= USB_WFI_TIMEOUT_MS) break;
}
}
return true;
}
/**
* Initializes the USB peripheral device.
*
* @remarks Enabling DMA transfer is currently not supported.
*/
void USBDeviceClass::init() {
/* initialize the USB device */
hPcdUsb->pData = this;
#ifdef USB_OTG_FS
hPcdUsb->Instance = USB_OTG_FS;
#else
hPcdUsb->Instance = USB;
#endif
hPcdUsb->Init.dev_endpoints = USB_ENDPOINTS; /* see USBDesc.h */
hPcdUsb->Init.speed = PCD_SPEED_FULL;
hPcdUsb->Init.phy_itface = PCD_PHY_EMBEDDED;
hPcdUsb->Init.low_power_enable = DISABLE;
hPcdUsb->Init.lpm_enable = DISABLE; /* Link Power Management */
hPcdUsb->Init.battery_charging_enable = DISABLE;
if (HAL_PCD_Init(hPcdUsb) != HAL_OK) {
systemErrorHandler();
return;
}
this->initialized = true;
}
/**
* De-initializes the USB peripheral device.
*
* @returns true on success, else false if no device had been previously initialized
*/
bool USBDeviceClass::end() {
if ( ! this->initialized ) return false;
HAL_PCD_DeInit(hPcdUsb);
usbDeleteBuffers();
return true;
}
/**
* Attach and start the USB device.
*
* @return true on success, else false
*/
bool USBDeviceClass::attach() {
if ( ! this->initialized ) return false;
_usbConfiguration = 0;
txPendingEp = 0;
rxPendingEp = 0;
for (size_t i = 0; i < (sizeof(bytesPendingEp) / sizeof(*bytesPendingEp)); i++) {
bytesPendingEp[i] = 0;
}
HAL_PCD_Start(hPcdUsb);
return true;
}
/**
* Detaches and stops the USB device.
*
* @return true on success, else false
*/
bool USBDeviceClass::detach() {
if ( ! this->initialized ) return false;
HAL_PCD_Stop(hPcdUsb);
usbDeleteBuffers();
return true;
}
/**
* Sets the USB device address.
*
* @param[in] addr - new address
*/
void USBDeviceClass::setAddress(uint32_t addr) {
HAL_PCD_SetAddress(hPcdUsb, uint8_t(addr));
}
/**
* Returns whether the USB device had been configured.
*
* @return true if configured, else false
*/
bool USBDeviceClass::configured() {
return _usbConfiguration != 0;
}
/**
* Returns whether the USB device is connected to a host.
*
* @return true if connected, else false
*/
bool USBDeviceClass::connected() {
const uint32_t frameNumber = usbFrameNumber();
delay(3); /* we receive one frame every millisecond in connected state */
return frameNumber != usbFrameNumber();
}
/**
* Resumes operation from standby.
*
* @remark This function is currently unsupported.
*/
void USBDeviceClass::standby() {
/* returning from standby is unsupported */
}
/**
* Handles the class interface setup request.
*
* @param[in] setup - setup message
* @return true on success, else false
*/
bool USBDeviceClass::handleClassInterfaceSetup(USBSetup & setup) {
bool res = PluggableUSB().setup(setup);
if (res == false || setup.bmRequestType == REQUEST_HOSTTODEVICE_CLASS_INTERFACE) {
this->sendZlp(0);
}
return res;
}
/**
* Handles the standard setup request.
*
* @param[in] setup - setup message
* @return true on success, else false
*/
bool USBDeviceClass::handleStandardSetup(USBSetup & setup) {
const uint16_t wValue = uint16_t((uint16_t(setup.wValueH) << 8) | setup.wValueL);
const uint8_t ep = uint8_t(setup.wIndex & 0xFF);
switch (setup.bRequest) {
case GET_STATUS:
switch (setup.bmRequestType & REQUEST_RECIPIENT) {
case REQUEST_DEVICE:
/* send the device status */
ctrlStatBuf[0] = 0;
ctrlStatBuf[1] = 0;
this->sendControl(ctrlStatBuf, 2);
break;
case REQUEST_ENDPOINT:
/* send the endpoint status and check if the endpoint is currently halted */
ctrlStatBuf[0] = isEndpointHalt ? 1 : 0;
ctrlStatBuf[1] = 0;
this->sendControl(ctrlStatBuf, 2);
break;
default:
return false;
}
break;
case CLEAR_FEATURE:
/* remove selected feature */
switch (wValue) {
case ENDPOINT_HALT:
isEndpointHalt = false;
if ((ep & 0xF) != 0) {
HAL_PCD_EP_ClrStall(hPcdUsb, ep);
}
this->sendZlp(0);
break;
case DEVICE_REMOTE_WAKEUP:
/* disable remote wake-up and send a ZLP */
HAL_PCD_DeActivateRemoteWakeup(hPcdUsb);
ctrlStatBuf[0] = isEndpointHalt ? 1 : 0;
ctrlStatBuf[1] = 0;
this->sendControl(ctrlStatBuf, 2);
break;
default:
break; /* silently ignored */
}
break;
case SET_FEATURE:
/* add selected feature */
switch (wValue) {
case ENDPOINT_HALT:
/* halt endpoint */
isEndpointHalt = true;
if ((ep & 0xF) != 0 && setup.wLength == 0) {
HAL_PCD_EP_SetStall(hPcdUsb, ep);
}
this->sendZlp(0);
break;
case DEVICE_REMOTE_WAKEUP:
/* enable remote wake-up and send a ZLP */
isRemoteWakeUpEnabled = true;
HAL_PCD_ActivateRemoteWakeup(hPcdUsb);
ctrlStatBuf[0] = 0;
this->sendControl(ctrlStatBuf, 1);
break;
default:
break; /* silently ignored */
}
break;
case SET_ADDRESS:
this->setAddress(setup.wValueL);
this->sendZlp(0);
break;
case GET_DESCRIPTOR:
return this->sendDescriptor(setup);
case SET_DESCRIPTOR:
return false;
case GET_CONFIGURATION:
ctrlStatBuf[0] = _usbConfiguration;
this->sendControl(ctrlStatBuf, 1);
break;
case SET_CONFIGURATION:
if ((setup.bmRequestType & REQUEST_RECIPIENT) == REQUEST_DEVICE) {
this->initEndpoints();
_usbConfiguration = setup.wValueL; /* bConfigurationValue */
this->sendZlp(0);
} else {
return false;
}
break;
case GET_INTERFACE:
ctrlStatBuf[0] = _usbSetInterface;
this->sendControl(ctrlStatBuf, 1);
break;
case SET_INTERFACE:
_usbSetInterface = setup.wValueL;
this->sendZlp(0);
break;
default:
return false;
}
return true;
}
/**
* Sends out the device descriptor for the request from given setup.
*
* @param[in] setup - setup message
* @return true on success, else false
*/
bool USBDeviceClass::sendDescriptor(USBSetup & setup) {
const uint8_t * descAddr = NULL;
uint8_t descLength = 0;
if (setup.wValueH == USB_CONFIGURATION_DESCRIPTOR_TYPE) {
return USBDevice.sendConfiguration(setup.wLength);
}
#ifdef PLUGGABLE_USB_ENABLED
const int res = PluggableUSB().getDescriptor(setup);
if (res != 0) {
return (res > 0 ? true : false);
}
#endif /* PLUGGABLE_USB_ENABLED */
switch (setup.wValueH) {
case USB_DEVICE_DESCRIPTOR_TYPE:
descAddr = reinterpret_cast<const uint8_t *>(&USB_DeviceDescriptorIAD);
descLength = *descAddr;
/* sent at the end of the function */
break;
case USB_STRING_DESCRIPTOR_TYPE:
switch (setup.wValueL) {
case 0:
descAddr = reinterpret_cast<const uint8_t *>(&STRING_LANGUAGE);
descLength = *descAddr;
/* sent at the end of the function */
break;
case IPRODUCT:
return this->sendStringDescriptor(STRING_PRODUCT, setup.wLength);
case IMANUFACTURER:
return this->sendStringDescriptor(STRING_MANUFACTURER, setup.wLength);
case ISERIAL:
{
char name[ISERIAL_MAX_LEN] = {0};
uint8_t len = 0;
#ifdef UID_BASE
const uint32_t * uidPtr = reinterpret_cast<const uint32_t *>(UID_BASE);
const uint32_t uid = uidPtr[0] ^ uidPtr[1] ^ uidPtr[2];
for (; len < 8; len++) {
name[len] = "0123456789ABCDEF"[(uid >> (4 * len)) & 0xF];
}
#endif /* UID_BASE */
#ifdef PLUGGABLE_USB_ENABLED
len = uint8_t(len + PluggableUSB().getShortName(name + len));
#endif /* PLUGGABLE_USB_ENABLED */
if (len > 0) {
return this->sendStringDescriptor(reinterpret_cast<const uint8_t *>(name), setup.wLength);
}
}
return false;
default:
return false;
}
break;
default:
return false;
}
this->sendControl(descAddr, min(descLength, setup.wLength));
return true;
}
/**
* Sends the given data on the control endpoint.
*
* @param[in] data - data buffer
* @param[in] len - data length
* @return processed data length
*/
uint32_t USBDeviceClass::sendControl(const void * data, uint32_t len) {
if ( _dry_run ) return len;
if ( _pack_message ) {
memcpy(_pack_buffer + _pack_size, data, len);
_pack_size = uint16_t(_pack_size + len);
return len;
}
sendOrBlock(USB_ENDPOINT_IN(0), data, len);
return len;
}
/**
* Received data from the control endpoint. This function blocks until
* some data has been received.
*
* @param[out] data - data buffer
* @param[in] len - buffer size
* @return received data length
*/
uint32_t USBDeviceClass::recvControl(void * data, uint32_t len) {
const uint32_t receivedLen = this->available(USB_ENDPOINT_OUT(0));
const uint32_t received = min(len, receivedLen);
if (received > 0) {
memcpy(data, _usbCtrlRecvBuf, size_t(received));
}
return received;
}
/**
* Construct and sends a dynamic configuration descriptor to the host.
*
* @param[in] maxLen - requested maximum send size
* @return true on success, else false
*/
bool USBDeviceClass::sendConfiguration(uint32_t maxLen) {
/* get the total size for the interface configuration */
_dry_run = true;
uint32_t total = 0;
const uint8_t interfaces = this->SendInterfaces(&total);
const ConfigDescriptor config = D_CONFIG(uint16_t(sizeof(ConfigDescriptor) + total), interfaces);
_dry_run = false;
/* send the actual configuration */
if (maxLen == sizeof(ConfigDescriptor)) {
this->sendControl(&config, sizeof(ConfigDescriptor));
return true;
}
total = 0;
this->packMessages(true);
this->sendControl(&config, sizeof(ConfigDescriptor));
this->SendInterfaces(&total);
/* configuration descriptor is sent complete without any truncation to maxLen */
this->packMessages(false);
return true;
}
/**
* Sends the USB descriptor string. This function internally performs the
* ASCII to UTF-16 conversion which is needed here.
*
* @param[in] string - USB descriptor string
* @param[in] maxLen - requested maximum send size
* return true on success, else false
*/
bool USBDeviceClass::sendStringDescriptor(const uint8_t * string, uint32_t maxLen) {
if (maxLen < 2) return false;
if (maxLen == 2) {
ctrlStatBuf[0] = 2; /* bLength */
ctrlStatBuf[1] = 0x03; /* bDescriptorType: String */
this->sendControl(ctrlStatBuf, 2);
return true;
}
size_t outLen = (strlen(reinterpret_cast<const char *>(string)) + 1) * 2;
if (outLen > maxLen) outLen = maxLen;
/* reuse _pack_buffer to avoid additional memory allocations */
if (outLen > sizeof(_pack_buffer)) outLen = sizeof(_pack_buffer);
_pack_buffer[0] = uint8_t(outLen); /* bLength */
_pack_buffer[1] = 0x03; /* bDescriptorType: String */
/* bString: */