OSDN Git Service

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