-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusb-mce.cpp
1846 lines (1599 loc) · 51 KB
/
usb-mce.cpp
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
/******************************************************************************
* usb-mce.cpp
*****************************************************************************/
/******************************************************************************
* Includes
*****************************************************************************/
#include "stdafx.h"
#include "usb.h"
#include "device.h"
#include "client.h"
#include "utils.h"
#include "usbmuxd.h"
#include "usb-mce_internal.h"
#include "WindowsUtil.h"
/* MCE Includes */
#include "usbmuxd_com_plugin_client.h"
#include "SocketUtil.h"
#include <Dbt.h>
#include "usb100.h"
/******************************************************************************
* usb_init Function
*****************************************************************************/
int usb_init(uint32_t hub_address, LPCWSTR pLuginPath)
{
/* Load the the port driver */
if (com_plugin_client_init(pLuginPath) != COM_OK || com_plugin_init(hub_address) != COM_OK)
{
return -1;
}
g_port_notification_callback_cookie = NULL;
g_next_usb_device_id = 1;
collection_init(&g_device_list);
InitializeCriticalSection(&g_pending_devices_lock);
return 0;
}
/******************************************************************************
* usb_shutdown Function
*****************************************************************************/
void usb_shutdown(void)
{
/* Remove each connected device */
FOREACH(struct usb_device *usbdev, &g_device_list, struct usb_device *)
{
device_remove(usbdev);
usb_disconnect(usbdev, true);
} ENDFOREACH
/* Release any pending device commands */
LOCK_PENDING_DEVICES();
if (false == g_pending_devices.IsEmpty())
{
size_t pending_commands_count = g_pending_devices.GetCount();
for (size_t i = 0; i < pending_commands_count; i++)
{
HEAP_FREE(g_pending_devices.RemoveHead());
}
}
UNLOCK_PENDING_DEVICES();
/* Unregister the port change notification */
if (g_port_notification_callback_cookie)
{
if (COM_OK != com_plugin_unregister_com_notification(g_port_notification_callback_cookie))
{
DEBUG_PRINT_WIN32_ERROR("PortUnRegisterPortNotification");
}
g_port_notification_callback_cookie = NULL;
}
DeleteCriticalSection(&g_pending_devices_lock);
collection_free(&g_device_list);
com_plugin_deinit();
}
/******************************************************************************
* usb_get_device_by_id Function
*****************************************************************************/
usb_device * usb_get_device_by_id(int id)
{
FOREACH(struct usb_device * dev, &g_device_list, struct usb_device *)
{
if (IS_VALID_DEVICE(dev) && (dev->id == id))
{
return dev;
}
} ENDFOREACH
return NULL;
}
/******************************************************************************
* usb_add_device Function
*****************************************************************************/
int usb_add_device(uint32_t device_location, void * completion_event)
{
usb_append_device_command(PENDING_DEVICE_COMMAND_ADD,
PENDING_DEVICE_COMMAND_SOURCE_MANUAL,
device_location,
completion_event,
DEVICE_MONITOR_DISABLE);
return 0;
}
/******************************************************************************
* usb_remove_device Function
*****************************************************************************/
int usb_remove_device(uint32_t device_location, void * completion_event)
{
usb_append_device_command(PENDING_DEVICE_COMMAND_REMOVE,
PENDING_DEVICE_COMMAND_SOURCE_MANUAL,
device_location,
completion_event,
DEVICE_MONITOR_DISABLE);
return 0;
}
/******************************************************************************
* usb_set_device_monitoring Function
*****************************************************************************/
int usb_set_device_monitoring(uint32_t device_location, enum device_monitor_state monitor_device, uint32_t timeout)
{
int ret = -1;
/* Create a completion event */
HANDLE completion_event = CreateEvent(NULL, FALSE, FALSE, NULL);
if (FALSE == IS_VALID_HANDLE(completion_event))
{
DEBUG_PRINT_WIN32_ERROR("CreateEvent");
return -1;
}
usb_append_device_command(PENDING_DEVICE_COMMAND_SET_MONITOR,
PENDING_DEVICE_COMMAND_SOURCE_MANUAL,
device_location,
completion_event,
monitor_device);
/* Wait for the new setting to take effect */
DWORD wait_result = WaitForSingleObject(completion_event, timeout);
if (WAIT_OBJECT_0 == wait_result)
{
ret = 0;
}
else
{
if (WAIT_TIMEOUT == wait_result)
{
DEBUG_PRINT_ERROR("Timeout while waiting for device %d monitoring change", device_location);
}
else
{
DEBUG_PRINT_WIN32_ERROR("WaitForSingleObject");
}
}
SAFE_CLOSE_HANDLE(completion_event);
return ret;
}
/******************************************************************************
* usb_set_device_monitoring_immediately Function
*****************************************************************************/
int usb_set_device_monitoring_immediately(uint32_t device_location, enum device_monitor_state monitor_device)
{
usb_append_device_command(PENDING_DEVICE_COMMAND_SET_MONITOR,
PENDING_DEVICE_COMMAND_SOURCE_MANUAL,
device_location,
NULL,
monitor_device);
/* Force the change to take effect immediately */
return usb_process(NULL);
}
#ifdef USE_PORTDRIVER_SOCKETS
/******************************************************************************
* usb_process Function
*****************************************************************************/
int usb_process(fd_set * read_fds)
{
FOREACH(struct usb_device *usb_dev, &g_device_list, struct usb_device *)
{
/* Handle pending transfers */
if (USB_DEVICE_STATE_ALIVE == usb_dev->state)
{
if (read_fds)
{
SOCKET endpoint_socket = INVALID_SOCKET;
PortGetCompletionSocketForEndpoint(&(usb_dev->port), usb_dev->info.ep_in, &endpoint_socket);
if (PORTOK != PortProcessPendingTransfers(&(usb_dev->port)))
{
LOG_WIN32_ERROR("PortProcessPendingTransfers");
}
}
}
/* If the device was marked as dead - remove it */
else if (USB_DEVICE_STATE_DEAD == usb_dev->state)
{
LOG_TRACE("Removing a dead device");
device_remove(usb_dev);
usb_disconnect(usb_dev, PENDING_DEVICE_COMMAND_SOURCE_MONITOR);
}
} ENDFOREACH
/* Handle pending devices */
LOCK_PENDING_DEVICES();
if (false == g_pending_devices.IsEmpty())
{
size_t pending_commands_count = g_pending_devices.GetCount();
for (size_t i = 0; i < pending_commands_count; i++)
{
PENDING_DEVICE_COMMAND * pending_command = g_pending_devices.RemoveHead();
switch (pending_command->type)
{
/* Add */
case PENDING_DEVICE_COMMAND_ADD:
usb_add_pending_device(pending_command->source,
pending_command->device_location,
pending_command->monitor,
pending_command->completion_event);
break;
/* Remove */
case PENDING_DEVICE_COMMAND_REMOVE:
usb_remove_pending_device(pending_command->source,
pending_command->device_location,
pending_command->completion_event);
break;
/* Monitor */
case PENDING_DEVICE_COMMAND_SET_MONITOR:
usb_handle_device_monitor_command(pending_command->device_location,
pending_command->monitor,
pending_command->completion_event);
break;
/* Invalid commnad */
default:
LOG_ERROR("Invalid pending device command type: %d", pending_command->type);
break;
}
/* Refresh the monitored ports state */
usb_update_monitored_devices();
HEAP_FREE(pending_command);
}
}
UNLOCK_PENDING_DEVICES();
return 0;
}
/******************************************************************************
* usb_add_fds Function
*****************************************************************************/
int usb_add_fds(fd_set * read_fds, fd_set * write_fds)
{
UNREFERENCED_PARAMETER(write_fds);
int fd_count = 0;
SOCKET endpoint_socket = INVALID_SOCKET;
FOREACH(struct usb_device * dev, &g_device_list, struct usb_device *)
{
if (USB_DEVICE_STATE_ALIVE == dev->state)
{
if (PORTOK == PortGetCompletionSocketForEndpoint(&(dev->port), dev->info.ep_in, &endpoint_socket))
{
FD_SET(endpoint_socket, read_fds);
fd_count++;
}
else
{
LOG_WIN32_ERROR("PortGetCompletionSocketForEndpoint");
}
}
} ENDFOREACH
return fd_count;
}
#else
/******************************************************************************
* usb_process Function
*****************************************************************************/
int usb_process(void * unused)
{
/* Handle pending devices */
LOCK_PENDING_DEVICES();
if (false == g_pending_devices.IsEmpty())
{
size_t pending_commands_count = g_pending_devices.GetCount();
for (size_t i = 0; i < pending_commands_count; i++)
{
PENDING_DEVICE_COMMAND * pending_command = g_pending_devices.RemoveHead();
switch (pending_command->type)
{
/* Add */
case PENDING_DEVICE_COMMAND_ADD:
usb_add_pending_device(pending_command->source,
pending_command->device_location,
pending_command->monitor,
pending_command->completion_event);
break;
/* Remove */
case PENDING_DEVICE_COMMAND_REMOVE:
usb_remove_pending_device(pending_command->source,
pending_command->device_location,
pending_command->completion_event);
break;
/* Monitor */
case PENDING_DEVICE_COMMAND_SET_MONITOR:
usb_handle_device_monitor_command(pending_command->device_location,
pending_command->monitor,
pending_command->completion_event);
break;
/* Invalid commnad */
default:
DEBUG_PRINT_ERROR("Invalid pending device command type: %d", pending_command->type);
break;
}
/* Refresh the monitored ports state */
usb_update_monitored_devices();
HEAP_FREE(pending_command);
}
}
UNLOCK_PENDING_DEVICES();
return 0;
}
/******************************************************************************
* usb_start_read Function
*****************************************************************************/
int usb_start_read(struct usb_device * dev)
{
/* Make sure the read event isn't signaled */
ResetEvent((dev->rx.overlapped).hEvent);
/* Try to perform a read transfer */
dev->rx.data_size = 0;
if (COM_OK == com_plugin_transfer(&(dev->port),
TRUE,
dev->info.ep_in,
dev->rx.buffer,
DEVICE_RX_BUFFER_SIZE,//USB_MRU,
(LPDWORD)(&(dev->rx.data_size)),
NULL,
0,
&(dev->rx.overlapped)))
{
/* The caller will always wait on the returned handle and call usb_get_read_result,
* without caring if the transfer was completed synchronously or not,
* so we'll signal the event manually */
SetEvent((dev->rx.overlapped).hEvent);
}
else
{
DWORD le = GetLastError();
if (ERROR_IO_PENDING != le)
{
usb_handle_port_failure(dev);
DEBUG_PRINT_WIN32_ERROR("PortPortTransfer");
return -1;
}
}
return (int)((dev->rx.overlapped).hEvent);
}
/******************************************************************************
* usb_get_read_result Function
*****************************************************************************/
int usb_get_read_result(struct usb_device * dev, void ** buf, uint32_t * buf_data_size)
{
/* Check if the transfer didn't complete */
if (0 == dev->rx.data_size)
{
if (COM_OK != com_plugin_get_transfer_result(&(dev->port),
&(dev->rx.overlapped),
(LPDWORD)(&(dev->rx.data_size)),
FALSE))
{
usb_handle_port_failure(dev);
DEBUG_PRINT_WIN32_ERROR("PortPortGetTransferResult");
return -1;
}
}
*buf = dev->rx.buffer;
*buf_data_size = dev->rx.data_size;
return 0;
}
#endif /* USE_PORTDRIVER_SOCKETS */
/******************************************************************************
* usb_send Function
*****************************************************************************/
void GetTXQElement(struct usb_device * dev, usb_device_tx_q_element& e, const unsigned char* buff)
{
if (!dev->tx.pool.try_dequeue(e))
{
e.theOverLapped = new OVERLAPPED;
memset(e.theOverLapped, 0, sizeof(OVERLAPPED));
e.theOverLapped->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
}
e.buffer = (void*)buff;
}
void ReUseTXQElement(struct usb_device * dev, usb_device_tx_q_element& e){
if (e.buffer)
free(e.buffer);
e.buffer = NULL;
dev->tx.pool.enqueue(e);
}
int usb_send(struct usb_device * dev, const unsigned char * buf, int length)
{
int iRet = -1;
usb_device_tx_q_element e;
GetTXQElement(dev, e, buf);
/* Try to perform */
DWORD dwBytesTransferred = 0;
if (COM_OK == com_plugin_transfer(&(dev->port),
FALSE,
dev->info.ep_out,
(void *)buf,
length,
&dwBytesTransferred,
NULL,
0,
e.theOverLapped))
{
iRet = 0;
ReUseTXQElement(dev, e);
}
else
{
/* Check if the transfer is pending */
if (ERROR_IO_PENDING == GetLastError())
{
if (dev->tx.thread)
{
iRet = 0;
dev->tx.q.enqueue(e);
}
else //write thread not started will do transfer result here
{
if (COM_OK == com_plugin_get_transfer_result(&(dev->port), e.theOverLapped, &dwBytesTransferred, TRUE))
{
iRet = 0;
}
else
{
DEBUG_PRINT_WIN32_ERROR("PortPortGetTransferResult");
iRet = -1;
}
ReUseTXQElement(dev,e);
}
}
else
{
DEBUG_PRINT_WIN32_ERROR("PortPortTransfer");
}
}
/* TMP Patch:
* When disconneting a device, we count on the "read" transfer (done by the reading thread) to fail.
* For some reason, we've encountered situations where the above transfer fails, but the
* "read" transfer doesn't (the PortPortTransfer just doesn't return).
* For now, until we understand this issue, it's better to crash than to deal with the "stuck" overlapped
* transfer. */
if (0 != iRet)
{
ExitProcess(1);
}
/* If needed - send a zero length packet */
if ((0 == iRet) && (0 == (length % dev->info.tx_max_packet_size)))
{
DWORD dwEmptyBulk = 0;
usb_device_tx_q_element ze;
GetTXQElement(dev, ze,NULL);
if (COM_OK == com_plugin_transfer(&(dev->port), FALSE, dev->info.ep_out, ze.buffer, 0, &dwEmptyBulk, NULL, 0, ze.theOverLapped))
{
iRet = 0;
ReUseTXQElement(dev, ze);
}
else
{
if ( dev->tx.thread)
{
iRet = 0;
dev->tx.q.enqueue(ze);
}
else //write thread not started will do transfer result here
{
if (COM_OK == com_plugin_get_transfer_result(&(dev->port), ze.theOverLapped, &dwEmptyBulk, TRUE))
{
iRet = 0;
}
else
{
DEBUG_PRINT_WIN32_ERROR("PortPortGetTransferResult Zero");
iRet = -1;
}
ReUseTXQElement(dev,ze);
}
}
}
return iRet;
}
/******************************************************************************
* usb_get_serial Function
*****************************************************************************/
const char *usb_get_serial(struct usb_device *dev)
{
if (NULL == dev)
{
return NULL;
}
return dev->info.serial;
}
/******************************************************************************
* usb_get_location Function
*****************************************************************************/
uint32_t usb_get_location(struct usb_device *dev)
{
if (NULL == dev)
{
return 0;
}
return dev->location;
}
/******************************************************************************
* usb_get_pid Function
*****************************************************************************/
uint16_t usb_get_pid(struct usb_device *dev)
{
if (NULL == dev)
{
return 0;
}
return dev->port.wPID;
}
/******************************************************************************
* usb_is_device_monitored Function
*****************************************************************************/
int usb_is_device_monitored(struct usb_device *dev)
{
if (FALSE == IS_VALID_DEVICE(dev))
{
return 0;
}
return (DEVICE_MONITOR_DISABLE != dev->monitor);
}
/******************************************************************************
* usb_has_devices Function
*****************************************************************************/
uint8_t usb_has_devices()
{
/* We might get called from a thread other than the main thread, so we need
* to make sure there won't be any device changes while we check */
LOCK_PENDING_DEVICES();
/* We simply check if we have devices in our list, either present or monitored */
uint8_t ret = collection_count(&g_device_list) > 0;
UNLOCK_PENDING_DEVICES();
return ret;
}
/******************************************************************************
* usb_set_device_ready Function
*****************************************************************************/
void usb_set_device_ready(struct usb_device *dev)
{
if (IS_VALID_DEVICE(dev))
{
if (IS_VALID_HANDLE(dev->device_ready_event))
{
if (FALSE == SetEvent(dev->device_ready_event))
{
DEBUG_PRINT_WIN32_ERROR("SetEvent");
}
}
}
}
/******************************************************************************
* Internal Functions
*****************************************************************************/
#ifdef USE_PORTDRIVER_SOCKETS
/******************************************************************************
* rx_callback Function
*****************************************************************************/
static void rx_callback(PORT_TRANSFER * ptTransfer)
{
struct usb_device * dev = (usb_device *)ptTransfer->pvCallbackContext;
if (PORT_TRANSFER_STATUS_COMPLETED == ptTransfer->eStatus)
{
/* Push the new data up to the protocol (device) layer */
uint32_t data_processed = 0;
while (data_processed < ptTransfer->dwBytesTransferred)
{
data_processed += device_data_input(dev,
(unsigned char *)(ptTransfer->pvBuffer) + data_processed,
ptTransfer->dwBytesTransferred - data_processed);
}
/* Resubmit the transfer */
if (PORTOK != PortSubmitTransfer(ptTransfer))
{
LOG_WIN32_ERROR("PortSubmitTransfer");
}
}
else
{
switch (ptTransfer->eStatus)
{
/* Note: When the device is remove, we'll get an PORT_TRANSFER_STATUS_DEVICE_REMOVED
* error. On MCE port reset - we'll get PORT_TRANSFER_STATUS_CANCELLED */
case PORT_TRANSFER_STATUS_CANCELLED:
case PORT_TRANSFER_STATUS_DEVICE_REMOVED:
LOG_ERROR("The device %d was removed unexpectedly", dev->location);
dev->state = USB_DEVICE_STATE_DEAD;
break;
/* Unknown error */
case PORT_TRANSFER_STATUS_FAILED:
LOG_ERROR("The transfer on device %d has failed", dev->location);
break;
default:
LOG_ERROR("Uknown transfer status: %d", ptTransfer->eStatus);
break;
}
}
}
/******************************************************************************
* start_rx_loop Function
*****************************************************************************/
static int start_rx_loop(struct usb_device *dev)
{
void * buffer = NULL;
PORT_TRANSFER * transfer = NULL;
/* Allocate a buffer for the transfer */
buffer = HEAP_ALLOC(void, DEVICE_RX_BUFFER_SIZE);
if (NULL == buffer)
{
return -1;
}
/* Allocate a new transfer */
if (PORTOK != PortAllocateTransfer(&(dev->port), rx_callback, dev, &transfer))
{
LOG_WIN32_ERROR("PortAllocateTransfer");
goto lblCleanup;
}
if (PORTOK != PortFillBulkOrInterruptTransfer(transfer, dev->info.ep_in, buffer, DEVICE_RX_BUFFER_SIZE))
{
LOG_WIN32_ERROR("PortFillBulkOrInterruptTransfer");
goto lblCleanup;
}
/* Submit the transfer */
if (PORTOK != PortSubmitTransfer(transfer))
{
LOG_WIN32_ERROR("PortSubmitTransfer");
goto lblCleanup;
}
collection_add(&(dev->rx_transfers), transfer);
return 0;
lblCleanup:
if (transfer)
{
if (PORTOK == PortFreeTransfer(transfer, FALSE))
{
transfer = NULL;
}
}
if (buffer && (NULL == transfer))
{
HEAP_FREE(buffer);
}
return -1;
}
/******************************************************************************
* start_reading_from_device Function
*****************************************************************************/
static int start_reading_from_device(struct usb_device * dev)
{
int rx_loops = NUM_RX_LOOPS;
/* Start reading from the device, using parallel read loops */
collection_init(&(dev)->rx_transfers);
for (rx_loops = NUM_RX_LOOPS; rx_loops > 0; rx_loops--)
{
if (start_rx_loop(dev) < 0)
{
LOG_ERROR("Failed to start RX loop number %d", NUM_RX_LOOPS - rx_loops);
}
}
/* Ensure we have at least 1 RX loop going */
if (NUM_RX_LOOPS == rx_loops)
{
LOG_ERROR("Failed to start any RX loop for device %d", dev->location);
return -1;
}
else if (rx_loops > 0)
{
LOG_ERROR("Failed to start all %d RX loops. Going on with %d loops. "
"This may have negative impact on device read speed.",
NUM_RX_LOOPS, NUM_RX_LOOPS - rx_loops);
}
else
{
LOG_TRACE("All %d RX loops started successfully", NUM_RX_LOOPS);
}
return 0;
}
/******************************************************************************
* usb_disconnect Function
*****************************************************************************/
static void usb_disconnect(struct usb_device * dev, bool manual_remove)
{
/* Close the device's port.
* Note: This must be done before freeing the rx transfers, to make sure
* there are no pending overlapped operations. */
bool port_was_closed = false;
if (PORTOK == PortClosePort(&(dev->port)))
{
port_was_closed = true;
}
else
{
LOG_WIN32_ERROR("PortClosePort");
}
/* Free the rx transfers */
if (IS_VALID_COLLECTION(&(dev->rx_transfers)))
{
if (port_was_closed)
{
FOREACH(PORT_TRANSFER * transfer, &(dev->rx_transfers), PORT_TRANSFER *)
{
void * transfer_buffer = transfer->pvBuffer;
if (PORTOK == PortFreeTransfer(transfer, FALSE))
{
HEAP_FREE(transfer_buffer);
}
} ENDFOREACH
}
collection_free(&(dev->rx_transfers));
}
/* If wer're really removing the device, we'll cleanup
* everything. But, if this was a removal of a monitored device,
* we'll just reset it's state */
if (manual_remove || (DEVICE_MONITOR_DISABLE == dev->monitor))
{
collection_remove(&g_device_list, dev);
HEAP_FREE(dev);
}
else
{
/* Reset the device's state */
SecureZeroMemory(&(dev->port), sizeof(dev->port));
SecureZeroMemory(&(dev->info), sizeof(dev->info));
dev->state = USB_DEVICE_STATE_WAITING_FOR_DEVICE;
}
}
#else
/******************************************************************************
* usb_disconnect Function
*****************************************************************************/
static void usb_disconnect(struct usb_device * dev, bool manual_remove)
{
/* Signal the read thread to stop event */
if (IS_VALID_HANDLE(dev->rx.thread))
{
DEBUG_PRINT("Terminating read thread for device %d", dev->id);
if (FALSE == SetEvent(dev->rx.thread_stop_event))
{
DEBUG_PRINT_WIN32_ERROR("SetEvent");
}
/* Wait for the read thread to finish */
DWORD dwWaitResult = WaitForSingleObject(dev->rx.thread, READ_THREAD_SHUTDOWN_TIMEOUT);
switch (dwWaitResult)
{
/* The thread has been terminated */
case WAIT_OBJECT_0:
DEBUG_PRINT("The read thread was terminated");
break;
/* Timeout */
case WAIT_TIMEOUT:
DEBUG_PRINT("Timeout while waiting for the read thread to terminate, killing the thread...");
if (FALSE == TerminateThread(dev->rx.thread, 0))
{
DEBUG_PRINT_WIN32_ERROR("TerminateThread");
return;
}
break;
/* Error */
default:
DEBUG_PRINT_WIN32_ERROR("WaitForSingleObject");
return;
}
}
if (dev->tx.writeThreadStop)
{
SetEvent(dev->tx.writeThreadStop);
usb_device_tx_q_element stop = { 0 };
dev->tx.q.enqueue(stop);//
if(WaitForSingleObject(dev->tx.thread,5000)!=WAIT_OBJECT_0)
{
DEBUG_PRINT_ERROR("waiting for write thread to stop failed");
}
else
{
DEBUG_PRINT_ERROR("waiting for write thread to stop success");
usb_device_tx_q_element freePoll;
while (dev->tx.pool.try_dequeue(freePoll))
{
if (freePoll.theOverLapped)
{
if (freePoll.theOverLapped->hEvent)
{
CloseHandle(freePoll.theOverLapped->hEvent);
}
delete (freePoll.theOverLapped);
}
}
DEBUG_PRINT_ERROR("deliting pool finished");
}
}
/* Cleanup this device's instance related resources */
if (COM_OK != com_plugin_close(&(dev->port)))
{
DEBUG_PRINT_WIN32_ERROR("PortClosePort");
}
SAFE_CLOSE_SOCKET(dev->rx.data_events_socket);
SAFE_CLOSE_HANDLE(dev->rx.thread);
/* If wer're really removing the device, we'll cleanup
* everything. But, if this was a removal of a monitored device,
* we'll just reset it's state */
if (manual_remove || (DEVICE_MONITOR_DISABLE == dev->monitor))
{
usb_free_device(dev);
}
else
{
/* Reset the device's state */
SecureZeroMemory(&(dev->port), sizeof(dev->port));
SecureZeroMemory(&(dev->info), sizeof(dev->info));
dev->state = USB_DEVICE_STATE_WAITING_FOR_DEVICE;
}
}
/******************************************************************************
* usb_read_thread_proc Function
*****************************************************************************/
static DWORD WINAPI usb_read_thread_proc(void * context)
{
CHAR cFlag = 1;
usb_device * dev = (usb_device *)context;
HANDLE ahEvents[2];
ahEvents[READ_WAIT_EVENTS_ARR_STOP_EVENT] = dev->rx.thread_stop_event;
ahEvents[READ_WAIT_EVENTS_ARR_DEVICE_EVENT] = (HANDLE)usb_start_read(dev);
if (FALSE == IS_VALID_HANDLE(ahEvents[READ_WAIT_EVENTS_ARR_DEVICE_EVENT]))
{
DEBUG_PRINT_ERROR("usb_start_read has failed");
return 0;
}
bool should_stop = false;
DWORD wait_result = WAIT_FAILED;
int socket_result = 0;
while (false == should_stop)
{
wait_result = WaitForMultipleObjects(STATIC_ARRAY_SIZE(ahEvents), ahEvents, FALSE, READ_WAIT_TIMEOUT);
switch (wait_result)
{
/* Stop Event */
case WAIT_OBJECT_0 + READ_WAIT_EVENTS_ARR_STOP_EVENT:
DEBUG_PRINT("Stop event was signaled");
should_stop = true;
break;
/* Device data */
case WAIT_OBJECT_0 + READ_WAIT_EVENTS_ARR_DEVICE_EVENT:
/* Notify the main thread we have new data and wait for it to process it.
* Note: It doesn't matter what we send and receive, but it should be one
* byte. */
socket_result = send(dev->rx.data_events_socket, &cFlag, sizeof(cFlag), 0);
if (sizeof(cFlag) == socket_result)
{
socket_result = recv(dev->rx.data_events_socket, &cFlag, sizeof(cFlag), 0);
if (sizeof(cFlag) == socket_result)
{
/* Start another read */
ahEvents[READ_WAIT_EVENTS_ARR_DEVICE_EVENT] = (HANDLE)usb_start_read(dev);
if (FALSE == IS_VALID_HANDLE(ahEvents[READ_WAIT_EVENTS_ARR_DEVICE_EVENT]))
{
DEBUG_PRINT_ERROR("usb_start_read has failed socket_result:%d", socket_result);
should_stop = true;
}
}
else
{
if (0 == socket_result)
{
DEBUG_PRINT("The device socket was closed");
}
else
{
DEBUG_PRINT_WSA_ERROR("recv");
}
should_stop = true;
}
}
else
{
if (0 == socket_result)
{