OSDN Git Service

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