Debian Codegraph @

spectro/usbio_dk.c

raw symbols SCIP
1
2 /* General USB I/O support for MSWin using the UsbDk system driver. */
3 /* This file is conditionaly #included into usbio.c */
4 /* Based on usbio_w0.c */
5
6 # pragma message("######### !!!!! usbio_usbdk.c compiled !!!!! ########")
7
8 /*
9 * Argyll Color Management System
10 *
11 * Author: Graeme W. Gill
12 * Date: 2023/9/25
13 *
14 * Copyright 2006 - 2023 Graeme W. Gill
15 * All rights reserved.
16 *
17 * This material is licenced under the GNU GENERAL PUBLIC LICENSE Version 2 or later :-
18 * see the License2.txt file for licencing details.
19 */
20
21 #include <stdlib.h>
22 #include <string.h>
23 #include <stdio.h>
24 #include <errno.h>
25 #include <ctype.h>
26 #include <windows.h>
27 #include <winioctl.h>
28 #include <setupapi.h>
29
30 #include "conv.h"
31
32 #pragma message("!!!!!!!!!!!!!!!!!!!! usbio_dk defined !!!!!!!!!!!!!!!!!!!!!!!!!!!!")
33
34 #undef DEBUG /* Turn on debug messages */
35
36 // See example d:/src/libusb/libusb_1026/libusb/os/windows_usbdk.c
37
38 /* --------------------------------------------------- */
39 /* UsbDk functions */
40
41 static UsbDk_inited = 0;
42
43 static UsbDk_InstallDriver_t UsbDk_InstallDriver = NULL;
44 static UsbDk_UninstallDriver_t UsbDk_UninstallDriver = NULL;
45 static UsbDk_GetDevicesList_t UsbDk_GetDevicesList = NULL;
46 static UsbDk_ReleaseDevicesList_t UsbDk_ReleaseDevicesList = NULL;
47 static UsbDk_GetConfigurationDescriptor_t UsbDk_GetConfigurationDescriptor = NULL;
48 static UsbDk_ReleaseConfigurationDescriptor_t UsbDk_ReleaseConfigurationDescriptor = NULL;
49 static UsbDk_StartRedirect_t UsbDk_StartRedirect = NULL;
50 static UsbDk_StopRedirect_t UsbDk_StopRedirect = NULL;
51 static UsbDk_WritePipe_t UsbDk_WritePipe = NULL;
52 static UsbDk_ReadPipe_t UsbDk_ReadPipe = NULL;
53 static UsbDk_AbortPipe_t UsbDk_AbortPipe = NULL;
54 static UsbDk_ResetPipe_t UsbDk_ResetPipe = NULL;
55 static UsbDk_SetAltsetting_t UsbDk_SetAltsetting = NULL;
56 static UsbDk_ResetDevice_t UsbDk_ResetDevice = NULL;
57 static UsbDk_GetRedirectorSystemHandle_t UsbDk_GetRedirectorSystemHandle = NULL;
58
59 /* Make sure UsbDk is installed, and get the function pointers. */
60 /* Return nz on failure */
61 static int init_UsbDk(icompaths *p) {
62 char *pf = NULL;
63 char path[1024];
64 HMODULE lib;
65
66 if (UsbDk_inited)
67 return 0;
68
69 a1logd(p->log, 6, "init_UsbDk called:\n");
70
71 // ~8 ???
72 // Should check registry for a UsbDk install, and check the version.
73 // If it is not a version with bug fixes, uninstall it
74 // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\UsbDk
75 // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\UsbDk\Parameters\Wdf
76
77 /* Look for the UsbDk .dll */
78 if ((pf = getenv("PROGRAMFILES")) == NULL)
79 pf = "C:\\Program Files";
80
81 strcpy(path, pf);
82 strcat(path, "/UsbDk Runtime Library/UsbDkHelper.dll");
83
84 if ((lib = LoadLibrary(path)) == NULL) {
85 // ~8 Should try and install ../usb/UsbDk_1.0.22_x64.msi or ../usb/UsbDk_1.0.22_x86.msi
86 // try and install it without the drivers running
87 a1logd(p->log, 1, "init_UsbDk didn't find library '%s'\n",path);
88 return 1;
89 }
90
91 a1logd(p->log, 7, "init_UsbDk found library\n");
92
93 UsbDk_InstallDriver = (UsbDk_InstallDriver_t)GetProcAddress(lib, "UsbDk_InstallDriver");
94 UsbDk_UninstallDriver = (UsbDk_UninstallDriver_t)GetProcAddress(lib, "UsbDk_UninstallDriver");
95 UsbDk_GetDevicesList = (UsbDk_GetDevicesList_t)GetProcAddress(lib, "UsbDk_GetDevicesList");
96 UsbDk_ReleaseDevicesList = (UsbDk_ReleaseDevicesList_t)
97 GetProcAddress(lib, "UsbDk_ReleaseDevicesList");
98 UsbDk_GetConfigurationDescriptor = (UsbDk_GetConfigurationDescriptor_t)
99 GetProcAddress(lib, "UsbDk_GetConfigurationDescriptor");
100 UsbDk_ReleaseConfigurationDescriptor = (UsbDk_ReleaseConfigurationDescriptor_t)
101 GetProcAddress(lib, "UsbDk_ReleaseConfigurationDescriptor");
102 UsbDk_StartRedirect = (UsbDk_StartRedirect_t)GetProcAddress(lib, "UsbDk_StartRedirect");
103 UsbDk_StopRedirect = (UsbDk_StopRedirect_t)GetProcAddress(lib, "UsbDk_StopRedirect");
104 UsbDk_WritePipe = (UsbDk_WritePipe_t)GetProcAddress(lib, "UsbDk_WritePipe");
105 UsbDk_ReadPipe = (UsbDk_ReadPipe_t)GetProcAddress(lib, "UsbDk_ReadPipe");
106 UsbDk_AbortPipe = (UsbDk_AbortPipe_t)GetProcAddress(lib, "UsbDk_AbortPipe");
107 UsbDk_ResetPipe = (UsbDk_ResetPipe_t)GetProcAddress(lib, "UsbDk_ResetPipe");
108 UsbDk_SetAltsetting = (UsbDk_SetAltsetting_t)GetProcAddress(lib, "UsbDk_SetAltsetting");
109 UsbDk_ResetDevice = (UsbDk_ResetDevice_t)GetProcAddress(lib, "UsbDk_ResetDevice");
110 UsbDk_GetRedirectorSystemHandle = (UsbDk_GetRedirectorSystemHandle_t)
111 GetProcAddress(lib, "UsbDk_GetRedirectorSystemHandle");
112
113 /* Did all that work ? */
114 if (UsbDk_InstallDriver == NULL
115 || UsbDk_UninstallDriver == NULL
116 || UsbDk_GetDevicesList == NULL
117 || UsbDk_ReleaseDevicesList == NULL
118 || UsbDk_GetConfigurationDescriptor == NULL
119 || UsbDk_ReleaseConfigurationDescriptor == NULL
120 || UsbDk_StartRedirect == NULL
121 || UsbDk_StopRedirect == NULL
122 || UsbDk_WritePipe == NULL
123 || UsbDk_ReadPipe == NULL
124 || UsbDk_AbortPipe == NULL
125 || UsbDk_ResetPipe == NULL
126 || UsbDk_SetAltsetting == NULL
127 || UsbDk_ResetDevice == NULL
128 || UsbDk_GetRedirectorSystemHandle == NULL) {
129 a1logd(p->log, 1, "init_UsbDk failed to find all function\n");
130 return 1;
131 }
132
133 // ~8 should check if the system driver is running ???
134 // Can do this by checking service manager ?
135 // offer to start drivers. If no, fail init
136 // Start drivers using UsbDk_InstallDriver() ?
137 // Ask for confirm, if no confirm in 10 seconds, uninstall driver and fail init
138
139 a1logd(p->log, 6, "init_UsbDk done\n");
140
141 return 0;
142 }
143
144 /* Return a diagnostic string from the ID */
145 /* The returned buffer is static. */
146 static char *ID2str(USB_DK_DEVICE_ID *ID) {
147 static char buf[200];
148
149 if ((icmUTF16toUTF8(NULL, NULL, ID->DeviceID)
150 + icmUTF16toUTF8(NULL, NULL, ID->InstanceID)
151 + 1) > 200) {
152 sprintf(buf, "USBDK_ID too long for buffer!");
153 return buf;
154 }
155
156 icmUTF16toUTF8(NULL, buf, ID->DeviceID);
157 strcat(buf, "-");
158 icmUTF16toUTF8(NULL, buf + strlen(buf), ID->InstanceID);
159
160 return buf;
161 }
162
163 /* Add an OVERLAP cleanup record */
164 static add_olr(icoms *p, struct usbdk_olr *olr) {
165
166 EnterCriticalSection(&p->usbd->lock);
167 olr->next = p->usbd->olr;
168 if (p->usbd->olr != NULL)
169 p->usbd->olr->last = &olr->next;
170 p->usbd->olr = olr;
171 olr->last = &p->usbd->olr;
172 LeaveCriticalSection(&p->usbd->lock);
173 }
174
175 /* Remove an OVERLAP cleanup record */
176 static rem_olr(icoms *p, struct usbdk_olr *olr) {
177
178 EnterCriticalSection(&p->usbd->lock);
179 *olr->last = olr->next;
180 if (olr->next != NULL)
181 olr->next->last = olr->last;
182 olr->last = NULL;
183 olr->next = NULL;
184 LeaveCriticalSection(&p->usbd->lock);
185 }
186
187 /* --------------------------------------------------- */
188
189 /* Add paths to USB connected device */
190 /* Return an icom error */
191 int usb_get_paths_dk(
192 icompaths *p
193 ) {
194 struct usb_idevice *usbd = NULL;
195 USB_DK_DEVICE_INFO *DevicesArray;
196 ULONG i, NumberDevices;
197 int upto;
198
199 a1logd(p->log, 5, "usb_get_paths_dk:\n");
200
201 if (init_UsbDk(p)) {
202 return ICOM_SYS;
203 }
204
205 if (!UsbDk_GetDevicesList(&DevicesArray, &NumberDevices)) {
206 a1logd(p->log, 1, "UsbDk_GetDevicesList failed\n");
207 return ICOM_SYS;
208 }
209 a1logd(p->log, 6, "UsbDk_GetDevicesList got %d devices\n",NumberDevices);
210
211 // USB_DK_DEVICE_ID ID;
212 // ULONG64 FilterID;
213 // ULONG64 Port;
214 // ULONG64 Speed;
215 // USB_DEVICE_DESCRIPTOR DeviceDescriptor;
216
217 //USB_DEVICE_DESCRIPTOR
218 // UCHAR bLength;
219 // UCHAR bDescriptorType;
220 // USHORT bcdUSB;
221 // UCHAR bDeviceClass;
222 // UCHAR bDeviceSubClass;
223 // UCHAR bDeviceProtocol;
224 // UCHAR bMaxPacketSize0;
225 // USHORT idVendor;
226 // USHORT idProduct;
227 // USHORT bcdDevice;
228 // UCHAR iManufacturer;
229 // UCHAR iProduct;
230 // UCHAR iSerialNumber;
231 // UCHAR bNumConfigurations;
232
233 upto = p->get_cur_count(p);
234
235 for (i = 0; i < NumberDevices; i++) {
236 unsigned int vid, pid, nep10 = 0xffff;
237 unsigned int nconfig, configix;
238 devType itype;
239
240 vid = DevicesArray[i].DeviceDescriptor.idVendor;
241 pid = DevicesArray[i].DeviceDescriptor.idProduct;
242 nconfig = DevicesArray[i].DeviceDescriptor.bNumConfigurations;
243
244 /*
245 iManufacturer = DevicesArray[i].DeviceDescriptor.iManufacturer;
246 iProduct = DevicesArray[i].DeviceDescriptor.iProduct;
247 iSerialNumber = DevicesArray[i].DeviceDescriptor.iSerialNumber;
248 */
249 # pragma message("######### usbio_dk.c Missing SerialNumber read code !!!!! ########")
250
251 a1logd(p->log, 6, "usb_get_paths_dk: checking vid 0x%04x, pid 0x%04x\n",vid,pid);
252
253 /* Do a preliminary match */
254 if ((itype = inst_usb_match(vid, pid, 0)) == instUnknown) {
255 a1logd(p->log, 6 , "usb_get_paths_dk: instrument not reconized\n");
256 continue;
257 }
258
259 /* Allocate an idevice so that we can fill in the end point information */
260 if ((usbd = (struct usb_idevice *) calloc(sizeof(struct usb_idevice), 1)) == NULL) {
261 a1loge(p->log, ICOM_SYS, "usb_get_paths_dk: calloc failed!\n");
262 return ICOM_SYS;
263 }
264
265 usbd->nconfig = nconfig;
266 usbd->is_dk = 1;
267 usbd->ID = DevicesArray[i].ID;
268
269 /* Read the configuration descriptors looking for the first configuration, first interface, */
270 /* and extract the number of end points for each configuration */
271 for (configix = 0; configix < nconfig; configix++) {
272 USB_DK_CONFIG_DESCRIPTOR_REQUEST Request;
273 USB_CONFIGURATION_DESCRIPTOR *Descriptor;
274 ULONG Length;
275 int configno, totlen;
276 unsigned char *bp, *zp;
277 unsigned int nifce, ifcount, nep;
278
279 /* Read the configuration descriptor */
280 Request.ID = DevicesArray[i].ID;
281 Request.Index = configix;
282
283 if (!UsbDk_GetConfigurationDescriptor(&Request, &Descriptor, &Length)) {
284 a1logd(p->log, 1, "usb_get_paths_dk: '%s' failed to read configix %d descriptor\n",
285 ID2str(&usbd->ID), configix);
286 free(usbd);
287 break;
288 }
289 // USB_CONFIGURATION_DESCRIPTOR
290 // UCHAR bLength;
291 // UCHAR bDescriptorType;
292 // USHORT wTotalLength;
293 // UCHAR bNumInterfaces;
294 // UCHAR bConfigurationValue;
295 // UCHAR iConfiguration; Index of string descriptor
296 // UCHAR bmAttributes;
297 // UCHAR MaxPower;
298 // UCHAR .... Interface & Endpoint descriptors
299 nifce = Descriptor->bNumInterfaces; /* number of interfaces */
300 configno = Descriptor->bConfigurationValue; /* Configuration number */
301
302 if (configno != 1) {
303 UsbDk_ReleaseConfigurationDescriptor(Descriptor);
304 continue;
305 }
306
307 if ((totlen = Descriptor->wTotalLength) < 6) {
308 a1logd(p->log, 1, "usb_get_paths_dk: '%s' config desc size strange\n",ID2str(&usbd->ID));
309 UsbDk_ReleaseConfigurationDescriptor(Descriptor);
310 free(usbd);
311 break;
312 }
313
314 bp = ((unsigned char *)Descriptor) + Descriptor->bLength; /* Skip coniguration tag */
315 zp = ((unsigned char *)Descriptor) + totlen; /* Past last bytes */
316
317 /* We are at the first configuration. */
318 /* Just read tags and keep track of where we are */
319 ifcount = 0;
320 nep = 0;
321 usbd->nifce = nifce; /* number of interfaces */
322 usbd->config = configno; /* this configuration */
323 for (;bp < zp; bp += bp[0]) {
324 int ifaceno;
325 if ((bp + 1) >= zp)
326 break; /* Hmm - bodgy, give up */
327 if (bp[1] == IUSB_DESC_TYPE_INTERFACE) {
328 ifcount++;
329 if ((bp + 2) >= zp)
330 break; /* Hmm - bodgy, give up */
331 ifaceno = bp[2]; /* Get bInterfaceNumber */
332 } else if (bp[1] == IUSB_DESC_TYPE_ENDPOINT) {
333 nep++;
334 if ((bp + 5) >= zp)
335 break; /* Hmm - bodgy */
336 /* At first config - */
337 /* record current nep and end point details */
338 if (configno == 1) { /* (if isn't actually needed...) */
339 int ad = bp[2];
340 nep10 = nep;
341 usbd->EPINFO(ad).valid = 1;
342 usbd->EPINFO(ad).addr = ad;
343 usbd->EPINFO(ad).packetsize = usb2ushort(bp + 4);
344 usbd->EPINFO(ad).type = bp[3] & IUSB_ENDPOINT_TYPE_MASK;
345 usbd->EPINFO(ad).ifaceno = ifaceno;
346 a1logd(p->log, 6, "set ep ad 0x%x packetsize %d type %d\n",ad,usbd->EPINFO(ad).packetsize,usbd->EPINFO(ad).type);
347 }
348 }
349 /* Ignore other tags */
350 }
351 UsbDk_ReleaseConfigurationDescriptor(Descriptor);
352
353 /* We only get here on the first config, so we're done. */
354 break;
355
356 } /* Next configuration */
357 if (nep10 == 0xffff) { /* Hmm. Failed to find number of end points */
358 a1logd(p->log, 1, "usb_get_paths_dk: failed to find number of end points\n");
359 free(usbd);
360 continue;
361 }
362
363 /* Found a known instrument, and not found by a previous driver ? */
364 if ((itype = inst_usb_match(vid, pid, nep10)) != instUnknown
365 && !p->check_usb_upto(p, upto, itype)) {
366 char pname[400];
367 int rv;
368
369 a1logd(p->log, 1, "usb_get_paths_dk: found instrument vid 0x%04x, pid 0x%04x\n",vid,pid);
370
371 /* Create a path/identification */
372 sprintf(pname,"%s (%s)", ID2str(&usbd->ID), inst_name(itype));
373
374 /* Add the path and ep info to the list */
375 if ((rv = p->add_usb(p, pname, vid, pid, nep10, usbd, itype)) != ICOM_OK) {
376 free(usbd);
377 UsbDk_ReleaseDevicesList(DevicesArray);
378 return rv;
379 }
380
381
382 } else {
383 free(usbd);
384 }
385 } /* Next device */
386
387 UsbDk_ReleaseDevicesList(DevicesArray);
388
389 return ICOM_OK;
390 }
391
392
393 /* Copy usb_idevice contents from icompaths to icom */
394 /* return icom error */
395 int usb_copy_usb_idevice_dk(icoms *d, icompath *s) {
396 int i;
397 if (s->usbd == NULL) {
398 d->usbd = NULL;
399 return ICOM_OK;
400 }
401 if ((d->usbd = calloc(sizeof(struct usb_idevice), 1)) == NULL) {
402 a1loge(d->log, ICOM_SYS, "usb_copy_usb_idevice_dk: malloc\n");
403 return ICOM_SYS;
404 }
405
406 d->usbd->is_dk = s->usbd->is_dk;
407 d->usbd->ID = s->usbd->ID;
408
409 if ((d->usbd->SerialNumber = strdup(s->usbd->SerialNumber)) == NULL) {
410 a1loge(d->log, ICOM_SYS, "usb_copy_usb_idevice: malloc\n");
411 return ICOM_SYS;
412 }
413
414 /* Copy the current state & ep info */
415 d->nconfig = s->usbd->nconfig;
416 d->config = s->usbd->config;
417 d->nifce = s->usbd->nifce;
418 for (i = 0; i < 32; i++)
419 d->ep[i] = s->usbd->ep[i]; /* Struct copy */
420 return ICOM_OK;
421 }
422
423 /* Cleanup and then free a usb dev entry */
424 void usb_del_usb_idevice_dk(struct usb_idevice *usbd) {
425
426 if (usbd == NULL)
427 return;
428 if (usbd->SerialNumber != NULL)
429 free(usbd->SerialNumber);
430 free(usbd);
431 }
432
433 /* Cleanup any USB specific icoms state */
434 void usb_del_usb_dk(icoms *p) {
435
436 usb_del_usb_idevice(p->usbd);
437 }
438
439 /* Close an open USB port */
440 /* If we don't do this, the port and/or the device may be left in an unusable state. */
441 void usb_close_port_dk(icoms *p) {
442 a1logd(p->log, 6, "usb_close_port_dk: called\n");
443
444 if (p->is_open && p->usbd != NULL) {
445 HANDLE handle = p->usbd->handle;
446 int i;
447 struct usbdk_olr *olr;
448
449 p->usbd->handle = INVALID_HANDLE_VALUE;
450
451 /* We don't need to release interfaces */
452
453 /* Be nice and clean up. This helps workaround issue #105... */
454 /* Make sure any outstanding transfers are cancelled. */
455 a1logd(p->log, 6, "usb_close_port_dk: cancelling transfers\n");
456 for (i = 0; i < 32; i++) {
457 if (!p->ep[i].valid)
458 continue;
459 UsbDk_AbortPipe(handle, (ULONG64)p->ep[i].addr);
460 }
461
462 /* If there are pending operations, complete the OVERLAPPED, */
463 /* or else the driver may lock up and the system might need a re-boot... */
464 for (olr = p->usbd->olr; olr != NULL; olr = olr->next) {
465 DWORD xlength;
466 if (olr->olaps.hEvent != NULL) {
467 a1logd(p->log, 6, "usb_close_port_dk: doing GetOverlappedResult\n");
468 GetOverlappedResult(p->usbd->syshandle, &olr->olaps, &xlength, TRUE);
469 CloseHandle(olr->olaps.hEvent);
470 }
471 }
472
473 #ifdef NEVER /* We don't need to do this, since UsbDk CYCLEs the port anyway... */
474 /* Workaround for some bugs - reset device on close */
475 if (p->uflags & icomuf_reset_before_close) {
476 a1logd(p->log, 6, "usb_close_port_dk: icomuf_reset_before_close\n");
477
478 if (!UsbDk_ResetDevice(handle)) {
479 a1logd(p->log, 1, "usb_close_port_dk: reset failed\n");
480 }
481 msec_sleep(500); /* Things foul up unless we wait for the reset... */
482 }
483 #endif
484
485 if (!UsbDk_StopRedirect(handle)) {
486 a1logd(p->log, 1, "usb_close_port_dk failed\n");
487 }
488
489 a1logd(p->log, 6, "usb_close_port_dk: usb port has been released and closed\n");
490 }
491 p->is_open = 0;
492
493 /* Find it and delete it from our static cleanup list */
494 usb_delete_from_cleanup_list(p);
495 }
496
497 static void *urb_reaper(void *context); /* Declare */
498
499 /* Open a USB port for all our uses. */
500 /* This always re-opens the port */
501 /* return icom error */
502 static int usb_open_port_dk(
503 icoms *p,
504 int config, /* Configuration number */
505 int wr_ep, /* Write end point */
506 int rd_ep, /* Read end point */
507 icomuflags usbflags,/* Any special handling flags */
508 int retries, /* > 0 if we should retry set_configuration (100msec) */
509 char **pnames /* List of process names to try and kill before opening */
510 ) {
511 int rv, tries = 0;
512 a1logd(p->log, 8, "usb_open_port_dk: Make sure USB port is open, tries %d\n",retries);
513
514 if (p->is_open)
515 p->close_port(p);
516
517 /* Make sure the port is open */
518 if (!p->is_open) {
519 int rv, i, iface;
520 kkill_nproc_ctx *kpc = NULL;
521
522 if (config != 1) {
523 /* NT defaults to config 1, and nothing currently needs any other config, */
524 /* so we haven't implemented selecting a config yet... */
525 a1loge(p->log, ICOM_NOTS, "usb_open_port_dk: native driver cant handle config %d\n",config);
526 return ICOM_NOTS;
527
528 msec_sleep(50); /* Allow device some time to configure */
529 }
530
531 InitializeCriticalSection(&p->usbd->lock);
532
533 /* Do open retries */
534 for (tries = 0; retries >= 0; retries--, tries++) {
535
536 a1logd(p->log, 8, "usb_open_port_dk: About to open USB port '%s'\n",ID2str(&p->usbd->ID));
537
538 if (tries > 0) {
539 //msec_sleep(i_rand(50,100));
540 msec_sleep(77);
541 }
542
543 if ((p->usbd->handle = UsbDk_StartRedirect(&p->usbd->ID)) == INVALID_HANDLE_VALUE) {
544 a1logd(p->log, 8, "usb_open_port_dk: open '%s' config %d failed (%d) (Device being used ?)\n",ID2str(&p->usbd->ID),config,GetLastError());
545 if (retries <= 0) {
546 if (kpc != NULL) {
547 if (kpc->th->result < 0)
548 a1logw(p->log, "usb_open_port_dk: killing competing processes failed\n");
549 kpc->del(kpc);
550 }
551 a1logw(p->log, "usb_open_port_dk: open '%s' config %d failed (%d) (Device being used ?)\n",ID2str(&p->usbd->ID),config,GetLastError());
552 return ICOM_SYS;
553 }
554 continue;
555 } else if (p->debug)
556 a1logd(p->log, 2, "usb_open_port_dk: open port '%s' succeeded\n",ID2str(&p->usbd->ID));
557
558 p->usbd->syshandle = UsbDk_GetRedirectorSystemHandle(p->usbd->handle);
559 p->uflags = usbflags;
560
561 /* We're done */
562 break;
563 }
564
565 if (kpc != NULL)
566 kpc->del(kpc);
567
568 /* We should only do a set configuration if the device has more than one */
569 /* possible configuration and it is currently not the desired configuration, */
570 /* but we should avoid doing a set configuration if the OS has already */
571 /* selected the configuration we want, since two set configs seem to */
572 /* mess up the Spyder2, BUT we can't do a get config because this */
573 /* messes up the i1pro-D. */
574
575 /* For the moment, assume that the configuration is correct... */
576
577 /* UsbDk doesn't seem to support claiming of interfaces. */
578 /* Perhaps this is because it is not set up to share a USB device */
579 /* - it grabs exclusive use. */
580
581 /* Clear any errors */
582 /* (Some I/F seem to hang if we do this, some seem to hang if we don't !) */
583 if (!(p->uflags & icomuf_no_open_clear)) {
584 for (i = 0; i < 32; i++) {
585 if (!p->ep[i].valid)
586 continue;
587 p->usb_clearhalt(p, p->ep[i].addr);
588 }
589 }
590
591 /* Set "serial" coms values */
592 p->wr_ep = wr_ep;
593 p->rd_ep = rd_ep;
594 p->rd_qa = p->EPINFO(rd_ep).packetsize;
595 if (p->rd_qa == 0)
596 p->rd_qa = 8;
597 a1logd(p->log, 8, "usb_open_port_dk: 'serial' read quanta = packet size = %d\n",p->rd_qa);
598
599 p->is_open = 1;
600 a1logd(p->log, 8, "usb_open_port_dk: USB port is now open\n");
601 }
602
603 /* Install the cleanup signal handlers, and add to our cleanup list */
604 usb_install_signal_handlers(p);
605
606 return ICOM_OK;
607 }
608
609 /* -------------------------------------------------------------- */
610
611 /* Our universal (non-control pipe) USB transfer function, used for rd/wr. */
612 /* It appears that we may return a timeout with valid characters. */
613 static int icoms_usb_transaction_dk(
614 icoms *p,
615 usb_cancelt *cancelt, /* if !NULL, allows signalling another thread that op has started */
616 int *transferred,
617 icom_usb_trantype ttype, /* transfer type */
618 unsigned char endpoint, /* 0x80 for write, 0x00 for read */
619 unsigned char *buffer,
620 int length, /* Length to write/expected length to read */
621 unsigned int timeout /* In msec */
622 ) {
623 USB_DK_TRANSFER_REQUEST Request = { 0 };
624 TransferResult result;
625 int rv = ICOM_OK;
626 struct usbdk_olr olr;
627 int dirw = (endpoint & IUSB_ENDPOINT_DIR_MASK) == IUSB_ENDPOINT_OUT ? 1 : 0;
628 DWORD xlength;
629 int retsz = 0;
630
631 in_usb_rw++;
632
633 a1logd(p->log, 8, "icoms_usb_transaction_dk: req type 0x%x ep 0x%x size %d\n",ttype,endpoint,length);
634
635 if (transferred != NULL)
636 *transferred = 0;
637
638 if (ttype != icom_usb_trantype_interrutpt
639 && ttype != icom_usb_trantype_bulk) {
640 /* We only handle interrupt & bulk, not control */
641 return ICOM_SYS;
642 }
643
644 Request.EndpointAddress = endpoint;
645 Request.Buffer = buffer;
646 Request.BufferLength = length;
647 Request.TransferType = icom_usb_trantype_interrutpt ? InterruptTransferType : BulkTransferType;
648
649 memset(&olr, 0, sizeof(struct usbdk_olr));
650
651 if ((olr.olaps.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL)
652 return ICOM_SYS;
653
654 add_olr(p, &olr);
655
656 if (dirw)
657 result = UsbDk_WritePipe(p->usbd->handle, &Request, &olr.olaps);
658 else
659 result = UsbDk_ReadPipe(p->usbd->handle, &Request, &olr.olaps);
660
661 if (result == TransferFailure) {
662 rv = dirw ? ICOM_USBW : ICOM_USBR;
663 goto done;
664 }
665
666 if (cancelt != NULL) {
667 amutex_lock(cancelt->cmtx);
668 cancelt->hcancel = (void *)&endpoint;
669 cancelt->state = 1;
670 amutex_unlock(cancelt->condx); /* Signal any thread waiting for IO start */
671 amutex_unlock(cancelt->cmtx);
672 }
673
674 if (WaitForSingleObject(olr.olaps.hEvent, timeout) == WAIT_TIMEOUT) {
675 /* Cancel the operation, because it timed out */
676 UsbDk_AbortPipe(p->usbd->handle, (ULONG64)endpoint);
677 rv = ICOM_TO;
678 }
679
680 if (!GetOverlappedResult(p->usbd->handle, &olr.olaps, &xlength, TRUE)) {
681 if (rv == ICOM_OK) {
682 if (GetLastError() == ERROR_OPERATION_ABORTED)
683 rv = ICOM_CANC;
684 else
685 rv = dirw ? ICOM_USBW : ICOM_USBR;
686 }
687 }
688 done:;
689 if (cancelt != NULL) {
690 amutex_lock(cancelt->cmtx);
691 cancelt->hcancel = (void *)NULL;
692 if (cancelt->state == 0)
693 amutex_unlock(cancelt->condx); /* Make sure this gets unlocked */
694 cancelt->state = 2;
695 amutex_unlock(cancelt->cmtx);
696 }
697
698 CloseHandle(olr.olaps.hEvent);
699 olr.olaps.hEvent = NULL;
700 rem_olr(p, &olr);
701
702 /* xlength doesn't seem to correspond with what UsbDk did, BytesTransferred does. */
703 retsz = (int)Request.Result.GenResult.BytesTransferred;
704
705 if (transferred != NULL)
706 *transferred = retsz;
707
708 /* The requested size wasn't transferred */
709 if (rv == ICOM_OK && retsz != length)
710 rv |= ICOM_SHORT;
711
712 if (in_usb_rw < 0) { /* We're being cleaned up */
713 a1logd(p->log, 8, "coms_usb_transaction: aborting because in_usb_rw = %dn",in_usb_rw);
714 exit(0);
715 }
716
717 in_usb_rw--;
718
719 a1logd(p->log, 8, "coms_usb_transaction: returning err 0x%x and %d bytes\n",rv, xlength);
720
721 return rv;
722 }
723
724
725 /* Our control message routine. */
726 /* It's basically up to the caller to set parameters that make up a valid request, */
727 /* as they are fed directly into the control setup. */
728 /* Return error icom error code */
729 static int icoms_usb_control_msg_dk(
730 icoms *p,
731 int *transferred,
732 int requesttype, /* Setup values */
733 int request,
734 int value,
735 int index,
736 unsigned char *bytes, /* Data to read or write */
737 int size, /* Size of data to read or write */
738 int timeout
739 ) {
740 USB_DK_TRANSFER_REQUEST Request = { 0 };
741 TransferResult result;
742 struct usbdk_olr olr;
743 int rv = ICOM_OK;
744 int dirw = (requesttype & IUSB_REQ_DIR_MASK) == IUSB_REQ_HOST_TO_DEV ? 1 : 0;
745 int tsize;
746 unsigned char *tbuf = NULL;
747 DWORD xlength;
748 int retsz = 0;
749
750 a1logd(p->log, 8, "icoms_usb_control_msg_dk: type 0x%x req 0x%x size %d\n",requesttype,request,size);
751
752 if (transferred != NULL)
753 *transferred = 0;
754
755 /* We're guessing that the first 8 bytes of the buffer are the setup, */
756 /* with anything after that being the read/write data... */
757
758 /* Allocate buffer that includes setup */
759 tsize = 8 + size;
760 if ((tbuf = calloc(1, tsize)) == NULL) {
761 a1loge(p->log, ICOM_SYS, "icoms_usb_control_msg_dk: calloc failed\n");
762 return ICOM_SYS;
763 }
764 short2usb(&tbuf[6], size);
765
766 if (dirw)
767 memcpy(tbuf + 8, bytes, size); /* Copy write data */
768
769 /* Fill in the setup */
770 tbuf[0] = requesttype;
771 tbuf[1] = request;
772 short2usb(&tbuf[2], value);
773 short2usb(&tbuf[4], index);
774
775 Request.EndpointAddress = 0; /* Control pipe */
776 Request.Buffer = tbuf;
777 Request.BufferLength = tsize;
778 Request.TransferType = ControlTransferType;
779
780 memset(&olr, 0, sizeof(struct usbdk_olr));
781
782 if ((olr.olaps.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL)
783 return ICOM_SYS;
784
785 add_olr(p, &olr);
786
787 if (dirw) {
788 result = UsbDk_WritePipe(p->usbd->handle, &Request, &olr.olaps);
789 } else {
790 result = UsbDk_ReadPipe(p->usbd->handle, &Request, &olr.olaps);
791 }
792
793 if (result == TransferFailure) {
794 CloseHandle(olr.olaps.hEvent);
795 return ICOM_USBW;
796 }
797
798 /* Hmm. If we don't do this, the UsbDk driver locks up on */
799 /* this device, and the system needs a re-boot. */
800 if (!GetOverlappedResult(p->usbd->syshandle, &olr.olaps, &xlength, TRUE)) {
801 CloseHandle(olr.olaps.hEvent);
802 olr.olaps.hEvent = NULL;
803 rem_olr(p, &olr);
804 return ICOM_USBR;
805 }
806 CloseHandle(olr.olaps.hEvent);
807 olr.olaps.hEvent = NULL;
808 rem_olr(p, &olr);
809
810 /* xlength doesn't seem to correspond with what UsbDk did, BytesTransferred does. */
811 retsz = (int)Request.Result.GenResult.BytesTransferred;
812
813 if (!dirw && retsz > 0) {
814 memcpy(bytes, tbuf + 8, retsz); /* Copy read data */
815 }
816
817 if (transferred != NULL)
818 *transferred = retsz;
819
820 /* The requested size wasn't transferred */
821 if (rv == ICOM_OK && retsz != size)
822 rv |= ICOM_SHORT;
823
824 a1logd(p->log, 8, "icoms_usb_control_msg_dk: returning err 0x%x and %d bytes\n",rv, retsz);
825 return rv;
826 }
827
828 /* Cancel i/o operation in another thread. */
829 /* Only Vista has CancelIoEx that can cancel a single operation, */
830 /* so we cancel the io to the end point, which will */
831 /* achieve what we want. */
832 int icoms_usb_cancel_io_dk(
833 icoms *p,
834 usb_cancelt *cancelt
835 ) {
836 int rv = ICOM_OK;
837
838 amutex_lock(cancelt->cmtx);
839 if (cancelt->hcancel != NULL) {
840 int ep = *((unsigned char *)cancelt->hcancel);
841
842 if (!UsbDk_AbortPipe(p->usbd->handle, (ULONG64)ep)) {
843 a1logd(p->log, 1, "icoms_usb_cancel_io_dk failed\n");
844 rv = ICOM_SYS;
845 }
846 }
847 amutex_unlock(cancelt->cmtx);
848 return rv;
849 }
850
851 /* - - - - - - - - - - - - - - - - - - - - - - - - - */
852 /* Reset and end point data toggle to 0 */
853 int icoms_usb_resetep_dk(
854 icoms *p,
855 int ep /* End point address */
856 ) {
857 if (!UsbDk_ResetPipe(p->usbd->handle, (ULONG64)ep)) {
858 a1logd(p->log, 1, "icoms_usb_resetep_dk failed\n");
859 return ICOM_SYS;
860 }
861 return ICOM_OK;
862 }
863
864 /* - - - - - - - - - - - - - - - - - - - - - - - - - */
865 /* Clear a halt on an end point */
866 /* (Actually does a resetep) */
867 int icoms_usb_clearhalt_dk(
868 icoms *p,
869 int ep /* End point address */
870 ) {
871 if (!UsbDk_ResetPipe(p->usbd->handle, (ULONG64)ep)) {
872 a1logd(p->log, 1, "icoms_resetpipe/clearhalt_dk failed\n");
873 return ICOM_SYS;
874 }
875 return ICOM_OK;
876 }
877
878 /* - - - - - - - - - - - - - - - - - - - - - - - - - */