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