forked from Zondax/hid
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcore.c
2932 lines (2633 loc) · 100 KB
/
core.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
/*
* Core functions for libusb
* Copyright © 2012-2023 Nathan Hjelm <[email protected]>
* Copyright © 2007-2008 Daniel Drake <[email protected]>
* Copyright © 2001 Johannes Erdfelt <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libusbi.h"
#include "version.h"
#ifdef __ANDROID__
#include <android/log.h>
#endif
#include <stdio.h>
#include <string.h>
#ifdef HAVE_SYSLOG
#include <syslog.h>
#endif
static const struct libusb_version libusb_version_internal =
{ LIBUSB_MAJOR, LIBUSB_MINOR, LIBUSB_MICRO, LIBUSB_NANO,
LIBUSB_RC, "https://libusb.info" };
static struct timespec timestamp_origin;
#if defined(ENABLE_LOGGING) && !defined(USE_SYSTEM_LOGGING_FACILITY)
static libusb_log_cb log_handler;
#endif
struct libusb_context *usbi_default_context;
struct libusb_context *usbi_fallback_context;
static int default_context_refcnt;
#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
static usbi_atomic_t default_debug_level = -1;
#endif
static usbi_mutex_static_t default_context_lock = USBI_MUTEX_INITIALIZER;
static struct usbi_option default_context_options[LIBUSB_OPTION_MAX];
usbi_mutex_static_t active_contexts_lock = USBI_MUTEX_INITIALIZER;
struct list_head active_contexts_list;
/**
* \mainpage libusb-1.0 API Reference
*
* \section intro Introduction
*
* libusb is an open source library that allows you to communicate with USB
* devices from user space. For more info, see the
* <a href="https://libusb.info">libusb homepage</a>.
*
* This documentation is aimed at application developers wishing to
* communicate with USB peripherals from their own software. After reviewing
* this documentation, feedback and questions can be sent to the
* <a href="https://mailing-list.libusb.info">libusb-devel mailing list</a>.
*
* This documentation assumes knowledge of how to operate USB devices from
* a software standpoint (descriptors, configurations, interfaces, endpoints,
* control/bulk/interrupt/isochronous transfers, etc). Full information
* can be found in the <a href="http://www.usb.org/developers/docs/">USB 3.0
* Specification</a> which is available for free download. You can probably
* find less verbose introductions by searching the web.
*
* \section API Application Programming Interface (API)
*
* See the \ref libusb_api page for a complete list of the libusb functions.
*
* \section features Library features
*
* - All transfer types supported (control/bulk/interrupt/isochronous)
* - 2 transfer interfaces:
* -# Synchronous (simple)
* -# Asynchronous (more complicated, but more powerful)
* - Thread safe (although the asynchronous interface means that you
* usually won't need to thread)
* - Lightweight with lean API
* - Compatible with libusb-0.1 through the libusb-compat-0.1 translation layer
* - Hotplug support (on some platforms). See \ref libusb_hotplug.
*
* \section gettingstarted Getting Started
*
* To begin reading the API documentation, start with the Modules page which
* links to the different categories of libusb's functionality.
*
* One decision you will have to make is whether to use the synchronous
* or the asynchronous data transfer interface. The \ref libusb_io documentation
* provides some insight into this topic.
*
* Some example programs can be found in the libusb source distribution under
* the "examples" subdirectory. The libusb homepage includes a list of
* real-life project examples which use libusb.
*
* \section errorhandling Error handling
*
* libusb functions typically return 0 on success or a negative error code
* on failure. These negative error codes relate to LIBUSB_ERROR constants
* which are listed on the \ref libusb_misc "miscellaneous" documentation page.
*
* \section msglog Debug message logging
*
* libusb uses stderr for all logging. By default, logging is set to NONE,
* which means that no output will be produced. However, unless the library
* has been compiled with logging disabled, then any application calls to
* libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level),
* libusb_init_context, or the setting of the environmental variable
* LIBUSB_DEBUG outside of the application, can result in logging being
* produced. Your application should therefore not close stderr, but instead
* direct it to the null device if its output is undesirable.
*
* The libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level) or
* libusb_init_context functions can be used to enable logging of certain
* messages. With the default configuration, libusb will not log much so if
* you are advised to use one of these functions to enable all
* error/warning/informational messages. It will help debug problems with your
* software.
*
* The logged messages are unstructured. There is no one-to-one correspondence
* between messages being logged and success or failure return codes from
* libusb functions. There is no format to the messages, so you should not
* try to capture or parse them. They are not and will not be localized.
* These messages are not intended to being passed to your application user;
* instead, you should interpret the error codes returned from libusb functions
* and provide appropriate notification to the user. The messages are simply
* there to aid you as a programmer, and if you're confused because you're
* getting a strange error code from a libusb function, enabling message
* logging may give you a suitable explanation.
*
* The LIBUSB_DEBUG environment variable can be used to enable message logging
* at run-time. This environment variable should be set to a log level number,
* which is interpreted the same as the
* libusb_set_option(ctx, LIBUSB_OPTION_LOG_LEVEL, level), or
* libusb_init_context(&ctx, &(struct libusb_init_option){.option = LIBUSB_OPTION_LOG_LEVEL, .value = {.ival = level}}, 0).
* When the environment variable is set, the message logging verbosity level is
* fixed and setting the LIBUSB_OPTION_LOG_LEVEL option has no effect.
*
* libusb can be compiled without any logging functions, useful for embedded
* systems. In this case, neither the LIBUSB_OPTION_LOG_LEVEL option, nor the
* LIBUSB_DEBUG environment variable will have any effect.
*
* libusb can also be compiled with verbose debugging messages always. When
* the library is compiled in this way, all messages of all verbosities are
* always logged. Again, in this case, neither the LIBUSB_OPTION_LOG_LEVEL
* option, nor the LIBUSB_DEBUG environment variable will have any effect.
*
* \section remarks Other remarks
*
* libusb does have imperfections. The \ref libusb_caveats "caveats" page attempts
* to document these.
*/
/**
* \page libusb_caveats Caveats
*
* \section threadsafety Thread safety
*
* libusb is designed to be completely thread-safe, but as with any API it
* cannot prevent a user from sabotaging themselves, either intentionally or
* otherwise.
*
* Observe the following general guidelines:
*
* - Calls to functions that release a resource (e.g. libusb_close(),
* libusb_free_config_descriptor()) should not be called concurrently on
* the same resource. This is no different than concurrently calling free()
* on the same allocated pointer.
* - Each individual \ref libusb_transfer should be prepared by a single
* thread. In other words, no two threads should ever be concurrently
* filling out the fields of a \ref libusb_transfer. You can liken this to
* calling sprintf() with the same destination buffer from multiple threads.
* The results will likely not be what you want unless the input parameters
* are all the same, but its best to avoid this situation entirely.
* - Both the \ref libusb_transfer structure and its associated data buffer
* should not be accessed between the time the transfer is submitted and the
* time the completion callback is invoked. You can think of "ownership" of
* these things as being transferred to libusb while the transfer is active.
* - The various "setter" functions (e.g. libusb_set_log_cb(),
* libusb_set_pollfd_notifiers()) should not be called concurrently on the
* resource. Though doing so will not lead to any undefined behavior, it
* will likely produce results that the application does not expect.
*
* Rules for multiple threads and asynchronous I/O are detailed
* \ref libusb_mtasync "here".
*
* \section fork Fork considerations
*
* libusb is <em>not</em> designed to work across fork() calls. Depending on
* the platform, there may be resources in the parent process that are not
* available to the child (e.g. the hotplug monitor thread on Linux). In
* addition, since the parent and child will share libusb's internal file
* descriptors, using libusb in any way from the child could cause the parent
* process's \ref libusb_context to get into an inconsistent state.
*
* On Linux, libusb's file descriptors will be marked as CLOEXEC, which means
* that it is safe to fork() and exec() without worrying about the child
* process needing to clean up state or having access to these file descriptors.
* Other platforms may not be so forgiving, so consider yourself warned!
*
* \section devresets Device resets
*
* The libusb_reset_device() function allows you to reset a device. If your
* program has to call such a function, it should obviously be aware that
* the reset will cause device state to change (e.g. register values may be
* reset).
*
* The problem is that any other program could reset the device your program
* is working with, at any time. libusb does not offer a mechanism to inform
* you when this has happened, so if someone else resets your device it will
* not be clear to your own program why the device state has changed.
*
* Ultimately, this is a limitation of writing drivers in user space.
* Separation from the USB stack in the underlying kernel makes it difficult
* for the operating system to deliver such notifications to your program.
* The Linux kernel USB stack allows such reset notifications to be delivered
* to in-kernel USB drivers, but it is not clear how such notifications could
* be delivered to second-class drivers that live in user space.
*
* \section blockonly Blocking-only functionality
*
* The functionality listed below is only available through synchronous,
* blocking functions. There are no asynchronous/non-blocking alternatives,
* and no clear ways of implementing these.
*
* - Configuration activation (libusb_set_configuration())
* - Interface/alternate setting activation (libusb_set_interface_alt_setting())
* - Releasing of interfaces (libusb_release_interface())
* - Clearing of halt/stall condition (libusb_clear_halt())
* - Device resets (libusb_reset_device())
*
* \section configsel Configuration selection and handling
*
* When libusb presents a device handle to an application, there is a chance
* that the corresponding device may be in unconfigured state. For devices
* with multiple configurations, there is also a chance that the configuration
* currently selected is not the one that the application wants to use.
*
* The obvious solution is to add a call to libusb_set_configuration() early
* on during your device initialization routines, but there are caveats to
* be aware of:
* -# If the device is already in the desired configuration, calling
* libusb_set_configuration() using the same configuration value will cause
* a lightweight device reset. This may not be desirable behaviour.
* -# In the case where the desired configuration is already active, libusb
* may not even be able to perform a lightweight device reset. For example,
* take my USB keyboard with fingerprint reader: I'm interested in driving
* the fingerprint reader interface through libusb, but the kernel's
* USB-HID driver will almost always have claimed the keyboard interface.
* Because the kernel has claimed an interface, it is not even possible to
* perform the lightweight device reset, so libusb_set_configuration() will
* fail. (Luckily the device in question only has a single configuration.)
* -# libusb will be unable to set a configuration if other programs or
* drivers have claimed interfaces. In particular, this means that kernel
* drivers must be detached from all the interfaces before
* libusb_set_configuration() may succeed.
*
* One solution to some of the above problems is to consider the currently
* active configuration. If the configuration we want is already active, then
* we don't have to select any configuration:
\code
cfg = -1;
libusb_get_configuration(dev, &cfg);
if (cfg != desired)
libusb_set_configuration(dev, desired);
\endcode
*
* This is probably suitable for most scenarios, but is inherently racy:
* another application or driver may change the selected configuration
* <em>after</em> the libusb_get_configuration() call.
*
* Even in cases where libusb_set_configuration() succeeds, consider that other
* applications or drivers may change configuration after your application
* calls libusb_set_configuration().
*
* One possible way to lock your device into a specific configuration is as
* follows:
* -# Set the desired configuration (or use the logic above to realise that
* it is already in the desired configuration)
* -# Claim the interface that you wish to use
* -# Check that the currently active configuration is the one that you want
* to use.
*
* The above method works because once an interface is claimed, no application
* or driver is able to select another configuration.
*
* \section earlycomp Early transfer completion
*
* NOTE: This section is currently Linux-centric. I am not sure if any of these
* considerations apply to Darwin or other platforms.
*
* When a transfer completes early (i.e. when less data is received/sent in
* any one packet than the transfer buffer allows for) then libusb is designed
* to terminate the transfer immediately, not transferring or receiving any
* more data unless other transfers have been queued by the user.
*
* On legacy platforms, libusb is unable to do this in all situations. After
* the incomplete packet occurs, "surplus" data may be transferred. For recent
* versions of libusb, this information is kept (the data length of the
* transfer is updated) and, for device-to-host transfers, any surplus data was
* added to the buffer. Still, this is not a nice solution because it loses the
* information about the end of the short packet, and the user probably wanted
* that surplus data to arrive in the next logical transfer.
*
* \section zlp Zero length packets
*
* - libusb is able to send a packet of zero length to an endpoint simply by
* submitting a transfer of zero length.
* - The \ref libusb_transfer_flags::LIBUSB_TRANSFER_ADD_ZERO_PACKET
* "LIBUSB_TRANSFER_ADD_ZERO_PACKET" flag is currently supported on Linux,
* Darwin and Windows (WinUSB).
*/
/**
* \page libusb_contexts Contexts
*
* It is possible that libusb may be used simultaneously from two independent
* libraries linked into the same executable. For example, if your application
* has a plugin-like system which allows the user to dynamically load a range
* of modules into your program, it is feasible that two independently
* developed modules may both use libusb.
*
* libusb is written to allow for these multiple user scenarios. The two
* "instances" of libusb will not interfere: an option set by one user will have
* no effect the same option for other users, other users can continue using
* libusb after one of them calls libusb_exit(), etc.
*
* This is made possible through libusb's <em>context</em> concept. When you
* call libusb_init_context(), you are (optionally) given a context. You can then pass
* this context pointer back into future libusb functions.
*
* In order to keep things simple for more simplistic applications, it is
* legal to pass NULL to all functions requiring a context pointer (as long as
* you're sure no other code will attempt to use libusb from the same process).
* When you pass NULL, the default context will be used. The default context
* is created the first time a process calls libusb_init_context() when no other
* context is alive. Contexts are destroyed during libusb_exit().
*
* The default context is reference-counted and can be shared. That means that
* if libusb_init_context(NULL, x, y) is called twice within the same process, the two
* users end up sharing the same context. The deinitialization and freeing of
* the default context will only happen when the last user calls libusb_exit().
* In other words, the default context is created and initialized when its
* reference count goes from 0 to 1, and is deinitialized and destroyed when
* its reference count goes from 1 to 0.
*
* You may be wondering why only a subset of libusb functions require a
* context pointer in their function definition. Internally, libusb stores
* context pointers in other objects (e.g. libusb_device instances) and hence
* can infer the context from those objects.
*/
/**
* \page libusb_api Application Programming Interface
*
* This is the complete list of libusb functions, structures and
* enumerations in alphabetical order.
*
* \section Functions
* - libusb_alloc_streams()
* - libusb_alloc_transfer()
* - libusb_attach_kernel_driver()
* - libusb_bulk_transfer()
* - libusb_cancel_transfer()
* - libusb_claim_interface()
* - libusb_clear_halt()
* - libusb_close()
* - libusb_control_transfer()
* - libusb_control_transfer_get_data()
* - libusb_control_transfer_get_setup()
* - libusb_cpu_to_le16()
* - libusb_detach_kernel_driver()
* - libusb_dev_mem_alloc()
* - libusb_dev_mem_free()
* - libusb_error_name()
* - libusb_event_handler_active()
* - libusb_event_handling_ok()
* - libusb_exit()
* - libusb_fill_bulk_stream_transfer()
* - libusb_fill_bulk_transfer()
* - libusb_fill_control_setup()
* - libusb_fill_control_transfer()
* - libusb_fill_interrupt_transfer()
* - libusb_fill_iso_transfer()
* - libusb_free_bos_descriptor()
* - libusb_free_config_descriptor()
* - libusb_free_container_id_descriptor()
* - libusb_free_device_list()
* - libusb_free_pollfds()
* - libusb_free_ss_endpoint_companion_descriptor()
* - libusb_free_ss_usb_device_capability_descriptor()
* - libusb_free_streams()
* - libusb_free_transfer()
* - libusb_free_usb_2_0_extension_descriptor()
* - libusb_get_active_config_descriptor()
* - libusb_get_bos_descriptor()
* - libusb_get_bus_number()
* - libusb_get_config_descriptor()
* - libusb_get_config_descriptor_by_value()
* - libusb_get_configuration()
* - libusb_get_container_id_descriptor()
* - libusb_get_descriptor()
* - libusb_get_device()
* - libusb_get_device_address()
* - libusb_get_device_descriptor()
* - libusb_get_device_list()
* - libusb_get_device_speed()
* - libusb_get_iso_packet_buffer()
* - libusb_get_iso_packet_buffer_simple()
* - libusb_get_max_alt_packet_size()
* - libusb_get_max_iso_packet_size()
* - libusb_get_max_packet_size()
* - libusb_get_next_timeout()
* - libusb_get_parent()
* - libusb_get_pollfds()
* - libusb_get_port_number()
* - libusb_get_port_numbers()
* - libusb_get_port_path()
* - libusb_get_ss_endpoint_companion_descriptor()
* - libusb_get_ss_usb_device_capability_descriptor()
* - libusb_get_string_descriptor()
* - libusb_get_string_descriptor_ascii()
* - libusb_get_usb_2_0_extension_descriptor()
* - libusb_get_version()
* - libusb_handle_events()
* - libusb_handle_events_completed()
* - libusb_handle_events_locked()
* - libusb_handle_events_timeout()
* - libusb_handle_events_timeout_completed()
* - libusb_has_capability()
* - libusb_hotplug_deregister_callback()
* - libusb_hotplug_register_callback()
* - libusb_init()
* - libusb_init_context()
* - libusb_interrupt_event_handler()
* - libusb_interrupt_transfer()
* - libusb_kernel_driver_active()
* - libusb_lock_events()
* - libusb_lock_event_waiters()
* - libusb_open()
* - libusb_open_device_with_vid_pid()
* - libusb_pollfds_handle_timeouts()
* - libusb_ref_device()
* - libusb_release_interface()
* - libusb_reset_device()
* - libusb_set_auto_detach_kernel_driver()
* - libusb_set_configuration()
* - libusb_set_debug()
* - libusb_set_log_cb()
* - libusb_set_interface_alt_setting()
* - libusb_set_iso_packet_lengths()
* - libusb_set_option()
* - libusb_setlocale()
* - libusb_set_pollfd_notifiers()
* - libusb_strerror()
* - libusb_submit_transfer()
* - libusb_transfer_get_stream_id()
* - libusb_transfer_set_stream_id()
* - libusb_try_lock_events()
* - libusb_unlock_events()
* - libusb_unlock_event_waiters()
* - libusb_unref_device()
* - libusb_wait_for_event()
* - libusb_wrap_sys_device()
*
* \section Structures
* - libusb_bos_descriptor
* - libusb_bos_dev_capability_descriptor
* - libusb_config_descriptor
* - libusb_container_id_descriptor
* - \ref libusb_context
* - libusb_control_setup
* - \ref libusb_device
* - libusb_device_descriptor
* - \ref libusb_device_handle
* - libusb_endpoint_descriptor
* - libusb_interface
* - libusb_interface_descriptor
* - libusb_iso_packet_descriptor
* - libusb_pollfd
* - libusb_ss_endpoint_companion_descriptor
* - libusb_ss_usb_device_capability_descriptor
* - libusb_transfer
* - libusb_usb_2_0_extension_descriptor
* - libusb_version
*
* \section Enums
* - \ref libusb_bos_type
* - \ref libusb_capability
* - \ref libusb_class_code
* - \ref libusb_descriptor_type
* - \ref libusb_endpoint_direction
* - \ref libusb_endpoint_transfer_type
* - \ref libusb_error
* - \ref libusb_iso_sync_type
* - \ref libusb_iso_usage_type
* - \ref libusb_log_level
* - \ref libusb_option
* - \ref libusb_request_recipient
* - \ref libusb_request_type
* - \ref libusb_speed
* - \ref libusb_ss_usb_device_capability_attributes
* - \ref libusb_standard_request
* - \ref libusb_supported_speed
* - \ref libusb_transfer_flags
* - \ref libusb_transfer_status
* - \ref libusb_transfer_type
* - \ref libusb_usb_2_0_extension_attributes
*/
/**
* @defgroup libusb_lib Library initialization/deinitialization
* This page details how to initialize and deinitialize libusb. Initialization
* must be performed before using any libusb functionality, and similarly you
* must not call any libusb functions after deinitialization.
*/
/**
* @defgroup libusb_dev Device handling and enumeration
* The functionality documented below is designed to help with the following
* operations:
* - Enumerating the USB devices currently attached to the system
* - Choosing a device to operate from your software
* - Opening and closing the chosen device
*
* \section nutshell In a nutshell...
*
* The description below really makes things sound more complicated than they
* actually are. The following sequence of function calls will be suitable
* for almost all scenarios and does not require you to have such a deep
* understanding of the resource management issues:
* \code
// discover devices
libusb_device **list;
libusb_device *found = NULL;
ssize_t cnt = libusb_get_device_list(NULL, &list);
ssize_t i = 0;
int err = 0;
if (cnt < 0)
error();
for (i = 0; i < cnt; i++) {
libusb_device *device = list[i];
if (is_interesting(device)) {
found = device;
break;
}
}
if (found) {
libusb_device_handle *handle;
err = libusb_open(found, &handle);
if (err)
error();
// etc
}
libusb_free_device_list(list, 1);
\endcode
*
* The two important points:
* - You asked libusb_free_device_list() to unreference the devices (2nd
* parameter)
* - You opened the device before freeing the list and unreferencing the
* devices
*
* If you ended up with a handle, you can now proceed to perform I/O on the
* device.
*
* \section devshandles Devices and device handles
* libusb has a concept of a USB device, represented by the
* \ref libusb_device opaque type. A device represents a USB device that
* is currently or was previously connected to the system. Using a reference
* to a device, you can determine certain information about the device (e.g.
* you can read the descriptor data).
*
* The libusb_get_device_list() function can be used to obtain a list of
* devices currently connected to the system. This is known as device
* discovery. Devices can also be discovered with the hotplug mechanism,
* whereby a callback function registered with libusb_hotplug_register_callback()
* will be called when a device of interest is connected or disconnected.
*
* Just because you have a reference to a device does not mean it is
* necessarily usable. The device may have been unplugged, you may not have
* permission to operate such device, or another program or driver may be
* using the device.
*
* When you've found a device that you'd like to operate, you must ask
* libusb to open the device using the libusb_open() function. Assuming
* success, libusb then returns you a <em>device handle</em>
* (a \ref libusb_device_handle pointer). All "real" I/O operations then
* operate on the handle rather than the original device pointer.
*
* \section devref Device discovery and reference counting
*
* Device discovery (i.e. calling libusb_get_device_list()) returns a
* freshly-allocated list of devices. The list itself must be freed when
* you are done with it. libusb also needs to know when it is OK to free
* the contents of the list - the devices themselves.
*
* To handle these issues, libusb provides you with two separate items:
* - A function to free the list itself
* - A reference counting system for the devices inside
*
* New devices presented by the libusb_get_device_list() function all have a
* reference count of 1. You can increase and decrease reference count using
* libusb_ref_device() and libusb_unref_device(). A device is destroyed when
* its reference count reaches 0.
*
* With the above information in mind, the process of opening a device can
* be viewed as follows:
* -# Discover devices using libusb_get_device_list() or libusb_hotplug_register_callback().
* -# Choose the device that you want to operate, and call libusb_open().
* -# Unref all devices in the discovered device list.
* -# Free the discovered device list.
*
* The order is important - you must not unreference the device before
* attempting to open it, because unreferencing it may destroy the device.
*
* For convenience, the libusb_free_device_list() function includes a
* parameter to optionally unreference all the devices in the list before
* freeing the list itself. This combines steps 3 and 4 above.
*
* As an implementation detail, libusb_open() actually adds a reference to
* the device in question. This is because the device remains available
* through the handle via libusb_get_device(). The reference is deleted during
* libusb_close().
*/
/** @defgroup libusb_misc Miscellaneous */
/* we traverse usbfs without knowing how many devices we are going to find.
* so we create this discovered_devs model which is similar to a linked-list
* which grows when required. it can be freed once discovery has completed,
* eliminating the need for a list node in the libusb_device structure
* itself. */
#define DISCOVERED_DEVICES_SIZE_STEP 16
static struct discovered_devs *discovered_devs_alloc(void)
{
struct discovered_devs *ret =
malloc(sizeof(*ret) + (sizeof(void *) * DISCOVERED_DEVICES_SIZE_STEP));
if (ret) {
ret->len = 0;
ret->capacity = DISCOVERED_DEVICES_SIZE_STEP;
}
return ret;
}
static void discovered_devs_free(struct discovered_devs *discdevs)
{
size_t i;
for (i = 0; i < discdevs->len; i++)
libusb_unref_device(discdevs->devices[i]);
free(discdevs);
}
/* append a device to the discovered devices collection. may realloc itself,
* returning new discdevs. returns NULL on realloc failure. */
struct discovered_devs *discovered_devs_append(
struct discovered_devs *discdevs, struct libusb_device *dev)
{
size_t len = discdevs->len;
size_t capacity;
struct discovered_devs *new_discdevs;
/* if there is space, just append the device */
if (len < discdevs->capacity) {
discdevs->devices[len] = libusb_ref_device(dev);
discdevs->len++;
return discdevs;
}
/* exceeded capacity, need to grow */
usbi_dbg(DEVICE_CTX(dev), "need to increase capacity");
capacity = discdevs->capacity + DISCOVERED_DEVICES_SIZE_STEP;
/* can't use usbi_reallocf here because in failure cases it would
* free the existing discdevs without unreferencing its devices. */
new_discdevs = realloc(discdevs,
sizeof(*discdevs) + (sizeof(void *) * capacity));
if (!new_discdevs) {
discovered_devs_free(discdevs);
return NULL;
}
discdevs = new_discdevs;
discdevs->capacity = capacity;
discdevs->devices[len] = libusb_ref_device(dev);
discdevs->len++;
return discdevs;
}
/* Allocate a new device with a specific session ID. The returned device has
* a reference count of 1. */
struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
unsigned long session_id)
{
size_t priv_size = usbi_backend.device_priv_size;
struct libusb_device *dev = calloc(1, PTR_ALIGN(sizeof(*dev)) + priv_size);
if (!dev)
return NULL;
usbi_atomic_store(&dev->refcnt, 1);
dev->ctx = ctx;
dev->session_data = session_id;
dev->speed = LIBUSB_SPEED_UNKNOWN;
if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG))
usbi_connect_device(dev);
return dev;
}
void usbi_connect_device(struct libusb_device *dev)
{
struct libusb_context *ctx = DEVICE_CTX(dev);
usbi_atomic_store(&dev->attached, 1);
usbi_mutex_lock(&dev->ctx->usb_devs_lock);
list_add(&dev->list, &dev->ctx->usb_devs);
usbi_mutex_unlock(&dev->ctx->usb_devs_lock);
usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED);
}
void usbi_disconnect_device(struct libusb_device *dev)
{
struct libusb_context *ctx = DEVICE_CTX(dev);
usbi_atomic_store(&dev->attached, 0);
usbi_mutex_lock(&ctx->usb_devs_lock);
list_del(&dev->list);
usbi_mutex_unlock(&ctx->usb_devs_lock);
usbi_hotplug_notification(ctx, dev, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT);
}
/* Perform some final sanity checks on a newly discovered device. If this
* function fails (negative return code), the device should not be added
* to the discovered device list. */
int usbi_sanitize_device(struct libusb_device *dev)
{
uint8_t num_configurations;
if (dev->device_descriptor.bLength != LIBUSB_DT_DEVICE_SIZE ||
dev->device_descriptor.bDescriptorType != LIBUSB_DT_DEVICE) {
usbi_err(DEVICE_CTX(dev), "invalid device descriptor");
return LIBUSB_ERROR_IO;
}
num_configurations = dev->device_descriptor.bNumConfigurations;
if (num_configurations > USB_MAXCONFIG) {
usbi_err(DEVICE_CTX(dev), "too many configurations");
return LIBUSB_ERROR_IO;
} else if (0 == num_configurations) {
usbi_dbg(DEVICE_CTX(dev), "zero configurations, maybe an unauthorized device");
}
return 0;
}
/* Examine libusb's internal list of known devices, looking for one with
* a specific session ID. Returns the matching device if it was found, and
* NULL otherwise. */
struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
unsigned long session_id)
{
struct libusb_device *dev;
struct libusb_device *ret = NULL;
usbi_mutex_lock(&ctx->usb_devs_lock);
for_each_device(ctx, dev) {
if (dev->session_data == session_id) {
ret = libusb_ref_device(dev);
break;
}
}
usbi_mutex_unlock(&ctx->usb_devs_lock);
return ret;
}
/** @ingroup libusb_dev
* Returns a list of USB devices currently attached to the system. This is
* your entry point into finding a USB device to operate.
*
* You are expected to unreference all the devices when you are done with
* them, and then free the list with libusb_free_device_list(). Note that
* libusb_free_device_list() can unref all the devices for you. Be careful
* not to unreference a device you are about to open until after you have
* opened it.
*
* This return value of this function indicates the number of devices in
* the resultant list. The list is actually one element larger, as it is
* NULL-terminated.
*
* \param ctx the context to operate on, or NULL for the default context
* \param list output location for a list of devices. Must be later freed with
* libusb_free_device_list().
* \returns the number of devices in the outputted list, or any
* \ref libusb_error according to errors encountered by the backend.
*/
ssize_t API_EXPORTED libusb_get_device_list(libusb_context *ctx,
libusb_device ***list)
{
struct discovered_devs *discdevs = discovered_devs_alloc();
struct libusb_device **ret;
int r = 0;
ssize_t i, len;
usbi_dbg(ctx, " ");
if (!discdevs)
return LIBUSB_ERROR_NO_MEM;
ctx = usbi_get_context(ctx);
if (libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
/* backend provides hotplug support */
struct libusb_device *dev;
if (usbi_backend.hotplug_poll)
usbi_backend.hotplug_poll();
usbi_mutex_lock(&ctx->usb_devs_lock);
for_each_device(ctx, dev) {
discdevs = discovered_devs_append(discdevs, dev);
if (!discdevs) {
r = LIBUSB_ERROR_NO_MEM;
break;
}
}
usbi_mutex_unlock(&ctx->usb_devs_lock);
} else {
/* backend does not provide hotplug support */
r = usbi_backend.get_device_list(ctx, &discdevs);
}
if (r < 0) {
len = r;
goto out;
}
/* convert discovered_devs into a list */
len = (ssize_t)discdevs->len;
ret = calloc((size_t)len + 1, sizeof(struct libusb_device *));
if (!ret) {
len = LIBUSB_ERROR_NO_MEM;
goto out;
}
ret[len] = NULL;
for (i = 0; i < len; i++) {
struct libusb_device *dev = discdevs->devices[i];
ret[i] = libusb_ref_device(dev);
}
*list = ret;
out:
if (discdevs)
discovered_devs_free(discdevs);
return len;
}
/** \ingroup libusb_dev
* Frees a list of devices previously discovered using
* libusb_get_device_list(). If the unref_devices parameter is set, the
* reference count of each device in the list is decremented by 1.
* \param list the list to free
* \param unref_devices whether to unref the devices in the list
*/
void API_EXPORTED libusb_free_device_list(libusb_device **list,
int unref_devices)
{
if (!list)
return;
if (unref_devices) {
int i = 0;
struct libusb_device *dev;
while ((dev = list[i++]) != NULL)
libusb_unref_device(dev);
}
free(list);
}
/** \ingroup libusb_dev
* Get the number of the bus that a device is connected to.
* \param dev a device
* \returns the bus number
*/
uint8_t API_EXPORTED libusb_get_bus_number(libusb_device *dev)
{
return dev->bus_number;
}
/** \ingroup libusb_dev
* Get the number of the port that a device is connected to.
* Unless the OS does something funky, or you are hot-plugging USB extension cards,
* the port number returned by this call is usually guaranteed to be uniquely tied
* to a physical port, meaning that different devices plugged on the same physical
* port should return the same port number.
*
* But outside of this, there is no guarantee that the port number returned by this
* call will remain the same, or even match the order in which ports have been
* numbered by the HUB/HCD manufacturer.
*
* \param dev a device
* \returns the port number (0 if not available)
*/
uint8_t API_EXPORTED libusb_get_port_number(libusb_device *dev)
{
return dev->port_number;
}
/** \ingroup libusb_dev
* Get the list of all port numbers from root for the specified device
*
* Since version 1.0.16, \ref LIBUSBX_API_VERSION >= 0x01000102
* \param dev a device
* \param port_numbers the array that should contain the port numbers
* \param port_numbers_len the maximum length of the array. As per the USB 3.0
* specs, the current maximum limit for the depth is 7.
* \returns the number of elements filled
* \returns \ref LIBUSB_ERROR_OVERFLOW if the array is too small
*/
int API_EXPORTED libusb_get_port_numbers(libusb_device *dev,
uint8_t *port_numbers, int port_numbers_len)
{
int i = port_numbers_len;
struct libusb_context *ctx = DEVICE_CTX(dev);
if (port_numbers_len <= 0)
return LIBUSB_ERROR_INVALID_PARAM;
/* HCDs can be listed as devices with port #0 */
while((dev) && (dev->port_number != 0)) {
if (--i < 0) {
usbi_warn(ctx, "port numbers array is too small");
return LIBUSB_ERROR_OVERFLOW;
}
port_numbers[i] = dev->port_number;
dev = dev->parent_dev;
}
if (i < port_numbers_len)
memmove(port_numbers, &port_numbers[i], (size_t)(port_numbers_len - i));
return port_numbers_len - i;
}
/** \ingroup libusb_dev
* \deprecated Please use \ref libusb_get_port_numbers() instead.
*/
int API_EXPORTED libusb_get_port_path(libusb_context *ctx, libusb_device *dev,
uint8_t *port_numbers, uint8_t port_numbers_len)
{
UNUSED(ctx);
return libusb_get_port_numbers(dev, port_numbers, port_numbers_len);
}
/** \ingroup libusb_dev
* Get the the parent from the specified device.
* \param dev a device
* \returns the device parent or NULL if not available
* You should issue a \ref libusb_get_device_list() before calling this
* function and make sure that you only access the parent before issuing
* \ref libusb_free_device_list(). The reason is that libusb currently does
* not maintain a permanent list of device instances, and therefore can
* only guarantee that parents are fully instantiated within a
* libusb_get_device_list() - libusb_free_device_list() block.
*/
DEFAULT_VISIBILITY
libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev)
{
return dev->parent_dev;
}
/** \ingroup libusb_dev
* Get the address of the device on the bus it is connected to.