xref: /aosp_15_r20/external/libusb/libusb/sync.c (revision 86b64dcb59b3a0b37502ecd56e119234366a6f7e)
1 /* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
2 /*
3  * Synchronous I/O functions for libusb
4  * Copyright © 2007-2008 Daniel Drake <[email protected]>
5  * Copyright © 2019 Nathan Hjelm <[email protected]>
6  * Copyright © 2019 Google LLC. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 #include "libusbi.h"
24 
25 #include <assert.h>
26 #include <string.h>
27 
28 /**
29  * @defgroup libusb_syncio Synchronous device I/O
30  *
31  * This page documents libusb's synchronous (blocking) API for USB device I/O.
32  * This interface is easy to use but has some limitations. More advanced users
33  * may wish to consider using the \ref libusb_asyncio "asynchronous I/O API" instead.
34  */
35 
sync_transfer_cb(struct libusb_transfer * transfer)36 static void LIBUSB_CALL sync_transfer_cb(struct libusb_transfer *transfer)
37 {
38 	usbi_dbg(TRANSFER_CTX(transfer), "actual_length=%d", transfer->actual_length);
39 
40 	int *completed = transfer->user_data;
41 	*completed = 1;
42 	/*
43 	 * Right after setting 'completed', another thread might free the transfer, so don't
44 	 * access it beyond this point. The instantiating thread (not necessarily the
45 	 * current one) interprets the result and frees the transfer.
46 	 */
47 }
48 
sync_transfer_wait_for_completion(struct libusb_transfer * transfer)49 static void sync_transfer_wait_for_completion(struct libusb_transfer *transfer)
50 {
51 	int r, *completed = transfer->user_data;
52 	struct libusb_context *ctx = HANDLE_CTX(transfer->dev_handle);
53 
54 	while (!*completed) {
55 		r = libusb_handle_events_completed(ctx, completed);
56 		if (r < 0) {
57 			if (r == LIBUSB_ERROR_INTERRUPTED)
58 				continue;
59 			usbi_err(ctx, "libusb_handle_events failed: %s, cancelling transfer and retrying",
60 				 libusb_error_name(r));
61 			libusb_cancel_transfer(transfer);
62 			continue;
63 		}
64 		if (NULL == transfer->dev_handle) {
65 			/* transfer completion after libusb_close() */
66 			transfer->status = LIBUSB_TRANSFER_NO_DEVICE;
67 			*completed = 1;
68 		}
69 	}
70 }
71 
72 /** \ingroup libusb_syncio
73  * Perform a USB control transfer.
74  *
75  * The direction of the transfer is inferred from the bmRequestType field of
76  * the setup packet.
77  *
78  * The wValue, wIndex and wLength fields values should be given in host-endian
79  * byte order.
80  *
81  * \param dev_handle a handle for the device to communicate with
82  * \param bmRequestType the request type field for the setup packet
83  * \param bRequest the request field for the setup packet
84  * \param wValue the value field for the setup packet
85  * \param wIndex the index field for the setup packet
86  * \param data a suitably-sized data buffer for either input or output
87  * (depending on direction bits within bmRequestType)
88  * \param wLength the length field for the setup packet. The data buffer should
89  * be at least this size.
90  * \param timeout timeout (in milliseconds) that this function should wait
91  * before giving up due to no response being received. For an unlimited
92  * timeout, use value 0.
93  * \returns on success, the number of bytes actually transferred
94  * \returns \ref LIBUSB_ERROR_TIMEOUT if the transfer timed out
95  * \returns \ref LIBUSB_ERROR_PIPE if the control request was not supported by the
96  * device
97  * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
98  * \returns \ref LIBUSB_ERROR_BUSY if called from event handling context
99  * \returns \ref LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
100  * the operating system and/or hardware can support (see \ref asynclimits)
101  * \returns another LIBUSB_ERROR code on other failures
102  */
libusb_control_transfer(libusb_device_handle * dev_handle,uint8_t bmRequestType,uint8_t bRequest,uint16_t wValue,uint16_t wIndex,unsigned char * data,uint16_t wLength,unsigned int timeout)103 int API_EXPORTED libusb_control_transfer(libusb_device_handle *dev_handle,
104 	uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
105 	unsigned char *data, uint16_t wLength, unsigned int timeout)
106 {
107 	struct libusb_transfer *transfer;
108 	unsigned char *buffer;
109 	int completed = 0;
110 	int r;
111 
112 	if (usbi_handling_events(HANDLE_CTX(dev_handle)))
113 		return LIBUSB_ERROR_BUSY;
114 
115 	transfer = libusb_alloc_transfer(0);
116 	if (!transfer)
117 		return LIBUSB_ERROR_NO_MEM;
118 
119 	buffer = malloc(LIBUSB_CONTROL_SETUP_SIZE + wLength);
120 	if (!buffer) {
121 		libusb_free_transfer(transfer);
122 		return LIBUSB_ERROR_NO_MEM;
123 	}
124 
125 	libusb_fill_control_setup(buffer, bmRequestType, bRequest, wValue, wIndex,
126 		wLength);
127 	if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)
128 		memcpy(buffer + LIBUSB_CONTROL_SETUP_SIZE, data, wLength);
129 
130 	libusb_fill_control_transfer(transfer, dev_handle, buffer,
131 		sync_transfer_cb, &completed, timeout);
132 	transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
133 	r = libusb_submit_transfer(transfer);
134 	if (r < 0) {
135 		libusb_free_transfer(transfer);
136 		return r;
137 	}
138 
139 	sync_transfer_wait_for_completion(transfer);
140 
141 	if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
142 		memcpy(data, libusb_control_transfer_get_data(transfer),
143 			(size_t)transfer->actual_length);
144 
145 	switch (transfer->status) {
146 	case LIBUSB_TRANSFER_COMPLETED:
147 		r = transfer->actual_length;
148 		break;
149 	case LIBUSB_TRANSFER_TIMED_OUT:
150 		r = LIBUSB_ERROR_TIMEOUT;
151 		break;
152 	case LIBUSB_TRANSFER_STALL:
153 		r = LIBUSB_ERROR_PIPE;
154 		break;
155 	case LIBUSB_TRANSFER_NO_DEVICE:
156 		r = LIBUSB_ERROR_NO_DEVICE;
157 		break;
158 	case LIBUSB_TRANSFER_OVERFLOW:
159 		r = LIBUSB_ERROR_OVERFLOW;
160 		break;
161 	case LIBUSB_TRANSFER_ERROR:
162 	case LIBUSB_TRANSFER_CANCELLED:
163 		r = LIBUSB_ERROR_IO;
164 		break;
165 	default:
166 		usbi_warn(HANDLE_CTX(dev_handle),
167 			"unrecognised status code %d", transfer->status);
168 		r = LIBUSB_ERROR_OTHER;
169 	}
170 
171 	libusb_free_transfer(transfer);
172 	return r;
173 }
174 
do_sync_bulk_transfer(struct libusb_device_handle * dev_handle,unsigned char endpoint,unsigned char * buffer,int length,int * transferred,unsigned int timeout,unsigned char type)175 static int do_sync_bulk_transfer(struct libusb_device_handle *dev_handle,
176 	unsigned char endpoint, unsigned char *buffer, int length,
177 	int *transferred, unsigned int timeout, unsigned char type)
178 {
179 	struct libusb_transfer *transfer;
180 	int completed = 0;
181 	int r;
182 
183 	if (usbi_handling_events(HANDLE_CTX(dev_handle)))
184 		return LIBUSB_ERROR_BUSY;
185 
186 	transfer = libusb_alloc_transfer(0);
187 	if (!transfer)
188 		return LIBUSB_ERROR_NO_MEM;
189 
190 	libusb_fill_bulk_transfer(transfer, dev_handle, endpoint, buffer, length,
191 		sync_transfer_cb, &completed, timeout);
192 	transfer->type = type;
193 
194 	r = libusb_submit_transfer(transfer);
195 	if (r < 0) {
196 		libusb_free_transfer(transfer);
197 		return r;
198 	}
199 
200 	sync_transfer_wait_for_completion(transfer);
201 
202 	if (transferred) {
203 		assert(transfer->actual_length >= 0);
204 		*transferred = transfer->actual_length;
205 	}
206 
207 	switch (transfer->status) {
208 	case LIBUSB_TRANSFER_COMPLETED:
209 		r = 0;
210 		break;
211 	case LIBUSB_TRANSFER_TIMED_OUT:
212 		r = LIBUSB_ERROR_TIMEOUT;
213 		break;
214 	case LIBUSB_TRANSFER_STALL:
215 		r = LIBUSB_ERROR_PIPE;
216 		break;
217 	case LIBUSB_TRANSFER_OVERFLOW:
218 		r = LIBUSB_ERROR_OVERFLOW;
219 		break;
220 	case LIBUSB_TRANSFER_NO_DEVICE:
221 		r = LIBUSB_ERROR_NO_DEVICE;
222 		break;
223 	case LIBUSB_TRANSFER_ERROR:
224 	case LIBUSB_TRANSFER_CANCELLED:
225 		r = LIBUSB_ERROR_IO;
226 		break;
227 	default:
228 		usbi_warn(HANDLE_CTX(dev_handle),
229 			"unrecognised status code %d", transfer->status);
230 		r = LIBUSB_ERROR_OTHER;
231 	}
232 
233 	libusb_free_transfer(transfer);
234 	return r;
235 }
236 
237 /** \ingroup libusb_syncio
238  * Perform a USB bulk transfer. The direction of the transfer is inferred from
239  * the direction bits of the endpoint address.
240  *
241  * For bulk reads, the <tt>length</tt> field indicates the maximum length of
242  * data you are expecting to receive. If less data arrives than expected,
243  * this function will return that data, so be sure to check the
244  * <tt>transferred</tt> output parameter.
245  *
246  * You should also check the <tt>transferred</tt> parameter for bulk writes.
247  * Not all of the data may have been written.
248  *
249  * Also check <tt>transferred</tt> when dealing with a timeout error code.
250  * libusb may have to split your transfer into a number of chunks to satisfy
251  * underlying O/S requirements, meaning that the timeout may expire after
252  * the first few chunks have completed. libusb is careful not to lose any data
253  * that may have been transferred; do not assume that timeout conditions
254  * indicate a complete lack of I/O. See \ref asynctimeout for more details.
255  *
256  * \param dev_handle a handle for the device to communicate with
257  * \param endpoint the address of a valid endpoint to communicate with
258  * \param data a suitably-sized data buffer for either input or output
259  * (depending on endpoint)
260  * \param length for bulk writes, the number of bytes from data to be sent. for
261  * bulk reads, the maximum number of bytes to receive into the data buffer.
262  * \param transferred output location for the number of bytes actually
263  * transferred. Since version 1.0.21 (\ref LIBUSB_API_VERSION >= 0x01000105),
264  * it is legal to pass a NULL pointer if you do not wish to receive this
265  * information.
266  * \param timeout timeout (in milliseconds) that this function should wait
267  * before giving up due to no response being received. For an unlimited
268  * timeout, use value 0.
269  *
270  * \returns 0 on success (and populates <tt>transferred</tt>)
271  * \returns \ref LIBUSB_ERROR_TIMEOUT if the transfer timed out (and populates
272  * <tt>transferred</tt>)
273  * \returns \ref LIBUSB_ERROR_PIPE if the endpoint halted
274  * \returns \ref LIBUSB_ERROR_OVERFLOW if the device offered more data, see
275  * \ref libusb_packetoverflow
276  * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
277  * \returns \ref LIBUSB_ERROR_BUSY if called from event handling context
278  * \returns \ref LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
279  * the operating system and/or hardware can support (see \ref asynclimits)
280  * \returns another LIBUSB_ERROR code on other failures
281  */
libusb_bulk_transfer(libusb_device_handle * dev_handle,unsigned char endpoint,unsigned char * data,int length,int * transferred,unsigned int timeout)282 int API_EXPORTED libusb_bulk_transfer(libusb_device_handle *dev_handle,
283 	unsigned char endpoint, unsigned char *data, int length,
284 	int *transferred, unsigned int timeout)
285 {
286 	return do_sync_bulk_transfer(dev_handle, endpoint, data, length,
287 		transferred, timeout, LIBUSB_TRANSFER_TYPE_BULK);
288 }
289 
290 /** \ingroup libusb_syncio
291  * Perform a USB interrupt transfer. The direction of the transfer is inferred
292  * from the direction bits of the endpoint address.
293  *
294  * For interrupt reads, the <tt>length</tt> field indicates the maximum length
295  * of data you are expecting to receive. If less data arrives than expected,
296  * this function will return that data, so be sure to check the
297  * <tt>transferred</tt> output parameter.
298  *
299  * You should also check the <tt>transferred</tt> parameter for interrupt
300  * writes. Not all of the data may have been written.
301  *
302  * Also check <tt>transferred</tt> when dealing with a timeout error code.
303  * libusb may have to split your transfer into a number of chunks to satisfy
304  * underlying O/S requirements, meaning that the timeout may expire after
305  * the first few chunks have completed. libusb is careful not to lose any data
306  * that may have been transferred; do not assume that timeout conditions
307  * indicate a complete lack of I/O. See \ref asynctimeout for more details.
308  *
309  * The default endpoint bInterval value is used as the polling interval.
310  *
311  * \param dev_handle a handle for the device to communicate with
312  * \param endpoint the address of a valid endpoint to communicate with
313  * \param data a suitably-sized data buffer for either input or output
314  * (depending on endpoint)
315  * \param length for bulk writes, the number of bytes from data to be sent. for
316  * bulk reads, the maximum number of bytes to receive into the data buffer.
317  * \param transferred output location for the number of bytes actually
318  * transferred. Will never be negative. Since version 1.0.21
319  * (\ref LIBUSB_API_VERSION >= 0x01000105), it is legal to pass a NULL
320  * pointer if you do not wish to receive this information.
321  * \param timeout timeout (in milliseconds) that this function should wait
322  * before giving up due to no response being received. For an unlimited
323  * timeout, use value 0.
324  *
325  * \returns 0 on success (and populates <tt>transferred</tt>)
326  * \returns \ref LIBUSB_ERROR_TIMEOUT if the transfer timed out
327  * \returns \ref LIBUSB_ERROR_PIPE if the endpoint halted
328  * \returns \ref LIBUSB_ERROR_OVERFLOW if the device offered more data, see
329  * \ref libusb_packetoverflow
330  * \returns \ref LIBUSB_ERROR_NO_DEVICE if the device has been disconnected
331  * \returns \ref LIBUSB_ERROR_BUSY if called from event handling context
332  * \returns \ref LIBUSB_ERROR_INVALID_PARAM if the transfer size is larger than
333  * the operating system and/or hardware can support (see \ref asynclimits)
334  * \returns another LIBUSB_ERROR code on other error
335  */
libusb_interrupt_transfer(libusb_device_handle * dev_handle,unsigned char endpoint,unsigned char * data,int length,int * transferred,unsigned int timeout)336 int API_EXPORTED libusb_interrupt_transfer(libusb_device_handle *dev_handle,
337 	unsigned char endpoint, unsigned char *data, int length,
338 	int *transferred, unsigned int timeout)
339 {
340 	return do_sync_bulk_transfer(dev_handle, endpoint, data, length,
341 		transferred, timeout, LIBUSB_TRANSFER_TYPE_INTERRUPT);
342 }
343