OSDN Git Service

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