Merge changes from topic "usb_gadget_reset"

* changes:
  Add USB Gadget Hal v1.1 default implementation
  Add USB Gadget V1.1 with hash code
  USB Gadget V1.1 interface
This commit is contained in:
Howard Yen
2020-01-22 20:56:44 +00:00
committed by Android (Google) Code Review
14 changed files with 1165 additions and 1 deletions

View File

@@ -475,7 +475,7 @@
</hal>
<hal format="hidl" optional="true">
<name>android.hardware.usb.gadget</name>
<version>1.0</version>
<version>1.0-1</version>
<interface>
<name>IUsbGadget</name>
<instance>default</instance>

View File

@@ -680,3 +680,4 @@ a2977755bc5f1ef47f04b7f2400632efda6218e1515dba847da487145cfabc4f android.hardwar
##
51d1c8d285e0456da2a3fdfbf4700c6277165d5e83219894d651c8ea0e39aa8b android.hardware.soundtrigger@2.3::types
12d7533ff0754f45bf59ab300799074570a99a676545652c2c23abc73cb4515d android.hardware.soundtrigger@2.3::ISoundTriggerHw
7746fda1fbf9c7c132bae701cc5a161309e4f5e7f3e8065811045975ee86196d android.hardware.usb.gadget@1.1::IUsbGadget

17
usb/gadget/1.1/Android.bp Normal file
View File

