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