• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.1-service.bonito"
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_1 {
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 
reset()286 Return<Status> UsbGadget::reset() {
287     if (!WriteStringToFile("none", PULLUP_PATH)) {
288         ALOGI("Gadget cannot be pulled down");
289         return Status::ERROR;
290     }
291 
292     return Status::SUCCESS;
293 }
294 
linkFunction(const char * function,int index)295 static int linkFunction(const char *function, int index) {
296   char functionPath[MAX_FILE_PATH_LENGTH];
297   char link[MAX_FILE_PATH_LENGTH];
298 
299   sprintf(functionPath, "%s%s", FUNCTIONS_PATH, function);
300   sprintf(link, "%s%d", FUNCTION_PATH, index);
301   if (symlink(functionPath, link)) {
302     ALOGE("Cannot create symlink %s -> %s errno:%d", link, functionPath, errno);
303     return -1;
304   }
305   return 0;
306 }
307 
setVidPid(const char * vid,const char * pid)308 static V1_0::Status setVidPid(const char *vid, const char *pid) {
309   if (!WriteStringToFile(vid, VENDOR_ID_PATH)) return Status::ERROR;
310 
311   if (!WriteStringToFile(pid, PRODUCT_ID_PATH)) return Status::ERROR;
312 
313   return Status::SUCCESS;
314 }
315 
getVendorFunctions()316 static std::string getVendorFunctions() {
317   if (GetProperty(BUILD_TYPE, "") == "user") return "user";
318 
319   std::string bootMode = GetProperty(PERSISTENT_BOOT_MODE, "");
320   std::string persistVendorFunctions =
321       GetProperty(PERSISTENT_VENDOR_CONFIG, "");
322   std::string vendorFunctions = GetProperty(VENDOR_CONFIG, "");
323   std::string ret = "";
324 
325   if (vendorFunctions != "") {
326     ret = vendorFunctions;
327   } else if (bootMode == "usbradio") {
328     if (persistVendorFunctions != "")
329       ret = persistVendorFunctions;
330     else
331       ret = "diag";
332     // vendor.usb.config will reflect the current configured functions
333     SetProperty(VENDOR_CONFIG, ret);
334   }
335 
336   return ret;
337 }
338 
validateAndSetVidPid(uint64_t functions)339 static V1_0::Status validateAndSetVidPid(uint64_t functions) {
340   V1_0::Status ret = Status::SUCCESS;
341   std::string vendorFunctions = getVendorFunctions();
342 
343   switch (functions) {
344     case static_cast<uint64_t>(GadgetFunction::MTP):
345       if (vendorFunctions == "diag") {
346         ret = setVidPid("0x05C6", "0x901B");
347       } else {
348         if (!(vendorFunctions == "user" || vendorFunctions == ""))
349           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
350         ret = setVidPid("0x18d1", "0x4ee1");
351       }
352       break;
353     case GadgetFunction::ADB | GadgetFunction::MTP:
354       if (vendorFunctions == "diag") {
355         ret = setVidPid("0x05C6", "0x903A");
356       } else {
357         if (!(vendorFunctions == "user" || vendorFunctions == ""))
358           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
359         ret = setVidPid("0x18d1", "0x4ee2");
360       }
361       break;
362     case static_cast<uint64_t>(GadgetFunction::RNDIS):
363       if (vendorFunctions == "diag") {
364         ret = setVidPid("0x05C6", "0x902C");
365       } else if (vendorFunctions == "serial_cdev,diag") {
366         ret = setVidPid("0x05C6", "0x90B5");
367       } else {
368         if (!(vendorFunctions == "user" || vendorFunctions == ""))
369           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
370         ret = setVidPid("0x18d1", "0x4ee3");
371       }
372       break;
373     case GadgetFunction::ADB | GadgetFunction::RNDIS:
374       if (vendorFunctions == "diag") {
375         ret = setVidPid("0x05C6", "0x902D");
376       } else if (vendorFunctions == "serial_cdev,diag") {
377         ret = setVidPid("0x05C6", "0x90B6");
378       } else {
379         if (!(vendorFunctions == "user" || vendorFunctions == ""))
380           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
381         ret = setVidPid("0x18d1", "0x4ee4");
382       }
383       break;
384     case static_cast<uint64_t>(GadgetFunction::PTP):
385       if (!(vendorFunctions == "user" || vendorFunctions == ""))
386         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
387       ret = setVidPid("0x18d1", "0x4ee5");
388       break;
389     case GadgetFunction::ADB | GadgetFunction::PTP:
390       if (!(vendorFunctions == "user" || vendorFunctions == ""))
391         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
392       ret = setVidPid("0x18d1", "0x4ee6");
393       break;
394     case static_cast<uint64_t>(GadgetFunction::ADB):
395       if (vendorFunctions == "diag") {
396         ret = setVidPid("0x05C6", "0x901D");
397       } else if (vendorFunctions == "diag,serial_cdev,rmnet_gsi") {
398         ret = setVidPid("0x05C6", "0x9091");
399       } else if (vendorFunctions == "diag,serial_cdev") {
400         ret = setVidPid("0x05C6", "0x901F");
401       } else {
402         if (!(vendorFunctions == "user" || vendorFunctions == ""))
403           ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
404         ret = setVidPid("0x18d1", "0x4ee7");
405       }
406       break;
407     case static_cast<uint64_t>(GadgetFunction::MIDI):
408       if (!(vendorFunctions == "user" || vendorFunctions == ""))
409         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
410       ret = setVidPid("0x18d1", "0x4ee8");
411       break;
412     case GadgetFunction::ADB | GadgetFunction::MIDI:
413       if (!(vendorFunctions == "user" || vendorFunctions == ""))
414         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
415       ret = setVidPid("0x18d1", "0x4ee9");
416       break;
417     case static_cast<uint64_t>(GadgetFunction::ACCESSORY):
418       if (!(vendorFunctions == "user" || vendorFunctions == ""))
419         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
420       ret = setVidPid("0x18d1", "0x2d00");
421       break;
422     case GadgetFunction::ADB | GadgetFunction::ACCESSORY:
423       if (!(vendorFunctions == "user" || vendorFunctions == ""))
424         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
425       ret = setVidPid("0x18d1", "0x2d01");
426       break;
427     case static_cast<uint64_t>(GadgetFunction::AUDIO_SOURCE):
428       if (!(vendorFunctions == "user" || vendorFunctions == ""))
429         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
430       ret = setVidPid("0x18d1", "0x2d02");
431       break;
432     case GadgetFunction::ADB | GadgetFunction::AUDIO_SOURCE:
433       if (!(vendorFunctions == "user" || vendorFunctions == ""))
434         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
435       ret = setVidPid("0x18d1", "0x2d03");
436       break;
437     case GadgetFunction::ACCESSORY | GadgetFunction::AUDIO_SOURCE:
438       if (!(vendorFunctions == "user" || vendorFunctions == ""))
439         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
440       ret = setVidPid("0x18d1", "0x2d04");
441       break;
442     case GadgetFunction::ADB | GadgetFunction::ACCESSORY |
443          GadgetFunction::AUDIO_SOURCE:
444       if (!(vendorFunctions == "user" || vendorFunctions == ""))
445         ALOGE("Invalid vendorFunctions set: %s", vendorFunctions.c_str());
446       ret = setVidPid("0x18d1", "0x2d05");
447       break;
448     default:
449       ALOGE("Combination not supported");
450       ret = Status::CONFIGURATION_NOT_SUPPORTED;
451   }
452   return ret;
453 }
454 
setupFunctions(uint64_t functions,const sp<V1_0::IUsbGadgetCallback> & callback,uint64_t timeout)455 V1_0::Status UsbGadget::setupFunctions(
456     uint64_t functions, const sp<V1_0::IUsbGadgetCallback> &callback,
457     uint64_t timeout) {
458   std::unique_lock<std::mutex> lk(mLock);
459 
460   unique_fd inotifyFd(inotify_init());
461   if (inotifyFd < 0) {
462     ALOGE("inotify init failed");
463     return Status::ERROR;
464   }
465 
466   bool ffsEnabled = false;
467   int i = 0;
468   std::string bootMode = GetProperty(PERSISTENT_BOOT_MODE, "");
469 
470   if (((functions & GadgetFunction::MTP) != 0)) {
471     ffsEnabled = true;
472     ALOGI("setCurrentUsbFunctions mtp");
473     if (!WriteStringToFile("1", DESC_USE_PATH)) return Status::ERROR;
474 
475     if (inotify_add_watch(inotifyFd, "/dev/usb-ffs/mtp/", IN_ALL_EVENTS) == -1)
476       return Status::ERROR;
477 
478     if (linkFunction("ffs.mtp", i++)) return Status::ERROR;
479 
480     // Add endpoints to be monitored.
481     mEndpointList.push_back("/dev/usb-ffs/mtp/ep1");
482     mEndpointList.push_back("/dev/usb-ffs/mtp/ep2");
483     mEndpointList.push_back("/dev/usb-ffs/mtp/ep3");
484   } else if (((functions & GadgetFunction::PTP) != 0)) {
485     ffsEnabled = true;
486     ALOGI("setCurrentUsbFunctions ptp");
487     if (!WriteStringToFile("1", DESC_USE_PATH)) return Status::ERROR;
488 
489     if (inotify_add_watch(inotifyFd, "/dev/usb-ffs/ptp/", IN_ALL_EVENTS) == -1)
490       return Status::ERROR;
491 
492 
493     if (linkFunction("ffs.ptp", i++)) return Status::ERROR;
494 
495     // Add endpoints to be monitored.
496     mEndpointList.push_back("/dev/usb-ffs/ptp/ep1");
497     mEndpointList.push_back("/dev/usb-ffs/ptp/ep2");
498     mEndpointList.push_back("/dev/usb-ffs/ptp/ep3");
499   }
500 
501   if ((functions & GadgetFunction::MIDI) != 0) {
502     ALOGI("setCurrentUsbFunctions MIDI");
503     if (linkFunction("midi.gs5", i++)) return Status::ERROR;
504   }
505 
506   if ((functions & GadgetFunction::ACCESSORY) != 0) {
507     ALOGI("setCurrentUsbFunctions Accessory");
508     if (linkFunction("accessory.gs2", i++)) return Status::ERROR;
509   }
510 
511   if ((functions & GadgetFunction::AUDIO_SOURCE) != 0) {
512     ALOGI("setCurrentUsbFunctions Audio Source");
513     if (linkFunction("audio_source.gs3", i++)) return Status::ERROR;
514   }
515 
516   if ((functions & GadgetFunction::RNDIS) != 0) {
517     ALOGI("setCurrentUsbFunctions rndis");
518     if (linkFunction("gsi.rndis", i++)) return Status::ERROR;
519   }
520 
521   std::string vendorFunctions = getVendorFunctions();
522   if (vendorFunctions != "") {
523     ALOGI("enable usbradio debug functions");
524     char *function = strtok(const_cast<char *>(vendorFunctions.c_str()), ",");
525     while (function != NULL) {
526       if (string(function) == "diag" && linkFunction("diag.diag", i++))
527         return Status::ERROR;
528       if (string(function) == "serial_cdev" && linkFunction("cser.dun.0", i++))
529         return Status::ERROR;
530       if (string(function) == "rmnet_gsi" && linkFunction("gsi.rmnet", i++))
531         return Status::ERROR;
532       function = strtok(NULL, ",");
533     }
534   }
535 
536   if ((functions & GadgetFunction::ADB) != 0) {
537     ffsEnabled = true;
538     ALOGI("setCurrentUsbFunctions Adb");
539     if (!WriteStringToFile("1", DESC_USE_PATH))
540       return Status::ERROR;
541     if (inotify_add_watch(inotifyFd, "/dev/usb-ffs/adb/", IN_ALL_EVENTS) == -1)
542       return Status::ERROR;
543 
544     if (linkFunction("ffs.adb", i++)) return Status::ERROR;
545     mEndpointList.push_back("/dev/usb-ffs/adb/ep1");
546     mEndpointList.push_back("/dev/usb-ffs/adb/ep2");
547     ALOGI("Service started");
548   }
549 
550   // Pull up the gadget right away when there are no ffs functions.
551   if (!ffsEnabled) {
552     if (!WriteStringToFile(GADGET_NAME, PULLUP_PATH)) return Status::ERROR;
553     mCurrentUsbFunctionsApplied = true;
554     if (callback)
555       callback->setCurrentUsbFunctionsCb(functions, Status::SUCCESS);
556     return Status::SUCCESS;
557   }
558 
559   unique_fd eventFd(eventfd(0, 0));
560   if (eventFd == -1) {
561     ALOGE("mEventFd failed to create %d", errno);
562     return Status::ERROR;
563   }
564 
565   unique_fd epollFd(epoll_create(2));
566   if (epollFd == -1) {
567     ALOGE("mEpollFd failed to create %d", errno);
568     return Status::ERROR;
569   }
570 
571   if (addEpollFd(epollFd, inotifyFd) == -1) return Status::ERROR;
572 
573   if (addEpollFd(epollFd, eventFd) == -1) return Status::ERROR;
574 
575   mEpollFd = move(epollFd);
576   mInotifyFd = move(inotifyFd);
577   mEventFd = move(eventFd);
578   gadgetPullup = false;
579 
580   // Monitors the ffs paths to pull up the gadget when descriptors are written.
581   // Also takes of the pulling up the gadget again if the userspace process
582   // dies and restarts.
583   mMonitor = unique_ptr<thread>(new thread(monitorFfs, this));
584   mMonitorCreated = true;
585   if (DEBUG) ALOGI("Mainthread in Cv");
586 
587   if (callback) {
588     if (mCv.wait_for(lk, timeout * 1ms, [] { return gadgetPullup; })) {
589       ALOGI("monitorFfs signalled true");
590     } else {
591       ALOGI("monitorFfs signalled error");
592       // continue monitoring as the descriptors might be written at a later
593       // point.
594     }
595     Return<void> ret = callback->setCurrentUsbFunctionsCb(
596         functions, gadgetPullup ? Status::SUCCESS : Status::ERROR);
597     if (!ret.isOk())
598       ALOGE("setCurrentUsbFunctionsCb error %s", ret.description().c_str());
599   }
600 
601   return Status::SUCCESS;
602 }
603 
setCurrentUsbFunctions(uint64_t functions,const sp<V1_0::IUsbGadgetCallback> & callback,uint64_t timeout)604 Return<void> UsbGadget::setCurrentUsbFunctions(
605     uint64_t functions, const sp<V1_0::IUsbGadgetCallback> &callback,
606     uint64_t timeout) {
607   std::unique_lock<std::mutex> lk(mLockSetCurrentFunction);
608 
609   mCurrentUsbFunctions = functions;
610   mCurrentUsbFunctionsApplied = false;
611 
612   // Unlink the gadget and stop the monitor if running.
613   V1_0::Status status = tearDownGadget();
614   if (status != Status::SUCCESS) {
615     goto error;
616   }
617 
618   ALOGI("Returned from tearDown gadget");
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