2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include <CoreFoundation/CoreFoundation.h>
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>
29 #define TRACE_TAG TRACE_USB
31 #include "usb_vendors.h"
35 static IONotificationPortRef notificationPort = 0;
36 static io_iterator_t* notificationIterators;
42 IOUSBInterfaceInterface **interface;
43 io_object_t usbNotification;
44 unsigned int zero_mask;
47 static CFRunLoopRef currentRunLoop = 0;
48 static pthread_mutex_t start_lock;
49 static pthread_cond_t start_cond;
52 static void AndroidInterfaceAdded(void *refCon, io_iterator_t iterator);
53 static void AndroidInterfaceNotify(void *refCon, io_iterator_t iterator,
54 natural_t messageType,
55 void *messageArgument);
56 static usb_handle* CheckInterface(IOUSBInterfaceInterface **iface,
57 UInt16 vendor, UInt16 product);
62 CFMutableDictionaryRef matchingDict;
63 CFRunLoopSourceRef runLoopSource;
64 SInt32 vendor, if_subclass, if_protocol;
67 //* To set up asynchronous notifications, create a notification port and
68 //* add its run loop event source to the program's run loop
69 notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
70 runLoopSource = IONotificationPortGetRunLoopSource(notificationPort);
71 CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
73 memset(notificationIterators, 0, sizeof(notificationIterators));
75 //* loop through all supported vendors
76 for (i = 0; i < vendorIdCount; i++) {
77 //* Create our matching dictionary to find the Android device's
79 //* IOServiceAddMatchingNotification consumes the reference, so we do
80 //* not need to release this
81 matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
84 DBG("ERR: Couldn't create USB matching dictionary.\n");
88 //* Match based on vendor id, interface subclass and protocol
89 vendor = vendorIds[i];
90 if_subclass = SDB_SUBCLASS;
91 if_protocol = SDB_PROTOCOL;
92 CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID),
93 CFNumberCreate(kCFAllocatorDefault,
94 kCFNumberSInt32Type, &vendor));
95 CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceSubClass),
96 CFNumberCreate(kCFAllocatorDefault,
97 kCFNumberSInt32Type, &if_subclass));
98 CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceProtocol),
99 CFNumberCreate(kCFAllocatorDefault,
100 kCFNumberSInt32Type, &if_protocol));
101 IOServiceAddMatchingNotification(
103 kIOFirstMatchNotification,
105 AndroidInterfaceAdded,
107 ¬ificationIterators[i]);
109 //* Iterate over set of matching interfaces to access already-present
110 //* devices and to arm the notification
111 AndroidInterfaceAdded(NULL, notificationIterators[i]);
118 AndroidInterfaceAdded(void *refCon, io_iterator_t iterator)
121 io_service_t usbDevice;
122 io_service_t usbInterface;
123 IOCFPlugInInterface **plugInInterface = NULL;
124 IOUSBInterfaceInterface220 **iface = NULL;
125 IOUSBDeviceInterface197 **dev = NULL;
133 while ((usbInterface = IOIteratorNext(iterator))) {
134 //* Create an intermediate interface plugin
135 kr = IOCreatePlugInInterfaceForService(usbInterface,
136 kIOUSBInterfaceUserClientTypeID,
137 kIOCFPlugInInterfaceID,
138 &plugInInterface, &score);
139 IOObjectRelease(usbInterface);
140 if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
141 DBG("ERR: Unable to create an interface plug-in (%08x)\n", kr);
145 //* This gets us the interface object
146 result = (*plugInInterface)->QueryInterface(plugInInterface,
147 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID)
149 //* We only needed the plugin to get the interface, so discard it
150 (*plugInInterface)->Release(plugInInterface);
151 if (result || !iface) {
152 DBG("ERR: Couldn't query the interface (%08x)\n", (int) result);
156 //* this gets us an ioservice, with which we will find the actual
157 //* device; after getting a plugin, and querying the interface, of
160 kr = (*iface)->GetDevice(iface, &usbDevice);
161 if (kIOReturnSuccess != kr || !usbDevice) {
162 DBG("ERR: Couldn't grab device from interface (%08x)\n", kr);
166 plugInInterface = NULL;
168 //* create an intermediate device plugin
169 kr = IOCreatePlugInInterfaceForService(usbDevice,
170 kIOUSBDeviceUserClientTypeID,
171 kIOCFPlugInInterfaceID,
172 &plugInInterface, &score);
173 //* only needed this to find the plugin
174 (void)IOObjectRelease(usbDevice);
175 if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
176 DBG("ERR: Unable to create a device plug-in (%08x)\n", kr);
180 result = (*plugInInterface)->QueryInterface(plugInInterface,
181 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID) &dev);
182 //* only needed this to query the plugin
183 (*plugInInterface)->Release(plugInInterface);
184 if (result || !dev) {
185 DBG("ERR: Couldn't create a device interface (%08x)\n",
190 //* Now after all that, we actually have a ref to the device and
191 //* the interface that matched our criteria
193 kr = (*dev)->GetDeviceVendor(dev, &vendor);
194 kr = (*dev)->GetDeviceProduct(dev, &product);
195 kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
197 if (serialIndex > 0) {
200 UInt16 languages[128];
202 memset(languages, 0, sizeof(languages));
205 USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
206 req.bRequest = kUSBRqGetDescriptor;
207 req.wValue = (kUSBStringDesc << 8) | 0;
209 req.pData = languages;
210 req.wLength = sizeof(languages);
211 kr = (*dev)->DeviceRequest(dev, &req);
213 if (kr == kIOReturnSuccess && req.wLenDone > 0) {
215 int langCount = (req.wLenDone - 2) / 2, lang;
217 for (lang = 1; lang <= langCount; lang++) {
219 memset(buffer, 0, sizeof(buffer));
220 memset(&req, 0, sizeof(req));
223 USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
224 req.bRequest = kUSBRqGetDescriptor;
225 req.wValue = (kUSBStringDesc << 8) | serialIndex;
226 req.wIndex = languages[lang];
228 req.wLength = sizeof(buffer);
229 kr = (*dev)->DeviceRequest(dev, &req);
231 if (kr == kIOReturnSuccess && req.wLenDone > 0) {
234 // skip first word, and copy the rest to the serial string,
235 // changing shorts to bytes.
236 count = (req.wLenDone - 1) / 2;
237 for (i = 0; i < count; i++)
238 serial[i] = buffer[i + 1];
245 (*dev)->Release(dev);
247 DBG("INFO: Found vid=%04x pid=%04x serial=%s\n", vendor, product,
250 usb_handle* handle = CheckInterface((IOUSBInterfaceInterface**)iface,
252 if (handle == NULL) {
253 DBG("ERR: Could not find device interface: %08x\n", kr);
254 (*iface)->Release(iface);
258 DBG("AndroidDeviceAdded calling register_usb_transport\n");
259 register_usb_transport(handle, (serial[0] ? serial : NULL), 1);
261 // Register for an interest notification of this device being removed.
262 // Pass the reference to our private data as the refCon for the
264 kr = IOServiceAddInterestNotification(notificationPort,
267 AndroidInterfaceNotify,
269 &handle->usbNotification);
271 if (kIOReturnSuccess != kr) {
272 DBG("ERR: Unable to create interest notification (%08x)\n", kr);
278 AndroidInterfaceNotify(void *refCon, io_service_t service, natural_t messageType, void *messageArgument)
280 usb_handle *handle = (usb_handle *)refCon;
282 if (messageType == kIOMessageServiceIsTerminated) {
284 DBG("ERR: NULL handle\n");
287 DBG("AndroidInterfaceNotify\n");
288 IOObjectRelease(handle->usbNotification);
293 //* TODO: simplify this further since we only register to get SDB interface
294 //* subclass+protocol events
296 CheckInterface(IOUSBInterfaceInterface **interface, UInt16 vendor, UInt16 product)
298 usb_handle* handle = NULL;
300 UInt8 interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
304 //* Now open the interface. This will cause the pipes associated with
305 //* the endpoints in the interface descriptor to be instantiated
306 kr = (*interface)->USBInterfaceOpen(interface);
307 if (kr != kIOReturnSuccess) {
308 DBG("ERR: Could not open interface: (%08x)\n", kr);
312 //* Get the number of endpoints associated with this interface
313 kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
314 if (kr != kIOReturnSuccess) {
315 DBG("ERR: Unable to get number of endpoints: (%08x)\n", kr);
319 //* Get interface class, subclass and protocol
320 if ((*interface)->GetInterfaceClass(interface, &interfaceClass) != kIOReturnSuccess ||
321 (*interface)->GetInterfaceSubClass(interface, &interfaceSubClass) != kIOReturnSuccess ||
322 (*interface)->GetInterfaceProtocol(interface, &interfaceProtocol) != kIOReturnSuccess) {
323 DBG("ERR: Unable to get interface class, subclass and protocol\n");
324 goto err_get_interface_class;
327 //* check to make sure interface class, subclass and protocol match SDB
328 //* avoid opening mass storage endpoints
329 if (!is_sdb_interface(vendor, product, interfaceClass,
330 interfaceSubClass, interfaceProtocol))
331 goto err_bad_sdb_interface;
333 handle = calloc(1, sizeof(usb_handle));
335 //* Iterate over the endpoints for this interface and find the first
336 //* bulk in/out pipes available. These will be our read/write pipes.
337 for (endpoint = 0; endpoint <= interfaceNumEndpoints; endpoint++) {
339 UInt16 maxPacketSize;
344 kr = (*interface)->GetPipeProperties(interface, endpoint, &direction,
345 &number, &transferType, &maxPacketSize, &interval);
347 if (kIOReturnSuccess == kr) {
348 if (kUSBBulk != transferType)
351 if (kUSBIn == direction)
352 handle->bulkIn = endpoint;
354 if (kUSBOut == direction)
355 handle->bulkOut = endpoint;
357 handle->zero_mask = maxPacketSize - 1;
359 DBG("ERR: FindDeviceInterface - could not get pipe properties\n");
360 goto err_get_pipe_props;
364 handle->interface = interface;
369 err_bad_sdb_interface:
370 err_get_interface_class:
372 (*interface)->USBInterfaceClose(interface);
377 void* RunLoopThread(void* unused)
383 currentRunLoop = CFRunLoopGetCurrent();
385 // Signal the parent that we are running
386 sdb_mutex_lock(&start_lock);
387 sdb_cond_signal(&start_cond);
388 sdb_mutex_unlock(&start_lock);
393 for (i = 0; i < vendorIdCount; i++) {
394 IOObjectRelease(notificationIterators[i]);
396 IONotificationPortDestroy(notificationPort);
398 DBG("RunLoopThread done\n");
403 static int initialized = 0;
410 notificationIterators = (io_iterator_t*)malloc(
411 vendorIdCount * sizeof(io_iterator_t));
413 sdb_mutex_init(&start_lock, NULL);
414 sdb_cond_init(&start_cond, NULL);
416 if(sdb_thread_create(&tid, RunLoopThread, NULL))
417 fatal_errno("cannot create input thread");
419 // Wait for initialization to finish
420 sdb_mutex_lock(&start_lock);
421 sdb_cond_wait(&start_cond, &start_lock);
422 sdb_mutex_unlock(&start_lock);
424 sdb_mutex_destroy(&start_lock);
425 sdb_cond_destroy(&start_cond);
433 DBG("usb_cleanup\n");
436 CFRunLoopStop(currentRunLoop);
438 if (notificationIterators != NULL) {
439 free(notificationIterators);
440 notificationIterators = NULL;
444 int usb_write(usb_handle *handle, const void *buf, int len)
454 if (NULL == handle->interface) {
455 DBG("ERR: usb_write interface was null\n");
459 if (0 == handle->bulkOut) {
460 DBG("ERR: bulkOut endpoint not assigned\n");
465 (*handle->interface)->WritePipe(
466 handle->interface, handle->bulkOut, (void *)buf, len);
468 if ((result == 0) && (handle->zero_mask)) {
469 /* we need 0-markers and our transfer */
470 if(!(len & handle->zero_mask)) {
472 (*handle->interface)->WritePipe(
473 handle->interface, handle->bulkOut, (void *)buf, 0);
480 DBG("ERR: usb_write failed with status %d\n", result);
484 int usb_read(usb_handle *handle, void *buf, int len)
487 UInt32 numBytes = len;
497 if (NULL == handle->interface) {
498 DBG("ERR: usb_read interface was null\n");
502 if (0 == handle->bulkIn) {
503 DBG("ERR: bulkIn endpoint not assigned\n");
508 (*handle->interface)->ReadPipe(handle->interface,
509 handle->bulkIn, buf, &numBytes);
514 DBG("ERR: usb_read failed with status %d\n", result);
520 int usb_close(usb_handle *handle)
525 void usb_kick(usb_handle *handle)
527 /* release the interface */
531 if (handle->interface)
533 (*handle->interface)->USBInterfaceClose(handle->interface);
534 (*handle->interface)->Release(handle->interface);
535 handle->interface = 0;