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 /* XXX: consider to move this to cfg/compiler.h */
62 #define ALIGNED(x) __attribute__ ((__aligned__(x)))
64 /* XXX: consider to move this to cfg/macros.h */
65 #define ALIGN_UP(value, align) (((value) & ((align) - 1)) ? \
66 (((value) + ((align) - 1)) & ~((align) - 1)) : \
69 /* XXX: redefine this to make it usable within C expression */
70 #define _MIN(a,b) (((a) < (b)) ? (a) : (b))
72 /* STM32 USB registers */
83 reg32_t __reserved[8];
91 /* Hardware registers */
92 static struct stm32_usb *usb = (struct stm32_usb *)USB_BASE_ADDR;
94 /* Endpoint descriptors: used for handling requests to use with endpoints */
95 static stm32_UsbEp ep_cnfg[EP_MAX_NUM];
97 /* USB EP0 control descriptor */
98 static const UsbEndpointDesc USB_CtrlEpDescr0 =
100 .bLength = sizeof(USB_CtrlEpDescr0),
101 .bDescriptorType = USB_DT_ENDPOINT,
102 .bEndpointAddress = USB_DIR_OUT | 0,
103 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
104 .wMaxPacketSize = USB_EP0_MAX_SIZE,
108 /* USB EP1 control descriptor */
109 static const UsbEndpointDesc USB_CtrlEpDescr1 =
111 .bLength = sizeof(USB_CtrlEpDescr1),
112 .bDescriptorType = USB_DT_ENDPOINT,
113 .bEndpointAddress = USB_DIR_IN | 0,
114 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
115 .wMaxPacketSize = USB_EP0_MAX_SIZE,
119 /* USB setup packet */
120 static UsbCtrlRequest setup_packet;
122 /* USB device controller: max supported interfaces */
123 #define USB_MAX_INTERFACE 1
125 /* USB device controller features */
126 #define STM32_UDC_FEATURE_SELFPOWERED BV(0)
127 #define STM32_UDC_FEATURE_REMOTE_WAKEUP BV(1)
129 /* Hardware-specific USB device controller structure */
130 typedef struct stm32_udc
134 const UsbConfigDesc *cfg;
136 uint32_t alt[USB_MAX_INTERFACE];
139 } PACKED stm32_udc_t;
141 /* Hardware-specific USB Device Controller */
142 static stm32_udc_t udc;
144 /* Generic USB Device Controller structure */
145 static UsbDevice *usb_dev;
147 /* USB packet memory management: list of allocated chunks */
148 static stm32_UsbMemSlot *mem_use;
150 /* USB packet memory management: memory buffer metadata */
151 static stm32_UsbMemSlot memory_buffer[EP_MAX_HW_NUM >> 1];
153 /* Endpoint TX and RX buffers */
155 /* XXX: use the empty cond section to silent a buggy doxygen warning */
156 static bool rx_done, tx_done;
157 static size_t rx_size, tx_size;
158 static uint8_t ep_buffer[_MIN(CONFIG_USB_BUFSIZE, USB_XFER_MAX_SIZE)] ALIGNED(4);
161 /* Allocate a free block of the packet memory */
162 static stm32_UsbMemSlot *usb_malloc(void)
166 for (i = 0; i < countof(memory_buffer); i++)
167 if (memory_buffer[i].Size == 0)
168 return &memory_buffer[i];
172 /* Release a block of the packet memory */
173 static void usb_free(stm32_UsbMemSlot *pPntr)
178 /* Allocate a free chunk of the packet memory (inside a block) */
179 static bool usb_alloc_buffer(uint16_t *pOffset, uint32_t *size,
182 stm32_UsbMemSlot *mem = mem_use,
183 *memNext, *mem_useNew;
184 uint32_t max_size = *size;
187 * Packet size alignment:
188 * - fine-granularity allocation: size alignment by 2;
189 * - coarse-granularity allocation: size alignment by 32.
192 max_size = ALIGN_UP(max_size, 2);
194 max_size = ALIGN_UP(max_size, 32);
196 * Finding free memory chunks from the allocated blocks of the USB
202 /* Offset alignment by 4 */
203 *pOffset = ALIGN_UP(mem->Start + mem->Size, 4);
205 if ((mem->next == NULL) ||
207 *pOffset + max_size))
211 /* Check for out-of-memory condition */
212 if ((*pOffset + max_size) >= USB_BDT_OFFSET)
215 * Allocate a new memory block, next to the last allocated block.
217 mem_useNew = usb_malloc();
218 if (mem_useNew == NULL)
220 /* Insert the block to the list of allocated blocks */
223 mem_use = mem_useNew;
224 mem_use->next = NULL;
228 mem_useNew->next = mem->next;
229 mem->next = mem_useNew;
231 /* Update block's metadata */
232 mem_useNew->ep_addr = EndPoint;
233 mem_useNew->Start = *pOffset;
234 mem_useNew->Size = max_size;
241 /* Release a chunk of the packet memory (inside a block) */
242 static void usb_free_buffer(int EndPoint)
244 stm32_UsbMemSlot *mem, *memPrev = NULL;
249 if (mem->ep_addr == EndPoint)
251 if (UNLIKELY(memPrev == NULL))
253 /* Free the first element of the list */
254 mem_use = mem_use->next;
259 memPrev->next = mem->next;
268 /*-------------------------------------------------------------------------*/
270 /* Connect USB controller */
271 static void usb_connect(void)
273 stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE, 1 << 11, 0);
276 /* Set USB device address */
277 static void usb_set_address(uint32_t addr)
279 usb->DADDR = addr | 0x80;
282 /* Suspend USB controller */
283 static void usb_suspend(void)
285 usb->CNTR |= bmFSUSP | bmLPMODE;
288 /* Resume USB controller */
289 static void usb_resume(void)
291 uint32_t line_status;
293 line_status = usb->FNR & 0xc000;
296 /* check for noise and eventually return to sleep */
297 if (line_status == 0xc000)
300 usb->CNTR &= ~(bmFSUSP | bmLPMODE);
303 /* Convert logical EP address to physical EP address */
304 static int usb_ep_logical_to_hw(uint8_t ep_addr)
306 int addr = (ep_addr & 0x0f) << 1;
307 return (ep_addr & 0x80) ? addr + 1 : addr;
311 static void ep_ctrl_set_ea(reg32_t *reg, uint32_t val)
314 val |= *reg & 0x0700;
315 val |= USB_CTRL_CLEAR_ONLY_MASK;
319 /* Get EP IN status */
320 static uint32_t ep_ctrl_get_stat_tx(reg32_t *reg)
322 return (*reg & (0x3UL << 4)) >> 4;
325 /* Set EP IN state */
326 static void ep_ctrl_set_stat_tx(reg32_t *reg, stm32_UsbEpState val)
332 * The EP can change state between read and write operations from VALID
333 * to NAK and result of set operation will be invalid.
335 for (i = 0; i < 2; i++)
337 if (ep_ctrl_get_stat_tx(reg) == val)
342 state |= USB_CTRL_CLEAR_ONLY_MASK;
343 /* Clear the toggle bits without STAT_TX (4,5) */
349 /* Set EP DTOG_TX bit (IN) */
350 static void ep_ctrl_set_dtog_tx(reg32_t *reg, uint32_t val)
352 val = val ? (*reg ^ (1UL << 6)) : *reg;
353 /* Clear the toggle bits without DTOG_TX (6) */
355 val |= USB_CTRL_CLEAR_ONLY_MASK;
359 /* Clear EP CTR_TX bit (IN) */
360 static void ep_ctrl_clr_ctr_tx(reg32_t *reg)
364 val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 7);
370 /* Clear EP CTR_RX bit (OUT) */
371 static void ep_ctrl_clr_ctr_rx(reg32_t *reg)
374 val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 15);
380 /* Set EP KIND bit */
381 static void ep_ctrl_set_ep_kind(reg32_t *reg, uint32_t val)
383 val = val ? (1UL << 8) : 0;
384 val |= *reg & ~(USB_CTRL_TOGGLE_MASK | (1UL << 8));
385 val |= USB_CTRL_CLEAR_ONLY_MASK;
390 static int ep_ctrl_set_ep_type(reg32_t *reg, uint8_t val)
394 if (UNLIKELY(val >= EP_TYPE_MAX))
397 return USB_INVAL_ERROR;
401 type |= *reg & ~(USB_CTRL_TOGGLE_MASK | (0x3UL << 9));
402 type |= USB_CTRL_CLEAR_ONLY_MASK;
408 /* Get EP STAT_RX (OUT) */
409 static uint32_t ep_ctrl_get_stat_rx(reg32_t *reg)
411 uint32_t val = *reg & (0x3UL << 12);
415 /* Set EP STAT_RX (OUT) */
416 static void ep_ctrl_set_stat_rx(reg32_t *reg, stm32_UsbEpState val)
422 * The EP can change state between read and write operations from VALID
423 * to NAK and result of set operation will be invalid.
425 for (i = 0; i < 2; i++)
427 if (ep_ctrl_get_stat_rx(reg) == val)
432 state |= USB_CTRL_CLEAR_ONLY_MASK;
433 /* Clear the toggle bits without STAT_RX (12,13) */
439 /* Set DTOG_RX bit */
440 static void ep_ctrl_set_dtog_rx(reg32_t *reg, uint32_t val)
442 val = val ? (*reg ^ (1UL << 14)) : *reg;
443 /* Clear the toggle bits without DTOG_RX (14) */
445 val |= USB_CTRL_CLEAR_ONLY_MASK;
449 /* Get EP SETUP bit */
450 static uint32_t ep_ctrl_get_setup(reg32_t *reg)
452 uint32_t val = *reg & (1UL << 11);
456 /* Core endpoint I/O function */
457 static void __usb_ep_io(int EP)
459 ssize_t Count, CountHold, Offset;
460 uint32_t *pDst, *pSrc, Data;
461 stm32_UsbEp *epd = &ep_cnfg[EP];
463 if (UNLIKELY(epd->hw == NULL))
465 LOG_ERR("%s: invalid endpoint (EP%d-%s)\n",
468 (EP & 0x01) ? "IN" : "OUT");
472 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
478 Count = epd->size - epd->offset;
479 while (epd->avail_data)
481 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
485 epd->status = BEGIN_SERVICED;
487 if ((epd->flags & STM32_USB_EP_ZERO_PACKET) &&
488 (Count == epd->max_size))
489 epd->flags |= STM32_USB_EP_ZERO_PACKET |
490 STM32_USB_EP_ZERO_POSSIBLE;
492 CountHold = Count = MIN(Count, epd->max_size);
494 epd->flags |= STM32_USB_EP_ZERO_PACKET;
495 Offset = epd->offset;
496 epd->offset += Count;
499 case USB_ENDPOINT_XFER_CONTROL:
500 case USB_ENDPOINT_XFER_INT:
501 pDst = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_TX_OFFSET));
503 case USB_ENDPOINT_XFER_BULK:
504 pDst = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_TX_OFFSET));
506 case USB_ENDPOINT_XFER_ISOC:
507 LOG_ERR("%s: isochronous transfer not supported\n",
509 /* Fallback to default */
515 /* Write data to packet memory buffer */
518 Data = *(epd->write_buffer + Offset++);
521 Data |= (uint32_t)(*(epd->write_buffer + Offset++)) << 8;
527 EP_DTB_WRITE(EP >> 1, COUNT_TX_OFFSET, CountHold);
528 ep_ctrl_set_stat_tx(epd->hw, EP_VALID);
530 --ep_cnfg[EP].avail_data;
531 Count = epd->size - epd->offset;
533 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
535 epd->status = COMPLETE;
536 /* call callback function */
544 while (epd->avail_data)
546 /* Get data size and buffer pointer */
549 case USB_ENDPOINT_XFER_CONTROL:
550 case USB_ENDPOINT_XFER_INT:
551 /* Get received bytes number */
552 Count = EP_DTB_READ(EP >> 1, COUNT_RX_OFFSET) & 0x3FF;
553 /* Get address of the USB packet buffer for corresponding EP */
554 pSrc = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_RX_OFFSET));
556 case USB_ENDPOINT_XFER_BULK:
557 /* Get received bytes number */
558 Count = EP_DTB_READ(EP >> 1, COUNT_RX_OFFSET) & 0x3FF;
559 /* Get address of the USB packet buffer for corresponding EP */
560 pSrc = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_RX_OFFSET));
562 case USB_ENDPOINT_XFER_ISOC:
563 LOG_ERR("%s: isochronous transfer not supported\n",
565 /* Fallback to default */
571 if (Count > (epd->size - epd->offset))
573 epd->status = BUFFER_OVERRUN;
574 epd->size = ep_cnfg[EP].offset;
577 else if (Count < ep_cnfg[EP].max_size)
579 epd->status = BUFFER_UNDERRUN;
580 epd->size = ep_cnfg[EP].offset + Count;
583 epd->status = BEGIN_SERVICED;
585 Offset = epd->offset;
586 epd->offset += Count;
588 /* Read data from packet memory buffer */
592 *(epd->read_buffer + Offset++) = Data;
596 *(epd->read_buffer + Offset++) = Data;
601 ep_ctrl_set_stat_rx(epd->hw, EP_VALID);
603 --ep_cnfg[EP].avail_data;
605 if (*epd->hw & (1UL << 11))
607 ep_cnfg[EP].status = SETUP_OVERWRITE;
610 if (!(Count = (epd->size - epd->offset)))
612 epd->status = COMPLETE;
616 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
618 /* call callback function */
626 * Return the lower value from Host expected size and size and set a flag
627 * STM32_USB_EP_ZERO_POSSIBLE when size is lower that host expected size.
629 static size_t usb_size(size_t size, size_t host_size)
631 if (size < host_size)
633 ep_cnfg[CTRL_ENP_IN].flags |= STM32_USB_EP_ZERO_POSSIBLE;
639 /* Configure an EP descriptor before performing a I/O operation */
640 #define USB_EP_IO(__EP, __op, __buf, __size, __complete) \
643 stm32_UsbIoStatus ret; \
645 /* Fill EP descriptor */ \
646 IRQ_SAVE_DISABLE(flags); \
649 ep_cnfg[__EP].status = NOT_READY; \
650 ep_cnfg[__EP].complete = NULL; \
654 if (ep_cnfg[__EP].status == BEGIN_SERVICED) \
660 * NOTE: the write_buffer and read_buffer are actually the \
661 * same location in memory (it's a union). \
663 * We have to do this trick to silent a build warning by \
664 * casting the I/O buffer to (void *) or (const void *). \
666 ep_cnfg[__EP].__op ## _buffer = __buf; \
667 ep_cnfg[__EP].offset = 0; \
668 ep_cnfg[__EP].size = __size; \
669 ep_cnfg[__EP].complete = __complete; \
671 ep_cnfg[__EP].flags = STM32_USB_EP_ZERO_PACKET; \
673 ep_cnfg[__EP].flags = 0; \
674 ep_cnfg[__EP].status = NO_SERVICED; \
676 /* Perform the I/O operation */ \
679 ret = ep_cnfg[__EP].status; \
681 IRQ_RESTORE(flags); \
685 /* Configure and endponint and perform a read operation */
686 static stm32_UsbIoStatus
687 __usb_ep_read(int ep, void *buffer, ssize_t size, void (*complete)(int))
689 if (UNLIKELY((ep >= EP_MAX_NUM) || (ep & 0x01)))
691 LOG_ERR("%s: invalid EP number %d\n", __func__, ep);
695 if (UNLIKELY((size_t)buffer & 0x03))
697 LOG_ERR("%s: unaligned buffer @ %p\n", __func__, buffer);
701 return USB_EP_IO(ep, read, buffer, size, complete);
704 /* Configure and endponint and perform a write operation */
705 static stm32_UsbIoStatus
706 __usb_ep_write(int ep, const void *buffer, ssize_t size, void (*complete)(int))
708 if (UNLIKELY((ep >= EP_MAX_NUM) || !(ep & 0x01)))
710 LOG_ERR("%s: invalid EP number %d\n", __func__, ep);
714 if (UNLIKELY((size_t)buffer & 0x03))
716 LOG_ERR("%s: unaligned buffer @ %p\n", __func__, buffer);
720 return USB_EP_IO(ep, write, buffer, size, complete);
723 static void usb_ep_low_level_config(int ep, uint16_t offset, uint16_t size)
725 stm32_UsbEp *epc = &ep_cnfg[ep];
731 ep_ctrl_set_stat_tx(epc->hw, EP_DISABLED);
732 /* Clear Tx toggle */
733 ep_ctrl_set_dtog_tx(epc->hw, 0);
734 /* Clear Correct Transfer for transmission flag */
735 ep_ctrl_clr_ctr_tx(epc->hw);
737 /* Update EP description table */
738 EP_DTB_WRITE(ep >> 1, ADDR_TX_OFFSET, offset);
739 EP_DTB_WRITE(ep >> 1, COUNT_TX_OFFSET, 0);
744 uint16_t rx_count = 0;
747 ep_ctrl_set_stat_rx(epc->hw, EP_DISABLED);
748 /* Clear Rx toggle */
749 ep_ctrl_set_dtog_rx(epc->hw, 0);
750 /* Clear Correct Transfer for reception flag */
751 ep_ctrl_clr_ctr_rx(epc->hw);
752 /* Descriptor block size field */
753 rx_count |= (size > 62) << 15;
754 /* Descriptor number of blocks field */
755 rx_count |= (((size > 62) ? (size >> 5) - 1 : size >> 1) &
757 /* Update EP description table */
758 EP_DTB_WRITE(ep >> 1, ADDR_RX_OFFSET, offset);
759 EP_DTB_WRITE(ep >> 1, COUNT_RX_OFFSET, rx_count);
763 /* Enable/Disable an endpoint */
764 static int usb_ep_configure(const UsbEndpointDesc *epd, bool enable)
772 EP = usb_ep_logical_to_hw(epd->bEndpointAddress);
773 ep_hw = &ep_cnfg[EP];
778 * Allocate packet memory for EP buffer/s calculate actual size
779 * only for the OUT EPs.
781 size = epd->wMaxPacketSize;
782 if (!usb_alloc_buffer(&Offset, &size, EP))
783 return -USB_MEMORY_FULL;
786 ep_hw->status = NOT_READY;
790 /* Set endpoint type */
791 ep_hw->type = usb_endpointType(epd);
792 /* Init EP max packet size */
793 ep_hw->max_size = epd->wMaxPacketSize;
796 ep_hw->avail_data = 1;
798 ep_hw->avail_data = 0;
799 hw = (reg32_t *)&usb->EP0R;
803 ep_ctrl_set_ea(hw, EP >> 1);
805 LOG_INFO("%s: EP%d-%s configured\n",
806 __func__, EP >> 1, EP & 1 ? "IN" : "OUT");
808 /* Low-level endpoint configuration */
809 usb_ep_low_level_config(EP, Offset, size);
811 /* Set EP Kind & enable */
814 case USB_ENDPOINT_XFER_CONTROL:
815 LOG_INFO("EP%d: CONTROL IN\n", EP >> 1);
816 ep_ctrl_set_ep_type(hw, EP_CTRL);
817 ep_ctrl_set_ep_kind(hw, 0);
819 case USB_ENDPOINT_XFER_INT:
820 LOG_INFO("EP%d: INTERRUPT IN\n", EP >> 1);
821 ep_ctrl_set_ep_type(hw, EP_INTERRUPT);
822 ep_ctrl_set_ep_kind(hw, 0);
824 case USB_ENDPOINT_XFER_BULK:
825 LOG_INFO("EP%d: BULK IN\n", EP >> 1);
826 ep_ctrl_set_ep_type(hw, EP_BULK);
827 ep_ctrl_set_ep_kind(hw, 0);
829 case USB_ENDPOINT_XFER_ISOC:
830 LOG_ERR("EP%d: ISOCHRONOUS IN: not supported\n", EP >> 1);
831 /* Fallback to default */
834 return -USB_NODEV_ERROR;
839 ep_ctrl_set_stat_tx(hw, EP_NAK);
840 /* Clear Correct Transfer for transmission flag */
841 ep_ctrl_clr_ctr_tx(hw);
846 ep_ctrl_set_stat_rx(hw, EP_VALID);
849 else if (ep_cnfg[EP].hw)
851 hw = (reg32_t *)&usb->EP0R;
858 ep_ctrl_set_stat_tx(hw, EP_DISABLED);
859 /* Clear Correct Transfer for reception flag */
860 ep_ctrl_clr_ctr_tx(hw);
866 ep_ctrl_set_stat_rx(hw, EP_DISABLED);
867 /* Clear Correct Transfer for reception flag */
868 ep_ctrl_clr_ctr_rx(hw);
872 ep_cnfg[EP].hw = NULL;
877 /* Get EP stall/unstall */
878 static int usb_ep_get_stall(int EP, bool *pStall)
880 if (ep_cnfg[EP].hw == NULL)
881 return -USB_NODEV_ERROR;
883 *pStall = (EP & 0x01) ?
884 (ep_ctrl_get_stat_tx(ep_cnfg[EP].hw) == EP_STALL): /* IN EP */
885 (ep_ctrl_get_stat_rx(ep_cnfg[EP].hw) == EP_STALL); /* OUT EP */
890 /* Set EP stall/unstall */
891 static int usb_ep_set_stall(int EP, bool Stall)
893 if (ep_cnfg[EP].hw == NULL)
894 return -USB_NODEV_ERROR;
898 ep_cnfg[EP].status = STALLED;
902 ep_ctrl_set_stat_tx(ep_cnfg[EP].hw, EP_STALL);
903 ep_cnfg[EP].avail_data = 1;
908 ep_ctrl_set_stat_rx(ep_cnfg[EP].hw, EP_STALL);
909 ep_cnfg[EP].avail_data = 0;
914 ep_cnfg[EP].status = NOT_READY;
918 ep_cnfg[EP].avail_data = 1;
919 /* reset Data Toggle bit */
920 ep_ctrl_set_dtog_tx(ep_cnfg[EP].hw, 0);
921 ep_ctrl_set_stat_tx(ep_cnfg[EP].hw, EP_NAK);
926 ep_cnfg[EP].avail_data = 0;
927 /* reset Data Toggle bit */
928 ep_ctrl_set_dtog_rx(ep_cnfg[EP].hw, 0);
929 ep_ctrl_set_stat_rx(ep_cnfg[EP].hw, EP_VALID);
935 /* Stall both directions of the control EP */
936 static void usb_ep_set_stall_ctrl(void)
938 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
939 ep_cnfg[CTRL_ENP_IN].status = STALLED;
940 ep_cnfg[CTRL_ENP_OUT].avail_data = 0;
941 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
943 usb_ep_set_stall(CTRL_ENP_IN, true);
944 usb_ep_set_stall(CTRL_ENP_OUT, true);
948 * Find the position of an interface descriptor inside the configuration
951 static int usb_find_interface(uint32_t num, uint32_t alt)
953 const UsbInterfaceDesc *id;
958 /* TODO: support more than one configuration per device */
959 id = (const UsbInterfaceDesc *)usb_dev->config[i];
962 if (id->bDescriptorType != USB_DT_INTERFACE)
964 if ((id->bInterfaceNumber == num) &&
965 (id->bAlternateSetting == alt))
968 return -USB_NODEV_ERROR;
972 * Configure/deconfigure EPs of a certain interface.
975 usb_configure_ep_interface(unsigned int num, unsigned int alt, bool enable)
977 const UsbEndpointDesc *epd;
981 * Find the position of the interface descriptor (inside the
982 * configuration descriptor).
984 start = usb_find_interface(num, alt);
987 LOG_ERR("%s: interface (%u,%u) not found\n",
992 * Cycle over endpoint descriptors.
994 * NOTE: the first endpoint descriptor is placed next to the interface
995 * descriptor, so we need to add +1 to the position of the interface
996 * descriptor to find it.
998 for (i = start + 1; ; i++)
1000 epd = (const UsbEndpointDesc *)usb_dev->config[i];
1001 if ((epd == NULL) || (epd->bDescriptorType == USB_DT_INTERFACE))
1003 if (epd->bDescriptorType != USB_DT_ENDPOINT)
1005 if (UNLIKELY(usb_ep_configure(epd, enable) < 0))
1007 LOG_ERR("%s: out of memory, can't initialize EP\n",
1014 /* Set device state */
1015 static void usb_set_device_state(int state)
1019 LOG_INFO("%s: new state %d\n", __func__, state);
1021 if (udc.state == USB_STATE_CONFIGURED)
1023 /* Deconfigure device */
1024 for (i = 0; i < udc.interfaces; ++i)
1025 usb_configure_ep_interface(i,
1030 case USB_STATE_ATTACHED:
1031 case USB_STATE_POWERED:
1032 case USB_STATE_DEFAULT:
1034 usb_dev->configured = false;
1035 udc.address = udc.cfg_id = 0;
1037 case USB_STATE_ADDRESS:
1040 case USB_STATE_CONFIGURED:
1041 /* Configure device */
1042 for (i = 0; i < udc.interfaces; ++i)
1043 usb_configure_ep_interface(i,
1047 /* Unknown state: disconnected or connection in progress */
1048 usb_dev->configured = false;
1056 /* Setup packet: set address status phase end handler */
1057 static void usb_add_status_handler_end(UNUSED_ARG(int, EP))
1061 w_value = usb_le16_to_cpu(setup_packet.wValue);
1062 udc.address = w_value & 0xff;
1063 usb_set_address(udc.address);
1066 usb_set_device_state(USB_STATE_ADDRESS);
1068 usb_set_device_state(USB_STATE_DEFAULT);
1070 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1071 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1074 /* Prepare status phase */
1075 static void usb_status_phase(bool in)
1078 __usb_ep_write(CTRL_ENP_IN, NULL, 0, NULL);
1081 /* Setup packet: status phase end handler */
1082 static void usb_status_handler_end(UNUSED_ARG(int, EP))
1084 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1085 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1088 /* Address status handler */
1089 static void usb_status_handler(UNUSED_ARG(int, EP))
1091 if (setup_packet.mRequestType & USB_DIR_IN)
1093 usb_status_phase(false);
1094 ep_cnfg[CTRL_ENP_OUT].complete = usb_status_handler_end;
1098 usb_status_phase(true);
1099 ep_cnfg[CTRL_ENP_IN].complete =
1100 (setup_packet.bRequest == USB_REQ_SET_ADDRESS) ?
1101 usb_add_status_handler_end :
1102 usb_status_handler_end;
1106 static void usb_endpointRead_complete(int ep)
1108 if (UNLIKELY(ep >= EP_MAX_NUM))
1113 ASSERT(!(ep & 0x01));
1116 rx_size = ep_cnfg[ep].size;
1119 ssize_t usb_endpointRead(int ep, void *buffer, ssize_t size)
1121 int ep_num = usb_ep_logical_to_hw(ep);
1122 ssize_t max_size = sizeof(ep_buffer);
1124 /* Non-blocking read for EP0 */
1125 if (ep_num == CTRL_ENP_OUT)
1127 size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
1128 if (UNLIKELY(size > max_size))
1130 LOG_ERR("%s: ep_buffer exceeded, try to enlarge CONFIG_USB_BUFSIZE\n",
1133 return -USB_BUF_OVERFLOW;
1136 usb_status_handler(ep_num);
1139 __usb_ep_read(ep_num, ep_buffer, size,
1140 usb_status_handler);
1141 memcpy(buffer, ep_buffer, size);
1145 if (UNLIKELY(!size))
1147 size = MIN(size, max_size);
1152 __usb_ep_read(ep_num, ep_buffer, size, usb_endpointRead_complete);
1155 memcpy(buffer, ep_buffer, rx_size);
1160 static void usb_endpointWrite_complete(int ep)
1162 if (UNLIKELY(ep >= EP_MAX_NUM))
1170 tx_size = ep_cnfg[ep].size;
1173 ssize_t usb_endpointWrite(int ep, const void *buffer, ssize_t size)
1175 int ep_num = usb_ep_logical_to_hw(ep);
1176 ssize_t max_size = sizeof(ep_buffer);
1178 /* Non-blocking write for EP0 */
1179 if (ep_num == CTRL_ENP_IN)
1181 size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
1182 if (UNLIKELY(size > max_size))
1184 LOG_ERR("%s: ep_buffer exceeded, try to enlarge CONFIG_USB_BUFSIZE\n",
1187 return -USB_BUF_OVERFLOW;
1190 usb_status_handler(ep_num);
1193 memcpy(ep_buffer, buffer, size);
1194 __usb_ep_write(ep_num, ep_buffer, size,
1195 usb_status_handler);
1199 if (UNLIKELY(!size))
1201 size = MIN(size, max_size);
1205 /* Blocking write */
1206 memcpy(ep_buffer, buffer, size);
1207 __usb_ep_write(ep_num, ep_buffer, size, usb_endpointWrite_complete);
1214 /* Global variable to handle the following non-blocking I/O operations */
1215 static uint32_t InData;
1217 /* Get device status */
1218 static int usb_send_device_status(uint16_t index)
1221 return -USB_NODEV_ERROR;
1223 InData = ((uint32_t)udc.feature) & 0xff;
1224 __usb_ep_write(CTRL_ENP_IN,
1225 (uint8_t *)&InData, sizeof(uint16_t),
1226 usb_status_handler);
1230 /* Get interface status */
1231 static int usb_send_interface_status(UNUSED_ARG(uint16_t, index))
1234 __usb_ep_write(CTRL_ENP_IN,
1235 (uint8_t *)&InData, sizeof(uint16_t),
1236 usb_status_handler);
1240 /* Get endpoint status */
1241 static int usb_send_ep_status(uint16_t index)
1243 if ((index & 0x7F) > 16)
1244 return -USB_NODEV_ERROR;
1247 usb_ep_get_stall(usb_ep_logical_to_hw(index), (bool *)&InData);
1248 __usb_ep_write(CTRL_ENP_IN,
1249 (uint8_t *)&InData, sizeof(uint16_t),
1250 usb_status_handler);
1254 /* USB setup packet: GET_STATUS request handler */
1255 static void usb_get_status_handler(void)
1257 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1258 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1259 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1261 /* GET_STATUS sanity checks */
1262 if (udc.state < USB_STATE_ADDRESS)
1264 LOG_WARN("%s: bad GET_STATUS request (State=%02x)\n",
1265 __func__, udc.state);
1266 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1271 LOG_WARN("%s: bad GET_STATUS request (wLength.Word=%02x)\n",
1272 __func__, w_length);
1273 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1276 if (!(setup_packet.mRequestType & USB_DIR_IN))
1278 LOG_WARN("%s: bad GET_STATUS request (mRequestType=%02x)\n",
1279 __func__, setup_packet.mRequestType);
1280 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1285 LOG_WARN("%s: bad GET_STATUS request (wValue=%02x)\n",
1287 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1291 /* Process GET_STATUS request */
1292 switch (setup_packet.mRequestType & USB_RECIP_MASK)
1294 case USB_RECIP_DEVICE:
1295 if (usb_send_device_status(w_index) < 0)
1297 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientDevice\n",
1299 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1302 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientDevice)\n",
1303 __func__, setup_packet.mRequestType);
1305 case USB_RECIP_INTERFACE:
1306 if (usb_send_interface_status(w_index) < 0)
1308 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientInterface\n",
1310 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1313 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientInterface)\n",
1314 __func__, setup_packet.mRequestType);
1316 case USB_RECIP_ENDPOINT:
1317 if (usb_send_ep_status(w_index) < 0)
1319 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1321 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1324 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientEndpoint)\n",
1325 __func__, setup_packet.mRequestType);
1328 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1330 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1335 static int usb_get_device_descriptor(int id)
1338 return -USB_NODEV_ERROR;
1340 usb_dev->device->bMaxPacketSize0 = USB_EP0_MAX_SIZE;
1341 __usb_ep_write(CTRL_ENP_IN, (const uint8_t *)usb_dev->device,
1342 usb_size(usb_dev->device->bLength,
1343 usb_le16_to_cpu(setup_packet.wLength)),
1344 usb_status_handler);
1349 * TODO: refactor this part to remove this temporary buffer.
1351 * It would be better to define all the USB descriptors in the right order and
1352 * send them as a contiguous buffer directly from the flash / rodata memory.
1354 #define USB_BUFSIZE (128)
1355 static uint8_t usb_cfg_buffer[USB_BUFSIZE];
1356 STATIC_ASSERT(USB_BUFSIZE < (1 << (sizeof(uint16_t) * 8)));
1358 static int usb_get_configuration_descriptor(int id)
1360 const UsbConfigDesc **config =
1361 (const UsbConfigDesc **)usb_dev->config;
1362 uint8_t *p = usb_cfg_buffer;
1365 /* TODO: support more than one configuration per device */
1366 if (UNLIKELY(id > 0))
1367 return -USB_NODEV_ERROR;
1369 for (i = 0; config[i]; i++)
1371 memcpy(p, config[i], config[i]->bLength);
1372 p += config[i]->bLength;
1374 if (UNLIKELY((p - usb_cfg_buffer) > USB_BUFSIZE))
1377 return -USB_BUF_OVERFLOW;
1380 ((UsbConfigDesc *)usb_cfg_buffer)->wTotalLength =
1381 usb_cpu_to_le16((uint16_t)(p - usb_cfg_buffer));
1382 __usb_ep_write(CTRL_ENP_IN,
1384 usb_size(p - usb_cfg_buffer,
1385 usb_le16_to_cpu(setup_packet.wLength)),
1386 usb_status_handler);
1390 static int usb_get_string_descriptor(unsigned int id)
1392 const UsbStringDesc *lang_str;
1393 unsigned int lang_id, str_id;
1394 uint16_t w_index_lo = usb_le16_to_cpu(setup_packet.wIndex) & 0x00ff;
1395 uint16_t w_index_hi = (usb_le16_to_cpu(setup_packet.wIndex) &
1398 ASSERT(usb_dev->strings != NULL);
1399 ASSERT(usb_dev->strings[0] != NULL);
1401 lang_str = usb_dev->strings[0];
1404 /* Find Language index */
1405 for (lang_id = 0; ; lang_id++)
1407 const UsbStringDesc *str =
1408 usb_dev->strings[lang_id];
1409 if (UNLIKELY(str == NULL))
1410 return -USB_NODEV_ERROR;
1411 if ((str->data[0] == w_index_lo) &&
1412 (str->data[1] == w_index_hi))
1415 /* Check buffer overflow to find string index */
1416 for (str_id = 0; str_id < id; str_id++)
1418 lang_str = usb_dev->strings[lang_id + 1 + str_id];
1419 if (lang_str == NULL)
1420 return -USB_NODEV_ERROR;
1423 __usb_ep_write(CTRL_ENP_IN,
1425 usb_size(lang_str->bLength,
1426 usb_le16_to_cpu(setup_packet.wLength)),
1427 usb_status_handler);
1431 static void usb_get_descriptor(void)
1433 uint16_t w_value_lo = usb_le16_to_cpu(setup_packet.wValue) & 0x00ff;
1434 uint16_t w_value_hi = (usb_le16_to_cpu(setup_packet.wValue) & 0xff00) >> 8;
1436 if (udc.state < USB_STATE_DEFAULT)
1438 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1444 LOG_INFO("%s: GET_DEVICE_DESCRIPTOR: id=%d, state=%d\n",
1448 if (usb_get_device_descriptor(w_value_lo) < 0)
1449 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1452 LOG_INFO("%s: GET_CONFIG_DESCRIPTOR: id=%d, state=%d\n",
1453 __func__, w_value_lo, udc.state);
1454 if (usb_get_configuration_descriptor(w_value_lo) < 0)
1455 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1458 LOG_INFO("%s: GET_STRING_DESCRIPTOR: id=%d, state=%d\n",
1459 __func__, w_value_lo, udc.state);
1460 if (usb_get_string_descriptor(w_value_lo) < 0)
1461 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1464 LOG_WARN("%s: GET_UNKNOWN_DESCRIPTOR: id=%d, state=%d\n",
1465 __func__, w_value_lo, udc.state);
1466 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1471 /* USB setup packet: class/vendor request handler */
1472 static void usb_event_handler(UsbDevice *dev)
1475 * TODO: get the appropriate usb_dev in function of the endpoint
1479 dev->event_cb(&setup_packet);
1482 /* USB setup packet: GET_DESCRIPTOR handler */
1483 static void usb_get_descriptor_handler(void)
1485 LOG_INFO("%s: GET_DESCRIPTOR: RECIP = %d\n",
1487 setup_packet.mRequestType & USB_RECIP_MASK);
1488 if ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1490 usb_get_descriptor();
1491 /* Getting descriptor for a device is a standard request */
1492 else if ((setup_packet.mRequestType & USB_DIR_MASK) == USB_DIR_IN)
1493 usb_event_handler(usb_dev);
1495 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1498 /* USB setup packet: SET_ADDRESS handler */
1499 static void usb_set_address_handler(void)
1501 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1502 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1503 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1505 LOG_INFO("%s: SET_ADDRESS: %d\n",
1506 __func__, usb_le16_to_cpu(setup_packet.wValue));
1507 if ((udc.state >= USB_STATE_DEFAULT) &&
1508 ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1509 USB_RECIP_DEVICE) &&
1510 (w_index == 0) && (w_length == 0) && (w_value < 128))
1511 usb_status_handler(CTRL_ENP_IN);
1513 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1516 /* USB setup packet: GET_CONFIGURATION handler */
1517 static void usb_get_config_handler(void)
1519 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1520 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1522 LOG_INFO("%s: GET_CONFIGURATION\n", __func__);
1523 if ((udc.state >= USB_STATE_ADDRESS) &&
1524 (w_value == 0) && (w_index == 0) && (w_value == 1))
1526 InData = udc.cfg_id;
1527 __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 1, usb_status_handler);
1530 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1533 static const UsbConfigDesc *usb_find_configuration(int num)
1535 const UsbConfigDesc *cfg;
1540 cfg = (const UsbConfigDesc *)usb_dev->config[i];
1543 if (cfg->bDescriptorType != USB_DT_CONFIG)
1545 if (cfg->bConfigurationValue == num)
1551 static int usb_set_config_state(uint32_t conf)
1553 const UsbConfigDesc *pCnfg;
1558 /* Find configuration descriptor */
1559 pCnfg = usb_find_configuration(conf);
1561 return -USB_NODEV_ERROR;
1563 /* Reset current configuration */
1564 usb_set_device_state(USB_STATE_ADDRESS);
1565 usb_dev->configured = false;
1568 /* Set Interface and Alternative Setting */
1570 /* Set self-powered state */
1571 if (pCnfg->bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1572 udc.feature |= STM32_UDC_FEATURE_SELFPOWERED;
1574 /* Configure all existing interfaces to alternative setting 0 */
1575 ASSERT(pCnfg->bNumInterfaces <= USB_MAX_INTERFACE);
1576 udc.interfaces = pCnfg->bNumInterfaces;
1577 for (i = 0; i < udc.interfaces; i++)
1579 usb_set_device_state(USB_STATE_CONFIGURED);
1580 usb_dev->configured = true;
1581 LOG_INFO("%s: device configured\n", __func__);
1585 usb_dev->configured = false;
1586 usb_set_device_state(USB_STATE_ADDRESS);
1591 /* USB setup packet: SET_CONFIGURATION handler */
1592 static void usb_set_config_handler(void)
1594 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1595 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1596 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1598 LOG_INFO("%s: SET_CONFIGURATION: %d\n",
1600 if ((udc.state >= USB_STATE_ADDRESS) &&
1601 (w_index == 0) && (w_length == 0) &&
1602 (usb_set_config_state(w_value & 0xff) == 0))
1603 usb_status_handler(CTRL_ENP_OUT);
1605 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1608 /* USB setup packet: standard request handler */
1609 static void usb_standard_request_handler(void)
1611 switch (setup_packet.bRequest)
1613 case USB_REQ_GET_STATUS:
1614 usb_get_status_handler();
1616 case USB_REQ_CLEAR_FEATURE:
1617 LOG_INFO("%s: bRequest=%d (CLEAR_FEATURE)\n",
1618 __func__, setup_packet.bRequest);
1620 case USB_REQ_SET_FEATURE:
1621 LOG_INFO("%s: bRequest=%d (SET_FEATURE)\n",
1622 __func__, setup_packet.bRequest);
1624 case USB_REQ_SET_ADDRESS:
1625 usb_set_address_handler();
1627 case USB_REQ_GET_DESCRIPTOR:
1628 usb_get_descriptor_handler();
1630 case USB_REQ_SET_DESCRIPTOR:
1631 LOG_INFO("%s: bRequest=%d (SET_DESCRIPTOR)\n",
1632 __func__, setup_packet.bRequest);
1634 case USB_REQ_GET_CONFIGURATION:
1635 usb_get_config_handler();
1637 case USB_REQ_SET_CONFIGURATION:
1638 usb_set_config_handler();
1640 case USB_REQ_GET_INTERFACE:
1641 LOG_INFO("%s: bRequest=%d (GET_INTERFACE)\n",
1642 __func__, setup_packet.bRequest);
1644 case USB_REQ_SET_INTERFACE:
1645 LOG_INFO("%s: bRequest=%d (SET_INTERFACE)\n",
1646 __func__, setup_packet.bRequest);
1648 case USB_REQ_SYNCH_FRAME:
1649 LOG_INFO("%s: bRequest=%d (SYNCH_FRAME)\n",
1650 __func__, setup_packet.bRequest);
1653 LOG_WARN("%s: bRequest=%d (Unknown)\n",
1654 __func__, setup_packet.bRequest);
1655 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1660 /* USB setup packet handler */
1661 static void usb_setup_handler(void)
1663 switch (setup_packet.mRequestType & USB_TYPE_MASK)
1666 case USB_TYPE_STANDARD:
1667 LOG_INFO("%s: bmRequestType=%02x (Standard)\n",
1668 __func__, setup_packet.mRequestType);
1669 usb_standard_request_handler();
1672 case USB_TYPE_CLASS:
1673 LOG_INFO("%s: bmRequestType=%02x (Class)\n",
1674 __func__, setup_packet.mRequestType);
1675 usb_event_handler(usb_dev);
1678 case USB_TYPE_VENDOR:
1679 LOG_INFO("%s: bmRequestType=%02x (Vendor)\n",
1680 __func__, setup_packet.mRequestType);
1681 usb_event_handler(usb_dev);
1683 case USB_TYPE_RESERVED:
1684 LOG_INFO("%s: bmRequestType=%02x (Reserved)\n",
1685 __func__, setup_packet.mRequestType);
1689 LOG_WARN("%s: bmRequestType=%02x (Unknown)\n",
1690 __func__, setup_packet.mRequestType);
1691 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1696 /* USB: low-level hardware initialization */
1697 static void usb_hw_reset(void)
1702 /* Initialize endpoint descriptors */
1703 for (i = 0; i < countof(ep_cnfg); i++)
1704 ep_cnfg[i].hw = NULL;
1706 /* Initialize USB memory */
1707 for (i = 0; i < countof(memory_buffer); i++)
1708 memory_buffer[i].Size = 0;
1709 usb->BTABLE = USB_BDT_OFFSET;
1712 /* Endpoint initialization */
1713 ret = usb_ep_configure(&USB_CtrlEpDescr0, true);
1714 if (UNLIKELY(ret < 0))
1716 LOG_WARN("%s: out of memory, cannot initialize EP0\n",
1720 ret = usb_ep_configure(&USB_CtrlEpDescr1, true);
1721 if (UNLIKELY(ret < 0))
1723 LOG_WARN("%s: out of memory, cannot initialize EP1\n",
1728 /* Set default address */
1731 /* Enable all the device interrupts */
1732 usb->CNTR = bmCTRM | bmRESETM | bmSOFM | bmERRM | bmPMAOVRM |
1736 /* Handle a correct transfer under ISR */
1737 static void usb_isr_correct_transfer(stm32_usb_irq_status_t interrupt)
1740 reg32_t *pReg = (reg32_t *)&usb->EP0R;
1742 /* Find corresponding EP */
1743 pReg += interrupt.EP_ID;
1744 EP = (int)(((*pReg & 0x0f) << 1) + (interrupt.DIR ? 0 : 1));
1745 ep_cnfg[EP].avail_data = 1;
1747 ASSERT(ep_cnfg[EP].hw);
1750 ep_ctrl_clr_ctr_tx(ep_cnfg[EP].hw);
1752 ep_ctrl_clr_ctr_rx(ep_cnfg[EP].hw);
1753 if (EP == CTRL_ENP_OUT)
1755 /* Determinate type of packet (only for control EP) */
1756 bool SetupPacket = ep_ctrl_get_setup(ep_cnfg[CTRL_ENP_OUT].hw);
1760 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
1761 /* init IO to receive Setup packet */
1762 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1763 __usb_ep_read(CTRL_ENP_OUT, &setup_packet,
1764 sizeof(setup_packet), NULL);
1766 /* reset EP IO ctrl */
1767 if (setup_packet.mRequestType & USB_DIR_IN)
1768 usb_status_handler(CTRL_ENP_OUT);
1769 usb_setup_handler();
1770 if (ep_cnfg[CTRL_ENP_OUT].status == STALLED)
1771 usb_ep_set_stall_ctrl();
1775 if (ep_cnfg[CTRL_ENP_OUT].complete &&
1776 setup_packet.mRequestType & USB_DIR_IN)
1777 ep_cnfg[CTRL_ENP_OUT].complete(CTRL_ENP_OUT);
1782 else if (EP == CTRL_ENP_IN)
1784 if (ep_cnfg[CTRL_ENP_IN].complete &&
1785 !(setup_packet.mRequestType & USB_DIR_IN))
1786 ep_cnfg[CTRL_ENP_IN].complete(CTRL_ENP_IN);
1795 /* USB: interrupt service routine */
1796 static void usb_isr(void)
1798 stm32_usb_irq_status_t interrupt;
1800 /* Get masked interrupt flags */
1801 interrupt.status = usb->ISTR;
1802 interrupt.status &= usb->CNTR | 0x1f;
1804 if (interrupt.PMAOVR)
1806 LOG_WARN("%s: DMA overrun / underrun\n", __func__);
1807 usb->ISTR = ~bmPMAOVRM;
1811 LOG_WARN("%s: engine error\n", __func__);
1812 usb->ISTR = ~bmERRM;
1814 if (interrupt.RESET)
1816 LOG_INFO("%s: device reset\n", __func__);
1817 usb->ISTR = ~bmRESETM;
1819 usb_set_device_state(USB_STATE_DEFAULT);
1825 * XXX: disable logging of frame interrupts (too much noise!)
1827 uint16_t frame_nr = usb->FNR & 0x0fff;
1828 LOG_INFO("%s: frame %#x\n", __func__, frame_nr);
1830 usb->ISTR = ~bmSOFM;
1834 LOG_INFO("%s: wake-up\n", __func__);
1835 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1840 LOG_INFO("%s: suspend\n", __func__);
1842 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1846 LOG_INFO("%s: expected frame\n", __func__);
1847 usb->ISTR = ~bmESOFM;
1851 usb_isr_correct_transfer(interrupt);
1855 /* USB: hardware initialization */
1856 static void usb_hw_init(void)
1858 /* Enable clocking on the required GPIO pins */
1859 RCC->APB2ENR |= RCC_APB2_GPIOA | RCC_APB2_GPIOC;
1861 /* Make sure that the CAN controller is disabled and held in reset */
1862 RCC->APB1ENR &= ~RCC_APB1_CAN;
1864 /* Configure USB_DM and USB_DP to work as USB lines */
1865 stm32_gpioPinConfig((struct stm32_gpio *)GPIOA_BASE,
1866 USB_DM_PIN | USB_DP_PIN,
1867 GPIO_MODE_AF_PP, GPIO_SPEED_50MHZ);
1868 /* Configure USB_DISC to work as USB disconnect */
1869 stm32_gpioPinConfig((struct stm32_gpio *)GPIOC_BASE,
1871 GPIO_MODE_OUT_PP, GPIO_SPEED_50MHZ);
1872 stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE,
1875 /* Ensure the USB clock is disabled before setting the prescaler */
1876 RCC->APB1ENR &= ~RCC_APB1_USB;
1878 /* Configure USB clock (48MHz) */
1879 *CFGR_USBPRE_BB &= ~RCC_USBCLK_PLLCLK_1DIV5;
1881 /* Activate USB clock */
1882 RCC->APB1ENR |= RCC_APB1_USB;
1884 /* Force USB reset and disable USB interrupts */
1888 /* Issue a USB reset */
1891 /* Clear spurious pending interrupt */
1894 /* Register interrupt handler */
1895 sysirq_setHandler(USB_LP_CAN_RX0_IRQHANDLER, usb_isr);
1897 /* Software connection enable */
1901 /* Initialize the USB controller */
1902 static void usb_init(void)
1904 udc.state = USB_STATE_NOTATTACHED;
1910 /* Register an upper layer USB device into the driver */
1911 int usb_deviceRegister(UsbDevice *dev)
1918 while (!usb_dev->configured)