1 /*
2  * Copyright (c) 2022 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <errno.h>
8 #include <zephyr/kernel.h>
9 #include <zephyr/usb/usbd.h>
10 #include <zephyr/drivers/usb/udc.h>
11 #include <zephyr/sys/byteorder.h>
12 #include <zephyr/sys/slist.h>
13 #include <zephyr/drivers/hwinfo.h>
14 
15 #include "usbd_device.h"
16 #include "usbd_desc.h"
17 #include "usbd_ch9.h"
18 #include "usbd_config.h"
19 #include "usbd_class.h"
20 #include "usbd_class_api.h"
21 #include "usbd_interface.h"
22 #include "usbd_msg.h"
23 
24 #include <zephyr/logging/log.h>
25 LOG_MODULE_REGISTER(usbd_ch9, CONFIG_USBD_LOG_LEVEL);
26 
27 #define CTRL_AWAIT_SETUP_DATA		0
28 #define CTRL_AWAIT_STATUS_STAGE		1
29 
30 #define SF_TEST_MODE_SELECTOR(wIndex)		((uint8_t)((wIndex) >> 8))
31 #define SF_TEST_LOWER_BYTE(wIndex)		((uint8_t)(wIndex))
32 
33 static int nonstd_request(struct usbd_context *const uds_ctx,
34 			  struct net_buf *const dbuf);
35 
reqtype_is_to_host(const struct usb_setup_packet * const setup)36 static bool reqtype_is_to_host(const struct usb_setup_packet *const setup)
37 {
38 	return setup->wLength && USB_REQTYPE_GET_DIR(setup->bmRequestType);
39 }
40 
reqtype_is_to_device(const struct usb_setup_packet * const setup)41 static bool reqtype_is_to_device(const struct usb_setup_packet *const setup)
42 {
43 	return !reqtype_is_to_host(setup);
44 }
45 
ch9_set_ctrl_type(struct usbd_context * const uds_ctx,const int type)46 static void ch9_set_ctrl_type(struct usbd_context *const uds_ctx,
47 				   const int type)
48 {
49 	uds_ctx->ch9_data.ctrl_type = type;
50 }
51 
ch9_get_ctrl_type(struct usbd_context * const uds_ctx)52 static int ch9_get_ctrl_type(struct usbd_context *const uds_ctx)
53 {
54 	return uds_ctx->ch9_data.ctrl_type;
55 }
56 
post_status_stage(struct usbd_context * const uds_ctx)57 static int post_status_stage(struct usbd_context *const uds_ctx)
58 {
59 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
60 	int ret = 0;
61 
62 	if (setup->bRequest == USB_SREQ_SET_ADDRESS) {
63 		ret = udc_set_address(uds_ctx->dev, setup->wValue);
64 		if (ret) {
65 			LOG_ERR("Failed to set device address 0x%x", setup->wValue);
66 		}
67 	}
68 
69 	if (setup->bRequest == USB_SREQ_SET_FEATURE &&
70 	    setup->wValue == USB_SFS_TEST_MODE) {
71 		uint8_t mode = SF_TEST_MODE_SELECTOR(setup->wIndex);
72 
73 		ret = udc_test_mode(uds_ctx->dev, mode, false);
74 		if (ret) {
75 			LOG_ERR("Failed to enable TEST_MODE %u", mode);
76 		}
77 	}
78 
79 	uds_ctx->ch9_data.post_status = false;
80 
81 	return ret;
82 }
83 
sreq_set_address(struct usbd_context * const uds_ctx)84 static int sreq_set_address(struct usbd_context *const uds_ctx)
85 {
86 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
87 	struct udc_device_caps caps = udc_caps(uds_ctx->dev);
88 
89 	/* Not specified if wIndex or wLength is non-zero, treat as error */
90 	if (setup->wValue > 127 || setup->wIndex || setup->wLength) {
91 		errno = -ENOTSUP;
92 		return 0;
93 	}
94 
95 	if (setup->RequestType.recipient != USB_REQTYPE_RECIPIENT_DEVICE) {
96 		errno = -ENOTSUP;
97 		return 0;
98 	}
99 
100 	if (usbd_state_is_configured(uds_ctx)) {
101 		errno = -EPERM;
102 		return 0;
103 	}
104 
105 	if (caps.addr_before_status) {
106 		int ret;
107 
108 		ret = udc_set_address(uds_ctx->dev, setup->wValue);
109 		if (ret) {
110 			LOG_ERR("Failed to set device address 0x%x", setup->wValue);
111 			return ret;
112 		}
113 	} else {
114 		uds_ctx->ch9_data.post_status = true;
115 	}
116 
117 	if (usbd_state_is_address(uds_ctx) && setup->wValue == 0) {
118 		uds_ctx->ch9_data.state = USBD_STATE_DEFAULT;
119 	} else {
120 		uds_ctx->ch9_data.state = USBD_STATE_ADDRESS;
121 	}
122 
123 
124 	return 0;
125 }
126 
sreq_set_configuration(struct usbd_context * const uds_ctx)127 static int sreq_set_configuration(struct usbd_context *const uds_ctx)
128 {
129 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
130 	const enum usbd_speed speed = usbd_bus_speed(uds_ctx);
131 	int ret;
132 
133 	LOG_INF("Set Configuration Request value %u", setup->wValue);
134 
135 	/* Not specified if wLength is non-zero, treat as error */
136 	if (setup->wValue > UINT8_MAX || setup->wLength) {
137 		errno = -ENOTSUP;
138 		return 0;
139 	}
140 
141 	if (setup->RequestType.recipient != USB_REQTYPE_RECIPIENT_DEVICE) {
142 		errno = -ENOTSUP;
143 		return 0;
144 	}
145 
146 	if (usbd_state_is_default(uds_ctx)) {
147 		errno = -EPERM;
148 		return 0;
149 	}
150 
151 	if (setup->wValue && !usbd_config_exist(uds_ctx, speed, setup->wValue)) {
152 		errno = -EPERM;
153 		return 0;
154 	}
155 
156 	if (setup->wValue == usbd_get_config_value(uds_ctx)) {
157 		LOG_DBG("Already in the configuration %u", setup->wValue);
158 		return 0;
159 	}
160 
161 	ret = usbd_config_set(uds_ctx, setup->wValue);
162 	if (ret) {
163 		LOG_ERR("Failed to set configuration %u, %d",
164 			setup->wValue, ret);
165 		return ret;
166 	}
167 
168 	if (setup->wValue == 0) {
169 		/* Enter address state */
170 		uds_ctx->ch9_data.state = USBD_STATE_ADDRESS;
171 	} else {
172 		uds_ctx->ch9_data.state = USBD_STATE_CONFIGURED;
173 	}
174 
175 	if (ret == 0) {
176 		usbd_msg_pub_simple(uds_ctx, USBD_MSG_CONFIGURATION, setup->wValue);
177 	}
178 
179 	return ret;
180 }
181 
sreq_set_interface(struct usbd_context * const uds_ctx)182 static int sreq_set_interface(struct usbd_context *const uds_ctx)
183 {
184 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
185 	int ret;
186 
187 	if (setup->RequestType.recipient != USB_REQTYPE_RECIPIENT_INTERFACE) {
188 		errno = -ENOTSUP;
189 		return 0;
190 	}
191 
192 	/* Not specified if wLength is non-zero, treat as error */
193 	if (setup->wLength) {
194 		errno = -ENOTSUP;
195 		return 0;
196 	}
197 
198 	if (setup->wValue > UINT8_MAX || setup->wIndex > UINT8_MAX) {
199 		errno = -ENOTSUP;
200 		return 0;
201 	}
202 
203 	if (!usbd_state_is_configured(uds_ctx)) {
204 		errno = -EPERM;
205 		return 0;
206 	}
207 
208 	ret = usbd_interface_set(uds_ctx, setup->wIndex, setup->wValue);
209 	if (ret == -ENOENT) {
210 		LOG_INF("Interface or alternate does not exist");
211 		errno = ret;
212 		ret = 0;
213 	}
214 
215 	return ret;
216 }
217 
sreq_feature_halt_notify(struct usbd_context * const uds_ctx,const uint8_t ep,const bool halted)218 static void sreq_feature_halt_notify(struct usbd_context *const uds_ctx,
219 				     const uint8_t ep, const bool halted)
220 {
221 	struct usbd_class_node *c_nd = usbd_class_get_by_ep(uds_ctx, ep);
222 
223 	if (c_nd != NULL) {
224 		usbd_class_feature_halt(c_nd->c_data, ep, halted);
225 	}
226 }
227 
sreq_clear_feature(struct usbd_context * const uds_ctx)228 static int sreq_clear_feature(struct usbd_context *const uds_ctx)
229 {
230 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
231 	uint8_t ep = setup->wIndex;
232 	int ret = 0;
233 
234 	/* Not specified if wLength is non-zero, treat as error */
235 	if (setup->wLength) {
236 		errno = -ENOTSUP;
237 		return 0;
238 	}
239 
240 	/* Not specified in default state, treat as error */
241 	if (usbd_state_is_default(uds_ctx)) {
242 		errno = -EPERM;
243 		return 0;
244 	}
245 
246 	if (usbd_state_is_address(uds_ctx) && setup->wIndex) {
247 		errno = -EPERM;
248 		return 0;
249 	}
250 
251 	switch (setup->RequestType.recipient) {
252 	case USB_REQTYPE_RECIPIENT_DEVICE:
253 		if (setup->wIndex != 0) {
254 			errno = -EPERM;
255 			return 0;
256 		}
257 
258 		if (setup->wValue == USB_SFS_REMOTE_WAKEUP) {
259 			LOG_DBG("Clear feature remote wakeup");
260 			uds_ctx->status.rwup = false;
261 		}
262 		break;
263 	case USB_REQTYPE_RECIPIENT_ENDPOINT:
264 		if (setup->wValue == USB_SFS_ENDPOINT_HALT) {
265 			/* UDC checks if endpoint is enabled */
266 			errno = usbd_ep_clear_halt(uds_ctx, ep);
267 			ret = (errno == -EPERM) ? errno : 0;
268 			if (ret == 0) {
269 				/* Notify class instance */
270 				sreq_feature_halt_notify(uds_ctx, ep, false);
271 			}
272 			break;
273 		}
274 		break;
275 	case USB_REQTYPE_RECIPIENT_INTERFACE:
276 	default:
277 		break;
278 	}
279 
280 	return ret;
281 }
282 
set_feature_test_mode(struct usbd_context * const uds_ctx)283 static int set_feature_test_mode(struct usbd_context *const uds_ctx)
284 {
285 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
286 	uint8_t mode = SF_TEST_MODE_SELECTOR(setup->wIndex);
287 
288 	if (setup->RequestType.recipient != USB_REQTYPE_RECIPIENT_DEVICE ||
289 	    SF_TEST_LOWER_BYTE(setup->wIndex) != 0) {
290 		errno = -ENOTSUP;
291 		return 0;
292 	}
293 
294 	if (udc_test_mode(uds_ctx->dev, mode, true) != 0) {
295 		errno = -ENOTSUP;
296 		return 0;
297 	}
298 
299 	uds_ctx->ch9_data.post_status = true;
300 
301 	return 0;
302 }
303 
sreq_set_feature(struct usbd_context * const uds_ctx)304 static int sreq_set_feature(struct usbd_context *const uds_ctx)
305 {
306 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
307 	uint8_t ep = setup->wIndex;
308 	int ret = 0;
309 
310 	/* Not specified if wLength is non-zero, treat as error */
311 	if (setup->wLength) {
312 		errno = -ENOTSUP;
313 		return 0;
314 	}
315 
316 	if (unlikely(setup->wValue == USB_SFS_TEST_MODE)) {
317 		return set_feature_test_mode(uds_ctx);
318 	}
319 
320 	/*
321 	 * Other request behavior is not specified in the default state, treat
322 	 * as an error.
323 	 */
324 	if (usbd_state_is_default(uds_ctx)) {
325 		errno = -EPERM;
326 		return 0;
327 	}
328 
329 	if (usbd_state_is_address(uds_ctx) && setup->wIndex) {
330 		errno = -EPERM;
331 		return 0;
332 	}
333 
334 	switch (setup->RequestType.recipient) {
335 	case USB_REQTYPE_RECIPIENT_DEVICE:
336 		if (setup->wIndex != 0) {
337 			errno = -EPERM;
338 			return 0;
339 		}
340 
341 		if (setup->wValue == USB_SFS_REMOTE_WAKEUP) {
342 			LOG_DBG("Set feature remote wakeup");
343 			uds_ctx->status.rwup = true;
344 		}
345 		break;
346 	case USB_REQTYPE_RECIPIENT_ENDPOINT:
347 		if (setup->wValue == USB_SFS_ENDPOINT_HALT) {
348 			/* UDC checks if endpoint is enabled */
349 			errno = usbd_ep_set_halt(uds_ctx, ep);
350 			ret = (errno == -EPERM) ? errno : 0;
351 			if (ret == 0) {
352 				/* Notify class instance */
353 				sreq_feature_halt_notify(uds_ctx, ep, true);
354 			}
355 			break;
356 		}
357 		break;
358 	case USB_REQTYPE_RECIPIENT_INTERFACE:
359 	default:
360 		break;
361 	}
362 
363 	return ret;
364 }
365 
std_request_to_device(struct usbd_context * const uds_ctx,struct net_buf * const buf)366 static int std_request_to_device(struct usbd_context *const uds_ctx,
367 				 struct net_buf *const buf)
368 {
369 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
370 	int ret;
371 
372 	switch (setup->bRequest) {
373 	case USB_SREQ_SET_ADDRESS:
374 		ret = sreq_set_address(uds_ctx);
375 		break;
376 	case USB_SREQ_SET_CONFIGURATION:
377 		ret = sreq_set_configuration(uds_ctx);
378 		break;
379 	case USB_SREQ_SET_INTERFACE:
380 		ret = sreq_set_interface(uds_ctx);
381 		break;
382 	case USB_SREQ_CLEAR_FEATURE:
383 		ret = sreq_clear_feature(uds_ctx);
384 		break;
385 	case USB_SREQ_SET_FEATURE:
386 		ret = sreq_set_feature(uds_ctx);
387 		break;
388 	default:
389 		errno = -ENOTSUP;
390 		ret = 0;
391 		break;
392 	}
393 
394 	return ret;
395 }
396 
sreq_get_status(struct usbd_context * const uds_ctx,struct net_buf * const buf)397 static int sreq_get_status(struct usbd_context *const uds_ctx,
398 			   struct net_buf *const buf)
399 {
400 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
401 	uint8_t ep = setup->wIndex;
402 	uint16_t response = 0;
403 
404 	if (setup->wLength != sizeof(response)) {
405 		errno = -ENOTSUP;
406 		return 0;
407 	}
408 
409 	/* Not specified in default state, treat as error */
410 	if (usbd_state_is_default(uds_ctx)) {
411 		errno = -EPERM;
412 		return 0;
413 	}
414 
415 	if (usbd_state_is_address(uds_ctx) && setup->wIndex) {
416 		errno = -EPERM;
417 		return 0;
418 	}
419 
420 	switch (setup->RequestType.recipient) {
421 	case USB_REQTYPE_RECIPIENT_DEVICE:
422 		if (setup->wIndex != 0) {
423 			errno = -EPERM;
424 			return 0;
425 		}
426 
427 		response = uds_ctx->status.rwup ?
428 			   USB_GET_STATUS_REMOTE_WAKEUP : 0;
429 		break;
430 	case USB_REQTYPE_RECIPIENT_ENDPOINT:
431 		response = usbd_ep_is_halted(uds_ctx, ep) ? BIT(0) : 0;
432 		break;
433 	case USB_REQTYPE_RECIPIENT_INTERFACE:
434 		/* Response is always reset to zero.
435 		 * TODO: add check if interface exist?
436 		 */
437 		break;
438 	default:
439 		break;
440 	}
441 
442 	if (net_buf_tailroom(buf) < setup->wLength) {
443 		errno = -ENOMEM;
444 		return 0;
445 	}
446 
447 	LOG_DBG("Get Status response 0x%04x", response);
448 	net_buf_add_le16(buf, response);
449 
450 	return 0;
451 }
452 
453 /*
454  * This function handles configuration and USB2.0 other-speed-configuration
455  * descriptor type requests.
456  */
sreq_get_desc_cfg(struct usbd_context * const uds_ctx,struct net_buf * const buf,const uint8_t idx,const bool other_cfg)457 static int sreq_get_desc_cfg(struct usbd_context *const uds_ctx,
458 			     struct net_buf *const buf,
459 			     const uint8_t idx,
460 			     const bool other_cfg)
461 {
462 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
463 	enum usbd_speed speed = usbd_bus_speed(uds_ctx);
464 	struct usb_cfg_descriptor other_desc;
465 	struct usb_cfg_descriptor *cfg_desc;
466 	struct usbd_config_node *cfg_nd;
467 	enum usbd_speed get_desc_speed;
468 	struct usbd_class_node *c_nd;
469 	uint16_t len;
470 
471 	/*
472 	 * If the other-speed-configuration-descriptor is requested and the
473 	 * controller does not support high speed, respond with an error.
474 	 */
475 	if (other_cfg && usbd_caps_speed(uds_ctx) != USBD_SPEED_HS) {
476 		errno = -ENOTSUP;
477 		return 0;
478 	}
479 
480 	if (other_cfg) {
481 		if (speed == USBD_SPEED_FS) {
482 			get_desc_speed = USBD_SPEED_HS;
483 		} else {
484 			get_desc_speed = USBD_SPEED_FS;
485 		}
486 	} else {
487 		get_desc_speed = speed;
488 	}
489 
490 	cfg_nd = usbd_config_get(uds_ctx, get_desc_speed, idx + 1);
491 	if (cfg_nd == NULL) {
492 		LOG_ERR("Configuration descriptor %u not found", idx + 1);
493 		errno = -ENOTSUP;
494 		return 0;
495 	}
496 
497 	if (other_cfg) {
498 		/* Copy the configuration descriptor and update the type */
499 		memcpy(&other_desc, cfg_nd->desc, sizeof(other_desc));
500 		other_desc.bDescriptorType = USB_DESC_OTHER_SPEED;
501 		cfg_desc = &other_desc;
502 	} else {
503 		cfg_desc = cfg_nd->desc;
504 	}
505 
506 	net_buf_add_mem(buf, cfg_desc, MIN(net_buf_tailroom(buf), cfg_desc->bLength));
507 
508 	SYS_SLIST_FOR_EACH_CONTAINER(&cfg_nd->class_list, c_nd, node) {
509 		struct usb_desc_header **dhp;
510 
511 		dhp = usbd_class_get_desc(c_nd->c_data, get_desc_speed);
512 		if (dhp == NULL) {
513 			continue;
514 		}
515 
516 		while (*dhp != NULL && (*dhp)->bLength != 0) {
517 			len = MIN(net_buf_tailroom(buf), (*dhp)->bLength);
518 			net_buf_add_mem(buf, *dhp, len);
519 			dhp++;
520 		}
521 	}
522 
523 	if (buf->len > setup->wLength) {
524 		net_buf_remove_mem(buf, buf->len - setup->wLength);
525 	}
526 
527 	LOG_DBG("Get Configuration descriptor %u, len %u", idx, buf->len);
528 
529 	return 0;
530 }
531 
532 #define USBD_HWID_SN_MAX 32U
533 
534 /* Generate valid USB device serial number from hwid */
get_sn_from_hwid(uint8_t sn[static USBD_HWID_SN_MAX])535 static ssize_t get_sn_from_hwid(uint8_t sn[static USBD_HWID_SN_MAX])
536 {
537 	static const char hex[] = "0123456789ABCDEF";
538 	uint8_t hwid[USBD_HWID_SN_MAX / 2U];
539 	ssize_t hwid_len = -ENOSYS;
540 
541 	if (IS_ENABLED(CONFIG_HWINFO)) {
542 		hwid_len = hwinfo_get_device_id(hwid, sizeof(hwid));
543 	}
544 
545 	if (hwid_len < 0) {
546 		if (hwid_len == -ENOSYS) {
547 			LOG_ERR("HWINFO not implemented or enabled");
548 		}
549 
550 		return hwid_len;
551 	}
552 
553 	for (ssize_t i = 0; i < hwid_len; i++) {
554 		sn[i * 2] = hex[hwid[i] >> 4];
555 		sn[i * 2 + 1] = hex[hwid[i] & 0xF];
556 	}
557 
558 	return hwid_len * 2;
559 }
560 
561 /* Copy and convert ASCII-7 string descriptor to UTF16-LE */
string_ascii7_to_utf16le(struct usbd_desc_node * const dn,struct net_buf * const buf,const uint16_t wLength)562 static void string_ascii7_to_utf16le(struct usbd_desc_node *const dn,
563 				     struct net_buf *const buf, const uint16_t wLength)
564 {
565 	uint8_t hwid_sn[USBD_HWID_SN_MAX];
566 	struct usb_desc_header head = {
567 		.bDescriptorType = dn->bDescriptorType,
568 	};
569 	uint8_t *ascii7_str;
570 	size_t len;
571 	size_t i;
572 
573 	if (dn->str.utype == USBD_DUT_STRING_SERIAL_NUMBER && dn->str.use_hwinfo) {
574 		ssize_t hwid_len = get_sn_from_hwid(hwid_sn);
575 
576 		if (hwid_len < 0) {
577 			errno = -ENOTSUP;
578 			return;
579 		}
580 
581 		head.bLength = sizeof(head) + hwid_len * 2;
582 		ascii7_str = hwid_sn;
583 	} else {
584 		head.bLength = dn->bLength;
585 		ascii7_str = (uint8_t *)dn->ptr;
586 	}
587 
588 	LOG_DBG("wLength %u, bLength %u, tailroom %u",
589 		wLength, head.bLength, net_buf_tailroom(buf));
590 
591 	len = MIN(net_buf_tailroom(buf), MIN(head.bLength,  wLength));
592 
593 	/* Add bLength and bDescriptorType */
594 	net_buf_add_mem(buf, &head, MIN(len, sizeof(head)));
595 	len -= MIN(len, sizeof(head));
596 
597 	for (i = 0; i < len / 2; i++) {
598 		__ASSERT(ascii7_str[i] > 0x1F && ascii7_str[i] < 0x7F,
599 			 "Only printable ascii-7 characters are allowed in USB "
600 			 "string descriptors");
601 		net_buf_add_le16(buf, ascii7_str[i]);
602 	}
603 
604 	if (len & 1) {
605 		net_buf_add_u8(buf, ascii7_str[i]);
606 	}
607 }
608 
sreq_get_desc_dev(struct usbd_context * const uds_ctx,struct net_buf * const buf)609 static int sreq_get_desc_dev(struct usbd_context *const uds_ctx,
610 			     struct net_buf *const buf)
611 {
612 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
613 	struct usb_desc_header *head;
614 	size_t len;
615 
616 	len = MIN(setup->wLength, net_buf_tailroom(buf));
617 
618 	switch (usbd_bus_speed(uds_ctx)) {
619 	case USBD_SPEED_FS:
620 		head = uds_ctx->fs_desc;
621 		break;
622 	case USBD_SPEED_HS:
623 		head = uds_ctx->hs_desc;
624 		break;
625 	default:
626 		errno = -ENOTSUP;
627 		return 0;
628 	}
629 
630 	net_buf_add_mem(buf, head, MIN(len, head->bLength));
631 
632 	return 0;
633 }
634 
sreq_get_desc_str(struct usbd_context * const uds_ctx,struct net_buf * const buf,const uint8_t idx)635 static int sreq_get_desc_str(struct usbd_context *const uds_ctx,
636 			     struct net_buf *const buf, const uint8_t idx)
637 {
638 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
639 	struct usbd_desc_node *d_nd;
640 	size_t len;
641 
642 	/* Get string descriptor */
643 	d_nd = usbd_get_descriptor(uds_ctx, USB_DESC_STRING, idx);
644 	if (d_nd == NULL) {
645 		errno = -ENOTSUP;
646 		return 0;
647 	}
648 
649 	if (usbd_str_desc_get_idx(d_nd) == 0U) {
650 		/* Language ID string descriptor */
651 		struct usb_string_descriptor langid = {
652 			.bLength = d_nd->bLength,
653 			.bDescriptorType = d_nd->bDescriptorType,
654 			.bString =  *(uint16_t *)d_nd->ptr,
655 		};
656 
657 		len = MIN(setup->wLength, net_buf_tailroom(buf));
658 		net_buf_add_mem(buf, &langid, MIN(len, langid.bLength));
659 	} else {
660 		/* String descriptors in ASCII7 format */
661 		string_ascii7_to_utf16le(d_nd, buf, setup->wLength);
662 	}
663 
664 	return 0;
665 }
666 
sreq_get_dev_qualifier(struct usbd_context * const uds_ctx,struct net_buf * const buf)667 static int sreq_get_dev_qualifier(struct usbd_context *const uds_ctx,
668 				  struct net_buf *const buf)
669 {
670 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
671 	/* At Full-Speed we want High-Speed descriptor and vice versa */
672 	struct usb_device_descriptor *d_desc =
673 		usbd_bus_speed(uds_ctx) == USBD_SPEED_FS ?
674 		uds_ctx->hs_desc : uds_ctx->fs_desc;
675 	struct usb_device_qualifier_descriptor q_desc = {
676 		.bLength = sizeof(struct usb_device_qualifier_descriptor),
677 		.bDescriptorType = USB_DESC_DEVICE_QUALIFIER,
678 		.bcdUSB = d_desc->bcdUSB,
679 		.bDeviceClass = d_desc->bDeviceClass,
680 		.bDeviceSubClass = d_desc->bDeviceSubClass,
681 		.bDeviceProtocol = d_desc->bDeviceProtocol,
682 		.bMaxPacketSize0 = d_desc->bMaxPacketSize0,
683 		.bNumConfigurations = d_desc->bNumConfigurations,
684 		.bReserved = 0U,
685 	};
686 	size_t len;
687 
688 	/*
689 	 * If the Device Qualifier descriptor is requested and the controller
690 	 * does not support high speed, respond with an error.
691 	 */
692 	if (usbd_caps_speed(uds_ctx) != USBD_SPEED_HS) {
693 		errno = -ENOTSUP;
694 		return 0;
695 	}
696 
697 	LOG_DBG("Get Device Qualifier");
698 	len = MIN(setup->wLength, net_buf_tailroom(buf));
699 	net_buf_add_mem(buf, &q_desc, MIN(len, q_desc.bLength));
700 
701 	return 0;
702 }
703 
desc_fill_bos_root(struct usbd_context * const uds_ctx,struct usb_bos_descriptor * const root)704 static void desc_fill_bos_root(struct usbd_context *const uds_ctx,
705 			       struct usb_bos_descriptor *const root)
706 {
707 	struct usbd_desc_node *desc_nd;
708 
709 	root->bLength = sizeof(struct usb_bos_descriptor);
710 	root->bDescriptorType = USB_DESC_BOS;
711 	root->wTotalLength = root->bLength;
712 	root->bNumDeviceCaps = 0;
713 
714 	SYS_DLIST_FOR_EACH_CONTAINER(&uds_ctx->descriptors, desc_nd, node) {
715 		if (desc_nd->bDescriptorType == USB_DESC_BOS) {
716 			root->wTotalLength += desc_nd->bLength;
717 			root->bNumDeviceCaps++;
718 		}
719 	}
720 }
721 
sreq_get_desc_bos(struct usbd_context * const uds_ctx,struct net_buf * const buf)722 static int sreq_get_desc_bos(struct usbd_context *const uds_ctx,
723 			     struct net_buf *const buf)
724 {
725 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
726 	struct usb_device_descriptor *dev_dsc;
727 	struct usb_bos_descriptor bos;
728 	struct usbd_desc_node *desc_nd;
729 	size_t len;
730 
731 	switch (usbd_bus_speed(uds_ctx)) {
732 	case USBD_SPEED_FS:
733 		dev_dsc = uds_ctx->fs_desc;
734 		break;
735 	case USBD_SPEED_HS:
736 		dev_dsc = uds_ctx->hs_desc;
737 		break;
738 	default:
739 		errno = -ENOTSUP;
740 		return 0;
741 	}
742 
743 	if (sys_le16_to_cpu(dev_dsc->bcdUSB) < 0x0201U) {
744 		errno = -ENOTSUP;
745 		return 0;
746 	}
747 
748 	desc_fill_bos_root(uds_ctx, &bos);
749 	len = MIN(net_buf_tailroom(buf), MIN(setup->wLength, bos.wTotalLength));
750 
751 	LOG_DBG("wLength %u, bLength %u, wTotalLength %u, tailroom %u",
752 		setup->wLength, bos.bLength, bos.wTotalLength, net_buf_tailroom(buf));
753 
754 	net_buf_add_mem(buf, &bos, MIN(len, bos.bLength));
755 
756 	len -= MIN(len, sizeof(bos));
757 	if (len == 0) {
758 		return 0;
759 	}
760 
761 	SYS_DLIST_FOR_EACH_CONTAINER(&uds_ctx->descriptors, desc_nd, node) {
762 		if (desc_nd->bDescriptorType == USB_DESC_BOS) {
763 			LOG_DBG("bLength %u, len %u, tailroom %u",
764 				desc_nd->bLength, len, net_buf_tailroom(buf));
765 			net_buf_add_mem(buf, desc_nd->ptr, MIN(len, desc_nd->bLength));
766 
767 			len -= MIN(len, desc_nd->bLength);
768 			if (len == 0) {
769 				break;
770 			}
771 		}
772 	}
773 
774 	return 0;
775 }
776 
sreq_get_descriptor(struct usbd_context * const uds_ctx,struct net_buf * const buf)777 static int sreq_get_descriptor(struct usbd_context *const uds_ctx,
778 			       struct net_buf *const buf)
779 {
780 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
781 	uint8_t desc_type = USB_GET_DESCRIPTOR_TYPE(setup->wValue);
782 	uint8_t desc_idx = USB_GET_DESCRIPTOR_INDEX(setup->wValue);
783 
784 	LOG_DBG("Get Descriptor request type %u index %u",
785 		desc_type, desc_idx);
786 
787 	if (setup->RequestType.recipient != USB_REQTYPE_RECIPIENT_DEVICE) {
788 		/*
789 		 * If the recipient is not the device then it is probably a
790 		 * class specific  request where wIndex is the interface
791 		 * number or endpoint and not the language ID. e.g. HID
792 		 * Class Get Descriptor request.
793 		 */
794 		return nonstd_request(uds_ctx, buf);
795 	}
796 
797 	switch (desc_type) {
798 	case USB_DESC_DEVICE:
799 		return sreq_get_desc_dev(uds_ctx, buf);
800 	case USB_DESC_CONFIGURATION:
801 		return sreq_get_desc_cfg(uds_ctx, buf, desc_idx, false);
802 	case USB_DESC_OTHER_SPEED:
803 		return sreq_get_desc_cfg(uds_ctx, buf, desc_idx, true);
804 	case USB_DESC_STRING:
805 		return sreq_get_desc_str(uds_ctx, buf, desc_idx);
806 	case USB_DESC_DEVICE_QUALIFIER:
807 		return sreq_get_dev_qualifier(uds_ctx, buf);
808 	case USB_DESC_BOS:
809 		return sreq_get_desc_bos(uds_ctx, buf);
810 	case USB_DESC_INTERFACE:
811 	case USB_DESC_ENDPOINT:
812 	default:
813 		break;
814 	}
815 
816 	errno = -ENOTSUP;
817 	return 0;
818 }
819 
sreq_get_configuration(struct usbd_context * const uds_ctx,struct net_buf * const buf)820 static int sreq_get_configuration(struct usbd_context *const uds_ctx,
821 				  struct net_buf *const buf)
822 
823 {
824 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
825 	uint8_t cfg = usbd_get_config_value(uds_ctx);
826 
827 	/* Not specified in default state, treat as error */
828 	if (usbd_state_is_default(uds_ctx)) {
829 		errno = -EPERM;
830 		return 0;
831 	}
832 
833 	if (setup->wLength != sizeof(cfg)) {
834 		errno = -ENOTSUP;
835 		return 0;
836 	}
837 
838 	if (net_buf_tailroom(buf) < setup->wLength) {
839 		errno = -ENOMEM;
840 		return 0;
841 	}
842 
843 	net_buf_add_u8(buf, cfg);
844 
845 	return 0;
846 }
847 
sreq_get_interface(struct usbd_context * const uds_ctx,struct net_buf * const buf)848 static int sreq_get_interface(struct usbd_context *const uds_ctx,
849 			      struct net_buf *const buf)
850 {
851 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
852 	struct usb_cfg_descriptor *cfg_desc;
853 	struct usbd_config_node *cfg_nd;
854 	uint8_t cur_alt;
855 
856 	if (setup->RequestType.recipient != USB_REQTYPE_RECIPIENT_INTERFACE) {
857 		errno = -EPERM;
858 		return 0;
859 	}
860 
861 	/* Treat as error in default (not specified) and addressed states. */
862 	cfg_nd = usbd_config_get_current(uds_ctx);
863 	if (cfg_nd == NULL) {
864 		errno = -EPERM;
865 		return 0;
866 	}
867 
868 	cfg_desc = cfg_nd->desc;
869 
870 	if (setup->wIndex > UINT8_MAX ||
871 	    setup->wIndex > cfg_desc->bNumInterfaces) {
872 		errno = -ENOTSUP;
873 		return 0;
874 	}
875 
876 	if (usbd_get_alt_value(uds_ctx, setup->wIndex, &cur_alt)) {
877 		errno = -ENOTSUP;
878 		return 0;
879 	}
880 
881 	LOG_DBG("Get Interfaces %u, alternate %u",
882 		setup->wIndex, cur_alt);
883 
884 	if (setup->wLength != sizeof(cur_alt)) {
885 		errno = -ENOTSUP;
886 		return 0;
887 	}
888 
889 	if (net_buf_tailroom(buf) < setup->wLength) {
890 		errno = -ENOMEM;
891 		return 0;
892 	}
893 
894 	net_buf_add_u8(buf, cur_alt);
895 
896 	return 0;
897 }
898 
std_request_to_host(struct usbd_context * const uds_ctx,struct net_buf * const buf)899 static int std_request_to_host(struct usbd_context *const uds_ctx,
900 			       struct net_buf *const buf)
901 {
902 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
903 	int ret;
904 
905 	switch (setup->bRequest) {
906 	case USB_SREQ_GET_STATUS:
907 		ret = sreq_get_status(uds_ctx, buf);
908 		break;
909 	case USB_SREQ_GET_DESCRIPTOR:
910 		ret = sreq_get_descriptor(uds_ctx, buf);
911 		break;
912 	case USB_SREQ_GET_CONFIGURATION:
913 		ret = sreq_get_configuration(uds_ctx, buf);
914 		break;
915 	case USB_SREQ_GET_INTERFACE:
916 		ret = sreq_get_interface(uds_ctx, buf);
917 		break;
918 	default:
919 		errno = -ENOTSUP;
920 		ret = 0;
921 		break;
922 	}
923 
924 	return ret;
925 }
926 
vendor_device_request(struct usbd_context * const uds_ctx,struct net_buf * const buf)927 static int vendor_device_request(struct usbd_context *const uds_ctx,
928 				 struct net_buf *const buf)
929 {
930 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
931 	struct usbd_vreq_node *vreq_nd;
932 
933 	vreq_nd = usbd_device_get_vreq(uds_ctx, setup->bRequest);
934 	if (vreq_nd == NULL) {
935 		errno = -ENOTSUP;
936 		return 0;
937 	}
938 
939 	if (reqtype_is_to_device(setup) && vreq_nd->to_dev != NULL) {
940 		LOG_DBG("Vendor request 0x%02x to device", setup->bRequest);
941 		errno = vreq_nd->to_dev(uds_ctx, setup, buf);
942 		return 0;
943 	}
944 
945 	if (reqtype_is_to_host(setup) && vreq_nd->to_host != NULL) {
946 		LOG_DBG("Vendor request 0x%02x to host", setup->bRequest);
947 		errno = vreq_nd->to_host(uds_ctx, setup, buf);
948 		return 0;
949 	}
950 
951 	errno = -ENOTSUP;
952 	return 0;
953 }
954 
nonstd_request(struct usbd_context * const uds_ctx,struct net_buf * const dbuf)955 static int nonstd_request(struct usbd_context *const uds_ctx,
956 			  struct net_buf *const dbuf)
957 {
958 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
959 	struct usbd_class_node *c_nd = NULL;
960 	int ret = 0;
961 
962 	switch (setup->RequestType.recipient) {
963 	case USB_REQTYPE_RECIPIENT_ENDPOINT:
964 		c_nd = usbd_class_get_by_ep(uds_ctx, setup->wIndex);
965 		break;
966 	case USB_REQTYPE_RECIPIENT_INTERFACE:
967 		c_nd = usbd_class_get_by_iface(uds_ctx, setup->wIndex);
968 		break;
969 	case USB_REQTYPE_RECIPIENT_DEVICE:
970 		c_nd = usbd_class_get_by_req(uds_ctx, setup->bRequest);
971 		break;
972 	default:
973 		break;
974 	}
975 
976 	if (c_nd != NULL) {
977 		if (reqtype_is_to_device(setup)) {
978 			ret = usbd_class_control_to_dev(c_nd->c_data, setup, dbuf);
979 		} else {
980 			ret = usbd_class_control_to_host(c_nd->c_data, setup, dbuf);
981 		}
982 	} else {
983 		return vendor_device_request(uds_ctx, dbuf);
984 	}
985 
986 	return ret;
987 }
988 
handle_setup_request(struct usbd_context * const uds_ctx,struct net_buf * const buf)989 static int handle_setup_request(struct usbd_context *const uds_ctx,
990 				struct net_buf *const buf)
991 {
992 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
993 	int ret;
994 
995 	errno = 0;
996 
997 	switch (setup->RequestType.type) {
998 	case USB_REQTYPE_TYPE_STANDARD:
999 		if (reqtype_is_to_device(setup)) {
1000 			ret = std_request_to_device(uds_ctx, buf);
1001 		} else {
1002 			ret = std_request_to_host(uds_ctx, buf);
1003 		}
1004 		break;
1005 	case USB_REQTYPE_TYPE_CLASS:
1006 	case USB_REQTYPE_TYPE_VENDOR:
1007 		ret = nonstd_request(uds_ctx, buf);
1008 		break;
1009 	default:
1010 		errno = -ENOTSUP;
1011 		ret = 0;
1012 	}
1013 
1014 	if (errno) {
1015 		LOG_INF("protocol error:");
1016 		LOG_HEXDUMP_INF(setup, sizeof(*setup), "setup:");
1017 		if (errno == -ENOTSUP) {
1018 			LOG_INF("not supported");
1019 		}
1020 		if (errno == -EPERM) {
1021 			LOG_INF("not permitted in device state %u",
1022 				uds_ctx->ch9_data.state);
1023 		}
1024 	}
1025 
1026 	return ret;
1027 }
1028 
ctrl_xfer_get_setup(struct usbd_context * const uds_ctx,struct net_buf * const buf)1029 static int ctrl_xfer_get_setup(struct usbd_context *const uds_ctx,
1030 			       struct net_buf *const buf)
1031 {
1032 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
1033 	struct net_buf *buf_b;
1034 	struct udc_buf_info *bi, *bi_b;
1035 
1036 	if (buf->len < sizeof(struct usb_setup_packet)) {
1037 		return -EINVAL;
1038 	}
1039 
1040 	memcpy(setup, buf->data, sizeof(struct usb_setup_packet));
1041 
1042 	setup->wValue = sys_le16_to_cpu(setup->wValue);
1043 	setup->wIndex = sys_le16_to_cpu(setup->wIndex);
1044 	setup->wLength = sys_le16_to_cpu(setup->wLength);
1045 
1046 	bi = udc_get_buf_info(buf);
1047 
1048 	buf_b = buf->frags;
1049 	if (buf_b == NULL) {
1050 		LOG_ERR("Buffer for data|status is missing");
1051 		return -ENODATA;
1052 	}
1053 
1054 	bi_b = udc_get_buf_info(buf_b);
1055 
1056 	if (reqtype_is_to_device(setup)) {
1057 		if (setup->wLength) {
1058 			if (!bi_b->data) {
1059 				LOG_ERR("%p is not data", buf_b);
1060 				return -EINVAL;
1061 			}
1062 		} else {
1063 			if (!bi_b->status) {
1064 				LOG_ERR("%p is not status", buf_b);
1065 				return -EINVAL;
1066 			}
1067 		}
1068 	} else {
1069 		if (!setup->wLength) {
1070 			LOG_ERR("device-to-host with wLength zero");
1071 			return -ENOTSUP;
1072 		}
1073 
1074 		if (!bi_b->data) {
1075 			LOG_ERR("%p is not data", buf_b);
1076 			return -EINVAL;
1077 		}
1078 
1079 	}
1080 
1081 	return 0;
1082 }
1083 
spool_data_out(struct net_buf * const buf)1084 static struct net_buf *spool_data_out(struct net_buf *const buf)
1085 {
1086 	struct net_buf *next_buf = buf;
1087 	struct udc_buf_info *bi;
1088 
1089 	while (next_buf) {
1090 		LOG_INF("spool %p", next_buf);
1091 		next_buf = net_buf_frag_del(NULL, next_buf);
1092 		if (next_buf) {
1093 			bi = udc_get_buf_info(next_buf);
1094 			if (bi->status) {
1095 				return next_buf;
1096 			}
1097 		}
1098 	}
1099 
1100 	return NULL;
1101 }
1102 
usbd_handle_ctrl_xfer(struct usbd_context * const uds_ctx,struct net_buf * const buf,const int err)1103 int usbd_handle_ctrl_xfer(struct usbd_context *const uds_ctx,
1104 			  struct net_buf *const buf, const int err)
1105 {
1106 	struct usb_setup_packet *setup = usbd_get_setup_pkt(uds_ctx);
1107 	struct udc_buf_info *bi;
1108 	int ret = 0;
1109 
1110 	bi = udc_get_buf_info(buf);
1111 	if (USB_EP_GET_IDX(bi->ep)) {
1112 		LOG_ERR("Can only handle control requests");
1113 		return -EIO;
1114 	}
1115 
1116 	if (err && err != -ENOMEM && !bi->setup) {
1117 		if (err == -ECONNABORTED) {
1118 			LOG_INF("Transfer 0x%02x aborted (bus reset?)", bi->ep);
1119 			net_buf_unref(buf);
1120 			return 0;
1121 		}
1122 
1123 		LOG_ERR("Control transfer for 0x%02x has error %d, halt",
1124 			bi->ep, err);
1125 		net_buf_unref(buf);
1126 		return err;
1127 	}
1128 
1129 	LOG_INF("Handle control %p ep 0x%02x, len %u, s:%u d:%u s:%u",
1130 		buf, bi->ep, buf->len, bi->setup, bi->data, bi->status);
1131 
1132 	if (bi->setup && bi->ep == USB_CONTROL_EP_OUT) {
1133 		struct net_buf *next_buf;
1134 
1135 		if (ctrl_xfer_get_setup(uds_ctx, buf)) {
1136 			LOG_ERR("Malformed setup packet");
1137 			net_buf_unref(buf);
1138 			goto ctrl_xfer_stall;
1139 		}
1140 
1141 		/* Remove setup packet buffer from the chain */
1142 		next_buf = net_buf_frag_del(NULL, buf);
1143 		if (next_buf == NULL) {
1144 			LOG_ERR("Buffer for data|status is missing");
1145 			goto ctrl_xfer_stall;
1146 		}
1147 
1148 		/*
1149 		 * Handle request and data stage, next_buf is either
1150 		 * data+status or status buffers.
1151 		 */
1152 		ret = handle_setup_request(uds_ctx, next_buf);
1153 		if (ret) {
1154 			net_buf_unref(next_buf);
1155 			return ret;
1156 		}
1157 
1158 		if (errno) {
1159 			/*
1160 			 * Halt, only protocol errors are recoverable.
1161 			 * Free data stage and linked status stage buffer.
1162 			 */
1163 			net_buf_unref(next_buf);
1164 			goto ctrl_xfer_stall;
1165 		}
1166 
1167 		ch9_set_ctrl_type(uds_ctx, CTRL_AWAIT_STATUS_STAGE);
1168 		if (reqtype_is_to_device(setup) && setup->wLength) {
1169 			/* Enqueue STATUS (IN) buffer */
1170 			next_buf = spool_data_out(next_buf);
1171 			if (next_buf == NULL) {
1172 				LOG_ERR("Buffer for status is missing");
1173 				goto ctrl_xfer_stall;
1174 			}
1175 
1176 			ret = usbd_ep_ctrl_enqueue(uds_ctx, next_buf);
1177 		} else {
1178 			/* Enqueue DATA (IN) or STATUS (OUT) buffer */
1179 			ret = usbd_ep_ctrl_enqueue(uds_ctx, next_buf);
1180 		}
1181 
1182 		return ret;
1183 	}
1184 
1185 	if (bi->status && bi->ep == USB_CONTROL_EP_OUT) {
1186 		if (ch9_get_ctrl_type(uds_ctx) == CTRL_AWAIT_STATUS_STAGE) {
1187 			LOG_INF("s-in-status finished");
1188 		} else {
1189 			LOG_WRN("Awaited s-in-status not finished");
1190 		}
1191 
1192 		net_buf_unref(buf);
1193 
1194 		return 0;
1195 	}
1196 
1197 	if (bi->status && bi->ep == USB_CONTROL_EP_IN) {
1198 		net_buf_unref(buf);
1199 
1200 		if (ch9_get_ctrl_type(uds_ctx) == CTRL_AWAIT_STATUS_STAGE) {
1201 			LOG_INF("s-(out)-status finished");
1202 			if (unlikely(uds_ctx->ch9_data.post_status)) {
1203 				ret = post_status_stage(uds_ctx);
1204 			}
1205 		} else {
1206 			LOG_WRN("Awaited s-(out)-status not finished");
1207 		}
1208 
1209 		return ret;
1210 	}
1211 
1212 ctrl_xfer_stall:
1213 	/*
1214 	 * Halt only the endpoint over which the host expects
1215 	 * data or status stage. This facilitates the work of the drivers.
1216 	 *
1217 	 * In the case there is -ENOMEM for data OUT stage halt
1218 	 * control OUT endpoint.
1219 	 */
1220 	if (reqtype_is_to_host(setup)) {
1221 		ret = udc_ep_set_halt(uds_ctx->dev, USB_CONTROL_EP_IN);
1222 	} else if (setup->wLength) {
1223 		uint8_t ep = (err == -ENOMEM) ? USB_CONTROL_EP_OUT : USB_CONTROL_EP_IN;
1224 
1225 		ret = udc_ep_set_halt(uds_ctx->dev, ep);
1226 	} else {
1227 		ret = udc_ep_set_halt(uds_ctx->dev, USB_CONTROL_EP_IN);
1228 	}
1229 
1230 	ch9_set_ctrl_type(uds_ctx, CTRL_AWAIT_SETUP_DATA);
1231 
1232 	return ret;
1233 }
1234 
usbd_init_control_pipe(struct usbd_context * const uds_ctx)1235 int usbd_init_control_pipe(struct usbd_context *const uds_ctx)
1236 {
1237 	uds_ctx->ch9_data.state = USBD_STATE_DEFAULT;
1238 	ch9_set_ctrl_type(uds_ctx, CTRL_AWAIT_SETUP_DATA);
1239 
1240 	return 0;
1241 }
1242