OSDN Git Service

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