OSDN Git Service

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