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