Debian Codegraph @

spectro/usbio_ox.c

raw symbols SCIP
1
2 /* General USB I/O support, OS X native implementation. */
3 /* This file is conditionaly #included into usbio.c */
4
5 /*
6 * Argyll Color Management System
7 *
8 * Author: Graeme W. Gill
9 * Date: 2006/22/4
10 *
11 * Copyright 2006 - 2013 Graeme W. Gill
12 * All rights reserved.
13 *
14 * This material is licenced under the GNU GENERAL PUBLIC LICENSE Version 2 or later :-
15 * see the License2.txt file for licencing details.
16 */
17
18 /* OS X I/O error codes are in IOKit/IOReturn.h */
19
20 #include <sys/time.h>
21
22 #include <CoreFoundation/CoreFoundation.h>
23 #include <IOKit/IOTypes.h>
24 #include <IOKit/IOKitLib.h>
25 #include <IOKit/usb/IOUSBLib.h>
26 #include <IOKit/IOCFPlugIn.h>
27 //#include <IOKit/IOCFBundle.h>
28 #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
29 # include <objc/objc-auto.h>
30 #endif
31
32 /* Add paths to USB connected instruments */
33 /* Return an icom error */
34 int usb_get_paths(
35 icompaths *p
36 ) {
37 kern_return_t kstat;
38 CFMutableDictionaryRef sdict; /* USB Device dictionary */
39 io_iterator_t mit; /* Matching itterator */
40 int vid, pid;
41 struct usb_idevice *usbd = NULL;
42
43 a1logd(p->log, 6, "usb_get_paths: about to look through devices:\n");
44
45 /* Get dictionary of USB devices */
46 if ((sdict = IOServiceMatching(kIOUSBDeviceClassName)) == NULL) {
47 a1loge(p->log, ICOM_SYS, "usb_get_paths() IOServiceMatching returned a NULL dictionary\n");
48 return ICOM_SYS;
49 }
50
51 /* Init itterator to find matching types. Consumes sdict reference */
52 if ((kstat = IOServiceGetMatchingServices(kIOMasterPortDefault, sdict, &mit))
53 != KERN_SUCCESS) {
54 a1loge(p->log, ICOM_SYS, "usb_get_paths() IOServiceGetMatchingServices returned %d\n", kstat);
55 return ICOM_SYS;
56 }
57
58 /* Find all the matching USB devices */
59 for (;;) {
60 io_object_t ioob; /* USB object found */
61 io_iterator_t it1; /* Child level 1 */
62 CFMutableDictionaryRef usbprops = 0; /* USB Device properties */
63 CFNumberRef vref, pref; /* USB Vendor and Product ID propeties */
64 CFNumberRef nconfref; /* No configurations */
65 CFNumberRef nepref, lidpref; /* No ep's, Location ID properties */
66 unsigned int vid = 0, pid = 0, nep, tnep, nconfig = 0, lid = 0;
67 devType itype;
68
69 if ((ioob = IOIteratorNext(mit)) == 0)
70 break;
71
72 /* Get the two properies we need. */
73 if ((vref = IORegistryEntryCreateCFProperty(ioob, CFSTR(kUSBVendorID),
74 kCFAllocatorDefault,kNilOptions)) != 0) {
75 CFNumberGetValue(vref, kCFNumberIntType, &vid);
76 CFRelease(vref);
77 }
78 if ((pref = IORegistryEntryCreateCFProperty(ioob, CFSTR(kUSBProductID),
79 kCFAllocatorDefault,kNilOptions)) != 0) {
80 CFNumberGetValue(pref, kCFNumberIntType, &pid);
81 CFRelease(pref);
82 }
83
84 if ((nconfref = IORegistryEntryCreateCFProperty(ioob, CFSTR("bNumConfigurations"),
85 kCFAllocatorDefault,kNilOptions)) != 0) {
86 CFNumberGetValue(nconfref, kCFNumberIntType, &nconfig);
87 CFRelease(nconfref);
88 }
89
90 if ((lidpref = IORegistryEntryCreateCFProperty(ioob, CFSTR("locationID"),
91 kCFAllocatorDefault,kNilOptions)) != 0) {
92 CFNumberGetValue(lidpref, kCFNumberIntType, &lid);
93 CFRelease(lidpref);
94 }
95
96 a1logd(p->log, 6, "usb_get_paths: checking vid 0x%04x, pid 0x%04x, lid 0x%x\n",vid,pid,lid);
97
98 /* Do a preliminary match */
99 if ((itype = inst_usb_match(vid, pid, 0)) == instUnknown) {
100 a1logd(p->log, 6 , "usb_get_paths: 0x%04x 0x%04x not reconized\n",vid,pid);
101 IOObjectRelease(ioob); /* Release found object */
102 continue;
103 }
104
105 /* Allocate an idevice so that we can fill in the end point information */
106 if ((usbd = (struct usb_idevice *) calloc(sizeof(struct usb_idevice), 1)) == NULL) {
107 a1loge(p->log, ICOM_SYS, "usb_get_paths: calloc failed!\n");
108 return ICOM_SYS;
109 }
110
111 usbd->nconfig = nconfig;
112 usbd->config = 1; /* We are only interested in config 1 */
113
114 /* Can we get Manufacturer, Product, SerialNumber using IORegistryEntryCreateCFProperty ? */
115
116 /* Go through all the Interfaces, adding up the number of end points */
117 tnep = 0;
118 if ((kstat = IORegistryEntryCreateIterator(ioob, kIOServicePlane,
119 kIORegistryIterateRecursively, &it1)) != KERN_SUCCESS) {
120 IOObjectRelease(ioob);
121 IOObjectRelease(mit);
122 a1loge(p->log, kstat, "usb_get_paths: IORegistryEntryCreateIterator() with %d\n",kstat);
123 return ICOM_SYS;
124 }
125 usbd->nifce = 0;
126 for (;;) {
127 io_object_t ch1; /* Child object 1 */
128 if ((ch1 = IOIteratorNext(it1)) == 0)
129 break;
130 if (IOObjectConformsTo(ch1, "IOUSBInterface")) {
131 unsigned int config = 0;
132
133 /* Get the configuration number */
134 if ((nconfref = IORegistryEntryCreateCFProperty(ch1, CFSTR(kUSBConfigurationValue),
135 kCFAllocatorDefault,kNilOptions)) != 0) {
136 CFNumberGetValue(nconfref, kCFNumberIntType, &config);
137 CFRelease(nconfref);
138 }
139
140 if (config != 1)
141 continue;
142
143 usbd->nifce++;
144
145 /* Get the number of end points */
146 if ((nepref = IORegistryEntryCreateCFProperty(ch1, CFSTR(kUSBNumEndpoints),
147 kCFAllocatorDefault,kNilOptions)) != 0) {
148 CFNumberGetValue(nepref, kCFNumberIntType, &nep);
149 CFRelease(nepref);
150 tnep += nep;
151 }
152 IOObjectRelease(ch1);
153 }
154 }
155 IOObjectRelease(it1);
156
157 if ((itype = inst_usb_match(vid, pid, tnep)) != instUnknown) {
158 int i;
159 char pname[400];
160 int rv;
161
162 /* If this device is HID, it will have already added to the paths list, */
163 /* so check for this and skip this device if it is already there. */
164 for (i = 0; i < p->ndpaths[dtix_combined]; i++) {
165 if (p->dpaths[i][dtix_combined]->vid == vid
166 && p->dpaths[i][dtix_combined]->pid == pid
167 && p->dpaths[i][dtix_combined]->hidd != NULL
168 && p->dpaths[i][dtix_combined]->hidd->lid == lid) {
169 a1logd(p->log, 1, "usb_get_paths: Ignoring device because it is already in list as HID\n");
170 break;
171 }
172 }
173 if (i < p->ndpaths[dtix_combined]) {
174 IOObjectRelease(ioob); /* Release found object */
175 free(usbd);
176
177 } else {
178
179 a1logd(p->log, 1, "usb_get_paths: found instrument vid 0x%04x, pid 0x%04x\n",vid,pid);
180 usbd->lid = lid;
181 usbd->ioob = ioob;
182
183 /* Create a path/identification */
184 sprintf(pname,"usb%d: (%s)", lid >> 20, inst_name(itype));
185
186 /* Add the path and ep info to the list */
187 if ((rv = p->add_usb(p, pname, vid, pid, tnep, usbd, itype)) != ICOM_OK) {
188 IOObjectRelease(ioob); /* Release found object */
189 free(usbd);
190 IOObjectRelease(mit); /* Release the itterator */
191 return rv;
192 }
193
194 }
195 } else {
196 IOObjectRelease(ioob); /* Release found object */
197 free(usbd);
198 }
199 }
200 IOObjectRelease(mit); /* Release the itterator */
201
202 a1logd(p->log, 8, "usb_get_paths: returning %d paths and ICOM_OK\n",p->ndpaths[dtix_combined]);
203 return ICOM_OK;
204 }
205
206 /* Copy usb_idevice contents from icompaths to icom */
207 /* return icom error */
208 int usb_copy_usb_idevice(icoms *d, icompath *s) {
209 int i;
210 if (s->usbd == NULL) {
211 d->usbd = NULL;
212 return ICOM_OK;
213 }
214 if ((d->usbd = calloc(sizeof(struct usb_idevice), 1)) == NULL) {
215 a1loge(d->log, ICOM_SYS, "usb_copy_usb_idevice: malloc\n");
216 return ICOM_SYS;
217 }
218 if (s->usbd->SerialNumber != NULL
219 && (d->usbd->SerialNumber = strdup(s->usbd->SerialNumber)) == NULL) {
220 a1loge(d->log, ICOM_SYS, "usb_copy_usb_idevice: malloc\n");
221 return ICOM_SYS;
222 }
223
224 d->nconfig = s->usbd->nconfig;
225 d->config = s->usbd->config;
226 d->nifce = s->usbd->nifce;
227 d->usbd->ioob = s->usbd->ioob;
228 IOObjectRetain(d->usbd->ioob);
229 return ICOM_OK;
230 }
231
232 /* Cleanup and then free a usb dev entry */
233 void usb_del_usb_idevice(struct usb_idevice *usbd) {
234
235 if (usbd == NULL)
236 return;
237
238 if (usbd->SerialNumber != NULL)
239 free(usbd->SerialNumber);
240
241 if (usbd->ioob != 0)
242 IOObjectRelease(usbd->ioob);
243
244 free(usbd);
245 }
246
247 /* Cleanup any USB specific icoms state */
248 void usb_del_usb(icoms *p) {
249
250 usb_del_usb_idevice(p->usbd);
251 }
252
253 /* Clean up anything allocated/created in p->usbd, but don't free p->usbd itself */
254 static void cleanup_device(icoms *p) {
255
256 if (p->usbd != NULL) {
257 if (p->usbd->device != NULL) { /* device is open */
258 int i;
259
260 /* Release all the interfaces */
261 for (i = 0; i < p->usbd->nifce; i++) {
262 if (p->usbd->interfaces[i] != NULL) {
263 (*p->usbd->interfaces[i])->USBInterfaceClose(p->usbd->interfaces[i]);
264 (*p->usbd->interfaces[i])->Release(p->usbd->interfaces[i]);
265 }
266 }
267
268 /* Close the device */
269 (*(p->usbd->device))->USBDeviceClose(p->usbd->device);
270 (*(p->usbd->device))->Release(p->usbd->device);
271 }
272 memset(p->usbd, 0, sizeof(struct usb_idevice));
273 }
274 }
275
276 /* Close an open USB port */
277 /* If we don't do this, the port and/or the device may be left in an unusable state. */
278 void usb_close_port(icoms *p) {
279
280 a1logd(p->log, 6, "usb_close_port: called\n");
281
282 if (p->is_open && p->usbd != NULL) {
283
284 /* Workaround for some bugs - reset device on close */
285 if (p->uflags & icomuf_reset_before_close) {
286 IOReturn rv;
287
288 a1logd(p->log, 6, "usb_close_port: icomuf_reset_before_close\n");
289
290 // OS X >= 10.11 ignores ResetDevice, so use alternative... */
291 if ((rv = (*(p->usbd->device))->USBDeviceReEnumerate(p->usbd->device, 0))
292 != kIOReturnSuccess)
293 a1logd(p->log, 1, "usb_close_port: USBDeviceReEnumerate failed with 0x%x\n",rv);
294 }
295
296 /* Close down and free everything in p->usbd */
297 cleanup_device(p);
298 if (p->usbd != NULL) {
299 free(p->usbd);
300 p->usbd = NULL;
301 }
302 a1logd(p->log, 6, "usb_close_port: usb port has been released and closed\n");
303 }
304 p->is_open = 0;
305
306 /* Find it and delete it from our static cleanup list */
307 usb_delete_from_cleanup_list(p);
308 }
309
310 static int icoms_usb_control_msg(icoms *p, int *transferred, int requesttype, int request,
311 int value, int index, unsigned char *bytes, int size, int timeout);
312 static void *io_runloop(void *context);
313
314 /* Open a USB port for all our uses. */
315 /* This always re-opens the port */
316 /* return icom error */
317 static int usb_open_port(
318 icoms *p,
319 int config, /* Configuration number, (1 based) */
320 int wr_ep, /* Write end point */
321 int rd_ep, /* Read end point */
322 icomuflags usbflags,/* Any special handling flags */
323 int retries, /* > 0 if we should retry set_configuration (100msec) */
324 char **pnames /* List of process names to try and kill before opening */
325 ) {
326 IOReturn rv;
327 int tries = 0;
328 a1logd(p->log, 8, "usb_open_port: Make sure USB port is open, tries %d\n",retries);
329
330 if (p->is_open)
331 p->close_port(p);
332
333 /* Make sure the port is open */
334 if (!p->is_open) {
335 kkill_nproc_ctx *kpc = NULL;
336
337 if (config != 1) {
338 /* Nothing currently needs it, so we haven't implemented it yet... */
339 a1loge(p->log, ICOM_NOTS, "usb_open_port: native driver cant handle config %d\n",config);
340 return ICOM_NOTS;
341 }
342
343 /* Do open retries */
344 for (tries = 0; retries >= 0; retries--, tries++) {
345 IOCFPlugInInterface **piif = NULL;
346 SInt32 score;
347
348 a1logd(p->log, 8, "usb_open_port: About to open USB port '%s'\n",p->name);
349
350 if (tries > 0) {
351 //msec_sleep(i_rand(50,100));
352 msec_sleep(77);
353 }
354 if (tries > 0 && pnames != NULL && kpc == NULL) {
355 if ((kpc = kkill_nprocess(pnames, p->log)) == NULL) {
356 a1logd(p->log, 1, "kkill_nprocess returned error!\n");
357 return ICOM_SYS;
358 }
359 }
360
361 if ((rv = IOCreatePlugInInterfaceForService(p->usbd->ioob,
362 kIOUSBDeviceUserClientTypeID, kIOCFPlugInInterfaceID,
363 &piif, &score)) != kIOReturnSuccess || piif == NULL) {
364 a1loge(p->log, rv, "usb_open_port: Failed to get piif for "
365 "USB device '%s', result 0x%x, piif 0x%x\n",p->name,rv,piif);
366 return ICOM_SYS;
367 }
368
369 p->usbd->device = NULL;
370 if ((rv = (*piif)->QueryInterface(piif,
371 CFUUIDGetUUIDBytes(DeviceInterfaceID), (void *)&p->usbd->device))
372 != kIOReturnSuccess || p->usbd->device == NULL) {
373 a1loge(p->log, rv, "usb_open_port: QueryInterface '%s' failed with 0%x\n",p->name, rv);
374 (*piif)->Release(piif);
375 return ICOM_SYS;
376 }
377 (*piif)->Release(piif); /* delete intermediate object */
378
379 if ((rv = (*p->usbd->device)->USBDeviceOpenSeize(p->usbd->device)) != kIOReturnSuccess) {
380 a1logd(p->log, 8, "usb_open_port: open '%s' config %d failed (0x%x) (Device being used ?)\n",p->name,config,rv);
381 if (retries <= 0) {
382 if (kpc != NULL) {
383 if (kpc->th->result < 0)
384 a1logw(p->log, "usb_open_port: killing competing processes failed\n");
385 kpc->del(kpc);
386 }
387 a1loge(p->log, rv, "usb_open_port: open '%s' config %d failed (0x%x) (Device being used ?)\n",p->name, config, rv);
388 (*p->usbd->device)->Release(p->usbd->device);
389 return ICOM_SYS;
390 }
391 continue;
392 } else if (p->debug)
393 a1logd(p->log, 1, "usb_open_port: open port '%s' succeeded\n",p->name);
394
395 p->uflags = usbflags;
396
397 /* We're done retries */
398 break;
399 }
400
401 if (kpc != NULL)
402 kpc->del(kpc);
403
404 /* Try and get the USB serial number */
405 #ifdef kUSBSerialNumberString /* Easy way */
406 {
407 CFStringRef sref; /* Serial number propety */
408 char serno[IUSB_DESC_TYPE_STRING_MAX_SIZE/2];
409
410 if ((sref = IORegistryEntryCreateCFProperty(p->usbd->ioob, CFSTR(kUSBSerialNumberString),
411 kCFAllocatorDefault,kNilOptions)) != 0) {
412 /* Convert from CF string to C string */
413 if (CFStringGetCString(sref, serno, IUSB_DESC_TYPE_STRING_MAX_SIZE/2,
414 kCFStringEncodingUTF8)) {
415 if ((p->usbd->SerialNumber = strdup(serno)) == NULL) {
416 a1loge(p->log, rv, "usb_open_port: open '%s' malloc failed\n",p->name);
417 cleanup_device(p);
418 return ICOM_SYS;
419 }
420 } else {
421 a1logd(p->log, 1, "usb_open_port: CFStringGetCString failed\n");
422 }
423 CFRelease(sref);
424 } else {
425 a1logd(p->log, 1, "usb_open_port: IORegistryEntryCreateCFProperty kUSBSerialNumberString failed\n");
426 }
427 }
428 #else /* The hard way... */
429 {
430 CFNumberRef siref; /* Serial number index */
431 unsigned int iserialno = 0;
432
433 if ((siref = IORegistryEntryCreateCFProperty(p->usbd->ioob, CFSTR(kUSBSerialNumberStringIndex),
434 kCFAllocatorDefault,kNilOptions)) != 0) {
435 CFNumberGetValue(siref, kCFNumberIntType, &iserialno);
436 CFRelease(siref);
437 } else {
438 a1logd(p->log, 6, "usb_open_port: failed to get kUSBSerialNumberStringIndex\n");
439 }
440 if (iserialno != 0) {
441 unsigned char buf[IUSB_DESC_TYPE_STRING_MAX_SIZE];
442 int se = 0;
443 int retsz = 0;
444
445 if (((se = icoms_usb_control_msg(p, &retsz,
446 IUSB_REQ_DEV_TO_HOST | IUSB_REQ_TYPE_STANDARD | IUSB_REQ_RECIP_DEVICE,
447 IUSB_REQ_GET_DESCRIPTOR,
448 (IUSB_DESC_TYPE_STRING << 8) | iserialno, 0,
449 buf, IUSB_DESC_TYPE_STRING_MAX_SIZE, 200)) != ICOM_OK && se != ICOM_SHORT)
450 || retsz < IUSB_DESC_TYPE_STRING_MIN_SIZE) {
451 a1logd(p->log, 1, "usb_open_port failed to read device serial no with ICOM err 0x%x and retsz %d\n",se,retsz);
452 } else {
453 unsigned int slen = buf[0];
454
455 if (slen > 2 && (slen & 1) == 0) {
456 icmUTF16 buf2[IUSB_DESC_TYPE_STRING_MAX_SIZE/2];
457 unsigned int j;
458 size_t s8len;
459
460 /* Convert to 16 bit native endian and add nul terminator */
461 slen = (slen-2)/2;
462 for (j = 0; j < slen; j++) {
463 buf2[j] = usb2ushort(buf + 2 + j * 2);
464 }
465 buf2[j] = 0;
466
467 s8len =icmUTF16toUTF8(NULL, NULL, buf2); /* Compute UTF8 size */
468
469 if ((p->usbd->SerialNumber = (char *) calloc(s8len, 1)) == NULL) {
470 a1loge(p->log, ICOM_SYS, "usb_get_paths_w0 calloc failed!\n");
471 cleanup_device(p);
472 return ICOM_SYS;
473 }
474 icmUTF16toUTF8(NULL, (unsigned char *)p->usbd->SerialNumber, buf2); /* Convert to UTF8 */
475 a1logd(p->log, 6, "usb_open_port got USB serial no '%s'\n",p->usbd->SerialNumber);
476 }
477 }
478 }
479 }
480 #endif /* !kUSBSerialNumberString */
481
482 /* We should only do a set configuration if the device has more than one */
483 /* possible configuration and it is currently not the desired configuration, */
484 /* but we should avoid doing a set configuration if the OS has already */
485 /* selected the configuration we want, since two set configs seem to */
486 /* mess up the Spyder2, BUT we can't do a get config because this */
487 /* messes up the i1pro-D. */
488
489 /* OS X doesn't do a set_configuration() by default, so force one. */
490 p->cconfig = 0;
491
492 if (p->cconfig != config) {
493 if ((rv = (*(p->usbd->device))->SetConfiguration(
494 p->usbd->device, config)) != kIOReturnSuccess) {
495 a1loge(p->log, rv, "usb_open_port: SetConfiguration failed with 0x%x\n",rv);
496 cleanup_device(p);
497 return ICOM_SYS;
498 }
499 p->cconfig = config;
500 a1logd(p->log, 6, "usb_open_port: SetConfiguration %d OK\n",config);
501 }
502
503 /* For some devices (Spyder 3/4 ?) on some versions of OS X (Ventura ?), */
504 /* we seem to need to let the device recover from the set configuration. */
505 msec_sleep(50);
506
507 /* Get interfaces */
508 {
509 int i, j;
510 IOUSBFindInterfaceRequest req;
511 io_iterator_t ioit;
512 io_service_t iface;
513 IOCFPlugInInterface **pluginref = NULL;
514 SInt32 score;
515
516 req.bInterfaceClass =
517 req.bInterfaceSubClass =
518 req.bInterfaceProtocol =
519 req.bAlternateSetting = kIOUSBFindInterfaceDontCare;
520
521 if ((rv = (*(p->usbd->device))->CreateInterfaceIterator(
522 p->usbd->device, &req, &ioit)) != kIOReturnSuccess) {
523 a1loge(p->log, rv, "usb_open_port: CreateInterfaceIterator failed with 0x%x\n",rv);
524 cleanup_device(p);
525 return ICOM_SYS;
526 }
527 iface = IOIteratorNext(ioit);
528 for (i = 0; iface != 0; i++, iface = IOIteratorNext(ioit)) {
529 u_int8_t nep;
530
531 if ((rv = IOCreatePlugInInterfaceForService(iface,
532 kIOUSBInterfaceUserClientTypeID,
533 kIOCFPlugInInterfaceID,
534 &pluginref, &score)) != kIOReturnSuccess) {
535 a1loge(p->log, rv, "usb_open_port: IOCreatePlugInInterfaceForService failed with 0x%x\n",rv);
536 IOObjectRelease(iface);
537 IOObjectRelease(ioit);
538 cleanup_device(p);
539 return ICOM_SYS;
540 }
541 IOObjectRelease(iface);
542 if ((rv = (*pluginref)->QueryInterface(pluginref,
543 CFUUIDGetUUIDBytes(InterfaceInterfaceID),
544 (void *)&p->usbd->interfaces[i])) != kIOReturnSuccess) {
545 a1loge(p->log, rv, "usb_open_port: QueryInterface failed with 0x%x\n",rv);
546 (*pluginref)->Stop(pluginref);
547 IODestroyPlugInInterface(pluginref);
548 IOObjectRelease(ioit);
549 cleanup_device(p);
550 return ICOM_SYS;
551 }
552 (*pluginref)->Stop(pluginref);
553 IODestroyPlugInInterface(pluginref); // this stops IOServices though ??
554
555 /* This can fail if the device has multiple interfaces, and */
556 /* one of them is grabbed by a system interface (i.e. debug serial port) */
557 /* So soft fail, and rely on ep use to fail for invalid interface */
558 if ((rv = (*(p->usbd->interfaces[i]))->USBInterfaceOpen(
559 p->usbd->interfaces[i])) != kIOReturnSuccess) {
560 #ifdef NEVER
561 a1loge(p->log, rv, "usb_open_port: USBInterfaceOpen %d failed with 0x%x\n",i, rv);
562 IOObjectRelease(ioit);
563 cleanup_device(p);
564 return ICOM_SYS;
565 #else
566 a1logw(p->log, "usb_open_port: USBInterfaceOpen %d failed with 0x%x\n",i,rv);
567 continue;
568 #endif
569 }
570
571 /* Get the end point details, and set reference to pipe no and interfece ix */
572 if ((rv = (*(p->usbd->interfaces[i]))->GetNumEndpoints(
573 p->usbd->interfaces[i], &nep)) != kIOReturnSuccess) {
574 a1loge(p->log, rv, "usb_open_port: GetNumEndpoints failed with 0x%x\n",rv);
575 IOObjectRelease(ioit);
576 cleanup_device(p);
577 return ICOM_SYS;
578 }
579 for (j = 0; j < nep; j++) {
580 UInt8 direction, pnumber, transferType, interval;
581 UInt16 maxPacketSize;
582 int ad;
583 if ((rv = (*(p->usbd->interfaces[i]))->GetPipeProperties(
584 p->usbd->interfaces[i], (UInt8)(j+1), &direction, &pnumber,
585 &transferType, &maxPacketSize, &interval)) != kIOReturnSuccess) {
586 a1loge(p->log, rv, "usb_open_port: GetPipeProperties failed with 0x%x\n",rv);
587 IOObjectRelease(ioit);
588 cleanup_device(p);
589 return ICOM_SYS;
590 }
591 ad = ((direction << IUSB_ENDPOINT_DIR_SHIFT) & IUSB_ENDPOINT_DIR_MASK)
592 | (pnumber & IUSB_ENDPOINT_NUM_MASK);
593 p->EPINFO(ad).valid = 1;
594 p->EPINFO(ad).addr = ad;
595 p->EPINFO(ad).packetsize = maxPacketSize;
596 p->EPINFO(ad).type = transferType & IUSB_ENDPOINT_TYPE_MASK;
597 p->EPINFO(ad).ifaceno = i;
598 p->EPINFO(ad).pipe = j+1;
599 a1logd(p->log, 6, "set ep ad 0x%x packetsize %d type %d, if %d, pipe %d\n",ad,maxPacketSize,transferType & IUSB_ENDPOINT_TYPE_MASK,i,j);
600 }
601 }
602 p->usbd->nifce = i; /* Just in case.. */
603
604 IOObjectRelease(ioit);
605 }
606
607 /* Clear any errors */
608 /* (Some I/F seem to hang if we do this, some seem to hang if we don't !) */
609 if (!(p->uflags & icomuf_no_open_clear)) {
610 int i;
611 for (i = 0; i < 32; i++) {
612 if (!p->ep[i].valid)
613 continue;
614 p->usb_clearhalt(p, p->ep[i].addr);
615 }
616 }
617
618 /* Set "serial" coms values */
619 p->wr_ep = wr_ep;
620 p->rd_ep = rd_ep;
621 p->rd_qa = p->EPINFO(rd_ep).packetsize;
622 if (p->rd_qa == 0)
623 p->rd_qa = 8;
624 a1logd(p->log, 8, "usb_open_port: 'serial' read quanta = packet size = %d\n",p->rd_qa);
625
626 p->is_open = 1;
627 a1logd(p->log, 8, "usb_open_port: USB port is now open\n");
628 }
629
630 /* Install the cleanup signal handlers, and add to our cleanup list */
631 usb_install_signal_handlers(p);
632
633 return ICOM_OK;
634 }
635
636 /* -------------------------------------------------------------- */
637
638 /* I/O structures */
639
640 typedef struct _usbio_req {
641 icoms *p;
642 int iix; /* Interface index */
643 UInt8 pno; /* pipe index */
644 volatile int done; /* Done flag */
645 int xlength; /* Bytes transferred */
646 IOReturn result; /* Result of transaction */
647 CFRunLoopRef rlr; /* RunLoop of calling thread */
648 } usbio_req;
649
650 /* Async completion callback - called by RunLoop */
651 static void io_callback(void *refcon, IOReturn result, void *arg0) {
652 usbio_req *req = (usbio_req *)refcon;
653
654 a1logd(req->p->log, 1, "io_callback: result 0x%x, length %d\n",result,(int)(long)arg0);
655
656 req->xlength = (int)(long)arg0;
657 req->result = result;
658 req->done = 1;
659
660 CFRunLoopStop(req->rlr); /* We're done */
661 }
662
663 /* Our universal (non-control) USB transfer function */
664 static int icoms_usb_transaction(
665 icoms *p,
666 usb_cancelt *cancelt,
667 int *transferred,
668 icom_usb_trantype ttype, /* transfer type */
669 unsigned char endpoint, /* 0x80 for control write, 0x00 for control read */
670 unsigned char *buffer,
671 int length,
672 unsigned int timeout /* In msec */
673 ) {
674 int reqrv = ICOM_OK, rv = 0;
675 int dirw = (endpoint & IUSB_ENDPOINT_DIR_MASK) == IUSB_ENDPOINT_OUT ? 1 : 0;
676 usbio_req req;
677 IOReturn result;
678 CFRunLoopSourceRef cfsource; /* Device event sources */
679 int iix = p->EPINFO(endpoint).ifaceno;
680 UInt8 pno = (UInt8)p->EPINFO(endpoint).pipe;
681
682 in_usb_rw++;
683
684 a1logd(p->log, 8, "icoms_usb_transaction: req type 0x%x ep 0x%x size %d\n",ttype,endpoint,length);
685
686 if (transferred != NULL)
687 *transferred = 0;
688
689 if (ttype != icom_usb_trantype_interrutpt
690 && ttype != icom_usb_trantype_bulk) {
691 /* We only handle interrupt & bulk, not control */
692 return ICOM_SYS;
693 }
694
695 req.p = p;
696 req.iix = iix;
697 req.pno = pno;
698 req.xlength = 0;
699 req.done = 0;
700
701 req.rlr = CFRunLoopGetCurrent(); /* Get this threads RunLoop */
702 CFRetain(req.rlr);
703
704 /* Create an async event source for the interface */
705 if ((result = (*(p->usbd->interfaces[iix]))->CreateInterfaceAsyncEventSource(
706 p->usbd->interfaces[iix], &cfsource)) != kIOReturnSuccess) {
707 a1logw(p->log, "icoms_usb_transaction: CreateInterfaceAsyncEventSource failed with 0x%x\n",result);
708 CFRelease(req.rlr);
709 return ICOM_SYS;
710 }
711 CFRetain(cfsource);
712
713 /* Add it to the RunLoop */
714 CFRunLoopAddSource(req.rlr, cfsource, kCFRunLoopDefaultMode);
715
716 if (dirw)
717 result = (*p->usbd->interfaces[iix])->WritePipeAsync(p->usbd->interfaces[iix],
718 pno, buffer, length, io_callback, &req);
719 else
720 result = (*p->usbd->interfaces[iix])->ReadPipeAsync(p->usbd->interfaces[iix],
721 pno, buffer, length, io_callback, &req);
722
723
724 if (result != kIOReturnSuccess) {
725 a1loge(p->log, ICOM_SYS, "icoms_usb_transaction: %sPipeAsync failed with 0x%x\n",dirw ? "Write" : "Read", result);
726 reqrv = ICOM_SYS;
727 goto done;
728 }
729
730 if (cancelt != NULL) {
731 amutex_lock(cancelt->cmtx);
732 cancelt->hcancel = (void *)&req;
733 cancelt->state = 1;
734 amutex_unlock(cancelt->condx); /* Signal any thread waiting for IO start */
735 amutex_unlock(cancelt->cmtx);
736 }
737
738 /* Wait for the callback to complete or for a timeout */
739 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0, false);
740
741 // kCFRunLoopRunFinished = 1
742 // kCFRunLoopRunStopped = 2
743 // kCFRunLoopRunTimedOut = 3
744 // kCFRunLoopRunHandledSource = 4
745
746 if (result == kCFRunLoopRunTimedOut) {
747 /* Timed out - so abort i/o */
748 a1logd(p->log, 8, "coms_usb_transaction: time out - aborting io\n");
749 (*p->usbd->interfaces[iix])->AbortPipe(p->usbd->interfaces[iix], pno);
750 CFRunLoopRun(); /* Wait for abort */
751 reqrv = ICOM_TO;
752 } else if (result != kCFRunLoopRunStopped) {
753 a1logd(p->log, 8, "coms_usb_transaction: unexpected result 0x%x\n",result);
754 reqrv = ICOM_USBR;
755 }
756
757 done:;
758 CFRunLoopRemoveSource(req.rlr, cfsource, kCFRunLoopDefaultMode);
759 CFRelease(cfsource);
760 CFRelease(req.rlr);
761
762 a1logd(p->log, 8, "coms_usb_transaction: completed with reqrv 0x%x and xlength %d\n",req.result,req.xlength);
763
764 /* If io was aborted, ClearPipeStall */
765 if (req.result == kIOReturnAborted) {
766 a1logd(p->log, 8, "coms_usb_transaction: io was aborted\n");
767 #if (InterfaceVersion > 182)
768 (*p->usbd->interfaces[iix])->ClearPipeStallBothEnds(p->usbd->interfaces[iix], pno);
769 #else
770 (*p->usbd->interfaces[iix])->ClearPipeStall(p->usbd->interfaces[iix], pno);
771 // icoms_usb_control_msg(p, NULL, IUSB_REQ_HOST_TO_DEV | IUSB_REQ_TYPE_STANDARD
772 // | IUSB_REQ_RECIP_ENDPOINT, IUSB_REQ_CLEAR_FEATURE,
773 // IUSB_FEATURE_EP_HALT, endpoint, NULL, 0, 200);
774 #endif
775 if (reqrv == ICOM_OK) /* If not aborted for a known reason, must be cancelled */
776 reqrv = ICOM_CANC;
777 }
778
779 /* If normal completion - not timed out or aborted */
780 if (reqrv == ICOM_OK) { /* Completed OK */
781 if (req.result == kIOReturnSuccess) {
782 if (req.xlength != length)
783 reqrv = ICOM_SHORT;
784 } else {
785 if (dirw)
786 reqrv = ICOM_USBW;
787 else
788 reqrv = ICOM_USBR;
789 }
790 }
791
792 if (transferred != NULL)
793 *transferred = req.xlength;
794
795 if (cancelt != NULL) {
796 amutex_lock(cancelt->cmtx);
797 cancelt->hcancel = (void *)NULL;
798 if (cancelt->state == 0)
799 amutex_unlock(cancelt->condx);
800 cancelt->state = 2;
801 amutex_unlock(cancelt->cmtx);
802 }
803
804 if (in_usb_rw < 0)
805 exit(0);
806
807 in_usb_rw--;
808
809 a1logd(p->log, 8, "coms_usb_transaction: returning err 0x%x and %d bytes\n",reqrv, req.xlength);
810
811 return reqrv;
812 }
813
814
815 /* Our control message routine */
816 /* Return error icom error code */
817 static int icoms_usb_control_msg(
818 icoms *p,
819 int *transferred,
820 int requesttype, int request,
821 int value, int index, unsigned char *bytes, int size,
822 int timeout) {
823 int reqrv = ICOM_OK;
824 int dirw = (requesttype & IUSB_REQ_DIR_MASK) == IUSB_REQ_HOST_TO_DEV ? 1 : 0;
825 IOReturn rv;
826 IOUSBDevRequestTO req;
827
828 a1logd(p->log, 8, "icoms_usb_control_msg: type 0x%x req 0x%x size %d\n",requesttype,request,size);
829 bzero(&req, sizeof(req));
830 req.bmRequestType = requesttype;
831 req.bRequest = request;
832 req.wValue = value;
833 req.wIndex = index;
834 req.wLength = size;
835 req.pData = bytes;
836 req.completionTimeout = timeout;
837 req.noDataTimeout = timeout;
838
839 if (transferred != NULL)
840 *transferred = 0;
841
842 if ((rv = (*(p->usbd->device))->DeviceRequestTO(p->usbd->device, &req)) != kIOReturnSuccess) {
843 if (rv == kIOUSBTransactionTimeout) {
844 reqrv = ICOM_TO;
845 } else {
846 if (dirw)
847 reqrv = ICOM_USBW;
848 else
849 reqrv = ICOM_USBR;
850 }
851 } else {
852 if (transferred != NULL)
853 *transferred = req.wLenDone;
854
855 /* The requested size wasn't transferred */
856 if (req.wLenDone != size)
857 reqrv |= ICOM_SHORT;
858 }
859
860 a1logd(p->log, 8, "icoms_usb_control_msg: returning err 0x%x and %d bytes\n",reqrv, transferred != NULL ? *transferred : -1);
861 return reqrv;
862 }
863
864 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
865 /* Time out error return value */
866
867 //#define USBIO_ERROR_TIMEOUT -ETIMEDOUT
868
869 /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
870
871 /* Cancel i/o in another thread */
872 int icoms_usb_cancel_io(
873 icoms *p,
874 usb_cancelt *cancelt
875 ) {
876 int reqrv = ICOM_OK;
877
878 amutex_lock(cancelt->cmtx);
879 usbio_req *req = (usbio_req *)cancelt->hcancel;
880 if (req != NULL) {
881 IOReturn rv;
882
883 if ((rv = (*p->usbd->interfaces[req->iix])->AbortPipe(
884 p->usbd->interfaces[req->iix], req->pno)) != kIOReturnSuccess) {
885 reqrv = ICOM_USBW;
886 }
887 }
888 amutex_unlock(cancelt->cmtx);
889
890 return reqrv;
891 }
892
893 /* - - - - - - - - - - - - - - - - - - - - - - - - - */
894 /* Reset and end point data toggle to 0 */
895 int icoms_usb_resetep(
896 icoms *p,
897 int ep /* End point address */
898 ) {
899 int reqrv = ICOM_OK;
900 int iix = p->EPINFO(ep).ifaceno;
901 UInt8 pno = (UInt8)p->EPINFO(ep).pipe;
902 IOReturn rv;
903
904 if ((rv = (*p->usbd->interfaces[iix])->ResetPipe(
905 p->usbd->interfaces[iix], pno)) != kIOReturnSuccess) {
906 a1logd(p->log, 1, "icoms_usb_resetep failed with 0x%x\n",rv);
907 reqrv = ICOM_USBW;
908 }
909 return reqrv;
910 }
911
912 /* - - - - - - - - - - - - - - - - - - - - - - - - - */
913 /* Clear a halt on an end point */
914 int icoms_usb_clearhalt(
915 icoms *p,
916 int ep /* End point address */
917 ) {
918 int reqrv = ICOM_OK;
919 int iix = p->EPINFO(ep).ifaceno;
920 UInt8 pno = (UInt8)p->EPINFO(ep).pipe;
921 IOReturn rv;
922 int irv;
923
924 #if (InterfaceVersion > 182)
925 if ((rv = (*p->usbd->interfaces[iix])->ClearPipeStallBothEnds(
926 p->usbd->interfaces[iix], pno)) != kIOReturnSuccess) {
927 a1logd(p->log, 1, "icoms_usb_clearhalt failed with 0x%x\n",rv);
928 reqrv = ICOM_USBW;
929 }
930 #else
931 if ((rv = (*p->usbd->interfaces[iix])->ClearPipeStall(
932 p->usbd->interfaces[iix], pno)) != kIOReturnSuccess) {
933 a1logd(p->log, 1, "icoms_usb_clearhalt failed with 0x%x\n",rv);
934 reqrv = ICOM_USBW;
935 }
936 if ((irv = icoms_usb_control_msg(p, NULL, IUSB_REQ_HOST_TO_DEV | IUSB_REQ_TYPE_STANDARD
937 | IUSB_REQ_RECIP_ENDPOINT, IUSB_REQ_CLEAR_FEATURE,
938 IUSB_FEATURE_EP_HALT, ep, NULL, 0, 200)) != ICOM_OK) {
939 a1logd(p->log, 1, "icoms_usb_clearhalt far end failed with 0x%x\n",irv);
940 reqrv = ICOM_USBW;
941 }
942 #endif
943 return reqrv;
944 }
945
946 /* - - - - - - - - - - - - - - - - - - - - - - - - - */
947
948 #ifdef NEVER
949 {
950 IOUSBFindInterfaceRequest req;
951 io_iterator_t ioit;
952
953 /* See if we can find any interfaces */
954 req.bInterfaceClass =
955 req.bInterfaceSubClass =
956 req.bInterfaceProtocol =
957 req.bAlternateSetting = kIOUSBFindInterfaceDontCare;
958
959 if ((rv = (*(p->usbd->device))->CreateInterfaceIterator(
960 p->usbd->device, &req, &ioit)) != kIOReturnSuccess) {
961 a1loge(p->log, rv, "usb_open_port: CreateInterfaceIterator failed with 0x%x\n",rv);
962 cleanup_device(p);
963 return ICOM_SYS;
964 }
965 if (IOIteratorNext(ioit) == 0) { /* Configure the device */
966 IOUSBConfigurationDescriptorPtr confdesc;
967
968 if ((rv = (*(p->usbd->device))->GetConfigurationDescriptorPtr(
969 p->usbd->device, config-1, &confdesc)) != kIOReturnSuccess) {
970 a1loge(p->log, rv, "usb_open_port: GetConfigurationDescriptorPtr failed with 0x%x\n",rv);
971 IOObjectRelease(ioit);
972 cleanup_device(p);
973 return ICOM_SYS;
974 }
975 if ((rv = (*(p->usbd->device))->SetConfiguration(
976 p->usbd->device, confdesc->bConfigurationValue)) != kIOReturnSuccess) {
977 a1loge(p->log, rv, "usb_open_port: SetConfiguration failed with 0x%x\n",rv);
978 IOObjectRelease(ioit);
979 cleanup_device(p);
980 return ICOM_SYS;
981 }
982 a1logd(p->log, 6, "usb_open_port: SetConfiguration %d OK\n",confdesc->bConfigurationValue);
983
984 } else { /* Some diagnostics */
985 UInt8 confno;
986 if ((rv = (*(p->usbd->device))->GetConfiguration(
987 p->usbd->device, &confno)) != kIOReturnSuccess) {
988 a1logd(p->log, 6, "usb_open_port: GetConfiguration failed with 0x%x\n",rv);
989 } else {
990 a1logd(p->log, 6, "usb_open_port: Device didn't need configuring - currently %d\n",confno);
991 }
992 }
993 IOObjectRelease(ioit);
994
995 }
996 #endif /* NEVER */