usb_osx.c revision 3fd82b8861aa410fab7785074941b459d92220c1
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <CoreFoundation/CoreFoundation.h>
18
19#include <IOKit/IOKitLib.h>
20#include <IOKit/IOCFPlugIn.h>
21#include <IOKit/usb/IOUSBLib.h>
22#include <IOKit/IOMessage.h>
23#include <mach/mach_port.h>
24
25#include "sysdeps.h"
26
27#include <stdio.h>
28
29#define TRACE_TAG   TRACE_USB
30#include "adb.h"
31
32#define  DBG   D
33
34#define ADB_SUBCLASS           0x42
35#define ADB_PROTOCOL           0x1
36
37int vendorIds[] = {
38    VENDOR_ID_GOOGLE,
39    VENDOR_ID_HTC,
40};
41#define NUM_VENDORS             (sizeof(vendorIds)/sizeof(vendorIds[0]))
42
43static IONotificationPortRef    notificationPort = 0;
44static io_iterator_t            notificationIterators[NUM_VENDORS];
45
46struct usb_handle
47{
48    UInt8                     bulkIn;
49    UInt8                     bulkOut;
50    IOUSBInterfaceInterface   **interface;
51    io_object_t               usbNotification;
52    unsigned int              zero_mask;
53};
54
55static CFRunLoopRef currentRunLoop = 0;
56static pthread_mutex_t start_lock;
57static pthread_cond_t start_cond;
58
59
60static void AndroidInterfaceAdded(void *refCon, io_iterator_t iterator);
61static void AndroidInterfaceNotify(void *refCon, io_iterator_t iterator,
62                                   natural_t messageType,
63                                   void *messageArgument);
64static usb_handle* CheckInterface(IOUSBInterfaceInterface **iface,
65                                  UInt16 vendor, UInt16 product);
66
67static int
68InitUSB()
69{
70    CFMutableDictionaryRef  matchingDict;
71    CFRunLoopSourceRef      runLoopSource;
72    SInt32                  vendor, if_subclass, if_protocol;
73    unsigned                i;
74
75    //* To set up asynchronous notifications, create a notification port and
76    //* add its run loop event source to the program's run loop
77    notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
78    runLoopSource = IONotificationPortGetRunLoopSource(notificationPort);
79    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
80
81    memset(notificationIterators, 0, sizeof(notificationIterators));
82
83    //* loop through all supported vendors
84    for (i = 0; i < NUM_VENDORS; i++) {
85        //* Create our matching dictionary to find the Android device's
86        //* adb interface
87        //* IOServiceAddMatchingNotification consumes the reference, so we do
88        //* not need to release this
89        matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
90
91        if (!matchingDict) {
92            DBG("ERR: Couldn't create USB matching dictionary.\n");
93            return -1;
94        }
95
96        //* Match based on vendor id, interface subclass and protocol
97        vendor = vendorIds[i];
98        if_subclass = ADB_SUBCLASS;
99        if_protocol = ADB_PROTOCOL;
100        CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID),
101                             CFNumberCreate(kCFAllocatorDefault,
102                                            kCFNumberSInt32Type, &vendor));
103        CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceSubClass),
104                             CFNumberCreate(kCFAllocatorDefault,
105                                            kCFNumberSInt32Type, &if_subclass));
106        CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceProtocol),
107                             CFNumberCreate(kCFAllocatorDefault,
108                                            kCFNumberSInt32Type, &if_protocol));
109        IOServiceAddMatchingNotification(
110                notificationPort,
111                kIOFirstMatchNotification,
112                matchingDict,
113                AndroidInterfaceAdded,
114                NULL,
115                &notificationIterators[i]);
116
117        //* Iterate over set of matching interfaces to access already-present
118        //* devices and to arm the notification
119        AndroidInterfaceAdded(NULL, notificationIterators[i]);
120    }
121
122    return 0;
123}
124
125static void
126AndroidInterfaceAdded(void *refCon, io_iterator_t iterator)
127{
128    kern_return_t            kr;
129    io_service_t             usbDevice;
130    io_service_t             usbInterface;
131    IOCFPlugInInterface      **plugInInterface = NULL;
132    IOUSBInterfaceInterface220  **iface = NULL;
133    IOUSBDeviceInterface197  **dev = NULL;
134    HRESULT                  result;
135    SInt32                   score;
136    UInt16                   vendor;
137    UInt16                   product;
138    UInt8                    serialIndex;
139    char                     serial[256];
140
141    while ((usbInterface = IOIteratorNext(iterator))) {
142        //* Create an intermediate interface plugin
143        kr = IOCreatePlugInInterfaceForService(usbInterface,
144                                               kIOUSBInterfaceUserClientTypeID,
145                                               kIOCFPlugInInterfaceID,
146                                               &plugInInterface, &score);
147        IOObjectRelease(usbInterface);
148        if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
149            DBG("ERR: Unable to create an interface plug-in (%08x)\n", kr);
150            continue;
151        }
152
153        //* This gets us the interface object
154        result = (*plugInInterface)->QueryInterface(plugInInterface,
155                CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID)
156                &iface);
157        //* We only needed the plugin to get the interface, so discard it
158        (*plugInInterface)->Release(plugInInterface);
159        if (result || !iface) {
160            DBG("ERR: Couldn't query the interface (%08x)\n", (int) result);
161            continue;
162        }
163
164        //* this gets us an ioservice, with which we will find the actual
165        //* device; after getting a plugin, and querying the interface, of
166        //* course.
167        //* Gotta love OS X
168        kr = (*iface)->GetDevice(iface, &usbDevice);
169        if (kIOReturnSuccess != kr || !usbDevice) {
170            DBG("ERR: Couldn't grab device from interface (%08x)\n", kr);
171            continue;
172        }
173
174        plugInInterface = NULL;
175        score = 0;
176        //* create an intermediate device plugin
177        kr = IOCreatePlugInInterfaceForService(usbDevice,
178                                               kIOUSBDeviceUserClientTypeID,
179                                               kIOCFPlugInInterfaceID,
180                                               &plugInInterface, &score);
181        //* only needed this to find the plugin
182        (void)IOObjectRelease(usbDevice);
183        if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
184            DBG("ERR: Unable to create a device plug-in (%08x)\n", kr);
185            continue;
186        }
187
188        result = (*plugInInterface)->QueryInterface(plugInInterface,
189                CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID) &dev);
190        //* only needed this to query the plugin
191        (*plugInInterface)->Release(plugInInterface);
192        if (result || !dev) {
193            DBG("ERR: Couldn't create a device interface (%08x)\n",
194                (int) result);
195            continue;
196        }
197
198        //* Now after all that, we actually have a ref to the device and
199        //* the interface that matched our criteria
200
201        kr = (*dev)->GetDeviceVendor(dev, &vendor);
202        kr = (*dev)->GetDeviceProduct(dev, &product);
203        kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
204
205        if (serialIndex > 0) {
206            IOUSBDevRequest req;
207            UInt16          buffer[256];
208
209            req.bmRequestType =
210                USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
211            req.bRequest = kUSBRqGetDescriptor;
212            req.wValue = (kUSBStringDesc << 8) | serialIndex;
213            req.wIndex = 0;
214            req.pData = buffer;
215            req.wLength = sizeof(buffer);
216            kr = (*dev)->DeviceRequest(dev, &req);
217
218            if (kr == kIOReturnSuccess && req.wLenDone > 0) {
219                int i, count;
220
221                // skip first word, and copy the rest to the serial string,
222                // changing shorts to bytes.
223                count = (req.wLenDone - 1) / 2;
224                for (i = 0; i < count; i++)
225                  serial[i] = buffer[i + 1];
226                serial[i] = 0;
227            }
228        }
229        (*dev)->Release(dev);
230
231        DBG("INFO: Found vid=%04x pid=%04x serial=%s\n", vendor, product,
232            serial);
233
234        usb_handle* handle = CheckInterface((IOUSBInterfaceInterface**)iface,
235                                            vendor, product);
236        if (handle == NULL) {
237            DBG("ERR: Could not find device interface: %08x\n", kr);
238            (*iface)->Release(iface);
239            continue;
240        }
241
242        DBG("AndroidDeviceAdded calling register_usb_transport\n");
243        register_usb_transport(handle, (serial[0] ? serial : NULL));
244
245        // Register for an interest notification of this device being removed.
246        // Pass the reference to our private data as the refCon for the
247        // notification.
248        kr = IOServiceAddInterestNotification(notificationPort,
249                usbInterface,
250                kIOGeneralInterest,
251                AndroidInterfaceNotify,
252                handle,
253                &handle->usbNotification);
254
255        if (kIOReturnSuccess != kr) {
256            DBG("ERR: Unable to create interest notification (%08x)\n", kr);
257        }
258    }
259}
260
261static void
262AndroidInterfaceNotify(void *refCon, io_service_t service, natural_t messageType, void *messageArgument)
263{
264    usb_handle *handle = (usb_handle *)refCon;
265
266    if (messageType == kIOMessageServiceIsTerminated) {
267        if (!handle) {
268            DBG("ERR: NULL handle\n");
269            return;
270        }
271        DBG("AndroidInterfaceNotify\n");
272        IOObjectRelease(handle->usbNotification);
273        usb_kick(handle);
274    }
275}
276
277//* TODO: simplify this further since we only register to get ADB interface
278//* subclass+protocol events
279static usb_handle*
280CheckInterface(IOUSBInterfaceInterface **interface, UInt16 vendor, UInt16 product)
281{
282    usb_handle*                 handle = NULL;
283    IOReturn                    kr;
284    UInt8  interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
285    UInt8  endpoint;
286
287
288    //* Now open the interface.  This will cause the pipes associated with
289    //* the endpoints in the interface descriptor to be instantiated
290    kr = (*interface)->USBInterfaceOpen(interface);
291    if (kr != kIOReturnSuccess) {
292        DBG("ERR: Could not open interface: (%08x)\n", kr);
293        return NULL;
294    }
295
296    //* Get the number of endpoints associated with this interface
297    kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
298    if (kr != kIOReturnSuccess) {
299        DBG("ERR: Unable to get number of endpoints: (%08x)\n", kr);
300        goto err_get_num_ep;
301    }
302
303    //* Get interface class, subclass and protocol
304    if ((*interface)->GetInterfaceClass(interface, &interfaceClass) != kIOReturnSuccess ||
305            (*interface)->GetInterfaceSubClass(interface, &interfaceSubClass) != kIOReturnSuccess ||
306            (*interface)->GetInterfaceProtocol(interface, &interfaceProtocol) != kIOReturnSuccess) {
307            DBG("ERR: Unable to get interface class, subclass and protocol\n");
308            goto err_get_interface_class;
309    }
310
311    //* check to make sure interface class, subclass and protocol match ADB
312    //* avoid opening mass storage endpoints
313    if (!is_adb_interface(vendor, product, interfaceClass,
314                interfaceSubClass, interfaceProtocol))
315        goto err_bad_adb_interface;
316
317    handle = calloc(1, sizeof(usb_handle));
318
319    //* Iterate over the endpoints for this interface and find the first
320    //* bulk in/out pipes available.  These will be our read/write pipes.
321    for (endpoint = 0; endpoint <= interfaceNumEndpoints; endpoint++) {
322        UInt8   transferType;
323        UInt16  maxPacketSize;
324        UInt8   interval;
325        UInt8   number;
326        UInt8   direction;
327
328        kr = (*interface)->GetPipeProperties(interface, endpoint, &direction,
329                &number, &transferType, &maxPacketSize, &interval);
330
331        if (kIOReturnSuccess == kr) {
332            if (kUSBBulk != transferType)
333                continue;
334
335            if (kUSBIn == direction)
336                handle->bulkIn = endpoint;
337
338            if (kUSBOut == direction)
339                handle->bulkOut = endpoint;
340
341            handle->zero_mask = maxPacketSize - 1;
342        } else {
343            DBG("ERR: FindDeviceInterface - could not get pipe properties\n");
344            goto err_get_pipe_props;
345        }
346    }
347
348    handle->interface = interface;
349    return handle;
350
351err_get_pipe_props:
352    free(handle);
353err_bad_adb_interface:
354err_get_interface_class:
355err_get_num_ep:
356    (*interface)->USBInterfaceClose(interface);
357    return NULL;
358}
359
360
361void* RunLoopThread(void* unused)
362{
363    unsigned i;
364
365    InitUSB();
366
367    currentRunLoop = CFRunLoopGetCurrent();
368
369    // Signal the parent that we are running
370    adb_mutex_lock(&start_lock);
371    adb_cond_signal(&start_cond);
372    adb_mutex_unlock(&start_lock);
373
374    CFRunLoopRun();
375    currentRunLoop = 0;
376
377    for (i = 0; i < NUM_VENDORS; i++) {
378        IOObjectRelease(notificationIterators[i]);
379    }
380    IONotificationPortDestroy(notificationPort);
381
382    DBG("RunLoopThread done\n");
383    return NULL;
384}
385
386
387static int initialized = 0;
388void usb_init()
389{
390    if (!initialized)
391    {
392        adb_thread_t    tid;
393
394        adb_mutex_init(&start_lock, NULL);
395        adb_cond_init(&start_cond, NULL);
396
397        if(adb_thread_create(&tid, RunLoopThread, NULL))
398            fatal_errno("cannot create input thread");
399
400        // Wait for initialization to finish
401        adb_mutex_lock(&start_lock);
402        adb_cond_wait(&start_cond, &start_lock);
403        adb_mutex_unlock(&start_lock);
404
405        adb_mutex_destroy(&start_lock);
406        adb_cond_destroy(&start_cond);
407
408        initialized = 1;
409    }
410}
411
412void usb_cleanup()
413{
414    DBG("usb_cleanup\n");
415    close_usb_devices();
416    if (currentRunLoop)
417        CFRunLoopStop(currentRunLoop);
418}
419
420int usb_write(usb_handle *handle, const void *buf, int len)
421{
422    IOReturn    result;
423
424    if (!len)
425        return 0;
426
427    if (!handle)
428        return -1;
429
430    if (NULL == handle->interface) {
431        DBG("ERR: usb_write interface was null\n");
432        return -1;
433    }
434
435    if (0 == handle->bulkOut) {
436        DBG("ERR: bulkOut endpoint not assigned\n");
437        return -1;
438    }
439
440    result =
441        (*handle->interface)->WritePipe(
442                              handle->interface, handle->bulkOut, (void *)buf, len);
443
444    if ((result == 0) && (handle->zero_mask)) {
445        /* we need 0-markers and our transfer */
446        if(!(len & handle->zero_mask)) {
447            result =
448                (*handle->interface)->WritePipe(
449                        handle->interface, handle->bulkOut, (void *)buf, 0);
450        }
451    }
452
453    if (0 == result)
454        return 0;
455
456    DBG("ERR: usb_write failed with status %d\n", result);
457    return -1;
458}
459
460int usb_read(usb_handle *handle, void *buf, int len)
461{
462    IOReturn result;
463    UInt32  numBytes = len;
464
465    if (!len) {
466        return 0;
467    }
468
469    if (!handle) {
470        return -1;
471    }
472
473    if (NULL == handle->interface) {
474        DBG("ERR: usb_read interface was null\n");
475        return -1;
476    }
477
478    if (0 == handle->bulkIn) {
479        DBG("ERR: bulkIn endpoint not assigned\n");
480        return -1;
481    }
482
483    result =
484      (*handle->interface)->ReadPipe(handle->interface,
485                                    handle->bulkIn, buf, &numBytes);
486
487    if (0 == result)
488        return 0;
489    else {
490        DBG("ERR: usb_read failed with status %d\n", result);
491    }
492
493    return -1;
494}
495
496int usb_close(usb_handle *handle)
497{
498    return 0;
499}
500
501void usb_kick(usb_handle *handle)
502{
503    /* release the interface */
504    if (!handle)
505        return;
506
507    if (handle->interface)
508    {
509        (*handle->interface)->USBInterfaceClose(handle->interface);
510        (*handle->interface)->Release(handle->interface);
511        handle->interface = 0;
512    }
513}
514