OSDN Git Service

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