manueller import aus nem CVS checkout (ist eh nur zum testen)
[ds1820tousb.git] / usbdrv / usbdrv.c
1 /* Name: usbdrv.c
2  * Project: AVR USB driver
3  * Author: Christian Starkjohann
4  * Creation Date: 2004-12-29
5  * Tabsize: 4
6  * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
7  * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
8  * This Revision: $Id: usbdrv.c 692 2008-11-07 15:07:40Z cs $
9  */
10
11 #include "usbportability.h"
12 #include "usbdrv.h"
13 #include "oddebug.h"
14
15 /*
16 General Description:
17 This module implements the C-part of the USB driver. See usbdrv.h for a
18 documentation of the entire driver.
19 */
20
21 /* ------------------------------------------------------------------------- */
22
23 /* raw USB registers / interface to assembler code: */
24 uchar usbRxBuf[2*USB_BUFSIZE];  /* raw RX buffer: PID, 8 bytes data, 2 bytes CRC */
25 uchar       usbInputBufOffset;  /* offset in usbRxBuf used for low level receiving */
26 uchar       usbDeviceAddr;      /* assigned during enumeration, defaults to 0 */
27 uchar       usbNewDeviceAddr;   /* device ID which should be set after status phase */
28 uchar       usbConfiguration;   /* currently selected configuration. Administered by driver, but not used */
29 volatile schar usbRxLen;        /* = 0; number of bytes in usbRxBuf; 0 means free, -1 for flow control */
30 uchar       usbCurrentTok;      /* last token received or endpoint number for last OUT token if != 0 */
31 uchar       usbRxToken;         /* token for data we received; or endpont number for last OUT */
32 volatile uchar usbTxLen = USBPID_NAK;   /* number of bytes to transmit with next IN token or handshake token */
33 uchar       usbTxBuf[USB_BUFSIZE];/* data to transmit with next IN, free if usbTxLen contains handshake token */
34 #if USB_COUNT_SOF
35 volatile uchar  usbSofCount;    /* incremented by assembler module every SOF */
36 #endif
37 #if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
38 usbTxStatus_t  usbTxStatus1;
39 #   if USB_CFG_HAVE_INTRIN_ENDPOINT3
40 usbTxStatus_t  usbTxStatus3;
41 #   endif
42 #endif
43 #if USB_CFG_CHECK_DATA_TOGGLING
44 uchar       usbCurrentDataToken;/* when we check data toggling to ignore duplicate packets */
45 #endif
46
47 /* USB status registers / not shared with asm code */
48 uchar               *usbMsgPtr;     /* data to transmit next -- ROM or RAM address */
49 static usbMsgLen_t  usbMsgLen = USB_NO_MSG; /* remaining number of bytes */
50 static uchar        usbMsgFlags;    /* flag values see below */
51
52 #define USB_FLG_MSGPTR_IS_ROM   (1<<6)
53 #define USB_FLG_USE_USER_RW     (1<<7)
54
55 /*
56 optimizing hints:
57 - do not post/pre inc/dec integer values in operations
58 - assign value of USB_READ_FLASH() to register variables and don't use side effects in arg
59 - use narrow scope for variables which should be in X/Y/Z register
60 - assign char sized expressions to variables to force 8 bit arithmetics
61 */
62
63 /* -------------------------- String Descriptors --------------------------- */
64
65 #if USB_CFG_DESCR_PROPS_STRINGS == 0
66
67 #if USB_CFG_DESCR_PROPS_STRING_0 == 0
68 #undef USB_CFG_DESCR_PROPS_STRING_0
69 #define USB_CFG_DESCR_PROPS_STRING_0    sizeof(usbDescriptorString0)
70 PROGMEM char usbDescriptorString0[] = { /* language descriptor */
71     4,          /* sizeof(usbDescriptorString0): length of descriptor in bytes */
72     3,          /* descriptor type */
73     0x09, 0x04, /* language index (0x0409 = US-English) */
74 };
75 #endif
76
77 #if USB_CFG_DESCR_PROPS_STRING_VENDOR == 0 && USB_CFG_VENDOR_NAME_LEN
78 #undef USB_CFG_DESCR_PROPS_STRING_VENDOR
79 #define USB_CFG_DESCR_PROPS_STRING_VENDOR   sizeof(usbDescriptorStringVendor)
80 PROGMEM int  usbDescriptorStringVendor[] = {
81     USB_STRING_DESCRIPTOR_HEADER(USB_CFG_VENDOR_NAME_LEN),
82     USB_CFG_VENDOR_NAME
83 };
84 #endif
85
86 #if USB_CFG_DESCR_PROPS_STRING_PRODUCT == 0 && USB_CFG_DEVICE_NAME_LEN
87 #undef USB_CFG_DESCR_PROPS_STRING_PRODUCT
88 #define USB_CFG_DESCR_PROPS_STRING_PRODUCT   sizeof(usbDescriptorStringDevice)
89 PROGMEM int  usbDescriptorStringDevice[] = {
90     USB_STRING_DESCRIPTOR_HEADER(USB_CFG_DEVICE_NAME_LEN),
91     USB_CFG_DEVICE_NAME
92 };
93 #endif
94
95 #if USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER == 0 && USB_CFG_SERIAL_NUMBER_LEN
96 #undef USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
97 #define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER    sizeof(usbDescriptorStringSerialNumber)
98 PROGMEM int usbDescriptorStringSerialNumber[] = {
99     USB_STRING_DESCRIPTOR_HEADER(USB_CFG_SERIAL_NUMBER_LEN),
100     USB_CFG_SERIAL_NUMBER
101 };
102 #endif
103
104 #endif  /* USB_CFG_DESCR_PROPS_STRINGS == 0 */
105
106 /* --------------------------- Device Descriptor --------------------------- */
107
108 #if USB_CFG_DESCR_PROPS_DEVICE == 0
109 #undef USB_CFG_DESCR_PROPS_DEVICE
110 #define USB_CFG_DESCR_PROPS_DEVICE  sizeof(usbDescriptorDevice)
111 PROGMEM char usbDescriptorDevice[] = {    /* USB device descriptor */
112     18,         /* sizeof(usbDescriptorDevice): length of descriptor in bytes */
113     USBDESCR_DEVICE,        /* descriptor type */
114     0x10, 0x01,             /* USB version supported */
115     USB_CFG_DEVICE_CLASS,
116     USB_CFG_DEVICE_SUBCLASS,
117     0,                      /* protocol */
118     8,                      /* max packet size */
119     /* the following two casts affect the first byte of the constant only, but
120      * that's sufficient to avoid a warning with the default values.
121      */
122     (char)USB_CFG_VENDOR_ID,/* 2 bytes */
123     (char)USB_CFG_DEVICE_ID,/* 2 bytes */
124     USB_CFG_DEVICE_VERSION, /* 2 bytes */
125     USB_CFG_DESCR_PROPS_STRING_VENDOR != 0 ? 1 : 0,         /* manufacturer string index */
126     USB_CFG_DESCR_PROPS_STRING_PRODUCT != 0 ? 2 : 0,        /* product string index */
127     USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER != 0 ? 3 : 0,  /* serial number string index */
128     1,          /* number of configurations */
129 };
130 #endif
131
132 /* ----------------------- Configuration Descriptor ------------------------ */
133
134 #if USB_CFG_DESCR_PROPS_HID_REPORT != 0 && USB_CFG_DESCR_PROPS_HID == 0
135 #undef USB_CFG_DESCR_PROPS_HID
136 #define USB_CFG_DESCR_PROPS_HID     9   /* length of HID descriptor in config descriptor below */
137 #endif
138
139 #if USB_CFG_DESCR_PROPS_CONFIGURATION == 0
140 #undef USB_CFG_DESCR_PROPS_CONFIGURATION
141 #define USB_CFG_DESCR_PROPS_CONFIGURATION   sizeof(usbDescriptorConfiguration)
142 PROGMEM char usbDescriptorConfiguration[] = {    /* USB configuration descriptor */
143     9,          /* sizeof(usbDescriptorConfiguration): length of descriptor in bytes */
144     USBDESCR_CONFIG,    /* descriptor type */
145     18 + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT3 +
146                 (USB_CFG_DESCR_PROPS_HID & 0xff), 0,
147                 /* total length of data returned (including inlined descriptors) */
148     1,          /* number of interfaces in this configuration */
149     1,          /* index of this configuration */
150     0,          /* configuration name string index */
151 #if USB_CFG_IS_SELF_POWERED
152     USBATTR_SELFPOWER,      /* attributes */
153 #else
154     (char)USBATTR_BUSPOWER, /* attributes */
155 #endif
156     USB_CFG_MAX_BUS_POWER/2,            /* max USB current in 2mA units */
157 /* interface descriptor follows inline: */
158     9,          /* sizeof(usbDescrInterface): length of descriptor in bytes */
159     USBDESCR_INTERFACE, /* descriptor type */
160     0,          /* index of this interface */
161     0,          /* alternate setting for this interface */
162     USB_CFG_HAVE_INTRIN_ENDPOINT + USB_CFG_HAVE_INTRIN_ENDPOINT3, /* endpoints excl 0: number of endpoint descriptors to follow */
163     USB_CFG_INTERFACE_CLASS,
164     USB_CFG_INTERFACE_SUBCLASS,
165     USB_CFG_INTERFACE_PROTOCOL,
166     0,          /* string index for interface */
167 #if (USB_CFG_DESCR_PROPS_HID & 0xff)    /* HID descriptor */
168     9,          /* sizeof(usbDescrHID): length of descriptor in bytes */
169     USBDESCR_HID,   /* descriptor type: HID */
170     0x01, 0x01, /* BCD representation of HID version */
171     0x00,       /* target country code */
172     0x01,       /* number of HID Report (or other HID class) Descriptor infos to follow */
173     0x22,       /* descriptor type: report */
174     USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH, 0,  /* total length of report descriptor */
175 #endif
176 #if USB_CFG_HAVE_INTRIN_ENDPOINT    /* endpoint descriptor for endpoint 1 */
177     7,          /* sizeof(usbDescrEndpoint) */
178     USBDESCR_ENDPOINT,  /* descriptor type = endpoint */
179     (char)0x81, /* IN endpoint number 1 */
180     0x03,       /* attrib: Interrupt endpoint */
181     8, 0,       /* maximum packet size */
182     USB_CFG_INTR_POLL_INTERVAL, /* in ms */
183 #endif
184 #if USB_CFG_HAVE_INTRIN_ENDPOINT3   /* endpoint descriptor for endpoint 3 */
185     7,          /* sizeof(usbDescrEndpoint) */
186     USBDESCR_ENDPOINT,  /* descriptor type = endpoint */
187     (char)0x83, /* IN endpoint number 1 */
188     0x03,       /* attrib: Interrupt endpoint */
189     8, 0,       /* maximum packet size */
190     USB_CFG_INTR_POLL_INTERVAL, /* in ms */
191 #endif
192 };
193 #endif
194
195 /* ------------------------------------------------------------------------- */
196
197 static inline void  usbResetDataToggling(void)
198 {
199 #if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
200     USB_SET_DATATOKEN1(USB_INITIAL_DATATOKEN);  /* reset data toggling for interrupt endpoint */
201 #   if USB_CFG_HAVE_INTRIN_ENDPOINT3
202     USB_SET_DATATOKEN3(USB_INITIAL_DATATOKEN);  /* reset data toggling for interrupt endpoint */
203 #   endif
204 #endif
205 }
206
207 static inline void  usbResetStall(void)
208 {
209 #if USB_CFG_IMPLEMENT_HALT && USB_CFG_HAVE_INTRIN_ENDPOINT
210         usbTxLen1 = USBPID_NAK;
211 #if USB_CFG_HAVE_INTRIN_ENDPOINT3
212         usbTxLen3 = USBPID_NAK;
213 #endif
214 #endif
215 }
216
217 /* ------------------------------------------------------------------------- */
218
219 #if !USB_CFG_SUPPRESS_INTR_CODE
220 #if USB_CFG_HAVE_INTRIN_ENDPOINT
221 static void usbGenericSetInterrupt(uchar *data, uchar len, usbTxStatus_t *txStatus)
222 {
223 uchar   *p;
224 char    i;
225
226 #if USB_CFG_IMPLEMENT_HALT
227     if(usbTxLen1 == USBPID_STALL)
228         return;
229 #endif
230     if(txStatus->len & 0x10){   /* packet buffer was empty */
231         txStatus->buffer[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* toggle token */
232     }else{
233         txStatus->len = USBPID_NAK; /* avoid sending outdated (overwritten) interrupt data */
234     }
235     p = txStatus->buffer + 1;
236     i = len;
237     do{                         /* if len == 0, we still copy 1 byte, but that's no problem */
238         *p++ = *data++;
239     }while(--i > 0);            /* loop control at the end is 2 bytes shorter than at beginning */
240     usbCrc16Append(&txStatus->buffer[1], len);
241     txStatus->len = len + 4;    /* len must be given including sync byte */
242     DBG2(0x21 + (((int)txStatus >> 3) & 3), txStatus->buffer, len + 3);
243 }
244
245 USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len)
246 {
247     usbGenericSetInterrupt(data, len, &usbTxStatus1);
248 }
249 #endif
250
251 #if USB_CFG_HAVE_INTRIN_ENDPOINT3
252 USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len)
253 {
254     usbGenericSetInterrupt(data, len, &usbTxStatus3);
255 }
256 #endif
257 #endif /* USB_CFG_SUPPRESS_INTR_CODE */
258
259 /* ------------------ utilities for code following below ------------------- */
260
261 /* Use defines for the switch statement so that we can choose between an
262  * if()else if() and a switch/case based implementation. switch() is more
263  * efficient for a LARGE set of sequential choices, if() is better in all other
264  * cases.
265  */
266 #if USB_CFG_USE_SWITCH_STATEMENT
267 #   define SWITCH_START(cmd)       switch(cmd){{
268 #   define SWITCH_CASE(value)      }break; case (value):{
269 #   define SWITCH_CASE2(v1,v2)     }break; case (v1): case(v2):{
270 #   define SWITCH_CASE3(v1,v2,v3)  }break; case (v1): case(v2): case(v3):{
271 #   define SWITCH_DEFAULT          }break; default:{
272 #   define SWITCH_END              }}
273 #else
274 #   define SWITCH_START(cmd)       {uchar _cmd = cmd; if(0){
275 #   define SWITCH_CASE(value)      }else if(_cmd == (value)){
276 #   define SWITCH_CASE2(v1,v2)     }else if(_cmd == (v1) || _cmd == (v2)){
277 #   define SWITCH_CASE3(v1,v2,v3)  }else if(_cmd == (v1) || _cmd == (v2) || (_cmd == v3)){
278 #   define SWITCH_DEFAULT          }else{
279 #   define SWITCH_END              }}
280 #endif
281
282 #ifndef USB_RX_USER_HOOK
283 #define USB_RX_USER_HOOK(data, len)
284 #endif
285 #ifndef USB_SET_ADDRESS_HOOK
286 #define USB_SET_ADDRESS_HOOK()
287 #endif
288
289 /* ------------------------------------------------------------------------- */
290
291 /* We use if() instead of #if in the macro below because #if can't be used
292  * in macros and the compiler optimizes constant conditions anyway.
293  * This may cause problems with undefined symbols if compiled without
294  * optimizing!
295  */
296 #define GET_DESCRIPTOR(cfgProp, staticName)         \
297     if(cfgProp){                                    \
298         if((cfgProp) & USB_PROP_IS_RAM)             \
299             flags = 0;                              \
300         if((cfgProp) & USB_PROP_IS_DYNAMIC){        \
301             len = usbFunctionDescriptor(rq);        \
302         }else{                                      \
303             len = USB_PROP_LENGTH(cfgProp);         \
304             usbMsgPtr = (uchar *)(staticName);      \
305         }                                           \
306     }
307
308 /* usbDriverDescriptor() is similar to usbFunctionDescriptor(), but used
309  * internally for all types of descriptors.
310  */
311 static inline usbMsgLen_t usbDriverDescriptor(usbRequest_t *rq)
312 {
313 usbMsgLen_t len = 0;
314 uchar       flags = USB_FLG_MSGPTR_IS_ROM;
315
316     SWITCH_START(rq->wValue.bytes[1])
317     SWITCH_CASE(USBDESCR_DEVICE)    /* 1 */
318         GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_DEVICE, usbDescriptorDevice)
319     SWITCH_CASE(USBDESCR_CONFIG)    /* 2 */
320         GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_CONFIGURATION, usbDescriptorConfiguration)
321     SWITCH_CASE(USBDESCR_STRING)    /* 3 */
322 #if USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC
323         if(USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_RAM)
324             flags = 0;
325         len = usbFunctionDescriptor(rq);
326 #else   /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
327         SWITCH_START(rq->wValue.bytes[0])
328         SWITCH_CASE(0)
329             GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_0, usbDescriptorString0)
330         SWITCH_CASE(1)
331             GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_VENDOR, usbDescriptorStringVendor)
332         SWITCH_CASE(2)
333             GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_PRODUCT, usbDescriptorStringDevice)
334         SWITCH_CASE(3)
335             GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER, usbDescriptorStringSerialNumber)
336         SWITCH_DEFAULT
337             if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
338                 len = usbFunctionDescriptor(rq);
339             }
340         SWITCH_END
341 #endif  /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
342 #if USB_CFG_DESCR_PROPS_HID_REPORT  /* only support HID descriptors if enabled */
343     SWITCH_CASE(USBDESCR_HID)       /* 0x21 */
344         GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID, usbDescriptorConfiguration + 18)
345     SWITCH_CASE(USBDESCR_HID_REPORT)/* 0x22 */
346         GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID_REPORT, usbDescriptorHidReport)
347 #endif
348     SWITCH_DEFAULT
349         if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
350             len = usbFunctionDescriptor(rq);
351         }
352     SWITCH_END
353     usbMsgFlags = flags;
354     return len;
355 }
356
357 /* ------------------------------------------------------------------------- */
358
359 /* usbDriverSetup() is similar to usbFunctionSetup(), but it's used for
360  * standard requests instead of class and custom requests.
361  */
362 static inline usbMsgLen_t usbDriverSetup(usbRequest_t *rq)
363 {
364 uchar   len  = 0, *dataPtr = usbTxBuf + 9;  /* there are 2 bytes free space at the end of the buffer */
365 uchar   value = rq->wValue.bytes[0];
366 #if USB_CFG_IMPLEMENT_HALT
367 uchar   index = rq->wIndex.bytes[0];
368 #endif
369
370     dataPtr[0] = 0; /* default reply common to USBRQ_GET_STATUS and USBRQ_GET_INTERFACE */
371     SWITCH_START(rq->bRequest)
372     SWITCH_CASE(USBRQ_GET_STATUS)           /* 0 */
373         uchar recipient = rq->bmRequestType & USBRQ_RCPT_MASK;  /* assign arith ops to variables to enforce byte size */
374         if(USB_CFG_IS_SELF_POWERED && recipient == USBRQ_RCPT_DEVICE)
375             dataPtr[0] =  USB_CFG_IS_SELF_POWERED;
376 #if USB_CFG_IMPLEMENT_HALT
377         if(recipient == USBRQ_RCPT_ENDPOINT && index == 0x81)   /* request status for endpoint 1 */
378             dataPtr[0] = usbTxLen1 == USBPID_STALL;
379 #endif
380         dataPtr[1] = 0;
381         len = 2;
382 #if USB_CFG_IMPLEMENT_HALT
383     SWITCH_CASE2(USBRQ_CLEAR_FEATURE, USBRQ_SET_FEATURE)    /* 1, 3 */
384         if(value == 0 && index == 0x81){    /* feature 0 == HALT for endpoint == 1 */
385             usbTxLen1 = rq->bRequest == USBRQ_CLEAR_FEATURE ? USBPID_NAK : USBPID_STALL;
386             usbResetDataToggling();
387         }
388 #endif
389     SWITCH_CASE(USBRQ_SET_ADDRESS)          /* 5 */
390         usbNewDeviceAddr = value;
391         USB_SET_ADDRESS_HOOK();
392     SWITCH_CASE(USBRQ_GET_DESCRIPTOR)       /* 6 */
393         len = usbDriverDescriptor(rq);
394         goto skipMsgPtrAssignment;
395     SWITCH_CASE(USBRQ_GET_CONFIGURATION)    /* 8 */
396         dataPtr = &usbConfiguration;  /* send current configuration value */
397         len = 1;
398     SWITCH_CASE(USBRQ_SET_CONFIGURATION)    /* 9 */
399         usbConfiguration = value;
400         usbResetStall();
401     SWITCH_CASE(USBRQ_GET_INTERFACE)        /* 10 */
402         len = 1;
403 #if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
404     SWITCH_CASE(USBRQ_SET_INTERFACE)        /* 11 */
405         usbResetDataToggling();
406         usbResetStall();
407 #endif
408     SWITCH_DEFAULT                          /* 7=SET_DESCRIPTOR, 12=SYNC_FRAME */
409         /* Should we add an optional hook here? */
410     SWITCH_END
411     usbMsgPtr = dataPtr;
412 skipMsgPtrAssignment:
413     return len;
414 }
415
416 /* ------------------------------------------------------------------------- */
417
418 /* usbProcessRx() is called for every message received by the interrupt
419  * routine. It distinguishes between SETUP and DATA packets and processes
420  * them accordingly.
421  */
422 static inline void usbProcessRx(uchar *data, uchar len)
423 {
424 usbRequest_t    *rq = (void *)data;
425
426 /* usbRxToken can be:
427  * 0x2d 00101101 (USBPID_SETUP for setup data)
428  * 0xe1 11100001 (USBPID_OUT: data phase of setup transfer)
429  * 0...0x0f for OUT on endpoint X
430  */
431     DBG2(0x10 + (usbRxToken & 0xf), data, len); /* SETUP=1d, SETUP-DATA=11, OUTx=1x */
432     USB_RX_USER_HOOK(data, len)
433 #if USB_CFG_IMPLEMENT_FN_WRITEOUT
434     if(usbRxToken < 0x10){  /* OUT to endpoint != 0: endpoint number in usbRxToken */
435         usbFunctionWriteOut(data, len);
436         return;
437     }
438 #endif
439     if(usbRxToken == (uchar)USBPID_SETUP){
440         if(len != 8)    /* Setup size must be always 8 bytes. Ignore otherwise. */
441             return;
442         usbMsgLen_t replyLen;
443         usbTxBuf[0] = USBPID_DATA0;         /* initialize data toggling */
444         usbTxLen = USBPID_NAK;              /* abort pending transmit */
445         usbMsgFlags = 0;
446         uchar type = rq->bmRequestType & USBRQ_TYPE_MASK;
447         if(type != USBRQ_TYPE_STANDARD){    /* standard requests are handled by driver */
448             replyLen = usbFunctionSetup(data);
449         }else{
450             replyLen = usbDriverSetup(rq);
451         }
452 #if USB_CFG_IMPLEMENT_FN_READ || USB_CFG_IMPLEMENT_FN_WRITE
453         if(replyLen == USB_NO_MSG){         /* use user-supplied read/write function */
454             /* do some conditioning on replyLen, but on IN transfers only */
455             if((rq->bmRequestType & USBRQ_DIR_MASK) != USBRQ_DIR_HOST_TO_DEVICE){
456                 if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */
457                     replyLen = rq->wLength.bytes[0];
458                 }else{
459                     replyLen = rq->wLength.word;
460                 }
461             }
462             usbMsgFlags = USB_FLG_USE_USER_RW;
463         }else   /* The 'else' prevents that we limit a replyLen of USB_NO_MSG to the maximum transfer len. */
464 #endif
465         if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */
466             if(!rq->wLength.bytes[1] && replyLen > rq->wLength.bytes[0])    /* limit length to max */
467                 replyLen = rq->wLength.bytes[0];
468         }else{
469             if(replyLen > rq->wLength.word)     /* limit length to max */
470                 replyLen = rq->wLength.word;
471         }
472         usbMsgLen = replyLen;
473     }else{  /* usbRxToken must be USBPID_OUT, which means data phase of setup (control-out) */
474 #if USB_CFG_IMPLEMENT_FN_WRITE
475         if(usbMsgFlags & USB_FLG_USE_USER_RW){
476             uchar rval = usbFunctionWrite(data, len);
477             if(rval == 0xff){   /* an error occurred */
478                 usbTxLen = USBPID_STALL;
479             }else if(rval != 0){    /* This was the final package */
480                 usbMsgLen = 0;  /* answer with a zero-sized data packet */
481             }
482         }
483 #endif
484     }
485 }
486
487 /* ------------------------------------------------------------------------- */
488
489 /* This function is similar to usbFunctionRead(), but it's also called for
490  * data handled automatically by the driver (e.g. descriptor reads).
491  */
492 static uchar usbDeviceRead(uchar *data, uchar len)
493 {
494     if(len > 0){    /* don't bother app with 0 sized reads */
495 #if USB_CFG_IMPLEMENT_FN_READ
496         if(usbMsgFlags & USB_FLG_USE_USER_RW){
497             len = usbFunctionRead(data, len);
498         }else
499 #endif
500         {
501             uchar i = len, *r = usbMsgPtr;
502             if(usbMsgFlags & USB_FLG_MSGPTR_IS_ROM){    /* ROM data */
503                 do{
504                     uchar c = USB_READ_FLASH(r);    /* assign to char size variable to enforce byte ops */
505                     *data++ = c;
506                     r++;
507                 }while(--i);
508             }else{  /* RAM data */
509                 do{
510                     *data++ = *r++;
511                 }while(--i);
512             }
513             usbMsgPtr = r;
514         }
515     }
516     return len;
517 }
518
519 /* ------------------------------------------------------------------------- */
520
521 /* usbBuildTxBlock() is called when we have data to transmit and the
522  * interrupt routine's transmit buffer is empty.
523  */
524 static inline void usbBuildTxBlock(void)
525 {
526 usbMsgLen_t wantLen;
527 uchar       len;
528
529     wantLen = usbMsgLen;
530     if(wantLen > 8)
531         wantLen = 8;
532     usbMsgLen -= wantLen;
533     usbTxBuf[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* DATA toggling */
534     len = usbDeviceRead(usbTxBuf + 1, wantLen);
535     if(len <= 8){           /* valid data packet */
536         usbCrc16Append(&usbTxBuf[1], len);
537         len += 4;           /* length including sync byte */
538         if(len < 12)        /* a partial package identifies end of message */
539             usbMsgLen = USB_NO_MSG;
540     }else{
541         len = USBPID_STALL;   /* stall the endpoint */
542         usbMsgLen = USB_NO_MSG;
543     }
544     usbTxLen = len;
545     DBG2(0x20, usbTxBuf, len-1);
546 }
547
548 /* ------------------------------------------------------------------------- */
549
550 static inline void usbHandleResetHook(uchar notResetState)
551 {
552 #ifdef USB_RESET_HOOK
553 static uchar    wasReset;
554 uchar           isReset = !notResetState;
555
556     if(wasReset != isReset){
557         USB_RESET_HOOK(isReset);
558         wasReset = isReset;
559     }
560 #endif
561 }
562
563 /* ------------------------------------------------------------------------- */
564
565 USB_PUBLIC void usbPoll(void)
566 {
567 schar   len;
568 uchar   i;
569
570     len = usbRxLen - 3;
571     if(len >= 0){
572 /* We could check CRC16 here -- but ACK has already been sent anyway. If you
573  * need data integrity checks with this driver, check the CRC in your app
574  * code and report errors back to the host. Since the ACK was already sent,
575  * retries must be handled on application level.
576  * unsigned crc = usbCrc16(buffer + 1, usbRxLen - 3);
577  */
578         usbProcessRx(usbRxBuf + USB_BUFSIZE + 1 - usbInputBufOffset, len);
579 #if USB_CFG_HAVE_FLOWCONTROL
580         if(usbRxLen > 0)    /* only mark as available if not inactivated */
581             usbRxLen = 0;
582 #else
583         usbRxLen = 0;       /* mark rx buffer as available */
584 #endif
585     }
586     if(usbTxLen & 0x10){    /* transmit system idle */
587         if(usbMsgLen != USB_NO_MSG){    /* transmit data pending? */
588             usbBuildTxBlock();
589         }
590     }
591     for(i = 20; i > 0; i--){
592         uchar usbLineStatus = USBIN & USBMASK;
593         if(usbLineStatus != 0)  /* SE0 has ended */
594             goto isNotReset;
595     }
596     /* RESET condition, called multiple times during reset */
597     usbNewDeviceAddr = 0;
598     usbDeviceAddr = 0;
599     usbResetStall();
600     DBG1(0xff, 0, 0);
601 isNotReset:
602     usbHandleResetHook(i);
603 }
604
605 /* ------------------------------------------------------------------------- */
606
607 USB_PUBLIC void usbInit(void)
608 {
609 #if USB_INTR_CFG_SET != 0
610     USB_INTR_CFG |= USB_INTR_CFG_SET;
611 #endif
612 #if USB_INTR_CFG_CLR != 0
613     USB_INTR_CFG &= ~(USB_INTR_CFG_CLR);
614 #endif
615     USB_INTR_ENABLE |= (1 << USB_INTR_ENABLE_BIT);
616     usbResetDataToggling();
617 #if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
618     usbTxLen1 = USBPID_NAK;
619 #if USB_CFG_HAVE_INTRIN_ENDPOINT3
620     usbTxLen3 = USBPID_NAK;
621 #endif
622 #endif
623 }
624
625 /* ------------------------------------------------------------------------- */
This page took 0.075865 seconds and 3 git commands to generate.