Move unpack lwip ip address macro to macros module.
[bertos.git] / bertos / drv / usb.h
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  * \author Andrea Righi <arighi@develer.com>
34  *
35  * \brief USB 2.0 standard descriptors
36  *
37  * This file holds USB constants and structures that are needed for USB device
38  * APIs, as defined in the USB 2.0 specification.
39  *
40  * \attention The API is work in progress and may change in future versions.
41  *
42  * $WIZ$ module_name = "usb"
43  * $WIZ$ module_configuration = "bertos/cfg/cfg_usb.h"
44  * $WIZ$ module_supports = "stm32"
45  */
46
47 #ifndef USB_H
48 #define USB_H
49
50 #include <cpu/byteorder.h>
51
52 #define usb_cpu_to_le16(x)      cpu_to_le16(x)
53 #define usb_le16_to_cpu(x)      le16_to_cpu(x)
54 #define usb_cpu_to_le32(x)      cpu_to_le32(x)
55 #define usb_le32_to_cpu(x)      le32_to_cpu(x)
56
57 /* State of a USB device */
58 enum usb_device_state {
59         USB_STATE_NOTATTACHED = 0,
60
61         /* chapter 9 device states */
62         USB_STATE_ATTACHED,
63         USB_STATE_POWERED,                      /* wired */
64         USB_STATE_DEFAULT,                      /* limited function */
65         USB_STATE_ADDRESS,
66         USB_STATE_CONFIGURED,                   /* most functions */
67 };
68
69 /*
70  * USB directions
71  *
72  * This bit flag is used in endpoint descriptors' bEndpointAddress field.
73  * It's also one of three fields in control requests bRequestType.
74  */
75 #define USB_DIR_OUT                     0               /* to device */
76 #define USB_DIR_IN                      0x80            /* to host */
77 #define USB_DIR_MASK                    0x80
78
79 /*
80  * USB types, the second of three bRequestType fields
81  */
82 #define USB_TYPE_MASK                   (0x03 << 5)
83 #define USB_TYPE_STANDARD               (0x00 << 5)
84 #define USB_TYPE_CLASS                  (0x01 << 5)
85 #define USB_TYPE_VENDOR                 (0x02 << 5)
86 #define USB_TYPE_RESERVED               (0x03 << 5)
87
88 /*
89  * USB recipients, the third of three bRequestType fields
90  */
91 #define USB_RECIP_MASK                  0x1f
92 #define USB_RECIP_DEVICE                0x00
93 #define USB_RECIP_INTERFACE             0x01
94 #define USB_RECIP_ENDPOINT              0x02
95 #define USB_RECIP_OTHER                 0x03
96
97 /*
98  * USB standard requests, for the bRequest field of a SETUP packet.
99  */
100 #define USB_REQ_GET_STATUS              0x00
101 #define USB_REQ_CLEAR_FEATURE           0x01
102 #define USB_REQ_SET_FEATURE             0x03
103 #define USB_REQ_SET_ADDRESS             0x05
104 #define USB_REQ_GET_DESCRIPTOR          0x06
105 #define USB_REQ_SET_DESCRIPTOR          0x07
106 #define USB_REQ_GET_CONFIGURATION       0x08
107 #define USB_REQ_SET_CONFIGURATION       0x09
108 #define USB_REQ_GET_INTERFACE           0x0A
109 #define USB_REQ_SET_INTERFACE           0x0B
110 #define USB_REQ_SYNCH_FRAME             0x0C
111
112 /*
113  * Descriptor types ... USB 2.0 spec table 9.5
114  */
115 #define USB_DT_DEVICE                   0x01
116 #define USB_DT_CONFIG                   0x02
117 #define USB_DT_STRING                   0x03
118 #define USB_DT_INTERFACE                0x04
119 #define USB_DT_ENDPOINT                 0x05
120 #define USB_DT_DEVICE_QUALIFIER         0x06
121 #define USB_DT_OTHER_SPEED_CONFIG       0x07
122 #define USB_DT_INTERFACE_POWER          0x08
123
124 /*
125  * Conventional codes for class-specific descriptors.  The convention is
126  * defined in the USB "Common Class" Spec (3.11).  Individual class specs
127  * are authoritative for their usage, not the "common class" writeup.
128  */
129 #define USB_DT_CS_DEVICE                (USB_TYPE_CLASS | USB_DT_DEVICE)
130 #define USB_DT_CS_CONFIG                (USB_TYPE_CLASS | USB_DT_CONFIG)
131 #define USB_DT_CS_STRING                (USB_TYPE_CLASS | USB_DT_STRING)
132 #define USB_DT_CS_INTERFACE             (USB_TYPE_CLASS | USB_DT_INTERFACE)
133 #define USB_DT_CS_ENDPOINT              (USB_TYPE_CLASS | USB_DT_ENDPOINT)
134
135 /**
136  *
137  * USB Control Request descriptor
138  *
139  * This structure is used to send control requests to a USB device.
140  *
141  * It matches the different fields of the USB 2.0 specification (section 9.3,
142  * table 9-2).
143  */
144 typedef struct UsbCtrlRequest
145 {
146         uint8_t mRequestType;
147         uint8_t bRequest;
148         uint16_t wValue;
149         uint16_t wIndex;
150         uint16_t wLength;
151 } PACKED UsbCtrlRequest;
152
153 /**
154  * USB common descriptor header.
155  *
156  * \note All the USB standard descriptors have these 2 fields at the beginning.
157  */
158 typedef struct UsbDescHeader
159 {
160         uint8_t bLength;
161         uint8_t bDescriptorType;
162 } PACKED UsbDescHeader;
163
164 /**
165  * USB Device descriptor
166  *
167  * \note See USB 2.0 specification.
168  */
169 typedef struct UsbDeviceDesc
170 {
171         uint8_t bLength;
172         uint8_t bDescriptorType;
173         uint16_t bcdUSB;
174         uint8_t bDeviceClass;
175         uint8_t bDeviceSubClass;
176         uint8_t bDeviceProtocol;
177         uint8_t bMaxPacketSize0;
178         uint16_t idVendor;
179         uint16_t idProduct;
180         uint16_t bcdDevice;
181         uint8_t iManufacturer;
182         uint8_t iProduct;
183         uint8_t iSerialNumber;
184         uint8_t bNumConfigurations;
185 } PACKED UsbDeviceDesc;
186
187 /**
188  * USB string descriptor.
189  *
190  * \note See USB 2.0 specification.
191  */
192 typedef struct UsbStringDesc
193 {
194         uint8_t bLength;
195         uint8_t bDescriptorType;
196         uint8_t data[0];
197 } PACKED UsbStringDesc;
198
199 #define USB_STRING_1(__a, ...) __a "\x00"
200 #define USB_STRING_2(__a, ...) __a "\x00" USB_STRING_1(__VA_ARGS__)
201 #define USB_STRING_3(__a, ...) __a "\x00" USB_STRING_2(__VA_ARGS__)
202 #define USB_STRING_4(__a, ...) __a "\x00" USB_STRING_3(__VA_ARGS__)
203 #define USB_STRING_5(__a, ...) __a "\x00" USB_STRING_4(__VA_ARGS__)
204 #define USB_STRING_6(__a, ...) __a "\x00" USB_STRING_5(__VA_ARGS__)
205 #define USB_STRING_7(__a, ...) __a "\x00" USB_STRING_6(__VA_ARGS__)
206 #define USB_STRING_8(__a, ...) __a "\x00" USB_STRING_7(__VA_ARGS__)
207 #define USB_STRING_9(__a, ...) __a "\x00" USB_STRING_8(__VA_ARGS__)
208 #define USB_STRING_10(__a, ...) __a "\x00" USB_STRING_9(__VA_ARGS__)
209 #define USB_STRING_11(__a, ...) __a "\x00" USB_STRING_10(__VA_ARGS__)
210 #define USB_STRING_12(__a, ...) __a "\x00" USB_STRING_11(__VA_ARGS__)
211 #define USB_STRING_13(__a, ...) __a "\x00" USB_STRING_12(__VA_ARGS__)
212 #define USB_STRING_14(__a, ...) __a "\x00" USB_STRING_13(__VA_ARGS__)
213 #define USB_STRING_15(__a, ...) __a "\x00" USB_STRING_14(__VA_ARGS__)
214 #define USB_STRING_16(__a, ...) __a "\x00" USB_STRING_15(__VA_ARGS__)
215
216 /**
217  * Pack a list with a variable number of elements into a UTF-16LE USB string.
218  *
219  * \note The macro is recursively defined according the number of elements
220  * passed as argument. At the moment we support strings with up to 16
221  * characters.
222  */
223 #define USB_STRING(...) PP_CAT(USB_STRING_, PP_COUNT(__VA_ARGS__))(__VA_ARGS__)
224
225 /**
226  * Define and initialize an USB string descriptor.
227  *
228  * This macro is reuquired to properly declare and initialize a constant USB
229  * string in UTF-16LE format.
230  *
231  * The structure must contain the standard common USB header (UsbDescHeader)
232  * and the UTF-16LE string all packed in a contiguous memory region.
233  */
234 #define DEFINE_USB_STRING(__name, __text)                               \
235         struct {                                                        \
236                 UsbDescHeader __header;                                 \
237                 uint8_t __body[sizeof(__text)];                         \
238         } PACKED __name = {                                             \
239                 .__header = {                                           \
240                         .bLength =                                      \
241                                 cpu_to_le16((uint16_t)sizeof(__name)),  \
242                         .bDescriptorType = USB_DT_STRING,               \
243                 },                                                      \
244                 .__body = {__text},                                     \
245         }
246
247 /*
248  * Device and/or Interface Class codes as found in bDeviceClass or
249  * bInterfaceClass and defined by www.usb.org documents.
250  */
251 #define USB_CLASS_PER_INTERFACE         0       /* for DeviceClass */
252 #define USB_CLASS_AUDIO                 1
253 #define USB_CLASS_COMM                  2
254 #define USB_CLASS_HID                   3
255 #define USB_CLASS_PHYSICAL              5
256 #define USB_CLASS_STILL_IMAGE           6
257 #define USB_CLASS_PRINTER               7
258 #define USB_CLASS_MASS_STORAGE          8
259 #define USB_CLASS_HUB                   9
260 #define USB_CLASS_CDC_DATA              0x0a
261 #define USB_CLASS_CSCID                 0x0b    /* chip+ smart card */
262 #define USB_CLASS_CONTENT_SEC           0x0d    /* content security */
263 #define USB_CLASS_VIDEO                 0x0e
264 #define USB_CLASS_WIRELESS_CONTROLLER   0xe0
265 #define USB_CLASS_MISC                  0xef
266 #define USB_CLASS_APP_SPEC              0xfe
267 #define USB_CLASS_VENDOR_SPEC           0xff
268
269 /* USB Device subclasses */
270 #define USB_CDC_SUBCLASS_ACM                    0x02
271 #define USB_CDC_SUBCLASS_ETHERNET               0x06
272 #define USB_CDC_SUBCLASS_WHCM                   0x08
273 #define USB_CDC_SUBCLASS_DMM                    0x09
274 #define USB_CDC_SUBCLASS_MDLM                   0x0a
275 #define USB_CDC_SUBCLASS_OBEX                   0x0b
276 #define USB_CDC_SUBCLASS_EEM                    0x0c
277 #define USB_CDC_SUBCLASS_NCM                    0x0d
278
279 /**
280  * Device configuration descriptor
281  *
282  * \note See USB 2.0 specification.
283  */
284 typedef struct UsbConfigDesc
285 {
286         uint8_t bLength;
287         uint8_t bDescriptorType;
288         uint16_t wTotalLength;
289         uint8_t bNumInterfaces;
290         uint8_t bConfigurationValue;
291         uint8_t iConfiguration;
292         uint8_t bmAttributes;
293         uint8_t bMaxPower;
294 } PACKED UsbConfigDesc;
295
296 /* from config descriptor bmAttributes */
297 #define USB_CONFIG_ATT_ONE              (1 << 7)        /* must be set */
298 #define USB_CONFIG_ATT_SELFPOWER        (1 << 6)        /* self powered */
299 #define USB_CONFIG_ATT_WAKEUP           (1 << 5)        /* can wakeup */
300 #define USB_CONFIG_ATT_BATTERY          (1 << 4)        /* battery powered */
301
302 /**
303  * Device interface descriptor
304  *
305  * \note See USB 2.0 specification.
306  */
307 typedef struct UsbInterfaceDesc
308 {
309         uint8_t bLength;
310         uint8_t bDescriptorType;
311         uint8_t bInterfaceNumber;
312         uint8_t bAlternateSetting;
313         uint8_t bNumEndpoints;
314         uint8_t bInterfaceClass;
315         uint8_t bInterfaceSubClass;
316         uint8_t bInterfaceProtocol;
317         uint8_t iInterface;
318 } PACKED UsbInterfaceDesc;
319
320 /**
321  * Endpoint descriptor
322  *
323  * \note See USB 2.0 specification.
324  */
325 typedef struct UsbEndpointDesc
326 {
327         uint8_t bLength;
328         uint8_t bDescriptorType;
329         uint8_t bEndpointAddress;
330         uint8_t bmAttributes;
331         uint16_t wMaxPacketSize;
332         uint8_t bInterval;
333 } PACKED UsbEndpointDesc;
334
335 /*
336  * Endpoints
337  */
338 #define USB_ENDPOINT_NUMBER_MASK        0x0f    /* in bEndpointAddress */
339 #define USB_ENDPOINT_DIR_MASK           USB_DIR_MASK
340
341 #define USB_ENDPOINT_SYNCTYPE           0x0c
342 #define USB_ENDPOINT_SYNC_NONE          (0 << 2)
343 #define USB_ENDPOINT_SYNC_ASYNC         (1 << 2)
344 #define USB_ENDPOINT_SYNC_ADAPTIVE      (2 << 2)
345 #define USB_ENDPOINT_SYNC_SYNC          (3 << 2)
346
347 #define USB_ENDPOINT_XFERTYPE_MASK      0x03    /* in bmAttributes */
348 #define USB_ENDPOINT_XFER_CONTROL       0
349 #define USB_ENDPOINT_XFER_ISOC          1
350 #define USB_ENDPOINT_XFER_BULK          2
351 #define USB_ENDPOINT_XFER_INT           3
352 #define USB_ENDPOINT_MAX_ADJUSTABLE     0x80
353
354 /**
355  * USB: generic device descriptor
356  */
357 typedef struct UsbDevice
358 {
359         UsbDeviceDesc *device;              ///< USB 2.0 device descriptor
360         const UsbDescHeader **config;       ///< USB 2.0 configuration descriptors
361         const UsbStringDesc **strings;      ///< USB strings
362
363         /* Callbacks */
364         void (*event_cb)(UsbCtrlRequest *); ///< Called to handle control requests.
365
366         /* Private data */
367         bool configured;                    ///< True when the device has been correctly initialized.
368 } UsbDevice;
369
370 /**
371  * Get the endpoint's address number of \a epd.
372  */
373 INLINE int usb_endpointNum(const UsbEndpointDesc *epd)
374 {
375         return epd->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
376 }
377
378 /**
379  * Get the transfer type of the endpoint \a epd.
380  */
381 INLINE int usb_endpointType(const struct UsbEndpointDesc *epd)
382 {
383         return epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
384 }
385
386 /**
387  * Check if the endpoint \a epd has IN direction.
388  */
389 INLINE int usb_endpointDirIn(const struct UsbEndpointDesc *epd)
390 {
391         return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN);
392 }
393
394 /**
395  * Check if the endpoint \a epd has OUT direction.
396  */
397 INLINE int usb_endpointDirOut(const struct UsbEndpointDesc *epd)
398 {
399         return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT);
400 }
401
402 /**
403  * Check if the endpoint \a epd has bulk transfer type.
404  */
405 INLINE int usb_endpointXferBulk(const struct UsbEndpointDesc *epd)
406 {
407         return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
408                 USB_ENDPOINT_XFER_BULK);
409 }
410
411 /**
412  * Check if the endpoint \a epd has control transfer type.
413  */
414 INLINE int usb_endpointXferControl(const struct UsbEndpointDesc *epd)
415 {
416         return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
417                 USB_ENDPOINT_XFER_CONTROL);
418 }
419
420 /**
421  * Check if the endpoint \a epd has interrupt transfer type.
422  */
423 INLINE int usb_endpointXferInt(const struct UsbEndpointDesc *epd)
424 {
425         return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
426                 USB_ENDPOINT_XFER_INT);
427 }
428
429 /**
430  * Check if the endpoint \a epd has isochronous transfer type.
431  */
432 INLINE int usb_endpointXferIsoc(const struct UsbEndpointDesc *epd)
433 {
434         return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
435                 USB_ENDPOINT_XFER_ISOC);
436 }
437
438 /**
439  * Check if the endpoint \a epd is bulk IN.
440  */
441 INLINE int usb_endpointIsBulkIn(const struct UsbEndpointDesc *epd)
442 {
443         return usb_endpointXferBulk(epd) && usb_endpointDirIn(epd);
444 }
445
446 /**
447  * Check if the endpoint \a epd is bulk OUT.
448  */
449 INLINE int usb_endpointIsBulkOut(const struct UsbEndpointDesc *epd)
450 {
451         return usb_endpointXferBulk(epd) && usb_endpointDirOut(epd);
452 }
453
454 /**
455  * Check if the endpoint \a epd is interrupt IN.
456  */
457 INLINE int usb_endpointIsIntIn(const struct UsbEndpointDesc *epd)
458 {
459         return usb_endpointXferInt(epd) && usb_endpointDirIn(epd);
460 }
461
462 /**
463  * Check if the endpoint \a epd is interrupt OUT.
464  */
465 INLINE int usb_endpointIsIntOut(const struct UsbEndpointDesc *epd)
466 {
467         return usb_endpointXferInt(epd) && usb_endpointDirOut(epd);
468 }
469
470 /**
471  * Check if the endpoint \a epd is isochronous IN.
472  */
473 INLINE int usb_endpointIsIsocIn(const struct UsbEndpointDesc *epd)
474 {
475         return usb_endpointXferIsoc(epd) && usb_endpointDirIn(epd);
476 }
477
478 /**
479  * Check if the endpoint \a epd is isochronous OUT.
480  */
481 INLINE int usb_endpointIsIsocOut(const struct UsbEndpointDesc *epd)
482 {
483         return usb_endpointXferIsoc(epd) && usb_endpointDirOut(epd);
484 }
485
486 /**
487  * Read up to \a size bytes from the USB endpoint identified by the address
488  * \a ep and store them in \a buffer.
489  *
490  * The \a timeout is an upper bound on the amount of time (in ticks) elapsed
491  * before returns. If \a timeout is zero, the the function returns immediatly
492  * and it basically works in non-blocking fashion. A negative value for \a
493  * timeout means that the function can block indefinitely.
494  *
495  * \return number of bytes actually read, or a negative value in case of
496  * errors.
497  */
498 ssize_t usb_endpointReadTimeout(int ep, void *buffer, ssize_t size,
499                                 ticks_t timeout);
500
501 INLINE ssize_t usb_endpointRead(int ep, void *buffer, ssize_t size)
502 {
503         return usb_endpointReadTimeout(ep, buffer, size, -1);
504 }
505
506 /**
507  * Write up to \a size bytes from the buffer pointed \a buffer to the USB
508  * endpoint identified by the address \a ep.
509  *
510  * The \a timeout is an upper bound on the amount of time (in ticks) elapsed
511  * before returns. If \a timeout is zero, the the function returns immediatly
512  * and it basically works in non-blocking fashion. A negative value for \a
513  * timeout means that the function can block indefinitely.
514  *
515  * \return number of bytes actually wrote, or a negative value in case of
516  * errors.
517  */
518 ssize_t usb_endpointWriteTimeout(int ep, const void *buffer, ssize_t size,
519                                 ticks_t timeout);
520
521 INLINE ssize_t usb_endpointWrite(int ep, const void *buffer, ssize_t size)
522 {
523         return usb_endpointWriteTimeout(ep, buffer, size, -1);
524 }
525
526 /**
527  * Register a generic USB device driver \a dev in the USB controller.
528  */
529 int usb_deviceRegister(UsbDevice *dev);
530
531 #endif /* USB_H */