1 /*
2  * Copyright 2018-2023, NXP
3  * Copyright (c) 2019 PHYTEC Messtechnik GmbH
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <soc.h>
9 #include <string.h>
10 #include <zephyr/drivers/usb/usb_dc.h>
11 #include <zephyr/usb/usb_device.h>
12 #include <soc.h>
13 #include <zephyr/init.h>
14 #include <zephyr/kernel.h>
15 #include <zephyr/drivers/pinctrl.h>
16 #include "usb.h"
17 #include "usb_device.h"
18 #include "usb_device_config.h"
19 #include "usb_device_dci.h"
20 
21 #ifdef CONFIG_USB_DC_NXP_EHCI
22 #undef DT_DRV_COMPAT
23 #define DT_DRV_COMPAT nxp_ehci
24 #include "usb_device_ehci.h"
25 #endif
26 #ifdef CONFIG_USB_DC_NXP_LPCIP3511
27 #undef DT_DRV_COMPAT
28 #define DT_DRV_COMPAT nxp_lpcip3511
29 #include "usb_device_lpcip3511.h"
30 #endif
31 #ifdef CONFIG_HAS_MCUX_CACHE
32 #include <fsl_cache.h>
33 #endif
34 
35 
36 #define LOG_LEVEL CONFIG_USB_DRIVER_LOG_LEVEL
37 #include <zephyr/logging/log.h>
38 #include <zephyr/irq.h>
39 LOG_MODULE_REGISTER(usb_dc_mcux);
40 
41 static void usb_isr_handler(void);
42 
43 /* the setup transfer state */
44 #define SETUP_DATA_STAGE_DONE	(0)
45 #define SETUP_DATA_STAGE_IN	(1)
46 #define SETUP_DATA_STAGE_OUT	(2)
47 
48 /*
49  * Endpoint absolute index calculation:
50  *
51  * MCUX EHCI USB device controller supports a specific
52  * number of bidirectional endpoints. Bidirectional means
53  * that an endpoint object is represented to the outside
54  * as an OUT and an IN Endpoint with its own buffers
55  * and control structures.
56  *
57  * EP_ABS_IDX refers to the corresponding control
58  * structure, for example:
59  *
60  *  EP addr | ep_idx | ep_abs_idx
61  * -------------------------------
62  *  0x00    | 0x00   | 0x00
63  *  0x80    | 0x00   | 0x01
64  *  0x01    | 0x01   | 0x02
65  *  0x81    | 0x01   | 0x03
66  *  ....    | ....   | ....
67  *
68  * The NUM_OF_EP_MAX (and number of s_ep_ctrl) should be double
69  * of num_bidir_endpoints.
70  */
71 #define EP_ABS_IDX(ep)		(USB_EP_GET_IDX(ep) * 2 + \
72 					(USB_EP_GET_DIR(ep) >> 7))
73 #define NUM_OF_EP_MAX		(DT_INST_PROP(0, num_bidir_endpoints) * 2)
74 
75 #define NUM_INSTS DT_NUM_INST_STATUS_OKAY(nxp_ehci) + DT_NUM_INST_STATUS_OKAY(nxp_lpcip3511)
76 BUILD_ASSERT(NUM_INSTS <= 1, "Only one USB device supported");
77 
78 /* Controller ID is for HAL usage */
79 #if defined(CONFIG_SOC_SERIES_IMXRT5XX) || \
80 	defined(CONFIG_SOC_SERIES_IMXRT6XX) || \
81 	defined(CONFIG_SOC_LPC55S28) || \
82 	defined(CONFIG_SOC_LPC55S16)
83 #define CONTROLLER_ID	kUSB_ControllerLpcIp3511Hs0
84 #elif defined(CONFIG_SOC_LPC55S36)
85 #define CONTROLLER_ID	kUSB_ControllerLpcIp3511Fs0
86 #elif defined(CONFIG_SOC_LPC55S69_CPU0) || defined(CONFIG_SOC_LPC55S69_CPU1)
87 #if DT_NODE_HAS_STATUS(DT_NODELABEL(usbhs), okay)
88 #define CONTROLLER_ID	kUSB_ControllerLpcIp3511Hs0
89 #elif DT_NODE_HAS_STATUS(DT_NODELABEL(usbfs), okay)
90 #define CONTROLLER_ID	kUSB_ControllerLpcIp3511Fs0
91 #endif /* LPC55s69 */
92 #elif defined(CONFIG_SOC_SERIES_IMXRT11XX) || \
93 	defined(CONFIG_SOC_SERIES_IMXRT10XX) || \
94 	defined(CONFIG_SOC_SERIES_MCXNX4X)
95 #if DT_NODE_HAS_STATUS(DT_NODELABEL(usb1), okay)
96 #define CONTROLLER_ID kUSB_ControllerEhci0
97 #elif DT_NODE_HAS_STATUS(DT_NODELABEL(usb2), okay)
98 #define CONTROLLER_ID kUSB_ControllerEhci1
99 #endif /* IMX RT */
100 #elif defined(CONFIG_SOC_SERIES_RW6XX)
101 #define CONTROLLER_ID kUSB_ControllerEhci0
102 #else
103 /* If SOC has EHCI or LPCIP3511 then probably just need to add controller ID to this code */
104 #error "USB driver does not yet support this SOC"
105 #endif /* CONTROLLER ID */
106 
107 /* We do not need a buffer for the write side on platforms that have USB RAM.
108  * The SDK driver will copy the data buffer to be sent to USB RAM.
109  */
110 #ifdef CONFIG_USB_DC_NXP_LPCIP3511
111 #define EP_BUF_NUMOF_BLOCKS	(NUM_OF_EP_MAX / 2)
112 #else
113 #define EP_BUF_NUMOF_BLOCKS	NUM_OF_EP_MAX
114 #endif
115 
116 /* The max MPS is 1023 for FS, 1024 for HS. */
117 #if defined(CONFIG_NOCACHE_MEMORY)
118 #define EP_BUF_NONCACHED
119 K_HEAP_DEFINE_NOCACHE(ep_buf_pool, 1024 * EP_BUF_NUMOF_BLOCKS);
120 #else
121 K_HEAP_DEFINE(ep_buf_pool, 1024 * EP_BUF_NUMOF_BLOCKS);
122 #endif
123 
124 struct usb_ep_ctrl_data {
125 	usb_device_callback_message_struct_t transfer_message;
126 	void *block;
127 	usb_dc_ep_callback callback;
128 	uint16_t ep_mps;
129 	uint8_t ep_enabled : 1;
130 	uint8_t ep_occupied : 1;
131 };
132 
133 struct usb_dc_state {
134 	usb_device_struct_t dev_struct;
135 	/* Controller handle */
136 	usb_dc_status_callback status_cb;
137 	struct usb_ep_ctrl_data *eps;
138 	bool attached;
139 	uint8_t setup_data_stage;
140 	K_KERNEL_STACK_MEMBER(thread_stack, CONFIG_USB_MCUX_THREAD_STACK_SIZE);
141 
142 	struct k_thread thread;
143 };
144 
145 static struct usb_ep_ctrl_data s_ep_ctrl[NUM_OF_EP_MAX];
146 static struct usb_dc_state dev_state;
147 
148 /* Message queue for the usb thread */
149 K_MSGQ_DEFINE(usb_dc_msgq, sizeof(usb_device_callback_message_struct_t),
150 	CONFIG_USB_DC_MSG_QUEUE_LEN, 4);
151 
152 #if defined(CONFIG_USB_DC_NXP_EHCI)
153 /* EHCI device driver interface */
154 static const usb_device_controller_interface_struct_t mcux_usb_iface = {
155 	USB_DeviceEhciInit, USB_DeviceEhciDeinit, USB_DeviceEhciSend,
156 	USB_DeviceEhciRecv, USB_DeviceEhciCancel, USB_DeviceEhciControl
157 };
158 
159 extern void USB_DeviceEhciIsrFunction(void *deviceHandle);
160 
161 #elif defined(CONFIG_USB_DC_NXP_LPCIP3511)
162 /* LPCIP3511 device driver interface */
163 static const usb_device_controller_interface_struct_t mcux_usb_iface = {
164 	USB_DeviceLpc3511IpInit, USB_DeviceLpc3511IpDeinit, USB_DeviceLpc3511IpSend,
165 	USB_DeviceLpc3511IpRecv, USB_DeviceLpc3511IpCancel, USB_DeviceLpc3511IpControl
166 };
167 
168 extern void USB_DeviceLpcIp3511IsrFunction(void *deviceHandle);
169 
170 #endif
171 
usb_dc_reset(void)172 int usb_dc_reset(void)
173 {
174 	if (dev_state.dev_struct.controllerHandle != NULL) {
175 		dev_state.dev_struct.controllerInterface->deviceControl(
176 						dev_state.dev_struct.controllerHandle,
177 						kUSB_DeviceControlSetDefaultStatus, NULL);
178 	}
179 
180 	return 0;
181 }
182 
usb_dc_attach(void)183 int usb_dc_attach(void)
184 {
185 	usb_status_t status;
186 
187 	dev_state.eps = &s_ep_ctrl[0];
188 	if (dev_state.attached) {
189 		LOG_WRN("Already attached");
190 		return 0;
191 	}
192 
193 	dev_state.dev_struct.controllerInterface = &mcux_usb_iface;
194 	status = dev_state.dev_struct.controllerInterface->deviceInit(CONTROLLER_ID,
195 						&dev_state.dev_struct,
196 						&dev_state.dev_struct.controllerHandle);
197 	if (kStatus_USB_Success != status) {
198 		return -EIO;
199 	}
200 
201 	IRQ_CONNECT(DT_INST_IRQN(0), DT_INST_IRQ(0, priority),
202 		    usb_isr_handler, 0, 0);
203 	irq_enable(DT_INST_IRQN(0));
204 	dev_state.attached = true;
205 	status = dev_state.dev_struct.controllerInterface->deviceControl(
206 						dev_state.dev_struct.controllerHandle,
207 						kUSB_DeviceControlRun, NULL);
208 
209 	LOG_DBG("Attached");
210 
211 	return 0;
212 }
213 
usb_dc_detach(void)214 int usb_dc_detach(void)
215 {
216 	usb_status_t status;
217 
218 	if (dev_state.dev_struct.controllerHandle == NULL) {
219 		LOG_WRN("Device not attached");
220 		return 0;
221 	}
222 
223 	status = dev_state.dev_struct.controllerInterface->deviceControl(
224 						   dev_state.dev_struct.controllerHandle,
225 						   kUSB_DeviceControlStop,
226 						   NULL);
227 	if (kStatus_USB_Success != status) {
228 		return -EIO;
229 	}
230 
231 	status = dev_state.dev_struct.controllerInterface->deviceDeinit(
232 						   dev_state.dev_struct.controllerHandle);
233 	if (kStatus_USB_Success != status) {
234 		return -EIO;
235 	}
236 
237 	dev_state.dev_struct.controllerHandle = NULL;
238 	dev_state.attached = false;
239 	LOG_DBG("Detached");
240 
241 	return 0;
242 }
243 
usb_dc_set_address(const uint8_t addr)244 int usb_dc_set_address(const uint8_t addr)
245 {
246 	usb_status_t status;
247 
248 	dev_state.dev_struct.deviceAddress = addr;
249 	status = dev_state.dev_struct.controllerInterface->deviceControl(
250 		dev_state.dev_struct.controllerHandle,
251 		kUSB_DeviceControlPreSetDeviceAddress,
252 		&dev_state.dev_struct.deviceAddress);
253 	if (kStatus_USB_Success != status) {
254 		LOG_ERR("Failed to set device address");
255 		return -EINVAL;
256 	}
257 	return 0;
258 }
259 
usb_dc_ep_check_cap(const struct usb_dc_ep_cfg_data * const cfg)260 int usb_dc_ep_check_cap(const struct usb_dc_ep_cfg_data *const cfg)
261 {
262 	uint8_t ep_abs_idx =  EP_ABS_IDX(cfg->ep_addr);
263 	uint8_t ep_idx = USB_EP_GET_IDX(cfg->ep_addr);
264 
265 	if ((cfg->ep_type == USB_DC_EP_CONTROL) && ep_idx) {
266 		LOG_ERR("invalid endpoint configuration");
267 		return -1;
268 	}
269 
270 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
271 		LOG_ERR("endpoint index/address out of range");
272 		return -1;
273 	}
274 
275 	return 0;
276 }
277 
usb_dc_ep_configure(const struct usb_dc_ep_cfg_data * const cfg)278 int usb_dc_ep_configure(const struct usb_dc_ep_cfg_data *const cfg)
279 {
280 	uint8_t ep_abs_idx =  EP_ABS_IDX(cfg->ep_addr);
281 	usb_device_endpoint_init_struct_t ep_init;
282 	struct usb_ep_ctrl_data *eps = &dev_state.eps[ep_abs_idx];
283 	usb_status_t status;
284 	uint8_t ep;
285 
286 	ep_init.zlt = 0U;
287 	ep_init.endpointAddress = cfg->ep_addr;
288 	ep_init.maxPacketSize = cfg->ep_mps;
289 	ep_init.transferType = cfg->ep_type;
290 
291 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
292 		LOG_ERR("Wrong endpoint index/address");
293 		return -EINVAL;
294 	}
295 
296 	if (dev_state.eps[ep_abs_idx].ep_enabled) {
297 		LOG_WRN("Endpoint already configured");
298 		return 0;
299 	}
300 
301 	ep = cfg->ep_addr;
302 	status = dev_state.dev_struct.controllerInterface->deviceControl(
303 			dev_state.dev_struct.controllerHandle,
304 			kUSB_DeviceControlEndpointDeinit, &ep);
305 	if (kStatus_USB_Success != status) {
306 		LOG_WRN("Failed to un-initialize endpoint (status=%d)", (int)status);
307 	}
308 
309 #ifdef CONFIG_USB_DC_NXP_LPCIP3511
310 	/* Allocate buffers used during read operation */
311 	if (USB_EP_DIR_IS_OUT(cfg->ep_addr)) {
312 #endif
313 		void **block;
314 
315 		block = &(eps->block);
316 		if (*block) {
317 			k_heap_free(&ep_buf_pool, *block);
318 			*block = NULL;
319 		}
320 
321 		*block = k_heap_alloc(&ep_buf_pool, cfg->ep_mps, K_NO_WAIT);
322 		if (*block == NULL) {
323 			LOG_ERR("Failed to allocate memory");
324 			return -ENOMEM;
325 		}
326 
327 		memset(*block, 0, cfg->ep_mps);
328 #ifdef CONFIG_USB_DC_NXP_LPCIP3511
329 	}
330 #endif
331 
332 	dev_state.eps[ep_abs_idx].ep_mps = cfg->ep_mps;
333 	status = dev_state.dev_struct.controllerInterface->deviceControl(
334 			dev_state.dev_struct.controllerHandle,
335 			kUSB_DeviceControlEndpointInit, &ep_init);
336 	if (kStatus_USB_Success != status) {
337 		LOG_ERR("Failed to initialize endpoint");
338 		return -EIO;
339 	}
340 
341 	/*
342 	 * If it is control endpoint, controller will prime setup
343 	 * here set the occupied flag.
344 	 */
345 	if ((USB_EP_GET_IDX(cfg->ep_addr) == USB_CONTROL_ENDPOINT) &&
346 	    (USB_EP_DIR_IS_OUT(cfg->ep_addr))) {
347 		dev_state.eps[ep_abs_idx].ep_occupied = true;
348 	}
349 	dev_state.eps[ep_abs_idx].ep_enabled = true;
350 
351 	return 0;
352 }
353 
usb_dc_ep_set_stall(const uint8_t ep)354 int usb_dc_ep_set_stall(const uint8_t ep)
355 {
356 	uint8_t endpoint = ep;
357 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
358 	usb_status_t status;
359 
360 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
361 		LOG_ERR("Wrong endpoint index/address");
362 		return -EINVAL;
363 	}
364 
365 	status = dev_state.dev_struct.controllerInterface->deviceControl(
366 			dev_state.dev_struct.controllerHandle,
367 			kUSB_DeviceControlEndpointStall, &endpoint);
368 	if (kStatus_USB_Success != status) {
369 		LOG_ERR("Failed to stall endpoint");
370 		return -EIO;
371 	}
372 
373 	return 0;
374 }
375 
usb_dc_ep_clear_stall(const uint8_t ep)376 int usb_dc_ep_clear_stall(const uint8_t ep)
377 {
378 	uint8_t endpoint = ep;
379 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
380 	usb_status_t status;
381 
382 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
383 		LOG_ERR("Wrong endpoint index/address");
384 		return -EINVAL;
385 	}
386 
387 	status = dev_state.dev_struct.controllerInterface->deviceControl(
388 			dev_state.dev_struct.controllerHandle,
389 			kUSB_DeviceControlEndpointUnstall, &endpoint);
390 	if (kStatus_USB_Success != status) {
391 		LOG_ERR("Failed to clear stall");
392 		return -EIO;
393 	}
394 
395 	if ((USB_EP_GET_IDX(ep) != USB_CONTROL_ENDPOINT) &&
396 	    (USB_EP_DIR_IS_OUT(ep))) {
397 		status = dev_state.dev_struct.controllerInterface->deviceRecv(
398 				dev_state.dev_struct.controllerHandle, ep,
399 				(uint8_t *)dev_state.eps[ep_abs_idx].block,
400 				(uint32_t)dev_state.eps[ep_abs_idx].ep_mps);
401 		if (kStatus_USB_Success != status) {
402 			LOG_ERR("Failed to enable reception on 0x%02x", ep);
403 			return -EIO;
404 		}
405 
406 		dev_state.eps[ep_abs_idx].ep_occupied = true;
407 	}
408 
409 	return 0;
410 }
411 
usb_dc_ep_is_stalled(const uint8_t ep,uint8_t * const stalled)412 int usb_dc_ep_is_stalled(const uint8_t ep, uint8_t *const stalled)
413 {
414 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
415 	usb_device_endpoint_status_struct_t ep_status;
416 	usb_status_t status;
417 
418 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
419 		LOG_ERR("Wrong endpoint index/address");
420 		return -EINVAL;
421 	}
422 
423 	if (!stalled) {
424 		return -EINVAL;
425 	}
426 
427 	*stalled = 0;
428 	ep_status.endpointAddress = ep;
429 	ep_status.endpointStatus = kUSB_DeviceEndpointStateIdle;
430 	status = dev_state.dev_struct.controllerInterface->deviceControl(
431 			dev_state.dev_struct.controllerHandle,
432 			kUSB_DeviceControlGetEndpointStatus, &ep_status);
433 	if (kStatus_USB_Success != status) {
434 		LOG_ERR("Failed to get endpoint status");
435 		return -EIO;
436 	}
437 
438 	*stalled = (uint8_t)ep_status.endpointStatus;
439 
440 	return 0;
441 }
442 
usb_dc_ep_halt(const uint8_t ep)443 int usb_dc_ep_halt(const uint8_t ep)
444 {
445 	return usb_dc_ep_set_stall(ep);
446 }
447 
usb_dc_ep_enable(const uint8_t ep)448 int usb_dc_ep_enable(const uint8_t ep)
449 {
450 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
451 	usb_status_t status;
452 
453 	/*
454 	 * endpoint 0 OUT is primed by controller driver when configure this
455 	 * endpoint.
456 	 */
457 	if (!ep_abs_idx) {
458 		return 0;
459 	}
460 
461 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
462 		LOG_ERR("Wrong endpoint index/address");
463 		return -EINVAL;
464 	}
465 
466 	if (dev_state.eps[ep_abs_idx].ep_occupied) {
467 		LOG_WRN("endpoint 0x%x already enabled", ep);
468 		return -EALREADY;
469 	}
470 
471 	if ((USB_EP_GET_IDX(ep) != USB_CONTROL_ENDPOINT) &&
472 	    (USB_EP_DIR_IS_OUT(ep))) {
473 		status = dev_state.dev_struct.controllerInterface->deviceRecv(
474 				dev_state.dev_struct.controllerHandle, ep,
475 				(uint8_t *)dev_state.eps[ep_abs_idx].block,
476 				(uint32_t)dev_state.eps[ep_abs_idx].ep_mps);
477 		if (kStatus_USB_Success != status) {
478 			LOG_ERR("Failed to enable reception on 0x%02x", ep);
479 			return -EIO;
480 		}
481 
482 		dev_state.eps[ep_abs_idx].ep_occupied = true;
483 	} else {
484 		/*
485 		 * control endpoint just be enabled before enumeration,
486 		 * when running here, setup has been primed.
487 		 */
488 		dev_state.eps[ep_abs_idx].ep_occupied = true;
489 	}
490 
491 	return 0;
492 }
493 
usb_dc_ep_disable(const uint8_t ep)494 int usb_dc_ep_disable(const uint8_t ep)
495 {
496 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
497 	usb_status_t status;
498 
499 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
500 		LOG_ERR("Wrong endpoint index/address");
501 		return -EINVAL;
502 	}
503 
504 	if (dev_state.dev_struct.controllerHandle != NULL) {
505 		status = dev_state.dev_struct.controllerInterface->deviceCancel(
506 							dev_state.dev_struct.controllerHandle,
507 							ep);
508 		if (kStatus_USB_Success != status) {
509 			LOG_ERR("Failed to disable ep 0x%02x", ep);
510 			return -EIO;
511 		}
512 	}
513 
514 	dev_state.eps[ep_abs_idx].ep_enabled = false;
515 	dev_state.eps[ep_abs_idx].ep_occupied = false;
516 
517 	return 0;
518 }
519 
usb_dc_ep_flush(const uint8_t ep)520 int usb_dc_ep_flush(const uint8_t ep)
521 {
522 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
523 
524 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
525 		LOG_ERR("Wrong endpoint index/address");
526 		return -EINVAL;
527 	}
528 
529 	LOG_DBG("Not implemented, idx 0x%02x, ep %u", ep_abs_idx, ep);
530 
531 	return 0;
532 }
533 
usb_dc_ep_write(const uint8_t ep,const uint8_t * const data,const uint32_t data_len,uint32_t * const ret_bytes)534 int usb_dc_ep_write(const uint8_t ep, const uint8_t *const data,
535 		    const uint32_t data_len, uint32_t *const ret_bytes)
536 {
537 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
538 	uint8_t *buffer;
539 	uint32_t len_to_send = data_len;
540 	usb_status_t status;
541 
542 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
543 		LOG_ERR("Wrong endpoint index/address");
544 		return -EINVAL;
545 	}
546 
547 	if (USB_EP_GET_DIR(ep) != USB_EP_DIR_IN) {
548 		LOG_ERR("Wrong endpoint direction");
549 		return -EINVAL;
550 	}
551 
552 	/* Copy the data for SoC's that do not have a USB RAM
553 	 * as the SDK driver will copy the data into USB RAM,
554 	 * if available.
555 	 */
556 #ifndef CONFIG_USB_DC_NXP_LPCIP3511
557 	buffer = (uint8_t *)dev_state.eps[ep_abs_idx].block;
558 
559 	if (data_len > dev_state.eps[ep_abs_idx].ep_mps) {
560 		len_to_send = dev_state.eps[ep_abs_idx].ep_mps;
561 	}
562 
563 	for (uint32_t n = 0; n < len_to_send; n++) {
564 		buffer[n] = data[n];
565 	}
566 #else
567 	buffer = (uint8_t *)data;
568 #endif
569 
570 #if defined(CONFIG_HAS_MCUX_CACHE) && !defined(EP_BUF_NONCACHED)
571 	DCACHE_CleanByRange((uint32_t)buffer, len_to_send);
572 #endif
573 	status = dev_state.dev_struct.controllerInterface->deviceSend(
574 						dev_state.dev_struct.controllerHandle,
575 						ep, buffer, len_to_send);
576 	if (kStatus_USB_Success != status) {
577 		LOG_ERR("Failed to fill ep 0x%02x buffer", ep);
578 		return -EIO;
579 	}
580 
581 	if (ret_bytes) {
582 		*ret_bytes = len_to_send;
583 	}
584 
585 	return 0;
586 }
587 
update_control_stage(usb_device_callback_message_struct_t * cb_msg,uint32_t data_len,uint32_t max_data_len)588 static void update_control_stage(usb_device_callback_message_struct_t *cb_msg,
589 				 uint32_t data_len, uint32_t max_data_len)
590 {
591 	struct usb_setup_packet *usbd_setup;
592 
593 	usbd_setup = (struct usb_setup_packet *)cb_msg->buffer;
594 
595 	if (cb_msg->isSetup) {
596 		if (usbd_setup->wLength == 0) {
597 			dev_state.setup_data_stage = SETUP_DATA_STAGE_DONE;
598 		} else if (usb_reqtype_is_to_host(usbd_setup)) {
599 			dev_state.setup_data_stage = SETUP_DATA_STAGE_IN;
600 		} else {
601 			dev_state.setup_data_stage = SETUP_DATA_STAGE_OUT;
602 		}
603 	} else {
604 		if (dev_state.setup_data_stage != SETUP_DATA_STAGE_DONE) {
605 			if ((data_len >= max_data_len) ||
606 			    (data_len < dev_state.eps[0].ep_mps)) {
607 				dev_state.setup_data_stage = SETUP_DATA_STAGE_DONE;
608 			}
609 		}
610 	}
611 }
612 
usb_dc_ep_read_wait(uint8_t ep,uint8_t * data,uint32_t max_data_len,uint32_t * read_bytes)613 int usb_dc_ep_read_wait(uint8_t ep, uint8_t *data, uint32_t max_data_len,
614 			uint32_t *read_bytes)
615 {
616 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
617 	uint32_t data_len;
618 	uint8_t *bufp = NULL;
619 
620 	if (dev_state.eps[ep_abs_idx].ep_occupied) {
621 		LOG_ERR("Endpoint is occupied by the controller");
622 		return -EBUSY;
623 	}
624 
625 	if ((ep_abs_idx >= NUM_OF_EP_MAX) ||
626 	    (USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT)) {
627 		LOG_ERR("Wrong endpoint index/address/direction");
628 		return -EINVAL;
629 	}
630 
631 	/* Allow to read 0 bytes */
632 	if (!data && max_data_len) {
633 		LOG_ERR("Wrong arguments");
634 		return -EINVAL;
635 	}
636 
637 	/*
638 	 * It is control setup, we should use message.buffer,
639 	 * this buffer is from internal setup array.
640 	 */
641 	bufp = dev_state.eps[ep_abs_idx].transfer_message.buffer;
642 	data_len = dev_state.eps[ep_abs_idx].transfer_message.length;
643 	if (data_len == USB_UNINITIALIZED_VAL_32) {
644 		if (read_bytes) {
645 			*read_bytes = 0;
646 		}
647 		return -EINVAL;
648 	}
649 
650 	if (!data && !max_data_len) {
651 		/* When both buffer and max data to read are zero return the
652 		 * available data in buffer.
653 		 */
654 		if (read_bytes) {
655 			*read_bytes = data_len;
656 		}
657 		return 0;
658 	}
659 
660 	if (data_len > max_data_len) {
661 		LOG_WRN("Not enough room to copy all the data!");
662 		data_len = max_data_len;
663 	}
664 
665 	if (data != NULL) {
666 		for (uint32_t i = 0; i < data_len; i++) {
667 			data[i] = bufp[i];
668 		}
669 	}
670 
671 	if (read_bytes) {
672 		*read_bytes = data_len;
673 	}
674 
675 	if (USB_EP_GET_IDX(ep) == USB_ENDPOINT_CONTROL) {
676 		update_control_stage(&dev_state.eps[0].transfer_message,
677 				     data_len, max_data_len);
678 	}
679 
680 	return 0;
681 }
682 
usb_dc_ep_read_continue(uint8_t ep)683 int usb_dc_ep_read_continue(uint8_t ep)
684 {
685 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
686 	usb_status_t status;
687 
688 	if (ep_abs_idx >= NUM_OF_EP_MAX ||
689 	    USB_EP_GET_DIR(ep) != USB_EP_DIR_OUT) {
690 		LOG_ERR("Wrong endpoint index/address/direction");
691 		return -EINVAL;
692 	}
693 
694 	if (dev_state.eps[ep_abs_idx].ep_occupied) {
695 		LOG_WRN("endpoint 0x%x already occupied", ep);
696 		return -EBUSY;
697 	}
698 
699 	if (USB_EP_GET_IDX(ep) == USB_ENDPOINT_CONTROL) {
700 		if (dev_state.setup_data_stage == SETUP_DATA_STAGE_DONE) {
701 			return 0;
702 		}
703 
704 		if (dev_state.setup_data_stage == SETUP_DATA_STAGE_IN) {
705 			dev_state.setup_data_stage = SETUP_DATA_STAGE_DONE;
706 		}
707 	}
708 
709 	status = dev_state.dev_struct.controllerInterface->deviceRecv(
710 			    dev_state.dev_struct.controllerHandle, ep,
711 			    (uint8_t *)dev_state.eps[ep_abs_idx].block,
712 			    dev_state.eps[ep_abs_idx].ep_mps);
713 	if (kStatus_USB_Success != status) {
714 		LOG_ERR("Failed to enable reception on ep 0x%02x", ep);
715 		return -EIO;
716 	}
717 
718 	dev_state.eps[ep_abs_idx].ep_occupied = true;
719 
720 	return 0;
721 }
722 
usb_dc_ep_read(const uint8_t ep,uint8_t * const data,const uint32_t max_data_len,uint32_t * const read_bytes)723 int usb_dc_ep_read(const uint8_t ep, uint8_t *const data,
724 		   const uint32_t max_data_len, uint32_t *const read_bytes)
725 {
726 	int retval = usb_dc_ep_read_wait(ep, data, max_data_len, read_bytes);
727 
728 	if (retval) {
729 		return retval;
730 	}
731 
732 	if (!data && !max_data_len) {
733 		/*
734 		 * When both buffer and max data to read are zero the above
735 		 * call would fetch the data len and we simply return.
736 		 */
737 		return 0;
738 	}
739 
740 	return usb_dc_ep_read_continue(ep);
741 }
742 
usb_dc_ep_set_callback(const uint8_t ep,const usb_dc_ep_callback cb)743 int usb_dc_ep_set_callback(const uint8_t ep, const usb_dc_ep_callback cb)
744 {
745 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
746 
747 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
748 		LOG_ERR("Wrong endpoint index/address");
749 		return -EINVAL;
750 	}
751 
752 	if (!dev_state.attached) {
753 		return -EINVAL;
754 	}
755 	dev_state.eps[ep_abs_idx].callback = cb;
756 
757 	return 0;
758 }
759 
usb_dc_set_status_callback(const usb_dc_status_callback cb)760 void usb_dc_set_status_callback(const usb_dc_status_callback cb)
761 {
762 	dev_state.status_cb = cb;
763 }
764 
usb_dc_ep_mps(const uint8_t ep)765 int usb_dc_ep_mps(const uint8_t ep)
766 {
767 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
768 
769 	if (ep_abs_idx >= NUM_OF_EP_MAX) {
770 		LOG_ERR("Wrong endpoint index/address");
771 		return -EINVAL;
772 	}
773 
774 	return dev_state.eps[ep_abs_idx].ep_mps;
775 }
776 
handle_bus_reset(void)777 static void handle_bus_reset(void)
778 {
779 	usb_device_endpoint_init_struct_t ep_init;
780 	uint8_t ep_abs_idx = 0;
781 	usb_status_t status;
782 
783 	dev_state.dev_struct.deviceAddress = 0;
784 	status = dev_state.dev_struct.controllerInterface->deviceControl(
785 			dev_state.dev_struct.controllerHandle,
786 			kUSB_DeviceControlSetDefaultStatus, NULL);
787 	if (kStatus_USB_Success != status) {
788 		LOG_ERR("Failed to set default status");
789 	}
790 
791 	for (int i = 0; i < NUM_OF_EP_MAX; i++) {
792 		dev_state.eps[i].ep_occupied = false;
793 		dev_state.eps[i].ep_enabled = false;
794 	}
795 
796 	ep_init.zlt = 0U;
797 	ep_init.transferType = USB_ENDPOINT_CONTROL;
798 	ep_init.maxPacketSize = USB_CONTROL_EP_MPS;
799 	ep_init.endpointAddress = USB_CONTROL_EP_OUT;
800 
801 	ep_abs_idx =  EP_ABS_IDX(ep_init.endpointAddress);
802 	dev_state.eps[ep_abs_idx].ep_mps = USB_CONTROL_EP_MPS;
803 
804 	status = dev_state.dev_struct.controllerInterface->deviceControl(
805 			dev_state.dev_struct.controllerHandle,
806 			kUSB_DeviceControlEndpointInit, &ep_init);
807 	if (kStatus_USB_Success != status) {
808 		LOG_ERR("Failed to initialize control OUT endpoint");
809 	}
810 
811 	dev_state.eps[ep_abs_idx].ep_occupied = false;
812 	dev_state.eps[ep_abs_idx].ep_enabled = true;
813 
814 	ep_init.endpointAddress = USB_CONTROL_EP_IN;
815 	ep_abs_idx = EP_ABS_IDX(ep_init.endpointAddress);
816 	dev_state.eps[ep_abs_idx].ep_mps = USB_CONTROL_EP_MPS;
817 	status = dev_state.dev_struct.controllerInterface->deviceControl(
818 			dev_state.dev_struct.controllerHandle,
819 			kUSB_DeviceControlEndpointInit, &ep_init);
820 	if (kStatus_USB_Success != status) {
821 		LOG_ERR("Failed to initialize control IN endpoint");
822 	}
823 
824 	dev_state.eps[ep_abs_idx].ep_occupied = false;
825 	dev_state.eps[ep_abs_idx].ep_enabled = true;
826 }
827 
handle_transfer_msg(usb_device_callback_message_struct_t * cb_msg)828 static void handle_transfer_msg(usb_device_callback_message_struct_t *cb_msg)
829 {
830 	uint8_t ep_status_code = 0;
831 	uint8_t ep = cb_msg->code;
832 	uint8_t ep_abs_idx = EP_ABS_IDX(ep);
833 	usb_status_t status;
834 
835 	dev_state.eps[ep_abs_idx].ep_occupied = false;
836 
837 	if (cb_msg->length == UINT32_MAX) {
838 		/*
839 		 * Probably called from USB_DeviceEhciCancel()
840 		 * LOG_WRN("Drop message for ep 0x%02x", ep);
841 		 */
842 		return;
843 	}
844 
845 	if (cb_msg->isSetup) {
846 		ep_status_code = USB_DC_EP_SETUP;
847 	} else {
848 		/* IN TOKEN */
849 		if (USB_EP_DIR_IS_IN(ep)) {
850 			if ((dev_state.dev_struct.deviceAddress != 0) && (ep_abs_idx == 1)) {
851 				/*
852 				 * Set Address in the status stage in
853 				 * the IN transfer.
854 				 */
855 				status = dev_state.dev_struct.controllerInterface->deviceControl(
856 					dev_state.dev_struct.controllerHandle,
857 					kUSB_DeviceControlSetDeviceAddress,
858 					&dev_state.dev_struct.deviceAddress);
859 				if (kStatus_USB_Success != status) {
860 					LOG_ERR("Failed to set device address");
861 					return;
862 				}
863 				dev_state.dev_struct.deviceAddress = 0;
864 			}
865 			ep_status_code = USB_DC_EP_DATA_IN;
866 		}
867 		/* OUT TOKEN */
868 		else {
869 			ep_status_code = USB_DC_EP_DATA_OUT;
870 		}
871 	}
872 
873 	if (dev_state.eps[ep_abs_idx].callback) {
874 #if defined(CONFIG_HAS_MCUX_CACHE) && !defined(EP_BUF_NONCACHED)
875 		if (cb_msg->length) {
876 			DCACHE_InvalidateByRange((uint32_t)cb_msg->buffer,
877 						 cb_msg->length);
878 		}
879 #endif
880 		dev_state.eps[ep_abs_idx].callback(ep, ep_status_code);
881 	} else {
882 		LOG_ERR("No cb pointer for endpoint 0x%02x", ep);
883 	}
884 }
885 
886 /**
887  * Similar to the kinetis driver, this thread is used to not run the USB device
888  * stack/endpoint callbacks in the ISR context. This is because callbacks from
889  * the USB stack may use mutexes, or other kernel functions not supported from
890  * an interrupt context.
891  */
usb_mcux_thread_main(void * arg1,void * arg2,void * arg3)892 static void usb_mcux_thread_main(void *arg1, void *arg2, void *arg3)
893 {
894 	ARG_UNUSED(arg1);
895 	ARG_UNUSED(arg2);
896 	ARG_UNUSED(arg3);
897 
898 	uint8_t ep_abs_idx;
899 	usb_device_callback_message_struct_t msg;
900 
901 	while (1) {
902 		k_msgq_get(&usb_dc_msgq, &msg, K_FOREVER);
903 		switch (msg.code) {
904 		case kUSB_DeviceNotifyBusReset:
905 			handle_bus_reset();
906 			dev_state.status_cb(USB_DC_RESET, NULL);
907 			break;
908 		case kUSB_DeviceNotifyError:
909 			dev_state.status_cb(USB_DC_ERROR, NULL);
910 			break;
911 		case kUSB_DeviceNotifySuspend:
912 			dev_state.status_cb(USB_DC_SUSPEND, NULL);
913 			break;
914 		case kUSB_DeviceNotifyResume:
915 			dev_state.status_cb(USB_DC_RESUME, NULL);
916 			break;
917 		default:
918 			ep_abs_idx = EP_ABS_IDX(msg.code);
919 
920 			if (ep_abs_idx >= NUM_OF_EP_MAX) {
921 				LOG_ERR("Wrong endpoint index/address");
922 				return;
923 			}
924 
925 			memcpy(&dev_state.eps[ep_abs_idx].transfer_message, &msg,
926 			       sizeof(usb_device_callback_message_struct_t));
927 			handle_transfer_msg(&dev_state.eps[ep_abs_idx].transfer_message);
928 		}
929 	}
930 }
931 
932 /* Notify the up layer the KHCI status changed. */
USB_DeviceNotificationTrigger(void * handle,void * msg)933 usb_status_t USB_DeviceNotificationTrigger(void *handle, void *msg)
934 {
935 	/* Submit to message queue */
936 	k_msgq_put(&usb_dc_msgq,
937 		(usb_device_callback_message_struct_t *)msg, K_NO_WAIT);
938 	return kStatus_USB_Success;
939 }
940 
usb_isr_handler(void)941 static void usb_isr_handler(void)
942 {
943 #if defined(CONFIG_USB_DC_NXP_EHCI)
944 	USB_DeviceEhciIsrFunction(&dev_state);
945 #elif defined(CONFIG_USB_DC_NXP_LPCIP3511)
946 	USB_DeviceLpcIp3511IsrFunction(&dev_state);
947 #endif
948 }
949 
usb_mcux_init(void)950 static int usb_mcux_init(void)
951 {
952 	int err;
953 
954 	k_thread_create(&dev_state.thread, dev_state.thread_stack,
955 			CONFIG_USB_MCUX_THREAD_STACK_SIZE,
956 			usb_mcux_thread_main, NULL, NULL, NULL,
957 			K_PRIO_COOP(2), 0, K_NO_WAIT);
958 	k_thread_name_set(&dev_state.thread, "usb_mcux");
959 
960 	PINCTRL_DT_INST_DEFINE(0);
961 
962 	/* Apply pinctrl state */
963 	err = pinctrl_apply_state(PINCTRL_DT_INST_DEV_CONFIG_GET(0), PINCTRL_STATE_DEFAULT);
964 	if (err) {
965 		return err;
966 	}
967 
968 	return 0;
969 }
970 
971 SYS_INIT(usb_mcux_init, POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);
972