-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.c
1284 lines (1080 loc) · 34.2 KB
/
io.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
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#ifdef USBI_TIMERFD_AVAILABLE
#include <unistd.h>
#include <sys/timerfd.h>
#endif
#include "libusbi.h"
#include "hotplug.h"
int usbi_io_init(struct libusb_context *ctx)
{
int r;
pthread_mutex_init(&ctx->flying_transfers_lock, NULL);
pthread_mutex_init(&ctx->events_lock, NULL);
pthread_mutex_init(&ctx->event_waiters_lock, NULL);
pthread_cond_init(&ctx->event_waiters_cond, NULL);
pthread_mutex_init(&ctx->event_data_lock, NULL);
pthread_key_create(&ctx->event_handling_key, NULL);
list_init(&ctx->flying_transfers);
list_init(&ctx->ipollfds);
list_init(&ctx->removed_ipollfds);
list_init(&ctx->hotplug_msgs);
list_init(&ctx->completed_transfers);
/* FIXME should use an eventfd on kernels that support it */
r = usbi_pipe(ctx->event_pipe);
if (r < 0) {
r = LIBUSB_ERROR_OTHER;
goto err;
}
r = usbi_add_pollfd(ctx, ctx->event_pipe[0], POLLIN);
if (r < 0)
goto err_close_pipe;
#ifdef USBI_TIMERFD_AVAILABLE
ctx->timerfd = timerfd_create(usbi_backend.get_timerfd_clockid(),
TFD_NONBLOCK | TFD_CLOEXEC);
if (ctx->timerfd >= 0) {
usbi_dbg("using timerfd for timeouts");
r = usbi_add_pollfd(ctx, ctx->timerfd, POLLIN);
if (r < 0)
goto err_close_timerfd;
} else {
usbi_dbg("timerfd not available (code %d error %d)", ctx->timerfd, errno);
ctx->timerfd = -1;
}
#endif
return 0;
#ifdef USBI_TIMERFD_AVAILABLE
err_close_timerfd:
close(ctx->timerfd);
usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
#endif
err_close_pipe:
close(ctx->event_pipe[0]);
close(ctx->event_pipe[1]);
err:
pthread_mutex_destroy(&ctx->flying_transfers_lock);
pthread_mutex_destroy(&ctx->events_lock);
pthread_mutex_destroy(&ctx->event_waiters_lock);
pthread_cond_destroy(&ctx->event_waiters_cond);
pthread_mutex_destroy(&ctx->event_data_lock);
pthread_key_delete(ctx->event_handling_key);
return r;
}
static void cleanup_removed_pollfds(struct libusb_context *ctx)
{
struct usbi_pollfd *ipollfd, *tmp;
list_for_each_entry_safe(ipollfd, tmp, &ctx->removed_ipollfds, list, struct usbi_pollfd) {
list_del(&ipollfd->list);
free(ipollfd);
}
}
void usbi_io_exit(struct libusb_context *ctx)
{
usbi_remove_pollfd(ctx, ctx->event_pipe[0]);
close(ctx->event_pipe[0]);
close(ctx->event_pipe[1]);
#ifdef USBI_TIMERFD_AVAILABLE
if (usbi_using_timerfd(ctx)) {
usbi_remove_pollfd(ctx, ctx->timerfd);
close(ctx->timerfd);
}
#endif
pthread_mutex_destroy(&ctx->flying_transfers_lock);
pthread_mutex_destroy(&ctx->events_lock);
pthread_mutex_destroy(&ctx->event_waiters_lock);
pthread_cond_destroy(&ctx->event_waiters_cond);
pthread_mutex_destroy(&ctx->event_data_lock);
pthread_key_delete(ctx->event_handling_key);
free(ctx->pollfds);
cleanup_removed_pollfds(ctx);
}
static int calculate_timeout(struct usbi_transfer *transfer)
{
int r;
struct timespec current_time;
unsigned int timeout =
USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout;
if (!timeout) {
timerclear(&transfer->timeout);
return 0;
}
r = usbi_backend.clock_gettime(USBI_CLOCK_MONOTONIC, ¤t_time);
if (r < 0) {
usbi_err(ITRANSFER_CTX(transfer),
"failed to read monotonic clock, errno=%d", errno);
return r;
}
current_time.tv_sec += timeout / 1000;
current_time.tv_nsec += (timeout % 1000) * 1000000;
while (current_time.tv_nsec >= 1000000000) {
current_time.tv_nsec -= 1000000000;
current_time.tv_sec++;
}
TIMESPEC_TO_TIMEVAL(&transfer->timeout, ¤t_time);
return 0;
}
DEFAULT_VISIBILITY
struct libusb_transfer *libusb_alloc_transfer(
int iso_packets)
{
struct libusb_transfer *transfer;
size_t os_alloc_size;
size_t alloc_size;
struct usbi_transfer *itransfer;
assert(iso_packets >= 0);
os_alloc_size = usbi_backend.transfer_priv_size;
alloc_size = sizeof(struct usbi_transfer)
+ sizeof(struct libusb_transfer)
+ (sizeof(struct libusb_iso_packet_descriptor) * (size_t)iso_packets)
+ os_alloc_size;
itransfer = calloc(1, alloc_size);
if (!itransfer)
return NULL;
itransfer->num_iso_packets = iso_packets;
pthread_mutex_init(&itransfer->lock, NULL);
transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
usbi_dbg("transfer %p", transfer);
return transfer;
}
void API_EXPORTED libusb_free_transfer(struct libusb_transfer *transfer)
{
struct usbi_transfer *itransfer;
if (!transfer)
return;
usbi_dbg("transfer %p", transfer);
if (transfer->flags & LIBUSB_TRANSFER_FREE_BUFFER)
free(transfer->buffer);
itransfer = LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
pthread_mutex_destroy(&itransfer->lock);
free(itransfer);
}
#ifdef USBI_TIMERFD_AVAILABLE
static int disarm_timerfd(struct libusb_context *ctx)
{
const struct itimerspec disarm_timer = { { 0, 0 }, { 0, 0 } };
int r;
usbi_dbg("a");
r = timerfd_settime(ctx->timerfd, 0, &disarm_timer, NULL);
if (r < 0)
return LIBUSB_ERROR_OTHER;
else
return 0;
}
static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
{
struct usbi_transfer *transfer;
list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
struct timeval *cur_tv = &transfer->timeout;
/* if we've reached transfers of infinite timeout, then we have no
* arming to do */
if (!timerisset(cur_tv))
goto disarm;
/* act on first transfer that has not already been handled */
if (!(transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))) {
int r;
const struct itimerspec it = { {0, 0},
{ cur_tv->tv_sec, cur_tv->tv_usec * 1000 } };
usbi_dbg("next timeout originally %dms", USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
if (r < 0)
return LIBUSB_ERROR_OTHER;
return 0;
}
}
disarm:
return disarm_timerfd(ctx);
}
#else
static int arm_timerfd_for_next_timeout(struct libusb_context *ctx)
{
UNUSED(ctx);
return 0;
}
#endif
static int add_to_flying_list(struct usbi_transfer *transfer)
{
struct usbi_transfer *cur;
struct timeval *timeout = &transfer->timeout;
struct libusb_context *ctx = ITRANSFER_CTX(transfer);
int r;
int first = 1;
r = calculate_timeout(transfer);
if (r)
return r;
/* if we have no other flying transfers, start the list with this one */
if (list_empty(&ctx->flying_transfers)) {
list_add(&transfer->list, &ctx->flying_transfers);
goto out;
}
/* if we have infinite timeout, append to end of list */
if (!timerisset(timeout)) {
list_add_tail(&transfer->list, &ctx->flying_transfers);
/* first is irrelevant in this case */
goto out;
}
/* otherwise, find appropriate place in list */
list_for_each_entry(cur, &ctx->flying_transfers, list, struct usbi_transfer) {
/* find first timeout that occurs after the transfer in question */
struct timeval *cur_tv = &cur->timeout;
if (!timerisset(cur_tv) || (cur_tv->tv_sec > timeout->tv_sec) ||
(cur_tv->tv_sec == timeout->tv_sec &&
cur_tv->tv_usec > timeout->tv_usec)) {
list_add_tail(&transfer->list, &cur->list);
goto out;
}
first = 0;
}
/* first is 0 at this stage (list not empty) */
/* otherwise we need to be inserted at the end */
list_add_tail(&transfer->list, &ctx->flying_transfers);
out:
#ifdef USBI_TIMERFD_AVAILABLE
if (first && usbi_using_timerfd(ctx) && timerisset(timeout)) {
/* if this transfer has the lowest timeout of all active transfers,
* rearm the timerfd with this transfer's timeout */
const struct itimerspec it = { {0, 0},
{ timeout->tv_sec, timeout->tv_usec * 1000 } };
usbi_dbg("arm timerfd for timeout in %dms (first in line)",
USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->timeout);
r = timerfd_settime(ctx->timerfd, TFD_TIMER_ABSTIME, &it, NULL);
if (r < 0) {
usbi_warn(ctx, "failed to arm first timerfd (errno %d)", errno);
r = LIBUSB_ERROR_OTHER;
}
}
#else
UNUSED(first);
#endif
if (r)
list_del(&transfer->list);
return r;
}
static int remove_from_flying_list(struct usbi_transfer *transfer)
{
struct libusb_context *ctx = ITRANSFER_CTX(transfer);
int rearm_timerfd;
int r = 0;
pthread_mutex_lock(&ctx->flying_transfers_lock);
rearm_timerfd = (timerisset(&transfer->timeout) &&
list_first_entry(&ctx->flying_transfers, struct usbi_transfer, list) == transfer);
list_del(&transfer->list);
if (usbi_using_timerfd(ctx) && rearm_timerfd)
r = arm_timerfd_for_next_timeout(ctx);
pthread_mutex_unlock(&ctx->flying_transfers_lock);
return r;
}
int API_EXPORTED libusb_submit_transfer(struct libusb_transfer *transfer)
{
struct usbi_transfer *itransfer =
LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
struct libusb_context *ctx = TRANSFER_CTX(transfer);
int r;
usbi_dbg("transfer %p", transfer);
pthread_mutex_lock(&ctx->flying_transfers_lock);
pthread_mutex_lock(&itransfer->lock);
if (itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT) {
pthread_mutex_unlock(&ctx->flying_transfers_lock);
pthread_mutex_unlock(&itransfer->lock);
return LIBUSB_ERROR_BUSY;
}
itransfer->transferred = 0;
itransfer->state_flags = 0;
itransfer->timeout_flags = 0;
r = add_to_flying_list(itransfer);
if (r) {
pthread_mutex_unlock(&ctx->flying_transfers_lock);
pthread_mutex_unlock(&itransfer->lock);
return r;
}
/*
* We must release the flying transfers lock here, because with
* some backends the submit_transfer method is synchroneous.
*/
pthread_mutex_unlock(&ctx->flying_transfers_lock);
r = usbi_backend.submit_transfer(itransfer);
if (r == LIBUSB_SUCCESS) {
itransfer->state_flags |= USBI_TRANSFER_IN_FLIGHT;
/* keep a reference to this device */
libusb_ref_device(transfer->dev_handle->dev);
}
pthread_mutex_unlock(&itransfer->lock);
if (r != LIBUSB_SUCCESS)
remove_from_flying_list(itransfer);
return r;
}
int API_EXPORTED libusb_cancel_transfer(struct libusb_transfer *transfer)
{
struct usbi_transfer *itransfer =
LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
int r;
usbi_dbg("transfer %p", transfer );
pthread_mutex_lock(&itransfer->lock);
if (!(itransfer->state_flags & USBI_TRANSFER_IN_FLIGHT)
|| (itransfer->state_flags & USBI_TRANSFER_CANCELLING)) {
r = LIBUSB_ERROR_NOT_FOUND;
goto out;
}
r = usbi_backend.cancel_transfer(itransfer);
if (r < 0) {
if (r != LIBUSB_ERROR_NOT_FOUND &&
r != LIBUSB_ERROR_NO_DEVICE)
usbi_err(TRANSFER_CTX(transfer),
"cancel transfer failed error %d", r);
else
usbi_dbg("cancel transfer failed error %d", r);
if (r == LIBUSB_ERROR_NO_DEVICE)
itransfer->state_flags |= USBI_TRANSFER_DEVICE_DISAPPEARED;
}
itransfer->state_flags |= USBI_TRANSFER_CANCELLING;
out:
pthread_mutex_unlock(&itransfer->lock);
return r;
}
void API_EXPORTED libusb_transfer_set_stream_id(
struct libusb_transfer *transfer, uint32_t stream_id)
{
struct usbi_transfer *itransfer =
LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
itransfer->stream_id = stream_id;
}
uint32_t API_EXPORTED libusb_transfer_get_stream_id(
struct libusb_transfer *transfer)
{
struct usbi_transfer *itransfer =
LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
return itransfer->stream_id;
}
int usbi_handle_transfer_completion(struct usbi_transfer *itransfer,
enum libusb_transfer_status status)
{
struct libusb_transfer *transfer =
USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
struct libusb_device_handle *dev_handle = transfer->dev_handle;
uint8_t flags;
int r;
r = remove_from_flying_list(itransfer);
if (r < 0)
usbi_err(ITRANSFER_CTX(itransfer), "failed to set timer for next timeout, errno=%d", errno);
pthread_mutex_lock(&itransfer->lock);
itransfer->state_flags &= ~USBI_TRANSFER_IN_FLIGHT;
pthread_mutex_unlock(&itransfer->lock);
if (status == LIBUSB_TRANSFER_COMPLETED
&& transfer->flags & LIBUSB_TRANSFER_SHORT_NOT_OK) {
int rqlen = transfer->length;
if (transfer->type == LIBUSB_TRANSFER_TYPE_CONTROL)
rqlen -= LIBUSB_CONTROL_SETUP_SIZE;
if (rqlen != itransfer->transferred) {
usbi_dbg("interpreting short transfer as error");
status = LIBUSB_TRANSFER_ERROR;
}
}
flags = transfer->flags;
transfer->status = status;
transfer->actual_length = itransfer->transferred;
usbi_dbg("transfer %p has callback %p", transfer, transfer->callback);
if (transfer->callback)
transfer->callback(transfer);
/* transfer might have been freed by the above call, do not use from
* this point. */
if (flags & LIBUSB_TRANSFER_FREE_TRANSFER)
libusb_free_transfer(transfer);
libusb_unref_device(dev_handle->dev);
return r;
}
int usbi_handle_transfer_cancellation(struct usbi_transfer *transfer)
{
struct libusb_context *ctx = ITRANSFER_CTX(transfer);
uint8_t timed_out;
pthread_mutex_lock(&ctx->flying_transfers_lock);
timed_out = transfer->timeout_flags & USBI_TRANSFER_TIMED_OUT;
pthread_mutex_unlock(&ctx->flying_transfers_lock);
/* if the URB was cancelled due to timeout, report timeout to the user */
if (timed_out) {
usbi_dbg("detected timeout cancellation");
return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_TIMED_OUT);
}
/* otherwise its a normal async cancel */
return usbi_handle_transfer_completion(transfer, LIBUSB_TRANSFER_CANCELLED);
}
void usbi_signal_transfer_completion(struct usbi_transfer *transfer)
{
libusb_device_handle *dev_handle = USBI_TRANSFER_TO_LIBUSB_TRANSFER(transfer)->dev_handle;
if (dev_handle) {
struct libusb_context *ctx = HANDLE_CTX(dev_handle);
int pending_events;
pthread_mutex_lock(&ctx->event_data_lock);
pending_events = usbi_pending_events(ctx);
list_add_tail(&transfer->completed_list, &ctx->completed_transfers);
if (!pending_events)
usbi_signal_event(ctx);
pthread_mutex_unlock(&ctx->event_data_lock);
}
}
int API_EXPORTED libusb_try_lock_events(libusb_context *ctx)
{
int r;
unsigned int ru;
USBI_GET_CONTEXT(ctx);
/* is someone else waiting to close a device? if so, don't let this thread
* start event handling */
pthread_mutex_lock(&ctx->event_data_lock);
ru = ctx->device_close;
pthread_mutex_unlock(&ctx->event_data_lock);
if (ru) {
usbi_dbg("someone else is closing a device");
return 1;
}
r = pthread_mutex_trylock(&ctx->events_lock);
if (r)
return 1;
ctx->event_handler_active = 1;
return 0;
}
void API_EXPORTED libusb_lock_events(libusb_context *ctx)
{
USBI_GET_CONTEXT(ctx);
pthread_mutex_lock(&ctx->events_lock);
ctx->event_handler_active = 1;
}
void API_EXPORTED libusb_unlock_events(libusb_context *ctx)
{
USBI_GET_CONTEXT(ctx);
ctx->event_handler_active = 0;
pthread_mutex_unlock(&ctx->events_lock);
/* FIXME: perhaps we should be a bit more efficient by not broadcasting
* the availability of the events lock when we are modifying pollfds
* (check ctx->device_close)? */
pthread_mutex_lock(&ctx->event_waiters_lock);
pthread_cond_broadcast(&ctx->event_waiters_cond);
pthread_mutex_unlock(&ctx->event_waiters_lock);
}
int API_EXPORTED libusb_event_handling_ok(libusb_context *ctx)
{
unsigned int r;
USBI_GET_CONTEXT(ctx);
/* is someone else waiting to close a device? if so, don't let this thread
* continue event handling */
pthread_mutex_lock(&ctx->event_data_lock);
r = ctx->device_close;
pthread_mutex_unlock(&ctx->event_data_lock);
if (r) {
usbi_dbg("someone else is closing a device");
return 0;
}
return 1;
}
int API_EXPORTED libusb_event_handler_active(libusb_context *ctx)
{
unsigned int r;
USBI_GET_CONTEXT(ctx);
/* is someone else waiting to close a device? if so, don't let this thread
* start event handling -- indicate that event handling is happening */
pthread_mutex_lock(&ctx->event_data_lock);
r = ctx->device_close;
pthread_mutex_unlock(&ctx->event_data_lock);
if (r) {
usbi_dbg("someone else is closing a device");
return 1;
}
return ctx->event_handler_active;
}
void API_EXPORTED libusb_interrupt_event_handler(libusb_context *ctx)
{
int pending_events;
USBI_GET_CONTEXT(ctx);
usbi_dbg("a");
pthread_mutex_lock(&ctx->event_data_lock);
pending_events = usbi_pending_events(ctx);
ctx->event_flags |= USBI_EVENT_USER_INTERRUPT;
if (!pending_events)
usbi_signal_event(ctx);
pthread_mutex_unlock(&ctx->event_data_lock);
}
void API_EXPORTED libusb_lock_event_waiters(libusb_context *ctx)
{
USBI_GET_CONTEXT(ctx);
pthread_mutex_lock(&ctx->event_waiters_lock);
}
void API_EXPORTED libusb_unlock_event_waiters(libusb_context *ctx)
{
USBI_GET_CONTEXT(ctx);
pthread_mutex_unlock(&ctx->event_waiters_lock);
}
int API_EXPORTED libusb_wait_for_event(libusb_context *ctx, struct timeval *tv)
{
struct timespec timeout;
int r;
USBI_GET_CONTEXT(ctx);
if (tv == NULL) {
pthread_cond_wait(&ctx->event_waiters_cond, &ctx->event_waiters_lock);
return 0;
}
r = usbi_backend.clock_gettime(USBI_CLOCK_REALTIME, &timeout);
if (r < 0)
return r;
timeout.tv_sec += tv->tv_sec;
timeout.tv_nsec += tv->tv_usec * 1000;
while (timeout.tv_nsec >= 1000000000L) {
timeout.tv_nsec -= 1000000000L;
timeout.tv_sec++;
}
r = pthread_cond_timedwait(&ctx->event_waiters_cond,
&ctx->event_waiters_lock, &timeout);
if (r < 0)
return r;
else
return (r == ETIMEDOUT);
}
static void handle_timeout(struct usbi_transfer *itransfer)
{
struct libusb_transfer *transfer =
USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
int r;
itransfer->timeout_flags |= USBI_TRANSFER_TIMEOUT_HANDLED;
r = libusb_cancel_transfer(transfer);
if (r == LIBUSB_SUCCESS)
itransfer->timeout_flags |= USBI_TRANSFER_TIMED_OUT;
else
usbi_warn(TRANSFER_CTX(transfer),
"async cancel failed %d errno=%d", r, errno);
}
static int handle_timeouts_locked(struct libusb_context *ctx)
{
int r;
struct timespec systime_ts;
struct timeval systime;
struct usbi_transfer *transfer;
if (list_empty(&ctx->flying_transfers))
return 0;
/* get current time */
r = usbi_backend.clock_gettime(USBI_CLOCK_MONOTONIC, &systime_ts);
if (r < 0)
return r;
TIMESPEC_TO_TIMEVAL(&systime, &systime_ts);
/* iterate through flying transfers list, finding all transfers that
* have expired timeouts */
list_for_each_entry(transfer, &ctx->flying_transfers, list, struct usbi_transfer) {
struct timeval *cur_tv = &transfer->timeout;
/* if we've reached transfers of infinite timeout, we're all done */
if (!timerisset(cur_tv))
return 0;
/* ignore timeouts we've already handled */
if (transfer->timeout_flags & (USBI_TRANSFER_TIMEOUT_HANDLED | USBI_TRANSFER_OS_HANDLES_TIMEOUT))
continue;
/* if transfer has non-expired timeout, nothing more to do */
if ((cur_tv->tv_sec > systime.tv_sec) ||
(cur_tv->tv_sec == systime.tv_sec &&
cur_tv->tv_usec > systime.tv_usec))
return 0;
/* otherwise, we've got an expired timeout to handle */
handle_timeout(transfer);
}
return 0;
}
static int handle_timeouts(struct libusb_context *ctx)
{
int r;
USBI_GET_CONTEXT(ctx);
pthread_mutex_lock(&ctx->flying_transfers_lock);
r = handle_timeouts_locked(ctx);
pthread_mutex_unlock(&ctx->flying_transfers_lock);
return r;
}
#ifdef USBI_TIMERFD_AVAILABLE
static int handle_timerfd_trigger(struct libusb_context *ctx)
{
int r;
pthread_mutex_lock(&ctx->flying_transfers_lock);
/* process the timeout that just happened */
r = handle_timeouts_locked(ctx);
if (r < 0)
goto out;
/* arm for next timeout*/
r = arm_timerfd_for_next_timeout(ctx);
out:
pthread_mutex_unlock(&ctx->flying_transfers_lock);
return r;
}
#endif
static int handle_events(struct libusb_context *ctx, struct timeval *tv)
{
int r;
struct usbi_pollfd *ipollfd;
nfds_t nfds = 0;
nfds_t internal_nfds;
struct pollfd *fds = NULL;
int i = -1;
int timeout_ms;
/* prevent attempts to recursively handle events (e.g. calling into
* libusb_handle_events() from within a hotplug or transfer callback) */
pthread_mutex_lock(&ctx->event_data_lock);
r = 0;
if (usbi_handling_events(ctx))
r = LIBUSB_ERROR_BUSY;
else
usbi_start_event_handling(ctx);
pthread_mutex_unlock(&ctx->event_data_lock);
if (r)
return r;
/* there are certain fds that libusb uses internally, currently:
*
* 1) event pipe
* 2) timerfd
*
* the backend will never need to attempt to handle events on these fds, so
* we determine how many fds are in use internally for this context and when
* handle_events() is called in the backend, the pollfd list and count will
* be adjusted to skip over these internal fds */
if (usbi_using_timerfd(ctx))
internal_nfds = 2;
else
internal_nfds = 1;
/* only reallocate the poll fds when the list of poll fds has been modified
* since the last poll, otherwise reuse them to save the additional overhead */
pthread_mutex_lock(&ctx->event_data_lock);
/* clean up removed poll fds */
cleanup_removed_pollfds(ctx);
if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED) {
usbi_dbg("poll fds modified, reallocating");
free(ctx->pollfds);
ctx->pollfds = NULL;
/* sanity check - it is invalid for a context to have fewer than the
* required internal fds (memory corruption?) */
assert(ctx->pollfds_cnt >= internal_nfds);
ctx->pollfds = calloc(ctx->pollfds_cnt, sizeof(*ctx->pollfds));
if (!ctx->pollfds) {
pthread_mutex_unlock(&ctx->event_data_lock);
r = LIBUSB_ERROR_NO_MEM;
goto done;
}
list_for_each_entry(ipollfd, &ctx->ipollfds, list, struct usbi_pollfd) {
struct libusb_pollfd *pollfd = &ipollfd->pollfd;
i++;
ctx->pollfds[i].fd = pollfd->fd;
ctx->pollfds[i].events = pollfd->events;
}
/* reset the flag now that we have the updated list */
ctx->event_flags &= ~USBI_EVENT_POLLFDS_MODIFIED;
/* if no further pending events, clear the event pipe so that we do
* not immediately return from poll */
if (!usbi_pending_events(ctx))
usbi_clear_event(ctx);
}
fds = ctx->pollfds;
nfds = ctx->pollfds_cnt;
pthread_mutex_unlock(&ctx->event_data_lock);
timeout_ms = (int)(tv->tv_sec * 1000) + (tv->tv_usec / 1000);
/* round up to next millisecond */
if (tv->tv_usec % 1000)
timeout_ms++;
usbi_dbg("poll() %d fds with timeout in %dms", (int)nfds, timeout_ms);
r = poll(fds, nfds, timeout_ms);
usbi_dbg("poll() returned %d", r);
if (r == 0) {
r = handle_timeouts(ctx);
goto done;
} else if (r == -1 && errno == EINTR) {
r = LIBUSB_ERROR_INTERRUPTED;
goto done;
} else if (r < 0) {
usbi_err(ctx, "poll failed %d err=%d", r, errno);
r = LIBUSB_ERROR_IO;
goto done;
}
/* fds[0] is always the event pipe */
if (fds[0].revents) {
struct list_head hotplug_msgs;
struct usbi_transfer *itransfer;
int hotplug_cb_deregistered = 0;
int ret = 0;
list_init(&hotplug_msgs);
usbi_dbg("caught a fish on the event pipe");
/* take the the event data lock while processing events */
pthread_mutex_lock(&ctx->event_data_lock);
/* check if someone added a new poll fd */
if (ctx->event_flags & USBI_EVENT_POLLFDS_MODIFIED)
usbi_dbg("someone updated the poll fds");
if (ctx->event_flags & USBI_EVENT_USER_INTERRUPT) {
usbi_dbg("someone purposely interrupted");
ctx->event_flags &= ~USBI_EVENT_USER_INTERRUPT;
}
if (ctx->event_flags & USBI_EVENT_HOTPLUG_CB_DEREGISTERED) {
usbi_dbg("someone unregistered a hotplug cb");
ctx->event_flags &= ~USBI_EVENT_HOTPLUG_CB_DEREGISTERED;
hotplug_cb_deregistered = 1;
}
/* check if someone is closing a device */
if (ctx->device_close)
usbi_dbg("someone is closing a device");
/* check for any pending hotplug messages */
if (!list_empty(&ctx->hotplug_msgs)) {
usbi_dbg("hotplug message received");
list_cut(&hotplug_msgs, &ctx->hotplug_msgs);
}
/* complete any pending transfers */
while (ret == 0 && !list_empty(&ctx->completed_transfers)) {
itransfer = list_first_entry(&ctx->completed_transfers, struct usbi_transfer, completed_list);
list_del(&itransfer->completed_list);
pthread_mutex_unlock(&ctx->event_data_lock);
ret = usbi_backend.handle_transfer_completion(itransfer);
if (ret)
usbi_err(ctx, "backend handle_transfer_completion failed with error %d", ret);
pthread_mutex_lock(&ctx->event_data_lock);
}
/* if no further pending events, clear the event pipe */
if (!usbi_pending_events(ctx))
usbi_clear_event(ctx);
pthread_mutex_unlock(&ctx->event_data_lock);
if (hotplug_cb_deregistered)
usbi_hotplug_deregister(ctx, 0);
/* process the hotplug messages, if any */
while (!list_empty(&hotplug_msgs)) {
struct libusb_hotplug_message *message =
list_first_entry(&hotplug_msgs, struct libusb_hotplug_message, list);
usbi_hotplug_match(ctx, message->device, message->event);
/* the device left, dereference the device */
if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == message->event)
libusb_unref_device(message->device);
list_del(&message->list);
free(message);
}
if (ret) {
/* return error code */
r = ret;
goto done;
}
if (0 == --r)
goto done;
}
#ifdef USBI_TIMERFD_AVAILABLE
/* on timerfd configurations, fds[1] is the timerfd */
if (usbi_using_timerfd(ctx) && fds[1].revents) {
/* timerfd indicates that a timeout has expired */
int ret;
usbi_dbg("timerfd triggered");
ret = handle_timerfd_trigger(ctx);
if (ret < 0) {
/* return error code */
r = ret;
goto done;
}
if (0 == --r)
goto done;
}
#endif
list_for_each_entry(ipollfd, &ctx->removed_ipollfds, list, struct usbi_pollfd) {
for (i = internal_nfds ; i < nfds ; ++i) {
if (ipollfd->pollfd.fd == fds[i].fd) {
/* pollfd was removed between the creation of the fd
* array and here. remove any triggered revent as
* it is no longer relevant */
usbi_dbg("pollfd %d was removed. ignoring raised events",
fds[i].fd);
fds[i].revents = 0;
break;
}
}
}
r = usbi_backend.handle_events(ctx, fds + internal_nfds, nfds - internal_nfds, r);
if (r)
usbi_err(ctx, "backend handle_events failed with error %d", r);
done:
usbi_end_event_handling(ctx);
return r;
}
/* returns the smallest of:
* 1. timeout of next URB
* 2. user-supplied timeout
* returns 1 if there is an already-expired timeout, otherwise returns 0
* and populates out
*/
static int get_next_timeout(libusb_context *ctx, struct timeval *tv,
struct timeval *out)
{
struct timeval timeout;
int r = libusb_get_next_timeout(ctx, &timeout);
if (r) {
/* timeout already expired? */
if (!timerisset(&timeout))
return 1;
/* choose the smallest of next URB timeout or user specified timeout */
if (timercmp(&timeout, tv, <))
*out = timeout;
else
*out = *tv;
} else {
*out = *tv;
}
return 0;
}
int API_EXPORTED libusb_handle_events_timeout_completed(libusb_context *ctx,
struct timeval *tv, int *completed)
{
int r;
struct timeval poll_timeout;
USBI_GET_CONTEXT(ctx);
r = get_next_timeout(ctx, tv, &poll_timeout);
if (r) {
/* timeout already expired */
return handle_timeouts(ctx);
}
retry:
if (libusb_try_lock_events(ctx) == 0) {
if (completed == NULL || !*completed) {
/* we obtained the event lock: do our own event handling */
usbi_dbg("doing our own event handling");
r = handle_events(ctx, &poll_timeout);
}
libusb_unlock_events(ctx);
return r;
}
/* another thread is doing event handling. wait for thread events that
* notify event completion. */
libusb_lock_event_waiters(ctx);
if (completed && *completed)
goto already_done;
if (!libusb_event_handler_active(ctx)) {
/* we hit a race: whoever was event handling earlier finished in the