blob: 92b09a2b44e6c01fb937ee16b711aa2b1f966e6e [file] [log] [blame]
Badhri Jagan Sridharanb9f69ea2021-10-19 13:09:44 -07001/*
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.aidl-service"
18
19#include <aidl/android/hardware/usb/PortRole.h>
20#include <android-base/logging.h>
21#include <android-base/properties.h>
22#include <android-base/strings.h>
23#include <assert.h>
24#include <dirent.h>
25#include <pthread.h>
26#include <stdio.h>
27#include <sys/types.h>
28#include <unistd.h>
29#include <chrono>
30#include <regex>
31#include <thread>
32#include <unordered_map>
33
34#include <cutils/uevent.h>
35#include <sys/epoll.h>
36#include <utils/Errors.h>
37#include <utils/StrongPointer.h>
38
39#include "Usb.h"
40
41using android::base::GetProperty;
42using android::base::Trim;
43
44namespace aidl {
45namespace android {
46namespace hardware {
47namespace usb {
48
49constexpr char kTypecPath[] = "/sys/class/typec/";
50constexpr char kDataRoleNode[] = "/data_role";
51constexpr char kPowerRoleNode[] = "/power_role";
52
53// Set by the signal handler to destroy the thread
54volatile bool destroyThread;
55
56void queryVersionHelper(android::hardware::usb::Usb *usb,
57 std::vector<PortStatus> *currentPortStatus);
58
59ScopedAStatus Usb::enableUsbData(const string& in_portName, bool in_enable, int64_t in_transactionId) {
60 std::vector<PortStatus> currentPortStatus;
61
62 pthread_mutex_lock(&mLock);
63 if (mCallback != NULL) {
64 ScopedAStatus ret = mCallback->notifyEnableUsbDataStatus(
65 in_portName, true, in_enable ? Status::SUCCESS : Status::ERROR, in_transactionId);
66 if (!ret.isOk())
67 ALOGE("notifyEnableUsbDataStatus error %s", ret.getDescription().c_str());
68 } else {
69 ALOGE("Not notifying the userspace. Callback is not set");
70 }
71 pthread_mutex_unlock(&mLock);
72 queryVersionHelper(this, &currentPortStatus);
73
74 return ScopedAStatus::ok();
75}
76
Badhri Jagan Sridharane7450582021-12-27 03:42:19 -080077ScopedAStatus Usb::enableUsbDataWhileDocked(const string& in_portName, int64_t in_transactionId) {
78
79 pthread_mutex_lock(&mLock);
80 if (mCallback != NULL) {
81 ScopedAStatus ret = mCallback->notifyEnableUsbDataWhileDockedStatus(
82 in_portName, Status::NOT_SUPPORTED, in_transactionId);
83 if (!ret.isOk())
84 ALOGE("notifyEnableUsbDataWhileDockedStatus error %s", ret.getDescription().c_str());
85 } else {
86 ALOGE("Not notifying the userspace. Callback is not set");
87 }
88 pthread_mutex_unlock(&mLock);
89
90 return ScopedAStatus::ok();
91}
92
Badhri Jagan Sridharanb9f69ea2021-10-19 13:09:44 -070093Status queryMoistureDetectionStatus(std::vector<PortStatus> *currentPortStatus) {
94 string enabled, status, path, DetectedPath;
95
96 for (int i = 0; i < currentPortStatus->size(); i++) {
97 (*currentPortStatus)[i].supportedContaminantProtectionModes
98 .push_back(ContaminantProtectionMode::NONE);
99 (*currentPortStatus)[i].contaminantProtectionStatus
100 = ContaminantProtectionStatus::NONE;
101 (*currentPortStatus)[i].contaminantDetectionStatus
102 = ContaminantDetectionStatus::NOT_SUPPORTED;
103 (*currentPortStatus)[i].supportsEnableContaminantPresenceDetection = false;
104 (*currentPortStatus)[i].supportsEnableContaminantPresenceProtection = false;
105 }
106
107 return Status::SUCCESS;
108}
109
110string appendRoleNodeHelper(const string &portName, PortRole::Tag tag) {
111 string node(kTypecPath + portName);
112
113 switch (tag) {
114 case PortRole::dataRole:
115 return node + kDataRoleNode;
116 case PortRole::powerRole:
117 return node + kPowerRoleNode;
118 case PortRole::mode:
119 return node + "/port_type";
120 default:
121 return "";
122 }
123}
124
125string convertRoletoString(PortRole role) {
126 if (role.getTag() == PortRole::powerRole) {
127 if (role.get<PortRole::powerRole>() == PortPowerRole::SOURCE)
128 return "source";
129 else if (role.get<PortRole::powerRole>() == PortPowerRole::SINK)
130 return "sink";
131 } else if (role.getTag() == PortRole::dataRole) {
132 if (role.get<PortRole::dataRole>() == PortDataRole::HOST)
133 return "host";
134 if (role.get<PortRole::dataRole>() == PortDataRole::DEVICE)
135 return "device";
136 } else if (role.getTag() == PortRole::mode) {
137 if (role.get<PortRole::mode>() == PortMode::UFP)
138 return "sink";
139 if (role.get<PortRole::mode>() == PortMode::DFP)
140 return "source";
141 }
142 return "none";
143}
144
145void extractRole(string *roleName) {
146 std::size_t first, last;
147
148 first = roleName->find("[");
149 last = roleName->find("]");
150
151 if (first != string::npos && last != string::npos) {
152 *roleName = roleName->substr(first + 1, last - first - 1);
153 }
154}
155
156void switchToDrp(const string &portName) {
157 string filename = appendRoleNodeHelper(string(portName.c_str()), PortRole::mode);
158 FILE *fp;
159
160 if (filename != "") {
161 fp = fopen(filename.c_str(), "w");
162 if (fp != NULL) {
163 int ret = fputs("dual", fp);
164 fclose(fp);
165 if (ret == EOF)
166 ALOGE("Fatal: Error while switching back to drp");
167 } else {
168 ALOGE("Fatal: Cannot open file to switch back to drp");
169 }
170 } else {
171 ALOGE("Fatal: invalid node type");
172 }
173}
174
175bool switchMode(const string &portName, const PortRole &in_role, struct Usb *usb) {
176 string filename = appendRoleNodeHelper(string(portName.c_str()), in_role.getTag());
177 string written;
178 FILE *fp;
179 bool roleSwitch = false;
180
181 if (filename == "") {
182 ALOGE("Fatal: invalid node type");
183 return false;
184 }
185
186 fp = fopen(filename.c_str(), "w");
187 if (fp != NULL) {
188 // Hold the lock here to prevent loosing connected signals
189 // as once the file is written the partner added signal
190 // can arrive anytime.
191 pthread_mutex_lock(&usb->mPartnerLock);
192 usb->mPartnerUp = false;
193 int ret = fputs(convertRoletoString(in_role).c_str(), fp);
194 fclose(fp);
195
196 if (ret != EOF) {
197 struct timespec to;
198 struct timespec now;
199
200 wait_again:
201 clock_gettime(CLOCK_MONOTONIC, &now);
202 to.tv_sec = now.tv_sec + PORT_TYPE_TIMEOUT;
203 to.tv_nsec = now.tv_nsec;
204
205 int err = pthread_cond_timedwait(&usb->mPartnerCV, &usb->mPartnerLock, &to);
206 // There are no uevent signals which implies role swap timed out.
207 if (err == ETIMEDOUT) {
208 ALOGI("uevents wait timedout");
209 // Validity check.
210 } else if (!usb->mPartnerUp) {
211 goto wait_again;
212 // Role switch succeeded since usb->mPartnerUp is true.
213 } else {
214 roleSwitch = true;
215 }
216 } else {
217 ALOGI("Role switch failed while wrting to file");
218 }
219 pthread_mutex_unlock(&usb->mPartnerLock);
220 }
221
222 if (!roleSwitch)
223 switchToDrp(string(portName.c_str()));
224
225 return roleSwitch;
226}
227
228Usb::Usb()
229 : mLock(PTHREAD_MUTEX_INITIALIZER),
230 mRoleSwitchLock(PTHREAD_MUTEX_INITIALIZER),
231 mPartnerLock(PTHREAD_MUTEX_INITIALIZER),
232 mPartnerUp(false)
233{
234 pthread_condattr_t attr;
235 if (pthread_condattr_init(&attr)) {
236 ALOGE("pthread_condattr_init failed: %s", strerror(errno));
237 abort();
238 }
239 if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)) {
240 ALOGE("pthread_condattr_setclock failed: %s", strerror(errno));
241 abort();
242 }
243 if (pthread_cond_init(&mPartnerCV, &attr)) {
244 ALOGE("pthread_cond_init failed: %s", strerror(errno));
245 abort();
246 }
247 if (pthread_condattr_destroy(&attr)) {
248 ALOGE("pthread_condattr_destroy failed: %s", strerror(errno));
249 abort();
250 }
251}
252
253ScopedAStatus Usb::switchRole(const string& in_portName,
254 const PortRole& in_role, int64_t in_transactionId) {
255 string filename = appendRoleNodeHelper(string(in_portName.c_str()), in_role.getTag());
256 string written;
257 FILE *fp;
258 bool roleSwitch = false;
259
260 if (filename == "") {
261 ALOGE("Fatal: invalid node type");
262 return ScopedAStatus::ok();
263 }
264
265 pthread_mutex_lock(&mRoleSwitchLock);
266
267 ALOGI("filename write: %s role:%s", filename.c_str(), convertRoletoString(in_role).c_str());
268
269 if (in_role.getTag() == PortRole::mode) {
270 roleSwitch = switchMode(in_portName, in_role, this);
271 } else {
272 fp = fopen(filename.c_str(), "w");
273 if (fp != NULL) {
274 int ret = fputs(convertRoletoString(in_role).c_str(), fp);
275 fclose(fp);
276 if ((ret != EOF) && ReadFileToString(filename, &written)) {
277 written = Trim(written);
278 extractRole(&written);
279 ALOGI("written: %s", written.c_str());
280 if (written == convertRoletoString(in_role)) {
281 roleSwitch = true;
282 } else {
283 ALOGE("Role switch failed");
284 }
285 } else {
286 ALOGE("failed to update the new role");
287 }
288 } else {
289 ALOGE("fopen failed");
290 }
291 }
292
293 pthread_mutex_lock(&mLock);
294 if (mCallback != NULL) {
295 ScopedAStatus ret = mCallback->notifyRoleSwitchStatus(
296 in_portName, in_role, roleSwitch ? Status::SUCCESS : Status::ERROR, in_transactionId);
297 if (!ret.isOk())
298 ALOGE("RoleSwitchStatus error %s", ret.getDescription().c_str());
299 } else {
300 ALOGE("Not notifying the userspace. Callback is not set");
301 }
302 pthread_mutex_unlock(&mLock);
303 pthread_mutex_unlock(&mRoleSwitchLock);
304
305 return ScopedAStatus::ok();
306}
307
Badhri Jagan Sridharan623f1332021-11-25 09:35:21 -0800308ScopedAStatus Usb::limitPowerTransfer(const string& in_portName, bool /*in_limit*/,
309 int64_t in_transactionId) {
310 std::vector<PortStatus> currentPortStatus;
311
312 pthread_mutex_lock(&mLock);
313 if (mCallback != NULL && in_transactionId >= 0) {
314 ScopedAStatus ret = mCallback->notifyLimitPowerTransferStatus(
315 in_portName, false, Status::NOT_SUPPORTED, in_transactionId);
316 if (!ret.isOk())
317 ALOGE("limitPowerTransfer error %s", ret.getDescription().c_str());
318 } else {
319 ALOGE("Not notifying the userspace. Callback is not set");
320 }
321 pthread_mutex_unlock(&mLock);
322
323 return ScopedAStatus::ok();
324}
325
Badhri Jagan Sridharanb9f69ea2021-10-19 13:09:44 -0700326Status getAccessoryConnected(const string &portName, string *accessory) {
327 string filename = kTypecPath + portName + "-partner/accessory_mode";
328
329 if (!ReadFileToString(filename, accessory)) {
330 ALOGE("getAccessoryConnected: Failed to open filesystem node: %s", filename.c_str());
331 return Status::ERROR;
332 }
333 *accessory = Trim(*accessory);
334
335 return Status::SUCCESS;
336}
337
338Status getCurrentRoleHelper(const string &portName, bool connected, PortRole *currentRole) {
339 string filename;
340 string roleName;
341 string accessory;
342
343 // Mode
344
345 if (currentRole->getTag() == PortRole::powerRole) {
346 filename = kTypecPath + portName + kPowerRoleNode;
347 currentRole->set<PortRole::powerRole>(PortPowerRole::NONE);
348 } else if (currentRole->getTag() == PortRole::dataRole) {
349 filename = kTypecPath + portName + kDataRoleNode;
350 currentRole->set<PortRole::dataRole>(PortDataRole::NONE);
351 } else if (currentRole->getTag() == PortRole::mode) {
352 filename = kTypecPath + portName + kDataRoleNode;
353 currentRole->set<PortRole::mode>(PortMode::NONE);
354 } else {
355 return Status::ERROR;
356 }
357
358 if (!connected)
359 return Status::SUCCESS;
360
361 if (currentRole->getTag() == PortRole::mode) {
362 if (getAccessoryConnected(portName, &accessory) != Status::SUCCESS) {
363 return Status::ERROR;
364 }
365 if (accessory == "analog_audio") {
366 currentRole->set<PortRole::mode>(PortMode::AUDIO_ACCESSORY);
367 return Status::SUCCESS;
368 } else if (accessory == "debug") {
369 currentRole->set<PortRole::mode>(PortMode::DEBUG_ACCESSORY);
370 return Status::SUCCESS;
371 }
372 }
373
374 if (!ReadFileToString(filename, &roleName)) {
375 ALOGE("getCurrentRole: Failed to open filesystem node: %s", filename.c_str());
376 return Status::ERROR;
377 }
378
379 roleName = Trim(roleName);
380 extractRole(&roleName);
381
382 if (roleName == "source") {
383 currentRole->set<PortRole::powerRole>(PortPowerRole::SOURCE);
384 } else if (roleName == "sink") {
385 currentRole->set<PortRole::powerRole>(PortPowerRole::SINK);
386 } else if (roleName == "host") {
387 if (currentRole->getTag() == PortRole::dataRole)
388 currentRole->set<PortRole::dataRole>(PortDataRole::HOST);
389 else
390 currentRole->set<PortRole::mode>(PortMode::DFP);
391 } else if (roleName == "device") {
392 if (currentRole->getTag() == PortRole::dataRole)
393 currentRole->set<PortRole::dataRole>(PortDataRole::DEVICE);
394 else
395 currentRole->set<PortRole::mode>(PortMode::UFP);
396 } else if (roleName != "none") {
397 /* case for none has already been addressed.
398 * so we check if the role isn't none.
399 */
400 return Status::UNRECOGNIZED_ROLE;
401 }
402
403 return Status::SUCCESS;
404}
405
406Status getTypeCPortNamesHelper(std::unordered_map<string, bool> *names) {
407 DIR *dp;
408
409 dp = opendir(kTypecPath);
410 if (dp != NULL) {
411 struct dirent *ep;
412
413 while ((ep = readdir(dp))) {
414 if (ep->d_type == DT_LNK) {
415 if (string::npos == string(ep->d_name).find("-partner")) {
416 std::unordered_map<string, bool>::const_iterator portName =
417 names->find(ep->d_name);
418 if (portName == names->end()) {
419 names->insert({ep->d_name, false});
420 }
421 } else {
422 (*names)[std::strtok(ep->d_name, "-")] = true;
423 }
424 }
425 }
426 closedir(dp);
427 return Status::SUCCESS;
428 }
429
430 ALOGE("Failed to open /sys/class/typec");
431 return Status::ERROR;
432}
433
434bool canSwitchRoleHelper(const string &portName) {
435 string filename = kTypecPath + portName + "-partner/supports_usb_power_delivery";
436 string supportsPD;
437
438 if (ReadFileToString(filename, &supportsPD)) {
439 supportsPD = Trim(supportsPD);
440 if (supportsPD == "yes") {
441 return true;
442 }
443 }
444
445 return false;
446}
447
448Status getPortStatusHelper(std::vector<PortStatus> *currentPortStatus) {
449 std::unordered_map<string, bool> names;
450 Status result = getTypeCPortNamesHelper(&names);
451 int i = -1;
452
453 if (result == Status::SUCCESS) {
454 currentPortStatus->resize(names.size());
455 for (std::pair<string, bool> port : names) {
456 i++;
457 ALOGI("%s", port.first.c_str());
458 (*currentPortStatus)[i].portName = port.first;
459
460 PortRole currentRole;
461 currentRole.set<PortRole::powerRole>(PortPowerRole::NONE);
462 if (getCurrentRoleHelper(port.first, port.second, &currentRole) == Status::SUCCESS){
463 (*currentPortStatus)[i].currentPowerRole = currentRole.get<PortRole::powerRole>();
464 } else {
465 ALOGE("Error while retrieving portNames");
466 goto done;
467 }
468
469 currentRole.set<PortRole::dataRole>(PortDataRole::NONE);
470 if (getCurrentRoleHelper(port.first, port.second, &currentRole) == Status::SUCCESS) {
471 (*currentPortStatus)[i].currentDataRole = currentRole.get<PortRole::dataRole>();
472 } else {
473 ALOGE("Error while retrieving current port role");
474 goto done;
475 }
476
477 currentRole.set<PortRole::mode>(PortMode::NONE);
478 if (getCurrentRoleHelper(port.first, port.second, &currentRole) == Status::SUCCESS) {
479 (*currentPortStatus)[i].currentMode = currentRole.get<PortRole::mode>();
480 } else {
481 ALOGE("Error while retrieving current data role");
482 goto done;
483 }
484
485 (*currentPortStatus)[i].canChangeMode = true;
486 (*currentPortStatus)[i].canChangeDataRole =
487 port.second ? canSwitchRoleHelper(port.first) : false;
488 (*currentPortStatus)[i].canChangePowerRole =
489 port.second ? canSwitchRoleHelper(port.first) : false;
490
491 (*currentPortStatus)[i].supportedModes.push_back(PortMode::DRP);
Badhri Jagan Sridharane7450582021-12-27 03:42:19 -0800492 (*currentPortStatus)[i].usbDataStatus.push_back(UsbDataStatus::ENABLED);
Badhri Jagan Sridharanb9f69ea2021-10-19 13:09:44 -0700493
494 ALOGI("%d:%s connected:%d canChangeMode:%d canChagedata:%d canChangePower:%d "
495 "usbDataEnabled:%d",
496 i, port.first.c_str(), port.second,
497 (*currentPortStatus)[i].canChangeMode,
498 (*currentPortStatus)[i].canChangeDataRole,
499 (*currentPortStatus)[i].canChangePowerRole, 0);
500 }
501
502 return Status::SUCCESS;
503 }
504done:
505 return Status::ERROR;
506}
507
508void queryVersionHelper(android::hardware::usb::Usb *usb,
509 std::vector<PortStatus> *currentPortStatus) {
510 Status status;
511 pthread_mutex_lock(&usb->mLock);
512 status = getPortStatusHelper(currentPortStatus);
513 queryMoistureDetectionStatus(currentPortStatus);
514 if (usb->mCallback != NULL) {
515 ScopedAStatus ret = usb->mCallback->notifyPortStatusChange(*currentPortStatus,
516 status);
517 if (!ret.isOk())
518 ALOGE("queryPortStatus error %s", ret.getDescription().c_str());
519 } else {
520 ALOGI("Notifying userspace skipped. Callback is NULL");
521 }
522 pthread_mutex_unlock(&usb->mLock);
523}
524
525ScopedAStatus Usb::queryPortStatus(int64_t in_transactionId) {
526 std::vector<PortStatus> currentPortStatus;
527
528 queryVersionHelper(this, &currentPortStatus);
529 pthread_mutex_lock(&mLock);
530 if (mCallback != NULL) {
531 ScopedAStatus ret = mCallback->notifyQueryPortStatus(
532 "all", Status::SUCCESS, in_transactionId);
533 if (!ret.isOk())
534 ALOGE("notifyQueryPortStatus error %s", ret.getDescription().c_str());
535 } else {
536 ALOGE("Not notifying the userspace. Callback is not set");
537 }
538 pthread_mutex_unlock(&mLock);
539
540 return ScopedAStatus::ok();
541}
542
543ScopedAStatus Usb::enableContaminantPresenceDetection(const string& in_portName,
544 bool /*in_enable*/, int64_t in_transactionId) {
545 std::vector<PortStatus> currentPortStatus;
546
547 pthread_mutex_lock(&mLock);
548 if (mCallback != NULL) {
549 ScopedAStatus ret = mCallback->notifyContaminantEnabledStatus(
550 in_portName, false, Status::ERROR, in_transactionId);
551 if (!ret.isOk())
552 ALOGE("enableContaminantPresenceDetection error %s", ret.getDescription().c_str());
553 } else {
554 ALOGE("Not notifying the userspace. Callback is not set");
555 }
556 pthread_mutex_unlock(&mLock);
557
558 queryVersionHelper(this, &currentPortStatus);
559 return ScopedAStatus::ok();
560}
561
562
563struct data {
564 int uevent_fd;
565 ::aidl::android::hardware::usb::Usb *usb;
566};
567
568static void uevent_event(uint32_t /*epevents*/, struct data *payload) {
569 char msg[UEVENT_MSG_LEN + 2];
570 char *cp;
571 int n;
572
573 n = uevent_kernel_multicast_recv(payload->uevent_fd, msg, UEVENT_MSG_LEN);
574 if (n <= 0)
575 return;
576 if (n >= UEVENT_MSG_LEN) /* overflow -- discard */
577 return;
578
579 msg[n] = '\0';
580 msg[n + 1] = '\0';
581 cp = msg;
582
583 while (*cp) {
584 if (std::regex_match(cp, std::regex("(add)(.*)(-partner)"))) {
585 ALOGI("partner added");
586 pthread_mutex_lock(&payload->usb->mPartnerLock);
587 payload->usb->mPartnerUp = true;
588 pthread_cond_signal(&payload->usb->mPartnerCV);
589 pthread_mutex_unlock(&payload->usb->mPartnerLock);
590 } else if (!strncmp(cp, "DEVTYPE=typec_", strlen("DEVTYPE=typec_"))) {
591 std::vector<PortStatus> currentPortStatus;
592 queryVersionHelper(payload->usb, &currentPortStatus);
593
594 // Role switch is not in progress and port is in disconnected state
595 if (!pthread_mutex_trylock(&payload->usb->mRoleSwitchLock)) {
596 for (unsigned long i = 0; i < currentPortStatus.size(); i++) {
597 DIR *dp =
598 opendir(string(kTypecPath +
599 string(currentPortStatus[i].portName.c_str()) +
600 "-partner").c_str());
601 if (dp == NULL) {
602 switchToDrp(currentPortStatus[i].portName);
603 } else {
604 closedir(dp);
605 }
606 }
607 pthread_mutex_unlock(&payload->usb->mRoleSwitchLock);
608 }
609 break;
610 } /* advance to after the next \0 */
611 while (*cp++) {
612 }
613 }
614}
615
616void *work(void *param) {
617 int epoll_fd, uevent_fd;
618 struct epoll_event ev;
619 int nevents = 0;
620 struct data payload;
621
622 uevent_fd = uevent_open_socket(UEVENT_MAX_EVENTS * UEVENT_MSG_LEN, true);
623
624 if (uevent_fd < 0) {
625 ALOGE("uevent_init: uevent_open_socket failed\n");
626 return NULL;
627 }
628
629 payload.uevent_fd = uevent_fd;
630 payload.usb = (::aidl::android::hardware::usb::Usb *)param;
631
632 fcntl(uevent_fd, F_SETFL, O_NONBLOCK);
633
634 ev.events = EPOLLIN;
635 ev.data.ptr = (void *)uevent_event;
636
637 epoll_fd = epoll_create(UEVENT_MAX_EVENTS);
638 if (epoll_fd == -1) {
639 ALOGE("epoll_create failed; errno=%d", errno);
640 goto error;
641 }
642
643 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, uevent_fd, &ev) == -1) {
644 ALOGE("epoll_ctl failed; errno=%d", errno);
645 goto error;
646 }
647
648 while (!destroyThread) {
649 struct epoll_event events[UEVENT_MAX_EVENTS];
650
651 nevents = epoll_wait(epoll_fd, events, UEVENT_MAX_EVENTS, -1);
652 if (nevents == -1) {
653 if (errno == EINTR)
654 continue;
655 ALOGE("usb epoll_wait failed; errno=%d", errno);
656 break;
657 }
658
659 for (int n = 0; n < nevents; ++n) {
660 if (events[n].data.ptr)
661 (*(void (*)(int, struct data *payload))events[n].data.ptr)(events[n].events,
662 &payload);
663 }
664 }
665
666 ALOGI("exiting worker thread");
667error:
668 close(uevent_fd);
669
670 if (epoll_fd >= 0)
671 close(epoll_fd);
672
673 return NULL;
674}
675
676void sighandler(int sig) {
677 if (sig == SIGUSR1) {
678 destroyThread = true;
679 ALOGI("destroy set");
680 return;
681 }
682 signal(SIGUSR1, sighandler);
683}
684
685ScopedAStatus Usb::setCallback(
686 const shared_ptr<IUsbCallback>& in_callback) {
687
688 pthread_mutex_lock(&mLock);
689 if ((mCallback == NULL && in_callback == NULL) ||
690 (mCallback != NULL && in_callback != NULL)) {
691 mCallback = in_callback;
692 pthread_mutex_unlock(&mLock);
693 return ScopedAStatus::ok();
694 }
695
696 mCallback = in_callback;
697 ALOGI("registering callback");
698
699 if (mCallback == NULL) {
700 if (!pthread_kill(mPoll, SIGUSR1)) {
701 pthread_join(mPoll, NULL);
702 ALOGI("pthread destroyed");
703 }
704 pthread_mutex_unlock(&mLock);
705 return ScopedAStatus::ok();
706 }
707
708 destroyThread = false;
709 signal(SIGUSR1, sighandler);
710
711 /*
712 * Create a background thread if the old callback value is NULL
713 * and being updated with a new value.
714 */
715 if (pthread_create(&mPoll, NULL, work, this)) {
716 ALOGE("pthread creation failed %d", errno);
717 mCallback = NULL;
718 }
719
720 pthread_mutex_unlock(&mLock);
721 return ScopedAStatus::ok();
722}
723
724} // namespace usb
725} // namespace hardware
726} // namespace android
727} // aidl