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