1/*
2 * Copyright (C) 2010 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#define LOG_TAG "UsbHostManagerJNI"
18#include "utils/Log.h"
19
20#include "jni.h"
21#include "JNIHelp.h"
22#include "android_runtime/AndroidRuntime.h"
23#include "utils/Vector.h"
24
25#include <usbhost/usbhost.h>
26
27#include <stdio.h>
28#include <asm/byteorder.h>
29#include <sys/types.h>
30#include <sys/stat.h>
31#include <fcntl.h>
32#include <sys/ioctl.h>
33
34namespace android
35{
36
37static struct parcel_file_descriptor_offsets_t
38{
39    jclass mClass;
40    jmethodID mConstructor;
41} gParcelFileDescriptorOffsets;
42
43static jmethodID method_usbDeviceAdded;
44static jmethodID method_usbDeviceRemoved;
45
46static void checkAndClearExceptionFromCallback(JNIEnv* env, const char* methodName) {
47    if (env->ExceptionCheck()) {
48        ALOGE("An exception was thrown by callback '%s'.", methodName);
49        LOGE_EX(env);
50        env->ExceptionClear();
51    }
52}
53
54static int usb_device_added(const char *devname, void* client_data) {
55    struct usb_descriptor_header* desc;
56    struct usb_descriptor_iter iter;
57
58    struct usb_device *device = usb_device_open(devname);
59    if (!device) {
60        ALOGE("usb_device_open failed\n");
61        return 0;
62    }
63
64    JNIEnv* env = AndroidRuntime::getJNIEnv();
65    jobject thiz = (jobject)client_data;
66    Vector<int> interfaceValues;
67    Vector<int> endpointValues;
68    const usb_device_descriptor* deviceDesc = usb_device_get_device_descriptor(device);
69
70    uint16_t vendorId = usb_device_get_vendor_id(device);
71    uint16_t productId = usb_device_get_product_id(device);
72    uint8_t deviceClass = deviceDesc->bDeviceClass;
73    uint8_t deviceSubClass = deviceDesc->bDeviceSubClass;
74    uint8_t protocol = deviceDesc->bDeviceProtocol;
75
76    usb_descriptor_iter_init(device, &iter);
77
78    while ((desc = usb_descriptor_iter_next(&iter)) != NULL) {
79        if (desc->bDescriptorType == USB_DT_INTERFACE) {
80            struct usb_interface_descriptor *interface = (struct usb_interface_descriptor *)desc;
81
82            // push class, subclass, protocol and number of endpoints into interfaceValues vector
83            interfaceValues.add(interface->bInterfaceNumber);
84            interfaceValues.add(interface->bInterfaceClass);
85            interfaceValues.add(interface->bInterfaceSubClass);
86            interfaceValues.add(interface->bInterfaceProtocol);
87            interfaceValues.add(interface->bNumEndpoints);
88        } else if (desc->bDescriptorType == USB_DT_ENDPOINT) {
89            struct usb_endpoint_descriptor *endpoint = (struct usb_endpoint_descriptor *)desc;
90
91            // push address, attributes, max packet size and interval into endpointValues vector
92            endpointValues.add(endpoint->bEndpointAddress);
93            endpointValues.add(endpoint->bmAttributes);
94            endpointValues.add(__le16_to_cpu(endpoint->wMaxPacketSize));
95            endpointValues.add(endpoint->bInterval);
96        }
97    }
98
99    usb_device_close(device);
100
101    // handle generic device notification
102    int length = interfaceValues.size();
103    jintArray interfaceArray = env->NewIntArray(length);
104    env->SetIntArrayRegion(interfaceArray, 0, length, interfaceValues.array());
105
106    length = endpointValues.size();
107    jintArray endpointArray = env->NewIntArray(length);
108    env->SetIntArrayRegion(endpointArray, 0, length, endpointValues.array());
109
110    jstring deviceName = env->NewStringUTF(devname);
111    env->CallVoidMethod(thiz, method_usbDeviceAdded,
112            deviceName, vendorId, productId, deviceClass,
113            deviceSubClass, protocol, interfaceArray, endpointArray);
114
115    env->DeleteLocalRef(interfaceArray);
116    env->DeleteLocalRef(endpointArray);
117    env->DeleteLocalRef(deviceName);
118    checkAndClearExceptionFromCallback(env, __FUNCTION__);
119
120    return 0;
121}
122
123static int usb_device_removed(const char *devname, void* client_data) {
124    JNIEnv* env = AndroidRuntime::getJNIEnv();
125    jobject thiz = (jobject)client_data;
126
127    jstring deviceName = env->NewStringUTF(devname);
128    env->CallVoidMethod(thiz, method_usbDeviceRemoved, deviceName);
129    env->DeleteLocalRef(deviceName);
130    checkAndClearExceptionFromCallback(env, __FUNCTION__);
131    return 0;
132}
133
134static void android_server_UsbHostManager_monitorUsbHostBus(JNIEnv *env, jobject thiz)
135{
136    struct usb_host_context* context = usb_host_init();
137    if (!context) {
138        ALOGE("usb_host_init failed");
139        return;
140    }
141    // this will never return so it is safe to pass thiz directly
142    usb_host_run(context, usb_device_added, usb_device_removed, NULL, (void *)thiz);
143}
144
145static jobject android_server_UsbHostManager_openDevice(JNIEnv *env, jobject thiz, jstring deviceName)
146{
147    const char *deviceNameStr = env->GetStringUTFChars(deviceName, NULL);
148    struct usb_device* device = usb_device_open(deviceNameStr);
149    env->ReleaseStringUTFChars(deviceName, deviceNameStr);
150
151    if (!device)
152        return NULL;
153
154    int fd = usb_device_get_fd(device);
155    if (fd < 0)
156        return NULL;
157    int newFD = dup(fd);
158    usb_device_close(device);
159
160    jobject fileDescriptor = jniCreateFileDescriptor(env, newFD);
161    if (fileDescriptor == NULL) {
162        return NULL;
163    }
164    return env->NewObject(gParcelFileDescriptorOffsets.mClass,
165        gParcelFileDescriptorOffsets.mConstructor, fileDescriptor);
166}
167
168static JNINativeMethod method_table[] = {
169    { "monitorUsbHostBus", "()V", (void*)android_server_UsbHostManager_monitorUsbHostBus },
170    { "nativeOpenDevice",  "(Ljava/lang/String;)Landroid/os/ParcelFileDescriptor;",
171                                  (void*)android_server_UsbHostManager_openDevice },
172};
173
174int register_android_server_UsbHostManager(JNIEnv *env)
175{
176    jclass clazz = env->FindClass("com/android/server/usb/UsbHostManager");
177    if (clazz == NULL) {
178        ALOGE("Can't find com/android/server/usb/UsbHostManager");
179        return -1;
180    }
181    method_usbDeviceAdded = env->GetMethodID(clazz, "usbDeviceAdded", "(Ljava/lang/String;IIIII[I[I)V");
182    if (method_usbDeviceAdded == NULL) {
183        ALOGE("Can't find usbDeviceAdded");
184        return -1;
185    }
186    method_usbDeviceRemoved = env->GetMethodID(clazz, "usbDeviceRemoved", "(Ljava/lang/String;)V");
187    if (method_usbDeviceRemoved == NULL) {
188        ALOGE("Can't find usbDeviceRemoved");
189        return -1;
190    }
191
192    clazz = env->FindClass("android/os/ParcelFileDescriptor");
193    LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.ParcelFileDescriptor");
194    gParcelFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
195    gParcelFileDescriptorOffsets.mConstructor = env->GetMethodID(clazz, "<init>", "(Ljava/io/FileDescriptor;)V");
196    LOG_FATAL_IF(gParcelFileDescriptorOffsets.mConstructor == NULL,
197                 "Unable to find constructor for android.os.ParcelFileDescriptor");
198
199    return jniRegisterNativeMethods(env, "com/android/server/usb/UsbHostManager",
200            method_table, NELEM(method_table));
201}
202
203};
204