1 /*
2  * Copyright (c) 2016 - 2023, Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /* This file is undergoing transition towards native Zephyr nrf USB driver. */
8 
9 /** @cond INTERNAL_HIDDEN */
10 
11 #include <nrfx.h>
12 
13 #include "nrf_usbd_common.h"
14 #include "nrf_usbd_common_errata.h"
15 #include <string.h>
16 #include <zephyr/kernel.h>
17 
18 #include <zephyr/logging/log.h>
19 LOG_MODULE_REGISTER(nrf_usbd_common, CONFIG_NRF_USBD_COMMON_LOG_LEVEL);
20 
21 #define NRF_USBD_COMMON_EPIN_CNT      9
22 #define NRF_USBD_COMMON_EPOUT_CNT     9
23 #define NRF_USBD_COMMON_EP_NUM(ep)    (ep & 0xF)
24 #define NRF_USBD_COMMON_EP_IS_IN(ep)  ((ep & 0x80) == 0x80)
25 #define NRF_USBD_COMMON_EP_IS_OUT(ep) ((ep & 0x80) == 0)
26 #define NRF_USBD_COMMON_EP_IS_ISO(ep) ((ep & 0xF) >= 8)
27 
28 #ifndef NRF_USBD_COMMON_ISO_DEBUG
29 /* Also generate information about ISOCHRONOUS events and transfers.
30  * Turn this off if no ISOCHRONOUS transfers are going to be debugged and this
31  * option generates a lot of useless messages.
32  */
33 #define NRF_USBD_COMMON_ISO_DEBUG 1
34 #endif
35 
36 #ifndef NRF_USBD_COMMON_FAILED_TRANSFERS_DEBUG
37 /* Also generate debug information for failed transfers.
38  * It might be useful but may generate a lot of useless debug messages
39  * in some library usages (for example when transfer is generated and the
40  * result is used to check whatever endpoint was busy.
41  */
42 #define NRF_USBD_COMMON_FAILED_TRANSFERS_DEBUG 1
43 #endif
44 
45 #ifndef NRF_USBD_COMMON_DMAREQ_PROCESS_DEBUG
46 /* Generate additional messages that mark the status inside
47  * @ref usbd_dmareq_process.
48  * It is useful to debug library internals but may generate a lot of
49  * useless debug messages.
50  */
51 #define NRF_USBD_COMMON_DMAREQ_PROCESS_DEBUG 1
52 #endif
53 
54 #ifndef NRF_USBD_COMMON_USE_WORKAROUND_FOR_ANOMALY_211
55 /* Anomaly 211 - Device remains in SUSPEND too long when host resumes
56  * a bus activity (sending SOF packets) without a RESUME condition.
57  */
58 #define NRF_USBD_COMMON_USE_WORKAROUND_FOR_ANOMALY_211 0
59 #endif
60 
61 /**
62  * @defgroup nrf_usbd_common_int USB Device driver internal part
63  * @internal
64  * @ingroup nrf_usbd_common
65  *
66  * This part contains auxiliary internal macros, variables and functions.
67  * @{
68  */
69 
70 /**
71  * @brief Assert endpoint number validity.
72  *
73  * Internal macro to be used during program creation in debug mode.
74  * Generates assertion if endpoint number is not valid.
75  *
76  * @param ep Endpoint number to validity check.
77  */
78 #define NRF_USBD_COMMON_ASSERT_EP_VALID(ep) __ASSERT_NO_MSG(         \
79 	((NRF_USBD_COMMON_EP_IS_IN(ep) &&                            \
80 	 (NRF_USBD_COMMON_EP_NUM(ep) < NRF_USBD_COMMON_EPIN_CNT)) || \
81 	 (NRF_USBD_COMMON_EP_IS_OUT(ep) &&                           \
82 	 (NRF_USBD_COMMON_EP_NUM(ep) < NRF_USBD_COMMON_EPOUT_CNT))));
83 
84 /**
85  * @brief Lowest position of bit for IN endpoint.
86  *
87  * The first bit position corresponding to IN endpoint.
88  * @sa ep2bit bit2ep
89  */
90 #define NRF_USBD_COMMON_EPIN_BITPOS_0 0
91 
92 /**
93  * @brief Lowest position of bit for OUT endpoint.
94  *
95  * The first bit position corresponding to OUT endpoint
96  * @sa ep2bit bit2ep
97  */
98 #define NRF_USBD_COMMON_EPOUT_BITPOS_0 16
99 
100 /**
101  * @brief Input endpoint bits mask.
102  */
103 #define NRF_USBD_COMMON_EPIN_BIT_MASK (0xFFFFU << NRF_USBD_COMMON_EPIN_BITPOS_0)
104 
105 /**
106  * @brief Output endpoint bits mask.
107  */
108 #define NRF_USBD_COMMON_EPOUT_BIT_MASK (0xFFFFU << NRF_USBD_COMMON_EPOUT_BITPOS_0)
109 
110 /**
111  * @brief Isochronous endpoint bit mask
112  */
113 #define USBD_EPISO_BIT_MASK                                                    \
114 	((1U << NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPOUT8)) |           \
115 	 (1U << NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPIN8)))
116 
117 /**
118  * @brief Auxiliary macro to change EP number into bit position.
119  *
120  * This macro is used by @ref ep2bit function but also for statically check
121  * the bitpos values integrity during compilation.
122  *
123  * @param[in] ep Endpoint number.
124  * @return Endpoint bit position.
125  */
126 #define NRF_USBD_COMMON_EP_BITPOS(ep) ((NRF_USBD_COMMON_EP_IS_IN(ep)      \
127 	? NRF_USBD_COMMON_EPIN_BITPOS_0 : NRF_USBD_COMMON_EPOUT_BITPOS_0) \
128 	+ NRF_USBD_COMMON_EP_NUM(ep))
129 
130 /**
131  * @brief Helper macro for creating an endpoint transfer event.
132  *
133  * @param[in] name     Name of the created transfer event variable.
134  * @param[in] endpoint Endpoint number.
135  * @param[in] ep_stat  Endpoint state to report.
136  *
137  * @return Initialized event constant variable.
138  */
139 #define NRF_USBD_COMMON_EP_TRANSFER_EVENT(name, endpont, ep_stat)                                  \
140 	const nrf_usbd_common_evt_t name = {NRF_USBD_COMMON_EVT_EPTRANSFER,                        \
141 				      .data = {.eptransfer = {.ep = endpont, .status = ep_stat}}}
142 
143 /* Check it the bit positions values match defined DATAEPSTATUS bit positions */
144 BUILD_ASSERT(
145 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPIN1) == USBD_EPDATASTATUS_EPIN1_Pos) &&
146 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPIN2) == USBD_EPDATASTATUS_EPIN2_Pos) &&
147 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPIN3) == USBD_EPDATASTATUS_EPIN3_Pos) &&
148 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPIN4) == USBD_EPDATASTATUS_EPIN4_Pos) &&
149 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPIN5) == USBD_EPDATASTATUS_EPIN5_Pos) &&
150 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPIN6) == USBD_EPDATASTATUS_EPIN6_Pos) &&
151 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPIN7) == USBD_EPDATASTATUS_EPIN7_Pos) &&
152 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPOUT1) == USBD_EPDATASTATUS_EPOUT1_Pos) &&
153 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPOUT2) == USBD_EPDATASTATUS_EPOUT2_Pos) &&
154 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPOUT3) == USBD_EPDATASTATUS_EPOUT3_Pos) &&
155 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPOUT4) == USBD_EPDATASTATUS_EPOUT4_Pos) &&
156 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPOUT5) == USBD_EPDATASTATUS_EPOUT5_Pos) &&
157 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPOUT6) == USBD_EPDATASTATUS_EPOUT6_Pos) &&
158 	(NRF_USBD_COMMON_EP_BITPOS(NRF_USBD_COMMON_EPOUT7) == USBD_EPDATASTATUS_EPOUT7_Pos),
159 	"NRF_USBD_COMMON bit positions do not match hardware"
160 );
161 
162 /**
163  * @brief Current driver state.
164  */
165 static nrfx_drv_state_t m_drv_state = NRFX_DRV_STATE_UNINITIALIZED;
166 
167 /**
168  * @brief Event handler for the driver.
169  *
170  * Event handler that would be called on events.
171  *
172  * @note Currently it cannot be null if any interrupt is activated.
173  */
174 static nrf_usbd_common_event_handler_t m_event_handler;
175 
176 /**
177  * @brief Detected state of the bus.
178  *
179  * Internal state changed in interrupts handling when
180  * RESUME or SUSPEND event is processed.
181  *
182  * Values:
183  * - true  - bus suspended
184  * - false - ongoing normal communication on the bus
185  *
186  * @note This is only the bus state and does not mean that the peripheral is in suspend state.
187  */
188 static volatile bool m_bus_suspend;
189 
190 /**
191  * @brief Direction of last received Setup transfer.
192  *
193  * This variable is used to redirect internal setup data event
194  * into selected endpoint (IN or OUT).
195  */
196 static nrf_usbd_common_ep_t m_last_setup_dir;
197 
198 /**
199  * @brief Mark endpoint readiness for DMA transfer.
200  *
201  * Bits in this variable are cleared and set in interrupts.
202  * 1 means that endpoint is ready for DMA transfer.
203  * 0 means that DMA transfer cannot be performed on selected endpoint.
204  */
205 static uint32_t m_ep_ready;
206 
207 /**
208  * @brief Mark endpoint with prepared data to transfer by DMA.
209  *
210  * This variable can be set in interrupt context or within critical section.
211  * It would be cleared only from USBD interrupt.
212  *
213  * Mask prepared USBD data for transmission.
214  * It is cleared when no more data to transmit left.
215  */
216 static uint32_t m_ep_dma_waiting;
217 
218 /* Semaphore to guard EasyDMA access.
219  * In USBD there is only one DMA channel working in background, and new transfer
220  * cannot be started when there is ongoing transfer on any other channel.
221  */
222 static K_SEM_DEFINE(dma_available, 1, 1);
223 
224 /* Endpoint on which DMA was started. */
225 static nrf_usbd_common_ep_t dma_ep;
226 
227 /**
228  * @brief Tracks whether total bytes transferred by DMA is even or odd.
229  */
230 static uint8_t m_dma_odd;
231 
232 /**
233  * @brief First time enabling after reset. Used in nRF52 errata 223.
234  */
235 static bool m_first_enable = true;
236 
237 /**
238  * @brief The structure that would hold transfer configuration to every endpoint
239  *
240  * The structure that holds all the data required by the endpoint to proceed
241  * with LIST functionality and generate quick callback directly when data
242  * buffer is ready.
243  */
244 typedef struct {
245 	nrf_usbd_common_transfer_t transfer_state;
246 	bool more_transactions;
247 	/** Number of transferred bytes in the current transfer. */
248 	size_t transfer_cnt;
249 	/** Configured endpoint size. */
250 	uint16_t max_packet_size;
251 	/** NRFX_SUCCESS or error code, never NRFX_ERROR_BUSY - this one is calculated. */
252 	nrf_usbd_common_ep_status_t status;
253 } usbd_ep_state_t;
254 
255 /**
256  * @brief The array of transfer configurations for the endpoints.
257  *
258  * The status of the transfer on each endpoint.
259  */
260 static struct {
261 	usbd_ep_state_t ep_out[NRF_USBD_COMMON_EPOUT_CNT]; /*!< Status for OUT endpoints. */
262 	usbd_ep_state_t ep_in[NRF_USBD_COMMON_EPIN_CNT];   /*!< Status for IN endpoints. */
263 } m_ep_state;
264 
265 #define NRF_USBD_COMMON_FEEDER_BUFFER_SIZE NRF_USBD_COMMON_EPSIZE
266 
267 /**
268  * @brief Buffer used to send data directly from FLASH.
269  *
270  * This is internal buffer that would be used to emulate the possibility
271  * to transfer data directly from FLASH.
272  * We do not have to care about the source of data when calling transfer functions.
273  *
274  * We do not need more buffers that one, because only one transfer can be pending
275  * at once.
276  */
277 static uint32_t m_tx_buffer[NRFX_CEIL_DIV(NRF_USBD_COMMON_FEEDER_BUFFER_SIZE, sizeof(uint32_t))];
278 
279 /* Early declaration. Documentation above definition. */
280 static void usbd_dmareq_process(void);
281 static inline void usbd_int_rise(void);
282 static void nrf_usbd_common_stop(void);
283 
284 /* Get EasyDMA end event address for given endpoint */
usbd_ep_to_endevent(nrf_usbd_common_ep_t ep)285 static volatile uint32_t *usbd_ep_to_endevent(nrf_usbd_common_ep_t ep)
286 {
287 	int ep_in = NRF_USBD_COMMON_EP_IS_IN(ep);
288 	int ep_num = NRF_USBD_COMMON_EP_NUM(ep);
289 
290 	NRF_USBD_COMMON_ASSERT_EP_VALID(ep);
291 
292 	if (!NRF_USBD_COMMON_EP_IS_ISO(ep_num)) {
293 		if (ep_in) {
294 			return &NRF_USBD->EVENTS_ENDEPIN[ep_num];
295 		} else {
296 			return &NRF_USBD->EVENTS_ENDEPOUT[ep_num];
297 		}
298 	}
299 
300 	return ep_in ? &NRF_USBD->EVENTS_ENDISOIN : &NRF_USBD->EVENTS_ENDISOOUT;
301 }
302 
303 /* Return number of bytes last transferred by EasyDMA on given endpoint */
usbd_ep_amount_get(nrf_usbd_common_ep_t ep)304 static uint32_t usbd_ep_amount_get(nrf_usbd_common_ep_t ep)
305 {
306 	int ep_in = NRF_USBD_COMMON_EP_IS_IN(ep);
307 	int ep_num = NRF_USBD_COMMON_EP_NUM(ep);
308 
309 	NRF_USBD_COMMON_ASSERT_EP_VALID(ep);
310 
311 	if (!NRF_USBD_COMMON_EP_IS_ISO(ep_num)) {
312 		if (ep_in) {
313 			return NRF_USBD->EPIN[ep_num].AMOUNT;
314 		} else {
315 			return NRF_USBD->EPOUT[ep_num].AMOUNT;
316 		}
317 	}
318 
319 	return ep_in ? NRF_USBD->ISOIN.AMOUNT : NRF_USBD->ISOOUT.AMOUNT;
320 }
321 
322 /* Start EasyDMA on given endpoint */
usbd_ep_dma_start(nrf_usbd_common_ep_t ep,uint32_t addr,size_t len)323 static void usbd_ep_dma_start(nrf_usbd_common_ep_t ep, uint32_t addr, size_t len)
324 {
325 	int ep_in = NRF_USBD_COMMON_EP_IS_IN(ep);
326 	int ep_num = NRF_USBD_COMMON_EP_NUM(ep);
327 
328 	NRF_USBD_COMMON_ASSERT_EP_VALID(ep);
329 
330 	if (!NRF_USBD_COMMON_EP_IS_ISO(ep_num)) {
331 		if (ep_in) {
332 			NRF_USBD->EPIN[ep_num].PTR = addr;
333 			NRF_USBD->EPIN[ep_num].MAXCNT = len;
334 			NRF_USBD->TASKS_STARTEPIN[ep_num] = 1;
335 		} else {
336 			NRF_USBD->EPOUT[ep_num].PTR = addr;
337 			NRF_USBD->EPOUT[ep_num].MAXCNT = len;
338 			NRF_USBD->TASKS_STARTEPOUT[ep_num] = 1;
339 		}
340 	} else if (ep_in) {
341 		NRF_USBD->ISOIN.PTR = addr;
342 		NRF_USBD->ISOIN.MAXCNT = len;
343 		NRF_USBD->TASKS_STARTISOIN = 1;
344 	} else {
345 		NRF_USBD->ISOOUT.PTR = addr;
346 		NRF_USBD->ISOOUT.MAXCNT = len;
347 		NRF_USBD->TASKS_STARTISOOUT = 1;
348 	}
349 }
350 
nrf_usbd_common_consumer(nrf_usbd_common_ep_transfer_t * p_next,nrf_usbd_common_transfer_t * p_transfer,size_t ep_size,size_t data_size)351 static bool nrf_usbd_common_consumer(nrf_usbd_common_ep_transfer_t *p_next,
352 				     nrf_usbd_common_transfer_t *p_transfer,
353 				     size_t ep_size, size_t data_size)
354 {
355 	__ASSERT_NO_MSG(ep_size >= data_size);
356 	__ASSERT_NO_MSG((p_transfer->p_data.rx == NULL) || nrfx_is_in_ram(p_transfer->p_data.rx));
357 
358 	size_t size = p_transfer->size;
359 
360 	if (size < data_size) {
361 		LOG_DBG("consumer: buffer too small: r: %u, l: %u", data_size, size);
362 		/* Buffer size to small */
363 		p_next->size = 0;
364 		p_next->p_data = p_transfer->p_data;
365 	} else {
366 		p_next->size = data_size;
367 		p_next->p_data = p_transfer->p_data;
368 		size -= data_size;
369 		p_transfer->size = size;
370 		p_transfer->p_data.addr += data_size;
371 	}
372 	return (ep_size == data_size) && (size != 0);
373 }
374 
nrf_usbd_common_feeder(nrf_usbd_common_ep_transfer_t * p_next,nrf_usbd_common_transfer_t * p_transfer,size_t ep_size)375 static bool nrf_usbd_common_feeder(nrf_usbd_common_ep_transfer_t *p_next,
376 				   nrf_usbd_common_transfer_t *p_transfer,
377 				   size_t ep_size)
378 {
379 	size_t tx_size = p_transfer->size;
380 
381 	if (tx_size > ep_size) {
382 		tx_size = ep_size;
383 	}
384 
385 	if (!nrfx_is_in_ram(p_transfer->p_data.tx)) {
386 		__ASSERT_NO_MSG(tx_size <= NRF_USBD_COMMON_FEEDER_BUFFER_SIZE);
387 		memcpy(m_tx_buffer, (p_transfer->p_data.tx), tx_size);
388 		p_next->p_data.tx = m_tx_buffer;
389 	} else {
390 		p_next->p_data = p_transfer->p_data;
391 	}
392 
393 	p_next->size = tx_size;
394 
395 	p_transfer->size -= tx_size;
396 	p_transfer->p_data.addr += tx_size;
397 
398 	if (p_transfer->flags & NRF_USBD_COMMON_TRANSFER_ZLP_FLAG) {
399 		return (tx_size != 0);
400 	} else {
401 		return (p_transfer->size != 0);
402 	}
403 }
404 
405 /**
406  * @brief Change Driver endpoint number to HAL endpoint number.
407  *
408  * @param ep Driver endpoint identifier.
409  *
410  * @return Endpoint identifier in HAL.
411  *
412  * @sa nrf_usbd_common_ep_from_hal
413  */
ep_to_hal(nrf_usbd_common_ep_t ep)414 static inline uint8_t ep_to_hal(nrf_usbd_common_ep_t ep)
415 {
416 	NRF_USBD_COMMON_ASSERT_EP_VALID(ep);
417 	return (uint8_t)ep;
418 }
419 
420 /**
421  * @brief Access selected endpoint state structure.
422  *
423  * Function used to change or just read the state of selected endpoint.
424  * It is used for internal transmission state.
425  *
426  * @param ep Endpoint number.
427  */
ep_state_access(nrf_usbd_common_ep_t ep)428 static inline usbd_ep_state_t *ep_state_access(nrf_usbd_common_ep_t ep)
429 {
430 	NRF_USBD_COMMON_ASSERT_EP_VALID(ep);
431 	return ((NRF_USBD_COMMON_EP_IS_IN(ep) ? m_ep_state.ep_in : m_ep_state.ep_out) +
432 		NRF_USBD_COMMON_EP_NUM(ep));
433 }
434 
435 /**
436  * @brief Change endpoint number to bit position.
437  *
438  * Bit positions are defined the same way as they are placed in DATAEPSTATUS register,
439  * but bits for endpoint 0 are included.
440  *
441  * @param ep Endpoint number.
442  *
443  * @return Bit position related to the given endpoint number.
444  *
445  * @sa bit2ep
446  */
ep2bit(nrf_usbd_common_ep_t ep)447 static inline uint8_t ep2bit(nrf_usbd_common_ep_t ep)
448 {
449 	NRF_USBD_COMMON_ASSERT_EP_VALID(ep);
450 	return NRF_USBD_COMMON_EP_BITPOS(ep);
451 }
452 
453 /**
454  * @brief Change bit position to endpoint number.
455  *
456  * @param bitpos Bit position.
457  *
458  * @return Endpoint number corresponding to given bit position.
459  *
460  * @sa ep2bit
461  */
bit2ep(uint8_t bitpos)462 static inline nrf_usbd_common_ep_t bit2ep(uint8_t bitpos)
463 {
464 	BUILD_ASSERT(NRF_USBD_COMMON_EPOUT_BITPOS_0 > NRF_USBD_COMMON_EPIN_BITPOS_0,
465 		     "OUT endpoint bits should be higher than IN endpoint bits");
466 	return (nrf_usbd_common_ep_t)((bitpos >= NRF_USBD_COMMON_EPOUT_BITPOS_0)
467 		? NRF_USBD_COMMON_EPOUT(bitpos - NRF_USBD_COMMON_EPOUT_BITPOS_0)
468 		: NRF_USBD_COMMON_EPIN(bitpos));
469 }
470 
471 /**
472  * @brief Mark that EasyDMA is working.
473  *
474  * Internal function to set the flag informing about EasyDMA transfer pending.
475  * This function is called always just after the EasyDMA transfer is started.
476  */
usbd_dma_pending_set(void)477 static inline void usbd_dma_pending_set(void)
478 {
479 	if (nrf_usbd_common_errata_199()) {
480 		*((volatile uint32_t *)0x40027C1C) = 0x00000082;
481 	}
482 }
483 
484 /**
485  * @brief Mark that EasyDMA is free.
486  *
487  * Internal function to clear the flag informing about EasyDMA transfer pending.
488  * This function is called always just after the finished EasyDMA transfer is detected.
489  */
usbd_dma_pending_clear(void)490 static inline void usbd_dma_pending_clear(void)
491 {
492 	if (nrf_usbd_common_errata_199()) {
493 		*((volatile uint32_t *)0x40027C1C) = 0x00000000;
494 	}
495 }
496 
497 /**
498  * @brief Abort pending transfer on selected endpoint.
499  *
500  * @param ep Endpoint number.
501  *
502  * @note
503  * This function locks interrupts that may be costly.
504  * It is good idea to test if the endpoint is still busy before calling this function:
505  * @code
506    (m_ep_dma_waiting & (1U << ep2bit(ep)))
507  * @endcode
508  * This function would check it again, but it makes it inside critical section.
509  */
usbd_ep_abort(nrf_usbd_common_ep_t ep)510 static inline void usbd_ep_abort(nrf_usbd_common_ep_t ep)
511 {
512 	unsigned int irq_lock_key = irq_lock();
513 	usbd_ep_state_t *p_state = ep_state_access(ep);
514 
515 	if (NRF_USBD_COMMON_EP_IS_OUT(ep)) {
516 		/* Host -> Device */
517 		if ((~m_ep_dma_waiting) & (1U << ep2bit(ep))) {
518 			/* If the bit in m_ep_dma_waiting in cleared - nothing would be
519 			 * processed inside transfer processing
520 			 */
521 			nrf_usbd_common_transfer_out_drop(ep);
522 		} else {
523 			p_state->more_transactions = false;
524 			m_ep_dma_waiting &= ~(1U << ep2bit(ep));
525 			m_ep_ready &= ~(1U << ep2bit(ep));
526 		}
527 		/* Aborted */
528 		p_state->status = NRF_USBD_COMMON_EP_ABORTED;
529 	} else {
530 		if (!NRF_USBD_COMMON_EP_IS_ISO(ep)) {
531 			/* Workaround: Disarm the endpoint if there is any data buffered. */
532 			if (ep != NRF_USBD_COMMON_EPIN0) {
533 				*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x800)) =
534 					0x7B6 + (2u * (NRF_USBD_COMMON_EP_NUM(ep) - 1));
535 				uint8_t temp =
536 					*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x804));
537 				temp |= (1U << 1);
538 				*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x804)) |= temp;
539 				(void)(*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x804)));
540 			} else {
541 				*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x800)) = 0x7B4;
542 				uint8_t temp =
543 					*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x804));
544 				temp |= (1U << 2);
545 				*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x804)) |= temp;
546 				(void)(*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x804)));
547 			}
548 		}
549 		if ((m_ep_dma_waiting | (~m_ep_ready)) & (1U << ep2bit(ep))) {
550 			/* Device -> Host */
551 			m_ep_dma_waiting &= ~(1U << ep2bit(ep));
552 			m_ep_ready |= 1U << ep2bit(ep);
553 
554 			p_state->more_transactions = false;
555 			p_state->status = NRF_USBD_COMMON_EP_ABORTED;
556 			NRF_USBD_COMMON_EP_TRANSFER_EVENT(evt, ep, NRF_USBD_COMMON_EP_ABORTED);
557 			m_event_handler(&evt);
558 		}
559 	}
560 
561 	irq_unlock(irq_lock_key);
562 }
563 
nrf_usbd_common_ep_abort(nrf_usbd_common_ep_t ep)564 void nrf_usbd_common_ep_abort(nrf_usbd_common_ep_t ep)
565 {
566 	/* Only abort if there is no active DMA */
567 	k_sem_take(&dma_available, K_FOREVER);
568 	usbd_ep_abort(ep);
569 	k_sem_give(&dma_available);
570 
571 	/* This function was holding DMA semaphore and could potentially prevent
572 	 * next DMA from executing. Fire IRQ handler to check if any DMA needs
573 	 * to be started.
574 	 */
575 	usbd_int_rise();
576 }
577 
578 /**
579  * @brief Abort all pending endpoints.
580  *
581  * Function aborts all pending endpoint transfers.
582  */
usbd_ep_abort_all(void)583 static void usbd_ep_abort_all(void)
584 {
585 	uint32_t ep_waiting = m_ep_dma_waiting | (m_ep_ready & NRF_USBD_COMMON_EPOUT_BIT_MASK);
586 
587 	while (ep_waiting != 0) {
588 		uint8_t bitpos = NRF_CTZ(ep_waiting);
589 
590 		if (!NRF_USBD_COMMON_EP_IS_ISO(bit2ep(bitpos))) {
591 			usbd_ep_abort(bit2ep(bitpos));
592 		}
593 		ep_waiting &= ~(1U << bitpos);
594 	}
595 
596 	m_ep_ready = (((1U << NRF_USBD_COMMON_EPIN_CNT) - 1U) << NRF_USBD_COMMON_EPIN_BITPOS_0);
597 }
598 
599 /**
600  * @brief Force the USBD interrupt into pending state.
601  *
602  * This function is used to force USBD interrupt to be processed right now.
603  * It makes it possible to process all EasyDMA access on one thread priority level.
604  */
usbd_int_rise(void)605 static inline void usbd_int_rise(void)
606 {
607 	NVIC_SetPendingIRQ(USBD_IRQn);
608 }
609 
610 /**
611  * @name USBD interrupt runtimes.
612  *
613  * Interrupt runtimes that would be vectorized using @ref m_isr.
614  * @{
615  */
616 
ev_usbreset_handler(void)617 static void ev_usbreset_handler(void)
618 {
619 	m_bus_suspend = false;
620 	m_last_setup_dir = NRF_USBD_COMMON_EPOUT0;
621 
622 	const nrf_usbd_common_evt_t evt = {.type = NRF_USBD_COMMON_EVT_RESET};
623 
624 	m_event_handler(&evt);
625 }
626 
nrf_usbd_dma_finished(nrf_usbd_common_ep_t ep)627 static void nrf_usbd_dma_finished(nrf_usbd_common_ep_t ep)
628 {
629 	/* DMA finished, track if total bytes transferred is even or odd */
630 	m_dma_odd ^= usbd_ep_amount_get(ep) & 1;
631 	usbd_dma_pending_clear();
632 	k_sem_give(&dma_available);
633 
634 	usbd_ep_state_t *p_state = ep_state_access(ep);
635 
636 	if (p_state->status == NRF_USBD_COMMON_EP_ABORTED) {
637 		/* Clear transfer information just in case */
638 		m_ep_dma_waiting &= ~(1U << ep2bit(ep));
639 	} else if (!p_state->more_transactions) {
640 		m_ep_dma_waiting &= ~(1U << ep2bit(ep));
641 
642 		if (NRF_USBD_COMMON_EP_IS_OUT(ep) || (ep == NRF_USBD_COMMON_EPIN8)) {
643 			/* Send event to the user - for an ISO IN or any OUT endpoint,
644 			 * the whole transfer is finished in this moment
645 			 */
646 			NRF_USBD_COMMON_EP_TRANSFER_EVENT(evt, ep, NRF_USBD_COMMON_EP_OK);
647 			m_event_handler(&evt);
648 		}
649 	} else if (ep == NRF_USBD_COMMON_EPOUT0) {
650 		nrf_usbd_common_setup_data_clear();
651 	}
652 }
653 
ev_sof_handler(void)654 static void ev_sof_handler(void)
655 {
656 	nrf_usbd_common_evt_t evt = {
657 		NRF_USBD_COMMON_EVT_SOF,
658 		.data = {.sof = {.framecnt = (uint16_t)NRF_USBD->FRAMECNTR}}};
659 
660 	/* Process isochronous endpoints */
661 	uint32_t iso_ready_mask = (1U << ep2bit(NRF_USBD_COMMON_EPIN8));
662 
663 	/* SIZE.ISOOUT is 0 only when no packet was received at all */
664 	if (NRF_USBD->SIZE.ISOOUT) {
665 		iso_ready_mask |= (1U << ep2bit(NRF_USBD_COMMON_EPOUT8));
666 	}
667 	m_ep_ready |= iso_ready_mask;
668 
669 	m_event_handler(&evt);
670 }
671 
672 /**
673  * @brief React on data transfer finished.
674  *
675  * Auxiliary internal function.
676  * @param ep     Endpoint number.
677  * @param bitpos Bit position for selected endpoint number.
678  */
usbd_ep_data_handler(nrf_usbd_common_ep_t ep,uint8_t bitpos)679 static void usbd_ep_data_handler(nrf_usbd_common_ep_t ep, uint8_t bitpos)
680 {
681 	LOG_DBG("USBD event: EndpointData: %x", ep);
682 	/* Mark endpoint ready for next DMA access */
683 	m_ep_ready |= (1U << bitpos);
684 
685 	if (NRF_USBD_COMMON_EP_IS_IN(ep)) {
686 		/* IN endpoint (Device -> Host) */
687 		if (0 == (m_ep_dma_waiting & (1U << bitpos))) {
688 			LOG_DBG("USBD event: EndpointData: In finished");
689 			/* No more data to be send - transmission finished */
690 			NRF_USBD_COMMON_EP_TRANSFER_EVENT(evt, ep, NRF_USBD_COMMON_EP_OK);
691 			m_event_handler(&evt);
692 		}
693 	} else {
694 		/* OUT endpoint (Host -> Device) */
695 		if (0 == (m_ep_dma_waiting & (1U << bitpos))) {
696 			LOG_DBG("USBD event: EndpointData: Out waiting");
697 			/* No buffer prepared - send event to the application */
698 			NRF_USBD_COMMON_EP_TRANSFER_EVENT(evt, ep, NRF_USBD_COMMON_EP_WAITING);
699 			m_event_handler(&evt);
700 		}
701 	}
702 }
703 
ev_setup_handler(void)704 static void ev_setup_handler(void)
705 {
706 	LOG_DBG("USBD event: Setup (rt:%.2x r:%.2x v:%.4x i:%.4x l:%u )",
707 		       NRF_USBD->BMREQUESTTYPE, NRF_USBD->BREQUEST,
708 		       NRF_USBD->WVALUEL | (NRF_USBD->WVALUEH << 8),
709 		       NRF_USBD->WINDEXL | (NRF_USBD->WINDEXH << 8),
710 		       NRF_USBD->WLENGTHL | (NRF_USBD->WLENGTHH << 8));
711 	uint8_t bmRequestType = NRF_USBD->BMREQUESTTYPE;
712 
713 	m_last_setup_dir =
714 		((bmRequestType & USBD_BMREQUESTTYPE_DIRECTION_Msk) ==
715 		 (USBD_BMREQUESTTYPE_DIRECTION_HostToDevice << USBD_BMREQUESTTYPE_DIRECTION_Pos))
716 			? NRF_USBD_COMMON_EPOUT0
717 			: NRF_USBD_COMMON_EPIN0;
718 
719 	m_ep_dma_waiting &= ~((1U << ep2bit(NRF_USBD_COMMON_EPOUT0)) |
720 			      (1U << ep2bit(NRF_USBD_COMMON_EPIN0)));
721 	m_ep_ready &= ~(1U << ep2bit(NRF_USBD_COMMON_EPOUT0));
722 	m_ep_ready |= 1U << ep2bit(NRF_USBD_COMMON_EPIN0);
723 
724 	const nrf_usbd_common_evt_t evt = {.type = NRF_USBD_COMMON_EVT_SETUP};
725 
726 	m_event_handler(&evt);
727 }
728 
ev_usbevent_handler(void)729 static void ev_usbevent_handler(void)
730 {
731 	uint32_t event = NRF_USBD->EVENTCAUSE;
732 
733 	/* Clear handled events */
734 	NRF_USBD->EVENTCAUSE = event;
735 
736 	if (event & USBD_EVENTCAUSE_ISOOUTCRC_Msk) {
737 		LOG_DBG("USBD event: ISOOUTCRC");
738 		/* Currently no support */
739 	}
740 	if (event & USBD_EVENTCAUSE_SUSPEND_Msk) {
741 		LOG_DBG("USBD event: SUSPEND");
742 		m_bus_suspend = true;
743 		const nrf_usbd_common_evt_t evt = {.type = NRF_USBD_COMMON_EVT_SUSPEND};
744 
745 		m_event_handler(&evt);
746 	}
747 	if (event & USBD_EVENTCAUSE_RESUME_Msk) {
748 		LOG_DBG("USBD event: RESUME");
749 		m_bus_suspend = false;
750 		const nrf_usbd_common_evt_t evt = {.type = NRF_USBD_COMMON_EVT_RESUME};
751 
752 		m_event_handler(&evt);
753 	}
754 	if (event & USBD_EVENTCAUSE_USBWUALLOWED_Msk) {
755 		LOG_DBG("USBD event: WUREQ (%s)", m_bus_suspend ? "In Suspend" : "Active");
756 		if (m_bus_suspend) {
757 			__ASSERT_NO_MSG(!nrf_usbd_common_suspend_check());
758 			m_bus_suspend = false;
759 
760 			NRF_USBD->DPDMVALUE = USBD_DPDMVALUE_STATE_Resume
761 				<< USBD_DPDMVALUE_STATE_Pos;
762 			NRF_USBD->TASKS_DPDMDRIVE = 1;
763 
764 			const nrf_usbd_common_evt_t evt = {.type = NRF_USBD_COMMON_EVT_WUREQ};
765 
766 			m_event_handler(&evt);
767 		}
768 	}
769 }
770 
ev_epdata_handler(uint32_t dataepstatus)771 static void ev_epdata_handler(uint32_t dataepstatus)
772 {
773 	LOG_DBG("USBD event: EndpointEPStatus: %x", dataepstatus);
774 
775 	/* All finished endpoint have to be marked as busy */
776 	while (dataepstatus) {
777 		uint8_t bitpos = NRF_CTZ(dataepstatus);
778 		nrf_usbd_common_ep_t ep = bit2ep(bitpos);
779 
780 		dataepstatus &= ~(1UL << bitpos);
781 
782 		(void)(usbd_ep_data_handler(ep, bitpos));
783 	}
784 }
785 
786 /**
787  * @brief Function to select the endpoint to start.
788  *
789  * Function that realizes algorithm to schedule right channel for EasyDMA transfer.
790  * It gets a variable with flags for the endpoints currently requiring transfer.
791  *
792  * @param[in] req Bit flags for channels currently requiring transfer.
793  *                Bits 0...8 used for IN endpoints.
794  *                Bits 16...24 used for OUT endpoints.
795  * @note
796  * This function would be never called with 0 as a @c req argument.
797  * @return The bit number of the endpoint that should be processed now.
798  */
usbd_dma_scheduler_algorithm(uint32_t req)799 static uint8_t usbd_dma_scheduler_algorithm(uint32_t req)
800 {
801 	/* Only prioritized scheduling mode is supported. */
802 	return NRF_CTZ(req);
803 }
804 
805 /**
806  * @brief Get the size of isochronous endpoint.
807  *
808  * The size of isochronous endpoint is configurable.
809  * This function returns the size of isochronous buffer taking into account
810  * current configuration.
811  *
812  * @param[in] ep Endpoint number.
813  *
814  * @return The size of endpoint buffer.
815  */
usbd_ep_iso_capacity(nrf_usbd_common_ep_t ep)816 static inline size_t usbd_ep_iso_capacity(nrf_usbd_common_ep_t ep)
817 {
818 	(void)ep;
819 
820 	if (NRF_USBD->ISOSPLIT == USBD_ISOSPLIT_SPLIT_HalfIN << USBD_ISOSPLIT_SPLIT_Pos) {
821 		return NRF_USBD_COMMON_ISOSIZE / 2;
822 	}
823 	return NRF_USBD_COMMON_ISOSIZE;
824 }
825 
826 /**
827  * @brief Process all DMA requests.
828  *
829  * Function that have to be called from USBD interrupt handler.
830  * It have to be called when all the interrupts connected with endpoints transfer
831  * and DMA transfer are already handled.
832  */
usbd_dmareq_process(void)833 static void usbd_dmareq_process(void)
834 {
835 	if ((m_ep_dma_waiting & m_ep_ready) &&
836 	    (k_sem_take(&dma_available, K_NO_WAIT) == 0)) {
837 		const bool low_power = nrf_usbd_common_suspend_check();
838 		uint32_t req;
839 
840 		while (!low_power && 0 != (req = m_ep_dma_waiting & m_ep_ready)) {
841 			uint8_t pos;
842 
843 			if (NRFX_USBD_CONFIG_DMASCHEDULER_ISO_BOOST &&
844 			    ((req & USBD_EPISO_BIT_MASK) != 0)) {
845 				pos = usbd_dma_scheduler_algorithm(req & USBD_EPISO_BIT_MASK);
846 			} else {
847 				pos = usbd_dma_scheduler_algorithm(req);
848 			}
849 			nrf_usbd_common_ep_t ep = bit2ep(pos);
850 			usbd_ep_state_t *p_state = ep_state_access(ep);
851 
852 			nrf_usbd_common_ep_transfer_t transfer;
853 			bool continue_transfer;
854 
855 			__ASSERT_NO_MSG(p_state->more_transactions);
856 
857 			if (NRF_USBD_COMMON_EP_IS_IN(ep)) {
858 				/* Device -> Host */
859 				continue_transfer = nrf_usbd_common_feeder(
860 					&transfer, &p_state->transfer_state,
861 					p_state->max_packet_size);
862 			} else {
863 				/* Host -> Device */
864 				const size_t rx_size = nrf_usbd_common_epout_size_get(ep);
865 
866 				continue_transfer = nrf_usbd_common_consumer(
867 					&transfer, &p_state->transfer_state,
868 					p_state->max_packet_size, rx_size);
869 
870 				if (transfer.p_data.rx == NULL) {
871 					/* Dropping transfer - allow processing */
872 					__ASSERT_NO_MSG(transfer.size == 0);
873 				} else if (transfer.size < rx_size) {
874 					LOG_DBG("Endpoint %x overload (r: %u, e: %u)", ep,
875 						       rx_size, transfer.size);
876 					p_state->status = NRF_USBD_COMMON_EP_OVERLOAD;
877 					m_ep_dma_waiting &= ~(1U << pos);
878 					NRF_USBD_COMMON_EP_TRANSFER_EVENT(evt, ep,
879 						NRF_USBD_COMMON_EP_OVERLOAD);
880 					m_event_handler(&evt);
881 					/* This endpoint will not be transmitted now, repeat the
882 					 * loop
883 					 */
884 					continue;
885 				} else {
886 					/* Nothing to do - only check integrity if assertions are
887 					 * enabled
888 					 */
889 					__ASSERT_NO_MSG(transfer.size == rx_size);
890 				}
891 			}
892 
893 			if (!continue_transfer) {
894 				p_state->more_transactions = false;
895 			}
896 
897 			usbd_dma_pending_set();
898 			m_ep_ready &= ~(1U << pos);
899 			if (NRF_USBD_COMMON_ISO_DEBUG || (!NRF_USBD_COMMON_EP_IS_ISO(ep))) {
900 				LOG_DBG("USB DMA process: Starting transfer on EP: %x, size: %u",
901 					ep, transfer.size);
902 			}
903 			/* Update number of currently transferred bytes */
904 			p_state->transfer_cnt += transfer.size;
905 			/* Start transfer to the endpoint buffer */
906 			dma_ep = ep;
907 			usbd_ep_dma_start(ep, transfer.p_data.addr, transfer.size);
908 
909 			/* Transfer started - exit the loop */
910 			return;
911 		}
912 		k_sem_give(&dma_available);
913 	} else {
914 		if (NRF_USBD_COMMON_DMAREQ_PROCESS_DEBUG) {
915 			LOG_DBG("USB DMA process - EasyDMA busy");
916 		}
917 	}
918 }
919 
920 /**
921  * @brief Begin errata 171.
922  */
usbd_errata_171_begin(void)923 static inline void usbd_errata_171_begin(void)
924 {
925 	unsigned int irq_lock_key = irq_lock();
926 
927 	if (*((volatile uint32_t *)(0x4006EC00)) == 0x00000000) {
928 		*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
929 		*((volatile uint32_t *)(0x4006EC14)) = 0x000000C0;
930 		*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
931 	} else {
932 		*((volatile uint32_t *)(0x4006EC14)) = 0x000000C0;
933 	}
934 
935 	irq_unlock(irq_lock_key);
936 }
937 
938 /**
939  * @brief End errata 171.
940  */
usbd_errata_171_end(void)941 static inline void usbd_errata_171_end(void)
942 {
943 	unsigned int irq_lock_key = irq_lock();
944 
945 	if (*((volatile uint32_t *)(0x4006EC00)) == 0x00000000) {
946 		*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
947 		*((volatile uint32_t *)(0x4006EC14)) = 0x00000000;
948 		*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
949 	} else {
950 		*((volatile uint32_t *)(0x4006EC14)) = 0x00000000;
951 	}
952 
953 	irq_unlock(irq_lock_key);
954 }
955 
956 /**
957  * @brief Begin erratas 187 and 211.
958  */
usbd_errata_187_211_begin(void)959 static inline void usbd_errata_187_211_begin(void)
960 {
961 	unsigned int irq_lock_key = irq_lock();
962 
963 	if (*((volatile uint32_t *)(0x4006EC00)) == 0x00000000) {
964 		*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
965 		*((volatile uint32_t *)(0x4006ED14)) = 0x00000003;
966 		*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
967 	} else {
968 		*((volatile uint32_t *)(0x4006ED14)) = 0x00000003;
969 	}
970 
971 	irq_unlock(irq_lock_key);
972 }
973 
974 /**
975  * @brief End erratas 187 and 211.
976  */
usbd_errata_187_211_end(void)977 static inline void usbd_errata_187_211_end(void)
978 {
979 	unsigned int irq_lock_key = irq_lock();
980 
981 	if (*((volatile uint32_t *)(0x4006EC00)) == 0x00000000) {
982 		*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
983 		*((volatile uint32_t *)(0x4006ED14)) = 0x00000000;
984 		*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
985 	} else {
986 		*((volatile uint32_t *)(0x4006ED14)) = 0x00000000;
987 	}
988 
989 	irq_unlock(irq_lock_key);
990 }
991 
992 /**
993  * @brief Enable USBD peripheral.
994  */
usbd_enable(void)995 static void usbd_enable(void)
996 {
997 	if (nrf_usbd_common_errata_187()) {
998 		usbd_errata_187_211_begin();
999 	}
1000 
1001 	if (nrf_usbd_common_errata_171()) {
1002 		usbd_errata_171_begin();
1003 	}
1004 
1005 	/* Enable the peripheral */
1006 	NRF_USBD->ENABLE = 1;
1007 
1008 	/* Waiting for peripheral to enable, this should take a few us */
1009 	while ((NRF_USBD->EVENTCAUSE & USBD_EVENTCAUSE_READY_Msk) == 0) {
1010 	}
1011 	NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk;
1012 
1013 	if (nrf_usbd_common_errata_171()) {
1014 		usbd_errata_171_end();
1015 	}
1016 
1017 	if (nrf_usbd_common_errata_187()) {
1018 		usbd_errata_187_211_end();
1019 	}
1020 }
1021 /** @} */
1022 
1023 /**
1024  * @name Interrupt handlers
1025  *
1026  * @{
1027  */
nrf_usbd_common_irq_handler(void)1028 void nrf_usbd_common_irq_handler(void)
1029 {
1030 	volatile uint32_t *dma_endevent;
1031 	uint32_t epdatastatus = 0;
1032 
1033 	/* Always check and clear SOF but call handler only if SOF interrupt
1034 	 * is actually enabled.
1035 	 */
1036 	if (NRF_USBD->EVENTS_SOF) {
1037 		NRF_USBD->EVENTS_SOF = 0;
1038 		if (NRF_USBD->INTENSET & USBD_INTEN_SOF_Msk) {
1039 			ev_sof_handler();
1040 		}
1041 	}
1042 
1043 	/* Clear EPDATA event and only then get and clear EPDATASTATUS to make
1044 	 * sure we don't miss any event.
1045 	 */
1046 	if (NRF_USBD->EVENTS_EPDATA) {
1047 		NRF_USBD->EVENTS_EPDATA = 0;
1048 		epdatastatus = NRF_USBD->EPDATASTATUS;
1049 		NRF_USBD->EPDATASTATUS = epdatastatus;
1050 	}
1051 
1052 	/* Use common variable to store EP0DATADONE processing needed flag */
1053 	if (NRF_USBD->EVENTS_EP0DATADONE) {
1054 		NRF_USBD->EVENTS_EP0DATADONE = 0;
1055 		epdatastatus |= BIT(ep2bit(m_last_setup_dir));
1056 	}
1057 
1058 	/* Check DMA end event only for last enabled DMA channel. Other channels
1059 	 * cannot be active and there's no harm in rechecking the event multiple
1060 	 * times (it is not a problem to check it even if DMA is not active).
1061 	 *
1062 	 * It is important to check DMA and handle DMA finished event before
1063 	 * handling acknowledged data transfer bits (epdatastatus) to avoid
1064 	 * a race condition between interrupt handler and host IN token.
1065 	 */
1066 	dma_endevent = usbd_ep_to_endevent(dma_ep);
1067 	if (*dma_endevent) {
1068 		*dma_endevent = 0;
1069 		nrf_usbd_dma_finished(dma_ep);
1070 	}
1071 
1072 	/* Process acknowledged transfers so we can prepare next DMA (if any) */
1073 	ev_epdata_handler(epdatastatus);
1074 
1075 	if (NRF_USBD->EVENTS_USBRESET) {
1076 		NRF_USBD->EVENTS_USBRESET = 0;
1077 		ev_usbreset_handler();
1078 	}
1079 
1080 	if (NRF_USBD->EVENTS_USBEVENT) {
1081 		NRF_USBD->EVENTS_USBEVENT = 0;
1082 		ev_usbevent_handler();
1083 	}
1084 
1085 	/* Handle SETUP only if there is no active DMA on EP0 */
1086 	if (unlikely(NRF_USBD->EVENTS_EP0SETUP) &&
1087 	    (k_sem_count_get(&dma_available) ||
1088 	     (dma_ep != NRF_USBD_COMMON_EPIN0 && dma_ep != NRF_USBD_COMMON_EPOUT0))) {
1089 		NRF_USBD->EVENTS_EP0SETUP = 0;
1090 		ev_setup_handler();
1091 	}
1092 
1093 	usbd_dmareq_process();
1094 }
1095 
1096 /** @} */
1097 /** @} */
1098 
nrf_usbd_common_init(nrf_usbd_common_event_handler_t event_handler)1099 nrfx_err_t nrf_usbd_common_init(nrf_usbd_common_event_handler_t event_handler)
1100 {
1101 	__ASSERT_NO_MSG(event_handler);
1102 
1103 	if (m_drv_state != NRFX_DRV_STATE_UNINITIALIZED) {
1104 		return NRFX_ERROR_INVALID_STATE;
1105 	}
1106 
1107 	m_event_handler = event_handler;
1108 	m_drv_state = NRFX_DRV_STATE_INITIALIZED;
1109 
1110 	uint8_t n;
1111 
1112 	for (n = 0; n < NRF_USBD_COMMON_EPIN_CNT; ++n) {
1113 		nrf_usbd_common_ep_t ep = NRF_USBD_COMMON_EPIN(n);
1114 
1115 		nrf_usbd_common_ep_max_packet_size_set(ep, NRF_USBD_COMMON_EP_IS_ISO(ep) ?
1116 			(NRF_USBD_COMMON_ISOSIZE / 2) : NRF_USBD_COMMON_EPSIZE);
1117 		usbd_ep_state_t *p_state = ep_state_access(ep);
1118 
1119 		p_state->status = NRF_USBD_COMMON_EP_OK;
1120 		p_state->more_transactions = false;
1121 		p_state->transfer_cnt = 0;
1122 	}
1123 	for (n = 0; n < NRF_USBD_COMMON_EPOUT_CNT; ++n) {
1124 		nrf_usbd_common_ep_t ep = NRF_USBD_COMMON_EPOUT(n);
1125 
1126 		nrf_usbd_common_ep_max_packet_size_set(ep, NRF_USBD_COMMON_EP_IS_ISO(ep) ?
1127 			(NRF_USBD_COMMON_ISOSIZE / 2) : NRF_USBD_COMMON_EPSIZE);
1128 		usbd_ep_state_t *p_state = ep_state_access(ep);
1129 
1130 		p_state->status = NRF_USBD_COMMON_EP_OK;
1131 		p_state->more_transactions = false;
1132 		p_state->transfer_cnt = 0;
1133 	}
1134 
1135 	return NRFX_SUCCESS;
1136 }
1137 
nrf_usbd_common_uninit(void)1138 void nrf_usbd_common_uninit(void)
1139 {
1140 	__ASSERT_NO_MSG(m_drv_state == NRFX_DRV_STATE_INITIALIZED);
1141 
1142 	m_event_handler = NULL;
1143 	m_drv_state = NRFX_DRV_STATE_UNINITIALIZED;
1144 }
1145 
nrf_usbd_common_enable(void)1146 void nrf_usbd_common_enable(void)
1147 {
1148 	__ASSERT_NO_MSG(m_drv_state == NRFX_DRV_STATE_INITIALIZED);
1149 
1150 	/* Prepare for READY event receiving */
1151 	NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk;
1152 
1153 	usbd_enable();
1154 
1155 	if (nrf_usbd_common_errata_223() && m_first_enable) {
1156 		NRF_USBD->ENABLE = 0;
1157 
1158 		usbd_enable();
1159 
1160 		m_first_enable = false;
1161 	}
1162 
1163 #if NRF_USBD_COMMON_USE_WORKAROUND_FOR_ANOMALY_211
1164 	if (nrf_usbd_common_errata_187() || nrf_usbd_common_errata_211())
1165 #else
1166 	if (nrf_usbd_common_errata_187())
1167 #endif
1168 	{
1169 		usbd_errata_187_211_begin();
1170 	}
1171 
1172 	if (nrf_usbd_common_errata_166()) {
1173 		*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x800)) = 0x7E3;
1174 		*((volatile uint32_t *)((uint32_t)(NRF_USBD) + 0x804)) = 0x40;
1175 		__ISB();
1176 		__DSB();
1177 	}
1178 
1179 	NRF_USBD->ISOSPLIT = USBD_ISOSPLIT_SPLIT_HalfIN << USBD_ISOSPLIT_SPLIT_Pos;
1180 
1181 	if (IS_ENABLED(CONFIG_NRF_USBD_ISO_IN_ZLP)) {
1182 		NRF_USBD->ISOINCONFIG = USBD_ISOINCONFIG_RESPONSE_ZeroData
1183 			<< USBD_ISOINCONFIG_RESPONSE_Pos;
1184 	} else {
1185 		NRF_USBD->ISOINCONFIG = USBD_ISOINCONFIG_RESPONSE_NoResp
1186 			<< USBD_ISOINCONFIG_RESPONSE_Pos;
1187 	}
1188 
1189 	m_ep_ready = (((1U << NRF_USBD_COMMON_EPIN_CNT) - 1U) << NRF_USBD_COMMON_EPIN_BITPOS_0);
1190 	m_ep_dma_waiting = 0;
1191 	m_dma_odd = 0;
1192 	__ASSERT_NO_MSG(k_sem_count_get(&dma_available) == 1);
1193 	usbd_dma_pending_clear();
1194 	m_last_setup_dir = NRF_USBD_COMMON_EPOUT0;
1195 
1196 	m_drv_state = NRFX_DRV_STATE_POWERED_ON;
1197 
1198 #if NRF_USBD_COMMON_USE_WORKAROUND_FOR_ANOMALY_211
1199 	if (nrf_usbd_common_errata_187() && !nrf_usbd_common_errata_211())
1200 #else
1201 	if (nrf_usbd_common_errata_187())
1202 #endif
1203 	{
1204 		usbd_errata_187_211_end();
1205 	}
1206 }
1207 
nrf_usbd_common_disable(void)1208 void nrf_usbd_common_disable(void)
1209 {
1210 	__ASSERT_NO_MSG(m_drv_state != NRFX_DRV_STATE_UNINITIALIZED);
1211 
1212 	/* Make sure DMA is not active */
1213 	k_sem_take(&dma_available, K_FOREVER);
1214 
1215 	/* Stop just in case */
1216 	nrf_usbd_common_stop();
1217 
1218 	/* Disable all parts */
1219 	if (m_dma_odd) {
1220 		/* Prevent invalid bus request after next USBD enable by ensuring
1221 		 * that total number of bytes transferred by DMA is even.
1222 		 */
1223 		NRF_USBD->EVENTS_ENDEPIN[0] = 0;
1224 		usbd_ep_dma_start(NRF_USBD_COMMON_EPIN0, (uint32_t)&m_dma_odd, 1);
1225 		while (!NRF_USBD->EVENTS_ENDEPIN[0]) {
1226 		}
1227 		NRF_USBD->EVENTS_ENDEPIN[0] = 0;
1228 		m_dma_odd = 0;
1229 	}
1230 	NRF_USBD->ENABLE = 0;
1231 	usbd_dma_pending_clear();
1232 	k_sem_give(&dma_available);
1233 	m_drv_state = NRFX_DRV_STATE_INITIALIZED;
1234 
1235 #if NRF_USBD_COMMON_USE_WORKAROUND_FOR_ANOMALY_211
1236 	if (nrf_usbd_common_errata_211()) {
1237 		usbd_errata_187_211_end();
1238 	}
1239 #endif
1240 }
1241 
nrf_usbd_common_start(bool enable_sof)1242 void nrf_usbd_common_start(bool enable_sof)
1243 {
1244 	__ASSERT_NO_MSG(m_drv_state == NRFX_DRV_STATE_POWERED_ON);
1245 	m_bus_suspend = false;
1246 
1247 	uint32_t int_mask = USBD_INTEN_USBRESET_Msk | USBD_INTEN_ENDEPIN0_Msk |
1248 		USBD_INTEN_ENDEPIN1_Msk | USBD_INTEN_ENDEPIN2_Msk |
1249 		USBD_INTEN_ENDEPIN3_Msk | USBD_INTEN_ENDEPIN4_Msk |
1250 		USBD_INTEN_ENDEPIN5_Msk | USBD_INTEN_ENDEPIN6_Msk |
1251 		USBD_INTEN_ENDEPIN7_Msk | USBD_INTEN_EP0DATADONE_Msk |
1252 		USBD_INTEN_ENDISOIN_Msk | USBD_INTEN_ENDEPOUT0_Msk |
1253 		USBD_INTEN_ENDEPOUT1_Msk | USBD_INTEN_ENDEPOUT2_Msk |
1254 		USBD_INTEN_ENDEPOUT3_Msk | USBD_INTEN_ENDEPOUT4_Msk |
1255 		USBD_INTEN_ENDEPOUT5_Msk | USBD_INTEN_ENDEPOUT6_Msk |
1256 		USBD_INTEN_ENDEPOUT7_Msk | USBD_INTEN_ENDISOOUT_Msk |
1257 		USBD_INTEN_USBEVENT_Msk | USBD_INTEN_EP0SETUP_Msk |
1258 		USBD_INTEN_EPDATA_Msk;
1259 
1260 	if (enable_sof) {
1261 		int_mask |= USBD_INTEN_SOF_Msk;
1262 	}
1263 
1264 	/* Enable all required interrupts */
1265 	NRF_USBD->INTEN = int_mask;
1266 
1267 	/* Enable interrupt globally */
1268 	irq_enable(USBD_IRQn);
1269 
1270 	/* Enable pullups */
1271 	NRF_USBD->USBPULLUP = 1;
1272 }
1273 
nrf_usbd_common_stop(void)1274 static void nrf_usbd_common_stop(void)
1275 {
1276 	__ASSERT_NO_MSG(m_drv_state == NRFX_DRV_STATE_POWERED_ON);
1277 
1278 	/* Clear interrupt */
1279 	NVIC_ClearPendingIRQ(USBD_IRQn);
1280 
1281 	if (irq_is_enabled(USBD_IRQn)) {
1282 		/* Abort transfers */
1283 		usbd_ep_abort_all();
1284 
1285 		/* Disable pullups */
1286 		NRF_USBD->USBPULLUP = 0;
1287 
1288 		/* Disable interrupt globally */
1289 		irq_disable(USBD_IRQn);
1290 
1291 		/* Disable all interrupts */
1292 		NRF_USBD->INTEN = 0;
1293 	}
1294 }
1295 
nrf_usbd_common_is_initialized(void)1296 bool nrf_usbd_common_is_initialized(void)
1297 {
1298 	return (m_drv_state >= NRFX_DRV_STATE_INITIALIZED);
1299 }
1300 
nrf_usbd_common_is_enabled(void)1301 bool nrf_usbd_common_is_enabled(void)
1302 {
1303 	return (m_drv_state >= NRFX_DRV_STATE_POWERED_ON);
1304 }
1305 
nrf_usbd_common_is_started(void)1306 bool nrf_usbd_common_is_started(void)
1307 {
1308 	return (nrf_usbd_common_is_enabled() && irq_is_enabled(USBD_IRQn));
1309 }
1310 
nrf_usbd_common_suspend(void)1311 bool nrf_usbd_common_suspend(void)
1312 {
1313 	bool suspended = false;
1314 	unsigned int irq_lock_key;
1315 
1316 	/* DMA doesn't work in Low Power mode, ensure there is no active DMA */
1317 	k_sem_take(&dma_available, K_FOREVER);
1318 	irq_lock_key = irq_lock();
1319 
1320 	if (m_bus_suspend) {
1321 		if (!(NRF_USBD->EVENTCAUSE & USBD_EVENTCAUSE_RESUME_Msk)) {
1322 			NRF_USBD->LOWPOWER = USBD_LOWPOWER_LOWPOWER_LowPower
1323 				<< USBD_LOWPOWER_LOWPOWER_Pos;
1324 			(void)NRF_USBD->LOWPOWER;
1325 			if (NRF_USBD->EVENTCAUSE & USBD_EVENTCAUSE_RESUME_Msk) {
1326 				NRF_USBD->LOWPOWER = USBD_LOWPOWER_LOWPOWER_ForceNormal
1327 					<< USBD_LOWPOWER_LOWPOWER_Pos;
1328 			} else {
1329 				suspended = true;
1330 			}
1331 		}
1332 	}
1333 
1334 	irq_unlock(irq_lock_key);
1335 	k_sem_give(&dma_available);
1336 
1337 	return suspended;
1338 }
1339 
nrf_usbd_common_wakeup_req(void)1340 bool nrf_usbd_common_wakeup_req(void)
1341 {
1342 	bool started = false;
1343 	unsigned int irq_lock_key = irq_lock();
1344 
1345 	if (m_bus_suspend && nrf_usbd_common_suspend_check()) {
1346 		NRF_USBD->LOWPOWER = USBD_LOWPOWER_LOWPOWER_ForceNormal
1347 			<< USBD_LOWPOWER_LOWPOWER_Pos;
1348 		started = true;
1349 
1350 		if (nrf_usbd_common_errata_171()) {
1351 			if (*((volatile uint32_t *)(0x4006EC00)) == 0x00000000) {
1352 				*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
1353 				*((volatile uint32_t *)(0x4006EC14)) = 0x000000C0;
1354 				*((volatile uint32_t *)(0x4006EC00)) = 0x00009375;
1355 			} else {
1356 				*((volatile uint32_t *)(0x4006EC14)) = 0x000000C0;
1357 			}
1358 		}
1359 	}
1360 
1361 	irq_unlock(irq_lock_key);
1362 
1363 	return started;
1364 }
1365 
nrf_usbd_common_suspend_check(void)1366 bool nrf_usbd_common_suspend_check(void)
1367 {
1368 	return NRF_USBD->LOWPOWER !=
1369 		(USBD_LOWPOWER_LOWPOWER_ForceNormal << USBD_LOWPOWER_LOWPOWER_Pos);
1370 }
1371 
nrf_usbd_common_bus_suspend_check(void)1372 bool nrf_usbd_common_bus_suspend_check(void)
1373 {
1374 	return m_bus_suspend;
1375 }
1376 
nrf_usbd_common_force_bus_wakeup(void)1377 void nrf_usbd_common_force_bus_wakeup(void)
1378 {
1379 	m_bus_suspend = false;
1380 }
1381 
nrf_usbd_common_ep_max_packet_size_set(nrf_usbd_common_ep_t ep,uint16_t size)1382 void nrf_usbd_common_ep_max_packet_size_set(nrf_usbd_common_ep_t ep, uint16_t size)
1383 {
1384 	/* Only the power of 2 size allowed for Control Endpoints */
1385 	__ASSERT_NO_MSG((((size & (size - 1)) == 0) || (NRF_USBD_COMMON_EP_NUM(ep) != 0)));
1386 	/* Only non zero size allowed for Control Endpoints */
1387 	__ASSERT_NO_MSG((size != 0) || (NRF_USBD_COMMON_EP_NUM(ep) != 0));
1388 	/* Packet size cannot be higher than maximum buffer size */
1389 	__ASSERT_NO_MSG((NRF_USBD_COMMON_EP_IS_ISO(ep) && (size <= usbd_ep_iso_capacity(ep))) ||
1390 		    (!NRF_USBD_COMMON_EP_IS_ISO(ep) && (size <= NRF_USBD_COMMON_EPSIZE)));
1391 
1392 	usbd_ep_state_t *p_state = ep_state_access(ep);
1393 
1394 	p_state->max_packet_size = size;
1395 }
1396 
nrf_usbd_common_ep_max_packet_size_get(nrf_usbd_common_ep_t ep)1397 uint16_t nrf_usbd_common_ep_max_packet_size_get(nrf_usbd_common_ep_t ep)
1398 {
1399 	usbd_ep_state_t const *p_state = ep_state_access(ep);
1400 
1401 	return p_state->max_packet_size;
1402 }
1403 
nrf_usbd_common_ep_enable_check(nrf_usbd_common_ep_t ep)1404 bool nrf_usbd_common_ep_enable_check(nrf_usbd_common_ep_t ep)
1405 {
1406 	int ep_in = NRF_USBD_COMMON_EP_IS_IN(ep);
1407 	int ep_num = NRF_USBD_COMMON_EP_NUM(ep);
1408 
1409 	NRF_USBD_COMMON_ASSERT_EP_VALID(ep);
1410 
1411 	return (ep_in ? NRF_USBD->EPINEN : NRF_USBD->EPOUTEN) & BIT(ep_num);
1412 }
1413 
nrf_usbd_common_ep_enable(nrf_usbd_common_ep_t ep)1414 void nrf_usbd_common_ep_enable(nrf_usbd_common_ep_t ep)
1415 {
1416 	int ep_in = NRF_USBD_COMMON_EP_IS_IN(ep);
1417 	int ep_num = NRF_USBD_COMMON_EP_NUM(ep);
1418 
1419 	if (nrf_usbd_common_ep_enable_check(ep)) {
1420 		return;
1421 	}
1422 
1423 	if (ep_in) {
1424 		NRF_USBD->EPINEN |= BIT(ep_num);
1425 	} else {
1426 		NRF_USBD->EPOUTEN |= BIT(ep_num);
1427 	}
1428 
1429 	if (ep >= NRF_USBD_COMMON_EPOUT1 && ep <= NRF_USBD_COMMON_EPOUT7) {
1430 		unsigned int irq_lock_key = irq_lock();
1431 
1432 		nrf_usbd_common_transfer_out_drop(ep);
1433 		m_ep_dma_waiting &= ~(1U << ep2bit(ep));
1434 
1435 		irq_unlock(irq_lock_key);
1436 	}
1437 }
1438 
nrf_usbd_common_ep_disable(nrf_usbd_common_ep_t ep)1439 void nrf_usbd_common_ep_disable(nrf_usbd_common_ep_t ep)
1440 {
1441 	int ep_in = NRF_USBD_COMMON_EP_IS_IN(ep);
1442 	int ep_num = NRF_USBD_COMMON_EP_NUM(ep);
1443 
1444 	/* Only disable endpoint if there is no active DMA */
1445 	k_sem_take(&dma_available, K_FOREVER);
1446 	usbd_ep_abort(ep);
1447 	if (ep_in) {
1448 		NRF_USBD->EPINEN &= ~BIT(ep_num);
1449 	} else {
1450 		NRF_USBD->EPOUTEN &= ~BIT(ep_num);
1451 	}
1452 	k_sem_give(&dma_available);
1453 
1454 	/* This function was holding DMA semaphore and could potentially prevent
1455 	 * next DMA from executing. Fire IRQ handler to check if any DMA needs
1456 	 * to be started.
1457 	 */
1458 	usbd_int_rise();
1459 }
1460 
nrf_usbd_common_ep_transfer(nrf_usbd_common_ep_t ep,nrf_usbd_common_transfer_t const * p_transfer)1461 nrfx_err_t nrf_usbd_common_ep_transfer(nrf_usbd_common_ep_t ep,
1462 				       nrf_usbd_common_transfer_t const *p_transfer)
1463 {
1464 	nrfx_err_t ret;
1465 	const uint8_t ep_bitpos = ep2bit(ep);
1466 	unsigned int irq_lock_key = irq_lock();
1467 
1468 	__ASSERT_NO_MSG(p_transfer != NULL);
1469 
1470 	/* Setup data transaction can go only in one direction at a time */
1471 	if ((NRF_USBD_COMMON_EP_NUM(ep) == 0) && (ep != m_last_setup_dir)) {
1472 		ret = NRFX_ERROR_INVALID_ADDR;
1473 		if (NRF_USBD_COMMON_FAILED_TRANSFERS_DEBUG &&
1474 		    (NRF_USBD_COMMON_ISO_DEBUG || (!NRF_USBD_COMMON_EP_IS_ISO(ep)))) {
1475 			LOG_DBG("Transfer failed: Invalid EPr\n");
1476 		}
1477 	} else if ((m_ep_dma_waiting | ((~m_ep_ready) & NRF_USBD_COMMON_EPIN_BIT_MASK)) &
1478 		   (1U << ep_bitpos)) {
1479 		/* IN (Device -> Host) transfer has to be transmitted out to allow new transmission
1480 		 */
1481 		ret = NRFX_ERROR_BUSY;
1482 		if (NRF_USBD_COMMON_FAILED_TRANSFERS_DEBUG) {
1483 			LOG_DBG("Transfer failed: EP is busy");
1484 		}
1485 	} else {
1486 		usbd_ep_state_t *p_state = ep_state_access(ep);
1487 
1488 		__ASSERT_NO_MSG(NRF_USBD_COMMON_EP_IS_IN(ep) ||
1489 				(p_transfer->p_data.rx == NULL) ||
1490 				(nrfx_is_in_ram(p_transfer->p_data.rx)));
1491 		p_state->more_transactions = true;
1492 		p_state->transfer_state = *p_transfer;
1493 
1494 		p_state->transfer_cnt = 0;
1495 		p_state->status = NRF_USBD_COMMON_EP_OK;
1496 		m_ep_dma_waiting |= 1U << ep_bitpos;
1497 		ret = NRFX_SUCCESS;
1498 		usbd_int_rise();
1499 	}
1500 
1501 	irq_unlock(irq_lock_key);
1502 
1503 	return ret;
1504 }
1505 
nrf_usbd_common_ep_status_get(nrf_usbd_common_ep_t ep,size_t * p_size)1506 nrf_usbd_common_ep_status_t nrf_usbd_common_ep_status_get(nrf_usbd_common_ep_t ep, size_t *p_size)
1507 {
1508 	nrf_usbd_common_ep_status_t ret;
1509 	usbd_ep_state_t const *p_state = ep_state_access(ep);
1510 	unsigned int irq_lock_key = irq_lock();
1511 
1512 	*p_size = p_state->transfer_cnt;
1513 	ret = (!p_state->more_transactions) ? p_state->status : NRF_USBD_COMMON_EP_BUSY;
1514 
1515 	irq_unlock(irq_lock_key);
1516 
1517 	return ret;
1518 }
1519 
nrf_usbd_common_epout_size_get(nrf_usbd_common_ep_t ep)1520 size_t nrf_usbd_common_epout_size_get(nrf_usbd_common_ep_t ep)
1521 {
1522 	if (NRF_USBD_COMMON_EP_IS_ISO(ep)) {
1523 		size_t size = NRF_USBD->SIZE.ISOOUT;
1524 
1525 		if ((size & USBD_SIZE_ISOOUT_ZERO_Msk) ==
1526 		    (USBD_SIZE_ISOOUT_ZERO_ZeroData << USBD_SIZE_ISOOUT_ZERO_Pos)) {
1527 			size = 0;
1528 		}
1529 		return size;
1530 	}
1531 
1532 	return NRF_USBD->SIZE.EPOUT[NRF_USBD_COMMON_EP_NUM(ep)];
1533 }
1534 
nrf_usbd_common_ep_is_busy(nrf_usbd_common_ep_t ep)1535 bool nrf_usbd_common_ep_is_busy(nrf_usbd_common_ep_t ep)
1536 {
1537 	return (0 != ((m_ep_dma_waiting | ((~m_ep_ready) & NRF_USBD_COMMON_EPIN_BIT_MASK)) &
1538 		      (1U << ep2bit(ep))));
1539 }
1540 
nrf_usbd_common_ep_stall(nrf_usbd_common_ep_t ep)1541 void nrf_usbd_common_ep_stall(nrf_usbd_common_ep_t ep)
1542 {
1543 	__ASSERT_NO_MSG(!NRF_USBD_COMMON_EP_IS_ISO(ep));
1544 
1545 	LOG_DBG("USB: EP %x stalled.", ep);
1546 	NRF_USBD->EPSTALL = (USBD_EPSTALL_STALL_Stall << USBD_EPSTALL_STALL_Pos) | ep;
1547 }
1548 
nrf_usbd_common_ep_stall_clear(nrf_usbd_common_ep_t ep)1549 void nrf_usbd_common_ep_stall_clear(nrf_usbd_common_ep_t ep)
1550 {
1551 	__ASSERT_NO_MSG(!NRF_USBD_COMMON_EP_IS_ISO(ep));
1552 
1553 	if (NRF_USBD_COMMON_EP_IS_OUT(ep) && nrf_usbd_common_ep_stall_check(ep)) {
1554 		nrf_usbd_common_transfer_out_drop(ep);
1555 	}
1556 	NRF_USBD->EPSTALL = (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | ep;
1557 }
1558 
nrf_usbd_common_ep_stall_check(nrf_usbd_common_ep_t ep)1559 bool nrf_usbd_common_ep_stall_check(nrf_usbd_common_ep_t ep)
1560 {
1561 	int ep_in = NRF_USBD_COMMON_EP_IS_IN(ep);
1562 	int ep_num = NRF_USBD_COMMON_EP_NUM(ep);
1563 
1564 	if (!NRF_USBD_COMMON_EP_IS_ISO(ep_num)) {
1565 		if (ep_in) {
1566 			return NRF_USBD->HALTED.EPIN[ep_num];
1567 		} else {
1568 			return NRF_USBD->HALTED.EPOUT[ep_num];
1569 		}
1570 	}
1571 
1572 	return false;
1573 }
1574 
nrf_usbd_common_ep_dtoggle_clear(nrf_usbd_common_ep_t ep)1575 void nrf_usbd_common_ep_dtoggle_clear(nrf_usbd_common_ep_t ep)
1576 {
1577 	__ASSERT_NO_MSG(!NRF_USBD_COMMON_EP_IS_ISO(ep));
1578 
1579 	NRF_USBD->DTOGGLE = ep | (USBD_DTOGGLE_VALUE_Nop << USBD_DTOGGLE_VALUE_Pos);
1580 	NRF_USBD->DTOGGLE = ep | (USBD_DTOGGLE_VALUE_Data0 << USBD_DTOGGLE_VALUE_Pos);
1581 }
1582 
nrf_usbd_common_setup_get(nrf_usbd_common_setup_t * p_setup)1583 void nrf_usbd_common_setup_get(nrf_usbd_common_setup_t *p_setup)
1584 {
1585 	memset(p_setup, 0, sizeof(nrf_usbd_common_setup_t));
1586 	p_setup->bmRequestType = NRF_USBD->BMREQUESTTYPE;
1587 	p_setup->bRequest = NRF_USBD->BREQUEST;
1588 	p_setup->wValue = NRF_USBD->WVALUEL | (NRF_USBD->WVALUEH << 8);
1589 	p_setup->wIndex = NRF_USBD->WINDEXL | (NRF_USBD->WINDEXH << 8);
1590 	p_setup->wLength = NRF_USBD->WLENGTHL | (NRF_USBD->WLENGTHH << 8);
1591 }
1592 
nrf_usbd_common_setup_data_clear(void)1593 void nrf_usbd_common_setup_data_clear(void)
1594 {
1595 	NRF_USBD->TASKS_EP0RCVOUT = 1;
1596 }
1597 
nrf_usbd_common_setup_clear(void)1598 void nrf_usbd_common_setup_clear(void)
1599 {
1600 	LOG_DBG(">> ep0status >>");
1601 	NRF_USBD->TASKS_EP0STATUS = 1;
1602 }
1603 
nrf_usbd_common_setup_stall(void)1604 void nrf_usbd_common_setup_stall(void)
1605 {
1606 	LOG_DBG("Setup stalled.");
1607 	NRF_USBD->TASKS_EP0STALL = 1;
1608 }
1609 
nrf_usbd_common_last_setup_dir_get(void)1610 nrf_usbd_common_ep_t nrf_usbd_common_last_setup_dir_get(void)
1611 {
1612 	return m_last_setup_dir;
1613 }
1614 
nrf_usbd_common_transfer_out_drop(nrf_usbd_common_ep_t ep)1615 void nrf_usbd_common_transfer_out_drop(nrf_usbd_common_ep_t ep)
1616 {
1617 	unsigned int irq_lock_key = irq_lock();
1618 
1619 	__ASSERT_NO_MSG(NRF_USBD_COMMON_EP_IS_OUT(ep));
1620 
1621 	m_ep_ready &= ~(1U << ep2bit(ep));
1622 	if (!NRF_USBD_COMMON_EP_IS_ISO(ep)) {
1623 		NRF_USBD->SIZE.EPOUT[NRF_USBD_COMMON_EP_NUM(ep)] = 0;
1624 	}
1625 
1626 	irq_unlock(irq_lock_key);
1627 }
1628 
1629 /** @endcond */
1630