1 /*
2  * Copyright (c) 2022 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file
9  * @brief New experimental USB device stack APIs and structures
10  *
11  * This file contains the USB device stack APIs and structures.
12  */
13 
14 #ifndef ZEPHYR_INCLUDE_USBD_H_
15 #define ZEPHYR_INCLUDE_USBD_H_
16 
17 #include <zephyr/device.h>
18 #include <zephyr/usb/bos.h>
19 #include <zephyr/usb/usb_ch9.h>
20 #include <zephyr/usb/usbd_msg.h>
21 #include <zephyr/drivers/usb/udc_buf.h>
22 #include <zephyr/sys/byteorder.h>
23 #include <zephyr/sys/slist.h>
24 #include <zephyr/logging/log.h>
25 #include <zephyr/sys/iterable_sections.h>
26 
27 #ifdef __cplusplus
28 extern "C" {
29 #endif
30 
31 /**
32  * @brief New USB device stack core API
33  * @defgroup usbd_api USB device core API
34  * @ingroup usb
35  * @{
36  */
37 
38 /*
39  * The USB Unicode bString is encoded in UTF16LE, which means it takes up
40  * twice the amount of bytes than the same string encoded in ASCII7.
41  * Use this macro to determine the length of the bString array.
42  *
43  * bString length without null character:
44  *   bString_length = (sizeof(initializer_string) - 1) * 2
45  * or:
46  *   bString_length = sizeof(initializer_string) * 2 - 2
47  */
48 #define USB_BSTRING_LENGTH(s)		(sizeof(s) * 2 - 2)
49 
50 /*
51  * The length of the string descriptor (bLength) is calculated from the
52  * size of the two octets bLength and bDescriptorType plus the
53  * length of the UTF16LE string:
54  *
55  *   bLength = 2 + bString_length
56  *   bLength = 2 + sizeof(initializer_string) * 2 - 2
57  *   bLength = sizeof(initializer_string) * 2
58  * Use this macro to determine the bLength of the string descriptor.
59  */
60 #define USB_STRING_DESCRIPTOR_LENGTH(s)	(sizeof(s) * 2)
61 
62 /** Used internally to keep descriptors in order
63  * @cond INTERNAL_HIDDEN
64  */
65 enum usbd_str_desc_utype {
66 	USBD_DUT_STRING_LANG,
67 	USBD_DUT_STRING_MANUFACTURER,
68 	USBD_DUT_STRING_PRODUCT,
69 	USBD_DUT_STRING_SERIAL_NUMBER,
70 	USBD_DUT_STRING_CONFIG,
71 	USBD_DUT_STRING_INTERFACE,
72 };
73 
74 enum usbd_bos_desc_utype {
75 	USBD_DUT_BOS_NONE,
76 };
77 /** @endcond */
78 
79 /**
80  * USBD string descriptor data
81  */
82 struct usbd_str_desc_data {
83 	/** Descriptor index, required for string descriptors */
84 	uint8_t idx;
85 	/** Descriptor usage type (not bDescriptorType) */
86 	enum usbd_str_desc_utype utype : 8;
87 	/** The string descriptor is in ASCII7 format */
88 	unsigned int ascii7 : 1;
89 	/** Device stack obtains SerialNumber using the HWINFO API */
90 	unsigned int use_hwinfo : 1;
91 };
92 
93 /**
94  * USBD BOS Device Capability descriptor data
95  */
96 struct usbd_bos_desc_data {
97 	/** Descriptor usage type (not bDescriptorType) */
98 	enum usbd_bos_desc_utype utype : 8;
99 };
100 
101 /**
102  * Descriptor node
103  *
104  * Descriptor node is used to manage descriptors that are not
105  * directly part of a structure, such as string or BOS capability descriptors.
106  */
107 struct usbd_desc_node {
108 	/** slist node struct */
109 	sys_dnode_t node;
110 	union {
111 		struct usbd_str_desc_data str;
112 		struct usbd_bos_desc_data bos;
113 	};
114 	/** Opaque pointer to a descriptor payload */
115 	const void *const ptr;
116 	/** Descriptor size in bytes */
117 	uint8_t bLength;
118 	/** Descriptor type */
119 	uint8_t bDescriptorType;
120 };
121 
122 /**
123  * Device configuration node
124  *
125  * Configuration node is used to manage device configurations,
126  * at least one configuration is required. It does not have an index,
127  * instead bConfigurationValue of the descriptor is used for
128  * identification.
129  */
130 struct usbd_config_node {
131 	/** slist node struct */
132 	sys_snode_t node;
133 	/** Pointer to configuration descriptor */
134 	void *desc;
135 	/** Optional pointer to string descriptor node */
136 	struct usbd_desc_node *str_desc_nd;
137 	/** List of registered classes (functions) */
138 	sys_slist_t class_list;
139 };
140 
141 /* TODO: Kconfig option USBD_NUMOF_INTERFACES_MAX? */
142 #define USBD_NUMOF_INTERFACES_MAX	16U
143 
144 /**
145  * USB device support middle layer runtime state
146  *
147  * Part of USB device states without suspended and powered
148  * states, as it is better to track them separately.
149  */
150 enum usbd_ch9_state {
151 	USBD_STATE_DEFAULT = 0,
152 	USBD_STATE_ADDRESS,
153 	USBD_STATE_CONFIGURED,
154 };
155 
156 
157 /**
158  * USB device support middle layer runtime data
159  */
160 struct usbd_ch9_data {
161 	/** Setup packet, up-to-date for the respective control request */
162 	struct usb_setup_packet setup;
163 	/** Control type, internally used for stage verification */
164 	int ctrl_type;
165 	/** Protocol state of the USB device stack */
166 	enum usbd_ch9_state state;
167 	/** Halted endpoints bitmap */
168 	uint32_t ep_halt;
169 	/** USB device stack selected configuration */
170 	uint8_t configuration;
171 	/** Post status stage work required, e.g. set new device address */
172 	bool post_status;
173 	/** Array to track interfaces alternate settings */
174 	uint8_t alternate[USBD_NUMOF_INTERFACES_MAX];
175 };
176 
177 /**
178  * @brief USB device speed
179  */
180 enum usbd_speed {
181 	/** Device supports or is connected to a full speed bus */
182 	USBD_SPEED_FS,
183 	/** Device supports or is connected to a high speed bus  */
184 	USBD_SPEED_HS,
185 	/** Device supports or is connected to a super speed bus */
186 	USBD_SPEED_SS,
187 };
188 
189 /**
190  * USB device support status
191  */
192 struct usbd_status {
193 	/** USB device support is initialized */
194 	unsigned int initialized : 1;
195 	/** USB device support is enabled */
196 	unsigned int enabled : 1;
197 	/** USB device is suspended */
198 	unsigned int suspended : 1;
199 	/** USB remote wake-up feature is enabled */
200 	unsigned int rwup : 1;
201 	/** USB device speed */
202 	enum usbd_speed speed : 2;
203 };
204 
205 struct usbd_context;
206 
207 /**
208  * @brief Callback type definition for USB device message delivery
209  *
210  * The implementation uses the system workqueue, and a callback provided and
211  * registered by the application. The application callback is called in the
212  * context of the system workqueue. Notification messages are stored in a queue
213  * and delivered to the callback in sequence.
214  *
215  * @param[in] ctx Pointer to USB device support context
216  * @param[in] msg Pointer to USB device message
217  */
218 typedef void (*usbd_msg_cb_t)(struct usbd_context *const ctx,
219 			      const struct usbd_msg *const msg);
220 
221 /**
222  * USB device support runtime context
223  *
224  * Main structure that organizes all descriptors, configuration,
225  * and interfaces. An UDC device must be assigned to this structure.
226  */
227 struct usbd_context {
228 	/** Name of the USB device */
229 	const char *name;
230 	/** Access mutex */
231 	struct k_mutex mutex;
232 	/** Pointer to UDC device */
233 	const struct device *dev;
234 	/** Notification message recipient callback */
235 	usbd_msg_cb_t msg_cb;
236 	/** Middle layer runtime data */
237 	struct usbd_ch9_data ch9_data;
238 	/** slist to manage descriptors like string, BOS */
239 	sys_dlist_t descriptors;
240 	/** slist to manage Full-Speed device configurations */
241 	sys_slist_t fs_configs;
242 	/** slist to manage High-Speed device configurations */
243 	sys_slist_t hs_configs;
244 	/** Status of the USB device support */
245 	struct usbd_status status;
246 	/** Pointer to Full-Speed device descriptor */
247 	void *fs_desc;
248 	/** Pointer to High-Speed device descriptor */
249 	void *hs_desc;
250 };
251 
252 /**
253  * @brief Vendor Requests Table
254  */
255 struct usbd_cctx_vendor_req {
256 	/** Array of vendor requests supported by the class */
257 	const uint8_t *reqs;
258 	/** Length of the array */
259 	uint8_t len;
260 };
261 
262 /** USB Class instance registered flag */
263 #define USBD_CCTX_REGISTERED		0
264 
265 struct usbd_class_data;
266 
267 /**
268  * @brief USB device support class instance API
269  */
270 struct usbd_class_api {
271 	/** Feature halt state update handler */
272 	void (*feature_halt)(struct usbd_class_data *const c_data,
273 			     uint8_t ep, bool halted);
274 
275 	/** Configuration update handler */
276 	void (*update)(struct usbd_class_data *const c_data,
277 		       uint8_t iface, uint8_t alternate);
278 
279 	/** USB control request handler to device */
280 	int (*control_to_dev)(struct usbd_class_data *const c_data,
281 			      const struct usb_setup_packet *const setup,
282 			      const struct net_buf *const buf);
283 
284 	/** USB control request handler to host */
285 	int (*control_to_host)(struct usbd_class_data *const c_data,
286 			       const struct usb_setup_packet *const setup,
287 			       struct net_buf *const buf);
288 
289 	/** Endpoint request completion event handler */
290 	int (*request)(struct usbd_class_data *const c_data,
291 		       struct net_buf *buf, int err);
292 
293 	/** USB power management handler suspended */
294 	void (*suspended)(struct usbd_class_data *const c_data);
295 
296 	/** USB power management handler resumed */
297 	void (*resumed)(struct usbd_class_data *const c_data);
298 
299 	/** Start of Frame */
300 	void (*sof)(struct usbd_class_data *const c_data);
301 
302 	/** Class associated configuration is selected */
303 	void (*enable)(struct usbd_class_data *const c_data);
304 
305 	/** Class associated configuration is disabled */
306 	void (*disable)(struct usbd_class_data *const c_data);
307 
308 	/** Initialization of the class implementation */
309 	int (*init)(struct usbd_class_data *const c_data);
310 
311 	/** Shutdown of the class implementation */
312 	void (*shutdown)(struct usbd_class_data *const c_data);
313 
314 	/** Get function descriptor based on speed parameter */
315 	void *(*get_desc)(struct usbd_class_data *const c_data,
316 			  const enum usbd_speed speed);
317 };
318 
319 /**
320  * @brief USB device support class data
321  */
322 struct usbd_class_data {
323 	/** Name of the USB device class instance */
324 	const char *name;
325 	/** Pointer to USB device stack context structure */
326 	struct usbd_context *uds_ctx;
327 	/** Pointer to device support class API */
328 	const struct usbd_class_api *api;
329 	/** Supported vendor request table, can be NULL */
330 	const struct usbd_cctx_vendor_req *v_reqs;
331 	/** Pointer to private data */
332 	void *priv;
333 };
334 
335 /**
336  * @cond INTERNAL_HIDDEN
337  *
338  * Variables necessary for per speed class management. For each speed (Full,
339  * High) there is separate `struct usbd_class_node` pointing to the same
340  * `struct usbd_class_data` (because the class can only operate at one speed
341  * at a time).
342  */
343 struct usbd_class_node {
344 	/** Node information for the slist. */
345 	sys_snode_t node;
346 	/** Pointer to public class node instance. */
347 	struct usbd_class_data *const c_data;
348 	/** Bitmap of all endpoints assigned to the instance.
349 	 *  The IN endpoints are mapped in the upper halfword.
350 	 */
351 	uint32_t ep_assigned;
352 	/** Bitmap of the enabled endpoints of the instance.
353 	 *  The IN endpoints are mapped in the upper halfword.
354 	 */
355 	uint32_t ep_active;
356 	/** Bitmap of the bInterfaceNumbers of the class instance */
357 	uint32_t iface_bm;
358 	/** Variable to store the state of the class instance */
359 	atomic_t state;
360 };
361 
362 /** @endcond */
363 
364 /**
365  * @brief Get the USB device runtime context under which the class is registered
366  *
367  * The class implementation must use this function and not access the members
368  * of the struct directly.
369  *
370  * @param[in] c_data Pointer to USB device class data
371  *
372  * @return Pointer to USB device runtime context
373  */
usbd_class_get_ctx(const struct usbd_class_data * const c_data)374 static inline struct usbd_context *usbd_class_get_ctx(const struct usbd_class_data *const c_data)
375 {
376 	return c_data->uds_ctx;
377 }
378 
379 /**
380  * @brief Get class implementation private data
381  *
382  * The class implementation must use this function and not access the members
383  * of the struct directly.
384  *
385  * @param[in] c_data Pointer to USB device class data
386  *
387  * @return Pointer to class implementation private data
388  */
usbd_class_get_private(const struct usbd_class_data * const c_data)389 static inline void *usbd_class_get_private(const struct usbd_class_data *const c_data)
390 {
391 	return c_data->priv;
392 }
393 
394 /**
395  * @brief Define USB device context structure
396  *
397  * Macro defines a USB device structure needed by the stack to manage its
398  * properties and runtime data. The @p vid and @p pid  parameters can also be
399  * changed using usbd_device_set_vid() and usbd_device_set_pid().
400  *
401  * Example of use:
402  *
403  * @code{.c}
404  * USBD_DEVICE_DEFINE(sample_usbd,
405  *                    DEVICE_DT_GET(DT_NODELABEL(zephyr_udc0)),
406  *                    YOUR_VID, YOUR_PID);
407  * @endcode
408  *
409  * @param device_name USB device context name
410  * @param udc_dev     Pointer to UDC device structure
411  * @param vid         Vendor ID
412  * @param pid         Product ID
413  */
414 #define USBD_DEVICE_DEFINE(device_name, udc_dev, vid, pid)		\
415 	static struct usb_device_descriptor				\
416 	fs_desc_##device_name = {					\
417 		.bLength = sizeof(struct usb_device_descriptor),	\
418 		.bDescriptorType = USB_DESC_DEVICE,			\
419 		.bcdUSB = sys_cpu_to_le16(USB_SRN_2_0),			\
420 		.bDeviceClass = USB_BCC_MISCELLANEOUS,			\
421 		.bDeviceSubClass = 2,					\
422 		.bDeviceProtocol = 1,					\
423 		.bMaxPacketSize0 = USB_CONTROL_EP_MPS,			\
424 		.idVendor = vid,					\
425 		.idProduct = pid,					\
426 		.bcdDevice = sys_cpu_to_le16(USB_BCD_DRN),		\
427 		.iManufacturer = 0,					\
428 		.iProduct = 0,						\
429 		.iSerialNumber = 0,					\
430 		.bNumConfigurations = 0,				\
431 	};								\
432 	static struct usb_device_descriptor				\
433 	hs_desc_##device_name = {					\
434 		.bLength = sizeof(struct usb_device_descriptor),	\
435 		.bDescriptorType = USB_DESC_DEVICE,			\
436 		.bcdUSB = sys_cpu_to_le16(USB_SRN_2_0),			\
437 		.bDeviceClass = USB_BCC_MISCELLANEOUS,			\
438 		.bDeviceSubClass = 2,					\
439 		.bDeviceProtocol = 1,					\
440 		.bMaxPacketSize0 = 64,					\
441 		.idVendor = vid,					\
442 		.idProduct = pid,					\
443 		.bcdDevice = sys_cpu_to_le16(USB_BCD_DRN),		\
444 		.iManufacturer = 0,					\
445 		.iProduct = 0,						\
446 		.iSerialNumber = 0,					\
447 		.bNumConfigurations = 0,				\
448 	};								\
449 	static STRUCT_SECTION_ITERABLE(usbd_context, device_name) = {	\
450 		.name = STRINGIFY(device_name),				\
451 		.dev = udc_dev,						\
452 		.fs_desc = &fs_desc_##device_name,			\
453 		.hs_desc = &hs_desc_##device_name,			\
454 	}
455 
456 /**
457  * @brief Define USB device configuration
458  *
459  * USB device requires at least one configuration instance per supported speed.
460  * @p attrib is a combination of `USB_SCD_SELF_POWERED` or `USB_SCD_REMOTE_WAKEUP`,
461  * depending on which characteristic the USB device should have in this
462  * configuration.
463  *
464  * @param name   Configuration name
465  * @param attrib Configuration characteristics. Attributes can also be updated
466  *               with usbd_config_attrib_rwup() and usbd_config_attrib_self()
467  * @param power  bMaxPower value in 2 mA units. This value can also be set with
468  *               usbd_config_maxpower()
469  * @param desc_nd Address of the string descriptor node used to describe the
470  *                configuration, see USBD_DESC_CONFIG_DEFINE().
471  *                String descriptors are optional and the parameter can be NULL.
472  */
473 #define USBD_CONFIGURATION_DEFINE(name, attrib, power, desc_nd)		\
474 	static struct usb_cfg_descriptor				\
475 	cfg_desc_##name = {						\
476 		.bLength = sizeof(struct usb_cfg_descriptor),		\
477 		.bDescriptorType = USB_DESC_CONFIGURATION,		\
478 		.wTotalLength = 0,					\
479 		.bNumInterfaces = 0,					\
480 		.bConfigurationValue = 1,				\
481 		.iConfiguration = 0,					\
482 		.bmAttributes = USB_SCD_RESERVED | (attrib),		\
483 		.bMaxPower = (power),					\
484 	};								\
485 	BUILD_ASSERT((power) < 256, "Too much power");			\
486 	static struct usbd_config_node name = {				\
487 		.desc = &cfg_desc_##name,				\
488 		.str_desc_nd = desc_nd,					\
489 	}
490 
491 /**
492  * @brief Create a string descriptor node and language string descriptor
493  *
494  * This macro defines a descriptor node and a string descriptor that,
495  * when added to the device context, is automatically used as the language
496  * string descriptor zero. Both descriptor node and descriptor are defined with
497  * static-storage-class specifier. Default and currently only supported
498  * language ID is 0x0409 English (United States).
499  * If string descriptors are used, it is necessary to add this descriptor
500  * as the first one to the USB device context.
501  *
502  * @param name Language string descriptor node identifier.
503  */
504 #define USBD_DESC_LANG_DEFINE(name)					\
505 	static uint16_t langid_##name = sys_cpu_to_le16(0x0409);	\
506 	static struct usbd_desc_node name = {				\
507 		.str = {						\
508 			.idx = 0,					\
509 			.utype = USBD_DUT_STRING_LANG,			\
510 		},							\
511 		.ptr = &langid_##name,					\
512 		.bLength = sizeof(struct usb_string_descriptor),	\
513 		.bDescriptorType = USB_DESC_STRING,			\
514 	}
515 
516 /**
517  * @brief Create a string descriptor
518  *
519  * This macro defines a descriptor node and a string descriptor.
520  * The string literal passed to the macro should be in the ASCII7 format. It
521  * is converted to UTF16LE format on the host request.
522  *
523  * @param d_name   Internal string descriptor node identifier name
524  * @param d_string ASCII7 encoded string literal
525  * @param d_utype  String descriptor usage type
526  */
527 #define USBD_DESC_STRING_DEFINE(d_name, d_string, d_utype)			\
528 	static uint8_t ascii_##d_name[USB_BSTRING_LENGTH(d_string)] = d_string;	\
529 	static struct usbd_desc_node d_name = {					\
530 		.str = {							\
531 			.utype = d_utype,					\
532 			.ascii7 = true,						\
533 		},								\
534 		.ptr = &ascii_##d_name,						\
535 		.bLength = USB_STRING_DESCRIPTOR_LENGTH(d_string),		\
536 		.bDescriptorType = USB_DESC_STRING,				\
537 	}
538 
539 /**
540  * @brief Create a string descriptor node and manufacturer string descriptor
541  *
542  * This macro defines a descriptor node and a string descriptor that,
543  * when added to the device context, is automatically used as the manufacturer
544  * string descriptor. Both descriptor node and descriptor are defined with
545  * static-storage-class specifier.
546  *
547  * @param d_name   String descriptor node identifier.
548  * @param d_string ASCII7 encoded manufacturer string literal
549  */
550 #define USBD_DESC_MANUFACTURER_DEFINE(d_name, d_string)			\
551 	USBD_DESC_STRING_DEFINE(d_name, d_string, USBD_DUT_STRING_MANUFACTURER)
552 
553 /**
554  * @brief Create a string descriptor node and product string descriptor
555  *
556  * This macro defines a descriptor node and a string descriptor that,
557  * when added to the device context, is automatically used as the product
558  * string descriptor. Both descriptor node and descriptor are defined with
559  * static-storage-class specifier.
560  *
561  * @param d_name   String descriptor node identifier.
562  * @param d_string ASCII7 encoded product string literal
563  */
564 #define USBD_DESC_PRODUCT_DEFINE(d_name, d_string)			\
565 	USBD_DESC_STRING_DEFINE(d_name, d_string, USBD_DUT_STRING_PRODUCT)
566 
567 /**
568  * @brief Create a string descriptor node and serial number string descriptor
569  *
570  * This macro defines a descriptor node that, when added to the device context,
571  * is automatically used as the serial number string descriptor. A valid serial
572  * number is generated from HWID (HWINFO= whenever this string descriptor is
573  * requested.
574  *
575  * @param d_name   String descriptor node identifier.
576  */
577 #define USBD_DESC_SERIAL_NUMBER_DEFINE(d_name)					\
578 	static struct usbd_desc_node d_name = {					\
579 		.str = {							\
580 			.utype = USBD_DUT_STRING_SERIAL_NUMBER,			\
581 			.ascii7 = true,						\
582 			.use_hwinfo = true,					\
583 		},								\
584 		.bDescriptorType = USB_DESC_STRING,				\
585 	}
586 
587 /**
588  * @brief Create a string descriptor node for configuration descriptor
589  *
590  * This macro defines a descriptor node whose address can be used as an
591  * argument for the USBD_CONFIGURATION_DEFINE() macro.
592  *
593  * @param d_name   String descriptor node identifier.
594  * @param d_string ASCII7 encoded configuration description string literal
595  */
596 #define USBD_DESC_CONFIG_DEFINE(d_name, d_string)			\
597 	USBD_DESC_STRING_DEFINE(d_name, d_string, USBD_DUT_STRING_CONFIG)
598 
599 /**
600  * @brief Define BOS Device Capability descriptor node
601  *
602  * The application defines a BOS capability descriptor node for descriptors
603  * such as USB 2.0 Extension Descriptor.
604  *
605  * @param name       Descriptor node identifier
606  * @param len        Device Capability descriptor length
607  * @param subset     Pointer to a Device Capability descriptor
608  */
609 #define USBD_DESC_BOS_DEFINE(name, len, subset)					\
610 	static struct usbd_desc_node name = {					\
611 		.bos = {							\
612 			.utype = USBD_DUT_BOS_NONE,				\
613 		},								\
614 		.ptr = subset,							\
615 		.bLength = len,							\
616 		.bDescriptorType = USB_DESC_BOS,				\
617 	}
618 
619 /**
620  * @brief Define USB device support class data
621  *
622  * Macro defines class (function) data, as well as corresponding node
623  * structures used internally by the stack.
624  *
625  * @param class_name   Class name
626  * @param class_api    Pointer to struct usbd_class_api
627  * @param class_priv   Class private data
628  * @param class_v_reqs Pointer to struct usbd_cctx_vendor_req
629  */
630 #define USBD_DEFINE_CLASS(class_name, class_api, class_priv, class_v_reqs)	\
631 	static struct usbd_class_data class_name = {				\
632 		.name = STRINGIFY(class_name),					\
633 		.api = class_api,						\
634 		.v_reqs = class_v_reqs,						\
635 		.priv = class_priv,						\
636 	};									\
637 	static STRUCT_SECTION_ITERABLE_ALTERNATE(				\
638 		usbd_class_fs, usbd_class_node, class_name##_fs) = {		\
639 		.c_data = &class_name,						\
640 	};									\
641 	static STRUCT_SECTION_ITERABLE_ALTERNATE(				\
642 		usbd_class_hs, usbd_class_node, class_name##_hs) = {		\
643 		.c_data = &class_name,						\
644 	}
645 
646 /** @brief Helper to declare request table of usbd_cctx_vendor_req
647  *
648  *  @param _reqs Pointer to the vendor request field
649  *  @param _len  Number of supported vendor requests
650  */
651 #define VENDOR_REQ_DEFINE(_reqs, _len) \
652 	{ \
653 		.reqs = (const uint8_t *)(_reqs), \
654 		.len = (_len), \
655 	}
656 
657 /** @brief Helper to declare supported vendor requests
658  *
659  *  @param _reqs Variable number of vendor requests
660  */
661 #define USBD_VENDOR_REQ(_reqs...) \
662 	VENDOR_REQ_DEFINE(((uint8_t []) { _reqs }), \
663 			  sizeof((uint8_t []) { _reqs }))
664 
665 
666 /**
667  * @brief Add common USB descriptor
668  *
669  * Add common descriptor like string or BOS Device Capability.
670  *
671  * @param[in] uds_ctx Pointer to USB device support context
672  * @param[in] dn      Pointer to USB descriptor node
673  *
674  * @return 0 on success, other values on fail.
675  */
676 int usbd_add_descriptor(struct usbd_context *uds_ctx,
677 			struct usbd_desc_node *dn);
678 
679 /**
680  * @brief Get USB string descriptor index from descriptor node
681  *
682  * @param[in] desc_nd Pointer to USB descriptor node
683  *
684  * @return Descriptor index, 0 if descriptor is not part of any device
685  */
686 uint8_t usbd_str_desc_get_idx(const struct usbd_desc_node *const desc_nd);
687 
688 /**
689  * @brief Remove USB string descriptor
690  *
691  * Remove linked USB string descriptor from any list.
692  *
693  * @param[in] desc_nd Pointer to USB descriptor node
694  */
695 void usbd_remove_descriptor(struct usbd_desc_node *const desc_nd);
696 
697 /**
698  * @brief Add a USB device configuration
699  *
700  * @param[in] uds_ctx Pointer to USB device support context
701  * @param[in] speed   Speed at which this configuration operates
702  * @param[in] cd      Pointer to USB configuration node
703  *
704  * @return 0 on success, other values on fail.
705  */
706 int usbd_add_configuration(struct usbd_context *uds_ctx,
707 			   const enum usbd_speed speed,
708 			   struct usbd_config_node *cd);
709 
710 /**
711  * @brief Register an USB class instance
712  *
713  * An USB class implementation can have one or more instances.
714  * To identify the instances we use device drivers API.
715  * Device names have a prefix derived from the name of the class,
716  * for example CDC_ACM for CDC ACM class instance,
717  * and can also be easily identified in the shell.
718  * Class instance can only be registered when the USB device stack
719  * is disabled.
720  * Registered instances are initialized at initialization
721  * of the USB device stack, and the interface descriptors
722  * of each instance are adapted to the whole context.
723  *
724  * @param[in] uds_ctx Pointer to USB device support context
725  * @param[in] name    Class instance name
726  * @param[in] speed   Configuration speed
727  * @param[in] cfg     Configuration value (bConfigurationValue)
728  *
729  * @return 0 on success, other values on fail.
730  */
731 int usbd_register_class(struct usbd_context *uds_ctx,
732 			const char *name,
733 			const enum usbd_speed speed, uint8_t cfg);
734 
735 /**
736  * @brief Register all available USB class instances
737  *
738  * Register all available instances. Like usbd_register_class, but does not
739  * take the instance name and instead registers all available instances.
740  *
741  * @note This cannot be combined. If your application calls
742  * usbd_register_class for any device, configuration number, or instance,
743  * either usbd_register_class or this function will fail.
744  *
745  * @param[in] uds_ctx Pointer to USB device support context
746  * @param[in] speed   Configuration speed
747  * @param[in] cfg     Configuration value (bConfigurationValue)
748  *
749  * @return 0 on success, other values on fail.
750  */
751 int usbd_register_all_classes(struct usbd_context *uds_ctx,
752 			      const enum usbd_speed speed, uint8_t cfg);
753 
754 /**
755  * @brief Unregister an USB class instance
756  *
757  * USB class instance will be removed and will not appear
758  * on the next start of the stack. Instance can only be unregistered
759  * when the USB device stack is disabled.
760  *
761  * @param[in] uds_ctx Pointer to USB device support context
762  * @param[in] name    Class instance name
763  * @param[in] speed   Configuration speed
764  * @param[in] cfg     Configuration value (bConfigurationValue)
765  *
766  * @return 0 on success, other values on fail.
767  */
768 int usbd_unregister_class(struct usbd_context *uds_ctx,
769 			  const char *name,
770 			  const enum usbd_speed speed, uint8_t cfg);
771 
772 /**
773  * @brief Unregister all available USB class instances
774  *
775  * Unregister all available instances. Like usbd_unregister_class, but does not
776  * take the instance name and instead unregisters all available instances.
777  *
778  * @param[in] uds_ctx Pointer to USB device support context
779  * @param[in] speed   Configuration speed
780  * @param[in] cfg     Configuration value (bConfigurationValue)
781  *
782  * @return 0 on success, other values on fail.
783  */
784 int usbd_unregister_all_classes(struct usbd_context *uds_ctx,
785 				const enum usbd_speed speed, uint8_t cfg);
786 
787 /**
788  * @brief Register USB notification message callback
789  *
790  * @param[in] uds_ctx Pointer to USB device support context
791  * @param[in] cb      Pointer to message callback function
792  *
793  * @return 0 on success, other values on fail.
794  */
795 int usbd_msg_register_cb(struct usbd_context *const uds_ctx,
796 			 const usbd_msg_cb_t cb);
797 
798 /**
799  * @brief Initialize USB device
800  *
801  * Initialize USB device descriptors and configuration,
802  * initialize USB device controller.
803  * Class instances should be registered before they are involved.
804  * However, the stack should also initialize without registered instances,
805  * even if the host would complain about missing interfaces.
806  *
807  * @param[in] uds_ctx Pointer to USB device support context
808  *
809  * @return 0 on success, other values on fail.
810  */
811 int usbd_init(struct usbd_context *uds_ctx);
812 
813 /**
814  * @brief Enable the USB device support and registered class instances
815  *
816  * This function enables the USB device support.
817  *
818  * @param[in] uds_ctx Pointer to USB device support context
819  *
820  * @return 0 on success, other values on fail.
821  */
822 int usbd_enable(struct usbd_context *uds_ctx);
823 
824 /**
825  * @brief Disable the USB device support
826  *
827  * This function disables the USB device support.
828  *
829  * @param[in] uds_ctx Pointer to USB device support context
830  *
831  * @return 0 on success, other values on fail.
832  */
833 int usbd_disable(struct usbd_context *uds_ctx);
834 
835 /**
836  * @brief Shutdown the USB device support
837  *
838  * This function completely disables the USB device support.
839  *
840  * @param[in] uds_ctx Pointer to USB device support context
841  *
842  * @return 0 on success, other values on fail.
843  */
844 int usbd_shutdown(struct usbd_context *const uds_ctx);
845 
846 /**
847  * @brief Halt endpoint
848  *
849  * @param[in] uds_ctx Pointer to USB device support context
850  * @param[in] ep      Endpoint address
851  *
852  * @return 0 on success, or error from udc_ep_set_halt()
853  */
854 int usbd_ep_set_halt(struct usbd_context *uds_ctx, uint8_t ep);
855 
856 /**
857  * @brief Clear endpoint halt
858  *
859  * @param[in] uds_ctx Pointer to USB device support context
860  * @param[in] ep      Endpoint address
861  *
862  * @return 0 on success, or error from udc_ep_clear_halt()
863  */
864 int usbd_ep_clear_halt(struct usbd_context *uds_ctx, uint8_t ep);
865 
866 /**
867  * @brief Checks whether the endpoint is halted.
868  *
869  * @param[in] uds_ctx Pointer to USB device support context
870  * @param[in] ep      Endpoint address
871  *
872  * @return true if endpoint is halted, false otherwise
873  */
874 bool usbd_ep_is_halted(struct usbd_context *uds_ctx, uint8_t ep);
875 
876 /**
877  * @brief Allocate buffer for USB device request
878  *
879  * Allocate a new buffer from controller's driver buffer pool.
880  *
881  * @param[in] c_data Pointer to USB device class data
882  * @param[in] ep     Endpoint address
883  * @param[in] size   Size of the request buffer
884  *
885  * @return pointer to allocated request or NULL on error.
886  */
887 struct net_buf *usbd_ep_buf_alloc(const struct usbd_class_data *const c_data,
888 				  const uint8_t ep, const size_t size);
889 
890 /**
891  * @brief Queue USB device control request
892  *
893  * Add control request to the queue.
894  *
895  * @param[in] uds_ctx Pointer to USB device support context
896  * @param[in] buf     Pointer to UDC request buffer
897  *
898  * @return 0 on success, all other values should be treated as error.
899  */
900 int usbd_ep_ctrl_enqueue(struct usbd_context *const uds_ctx,
901 			 struct net_buf *const buf);
902 
903 /**
904  * @brief Queue USB device request
905  *
906  * Add request to the queue.
907  *
908  * @param[in] c_data   Pointer to USB device class data
909  * @param[in] buf    Pointer to UDC request buffer
910  *
911  * @return 0 on success, or error from udc_ep_enqueue()
912  */
913 int usbd_ep_enqueue(const struct usbd_class_data *const c_data,
914 		    struct net_buf *const buf);
915 
916 /**
917  * @brief Remove all USB device controller requests from endpoint queue
918  *
919  * @param[in] uds_ctx Pointer to USB device support context
920  * @param[in] ep      Endpoint address
921  *
922  * @return 0 on success, or error from udc_ep_dequeue()
923  */
924 int usbd_ep_dequeue(struct usbd_context *uds_ctx, const uint8_t ep);
925 
926 /**
927  * @brief Free USB device request buffer
928  *
929  * Put the buffer back into the request buffer pool.
930  *
931  * @param[in] uds_ctx Pointer to USB device support context
932  * @param[in] buf     Pointer to UDC request buffer
933  *
934  * @return 0 on success, all other values should be treated as error.
935  */
936 int usbd_ep_buf_free(struct usbd_context *uds_ctx, struct net_buf *buf);
937 
938 /**
939  * @brief Checks whether the USB device controller is suspended.
940  *
941  * @param[in] uds_ctx Pointer to USB device support context
942  *
943  * @return true if endpoint is halted, false otherwise
944  */
945 bool usbd_is_suspended(struct usbd_context *uds_ctx);
946 
947 /**
948  * @brief Initiate the USB remote wakeup (TBD)
949  *
950  * @return 0 on success, other values on fail.
951  */
952 int usbd_wakeup_request(struct usbd_context *uds_ctx);
953 
954 /**
955  * @brief Get actual device speed
956  *
957  * @param[in] uds_ctx Pointer to a device context
958  *
959  * @return Actual device speed
960  */
961 enum usbd_speed usbd_bus_speed(const struct usbd_context *const uds_ctx);
962 
963 /**
964  * @brief Get highest speed supported by the controller
965  *
966  * @param[in] uds_ctx Pointer to a device context
967  *
968  * @return Highest supported speed
969  */
970 enum usbd_speed usbd_caps_speed(const struct usbd_context *const uds_ctx);
971 
972 /**
973  * @brief Set USB device descriptor value bcdUSB
974  *
975  * @param[in] uds_ctx Pointer to USB device support context
976  * @param[in] speed   Speed for which the bcdUSB should be set
977  * @param[in] bcd     bcdUSB value
978  *
979  * @return 0 on success, other values on fail.
980  */
981 int usbd_device_set_bcd_usb(struct usbd_context *const uds_ctx,
982 			    const enum usbd_speed speed, const uint16_t bcd);
983 
984 /**
985  * @brief Set USB device descriptor value idVendor
986  *
987  * @param[in] uds_ctx Pointer to USB device support context
988  * @param[in] vid     idVendor value
989  *
990  * @return 0 on success, other values on fail.
991  */
992 int usbd_device_set_vid(struct usbd_context *const uds_ctx,
993 			 const uint16_t vid);
994 
995 /**
996  * @brief Set USB device descriptor value idProduct
997  *
998  * @param[in] uds_ctx Pointer to USB device support context
999  * @param[in] pid     idProduct value
1000  *
1001  * @return 0 on success, other values on fail.
1002  */
1003 int usbd_device_set_pid(struct usbd_context *const uds_ctx,
1004 			const uint16_t pid);
1005 
1006 /**
1007  * @brief Set USB device descriptor value bcdDevice
1008  *
1009  * @param[in] uds_ctx Pointer to USB device support context
1010  * @param[in] bcd     bcdDevice value
1011  *
1012  * @return 0 on success, other values on fail.
1013  */
1014 int usbd_device_set_bcd_device(struct usbd_context *const uds_ctx,
1015 			       const uint16_t bcd);
1016 
1017 /**
1018  * @brief Set USB device descriptor code triple Base Class, SubClass, and Protocol
1019  *
1020  * @param[in] uds_ctx    Pointer to USB device support context
1021  * @param[in] speed      Speed for which the code triple should be set
1022  * @param[in] base_class bDeviceClass value
1023  * @param[in] subclass   bDeviceSubClass value
1024  * @param[in] protocol   bDeviceProtocol value
1025  *
1026  * @return 0 on success, other values on fail.
1027  */
1028 int usbd_device_set_code_triple(struct usbd_context *const uds_ctx,
1029 				const enum usbd_speed speed,
1030 				const uint8_t base_class,
1031 				const uint8_t subclass, const uint8_t protocol);
1032 
1033 /**
1034  * @brief Setup USB device configuration attribute Remote Wakeup
1035  *
1036  * @param[in] uds_ctx Pointer to USB device support context
1037  * @param[in] speed   Configuration speed
1038  * @param[in] cfg     Configuration number
1039  * @param[in] enable  Sets attribute if true, clears it otherwise
1040  *
1041  * @return 0 on success, other values on fail.
1042  */
1043 int usbd_config_attrib_rwup(struct usbd_context *const uds_ctx,
1044 			    const enum usbd_speed speed,
1045 			    const uint8_t cfg, const bool enable);
1046 
1047 /**
1048  * @brief Setup USB device configuration attribute Self-powered
1049  *
1050  * @param[in] uds_ctx Pointer to USB device support context
1051  * @param[in] speed   Configuration speed
1052  * @param[in] cfg     Configuration number
1053  * @param[in] enable  Sets attribute if true, clears it otherwise
1054  *
1055  * @return 0 on success, other values on fail.
1056  */
1057 int usbd_config_attrib_self(struct usbd_context *const uds_ctx,
1058 			    const enum usbd_speed speed,
1059 			    const uint8_t cfg, const bool enable);
1060 
1061 /**
1062  * @brief Setup USB device configuration power consumption
1063  *
1064  * @param[in] uds_ctx Pointer to USB device support context
1065  * @param[in] speed   Configuration speed
1066  * @param[in] cfg     Configuration number
1067  * @param[in] power   Maximum power consumption value (bMaxPower)
1068  *
1069  * @return 0 on success, other values on fail.
1070  */
1071 int usbd_config_maxpower(struct usbd_context *const uds_ctx,
1072 			 const enum usbd_speed speed,
1073 			 const uint8_t cfg, const uint8_t power);
1074 
1075 /**
1076  * @brief Check that the controller can detect the VBUS state change.
1077  *
1078  * This can be used in a generic application to explicitly handle the VBUS
1079  * detected event after usbd_init(). For example, to call usbd_enable() after a
1080  * short delay to give the PMIC time to detect the bus, or to handle cases
1081  * where usbd_enable() can only be called after a VBUS detected event.
1082  *
1083  * @param[in] uds_ctx Pointer to USB device support context
1084  *
1085  * @return true if controller can detect VBUS state change, false otherwise
1086  */
1087 bool usbd_can_detect_vbus(struct usbd_context *const uds_ctx);
1088 
1089 /**
1090  * @}
1091  */
1092 
1093 #ifdef __cplusplus
1094 }
1095 #endif
1096 
1097 #endif /* ZEPHYR_INCLUDE_USBD_H_ */
1098