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 #include <chrono>
23 #include <cstdint>
24 
25 #include <cutils/compiler.h>
26 #include <cutils/sched_policy.h>
27 
28 #include <gui/DisplayEventReceiver.h>
29 
30 #include <utils/Errors.h>
31 #include <utils/String8.h>
32 #include <utils/Trace.h>
33 
34 #include "EventThread.h"
35 
36 using namespace std::chrono_literals;
37 
38 // ---------------------------------------------------------------------------
39 
40 namespace android {
41 
42 // ---------------------------------------------------------------------------
43 
44 EventThread::~EventThread() = default;
45 
46 namespace impl {
47 
EventThread(VSyncSource * src,ResyncWithRateLimitCallback resyncWithRateLimitCallback,InterceptVSyncsCallback interceptVSyncsCallback,const char * threadName)48 EventThread::EventThread(VSyncSource* src, ResyncWithRateLimitCallback resyncWithRateLimitCallback,
49                          InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName)
50       : mVSyncSource(src),
51         mResyncWithRateLimitCallback(resyncWithRateLimitCallback),
52         mInterceptVSyncsCallback(interceptVSyncsCallback) {
53     for (auto& event : mVSyncEvent) {
54         event.header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
55         event.header.id = 0;
56         event.header.timestamp = 0;
57         event.vsync.count = 0;
58     }
59 
60     mThread = std::thread(&EventThread::threadMain, this);
61 
62     pthread_setname_np(mThread.native_handle(), threadName);
63 
64     pid_t tid = pthread_gettid_np(mThread.native_handle());
65 
66     // Use SCHED_FIFO to minimize jitter
67     constexpr int EVENT_THREAD_PRIORITY = 2;
68     struct sched_param param = {0};
69     param.sched_priority = EVENT_THREAD_PRIORITY;
70     if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, &param) != 0) {
71         ALOGE("Couldn't set SCHED_FIFO for EventThread");
72     }
73 
74     set_sched_policy(tid, SP_FOREGROUND);
75 }
76 
~EventThread()77 EventThread::~EventThread() {
78     {
79         std::lock_guard<std::mutex> lock(mMutex);
80         mKeepRunning = false;
81         mCondition.notify_all();
82     }
83     mThread.join();
84 }
85 
setPhaseOffset(nsecs_t phaseOffset)86 void EventThread::setPhaseOffset(nsecs_t phaseOffset) {
87     std::lock_guard<std::mutex> lock(mMutex);
88     mVSyncSource->setPhaseOffset(phaseOffset);
89 }
90 
createEventConnection() const91 sp<BnDisplayEventConnection> EventThread::createEventConnection() const {
92     return new Connection(const_cast<EventThread*>(this));
93 }
94 
registerDisplayEventConnection(const sp<EventThread::Connection> & connection)95 status_t EventThread::registerDisplayEventConnection(
96         const sp<EventThread::Connection>& connection) {
97     std::lock_guard<std::mutex> lock(mMutex);
98     mDisplayEventConnections.add(connection);
99     mCondition.notify_all();
100     return NO_ERROR;
101 }
102 
removeDisplayEventConnectionLocked(const wp<EventThread::Connection> & connection)103 void EventThread::removeDisplayEventConnectionLocked(const wp<EventThread::Connection>& connection) {
104     mDisplayEventConnections.remove(connection);
105 }
106 
setVsyncRate(uint32_t count,const sp<EventThread::Connection> & connection)107 void EventThread::setVsyncRate(uint32_t count, const sp<EventThread::Connection>& connection) {
108     if (int32_t(count) >= 0) { // server must protect against bad params
109         std::lock_guard<std::mutex> lock(mMutex);
110         const int32_t new_count = (count == 0) ? -1 : count;
111         if (connection->count != new_count) {
112             connection->count = new_count;
113             mCondition.notify_all();
114         }
115     }
116 }
117 
requestNextVsync(const sp<EventThread::Connection> & connection)118 void EventThread::requestNextVsync(const sp<EventThread::Connection>& connection) {
119     std::lock_guard<std::mutex> lock(mMutex);
120 
121     if (mResyncWithRateLimitCallback) {
122         mResyncWithRateLimitCallback();
123     }
124 
125     if (connection->count < 0) {
126         connection->count = 0;
127         mCondition.notify_all();
128     }
129 }
130 
onScreenReleased()131 void EventThread::onScreenReleased() {
132     std::lock_guard<std::mutex> lock(mMutex);
133     if (!mUseSoftwareVSync) {
134         // disable reliance on h/w vsync
135         mUseSoftwareVSync = true;
136         mCondition.notify_all();
137     }
138 }
139 
onScreenAcquired()140 void EventThread::onScreenAcquired() {
141     std::lock_guard<std::mutex> lock(mMutex);
142     if (mUseSoftwareVSync) {
143         // resume use of h/w vsync
144         mUseSoftwareVSync = false;
145         mCondition.notify_all();
146     }
147 }
148 
onVSyncEvent(nsecs_t timestamp)149 void EventThread::onVSyncEvent(nsecs_t timestamp) {
150     std::lock_guard<std::mutex> lock(mMutex);
151     mVSyncEvent[0].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
152     mVSyncEvent[0].header.id = 0;
153     mVSyncEvent[0].header.timestamp = timestamp;
154     mVSyncEvent[0].vsync.count++;
155     mCondition.notify_all();
156 }
157 
onHotplugReceived(int type,bool connected)158 void EventThread::onHotplugReceived(int type, bool connected) {
159     ALOGE_IF(type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES,
160              "received hotplug event for an invalid display (id=%d)", type);
161 
162     std::lock_guard<std::mutex> lock(mMutex);
163     if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
164         DisplayEventReceiver::Event event;
165         event.header.type = DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG;
166         event.header.id = type;
167         event.header.timestamp = systemTime();
168         event.hotplug.connected = connected;
169         mPendingEvents.add(event);
170         mCondition.notify_all();
171     }
172 }
173 
threadMain()174 void EventThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {
175     std::unique_lock<std::mutex> lock(mMutex);
176     while (mKeepRunning) {
177         DisplayEventReceiver::Event event;
178         Vector<sp<EventThread::Connection> > signalConnections;
179         signalConnections = waitForEventLocked(&lock, &event);
180 
181         // dispatch events to listeners...
182         const size_t count = signalConnections.size();
183         for (size_t i = 0; i < count; i++) {
184             const sp<Connection>& conn(signalConnections[i]);
185             // now see if we still need to report this event
186             status_t err = conn->postEvent(event);
187             if (err == -EAGAIN || err == -EWOULDBLOCK) {
188                 // The destination doesn't accept events anymore, it's probably
189                 // full. For now, we just drop the events on the floor.
190                 // FIXME: Note that some events cannot be dropped and would have
191                 // to be re-sent later.
192                 // Right-now we don't have the ability to do this.
193                 ALOGW("EventThread: dropping event (%08x) for connection %p", event.header.type,
194                       conn.get());
195             } else if (err < 0) {
196                 // handle any other error on the pipe as fatal. the only
197                 // reasonable thing to do is to clean-up this connection.
198                 // The most common error we'll get here is -EPIPE.
199                 removeDisplayEventConnectionLocked(signalConnections[i]);
200             }
201         }
202     }
203 }
204 
205 // This will return when (1) a vsync event has been received, and (2) there was
206 // at least one connection interested in receiving it when we started waiting.
waitForEventLocked(std::unique_lock<std::mutex> * lock,DisplayEventReceiver::Event * event)207 Vector<sp<EventThread::Connection> > EventThread::waitForEventLocked(
208         std::unique_lock<std::mutex>* lock, DisplayEventReceiver::Event* event) {
209     Vector<sp<EventThread::Connection> > signalConnections;
210 
211     while (signalConnections.isEmpty() && mKeepRunning) {
212         bool eventPending = false;
213         bool waitForVSync = false;
214 
215         size_t vsyncCount = 0;
216         nsecs_t timestamp = 0;
217         for (int32_t i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; i++) {
218             timestamp = mVSyncEvent[i].header.timestamp;
219             if (timestamp) {
220                 // we have a vsync event to dispatch
221                 if (mInterceptVSyncsCallback) {
222                     mInterceptVSyncsCallback(timestamp);
223                 }
224                 *event = mVSyncEvent[i];
225                 mVSyncEvent[i].header.timestamp = 0;
226                 vsyncCount = mVSyncEvent[i].vsync.count;
227                 break;
228             }
229         }
230 
231         if (!timestamp) {
232             // no vsync event, see if there are some other event
233             eventPending = !mPendingEvents.isEmpty();
234             if (eventPending) {
235                 // we have some other event to dispatch
236                 *event = mPendingEvents[0];
237                 mPendingEvents.removeAt(0);
238             }
239         }
240 
241         // find out connections waiting for events
242         size_t count = mDisplayEventConnections.size();
243         for (size_t i = 0; i < count;) {
244             sp<Connection> connection(mDisplayEventConnections[i].promote());
245             if (connection != nullptr) {
246                 bool added = false;
247                 if (connection->count >= 0) {
248                     // we need vsync events because at least
249                     // one connection is waiting for it
250                     waitForVSync = true;
251                     if (timestamp) {
252                         // we consume the event only if it's time
253                         // (ie: we received a vsync event)
254                         if (connection->count == 0) {
255                             // fired this time around
256                             connection->count = -1;
257                             signalConnections.add(connection);
258                             added = true;
259                         } else if (connection->count == 1 ||
260                                    (vsyncCount % connection->count) == 0) {
261                             // continuous event, and time to report it
262                             signalConnections.add(connection);
263                             added = true;
264                         }
265                     }
266                 }
267 
268                 if (eventPending && !timestamp && !added) {
269                     // we don't have a vsync event to process
270                     // (timestamp==0), but we have some pending
271                     // messages.
272                     signalConnections.add(connection);
273                 }
274                 ++i;
275             } else {
276                 // we couldn't promote this reference, the connection has
277                 // died, so clean-up!
278                 mDisplayEventConnections.removeAt(i);
279                 --count;
280             }
281         }
282 
283         // Here we figure out if we need to enable or disable vsyncs
284         if (timestamp && !waitForVSync) {
285             // we received a VSYNC but we have no clients
286             // don't report it, and disable VSYNC events
287             disableVSyncLocked();
288         } else if (!timestamp && waitForVSync) {
289             // we have at least one client, so we want vsync enabled
290             // (TODO: this function is called right after we finish
291             // notifying clients of a vsync, so this call will be made
292             // at the vsync rate, e.g. 60fps.  If we can accurately
293             // track the current state we could avoid making this call
294             // so often.)
295             enableVSyncLocked();
296         }
297 
298         // note: !timestamp implies signalConnections.isEmpty(), because we
299         // don't populate signalConnections if there's no vsync pending
300         if (!timestamp && !eventPending) {
301             // wait for something to happen
302             if (waitForVSync) {
303                 // This is where we spend most of our time, waiting
304                 // for vsync events and new client registrations.
305                 //
306                 // If the screen is off, we can't use h/w vsync, so we
307                 // use a 16ms timeout instead.  It doesn't need to be
308                 // precise, we just need to keep feeding our clients.
309                 //
310                 // We don't want to stall if there's a driver bug, so we
311                 // use a (long) timeout when waiting for h/w vsync, and
312                 // generate fake events when necessary.
313                 bool softwareSync = mUseSoftwareVSync;
314                 auto timeout = softwareSync ? 16ms : 1000ms;
315                 if (mCondition.wait_for(*lock, timeout) == std::cv_status::timeout) {
316                     if (!softwareSync) {
317                         ALOGW("Timed out waiting for hw vsync; faking it");
318                     }
319                     // FIXME: how do we decide which display id the fake
320                     // vsync came from ?
321                     mVSyncEvent[0].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
322                     mVSyncEvent[0].header.id = DisplayDevice::DISPLAY_PRIMARY;
323                     mVSyncEvent[0].header.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
324                     mVSyncEvent[0].vsync.count++;
325                 }
326             } else {
327                 // Nobody is interested in vsync, so we just want to sleep.
328                 // h/w vsync should be disabled, so this will wait until we
329                 // get a new connection, or an existing connection becomes
330                 // interested in receiving vsync again.
331                 mCondition.wait(*lock);
332             }
333         }
334     }
335 
336     // here we're guaranteed to have a timestamp and some connections to signal
337     // (The connections might have dropped out of mDisplayEventConnections
338     // while we were asleep, but we'll still have strong references to them.)
339     return signalConnections;
340 }
341 
enableVSyncLocked()342 void EventThread::enableVSyncLocked() {
343     if (!mUseSoftwareVSync) {
344         // never enable h/w VSYNC when screen is off
345         if (!mVsyncEnabled) {
346             mVsyncEnabled = true;
347             mVSyncSource->setCallback(this);
348             mVSyncSource->setVSyncEnabled(true);
349         }
350     }
351     mDebugVsyncEnabled = true;
352 }
353 
disableVSyncLocked()354 void EventThread::disableVSyncLocked() {
355     if (mVsyncEnabled) {
356         mVsyncEnabled = false;
357         mVSyncSource->setVSyncEnabled(false);
358         mDebugVsyncEnabled = false;
359     }
360 }
361 
dump(String8 & result) const362 void EventThread::dump(String8& result) const {
363     std::lock_guard<std::mutex> lock(mMutex);
364     result.appendFormat("VSYNC state: %s\n", mDebugVsyncEnabled ? "enabled" : "disabled");
365     result.appendFormat("  soft-vsync: %s\n", mUseSoftwareVSync ? "enabled" : "disabled");
366     result.appendFormat("  numListeners=%zu,\n  events-delivered: %u\n",
367                         mDisplayEventConnections.size(),
368                         mVSyncEvent[DisplayDevice::DISPLAY_PRIMARY].vsync.count);
369     for (size_t i = 0; i < mDisplayEventConnections.size(); i++) {
370         sp<Connection> connection = mDisplayEventConnections.itemAt(i).promote();
371         result.appendFormat("    %p: count=%d\n", connection.get(),
372                             connection != nullptr ? connection->count : 0);
373     }
374 }
375 
376 // ---------------------------------------------------------------------------
377 
Connection(EventThread * eventThread)378 EventThread::Connection::Connection(EventThread* eventThread)
379       : count(-1), mEventThread(eventThread), mChannel(gui::BitTube::DefaultSize) {}
380 
~Connection()381 EventThread::Connection::~Connection() {
382     // do nothing here -- clean-up will happen automatically
383     // when the main thread wakes up
384 }
385 
onFirstRef()386 void EventThread::Connection::onFirstRef() {
387     // NOTE: mEventThread doesn't hold a strong reference on us
388     mEventThread->registerDisplayEventConnection(this);
389 }
390 
stealReceiveChannel(gui::BitTube * outChannel)391 status_t EventThread::Connection::stealReceiveChannel(gui::BitTube* outChannel) {
392     outChannel->setReceiveFd(mChannel.moveReceiveFd());
393     return NO_ERROR;
394 }
395 
setVsyncRate(uint32_t count)396 status_t EventThread::Connection::setVsyncRate(uint32_t count) {
397     mEventThread->setVsyncRate(count, this);
398     return NO_ERROR;
399 }
400 
requestNextVsync()401 void EventThread::Connection::requestNextVsync() {
402     mEventThread->requestNextVsync(this);
403 }
404 
postEvent(const DisplayEventReceiver::Event & event)405 status_t EventThread::Connection::postEvent(const DisplayEventReceiver::Event& event) {
406     ssize_t size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
407     return size < 0 ? status_t(size) : status_t(NO_ERROR);
408 }
409 
410 // ---------------------------------------------------------------------------
411 
412 } // namespace impl
413 } // namespace android
414