usb_osx.c 17 KB

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