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];
96 STATIC_ASSERT(EP_MAX_NUM <= EP_MAX_HW_NUM);
98 /* USB EP0 control descriptor */
99 static const UsbEndpointDesc USB_CtrlEpDescr0 =
101 .bLength = sizeof(USB_CtrlEpDescr0),
102 .bDescriptorType = USB_DT_ENDPOINT,
103 .bEndpointAddress = USB_DIR_OUT | 0,
104 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
105 .wMaxPacketSize = USB_EP0_MAX_SIZE,
109 /* USB EP1 control descriptor */
110 static const UsbEndpointDesc USB_CtrlEpDescr1 =
112 .bLength = sizeof(USB_CtrlEpDescr1),
113 .bDescriptorType = USB_DT_ENDPOINT,
114 .bEndpointAddress = USB_DIR_IN | 0,
115 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
116 .wMaxPacketSize = USB_EP0_MAX_SIZE,
120 /* USB setup packet */
121 static UsbCtrlRequest setup_packet;
123 /* USB device controller: max supported interfaces */
124 #define USB_MAX_INTERFACE 1
126 /* USB device controller features */
127 #define STM32_UDC_FEATURE_SELFPOWERED BV(0)
128 #define STM32_UDC_FEATURE_REMOTE_WAKEUP BV(1)
130 /* Hardware-specific USB device controller structure */
131 typedef struct stm32_udc
135 const UsbConfigDesc *cfg;
137 uint32_t alt[USB_MAX_INTERFACE];
140 } PACKED stm32_udc_t;
142 /* Hardware-specific USB Device Controller */
143 static stm32_udc_t udc;
145 /* Generic USB Device Controller structure */
146 static UsbDevice *usb_dev;
148 /* USB packet memory management: list of allocated chunks */
149 static stm32_UsbMemSlot *mem_use;
151 /* USB packet memory management: memory buffer metadata */
152 static stm32_UsbMemSlot memory_buffer[EP_MAX_NUM];
154 /* Endpoint TX and RX buffers */
156 /* XXX: use the empty cond section to silent a buggy doxygen warning */
157 static bool rx_done, tx_done;
158 static size_t rx_size, tx_size;
160 #define EP_BUFFER_SIZE _MIN(CONFIG_USB_BUFSIZE, USB_XFER_MAX_SIZE)
161 STATIC_ASSERT(!(EP_BUFFER_SIZE & 0x03));
163 static uint8_t ep_buffer[EP_MAX_NUM][EP_BUFFER_SIZE] ALIGNED(4);
166 /* Allocate a free block of the packet memory */
167 static stm32_UsbMemSlot *usb_malloc(void)
171 for (i = 0; i < countof(memory_buffer); i++)
172 if (memory_buffer[i].Size == 0)
173 return &memory_buffer[i];
177 /* Release a block of the packet memory */
178 static void usb_free(stm32_UsbMemSlot *pPntr)
183 /* Allocate a free chunk of the packet memory (inside a block) */
184 static bool usb_alloc_buffer(uint16_t *pOffset, uint32_t *size,
187 stm32_UsbMemSlot *mem = mem_use,
188 *memNext, *mem_useNew;
189 uint32_t max_size = *size;
192 * Packet size alignment:
193 * - fine-granularity allocation: size alignment by 2;
194 * - coarse-granularity allocation: size alignment by 32.
197 max_size = ALIGN_UP(max_size, 2);
199 max_size = ALIGN_UP(max_size, 32);
201 * Finding free memory chunks from the allocated blocks of the USB
207 /* Offset alignment by 4 */
208 *pOffset = ALIGN_UP(mem->Start + mem->Size, 4);
210 if ((mem->next == NULL) ||
212 *pOffset + max_size))
216 /* Check for out-of-memory condition */
217 if (UNLIKELY((*pOffset + max_size) >= USB_BDT_OFFSET))
220 * Allocate a new memory block, next to the last allocated block.
222 mem_useNew = usb_malloc();
223 if (UNLIKELY(mem_useNew == NULL))
225 /* Insert the block to the list of allocated blocks */
228 mem_use = mem_useNew;
229 mem_use->next = NULL;
233 mem_useNew->next = mem->next;
234 mem->next = mem_useNew;
236 /* Update block's metadata */
237 mem_useNew->ep_addr = EndPoint;
238 mem_useNew->Start = *pOffset;
239 mem_useNew->Size = max_size;
246 /* Release a chunk of the packet memory (inside a block) */
247 static void usb_free_buffer(int EndPoint)
249 stm32_UsbMemSlot *mem, *memPrev = NULL;
254 if (mem->ep_addr == EndPoint)
256 if (UNLIKELY(memPrev == NULL))
258 /* Free the first element of the list */
259 mem_use = mem_use->next;
264 memPrev->next = mem->next;
273 /*-------------------------------------------------------------------------*/
275 /* Connect USB controller */
276 static void usb_connect(void)
278 stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE, 1 << 11, 0);
281 /* Set USB device address */
282 static void usb_set_address(uint32_t addr)
284 usb->DADDR = addr | 0x80;
287 /* Suspend USB controller */
288 static void usb_suspend(void)
290 usb->CNTR |= bmFSUSP | bmLPMODE;
293 /* Resume USB controller */
294 static void usb_resume(void)
296 uint32_t line_status;
298 line_status = usb->FNR & 0xc000;
301 /* check for noise and eventually return to sleep */
302 if (line_status == 0xc000)
305 usb->CNTR &= ~(bmFSUSP | bmLPMODE);
308 /* Convert logical EP address to physical EP address */
309 static int usb_ep_logical_to_hw(uint8_t ep_addr)
311 int addr = (ep_addr & 0x0f) << 1;
312 return (ep_addr & 0x80) ? addr + 1 : addr;
316 static void ep_ctrl_set_ea(reg32_t *reg, uint32_t val)
319 val |= *reg & 0x0700;
320 val |= USB_CTRL_CLEAR_ONLY_MASK;
324 /* Get EP IN status */
325 static uint32_t ep_ctrl_get_stat_tx(reg32_t *reg)
327 return (*reg & (0x3UL << 4)) >> 4;
330 /* Set EP IN state */
331 static void ep_ctrl_set_stat_tx(reg32_t *reg, stm32_UsbEpState val)
337 * The EP can change state between read and write operations from VALID
338 * to NAK and result of set operation will be invalid.
340 for (i = 0; i < 2; i++)
342 if (ep_ctrl_get_stat_tx(reg) == val)
347 state |= USB_CTRL_CLEAR_ONLY_MASK;
348 /* Clear the toggle bits without STAT_TX (4,5) */
354 /* Set EP DTOG_TX bit (IN) */
355 static void ep_ctrl_set_dtog_tx(reg32_t *reg, uint32_t val)
357 val = val ? (*reg ^ (1UL << 6)) : *reg;
358 /* Clear the toggle bits without DTOG_TX (6) */
360 val |= USB_CTRL_CLEAR_ONLY_MASK;
364 /* Clear EP CTR_TX bit (IN) */
365 static void ep_ctrl_clr_ctr_tx(reg32_t *reg)
369 val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 7);
375 /* Clear EP CTR_RX bit (OUT) */
376 static void ep_ctrl_clr_ctr_rx(reg32_t *reg)
379 val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 15);
385 /* Set EP KIND bit */
386 static void ep_ctrl_set_ep_kind(reg32_t *reg, uint32_t val)
388 val = val ? (1UL << 8) : 0;
389 val |= *reg & ~(USB_CTRL_TOGGLE_MASK | (1UL << 8));
390 val |= USB_CTRL_CLEAR_ONLY_MASK;
395 static int ep_ctrl_set_ep_type(reg32_t *reg, uint8_t val)
399 if (UNLIKELY(val >= EP_TYPE_MAX))
402 return USB_INVAL_ERROR;
406 type |= *reg & ~(USB_CTRL_TOGGLE_MASK | (0x3UL << 9));
407 type |= USB_CTRL_CLEAR_ONLY_MASK;
413 /* Get EP STAT_RX (OUT) */
414 static uint32_t ep_ctrl_get_stat_rx(reg32_t *reg)
416 uint32_t val = *reg & (0x3UL << 12);
420 /* Set EP STAT_RX (OUT) */
421 static void ep_ctrl_set_stat_rx(reg32_t *reg, stm32_UsbEpState val)
427 * The EP can change state between read and write operations from VALID
428 * to NAK and result of set operation will be invalid.
430 for (i = 0; i < 2; i++)
432 if (ep_ctrl_get_stat_rx(reg) == val)
437 state |= USB_CTRL_CLEAR_ONLY_MASK;
438 /* Clear the toggle bits without STAT_RX (12,13) */
444 /* Set DTOG_RX bit */
445 static void ep_ctrl_set_dtog_rx(reg32_t *reg, uint32_t val)
447 val = val ? (*reg ^ (1UL << 14)) : *reg;
448 /* Clear the toggle bits without DTOG_RX (14) */
450 val |= USB_CTRL_CLEAR_ONLY_MASK;
454 /* Get EP SETUP bit */
455 static uint32_t ep_ctrl_get_setup(reg32_t *reg)
457 uint32_t val = *reg & (1UL << 11);
461 /* Core endpoint I/O function */
462 static void __usb_ep_io(int EP)
464 ssize_t Count, CountHold, Offset;
465 uint32_t *pDst, *pSrc, Data;
466 stm32_UsbEp *epd = &ep_cnfg[EP];
468 if (UNLIKELY(epd->hw == NULL))
470 LOG_ERR("%s: invalid endpoint (EP%d-%s)\n",
473 (EP & 0x01) ? "IN" : "OUT");
477 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
483 Count = epd->size - epd->offset;
484 while (epd->avail_data)
486 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
490 epd->status = BEGIN_SERVICED;
492 if ((epd->flags & STM32_USB_EP_ZERO_PACKET) &&
493 (Count == epd->max_size))
494 epd->flags |= STM32_USB_EP_ZERO_PACKET |
495 STM32_USB_EP_ZERO_POSSIBLE;
497 CountHold = Count = MIN(Count, epd->max_size);
499 epd->flags |= STM32_USB_EP_ZERO_PACKET;
500 Offset = epd->offset;
501 epd->offset += Count;
504 case USB_ENDPOINT_XFER_CONTROL:
505 case USB_ENDPOINT_XFER_INT:
506 pDst = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_TX_OFFSET));
508 case USB_ENDPOINT_XFER_BULK:
509 pDst = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_TX_OFFSET));
511 case USB_ENDPOINT_XFER_ISOC:
512 LOG_ERR("%s: isochronous transfer not supported\n",
514 /* Fallback to default */
520 /* Write data to packet memory buffer */
523 Data = *(epd->write_buffer + Offset++);
526 Data |= (uint32_t)(*(epd->write_buffer + Offset++)) << 8;
532 EP_DTB_WRITE(EP >> 1, COUNT_TX_OFFSET, CountHold);
533 ep_ctrl_set_stat_tx(epd->hw, EP_VALID);
535 --ep_cnfg[EP].avail_data;
536 Count = epd->size - epd->offset;
538 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
540 epd->status = COMPLETE;
541 /* call callback function */
549 while (epd->avail_data)
551 /* Get data size and buffer pointer */
554 case USB_ENDPOINT_XFER_CONTROL:
555 case USB_ENDPOINT_XFER_INT:
556 /* Get received bytes number */
557 Count = EP_DTB_READ(EP >> 1, COUNT_RX_OFFSET) & 0x3FF;
558 /* Get address of the USB packet buffer for corresponding EP */
559 pSrc = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_RX_OFFSET));
561 case USB_ENDPOINT_XFER_BULK:
562 /* Get received bytes number */
563 Count = EP_DTB_READ(EP >> 1, COUNT_RX_OFFSET) & 0x3FF;
564 /* Get address of the USB packet buffer for corresponding EP */
565 pSrc = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_RX_OFFSET));
567 case USB_ENDPOINT_XFER_ISOC:
568 LOG_ERR("%s: isochronous transfer not supported\n",
570 /* Fallback to default */
576 if (Count > (epd->size - epd->offset))
578 epd->status = BUFFER_OVERRUN;
579 epd->size = ep_cnfg[EP].offset;
582 else if (Count < ep_cnfg[EP].max_size)
584 epd->status = BUFFER_UNDERRUN;
585 epd->size = ep_cnfg[EP].offset + Count;
588 epd->status = BEGIN_SERVICED;
590 Offset = epd->offset;
591 epd->offset += Count;
593 /* Read data from packet memory buffer */
597 *(epd->read_buffer + Offset++) = Data;
601 *(epd->read_buffer + Offset++) = Data;
606 ep_ctrl_set_stat_rx(epd->hw, EP_VALID);
608 --ep_cnfg[EP].avail_data;
610 if (*epd->hw & (1UL << 11))
612 ep_cnfg[EP].status = SETUP_OVERWRITE;
615 if (!(Count = (epd->size - epd->offset)))
617 epd->status = COMPLETE;
621 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
623 /* call callback function */
631 * Return the lower value from Host expected size and size and set a flag
632 * STM32_USB_EP_ZERO_POSSIBLE when size is lower that host expected size.
634 static size_t usb_size(size_t size, size_t host_size)
636 if (size < host_size)
638 ep_cnfg[CTRL_ENP_IN].flags |= STM32_USB_EP_ZERO_POSSIBLE;
644 /* Configure an EP descriptor before performing a I/O operation */
645 #define USB_EP_IO(__EP, __op, __buf, __size, __complete) \
648 stm32_UsbIoStatus ret; \
650 /* Fill EP descriptor */ \
651 IRQ_SAVE_DISABLE(flags); \
654 ep_cnfg[__EP].status = NOT_READY; \
655 ep_cnfg[__EP].complete = NULL; \
659 if (ep_cnfg[__EP].status == BEGIN_SERVICED) \
665 * NOTE: the write_buffer and read_buffer are actually the \
666 * same location in memory (it's a union). \
668 * We have to do this trick to silent a build warning by \
669 * casting the I/O buffer to (void *) or (const void *). \
671 ep_cnfg[__EP].__op ## _buffer = __buf; \
672 ep_cnfg[__EP].offset = 0; \
673 ep_cnfg[__EP].size = __size; \
674 ep_cnfg[__EP].complete = __complete; \
676 ep_cnfg[__EP].flags = STM32_USB_EP_ZERO_PACKET; \
678 ep_cnfg[__EP].flags = 0; \
679 ep_cnfg[__EP].status = NO_SERVICED; \
681 /* Perform the I/O operation */ \
684 ret = ep_cnfg[__EP].status; \
686 IRQ_RESTORE(flags); \
690 /* Configure and endponint and perform a read operation */
691 static stm32_UsbIoStatus
692 __usb_ep_read(int ep, void *buffer, ssize_t size, void (*complete)(int))
694 if (UNLIKELY((ep >= EP_MAX_NUM) || (ep & 0x01)))
696 LOG_ERR("%s: invalid EP number %d\n", __func__, ep);
700 if (UNLIKELY((size_t)buffer & 0x03))
702 LOG_ERR("%s: unaligned buffer @ %p\n", __func__, buffer);
706 return USB_EP_IO(ep, read, buffer, size, complete);
709 /* Configure and endponint and perform a write operation */
710 static stm32_UsbIoStatus
711 __usb_ep_write(int ep, const void *buffer, ssize_t size, void (*complete)(int))
713 if (UNLIKELY((ep >= EP_MAX_NUM) || !(ep & 0x01)))
715 LOG_ERR("%s: invalid EP number %d\n", __func__, ep);
719 if (UNLIKELY((size_t)buffer & 0x03))
721 LOG_ERR("%s: unaligned buffer @ %p\n", __func__, buffer);
725 return USB_EP_IO(ep, write, buffer, size, complete);
728 static void usb_ep_low_level_config(int ep, uint16_t offset, uint16_t size)
730 stm32_UsbEp *epc = &ep_cnfg[ep];
736 ep_ctrl_set_stat_tx(epc->hw, EP_DISABLED);
737 /* Clear Tx toggle */
738 ep_ctrl_set_dtog_tx(epc->hw, 0);
739 /* Clear Correct Transfer for transmission flag */
740 ep_ctrl_clr_ctr_tx(epc->hw);
742 /* Update EP description table */
743 EP_DTB_WRITE(ep >> 1, ADDR_TX_OFFSET, offset);
744 EP_DTB_WRITE(ep >> 1, COUNT_TX_OFFSET, 0);
749 uint16_t rx_count = 0;
752 ep_ctrl_set_stat_rx(epc->hw, EP_DISABLED);
753 /* Clear Rx toggle */
754 ep_ctrl_set_dtog_rx(epc->hw, 0);
755 /* Clear Correct Transfer for reception flag */
756 ep_ctrl_clr_ctr_rx(epc->hw);
757 /* Descriptor block size field */
758 rx_count |= (size > 62) << 15;
759 /* Descriptor number of blocks field */
760 rx_count |= (((size > 62) ? (size >> 5) - 1 : size >> 1) &
762 /* Update EP description table */
763 EP_DTB_WRITE(ep >> 1, ADDR_RX_OFFSET, offset);
764 EP_DTB_WRITE(ep >> 1, COUNT_RX_OFFSET, rx_count);
768 /* Enable/Disable an endpoint */
769 static int usb_ep_configure(const UsbEndpointDesc *epd, bool enable)
777 EP = usb_ep_logical_to_hw(epd->bEndpointAddress);
778 ep_hw = &ep_cnfg[EP];
783 * Allocate packet memory for EP buffer/s calculate actual size
784 * only for the OUT EPs.
786 size = epd->wMaxPacketSize;
787 if (!usb_alloc_buffer(&Offset, &size, EP))
788 return -USB_MEMORY_FULL;
791 ep_hw->status = NOT_READY;
795 /* Set endpoint type */
796 ep_hw->type = usb_endpointType(epd);
797 /* Init EP max packet size */
798 ep_hw->max_size = epd->wMaxPacketSize;
801 ep_hw->avail_data = 1;
803 ep_hw->avail_data = 0;
804 hw = (reg32_t *)&usb->EP0R;
808 ep_ctrl_set_ea(hw, EP >> 1);
810 LOG_INFO("%s: EP%d-%s configured\n",
811 __func__, EP >> 1, EP & 1 ? "IN" : "OUT");
813 /* Low-level endpoint configuration */
814 usb_ep_low_level_config(EP, Offset, size);
816 /* Set EP Kind & enable */
819 case USB_ENDPOINT_XFER_CONTROL:
820 LOG_INFO("EP%d: CONTROL IN\n", EP >> 1);
821 ep_ctrl_set_ep_type(hw, EP_CTRL);
822 ep_ctrl_set_ep_kind(hw, 0);
824 case USB_ENDPOINT_XFER_INT:
825 LOG_INFO("EP%d: INTERRUPT IN\n", EP >> 1);
826 ep_ctrl_set_ep_type(hw, EP_INTERRUPT);
827 ep_ctrl_set_ep_kind(hw, 0);
829 case USB_ENDPOINT_XFER_BULK:
830 LOG_INFO("EP%d: BULK IN\n", EP >> 1);
831 ep_ctrl_set_ep_type(hw, EP_BULK);
832 ep_ctrl_set_ep_kind(hw, 0);
834 case USB_ENDPOINT_XFER_ISOC:
835 LOG_ERR("EP%d: ISOCHRONOUS IN: not supported\n", EP >> 1);
836 /* Fallback to default */
839 return -USB_NODEV_ERROR;
844 ep_ctrl_set_stat_tx(hw, EP_NAK);
845 /* Clear Correct Transfer for transmission flag */
846 ep_ctrl_clr_ctr_tx(hw);
851 ep_ctrl_set_stat_rx(hw, EP_VALID);
854 else if (ep_cnfg[EP].hw)
856 hw = (reg32_t *)&usb->EP0R;
863 ep_ctrl_set_stat_tx(hw, EP_DISABLED);
864 /* Clear Correct Transfer for reception flag */
865 ep_ctrl_clr_ctr_tx(hw);
871 ep_ctrl_set_stat_rx(hw, EP_DISABLED);
872 /* Clear Correct Transfer for reception flag */
873 ep_ctrl_clr_ctr_rx(hw);
877 ep_cnfg[EP].hw = NULL;
882 /* Get EP stall/unstall */
883 static int usb_ep_get_stall(int EP, bool *pStall)
885 if (ep_cnfg[EP].hw == NULL)
886 return -USB_NODEV_ERROR;
888 *pStall = (EP & 0x01) ?
889 (ep_ctrl_get_stat_tx(ep_cnfg[EP].hw) == EP_STALL): /* IN EP */
890 (ep_ctrl_get_stat_rx(ep_cnfg[EP].hw) == EP_STALL); /* OUT EP */
895 /* Set EP stall/unstall */
896 static int usb_ep_set_stall(int EP, bool Stall)
898 if (ep_cnfg[EP].hw == NULL)
899 return -USB_NODEV_ERROR;
903 ep_cnfg[EP].status = STALLED;
907 ep_ctrl_set_stat_tx(ep_cnfg[EP].hw, EP_STALL);
908 ep_cnfg[EP].avail_data = 1;
913 ep_ctrl_set_stat_rx(ep_cnfg[EP].hw, EP_STALL);
914 ep_cnfg[EP].avail_data = 0;
919 ep_cnfg[EP].status = NOT_READY;
923 ep_cnfg[EP].avail_data = 1;
924 /* reset Data Toggle bit */
925 ep_ctrl_set_dtog_tx(ep_cnfg[EP].hw, 0);
926 ep_ctrl_set_stat_tx(ep_cnfg[EP].hw, EP_NAK);
931 ep_cnfg[EP].avail_data = 0;
932 /* reset Data Toggle bit */
933 ep_ctrl_set_dtog_rx(ep_cnfg[EP].hw, 0);
934 ep_ctrl_set_stat_rx(ep_cnfg[EP].hw, EP_VALID);
940 /* Stall both directions of the control EP */
941 static void usb_ep_set_stall_ctrl(void)
943 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
944 ep_cnfg[CTRL_ENP_IN].status = STALLED;
945 ep_cnfg[CTRL_ENP_OUT].avail_data = 0;
946 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
948 usb_ep_set_stall(CTRL_ENP_IN, true);
949 usb_ep_set_stall(CTRL_ENP_OUT, true);
953 * Find the position of an interface descriptor inside the configuration
956 static int usb_find_interface(uint32_t num, uint32_t alt)
958 const UsbInterfaceDesc *id;
963 /* TODO: support more than one configuration per device */
964 id = (const UsbInterfaceDesc *)usb_dev->config[i];
967 if (id->bDescriptorType != USB_DT_INTERFACE)
969 if ((id->bInterfaceNumber == num) &&
970 (id->bAlternateSetting == alt))
973 return -USB_NODEV_ERROR;
977 * Configure/deconfigure EPs of a certain interface.
980 usb_configure_ep_interface(unsigned int num, unsigned int alt, bool enable)
982 const UsbEndpointDesc *epd;
986 * Find the position of the interface descriptor (inside the
987 * configuration descriptor).
989 start = usb_find_interface(num, alt);
992 LOG_ERR("%s: interface (%u,%u) not found\n",
997 * Cycle over endpoint descriptors.
999 * NOTE: the first endpoint descriptor is placed next to the interface
1000 * descriptor, so we need to add +1 to the position of the interface
1001 * descriptor to find it.
1003 for (i = start + 1; ; i++)
1005 epd = (const UsbEndpointDesc *)usb_dev->config[i];
1006 if ((epd == NULL) || (epd->bDescriptorType == USB_DT_INTERFACE))
1008 if (epd->bDescriptorType != USB_DT_ENDPOINT)
1010 if (UNLIKELY(usb_ep_configure(epd, enable) < 0))
1012 LOG_ERR("%s: out of memory, can't initialize EP\n",
1019 /* Set device state */
1020 static void usb_set_device_state(int state)
1024 LOG_INFO("%s: new state %d\n", __func__, state);
1026 if (udc.state == USB_STATE_CONFIGURED)
1028 /* Deconfigure device */
1029 for (i = 0; i < udc.interfaces; ++i)
1030 usb_configure_ep_interface(i,
1035 case USB_STATE_ATTACHED:
1036 case USB_STATE_POWERED:
1037 case USB_STATE_DEFAULT:
1039 usb_dev->configured = false;
1040 udc.address = udc.cfg_id = 0;
1042 case USB_STATE_ADDRESS:
1045 case USB_STATE_CONFIGURED:
1046 /* Configure device */
1047 for (i = 0; i < udc.interfaces; ++i)
1048 usb_configure_ep_interface(i,
1052 /* Unknown state: disconnected or connection in progress */
1053 usb_dev->configured = false;
1061 /* Setup packet: set address status phase end handler */
1062 static void usb_add_status_handler_end(UNUSED_ARG(int, EP))
1066 w_value = usb_le16_to_cpu(setup_packet.wValue);
1067 udc.address = w_value & 0xff;
1068 usb_set_address(udc.address);
1071 usb_set_device_state(USB_STATE_ADDRESS);
1073 usb_set_device_state(USB_STATE_DEFAULT);
1075 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1076 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1079 /* Prepare status phase */
1080 static void usb_status_phase(bool in)
1083 __usb_ep_write(CTRL_ENP_IN, NULL, 0, NULL);
1086 /* Setup packet: status phase end handler */
1087 static void usb_status_handler_end(UNUSED_ARG(int, EP))
1089 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1090 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1093 /* Address status handler */
1094 static void usb_status_handler(UNUSED_ARG(int, EP))
1096 if (setup_packet.mRequestType & USB_DIR_IN)
1098 usb_status_phase(false);
1099 ep_cnfg[CTRL_ENP_OUT].complete = usb_status_handler_end;
1103 usb_status_phase(true);
1104 ep_cnfg[CTRL_ENP_IN].complete =
1105 (setup_packet.bRequest == USB_REQ_SET_ADDRESS) ?
1106 usb_add_status_handler_end :
1107 usb_status_handler_end;
1111 static void usb_endpointRead_complete(int ep)
1113 if (UNLIKELY(ep >= EP_MAX_NUM))
1118 ASSERT(!(ep & 0x01));
1121 rx_size = ep_cnfg[ep].size;
1124 ssize_t usb_endpointRead(int ep, void *buffer, ssize_t size)
1126 int ep_num = usb_ep_logical_to_hw(ep);
1127 ssize_t max_size = sizeof(ep_buffer[ep_num]);
1129 /* Non-blocking read for EP0 */
1130 if (ep_num == CTRL_ENP_OUT)
1132 size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
1133 if (UNLIKELY(size > max_size))
1135 LOG_ERR("%s: ep_buffer exceeded, try to enlarge CONFIG_USB_BUFSIZE\n",
1138 return -USB_BUF_OVERFLOW;
1141 usb_status_handler(ep_num);
1144 __usb_ep_read(ep_num, ep_buffer[ep_num], size,
1145 usb_status_handler);
1146 memcpy(buffer, ep_buffer[ep_num], size);
1150 if (UNLIKELY(!size))
1152 size = MIN(size, max_size);
1157 __usb_ep_read(ep_num, ep_buffer[ep_num], size,
1158 usb_endpointRead_complete);
1161 memcpy(buffer, ep_buffer[ep_num], rx_size);
1166 static void usb_endpointWrite_complete(int ep)
1168 if (UNLIKELY(ep >= EP_MAX_NUM))
1176 tx_size = ep_cnfg[ep].size;
1179 ssize_t usb_endpointWrite(int ep, const void *buffer, ssize_t size)
1181 int ep_num = usb_ep_logical_to_hw(ep);
1182 ssize_t max_size = sizeof(ep_buffer[ep_num]);
1184 /* Non-blocking write for EP0 */
1185 if (ep_num == CTRL_ENP_IN)
1187 size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
1188 if (UNLIKELY(size > max_size))
1190 LOG_ERR("%s: ep_buffer exceeded, try to enlarge CONFIG_USB_BUFSIZE\n",
1193 return -USB_BUF_OVERFLOW;
1196 usb_status_handler(ep_num);
1199 memcpy(ep_buffer[ep_num], buffer, size);
1200 __usb_ep_write(ep_num, ep_buffer[ep_num], size,
1201 usb_status_handler);
1205 if (UNLIKELY(!size))
1207 size = MIN(size, max_size);
1211 /* Blocking write */
1212 memcpy(ep_buffer[ep_num], buffer, size);
1213 __usb_ep_write(ep_num, ep_buffer[ep_num], size,
1214 usb_endpointWrite_complete);
1221 /* Global variable to handle the following non-blocking I/O operations */
1222 static uint32_t InData;
1224 /* Get device status */
1225 static int usb_send_device_status(uint16_t index)
1228 return -USB_NODEV_ERROR;
1230 InData = ((uint32_t)udc.feature) & 0xff;
1231 __usb_ep_write(CTRL_ENP_IN,
1232 (uint8_t *)&InData, sizeof(uint16_t),
1233 usb_status_handler);
1237 /* Get interface status */
1238 static int usb_send_interface_status(UNUSED_ARG(uint16_t, index))
1241 __usb_ep_write(CTRL_ENP_IN,
1242 (uint8_t *)&InData, sizeof(uint16_t),
1243 usb_status_handler);
1247 /* Get endpoint status */
1248 static int usb_send_ep_status(uint16_t index)
1250 if ((index & 0x7F) > 16)
1251 return -USB_NODEV_ERROR;
1254 usb_ep_get_stall(usb_ep_logical_to_hw(index), (bool *)&InData);
1255 __usb_ep_write(CTRL_ENP_IN,
1256 (uint8_t *)&InData, sizeof(uint16_t),
1257 usb_status_handler);
1261 /* USB setup packet: GET_STATUS request handler */
1262 static void usb_get_status_handler(void)
1264 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1265 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1266 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1268 /* GET_STATUS sanity checks */
1269 if (udc.state < USB_STATE_ADDRESS)
1271 LOG_WARN("%s: bad GET_STATUS request (State=%02x)\n",
1272 __func__, udc.state);
1273 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1278 LOG_WARN("%s: bad GET_STATUS request (wLength.Word=%02x)\n",
1279 __func__, w_length);
1280 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1283 if (!(setup_packet.mRequestType & USB_DIR_IN))
1285 LOG_WARN("%s: bad GET_STATUS request (mRequestType=%02x)\n",
1286 __func__, setup_packet.mRequestType);
1287 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1292 LOG_WARN("%s: bad GET_STATUS request (wValue=%02x)\n",
1294 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1298 /* Process GET_STATUS request */
1299 switch (setup_packet.mRequestType & USB_RECIP_MASK)
1301 case USB_RECIP_DEVICE:
1302 if (usb_send_device_status(w_index) < 0)
1304 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientDevice\n",
1306 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1309 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientDevice)\n",
1310 __func__, setup_packet.mRequestType);
1312 case USB_RECIP_INTERFACE:
1313 if (usb_send_interface_status(w_index) < 0)
1315 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientInterface\n",
1317 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1320 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientInterface)\n",
1321 __func__, setup_packet.mRequestType);
1323 case USB_RECIP_ENDPOINT:
1324 if (usb_send_ep_status(w_index) < 0)
1326 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1328 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1331 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientEndpoint)\n",
1332 __func__, setup_packet.mRequestType);
1335 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1337 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1342 static int usb_get_device_descriptor(int id)
1345 return -USB_NODEV_ERROR;
1347 usb_dev->device->bMaxPacketSize0 = USB_EP0_MAX_SIZE;
1348 __usb_ep_write(CTRL_ENP_IN, (const uint8_t *)usb_dev->device,
1349 usb_size(usb_dev->device->bLength,
1350 usb_le16_to_cpu(setup_packet.wLength)),
1351 usb_status_handler);
1356 * TODO: refactor this part to remove this temporary buffer.
1358 * It would be better to define all the USB descriptors in the right order and
1359 * send them as a contiguous buffer directly from the flash / rodata memory.
1361 #define USB_BUFSIZE (128)
1362 static uint8_t usb_cfg_buffer[USB_BUFSIZE];
1363 STATIC_ASSERT(USB_BUFSIZE < (1 << (sizeof(uint16_t) * 8)));
1365 static int usb_get_configuration_descriptor(int id)
1367 const UsbConfigDesc **config =
1368 (const UsbConfigDesc **)usb_dev->config;
1369 uint8_t *p = usb_cfg_buffer;
1372 /* TODO: support more than one configuration per device */
1373 if (UNLIKELY(id > 0))
1374 return -USB_NODEV_ERROR;
1376 for (i = 0; config[i]; i++)
1378 memcpy(p, config[i], config[i]->bLength);
1379 p += config[i]->bLength;
1381 if (UNLIKELY((p - usb_cfg_buffer) > USB_BUFSIZE))
1384 return -USB_BUF_OVERFLOW;
1387 ((UsbConfigDesc *)usb_cfg_buffer)->wTotalLength =
1388 usb_cpu_to_le16((uint16_t)(p - usb_cfg_buffer));
1389 __usb_ep_write(CTRL_ENP_IN,
1391 usb_size(p - usb_cfg_buffer,
1392 usb_le16_to_cpu(setup_packet.wLength)),
1393 usb_status_handler);
1397 static int usb_get_string_descriptor(unsigned int id)
1399 const UsbStringDesc *lang_str;
1400 unsigned int lang_id, str_id;
1401 uint16_t w_index_lo = usb_le16_to_cpu(setup_packet.wIndex) & 0x00ff;
1402 uint16_t w_index_hi = (usb_le16_to_cpu(setup_packet.wIndex) &
1405 ASSERT(usb_dev->strings != NULL);
1406 ASSERT(usb_dev->strings[0] != NULL);
1408 lang_str = usb_dev->strings[0];
1411 /* Find Language index */
1412 for (lang_id = 0; ; lang_id++)
1414 const UsbStringDesc *str =
1415 usb_dev->strings[lang_id];
1416 if (UNLIKELY(str == NULL))
1417 return -USB_NODEV_ERROR;
1418 if ((str->data[0] == w_index_lo) &&
1419 (str->data[1] == w_index_hi))
1422 /* Check buffer overflow to find string index */
1423 for (str_id = 0; str_id < id; str_id++)
1425 lang_str = usb_dev->strings[lang_id + 1 + str_id];
1426 if (lang_str == NULL)
1427 return -USB_NODEV_ERROR;
1430 __usb_ep_write(CTRL_ENP_IN,
1432 usb_size(lang_str->bLength,
1433 usb_le16_to_cpu(setup_packet.wLength)),
1434 usb_status_handler);
1438 static void usb_get_descriptor(void)
1440 uint16_t w_value_lo = usb_le16_to_cpu(setup_packet.wValue) & 0x00ff;
1441 uint16_t w_value_hi = (usb_le16_to_cpu(setup_packet.wValue) & 0xff00) >> 8;
1443 if (udc.state < USB_STATE_DEFAULT)
1445 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1451 LOG_INFO("%s: GET_DEVICE_DESCRIPTOR: id=%d, state=%d\n",
1455 if (usb_get_device_descriptor(w_value_lo) < 0)
1456 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1459 LOG_INFO("%s: GET_CONFIG_DESCRIPTOR: id=%d, state=%d\n",
1460 __func__, w_value_lo, udc.state);
1461 if (usb_get_configuration_descriptor(w_value_lo) < 0)
1462 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1465 LOG_INFO("%s: GET_STRING_DESCRIPTOR: id=%d, state=%d\n",
1466 __func__, w_value_lo, udc.state);
1467 if (usb_get_string_descriptor(w_value_lo) < 0)
1468 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1471 LOG_WARN("%s: GET_UNKNOWN_DESCRIPTOR: id=%d, state=%d\n",
1472 __func__, w_value_lo, udc.state);
1473 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1478 /* USB setup packet: class/vendor request handler */
1479 static void usb_event_handler(UsbDevice *dev)
1482 * TODO: get the appropriate usb_dev in function of the endpoint
1486 dev->event_cb(&setup_packet);
1489 /* USB setup packet: GET_DESCRIPTOR handler */
1490 static void usb_get_descriptor_handler(void)
1492 LOG_INFO("%s: GET_DESCRIPTOR: RECIP = %d\n",
1494 setup_packet.mRequestType & USB_RECIP_MASK);
1495 if ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1497 usb_get_descriptor();
1498 /* Getting descriptor for a device is a standard request */
1499 else if ((setup_packet.mRequestType & USB_DIR_MASK) == USB_DIR_IN)
1500 usb_event_handler(usb_dev);
1502 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1505 /* USB setup packet: SET_ADDRESS handler */
1506 static void usb_set_address_handler(void)
1508 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1509 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1510 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1512 LOG_INFO("%s: SET_ADDRESS: %d\n",
1513 __func__, usb_le16_to_cpu(setup_packet.wValue));
1514 if ((udc.state >= USB_STATE_DEFAULT) &&
1515 ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1516 USB_RECIP_DEVICE) &&
1517 (w_index == 0) && (w_length == 0) && (w_value < 128))
1518 usb_status_handler(CTRL_ENP_IN);
1520 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1523 /* USB setup packet: GET_CONFIGURATION handler */
1524 static void usb_get_config_handler(void)
1526 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1527 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1529 LOG_INFO("%s: GET_CONFIGURATION\n", __func__);
1530 if ((udc.state >= USB_STATE_ADDRESS) &&
1531 (w_value == 0) && (w_index == 0) && (w_value == 1))
1533 InData = udc.cfg_id;
1534 __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 1, usb_status_handler);
1537 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1540 static const UsbConfigDesc *usb_find_configuration(int num)
1542 const UsbConfigDesc *cfg;
1547 cfg = (const UsbConfigDesc *)usb_dev->config[i];
1550 if (cfg->bDescriptorType != USB_DT_CONFIG)
1552 if (cfg->bConfigurationValue == num)
1558 static int usb_set_config_state(uint32_t conf)
1560 const UsbConfigDesc *pCnfg;
1565 /* Find configuration descriptor */
1566 pCnfg = usb_find_configuration(conf);
1568 return -USB_NODEV_ERROR;
1570 /* Reset current configuration */
1571 usb_set_device_state(USB_STATE_ADDRESS);
1572 usb_dev->configured = false;
1575 /* Set Interface and Alternative Setting */
1577 /* Set self-powered state */
1578 if (pCnfg->bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1579 udc.feature |= STM32_UDC_FEATURE_SELFPOWERED;
1581 /* Configure all existing interfaces to alternative setting 0 */
1582 ASSERT(pCnfg->bNumInterfaces <= USB_MAX_INTERFACE);
1583 udc.interfaces = pCnfg->bNumInterfaces;
1584 for (i = 0; i < udc.interfaces; i++)
1586 usb_set_device_state(USB_STATE_CONFIGURED);
1587 usb_dev->configured = true;
1588 LOG_INFO("%s: device configured\n", __func__);
1592 usb_dev->configured = false;
1593 usb_set_device_state(USB_STATE_ADDRESS);
1598 /* USB setup packet: SET_CONFIGURATION handler */
1599 static void usb_set_config_handler(void)
1601 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1602 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1603 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1605 LOG_INFO("%s: SET_CONFIGURATION: %d\n",
1607 if ((udc.state >= USB_STATE_ADDRESS) &&
1608 (w_index == 0) && (w_length == 0) &&
1609 (usb_set_config_state(w_value & 0xff) == 0))
1610 usb_status_handler(CTRL_ENP_OUT);
1612 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1615 /* USB setup packet: standard request handler */
1616 static void usb_standard_request_handler(void)
1618 switch (setup_packet.bRequest)
1620 case USB_REQ_GET_STATUS:
1621 usb_get_status_handler();
1623 case USB_REQ_CLEAR_FEATURE:
1624 LOG_INFO("%s: bRequest=%d (CLEAR_FEATURE)\n",
1625 __func__, setup_packet.bRequest);
1627 case USB_REQ_SET_FEATURE:
1628 LOG_INFO("%s: bRequest=%d (SET_FEATURE)\n",
1629 __func__, setup_packet.bRequest);
1631 case USB_REQ_SET_ADDRESS:
1632 usb_set_address_handler();
1634 case USB_REQ_GET_DESCRIPTOR:
1635 usb_get_descriptor_handler();
1637 case USB_REQ_SET_DESCRIPTOR:
1638 LOG_INFO("%s: bRequest=%d (SET_DESCRIPTOR)\n",
1639 __func__, setup_packet.bRequest);
1641 case USB_REQ_GET_CONFIGURATION:
1642 usb_get_config_handler();
1644 case USB_REQ_SET_CONFIGURATION:
1645 usb_set_config_handler();
1647 case USB_REQ_GET_INTERFACE:
1648 LOG_INFO("%s: bRequest=%d (GET_INTERFACE)\n",
1649 __func__, setup_packet.bRequest);
1651 case USB_REQ_SET_INTERFACE:
1652 LOG_INFO("%s: bRequest=%d (SET_INTERFACE)\n",
1653 __func__, setup_packet.bRequest);
1655 case USB_REQ_SYNCH_FRAME:
1656 LOG_INFO("%s: bRequest=%d (SYNCH_FRAME)\n",
1657 __func__, setup_packet.bRequest);
1660 LOG_WARN("%s: bRequest=%d (Unknown)\n",
1661 __func__, setup_packet.bRequest);
1662 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1667 /* USB setup packet handler */
1668 static void usb_setup_handler(void)
1670 switch (setup_packet.mRequestType & USB_TYPE_MASK)
1673 case USB_TYPE_STANDARD:
1674 LOG_INFO("%s: bmRequestType=%02x (Standard)\n",
1675 __func__, setup_packet.mRequestType);
1676 usb_standard_request_handler();
1679 case USB_TYPE_CLASS:
1680 LOG_INFO("%s: bmRequestType=%02x (Class)\n",
1681 __func__, setup_packet.mRequestType);
1682 usb_event_handler(usb_dev);
1685 case USB_TYPE_VENDOR:
1686 LOG_INFO("%s: bmRequestType=%02x (Vendor)\n",
1687 __func__, setup_packet.mRequestType);
1688 usb_event_handler(usb_dev);
1690 case USB_TYPE_RESERVED:
1691 LOG_INFO("%s: bmRequestType=%02x (Reserved)\n",
1692 __func__, setup_packet.mRequestType);
1696 LOG_WARN("%s: bmRequestType=%02x (Unknown)\n",
1697 __func__, setup_packet.mRequestType);
1698 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1703 /* USB: low-level hardware initialization */
1704 static void usb_hw_reset(void)
1709 /* Initialize endpoint descriptors */
1710 for (i = 0; i < countof(ep_cnfg); i++)
1711 ep_cnfg[i].hw = NULL;
1713 /* Initialize USB memory */
1714 for (i = 0; i < countof(memory_buffer); i++)
1715 memory_buffer[i].Size = 0;
1716 usb->BTABLE = USB_BDT_OFFSET;
1719 /* Endpoint initialization */
1720 ret = usb_ep_configure(&USB_CtrlEpDescr0, true);
1721 if (UNLIKELY(ret < 0))
1723 LOG_WARN("%s: out of memory, cannot initialize EP0\n",
1727 ret = usb_ep_configure(&USB_CtrlEpDescr1, true);
1728 if (UNLIKELY(ret < 0))
1730 LOG_WARN("%s: out of memory, cannot initialize EP1\n",
1735 /* Set default address */
1738 /* Enable all the device interrupts */
1739 usb->CNTR = bmCTRM | bmRESETM | bmSOFM | bmERRM | bmPMAOVRM |
1743 /* Handle a correct transfer under ISR */
1744 static void usb_isr_correct_transfer(stm32_usb_irq_status_t interrupt)
1747 reg32_t *pReg = (reg32_t *)&usb->EP0R;
1749 /* Find corresponding EP */
1750 pReg += interrupt.EP_ID;
1751 EP = (int)(((*pReg & 0x0f) << 1) + (interrupt.DIR ? 0 : 1));
1752 ep_cnfg[EP].avail_data = 1;
1754 ASSERT(ep_cnfg[EP].hw);
1757 ep_ctrl_clr_ctr_tx(ep_cnfg[EP].hw);
1759 ep_ctrl_clr_ctr_rx(ep_cnfg[EP].hw);
1760 if (EP == CTRL_ENP_OUT)
1762 /* Determinate type of packet (only for control EP) */
1763 bool SetupPacket = ep_ctrl_get_setup(ep_cnfg[CTRL_ENP_OUT].hw);
1767 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
1768 /* init IO to receive Setup packet */
1769 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1770 __usb_ep_read(CTRL_ENP_OUT, &setup_packet,
1771 sizeof(setup_packet), NULL);
1773 /* reset EP IO ctrl */
1774 if (setup_packet.mRequestType & USB_DIR_IN)
1775 usb_status_handler(CTRL_ENP_OUT);
1776 usb_setup_handler();
1777 if (ep_cnfg[CTRL_ENP_OUT].status == STALLED)
1778 usb_ep_set_stall_ctrl();
1782 if (ep_cnfg[CTRL_ENP_OUT].complete &&
1783 setup_packet.mRequestType & USB_DIR_IN)
1784 ep_cnfg[CTRL_ENP_OUT].complete(CTRL_ENP_OUT);
1789 else if (EP == CTRL_ENP_IN)
1791 if (ep_cnfg[CTRL_ENP_IN].complete &&
1792 !(setup_packet.mRequestType & USB_DIR_IN))
1793 ep_cnfg[CTRL_ENP_IN].complete(CTRL_ENP_IN);
1802 /* USB: interrupt service routine */
1803 static void usb_isr(void)
1805 stm32_usb_irq_status_t interrupt;
1807 /* Get masked interrupt flags */
1808 interrupt.status = usb->ISTR;
1809 interrupt.status &= usb->CNTR | 0x1f;
1811 if (interrupt.PMAOVR)
1813 LOG_WARN("%s: DMA overrun / underrun\n", __func__);
1814 usb->ISTR = ~bmPMAOVRM;
1818 LOG_WARN("%s: engine error\n", __func__);
1819 usb->ISTR = ~bmERRM;
1821 if (interrupt.RESET)
1823 LOG_INFO("%s: device reset\n", __func__);
1824 usb->ISTR = ~bmRESETM;
1826 usb_set_device_state(USB_STATE_DEFAULT);
1832 * XXX: disable logging of frame interrupts (too much noise!)
1834 uint16_t frame_nr = usb->FNR & 0x0fff;
1835 LOG_INFO("%s: frame %#x\n", __func__, frame_nr);
1837 usb->ISTR = ~bmSOFM;
1841 LOG_INFO("%s: wake-up\n", __func__);
1842 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1847 LOG_INFO("%s: suspend\n", __func__);
1849 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1853 LOG_INFO("%s: expected frame\n", __func__);
1854 usb->ISTR = ~bmESOFM;
1858 usb_isr_correct_transfer(interrupt);
1862 /* USB: hardware initialization */
1863 static void usb_hw_init(void)
1865 /* Enable clocking on the required GPIO pins */
1866 RCC->APB2ENR |= RCC_APB2_GPIOA | RCC_APB2_GPIOC;
1868 /* Make sure that the CAN controller is disabled and held in reset */
1869 RCC->APB1ENR &= ~RCC_APB1_CAN;
1871 /* Configure USB_DM and USB_DP to work as USB lines */
1872 stm32_gpioPinConfig((struct stm32_gpio *)GPIOA_BASE,
1873 USB_DM_PIN | USB_DP_PIN,
1874 GPIO_MODE_AF_PP, GPIO_SPEED_50MHZ);
1875 /* Configure USB_DISC to work as USB disconnect */
1876 stm32_gpioPinConfig((struct stm32_gpio *)GPIOC_BASE,
1878 GPIO_MODE_OUT_PP, GPIO_SPEED_50MHZ);
1879 stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE,
1882 /* Ensure the USB clock is disabled before setting the prescaler */
1883 RCC->APB1ENR &= ~RCC_APB1_USB;
1885 /* Configure USB clock (48MHz) */
1886 *CFGR_USBPRE_BB &= ~RCC_USBCLK_PLLCLK_1DIV5;
1888 /* Activate USB clock */
1889 RCC->APB1ENR |= RCC_APB1_USB;
1891 /* Force USB reset and disable USB interrupts */
1895 /* Issue a USB reset */
1898 /* Clear spurious pending interrupt */
1901 /* Register interrupt handler */
1902 sysirq_setHandler(USB_LP_CAN_RX0_IRQHANDLER, usb_isr);
1904 /* Software connection enable */
1908 /* Initialize the USB controller */
1909 static void usb_init(void)
1911 udc.state = USB_STATE_NOTATTACHED;
1917 /* Register an upper layer USB device into the driver */
1918 int usb_deviceRegister(UsbDevice *dev)
1925 while (!usb_dev->configured)