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