OSDN Git Service

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