1/* 2 * Core functions for libusb 3 * Copyright (C) 2007-2008 Daniel Drake <dsd@gentoo.org> 4 * Copyright (c) 2001 Johannes Erdfelt <johannes@erdfelt.com> 5 * 6 * This library is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU Lesser General Public 8 * License as published by the Free Software Foundation; either 9 * version 2.1 of the License, or (at your option) any later version. 10 * 11 * This library is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 * Lesser General Public License for more details. 15 * 16 * You should have received a copy of the GNU Lesser General Public 17 * License along with this library; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 19 */ 20 21#include <config.h> 22 23#include <errno.h> 24#include <poll.h> 25#include <stdarg.h> 26#include <stdio.h> 27#include <stdlib.h> 28#include <string.h> 29#include <sys/types.h> 30#include <unistd.h> 31 32#include "libusb.h" 33#include "libusbi.h" 34 35#if defined(OS_LINUX) 36const struct usbi_os_backend * const usbi_backend = &linux_usbfs_backend; 37#elif defined(OS_DARWIN) 38const struct usbi_os_backend * const usbi_backend = &darwin_backend; 39#else 40#error "Unsupported OS" 41#endif 42 43struct libusb_context *usbi_default_context = NULL; 44static pthread_mutex_t default_context_lock = PTHREAD_MUTEX_INITIALIZER; 45 46/** 47 * \mainpage libusb-1.0 API Reference 48 * 49 * \section intro Introduction 50 * 51 * libusb is an open source library that allows you to communicate with USB 52 * devices from userspace. For more info, see the 53 * <a href="http://libusb.sourceforge.net">libusb homepage</a>. 54 * 55 * This documentation is aimed at application developers wishing to 56 * communicate with USB peripherals from their own software. After reviewing 57 * this documentation, feedback and questions can be sent to the 58 * <a href="http://sourceforge.net/mail/?group_id=1674">libusb-devel mailing 59 * list</a>. 60 * 61 * This documentation assumes knowledge of how to operate USB devices from 62 * a software standpoint (descriptors, configurations, interfaces, endpoints, 63 * control/bulk/interrupt/isochronous transfers, etc). Full information 64 * can be found in the <a href="http://www.usb.org/developers/docs/">USB 2.0 65 * Specification</a> which is available for free download. You can probably 66 * find less verbose introductions by searching the web. 67 * 68 * \section features Library features 69 * 70 * - All transfer types supported (control/bulk/interrupt/isochronous) 71 * - 2 transfer interfaces: 72 * -# Synchronous (simple) 73 * -# Asynchronous (more complicated, but more powerful) 74 * - Thread safe (although the asynchronous interface means that you 75 * usually won't need to thread) 76 * - Lightweight with lean API 77 * - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer 78 * 79 * \section gettingstarted Getting Started 80 * 81 * To begin reading the API documentation, start with the Modules page which 82 * links to the different categories of libusb's functionality. 83 * 84 * One decision you will have to make is whether to use the synchronous 85 * or the asynchronous data transfer interface. The \ref io documentation 86 * provides some insight into this topic. 87 * 88 * Some example programs can be found in the libusb source distribution under 89 * the "examples" subdirectory. The libusb homepage includes a list of 90 * real-life project examples which use libusb. 91 * 92 * \section errorhandling Error handling 93 * 94 * libusb functions typically return 0 on success or a negative error code 95 * on failure. These negative error codes relate to LIBUSB_ERROR constants 96 * which are listed on the \ref misc "miscellaneous" documentation page. 97 * 98 * \section msglog Debug message logging 99 * 100 * libusb does not log any messages by default. Your application is therefore 101 * free to close stdout/stderr and those descriptors may be reused without 102 * worry. 103 * 104 * The libusb_set_debug() function can be used to enable stdout/stderr logging 105 * of certain messages. Under standard configuration, libusb doesn't really 106 * log much at all, so you are advised to use this function to enable all 107 * error/warning/informational messages. It will help you debug problems with 108 * your software. 109 * 110 * The logged messages are unstructured. There is no one-to-one correspondence 111 * between messages being logged and success or failure return codes from 112 * libusb functions. There is no format to the messages, so you should not 113 * try to capture or parse them. They are not and will not be localized. 114 * These messages are not suitable for being passed to your application user; 115 * instead, you should interpret the error codes returned from libusb functions 116 * and provide appropriate notification to the user. The messages are simply 117 * there to aid you as a programmer, and if you're confused because you're 118 * getting a strange error code from a libusb function, enabling message 119 * logging may give you a suitable explanation. 120 * 121 * The LIBUSB_DEBUG environment variable can be used to enable message logging 122 * at run-time. This environment variable should be set to a number, which is 123 * interpreted the same as the libusb_set_debug() parameter. When this 124 * environment variable is set, the message logging verbosity level is fixed 125 * and libusb_set_debug() effectively does nothing. 126 * 127 * libusb can be compiled without any logging functions, useful for embedded 128 * systems. In this case, libusb_set_debug() and the LIBUSB_DEBUG environment 129 * variable have no effects. 130 * 131 * libusb can also be compiled with verbose debugging messages. When the 132 * library is compiled in this way, all messages of all verbosities are always 133 * logged. libusb_set_debug() and the LIBUSB_DEBUG environment variable have 134 * no effects. 135 * 136 * \section remarks Other remarks 137 * 138 * libusb does have imperfections. The \ref caveats "caveats" page attempts 139 * to document these. 140 */ 141 142/** 143 * \page caveats Caveats 144 * 145 * \section devresets Device resets 146 * 147 * The libusb_reset_device() function allows you to reset a device. If your 148 * program has to call such a function, it should obviously be aware that 149 * the reset will cause device state to change (e.g. register values may be 150 * reset). 151 * 152 * The problem is that any other program could reset the device your program 153 * is working with, at any time. libusb does not offer a mechanism to inform 154 * you when this has happened, so if someone else resets your device it will 155 * not be clear to your own program why the device state has changed. 156 * 157 * Ultimately, this is a limitation of writing drivers in userspace. 158 * Separation from the USB stack in the underlying kernel makes it difficult 159 * for the operating system to deliver such notifications to your program. 160 * The Linux kernel USB stack allows such reset notifications to be delivered 161 * to in-kernel USB drivers, but it is not clear how such notifications could 162 * be delivered to second-class drivers that live in userspace. 163 * 164 * \section blockonly Blocking-only functionality 165 * 166 * The functionality listed below is only available through synchronous, 167 * blocking functions. There are no asynchronous/non-blocking alternatives, 168 * and no clear ways of implementing these. 169 * 170 * - Configuration activation (libusb_set_configuration()) 171 * - Interface/alternate setting activation (libusb_set_interface_alt_setting()) 172 * - Releasing of interfaces (libusb_release_interface()) 173 * - Clearing of halt/stall condition (libusb_clear_halt()) 174 * - Device resets (libusb_reset_device()) 175 * 176 * \section nohotplug No hotplugging 177 * 178 * libusb-1.0 lacks functionality for providing notifications of when devices 179 * are added or removed. This functionality is planned to be implemented 180 * for libusb-1.1. 181 * 182 * That said, there is basic disconnection handling for open device handles: 183 * - If there are ongoing transfers, libusb's handle_events loop will detect 184 * disconnections and complete ongoing transfers with the 185 * LIBUSB_TRANSFER_NO_DEVICE status code. 186 * - Many functions such as libusb_set_configuration() return the special 187 * LIBUSB_ERROR_NO_DEVICE error code when the device has been disconnected. 188 * 189 * \section configsel Configuration selection and handling 190 * 191 * When libusb presents a device handle to an application, there is a chance 192 * that the corresponding device may be in unconfigured state. For devices 193 * with multiple configurations, there is also a chance that the configuration 194 * currently selected is not the one that the application wants to use. 195 * 196 * The obvious solution is to add a call to libusb_set_configuration() early 197 * on during your device initialization routines, but there are caveats to 198 * be aware of: 199 * -# If the device is already in the desired configuration, calling 200 * libusb_set_configuration() using the same configuration value will cause 201 * a lightweight device reset. This may not be desirable behaviour. 202 * -# libusb will be unable to change configuration if the device is in 203 * another configuration and other programs or drivers have claimed 204 * interfaces under that configuration. 205 * -# In the case where the desired configuration is already active, libusb 206 * may not even be able to perform a lightweight device reset. For example, 207 * take my USB keyboard with fingerprint reader: I'm interested in driving 208 * the fingerprint reader interface through libusb, but the kernel's 209 * USB-HID driver will almost always have claimed the keyboard interface. 210 * Because the kernel has claimed an interface, it is not even possible to 211 * perform the lightweight device reset, so libusb_set_configuration() will 212 * fail. (Luckily the device in question only has a single configuration.) 213 * 214 * One solution to some of the above problems is to consider the currently 215 * active configuration. If the configuration we want is already active, then 216 * we don't have to select any configuration: 217\code 218cfg = libusb_get_configuration(dev); 219if (cfg != desired) 220 libusb_set_configuration(dev, desired); 221\endcode 222 * 223 * This is probably suitable for most scenarios, but is inherently racy: 224 * another application or driver may change the selected configuration 225 * <em>after</em> the libusb_get_configuration() call. 226 * 227 * Even in cases where libusb_set_configuration() succeeds, consider that other 228 * applications or drivers may change configuration after your application 229 * calls libusb_set_configuration(). 230 * 231 * One possible way to lock your device into a specific configuration is as 232 * follows: 233 * -# Set the desired configuration (or use the logic above to realise that 234 * it is already in the desired configuration) 235 * -# Claim the interface that you wish to use 236 * -# Check that the currently active configuration is the one that you want 237 * to use. 238 * 239 * The above method works because once an interface is claimed, no application 240 * or driver is able to select another configuration. 241 * 242 * \section earlycomp Early transfer completion 243 * 244 * NOTE: This section is currently Linux-centric. I am not sure if any of these 245 * considerations apply to Darwin or other platforms. 246 * 247 * When a transfer completes early (i.e. when less data is received/sent in 248 * any one packet than the transfer buffer allows for) then libusb is designed 249 * to terminate the transfer immediately, not transferring or receiving any 250 * more data unless other transfers have been queued by the user. 251 * 252 * On legacy platforms, libusb is unable to do this in all situations. After 253 * the incomplete packet occurs, "surplus" data may be transferred. Prior to 254 * libusb v1.0.2, this information was lost (and for device-to-host transfers, 255 * the corresponding data was discarded). As of libusb v1.0.3, this information 256 * is kept (the data length of the transfer is updated) and, for device-to-host 257 * transfesr, any surplus data was added to the buffer. Still, this is not 258 * a nice solution because it loses the information about the end of the short 259 * packet, and the user probably wanted that surplus data to arrive in the next 260 * logical transfer. 261 * 262 * A previous workaround was to only ever submit transfers of size 16kb or 263 * less. 264 * 265 * As of libusb v1.0.4 and Linux v2.6.32, this is fixed. A technical 266 * explanation of this issue follows. 267 * 268 * When you ask libusb to submit a bulk transfer larger than 16kb in size, 269 * libusb breaks it up into a number of smaller subtransfers. This is because 270 * the usbfs kernel interface only accepts transfers of up to 16kb in size. 271 * The subtransfers are submitted all at once so that the kernel can queue 272 * them at the hardware level, therefore maximizing bus throughput. 273 * 274 * On legacy platforms, this caused problems when transfers completed early 275 * Upon this event, the kernel would terminate all further packets in that 276 * subtransfer (but not any following ones). libusb would note this event and 277 * immediately cancel any following subtransfers that had been queued, 278 * but often libusb was not fast enough, and the following subtransfers had 279 * started before libusb got around to cancelling them. 280 * 281 * Thanks to an API extension to usbfs, this is fixed with recent kernel and 282 * libusb releases. The solution was to allow libusb to communicate to the 283 * kernel where boundaries occur between logical libusb-level transfers. When 284 * a short transfer (or other error) occurs, the kernel will cancel all the 285 * subtransfers until the boundary without allowing those transfers to start. 286 */ 287 288/** 289 * \page contexts Contexts 290 * 291 * It is possible that libusb may be used simultaneously from two independent 292 * libraries linked into the same executable. For example, if your application 293 * has a plugin-like system which allows the user to dynamically load a range 294 * of modules into your program, it is feasible that two independently 295 * developed modules may both use libusb. 296 * 297 * libusb is written to allow for these multiple user scenarios. The two 298 * "instances" of libusb will not interfere: libusb_set_debug() calls 299 * from one user will not affect the same settings for other users, other 300 * users can continue using libusb after one of them calls libusb_exit(), etc. 301 * 302 * This is made possible through libusb's <em>context</em> concept. When you 303 * call libusb_init(), you are (optionally) given a context. You can then pass 304 * this context pointer back into future libusb functions. 305 * 306 * In order to keep things simple for more simplistic applications, it is 307 * legal to pass NULL to all functions requiring a context pointer (as long as 308 * you're sure no other code will attempt to use libusb from the same process). 309 * When you pass NULL, the default context will be used. The default context 310 * is created the first time a process calls libusb_init() when no other 311 * context is alive. Contexts are destroyed during libusb_exit(). 312 * 313 * You may be wondering why only a subset of libusb functions require a 314 * context pointer in their function definition. Internally, libusb stores 315 * context pointers in other objects (e.g. libusb_device instances) and hence 316 * can infer the context from those objects. 317 */ 318 319/** 320 * @defgroup lib Library initialization/deinitialization 321 * This page details how to initialize and deinitialize libusb. Initialization 322 * must be performed before using any libusb functionality, and similarly you 323 * must not call any libusb functions after deinitialization. 324 */ 325 326/** 327 * @defgroup dev Device handling and enumeration 328 * The functionality documented below is designed to help with the following 329 * operations: 330 * - Enumerating the USB devices currently attached to the system 331 * - Choosing a device to operate from your software 332 * - Opening and closing the chosen device 333 * 334 * \section nutshell In a nutshell... 335 * 336 * The description below really makes things sound more complicated than they 337 * actually are. The following sequence of function calls will be suitable 338 * for almost all scenarios and does not require you to have such a deep 339 * understanding of the resource management issues: 340 * \code 341// discover devices 342libusb_device **list; 343libusb_device *found = NULL; 344ssize_t cnt = libusb_get_device_list(NULL, &list); 345ssize_t i = 0; 346int err = 0; 347if (cnt < 0) 348 error(); 349 350for (i = 0; i < cnt; i++) { 351 libusb_device *device = list[i]; 352 if (is_interesting(device)) { 353 found = device; 354 break; 355 } 356} 357 358if (found) { 359 libusb_device_handle *handle; 360 361 err = libusb_open(found, &handle); 362 if (err) 363 error(); 364 // etc 365} 366 367libusb_free_device_list(list, 1); 368\endcode 369 * 370 * The two important points: 371 * - You asked libusb_free_device_list() to unreference the devices (2nd 372 * parameter) 373 * - You opened the device before freeing the list and unreferencing the 374 * devices 375 * 376 * If you ended up with a handle, you can now proceed to perform I/O on the 377 * device. 378 * 379 * \section devshandles Devices and device handles 380 * libusb has a concept of a USB device, represented by the 381 * \ref libusb_device opaque type. A device represents a USB device that 382 * is currently or was previously connected to the system. Using a reference 383 * to a device, you can determine certain information about the device (e.g. 384 * you can read the descriptor data). 385 * 386 * The libusb_get_device_list() function can be used to obtain a list of 387 * devices currently connected to the system. This is known as device 388 * discovery. 389 * 390 * Just because you have a reference to a device does not mean it is 391 * necessarily usable. The device may have been unplugged, you may not have 392 * permission to operate such device, or another program or driver may be 393 * using the device. 394 * 395 * When you've found a device that you'd like to operate, you must ask 396 * libusb to open the device using the libusb_open() function. Assuming 397 * success, libusb then returns you a <em>device handle</em> 398 * (a \ref libusb_device_handle pointer). All "real" I/O operations then 399 * operate on the handle rather than the original device pointer. 400 * 401 * \section devref Device discovery and reference counting 402 * 403 * Device discovery (i.e. calling libusb_get_device_list()) returns a 404 * freshly-allocated list of devices. The list itself must be freed when 405 * you are done with it. libusb also needs to know when it is OK to free 406 * the contents of the list - the devices themselves. 407 * 408 * To handle these issues, libusb provides you with two separate items: 409 * - A function to free the list itself 410 * - A reference counting system for the devices inside 411 * 412 * New devices presented by the libusb_get_device_list() function all have a 413 * reference count of 1. You can increase and decrease reference count using 414 * libusb_ref_device() and libusb_unref_device(). A device is destroyed when 415 * its reference count reaches 0. 416 * 417 * With the above information in mind, the process of opening a device can 418 * be viewed as follows: 419 * -# Discover devices using libusb_get_device_list(). 420 * -# Choose the device that you want to operate, and call libusb_open(). 421 * -# Unref all devices in the discovered device list. 422 * -# Free the discovered device list. 423 * 424 * The order is important - you must not unreference the device before 425 * attempting to open it, because unreferencing it may destroy the device. 426 * 427 * For convenience, the libusb_free_device_list() function includes a 428 * parameter to optionally unreference all the devices in the list before 429 * freeing the list itself. This combines steps 3 and 4 above. 430 * 431 * As an implementation detail, libusb_open() actually adds a reference to 432 * the device in question. This is because the device remains available 433 * through the handle via libusb_get_device(). The reference is deleted during 434 * libusb_close(). 435 */ 436 437/** @defgroup misc Miscellaneous */ 438 439/* we traverse usbfs without knowing how many devices we are going to find. 440 * so we create this discovered_devs model which is similar to a linked-list 441 * which grows when required. it can be freed once discovery has completed, 442 * eliminating the need for a list node in the libusb_device structure 443 * itself. */ 444#define DISCOVERED_DEVICES_SIZE_STEP 8 445 446static struct discovered_devs *discovered_devs_alloc(void) 447{ 448 struct discovered_devs *ret = 449 malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP)); 450 451 if (ret) { 452 ret->len = 0; 453 ret->capacity = DISCOVERED_DEVICES_SIZE_STEP; 454 } 455 return ret; 456} 457 458/* append a device to the discovered devices collection. may realloc itself, 459 * returning new discdevs. returns NULL on realloc failure. */ 460struct discovered_devs *discovered_devs_append( 461 struct discovered_devs *discdevs, struct libusb_device *dev) 462{ 463 size_t len = discdevs->len; 464 size_t capacity; 465 466 /* if there is space, just append the device */ 467 if (len < discdevs->capacity) { 468 discdevs->devices[len] = libusb_ref_device(dev); 469 discdevs->len++; 470 return discdevs; 471 } 472 473 /* exceeded capacity, need to grow */ 474 usbi_dbg("need to increase capacity"); 475 capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP; 476 discdevs = realloc(discdevs, 477 sizeof(*discdevs) + (sizeof(void *) * capacity)); 478 if (discdevs) { 479 discdevs->capacity = capacity; 480 discdevs->devices[len] = libusb_ref_device(dev); 481 discdevs->len++; 482 } 483 484 return discdevs; 485} 486 487static void discovered_devs_free(struct discovered_devs *discdevs) 488{ 489 size_t i; 490 491 for (i = 0; i < discdevs->len; i++) 492 libusb_unref_device(discdevs->devices[i]); 493 494 free(discdevs); 495} 496 497/* Allocate a new device with a specific session ID. The returned device has 498 * a reference count of 1. */ 499struct libusb_device *usbi_alloc_device(struct libusb_context *ctx, 500 unsigned long session_id) 501{ 502 size_t priv_size = usbi_backend->device_priv_size; 503 struct libusb_device *dev = malloc(sizeof(*dev) + priv_size); 504 int r; 505 506 if (!dev) 507 return NULL; 508 509 r = pthread_mutex_init(&dev->lock, NULL); 510 if (r) 511 return NULL; 512 513 dev->ctx = ctx; 514 dev->refcnt = 1; 515 dev->session_data = session_id; 516 memset(&dev->os_priv, 0, priv_size); 517 518 pthread_mutex_lock(&ctx->usb_devs_lock); 519 list_add(&dev->list, &ctx->usb_devs); 520 pthread_mutex_unlock(&ctx->usb_devs_lock); 521 return dev; 522} 523 524/* Perform some final sanity checks on a newly discovered device. If this 525 * function fails (negative return code), the device should not be added 526 * to the discovered device list. */ 527int usbi_sanitize_device(struct libusb_device *dev) 528{ 529 int r; 530 unsigned char raw_desc[DEVICE_DESC_LENGTH]; 531 uint8_t num_configurations; 532 int host_endian; 533 534 r = usbi_backend->get_device_descriptor(dev, raw_desc, &host_endian); 535 if (r < 0) 536 return r; 537 538 num_configurations = raw_desc[DEVICE_DESC_LENGTH - 1]; 539 if (num_configurations > USB_MAXCONFIG) { 540 usbi_err(DEVICE_CTX(dev), "too many configurations"); 541 return LIBUSB_ERROR_IO; 542 } else if (num_configurations < 1) { 543 usbi_dbg("no configurations?"); 544 return LIBUSB_ERROR_IO; 545 } 546 547 dev->num_configurations = num_configurations; 548 return 0; 549} 550 551/* Examine libusb's internal list of known devices, looking for one with 552 * a specific session ID. Returns the matching device if it was found, and 553 * NULL otherwise. */ 554struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx, 555 unsigned long session_id) 556{ 557 struct libusb_device *dev; 558 struct libusb_device *ret = NULL; 559 560 pthread_mutex_lock(&ctx->usb_devs_lock); 561 list_for_each_entry(dev, &ctx->usb_devs, list) 562 if (dev->session_data == session_id) { 563 ret = dev; 564 break; 565 } 566 pthread_mutex_unlock(&ctx->usb_devs_lock); 567 568 return ret; 569} 570 571/** @ingroup dev 572 * Returns a list of USB devices currently attached to the system. This is 573 * your entry point into finding a USB device to operate. 574 * 575 * You are expected to unreference all the devices when you are done with 576 * them, and then free the list with libusb_free_device_list(). Note that 577 * libusb_free_device_list() can unref all the devices for you. Be careful 578 * not to unreference a device you are about to open until after you have 579 * opened it. 580 * 581 * This return value of this function indicates the number of devices in 582 * the resultant list. The list is actually one element larger, as it is 583 * NULL-terminated. 584 * 585 * \param ctx the context to operate on, or NULL for the default context 586 * \param list output location for a list of devices. Must be later freed with 587 * libusb_free_device_list(). 588 * \returns the number of devices in the outputted list, or LIBUSB_ERROR_NO_MEM 589 * on memory allocation failure. 590 */ 591API_EXPORTED ssize_t libusb_get_device_list(libusb_context *ctx, 592 libusb_device ***list) 593{ 594 struct discovered_devs *discdevs = discovered_devs_alloc(); 595 struct libusb_device **ret; 596 int r = 0; 597 size_t i; 598 ssize_t len; 599 USBI_GET_CONTEXT(ctx); 600 usbi_dbg(""); 601 602 if (!discdevs) 603 return LIBUSB_ERROR_NO_MEM; 604 605 r = usbi_backend->get_device_list(ctx, &discdevs); 606 if (r < 0) { 607 len = r; 608 goto out; 609 } 610 611 /* convert discovered_devs into a list */ 612 len = discdevs->len; 613 ret = malloc(sizeof(void *) * (len + 1)); 614 if (!ret) { 615 len = LIBUSB_ERROR_NO_MEM; 616 goto out; 617 } 618 619 ret[len] = NULL; 620 for (i = 0; i < len; i++) { 621 struct libusb_device *dev = discdevs->devices[i]; 622 ret[i] = libusb_ref_device(dev); 623 } 624 *list = ret; 625 626out: 627 discovered_devs_free(discdevs); 628 return len; 629} 630 631/** \ingroup dev 632 * Frees a list of devices previously discovered using 633 * libusb_get_device_list(). If the unref_devices parameter is set, the 634 * reference count of each device in the list is decremented by 1. 635 * \param list the list to free 636 * \param unref_devices whether to unref the devices in the list 637 */ 638API_EXPORTED void libusb_free_device_list(libusb_device **list, 639 int unref_devices) 640{ 641 if (!list) 642 return; 643 644 if (unref_devices) { 645 int i = 0; 646 struct libusb_device *dev; 647 648 while ((dev = list[i++]) != NULL) 649 libusb_unref_device(dev); 650 } 651 free(list); 652} 653 654/** \ingroup dev 655 * Get the number of the bus that a device is connected to. 656 * \param dev a device 657 * \returns the bus number 658 */ 659API_EXPORTED uint8_t libusb_get_bus_number(libusb_device *dev) 660{ 661 return dev->bus_number; 662} 663 664/** \ingroup dev 665 * Get the address of the device on the bus it is connected to. 666 * \param dev a device 667 * \returns the device address 668 */ 669API_EXPORTED uint8_t libusb_get_device_address(libusb_device *dev) 670{ 671 return dev->device_address; 672} 673 674static const struct libusb_endpoint_descriptor *find_endpoint( 675 struct libusb_config_descriptor *config, unsigned char endpoint) 676{ 677 int iface_idx; 678 for (iface_idx = 0; iface_idx < config->bNumInterfaces; iface_idx++) { 679 const struct libusb_interface *iface = &config->interface[iface_idx]; 680 int altsetting_idx; 681 682 for (altsetting_idx = 0; altsetting_idx < iface->num_altsetting; 683 altsetting_idx++) { 684 const struct libusb_interface_descriptor *altsetting 685 = &iface->altsetting[altsetting_idx]; 686 int ep_idx; 687 688 for (ep_idx = 0; ep_idx < altsetting->bNumEndpoints; ep_idx++) { 689 const struct libusb_endpoint_descriptor *ep = 690 &altsetting->endpoint[ep_idx]; 691 if (ep->bEndpointAddress == endpoint) 692 return ep; 693 } 694 } 695 } 696 return NULL; 697} 698 699/** \ingroup dev 700 * Convenience function to retrieve the wMaxPacketSize value for a particular 701 * endpoint in the active device configuration. 702 * 703 * This function was originally intended to be of assistance when setting up 704 * isochronous transfers, but a design mistake resulted in this function 705 * instead. It simply returns the wMaxPacketSize value without considering 706 * its contents. If you're dealing with isochronous transfers, you probably 707 * want libusb_get_max_iso_packet_size() instead. 708 * 709 * \param dev a device 710 * \param endpoint address of the endpoint in question 711 * \returns the wMaxPacketSize value 712 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist 713 * \returns LIBUSB_ERROR_OTHER on other failure 714 */ 715API_EXPORTED int libusb_get_max_packet_size(libusb_device *dev, 716 unsigned char endpoint) 717{ 718 struct libusb_config_descriptor *config; 719 const struct libusb_endpoint_descriptor *ep; 720 int r; 721 722 r = libusb_get_active_config_descriptor(dev, &config); 723 if (r < 0) { 724 usbi_err(DEVICE_CTX(dev), 725 "could not retrieve active config descriptor"); 726 return LIBUSB_ERROR_OTHER; 727 } 728 729 ep = find_endpoint(config, endpoint); 730 if (!ep) 731 return LIBUSB_ERROR_NOT_FOUND; 732 733 r = ep->wMaxPacketSize; 734 libusb_free_config_descriptor(config); 735 return r; 736} 737 738/** \ingroup dev 739 * Calculate the maximum packet size which a specific endpoint is capable is 740 * sending or receiving in the duration of 1 microframe 741 * 742 * Only the active configution is examined. The calculation is based on the 743 * wMaxPacketSize field in the endpoint descriptor as described in section 744 * 9.6.6 in the USB 2.0 specifications. 745 * 746 * If acting on an isochronous or interrupt endpoint, this function will 747 * multiply the value found in bits 0:10 by the number of transactions per 748 * microframe (determined by bits 11:12). Otherwise, this function just 749 * returns the numeric value found in bits 0:10. 750 * 751 * This function is useful for setting up isochronous transfers, for example 752 * you might pass the return value from this function to 753 * libusb_set_iso_packet_lengths() in order to set the length field of every 754 * isochronous packet in a transfer. 755 * 756 * Since v1.0.3. 757 * 758 * \param dev a device 759 * \param endpoint address of the endpoint in question 760 * \returns the maximum packet size which can be sent/received on this endpoint 761 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist 762 * \returns LIBUSB_ERROR_OTHER on other failure 763 */ 764API_EXPORTED int libusb_get_max_iso_packet_size(libusb_device *dev, 765 unsigned char endpoint) 766{ 767 struct libusb_config_descriptor *config; 768 const struct libusb_endpoint_descriptor *ep; 769 enum libusb_transfer_type ep_type; 770 uint16_t val; 771 int r; 772 773 r = libusb_get_active_config_descriptor(dev, &config); 774 if (r < 0) { 775 usbi_err(DEVICE_CTX(dev), 776 "could not retrieve active config descriptor"); 777 return LIBUSB_ERROR_OTHER; 778 } 779 780 ep = find_endpoint(config, endpoint); 781 if (!ep) 782 return LIBUSB_ERROR_NOT_FOUND; 783 784 val = ep->wMaxPacketSize; 785 ep_type = ep->bmAttributes & 0x3; 786 libusb_free_config_descriptor(config); 787 788 r = val & 0x07ff; 789 if (ep_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS 790 || ep_type == LIBUSB_TRANSFER_TYPE_INTERRUPT) 791 r *= (1 + ((val >> 11) & 3)); 792 return r; 793} 794 795/** \ingroup dev 796 * Increment the reference count of a device. 797 * \param dev the device to reference 798 * \returns the same device 799 */ 800API_EXPORTED libusb_device *libusb_ref_device(libusb_device *dev) 801{ 802 pthread_mutex_lock(&dev->lock); 803 dev->refcnt++; 804 pthread_mutex_unlock(&dev->lock); 805 return dev; 806} 807 808/** \ingroup dev 809 * Decrement the reference count of a device. If the decrement operation 810 * causes the reference count to reach zero, the device shall be destroyed. 811 * \param dev the device to unreference 812 */ 813API_EXPORTED void libusb_unref_device(libusb_device *dev) 814{ 815 int refcnt; 816 817 if (!dev) 818 return; 819 820 pthread_mutex_lock(&dev->lock); 821 refcnt = --dev->refcnt; 822 pthread_mutex_unlock(&dev->lock); 823 824 if (refcnt == 0) { 825 usbi_dbg("destroy device %d.%d", dev->bus_number, dev->device_address); 826 827 if (usbi_backend->destroy_device) 828 usbi_backend->destroy_device(dev); 829 830 pthread_mutex_lock(&dev->ctx->usb_devs_lock); 831 list_del(&dev->list); 832 pthread_mutex_unlock(&dev->ctx->usb_devs_lock); 833 834 pthread_mutex_destroy(&dev->lock); 835 free(dev); 836 } 837} 838 839/** \ingroup dev 840 * Open a device and obtain a device handle. A handle allows you to perform 841 * I/O on the device in question. 842 * 843 * Internally, this function adds a reference to the device and makes it 844 * available to you through libusb_get_device(). This reference is removed 845 * during libusb_close(). 846 * 847 * This is a non-blocking function; no requests are sent over the bus. 848 * 849 * \param dev the device to open 850 * \param handle output location for the returned device handle pointer. Only 851 * populated when the return code is 0. 852 * \returns 0 on success 853 * \returns LIBUSB_ERROR_NO_MEM on memory allocation failure 854 * \returns LIBUSB_ERROR_ACCESS if the user has insufficient permissions 855 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 856 * \returns another LIBUSB_ERROR code on other failure 857 */ 858API_EXPORTED int libusb_open(libusb_device *dev, libusb_device_handle **handle) 859{ 860 struct libusb_context *ctx = DEVICE_CTX(dev); 861 struct libusb_device_handle *_handle; 862 size_t priv_size = usbi_backend->device_handle_priv_size; 863 unsigned char dummy = 1; 864 int r; 865 usbi_dbg("open %d.%d", dev->bus_number, dev->device_address); 866 867 _handle = malloc(sizeof(*_handle) + priv_size); 868 if (!_handle) 869 return LIBUSB_ERROR_NO_MEM; 870 871 r = pthread_mutex_init(&_handle->lock, NULL); 872 if (r) 873 return LIBUSB_ERROR_OTHER; 874 875 _handle->dev = libusb_ref_device(dev); 876 _handle->claimed_interfaces = 0; 877 memset(&_handle->os_priv, 0, priv_size); 878 879 r = usbi_backend->open(_handle); 880 if (r < 0) { 881 libusb_unref_device(dev); 882 free(_handle); 883 return r; 884 } 885 886 pthread_mutex_lock(&ctx->open_devs_lock); 887 list_add(&_handle->list, &ctx->open_devs); 888 pthread_mutex_unlock(&ctx->open_devs_lock); 889 *handle = _handle; 890 891 892 /* At this point, we want to interrupt any existing event handlers so 893 * that they realise the addition of the new device's poll fd. One 894 * example when this is desirable is if the user is running a separate 895 * dedicated libusb events handling thread, which is running with a long 896 * or infinite timeout. We want to interrupt that iteration of the loop, 897 * so that it picks up the new fd, and then continues. */ 898 899 /* record that we are messing with poll fds */ 900 pthread_mutex_lock(&ctx->pollfd_modify_lock); 901 ctx->pollfd_modify++; 902 pthread_mutex_unlock(&ctx->pollfd_modify_lock); 903 904 /* write some data on control pipe to interrupt event handlers */ 905 r = write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy)); 906 if (r <= 0) { 907 usbi_warn(ctx, "internal signalling write failed"); 908 pthread_mutex_lock(&ctx->pollfd_modify_lock); 909 ctx->pollfd_modify--; 910 pthread_mutex_unlock(&ctx->pollfd_modify_lock); 911 return 0; 912 } 913 914 /* take event handling lock */ 915 libusb_lock_events(ctx); 916 917 /* read the dummy data */ 918 r = read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy)); 919 if (r <= 0) 920 usbi_warn(ctx, "internal signalling read failed"); 921 922 /* we're done with modifying poll fds */ 923 pthread_mutex_lock(&ctx->pollfd_modify_lock); 924 ctx->pollfd_modify--; 925 pthread_mutex_unlock(&ctx->pollfd_modify_lock); 926 927 /* Release event handling lock and wake up event waiters */ 928 libusb_unlock_events(ctx); 929 930 return 0; 931} 932 933/** \ingroup dev 934 * Convenience function for finding a device with a particular 935 * <tt>idVendor</tt>/<tt>idProduct</tt> combination. This function is intended 936 * for those scenarios where you are using libusb to knock up a quick test 937 * application - it allows you to avoid calling libusb_get_device_list() and 938 * worrying about traversing/freeing the list. 939 * 940 * This function has limitations and is hence not intended for use in real 941 * applications: if multiple devices have the same IDs it will only 942 * give you the first one, etc. 943 * 944 * \param ctx the context to operate on, or NULL for the default context 945 * \param vendor_id the idVendor value to search for 946 * \param product_id the idProduct value to search for 947 * \returns a handle for the first found device, or NULL on error or if the 948 * device could not be found. */ 949API_EXPORTED libusb_device_handle *libusb_open_device_with_vid_pid( 950 libusb_context *ctx, uint16_t vendor_id, uint16_t product_id) 951{ 952 struct libusb_device **devs; 953 struct libusb_device *found = NULL; 954 struct libusb_device *dev; 955 struct libusb_device_handle *handle = NULL; 956 size_t i = 0; 957 int r; 958 959 if (libusb_get_device_list(ctx, &devs) < 0) 960 return NULL; 961 962 while ((dev = devs[i++]) != NULL) { 963 struct libusb_device_descriptor desc; 964 r = libusb_get_device_descriptor(dev, &desc); 965 if (r < 0) 966 goto out; 967 if (desc.idVendor == vendor_id && desc.idProduct == product_id) { 968 found = dev; 969 break; 970 } 971 } 972 973 if (found) { 974 r = libusb_open(found, &handle); 975 if (r < 0) 976 handle = NULL; 977 } 978 979out: 980 libusb_free_device_list(devs, 1); 981 return handle; 982} 983 984static void do_close(struct libusb_context *ctx, 985 struct libusb_device_handle *dev_handle) 986{ 987 pthread_mutex_lock(&ctx->open_devs_lock); 988 list_del(&dev_handle->list); 989 pthread_mutex_unlock(&ctx->open_devs_lock); 990 991 usbi_backend->close(dev_handle); 992 libusb_unref_device(dev_handle->dev); 993 free(dev_handle); 994} 995 996/** \ingroup dev 997 * Close a device handle. Should be called on all open handles before your 998 * application exits. 999 * 1000 * Internally, this function destroys the reference that was added by 1001 * libusb_open() on the given device. 1002 * 1003 * This is a non-blocking function; no requests are sent over the bus. 1004 * 1005 * \param dev_handle the handle to close 1006 */ 1007API_EXPORTED void libusb_close(libusb_device_handle *dev_handle) 1008{ 1009 struct libusb_context *ctx; 1010 unsigned char dummy = 1; 1011 ssize_t r; 1012 1013 if (!dev_handle) 1014 return; 1015 usbi_dbg(""); 1016 1017 ctx = HANDLE_CTX(dev_handle); 1018 1019 /* Similarly to libusb_open(), we want to interrupt all event handlers 1020 * at this point. More importantly, we want to perform the actual close of 1021 * the device while holding the event handling lock (preventing any other 1022 * thread from doing event handling) because we will be removing a file 1023 * descriptor from the polling loop. */ 1024 1025 /* record that we are messing with poll fds */ 1026 pthread_mutex_lock(&ctx->pollfd_modify_lock); 1027 ctx->pollfd_modify++; 1028 pthread_mutex_unlock(&ctx->pollfd_modify_lock); 1029 1030 /* write some data on control pipe to interrupt event handlers */ 1031 r = write(ctx->ctrl_pipe[1], &dummy, sizeof(dummy)); 1032 if (r <= 0) { 1033 usbi_warn(ctx, "internal signalling write failed, closing anyway"); 1034 do_close(ctx, dev_handle); 1035 pthread_mutex_lock(&ctx->pollfd_modify_lock); 1036 ctx->pollfd_modify--; 1037 pthread_mutex_unlock(&ctx->pollfd_modify_lock); 1038 return; 1039 } 1040 1041 /* take event handling lock */ 1042 libusb_lock_events(ctx); 1043 1044 /* read the dummy data */ 1045 r = read(ctx->ctrl_pipe[0], &dummy, sizeof(dummy)); 1046 if (r <= 0) 1047 usbi_warn(ctx, "internal signalling read failed, closing anyway"); 1048 1049 /* Close the device */ 1050 do_close(ctx, dev_handle); 1051 1052 /* we're done with modifying poll fds */ 1053 pthread_mutex_lock(&ctx->pollfd_modify_lock); 1054 ctx->pollfd_modify--; 1055 pthread_mutex_unlock(&ctx->pollfd_modify_lock); 1056 1057 /* Release event handling lock and wake up event waiters */ 1058 libusb_unlock_events(ctx); 1059} 1060 1061/** \ingroup dev 1062 * Get the underlying device for a handle. This function does not modify 1063 * the reference count of the returned device, so do not feel compelled to 1064 * unreference it when you are done. 1065 * \param dev_handle a device handle 1066 * \returns the underlying device 1067 */ 1068API_EXPORTED libusb_device *libusb_get_device(libusb_device_handle *dev_handle) 1069{ 1070 return dev_handle->dev; 1071} 1072 1073/** \ingroup dev 1074 * Determine the bConfigurationValue of the currently active configuration. 1075 * 1076 * You could formulate your own control request to obtain this information, 1077 * but this function has the advantage that it may be able to retrieve the 1078 * information from operating system caches (no I/O involved). 1079 * 1080 * If the OS does not cache this information, then this function will block 1081 * while a control transfer is submitted to retrieve the information. 1082 * 1083 * This function will return a value of 0 in the <tt>config</tt> output 1084 * parameter if the device is in unconfigured state. 1085 * 1086 * \param dev a device handle 1087 * \param config output location for the bConfigurationValue of the active 1088 * configuration (only valid for return code 0) 1089 * \returns 0 on success 1090 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 1091 * \returns another LIBUSB_ERROR code on other failure 1092 */ 1093API_EXPORTED int libusb_get_configuration(libusb_device_handle *dev, 1094 int *config) 1095{ 1096 int r = LIBUSB_ERROR_NOT_SUPPORTED; 1097 1098 usbi_dbg(""); 1099 if (usbi_backend->get_configuration) 1100 r = usbi_backend->get_configuration(dev, config); 1101 1102 if (r == LIBUSB_ERROR_NOT_SUPPORTED) { 1103 uint8_t tmp = 0; 1104 usbi_dbg("falling back to control message"); 1105 r = libusb_control_transfer(dev, LIBUSB_ENDPOINT_IN, 1106 LIBUSB_REQUEST_GET_CONFIGURATION, 0, 0, &tmp, 1, 1000); 1107 if (r == 0) { 1108 usbi_err(HANDLE_CTX(dev), "zero bytes returned in ctrl transfer?"); 1109 r = LIBUSB_ERROR_IO; 1110 } else if (r == 1) { 1111 r = 0; 1112 *config = tmp; 1113 } else { 1114 usbi_dbg("control failed, error %d", r); 1115 } 1116 } 1117 1118 if (r == 0) 1119 usbi_dbg("active config %d", *config); 1120 1121 return r; 1122} 1123 1124/** \ingroup dev 1125 * Set the active configuration for a device. 1126 * 1127 * The operating system may or may not have already set an active 1128 * configuration on the device. It is up to your application to ensure the 1129 * correct configuration is selected before you attempt to claim interfaces 1130 * and perform other operations. 1131 * 1132 * If you call this function on a device already configured with the selected 1133 * configuration, then this function will act as a lightweight device reset: 1134 * it will issue a SET_CONFIGURATION request using the current configuration, 1135 * causing most USB-related device state to be reset (altsetting reset to zero, 1136 * endpoint halts cleared, toggles reset). 1137 * 1138 * You cannot change/reset configuration if your application has claimed 1139 * interfaces - you should free them with libusb_release_interface() first. 1140 * You cannot change/reset configuration if other applications or drivers have 1141 * claimed interfaces. 1142 * 1143 * A configuration value of -1 will put the device in unconfigured state. 1144 * The USB specifications state that a configuration value of 0 does this, 1145 * however buggy devices exist which actually have a configuration 0. 1146 * 1147 * You should always use this function rather than formulating your own 1148 * SET_CONFIGURATION control request. This is because the underlying operating 1149 * system needs to know when such changes happen. 1150 * 1151 * This is a blocking function. 1152 * 1153 * \param dev a device handle 1154 * \param configuration the bConfigurationValue of the configuration you 1155 * wish to activate, or -1 if you wish to put the device in unconfigured state 1156 * \returns 0 on success 1157 * \returns LIBUSB_ERROR_NOT_FOUND if the requested configuration does not exist 1158 * \returns LIBUSB_ERROR_BUSY if interfaces are currently claimed 1159 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 1160 * \returns another LIBUSB_ERROR code on other failure 1161 */ 1162API_EXPORTED int libusb_set_configuration(libusb_device_handle *dev, 1163 int configuration) 1164{ 1165 usbi_dbg("configuration %d", configuration); 1166 return usbi_backend->set_configuration(dev, configuration); 1167} 1168 1169/** \ingroup dev 1170 * Claim an interface on a given device handle. You must claim the interface 1171 * you wish to use before you can perform I/O on any of its endpoints. 1172 * 1173 * It is legal to attempt to claim an already-claimed interface, in which 1174 * case libusb just returns 0 without doing anything. 1175 * 1176 * Claiming of interfaces is a purely logical operation; it does not cause 1177 * any requests to be sent over the bus. Interface claiming is used to 1178 * instruct the underlying operating system that your application wishes 1179 * to take ownership of the interface. 1180 * 1181 * This is a non-blocking function. 1182 * 1183 * \param dev a device handle 1184 * \param interface_number the <tt>bInterfaceNumber</tt> of the interface you 1185 * wish to claim 1186 * \returns 0 on success 1187 * \returns LIBUSB_ERROR_NOT_FOUND if the requested interface does not exist 1188 * \returns LIBUSB_ERROR_BUSY if another program or driver has claimed the 1189 * interface 1190 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 1191 * \returns a LIBUSB_ERROR code on other failure 1192 */ 1193API_EXPORTED int libusb_claim_interface(libusb_device_handle *dev, 1194 int interface_number) 1195{ 1196 int r = 0; 1197 1198 usbi_dbg("interface %d", interface_number); 1199 if (interface_number >= sizeof(dev->claimed_interfaces) * 8) 1200 return LIBUSB_ERROR_INVALID_PARAM; 1201 1202 pthread_mutex_lock(&dev->lock); 1203 if (dev->claimed_interfaces & (1 << interface_number)) 1204 goto out; 1205 1206 r = usbi_backend->claim_interface(dev, interface_number); 1207 if (r == 0) 1208 dev->claimed_interfaces |= 1 << interface_number; 1209 1210out: 1211 pthread_mutex_unlock(&dev->lock); 1212 return r; 1213} 1214 1215/** \ingroup dev 1216 * Release an interface previously claimed with libusb_claim_interface(). You 1217 * should release all claimed interfaces before closing a device handle. 1218 * 1219 * This is a blocking function. A SET_INTERFACE control request will be sent 1220 * to the device, resetting interface state to the first alternate setting. 1221 * 1222 * \param dev a device handle 1223 * \param interface_number the <tt>bInterfaceNumber</tt> of the 1224 * previously-claimed interface 1225 * \returns 0 on success 1226 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed 1227 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 1228 * \returns another LIBUSB_ERROR code on other failure 1229 */ 1230API_EXPORTED int libusb_release_interface(libusb_device_handle *dev, 1231 int interface_number) 1232{ 1233 int r; 1234 1235 usbi_dbg("interface %d", interface_number); 1236 if (interface_number >= sizeof(dev->claimed_interfaces) * 8) 1237 return LIBUSB_ERROR_INVALID_PARAM; 1238 1239 pthread_mutex_lock(&dev->lock); 1240 if (!(dev->claimed_interfaces & (1 << interface_number))) { 1241 r = LIBUSB_ERROR_NOT_FOUND; 1242 goto out; 1243 } 1244 1245 r = usbi_backend->release_interface(dev, interface_number); 1246 if (r == 0) 1247 dev->claimed_interfaces &= ~(1 << interface_number); 1248 1249out: 1250 pthread_mutex_unlock(&dev->lock); 1251 return r; 1252} 1253 1254/** \ingroup dev 1255 * Activate an alternate setting for an interface. The interface must have 1256 * been previously claimed with libusb_claim_interface(). 1257 * 1258 * You should always use this function rather than formulating your own 1259 * SET_INTERFACE control request. This is because the underlying operating 1260 * system needs to know when such changes happen. 1261 * 1262 * This is a blocking function. 1263 * 1264 * \param dev a device handle 1265 * \param interface_number the <tt>bInterfaceNumber</tt> of the 1266 * previously-claimed interface 1267 * \param alternate_setting the <tt>bAlternateSetting</tt> of the alternate 1268 * setting to activate 1269 * \returns 0 on success 1270 * \returns LIBUSB_ERROR_NOT_FOUND if the interface was not claimed, or the 1271 * requested alternate setting does not exist 1272 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 1273 * \returns another LIBUSB_ERROR code on other failure 1274 */ 1275API_EXPORTED int libusb_set_interface_alt_setting(libusb_device_handle *dev, 1276 int interface_number, int alternate_setting) 1277{ 1278 usbi_dbg("interface %d altsetting %d", 1279 interface_number, alternate_setting); 1280 if (interface_number >= sizeof(dev->claimed_interfaces) * 8) 1281 return LIBUSB_ERROR_INVALID_PARAM; 1282 1283 pthread_mutex_lock(&dev->lock); 1284 if (!(dev->claimed_interfaces & (1 << interface_number))) { 1285 pthread_mutex_unlock(&dev->lock); 1286 return LIBUSB_ERROR_NOT_FOUND; 1287 } 1288 pthread_mutex_unlock(&dev->lock); 1289 1290 return usbi_backend->set_interface_altsetting(dev, interface_number, 1291 alternate_setting); 1292} 1293 1294/** \ingroup dev 1295 * Clear the halt/stall condition for an endpoint. Endpoints with halt status 1296 * are unable to receive or transmit data until the halt condition is stalled. 1297 * 1298 * You should cancel all pending transfers before attempting to clear the halt 1299 * condition. 1300 * 1301 * This is a blocking function. 1302 * 1303 * \param dev a device handle 1304 * \param endpoint the endpoint to clear halt status 1305 * \returns 0 on success 1306 * \returns LIBUSB_ERROR_NOT_FOUND if the endpoint does not exist 1307 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 1308 * \returns another LIBUSB_ERROR code on other failure 1309 */ 1310API_EXPORTED int libusb_clear_halt(libusb_device_handle *dev, 1311 unsigned char endpoint) 1312{ 1313 usbi_dbg("endpoint %x", endpoint); 1314 return usbi_backend->clear_halt(dev, endpoint); 1315} 1316 1317/** \ingroup dev 1318 * Perform a USB port reset to reinitialize a device. The system will attempt 1319 * to restore the previous configuration and alternate settings after the 1320 * reset has completed. 1321 * 1322 * If the reset fails, the descriptors change, or the previous state cannot be 1323 * restored, the device will appear to be disconnected and reconnected. This 1324 * means that the device handle is no longer valid (you should close it) and 1325 * rediscover the device. A return code of LIBUSB_ERROR_NOT_FOUND indicates 1326 * when this is the case. 1327 * 1328 * This is a blocking function which usually incurs a noticeable delay. 1329 * 1330 * \param dev a handle of the device to reset 1331 * \returns 0 on success 1332 * \returns LIBUSB_ERROR_NOT_FOUND if re-enumeration is required, or if the 1333 * device has been disconnected 1334 * \returns another LIBUSB_ERROR code on other failure 1335 */ 1336API_EXPORTED int libusb_reset_device(libusb_device_handle *dev) 1337{ 1338 usbi_dbg(""); 1339 return usbi_backend->reset_device(dev); 1340} 1341 1342/** \ingroup dev 1343 * Determine if a kernel driver is active on an interface. If a kernel driver 1344 * is active, you cannot claim the interface, and libusb will be unable to 1345 * perform I/O. 1346 * 1347 * \param dev a device handle 1348 * \param interface the interface to check 1349 * \returns 0 if no kernel driver is active 1350 * \returns 1 if a kernel driver is active 1351 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 1352 * \returns another LIBUSB_ERROR code on other failure 1353 * \see libusb_detach_kernel_driver() 1354 */ 1355API_EXPORTED int libusb_kernel_driver_active(libusb_device_handle *dev, 1356 int interface) 1357{ 1358 usbi_dbg("interface %d", interface); 1359 if (usbi_backend->kernel_driver_active) 1360 return usbi_backend->kernel_driver_active(dev, interface); 1361 else 1362 return LIBUSB_ERROR_NOT_SUPPORTED; 1363} 1364 1365/** \ingroup dev 1366 * Detach a kernel driver from an interface. If successful, you will then be 1367 * able to claim the interface and perform I/O. 1368 * 1369 * \param dev a device handle 1370 * \param interface the interface to detach the driver from 1371 * \returns 0 on success 1372 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active 1373 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist 1374 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 1375 * \returns another LIBUSB_ERROR code on other failure 1376 * \see libusb_kernel_driver_active() 1377 */ 1378API_EXPORTED int libusb_detach_kernel_driver(libusb_device_handle *dev, 1379 int interface) 1380{ 1381 usbi_dbg("interface %d", interface); 1382 if (usbi_backend->detach_kernel_driver) 1383 return usbi_backend->detach_kernel_driver(dev, interface); 1384 else 1385 return LIBUSB_ERROR_NOT_SUPPORTED; 1386} 1387 1388/** \ingroup dev 1389 * Re-attach an interface's kernel driver, which was previously detached 1390 * using libusb_detach_kernel_driver(). 1391 * 1392 * \param dev a device handle 1393 * \param interface the interface to attach the driver from 1394 * \returns 0 on success 1395 * \returns LIBUSB_ERROR_NOT_FOUND if no kernel driver was active 1396 * \returns LIBUSB_ERROR_INVALID_PARAM if the interface does not exist 1397 * \returns LIBUSB_ERROR_NO_DEVICE if the device has been disconnected 1398 * \returns LIBUSB_ERROR_BUSY if the driver cannot be attached because the 1399 * interface is claimed by a program or driver 1400 * \returns another LIBUSB_ERROR code on other failure 1401 * \see libusb_kernel_driver_active() 1402 */ 1403API_EXPORTED int libusb_attach_kernel_driver(libusb_device_handle *dev, 1404 int interface) 1405{ 1406 usbi_dbg("interface %d", interface); 1407 if (usbi_backend->attach_kernel_driver) 1408 return usbi_backend->attach_kernel_driver(dev, interface); 1409 else 1410 return LIBUSB_ERROR_NOT_SUPPORTED; 1411} 1412 1413/** \ingroup lib 1414 * Set message verbosity. 1415 * - Level 0: no messages ever printed by the library (default) 1416 * - Level 1: error messages are printed to stderr 1417 * - Level 2: warning and error messages are printed to stderr 1418 * - Level 3: informational messages are printed to stdout, warning and error 1419 * messages are printed to stderr 1420 * 1421 * The default level is 0, which means no messages are ever printed. If you 1422 * choose to increase the message verbosity level, ensure that your 1423 * application does not close the stdout/stderr file descriptors. 1424 * 1425 * You are advised to set level 3. libusb is conservative with its message 1426 * logging and most of the time, will only log messages that explain error 1427 * conditions and other oddities. This will help you debug your software. 1428 * 1429 * If the LIBUSB_DEBUG environment variable was set when libusb was 1430 * initialized, this function does nothing: the message verbosity is fixed 1431 * to the value in the environment variable. 1432 * 1433 * If libusb was compiled without any message logging, this function does 1434 * nothing: you'll never get any messages. 1435 * 1436 * If libusb was compiled with verbose debug message logging, this function 1437 * does nothing: you'll always get messages from all levels. 1438 * 1439 * \param ctx the context to operate on, or NULL for the default context 1440 * \param level debug level to set 1441 */ 1442API_EXPORTED void libusb_set_debug(libusb_context *ctx, int level) 1443{ 1444 USBI_GET_CONTEXT(ctx); 1445 if (!ctx->debug_fixed) 1446 ctx->debug = level; 1447} 1448 1449/** \ingroup lib 1450 * Initialize libusb. This function must be called before calling any other 1451 * libusb function. 1452 * \param context Optional output location for context pointer. 1453 * Only valid on return code 0. 1454 * \returns 0 on success, or a LIBUSB_ERROR code on failure 1455 */ 1456API_EXPORTED int libusb_init(libusb_context **context) 1457{ 1458 char *dbg = getenv("LIBUSB_DEBUG"); 1459 struct libusb_context *ctx = malloc(sizeof(*ctx)); 1460 int r; 1461 1462 if (!ctx) 1463 return LIBUSB_ERROR_NO_MEM; 1464 memset(ctx, 0, sizeof(*ctx)); 1465 1466 if (dbg) { 1467 ctx->debug = atoi(dbg); 1468 if (ctx->debug) 1469 ctx->debug_fixed = 1; 1470 } 1471 1472 usbi_dbg(""); 1473 1474 if (usbi_backend->init) { 1475 r = usbi_backend->init(ctx); 1476 if (r) 1477 goto err; 1478 } 1479 1480 pthread_mutex_init(&ctx->usb_devs_lock, NULL); 1481 pthread_mutex_init(&ctx->open_devs_lock, NULL); 1482 list_init(&ctx->usb_devs); 1483 list_init(&ctx->open_devs); 1484 1485 r = usbi_io_init(ctx); 1486 if (r < 0) { 1487 if (usbi_backend->exit) 1488 usbi_backend->exit(); 1489 goto err; 1490 } 1491 1492 pthread_mutex_lock(&default_context_lock); 1493 if (!usbi_default_context) { 1494 usbi_dbg("created default context"); 1495 usbi_default_context = ctx; 1496 } 1497 pthread_mutex_unlock(&default_context_lock); 1498 1499 if (context) 1500 *context = ctx; 1501 return 0; 1502 1503err: 1504 free(ctx); 1505 return r; 1506} 1507 1508/** \ingroup lib 1509 * Deinitialize libusb. Should be called after closing all open devices and 1510 * before your application terminates. 1511 * \param ctx the context to deinitialize, or NULL for the default context 1512 */ 1513API_EXPORTED void libusb_exit(struct libusb_context *ctx) 1514{ 1515 USBI_GET_CONTEXT(ctx); 1516 usbi_dbg(""); 1517 1518 /* a little sanity check. doesn't bother with open_devs locking because 1519 * unless there is an application bug, nobody will be accessing this. */ 1520 if (!list_empty(&ctx->open_devs)) 1521 usbi_warn(ctx, "application left some devices open"); 1522 1523 usbi_io_exit(ctx); 1524 if (usbi_backend->exit) 1525 usbi_backend->exit(); 1526 1527 pthread_mutex_lock(&default_context_lock); 1528 if (ctx == usbi_default_context) { 1529 usbi_dbg("freeing default context"); 1530 usbi_default_context = NULL; 1531 } 1532 pthread_mutex_unlock(&default_context_lock); 1533 1534 free(ctx); 1535} 1536 1537void usbi_log(struct libusb_context *ctx, enum usbi_log_level level, 1538 const char *function, const char *format, ...) 1539{ 1540 va_list args; 1541 FILE *stream = stdout; 1542 const char *prefix; 1543 1544#ifndef ENABLE_DEBUG_LOGGING 1545 USBI_GET_CONTEXT(ctx); 1546 if (!ctx->debug) 1547 return; 1548 if (level == LOG_LEVEL_WARNING && ctx->debug < 2) 1549 return; 1550 if (level == LOG_LEVEL_INFO && ctx->debug < 3) 1551 return; 1552#endif 1553 1554 switch (level) { 1555 case LOG_LEVEL_INFO: 1556 prefix = "info"; 1557 break; 1558 case LOG_LEVEL_WARNING: 1559 stream = stderr; 1560 prefix = "warning"; 1561 break; 1562 case LOG_LEVEL_ERROR: 1563 stream = stderr; 1564 prefix = "error"; 1565 break; 1566 case LOG_LEVEL_DEBUG: 1567 stream = stderr; 1568 prefix = "debug"; 1569 break; 1570 default: 1571 stream = stderr; 1572 prefix = "unknown"; 1573 break; 1574 } 1575 1576 fprintf(stream, "libusb:%s [%s] ", prefix, function); 1577 1578 va_start (args, format); 1579 vfprintf(stream, format, args); 1580 va_end (args); 1581 1582 fprintf(stream, "\n"); 1583} 1584 1585