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