]> begriffs open source - cmsis-freertos/blob - Demo/lwIP_Demo_Rowley_ARM7/USB/USB-CDC.c
Update cmsis_os2.c
[cmsis-freertos] / Demo / lwIP_Demo_Rowley_ARM7 / USB / USB-CDC.c
1 /*
2     FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
3     All rights reserved
4
5     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
6
7     This file is part of the FreeRTOS distribution.
8
9     FreeRTOS is free software; you can redistribute it and/or modify it under
10     the terms of the GNU General Public License (version 2) as published by the
11     Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
12
13     ***************************************************************************
14     >>!   NOTE: The modification to the GPL is included to allow you to     !<<
15     >>!   distribute a combined work that includes FreeRTOS without being   !<<
16     >>!   obliged to provide the source code for proprietary components     !<<
17     >>!   outside of the FreeRTOS kernel.                                   !<<
18     ***************************************************************************
19
20     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
21     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22     FOR A PARTICULAR PURPOSE.  Full license text is available on the following
23     link: http://www.freertos.org/a00114.html
24
25     ***************************************************************************
26      *                                                                       *
27      *    FreeRTOS provides completely free yet professionally developed,    *
28      *    robust, strictly quality controlled, supported, and cross          *
29      *    platform software that is more than just the market leader, it     *
30      *    is the industry's de facto standard.                               *
31      *                                                                       *
32      *    Help yourself get started quickly while simultaneously helping     *
33      *    to support the FreeRTOS project by purchasing a FreeRTOS           *
34      *    tutorial book, reference manual, or both:                          *
35      *    http://www.FreeRTOS.org/Documentation                              *
36      *                                                                       *
37     ***************************************************************************
38
39     http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
40     the FAQ page "My application does not run, what could be wrong?".  Have you
41     defined configASSERT()?
42
43     http://www.FreeRTOS.org/support - In return for receiving this top quality
44     embedded software for free we request you assist our global community by
45     participating in the support forum.
46
47     http://www.FreeRTOS.org/training - Investing in training allows your team to
48     be as productive as possible as early as possible.  Now you can receive
49     FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
50     Ltd, and the world's leading authority on the world's leading RTOS.
51
52     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
53     including FreeRTOS+Trace - an indispensable productivity tool, a DOS
54     compatible FAT file system, and our tiny thread aware UDP/IP stack.
55
56     http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
57     Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
58
59     http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
60     Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
61     licenses offer ticketed support, indemnification and commercial middleware.
62
63     http://www.SafeRTOS.com - High Integrity Systems also provide a safety
64     engineered and independently SIL3 certified version for use in safety and
65     mission critical applications that require provable dependability.
66
67     1 tab == 4 spaces!
68 */
69
70 /*
71         USB Communications Device Class driver.
72         Implements task vUSBCDCTask and provides an Abstract Control Model serial 
73         interface.  Control is through endpoint 0, device-to-host notification is 
74         provided by interrupt-in endpoint 3, and raw data is transferred through 
75         bulk endpoints 1 and 2.
76
77         - developed from original FreeRTOS HID example by Scott Miller
78         - modified to support 3.2 GCC by najay
79 */
80
81 /* Standard includes. */
82 #include <string.h>
83 #include <stdio.h>
84
85 /* Demo board includes. */
86 #include "Board.h"
87
88 /* Scheduler includes. */
89 #include "FreeRTOS.h"
90 #include "task.h"
91 #include "queue.h"
92
93 /* Demo app includes. */
94 #include "USB-CDC.h"
95 #include "descriptors.h"
96
97 #define usbNO_BLOCK ( ( TickType_t ) 0 )
98
99 /* Reset all endpoints */
100 static void prvResetEndPoints( void );
101
102 /* Clear pull up resistor to detach device from host */
103 static void vDetachUSBInterface( void );
104
105 /* Set up interface and initialize variables */
106 static void vInitUSBInterface( void );
107
108 /* Handle control endpoint events. */
109 static void prvProcessEndPoint0Interrupt( xISRStatus *pxMessage );
110
111 /* Handle standard device requests. */
112 static void prvHandleStandardDeviceRequest( xUSB_REQUEST *pxRequest );
113
114 /* Handle standard interface requests. */
115 static void prvHandleStandardInterfaceRequest( xUSB_REQUEST *pxRequest );
116
117 /* Handle endpoint requests. */
118 static void prvHandleStandardEndPointRequest( xUSB_REQUEST *pxRequest );
119
120 /* Handle class interface requests. */
121 static void prvHandleClassInterfaceRequest( xUSB_REQUEST *pxRequest );
122
123 /* Prepare control data transfer.  prvSendNextSegment starts transfer. */
124 static void prvSendControlData( unsigned char *pucData, unsigned short usRequestedLength, unsigned long ulLengthLeftToSend, long lSendingDescriptor );
125
126 /* Send next segment of data for the control transfer */
127 static void prvSendNextSegment( void );
128
129 /* Send stall - used to respond to unsupported requests */
130 static void prvSendStall( void );
131
132 /* Send a zero-length (null) packet */
133 static void prvSendZLP( void );
134
135 /* Handle requests for standard interface descriptors */
136 static void prvGetStandardInterfaceDescriptor( xUSB_REQUEST *pxRequest );
137
138 /*------------------------------------------------------------*/
139
140 /* File scope static variables */
141 static unsigned char ucUSBConfig = ( unsigned char ) 0;
142 static unsigned long ulReceivedAddress = ( unsigned long ) 0;
143 static eDRIVER_STATE eDriverState = eNOTHING;
144
145 /* Incoming and outgoing control data structures */
146 static xCONTROL_MESSAGE pxControlTx;
147 static xCONTROL_MESSAGE pxControlRx;
148
149 /* Queue holding pointers to pending messages */
150 QueueHandle_t xUSBInterruptQueue; 
151
152 /* Queues used to hold received characters, and characters waiting to be
153 transmitted.  Rx queue must be larger than FIFO size. */
154 static QueueHandle_t xRxCDC; 
155 static QueueHandle_t xTxCDC; 
156
157 /* Line coding - 115,200 baud, N-8-1 */
158 static const unsigned char pxLineCoding[] = { 0x00, 0xC2, 0x01, 0x00, 0x00, 0x00, 0x08 };
159
160 /* Status variables. */
161 static unsigned char ucControlState;
162 static unsigned int uiCurrentBank;
163
164
165 /*------------------------------------------------------------*/
166
167
168 void vUSBCDCTask( void *pvParameters )
169 {
170 xISRStatus *pxMessage;
171 unsigned long ulStatus;
172 unsigned long ulRxBytes;
173 unsigned char ucByte;
174 portBASE_TYPE xByte;
175
176         ( void ) pvParameters;
177
178         /* Disconnect USB device from hub.  For debugging - causes host to register reset */
179         portENTER_CRITICAL();
180                  vDetachUSBInterface();
181         portEXIT_CRITICAL();
182         
183         vTaskDelay( portTICK_PERIOD_MS * 60 );
184
185         /* Init USB interface */
186         portENTER_CRITICAL();
187                 vInitUSBInterface();
188         portEXIT_CRITICAL();
189         
190         /* Main task loop.  Process incoming endpoint 0 interrupts, handle data transfers. */
191          
192         for( ;; )
193         {
194                 /* Look for data coming from the ISR. */
195                 if( xQueueReceive( xUSBInterruptQueue, &pxMessage, usbSHORTEST_DELAY ) )
196                 {
197                         if( pxMessage->ulISR & AT91C_UDP_EPINT0 )
198                         {
199                                 /* All endpoint 0 interrupts are handled here. */
200                                 prvProcessEndPoint0Interrupt( pxMessage );
201                         }
202
203                         if( pxMessage->ulISR & AT91C_UDP_ENDBUSRES )
204                         {
205                                 /* End of bus reset - reset the endpoints and de-configure. */
206                                 prvResetEndPoints();            
207                         }
208                 }
209                 
210                 /* See if we're ready to send and receive data. */
211                 if( eDriverState == eREADY_TO_SEND && ucControlState ) 
212                 {
213                         if( ( !(AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_2 ] & AT91C_UDP_TXPKTRDY) ) && uxQueueMessagesWaiting( xTxCDC ) )
214                         {
215                                 for( xByte = 0; xByte < 64; xByte++ )
216                                 {                                  
217                                         if( !xQueueReceive( xTxCDC, &ucByte, 0 ) ) 
218                                         {
219                                                 /* No data buffered to transmit. */
220                                                 break;
221                                         }
222
223                                         /* Got a byte to transmit. */
224                                         AT91C_BASE_UDP->UDP_FDR[ usbEND_POINT_2 ] = ucByte;
225                                 } 
226                                 AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_2 ] |= AT91C_UDP_TXPKTRDY;
227                         }
228
229                         /* Check for incoming data (host-to-device) on endpoint 1. */
230                         while( AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_1 ] & (AT91C_UDP_RX_DATA_BK0 | AT91C_UDP_RX_DATA_BK1) )
231                         {
232                                 ulRxBytes = (AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_1 ] >> 16) & usbRX_COUNT_MASK;
233
234                                 /* Only process FIFO if there's room to store it in the queue */
235                                 if( ulRxBytes < ( USB_CDC_QUEUE_SIZE - uxQueueMessagesWaiting( xRxCDC ) ) )
236                                 {
237                                         while( ulRxBytes-- )
238                                         {
239                                                 ucByte = AT91C_BASE_UDP->UDP_FDR[ usbEND_POINT_1 ];
240                                                 xQueueSend( xRxCDC, &ucByte, 0 );
241                                         }
242
243                                         /* Release the FIFO */
244                                         portENTER_CRITICAL();
245                                         {
246                                                 ulStatus = AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_1 ];
247                                                 usbCSR_CLEAR_BIT( &ulStatus, uiCurrentBank );
248                                                 AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_1 ] = ulStatus;
249                                         }
250                                         portEXIT_CRITICAL();
251
252                                         /* Re-enable endpoint 1's interrupts */
253                                         AT91C_BASE_UDP->UDP_IER = AT91C_UDP_EPINT1;
254                                 
255                                         /* Update the current bank in use */
256                                         if( uiCurrentBank == AT91C_UDP_RX_DATA_BK0 ) 
257                                         {
258                                                 uiCurrentBank = AT91C_UDP_RX_DATA_BK1;
259                                         }
260                                         else 
261                                         {
262                                                 uiCurrentBank = AT91C_UDP_RX_DATA_BK0;
263                                         }
264
265                                 }
266                                 else 
267                                 {
268                                         break;
269                                 }
270                         }
271                 }
272         }
273 }
274 /*------------------------------------------------------------*/
275
276 void vUSBSendByte( char cByte )
277 {
278         /* Queue the byte to be sent.  The USB task will send it. */
279         xQueueSend( xTxCDC, &cByte, usbNO_BLOCK );
280 }
281 /*------------------------------------------------------------*/
282
283 static void prvSendZLP( void )
284 {
285 unsigned long ulStatus;
286
287         /* Wait until the FIFO is free - even though we are not going to use it.
288         THERE IS NO TIMEOUT HERE! */
289         while( AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ] & AT91C_UDP_TXPKTRDY )
290         {
291                 vTaskDelay( usbSHORTEST_DELAY );
292         }
293
294         portENTER_CRITICAL();
295         {
296                 /* Cancel any further pending data */
297                 pxControlTx.ulTotalDataLength = pxControlTx.ulNextCharIndex;
298
299                 /* Set the TXPKTRDY bit to cause a transmission with no data. */
300                 ulStatus = AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ];
301                 usbCSR_SET_BIT( &ulStatus, AT91C_UDP_TXPKTRDY );
302                 AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ] = ulStatus;
303         }
304         portEXIT_CRITICAL();
305 }
306 /*------------------------------------------------------------*/
307
308 static void prvSendStall( void )
309 {
310         unsigned long ulStatus;
311
312         portENTER_CRITICAL();
313         {
314                 /* Force a stall by simply setting the FORCESTALL bit in the CSR. */
315                 ulStatus = AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ];
316                 usbCSR_SET_BIT( &ulStatus, AT91C_UDP_FORCESTALL );
317                 AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ] = ulStatus;
318         }
319         portEXIT_CRITICAL();
320 }
321 /*------------------------------------------------------------*/
322
323 static void prvResetEndPoints( void )
324 {
325 unsigned long ulTemp;
326
327         eDriverState = eJUST_RESET;
328         ucControlState = 0;
329
330         /* Reset all the end points. */
331         AT91C_BASE_UDP->UDP_RSTEP  = usbEND_POINT_RESET_MASK;
332         AT91C_BASE_UDP->UDP_RSTEP  = ( unsigned long ) 0x00;
333
334         /* Enable data to be sent and received. */
335         AT91C_BASE_UDP->UDP_FADDR = AT91C_UDP_FEN;
336
337         /* Repair the configuration end point. */
338         portENTER_CRITICAL();
339         {
340                 ulTemp = AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ];
341                 usbCSR_SET_BIT( &ulTemp, ( ( unsigned long ) ( AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_CTRL ) ) );
342                 AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ] = ulTemp;
343                 AT91C_BASE_UDP->UDP_IER = AT91C_UDP_EPINT0;
344         }
345         portEXIT_CRITICAL();
346         uiCurrentBank = AT91C_UDP_RX_DATA_BK0;
347 }
348 /*------------------------------------------------------------*/
349
350 static void prvProcessEndPoint0Interrupt( xISRStatus *pxMessage )
351 {
352 static xUSB_REQUEST xRequest;
353 unsigned long ulRxBytes;
354
355         /* Get number of bytes received, if any */
356         ulRxBytes = pxMessage->ulCSR0 >> 16;
357         ulRxBytes &= usbRX_COUNT_MASK;
358
359         if( pxMessage->ulCSR0 & AT91C_UDP_TXCOMP )
360         {
361                 /* We received a TX complete interrupt.  What we do depends on
362                 what we sent to get this interrupt. */
363
364                 if( eDriverState == eJUST_GOT_CONFIG )
365                 {
366                         /* We sent an acknowledgement of a SET_CONFIG request.  We
367                         are now at the end of the enumeration.
368                         
369                         TODO: Config 0 sets unconfigured state, should enter Address state.
370                         Request for unsupported config should stall. */
371                         AT91C_BASE_UDP->UDP_GLBSTATE = AT91C_UDP_CONFG;
372                         
373                         /* Set up endpoints */
374                         portENTER_CRITICAL();
375                         {
376                                 unsigned long ulTemp;
377
378                                 /* Set endpoint 1 to bulk-out */
379                                 ulTemp = AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_1 ];                                     
380                                 usbCSR_SET_BIT( &ulTemp, AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_BULK_OUT );
381                                 AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_1 ] = ulTemp;             
382                                 AT91C_BASE_UDP->UDP_IER = AT91C_UDP_EPINT1;
383                                 /* Set endpoint 2 to bulk-in */
384                                 ulTemp = AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_2 ];                                     
385                                 usbCSR_SET_BIT( &ulTemp, AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_BULK_IN );
386                                 AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_2 ] = ulTemp;             
387                                 AT91C_BASE_UDP->UDP_IER = AT91C_UDP_EPINT2;
388                                         /* Set endpoint 3 to interrupt-in, enable it, and enable interrupts */
389                                 ulTemp = AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_3 ];                                     
390                                 usbCSR_SET_BIT( &ulTemp, AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_INT_IN );
391                                 AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_3 ] = ulTemp;             
392                                 /*AT91F_UDP_EnableIt( AT91C_BASE_UDP, AT91C_UDP_EPINT3 );                                */
393                         }
394                         portEXIT_CRITICAL();
395
396                         eDriverState = eREADY_TO_SEND;
397                 }               
398                 else if( eDriverState == eJUST_GOT_ADDRESS )
399                 {
400                         /* We sent an acknowledgement of a SET_ADDRESS request.  Move
401                         to the addressed state. */
402                         if( ulReceivedAddress != ( unsigned long ) 0 )
403                         {                       
404                                 AT91C_BASE_UDP->UDP_GLBSTATE = AT91C_UDP_FADDEN;
405                         }
406                         else
407                         {
408                                 AT91C_BASE_UDP->UDP_GLBSTATE = 0;
409                         }                       
410
411                         AT91C_BASE_UDP->UDP_FADDR = ( AT91C_UDP_FEN | ulReceivedAddress );              
412                         eDriverState = eNOTHING;
413                 }
414                 else
415                 {               
416                         /* The TXCOMP was not for any special type of transmission.  See
417                         if there is any more data to send. */
418                         prvSendNextSegment();
419                 }
420         }
421
422         if( pxMessage->ulCSR0 & AT91C_UDP_RX_DATA_BK0 )
423         {
424                 /* Received a control data packet.  May be a 0-length ACK or a data stage. */
425                 unsigned char ucBytesToGet;
426          
427                 /* Got data.  Cancel any outgoing data. */
428                 pxControlTx.ulNextCharIndex = pxControlTx.ulTotalDataLength;
429                 
430                  /* Determine how many bytes we need to receive. */
431                 ucBytesToGet = pxControlRx.ulTotalDataLength - pxControlRx.ulNextCharIndex;
432                 if( ucBytesToGet > ulRxBytes ) 
433                 {       
434                         ucBytesToGet = ulRxBytes;
435                 }
436
437                 /* If we're not expecting any data, it's an ack - just quit now. */
438                 if( !ucBytesToGet )
439                 {
440                          return;
441                 }
442
443                 /* Get the required data and update the index. */
444                 memcpy( pxControlRx.ucBuffer, pxMessage->ucFifoData, ucBytesToGet );
445                 pxControlRx.ulNextCharIndex += ucBytesToGet;    
446         }
447
448         if( pxMessage->ulCSR0 & AT91C_UDP_RXSETUP )
449         {
450                 /* Received a SETUP packet.  May be followed by data packets. */
451
452                 if( ulRxBytes >= usbEXPECTED_NUMBER_OF_BYTES )
453                 {                               
454                         /* Create an xUSB_REQUEST variable from the raw bytes array. */
455
456                         xRequest.ucReqType = pxMessage->ucFifoData[ usbREQUEST_TYPE_INDEX ];
457                         xRequest.ucRequest = pxMessage->ucFifoData[ usbREQUEST_INDEX ];
458
459                         xRequest.usValue = pxMessage->ucFifoData[ usbVALUE_HIGH_BYTE ];
460                         xRequest.usValue <<= 8;
461                         xRequest.usValue |= pxMessage->ucFifoData[ usbVALUE_LOW_BYTE ];
462                                                 
463                         xRequest.usIndex = pxMessage->ucFifoData[ usbINDEX_HIGH_BYTE ];
464                         xRequest.usIndex <<= 8;
465                         xRequest.usIndex |= pxMessage->ucFifoData[ usbINDEX_LOW_BYTE ];
466                         
467                         xRequest.usLength = pxMessage->ucFifoData[ usbLENGTH_HIGH_BYTE ];
468                         xRequest.usLength <<= 8;
469                         xRequest.usLength |= pxMessage->ucFifoData[ usbLENGTH_LOW_BYTE ];
470
471                         pxControlRx.ulNextCharIndex = 0;
472                         if( ! (xRequest.ucReqType & 0x80) ) /* Host-to-Device transfer, may need to get data first */
473                         {
474                                 if( xRequest.usLength > usbMAX_CONTROL_MESSAGE_SIZE )
475                                 {       
476                                         /* Too big!  No space for control data, stall and abort. */
477                                         prvSendStall();
478                                         return;
479                                 }
480
481                                 pxControlRx.ulTotalDataLength = xRequest.usLength;
482                         }
483                         else
484                         {
485                                 /* We're sending the data, don't wait for any. */
486                                 pxControlRx.ulTotalDataLength = 0; 
487                         }
488                 }
489         }
490
491         /* See if we've got a pending request and all its associated data ready */
492         if( ( pxMessage->ulCSR0 & ( AT91C_UDP_RX_DATA_BK0 | AT91C_UDP_RXSETUP ) ) 
493                 && ( pxControlRx.ulNextCharIndex >= pxControlRx.ulTotalDataLength ) )
494         {
495                 unsigned char ucRequest;
496
497                 /* Manipulate the ucRequestType and the ucRequest parameters to 
498                 generate a zero based request selection.  This is just done to 
499                 break up the requests into subsections for clarity.  The 
500                 alternative would be to have more huge switch statement that would
501                 be difficult to optimise. */
502                 ucRequest = ( ( xRequest.ucReqType & 0x60 ) >> 3 );
503                 ucRequest |= ( xRequest.ucReqType & 0x03 );
504                         
505                 switch( ucRequest )
506                 {
507                         case usbSTANDARD_DEVICE_REQUEST:        
508                                 /* Standard Device request */
509                                 prvHandleStandardDeviceRequest( &xRequest );
510                                 break;
511
512                         case usbSTANDARD_INTERFACE_REQUEST:     
513                                 /* Standard Interface request */
514                                 prvHandleStandardInterfaceRequest( &xRequest );
515                                 break;
516
517                         case usbSTANDARD_END_POINT_REQUEST:     
518                                 /* Standard Endpoint request */
519                                 prvHandleStandardEndPointRequest( &xRequest );
520                                 break;
521
522                         case usbCLASS_INTERFACE_REQUEST:        
523                                 /* Class Interface request */
524                                 prvHandleClassInterfaceRequest( &xRequest );
525                                 break;
526
527                         default:        /* This is not something we want to respond to. */
528                                 prvSendStall(); 
529                 }
530         }
531 }
532 /*------------------------------------------------------------*/
533
534 static void prvGetStandardDeviceDescriptor( xUSB_REQUEST *pxRequest )
535 {
536         /* The type is in the high byte.  Return whatever has been requested. */
537         switch( ( pxRequest->usValue & 0xff00 ) >> 8 )
538         {
539                 case usbDESCRIPTOR_TYPE_DEVICE:
540                         prvSendControlData( ( unsigned char * ) &pxDeviceDescriptor, pxRequest->usLength, sizeof( pxDeviceDescriptor ), pdTRUE );
541                         break;
542
543                 case usbDESCRIPTOR_TYPE_CONFIGURATION:
544                         prvSendControlData( ( unsigned char * ) &( pxConfigDescriptor ), pxRequest->usLength, sizeof( pxConfigDescriptor ), pdTRUE );
545                         break;
546
547                 case usbDESCRIPTOR_TYPE_STRING:
548
549                         /* The index to the string descriptor is the lower byte. */
550                         switch( pxRequest->usValue & 0xff )
551                         {                       
552                                 case usbLANGUAGE_STRING:
553                                         prvSendControlData( ( unsigned char * ) &pxLanguageStringDescriptor, pxRequest->usLength, sizeof(pxLanguageStringDescriptor), pdTRUE );
554                                         break;
555
556                                 case usbMANUFACTURER_STRING:
557                                         prvSendControlData( ( unsigned char * ) &pxManufacturerStringDescriptor, pxRequest->usLength, sizeof( pxManufacturerStringDescriptor ), pdTRUE );
558                                         break;
559
560                                 case usbPRODUCT_STRING:
561                                         prvSendControlData( ( unsigned char * ) &pxProductStringDescriptor, pxRequest->usLength, sizeof( pxProductStringDescriptor ), pdTRUE );
562                                         break;
563
564                                 case usbCONFIGURATION_STRING:
565                                         prvSendControlData( ( unsigned char * ) &pxConfigurationStringDescriptor, pxRequest->usLength, sizeof( pxConfigurationStringDescriptor ), pdTRUE );
566                                         break;
567
568                                 case usbINTERFACE_STRING:
569                                         prvSendControlData( ( unsigned char * ) &pxInterfaceStringDescriptor, pxRequest->usLength, sizeof( pxInterfaceStringDescriptor ), pdTRUE );
570                                         break;
571
572                                 default:
573                                         prvSendStall();
574                                         break;
575                         }
576                         break;
577
578                 default:
579                         prvSendStall();
580                         break;
581         }
582 }
583 /*------------------------------------------------------------*/
584
585 static void prvHandleStandardDeviceRequest( xUSB_REQUEST *pxRequest )
586 {
587 unsigned short usStatus = 0;
588
589         switch( pxRequest->ucRequest )
590         {
591                 case usbGET_STATUS_REQUEST:
592                         /* Just send two byte dummy status. */
593                         prvSendControlData( ( unsigned char * ) &usStatus, sizeof( usStatus ), sizeof( usStatus ), pdFALSE );
594                         break;
595
596                 case usbGET_DESCRIPTOR_REQUEST:
597                         /* Send device descriptor */
598                         prvGetStandardDeviceDescriptor( pxRequest );
599                         break;
600
601                 case usbGET_CONFIGURATION_REQUEST:
602                         /* Send selected device configuration */
603                         prvSendControlData( ( unsigned char * ) &ucUSBConfig, sizeof( ucUSBConfig ), sizeof( ucUSBConfig ), pdFALSE );
604                         break;
605
606                 case usbSET_FEATURE_REQUEST:
607                         prvSendZLP();
608                         break;
609
610                 case usbSET_ADDRESS_REQUEST:                    
611                         /* Get assigned address and send ack, but don't implement new address until we get a TXCOMP */
612                         prvSendZLP();                   
613                         eDriverState = eJUST_GOT_ADDRESS;                       
614                         ulReceivedAddress = ( unsigned long ) pxRequest->usValue;
615                         break;
616
617                 case usbSET_CONFIGURATION_REQUEST:
618                         /* Ack SET_CONFIGURATION request, but don't implement until TXCOMP */
619                         ucUSBConfig = ( unsigned char ) ( pxRequest->usValue & 0xff );
620                         eDriverState = eJUST_GOT_CONFIG;
621                         prvSendZLP();
622                         break;
623
624                 default:
625                         /* Any unsupported request results in a STALL response. */
626                         prvSendStall();
627                         break;
628         }
629 }
630 /*------------------------------------------------------------*/
631
632 static void prvHandleClassInterfaceRequest( xUSB_REQUEST *pxRequest )
633 {
634         switch( pxRequest->ucRequest )
635         {
636                 case usbSEND_ENCAPSULATED_COMMAND:
637                         prvSendStall();
638                         break;
639
640                 case usbGET_ENCAPSULATED_RESPONSE:
641                         prvSendStall();
642                         break;
643
644                 case usbSET_LINE_CODING:
645                         /* Set line coding - baud rate, data bits, parity, stop bits */
646                         prvSendZLP();
647                         memcpy( ( void * ) pxLineCoding, pxControlRx.ucBuffer, sizeof( pxLineCoding ) );
648                         break;
649
650                 case usbGET_LINE_CODING:
651                         /* Get line coding */
652                         prvSendControlData( (unsigned char *) &pxLineCoding, pxRequest->usLength, sizeof( pxLineCoding ), pdFALSE );
653                         break;
654
655                 case usbSET_CONTROL_LINE_STATE:
656                         /* D0: 1=DTR, 0=No DTR,  D1: 1=Activate Carrier, 0=Deactivate carrier (RTS, half-duplex) */
657                         prvSendZLP();
658                         ucControlState = pxRequest->usValue;
659                         break;
660
661                 default:
662                         prvSendStall();
663                         break;
664         }
665 }
666 /*------------------------------------------------------------*/
667
668 static void prvGetStandardInterfaceDescriptor( xUSB_REQUEST *pxRequest )
669 {
670         switch( ( pxRequest->usValue & ( unsigned short ) 0xff00 ) >> 8 )
671         {
672                 default:
673                         prvSendStall();
674                         break;
675         }
676 }
677 /*-----------------------------------------------------------*/
678
679 static void prvHandleStandardInterfaceRequest( xUSB_REQUEST *pxRequest )
680 {
681 unsigned short usStatus = 0;
682
683         switch( pxRequest->ucRequest )
684         {
685                 case usbGET_STATUS_REQUEST:
686                         /* Send dummy 2 bytes. */
687                         prvSendControlData( ( unsigned char * ) &usStatus, sizeof( usStatus ), sizeof( usStatus ), pdFALSE );
688                         break;
689
690                 case usbGET_DESCRIPTOR_REQUEST:
691                         prvGetStandardInterfaceDescriptor( pxRequest ); 
692                         break;
693
694                 /* This minimal implementation does not respond to these. */
695                 case usbGET_INTERFACE_REQUEST:
696                 case usbSET_FEATURE_REQUEST:
697                 case usbSET_INTERFACE_REQUEST:  
698
699                 default:
700                         prvSendStall();
701                         break;
702         }
703 }
704 /*-----------------------------------------------------------*/
705
706 static void prvHandleStandardEndPointRequest( xUSB_REQUEST *pxRequest )
707 {
708         switch( pxRequest->ucRequest )
709         {
710                 /* This minimal implementation does not expect to respond to these. */
711                 case usbGET_STATUS_REQUEST:
712                 case usbCLEAR_FEATURE_REQUEST: 
713                 case usbSET_FEATURE_REQUEST:
714
715                 default:                        
716                         prvSendStall();
717                         break;
718         }
719 }
720 /*-----------------------------------------------------------*/
721
722 static void vDetachUSBInterface( void)
723 {
724         /* Setup the PIO for the USB pull up resistor. */
725         AT91C_BASE_PIOA->PIO_PER = AT91C_PIO_PA16;
726         AT91C_BASE_PIOA->PIO_OER = AT91C_PIO_PA16;
727
728
729         /* Disable pull up */
730         AT91C_BASE_PIOA->PIO_SODR = AT91C_PIO_PA16;
731
732 /*-----------------------------------------------------------*/
733
734 static void vInitUSBInterface( void )
735 {
736 extern void ( vUSB_ISR_Wrapper )( void );
737
738         /* Create the queue used to communicate between the USB ISR and task. */
739         xUSBInterruptQueue = xQueueCreate( usbQUEUE_LENGTH + 1, sizeof( xISRStatus * ) );
740         
741         /* Create the queues used to hold Rx and Tx characters. */
742         xRxCDC = xQueueCreate( USB_CDC_QUEUE_SIZE, ( unsigned char ) sizeof( signed char ) );
743         xTxCDC = xQueueCreate( USB_CDC_QUEUE_SIZE + 1, ( unsigned char ) sizeof( signed char ) );
744
745         if( (!xUSBInterruptQueue) || (!xRxCDC) || (!xTxCDC) )
746         {       
747                 /* Not enough RAM to create queues!. */
748                 return;
749         }
750         
751         /* Initialise a few state variables. */
752         pxControlTx.ulNextCharIndex = ( unsigned long ) 0;
753         pxControlRx.ulNextCharIndex = ( unsigned long ) 0;
754         ucUSBConfig = ( unsigned char ) 0;
755         eDriverState = eNOTHING;
756         ucControlState = 0;
757         uiCurrentBank = AT91C_UDP_RX_DATA_BK0;
758
759
760         /* HARDWARE SETUP */
761
762         /* Set the PLL USB Divider */
763         AT91C_BASE_CKGR->CKGR_PLLR |= AT91C_CKGR_USBDIV_1;
764
765         /* Enables the 48MHz USB clock UDPCK and System Peripheral USB Clock. */
766         AT91C_BASE_PMC->PMC_SCER = AT91C_PMC_UDP;
767         AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_UDP);
768
769         /* Setup the PIO for the USB pull up resistor. */
770         AT91C_BASE_PIOA->PIO_PER = AT91C_PIO_PA16;
771         AT91C_BASE_PIOA->PIO_OER = AT91C_PIO_PA16;
772
773
774         /* Start without the pullup - this will get set at the end of this 
775         function. */
776         AT91C_BASE_PIOA->PIO_SODR = AT91C_PIO_PA16;
777
778
779         /* When using the USB debugger the peripheral registers do not always get
780         set to the correct default values.  To make sure set the relevant registers
781         manually here. */
782         AT91C_BASE_UDP->UDP_IDR = ( unsigned long ) 0xffffffff;
783         AT91C_BASE_UDP->UDP_ICR = ( unsigned long ) 0xffffffff;
784         AT91C_BASE_UDP->UDP_CSR[ 0 ] = ( unsigned long ) 0x00;
785         AT91C_BASE_UDP->UDP_CSR[ 1 ] = ( unsigned long ) 0x00;
786         AT91C_BASE_UDP->UDP_CSR[ 2 ] = ( unsigned long ) 0x00;
787         AT91C_BASE_UDP->UDP_CSR[ 3 ] = ( unsigned long ) 0x00;
788         AT91C_BASE_UDP->UDP_GLBSTATE = 0;
789         AT91C_BASE_UDP->UDP_FADDR = 0;
790
791         /* Enable the transceiver. */
792         AT91C_UDP_TRANSCEIVER_ENABLE = 0;
793
794         /* Enable the USB interrupts - other interrupts get enabled as the 
795         enumeration process progresses. */
796         AT91F_AIC_ConfigureIt( AT91C_ID_UDP, usbINTERRUPT_PRIORITY, AT91C_AIC_SRCTYPE_INT_HIGH_LEVEL, ( void (*)( void ) ) vUSB_ISR_Wrapper );
797         AT91C_BASE_AIC->AIC_IECR = 0x1 << AT91C_ID_UDP;
798
799
800         /* Wait a short while before making our presence known. */
801         vTaskDelay( usbINIT_DELAY );
802         AT91C_BASE_PIOA->PIO_CODR = AT91C_PIO_PA16;
803 }
804 /*-----------------------------------------------------------*/
805
806 static void prvSendControlData( unsigned char *pucData, unsigned short usRequestedLength, unsigned long ulLengthToSend, long lSendingDescriptor )
807 {
808         if( ( ( unsigned long ) usRequestedLength < ulLengthToSend ) )
809         {
810                 /* Cap the data length to that requested. */
811                 ulLengthToSend = ( unsigned short ) usRequestedLength;
812         }
813         else if( ( ulLengthToSend < ( unsigned long ) usRequestedLength ) && lSendingDescriptor )
814         {
815                 /* We are sending a descriptor.  If the descriptor is an exact 
816                 multiple of the FIFO length then it will have to be terminated
817                 with a NULL packet.  Set the state to indicate this if
818                 necessary. */
819                 if( ( ulLengthToSend % usbFIFO_LENGTH ) == 0 )
820                 {
821                         eDriverState = eSENDING_EVEN_DESCRIPTOR;
822                 }
823         }
824
825         /* Here we assume that the previous message has been sent.  THERE IS NO
826         BUFFER OVERFLOW PROTECTION HERE.
827
828         Copy the data to send into the buffer as we cannot send it all at once
829         (if it is greater than 8 bytes in length). */
830         memcpy( pxControlTx.ucBuffer, pucData, ulLengthToSend );
831
832         /* Reinitialise the buffer index so we start sending from the start of 
833         the data. */
834         pxControlTx.ulTotalDataLength = ulLengthToSend;
835         pxControlTx.ulNextCharIndex = ( unsigned long ) 0;
836
837         /* Send the first 8 bytes now.  The rest will get sent in response to 
838         TXCOMP interrupts. */
839         prvSendNextSegment();
840 }
841 /*-----------------------------------------------------------*/
842
843 static void prvSendNextSegment( void )
844 {
845 volatile unsigned long ulNextLength, ulStatus, ulLengthLeftToSend;
846
847         /* Is there any data to send? */
848         if( pxControlTx.ulTotalDataLength > pxControlTx.ulNextCharIndex )
849         {
850                 ulLengthLeftToSend = pxControlTx.ulTotalDataLength - pxControlTx.ulNextCharIndex;
851         
852                 /* We can only send 8 bytes to the fifo at a time. */
853                 if( ulLengthLeftToSend > usbFIFO_LENGTH )
854                 {
855                         ulNextLength = usbFIFO_LENGTH;
856                 }
857                 else
858                 {
859                         ulNextLength = ulLengthLeftToSend;
860                 }
861
862                 /* Wait until we can place data in the fifo.  THERE IS NO TIMEOUT
863                 HERE! */
864                 while( AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ] & AT91C_UDP_TXPKTRDY )
865                 {
866                         vTaskDelay( usbSHORTEST_DELAY );
867                 }
868
869                 /* Write the data to the FIFO. */
870                 while( ulNextLength > ( unsigned long ) 0 )
871                 {
872                         AT91C_BASE_UDP->UDP_FDR[ usbEND_POINT_0 ] = pxControlTx.ucBuffer[ pxControlTx.ulNextCharIndex ];
873         
874                         ulNextLength--;
875                         pxControlTx.ulNextCharIndex++;
876                 }
877         
878                 /* Start the transmission. */
879                 portENTER_CRITICAL();
880                 {
881                         ulStatus = AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ];
882                         usbCSR_SET_BIT( &ulStatus, ( ( unsigned long ) 0x10 ) );
883                         AT91C_BASE_UDP->UDP_CSR[ usbEND_POINT_0 ] = ulStatus;
884                 }
885                 portEXIT_CRITICAL();
886         }
887         else
888         {
889                 /* There is no data to send.  If we were sending a descriptor and the 
890                 descriptor was an exact multiple of the max packet size then we need
891                 to send a null to terminate the transmission. */
892                 if( eDriverState == eSENDING_EVEN_DESCRIPTOR )
893                 {
894                         prvSendZLP();
895                         eDriverState = eNOTHING;
896                 }
897         }
898 }
899
900