OSDN Git Service

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