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 #define LOG_TAG "android.hardware.usb.gadget@1.0-service.crosshatch"
18 
19 #include "UsbGadget.h"
20 #include <dirent.h>
21 #include <fcntl.h>
22 #include <stdio.h>
23 #include <sys/inotify.h>
24 #include <sys/mount.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <unistd.h>
28 
29 constexpr int BUFFER_SIZE = 512;
30 constexpr int MAX_FILE_PATH_LENGTH = 256;
31 constexpr int EPOLL_EVENTS = 10;
32 constexpr bool DEBUG = false;
33 constexpr int DISCONNECT_WAIT_US = 100000;
34 constexpr int PULL_UP_DELAY = 500000;
35 
36 #define BUILD_TYPE "ro.build.type"
37 #define GADGET_PATH "/config/usb_gadget/g1/"
38 #define PULLUP_PATH GADGET_PATH "UDC"
39 #define GADGET_NAME "a600000.dwc3"
40 #define PERSISTENT_BOOT_MODE "ro.bootmode"
41 #define VENDOR_ID_PATH GADGET_PATH "idVendor"
42 #define PRODUCT_ID_PATH GADGET_PATH "idProduct"
43 #define DEVICE_CLASS_PATH GADGET_PATH "bDeviceClass"
44 #define DEVICE_SUB_CLASS_PATH GADGET_PATH "bDeviceSubClass"
45 #define DEVICE_PROTOCOL_PATH GADGET_PATH "bDeviceProtocol"
46 #define DESC_USE_PATH GADGET_PATH "os_desc/use"
47 #define OS_DESC_PATH GADGET_PATH "os_desc/b.1"
48 #define CONFIG_PATH GADGET_PATH "configs/b.1/"
49 #define FUNCTIONS_PATH GADGET_PATH "functions/"
50 #define FUNCTION_NAME "function"
51 #define FUNCTION_PATH CONFIG_PATH FUNCTION_NAME
52 #define RNDIS_PATH FUNCTIONS_PATH "gsi.rndis"
53 
54 #define PERSISTENT_VENDOR_CONFIG "persist.vendor.usb.usbradio.config"
55 #define VENDOR_CONFIG "vendor.usb.config"
56 
57 namespace android {
58 namespace hardware {
59 namespace usb {
60 namespace gadget {
61 namespace V1_0 {
62 namespace implementation {
63 
64 volatile bool gadgetPullup;
65 
66 // Used for debug.
displayInotifyEvent(struct inotify_event * i)67 static void displayInotifyEvent(struct inotify_event *i) {
68   ALOGE("    wd =%2d; ", i->wd);
69   if (i->cookie > 0) ALOGE("cookie =%4d; ", i->cookie);
70 
71   ALOGE("mask = ");
72   if (i->mask & IN_ACCESS) ALOGE("IN_ACCESS ");
73   if (i->mask & IN_ATTRIB) ALOGE("IN_ATTRIB ");
74   if (i->mask & IN_CLOSE_NOWRITE) ALOGE("IN_CLOSE_NOWRITE ");
75   if (i->mask & IN_CLOSE_WRITE) ALOGE("IN_CLOSE_WRITE ");
76   if (i->mask & IN_CREATE) ALOGE("IN_CREATE ");
77   if (i->mask & IN_DELETE) ALOGE("IN_DELETE ");
78   if (i->mask & IN_DELETE_SELF) ALOGE("IN_DELETE_SELF ");
79   if (i->mask & IN_IGNORED) ALOGE("IN_IGNORED ");
80   if (i->mask & IN_ISDIR) ALOGE("IN_ISDIR ");
81   if (i->mask & IN_MODIFY) ALOGE("IN_MODIFY ");
82   if (i->mask & IN_MOVE_SELF) ALOGE("IN_MOVE_SELF ");
83   if (i->mask & IN_MOVED_FROM) ALOGE("IN_MOVED_FROM ");
84   if (i->mask & IN_MOVED_TO) ALOGE("IN_MOVED_TO ");
85   if (i->mask & IN_OPEN) ALOGE("IN_OPEN ");
86   if (i->mask & IN_Q_OVERFLOW) ALOGE("IN_Q_OVERFLOW ");
87   if (i->mask & IN_UNMOUNT) ALOGE("IN_UNMOUNT ");
88   ALOGE("\n");
89 
90   if (i->len > 0) ALOGE("        name = %s\n", i->name);
91 }
92 
monitorFfs(void * param)93 static void *monitorFfs(void *param) {
94   UsbGadget *usbGadget = (UsbGadget *)param;
95   char buf[BUFFER_SIZE];
96   bool writeUdc = true, stopMonitor = false;
97   struct epoll_event events[EPOLL_EVENTS];
98   steady_clock::time_point disconnect;
99 
100   bool descriptorWritten = true;
101   for (int i = 0; i < static_cast<int>(usbGadget->mEndpointList.size()); i++) {
102     if (access(usbGadget->mEndpointList.at(i).c_str(), R_OK)) {
103       descriptorWritten = false;
104       break;
105     }
106   }
107 
108   // notify here if the endpoints are already present.
109   if (descriptorWritten) {
110     usleep(PULL_UP_DELAY);
111     if (!!WriteStringToFile(GADGET_NAME, PULLUP_PATH)) {
112       lock_guard<mutex> lock(usbGadget->mLock);
113       usbGadget->mCurrentUsbFunctionsApplied = true;
114       gadgetPullup = true;
115       writeUdc = false;
116       ALOGI("GADGET pulled up");
117       usbGadget->mCv.notify_all();
118     }
119   }
120 
121   while (!stopMonitor) {
122     int nrEvents = epoll_wait(usbGadget->mEpollFd, events, EPOLL_EVENTS, -1);
123 
124     if (nrEvents <= 0) {
125       ALOGE("epoll wait did not return descriptor number");
126       continue;
127     }
128 
129     for (int i = 0; i < nrEvents; i++) {
130       ALOGI("event=%u on fd=%d\n", events[i].events, events[i].data.fd);
131 
132       if (events[i].data.fd == usbGadget->mInotifyFd) {
133         // Process all of the events in buffer returned by read().
134         int numRead = read(usbGadget->mInotifyFd, buf, BUFFER_SIZE);
135         for (char *p = buf; p < buf + numRead;) {
136           struct inotify_event *event = (struct inotify_event *)p;
137           if (DEBUG) displayInotifyEvent(event);
138 
139           p += sizeof(struct inotify_event) + event->len;
140 
141           bool descriptorPresent = true;
142           for (int j = 0; j < static_cast<int>(usbGadget->mEndpointList.size());
143                j++) {
144             if (access(usbGadget->mEndpointList.at(j).c_str(), R_OK)) {
145               if (DEBUG)
146                 ALOGI("%s absent", usbGadget->mEndpointList.at(j).c_str());
147               descriptorPresent = false;
148               break;
149             }
150           }
151 
152           if (!descriptorPresent && !writeUdc) {
153             if (DEBUG) ALOGI("endpoints not up");
154             writeUdc = true;
155             disconnect = std::chrono::steady_clock::now();
156           } else if (descriptorPresent && writeUdc) {
157             steady_clock::time_point temp = steady_clock::now();
158 
159             if (std::chrono::duration_cast<microseconds>(temp - disconnect).count()
160                 < PULL_UP_DELAY)
161               usleep(PULL_UP_DELAY);
162 
163             if(!!WriteStringToFile(GADGET_NAME, PULLUP_PATH)) {
164               lock_guard<mutex> lock(usbGadget->mLock);
165               usbGadget->mCurrentUsbFunctionsApplied = true;
166               ALOGI("GADGET pulled up");
167               writeUdc = false;
168               gadgetPullup = true;
169               // notify the main thread to signal userspace.
170               usbGadget->mCv.notify_all();
171             }
172           }
173         }
174       } else {
175         uint64_t flag;
176         read(usbGadget->mEventFd, &flag, sizeof(flag));
177         if (flag == 100) {
178           stopMonitor = true;
179           break;
180         }
181       }
182     }
183   }
184   return NULL;
185 }
186 
UsbGadget()187 UsbGadget::UsbGadget()
188     : mMonitorCreated(false), mCurrentUsbFunctionsApplied(false) {
189   if (access(OS_DESC_PATH, R_OK) != 0) ALOGE("configfs setup not done yet");
190 }
191 
unlinkFunctions(const char * path)192 static int unlinkFunctions(const char *path) {
193   DIR *config = opendir(path);
194   struct dirent *function;
195   char filepath[MAX_FILE_PATH_LENGTH];
196   int ret = 0;
197 
198   if (config == NULL) return -1;
199 
200   // d_type does not seems to be supported in /config
201   // so filtering by name.
202   while (((function = readdir(config)) != NULL)) {
203     if ((strstr(function->d_name, FUNCTION_NAME) == NULL)) continue;
204     // build the path for each file in the folder.
205     sprintf(filepath, "%s/%s", path, function->d_name);
206     ret = remove(filepath);
207     if (ret) {
208       ALOGE("Unable  remove file %s errno:%d", filepath, errno);
209       break;
210     }
211   }
212 
213   closedir(config);
214   return ret;
215 }
216 
addEpollFd(const unique_fd & epfd,const unique_fd & fd)217 static int addEpollFd(const unique_fd &epfd, const unique_fd &fd) {
218   struct epoll_event event;
219   int ret;
220 
221   event.data.fd = fd;
222   event.events = EPOLLIN;
223 
224   ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event);
225   if (ret) ALOGE("epoll_ctl error %d", errno);
226 
227   return ret;
228 }
229 
getCurrentUsbFunctions(const sp<V1_0::IUsbGadgetCallback> & callback)230 Return<void> UsbGadget::getCurrentUsbFunctions(
231     const sp<V1_0::IUsbGadgetCallback> &callback) {
232   Return<void> ret = callback->getCurrentUsbFunctionsCb(
233       mCurrentUsbFunctions, mCurrentUsbFunctionsApplied
234                                 ? Status::FUNCTIONS_APPLIED
235                                 : Status::FUNCTIONS_NOT_APPLIED);
236   if (!ret.isOk())
237     ALOGE("Call to getCurrentUsbFunctionsCb failed %s",
238           ret.description().c_str());
239 
240   return Void();
241 }
242 
tearDownGadget()243 V1_0::Status UsbGadget::tearDownGadget() {
244   ALOGI("setCurrentUsbFunctions None");
245 
246   if (!WriteStringToFile("none", PULLUP_PATH))
247     ALOGI("Gadget cannot be pulled down");
248 
249   if (!WriteStringToFile("0", DEVICE_CLASS_PATH)) return Status::ERROR;
250 
251   if (!WriteStringToFile("0", DEVICE_SUB_CLASS_PATH)) return Status::ERROR;
252 
253   if (!WriteStringToFile("0", DEVICE_PROTOCOL_PATH)) return Status::ERROR;
254 
255   if (!WriteStringToFile("0", DESC_USE_PATH)) return Status::ERROR;
256 
257   if (unlinkFunctions(CONFIG_PATH)) return Status::ERROR;
258 
259   if (mMonitorCreated) {
260     uint64_t flag = 100;
261     unsigned long ret;
262 
263     // Stop the monitor thread by writing into signal fd.
264     ret = TEMP_FAILURE_RETRY(write(mEventFd, &flag, sizeof(flag)));
265     if (ret < 0) {
266         ALOGE("Error writing errno=%d", errno);
267     } else if (ret < sizeof(flag)) {
268         ALOGE("Short write length=%zd", ret);
269     }
270 
271     ALOGI("mMonitor signalled to exit");
272     mMonitor->join();
273     mMonitorCreated = false;
274     ALOGI("mMonitor destroyed");
275   } else {
276     ALOGI("mMonitor not running");
277   }
278 
279   mInotifyFd.reset(-1);
280   mEventFd.reset(-1);
281   mEpollFd.reset(-1);
282   mEndpointList.clear();
283   return Status::SUCCESS;
284 }
285 
linkFunction(const char * function,int index)286 static int linkFunction(const char *function, int index) {
287   char functionPath[MAX_FILE_PATH_LENGTH];
288   char link[MAX_FILE_PATH_LENGTH];
289 
290   sprintf(functionPath, "%s%s", FUNCTIONS_PATH, function);
291   sprintf(link, "%s%d", FUNCTION_PATH, index);
292   if (symlink(functionPath, link)) {
293     ALOGE("Cannot create symlink %s -> %s errno:%d", link, functionPath, errno);
294     return -1;
295   }
296   return 0;
297 }
298 
setVidPid(const char * vid,const char * pid)299 static V1_0::Status setVidPid(const char *vid, const char *pid) {
300   if (!WriteStringToFile(vid, VENDOR_ID_PATH)) return Status::ERROR;
301 
302   if (!WriteStringToFile(pid, PRODUCT_ID_PATH)) return Status::ERROR;
303 
304   return Status::SUCCESS;
305 }
306 
getVendorFunctions()307 static std::string getVendorFunctions() {
308   if (GetProperty(BUILD_TYPE, "") == "user") return "user";
309 
310   std::string bootMode = GetProperty(PERSISTENT_BOOT_MODE, "");
311   std::string persistVendorFunctions =
312       GetProperty(PERSISTENT_VENDOR_CONFIG, "");
313   std::string vendorFunctions = GetProperty(VENDOR_CONFIG, "");
314   std::string ret = "";
315 
316   if (vendorFunctions != "") {
317     ret = vendorFunctions;
318   } else if (bootMode == "usbradio") {
319     if (persistVendorFunctions != "")
320       ret = persistVendorFunctions;
321     else
322       ret = "diag";
323     // vendor.usb.config will reflect the current configured functions
324     SetProperty(VENDOR_CONFIG, ret);
325   }
326 
327   return ret;
328 }
329 
validateAndSetVidPid(uint64_t functions)330 static V1_0::Status validateAndSetVidPid(uint64_t functions) {
331   V1_0::Status ret = Status::SUCCESS;
332   std::string vendorFunctions = getVendorFunctions();
333 
334   switch (functions) {
335     case static_cast<uint64_t>(GadgetFunction::MTP):
336       if (vendorFunctions == "diag") {
337         ret = setVidPid("0x05C6", "0x901B");
338       } else {
339         if (!(vendorFunctions == "user" || vendorFunctions == ""))
340           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
341         ret = setVidPid("0x18d1", "0x4ee1");
342       }
343       break;
344     case GadgetFunction::ADB | GadgetFunction::MTP:
345       if (vendorFunctions == "diag") {
346         ret = setVidPid("0x05C6", "0x903A");
347       } else {
348         if (!(vendorFunctions == "user" || vendorFunctions == ""))
349           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
350         ret = setVidPid("0x18d1", "0x4ee2");
351       }
352       break;
353     case static_cast<uint64_t>(GadgetFunction::RNDIS):
354       if (vendorFunctions == "diag") {
355         ret = setVidPid("0x05C6", "0x902C");
356       } else if (vendorFunctions == "serial_cdev,diag") {
357         ret = setVidPid("0x05C6", "0x90B5");
358       } else {
359         if (!(vendorFunctions == "user" || vendorFunctions == ""))
360           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
361         ret = setVidPid("0x18d1", "0x4ee3");
362       }
363       break;
364     case GadgetFunction::ADB | GadgetFunction::RNDIS:
365       if (vendorFunctions == "diag") {
366         ret = setVidPid("0x05C6", "0x902D");
367       } else if (vendorFunctions == "serial_cdev,diag") {
368         ret = setVidPid("0x05C6", "0x90B6");
369       } else {
370         if (!(vendorFunctions == "user" || vendorFunctions == ""))
371           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
372         ret = setVidPid("0x18d1", "0x4ee4");
373       }
374       break;
375     case static_cast<uint64_t>(GadgetFunction::PTP):
376       if (!(vendorFunctions == "user" || vendorFunctions == ""))
377         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
378       ret = setVidPid("0x18d1", "0x4ee5");
379       break;
380     case GadgetFunction::ADB | GadgetFunction::PTP:
381       if (!(vendorFunctions == "user" || vendorFunctions == ""))
382         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
383       ret = setVidPid("0x18d1", "0x4ee6");
384       break;
385     case static_cast<uint64_t>(GadgetFunction::ADB):
386       if (vendorFunctions == "diag") {
387         ret = setVidPid("0x05C6", "0x901D");
388       } else if (vendorFunctions == "diag,serial_cdev,rmnet_gsi") {
389         ret = setVidPid("0x05C6", "0x9091");
390       } else if (vendorFunctions == "diag,serial_cdev") {
391         ret = setVidPid("0x05C6", "0x901F");
392       } else {
393         if (!(vendorFunctions == "user" || vendorFunctions == ""))
394           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
395         ret = setVidPid("0x18d1", "0x4ee7");
396       }
397       break;
398     case static_cast<uint64_t>(GadgetFunction::MIDI):
399       if (!(vendorFunctions == "user" || vendorFunctions == ""))
400         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
401       ret = setVidPid("0x18d1", "0x4ee8");
402       break;
403     case GadgetFunction::ADB | GadgetFunction::MIDI:
404       if (!(vendorFunctions == "user" || vendorFunctions == ""))
405         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
406       ret = setVidPid("0x18d1", "0x4ee9");
407       break;
408     case static_cast<uint64_t>(GadgetFunction::ACCESSORY):
409       if (!(vendorFunctions == "user" || vendorFunctions == ""))
410         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
411       ret = setVidPid("0x18d1", "0x2d00");
412       break;
413     case GadgetFunction::ADB | GadgetFunction::ACCESSORY:
414       if (!(vendorFunctions == "user" || vendorFunctions == ""))
415         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
416       ret = setVidPid("0x18d1", "0x2d01");
417       break;
418     case static_cast<uint64_t>(GadgetFunction::AUDIO_SOURCE):
419       if (!(vendorFunctions == "user" || vendorFunctions == ""))
420         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
421       ret = setVidPid("0x18d1", "0x2d02");
422       break;
423     case GadgetFunction::ADB | GadgetFunction::AUDIO_SOURCE:
424       if (!(vendorFunctions == "user" || vendorFunctions == ""))
425         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
426       ret = setVidPid("0x18d1", "0x2d03");
427       break;
428     case GadgetFunction::ACCESSORY | GadgetFunction::AUDIO_SOURCE:
429       if (!(vendorFunctions == "user" || vendorFunctions == ""))
430         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
431       ret = setVidPid("0x18d1", "0x2d04");
432       break;
433     case GadgetFunction::ADB | GadgetFunction::ACCESSORY |
434          GadgetFunction::AUDIO_SOURCE:
435       if (!(vendorFunctions == "user" || vendorFunctions == ""))
436         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
437       ret = setVidPid("0x18d1", "0x2d05");
438       break;
439     default:
440       ALOGE("Combination not supported");
441       ret = Status::CONFIGURATION_NOT_SUPPORTED;
442   }
443   return ret;
444 }
445 
setupFunctions(uint64_t functions,const sp<V1_0::IUsbGadgetCallback> & callback,uint64_t timeout)446 V1_0::Status UsbGadget::setupFunctions(
447     uint64_t functions, const sp<V1_0::IUsbGadgetCallback> &callback,
448     uint64_t timeout) {
449   std::unique_lock<std::mutex> lk(mLock);
450 
451   unique_fd inotifyFd(inotify_init());
452   if (inotifyFd < 0) {
453     ALOGE("inotify init failed");
454     return Status::ERROR;
455   }
456 
457   bool ffsEnabled = false;
458   int i = 0;
459   std::string bootMode = GetProperty(PERSISTENT_BOOT_MODE, "");
460 
461   if (((functions & GadgetFunction::MTP) != 0)) {
462     ffsEnabled = true;
463     ALOGI("setCurrentUsbFunctions mtp");
464     if (!WriteStringToFile("1", DESC_USE_PATH)) return Status::ERROR;
465 
466     if (inotify_add_watch(inotifyFd, "/dev/usb-ffs/mtp/", IN_ALL_EVENTS) == -1)
467       return Status::ERROR;
468 
469     if (linkFunction("ffs.mtp", i++)) return Status::ERROR;
470 
471     // Add endpoints to be monitored.
472     mEndpointList.push_back("/dev/usb-ffs/mtp/ep1");
473     mEndpointList.push_back("/dev/usb-ffs/mtp/ep2");
474     mEndpointList.push_back("/dev/usb-ffs/mtp/ep3");
475   } else if (((functions & GadgetFunction::PTP) != 0)) {
476     ffsEnabled = true;
477     ALOGI("setCurrentUsbFunctions ptp");
478     if (!WriteStringToFile("1", DESC_USE_PATH)) return Status::ERROR;
479 
480     if (inotify_add_watch(inotifyFd, "/dev/usb-ffs/ptp/", IN_ALL_EVENTS) == -1)
481       return Status::ERROR;
482 
483 
484     if (linkFunction("ffs.ptp", i++)) return Status::ERROR;
485 
486     // Add endpoints to be monitored.
487     mEndpointList.push_back("/dev/usb-ffs/ptp/ep1");
488     mEndpointList.push_back("/dev/usb-ffs/ptp/ep2");
489     mEndpointList.push_back("/dev/usb-ffs/ptp/ep3");
490   }
491 
492   if ((functions & GadgetFunction::MIDI) != 0) {
493     ALOGI("setCurrentUsbFunctions MIDI");
494     if (linkFunction("midi.gs5", i++)) return Status::ERROR;
495   }
496 
497   if ((functions & GadgetFunction::ACCESSORY) != 0) {
498     ALOGI("setCurrentUsbFunctions Accessory");
499     if (linkFunction("accessory.gs2", i++)) return Status::ERROR;
500   }
501 
502   if ((functions & GadgetFunction::AUDIO_SOURCE) != 0) {
503     ALOGI("setCurrentUsbFunctions Audio Source");
504     if (linkFunction("audio_source.gs3", i++)) return Status::ERROR;
505   }
506 
507   if ((functions & GadgetFunction::RNDIS) != 0) {
508     ALOGI("setCurrentUsbFunctions rndis");
509     if (linkFunction("gsi.rndis", i++)) return Status::ERROR;
510   }
511 
512   std::string vendorFunctions = getVendorFunctions();
513   if (vendorFunctions != "") {
514     ALOGI("enable usbradio debug functions");
515     char *function = strtok(const_cast<char *>(vendorFunctions.c_str()), ",");
516     while (function != NULL) {
517       if (string(function) == "diag" && linkFunction("diag.diag", i++))
518         return Status::ERROR;
519       if (string(function) == "serial_cdev" && linkFunction("cser.dun.0", i++))
520         return Status::ERROR;
521       if (string(function) == "rmnet_gsi" && linkFunction("gsi.rmnet", i++))
522         return Status::ERROR;
523       function = strtok(NULL, ",");
524     }
525   }
526 
527   if ((functions & GadgetFunction::ADB) != 0) {
528     ffsEnabled = true;
529     ALOGI("setCurrentUsbFunctions Adb");
530     if (inotify_add_watch(inotifyFd, "/dev/usb-ffs/adb/", IN_ALL_EVENTS) == -1)
531       return Status::ERROR;
532 
533     if (linkFunction("ffs.adb", i++)) return Status::ERROR;
534     mEndpointList.push_back("/dev/usb-ffs/adb/ep1");
535     mEndpointList.push_back("/dev/usb-ffs/adb/ep2");
536     ALOGI("Service started");
537   }
538 
539   // Pull up the gadget right away when there are no ffs functions.
540   if (!ffsEnabled) {
541     if (!WriteStringToFile(GADGET_NAME, PULLUP_PATH)) return Status::ERROR;
542     mCurrentUsbFunctionsApplied = true;
543     if (callback)
544       callback->setCurrentUsbFunctionsCb(functions, Status::SUCCESS);
545     return Status::SUCCESS;
546   }
547 
548   unique_fd eventFd(eventfd(0, 0));
549   if (eventFd == -1) {
550     ALOGE("mEventFd failed to create %d", errno);
551     return Status::ERROR;
552   }
553 
554   unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
555   if (epollFd == -1) {
556     ALOGE("mEpollFd failed to create %d", errno);
557     return Status::ERROR;
558   }
559 
560   if (addEpollFd(epollFd, inotifyFd) == -1) return Status::ERROR;
561 
562   if (addEpollFd(epollFd, eventFd) == -1) return Status::ERROR;
563 
564   mEpollFd = move(epollFd);
565   mInotifyFd = move(inotifyFd);
566   mEventFd = move(eventFd);
567   gadgetPullup = false;
568 
569   // Monitors the ffs paths to pull up the gadget when descriptors are written.
570   // Also takes of the pulling up the gadget again if the userspace process
571   // dies and restarts.
572   mMonitor = unique_ptr<thread>(new thread(monitorFfs, this));
573   mMonitorCreated = true;
574   if (DEBUG) ALOGI("Mainthread in Cv");
575 
576   if (callback) {
577     if (mCv.wait_for(lk, timeout * 1ms, [] { return gadgetPullup; })) {
578       ALOGI("monitorFfs signalled true");
579     } else {
580       ALOGI("monitorFfs signalled error");
581       // continue monitoring as the descriptors might be written at a later
582       // point.
583     }
584     Return<void> ret = callback->setCurrentUsbFunctionsCb(
585         functions, gadgetPullup ? Status::SUCCESS : Status::ERROR);
586     if (!ret.isOk())
587       ALOGE("setCurrentUsbFunctionsCb error %s", ret.description().c_str());
588   }
589 
590   return Status::SUCCESS;
591 }
592 
setCurrentUsbFunctions(uint64_t functions,const sp<V1_0::IUsbGadgetCallback> & callback,uint64_t timeout)593 Return<void> UsbGadget::setCurrentUsbFunctions(
594     uint64_t functions, const sp<V1_0::IUsbGadgetCallback> &callback,
595     uint64_t timeout) {
596   std::unique_lock<std::mutex> lk(mLockSetCurrentFunction);
597 
598   mCurrentUsbFunctions = functions;
599   mCurrentUsbFunctionsApplied = false;
600 
601   // Unlink the gadget and stop the monitor if running.
602   V1_0::Status status = tearDownGadget();
603   if (status != Status::SUCCESS) {
604     goto error;
605   }
606 
607   ALOGI("Returned from tearDown gadget");
608 
609   // Leave the gadget pulled down to give time for the host to sense disconnect.
610   usleep(DISCONNECT_WAIT_US);
611 
612   if (functions == static_cast<uint64_t>(GadgetFunction::NONE)) {
613     if (callback == NULL) return Void();
614     Return<void> ret =
615         callback->setCurrentUsbFunctionsCb(functions, Status::SUCCESS);
616     if (!ret.isOk())
617       ALOGE("Error while calling setCurrentUsbFunctionsCb %s",
618             ret.description().c_str());
619     return Void();
620   }
621 
622   status = validateAndSetVidPid(functions);
623 
624   if (status != Status::SUCCESS) {
625     goto error;
626   }
627 
628   status = setupFunctions(functions, callback, timeout);
629   if (status != Status::SUCCESS) {
630     goto error;
631   }
632 
633   ALOGI("Usb Gadget setcurrent functions called successfully");
634   return Void();
635 
636 error:
637   ALOGI("Usb Gadget setcurrent functions failed");
638   if (callback == NULL) return Void();
639   Return<void> ret = callback->setCurrentUsbFunctionsCb(functions, status);
640   if (!ret.isOk())
641     ALOGE("Error while calling setCurrentUsbFunctionsCb %s",
642           ret.description().c_str());
643   return Void();
644 }
645 }  // namespace implementation
646 }  // namespace V1_0
647 }  // namespace gadget
648 }  // namespace usb
649 }  // namespace hardware
650 }  // namespace android
651