OSDN Git Service

SF: Force empty sync transactions to apply anyway
[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 a synchronous transaction is explicitly requested without any changes,
2169     // force a transaction anyway. This can be used as a flush mechanism for
2170     // previous async transactions.
2171     if (transactionFlags == 0 && (flags & eSynchronous)) {
2172         transactionFlags = eTransactionNeeded;
2173     }
2174
2175     if (transactionFlags) {
2176         // this triggers the transaction
2177         setTransactionFlags(transactionFlags);
2178
2179         // if this is a synchronous transaction, wait for it to take effect
2180         // before returning.
2181         if (flags & eSynchronous) {
2182             mTransactionPending = true;
2183         }
2184         if (flags & eAnimation) {
2185             mAnimTransactionPending = true;
2186         }
2187         while (mTransactionPending) {
2188             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2189             if (CC_UNLIKELY(err != NO_ERROR)) {
2190                 // just in case something goes wrong in SF, return to the
2191                 // called after a few seconds.
2192                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2193                 mTransactionPending = false;
2194                 break;
2195             }
2196         }
2197     }
2198 }
2199
2200 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2201 {
2202     ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2203     if (dpyIdx < 0)
2204         return 0;
2205
2206     uint32_t flags = 0;
2207     DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2208     if (disp.isValid()) {
2209         const uint32_t what = s.what;
2210         if (what & DisplayState::eSurfaceChanged) {
2211             if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2212                 disp.surface = s.surface;
2213                 flags |= eDisplayTransactionNeeded;
2214             }
2215         }
2216         if (what & DisplayState::eLayerStackChanged) {
2217             if (disp.layerStack != s.layerStack) {
2218                 disp.layerStack = s.layerStack;
2219                 flags |= eDisplayTransactionNeeded;
2220             }
2221         }
2222         if (what & DisplayState::eDisplayProjectionChanged) {
2223             if (disp.orientation != s.orientation) {
2224                 disp.orientation = s.orientation;
2225                 flags |= eDisplayTransactionNeeded;
2226             }
2227             if (disp.frame != s.frame) {
2228                 disp.frame = s.frame;
2229                 flags |= eDisplayTransactionNeeded;
2230             }
2231             if (disp.viewport != s.viewport) {
2232                 disp.viewport = s.viewport;
2233                 flags |= eDisplayTransactionNeeded;
2234             }
2235         }
2236         if (what & DisplayState::eDisplaySizeChanged) {
2237             if (disp.width != s.width) {
2238                 disp.width = s.width;
2239                 flags |= eDisplayTransactionNeeded;
2240             }
2241             if (disp.height != s.height) {
2242                 disp.height = s.height;
2243                 flags |= eDisplayTransactionNeeded;
2244             }
2245         }
2246     }
2247     return flags;
2248 }
2249
2250 uint32_t SurfaceFlinger::setClientStateLocked(
2251         const sp<Client>& client,
2252         const layer_state_t& s)
2253 {
2254     uint32_t flags = 0;
2255     sp<Layer> layer(client->getLayerUser(s.surface));
2256     if (layer != 0) {
2257         const uint32_t what = s.what;
2258         if (what & layer_state_t::ePositionChanged) {
2259             if (layer->setPosition(s.x, s.y))
2260                 flags |= eTraversalNeeded;
2261         }
2262         if (what & layer_state_t::eLayerChanged) {
2263             // NOTE: index needs to be calculated before we update the state
2264             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2265             if (layer->setLayer(s.z) && idx >= 0) {
2266                 mCurrentState.layersSortedByZ.removeAt(idx);
2267                 mCurrentState.layersSortedByZ.add(layer);
2268                 // we need traversal (state changed)
2269                 // AND transaction (list changed)
2270                 flags |= eTransactionNeeded|eTraversalNeeded;
2271             }
2272         }
2273         if (what & layer_state_t::eSizeChanged) {
2274             if (layer->setSize(s.w, s.h)) {
2275                 flags |= eTraversalNeeded;
2276             }
2277         }
2278         if (what & layer_state_t::eAlphaChanged) {
2279             if (layer->setAlpha(s.alpha))
2280                 flags |= eTraversalNeeded;
2281         }
2282         if (what & layer_state_t::eMatrixChanged) {
2283             if (layer->setMatrix(s.matrix))
2284                 flags |= eTraversalNeeded;
2285         }
2286         if (what & layer_state_t::eTransparentRegionChanged) {
2287             if (layer->setTransparentRegionHint(s.transparentRegion))
2288                 flags |= eTraversalNeeded;
2289         }
2290         if (what & layer_state_t::eFlagsChanged) {
2291             if (layer->setFlags(s.flags, s.mask))
2292                 flags |= eTraversalNeeded;
2293         }
2294         if (what & layer_state_t::eCropChanged) {
2295             if (layer->setCrop(s.crop))
2296                 flags |= eTraversalNeeded;
2297         }
2298         if (what & layer_state_t::eFinalCropChanged) {
2299             if (layer->setFinalCrop(s.finalCrop))
2300                 flags |= eTraversalNeeded;
2301         }
2302         if (what & layer_state_t::eLayerStackChanged) {
2303             // NOTE: index needs to be calculated before we update the state
2304             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2305             if (layer->setLayerStack(s.layerStack) && idx >= 0) {
2306                 mCurrentState.layersSortedByZ.removeAt(idx);
2307                 mCurrentState.layersSortedByZ.add(layer);
2308                 // we need traversal (state changed)
2309                 // AND transaction (list changed)
2310                 flags |= eTransactionNeeded|eTraversalNeeded;
2311             }
2312         }
2313         if (what & layer_state_t::eDeferTransaction) {
2314             layer->deferTransactionUntil(s.handle, s.frameNumber);
2315             // We don't trigger a traversal here because if no other state is
2316             // changed, we don't want this to cause any more work
2317         }
2318         if (what & layer_state_t::eOverrideScalingModeChanged) {
2319             layer->setOverrideScalingMode(s.overrideScalingMode);
2320             // We don't trigger a traversal here because if no other state is
2321             // changed, we don't want this to cause any more work
2322         }
2323     }
2324     return flags;
2325 }
2326
2327 status_t SurfaceFlinger::createLayer(
2328         const String8& name,
2329         const sp<Client>& client,
2330         uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2331         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2332 {
2333     //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2334     if (int32_t(w|h) < 0) {
2335         ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2336                 int(w), int(h));
2337         return BAD_VALUE;
2338     }
2339
2340     status_t result = NO_ERROR;
2341
2342     sp<Layer> layer;
2343
2344     switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2345         case ISurfaceComposerClient::eFXSurfaceNormal:
2346             result = createNormalLayer(client,
2347                     name, w, h, flags, format,
2348                     handle, gbp, &layer);
2349             break;
2350         case ISurfaceComposerClient::eFXSurfaceDim:
2351             result = createDimLayer(client,
2352                     name, w, h, flags,
2353                     handle, gbp, &layer);
2354             break;
2355         default:
2356             result = BAD_VALUE;
2357             break;
2358     }
2359
2360     if (result != NO_ERROR) {
2361         return result;
2362     }
2363
2364     result = addClientLayer(client, *handle, *gbp, layer);
2365     if (result != NO_ERROR) {
2366         return result;
2367     }
2368
2369     setTransactionFlags(eTransactionNeeded);
2370     return result;
2371 }
2372
2373 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2374         const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2375         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2376 {
2377     // initialize the surfaces
2378     switch (format) {
2379     case PIXEL_FORMAT_TRANSPARENT:
2380     case PIXEL_FORMAT_TRANSLUCENT:
2381         format = PIXEL_FORMAT_RGBA_8888;
2382         break;
2383     case PIXEL_FORMAT_OPAQUE:
2384         format = PIXEL_FORMAT_RGBX_8888;
2385         break;
2386     }
2387
2388     *outLayer = new Layer(this, client, name, w, h, flags);
2389     status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2390     if (err == NO_ERROR) {
2391         *handle = (*outLayer)->getHandle();
2392         *gbp = (*outLayer)->getProducer();
2393     }
2394
2395     ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2396     return err;
2397 }
2398
2399 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2400         const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2401         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2402 {
2403     *outLayer = new LayerDim(this, client, name, w, h, flags);
2404     *handle = (*outLayer)->getHandle();
2405     *gbp = (*outLayer)->getProducer();
2406     return NO_ERROR;
2407 }
2408
2409 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2410 {
2411     // called by the window manager when it wants to remove a Layer
2412     status_t err = NO_ERROR;
2413     sp<Layer> l(client->getLayerUser(handle));
2414     if (l != NULL) {
2415         err = removeLayer(l);
2416         ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2417                 "error removing layer=%p (%s)", l.get(), strerror(-err));
2418     }
2419     return err;
2420 }
2421
2422 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2423 {
2424     // called by ~LayerCleaner() when all references to the IBinder (handle)
2425     // are gone
2426     status_t err = NO_ERROR;
2427     sp<Layer> l(layer.promote());
2428     if (l != NULL) {
2429         err = removeLayer(l);
2430         ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2431                 "error removing layer=%p (%s)", l.get(), strerror(-err));
2432     }
2433     return err;
2434 }
2435
2436 // ---------------------------------------------------------------------------
2437
2438 void SurfaceFlinger::onInitializeDisplays() {
2439     // reset screen orientation and use primary layer stack
2440     Vector<ComposerState> state;
2441     Vector<DisplayState> displays;
2442     DisplayState d;
2443     d.what = DisplayState::eDisplayProjectionChanged |
2444              DisplayState::eLayerStackChanged;
2445     d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2446     d.layerStack = 0;
2447     d.orientation = DisplayState::eOrientationDefault;
2448     d.frame.makeInvalid();
2449     d.viewport.makeInvalid();
2450     d.width = 0;
2451     d.height = 0;
2452     displays.add(d);
2453     setTransactionState(state, displays, 0);
2454     setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2455
2456     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2457     const nsecs_t period = activeConfig->getVsyncPeriod();
2458     mAnimFrameTracker.setDisplayRefreshPeriod(period);
2459 }
2460
2461 void SurfaceFlinger::initializeDisplays() {
2462     class MessageScreenInitialized : public MessageBase {
2463         SurfaceFlinger* flinger;
2464     public:
2465         MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2466         virtual bool handler() {
2467             flinger->onInitializeDisplays();
2468             return true;
2469         }
2470     };
2471     sp<MessageBase> msg = new MessageScreenInitialized(this);
2472     postMessageAsync(msg);  // we may be called from main thread, use async message
2473 }
2474
2475 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2476         int mode) {
2477     ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2478             this);
2479     int32_t type = hw->getDisplayType();
2480     int currentMode = hw->getPowerMode();
2481
2482     if (mode == currentMode) {
2483         ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2484         return;
2485     }
2486
2487     hw->setPowerMode(mode);
2488     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2489         ALOGW("Trying to set power mode for virtual display");
2490         return;
2491     }
2492
2493     if (currentMode == HWC_POWER_MODE_OFF) {
2494         getHwComposer().setPowerMode(type, mode);
2495         if (type == DisplayDevice::DISPLAY_PRIMARY) {
2496             // FIXME: eventthread only knows about the main display right now
2497             mEventThread->onScreenAcquired();
2498             resyncToHardwareVsync(true);
2499         }
2500
2501         mVisibleRegionsDirty = true;
2502         mHasPoweredOff = true;
2503         repaintEverything();
2504     } else if (mode == HWC_POWER_MODE_OFF) {
2505         if (type == DisplayDevice::DISPLAY_PRIMARY) {
2506             disableHardwareVsync(true); // also cancels any in-progress resync
2507
2508             // FIXME: eventthread only knows about the main display right now
2509             mEventThread->onScreenReleased();
2510         }
2511
2512         getHwComposer().setPowerMode(type, mode);
2513         mVisibleRegionsDirty = true;
2514         // from this point on, SF will stop drawing on this display
2515     } else {
2516         getHwComposer().setPowerMode(type, mode);
2517     }
2518 }
2519
2520 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2521     class MessageSetPowerMode: public MessageBase {
2522         SurfaceFlinger& mFlinger;
2523         sp<IBinder> mDisplay;
2524         int mMode;
2525     public:
2526         MessageSetPowerMode(SurfaceFlinger& flinger,
2527                 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2528                     mDisplay(disp) { mMode = mode; }
2529         virtual bool handler() {
2530             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2531             if (hw == NULL) {
2532                 ALOGE("Attempt to set power mode = %d for null display %p",
2533                         mMode, mDisplay.get());
2534             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2535                 ALOGW("Attempt to set power mode = %d for virtual display",
2536                         mMode);
2537             } else {
2538                 mFlinger.setPowerModeInternal(hw, mMode);
2539             }
2540             return true;
2541         }
2542     };
2543     sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2544     postMessageSync(msg);
2545 }
2546
2547 // ---------------------------------------------------------------------------
2548
2549 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2550 {
2551     String8 result;
2552
2553     IPCThreadState* ipc = IPCThreadState::self();
2554     const int pid = ipc->getCallingPid();
2555     const int uid = ipc->getCallingUid();
2556     if ((uid != AID_SHELL) &&
2557             !PermissionCache::checkPermission(sDump, pid, uid)) {
2558         result.appendFormat("Permission Denial: "
2559                 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2560     } else {
2561         // Try to get the main lock, but give up after one second
2562         // (this would indicate SF is stuck, but we want to be able to
2563         // print something in dumpsys).
2564         status_t err = mStateLock.timedLock(s2ns(1));
2565         bool locked = (err == NO_ERROR);
2566         if (!locked) {
2567             result.appendFormat(
2568                     "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2569                     "dumping anyways (no locks held)\n", strerror(-err), err);
2570         }
2571
2572         bool dumpAll = true;
2573         size_t index = 0;
2574         size_t numArgs = args.size();
2575         if (numArgs) {
2576             if ((index < numArgs) &&
2577                     (args[index] == String16("--list"))) {
2578                 index++;
2579                 listLayersLocked(args, index, result);
2580                 dumpAll = false;
2581             }
2582
2583             if ((index < numArgs) &&
2584                     (args[index] == String16("--latency"))) {
2585                 index++;
2586                 dumpStatsLocked(args, index, result);
2587                 dumpAll = false;
2588             }
2589
2590             if ((index < numArgs) &&
2591                     (args[index] == String16("--latency-clear"))) {
2592                 index++;
2593                 clearStatsLocked(args, index, result);
2594                 dumpAll = false;
2595             }
2596
2597             if ((index < numArgs) &&
2598                     (args[index] == String16("--dispsync"))) {
2599                 index++;
2600                 mPrimaryDispSync.dump(result);
2601                 dumpAll = false;
2602             }
2603
2604             if ((index < numArgs) &&
2605                     (args[index] == String16("--static-screen"))) {
2606                 index++;
2607                 dumpStaticScreenStats(result);
2608                 dumpAll = false;
2609             }
2610
2611 #ifdef ENABLE_FENCE_TRACKING
2612             if ((index < numArgs) &&
2613                     (args[index] == String16("--fences"))) {
2614                 index++;
2615                 mFenceTracker.dump(&result);
2616                 dumpAll = false;
2617             }
2618 #endif
2619         }
2620
2621         if (dumpAll) {
2622             dumpAllLocked(args, index, result);
2623         }
2624
2625         if (locked) {
2626             mStateLock.unlock();
2627         }
2628     }
2629     write(fd, result.string(), result.size());
2630     return NO_ERROR;
2631 }
2632
2633 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2634         size_t& /* index */, String8& result) const
2635 {
2636     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2637     const size_t count = currentLayers.size();
2638     for (size_t i=0 ; i<count ; i++) {
2639         const sp<Layer>& layer(currentLayers[i]);
2640         result.appendFormat("%s\n", layer->getName().string());
2641     }
2642 }
2643
2644 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2645         String8& result) const
2646 {
2647     String8 name;
2648     if (index < args.size()) {
2649         name = String8(args[index]);
2650         index++;
2651     }
2652
2653     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2654     const nsecs_t period = activeConfig->getVsyncPeriod();
2655     result.appendFormat("%" PRId64 "\n", period);
2656
2657     if (name.isEmpty()) {
2658         mAnimFrameTracker.dumpStats(result);
2659     } else {
2660         const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2661         const size_t count = currentLayers.size();
2662         for (size_t i=0 ; i<count ; i++) {
2663             const sp<Layer>& layer(currentLayers[i]);
2664             if (name == layer->getName()) {
2665                 layer->dumpFrameStats(result);
2666             }
2667         }
2668     }
2669 }
2670
2671 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2672         String8& /* result */)
2673 {
2674     String8 name;
2675     if (index < args.size()) {
2676         name = String8(args[index]);
2677         index++;
2678     }
2679
2680     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2681     const size_t count = currentLayers.size();
2682     for (size_t i=0 ; i<count ; i++) {
2683         const sp<Layer>& layer(currentLayers[i]);
2684         if (name.isEmpty() || (name == layer->getName())) {
2685             layer->clearFrameStats();
2686         }
2687     }
2688
2689     mAnimFrameTracker.clearStats();
2690 }
2691
2692 // This should only be called from the main thread.  Otherwise it would need
2693 // the lock and should use mCurrentState rather than mDrawingState.
2694 void SurfaceFlinger::logFrameStats() {
2695     const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2696     const size_t count = drawingLayers.size();
2697     for (size_t i=0 ; i<count ; i++) {
2698         const sp<Layer>& layer(drawingLayers[i]);
2699         layer->logFrameStats();
2700     }
2701
2702     mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2703 }
2704
2705 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2706 {
2707     static const char* config =
2708             " [sf"
2709 #ifdef HAS_CONTEXT_PRIORITY
2710             " HAS_CONTEXT_PRIORITY"
2711 #endif
2712 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2713             " NEVER_DEFAULT_TO_ASYNC_MODE"
2714 #endif
2715 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2716             " TARGET_DISABLE_TRIPLE_BUFFERING"
2717 #endif
2718             "]";
2719     result.append(config);
2720 }
2721
2722 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2723 {
2724     result.appendFormat("Static screen stats:\n");
2725     for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2726         float bucketTimeSec = mFrameBuckets[b] / 1e9;
2727         float percent = 100.0f *
2728                 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2729         result.appendFormat("  < %zd frames: %.3f s (%.1f%%)\n",
2730                 b + 1, bucketTimeSec, percent);
2731     }
2732     float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2733     float percent = 100.0f *
2734             static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2735     result.appendFormat("  %zd+ frames: %.3f s (%.1f%%)\n",
2736             NUM_BUCKETS - 1, bucketTimeSec, percent);
2737 }
2738
2739 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2740         String8& result) const
2741 {
2742     bool colorize = false;
2743     if (index < args.size()
2744             && (args[index] == String16("--color"))) {
2745         colorize = true;
2746         index++;
2747     }
2748
2749     Colorizer colorizer(colorize);
2750
2751     // figure out if we're stuck somewhere
2752     const nsecs_t now = systemTime();
2753     const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2754     const nsecs_t inTransaction(mDebugInTransaction);
2755     nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2756     nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2757
2758     /*
2759      * Dump library configuration.
2760      */
2761
2762     colorizer.bold(result);
2763     result.append("Build configuration:");
2764     colorizer.reset(result);
2765     appendSfConfigString(result);
2766     appendUiConfigString(result);
2767     appendGuiConfigString(result);
2768     result.append("\n");
2769
2770     colorizer.bold(result);
2771     result.append("Sync configuration: ");
2772     colorizer.reset(result);
2773     result.append(SyncFeatures::getInstance().toString());
2774     result.append("\n");
2775
2776     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2777
2778     colorizer.bold(result);
2779     result.append("DispSync configuration: ");
2780     colorizer.reset(result);
2781     result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2782             "present offset %d ns (refresh %" PRId64 " ns)",
2783         vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2784         PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
2785     result.append("\n");
2786
2787     // Dump static screen stats
2788     result.append("\n");
2789     dumpStaticScreenStats(result);
2790     result.append("\n");
2791
2792     /*
2793      * Dump the visible layer list
2794      */
2795     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2796     const size_t count = currentLayers.size();
2797     colorizer.bold(result);
2798     result.appendFormat("Visible layers (count = %zu)\n", count);
2799     colorizer.reset(result);
2800     for (size_t i=0 ; i<count ; i++) {
2801         const sp<Layer>& layer(currentLayers[i]);
2802         layer->dump(result, colorizer);
2803     }
2804
2805     /*
2806      * Dump Display state
2807      */
2808
2809     colorizer.bold(result);
2810     result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2811     colorizer.reset(result);
2812     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2813         const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2814         hw->dump(result);
2815     }
2816
2817     /*
2818      * Dump SurfaceFlinger global state
2819      */
2820
2821     colorizer.bold(result);
2822     result.append("SurfaceFlinger global state:\n");
2823     colorizer.reset(result);
2824
2825     HWComposer& hwc(getHwComposer());
2826     sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2827
2828     colorizer.bold(result);
2829     result.appendFormat("EGL implementation : %s\n",
2830             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2831     colorizer.reset(result);
2832     result.appendFormat("%s\n",
2833             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2834
2835     mRenderEngine->dump(result);
2836
2837     hw->undefinedRegion.dump(result, "undefinedRegion");
2838     result.appendFormat("  orientation=%d, isDisplayOn=%d\n",
2839             hw->getOrientation(), hw->isDisplayOn());
2840     result.appendFormat(
2841             "  last eglSwapBuffers() time: %f us\n"
2842             "  last transaction time     : %f us\n"
2843             "  transaction-flags         : %08x\n"
2844             "  refresh-rate              : %f fps\n"
2845             "  x-dpi                     : %f\n"
2846             "  y-dpi                     : %f\n"
2847             "  gpu_to_cpu_unsupported    : %d\n"
2848             ,
2849             mLastSwapBufferTime/1000.0,
2850             mLastTransactionTime/1000.0,
2851             mTransactionFlags,
2852             1e9 / activeConfig->getVsyncPeriod(),
2853             activeConfig->getDpiX(),
2854             activeConfig->getDpiY(),
2855             !mGpuToCpuSupported);
2856
2857     result.appendFormat("  eglSwapBuffers time: %f us\n",
2858             inSwapBuffersDuration/1000.0);
2859
2860     result.appendFormat("  transaction time: %f us\n",
2861             inTransactionDuration/1000.0);
2862
2863     /*
2864      * VSYNC state
2865      */
2866     mEventThread->dump(result);
2867
2868     /*
2869      * Dump HWComposer state
2870      */
2871     colorizer.bold(result);
2872     result.append("h/w composer state:\n");
2873     colorizer.reset(result);
2874     bool hwcDisabled = mDebugDisableHWC || mDebugRegion || mDaltonize ||
2875             mHasColorMatrix;
2876     result.appendFormat("  h/w composer %s\n",
2877             hwcDisabled ? "disabled" : "enabled");
2878     hwc.dump(result);
2879
2880     /*
2881      * Dump gralloc state
2882      */
2883     const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2884     alloc.dump(result);
2885 }
2886
2887 const Vector< sp<Layer> >&
2888 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2889     // Note: mStateLock is held here
2890     wp<IBinder> dpy;
2891     for (size_t i=0 ; i<mDisplays.size() ; i++) {
2892         if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2893             dpy = mDisplays.keyAt(i);
2894             break;
2895         }
2896     }
2897     if (dpy == NULL) {
2898         ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2899         // Just use the primary display so we have something to return
2900         dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2901     }
2902     return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2903 }
2904
2905 bool SurfaceFlinger::startDdmConnection()
2906 {
2907     void* libddmconnection_dso =
2908             dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2909     if (!libddmconnection_dso) {
2910         return false;
2911     }
2912     void (*DdmConnection_start)(const char* name);
2913     DdmConnection_start =
2914             (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2915     if (!DdmConnection_start) {
2916         dlclose(libddmconnection_dso);
2917         return false;
2918     }
2919     (*DdmConnection_start)(getServiceName());
2920     return true;
2921 }
2922
2923 status_t SurfaceFlinger::onTransact(
2924     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2925 {
2926     switch (code) {
2927         case CREATE_CONNECTION:
2928         case CREATE_DISPLAY:
2929         case SET_TRANSACTION_STATE:
2930         case BOOT_FINISHED:
2931         case CLEAR_ANIMATION_FRAME_STATS:
2932         case GET_ANIMATION_FRAME_STATS:
2933         case SET_POWER_MODE:
2934         case GET_HDR_CAPABILITIES:
2935         {
2936             // codes that require permission check
2937             IPCThreadState* ipc = IPCThreadState::self();
2938             const int pid = ipc->getCallingPid();
2939             const int uid = ipc->getCallingUid();
2940             if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
2941                     !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2942                 ALOGE("Permission Denial: "
2943                         "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2944                 return PERMISSION_DENIED;
2945             }
2946             break;
2947         }
2948         case CAPTURE_SCREEN:
2949         {
2950             // codes that require permission check
2951             IPCThreadState* ipc = IPCThreadState::self();
2952             const int pid = ipc->getCallingPid();
2953             const int uid = ipc->getCallingUid();
2954             if ((uid != AID_GRAPHICS) &&
2955                     !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2956                 ALOGE("Permission Denial: "
2957                         "can't read framebuffer pid=%d, uid=%d", pid, uid);
2958                 return PERMISSION_DENIED;
2959             }
2960             break;
2961         }
2962     }
2963
2964     status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2965     if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2966         CHECK_INTERFACE(ISurfaceComposer, data, reply);
2967         if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2968             IPCThreadState* ipc = IPCThreadState::self();
2969             const int pid = ipc->getCallingPid();
2970             const int uid = ipc->getCallingUid();
2971             ALOGE("Permission Denial: "
2972                     "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2973             return PERMISSION_DENIED;
2974         }
2975         int n;
2976         switch (code) {
2977             case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2978             case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2979                 return NO_ERROR;
2980             case 1002:  // SHOW_UPDATES
2981                 n = data.readInt32();
2982                 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2983                 invalidateHwcGeometry();
2984                 repaintEverything();
2985                 return NO_ERROR;
2986             case 1004:{ // repaint everything
2987                 repaintEverything();
2988                 return NO_ERROR;
2989             }
2990             case 1005:{ // force transaction
2991                 setTransactionFlags(
2992                         eTransactionNeeded|
2993                         eDisplayTransactionNeeded|
2994                         eTraversalNeeded);
2995                 return NO_ERROR;
2996             }
2997             case 1006:{ // send empty update
2998                 signalRefresh();
2999                 return NO_ERROR;
3000             }
3001             case 1008:  // toggle use of hw composer
3002                 n = data.readInt32();
3003                 mDebugDisableHWC = n ? 1 : 0;
3004                 invalidateHwcGeometry();
3005                 repaintEverything();
3006                 return NO_ERROR;
3007             case 1009:  // toggle use of transform hint
3008                 n = data.readInt32();
3009                 mDebugDisableTransformHint = n ? 1 : 0;
3010                 invalidateHwcGeometry();
3011                 repaintEverything();
3012                 return NO_ERROR;
3013             case 1010:  // interrogate.
3014                 reply->writeInt32(0);
3015                 reply->writeInt32(0);
3016                 reply->writeInt32(mDebugRegion);
3017                 reply->writeInt32(0);
3018                 reply->writeInt32(mDebugDisableHWC);
3019                 return NO_ERROR;
3020             case 1013: {
3021                 Mutex::Autolock _l(mStateLock);
3022                 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3023                 reply->writeInt32(hw->getPageFlipCount());
3024                 return NO_ERROR;
3025             }
3026             case 1014: {
3027                 // daltonize
3028                 n = data.readInt32();
3029                 switch (n % 10) {
3030                     case 1: mDaltonizer.setType(Daltonizer::protanomaly);   break;
3031                     case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3032                     case 3: mDaltonizer.setType(Daltonizer::tritanomaly);   break;
3033                 }
3034                 if (n >= 10) {
3035                     mDaltonizer.setMode(Daltonizer::correction);
3036                 } else {
3037                     mDaltonizer.setMode(Daltonizer::simulation);
3038                 }
3039                 mDaltonize = n > 0;
3040                 invalidateHwcGeometry();
3041                 repaintEverything();
3042                 return NO_ERROR;
3043             }
3044             case 1015: {
3045                 // apply a color matrix
3046                 n = data.readInt32();
3047                 mHasColorMatrix = n ? 1 : 0;
3048                 if (n) {
3049                     // color matrix is sent as mat3 matrix followed by vec3
3050                     // offset, then packed into a mat4 where the last row is
3051                     // the offset and extra values are 0
3052                     for (size_t i = 0 ; i < 4; i++) {
3053                       for (size_t j = 0; j < 4; j++) {
3054                           mColorMatrix[i][j] = data.readFloat();
3055                       }
3056                     }
3057                 } else {
3058                     mColorMatrix = mat4();
3059                 }
3060                 invalidateHwcGeometry();
3061                 repaintEverything();
3062                 return NO_ERROR;
3063             }
3064             // This is an experimental interface
3065             // Needs to be shifted to proper binder interface when we productize
3066             case 1016: {
3067                 n = data.readInt32();
3068                 mPrimaryDispSync.setRefreshSkipCount(n);
3069                 return NO_ERROR;
3070             }
3071             case 1017: {
3072                 n = data.readInt32();
3073                 mForceFullDamage = static_cast<bool>(n);
3074                 return NO_ERROR;
3075             }
3076             case 1018: { // Modify Choreographer's phase offset
3077                 n = data.readInt32();
3078                 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3079                 return NO_ERROR;
3080             }
3081             case 1019: { // Modify SurfaceFlinger's phase offset
3082                 n = data.readInt32();
3083                 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3084                 return NO_ERROR;
3085             }
3086         }
3087     }
3088     return err;
3089 }
3090
3091 void SurfaceFlinger::repaintEverything() {
3092     android_atomic_or(1, &mRepaintEverything);
3093     signalTransaction();
3094 }
3095
3096 // ---------------------------------------------------------------------------
3097 // Capture screen into an IGraphiBufferProducer
3098 // ---------------------------------------------------------------------------
3099
3100 /* The code below is here to handle b/8734824
3101  *
3102  * We create a IGraphicBufferProducer wrapper that forwards all calls
3103  * from the surfaceflinger thread to the calling binder thread, where they
3104  * are executed. This allows the calling thread in the calling process to be
3105  * reused and not depend on having "enough" binder threads to handle the
3106  * requests.
3107  */
3108 class GraphicProducerWrapper : public BBinder, public MessageHandler {
3109     /* Parts of GraphicProducerWrapper are run on two different threads,
3110      * communicating by sending messages via Looper but also by shared member
3111      * data. Coherence maintenance is subtle and in places implicit (ugh).
3112      *
3113      * Don't rely on Looper's sendMessage/handleMessage providing
3114      * release/acquire semantics for any data not actually in the Message.
3115      * Data going from surfaceflinger to binder threads needs to be
3116      * synchronized explicitly.
3117      *
3118      * Barrier open/wait do provide release/acquire semantics. This provides
3119      * implicit synchronization for data coming back from binder to
3120      * surfaceflinger threads.
3121      */
3122
3123     sp<IGraphicBufferProducer> impl;
3124     sp<Looper> looper;
3125     status_t result;
3126     bool exitPending;
3127     bool exitRequested;
3128     Barrier barrier;
3129     uint32_t code;
3130     Parcel const* data;
3131     Parcel* reply;
3132
3133     enum {
3134         MSG_API_CALL,
3135         MSG_EXIT
3136     };
3137
3138     /*
3139      * Called on surfaceflinger thread. This is called by our "fake"
3140      * BpGraphicBufferProducer. We package the data and reply Parcel and
3141      * forward them to the binder thread.
3142      */
3143     virtual status_t transact(uint32_t code,
3144             const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3145         this->code = code;
3146         this->data = &data;
3147         this->reply = reply;
3148         if (exitPending) {
3149             // if we've exited, we run the message synchronously right here.
3150             // note (JH): as far as I can tell from looking at the code, this
3151             // never actually happens. if it does, i'm not sure if it happens
3152             // on the surfaceflinger or binder thread.
3153             handleMessage(Message(MSG_API_CALL));
3154         } else {
3155             barrier.close();
3156             // Prevent stores to this->{code, data, reply} from being
3157             // reordered later than the construction of Message.
3158             atomic_thread_fence(memory_order_release);
3159             looper->sendMessage(this, Message(MSG_API_CALL));
3160             barrier.wait();
3161         }
3162         return result;
3163     }
3164
3165     /*
3166      * here we run on the binder thread. All we've got to do is
3167      * call the real BpGraphicBufferProducer.
3168      */
3169     virtual void handleMessage(const Message& message) {
3170         int what = message.what;
3171         // Prevent reads below from happening before the read from Message
3172         atomic_thread_fence(memory_order_acquire);
3173         if (what == MSG_API_CALL) {
3174             result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3175             barrier.open();
3176         } else if (what == MSG_EXIT) {
3177             exitRequested = true;
3178         }
3179     }
3180
3181 public:
3182     GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3183     :   impl(impl),
3184         looper(new Looper(true)),
3185         result(NO_ERROR),
3186         exitPending(false),
3187         exitRequested(false),
3188         code(0),
3189         data(NULL),
3190         reply(NULL)
3191     {}
3192
3193     // Binder thread
3194     status_t waitForResponse() {
3195         do {
3196             looper->pollOnce(-1);
3197         } while (!exitRequested);
3198         return result;
3199     }
3200
3201     // Client thread
3202     void exit(status_t result) {
3203         this->result = result;
3204         exitPending = true;
3205         // Ensure this->result is visible to the binder thread before it
3206         // handles the message.
3207         atomic_thread_fence(memory_order_release);
3208         looper->sendMessage(this, Message(MSG_EXIT));
3209     }
3210 };
3211
3212
3213 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3214         const sp<IGraphicBufferProducer>& producer,
3215         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3216         uint32_t minLayerZ, uint32_t maxLayerZ,
3217         bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3218
3219     if (CC_UNLIKELY(display == 0))
3220         return BAD_VALUE;
3221
3222     if (CC_UNLIKELY(producer == 0))
3223         return BAD_VALUE;
3224
3225     // if we have secure windows on this display, never allow the screen capture
3226     // unless the producer interface is local (i.e.: we can take a screenshot for
3227     // ourselves).
3228     bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3229
3230     // Convert to surfaceflinger's internal rotation type.
3231     Transform::orientation_flags rotationFlags;
3232     switch (rotation) {
3233         case ISurfaceComposer::eRotateNone:
3234             rotationFlags = Transform::ROT_0;
3235             break;
3236         case ISurfaceComposer::eRotate90:
3237             rotationFlags = Transform::ROT_90;
3238             break;
3239         case ISurfaceComposer::eRotate180:
3240             rotationFlags = Transform::ROT_180;
3241             break;
3242         case ISurfaceComposer::eRotate270:
3243             rotationFlags = Transform::ROT_270;
3244             break;
3245         default:
3246             rotationFlags = Transform::ROT_0;
3247             ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3248             break;
3249     }
3250
3251     class MessageCaptureScreen : public MessageBase {
3252         SurfaceFlinger* flinger;
3253         sp<IBinder> display;
3254         sp<IGraphicBufferProducer> producer;
3255         Rect sourceCrop;
3256         uint32_t reqWidth, reqHeight;
3257         uint32_t minLayerZ,maxLayerZ;
3258         bool useIdentityTransform;
3259         Transform::orientation_flags rotation;
3260         status_t result;
3261         bool isLocalScreenshot;
3262     public:
3263         MessageCaptureScreen(SurfaceFlinger* flinger,
3264                 const sp<IBinder>& display,
3265                 const sp<IGraphicBufferProducer>& producer,
3266                 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3267                 uint32_t minLayerZ, uint32_t maxLayerZ,
3268                 bool useIdentityTransform,
3269                 Transform::orientation_flags rotation,
3270                 bool isLocalScreenshot)
3271             : flinger(flinger), display(display), producer(producer),
3272               sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3273               minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3274               useIdentityTransform(useIdentityTransform),
3275               rotation(rotation), result(PERMISSION_DENIED),
3276               isLocalScreenshot(isLocalScreenshot)
3277         {
3278         }
3279         status_t getResult() const {
3280             return result;
3281         }
3282         virtual bool handler() {
3283             Mutex::Autolock _l(flinger->mStateLock);
3284             sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3285             result = flinger->captureScreenImplLocked(hw, producer,
3286                     sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3287                     useIdentityTransform, rotation, isLocalScreenshot);
3288             static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3289             return true;
3290         }
3291     };
3292
3293     // make sure to process transactions before screenshots -- a transaction
3294     // might already be pending but scheduled for VSYNC; this guarantees we
3295     // will handle it before the screenshot. When VSYNC finally arrives
3296     // the scheduled transaction will be a no-op. If no transactions are
3297     // scheduled at this time, this will end-up being a no-op as well.
3298     mEventQueue.invalidateTransactionNow();
3299
3300     // this creates a "fake" BBinder which will serve as a "fake" remote
3301     // binder to receive the marshaled calls and forward them to the
3302     // real remote (a BpGraphicBufferProducer)
3303     sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3304
3305     // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3306     // which does the marshaling work forwards to our "fake remote" above.
3307     sp<MessageBase> msg = new MessageCaptureScreen(this,
3308             display, IGraphicBufferProducer::asInterface( wrapper ),
3309             sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3310             useIdentityTransform, rotationFlags, isLocalScreenshot);
3311
3312     status_t res = postMessageAsync(msg);
3313     if (res == NO_ERROR) {
3314         res = wrapper->waitForResponse();
3315     }
3316     return res;
3317 }
3318
3319
3320 void SurfaceFlinger::renderScreenImplLocked(
3321         const sp<const DisplayDevice>& hw,
3322         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3323         uint32_t minLayerZ, uint32_t maxLayerZ,
3324         bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3325 {
3326     ATRACE_CALL();
3327     RenderEngine& engine(getRenderEngine());
3328
3329     // get screen geometry
3330     const int32_t hw_w = hw->getWidth();
3331     const int32_t hw_h = hw->getHeight();
3332     const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3333                            static_cast<int32_t>(reqHeight) != hw_h;
3334
3335     // if a default or invalid sourceCrop is passed in, set reasonable values
3336     if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3337             !sourceCrop.isValid()) {
3338         sourceCrop.setLeftTop(Point(0, 0));
3339         sourceCrop.setRightBottom(Point(hw_w, hw_h));
3340     }
3341
3342     // ensure that sourceCrop is inside screen
3343     if (sourceCrop.left < 0) {
3344         ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3345     }
3346     if (sourceCrop.right > hw_w) {
3347         ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3348     }
3349     if (sourceCrop.top < 0) {
3350         ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3351     }
3352     if (sourceCrop.bottom > hw_h) {
3353         ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3354     }
3355
3356     // make sure to clear all GL error flags
3357     engine.checkErrors();
3358
3359     // set-up our viewport
3360     engine.setViewportAndProjection(
3361         reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3362     engine.disableTexturing();
3363
3364     // redraw the screen entirely...
3365     engine.clearWithColor(0, 0, 0, 1);
3366
3367     const LayerVector& layers( mDrawingState.layersSortedByZ );
3368     const size_t count = layers.size();
3369     for (size_t i=0 ; i<count ; ++i) {
3370         const sp<Layer>& layer(layers[i]);
3371         const Layer::State& state(layer->getDrawingState());
3372         if (state.layerStack == hw->getLayerStack()) {
3373             if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3374                 if (layer->isVisible()) {
3375                     if (filtering) layer->setFiltering(true);
3376                     layer->draw(hw, useIdentityTransform);
3377                     if (filtering) layer->setFiltering(false);
3378                 }
3379             }
3380         }
3381     }
3382
3383     hw->setViewportAndProjection();
3384 }
3385
3386
3387 status_t SurfaceFlinger::captureScreenImplLocked(
3388         const sp<const DisplayDevice>& hw,
3389         const sp<IGraphicBufferProducer>& producer,
3390         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3391         uint32_t minLayerZ, uint32_t maxLayerZ,
3392         bool useIdentityTransform, Transform::orientation_flags rotation,
3393         bool isLocalScreenshot)
3394 {
3395     ATRACE_CALL();
3396
3397     // get screen geometry
3398     uint32_t hw_w = hw->getWidth();
3399     uint32_t hw_h = hw->getHeight();
3400
3401     if (rotation & Transform::ROT_90) {
3402         std::swap(hw_w, hw_h);
3403     }
3404
3405     if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3406         ALOGE("size mismatch (%d, %d) > (%d, %d)",
3407                 reqWidth, reqHeight, hw_w, hw_h);
3408         return BAD_VALUE;
3409     }
3410
3411     reqWidth  = (!reqWidth)  ? hw_w : reqWidth;
3412     reqHeight = (!reqHeight) ? hw_h : reqHeight;
3413
3414     bool secureLayerIsVisible = false;
3415     const LayerVector& layers(mDrawingState.layersSortedByZ);
3416     const size_t count = layers.size();
3417     for (size_t i = 0 ; i < count ; ++i) {
3418         const sp<Layer>& layer(layers[i]);
3419         const Layer::State& state(layer->getDrawingState());
3420         if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3421                 state.z <= maxLayerZ && layer->isVisible() &&
3422                 layer->isSecure()) {
3423             secureLayerIsVisible = true;
3424         }
3425     }
3426
3427     if (!isLocalScreenshot && secureLayerIsVisible) {
3428         ALOGW("FB is protected: PERMISSION_DENIED");
3429         return PERMISSION_DENIED;
3430     }
3431
3432     // create a surface (because we're a producer, and we need to
3433     // dequeue/queue a buffer)
3434     sp<Surface> sur = new Surface(producer, false);
3435     ANativeWindow* window = sur.get();
3436
3437     status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3438     if (result == NO_ERROR) {
3439         uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3440                         GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3441
3442         int err = 0;
3443         err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3444         err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3445         err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3446         err |= native_window_set_usage(window, usage);
3447
3448         if (err == NO_ERROR) {
3449             ANativeWindowBuffer* buffer;
3450             /* TODO: Once we have the sync framework everywhere this can use
3451              * server-side waits on the fence that dequeueBuffer returns.
3452              */
3453             result = native_window_dequeue_buffer_and_wait(window,  &buffer);
3454             if (result == NO_ERROR) {
3455                 int syncFd = -1;
3456                 // create an EGLImage from the buffer so we can later
3457                 // turn it into a texture
3458                 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3459                         EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3460                 if (image != EGL_NO_IMAGE_KHR) {
3461                     // this binds the given EGLImage as a framebuffer for the
3462                     // duration of this scope.
3463                     RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3464                     if (imageBond.getStatus() == NO_ERROR) {
3465                         // this will in fact render into our dequeued buffer
3466                         // via an FBO, which means we didn't have to create
3467                         // an EGLSurface and therefore we're not
3468                         // dependent on the context's EGLConfig.
3469                         renderScreenImplLocked(
3470                             hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3471                             useIdentityTransform, rotation);
3472
3473                         // Attempt to create a sync khr object that can produce a sync point. If that
3474                         // isn't available, create a non-dupable sync object in the fallback path and
3475                         // wait on it directly.
3476                         EGLSyncKHR sync;
3477                         if (!DEBUG_SCREENSHOTS) {
3478                            sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3479                            // native fence fd will not be populated until flush() is done.
3480                            getRenderEngine().flush();
3481                         } else {
3482                             sync = EGL_NO_SYNC_KHR;
3483                         }
3484                         if (sync != EGL_NO_SYNC_KHR) {
3485                             // get the sync fd
3486                             syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3487                             if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3488                                 ALOGW("captureScreen: failed to dup sync khr object");
3489                                 syncFd = -1;
3490                             }
3491                             eglDestroySyncKHR(mEGLDisplay, sync);
3492                         } else {
3493                             // fallback path
3494                             sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3495                             if (sync != EGL_NO_SYNC_KHR) {
3496                                 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3497                                     EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3498                                 EGLint eglErr = eglGetError();
3499                                 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3500                                     ALOGW("captureScreen: fence wait timed out");
3501                                 } else {
3502                                     ALOGW_IF(eglErr != EGL_SUCCESS,
3503                                             "captureScreen: error waiting on EGL fence: %#x", eglErr);
3504                                 }
3505                                 eglDestroySyncKHR(mEGLDisplay, sync);
3506                             } else {
3507                                 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3508                             }
3509                         }
3510                         if (DEBUG_SCREENSHOTS) {
3511                             uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3512                             getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3513                             checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3514                                     hw, minLayerZ, maxLayerZ);
3515                             delete [] pixels;
3516                         }
3517
3518                     } else {
3519                         ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3520                         result = INVALID_OPERATION;
3521                         window->cancelBuffer(window, buffer, syncFd);
3522                         buffer = NULL;
3523                     }
3524                     // destroy our image
3525                     eglDestroyImageKHR(mEGLDisplay, image);
3526                 } else {
3527                     result = BAD_VALUE;
3528                 }
3529                 if (buffer) {
3530                     // queueBuffer takes ownership of syncFd
3531                     result = window->queueBuffer(window, buffer, syncFd);
3532                 }
3533             }
3534         } else {
3535             result = BAD_VALUE;
3536         }
3537         native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3538     }
3539
3540     return result;
3541 }
3542
3543 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3544         const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3545     if (DEBUG_SCREENSHOTS) {
3546         for (size_t y=0 ; y<h ; y++) {
3547             uint32_t const * p = (uint32_t const *)vaddr + y*s;
3548             for (size_t x=0 ; x<w ; x++) {
3549                 if (p[x] != 0xFF000000) return;
3550             }
3551         }
3552         ALOGE("*** we just took a black screenshot ***\n"
3553                 "requested minz=%d, maxz=%d, layerStack=%d",
3554                 minLayerZ, maxLayerZ, hw->getLayerStack());
3555         const LayerVector& layers( mDrawingState.layersSortedByZ );
3556         const size_t count = layers.size();
3557         for (size_t i=0 ; i<count ; ++i) {
3558             const sp<Layer>& layer(layers[i]);
3559             const Layer::State& state(layer->getDrawingState());
3560             const bool visible = (state.layerStack == hw->getLayerStack())
3561                                 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3562                                 && (layer->isVisible());
3563             ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
3564                     visible ? '+' : '-',
3565                             i, layer->getName().string(), state.layerStack, state.z,
3566                             layer->isVisible(), state.flags, state.alpha);
3567         }
3568     }
3569 }
3570
3571 // ---------------------------------------------------------------------------
3572
3573 SurfaceFlinger::LayerVector::LayerVector() {
3574 }
3575
3576 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3577     : SortedVector<sp<Layer> >(rhs) {
3578 }
3579
3580 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3581     const void* rhs) const
3582 {
3583     // sort layers per layer-stack, then by z-order and finally by sequence
3584     const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3585     const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3586
3587     uint32_t ls = l->getCurrentState().layerStack;
3588     uint32_t rs = r->getCurrentState().layerStack;
3589     if (ls != rs)
3590         return ls - rs;
3591
3592     uint32_t lz = l->getCurrentState().z;
3593     uint32_t rz = r->getCurrentState().z;
3594     if (lz != rz)
3595         return lz - rz;
3596
3597     return l->sequence - r->sequence;
3598 }
3599
3600 // ---------------------------------------------------------------------------
3601
3602 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3603     : type(DisplayDevice::DISPLAY_ID_INVALID),
3604       layerStack(DisplayDevice::NO_LAYER_STACK),
3605       orientation(0),
3606       width(0),
3607       height(0),
3608       isSecure(false) {
3609 }
3610
3611 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3612     DisplayDevice::DisplayType type, bool isSecure)
3613     : type(type),
3614       layerStack(DisplayDevice::NO_LAYER_STACK),
3615       orientation(0),
3616       width(0),
3617       height(0),
3618       isSecure(isSecure) {
3619     viewport.makeInvalid();
3620     frame.makeInvalid();
3621 }
3622
3623 // ---------------------------------------------------------------------------
3624
3625 }; // namespace android
3626
3627
3628 #if defined(__gl_h_)
3629 #error "don't include gl/gl.h in this file"
3630 #endif
3631
3632 #if defined(__gl2_h_)
3633 #error "don't include gl2/gl2.h in this file"
3634 #endif