blob: 2ee2aae5da29e0223fefd2df71113b1438cc8404 [file] [log] [blame]
The Android Open Source Project9ca14dc2009-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
Yabin Cui19bec5b2015-09-22 15:52:57 -070017#define TRACE_TAG USB
Dan Albertdb6fe642015-03-19 15:21:08 -070018
19#include "sysdeps.h"
20
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080021#include <CoreFoundation/CoreFoundation.h>
22
23#include <IOKit/IOKitLib.h>
24#include <IOKit/IOCFPlugIn.h>
25#include <IOKit/usb/IOUSBLib.h>
26#include <IOKit/IOMessage.h>
27#include <mach/mach_port.h>
28
Dan Albert25896062015-04-16 19:20:40 -070029#include <inttypes.h>
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080030#include <stdio.h>
31
Yabin Cui234a02a2016-03-25 13:55:07 -070032#include <atomic>
33#include <memory>
34#include <mutex>
35#include <vector>
36
Elliott Hughesf55ead92015-12-04 22:00:26 -080037#include <android-base/logging.h>
38#include <android-base/stringprintf.h>
Siva Velusamy878e36b2015-08-18 17:53:16 -070039
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080040#include "adb.h"
Dan Albertbd3d4482015-02-25 10:26:17 -080041#include "transport.h"
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080042
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080043struct usb_handle
44{
Siva Velusamy3ce46072015-08-13 08:48:06 -070045 UInt8 bulkIn;
46 UInt8 bulkOut;
47 IOUSBInterfaceInterface190** interface;
Siva Velusamy3ce46072015-08-13 08:48:06 -070048 unsigned int zero_mask;
Yabin Cui234a02a2016-03-25 13:55:07 -070049
50 // For garbage collecting disconnected devices.
51 bool mark;
52 std::string devpath;
53 std::atomic<bool> dead;
54
55 usb_handle() : bulkIn(0), bulkOut(0), interface(nullptr),
56 zero_mask(0), mark(false), dead(false) {
57 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080058};
59
Yabin Cui234a02a2016-03-25 13:55:07 -070060static std::atomic<bool> usb_inited_flag;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080061
Yabin Cui234a02a2016-03-25 13:55:07 -070062static auto& g_usb_handles_mutex = *new std::mutex();
63static auto& g_usb_handles = *new std::vector<std::unique_ptr<usb_handle>>();
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080064
Yabin Cui234a02a2016-03-25 13:55:07 -070065static bool IsKnownDevice(const std::string& devpath) {
66 std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
67 for (auto& usb : g_usb_handles) {
68 if (usb->devpath == devpath) {
69 // Set mark flag to indicate this device is still alive.
70 usb->mark = true;
71 return true;
72 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080073 }
Yabin Cui234a02a2016-03-25 13:55:07 -070074 return false;
75}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -080076
Yabin Cui234a02a2016-03-25 13:55:07 -070077static void usb_kick_locked(usb_handle* handle);
Al Sutton178bae82014-11-21 12:21:12 +000078
Yabin Cui234a02a2016-03-25 13:55:07 -070079static void KickDisconnectedDevices() {
80 std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
81 for (auto& usb : g_usb_handles) {
82 if (!usb->mark) {
83 usb_kick_locked(usb.get());
84 } else {
85 usb->mark = false;
86 }
87 }
88}
Al Sutton178bae82014-11-21 12:21:12 +000089
Yabin Cui234a02a2016-03-25 13:55:07 -070090static void AddDevice(std::unique_ptr<usb_handle> handle) {
91 handle->mark = true;
92 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
93 g_usb_handles.push_back(std::move(handle));
94}
95
96static void AndroidInterfaceAdded(io_iterator_t iterator);
97static std::unique_ptr<usb_handle> CheckInterface(IOUSBInterfaceInterface190 **iface,
98 UInt16 vendor, UInt16 product);
99
100static bool FindUSBDevices() {
101 // Create the matching dictionary to find the Android device's adb interface.
102 CFMutableDictionaryRef matchingDict = IOServiceMatching(kIOUSBInterfaceClassName);
103 if (!matchingDict) {
104 LOG(ERROR) << "couldn't create USB matching dictionary";
105 return false;
106 }
107 // Create an iterator for all I/O Registry objects that match the dictionary.
108 io_iterator_t iter = 0;
109 kern_return_t kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
110 if (kr != KERN_SUCCESS) {
111 LOG(ERROR) << "failed to get matching services";
112 return false;
113 }
114 // Iterate over all matching objects.
115 AndroidInterfaceAdded(iter);
116 IOObjectRelease(iter);
117 return true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800118}
119
120static void
Yabin Cui234a02a2016-03-25 13:55:07 -0700121AndroidInterfaceAdded(io_iterator_t iterator)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800122{
123 kern_return_t kr;
124 io_service_t usbDevice;
Dima Zavin3e824912009-05-08 18:25:58 -0700125 io_service_t usbInterface;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800126 IOCFPlugInInterface **plugInInterface = NULL;
Dima Zavin3e824912009-05-08 18:25:58 -0700127 IOUSBInterfaceInterface220 **iface = NULL;
128 IOUSBDeviceInterface197 **dev = NULL;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800129 HRESULT result;
130 SInt32 score;
Elliott Hughes8dc9c862015-08-25 17:48:12 -0700131 uint32_t locationId;
Dan Albert25896062015-04-16 19:20:40 -0700132 UInt8 if_class, subclass, protocol;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800133 UInt16 vendor;
134 UInt16 product;
135 UInt8 serialIndex;
136 char serial[256];
Yabin Cui234a02a2016-03-25 13:55:07 -0700137 std::string devpath;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800138
Dima Zavin3e824912009-05-08 18:25:58 -0700139 while ((usbInterface = IOIteratorNext(iterator))) {
140 //* Create an intermediate interface plugin
141 kr = IOCreatePlugInInterfaceForService(usbInterface,
142 kIOUSBInterfaceUserClientTypeID,
143 kIOCFPlugInInterfaceID,
144 &plugInInterface, &score);
145 IOObjectRelease(usbInterface);
146 if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700147 LOG(ERROR) << "Unable to create an interface plug-in (" << std::hex << kr << ")";
Dima Zavin3e824912009-05-08 18:25:58 -0700148 continue;
149 }
150
151 //* This gets us the interface object
Dan Albert25896062015-04-16 19:20:40 -0700152 result = (*plugInInterface)->QueryInterface(
153 plugInInterface,
154 CFUUIDGetUUIDBytes(kIOUSBInterfaceInterfaceID), (LPVOID*)&iface);
Dima Zavin3e824912009-05-08 18:25:58 -0700155 //* We only needed the plugin to get the interface, so discard it
156 (*plugInInterface)->Release(plugInInterface);
157 if (result || !iface) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700158 LOG(ERROR) << "Couldn't query the interface (" << std::hex << result << ")";
Dima Zavin3e824912009-05-08 18:25:58 -0700159 continue;
160 }
161
Dan Albert25896062015-04-16 19:20:40 -0700162 kr = (*iface)->GetInterfaceClass(iface, &if_class);
Al Sutton178bae82014-11-21 12:21:12 +0000163 kr = (*iface)->GetInterfaceSubClass(iface, &subclass);
164 kr = (*iface)->GetInterfaceProtocol(iface, &protocol);
Dan Albert25896062015-04-16 19:20:40 -0700165 if(if_class != ADB_CLASS || subclass != ADB_SUBCLASS || protocol != ADB_PROTOCOL) {
Al Sutton178bae82014-11-21 12:21:12 +0000166 // Ignore non-ADB devices.
Siva Velusamy878e36b2015-08-18 17:53:16 -0700167 LOG(DEBUG) << "Ignoring interface with incorrect class/subclass/protocol - " << if_class
168 << ", " << subclass << ", " << protocol;
Al Sutton178bae82014-11-21 12:21:12 +0000169 (*iface)->Release(iface);
170 continue;
171 }
172
Dima Zavin3e824912009-05-08 18:25:58 -0700173 //* this gets us an ioservice, with which we will find the actual
174 //* device; after getting a plugin, and querying the interface, of
175 //* course.
176 //* Gotta love OS X
177 kr = (*iface)->GetDevice(iface, &usbDevice);
178 if (kIOReturnSuccess != kr || !usbDevice) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700179 LOG(ERROR) << "Couldn't grab device from interface (" << std::hex << kr << ")";
Josh Gao37df9e72016-09-27 12:35:55 -0700180 (*iface)->Release(iface);
Dima Zavin3e824912009-05-08 18:25:58 -0700181 continue;
182 }
183
184 plugInInterface = NULL;
185 score = 0;
186 //* create an intermediate device plugin
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800187 kr = IOCreatePlugInInterfaceForService(usbDevice,
188 kIOUSBDeviceUserClientTypeID,
189 kIOCFPlugInInterfaceID,
190 &plugInInterface, &score);
Dima Zavin3e824912009-05-08 18:25:58 -0700191 //* only needed this to find the plugin
192 (void)IOObjectRelease(usbDevice);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800193 if ((kIOReturnSuccess != kr) || (!plugInInterface)) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700194 LOG(ERROR) << "Unable to create a device plug-in (" << std::hex << kr << ")";
Josh Gao37df9e72016-09-27 12:35:55 -0700195 (*iface)->Release(iface);
Dima Zavin3e824912009-05-08 18:25:58 -0700196 continue;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800197 }
198
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800199 result = (*plugInInterface)->QueryInterface(plugInInterface,
Dan Albert25896062015-04-16 19:20:40 -0700200 CFUUIDGetUUIDBytes(kIOUSBDeviceInterfaceID), (LPVOID*)&dev);
Dima Zavin3e824912009-05-08 18:25:58 -0700201 //* only needed this to query the plugin
202 (*plugInInterface)->Release(plugInInterface);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800203 if (result || !dev) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700204 LOG(ERROR) << "Couldn't create a device interface (" << std::hex << result << ")";
Josh Gao37df9e72016-09-27 12:35:55 -0700205 (*iface)->Release(iface);
Dima Zavin3e824912009-05-08 18:25:58 -0700206 continue;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800207 }
208
Dima Zavin3e824912009-05-08 18:25:58 -0700209 //* Now after all that, we actually have a ref to the device and
210 //* the interface that matched our criteria
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800211 kr = (*dev)->GetDeviceVendor(dev, &vendor);
212 kr = (*dev)->GetDeviceProduct(dev, &product);
Scott Anderson6dfaf4b2012-04-20 11:21:14 -0700213 kr = (*dev)->GetLocationID(dev, &locationId);
Yabin Cui234a02a2016-03-25 13:55:07 -0700214 if (kr == KERN_SUCCESS) {
215 devpath = android::base::StringPrintf("usb:%" PRIu32 "X", locationId);
216 if (IsKnownDevice(devpath)) {
Josh Gao37df9e72016-09-27 12:35:55 -0700217 (*dev)->Release(dev);
218 (*iface)->Release(iface);
Yabin Cui234a02a2016-03-25 13:55:07 -0700219 continue;
220 }
Scott Anderson6dfaf4b2012-04-20 11:21:14 -0700221 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800222 kr = (*dev)->USBGetSerialNumberStringIndex(dev, &serialIndex);
223
Siva Velusamy878e36b2015-08-18 17:53:16 -0700224 if (serialIndex > 0) {
225 IOUSBDevRequest req;
226 UInt16 buffer[256];
227 UInt16 languages[128];
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800228
Siva Velusamy878e36b2015-08-18 17:53:16 -0700229 memset(languages, 0, sizeof(languages));
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800230
Siva Velusamy878e36b2015-08-18 17:53:16 -0700231 req.bmRequestType =
232 USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
233 req.bRequest = kUSBRqGetDescriptor;
234 req.wValue = (kUSBStringDesc << 8) | 0;
235 req.wIndex = 0;
236 req.pData = languages;
237 req.wLength = sizeof(languages);
238 kr = (*dev)->DeviceRequest(dev, &req);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800239
Siva Velusamy878e36b2015-08-18 17:53:16 -0700240 if (kr == kIOReturnSuccess && req.wLenDone > 0) {
Guang Zhu84b5bd22009-08-06 17:21:52 -0700241
Siva Velusamy878e36b2015-08-18 17:53:16 -0700242 int langCount = (req.wLenDone - 2) / 2, lang;
Guang Zhu84b5bd22009-08-06 17:21:52 -0700243
Siva Velusamy878e36b2015-08-18 17:53:16 -0700244 for (lang = 1; lang <= langCount; lang++) {
Guang Zhu84b5bd22009-08-06 17:21:52 -0700245
Siva Velusamy878e36b2015-08-18 17:53:16 -0700246 memset(buffer, 0, sizeof(buffer));
247 memset(&req, 0, sizeof(req));
Guang Zhu84b5bd22009-08-06 17:21:52 -0700248
Siva Velusamy878e36b2015-08-18 17:53:16 -0700249 req.bmRequestType =
250 USBmakebmRequestType(kUSBIn, kUSBStandard, kUSBDevice);
251 req.bRequest = kUSBRqGetDescriptor;
252 req.wValue = (kUSBStringDesc << 8) | serialIndex;
253 req.wIndex = languages[lang];
254 req.pData = buffer;
255 req.wLength = sizeof(buffer);
256 kr = (*dev)->DeviceRequest(dev, &req);
Guang Zhu84b5bd22009-08-06 17:21:52 -0700257
Siva Velusamy878e36b2015-08-18 17:53:16 -0700258 if (kr == kIOReturnSuccess && req.wLenDone > 0) {
259 int i, count;
Guang Zhu84b5bd22009-08-06 17:21:52 -0700260
Siva Velusamy878e36b2015-08-18 17:53:16 -0700261 // skip first word, and copy the rest to the serial string,
262 // changing shorts to bytes.
263 count = (req.wLenDone - 1) / 2;
264 for (i = 0; i < count; i++)
265 serial[i] = buffer[i + 1];
266 serial[i] = 0;
267 break;
268 }
269 }
270 }
271 }
272
Dima Zavin3e824912009-05-08 18:25:58 -0700273 (*dev)->Release(dev);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800274
Yabin Cui234a02a2016-03-25 13:55:07 -0700275 VLOG(USB) << android::base::StringPrintf("Found vid=%04x pid=%04x serial=%s\n",
Siva Velusamy878e36b2015-08-18 17:53:16 -0700276 vendor, product, serial);
Yabin Cui234a02a2016-03-25 13:55:07 -0700277 if (devpath.empty()) {
278 devpath = serial;
279 }
280 if (IsKnownDevice(devpath)) {
281 (*iface)->USBInterfaceClose(iface);
Dima Zavin3e824912009-05-08 18:25:58 -0700282 (*iface)->Release(iface);
283 continue;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800284 }
285
Yabin Cui234a02a2016-03-25 13:55:07 -0700286 std::unique_ptr<usb_handle> handle = CheckInterface((IOUSBInterfaceInterface190**)iface,
287 vendor, product);
288 if (handle == nullptr) {
289 LOG(ERROR) << "Could not find device interface";
290 (*iface)->Release(iface);
291 continue;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800292 }
Yabin Cui234a02a2016-03-25 13:55:07 -0700293 handle->devpath = devpath;
294 usb_handle* handle_p = handle.get();
295 VLOG(USB) << "Add usb device " << serial;
296 AddDevice(std::move(handle));
297 register_usb_transport(handle_p, serial, devpath.c_str(), 1);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800298 }
299}
300
Siva Velusamy3ce46072015-08-13 08:48:06 -0700301// Used to clear both the endpoints before starting.
302// When adb quits, we might clear the host endpoint but not the device.
303// So we make sure both sides are clear before starting up.
304static bool ClearPipeStallBothEnds(IOUSBInterfaceInterface190** interface, UInt8 bulkEp) {
305 IOReturn rc = (*interface)->ClearPipeStallBothEnds(interface, bulkEp);
306 if (rc != kIOReturnSuccess) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700307 LOG(ERROR) << "Could not clear pipe stall both ends: " << std::hex << rc;
Siva Velusamy3ce46072015-08-13 08:48:06 -0700308 return false;
309 }
310 return true;
311}
312
Dima Zavin3e824912009-05-08 18:25:58 -0700313//* TODO: simplify this further since we only register to get ADB interface
314//* subclass+protocol events
Yabin Cui234a02a2016-03-25 13:55:07 -0700315static std::unique_ptr<usb_handle>
Siva Velusamy3ce46072015-08-13 08:48:06 -0700316CheckInterface(IOUSBInterfaceInterface190 **interface, UInt16 vendor, UInt16 product)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800317{
Yabin Cui234a02a2016-03-25 13:55:07 -0700318 std::unique_ptr<usb_handle> handle;
Elliott Hughes6d6cb542015-08-13 15:01:18 -0700319 IOReturn kr;
320 UInt8 interfaceNumEndpoints, interfaceClass, interfaceSubClass, interfaceProtocol;
321 UInt8 endpoint;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800322
Dima Zavin3e824912009-05-08 18:25:58 -0700323 //* Now open the interface. This will cause the pipes associated with
324 //* the endpoints in the interface descriptor to be instantiated
325 kr = (*interface)->USBInterfaceOpen(interface);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800326 if (kr != kIOReturnSuccess) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700327 LOG(ERROR) << "Could not open interface: " << std::hex << kr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800328 return NULL;
329 }
330
Dima Zavin3e824912009-05-08 18:25:58 -0700331 //* Get the number of endpoints associated with this interface
332 kr = (*interface)->GetNumEndpoints(interface, &interfaceNumEndpoints);
333 if (kr != kIOReturnSuccess) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700334 LOG(ERROR) << "Unable to get number of endpoints: " << std::hex << kr;
Dima Zavin3e824912009-05-08 18:25:58 -0700335 goto err_get_num_ep;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800336 }
337
Dima Zavin3e824912009-05-08 18:25:58 -0700338 //* Get interface class, subclass and protocol
339 if ((*interface)->GetInterfaceClass(interface, &interfaceClass) != kIOReturnSuccess ||
340 (*interface)->GetInterfaceSubClass(interface, &interfaceSubClass) != kIOReturnSuccess ||
341 (*interface)->GetInterfaceProtocol(interface, &interfaceProtocol) != kIOReturnSuccess) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700342 LOG(ERROR) << "Unable to get interface class, subclass and protocol";
Dima Zavin3e824912009-05-08 18:25:58 -0700343 goto err_get_interface_class;
344 }
345
346 //* check to make sure interface class, subclass and protocol match ADB
347 //* avoid opening mass storage endpoints
Josh Gao08dda212016-09-26 21:18:58 -0700348 if (!is_adb_interface(interfaceClass, interfaceSubClass, interfaceProtocol)) {
Dima Zavin3e824912009-05-08 18:25:58 -0700349 goto err_bad_adb_interface;
Siva Velusamy3ce46072015-08-13 08:48:06 -0700350 }
Dima Zavin3e824912009-05-08 18:25:58 -0700351
Yabin Cui234a02a2016-03-25 13:55:07 -0700352 handle.reset(new usb_handle);
353 if (handle == nullptr) {
354 goto err_bad_adb_interface;
355 }
Dima Zavin3e824912009-05-08 18:25:58 -0700356
357 //* Iterate over the endpoints for this interface and find the first
358 //* bulk in/out pipes available. These will be our read/write pipes.
Elliott Hughes6d6cb542015-08-13 15:01:18 -0700359 for (endpoint = 1; endpoint <= interfaceNumEndpoints; endpoint++) {
Dima Zavin3e824912009-05-08 18:25:58 -0700360 UInt8 transferType;
361 UInt16 maxPacketSize;
362 UInt8 interval;
363 UInt8 number;
364 UInt8 direction;
365
366 kr = (*interface)->GetPipeProperties(interface, endpoint, &direction,
367 &number, &transferType, &maxPacketSize, &interval);
Siva Velusamy3ce46072015-08-13 08:48:06 -0700368 if (kr != kIOReturnSuccess) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700369 LOG(ERROR) << "FindDeviceInterface - could not get pipe properties: "
370 << std::hex << kr;
Dima Zavin3e824912009-05-08 18:25:58 -0700371 goto err_get_pipe_props;
372 }
Siva Velusamy3ce46072015-08-13 08:48:06 -0700373
374 if (kUSBBulk != transferType) continue;
375
376 if (kUSBIn == direction) {
377 handle->bulkIn = endpoint;
378 if (!ClearPipeStallBothEnds(interface, handle->bulkIn)) goto err_get_pipe_props;
379 }
380
381 if (kUSBOut == direction) {
382 handle->bulkOut = endpoint;
383 if (!ClearPipeStallBothEnds(interface, handle->bulkOut)) goto err_get_pipe_props;
384 }
385
386 handle->zero_mask = maxPacketSize - 1;
Dima Zavin3e824912009-05-08 18:25:58 -0700387 }
388
389 handle->interface = interface;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800390 return handle;
Dima Zavin3e824912009-05-08 18:25:58 -0700391
392err_get_pipe_props:
Dima Zavin3e824912009-05-08 18:25:58 -0700393err_bad_adb_interface:
394err_get_interface_class:
395err_get_num_ep:
396 (*interface)->USBInterfaceClose(interface);
Yabin Cui234a02a2016-03-25 13:55:07 -0700397 return nullptr;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800398}
399
Yabin Cui234a02a2016-03-25 13:55:07 -0700400std::mutex& operate_device_lock = *new std::mutex();
401
Josh Gao7d405252016-02-12 14:31:15 -0800402static void RunLoopThread(void* unused) {
Siva Velusamy2669cf92015-08-28 16:37:29 -0700403 adb_thread_setname("RunLoop");
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800404
Yabin Cui234a02a2016-03-25 13:55:07 -0700405 VLOG(USB) << "RunLoopThread started";
406 while (true) {
407 {
408 std::lock_guard<std::mutex> lock_guard(operate_device_lock);
409 FindUSBDevices();
410 KickDisconnectedDevices();
411 }
412 // Signal the parent that we are running
413 usb_inited_flag = true;
414 adb_sleep_ms(1000);
415 }
416 VLOG(USB) << "RunLoopThread done";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800417}
418
Dan Albert53a37442015-05-08 16:13:53 -0700419static void usb_cleanup() {
Yabin Cui234a02a2016-03-25 13:55:07 -0700420 VLOG(USB) << "usb_cleanup";
421 // Wait until usb operations in RunLoopThread finish, and prevent further operations.
422 operate_device_lock.lock();
Dan Albert53a37442015-05-08 16:13:53 -0700423 close_usb_devices();
Dan Albert53a37442015-05-08 16:13:53 -0700424}
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800425
Elliott Hughesf2517142015-05-05 13:41:21 -0700426void usb_init() {
Dan Albert53a37442015-05-08 16:13:53 -0700427 static bool initialized = false;
428 if (!initialized) {
429 atexit(usb_cleanup);
430
Yabin Cui234a02a2016-03-25 13:55:07 -0700431 usb_inited_flag = false;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800432
Elliott Hughesf2517142015-05-05 13:41:21 -0700433 if (!adb_thread_create(RunLoopThread, nullptr)) {
Yabin Cui4e222292015-08-31 11:50:24 -0700434 fatal_errno("cannot create RunLoop thread");
Elliott Hughesf2517142015-05-05 13:41:21 -0700435 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800436
437 // Wait for initialization to finish
Yabin Cui234a02a2016-03-25 13:55:07 -0700438 while (!usb_inited_flag) {
439 adb_sleep_ms(100);
440 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800441
Dan Albert53a37442015-05-08 16:13:53 -0700442 initialized = true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800443 }
444}
445
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800446int usb_write(usb_handle *handle, const void *buf, int len)
447{
448 IOReturn result;
449
450 if (!len)
451 return 0;
452
Yabin Cui234a02a2016-03-25 13:55:07 -0700453 if (!handle || handle->dead)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800454 return -1;
455
456 if (NULL == handle->interface) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700457 LOG(ERROR) << "usb_write interface was null";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800458 return -1;
459 }
460
461 if (0 == handle->bulkOut) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700462 LOG(ERROR) << "bulkOut endpoint not assigned";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800463 return -1;
464 }
465
466 result =
Siva Velusamy878e36b2015-08-18 17:53:16 -0700467 (*handle->interface)->WritePipe(handle->interface, handle->bulkOut, (void *)buf, len);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800468
469 if ((result == 0) && (handle->zero_mask)) {
470 /* we need 0-markers and our transfer */
471 if(!(len & handle->zero_mask)) {
472 result =
473 (*handle->interface)->WritePipe(
474 handle->interface, handle->bulkOut, (void *)buf, 0);
475 }
476 }
477
478 if (0 == result)
479 return 0;
480
Siva Velusamy878e36b2015-08-18 17:53:16 -0700481 LOG(ERROR) << "usb_write failed with status: " << std::hex << result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800482 return -1;
483}
484
485int usb_read(usb_handle *handle, void *buf, int len)
486{
487 IOReturn result;
488 UInt32 numBytes = len;
489
490 if (!len) {
491 return 0;
492 }
493
Yabin Cui234a02a2016-03-25 13:55:07 -0700494 if (!handle || handle->dead) {
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800495 return -1;
496 }
497
498 if (NULL == handle->interface) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700499 LOG(ERROR) << "usb_read interface was null";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800500 return -1;
501 }
502
503 if (0 == handle->bulkIn) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700504 LOG(ERROR) << "bulkIn endpoint not assigned";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800505 return -1;
506 }
507
Esteban de la Canal647231a2014-09-11 11:02:17 -0700508 result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800509
Esteban de la Canal647231a2014-09-11 11:02:17 -0700510 if (kIOUSBPipeStalled == result) {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700511 LOG(ERROR) << "Pipe stalled, clearing stall.\n";
Esteban de la Canal647231a2014-09-11 11:02:17 -0700512 (*handle->interface)->ClearPipeStall(handle->interface, handle->bulkIn);
513 result = (*handle->interface)->ReadPipe(handle->interface, handle->bulkIn, buf, &numBytes);
514 }
515
516 if (kIOReturnSuccess == result)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800517 return 0;
518 else {
Siva Velusamy878e36b2015-08-18 17:53:16 -0700519 LOG(ERROR) << "usb_read failed with status: " << std::hex << result;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800520 }
521
522 return -1;
523}
524
525int usb_close(usb_handle *handle)
526{
Yabin Cui234a02a2016-03-25 13:55:07 -0700527 std::lock_guard<std::mutex> lock(g_usb_handles_mutex);
528 for (auto it = g_usb_handles.begin(); it != g_usb_handles.end(); ++it) {
529 if ((*it).get() == handle) {
530 g_usb_handles.erase(it);
531 break;
532 }
533 }
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800534 return 0;
535}
536
Yabin Cui234a02a2016-03-25 13:55:07 -0700537static void usb_kick_locked(usb_handle *handle)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800538{
Siva Velusamy878e36b2015-08-18 17:53:16 -0700539 LOG(INFO) << "Kicking handle";
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800540 /* release the interface */
Dima Zavin3e824912009-05-08 18:25:58 -0700541 if (!handle)
542 return;
543
Yabin Cui234a02a2016-03-25 13:55:07 -0700544 if (!handle->dead)
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800545 {
Yabin Cui234a02a2016-03-25 13:55:07 -0700546 handle->dead = true;
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800547 (*handle->interface)->USBInterfaceClose(handle->interface);
548 (*handle->interface)->Release(handle->interface);
The Android Open Source Project9ca14dc2009-03-03 19:32:55 -0800549 }
550}
Yabin Cui234a02a2016-03-25 13:55:07 -0700551
552void usb_kick(usb_handle *handle) {
553 // Use the lock to avoid multiple thread kicking the device at the same time.
554 std::lock_guard<std::mutex> lock_guard(g_usb_handles_mutex);
555 usb_kick_locked(handle);
556}