ef1abda2aec54ad33d3fb1d220b7fefe41d021be
[bertos.git] / bertos / cpu / cortex-m3 / drv / usb_stm32.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
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.
10  *
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.
15  *
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
19  *
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.
28  *
29  * Copyright 2010 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \brief STM32 USB driver
34  *
35  * \author Andrea Righi <arighi@develer.com>
36  */
37
38 #include "cfg/cfg_usb.h"
39
40 #define LOG_LEVEL  USB_LOG_LEVEL
41 #define LOG_FORMAT USB_LOG_FORMAT
42
43 #include <cfg/log.h>
44 #include <cfg/debug.h>
45 #include <cfg/macros.h>
46 #include <cfg/module.h>
47
48 #include <cpu/irq.h>
49 #include <cpu/power.h>
50
51 #include <drv/irq_cm3.h>
52 #include <drv/gpio_stm32.h>
53 #include <drv/clock_stm32.h>
54 #include <drv/timer.h>
55 #include <drv/usb.h>
56
57 #include <string.h> /* memcpy() */
58
59 #include "usb_stm32.h"
60
61 #define ALIGN_UP(value, align)  (((value) & ((align) - 1)) ? \
62                                 (((value) + ((align) - 1)) & ~((align) - 1)) : \
63                                 (value))
64 /* STM32 USB registers */
65 struct stm32_usb
66 {
67         reg32_t EP0R;
68         reg32_t EP1R;
69         reg32_t EP2R;
70         reg32_t EP3R;
71         reg32_t EP4R;
72         reg32_t EP5R;
73         reg32_t EP6R;
74         reg32_t EP7R;
75         reg32_t __reserved[8];
76         reg32_t CNTR;
77         reg32_t ISTR;
78         reg32_t FNR;
79         reg32_t DADDR;
80         reg32_t BTABLE;
81 };
82
83 /* Hardware registers */
84 static struct stm32_usb *usb = (struct stm32_usb *)USB_BASE_ADDR;
85
86 /* Endpoint descriptors: used for handling requests to use with endpoints */
87 static stm32_usb_ep_t ep_cnfg[ENP_MAX_NUMB];
88
89 /* USB EP0 control descriptor */
90 static const usb_endpoint_descriptor_t USB_CtrlEpDescr0 =
91 {
92         .bLength = sizeof(USB_CtrlEpDescr0),
93         .bDescriptorType = USB_DT_ENDPOINT,
94         .bEndpointAddress = USB_DIR_OUT | 0,
95         .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
96         .wMaxPacketSize = USB_EP0_MAX_SIZE,
97         .bInterval = 0,
98 };
99
100 /* USB EP1 control descriptor */
101 static const usb_endpoint_descriptor_t USB_CtrlEpDescr1 =
102 {
103         .bLength = sizeof(USB_CtrlEpDescr1),
104         .bDescriptorType = USB_DT_ENDPOINT,
105         .bEndpointAddress = USB_DIR_IN | 0,
106         .bmAttributes = USB_ENDPOINT_XFER_CONTROL,
107         .wMaxPacketSize = USB_EP0_MAX_SIZE,
108         .bInterval = 0,
109 };
110
111 /* USB setup packet */
112 static usb_ctrlrequest_t setup_packet;
113
114 /* USB device controller: max supported interfaces */
115 #define USB_MAX_INTERFACE       1
116
117 /* USB device controller features */
118 #define STM32_UDC_FEATURE_SELFPOWERED   BV(0)
119 #define STM32_UDC_FEATURE_REMOTE_WAKEUP BV(1)
120
121 /* Hardware-specific USB device controller structure */
122 typedef struct stm32_udc
123 {
124         uint8_t state;
125         uint32_t cfg_id;
126         const usb_config_descriptor_t *cfg;
127         uint32_t interfaces;
128         uint32_t alt[USB_MAX_INTERFACE];
129         uint32_t address;
130         uint8_t feature;
131 } PACKED stm32_udc_t;
132
133 /* Hardware-specific USB Device Controller */
134 static stm32_udc_t udc;
135
136 /* Generic USB Device Controller structure */
137 static struct usb_device *usb_dev;
138
139 /* USB packet memory management: list of allocated chunks */
140 static pack_mem_slot_t *pPacketMemUse;
141
142 /* USB packet memory management: memory buffer metadata */
143 #define EP_MAX_SLOTS    16
144 static pack_mem_slot_t PacketMemBuff[EP_MAX_SLOTS];
145
146 /* Allocate a free block of the packet memory */
147 static pack_mem_slot_t *usb_malloc(void)
148 {
149         unsigned int i;
150
151         for (i = 0; i < countof(PacketMemBuff); i++)
152                 if (PacketMemBuff[i].Size == 0)
153                         return &PacketMemBuff[i];
154         return NULL;
155 }
156
157 /* Release a block of the packet memory */
158 static void usb_free(pack_mem_slot_t *pPntr)
159 {
160         pPntr->Size = 0;
161 }
162
163 /* Allocate a free chunk of the packet memory (inside a block) */
164 static bool USB_AllocateBuffer(uint16_t *pOffset, uint32_t *pPacketSize,
165                             int EndPoint)
166 {
167         pack_mem_slot_t *pPacketMem = pPacketMemUse,
168                         *pPacketMemNext, *pPacketMemUseNew;
169         uint32_t MaxPacketSize = *pPacketSize;
170
171         /*
172          * Packet size alignment:
173          *  - fine-granularity allocation: size alignment by 2;
174          *  - coarse-granularity allocation: size alignment by 32.
175          */
176         if (MaxPacketSize < 62)
177                 MaxPacketSize = ALIGN_UP(MaxPacketSize, 2);
178         else
179                 MaxPacketSize = ALIGN_UP(MaxPacketSize, 32);
180         /*
181          * Finding free memory chunks from the allocated blocks of the USB
182          * packet memory.
183          */
184         *pOffset = 0;
185         while (pPacketMem != NULL)
186         {
187                 /* Offset alignment by 4 */
188                 *pOffset = ALIGN_UP(pPacketMem->Start + pPacketMem->Size, 4);
189                 pPacketMemNext = pPacketMem->next;
190                 if ((pPacketMem->next == NULL) ||
191                                 (pPacketMemNext->Start >=
192                                         *pOffset + MaxPacketSize))
193                         break;
194                 pPacketMem = pPacketMem->next;
195         }
196         /* Check for out-of-memory condition */
197         if ((*pOffset + MaxPacketSize) >= USB_BDT_OFFSET)
198                 return false;
199         /*
200          * Allocate a new memory block, next to the last allocated block.
201          */
202         pPacketMemUseNew = usb_malloc();
203         if (pPacketMemUseNew == NULL)
204                 return false;
205         /* Insert the block to the list of allocated blocks */
206         if (pPacketMemUse == NULL)
207         {
208                 pPacketMemUse = pPacketMemUseNew;
209                 pPacketMemUse->next = NULL;
210         }
211         else
212         {
213                 pPacketMemUseNew->next = pPacketMem->next;
214                 pPacketMem->next = pPacketMemUseNew;
215         }
216         /* Update block's metadata */
217         pPacketMemUseNew->ep_addr = EndPoint;
218         pPacketMemUseNew->Start = *pOffset;
219         pPacketMemUseNew->Size = MaxPacketSize;
220
221         *pPacketSize = MaxPacketSize;
222
223         return true;
224 }
225
226 /* Release a chunk of the packet memory (inside a block) */
227 static void USB_ReleaseBuffer(int EndPoint)
228 {
229         pack_mem_slot_t *pPacketMem, *pPacketMemPrev = NULL;
230         pPacketMem = pPacketMemUse;
231
232         while (pPacketMem != NULL)
233         {
234                 if (pPacketMem->ep_addr == EndPoint)
235                 {
236                         if (UNLIKELY(pPacketMemPrev == NULL))
237                         {
238                                 /* Free the first element of the list */
239                                 pPacketMemUse = pPacketMemUse->next;
240                                 usb_free(pPacketMem);
241                                 pPacketMem = pPacketMemUse;
242                                 continue;
243                         }
244                         pPacketMemPrev->next = pPacketMem->next;
245                         usb_free(pPacketMem);
246                 }
247                 else
248                         pPacketMemPrev = pPacketMem;
249                 pPacketMem = pPacketMemPrev->next;
250         }
251 }
252
253 /*-------------------------------------------------------------------------*/
254
255 /* Connect USB controller */
256 static void usb_connect(void)
257 {
258         stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE, 1 << 11, 0);
259 }
260
261 /* Set USB device address */
262 static void usb_set_address(uint32_t addr)
263 {
264         usb->DADDR = addr | 0x80;
265 }
266
267 /* Suspend USB controller */
268 static void usb_suspend(void)
269 {
270         usb->CNTR |= bmFSUSP | bmLPMODE;
271 }
272
273 /* Resume USB controller */
274 static void usb_resume(void)
275 {
276         uint32_t line_status;
277
278         line_status = usb->FNR & 0xc000;
279         if (!line_status)
280                 return;
281         /* check for noise and eventually return to sleep */
282         if (line_status == 0xc000)
283                 usb_suspend();
284         else
285                 usb->CNTR &= ~(bmFSUSP | bmLPMODE);
286 }
287
288 /* Convert logical EP address to physical EP address */
289 static int USB_EpLogToPhysAdd(uint8_t ep_addr)
290 {
291         int addr = (ep_addr & 0x0f) << 1;
292         return (ep_addr & 0x80) ? addr + 1 : addr;
293 }
294
295 /* Set EP address */
296 static void EpCtrlSet_EA(reg32_t *reg, uint32_t val)
297 {
298         val &= 0x0f;
299         val |= *reg & 0x0700;
300         val |= USB_CTRL_CLEAR_ONLY_MASK;
301         *reg = val;
302 }
303
304 /* Get EP IN status */
305 static uint32_t EpCtrlGet_STAT_TX(reg32_t *reg)
306 {
307         return (*reg & (0x3UL << 4)) >> 4;
308 }
309
310 /* Set EP IN state */
311 static void EpCtrlSet_STAT_TX(reg32_t *reg, ep_state_t val)
312 {
313         uint32_t state;
314         int i;
315
316         /*
317          * The EP can change state between read and write operations from VALID
318          * to NAK and result of set operation will be invalid.
319          */
320         for (i = 0; i < 2; i++)
321         {
322                 if (EpCtrlGet_STAT_TX(reg) == val)
323                         return;
324                 state = val;
325                 state <<= 4;
326                 state ^= *reg;
327                 state |= USB_CTRL_CLEAR_ONLY_MASK;
328                 /* Clear the toggle bits without STAT_TX (4,5) */
329                 state &= ~0x7040;
330                 *reg = state;
331         }
332 }
333
334 /* Set EP DTOG_TX bit (IN) */
335 static void EpCtrlSet_DTOG_TX(reg32_t *reg, uint32_t val)
336 {
337         val = val ? (*reg ^ (1UL << 6)) : *reg;
338         /* Clear the toggle bits without DTOG_TX (6) */
339         val &= ~0x7030;
340         val |= USB_CTRL_CLEAR_ONLY_MASK;
341         *reg = val;
342 }
343
344 /* Clear EP CTR_TX bit (IN) */
345 static void EpCtrlClr_CTR_TX(reg32_t *reg)
346 {
347         uint32_t val = *reg;
348
349         val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 7);
350         /* Set RX_CTR */
351         val |= 1UL << 15;
352         *reg = val;
353 }
354
355 /* Clear EP CTR_RX bit (OUT) */
356 static void EpCtrlClr_CTR_RX(reg32_t *reg)
357 {
358         uint32_t val = *reg;
359         val &= ~(USB_CTRL_TOGGLE_MASK | 1UL << 15);
360         /* Set TX_CTR */
361         val |= 1UL << 7;
362         *reg = val;
363 }
364
365 /* Set EP KIND bit */
366 static void EpCtrlSet_EP_KIND(reg32_t *reg, uint32_t val)
367 {
368         val = val ? (1UL << 8) : 0;
369         val |= *reg & ~(USB_CTRL_TOGGLE_MASK | (1UL << 8));
370         val |= USB_CTRL_CLEAR_ONLY_MASK;
371         *reg = val;
372 }
373
374 /* Set EP type */
375 static int EpCtrlSet_EP_TYPE(reg32_t *reg, uint8_t val)
376 {
377         uint32_t type;
378
379         if (UNLIKELY(val >= EP_TYPE_MAX))
380         {
381                 ASSERT(0);
382                 return USB_INVAL_ERROR;
383         }
384         type = val;
385         type <<= 9;
386         type |= *reg & ~(USB_CTRL_TOGGLE_MASK | (0x3UL << 9));
387         type |= USB_CTRL_CLEAR_ONLY_MASK;
388         *reg = type;
389
390         return USB_OK;
391 }
392
393 /* Get EP STAT_RX (OUT) */
394 static uint32_t EpCtrlGet_STAT_RX(reg32_t *reg)
395 {
396         uint32_t val = *reg & (0x3UL << 12);
397         return val >> 12;
398 }
399
400 /* Set EP STAT_RX (OUT) */
401 static void EpCtrlSet_STAT_RX(reg32_t *reg, ep_state_t val)
402 {
403         uint32_t state;
404         int i;
405
406         /*
407          * The EP can change state between read and write operations from VALID
408          * to NAK and result of set operation will be invalid.
409          */
410         for (i = 0; i < 2; i++)
411         {
412                 if (EpCtrlGet_STAT_RX(reg) == val)
413                         return;
414                 state = val;
415                 state <<= 12;
416                 state ^= *reg;
417                 state |= USB_CTRL_CLEAR_ONLY_MASK;
418                 /* Clear the toggle bits without STAT_RX (12,13) */
419                 state &= ~0x4070;
420                 *reg = state;
421         }
422 }
423
424 /* Set DTOG_RX bit */
425 static void EpCtrlSet_DTOG_RX(reg32_t *reg, uint32_t val)
426 {
427         val = val ? (*reg ^ (1UL << 14)) : *reg;
428         /* Clear the toggle bits without DTOG_RX (14) */
429         val &= ~0x3070;
430         val |= USB_CTRL_CLEAR_ONLY_MASK;
431         *reg = val;
432 }
433
434 /* Get EP SETUP bit */
435 static uint32_t EpCtrlGet_SETUP(reg32_t *reg)
436 {
437         uint32_t val = *reg & (1UL << 11);
438         return val ? 1 : 0;
439 }
440
441 /* Core endpoint I/O function */
442 static void __usb_ep_io(int EP)
443 {
444         ssize_t Count, CountHold, Offset;
445         uint32_t *pDst, *pSrc, Data;
446         bool CurrentBuffer;
447         stm32_usb_ep_t *epd = &ep_cnfg[EP];
448
449         ASSERT(epd->hw);
450         if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
451                 return;
452
453         if (EP & 0x01)
454         {
455                 /* EP IN */
456                 Count = epd->size - epd->offset;
457                 while (epd->avail_data)
458                 {
459                         if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
460                                 break;
461
462                         /* Set Status */
463                         epd->status = BEGIN_SERVICED;
464                         /* Get data size */
465                         if ((epd->flags & STM32_USB_EP_ZERO_PACKET) &&
466                                         (Count == epd->max_size))
467                                 epd->flags |= STM32_USB_EP_ZERO_PACKET |
468                                                 STM32_USB_EP_ZERO_POSSIBLE;
469
470                         CountHold = Count = MIN(Count, epd->max_size);
471                         if (!Count)
472                                 epd->flags |= STM32_USB_EP_ZERO_PACKET;
473                         Offset = epd->offset;
474                         epd->offset += Count;
475                         CurrentBuffer = true;
476                         switch (epd->type)
477                         {
478                         case USB_ENDPOINT_XFER_CONTROL:
479                         case USB_ENDPOINT_XFER_INT:
480                                 pDst = (uint32_t *)addr2usbmem(ReadEpDTB_AddrTx(EP >> 1));
481                                 break;
482                         case USB_ENDPOINT_XFER_BULK:
483                                 pDst = (uint32_t *)addr2usbmem(ReadEpDTB_AddrTx(EP >> 1));
484                                 break;
485                         case USB_ENDPOINT_XFER_ISOC:
486                                 LOG_ERR("%s: isochronous transfer not supported\n",
487                                         __func__);
488                                 /* Fallback to default */
489                         default:
490                                 ASSERT(0);
491                                 return;
492                         }
493
494                         /* Write data to packet memory buffer */
495                         while (Count)
496                         {
497                                 Data = *(epd->write_buffer + Offset++);
498                                 if (--Count)
499                                 {
500                                         Data |= (uint32_t)(*(epd->write_buffer + Offset++)) << 8;
501                                         --Count;
502                                 }
503                                 *pDst++ = Data;
504                         }
505
506                         if (CurrentBuffer)
507                                 WriteEpDTB_CountTx(EP >> 1, CountHold);
508                         else
509                                 WriteEpDTB_CountRx(EP >> 1, CountHold);
510
511                         EpCtrlSet_STAT_TX(epd->hw, EP_VALID);
512
513                         --ep_cnfg[EP].avail_data;
514                         Count = epd->size - epd->offset;
515                 }
516                 if (!Count && !(epd->flags & STM32_USB_EP_ZERO_PACKET))
517                 {
518                         epd->status = COMPLETE;
519                         /* call callback function */
520                         if (epd->complete)
521                                 epd->complete(EP);
522                 }
523         }
524         else
525         {
526                 /* EP OUT */
527                 while (epd->avail_data)
528                 {
529                         /* Get data size and buffer pointer */
530                         switch (epd->type)
531                         {
532                         case USB_ENDPOINT_XFER_CONTROL:
533                         case USB_ENDPOINT_XFER_INT:
534                                 /* Get received bytes number */
535                                 Count = ReadEpDTB_CountRx(EP >> 1) & 0x3FF;
536                                 /* Get address of the USB packet buffer for corresponding EP */
537                                 pSrc = (uint32_t *)addr2usbmem(ReadEpDTB_AddrRx(EP >> 1));
538                                 break;
539                         case USB_ENDPOINT_XFER_BULK:
540                                 /* Get received bytes number */
541                                 Count = ReadEpDTB_CountRx(EP >> 1) & 0x3FF;
542                                 /* Get address of the USB packet buffer for corresponding EP */
543                                 pSrc = (uint32_t *)addr2usbmem(ReadEpDTB_AddrRx(EP >> 1));
544                                 break;
545                         case USB_ENDPOINT_XFER_ISOC:
546                                 LOG_ERR("%s: isochronous transfer not supported\n",
547                                         __func__);
548                                 /* Fallback to default */
549                         default:
550                                 ASSERT(0);
551                                 return;
552                         }
553
554                         if (Count > (epd->size - epd->offset))
555                         {
556                                 epd->status = BUFFER_OVERRUN;
557                                 epd->size = ep_cnfg[EP].offset;
558                                 break;
559                         }
560                         else if (Count < ep_cnfg[EP].max_size)
561                         {
562                                 epd->status = BUFFER_UNDERRUN;
563                                 epd->size = ep_cnfg[EP].offset + Count;
564                         }
565                         else
566                                 epd->status = BEGIN_SERVICED;
567
568                         Offset = epd->offset;
569                         epd->offset += Count;
570
571                         /* Read data from packet memory buffer */
572                         while (Count)
573                         {
574                                 Data = *pSrc++;
575                                 *(epd->read_buffer + Offset++) = Data;
576                                 if (--Count)
577                                 {
578                                         Data >>= 8;
579                                         *(epd->read_buffer + Offset++) = Data;
580                                         --Count;
581                                 }
582                         }
583
584                         EpCtrlSet_STAT_RX(epd->hw, EP_VALID);
585
586                         --ep_cnfg[EP].avail_data;
587
588                         if (*epd->hw & (1UL << 11))
589                         {
590                                 ep_cnfg[EP].status = SETUP_OVERWRITE;
591                                 return;
592                         }
593                         if (!(Count = (epd->size - epd->offset)))
594                         {
595                                 epd->status = COMPLETE;
596                                 break;
597                         }
598                 }
599                 if (epd->status != BEGIN_SERVICED && epd->status != NO_SERVICED)
600                 {
601                         /* call callback function */
602                         if (epd->complete)
603                                 epd->complete(EP);
604                 }
605         }
606 }
607
608 /* Configure an EP descriptor before performing a I/O operation */
609 #define USB_EP_IO(__EP, __op, __buf, __size, __complete)                \
610 ({                                                                      \
611         cpu_flags_t flags;                                              \
612         stm32_usb_io_status_t ret;                                      \
613                                                                         \
614         /* NOTE: buffer must be 4-bytes aligned */                      \
615         ASSERT(!((size_t)__buf & 0x03));                                \
616                                                                         \
617         /* Fill EP descriptor */                                        \
618         IRQ_SAVE_DISABLE(flags);                                        \
619         if (__size < 0)                                                 \
620         {                                                               \
621                 ep_cnfg[__EP].status = NOT_READY;                       \
622                 ep_cnfg[__EP].complete = NULL;                          \
623                 ret = NOT_READY;                                        \
624                 goto out;                                               \
625         }                                                               \
626         if (ep_cnfg[__EP].status == BEGIN_SERVICED)                     \
627         {                                                               \
628                 ret = NOT_READY;                                        \
629                 goto out;                                               \
630         }                                                               \
631         /*                                                              \
632          * NOTE: the write_buffer and read_buffer are actually the      \
633          * same location in memory (it's a union).                      \
634          *                                                              \
635          * We have to do this trick to silent a build warning by        \
636          * casting the I/O buffer to (void *) or (const void *).        \
637          */                                                             \
638         ep_cnfg[__EP].__op ## _buffer = __buf;                          \
639         ep_cnfg[__EP].offset = 0;                                       \
640         ep_cnfg[__EP].size = __size;                                    \
641         ep_cnfg[__EP].complete = __complete;                            \
642         if (!size)                                                      \
643                 ep_cnfg[__EP].flags = STM32_USB_EP_ZERO_PACKET;         \
644         else                                                            \
645                 ep_cnfg[__EP].flags = 0;                                \
646         ep_cnfg[__EP].status = NO_SERVICED;                             \
647                                                                         \
648         /* Perform the I/O operation */                                 \
649         __usb_ep_io(__EP);                                              \
650                                                                         \
651         ret = ep_cnfg[__EP].status;                                     \
652 out:                                                                    \
653         IRQ_RESTORE(flags);                                             \
654         ret;                                                            \
655 })
656
657 /* Configure and endponint and perform a read operation */
658 static stm32_usb_io_status_t
659 __usb_ep_read(int ep, void *buffer, ssize_t size, void (*complete)(int))
660 {
661         if (UNLIKELY(ep >= ENP_MAX_NUMB))
662         {
663                 ASSERT(0);
664                 return STALLED;
665         }
666         ASSERT(!(ep & 0x01));
667         return USB_EP_IO(ep, read, buffer, size, complete);
668 }
669
670 /* Configure and endponint and perform a write operation */
671 static stm32_usb_io_status_t
672 __usb_ep_write(int ep, const void *buffer, ssize_t size, void (*complete)(int))
673 {
674         if (UNLIKELY(ep >= ENP_MAX_NUMB))
675         {
676                 ASSERT(0);
677                 return STALLED;
678         }
679         ASSERT(ep & 0x01);
680         return USB_EP_IO(ep, write, buffer, size, complete);
681 }
682
683 static bool rx_done;
684 static size_t rx_size;
685
686 static void usb_ep_read_complete(int ep)
687 {
688         if (UNLIKELY(ep >= ENP_MAX_NUMB))
689         {
690                 ASSERT(0);
691                 return;
692         }
693         ASSERT(!(ep & 0x01));
694
695         rx_done = true;
696         rx_size = ep_cnfg[ep].size;
697 }
698
699 ssize_t usb_ep_read(int ep, void *buffer, ssize_t size)
700 {
701         if (UNLIKELY(!size))
702                 return 0;
703         size = MIN(size, USB_RX_MAX_SIZE);
704         rx_done = false;
705         rx_size = 0;
706
707         /* Blocking read */
708         __usb_ep_read(USB_EpLogToPhysAdd(ep), buffer, size,
709                                 usb_ep_read_complete);
710         while (!rx_done)
711                 cpu_relax();
712
713         return rx_size;
714 }
715
716 static bool tx_done;
717 static size_t tx_size;
718
719 static void usb_ep_write_complete(int ep)
720 {
721         if (UNLIKELY(ep >= ENP_MAX_NUMB))
722         {
723                 ASSERT(0);
724                 return;
725         }
726         ASSERT(ep & 0x01);
727
728         tx_done = true;
729         tx_size = ep_cnfg[ep].size;
730 }
731
732 ssize_t usb_ep_write(int ep, const void *buffer, ssize_t size)
733 {
734         if (UNLIKELY(!size))
735                 return 0;
736         size = MIN(size, USB_TX_MAX_SIZE);
737         tx_done = false;
738         tx_size = 0;
739
740         /* Blocking write */
741         __usb_ep_write(USB_EpLogToPhysAdd(ep), buffer, size,
742                                 usb_ep_write_complete);
743         while (!tx_done)
744                 cpu_relax();
745
746         return tx_size;
747 }
748
749 static void usb_ep_low_level_config(int ep, uint16_t offset, uint16_t size)
750 {
751         stm32_usb_ep_t *epc = &ep_cnfg[ep];
752
753         /* IN EP */
754         if (ep & 0x01)
755         {
756                 /* Disable EP */
757                 EpCtrlSet_STAT_TX(epc->hw, EP_DISABLED);
758                 /* Clear Tx toggle */
759                 EpCtrlSet_DTOG_TX(epc->hw, 0);
760                 /* Clear Correct Transfer for transmission flag */
761                 EpCtrlClr_CTR_TX(epc->hw);
762
763                 /* Update EP description table */
764                 WriteEpDTB_AddrTx(ep >> 1, offset);
765                 WriteEpDTB_CountTx(ep >> 1, 0);
766         }
767         /* OUT EP */
768         else
769         {
770                 uint16_t rx_count = 0;
771
772                 /* Disable EP */
773                 EpCtrlSet_STAT_RX(epc->hw, EP_DISABLED);
774                 /* Clear Rx toggle */
775                 EpCtrlSet_DTOG_RX(epc->hw, 0);
776                 /* Clear Correct Transfer for reception flag */
777                 EpCtrlClr_CTR_RX(epc->hw);
778                 /* Descriptor block size field */
779                 rx_count |= (size > 62) << 15;
780                 /* Descriptor number of blocks field */
781                 rx_count |= (((size > 62) ?  (size >> 5) - 1 : size >> 1) &
782                                 0x1f) << 10;
783                 /* Update EP description table */
784                 WriteEpDTB_AddrRx(ep >> 1, offset);
785                 WriteEpDTB_CountRx(ep >> 1, rx_count);
786         }
787 }
788
789 /* Enable/Disable an endpoint */
790 static int usb_ep_configure(const usb_endpoint_descriptor_t *epd, bool enable)
791 {
792         int EP;
793         stm32_usb_ep_t *ep_hw;
794         reg32_t *hw;
795         uint16_t Offset;
796         uint32_t MaxPacketSizeTmp;
797
798         EP = USB_EpLogToPhysAdd(epd->bEndpointAddress);
799         ep_hw = &ep_cnfg[EP];
800
801         if (enable)
802         {
803                 /*
804                  * Allocate packet memory for EP buffer/s calculate actual size
805                  * only for the OUT EPs.
806                  */
807                 MaxPacketSizeTmp = epd->wMaxPacketSize;
808                 if (!USB_AllocateBuffer(&Offset, &MaxPacketSizeTmp, EP))
809                         return -USB_MEMORY_FULL;
810
811                 /* Set EP status */
812                 ep_hw->status  = NOT_READY;
813                 /* Init EP flags */
814                 ep_hw->flags = 0;
815
816                 /* Set endpoint type */
817                 ep_hw->type = usb_endpoint_type(epd);
818                 /* Init EP max packet size */
819                 ep_hw->max_size = epd->wMaxPacketSize;
820
821                 if (EP & 0x01)
822                         ep_hw->avail_data = 1;
823                 else
824                         ep_hw->avail_data = 0;
825                 hw = (reg32_t *)&usb->EP0R;
826                 hw += EP >> 1;
827
828                 /* Set Ep Address */
829                 EpCtrlSet_EA(hw, EP >> 1);
830                 ep_hw->hw = hw;
831
832                 /* Low-level endpoint configuration */
833                 usb_ep_low_level_config(EP, Offset, MaxPacketSizeTmp);
834
835                 /* Set EP Kind & enable */
836                 switch (ep_hw->type)
837                 {
838                 case USB_ENDPOINT_XFER_CONTROL:
839                         LOG_INFO("EP%d: CONTROL IN\n", EP >> 1);
840                         EpCtrlSet_EP_TYPE(hw, EP_CTRL);
841                         EpCtrlSet_EP_KIND(hw, 0);
842                         break;
843                 case USB_ENDPOINT_XFER_INT:
844                         LOG_INFO("EP%d: INTERRUPT IN\n", EP >> 1);
845                         EpCtrlSet_EP_TYPE(hw, EP_INTERRUPT);
846                         EpCtrlSet_EP_KIND(hw, 0);
847                         break;
848                 case USB_ENDPOINT_XFER_BULK:
849                         LOG_INFO("EP%d: BULK IN\n", EP >> 1);
850                         EpCtrlSet_EP_TYPE(hw, EP_BULK);
851                         EpCtrlSet_EP_KIND(hw, 0);
852                         break;
853                 case USB_ENDPOINT_XFER_ISOC:
854                         LOG_ERR("EP%d: ISOCHRONOUS IN: not supported\n", EP >> 1);
855                         /* Fallback to default */
856                 default:
857                         ASSERT(0);
858                         return -USB_NODEV_ERROR;
859                 }
860                 if (EP & 0x01)
861                 {
862                         /* Enable EP */
863                         EpCtrlSet_STAT_TX(hw, EP_NAK);
864                         /* Clear Correct Transfer for transmission flag */
865                         EpCtrlClr_CTR_TX(hw);
866                 }
867                 else
868                 {
869                         /* Enable EP */
870                         EpCtrlSet_STAT_RX(hw, EP_VALID);
871                 }
872         }
873         else if (ep_cnfg[EP].hw)
874         {
875                 hw = (reg32_t *)&usb->EP0R;
876                 hw += EP >> 1;
877
878                 /* IN EP */
879                 if (EP & 0x01)
880                 {
881                         /* Disable IN EP */
882                         EpCtrlSet_STAT_TX(hw, EP_DISABLED);
883                         /* Clear Correct Transfer for reception flag */
884                         EpCtrlClr_CTR_TX(hw);
885                 }
886                 /* OUT EP */
887                 else
888                 {
889                         /* Disable OUT EP */
890                         EpCtrlSet_STAT_RX(hw, EP_DISABLED);
891                         /* Clear Correct Transfer for reception flag */
892                         EpCtrlClr_CTR_RX(hw);
893                 }
894                 /* Release buffer */
895                 USB_ReleaseBuffer(EP);
896                 ep_cnfg[EP].hw = NULL;
897         }
898         return 0;
899 }
900
901 /* Get EP stall/unstall */
902 static int USB_GetStallEP(int EP, bool *pStall)
903 {
904         if (ep_cnfg[EP].hw == NULL)
905                 return -USB_NODEV_ERROR;
906
907         *pStall = (EP & 0x01) ?
908                 (EpCtrlGet_STAT_TX(ep_cnfg[EP].hw) == EP_STALL):  /* IN EP  */
909                 (EpCtrlGet_STAT_RX(ep_cnfg[EP].hw) == EP_STALL);  /* OUT EP */
910
911         return USB_OK;
912 }
913
914 /* Set EP stall/unstall */
915 static int USB_SetStallEP(int EP, bool Stall)
916 {
917         if (ep_cnfg[EP].hw == NULL)
918                 return -USB_NODEV_ERROR;
919
920         if (Stall)
921         {
922                 ep_cnfg[EP].status = STALLED;
923                 if (EP & 0x01)
924                 {
925                         /* IN EP */
926                         EpCtrlSet_STAT_TX(ep_cnfg[EP].hw, EP_STALL);
927                         ep_cnfg[EP].avail_data = 1;
928                 }
929                 else
930                 {
931                         /* OUT EP */
932                         EpCtrlSet_STAT_RX(ep_cnfg[EP].hw, EP_STALL);
933                         ep_cnfg[EP].avail_data = 0;
934                 }
935         }
936         else
937         {
938                 ep_cnfg[EP].status = NOT_READY;
939                 if(EP & 0x01)
940                 {
941                         /* IN EP */
942                         ep_cnfg[EP].avail_data = 1;
943                         /* reset Data Toggle bit */
944                         EpCtrlSet_DTOG_TX(ep_cnfg[EP].hw, 0);
945                         EpCtrlSet_STAT_TX(ep_cnfg[EP].hw, EP_NAK);
946                 }
947                 else
948                 {
949                         /* OUT EP */
950                         ep_cnfg[EP].avail_data = 0;
951                         /* reset Data Toggle bit */
952                         EpCtrlSet_DTOG_RX(ep_cnfg[EP].hw, 0);
953                         EpCtrlSet_STAT_RX(ep_cnfg[EP].hw, EP_VALID);
954                 }
955         }
956         return USB_OK;
957 }
958
959 /* Stall both directions of the control EP */
960 static void USB_StallCtrlEP(void)
961 {
962         ep_cnfg[CTRL_ENP_IN].avail_data = 1;
963         ep_cnfg[CTRL_ENP_IN].status = STALLED;
964         ep_cnfg[CTRL_ENP_OUT].avail_data = 0;
965         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
966
967         USB_SetStallEP(CTRL_ENP_IN, true);
968         USB_SetStallEP(CTRL_ENP_OUT, true);
969 }
970
971 /*
972  * Find the position of an interface descriptor inside the configuration
973  * descriptor.
974  */
975 static int usb_find_interface(uint32_t num, uint32_t alt)
976 {
977         usb_interface_descriptor_t *id;
978         int i;
979
980         for (i = 0; ; i++)
981         {
982                 /* TODO: support more than one configuration per device */
983                 id = (usb_interface_descriptor_t *)usb_dev->config[i];
984                 if (id == NULL)
985                         break;
986                 if (id->bDescriptorType != USB_DT_INTERFACE)
987                         continue;
988                 if ((id->bInterfaceNumber == num) &&
989                                 (id->bAlternateSetting == alt))
990                         return i;
991         }
992         return -USB_NODEV_ERROR;
993 }
994
995 /*
996  * Configure/deconfigure EPs of a certain interface.
997  */
998 static void
999 usb_configure_ep_interface(unsigned int num, unsigned int alt, bool enable)
1000 {
1001         usb_endpoint_descriptor_t *epd;
1002         int i, start;
1003
1004         /*
1005          * Find the position of the interface descriptor (inside the
1006          * configuration descriptor).
1007          */
1008         start = usb_find_interface(num, alt);
1009         if (start < 0)
1010         {
1011                 LOG_ERR("%s: interface (%u,%u) not found\n",
1012                         __func__, num, alt);
1013                 return;
1014         }
1015         /*
1016          * Cycle over endpoint descriptors.
1017          *
1018          * NOTE: the first endpoint descriptor is placed next to the interface
1019          * descriptor, so we need to add +1 to the position of the interface
1020          * descriptor to find it.
1021          */
1022         for (i = start + 1; ; i++)
1023         {
1024                 epd = (usb_endpoint_descriptor_t *)usb_dev->config[i];
1025                 if ((epd == NULL) || (epd->bDescriptorType != USB_DT_ENDPOINT))
1026                         break;
1027                 if (UNLIKELY(usb_ep_configure(epd, enable) < 0))
1028                 {
1029                         LOG_ERR("%s: out of memory, can't initialize EP\n",
1030                                 __func__);
1031                         return;
1032                 }
1033         }
1034 }
1035
1036 /* Set device state */
1037 static void usb_set_device_state(int state)
1038 {
1039         unsigned int i;
1040
1041         LOG_INFO("%s: new state %d\n", __func__, state);
1042
1043         if (udc.state == USB_STATE_CONFIGURED)
1044         {
1045                 /* Deconfigure device */
1046                 for (i = 0; i < udc.interfaces; ++i)
1047                         usb_configure_ep_interface(i,
1048                                 udc.alt[i], false);
1049         }
1050         switch (state)
1051         {
1052         case USB_STATE_ATTACHED:
1053         case USB_STATE_POWERED:
1054         case USB_STATE_DEFAULT:
1055                 usb_set_address(0);
1056                 usb_dev->configured = false;
1057                 udc.address = udc.cfg_id = 0;
1058                 break;
1059         case USB_STATE_ADDRESS:
1060                 udc.cfg_id = 0;
1061                 break;
1062         case USB_STATE_CONFIGURED:
1063                 /* Configure device */
1064                 for (i = 0; i < udc.interfaces; ++i)
1065                         usb_configure_ep_interface(i,
1066                                 udc.alt[i], true);
1067                 break;
1068         default:
1069                 /* Unknown state: disconnected or connection in progress */
1070                 usb_dev->configured = false;
1071                 udc.address = 0;
1072                 udc.cfg_id = 0;
1073                 break;
1074         }
1075         udc.state = state;
1076 }
1077
1078 /* Setup packet: set address status phase end handler */
1079 static void USB_AddStatusEndHandler(UNUSED_ARG(int, EP))
1080 {
1081         uint16_t w_value;
1082
1083         w_value = usb_le16_to_cpu(setup_packet.wValue);
1084         udc.address = w_value & 0xff;
1085         usb_set_address(udc.address);
1086
1087         if (udc.address)
1088                 usb_set_device_state(USB_STATE_ADDRESS);
1089         else
1090                 usb_set_device_state(USB_STATE_DEFAULT);
1091
1092         __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1093         __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1094 }
1095
1096 /* Prepare status phase */
1097 static void USB_StatusPhase(bool in)
1098 {
1099         if (in)
1100                 __usb_ep_write(CTRL_ENP_IN, NULL, 0, NULL);
1101 }
1102
1103 /* Setup packet: status phase end handler */
1104 static void USB_StatusEndHandler(UNUSED_ARG(int, EP))
1105 {
1106         __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1107         __usb_ep_read(CTRL_ENP_OUT, NULL, -1, NULL);
1108 }
1109
1110 /* Address status handler */
1111 static void USB_StatusHandler(UNUSED_ARG(int, EP))
1112 {
1113         if (setup_packet.mRequestType & USB_DIR_IN)
1114         {
1115                 USB_StatusPhase(false);
1116                 ep_cnfg[CTRL_ENP_OUT].complete = USB_StatusEndHandler;
1117         }
1118         else
1119         {
1120                 USB_StatusPhase(true);
1121                 ep_cnfg[CTRL_ENP_IN].complete =
1122                         (setup_packet.bRequest == USB_REQ_SET_ADDRESS) ?
1123                                 USB_AddStatusEndHandler :
1124                                 USB_StatusEndHandler;
1125         }
1126 }
1127
1128 /* Global variable to handle the following non-blocking I/O operations */
1129 static uint32_t InData;
1130
1131 /* Get device status */
1132 static int UsbDevStatus(uint16_t index)
1133 {
1134         if (index)
1135                 return -USB_NODEV_ERROR;
1136
1137         InData = ((uint32_t)udc.feature) & 0xff;
1138         __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 2, USB_StatusHandler);
1139
1140         return 0;
1141 }
1142
1143 /* Get interface status */
1144 static int UsbInterfaceStatus(UNUSED_ARG(uint16_t, index))
1145 {
1146         InData = 0;
1147         __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 2, USB_StatusHandler);
1148
1149         return 0;
1150 }
1151
1152 /* Get endpoint status */
1153 static int UsbEpStatus(uint16_t index)
1154 {
1155         if ((index & 0x7F) > 16)
1156                 return -USB_NODEV_ERROR;
1157
1158         InData = 0;
1159         USB_GetStallEP(USB_EpLogToPhysAdd(index), (bool *)&InData);
1160         __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 2, USB_StatusHandler);
1161
1162         return 0;
1163 }
1164
1165 /* USB setup packet: GET_STATUS request handler */
1166 static void USB_GetStatusHandler(void)
1167 {
1168         uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1169         uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1170         uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1171
1172         /* GET_STATUS sanity checks */
1173         if (udc.state < USB_STATE_ADDRESS)
1174         {
1175                 LOG_WARN("%s: bad GET_STATUS request (State=%02x)\n",
1176                                 __func__, udc.state);
1177                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1178                 return;
1179         }
1180         if (w_length != 2)
1181         {
1182                 LOG_WARN("%s: bad GET_STATUS request (wLength.Word=%02x)\n",
1183                                 __func__, w_length);
1184                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1185                 return;
1186         }
1187         if (!(setup_packet.mRequestType & USB_DIR_IN))
1188         {
1189                 LOG_WARN("%s: bad GET_STATUS request (mRequestType=%02x)\n",
1190                                 __func__, setup_packet.mRequestType);
1191                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1192                 return;
1193         }
1194         if (w_value)
1195         {
1196                 LOG_WARN("%s: bad GET_STATUS request (wValue=%02x)\n",
1197                                 __func__, w_value);
1198                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1199                 return;
1200         }
1201
1202         /* Process GET_STATUS request */
1203         switch (setup_packet.mRequestType & USB_RECIP_MASK)
1204         {
1205         case USB_RECIP_DEVICE:
1206                 if (UsbDevStatus(w_index) < 0)
1207                 {
1208                         LOG_WARN("%s: GET_STATUS: invalid UsbRecipientDevice\n",
1209                                         __func__);
1210                         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1211                         return;
1212                 }
1213                 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientDevice)\n",
1214                                 __func__, setup_packet.mRequestType);
1215                 break;
1216         case USB_RECIP_INTERFACE:
1217                 if (UsbInterfaceStatus(w_index) < 0)
1218                 {
1219                         LOG_WARN("%s: GET_STATUS: invalid UsbRecipientInterface\n",
1220                                         __func__);
1221                         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1222                         return;
1223                 }
1224                 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientInterface)\n",
1225                                 __func__, setup_packet.mRequestType);
1226                 break;
1227         case USB_RECIP_ENDPOINT:
1228                 if (UsbEpStatus(w_index) < 0)
1229                 {
1230                         LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1231                                         __func__);
1232                         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1233                         return;
1234                 }
1235                 LOG_INFO("%s: GET_STATUS: mRequestType=%02x (UsbRecipientEndpoint)\n",
1236                                 __func__, setup_packet.mRequestType);
1237                 break;
1238         default:
1239                 LOG_WARN("%s: GET_STATUS: invalid UsbRecipientEndpoint\n",
1240                                 __func__);
1241                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1242                 break;
1243         }
1244 }
1245
1246 /*
1247  * Return the lower value from Host expected size and size and set a flag
1248  * STM32_USB_EP_ZERO_POSSIBLE when size is lower that host expected size.
1249  */
1250 static size_t usb_size(size_t size, size_t host_size)
1251 {
1252         if (size < host_size)
1253         {
1254                 ep_cnfg[CTRL_ENP_IN].flags |= STM32_USB_EP_ZERO_POSSIBLE;
1255                 return size;
1256         }
1257         return host_size;
1258 }
1259
1260 static int usb_get_device_descriptor(int id)
1261 {
1262         if (id)
1263                 return -USB_NODEV_ERROR;
1264
1265         usb_dev->device->bMaxPacketSize0 = USB_EP0_MAX_SIZE;
1266         __usb_ep_write(CTRL_ENP_IN, (const uint8_t *)usb_dev->device,
1267                         usb_size(usb_dev->device->bLength,
1268                         setup_packet.wLength),
1269                         USB_StatusHandler);
1270         return 0;
1271 }
1272
1273 #define USB_BUFSIZE (128)
1274 static uint8_t usb_cfg_buffer[USB_BUFSIZE];
1275
1276 static int usb_get_configuration_descriptor(int id)
1277 {
1278         const usb_config_descriptor_t **config =
1279                         (const usb_config_descriptor_t **)usb_dev->config;
1280         uint8_t *p = usb_cfg_buffer;
1281         int i;
1282
1283         /* TODO: support more than one configuration per device */
1284         if (UNLIKELY(id > 0))
1285                 return -USB_NODEV_ERROR;
1286
1287         for (i = 0; config[i]; i++)
1288         {
1289                 memcpy(p, config[i], config[i]->bLength);
1290                 p += config[i]->bLength;
1291
1292                 if (UNLIKELY((p - usb_cfg_buffer) > USB_BUFSIZE))
1293                 {
1294                         ASSERT(0);
1295                         return -USB_BUF_OVERFLOW;
1296                 }
1297         }
1298         ((usb_config_descriptor_t *)usb_cfg_buffer)->wTotalLength =
1299                                         usb_cpu_to_le16(p - usb_cfg_buffer);
1300         __usb_ep_write(CTRL_ENP_IN,
1301                         usb_cfg_buffer,
1302                         usb_size(p - usb_cfg_buffer,
1303                                 setup_packet.wLength),
1304                         USB_StatusHandler);
1305         return 0;
1306 }
1307
1308 static int usb_get_string_descriptor(unsigned int id)
1309 {
1310         usb_string_descriptor_t *lang_str;
1311         unsigned int lang_id, str_id;
1312         uint16_t w_index_lo = usb_le16_to_cpu(setup_packet.wIndex) & 0x00ff;
1313         uint16_t w_index_hi = (usb_le16_to_cpu(setup_packet.wIndex) & 0xff00) >> 8;
1314
1315         ASSERT(usb_dev->strings != NULL);
1316         ASSERT(usb_dev->strings[0] != NULL);
1317
1318         lang_str = usb_dev->strings[0];
1319         if (id)
1320         {
1321                 /* Find Language index */
1322                 for (lang_id = 0; ; lang_id++)
1323                 {
1324                         usb_string_descriptor_t *str = usb_dev->strings[lang_id];
1325
1326                         if (UNLIKELY(str == NULL))
1327                                 return -USB_NODEV_ERROR;
1328                         if ((str->data[0] == w_index_lo) &&
1329                                         (str->data[1] == w_index_hi))
1330                                 break;
1331                 }
1332                 /* Check buffer overflow to find string index */
1333                 for (str_id = 0; str_id < id; str_id++)
1334                 {
1335                         lang_str = usb_dev->strings[lang_id + 1 + str_id];
1336                         if (lang_str == NULL)
1337                                 return -USB_NODEV_ERROR;
1338                 }
1339         }
1340         __usb_ep_write(CTRL_ENP_IN,
1341                         lang_str,
1342                         usb_size(lang_str->bLength, setup_packet.wLength),
1343                         USB_StatusHandler);
1344         return 0;
1345 }
1346
1347 static void UsbGetDescriptor(void)
1348 {
1349         uint16_t w_value_lo = usb_le16_to_cpu(setup_packet.wValue) & 0x00ff;
1350         uint16_t w_value_hi = (usb_le16_to_cpu(setup_packet.wValue) & 0xff00) >> 8;
1351
1352         if (udc.state < USB_STATE_DEFAULT)
1353         {
1354                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1355                 return;
1356         }
1357         switch (w_value_hi)
1358         {
1359         case USB_DT_DEVICE:
1360                 LOG_INFO("%s: GET_DEVICE_DESCRIPTOR: id=%d, state=%d\n",
1361                                 __func__,
1362                                 w_value_lo,
1363                                 udc.state);
1364                 if (usb_get_device_descriptor(w_value_lo) < 0)
1365                         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1366                 break;
1367         case USB_DT_CONFIG:
1368                 LOG_INFO("%s: GET_CONFIG_DESCRIPTOR: id=%d, state=%d\n",
1369                                 __func__, w_value_lo, udc.state);
1370                 if (usb_get_configuration_descriptor(w_value_lo) < 0)
1371                         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1372                 break;
1373         case USB_DT_STRING:
1374                 LOG_INFO("%s: GET_STRING_DESCRIPTOR: id=%d, state=%d\n",
1375                                 __func__, w_value_lo, udc.state);
1376                 if (usb_get_string_descriptor(w_value_lo) < 0)
1377                         ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1378                 break;
1379         default:
1380                 LOG_WARN("%s: GET_UNKNOWN_DESCRIPTOR: id=%d, state=%d\n",
1381                                 __func__, w_value_lo, udc.state);
1382                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1383                 break;
1384         }
1385 }
1386
1387 /* USB setup packet: GET_DESCRIPTOR handler */
1388 static void UBS_GetDescriptorHandler(void)
1389 {
1390         LOG_INFO("%s: GET_DESCRIPTOR: RECIP = %d\n",
1391                         __func__,
1392                         setup_packet.mRequestType & USB_RECIP_MASK);
1393         if ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1394                         USB_RECIP_DEVICE)
1395                 UsbGetDescriptor();
1396         else
1397                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1398 }
1399
1400 /* USB setup packet: SET_ADDRESS handler */
1401 static void USB_SetAddressHandler(void)
1402 {
1403         uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1404         uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1405         uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1406
1407         LOG_INFO("%s: SET_ADDRESS: %d\n",
1408                         __func__, usb_le16_to_cpu(setup_packet.wValue));
1409         if ((udc.state >= USB_STATE_DEFAULT) &&
1410                         ((setup_packet.mRequestType & USB_RECIP_MASK) ==
1411                                         USB_RECIP_DEVICE) &&
1412                         (w_index == 0) && (w_length == 0) && (w_value < 128))
1413                 USB_StatusHandler(CTRL_ENP_IN);
1414         else
1415                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1416 }
1417
1418 /* USB setup packet: GET_CONFIGURATION handler */
1419 static void USB_GetConfigurationHandler(void)
1420 {
1421         uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1422         uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1423
1424         LOG_INFO("%s: GET_CONFIGURATION\n", __func__);
1425         if ((udc.state >= USB_STATE_ADDRESS) &&
1426                         (w_value == 0) && (w_index == 0) && (w_value == 1))
1427         {
1428                 InData = udc.cfg_id;
1429                 __usb_ep_write(CTRL_ENP_IN, (uint8_t *)&InData, 1, USB_StatusHandler);
1430         }
1431         else
1432                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1433 }
1434
1435 static const usb_config_descriptor_t *usb_find_configuration(int num)
1436 {
1437         const usb_config_descriptor_t *cfg;
1438         int i;
1439
1440         for (i = 0; ; i++)
1441         {
1442                 cfg = (const usb_config_descriptor_t *)usb_dev->config[i];
1443                 if (cfg == NULL)
1444                         break;
1445                 if (cfg->bDescriptorType != USB_DT_CONFIG)
1446                         continue;
1447                 if (cfg->bConfigurationValue == num)
1448                         return cfg;
1449         }
1450         return NULL;
1451 }
1452
1453 static int UsbSetConfigurationState(uint32_t Configuration)
1454 {
1455         const usb_config_descriptor_t *pCnfg;
1456         unsigned int i;
1457
1458         if (Configuration)
1459         {
1460                 /* Find configuration descriptor */
1461                 pCnfg = usb_find_configuration(Configuration);
1462                 if (pCnfg == NULL)
1463                         return -USB_NODEV_ERROR;
1464
1465                 /* Reset current configuration */
1466                 usb_set_device_state(USB_STATE_ADDRESS);
1467                 usb_dev->configured = false;
1468                 udc.cfg = pCnfg;
1469
1470                 /* Set Interface and Alternative Setting */
1471                 udc.cfg_id = Configuration;
1472                 /* Set self-powered state */
1473                 if (pCnfg->bmAttributes & USB_CONFIG_ATT_SELFPOWER)
1474                         udc.feature |= STM32_UDC_FEATURE_SELFPOWERED;
1475
1476                 /* Configure all existing interfaces to alternative setting 0 */
1477                 ASSERT(pCnfg->bNumInterfaces <= USB_MAX_INTERFACE);
1478                 udc.interfaces = pCnfg->bNumInterfaces;
1479                 for (i = 0; i < udc.interfaces; i++)
1480                         udc.alt[i] = 0;
1481                 usb_set_device_state(USB_STATE_CONFIGURED);
1482                 usb_dev->configured = true;
1483         }
1484         else
1485         {
1486                 usb_dev->configured = false;
1487                 usb_set_device_state(USB_STATE_ADDRESS);
1488         }
1489         return 0;
1490 }
1491
1492 /* USB setup packet: SET_CONFIGURATION handler */
1493 static void USB_SetConfigurationHandler(void)
1494 {
1495         uint16_t w_value = usb_le16_to_cpu(setup_packet.wValue);
1496         uint16_t w_index = usb_le16_to_cpu(setup_packet.wIndex);
1497         uint16_t w_length = usb_le16_to_cpu(setup_packet.wLength);
1498
1499         LOG_INFO("%s: SET_CONFIGURATION: %d\n",
1500                         __func__, w_value);
1501         if ((udc.state >= USB_STATE_ADDRESS) &&
1502                         (w_index == 0) && (w_length == 0) &&
1503                         (UsbSetConfigurationState(w_value & 0xff) == 0))
1504                 USB_StatusHandler(CTRL_ENP_OUT);
1505         else
1506                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1507 }
1508
1509 /* USB setup packet: standard request handler */
1510 static void USB_StandardRequestHandler(void)
1511 {
1512         switch (setup_packet.bRequest)
1513         {
1514         case USB_REQ_GET_STATUS:
1515                 USB_GetStatusHandler();
1516                 break;
1517         case USB_REQ_CLEAR_FEATURE:
1518                 LOG_INFO("%s: bRequest=%d (CLEAR_FEATURE)\n",
1519                                 __func__, setup_packet.bRequest);
1520                 break;
1521         case USB_REQ_SET_FEATURE:
1522                 LOG_INFO("%s: bRequest=%d (SET_FEATURE)\n",
1523                                 __func__, setup_packet.bRequest);
1524                 break;
1525         case USB_REQ_SET_ADDRESS:
1526                 USB_SetAddressHandler();
1527                 break;
1528         case USB_REQ_GET_DESCRIPTOR:
1529                 UBS_GetDescriptorHandler();
1530                 break;
1531         case USB_REQ_SET_DESCRIPTOR:
1532                 LOG_INFO("%s: bRequest=%d (SET_DESCRIPTOR)\n",
1533                                 __func__, setup_packet.bRequest);
1534                 break;
1535         case USB_REQ_GET_CONFIGURATION:
1536                 USB_GetConfigurationHandler();
1537                 break;
1538         case USB_REQ_SET_CONFIGURATION:
1539                 USB_SetConfigurationHandler();
1540                 break;
1541         case USB_REQ_GET_INTERFACE:
1542                 LOG_INFO("%s: bRequest=%d (GET_INTERFACE)\n",
1543                                 __func__, setup_packet.bRequest);
1544                 break;
1545         case USB_REQ_SET_INTERFACE:
1546                 LOG_INFO("%s: bRequest=%d (SET_INTERFACE)\n",
1547                                 __func__, setup_packet.bRequest);
1548                 break;
1549         case USB_REQ_SYNCH_FRAME:
1550                 LOG_INFO("%s: bRequest=%d (SYNCH_FRAME)\n",
1551                                 __func__, setup_packet.bRequest);
1552                 break;
1553         default:
1554                 LOG_WARN("%s: bRequest=%d (Unknown)\n",
1555                                 __func__, setup_packet.bRequest);
1556                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1557                 break;
1558         }
1559 }
1560
1561 /* USB setup packet handler */
1562 static void USB_SetupHandler(void)
1563 {
1564         switch (setup_packet.mRequestType & USB_TYPE_MASK)
1565         {
1566         /* Standard */
1567         case USB_TYPE_STANDARD:
1568                 LOG_INFO("%s: bmRequestType=%02x (Standard)\n",
1569                                 __func__, setup_packet.mRequestType);
1570                 USB_StandardRequestHandler();
1571                 break;
1572         /* Class */
1573         case USB_TYPE_CLASS:
1574                 LOG_INFO("%s: bmRequestType=%02x (Class)\n",
1575                                 __func__, setup_packet.mRequestType);
1576                 break;
1577         /* Vendor */
1578         case USB_TYPE_VENDOR:
1579                 LOG_INFO("%s: bmRequestType=%02x (Vendor)\n",
1580                                 __func__, setup_packet.mRequestType);
1581                 break;
1582         case USB_TYPE_RESERVED:
1583                 LOG_INFO("%s: bmRequestType=%02x (Reserved)\n",
1584                                 __func__, setup_packet.mRequestType);
1585                 break;
1586         /* Other */
1587         default:
1588                 LOG_WARN("%s: bmRequestType=%02x (Unknown)\n",
1589                                 __func__, setup_packet.mRequestType);
1590                 ep_cnfg[CTRL_ENP_OUT].status = STALLED;
1591                 break;
1592         }
1593 }
1594
1595 static void usb_hw_reset(void)
1596 {
1597         unsigned int i;
1598         int ret;
1599
1600         /* Initialize endpoint descriptors */
1601         for (i = 0; i < countof(ep_cnfg); i++)
1602                 ep_cnfg[i].hw = NULL;
1603
1604         /* Initialize USB memory */
1605         for (i = 0; i < countof(PacketMemBuff); i++)
1606                 PacketMemBuff[i].Size = 0;
1607         usb->BTABLE = USB_BDT_OFFSET;
1608         pPacketMemUse = NULL;
1609
1610         /* Endpoint initialization */
1611         ret = usb_ep_configure(&USB_CtrlEpDescr0, true);
1612         if (UNLIKELY(ret < 0))
1613         {
1614                 LOG_WARN("%s: out of memory, cannot initialize EP0\n",
1615                                 __func__);
1616                 return;
1617         }
1618         ret = usb_ep_configure(&USB_CtrlEpDescr1, true);
1619         if (UNLIKELY(ret < 0))
1620         {
1621                 LOG_WARN("%s: out of memory, cannot initialize EP1\n",
1622                                 __func__);
1623                 return;
1624         }
1625
1626         /* Set default address */
1627         usb_set_address(0);
1628
1629         /* Enable all the device interrupts */
1630 #if 0
1631         usb->CNTR = bmCTRM | bmRESETM | bmSOFM | bmERRM | bmPMAOVRM |
1632                         bmSUSPM | bmWKUPM;
1633 #else
1634         /* XXX: disable frame interrupts for now (too much noise!) */
1635         usb->CNTR = bmCTRM | bmRESETM | bmERRM | bmPMAOVRM | bmSUSPM | bmWKUPM;
1636 #endif
1637 }
1638
1639 /* Handle a correct transfer under ISR */
1640 static void usb_isr_correct_transfer(stm32_usb_irq_status_t interrupt)
1641 {
1642         int EP;
1643         reg32_t *pReg = (reg32_t *)&usb->EP0R;
1644
1645         /* Find corresponding EP */
1646         pReg += interrupt.EP_ID;
1647         EP = (int)(((*pReg & 0x0f) << 1) + (interrupt.DIR ? 0 : 1));
1648         ep_cnfg[EP].avail_data = 1;
1649
1650         ASSERT(ep_cnfg[EP].hw);
1651         /* IN EP */
1652         if (EP & 0x01)
1653                 EpCtrlClr_CTR_TX(ep_cnfg[EP].hw);
1654         else
1655                 EpCtrlClr_CTR_RX(ep_cnfg[EP].hw);
1656         if (EP == CTRL_ENP_OUT)
1657         {
1658                 /* Determinate type of packet (only for control EP) */
1659                 bool SetupPacket = EpCtrlGet_SETUP(ep_cnfg[CTRL_ENP_OUT].hw);
1660
1661                 if (SetupPacket)
1662                 {
1663                         ep_cnfg[CTRL_ENP_IN].avail_data = 1;
1664                         /* init IO to receive Setup packet */
1665                         __usb_ep_write(CTRL_ENP_IN, NULL, -1, NULL);
1666                         __usb_ep_read(CTRL_ENP_OUT, &setup_packet,
1667                                         sizeof(setup_packet), NULL);
1668
1669                         /* reset EP IO ctrl */
1670                         if (setup_packet.mRequestType & USB_DIR_IN)
1671                                 USB_StatusHandler(CTRL_ENP_OUT);
1672                         USB_SetupHandler();
1673                         if (ep_cnfg[CTRL_ENP_OUT].status == STALLED)
1674                                 USB_StallCtrlEP();
1675                 }
1676                 else
1677                 {
1678                         if (ep_cnfg[CTRL_ENP_OUT].complete &&
1679                                         setup_packet.mRequestType & USB_DIR_IN)
1680                                 ep_cnfg[CTRL_ENP_OUT].complete(CTRL_ENP_OUT);
1681                         else
1682                                 __usb_ep_io(EP);
1683                 }
1684         }
1685         else if (EP == CTRL_ENP_IN)
1686         {
1687                 if (ep_cnfg[CTRL_ENP_IN].complete &&
1688                                 !(setup_packet.mRequestType & USB_DIR_IN))
1689                         ep_cnfg[CTRL_ENP_IN].complete(CTRL_ENP_IN);
1690                 else
1691                         __usb_ep_io(EP);
1692
1693         }
1694         else
1695                 __usb_ep_io(EP);
1696 }
1697
1698 /* USB: interrupt service routine */
1699 static void usb_isr(void)
1700 {
1701         stm32_usb_irq_status_t interrupt;
1702
1703         /* Get masked interrupt flags */
1704         interrupt.status = usb->ISTR;
1705         interrupt.status &= usb->CNTR | 0x1f;
1706
1707         if (interrupt.PMAOVR)
1708         {
1709                 LOG_WARN("%s: DMA overrun / underrun\n", __func__);
1710                 usb->ISTR = ~bmPMAOVRM;
1711         }
1712         if (interrupt.ERR)
1713         {
1714                 LOG_WARN("%s: engine error\n", __func__);
1715                 usb->ISTR = ~bmERRM;
1716         }
1717         if (interrupt.RESET)
1718         {
1719                 LOG_INFO("%s: device reset\n", __func__);
1720                 usb->ISTR = ~bmRESETM;
1721                 usb_hw_reset();
1722                 usb_set_device_state(USB_STATE_DEFAULT);
1723         }
1724         if (interrupt.SOF)
1725         {
1726                 uint16_t frame_nr = usb->FNR & 0x0fff;
1727
1728                 LOG_INFO("%s: frame %#x\n", __func__, frame_nr);
1729                 usb->ISTR = ~bmSOFM;
1730         }
1731         if (interrupt.WKUP)
1732         {
1733                 LOG_INFO("%s: wake-up\n", __func__);
1734                 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1735                 usb_resume();
1736         }
1737         if (interrupt.SUSP)
1738         {
1739                 LOG_INFO("%s: suspend\n", __func__);
1740                 usb_suspend();
1741                 usb->ISTR = ~(bmSUSPM | bmWKUPM);
1742         }
1743         if (interrupt.ESOF)
1744         {
1745                 LOG_INFO("%s: expected frame\n", __func__);
1746                 usb->ISTR = ~bmESOFM;
1747         }
1748         if (interrupt.CTR)
1749         {
1750                 usb_isr_correct_transfer(interrupt);
1751         }
1752 }
1753
1754 /* USB: hardware initialization */
1755 static void usb_hw_init(void)
1756 {
1757         /* Enable clocking on the required GPIO pins */
1758         RCC->APB2ENR |= RCC_APB2_GPIOA | RCC_APB2_GPIOC;
1759
1760         /* Make sure that the CAN controller is disabled and held in reset */
1761         RCC->APB1ENR &= ~RCC_APB1_CAN;
1762
1763         /* Configure USB_DM and USB_DP to work as USB lines */
1764         stm32_gpioPinConfig((struct stm32_gpio *)GPIOA_BASE,
1765                         USB_DM_PIN | USB_DP_PIN,
1766                         GPIO_MODE_AF_PP, GPIO_SPEED_50MHZ);
1767         /* Configure USB_DISC to work as USB disconnect */
1768         stm32_gpioPinConfig((struct stm32_gpio *)GPIOC_BASE,
1769                         USB_DISC_PIN,
1770                         GPIO_MODE_OUT_PP, GPIO_SPEED_50MHZ);
1771         stm32_gpioPinWrite((struct stm32_gpio *)GPIOC_BASE,
1772                                 USB_DISC_PIN, 1);
1773
1774         /* Ensure the USB clock is disabled before setting the prescaler */
1775         RCC->APB1ENR &= ~RCC_APB1_USB;
1776
1777         /* Configure USB clock (48MHz) */
1778         *CFGR_USBPRE_BB &= ~RCC_USBCLK_PLLCLK_1DIV5;
1779
1780         /* Activate USB clock */
1781         RCC->APB1ENR |= RCC_APB1_USB;
1782
1783         /* Force USB reset and disable USB interrupts */
1784         usb->CNTR = bmFRES;
1785         timer_delayHp(1);
1786
1787         /* Issue a USB reset */
1788         usb_hw_reset();
1789
1790         /* Clear spurious pending interrupt */
1791         usb->ISTR = 0;
1792
1793         /* Register interrupt handler */
1794         sysirq_setHandler(USB_LP_CAN_RX0_IRQHANDLER, usb_isr);
1795
1796         /* Software connection enable */
1797         usb_connect();
1798 }
1799
1800 /* Initialize the USB controller */
1801 static void usb_init(void)
1802 {
1803         udc.state = USB_STATE_NOTATTACHED;
1804         udc.feature = 0;
1805
1806         usb_hw_init();
1807 }
1808
1809 /* Register an upper layer USB device into the driver */
1810 int usb_device_register(struct usb_device *dev)
1811 {
1812 #if CONFIG_KERN
1813         MOD_CHECK(proc);
1814 #endif
1815         usb_dev = dev;
1816         usb_init();
1817         while (!usb_dev->configured)
1818                 cpu_relax();
1819         return 0;
1820 }