• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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@1.3-service.sunfish"
18 
19 #include <android-base/logging.h>
20 #include <android-base/properties.h>
21 #include <assert.h>
22 #include <dirent.h>
23 #include <pthread.h>
24 #include <stdio.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 #include <chrono>
28 #include <regex>
29 #include <thread>
30 #include <unordered_map>
31 
32 #include <cutils/uevent.h>
33 #include <sys/epoll.h>
34 #include <utils/Errors.h>
35 #include <utils/StrongPointer.h>
36 
37 #include "Usb.h"
38 
39 using android::base::GetProperty;
40 
41 namespace android {
42 namespace hardware {
43 namespace usb {
44 namespace V1_3 {
45 namespace implementation {
46 
enableUsbDataSignal(bool enable)47 Return<bool> Usb::enableUsbDataSignal(bool enable) {
48     bool result = true;
49 
50     ALOGI("Userspace turn %s USB data signaling", enable ? "on" : "off");
51 
52     if (enable) {
53         if (!WriteStringToFile("1", USB_DATA_PATH)) {
54             ALOGE("Not able to turn on usb connection notification");
55             result = false;
56         }
57 
58         if (!WriteStringToFile(kGadgetName, PULLUP_PATH)) {
59             ALOGE("Gadget cannot be pulled up");
60             result = false;
61         }
62     } else {
63         if (!WriteStringToFile("1", ID_PATH)) {
64             ALOGE("Not able to turn off host mode");
65             result = false;
66         }
67 
68         if (!WriteStringToFile("0", VBUS_PATH)) {
69             ALOGE("Not able to set Vbus state");
70             result = false;
71         }
72 
73         if (!WriteStringToFile("0", USB_DATA_PATH)) {
74             ALOGE("Not able to turn on usb connection notification");
75             result = false;
76         }
77 
78         if (!WriteStringToFile("none", PULLUP_PATH)) {
79             ALOGE("Gadget cannot be pulled down");
80             result = false;
81         }
82     }
83 
84     return result;
85 }
86 
87 // Set by the signal handler to destroy the thread
88 volatile bool destroyThread;
89 
90 constexpr char kEnabledPath[] = "/sys/class/power_supply/usb/moisture_detection_enabled";
91 constexpr char kDetectedPath[] = "/sys/class/power_supply/usb/moisture_detected";
92 constexpr char kConsole[] = "init.svc.console";
93 constexpr char kDisableContatminantDetection[] = "vendor.usb.contaminantdisable";
94 
95 void queryVersionHelper(implementation::Usb *usb, hidl_vec<PortStatus> *currentPortStatus_1_2);
96 
readFile(const std::string & filename,std::string * contents)97 int32_t readFile(const std::string &filename, std::string *contents) {
98     FILE *fp;
99     ssize_t read = 0;
100     char *line = NULL;
101     size_t len = 0;
102 
103     fp = fopen(filename.c_str(), "r");
104     if (fp != NULL) {
105         if ((read = getline(&line, &len, fp)) != -1) {
106             char *pos;
107             if ((pos = strchr(line, '\n')) != NULL)
108                 *pos = '\0';
109             *contents = line;
110         }
111         free(line);
112         fclose(fp);
113         return 0;
114     } else {
115         ALOGE("fopen failed");
116     }
117 
118     return -1;
119 }
120 
writeFile(const std::string & filename,const std::string & contents)121 int32_t writeFile(const std::string &filename, const std::string &contents) {
122     FILE *fp;
123     std::string written;
124 
125     fp = fopen(filename.c_str(), "w");
126     if (fp != NULL) {
127         // FAILURE RETRY
128         int ret = fputs(contents.c_str(), fp);
129         fclose(fp);
130         if ((ret != EOF) && !readFile(filename, &written) && written == contents)
131             return 0;
132     }
133     return -1;
134 }
135 
queryMoistureDetectionStatus(hidl_vec<PortStatus> * currentPortStatus_1_2)136 Status queryMoistureDetectionStatus(hidl_vec<PortStatus> *currentPortStatus_1_2) {
137     std::string enabled, status;
138 
139     if (currentPortStatus_1_2 == NULL || currentPortStatus_1_2->size() == 0) {
140         ALOGE("currentPortStatus_1_2 is not available");
141         return Status::ERROR;
142     }
143 
144     (*currentPortStatus_1_2)[0].supportedContaminantProtectionModes = 0;
145     (*currentPortStatus_1_2)[0].supportedContaminantProtectionModes |=
146         V1_2::ContaminantProtectionMode::FORCE_SINK;
147     (*currentPortStatus_1_2)[0].contaminantProtectionStatus = V1_2::ContaminantProtectionStatus::NONE;
148     (*currentPortStatus_1_2)[0].contaminantDetectionStatus = V1_2::ContaminantDetectionStatus::DISABLED;
149     (*currentPortStatus_1_2)[0].supportsEnableContaminantPresenceDetection = true;
150     (*currentPortStatus_1_2)[0].supportsEnableContaminantPresenceProtection = false;
151 
152     if (readFile(kEnabledPath, &enabled)) {
153         ALOGE("Failed to open moisture_detection_enabled");
154         return Status::ERROR;
155     }
156 
157     if (enabled == "1") {
158         if (readFile(kDetectedPath, &status)) {
159             ALOGE("Failed to open moisture_detected");
160             return Status::ERROR;
161         }
162         if (status == "1") {
163             (*currentPortStatus_1_2)[0].contaminantDetectionStatus =
164                 V1_2::ContaminantDetectionStatus::DETECTED;
165             (*currentPortStatus_1_2)[0].contaminantProtectionStatus =
166                 V1_2::ContaminantProtectionStatus::FORCE_SINK;
167         } else
168             (*currentPortStatus_1_2)[0].contaminantDetectionStatus =
169                 V1_2::ContaminantDetectionStatus::NOT_DETECTED;
170     }
171 
172      ALOGI("ContaminantDetectionStatus:%d ContaminantProtectionStatus:%d",
173 	   (*currentPortStatus_1_2)[0].contaminantDetectionStatus,
174 	   (*currentPortStatus_1_2)[0].contaminantProtectionStatus);
175 
176     return Status::SUCCESS;
177 }
178 
enableContaminantPresenceDetection(const hidl_string &,bool enable)179 Return<void> Usb::enableContaminantPresenceDetection(const hidl_string & /*portName*/,
180                                                      bool enable) {
181 
182     std::string status = GetProperty(kConsole, "");
183     std::string disable = GetProperty(kDisableContatminantDetection, "");
184 
185 
186     if (status != "running" && disable != "true")
187         writeFile(kEnabledPath, enable ? "1" : "0");
188 
189     hidl_vec<PortStatus> currentPortStatus_1_2;
190 
191     queryVersionHelper(this, &currentPortStatus_1_2);
192     return Void();
193 }
194 
enableContaminantPresenceProtection(const hidl_string &,bool)195 Return<void> Usb::enableContaminantPresenceProtection(const hidl_string & /*portName*/,
196                                                       bool /*enable*/) {
197     hidl_vec<PortStatus> currentPortStatus_1_2;
198 
199     queryVersionHelper(this, &currentPortStatus_1_2);
200     return Void();
201 }
202 
appendRoleNodeHelper(const std::string & portName,PortRoleType type)203 std::string appendRoleNodeHelper(const std::string &portName, PortRoleType type) {
204     std::string node("/sys/class/typec/" + portName);
205 
206     switch (type) {
207         case PortRoleType::DATA_ROLE:
208             return node + "/data_role";
209         case PortRoleType::POWER_ROLE:
210             return node + "/power_role";
211         case PortRoleType::MODE:
212             return node + "/port_type";
213         default:
214             return "";
215     }
216 }
217 
convertRoletoString(PortRole role)218 std::string convertRoletoString(PortRole role) {
219     if (role.type == PortRoleType::POWER_ROLE) {
220         if (role.role == static_cast<uint32_t>(PortPowerRole::SOURCE))
221             return "source";
222         else if (role.role == static_cast<uint32_t>(PortPowerRole::SINK))
223             return "sink";
224     } else if (role.type == PortRoleType::DATA_ROLE) {
225         if (role.role == static_cast<uint32_t>(PortDataRole::HOST))
226             return "host";
227         if (role.role == static_cast<uint32_t>(PortDataRole::DEVICE))
228             return "device";
229     } else if (role.type == PortRoleType::MODE) {
230         if (role.role == static_cast<uint32_t>(PortMode_1_1::UFP))
231             return "sink";
232         if (role.role == static_cast<uint32_t>(PortMode_1_1::DFP))
233             return "source";
234     }
235     return "none";
236 }
237 
extractRole(std::string * roleName)238 void extractRole(std::string *roleName) {
239     std::size_t first, last;
240 
241     first = roleName->find("[");
242     last = roleName->find("]");
243 
244     if (first != std::string::npos && last != std::string::npos) {
245         *roleName = roleName->substr(first + 1, last - first - 1);
246     }
247 }
248 
switchToDrp(const std::string & portName)249 void switchToDrp(const std::string &portName) {
250     std::string filename = appendRoleNodeHelper(std::string(portName.c_str()), PortRoleType::MODE);
251     FILE *fp;
252 
253     if (filename != "") {
254         fp = fopen(filename.c_str(), "w");
255         if (fp != NULL) {
256             int ret = fputs("dual", fp);
257             fclose(fp);
258             if (ret == EOF)
259                 ALOGE("Fatal: Error while switching back to drp");
260         } else {
261             ALOGE("Fatal: Cannot open file to switch back to drp");
262         }
263     } else {
264         ALOGE("Fatal: invalid node type");
265     }
266 }
267 
switchMode(const hidl_string & portName,const PortRole & newRole,struct Usb * usb)268 bool switchMode(const hidl_string &portName, const PortRole &newRole, struct Usb *usb) {
269     std::string filename = appendRoleNodeHelper(std::string(portName.c_str()), newRole.type);
270     std::string written;
271     FILE *fp;
272     bool roleSwitch = false;
273 
274     if (filename == "") {
275         ALOGE("Fatal: invalid node type");
276         return false;
277     }
278 
279     fp = fopen(filename.c_str(), "w");
280     if (fp != NULL) {
281         // Hold the lock here to prevent loosing connected signals
282         // as once the file is written the partner added signal
283         // can arrive anytime.
284         pthread_mutex_lock(&usb->mPartnerLock);
285         usb->mPartnerUp = false;
286         int ret = fputs(convertRoletoString(newRole).c_str(), fp);
287         fclose(fp);
288 
289         if (ret != EOF) {
290             struct timespec to;
291             struct timespec now;
292 
293         wait_again:
294             clock_gettime(CLOCK_MONOTONIC, &now);
295             to.tv_sec = now.tv_sec + PORT_TYPE_TIMEOUT;
296             to.tv_nsec = now.tv_nsec;
297 
298             int err = pthread_cond_timedwait(&usb->mPartnerCV, &usb->mPartnerLock, &to);
299             // There are no uevent signals which implies role swap timed out.
300             if (err == ETIMEDOUT) {
301                 ALOGI("uevents wait timedout");
302                 // Sanity check.
303             } else if (!usb->mPartnerUp) {
304                 goto wait_again;
305                 // Role switch succeeded since usb->mPartnerUp is true.
306             } else {
307                 roleSwitch = true;
308             }
309         } else {
310             ALOGI("Role switch failed while wrting to file");
311         }
312         pthread_mutex_unlock(&usb->mPartnerLock);
313     }
314 
315     if (!roleSwitch)
316         switchToDrp(std::string(portName.c_str()));
317 
318     return roleSwitch;
319 }
320 
Usb()321 Usb::Usb()
322     : mLock(PTHREAD_MUTEX_INITIALIZER),
323       mRoleSwitchLock(PTHREAD_MUTEX_INITIALIZER),
324       mPartnerLock(PTHREAD_MUTEX_INITIALIZER),
325       mPartnerUp(false) {
326     pthread_condattr_t attr;
327     if (pthread_condattr_init(&attr)) {
328         ALOGE("pthread_condattr_init failed: %s", strerror(errno));
329         abort();
330     }
331     if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)) {
332         ALOGE("pthread_condattr_setclock failed: %s", strerror(errno));
333         abort();
334     }
335     if (pthread_cond_init(&mPartnerCV, &attr)) {
336         ALOGE("pthread_cond_init failed: %s", strerror(errno));
337         abort();
338     }
339     if (pthread_condattr_destroy(&attr)) {
340         ALOGE("pthread_condattr_destroy failed: %s", strerror(errno));
341         abort();
342     }
343 }
344 
switchRole(const hidl_string & portName,const V1_0::PortRole & newRole)345 Return<void> Usb::switchRole(const hidl_string &portName, const V1_0::PortRole &newRole) {
346     std::string filename = appendRoleNodeHelper(std::string(portName.c_str()), newRole.type);
347     std::string written;
348     FILE *fp;
349     bool roleSwitch = false;
350 
351     if (filename == "") {
352         ALOGE("Fatal: invalid node type");
353         return Void();
354     }
355 
356     pthread_mutex_lock(&mRoleSwitchLock);
357 
358     ALOGI("filename write: %s role:%s", filename.c_str(), convertRoletoString(newRole).c_str());
359 
360     if (newRole.type == PortRoleType::MODE) {
361         roleSwitch = switchMode(portName, newRole, this);
362     } else {
363         fp = fopen(filename.c_str(), "w");
364         if (fp != NULL) {
365             int ret = fputs(convertRoletoString(newRole).c_str(), fp);
366             fclose(fp);
367             if ((ret != EOF) && !readFile(filename, &written)) {
368                 extractRole(&written);
369                 ALOGI("written: %s", written.c_str());
370                 if (written == convertRoletoString(newRole)) {
371                     roleSwitch = true;
372                 } else {
373                     ALOGE("Role switch failed");
374                 }
375             } else {
376                 ALOGE("failed to update the new role");
377             }
378         } else {
379             ALOGE("fopen failed");
380         }
381     }
382 
383     pthread_mutex_lock(&mLock);
384     if (mCallback_1_0 != NULL) {
385         Return<void> ret = mCallback_1_0->notifyRoleSwitchStatus(
386             portName, newRole, roleSwitch ? Status::SUCCESS : Status::ERROR);
387         if (!ret.isOk())
388             ALOGE("RoleSwitchStatus error %s", ret.description().c_str());
389     } else {
390         ALOGE("Not notifying the userspace. Callback is not set");
391     }
392     pthread_mutex_unlock(&mLock);
393     pthread_mutex_unlock(&mRoleSwitchLock);
394 
395     return Void();
396 }
397 
getAccessoryConnected(const std::string & portName,std::string * accessory)398 Status getAccessoryConnected(const std::string &portName, std::string *accessory) {
399     std::string filename = "/sys/class/typec/" + portName + "-partner/accessory_mode";
400 
401     if (readFile(filename, accessory)) {
402         ALOGE("getAccessoryConnected: Failed to open filesystem node: %s", filename.c_str());
403         return Status::ERROR;
404     }
405 
406     return Status::SUCCESS;
407 }
408 
getCurrentRoleHelper(const std::string & portName,bool connected,PortRoleType type,uint32_t * currentRole)409 Status getCurrentRoleHelper(const std::string &portName, bool connected, PortRoleType type,
410                             uint32_t *currentRole) {
411     std::string filename;
412     std::string roleName;
413     std::string accessory;
414 
415     // Mode
416 
417     if (type == PortRoleType::POWER_ROLE) {
418         filename = "/sys/class/typec/" + portName + "/power_role";
419         *currentRole = static_cast<uint32_t>(PortPowerRole::NONE);
420     } else if (type == PortRoleType::DATA_ROLE) {
421         filename = "/sys/class/typec/" + portName + "/data_role";
422         *currentRole = static_cast<uint32_t>(PortDataRole::NONE);
423     } else if (type == PortRoleType::MODE) {
424         filename = "/sys/class/typec/" + portName + "/data_role";
425         *currentRole = static_cast<uint32_t>(PortMode_1_1::NONE);
426     } else {
427         return Status::ERROR;
428     }
429 
430     if (!connected)
431         return Status::SUCCESS;
432 
433     if (type == PortRoleType::MODE) {
434         if (getAccessoryConnected(portName, &accessory) != Status::SUCCESS) {
435             return Status::ERROR;
436         }
437         if (accessory == "analog_audio") {
438             *currentRole = static_cast<uint32_t>(PortMode_1_1::AUDIO_ACCESSORY);
439             return Status::SUCCESS;
440         } else if (accessory == "debug") {
441             *currentRole = static_cast<uint32_t>(PortMode_1_1::DEBUG_ACCESSORY);
442             return Status::SUCCESS;
443         }
444     }
445 
446     if (readFile(filename, &roleName)) {
447         ALOGE("getCurrentRole: Failed to open filesystem node: %s", filename.c_str());
448         return Status::ERROR;
449     }
450 
451     extractRole(&roleName);
452 
453     if (roleName == "source") {
454         *currentRole = static_cast<uint32_t>(PortPowerRole::SOURCE);
455     } else if (roleName == "sink") {
456         *currentRole = static_cast<uint32_t>(PortPowerRole::SINK);
457     } else if (roleName == "host") {
458         if (type == PortRoleType::DATA_ROLE)
459             *currentRole = static_cast<uint32_t>(PortDataRole::HOST);
460         else
461             *currentRole = static_cast<uint32_t>(PortMode_1_1::DFP);
462     } else if (roleName == "device") {
463         if (type == PortRoleType::DATA_ROLE)
464             *currentRole = static_cast<uint32_t>(PortDataRole::DEVICE);
465         else
466             *currentRole = static_cast<uint32_t>(PortMode_1_1::UFP);
467     } else if (roleName != "none") {
468         /* case for none has already been addressed.
469          * so we check if the role isnt none.
470          */
471         return Status::UNRECOGNIZED_ROLE;
472     }
473 
474     return Status::SUCCESS;
475 }
476 
getTypeCPortNamesHelper(std::unordered_map<std::string,bool> * names)477 Status getTypeCPortNamesHelper(std::unordered_map<std::string, bool> *names) {
478     DIR *dp;
479 
480     dp = opendir("/sys/class/typec");
481     if (dp != NULL) {
482         struct dirent *ep;
483 
484         while ((ep = readdir(dp))) {
485             if (ep->d_type == DT_LNK) {
486                 if (std::string::npos == std::string(ep->d_name).find("-partner")) {
487                     std::unordered_map<std::string, bool>::const_iterator portName =
488                         names->find(ep->d_name);
489                     if (portName == names->end()) {
490                         names->insert({ep->d_name, false});
491                     }
492                 } else {
493                     (*names)[std::strtok(ep->d_name, "-")] = true;
494                 }
495             }
496         }
497         closedir(dp);
498         return Status::SUCCESS;
499     }
500 
501     ALOGE("Failed to open /sys/class/typec");
502     return Status::ERROR;
503 }
504 
canSwitchRoleHelper(const std::string & portName,PortRoleType)505 bool canSwitchRoleHelper(const std::string &portName, PortRoleType /*type*/) {
506     std::string filename = "/sys/class/typec/" + portName + "-partner/supports_usb_power_delivery";
507     std::string supportsPD;
508 
509     if (!readFile(filename, &supportsPD)) {
510         if (supportsPD == "yes") {
511             return true;
512         }
513     }
514 
515     return false;
516 }
517 
518 /*
519  * Reuse the same method for both V1_0 and V1_1 callback objects.
520  * The caller of this method would reconstruct the V1_0::PortStatus
521  * object if required.
522  */
getPortStatusHelper(hidl_vec<PortStatus> * currentPortStatus_1_2,HALVersion version)523 Status getPortStatusHelper(hidl_vec<PortStatus> *currentPortStatus_1_2, HALVersion version) {
524     std::unordered_map<std::string, bool> names;
525     Status result = getTypeCPortNamesHelper(&names);
526     int i = -1;
527 
528     if (result == Status::SUCCESS) {
529         currentPortStatus_1_2->resize(names.size());
530         for (std::pair<std::string, bool> port : names) {
531             i++;
532             ALOGI("%s", port.first.c_str());
533             (*currentPortStatus_1_2)[i].status_1_1.status.portName = port.first;
534 
535             uint32_t currentRole;
536             if (getCurrentRoleHelper(port.first, port.second, PortRoleType::POWER_ROLE,
537                                      &currentRole) == Status::SUCCESS) {
538                 (*currentPortStatus_1_2)[i].status_1_1.status.currentPowerRole =
539                     static_cast<PortPowerRole>(currentRole);
540             } else {
541                 ALOGE("Error while retrieving portNames");
542                 goto done;
543             }
544 
545             if (getCurrentRoleHelper(port.first, port.second, PortRoleType::DATA_ROLE,
546                                      &currentRole) == Status::SUCCESS) {
547                 (*currentPortStatus_1_2)[i].status_1_1.status.currentDataRole =
548                     static_cast<PortDataRole>(currentRole);
549             } else {
550                 ALOGE("Error while retrieving current port role");
551                 goto done;
552             }
553 
554             if (getCurrentRoleHelper(port.first, port.second, PortRoleType::MODE, &currentRole) ==
555                 Status::SUCCESS) {
556                 (*currentPortStatus_1_2)[i].status_1_1.currentMode =
557                     static_cast<PortMode_1_1>(currentRole);
558                 (*currentPortStatus_1_2)[i].status_1_1.status.currentMode =
559                     static_cast<V1_0::PortMode>(currentRole);
560             } else {
561                 ALOGE("Error while retrieving current data role");
562                 goto done;
563             }
564 
565             (*currentPortStatus_1_2)[i].status_1_1.status.canChangeMode = true;
566             (*currentPortStatus_1_2)[i].status_1_1.status.canChangeDataRole =
567                 port.second ? canSwitchRoleHelper(port.first, PortRoleType::DATA_ROLE) : false;
568             (*currentPortStatus_1_2)[i].status_1_1.status.canChangePowerRole =
569                 port.second ? canSwitchRoleHelper(port.first, PortRoleType::POWER_ROLE) : false;
570 
571             if (version == HALVersion::V1_0) {
572                 ALOGI("HAL version V1_0");
573                 (*currentPortStatus_1_2)[i].status_1_1.status.supportedModes = V1_0::PortMode::DRP;
574             } else {
575 		if (version == HALVersion::V1_1)
576                     ALOGI("HAL version V1_1");
577 		else
578                     ALOGI("HAL version V1_2");
579                 (*currentPortStatus_1_2)[i].status_1_1.supportedModes = 0 | PortMode_1_1::DRP;
580                 (*currentPortStatus_1_2)[i].status_1_1.status.supportedModes = V1_0::PortMode::NONE;
581                 (*currentPortStatus_1_2)[i].status_1_1.status.currentMode = V1_0::PortMode::NONE;
582             }
583 
584             ALOGI(
585                 "%d:%s connected:%d canChangeMode:%d canChagedata:%d canChangePower:%d "
586                 "supportedModes:%d",
587                 i, port.first.c_str(), port.second,
588                 (*currentPortStatus_1_2)[i].status_1_1.status.canChangeMode,
589                 (*currentPortStatus_1_2)[i].status_1_1.status.canChangeDataRole,
590                 (*currentPortStatus_1_2)[i].status_1_1.status.canChangePowerRole,
591                 (*currentPortStatus_1_2)[i].status_1_1.supportedModes);
592         }
593         return Status::SUCCESS;
594     }
595 done:
596     return Status::ERROR;
597 }
598 
queryVersionHelper(implementation::Usb * usb,hidl_vec<PortStatus> * currentPortStatus_1_2)599 void queryVersionHelper(implementation::Usb *usb, hidl_vec<PortStatus> *currentPortStatus_1_2) {
600     hidl_vec<V1_1::PortStatus_1_1> currentPortStatus_1_1;
601     hidl_vec<V1_0::PortStatus> currentPortStatus;
602     Status status;
603     sp<V1_1::IUsbCallback> callback_V1_1 = V1_1::IUsbCallback::castFrom(usb->mCallback_1_0);
604     sp<IUsbCallback> callback_V1_2 = IUsbCallback::castFrom(usb->mCallback_1_0);
605 
606     pthread_mutex_lock(&usb->mLock);
607     if (usb->mCallback_1_0 != NULL) {
608         if (callback_V1_2 != NULL) {
609             status = getPortStatusHelper(currentPortStatus_1_2, HALVersion::V1_2);
610             if (status == Status::SUCCESS)
611                 queryMoistureDetectionStatus(currentPortStatus_1_2);
612         } else if (callback_V1_1 != NULL) {
613             status = getPortStatusHelper(currentPortStatus_1_2, HALVersion::V1_1);
614             currentPortStatus_1_1.resize(currentPortStatus_1_2->size());
615             for (unsigned long i = 0; i < currentPortStatus_1_2->size(); i++)
616                 currentPortStatus_1_1[i] = (*currentPortStatus_1_2)[i].status_1_1;
617         } else {
618             status = getPortStatusHelper(currentPortStatus_1_2, HALVersion::V1_0);
619             currentPortStatus.resize(currentPortStatus_1_2->size());
620             for (unsigned long i = 0; i < currentPortStatus_1_2->size(); i++)
621                 currentPortStatus[i] = (*currentPortStatus_1_2)[i].status_1_1.status;
622         }
623 
624         Return<void> ret;
625 
626         if (callback_V1_2 != NULL)
627             ret = callback_V1_2->notifyPortStatusChange_1_2(*currentPortStatus_1_2, status);
628         else if (callback_V1_1 != NULL)
629             ret = callback_V1_1->notifyPortStatusChange_1_1(currentPortStatus_1_1, status);
630         else
631             ret = usb->mCallback_1_0->notifyPortStatusChange(currentPortStatus, status);
632 
633         if (!ret.isOk())
634             ALOGE("queryPortStatus_1_2 error %s", ret.description().c_str());
635     } else {
636         ALOGI("Notifying userspace skipped. Callback is NULL");
637     }
638     pthread_mutex_unlock(&usb->mLock);
639 }
640 
queryPortStatus()641 Return<void> Usb::queryPortStatus() {
642     hidl_vec<PortStatus> currentPortStatus_1_2;
643 
644     queryVersionHelper(this, &currentPortStatus_1_2);
645     return Void();
646 }
647 
648 struct data {
649     int uevent_fd;
650     android::hardware::usb::V1_3::implementation::Usb *usb;
651 };
652 
uevent_event(uint32_t,struct data * payload)653 static void uevent_event(uint32_t /*epevents*/, struct data *payload) {
654     char msg[UEVENT_MSG_LEN + 2];
655     char *cp;
656     int n;
657 
658     n = uevent_kernel_multicast_recv(payload->uevent_fd, msg, UEVENT_MSG_LEN);
659     if (n <= 0)
660         return;
661     if (n >= UEVENT_MSG_LEN) /* overflow -- discard */
662         return;
663 
664     msg[n] = '\0';
665     msg[n + 1] = '\0';
666     cp = msg;
667 
668     while (*cp) {
669         if (std::regex_match(cp, std::regex("(add)(.*)(-partner)"))) {
670             ALOGI("partner added");
671             pthread_mutex_lock(&payload->usb->mPartnerLock);
672             payload->usb->mPartnerUp = true;
673             pthread_cond_signal(&payload->usb->mPartnerCV);
674             pthread_mutex_unlock(&payload->usb->mPartnerLock);
675         } else if (!strncmp(cp, "DEVTYPE=typec_", strlen("DEVTYPE=typec_")) ||
676                    !strncmp(cp, "POWER_SUPPLY_MOISTURE_DETECTED",
677                             strlen("POWER_SUPPLY_MOISTURE_DETECTED"))) {
678             hidl_vec<PortStatus> currentPortStatus_1_2;
679             queryVersionHelper(payload->usb, &currentPortStatus_1_2);
680 
681             // Role switch is not in progress and port is in disconnected state
682             if (!pthread_mutex_trylock(&payload->usb->mRoleSwitchLock)) {
683                 for (unsigned long i = 0; i < currentPortStatus_1_2.size(); i++) {
684                     DIR *dp =
685                         opendir(std::string("/sys/class/typec/" +
686                                             std::string(currentPortStatus_1_2[i]
687                                                             .status_1_1.status.portName.c_str()) +
688                                             "-partner")
689                                     .c_str());
690                     if (dp == NULL) {
691                         // PortRole role = {.role = static_cast<uint32_t>(PortMode::UFP)};
692                         switchToDrp(currentPortStatus_1_2[i].status_1_1.status.portName);
693                     } else {
694                         closedir(dp);
695                     }
696                 }
697                 pthread_mutex_unlock(&payload->usb->mRoleSwitchLock);
698             }
699             break;
700         }
701         /* advance to after the next \0 */
702         while (*cp++) {
703         }
704     }
705 }
706 
work(void * param)707 void *work(void *param) {
708     int epoll_fd, uevent_fd;
709     struct epoll_event ev;
710     int nevents = 0;
711     struct data payload;
712 
713     ALOGE("creating thread");
714 
715     uevent_fd = uevent_open_socket(64 * 1024, true);
716 
717     if (uevent_fd < 0) {
718         ALOGE("uevent_init: uevent_open_socket failed\n");
719         return NULL;
720     }
721 
722     payload.uevent_fd = uevent_fd;
723     payload.usb = (android::hardware::usb::V1_3::implementation::Usb *)param;
724 
725     fcntl(uevent_fd, F_SETFL, O_NONBLOCK);
726 
727     ev.events = EPOLLIN;
728     ev.data.ptr = (void *)uevent_event;
729 
730     epoll_fd = epoll_create(64);
731     if (epoll_fd == -1) {
732         ALOGE("epoll_create failed; errno=%d", errno);
733         goto error;
734     }
735 
736     if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, uevent_fd, &ev) == -1) {
737         ALOGE("epoll_ctl failed; errno=%d", errno);
738         goto error;
739     }
740 
741     while (!destroyThread) {
742         struct epoll_event events[64];
743 
744         nevents = epoll_wait(epoll_fd, events, 64, -1);
745         if (nevents == -1) {
746             if (errno == EINTR)
747                 continue;
748             ALOGE("usb epoll_wait failed; errno=%d", errno);
749             break;
750         }
751 
752         for (int n = 0; n < nevents; ++n) {
753             if (events[n].data.ptr)
754                 (*(void (*)(int, struct data *payload))events[n].data.ptr)(events[n].events,
755                                                                            &payload);
756         }
757     }
758 
759     ALOGI("exiting worker thread");
760 error:
761     close(uevent_fd);
762 
763     if (epoll_fd >= 0)
764         close(epoll_fd);
765 
766     return NULL;
767 }
768 
sighandler(int sig)769 void sighandler(int sig) {
770     if (sig == SIGUSR1) {
771         destroyThread = true;
772         ALOGI("destroy set");
773         return;
774     }
775     signal(SIGUSR1, sighandler);
776 }
777 
setCallback(const sp<V1_0::IUsbCallback> & callback)778 Return<void> Usb::setCallback(const sp<V1_0::IUsbCallback> &callback) {
779     sp<V1_1::IUsbCallback> callback_V1_1 = V1_1::IUsbCallback::castFrom(callback);
780     sp<IUsbCallback> callback_V1_2 = IUsbCallback::castFrom(callback);
781 
782     if (callback != NULL) {
783         if (callback_V1_2 != NULL)
784             ALOGI("Registering 1.2 callback");
785         else if (callback_V1_1 != NULL)
786             ALOGI("Registering 1.1 callback");
787     }
788 
789     pthread_mutex_lock(&mLock);
790     /*
791      * When both the old callback and new callback values are NULL,
792      * there is no need to spin off the worker thread.
793      * When both the values are not NULL, we would already have a
794      * worker thread running, so updating the callback object would
795      * be suffice.
796      */
797     if ((mCallback_1_0 == NULL && callback == NULL) ||
798         (mCallback_1_0 != NULL && callback != NULL)) {
799         /*
800          * Always store as V1_0 callback object. Type cast to V1_1
801          * when the callback is actually invoked.
802          */
803         mCallback_1_0 = callback;
804         pthread_mutex_unlock(&mLock);
805         return Void();
806     }
807 
808     mCallback_1_0 = callback;
809     ALOGI("registering callback");
810 
811     // Kill the worker thread if the new callback is NULL.
812     if (mCallback_1_0 == NULL) {
813         pthread_mutex_unlock(&mLock);
814         if (!pthread_kill(mPoll, SIGUSR1)) {
815             pthread_join(mPoll, NULL);
816             ALOGI("pthread destroyed");
817         }
818         return Void();
819     }
820 
821     destroyThread = false;
822     signal(SIGUSR1, sighandler);
823 
824     /*
825      * Create a background thread if the old callback value is NULL
826      * and being updated with a new value.
827      */
828     if (pthread_create(&mPoll, NULL, work, this)) {
829         ALOGE("pthread creation failed %d", errno);
830         mCallback_1_0 = NULL;
831     }
832 
833     pthread_mutex_unlock(&mLock);
834     return Void();
835 }
836 
837 }  // namespace implementation
838 }  // namespace V1_3
839 }  // namespace usb
840 }  // namespace hardware
841 }  // namespace android
842