BeRTOS
usb_stm32.c
Go to the documentation of this file.
00001 
00038 #include "cfg/cfg_usb.h"
00039 
00040 #define LOG_LEVEL  USB_LOG_LEVEL
00041 #define LOG_FORMAT USB_LOG_FORMAT
00042 
00043 #include <cfg/log.h>
00044 #include <cfg/debug.h>
00045 #include <cfg/macros.h>
00046 #include <cfg/module.h>
00047 
00048 #include <cpu/irq.h>
00049 #include <cpu/power.h>
00050 
00051 #include <drv/irq_cm3.h>
00052 #include <drv/gpio_stm32.h>
00053 #include <drv/clock_stm32.h>
00054 #include <drv/timer.h>
00055 #include <drv/usb.h>
00056 
00057 #include <mware/event.h>
00058 
00059 #include <string.h> /* memcpy() */
00060 
00061 #include "usb_stm32.h"
00062 
00063 /* XXX: consider to move this to cfg/macros.h */
00064 
00065 /* XXX: redefine this to make it usable within C expression */
00066 #define _MIN(a,b)   (((a) < (b)) ? (a) : (b))
00067 
00068 /* STM32 USB registers */
00069 struct stm32_usb
00070 {
00071     reg32_t EP0R;
00072     reg32_t EP1R;
00073     reg32_t EP2R;
00074     reg32_t EP3R;
00075     reg32_t EP4R;
00076     reg32_t EP5R;
00077     reg32_t EP6R;
00078     reg32_t EP7R;
00079     reg32_t __reserved[8];
00080     reg32_t CNTR;
00081     reg32_t ISTR;
00082     reg32_t FNR;
00083     reg32_t DADDR;
00084     reg32_t BTABLE;
00085 };
00086 
00087 /* Hardware registers */
00088 static struct stm32_usb *usb = (struct stm32_usb *)USB_BASE_ADDR;
00089 
00090 /* Endpoint descriptors: used for handling requests to use with endpoints */
00091 static stm32_UsbEp ep_cnfg[EP_MAX_NUM];
00092 STATIC_ASSERT(EP_MAX_NUM <= EP_MAX_HW_NUM);
00093 
00094 /* USB EP0 control descriptor */
00095 static const UsbEndpointDesc USB_CtrlEpDescr0 =
00096 {
00097     .bLength = sizeof(USB_CtrlEpDescr0),
00098     .bDescriptorType = USB_DT_ENDPOINT,
00099     .bEndpointAddress = USB_DIR_OUT | 0,
00100     .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
00101     .wMaxPacketSize = USB_EP0_MAX_SIZE,
00102     .bInterval = 0,
00103 };
00104 
00105 /* USB EP1 control descriptor */
00106 static const UsbEndpointDesc USB_CtrlEpDescr1 =
00107 {
00108     .bLength = sizeof(USB_CtrlEpDescr1),
00109     .bDescriptorType = USB_DT_ENDPOINT,
00110     .bEndpointAddress = USB_DIR_IN | 0,
00111     .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
00112     .wMaxPacketSize = USB_EP0_MAX_SIZE,
00113     .bInterval = 0,
00114 };
00115 
00116 /* USB setup packet */
00117 static UsbCtrlRequest setup_packet;
00118 
00119 /* USB device controller: max supported interfaces */
00120 #define USB_MAX_INTERFACE   CONFIG_USB_INTERFACE_MAX
00121 
00122 /* USB device controller features */
00123 #define STM32_UDC_FEATURE_SELFPOWERED   BV(0)
00124 #define STM32_UDC_FEATURE_REMOTE_WAKEUP BV(1)
00125 
00126 /* Hardware-specific USB device controller structure */
00127 typedef struct stm32_udc
00128 {
00129     uint8_t state;
00130     uint32_t cfg_id;
00131     const UsbConfigDesc *cfg;
00132     uint32_t interfaces;
00133     uint32_t alt[USB_MAX_INTERFACE];
00134     uint32_t address;
00135     uint8_t feature;
00136 } PACKED stm32_udc_t;
00137 
00138 /* Hardware-specific USB Device Controller */
00139 static stm32_udc_t udc;
00140 
00141 /* Generic USB Device Controller structure */
00142 static UsbDevice *usb_dev;
00143 
00144 /* USB packet memory management: list of allocated chunks */
00145 static stm32_UsbMemSlot *mem_use;
00146 
00147 /* USB packet memory management: memory buffer metadata */
00148 static stm32_UsbMemSlot memory_buffer[EP_MAX_NUM];
00149 
00150 /* Endpoint TX and RX buffers */
00151 static size_t rx_size, tx_size;
00152 
00153 #define EP_BUFFER_SIZE _MIN(CONFIG_USB_BUFSIZE, USB_XFER_MAX_SIZE)
00154 STATIC_ASSERT(!(EP_BUFFER_SIZE & 0x03));
00155 
00156 static uint8_t ep_buffer[EP_MAX_NUM][EP_BUFFER_SIZE] ALIGNED(4);
00157 
00158 static Event usb_event_done[EP_MAX_SLOTS];
00159 
00160 /* Check if we're running in atomic (non-sleepable) context or not */
00161 static volatile bool in_atomic = false;
00162 
00163 /* Allocate a free block of the packet memory */
00164 static stm32_UsbMemSlot *usb_malloc(void)
00165 {
00166     unsigned int i;
00167 
00168     for (i = 0; i < countof(memory_buffer); i++)
00169         if (memory_buffer[i].Size == 0)
00170             return &memory_buffer[i];
00171     return NULL;
00172 }
00173 
00174 /* Release a block of the packet memory */
00175 static void usb_free(stm32_UsbMemSlot *pPntr)
00176 {
00177     pPntr->Size = 0;
00178 }
00179 
00180 /* Allocate a free chunk of the packet memory (inside a block) */
00181 static bool usb_alloc_buffer(uint16_t *pOffset, uint32_t *size,
00182                             int EndPoint)
00183 {
00184     stm32_UsbMemSlot *mem = mem_use,
00185             *memNext, *mem_useNew;
00186     uint32_t max_size = *size;
00187 
00188     /*
00189      * Packet size alignment:
00190      *  - fine-granularity allocation: size alignment by 2;
00191      *  - coarse-granularity allocation: size alignment by 32.
00192      */
00193     if (max_size < 62)
00194         max_size = ALIGN_UP(max_size, 2);
00195     else
00196         max_size = ALIGN_UP(max_size, 32);
00197     /*
00198      * Finding free memory chunks from the allocated blocks of the USB
00199      * packet memory.
00200      */
00201     *pOffset = 0;
00202     while (mem != NULL)
00203     {
00204         /* Offset alignment by 4 */
00205         *pOffset = ALIGN_UP(mem->Start + mem->Size, 4);
00206         memNext = mem->next;
00207         if ((mem->next == NULL) ||
00208                 (memNext->Start >=
00209                     *pOffset + max_size))
00210             break;
00211         mem = mem->next;
00212     }
00213     /* Check for out-of-memory condition */
00214     if (UNLIKELY((*pOffset + max_size) >= USB_BDT_OFFSET))
00215         return false;
00216     /*
00217      * Allocate a new memory block, next to the last allocated block.
00218      */
00219     mem_useNew = usb_malloc();
00220     if (UNLIKELY(mem_useNew == NULL))
00221         return false;
00222     /* Insert the block to the list of allocated blocks */
00223     if (mem_use == NULL)
00224     {
00225         mem_use = mem_useNew;
00226         mem_use->next = NULL;
00227     }
00228     else
00229     {
00230         mem_useNew->next = mem->next;
00231         mem->next = mem_useNew;
00232     }
00233     /* Update block's metadata */
00234     mem_useNew->ep_addr = EndPoint;
00235     mem_useNew->Start = *pOffset;
00236     mem_useNew->Size = max_size;
00237 
00238     *size = max_size;
00239 
00240     return true;
00241 }
00242 
00243 /* Release a chunk of the packet memory (inside a block) */
00244 static void usb_free_buffer(int EndPoint)
00245 {
00246     stm32_UsbMemSlot *mem, *memPrev = NULL;
00247     mem = mem_use;
00248 
00249     while (mem != NULL)
00250     {
00251         if (mem->ep_addr == EndPoint)
00252         {
00253             if (UNLIKELY(memPrev == NULL))
00254             {
00255                 /* Free the first element of the list */
00256                 mem_use = mem_use->next;
00257                 usb_free(mem);
00258                 mem = mem_use;
00259                 continue;
00260             }
00261             memPrev->next = mem->next;
00262             usb_free(mem);
00263         }
00264         else
00265             memPrev = mem;
00266         mem = memPrev->next;
00267     }
00268 }
00269 
00270 /*-------------------------------------------------------------------------*/
00271 
00272 /* Connect USB controller */
00273 static void usb_connect(void)
00274 {
00275     stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE, 1 << 11, 0);
00276 }
00277 
00278 /* Set USB device address */
00279 static void usb_set_address(uint32_t addr)
00280 {
00281     usb->DADDR = addr | 0x80;
00282 }
00283 
00284 /* Suspend USB controller */
00285 static void usb_suspend(void)
00286 {
00287     usb->CNTR |= bmFSUSP | bmLPMODE;
00288 }
00289 
00290 /* Resume USB controller */
00291 static void usb_resume(void)
00292 {
00293     uint32_t line_status;
00294 
00295     line_status = usb->FNR & 0xc000;
00296     if (!line_status)
00297         return;
00298     /* check for noise and eventually return to sleep */
00299     if (line_status == 0xc000)
00300         usb_suspend();
00301     else
00302         usb->CNTR &= ~(bmFSUSP | bmLPMODE);
00303 }
00304 
00305 /* Convert logical EP address to physical EP address */
00306 static int usb_ep_logical_to_hw(uint8_t ep_addr)
00307 {
00308     int addr = (ep_addr & 0x0f) << 1;
00309     return (ep_addr & 0x80) ? addr + 1 : addr;
00310 }
00311 
00312 /* Set EP address */
00313 static void ep_ctrl_set_ea(reg32_t *reg, uint32_t val)
00314 {
00315     val &= 0x0f;
00316     val |= *reg & 0x0700;
00317     val |= USB_CTRL_CLEAR_ONLY_MASK;
00318     *reg = val;
00319 }
00320 
00321 /* Get EP IN status */
00322 static uint32_t ep_ctrl_get_stat_tx(reg32_t *reg)
00323 {
00324     return (*reg & (0x3UL << 4)) >> 4;
00325 }
00326 
00327 /* Set EP IN state */
00328 static void ep_ctrl_set_stat_tx(reg32_t *reg, stm32_UsbEpState val)
00329 {
00330     uint32_t state;
00331     int i;
00332 
00333     /*
00334      * The EP can change state between read and write operations from VALID
00335      * to NAK and result of set operation will be invalid.
00336      */
00337     for (i = 0; i < 2; i++)
00338     {
00339         if (ep_ctrl_get_stat_tx(reg) == val)
00340             return;
00341         state = val;
00342         state <<= 4;
00343         state ^= *reg;
00344         state |= USB_CTRL_CLEAR_ONLY_MASK;
00345         /* Clear the toggle bits without STAT_TX (4,5) */
00346         state &= ~0x7040;
00347         *reg = state;
00348     }
00349 }
00350 
00351 /* Set EP DTOG_TX bit (IN) */
00352 static void ep_ctrl_set_dtog_tx(reg32_t *reg, uint32_t val)
00353 {
00354     val = val ? (*reg ^ (1UL << 6)) : *reg;
00355     /* Clear the toggle bits without DTOG_TX (6) */
00356     val &= ~0x7030;
00357     val |= USB_CTRL_CLEAR_ONLY_MASK;
00358     *reg = val;
00359 }
00360 
00361 /* Clear EP CTR_TX bit (IN) */
00362 static void ep_ctrl_clr_ctr_tx(reg32_t *reg)
00363 {
00364     uint32_t val = *reg;
00365 
00366     val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 7);
00367     /* Set RX_CTR */
00368     val |= 1UL << 15;
00369     *reg = val;
00370 }
00371 
00372 /* Clear EP CTR_RX bit (OUT) */
00373 static void ep_ctrl_clr_ctr_rx(reg32_t *reg)
00374 {
00375     uint32_t val = *reg;
00376     val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 15);
00377     /* Set TX_CTR */
00378     val |= 1UL << 7;
00379     *reg = val;
00380 }
00381 
00382 /* Set EP KIND bit */
00383 static void ep_ctrl_set_ep_kind(reg32_t *reg, uint32_t val)
00384 {
00385     val = val ? (1UL << 8) : 0;
00386     val |= *reg & ~(USB_CTRL_TOGGLE_MASK | (1UL << 8));
00387     val |= USB_CTRL_CLEAR_ONLY_MASK;
00388     *reg = val;
00389 }
00390 
00391 /* Set EP type */
00392 static int ep_ctrl_set_ep_type(reg32_t *reg, uint8_t val)
00393 {
00394     uint32_t type;
00395 
00396     if (UNLIKELY(val >= EP_TYPE_MAX))
00397     {
00398         ASSERT(0);
00399         return USB_INVAL_ERROR;
00400     }
00401     type = val;
00402     type <<= 9;
00403     type |= *reg & ~(USB_CTRL_TOGGLE_MASK | (0x3UL << 9));
00404     type |= USB_CTRL_CLEAR_ONLY_MASK;
00405     *reg = type;
00406 
00407     return USB_OK;
00408 }
00409 
00410 /* Get EP STAT_RX (OUT) */
00411 static uint32_t ep_ctrl_get_stat_rx(reg32_t *reg)
00412 {
00413     uint32_t val = *reg & (0x3UL << 12);
00414     return val >> 12;
00415 }
00416 
00417 /* Set EP STAT_RX (OUT) */
00418 static void ep_ctrl_set_stat_rx(reg32_t *reg, stm32_UsbEpState val)
00419 {
00420     uint32_t state;
00421     int i;
00422 
00423     /*
00424      * The EP can change state between read and write operations from VALID
00425      * to NAK and result of set operation will be invalid.
00426      */
00427     for (i = 0; i < 2; i++)
00428     {
00429         if (ep_ctrl_get_stat_rx(reg) == val)
00430             return;
00431         state = val;
00432         state <<= 12;
00433         state ^= *reg;
00434         state |= USB_CTRL_CLEAR_ONLY_MASK;
00435         /* Clear the toggle bits without STAT_RX (12,13) */
00436         state &= ~0x4070;
00437         *reg = state;
00438     }
00439 }
00440 
00441 /* Set DTOG_RX bit */
00442 static void ep_ctrl_set_dtog_rx(reg32_t *reg, uint32_t val)
00443 {
00444     val = val ? (*reg ^ (1UL << 14)) : *reg;
00445     /* Clear the toggle bits without DTOG_RX (14) */
00446     val &= ~0x3070;
00447     val |= USB_CTRL_CLEAR_ONLY_MASK;
00448     *reg = val;
00449 }
00450 
00451 /* Get EP SETUP bit */
00452 static uint32_t ep_ctrl_get_setup(reg32_t *reg)
00453 {
00454     uint32_t val = *reg & (1UL << 11);
00455     return val ? 1 : 0;
00456 }
00457 
00458 /* Core endpoint I/O function */
00459 static void __usb_ep_io(int EP)
00460 {
00461     ssize_t Count, CountHold, Offset;
00462     uint32_t *pDst, *pSrc, Data;
00463     stm32_UsbEp *epd = &ep_cnfg[EP];
00464 
00465     if (UNLIKELY(epd->hw == NULL))
00466     {
00467         LOG_ERR("%s: invalid endpoint (EP%d-%s)\n",
00468                 __func__,
00469                 EP >> 1,
00470                 (EP & 0x01) ? "IN" : "OUT");
00471         ASSERT(0);
00472         return;
00473     }
00474     if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
00475         return;
00476 
00477     if (EP & 0x01)
00478     {
00479         /* EP IN */
00480         Count = epd->size - epd->offset;
00481         while (epd->avail_data)
00482         {
00483             if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
00484                 break;
00485 
00486             /* Set Status */
00487             epd->status = BEGIN_SERVICED;
00488             /* Get data size */
00489             if ((epd->flags & STM32_USB_EP_ZERO_PACKET) &&
00490                     (Count == epd->max_size))
00491                 epd->flags |= STM32_USB_EP_ZERO_PACKET |
00492                         STM32_USB_EP_ZERO_POSSIBLE;
00493 
00494             CountHold = Count = MIN(Count, epd->max_size);
00495             if (!Count)
00496                 epd->flags |= STM32_USB_EP_ZERO_PACKET;
00497             Offset = epd->offset;
00498             epd->offset += Count;
00499             switch (epd->type)
00500             {
00501             case USB_ENDPOINT_XFER_CONTROL:
00502             case USB_ENDPOINT_XFER_INT:
00503                 pDst = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_TX_OFFSET));
00504                 break;
00505             case USB_ENDPOINT_XFER_BULK:
00506                 pDst = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_TX_OFFSET));
00507                 break;
00508             case USB_ENDPOINT_XFER_ISOC:
00509                 LOG_ERR("%s: isochronous transfer not supported\n",
00510                     __func__);
00511                 /* Fallback to default */
00512             default:
00513                 ASSERT(0);
00514                 return;
00515             }
00516 
00517             /* Write data to packet memory buffer */
00518             while (Count)
00519             {
00520                 Data = *(epd->write_buffer + Offset++);
00521                 if (--Count)
00522                 {
00523                     Data |= (uint32_t)(*(epd->write_buffer + Offset++)) << 8;
00524                     --Count;
00525                 }
00526                 *pDst++ = Data;
00527             }
00528 
00529             EP_DTB_WRITE(EP >> 1, COUNT_TX_OFFSET, CountHold);
00530             ep_ctrl_set_stat_tx(epd->hw, EP_VALID);
00531 
00532             --ep_cnfg[EP].avail_data;
00533             Count = epd->size - epd->offset;
00534         }
00535         if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
00536         {
00537             epd->status = COMPLETE;
00538             /* call callback function */
00539             if (epd->complete)
00540                 epd->complete(EP);
00541         }
00542     }
00543     else
00544     {
00545         /* EP OUT */
00546         while (epd->avail_data)
00547         {
00548             /* Get data size and buffer pointer */
00549             switch (epd->type)
00550             {
00551             case USB_ENDPOINT_XFER_CONTROL:
00552             case USB_ENDPOINT_XFER_INT:
00553                 /* Get received bytes number */
00554                 Count = EP_DTB_READ(EP >> 1, COUNT_RX_OFFSET) & 0x3FF;
00555                 /* Get address of the USB packet buffer for corresponding EP */
00556                 pSrc = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_RX_OFFSET));
00557                 break;
00558             case USB_ENDPOINT_XFER_BULK:
00559                 /* Get received bytes number */
00560                 Count = EP_DTB_READ(EP >> 1, COUNT_RX_OFFSET) & 0x3FF;
00561                 /* Get address of the USB packet buffer for corresponding EP */
00562                 pSrc = (uint32_t *)USB_MEM_ADDR(EP_DTB_READ(EP >> 1, ADDR_RX_OFFSET));
00563                 break;
00564             case USB_ENDPOINT_XFER_ISOC:
00565                 LOG_ERR("%s: isochronous transfer not supported\n",
00566                     __func__);
00567                 /* Fallback to default */
00568             default:
00569                 ASSERT(0);
00570                 return;
00571             }
00572 
00573             if (Count > (epd->size - epd->offset))
00574             {
00575                 epd->status = BUFFER_OVERRUN;
00576                 epd->size = ep_cnfg[EP].offset;
00577                 break;
00578             }
00579             else if (Count < ep_cnfg[EP].max_size)
00580             {
00581                 epd->status = BUFFER_UNDERRUN;
00582                 epd->size = ep_cnfg[EP].offset + Count;
00583             }
00584             else
00585                 epd->status = BEGIN_SERVICED;
00586 
00587             Offset = epd->offset;
00588             epd->offset += Count;
00589 
00590             /* Read data from packet memory buffer */
00591             while (Count)
00592             {
00593                 Data = *pSrc++;
00594                 *(epd->read_buffer + Offset++) = Data;
00595                 if (--Count)
00596                 {
00597                     Data >>= 8;
00598                     *(epd->read_buffer + Offset++) = Data;
00599                     --Count;
00600                 }
00601             }
00602 
00603             ep_ctrl_set_stat_rx(epd->hw, EP_VALID);
00604 
00605             --ep_cnfg[EP].avail_data;
00606 
00607             if (*epd->hw & (1UL << 11))
00608             {
00609                 ep_cnfg[EP].status = SETUP_OVERWRITE;
00610                 return;
00611             }
00612             if (!(Count = (epd->size - epd->offset)))
00613             {
00614                 epd->status = COMPLETE;
00615                 break;
00616             }
00617         }
00618         if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
00619         {
00620             /* call callback function */
00621             if (epd->complete)
00622                 epd->complete(EP);
00623         }
00624     }
00625 }
00626 
00627 /*
00628  * Return the lower value from Host expected size and size and set a flag
00629  * STM32_USB_EP_ZERO_POSSIBLE when size is lower that host expected size.
00630  */
00631 static size_t usb_size(size_t size, size_t host_size)
00632 {
00633     if (size < host_size)
00634     {
00635         ep_cnfg[CTRL_ENP_IN].flags |= STM32_USB_EP_ZERO_POSSIBLE;
00636         return size;
00637     }
00638     return host_size;
00639 }
00640 
00641 /* Configure an EP descriptor before performing a I/O operation */
00642 #define USB_EP_IO(__EP, __op, __buf, __size, __complete)        \
00643 ({                                  \
00644     cpu_flags_t flags;                      \
00645     stm32_UsbIoStatus ret;                  \
00646                                     \
00647     /* Fill EP descriptor */                    \
00648     IRQ_SAVE_DISABLE(flags);                    \
00649     if (__size < 0)                         \
00650     {                               \
00651         ep_cnfg[__EP].status = NOT_READY;           \
00652         ep_cnfg[__EP].complete = NULL;              \
00653         ret = NOT_READY;                    \
00654         goto out;                       \
00655     }                               \
00656     if (ep_cnfg[__EP].status == BEGIN_SERVICED)         \
00657     {                               \
00658         ret = NOT_READY;                    \
00659         goto out;                       \
00660     }                               \
00661     /*                              \
00662      * NOTE: the write_buffer and read_buffer are actually the  \
00663      * same location in memory (it's a union).          \
00664      *                              \
00665      * We have to do this trick to silent a build warning by    \
00666      * casting the I/O buffer to (void *) or (const void *).    \
00667      */                             \
00668     ep_cnfg[__EP].__op ## _buffer = __buf;              \
00669     ep_cnfg[__EP].offset = 0;                   \
00670     ep_cnfg[__EP].size = __size;                    \
00671     ep_cnfg[__EP].complete = __complete;                \
00672     if (!size)                          \
00673         ep_cnfg[__EP].flags = STM32_USB_EP_ZERO_PACKET;     \
00674     else                                \
00675         ep_cnfg[__EP].flags = 0;                \
00676     ep_cnfg[__EP].status = NO_SERVICED;             \
00677                                     \
00678     /* Perform the I/O operation */                 \
00679     __usb_ep_io(__EP);                      \
00680                                     \
00681     ret = ep_cnfg[__EP].status;                 \
00682 out:                                    \
00683     IRQ_RESTORE(flags);                     \
00684     ret;                                \
00685 })
00686 
00687 /* Configure and endponint and perform a read operation */
00688 static stm32_UsbIoStatus
00689 __usb_ep_read(int ep, void *buffer, ssize_t size, void (*complete)(int))
00690 {
00691     if (UNLIKELY((ep >= EP_MAX_NUM) || (ep & 0x01)))
00692     {
00693         LOG_ERR("%s: invalid EP number %d\n", __func__, ep);
00694         ASSERT(0);
00695         return STALLED;
00696     }
00697     if (UNLIKELY((size_t)buffer & 0x03))
00698     {
00699         LOG_ERR("%s: unaligned buffer @ %p\n", __func__, buffer);
00700         ASSERT(0);
00701         return STALLED;
00702     }
00703     return USB_EP_IO(ep, read, buffer, size, complete);
00704 }
00705 
00706 /* Configure and endponint and perform a write operation */
00707 static stm32_UsbIoStatus
00708 __usb_ep_write(int ep, const void *buffer, ssize_t size, void (*complete)(int))
00709 {
00710     if (UNLIKELY((ep >= EP_MAX_NUM) || !(ep & 0x01)))
00711     {
00712         LOG_ERR("%s: invalid EP number %d\n", __func__, ep);
00713         ASSERT(0);
00714         return STALLED;
00715     }
00716     if (UNLIKELY((size_t)buffer & 0x03))
00717     {
00718         LOG_ERR("%s: unaligned buffer @ %p\n", __func__, buffer);
00719         ASSERT(0);
00720         return STALLED;
00721     }
00722     return USB_EP_IO(ep, write, buffer, size, complete);
00723 }
00724 
00725 static void usb_ep_low_level_config(int ep, uint16_t offset, uint16_t size)
00726 {
00727     stm32_UsbEp *epc = &ep_cnfg[ep];
00728 
00729     /* IN EP */
00730     if (ep & 0x01)
00731     {
00732         /* Disable EP */
00733         ep_ctrl_set_stat_tx(epc->hw, EP_DISABLED);
00734         /* Clear Tx toggle */
00735         ep_ctrl_set_dtog_tx(epc->hw, 0);
00736         /* Clear Correct Transfer for transmission flag */
00737         ep_ctrl_clr_ctr_tx(epc->hw);
00738 
00739         /* Update EP description table */
00740         EP_DTB_WRITE(ep >> 1, ADDR_TX_OFFSET, offset);
00741         EP_DTB_WRITE(ep >> 1, COUNT_TX_OFFSET, 0);
00742     }
00743     /* OUT EP */
00744     else
00745     {
00746         uint16_t rx_count = 0;
00747 
00748         /* Disable EP */
00749         ep_ctrl_set_stat_rx(epc->hw, EP_DISABLED);
00750         /* Clear Rx toggle */
00751         ep_ctrl_set_dtog_rx(epc->hw, 0);
00752         /* Clear Correct Transfer for reception flag */
00753         ep_ctrl_clr_ctr_rx(epc->hw);
00754         /* Descriptor block size field */
00755         rx_count |= (size > 62) << 15;
00756         /* Descriptor number of blocks field */
00757         rx_count |= (((size > 62) ?  (size >> 5) - 1 : size >> 1) &
00758                 0x1f) << 10;
00759         /* Update EP description table */
00760         EP_DTB_WRITE(ep >> 1, ADDR_RX_OFFSET, offset);
00761         EP_DTB_WRITE(ep >> 1, COUNT_RX_OFFSET, rx_count);
00762     }
00763 }
00764 
00765 /* Enable/Disable an endpoint */
00766 static int usb_ep_configure(const UsbEndpointDesc *epd, bool enable)
00767 {
00768     int EP;
00769     stm32_UsbEp *ep_hw;
00770     reg32_t *hw;
00771     uint16_t Offset;
00772     uint32_t size;
00773 
00774     EP = usb_ep_logical_to_hw(epd->bEndpointAddress);
00775     ep_hw = &ep_cnfg[EP];
00776 
00777     if (enable)
00778     {
00779         /*
00780          * Allocate packet memory for EP buffer/s calculate actual size
00781          * only for the OUT EPs.
00782          */
00783         size = epd->wMaxPacketSize;
00784         if (!usb_alloc_buffer(&Offset, &size, EP))
00785             return -USB_MEMORY_FULL;
00786 
00787         /* Set EP status */
00788         ep_hw->status  = NOT_READY;
00789         /* Init EP flags */
00790         ep_hw->flags = 0;
00791 
00792         /* Set endpoint type */
00793         ep_hw->type = usb_endpointType(epd);
00794         /* Init EP max packet size */
00795         ep_hw->max_size = epd->wMaxPacketSize;
00796 
00797         if (EP & 0x01)
00798             ep_hw->avail_data = 1;
00799         else
00800             ep_hw->avail_data = 0;
00801         hw = (reg32_t *)&usb->EP0R;
00802         hw += EP >> 1;
00803 
00804         /* Set Ep Address */
00805         ep_ctrl_set_ea(hw, EP >> 1);
00806         ep_hw->hw = hw;
00807         LOG_INFO("%s: EP%d-%s configured\n",
00808                 __func__, EP >> 1, EP & 1 ? "IN" : "OUT");
00809 
00810         /* Low-level endpoint configuration */
00811         usb_ep_low_level_config(EP, Offset, size);
00812 
00813         /* Set EP Kind & enable */
00814         switch (ep_hw->type)
00815         {
00816         case USB_ENDPOINT_XFER_CONTROL:
00817             LOG_INFO("EP%d: CONTROL %s\n", EP >> 1,
00818                     EP & 1 ? "IN" : "OUT");
00819             ep_ctrl_set_ep_type(hw, EP_CTRL);
00820             ep_ctrl_set_ep_kind(hw, 0);
00821             break;
00822         case USB_ENDPOINT_XFER_INT:
00823             LOG_INFO("EP%d: INTERRUPT %s\n", EP >> 1,
00824                     EP & 1 ? "IN" : "OUT");
00825             ep_ctrl_set_ep_type(hw, EP_INTERRUPT);
00826             ep_ctrl_set_ep_kind(hw, 0);
00827             break;
00828         case USB_ENDPOINT_XFER_BULK:
00829             LOG_INFO("EP%d: BULK %s\n", EP >> 1,
00830                     EP & 1 ? "IN" : "OUT");
00831             ep_ctrl_set_ep_type(hw, EP_BULK);
00832             ep_ctrl_set_ep_kind(hw, 0);
00833             break;
00834         case USB_ENDPOINT_XFER_ISOC:
00835             LOG_ERR("EP%d: ISOCHRONOUS %s: not supported\n",
00836                     EP >> 1,
00837                     EP & 1 ? "IN" : "OUT");
00838             /* Fallback to default */
00839         default:
00840             ASSERT(0);
00841             return -USB_NODEV_ERROR;
00842         }
00843         if (EP & 0x01)
00844         {
00845             /* Enable EP */
00846             ep_ctrl_set_stat_tx(hw, EP_NAK);
00847             /* Clear Correct Transfer for transmission flag */
00848             ep_ctrl_clr_ctr_tx(hw);
00849         }
00850         else
00851         {
00852             /* Enable EP */
00853             ep_ctrl_set_stat_rx(hw, EP_VALID);
00854         }
00855     }
00856     else if (ep_cnfg[EP].hw)
00857     {
00858         hw = (reg32_t *)&usb->EP0R;
00859         hw += EP >> 1;
00860 
00861         /* IN EP */
00862         if (EP & 0x01)
00863         {
00864             /* Disable IN EP */
00865             ep_ctrl_set_stat_tx(hw, EP_DISABLED);
00866             /* Clear Correct Transfer for reception flag */
00867             ep_ctrl_clr_ctr_tx(hw);
00868         }
00869         /* OUT EP */
00870         else
00871         {
00872             /* Disable OUT EP */
00873             ep_ctrl_set_stat_rx(hw, EP_DISABLED);
00874             /* Clear Correct Transfer for reception flag */
00875             ep_ctrl_clr_ctr_rx(hw);
00876         }
00877         /* Release buffer */
00878         usb_free_buffer(EP);
00879         ep_cnfg[EP].hw = NULL;
00880     }
00881     return 0;
00882 }
00883 
00884 /* Get EP stall/unstall */
00885 static int usb_ep_get_stall(int EP, bool *pStall)
00886 {
00887     if (ep_cnfg[EP].hw == NULL)
00888         return -USB_NODEV_ERROR;
00889 
00890     *pStall = (EP & 0x01) ?
00891         (ep_ctrl_get_stat_tx(ep_cnfg[EP].hw) == EP_STALL):  /* IN EP  */
00892         (ep_ctrl_get_stat_rx(ep_cnfg[EP].hw) == EP_STALL);  /* OUT EP */
00893 
00894     return USB_OK;
00895 }
00896 
00897 /* Set EP stall/unstall */
00898 static int usb_ep_set_stall(int EP, bool Stall)
00899 {
00900     if (ep_cnfg[EP].hw == NULL)
00901         return -USB_NODEV_ERROR;
00902 
00903     if (Stall)
00904     {
00905         ep_cnfg[EP].status = STALLED;
00906         if (EP & 0x01)
00907         {
00908             /* IN EP */
00909             ep_ctrl_set_stat_tx(ep_cnfg[EP].hw, EP_STALL);
00910             ep_cnfg[EP].avail_data = 1;
00911         }
00912         else
00913         {
00914             /* OUT EP */
00915             ep_ctrl_set_stat_rx(ep_cnfg[EP].hw, EP_STALL);
00916             ep_cnfg[EP].avail_data = 0;
00917         }
00918     }
00919     else
00920     {
00921         ep_cnfg[EP].status = NOT_READY;
00922         if(EP & 0x01)
00923         {
00924             /* IN EP */
00925             ep_cnfg[EP].avail_data = 1;
00926             /* reset Data Toggle bit */
00927             ep_ctrl_set_dtog_tx(ep_cnfg[EP].hw, 0);
00928             ep_ctrl_set_stat_tx(ep_cnfg[EP].hw, EP_NAK);
00929         }
00930         else
00931         {
00932             /* OUT EP */
00933             ep_cnfg[EP].avail_data = 0;
00934             /* reset Data Toggle bit */
00935             ep_ctrl_set_dtog_rx(ep_cnfg[EP].hw, 0);
00936             ep_ctrl_set_stat_rx(ep_cnfg[EP].hw, EP_VALID);
00937         }
00938     }
00939     return USB_OK;
00940 }
00941 
00942 /* Stall both directions of the control EP */
00943 static void usb_ep_set_stall_ctrl(void)
00944 {
00945     ep_cnfg[CTRL_ENP_IN].avail_data = 1;
00946     ep_cnfg[CTRL_ENP_IN].status = STALLED;
00947     ep_cnfg[CTRL_ENP_OUT].avail_data = 0;
00948     ep_cnfg[CTRL_ENP_OUT].status = STALLED;
00949 
00950     usb_ep_set_stall(CTRL_ENP_IN, true);
00951     usb_ep_set_stall(CTRL_ENP_OUT, true);
00952 }
00953 
00954 /*
00955  * Find the position of an interface descriptor inside the configuration
00956  * descriptor.
00957  */
00958 static int usb_find_interface(uint32_t num, uint32_t alt)
00959 {
00960     const UsbInterfaceDesc *id;
00961     int i;
00962 
00963     for (i = 0; ; i++)
00964     {
00965         /* TODO: support more than one configuration per device */
00966         id = (const UsbInterfaceDesc *)usb_dev->config[i];
00967         if (id == NULL)
00968             break;
00969         if (id->bDescriptorType != USB_DT_INTERFACE)
00970             continue;
00971         if ((id->bInterfaceNumber == num) &&
00972                 (id->bAlternateSetting == alt))
00973             return i;
00974     }
00975     return -USB_NODEV_ERROR;
00976 }
00977 
00978 /*
00979  * Configure/deconfigure EPs of a certain interface.
00980  */
00981 static void
00982 usb_configure_ep_interface(unsigned int num, unsigned int alt, bool enable)
00983 {
00984     const UsbEndpointDesc *epd;
00985     int i, start;
00986 
00987     /*
00988      * Find the position of the interface descriptor (inside the
00989      * configuration descriptor).
00990      */
00991     start = usb_find_interface(num, alt);
00992     if (start < 0)
00993     {
00994         LOG_ERR("%s: interface (%u,%u) not found\n",
00995             __func__, num, alt);
00996         return;
00997     }
00998     /*
00999      * Cycle over endpoint descriptors.
01000      *
01001      * NOTE: the first endpoint descriptor is placed next to the interface
01002      * descriptor, so we need to add +1 to the position of the interface
01003      * descriptor to find it.
01004      */
01005     for (i = start + 1; ; i++)
01006     {
01007         epd = (const UsbEndpointDesc *)usb_dev->config[i];
01008         if ((epd == NULL) || (epd->bDescriptorType == USB_DT_INTERFACE))
01009             break;
01010         if (epd->bDescriptorType != USB_DT_ENDPOINT)
01011             continue;
01012         if (UNLIKELY(usb_ep_configure(epd, enable) < 0))
01013         {
01014             LOG_ERR("%s: out of memory, can't initialize EP\n",
01015                 __func__);
01016             return;
01017         }
01018     }
01019 }
01020 
01021 /* Set device state */
01022 static void usb_set_device_state(int state)
01023 {
01024     unsigned int i;
01025 
01026     LOG_INFO("%s: new state %d\n", __func__, state);
01027 
01028     if (udc.state == USB_STATE_CONFIGURED)
01029     {
01030         /* Deconfigure device */
01031         for (i = 0; i < udc.interfaces; ++i)
01032             usb_configure_ep_interface(i,
01033                 udc.alt[i], false);
01034     }
01035     switch (state)
01036     {
01037     case USB_STATE_ATTACHED:
01038     case USB_STATE_POWERED:
01039     case USB_STATE_DEFAULT:
01040         usb_set_address(0);
01041         usb_dev->configured = false;
01042         udc.address = udc.cfg_id = 0;
01043         break;
01044     case USB_STATE_ADDRESS:
01045         udc.cfg_id = 0;
01046         break;
01047     case USB_STATE_CONFIGURED:
01048         /* Configure device */
01049         for (i = 0; i < udc.interfaces; ++i)
01050             usb_configure_ep_interface(i,
01051                 udc.alt[i], true);
01052         break;
01053     default:
01054         /* Unknown state: disconnected or connection in progress */
01055         usb_dev->configured = false;
01056         udc.address = 0;
01057         udc.cfg_id = 0;
01058         break;
01059     }
01060     udc.state = state;
01061 }
01062 
01063 /* Setup packet: set address status phase end handler */
01064 static void usb_add_status_handler_end(UNUSED_ARG(int, EP))
01065 {
01066     uint16_t w_value;
01067 
01068     w_value = usb_le16_to_cpu(setup_packet.wValue);
01069     udc.address = w_value & 0xff;
01070     usb_set_address(udc.address);
01071 
01072     if (udc.address)
01073         usb_set_device_state(USB_STATE_ADDRESS);
01074     else
01075         usb_set_device_state(USB_STATE_DEFAULT);
01076 
01077     __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
01078     __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
01079 }
01080 
01081 /* Prepare status phase */
01082 static void usb_status_phase(bool in)
01083 {
01084     if (in)
01085         __usb_ep_write(CTRL_ENP_IN, NULL, 0, NULL);
01086 }
01087 
01088 /* Setup packet: status phase end handler */
01089 static void usb_status_handler_end(UNUSED_ARG(int, EP))
01090 {
01091     __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
01092     __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
01093 }
01094 
01095 /* Address status handler */
01096 static void usb_status_handler(UNUSED_ARG(int, EP))
01097 {
01098     if (setup_packet.mRequestType & USB_DIR_IN)
01099     {
01100         usb_status_phase(false);
01101         ep_cnfg[CTRL_ENP_OUT].complete = usb_status_handler_end;
01102     }
01103     else
01104     {
01105         usb_status_phase(true);
01106         ep_cnfg[CTRL_ENP_IN].complete =
01107             (setup_packet.bRequest == USB_REQ_SET_ADDRESS) ?
01108                 usb_add_status_handler_end :
01109                 usb_status_handler_end;
01110     }
01111 }
01112 
01113 static void usb_endpointRead_complete(int ep)
01114 {
01115     if (UNLIKELY(ep >= EP_MAX_NUM))
01116     {
01117         ASSERT(0);
01118         return;
01119     }
01120     ASSERT(!(ep & 0x01));
01121 
01122     event_do(&usb_event_done[ep >> 1]);
01123     rx_size = ep_cnfg[ep].size;
01124 }
01125 
01126 ssize_t usb_endpointReadTimeout(int ep, void *buffer, ssize_t size,
01127                 ticks_t timeout)
01128 {
01129     int ep_num = usb_ep_logical_to_hw(ep);
01130     ssize_t max_size = sizeof(ep_buffer[ep_num]);
01131 
01132     /* Non-blocking read for EP0 */
01133     if (in_atomic && (ep_num == CTRL_ENP_OUT))
01134     {
01135         size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
01136         if (UNLIKELY(size > max_size))
01137         {
01138             LOG_ERR("%s: ep_buffer exceeded, try to enlarge CONFIG_USB_BUFSIZE\n",
01139                     __func__);
01140             ASSERT(0);
01141             return -USB_BUF_OVERFLOW;
01142         }
01143         if (!size)
01144             usb_status_handler(ep_num);
01145         else
01146         {
01147             __usb_ep_read(ep_num, ep_buffer[ep_num], size,
01148                     usb_status_handler);
01149             memcpy(buffer, ep_buffer[ep_num], size);
01150         }
01151         return size;
01152     }
01153     if (UNLIKELY(!size))
01154         return 0;
01155     size = MIN(size, max_size);
01156     event_initGeneric(&usb_event_done[ep_num >> 1]);
01157     rx_size = 0;
01158 
01159     /* Blocking read */
01160     __usb_ep_read(ep_num, ep_buffer[ep_num], size,
01161                 usb_endpointRead_complete);
01162     if (timeout < 0)
01163         event_wait(&usb_event_done[ep_num >> 1]);
01164     else
01165         if (!event_waitTimeout(&usb_event_done[ep_num >> 1], timeout))
01166             return 0;
01167     memcpy(buffer, ep_buffer[ep_num], rx_size);
01168 
01169     return rx_size;
01170 }
01171 
01172 static void usb_endpointWrite_complete(int ep)
01173 {
01174     if (UNLIKELY(ep >= EP_MAX_NUM))
01175     {
01176         ASSERT(0);
01177         return;
01178     }
01179     ASSERT(ep & 0x01);
01180 
01181     event_do(&usb_event_done[ep >> 1]);
01182     tx_size = ep_cnfg[ep].size;
01183 }
01184 
01185 ssize_t usb_endpointWriteTimeout(int ep, const void *buffer, ssize_t size,
01186                 ticks_t timeout)
01187 {
01188     int ep_num = usb_ep_logical_to_hw(ep);
01189     ssize_t max_size = sizeof(ep_buffer[ep_num]);
01190 
01191     /* Non-blocking write for EP0 */
01192     if (in_atomic && (ep_num == CTRL_ENP_IN))
01193     {
01194         size = usb_size(size, usb_le16_to_cpu(setup_packet.wLength));
01195         if (UNLIKELY(size > max_size))
01196         {
01197             LOG_ERR("%s: ep_buffer exceeded, try to enlarge CONFIG_USB_BUFSIZE\n",
01198                     __func__);
01199             ASSERT(0);
01200             return -USB_BUF_OVERFLOW;
01201         }
01202         if (!size)
01203             usb_status_handler(ep_num);
01204         else
01205         {
01206             memcpy(ep_buffer[ep_num], buffer, size);
01207             __usb_ep_write(ep_num, ep_buffer[ep_num], size,
01208                     usb_status_handler);
01209         }
01210         return size;
01211     }
01212     if (UNLIKELY(!size))
01213         return 0;
01214     size = MIN(size, max_size);
01215     event_initGeneric(&usb_event_done[ep_num >> 1]);
01216     tx_size = 0;
01217 
01218     /* Blocking write */
01219     memcpy(ep_buffer[ep_num], buffer, size);
01220     __usb_ep_write(ep_num, ep_buffer[ep_num], size,
01221                 usb_endpointWrite_complete);
01222     if (timeout < 0)
01223         event_wait(&usb_event_done[ep_num >> 1]);
01224     else
01225         if (!event_waitTimeout(&usb_event_done[ep_num >> 1], timeout))
01226             return 0;
01227 
01228     return tx_size;
01229 }
01230 
01231 /* Global variable to handle the following non-blocking I/O operations */
01232 static uint32_t InData;
01233 
01234 /* Get device status */
01235 static int usb_send_device_status(uint16_t index)
01236 {
01237     if (index)
01238         return -USB_NODEV_ERROR;
01239 
01240     InData = ((uint32_t)udc.feature) & 0xff;
01241     __usb_ep_write(CTRL_ENP_IN,
01242             (uint8_t *)&InData, sizeof(uint16_t),
01243             usb_status_handler);
01244     return 0;
01245 }
01246 
01247 /* Get interface status */
01248 static int usb_send_interface_status(UNUSED_ARG(uint16_t, index))
01249 {
01250     InData = 0;
01251     __usb_ep_write(CTRL_ENP_IN,
01252             (uint8_t *)&InData, sizeof(uint16_t),
01253             usb_status_handler);
01254     return 0;
01255 }
01256 
01257 /* Get endpoint status */
01258 static int usb_send_ep_status(uint16_t index)
01259 {
01260     if ((index & 0x7F) > 16)
01261         return -USB_NODEV_ERROR;
01262 
01263     InData = 0;
01264     usb_ep_get_stall(usb_ep_logical_to_hw(index), (bool *)&InData);
01265     __usb_ep_write(CTRL_ENP_IN,
01266             (uint8_t *)&InData, sizeof(uint16_t),
01267             usb_status_handler);
01268     return 0;
01269 }
01270 
01271 /* USB setup packet: GET_STATUS request handler */
01272 static void usb_get_status_handler(void)
01273 {
01274     uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
01275     uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
01276     uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
01277 
01278     /* GET_STATUS sanity checks */
01279     if (udc.state < USB_STATE_ADDRESS)
01280     {
01281         LOG_WARN("%s: bad GET_STATUS request (State=%02x)\n",
01282                 __func__, udc.state);
01283         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01284         return;
01285     }
01286     if (w_length != 2)
01287     {
01288         LOG_WARN("%s: bad GET_STATUS request (wLength.Word=%02x)\n",
01289                 __func__, w_length);
01290         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01291         return;
01292     }
01293     if (!(setup_packet.mRequestType & USB_DIR_IN))
01294     {
01295         LOG_WARN("%s: bad GET_STATUS request (mRequestType=%02x)\n",
01296                 __func__, setup_packet.mRequestType);
01297         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01298         return;
01299     }
01300     if (w_value)
01301     {
01302         LOG_WARN("%s: bad GET_STATUS request (wValue=%02x)\n",
01303                 __func__, w_value);
01304         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01305         return;
01306     }
01307 
01308     /* Process GET_STATUS request */
01309     switch (setup_packet.mRequestType & USB_RECIP_MASK)
01310     {
01311     case USB_RECIP_DEVICE:
01312         if (usb_send_device_status(w_index) < 0)
01313         {
01314             LOG_WARN("%s: GET_STATUS: invalid UsbRecipientDevice\n",
01315                     __func__);
01316             ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01317             return;
01318         }
01319         LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientDevice)\n",
01320                 __func__, setup_packet.mRequestType);
01321         break;
01322     case USB_RECIP_INTERFACE:
01323         if (usb_send_interface_status(w_index) < 0)
01324         {
01325             LOG_WARN("%s: GET_STATUS: invalid UsbRecipientInterface\n",
01326                     __func__);
01327             ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01328             return;
01329         }
01330         LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientInterface)\n",
01331                 __func__, setup_packet.mRequestType);
01332         break;
01333     case USB_RECIP_ENDPOINT:
01334         if (usb_send_ep_status(w_index) < 0)
01335         {
01336             LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
01337                     __func__);
01338             ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01339             return;
01340         }
01341         LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientEndpoint)\n",
01342                 __func__, setup_packet.mRequestType);
01343         break;
01344     default:
01345         LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
01346                 __func__);
01347         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01348         break;
01349     }
01350 }
01351 
01352 static int usb_get_device_descriptor(int id)
01353 {
01354     if (id)
01355         return -USB_NODEV_ERROR;
01356 
01357     usb_dev->device->bMaxPacketSize0 = USB_EP0_MAX_SIZE;
01358     __usb_ep_write(CTRL_ENP_IN, (const uint8_t *)usb_dev->device,
01359             usb_size(usb_dev->device->bLength,
01360                 usb_le16_to_cpu(setup_packet.wLength)),
01361             usb_status_handler);
01362     return 0;
01363 }
01364 
01365 /*
01366  * TODO: refactor this part to remove this temporary buffer.
01367  *
01368  * It would be better to define all the USB descriptors in the right order and
01369  * send them as a contiguous buffer directly from the flash / rodata memory.
01370  */
01371 #define USB_BUFSIZE (128)
01372 static uint8_t usb_cfg_buffer[USB_BUFSIZE];
01373 STATIC_ASSERT(USB_BUFSIZE < (1 << (sizeof(uint16_t) * 8)));
01374 
01375 static int usb_get_configuration_descriptor(int id)
01376 {
01377     const UsbConfigDesc **config =
01378             (const UsbConfigDesc **)usb_dev->config;
01379     uint8_t *p = usb_cfg_buffer;
01380     int i;
01381 
01382     /* TODO: support more than one configuration per device */
01383     if (UNLIKELY(id > 0))
01384         return -USB_NODEV_ERROR;
01385 
01386     for (i = 0; config[i]; i++)
01387     {
01388         memcpy(p, config[i], config[i]->bLength);
01389         p += config[i]->bLength;
01390 
01391         if (UNLIKELY((p - usb_cfg_buffer) > USB_BUFSIZE))
01392         {
01393             ASSERT(0);
01394             return -USB_BUF_OVERFLOW;
01395         }
01396     }
01397     ((UsbConfigDesc *)usb_cfg_buffer)->wTotalLength =
01398             usb_cpu_to_le16((uint16_t)(p - usb_cfg_buffer));
01399     __usb_ep_write(CTRL_ENP_IN,
01400             usb_cfg_buffer,
01401             usb_size(p - usb_cfg_buffer,
01402                 usb_le16_to_cpu(setup_packet.wLength)),
01403             usb_status_handler);
01404     return 0;
01405 }
01406 
01407 static int usb_get_string_descriptor(unsigned int id)
01408 {
01409     const UsbStringDesc *lang_str;
01410     unsigned int lang_id, str_id;
01411     uint16_t w_index_lo = usb_le16_to_cpu(setup_packet.wIndex) & 0x00ff;
01412     uint16_t w_index_hi = (usb_le16_to_cpu(setup_packet.wIndex) &
01413                         0xff00) >> 8;
01414 
01415     ASSERT(usb_dev->strings != NULL);
01416     ASSERT(usb_dev->strings[0] != NULL);
01417 
01418     lang_str = usb_dev->strings[0];
01419     if (id)
01420     {
01421         /* Find Language index */
01422         for (lang_id = 0; ; lang_id++)
01423         {
01424             const UsbStringDesc *str =
01425                         usb_dev->strings[lang_id];
01426             if (UNLIKELY(str == NULL))
01427                 return -USB_NODEV_ERROR;
01428             if ((str->data[0] == w_index_lo) &&
01429                     (str->data[1] == w_index_hi))
01430                 break;
01431         }
01432         /* Check buffer overflow to find string index */
01433         for (str_id = 0; str_id < id; str_id++)
01434         {
01435             lang_str = usb_dev->strings[lang_id + 1 + str_id];
01436             if (lang_str == NULL)
01437                 return -USB_NODEV_ERROR;
01438         }
01439     }
01440     __usb_ep_write(CTRL_ENP_IN,
01441             lang_str,
01442             usb_size(lang_str->bLength,
01443                 usb_le16_to_cpu(setup_packet.wLength)),
01444             usb_status_handler);
01445     return 0;
01446 }
01447 
01448 static void usb_get_descriptor(void)
01449 {
01450     uint16_t w_value_lo = usb_le16_to_cpu(setup_packet.wValue) & 0x00ff;
01451     uint16_t w_value_hi = (usb_le16_to_cpu(setup_packet.wValue) & 0xff00) >> 8;
01452 
01453     if (udc.state < USB_STATE_DEFAULT)
01454     {
01455         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01456         return;
01457     }
01458     switch (w_value_hi)
01459     {
01460     case USB_DT_DEVICE:
01461         LOG_INFO("%s: GET_DEVICE_DESCRIPTOR: id=%d, state=%d\n",
01462                 __func__,
01463                 w_value_lo,
01464                 udc.state);
01465         if (usb_get_device_descriptor(w_value_lo) < 0)
01466             ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01467         break;
01468     case USB_DT_CONFIG:
01469         LOG_INFO("%s: GET_CONFIG_DESCRIPTOR: id=%d, state=%d\n",
01470                 __func__, w_value_lo, udc.state);
01471         if (usb_get_configuration_descriptor(w_value_lo) < 0)
01472             ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01473         break;
01474     case USB_DT_STRING:
01475         LOG_INFO("%s: GET_STRING_DESCRIPTOR: id=%d, state=%d\n",
01476                 __func__, w_value_lo, udc.state);
01477         if (usb_get_string_descriptor(w_value_lo) < 0)
01478             ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01479         break;
01480     default:
01481         LOG_WARN("%s: GET_UNKNOWN_DESCRIPTOR: id=%d, state=%d\n",
01482                 __func__, w_value_lo, udc.state);
01483         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01484         break;
01485     }
01486 }
01487 
01488 /* USB setup packet: class/vendor request handler */
01489 static void usb_event_handler(UsbDevice *dev)
01490 {
01491     /*
01492      * TODO: get the appropriate usb_dev in function of the endpoint
01493      * address.
01494      */
01495     if (dev->event_cb)
01496         dev->event_cb(&setup_packet);
01497 }
01498 
01499 /* USB setup packet: GET_DESCRIPTOR handler */
01500 static void usb_get_descriptor_handler(void)
01501 {
01502     LOG_INFO("%s: GET_DESCRIPTOR: RECIP = %d\n",
01503             __func__,
01504             setup_packet.mRequestType & USB_RECIP_MASK);
01505     if ((setup_packet.mRequestType & USB_RECIP_MASK) ==
01506             USB_RECIP_DEVICE)
01507         usb_get_descriptor();
01508     else
01509         usb_event_handler(usb_dev);
01510 }
01511 
01512 /* USB setup packet: SET_ADDRESS handler */
01513 static void usb_set_address_handler(void)
01514 {
01515     uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
01516     uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
01517     uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
01518 
01519     LOG_INFO("%s: SET_ADDRESS: %d\n",
01520             __func__, usb_le16_to_cpu(setup_packet.wValue));
01521     if ((udc.state >= USB_STATE_DEFAULT) &&
01522             ((setup_packet.mRequestType & USB_RECIP_MASK) ==
01523                     USB_RECIP_DEVICE) &&
01524             (w_index == 0) && (w_length == 0) && (w_value < 128))
01525         usb_status_handler(CTRL_ENP_IN);
01526     else
01527         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01528 }
01529 
01530 /* USB setup packet: GET_CONFIGURATION handler */
01531 static void usb_get_config_handler(void)
01532 {
01533     uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
01534     uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
01535 
01536     LOG_INFO("%s: GET_CONFIGURATION\n", __func__);
01537     if ((udc.state >= USB_STATE_ADDRESS) &&
01538             (w_value == 0) && (w_index == 0) && (w_value == 1))
01539     {
01540         InData = udc.cfg_id;
01541         __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 1, usb_status_handler);
01542     }
01543     else
01544         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01545 }
01546 
01547 static const UsbConfigDesc *usb_find_configuration(int num)
01548 {
01549     const UsbConfigDesc *cfg;
01550     int i;
01551 
01552     for (i = 0; ; i++)
01553     {
01554         cfg = (const UsbConfigDesc *)usb_dev->config[i];
01555         if (cfg == NULL)
01556             break;
01557         if (cfg->bDescriptorType != USB_DT_CONFIG)
01558             continue;
01559         if (cfg->bConfigurationValue == num)
01560             return cfg;
01561     }
01562     return NULL;
01563 }
01564 
01565 static int usb_set_config_state(uint32_t conf)
01566 {
01567     const UsbConfigDesc *pCnfg;
01568     unsigned int i;
01569 
01570     if (conf)
01571     {
01572         /* Find configuration descriptor */
01573         pCnfg = usb_find_configuration(conf);
01574         if (pCnfg == NULL)
01575             return -USB_NODEV_ERROR;
01576 
01577         /* Reset current configuration */
01578         usb_set_device_state(USB_STATE_ADDRESS);
01579         usb_dev->configured = false;
01580         udc.cfg = pCnfg;
01581 
01582         /* Set Interface and Alternative Setting */
01583         udc.cfg_id = conf;
01584         /* Set self-powered state */
01585         if (pCnfg->bmAttributes & USB_CONFIG_ATT_SELFPOWER)
01586             udc.feature |= STM32_UDC_FEATURE_SELFPOWERED;
01587 
01588         /* Configure all existing interfaces to alternative setting 0 */
01589         ASSERT(pCnfg->bNumInterfaces <= USB_MAX_INTERFACE);
01590         udc.interfaces = pCnfg->bNumInterfaces;
01591         for (i = 0; i < udc.interfaces; i++)
01592             udc.alt[i] = 0;
01593         usb_set_device_state(USB_STATE_CONFIGURED);
01594         usb_dev->configured = true;
01595         event_do(&usb_event_done[0]);
01596         LOG_INFO("%s: device configured\n", __func__);
01597     }
01598     else
01599     {
01600         usb_dev->configured = false;
01601         usb_set_device_state(USB_STATE_ADDRESS);
01602     }
01603     return 0;
01604 }
01605 
01606 /* USB setup packet: SET_CONFIGURATION handler */
01607 static void usb_set_config_handler(void)
01608 {
01609     uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
01610     uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
01611     uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
01612 
01613     LOG_INFO("%s: SET_CONFIGURATION: %d\n",
01614             __func__, w_value);
01615     if ((udc.state >= USB_STATE_ADDRESS) &&
01616             (w_index == 0) && (w_length == 0) &&
01617             (usb_set_config_state(w_value & 0xff) == 0))
01618         usb_status_handler(CTRL_ENP_OUT);
01619     else
01620         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01621 }
01622 
01623 /* USB setup packet: standard request handler */
01624 static void usb_standard_request_handler(void)
01625 {
01626     switch (setup_packet.bRequest)
01627     {
01628     case USB_REQ_GET_STATUS:
01629         usb_get_status_handler();
01630         break;
01631     case USB_REQ_CLEAR_FEATURE:
01632         LOG_INFO("%s: bRequest=%d (CLEAR_FEATURE)\n",
01633                 __func__, setup_packet.bRequest);
01634         break;
01635     case USB_REQ_SET_FEATURE:
01636         LOG_INFO("%s: bRequest=%d (SET_FEATURE)\n",
01637                 __func__, setup_packet.bRequest);
01638         break;
01639     case USB_REQ_SET_ADDRESS:
01640         usb_set_address_handler();
01641         break;
01642     case USB_REQ_GET_DESCRIPTOR:
01643         usb_get_descriptor_handler();
01644         break;
01645     case USB_REQ_SET_DESCRIPTOR:
01646         LOG_INFO("%s: bRequest=%d (SET_DESCRIPTOR)\n",
01647                 __func__, setup_packet.bRequest);
01648         break;
01649     case USB_REQ_GET_CONFIGURATION:
01650         usb_get_config_handler();
01651         break;
01652     case USB_REQ_SET_CONFIGURATION:
01653         usb_set_config_handler();
01654         break;
01655     case USB_REQ_GET_INTERFACE:
01656         LOG_INFO("%s: bRequest=%d (GET_INTERFACE)\n",
01657                 __func__, setup_packet.bRequest);
01658         break;
01659     case USB_REQ_SET_INTERFACE:
01660         LOG_INFO("%s: bRequest=%d (SET_INTERFACE)\n",
01661                 __func__, setup_packet.bRequest);
01662         break;
01663     case USB_REQ_SYNCH_FRAME:
01664         LOG_INFO("%s: bRequest=%d (SYNCH_FRAME)\n",
01665                 __func__, setup_packet.bRequest);
01666         break;
01667     default:
01668         LOG_WARN("%s: bRequest=%d (Unknown)\n",
01669                 __func__, setup_packet.bRequest);
01670         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01671         break;
01672     }
01673 }
01674 
01675 /* USB setup packet handler */
01676 static void usb_setup_handler(void)
01677 {
01678     switch (setup_packet.mRequestType & USB_TYPE_MASK)
01679     {
01680     /* Standard */
01681     case USB_TYPE_STANDARD:
01682         LOG_INFO("%s: bmRequestType=%02x (Standard)\n",
01683                 __func__, setup_packet.mRequestType);
01684         usb_standard_request_handler();
01685         break;
01686     /* Class */
01687     case USB_TYPE_CLASS:
01688         LOG_INFO("%s: bmRequestType=%02x (Class)\n",
01689                 __func__, setup_packet.mRequestType);
01690         usb_event_handler(usb_dev);
01691         break;
01692     /* Vendor */
01693     case USB_TYPE_VENDOR:
01694         LOG_INFO("%s: bmRequestType=%02x (Vendor)\n",
01695                 __func__, setup_packet.mRequestType);
01696         usb_event_handler(usb_dev);
01697         break;
01698     case USB_TYPE_RESERVED:
01699         LOG_INFO("%s: bmRequestType=%02x (Reserved)\n",
01700                 __func__, setup_packet.mRequestType);
01701         break;
01702     /* Other */
01703     default:
01704         LOG_WARN("%s: bmRequestType=%02x (Unknown)\n",
01705                 __func__, setup_packet.mRequestType);
01706         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
01707         break;
01708     }
01709 }
01710 
01711 /* USB: low-level hardware initialization */
01712 static void usb_hw_reset(void)
01713 {
01714     unsigned int i;
01715     int ret;
01716 
01717     /* Initialize endpoint descriptors */
01718     for (i = 0; i < countof(ep_cnfg); i++)
01719         ep_cnfg[i].hw = NULL;
01720 
01721     /* Initialize USB memory */
01722     for (i = 0; i < countof(memory_buffer); i++)
01723         memory_buffer[i].Size = 0;
01724     usb->BTABLE = USB_BDT_OFFSET;
01725     mem_use = NULL;
01726 
01727     /* Endpoint initialization */
01728     ret = usb_ep_configure(&USB_CtrlEpDescr0, true);
01729     if (UNLIKELY(ret < 0))
01730     {
01731         LOG_WARN("%s: out of memory, cannot initialize EP0\n",
01732                 __func__);
01733         return;
01734     }
01735     ret = usb_ep_configure(&USB_CtrlEpDescr1, true);
01736     if (UNLIKELY(ret < 0))
01737     {
01738         LOG_WARN("%s: out of memory, cannot initialize EP1\n",
01739                 __func__);
01740         return;
01741     }
01742 
01743     /* Set default address */
01744     usb_set_address(0);
01745 
01746     /* Enable all the device interrupts */
01747     usb->CNTR = bmCTRM | bmRESETM | bmSOFM | bmERRM | bmPMAOVRM |
01748             bmSUSPM | bmWKUPM;
01749 }
01750 
01751 /* Handle a correct transfer under ISR */
01752 static void usb_isr_correct_transfer(stm32_usb_irq_status_t interrupt)
01753 {
01754     int EP;
01755     reg32_t *pReg = (reg32_t *)&usb->EP0R;
01756 
01757     /* Find corresponding EP */
01758     pReg += interrupt.EP_ID;
01759     EP = (int)(((*pReg & 0x0f) << 1) + (interrupt.DIR ? 0 : 1));
01760     ep_cnfg[EP].avail_data = 1;
01761 
01762     ASSERT(ep_cnfg[EP].hw);
01763     /* IN EP */
01764     if (EP & 0x01)
01765         ep_ctrl_clr_ctr_tx(ep_cnfg[EP].hw);
01766     else
01767         ep_ctrl_clr_ctr_rx(ep_cnfg[EP].hw);
01768     if (EP == CTRL_ENP_OUT)
01769     {
01770         /* Determinate type of packet (only for control EP) */
01771         bool SetupPacket = ep_ctrl_get_setup(ep_cnfg[CTRL_ENP_OUT].hw);
01772 
01773         if (SetupPacket)
01774         {
01775             ep_cnfg[CTRL_ENP_IN].avail_data = 1;
01776             /* init IO to receive Setup packet */
01777             __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
01778             __usb_ep_read(CTRL_ENP_OUT, &setup_packet,
01779                     sizeof(setup_packet), NULL);
01780 
01781             /* reset EP IO ctrl */
01782             if (setup_packet.mRequestType & USB_DIR_IN)
01783                 usb_status_handler(CTRL_ENP_OUT);
01784             usb_setup_handler();
01785             if (ep_cnfg[CTRL_ENP_OUT].status == STALLED)
01786                 usb_ep_set_stall_ctrl();
01787         }
01788         else
01789         {
01790             if (ep_cnfg[CTRL_ENP_OUT].complete &&
01791                     setup_packet.mRequestType & USB_DIR_IN)
01792                 ep_cnfg[CTRL_ENP_OUT].complete(CTRL_ENP_OUT);
01793             else
01794                 __usb_ep_io(EP);
01795         }
01796     }
01797     else if (EP == CTRL_ENP_IN)
01798     {
01799         if (ep_cnfg[CTRL_ENP_IN].complete &&
01800                 !(setup_packet.mRequestType & USB_DIR_IN))
01801             ep_cnfg[CTRL_ENP_IN].complete(CTRL_ENP_IN);
01802         else
01803             __usb_ep_io(EP);
01804 
01805     }
01806     else
01807         __usb_ep_io(EP);
01808 }
01809 
01810 /* USB: interrupt service routine */
01811 static void usb_isr(void)
01812 {
01813     stm32_usb_irq_status_t interrupt;
01814 
01815     /* Get masked interrupt flags */
01816     interrupt.status = usb->ISTR;
01817     interrupt.status &= usb->CNTR | 0x1f;
01818 
01819     /* Set the context as atomic */
01820     in_atomic = true;
01821 
01822     if (interrupt.PMAOVR)
01823     {
01824         LOG_WARN("%s: DMA overrun / underrun\n", __func__);
01825         usb->ISTR = ~bmPMAOVRM;
01826     }
01827     if (interrupt.ERR)
01828     {
01829         LOG_WARN("%s: engine error\n", __func__);
01830         usb->ISTR = ~bmERRM;
01831     }
01832     if (interrupt.RESET)
01833     {
01834         LOG_INFO("%s: device reset\n", __func__);
01835         usb->ISTR = ~bmRESETM;
01836         usb_hw_reset();
01837         usb_set_device_state(USB_STATE_DEFAULT);
01838     }
01839     if (interrupt.SOF)
01840     {
01841 #if 0
01842         /*
01843          * XXX: disable logging of frame interrupts (too much noise!)
01844          */
01845         uint16_t frame_nr = usb->FNR & 0x0fff;
01846         LOG_INFO("%s: frame %#x\n", __func__, frame_nr);
01847 #endif
01848         usb->ISTR = ~bmSOFM;
01849     }
01850     if (interrupt.WKUP)
01851     {
01852         LOG_INFO("%s: wake-up\n", __func__);
01853         usb->ISTR = ~(bmSUSPM | bmWKUPM);
01854         usb_resume();
01855     }
01856     if (interrupt.SUSP)
01857     {
01858         LOG_INFO("%s: suspend\n", __func__);
01859         usb_suspend();
01860         usb->ISTR = ~(bmSUSPM | bmWKUPM);
01861     }
01862     if (interrupt.ESOF)
01863     {
01864         LOG_INFO("%s: expected frame\n", __func__);
01865         usb->ISTR = ~bmESOFM;
01866     }
01867     if (interrupt.CTR)
01868     {
01869         usb_isr_correct_transfer(interrupt);
01870     }
01871     in_atomic = false;
01872 }
01873 
01874 /* USB: hardware initialization */
01875 static void usb_hw_init(void)
01876 {
01877     /* Enable clocking on the required GPIO pins */
01878     RCC->APB2ENR |= RCC_APB2_GPIOA | RCC_APB2_GPIOC;
01879 
01880     /* Make sure that the CAN controller is disabled and held in reset */
01881     RCC->APB1ENR &= ~RCC_APB1_CAN;
01882 
01883     /* Configure USB_DM and USB_DP to work as USB lines */
01884     stm32_gpioPinConfig((struct stm32_gpio *)GPIOA_BASE,
01885             USB_DM_PIN | USB_DP_PIN,
01886             GPIO_MODE_AF_PP, GPIO_SPEED_50MHZ);
01887     /* Configure USB_DISC to work as USB disconnect */
01888     stm32_gpioPinConfig((struct stm32_gpio *)GPIOC_BASE,
01889             USB_DISC_PIN,
01890             GPIO_MODE_OUT_PP, GPIO_SPEED_50MHZ);
01891     stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE,
01892                 USB_DISC_PIN, 1);
01893 
01894     /* Ensure the USB clock is disabled before setting the prescaler */
01895     RCC->APB1ENR &= ~RCC_APB1_USB;
01896 
01897     /* Configure USB clock (48MHz) */
01898     *CFGR_USBPRE_BB &= ~RCC_USBCLK_PLLCLK_1DIV5;
01899 
01900     /* Activate USB clock */
01901     RCC->APB1ENR |= RCC_APB1_USB;
01902 
01903     /* Force USB reset and disable USB interrupts */
01904     usb->CNTR = bmFRES;
01905     timer_delayHp(1);
01906 
01907     /* Issue a USB reset */
01908     usb_hw_reset();
01909 
01910     /* Clear spurious pending interrupt */
01911     usb->ISTR = 0;
01912 
01913     /* Register interrupt handler */
01914     sysirq_setHandler(USB_LP_CAN_RX0_IRQHANDLER, usb_isr);
01915 
01916     /* Software connection enable */
01917     usb_connect();
01918 }
01919 
01920 /* Initialize the USB controller */
01921 static void usb_init(void)
01922 {
01923     udc.state = USB_STATE_NOTATTACHED;
01924     udc.feature = 0;
01925 
01926     usb_hw_init();
01927 }
01928 
01929 /* Register an upper layer USB device into the driver */
01930 int usb_deviceRegister(UsbDevice *dev)
01931 {
01932 #if CONFIG_KERN
01933     MOD_CHECK(proc);
01934 #endif
01935     usb_dev = dev;
01936     usb_dev->configured = false;
01937 
01938     event_initGeneric(&usb_event_done[0]);
01939     usb_init();
01940     event_wait(&usb_event_done[0]);
01941 
01942     return 0;
01943 }