1 /* SPDX-License-Identifier: BSD-3-Clause */
2 
3 /*
4  *  LPCUSB, an USB device driver for LPC microcontrollers
5  *  Copyright (C) 2006 Bertrik Sikken (bertrik@sikken.nl)
6  *  Copyright (c) 2016 Intel Corporation
7  *
8  *  Redistribution and use in source and binary forms, with or without
9  *  modification, are permitted provided that the following conditions are met:
10  *
11  *  1. Redistributions of source code must retain the above copyright
12  *     notice, this list of conditions and the following disclaimer.
13  *  2. Redistributions in binary form must reproduce the above copyright
14  *     notice, this list of conditions and the following disclaimer in the
15  *     documentation and/or other materials provided with the distribution.
16  *  3. The name of the author may not be used to endorse or promote products
17  *     derived from this software without specific prior written permission.
18  *
19  *  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  *  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  *  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  *  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  *  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 /**
32  * @file
33  * @brief USB device core layer APIs and structures
34  *
35  * This file contains the USB device core layer APIs and structures.
36  */
37 
38 #ifndef ZEPHYR_INCLUDE_USB_USB_DEVICE_H_
39 #define ZEPHYR_INCLUDE_USB_USB_DEVICE_H_
40 
41 #include <zephyr/drivers/usb/usb_dc.h>
42 #include <zephyr/usb/usb_ch9.h>
43 #include <zephyr/logging/log.h>
44 #include <zephyr/sys/iterable_sections.h>
45 
46 #ifdef __cplusplus
47 extern "C" {
48 #endif
49 
50 /*
51  * These macros should be used to place the USB descriptors
52  * in predetermined order in the RAM.
53  */
54 #define USBD_DEVICE_DESCR_DEFINE(p) \
55 	static __in_section(usb, descriptor_##p, 0) __used __aligned(1)
56 #define USBD_CLASS_DESCR_DEFINE(p, instance) \
57 	static __in_section(usb, descriptor_##p.1, instance) __used __aligned(1)
58 #define USBD_MISC_DESCR_DEFINE(p) \
59 	static __in_section(usb, descriptor_##p, 2) __used __aligned(1)
60 #define USBD_USER_DESCR_DEFINE(p) \
61 	static __in_section(usb, descriptor_##p, 3) __used __aligned(1)
62 #define USBD_STRING_DESCR_DEFINE(p) \
63 	static __in_section(usb, descriptor_##p, 4) __used __aligned(1)
64 #define USBD_STRING_DESCR_USER_DEFINE(p) \
65 	static __in_section(usb, descriptor_##p, 5) __used __aligned(1)
66 #define USBD_TERM_DESCR_DEFINE(p) \
67 	static __in_section(usb, descriptor_##p, 6) __used __aligned(1)
68 
69 /*
70  * This macro should be used to place the struct usb_cfg_data
71  * inside usb data section in the RAM.
72  */
73 #define USBD_DEFINE_CFG_DATA(name) \
74 	static STRUCT_SECTION_ITERABLE(usb_cfg_data, name)
75 
76 /*************************************************************************
77  *  USB configuration
78  **************************************************************************/
79 
80 #define USB_MAX_CTRL_MPS	64   /**< maximum packet size (MPS) for EP 0 */
81 #define USB_MAX_FS_BULK_MPS	64   /**< full speed MPS for bulk EP */
82 #define USB_MAX_FS_INT_MPS	64   /**< full speed MPS for interrupt EP */
83 #define USB_MAX_FS_ISO_MPS	1023 /**< full speed MPS for isochronous EP */
84 
85 /*************************************************************************
86  *  USB application interface
87  **************************************************************************/
88 
89 /**
90  * @brief USB Device Core Layer API
91  * @defgroup _usb_device_core_api USB Device Core API
92  * @since 1.5
93  * @version 1.0.0
94  * @{
95  */
96 
97 /**
98  * @brief Callback function signature for the USB Endpoint status
99  */
100 typedef void (*usb_ep_callback)(uint8_t ep,
101 				enum usb_dc_ep_cb_status_code cb_status);
102 
103 /**
104  * @brief Callback function signature for class specific requests
105  *
106  * Function which handles Class specific requests corresponding to an
107  * interface number specified in the device descriptor table. For host
108  * to device direction the 'len' and 'payload_data' contain the length
109  * of the received data and the pointer to the received data respectively.
110  * For device to host class requests, 'len' and 'payload_data' should be
111  * set by the callback function with the length and the address of the
112  * data to be transmitted buffer respectively.
113  */
114 typedef int (*usb_request_handler)(struct usb_setup_packet *setup,
115 				   int32_t *transfer_len, uint8_t **payload_data);
116 
117 /**
118  * @brief Function for interface runtime configuration
119  */
120 typedef void (*usb_interface_config)(struct usb_desc_header *head,
121 				     uint8_t bInterfaceNumber);
122 
123 /**
124  * @brief USB Endpoint Configuration
125  *
126  * This structure contains configuration for the endpoint.
127  */
128 struct usb_ep_cfg_data {
129 	/**
130 	 * Callback function for notification of data received and
131 	 * available to application or transmit done, NULL if callback
132 	 * not required by application code
133 	 */
134 	usb_ep_callback ep_cb;
135 	/**
136 	 * The number associated with the EP in the device configuration
137 	 * structure
138 	 *   IN  EP = 0x80 | \<endpoint number\>
139 	 *   OUT EP = 0x00 | \<endpoint number\>
140 	 */
141 	uint8_t ep_addr;
142 };
143 
144 /**
145  * @brief USB Interface Configuration
146  *
147  * This structure contains USB interface configuration.
148  */
149 struct usb_interface_cfg_data {
150 	/** Handler for USB Class specific Control (EP 0) communications */
151 	usb_request_handler class_handler;
152 	/** Handler for USB Vendor specific commands */
153 	usb_request_handler vendor_handler;
154 	/**
155 	 * The custom request handler gets a first chance at handling
156 	 * the request before it is handed over to the 'chapter 9' request
157 	 * handler.
158 	 * return 0 on success, -EINVAL if the request has not been handled by
159 	 *	  the custom handler and instead needs to be handled by the
160 	 *	  core USB stack. Any other error code to denote failure within
161 	 *	  the custom handler.
162 	 */
163 	usb_request_handler custom_handler;
164 };
165 
166 /**
167  * @brief USB device configuration
168  *
169  * The Application instantiates this with given parameters added
170  * using the "usb_set_config" function. Once this function is called
171  * changes to this structure will result in undefined behavior. This structure
172  * may only be updated after calls to usb_deconfig
173  */
174 struct usb_cfg_data {
175 	/**
176 	 * USB device description, see
177 	 * http://www.beyondlogic.org/usbnutshell/usb5.shtml#DeviceDescriptors
178 	 */
179 	const uint8_t *usb_device_description;
180 	/** Pointer to interface descriptor */
181 	void *interface_descriptor;
182 	/** Function for interface runtime configuration */
183 	usb_interface_config interface_config;
184 	/** Callback to be notified on USB connection status change */
185 	void (*cb_usb_status)(struct usb_cfg_data *cfg,
186 			      enum usb_dc_status_code cb_status,
187 			      const uint8_t *param);
188 	/** USB interface (Class) handler and storage space */
189 	struct usb_interface_cfg_data interface;
190 	/** Number of individual endpoints in the device configuration */
191 	uint8_t num_endpoints;
192 	/**
193 	 * Pointer to an array of endpoint structs of length equal to the
194 	 * number of EP associated with the device description,
195 	 * not including control endpoints
196 	 */
197 	struct usb_ep_cfg_data *endpoint;
198 };
199 
200 /**
201  * @brief Configure USB controller
202  *
203  * Function to configure USB controller.
204  * Configuration parameters must be valid or an error is returned
205  *
206  * @param[in] usb_descriptor USB descriptor table
207  *
208  * @return 0 on success, negative errno code on fail
209  */
210 int usb_set_config(const uint8_t *usb_descriptor);
211 
212 /**
213  * @brief Deconfigure USB controller
214  *
215  * This function returns the USB device to it's initial state
216  *
217  * @return 0 on success, negative errno code on fail
218  */
219 int usb_deconfig(void);
220 
221 /**
222  * @brief Enable the USB subsystem and associated hardware
223  *
224  * This function initializes the USB core subsystem and enables the
225  * corresponding hardware so that it can begin transmitting and receiving
226  * on the USB bus, as well as generating interrupts.
227  *
228  * Class-specific initialization and registration must be performed by the user
229  * before invoking this, so that any data or events on the bus are processed
230  * correctly by the associated class handling code.
231  *
232  * @param[in] status_cb Callback registered by user to notify
233  *                      about USB device controller state.
234  *
235  * @return 0 on success, negative errno code on fail.
236  */
237 int usb_enable(usb_dc_status_callback status_cb);
238 
239 /**
240  * @brief Disable the USB device
241  *
242  * Function to disable the USB device.
243  * Upon success, the specified USB interface is clock gated in hardware,
244  * it is no longer capable of generating interrupts.
245  *
246  * @return 0 on success, negative errno code on fail
247  */
248 int usb_disable(void);
249 
250 /**
251  * @brief Write data to the specified endpoint
252  *
253  * Function to write data to the specified endpoint. The supplied
254  * usb_ep_callback will be called when transmission is done.
255  *
256  * @param[in]  ep        Endpoint address corresponding to the one listed in the
257  *                       device configuration table
258  * @param[in]  data      Pointer to data to write
259  * @param[in]  data_len  Length of data requested to write. This may be zero for
260  *                       a zero length status packet.
261  * @param[out] bytes_ret Bytes written to the EP FIFO. This value may be NULL if
262  *                       the application expects all bytes to be written
263  *
264  * @return 0 on success, negative errno code on fail
265  */
266 int usb_write(uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *bytes_ret);
267 
268 /**
269  * @brief Read data from the specified endpoint
270  *
271  * This function is called by the Endpoint handler function, after an
272  * OUT interrupt has been received for that EP. The application must
273  * only call this function through the supplied usb_ep_callback function.
274  *
275  * @param[in]  ep           Endpoint address corresponding to the one listed in
276  *                          the device configuration table
277  * @param[in]  data         Pointer to data buffer to write to
278  * @param[in]  max_data_len Max length of data to read
279  * @param[out] ret_bytes    Number of bytes read. If data is NULL and
280  *                          max_data_len is 0 the number of bytes available
281  *                          for read is returned.
282  *
283  * @return  0 on success, negative errno code on fail
284  */
285 int usb_read(uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *ret_bytes);
286 
287 /**
288  * @brief Set STALL condition on the specified endpoint
289  *
290  * This function is called by USB device class handler code to set stall
291  * condition on endpoint.
292  *
293  * @param[in]  ep           Endpoint address corresponding to the one listed in
294  *                          the device configuration table
295  *
296  * @return  0 on success, negative errno code on fail
297  */
298 int usb_ep_set_stall(uint8_t ep);
299 
300 /**
301  * @brief Clears STALL condition on the specified endpoint
302  *
303  * This function is called by USB device class handler code to clear stall
304  * condition on endpoint.
305  *
306  * @param[in]  ep           Endpoint address corresponding to the one listed in
307  *                          the device configuration table
308  *
309  * @return  0 on success, negative errno code on fail
310  */
311 int usb_ep_clear_stall(uint8_t ep);
312 
313 /**
314  * @brief Read data from the specified endpoint
315  *
316  * This is similar to usb_ep_read, the difference being that, it doesn't
317  * clear the endpoint NAKs so that the consumer is not bogged down by further
318  * upcalls till he is done with the processing of the data. The caller should
319  * reactivate ep by invoking usb_ep_read_continue() do so.
320  *
321  * @param[in]  ep           Endpoint address corresponding to the one
322  *                          listed in the device configuration table
323  * @param[in]  data         pointer to data buffer to write to
324  * @param[in]  max_data_len max length of data to read
325  * @param[out] read_bytes   Number of bytes read. If data is NULL and
326  *                          max_data_len is 0 the number of bytes
327  *                          available for read should be returned.
328  *
329  * @return 0 on success, negative errno code on fail.
330  */
331 int usb_ep_read_wait(uint8_t ep, uint8_t *data, uint32_t max_data_len,
332 		     uint32_t *read_bytes);
333 
334 
335 /**
336  * @brief Continue reading data from the endpoint
337  *
338  * Clear the endpoint NAK and enable the endpoint to accept more data
339  * from the host. Usually called after usb_ep_read_wait() when the consumer
340  * is fine to accept more data. Thus these calls together acts as flow control
341  * mechanism.
342  *
343  * @param[in]  ep           Endpoint address corresponding to the one
344  *                          listed in the device configuration table
345  *
346  * @return 0 on success, negative errno code on fail.
347  */
348 int usb_ep_read_continue(uint8_t ep);
349 
350 /**
351  * Callback function signature for transfer completion.
352  */
353 typedef void (*usb_transfer_callback)(uint8_t ep, int tsize, void *priv);
354 
355 /* USB transfer flags */
356 #define USB_TRANS_READ       BIT(0)   /** Read transfer flag */
357 #define USB_TRANS_WRITE      BIT(1)   /** Write transfer flag */
358 #define USB_TRANS_NO_ZLP     BIT(2)   /** No zero-length packet flag */
359 
360 /**
361  * @brief Transfer management endpoint callback
362  *
363  * If a USB class driver wants to use high-level transfer functions, driver
364  * needs to register this callback as usb endpoint callback.
365  */
366 void usb_transfer_ep_callback(uint8_t ep, enum usb_dc_ep_cb_status_code);
367 
368 /**
369  * @brief Start a transfer
370  *
371  * Start a usb transfer to/from the data buffer. This function is asynchronous
372  * and can be executed in IRQ context. The provided callback will be called
373  * on transfer completion (or error) in thread context.
374  *
375  * @param[in]  ep           Endpoint address corresponding to the one
376  *                          listed in the device configuration table
377  * @param[in]  data         Pointer to data buffer to write-to/read-from
378  * @param[in]  dlen         Size of data buffer
379  * @param[in]  flags        Transfer flags (USB_TRANS_READ, USB_TRANS_WRITE...)
380  * @param[in]  cb           Function called on transfer completion/failure
381  * @param[in]  priv         Data passed back to the transfer completion callback
382  *
383  * @return 0 on success, negative errno code on fail.
384  */
385 int usb_transfer(uint8_t ep, uint8_t *data, size_t dlen, unsigned int flags,
386 		 usb_transfer_callback cb, void *priv);
387 
388 /**
389  * @brief Start a transfer and block-wait for completion
390  *
391  * Synchronous version of usb_transfer, wait for transfer completion before
392  * returning.
393  * A return value of zero can also mean that transfer was cancelled or that the
394  * endpoint is not ready. This is due to the design of transfers and usb_dc API.
395  *
396  * @param[in]  ep           Endpoint address corresponding to the one
397  *                          listed in the device configuration table
398  * @param[in]  data         Pointer to data buffer to write-to/read-from
399  * @param[in]  dlen         Size of data buffer
400  * @param[in]  flags        Transfer flags
401  *
402  * @return number of bytes transferred on success, negative errno code on fail.
403  */
404 int usb_transfer_sync(uint8_t ep, uint8_t *data, size_t dlen, unsigned int flags);
405 
406 /**
407  * @brief Cancel any ongoing transfer on the specified endpoint
408  *
409  * @param[in]  ep           Endpoint address corresponding to the one
410  *                          listed in the device configuration table
411  */
412 void usb_cancel_transfer(uint8_t ep);
413 
414 /**
415  * @brief Cancel all ongoing transfers
416  */
417 void usb_cancel_transfers(void);
418 
419 /**
420  * @brief Check that transfer is ongoing for the endpoint
421  *
422  * @param[in]  ep           Endpoint address corresponding to the one
423  *                          listed in the device configuration table
424  *
425  * @return true if transfer is ongoing, false otherwise.
426  */
427 bool usb_transfer_is_busy(uint8_t ep);
428 
429 /**
430  * @brief Start the USB remote wakeup procedure
431  *
432  * Function to request a remote wakeup.
433  * This feature must be enabled in configuration, otherwise
434  * it will always return -ENOTSUP error.
435  *
436  * @return 0 on success, negative errno code on fail,
437  *         i.e. when the bus is already active.
438  */
439 int usb_wakeup_request(void);
440 
441 /**
442  * @brief Get status of the USB remote wakeup feature
443  *
444  * @return true if remote wakeup has been enabled by the host, false otherwise.
445  */
446 bool usb_get_remote_wakeup_status(void);
447 
448 /**
449  * @brief Helper macro to place the BOS compatibility descriptor
450  *        in the right memory section.
451  */
452 #define USB_DEVICE_BOS_DESC_DEFINE_CAP \
453 	static __in_section(usb, bos_desc_area, 1) __aligned(1) __used
454 
455 /**
456  * @brief Register BOS capability descriptor
457  *
458  * This function should be used by the application to register BOS capability
459  * descriptors before the USB device stack is enabled.
460  *
461  * @param[in] hdr Pointer to BOS capability descriptor
462  */
463 void usb_bos_register_cap(void *hdr);
464 
465 /**
466  * @}
467  */
468 
469 #ifdef __cplusplus
470 }
471 #endif
472 
473 #endif /* ZEPHYR_INCLUDE_USB_USB_DEVICE_H_ */
474