@@ -0,0 +1,17 @@
// This file is autogenerated by hidl-gen -Landroidbp.
hidl_interface {
name: "android.hardware.usb.gadget@1.1",
root: "android.hardware",
vndk: {
enabled: true,
},
srcs: [
"IUsbGadget.hal",
],
interfaces: [
"android.hardware.usb.gadget@1.0",
"android.hidl.base@1.0",
],
gen_java: true,
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.hardware.usb.gadget@1.1;
import @1.0::IUsbGadget;
import @1.0::Status;
interface IUsbGadget extends @1.0::IUsbGadget {
/**
* This function is used to reset USB gadget driver.
* Performs USB data connection reset. The connection will disconnect and
* reconnect.
*
* return status indicate success or not.
*/
reset() generates(Status status);
};

View File

@@ -0,0 +1,39 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
cc_binary {
name: "android.hardware.usb.gadget@1.1-service",
defaults: ["hidl_defaults"],
relative_install_path: "hw",
init_rc: ["android.hardware.usb.gadget@1.1-service.rc"],
vintf_fragments: ["android.hardware.usb.gadget@1.1-service.xml"],
vendor: true,
srcs: [
"service.cpp",
"UsbGadget.cpp",
],
shared_libs: [
"android.hardware.usb.gadget@1.0",
"android.hardware.usb.gadget@1.1",
"libbase",
"libcutils",
"libhardware",
"libhidlbase",
"liblog",
"libutils",
],
static_libs: ["libusbconfigfs"],
}

View File

@@ -0,0 +1,229 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "android.hardware.usb.gadget@1.1-service"
#include "UsbGadget.h"
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/inotify.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
namespace android {
namespace hardware {
namespace usb {
namespace gadget {
namespace V1_1 {
namespace implementation {
UsbGadget::UsbGadget() {
if (access(OS_DESC_PATH, R_OK) != 0) {
ALOGE("configfs setup not done yet");
abort();
}
}
void currentFunctionsAppliedCallback(bool functionsApplied, void* payload) {
UsbGadget* gadget = (UsbGadget*)payload;
gadget->mCurrentUsbFunctionsApplied = functionsApplied;
}
Return<void> UsbGadget::getCurrentUsbFunctions(const sp<V1_0::IUsbGadgetCallback>& callback) {
Return<void> ret = callback->getCurrentUsbFunctionsCb(
mCurrentUsbFunctions, mCurrentUsbFunctionsApplied ? Status::FUNCTIONS_APPLIED
: Status::FUNCTIONS_NOT_APPLIED);
if (!ret.isOk()) ALOGE("Call to getCurrentUsbFunctionsCb failed %s", ret.description().c_str());
return Void();
}
V1_0::Status UsbGadget::tearDownGadget() {
if (resetGadget() != V1_0::Status::SUCCESS) return V1_0::Status::ERROR;
if (monitorFfs.isMonitorRunning()) {
monitorFfs.reset();
} else {
ALOGI("mMonitor not running");
}
return V1_0::Status::SUCCESS;
}
Return<Status> UsbGadget::reset() {
if (!WriteStringToFile("none", PULLUP_PATH)) {
ALOGI("Gadget cannot be pulled down");
return Status::ERROR;
}
return Status::SUCCESS;
}
static V1_0::Status validateAndSetVidPid(uint64_t functions) {
V1_0::Status ret = V1_0::Status::SUCCESS;
switch (functions) {
case static_cast<uint64_t>(V1_0::GadgetFunction::MTP):
ret = setVidPid("0x18d1", "0x4ee1");
break;
case V1_0::GadgetFunction::ADB | V1_0::GadgetFunction::MTP:
ret = setVidPid("0x18d1", "0x4ee2");
break;
case static_cast<uint64_t>(V1_0::GadgetFunction::RNDIS):
ret = setVidPid("0x18d1", "0x4ee3");
break;
case V1_0::GadgetFunction::ADB | V1_0::GadgetFunction::RNDIS:
ret = setVidPid("0x18d1", "0x4ee4");
break;
case static_cast<uint64_t>(V1_0::GadgetFunction::PTP):
ret = setVidPid("0x18d1", "0x4ee5");
break;
case V1_0::GadgetFunction::ADB | V1_0::GadgetFunction::PTP:
ret = setVidPid("0x18d1", "0x4ee6");
break;
case static_cast<uint64_t>(V1_0::GadgetFunction::ADB):
ret = setVidPid("0x18d1", "0x4ee7");
break;
case static_cast<uint64_t>(V1_0::GadgetFunction::MIDI):
ret = setVidPid("0x18d1", "0x4ee8");
break;
case V1_0::GadgetFunction::ADB | V1_0::GadgetFunction::MIDI:
ret = setVidPid("0x18d1", "0x4ee9");
break;
case static_cast<uint64_t>(V1_0::GadgetFunction::ACCESSORY):
ret = setVidPid("0x18d1", "0x2d00");
break;
case V1_0::GadgetFunction::ADB | V1_0::GadgetFunction::ACCESSORY:
ret = setVidPid("0x18d1", "0x2d01");
break;
case static_cast<uint64_t>(V1_0::GadgetFunction::AUDIO_SOURCE):
ret = setVidPid("0x18d1", "0x2d02");
break;
case V1_0::GadgetFunction::ADB | V1_0::GadgetFunction::AUDIO_SOURCE:
ret = setVidPid("0x18d1", "0x2d03");
break;
case V1_0::GadgetFunction::ACCESSORY | V1_0::GadgetFunction::AUDIO_SOURCE:
ret = setVidPid("0x18d1", "0x2d04");
break;
case V1_0::GadgetFunction::ADB | V1_0::GadgetFunction::ACCESSORY |
V1_0::GadgetFunction::AUDIO_SOURCE:
ret = setVidPid("0x18d1", "0x2d05");
break;
default:
ALOGE("Combination not supported");
ret = V1_0::Status::CONFIGURATION_NOT_SUPPORTED;
}
return ret;
}
V1_0::Status UsbGadget::setupFunctions(uint64_t functions,
const sp<V1_0::IUsbGadgetCallback>& callback,
uint64_t timeout) {
bool ffsEnabled = false;
int i = 0;
if (addGenericAndroidFunctions(&monitorFfs, functions, &ffsEnabled, &i) !=
V1_0::Status::SUCCESS)
return V1_0::Status::ERROR;
if ((functions & V1_0::GadgetFunction::ADB) != 0) {
ffsEnabled = true;
if (addAdb(&monitorFfs, &i) != V1_0::Status::SUCCESS) return V1_0::Status::ERROR;
}
// Pull up the gadget right away when there are no ffs functions.
if (!ffsEnabled) {
if (!WriteStringToFile(kGadgetName, PULLUP_PATH)) return V1_0::Status::ERROR;
mCurrentUsbFunctionsApplied = true;
if (callback) callback->setCurrentUsbFunctionsCb(functions, V1_0::Status::SUCCESS);
return V1_0::Status::SUCCESS;
}
monitorFfs.registerFunctionsAppliedCallback(&currentFunctionsAppliedCallback, this);
// Monitors the ffs paths to pull up the gadget when descriptors are written.
// Also takes of the pulling up the gadget again if the userspace process
// dies and restarts.
monitorFfs.startMonitor();
if (kDebug) ALOGI("Mainthread in Cv");
if (callback) {
bool pullup = monitorFfs.waitForPullUp(timeout);
Return<void> ret = callback->setCurrentUsbFunctionsCb(
functions, pullup ? V1_0::Status::SUCCESS : V1_0::Status::ERROR);
if (!ret.isOk()) ALOGE("setCurrentUsbFunctionsCb error %s", ret.description().c_str());
}
return V1_0::Status::SUCCESS;
}
Return<void> UsbGadget::setCurrentUsbFunctions(uint64_t functions,
const sp<V1_0::IUsbGadgetCallback>& callback,
uint64_t timeout) {
std::unique_lock<std::mutex> lk(mLockSetCurrentFunction);
mCurrentUsbFunctions = functions;
mCurrentUsbFunctionsApplied = false;
// Unlink the gadget and stop the monitor if running.
V1_0::Status status = tearDownGadget();
if (status != V1_0::Status::SUCCESS) {
goto error;
}
ALOGI("Returned from tearDown gadget");
// Leave the gadget pulled down to give time for the host to sense disconnect.
usleep(kDisconnectWaitUs);
if (functions == static_cast<uint64_t>(V1_0::GadgetFunction::NONE)) {
if (callback == NULL) return Void();
Return<void> ret = callback->setCurrentUsbFunctionsCb(functions, V1_0::Status::SUCCESS);
if (!ret.isOk())
ALOGE("Error while calling setCurrentUsbFunctionsCb %s", ret.description().c_str());
return Void();
}
status = validateAndSetVidPid(functions);
if (status != V1_0::Status::SUCCESS) {
goto error;
}
status = setupFunctions(functions, callback, timeout);
if (status != V1_0::Status::SUCCESS) {
goto error;
}
ALOGI("Usb Gadget setcurrent functions called successfully");
return Void();
error:
ALOGI("Usb Gadget setcurrent functions failed");
if (callback == NULL) return Void();
Return<void> ret = callback->setCurrentUsbFunctionsCb(functions, status);
if (!ret.isOk())
ALOGE("Error while calling setCurrentUsbFunctionsCb %s", ret.description().c_str());
return Void();
}
} // namespace implementation
} // namespace V1_1
} // namespace gadget
} // namespace usb
} // namespace hardware
} // namespace android

View File

@@ -0,0 +1,98 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_HARDWARE_USB_GADGET_V1_1_USBGADGET_H
#define ANDROID_HARDWARE_USB_GADGET_V1_1_USBGADGET_H
#include <UsbGadgetCommon.h>
#include <android-base/file.h>
#include <android-base/properties.h>
#include <android-base/unique_fd.h>
#include <android/hardware/usb/gadget/1.1/IUsbGadget.h>
#include <hidl/MQDescriptor.h>
#include <hidl/Status.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <utils/Log.h>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
namespace android {
namespace hardware {
namespace usb {
namespace gadget {
namespace V1_1 {
namespace implementation {
using ::android::sp;
using ::android::base::GetProperty;
using ::android::base::SetProperty;
using ::android::base::unique_fd;
using ::android::base::WriteStringToFile;
using ::android::hardware::hidl_array;
using ::android::hardware::hidl_memory;
using ::android::hardware::hidl_string;
using ::android::hardware::hidl_vec;
using ::android::hardware::Return;
using ::android::hardware::Void;
using ::android::hardware::usb::gadget::addAdb;
using ::android::hardware::usb::gadget::addEpollFd;
using ::android::hardware::usb::gadget::getVendorFunctions;
using ::android::hardware::usb::gadget::kDebug;
using ::android::hardware::usb::gadget::kDisconnectWaitUs;
using ::android::hardware::usb::gadget::linkFunction;
using ::android::hardware::usb::gadget::MonitorFfs;
using ::android::hardware::usb::gadget::resetGadget;
using ::android::hardware::usb::gadget::setVidPid;
using ::android::hardware::usb::gadget::unlinkFunctions;
using ::std::string;
constexpr char kGadgetName[] = "a600000.dwc3";
static MonitorFfs monitorFfs(kGadgetName);
struct UsbGadget : public IUsbGadget {
UsbGadget();
// Makes sure that only one request is processed at a time.
std::mutex mLockSetCurrentFunction;
uint64_t mCurrentUsbFunctions;
bool mCurrentUsbFunctionsApplied;
Return<void> setCurrentUsbFunctions(uint64_t functions,
const sp<V1_0::IUsbGadgetCallback>& callback,
uint64_t timeout) override;
Return<void> getCurrentUsbFunctions(const sp<V1_0::IUsbGadgetCallback>& callback) override;
Return<Status> reset() override;
private:
V1_0::Status tearDownGadget();
V1_0::Status setupFunctions(uint64_t functions, const sp<V1_0::IUsbGadgetCallback>& callback,
uint64_t timeout);
};
} // namespace implementation
} // namespace V1_1
} // namespace gadget
} // namespace usb
} // namespace hardware
} // namespace android
#endif // ANDROID_HARDWARE_USB_V1_1_USBGADGET_H

View File

@@ -0,0 +1,6 @@
service vendor.usb-gadget-hal-1-1 /vendor/bin/hw/android.hardware.usb.gadget@1.1-service
interface android.hardware.usb.gadget@1.0::IUsbGadget default
interface android.hardware.usb.gadget@1.1::IUsbGadget default
class hal
user root
group root shell mtp

View File

@@ -0,0 +1,12 @@
<manifest version="1.0" type="device">
<hal format="hidl">
<name>android.hardware.usb.gadget</name>
<transport>hwbinder</transport>
<version>1.1</version>
<interface>
<name>IUsbGadget</name>
<instance>default</instance>
</interface>
</hal>
</manifest>

View File

@@ -0,0 +1,40 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
cc_library_static {
name: "libusbconfigfs",
vendor_available: true,
export_include_dirs: ["include"],
srcs: [
"UsbGadgetUtils.cpp",
"MonitorFfs.cpp",
],
cflags: [
"-Wall",
"-Werror",
],
shared_libs: [
"android.hardware.usb.gadget@1.0",
"android.hardware.usb.gadget@1.1",
"libbase",
"libcutils",
"libhidlbase",
"libutils",
],
}

View File

@@ -0,0 +1,269 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "libusbconfigfs"
#include "include/UsbGadgetCommon.h"
namespace android {
namespace hardware {
namespace usb {
namespace gadget {
static volatile bool gadgetPullup;
MonitorFfs::MonitorFfs(const char* const gadget)
: mWatchFd(),
mEndpointList(),
mLock(),
mCv(),
mLockFd(),
mCurrentUsbFunctionsApplied(false),
mMonitor(),
mCallback(NULL),
mPayload(NULL),
mGadgetName(gadget),
mMonitorRunning(false) {
unique_fd eventFd(eventfd(0, 0));
if (eventFd == -1) {
ALOGE("mEventFd failed to create %d", errno);
abort();
}
unique_fd epollFd(epoll_create(2));
if (epollFd == -1) {
ALOGE("mEpollFd failed to create %d", errno);
abort();
}
unique_fd inotifyFd(inotify_init());
if (inotifyFd < 0) {
ALOGE("inotify init failed");
abort();
}
if (addEpollFd(epollFd, inotifyFd) == -1) abort();
if (addEpollFd(epollFd, eventFd) == -1) abort();
mEpollFd = move(epollFd);
mInotifyFd = move(inotifyFd);
mEventFd = move(eventFd);
gadgetPullup = false;
}
static void displayInotifyEvent(struct inotify_event* i) {
ALOGE(" wd =%2d; ", i->wd);
if (i->cookie > 0) ALOGE("cookie =%4d; ", i->cookie);
ALOGE("mask = ");
if (i->mask & IN_ACCESS) ALOGE("IN_ACCESS ");
if (i->mask & IN_ATTRIB) ALOGE("IN_ATTRIB ");
if (i->mask & IN_CLOSE_NOWRITE) ALOGE("IN_CLOSE_NOWRITE ");
if (i->mask & IN_CLOSE_WRITE) ALOGE("IN_CLOSE_WRITE ");
if (i->mask & IN_CREATE) ALOGE("IN_CREATE ");
if (i->mask & IN_DELETE) ALOGE("IN_DELETE ");
if (i->mask & IN_DELETE_SELF) ALOGE("IN_DELETE_SELF ");
if (i->mask & IN_IGNORED) ALOGE("IN_IGNORED ");
if (i->mask & IN_ISDIR) ALOGE("IN_ISDIR ");
if (i->mask & IN_MODIFY) ALOGE("IN_MODIFY ");
if (i->mask & IN_MOVE_SELF) ALOGE("IN_MOVE_SELF ");
if (i->mask & IN_MOVED_FROM) ALOGE("IN_MOVED_FROM ");
if (i->mask & IN_MOVED_TO) ALOGE("IN_MOVED_TO ");
if (i->mask & IN_OPEN) ALOGE("IN_OPEN ");
if (i->mask & IN_Q_OVERFLOW) ALOGE("IN_Q_OVERFLOW ");
if (i->mask & IN_UNMOUNT) ALOGE("IN_UNMOUNT ");
ALOGE("\n");
if (i->len > 0) ALOGE(" name = %s\n", i->name);
}
void* MonitorFfs::startMonitorFd(void* param) {
MonitorFfs* monitorFfs = (MonitorFfs*)param;
char buf[kBufferSize];
bool writeUdc = true, stopMonitor = false;
struct epoll_event events[kEpollEvents];
steady_clock::time_point disconnect;
bool descriptorWritten = true;
for (int i = 0; i < static_cast<int>(monitorFfs->mEndpointList.size()); i++) {
if (access(monitorFfs->mEndpointList.at(i).c_str(), R_OK)) {
descriptorWritten = false;
break;
}
}
// notify here if the endpoints are already present.
if (descriptorWritten) {
usleep(kPullUpDelay);
if (!!WriteStringToFile(monitorFfs->mGadgetName, PULLUP_PATH)) {
lock_guard<mutex> lock(monitorFfs->mLock);
monitorFfs->mCurrentUsbFunctionsApplied = true;
monitorFfs->mCallback(monitorFfs->mCurrentUsbFunctionsApplied, monitorFfs->mPayload);
gadgetPullup = true;
writeUdc = false;
ALOGI("GADGET pulled up");
monitorFfs->mCv.notify_all();
}
}
while (!stopMonitor) {
int nrEvents = epoll_wait(monitorFfs->mEpollFd, events, kEpollEvents, -1);
if (nrEvents <= 0) {
ALOGE("epoll wait did not return descriptor number");
continue;
}
for (int i = 0; i < nrEvents; i++) {
ALOGI("event=%u on fd=%d\n", events[i].events, events[i].data.fd);
if (events[i].data.fd == monitorFfs->mInotifyFd) {
// Process all of the events in buffer returned by read().
int numRead = read(monitorFfs->mInotifyFd, buf, kBufferSize);
for (char* p = buf; p < buf + numRead;) {
struct inotify_event* event = (struct inotify_event*)p;
if (kDebug) displayInotifyEvent(event);
p += sizeof(struct inotify_event) + event->len;
bool descriptorPresent = true;
for (int j = 0; j < static_cast<int>(monitorFfs->mEndpointList.size()); j++) {
if (access(monitorFfs->mEndpointList.at(j).c_str(), R_OK)) {
if (kDebug) ALOGI("%s absent", monitorFfs->mEndpointList.at(j).c_str());
descriptorPresent = false;
break;
}
}
if (!descriptorPresent && !writeUdc) {
if (kDebug) ALOGI("endpoints not up");
writeUdc = true;
disconnect = std::chrono::steady_clock::now();
} else if (descriptorPresent && writeUdc) {
steady_clock::time_point temp = steady_clock::now();
if (std::chrono::duration_cast<microseconds>(temp - disconnect).count() <
kPullUpDelay)
usleep(kPullUpDelay);
if (!!WriteStringToFile(monitorFfs->mGadgetName, PULLUP_PATH)) {
lock_guard<mutex> lock(monitorFfs->mLock);
monitorFfs->mCurrentUsbFunctionsApplied = true;
monitorFfs->mCallback(monitorFfs->mCurrentUsbFunctionsApplied,
monitorFfs->mPayload);
ALOGI("GADGET pulled up");
writeUdc = false;
gadgetPullup = true;
// notify the main thread to signal userspace.
monitorFfs->mCv.notify_all();
}
}
}
} else {
uint64_t flag;
read(monitorFfs->mEventFd, &flag, sizeof(flag));
if (flag == 100) {
stopMonitor = true;
break;
}
}
}
}
return NULL;
}
void MonitorFfs::reset() {
lock_guard<mutex> lock(mLockFd);
uint64_t flag = 100;
unsigned long ret;
if (mMonitorRunning) {
// Stop the monitor thread by writing into signal fd.
ret = TEMP_FAILURE_RETRY(write(mEventFd, &flag, sizeof(flag)));
if (ret < 0) ALOGE("Error writing eventfd errno=%d", errno);
ALOGI("mMonitor signalled to exit");
mMonitor->join();
ALOGI("mMonitor destroyed");
mMonitorRunning = false;
}
for (std::vector<int>::size_type i = 0; i != mWatchFd.size(); i++)
inotify_rm_watch(mInotifyFd, mWatchFd[i]);
mEndpointList.clear();
gadgetPullup = false;
mCallback = NULL;
mPayload = NULL;
}
bool MonitorFfs::startMonitor() {
mMonitor = unique_ptr<thread>(new thread(this->startMonitorFd, this));
mMonitorRunning = true;
return true;
}
bool MonitorFfs::isMonitorRunning() {
return mMonitorRunning;
}
bool MonitorFfs::waitForPullUp(int timeout_ms) {
std::unique_lock<std::mutex> lk(mLock);
if (gadgetPullup) return true;
if (mCv.wait_for(lk, timeout_ms * 1ms, [] { return gadgetPullup; })) {
ALOGI("monitorFfs signalled true");
return true;
} else {
ALOGI("monitorFfs signalled error");
// continue monitoring as the descriptors might be written at a later
// point.
return false;
}
}
bool MonitorFfs::addInotifyFd(string fd) {
lock_guard<mutex> lock(mLockFd);
int wfd;
wfd = inotify_add_watch(mInotifyFd, fd.c_str(), IN_ALL_EVENTS);
if (wfd == -1)
return false;
else
mWatchFd.push_back(wfd);
return true;
}
void MonitorFfs::addEndPoint(string ep) {
lock_guard<mutex> lock(mLockFd);
mEndpointList.push_back(ep);
}
void MonitorFfs::registerFunctionsAppliedCallback(void (*callback)(bool functionsApplied,
void* payload),
void* payload) {
mCallback = callback;
mPayload = payload;
}
} // namespace gadget
} // namespace usb
} // namespace hardware
} // namespace android

View File

@@ -0,0 +1,193 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "libusbconfigfs"
#include "include/UsbGadgetCommon.h"
namespace android {
namespace hardware {
namespace usb {
namespace gadget {
int unlinkFunctions(const char* path) {
DIR* config = opendir(path);
struct dirent* function;
char filepath[kMaxFilePathLength];
int ret = 0;
if (config == NULL) return -1;
// d_type does not seems to be supported in /config
// so filtering by name.
while (((function = readdir(config)) != NULL)) {
if ((strstr(function->d_name, FUNCTION_NAME) == NULL)) continue;
// build the path for each file in the folder.
sprintf(filepath, "%s/%s", path, function->d_name);
ret = remove(filepath);
if (ret) {
ALOGE("Unable remove file %s errno:%d", filepath, errno);
break;
}
}
closedir(config);
return ret;
}
int addEpollFd(const unique_fd& epfd, const unique_fd& fd) {
struct epoll_event event;
int ret;
event.data.fd = fd;
event.events = EPOLLIN;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event);
if (ret) ALOGE("epoll_ctl error %d", errno);
return ret;
}
int linkFunction(const char* function, int index) {
char functionPath[kMaxFilePathLength];
char link[kMaxFilePathLength];
sprintf(functionPath, "%s%s", FUNCTIONS_PATH, function);
sprintf(link, "%s%d", FUNCTION_PATH, index);
if (symlink(functionPath, link)) {
ALOGE("Cannot create symlink %s -> %s errno:%d", link, functionPath, errno);
return -1;
}
return 0;
}
Status setVidPid(const char* vid, const char* pid) {
if (!WriteStringToFile(vid, VENDOR_ID_PATH)) return Status::ERROR;
if (!WriteStringToFile(pid, PRODUCT_ID_PATH)) return Status::ERROR;
return Status::SUCCESS;
}
std::string getVendorFunctions() {
if (GetProperty(kBuildType, "") == "user") return "user";
std::string bootMode = GetProperty(PERSISTENT_BOOT_MODE, "");
std::string persistVendorFunctions = GetProperty(kPersistentVendorConfig, "");
std::string vendorFunctions = GetProperty(kVendorConfig, "");
std::string ret = "";
if (vendorFunctions != "") {
ret = vendorFunctions;
} else if (bootMode == "usbradio" || bootMode == "factory" || bootMode == "ffbm-00" ||
bootMode == "ffbm-01") {
if (persistVendorFunctions != "")
ret = persistVendorFunctions;
else
ret = "diag";
// vendor.usb.config will reflect the current configured functions
SetProperty(kVendorConfig, ret);
}
return ret;
}
Status resetGadget() {
ALOGI("setCurrentUsbFunctions None");
if (!WriteStringToFile("none", PULLUP_PATH)) ALOGI("Gadget cannot be pulled down");
if (!WriteStringToFile("0", DEVICE_CLASS_PATH)) return Status::ERROR;
if (!WriteStringToFile("0", DEVICE_SUB_CLASS_PATH)) return Status::ERROR;
if (!WriteStringToFile("0", DEVICE_PROTOCOL_PATH)) return Status::ERROR;
if (!WriteStringToFile("0", DESC_USE_PATH)) return Status::ERROR;
if (unlinkFunctions(CONFIG_PATH)) return Status::ERROR;
return Status::SUCCESS;
}
Status addGenericAndroidFunctions(MonitorFfs* monitorFfs, uint64_t functions, bool* ffsEnabled,
int* functionCount) {
if (((functions & GadgetFunction::MTP) != 0)) {
*ffsEnabled = true;
ALOGI("setCurrentUsbFunctions mtp");
if (!WriteStringToFile("1", DESC_USE_PATH)) return Status::ERROR;
if (!monitorFfs->addInotifyFd("/dev/usb-ffs/mtp/")) return Status::ERROR;
if (linkFunction("ffs.mtp", (*functionCount)++)) return Status::ERROR;
// Add endpoints to be monitored.
monitorFfs->addEndPoint("/dev/usb-ffs/mtp/ep1");
monitorFfs->addEndPoint("/dev/usb-ffs/mtp/ep2");
monitorFfs->addEndPoint("/dev/usb-ffs/mtp/ep3");
} else if (((functions & GadgetFunction::PTP) != 0)) {
*ffsEnabled = true;
ALOGI("setCurrentUsbFunctions ptp");
if (!WriteStringToFile("1", DESC_USE_PATH)) return Status::ERROR;
if (!monitorFfs->addInotifyFd("/dev/usb-ffs/ptp/")) return Status::ERROR;
if (linkFunction("ffs.ptp", (*functionCount)++)) return Status::ERROR;
// Add endpoints to be monitored.
monitorFfs->addEndPoint("/dev/usb-ffs/ptp/ep1");
monitorFfs->addEndPoint("/dev/usb-ffs/ptp/ep2");
monitorFfs->addEndPoint("/dev/usb-ffs/ptp/ep3");
}
if ((functions & GadgetFunction::MIDI) != 0) {
ALOGI("setCurrentUsbFunctions MIDI");
if (linkFunction("midi.gs5", (*functionCount)++)) return Status::ERROR;
}
if ((functions & GadgetFunction::ACCESSORY) != 0) {
ALOGI("setCurrentUsbFunctions Accessory");
if (linkFunction("accessory.gs2", (*functionCount)++)) return Status::ERROR;
}
if ((functions & GadgetFunction::AUDIO_SOURCE) != 0) {
ALOGI("setCurrentUsbFunctions Audio Source");
if (linkFunction("audio_source.gs3", (*functionCount)++)) return Status::ERROR;
}
if ((functions & GadgetFunction::RNDIS) != 0) {
ALOGI("setCurrentUsbFunctions rndis");
if (linkFunction("gsi.rndis", (*functionCount)++)) return Status::ERROR;
}
return Status::SUCCESS;
}
Status addAdb(MonitorFfs* monitorFfs, int* functionCount) {
ALOGI("setCurrentUsbFunctions Adb");
if (!monitorFfs->addInotifyFd("/dev/usb-ffs/adb/")) return Status::ERROR;
if (linkFunction("ffs.adb", (*functionCount)++)) return Status::ERROR;
monitorFfs->addEndPoint("/dev/usb-ffs/adb/ep1");
monitorFfs->addEndPoint("/dev/usb-ffs/adb/ep2");
ALOGI("Service started");
return Status::SUCCESS;
}
} // namespace gadget
} // namespace usb
} // namespace hardware
} // namespace android

