1 /*
2  * Copyright (C) 2018 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_GOOGLE_PIXEL_USB_USBGADGETCOMMON_H
18 #define HARDWARE_GOOGLE_PIXEL_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.0/IUsbGadget.h>
25 
26 #include <dirent.h>
27 #include <fcntl.h>
28 #include <stdio.h>
29 #include <sys/epoll.h>
30 #include <sys/eventfd.h>
31 #include <sys/inotify.h>
32 #include <sys/mount.h>
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <unistd.h>
36 #include <utils/Log.h>
37 #include <chrono>
38 #include <condition_variable>
39 #include <mutex>
40 #include <string>
41 #include <thread>
42 
43 namespace android {
44 namespace hardware {
45 namespace google {
46 namespace pixel {
47 namespace usb {
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::GadgetFunction;
83 using ::android::hardware::usb::gadget::V1_0::Status;
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,
149                                                          void *(payload)),
150                                         void *payload);
151   bool isMonitorRunning();
152   // Ep monitoring and the gadget pull up logic.
153   static void *startMonitorFd(void *param);
154 };
155 
156 //**************** Helper functions ************************//
157 
158 // Adds the given fd to the epollfd(epfd).
159 int addEpollFd(const unique_fd &epfd, const unique_fd &fd);
160 // Removes all the usb functions link in the specified path.
161 int unlinkFunctions(const char *path);
162 // Craetes a configfs link for the function.
163 int linkFunction(const char *function, int index);
164 // Sets the USB VID and PID.
165 Status setVidPid(const char *vid, const char *pid);
166 // Extracts vendor functions from the vendor init properties.
167 std::string getVendorFunctions();
168 // Adds Adb to the usb configuration.
169 Status addAdb(MonitorFfs *monitorFfs, int *functionCount);
170 // Adds all applicable generic android usb functions other than ADB.
171 Status addGenericAndroidFunctions(MonitorFfs *monitorFfs, uint64_t functions,
172                                   bool *ffsEnabled, int *functionCount);
173 // Pulls down USB gadget.
174 Status resetGadget();
175 
176 }  // namespace usb
177 }  // namespace pixel
178 }  // namespace google
179 }  // namespace hardware
180 }  // namespace android
181 #endif
182