4 * This file is part of BeRTOS.
6 * Bertos is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * As a special exception, you may use this file as part of a free software
21 * library without restriction. Specifically, if other files instantiate
22 * templates or use macros or inline functions from this file, or you compile
23 * this file and link it with other files to produce an executable, this
24 * file does not by itself cause the resulting executable to be covered by
25 * the GNU General Public License. This exception does not however
26 * invalidate any other reasons why the executable file might be covered by
27 * the GNU General Public License.
29 * Copyright 2010 Develer S.r.l. (http://www.develer.com/)
33 * \brief STM32 USB driver
35 * \author Andrea Righi <arighi@develer.com>
38 #include "cfg/cfg_usb.h"
40 #define LOG_LEVEL USB_LOG_LEVEL
41 #define LOG_FORMAT USB_LOG_FORMAT
44 #include <cfg/debug.h>
45 #include <cfg/macros.h>
46 #include <cfg/module.h>
49 #include <cpu/power.h>
51 #include <drv/irq_cm3.h>
52 #include <drv/gpio_stm32.h>
53 #include <drv/clock_stm32.h>
54 #include <drv/timer.h>
57 #include <string.h> /* memcpy() */
59 #include "usb_stm32.h"
61 #define ALIGN_UP(value, align) (((value) & ((align) - 1)) ? \
62 (((value) + ((align) - 1)) & ~((align) - 1)) : \
64 /* STM32 USB registers */
75 reg32_t __reserved[8];
83 /* Hardware registers */
84 static struct stm32_usb *usb = (struct stm32_usb *)USB_BASE_ADDR;
86 /* Endpoint descriptors: used for handling requests to use with endpoints */
87 static stm32_usb_ep_t ep_cnfg[ENP_MAX_NUMB];
89 /* USB EP0 control descriptor */
90 static const usb_endpoint_descriptor_t USB_CtrlEpDescr0 =
92 .bLength = sizeof(USB_CtrlEpDescr0),
93 .bDescriptorType = USB_DT_ENDPOINT,
94 .bEndpointAddress = USB_DIR_OUT | 0,
95 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
96 .wMaxPacketSize = USB_EP0_MAX_SIZE,
100 /* USB EP1 control descriptor */
101 static const usb_endpoint_descriptor_t USB_CtrlEpDescr1 =
103 .bLength = sizeof(USB_CtrlEpDescr1),
104 .bDescriptorType = USB_DT_ENDPOINT,
105 .bEndpointAddress = USB_DIR_IN | 0,
106 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
107 .wMaxPacketSize = USB_EP0_MAX_SIZE,
111 /* USB setup packet */
112 static usb_ctrlrequest_t setup_packet;
114 /* USB device controller: max supported interfaces */
115 #define USB_MAX_INTERFACE 1
117 /* USB device controller features */
118 #define STM32_UDC_FEATURE_SELFPOWERED BV(0)
119 #define STM32_UDC_FEATURE_REMOTE_WAKEUP BV(1)
121 /* Hardware-specific USB device controller structure */
122 typedef struct stm32_udc
126 const usb_config_descriptor_t *cfg;
128 uint32_t alt[USB_MAX_INTERFACE];
131 } PACKED stm32_udc_t;
133 /* Hardware-specific USB Device Controller */
134 static stm32_udc_t udc;
136 /* Generic USB Device Controller structure */
137 static struct usb_device *usb_dev;
139 /* USB packet memory management: list of allocated chunks */
140 static pack_mem_slot_t *pPacketMemUse;
142 /* USB packet memory management: memory buffer metadata */
143 #define EP_MAX_SLOTS 16
144 static pack_mem_slot_t PacketMemBuff[EP_MAX_SLOTS];
146 /* Allocate a free block of the packet memory */
147 static pack_mem_slot_t *usb_malloc(void)
151 for (i = 0; i < countof(PacketMemBuff); i++)
152 if (PacketMemBuff[i].Size == 0)
153 return &PacketMemBuff[i];
157 /* Release a block of the packet memory */
158 static void usb_free(pack_mem_slot_t *pPntr)
163 /* Allocate a free chunk of the packet memory (inside a block) */
164 static bool USB_AllocateBuffer(uint16_t *pOffset, uint32_t *pPacketSize,
167 pack_mem_slot_t *pPacketMem = pPacketMemUse,
168 *pPacketMemNext, *pPacketMemUseNew;
169 uint32_t MaxPacketSize = *pPacketSize;
172 * Packet size alignment:
173 * - fine-granularity allocation: size alignment by 2;
174 * - coarse-granularity allocation: size alignment by 32.
176 if (MaxPacketSize < 62)
177 MaxPacketSize = ALIGN_UP(MaxPacketSize, 2);
179 MaxPacketSize = ALIGN_UP(MaxPacketSize, 32);
181 * Finding free memory chunks from the allocated blocks of the USB
185 while (pPacketMem != NULL)
187 /* Offset alignment by 4 */
188 *pOffset = ALIGN_UP(pPacketMem->Start + pPacketMem->Size, 4);
189 pPacketMemNext = pPacketMem->next;
190 if ((pPacketMem->next == NULL) ||
191 (pPacketMemNext->Start >=
192 *pOffset + MaxPacketSize))
194 pPacketMem = pPacketMem->next;
196 /* Check for out-of-memory condition */
197 if ((*pOffset + MaxPacketSize) >= USB_BDT_OFFSET)
200 * Allocate a new memory block, next to the last allocated block.
202 pPacketMemUseNew = usb_malloc();
203 if (pPacketMemUseNew == NULL)
205 /* Insert the block to the list of allocated blocks */
206 if (pPacketMemUse == NULL)
208 pPacketMemUse = pPacketMemUseNew;
209 pPacketMemUse->next = NULL;
213 pPacketMemUseNew->next = pPacketMem->next;
214 pPacketMem->next = pPacketMemUseNew;
216 /* Update block's metadata */
217 pPacketMemUseNew->ep_addr = EndPoint;
218 pPacketMemUseNew->Start = *pOffset;
219 pPacketMemUseNew->Size = MaxPacketSize;
221 *pPacketSize = MaxPacketSize;
226 /* Release a chunk of the packet memory (inside a block) */
227 static void USB_ReleaseBuffer(int EndPoint)
229 pack_mem_slot_t *pPacketMem, *pPacketMemPrev = NULL;
230 pPacketMem = pPacketMemUse;
232 while (pPacketMem != NULL)
234 if (pPacketMem->ep_addr == EndPoint)
236 if (UNLIKELY(pPacketMemPrev == NULL))
238 /* Free the first element of the list */
239 pPacketMemUse = pPacketMemUse->next;
240 usb_free(pPacketMem);
241 pPacketMem = pPacketMemUse;
244 pPacketMemPrev->next = pPacketMem->next;
245 usb_free(pPacketMem);
248 pPacketMemPrev = pPacketMem;
249 pPacketMem = pPacketMemPrev->next;
253 /*-------------------------------------------------------------------------*/
255 /* Connect USB controller */
256 static void usb_connect(void)
258 stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE, 1 << 11, 0);
261 /* Set USB device address */
262 static void usb_set_address(uint32_t addr)
264 usb->DADDR = addr | 0x80;
267 /* Suspend USB controller */
268 static void usb_suspend(void)
270 usb->CNTR |= bmFSUSP | bmLPMODE;
273 /* Resume USB controller */
274 static void usb_resume(void)
276 uint32_t line_status;
278 line_status = usb->FNR & 0xc000;
281 /* check for noise and eventually return to sleep */
282 if (line_status == 0xc000)
285 usb->CNTR &= ~(bmFSUSP | bmLPMODE);
288 /* Convert logical EP address to physical EP address */
289 static int USB_EpLogToPhysAdd(uint8_t ep_addr)
291 int addr = (ep_addr & 0x0f) << 1;
292 return (ep_addr & 0x80) ? addr + 1 : addr;
296 static void EpCtrlSet_EA(reg32_t *reg, uint32_t val)
299 val |= *reg & 0x0700;
300 val |= USB_CTRL_CLEAR_ONLY_MASK;
304 /* Get EP IN status */
305 static uint32_t EpCtrlGet_STAT_TX(reg32_t *reg)
307 return (*reg & (0x3UL << 4)) >> 4;
310 /* Set EP IN state */
311 static void EpCtrlSet_STAT_TX(reg32_t *reg, ep_state_t val)
317 * The EP can change state between read and write operations from VALID
318 * to NAK and result of set operation will be invalid.
320 for (i = 0; i < 2; i++)
322 if (EpCtrlGet_STAT_TX(reg) == val)
327 state |= USB_CTRL_CLEAR_ONLY_MASK;
328 /* Clear the toggle bits without STAT_TX (4,5) */
334 /* Set EP DTOG_TX bit (IN) */
335 static void EpCtrlSet_DTOG_TX(reg32_t *reg, uint32_t val)
337 val = val ? (*reg ^ (1UL << 6)) : *reg;
338 /* Clear the toggle bits without DTOG_TX (6) */
340 val |= USB_CTRL_CLEAR_ONLY_MASK;
344 /* Clear EP CTR_TX bit (IN) */
345 static void EpCtrlClr_CTR_TX(reg32_t *reg)
349 val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 7);
355 /* Clear EP CTR_RX bit (OUT) */
356 static void EpCtrlClr_CTR_RX(reg32_t *reg)
359 val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 15);
365 /* Set EP KIND bit */
366 static void EpCtrlSet_EP_KIND(reg32_t *reg, uint32_t val)
368 val = val ? (1UL << 8) : 0;
369 val |= *reg & ~(USB_CTRL_TOGGLE_MASK | (1UL << 8));
370 val |= USB_CTRL_CLEAR_ONLY_MASK;
375 static int EpCtrlSet_EP_TYPE(reg32_t *reg, uint8_t val)
379 if (UNLIKELY(val >= EP_TYPE_MAX))
382 return USB_INVAL_ERROR;
386 type |= *reg & ~(USB_CTRL_TOGGLE_MASK | (0x3UL << 9));
387 type |= USB_CTRL_CLEAR_ONLY_MASK;
393 /* Get EP STAT_RX (OUT) */
394 static uint32_t EpCtrlGet_STAT_RX(reg32_t *reg)
396 uint32_t val = *reg & (0x3UL << 12);
400 /* Set EP STAT_RX (OUT) */
401 static void EpCtrlSet_STAT_RX(reg32_t *reg, ep_state_t val)
407 * The EP can change state between read and write operations from VALID
408 * to NAK and result of set operation will be invalid.
410 for (i = 0; i < 2; i++)
412 if (EpCtrlGet_STAT_RX(reg) == val)
417 state |= USB_CTRL_CLEAR_ONLY_MASK;
418 /* Clear the toggle bits without STAT_RX (12,13) */
424 /* Set DTOG_RX bit */
425 static void EpCtrlSet_DTOG_RX(reg32_t *reg, uint32_t val)
427 val = val ? (*reg ^ (1UL << 14)) : *reg;
428 /* Clear the toggle bits without DTOG_RX (14) */
430 val |= USB_CTRL_CLEAR_ONLY_MASK;
434 /* Get EP SETUP bit */
435 static uint32_t EpCtrlGet_SETUP(reg32_t *reg)
437 uint32_t val = *reg & (1UL << 11);
441 /* Core endpoint I/O function */
442 static void __usb_ep_io(int EP)
444 ssize_t Count, CountHold, Offset;
445 uint32_t *pDst, *pSrc, Data;
447 stm32_usb_ep_t *epd = &ep_cnfg[EP];
450 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
456 Count = epd->size - epd->offset;
457 while (epd->avail_data)
459 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
463 epd->status = BEGIN_SERVICED;
465 if ((epd->flags & STM32_USB_EP_ZERO_PACKET) &&
466 (Count == epd->max_size))
467 epd->flags |= STM32_USB_EP_ZERO_PACKET |
468 STM32_USB_EP_ZERO_POSSIBLE;
470 CountHold = Count = MIN(Count, epd->max_size);
472 epd->flags |= STM32_USB_EP_ZERO_PACKET;
473 Offset = epd->offset;
474 epd->offset += Count;
475 CurrentBuffer = true;
478 case USB_ENDPOINT_XFER_CONTROL:
479 case USB_ENDPOINT_XFER_INT:
480 pDst = (uint32_t *)addr2usbmem(ReadEpDTB_AddrTx(EP >> 1));
482 case USB_ENDPOINT_XFER_BULK:
483 pDst = (uint32_t *)addr2usbmem(ReadEpDTB_AddrTx(EP >> 1));
485 case USB_ENDPOINT_XFER_ISOC:
486 LOG_ERR("%s: isochronous transfer not supported\n",
488 /* Fallback to default */
494 /* Write data to packet memory buffer */
497 Data = *(epd->write_buffer + Offset++);
500 Data |= (uint32_t)(*(epd->write_buffer + Offset++)) << 8;
507 WriteEpDTB_CountTx(EP >> 1, CountHold);
509 WriteEpDTB_CountRx(EP >> 1, CountHold);
511 EpCtrlSet_STAT_TX(epd->hw, EP_VALID);
513 --ep_cnfg[EP].avail_data;
514 Count = epd->size - epd->offset;
516 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
518 epd->status = COMPLETE;
519 /* call callback function */
527 while (epd->avail_data)
529 /* Get data size and buffer pointer */
532 case USB_ENDPOINT_XFER_CONTROL:
533 case USB_ENDPOINT_XFER_INT:
534 /* Get received bytes number */
535 Count = ReadEpDTB_CountRx(EP >> 1) & 0x3FF;
536 /* Get address of the USB packet buffer for corresponding EP */
537 pSrc = (uint32_t *)addr2usbmem(ReadEpDTB_AddrRx(EP >> 1));
539 case USB_ENDPOINT_XFER_BULK:
540 /* Get received bytes number */
541 Count = ReadEpDTB_CountRx(EP >> 1) & 0x3FF;
542 /* Get address of the USB packet buffer for corresponding EP */
543 pSrc = (uint32_t *)addr2usbmem(ReadEpDTB_AddrRx(EP >> 1));
545 case USB_ENDPOINT_XFER_ISOC:
546 LOG_ERR("%s: isochronous transfer not supported\n",
548 /* Fallback to default */
554 if (Count > (epd->size - epd->offset))
556 epd->status = BUFFER_OVERRUN;
557 epd->size = ep_cnfg[EP].offset;
560 else if (Count < ep_cnfg[EP].max_size)
562 epd->status = BUFFER_UNDERRUN;
563 epd->size = ep_cnfg[EP].offset + Count;
566 epd->status = BEGIN_SERVICED;
568 Offset = epd->offset;
569 epd->offset += Count;
571 /* Read data from packet memory buffer */
575 *(epd->read_buffer + Offset++) = Data;
579 *(epd->read_buffer + Offset++) = Data;
584 EpCtrlSet_STAT_RX(epd->hw, EP_VALID);
586 --ep_cnfg[EP].avail_data;
588 if (*epd->hw & (1UL << 11))
590 ep_cnfg[EP].status = SETUP_OVERWRITE;
593 if (!(Count = (epd->size - epd->offset)))
595 epd->status = COMPLETE;
599 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
601 /* call callback function */
608 /* Configure an EP descriptor before performing a I/O operation */
609 #define USB_EP_IO(__EP, __op, __buf, __size, __complete) \
612 stm32_usb_io_status_t ret; \
614 /* Fill EP descriptor */ \
615 IRQ_SAVE_DISABLE(flags); \
618 ep_cnfg[__EP].status = NOT_READY; \
619 ep_cnfg[__EP].complete = NULL; \
623 if (ep_cnfg[__EP].status == BEGIN_SERVICED) \
629 * NOTE: the write_buffer and read_buffer are actually the \
630 * same location in memory (it's a union). \
632 * We have to do this trick to silent a build warning by \
633 * casting the I/O buffer to (void *) or (const void *). \
635 ep_cnfg[__EP].__op ## _buffer = __buf; \
636 ep_cnfg[__EP].offset = 0; \
637 ep_cnfg[__EP].size = __size; \
638 ep_cnfg[__EP].complete = __complete; \
640 ep_cnfg[__EP].flags = STM32_USB_EP_ZERO_PACKET; \
642 ep_cnfg[__EP].flags = 0; \
643 ep_cnfg[__EP].status = NO_SERVICED; \
645 /* Perform the I/O operation */ \
648 ret = ep_cnfg[__EP].status; \
650 IRQ_RESTORE(flags); \
654 /* Configure and endponint and perform a read operation */
655 static stm32_usb_io_status_t
656 __usb_ep_read(int ep, void *buffer, ssize_t size, void (*complete)(int))
658 if (UNLIKELY(ep >= ENP_MAX_NUMB))
663 ASSERT(!(ep & 0x01));
664 return USB_EP_IO(ep, read, buffer, size, complete);
667 /* Configure and endponint and perform a write operation */
668 static stm32_usb_io_status_t
669 __usb_ep_write(int ep, const void *buffer, ssize_t size, void (*complete)(int))
671 if (UNLIKELY(ep >= ENP_MAX_NUMB))
677 return USB_EP_IO(ep, write, buffer, size, complete);
681 static size_t rx_size;
683 static void usb_ep_read_complete(int ep)
685 if (UNLIKELY(ep >= ENP_MAX_NUMB))
690 ASSERT(!(ep & 0x01));
693 rx_size = ep_cnfg[ep].size;
696 ssize_t usb_ep_read(int ep, void *buffer, ssize_t size)
700 size = MIN(size, USB_RX_MAX_SIZE);
705 __usb_ep_read(USB_EpLogToPhysAdd(ep), buffer, size,
706 usb_ep_read_complete);
714 static size_t tx_size;
716 static void usb_ep_write_complete(int ep)
718 if (UNLIKELY(ep >= ENP_MAX_NUMB))
726 tx_size = ep_cnfg[ep].size;
729 ssize_t usb_ep_write(int ep, const void *buffer, ssize_t size)
733 size = MIN(size, USB_TX_MAX_SIZE);
738 __usb_ep_write(USB_EpLogToPhysAdd(ep), buffer, size,
739 usb_ep_write_complete);
746 static void usb_ep_low_level_config(int ep, uint16_t offset, uint16_t size)
748 stm32_usb_ep_t *epc = &ep_cnfg[ep];
754 EpCtrlSet_STAT_TX(epc->hw, EP_DISABLED);
755 /* Clear Tx toggle */
756 EpCtrlSet_DTOG_TX(epc->hw, 0);
757 /* Clear Correct Transfer for transmission flag */
758 EpCtrlClr_CTR_TX(epc->hw);
760 /* Update EP description table */
761 WriteEpDTB_AddrTx(ep >> 1, offset);
762 WriteEpDTB_CountTx(ep >> 1, 0);
767 uint16_t rx_count = 0;
770 EpCtrlSet_STAT_RX(epc->hw, EP_DISABLED);
771 /* Clear Rx toggle */
772 EpCtrlSet_DTOG_RX(epc->hw, 0);
773 /* Clear Correct Transfer for reception flag */
774 EpCtrlClr_CTR_RX(epc->hw);
775 /* Descriptor block size field */
776 rx_count |= (size > 62) << 15;
777 /* Descriptor number of blocks field */
778 rx_count |= (((size > 62) ? (size >> 5) - 1 : size >> 1) &
780 /* Update EP description table */
781 WriteEpDTB_AddrRx(ep >> 1, offset);
782 WriteEpDTB_CountRx(ep >> 1, rx_count);
786 /* Enable/Disable an endpoint */
787 static int usb_ep_configure(const usb_endpoint_descriptor_t *epd, bool enable)
790 stm32_usb_ep_t *ep_hw;
793 uint32_t MaxPacketSizeTmp;
795 EP = USB_EpLogToPhysAdd(epd->bEndpointAddress);
796 ep_hw = &ep_cnfg[EP];
801 * Allocate packet memory for EP buffer/s calculate actual size
802 * only for the OUT EPs.
804 MaxPacketSizeTmp = epd->wMaxPacketSize;
805 if (!USB_AllocateBuffer(&Offset, &MaxPacketSizeTmp, EP))
806 return -USB_MEMORY_FULL;
809 ep_hw->status = NOT_READY;
813 /* Set endpoint type */
814 ep_hw->type = usb_endpoint_type(epd);
815 /* Init EP max packet size */
816 ep_hw->max_size = epd->wMaxPacketSize;
819 ep_hw->avail_data = 1;
821 ep_hw->avail_data = 0;
822 hw = (reg32_t *)&usb->EP0R;
826 EpCtrlSet_EA(hw, EP >> 1);
829 /* Low-level endpoint configuration */
830 usb_ep_low_level_config(EP, Offset, MaxPacketSizeTmp);
832 /* Set EP Kind & enable */
835 case USB_ENDPOINT_XFER_CONTROL:
836 LOG_INFO("EP%d: CONTROL IN\n", EP >> 1);
837 EpCtrlSet_EP_TYPE(hw, EP_CTRL);
838 EpCtrlSet_EP_KIND(hw, 0);
840 case USB_ENDPOINT_XFER_INT:
841 LOG_INFO("EP%d: INTERRUPT IN\n", EP >> 1);
842 EpCtrlSet_EP_TYPE(hw, EP_INTERRUPT);
843 EpCtrlSet_EP_KIND(hw, 0);
845 case USB_ENDPOINT_XFER_BULK:
846 LOG_INFO("EP%d: BULK IN\n", EP >> 1);
847 EpCtrlSet_EP_TYPE(hw, EP_BULK);
848 EpCtrlSet_EP_KIND(hw, 0);
850 case USB_ENDPOINT_XFER_ISOC:
851 LOG_ERR("EP%d: ISOCHRONOUS IN: not supported\n", EP >> 1);
852 /* Fallback to default */
855 return -USB_NODEV_ERROR;
860 EpCtrlSet_STAT_TX(hw, EP_NAK);
861 /* Clear Correct Transfer for transmission flag */
862 EpCtrlClr_CTR_TX(hw);
867 EpCtrlSet_STAT_RX(hw, EP_VALID);
870 else if (ep_cnfg[EP].hw)
872 hw = (reg32_t *)&usb->EP0R;
879 EpCtrlSet_STAT_TX(hw, EP_DISABLED);
880 /* Clear Correct Transfer for reception flag */
881 EpCtrlClr_CTR_TX(hw);
887 EpCtrlSet_STAT_RX(hw, EP_DISABLED);
888 /* Clear Correct Transfer for reception flag */
889 EpCtrlClr_CTR_RX(hw);
892 USB_ReleaseBuffer(EP);
893 ep_cnfg[EP].hw = NULL;
898 /* Get EP stall/unstall */
899 static int USB_GetStallEP(int EP, bool *pStall)
901 if (ep_cnfg[EP].hw == NULL)
902 return -USB_NODEV_ERROR;
904 *pStall = (EP & 0x01) ?
905 (EpCtrlGet_STAT_TX(ep_cnfg[EP].hw) == EP_STALL): /* IN EP */
906 (EpCtrlGet_STAT_RX(ep_cnfg[EP].hw) == EP_STALL); /* OUT EP */
911 /* Set EP stall/unstall */
912 static int USB_SetStallEP(int EP, bool Stall)
914 if (ep_cnfg[EP].hw == NULL)
915 return -USB_NODEV_ERROR;
919 ep_cnfg[EP].status = STALLED;
923 EpCtrlSet_STAT_TX(ep_cnfg[EP].hw, EP_STALL);
924 ep_cnfg[EP].avail_data = 1;
929 EpCtrlSet_STAT_RX(ep_cnfg[EP].hw, EP_STALL);
930 ep_cnfg[EP].avail_data = 0;
935 ep_cnfg[EP].status = NOT_READY;
939 ep_cnfg[EP].avail_data = 1;
940 /* reset Data Toggle bit */
941 EpCtrlSet_DTOG_TX(ep_cnfg[EP].hw, 0);
942 EpCtrlSet_STAT_TX(ep_cnfg[EP].hw, EP_NAK);
947 ep_cnfg[EP].avail_data = 0;
948 /* reset Data Toggle bit */
949 EpCtrlSet_DTOG_RX(ep_cnfg[EP].hw, 0);
950 EpCtrlSet_STAT_RX(ep_cnfg[EP].hw, EP_VALID);
956 /* Stall both directions of the control EP */
957 static void USB_StallCtrlEP(void)
959 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
960 ep_cnfg[CTRL_ENP_IN].status = STALLED;
961 ep_cnfg[CTRL_ENP_OUT].avail_data = 0;
962 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
964 USB_SetStallEP(CTRL_ENP_IN, true);
965 USB_SetStallEP(CTRL_ENP_OUT, true);
969 * Find the position of an interface descriptor inside the configuration
972 static int usb_find_interface(uint32_t num, uint32_t alt)
974 usb_interface_descriptor_t *id;
979 /* TODO: support more than one configuration per device */
980 id = (usb_interface_descriptor_t *)usb_dev->config[i];
983 if (id->bDescriptorType != USB_DT_INTERFACE)
985 if ((id->bInterfaceNumber == num) &&
986 (id->bAlternateSetting == alt))
989 return -USB_NODEV_ERROR;
993 * Configure/deconfigure EPs of a certain interface.
996 usb_configure_ep_interface(unsigned int num, unsigned int alt, bool enable)
998 usb_endpoint_descriptor_t *epd;
1002 * Find the position of the interface descriptor (inside the
1003 * configuration descriptor).
1005 start = usb_find_interface(num, alt);
1008 LOG_ERR("%s: interface (%u,%u) not found\n",
1009 __func__, num, alt);
1013 * Cycle over endpoint descriptors.
1015 * NOTE: the first endpoint descriptor is placed next to the interface
1016 * descriptor, so we need to add +1 to the position of the interface
1017 * descriptor to find it.
1019 for (i = start + 1; ; i++)
1021 epd = (usb_endpoint_descriptor_t *)usb_dev->config[i];
1022 if ((epd == NULL) || (epd->bDescriptorType != USB_DT_ENDPOINT))
1024 if (UNLIKELY(usb_ep_configure(epd, enable) < 0))
1026 LOG_ERR("%s: out of memory, can't initialize EP\n",
1033 /* Set device state */
1034 static void usb_set_device_state(int state)
1038 LOG_INFO("%s: new state %d\n", __func__, state);
1040 if (udc.state == USB_STATE_CONFIGURED)
1042 /* Deconfigure device */
1043 for (i = 0; i < udc.interfaces; ++i)
1044 usb_configure_ep_interface(i,
1049 case USB_STATE_ATTACHED:
1050 case USB_STATE_POWERED:
1051 case USB_STATE_DEFAULT:
1053 usb_dev->configured = false;
1054 udc.address = udc.cfg_id = 0;
1056 case USB_STATE_ADDRESS:
1059 case USB_STATE_CONFIGURED:
1060 /* Configure device */
1061 for (i = 0; i < udc.interfaces; ++i)
1062 usb_configure_ep_interface(i,
1066 /* Unknown state: disconnected or connection in progress */
1067 usb_dev->configured = false;
1075 /* Setup packet: set address status phase end handler */
1076 static void USB_AddStatusEndHandler(UNUSED_ARG(int, EP))
1080 w_value = usb_le16_to_cpu(setup_packet.wValue);
1081 udc.address = w_value & 0xff;
1082 usb_set_address(udc.address);
1085 usb_set_device_state(USB_STATE_ADDRESS);
1087 usb_set_device_state(USB_STATE_DEFAULT);
1089 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1090 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1093 /* Prepare status phase */
1094 static void USB_StatusPhase(bool in)
1097 __usb_ep_write(CTRL_ENP_IN, NULL, 0, NULL);
1100 /* Setup packet: status phase end handler */
1101 static void USB_StatusEndHandler(UNUSED_ARG(int, EP))
1103 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1104 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1107 /* Address status handler */
1108 static void USB_StatusHandler(UNUSED_ARG(int, EP))
1110 if (setup_packet.mRequestType & USB_DIR_IN)
1112 USB_StatusPhase(false);
1113 ep_cnfg[CTRL_ENP_OUT].complete = USB_StatusEndHandler;
1117 USB_StatusPhase(true);
1118 ep_cnfg[CTRL_ENP_IN].complete =
1119 (setup_packet.bRequest == USB_REQ_SET_ADDRESS) ?
1120 USB_AddStatusEndHandler :
1121 USB_StatusEndHandler;
1125 /* Global variable to handle the following non-blocking I/O operations */
1126 static uint32_t InData;
1128 /* Get device status */
1129 static int UsbDevStatus(uint16_t index)
1132 return -USB_NODEV_ERROR;
1134 InData = ((uint32_t)udc.feature) & 0xff;
1135 __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 2, USB_StatusHandler);
1140 /* Get interface status */
1141 static int UsbInterfaceStatus(UNUSED_ARG(uint16_t, index))
1144 __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 2, USB_StatusHandler);
1149 /* Get endpoint status */
1150 static int UsbEpStatus(uint16_t index)
1152 if ((index & 0x7F) > 16)
1153 return -USB_NODEV_ERROR;
1156 USB_GetStallEP(USB_EpLogToPhysAdd(index), (bool *)&InData);
1157 __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 2, USB_StatusHandler);
1162 /* USB setup packet: GET_STATUS request handler */
1163 static void USB_GetStatusHandler(void)
1165 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1166 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1167 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1169 /* GET_STATUS sanity checks */
1170 if (udc.state < USB_STATE_ADDRESS)
1172 LOG_WARN("%s: bad GET_STATUS request (State=%02x)\n",
1173 __func__, udc.state);
1174 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1179 LOG_WARN("%s: bad GET_STATUS request (wLength.Word=%02x)\n",
1180 __func__, w_length);
1181 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1184 if (!(setup_packet.mRequestType & USB_DIR_IN))
1186 LOG_WARN("%s: bad GET_STATUS request (mRequestType=%02x)\n",
1187 __func__, setup_packet.mRequestType);
1188 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1193 LOG_WARN("%s: bad GET_STATUS request (wValue=%02x)\n",
1195 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1199 /* Process GET_STATUS request */
1200 switch (setup_packet.mRequestType & USB_RECIP_MASK)
1202 case USB_RECIP_DEVICE:
1203 if (UsbDevStatus(w_index) < 0)
1205 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientDevice\n",
1207 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1210 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientDevice)\n",
1211 __func__, setup_packet.mRequestType);
1213 case USB_RECIP_INTERFACE:
1214 if (UsbInterfaceStatus(w_index) < 0)
1216 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientInterface\n",
1218 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1221 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientInterface)\n",
1222 __func__, setup_packet.mRequestType);
1224 case USB_RECIP_ENDPOINT:
1225 if (UsbEpStatus(w_index) < 0)
1227 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1229 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1232 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientEndpoint)\n",
1233 __func__, setup_packet.mRequestType);
1236 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1238 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1244 * Return the lower value from Host expected size and size and set a flag
1245 * STM32_USB_EP_ZERO_POSSIBLE when size is lower that host expected size.
1247 static size_t usb_size(size_t size, size_t host_size)
1249 if (size < host_size)
1251 ep_cnfg[CTRL_ENP_IN].flags |= STM32_USB_EP_ZERO_POSSIBLE;
1257 static int usb_get_device_descriptor(int id)
1260 return -USB_NODEV_ERROR;
1262 usb_dev->device->bMaxPacketSize0 = USB_EP0_MAX_SIZE;
1263 __usb_ep_write(CTRL_ENP_IN, (const uint8_t *)usb_dev->device,
1264 usb_size(usb_dev->device->bLength,
1265 setup_packet.wLength),
1270 #define USB_BUFSIZE (128)
1271 static uint8_t usb_cfg_buffer[USB_BUFSIZE];
1273 static int usb_get_configuration_descriptor(int id)
1275 const usb_config_descriptor_t **config =
1276 (const usb_config_descriptor_t **)usb_dev->config;
1277 uint8_t *p = usb_cfg_buffer;
1280 /* TODO: support more than one configuration per device */
1281 if (UNLIKELY(id > 0))
1282 return -USB_NODEV_ERROR;
1284 for (i = 0; config[i]; i++)
1286 memcpy(p, config[i], config[i]->bLength);
1287 p += config[i]->bLength;
1289 if (UNLIKELY((p - usb_cfg_buffer) > USB_BUFSIZE))
1292 return -USB_BUF_OVERFLOW;
1295 ((usb_config_descriptor_t *)usb_cfg_buffer)->wTotalLength =
1296 usb_cpu_to_le16(p - usb_cfg_buffer);
1297 __usb_ep_write(CTRL_ENP_IN,
1299 usb_size(p - usb_cfg_buffer,
1300 setup_packet.wLength),
1305 static int usb_get_string_descriptor(unsigned int id)
1307 usb_string_descriptor_t *lang_str;
1308 unsigned int lang_id, str_id;
1309 uint16_t w_index_lo = usb_le16_to_cpu(setup_packet.wIndex) & 0x00ff;
1310 uint16_t w_index_hi = (usb_le16_to_cpu(setup_packet.wIndex) & 0xff00) >> 8;
1312 ASSERT(usb_dev->strings != NULL);
1313 ASSERT(usb_dev->strings[0] != NULL);
1315 lang_str = usb_dev->strings[0];
1318 /* Find Language index */
1319 for (lang_id = 0; ; lang_id++)
1321 usb_string_descriptor_t *str = usb_dev->strings[lang_id];
1323 if (UNLIKELY(str == NULL))
1324 return -USB_NODEV_ERROR;
1325 if ((str->data[0] == w_index_lo) &&
1326 (str->data[1] == w_index_hi))
1329 /* Check buffer overflow to find string index */
1330 for (str_id = 0; str_id < id; str_id++)
1332 lang_str = usb_dev->strings[lang_id + 1 + str_id];
1333 if (lang_str == NULL)
1334 return -USB_NODEV_ERROR;
1337 __usb_ep_write(CTRL_ENP_IN,
1339 usb_size(lang_str->bLength, setup_packet.wLength),
1344 static void UsbGetDescriptor(void)
1346 uint16_t w_value_lo = usb_le16_to_cpu(setup_packet.wValue) & 0x00ff;
1347 uint16_t w_value_hi = (usb_le16_to_cpu(setup_packet.wValue) & 0xff00) >> 8;
1349 if (udc.state < USB_STATE_DEFAULT)
1351 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1357 LOG_INFO("%s: GET_DEVICE_DESCRIPTOR: id=%d, state=%d\n",
1361 if (usb_get_device_descriptor(w_value_lo) < 0)
1362 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1365 LOG_INFO("%s: GET_CONFIG_DESCRIPTOR: id=%d, state=%d\n",
1366 __func__, w_value_lo, udc.state);
1367 if (usb_get_configuration_descriptor(w_value_lo) < 0)
1368 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1371 LOG_INFO("%s: GET_STRING_DESCRIPTOR: id=%d, state=%d\n",
1372 __func__, w_value_lo, udc.state);
1373 if (usb_get_string_descriptor(w_value_lo) < 0)
1374 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1377 LOG_WARN("%s: GET_UNKNOWN_DESCRIPTOR: id=%d, state=%d\n",
1378 __func__, w_value_lo, udc.state);
1379 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1384 /* USB setup packet: GET_DESCRIPTOR handler */
1385 static void UBS_GetDescriptorHandler(void)
1387 LOG_INFO("%s: GET_DESCRIPTOR: RECIP = %d\n",
1389 setup_packet.mRequestType & USB_RECIP_MASK);
1390 if ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1394 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1397 /* USB setup packet: SET_ADDRESS handler */
1398 static void USB_SetAddressHandler(void)
1400 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1401 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1402 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1404 LOG_INFO("%s: SET_ADDRESS: %d\n",
1405 __func__, usb_le16_to_cpu(setup_packet.wValue));
1406 if ((udc.state >= USB_STATE_DEFAULT) &&
1407 ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1408 USB_RECIP_DEVICE) &&
1409 (w_index == 0) && (w_length == 0) && (w_value < 128))
1410 USB_StatusHandler(CTRL_ENP_IN);
1412 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1415 /* USB setup packet: GET_CONFIGURATION handler */
1416 static void USB_GetConfigurationHandler(void)
1418 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1419 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1421 LOG_INFO("%s: GET_CONFIGURATION\n", __func__);
1422 if ((udc.state >= USB_STATE_ADDRESS) &&
1423 (w_value == 0) && (w_index == 0) && (w_value == 1))
1425 InData = udc.cfg_id;
1426 __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 1, USB_StatusHandler);
1429 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1432 static const usb_config_descriptor_t *usb_find_configuration(int num)
1434 const usb_config_descriptor_t *cfg;
1439 cfg = (const usb_config_descriptor_t *)usb_dev->config[i];
1442 if (cfg->bDescriptorType != USB_DT_CONFIG)
1444 if (cfg->bConfigurationValue == num)
1450 static int UsbSetConfigurationState(uint32_t Configuration)
1452 const usb_config_descriptor_t *pCnfg;
1457 /* Find configuration descriptor */
1458 pCnfg = usb_find_configuration(Configuration);
1460 return -USB_NODEV_ERROR;
1462 /* Reset current configuration */
1463 usb_set_device_state(USB_STATE_ADDRESS);
1464 usb_dev->configured = false;
1467 /* Set Interface and Alternative Setting */
1468 udc.cfg_id = Configuration;
1469 /* Set self-powered state */
1470 if (pCnfg->bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1471 udc.feature |= STM32_UDC_FEATURE_SELFPOWERED;
1473 /* Configure all existing interfaces to alternative setting 0 */
1474 ASSERT(pCnfg->bNumInterfaces <= USB_MAX_INTERFACE);
1475 udc.interfaces = pCnfg->bNumInterfaces;
1476 for (i = 0; i < udc.interfaces; i++)
1478 usb_set_device_state(USB_STATE_CONFIGURED);
1479 usb_dev->configured = true;
1483 usb_dev->configured = false;
1484 usb_set_device_state(USB_STATE_ADDRESS);
1489 /* USB setup packet: SET_CONFIGURATION handler */
1490 static void USB_SetConfigurationHandler(void)
1492 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1493 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1494 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1496 LOG_INFO("%s: SET_CONFIGURATION: %d\n",
1498 if ((udc.state >= USB_STATE_ADDRESS) &&
1499 (w_index == 0) && (w_length == 0) &&
1500 (UsbSetConfigurationState(w_value & 0xff) == 0))
1501 USB_StatusHandler(CTRL_ENP_OUT);
1503 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1506 /* USB setup packet: standard request handler */
1507 static void USB_StandardRequestHandler(void)
1509 switch (setup_packet.bRequest)
1511 case USB_REQ_GET_STATUS:
1512 USB_GetStatusHandler();
1514 case USB_REQ_CLEAR_FEATURE:
1515 LOG_INFO("%s: bRequest=%d (CLEAR_FEATURE)\n",
1516 __func__, setup_packet.bRequest);
1518 case USB_REQ_SET_FEATURE:
1519 LOG_INFO("%s: bRequest=%d (SET_FEATURE)\n",
1520 __func__, setup_packet.bRequest);
1522 case USB_REQ_SET_ADDRESS:
1523 USB_SetAddressHandler();
1525 case USB_REQ_GET_DESCRIPTOR:
1526 UBS_GetDescriptorHandler();
1528 case USB_REQ_SET_DESCRIPTOR:
1529 LOG_INFO("%s: bRequest=%d (SET_DESCRIPTOR)\n",
1530 __func__, setup_packet.bRequest);
1532 case USB_REQ_GET_CONFIGURATION:
1533 USB_GetConfigurationHandler();
1535 case USB_REQ_SET_CONFIGURATION:
1536 USB_SetConfigurationHandler();
1538 case USB_REQ_GET_INTERFACE:
1539 LOG_INFO("%s: bRequest=%d (GET_INTERFACE)\n",
1540 __func__, setup_packet.bRequest);
1542 case USB_REQ_SET_INTERFACE:
1543 LOG_INFO("%s: bRequest=%d (SET_INTERFACE)\n",
1544 __func__, setup_packet.bRequest);
1546 case USB_REQ_SYNCH_FRAME:
1547 LOG_INFO("%s: bRequest=%d (SYNCH_FRAME)\n",
1548 __func__, setup_packet.bRequest);
1551 LOG_WARN("%s: bRequest=%d (Unknown)\n",
1552 __func__, setup_packet.bRequest);
1553 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1558 /* USB setup packet handler */
1559 static void USB_SetupHandler(void)
1561 switch (setup_packet.mRequestType & USB_TYPE_MASK)
1564 case USB_TYPE_STANDARD:
1565 LOG_INFO("%s: bmRequestType=%02x (Standard)\n",
1566 __func__, setup_packet.mRequestType);
1567 USB_StandardRequestHandler();
1570 case USB_TYPE_CLASS:
1571 LOG_INFO("%s: bmRequestType=%02x (Class)\n",
1572 __func__, setup_packet.mRequestType);
1575 case USB_TYPE_VENDOR:
1576 LOG_INFO("%s: bmRequestType=%02x (Vendor)\n",
1577 __func__, setup_packet.mRequestType);
1579 case USB_TYPE_RESERVED:
1580 LOG_INFO("%s: bmRequestType=%02x (Reserved)\n",
1581 __func__, setup_packet.mRequestType);
1585 LOG_WARN("%s: bmRequestType=%02x (Unknown)\n",
1586 __func__, setup_packet.mRequestType);
1587 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1592 static void usb_hw_reset(void)
1597 /* Initialize endpoint descriptors */
1598 for (i = 0; i < countof(ep_cnfg); i++)
1599 ep_cnfg[i].hw = NULL;
1601 /* Initialize USB memory */
1602 for (i = 0; i < countof(PacketMemBuff); i++)
1603 PacketMemBuff[i].Size = 0;
1604 usb->BTABLE = USB_BDT_OFFSET;
1605 pPacketMemUse = NULL;
1607 /* Endpoint initialization */
1608 ret = usb_ep_configure(&USB_CtrlEpDescr0, true);
1609 if (UNLIKELY(ret < 0))
1611 LOG_WARN("%s: out of memory, cannot initialize EP0\n",
1615 ret = usb_ep_configure(&USB_CtrlEpDescr1, true);
1616 if (UNLIKELY(ret < 0))
1618 LOG_WARN("%s: out of memory, cannot initialize EP1\n",
1623 /* Set default address */
1626 /* Enable all the device interrupts */
1628 usb->CNTR = bmCTRM | bmRESETM | bmSOFM | bmERRM | bmPMAOVRM |
1631 /* XXX: disable frame interrupts for now (too much noise!) */
1632 usb->CNTR = bmCTRM | bmRESETM | bmERRM | bmPMAOVRM | bmSUSPM | bmWKUPM;
1636 /* Handle a correct transfer under ISR */
1637 static void usb_isr_correct_transfer(stm32_usb_irq_status_t interrupt)
1640 reg32_t *pReg = (reg32_t *)&usb->EP0R;
1642 /* Find corresponding EP */
1643 pReg += interrupt.EP_ID;
1644 EP = (int)(((*pReg & 0x0f) << 1) + (interrupt.DIR ? 0 : 1));
1645 ep_cnfg[EP].avail_data = 1;
1647 ASSERT(ep_cnfg[EP].hw);
1650 EpCtrlClr_CTR_TX(ep_cnfg[EP].hw);
1652 EpCtrlClr_CTR_RX(ep_cnfg[EP].hw);
1653 if (EP == CTRL_ENP_OUT)
1655 /* Determinate type of packet (only for control EP) */
1656 bool SetupPacket = EpCtrlGet_SETUP(ep_cnfg[CTRL_ENP_OUT].hw);
1660 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
1661 /* init IO to receive Setup packet */
1662 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1663 __usb_ep_read(CTRL_ENP_OUT, &setup_packet,
1664 sizeof(setup_packet), NULL);
1666 /* reset EP IO ctrl */
1667 if (setup_packet.mRequestType & USB_DIR_IN)
1668 USB_StatusHandler(CTRL_ENP_OUT);
1670 if (ep_cnfg[CTRL_ENP_OUT].status == STALLED)
1675 if (ep_cnfg[CTRL_ENP_OUT].complete &&
1676 setup_packet.mRequestType & USB_DIR_IN)
1677 ep_cnfg[CTRL_ENP_OUT].complete(CTRL_ENP_OUT);
1682 else if (EP == CTRL_ENP_IN)
1684 if (ep_cnfg[CTRL_ENP_IN].complete &&
1685 !(setup_packet.mRequestType & USB_DIR_IN))
1686 ep_cnfg[CTRL_ENP_IN].complete(CTRL_ENP_IN);
1695 /* USB: interrupt service routine */
1696 static void usb_isr(void)
1698 stm32_usb_irq_status_t interrupt;
1700 /* Get masked interrupt flags */
1701 interrupt.status = usb->ISTR;
1702 interrupt.status &= usb->CNTR | 0x1f;
1704 if (interrupt.PMAOVR)
1706 LOG_WARN("%s: DMA overrun / underrun\n", __func__);
1707 usb->ISTR = ~bmPMAOVRM;
1711 LOG_WARN("%s: engine error\n", __func__);
1712 usb->ISTR = ~bmERRM;
1714 if (interrupt.RESET)
1716 LOG_INFO("%s: device reset\n", __func__);
1717 usb->ISTR = ~bmRESETM;
1719 usb_set_device_state(USB_STATE_DEFAULT);
1723 uint16_t frame_nr = usb->FNR & 0x0fff;
1725 LOG_INFO("%s: frame %#x\n", __func__, frame_nr);
1726 usb->ISTR = ~bmSOFM;
1730 LOG_INFO("%s: wake-up\n", __func__);
1731 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1736 LOG_INFO("%s: suspend\n", __func__);
1738 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1742 LOG_INFO("%s: expected frame\n", __func__);
1743 usb->ISTR = ~bmESOFM;
1747 usb_isr_correct_transfer(interrupt);
1751 /* USB: hardware initialization */
1752 static void usb_hw_init(void)
1754 /* Enable clocking on the required GPIO pins */
1755 RCC->APB2ENR |= RCC_APB2_GPIOA | RCC_APB2_GPIOC;
1757 /* Make sure that the CAN controller is disabled and held in reset */
1758 RCC->APB1ENR &= ~RCC_APB1_CAN;
1760 /* Configure USB_DM and USB_DP to work as USB lines */
1761 stm32_gpioPinConfig((struct stm32_gpio *)GPIOA_BASE,
1762 USB_DM_PIN | USB_DP_PIN,
1763 GPIO_MODE_AF_PP, GPIO_SPEED_50MHZ);
1764 /* Configure USB_DISC to work as USB disconnect */
1765 stm32_gpioPinConfig((struct stm32_gpio *)GPIOC_BASE,
1767 GPIO_MODE_OUT_PP, GPIO_SPEED_50MHZ);
1768 stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE,
1771 /* Ensure the USB clock is disabled before setting the prescaler */
1772 RCC->APB1ENR &= ~RCC_APB1_USB;
1774 /* Configure USB clock (48MHz) */
1775 *CFGR_USBPRE_BB &= ~RCC_USBCLK_PLLCLK_1DIV5;
1777 /* Activate USB clock */
1778 RCC->APB1ENR |= RCC_APB1_USB;
1780 /* Force USB reset and disable USB interrupts */
1784 /* Issue a USB reset */
1787 /* Clear spurious pending interrupt */
1790 /* Register interrupt handler */
1791 sysirq_setHandler(USB_LP_CAN_RX0_IRQHANDLER, usb_isr);
1793 /* Software connection enable */
1797 /* Initialize the USB controller */
1798 static void usb_init(void)
1800 udc.state = USB_STATE_NOTATTACHED;
1806 /* Register an upper layer USB device into the driver */
1807 int usb_device_register(struct usb_device *dev)
1814 while (!usb_dev->configured)