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