]> sigrok.org Git - libsigrok.git/blame - src/usb.c
Doxygen: Properly mark a few symbols as private.
[libsigrok.git] / src / usb.c
CommitLineData
0c632d36 1/*
50985c20 2 * This file is part of the libsigrok project.
0c632d36
UH
3 *
4 * Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
c2bf5506 6 * Copyright (C) 2015 Daniel Elstner <daniel.kitta@gmail.com>
0c632d36 7 *
c2bf5506 8 * This program is free software: you can redistribute it and/or modify
0c632d36 9 * it under the terms of the GNU General Public License as published by
c2bf5506 10 * the Free Software Foundation, either version 3 of the License, or
0c632d36
UH
11 * (at your option) any later version.
12 *
13 * This program 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
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
c2bf5506 19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
0c632d36
UH
20 */
21
6ec6c43b 22#include <config.h>
0c632d36 23#include <stdlib.h>
db156e54 24#include <memory.h>
0c632d36
UH
25#include <glib.h>
26#include <libusb.h>
c1aae900 27#include <libsigrok/libsigrok.h>
0c632d36
UH
28#include "libsigrok-internal.h"
29
1953564a 30/* SR_CONF_CONN takes one of these: */
039a2fd7 31#define CONN_USB_VIDPID "^([0-9a-fA-F]{4})\\.([0-9a-fA-F]{4})$"
0c632d36
UH
32#define CONN_USB_BUSADDR "^(\\d+)\\.(\\d+)$"
33
3544f848 34#define LOG_PREFIX "usb"
0c632d36 35
c1adbb1e
DE
36#if !HAVE_LIBUSB_OS_HANDLE
37typedef int libusb_os_handle;
38#endif
39
c2bf5506 40/** Custom GLib event source for libusb I/O.
c2bf5506
DE
41 */
42struct usb_source {
43 GSource base;
44
45 int64_t timeout_us;
46 int64_t due_us;
47
48 /* Needed to keep track of installed sources */
49 struct sr_session *session;
50
51 struct libusb_context *usb_ctx;
52 GPtrArray *pollfds;
53};
54
55/** USB event source prepare() method.
56 */
57static gboolean usb_source_prepare(GSource *source, int *timeout)
58{
59 int64_t now_us, usb_due_us;
60 struct usb_source *usource;
61 struct timeval usb_timeout;
62 int remaining_ms;
63 int ret;
64
65 usource = (struct usb_source *)source;
66
67 ret = libusb_get_next_timeout(usource->usb_ctx, &usb_timeout);
68 if (G_UNLIKELY(ret < 0)) {
69 sr_err("Failed to get libusb timeout: %s",
70 libusb_error_name(ret));
71 }
72 now_us = g_source_get_time(source);
73
74 if (usource->due_us == 0) {
75 /* First-time initialization of the expiration time */
76 usource->due_us = now_us + usource->timeout_us;
77 }
78 if (ret == 1) {
79 usb_due_us = (int64_t)usb_timeout.tv_sec * G_USEC_PER_SEC
80 + usb_timeout.tv_usec + now_us;
81 if (usb_due_us < usource->due_us)
82 usource->due_us = usb_due_us;
83 }
84 if (usource->due_us != INT64_MAX)
85 remaining_ms = (MAX(0, usource->due_us - now_us) + 999) / 1000;
86 else
87 remaining_ms = -1;
88
89 *timeout = remaining_ms;
90
91 return (remaining_ms == 0);
92}
93
94/** USB event source check() method.
95 */
96static gboolean usb_source_check(GSource *source)
97{
98 struct usb_source *usource;
99 GPollFD *pollfd;
100 unsigned int revents;
101 unsigned int i;
102
103 usource = (struct usb_source *)source;
104 revents = 0;
105
106 for (i = 0; i < usource->pollfds->len; i++) {
107 pollfd = g_ptr_array_index(usource->pollfds, i);
108 revents |= pollfd->revents;
109 }
110 return (revents != 0 || (usource->due_us != INT64_MAX
111 && usource->due_us <= g_source_get_time(source)));
112}
113
114/** USB event source dispatch() method.
115 */
116static gboolean usb_source_dispatch(GSource *source,
117 GSourceFunc callback, void *user_data)
118{
119 struct usb_source *usource;
120 GPollFD *pollfd;
121 unsigned int revents;
122 unsigned int i;
123 gboolean keep;
124
125 usource = (struct usb_source *)source;
126 revents = 0;
127 /*
128 * This is somewhat arbitrary, but drivers use revents to distinguish
129 * actual I/O from timeouts. When we remove the user timeout from the
130 * driver API, this will no longer be needed.
131 */
132 for (i = 0; i < usource->pollfds->len; i++) {
133 pollfd = g_ptr_array_index(usource->pollfds, i);
134 revents |= pollfd->revents;
135 }
c2bf5506
DE
136
137 if (!callback) {
138 sr_err("Callback not set, cannot dispatch event.");
139 return G_SOURCE_REMOVE;
140 }
141 keep = (*(sr_receive_data_callback)callback)(-1, revents, user_data);
142
143 if (G_LIKELY(keep) && G_LIKELY(!g_source_is_destroyed(source))) {
144 if (usource->timeout_us >= 0)
145 usource->due_us = g_source_get_time(source)
146 + usource->timeout_us;
147 else
148 usource->due_us = INT64_MAX;
149 }
150 return keep;
151}
152
153/** USB event source finalize() method.
154 */
155static void usb_source_finalize(GSource *source)
156{
157 struct usb_source *usource;
158
159 usource = (struct usb_source *)source;
160
161 sr_spew("%s", __func__);
162
163 libusb_set_pollfd_notifiers(usource->usb_ctx, NULL, NULL, NULL);
164
165 g_ptr_array_unref(usource->pollfds);
166 usource->pollfds = NULL;
167
168 sr_session_source_destroyed(usource->session,
169 usource->usb_ctx, source);
170}
171
172/** Callback invoked when a new libusb FD should be added to the poll set.
173 */
174static LIBUSB_CALL void usb_pollfd_added(libusb_os_handle fd,
175 short events, void *user_data)
176{
177 struct usb_source *usource;
178 GPollFD *pollfd;
179
180 usource = user_data;
181
5eff221e
DE
182 if (G_UNLIKELY(g_source_is_destroyed(&usource->base)))
183 return;
184
c2bf5506 185 pollfd = g_slice_new(GPollFD);
00f0016c 186#ifdef _WIN32
c2bf5506
DE
187 events = G_IO_IN;
188#endif
189 pollfd->fd = (gintptr)fd;
190 pollfd->events = events;
191 pollfd->revents = 0;
192
193 g_ptr_array_add(usource->pollfds, pollfd);
5eff221e 194 g_source_add_poll(&usource->base, pollfd);
c2bf5506
DE
195}
196
197/** Callback invoked when a libusb FD should be removed from the poll set.
198 */
199static LIBUSB_CALL void usb_pollfd_removed(libusb_os_handle fd, void *user_data)
200{
201 struct usb_source *usource;
202 GPollFD *pollfd;
203 unsigned int i;
204
205 usource = user_data;
206
5eff221e
DE
207 if (G_UNLIKELY(g_source_is_destroyed(&usource->base)))
208 return;
209
c2bf5506
DE
210 /* It's likely that the removed poll FD is at the end.
211 */
212 for (i = usource->pollfds->len; G_LIKELY(i > 0); i--) {
213 pollfd = g_ptr_array_index(usource->pollfds, i - 1);
214
215 if ((libusb_os_handle)pollfd->fd == fd) {
5eff221e 216 g_source_remove_poll(&usource->base, pollfd);
c2bf5506
DE
217 g_ptr_array_remove_index_fast(usource->pollfds, i - 1);
218 return;
219 }
220 }
221 sr_err("FD to be removed (%" G_GINTPTR_FORMAT
222 ") not found in event source poll set.", (gintptr)fd);
223}
224
225/** Destroy notify callback for FDs maintained by the USB event source.
226 */
227static void usb_source_free_pollfd(void *data)
228{
229 g_slice_free(GPollFD, data);
230}
231
232/** Create an event source for libusb I/O.
233 *
234 * TODO: The combination of the USB I/O source with a user timeout is
235 * conceptually broken. The user timeout supplied here is completely
236 * unrelated to I/O -- the actual I/O timeout is set when submitting
237 * a USB transfer.
238 * The sigrok drivers generally use the timeout to poll device state.
239 * Usually, this polling can be sensibly done only when there is no
240 * active USB transfer -- i.e. it's actually mutually exclusive with
241 * waiting for transfer completion.
242 * Thus, the user timeout should be removed from the USB event source
243 * API at some point. Instead, drivers should install separate timer
244 * event sources for their polling needs.
245 *
246 * @param session The session the event source belongs to.
247 * @param usb_ctx The libusb context for which to handle events.
248 * @param timeout_ms The timeout interval in ms, or -1 to wait indefinitely.
249 * @return A new event source object, or NULL on failure.
250 */
251static GSource *usb_source_new(struct sr_session *session,
252 struct libusb_context *usb_ctx, int timeout_ms)
253{
254 static GSourceFuncs usb_source_funcs = {
255 .prepare = &usb_source_prepare,
256 .check = &usb_source_check,
257 .dispatch = &usb_source_dispatch,
258 .finalize = &usb_source_finalize
259 };
260 GSource *source;
261 struct usb_source *usource;
262 const struct libusb_pollfd **upollfds, **upfd;
263
264 upollfds = libusb_get_pollfds(usb_ctx);
265 if (!upollfds) {
266 sr_err("Failed to get libusb file descriptors.");
267 return NULL;
268 }
269 source = g_source_new(&usb_source_funcs, sizeof(struct usb_source));
270 usource = (struct usb_source *)source;
271
272 g_source_set_name(source, "usb");
273
274 if (timeout_ms >= 0) {
275 usource->timeout_us = 1000 * (int64_t)timeout_ms;
276 usource->due_us = 0;
277 } else {
278 usource->timeout_us = -1;
279 usource->due_us = INT64_MAX;
280 }
281 usource->session = session;
282 usource->usb_ctx = usb_ctx;
283 usource->pollfds = g_ptr_array_new_full(8, &usb_source_free_pollfd);
284
285 for (upfd = upollfds; *upfd != NULL; upfd++)
286 usb_pollfd_added((*upfd)->fd, (*upfd)->events, usource);
287
288#if (LIBUSB_API_VERSION >= 0x01000104)
289 libusb_free_pollfds(upollfds);
290#else
291 free(upollfds);
292#endif
293 libusb_set_pollfd_notifiers(usb_ctx,
294 &usb_pollfd_added, &usb_pollfd_removed, usource);
295
296 return source;
297}
298
7ae6a758
BV
299/**
300 * Find USB devices according to a connection string.
301 *
302 * @param usb_ctx libusb context to use while scanning.
303 * @param conn Connection string specifying the device(s) to match. This
304 * can be of the form "<bus>.<address>", or "<vendorid>.<productid>".
305 *
306 * @return A GSList of struct sr_usb_dev_inst, with bus and address fields
307 * matching the device that matched the connection string. The GSList and
308 * its contents must be freed by the caller.
309 */
310SR_PRIV GSList *sr_usb_find(libusb_context *usb_ctx, const char *conn)
0c632d36 311{
7ae6a758 312 struct sr_usb_dev_inst *usb;
0c632d36
UH
313 struct libusb_device **devlist;
314 struct libusb_device_descriptor des;
315 GSList *devices;
316 GRegex *reg;
317 GMatchInfo *match;
318 int vid, pid, bus, addr, b, a, ret, i;
319 char *mstr;
320
321 vid = pid = bus = addr = 0;
322 reg = g_regex_new(CONN_USB_VIDPID, 0, 0, NULL);
323 if (g_regex_match(reg, conn, 0, &match)) {
e7f378fd 324 if ((mstr = g_match_info_fetch(match, 1)))
0c632d36 325 vid = strtoul(mstr, NULL, 16);
0c632d36
UH
326 g_free(mstr);
327
e7f378fd 328 if ((mstr = g_match_info_fetch(match, 2)))
0c632d36 329 pid = strtoul(mstr, NULL, 16);
0c632d36 330 g_free(mstr);
91057d2f 331 /* Trying to find USB device via VID:PID. */
0c632d36
UH
332 } else {
333 g_match_info_unref(match);
334 g_regex_unref(reg);
335 reg = g_regex_new(CONN_USB_BUSADDR, 0, 0, NULL);
336 if (g_regex_match(reg, conn, 0, &match)) {
e7f378fd 337 if ((mstr = g_match_info_fetch(match, 1)))
1eb0a0df 338 bus = strtoul(mstr, NULL, 10);
0c632d36
UH
339 g_free(mstr);
340
e7f378fd 341 if ((mstr = g_match_info_fetch(match, 2)))
1eb0a0df 342 addr = strtoul(mstr, NULL, 10);
0c632d36 343 g_free(mstr);
91057d2f 344 /* Trying to find USB device via bus.address. */
0c632d36
UH
345 }
346 }
347 g_match_info_unref(match);
348 g_regex_unref(reg);
349
350 if (vid + pid + bus + addr == 0) {
e7f378fd 351 sr_err("Neither VID:PID nor bus.address was specified.");
0c632d36
UH
352 return NULL;
353 }
354
e4ce146f 355 if (bus > 255) {
0c632d36
UH
356 sr_err("Invalid bus specified: %d.", bus);
357 return NULL;
358 }
359
360 if (addr > 127) {
361 sr_err("Invalid address specified: %d.", addr);
362 return NULL;
363 }
364
365 /* Looks like a valid USB device specification, but is it connected? */
366 devices = NULL;
367 libusb_get_device_list(usb_ctx, &devlist);
368 for (i = 0; devlist[i]; i++) {
369 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
d4928d71
PS
370 sr_err("Failed to get device descriptor: %s.",
371 libusb_error_name(ret));
0c632d36
UH
372 continue;
373 }
374
7ae6a758 375 if (vid + pid && (des.idVendor != vid || des.idProduct != pid))
0c632d36 376 continue;
0c632d36 377
7ae6a758
BV
378 b = libusb_get_bus_number(devlist[i]);
379 a = libusb_get_device_address(devlist[i]);
380 if (bus + addr && (b != bus || a != addr))
0c632d36 381 continue;
0c632d36
UH
382
383 sr_dbg("Found USB device (VID:PID = %04x:%04x, bus.address = "
384 "%d.%d).", des.idVendor, des.idProduct, b, a);
385
6f63b1ee 386 usb = sr_usb_dev_inst_new(b, a, NULL);
7ae6a758 387 devices = g_slist_append(devices, usb);
0c632d36
UH
388 }
389 libusb_free_device_list(devlist, 1);
390
91057d2f 391 /* No log message for #devices found (caller will log that). */
176d785d 392
0c632d36
UH
393 return devices;
394}
395
396SR_PRIV int sr_usb_open(libusb_context *usb_ctx, struct sr_usb_dev_inst *usb)
397{
398 struct libusb_device **devlist;
399 struct libusb_device_descriptor des;
400 int ret, r, cnt, i, a, b;
401
c5f1a021 402 sr_dbg("Trying to open USB device %d.%d.", usb->bus, usb->address);
0c632d36
UH
403
404 if ((cnt = libusb_get_device_list(usb_ctx, &devlist)) < 0) {
405 sr_err("Failed to retrieve device list: %s.",
406 libusb_error_name(cnt));
407 return SR_ERR;
408 }
409
410 ret = SR_ERR;
411 for (i = 0; i < cnt; i++) {
412 if ((r = libusb_get_device_descriptor(devlist[i], &des)) < 0) {
413 sr_err("Failed to get device descriptor: %s.",
414 libusb_error_name(r));
415 continue;
416 }
417
418 b = libusb_get_bus_number(devlist[i]);
419 a = libusb_get_device_address(devlist[i]);
c5f1a021 420 if (b != usb->bus || a != usb->address)
0c632d36 421 continue;
0c632d36
UH
422
423 if ((r = libusb_open(devlist[i], &usb->devhdl)) < 0) {
424 sr_err("Failed to open device: %s.",
425 libusb_error_name(r));
426 break;
427 }
428
429 sr_dbg("Opened USB device (VID:PID = %04x:%04x, bus.address = "
430 "%d.%d).", des.idVendor, des.idProduct, b, a);
431
432 ret = SR_OK;
433 break;
434 }
435
436 libusb_free_device_list(devlist, 1);
437
438 return ret;
439}
6c60facc 440
67e95ed3
BV
441SR_PRIV void sr_usb_close(struct sr_usb_dev_inst *usb)
442{
443 libusb_close(usb->devhdl);
444 usb->devhdl = NULL;
445 sr_dbg("Closed USB device %d.%d.", usb->bus, usb->address);
446}
447
102f1239
BV
448SR_PRIV int usb_source_add(struct sr_session *session, struct sr_context *ctx,
449 int timeout, sr_receive_data_callback cb, void *cb_data)
6c60facc 450{
c2bf5506 451 GSource *source;
92248e78
DE
452 int ret;
453
c2bf5506
DE
454 source = usb_source_new(session, ctx->libusb_ctx, timeout);
455 if (!source)
92248e78 456 return SR_ERR;
534b634c 457
c2bf5506 458 g_source_set_callback(source, (GSourceFunc)cb, cb_data, NULL);
534b634c 459
c2bf5506
DE
460 ret = sr_session_source_add_internal(session, ctx->libusb_ctx, source);
461 g_source_unref(source);
4b9e2532 462
c2bf5506 463 return ret;
6c60facc
ML
464}
465
102f1239 466SR_PRIV int usb_source_remove(struct sr_session *session, struct sr_context *ctx)
6c60facc 467{
c2bf5506 468 return sr_session_source_remove_internal(session, ctx->libusb_ctx);
6c60facc 469}
db156e54 470
76bc5f63 471SR_PRIV int usb_get_port_path(libusb_device *dev, char *path, int path_len)
db156e54 472{
76bc5f63
AJ
473 uint8_t port_numbers[8];
474 int i, n, len;
475
19643b96
UJ
476/*
477 * FreeBSD requires that devices prior to calling libusb_get_port_numbers()
478 * have been opened with libusb_open().
b98b7022 479 * This apparently also applies to some Mac OS X versions.
19643b96 480 */
b98b7022 481#if defined(__FreeBSD__) || defined(__APPLE__)
19643b96
UJ
482 struct libusb_device_handle *devh;
483 if (libusb_open(dev, &devh) != 0)
484 return SR_ERR;
485#endif
76bc5f63 486 n = libusb_get_port_numbers(dev, port_numbers, sizeof(port_numbers));
b98b7022 487#if defined(__FreeBSD__) || defined(__APPLE__)
19643b96
UJ
488 libusb_close(devh);
489#endif
76bc5f63 490
b98b7022
UH
491/* Workaround FreeBSD / Mac OS X libusb_get_port_numbers() returning 0. */
492#if defined(__FreeBSD__) || defined(__APPLE__)
19643b96
UJ
493 if (n == 0) {
494 port_numbers[0] = libusb_get_device_address(dev);
495 n = 1;
496 }
497#endif
2f004b4b
VP
498 if (n < 1)
499 return SR_ERR;
500
76bc5f63
AJ
501 len = snprintf(path, path_len, "usb/%d-%d",
502 libusb_get_bus_number(dev), port_numbers[0]);
db156e54 503
76bc5f63
AJ
504 for (i = 1; i < n; i++)
505 len += snprintf(path+len, path_len-len, ".%d", port_numbers[i]);
db156e54
SA
506
507 return SR_OK;
508}
69f7d9b4
JH
509
510/**
07182332 511 * Check the USB configuration to determine if this device has a given
69f7d9b4
JH
512 * manufacturer and product string.
513 *
514 * @return TRUE if the device's configuration profile strings
515 * configuration, FALSE otherwise.
516 */
517SR_PRIV gboolean usb_match_manuf_prod(libusb_device *dev,
518 const char *manufacturer, const char *product)
519{
520 struct libusb_device_descriptor des;
521 struct libusb_device_handle *hdl;
522 gboolean ret;
523 unsigned char strdesc[64];
524
525 hdl = NULL;
526 ret = FALSE;
527 while (!ret) {
528 /* Assume the FW has not been loaded, unless proven wrong. */
529 libusb_get_device_descriptor(dev, &des);
530
531 if (libusb_open(dev, &hdl) != 0)
532 break;
533
534 if (libusb_get_string_descriptor_ascii(hdl,
535 des.iManufacturer, strdesc, sizeof(strdesc)) < 0)
536 break;
537 if (strcmp((const char *)strdesc, manufacturer))
538 break;
539
540 if (libusb_get_string_descriptor_ascii(hdl,
541 des.iProduct, strdesc, sizeof(strdesc)) < 0)
542 break;
543 if (strcmp((const char *)strdesc, product))
544 break;
545
546 ret = TRUE;
547 }
548 if (hdl)
549 libusb_close(hdl);
550
551 return ret;
552}