forked from Zondax/hid
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlibusbi.h
1535 lines (1312 loc) · 51.4 KB
/
libusbi.h
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
/*
* Internal header for libusb
* Copyright © 2007-2009 Daniel Drake <[email protected]>
* Copyright © 2001 Johannes Erdfelt <[email protected]>
* Copyright © 2019 Nathan Hjelm <[email protected]>
* Copyright © 2019-2020 Google LLC. All rights reserved.
* Copyright © 2020 Chris Dickens <[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
*/
#ifndef LIBUSBI_H
#define LIBUSBI_H
#include <config.h>
#include <assert.h>
#include <inttypes.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdlib.h>
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#include "libusb.h"
/* Not all C standard library headers define static_assert in assert.h
* Additionally, Visual Studio treats static_assert as a keyword.
*/
#if !defined(__cplusplus) && !defined(static_assert) && !defined(_MSC_VER)
#define static_assert(cond, msg) _Static_assert(cond, msg)
#endif
#ifdef NDEBUG
#define ASSERT_EQ(expression, value) (void)expression
#define ASSERT_NE(expression, value) (void)expression
#else
#define ASSERT_EQ(expression, value) assert(expression == value)
#define ASSERT_NE(expression, value) assert(expression != value)
#endif
#define container_of(ptr, type, member) \
((type *)((uintptr_t)(ptr) - (uintptr_t)offsetof(type, member)))
#ifndef ARRAYSIZE
#define ARRAYSIZE(array) (sizeof(array) / sizeof(array[0]))
#endif
#ifndef CLAMP
#define CLAMP(val, min, max) \
((val) < (min) ? (min) : ((val) > (max) ? (max) : (val)))
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
/* The following is used to silence warnings for unused variables */
#if defined(UNREFERENCED_PARAMETER) && !defined(__GNUC__)
#define UNUSED(var) UNREFERENCED_PARAMETER(var)
#else
#define UNUSED(var) do { (void)(var); } while(0)
#endif
/* Macro to align a value up to the next multiple of the size of a pointer */
#define PTR_ALIGN(v) \
(((v) + (sizeof(void *) - 1)) & ~(sizeof(void *) - 1))
/* Atomic operations
*
* Useful for reference counting or when accessing a value without a lock
*
* The following atomic operations are defined:
* usbi_atomic_load() - Atomically read a variable's value
* usbi_atomic_store() - Atomically write a new value value to a variable
* usbi_atomic_inc() - Atomically increment a variable's value and return the new value
* usbi_atomic_dec() - Atomically decrement a variable's value and return the new value
*
* All of these operations are ordered with each other, thus the effects of
* any one operation is guaranteed to be seen by any other operation.
*/
#ifdef _MSC_VER
typedef volatile LONG usbi_atomic_t;
#define usbi_atomic_load(a) (*(a))
#define usbi_atomic_store(a, v) (*(a)) = (v)
#define usbi_atomic_inc(a) InterlockedIncrement((a))
#define usbi_atomic_dec(a) InterlockedDecrement((a))
#else
#if defined(__HAIKU__) && defined(__GNUC__) && !defined(__clang__)
/* The Haiku port of libusb has some C++ files and GCC does not define
* anything in stdatomic.h when compiled in C++11 (only in C++23).
* This appears to be a bug in gcc's stdatomic.h, and should be fixed either
* in gcc or in Haiku. Until then, use the gcc builtins. */
typedef long usbi_atomic_t;
#define usbi_atomic_load(a) __atomic_load_n((a), __ATOMIC_SEQ_CST)
#define usbi_atomic_store(a, v) __atomic_store_n((a), (v), __ATOMIC_SEQ_CST)
#define usbi_atomic_inc(a) __atomic_add_fetch((a), 1, __ATOMIC_SEQ_CST)
#define usbi_atomic_dec(a) __atomic_sub_fetch((a), 1, __ATOMIC_SEQ_CST)
#else
#include <stdatomic.h>
typedef atomic_long usbi_atomic_t;
#define usbi_atomic_load(a) atomic_load((a))
#define usbi_atomic_store(a, v) atomic_store((a), (v))
#define usbi_atomic_inc(a) (atomic_fetch_add((a), 1) + 1)
#define usbi_atomic_dec(a) (atomic_fetch_add((a), -1) - 1)
#endif
#endif
/* Internal abstractions for event handling and thread synchronization */
#if defined(PLATFORM_POSIX)
#include "os/events_posix.h"
#include "os/threads_posix.h"
#elif defined(PLATFORM_WINDOWS)
#include "os/events_windows.h"
#include "os/threads_windows.h"
#endif
/* Inside the libusb code, mark all public functions as follows:
* return_type API_EXPORTED function_name(params) { ... }
* But if the function returns a pointer, mark it as follows:
* DEFAULT_VISIBILITY return_type * LIBUSB_CALL function_name(params) { ... }
* In the libusb public header, mark all declarations as:
* return_type LIBUSB_CALL function_name(params);
*/
#define API_EXPORTED LIBUSB_CALL DEFAULT_VISIBILITY
#define API_EXPORTEDV LIBUSB_CALLV DEFAULT_VISIBILITY
#ifdef __cplusplus
extern "C" {
#endif
#define USB_MAXENDPOINTS 32
#define USB_MAXINTERFACES 32
#define USB_MAXCONFIG 8
/* Backend specific capabilities */
#define USBI_CAP_HAS_HID_ACCESS 0x00010000
#define USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER 0x00020000
/* Maximum number of bytes in a log line */
#define USBI_MAX_LOG_LEN 1024
/* Terminator for log lines */
#define USBI_LOG_LINE_END "\n"
struct list_head {
struct list_head *prev, *next;
};
/* Get an entry from the list
* ptr - the address of this list_head element in "type"
* type - the data type that contains "member"
* member - the list_head element in "type"
*/
#define list_entry(ptr, type, member) \
container_of(ptr, type, member)
#define list_first_entry(ptr, type, member) \
list_entry((ptr)->next, type, member)
#define list_next_entry(ptr, type, member) \
list_entry((ptr)->member.next, type, member)
/* Get each entry from a list
* pos - A structure pointer has a "member" element
* head - list head
* member - the list_head element in "pos"
* type - the type of the first parameter
*/
#define list_for_each_entry(pos, head, member, type) \
for (pos = list_first_entry(head, type, member); \
&pos->member != (head); \
pos = list_next_entry(pos, type, member))
#define list_for_each_entry_safe(pos, n, head, member, type) \
for (pos = list_first_entry(head, type, member), \
n = list_next_entry(pos, type, member); \
&pos->member != (head); \
pos = n, n = list_next_entry(n, type, member))
/* Helper macros to iterate over a list. The structure pointed
* to by "pos" must have a list_head member named "list".
*/
#define for_each_helper(pos, head, type) \
list_for_each_entry(pos, head, list, type)
#define for_each_safe_helper(pos, n, head, type) \
list_for_each_entry_safe(pos, n, head, list, type)
#define list_empty(entry) ((entry)->next == (entry))
static inline void list_init(struct list_head *entry)
{
entry->prev = entry->next = entry;
}
static inline void list_add(struct list_head *entry, struct list_head *head)
{
entry->next = head->next;
entry->prev = head;
head->next->prev = entry;
head->next = entry;
}
static inline void list_add_tail(struct list_head *entry,
struct list_head *head)
{
entry->next = head;
entry->prev = head->prev;
head->prev->next = entry;
head->prev = entry;
}
static inline void list_del(struct list_head *entry)
{
entry->next->prev = entry->prev;
entry->prev->next = entry->next;
entry->next = entry->prev = NULL;
}
static inline void list_cut(struct list_head *list, struct list_head *head)
{
if (list_empty(head)) {
list_init(list);
return;
}
list->next = head->next;
list->next->prev = list;
list->prev = head->prev;
list->prev->next = list;
list_init(head);
}
static inline void list_splice_front(struct list_head *list, struct list_head *head)
{
list->next->prev = head;
list->prev->next = head->next;
head->next->prev = list->prev;
head->next = list->next;
}
static inline void *usbi_reallocf(void *ptr, size_t size)
{
void *ret = realloc(ptr, size);
if (!ret)
free(ptr);
return ret;
}
#if !defined(USEC_PER_SEC)
#define USEC_PER_SEC 1000000L
#endif
#if !defined(NSEC_PER_SEC)
#define NSEC_PER_SEC 1000000000L
#endif
#define TIMEVAL_IS_VALID(tv) \
((tv)->tv_sec >= 0 && \
(tv)->tv_usec >= 0 && (tv)->tv_usec < USEC_PER_SEC)
#define TIMESPEC_IS_SET(ts) ((ts)->tv_sec || (ts)->tv_nsec)
#define TIMESPEC_CLEAR(ts) (ts)->tv_sec = (ts)->tv_nsec = 0
#define TIMESPEC_CMP(a, b, CMP) \
(((a)->tv_sec == (b)->tv_sec) \
? ((a)->tv_nsec CMP (b)->tv_nsec) \
: ((a)->tv_sec CMP (b)->tv_sec))
#define TIMESPEC_SUB(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
(result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \
if ((result)->tv_nsec < 0L) { \
--(result)->tv_sec; \
(result)->tv_nsec += NSEC_PER_SEC; \
} \
} while (0)
#if defined(PLATFORM_WINDOWS)
#define TIMEVAL_TV_SEC_TYPE long
#else
#define TIMEVAL_TV_SEC_TYPE time_t
#endif
/* Some platforms don't have this define */
#ifndef TIMESPEC_TO_TIMEVAL
#define TIMESPEC_TO_TIMEVAL(tv, ts) \
do { \
(tv)->tv_sec = (TIMEVAL_TV_SEC_TYPE) (ts)->tv_sec; \
(tv)->tv_usec = (ts)->tv_nsec / 1000L; \
} while (0)
#endif
#ifdef ENABLE_LOGGING
#if defined(_MSC_VER) && (_MSC_VER < 1900)
#include <stdio.h>
#define snprintf usbi_snprintf
#define vsnprintf usbi_vsnprintf
int usbi_snprintf(char *dst, size_t size, const char *format, ...);
int usbi_vsnprintf(char *dst, size_t size, const char *format, va_list args);
#define LIBUSB_PRINTF_WIN32
#endif /* defined(_MSC_VER) && (_MSC_VER < 1900) */
void usbi_log(struct libusb_context *ctx, enum libusb_log_level level,
const char *function, const char *format, ...) PRINTF_FORMAT(4, 5);
#define _usbi_log(ctx, level, ...) usbi_log(ctx, level, __func__, __VA_ARGS__)
#define usbi_err(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_ERROR, __VA_ARGS__)
#define usbi_warn(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_WARNING, __VA_ARGS__)
#define usbi_info(ctx, ...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_INFO, __VA_ARGS__)
#define usbi_dbg(ctx ,...) _usbi_log(ctx, LIBUSB_LOG_LEVEL_DEBUG, __VA_ARGS__)
#else /* ENABLE_LOGGING */
#define usbi_err(ctx, ...) do { (void)(ctx); } while(0)
#define usbi_warn(ctx, ...) do { (void)(ctx); } while(0)
#define usbi_info(ctx, ...) do { (void)(ctx); } while(0)
#define usbi_dbg(ctx, ...) do { (void)(ctx); } while(0)
#endif /* ENABLE_LOGGING */
#define DEVICE_CTX(dev) ((dev)->ctx)
#define HANDLE_CTX(handle) ((handle) ? DEVICE_CTX((handle)->dev) : NULL)
#define ITRANSFER_CTX(itransfer) \
((itransfer)->dev ? DEVICE_CTX((itransfer)->dev) : NULL)
#define TRANSFER_CTX(transfer) \
(ITRANSFER_CTX(LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer)))
#define IS_EPIN(ep) (0 != ((ep) & LIBUSB_ENDPOINT_IN))
#define IS_EPOUT(ep) (!IS_EPIN(ep))
#define IS_XFERIN(xfer) (0 != ((xfer)->endpoint & LIBUSB_ENDPOINT_IN))
#define IS_XFEROUT(xfer) (!IS_XFERIN(xfer))
struct libusb_context {
#if defined(ENABLE_LOGGING) && !defined(ENABLE_DEBUG_LOGGING)
enum libusb_log_level debug;
int debug_fixed;
libusb_log_cb log_handler;
#endif
/* used for signalling occurrence of an internal event. */
usbi_event_t event;
#ifdef HAVE_OS_TIMER
/* used for timeout handling, if supported by OS.
* this timer is maintained to trigger on the next pending timeout */
usbi_timer_t timer;
#endif
struct list_head usb_devs;
usbi_mutex_t usb_devs_lock;
/* A list of open handles. Backends are free to traverse this if required.
*/
struct list_head open_devs;
usbi_mutex_t open_devs_lock;
/* A list of registered hotplug callbacks */
struct list_head hotplug_cbs;
libusb_hotplug_callback_handle next_hotplug_cb_handle;
usbi_mutex_t hotplug_cbs_lock;
/* A flag to indicate that the context is ready for hotplug notifications */
usbi_atomic_t hotplug_ready;
/* this is a list of in-flight transfer handles, sorted by timeout
* expiration. URBs to timeout the soonest are placed at the beginning of
* the list, URBs that will time out later are placed after, and urbs with
* infinite timeout are always placed at the very end. */
struct list_head flying_transfers;
/* Note paths taking both this and usbi_transfer->lock must always
* take this lock first */
usbi_mutex_t flying_transfers_lock; /* for flying_transfers and timeout_flags */
#if !defined(PLATFORM_WINDOWS)
/* user callbacks for pollfd changes */
libusb_pollfd_added_cb fd_added_cb;
libusb_pollfd_removed_cb fd_removed_cb;
void *fd_cb_user_data;
#endif
/* ensures that only one thread is handling events at any one time */
usbi_mutex_t events_lock;
/* used to see if there is an active thread doing event handling */
int event_handler_active;
/* A thread-local storage key to track which thread is performing event
* handling */
usbi_tls_key_t event_handling_key;
/* used to wait for event completion in threads other than the one that is
* event handling */
usbi_mutex_t event_waiters_lock;
usbi_cond_t event_waiters_cond;
/* A lock to protect internal context event data. */
usbi_mutex_t event_data_lock;
/* A bitmask of flags that are set to indicate specific events that need to
* be handled. Protected by event_data_lock. */
unsigned int event_flags;
/* A counter that is set when we want to interrupt and prevent event handling,
* in order to safely close a device. Protected by event_data_lock. */
unsigned int device_close;
/* A list of currently active event sources. Protected by event_data_lock. */
struct list_head event_sources;
/* A list of event sources that have been removed since the last time
* event sources were waited on. Protected by event_data_lock. */
struct list_head removed_event_sources;
/* A pointer and count to platform-specific data used for monitoring event
* sources. Only accessed during event handling. */
void *event_data;
unsigned int event_data_cnt;
/* A list of pending hotplug messages. Protected by event_data_lock. */
struct list_head hotplug_msgs;
/* A list of pending completed transfers. Protected by event_data_lock. */
struct list_head completed_transfers;
struct list_head list;
};
extern struct libusb_context *usbi_default_context;
extern struct libusb_context *usbi_fallback_context;
extern struct list_head active_contexts_list;
extern usbi_mutex_static_t active_contexts_lock;
static inline struct libusb_context *usbi_get_context(struct libusb_context *ctx)
{
static int warned = 0;
if (!ctx) {
ctx = usbi_default_context;
}
if (!ctx) {
ctx = usbi_fallback_context;
if (ctx && warned == 0) {
usbi_err(ctx, "API misuse! Using non-default context as implicit default.");
warned = 1;
}
}
return ctx;
}
enum usbi_event_flags {
/* The list of event sources has been modified */
USBI_EVENT_EVENT_SOURCES_MODIFIED = 1U << 0,
/* The user has interrupted the event handler */
USBI_EVENT_USER_INTERRUPT = 1U << 1,
/* A hotplug callback deregistration is pending */
USBI_EVENT_HOTPLUG_CB_DEREGISTERED = 1U << 2,
/* One or more hotplug messages are pending */
USBI_EVENT_HOTPLUG_MSG_PENDING = 1U << 3,
/* One or more completed transfers are pending */
USBI_EVENT_TRANSFER_COMPLETED = 1U << 4,
/* A device is in the process of being closed */
USBI_EVENT_DEVICE_CLOSE = 1U << 5,
};
/* Macros for managing event handling state */
static inline int usbi_handling_events(struct libusb_context *ctx)
{
return usbi_tls_key_get(ctx->event_handling_key) != NULL;
}
static inline void usbi_start_event_handling(struct libusb_context *ctx)
{
usbi_tls_key_set(ctx->event_handling_key, ctx);
}
static inline void usbi_end_event_handling(struct libusb_context *ctx)
{
usbi_tls_key_set(ctx->event_handling_key, NULL);
}
struct libusb_device {
usbi_atomic_t refcnt;
struct libusb_context *ctx;
struct libusb_device *parent_dev;
uint8_t bus_number;
uint8_t port_number;
uint8_t device_address;
enum libusb_speed speed;
struct list_head list;
unsigned long session_data;
struct libusb_device_descriptor device_descriptor;
usbi_atomic_t attached;
};
struct libusb_device_handle {
/* lock protects claimed_interfaces */
usbi_mutex_t lock;
unsigned long claimed_interfaces;
struct list_head list;
struct libusb_device *dev;
int auto_detach_kernel_driver;
};
/* Function called by backend during device initialization to convert
* multi-byte fields in the device descriptor to host-endian format.
*/
static inline void usbi_localize_device_descriptor(struct libusb_device_descriptor *desc)
{
desc->bcdUSB = libusb_le16_to_cpu(desc->bcdUSB);
desc->idVendor = libusb_le16_to_cpu(desc->idVendor);
desc->idProduct = libusb_le16_to_cpu(desc->idProduct);
desc->bcdDevice = libusb_le16_to_cpu(desc->bcdDevice);
}
#if defined(HAVE_CLOCK_GETTIME) && !defined(__APPLE__)
static inline void usbi_get_monotonic_time(struct timespec *tp)
{
ASSERT_EQ(clock_gettime(CLOCK_MONOTONIC, tp), 0);
}
static inline void usbi_get_real_time(struct timespec *tp)
{
ASSERT_EQ(clock_gettime(CLOCK_REALTIME, tp), 0);
}
#else
/* If the platform doesn't provide the clock_gettime() function, the backend
* must provide its own clock implementations. Two clock functions are
* required:
*
* usbi_get_monotonic_time(): returns the time since an unspecified starting
* point (usually boot) that is monotonically
* increasing.
* usbi_get_real_time(): returns the time since system epoch.
*/
void usbi_get_monotonic_time(struct timespec *tp);
void usbi_get_real_time(struct timespec *tp);
#endif
/* in-memory transfer layout:
*
* 1. os private data
* 2. struct usbi_transfer
* 3. struct libusb_transfer (which includes iso packets) [variable size]
*
* You can convert between them with the macros:
* TRANSFER_PRIV_TO_USBI_TRANSFER
* USBI_TRANSFER_TO_TRANSFER_PRIV
* USBI_TRANSFER_TO_LIBUSB_TRANSFER
* LIBUSB_TRANSFER_TO_USBI_TRANSFER
*/
struct usbi_transfer {
int num_iso_packets;
struct list_head list;
struct list_head completed_list;
struct timespec timeout;
int transferred;
uint32_t stream_id;
uint32_t state_flags; /* Protected by usbi_transfer->lock */
uint32_t timeout_flags; /* Protected by the flying_transfers_lock */
/* The device reference is held until destruction for logging
* even after dev_handle is set to NULL. */
struct libusb_device *dev;
/* this lock is held during libusb_submit_transfer() and
* libusb_cancel_transfer() (allowing the OS backend to prevent duplicate
* cancellation, submission-during-cancellation, etc). the OS backend
* should also take this lock in the handle_events path, to prevent the user
* cancelling the transfer from another thread while you are processing
* its completion (presumably there would be races within your OS backend
* if this were possible).
* Note paths taking both this and the flying_transfers_lock must
* always take the flying_transfers_lock first */
usbi_mutex_t lock;
void *priv;
};
enum usbi_transfer_state_flags {
/* Transfer successfully submitted by backend */
USBI_TRANSFER_IN_FLIGHT = 1U << 0,
/* Cancellation was requested via libusb_cancel_transfer() */
USBI_TRANSFER_CANCELLING = 1U << 1,
/* Operation on the transfer failed because the device disappeared */
USBI_TRANSFER_DEVICE_DISAPPEARED = 1U << 2,
};
enum usbi_transfer_timeout_flags {
/* Set by backend submit_transfer() if the OS handles timeout */
USBI_TRANSFER_OS_HANDLES_TIMEOUT = 1U << 0,
/* The transfer timeout has been handled */
USBI_TRANSFER_TIMEOUT_HANDLED = 1U << 1,
/* The transfer timeout was successfully processed */
USBI_TRANSFER_TIMED_OUT = 1U << 2,
};
#define TRANSFER_PRIV_TO_USBI_TRANSFER(transfer_priv) \
((struct usbi_transfer *) \
((unsigned char *)(transfer_priv) \
+ PTR_ALIGN(sizeof(*transfer_priv))))
#define USBI_TRANSFER_TO_TRANSFER_PRIV(itransfer) \
((unsigned char *) \
((unsigned char *)(itransfer) \
- PTR_ALIGN(usbi_backend.transfer_priv_size)))
#define USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer) \
((struct libusb_transfer *) \
((unsigned char *)(itransfer) \
+ PTR_ALIGN(sizeof(struct usbi_transfer))))
#define LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer) \
((struct usbi_transfer *) \
((unsigned char *)(transfer) \
- PTR_ALIGN(sizeof(struct usbi_transfer))))
#ifdef _MSC_VER
#pragma pack(push, 1)
#endif
/* All standard descriptors have these 2 fields in common */
struct usbi_descriptor_header {
uint8_t bLength;
uint8_t bDescriptorType;
} LIBUSB_PACKED;
struct usbi_device_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint16_t idVendor;
uint16_t idProduct;
uint16_t bcdDevice;
uint8_t iManufacturer;
uint8_t iProduct;
uint8_t iSerialNumber;
uint8_t bNumConfigurations;
} LIBUSB_PACKED;
struct usbi_configuration_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumInterfaces;
uint8_t bConfigurationValue;
uint8_t iConfiguration;
uint8_t bmAttributes;
uint8_t bMaxPower;
} LIBUSB_PACKED;
struct usbi_interface_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bInterfaceNumber;
uint8_t bAlternateSetting;
uint8_t bNumEndpoints;
uint8_t bInterfaceClass;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
uint8_t iInterface;
} LIBUSB_PACKED;
struct usbi_string_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wData[LIBUSB_FLEXIBLE_ARRAY];
} LIBUSB_PACKED;
struct usbi_bos_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumDeviceCaps;
} LIBUSB_PACKED;
#ifdef _MSC_VER
#pragma pack(pop)
#endif
union usbi_config_desc_buf {
struct usbi_configuration_descriptor desc;
uint8_t buf[LIBUSB_DT_CONFIG_SIZE];
uint16_t align; /* Force 2-byte alignment */
};
union usbi_string_desc_buf {
struct usbi_string_descriptor desc;
uint8_t buf[255]; /* Some devices choke on size > 255 */
uint16_t align; /* Force 2-byte alignment */
};
union usbi_bos_desc_buf {
struct usbi_bos_descriptor desc;
uint8_t buf[LIBUSB_DT_BOS_SIZE];
uint16_t align; /* Force 2-byte alignment */
};
enum usbi_hotplug_flags {
/* This callback is interested in device arrivals */
USBI_HOTPLUG_DEVICE_ARRIVED = LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
/* This callback is interested in device removals */
USBI_HOTPLUG_DEVICE_LEFT = LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT,
/* IMPORTANT: The values for the below entries must start *after*
* the highest value of the above entries!!!
*/
/* The vendor_id field is valid for matching */
USBI_HOTPLUG_VENDOR_ID_VALID = (1U << 3),
/* The product_id field is valid for matching */
USBI_HOTPLUG_PRODUCT_ID_VALID = (1U << 4),
/* The dev_class field is valid for matching */
USBI_HOTPLUG_DEV_CLASS_VALID = (1U << 5),
/* This callback has been unregistered and needs to be freed */
USBI_HOTPLUG_NEEDS_FREE = (1U << 6),
};
struct usbi_hotplug_callback {
/* Flags that control how this callback behaves */
uint8_t flags;
/* Vendor ID to match (if flags says this is valid) */
uint16_t vendor_id;
/* Product ID to match (if flags says this is valid) */
uint16_t product_id;
/* Device class to match (if flags says this is valid) */
uint8_t dev_class;
/* Callback function to invoke for matching event/device */
libusb_hotplug_callback_fn cb;
/* Handle for this callback (used to match on deregister) */
libusb_hotplug_callback_handle handle;
/* User data that will be passed to the callback function */
void *user_data;
/* List this callback is registered in (ctx->hotplug_cbs) */
struct list_head list;
};
struct usbi_hotplug_message {
/* The hotplug event that occurred */
libusb_hotplug_event event;
/* The device for which this hotplug event occurred */
struct libusb_device *device;
/* List this message is contained in (ctx->hotplug_msgs) */
struct list_head list;
};
/* shared data and functions */
void usbi_hotplug_init(struct libusb_context *ctx);
void usbi_hotplug_exit(struct libusb_context *ctx);
void usbi_hotplug_notification(struct libusb_context *ctx, struct libusb_device *dev,
libusb_hotplug_event event);
void usbi_hotplug_process(struct libusb_context *ctx, struct list_head *hotplug_msgs);
int usbi_io_init(struct libusb_context *ctx);
void usbi_io_exit(struct libusb_context *ctx);
struct libusb_device *usbi_alloc_device(struct libusb_context *ctx,
unsigned long session_id);
struct libusb_device *usbi_get_device_by_session_id(struct libusb_context *ctx,
unsigned long session_id);
int usbi_sanitize_device(struct libusb_device *dev);
void usbi_handle_disconnect(struct libusb_device_handle *dev_handle);
int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
enum libusb_transfer_status status);
int usbi_handle_transfer_cancellation(struct usbi_transfer *itransfer);
void usbi_signal_transfer_completion(struct usbi_transfer *itransfer);
void usbi_connect_device(struct libusb_device *dev);
void usbi_disconnect_device(struct libusb_device *dev);
struct usbi_event_source {
struct usbi_event_source_data {
usbi_os_handle_t os_handle;
short poll_events;
} data;
struct list_head list;
};
int usbi_add_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle,
short poll_events);
void usbi_remove_event_source(struct libusb_context *ctx, usbi_os_handle_t os_handle);
struct usbi_option {
int is_set;
union {
int ival;
libusb_log_cb log_cbval;
} arg;
};
/* OS event abstraction */
int usbi_create_event(usbi_event_t *event);
void usbi_destroy_event(usbi_event_t *event);
void usbi_signal_event(usbi_event_t *event);
void usbi_clear_event(usbi_event_t *event);
#ifdef HAVE_OS_TIMER
int usbi_create_timer(usbi_timer_t *timer);
void usbi_destroy_timer(usbi_timer_t *timer);
int usbi_arm_timer(usbi_timer_t *timer, const struct timespec *timeout);
int usbi_disarm_timer(usbi_timer_t *timer);
#endif
static inline int usbi_using_timer(struct libusb_context *ctx)
{
#ifdef HAVE_OS_TIMER
return usbi_timer_valid(&ctx->timer);
#else
UNUSED(ctx);
return 0;
#endif
}
struct usbi_reported_events {
union {
struct {
unsigned int event_triggered:1;
#ifdef HAVE_OS_TIMER
unsigned int timer_triggered:1;
#endif
};
unsigned int event_bits;
};
void *event_data;
unsigned int event_data_count;
unsigned int num_ready;
};
int usbi_alloc_event_data(struct libusb_context *ctx);
int usbi_wait_for_events(struct libusb_context *ctx,
struct usbi_reported_events *reported_events, int timeout_ms);
/* accessor functions for structure private data */
static inline void *usbi_get_context_priv(struct libusb_context *ctx)
{
return (unsigned char *)ctx + PTR_ALIGN(sizeof(*ctx));
}
static inline void *usbi_get_device_priv(struct libusb_device *dev)
{
return (unsigned char *)dev + PTR_ALIGN(sizeof(*dev));
}
static inline void *usbi_get_device_handle_priv(struct libusb_device_handle *dev_handle)
{
return (unsigned char *)dev_handle + PTR_ALIGN(sizeof(*dev_handle));
}
static inline void *usbi_get_transfer_priv(struct usbi_transfer *itransfer)
{
return itransfer->priv;
}
/* device discovery */
/* 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. */
struct discovered_devs {
size_t len;
size_t capacity;
struct libusb_device *devices[LIBUSB_FLEXIBLE_ARRAY];
};
struct discovered_devs *discovered_devs_append(
struct discovered_devs *discdevs, struct libusb_device *dev);
/* OS abstraction */
/* This is the interface that OS backends need to implement.
* All fields are mandatory, except ones explicitly noted as optional. */
struct usbi_os_backend {
/* A human-readable name for your backend, e.g. "Linux usbfs" */
const char *name;
/* Binary mask for backend specific capabilities */
uint32_t caps;
/* Perform initialization of your backend. You might use this function
* to determine specific capabilities of the system, allocate required
* data structures for later, etc.
*
* This function is called when a libusb user initializes the library
* prior to use. Mutual exclusion with other init and exit calls is
* guaranteed when this function is called.
*
* Return 0 on success, or a LIBUSB_ERROR code on failure.
*/
int (*init)(struct libusb_context *ctx);
/* Deinitialization. Optional. This function should destroy anything
* that was set up by init.
*
* This function is called when the user deinitializes the library.
* Mutual exclusion with other init and exit calls is guaranteed when
* this function is called.
*/
void (*exit)(struct libusb_context *ctx);
/* Set a backend-specific option. Optional.
*
* This function is called when the user calls libusb_set_option() and
* the option is not handled by the core library.
*
* Return 0 on success, or a LIBUSB_ERROR code on failure.
*/
int (*set_option)(struct libusb_context *ctx, enum libusb_option option,
va_list args);
/* Enumerate all the USB devices on the system, returning them in a list
* of discovered devices.
*
* Your implementation should enumerate all devices on the system,
* regardless of whether they have been seen before or not.
*
* When you have found a device, compute a session ID for it. The session
* ID should uniquely represent that particular device for that particular
* connection session since boot (i.e. if you disconnect and reconnect a
* device immediately after, it should be assigned a different session ID).
* If your OS cannot provide a unique session ID as described above,
* presenting a session ID of (bus_number << 8 | device_address) should
* be sufficient. Bus numbers and device addresses wrap and get reused,
* but that is an unlikely case.
*
* After computing a session ID for a device, call
* usbi_get_device_by_session_id(). This function checks if libusb already
* knows about the device, and if so, it provides you with a reference
* to a libusb_device structure for it.
*
* If usbi_get_device_by_session_id() returns NULL, it is time to allocate
* a new device structure for the device. Call usbi_alloc_device() to
* obtain a new libusb_device structure with reference count 1. Populate
* the bus_number and device_address attributes of the new device, and
* perform any other internal backend initialization you need to do. At
* this point, you should be ready to provide device descriptors and so
* on through the get_*_descriptor functions. Finally, call
* usbi_sanitize_device() to perform some final sanity checks on the
* device. Assuming all of the above succeeded, we can now continue.
* If any of the above failed, remember to unreference the device that
* was returned by usbi_alloc_device().