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