OSDN Git Service

merge in nyc-release history after reset to nyc-dev
[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         ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
804         return;
805     }
806
807     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
808     const nsecs_t period = activeConfig->getVsyncPeriod();
809
810     mPrimaryDispSync.reset();
811     mPrimaryDispSync.setPeriod(period);
812
813     if (!mPrimaryHWVsyncEnabled) {
814         mPrimaryDispSync.beginResync();
815         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
816         mEventControlThread->setVsyncEnabled(true);
817         mPrimaryHWVsyncEnabled = true;
818     }
819 }
820
821 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
822     Mutex::Autolock _l(mHWVsyncLock);
823     if (mPrimaryHWVsyncEnabled) {
824         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
825         mEventControlThread->setVsyncEnabled(false);
826         mPrimaryDispSync.endResync();
827         mPrimaryHWVsyncEnabled = false;
828     }
829     if (makeUnavailable) {
830         mHWVsyncAvailable = false;
831     }
832 }
833
834 void SurfaceFlinger::resyncWithRateLimit() {
835     static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
836     if (systemTime() - mLastSwapTime > kIgnoreDelay) {
837         resyncToHardwareVsync(true);
838     }
839 }
840
841 void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
842     bool needsHwVsync = false;
843
844     { // Scope for the lock
845         Mutex::Autolock _l(mHWVsyncLock);
846         if (type == 0 && mPrimaryHWVsyncEnabled) {
847             needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
848         }
849     }
850
851     if (needsHwVsync) {
852         enableHardwareVsync();
853     } else {
854         disableHardwareVsync(false);
855     }
856 }
857
858 void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
859     ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
860     if (disp == DisplayDevice::DISPLAY_PRIMARY) {
861         Mutex::Autolock lock(mStateLock);
862
863         // All non-virtual displays are currently considered secure.
864         bool isSecure = true;
865
866         int32_t type = DisplayDevice::DISPLAY_PRIMARY;
867         createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
868         wp<IBinder> token = mBuiltinDisplays[type];
869
870         sp<IGraphicBufferProducer> producer;
871         sp<IGraphicBufferConsumer> consumer;
872         BufferQueue::createBufferQueue(&producer, &consumer,
873                 new GraphicBufferAlloc());
874
875         sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
876                 DisplayDevice::DISPLAY_PRIMARY, consumer);
877         sp<DisplayDevice> hw = new DisplayDevice(this,
878                 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
879                 producer, mRenderEngine->getEGLConfig());
880         mDisplays.add(token, hw);
881     } else {
882         auto type = DisplayDevice::DISPLAY_EXTERNAL;
883         Mutex::Autolock _l(mStateLock);
884         if (connected) {
885             createBuiltinDisplayLocked(type);
886         } else {
887             mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
888             mBuiltinDisplays[type].clear();
889         }
890         setTransactionFlags(eDisplayTransactionNeeded);
891
892         // Defer EventThread notification until SF has updated mDisplays.
893     }
894 }
895
896 void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
897     ATRACE_CALL();
898     getHwComposer().setVsyncEnabled(disp,
899             enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
900 }
901
902 void SurfaceFlinger::onMessageReceived(int32_t what) {
903     ATRACE_CALL();
904     switch (what) {
905         case MessageQueue::TRANSACTION: {
906             handleMessageTransaction();
907             break;
908         }
909         case MessageQueue::INVALIDATE: {
910             bool refreshNeeded = handleMessageTransaction();
911             refreshNeeded |= handleMessageInvalidate();
912             refreshNeeded |= mRepaintEverything;
913             if (refreshNeeded) {
914                 // Signal a refresh if a transaction modified the window state,
915                 // a new buffer was latched, or if HWC has requested a full
916                 // repaint
917                 signalRefresh();
918             }
919             break;
920         }
921         case MessageQueue::REFRESH: {
922             handleMessageRefresh();
923             break;
924         }
925     }
926 }
927
928 bool SurfaceFlinger::handleMessageTransaction() {
929     uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
930     if (transactionFlags) {
931         handleTransaction(transactionFlags);
932         return true;
933     }
934     return false;
935 }
936
937 bool SurfaceFlinger::handleMessageInvalidate() {
938     ATRACE_CALL();
939     return handlePageFlip();
940 }
941
942 void SurfaceFlinger::handleMessageRefresh() {
943     ATRACE_CALL();
944
945 #ifdef ENABLE_FENCE_TRACKING
946     nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
947 #else
948     nsecs_t refreshStartTime = 0;
949 #endif
950     static nsecs_t previousExpectedPresent = 0;
951     nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
952     static bool previousFrameMissed = false;
953     bool frameMissed = (expectedPresent == previousExpectedPresent);
954     if (frameMissed != previousFrameMissed) {
955         ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
956     }
957     previousFrameMissed = frameMissed;
958
959     if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
960         // Latch buffers, but don't send anything to HWC, then signal another
961         // wakeup for the next vsync
962         preComposition();
963         repaintEverything();
964     } else {
965         preComposition();
966         rebuildLayerStacks();
967         setUpHWComposer();
968         doDebugFlashRegions();
969         doComposition();
970         postComposition(refreshStartTime);
971     }
972
973     // Release any buffers which were replaced this frame
974     for (auto& layer : mLayersWithQueuedFrames) {
975         layer->releasePendingBuffer();
976     }
977     mLayersWithQueuedFrames.clear();
978
979     previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
980 }
981
982 void SurfaceFlinger::doDebugFlashRegions()
983 {
984     // is debugging enabled
985     if (CC_LIKELY(!mDebugRegion))
986         return;
987
988     const bool repaintEverything = mRepaintEverything;
989     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
990         const sp<DisplayDevice>& hw(mDisplays[dpy]);
991         if (hw->isDisplayOn()) {
992             // transform the dirty region into this screen's coordinate space
993             const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
994             if (!dirtyRegion.isEmpty()) {
995                 // redraw the whole screen
996                 doComposeSurfaces(hw, Region(hw->bounds()));
997
998                 // and draw the dirty region
999                 const int32_t height = hw->getHeight();
1000                 RenderEngine& engine(getRenderEngine());
1001                 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1002
1003                 hw->swapBuffers(getHwComposer());
1004             }
1005         }
1006     }
1007
1008     postFramebuffer();
1009
1010     if (mDebugRegion > 1) {
1011         usleep(mDebugRegion * 1000);
1012     }
1013
1014     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1015         status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
1016         ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1017                 " %d (%s)", displayId, result, strerror(-result));
1018     }
1019 }
1020
1021 void SurfaceFlinger::preComposition()
1022 {
1023     ATRACE_CALL();
1024     ALOGV("preComposition");
1025
1026     bool needExtraInvalidate = false;
1027     const LayerVector& layers(mDrawingState.layersSortedByZ);
1028     const size_t count = layers.size();
1029     for (size_t i=0 ; i<count ; i++) {
1030         if (layers[i]->onPreComposition()) {
1031             needExtraInvalidate = true;
1032         }
1033     }
1034     if (needExtraInvalidate) {
1035         signalLayerUpdate();
1036     }
1037 }
1038
1039 #ifdef ENABLE_FENCE_TRACKING
1040 void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
1041 #else
1042 void SurfaceFlinger::postComposition(nsecs_t /*refreshStartTime*/)
1043 #endif
1044 {
1045     ATRACE_CALL();
1046     ALOGV("postComposition");
1047
1048     const LayerVector& layers(mDrawingState.layersSortedByZ);
1049     const size_t count = layers.size();
1050     for (size_t i=0 ; i<count ; i++) {
1051         layers[i]->onPostComposition();
1052     }
1053
1054     sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
1055
1056     if (presentFence->isValid()) {
1057         if (mPrimaryDispSync.addPresentFence(presentFence)) {
1058             enableHardwareVsync();
1059         } else {
1060             disableHardwareVsync(false);
1061         }
1062     }
1063
1064     const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1065     if (kIgnorePresentFences) {
1066         if (hw->isDisplayOn()) {
1067             enableHardwareVsync();
1068         }
1069     }
1070
1071 #ifdef ENABLE_FENCE_TRACKING
1072     mFenceTracker.addFrame(refreshStartTime, presentFence,
1073             hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1074 #endif
1075
1076     if (mAnimCompositionPending) {
1077         mAnimCompositionPending = false;
1078
1079         if (presentFence->isValid()) {
1080             mAnimFrameTracker.setActualPresentFence(presentFence);
1081         } else {
1082             // The HWC doesn't support present fences, so use the refresh
1083             // timestamp instead.
1084             nsecs_t presentTime =
1085                     mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1086             mAnimFrameTracker.setActualPresentTime(presentTime);
1087         }
1088         mAnimFrameTracker.advanceFrame();
1089     }
1090
1091     if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1092         return;
1093     }
1094
1095     nsecs_t currentTime = systemTime();
1096     if (mHasPoweredOff) {
1097         mHasPoweredOff = false;
1098     } else {
1099         nsecs_t period = mPrimaryDispSync.getPeriod();
1100         nsecs_t elapsedTime = currentTime - mLastSwapTime;
1101         size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1102         if (numPeriods < NUM_BUCKETS - 1) {
1103             mFrameBuckets[numPeriods] += elapsedTime;
1104         } else {
1105             mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1106         }
1107         mTotalTime += elapsedTime;
1108     }
1109     mLastSwapTime = currentTime;
1110 }
1111
1112 void SurfaceFlinger::rebuildLayerStacks() {
1113     ATRACE_CALL();
1114     ALOGV("rebuildLayerStacks");
1115
1116     // rebuild the visible layer list per screen
1117     if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1118         ATRACE_CALL();
1119         mVisibleRegionsDirty = false;
1120         invalidateHwcGeometry();
1121
1122         const LayerVector& layers(mDrawingState.layersSortedByZ);
1123         for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1124             Region opaqueRegion;
1125             Region dirtyRegion;
1126             Vector<sp<Layer>> layersSortedByZ;
1127             const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1128             const Transform& tr(displayDevice->getTransform());
1129             const Rect bounds(displayDevice->getBounds());
1130             if (displayDevice->isDisplayOn()) {
1131                 SurfaceFlinger::computeVisibleRegions(layers,
1132                         displayDevice->getLayerStack(), dirtyRegion,
1133                         opaqueRegion);
1134
1135                 const size_t count = layers.size();
1136                 for (size_t i=0 ; i<count ; i++) {
1137                     const sp<Layer>& layer(layers[i]);
1138                     const Layer::State& s(layer->getDrawingState());
1139                     if (s.layerStack == displayDevice->getLayerStack()) {
1140                         Region drawRegion(tr.transform(
1141                                 layer->visibleNonTransparentRegion));
1142                         drawRegion.andSelf(bounds);
1143                         if (!drawRegion.isEmpty()) {
1144                             layersSortedByZ.add(layer);
1145                         } else {
1146                             // Clear out the HWC layer if this layer was
1147                             // previously visible, but no longer is
1148                             layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1149                                     nullptr);
1150                         }
1151                     }
1152                 }
1153             }
1154             displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1155             displayDevice->undefinedRegion.set(bounds);
1156             displayDevice->undefinedRegion.subtractSelf(
1157                     tr.transform(opaqueRegion));
1158             displayDevice->dirtyRegion.orSelf(dirtyRegion);
1159         }
1160     }
1161 }
1162
1163 void SurfaceFlinger::setUpHWComposer() {
1164     ATRACE_CALL();
1165     ALOGV("setUpHWComposer");
1166
1167     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1168         bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1169         bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1170         bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1171
1172         // If nothing has changed (!dirty), don't recompose.
1173         // If something changed, but we don't currently have any visible layers,
1174         //   and didn't when we last did a composition, then skip it this time.
1175         // The second rule does two things:
1176         // - When all layers are removed from a display, we'll emit one black
1177         //   frame, then nothing more until we get new layers.
1178         // - When a display is created with a private layer stack, we won't
1179         //   emit any black frames until a layer is added to the layer stack.
1180         bool mustRecompose = dirty && !(empty && wasEmpty);
1181
1182         ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1183                 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1184                 mustRecompose ? "doing" : "skipping",
1185                 dirty ? "+" : "-",
1186                 empty ? "+" : "-",
1187                 wasEmpty ? "+" : "-");
1188
1189         mDisplays[dpy]->beginFrame(mustRecompose);
1190
1191         if (mustRecompose) {
1192             mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1193         }
1194     }
1195
1196     // build the h/w work list
1197     if (CC_UNLIKELY(mGeometryInvalid)) {
1198         mGeometryInvalid = false;
1199         for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1200             sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1201             const auto hwcId = displayDevice->getHwcDisplayId();
1202             if (hwcId >= 0) {
1203                 const Vector<sp<Layer>>& currentLayers(
1204                         displayDevice->getVisibleLayersSortedByZ());
1205                 bool foundLayerWithoutHwc = false;
1206                 for (auto& layer : currentLayers) {
1207                     if (!layer->hasHwcLayer(hwcId)) {
1208                         auto hwcLayer = mHwc->createLayer(hwcId);
1209                         if (hwcLayer) {
1210                             layer->setHwcLayer(hwcId, std::move(hwcLayer));
1211                         } else {
1212                             layer->forceClientComposition(hwcId);
1213                             foundLayerWithoutHwc = true;
1214                             continue;
1215                         }
1216                     }
1217
1218                     layer->setGeometry(displayDevice);
1219                     if (mDebugDisableHWC || mDebugRegion || mDaltonize ||
1220                             mHasColorMatrix) {
1221                         layer->forceClientComposition(hwcId);
1222                     }
1223                 }
1224             }
1225         }
1226     }
1227
1228     // Set the per-frame data
1229     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1230         auto& displayDevice = mDisplays[displayId];
1231         const auto hwcId = displayDevice->getHwcDisplayId();
1232         if (hwcId < 0) {
1233             continue;
1234         }
1235         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1236             layer->setPerFrameData(displayDevice);
1237         }
1238     }
1239
1240     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1241         status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
1242         ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1243                 " %d (%s)", displayId, result, strerror(-result));
1244     }
1245 }
1246
1247 void SurfaceFlinger::doComposition() {
1248     ATRACE_CALL();
1249     ALOGV("doComposition");
1250
1251     const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1252     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1253         const sp<DisplayDevice>& hw(mDisplays[dpy]);
1254         if (hw->isDisplayOn()) {
1255             // transform the dirty region into this screen's coordinate space
1256             const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1257
1258             // repaint the framebuffer (if needed)
1259             doDisplayComposition(hw, dirtyRegion);
1260
1261             hw->dirtyRegion.clear();
1262             hw->flip(hw->swapRegion);
1263             hw->swapRegion.clear();
1264         }
1265     }
1266     postFramebuffer();
1267 }
1268
1269 void SurfaceFlinger::postFramebuffer()
1270 {
1271     ATRACE_CALL();
1272     ALOGV("postFramebuffer");
1273
1274     const nsecs_t now = systemTime();
1275     mDebugInSwapBuffers = now;
1276
1277     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1278         auto& displayDevice = mDisplays[displayId];
1279         const auto hwcId = displayDevice->getHwcDisplayId();
1280         if (hwcId >= 0) {
1281             mHwc->commit(hwcId);
1282         }
1283         displayDevice->onSwapBuffersCompleted();
1284         if (displayId == 0) {
1285             // Make the default display current because the VirtualDisplayDevice
1286             // code cannot deal with dequeueBuffer() being called outside of the
1287             // composition loop; however the code below can call glFlush() which
1288             // is allowed to (and does in some case) call dequeueBuffer().
1289             displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1290         }
1291         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1292             sp<Fence> releaseFence = Fence::NO_FENCE;
1293             if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1294                 releaseFence = displayDevice->getClientTargetAcquireFence();
1295             } else {
1296                 auto hwcLayer = layer->getHwcLayer(hwcId);
1297                 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
1298             }
1299             layer->onLayerDisplayed(releaseFence);
1300         }
1301         if (hwcId >= 0) {
1302             mHwc->clearReleaseFences(hwcId);
1303         }
1304     }
1305
1306     mLastSwapBufferTime = systemTime() - now;
1307     mDebugInSwapBuffers = 0;
1308
1309     uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1310     if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1311         logFrameStats();
1312     }
1313 }
1314
1315 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1316 {
1317     ATRACE_CALL();
1318
1319     // here we keep a copy of the drawing state (that is the state that's
1320     // going to be overwritten by handleTransactionLocked()) outside of
1321     // mStateLock so that the side-effects of the State assignment
1322     // don't happen with mStateLock held (which can cause deadlocks).
1323     State drawingState(mDrawingState);
1324
1325     Mutex::Autolock _l(mStateLock);
1326     const nsecs_t now = systemTime();
1327     mDebugInTransaction = now;
1328
1329     // Here we're guaranteed that some transaction flags are set
1330     // so we can call handleTransactionLocked() unconditionally.
1331     // We call getTransactionFlags(), which will also clear the flags,
1332     // with mStateLock held to guarantee that mCurrentState won't change
1333     // until the transaction is committed.
1334
1335     transactionFlags = getTransactionFlags(eTransactionMask);
1336     handleTransactionLocked(transactionFlags);
1337
1338     mLastTransactionTime = systemTime() - now;
1339     mDebugInTransaction = 0;
1340     invalidateHwcGeometry();
1341     // here the transaction has been committed
1342 }
1343
1344 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1345 {
1346     const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1347     const size_t count = currentLayers.size();
1348
1349     // Notify all layers of available frames
1350     for (size_t i = 0; i < count; ++i) {
1351         currentLayers[i]->notifyAvailableFrames();
1352     }
1353
1354     /*
1355      * Traversal of the children
1356      * (perform the transaction for each of them if needed)
1357      */
1358
1359     if (transactionFlags & eTraversalNeeded) {
1360         for (size_t i=0 ; i<count ; i++) {
1361             const sp<Layer>& layer(currentLayers[i]);
1362             uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1363             if (!trFlags) continue;
1364
1365             const uint32_t flags = layer->doTransaction(0);
1366             if (flags & Layer::eVisibleRegion)
1367                 mVisibleRegionsDirty = true;
1368         }
1369     }
1370
1371     /*
1372      * Perform display own transactions if needed
1373      */
1374
1375     if (transactionFlags & eDisplayTransactionNeeded) {
1376         // here we take advantage of Vector's copy-on-write semantics to
1377         // improve performance by skipping the transaction entirely when
1378         // know that the lists are identical
1379         const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1380         const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1381         if (!curr.isIdenticalTo(draw)) {
1382             mVisibleRegionsDirty = true;
1383             const size_t cc = curr.size();
1384                   size_t dc = draw.size();
1385
1386             // find the displays that were removed
1387             // (ie: in drawing state but not in current state)
1388             // also handle displays that changed
1389             // (ie: displays that are in both lists)
1390             for (size_t i=0 ; i<dc ; i++) {
1391                 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1392                 if (j < 0) {
1393                     // in drawing state but not in current state
1394                     if (!draw[i].isMainDisplay()) {
1395                         // Call makeCurrent() on the primary display so we can
1396                         // be sure that nothing associated with this display
1397                         // is current.
1398                         const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1399                         defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1400                         sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1401                         if (hw != NULL)
1402                             hw->disconnect(getHwComposer());
1403                         if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1404                             mEventThread->onHotplugReceived(draw[i].type, false);
1405                         mDisplays.removeItem(draw.keyAt(i));
1406                     } else {
1407                         ALOGW("trying to remove the main display");
1408                     }
1409                 } else {
1410                     // this display is in both lists. see if something changed.
1411                     const DisplayDeviceState& state(curr[j]);
1412                     const wp<IBinder>& display(curr.keyAt(j));
1413                     const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1414                     const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1415                     if (state_binder != draw_binder) {
1416                         // changing the surface is like destroying and
1417                         // recreating the DisplayDevice, so we just remove it
1418                         // from the drawing state, so that it get re-added
1419                         // below.
1420                         sp<DisplayDevice> hw(getDisplayDevice(display));
1421                         if (hw != NULL)
1422                             hw->disconnect(getHwComposer());
1423                         mDisplays.removeItem(display);
1424                         mDrawingState.displays.removeItemsAt(i);
1425                         dc--; i--;
1426                         // at this point we must loop to the next item
1427                         continue;
1428                     }
1429
1430                     const sp<DisplayDevice> disp(getDisplayDevice(display));
1431                     if (disp != NULL) {
1432                         if (state.layerStack != draw[i].layerStack) {
1433                             disp->setLayerStack(state.layerStack);
1434                         }
1435                         if ((state.orientation != draw[i].orientation)
1436                                 || (state.viewport != draw[i].viewport)
1437                                 || (state.frame != draw[i].frame))
1438                         {
1439                             disp->setProjection(state.orientation,
1440                                     state.viewport, state.frame);
1441                         }
1442                         if (state.width != draw[i].width || state.height != draw[i].height) {
1443                             disp->setDisplaySize(state.width, state.height);
1444                         }
1445                     }
1446                 }
1447             }
1448
1449             // find displays that were added
1450             // (ie: in current state but not in drawing state)
1451             for (size_t i=0 ; i<cc ; i++) {
1452                 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1453                     const DisplayDeviceState& state(curr[i]);
1454
1455                     sp<DisplaySurface> dispSurface;
1456                     sp<IGraphicBufferProducer> producer;
1457                     sp<IGraphicBufferProducer> bqProducer;
1458                     sp<IGraphicBufferConsumer> bqConsumer;
1459                     BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1460                             new GraphicBufferAlloc());
1461
1462                     int32_t hwcId = -1;
1463                     if (state.isVirtualDisplay()) {
1464                         // Virtual displays without a surface are dormant:
1465                         // they have external state (layer stack, projection,
1466                         // etc.) but no internal state (i.e. a DisplayDevice).
1467                         if (state.surface != NULL) {
1468
1469                             int width = 0;
1470                             int status = state.surface->query(
1471                                     NATIVE_WINDOW_WIDTH, &width);
1472                             ALOGE_IF(status != NO_ERROR,
1473                                     "Unable to query width (%d)", status);
1474                             int height = 0;
1475                             status = state.surface->query(
1476                                     NATIVE_WINDOW_HEIGHT, &height);
1477                             ALOGE_IF(status != NO_ERROR,
1478                                     "Unable to query height (%d)", status);
1479
1480                             mHwc->allocateVirtualDisplay(width, height,
1481                                     &hwcId);
1482
1483                             sp<VirtualDisplaySurface> vds =
1484                                     new VirtualDisplaySurface(*mHwc,
1485                                             hwcId, state.surface, bqProducer,
1486                                             bqConsumer, state.displayName);
1487
1488                             dispSurface = vds;
1489                             producer = vds;
1490                         }
1491                     } else {
1492                         ALOGE_IF(state.surface!=NULL,
1493                                 "adding a supported display, but rendering "
1494                                 "surface is provided (%p), ignoring it",
1495                                 state.surface.get());
1496                         if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1497                             hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1498                             dispSurface = new FramebufferSurface(*mHwc,
1499                                     DisplayDevice::DISPLAY_EXTERNAL,
1500                                     bqConsumer);
1501                             producer = bqProducer;
1502                         } else {
1503                             ALOGE("Attempted to add non-external non-virtual"
1504                                     " display");
1505                         }
1506                     }
1507
1508                     const wp<IBinder>& display(curr.keyAt(i));
1509                     if (dispSurface != NULL) {
1510                         sp<DisplayDevice> hw = new DisplayDevice(this,
1511                                 state.type, hwcId, state.isSecure, display,
1512                                 dispSurface, producer,
1513                                 mRenderEngine->getEGLConfig());
1514                         hw->setLayerStack(state.layerStack);
1515                         hw->setProjection(state.orientation,
1516                                 state.viewport, state.frame);
1517                         hw->setDisplayName(state.displayName);
1518                         mDisplays.add(display, hw);
1519                         if (!state.isVirtualDisplay()) {
1520                             mEventThread->onHotplugReceived(state.type, true);
1521                         }
1522                     }
1523                 }
1524             }
1525         }
1526     }
1527
1528     if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1529         // The transform hint might have changed for some layers
1530         // (either because a display has changed, or because a layer
1531         // as changed).
1532         //
1533         // Walk through all the layers in currentLayers,
1534         // and update their transform hint.
1535         //
1536         // If a layer is visible only on a single display, then that
1537         // display is used to calculate the hint, otherwise we use the
1538         // default display.
1539         //
1540         // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1541         // the hint is set before we acquire a buffer from the surface texture.
1542         //
1543         // NOTE: layer transactions have taken place already, so we use their
1544         // drawing state. However, SurfaceFlinger's own transaction has not
1545         // happened yet, so we must use the current state layer list
1546         // (soon to become the drawing state list).
1547         //
1548         sp<const DisplayDevice> disp;
1549         uint32_t currentlayerStack = 0;
1550         for (size_t i=0; i<count; i++) {
1551             // NOTE: we rely on the fact that layers are sorted by
1552             // layerStack first (so we don't have to traverse the list
1553             // of displays for every layer).
1554             const sp<Layer>& layer(currentLayers[i]);
1555             uint32_t layerStack = layer->getDrawingState().layerStack;
1556             if (i==0 || currentlayerStack != layerStack) {
1557                 currentlayerStack = layerStack;
1558                 // figure out if this layerstack is mirrored
1559                 // (more than one display) if so, pick the default display,
1560                 // if not, pick the only display it's on.
1561                 disp.clear();
1562                 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1563                     sp<const DisplayDevice> hw(mDisplays[dpy]);
1564                     if (hw->getLayerStack() == currentlayerStack) {
1565                         if (disp == NULL) {
1566                             disp = hw;
1567                         } else {
1568                             disp = NULL;
1569                             break;
1570                         }
1571                     }
1572                 }
1573             }
1574             if (disp == NULL) {
1575                 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1576                 // redraw after transform hint changes. See bug 8508397.
1577
1578                 // could be null when this layer is using a layerStack
1579                 // that is not visible on any display. Also can occur at
1580                 // screen off/on times.
1581                 disp = getDefaultDisplayDevice();
1582             }
1583             layer->updateTransformHint(disp);
1584         }
1585     }
1586
1587
1588     /*
1589      * Perform our own transaction if needed
1590      */
1591
1592     const LayerVector& layers(mDrawingState.layersSortedByZ);
1593     if (currentLayers.size() > layers.size()) {
1594         // layers have been added
1595         mVisibleRegionsDirty = true;
1596     }
1597
1598     // some layers might have been removed, so
1599     // we need to update the regions they're exposing.
1600     if (mLayersRemoved) {
1601         mLayersRemoved = false;
1602         mVisibleRegionsDirty = true;
1603         const size_t count = layers.size();
1604         for (size_t i=0 ; i<count ; i++) {
1605             const sp<Layer>& layer(layers[i]);
1606             if (currentLayers.indexOf(layer) < 0) {
1607                 // this layer is not visible anymore
1608                 // TODO: we could traverse the tree from front to back and
1609                 //       compute the actual visible region
1610                 // TODO: we could cache the transformed region
1611                 const Layer::State& s(layer->getDrawingState());
1612                 Region visibleReg = s.active.transform.transform(
1613                         Region(Rect(s.active.w, s.active.h)));
1614                 invalidateLayerStack(s.layerStack, visibleReg);
1615             }
1616         }
1617     }
1618
1619     commitTransaction();
1620
1621     updateCursorAsync();
1622 }
1623
1624 void SurfaceFlinger::updateCursorAsync()
1625 {
1626     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1627         auto& displayDevice = mDisplays[displayId];
1628         if (displayDevice->getHwcDisplayId() < 0) {
1629             continue;
1630         }
1631
1632         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1633             layer->updateCursorPosition(displayDevice);
1634         }
1635     }
1636 }
1637
1638 void SurfaceFlinger::commitTransaction()
1639 {
1640     if (!mLayersPendingRemoval.isEmpty()) {
1641         // Notify removed layers now that they can't be drawn from
1642         for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1643             mLayersPendingRemoval[i]->onRemoved();
1644         }
1645         mLayersPendingRemoval.clear();
1646     }
1647
1648     // If this transaction is part of a window animation then the next frame
1649     // we composite should be considered an animation as well.
1650     mAnimCompositionPending = mAnimTransactionPending;
1651
1652     mDrawingState = mCurrentState;
1653     mTransactionPending = false;
1654     mAnimTransactionPending = false;
1655     mTransactionCV.broadcast();
1656 }
1657
1658 void SurfaceFlinger::computeVisibleRegions(
1659         const LayerVector& currentLayers, uint32_t layerStack,
1660         Region& outDirtyRegion, Region& outOpaqueRegion)
1661 {
1662     ATRACE_CALL();
1663     ALOGV("computeVisibleRegions");
1664
1665     Region aboveOpaqueLayers;
1666     Region aboveCoveredLayers;
1667     Region dirty;
1668
1669     outDirtyRegion.clear();
1670
1671     size_t i = currentLayers.size();
1672     while (i--) {
1673         const sp<Layer>& layer = currentLayers[i];
1674
1675         // start with the whole surface at its current location
1676         const Layer::State& s(layer->getDrawingState());
1677
1678         // only consider the layers on the given layer stack
1679         if (s.layerStack != layerStack)
1680             continue;
1681
1682         /*
1683          * opaqueRegion: area of a surface that is fully opaque.
1684          */
1685         Region opaqueRegion;
1686
1687         /*
1688          * visibleRegion: area of a surface that is visible on screen
1689          * and not fully transparent. This is essentially the layer's
1690          * footprint minus the opaque regions above it.
1691          * Areas covered by a translucent surface are considered visible.
1692          */
1693         Region visibleRegion;
1694
1695         /*
1696          * coveredRegion: area of a surface that is covered by all
1697          * visible regions above it (which includes the translucent areas).
1698          */
1699         Region coveredRegion;
1700
1701         /*
1702          * transparentRegion: area of a surface that is hinted to be completely
1703          * transparent. This is only used to tell when the layer has no visible
1704          * non-transparent regions and can be removed from the layer list. It
1705          * does not affect the visibleRegion of this layer or any layers
1706          * beneath it. The hint may not be correct if apps don't respect the
1707          * SurfaceView restrictions (which, sadly, some don't).
1708          */
1709         Region transparentRegion;
1710
1711
1712         // handle hidden surfaces by setting the visible region to empty
1713         if (CC_LIKELY(layer->isVisible())) {
1714             const bool translucent = !layer->isOpaque(s);
1715             Rect bounds(s.active.transform.transform(layer->computeBounds()));
1716             visibleRegion.set(bounds);
1717             if (!visibleRegion.isEmpty()) {
1718                 // Remove the transparent area from the visible region
1719                 if (translucent) {
1720                     const Transform tr(s.active.transform);
1721                     if (tr.transformed()) {
1722                         if (tr.preserveRects()) {
1723                             // transform the transparent region
1724                             transparentRegion = tr.transform(s.activeTransparentRegion);
1725                         } else {
1726                             // transformation too complex, can't do the
1727                             // transparent region optimization.
1728                             transparentRegion.clear();
1729                         }
1730                     } else {
1731                         transparentRegion = s.activeTransparentRegion;
1732                     }
1733                 }
1734
1735                 // compute the opaque region
1736                 const int32_t layerOrientation = s.active.transform.getOrientation();
1737                 if (s.alpha == 1.0f && !translucent &&
1738                         ((layerOrientation & Transform::ROT_INVALID) == false)) {
1739                     // the opaque region is the layer's footprint
1740                     opaqueRegion = visibleRegion;
1741                 }
1742             }
1743         }
1744
1745         // Clip the covered region to the visible region
1746         coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1747
1748         // Update aboveCoveredLayers for next (lower) layer
1749         aboveCoveredLayers.orSelf(visibleRegion);
1750
1751         // subtract the opaque region covered by the layers above us
1752         visibleRegion.subtractSelf(aboveOpaqueLayers);
1753
1754         // compute this layer's dirty region
1755         if (layer->contentDirty) {
1756             // we need to invalidate the whole region
1757             dirty = visibleRegion;
1758             // as well, as the old visible region
1759             dirty.orSelf(layer->visibleRegion);
1760             layer->contentDirty = false;
1761         } else {
1762             /* compute the exposed region:
1763              *   the exposed region consists of two components:
1764              *   1) what's VISIBLE now and was COVERED before
1765              *   2) what's EXPOSED now less what was EXPOSED before
1766              *
1767              * note that (1) is conservative, we start with the whole
1768              * visible region but only keep what used to be covered by
1769              * something -- which mean it may have been exposed.
1770              *
1771              * (2) handles areas that were not covered by anything but got
1772              * exposed because of a resize.
1773              */
1774             const Region newExposed = visibleRegion - coveredRegion;
1775             const Region oldVisibleRegion = layer->visibleRegion;
1776             const Region oldCoveredRegion = layer->coveredRegion;
1777             const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1778             dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1779         }
1780         dirty.subtractSelf(aboveOpaqueLayers);
1781
1782         // accumulate to the screen dirty region
1783         outDirtyRegion.orSelf(dirty);
1784
1785         // Update aboveOpaqueLayers for next (lower) layer
1786         aboveOpaqueLayers.orSelf(opaqueRegion);
1787
1788         // Store the visible region in screen space
1789         layer->setVisibleRegion(visibleRegion);
1790         layer->setCoveredRegion(coveredRegion);
1791         layer->setVisibleNonTransparentRegion(
1792                 visibleRegion.subtract(transparentRegion));
1793     }
1794
1795     outOpaqueRegion = aboveOpaqueLayers;
1796 }
1797
1798 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1799         const Region& dirty) {
1800     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1801         const sp<DisplayDevice>& hw(mDisplays[dpy]);
1802         if (hw->getLayerStack() == layerStack) {
1803             hw->dirtyRegion.orSelf(dirty);
1804         }
1805     }
1806 }
1807
1808 bool SurfaceFlinger::handlePageFlip()
1809 {
1810     ALOGV("handlePageFlip");
1811
1812     Region dirtyRegion;
1813
1814     bool visibleRegions = false;
1815     const LayerVector& layers(mDrawingState.layersSortedByZ);
1816     bool frameQueued = false;
1817
1818     // Store the set of layers that need updates. This set must not change as
1819     // buffers are being latched, as this could result in a deadlock.
1820     // Example: Two producers share the same command stream and:
1821     // 1.) Layer 0 is latched
1822     // 2.) Layer 0 gets a new frame
1823     // 2.) Layer 1 gets a new frame
1824     // 3.) Layer 1 is latched.
1825     // Display is now waiting on Layer 1's frame, which is behind layer 0's
1826     // second frame. But layer 0's second frame could be waiting on display.
1827     for (size_t i = 0, count = layers.size(); i<count ; i++) {
1828         const sp<Layer>& layer(layers[i]);
1829         if (layer->hasQueuedFrame()) {
1830             frameQueued = true;
1831             if (layer->shouldPresentNow(mPrimaryDispSync)) {
1832                 mLayersWithQueuedFrames.push_back(layer.get());
1833             } else {
1834                 layer->useEmptyDamage();
1835             }
1836         } else {
1837             layer->useEmptyDamage();
1838         }
1839     }
1840     for (auto& layer : mLayersWithQueuedFrames) {
1841         const Region dirty(layer->latchBuffer(visibleRegions));
1842         layer->useSurfaceDamage();
1843         const Layer::State& s(layer->getDrawingState());
1844         invalidateLayerStack(s.layerStack, dirty);
1845     }
1846
1847     mVisibleRegionsDirty |= visibleRegions;
1848
1849     // If we will need to wake up at some time in the future to deal with a
1850     // queued frame that shouldn't be displayed during this vsync period, wake
1851     // up during the next vsync period to check again.
1852     if (frameQueued && mLayersWithQueuedFrames.empty()) {
1853         signalLayerUpdate();
1854     }
1855
1856     // Only continue with the refresh if there is actually new work to do
1857     return !mLayersWithQueuedFrames.empty();
1858 }
1859
1860 void SurfaceFlinger::invalidateHwcGeometry()
1861 {
1862     mGeometryInvalid = true;
1863 }
1864
1865
1866 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1867         const Region& inDirtyRegion)
1868 {
1869     // We only need to actually compose the display if:
1870     // 1) It is being handled by hardware composer, which may need this to
1871     //    keep its virtual display state machine in sync, or
1872     // 2) There is work to be done (the dirty region isn't empty)
1873     bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1874     if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1875         ALOGV("Skipping display composition");
1876         return;
1877     }
1878
1879     ALOGV("doDisplayComposition");
1880
1881     Region dirtyRegion(inDirtyRegion);
1882
1883     // compute the invalid region
1884     hw->swapRegion.orSelf(dirtyRegion);
1885
1886     uint32_t flags = hw->getFlags();
1887     if (flags & DisplayDevice::SWAP_RECTANGLE) {
1888         // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1889         // takes a rectangle, we must make sure to update that whole
1890         // rectangle in that case
1891         dirtyRegion.set(hw->swapRegion.bounds());
1892     } else {
1893         if (flags & DisplayDevice::PARTIAL_UPDATES) {
1894             // We need to redraw the rectangle that will be updated
1895             // (pushed to the framebuffer).
1896             // This is needed because PARTIAL_UPDATES only takes one
1897             // rectangle instead of a region (see DisplayDevice::flip())
1898             dirtyRegion.set(hw->swapRegion.bounds());
1899         } else {
1900             // we need to redraw everything (the whole screen)
1901             dirtyRegion.set(hw->bounds());
1902             hw->swapRegion = dirtyRegion;
1903         }
1904     }
1905
1906     if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1907         if (!doComposeSurfaces(hw, dirtyRegion)) return;
1908     } else {
1909         RenderEngine& engine(getRenderEngine());
1910         mat4 colorMatrix = mColorMatrix;
1911         if (mDaltonize) {
1912             colorMatrix = colorMatrix * mDaltonizer();
1913         }
1914         mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
1915         doComposeSurfaces(hw, dirtyRegion);
1916         engine.setupColorTransform(oldMatrix);
1917     }
1918
1919     // update the swap region and clear the dirty region
1920     hw->swapRegion.orSelf(dirtyRegion);
1921
1922     // swap buffers (presentation)
1923     hw->swapBuffers(getHwComposer());
1924 }
1925
1926 bool SurfaceFlinger::doComposeSurfaces(
1927         const sp<const DisplayDevice>& displayDevice, const Region& dirty)
1928 {
1929     ALOGV("doComposeSurfaces");
1930
1931     const auto hwcId = displayDevice->getHwcDisplayId();
1932     bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1933     if (hasClientComposition) {
1934         ALOGV("hasClientComposition");
1935
1936         if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
1937             ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1938                   displayDevice->getDisplayName().string());
1939             eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1940             if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1941               ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1942             }
1943             return false;
1944         }
1945
1946         // Never touch the framebuffer if we don't have any framebuffer layers
1947         const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1948         if (hasDeviceComposition) {
1949             // when using overlays, we assume a fully transparent framebuffer
1950             // NOTE: we could reduce how much we need to clear, for instance
1951             // remove where there are opaque FB layers. however, on some
1952             // GPUs doing a "clean slate" clear might be more efficient.
1953             // We'll revisit later if needed.
1954             mRenderEngine->clearWithColor(0, 0, 0, 0);
1955         } else {
1956             // we start with the whole screen area
1957             const Region bounds(displayDevice->getBounds());
1958
1959             // we remove the scissor part
1960             // we're left with the letterbox region
1961             // (common case is that letterbox ends-up being empty)
1962             const Region letterbox(bounds.subtract(displayDevice->getScissor()));
1963
1964             // compute the area to clear
1965             Region region(displayDevice->undefinedRegion.merge(letterbox));
1966
1967             // but limit it to the dirty region
1968             region.andSelf(dirty);
1969
1970             // screen is already cleared here
1971             if (!region.isEmpty()) {
1972                 // can happen with SurfaceView
1973                 drawWormhole(displayDevice, region);
1974             }
1975         }
1976
1977         if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1978             // just to be on the safe side, we don't set the
1979             // scissor on the main display. It should never be needed
1980             // anyways (though in theory it could since the API allows it).
1981             const Rect& bounds(displayDevice->getBounds());
1982             const Rect& scissor(displayDevice->getScissor());
1983             if (scissor != bounds) {
1984                 // scissor doesn't match the screen's dimensions, so we
1985                 // need to clear everything outside of it and enable
1986                 // the GL scissor so we don't draw anything where we shouldn't
1987
1988                 // enable scissor for this frame
1989                 const uint32_t height = displayDevice->getHeight();
1990                 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
1991                         scissor.getWidth(), scissor.getHeight());
1992             }
1993         }
1994     }
1995
1996     /*
1997      * and then, render the layers targeted at the framebuffer
1998      */
1999
2000     ALOGV("Rendering client layers");
2001     const Transform& displayTransform = displayDevice->getTransform();
2002     if (hwcId >= 0) {
2003         // we're using h/w composer
2004         bool firstLayer = true;
2005         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2006             const Region clip(dirty.intersect(
2007                     displayTransform.transform(layer->visibleRegion)));
2008             ALOGV("Layer: %s", layer->getName().string());
2009             ALOGV("  Composition type: %s",
2010                     to_string(layer->getCompositionType(hwcId)).c_str());
2011             if (!clip.isEmpty()) {
2012                 switch (layer->getCompositionType(hwcId)) {
2013                     case HWC2::Composition::Cursor:
2014                     case HWC2::Composition::Device:
2015                     case HWC2::Composition::SolidColor: {
2016                         const Layer::State& state(layer->getDrawingState());
2017                         if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2018                                 layer->isOpaque(state) && (state.alpha == 1.0f)
2019                                 && hasClientComposition) {
2020                             // never clear the very first layer since we're
2021                             // guaranteed the FB is already cleared
2022                             layer->clearWithOpenGL(displayDevice, clip);
2023                         }
2024                         break;
2025                     }
2026                     case HWC2::Composition::Client: {
2027                         layer->draw(displayDevice, clip);
2028                         break;
2029                     }
2030                     default:
2031                         break;
2032                 }
2033             } else {
2034                 ALOGV("  Skipping for empty clip");
2035             }
2036             firstLayer = false;
2037         }
2038     } else {
2039         // we're not using h/w composer
2040         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2041             const Region clip(dirty.intersect(
2042                     displayTransform.transform(layer->visibleRegion)));
2043             if (!clip.isEmpty()) {
2044                 layer->draw(displayDevice, clip);
2045             }
2046         }
2047     }
2048
2049     // disable scissor at the end of the frame
2050     mRenderEngine->disableScissor();
2051     return true;
2052 }
2053
2054 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2055     const int32_t height = hw->getHeight();
2056     RenderEngine& engine(getRenderEngine());
2057     engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2058 }
2059
2060 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2061         const sp<IBinder>& handle,
2062         const sp<IGraphicBufferProducer>& gbc,
2063         const sp<Layer>& lbc)
2064 {
2065     // add this layer to the current state list
2066     {
2067         Mutex::Autolock _l(mStateLock);
2068         if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2069             return NO_MEMORY;
2070         }
2071         mCurrentState.layersSortedByZ.add(lbc);
2072         mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2073     }
2074
2075     // attach this layer to the client
2076     client->attachLayer(handle, lbc);
2077
2078     return NO_ERROR;
2079 }
2080
2081 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
2082     Mutex::Autolock _l(mStateLock);
2083     ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2084     if (index >= 0) {
2085         mLayersPendingRemoval.push(layer);
2086         mLayersRemoved = true;
2087         setTransactionFlags(eTransactionNeeded);
2088         return NO_ERROR;
2089     }
2090     return status_t(index);
2091 }
2092
2093 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2094     return android_atomic_release_load(&mTransactionFlags);
2095 }
2096
2097 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2098     return android_atomic_and(~flags, &mTransactionFlags) & flags;
2099 }
2100
2101 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2102     uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2103     if ((old & flags)==0) { // wake the server up
2104         signalTransaction();
2105     }
2106     return old;
2107 }
2108
2109 void SurfaceFlinger::setTransactionState(
2110         const Vector<ComposerState>& state,
2111         const Vector<DisplayState>& displays,
2112         uint32_t flags)
2113 {
2114     ATRACE_CALL();
2115     Mutex::Autolock _l(mStateLock);
2116     uint32_t transactionFlags = 0;
2117
2118     if (flags & eAnimation) {
2119         // For window updates that are part of an animation we must wait for
2120         // previous animation "frames" to be handled.
2121         while (mAnimTransactionPending) {
2122             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2123             if (CC_UNLIKELY(err != NO_ERROR)) {
2124                 // just in case something goes wrong in SF, return to the
2125                 // caller after a few seconds.
2126                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2127                         "waiting for previous animation frame");
2128                 mAnimTransactionPending = false;
2129                 break;
2130             }
2131         }
2132     }
2133
2134     size_t count = displays.size();
2135     for (size_t i=0 ; i<count ; i++) {
2136         const DisplayState& s(displays[i]);
2137         transactionFlags |= setDisplayStateLocked(s);
2138     }
2139
2140     count = state.size();
2141     for (size_t i=0 ; i<count ; i++) {
2142         const ComposerState& s(state[i]);
2143         // Here we need to check that the interface we're given is indeed
2144         // one of our own. A malicious client could give us a NULL
2145         // IInterface, or one of its own or even one of our own but a
2146         // different type. All these situations would cause us to crash.
2147         //
2148         // NOTE: it would be better to use RTTI as we could directly check
2149         // that we have a Client*. however, RTTI is disabled in Android.
2150         if (s.client != NULL) {
2151             sp<IBinder> binder = IInterface::asBinder(s.client);
2152             if (binder != NULL) {
2153                 String16 desc(binder->getInterfaceDescriptor());
2154                 if (desc == ISurfaceComposerClient::descriptor) {
2155                     sp<Client> client( static_cast<Client *>(s.client.get()) );
2156                     transactionFlags |= setClientStateLocked(client, s.state);
2157                 }
2158             }
2159         }
2160     }
2161
2162     if (transactionFlags) {
2163         // this triggers the transaction
2164         setTransactionFlags(transactionFlags);
2165
2166         // if this is a synchronous transaction, wait for it to take effect
2167         // before returning.
2168         if (flags & eSynchronous) {
2169             mTransactionPending = true;
2170         }
2171         if (flags & eAnimation) {
2172             mAnimTransactionPending = true;
2173         }
2174         while (mTransactionPending) {
2175             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2176             if (CC_UNLIKELY(err != NO_ERROR)) {
2177                 // just in case something goes wrong in SF, return to the
2178                 // called after a few seconds.
2179                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2180                 mTransactionPending = false;
2181                 break;
2182             }
2183         }
2184     }
2185 }
2186
2187 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2188 {
2189     ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2190     if (dpyIdx < 0)
2191         return 0;
2192
2193     uint32_t flags = 0;
2194     DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2195     if (disp.isValid()) {
2196         const uint32_t what = s.what;
2197         if (what & DisplayState::eSurfaceChanged) {
2198             if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2199                 disp.surface = s.surface;
2200                 flags |= eDisplayTransactionNeeded;
2201             }
2202         }
2203         if (what & DisplayState::eLayerStackChanged) {
2204             if (disp.layerStack != s.layerStack) {
2205                 disp.layerStack = s.layerStack;
2206                 flags |= eDisplayTransactionNeeded;
2207             }
2208         }
2209         if (what & DisplayState::eDisplayProjectionChanged) {
2210             if (disp.orientation != s.orientation) {
2211                 disp.orientation = s.orientation;
2212                 flags |= eDisplayTransactionNeeded;
2213             }
2214             if (disp.frame != s.frame) {
2215                 disp.frame = s.frame;
2216                 flags |= eDisplayTransactionNeeded;
2217             }
2218             if (disp.viewport != s.viewport) {
2219                 disp.viewport = s.viewport;
2220                 flags |= eDisplayTransactionNeeded;
2221             }
2222         }
2223         if (what & DisplayState::eDisplaySizeChanged) {
2224             if (disp.width != s.width) {
2225                 disp.width = s.width;
2226                 flags |= eDisplayTransactionNeeded;
2227             }
2228             if (disp.height != s.height) {
2229                 disp.height = s.height;
2230                 flags |= eDisplayTransactionNeeded;
2231             }
2232         }
2233     }
2234     return flags;
2235 }
2236
2237 uint32_t SurfaceFlinger::setClientStateLocked(
2238         const sp<Client>& client,
2239         const layer_state_t& s)
2240 {
2241     uint32_t flags = 0;
2242     sp<Layer> layer(client->getLayerUser(s.surface));
2243     if (layer != 0) {
2244         const uint32_t what = s.what;
2245         if (what & layer_state_t::ePositionChanged) {
2246             if (layer->setPosition(s.x, s.y))
2247                 flags |= eTraversalNeeded;
2248         }
2249         if (what & layer_state_t::eLayerChanged) {
2250             // NOTE: index needs to be calculated before we update the state
2251             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2252             if (layer->setLayer(s.z) && idx >= 0) {
2253                 mCurrentState.layersSortedByZ.removeAt(idx);
2254                 mCurrentState.layersSortedByZ.add(layer);
2255                 // we need traversal (state changed)
2256                 // AND transaction (list changed)
2257                 flags |= eTransactionNeeded|eTraversalNeeded;
2258             }
2259         }
2260         if (what & layer_state_t::eSizeChanged) {
2261             if (layer->setSize(s.w, s.h)) {
2262                 flags |= eTraversalNeeded;
2263             }
2264         }
2265         if (what & layer_state_t::eAlphaChanged) {
2266             if (layer->setAlpha(s.alpha))
2267                 flags |= eTraversalNeeded;
2268         }
2269         if (what & layer_state_t::eMatrixChanged) {
2270             if (layer->setMatrix(s.matrix))
2271                 flags |= eTraversalNeeded;
2272         }
2273         if (what & layer_state_t::eTransparentRegionChanged) {
2274             if (layer->setTransparentRegionHint(s.transparentRegion))
2275                 flags |= eTraversalNeeded;
2276         }
2277         if (what & layer_state_t::eFlagsChanged) {
2278             if (layer->setFlags(s.flags, s.mask))
2279                 flags |= eTraversalNeeded;
2280         }
2281         if (what & layer_state_t::eCropChanged) {
2282             if (layer->setCrop(s.crop))
2283                 flags |= eTraversalNeeded;
2284         }
2285         if (what & layer_state_t::eFinalCropChanged) {
2286             if (layer->setFinalCrop(s.finalCrop))
2287                 flags |= eTraversalNeeded;
2288         }
2289         if (what & layer_state_t::eLayerStackChanged) {
2290             // NOTE: index needs to be calculated before we update the state
2291             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2292             if (layer->setLayerStack(s.layerStack) && idx >= 0) {
2293                 mCurrentState.layersSortedByZ.removeAt(idx);
2294                 mCurrentState.layersSortedByZ.add(layer);
2295                 // we need traversal (state changed)
2296                 // AND transaction (list changed)
2297                 flags |= eTransactionNeeded|eTraversalNeeded;
2298             }
2299         }
2300         if (what & layer_state_t::eDeferTransaction) {
2301             layer->deferTransactionUntil(s.handle, s.frameNumber);
2302             // We don't trigger a traversal here because if no other state is
2303             // changed, we don't want this to cause any more work
2304         }
2305     }
2306     return flags;
2307 }
2308
2309 status_t SurfaceFlinger::createLayer(
2310         const String8& name,
2311         const sp<Client>& client,
2312         uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2313         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2314 {
2315     //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2316     if (int32_t(w|h) < 0) {
2317         ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2318                 int(w), int(h));
2319         return BAD_VALUE;
2320     }
2321
2322     status_t result = NO_ERROR;
2323
2324     sp<Layer> layer;
2325
2326     switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2327         case ISurfaceComposerClient::eFXSurfaceNormal:
2328             result = createNormalLayer(client,
2329                     name, w, h, flags, format,
2330                     handle, gbp, &layer);
2331             break;
2332         case ISurfaceComposerClient::eFXSurfaceDim:
2333             result = createDimLayer(client,
2334                     name, w, h, flags,
2335                     handle, gbp, &layer);
2336             break;
2337         default:
2338             result = BAD_VALUE;
2339             break;
2340     }
2341
2342     if (result != NO_ERROR) {
2343         return result;
2344     }
2345
2346     result = addClientLayer(client, *handle, *gbp, layer);
2347     if (result != NO_ERROR) {
2348         return result;
2349     }
2350
2351     setTransactionFlags(eTransactionNeeded);
2352     return result;
2353 }
2354
2355 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2356         const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2357         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2358 {
2359     // initialize the surfaces
2360     switch (format) {
2361     case PIXEL_FORMAT_TRANSPARENT:
2362     case PIXEL_FORMAT_TRANSLUCENT:
2363         format = PIXEL_FORMAT_RGBA_8888;
2364         break;
2365     case PIXEL_FORMAT_OPAQUE:
2366         format = PIXEL_FORMAT_RGBX_8888;
2367         break;
2368     }
2369
2370     *outLayer = new Layer(this, client, name, w, h, flags);
2371     status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2372     if (err == NO_ERROR) {
2373         *handle = (*outLayer)->getHandle();
2374         *gbp = (*outLayer)->getProducer();
2375     }
2376
2377     ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2378     return err;
2379 }
2380
2381 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2382         const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2383         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2384 {
2385     *outLayer = new LayerDim(this, client, name, w, h, flags);
2386     *handle = (*outLayer)->getHandle();
2387     *gbp = (*outLayer)->getProducer();
2388     return NO_ERROR;
2389 }
2390
2391 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2392 {
2393     // called by the window manager when it wants to remove a Layer
2394     status_t err = NO_ERROR;
2395     sp<Layer> l(client->getLayerUser(handle));
2396     if (l != NULL) {
2397         err = removeLayer(l);
2398         ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2399                 "error removing layer=%p (%s)", l.get(), strerror(-err));
2400     }
2401     return err;
2402 }
2403
2404 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2405 {
2406     // called by ~LayerCleaner() when all references to the IBinder (handle)
2407     // are gone
2408     status_t err = NO_ERROR;
2409     sp<Layer> l(layer.promote());
2410     if (l != NULL) {
2411         err = removeLayer(l);
2412         ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2413                 "error removing layer=%p (%s)", l.get(), strerror(-err));
2414     }
2415     return err;
2416 }
2417
2418 // ---------------------------------------------------------------------------
2419
2420 void SurfaceFlinger::onInitializeDisplays() {
2421     // reset screen orientation and use primary layer stack
2422     Vector<ComposerState> state;
2423     Vector<DisplayState> displays;
2424     DisplayState d;
2425     d.what = DisplayState::eDisplayProjectionChanged |
2426              DisplayState::eLayerStackChanged;
2427     d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2428     d.layerStack = 0;
2429     d.orientation = DisplayState::eOrientationDefault;
2430     d.frame.makeInvalid();
2431     d.viewport.makeInvalid();
2432     d.width = 0;
2433     d.height = 0;
2434     displays.add(d);
2435     setTransactionState(state, displays, 0);
2436     setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2437
2438     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2439     const nsecs_t period = activeConfig->getVsyncPeriod();
2440     mAnimFrameTracker.setDisplayRefreshPeriod(period);
2441 }
2442
2443 void SurfaceFlinger::initializeDisplays() {
2444     class MessageScreenInitialized : public MessageBase {
2445         SurfaceFlinger* flinger;
2446     public:
2447         MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2448         virtual bool handler() {
2449             flinger->onInitializeDisplays();
2450             return true;
2451         }
2452     };
2453     sp<MessageBase> msg = new MessageScreenInitialized(this);
2454     postMessageAsync(msg);  // we may be called from main thread, use async message
2455 }
2456
2457 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2458         int mode) {
2459     ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2460             this);
2461     int32_t type = hw->getDisplayType();
2462     int currentMode = hw->getPowerMode();
2463
2464     if (mode == currentMode) {
2465         ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2466         return;
2467     }
2468
2469     hw->setPowerMode(mode);
2470     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2471         ALOGW("Trying to set power mode for virtual display");
2472         return;
2473     }
2474
2475     if (currentMode == HWC_POWER_MODE_OFF) {
2476         getHwComposer().setPowerMode(type, mode);
2477         if (type == DisplayDevice::DISPLAY_PRIMARY) {
2478             // FIXME: eventthread only knows about the main display right now
2479             mEventThread->onScreenAcquired();
2480             resyncToHardwareVsync(true);
2481         }
2482
2483         mVisibleRegionsDirty = true;
2484         mHasPoweredOff = true;
2485         repaintEverything();
2486     } else if (mode == HWC_POWER_MODE_OFF) {
2487         if (type == DisplayDevice::DISPLAY_PRIMARY) {
2488             disableHardwareVsync(true); // also cancels any in-progress resync
2489
2490             // FIXME: eventthread only knows about the main display right now
2491             mEventThread->onScreenReleased();
2492         }
2493
2494         getHwComposer().setPowerMode(type, mode);
2495         mVisibleRegionsDirty = true;
2496         // from this point on, SF will stop drawing on this display
2497     } else {
2498         getHwComposer().setPowerMode(type, mode);
2499     }
2500 }
2501
2502 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2503     class MessageSetPowerMode: public MessageBase {
2504         SurfaceFlinger& mFlinger;
2505         sp<IBinder> mDisplay;
2506         int mMode;
2507     public:
2508         MessageSetPowerMode(SurfaceFlinger& flinger,
2509                 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2510                     mDisplay(disp) { mMode = mode; }
2511         virtual bool handler() {
2512             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2513             if (hw == NULL) {
2514                 ALOGE("Attempt to set power mode = %d for null display %p",
2515                         mMode, mDisplay.get());
2516             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2517                 ALOGW("Attempt to set power mode = %d for virtual display",
2518                         mMode);
2519             } else {
2520                 mFlinger.setPowerModeInternal(hw, mMode);
2521             }
2522             return true;
2523         }
2524     };
2525     sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2526     postMessageSync(msg);
2527 }
2528
2529 // ---------------------------------------------------------------------------
2530
2531 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2532 {
2533     String8 result;
2534
2535     IPCThreadState* ipc = IPCThreadState::self();
2536     const int pid = ipc->getCallingPid();
2537     const int uid = ipc->getCallingUid();
2538     if ((uid != AID_SHELL) &&
2539             !PermissionCache::checkPermission(sDump, pid, uid)) {
2540         result.appendFormat("Permission Denial: "
2541                 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2542     } else {
2543         // Try to get the main lock, but give up after one second
2544         // (this would indicate SF is stuck, but we want to be able to
2545         // print something in dumpsys).
2546         status_t err = mStateLock.timedLock(s2ns(1));
2547         bool locked = (err == NO_ERROR);
2548         if (!locked) {
2549             result.appendFormat(
2550                     "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2551                     "dumping anyways (no locks held)\n", strerror(-err), err);
2552         }
2553
2554         bool dumpAll = true;
2555         size_t index = 0;
2556         size_t numArgs = args.size();
2557         if (numArgs) {
2558             if ((index < numArgs) &&
2559                     (args[index] == String16("--list"))) {
2560                 index++;
2561                 listLayersLocked(args, index, result);
2562                 dumpAll = false;
2563             }
2564
2565             if ((index < numArgs) &&
2566                     (args[index] == String16("--latency"))) {
2567                 index++;
2568                 dumpStatsLocked(args, index, result);
2569                 dumpAll = false;
2570             }
2571
2572             if ((index < numArgs) &&
2573                     (args[index] == String16("--latency-clear"))) {
2574                 index++;
2575                 clearStatsLocked(args, index, result);
2576                 dumpAll = false;
2577             }
2578
2579             if ((index < numArgs) &&
2580                     (args[index] == String16("--dispsync"))) {
2581                 index++;
2582                 mPrimaryDispSync.dump(result);
2583                 dumpAll = false;
2584             }
2585
2586             if ((index < numArgs) &&
2587                     (args[index] == String16("--static-screen"))) {
2588                 index++;
2589                 dumpStaticScreenStats(result);
2590                 dumpAll = false;
2591             }
2592
2593 #ifdef ENABLE_FENCE_TRACKING
2594             if ((index < numArgs) &&
2595                     (args[index] == String16("--fences"))) {
2596                 index++;
2597                 mFenceTracker.dump(&result);
2598                 dumpAll = false;
2599             }
2600 #endif
2601         }
2602
2603         if (dumpAll) {
2604             dumpAllLocked(args, index, result);
2605         }
2606
2607         if (locked) {
2608             mStateLock.unlock();
2609         }
2610     }
2611     write(fd, result.string(), result.size());
2612     return NO_ERROR;
2613 }
2614
2615 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2616         size_t& /* index */, String8& result) const
2617 {
2618     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2619     const size_t count = currentLayers.size();
2620     for (size_t i=0 ; i<count ; i++) {
2621         const sp<Layer>& layer(currentLayers[i]);
2622         result.appendFormat("%s\n", layer->getName().string());
2623     }
2624 }
2625
2626 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2627         String8& result) const
2628 {
2629     String8 name;
2630     if (index < args.size()) {
2631         name = String8(args[index]);
2632         index++;
2633     }
2634
2635     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2636     const nsecs_t period = activeConfig->getVsyncPeriod();
2637     result.appendFormat("%" PRId64 "\n", period);
2638
2639     if (name.isEmpty()) {
2640         mAnimFrameTracker.dumpStats(result);
2641     } else {
2642         const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2643         const size_t count = currentLayers.size();
2644         for (size_t i=0 ; i<count ; i++) {
2645             const sp<Layer>& layer(currentLayers[i]);
2646             if (name == layer->getName()) {
2647                 layer->dumpFrameStats(result);
2648             }
2649         }
2650     }
2651 }
2652
2653 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2654         String8& /* result */)
2655 {
2656     String8 name;
2657     if (index < args.size()) {
2658         name = String8(args[index]);
2659         index++;
2660     }
2661
2662     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2663     const size_t count = currentLayers.size();
2664     for (size_t i=0 ; i<count ; i++) {
2665         const sp<Layer>& layer(currentLayers[i]);
2666         if (name.isEmpty() || (name == layer->getName())) {
2667             layer->clearFrameStats();
2668         }
2669     }
2670
2671     mAnimFrameTracker.clearStats();
2672 }
2673
2674 // This should only be called from the main thread.  Otherwise it would need
2675 // the lock and should use mCurrentState rather than mDrawingState.
2676 void SurfaceFlinger::logFrameStats() {
2677     const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2678     const size_t count = drawingLayers.size();
2679     for (size_t i=0 ; i<count ; i++) {
2680         const sp<Layer>& layer(drawingLayers[i]);
2681         layer->logFrameStats();
2682     }
2683
2684     mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2685 }
2686
2687 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2688 {
2689     static const char* config =
2690             " [sf"
2691 #ifdef HAS_CONTEXT_PRIORITY
2692             " HAS_CONTEXT_PRIORITY"
2693 #endif
2694 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2695             " NEVER_DEFAULT_TO_ASYNC_MODE"
2696 #endif
2697 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2698             " TARGET_DISABLE_TRIPLE_BUFFERING"
2699 #endif
2700             "]";
2701     result.append(config);
2702 }
2703
2704 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2705 {
2706     result.appendFormat("Static screen stats:\n");
2707     for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2708         float bucketTimeSec = mFrameBuckets[b] / 1e9;
2709         float percent = 100.0f *
2710                 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2711         result.appendFormat("  < %zd frames: %.3f s (%.1f%%)\n",
2712                 b + 1, bucketTimeSec, percent);
2713     }
2714     float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2715     float percent = 100.0f *
2716             static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2717     result.appendFormat("  %zd+ frames: %.3f s (%.1f%%)\n",
2718             NUM_BUCKETS - 1, bucketTimeSec, percent);
2719 }
2720
2721 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2722         String8& result) const
2723 {
2724     bool colorize = false;
2725     if (index < args.size()
2726             && (args[index] == String16("--color"))) {
2727         colorize = true;
2728         index++;
2729     }
2730
2731     Colorizer colorizer(colorize);
2732
2733     // figure out if we're stuck somewhere
2734     const nsecs_t now = systemTime();
2735     const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2736     const nsecs_t inTransaction(mDebugInTransaction);
2737     nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2738     nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2739
2740     /*
2741      * Dump library configuration.
2742      */
2743
2744     colorizer.bold(result);
2745     result.append("Build configuration:");
2746     colorizer.reset(result);
2747     appendSfConfigString(result);
2748     appendUiConfigString(result);
2749     appendGuiConfigString(result);
2750     result.append("\n");
2751
2752     colorizer.bold(result);
2753     result.append("Sync configuration: ");
2754     colorizer.reset(result);
2755     result.append(SyncFeatures::getInstance().toString());
2756     result.append("\n");
2757
2758     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2759
2760     colorizer.bold(result);
2761     result.append("DispSync configuration: ");
2762     colorizer.reset(result);
2763     result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2764             "present offset %d ns (refresh %" PRId64 " ns)",
2765         vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2766         PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
2767     result.append("\n");
2768
2769     // Dump static screen stats
2770     result.append("\n");
2771     dumpStaticScreenStats(result);
2772     result.append("\n");
2773
2774     /*
2775      * Dump the visible layer list
2776      */
2777     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2778     const size_t count = currentLayers.size();
2779     colorizer.bold(result);
2780     result.appendFormat("Visible layers (count = %zu)\n", count);
2781     colorizer.reset(result);
2782     for (size_t i=0 ; i<count ; i++) {
2783         const sp<Layer>& layer(currentLayers[i]);
2784         layer->dump(result, colorizer);
2785     }
2786
2787     /*
2788      * Dump Display state
2789      */
2790
2791     colorizer.bold(result);
2792     result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2793     colorizer.reset(result);
2794     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2795         const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2796         hw->dump(result);
2797     }
2798
2799     /*
2800      * Dump SurfaceFlinger global state
2801      */
2802
2803     colorizer.bold(result);
2804     result.append("SurfaceFlinger global state:\n");
2805     colorizer.reset(result);
2806
2807     HWComposer& hwc(getHwComposer());
2808     sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2809
2810     colorizer.bold(result);
2811     result.appendFormat("EGL implementation : %s\n",
2812             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2813     colorizer.reset(result);
2814     result.appendFormat("%s\n",
2815             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2816
2817     mRenderEngine->dump(result);
2818
2819     hw->undefinedRegion.dump(result, "undefinedRegion");
2820     result.appendFormat("  orientation=%d, isDisplayOn=%d\n",
2821             hw->getOrientation(), hw->isDisplayOn());
2822     result.appendFormat(
2823             "  last eglSwapBuffers() time: %f us\n"
2824             "  last transaction time     : %f us\n"
2825             "  transaction-flags         : %08x\n"
2826             "  refresh-rate              : %f fps\n"
2827             "  x-dpi                     : %f\n"
2828             "  y-dpi                     : %f\n"
2829             "  gpu_to_cpu_unsupported    : %d\n"
2830             ,
2831             mLastSwapBufferTime/1000.0,
2832             mLastTransactionTime/1000.0,
2833             mTransactionFlags,
2834             1e9 / activeConfig->getVsyncPeriod(),
2835             activeConfig->getDpiX(),
2836             activeConfig->getDpiY(),
2837             !mGpuToCpuSupported);
2838
2839     result.appendFormat("  eglSwapBuffers time: %f us\n",
2840             inSwapBuffersDuration/1000.0);
2841
2842     result.appendFormat("  transaction time: %f us\n",
2843             inTransactionDuration/1000.0);
2844
2845     /*
2846      * VSYNC state
2847      */
2848     mEventThread->dump(result);
2849
2850     /*
2851      * Dump HWComposer state
2852      */
2853     colorizer.bold(result);
2854     result.append("h/w composer state:\n");
2855     colorizer.reset(result);
2856     bool hwcDisabled = mDebugDisableHWC || mDebugRegion || mDaltonize ||
2857             mHasColorMatrix;
2858     result.appendFormat("  h/w composer %s\n",
2859             hwcDisabled ? "disabled" : "enabled");
2860     hwc.dump(result);
2861
2862     /*
2863      * Dump gralloc state
2864      */
2865     const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2866     alloc.dump(result);
2867 }
2868
2869 const Vector< sp<Layer> >&
2870 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2871     // Note: mStateLock is held here
2872     wp<IBinder> dpy;
2873     for (size_t i=0 ; i<mDisplays.size() ; i++) {
2874         if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2875             dpy = mDisplays.keyAt(i);
2876             break;
2877         }
2878     }
2879     if (dpy == NULL) {
2880         ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2881         // Just use the primary display so we have something to return
2882         dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2883     }
2884     return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2885 }
2886
2887 bool SurfaceFlinger::startDdmConnection()
2888 {
2889     void* libddmconnection_dso =
2890             dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2891     if (!libddmconnection_dso) {
2892         return false;
2893     }
2894     void (*DdmConnection_start)(const char* name);
2895     DdmConnection_start =
2896             (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2897     if (!DdmConnection_start) {
2898         dlclose(libddmconnection_dso);
2899         return false;
2900     }
2901     (*DdmConnection_start)(getServiceName());
2902     return true;
2903 }
2904
2905 status_t SurfaceFlinger::onTransact(
2906     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2907 {
2908     switch (code) {
2909         case CREATE_CONNECTION:
2910         case CREATE_DISPLAY:
2911         case SET_TRANSACTION_STATE:
2912         case BOOT_FINISHED:
2913         case CLEAR_ANIMATION_FRAME_STATS:
2914         case GET_ANIMATION_FRAME_STATS:
2915         case SET_POWER_MODE:
2916         case GET_HDR_CAPABILITIES:
2917         {
2918             // codes that require permission check
2919             IPCThreadState* ipc = IPCThreadState::self();
2920             const int pid = ipc->getCallingPid();
2921             const int uid = ipc->getCallingUid();
2922             if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
2923                     !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2924                 ALOGE("Permission Denial: "
2925                         "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2926                 return PERMISSION_DENIED;
2927             }
2928             break;
2929         }
2930         case CAPTURE_SCREEN:
2931         {
2932             // codes that require permission check
2933             IPCThreadState* ipc = IPCThreadState::self();
2934             const int pid = ipc->getCallingPid();
2935             const int uid = ipc->getCallingUid();
2936             if ((uid != AID_GRAPHICS) &&
2937                     !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2938                 ALOGE("Permission Denial: "
2939                         "can't read framebuffer pid=%d, uid=%d", pid, uid);
2940                 return PERMISSION_DENIED;
2941             }
2942             break;
2943         }
2944     }
2945
2946     status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2947     if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2948         CHECK_INTERFACE(ISurfaceComposer, data, reply);
2949         if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2950             IPCThreadState* ipc = IPCThreadState::self();
2951             const int pid = ipc->getCallingPid();
2952             const int uid = ipc->getCallingUid();
2953             ALOGE("Permission Denial: "
2954                     "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2955             return PERMISSION_DENIED;
2956         }
2957         int n;
2958         switch (code) {
2959             case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2960             case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2961                 return NO_ERROR;
2962             case 1002:  // SHOW_UPDATES
2963                 n = data.readInt32();
2964                 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2965                 invalidateHwcGeometry();
2966                 repaintEverything();
2967                 return NO_ERROR;
2968             case 1004:{ // repaint everything
2969                 repaintEverything();
2970                 return NO_ERROR;
2971             }
2972             case 1005:{ // force transaction
2973                 setTransactionFlags(
2974                         eTransactionNeeded|
2975                         eDisplayTransactionNeeded|
2976                         eTraversalNeeded);
2977                 return NO_ERROR;
2978             }
2979             case 1006:{ // send empty update
2980                 signalRefresh();
2981                 return NO_ERROR;
2982             }
2983             case 1008:  // toggle use of hw composer
2984                 n = data.readInt32();
2985                 mDebugDisableHWC = n ? 1 : 0;
2986                 invalidateHwcGeometry();
2987                 repaintEverything();
2988                 return NO_ERROR;
2989             case 1009:  // toggle use of transform hint
2990                 n = data.readInt32();
2991                 mDebugDisableTransformHint = n ? 1 : 0;
2992                 invalidateHwcGeometry();
2993                 repaintEverything();
2994                 return NO_ERROR;
2995             case 1010:  // interrogate.
2996                 reply->writeInt32(0);
2997                 reply->writeInt32(0);
2998                 reply->writeInt32(mDebugRegion);
2999                 reply->writeInt32(0);
3000                 reply->writeInt32(mDebugDisableHWC);
3001                 return NO_ERROR;
3002             case 1013: {
3003                 Mutex::Autolock _l(mStateLock);
3004                 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3005                 reply->writeInt32(hw->getPageFlipCount());
3006                 return NO_ERROR;
3007             }
3008             case 1014: {
3009                 // daltonize
3010                 n = data.readInt32();
3011                 switch (n % 10) {
3012                     case 1: mDaltonizer.setType(Daltonizer::protanomaly);   break;
3013                     case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3014                     case 3: mDaltonizer.setType(Daltonizer::tritanomaly);   break;
3015                 }
3016                 if (n >= 10) {
3017                     mDaltonizer.setMode(Daltonizer::correction);
3018                 } else {
3019                     mDaltonizer.setMode(Daltonizer::simulation);
3020                 }
3021                 mDaltonize = n > 0;
3022                 invalidateHwcGeometry();
3023                 repaintEverything();
3024                 return NO_ERROR;
3025             }
3026             case 1015: {
3027                 // apply a color matrix
3028                 n = data.readInt32();
3029                 mHasColorMatrix = n ? 1 : 0;
3030                 if (n) {
3031                     // color matrix is sent as mat3 matrix followed by vec3
3032                     // offset, then packed into a mat4 where the last row is
3033                     // the offset and extra values are 0
3034                     for (size_t i = 0 ; i < 4; i++) {
3035                       for (size_t j = 0; j < 4; j++) {
3036                           mColorMatrix[i][j] = data.readFloat();
3037                       }
3038                     }
3039                 } else {
3040                     mColorMatrix = mat4();
3041                 }
3042                 invalidateHwcGeometry();
3043                 repaintEverything();
3044                 return NO_ERROR;
3045             }
3046             // This is an experimental interface
3047             // Needs to be shifted to proper binder interface when we productize
3048             case 1016: {
3049                 n = data.readInt32();
3050                 mPrimaryDispSync.setRefreshSkipCount(n);
3051                 return NO_ERROR;
3052             }
3053             case 1017: {
3054                 n = data.readInt32();
3055                 mForceFullDamage = static_cast<bool>(n);
3056                 return NO_ERROR;
3057             }
3058             case 1018: { // Modify Choreographer's phase offset
3059                 n = data.readInt32();
3060                 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3061                 return NO_ERROR;
3062             }
3063             case 1019: { // Modify SurfaceFlinger's phase offset
3064                 n = data.readInt32();
3065                 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3066                 return NO_ERROR;
3067             }
3068         }
3069     }
3070     return err;
3071 }
3072
3073 void SurfaceFlinger::repaintEverything() {
3074     android_atomic_or(1, &mRepaintEverything);
3075     signalTransaction();
3076 }
3077
3078 // ---------------------------------------------------------------------------
3079 // Capture screen into an IGraphiBufferProducer
3080 // ---------------------------------------------------------------------------
3081
3082 /* The code below is here to handle b/8734824
3083  *
3084  * We create a IGraphicBufferProducer wrapper that forwards all calls
3085  * from the surfaceflinger thread to the calling binder thread, where they
3086  * are executed. This allows the calling thread in the calling process to be
3087  * reused and not depend on having "enough" binder threads to handle the
3088  * requests.
3089  */
3090 class GraphicProducerWrapper : public BBinder, public MessageHandler {
3091     /* Parts of GraphicProducerWrapper are run on two different threads,
3092      * communicating by sending messages via Looper but also by shared member
3093      * data. Coherence maintenance is subtle and in places implicit (ugh).
3094      *
3095      * Don't rely on Looper's sendMessage/handleMessage providing
3096      * release/acquire semantics for any data not actually in the Message.
3097      * Data going from surfaceflinger to binder threads needs to be
3098      * synchronized explicitly.
3099      *
3100      * Barrier open/wait do provide release/acquire semantics. This provides
3101      * implicit synchronization for data coming back from binder to
3102      * surfaceflinger threads.
3103      */
3104
3105     sp<IGraphicBufferProducer> impl;
3106     sp<Looper> looper;
3107     status_t result;
3108     bool exitPending;
3109     bool exitRequested;
3110     Barrier barrier;
3111     uint32_t code;
3112     Parcel const* data;
3113     Parcel* reply;
3114
3115     enum {
3116         MSG_API_CALL,
3117         MSG_EXIT
3118     };
3119
3120     /*
3121      * Called on surfaceflinger thread. This is called by our "fake"
3122      * BpGraphicBufferProducer. We package the data and reply Parcel and
3123      * forward them to the binder thread.
3124      */
3125     virtual status_t transact(uint32_t code,
3126             const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3127         this->code = code;
3128         this->data = &data;
3129         this->reply = reply;
3130         if (exitPending) {
3131             // if we've exited, we run the message synchronously right here.
3132             // note (JH): as far as I can tell from looking at the code, this
3133             // never actually happens. if it does, i'm not sure if it happens
3134             // on the surfaceflinger or binder thread.
3135             handleMessage(Message(MSG_API_CALL));
3136         } else {
3137             barrier.close();
3138             // Prevent stores to this->{code, data, reply} from being
3139             // reordered later than the construction of Message.
3140             atomic_thread_fence(memory_order_release);
3141             looper->sendMessage(this, Message(MSG_API_CALL));
3142             barrier.wait();
3143         }
3144         return result;
3145     }
3146
3147     /*
3148      * here we run on the binder thread. All we've got to do is
3149      * call the real BpGraphicBufferProducer.
3150      */
3151     virtual void handleMessage(const Message& message) {
3152         int what = message.what;
3153         // Prevent reads below from happening before the read from Message
3154         atomic_thread_fence(memory_order_acquire);
3155         if (what == MSG_API_CALL) {
3156             result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3157             barrier.open();
3158         } else if (what == MSG_EXIT) {
3159             exitRequested = true;
3160         }
3161     }
3162
3163 public:
3164     GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3165     :   impl(impl),
3166         looper(new Looper(true)),
3167         result(NO_ERROR),
3168         exitPending(false),
3169         exitRequested(false),
3170         code(0),
3171         data(NULL),
3172         reply(NULL)
3173     {}
3174
3175     // Binder thread
3176     status_t waitForResponse() {
3177         do {
3178             looper->pollOnce(-1);
3179         } while (!exitRequested);
3180         return result;
3181     }
3182
3183     // Client thread
3184     void exit(status_t result) {
3185         this->result = result;
3186         exitPending = true;
3187         // Ensure this->result is visible to the binder thread before it
3188         // handles the message.
3189         atomic_thread_fence(memory_order_release);
3190         looper->sendMessage(this, Message(MSG_EXIT));
3191     }
3192 };
3193
3194
3195 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3196         const sp<IGraphicBufferProducer>& producer,
3197         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3198         uint32_t minLayerZ, uint32_t maxLayerZ,
3199         bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3200
3201     if (CC_UNLIKELY(display == 0))
3202         return BAD_VALUE;
3203
3204     if (CC_UNLIKELY(producer == 0))
3205         return BAD_VALUE;
3206
3207     // if we have secure windows on this display, never allow the screen capture
3208     // unless the producer interface is local (i.e.: we can take a screenshot for
3209     // ourselves).
3210     bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3211
3212     // Convert to surfaceflinger's internal rotation type.
3213     Transform::orientation_flags rotationFlags;
3214     switch (rotation) {
3215         case ISurfaceComposer::eRotateNone:
3216             rotationFlags = Transform::ROT_0;
3217             break;
3218         case ISurfaceComposer::eRotate90:
3219             rotationFlags = Transform::ROT_90;
3220             break;
3221         case ISurfaceComposer::eRotate180:
3222             rotationFlags = Transform::ROT_180;
3223             break;
3224         case ISurfaceComposer::eRotate270:
3225             rotationFlags = Transform::ROT_270;
3226             break;
3227         default:
3228             rotationFlags = Transform::ROT_0;
3229             ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3230             break;
3231     }
3232
3233     class MessageCaptureScreen : public MessageBase {
3234         SurfaceFlinger* flinger;
3235         sp<IBinder> display;
3236         sp<IGraphicBufferProducer> producer;
3237         Rect sourceCrop;
3238         uint32_t reqWidth, reqHeight;
3239         uint32_t minLayerZ,maxLayerZ;
3240         bool useIdentityTransform;
3241         Transform::orientation_flags rotation;
3242         status_t result;
3243         bool isLocalScreenshot;
3244     public:
3245         MessageCaptureScreen(SurfaceFlinger* flinger,
3246                 const sp<IBinder>& display,
3247                 const sp<IGraphicBufferProducer>& producer,
3248                 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3249                 uint32_t minLayerZ, uint32_t maxLayerZ,
3250                 bool useIdentityTransform,
3251                 Transform::orientation_flags rotation,
3252                 bool isLocalScreenshot)
3253             : flinger(flinger), display(display), producer(producer),
3254               sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3255               minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3256               useIdentityTransform(useIdentityTransform),
3257               rotation(rotation), result(PERMISSION_DENIED),
3258               isLocalScreenshot(isLocalScreenshot)
3259         {
3260         }
3261         status_t getResult() const {
3262             return result;
3263         }
3264         virtual bool handler() {
3265             Mutex::Autolock _l(flinger->mStateLock);
3266             sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3267             result = flinger->captureScreenImplLocked(hw, producer,
3268                     sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3269                     useIdentityTransform, rotation, isLocalScreenshot);
3270             static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3271             return true;
3272         }
3273     };
3274
3275     // make sure to process transactions before screenshots -- a transaction
3276     // might already be pending but scheduled for VSYNC; this guarantees we
3277     // will handle it before the screenshot. When VSYNC finally arrives
3278     // the scheduled transaction will be a no-op. If no transactions are
3279     // scheduled at this time, this will end-up being a no-op as well.
3280     mEventQueue.invalidateTransactionNow();
3281
3282     // this creates a "fake" BBinder which will serve as a "fake" remote
3283     // binder to receive the marshaled calls and forward them to the
3284     // real remote (a BpGraphicBufferProducer)
3285     sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3286
3287     // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3288     // which does the marshaling work forwards to our "fake remote" above.
3289     sp<MessageBase> msg = new MessageCaptureScreen(this,
3290             display, IGraphicBufferProducer::asInterface( wrapper ),
3291             sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3292             useIdentityTransform, rotationFlags, isLocalScreenshot);
3293
3294     status_t res = postMessageAsync(msg);
3295     if (res == NO_ERROR) {
3296         res = wrapper->waitForResponse();
3297     }
3298     return res;
3299 }
3300
3301
3302 void SurfaceFlinger::renderScreenImplLocked(
3303         const sp<const DisplayDevice>& hw,
3304         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3305         uint32_t minLayerZ, uint32_t maxLayerZ,
3306         bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3307 {
3308     ATRACE_CALL();
3309     RenderEngine& engine(getRenderEngine());
3310
3311     // get screen geometry
3312     const int32_t hw_w = hw->getWidth();
3313     const int32_t hw_h = hw->getHeight();
3314     const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3315                            static_cast<int32_t>(reqHeight) != hw_h;
3316
3317     // if a default or invalid sourceCrop is passed in, set reasonable values
3318     if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3319             !sourceCrop.isValid()) {
3320         sourceCrop.setLeftTop(Point(0, 0));
3321         sourceCrop.setRightBottom(Point(hw_w, hw_h));
3322     }
3323
3324     // ensure that sourceCrop is inside screen
3325     if (sourceCrop.left < 0) {
3326         ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3327     }
3328     if (sourceCrop.right > hw_w) {
3329         ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3330     }
3331     if (sourceCrop.top < 0) {
3332         ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3333     }
3334     if (sourceCrop.bottom > hw_h) {
3335         ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3336     }
3337
3338     // make sure to clear all GL error flags
3339     engine.checkErrors();
3340
3341     // set-up our viewport
3342     engine.setViewportAndProjection(
3343         reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3344     engine.disableTexturing();
3345
3346     // redraw the screen entirely...
3347     engine.clearWithColor(0, 0, 0, 1);
3348
3349     const LayerVector& layers( mDrawingState.layersSortedByZ );
3350     const size_t count = layers.size();
3351     for (size_t i=0 ; i<count ; ++i) {
3352         const sp<Layer>& layer(layers[i]);
3353         const Layer::State& state(layer->getDrawingState());
3354         if (state.layerStack == hw->getLayerStack()) {
3355             if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3356                 if (layer->isVisible()) {
3357                     if (filtering) layer->setFiltering(true);
3358                     layer->draw(hw, useIdentityTransform);
3359                     if (filtering) layer->setFiltering(false);
3360                 }
3361             }
3362         }
3363     }
3364
3365     hw->setViewportAndProjection();
3366 }
3367
3368
3369 status_t SurfaceFlinger::captureScreenImplLocked(
3370         const sp<const DisplayDevice>& hw,
3371         const sp<IGraphicBufferProducer>& producer,
3372         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3373         uint32_t minLayerZ, uint32_t maxLayerZ,
3374         bool useIdentityTransform, Transform::orientation_flags rotation,
3375         bool isLocalScreenshot)
3376 {
3377     ATRACE_CALL();
3378
3379     // get screen geometry
3380     uint32_t hw_w = hw->getWidth();
3381     uint32_t hw_h = hw->getHeight();
3382
3383     if (rotation & Transform::ROT_90) {
3384         std::swap(hw_w, hw_h);
3385     }
3386
3387     if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3388         ALOGE("size mismatch (%d, %d) > (%d, %d)",
3389                 reqWidth, reqHeight, hw_w, hw_h);
3390         return BAD_VALUE;
3391     }
3392
3393     reqWidth  = (!reqWidth)  ? hw_w : reqWidth;
3394     reqHeight = (!reqHeight) ? hw_h : reqHeight;
3395
3396     bool secureLayerIsVisible = false;
3397     const LayerVector& layers(mDrawingState.layersSortedByZ);
3398     const size_t count = layers.size();
3399     for (size_t i = 0 ; i < count ; ++i) {
3400         const sp<Layer>& layer(layers[i]);
3401         const Layer::State& state(layer->getDrawingState());
3402         if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3403                 state.z <= maxLayerZ && layer->isVisible() &&
3404                 layer->isSecure()) {
3405             secureLayerIsVisible = true;
3406         }
3407     }
3408
3409     if (!isLocalScreenshot && secureLayerIsVisible) {
3410         ALOGW("FB is protected: PERMISSION_DENIED");
3411         return PERMISSION_DENIED;
3412     }
3413
3414     // create a surface (because we're a producer, and we need to
3415     // dequeue/queue a buffer)
3416     sp<Surface> sur = new Surface(producer, false);
3417     ANativeWindow* window = sur.get();
3418
3419     status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3420     if (result == NO_ERROR) {
3421         uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3422                         GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3423
3424         int err = 0;
3425         err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3426         err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3427         err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3428         err |= native_window_set_usage(window, usage);
3429
3430         if (err == NO_ERROR) {
3431             ANativeWindowBuffer* buffer;
3432             /* TODO: Once we have the sync framework everywhere this can use
3433              * server-side waits on the fence that dequeueBuffer returns.
3434              */
3435             result = native_window_dequeue_buffer_and_wait(window,  &buffer);
3436             if (result == NO_ERROR) {
3437                 int syncFd = -1;
3438                 // create an EGLImage from the buffer so we can later
3439                 // turn it into a texture
3440                 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3441                         EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3442                 if (image != EGL_NO_IMAGE_KHR) {
3443                     // this binds the given EGLImage as a framebuffer for the
3444                     // duration of this scope.
3445                     RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3446                     if (imageBond.getStatus() == NO_ERROR) {
3447                         // this will in fact render into our dequeued buffer
3448                         // via an FBO, which means we didn't have to create
3449                         // an EGLSurface and therefore we're not
3450                         // dependent on the context's EGLConfig.
3451                         renderScreenImplLocked(
3452                             hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3453                             useIdentityTransform, rotation);
3454
3455                         // Attempt to create a sync khr object that can produce a sync point. If that
3456                         // isn't available, create a non-dupable sync object in the fallback path and
3457                         // wait on it directly.
3458                         EGLSyncKHR sync;
3459                         if (!DEBUG_SCREENSHOTS) {
3460                            sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3461                            // native fence fd will not be populated until flush() is done.
3462                            getRenderEngine().flush();
3463                         } else {
3464                             sync = EGL_NO_SYNC_KHR;
3465                         }
3466                         if (sync != EGL_NO_SYNC_KHR) {
3467                             // get the sync fd
3468                             syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3469                             if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3470                                 ALOGW("captureScreen: failed to dup sync khr object");
3471                                 syncFd = -1;
3472                             }
3473                             eglDestroySyncKHR(mEGLDisplay, sync);
3474                         } else {
3475                             // fallback path
3476                             sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3477                             if (sync != EGL_NO_SYNC_KHR) {
3478                                 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3479                                     EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3480                                 EGLint eglErr = eglGetError();
3481                                 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3482                                     ALOGW("captureScreen: fence wait timed out");
3483                                 } else {
3484                                     ALOGW_IF(eglErr != EGL_SUCCESS,
3485                                             "captureScreen: error waiting on EGL fence: %#x", eglErr);
3486                                 }
3487                                 eglDestroySyncKHR(mEGLDisplay, sync);
3488                             } else {
3489                                 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3490                             }
3491                         }
3492                         if (DEBUG_SCREENSHOTS) {
3493                             uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3494                             getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3495                             checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3496                                     hw, minLayerZ, maxLayerZ);
3497                             delete [] pixels;
3498                         }
3499
3500                     } else {
3501                         ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3502                         result = INVALID_OPERATION;
3503                         window->cancelBuffer(window, buffer, syncFd);
3504                         buffer = NULL;
3505                     }
3506                     // destroy our image
3507                     eglDestroyImageKHR(mEGLDisplay, image);
3508                 } else {
3509                     result = BAD_VALUE;
3510                 }
3511                 if (buffer) {
3512                     // queueBuffer takes ownership of syncFd
3513                     result = window->queueBuffer(window, buffer, syncFd);
3514                 }
3515             }
3516         } else {
3517             result = BAD_VALUE;
3518         }
3519         native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3520     }
3521
3522     return result;
3523 }
3524
3525 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3526         const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3527     if (DEBUG_SCREENSHOTS) {
3528         for (size_t y=0 ; y<h ; y++) {
3529             uint32_t const * p = (uint32_t const *)vaddr + y*s;
3530             for (size_t x=0 ; x<w ; x++) {
3531                 if (p[x] != 0xFF000000) return;
3532             }
3533         }
3534         ALOGE("*** we just took a black screenshot ***\n"
3535                 "requested minz=%d, maxz=%d, layerStack=%d",
3536                 minLayerZ, maxLayerZ, hw->getLayerStack());
3537         const LayerVector& layers( mDrawingState.layersSortedByZ );
3538         const size_t count = layers.size();
3539         for (size_t i=0 ; i<count ; ++i) {
3540             const sp<Layer>& layer(layers[i]);
3541             const Layer::State& state(layer->getDrawingState());
3542             const bool visible = (state.layerStack == hw->getLayerStack())
3543                                 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3544                                 && (layer->isVisible());
3545             ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
3546                     visible ? '+' : '-',
3547                             i, layer->getName().string(), state.layerStack, state.z,
3548                             layer->isVisible(), state.flags, state.alpha);
3549         }
3550     }
3551 }
3552
3553 // ---------------------------------------------------------------------------
3554
3555 SurfaceFlinger::LayerVector::LayerVector() {
3556 }
3557
3558 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3559     : SortedVector<sp<Layer> >(rhs) {
3560 }
3561
3562 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3563     const void* rhs) const
3564 {
3565     // sort layers per layer-stack, then by z-order and finally by sequence
3566     const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3567     const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3568
3569     uint32_t ls = l->getCurrentState().layerStack;
3570     uint32_t rs = r->getCurrentState().layerStack;
3571     if (ls != rs)
3572         return ls - rs;
3573
3574     uint32_t lz = l->getCurrentState().z;
3575     uint32_t rz = r->getCurrentState().z;
3576     if (lz != rz)
3577         return lz - rz;
3578
3579     return l->sequence - r->sequence;
3580 }
3581
3582 // ---------------------------------------------------------------------------
3583
3584 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3585     : type(DisplayDevice::DISPLAY_ID_INVALID),
3586       layerStack(DisplayDevice::NO_LAYER_STACK),
3587       orientation(0),
3588       width(0),
3589       height(0),
3590       isSecure(false) {
3591 }
3592
3593 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3594     DisplayDevice::DisplayType type, bool isSecure)
3595     : type(type),
3596       layerStack(DisplayDevice::NO_LAYER_STACK),
3597       orientation(0),
3598       width(0),
3599       height(0),
3600       isSecure(isSecure) {
3601     viewport.makeInvalid();
3602     frame.makeInvalid();
3603 }
3604
3605 // ---------------------------------------------------------------------------
3606
3607 }; // namespace android
3608
3609
3610 #if defined(__gl_h_)
3611 #error "don't include gl/gl.h in this file"
3612 #endif
3613
3614 #if defined(__gl2_h_)
3615 #error "don't include gl2/gl2.h in this file"
3616 #endif