1 /*
2  * Copyright (C) 2011 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 ATRACE_TAG ATRACE_TAG_GRAPHICS
18 
19 #include <pthread.h>
20 #include <sched.h>
21 #include <sys/types.h>
22 
23 #include <chrono>
24 #include <cstdint>
25 #include <optional>
26 #include <type_traits>
27 
28 #include <android-base/stringprintf.h>
29 
30 #include <cutils/compiler.h>
31 #include <cutils/sched_policy.h>
32 
33 #include <gui/DisplayEventReceiver.h>
34 
35 #include <utils/Errors.h>
36 #include <utils/Trace.h>
37 
38 #include "EventThread.h"
39 
40 using namespace std::chrono_literals;
41 
42 namespace android {
43 
44 using base::StringAppendF;
45 using base::StringPrintf;
46 
47 namespace {
48 
vsyncPeriod(VSyncRequest request)49 auto vsyncPeriod(VSyncRequest request) {
50     return static_cast<std::underlying_type_t<VSyncRequest>>(request);
51 }
52 
toString(VSyncRequest request)53 std::string toString(VSyncRequest request) {
54     switch (request) {
55         case VSyncRequest::None:
56             return "VSyncRequest::None";
57         case VSyncRequest::Single:
58             return "VSyncRequest::Single";
59         default:
60             return StringPrintf("VSyncRequest::Periodic{period=%d}", vsyncPeriod(request));
61     }
62 }
63 
toString(const EventThreadConnection & connection)64 std::string toString(const EventThreadConnection& connection) {
65     return StringPrintf("Connection{%p, %s}", &connection,
66                         toString(connection.vsyncRequest).c_str());
67 }
68 
toString(const DisplayEventReceiver::Event & event)69 std::string toString(const DisplayEventReceiver::Event& event) {
70     switch (event.header.type) {
71         case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
72             return StringPrintf("Hotplug{displayId=%" ANDROID_PHYSICAL_DISPLAY_ID_FORMAT ", %s}",
73                                 event.header.displayId,
74                                 event.hotplug.connected ? "connected" : "disconnected");
75         case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
76             return StringPrintf("VSync{displayId=%" ANDROID_PHYSICAL_DISPLAY_ID_FORMAT
77                                 ", count=%u}",
78                                 event.header.displayId, event.vsync.count);
79         case DisplayEventReceiver::DISPLAY_EVENT_CONFIG_CHANGED:
80             return StringPrintf("ConfigChanged{displayId=%" ANDROID_PHYSICAL_DISPLAY_ID_FORMAT
81                                 ", configId=%u}",
82                                 event.header.displayId, event.config.configId);
83         default:
84             return "Event{}";
85     }
86 }
87 
makeHotplug(PhysicalDisplayId displayId,nsecs_t timestamp,bool connected)88 DisplayEventReceiver::Event makeHotplug(PhysicalDisplayId displayId, nsecs_t timestamp,
89                                         bool connected) {
90     DisplayEventReceiver::Event event;
91     event.header = {DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG, displayId, timestamp};
92     event.hotplug.connected = connected;
93     return event;
94 }
95 
makeVSync(PhysicalDisplayId displayId,nsecs_t timestamp,uint32_t count)96 DisplayEventReceiver::Event makeVSync(PhysicalDisplayId displayId, nsecs_t timestamp,
97                                       uint32_t count) {
98     DisplayEventReceiver::Event event;
99     event.header = {DisplayEventReceiver::DISPLAY_EVENT_VSYNC, displayId, timestamp};
100     event.vsync.count = count;
101     return event;
102 }
103 
makeConfigChanged(PhysicalDisplayId displayId,int32_t configId)104 DisplayEventReceiver::Event makeConfigChanged(PhysicalDisplayId displayId, int32_t configId) {
105     DisplayEventReceiver::Event event;
106     event.header = {DisplayEventReceiver::DISPLAY_EVENT_CONFIG_CHANGED, displayId, systemTime()};
107     event.config.configId = configId;
108     return event;
109 }
110 
111 } // namespace
112 
EventThreadConnection(EventThread * eventThread,ResyncCallback resyncCallback,ISurfaceComposer::ConfigChanged configChanged)113 EventThreadConnection::EventThreadConnection(EventThread* eventThread,
114                                              ResyncCallback resyncCallback,
115                                              ISurfaceComposer::ConfigChanged configChanged)
116       : resyncCallback(std::move(resyncCallback)),
117         configChanged(configChanged),
118         mEventThread(eventThread),
119         mChannel(gui::BitTube::DefaultSize) {}
120 
~EventThreadConnection()121 EventThreadConnection::~EventThreadConnection() {
122     // do nothing here -- clean-up will happen automatically
123     // when the main thread wakes up
124 }
125 
onFirstRef()126 void EventThreadConnection::onFirstRef() {
127     // NOTE: mEventThread doesn't hold a strong reference on us
128     mEventThread->registerDisplayEventConnection(this);
129 }
130 
stealReceiveChannel(gui::BitTube * outChannel)131 status_t EventThreadConnection::stealReceiveChannel(gui::BitTube* outChannel) {
132     outChannel->setReceiveFd(mChannel.moveReceiveFd());
133     return NO_ERROR;
134 }
135 
setVsyncRate(uint32_t rate)136 status_t EventThreadConnection::setVsyncRate(uint32_t rate) {
137     mEventThread->setVsyncRate(rate, this);
138     return NO_ERROR;
139 }
140 
requestNextVsync()141 void EventThreadConnection::requestNextVsync() {
142     ATRACE_NAME("requestNextVsync");
143     mEventThread->requestNextVsync(this);
144 }
145 
postEvent(const DisplayEventReceiver::Event & event)146 status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
147     ssize_t size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
148     return size < 0 ? status_t(size) : status_t(NO_ERROR);
149 }
150 
151 // ---------------------------------------------------------------------------
152 
153 EventThread::~EventThread() = default;
154 
155 namespace impl {
156 
EventThread(std::unique_ptr<VSyncSource> src,InterceptVSyncsCallback interceptVSyncsCallback,const char * threadName)157 EventThread::EventThread(std::unique_ptr<VSyncSource> src,
158                          InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName)
159       : EventThread(nullptr, std::move(src), std::move(interceptVSyncsCallback), threadName) {}
160 
EventThread(VSyncSource * src,InterceptVSyncsCallback interceptVSyncsCallback,const char * threadName)161 EventThread::EventThread(VSyncSource* src, InterceptVSyncsCallback interceptVSyncsCallback,
162                          const char* threadName)
163       : EventThread(src, nullptr, std::move(interceptVSyncsCallback), threadName) {}
164 
EventThread(VSyncSource * src,std::unique_ptr<VSyncSource> uniqueSrc,InterceptVSyncsCallback interceptVSyncsCallback,const char * threadName)165 EventThread::EventThread(VSyncSource* src, std::unique_ptr<VSyncSource> uniqueSrc,
166                          InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName)
167       : mVSyncSource(src),
168         mVSyncSourceUnique(std::move(uniqueSrc)),
169         mInterceptVSyncsCallback(std::move(interceptVSyncsCallback)),
170         mThreadName(threadName) {
171     if (src == nullptr) {
172         mVSyncSource = mVSyncSourceUnique.get();
173     }
174     mVSyncSource->setCallback(this);
175 
176     mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
177         std::unique_lock<std::mutex> lock(mMutex);
178         threadMain(lock);
179     });
180 
181     pthread_setname_np(mThread.native_handle(), threadName);
182 
183     pid_t tid = pthread_gettid_np(mThread.native_handle());
184 
185     // Use SCHED_FIFO to minimize jitter
186     constexpr int EVENT_THREAD_PRIORITY = 2;
187     struct sched_param param = {0};
188     param.sched_priority = EVENT_THREAD_PRIORITY;
189     if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
190         ALOGE("Couldn't set SCHED_FIFO for EventThread");
191     }
192 
193     set_sched_policy(tid, SP_FOREGROUND);
194 }
195 
~EventThread()196 EventThread::~EventThread() {
197     mVSyncSource->setCallback(nullptr);
198 
199     {
200         std::lock_guard<std::mutex> lock(mMutex);
201         mState = State::Quit;
202         mCondition.notify_all();
203     }
204     mThread.join();
205 }
206 
setPhaseOffset(nsecs_t phaseOffset)207 void EventThread::setPhaseOffset(nsecs_t phaseOffset) {
208     std::lock_guard<std::mutex> lock(mMutex);
209     mVSyncSource->setPhaseOffset(phaseOffset);
210 }
211 
createEventConnection(ResyncCallback resyncCallback,ISurfaceComposer::ConfigChanged configChanged) const212 sp<EventThreadConnection> EventThread::createEventConnection(
213         ResyncCallback resyncCallback, ISurfaceComposer::ConfigChanged configChanged) const {
214     return new EventThreadConnection(const_cast<EventThread*>(this), std::move(resyncCallback),
215                                      configChanged);
216 }
217 
registerDisplayEventConnection(const sp<EventThreadConnection> & connection)218 status_t EventThread::registerDisplayEventConnection(const sp<EventThreadConnection>& connection) {
219     std::lock_guard<std::mutex> lock(mMutex);
220 
221     // this should never happen
222     auto it = std::find(mDisplayEventConnections.cbegin(),
223             mDisplayEventConnections.cend(), connection);
224     if (it != mDisplayEventConnections.cend()) {
225         ALOGW("DisplayEventConnection %p already exists", connection.get());
226         mCondition.notify_all();
227         return ALREADY_EXISTS;
228     }
229 
230     mDisplayEventConnections.push_back(connection);
231     mCondition.notify_all();
232     return NO_ERROR;
233 }
234 
removeDisplayEventConnectionLocked(const wp<EventThreadConnection> & connection)235 void EventThread::removeDisplayEventConnectionLocked(const wp<EventThreadConnection>& connection) {
236     auto it = std::find(mDisplayEventConnections.cbegin(),
237             mDisplayEventConnections.cend(), connection);
238     if (it != mDisplayEventConnections.cend()) {
239         mDisplayEventConnections.erase(it);
240     }
241 }
242 
setVsyncRate(uint32_t rate,const sp<EventThreadConnection> & connection)243 void EventThread::setVsyncRate(uint32_t rate, const sp<EventThreadConnection>& connection) {
244     if (static_cast<std::underlying_type_t<VSyncRequest>>(rate) < 0) {
245         return;
246     }
247 
248     std::lock_guard<std::mutex> lock(mMutex);
249 
250     const auto request = rate == 0 ? VSyncRequest::None : static_cast<VSyncRequest>(rate);
251     if (connection->vsyncRequest != request) {
252         connection->vsyncRequest = request;
253         mCondition.notify_all();
254     }
255 }
256 
requestNextVsync(const sp<EventThreadConnection> & connection)257 void EventThread::requestNextVsync(const sp<EventThreadConnection>& connection) {
258     if (connection->resyncCallback) {
259         connection->resyncCallback();
260     }
261 
262     std::lock_guard<std::mutex> lock(mMutex);
263 
264     if (connection->vsyncRequest == VSyncRequest::None) {
265         connection->vsyncRequest = VSyncRequest::Single;
266         mCondition.notify_all();
267     }
268 }
269 
onScreenReleased()270 void EventThread::onScreenReleased() {
271     std::lock_guard<std::mutex> lock(mMutex);
272     if (!mVSyncState || mVSyncState->synthetic) {
273         return;
274     }
275 
276     mVSyncState->synthetic = true;
277     mCondition.notify_all();
278 }
279 
onScreenAcquired()280 void EventThread::onScreenAcquired() {
281     std::lock_guard<std::mutex> lock(mMutex);
282     if (!mVSyncState || !mVSyncState->synthetic) {
283         return;
284     }
285 
286     mVSyncState->synthetic = false;
287     mCondition.notify_all();
288 }
289 
onVSyncEvent(nsecs_t timestamp)290 void EventThread::onVSyncEvent(nsecs_t timestamp) {
291     std::lock_guard<std::mutex> lock(mMutex);
292 
293     LOG_FATAL_IF(!mVSyncState);
294     mPendingEvents.push_back(makeVSync(mVSyncState->displayId, timestamp, ++mVSyncState->count));
295     mCondition.notify_all();
296 }
297 
onHotplugReceived(PhysicalDisplayId displayId,bool connected)298 void EventThread::onHotplugReceived(PhysicalDisplayId displayId, bool connected) {
299     std::lock_guard<std::mutex> lock(mMutex);
300 
301     mPendingEvents.push_back(makeHotplug(displayId, systemTime(), connected));
302     mCondition.notify_all();
303 }
304 
onConfigChanged(PhysicalDisplayId displayId,int32_t configId)305 void EventThread::onConfigChanged(PhysicalDisplayId displayId, int32_t configId) {
306     std::lock_guard<std::mutex> lock(mMutex);
307 
308     mPendingEvents.push_back(makeConfigChanged(displayId, configId));
309     mCondition.notify_all();
310 }
311 
threadMain(std::unique_lock<std::mutex> & lock)312 void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
313     DisplayEventConsumers consumers;
314 
315     while (mState != State::Quit) {
316         std::optional<DisplayEventReceiver::Event> event;
317 
318         // Determine next event to dispatch.
319         if (!mPendingEvents.empty()) {
320             event = mPendingEvents.front();
321             mPendingEvents.pop_front();
322 
323             switch (event->header.type) {
324                 case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
325                     if (event->hotplug.connected && !mVSyncState) {
326                         mVSyncState.emplace(event->header.displayId);
327                     } else if (!event->hotplug.connected && mVSyncState &&
328                                mVSyncState->displayId == event->header.displayId) {
329                         mVSyncState.reset();
330                     }
331                     break;
332 
333                 case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
334                     if (mInterceptVSyncsCallback) {
335                         mInterceptVSyncsCallback(event->header.timestamp);
336                     }
337                     break;
338             }
339         }
340 
341         bool vsyncRequested = false;
342 
343         // Find connections that should consume this event.
344         auto it = mDisplayEventConnections.begin();
345         while (it != mDisplayEventConnections.end()) {
346             if (const auto connection = it->promote()) {
347                 vsyncRequested |= connection->vsyncRequest != VSyncRequest::None;
348 
349                 if (event && shouldConsumeEvent(*event, connection)) {
350                     consumers.push_back(connection);
351                 }
352 
353                 ++it;
354             } else {
355                 it = mDisplayEventConnections.erase(it);
356             }
357         }
358 
359         if (!consumers.empty()) {
360             dispatchEvent(*event, consumers);
361             consumers.clear();
362         }
363 
364         State nextState;
365         if (mVSyncState && vsyncRequested) {
366             nextState = mVSyncState->synthetic ? State::SyntheticVSync : State::VSync;
367         } else {
368             ALOGW_IF(!mVSyncState, "Ignoring VSYNC request while display is disconnected");
369             nextState = State::Idle;
370         }
371 
372         if (mState != nextState) {
373             if (mState == State::VSync) {
374                 mVSyncSource->setVSyncEnabled(false);
375             } else if (nextState == State::VSync) {
376                 mVSyncSource->setVSyncEnabled(true);
377             }
378 
379             mState = nextState;
380         }
381 
382         if (event) {
383             continue;
384         }
385 
386         // Wait for event or client registration/request.
387         if (mState == State::Idle) {
388             mCondition.wait(lock);
389         } else {
390             // Generate a fake VSYNC after a long timeout in case the driver stalls. When the
391             // display is off, keep feeding clients at 60 Hz.
392             const auto timeout = mState == State::SyntheticVSync ? 16ms : 1000ms;
393             if (mCondition.wait_for(lock, timeout) == std::cv_status::timeout) {
394                 ALOGW_IF(mState == State::VSync, "Faking VSYNC due to driver stall");
395 
396                 LOG_FATAL_IF(!mVSyncState);
397                 mPendingEvents.push_back(makeVSync(mVSyncState->displayId,
398                                                    systemTime(SYSTEM_TIME_MONOTONIC),
399                                                    ++mVSyncState->count));
400             }
401         }
402     }
403 }
404 
shouldConsumeEvent(const DisplayEventReceiver::Event & event,const sp<EventThreadConnection> & connection) const405 bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event,
406                                      const sp<EventThreadConnection>& connection) const {
407     switch (event.header.type) {
408         case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG:
409             return true;
410 
411         case DisplayEventReceiver::DISPLAY_EVENT_CONFIG_CHANGED:
412             return connection->configChanged == ISurfaceComposer::eConfigChangedDispatch;
413 
414         case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
415             switch (connection->vsyncRequest) {
416                 case VSyncRequest::None:
417                     return false;
418                 case VSyncRequest::Single:
419                     connection->vsyncRequest = VSyncRequest::None;
420                     return true;
421                 case VSyncRequest::Periodic:
422                     return true;
423                 default:
424                     return event.vsync.count % vsyncPeriod(connection->vsyncRequest) == 0;
425             }
426 
427         default:
428             return false;
429     }
430 }
431 
dispatchEvent(const DisplayEventReceiver::Event & event,const DisplayEventConsumers & consumers)432 void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
433                                 const DisplayEventConsumers& consumers) {
434     for (const auto& consumer : consumers) {
435         switch (consumer->postEvent(event)) {
436             case NO_ERROR:
437                 break;
438 
439             case -EAGAIN:
440                 // TODO: Try again if pipe is full.
441                 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
442                       toString(*consumer).c_str());
443                 break;
444 
445             default:
446                 // Treat EPIPE and other errors as fatal.
447                 removeDisplayEventConnectionLocked(consumer);
448         }
449     }
450 }
451 
dump(std::string & result) const452 void EventThread::dump(std::string& result) const {
453     std::lock_guard<std::mutex> lock(mMutex);
454 
455     StringAppendF(&result, "%s: state=%s VSyncState=", mThreadName, toCString(mState));
456     if (mVSyncState) {
457         StringAppendF(&result, "{displayId=%" ANDROID_PHYSICAL_DISPLAY_ID_FORMAT ", count=%u%s}\n",
458                       mVSyncState->displayId, mVSyncState->count,
459                       mVSyncState->synthetic ? ", synthetic" : "");
460     } else {
461         StringAppendF(&result, "none\n");
462     }
463 
464     StringAppendF(&result, "  pending events (count=%zu):\n", mPendingEvents.size());
465     for (const auto& event : mPendingEvents) {
466         StringAppendF(&result, "    %s\n", toString(event).c_str());
467     }
468 
469     StringAppendF(&result, "  connections (count=%zu):\n", mDisplayEventConnections.size());
470     for (const auto& ptr : mDisplayEventConnections) {
471         if (const auto connection = ptr.promote()) {
472             StringAppendF(&result, "    %s\n", toString(*connection).c_str());
473         }
474     }
475 }
476 
toCString(State state)477 const char* EventThread::toCString(State state) {
478     switch (state) {
479         case State::Idle:
480             return "Idle";
481         case State::Quit:
482             return "Quit";
483         case State::SyntheticVSync:
484             return "SyntheticVSync";
485         case State::VSync:
486             return "VSync";
487     }
488 }
489 
490 } // namespace impl
491 } // namespace android
492