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 UsbEndpointDesc 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 UsbEndpointDesc 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 UsbCtrlRequest 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 UsbConfigDesc *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 UsbDevice *usb_dev;
139 /* USB packet memory management: list of allocated chunks */
140 static pack_mem_slot_t *mem_use;
142 /* USB packet memory management: memory buffer metadata */
143 #define EP_MAX_SLOTS 16
144 static pack_mem_slot_t memory_buffer[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(memory_buffer); i++)
152 if (memory_buffer[i].Size == 0)
153 return &memory_buffer[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_alloc_buffer(uint16_t *pOffset, uint32_t *size,
167 pack_mem_slot_t *mem = mem_use,
168 *memNext, *mem_useNew;
169 uint32_t max_size = *size;
172 * Packet size alignment:
173 * - fine-granularity allocation: size alignment by 2;
174 * - coarse-granularity allocation: size alignment by 32.
177 max_size = ALIGN_UP(max_size, 2);
179 max_size = ALIGN_UP(max_size, 32);
181 * Finding free memory chunks from the allocated blocks of the USB
187 /* Offset alignment by 4 */
188 *pOffset = ALIGN_UP(mem->Start + mem->Size, 4);
190 if ((mem->next == NULL) ||
192 *pOffset + max_size))
196 /* Check for out-of-memory condition */
197 if ((*pOffset + max_size) >= USB_BDT_OFFSET)
200 * Allocate a new memory block, next to the last allocated block.
202 mem_useNew = usb_malloc();
203 if (mem_useNew == NULL)
205 /* Insert the block to the list of allocated blocks */
208 mem_use = mem_useNew;
209 mem_use->next = NULL;
213 mem_useNew->next = mem->next;
214 mem->next = mem_useNew;
216 /* Update block's metadata */
217 mem_useNew->ep_addr = EndPoint;
218 mem_useNew->Start = *pOffset;
219 mem_useNew->Size = max_size;
226 /* Release a chunk of the packet memory (inside a block) */
227 static void usb_free_buffer(int EndPoint)
229 pack_mem_slot_t *mem, *memPrev = NULL;
234 if (mem->ep_addr == EndPoint)
236 if (UNLIKELY(memPrev == NULL))
238 /* Free the first element of the list */
239 mem_use = mem_use->next;
244 memPrev->next = mem->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_ep_logical_to_hw(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];
449 if (UNLIKELY(epd->hw == NULL))
451 LOG_ERR("%s: invalid endpoint (EP%d-%s)\n",
454 (EP & 0x01) ? "IN" : "OUT");
458 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
464 Count = epd->size - epd->offset;
465 while (epd->avail_data)
467 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
471 epd->status = BEGIN_SERVICED;
473 if ((epd->flags & STM32_USB_EP_ZERO_PACKET) &&
474 (Count == epd->max_size))
475 epd->flags |= STM32_USB_EP_ZERO_PACKET |
476 STM32_USB_EP_ZERO_POSSIBLE;
478 CountHold = Count = MIN(Count, epd->max_size);
480 epd->flags |= STM32_USB_EP_ZERO_PACKET;
481 Offset = epd->offset;
482 epd->offset += Count;
483 CurrentBuffer = true;
486 case USB_ENDPOINT_XFER_CONTROL:
487 case USB_ENDPOINT_XFER_INT:
488 pDst = (uint32_t *)addr2usbmem(ReadEpDTB_AddrTx(EP >> 1));
490 case USB_ENDPOINT_XFER_BULK:
491 pDst = (uint32_t *)addr2usbmem(ReadEpDTB_AddrTx(EP >> 1));
493 case USB_ENDPOINT_XFER_ISOC:
494 LOG_ERR("%s: isochronous transfer not supported\n",
496 /* Fallback to default */
502 /* Write data to packet memory buffer */
505 Data = *(epd->write_buffer + Offset++);
508 Data |= (uint32_t)(*(epd->write_buffer + Offset++)) << 8;
515 WriteEpDTB_CountTx(EP >> 1, CountHold);
517 WriteEpDTB_CountRx(EP >> 1, CountHold);
519 EpCtrlSet_STAT_TX(epd->hw, EP_VALID);
521 --ep_cnfg[EP].avail_data;
522 Count = epd->size - epd->offset;
524 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
526 epd->status = COMPLETE;
527 /* call callback function */
535 while (epd->avail_data)
537 /* Get data size and buffer pointer */
540 case USB_ENDPOINT_XFER_CONTROL:
541 case USB_ENDPOINT_XFER_INT:
542 /* Get received bytes number */
543 Count = ReadEpDTB_CountRx(EP >> 1) & 0x3FF;
544 /* Get address of the USB packet buffer for corresponding EP */
545 pSrc = (uint32_t *)addr2usbmem(ReadEpDTB_AddrRx(EP >> 1));
547 case USB_ENDPOINT_XFER_BULK:
548 /* Get received bytes number */
549 Count = ReadEpDTB_CountRx(EP >> 1) & 0x3FF;
550 /* Get address of the USB packet buffer for corresponding EP */
551 pSrc = (uint32_t *)addr2usbmem(ReadEpDTB_AddrRx(EP >> 1));
553 case USB_ENDPOINT_XFER_ISOC:
554 LOG_ERR("%s: isochronous transfer not supported\n",
556 /* Fallback to default */
562 if (Count > (epd->size - epd->offset))
564 epd->status = BUFFER_OVERRUN;
565 epd->size = ep_cnfg[EP].offset;
568 else if (Count < ep_cnfg[EP].max_size)
570 epd->status = BUFFER_UNDERRUN;
571 epd->size = ep_cnfg[EP].offset + Count;
574 epd->status = BEGIN_SERVICED;
576 Offset = epd->offset;
577 epd->offset += Count;
579 /* Read data from packet memory buffer */
583 *(epd->read_buffer + Offset++) = Data;
587 *(epd->read_buffer + Offset++) = Data;
592 EpCtrlSet_STAT_RX(epd->hw, EP_VALID);
594 --ep_cnfg[EP].avail_data;
596 if (*epd->hw & (1UL << 11))
598 ep_cnfg[EP].status = SETUP_OVERWRITE;
601 if (!(Count = (epd->size - epd->offset)))
603 epd->status = COMPLETE;
607 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
609 /* call callback function */
617 * Return the lower value from Host expected size and size and set a flag
618 * STM32_USB_EP_ZERO_POSSIBLE when size is lower that host expected size.
620 static size_t usb_size(size_t size, size_t host_size)
622 if (size < host_size)
624 ep_cnfg[CTRL_ENP_IN].flags |= STM32_USB_EP_ZERO_POSSIBLE;
630 /* Configure an EP descriptor before performing a I/O operation */
631 #define USB_EP_IO(__EP, __op, __buf, __size, __complete) \
634 stm32_usb_io_status_t ret; \
636 /* Fill EP descriptor */ \
637 IRQ_SAVE_DISABLE(flags); \
640 ep_cnfg[__EP].status = NOT_READY; \
641 ep_cnfg[__EP].complete = NULL; \
645 if (ep_cnfg[__EP].status == BEGIN_SERVICED) \
651 * NOTE: the write_buffer and read_buffer are actually the \
652 * same location in memory (it's a union). \
654 * We have to do this trick to silent a build warning by \
655 * casting the I/O buffer to (void *) or (const void *). \
657 ep_cnfg[__EP].__op ## _buffer = __buf; \
658 ep_cnfg[__EP].offset = 0; \
659 ep_cnfg[__EP].size = __size; \
660 ep_cnfg[__EP].complete = __complete; \
662 ep_cnfg[__EP].flags = STM32_USB_EP_ZERO_PACKET; \
664 ep_cnfg[__EP].flags = 0; \
665 ep_cnfg[__EP].status = NO_SERVICED; \
667 /* Perform the I/O operation */ \
670 ret = ep_cnfg[__EP].status; \
672 IRQ_RESTORE(flags); \
676 /* Configure and endponint and perform a read operation */
677 static stm32_usb_io_status_t
678 __usb_ep_read(int ep, void *buffer, ssize_t size, void (*complete)(int))
680 if (UNLIKELY(ep >= ENP_MAX_NUMB))
685 ASSERT(!(ep & 0x01));
686 return USB_EP_IO(ep, read, buffer, size, complete);
689 /* Configure and endponint and perform a write operation */
690 static stm32_usb_io_status_t
691 __usb_ep_write(int ep, const void *buffer, ssize_t size, void (*complete)(int))
693 if (UNLIKELY(ep >= ENP_MAX_NUMB))
699 return USB_EP_IO(ep, write, buffer, size, complete);
702 static void usb_ep_low_level_config(int ep, uint16_t offset, uint16_t size)
704 stm32_usb_ep_t *epc = &ep_cnfg[ep];
710 EpCtrlSet_STAT_TX(epc->hw, EP_DISABLED);
711 /* Clear Tx toggle */
712 EpCtrlSet_DTOG_TX(epc->hw, 0);
713 /* Clear Correct Transfer for transmission flag */
714 EpCtrlClr_CTR_TX(epc->hw);
716 /* Update EP description table */
717 WriteEpDTB_AddrTx(ep >> 1, offset);
718 WriteEpDTB_CountTx(ep >> 1, 0);
723 uint16_t rx_count = 0;
726 EpCtrlSet_STAT_RX(epc->hw, EP_DISABLED);
727 /* Clear Rx toggle */
728 EpCtrlSet_DTOG_RX(epc->hw, 0);
729 /* Clear Correct Transfer for reception flag */
730 EpCtrlClr_CTR_RX(epc->hw);
731 /* Descriptor block size field */
732 rx_count |= (size > 62) << 15;
733 /* Descriptor number of blocks field */
734 rx_count |= (((size > 62) ? (size >> 5) - 1 : size >> 1) &
736 /* Update EP description table */
737 WriteEpDTB_AddrRx(ep >> 1, offset);
738 WriteEpDTB_CountRx(ep >> 1, rx_count);
742 /* Enable/Disable an endpoint */
743 static int usb_ep_configure(const UsbEndpointDesc *epd, bool enable)
746 stm32_usb_ep_t *ep_hw;
751 EP = usb_ep_logical_to_hw(epd->bEndpointAddress);
752 ep_hw = &ep_cnfg[EP];
757 * Allocate packet memory for EP buffer/s calculate actual size
758 * only for the OUT EPs.
760 size = epd->wMaxPacketSize;
761 if (!usb_alloc_buffer(&Offset, &size, EP))
762 return -USB_MEMORY_FULL;
765 ep_hw->status = NOT_READY;
769 /* Set endpoint type */
770 ep_hw->type = usb_endpointType(epd);
771 /* Init EP max packet size */
772 ep_hw->max_size = epd->wMaxPacketSize;
775 ep_hw->avail_data = 1;
777 ep_hw->avail_data = 0;
778 hw = (reg32_t *)&usb->EP0R;
782 EpCtrlSet_EA(hw, EP >> 1);
784 LOG_INFO("%s: EP%d-%s configured\n",
785 __func__, EP >> 1, EP & 1 ? "IN" : "OUT");
787 /* Low-level endpoint configuration */
788 usb_ep_low_level_config(EP, Offset, size);
790 /* Set EP Kind & enable */
793 case USB_ENDPOINT_XFER_CONTROL:
794 LOG_INFO("EP%d: CONTROL IN\n", EP >> 1);
795 EpCtrlSet_EP_TYPE(hw, EP_CTRL);
796 EpCtrlSet_EP_KIND(hw, 0);
798 case USB_ENDPOINT_XFER_INT:
799 LOG_INFO("EP%d: INTERRUPT IN\n", EP >> 1);
800 EpCtrlSet_EP_TYPE(hw, EP_INTERRUPT);
801 EpCtrlSet_EP_KIND(hw, 0);
803 case USB_ENDPOINT_XFER_BULK:
804 LOG_INFO("EP%d: BULK IN\n", EP >> 1);
805 EpCtrlSet_EP_TYPE(hw, EP_BULK);
806 EpCtrlSet_EP_KIND(hw, 0);
808 case USB_ENDPOINT_XFER_ISOC:
809 LOG_ERR("EP%d: ISOCHRONOUS IN: not supported\n", EP >> 1);
810 /* Fallback to default */
813 return -USB_NODEV_ERROR;
818 EpCtrlSet_STAT_TX(hw, EP_NAK);
819 /* Clear Correct Transfer for transmission flag */
820 EpCtrlClr_CTR_TX(hw);
825 EpCtrlSet_STAT_RX(hw, EP_VALID);
828 else if (ep_cnfg[EP].hw)
830 hw = (reg32_t *)&usb->EP0R;
837 EpCtrlSet_STAT_TX(hw, EP_DISABLED);
838 /* Clear Correct Transfer for reception flag */
839 EpCtrlClr_CTR_TX(hw);
845 EpCtrlSet_STAT_RX(hw, EP_DISABLED);
846 /* Clear Correct Transfer for reception flag */
847 EpCtrlClr_CTR_RX(hw);
851 ep_cnfg[EP].hw = NULL;
856 /* Get EP stall/unstall */
857 static int USB_GetStallEP(int EP, bool *pStall)
859 if (ep_cnfg[EP].hw == NULL)
860 return -USB_NODEV_ERROR;
862 *pStall = (EP & 0x01) ?
863 (EpCtrlGet_STAT_TX(ep_cnfg[EP].hw) == EP_STALL): /* IN EP */
864 (EpCtrlGet_STAT_RX(ep_cnfg[EP].hw) == EP_STALL); /* OUT EP */
869 /* Set EP stall/unstall */
870 static int USB_SetStallEP(int EP, bool Stall)
872 if (ep_cnfg[EP].hw == NULL)
873 return -USB_NODEV_ERROR;
877 ep_cnfg[EP].status = STALLED;
881 EpCtrlSet_STAT_TX(ep_cnfg[EP].hw, EP_STALL);
882 ep_cnfg[EP].avail_data = 1;
887 EpCtrlSet_STAT_RX(ep_cnfg[EP].hw, EP_STALL);
888 ep_cnfg[EP].avail_data = 0;
893 ep_cnfg[EP].status = NOT_READY;
897 ep_cnfg[EP].avail_data = 1;
898 /* reset Data Toggle bit */
899 EpCtrlSet_DTOG_TX(ep_cnfg[EP].hw, 0);
900 EpCtrlSet_STAT_TX(ep_cnfg[EP].hw, EP_NAK);
905 ep_cnfg[EP].avail_data = 0;
906 /* reset Data Toggle bit */
907 EpCtrlSet_DTOG_RX(ep_cnfg[EP].hw, 0);
908 EpCtrlSet_STAT_RX(ep_cnfg[EP].hw, EP_VALID);
914 /* Stall both directions of the control EP */
915 static void USB_StallCtrlEP(void)
917 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
918 ep_cnfg[CTRL_ENP_IN].status = STALLED;
919 ep_cnfg[CTRL_ENP_OUT].avail_data = 0;
920 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
922 USB_SetStallEP(CTRL_ENP_IN, true);
923 USB_SetStallEP(CTRL_ENP_OUT, true);
927 * Find the position of an interface descriptor inside the configuration
930 static int usb_find_interface(uint32_t num, uint32_t alt)
932 const UsbInterfaceDesc *id;
937 /* TODO: support more than one configuration per device */
938 id = (const UsbInterfaceDesc *)usb_dev->config[i];
941 if (id->bDescriptorType != USB_DT_INTERFACE)
943 if ((id->bInterfaceNumber == num) &&
944 (id->bAlternateSetting == alt))
947 return -USB_NODEV_ERROR;
951 * Configure/deconfigure EPs of a certain interface.
954 usb_configure_ep_interface(unsigned int num, unsigned int alt, bool enable)
956 const UsbEndpointDesc *epd;
960 * Find the position of the interface descriptor (inside the
961 * configuration descriptor).
963 start = usb_find_interface(num, alt);
966 LOG_ERR("%s: interface (%u,%u) not found\n",
971 * Cycle over endpoint descriptors.
973 * NOTE: the first endpoint descriptor is placed next to the interface
974 * descriptor, so we need to add +1 to the position of the interface
975 * descriptor to find it.
977 for (i = start + 1; ; i++)
979 epd = (const UsbEndpointDesc *)usb_dev->config[i];
980 if ((epd == NULL) || (epd->bDescriptorType == USB_DT_INTERFACE))
982 if (epd->bDescriptorType != USB_DT_ENDPOINT)
984 if (UNLIKELY(usb_ep_configure(epd, enable) < 0))
986 LOG_ERR("%s: out of memory, can't initialize EP\n",
993 /* Set device state */
994 static void usb_set_device_state(int state)
998 LOG_INFO("%s: new state %d\n", __func__, state);
1000 if (udc.state == USB_STATE_CONFIGURED)
1002 /* Deconfigure device */
1003 for (i = 0; i < udc.interfaces; ++i)
1004 usb_configure_ep_interface(i,
1009 case USB_STATE_ATTACHED:
1010 case USB_STATE_POWERED:
1011 case USB_STATE_DEFAULT:
1013 usb_dev->configured = false;
1014 udc.address = udc.cfg_id = 0;
1016 case USB_STATE_ADDRESS:
1019 case USB_STATE_CONFIGURED:
1020 /* Configure device */
1021 for (i = 0; i < udc.interfaces; ++i)
1022 usb_configure_ep_interface(i,
1026 /* Unknown state: disconnected or connection in progress */
1027 usb_dev->configured = false;
1035 /* Setup packet: set address status phase end handler */
1036 static void USB_AddStatusEndHandler(UNUSED_ARG(int, EP))
1040 w_value = usb_le16_to_cpu(setup_packet.wValue);
1041 udc.address = w_value & 0xff;
1042 usb_set_address(udc.address);
1045 usb_set_device_state(USB_STATE_ADDRESS);
1047 usb_set_device_state(USB_STATE_DEFAULT);
1049 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1050 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1053 /* Prepare status phase */
1054 static void USB_StatusPhase(bool in)
1057 __usb_ep_write(CTRL_ENP_IN, NULL, 0, NULL);
1060 /* Setup packet: status phase end handler */
1061 static void USB_StatusEndHandler(UNUSED_ARG(int, EP))
1063 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1064 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1067 /* Address status handler */
1068 static void USB_StatusHandler(UNUSED_ARG(int, EP))
1070 if (setup_packet.mRequestType & USB_DIR_IN)
1072 USB_StatusPhase(false);
1073 ep_cnfg[CTRL_ENP_OUT].complete = USB_StatusEndHandler;
1077 USB_StatusPhase(true);
1078 ep_cnfg[CTRL_ENP_IN].complete =
1079 (setup_packet.bRequest == USB_REQ_SET_ADDRESS) ?
1080 USB_AddStatusEndHandler :
1081 USB_StatusEndHandler;
1085 static bool rx_done;
1086 static size_t rx_size;
1088 static void usb_endpointRead_complete(int ep)
1090 if (UNLIKELY(ep >= ENP_MAX_NUMB))
1095 ASSERT(!(ep & 0x01));
1098 rx_size = ep_cnfg[ep].size;
1101 ssize_t usb_endpointRead(int ep, void *buffer, ssize_t size)
1103 int ep_num = usb_ep_logical_to_hw(ep);
1105 /* Non-blocking read for EP0 */
1106 if (ep_num == CTRL_ENP_OUT)
1108 size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
1110 USB_StatusHandler(ep_num);
1112 __usb_ep_read(ep_num, buffer, size,
1116 if (UNLIKELY(!size))
1118 size = MIN(size, USB_RX_MAX_SIZE);
1123 __usb_ep_read(ep_num, buffer, size, usb_endpointRead_complete);
1130 static bool tx_done;
1131 static size_t tx_size;
1133 static void usb_endpointWrite_complete(int ep)
1135 if (UNLIKELY(ep >= ENP_MAX_NUMB))
1143 tx_size = ep_cnfg[ep].size;
1146 ssize_t usb_endpointWrite(int ep, const void *buffer, ssize_t size)
1148 int ep_num = usb_ep_logical_to_hw(ep);
1150 /* Non-blocking write for EP0 */
1151 if (ep_num == CTRL_ENP_IN)
1153 size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
1155 USB_StatusHandler(ep_num);
1157 __usb_ep_write(ep_num, buffer, size,
1161 if (UNLIKELY(!size))
1163 size = MIN(size, USB_TX_MAX_SIZE);
1167 /* Blocking write */
1168 __usb_ep_write(ep_num, buffer, size, usb_endpointWrite_complete);
1175 /* Global variable to handle the following non-blocking I/O operations */
1176 static uint32_t InData;
1178 /* Get device status */
1179 static int UsbDevStatus(uint16_t index)
1182 return -USB_NODEV_ERROR;
1184 InData = ((uint32_t)udc.feature) & 0xff;
1185 __usb_ep_write(CTRL_ENP_IN,
1186 (uint8_t *)&InData, sizeof(uint16_t),
1191 /* Get interface status */
1192 static int UsbInterfaceStatus(UNUSED_ARG(uint16_t, index))
1195 __usb_ep_write(CTRL_ENP_IN,
1196 (uint8_t *)&InData, sizeof(uint16_t),
1201 /* Get endpoint status */
1202 static int UsbEpStatus(uint16_t index)
1204 if ((index & 0x7F) > 16)
1205 return -USB_NODEV_ERROR;
1208 USB_GetStallEP(usb_ep_logical_to_hw(index), (bool *)&InData);
1209 __usb_ep_write(CTRL_ENP_IN,
1210 (uint8_t *)&InData, sizeof(uint16_t),
1215 /* USB setup packet: GET_STATUS request handler */
1216 static void USB_GetStatusHandler(void)
1218 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1219 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1220 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1222 /* GET_STATUS sanity checks */
1223 if (udc.state < USB_STATE_ADDRESS)
1225 LOG_WARN("%s: bad GET_STATUS request (State=%02x)\n",
1226 __func__, udc.state);
1227 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1232 LOG_WARN("%s: bad GET_STATUS request (wLength.Word=%02x)\n",
1233 __func__, w_length);
1234 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1237 if (!(setup_packet.mRequestType & USB_DIR_IN))
1239 LOG_WARN("%s: bad GET_STATUS request (mRequestType=%02x)\n",
1240 __func__, setup_packet.mRequestType);
1241 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1246 LOG_WARN("%s: bad GET_STATUS request (wValue=%02x)\n",
1248 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1252 /* Process GET_STATUS request */
1253 switch (setup_packet.mRequestType & USB_RECIP_MASK)
1255 case USB_RECIP_DEVICE:
1256 if (UsbDevStatus(w_index) < 0)
1258 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientDevice\n",
1260 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1263 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientDevice)\n",
1264 __func__, setup_packet.mRequestType);
1266 case USB_RECIP_INTERFACE:
1267 if (UsbInterfaceStatus(w_index) < 0)
1269 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientInterface\n",
1271 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1274 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientInterface)\n",
1275 __func__, setup_packet.mRequestType);
1277 case USB_RECIP_ENDPOINT:
1278 if (UsbEpStatus(w_index) < 0)
1280 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1282 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1285 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientEndpoint)\n",
1286 __func__, setup_packet.mRequestType);
1289 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1291 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1296 static int usb_get_device_descriptor(int id)
1299 return -USB_NODEV_ERROR;
1301 usb_dev->device->bMaxPacketSize0 = USB_EP0_MAX_SIZE;
1302 __usb_ep_write(CTRL_ENP_IN, (const uint8_t *)usb_dev->device,
1303 usb_size(usb_dev->device->bLength,
1304 usb_le16_to_cpu(setup_packet.wLength)),
1309 #define USB_BUFSIZE (128)
1310 static uint8_t usb_cfg_buffer[USB_BUFSIZE];
1311 STATIC_ASSERT(USB_BUFSIZE < (1 << (sizeof(uint16_t) * 8)));
1313 static int usb_get_configuration_descriptor(int id)
1315 const UsbConfigDesc **config =
1316 (const UsbConfigDesc **)usb_dev->config;
1317 uint8_t *p = usb_cfg_buffer;
1320 /* TODO: support more than one configuration per device */
1321 if (UNLIKELY(id > 0))
1322 return -USB_NODEV_ERROR;
1324 for (i = 0; config[i]; i++)
1326 memcpy(p, config[i], config[i]->bLength);
1327 p += config[i]->bLength;
1329 if (UNLIKELY((p - usb_cfg_buffer) > USB_BUFSIZE))
1332 return -USB_BUF_OVERFLOW;
1335 ((UsbConfigDesc *)usb_cfg_buffer)->wTotalLength =
1336 usb_cpu_to_le16((uint16_t)(p - usb_cfg_buffer));
1337 __usb_ep_write(CTRL_ENP_IN,
1339 usb_size(p - usb_cfg_buffer,
1340 usb_le16_to_cpu(setup_packet.wLength)),
1345 static int usb_get_string_descriptor(unsigned int id)
1347 const UsbStringDesc *lang_str;
1348 unsigned int lang_id, str_id;
1349 uint16_t w_index_lo = usb_le16_to_cpu(setup_packet.wIndex) & 0x00ff;
1350 uint16_t w_index_hi = (usb_le16_to_cpu(setup_packet.wIndex) &
1353 ASSERT(usb_dev->strings != NULL);
1354 ASSERT(usb_dev->strings[0] != NULL);
1356 lang_str = usb_dev->strings[0];
1359 /* Find Language index */
1360 for (lang_id = 0; ; lang_id++)
1362 const UsbStringDesc *str =
1363 usb_dev->strings[lang_id];
1364 if (UNLIKELY(str == NULL))
1365 return -USB_NODEV_ERROR;
1366 if ((str->data[0] == w_index_lo) &&
1367 (str->data[1] == w_index_hi))
1370 /* Check buffer overflow to find string index */
1371 for (str_id = 0; str_id < id; str_id++)
1373 lang_str = usb_dev->strings[lang_id + 1 + str_id];
1374 if (lang_str == NULL)
1375 return -USB_NODEV_ERROR;
1378 __usb_ep_write(CTRL_ENP_IN,
1380 usb_size(lang_str->bLength,
1381 usb_le16_to_cpu(setup_packet.wLength)),
1386 static void UsbGetDescriptor(void)
1388 uint16_t w_value_lo = usb_le16_to_cpu(setup_packet.wValue) & 0x00ff;
1389 uint16_t w_value_hi = (usb_le16_to_cpu(setup_packet.wValue) & 0xff00) >> 8;
1391 if (udc.state < USB_STATE_DEFAULT)
1393 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1399 LOG_INFO("%s: GET_DEVICE_DESCRIPTOR: id=%d, state=%d\n",
1403 if (usb_get_device_descriptor(w_value_lo) < 0)
1404 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1407 LOG_INFO("%s: GET_CONFIG_DESCRIPTOR: id=%d, state=%d\n",
1408 __func__, w_value_lo, udc.state);
1409 if (usb_get_configuration_descriptor(w_value_lo) < 0)
1410 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1413 LOG_INFO("%s: GET_STRING_DESCRIPTOR: id=%d, state=%d\n",
1414 __func__, w_value_lo, udc.state);
1415 if (usb_get_string_descriptor(w_value_lo) < 0)
1416 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1419 LOG_WARN("%s: GET_UNKNOWN_DESCRIPTOR: id=%d, state=%d\n",
1420 __func__, w_value_lo, udc.state);
1421 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1426 /* USB setup packet: class/vendor request handler */
1427 static void usb_event_handler(UsbDevice *dev)
1430 * TODO: get the appropriate usb_dev in function of the endpoint
1434 dev->event_cb(&setup_packet);
1437 /* USB setup packet: GET_DESCRIPTOR handler */
1438 static void UBS_GetDescriptorHandler(void)
1440 LOG_INFO("%s: GET_DESCRIPTOR: RECIP = %d\n",
1442 setup_packet.mRequestType & USB_RECIP_MASK);
1443 if ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1446 /* Getting descriptor for a device is a standard request */
1447 else if ((setup_packet.mRequestType & USB_DIR_MASK) == USB_DIR_IN)
1448 usb_event_handler(usb_dev);
1450 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1453 /* USB setup packet: SET_ADDRESS handler */
1454 static void USB_SetAddressHandler(void)
1456 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1457 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1458 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1460 LOG_INFO("%s: SET_ADDRESS: %d\n",
1461 __func__, usb_le16_to_cpu(setup_packet.wValue));
1462 if ((udc.state >= USB_STATE_DEFAULT) &&
1463 ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1464 USB_RECIP_DEVICE) &&
1465 (w_index == 0) && (w_length == 0) && (w_value < 128))
1466 USB_StatusHandler(CTRL_ENP_IN);
1468 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1471 /* USB setup packet: GET_CONFIGURATION handler */
1472 static void USB_GetConfigurationHandler(void)
1474 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1475 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1477 LOG_INFO("%s: GET_CONFIGURATION\n", __func__);
1478 if ((udc.state >= USB_STATE_ADDRESS) &&
1479 (w_value == 0) && (w_index == 0) && (w_value == 1))
1481 InData = udc.cfg_id;
1482 __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 1, USB_StatusHandler);
1485 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1488 static const UsbConfigDesc *usb_find_configuration(int num)
1490 const UsbConfigDesc *cfg;
1495 cfg = (const UsbConfigDesc *)usb_dev->config[i];
1498 if (cfg->bDescriptorType != USB_DT_CONFIG)
1500 if (cfg->bConfigurationValue == num)
1506 static int UsbSetConfigurationState(uint32_t Configuration)
1508 const UsbConfigDesc *pCnfg;
1513 /* Find configuration descriptor */
1514 pCnfg = usb_find_configuration(Configuration);
1516 return -USB_NODEV_ERROR;
1518 /* Reset current configuration */
1519 usb_set_device_state(USB_STATE_ADDRESS);
1520 usb_dev->configured = false;
1523 /* Set Interface and Alternative Setting */
1524 udc.cfg_id = Configuration;
1525 /* Set self-powered state */
1526 if (pCnfg->bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1527 udc.feature |= STM32_UDC_FEATURE_SELFPOWERED;
1529 /* Configure all existing interfaces to alternative setting 0 */
1530 ASSERT(pCnfg->bNumInterfaces <= USB_MAX_INTERFACE);
1531 udc.interfaces = pCnfg->bNumInterfaces;
1532 for (i = 0; i < udc.interfaces; i++)
1534 usb_set_device_state(USB_STATE_CONFIGURED);
1535 usb_dev->configured = true;
1539 usb_dev->configured = false;
1540 usb_set_device_state(USB_STATE_ADDRESS);
1545 /* USB setup packet: SET_CONFIGURATION handler */
1546 static void USB_SetConfigurationHandler(void)
1548 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1549 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1550 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1552 LOG_INFO("%s: SET_CONFIGURATION: %d\n",
1554 if ((udc.state >= USB_STATE_ADDRESS) &&
1555 (w_index == 0) && (w_length == 0) &&
1556 (UsbSetConfigurationState(w_value & 0xff) == 0))
1557 USB_StatusHandler(CTRL_ENP_OUT);
1559 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1562 /* USB setup packet: standard request handler */
1563 static void USB_StandardRequestHandler(void)
1565 switch (setup_packet.bRequest)
1567 case USB_REQ_GET_STATUS:
1568 USB_GetStatusHandler();
1570 case USB_REQ_CLEAR_FEATURE:
1571 LOG_INFO("%s: bRequest=%d (CLEAR_FEATURE)\n",
1572 __func__, setup_packet.bRequest);
1574 case USB_REQ_SET_FEATURE:
1575 LOG_INFO("%s: bRequest=%d (SET_FEATURE)\n",
1576 __func__, setup_packet.bRequest);
1578 case USB_REQ_SET_ADDRESS:
1579 USB_SetAddressHandler();
1581 case USB_REQ_GET_DESCRIPTOR:
1582 UBS_GetDescriptorHandler();
1584 case USB_REQ_SET_DESCRIPTOR:
1585 LOG_INFO("%s: bRequest=%d (SET_DESCRIPTOR)\n",
1586 __func__, setup_packet.bRequest);
1588 case USB_REQ_GET_CONFIGURATION:
1589 USB_GetConfigurationHandler();
1591 case USB_REQ_SET_CONFIGURATION:
1592 USB_SetConfigurationHandler();
1594 case USB_REQ_GET_INTERFACE:
1595 LOG_INFO("%s: bRequest=%d (GET_INTERFACE)\n",
1596 __func__, setup_packet.bRequest);
1598 case USB_REQ_SET_INTERFACE:
1599 LOG_INFO("%s: bRequest=%d (SET_INTERFACE)\n",
1600 __func__, setup_packet.bRequest);
1602 case USB_REQ_SYNCH_FRAME:
1603 LOG_INFO("%s: bRequest=%d (SYNCH_FRAME)\n",
1604 __func__, setup_packet.bRequest);
1607 LOG_WARN("%s: bRequest=%d (Unknown)\n",
1608 __func__, setup_packet.bRequest);
1609 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1614 /* USB setup packet handler */
1615 static void USB_SetupHandler(void)
1617 switch (setup_packet.mRequestType & USB_TYPE_MASK)
1620 case USB_TYPE_STANDARD:
1621 LOG_INFO("%s: bmRequestType=%02x (Standard)\n",
1622 __func__, setup_packet.mRequestType);
1623 USB_StandardRequestHandler();
1626 case USB_TYPE_CLASS:
1627 LOG_INFO("%s: bmRequestType=%02x (Class)\n",
1628 __func__, setup_packet.mRequestType);
1629 usb_event_handler(usb_dev);
1632 case USB_TYPE_VENDOR:
1633 LOG_INFO("%s: bmRequestType=%02x (Vendor)\n",
1634 __func__, setup_packet.mRequestType);
1635 usb_event_handler(usb_dev);
1637 case USB_TYPE_RESERVED:
1638 LOG_INFO("%s: bmRequestType=%02x (Reserved)\n",
1639 __func__, setup_packet.mRequestType);
1643 LOG_WARN("%s: bmRequestType=%02x (Unknown)\n",
1644 __func__, setup_packet.mRequestType);
1645 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1650 /* USB: low-level hardware initialization */
1651 static void usb_hw_reset(void)
1656 /* Initialize endpoint descriptors */
1657 for (i = 0; i < countof(ep_cnfg); i++)
1658 ep_cnfg[i].hw = NULL;
1660 /* Initialize USB memory */
1661 for (i = 0; i < countof(memory_buffer); i++)
1662 memory_buffer[i].Size = 0;
1663 usb->BTABLE = USB_BDT_OFFSET;
1666 /* Endpoint initialization */
1667 ret = usb_ep_configure(&USB_CtrlEpDescr0, true);
1668 if (UNLIKELY(ret < 0))
1670 LOG_WARN("%s: out of memory, cannot initialize EP0\n",
1674 ret = usb_ep_configure(&USB_CtrlEpDescr1, true);
1675 if (UNLIKELY(ret < 0))
1677 LOG_WARN("%s: out of memory, cannot initialize EP1\n",
1682 /* Set default address */
1685 /* Enable all the device interrupts */
1686 usb->CNTR = bmCTRM | bmRESETM | bmSOFM | bmERRM | bmPMAOVRM |
1690 /* Handle a correct transfer under ISR */
1691 static void usb_isr_correct_transfer(stm32_usb_irq_status_t interrupt)
1694 reg32_t *pReg = (reg32_t *)&usb->EP0R;
1696 /* Find corresponding EP */
1697 pReg += interrupt.EP_ID;
1698 EP = (int)(((*pReg & 0x0f) << 1) + (interrupt.DIR ? 0 : 1));
1699 ep_cnfg[EP].avail_data = 1;
1701 ASSERT(ep_cnfg[EP].hw);
1704 EpCtrlClr_CTR_TX(ep_cnfg[EP].hw);
1706 EpCtrlClr_CTR_RX(ep_cnfg[EP].hw);
1707 if (EP == CTRL_ENP_OUT)
1709 /* Determinate type of packet (only for control EP) */
1710 bool SetupPacket = EpCtrlGet_SETUP(ep_cnfg[CTRL_ENP_OUT].hw);
1714 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
1715 /* init IO to receive Setup packet */
1716 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1717 __usb_ep_read(CTRL_ENP_OUT, &setup_packet,
1718 sizeof(setup_packet), NULL);
1720 /* reset EP IO ctrl */
1721 if (setup_packet.mRequestType & USB_DIR_IN)
1722 USB_StatusHandler(CTRL_ENP_OUT);
1724 if (ep_cnfg[CTRL_ENP_OUT].status == STALLED)
1729 if (ep_cnfg[CTRL_ENP_OUT].complete &&
1730 setup_packet.mRequestType & USB_DIR_IN)
1731 ep_cnfg[CTRL_ENP_OUT].complete(CTRL_ENP_OUT);
1736 else if (EP == CTRL_ENP_IN)
1738 if (ep_cnfg[CTRL_ENP_IN].complete &&
1739 !(setup_packet.mRequestType & USB_DIR_IN))
1740 ep_cnfg[CTRL_ENP_IN].complete(CTRL_ENP_IN);
1749 /* USB: interrupt service routine */
1750 static void usb_isr(void)
1752 stm32_usb_irq_status_t interrupt;
1754 /* Get masked interrupt flags */
1755 interrupt.status = usb->ISTR;
1756 interrupt.status &= usb->CNTR | 0x1f;
1758 if (interrupt.PMAOVR)
1760 LOG_WARN("%s: DMA overrun / underrun\n", __func__);
1761 usb->ISTR = ~bmPMAOVRM;
1765 LOG_WARN("%s: engine error\n", __func__);
1766 usb->ISTR = ~bmERRM;
1768 if (interrupt.RESET)
1770 LOG_INFO("%s: device reset\n", __func__);
1771 usb->ISTR = ~bmRESETM;
1773 usb_set_device_state(USB_STATE_DEFAULT);
1779 * XXX: disable logging of frame interrupts (too much noise!)
1781 uint16_t frame_nr = usb->FNR & 0x0fff;
1782 LOG_INFO("%s: frame %#x\n", __func__, frame_nr);
1784 usb->ISTR = ~bmSOFM;
1788 LOG_INFO("%s: wake-up\n", __func__);
1789 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1794 LOG_INFO("%s: suspend\n", __func__);
1796 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1800 LOG_INFO("%s: expected frame\n", __func__);
1801 usb->ISTR = ~bmESOFM;
1805 usb_isr_correct_transfer(interrupt);
1809 /* USB: hardware initialization */
1810 static void usb_hw_init(void)
1812 /* Enable clocking on the required GPIO pins */
1813 RCC->APB2ENR |= RCC_APB2_GPIOA | RCC_APB2_GPIOC;
1815 /* Make sure that the CAN controller is disabled and held in reset */
1816 RCC->APB1ENR &= ~RCC_APB1_CAN;
1818 /* Configure USB_DM and USB_DP to work as USB lines */
1819 stm32_gpioPinConfig((struct stm32_gpio *)GPIOA_BASE,
1820 USB_DM_PIN | USB_DP_PIN,
1821 GPIO_MODE_AF_PP, GPIO_SPEED_50MHZ);
1822 /* Configure USB_DISC to work as USB disconnect */
1823 stm32_gpioPinConfig((struct stm32_gpio *)GPIOC_BASE,
1825 GPIO_MODE_OUT_PP, GPIO_SPEED_50MHZ);
1826 stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE,
1829 /* Ensure the USB clock is disabled before setting the prescaler */
1830 RCC->APB1ENR &= ~RCC_APB1_USB;
1832 /* Configure USB clock (48MHz) */
1833 *CFGR_USBPRE_BB &= ~RCC_USBCLK_PLLCLK_1DIV5;
1835 /* Activate USB clock */
1836 RCC->APB1ENR |= RCC_APB1_USB;
1838 /* Force USB reset and disable USB interrupts */
1842 /* Issue a USB reset */
1845 /* Clear spurious pending interrupt */
1848 /* Register interrupt handler */
1849 sysirq_setHandler(USB_LP_CAN_RX0_IRQHANDLER, usb_isr);
1851 /* Software connection enable */
1855 /* Initialize the USB controller */
1856 static void usb_init(void)
1858 udc.state = USB_STATE_NOTATTACHED;
1864 /* Register an upper layer USB device into the driver */
1865 int usb_deviceRegister(UsbDevice *dev)
1872 while (!usb_dev->configured)