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 
61 #define GADGET_PATH "/config/usb_gadget/g1/"
62 #define PULLUP_PATH GADGET_PATH "UDC"
63 #define PERSISTENT_BOOT_MODE "ro.bootmode"
64 #define VENDOR_ID_PATH GADGET_PATH "idVendor"
65 #define PRODUCT_ID_PATH GADGET_PATH "idProduct"
66 #define DEVICE_CLASS_PATH GADGET_PATH "bDeviceClass"
67 #define DEVICE_SUB_CLASS_PATH GADGET_PATH "bDeviceSubClass"
68 #define DEVICE_PROTOCOL_PATH GADGET_PATH "bDeviceProtocol"
69 #define DESC_USE_PATH GADGET_PATH "os_desc/use"
70 #define OS_DESC_PATH GADGET_PATH "os_desc/b.1"
71 #define CONFIG_PATH GADGET_PATH "configs/b.1/"
72 #define FUNCTIONS_PATH GADGET_PATH "functions/"
73 #define FUNCTION_NAME "function"
74 #define FUNCTION_PATH CONFIG_PATH FUNCTION_NAME
75 #define RNDIS_PATH FUNCTIONS_PATH "gsi.rndis"
76 
77 using ::android::base::GetProperty;
78 using ::android::base::SetProperty;
79 using ::android::base::unique_fd;
80 using ::android::base::WriteStringToFile;
81 using ::android::hardware::usb::gadget::V1_0::GadgetFunction;
82 using ::android::hardware::usb::gadget::V1_0::Status;
83 
84 using ::std::lock_guard;
85 using ::std::move;
86 using ::std::mutex;
87 using ::std::string;
88 using ::std::thread;
89 using ::std::unique_ptr;
90 using ::std::vector;
91 using ::std::chrono::microseconds;
92 using ::std::chrono::steady_clock;
93 using ::std::literals::chrono_literals::operator""ms;
94 
95 // MonitorFfs automously manages gadget pullup by monitoring
96 // the ep file status. Restarts the usb gadget when the ep
97 // owner restarts.
98 class MonitorFfs {
99  private:
100   // Monitors the endpoints Inotify events.
101   unique_fd mInotifyFd;
102   // Control pipe for shutting down the mMonitor thread.
103   // mMonitor exits when SHUTDOWN_MONITOR is written into
104   // mEventFd/
105   unique_fd mEventFd;
106   // Pools on mInotifyFd and mEventFd.
107   unique_fd mEpollFd;
108   vector<int> mWatchFd;
109 
110   // Maintains the list of Endpoints.
111   vector<string> mEndpointList;
112   // protects the CV.
113   std::mutex mLock;
114   std::condition_variable mCv;
115   // protects mInotifyFd, mEpollFd.
116   std::mutex mLockFd;
117 
118   // Flag to maintain the current status of gadget pullup.
119   bool mCurrentUsbFunctionsApplied;
120 
121   // Thread object that executes the ep monitoring logic.
122   unique_ptr<thread> mMonitor;
123   // Callback to be invoked when gadget is pulled up.
124   void (*mCallback)(bool functionsApplied, void *payload);
125   void *mPayload;
126   // Name of the USB gadget. Used for pullup.
127   const char *const mGadgetName;
128   // Monitor State
129   bool mMonitorRunning;
130 
131  public:
132   MonitorFfs(const char *const gadget);
133   // Inits all the UniqueFds.
134   void reset();
135   // Starts monitoring endpoints and pullup the gadget when
136   // the descriptors are written.
137   bool startMonitor();
138   // Waits for timeout_ms for gadget pull up to happen.
139   // Returns immediately if the gadget is already pulled up.
140   bool waitForPullUp(int timeout_ms);
141   // Adds the given fd to the watch list.
142   bool addInotifyFd(string fd);
143   // Adds the given endpoint to the watch list.
144   void addEndPoint(string ep);
145   // Registers the async callback from the caller to notify the caller
146   // when the gadget pull up happens.
147   void registerFunctionsAppliedCallback(void (*callback)(bool functionsApplied,
148                                                          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,
171                                   bool *ffsEnabled, int *functionCount);
172 // Pulls down USB gadget.
173 Status resetGadget();
174 
175 }  // namespace usb
176 }  // namespace pixel
177 }  // namespace google
178 }  // namespace hardware
179 }  // namespace android
180 #endif
181