1 /*
2 * LPCUSB, an USB device driver for LPC microcontrollers
3 * Copyright (C) 2006 Bertrik Sikken (bertrik@sikken.nl)
4 * Copyright (c) 2016 Intel Corporation
5 * Copyright (c) 2020 PHYTEC Messtechnik GmbH
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30 /**
31 * @file
32 * @brief USB device core layer
33 *
34 * This module handles control transfer handler, standard request handler and
35 * USB Interface for customer application.
36 *
37 * Control transfers handler is normally installed on the
38 * endpoint 0 callback.
39 *
40 * Control transfers can be of the following type:
41 * 0 Standard;
42 * 1 Class;
43 * 2 Vendor;
44 * 3 Reserved.
45 *
46 * A callback can be installed for each of these control transfers using
47 * usb_register_request_handler.
48 * When an OUT request arrives, data is collected in the data store provided
49 * with the usb_register_request_handler call. When the transfer is done, the
50 * callback is called.
51 * When an IN request arrives, the callback is called immediately to either
52 * put the control transfer data in the data store, or to get a pointer to
53 * control transfer data. The data is then packetized and sent to the host.
54 *
55 * Standard request handler handles the 'chapter 9' processing, specifically
56 * the standard device requests in table 9-3 from the universal serial bus
57 * specification revision 2.0
58 */
59
60 #include <errno.h>
61 #include <stddef.h>
62 #include <zephyr/sys/util.h>
63 #include <zephyr/sys/__assert.h>
64 #include <zephyr/init.h>
65 #include <zephyr/drivers/gpio.h>
66 #include <zephyr/sys/byteorder.h>
67 #include <zephyr/usb/usb_device.h>
68 #include <usb_descriptor.h>
69 #include <zephyr/usb/class/usb_audio.h>
70 #include <zephyr/sys/iterable_sections.h>
71 #include <zephyr/logging/log.h>
72 LOG_MODULE_REGISTER(usb_device, CONFIG_USB_DEVICE_LOG_LEVEL);
73
74 #include <zephyr/usb/bos.h>
75 #include <os_desc.h>
76 #include "usb_transfer.h"
77
78 #define MAX_DESC_HANDLERS 4 /** Device, interface, endpoint, other */
79
80 /* general descriptor field offsets */
81 #define DESC_bLength 0 /** Length offset */
82 #define DESC_bDescriptorType 1 /** Descriptor type offset */
83
84 /* config descriptor field offsets */
85 #define CONF_DESC_wTotalLength 2 /** Total length offset */
86 #define CONF_DESC_bConfigurationValue 5 /** Configuration value offset */
87 #define CONF_DESC_bmAttributes 7 /** configuration characteristics */
88
89 /* interface descriptor field offsets */
90 #define INTF_DESC_bInterfaceNumber 2 /** Interface number offset */
91 #define INTF_DESC_bAlternateSetting 3 /** Alternate setting offset */
92
93 /* endpoint descriptor field offsets */
94 #define ENDP_DESC_bEndpointAddress 2U /** Endpoint address offset */
95 #define ENDP_DESC_bmAttributes 3U /** Bulk or interrupt? */
96 #define ENDP_DESC_wMaxPacketSize 4U /** Maximum packet size offset */
97
98 #define MAX_NUM_REQ_HANDLERS 4U
99 #define MAX_STD_REQ_MSG_SIZE 8U
100
101 K_MUTEX_DEFINE(usb_enable_lock);
102
103 static struct usb_dev_priv {
104 /** Setup packet */
105 struct usb_setup_packet setup;
106 /** Pointer to data buffer */
107 uint8_t *data_buf;
108 /** Remaining bytes in buffer */
109 int32_t data_buf_residue;
110 /** Total length of control transfer */
111 int32_t data_buf_len;
112 /** Zero length packet flag of control transfer */
113 bool zlp_flag;
114 /** Installed custom request handler */
115 usb_request_handler custom_req_handler;
116 /** USB stack status callback */
117 usb_dc_status_callback status_callback;
118 /** USB user status callback */
119 usb_dc_status_callback user_status_callback;
120 /** Pointer to registered descriptors */
121 const uint8_t *descriptors;
122 /** Array of installed request handler callbacks */
123 usb_request_handler req_handlers[MAX_NUM_REQ_HANDLERS];
124 /* Buffer used for storing standard, class and vendor request data */
125 uint8_t req_data[CONFIG_USB_REQUEST_BUFFER_SIZE];
126
127 /** Variable to check whether the usb has been enabled */
128 bool enabled;
129 /** Variable to check whether the usb has been configured */
130 bool configured;
131 /** Currently selected configuration */
132 uint8_t configuration;
133 /** Currently selected alternate setting */
134 uint8_t alt_setting[CONFIG_USB_MAX_ALT_SETTING];
135 /** Remote wakeup feature status */
136 bool remote_wakeup;
137 /** Tracks whether set_endpoint() had been called on an EP */
138 uint32_t ep_bm;
139 /** Maximum Packet Size (MPS) of control endpoint */
140 uint8_t mps0;
141 } usb_dev;
142
143 /* Setup packet definition used to read raw data from USB line */
144 struct usb_setup_packet_packed {
145 uint8_t bmRequestType;
146 uint8_t bRequest;
147 uint16_t wValue;
148 uint16_t wIndex;
149 uint16_t wLength;
150 } __packed;
151
152 static bool reset_endpoint(const struct usb_ep_descriptor *ep_desc);
153
154 /*
155 * @brief print the contents of a setup packet
156 *
157 * @param [in] setup The setup packet
158 *
159 */
usb_print_setup(struct usb_setup_packet * setup)160 static void usb_print_setup(struct usb_setup_packet *setup)
161 {
162 /* avoid compiler warning if LOG_DBG is not defined */
163 ARG_UNUSED(setup);
164
165 LOG_DBG("Setup: "
166 "bmRT 0x%02x, bR 0x%02x, wV 0x%04x, wI 0x%04x, wL 0x%04x",
167 setup->bmRequestType,
168 setup->bRequest,
169 setup->wValue,
170 setup->wIndex,
171 setup->wLength);
172 }
173
usb_reset_alt_setting(void)174 static void usb_reset_alt_setting(void)
175 {
176 memset(usb_dev.alt_setting, 0, ARRAY_SIZE(usb_dev.alt_setting));
177 }
178
usb_set_alt_setting(uint8_t iface,uint8_t alt_setting)179 static bool usb_set_alt_setting(uint8_t iface, uint8_t alt_setting)
180 {
181 if (iface < ARRAY_SIZE(usb_dev.alt_setting)) {
182 usb_dev.alt_setting[iface] = alt_setting;
183 return true;
184 }
185
186 return false;
187 }
188
usb_get_alt_setting(uint8_t iface)189 static uint8_t usb_get_alt_setting(uint8_t iface)
190 {
191 if (iface < ARRAY_SIZE(usb_dev.alt_setting)) {
192 return usb_dev.alt_setting[iface];
193 }
194
195 return 0;
196 }
197
198 /*
199 * @brief handle a request by calling one of the installed request handlers
200 *
201 * Local function to handle a request by calling one of the installed request
202 * handlers. In case of data going from host to device, the data is at *ppbData.
203 * In case of data going from device to host, the handler can either choose to
204 * write its data at *ppbData or update the data pointer.
205 *
206 * @param [in] setup The setup packet
207 * @param [in,out] len Pointer to data length
208 * @param [in,out] data Data buffer
209 *
210 * @return true if the request was handles successfully
211 */
usb_handle_request(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data)212 static bool usb_handle_request(struct usb_setup_packet *setup,
213 int32_t *len, uint8_t **data)
214 {
215 uint32_t type = setup->RequestType.type;
216 usb_request_handler handler;
217
218 if (type >= MAX_NUM_REQ_HANDLERS) {
219 LOG_DBG("Error Incorrect iType %d", type);
220 return false;
221 }
222
223 handler = usb_dev.req_handlers[type];
224 if (handler == NULL) {
225 LOG_DBG("No handler for reqtype %d", type);
226 return false;
227 }
228
229 if ((*handler)(setup, len, data) < 0) {
230 LOG_DBG("Handler Error %d", type);
231 usb_print_setup(setup);
232 return false;
233 }
234
235 return true;
236 }
237
238 /*
239 * @brief send next chunk of data (possibly 0 bytes) to host
240 */
usb_data_to_host(void)241 static void usb_data_to_host(void)
242 {
243 if (usb_dev.zlp_flag == false) {
244 uint32_t chunk = usb_dev.data_buf_residue;
245
246 /*Always EP0 for control*/
247 usb_write(USB_CONTROL_EP_IN, usb_dev.data_buf,
248 usb_dev.data_buf_residue, &chunk);
249 usb_dev.data_buf += chunk;
250 usb_dev.data_buf_residue -= chunk;
251
252 /*
253 * Set ZLP flag when host asks for a bigger length and the
254 * last chunk is wMaxPacketSize long, to indicate the last
255 * packet.
256 */
257 if (!usb_dev.data_buf_residue && chunk &&
258 usb_dev.setup.wLength > usb_dev.data_buf_len) {
259 /* Send less data as requested during the Setup stage */
260 if (!(usb_dev.data_buf_len % usb_dev.mps0)) {
261 /* Transfers a zero-length packet */
262 LOG_DBG("ZLP, requested %u , length %u ",
263 usb_dev.setup.wLength,
264 usb_dev.data_buf_len);
265 usb_dev.zlp_flag = true;
266 }
267 }
268
269 } else {
270 usb_dev.zlp_flag = false;
271 usb_dc_ep_write(USB_CONTROL_EP_IN, NULL, 0, NULL);
272 }
273 }
274
275 /*
276 * @brief handle IN/OUT transfers on EP0
277 *
278 * @param [in] ep Endpoint address
279 * @param [in] ep_status Endpoint status
280 */
usb_handle_control_transfer(uint8_t ep,enum usb_dc_ep_cb_status_code ep_status)281 static void usb_handle_control_transfer(uint8_t ep,
282 enum usb_dc_ep_cb_status_code ep_status)
283 {
284 uint32_t chunk = 0U;
285 struct usb_setup_packet *setup = &usb_dev.setup;
286 struct usb_setup_packet_packed setup_raw;
287
288 LOG_DBG("ep 0x%02x, status 0x%02x", ep, ep_status);
289
290 if (ep == USB_CONTROL_EP_OUT && ep_status == USB_DC_EP_SETUP) {
291 /*
292 * OUT transfer, Setup packet,
293 * reset request message state machine
294 */
295 if (usb_dc_ep_read(ep, (uint8_t *)&setup_raw,
296 sizeof(setup_raw), NULL) < 0) {
297 LOG_DBG("Read Setup Packet failed");
298 usb_dc_ep_set_stall(USB_CONTROL_EP_IN);
299 return;
300 }
301
302 /* Take care of endianness */
303 setup->bmRequestType = setup_raw.bmRequestType;
304 setup->bRequest = setup_raw.bRequest;
305 setup->wValue = sys_le16_to_cpu(setup_raw.wValue);
306 setup->wIndex = sys_le16_to_cpu(setup_raw.wIndex);
307 setup->wLength = sys_le16_to_cpu(setup_raw.wLength);
308
309 usb_dev.data_buf = usb_dev.req_data;
310 usb_dev.zlp_flag = false;
311 /*
312 * Set length to 0 as a precaution so that no trouble
313 * happens if control request handler does not check the
314 * request values sufficiently.
315 */
316 usb_dev.data_buf_len = 0;
317 usb_dev.data_buf_residue = 0;
318
319 if (usb_reqtype_is_to_device(setup)) {
320 if (setup->wLength > CONFIG_USB_REQUEST_BUFFER_SIZE) {
321 LOG_ERR("Request buffer too small");
322 usb_dc_ep_set_stall(USB_CONTROL_EP_IN);
323 usb_dc_ep_set_stall(USB_CONTROL_EP_OUT);
324 return;
325 }
326
327 if (setup->wLength) {
328 /* Continue with data OUT stage */
329 usb_dev.data_buf_len = setup->wLength;
330 usb_dev.data_buf_residue = setup->wLength;
331 return;
332 }
333 }
334
335 /* Ask installed handler to process request */
336 if (!usb_handle_request(setup,
337 &usb_dev.data_buf_len,
338 &usb_dev.data_buf)) {
339 LOG_DBG("usb_handle_request failed");
340 usb_dc_ep_set_stall(USB_CONTROL_EP_IN);
341 return;
342 }
343
344 /* Send smallest of requested and offered length */
345 usb_dev.data_buf_residue = MIN(usb_dev.data_buf_len,
346 setup->wLength);
347 /* Send first part (possibly a zero-length status message) */
348 usb_data_to_host();
349 } else if (ep == USB_CONTROL_EP_OUT) {
350 /* OUT transfer, data or status packets */
351 if (usb_dev.data_buf_residue <= 0) {
352 /* absorb zero-length status message */
353 if (usb_dc_ep_read(USB_CONTROL_EP_OUT,
354 usb_dev.data_buf, 0, &chunk) < 0) {
355 LOG_DBG("Read DATA Packet failed");
356 usb_dc_ep_set_stall(USB_CONTROL_EP_IN);
357 }
358 return;
359 }
360
361 if (usb_dc_ep_read(USB_CONTROL_EP_OUT,
362 usb_dev.data_buf,
363 usb_dev.data_buf_residue, &chunk) < 0) {
364 LOG_DBG("Read DATA Packet failed");
365 usb_dc_ep_set_stall(USB_CONTROL_EP_IN);
366 usb_dc_ep_set_stall(USB_CONTROL_EP_OUT);
367 return;
368 }
369
370 usb_dev.data_buf += chunk;
371 usb_dev.data_buf_residue -= chunk;
372 if (usb_dev.data_buf_residue == 0) {
373 /* Received all, send data to handler */
374 usb_dev.data_buf = usb_dev.req_data;
375 if (!usb_handle_request(setup,
376 &usb_dev.data_buf_len,
377 &usb_dev.data_buf)) {
378 LOG_DBG("usb_handle_request1 failed");
379 usb_dc_ep_set_stall(USB_CONTROL_EP_IN);
380 return;
381 }
382
383 /*Send status to host*/
384 LOG_DBG(">> usb_data_to_host(2)");
385 usb_data_to_host();
386 }
387 } else if (ep == USB_CONTROL_EP_IN) {
388 /* Send more data if available */
389 if (usb_dev.data_buf_residue != 0 || usb_dev.zlp_flag == true) {
390 usb_data_to_host();
391 }
392 } else {
393 __ASSERT_NO_MSG(false);
394 }
395 }
396
397 /*
398 * @brief register a callback for handling requests
399 *
400 * @param [in] type Type of request, e.g. USB_REQTYPE_TYPE_STANDARD
401 * @param [in] handler Callback function pointer
402 */
usb_register_request_handler(int32_t type,usb_request_handler handler)403 static void usb_register_request_handler(int32_t type,
404 usb_request_handler handler)
405 {
406 usb_dev.req_handlers[type] = handler;
407 }
408
409 /*
410 * @brief register a pointer to a descriptor block
411 *
412 * This function registers a pointer to a descriptor block containing all
413 * descriptors for the device.
414 *
415 * @param [in] usb_descriptors The descriptor byte array
416 */
usb_register_descriptors(const uint8_t * usb_descriptors)417 static void usb_register_descriptors(const uint8_t *usb_descriptors)
418 {
419 usb_dev.descriptors = usb_descriptors;
420 }
421
usb_get_status(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data_buf)422 static bool usb_get_status(struct usb_setup_packet *setup,
423 int32_t *len, uint8_t **data_buf)
424 {
425 uint8_t *data = *data_buf;
426
427 LOG_DBG("Get Status request");
428 data[0] = 0U;
429 data[1] = 0U;
430
431 if (IS_ENABLED(CONFIG_USB_SELF_POWERED)) {
432 data[0] |= USB_GET_STATUS_SELF_POWERED;
433 }
434
435 if (IS_ENABLED(CONFIG_USB_DEVICE_REMOTE_WAKEUP)) {
436 data[0] |= (usb_dev.remote_wakeup ?
437 USB_GET_STATUS_REMOTE_WAKEUP : 0);
438 }
439
440 *len = 2;
441
442 return true;
443 }
444
445 /*
446 * @brief get specified USB descriptor
447 *
448 * This function parses the list of installed USB descriptors and attempts
449 * to find the specified USB descriptor.
450 *
451 * @param [in] setup The setup packet
452 * @param [out] len Descriptor length
453 * @param [out] data Descriptor data
454 *
455 * @return true if the descriptor was found, false otherwise
456 */
usb_get_descriptor(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data)457 static bool usb_get_descriptor(struct usb_setup_packet *setup,
458 int32_t *len, uint8_t **data)
459 {
460 uint8_t type = 0U;
461 uint8_t index = 0U;
462 uint8_t *p = NULL;
463 uint32_t cur_index = 0U;
464 bool found = false;
465
466 LOG_DBG("Get Descriptor request");
467 type = USB_GET_DESCRIPTOR_TYPE(setup->wValue);
468 index = USB_GET_DESCRIPTOR_INDEX(setup->wValue);
469
470 /*
471 * Invalid types of descriptors,
472 * see USB Spec. Revision 2.0, 9.4.3 Get Descriptor
473 */
474 if ((type == USB_DESC_INTERFACE) || (type == USB_DESC_ENDPOINT) ||
475 (type > USB_DESC_OTHER_SPEED)) {
476 return false;
477 }
478
479 p = (uint8_t *)usb_dev.descriptors;
480 cur_index = 0U;
481
482 while (p[DESC_bLength] != 0U) {
483 if (p[DESC_bDescriptorType] == type) {
484 if (cur_index == index) {
485 found = true;
486 break;
487 }
488 cur_index++;
489 }
490 /* skip to next descriptor */
491 p += p[DESC_bLength];
492 }
493
494 if (found) {
495 /* set data pointer */
496 *data = p;
497 /* get length from structure */
498 if (type == USB_DESC_CONFIGURATION) {
499 /* configuration descriptor is an
500 * exception, length is at offset
501 * 2 and 3
502 */
503 *len = (p[CONF_DESC_wTotalLength]) |
504 (p[CONF_DESC_wTotalLength + 1] << 8);
505 } else {
506 /* normally length is at offset 0 */
507 *len = p[DESC_bLength];
508 }
509 } else {
510 /* nothing found */
511 LOG_DBG("Desc %x not found!", setup->wValue);
512 }
513 return found;
514 }
515
516 /*
517 * @brief Get 32-bit endpoint bitmask from index
518 *
519 * In the returned 32-bit word, the bit positions in the lower 16 bits
520 * indicate OUT endpoints, while the upper 16 bits indicate IN
521 * endpoints
522 *
523 * @param [in] ep Endpoint of interest
524 *
525 * @return 32-bit bitmask
526 */
get_ep_bm_from_addr(uint8_t ep)527 static uint32_t get_ep_bm_from_addr(uint8_t ep)
528 {
529 uint32_t ep_bm = 0;
530 uint8_t ep_idx;
531
532 ep_idx = ep & (~USB_EP_DIR_IN);
533 if (ep_idx > 15) {
534 LOG_ERR("Endpoint 0x%02x is invalid", ep);
535 goto done;
536 }
537
538 if (ep & USB_EP_DIR_IN) {
539 ep_bm = BIT(ep_idx + 16);
540 } else {
541 ep_bm = BIT(ep_idx);
542 }
543 done:
544 return ep_bm;
545 }
546
547 /*
548 * @brief configure and enable endpoint
549 *
550 * This function sets endpoint configuration according to one specified in USB
551 * endpoint descriptor and then enables it for data transfers.
552 *
553 * @param [in] ep_desc Endpoint descriptor byte array
554 *
555 * @return true if successfully configured and enabled
556 */
set_endpoint(const struct usb_ep_descriptor * ep_desc)557 static bool set_endpoint(const struct usb_ep_descriptor *ep_desc)
558 {
559 struct usb_dc_ep_cfg_data ep_cfg;
560 uint32_t ep_bm;
561 int ret;
562
563 ep_cfg.ep_addr = ep_desc->bEndpointAddress;
564 ep_cfg.ep_mps = sys_le16_to_cpu(ep_desc->wMaxPacketSize);
565 ep_cfg.ep_type = ep_desc->bmAttributes & USB_EP_TRANSFER_TYPE_MASK;
566
567 LOG_DBG("Set endpoint 0x%x type %u MPS %u",
568 ep_cfg.ep_addr, ep_cfg.ep_type, ep_cfg.ep_mps);
569
570 /* if endpoint is has been set() previously, reset() it first */
571 ep_bm = get_ep_bm_from_addr(ep_desc->bEndpointAddress);
572 if (ep_bm & usb_dev.ep_bm) {
573 reset_endpoint(ep_desc);
574 /* allow any canceled transfers to terminate */
575 if (!k_is_in_isr()) {
576 k_usleep(150);
577 }
578 }
579
580 ret = usb_dc_ep_configure(&ep_cfg);
581 if (ret == -EALREADY) {
582 LOG_WRN("Endpoint 0x%02x already configured", ep_cfg.ep_addr);
583 } else if (ret) {
584 LOG_ERR("Failed to configure endpoint 0x%02x", ep_cfg.ep_addr);
585 return false;
586 } else {
587 ;
588 }
589
590 ret = usb_dc_ep_enable(ep_cfg.ep_addr);
591 if (ret == -EALREADY) {
592 LOG_WRN("Endpoint 0x%02x already enabled", ep_cfg.ep_addr);
593 } else if (ret) {
594 LOG_ERR("Failed to enable endpoint 0x%02x", ep_cfg.ep_addr);
595 return false;
596 } else {
597 ;
598 }
599
600 usb_dev.configured = true;
601 usb_dev.ep_bm |= ep_bm;
602
603 return true;
604 }
605
disable_endpoint(uint8_t ep_addr)606 static int disable_endpoint(uint8_t ep_addr)
607 {
608 uint32_t ep_bm;
609 int ret;
610
611 ret = usb_dc_ep_disable(ep_addr);
612 if (ret == -EALREADY) {
613 LOG_WRN("Endpoint 0x%02x already disabled", ep_addr);
614 } else if (ret) {
615 LOG_ERR("Failed to disable endpoint 0x%02x", ep_addr);
616 return ret;
617 }
618
619 /* clear endpoint mask */
620 ep_bm = get_ep_bm_from_addr(ep_addr);
621 usb_dev.ep_bm &= ~ep_bm;
622
623 return 0;
624 }
625
626 /*
627 * @brief Disable endpoint for transferring data
628 *
629 * This function cancels transfers that are associated with endpoint and
630 * disabled endpoint itself.
631 *
632 * @param [in] ep_desc Endpoint descriptor byte array
633 *
634 * @return true if successfully deconfigured and disabled
635 */
reset_endpoint(const struct usb_ep_descriptor * ep_desc)636 static bool reset_endpoint(const struct usb_ep_descriptor *ep_desc)
637 {
638 struct usb_dc_ep_cfg_data ep_cfg;
639
640 ep_cfg.ep_addr = ep_desc->bEndpointAddress;
641 ep_cfg.ep_type = ep_desc->bmAttributes & USB_EP_TRANSFER_TYPE_MASK;
642
643 LOG_DBG("Reset endpoint 0x%02x type %u",
644 ep_cfg.ep_addr, ep_cfg.ep_type);
645
646 usb_cancel_transfer(ep_cfg.ep_addr);
647
648 return disable_endpoint(ep_cfg.ep_addr) ? false : true;
649 }
650
usb_eps_reconfigure(struct usb_ep_descriptor * ep_desc,uint8_t cur_alt_setting,uint8_t alt_setting)651 static bool usb_eps_reconfigure(struct usb_ep_descriptor *ep_desc,
652 uint8_t cur_alt_setting,
653 uint8_t alt_setting)
654 {
655 bool ret;
656
657 if (cur_alt_setting != alt_setting) {
658 LOG_DBG("Disable endpoint 0x%02x", ep_desc->bEndpointAddress);
659 ret = reset_endpoint(ep_desc);
660 } else {
661 LOG_DBG("Enable endpoint 0x%02x", ep_desc->bEndpointAddress);
662 ret = set_endpoint(ep_desc);
663 }
664
665 return ret;
666 }
667
668 /*
669 * @brief set USB configuration
670 *
671 * This function configures the device according to the specified configuration
672 * index and alternate setting by parsing the installed USB descriptor list.
673 * A configuration index of 0 unconfigures the device.
674 *
675 * @param [in] setup The setup packet
676 *
677 * @return true if successfully configured false if error or unconfigured
678 */
usb_set_configuration(struct usb_setup_packet * setup)679 static bool usb_set_configuration(struct usb_setup_packet *setup)
680 {
681 uint8_t *p = (uint8_t *)usb_dev.descriptors;
682 uint8_t cur_alt_setting = 0xFF;
683 uint8_t cur_config = 0xFF;
684 bool found = false;
685
686 LOG_DBG("Set Configuration %u request", setup->wValue);
687
688 if (setup->wValue == 0U) {
689 usb_reset_alt_setting();
690 usb_dev.configuration = setup->wValue;
691 if (usb_dev.status_callback) {
692 usb_dev.status_callback(USB_DC_CONFIGURED,
693 &usb_dev.configuration);
694 }
695
696 return true;
697 }
698
699 /* configure endpoints for this configuration/altsetting */
700 while (p[DESC_bLength] != 0U) {
701 switch (p[DESC_bDescriptorType]) {
702 case USB_DESC_CONFIGURATION:
703 /* remember current configuration index */
704 cur_config = p[CONF_DESC_bConfigurationValue];
705 if (cur_config == setup->wValue) {
706 found = true;
707 }
708
709 break;
710
711 case USB_DESC_INTERFACE:
712 /* remember current alternate setting */
713 cur_alt_setting =
714 p[INTF_DESC_bAlternateSetting];
715 break;
716
717 case USB_DESC_ENDPOINT:
718 if ((cur_config != setup->wValue) ||
719 (cur_alt_setting != 0)) {
720 break;
721 }
722
723 found = set_endpoint((struct usb_ep_descriptor *)p);
724 break;
725
726 default:
727 break;
728 }
729
730 /* skip to next descriptor */
731 p += p[DESC_bLength];
732 }
733
734 if (found) {
735 usb_reset_alt_setting();
736 usb_dev.configuration = setup->wValue;
737 if (usb_dev.status_callback) {
738 usb_dev.status_callback(USB_DC_CONFIGURED,
739 &usb_dev.configuration);
740 }
741 } else {
742 LOG_DBG("Set Configuration %u failed", setup->wValue);
743 }
744
745 return found;
746 }
747
748 /*
749 * @brief set USB interface
750 *
751 * @param [in] setup The setup packet
752 *
753 * @return true if successfully configured false if error or unconfigured
754 */
usb_set_interface(struct usb_setup_packet * setup)755 static bool usb_set_interface(struct usb_setup_packet *setup)
756 {
757 const uint8_t *p = usb_dev.descriptors;
758 const uint8_t *if_desc = NULL;
759 struct usb_ep_descriptor *ep;
760 uint8_t cur_alt_setting = 0xFF;
761 uint8_t cur_iface = 0xFF;
762 bool ret = false;
763
764 LOG_DBG("Set Interface %u alternate %u", setup->wIndex, setup->wValue);
765
766 while (p[DESC_bLength] != 0U) {
767 switch (p[DESC_bDescriptorType]) {
768 case USB_DESC_INTERFACE:
769 /* remember current alternate setting */
770 cur_alt_setting = p[INTF_DESC_bAlternateSetting];
771 cur_iface = p[INTF_DESC_bInterfaceNumber];
772
773 if (cur_iface == setup->wIndex &&
774 cur_alt_setting == setup->wValue) {
775 ret = usb_set_alt_setting(setup->wIndex,
776 setup->wValue);
777 if_desc = (void *)p;
778 }
779
780 LOG_DBG("Current iface %u alt setting %u",
781 cur_iface, cur_alt_setting);
782 break;
783 case USB_DESC_ENDPOINT:
784 if (cur_iface == setup->wIndex) {
785 ep = (struct usb_ep_descriptor *)p;
786 ret = usb_eps_reconfigure(ep, cur_alt_setting,
787 setup->wValue);
788 }
789 break;
790 default:
791 break;
792 }
793
794 /* skip to next descriptor */
795 p += p[DESC_bLength];
796 }
797
798 if (usb_dev.status_callback) {
799 usb_dev.status_callback(USB_DC_INTERFACE, if_desc);
800 }
801
802 return ret;
803 }
804
usb_get_interface(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data_buf)805 static bool usb_get_interface(struct usb_setup_packet *setup,
806 int32_t *len, uint8_t **data_buf)
807 {
808 const uint8_t *p = usb_dev.descriptors;
809 uint8_t *data = *data_buf;
810 uint8_t cur_iface;
811
812 while (p[DESC_bLength] != 0U) {
813 if (p[DESC_bDescriptorType] == USB_DESC_INTERFACE) {
814 cur_iface = p[INTF_DESC_bInterfaceNumber];
815 if (cur_iface == setup->wIndex) {
816 data[0] = usb_get_alt_setting(cur_iface);
817 LOG_DBG("Current iface %u alt setting %u",
818 setup->wIndex, data[0]);
819 *len = 1;
820 return true;
821 }
822 }
823
824 /* skip to next descriptor */
825 p += p[DESC_bLength];
826 }
827
828 return false;
829 }
830
831 /**
832 * @brief Check if the device is in Configured state
833 *
834 * @return true if Configured, false otherwise.
835 */
is_device_configured(void)836 static bool is_device_configured(void)
837 {
838 return (usb_dev.configuration != 0);
839 }
840
841 /*
842 * @brief handle a standard device request
843 *
844 * @param [in] setup The setup packet
845 * @param [in,out] len Pointer to data length
846 * @param [in,out] data_buf Data buffer
847 *
848 * @return true if the request was handled successfully
849 */
usb_handle_std_device_req(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data_buf)850 static bool usb_handle_std_device_req(struct usb_setup_packet *setup,
851 int32_t *len, uint8_t **data_buf)
852 {
853 uint8_t *data = *data_buf;
854
855 if (usb_reqtype_is_to_host(setup)) {
856 switch (setup->bRequest) {
857 case USB_SREQ_GET_STATUS:
858 return usb_get_status(setup, len, data_buf);
859
860 case USB_SREQ_GET_DESCRIPTOR:
861 return usb_get_descriptor(setup, len, data_buf);
862
863 case USB_SREQ_GET_CONFIGURATION:
864 LOG_DBG("Get Configuration request");
865 /* indicate if we are configured */
866 data[0] = usb_dev.configuration;
867 *len = 1;
868 return true;
869 default:
870 break;
871 }
872 } else {
873 switch (setup->bRequest) {
874 case USB_SREQ_SET_ADDRESS:
875 LOG_DBG("Set Address %u request", setup->wValue);
876 return !usb_dc_set_address(setup->wValue);
877
878 case USB_SREQ_SET_CONFIGURATION:
879 return usb_set_configuration(setup);
880
881 case USB_SREQ_CLEAR_FEATURE:
882 LOG_DBG("Clear Feature request");
883
884 if (IS_ENABLED(CONFIG_USB_DEVICE_REMOTE_WAKEUP)) {
885 if (setup->wValue == USB_SFS_REMOTE_WAKEUP) {
886 usb_dev.remote_wakeup = false;
887 return true;
888 }
889 }
890 break;
891
892 case USB_SREQ_SET_FEATURE:
893 LOG_DBG("Set Feature request");
894
895 if (IS_ENABLED(CONFIG_USB_DEVICE_REMOTE_WAKEUP)) {
896 if (setup->wValue == USB_SFS_REMOTE_WAKEUP) {
897 usb_dev.remote_wakeup = true;
898 return true;
899 }
900 }
901 break;
902
903 default:
904 break;
905 }
906 }
907
908 LOG_DBG("Unsupported bmRequestType 0x%02x bRequest 0x%02x",
909 setup->bmRequestType, setup->bRequest);
910 return false;
911 }
912
913 /**
914 * @brief Check if the interface of given number is valid
915 *
916 * @param [in] interface Number of the addressed interface
917 *
918 * This function searches through descriptor and checks
919 * is the Host has addressed valid interface.
920 *
921 * @return true if interface exists - valid
922 */
is_interface_valid(uint8_t interface)923 static bool is_interface_valid(uint8_t interface)
924 {
925 const uint8_t *p = (uint8_t *)usb_dev.descriptors;
926 const struct usb_cfg_descriptor *cfg_descr;
927
928 /* Search through descriptor for matching interface */
929 while (p[DESC_bLength] != 0U) {
930 if (p[DESC_bDescriptorType] == USB_DESC_CONFIGURATION) {
931 cfg_descr = (const struct usb_cfg_descriptor *)p;
932 if (interface < cfg_descr->bNumInterfaces) {
933 return true;
934 }
935 }
936 p += p[DESC_bLength];
937 }
938
939 return false;
940 }
941
942 /*
943 * @brief handle a standard interface request
944 *
945 * @param [in] setup The setup packet
946 * @param [in,out] len Pointer to data length
947 * @param [in] data_buf Data buffer
948 *
949 * @return true if the request was handled successfully
950 */
usb_handle_std_interface_req(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data_buf)951 static bool usb_handle_std_interface_req(struct usb_setup_packet *setup,
952 int32_t *len, uint8_t **data_buf)
953 {
954 uint8_t *data = *data_buf;
955
956 /** The device must be configured to accept standard interface
957 * requests and the addressed Interface must be valid.
958 */
959 if (!is_device_configured() ||
960 (!is_interface_valid((uint8_t)setup->wIndex))) {
961 return false;
962 }
963
964 if (usb_reqtype_is_to_host(setup)) {
965 switch (setup->bRequest) {
966 case USB_SREQ_GET_STATUS:
967 /* no bits specified */
968 data[0] = 0U;
969 data[1] = 0U;
970 *len = 2;
971 return true;
972
973 case USB_SREQ_GET_INTERFACE:
974 return usb_get_interface(setup, len, data_buf);
975
976 default:
977 break;
978 }
979 } else {
980 if (setup->bRequest == USB_SREQ_SET_INTERFACE) {
981 return usb_set_interface(setup);
982 }
983
984 }
985
986 LOG_DBG("Unsupported bmRequestType 0x%02x bRequest 0x%02x",
987 setup->bmRequestType, setup->bRequest);
988 return false;
989 }
990
991 /**
992 * @brief Check if the endpoint of given address is valid
993 *
994 * @param [in] ep Address of the Endpoint
995 *
996 * This function checks if the Endpoint of given address
997 * is valid for the configured device. Valid Endpoint is
998 * either Control Endpoint or one used by the device.
999 *
1000 * @return true if endpoint exists - valid
1001 */
is_ep_valid(uint8_t ep)1002 static bool is_ep_valid(uint8_t ep)
1003 {
1004 const struct usb_ep_cfg_data *ep_data;
1005
1006 /* Check if its Endpoint 0 */
1007 if (USB_EP_GET_IDX(ep) == 0) {
1008 return true;
1009 }
1010
1011 STRUCT_SECTION_FOREACH(usb_cfg_data, cfg_data) {
1012 ep_data = cfg_data->endpoint;
1013
1014 for (uint8_t n = 0; n < cfg_data->num_endpoints; n++) {
1015 if (ep_data[n].ep_addr == ep) {
1016 return true;
1017 }
1018 }
1019 }
1020
1021 return false;
1022 }
1023
usb_get_status_endpoint(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data_buf)1024 static bool usb_get_status_endpoint(struct usb_setup_packet *setup,
1025 int32_t *len, uint8_t **data_buf)
1026 {
1027 uint8_t ep = setup->wIndex;
1028 uint8_t *data = *data_buf;
1029
1030 /* Check if request addresses valid Endpoint */
1031 if (!is_ep_valid(ep)) {
1032 return false;
1033 }
1034
1035 /* This request is valid for Control Endpoints when
1036 * the device is not yet configured. For other
1037 * Endpoints the device must be configured.
1038 * Firstly check if addressed ep is Control Endpoint.
1039 * If no then the device must be in Configured state
1040 * to accept the request.
1041 */
1042 if ((USB_EP_GET_IDX(ep) == 0) || is_device_configured()) {
1043 /* bit 0 - Endpoint halted or not */
1044 usb_dc_ep_is_stalled(ep, &data[0]);
1045 data[1] = 0U;
1046 *len = 2;
1047 return true;
1048 }
1049
1050 return false;
1051 }
1052
1053
usb_halt_endpoint_req(struct usb_setup_packet * setup,bool halt)1054 static bool usb_halt_endpoint_req(struct usb_setup_packet *setup, bool halt)
1055 {
1056 uint8_t ep = setup->wIndex;
1057
1058 /* Check if request addresses valid Endpoint */
1059 if (!is_ep_valid(ep)) {
1060 return false;
1061 }
1062
1063 /* This request is valid for Control Endpoints when
1064 * the device is not yet configured. For other
1065 * Endpoints the device must be configured.
1066 * Firstly check if addressed ep is Control Endpoint.
1067 * If no then the device must be in Configured state
1068 * to accept the request.
1069 */
1070 if ((USB_EP_GET_IDX(ep) == 0) || is_device_configured()) {
1071 if (halt) {
1072 LOG_INF("Set halt ep 0x%02x", ep);
1073 usb_dc_ep_set_stall(ep);
1074 if (usb_dev.status_callback) {
1075 usb_dev.status_callback(USB_DC_SET_HALT, &ep);
1076 }
1077 } else {
1078 LOG_INF("Clear halt ep 0x%02x", ep);
1079 usb_dc_ep_clear_stall(ep);
1080 if (usb_dev.status_callback) {
1081 usb_dev.status_callback(USB_DC_CLEAR_HALT, &ep);
1082 }
1083 }
1084
1085 return true;
1086 }
1087
1088 return false;
1089 }
1090
1091 /*
1092 * @brief handle a standard endpoint request
1093 *
1094 * @param [in] setup The setup packet
1095 * @param [in,out] len Pointer to data length
1096 * @param [in] data_buf Data buffer
1097 *
1098 * @return true if the request was handled successfully
1099 */
usb_handle_std_endpoint_req(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data_buf)1100 static bool usb_handle_std_endpoint_req(struct usb_setup_packet *setup,
1101 int32_t *len, uint8_t **data_buf)
1102 {
1103
1104 if (usb_reqtype_is_to_host(setup)) {
1105 if (setup->bRequest == USB_SREQ_GET_STATUS) {
1106 return usb_get_status_endpoint(setup, len, data_buf);
1107 }
1108 } else {
1109 switch (setup->bRequest) {
1110 case USB_SREQ_CLEAR_FEATURE:
1111 if (setup->wValue == USB_SFS_ENDPOINT_HALT) {
1112 return usb_halt_endpoint_req(setup, false);
1113 }
1114 break;
1115 case USB_SREQ_SET_FEATURE:
1116 if (setup->wValue == USB_SFS_ENDPOINT_HALT) {
1117 return usb_halt_endpoint_req(setup, true);
1118 }
1119 break;
1120 default:
1121 break;
1122 }
1123 }
1124
1125 LOG_DBG("Unsupported bmRequestType 0x%02x bRequest 0x%02x",
1126 setup->bmRequestType, setup->bRequest);
1127 return false;
1128 }
1129
1130 /*
1131 * @brief default handler for standard ('chapter 9') requests
1132 *
1133 * If a custom request handler was installed, this handler is called first.
1134 *
1135 * @param [in] setup The setup packet
1136 * @param [in,out] len Pointer to data length
1137 * @param [in] data_buf Data buffer
1138 *
1139 * @return true if the request was handled successfully
1140 */
usb_handle_standard_request(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data_buf)1141 static int usb_handle_standard_request(struct usb_setup_packet *setup,
1142 int32_t *len, uint8_t **data_buf)
1143 {
1144 int rc = 0;
1145
1146 if (!usb_handle_bos(setup, len, data_buf)) {
1147 return 0;
1148 }
1149
1150 if (!usb_handle_os_desc(setup, len, data_buf)) {
1151 return 0;
1152 }
1153
1154 /* try the custom request handler first */
1155 if (usb_dev.custom_req_handler &&
1156 !usb_dev.custom_req_handler(setup, len, data_buf)) {
1157 return 0;
1158 }
1159
1160 switch (setup->RequestType.recipient) {
1161 case USB_REQTYPE_RECIPIENT_DEVICE:
1162 if (usb_handle_std_device_req(setup, len, data_buf) == false) {
1163 rc = -EINVAL;
1164 }
1165 break;
1166 case USB_REQTYPE_RECIPIENT_INTERFACE:
1167 if (usb_handle_std_interface_req(setup, len, data_buf) == false) {
1168 rc = -EINVAL;
1169 }
1170 break;
1171 case USB_REQTYPE_RECIPIENT_ENDPOINT:
1172 if (usb_handle_std_endpoint_req(setup, len, data_buf) == false) {
1173 rc = -EINVAL;
1174 }
1175 break;
1176 default:
1177 rc = -EINVAL;
1178 }
1179 return rc;
1180 }
1181
1182 /*
1183 * @brief Registers a callback for custom device requests
1184 *
1185 * In usb_register_custom_req_handler, the custom request handler gets a first
1186 * chance at handling the request before it is handed over to the 'chapter 9'
1187 * request handler.
1188 *
1189 * This can be used for example in HID devices, where a REQ_GET_DESCRIPTOR
1190 * request is sent to an interface, which is not covered by the 'chapter 9'
1191 * specification.
1192 *
1193 * @param [in] handler Callback function pointer
1194 */
usb_register_custom_req_handler(usb_request_handler handler)1195 static void usb_register_custom_req_handler(usb_request_handler handler)
1196 {
1197 usb_dev.custom_req_handler = handler;
1198 }
1199
1200 /*
1201 * @brief register a callback for device status
1202 *
1203 * This function registers a callback for device status. The registered callback
1204 * is used to report changes in the status of the device controller.
1205 *
1206 * @param [in] cb Callback function pointer
1207 */
usb_register_status_callback(usb_dc_status_callback cb)1208 static void usb_register_status_callback(usb_dc_status_callback cb)
1209 {
1210 usb_dev.status_callback = cb;
1211 }
1212
foreach_ep(int (* endpoint_callback)(const struct usb_ep_cfg_data *))1213 static int foreach_ep(int (* endpoint_callback)(const struct usb_ep_cfg_data *))
1214 {
1215 struct usb_ep_cfg_data *ep_data;
1216
1217 STRUCT_SECTION_FOREACH(usb_cfg_data, cfg_data) {
1218 ep_data = cfg_data->endpoint;
1219
1220 for (uint8_t n = 0; n < cfg_data->num_endpoints; n++) {
1221 int ret;
1222
1223 ret = endpoint_callback(&ep_data[n]);
1224 if (ret < 0) {
1225 return ret;
1226 }
1227 }
1228 }
1229
1230 return 0;
1231 }
1232
disable_interface_ep(const struct usb_ep_cfg_data * ep_data)1233 static int disable_interface_ep(const struct usb_ep_cfg_data *ep_data)
1234 {
1235 uint32_t ep_bm;
1236 int ret;
1237
1238 ret = usb_dc_ep_disable(ep_data->ep_addr);
1239
1240 /* clear endpoint mask */
1241 ep_bm = get_ep_bm_from_addr(ep_data->ep_addr);
1242 usb_dev.ep_bm &= ~ep_bm;
1243
1244 return ret;
1245 }
1246
forward_status_cb(enum usb_dc_status_code status,const uint8_t * param)1247 static void forward_status_cb(enum usb_dc_status_code status, const uint8_t *param)
1248 {
1249 if (status == USB_DC_DISCONNECTED) {
1250 usb_reset_alt_setting();
1251 }
1252
1253 if (status == USB_DC_DISCONNECTED || status == USB_DC_RESET) {
1254 if (usb_dev.configured) {
1255 usb_cancel_transfers();
1256 foreach_ep(disable_interface_ep);
1257 usb_dev.configured = false;
1258 }
1259 }
1260
1261 STRUCT_SECTION_FOREACH(usb_cfg_data, cfg_data) {
1262 if (cfg_data->cb_usb_status) {
1263 cfg_data->cb_usb_status(cfg_data, status, param);
1264 }
1265 }
1266
1267 if (usb_dev.user_status_callback) {
1268 usb_dev.user_status_callback(status, param);
1269 }
1270 }
1271
1272 /**
1273 * @brief turn on/off USB VBUS voltage
1274 *
1275 * To utilize this in the devicetree the chosen node should have a
1276 * zephyr,usb-device property that points to the usb device controller node.
1277 * Additionally the usb device controller node should have a vbus-gpios
1278 * property that has the GPIO details.
1279 *
1280 * Something like:
1281 *
1282 * chosen {
1283 * zephyr,usb-device = &usbd;
1284 * };
1285 *
1286 * usbd: usbd {
1287 * vbus-gpios = <&gpio1 5 GPIO_ACTIVE_HIGH>;
1288 * };
1289 *
1290 * @param on Set to false to turn off and to true to turn on VBUS
1291 *
1292 * @return 0 on success, negative errno code on fail
1293 */
usb_vbus_set(bool on)1294 static int usb_vbus_set(bool on)
1295 {
1296 #define USB_DEV_NODE DT_CHOSEN(zephyr_usb_device)
1297 #if DT_NODE_HAS_STATUS(USB_DEV_NODE, okay) && \
1298 DT_NODE_HAS_PROP(USB_DEV_NODE, vbus_gpios)
1299 int ret = 0;
1300 struct gpio_dt_spec gpio_dev = GPIO_DT_SPEC_GET(USB_DEV_NODE, vbus_gpios);
1301
1302 if (!gpio_is_ready_dt(&gpio_dev)) {
1303 LOG_DBG("USB requires GPIO. Device %s is not ready!", gpio_dev.port->name);
1304 return -ENODEV;
1305 }
1306
1307 /* Enable USB IO */
1308 ret = gpio_pin_configure_dt(&gpio_dev, GPIO_OUTPUT);
1309 if (ret) {
1310 return ret;
1311 }
1312
1313 ret = gpio_pin_set_dt(&gpio_dev, on == true ? 1 : 0);
1314 if (ret) {
1315 return ret;
1316 }
1317 #endif
1318
1319 return 0;
1320 }
1321
usb_deconfig(void)1322 int usb_deconfig(void)
1323 {
1324 /* unregister descriptors */
1325 usb_register_descriptors(NULL);
1326
1327 /* unregister standard request handler */
1328 usb_register_request_handler(USB_REQTYPE_TYPE_STANDARD, NULL);
1329
1330 /* unregister class request handlers for each interface*/
1331 usb_register_request_handler(USB_REQTYPE_TYPE_CLASS, NULL);
1332
1333 /* unregister class request handlers for each interface*/
1334 usb_register_custom_req_handler(NULL);
1335
1336 /* unregister status callback */
1337 usb_register_status_callback(NULL);
1338
1339 /* unregister user status callback */
1340 usb_dev.user_status_callback = NULL;
1341
1342 /* Reset USB controller */
1343 usb_dc_reset();
1344
1345 return 0;
1346 }
1347
usb_disable(void)1348 int usb_disable(void)
1349 {
1350 int ret;
1351
1352 if (usb_dev.enabled != true) {
1353 /*Already disabled*/
1354 return 0;
1355 }
1356
1357 ret = usb_dc_detach();
1358 if (ret < 0) {
1359 return ret;
1360 }
1361
1362 usb_cancel_transfers();
1363 for (uint8_t i = 0; i <= 15; i++) {
1364 if (usb_dev.ep_bm & BIT(i)) {
1365 ret = disable_endpoint(i);
1366 if (ret < 0) {
1367 return ret;
1368 }
1369 }
1370 if (usb_dev.ep_bm & BIT(i + 16)) {
1371 ret = disable_endpoint(USB_EP_DIR_IN | i);
1372 if (ret < 0) {
1373 return ret;
1374 }
1375 }
1376 }
1377
1378 /* Disable VBUS if needed */
1379 usb_vbus_set(false);
1380
1381 usb_dev.enabled = false;
1382
1383 return 0;
1384 }
1385
usb_write(uint8_t ep,const uint8_t * data,uint32_t data_len,uint32_t * bytes_ret)1386 int usb_write(uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *bytes_ret)
1387 {
1388 int tries = CONFIG_USB_NUMOF_EP_WRITE_RETRIES;
1389 int ret;
1390
1391 do {
1392 ret = usb_dc_ep_write(ep, data, data_len, bytes_ret);
1393 if (ret == -EAGAIN) {
1394 LOG_WRN("Failed to write endpoint buffer 0x%02x", ep);
1395 k_yield();
1396 }
1397
1398 } while (ret == -EAGAIN && tries--);
1399
1400 return ret;
1401 }
1402
usb_read(uint8_t ep,uint8_t * data,uint32_t max_data_len,uint32_t * ret_bytes)1403 int usb_read(uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *ret_bytes)
1404 {
1405 return usb_dc_ep_read(ep, data, max_data_len, ret_bytes);
1406 }
1407
usb_ep_set_stall(uint8_t ep)1408 int usb_ep_set_stall(uint8_t ep)
1409 {
1410 return usb_dc_ep_set_stall(ep);
1411 }
1412
usb_ep_clear_stall(uint8_t ep)1413 int usb_ep_clear_stall(uint8_t ep)
1414 {
1415 return usb_dc_ep_clear_stall(ep);
1416 }
1417
usb_ep_read_wait(uint8_t ep,uint8_t * data,uint32_t max_data_len,uint32_t * ret_bytes)1418 int usb_ep_read_wait(uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *ret_bytes)
1419 {
1420 return usb_dc_ep_read_wait(ep, data, max_data_len, ret_bytes);
1421 }
1422
usb_ep_read_continue(uint8_t ep)1423 int usb_ep_read_continue(uint8_t ep)
1424 {
1425 return usb_dc_ep_read_continue(ep);
1426 }
1427
usb_get_remote_wakeup_status(void)1428 bool usb_get_remote_wakeup_status(void)
1429 {
1430 return usb_dev.remote_wakeup;
1431 }
1432
usb_wakeup_request(void)1433 int usb_wakeup_request(void)
1434 {
1435 if (IS_ENABLED(CONFIG_USB_DEVICE_REMOTE_WAKEUP)) {
1436 if (usb_get_remote_wakeup_status()) {
1437 return usb_dc_wakeup_request();
1438 }
1439 return -EACCES;
1440 } else {
1441 return -ENOTSUP;
1442 }
1443 }
1444
1445 /*
1446 * The functions class_handler(), custom_handler() and vendor_handler()
1447 * go through the interfaces one after the other and compare the
1448 * bInterfaceNumber with the wIndex and and then call the appropriate
1449 * callback of the USB function.
1450 * Note, a USB function can have more than one interface and the
1451 * request does not have to be directed to the first interface (unlikely).
1452 * These functions can be simplified and moved to usb_handle_request()
1453 * when legacy initialization through the usb_set_config() and
1454 * usb_enable() is no longer needed.
1455 */
1456
class_handler(struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)1457 static int class_handler(struct usb_setup_packet *pSetup,
1458 int32_t *len, uint8_t **data)
1459 {
1460 const struct usb_if_descriptor *if_descr;
1461 struct usb_interface_cfg_data *iface;
1462
1463 LOG_DBG("bRequest 0x%02x, wIndex 0x%04x",
1464 pSetup->bRequest, pSetup->wIndex);
1465
1466 STRUCT_SECTION_FOREACH(usb_cfg_data, cfg_data) {
1467 iface = &cfg_data->interface;
1468 if_descr = cfg_data->interface_descriptor;
1469 /*
1470 * Wind forward until it is within the range
1471 * of the current descriptor.
1472 */
1473 if ((uint8_t *)if_descr < usb_dev.descriptors) {
1474 continue;
1475 }
1476
1477 if (iface->class_handler &&
1478 if_descr->bInterfaceNumber == (pSetup->wIndex & 0xFF)) {
1479 return iface->class_handler(pSetup, len, data);
1480 }
1481 }
1482
1483 return -ENOTSUP;
1484 }
1485
custom_handler(struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)1486 static int custom_handler(struct usb_setup_packet *pSetup,
1487 int32_t *len, uint8_t **data)
1488 {
1489 const struct usb_if_descriptor *if_descr;
1490 struct usb_interface_cfg_data *iface;
1491
1492 LOG_DBG("bRequest 0x%02x, wIndex 0x%04x",
1493 pSetup->bRequest, pSetup->wIndex);
1494
1495 STRUCT_SECTION_FOREACH(usb_cfg_data, cfg_data) {
1496 iface = &cfg_data->interface;
1497 if_descr = cfg_data->interface_descriptor;
1498 /*
1499 * Wind forward until it is within the range
1500 * of the current descriptor.
1501 */
1502 if ((uint8_t *)if_descr < usb_dev.descriptors) {
1503 continue;
1504 }
1505
1506 if (iface->custom_handler == NULL) {
1507 continue;
1508 }
1509
1510 if (if_descr->bInterfaceNumber == (pSetup->wIndex & 0xFF)) {
1511 return iface->custom_handler(pSetup, len, data);
1512 } else {
1513 /*
1514 * Audio has several interfaces. if_descr points to
1515 * the first interface, but the request may be for
1516 * subsequent ones, so forward each request to audio.
1517 * The class does not actively engage in request
1518 * handling and therefore we can ignore return value.
1519 */
1520 if (if_descr->bInterfaceClass == USB_BCC_AUDIO) {
1521 (void)iface->custom_handler(pSetup, len, data);
1522 }
1523 }
1524 }
1525
1526 return -ENOTSUP;
1527 }
1528
vendor_handler(struct usb_setup_packet * pSetup,int32_t * len,uint8_t ** data)1529 static int vendor_handler(struct usb_setup_packet *pSetup,
1530 int32_t *len, uint8_t **data)
1531 {
1532 struct usb_interface_cfg_data *iface;
1533
1534 LOG_DBG("bRequest 0x%02x, wIndex 0x%04x",
1535 pSetup->bRequest, pSetup->wIndex);
1536
1537 if (usb_os_desc_enabled()) {
1538 if (!usb_handle_os_desc_feature(pSetup, len, data)) {
1539 return 0;
1540 }
1541 }
1542
1543 STRUCT_SECTION_FOREACH(usb_cfg_data, cfg_data) {
1544 iface = &cfg_data->interface;
1545 if (iface->vendor_handler) {
1546 if (!iface->vendor_handler(pSetup, len, data)) {
1547 return 0;
1548 }
1549 }
1550 }
1551
1552 return -ENOTSUP;
1553 }
1554
composite_setup_ep_cb(void)1555 static int composite_setup_ep_cb(void)
1556 {
1557 struct usb_ep_cfg_data *ep_data;
1558
1559 STRUCT_SECTION_FOREACH(usb_cfg_data, cfg_data) {
1560 ep_data = cfg_data->endpoint;
1561 for (uint8_t n = 0; n < cfg_data->num_endpoints; n++) {
1562 LOG_DBG("set cb, ep: 0x%x", ep_data[n].ep_addr);
1563 if (usb_dc_ep_set_callback(ep_data[n].ep_addr,
1564 ep_data[n].ep_cb)) {
1565 return -1;
1566 }
1567 }
1568 }
1569
1570 return 0;
1571 }
1572
usb_set_config(const uint8_t * device_descriptor)1573 int usb_set_config(const uint8_t *device_descriptor)
1574 {
1575 /* register descriptors */
1576 usb_register_descriptors(device_descriptor);
1577
1578 /* register standard request handler */
1579 usb_register_request_handler(USB_REQTYPE_TYPE_STANDARD,
1580 usb_handle_standard_request);
1581
1582 /* register class request handlers for each interface*/
1583 usb_register_request_handler(USB_REQTYPE_TYPE_CLASS, class_handler);
1584
1585 /* register vendor request handler */
1586 usb_register_request_handler(USB_REQTYPE_TYPE_VENDOR, vendor_handler);
1587
1588 /* register class request handlers for each interface*/
1589 usb_register_custom_req_handler(custom_handler);
1590
1591 return 0;
1592 }
1593
usb_enable(usb_dc_status_callback status_cb)1594 int usb_enable(usb_dc_status_callback status_cb)
1595 {
1596 int ret;
1597 struct usb_dc_ep_cfg_data ep0_cfg;
1598 struct usb_device_descriptor *dev_desc = (void *)usb_dev.descriptors;
1599
1600 /* Prevent from calling usb_enable form different context.
1601 * This should only be called once.
1602 */
1603 LOG_DBG("lock usb_enable_lock mutex");
1604 k_mutex_lock(&usb_enable_lock, K_FOREVER);
1605
1606 if (usb_dev.enabled == true) {
1607 LOG_WRN("USB device support already enabled");
1608 ret = -EALREADY;
1609 goto out;
1610 }
1611
1612 /* Enable VBUS if needed */
1613 ret = usb_vbus_set(true);
1614 if (ret < 0) {
1615 goto out;
1616 }
1617
1618 usb_dev.user_status_callback = status_cb;
1619 usb_register_status_callback(forward_status_cb);
1620 usb_dc_set_status_callback(forward_status_cb);
1621
1622 ret = usb_dc_attach();
1623 if (ret < 0) {
1624 goto out;
1625 }
1626
1627 ret = usb_transfer_init();
1628 if (ret < 0) {
1629 goto out;
1630 }
1631
1632 if (dev_desc->bDescriptorType != USB_DESC_DEVICE ||
1633 dev_desc->bMaxPacketSize0 == 0) {
1634 LOG_ERR("Erroneous device descriptor or bMaxPacketSize0");
1635 ret = -EINVAL;
1636 goto out;
1637 }
1638
1639 /* Configure control EP */
1640 usb_dev.mps0 = dev_desc->bMaxPacketSize0;
1641 ep0_cfg.ep_mps = usb_dev.mps0;
1642 ep0_cfg.ep_type = USB_DC_EP_CONTROL;
1643
1644 ep0_cfg.ep_addr = USB_CONTROL_EP_OUT;
1645 ret = usb_dc_ep_configure(&ep0_cfg);
1646 if (ret < 0) {
1647 goto out;
1648 }
1649
1650 ep0_cfg.ep_addr = USB_CONTROL_EP_IN;
1651 ret = usb_dc_ep_configure(&ep0_cfg);
1652 if (ret < 0) {
1653 goto out;
1654 }
1655
1656 /* Register endpoint 0 handlers*/
1657 ret = usb_dc_ep_set_callback(USB_CONTROL_EP_OUT,
1658 usb_handle_control_transfer);
1659 if (ret < 0) {
1660 goto out;
1661 }
1662
1663 ret = usb_dc_ep_set_callback(USB_CONTROL_EP_IN,
1664 usb_handle_control_transfer);
1665 if (ret < 0) {
1666 goto out;
1667 }
1668
1669 /* Register endpoint handlers*/
1670 ret = composite_setup_ep_cb();
1671 if (ret < 0) {
1672 goto out;
1673 }
1674
1675 /* Enable control EP */
1676 ret = usb_dc_ep_enable(USB_CONTROL_EP_OUT);
1677 if (ret < 0) {
1678 goto out;
1679 }
1680 usb_dev.ep_bm |= get_ep_bm_from_addr(USB_CONTROL_EP_OUT);
1681
1682 ret = usb_dc_ep_enable(USB_CONTROL_EP_IN);
1683 if (ret < 0) {
1684 goto out;
1685 }
1686 usb_dev.ep_bm |= get_ep_bm_from_addr(USB_CONTROL_EP_IN);
1687
1688 usb_dev.enabled = true;
1689 ret = 0;
1690 out:
1691 LOG_DBG("unlock usb_enable_lock mutex");
1692 k_mutex_unlock(&usb_enable_lock);
1693 return ret;
1694 }
1695
1696 /*
1697 * This function configures the USB device stack based on USB descriptor and
1698 * usb_cfg_data.
1699 */
usb_device_init(void)1700 static int usb_device_init(void)
1701 {
1702 uint8_t *device_descriptor;
1703
1704 if (usb_dev.enabled == true) {
1705 return -EALREADY;
1706 }
1707
1708 /* register device descriptor */
1709 device_descriptor = usb_get_device_descriptor();
1710 if (!device_descriptor) {
1711 LOG_ERR("Failed to configure USB device stack");
1712 return -1;
1713 }
1714
1715 usb_set_config(device_descriptor);
1716
1717 if (IS_ENABLED(CONFIG_USB_DEVICE_INITIALIZE_AT_BOOT)) {
1718 return usb_enable(NULL);
1719 }
1720
1721 return 0;
1722 }
1723
1724 SYS_INIT(usb_device_init, POST_KERNEL, CONFIG_APPLICATION_INIT_PRIORITY);
1725