View File

@@ -0,0 +1,177 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef HARDWARE_USB_USBGADGETCOMMON_H
#define HARDWARE_USB_USBGADGETCOMMON_H
#include <android-base/file.h>
#include <android-base/properties.h>
#include <android-base/unique_fd.h>
#include <android/hardware/usb/gadget/1.1/IUsbGadget.h>
#include <dirent.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <sys/inotify.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utils/Log.h>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
namespace android {
namespace hardware {
namespace usb {
namespace gadget {
constexpr int kBufferSize = 512;
constexpr int kMaxFilePathLength = 256;
constexpr int kEpollEvents = 10;
constexpr bool kDebug = false;
constexpr int kDisconnectWaitUs = 100000;
constexpr int kPullUpDelay = 500000;
constexpr int kShutdownMonitor = 100;
constexpr char kBuildType[] = "ro.build.type";
constexpr char kPersistentVendorConfig[] = "persist.vendor.usb.usbradio.config";
constexpr char kVendorConfig[] = "vendor.usb.config";
#define GADGET_PATH "/config/usb_gadget/g1/"
#define PULLUP_PATH GADGET_PATH "UDC"
#define PERSISTENT_BOOT_MODE "ro.bootmode"
#define VENDOR_ID_PATH GADGET_PATH "idVendor"
#define PRODUCT_ID_PATH GADGET_PATH "idProduct"
#define DEVICE_CLASS_PATH GADGET_PATH "bDeviceClass"
#define DEVICE_SUB_CLASS_PATH GADGET_PATH "bDeviceSubClass"
#define DEVICE_PROTOCOL_PATH GADGET_PATH "bDeviceProtocol"
#define DESC_USE_PATH GADGET_PATH "os_desc/use"
#define OS_DESC_PATH GADGET_PATH "os_desc/b.1"
#define CONFIG_PATH GADGET_PATH "configs/b.1/"
#define FUNCTIONS_PATH GADGET_PATH "functions/"
#define FUNCTION_NAME "function"
#define FUNCTION_PATH CONFIG_PATH FUNCTION_NAME
#define RNDIS_PATH FUNCTIONS_PATH "gsi.rndis"
using ::android::base::GetProperty;
using ::android::base::SetProperty;
using ::android::base::unique_fd;
using ::android::base::WriteStringToFile;
using ::android::hardware::usb::gadget::V1_0::GadgetFunction;
using ::android::hardware::usb::gadget::V1_0::Status;
using ::std::lock_guard;
using ::std::move;
using ::std::mutex;
using ::std::string;
using ::std::thread;
using ::std::unique_ptr;
using ::std::vector;
using ::std::chrono::microseconds;
using ::std::chrono::steady_clock;
using ::std::literals::chrono_literals::operator""ms;
// MonitorFfs automously manages gadget pullup by monitoring
// the ep file status. Restarts the usb gadget when the ep
// owner restarts.
class MonitorFfs {
private:
// Monitors the endpoints Inotify events.
unique_fd mInotifyFd;
// Control pipe for shutting down the mMonitor thread.
// mMonitor exits when SHUTDOWN_MONITOR is written into
// mEventFd/
unique_fd mEventFd;
// Pools on mInotifyFd and mEventFd.
unique_fd mEpollFd;
vector<int> mWatchFd;
// Maintains the list of Endpoints.
vector<string> mEndpointList;
// protects the CV.
std::mutex mLock;
std::condition_variable mCv;
// protects mInotifyFd, mEpollFd.
std::mutex mLockFd;
// Flag to maintain the current status of gadget pullup.
bool mCurrentUsbFunctionsApplied;
// Thread object that executes the ep monitoring logic.
unique_ptr<thread> mMonitor;
// Callback to be invoked when gadget is pulled up.
void (*mCallback)(bool functionsApplied, void* payload);
void* mPayload;
// Name of the USB gadget. Used for pullup.
const char* const mGadgetName;
// Monitor State
bool mMonitorRunning;
public:
MonitorFfs(const char* const gadget);
// Inits all the UniqueFds.
void reset();
// Starts monitoring endpoints and pullup the gadget when
// the descriptors are written.
bool startMonitor();
// Waits for timeout_ms for gadget pull up to happen.
// Returns immediately if the gadget is already pulled up.
bool waitForPullUp(int timeout_ms);
// Adds the given fd to the watch list.
bool addInotifyFd(string fd);
// Adds the given endpoint to the watch list.
void addEndPoint(string ep);
// Registers the async callback from the caller to notify the caller
// when the gadget pull up happens.
void registerFunctionsAppliedCallback(void (*callback)(bool functionsApplied, void*(payload)),
void* payload);
bool isMonitorRunning();
// Ep monitoring and the gadget pull up logic.
static void* startMonitorFd(void* param);
};
//**************** Helper functions ************************//
// Adds the given fd to the epollfd(epfd).
int addEpollFd(const unique_fd& epfd, const unique_fd& fd);
// Removes all the usb functions link in the specified path.
int unlinkFunctions(const char* path);
// Craetes a configfs link for the function.
int linkFunction(const char* function, int index);
// Sets the USB VID and PID.
Status setVidPid(const char* vid, const char* pid);
// Extracts vendor functions from the vendor init properties.
std::string getVendorFunctions();
// Adds Adb to the usb configuration.
Status addAdb(MonitorFfs* monitorFfs, int* functionCount);
// Adds all applicable generic android usb functions other than ADB.
Status addGenericAndroidFunctions(MonitorFfs* monitorFfs, uint64_t functions, bool* ffsEnabled,
int* functionCount);
// Pulls down USB gadget.
Status resetGadget();
} // namespace gadget
} // namespace usb
} // namespace hardware
} // namespace android
#endif

View File

@@ -0,0 +1,52 @@
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "android.hardware.usb.gadget@1.1-service"
#include <hidl/HidlTransportSupport.h>
#include "UsbGadget.h"
using android::sp;
// libhwbinder:
using android::hardware::configureRpcThreadpool;
using android::hardware::joinRpcThreadpool;
// Generated HIDL files
using android::hardware::usb::gadget::V1_1::IUsbGadget;
using android::hardware::usb::gadget::V1_1::implementation::UsbGadget;
using android::OK;
using android::status_t;
int main() {
configureRpcThreadpool(1, true /*callerWillJoin*/);
android::sp<IUsbGadget> service2 = new UsbGadget();
status_t status = service2->registerAsService();
if (status != OK) {
ALOGE("Cannot register USB Gadget HAL service");
return 1;
}
ALOGI("USB Gadget HAL Ready.");
joinRpcThreadpool();
// Under noraml cases, execution will not reach this line.
ALOGI("USB Gadget HAL failed to join thread pool.");
return 1;
}