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