1 /* usb_descriptor.c - USB common device descriptor definition */
2
3 /*
4 * Copyright (c) 2017 PHYTEC Messtechnik GmbH
5 * Copyright (c) 2017, 2018 Intel Corporation
6 *
7 * SPDX-License-Identifier: Apache-2.0
8 */
9
10 #include <string.h>
11 #include <zephyr/sys/byteorder.h>
12 #include <zephyr/sys/__assert.h>
13 #include <zephyr/usb/usb_device.h>
14 #include "usb_descriptor.h"
15 #include <zephyr/drivers/hwinfo.h>
16 #include <zephyr/sys/iterable_sections.h>
17 #include <zephyr/logging/log.h>
18 LOG_MODULE_REGISTER(usb_descriptor, CONFIG_USB_DEVICE_LOG_LEVEL);
19
20 /*
21 * The last index of the initializer_string without null character is:
22 * ascii_idx_max = bLength / 2 - 2
23 * Use this macro to determine the last index of ASCII7 string.
24 */
25 #define USB_BSTRING_ASCII_IDX_MAX(n) (n / 2 - 2)
26
27 /*
28 * The last index of the bString is:
29 * utf16le_idx_max = sizeof(initializer_string) * 2 - 2 - 1
30 * utf16le_idx_max = bLength - 2 - 1
31 * Use this macro to determine the last index of UTF16LE string.
32 */
33 #define USB_BSTRING_UTF16LE_IDX_MAX(n) (n - 3)
34
35 /* Linker-defined symbols bound the USB descriptor structs */
36 extern struct usb_desc_header __usb_descriptor_start[];
37 extern struct usb_desc_header __usb_descriptor_end[];
38
39 /* Structure representing the global USB description */
40 struct common_descriptor {
41 struct usb_device_descriptor device_descriptor;
42 struct usb_cfg_descriptor cfg_descr;
43 } __packed;
44
45 #define USB_DESC_MANUFACTURER_IDX 1
46 #define USB_DESC_PRODUCT_IDX 2
47 #define USB_DESC_SERIAL_NUMBER_IDX 3
48
49 #ifdef CONFIG_USB_CONFIGURATION_STRING_DESC_ENABLE
50 #define USB_DESC_CONFIGURATION_IDX 4
51 #endif
52
53 /*
54 * Device and configuration descriptor placed in the device section,
55 * no additional descriptor may be placed there.
56 */
57 USBD_DEVICE_DESCR_DEFINE(primary) struct common_descriptor common_desc = {
58 /* Device descriptor */
59 .device_descriptor = {
60 .bLength = sizeof(struct usb_device_descriptor),
61 .bDescriptorType = USB_DESC_DEVICE,
62 #ifdef CONFIG_USB_DEVICE_BOS
63 .bcdUSB = sys_cpu_to_le16(USB_SRN_2_0_1),
64 #else
65 .bcdUSB = sys_cpu_to_le16(USB_SRN_2_0),
66 #endif
67 #ifdef CONFIG_USB_COMPOSITE_DEVICE
68 .bDeviceClass = USB_BCC_MISCELLANEOUS,
69 .bDeviceSubClass = 0x02,
70 .bDeviceProtocol = 0x01,
71 #else
72 .bDeviceClass = 0,
73 .bDeviceSubClass = 0,
74 .bDeviceProtocol = 0,
75 #endif
76 .bMaxPacketSize0 = USB_MAX_CTRL_MPS,
77 .idVendor = sys_cpu_to_le16((uint16_t)CONFIG_USB_DEVICE_VID),
78 .idProduct = sys_cpu_to_le16((uint16_t)CONFIG_USB_DEVICE_PID),
79 .bcdDevice = sys_cpu_to_le16(USB_BCD_DRN),
80 .iManufacturer = USB_DESC_MANUFACTURER_IDX,
81 .iProduct = USB_DESC_PRODUCT_IDX,
82 .iSerialNumber = USB_DESC_SERIAL_NUMBER_IDX,
83 .bNumConfigurations = 1,
84 },
85 /* Configuration descriptor */
86 .cfg_descr = {
87 .bLength = sizeof(struct usb_cfg_descriptor),
88 .bDescriptorType = USB_DESC_CONFIGURATION,
89 /*wTotalLength will be fixed in usb_fix_descriptor() */
90 .wTotalLength = 0,
91 .bNumInterfaces = 0,
92 .bConfigurationValue = 1,
93 #ifdef CONFIG_USB_CONFIGURATION_STRING_DESC_ENABLE
94 .iConfiguration = USB_DESC_CONFIGURATION_IDX,
95 #else
96 .iConfiguration = 0,
97 #endif
98 .bmAttributes = USB_SCD_RESERVED |
99 COND_CODE_1(CONFIG_USB_SELF_POWERED,
100 (USB_SCD_SELF_POWERED), (0)) |
101 COND_CODE_1(CONFIG_USB_DEVICE_REMOTE_WAKEUP,
102 (USB_SCD_REMOTE_WAKEUP), (0)),
103 .bMaxPower = CONFIG_USB_MAX_POWER,
104 },
105 };
106
107 struct usb_string_desription {
108 struct usb_string_descriptor lang_descr;
109 struct usb_mfr_descriptor {
110 uint8_t bLength;
111 uint8_t bDescriptorType;
112 uint8_t bString[USB_BSTRING_LENGTH(
113 CONFIG_USB_DEVICE_MANUFACTURER)];
114 } __packed utf16le_mfr;
115
116 struct usb_product_descriptor {
117 uint8_t bLength;
118 uint8_t bDescriptorType;
119 uint8_t bString[USB_BSTRING_LENGTH(CONFIG_USB_DEVICE_PRODUCT)];
120 } __packed utf16le_product;
121
122 struct usb_sn_descriptor {
123 uint8_t bLength;
124 uint8_t bDescriptorType;
125 uint8_t bString[USB_BSTRING_LENGTH(CONFIG_USB_DEVICE_SN)];
126 } __packed utf16le_sn;
127
128 #ifdef CONFIG_USB_CONFIGURATION_STRING_DESC_ENABLE
129 struct usb_conf_descriptor {
130 uint8_t bLength;
131 uint8_t bDescriptorType;
132 uint8_t bString[USB_BSTRING_LENGTH(CONFIG_USB_CONFIGURATION_STRING_DESC)];
133 } __packed utf16le_conf;
134 #endif
135 } __packed;
136
137 /*
138 * Language, Manufacturer, Product and Serial string descriptors,
139 * placed in the string section.
140 * FIXME: These should be sorted additionally.
141 */
142 USBD_STRING_DESCR_DEFINE(primary) struct usb_string_desription string_descr = {
143 .lang_descr = {
144 .bLength = sizeof(struct usb_string_descriptor),
145 .bDescriptorType = USB_DESC_STRING,
146 .bString = sys_cpu_to_le16(0x0409),
147 },
148 /* Manufacturer String Descriptor */
149 .utf16le_mfr = {
150 .bLength = USB_STRING_DESCRIPTOR_LENGTH(
151 CONFIG_USB_DEVICE_MANUFACTURER),
152 .bDescriptorType = USB_DESC_STRING,
153 .bString = CONFIG_USB_DEVICE_MANUFACTURER,
154 },
155 /* Product String Descriptor */
156 .utf16le_product = {
157 .bLength = USB_STRING_DESCRIPTOR_LENGTH(
158 CONFIG_USB_DEVICE_PRODUCT),
159 .bDescriptorType = USB_DESC_STRING,
160 .bString = CONFIG_USB_DEVICE_PRODUCT,
161 },
162 /* Serial Number String Descriptor */
163 .utf16le_sn = {
164 .bLength = USB_STRING_DESCRIPTOR_LENGTH(CONFIG_USB_DEVICE_SN),
165 .bDescriptorType = USB_DESC_STRING,
166 .bString = CONFIG_USB_DEVICE_SN,
167 },
168 #ifdef CONFIG_USB_CONFIGURATION_STRING_DESC_ENABLE
169 /* Configuration String Descriptor */
170 .utf16le_conf = {
171 .bLength = USB_STRING_DESCRIPTOR_LENGTH(CONFIG_USB_CONFIGURATION_STRING_DESC),
172 .bDescriptorType = USB_DESC_STRING,
173 .bString = CONFIG_USB_CONFIGURATION_STRING_DESC,
174 },
175 #endif
176 };
177
178 /* This element marks the end of the entire descriptor. */
179 USBD_TERM_DESCR_DEFINE(primary) struct usb_desc_header term_descr = {
180 .bLength = 0,
181 .bDescriptorType = 0,
182 };
183
184 /*
185 * This function fixes bString by transforming the ASCII-7 string
186 * into a UTF16-LE during runtime.
187 */
ascii7_to_utf16le(void * descriptor)188 static void ascii7_to_utf16le(void *descriptor)
189 {
190 struct usb_string_descriptor *str_descr = descriptor;
191 int idx_max = USB_BSTRING_UTF16LE_IDX_MAX(str_descr->bLength);
192 int ascii_idx_max = USB_BSTRING_ASCII_IDX_MAX(str_descr->bLength);
193 uint8_t *buf = (uint8_t *)&str_descr->bString;
194
195 LOG_DBG("idx_max %d, ascii_idx_max %d, buf %p",
196 idx_max, ascii_idx_max, (void *)buf);
197
198 for (int i = idx_max; i >= 0; i -= 2) {
199 LOG_DBG("char %c : %x, idx %d -> %d",
200 buf[ascii_idx_max],
201 buf[ascii_idx_max],
202 ascii_idx_max, i);
203 __ASSERT(buf[ascii_idx_max] > 0x1F && buf[ascii_idx_max] < 0x7F,
204 "Only printable ascii-7 characters are allowed in USB "
205 "string descriptors");
206 buf[i] = 0U;
207 buf[i - 1] = buf[ascii_idx_max--];
208 }
209 }
210
211 /*
212 * Look for the bString that has the address equal to the ptr and
213 * return its index. Use it to determine the index of the bString and
214 * assign it to the interfaces iInterface variable.
215 */
usb_get_str_descriptor_idx(void * ptr)216 int usb_get_str_descriptor_idx(void *ptr)
217 {
218 struct usb_desc_header *head = __usb_descriptor_start;
219 struct usb_string_descriptor *str = ptr;
220 int str_descr_idx = 0;
221
222 while (head->bLength != 0U) {
223 switch (head->bDescriptorType) {
224 case USB_DESC_STRING:
225 if (head == (struct usb_desc_header *)str) {
226 return str_descr_idx;
227 }
228
229 str_descr_idx += 1;
230 break;
231 default:
232 break;
233 }
234
235 /* move to next descriptor */
236 head = (struct usb_desc_header *)((uint8_t *)head + head->bLength);
237 }
238
239 return 0;
240 }
241
242 /*
243 * Validate endpoint address and Update the endpoint descriptors at runtime,
244 * the result depends on the capabilities of the driver and the number and
245 * type of endpoints.
246 * The default endpoint address is stored in endpoint descriptor and
247 * usb_ep_cfg_data, so both variables bEndpointAddress and ep_addr need
248 * to be updated.
249 */
usb_validate_ep_cfg_data(struct usb_ep_descriptor * const ep_descr,struct usb_cfg_data * const cfg_data,uint32_t * requested_ep)250 static int usb_validate_ep_cfg_data(struct usb_ep_descriptor * const ep_descr,
251 struct usb_cfg_data * const cfg_data,
252 uint32_t *requested_ep)
253 {
254 for (unsigned int i = 0; i < cfg_data->num_endpoints; i++) {
255 struct usb_ep_cfg_data *ep_data = cfg_data->endpoint;
256
257 /*
258 * Trying to find the right entry in the usb_ep_cfg_data.
259 */
260 if (ep_descr->bEndpointAddress != ep_data[i].ep_addr) {
261 continue;
262 }
263
264 for (uint8_t idx = 1; idx < 16U; idx++) {
265 struct usb_dc_ep_cfg_data ep_cfg;
266
267 ep_cfg.ep_type = (ep_descr->bmAttributes &
268 USB_EP_TRANSFER_TYPE_MASK);
269 ep_cfg.ep_mps = ep_descr->wMaxPacketSize;
270 ep_cfg.ep_addr = ep_descr->bEndpointAddress;
271 if (ep_cfg.ep_addr & USB_EP_DIR_IN) {
272 if ((*requested_ep & (1U << (idx + 16U)))) {
273 continue;
274 }
275
276 ep_cfg.ep_addr = (USB_EP_DIR_IN | idx);
277 } else {
278 if ((*requested_ep & (1U << (idx)))) {
279 continue;
280 }
281
282 ep_cfg.ep_addr = idx;
283 }
284 if (!usb_dc_ep_check_cap(&ep_cfg)) {
285 LOG_DBG("Fixing EP address %x -> %x",
286 ep_descr->bEndpointAddress,
287 ep_cfg.ep_addr);
288 ep_descr->bEndpointAddress = ep_cfg.ep_addr;
289 ep_data[i].ep_addr = ep_cfg.ep_addr;
290 if (ep_cfg.ep_addr & USB_EP_DIR_IN) {
291 *requested_ep |= (1U << (idx + 16U));
292 } else {
293 *requested_ep |= (1U << idx);
294 }
295 LOG_DBG("endpoint 0x%x", ep_data[i].ep_addr);
296 return 0;
297 }
298 }
299 }
300 return -1;
301 }
302
303 /*
304 * The interface descriptor of a USB function must be assigned to the
305 * usb_cfg_data so that usb_ep_cfg_data and matching endpoint descriptor
306 * can be found.
307 */
usb_get_cfg_data(struct usb_if_descriptor * iface)308 static struct usb_cfg_data *usb_get_cfg_data(struct usb_if_descriptor *iface)
309 {
310 STRUCT_SECTION_FOREACH(usb_cfg_data, cfg_data) {
311 if (cfg_data->interface_descriptor == iface) {
312 return cfg_data;
313 }
314 }
315
316 return NULL;
317 }
318
319 /*
320 * Default USB Serial Number string descriptor will be derived from
321 * Hardware Information Driver (HWINFO). User can implement own variant
322 * of this function. Please note that the length of the new Serial Number
323 * descriptor may not exceed the length of the CONFIG_USB_DEVICE_SN. In
324 * case the device ID returned by the HWINFO driver is bigger, the lower
325 * part is used for the USB Serial Number, as that part is usually having
326 * more entropy.
327 */
usb_update_sn_string_descriptor(void)328 __weak uint8_t *usb_update_sn_string_descriptor(void)
329 {
330 /*
331 * The biggest device ID supported by the HWINFO driver is currently
332 * 128 bits, which is 16 bytes. Assume this is the maximum for now,
333 * unless the user requested a longer serial number.
334 */
335 const int usblen = sizeof(CONFIG_USB_DEVICE_SN) / 2;
336 uint8_t hwid[MAX(16, sizeof(CONFIG_USB_DEVICE_SN) / 2)];
337 static uint8_t sn[sizeof(CONFIG_USB_DEVICE_SN) + 1];
338 const char hex[] = "0123456789ABCDEF";
339 int hwlen, skip;
340
341 memset(hwid, 0, sizeof(hwid));
342 memset(sn, 0, sizeof(sn));
343
344 hwlen = hwinfo_get_device_id(hwid, sizeof(hwid));
345 if (hwlen > 0) {
346 skip = MAX(0, hwlen - usblen);
347 LOG_HEXDUMP_DBG(&hwid[skip], usblen, "Serial Number");
348 for (int i = 0; i < usblen; i++) {
349 sn[i * 2] = hex[hwid[i + skip] >> 4];
350 sn[i * 2 + 1] = hex[hwid[i + skip] & 0xF];
351 }
352 }
353
354 return sn;
355 }
356
usb_fix_ascii_sn_string_descriptor(struct usb_sn_descriptor * sn)357 static void usb_fix_ascii_sn_string_descriptor(struct usb_sn_descriptor *sn)
358 {
359 uint8_t *runtime_sn = usb_update_sn_string_descriptor();
360 int runtime_sn_len, default_sn_len;
361
362 if (!runtime_sn) {
363 return;
364 }
365
366 runtime_sn_len = strlen(runtime_sn);
367 if (!runtime_sn_len) {
368 return;
369 }
370
371 default_sn_len = strlen(CONFIG_USB_DEVICE_SN);
372
373 if (runtime_sn_len != default_sn_len) {
374 LOG_WRN("the new SN descriptor doesn't have the same "
375 "length as CONFIG_USB_DEVICE_SN");
376 }
377
378 memcpy(sn->bString, runtime_sn, MIN(runtime_sn_len, default_sn_len));
379 }
380
usb_desc_update_mps0(struct usb_device_descriptor * const desc)381 static void usb_desc_update_mps0(struct usb_device_descriptor *const desc)
382 {
383 struct usb_dc_ep_cfg_data ep_cfg = {
384 .ep_addr = 0,
385 .ep_mps = USB_MAX_CTRL_MPS,
386 .ep_type = USB_DC_EP_CONTROL,
387 };
388 int ret;
389
390 ret = usb_dc_ep_check_cap(&ep_cfg);
391 if (ret) {
392 /* Try the minimum bMaxPacketSize0 that must be supported. */
393 ep_cfg.ep_mps = 8;
394 ret = usb_dc_ep_check_cap(&ep_cfg);
395 if (ret) {
396 ep_cfg.ep_mps = 0;
397 }
398
399 __ASSERT(ret == 0, "Failed to find valid bMaxPacketSize0");
400 }
401
402 desc->bMaxPacketSize0 = ep_cfg.ep_mps;
403 LOG_DBG("Set bMaxPacketSize0 %u", desc->bMaxPacketSize0);
404 }
405
406 /*
407 * The entire descriptor, placed in the .usb.descriptor section,
408 * needs to be fixed before use. Currently, only the length of the
409 * entire device configuration (with all interfaces and endpoints)
410 * and the string descriptors will be corrected.
411 *
412 * Restrictions:
413 * - just one device configuration (there is only one)
414 * - string descriptor must be present
415 */
usb_fix_descriptor(struct usb_desc_header * head)416 static int usb_fix_descriptor(struct usb_desc_header *head)
417 {
418 struct usb_cfg_descriptor *cfg_descr = NULL;
419 struct usb_if_descriptor *if_descr = NULL;
420 struct usb_cfg_data *cfg_data = NULL;
421 struct usb_ep_descriptor *ep_descr = NULL;
422 uint8_t numof_ifaces = 0U;
423 uint8_t str_descr_idx = 0U;
424 uint32_t requested_ep = BIT(16) | BIT(0);
425
426 while (head->bLength != 0U) {
427 switch (head->bDescriptorType) {
428 case USB_DESC_DEVICE:
429 LOG_DBG("Device descriptor %p", head);
430 usb_desc_update_mps0((void *)head);
431 break;
432 case USB_DESC_CONFIGURATION:
433 cfg_descr = (struct usb_cfg_descriptor *)head;
434 LOG_DBG("Configuration descriptor %p", head);
435 break;
436 case USB_DESC_INTERFACE_ASSOC:
437 LOG_DBG("Association descriptor %p", head);
438 break;
439 case USB_DESC_INTERFACE:
440 if_descr = (struct usb_if_descriptor *)head;
441 LOG_DBG("Interface descriptor %p", head);
442 if (if_descr->bAlternateSetting) {
443 LOG_DBG("Skip alternate interface");
444 break;
445 }
446
447 if (if_descr->bInterfaceNumber == 0U) {
448 cfg_data = usb_get_cfg_data(if_descr);
449 if (!cfg_data) {
450 LOG_ERR("There is no usb_cfg_data "
451 "for %p", head);
452 return -1;
453 }
454
455 if (cfg_data->interface_config) {
456 cfg_data->interface_config(head,
457 numof_ifaces);
458 }
459 }
460
461 numof_ifaces++;
462 break;
463 case USB_DESC_ENDPOINT:
464 if (!cfg_data) {
465 LOG_ERR("Uninitialized usb_cfg_data pointer, "
466 "corrupted device descriptor?");
467 return -1;
468 }
469
470 LOG_DBG("Endpoint descriptor %p", head);
471 ep_descr = (struct usb_ep_descriptor *)head;
472 if (usb_validate_ep_cfg_data(ep_descr,
473 cfg_data,
474 &requested_ep)) {
475 LOG_ERR("Failed to validate endpoints");
476 return -1;
477 }
478
479 break;
480 case 0:
481 case USB_DESC_STRING:
482 /*
483 * Copy runtime SN string descriptor first, if has
484 */
485 if (str_descr_idx == USB_DESC_SERIAL_NUMBER_IDX) {
486 struct usb_sn_descriptor *sn =
487 (struct usb_sn_descriptor *)head;
488 usb_fix_ascii_sn_string_descriptor(sn);
489 }
490 /*
491 * Skip language descriptor but correct
492 * wTotalLength and bNumInterfaces once.
493 */
494 if (str_descr_idx) {
495 ascii7_to_utf16le(head);
496 } else {
497 if (!cfg_descr) {
498 LOG_ERR("Incomplete device descriptor");
499 return -1;
500 }
501
502 LOG_DBG("Now the wTotalLength is %zd",
503 (uint8_t *)head - (uint8_t *)cfg_descr);
504 sys_put_le16((uint8_t *)head - (uint8_t *)cfg_descr,
505 (uint8_t *)&cfg_descr->wTotalLength);
506 cfg_descr->bNumInterfaces = numof_ifaces;
507 }
508
509 str_descr_idx += 1U;
510
511 break;
512 default:
513 break;
514 }
515
516 /* Move to next descriptor */
517 head = (struct usb_desc_header *)((uint8_t *)head + head->bLength);
518 }
519
520 if ((head + 1) != __usb_descriptor_end) {
521 LOG_DBG("try to fix next descriptor at %p", head + 1);
522 return usb_fix_descriptor(head + 1);
523 }
524
525 return 0;
526 }
527
528
usb_get_device_descriptor(void)529 uint8_t *usb_get_device_descriptor(void)
530 {
531 static bool initialized;
532
533 LOG_DBG("__usb_descriptor_start %p", __usb_descriptor_start);
534 LOG_DBG("__usb_descriptor_end %p", __usb_descriptor_end);
535
536 if (!initialized) {
537 if (usb_fix_descriptor(__usb_descriptor_start)) {
538 LOG_ERR("Failed to fixup USB descriptor");
539 return NULL;
540 }
541
542 initialized = true;
543 }
544
545 return (uint8_t *) __usb_descriptor_start;
546 }
547
usb_get_dev_data_by_cfg(sys_slist_t * list,struct usb_cfg_data * cfg)548 struct usb_dev_data *usb_get_dev_data_by_cfg(sys_slist_t *list,
549 struct usb_cfg_data *cfg)
550 {
551 struct usb_dev_data *dev_data;
552
553 SYS_SLIST_FOR_EACH_CONTAINER(list, dev_data, node) {
554 const struct device *dev = dev_data->dev;
555 const struct usb_cfg_data *cfg_cur = dev->config;
556
557 if (cfg_cur == cfg) {
558 return dev_data;
559 }
560 }
561
562 LOG_DBG("Device data not found for cfg %p", cfg);
563
564 return NULL;
565 }
566
usb_get_dev_data_by_iface(sys_slist_t * list,uint8_t iface_num)567 struct usb_dev_data *usb_get_dev_data_by_iface(sys_slist_t *list,
568 uint8_t iface_num)
569 {
570 struct usb_dev_data *dev_data;
571
572 SYS_SLIST_FOR_EACH_CONTAINER(list, dev_data, node) {
573 const struct device *dev = dev_data->dev;
574 const struct usb_cfg_data *cfg = dev->config;
575 const struct usb_if_descriptor *if_desc =
576 cfg->interface_descriptor;
577
578 if (if_desc->bInterfaceNumber == iface_num) {
579 return dev_data;
580 }
581 }
582
583 LOG_DBG("Device data not found for iface number %u", iface_num);
584
585 return NULL;
586 }
587
usb_get_dev_data_by_ep(sys_slist_t * list,uint8_t ep)588 struct usb_dev_data *usb_get_dev_data_by_ep(sys_slist_t *list, uint8_t ep)
589 {
590 struct usb_dev_data *dev_data;
591
592 SYS_SLIST_FOR_EACH_CONTAINER(list, dev_data, node) {
593 const struct device *dev = dev_data->dev;
594 const struct usb_cfg_data *cfg = dev->config;
595 const struct usb_ep_cfg_data *ep_data = cfg->endpoint;
596
597 for (uint8_t i = 0; i < cfg->num_endpoints; i++) {
598 if (ep_data[i].ep_addr == ep) {
599 return dev_data;
600 }
601 }
602 }
603
604 LOG_DBG("Device data not found for ep %u", ep);
605
606 return NULL;
607 }
608