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