From 4fdb12f625e40a32bd4fe228b939099d1ccad361 Mon Sep 17 00:00:00 2001 From: Steven Moreland Date: Tue, 21 Jul 2020 02:21:48 +0000 Subject: libbinder: avoid global mutex every binder call We can't get rid of a mutex (or similar) for the rarer ProcessState::selfOrNull access, but for ProcessState::self() accesses, which happen at least once every binder call, we can use the very fast once flags. Bug: 161336582 Test: boots Change-Id: I66fee6be0260f59f80a85328228776de7e68c7fb --- libs/binder/ProcessState.cpp | 60 ++++++++++++++++++++++++++------------------ 1 file changed, 36 insertions(+), 24 deletions(-) (limited to 'libs/binder/ProcessState.cpp') diff --git a/libs/binder/ProcessState.cpp b/libs/binder/ProcessState.cpp index 0f81e0bef0..02e01934bb 100644 --- a/libs/binder/ProcessState.cpp +++ b/libs/binder/ProcessState.cpp @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -73,38 +74,49 @@ protected: sp ProcessState::self() { - Mutex::Autolock _l(gProcessMutex); - if (gProcess != nullptr) { - return gProcess; - } - gProcess = new ProcessState(kDefaultDriver); - return gProcess; + return init(kDefaultDriver, false /*requireDefault*/); } sp ProcessState::initWithDriver(const char* driver) { - Mutex::Autolock _l(gProcessMutex); - if (gProcess != nullptr) { - // Allow for initWithDriver to be called repeatedly with the same - // driver. - if (!strcmp(gProcess->getDriverName().c_str(), driver)) { - return gProcess; - } - LOG_ALWAYS_FATAL("ProcessState was already initialized."); - } - - if (access(driver, R_OK) == -1) { - ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver); - driver = "/dev/binder"; - } - - gProcess = new ProcessState(driver); - return gProcess; + return init(driver, true /*requireDefault*/); } sp ProcessState::selfOrNull() { - Mutex::Autolock _l(gProcessMutex); + return init(nullptr, false /*requireDefault*/); +} + +sp ProcessState::init(const char *driver, bool requireDefault) +{ + [[clang::no_destroy]] static sp gProcess; + [[clang::no_destroy]] static std::mutex gProcessMutex; + + if (driver == nullptr) { + std::lock_guard l(gProcessMutex); + return gProcess; + } + + [[clang::no_destroy]] static std::once_flag gProcessOnce; + std::call_once(gProcessOnce, [&](){ + if (access(driver, R_OK) == -1) { + ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver); + driver = "/dev/binder"; + } + + std::lock_guard l(gProcessMutex); + gProcess = new ProcessState(driver); + }); + + if (requireDefault) { + // Detect if we are trying to initialize with a different driver, and + // consider that an error. ProcessState will only be initialized once above. + LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver, + "ProcessState was already initialized with %s," + " can't initialize with %s.", + gProcess->getDriverName().c_str(), driver); + } + return gProcess; } -- cgit v1.2.3-59-g8ed1b