1 // SPDX-License-Identifier: GPL-2.0+
3 * usb/gadget/config.c -- simplify building config descriptors
5 * Copyright (C) 2003 David Brownell
11 #include <asm/unaligned.h>
12 #include <linux/errno.h>
13 #include <linux/list.h>
14 #include <linux/string.h>
16 #include <linux/usb/ch9.h>
17 #include <linux/usb/gadget.h>
20 * usb_descriptor_fillbuf - fill buffer with descriptors
21 * @buf: Buffer to be filled
22 * @buflen: Size of buf
23 * @src: Array of descriptor pointers, terminated by null pointer.
25 * Copies descriptors into the buffer, returning the length or a
26 * negative error code if they can't all be copied. Useful when
27 * assembling descriptors for an associated set of interfaces used
28 * as part of configuring a composite device; or in other cases where
29 * sets of descriptors need to be marshaled.
32 usb_descriptor_fillbuf(void *buf, unsigned buflen,
33 const struct usb_descriptor_header **src)
40 /* fill buffer from src[] until null descriptor ptr */
41 for (; NULL != *src; src++) {
42 unsigned len = (*src)->bLength;
46 memcpy(dest, *src, len);
50 return dest - (u8 *)buf;
54 * usb_gadget_config_buf - builts a complete configuration descriptor
55 * @config: Header for the descriptor, including characteristics such
56 * as power requirements and number of interfaces.
57 * @desc: Null-terminated vector of pointers to the descriptors (interface,
58 * endpoint, etc) defining all functions in this device configuration.
59 * @buf: Buffer for the resulting configuration descriptor.
60 * @length: Length of buffer. If this is not big enough to hold the
61 * entire configuration descriptor, an error code will be returned.
63 * This copies descriptors into the response buffer, building a descriptor
64 * for that configuration. It returns the buffer length or a negative
65 * status code. The config.wTotalLength field is set to match the length
66 * of the result, but other descriptor fields (including power usage and
67 * interface count) must be set by the caller.
69 * Gadget drivers could use this when constructing a config descriptor
70 * in response to USB_REQ_GET_DESCRIPTOR. They will need to patch the
71 * resulting bDescriptorType value if USB_DT_OTHER_SPEED_CONFIG is needed.
73 int usb_gadget_config_buf(
74 const struct usb_config_descriptor *config,
77 const struct usb_descriptor_header **desc
80 struct usb_config_descriptor *cp = buf;
83 /* config descriptor first */
84 if (length < USB_DT_CONFIG_SIZE || !desc)
86 /* config need not be aligned */
87 memcpy(cp, config, sizeof(*cp));
89 /* then interface/endpoint/class/vendor/... */
90 len = usb_descriptor_fillbuf(USB_DT_CONFIG_SIZE + (u8 *)buf,
91 length - USB_DT_CONFIG_SIZE, desc);
94 len += USB_DT_CONFIG_SIZE;
98 /* patch up the config descriptor */
99 cp->bLength = USB_DT_CONFIG_SIZE;
100 cp->bDescriptorType = USB_DT_CONFIG;
101 put_unaligned_le16(len, &cp->wTotalLength);
102 cp->bmAttributes |= USB_CONFIG_ATT_ONE;