1 /*
2 * Copyright (C) 2007 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_NDEBUG 0
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
20 #include <stdint.h>
21 #include <sys/types.h>
22 #include <algorithm>
23 #include <errno.h>
24 #include <math.h>
25 #include <mutex>
26 #include <dlfcn.h>
27 #include <inttypes.h>
28 #include <stdatomic.h>
29 #include <optional>
30
31 #include <EGL/egl.h>
32
33 #include <cutils/properties.h>
34 #include <log/log.h>
35
36 #include <binder/IPCThreadState.h>
37 #include <binder/IServiceManager.h>
38 #include <binder/PermissionCache.h>
39
40 #include <dvr/vr_flinger.h>
41
42 #include <ui/DebugUtils.h>
43 #include <ui/DisplayInfo.h>
44 #include <ui/DisplayStatInfo.h>
45
46 #include <gui/BufferQueue.h>
47 #include <gui/GuiConfig.h>
48 #include <gui/IDisplayEventConnection.h>
49 #include <gui/Surface.h>
50
51 #include <ui/GraphicBufferAllocator.h>
52 #include <ui/PixelFormat.h>
53 #include <ui/UiConfig.h>
54
55 #include <utils/misc.h>
56 #include <utils/String8.h>
57 #include <utils/String16.h>
58 #include <utils/StopWatch.h>
59 #include <utils/Timers.h>
60 #include <utils/Trace.h>
61
62 #include <private/android_filesystem_config.h>
63 #include <private/gui/SyncFeatures.h>
64
65 #include "Client.h"
66 #include "clz.h"
67 #include "Colorizer.h"
68 #include "DdmConnection.h"
69 #include "DisplayDevice.h"
70 #include "DispSync.h"
71 #include "EventControlThread.h"
72 #include "EventThread.h"
73 #include "Layer.h"
74 #include "LayerVector.h"
75 #include "LayerDim.h"
76 #include "MonitoredProducer.h"
77 #include "SurfaceFlinger.h"
78
79 #include "DisplayHardware/ComposerHal.h"
80 #include "DisplayHardware/FramebufferSurface.h"
81 #include "DisplayHardware/HWComposer.h"
82 #include "DisplayHardware/VirtualDisplaySurface.h"
83
84 #include "Effects/Daltonizer.h"
85
86 #include "RenderEngine/RenderEngine.h"
87 #include <cutils/compiler.h>
88
89 #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
90 #include <configstore/Utils.h>
91
92 #define DISPLAY_COUNT 1
93
94 /*
95 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
96 * black pixels.
97 */
98 #define DEBUG_SCREENSHOTS false
99
100 extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
101
102 namespace android {
103
104 using namespace android::hardware::configstore;
105 using namespace android::hardware::configstore::V1_0;
106
107 namespace {
108 class ConditionalLock {
109 public:
ConditionalLock(Mutex & mutex,bool lock)110 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
111 if (lock) {
112 mMutex.lock();
113 }
114 }
~ConditionalLock()115 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
116 private:
117 Mutex& mMutex;
118 bool mLocked;
119 };
120 } // namespace anonymous
121
122 // ---------------------------------------------------------------------------
123
124 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127 const String16 sDump("android.permission.DUMP");
128
129 // ---------------------------------------------------------------------------
130 int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
131 int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
132 bool SurfaceFlinger::useContextPriority;
133 int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
134 bool SurfaceFlinger::useHwcForRgbToYuv;
135 uint64_t SurfaceFlinger::maxVirtualDisplaySize;
136 bool SurfaceFlinger::hasSyncFramework;
137 bool SurfaceFlinger::useVrFlinger;
138 int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
139 bool SurfaceFlinger::hasWideColorDisplay;
140
SurfaceFlinger()141 SurfaceFlinger::SurfaceFlinger()
142 : BnSurfaceComposer(),
143 mTransactionFlags(0),
144 mTransactionPending(false),
145 mAnimTransactionPending(false),
146 mLayersRemoved(false),
147 mLayersAdded(false),
148 mRepaintEverything(0),
149 mRenderEngine(nullptr),
150 mBootTime(systemTime()),
151 mBuiltinDisplays(),
152 mVisibleRegionsDirty(false),
153 mGeometryInvalid(false),
154 mAnimCompositionPending(false),
155 mDebugRegion(0),
156 mDebugDDMS(0),
157 mDebugDisableHWC(0),
158 mDebugDisableTransformHint(0),
159 mDebugInSwapBuffers(0),
160 mLastSwapBufferTime(0),
161 mDebugInTransaction(0),
162 mLastTransactionTime(0),
163 mBootFinished(false),
164 mForceFullDamage(false),
165 mInterceptor(this),
166 mPrimaryDispSync("PrimaryDispSync"),
167 mPrimaryHWVsyncEnabled(false),
168 mHWVsyncAvailable(false),
169 mHasColorMatrix(false),
170 mHasPoweredOff(false),
171 mFrameBuckets(),
172 mTotalTime(0),
173 mLastSwapTime(0),
174 mNumLayers(0),
175 mVrFlingerRequestsDisplay(false),
176 mMainThreadId(std::this_thread::get_id()),
177 mComposerSequenceId(0)
178 {
179 ALOGI("SurfaceFlinger is starting");
180
181 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
183
184 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
186
187 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
188 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
189
190 useContextPriority = getBool< ISurfaceFlingerConfigs,
191 &ISurfaceFlingerConfigs::useContextPriority>(false);
192
193 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
194 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
195
196 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
197 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
198
199 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
200 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
201
202 // Vr flinger is only enabled on Daydream ready devices.
203 useVrFlinger = getBool< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::useVrFlinger>(false);
205
206 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
208
209 hasWideColorDisplay =
210 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
211
212 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
213
214 // debugging stuff...
215 char value[PROPERTY_VALUE_MAX];
216
217 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
218 mGpuToCpuSupported = !atoi(value);
219
220 property_get("debug.sf.showupdates", value, "0");
221 mDebugRegion = atoi(value);
222
223 property_get("debug.sf.ddms", value, "0");
224 mDebugDDMS = atoi(value);
225 if (mDebugDDMS) {
226 if (!startDdmConnection()) {
227 // start failed, and DDMS debugging not enabled
228 mDebugDDMS = 0;
229 }
230 }
231 ALOGI_IF(mDebugRegion, "showupdates enabled");
232 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
233
234 property_get("debug.sf.disable_backpressure", value, "0");
235 mPropagateBackpressure = !atoi(value);
236 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
237
238 property_get("debug.sf.enable_hwc_vds", value, "0");
239 mUseHwcVirtualDisplays = atoi(value);
240 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
241
242 property_get("ro.sf.disable_triple_buffer", value, "1");
243 mLayerTripleBufferingDisabled = atoi(value);
244 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
245
246 // We should be reading 'persist.sys.sf.color_saturation' here
247 // but since /data may be encrypted, we need to wait until after vold
248 // comes online to attempt to read the property. The property is
249 // instead read after the boot animation
250 }
251
onFirstRef()252 void SurfaceFlinger::onFirstRef()
253 {
254 mEventQueue.init(this);
255 }
256
~SurfaceFlinger()257 SurfaceFlinger::~SurfaceFlinger()
258 {
259 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
260 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
261 eglTerminate(display);
262 }
263
binderDied(const wp<IBinder> &)264 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
265 {
266 // the window manager died on us. prepare its eulogy.
267
268 // restore initial conditions (default device unblank, etc)
269 initializeDisplays();
270
271 // restart the boot-animation
272 startBootAnim();
273 }
274
initClient(const sp<Client> & client)275 static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
276 status_t err = client->initCheck();
277 if (err == NO_ERROR) {
278 return client;
279 }
280 return nullptr;
281 }
282
createConnection()283 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
284 return initClient(new Client(this));
285 }
286
createScopedConnection(const sp<IGraphicBufferProducer> & gbp)287 sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
288 const sp<IGraphicBufferProducer>& gbp) {
289 if (authenticateSurfaceTexture(gbp) == false) {
290 return nullptr;
291 }
292 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
293 if (layer == nullptr) {
294 return nullptr;
295 }
296
297 return initClient(new Client(this, layer));
298 }
299
createDisplay(const String8 & displayName,bool secure)300 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
301 bool secure)
302 {
303 class DisplayToken : public BBinder {
304 sp<SurfaceFlinger> flinger;
305 virtual ~DisplayToken() {
306 // no more references, this display must be terminated
307 Mutex::Autolock _l(flinger->mStateLock);
308 flinger->mCurrentState.displays.removeItem(this);
309 flinger->setTransactionFlags(eDisplayTransactionNeeded);
310 }
311 public:
312 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
313 : flinger(flinger) {
314 }
315 };
316
317 sp<BBinder> token = new DisplayToken(this);
318
319 Mutex::Autolock _l(mStateLock);
320 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
321 info.displayName = displayName;
322 mCurrentState.displays.add(token, info);
323 mInterceptor.saveDisplayCreation(info);
324 return token;
325 }
326
destroyDisplay(const sp<IBinder> & display)327 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
328 Mutex::Autolock _l(mStateLock);
329
330 ssize_t idx = mCurrentState.displays.indexOfKey(display);
331 if (idx < 0) {
332 ALOGW("destroyDisplay: invalid display token");
333 return;
334 }
335
336 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
337 if (!info.isVirtualDisplay()) {
338 ALOGE("destroyDisplay called for non-virtual display");
339 return;
340 }
341 mInterceptor.saveDisplayDeletion(info.displayId);
342 mCurrentState.displays.removeItemsAt(idx);
343 setTransactionFlags(eDisplayTransactionNeeded);
344 }
345
createBuiltinDisplayLocked(DisplayDevice::DisplayType type)346 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
347 ALOGV("createBuiltinDisplayLocked(%d)", type);
348 ALOGW_IF(mBuiltinDisplays[type],
349 "Overwriting display token for display type %d", type);
350 mBuiltinDisplays[type] = new BBinder();
351 // All non-virtual displays are currently considered secure.
352 DisplayDeviceState info(type, true);
353 mCurrentState.displays.add(mBuiltinDisplays[type], info);
354 mInterceptor.saveDisplayCreation(info);
355 }
356
getBuiltInDisplay(int32_t id)357 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
358 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
359 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
360 return NULL;
361 }
362 return mBuiltinDisplays[id];
363 }
364
bootFinished()365 void SurfaceFlinger::bootFinished()
366 {
367 if (mStartPropertySetThread->join() != NO_ERROR) {
368 ALOGE("Join StartPropertySetThread failed!");
369 }
370 const nsecs_t now = systemTime();
371 const nsecs_t duration = now - mBootTime;
372 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
373
374 // wait patiently for the window manager death
375 const String16 name("window");
376 sp<IBinder> window(defaultServiceManager()->getService(name));
377 if (window != 0) {
378 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
379 }
380
381 if (mVrFlinger) {
382 mVrFlinger->OnBootFinished();
383 }
384
385 // stop boot animation
386 // formerly we would just kill the process, but we now ask it to exit so it
387 // can choose where to stop the animation.
388 property_set("service.bootanim.exit", "1");
389
390 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
391 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
392 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
393
394 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
395 readPersistentProperties();
396 });
397 postMessageAsync(readProperties);
398 }
399
deleteTextureAsync(uint32_t texture)400 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
401 class MessageDestroyGLTexture : public MessageBase {
402 RenderEngine& engine;
403 uint32_t texture;
404 public:
405 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
406 : engine(engine), texture(texture) {
407 }
408 virtual bool handler() {
409 engine.deleteTextures(1, &texture);
410 return true;
411 }
412 };
413 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
414 }
415
416 class DispSyncSource : public VSyncSource, private DispSync::Callback {
417 public:
DispSyncSource(DispSync * dispSync,nsecs_t phaseOffset,bool traceVsync,const char * name)418 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
419 const char* name) :
420 mName(name),
421 mValue(0),
422 mTraceVsync(traceVsync),
423 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
424 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
425 mDispSync(dispSync),
426 mCallbackMutex(),
427 mCallback(),
428 mVsyncMutex(),
429 mPhaseOffset(phaseOffset),
430 mEnabled(false) {}
431
~DispSyncSource()432 virtual ~DispSyncSource() {}
433
setVSyncEnabled(bool enable)434 virtual void setVSyncEnabled(bool enable) {
435 Mutex::Autolock lock(mVsyncMutex);
436 if (enable) {
437 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
438 static_cast<DispSync::Callback*>(this));
439 if (err != NO_ERROR) {
440 ALOGE("error registering vsync callback: %s (%d)",
441 strerror(-err), err);
442 }
443 //ATRACE_INT(mVsyncOnLabel.string(), 1);
444 } else {
445 status_t err = mDispSync->removeEventListener(
446 static_cast<DispSync::Callback*>(this));
447 if (err != NO_ERROR) {
448 ALOGE("error unregistering vsync callback: %s (%d)",
449 strerror(-err), err);
450 }
451 //ATRACE_INT(mVsyncOnLabel.string(), 0);
452 }
453 mEnabled = enable;
454 }
455
setCallback(const sp<VSyncSource::Callback> & callback)456 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
457 Mutex::Autolock lock(mCallbackMutex);
458 mCallback = callback;
459 }
460
setPhaseOffset(nsecs_t phaseOffset)461 virtual void setPhaseOffset(nsecs_t phaseOffset) {
462 Mutex::Autolock lock(mVsyncMutex);
463
464 // Normalize phaseOffset to [0, period)
465 auto period = mDispSync->getPeriod();
466 phaseOffset %= period;
467 if (phaseOffset < 0) {
468 // If we're here, then phaseOffset is in (-period, 0). After this
469 // operation, it will be in (0, period)
470 phaseOffset += period;
471 }
472 mPhaseOffset = phaseOffset;
473
474 // If we're not enabled, we don't need to mess with the listeners
475 if (!mEnabled) {
476 return;
477 }
478
479 // Remove the listener with the old offset
480 status_t err = mDispSync->removeEventListener(
481 static_cast<DispSync::Callback*>(this));
482 if (err != NO_ERROR) {
483 ALOGE("error unregistering vsync callback: %s (%d)",
484 strerror(-err), err);
485 }
486
487 // Add a listener with the new offset
488 err = mDispSync->addEventListener(mName, mPhaseOffset,
489 static_cast<DispSync::Callback*>(this));
490 if (err != NO_ERROR) {
491 ALOGE("error registering vsync callback: %s (%d)",
492 strerror(-err), err);
493 }
494 }
495
496 private:
onDispSyncEvent(nsecs_t when)497 virtual void onDispSyncEvent(nsecs_t when) {
498 sp<VSyncSource::Callback> callback;
499 {
500 Mutex::Autolock lock(mCallbackMutex);
501 callback = mCallback;
502
503 if (mTraceVsync) {
504 mValue = (mValue + 1) % 2;
505 ATRACE_INT(mVsyncEventLabel.string(), mValue);
506 }
507 }
508
509 if (callback != NULL) {
510 callback->onVSyncEvent(when);
511 }
512 }
513
514 const char* const mName;
515
516 int mValue;
517
518 const bool mTraceVsync;
519 const String8 mVsyncOnLabel;
520 const String8 mVsyncEventLabel;
521
522 DispSync* mDispSync;
523
524 Mutex mCallbackMutex; // Protects the following
525 sp<VSyncSource::Callback> mCallback;
526
527 Mutex mVsyncMutex; // Protects the following
528 nsecs_t mPhaseOffset;
529 bool mEnabled;
530 };
531
532 class InjectVSyncSource : public VSyncSource {
533 public:
InjectVSyncSource()534 InjectVSyncSource() {}
535
~InjectVSyncSource()536 virtual ~InjectVSyncSource() {}
537
setCallback(const sp<VSyncSource::Callback> & callback)538 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
539 std::lock_guard<std::mutex> lock(mCallbackMutex);
540 mCallback = callback;
541 }
542
onInjectSyncEvent(nsecs_t when)543 virtual void onInjectSyncEvent(nsecs_t when) {
544 std::lock_guard<std::mutex> lock(mCallbackMutex);
545 if (mCallback != nullptr) {
546 mCallback->onVSyncEvent(when);
547 }
548 }
549
setVSyncEnabled(bool)550 virtual void setVSyncEnabled(bool) {}
setPhaseOffset(nsecs_t)551 virtual void setPhaseOffset(nsecs_t) {}
552
553 private:
554 std::mutex mCallbackMutex; // Protects the following
555 sp<VSyncSource::Callback> mCallback;
556 };
557
558 // Do not call property_set on main thread which will be blocked by init
559 // Use StartPropertySetThread instead.
init()560 void SurfaceFlinger::init() {
561 ALOGI( "SurfaceFlinger's main thread ready to run. "
562 "Initializing graphics H/W...");
563
564 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
565
566 Mutex::Autolock _l(mStateLock);
567
568 // initialize EGL for the default display
569 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
570 eglInitialize(mEGLDisplay, NULL, NULL);
571
572 // start the EventThread
573 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
574 vsyncPhaseOffsetNs, true, "app");
575 mEventThread = new EventThread(vsyncSrc, *this, false);
576 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
577 sfVsyncPhaseOffsetNs, true, "sf");
578 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
579 mEventQueue.setEventThread(mSFEventThread);
580
581 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
582 struct sched_param param = {0};
583 param.sched_priority = 2;
584 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, ¶m) != 0) {
585 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
586 }
587 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, ¶m) != 0) {
588 ALOGE("Couldn't set SCHED_FIFO for EventThread");
589 }
590
591 // Get a RenderEngine for the given display / config (can't fail)
592 mRenderEngine = RenderEngine::create(mEGLDisplay,
593 HAL_PIXEL_FORMAT_RGBA_8888,
594 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
595
596 // retrieve the EGL context that was selected/created
597 mEGLContext = mRenderEngine->getEGLContext();
598
599 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
600 "couldn't create EGLContext");
601
602 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
603 "Starting with vr flinger active is not currently supported.");
604 mHwc.reset(new HWComposer(false));
605 mHwc->registerCallback(this, mComposerSequenceId);
606
607 if (useVrFlinger) {
608 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
609 // This callback is called from the vr flinger dispatch thread. We
610 // need to call signalTransaction(), which requires holding
611 // mStateLock when we're not on the main thread. Acquiring
612 // mStateLock from the vr flinger dispatch thread might trigger a
613 // deadlock in surface flinger (see b/66916578), so post a message
614 // to be handled on the main thread instead.
615 sp<LambdaMessage> message = new LambdaMessage([=]() {
616 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
617 mVrFlingerRequestsDisplay = requestDisplay;
618 signalTransaction();
619 });
620 postMessageAsync(message);
621 };
622 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
623 vrFlingerRequestDisplayCallback);
624 if (!mVrFlinger) {
625 ALOGE("Failed to start vrflinger");
626 }
627 }
628
629 mEventControlThread = new EventControlThread(this);
630 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
631
632 // initialize our drawing state
633 mDrawingState = mCurrentState;
634
635 // set initial conditions (e.g. unblank default device)
636 initializeDisplays();
637
638 mRenderEngine->primeCache();
639
640 // Inform native graphics APIs whether the present timestamp is supported:
641 if (getHwComposer().hasCapability(
642 HWC2::Capability::PresentFenceIsNotReliable)) {
643 mStartPropertySetThread = new StartPropertySetThread(false);
644 } else {
645 mStartPropertySetThread = new StartPropertySetThread(true);
646 }
647
648 if (mStartPropertySetThread->Start() != NO_ERROR) {
649 ALOGE("Run StartPropertySetThread failed!");
650 }
651
652 ALOGV("Done initializing");
653 }
654
readPersistentProperties()655 void SurfaceFlinger::readPersistentProperties() {
656 char value[PROPERTY_VALUE_MAX];
657
658 property_get("persist.sys.sf.color_saturation", value, "1.0");
659 mSaturation = atof(value);
660 ALOGV("Saturation is set to %.2f", mSaturation);
661
662 property_get("persist.sys.sf.native_mode", value, "0");
663 mForceNativeColorMode = atoi(value) == 1;
664 if (mForceNativeColorMode) {
665 ALOGV("Forcing native color mode");
666 }
667 }
668
startBootAnim()669 void SurfaceFlinger::startBootAnim() {
670 // Start boot animation service by setting a property mailbox
671 // if property setting thread is already running, Start() will be just a NOP
672 mStartPropertySetThread->Start();
673 // Wait until property was set
674 if (mStartPropertySetThread->join() != NO_ERROR) {
675 ALOGE("Join StartPropertySetThread failed!");
676 }
677 }
678
getMaxTextureSize() const679 size_t SurfaceFlinger::getMaxTextureSize() const {
680 return mRenderEngine->getMaxTextureSize();
681 }
682
getMaxViewportDims() const683 size_t SurfaceFlinger::getMaxViewportDims() const {
684 return mRenderEngine->getMaxViewportDims();
685 }
686
687 // ----------------------------------------------------------------------------
688
authenticateSurfaceTexture(const sp<IGraphicBufferProducer> & bufferProducer) const689 bool SurfaceFlinger::authenticateSurfaceTexture(
690 const sp<IGraphicBufferProducer>& bufferProducer) const {
691 Mutex::Autolock _l(mStateLock);
692 return authenticateSurfaceTextureLocked(bufferProducer);
693 }
694
authenticateSurfaceTextureLocked(const sp<IGraphicBufferProducer> & bufferProducer) const695 bool SurfaceFlinger::authenticateSurfaceTextureLocked(
696 const sp<IGraphicBufferProducer>& bufferProducer) const {
697 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
698 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
699 }
700
getSupportedFrameTimestamps(std::vector<FrameEvent> * outSupported) const701 status_t SurfaceFlinger::getSupportedFrameTimestamps(
702 std::vector<FrameEvent>* outSupported) const {
703 *outSupported = {
704 FrameEvent::REQUESTED_PRESENT,
705 FrameEvent::ACQUIRE,
706 FrameEvent::LATCH,
707 FrameEvent::FIRST_REFRESH_START,
708 FrameEvent::LAST_REFRESH_START,
709 FrameEvent::GPU_COMPOSITION_DONE,
710 FrameEvent::DEQUEUE_READY,
711 FrameEvent::RELEASE,
712 };
713 ConditionalLock _l(mStateLock,
714 std::this_thread::get_id() != mMainThreadId);
715 if (!getHwComposer().hasCapability(
716 HWC2::Capability::PresentFenceIsNotReliable)) {
717 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
718 }
719 return NO_ERROR;
720 }
721
getDisplayConfigs(const sp<IBinder> & display,Vector<DisplayInfo> * configs)722 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
723 Vector<DisplayInfo>* configs) {
724 if ((configs == NULL) || (display.get() == NULL)) {
725 return BAD_VALUE;
726 }
727
728 if (!display.get())
729 return NAME_NOT_FOUND;
730
731 int32_t type = NAME_NOT_FOUND;
732 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
733 if (display == mBuiltinDisplays[i]) {
734 type = i;
735 break;
736 }
737 }
738
739 if (type < 0) {
740 return type;
741 }
742
743 // TODO: Not sure if display density should handled by SF any longer
744 class Density {
745 static int getDensityFromProperty(char const* propName) {
746 char property[PROPERTY_VALUE_MAX];
747 int density = 0;
748 if (property_get(propName, property, NULL) > 0) {
749 density = atoi(property);
750 }
751 return density;
752 }
753 public:
754 static int getEmuDensity() {
755 return getDensityFromProperty("qemu.sf.lcd_density"); }
756 static int getBuildDensity() {
757 return getDensityFromProperty("ro.sf.lcd_density"); }
758 };
759
760 configs->clear();
761
762 ConditionalLock _l(mStateLock,
763 std::this_thread::get_id() != mMainThreadId);
764 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
765 DisplayInfo info = DisplayInfo();
766
767 float xdpi = hwConfig->getDpiX();
768 float ydpi = hwConfig->getDpiY();
769
770 if (type == DisplayDevice::DISPLAY_PRIMARY) {
771 // The density of the device is provided by a build property
772 float density = Density::getBuildDensity() / 160.0f;
773 if (density == 0) {
774 // the build doesn't provide a density -- this is wrong!
775 // use xdpi instead
776 ALOGE("ro.sf.lcd_density must be defined as a build property");
777 density = xdpi / 160.0f;
778 }
779 if (Density::getEmuDensity()) {
780 // if "qemu.sf.lcd_density" is specified, it overrides everything
781 xdpi = ydpi = density = Density::getEmuDensity();
782 density /= 160.0f;
783 }
784 info.density = density;
785
786 // TODO: this needs to go away (currently needed only by webkit)
787 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
788 info.orientation = hw->getOrientation();
789 } else {
790 // TODO: where should this value come from?
791 static const int TV_DENSITY = 213;
792 info.density = TV_DENSITY / 160.0f;
793 info.orientation = 0;
794 }
795
796 info.w = hwConfig->getWidth();
797 info.h = hwConfig->getHeight();
798 info.xdpi = xdpi;
799 info.ydpi = ydpi;
800 info.fps = 1e9 / hwConfig->getVsyncPeriod();
801 info.appVsyncOffset = vsyncPhaseOffsetNs;
802
803 // This is how far in advance a buffer must be queued for
804 // presentation at a given time. If you want a buffer to appear
805 // on the screen at time N, you must submit the buffer before
806 // (N - presentationDeadline).
807 //
808 // Normally it's one full refresh period (to give SF a chance to
809 // latch the buffer), but this can be reduced by configuring a
810 // DispSync offset. Any additional delays introduced by the hardware
811 // composer or panel must be accounted for here.
812 //
813 // We add an additional 1ms to allow for processing time and
814 // differences between the ideal and actual refresh rate.
815 info.presentationDeadline = hwConfig->getVsyncPeriod() -
816 sfVsyncPhaseOffsetNs + 1000000;
817
818 // All non-virtual displays are currently considered secure.
819 info.secure = true;
820
821 configs->push_back(info);
822 }
823
824 return NO_ERROR;
825 }
826
getDisplayStats(const sp<IBinder> &,DisplayStatInfo * stats)827 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
828 DisplayStatInfo* stats) {
829 if (stats == NULL) {
830 return BAD_VALUE;
831 }
832
833 // FIXME for now we always return stats for the primary display
834 memset(stats, 0, sizeof(*stats));
835 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
836 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
837 return NO_ERROR;
838 }
839
getActiveConfig(const sp<IBinder> & display)840 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
841 if (display == NULL) {
842 ALOGE("%s : display is NULL", __func__);
843 return BAD_VALUE;
844 }
845
846 sp<const DisplayDevice> device(getDisplayDevice(display));
847 if (device != NULL) {
848 return device->getActiveConfig();
849 }
850
851 return BAD_VALUE;
852 }
853
setActiveConfigInternal(const sp<DisplayDevice> & hw,int mode)854 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
855 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
856 this);
857 int32_t type = hw->getDisplayType();
858 int currentMode = hw->getActiveConfig();
859
860 if (mode == currentMode) {
861 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
862 return;
863 }
864
865 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
866 ALOGW("Trying to set config for virtual display");
867 return;
868 }
869
870 hw->setActiveConfig(mode);
871 getHwComposer().setActiveConfig(type, mode);
872 }
873
setActiveConfig(const sp<IBinder> & display,int mode)874 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
875 class MessageSetActiveConfig: public MessageBase {
876 SurfaceFlinger& mFlinger;
877 sp<IBinder> mDisplay;
878 int mMode;
879 public:
880 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
881 int mode) :
882 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
883 virtual bool handler() {
884 Vector<DisplayInfo> configs;
885 mFlinger.getDisplayConfigs(mDisplay, &configs);
886 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
887 ALOGE("Attempt to set active config = %d for display with %zu configs",
888 mMode, configs.size());
889 return true;
890 }
891 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
892 if (hw == NULL) {
893 ALOGE("Attempt to set active config = %d for null display %p",
894 mMode, mDisplay.get());
895 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
896 ALOGW("Attempt to set active config = %d for virtual display",
897 mMode);
898 } else {
899 mFlinger.setActiveConfigInternal(hw, mMode);
900 }
901 return true;
902 }
903 };
904 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
905 postMessageSync(msg);
906 return NO_ERROR;
907 }
getDisplayColorModes(const sp<IBinder> & display,Vector<android_color_mode_t> * outColorModes)908 status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
909 Vector<android_color_mode_t>* outColorModes) {
910 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
911 return BAD_VALUE;
912 }
913
914 if (!display.get()) {
915 return NAME_NOT_FOUND;
916 }
917
918 int32_t type = NAME_NOT_FOUND;
919 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
920 if (display == mBuiltinDisplays[i]) {
921 type = i;
922 break;
923 }
924 }
925
926 if (type < 0) {
927 return type;
928 }
929
930 std::vector<android_color_mode_t> modes;
931 {
932 ConditionalLock _l(mStateLock,
933 std::this_thread::get_id() != mMainThreadId);
934 modes = getHwComposer().getColorModes(type);
935 }
936 outColorModes->clear();
937 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
938
939 return NO_ERROR;
940 }
941
getActiveColorMode(const sp<IBinder> & display)942 android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
943 sp<const DisplayDevice> device(getDisplayDevice(display));
944 if (device != nullptr) {
945 return device->getActiveColorMode();
946 }
947 return static_cast<android_color_mode_t>(BAD_VALUE);
948 }
949
setActiveColorModeInternal(const sp<DisplayDevice> & hw,android_color_mode_t mode)950 void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
951 android_color_mode_t mode) {
952 int32_t type = hw->getDisplayType();
953 android_color_mode_t currentMode = hw->getActiveColorMode();
954
955 if (mode == currentMode) {
956 return;
957 }
958
959 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
960 ALOGW("Trying to set config for virtual display");
961 return;
962 }
963
964 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
965 hw->getDisplayType());
966
967 hw->setActiveColorMode(mode);
968 getHwComposer().setActiveColorMode(type, mode);
969 }
970
971
setActiveColorMode(const sp<IBinder> & display,android_color_mode_t colorMode)972 status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
973 android_color_mode_t colorMode) {
974 class MessageSetActiveColorMode: public MessageBase {
975 SurfaceFlinger& mFlinger;
976 sp<IBinder> mDisplay;
977 android_color_mode_t mMode;
978 public:
979 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
980 android_color_mode_t mode) :
981 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
982 virtual bool handler() {
983 Vector<android_color_mode_t> modes;
984 mFlinger.getDisplayColorModes(mDisplay, &modes);
985 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
986 if (mMode < 0 || !exists) {
987 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
988 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
989 return true;
990 }
991 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
992 if (hw == nullptr) {
993 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
994 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
995 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
996 ALOGW("Attempt to set active color mode %s %d for virtual display",
997 decodeColorMode(mMode).c_str(), mMode);
998 } else {
999 mFlinger.setActiveColorModeInternal(hw, mMode);
1000 }
1001 return true;
1002 }
1003 };
1004 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1005 postMessageSync(msg);
1006 return NO_ERROR;
1007 }
1008
clearAnimationFrameStats()1009 status_t SurfaceFlinger::clearAnimationFrameStats() {
1010 Mutex::Autolock _l(mStateLock);
1011 mAnimFrameTracker.clearStats();
1012 return NO_ERROR;
1013 }
1014
getAnimationFrameStats(FrameStats * outStats) const1015 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1016 Mutex::Autolock _l(mStateLock);
1017 mAnimFrameTracker.getStats(outStats);
1018 return NO_ERROR;
1019 }
1020
getHdrCapabilities(const sp<IBinder> & display,HdrCapabilities * outCapabilities) const1021 status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1022 HdrCapabilities* outCapabilities) const {
1023 Mutex::Autolock _l(mStateLock);
1024
1025 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
1026 if (displayDevice == nullptr) {
1027 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1028 return BAD_VALUE;
1029 }
1030
1031 std::unique_ptr<HdrCapabilities> capabilities =
1032 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1033 if (capabilities) {
1034 std::swap(*outCapabilities, *capabilities);
1035 } else {
1036 return BAD_VALUE;
1037 }
1038
1039 return NO_ERROR;
1040 }
1041
enableVSyncInjectionsInternal(bool enable)1042 void SurfaceFlinger::enableVSyncInjectionsInternal(bool enable) {
1043 Mutex::Autolock _l(mStateLock);
1044
1045 if (mInjectVSyncs == enable) {
1046 return;
1047 }
1048
1049 if (enable) {
1050 ALOGV("VSync Injections enabled");
1051 if (mVSyncInjector.get() == nullptr) {
1052 mVSyncInjector = new InjectVSyncSource();
1053 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1054 }
1055 mEventQueue.setEventThread(mInjectorEventThread);
1056 } else {
1057 ALOGV("VSync Injections disabled");
1058 mEventQueue.setEventThread(mSFEventThread);
1059 }
1060
1061 mInjectVSyncs = enable;
1062 }
1063
enableVSyncInjections(bool enable)1064 status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1065 class MessageEnableVSyncInjections : public MessageBase {
1066 SurfaceFlinger* mFlinger;
1067 bool mEnable;
1068 public:
1069 MessageEnableVSyncInjections(SurfaceFlinger* flinger, bool enable)
1070 : mFlinger(flinger), mEnable(enable) { }
1071 virtual bool handler() {
1072 mFlinger->enableVSyncInjectionsInternal(mEnable);
1073 return true;
1074 }
1075 };
1076 sp<MessageBase> msg = new MessageEnableVSyncInjections(this, enable);
1077 postMessageSync(msg);
1078 return NO_ERROR;
1079 }
1080
injectVSync(nsecs_t when)1081 status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1082 Mutex::Autolock _l(mStateLock);
1083
1084 if (!mInjectVSyncs) {
1085 ALOGE("VSync Injections not enabled");
1086 return BAD_VALUE;
1087 }
1088 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1089 ALOGV("Injecting VSync inside SurfaceFlinger");
1090 mVSyncInjector->onInjectSyncEvent(when);
1091 }
1092 return NO_ERROR;
1093 }
1094
1095 // ----------------------------------------------------------------------------
1096
createDisplayEventConnection(ISurfaceComposer::VsyncSource vsyncSource)1097 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1098 ISurfaceComposer::VsyncSource vsyncSource) {
1099 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1100 return mSFEventThread->createEventConnection();
1101 } else {
1102 return mEventThread->createEventConnection();
1103 }
1104 }
1105
1106 // ----------------------------------------------------------------------------
1107
waitForEvent()1108 void SurfaceFlinger::waitForEvent() {
1109 mEventQueue.waitMessage();
1110 }
1111
signalTransaction()1112 void SurfaceFlinger::signalTransaction() {
1113 mEventQueue.invalidate();
1114 }
1115
signalLayerUpdate()1116 void SurfaceFlinger::signalLayerUpdate() {
1117 mEventQueue.invalidate();
1118 }
1119
signalRefresh()1120 void SurfaceFlinger::signalRefresh() {
1121 mRefreshPending = true;
1122 mEventQueue.refresh();
1123 }
1124
postMessageAsync(const sp<MessageBase> & msg,nsecs_t reltime,uint32_t)1125 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
1126 nsecs_t reltime, uint32_t /* flags */) {
1127 return mEventQueue.postMessage(msg, reltime);
1128 }
1129
postMessageSync(const sp<MessageBase> & msg,nsecs_t reltime,uint32_t)1130 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
1131 nsecs_t reltime, uint32_t /* flags */) {
1132 status_t res = mEventQueue.postMessage(msg, reltime);
1133 if (res == NO_ERROR) {
1134 msg->wait();
1135 }
1136 return res;
1137 }
1138
run()1139 void SurfaceFlinger::run() {
1140 do {
1141 waitForEvent();
1142 } while (true);
1143 }
1144
enableHardwareVsync()1145 void SurfaceFlinger::enableHardwareVsync() {
1146 Mutex::Autolock _l(mHWVsyncLock);
1147 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
1148 mPrimaryDispSync.beginResync();
1149 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1150 mEventControlThread->setVsyncEnabled(true);
1151 mPrimaryHWVsyncEnabled = true;
1152 }
1153 }
1154
resyncToHardwareVsync(bool makeAvailable)1155 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
1156 Mutex::Autolock _l(mHWVsyncLock);
1157
1158 if (makeAvailable) {
1159 mHWVsyncAvailable = true;
1160 } else if (!mHWVsyncAvailable) {
1161 // Hardware vsync is not currently available, so abort the resync
1162 // attempt for now
1163 return;
1164 }
1165
1166 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1167 const nsecs_t period = activeConfig->getVsyncPeriod();
1168
1169 mPrimaryDispSync.reset();
1170 mPrimaryDispSync.setPeriod(period);
1171
1172 if (!mPrimaryHWVsyncEnabled) {
1173 mPrimaryDispSync.beginResync();
1174 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1175 mEventControlThread->setVsyncEnabled(true);
1176 mPrimaryHWVsyncEnabled = true;
1177 }
1178 }
1179
disableHardwareVsync(bool makeUnavailable)1180 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
1181 Mutex::Autolock _l(mHWVsyncLock);
1182 if (mPrimaryHWVsyncEnabled) {
1183 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1184 mEventControlThread->setVsyncEnabled(false);
1185 mPrimaryDispSync.endResync();
1186 mPrimaryHWVsyncEnabled = false;
1187 }
1188 if (makeUnavailable) {
1189 mHWVsyncAvailable = false;
1190 }
1191 }
1192
resyncWithRateLimit()1193 void SurfaceFlinger::resyncWithRateLimit() {
1194 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1195
1196 // No explicit locking is needed here since EventThread holds a lock while calling this method
1197 static nsecs_t sLastResyncAttempted = 0;
1198 const nsecs_t now = systemTime();
1199 if (now - sLastResyncAttempted > kIgnoreDelay) {
1200 resyncToHardwareVsync(false);
1201 }
1202 sLastResyncAttempted = now;
1203 }
1204
onVsyncReceived(int32_t sequenceId,hwc2_display_t displayId,int64_t timestamp)1205 void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1206 hwc2_display_t displayId, int64_t timestamp) {
1207 Mutex::Autolock lock(mStateLock);
1208 // Ignore any vsyncs from a previous hardware composer.
1209 if (sequenceId != mComposerSequenceId) {
1210 return;
1211 }
1212
1213 int32_t type;
1214 if (!mHwc->onVsync(displayId, timestamp, &type)) {
1215 return;
1216 }
1217
1218 bool needsHwVsync = false;
1219
1220 { // Scope for the lock
1221 Mutex::Autolock _l(mHWVsyncLock);
1222 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
1223 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
1224 }
1225 }
1226
1227 if (needsHwVsync) {
1228 enableHardwareVsync();
1229 } else {
1230 disableHardwareVsync(false);
1231 }
1232 }
1233
getCompositorTiming(CompositorTiming * compositorTiming)1234 void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1235 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1236 *compositorTiming = mCompositorTiming;
1237 }
1238
createDefaultDisplayDevice()1239 void SurfaceFlinger::createDefaultDisplayDevice() {
1240 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
1241 wp<IBinder> token = mBuiltinDisplays[type];
1242
1243 // All non-virtual displays are currently considered secure.
1244 const bool isSecure = true;
1245
1246 sp<IGraphicBufferProducer> producer;
1247 sp<IGraphicBufferConsumer> consumer;
1248 BufferQueue::createBufferQueue(&producer, &consumer);
1249
1250 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1251
1252 bool hasWideColorModes = false;
1253 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1254 for (android_color_mode_t colorMode : modes) {
1255 switch (colorMode) {
1256 case HAL_COLOR_MODE_DISPLAY_P3:
1257 case HAL_COLOR_MODE_ADOBE_RGB:
1258 case HAL_COLOR_MODE_DCI_P3:
1259 hasWideColorModes = true;
1260 break;
1261 default:
1262 break;
1263 }
1264 }
1265 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
1266 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1267 token, fbs, producer, mRenderEngine->getEGLConfig(),
1268 useWideColorMode);
1269 mDisplays.add(token, hw);
1270 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1271 if (useWideColorMode) {
1272 defaultColorMode = HAL_COLOR_MODE_SRGB;
1273 }
1274 setActiveColorModeInternal(hw, defaultColorMode);
1275 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
1276
1277 // Add the primary display token to mDrawingState so we don't try to
1278 // recreate the DisplayDevice for the primary display.
1279 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1280
1281 // make the GLContext current so that we can create textures when creating
1282 // Layers (which may happens before we render something)
1283 hw->makeCurrent(mEGLDisplay, mEGLContext);
1284 }
1285
onHotplugReceived(int32_t sequenceId,hwc2_display_t display,HWC2::Connection connection,bool primaryDisplay)1286 void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1287 hwc2_display_t display, HWC2::Connection connection,
1288 bool primaryDisplay) {
1289 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1290 sequenceId, display,
1291 connection == HWC2::Connection::Connected ?
1292 "connected" : "disconnected",
1293 primaryDisplay ? "primary" : "external");
1294
1295 // Only lock if we're not on the main thread. This function is normally
1296 // called on a hwbinder thread, but for the primary display it's called on
1297 // the main thread with the state lock already held, so don't attempt to
1298 // acquire it here.
1299 ConditionalLock lock(mStateLock,
1300 std::this_thread::get_id() != mMainThreadId);
1301
1302 if (primaryDisplay) {
1303 mHwc->onHotplug(display, connection);
1304 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1305 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1306 }
1307 createDefaultDisplayDevice();
1308 } else {
1309 if (sequenceId != mComposerSequenceId) {
1310 return;
1311 }
1312 if (mHwc->isUsingVrComposer()) {
1313 ALOGE("External displays are not supported by the vr hardware composer.");
1314 return;
1315 }
1316 mHwc->onHotplug(display, connection);
1317 auto type = DisplayDevice::DISPLAY_EXTERNAL;
1318 if (connection == HWC2::Connection::Connected) {
1319 createBuiltinDisplayLocked(type);
1320 } else {
1321 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1322 mBuiltinDisplays[type].clear();
1323 }
1324 setTransactionFlags(eDisplayTransactionNeeded);
1325
1326 // Defer EventThread notification until SF has updated mDisplays.
1327 }
1328 }
1329
onRefreshReceived(int sequenceId,hwc2_display_t)1330 void SurfaceFlinger::onRefreshReceived(int sequenceId,
1331 hwc2_display_t /*display*/) {
1332 Mutex::Autolock lock(mStateLock);
1333 if (sequenceId != mComposerSequenceId) {
1334 return;
1335 }
1336 repaintEverythingLocked();
1337 }
1338
setVsyncEnabled(int disp,int enabled)1339 void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
1340 ATRACE_CALL();
1341 Mutex::Autolock lock(mStateLock);
1342 getHwComposer().setVsyncEnabled(disp,
1343 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1344 }
1345
1346 // Note: it is assumed the caller holds |mStateLock| when this is called
resetDisplayState()1347 void SurfaceFlinger::resetDisplayState() {
1348 disableHardwareVsync(true);
1349 // Clear the drawing state so that the logic inside of
1350 // handleTransactionLocked will fire. It will determine the delta between
1351 // mCurrentState and mDrawingState and re-apply all changes when we make the
1352 // transition.
1353 mDrawingState.displays.clear();
1354 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1355 mDisplays.clear();
1356 }
1357
updateVrFlinger()1358 void SurfaceFlinger::updateVrFlinger() {
1359 if (!mVrFlinger)
1360 return;
1361 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1362 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
1363 return;
1364 }
1365
1366 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1367 ALOGE("Vr flinger is only supported for remote hardware composer"
1368 " service connections. Ignoring request to transition to vr"
1369 " flinger.");
1370 mVrFlingerRequestsDisplay = false;
1371 return;
1372 }
1373
1374 Mutex::Autolock _l(mStateLock);
1375
1376 int currentDisplayPowerMode = getDisplayDeviceLocked(
1377 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
1378
1379 if (!vrFlingerRequestsDisplay) {
1380 mVrFlinger->SeizeDisplayOwnership();
1381 }
1382
1383 resetDisplayState();
1384 mHwc.reset(); // Delete the current instance before creating the new one
1385 mHwc.reset(new HWComposer(vrFlingerRequestsDisplay));
1386 mHwc->registerCallback(this, ++mComposerSequenceId);
1387
1388 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1389 "Switched to non-remote hardware composer");
1390
1391 if (vrFlingerRequestsDisplay) {
1392 mVrFlinger->GrantDisplayOwnership();
1393 } else {
1394 enableHardwareVsync();
1395 }
1396
1397 mVisibleRegionsDirty = true;
1398 invalidateHwcGeometry();
1399
1400 // Re-enable default display.
1401 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1402 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1403 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
1404
1405 // Reset the timing values to account for the period of the swapped in HWC
1406 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1407 const nsecs_t period = activeConfig->getVsyncPeriod();
1408 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1409
1410 // Use phase of 0 since phase is not known.
1411 // Use latency of 0, which will snap to the ideal latency.
1412 setCompositorTimingSnapped(0, period, 0);
1413
1414 android_atomic_or(1, &mRepaintEverything);
1415 setTransactionFlags(eDisplayTransactionNeeded);
1416 }
1417
onMessageReceived(int32_t what)1418 void SurfaceFlinger::onMessageReceived(int32_t what) {
1419 ATRACE_CALL();
1420 switch (what) {
1421 case MessageQueue::INVALIDATE: {
1422 bool frameMissed = !mHadClientComposition &&
1423 mPreviousPresentFence != Fence::NO_FENCE &&
1424 (mPreviousPresentFence->getSignalTime() ==
1425 Fence::SIGNAL_TIME_PENDING);
1426 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1427 if (mPropagateBackpressure && frameMissed) {
1428 signalLayerUpdate();
1429 break;
1430 }
1431
1432 // Now that we're going to make it to the handleMessageTransaction()
1433 // call below it's safe to call updateVrFlinger(), which will
1434 // potentially trigger a display handoff.
1435 updateVrFlinger();
1436
1437 bool refreshNeeded = handleMessageTransaction();
1438 refreshNeeded |= handleMessageInvalidate();
1439 refreshNeeded |= mRepaintEverything;
1440 if (refreshNeeded) {
1441 // Signal a refresh if a transaction modified the window state,
1442 // a new buffer was latched, or if HWC has requested a full
1443 // repaint
1444 signalRefresh();
1445 }
1446 break;
1447 }
1448 case MessageQueue::REFRESH: {
1449 handleMessageRefresh();
1450 break;
1451 }
1452 }
1453 }
1454
handleMessageTransaction()1455 bool SurfaceFlinger::handleMessageTransaction() {
1456 uint32_t transactionFlags = peekTransactionFlags();
1457 if (transactionFlags) {
1458 handleTransaction(transactionFlags);
1459 return true;
1460 }
1461 return false;
1462 }
1463
handleMessageInvalidate()1464 bool SurfaceFlinger::handleMessageInvalidate() {
1465 ATRACE_CALL();
1466 return handlePageFlip();
1467 }
1468
handleMessageRefresh()1469 void SurfaceFlinger::handleMessageRefresh() {
1470 ATRACE_CALL();
1471
1472 mRefreshPending = false;
1473
1474 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1475
1476 preComposition(refreshStartTime);
1477 rebuildLayerStacks();
1478 setUpHWComposer();
1479 doDebugFlashRegions();
1480 doComposition();
1481 postComposition(refreshStartTime);
1482
1483 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1484
1485 mHadClientComposition = false;
1486 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1487 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1488 mHadClientComposition = mHadClientComposition ||
1489 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1490 }
1491
1492 mLayersWithQueuedFrames.clear();
1493 }
1494
doDebugFlashRegions()1495 void SurfaceFlinger::doDebugFlashRegions()
1496 {
1497 // is debugging enabled
1498 if (CC_LIKELY(!mDebugRegion))
1499 return;
1500
1501 const bool repaintEverything = mRepaintEverything;
1502 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1503 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1504 if (hw->isDisplayOn()) {
1505 // transform the dirty region into this screen's coordinate space
1506 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1507 if (!dirtyRegion.isEmpty()) {
1508 // redraw the whole screen
1509 doComposeSurfaces(hw, Region(hw->bounds()));
1510
1511 // and draw the dirty region
1512 const int32_t height = hw->getHeight();
1513 RenderEngine& engine(getRenderEngine());
1514 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1515
1516 hw->swapBuffers(getHwComposer());
1517 }
1518 }
1519 }
1520
1521 postFramebuffer();
1522
1523 if (mDebugRegion > 1) {
1524 usleep(mDebugRegion * 1000);
1525 }
1526
1527 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1528 auto& displayDevice = mDisplays[displayId];
1529 if (!displayDevice->isDisplayOn()) {
1530 continue;
1531 }
1532
1533 status_t result = displayDevice->prepareFrame(*mHwc);
1534 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1535 " %d (%s)", displayId, result, strerror(-result));
1536 }
1537 }
1538
preComposition(nsecs_t refreshStartTime)1539 void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
1540 {
1541 ATRACE_CALL();
1542 ALOGV("preComposition");
1543
1544 bool needExtraInvalidate = false;
1545 mDrawingState.traverseInZOrder([&](Layer* layer) {
1546 if (layer->onPreComposition(refreshStartTime)) {
1547 needExtraInvalidate = true;
1548 }
1549 });
1550
1551 if (needExtraInvalidate) {
1552 signalLayerUpdate();
1553 }
1554 }
1555
updateCompositorTiming(nsecs_t vsyncPhase,nsecs_t vsyncInterval,nsecs_t compositeTime,std::shared_ptr<FenceTime> & presentFenceTime)1556 void SurfaceFlinger::updateCompositorTiming(
1557 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1558 std::shared_ptr<FenceTime>& presentFenceTime) {
1559 // Update queue of past composite+present times and determine the
1560 // most recently known composite to present latency.
1561 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1562 nsecs_t compositeToPresentLatency = -1;
1563 while (!mCompositePresentTimes.empty()) {
1564 CompositePresentTime& cpt = mCompositePresentTimes.front();
1565 // Cached values should have been updated before calling this method,
1566 // which helps avoid duplicate syscalls.
1567 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1568 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1569 break;
1570 }
1571 compositeToPresentLatency = displayTime - cpt.composite;
1572 mCompositePresentTimes.pop();
1573 }
1574
1575 // Don't let mCompositePresentTimes grow unbounded, just in case.
1576 while (mCompositePresentTimes.size() > 16) {
1577 mCompositePresentTimes.pop();
1578 }
1579
1580 setCompositorTimingSnapped(
1581 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1582 }
1583
setCompositorTimingSnapped(nsecs_t vsyncPhase,nsecs_t vsyncInterval,nsecs_t compositeToPresentLatency)1584 void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1585 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
1586 // Integer division and modulo round toward 0 not -inf, so we need to
1587 // treat negative and positive offsets differently.
1588 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
1589 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1590 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1591
1592 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1593 if (idealLatency <= 0) {
1594 idealLatency = vsyncInterval;
1595 }
1596
1597 // Snap the latency to a value that removes scheduling jitter from the
1598 // composition and present times, which often have >1ms of jitter.
1599 // Reducing jitter is important if an app attempts to extrapolate
1600 // something (such as user input) to an accurate diasplay time.
1601 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1602 // with (presentLatency % interval).
1603 nsecs_t bias = vsyncInterval / 2;
1604 int64_t extraVsyncs =
1605 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1606 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1607 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
1608
1609 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1610 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1611 mCompositorTiming.interval = vsyncInterval;
1612 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1613 }
1614
postComposition(nsecs_t refreshStartTime)1615 void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
1616 {
1617 ATRACE_CALL();
1618 ALOGV("postComposition");
1619
1620 // Release any buffers which were replaced this frame
1621 nsecs_t dequeueReadyTime = systemTime();
1622 for (auto& layer : mLayersWithQueuedFrames) {
1623 layer->releasePendingBuffer(dequeueReadyTime);
1624 }
1625
1626 // |mStateLock| not needed as we are on the main thread
1627 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
1628
1629 mGlCompositionDoneTimeline.updateSignalTimes();
1630 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1631 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1632 glCompositionDoneFenceTime =
1633 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1634 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1635 } else {
1636 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1637 }
1638
1639 mDisplayTimeline.updateSignalTimes();
1640 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1641 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1642 mDisplayTimeline.push(presentFenceTime);
1643
1644 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1645 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1646
1647 // We use the refreshStartTime which might be sampled a little later than
1648 // when we started doing work for this frame, but that should be okay
1649 // since updateCompositorTiming has snapping logic.
1650 updateCompositorTiming(
1651 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
1652 CompositorTiming compositorTiming;
1653 {
1654 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1655 compositorTiming = mCompositorTiming;
1656 }
1657
1658 mDrawingState.traverseInZOrder([&](Layer* layer) {
1659 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1660 presentFenceTime, compositorTiming);
1661 if (frameLatched) {
1662 recordBufferingStats(layer->getName().string(),
1663 layer->getOccupancyHistory(false));
1664 }
1665 });
1666
1667 if (presentFenceTime->isValid()) {
1668 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
1669 enableHardwareVsync();
1670 } else {
1671 disableHardwareVsync(false);
1672 }
1673 }
1674
1675 if (!hasSyncFramework) {
1676 if (hw->isDisplayOn()) {
1677 enableHardwareVsync();
1678 }
1679 }
1680
1681 if (mAnimCompositionPending) {
1682 mAnimCompositionPending = false;
1683
1684 if (presentFenceTime->isValid()) {
1685 mAnimFrameTracker.setActualPresentFence(
1686 std::move(presentFenceTime));
1687 } else {
1688 // The HWC doesn't support present fences, so use the refresh
1689 // timestamp instead.
1690 nsecs_t presentTime =
1691 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1692 mAnimFrameTracker.setActualPresentTime(presentTime);
1693 }
1694 mAnimFrameTracker.advanceFrame();
1695 }
1696
1697 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1698 return;
1699 }
1700
1701 nsecs_t currentTime = systemTime();
1702 if (mHasPoweredOff) {
1703 mHasPoweredOff = false;
1704 } else {
1705 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1706 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
1707 if (numPeriods < NUM_BUCKETS - 1) {
1708 mFrameBuckets[numPeriods] += elapsedTime;
1709 } else {
1710 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1711 }
1712 mTotalTime += elapsedTime;
1713 }
1714 mLastSwapTime = currentTime;
1715 }
1716
rebuildLayerStacks()1717 void SurfaceFlinger::rebuildLayerStacks() {
1718 ATRACE_CALL();
1719 ALOGV("rebuildLayerStacks");
1720
1721 // rebuild the visible layer list per screen
1722 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1723 ATRACE_CALL();
1724 mVisibleRegionsDirty = false;
1725 invalidateHwcGeometry();
1726
1727 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1728 Region opaqueRegion;
1729 Region dirtyRegion;
1730 Vector<sp<Layer>> layersSortedByZ;
1731 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1732 const Transform& tr(displayDevice->getTransform());
1733 const Rect bounds(displayDevice->getBounds());
1734 if (displayDevice->isDisplayOn()) {
1735 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
1736
1737 mDrawingState.traverseInZOrder([&](Layer* layer) {
1738 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1739 displayDevice->isPrimary())) {
1740 Region drawRegion(tr.transform(
1741 layer->visibleNonTransparentRegion));
1742 drawRegion.andSelf(bounds);
1743 if (!drawRegion.isEmpty()) {
1744 layersSortedByZ.add(layer);
1745 } else {
1746 // Clear out the HWC layer if this layer was
1747 // previously visible, but no longer is
1748 layer->destroyHwcLayer(
1749 displayDevice->getHwcDisplayId());
1750 }
1751 } else {
1752 // WM changes displayDevice->layerStack upon sleep/awake.
1753 // Here we make sure we delete the HWC layers even if
1754 // WM changed their layer stack.
1755 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
1756 }
1757 });
1758 }
1759 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1760 displayDevice->undefinedRegion.set(bounds);
1761 displayDevice->undefinedRegion.subtractSelf(
1762 tr.transform(opaqueRegion));
1763 displayDevice->dirtyRegion.orSelf(dirtyRegion);
1764 }
1765 }
1766 }
1767
computeSaturationMatrix() const1768 mat4 SurfaceFlinger::computeSaturationMatrix() const {
1769 if (mSaturation == 1.0f) {
1770 return mat4();
1771 }
1772
1773 // Rec.709 luma coefficients
1774 float3 luminance{0.213f, 0.715f, 0.072f};
1775 luminance *= 1.0f - mSaturation;
1776 return mat4(
1777 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1778 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1779 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1780 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1781 );
1782 }
1783
1784 // pickColorMode translates a given dataspace into the best available color mode.
1785 // Currently only support sRGB and Display-P3.
pickColorMode(android_dataspace dataSpace) const1786 android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
1787 if (mForceNativeColorMode) {
1788 return HAL_COLOR_MODE_NATIVE;
1789 }
1790
1791 switch (dataSpace) {
1792 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1793 // system expects.
1794 case HAL_DATASPACE_UNKNOWN:
1795 case HAL_DATASPACE_SRGB:
1796 case HAL_DATASPACE_V0_SRGB:
1797 return HAL_COLOR_MODE_SRGB;
1798 break;
1799
1800 case HAL_DATASPACE_DISPLAY_P3:
1801 return HAL_COLOR_MODE_DISPLAY_P3;
1802 break;
1803
1804 default:
1805 // TODO (courtneygo): Do we want to assert an error here?
1806 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1807 dataSpace);
1808 return HAL_COLOR_MODE_SRGB;
1809 break;
1810 }
1811 }
1812
bestTargetDataSpace(android_dataspace a,android_dataspace b) const1813 android_dataspace SurfaceFlinger::bestTargetDataSpace(
1814 android_dataspace a, android_dataspace b) const {
1815 // Only support sRGB and Display-P3 right now.
1816 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1817 return HAL_DATASPACE_DISPLAY_P3;
1818 }
1819 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1820 return HAL_DATASPACE_DISPLAY_P3;
1821 }
1822 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1823 return HAL_DATASPACE_DISPLAY_P3;
1824 }
1825
1826 return HAL_DATASPACE_V0_SRGB;
1827 }
1828
setUpHWComposer()1829 void SurfaceFlinger::setUpHWComposer() {
1830 ATRACE_CALL();
1831 ALOGV("setUpHWComposer");
1832
1833 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1834 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1835 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1836 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1837
1838 // If nothing has changed (!dirty), don't recompose.
1839 // If something changed, but we don't currently have any visible layers,
1840 // and didn't when we last did a composition, then skip it this time.
1841 // The second rule does two things:
1842 // - When all layers are removed from a display, we'll emit one black
1843 // frame, then nothing more until we get new layers.
1844 // - When a display is created with a private layer stack, we won't
1845 // emit any black frames until a layer is added to the layer stack.
1846 bool mustRecompose = dirty && !(empty && wasEmpty);
1847
1848 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1849 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1850 mustRecompose ? "doing" : "skipping",
1851 dirty ? "+" : "-",
1852 empty ? "+" : "-",
1853 wasEmpty ? "+" : "-");
1854
1855 mDisplays[dpy]->beginFrame(mustRecompose);
1856
1857 if (mustRecompose) {
1858 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1859 }
1860 }
1861
1862 // build the h/w work list
1863 if (CC_UNLIKELY(mGeometryInvalid)) {
1864 mGeometryInvalid = false;
1865 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1866 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1867 const auto hwcId = displayDevice->getHwcDisplayId();
1868 if (hwcId >= 0) {
1869 const Vector<sp<Layer>>& currentLayers(
1870 displayDevice->getVisibleLayersSortedByZ());
1871 for (size_t i = 0; i < currentLayers.size(); i++) {
1872 const auto& layer = currentLayers[i];
1873 if (!layer->hasHwcLayer(hwcId)) {
1874 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
1875 layer->forceClientComposition(hwcId);
1876 continue;
1877 }
1878 }
1879
1880 layer->setGeometry(displayDevice, i);
1881 if (mDebugDisableHWC || mDebugRegion) {
1882 layer->forceClientComposition(hwcId);
1883 }
1884 }
1885 }
1886 }
1887 }
1888
1889
1890 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
1891
1892 // Set the per-frame data
1893 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1894 auto& displayDevice = mDisplays[displayId];
1895 const auto hwcId = displayDevice->getHwcDisplayId();
1896
1897 if (hwcId < 0) {
1898 continue;
1899 }
1900 if (colorMatrix != mPreviousColorMatrix) {
1901 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1902 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1903 "display %zd: %d", displayId, result);
1904 }
1905 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1906 layer->setPerFrameData(displayDevice);
1907 }
1908
1909 if (hasWideColorDisplay) {
1910 android_color_mode newColorMode;
1911 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1912
1913 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1914 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1915 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1916 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1917 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1918 }
1919 newColorMode = pickColorMode(newDataSpace);
1920
1921 setActiveColorModeInternal(displayDevice, newColorMode);
1922 }
1923 }
1924
1925 mPreviousColorMatrix = colorMatrix;
1926
1927 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1928 auto& displayDevice = mDisplays[displayId];
1929 if (!displayDevice->isDisplayOn()) {
1930 continue;
1931 }
1932
1933 status_t result = displayDevice->prepareFrame(*mHwc);
1934 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1935 " %d (%s)", displayId, result, strerror(-result));
1936 }
1937 }
1938
doComposition()1939 void SurfaceFlinger::doComposition() {
1940 ATRACE_CALL();
1941 ALOGV("doComposition");
1942
1943 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1944 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1945 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1946 if (hw->isDisplayOn()) {
1947 // transform the dirty region into this screen's coordinate space
1948 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1949
1950 // repaint the framebuffer (if needed)
1951 doDisplayComposition(hw, dirtyRegion);
1952
1953 hw->dirtyRegion.clear();
1954 hw->flip(hw->swapRegion);
1955 hw->swapRegion.clear();
1956 }
1957 }
1958 postFramebuffer();
1959 }
1960
postFramebuffer()1961 void SurfaceFlinger::postFramebuffer()
1962 {
1963 ATRACE_CALL();
1964 ALOGV("postFramebuffer");
1965
1966 const nsecs_t now = systemTime();
1967 mDebugInSwapBuffers = now;
1968
1969 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1970 auto& displayDevice = mDisplays[displayId];
1971 if (!displayDevice->isDisplayOn()) {
1972 continue;
1973 }
1974 const auto hwcId = displayDevice->getHwcDisplayId();
1975 if (hwcId >= 0) {
1976 mHwc->presentAndGetReleaseFences(hwcId);
1977 }
1978 displayDevice->onSwapBuffersCompleted();
1979 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1980 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1981 sp<Fence> releaseFence = Fence::NO_FENCE;
1982 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1983 releaseFence = displayDevice->getClientTargetAcquireFence();
1984 } else {
1985 auto hwcLayer = layer->getHwcLayer(hwcId);
1986 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
1987 }
1988 layer->onLayerDisplayed(releaseFence);
1989 }
1990 if (hwcId >= 0) {
1991 mHwc->clearReleaseFences(hwcId);
1992 }
1993 }
1994
1995 mLastSwapBufferTime = systemTime() - now;
1996 mDebugInSwapBuffers = 0;
1997
1998 // |mStateLock| not needed as we are on the main thread
1999 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2000 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2001 logFrameStats();
2002 }
2003 }
2004
handleTransaction(uint32_t transactionFlags)2005 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
2006 {
2007 ATRACE_CALL();
2008
2009 // here we keep a copy of the drawing state (that is the state that's
2010 // going to be overwritten by handleTransactionLocked()) outside of
2011 // mStateLock so that the side-effects of the State assignment
2012 // don't happen with mStateLock held (which can cause deadlocks).
2013 State drawingState(mDrawingState);
2014
2015 Mutex::Autolock _l(mStateLock);
2016 const nsecs_t now = systemTime();
2017 mDebugInTransaction = now;
2018
2019 // Here we're guaranteed that some transaction flags are set
2020 // so we can call handleTransactionLocked() unconditionally.
2021 // We call getTransactionFlags(), which will also clear the flags,
2022 // with mStateLock held to guarantee that mCurrentState won't change
2023 // until the transaction is committed.
2024
2025 transactionFlags = getTransactionFlags(eTransactionMask);
2026 handleTransactionLocked(transactionFlags);
2027
2028 mLastTransactionTime = systemTime() - now;
2029 mDebugInTransaction = 0;
2030 invalidateHwcGeometry();
2031 // here the transaction has been committed
2032 }
2033
handleTransactionLocked(uint32_t transactionFlags)2034 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
2035 {
2036 // Notify all layers of available frames
2037 mCurrentState.traverseInZOrder([](Layer* layer) {
2038 layer->notifyAvailableFrames();
2039 });
2040
2041 /*
2042 * Traversal of the children
2043 * (perform the transaction for each of them if needed)
2044 */
2045
2046 if (transactionFlags & eTraversalNeeded) {
2047 mCurrentState.traverseInZOrder([&](Layer* layer) {
2048 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2049 if (!trFlags) return;
2050
2051 const uint32_t flags = layer->doTransaction(0);
2052 if (flags & Layer::eVisibleRegion)
2053 mVisibleRegionsDirty = true;
2054 });
2055 }
2056
2057 /*
2058 * Perform display own transactions if needed
2059 */
2060
2061 if (transactionFlags & eDisplayTransactionNeeded) {
2062 // here we take advantage of Vector's copy-on-write semantics to
2063 // improve performance by skipping the transaction entirely when
2064 // know that the lists are identical
2065 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2066 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2067 if (!curr.isIdenticalTo(draw)) {
2068 mVisibleRegionsDirty = true;
2069 const size_t cc = curr.size();
2070 size_t dc = draw.size();
2071
2072 // find the displays that were removed
2073 // (ie: in drawing state but not in current state)
2074 // also handle displays that changed
2075 // (ie: displays that are in both lists)
2076 for (size_t i=0 ; i<dc ; i++) {
2077 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2078 if (j < 0) {
2079 // in drawing state but not in current state
2080 if (!draw[i].isMainDisplay()) {
2081 // Call makeCurrent() on the primary display so we can
2082 // be sure that nothing associated with this display
2083 // is current.
2084 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2085 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
2086 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2087 if (hw != NULL)
2088 hw->disconnect(getHwComposer());
2089 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2090 mEventThread->onHotplugReceived(draw[i].type, false);
2091 mDisplays.removeItem(draw.keyAt(i));
2092 } else {
2093 ALOGW("trying to remove the main display");
2094 }
2095 } else {
2096 // this display is in both lists. see if something changed.
2097 const DisplayDeviceState& state(curr[j]);
2098 const wp<IBinder>& display(curr.keyAt(j));
2099 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2100 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2101 if (state_binder != draw_binder) {
2102 // changing the surface is like destroying and
2103 // recreating the DisplayDevice, so we just remove it
2104 // from the drawing state, so that it get re-added
2105 // below.
2106 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2107 if (hw != NULL)
2108 hw->disconnect(getHwComposer());
2109 mDisplays.removeItem(display);
2110 mDrawingState.displays.removeItemsAt(i);
2111 dc--; i--;
2112 // at this point we must loop to the next item
2113 continue;
2114 }
2115
2116 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2117 if (disp != NULL) {
2118 if (state.layerStack != draw[i].layerStack) {
2119 disp->setLayerStack(state.layerStack);
2120 }
2121 if ((state.orientation != draw[i].orientation)
2122 || (state.viewport != draw[i].viewport)
2123 || (state.frame != draw[i].frame))
2124 {
2125 disp->setProjection(state.orientation,
2126 state.viewport, state.frame);
2127 }
2128 if (state.width != draw[i].width || state.height != draw[i].height) {
2129 disp->setDisplaySize(state.width, state.height);
2130 }
2131 }
2132 }
2133 }
2134
2135 // find displays that were added
2136 // (ie: in current state but not in drawing state)
2137 for (size_t i=0 ; i<cc ; i++) {
2138 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2139 const DisplayDeviceState& state(curr[i]);
2140
2141 sp<DisplaySurface> dispSurface;
2142 sp<IGraphicBufferProducer> producer;
2143 sp<IGraphicBufferProducer> bqProducer;
2144 sp<IGraphicBufferConsumer> bqConsumer;
2145 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
2146
2147 int32_t hwcId = -1;
2148 if (state.isVirtualDisplay()) {
2149 // Virtual displays without a surface are dormant:
2150 // they have external state (layer stack, projection,
2151 // etc.) but no internal state (i.e. a DisplayDevice).
2152 if (state.surface != NULL) {
2153
2154 // Allow VR composer to use virtual displays.
2155 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
2156 int width = 0;
2157 int status = state.surface->query(
2158 NATIVE_WINDOW_WIDTH, &width);
2159 ALOGE_IF(status != NO_ERROR,
2160 "Unable to query width (%d)", status);
2161 int height = 0;
2162 status = state.surface->query(
2163 NATIVE_WINDOW_HEIGHT, &height);
2164 ALOGE_IF(status != NO_ERROR,
2165 "Unable to query height (%d)", status);
2166 int intFormat = 0;
2167 status = state.surface->query(
2168 NATIVE_WINDOW_FORMAT, &intFormat);
2169 ALOGE_IF(status != NO_ERROR,
2170 "Unable to query format (%d)", status);
2171 auto format = static_cast<android_pixel_format_t>(
2172 intFormat);
2173
2174 mHwc->allocateVirtualDisplay(width, height, &format,
2175 &hwcId);
2176 }
2177
2178 // TODO: Plumb requested format back up to consumer
2179
2180 sp<VirtualDisplaySurface> vds =
2181 new VirtualDisplaySurface(*mHwc,
2182 hwcId, state.surface, bqProducer,
2183 bqConsumer, state.displayName);
2184
2185 dispSurface = vds;
2186 producer = vds;
2187 }
2188 } else {
2189 ALOGE_IF(state.surface!=NULL,
2190 "adding a supported display, but rendering "
2191 "surface is provided (%p), ignoring it",
2192 state.surface.get());
2193
2194 hwcId = state.type;
2195 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2196 producer = bqProducer;
2197 }
2198
2199 const wp<IBinder>& display(curr.keyAt(i));
2200 if (dispSurface != NULL) {
2201 sp<DisplayDevice> hw =
2202 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2203 dispSurface, producer,
2204 mRenderEngine->getEGLConfig(),
2205 hasWideColorDisplay);
2206 hw->setLayerStack(state.layerStack);
2207 hw->setProjection(state.orientation,
2208 state.viewport, state.frame);
2209 hw->setDisplayName(state.displayName);
2210 mDisplays.add(display, hw);
2211 if (!state.isVirtualDisplay()) {
2212 mEventThread->onHotplugReceived(state.type, true);
2213 }
2214 }
2215 }
2216 }
2217 }
2218 }
2219
2220 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2221 // The transform hint might have changed for some layers
2222 // (either because a display has changed, or because a layer
2223 // as changed).
2224 //
2225 // Walk through all the layers in currentLayers,
2226 // and update their transform hint.
2227 //
2228 // If a layer is visible only on a single display, then that
2229 // display is used to calculate the hint, otherwise we use the
2230 // default display.
2231 //
2232 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2233 // the hint is set before we acquire a buffer from the surface texture.
2234 //
2235 // NOTE: layer transactions have taken place already, so we use their
2236 // drawing state. However, SurfaceFlinger's own transaction has not
2237 // happened yet, so we must use the current state layer list
2238 // (soon to become the drawing state list).
2239 //
2240 sp<const DisplayDevice> disp;
2241 uint32_t currentlayerStack = 0;
2242 bool first = true;
2243 mCurrentState.traverseInZOrder([&](Layer* layer) {
2244 // NOTE: we rely on the fact that layers are sorted by
2245 // layerStack first (so we don't have to traverse the list
2246 // of displays for every layer).
2247 uint32_t layerStack = layer->getLayerStack();
2248 if (first || currentlayerStack != layerStack) {
2249 currentlayerStack = layerStack;
2250 // figure out if this layerstack is mirrored
2251 // (more than one display) if so, pick the default display,
2252 // if not, pick the only display it's on.
2253 disp.clear();
2254 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2255 sp<const DisplayDevice> hw(mDisplays[dpy]);
2256 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
2257 if (disp == NULL) {
2258 disp = hw;
2259 } else {
2260 disp = NULL;
2261 break;
2262 }
2263 }
2264 }
2265 }
2266 if (disp == NULL) {
2267 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2268 // redraw after transform hint changes. See bug 8508397.
2269
2270 // could be null when this layer is using a layerStack
2271 // that is not visible on any display. Also can occur at
2272 // screen off/on times.
2273 disp = getDefaultDisplayDeviceLocked();
2274 }
2275 layer->updateTransformHint(disp);
2276
2277 first = false;
2278 });
2279 }
2280
2281
2282 /*
2283 * Perform our own transaction if needed
2284 */
2285
2286 if (mLayersAdded) {
2287 mLayersAdded = false;
2288 // Layers have been added.
2289 mVisibleRegionsDirty = true;
2290 }
2291
2292 // some layers might have been removed, so
2293 // we need to update the regions they're exposing.
2294 if (mLayersRemoved) {
2295 mLayersRemoved = false;
2296 mVisibleRegionsDirty = true;
2297 mDrawingState.traverseInZOrder([&](Layer* layer) {
2298 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
2299 // this layer is not visible anymore
2300 // TODO: we could traverse the tree from front to back and
2301 // compute the actual visible region
2302 // TODO: we could cache the transformed region
2303 Region visibleReg;
2304 visibleReg.set(layer->computeScreenBounds());
2305 invalidateLayerStack(layer, visibleReg);
2306 }
2307 });
2308 }
2309
2310 commitTransaction();
2311
2312 updateCursorAsync();
2313 }
2314
updateCursorAsync()2315 void SurfaceFlinger::updateCursorAsync()
2316 {
2317 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2318 auto& displayDevice = mDisplays[displayId];
2319 if (displayDevice->getHwcDisplayId() < 0) {
2320 continue;
2321 }
2322
2323 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2324 layer->updateCursorPosition(displayDevice);
2325 }
2326 }
2327 }
2328
commitTransaction()2329 void SurfaceFlinger::commitTransaction()
2330 {
2331 if (!mLayersPendingRemoval.isEmpty()) {
2332 // Notify removed layers now that they can't be drawn from
2333 for (const auto& l : mLayersPendingRemoval) {
2334 recordBufferingStats(l->getName().string(),
2335 l->getOccupancyHistory(true));
2336 l->onRemoved();
2337 }
2338 mLayersPendingRemoval.clear();
2339 }
2340
2341 // If this transaction is part of a window animation then the next frame
2342 // we composite should be considered an animation as well.
2343 mAnimCompositionPending = mAnimTransactionPending;
2344
2345 mDrawingState = mCurrentState;
2346 mDrawingState.traverseInZOrder([](Layer* layer) {
2347 layer->commitChildList();
2348 });
2349 mTransactionPending = false;
2350 mAnimTransactionPending = false;
2351 mTransactionCV.broadcast();
2352 }
2353
computeVisibleRegions(const sp<const DisplayDevice> & displayDevice,Region & outDirtyRegion,Region & outOpaqueRegion)2354 void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
2355 Region& outDirtyRegion, Region& outOpaqueRegion)
2356 {
2357 ATRACE_CALL();
2358 ALOGV("computeVisibleRegions");
2359
2360 Region aboveOpaqueLayers;
2361 Region aboveCoveredLayers;
2362 Region dirty;
2363
2364 outDirtyRegion.clear();
2365
2366 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2367 // start with the whole surface at its current location
2368 const Layer::State& s(layer->getDrawingState());
2369
2370 // only consider the layers on the given layer stack
2371 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
2372 return;
2373
2374 /*
2375 * opaqueRegion: area of a surface that is fully opaque.
2376 */
2377 Region opaqueRegion;
2378
2379 /*
2380 * visibleRegion: area of a surface that is visible on screen
2381 * and not fully transparent. This is essentially the layer's
2382 * footprint minus the opaque regions above it.
2383 * Areas covered by a translucent surface are considered visible.
2384 */
2385 Region visibleRegion;
2386
2387 /*
2388 * coveredRegion: area of a surface that is covered by all
2389 * visible regions above it (which includes the translucent areas).
2390 */
2391 Region coveredRegion;
2392
2393 /*
2394 * transparentRegion: area of a surface that is hinted to be completely
2395 * transparent. This is only used to tell when the layer has no visible
2396 * non-transparent regions and can be removed from the layer list. It
2397 * does not affect the visibleRegion of this layer or any layers
2398 * beneath it. The hint may not be correct if apps don't respect the
2399 * SurfaceView restrictions (which, sadly, some don't).
2400 */
2401 Region transparentRegion;
2402
2403
2404 // handle hidden surfaces by setting the visible region to empty
2405 if (CC_LIKELY(layer->isVisible())) {
2406 const bool translucent = !layer->isOpaque(s);
2407 Rect bounds(layer->computeScreenBounds());
2408 visibleRegion.set(bounds);
2409 Transform tr = layer->getTransform();
2410 if (!visibleRegion.isEmpty()) {
2411 // Remove the transparent area from the visible region
2412 if (translucent) {
2413 if (tr.preserveRects()) {
2414 // transform the transparent region
2415 transparentRegion = tr.transform(s.activeTransparentRegion);
2416 } else {
2417 // transformation too complex, can't do the
2418 // transparent region optimization.
2419 transparentRegion.clear();
2420 }
2421 }
2422
2423 // compute the opaque region
2424 const int32_t layerOrientation = tr.getOrientation();
2425 if (s.alpha == 1.0f && !translucent &&
2426 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2427 // the opaque region is the layer's footprint
2428 opaqueRegion = visibleRegion;
2429 }
2430 }
2431 }
2432
2433 // Clip the covered region to the visible region
2434 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2435
2436 // Update aboveCoveredLayers for next (lower) layer
2437 aboveCoveredLayers.orSelf(visibleRegion);
2438
2439 // subtract the opaque region covered by the layers above us
2440 visibleRegion.subtractSelf(aboveOpaqueLayers);
2441
2442 // compute this layer's dirty region
2443 if (layer->contentDirty) {
2444 // we need to invalidate the whole region
2445 dirty = visibleRegion;
2446 // as well, as the old visible region
2447 dirty.orSelf(layer->visibleRegion);
2448 layer->contentDirty = false;
2449 } else {
2450 /* compute the exposed region:
2451 * the exposed region consists of two components:
2452 * 1) what's VISIBLE now and was COVERED before
2453 * 2) what's EXPOSED now less what was EXPOSED before
2454 *
2455 * note that (1) is conservative, we start with the whole
2456 * visible region but only keep what used to be covered by
2457 * something -- which mean it may have been exposed.
2458 *
2459 * (2) handles areas that were not covered by anything but got
2460 * exposed because of a resize.
2461 */
2462 const Region newExposed = visibleRegion - coveredRegion;
2463 const Region oldVisibleRegion = layer->visibleRegion;
2464 const Region oldCoveredRegion = layer->coveredRegion;
2465 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2466 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
2467 }
2468 dirty.subtractSelf(aboveOpaqueLayers);
2469
2470 // accumulate to the screen dirty region
2471 outDirtyRegion.orSelf(dirty);
2472
2473 // Update aboveOpaqueLayers for next (lower) layer
2474 aboveOpaqueLayers.orSelf(opaqueRegion);
2475
2476 // Store the visible region in screen space
2477 layer->setVisibleRegion(visibleRegion);
2478 layer->setCoveredRegion(coveredRegion);
2479 layer->setVisibleNonTransparentRegion(
2480 visibleRegion.subtract(transparentRegion));
2481 });
2482
2483 outOpaqueRegion = aboveOpaqueLayers;
2484 }
2485
invalidateLayerStack(const sp<const Layer> & layer,const Region & dirty)2486 void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
2487 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2488 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2489 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
2490 hw->dirtyRegion.orSelf(dirty);
2491 }
2492 }
2493 }
2494
handlePageFlip()2495 bool SurfaceFlinger::handlePageFlip()
2496 {
2497 ALOGV("handlePageFlip");
2498
2499 nsecs_t latchTime = systemTime();
2500
2501 bool visibleRegions = false;
2502 bool frameQueued = false;
2503 bool newDataLatched = false;
2504
2505 // Store the set of layers that need updates. This set must not change as
2506 // buffers are being latched, as this could result in a deadlock.
2507 // Example: Two producers share the same command stream and:
2508 // 1.) Layer 0 is latched
2509 // 2.) Layer 0 gets a new frame
2510 // 2.) Layer 1 gets a new frame
2511 // 3.) Layer 1 is latched.
2512 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2513 // second frame. But layer 0's second frame could be waiting on display.
2514 mDrawingState.traverseInZOrder([&](Layer* layer) {
2515 if (layer->hasQueuedFrame()) {
2516 frameQueued = true;
2517 if (layer->shouldPresentNow(mPrimaryDispSync)) {
2518 mLayersWithQueuedFrames.push_back(layer);
2519 } else {
2520 layer->useEmptyDamage();
2521 }
2522 } else {
2523 layer->useEmptyDamage();
2524 }
2525 });
2526
2527 for (auto& layer : mLayersWithQueuedFrames) {
2528 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
2529 layer->useSurfaceDamage();
2530 invalidateLayerStack(layer, dirty);
2531 if (layer->isBufferLatched()) {
2532 newDataLatched = true;
2533 }
2534 }
2535
2536 mVisibleRegionsDirty |= visibleRegions;
2537
2538 // If we will need to wake up at some time in the future to deal with a
2539 // queued frame that shouldn't be displayed during this vsync period, wake
2540 // up during the next vsync period to check again.
2541 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
2542 signalLayerUpdate();
2543 }
2544
2545 // Only continue with the refresh if there is actually new work to do
2546 return !mLayersWithQueuedFrames.empty() && newDataLatched;
2547 }
2548
invalidateHwcGeometry()2549 void SurfaceFlinger::invalidateHwcGeometry()
2550 {
2551 mGeometryInvalid = true;
2552 }
2553
2554
doDisplayComposition(const sp<const DisplayDevice> & displayDevice,const Region & inDirtyRegion)2555 void SurfaceFlinger::doDisplayComposition(
2556 const sp<const DisplayDevice>& displayDevice,
2557 const Region& inDirtyRegion)
2558 {
2559 // We only need to actually compose the display if:
2560 // 1) It is being handled by hardware composer, which may need this to
2561 // keep its virtual display state machine in sync, or
2562 // 2) There is work to be done (the dirty region isn't empty)
2563 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
2564 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
2565 ALOGV("Skipping display composition");
2566 return;
2567 }
2568
2569 ALOGV("doDisplayComposition");
2570
2571 Region dirtyRegion(inDirtyRegion);
2572
2573 // compute the invalid region
2574 displayDevice->swapRegion.orSelf(dirtyRegion);
2575
2576 uint32_t flags = displayDevice->getFlags();
2577 if (flags & DisplayDevice::SWAP_RECTANGLE) {
2578 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2579 // takes a rectangle, we must make sure to update that whole
2580 // rectangle in that case
2581 dirtyRegion.set(displayDevice->swapRegion.bounds());
2582 } else {
2583 if (flags & DisplayDevice::PARTIAL_UPDATES) {
2584 // We need to redraw the rectangle that will be updated
2585 // (pushed to the framebuffer).
2586 // This is needed because PARTIAL_UPDATES only takes one
2587 // rectangle instead of a region (see DisplayDevice::flip())
2588 dirtyRegion.set(displayDevice->swapRegion.bounds());
2589 } else {
2590 // we need to redraw everything (the whole screen)
2591 dirtyRegion.set(displayDevice->bounds());
2592 displayDevice->swapRegion = dirtyRegion;
2593 }
2594 }
2595
2596 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
2597
2598 // update the swap region and clear the dirty region
2599 displayDevice->swapRegion.orSelf(dirtyRegion);
2600
2601 // swap buffers (presentation)
2602 displayDevice->swapBuffers(getHwComposer());
2603 }
2604
doComposeSurfaces(const sp<const DisplayDevice> & displayDevice,const Region & dirty)2605 bool SurfaceFlinger::doComposeSurfaces(
2606 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
2607 {
2608 ALOGV("doComposeSurfaces");
2609
2610 const auto hwcId = displayDevice->getHwcDisplayId();
2611
2612 mat4 oldColorMatrix;
2613 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2614 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2615 if (applyColorMatrix) {
2616 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2617 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2618 }
2619
2620 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2621 if (hasClientComposition) {
2622 ALOGV("hasClientComposition");
2623
2624 #ifdef USE_HWC2
2625 mRenderEngine->setWideColor(
2626 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2627 mRenderEngine->setColorMode(mForceNativeColorMode ?
2628 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
2629 #endif
2630 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
2631 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
2632 displayDevice->getDisplayName().string());
2633 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2634
2635 // |mStateLock| not needed as we are on the main thread
2636 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
2637 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2638 }
2639 return false;
2640 }
2641
2642 // Never touch the framebuffer if we don't have any framebuffer layers
2643 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2644 if (hasDeviceComposition) {
2645 // when using overlays, we assume a fully transparent framebuffer
2646 // NOTE: we could reduce how much we need to clear, for instance
2647 // remove where there are opaque FB layers. however, on some
2648 // GPUs doing a "clean slate" clear might be more efficient.
2649 // We'll revisit later if needed.
2650 mRenderEngine->clearWithColor(0, 0, 0, 0);
2651 } else {
2652 // we start with the whole screen area
2653 const Region bounds(displayDevice->getBounds());
2654
2655 // we remove the scissor part
2656 // we're left with the letterbox region
2657 // (common case is that letterbox ends-up being empty)
2658 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
2659
2660 // compute the area to clear
2661 Region region(displayDevice->undefinedRegion.merge(letterbox));
2662
2663 // but limit it to the dirty region
2664 region.andSelf(dirty);
2665
2666 // screen is already cleared here
2667 if (!region.isEmpty()) {
2668 // can happen with SurfaceView
2669 drawWormhole(displayDevice, region);
2670 }
2671 }
2672
2673 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2674 // just to be on the safe side, we don't set the
2675 // scissor on the main display. It should never be needed
2676 // anyways (though in theory it could since the API allows it).
2677 const Rect& bounds(displayDevice->getBounds());
2678 const Rect& scissor(displayDevice->getScissor());
2679 if (scissor != bounds) {
2680 // scissor doesn't match the screen's dimensions, so we
2681 // need to clear everything outside of it and enable
2682 // the GL scissor so we don't draw anything where we shouldn't
2683
2684 // enable scissor for this frame
2685 const uint32_t height = displayDevice->getHeight();
2686 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
2687 scissor.getWidth(), scissor.getHeight());
2688 }
2689 }
2690 }
2691
2692 /*
2693 * and then, render the layers targeted at the framebuffer
2694 */
2695
2696 ALOGV("Rendering client layers");
2697 const Transform& displayTransform = displayDevice->getTransform();
2698 if (hwcId >= 0) {
2699 // we're using h/w composer
2700 bool firstLayer = true;
2701 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2702 const Region clip(dirty.intersect(
2703 displayTransform.transform(layer->visibleRegion)));
2704 ALOGV("Layer: %s", layer->getName().string());
2705 ALOGV(" Composition type: %s",
2706 to_string(layer->getCompositionType(hwcId)).c_str());
2707 if (!clip.isEmpty()) {
2708 switch (layer->getCompositionType(hwcId)) {
2709 case HWC2::Composition::Cursor:
2710 case HWC2::Composition::Device:
2711 case HWC2::Composition::Sideband:
2712 case HWC2::Composition::SolidColor: {
2713 const Layer::State& state(layer->getDrawingState());
2714 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2715 layer->isOpaque(state) && (state.alpha == 1.0f)
2716 && hasClientComposition) {
2717 // never clear the very first layer since we're
2718 // guaranteed the FB is already cleared
2719 layer->clearWithOpenGL(displayDevice);
2720 }
2721 break;
2722 }
2723 case HWC2::Composition::Client: {
2724 layer->draw(displayDevice, clip);
2725 break;
2726 }
2727 default:
2728 break;
2729 }
2730 } else {
2731 ALOGV(" Skipping for empty clip");
2732 }
2733 firstLayer = false;
2734 }
2735 } else {
2736 // we're not using h/w composer
2737 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2738 const Region clip(dirty.intersect(
2739 displayTransform.transform(layer->visibleRegion)));
2740 if (!clip.isEmpty()) {
2741 layer->draw(displayDevice, clip);
2742 }
2743 }
2744 }
2745
2746 if (applyColorMatrix) {
2747 getRenderEngine().setupColorTransform(oldColorMatrix);
2748 }
2749
2750 // disable scissor at the end of the frame
2751 mRenderEngine->disableScissor();
2752 return true;
2753 }
2754
drawWormhole(const sp<const DisplayDevice> & displayDevice,const Region & region) const2755 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2756 const int32_t height = displayDevice->getHeight();
2757 RenderEngine& engine(getRenderEngine());
2758 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2759 }
2760
addClientLayer(const sp<Client> & client,const sp<IBinder> & handle,const sp<IGraphicBufferProducer> & gbc,const sp<Layer> & lbc,const sp<Layer> & parent)2761 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2762 const sp<IBinder>& handle,
2763 const sp<IGraphicBufferProducer>& gbc,
2764 const sp<Layer>& lbc,
2765 const sp<Layer>& parent)
2766 {
2767 // add this layer to the current state list
2768 {
2769 Mutex::Autolock _l(mStateLock);
2770 if (mNumLayers >= MAX_LAYERS) {
2771 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2772 MAX_LAYERS);
2773 return NO_MEMORY;
2774 }
2775 if (parent == nullptr) {
2776 mCurrentState.layersSortedByZ.add(lbc);
2777 } else {
2778 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2779 ALOGE("addClientLayer called with a removed parent");
2780 return NAME_NOT_FOUND;
2781 }
2782 parent->addChild(lbc);
2783 }
2784
2785 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2786 mLayersAdded = true;
2787 mNumLayers++;
2788 }
2789
2790 // attach this layer to the client
2791 client->attachLayer(handle, lbc);
2792
2793 return NO_ERROR;
2794 }
2795
removeLayer(const sp<Layer> & layer,bool topLevelOnly)2796 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
2797 Mutex::Autolock _l(mStateLock);
2798
2799 const auto& p = layer->getParent();
2800 ssize_t index;
2801 if (p != nullptr) {
2802 if (topLevelOnly) {
2803 return NO_ERROR;
2804 }
2805
2806 sp<Layer> ancestor = p;
2807 while (ancestor->getParent() != nullptr) {
2808 ancestor = ancestor->getParent();
2809 }
2810 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2811 ALOGE("removeLayer called with a layer whose parent has been removed");
2812 return NAME_NOT_FOUND;
2813 }
2814
2815 index = p->removeChild(layer);
2816 } else {
2817 index = mCurrentState.layersSortedByZ.remove(layer);
2818 }
2819
2820 // As a matter of normal operation, the LayerCleaner will produce a second
2821 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2822 // so we will succeed in promoting it, but it's already been removed
2823 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2824 // otherwise something has gone wrong and we are leaking the layer.
2825 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
2826 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2827 layer->getName().string(),
2828 (p != nullptr) ? p->getName().string() : "no-parent");
2829 return BAD_VALUE;
2830 } else if (index < 0) {
2831 return NO_ERROR;
2832 }
2833
2834 layer->onRemovedFromCurrentState();
2835 mLayersPendingRemoval.add(layer);
2836 mLayersRemoved = true;
2837 mNumLayers -= 1 + layer->getChildrenCount();
2838 setTransactionFlags(eTransactionNeeded);
2839 return NO_ERROR;
2840 }
2841
peekTransactionFlags()2842 uint32_t SurfaceFlinger::peekTransactionFlags() {
2843 return android_atomic_release_load(&mTransactionFlags);
2844 }
2845
getTransactionFlags(uint32_t flags)2846 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2847 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2848 }
2849
setTransactionFlags(uint32_t flags)2850 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2851 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2852 if ((old & flags)==0) { // wake the server up
2853 signalTransaction();
2854 }
2855 return old;
2856 }
2857
setTransactionState(const Vector<ComposerState> & state,const Vector<DisplayState> & displays,uint32_t flags)2858 void SurfaceFlinger::setTransactionState(
2859 const Vector<ComposerState>& state,
2860 const Vector<DisplayState>& displays,
2861 uint32_t flags)
2862 {
2863 ATRACE_CALL();
2864 Mutex::Autolock _l(mStateLock);
2865 uint32_t transactionFlags = 0;
2866
2867 if (flags & eAnimation) {
2868 // For window updates that are part of an animation we must wait for
2869 // previous animation "frames" to be handled.
2870 while (mAnimTransactionPending) {
2871 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2872 if (CC_UNLIKELY(err != NO_ERROR)) {
2873 // just in case something goes wrong in SF, return to the
2874 // caller after a few seconds.
2875 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2876 "waiting for previous animation frame");
2877 mAnimTransactionPending = false;
2878 break;
2879 }
2880 }
2881 }
2882
2883 size_t count = displays.size();
2884 for (size_t i=0 ; i<count ; i++) {
2885 const DisplayState& s(displays[i]);
2886 transactionFlags |= setDisplayStateLocked(s);
2887 }
2888
2889 count = state.size();
2890 for (size_t i=0 ; i<count ; i++) {
2891 const ComposerState& s(state[i]);
2892 // Here we need to check that the interface we're given is indeed
2893 // one of our own. A malicious client could give us a NULL
2894 // IInterface, or one of its own or even one of our own but a
2895 // different type. All these situations would cause us to crash.
2896 //
2897 // NOTE: it would be better to use RTTI as we could directly check
2898 // that we have a Client*. however, RTTI is disabled in Android.
2899 if (s.client != NULL) {
2900 sp<IBinder> binder = IInterface::asBinder(s.client);
2901 if (binder != NULL) {
2902 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
2903 sp<Client> client( static_cast<Client *>(s.client.get()) );
2904 transactionFlags |= setClientStateLocked(client, s.state);
2905 }
2906 }
2907 }
2908 }
2909
2910 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2911 // anyway. This can be used as a flush mechanism for previous async transactions.
2912 // Empty animation transaction can be used to simulate back-pressure, so also force a
2913 // transaction for empty animation transactions.
2914 if (transactionFlags == 0 &&
2915 ((flags & eSynchronous) || (flags & eAnimation))) {
2916 transactionFlags = eTransactionNeeded;
2917 }
2918
2919 if (transactionFlags) {
2920 if (mInterceptor.isEnabled()) {
2921 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2922 }
2923
2924 // this triggers the transaction
2925 setTransactionFlags(transactionFlags);
2926
2927 // if this is a synchronous transaction, wait for it to take effect
2928 // before returning.
2929 if (flags & eSynchronous) {
2930 mTransactionPending = true;
2931 }
2932 if (flags & eAnimation) {
2933 mAnimTransactionPending = true;
2934 }
2935 while (mTransactionPending) {
2936 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2937 if (CC_UNLIKELY(err != NO_ERROR)) {
2938 // just in case something goes wrong in SF, return to the
2939 // called after a few seconds.
2940 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2941 mTransactionPending = false;
2942 break;
2943 }
2944 }
2945 }
2946 }
2947
setDisplayStateLocked(const DisplayState & s)2948 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2949 {
2950 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2951 if (dpyIdx < 0)
2952 return 0;
2953
2954 uint32_t flags = 0;
2955 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2956 if (disp.isValid()) {
2957 const uint32_t what = s.what;
2958 if (what & DisplayState::eSurfaceChanged) {
2959 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2960 disp.surface = s.surface;
2961 flags |= eDisplayTransactionNeeded;
2962 }
2963 }
2964 if (what & DisplayState::eLayerStackChanged) {
2965 if (disp.layerStack != s.layerStack) {
2966 disp.layerStack = s.layerStack;
2967 flags |= eDisplayTransactionNeeded;
2968 }
2969 }
2970 if (what & DisplayState::eDisplayProjectionChanged) {
2971 if (disp.orientation != s.orientation) {
2972 disp.orientation = s.orientation;
2973 flags |= eDisplayTransactionNeeded;
2974 }
2975 if (disp.frame != s.frame) {
2976 disp.frame = s.frame;
2977 flags |= eDisplayTransactionNeeded;
2978 }
2979 if (disp.viewport != s.viewport) {
2980 disp.viewport = s.viewport;
2981 flags |= eDisplayTransactionNeeded;
2982 }
2983 }
2984 if (what & DisplayState::eDisplaySizeChanged) {
2985 if (disp.width != s.width) {
2986 disp.width = s.width;
2987 flags |= eDisplayTransactionNeeded;
2988 }
2989 if (disp.height != s.height) {
2990 disp.height = s.height;
2991 flags |= eDisplayTransactionNeeded;
2992 }
2993 }
2994 }
2995 return flags;
2996 }
2997
setClientStateLocked(const sp<Client> & client,const layer_state_t & s)2998 uint32_t SurfaceFlinger::setClientStateLocked(
2999 const sp<Client>& client,
3000 const layer_state_t& s)
3001 {
3002 uint32_t flags = 0;
3003 sp<Layer> layer(client->getLayerUser(s.surface));
3004 if (layer != 0) {
3005 const uint32_t what = s.what;
3006 bool geometryAppliesWithResize =
3007 what & layer_state_t::eGeometryAppliesWithResize;
3008 if (what & layer_state_t::ePositionChanged) {
3009 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3010 flags |= eTraversalNeeded;
3011 }
3012 }
3013 if (what & layer_state_t::eLayerChanged) {
3014 // NOTE: index needs to be calculated before we update the state
3015 const auto& p = layer->getParent();
3016 if (p == nullptr) {
3017 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3018 if (layer->setLayer(s.z) && idx >= 0) {
3019 mCurrentState.layersSortedByZ.removeAt(idx);
3020 mCurrentState.layersSortedByZ.add(layer);
3021 // we need traversal (state changed)
3022 // AND transaction (list changed)
3023 flags |= eTransactionNeeded|eTraversalNeeded;
3024 }
3025 } else {
3026 if (p->setChildLayer(layer, s.z)) {
3027 flags |= eTransactionNeeded|eTraversalNeeded;
3028 }
3029 }
3030 }
3031 if (what & layer_state_t::eRelativeLayerChanged) {
3032 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
3033 flags |= eTransactionNeeded|eTraversalNeeded;
3034 }
3035 }
3036 if (what & layer_state_t::eSizeChanged) {
3037 if (layer->setSize(s.w, s.h)) {
3038 flags |= eTraversalNeeded;
3039 }
3040 }
3041 if (what & layer_state_t::eAlphaChanged) {
3042 if (layer->setAlpha(s.alpha))
3043 flags |= eTraversalNeeded;
3044 }
3045 if (what & layer_state_t::eMatrixChanged) {
3046 if (layer->setMatrix(s.matrix))
3047 flags |= eTraversalNeeded;
3048 }
3049 if (what & layer_state_t::eTransparentRegionChanged) {
3050 if (layer->setTransparentRegionHint(s.transparentRegion))
3051 flags |= eTraversalNeeded;
3052 }
3053 if (what & layer_state_t::eFlagsChanged) {
3054 if (layer->setFlags(s.flags, s.mask))
3055 flags |= eTraversalNeeded;
3056 }
3057 if (what & layer_state_t::eCropChanged) {
3058 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3059 flags |= eTraversalNeeded;
3060 }
3061 if (what & layer_state_t::eFinalCropChanged) {
3062 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3063 flags |= eTraversalNeeded;
3064 }
3065 if (what & layer_state_t::eLayerStackChanged) {
3066 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3067 // We only allow setting layer stacks for top level layers,
3068 // everything else inherits layer stack from its parent.
3069 if (layer->hasParent()) {
3070 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3071 layer->getName().string());
3072 } else if (idx < 0) {
3073 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3074 "that also does not appear in the top level layer list. Something"
3075 " has gone wrong.", layer->getName().string());
3076 } else if (layer->setLayerStack(s.layerStack)) {
3077 mCurrentState.layersSortedByZ.removeAt(idx);
3078 mCurrentState.layersSortedByZ.add(layer);
3079 // we need traversal (state changed)
3080 // AND transaction (list changed)
3081 flags |= eTransactionNeeded|eTraversalNeeded;
3082 }
3083 }
3084 if (what & layer_state_t::eDeferTransaction) {
3085 if (s.barrierHandle != nullptr) {
3086 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3087 } else if (s.barrierGbp != nullptr) {
3088 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3089 if (authenticateSurfaceTextureLocked(gbp)) {
3090 const auto& otherLayer =
3091 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3092 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3093 } else {
3094 ALOGE("Attempt to defer transaction to to an"
3095 " unrecognized GraphicBufferProducer");
3096 }
3097 }
3098 // We don't trigger a traversal here because if no other state is
3099 // changed, we don't want this to cause any more work
3100 }
3101 if (what & layer_state_t::eReparentChildren) {
3102 if (layer->reparentChildren(s.reparentHandle)) {
3103 flags |= eTransactionNeeded|eTraversalNeeded;
3104 }
3105 }
3106 if (what & layer_state_t::eDetachChildren) {
3107 layer->detachChildren();
3108 }
3109 if (what & layer_state_t::eOverrideScalingModeChanged) {
3110 layer->setOverrideScalingMode(s.overrideScalingMode);
3111 // We don't trigger a traversal here because if no other state is
3112 // changed, we don't want this to cause any more work
3113 }
3114 }
3115 return flags;
3116 }
3117
createLayer(const String8 & name,const sp<Client> & client,uint32_t w,uint32_t h,PixelFormat format,uint32_t flags,uint32_t windowType,uint32_t ownerUid,sp<IBinder> * handle,sp<IGraphicBufferProducer> * gbp,sp<Layer> * parent)3118 status_t SurfaceFlinger::createLayer(
3119 const String8& name,
3120 const sp<Client>& client,
3121 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
3122 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3123 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
3124 {
3125 if (int32_t(w|h) < 0) {
3126 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
3127 int(w), int(h));
3128 return BAD_VALUE;
3129 }
3130
3131 status_t result = NO_ERROR;
3132
3133 sp<Layer> layer;
3134
3135 String8 uniqueName = getUniqueLayerName(name);
3136
3137 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3138 case ISurfaceComposerClient::eFXSurfaceNormal:
3139 result = createNormalLayer(client,
3140 uniqueName, w, h, flags, format,
3141 handle, gbp, &layer);
3142 break;
3143 case ISurfaceComposerClient::eFXSurfaceDim:
3144 result = createDimLayer(client,
3145 uniqueName, w, h, flags,
3146 handle, gbp, &layer);
3147 break;
3148 default:
3149 result = BAD_VALUE;
3150 break;
3151 }
3152
3153 if (result != NO_ERROR) {
3154 return result;
3155 }
3156
3157 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3158 // TODO b/64227542
3159 if (windowType == 441731) {
3160 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3161 layer->setPrimaryDisplayOnly();
3162 }
3163
3164 layer->setInfo(windowType, ownerUid);
3165
3166 result = addClientLayer(client, *handle, *gbp, layer, *parent);
3167 if (result != NO_ERROR) {
3168 return result;
3169 }
3170 mInterceptor.saveSurfaceCreation(layer);
3171
3172 setTransactionFlags(eTransactionNeeded);
3173 return result;
3174 }
3175
getUniqueLayerName(const String8 & name)3176 String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3177 {
3178 bool matchFound = true;
3179 uint32_t dupeCounter = 0;
3180
3181 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3182 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3183
3184 // Loop over layers until we're sure there is no matching name
3185 while (matchFound) {
3186 matchFound = false;
3187 mDrawingState.traverseInZOrder([&](Layer* layer) {
3188 if (layer->getName() == uniqueName) {
3189 matchFound = true;
3190 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3191 }
3192 });
3193 }
3194
3195 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3196
3197 return uniqueName;
3198 }
3199
createNormalLayer(const sp<Client> & client,const String8 & name,uint32_t w,uint32_t h,uint32_t flags,PixelFormat & format,sp<IBinder> * handle,sp<IGraphicBufferProducer> * gbp,sp<Layer> * outLayer)3200 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3201 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3202 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
3203 {
3204 // initialize the surfaces
3205 switch (format) {
3206 case PIXEL_FORMAT_TRANSPARENT:
3207 case PIXEL_FORMAT_TRANSLUCENT:
3208 format = PIXEL_FORMAT_RGBA_8888;
3209 break;
3210 case PIXEL_FORMAT_OPAQUE:
3211 format = PIXEL_FORMAT_RGBX_8888;
3212 break;
3213 }
3214
3215 *outLayer = new Layer(this, client, name, w, h, flags);
3216 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3217 if (err == NO_ERROR) {
3218 *handle = (*outLayer)->getHandle();
3219 *gbp = (*outLayer)->getProducer();
3220 }
3221
3222 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3223 return err;
3224 }
3225
createDimLayer(const sp<Client> & client,const String8 & name,uint32_t w,uint32_t h,uint32_t flags,sp<IBinder> * handle,sp<IGraphicBufferProducer> * gbp,sp<Layer> * outLayer)3226 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3227 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3228 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
3229 {
3230 *outLayer = new LayerDim(this, client, name, w, h, flags);
3231 *handle = (*outLayer)->getHandle();
3232 *gbp = (*outLayer)->getProducer();
3233 return NO_ERROR;
3234 }
3235
onLayerRemoved(const sp<Client> & client,const sp<IBinder> & handle)3236 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
3237 {
3238 // called by a client when it wants to remove a Layer
3239 status_t err = NO_ERROR;
3240 sp<Layer> l(client->getLayerUser(handle));
3241 if (l != NULL) {
3242 mInterceptor.saveSurfaceDeletion(l);
3243 err = removeLayer(l);
3244 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3245 "error removing layer=%p (%s)", l.get(), strerror(-err));
3246 }
3247 return err;
3248 }
3249
onLayerDestroyed(const wp<Layer> & layer)3250 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
3251 {
3252 // called by ~LayerCleaner() when all references to the IBinder (handle)
3253 // are gone
3254 sp<Layer> l = layer.promote();
3255 if (l == nullptr) {
3256 // The layer has already been removed, carry on
3257 return NO_ERROR;
3258 }
3259 // If we have a parent, then we can continue to live as long as it does.
3260 return removeLayer(l, true);
3261 }
3262
3263 // ---------------------------------------------------------------------------
3264
onInitializeDisplays()3265 void SurfaceFlinger::onInitializeDisplays() {
3266 // reset screen orientation and use primary layer stack
3267 Vector<ComposerState> state;
3268 Vector<DisplayState> displays;
3269 DisplayState d;
3270 d.what = DisplayState::eDisplayProjectionChanged |
3271 DisplayState::eLayerStackChanged;
3272 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
3273 d.layerStack = 0;
3274 d.orientation = DisplayState::eOrientationDefault;
3275 d.frame.makeInvalid();
3276 d.viewport.makeInvalid();
3277 d.width = 0;
3278 d.height = 0;
3279 displays.add(d);
3280 setTransactionState(state, displays, 0);
3281 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3282 /*stateLockHeld*/ false);
3283
3284 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3285 const nsecs_t period = activeConfig->getVsyncPeriod();
3286 mAnimFrameTracker.setDisplayRefreshPeriod(period);
3287
3288 // Use phase of 0 since phase is not known.
3289 // Use latency of 0, which will snap to the ideal latency.
3290 setCompositorTimingSnapped(0, period, 0);
3291 }
3292
initializeDisplays()3293 void SurfaceFlinger::initializeDisplays() {
3294 class MessageScreenInitialized : public MessageBase {
3295 SurfaceFlinger* flinger;
3296 public:
3297 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
3298 virtual bool handler() {
3299 flinger->onInitializeDisplays();
3300 return true;
3301 }
3302 };
3303 sp<MessageBase> msg = new MessageScreenInitialized(this);
3304 postMessageAsync(msg); // we may be called from main thread, use async message
3305 }
3306
setPowerModeInternal(const sp<DisplayDevice> & hw,int mode,bool stateLockHeld)3307 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3308 int mode, bool stateLockHeld) {
3309 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3310 this);
3311 int32_t type = hw->getDisplayType();
3312 int currentMode = hw->getPowerMode();
3313
3314 if (mode == currentMode) {
3315 return;
3316 }
3317
3318 hw->setPowerMode(mode);
3319 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3320 ALOGW("Trying to set power mode for virtual display");
3321 return;
3322 }
3323
3324 if (mInterceptor.isEnabled()) {
3325 ConditionalLock lock(mStateLock, !stateLockHeld);
3326 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3327 if (idx < 0) {
3328 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3329 return;
3330 }
3331 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3332 }
3333
3334 if (currentMode == HWC_POWER_MODE_OFF) {
3335 // Turn on the display
3336 getHwComposer().setPowerMode(type, mode);
3337 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3338 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
3339 // FIXME: eventthread only knows about the main display right now
3340 mEventThread->onScreenAcquired();
3341 resyncToHardwareVsync(true);
3342 }
3343
3344 mVisibleRegionsDirty = true;
3345 mHasPoweredOff = true;
3346 repaintEverythingLocked();
3347
3348 struct sched_param param = {0};
3349 param.sched_priority = 1;
3350 if (sched_setscheduler(0, SCHED_FIFO, ¶m) != 0) {
3351 ALOGW("Couldn't set SCHED_FIFO on display on");
3352 }
3353 } else if (mode == HWC_POWER_MODE_OFF) {
3354 // Turn off the display
3355 struct sched_param param = {0};
3356 if (sched_setscheduler(0, SCHED_OTHER, ¶m) != 0) {
3357 ALOGW("Couldn't set SCHED_OTHER on display off");
3358 }
3359
3360 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3361 disableHardwareVsync(true); // also cancels any in-progress resync
3362
3363 // FIXME: eventthread only knows about the main display right now
3364 mEventThread->onScreenReleased();
3365 }
3366
3367 getHwComposer().setPowerMode(type, mode);
3368 mVisibleRegionsDirty = true;
3369 // from this point on, SF will stop drawing on this display
3370 } else if (mode == HWC_POWER_MODE_DOZE ||
3371 mode == HWC_POWER_MODE_NORMAL) {
3372 // Update display while dozing
3373 getHwComposer().setPowerMode(type, mode);
3374 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3375 // FIXME: eventthread only knows about the main display right now
3376 mEventThread->onScreenAcquired();
3377 resyncToHardwareVsync(true);
3378 }
3379 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3380 // Leave display going to doze
3381 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3382 disableHardwareVsync(true); // also cancels any in-progress resync
3383 // FIXME: eventthread only knows about the main display right now
3384 mEventThread->onScreenReleased();
3385 }
3386 getHwComposer().setPowerMode(type, mode);
3387 } else {
3388 ALOGE("Attempting to set unknown power mode: %d\n", mode);
3389 getHwComposer().setPowerMode(type, mode);
3390 }
3391 }
3392
setPowerMode(const sp<IBinder> & display,int mode)3393 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3394 class MessageSetPowerMode: public MessageBase {
3395 SurfaceFlinger& mFlinger;
3396 sp<IBinder> mDisplay;
3397 int mMode;
3398 public:
3399 MessageSetPowerMode(SurfaceFlinger& flinger,
3400 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3401 mDisplay(disp) { mMode = mode; }
3402 virtual bool handler() {
3403 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
3404 if (hw == NULL) {
3405 ALOGE("Attempt to set power mode = %d for null display %p",
3406 mMode, mDisplay.get());
3407 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
3408 ALOGW("Attempt to set power mode = %d for virtual display",
3409 mMode);
3410 } else {
3411 mFlinger.setPowerModeInternal(
3412 hw, mMode, /*stateLockHeld*/ false);
3413 }
3414 return true;
3415 }
3416 };
3417 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
3418 postMessageSync(msg);
3419 }
3420
3421 // ---------------------------------------------------------------------------
3422
dump(int fd,const Vector<String16> & args)3423 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3424 {
3425 String8 result;
3426
3427 IPCThreadState* ipc = IPCThreadState::self();
3428 const int pid = ipc->getCallingPid();
3429 const int uid = ipc->getCallingUid();
3430 if ((uid != AID_SHELL) &&
3431 !PermissionCache::checkPermission(sDump, pid, uid)) {
3432 result.appendFormat("Permission Denial: "
3433 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
3434 } else {
3435 // Try to get the main lock, but give up after one second
3436 // (this would indicate SF is stuck, but we want to be able to
3437 // print something in dumpsys).
3438 status_t err = mStateLock.timedLock(s2ns(1));
3439 bool locked = (err == NO_ERROR);
3440 if (!locked) {
3441 result.appendFormat(
3442 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3443 "dumping anyways (no locks held)\n", strerror(-err), err);
3444 }
3445
3446 bool dumpAll = true;
3447 size_t index = 0;
3448 size_t numArgs = args.size();
3449 if (numArgs) {
3450 if ((index < numArgs) &&
3451 (args[index] == String16("--list"))) {
3452 index++;
3453 listLayersLocked(args, index, result);
3454 dumpAll = false;
3455 }
3456
3457 if ((index < numArgs) &&
3458 (args[index] == String16("--latency"))) {
3459 index++;
3460 dumpStatsLocked(args, index, result);
3461 dumpAll = false;
3462 }
3463
3464 if ((index < numArgs) &&
3465 (args[index] == String16("--latency-clear"))) {
3466 index++;
3467 clearStatsLocked(args, index, result);
3468 dumpAll = false;
3469 }
3470
3471 if ((index < numArgs) &&
3472 (args[index] == String16("--dispsync"))) {
3473 index++;
3474 mPrimaryDispSync.dump(result);
3475 dumpAll = false;
3476 }
3477
3478 if ((index < numArgs) &&
3479 (args[index] == String16("--static-screen"))) {
3480 index++;
3481 dumpStaticScreenStats(result);
3482 dumpAll = false;
3483 }
3484
3485 if ((index < numArgs) &&
3486 (args[index] == String16("--frame-events"))) {
3487 index++;
3488 dumpFrameEventsLocked(result);
3489 dumpAll = false;
3490 }
3491
3492 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3493 index++;
3494 dumpWideColorInfo(result);
3495 dumpAll = false;
3496 }
3497 }
3498
3499 if (dumpAll) {
3500 dumpAllLocked(args, index, result);
3501 }
3502
3503 if (locked) {
3504 mStateLock.unlock();
3505 }
3506 }
3507 write(fd, result.string(), result.size());
3508 return NO_ERROR;
3509 }
3510
listLayersLocked(const Vector<String16> &,size_t &,String8 & result) const3511 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3512 size_t& /* index */, String8& result) const
3513 {
3514 mCurrentState.traverseInZOrder([&](Layer* layer) {
3515 result.appendFormat("%s\n", layer->getName().string());
3516 });
3517 }
3518
dumpStatsLocked(const Vector<String16> & args,size_t & index,String8 & result) const3519 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
3520 String8& result) const
3521 {
3522 String8 name;
3523 if (index < args.size()) {
3524 name = String8(args[index]);
3525 index++;
3526 }
3527
3528 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3529 const nsecs_t period = activeConfig->getVsyncPeriod();
3530 result.appendFormat("%" PRId64 "\n", period);
3531
3532 if (name.isEmpty()) {
3533 mAnimFrameTracker.dumpStats(result);
3534 } else {
3535 mCurrentState.traverseInZOrder([&](Layer* layer) {
3536 if (name == layer->getName()) {
3537 layer->dumpFrameStats(result);
3538 }
3539 });
3540 }
3541 }
3542
clearStatsLocked(const Vector<String16> & args,size_t & index,String8 &)3543 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
3544 String8& /* result */)
3545 {
3546 String8 name;
3547 if (index < args.size()) {
3548 name = String8(args[index]);
3549 index++;
3550 }
3551
3552 mCurrentState.traverseInZOrder([&](Layer* layer) {
3553 if (name.isEmpty() || (name == layer->getName())) {
3554 layer->clearFrameStats();
3555 }
3556 });
3557
3558 mAnimFrameTracker.clearStats();
3559 }
3560
3561 // This should only be called from the main thread. Otherwise it would need
3562 // the lock and should use mCurrentState rather than mDrawingState.
logFrameStats()3563 void SurfaceFlinger::logFrameStats() {
3564 mDrawingState.traverseInZOrder([&](Layer* layer) {
3565 layer->logFrameStats();
3566 });
3567
3568 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3569 }
3570
appendSfConfigString(String8 & result) const3571 void SurfaceFlinger::appendSfConfigString(String8& result) const
3572 {
3573 result.append(" [sf");
3574 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3575
3576 if (isLayerTripleBufferingDisabled())
3577 result.append(" DISABLE_TRIPLE_BUFFERING");
3578
3579 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
3580 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3581 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3582 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3583 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3584 maxFrameBufferAcquiredBuffers);
3585 result.append("]");
3586 }
3587
dumpStaticScreenStats(String8 & result) const3588 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3589 {
3590 result.appendFormat("Static screen stats:\n");
3591 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3592 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3593 float percent = 100.0f *
3594 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3595 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3596 b + 1, bucketTimeSec, percent);
3597 }
3598 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3599 float percent = 100.0f *
3600 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3601 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3602 NUM_BUCKETS - 1, bucketTimeSec, percent);
3603 }
3604
recordBufferingStats(const char * layerName,std::vector<OccupancyTracker::Segment> && history)3605 void SurfaceFlinger::recordBufferingStats(const char* layerName,
3606 std::vector<OccupancyTracker::Segment>&& history) {
3607 Mutex::Autolock lock(mBufferingStatsMutex);
3608 auto& stats = mBufferingStats[layerName];
3609 for (const auto& segment : history) {
3610 if (!segment.usedThirdBuffer) {
3611 stats.twoBufferTime += segment.totalTime;
3612 }
3613 if (segment.occupancyAverage < 1.0f) {
3614 stats.doubleBufferedTime += segment.totalTime;
3615 } else if (segment.occupancyAverage < 2.0f) {
3616 stats.tripleBufferedTime += segment.totalTime;
3617 }
3618 ++stats.numSegments;
3619 stats.totalTime += segment.totalTime;
3620 }
3621 }
3622
dumpFrameEventsLocked(String8 & result)3623 void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3624 result.appendFormat("Layer frame timestamps:\n");
3625
3626 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3627 const size_t count = currentLayers.size();
3628 for (size_t i=0 ; i<count ; i++) {
3629 currentLayers[i]->dumpFrameEvents(result);
3630 }
3631 }
3632
dumpBufferingStats(String8 & result) const3633 void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3634 result.append("Buffering stats:\n");
3635 result.append(" [Layer name] <Active time> <Two buffer> "
3636 "<Double buffered> <Triple buffered>\n");
3637 Mutex::Autolock lock(mBufferingStatsMutex);
3638 typedef std::tuple<std::string, float, float, float> BufferTuple;
3639 std::map<float, BufferTuple, std::greater<float>> sorted;
3640 for (const auto& statsPair : mBufferingStats) {
3641 const char* name = statsPair.first.c_str();
3642 const BufferingStats& stats = statsPair.second;
3643 if (stats.numSegments == 0) {
3644 continue;
3645 }
3646 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3647 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3648 stats.totalTime;
3649 float doubleBufferRatio = static_cast<float>(
3650 stats.doubleBufferedTime) / stats.totalTime;
3651 float tripleBufferRatio = static_cast<float>(
3652 stats.tripleBufferedTime) / stats.totalTime;
3653 sorted.insert({activeTime, {name, twoBufferRatio,
3654 doubleBufferRatio, tripleBufferRatio}});
3655 }
3656 for (const auto& sortedPair : sorted) {
3657 float activeTime = sortedPair.first;
3658 const BufferTuple& values = sortedPair.second;
3659 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3660 std::get<0>(values).c_str(), activeTime,
3661 std::get<1>(values), std::get<2>(values),
3662 std::get<3>(values));
3663 }
3664 result.append("\n");
3665 }
3666
dumpWideColorInfo(String8 & result) const3667 void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3668 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3669 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
3670
3671 // TODO: print out if wide-color mode is active or not
3672
3673 for (size_t d = 0; d < mDisplays.size(); d++) {
3674 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3675 int32_t hwcId = displayDevice->getHwcDisplayId();
3676 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3677 continue;
3678 }
3679
3680 result.appendFormat("Display %d color modes:\n", hwcId);
3681 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3682 for (auto&& mode : modes) {
3683 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3684 }
3685
3686 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3687 result.appendFormat(" Current color mode: %s (%d)\n",
3688 decodeColorMode(currentMode).c_str(), currentMode);
3689 }
3690 result.append("\n");
3691 }
3692
dumpAllLocked(const Vector<String16> & args,size_t & index,String8 & result) const3693 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3694 String8& result) const
3695 {
3696 bool colorize = false;
3697 if (index < args.size()
3698 && (args[index] == String16("--color"))) {
3699 colorize = true;
3700 index++;
3701 }
3702
3703 Colorizer colorizer(colorize);
3704
3705 // figure out if we're stuck somewhere
3706 const nsecs_t now = systemTime();
3707 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3708 const nsecs_t inTransaction(mDebugInTransaction);
3709 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3710 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3711
3712 /*
3713 * Dump library configuration.
3714 */
3715
3716 colorizer.bold(result);
3717 result.append("Build configuration:");
3718 colorizer.reset(result);
3719 appendSfConfigString(result);
3720 appendUiConfigString(result);
3721 appendGuiConfigString(result);
3722 result.append("\n");
3723
3724 result.append("\nWide-Color information:\n");
3725 dumpWideColorInfo(result);
3726
3727 colorizer.bold(result);
3728 result.append("Sync configuration: ");
3729 colorizer.reset(result);
3730 result.append(SyncFeatures::getInstance().toString());
3731 result.append("\n");
3732
3733 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3734
3735 colorizer.bold(result);
3736 result.append("DispSync configuration: ");
3737 colorizer.reset(result);
3738 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3739 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
3740 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3741 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
3742 result.append("\n");
3743
3744 // Dump static screen stats
3745 result.append("\n");
3746 dumpStaticScreenStats(result);
3747 result.append("\n");
3748
3749 dumpBufferingStats(result);
3750
3751 /*
3752 * Dump the visible layer list
3753 */
3754 colorizer.bold(result);
3755 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
3756 colorizer.reset(result);
3757 mCurrentState.traverseInZOrder([&](Layer* layer) {
3758 layer->dump(result, colorizer);
3759 });
3760
3761 /*
3762 * Dump Display state
3763 */
3764
3765 colorizer.bold(result);
3766 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3767 colorizer.reset(result);
3768 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3769 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3770 hw->dump(result);
3771 }
3772
3773 /*
3774 * Dump SurfaceFlinger global state
3775 */
3776
3777 colorizer.bold(result);
3778 result.append("SurfaceFlinger global state:\n");
3779 colorizer.reset(result);
3780
3781 HWComposer& hwc(getHwComposer());
3782 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
3783
3784 colorizer.bold(result);
3785 result.appendFormat("EGL implementation : %s\n",
3786 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3787 colorizer.reset(result);
3788 result.appendFormat("%s\n",
3789 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3790
3791 mRenderEngine->dump(result);
3792
3793 hw->undefinedRegion.dump(result, "undefinedRegion");
3794 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3795 hw->getOrientation(), hw->isDisplayOn());
3796 result.appendFormat(
3797 " last eglSwapBuffers() time: %f us\n"
3798 " last transaction time : %f us\n"
3799 " transaction-flags : %08x\n"
3800 " refresh-rate : %f fps\n"
3801 " x-dpi : %f\n"
3802 " y-dpi : %f\n"
3803 " gpu_to_cpu_unsupported : %d\n"
3804 ,
3805 mLastSwapBufferTime/1000.0,
3806 mLastTransactionTime/1000.0,
3807 mTransactionFlags,
3808 1e9 / activeConfig->getVsyncPeriod(),
3809 activeConfig->getDpiX(),
3810 activeConfig->getDpiY(),
3811 !mGpuToCpuSupported);
3812
3813 result.appendFormat(" eglSwapBuffers time: %f us\n",
3814 inSwapBuffersDuration/1000.0);
3815
3816 result.appendFormat(" transaction time: %f us\n",
3817 inTransactionDuration/1000.0);
3818
3819 /*
3820 * VSYNC state
3821 */
3822 mEventThread->dump(result);
3823 result.append("\n");
3824
3825 /*
3826 * HWC layer minidump
3827 */
3828 for (size_t d = 0; d < mDisplays.size(); d++) {
3829 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3830 int32_t hwcId = displayDevice->getHwcDisplayId();
3831 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3832 continue;
3833 }
3834
3835 result.appendFormat("Display %d HWC layers:\n", hwcId);
3836 Layer::miniDumpHeader(result);
3837 mCurrentState.traverseInZOrder([&](Layer* layer) {
3838 layer->miniDump(result, hwcId);
3839 });
3840 result.append("\n");
3841 }
3842
3843 /*
3844 * Dump HWComposer state
3845 */
3846 colorizer.bold(result);
3847 result.append("h/w composer state:\n");
3848 colorizer.reset(result);
3849 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
3850 result.appendFormat(" h/w composer %s\n",
3851 hwcDisabled ? "disabled" : "enabled");
3852 hwc.dump(result);
3853
3854 /*
3855 * Dump gralloc state
3856 */
3857 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3858 alloc.dump(result);
3859
3860 /*
3861 * Dump VrFlinger state if in use.
3862 */
3863 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3864 result.append("VrFlinger state:\n");
3865 result.append(mVrFlinger->Dump().c_str());
3866 result.append("\n");
3867 }
3868 }
3869
3870 const Vector< sp<Layer> >&
getLayerSortedByZForHwcDisplay(int id)3871 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3872 // Note: mStateLock is held here
3873 wp<IBinder> dpy;
3874 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3875 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3876 dpy = mDisplays.keyAt(i);
3877 break;
3878 }
3879 }
3880 if (dpy == NULL) {
3881 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3882 // Just use the primary display so we have something to return
3883 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3884 }
3885 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
3886 }
3887
startDdmConnection()3888 bool SurfaceFlinger::startDdmConnection()
3889 {
3890 void* libddmconnection_dso =
3891 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3892 if (!libddmconnection_dso) {
3893 return false;
3894 }
3895 void (*DdmConnection_start)(const char* name);
3896 DdmConnection_start =
3897 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3898 if (!DdmConnection_start) {
3899 dlclose(libddmconnection_dso);
3900 return false;
3901 }
3902 (*DdmConnection_start)(getServiceName());
3903 return true;
3904 }
3905
CheckTransactCodeCredentials(uint32_t code)3906 status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
3907 switch (code) {
3908 case CREATE_CONNECTION:
3909 case CREATE_DISPLAY:
3910 case BOOT_FINISHED:
3911 case CLEAR_ANIMATION_FRAME_STATS:
3912 case GET_ANIMATION_FRAME_STATS:
3913 case SET_POWER_MODE:
3914 case GET_HDR_CAPABILITIES:
3915 case ENABLE_VSYNC_INJECTIONS:
3916 case INJECT_VSYNC:
3917 {
3918 // codes that require permission check
3919 IPCThreadState* ipc = IPCThreadState::self();
3920 const int pid = ipc->getCallingPid();
3921 const int uid = ipc->getCallingUid();
3922 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3923 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3924 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3925 return PERMISSION_DENIED;
3926 }
3927 break;
3928 }
3929 /*
3930 * Calling setTransactionState is safe, because you need to have been
3931 * granted a reference to Client* and Handle* to do anything with it.
3932 *
3933 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3934 */
3935 case SET_TRANSACTION_STATE:
3936 case CREATE_SCOPED_CONNECTION:
3937 {
3938 return OK;
3939 }
3940 case CAPTURE_SCREEN:
3941 {
3942 // codes that require permission check
3943 IPCThreadState* ipc = IPCThreadState::self();
3944 const int pid = ipc->getCallingPid();
3945 const int uid = ipc->getCallingUid();
3946 if ((uid != AID_GRAPHICS) &&
3947 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3948 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
3949 return PERMISSION_DENIED;
3950 }
3951 break;
3952 }
3953 }
3954 return OK;
3955 }
3956
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)3957 status_t SurfaceFlinger::onTransact(
3958 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3959 {
3960 status_t credentialCheck = CheckTransactCodeCredentials(code);
3961 if (credentialCheck != OK) {
3962 return credentialCheck;
3963 }
3964
3965 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3966 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3967 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3968 IPCThreadState* ipc = IPCThreadState::self();
3969 const int uid = ipc->getCallingUid();
3970 if (CC_UNLIKELY(uid != AID_SYSTEM
3971 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
3972 const int pid = ipc->getCallingPid();
3973 ALOGE("Permission Denial: "
3974 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3975 return PERMISSION_DENIED;
3976 }
3977 int n;
3978 switch (code) {
3979 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3980 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3981 return NO_ERROR;
3982 case 1002: // SHOW_UPDATES
3983 n = data.readInt32();
3984 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3985 invalidateHwcGeometry();
3986 repaintEverything();
3987 return NO_ERROR;
3988 case 1004:{ // repaint everything
3989 repaintEverything();
3990 return NO_ERROR;
3991 }
3992 case 1005:{ // force transaction
3993 Mutex::Autolock _l(mStateLock);
3994 setTransactionFlags(
3995 eTransactionNeeded|
3996 eDisplayTransactionNeeded|
3997 eTraversalNeeded);
3998 return NO_ERROR;
3999 }
4000 case 1006:{ // send empty update
4001 signalRefresh();
4002 return NO_ERROR;
4003 }
4004 case 1008: // toggle use of hw composer
4005 n = data.readInt32();
4006 mDebugDisableHWC = n ? 1 : 0;
4007 invalidateHwcGeometry();
4008 repaintEverything();
4009 return NO_ERROR;
4010 case 1009: // toggle use of transform hint
4011 n = data.readInt32();
4012 mDebugDisableTransformHint = n ? 1 : 0;
4013 invalidateHwcGeometry();
4014 repaintEverything();
4015 return NO_ERROR;
4016 case 1010: // interrogate.
4017 reply->writeInt32(0);
4018 reply->writeInt32(0);
4019 reply->writeInt32(mDebugRegion);
4020 reply->writeInt32(0);
4021 reply->writeInt32(mDebugDisableHWC);
4022 return NO_ERROR;
4023 case 1013: {
4024 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4025 reply->writeInt32(hw->getPageFlipCount());
4026 return NO_ERROR;
4027 }
4028 case 1014: {
4029 // daltonize
4030 n = data.readInt32();
4031 switch (n % 10) {
4032 case 1:
4033 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4034 break;
4035 case 2:
4036 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4037 break;
4038 case 3:
4039 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4040 break;
4041 default:
4042 mDaltonizer.setType(ColorBlindnessType::None);
4043 break;
4044 }
4045 if (n >= 10) {
4046 mDaltonizer.setMode(ColorBlindnessMode::Correction);
4047 } else {
4048 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
4049 }
4050 invalidateHwcGeometry();
4051 repaintEverything();
4052 return NO_ERROR;
4053 }
4054 case 1015: {
4055 // apply a color matrix
4056 n = data.readInt32();
4057 if (n) {
4058 // color matrix is sent as a column-major mat4 matrix
4059 for (size_t i = 0 ; i < 4; i++) {
4060 for (size_t j = 0; j < 4; j++) {
4061 mColorMatrix[i][j] = data.readFloat();
4062 }
4063 }
4064 } else {
4065 mColorMatrix = mat4();
4066 }
4067
4068 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4069 // the division by w in the fragment shader
4070 float4 lastRow(transpose(mColorMatrix)[3]);
4071 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4072 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4073 }
4074
4075 invalidateHwcGeometry();
4076 repaintEverything();
4077 return NO_ERROR;
4078 }
4079 // This is an experimental interface
4080 // Needs to be shifted to proper binder interface when we productize
4081 case 1016: {
4082 n = data.readInt32();
4083 mPrimaryDispSync.setRefreshSkipCount(n);
4084 return NO_ERROR;
4085 }
4086 case 1017: {
4087 n = data.readInt32();
4088 mForceFullDamage = static_cast<bool>(n);
4089 return NO_ERROR;
4090 }
4091 case 1018: { // Modify Choreographer's phase offset
4092 n = data.readInt32();
4093 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4094 return NO_ERROR;
4095 }
4096 case 1019: { // Modify SurfaceFlinger's phase offset
4097 n = data.readInt32();
4098 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4099 return NO_ERROR;
4100 }
4101 case 1020: { // Layer updates interceptor
4102 n = data.readInt32();
4103 if (n) {
4104 ALOGV("Interceptor enabled");
4105 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
4106 }
4107 else{
4108 ALOGV("Interceptor disabled");
4109 mInterceptor.disable();
4110 }
4111 return NO_ERROR;
4112 }
4113 case 1021: { // Disable HWC virtual displays
4114 n = data.readInt32();
4115 mUseHwcVirtualDisplays = !n;
4116 return NO_ERROR;
4117 }
4118 case 1022: { // Set saturation boost
4119 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4120
4121 invalidateHwcGeometry();
4122 repaintEverything();
4123 return NO_ERROR;
4124 }
4125 case 1023: { // Set native mode
4126 mForceNativeColorMode = data.readInt32() == 1;
4127
4128 invalidateHwcGeometry();
4129 repaintEverything();
4130 return NO_ERROR;
4131 }
4132 case 1024: { // Is wide color gamut rendering/color management supported?
4133 reply->writeBool(hasWideColorDisplay);
4134 return NO_ERROR;
4135 }
4136 }
4137 }
4138 return err;
4139 }
4140
repaintEverythingLocked()4141 void SurfaceFlinger::repaintEverythingLocked() {
4142 android_atomic_or(1, &mRepaintEverything);
4143 signalTransaction();
4144 }
4145
repaintEverything()4146 void SurfaceFlinger::repaintEverything() {
4147 ConditionalLock _l(mStateLock,
4148 std::this_thread::get_id() != mMainThreadId);
4149 repaintEverythingLocked();
4150 }
4151
4152 // Checks that the requested width and height are valid and updates them to the display dimensions
4153 // if they are set to 0
updateDimensionsLocked(const sp<const DisplayDevice> & displayDevice,Transform::orientation_flags rotation,uint32_t * requestedWidth,uint32_t * requestedHeight)4154 static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4155 Transform::orientation_flags rotation,
4156 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4157 // get screen geometry
4158 uint32_t displayWidth = displayDevice->getWidth();
4159 uint32_t displayHeight = displayDevice->getHeight();
4160
4161 if (rotation & Transform::ROT_90) {
4162 std::swap(displayWidth, displayHeight);
4163 }
4164
4165 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4166 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4167 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4168 return BAD_VALUE;
4169 }
4170
4171 if (*requestedWidth == 0) {
4172 *requestedWidth = displayWidth;
4173 }
4174 if (*requestedHeight == 0) {
4175 *requestedHeight = displayHeight;
4176 }
4177
4178 return NO_ERROR;
4179 }
4180
4181 // A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4182 class WindowDisconnector {
4183 public:
WindowDisconnector(ANativeWindow * window,int api)4184 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
~WindowDisconnector()4185 ~WindowDisconnector() {
4186 native_window_api_disconnect(mWindow, mApi);
4187 }
4188
4189 private:
4190 ANativeWindow* mWindow;
4191 const int mApi;
4192 };
4193
getWindowBuffer(ANativeWindow * window,uint32_t requestedWidth,uint32_t requestedHeight,bool hasWideColorDisplay,bool renderEngineUsesWideColor,ANativeWindowBuffer ** outBuffer)4194 static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4195 uint32_t requestedHeight, bool hasWideColorDisplay,
4196 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4197 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4198 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4199
4200 int err = 0;
4201 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4202 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4203 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4204 err |= native_window_set_usage(window, usage);
4205
4206 if (hasWideColorDisplay) {
4207 err |= native_window_set_buffers_data_space(window,
4208 renderEngineUsesWideColor
4209 ? HAL_DATASPACE_DISPLAY_P3
4210 : HAL_DATASPACE_V0_SRGB);
4211 }
4212
4213 if (err != NO_ERROR) {
4214 return BAD_VALUE;
4215 }
4216
4217 /* TODO: Once we have the sync framework everywhere this can use
4218 * server-side waits on the fence that dequeueBuffer returns.
4219 */
4220 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4221 if (err != NO_ERROR) {
4222 return err;
4223 }
4224
4225 return NO_ERROR;
4226 }
4227
captureScreen(const sp<IBinder> & display,const sp<IGraphicBufferProducer> & producer,Rect sourceCrop,uint32_t reqWidth,uint32_t reqHeight,int32_t minLayerZ,int32_t maxLayerZ,bool useIdentityTransform,ISurfaceComposer::Rotation rotation)4228 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4229 const sp<IGraphicBufferProducer>& producer,
4230 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4231 int32_t minLayerZ, int32_t maxLayerZ,
4232 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
4233 ATRACE_CALL();
4234
4235 if (CC_UNLIKELY(display == 0))
4236 return BAD_VALUE;
4237
4238 if (CC_UNLIKELY(producer == 0))
4239 return BAD_VALUE;
4240
4241 // if we have secure windows on this display, never allow the screen capture
4242 // unless the producer interface is local (i.e.: we can take a screenshot for
4243 // ourselves).
4244 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
4245
4246 // Convert to surfaceflinger's internal rotation type.
4247 Transform::orientation_flags rotationFlags;
4248 switch (rotation) {
4249 case ISurfaceComposer::eRotateNone:
4250 rotationFlags = Transform::ROT_0;
4251 break;
4252 case ISurfaceComposer::eRotate90:
4253 rotationFlags = Transform::ROT_90;
4254 break;
4255 case ISurfaceComposer::eRotate180:
4256 rotationFlags = Transform::ROT_180;
4257 break;
4258 case ISurfaceComposer::eRotate270:
4259 rotationFlags = Transform::ROT_270;
4260 break;
4261 default:
4262 rotationFlags = Transform::ROT_0;
4263 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4264 break;
4265 }
4266
4267 { // Autolock scope
4268 Mutex::Autolock lock(mStateLock);
4269 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4270 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
4271 }
4272
4273 // create a surface (because we're a producer, and we need to
4274 // dequeue/queue a buffer)
4275 sp<Surface> surface = new Surface(producer, false);
4276
4277 // Put the screenshot Surface into async mode so that
4278 // Layer::headFenceHasSignaled will always return true and we'll latch the
4279 // first buffer regardless of whether or not its acquire fence has
4280 // signaled. This is needed to avoid a race condition in the rotation
4281 // animation. See b/30209608
4282 surface->setAsyncMode(true);
4283
4284 ANativeWindow* window = surface.get();
4285
4286 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4287 if (result != NO_ERROR) {
4288 return result;
4289 }
4290 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4291
4292 ANativeWindowBuffer* buffer = nullptr;
4293 result = getWindowBuffer(window, reqWidth, reqHeight,
4294 hasWideColorDisplay && !mForceNativeColorMode,
4295 getRenderEngine().usesWideColor(), &buffer);
4296 if (result != NO_ERROR) {
4297 return result;
4298 }
4299
4300 // This mutex protects syncFd and captureResult for communication of the return values from the
4301 // main thread back to this Binder thread
4302 std::mutex captureMutex;
4303 std::condition_variable captureCondition;
4304 std::unique_lock<std::mutex> captureLock(captureMutex);
4305 int syncFd = -1;
4306 std::optional<status_t> captureResult;
4307
4308 sp<LambdaMessage> message = new LambdaMessage([&]() {
4309 // If there is a refresh pending, bug out early and tell the binder thread to try again
4310 // after the refresh.
4311 if (mRefreshPending) {
4312 ATRACE_NAME("Skipping screenshot for now");
4313 std::unique_lock<std::mutex> captureLock(captureMutex);
4314 captureResult = std::make_optional<status_t>(EAGAIN);
4315 captureCondition.notify_one();
4316 return;
4317 }
4318
4319 status_t result = NO_ERROR;
4320 int fd = -1;
4321 {
4322 Mutex::Autolock _l(mStateLock);
4323 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4324 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4325 minLayerZ, maxLayerZ, useIdentityTransform,
4326 rotationFlags, isLocalScreenshot, &fd);
4327 }
4328
4329 {
4330 std::unique_lock<std::mutex> captureLock(captureMutex);
4331 syncFd = fd;
4332 captureResult = std::make_optional<status_t>(result);
4333 captureCondition.notify_one();
4334 }
4335 });
4336
4337 result = postMessageAsync(message);
4338 if (result == NO_ERROR) {
4339 captureCondition.wait(captureLock, [&]() { return captureResult; });
4340 while (*captureResult == EAGAIN) {
4341 captureResult.reset();
4342 result = postMessageAsync(message);
4343 if (result != NO_ERROR) {
4344 return result;
4345 }
4346 captureCondition.wait(captureLock, [&]() { return captureResult; });
4347 }
4348 result = *captureResult;
4349 }
4350
4351 if (result == NO_ERROR) {
4352 // queueBuffer takes ownership of syncFd
4353 result = window->queueBuffer(window, buffer, syncFd);
4354 }
4355
4356 return result;
4357 }
4358
4359
renderScreenImplLocked(const sp<const DisplayDevice> & hw,Rect sourceCrop,uint32_t reqWidth,uint32_t reqHeight,int32_t minLayerZ,int32_t maxLayerZ,bool yswap,bool useIdentityTransform,Transform::orientation_flags rotation)4360 void SurfaceFlinger::renderScreenImplLocked(
4361 const sp<const DisplayDevice>& hw,
4362 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4363 int32_t minLayerZ, int32_t maxLayerZ,
4364 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
4365 {
4366 ATRACE_CALL();
4367 RenderEngine& engine(getRenderEngine());
4368
4369 // get screen geometry
4370 const int32_t hw_w = hw->getWidth();
4371 const int32_t hw_h = hw->getHeight();
4372 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
4373 static_cast<int32_t>(reqHeight) != hw_h;
4374
4375 // if a default or invalid sourceCrop is passed in, set reasonable values
4376 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4377 !sourceCrop.isValid()) {
4378 sourceCrop.setLeftTop(Point(0, 0));
4379 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4380 }
4381
4382 // ensure that sourceCrop is inside screen
4383 if (sourceCrop.left < 0) {
4384 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4385 }
4386 if (sourceCrop.right > hw_w) {
4387 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
4388 }
4389 if (sourceCrop.top < 0) {
4390 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4391 }
4392 if (sourceCrop.bottom > hw_h) {
4393 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
4394 }
4395
4396 #ifdef USE_HWC2
4397 engine.setWideColor(hw->getWideColorSupport() && !mForceNativeColorMode);
4398 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : hw->getActiveColorMode());
4399 #endif
4400
4401 // make sure to clear all GL error flags
4402 engine.checkErrors();
4403
4404 // set-up our viewport
4405 engine.setViewportAndProjection(
4406 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
4407 engine.disableTexturing();
4408
4409 // redraw the screen entirely...
4410 engine.clearWithColor(0, 0, 0, 1);
4411
4412 // We loop through the first level of layers without traversing,
4413 // as we need to interpret min/max layer Z in the top level Z space.
4414 for (const auto& layer : mDrawingState.layersSortedByZ) {
4415 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4416 continue;
4417 }
4418 const Layer::State& state(layer->getDrawingState());
4419 if (state.z < minLayerZ || state.z > maxLayerZ) {
4420 continue;
4421 }
4422 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4423 if (!layer->isVisible()) {
4424 return;
4425 }
4426 if (filtering) layer->setFiltering(true);
4427 layer->draw(hw, useIdentityTransform);
4428 if (filtering) layer->setFiltering(false);
4429 });
4430 }
4431
4432 hw->setViewportAndProjection();
4433 }
4434
4435 // A simple RAII class that holds an EGLImage and destroys it either:
4436 // a) When the destroy() method is called
4437 // b) When the object goes out of scope
4438 class ImageHolder {
4439 public:
ImageHolder(EGLDisplay display,EGLImageKHR image)4440 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
~ImageHolder()4441 ~ImageHolder() { destroy(); }
4442
destroy()4443 void destroy() {
4444 if (mImage != EGL_NO_IMAGE_KHR) {
4445 eglDestroyImageKHR(mDisplay, mImage);
4446 mImage = EGL_NO_IMAGE_KHR;
4447 }
4448 }
4449
4450 private:
4451 const EGLDisplay mDisplay;
4452 EGLImageKHR mImage;
4453 };
4454
captureScreenImplLocked(const sp<const DisplayDevice> & hw,ANativeWindowBuffer * buffer,Rect sourceCrop,uint32_t reqWidth,uint32_t reqHeight,int32_t minLayerZ,int32_t maxLayerZ,bool useIdentityTransform,Transform::orientation_flags rotation,bool isLocalScreenshot,int * outSyncFd)4455 status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4456 ANativeWindowBuffer* buffer, Rect sourceCrop,
4457 uint32_t reqWidth, uint32_t reqHeight,
4458 int32_t minLayerZ, int32_t maxLayerZ,
4459 bool useIdentityTransform,
4460 Transform::orientation_flags rotation,
4461 bool isLocalScreenshot, int* outSyncFd) {
4462 ATRACE_CALL();
4463
4464 bool secureLayerIsVisible = false;
4465 for (const auto& layer : mDrawingState.layersSortedByZ) {
4466 const Layer::State& state(layer->getDrawingState());
4467 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
4468 (state.z < minLayerZ || state.z > maxLayerZ)) {
4469 continue;
4470 }
4471 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
4472 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4473 layer->isSecure());
4474 });
4475 }
4476
4477 if (!isLocalScreenshot && secureLayerIsVisible) {
4478 ALOGW("FB is protected: PERMISSION_DENIED");
4479 return PERMISSION_DENIED;
4480 }
4481
4482 int syncFd = -1;
4483 // create an EGLImage from the buffer so we can later
4484 // turn it into a texture
4485 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4486 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4487 if (image == EGL_NO_IMAGE_KHR) {
4488 return BAD_VALUE;
4489 }
4490
4491 // This will automatically destroy the image if we return before calling its destroy method
4492 ImageHolder imageHolder(mEGLDisplay, image);
4493
4494 // this binds the given EGLImage as a framebuffer for the
4495 // duration of this scope.
4496 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4497 if (imageBond.getStatus() != NO_ERROR) {
4498 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4499 return INVALID_OPERATION;
4500 }
4501
4502 // this will in fact render into our dequeued buffer
4503 // via an FBO, which means we didn't have to create
4504 // an EGLSurface and therefore we're not
4505 // dependent on the context's EGLConfig.
4506 renderScreenImplLocked(
4507 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4508 useIdentityTransform, rotation);
4509
4510 // Attempt to create a sync khr object that can produce a sync point. If that
4511 // isn't available, create a non-dupable sync object in the fallback path and
4512 // wait on it directly.
4513 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4514 if (!DEBUG_SCREENSHOTS) {
4515 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4516 // native fence fd will not be populated until flush() is done.
4517 getRenderEngine().flush();
4518 }
4519
4520 if (sync != EGL_NO_SYNC_KHR) {
4521 // get the sync fd
4522 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4523 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4524 ALOGW("captureScreen: failed to dup sync khr object");
4525 syncFd = -1;
4526 }
4527 eglDestroySyncKHR(mEGLDisplay, sync);
4528 } else {
4529 // fallback path
4530 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4531 if (sync != EGL_NO_SYNC_KHR) {
4532 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4533 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4534 EGLint eglErr = eglGetError();
4535 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4536 ALOGW("captureScreen: fence wait timed out");
4537 } else {
4538 ALOGW_IF(eglErr != EGL_SUCCESS,
4539 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4540 }
4541 eglDestroySyncKHR(mEGLDisplay, sync);
4542 } else {
4543 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4544 }
4545 }
4546 *outSyncFd = syncFd;
4547
4548 if (DEBUG_SCREENSHOTS) {
4549 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4550 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4551 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4552 hw, minLayerZ, maxLayerZ);
4553 delete [] pixels;
4554 }
4555
4556 // destroy our image
4557 imageHolder.destroy();
4558
4559 return NO_ERROR;
4560 }
4561
checkScreenshot(size_t w,size_t s,size_t h,void const * vaddr,const sp<const DisplayDevice> & hw,int32_t minLayerZ,int32_t maxLayerZ)4562 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
4563 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
4564 if (DEBUG_SCREENSHOTS) {
4565 for (size_t y=0 ; y<h ; y++) {
4566 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4567 for (size_t x=0 ; x<w ; x++) {
4568 if (p[x] != 0xFF000000) return;
4569 }
4570 }
4571 ALOGE("*** we just took a black screenshot ***\n"
4572 "requested minz=%d, maxz=%d, layerStack=%d",
4573 minLayerZ, maxLayerZ, hw->getLayerStack());
4574
4575 size_t i = 0;
4576 for (const auto& layer : mDrawingState.layersSortedByZ) {
4577 const Layer::State& state(layer->getDrawingState());
4578 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
4579 state.z <= maxLayerZ) {
4580 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4581 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4582 layer->isVisible() ? '+' : '-',
4583 i, layer->getName().string(), layer->getLayerStack(), state.z,
4584 layer->isVisible(), state.flags, state.alpha);
4585 i++;
4586 });
4587 }
4588 }
4589 }
4590 }
4591
4592 // ---------------------------------------------------------------------------
4593
traverseInZOrder(const LayerVector::Visitor & visitor) const4594 void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4595 layersSortedByZ.traverseInZOrder(stateSet, visitor);
4596 }
4597
traverseInReverseZOrder(const LayerVector::Visitor & visitor) const4598 void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4599 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
4600 }
4601
4602 }; // namespace android
4603
4604
4605 #if defined(__gl_h_)
4606 #error "don't include gl/gl.h in this file"
4607 #endif
4608
4609 #if defined(__gl2_h_)
4610 #error "don't include gl2/gl2.h in this file"
4611 #endif
4612