blob: 2d4c1a95b8009d36aa36567d7cfd5cfe8da48a37 [file] [log] [blame]
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -08001/*
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
Dima Zavin3fd82b82009-05-08 18:25:58 -070034#define ADB_SUBCLASS 0x42
35#define ADB_PROTOCOL 0x1
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080036
Dima Zavin3fd82b82009-05-08 18:25:58 -070037int vendorIds[] = {
38 VENDOR_ID_GOOGLE,
39 VENDOR_ID_HTC,
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080040};
Dima Zavin3fd82b82009-05-08 18:25:58 -070041#define NUM_VENDORS (sizeof(vendorIds)/sizeof(vendorIds[0]))
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080042
43static IONotificationPortRef notificationPort = 0;
Dima Zavin3fd82b82009-05-08 18:25:58 -070044static io_iterator_t notificationIterators[NUM_VENDORS];
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080045
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
Dima Zavin3fd82b82009-05-08 18:25:58 -070060static 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);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080066
67static int
68InitUSB()
69{
70 CFMutableDictionaryRef matchingDict;
71 CFRunLoopSourceRef runLoopSource;
Dima Zavin3fd82b82009-05-08 18:25:58 -070072 SInt32 vendor, if_subclass, if_protocol;
73 unsigned i;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080074
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
Dima Zavin3fd82b82009-05-08 18:25:58 -070083 //* 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);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -080090
91 if (!matchingDict) {
92 DBG("ERR: Couldn't create USB matching dictionary.\n");
93 return -1;
94 }
95
Dima Zavin3fd82b82009-05-08 18:25:58 -070096 //* 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));
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800109 IOServiceAddMatchingNotification(
110 notificationPort,
111 kIOFirstMatchNotification,
112 matchingDict,
Dima Zavin3fd82b82009-05-08 18:25:58 -0700113 AndroidInterfaceAdded,
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800114 NULL,
115 &notificationIterators[i]);
116
Dima Zavin3fd82b82009-05-08 18:25:58 -0700117 //* Iterate over set of matching interfaces to access already-present
118 //* devices and to arm the notification
119 AndroidInterfaceAdded(NULL, notificationIterators[i]);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800120 }
121
122 return 0;
123}
124
125static void
Dima Zavin3fd82b82009-05-08 18:25:58 -0700126AndroidInterfaceAdded(void *refCon, io_iterator_t iterator)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800127{
128 kern_return_t kr;
129 io_service_t usbDevice;
Dima Zavin3fd82b82009-05-08 18:25:58 -0700130 io_service_t usbInterface;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800131 IOCFPlugInInterface **plugInInterface = NULL;
Dima Zavin3fd82b82009-05-08 18:25:58 -0700132 IOUSBInterfaceInterface220 **iface = NULL;
133 IOUSBDeviceInterface197 **dev = NULL;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800134 HRESULT result;
135 SInt32 score;
136 UInt16 vendor;
137 UInt16 product;
138 UInt8 serialIndex;
139 char serial[256];
140
Dima Zavin3fd82b82009-05-08 18:25:58 -0700141 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
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800177 kr = IOCreatePlugInInterfaceForService(usbDevice,
178 kIOUSBDeviceUserClientTypeID,
179 kIOCFPlugInInterfaceID,
180 &plugInInterface, &score);
Dima Zavin3fd82b82009-05-08 18:25:58 -0700181 //* only needed this to find the plugin
182 (void)IOObjectRelease(usbDevice);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800183 if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
Dima Zavin3fd82b82009-05-08 18:25:58 -0700184 DBG("ERR: Unable to create a device plug-in (%08x)\n", kr);
185 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800186 }
187
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800188 result = (*plugInInterface)->QueryInterface(plugInInterface,
189 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID) &dev);
Dima Zavin3fd82b82009-05-08 18:25:58 -0700190 //* only needed this to query the plugin
191 (*plugInInterface)->Release(plugInInterface);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800192 if (result || !dev) {
Dima Zavin3fd82b82009-05-08 18:25:58 -0700193 DBG("ERR: Couldn't create a device interface (%08x)\n",
194 (int) result);
195 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800196 }
197
Dima Zavin3fd82b82009-05-08 18:25:58 -0700198 //* Now after all that, we actually have a ref to the device and
199 //* the interface that matched our criteria
200
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800201 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
Dima Zavin3fd82b82009-05-08 18:25:58 -0700209 req.bmRequestType =
210 USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800211 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
Dima Zavin3fd82b82009-05-08 18:25:58 -0700221 // skip first word, and copy the rest to the serial string,
222 // changing shorts to bytes.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800223 count = (req.wLenDone - 1) / 2;
224 for (i = 0; i < count; i++)
225 serial[i] = buffer[i + 1];
226 serial[i] = 0;
227 }
228 }
Dima Zavin3fd82b82009-05-08 18:25:58 -0700229 (*dev)->Release(dev);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800230
Dima Zavin3fd82b82009-05-08 18:25:58 -0700231 DBG("INFO: Found vid=%04x pid=%04x serial=%s\n", vendor, product,
232 serial);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800233
Dima Zavin3fd82b82009-05-08 18:25:58 -0700234 usb_handle* handle = CheckInterface((IOUSBInterfaceInterface**)iface,
235 vendor, product);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800236 if (handle == NULL) {
237 DBG("ERR: Could not find device interface: %08x\n", kr);
Dima Zavin3fd82b82009-05-08 18:25:58 -0700238 (*iface)->Release(iface);
239 continue;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800240 }
241
242 DBG("AndroidDeviceAdded calling register_usb_transport\n");
243 register_usb_transport(handle, (serial[0] ? serial : NULL));
244
Dima Zavin3fd82b82009-05-08 18:25:58 -0700245 // 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.
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800248 kr = IOServiceAddInterestNotification(notificationPort,
Dima Zavin3fd82b82009-05-08 18:25:58 -0700249 usbInterface,
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800250 kIOGeneralInterest,
Dima Zavin3fd82b82009-05-08 18:25:58 -0700251 AndroidInterfaceNotify,
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800252 handle,
253 &handle->usbNotification);
Dima Zavin3fd82b82009-05-08 18:25:58 -0700254
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800255 if (kIOReturnSuccess != kr) {
256 DBG("ERR: Unable to create interest notification (%08x)\n", kr);
257 }
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800258 }
259}
260
261static void
Dima Zavin3fd82b82009-05-08 18:25:58 -0700262AndroidInterfaceNotify(void *refCon, io_service_t service, natural_t messageType, void *messageArgument)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800263{
264 usb_handle *handle = (usb_handle *)refCon;
265
266 if (messageType == kIOMessageServiceIsTerminated) {
Dima Zavin3fd82b82009-05-08 18:25:58 -0700267 if (!handle) {
268 DBG("ERR: NULL handle\n");
269 return;
270 }
271 DBG("AndroidInterfaceNotify\n");
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800272 IOObjectRelease(handle->usbNotification);
273 usb_kick(handle);
274 }
275}
276
Dima Zavin3fd82b82009-05-08 18:25:58 -0700277//* TODO: simplify this further since we only register to get ADB interface
278//* subclass+protocol events
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800279static usb_handle*
Dima Zavin3fd82b82009-05-08 18:25:58 -0700280CheckInterface(IOUSBInterfaceInterface **interface, UInt16 vendor, UInt16 product)
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800281{
282 usb_handle* handle = NULL;
283 IOReturn kr;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800284 UInt8 interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
Dima Zavin3fd82b82009-05-08 18:25:58 -0700285 UInt8 endpoint;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800286
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800287
Dima Zavin3fd82b82009-05-08 18:25:58 -0700288 //* 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);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800291 if (kr != kIOReturnSuccess) {
Dima Zavin3fd82b82009-05-08 18:25:58 -0700292 DBG("ERR: Could not open interface: (%08x)\n", kr);
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800293 return NULL;
294 }
295
Dima Zavin3fd82b82009-05-08 18:25:58 -0700296 //* 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;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800301 }
302
Dima Zavin3fd82b82009-05-08 18:25:58 -0700303 //* 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;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800349 return handle;
Dima Zavin3fd82b82009-05-08 18:25:58 -0700350
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;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800358}
359
360
361void* RunLoopThread(void* unused)
362{
Dima Zavin3fd82b82009-05-08 18:25:58 -0700363 unsigned i;
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800364
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
Dima Zavin3fd82b82009-05-08 18:25:58 -0700377 for (i = 0; i < NUM_VENDORS; i++) {
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800378 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 */
Dima Zavin3fd82b82009-05-08 18:25:58 -0700504 if (!handle)
505 return;
506
The Android Open Source Projectdd7bc332009-03-03 19:32:55 -0800507 if (handle->interface)
508 {
509 (*handle->interface)->USBInterfaceClose(handle->interface);
510 (*handle->interface)->Release(handle->interface);
511 handle->interface = 0;
512 }
513}