1 /*
2  * Copyright (C) 2020 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 #ifndef HARDWARE_USB_USBGADGETCOMMON_H
18 #define HARDWARE_USB_USBGADGETCOMMON_H
19 
20 #include <android-base/file.h>
21 #include <android-base/properties.h>
22 #include <android-base/unique_fd.h>
23 
24 #include <android/hardware/usb/gadget/1.2/IUsbGadget.h>
25 #include <android/hardware/usb/gadget/1.2/types.h>
26 
27 #include <dirent.h>
28 #include <fcntl.h>
29 #include <stdio.h>
30 #include <sys/epoll.h>
31 #include <sys/eventfd.h>
32 #include <sys/inotify.h>
33 #include <sys/mount.h>
34 #include <sys/stat.h>
35 #include <sys/types.h>
36 #include <unistd.h>
37 #include <utils/Log.h>
38 #include <chrono>
39 #include <condition_variable>
40 #include <mutex>
41 #include <string>
42 #include <thread>
43 
44 namespace android {
45 namespace hardware {
46 namespace usb {
47 namespace gadget {
48 
49 constexpr int kBufferSize = 512;
50 constexpr int kMaxFilePathLength = 256;
51 constexpr int kEpollEvents = 10;
52 constexpr bool kDebug = false;
53 constexpr int kDisconnectWaitUs = 100000;
54 constexpr int kPullUpDelay = 500000;
55 constexpr int kShutdownMonitor = 100;
56 
57 constexpr char kBuildType[] = "ro.build.type";
58 constexpr char kPersistentVendorConfig[] = "persist.vendor.usb.usbradio.config";
59 constexpr char kVendorConfig[] = "vendor.usb.config";
60 constexpr char kVendorRndisConfig[] = "vendor.usb.rndis.config";
61 
62 #define GADGET_PATH "/config/usb_gadget/g1/"
63 #define PULLUP_PATH GADGET_PATH "UDC"
64 #define PERSISTENT_BOOT_MODE "ro.bootmode"
65 #define VENDOR_ID_PATH GADGET_PATH "idVendor"
66 #define PRODUCT_ID_PATH GADGET_PATH "idProduct"
67 #define DEVICE_CLASS_PATH GADGET_PATH "bDeviceClass"
68 #define DEVICE_SUB_CLASS_PATH GADGET_PATH "bDeviceSubClass"
69 #define DEVICE_PROTOCOL_PATH GADGET_PATH "bDeviceProtocol"
70 #define DESC_USE_PATH GADGET_PATH "os_desc/use"
71 #define OS_DESC_PATH GADGET_PATH "os_desc/b.1"
72 #define CONFIG_PATH GADGET_PATH "configs/b.1/"
73 #define FUNCTIONS_PATH GADGET_PATH "functions/"
74 #define FUNCTION_NAME "function"
75 #define FUNCTION_PATH CONFIG_PATH FUNCTION_NAME
76 #define RNDIS_PATH FUNCTIONS_PATH "gsi.rndis"
77 
78 using ::android::base::GetProperty;
79 using ::android::base::SetProperty;
80 using ::android::base::unique_fd;
81 using ::android::base::WriteStringToFile;
82 using ::android::hardware::usb::gadget::V1_0::Status;
83 using ::android::hardware::usb::gadget::V1_2::GadgetFunction;
84 
85 using ::std::lock_guard;
86 using ::std::move;
87 using ::std::mutex;
88 using ::std::string;
89 using ::std::thread;
90 using ::std::unique_ptr;
91 using ::std::vector;
92 using ::std::chrono::microseconds;
93 using ::std::chrono::steady_clock;
94 using ::std::literals::chrono_literals::operator""ms;
95 
96 // MonitorFfs automously manages gadget pullup by monitoring
97 // the ep file status. Restarts the usb gadget when the ep
98 // owner restarts.
99 class MonitorFfs {
100   private:
101     // Monitors the endpoints Inotify events.
102     unique_fd mInotifyFd;
103     // Control pipe for shutting down the mMonitor thread.
104     // mMonitor exits when SHUTDOWN_MONITOR is written into
105     // mEventFd/
106     unique_fd mEventFd;
107     // Pools on mInotifyFd and mEventFd.
108     unique_fd mEpollFd;
109     vector<int> mWatchFd;
110 
111     // Maintains the list of Endpoints.
112     vector<string> mEndpointList;
113     // protects the CV.
114     std::mutex mLock;
115     std::condition_variable mCv;
116     // protects mInotifyFd, mEpollFd.
117     std::mutex mLockFd;
118 
119     // Flag to maintain the current status of gadget pullup.
120     bool mCurrentUsbFunctionsApplied;
121 
122     // Thread object that executes the ep monitoring logic.
123     unique_ptr<thread> mMonitor;
124     // Callback to be invoked when gadget is pulled up.
125     void (*mCallback)(bool functionsApplied, void* payload);
126     void* mPayload;
127     // Name of the USB gadget. Used for pullup.
128     const char* const mGadgetName;
129     // Monitor State
130     bool mMonitorRunning;
131 
132   public:
133     MonitorFfs(const char* const gadget);
134     // Inits all the UniqueFds.
135     void reset();
136     // Starts monitoring endpoints and pullup the gadget when
137     // the descriptors are written.
138     bool startMonitor();
139     // Waits for timeout_ms for gadget pull up to happen.
140     // Returns immediately if the gadget is already pulled up.
141     bool waitForPullUp(int timeout_ms);
142     // Adds the given fd to the watch list.
143     bool addInotifyFd(string fd);
144     // Adds the given endpoint to the watch list.
145     void addEndPoint(string ep);
146     // Registers the async callback from the caller to notify the caller
147     // when the gadget pull up happens.
148     void registerFunctionsAppliedCallback(void (*callback)(bool functionsApplied, void*(payload)),
149                                           void* payload);
150     bool isMonitorRunning();
151     // Ep monitoring and the gadget pull up logic.
152     static void* startMonitorFd(void* param);
153 };
154 
155 //**************** Helper functions ************************//
156 
157 // Adds the given fd to the epollfd(epfd).
158 int addEpollFd(const unique_fd& epfd, const unique_fd& fd);
159 // Removes all the usb functions link in the specified path.
160 int unlinkFunctions(const char* path);
161 // Craetes a configfs link for the function.
162 int linkFunction(const char* function, int index);
163 // Sets the USB VID and PID.
164 Status setVidPid(const char* vid, const char* pid);
165 // Extracts vendor functions from the vendor init properties.
166 std::string getVendorFunctions();
167 // Adds Adb to the usb configuration.
168 Status addAdb(MonitorFfs* monitorFfs, int* functionCount);
169 // Adds all applicable generic android usb functions other than ADB.
170 Status addGenericAndroidFunctions(MonitorFfs* monitorFfs, uint64_t functions, bool* ffsEnabled,
171                                   int* functionCount);
172 // Pulls down USB gadget.
173 Status resetGadget();
174 
175 }  // namespace gadget
176 }  // namespace usb
177 }  // namespace hardware
178 }  // namespace android
179 #endif
180