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