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 <mware/event.h>
59 #include <string.h> /* memcpy() */
61 #include "usb_stm32.h"
63 /* XXX: consider to move this to cfg/macros.h */
65 /* XXX: redefine this to make it usable within C expression */
66 #define _MIN(a,b) (((a) < (b)) ? (a) : (b))
68 /* STM32 USB registers */
79 reg32_t __reserved[8];
87 /* Hardware registers */
88 static struct stm32_usb *usb = (struct stm32_usb *)USB_BASE_ADDR;
90 /* Endpoint descriptors: used for handling requests to use with endpoints */
91 static stm32_UsbEp ep_cnfg[EP_MAX_NUM];
92 STATIC_ASSERT(EP_MAX_NUM <= EP_MAX_HW_NUM);
94 /* USB EP0 control descriptor */
95 static const UsbEndpointDesc USB_CtrlEpDescr0 =
97 .bLength = sizeof(USB_CtrlEpDescr0),
98 .bDescriptorType = USB_DT_ENDPOINT,
99 .bEndpointAddress = USB_DIR_OUT | 0,
100 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
101 .wMaxPacketSize = USB_EP0_MAX_SIZE,
105 /* USB EP1 control descriptor */
106 static const UsbEndpointDesc USB_CtrlEpDescr1 =
108 .bLength = sizeof(USB_CtrlEpDescr1),
109 .bDescriptorType = USB_DT_ENDPOINT,
110 .bEndpointAddress = USB_DIR_IN | 0,
111 .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
112 .wMaxPacketSize = USB_EP0_MAX_SIZE,
116 /* USB setup packet */
117 static UsbCtrlRequest setup_packet;
119 /* USB device controller: max supported interfaces */
120 #define USB_MAX_INTERFACE CONFIG_USB_INTERFACE_MAX
122 /* USB device controller features */
123 #define STM32_UDC_FEATURE_SELFPOWERED BV(0)
124 #define STM32_UDC_FEATURE_REMOTE_WAKEUP BV(1)
126 /* Hardware-specific USB device controller structure */
127 typedef struct stm32_udc
131 const UsbConfigDesc *cfg;
133 uint32_t alt[USB_MAX_INTERFACE];
136 } PACKED stm32_udc_t;
138 /* Hardware-specific USB Device Controller */
139 static stm32_udc_t udc;
141 /* Generic USB Device Controller structure */
142 static UsbDevice *usb_dev;
144 /* USB packet memory management: list of allocated chunks */
145 static stm32_UsbMemSlot *mem_use;
147 /* USB packet memory management: memory buffer metadata */
148 static stm32_UsbMemSlot memory_buffer[EP_MAX_NUM];
150 /* Endpoint TX and RX buffers */
151 static size_t rx_size, tx_size;
153 #define EP_BUFFER_SIZE _MIN(CONFIG_USB_BUFSIZE, USB_XFER_MAX_SIZE)
154 STATIC_ASSERT(!(EP_BUFFER_SIZE & 0x03));
156 static uint8_t ep_buffer[EP_MAX_NUM][EP_BUFFER_SIZE] ALIGNED(4);
158 static Event usb_event_done[EP_MAX_SLOTS];
160 /* Check if we're running in atomic (non-sleepable) context or not */
161 static volatile bool in_atomic = false;
163 /* Allocate a free block of the packet memory */
164 static stm32_UsbMemSlot *usb_malloc(void)
168 for (i = 0; i < countof(memory_buffer); i++)
169 if (memory_buffer[i].Size == 0)
170 return &memory_buffer[i];
174 /* Release a block of the packet memory */
175 static void usb_free(stm32_UsbMemSlot *pPntr)
180 /* Allocate a free chunk of the packet memory (inside a block) */
181 static bool usb_alloc_buffer(uint16_t *pOffset, uint32_t *size,
184 stm32_UsbMemSlot *mem = mem_use,
185 *memNext, *mem_useNew;
186 uint32_t max_size = *size;
189 * Packet size alignment:
190 * - fine-granularity allocation: size alignment by 2;
191 * - coarse-granularity allocation: size alignment by 32.
194 max_size = ALIGN_UP(max_size, 2);
196 max_size = ALIGN_UP(max_size, 32);
198 * Finding free memory chunks from the allocated blocks of the USB
204 /* Offset alignment by 4 */
205 *pOffset = ALIGN_UP(mem->Start + mem->Size, 4);
207 if ((mem->next == NULL) ||
209 *pOffset + max_size))
213 /* Check for out-of-memory condition */
214 if (UNLIKELY((*pOffset + max_size) >= USB_BDT_OFFSET))
217 * Allocate a new memory block, next to the last allocated block.
219 mem_useNew = usb_malloc();
220 if (UNLIKELY(mem_useNew == NULL))
222 /* Insert the block to the list of allocated blocks */
225 mem_use = mem_useNew;
226 mem_use->next = NULL;
230 mem_useNew->next = mem->next;
231 mem->next = mem_useNew;
233 /* Update block's metadata */
234 mem_useNew->ep_addr = EndPoint;
235 mem_useNew->Start = *pOffset;
236 mem_useNew->Size = max_size;
243 /* Release a chunk of the packet memory (inside a block) */
244 static void usb_free_buffer(int EndPoint)
246 stm32_UsbMemSlot *mem, *memPrev = NULL;
251 if (mem->ep_addr == EndPoint)
253 if (UNLIKELY(memPrev == NULL))
255 /* Free the first element of the list */
256 mem_use = mem_use->next;
261 memPrev->next = mem->next;
270 /*-------------------------------------------------------------------------*/
272 /* Connect USB controller */
273 static void usb_connect(void)
275 stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE, 1 << 11, 0);
278 /* Set USB device address */
279 static void usb_set_address(uint32_t addr)
281 usb->DADDR = addr | 0x80;
284 /* Suspend USB controller */
285 static void usb_suspend(void)
287 usb->CNTR |= bmFSUSP | bmLPMODE;
290 /* Resume USB controller */
291 static void usb_resume(void)
293 uint32_t line_status;
295 line_status = usb->FNR & 0xc000;
298 /* check for noise and eventually return to sleep */
299 if (line_status == 0xc000)
302 usb->CNTR &= ~(bmFSUSP | bmLPMODE);
305 /* Convert logical EP address to physical EP address */
306 static int usb_ep_logical_to_hw(uint8_t ep_addr)
308 int addr = (ep_addr & 0x0f) << 1;
309 return (ep_addr & 0x80) ? addr + 1 : addr;
313 static void ep_ctrl_set_ea(reg32_t *reg, uint32_t val)
316 val |= *reg & 0x0700;
317 val |= USB_CTRL_CLEAR_ONLY_MASK;
321 /* Get EP IN status */
322 static uint32_t ep_ctrl_get_stat_tx(reg32_t *reg)
324 return (*reg & (0x3UL << 4)) >> 4;
327 /* Set EP IN state */
328 static void ep_ctrl_set_stat_tx(reg32_t *reg, stm32_UsbEpState val)
334 * The EP can change state between read and write operations from VALID
335 * to NAK and result of set operation will be invalid.
337 for (i = 0; i < 2; i++)
339 if (ep_ctrl_get_stat_tx(reg) == val)
344 state |= USB_CTRL_CLEAR_ONLY_MASK;
345 /* Clear the toggle bits without STAT_TX (4,5) */
351 /* Set EP DTOG_TX bit (IN) */
352 static void ep_ctrl_set_dtog_tx(reg32_t *reg, uint32_t val)
354 val = val ? (*reg ^ (1UL << 6)) : *reg;
355 /* Clear the toggle bits without DTOG_TX (6) */
357 val |= USB_CTRL_CLEAR_ONLY_MASK;
361 /* Clear EP CTR_TX bit (IN) */
362 static void ep_ctrl_clr_ctr_tx(reg32_t *reg)
366 val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 7);
372 /* Clear EP CTR_RX bit (OUT) */
373 static void ep_ctrl_clr_ctr_rx(reg32_t *reg)
376 val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 15);
382 /* Set EP KIND bit */
383 static void ep_ctrl_set_ep_kind(reg32_t *reg, uint32_t val)
385 val = val ? (1UL << 8) : 0;
386 val |= *reg & ~(USB_CTRL_TOGGLE_MASK | (1UL << 8));
387 val |= USB_CTRL_CLEAR_ONLY_MASK;
392 static int ep_ctrl_set_ep_type(reg32_t *reg, uint8_t val)
396 if (UNLIKELY(val >= EP_TYPE_MAX))
399 return USB_INVAL_ERROR;
403 type |= *reg & ~(USB_CTRL_TOGGLE_MASK | (0x3UL << 9));
404 type |= USB_CTRL_CLEAR_ONLY_MASK;
410 /* Get EP STAT_RX (OUT) */
411 static uint32_t ep_ctrl_get_stat_rx(reg32_t *reg)
413 uint32_t val = *reg & (0x3UL << 12);
417 /* Set EP STAT_RX (OUT) */
418 static void ep_ctrl_set_stat_rx(reg32_t *reg, stm32_UsbEpState val)
424 * The EP can change state between read and write operations from VALID
425 * to NAK and result of set operation will be invalid.
427 for (i = 0; i < 2; i++)
429 if (ep_ctrl_get_stat_rx(reg) == val)
434 state |= USB_CTRL_CLEAR_ONLY_MASK;
435 /* Clear the toggle bits without STAT_RX (12,13) */
441 /* Set DTOG_RX bit */
442 static void ep_ctrl_set_dtog_rx(reg32_t *reg, uint32_t val)
444 val = val ? (*reg ^ (1UL << 14)) : *reg;
445 /* Clear the toggle bits without DTOG_RX (14) */
447 val |= USB_CTRL_CLEAR_ONLY_MASK;
451 /* Get EP SETUP bit */
452 static uint32_t ep_ctrl_get_setup(reg32_t *reg)
454 uint32_t val = *reg & (1UL << 11);
458 /* Core endpoint I/O function */
459 static void __usb_ep_io(int EP)
461 ssize_t Count, CountHold, Offset;
462 uint32_t *pDst, *pSrc, Data;
463 stm32_UsbEp *epd = &ep_cnfg[EP];
465 if (UNLIKELY(epd->hw == NULL))
467 LOG_ERR("%s: invalid endpoint (EP%d-%s)\n",
470 (EP & 0x01) ? "IN" : "OUT");
474 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
480 Count = epd->size - epd->offset;
481 while (epd->avail_data)
483 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
487 epd->status = BEGIN_SERVICED;
489 if ((epd->flags & STM32_USB_EP_ZERO_PACKET) &&
490 (Count == epd->max_size))
491 epd->flags |= STM32_USB_EP_ZERO_PACKET |
492 STM32_USB_EP_ZERO_POSSIBLE;
494 CountHold = Count = MIN(Count, epd->max_size);
496 epd->flags |= STM32_USB_EP_ZERO_PACKET;
497 Offset = epd->offset;
498 epd->offset += Count;
501 case USB_ENDPOINT_XFER_CONTROL:
502 case USB_ENDPOINT_XFER_INT:
503 pDst = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_TX_OFFSET));
505 case USB_ENDPOINT_XFER_BULK:
506 pDst = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_TX_OFFSET));
508 case USB_ENDPOINT_XFER_ISOC:
509 LOG_ERR("%s: isochronous transfer not supported\n",
511 /* Fallback to default */
517 /* Write data to packet memory buffer */
520 Data = *(epd->write_buffer + Offset++);
523 Data |= (uint32_t)(*(epd->write_buffer + Offset++)) << 8;
529 EP_DTB_WRITE(EP >> 1, COUNT_TX_OFFSET, CountHold);
530 ep_ctrl_set_stat_tx(epd->hw, EP_VALID);
532 --ep_cnfg[EP].avail_data;
533 Count = epd->size - epd->offset;
535 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
537 epd->status = COMPLETE;
538 /* call callback function */
546 while (epd->avail_data)
548 /* Get data size and buffer pointer */
551 case USB_ENDPOINT_XFER_CONTROL:
552 case USB_ENDPOINT_XFER_INT:
553 /* Get received bytes number */
554 Count = EP_DTB_READ(EP >> 1, COUNT_RX_OFFSET) & 0x3FF;
555 /* Get address of the USB packet buffer for corresponding EP */
556 pSrc = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_RX_OFFSET));
558 case USB_ENDPOINT_XFER_BULK:
559 /* Get received bytes number */
560 Count = EP_DTB_READ(EP >> 1, COUNT_RX_OFFSET) & 0x3FF;
561 /* Get address of the USB packet buffer for corresponding EP */
562 pSrc = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_RX_OFFSET));
564 case USB_ENDPOINT_XFER_ISOC:
565 LOG_ERR("%s: isochronous transfer not supported\n",
567 /* Fallback to default */
573 if (Count > (epd->size - epd->offset))
575 epd->status = BUFFER_OVERRUN;
576 epd->size = ep_cnfg[EP].offset;
579 else if (Count < ep_cnfg[EP].max_size)
581 epd->status = BUFFER_UNDERRUN;
582 epd->size = ep_cnfg[EP].offset + Count;
585 epd->status = BEGIN_SERVICED;
587 Offset = epd->offset;
588 epd->offset += Count;
590 /* Read data from packet memory buffer */
594 *(epd->read_buffer + Offset++) = Data;
598 *(epd->read_buffer + Offset++) = Data;
603 ep_ctrl_set_stat_rx(epd->hw, EP_VALID);
605 --ep_cnfg[EP].avail_data;
607 if (*epd->hw & (1UL << 11))
609 ep_cnfg[EP].status = SETUP_OVERWRITE;
612 if (!(Count = (epd->size - epd->offset)))
614 epd->status = COMPLETE;
618 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
620 /* call callback function */
628 * Return the lower value from Host expected size and size and set a flag
629 * STM32_USB_EP_ZERO_POSSIBLE when size is lower that host expected size.
631 static size_t usb_size(size_t size, size_t host_size)
633 if (size < host_size)
635 ep_cnfg[CTRL_ENP_IN].flags |= STM32_USB_EP_ZERO_POSSIBLE;
641 /* Configure an EP descriptor before performing a I/O operation */
642 #define USB_EP_IO(__EP, __op, __buf, __size, __complete) \
645 stm32_UsbIoStatus ret; \
647 /* Fill EP descriptor */ \
648 IRQ_SAVE_DISABLE(flags); \
651 ep_cnfg[__EP].status = NOT_READY; \
652 ep_cnfg[__EP].complete = NULL; \
656 if (ep_cnfg[__EP].status == BEGIN_SERVICED) \
662 * NOTE: the write_buffer and read_buffer are actually the \
663 * same location in memory (it's a union). \
665 * We have to do this trick to silent a build warning by \
666 * casting the I/O buffer to (void *) or (const void *). \
668 ep_cnfg[__EP].__op ## _buffer = __buf; \
669 ep_cnfg[__EP].offset = 0; \
670 ep_cnfg[__EP].size = __size; \
671 ep_cnfg[__EP].complete = __complete; \
673 ep_cnfg[__EP].flags = STM32_USB_EP_ZERO_PACKET; \
675 ep_cnfg[__EP].flags = 0; \
676 ep_cnfg[__EP].status = NO_SERVICED; \
678 /* Perform the I/O operation */ \
681 ret = ep_cnfg[__EP].status; \
683 IRQ_RESTORE(flags); \
687 /* Configure and endponint and perform a read operation */
688 static stm32_UsbIoStatus
689 __usb_ep_read(int ep, void *buffer, ssize_t size, void (*complete)(int))
691 if (UNLIKELY((ep >= EP_MAX_NUM) || (ep & 0x01)))
693 LOG_ERR("%s: invalid EP number %d\n", __func__, ep);
697 if (UNLIKELY((size_t)buffer & 0x03))
699 LOG_ERR("%s: unaligned buffer @ %p\n", __func__, buffer);
703 return USB_EP_IO(ep, read, buffer, size, complete);
706 /* Configure and endponint and perform a write operation */
707 static stm32_UsbIoStatus
708 __usb_ep_write(int ep, const void *buffer, ssize_t size, void (*complete)(int))
710 if (UNLIKELY((ep >= EP_MAX_NUM) || !(ep & 0x01)))
712 LOG_ERR("%s: invalid EP number %d\n", __func__, ep);
716 if (UNLIKELY((size_t)buffer & 0x03))
718 LOG_ERR("%s: unaligned buffer @ %p\n", __func__, buffer);
722 return USB_EP_IO(ep, write, buffer, size, complete);
725 static void usb_ep_low_level_config(int ep, uint16_t offset, uint16_t size)
727 stm32_UsbEp *epc = &ep_cnfg[ep];
733 ep_ctrl_set_stat_tx(epc->hw, EP_DISABLED);
734 /* Clear Tx toggle */
735 ep_ctrl_set_dtog_tx(epc->hw, 0);
736 /* Clear Correct Transfer for transmission flag */
737 ep_ctrl_clr_ctr_tx(epc->hw);
739 /* Update EP description table */
740 EP_DTB_WRITE(ep >> 1, ADDR_TX_OFFSET, offset);
741 EP_DTB_WRITE(ep >> 1, COUNT_TX_OFFSET, 0);
746 uint16_t rx_count = 0;
749 ep_ctrl_set_stat_rx(epc->hw, EP_DISABLED);
750 /* Clear Rx toggle */
751 ep_ctrl_set_dtog_rx(epc->hw, 0);
752 /* Clear Correct Transfer for reception flag */
753 ep_ctrl_clr_ctr_rx(epc->hw);
754 /* Descriptor block size field */
755 rx_count |= (size > 62) << 15;
756 /* Descriptor number of blocks field */
757 rx_count |= (((size > 62) ? (size >> 5) - 1 : size >> 1) &
759 /* Update EP description table */
760 EP_DTB_WRITE(ep >> 1, ADDR_RX_OFFSET, offset);
761 EP_DTB_WRITE(ep >> 1, COUNT_RX_OFFSET, rx_count);
765 /* Enable/Disable an endpoint */
766 static int usb_ep_configure(const UsbEndpointDesc *epd, bool enable)
774 EP = usb_ep_logical_to_hw(epd->bEndpointAddress);
775 ep_hw = &ep_cnfg[EP];
780 * Allocate packet memory for EP buffer/s calculate actual size
781 * only for the OUT EPs.
783 size = epd->wMaxPacketSize;
784 if (!usb_alloc_buffer(&Offset, &size, EP))
785 return -USB_MEMORY_FULL;
788 ep_hw->status = NOT_READY;
792 /* Set endpoint type */
793 ep_hw->type = usb_endpointType(epd);
794 /* Init EP max packet size */
795 ep_hw->max_size = epd->wMaxPacketSize;
798 ep_hw->avail_data = 1;
800 ep_hw->avail_data = 0;
801 hw = (reg32_t *)&usb->EP0R;
805 ep_ctrl_set_ea(hw, EP >> 1);
807 LOG_INFO("%s: EP%d-%s configured\n",
808 __func__, EP >> 1, EP & 1 ? "IN" : "OUT");
810 /* Low-level endpoint configuration */
811 usb_ep_low_level_config(EP, Offset, size);
813 /* Set EP Kind & enable */
816 case USB_ENDPOINT_XFER_CONTROL:
817 LOG_INFO("EP%d: CONTROL %s\n", EP >> 1,
818 EP & 1 ? "IN" : "OUT");
819 ep_ctrl_set_ep_type(hw, EP_CTRL);
820 ep_ctrl_set_ep_kind(hw, 0);
822 case USB_ENDPOINT_XFER_INT:
823 LOG_INFO("EP%d: INTERRUPT %s\n", EP >> 1,
824 EP & 1 ? "IN" : "OUT");
825 ep_ctrl_set_ep_type(hw, EP_INTERRUPT);
826 ep_ctrl_set_ep_kind(hw, 0);
828 case USB_ENDPOINT_XFER_BULK:
829 LOG_INFO("EP%d: BULK %s\n", EP >> 1,
830 EP & 1 ? "IN" : "OUT");
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 %s: not supported\n",
837 EP & 1 ? "IN" : "OUT");
838 /* Fallback to default */
841 return -USB_NODEV_ERROR;
846 ep_ctrl_set_stat_tx(hw, EP_NAK);
847 /* Clear Correct Transfer for transmission flag */
848 ep_ctrl_clr_ctr_tx(hw);
853 ep_ctrl_set_stat_rx(hw, EP_VALID);
856 else if (ep_cnfg[EP].hw)
858 hw = (reg32_t *)&usb->EP0R;
865 ep_ctrl_set_stat_tx(hw, EP_DISABLED);
866 /* Clear Correct Transfer for reception flag */
867 ep_ctrl_clr_ctr_tx(hw);
873 ep_ctrl_set_stat_rx(hw, EP_DISABLED);
874 /* Clear Correct Transfer for reception flag */
875 ep_ctrl_clr_ctr_rx(hw);
879 ep_cnfg[EP].hw = NULL;
884 /* Get EP stall/unstall */
885 static int usb_ep_get_stall(int EP, bool *pStall)
887 if (ep_cnfg[EP].hw == NULL)
888 return -USB_NODEV_ERROR;
890 *pStall = (EP & 0x01) ?
891 (ep_ctrl_get_stat_tx(ep_cnfg[EP].hw) == EP_STALL): /* IN EP */
892 (ep_ctrl_get_stat_rx(ep_cnfg[EP].hw) == EP_STALL); /* OUT EP */
897 /* Set EP stall/unstall */
898 static int usb_ep_set_stall(int EP, bool Stall)
900 if (ep_cnfg[EP].hw == NULL)
901 return -USB_NODEV_ERROR;
905 ep_cnfg[EP].status = STALLED;
909 ep_ctrl_set_stat_tx(ep_cnfg[EP].hw, EP_STALL);
910 ep_cnfg[EP].avail_data = 1;
915 ep_ctrl_set_stat_rx(ep_cnfg[EP].hw, EP_STALL);
916 ep_cnfg[EP].avail_data = 0;
921 ep_cnfg[EP].status = NOT_READY;
925 ep_cnfg[EP].avail_data = 1;
926 /* reset Data Toggle bit */
927 ep_ctrl_set_dtog_tx(ep_cnfg[EP].hw, 0);
928 ep_ctrl_set_stat_tx(ep_cnfg[EP].hw, EP_NAK);
933 ep_cnfg[EP].avail_data = 0;
934 /* reset Data Toggle bit */
935 ep_ctrl_set_dtog_rx(ep_cnfg[EP].hw, 0);
936 ep_ctrl_set_stat_rx(ep_cnfg[EP].hw, EP_VALID);
942 /* Stall both directions of the control EP */
943 static void usb_ep_set_stall_ctrl(void)
945 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
946 ep_cnfg[CTRL_ENP_IN].status = STALLED;
947 ep_cnfg[CTRL_ENP_OUT].avail_data = 0;
948 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
950 usb_ep_set_stall(CTRL_ENP_IN, true);
951 usb_ep_set_stall(CTRL_ENP_OUT, true);
955 * Find the position of an interface descriptor inside the configuration
958 static int usb_find_interface(uint32_t num, uint32_t alt)
960 const UsbInterfaceDesc *id;
965 /* TODO: support more than one configuration per device */
966 id = (const UsbInterfaceDesc *)usb_dev->config[i];
969 if (id->bDescriptorType != USB_DT_INTERFACE)
971 if ((id->bInterfaceNumber == num) &&
972 (id->bAlternateSetting == alt))
975 return -USB_NODEV_ERROR;
979 * Configure/deconfigure EPs of a certain interface.
982 usb_configure_ep_interface(unsigned int num, unsigned int alt, bool enable)
984 const UsbEndpointDesc *epd;
988 * Find the position of the interface descriptor (inside the
989 * configuration descriptor).
991 start = usb_find_interface(num, alt);
994 LOG_ERR("%s: interface (%u,%u) not found\n",
999 * Cycle over endpoint descriptors.
1001 * NOTE: the first endpoint descriptor is placed next to the interface
1002 * descriptor, so we need to add +1 to the position of the interface
1003 * descriptor to find it.
1005 for (i = start + 1; ; i++)
1007 epd = (const UsbEndpointDesc *)usb_dev->config[i];
1008 if ((epd == NULL) || (epd->bDescriptorType == USB_DT_INTERFACE))
1010 if (epd->bDescriptorType != USB_DT_ENDPOINT)
1012 if (UNLIKELY(usb_ep_configure(epd, enable) < 0))
1014 LOG_ERR("%s: out of memory, can't initialize EP\n",
1021 /* Set device state */
1022 static void usb_set_device_state(int state)
1026 LOG_INFO("%s: new state %d\n", __func__, state);
1028 if (udc.state == USB_STATE_CONFIGURED)
1030 /* Deconfigure device */
1031 for (i = 0; i < udc.interfaces; ++i)
1032 usb_configure_ep_interface(i,
1037 case USB_STATE_ATTACHED:
1038 case USB_STATE_POWERED:
1039 case USB_STATE_DEFAULT:
1041 usb_dev->configured = false;
1042 udc.address = udc.cfg_id = 0;
1044 case USB_STATE_ADDRESS:
1047 case USB_STATE_CONFIGURED:
1048 /* Configure device */
1049 for (i = 0; i < udc.interfaces; ++i)
1050 usb_configure_ep_interface(i,
1054 /* Unknown state: disconnected or connection in progress */
1055 usb_dev->configured = false;
1063 /* Setup packet: set address status phase end handler */
1064 static void usb_add_status_handler_end(UNUSED_ARG(int, EP))
1068 w_value = usb_le16_to_cpu(setup_packet.wValue);
1069 udc.address = w_value & 0xff;
1070 usb_set_address(udc.address);
1073 usb_set_device_state(USB_STATE_ADDRESS);
1075 usb_set_device_state(USB_STATE_DEFAULT);
1077 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1078 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1081 /* Prepare status phase */
1082 static void usb_status_phase(bool in)
1085 __usb_ep_write(CTRL_ENP_IN, NULL, 0, NULL);
1088 /* Setup packet: status phase end handler */
1089 static void usb_status_handler_end(UNUSED_ARG(int, EP))
1091 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1092 __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1095 /* Address status handler */
1096 static void usb_status_handler(UNUSED_ARG(int, EP))
1098 if (setup_packet.mRequestType & USB_DIR_IN)
1100 usb_status_phase(false);
1101 ep_cnfg[CTRL_ENP_OUT].complete = usb_status_handler_end;
1105 usb_status_phase(true);
1106 ep_cnfg[CTRL_ENP_IN].complete =
1107 (setup_packet.bRequest == USB_REQ_SET_ADDRESS) ?
1108 usb_add_status_handler_end :
1109 usb_status_handler_end;
1113 static void usb_endpointRead_complete(int ep)
1115 if (UNLIKELY(ep >= EP_MAX_NUM))
1120 ASSERT(!(ep & 0x01));
1122 event_do(&usb_event_done[ep >> 1]);
1123 rx_size = ep_cnfg[ep].size;
1126 ssize_t usb_endpointReadTimeout(int ep, void *buffer, ssize_t size,
1129 int ep_num = usb_ep_logical_to_hw(ep);
1130 ssize_t max_size = sizeof(ep_buffer[ep_num]);
1132 /* Non-blocking read for EP0 */
1133 if (in_atomic && (ep_num == CTRL_ENP_OUT))
1135 size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
1136 if (UNLIKELY(size > max_size))
1138 LOG_ERR("%s: ep_buffer exceeded, try to enlarge CONFIG_USB_BUFSIZE\n",
1141 return -USB_BUF_OVERFLOW;
1144 usb_status_handler(ep_num);
1147 __usb_ep_read(ep_num, ep_buffer[ep_num], size,
1148 usb_status_handler);
1149 memcpy(buffer, ep_buffer[ep_num], size);
1153 if (UNLIKELY(!size))
1155 size = MIN(size, max_size);
1156 event_initGeneric(&usb_event_done[ep_num >> 1]);
1160 __usb_ep_read(ep_num, ep_buffer[ep_num], size,
1161 usb_endpointRead_complete);
1163 event_wait(&usb_event_done[ep_num >> 1]);
1165 if (!event_waitTimeout(&usb_event_done[ep_num >> 1], timeout))
1167 memcpy(buffer, ep_buffer[ep_num], rx_size);
1172 static void usb_endpointWrite_complete(int ep)
1174 if (UNLIKELY(ep >= EP_MAX_NUM))
1181 event_do(&usb_event_done[ep >> 1]);
1182 tx_size = ep_cnfg[ep].size;
1185 ssize_t usb_endpointWriteTimeout(int ep, const void *buffer, ssize_t size,
1188 int ep_num = usb_ep_logical_to_hw(ep);
1189 ssize_t max_size = sizeof(ep_buffer[ep_num]);
1191 /* Non-blocking write for EP0 */
1192 if (in_atomic && (ep_num == CTRL_ENP_IN))
1194 size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
1195 if (UNLIKELY(size > max_size))
1197 LOG_ERR("%s: ep_buffer exceeded, try to enlarge CONFIG_USB_BUFSIZE\n",
1200 return -USB_BUF_OVERFLOW;
1203 usb_status_handler(ep_num);
1206 memcpy(ep_buffer[ep_num], buffer, size);
1207 __usb_ep_write(ep_num, ep_buffer[ep_num], size,
1208 usb_status_handler);
1212 if (UNLIKELY(!size))
1214 size = MIN(size, max_size);
1215 event_initGeneric(&usb_event_done[ep_num >> 1]);
1218 /* Blocking write */
1219 memcpy(ep_buffer[ep_num], buffer, size);
1220 __usb_ep_write(ep_num, ep_buffer[ep_num], size,
1221 usb_endpointWrite_complete);
1223 event_wait(&usb_event_done[ep_num >> 1]);
1225 if (!event_waitTimeout(&usb_event_done[ep_num >> 1], timeout))
1231 /* Global variable to handle the following non-blocking I/O operations */
1232 static uint32_t InData;
1234 /* Get device status */
1235 static int usb_send_device_status(uint16_t index)
1238 return -USB_NODEV_ERROR;
1240 InData = ((uint32_t)udc.feature) & 0xff;
1241 __usb_ep_write(CTRL_ENP_IN,
1242 (uint8_t *)&InData, sizeof(uint16_t),
1243 usb_status_handler);
1247 /* Get interface status */
1248 static int usb_send_interface_status(UNUSED_ARG(uint16_t, index))
1251 __usb_ep_write(CTRL_ENP_IN,
1252 (uint8_t *)&InData, sizeof(uint16_t),
1253 usb_status_handler);
1257 /* Get endpoint status */
1258 static int usb_send_ep_status(uint16_t index)
1260 if ((index & 0x7F) > 16)
1261 return -USB_NODEV_ERROR;
1264 usb_ep_get_stall(usb_ep_logical_to_hw(index), (bool *)&InData);
1265 __usb_ep_write(CTRL_ENP_IN,
1266 (uint8_t *)&InData, sizeof(uint16_t),
1267 usb_status_handler);
1271 /* USB setup packet: GET_STATUS request handler */
1272 static void usb_get_status_handler(void)
1274 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1275 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1276 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1278 /* GET_STATUS sanity checks */
1279 if (udc.state < USB_STATE_ADDRESS)
1281 LOG_WARN("%s: bad GET_STATUS request (State=%02x)\n",
1282 __func__, udc.state);
1283 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1288 LOG_WARN("%s: bad GET_STATUS request (wLength.Word=%02x)\n",
1289 __func__, w_length);
1290 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1293 if (!(setup_packet.mRequestType & USB_DIR_IN))
1295 LOG_WARN("%s: bad GET_STATUS request (mRequestType=%02x)\n",
1296 __func__, setup_packet.mRequestType);
1297 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1302 LOG_WARN("%s: bad GET_STATUS request (wValue=%02x)\n",
1304 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1308 /* Process GET_STATUS request */
1309 switch (setup_packet.mRequestType & USB_RECIP_MASK)
1311 case USB_RECIP_DEVICE:
1312 if (usb_send_device_status(w_index) < 0)
1314 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientDevice\n",
1316 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1319 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientDevice)\n",
1320 __func__, setup_packet.mRequestType);
1322 case USB_RECIP_INTERFACE:
1323 if (usb_send_interface_status(w_index) < 0)
1325 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientInterface\n",
1327 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1330 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientInterface)\n",
1331 __func__, setup_packet.mRequestType);
1333 case USB_RECIP_ENDPOINT:
1334 if (usb_send_ep_status(w_index) < 0)
1336 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1338 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1341 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientEndpoint)\n",
1342 __func__, setup_packet.mRequestType);
1345 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1347 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1352 static int usb_get_device_descriptor(int id)
1355 return -USB_NODEV_ERROR;
1357 usb_dev->device->bMaxPacketSize0 = USB_EP0_MAX_SIZE;
1358 __usb_ep_write(CTRL_ENP_IN, (const uint8_t *)usb_dev->device,
1359 usb_size(usb_dev->device->bLength,
1360 usb_le16_to_cpu(setup_packet.wLength)),
1361 usb_status_handler);
1366 * TODO: refactor this part to remove this temporary buffer.
1368 * It would be better to define all the USB descriptors in the right order and
1369 * send them as a contiguous buffer directly from the flash / rodata memory.
1371 #define USB_BUFSIZE (128)
1372 static uint8_t usb_cfg_buffer[USB_BUFSIZE];
1373 STATIC_ASSERT(USB_BUFSIZE < (1 << (sizeof(uint16_t) * 8)));
1375 static int usb_get_configuration_descriptor(int id)
1377 const UsbConfigDesc **config =
1378 (const UsbConfigDesc **)usb_dev->config;
1379 uint8_t *p = usb_cfg_buffer;
1382 /* TODO: support more than one configuration per device */
1383 if (UNLIKELY(id > 0))
1384 return -USB_NODEV_ERROR;
1386 for (i = 0; config[i]; i++)
1388 memcpy(p, config[i], config[i]->bLength);
1389 p += config[i]->bLength;
1391 if (UNLIKELY((p - usb_cfg_buffer) > USB_BUFSIZE))
1394 return -USB_BUF_OVERFLOW;
1397 ((UsbConfigDesc *)usb_cfg_buffer)->wTotalLength =
1398 usb_cpu_to_le16((uint16_t)(p - usb_cfg_buffer));
1399 __usb_ep_write(CTRL_ENP_IN,
1401 usb_size(p - usb_cfg_buffer,
1402 usb_le16_to_cpu(setup_packet.wLength)),
1403 usb_status_handler);
1407 static int usb_get_string_descriptor(unsigned int id)
1409 const UsbStringDesc *lang_str;
1410 unsigned int lang_id, str_id;
1411 uint16_t w_index_lo = usb_le16_to_cpu(setup_packet.wIndex) & 0x00ff;
1412 uint16_t w_index_hi = (usb_le16_to_cpu(setup_packet.wIndex) &
1415 ASSERT(usb_dev->strings != NULL);
1416 ASSERT(usb_dev->strings[0] != NULL);
1418 lang_str = usb_dev->strings[0];
1421 /* Find Language index */
1422 for (lang_id = 0; ; lang_id++)
1424 const UsbStringDesc *str =
1425 usb_dev->strings[lang_id];
1426 if (UNLIKELY(str == NULL))
1427 return -USB_NODEV_ERROR;
1428 if ((str->data[0] == w_index_lo) &&
1429 (str->data[1] == w_index_hi))
1432 /* Check buffer overflow to find string index */
1433 for (str_id = 0; str_id < id; str_id++)
1435 lang_str = usb_dev->strings[lang_id + 1 + str_id];
1436 if (lang_str == NULL)
1437 return -USB_NODEV_ERROR;
1440 __usb_ep_write(CTRL_ENP_IN,
1442 usb_size(lang_str->bLength,
1443 usb_le16_to_cpu(setup_packet.wLength)),
1444 usb_status_handler);
1448 static void usb_get_descriptor(void)
1450 uint16_t w_value_lo = usb_le16_to_cpu(setup_packet.wValue) & 0x00ff;
1451 uint16_t w_value_hi = (usb_le16_to_cpu(setup_packet.wValue) & 0xff00) >> 8;
1453 if (udc.state < USB_STATE_DEFAULT)
1455 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1461 LOG_INFO("%s: GET_DEVICE_DESCRIPTOR: id=%d, state=%d\n",
1465 if (usb_get_device_descriptor(w_value_lo) < 0)
1466 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1469 LOG_INFO("%s: GET_CONFIG_DESCRIPTOR: id=%d, state=%d\n",
1470 __func__, w_value_lo, udc.state);
1471 if (usb_get_configuration_descriptor(w_value_lo) < 0)
1472 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1475 LOG_INFO("%s: GET_STRING_DESCRIPTOR: id=%d, state=%d\n",
1476 __func__, w_value_lo, udc.state);
1477 if (usb_get_string_descriptor(w_value_lo) < 0)
1478 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1481 LOG_WARN("%s: GET_UNKNOWN_DESCRIPTOR: id=%d, state=%d\n",
1482 __func__, w_value_lo, udc.state);
1483 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1488 /* USB setup packet: class/vendor request handler */
1489 static void usb_event_handler(UsbDevice *dev)
1492 * TODO: get the appropriate usb_dev in function of the endpoint
1496 dev->event_cb(&setup_packet);
1499 /* USB setup packet: GET_DESCRIPTOR handler */
1500 static void usb_get_descriptor_handler(void)
1502 LOG_INFO("%s: GET_DESCRIPTOR: RECIP = %d\n",
1504 setup_packet.mRequestType & USB_RECIP_MASK);
1505 if ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1507 usb_get_descriptor();
1509 usb_event_handler(usb_dev);
1512 /* USB setup packet: SET_ADDRESS handler */
1513 static void usb_set_address_handler(void)
1515 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1516 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1517 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1519 LOG_INFO("%s: SET_ADDRESS: %d\n",
1520 __func__, usb_le16_to_cpu(setup_packet.wValue));
1521 if ((udc.state >= USB_STATE_DEFAULT) &&
1522 ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1523 USB_RECIP_DEVICE) &&
1524 (w_index == 0) && (w_length == 0) && (w_value < 128))
1525 usb_status_handler(CTRL_ENP_IN);
1527 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1530 /* USB setup packet: GET_CONFIGURATION handler */
1531 static void usb_get_config_handler(void)
1533 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1534 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1536 LOG_INFO("%s: GET_CONFIGURATION\n", __func__);
1537 if ((udc.state >= USB_STATE_ADDRESS) &&
1538 (w_value == 0) && (w_index == 0) && (w_value == 1))
1540 InData = udc.cfg_id;
1541 __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 1, usb_status_handler);
1544 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1547 static const UsbConfigDesc *usb_find_configuration(int num)
1549 const UsbConfigDesc *cfg;
1554 cfg = (const UsbConfigDesc *)usb_dev->config[i];
1557 if (cfg->bDescriptorType != USB_DT_CONFIG)
1559 if (cfg->bConfigurationValue == num)
1565 static int usb_set_config_state(uint32_t conf)
1567 const UsbConfigDesc *pCnfg;
1572 /* Find configuration descriptor */
1573 pCnfg = usb_find_configuration(conf);
1575 return -USB_NODEV_ERROR;
1577 /* Reset current configuration */
1578 usb_set_device_state(USB_STATE_ADDRESS);
1579 usb_dev->configured = false;
1582 /* Set Interface and Alternative Setting */
1584 /* Set self-powered state */
1585 if (pCnfg->bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1586 udc.feature |= STM32_UDC_FEATURE_SELFPOWERED;
1588 /* Configure all existing interfaces to alternative setting 0 */
1589 ASSERT(pCnfg->bNumInterfaces <= USB_MAX_INTERFACE);
1590 udc.interfaces = pCnfg->bNumInterfaces;
1591 for (i = 0; i < udc.interfaces; i++)
1593 usb_set_device_state(USB_STATE_CONFIGURED);
1594 usb_dev->configured = true;
1595 event_do(&usb_event_done[0]);
1596 LOG_INFO("%s: device configured\n", __func__);
1600 usb_dev->configured = false;
1601 usb_set_device_state(USB_STATE_ADDRESS);
1606 /* USB setup packet: SET_CONFIGURATION handler */
1607 static void usb_set_config_handler(void)
1609 uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1610 uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1611 uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1613 LOG_INFO("%s: SET_CONFIGURATION: %d\n",
1615 if ((udc.state >= USB_STATE_ADDRESS) &&
1616 (w_index == 0) && (w_length == 0) &&
1617 (usb_set_config_state(w_value & 0xff) == 0))
1618 usb_status_handler(CTRL_ENP_OUT);
1620 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1623 /* USB setup packet: standard request handler */
1624 static void usb_standard_request_handler(void)
1626 switch (setup_packet.bRequest)
1628 case USB_REQ_GET_STATUS:
1629 usb_get_status_handler();
1631 case USB_REQ_CLEAR_FEATURE:
1632 LOG_INFO("%s: bRequest=%d (CLEAR_FEATURE)\n",
1633 __func__, setup_packet.bRequest);
1635 case USB_REQ_SET_FEATURE:
1636 LOG_INFO("%s: bRequest=%d (SET_FEATURE)\n",
1637 __func__, setup_packet.bRequest);
1639 case USB_REQ_SET_ADDRESS:
1640 usb_set_address_handler();
1642 case USB_REQ_GET_DESCRIPTOR:
1643 usb_get_descriptor_handler();
1645 case USB_REQ_SET_DESCRIPTOR:
1646 LOG_INFO("%s: bRequest=%d (SET_DESCRIPTOR)\n",
1647 __func__, setup_packet.bRequest);
1649 case USB_REQ_GET_CONFIGURATION:
1650 usb_get_config_handler();
1652 case USB_REQ_SET_CONFIGURATION:
1653 usb_set_config_handler();
1655 case USB_REQ_GET_INTERFACE:
1656 LOG_INFO("%s: bRequest=%d (GET_INTERFACE)\n",
1657 __func__, setup_packet.bRequest);
1659 case USB_REQ_SET_INTERFACE:
1660 LOG_INFO("%s: bRequest=%d (SET_INTERFACE)\n",
1661 __func__, setup_packet.bRequest);
1663 case USB_REQ_SYNCH_FRAME:
1664 LOG_INFO("%s: bRequest=%d (SYNCH_FRAME)\n",
1665 __func__, setup_packet.bRequest);
1668 LOG_WARN("%s: bRequest=%d (Unknown)\n",
1669 __func__, setup_packet.bRequest);
1670 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1675 /* USB setup packet handler */
1676 static void usb_setup_handler(void)
1678 switch (setup_packet.mRequestType & USB_TYPE_MASK)
1681 case USB_TYPE_STANDARD:
1682 LOG_INFO("%s: bmRequestType=%02x (Standard)\n",
1683 __func__, setup_packet.mRequestType);
1684 usb_standard_request_handler();
1687 case USB_TYPE_CLASS:
1688 LOG_INFO("%s: bmRequestType=%02x (Class)\n",
1689 __func__, setup_packet.mRequestType);
1690 usb_event_handler(usb_dev);
1693 case USB_TYPE_VENDOR:
1694 LOG_INFO("%s: bmRequestType=%02x (Vendor)\n",
1695 __func__, setup_packet.mRequestType);
1696 usb_event_handler(usb_dev);
1698 case USB_TYPE_RESERVED:
1699 LOG_INFO("%s: bmRequestType=%02x (Reserved)\n",
1700 __func__, setup_packet.mRequestType);
1704 LOG_WARN("%s: bmRequestType=%02x (Unknown)\n",
1705 __func__, setup_packet.mRequestType);
1706 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1711 /* USB: low-level hardware initialization */
1712 static void usb_hw_reset(void)
1717 /* Initialize endpoint descriptors */
1718 for (i = 0; i < countof(ep_cnfg); i++)
1719 ep_cnfg[i].hw = NULL;
1721 /* Initialize USB memory */
1722 for (i = 0; i < countof(memory_buffer); i++)
1723 memory_buffer[i].Size = 0;
1724 usb->BTABLE = USB_BDT_OFFSET;
1727 /* Endpoint initialization */
1728 ret = usb_ep_configure(&USB_CtrlEpDescr0, true);
1729 if (UNLIKELY(ret < 0))
1731 LOG_WARN("%s: out of memory, cannot initialize EP0\n",
1735 ret = usb_ep_configure(&USB_CtrlEpDescr1, true);
1736 if (UNLIKELY(ret < 0))
1738 LOG_WARN("%s: out of memory, cannot initialize EP1\n",
1743 /* Set default address */
1746 /* Enable all the device interrupts */
1747 usb->CNTR = bmCTRM | bmRESETM | bmSOFM | bmERRM | bmPMAOVRM |
1751 /* Handle a correct transfer under ISR */
1752 static void usb_isr_correct_transfer(stm32_usb_irq_status_t interrupt)
1755 reg32_t *pReg = (reg32_t *)&usb->EP0R;
1757 /* Find corresponding EP */
1758 pReg += interrupt.EP_ID;
1759 EP = (int)(((*pReg & 0x0f) << 1) + (interrupt.DIR ? 0 : 1));
1760 ep_cnfg[EP].avail_data = 1;
1762 ASSERT(ep_cnfg[EP].hw);
1765 ep_ctrl_clr_ctr_tx(ep_cnfg[EP].hw);
1767 ep_ctrl_clr_ctr_rx(ep_cnfg[EP].hw);
1768 if (EP == CTRL_ENP_OUT)
1770 /* Determinate type of packet (only for control EP) */
1771 bool SetupPacket = ep_ctrl_get_setup(ep_cnfg[CTRL_ENP_OUT].hw);
1775 ep_cnfg[CTRL_ENP_IN].avail_data = 1;
1776 /* init IO to receive Setup packet */
1777 __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1778 __usb_ep_read(CTRL_ENP_OUT, &setup_packet,
1779 sizeof(setup_packet), NULL);
1781 /* reset EP IO ctrl */
1782 if (setup_packet.mRequestType & USB_DIR_IN)
1783 usb_status_handler(CTRL_ENP_OUT);
1784 usb_setup_handler();
1785 if (ep_cnfg[CTRL_ENP_OUT].status == STALLED)
1786 usb_ep_set_stall_ctrl();
1790 if (ep_cnfg[CTRL_ENP_OUT].complete &&
1791 setup_packet.mRequestType & USB_DIR_IN)
1792 ep_cnfg[CTRL_ENP_OUT].complete(CTRL_ENP_OUT);
1797 else if (EP == CTRL_ENP_IN)
1799 if (ep_cnfg[CTRL_ENP_IN].complete &&
1800 !(setup_packet.mRequestType & USB_DIR_IN))
1801 ep_cnfg[CTRL_ENP_IN].complete(CTRL_ENP_IN);
1810 /* USB: interrupt service routine */
1811 static void usb_isr(void)
1813 stm32_usb_irq_status_t interrupt;
1815 /* Get masked interrupt flags */
1816 interrupt.status = usb->ISTR;
1817 interrupt.status &= usb->CNTR | 0x1f;
1819 /* Set the context as atomic */
1822 if (interrupt.PMAOVR)
1824 LOG_WARN("%s: DMA overrun / underrun\n", __func__);
1825 usb->ISTR = ~bmPMAOVRM;
1829 LOG_WARN("%s: engine error\n", __func__);
1830 usb->ISTR = ~bmERRM;
1832 if (interrupt.RESET)
1834 LOG_INFO("%s: device reset\n", __func__);
1835 usb->ISTR = ~bmRESETM;
1837 usb_set_device_state(USB_STATE_DEFAULT);
1843 * XXX: disable logging of frame interrupts (too much noise!)
1845 uint16_t frame_nr = usb->FNR & 0x0fff;
1846 LOG_INFO("%s: frame %#x\n", __func__, frame_nr);
1848 usb->ISTR = ~bmSOFM;
1852 LOG_INFO("%s: wake-up\n", __func__);
1853 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1858 LOG_INFO("%s: suspend\n", __func__);
1860 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1864 LOG_INFO("%s: expected frame\n", __func__);
1865 usb->ISTR = ~bmESOFM;
1869 usb_isr_correct_transfer(interrupt);
1874 /* USB: hardware initialization */
1875 static void usb_hw_init(void)
1877 /* Enable clocking on the required GPIO pins */
1878 RCC->APB2ENR |= RCC_APB2_GPIOA | RCC_APB2_GPIOC;
1880 /* Make sure that the CAN controller is disabled and held in reset */
1881 RCC->APB1ENR &= ~RCC_APB1_CAN;
1883 /* Configure USB_DM and USB_DP to work as USB lines */
1884 stm32_gpioPinConfig((struct stm32_gpio *)GPIOA_BASE,
1885 USB_DM_PIN | USB_DP_PIN,
1886 GPIO_MODE_AF_PP, GPIO_SPEED_50MHZ);
1887 /* Configure USB_DISC to work as USB disconnect */
1888 stm32_gpioPinConfig((struct stm32_gpio *)GPIOC_BASE,
1890 GPIO_MODE_OUT_PP, GPIO_SPEED_50MHZ);
1891 stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE,
1894 /* Ensure the USB clock is disabled before setting the prescaler */
1895 RCC->APB1ENR &= ~RCC_APB1_USB;
1897 /* Configure USB clock (48MHz) */
1898 *CFGR_USBPRE_BB &= ~RCC_USBCLK_PLLCLK_1DIV5;
1900 /* Activate USB clock */
1901 RCC->APB1ENR |= RCC_APB1_USB;
1903 /* Force USB reset and disable USB interrupts */
1907 /* Issue a USB reset */
1910 /* Clear spurious pending interrupt */
1913 /* Register interrupt handler */
1914 sysirq_setHandler(USB_LP_CAN_RX0_IRQHANDLER, usb_isr);
1916 /* Software connection enable */
1920 /* Initialize the USB controller */
1921 static void usb_init(void)
1923 udc.state = USB_STATE_NOTATTACHED;
1929 /* Register an upper layer USB device into the driver */
1930 int usb_deviceRegister(UsbDevice *dev)
1936 usb_dev->configured = false;
1938 event_initGeneric(&usb_event_done[0]);
1940 event_wait(&usb_event_done[0]);