SurfaceFlinger.cpp revision 4f4f0943489d9113c66ac22b58cfba8c21dfa879
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
25#if defined(HAVE_PTHREADS)
26#include <sys/resource.h>
27#endif
28
29#include <EGL/egl.h>
30
31#include <cutils/log.h>
32#include <cutils/properties.h>
33
34#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
36#include <binder/MemoryHeapBase.h>
37#include <binder/PermissionCache.h>
38
39#include <ui/DisplayInfo.h>
40
41#include <gui/BitTube.h>
42#include <gui/BufferQueue.h>
43#include <gui/GuiConfig.h>
44#include <gui/IDisplayEventConnection.h>
45#include <gui/Surface.h>
46#include <gui/GraphicBufferAlloc.h>
47
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
50#include <ui/UiConfig.h>
51
52#include <utils/misc.h>
53#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
56#include <utils/Trace.h>
57
58#include <private/android_filesystem_config.h>
59#include <private/gui/SyncFeatures.h>
60
61#include "Client.h"
62#include "clz.h"
63#include "Colorizer.h"
64#include "DdmConnection.h"
65#include "DisplayDevice.h"
66#include "EventThread.h"
67#include "Layer.h"
68#include "LayerDim.h"
69#include "SurfaceFlinger.h"
70
71#include "DisplayHardware/FramebufferSurface.h"
72#include "DisplayHardware/HWComposer.h"
73#include "DisplayHardware/VirtualDisplaySurface.h"
74
75#include "RenderEngine/RenderEngine.h"
76
77#define DISPLAY_COUNT       1
78
79/*
80 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
81 * black pixels.
82 */
83#define DEBUG_SCREENSHOTS   false
84
85EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
86
87namespace android {
88// ---------------------------------------------------------------------------
89
90const String16 sHardwareTest("android.permission.HARDWARE_TEST");
91const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
92const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
93const String16 sDump("android.permission.DUMP");
94
95// ---------------------------------------------------------------------------
96
97SurfaceFlinger::SurfaceFlinger()
98    :   BnSurfaceComposer(),
99        mTransactionFlags(0),
100        mTransactionPending(false),
101        mAnimTransactionPending(false),
102        mLayersRemoved(false),
103        mRepaintEverything(0),
104        mRenderEngine(NULL),
105        mBootTime(systemTime()),
106        mVisibleRegionsDirty(false),
107        mHwWorkListDirty(false),
108        mAnimCompositionPending(false),
109        mDebugRegion(0),
110        mDebugDDMS(0),
111        mDebugDisableHWC(0),
112        mDebugDisableTransformHint(0),
113        mDebugInSwapBuffers(0),
114        mLastSwapBufferTime(0),
115        mDebugInTransaction(0),
116        mLastTransactionTime(0),
117        mBootFinished(false)
118{
119    ALOGI("SurfaceFlinger is starting");
120
121    // debugging stuff...
122    char value[PROPERTY_VALUE_MAX];
123
124    property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
125    mGpuToCpuSupported = !atoi(value);
126
127    property_get("debug.sf.showupdates", value, "0");
128    mDebugRegion = atoi(value);
129
130    property_get("debug.sf.ddms", value, "0");
131    mDebugDDMS = atoi(value);
132    if (mDebugDDMS) {
133        if (!startDdmConnection()) {
134            // start failed, and DDMS debugging not enabled
135            mDebugDDMS = 0;
136        }
137    }
138    ALOGI_IF(mDebugRegion, "showupdates enabled");
139    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
140}
141
142void SurfaceFlinger::onFirstRef()
143{
144    mEventQueue.init(this);
145}
146
147SurfaceFlinger::~SurfaceFlinger()
148{
149    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
150    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
151    eglTerminate(display);
152}
153
154void SurfaceFlinger::binderDied(const wp<IBinder>& who)
155{
156    // the window manager died on us. prepare its eulogy.
157
158    // restore initial conditions (default device unblank, etc)
159    initializeDisplays();
160
161    // restart the boot-animation
162    startBootAnim();
163}
164
165sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
166{
167    sp<ISurfaceComposerClient> bclient;
168    sp<Client> client(new Client(this));
169    status_t err = client->initCheck();
170    if (err == NO_ERROR) {
171        bclient = client;
172    }
173    return bclient;
174}
175
176sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
177        bool secure)
178{
179    class DisplayToken : public BBinder {
180        sp<SurfaceFlinger> flinger;
181        virtual ~DisplayToken() {
182             // no more references, this display must be terminated
183             Mutex::Autolock _l(flinger->mStateLock);
184             flinger->mCurrentState.displays.removeItem(this);
185             flinger->setTransactionFlags(eDisplayTransactionNeeded);
186         }
187     public:
188        DisplayToken(const sp<SurfaceFlinger>& flinger)
189            : flinger(flinger) {
190        }
191    };
192
193    sp<BBinder> token = new DisplayToken(this);
194
195    Mutex::Autolock _l(mStateLock);
196    DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
197    info.displayName = displayName;
198    info.isSecure = secure;
199    mCurrentState.displays.add(token, info);
200
201    return token;
202}
203
204void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
205    Mutex::Autolock _l(mStateLock);
206
207    ssize_t idx = mCurrentState.displays.indexOfKey(display);
208    if (idx < 0) {
209        ALOGW("destroyDisplay: invalid display token");
210        return;
211    }
212
213    const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
214    if (!info.isVirtualDisplay()) {
215        ALOGE("destroyDisplay called for non-virtual display");
216        return;
217    }
218
219    mCurrentState.displays.removeItemsAt(idx);
220    setTransactionFlags(eDisplayTransactionNeeded);
221}
222
223void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
224    ALOGW_IF(mBuiltinDisplays[type],
225            "Overwriting display token for display type %d", type);
226    mBuiltinDisplays[type] = new BBinder();
227    DisplayDeviceState info(type);
228    // All non-virtual displays are currently considered secure.
229    info.isSecure = true;
230    mCurrentState.displays.add(mBuiltinDisplays[type], info);
231}
232
233sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
234    if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
235        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
236        return NULL;
237    }
238    return mBuiltinDisplays[id];
239}
240
241sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
242{
243    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
244    return gba;
245}
246
247void SurfaceFlinger::bootFinished()
248{
249    const nsecs_t now = systemTime();
250    const nsecs_t duration = now - mBootTime;
251    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
252    mBootFinished = true;
253
254    // wait patiently for the window manager death
255    const String16 name("window");
256    sp<IBinder> window(defaultServiceManager()->getService(name));
257    if (window != 0) {
258        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
259    }
260
261    // stop boot animation
262    // formerly we would just kill the process, but we now ask it to exit so it
263    // can choose where to stop the animation.
264    property_set("service.bootanim.exit", "1");
265}
266
267void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
268    class MessageDestroyGLTexture : public MessageBase {
269        RenderEngine& engine;
270        uint32_t texture;
271    public:
272        MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
273            : engine(engine), texture(texture) {
274        }
275        virtual bool handler() {
276            engine.deleteTextures(1, &texture);
277            return true;
278        }
279    };
280    postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
281}
282
283status_t SurfaceFlinger::selectConfigForAttribute(
284        EGLDisplay dpy,
285        EGLint const* attrs,
286        EGLint attribute, EGLint wanted,
287        EGLConfig* outConfig)
288{
289    EGLConfig config = NULL;
290    EGLint numConfigs = -1, n=0;
291    eglGetConfigs(dpy, NULL, 0, &numConfigs);
292    EGLConfig* const configs = new EGLConfig[numConfigs];
293    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
294
295    if (n) {
296        if (attribute != EGL_NONE) {
297            for (int i=0 ; i<n ; i++) {
298                EGLint value = 0;
299                eglGetConfigAttrib(dpy, configs[i], attribute, &value);
300                if (wanted == value) {
301                    *outConfig = configs[i];
302                    delete [] configs;
303                    return NO_ERROR;
304                }
305            }
306        } else {
307            // just pick the first one
308            *outConfig = configs[0];
309            delete [] configs;
310            return NO_ERROR;
311        }
312    }
313    delete [] configs;
314    return NAME_NOT_FOUND;
315}
316
317class EGLAttributeVector {
318    struct Attribute;
319    class Adder;
320    friend class Adder;
321    KeyedVector<Attribute, EGLint> mList;
322    struct Attribute {
323        Attribute() {};
324        Attribute(EGLint v) : v(v) { }
325        EGLint v;
326        bool operator < (const Attribute& other) const {
327            // this places EGL_NONE at the end
328            EGLint lhs(v);
329            EGLint rhs(other.v);
330            if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
331            if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
332            return lhs < rhs;
333        }
334    };
335    class Adder {
336        friend class EGLAttributeVector;
337        EGLAttributeVector& v;
338        EGLint attribute;
339        Adder(EGLAttributeVector& v, EGLint attribute)
340            : v(v), attribute(attribute) {
341        }
342    public:
343        void operator = (EGLint value) {
344            if (attribute != EGL_NONE) {
345                v.mList.add(attribute, value);
346            }
347        }
348        operator EGLint () const { return v.mList[attribute]; }
349    };
350public:
351    EGLAttributeVector() {
352        mList.add(EGL_NONE, EGL_NONE);
353    }
354    void remove(EGLint attribute) {
355        if (attribute != EGL_NONE) {
356            mList.removeItem(attribute);
357        }
358    }
359    Adder operator [] (EGLint attribute) {
360        return Adder(*this, attribute);
361    }
362    EGLint operator [] (EGLint attribute) const {
363       return mList[attribute];
364    }
365    // cast-operator to (EGLint const*)
366    operator EGLint const* () const { return &mList.keyAt(0).v; }
367};
368
369EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
370    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
371    // it is to be used with WIFI displays
372    EGLConfig config;
373    EGLint dummy;
374    status_t err;
375
376    EGLAttributeVector attribs;
377    // TODO: enable ES2
378    //attribs[EGL_RENDERABLE_TYPE]            = EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT;
379    attribs[EGL_SURFACE_TYPE]               = EGL_WINDOW_BIT | EGL_PBUFFER_BIT;
380    attribs[EGL_RECORDABLE_ANDROID]         = EGL_TRUE;
381    attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
382    attribs[EGL_RED_SIZE]                   = 8;
383    attribs[EGL_GREEN_SIZE]                 = 8;
384    attribs[EGL_BLUE_SIZE]                  = 8;
385
386    err = selectConfigForAttribute(display, attribs, EGL_NONE, EGL_NONE, &config);
387    if (!err)
388        goto success;
389
390    // this didn't work, probably because we're on the emulator...
391    // try a simplified query
392    ALOGW("no suitable EGLConfig found, trying a simpler query");
393    attribs.remove(EGL_RENDERABLE_TYPE);
394    attribs.remove(EGL_FRAMEBUFFER_TARGET_ANDROID);
395    attribs.remove(EGL_RECORDABLE_ANDROID);
396    attribs.remove(EGL_RED_SIZE);
397    attribs.remove(EGL_GREEN_SIZE);
398    attribs.remove(EGL_BLUE_SIZE);
399    err = selectConfigForAttribute(display, attribs,
400            EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
401    if (!err)
402        goto success;
403
404    // this EGL is too lame for Android
405    LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
406    return 0;
407
408success:
409    if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy))
410        ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
411    return config;
412}
413
414void SurfaceFlinger::init() {
415
416    ALOGI(  "SurfaceFlinger's main thread ready to run. "
417            "Initializing graphics H/W...");
418
419    Mutex::Autolock _l(mStateLock);
420
421    // initialize EGL for the default display
422    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
423    eglInitialize(mEGLDisplay, NULL, NULL);
424
425    // Initialize the H/W composer object.  There may or may not be an
426    // actual hardware composer underneath.
427    mHwc = new HWComposer(this,
428            *static_cast<HWComposer::EventHandler *>(this));
429
430    // initialize the config and context (can't fail)
431    mEGLConfig = selectEGLConfig(mEGLDisplay, mHwc->getVisualID());
432
433    // print some debugging info
434    EGLint r,g,b,a;
435    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_RED_SIZE,   &r);
436    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_GREEN_SIZE, &g);
437    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_BLUE_SIZE,  &b);
438    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_ALPHA_SIZE, &a);
439    ALOGI("EGL informations:");
440    ALOGI("vendor    : %s", eglQueryString(mEGLDisplay, EGL_VENDOR));
441    ALOGI("version   : %s", eglQueryString(mEGLDisplay, EGL_VERSION));
442    ALOGI("extensions: %s", eglQueryString(mEGLDisplay, EGL_EXTENSIONS));
443    ALOGI("Client API: %s", eglQueryString(mEGLDisplay, EGL_CLIENT_APIS)?:"Not Supported");
444    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
445
446    // get a RenderEngine for the given display / config (can't fail)
447    mRenderEngine = RenderEngine::create(mEGLDisplay, mEGLConfig);
448
449    // retrieve the EGL context that was selected/created
450    mEGLContext = mRenderEngine->getEGLContext();
451
452    // figure out which format we got
453    eglGetConfigAttrib(mEGLDisplay, mEGLConfig,
454            EGL_NATIVE_VISUAL_ID, &mEGLNativeVisualId);
455
456    LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
457            "couldn't create EGLContext");
458
459    // initialize our non-virtual displays
460    for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
461        DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
462        // set-up the displays that are already connected
463        if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
464            // All non-virtual displays are currently considered secure.
465            bool isSecure = true;
466            createBuiltinDisplayLocked(type);
467            wp<IBinder> token = mBuiltinDisplays[i];
468
469            sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
470            sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i, bq);
471            sp<DisplayDevice> hw = new DisplayDevice(this,
472                    type, allocateHwcDisplayId(type), isSecure, token,
473                    fbs, bq,
474                    mEGLConfig);
475            if (i > DisplayDevice::DISPLAY_PRIMARY) {
476                // FIXME: currently we don't get blank/unblank requests
477                // for displays other than the main display, so we always
478                // assume a connected display is unblanked.
479                ALOGD("marking display %d as acquired/unblanked", i);
480                hw->acquireScreen();
481            }
482            mDisplays.add(token, hw);
483        }
484    }
485
486    // make the GLContext current so that we can create textures when creating Layers
487    // (which may happens before we render something)
488    getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
489
490    // start the EventThread
491    mEventThread = new EventThread(this);
492    mEventQueue.setEventThread(mEventThread);
493
494    // initialize our drawing state
495    mDrawingState = mCurrentState;
496
497    // set initial conditions (e.g. unblank default device)
498    initializeDisplays();
499
500    // start boot animation
501    startBootAnim();
502}
503
504int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
505    return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
506            type : mHwc->allocateDisplayId();
507}
508
509void SurfaceFlinger::startBootAnim() {
510    // start boot animation
511    property_set("service.bootanim.exit", "0");
512    property_set("ctl.start", "bootanim");
513}
514
515size_t SurfaceFlinger::getMaxTextureSize() const {
516    return mRenderEngine->getMaxTextureSize();
517}
518
519size_t SurfaceFlinger::getMaxViewportDims() const {
520    return mRenderEngine->getMaxViewportDims();
521}
522
523// ----------------------------------------------------------------------------
524
525bool SurfaceFlinger::authenticateSurfaceTexture(
526        const sp<IGraphicBufferProducer>& bufferProducer) const {
527    Mutex::Autolock _l(mStateLock);
528    sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
529    return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
530}
531
532status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
533    int32_t type = NAME_NOT_FOUND;
534    for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
535        if (display == mBuiltinDisplays[i]) {
536            type = i;
537            break;
538        }
539    }
540
541    if (type < 0) {
542        return type;
543    }
544
545    const HWComposer& hwc(getHwComposer());
546    float xdpi = hwc.getDpiX(type);
547    float ydpi = hwc.getDpiY(type);
548
549    // TODO: Not sure if display density should handled by SF any longer
550    class Density {
551        static int getDensityFromProperty(char const* propName) {
552            char property[PROPERTY_VALUE_MAX];
553            int density = 0;
554            if (property_get(propName, property, NULL) > 0) {
555                density = atoi(property);
556            }
557            return density;
558        }
559    public:
560        static int getEmuDensity() {
561            return getDensityFromProperty("qemu.sf.lcd_density"); }
562        static int getBuildDensity()  {
563            return getDensityFromProperty("ro.sf.lcd_density"); }
564    };
565
566    if (type == DisplayDevice::DISPLAY_PRIMARY) {
567        // The density of the device is provided by a build property
568        float density = Density::getBuildDensity() / 160.0f;
569        if (density == 0) {
570            // the build doesn't provide a density -- this is wrong!
571            // use xdpi instead
572            ALOGE("ro.sf.lcd_density must be defined as a build property");
573            density = xdpi / 160.0f;
574        }
575        if (Density::getEmuDensity()) {
576            // if "qemu.sf.lcd_density" is specified, it overrides everything
577            xdpi = ydpi = density = Density::getEmuDensity();
578            density /= 160.0f;
579        }
580        info->density = density;
581
582        // TODO: this needs to go away (currently needed only by webkit)
583        sp<const DisplayDevice> hw(getDefaultDisplayDevice());
584        info->orientation = hw->getOrientation();
585    } else {
586        // TODO: where should this value come from?
587        static const int TV_DENSITY = 213;
588        info->density = TV_DENSITY / 160.0f;
589        info->orientation = 0;
590    }
591
592    info->w = hwc.getWidth(type);
593    info->h = hwc.getHeight(type);
594    info->xdpi = xdpi;
595    info->ydpi = ydpi;
596    info->fps = float(1e9 / hwc.getRefreshPeriod(type));
597
598    // All non-virtual displays are currently considered secure.
599    info->secure = true;
600
601    return NO_ERROR;
602}
603
604// ----------------------------------------------------------------------------
605
606sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
607    return mEventThread->createEventConnection();
608}
609
610// ----------------------------------------------------------------------------
611
612void SurfaceFlinger::waitForEvent() {
613    mEventQueue.waitMessage();
614}
615
616void SurfaceFlinger::signalTransaction() {
617    mEventQueue.invalidate();
618}
619
620void SurfaceFlinger::signalLayerUpdate() {
621    mEventQueue.invalidate();
622}
623
624void SurfaceFlinger::signalRefresh() {
625    mEventQueue.refresh();
626}
627
628status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
629        nsecs_t reltime, uint32_t flags) {
630    return mEventQueue.postMessage(msg, reltime);
631}
632
633status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
634        nsecs_t reltime, uint32_t flags) {
635    status_t res = mEventQueue.postMessage(msg, reltime);
636    if (res == NO_ERROR) {
637        msg->wait();
638    }
639    return res;
640}
641
642void SurfaceFlinger::run() {
643#if defined(HAVE_PTHREADS)
644    setpriority(PRIO_PROCESS, 0, PRIORITY_URGENT_DISPLAY);
645#endif
646    do {
647        waitForEvent();
648    } while (true);
649}
650
651void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
652    if (mEventThread == NULL) {
653        // This is a temporary workaround for b/7145521.  A non-null pointer
654        // does not mean EventThread has finished initializing, so this
655        // is not a correct fix.
656        ALOGW("WARNING: EventThread not started, ignoring vsync");
657        return;
658    }
659    if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
660        // we should only receive DisplayDevice::DisplayType from the vsync callback
661        mEventThread->onVSyncReceived(type, timestamp);
662    }
663}
664
665void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
666    if (mEventThread == NULL) {
667        // This is a temporary workaround for b/7145521.  A non-null pointer
668        // does not mean EventThread has finished initializing, so this
669        // is not a correct fix.
670        ALOGW("WARNING: EventThread not started, ignoring hotplug");
671        return;
672    }
673
674    if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
675        Mutex::Autolock _l(mStateLock);
676        if (connected) {
677            createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
678        } else {
679            mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
680            mBuiltinDisplays[type].clear();
681        }
682        setTransactionFlags(eDisplayTransactionNeeded);
683
684        // Defer EventThread notification until SF has updated mDisplays.
685    }
686}
687
688void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
689    getHwComposer().eventControl(disp, event, enabled);
690}
691
692void SurfaceFlinger::onMessageReceived(int32_t what) {
693    ATRACE_CALL();
694    switch (what) {
695    case MessageQueue::TRANSACTION:
696        handleMessageTransaction();
697        break;
698    case MessageQueue::INVALIDATE:
699        handleMessageTransaction();
700        handleMessageInvalidate();
701        signalRefresh();
702        break;
703    case MessageQueue::REFRESH:
704        handleMessageRefresh();
705        break;
706    }
707}
708
709void SurfaceFlinger::handleMessageTransaction() {
710    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
711    if (transactionFlags) {
712        handleTransaction(transactionFlags);
713    }
714}
715
716void SurfaceFlinger::handleMessageInvalidate() {
717    ATRACE_CALL();
718    handlePageFlip();
719}
720
721void SurfaceFlinger::handleMessageRefresh() {
722    ATRACE_CALL();
723    preComposition();
724    rebuildLayerStacks();
725    setUpHWComposer();
726    doDebugFlashRegions();
727    doComposition();
728    postComposition();
729}
730
731void SurfaceFlinger::doDebugFlashRegions()
732{
733    // is debugging enabled
734    if (CC_LIKELY(!mDebugRegion))
735        return;
736
737    const bool repaintEverything = mRepaintEverything;
738    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
739        const sp<DisplayDevice>& hw(mDisplays[dpy]);
740        if (hw->canDraw()) {
741            // transform the dirty region into this screen's coordinate space
742            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
743            if (!dirtyRegion.isEmpty()) {
744                // redraw the whole screen
745                doComposeSurfaces(hw, Region(hw->bounds()));
746
747                // and draw the dirty region
748                const int32_t height = hw->getHeight();
749                RenderEngine& engine(getRenderEngine());
750                engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
751
752                hw->compositionComplete();
753                hw->swapBuffers(getHwComposer());
754            }
755        }
756    }
757
758    postFramebuffer();
759
760    if (mDebugRegion > 1) {
761        usleep(mDebugRegion * 1000);
762    }
763
764    HWComposer& hwc(getHwComposer());
765    if (hwc.initCheck() == NO_ERROR) {
766        status_t err = hwc.prepare();
767        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
768    }
769}
770
771void SurfaceFlinger::preComposition()
772{
773    bool needExtraInvalidate = false;
774    const LayerVector& layers(mDrawingState.layersSortedByZ);
775    const size_t count = layers.size();
776    for (size_t i=0 ; i<count ; i++) {
777        if (layers[i]->onPreComposition()) {
778            needExtraInvalidate = true;
779        }
780    }
781    if (needExtraInvalidate) {
782        signalLayerUpdate();
783    }
784}
785
786void SurfaceFlinger::postComposition()
787{
788    const LayerVector& layers(mDrawingState.layersSortedByZ);
789    const size_t count = layers.size();
790    for (size_t i=0 ; i<count ; i++) {
791        layers[i]->onPostComposition();
792    }
793
794    if (mAnimCompositionPending) {
795        mAnimCompositionPending = false;
796
797        const HWComposer& hwc = getHwComposer();
798        sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
799        if (presentFence->isValid()) {
800            mAnimFrameTracker.setActualPresentFence(presentFence);
801        } else {
802            // The HWC doesn't support present fences, so use the refresh
803            // timestamp instead.
804            nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
805            mAnimFrameTracker.setActualPresentTime(presentTime);
806        }
807        mAnimFrameTracker.advanceFrame();
808    }
809}
810
811void SurfaceFlinger::rebuildLayerStacks() {
812    // rebuild the visible layer list per screen
813    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
814        ATRACE_CALL();
815        mVisibleRegionsDirty = false;
816        invalidateHwcGeometry();
817
818        const LayerVector& layers(mDrawingState.layersSortedByZ);
819        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
820            Region opaqueRegion;
821            Region dirtyRegion;
822            Vector< sp<Layer> > layersSortedByZ;
823            const sp<DisplayDevice>& hw(mDisplays[dpy]);
824            const Transform& tr(hw->getTransform());
825            const Rect bounds(hw->getBounds());
826            if (hw->canDraw()) {
827                SurfaceFlinger::computeVisibleRegions(layers,
828                        hw->getLayerStack(), dirtyRegion, opaqueRegion);
829
830                const size_t count = layers.size();
831                for (size_t i=0 ; i<count ; i++) {
832                    const sp<Layer>& layer(layers[i]);
833                    const Layer::State& s(layer->getDrawingState());
834                    if (s.layerStack == hw->getLayerStack()) {
835                        Region drawRegion(tr.transform(
836                                layer->visibleNonTransparentRegion));
837                        drawRegion.andSelf(bounds);
838                        if (!drawRegion.isEmpty()) {
839                            layersSortedByZ.add(layer);
840                        }
841                    }
842                }
843            }
844            hw->setVisibleLayersSortedByZ(layersSortedByZ);
845            hw->undefinedRegion.set(bounds);
846            hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
847            hw->dirtyRegion.orSelf(dirtyRegion);
848        }
849    }
850}
851
852void SurfaceFlinger::setUpHWComposer() {
853    HWComposer& hwc(getHwComposer());
854    if (hwc.initCheck() == NO_ERROR) {
855        // build the h/w work list
856        if (CC_UNLIKELY(mHwWorkListDirty)) {
857            mHwWorkListDirty = false;
858            for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
859                sp<const DisplayDevice> hw(mDisplays[dpy]);
860                const int32_t id = hw->getHwcDisplayId();
861                if (id >= 0) {
862                    const Vector< sp<Layer> >& currentLayers(
863                        hw->getVisibleLayersSortedByZ());
864                    const size_t count = currentLayers.size();
865                    if (hwc.createWorkList(id, count) == NO_ERROR) {
866                        HWComposer::LayerListIterator cur = hwc.begin(id);
867                        const HWComposer::LayerListIterator end = hwc.end(id);
868                        for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
869                            const sp<Layer>& layer(currentLayers[i]);
870                            layer->setGeometry(hw, *cur);
871                            if (mDebugDisableHWC || mDebugRegion) {
872                                cur->setSkip(true);
873                            }
874                        }
875                    }
876                }
877            }
878        }
879
880        // set the per-frame data
881        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
882            sp<const DisplayDevice> hw(mDisplays[dpy]);
883            const int32_t id = hw->getHwcDisplayId();
884            if (id >= 0) {
885                const Vector< sp<Layer> >& currentLayers(
886                    hw->getVisibleLayersSortedByZ());
887                const size_t count = currentLayers.size();
888                HWComposer::LayerListIterator cur = hwc.begin(id);
889                const HWComposer::LayerListIterator end = hwc.end(id);
890                for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
891                    /*
892                     * update the per-frame h/w composer data for each layer
893                     * and build the transparent region of the FB
894                     */
895                    const sp<Layer>& layer(currentLayers[i]);
896                    layer->setPerFrameData(hw, *cur);
897                }
898            }
899        }
900
901        status_t err = hwc.prepare();
902        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
903
904        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
905            sp<const DisplayDevice> hw(mDisplays[dpy]);
906            hw->prepareFrame(hwc);
907        }
908    }
909}
910
911void SurfaceFlinger::doComposition() {
912    ATRACE_CALL();
913    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
914    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
915        const sp<DisplayDevice>& hw(mDisplays[dpy]);
916        if (hw->canDraw()) {
917            // transform the dirty region into this screen's coordinate space
918            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
919
920            // repaint the framebuffer (if needed)
921            doDisplayComposition(hw, dirtyRegion);
922
923            hw->dirtyRegion.clear();
924            hw->flip(hw->swapRegion);
925            hw->swapRegion.clear();
926        }
927        // inform the h/w that we're done compositing
928        hw->compositionComplete();
929    }
930    postFramebuffer();
931}
932
933void SurfaceFlinger::postFramebuffer()
934{
935    ATRACE_CALL();
936
937    const nsecs_t now = systemTime();
938    mDebugInSwapBuffers = now;
939
940    HWComposer& hwc(getHwComposer());
941    if (hwc.initCheck() == NO_ERROR) {
942        if (!hwc.supportsFramebufferTarget()) {
943            // EGL spec says:
944            //   "surface must be bound to the calling thread's current context,
945            //    for the current rendering API."
946            getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
947        }
948        hwc.commit();
949    }
950
951    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
952        sp<const DisplayDevice> hw(mDisplays[dpy]);
953        const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
954        hw->onSwapBuffersCompleted(hwc);
955        const size_t count = currentLayers.size();
956        int32_t id = hw->getHwcDisplayId();
957        if (id >=0 && hwc.initCheck() == NO_ERROR) {
958            HWComposer::LayerListIterator cur = hwc.begin(id);
959            const HWComposer::LayerListIterator end = hwc.end(id);
960            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
961                currentLayers[i]->onLayerDisplayed(hw, &*cur);
962            }
963        } else {
964            for (size_t i = 0; i < count; i++) {
965                currentLayers[i]->onLayerDisplayed(hw, NULL);
966            }
967        }
968    }
969
970    mLastSwapBufferTime = systemTime() - now;
971    mDebugInSwapBuffers = 0;
972
973    uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
974    if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
975        logFrameStats();
976    }
977}
978
979void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
980{
981    ATRACE_CALL();
982
983    // here we keep a copy of the drawing state (that is the state that's
984    // going to be overwritten by handleTransactionLocked()) outside of
985    // mStateLock so that the side-effects of the State assignment
986    // don't happen with mStateLock held (which can cause deadlocks).
987    State drawingState(mDrawingState);
988
989    Mutex::Autolock _l(mStateLock);
990    const nsecs_t now = systemTime();
991    mDebugInTransaction = now;
992
993    // Here we're guaranteed that some transaction flags are set
994    // so we can call handleTransactionLocked() unconditionally.
995    // We call getTransactionFlags(), which will also clear the flags,
996    // with mStateLock held to guarantee that mCurrentState won't change
997    // until the transaction is committed.
998
999    transactionFlags = getTransactionFlags(eTransactionMask);
1000    handleTransactionLocked(transactionFlags);
1001
1002    mLastTransactionTime = systemTime() - now;
1003    mDebugInTransaction = 0;
1004    invalidateHwcGeometry();
1005    // here the transaction has been committed
1006}
1007
1008void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1009{
1010    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1011    const size_t count = currentLayers.size();
1012
1013    /*
1014     * Traversal of the children
1015     * (perform the transaction for each of them if needed)
1016     */
1017
1018    if (transactionFlags & eTraversalNeeded) {
1019        for (size_t i=0 ; i<count ; i++) {
1020            const sp<Layer>& layer(currentLayers[i]);
1021            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1022            if (!trFlags) continue;
1023
1024            const uint32_t flags = layer->doTransaction(0);
1025            if (flags & Layer::eVisibleRegion)
1026                mVisibleRegionsDirty = true;
1027        }
1028    }
1029
1030    /*
1031     * Perform display own transactions if needed
1032     */
1033
1034    if (transactionFlags & eDisplayTransactionNeeded) {
1035        // here we take advantage of Vector's copy-on-write semantics to
1036        // improve performance by skipping the transaction entirely when
1037        // know that the lists are identical
1038        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1039        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1040        if (!curr.isIdenticalTo(draw)) {
1041            mVisibleRegionsDirty = true;
1042            const size_t cc = curr.size();
1043                  size_t dc = draw.size();
1044
1045            // find the displays that were removed
1046            // (ie: in drawing state but not in current state)
1047            // also handle displays that changed
1048            // (ie: displays that are in both lists)
1049            for (size_t i=0 ; i<dc ; i++) {
1050                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1051                if (j < 0) {
1052                    // in drawing state but not in current state
1053                    if (!draw[i].isMainDisplay()) {
1054                        // Call makeCurrent() on the primary display so we can
1055                        // be sure that nothing associated with this display
1056                        // is current.
1057                        const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1058                        defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1059                        sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1060                        if (hw != NULL)
1061                            hw->disconnect(getHwComposer());
1062                        if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1063                            mEventThread->onHotplugReceived(draw[i].type, false);
1064                        mDisplays.removeItem(draw.keyAt(i));
1065                    } else {
1066                        ALOGW("trying to remove the main display");
1067                    }
1068                } else {
1069                    // this display is in both lists. see if something changed.
1070                    const DisplayDeviceState& state(curr[j]);
1071                    const wp<IBinder>& display(curr.keyAt(j));
1072                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1073                        // changing the surface is like destroying and
1074                        // recreating the DisplayDevice, so we just remove it
1075                        // from the drawing state, so that it get re-added
1076                        // below.
1077                        sp<DisplayDevice> hw(getDisplayDevice(display));
1078                        if (hw != NULL)
1079                            hw->disconnect(getHwComposer());
1080                        mDisplays.removeItem(display);
1081                        mDrawingState.displays.removeItemsAt(i);
1082                        dc--; i--;
1083                        // at this point we must loop to the next item
1084                        continue;
1085                    }
1086
1087                    const sp<DisplayDevice> disp(getDisplayDevice(display));
1088                    if (disp != NULL) {
1089                        if (state.layerStack != draw[i].layerStack) {
1090                            disp->setLayerStack(state.layerStack);
1091                        }
1092                        if ((state.orientation != draw[i].orientation)
1093                                || (state.viewport != draw[i].viewport)
1094                                || (state.frame != draw[i].frame))
1095                        {
1096                            disp->setProjection(state.orientation,
1097                                    state.viewport, state.frame);
1098                        }
1099                    }
1100                }
1101            }
1102
1103            // find displays that were added
1104            // (ie: in current state but not in drawing state)
1105            for (size_t i=0 ; i<cc ; i++) {
1106                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1107                    const DisplayDeviceState& state(curr[i]);
1108
1109                    sp<DisplaySurface> dispSurface;
1110                    sp<IGraphicBufferProducer> producer;
1111                    sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
1112
1113                    int32_t hwcDisplayId = -1;
1114                    if (state.isVirtualDisplay()) {
1115                        // Virtual displays without a surface are dormant:
1116                        // they have external state (layer stack, projection,
1117                        // etc.) but no internal state (i.e. a DisplayDevice).
1118                        if (state.surface != NULL) {
1119
1120                            hwcDisplayId = allocateHwcDisplayId(state.type);
1121                            sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1122                                    *mHwc, hwcDisplayId, state.surface, bq,
1123                                    state.displayName);
1124
1125                            dispSurface = vds;
1126                            if (hwcDisplayId >= 0) {
1127                                producer = vds;
1128                            } else {
1129                                // There won't be any interaction with HWC for this virtual display,
1130                                // so the GLES driver can pass buffers directly to the sink.
1131                                producer = state.surface;
1132                            }
1133                        }
1134                    } else {
1135                        ALOGE_IF(state.surface!=NULL,
1136                                "adding a supported display, but rendering "
1137                                "surface is provided (%p), ignoring it",
1138                                state.surface.get());
1139                        hwcDisplayId = allocateHwcDisplayId(state.type);
1140                        // for supported (by hwc) displays we provide our
1141                        // own rendering surface
1142                        dispSurface = new FramebufferSurface(*mHwc, state.type, bq);
1143                        producer = bq;
1144                    }
1145
1146                    const wp<IBinder>& display(curr.keyAt(i));
1147                    if (dispSurface != NULL) {
1148                        sp<DisplayDevice> hw = new DisplayDevice(this,
1149                                state.type, hwcDisplayId, state.isSecure,
1150                                display, dispSurface, producer, mEGLConfig);
1151                        hw->setLayerStack(state.layerStack);
1152                        hw->setProjection(state.orientation,
1153                                state.viewport, state.frame);
1154                        hw->setDisplayName(state.displayName);
1155                        mDisplays.add(display, hw);
1156                        if (state.isVirtualDisplay()) {
1157                            if (hwcDisplayId >= 0) {
1158                                mHwc->setVirtualDisplayProperties(hwcDisplayId,
1159                                        hw->getWidth(), hw->getHeight(),
1160                                        hw->getFormat());
1161                            }
1162                        } else {
1163                            mEventThread->onHotplugReceived(state.type, true);
1164                        }
1165                    }
1166                }
1167            }
1168        }
1169    }
1170
1171    if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1172        // The transform hint might have changed for some layers
1173        // (either because a display has changed, or because a layer
1174        // as changed).
1175        //
1176        // Walk through all the layers in currentLayers,
1177        // and update their transform hint.
1178        //
1179        // If a layer is visible only on a single display, then that
1180        // display is used to calculate the hint, otherwise we use the
1181        // default display.
1182        //
1183        // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1184        // the hint is set before we acquire a buffer from the surface texture.
1185        //
1186        // NOTE: layer transactions have taken place already, so we use their
1187        // drawing state. However, SurfaceFlinger's own transaction has not
1188        // happened yet, so we must use the current state layer list
1189        // (soon to become the drawing state list).
1190        //
1191        sp<const DisplayDevice> disp;
1192        uint32_t currentlayerStack = 0;
1193        for (size_t i=0; i<count; i++) {
1194            // NOTE: we rely on the fact that layers are sorted by
1195            // layerStack first (so we don't have to traverse the list
1196            // of displays for every layer).
1197            const sp<Layer>& layer(currentLayers[i]);
1198            uint32_t layerStack = layer->getDrawingState().layerStack;
1199            if (i==0 || currentlayerStack != layerStack) {
1200                currentlayerStack = layerStack;
1201                // figure out if this layerstack is mirrored
1202                // (more than one display) if so, pick the default display,
1203                // if not, pick the only display it's on.
1204                disp.clear();
1205                for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1206                    sp<const DisplayDevice> hw(mDisplays[dpy]);
1207                    if (hw->getLayerStack() == currentlayerStack) {
1208                        if (disp == NULL) {
1209                            disp = hw;
1210                        } else {
1211                            disp = NULL;
1212                            break;
1213                        }
1214                    }
1215                }
1216            }
1217            if (disp == NULL) {
1218                // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1219                // redraw after transform hint changes. See bug 8508397.
1220
1221                // could be null when this layer is using a layerStack
1222                // that is not visible on any display. Also can occur at
1223                // screen off/on times.
1224                disp = getDefaultDisplayDevice();
1225            }
1226            layer->updateTransformHint(disp);
1227        }
1228    }
1229
1230
1231    /*
1232     * Perform our own transaction if needed
1233     */
1234
1235    const LayerVector& layers(mDrawingState.layersSortedByZ);
1236    if (currentLayers.size() > layers.size()) {
1237        // layers have been added
1238        mVisibleRegionsDirty = true;
1239    }
1240
1241    // some layers might have been removed, so
1242    // we need to update the regions they're exposing.
1243    if (mLayersRemoved) {
1244        mLayersRemoved = false;
1245        mVisibleRegionsDirty = true;
1246        const size_t count = layers.size();
1247        for (size_t i=0 ; i<count ; i++) {
1248            const sp<Layer>& layer(layers[i]);
1249            if (currentLayers.indexOf(layer) < 0) {
1250                // this layer is not visible anymore
1251                // TODO: we could traverse the tree from front to back and
1252                //       compute the actual visible region
1253                // TODO: we could cache the transformed region
1254                const Layer::State& s(layer->getDrawingState());
1255                Region visibleReg = s.transform.transform(
1256                        Region(Rect(s.active.w, s.active.h)));
1257                invalidateLayerStack(s.layerStack, visibleReg);
1258            }
1259        }
1260    }
1261
1262    commitTransaction();
1263}
1264
1265void SurfaceFlinger::commitTransaction()
1266{
1267    if (!mLayersPendingRemoval.isEmpty()) {
1268        // Notify removed layers now that they can't be drawn from
1269        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1270            mLayersPendingRemoval[i]->onRemoved();
1271        }
1272        mLayersPendingRemoval.clear();
1273    }
1274
1275    // If this transaction is part of a window animation then the next frame
1276    // we composite should be considered an animation as well.
1277    mAnimCompositionPending = mAnimTransactionPending;
1278
1279    mDrawingState = mCurrentState;
1280    mTransactionPending = false;
1281    mAnimTransactionPending = false;
1282    mTransactionCV.broadcast();
1283}
1284
1285void SurfaceFlinger::computeVisibleRegions(
1286        const LayerVector& currentLayers, uint32_t layerStack,
1287        Region& outDirtyRegion, Region& outOpaqueRegion)
1288{
1289    ATRACE_CALL();
1290
1291    Region aboveOpaqueLayers;
1292    Region aboveCoveredLayers;
1293    Region dirty;
1294
1295    outDirtyRegion.clear();
1296
1297    size_t i = currentLayers.size();
1298    while (i--) {
1299        const sp<Layer>& layer = currentLayers[i];
1300
1301        // start with the whole surface at its current location
1302        const Layer::State& s(layer->getDrawingState());
1303
1304        // only consider the layers on the given layer stack
1305        if (s.layerStack != layerStack)
1306            continue;
1307
1308        /*
1309         * opaqueRegion: area of a surface that is fully opaque.
1310         */
1311        Region opaqueRegion;
1312
1313        /*
1314         * visibleRegion: area of a surface that is visible on screen
1315         * and not fully transparent. This is essentially the layer's
1316         * footprint minus the opaque regions above it.
1317         * Areas covered by a translucent surface are considered visible.
1318         */
1319        Region visibleRegion;
1320
1321        /*
1322         * coveredRegion: area of a surface that is covered by all
1323         * visible regions above it (which includes the translucent areas).
1324         */
1325        Region coveredRegion;
1326
1327        /*
1328         * transparentRegion: area of a surface that is hinted to be completely
1329         * transparent. This is only used to tell when the layer has no visible
1330         * non-transparent regions and can be removed from the layer list. It
1331         * does not affect the visibleRegion of this layer or any layers
1332         * beneath it. The hint may not be correct if apps don't respect the
1333         * SurfaceView restrictions (which, sadly, some don't).
1334         */
1335        Region transparentRegion;
1336
1337
1338        // handle hidden surfaces by setting the visible region to empty
1339        if (CC_LIKELY(layer->isVisible())) {
1340            const bool translucent = !layer->isOpaque();
1341            Rect bounds(s.transform.transform(layer->computeBounds()));
1342            visibleRegion.set(bounds);
1343            if (!visibleRegion.isEmpty()) {
1344                // Remove the transparent area from the visible region
1345                if (translucent) {
1346                    const Transform tr(s.transform);
1347                    if (tr.transformed()) {
1348                        if (tr.preserveRects()) {
1349                            // transform the transparent region
1350                            transparentRegion = tr.transform(s.activeTransparentRegion);
1351                        } else {
1352                            // transformation too complex, can't do the
1353                            // transparent region optimization.
1354                            transparentRegion.clear();
1355                        }
1356                    } else {
1357                        transparentRegion = s.activeTransparentRegion;
1358                    }
1359                }
1360
1361                // compute the opaque region
1362                const int32_t layerOrientation = s.transform.getOrientation();
1363                if (s.alpha==255 && !translucent &&
1364                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1365                    // the opaque region is the layer's footprint
1366                    opaqueRegion = visibleRegion;
1367                }
1368            }
1369        }
1370
1371        // Clip the covered region to the visible region
1372        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1373
1374        // Update aboveCoveredLayers for next (lower) layer
1375        aboveCoveredLayers.orSelf(visibleRegion);
1376
1377        // subtract the opaque region covered by the layers above us
1378        visibleRegion.subtractSelf(aboveOpaqueLayers);
1379
1380        // compute this layer's dirty region
1381        if (layer->contentDirty) {
1382            // we need to invalidate the whole region
1383            dirty = visibleRegion;
1384            // as well, as the old visible region
1385            dirty.orSelf(layer->visibleRegion);
1386            layer->contentDirty = false;
1387        } else {
1388            /* compute the exposed region:
1389             *   the exposed region consists of two components:
1390             *   1) what's VISIBLE now and was COVERED before
1391             *   2) what's EXPOSED now less what was EXPOSED before
1392             *
1393             * note that (1) is conservative, we start with the whole
1394             * visible region but only keep what used to be covered by
1395             * something -- which mean it may have been exposed.
1396             *
1397             * (2) handles areas that were not covered by anything but got
1398             * exposed because of a resize.
1399             */
1400            const Region newExposed = visibleRegion - coveredRegion;
1401            const Region oldVisibleRegion = layer->visibleRegion;
1402            const Region oldCoveredRegion = layer->coveredRegion;
1403            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1404            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1405        }
1406        dirty.subtractSelf(aboveOpaqueLayers);
1407
1408        // accumulate to the screen dirty region
1409        outDirtyRegion.orSelf(dirty);
1410
1411        // Update aboveOpaqueLayers for next (lower) layer
1412        aboveOpaqueLayers.orSelf(opaqueRegion);
1413
1414        // Store the visible region in screen space
1415        layer->setVisibleRegion(visibleRegion);
1416        layer->setCoveredRegion(coveredRegion);
1417        layer->setVisibleNonTransparentRegion(
1418                visibleRegion.subtract(transparentRegion));
1419    }
1420
1421    outOpaqueRegion = aboveOpaqueLayers;
1422}
1423
1424void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1425        const Region& dirty) {
1426    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1427        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1428        if (hw->getLayerStack() == layerStack) {
1429            hw->dirtyRegion.orSelf(dirty);
1430        }
1431    }
1432}
1433
1434void SurfaceFlinger::handlePageFlip()
1435{
1436    Region dirtyRegion;
1437
1438    bool visibleRegions = false;
1439    const LayerVector& layers(mDrawingState.layersSortedByZ);
1440    const size_t count = layers.size();
1441    for (size_t i=0 ; i<count ; i++) {
1442        const sp<Layer>& layer(layers[i]);
1443        const Region dirty(layer->latchBuffer(visibleRegions));
1444        const Layer::State& s(layer->getDrawingState());
1445        invalidateLayerStack(s.layerStack, dirty);
1446    }
1447
1448    mVisibleRegionsDirty |= visibleRegions;
1449}
1450
1451void SurfaceFlinger::invalidateHwcGeometry()
1452{
1453    mHwWorkListDirty = true;
1454}
1455
1456
1457void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1458        const Region& inDirtyRegion)
1459{
1460    Region dirtyRegion(inDirtyRegion);
1461
1462    // compute the invalid region
1463    hw->swapRegion.orSelf(dirtyRegion);
1464
1465    uint32_t flags = hw->getFlags();
1466    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1467        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1468        // takes a rectangle, we must make sure to update that whole
1469        // rectangle in that case
1470        dirtyRegion.set(hw->swapRegion.bounds());
1471    } else {
1472        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1473            // We need to redraw the rectangle that will be updated
1474            // (pushed to the framebuffer).
1475            // This is needed because PARTIAL_UPDATES only takes one
1476            // rectangle instead of a region (see DisplayDevice::flip())
1477            dirtyRegion.set(hw->swapRegion.bounds());
1478        } else {
1479            // we need to redraw everything (the whole screen)
1480            dirtyRegion.set(hw->bounds());
1481            hw->swapRegion = dirtyRegion;
1482        }
1483    }
1484
1485    doComposeSurfaces(hw, dirtyRegion);
1486
1487    // update the swap region and clear the dirty region
1488    hw->swapRegion.orSelf(dirtyRegion);
1489
1490    // swap buffers (presentation)
1491    hw->swapBuffers(getHwComposer());
1492}
1493
1494void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1495{
1496    RenderEngine& engine(getRenderEngine());
1497    const int32_t id = hw->getHwcDisplayId();
1498    HWComposer& hwc(getHwComposer());
1499    HWComposer::LayerListIterator cur = hwc.begin(id);
1500    const HWComposer::LayerListIterator end = hwc.end(id);
1501
1502    const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1503    if (hasGlesComposition) {
1504        if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1505            ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1506                  hw->getDisplayName().string());
1507            return;
1508        }
1509
1510        // Never touch the framebuffer if we don't have any framebuffer layers
1511        const bool hasHwcComposition = hwc.hasHwcComposition(id);
1512        if (hasHwcComposition) {
1513            // when using overlays, we assume a fully transparent framebuffer
1514            // NOTE: we could reduce how much we need to clear, for instance
1515            // remove where there are opaque FB layers. however, on some
1516            // GPUs doing a "clean slate" clear might be more efficient.
1517            // We'll revisit later if needed.
1518            engine.clearWithColor(0, 0, 0, 0);
1519        } else {
1520            // we start with the whole screen area
1521            const Region bounds(hw->getBounds());
1522
1523            // we remove the scissor part
1524            // we're left with the letterbox region
1525            // (common case is that letterbox ends-up being empty)
1526            const Region letterbox(bounds.subtract(hw->getScissor()));
1527
1528            // compute the area to clear
1529            Region region(hw->undefinedRegion.merge(letterbox));
1530
1531            // but limit it to the dirty region
1532            region.andSelf(dirty);
1533
1534            // screen is already cleared here
1535            if (!region.isEmpty()) {
1536                // can happen with SurfaceView
1537                drawWormhole(hw, region);
1538            }
1539        }
1540
1541        if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1542            // just to be on the safe side, we don't set the
1543            // scissor on the main display. It should never be needed
1544            // anyways (though in theory it could since the API allows it).
1545            const Rect& bounds(hw->getBounds());
1546            const Rect& scissor(hw->getScissor());
1547            if (scissor != bounds) {
1548                // scissor doesn't match the screen's dimensions, so we
1549                // need to clear everything outside of it and enable
1550                // the GL scissor so we don't draw anything where we shouldn't
1551
1552                // enable scissor for this frame
1553                const uint32_t height = hw->getHeight();
1554                engine.setScissor(scissor.left, height - scissor.bottom,
1555                        scissor.getWidth(), scissor.getHeight());
1556            }
1557        }
1558    }
1559
1560    /*
1561     * and then, render the layers targeted at the framebuffer
1562     */
1563
1564    const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1565    const size_t count = layers.size();
1566    const Transform& tr = hw->getTransform();
1567    if (cur != end) {
1568        // we're using h/w composer
1569        for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1570            const sp<Layer>& layer(layers[i]);
1571            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1572            if (!clip.isEmpty()) {
1573                switch (cur->getCompositionType()) {
1574                    case HWC_OVERLAY: {
1575                        if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1576                                && i
1577                                && layer->isOpaque()
1578                                && hasGlesComposition) {
1579                            // never clear the very first layer since we're
1580                            // guaranteed the FB is already cleared
1581                            layer->clearWithOpenGL(hw, clip);
1582                        }
1583                        break;
1584                    }
1585                    case HWC_FRAMEBUFFER: {
1586                        layer->draw(hw, clip);
1587                        break;
1588                    }
1589                    case HWC_FRAMEBUFFER_TARGET: {
1590                        // this should not happen as the iterator shouldn't
1591                        // let us get there.
1592                        ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1593                        break;
1594                    }
1595                }
1596            }
1597            layer->setAcquireFence(hw, *cur);
1598        }
1599    } else {
1600        // we're not using h/w composer
1601        for (size_t i=0 ; i<count ; ++i) {
1602            const sp<Layer>& layer(layers[i]);
1603            const Region clip(dirty.intersect(
1604                    tr.transform(layer->visibleRegion)));
1605            if (!clip.isEmpty()) {
1606                layer->draw(hw, clip);
1607            }
1608        }
1609    }
1610
1611    // disable scissor at the end of the frame
1612    engine.disableScissor();
1613}
1614
1615void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
1616    const int32_t height = hw->getHeight();
1617    RenderEngine& engine(getRenderEngine());
1618    engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
1619}
1620
1621void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1622        const sp<IBinder>& handle,
1623        const sp<IGraphicBufferProducer>& gbc,
1624        const sp<Layer>& lbc)
1625{
1626    // attach this layer to the client
1627    client->attachLayer(handle, lbc);
1628
1629    // add this layer to the current state list
1630    Mutex::Autolock _l(mStateLock);
1631    mCurrentState.layersSortedByZ.add(lbc);
1632    mGraphicBufferProducerList.add(gbc->asBinder());
1633}
1634
1635status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
1636    Mutex::Autolock _l(mStateLock);
1637    ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1638    if (index >= 0) {
1639        mLayersPendingRemoval.push(layer);
1640        mLayersRemoved = true;
1641        setTransactionFlags(eTransactionNeeded);
1642        return NO_ERROR;
1643    }
1644    return status_t(index);
1645}
1646
1647uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) {
1648    return android_atomic_release_load(&mTransactionFlags);
1649}
1650
1651uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
1652    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1653}
1654
1655uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
1656    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1657    if ((old & flags)==0) { // wake the server up
1658        signalTransaction();
1659    }
1660    return old;
1661}
1662
1663void SurfaceFlinger::setTransactionState(
1664        const Vector<ComposerState>& state,
1665        const Vector<DisplayState>& displays,
1666        uint32_t flags)
1667{
1668    ATRACE_CALL();
1669    Mutex::Autolock _l(mStateLock);
1670    uint32_t transactionFlags = 0;
1671
1672    if (flags & eAnimation) {
1673        // For window updates that are part of an animation we must wait for
1674        // previous animation "frames" to be handled.
1675        while (mAnimTransactionPending) {
1676            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1677            if (CC_UNLIKELY(err != NO_ERROR)) {
1678                // just in case something goes wrong in SF, return to the
1679                // caller after a few seconds.
1680                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1681                        "waiting for previous animation frame");
1682                mAnimTransactionPending = false;
1683                break;
1684            }
1685        }
1686    }
1687
1688    size_t count = displays.size();
1689    for (size_t i=0 ; i<count ; i++) {
1690        const DisplayState& s(displays[i]);
1691        transactionFlags |= setDisplayStateLocked(s);
1692    }
1693
1694    count = state.size();
1695    for (size_t i=0 ; i<count ; i++) {
1696        const ComposerState& s(state[i]);
1697        // Here we need to check that the interface we're given is indeed
1698        // one of our own. A malicious client could give us a NULL
1699        // IInterface, or one of its own or even one of our own but a
1700        // different type. All these situations would cause us to crash.
1701        //
1702        // NOTE: it would be better to use RTTI as we could directly check
1703        // that we have a Client*. however, RTTI is disabled in Android.
1704        if (s.client != NULL) {
1705            sp<IBinder> binder = s.client->asBinder();
1706            if (binder != NULL) {
1707                String16 desc(binder->getInterfaceDescriptor());
1708                if (desc == ISurfaceComposerClient::descriptor) {
1709                    sp<Client> client( static_cast<Client *>(s.client.get()) );
1710                    transactionFlags |= setClientStateLocked(client, s.state);
1711                }
1712            }
1713        }
1714    }
1715
1716    if (transactionFlags) {
1717        // this triggers the transaction
1718        setTransactionFlags(transactionFlags);
1719
1720        // if this is a synchronous transaction, wait for it to take effect
1721        // before returning.
1722        if (flags & eSynchronous) {
1723            mTransactionPending = true;
1724        }
1725        if (flags & eAnimation) {
1726            mAnimTransactionPending = true;
1727        }
1728        while (mTransactionPending) {
1729            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1730            if (CC_UNLIKELY(err != NO_ERROR)) {
1731                // just in case something goes wrong in SF, return to the
1732                // called after a few seconds.
1733                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1734                mTransactionPending = false;
1735                break;
1736            }
1737        }
1738    }
1739}
1740
1741uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1742{
1743    ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1744    if (dpyIdx < 0)
1745        return 0;
1746
1747    uint32_t flags = 0;
1748    DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1749    if (disp.isValid()) {
1750        const uint32_t what = s.what;
1751        if (what & DisplayState::eSurfaceChanged) {
1752            if (disp.surface->asBinder() != s.surface->asBinder()) {
1753                disp.surface = s.surface;
1754                flags |= eDisplayTransactionNeeded;
1755            }
1756        }
1757        if (what & DisplayState::eLayerStackChanged) {
1758            if (disp.layerStack != s.layerStack) {
1759                disp.layerStack = s.layerStack;
1760                flags |= eDisplayTransactionNeeded;
1761            }
1762        }
1763        if (what & DisplayState::eDisplayProjectionChanged) {
1764            if (disp.orientation != s.orientation) {
1765                disp.orientation = s.orientation;
1766                flags |= eDisplayTransactionNeeded;
1767            }
1768            if (disp.frame != s.frame) {
1769                disp.frame = s.frame;
1770                flags |= eDisplayTransactionNeeded;
1771            }
1772            if (disp.viewport != s.viewport) {
1773                disp.viewport = s.viewport;
1774                flags |= eDisplayTransactionNeeded;
1775            }
1776        }
1777    }
1778    return flags;
1779}
1780
1781uint32_t SurfaceFlinger::setClientStateLocked(
1782        const sp<Client>& client,
1783        const layer_state_t& s)
1784{
1785    uint32_t flags = 0;
1786    sp<Layer> layer(client->getLayerUser(s.surface));
1787    if (layer != 0) {
1788        const uint32_t what = s.what;
1789        if (what & layer_state_t::ePositionChanged) {
1790            if (layer->setPosition(s.x, s.y))
1791                flags |= eTraversalNeeded;
1792        }
1793        if (what & layer_state_t::eLayerChanged) {
1794            // NOTE: index needs to be calculated before we update the state
1795            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1796            if (layer->setLayer(s.z)) {
1797                mCurrentState.layersSortedByZ.removeAt(idx);
1798                mCurrentState.layersSortedByZ.add(layer);
1799                // we need traversal (state changed)
1800                // AND transaction (list changed)
1801                flags |= eTransactionNeeded|eTraversalNeeded;
1802            }
1803        }
1804        if (what & layer_state_t::eSizeChanged) {
1805            if (layer->setSize(s.w, s.h)) {
1806                flags |= eTraversalNeeded;
1807            }
1808        }
1809        if (what & layer_state_t::eAlphaChanged) {
1810            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1811                flags |= eTraversalNeeded;
1812        }
1813        if (what & layer_state_t::eMatrixChanged) {
1814            if (layer->setMatrix(s.matrix))
1815                flags |= eTraversalNeeded;
1816        }
1817        if (what & layer_state_t::eTransparentRegionChanged) {
1818            if (layer->setTransparentRegionHint(s.transparentRegion))
1819                flags |= eTraversalNeeded;
1820        }
1821        if (what & layer_state_t::eVisibilityChanged) {
1822            if (layer->setFlags(s.flags, s.mask))
1823                flags |= eTraversalNeeded;
1824        }
1825        if (what & layer_state_t::eCropChanged) {
1826            if (layer->setCrop(s.crop))
1827                flags |= eTraversalNeeded;
1828        }
1829        if (what & layer_state_t::eLayerStackChanged) {
1830            // NOTE: index needs to be calculated before we update the state
1831            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1832            if (layer->setLayerStack(s.layerStack)) {
1833                mCurrentState.layersSortedByZ.removeAt(idx);
1834                mCurrentState.layersSortedByZ.add(layer);
1835                // we need traversal (state changed)
1836                // AND transaction (list changed)
1837                flags |= eTransactionNeeded|eTraversalNeeded;
1838            }
1839        }
1840    }
1841    return flags;
1842}
1843
1844status_t SurfaceFlinger::createLayer(
1845        const String8& name,
1846        const sp<Client>& client,
1847        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
1848        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
1849{
1850    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1851    if (int32_t(w|h) < 0) {
1852        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1853                int(w), int(h));
1854        return BAD_VALUE;
1855    }
1856
1857    status_t result = NO_ERROR;
1858
1859    sp<Layer> layer;
1860
1861    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1862        case ISurfaceComposerClient::eFXSurfaceNormal:
1863            result = createNormalLayer(client,
1864                    name, w, h, flags, format,
1865                    handle, gbp, &layer);
1866            break;
1867        case ISurfaceComposerClient::eFXSurfaceDim:
1868            result = createDimLayer(client,
1869                    name, w, h, flags,
1870                    handle, gbp, &layer);
1871            break;
1872        default:
1873            result = BAD_VALUE;
1874            break;
1875    }
1876
1877    if (result == NO_ERROR) {
1878        addClientLayer(client, *handle, *gbp, layer);
1879        setTransactionFlags(eTransactionNeeded);
1880    }
1881    return result;
1882}
1883
1884status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
1885        const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
1886        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
1887{
1888    // initialize the surfaces
1889    switch (format) {
1890    case PIXEL_FORMAT_TRANSPARENT:
1891    case PIXEL_FORMAT_TRANSLUCENT:
1892        format = PIXEL_FORMAT_RGBA_8888;
1893        break;
1894    case PIXEL_FORMAT_OPAQUE:
1895#ifdef NO_RGBX_8888
1896        format = PIXEL_FORMAT_RGB_565;
1897#else
1898        format = PIXEL_FORMAT_RGBX_8888;
1899#endif
1900        break;
1901    }
1902
1903#ifdef NO_RGBX_8888
1904    if (format == PIXEL_FORMAT_RGBX_8888)
1905        format = PIXEL_FORMAT_RGBA_8888;
1906#endif
1907
1908    *outLayer = new Layer(this, client, name, w, h, flags);
1909    status_t err = (*outLayer)->setBuffers(w, h, format, flags);
1910    if (err == NO_ERROR) {
1911        *handle = (*outLayer)->getHandle();
1912        *gbp = (*outLayer)->getBufferQueue();
1913    }
1914
1915    ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
1916    return err;
1917}
1918
1919status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
1920        const String8& name, uint32_t w, uint32_t h, uint32_t flags,
1921        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
1922{
1923    *outLayer = new LayerDim(this, client, name, w, h, flags);
1924    *handle = (*outLayer)->getHandle();
1925    *gbp = (*outLayer)->getBufferQueue();
1926    return NO_ERROR;
1927}
1928
1929status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
1930{
1931    // called by the window manager when it wants to remove a Layer
1932    status_t err = NO_ERROR;
1933    sp<Layer> l(client->getLayerUser(handle));
1934    if (l != NULL) {
1935        err = removeLayer(l);
1936        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1937                "error removing layer=%p (%s)", l.get(), strerror(-err));
1938    }
1939    return err;
1940}
1941
1942status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
1943{
1944    // called by ~LayerCleaner() when all references to the IBinder (handle)
1945    // are gone
1946    status_t err = NO_ERROR;
1947    sp<Layer> l(layer.promote());
1948    if (l != NULL) {
1949        err = removeLayer(l);
1950        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1951                "error removing layer=%p (%s)", l.get(), strerror(-err));
1952    }
1953    return err;
1954}
1955
1956// ---------------------------------------------------------------------------
1957
1958void SurfaceFlinger::onInitializeDisplays() {
1959    // reset screen orientation and use primary layer stack
1960    Vector<ComposerState> state;
1961    Vector<DisplayState> displays;
1962    DisplayState d;
1963    d.what = DisplayState::eDisplayProjectionChanged |
1964             DisplayState::eLayerStackChanged;
1965    d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
1966    d.layerStack = 0;
1967    d.orientation = DisplayState::eOrientationDefault;
1968    d.frame.makeInvalid();
1969    d.viewport.makeInvalid();
1970    displays.add(d);
1971    setTransactionState(state, displays, 0);
1972    onScreenAcquired(getDefaultDisplayDevice());
1973
1974    const nsecs_t period =
1975            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
1976    mAnimFrameTracker.setDisplayRefreshPeriod(period);
1977}
1978
1979void SurfaceFlinger::initializeDisplays() {
1980    class MessageScreenInitialized : public MessageBase {
1981        SurfaceFlinger* flinger;
1982    public:
1983        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
1984        virtual bool handler() {
1985            flinger->onInitializeDisplays();
1986            return true;
1987        }
1988    };
1989    sp<MessageBase> msg = new MessageScreenInitialized(this);
1990    postMessageAsync(msg);  // we may be called from main thread, use async message
1991}
1992
1993
1994void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
1995    ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
1996    if (hw->isScreenAcquired()) {
1997        // this is expected, e.g. when power manager wakes up during boot
1998        ALOGD(" screen was previously acquired");
1999        return;
2000    }
2001
2002    hw->acquireScreen();
2003    int32_t type = hw->getDisplayType();
2004    if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2005        // built-in display, tell the HWC
2006        getHwComposer().acquire(type);
2007
2008        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2009            // FIXME: eventthread only knows about the main display right now
2010            mEventThread->onScreenAcquired();
2011        }
2012    }
2013    mVisibleRegionsDirty = true;
2014    repaintEverything();
2015}
2016
2017void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
2018    ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
2019    if (!hw->isScreenAcquired()) {
2020        ALOGD(" screen was previously released");
2021        return;
2022    }
2023
2024    hw->releaseScreen();
2025    int32_t type = hw->getDisplayType();
2026    if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2027        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2028            // FIXME: eventthread only knows about the main display right now
2029            mEventThread->onScreenReleased();
2030        }
2031
2032        // built-in display, tell the HWC
2033        getHwComposer().release(type);
2034    }
2035    mVisibleRegionsDirty = true;
2036    // from this point on, SF will stop drawing on this display
2037}
2038
2039void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2040    class MessageScreenAcquired : public MessageBase {
2041        SurfaceFlinger& mFlinger;
2042        sp<IBinder> mDisplay;
2043    public:
2044        MessageScreenAcquired(SurfaceFlinger& flinger,
2045                const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2046        virtual bool handler() {
2047            const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2048            if (hw == NULL) {
2049                ALOGE("Attempt to unblank null display %p", mDisplay.get());
2050            } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2051                ALOGW("Attempt to unblank virtual display");
2052            } else {
2053                mFlinger.onScreenAcquired(hw);
2054            }
2055            return true;
2056        }
2057    };
2058    sp<MessageBase> msg = new MessageScreenAcquired(*this, display);
2059    postMessageSync(msg);
2060}
2061
2062void SurfaceFlinger::blank(const sp<IBinder>& display) {
2063    class MessageScreenReleased : public MessageBase {
2064        SurfaceFlinger& mFlinger;
2065        sp<IBinder> mDisplay;
2066    public:
2067        MessageScreenReleased(SurfaceFlinger& flinger,
2068                const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2069        virtual bool handler() {
2070            const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2071            if (hw == NULL) {
2072                ALOGE("Attempt to blank null display %p", mDisplay.get());
2073            } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2074                ALOGW("Attempt to blank virtual display");
2075            } else {
2076                mFlinger.onScreenReleased(hw);
2077            }
2078            return true;
2079        }
2080    };
2081    sp<MessageBase> msg = new MessageScreenReleased(*this, display);
2082    postMessageSync(msg);
2083}
2084
2085// ---------------------------------------------------------------------------
2086
2087status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2088{
2089    String8 result;
2090
2091    IPCThreadState* ipc = IPCThreadState::self();
2092    const int pid = ipc->getCallingPid();
2093    const int uid = ipc->getCallingUid();
2094    if ((uid != AID_SHELL) &&
2095            !PermissionCache::checkPermission(sDump, pid, uid)) {
2096        result.appendFormat("Permission Denial: "
2097                "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2098    } else {
2099        // Try to get the main lock, but don't insist if we can't
2100        // (this would indicate SF is stuck, but we want to be able to
2101        // print something in dumpsys).
2102        int retry = 3;
2103        while (mStateLock.tryLock()<0 && --retry>=0) {
2104            usleep(1000000);
2105        }
2106        const bool locked(retry >= 0);
2107        if (!locked) {
2108            result.append(
2109                    "SurfaceFlinger appears to be unresponsive, "
2110                    "dumping anyways (no locks held)\n");
2111        }
2112
2113        bool dumpAll = true;
2114        size_t index = 0;
2115        size_t numArgs = args.size();
2116        if (numArgs) {
2117            if ((index < numArgs) &&
2118                    (args[index] == String16("--list"))) {
2119                index++;
2120                listLayersLocked(args, index, result);
2121                dumpAll = false;
2122            }
2123
2124            if ((index < numArgs) &&
2125                    (args[index] == String16("--latency"))) {
2126                index++;
2127                dumpStatsLocked(args, index, result);
2128                dumpAll = false;
2129            }
2130
2131            if ((index < numArgs) &&
2132                    (args[index] == String16("--latency-clear"))) {
2133                index++;
2134                clearStatsLocked(args, index, result);
2135                dumpAll = false;
2136            }
2137        }
2138
2139        if (dumpAll) {
2140            dumpAllLocked(args, index, result);
2141        }
2142
2143        if (locked) {
2144            mStateLock.unlock();
2145        }
2146    }
2147    write(fd, result.string(), result.size());
2148    return NO_ERROR;
2149}
2150
2151void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2152        String8& result) const
2153{
2154    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2155    const size_t count = currentLayers.size();
2156    for (size_t i=0 ; i<count ; i++) {
2157        const sp<Layer>& layer(currentLayers[i]);
2158        result.appendFormat("%s\n", layer->getName().string());
2159    }
2160}
2161
2162void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2163        String8& result) const
2164{
2165    String8 name;
2166    if (index < args.size()) {
2167        name = String8(args[index]);
2168        index++;
2169    }
2170
2171    const nsecs_t period =
2172            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2173    result.appendFormat("%lld\n", period);
2174
2175    if (name.isEmpty()) {
2176        mAnimFrameTracker.dump(result);
2177    } else {
2178        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2179        const size_t count = currentLayers.size();
2180        for (size_t i=0 ; i<count ; i++) {
2181            const sp<Layer>& layer(currentLayers[i]);
2182            if (name == layer->getName()) {
2183                layer->dumpStats(result);
2184            }
2185        }
2186    }
2187}
2188
2189void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2190        String8& result)
2191{
2192    String8 name;
2193    if (index < args.size()) {
2194        name = String8(args[index]);
2195        index++;
2196    }
2197
2198    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2199    const size_t count = currentLayers.size();
2200    for (size_t i=0 ; i<count ; i++) {
2201        const sp<Layer>& layer(currentLayers[i]);
2202        if (name.isEmpty() || (name == layer->getName())) {
2203            layer->clearStats();
2204        }
2205    }
2206
2207    mAnimFrameTracker.clear();
2208}
2209
2210// This should only be called from the main thread.  Otherwise it would need
2211// the lock and should use mCurrentState rather than mDrawingState.
2212void SurfaceFlinger::logFrameStats() {
2213    const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2214    const size_t count = drawingLayers.size();
2215    for (size_t i=0 ; i<count ; i++) {
2216        const sp<Layer>& layer(drawingLayers[i]);
2217        layer->logFrameStats();
2218    }
2219
2220    mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2221}
2222
2223/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2224{
2225    static const char* config =
2226            " [sf"
2227#ifdef NO_RGBX_8888
2228            " NO_RGBX_8888"
2229#endif
2230#ifdef HAS_CONTEXT_PRIORITY
2231            " HAS_CONTEXT_PRIORITY"
2232#endif
2233#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2234            " NEVER_DEFAULT_TO_ASYNC_MODE"
2235#endif
2236#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2237            " TARGET_DISABLE_TRIPLE_BUFFERING"
2238#endif
2239            "]";
2240    result.append(config);
2241}
2242
2243void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2244        String8& result) const
2245{
2246    bool colorize = false;
2247    if (index < args.size()
2248            && (args[index] == String16("--color"))) {
2249        colorize = true;
2250        index++;
2251    }
2252
2253    Colorizer colorizer(colorize);
2254
2255    // figure out if we're stuck somewhere
2256    const nsecs_t now = systemTime();
2257    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2258    const nsecs_t inTransaction(mDebugInTransaction);
2259    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2260    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2261
2262    /*
2263     * Dump library configuration.
2264     */
2265
2266    colorizer.bold(result);
2267    result.append("Build configuration:");
2268    colorizer.reset(result);
2269    appendSfConfigString(result);
2270    appendUiConfigString(result);
2271    appendGuiConfigString(result);
2272    result.append("\n");
2273
2274    colorizer.bold(result);
2275    result.append("Sync configuration: ");
2276    colorizer.reset(result);
2277    result.append(SyncFeatures::getInstance().toString());
2278    result.append("\n");
2279
2280    /*
2281     * Dump the visible layer list
2282     */
2283    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2284    const size_t count = currentLayers.size();
2285    colorizer.bold(result);
2286    result.appendFormat("Visible layers (count = %d)\n", count);
2287    colorizer.reset(result);
2288    for (size_t i=0 ; i<count ; i++) {
2289        const sp<Layer>& layer(currentLayers[i]);
2290        layer->dump(result, colorizer);
2291    }
2292
2293    /*
2294     * Dump Display state
2295     */
2296
2297    colorizer.bold(result);
2298    result.appendFormat("Displays (%d entries)\n", mDisplays.size());
2299    colorizer.reset(result);
2300    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2301        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2302        hw->dump(result);
2303    }
2304
2305    /*
2306     * Dump SurfaceFlinger global state
2307     */
2308
2309    colorizer.bold(result);
2310    result.append("SurfaceFlinger global state:\n");
2311    colorizer.reset(result);
2312
2313    HWComposer& hwc(getHwComposer());
2314    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2315
2316    colorizer.bold(result);
2317    result.appendFormat("EGL implementation : %s\n",
2318            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2319    colorizer.reset(result);
2320    result.appendFormat("%s\n",
2321            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2322
2323    mRenderEngine->dump(result);
2324
2325    hw->undefinedRegion.dump(result, "undefinedRegion");
2326    result.appendFormat("  orientation=%d, canDraw=%d\n",
2327            hw->getOrientation(), hw->canDraw());
2328    result.appendFormat(
2329            "  last eglSwapBuffers() time: %f us\n"
2330            "  last transaction time     : %f us\n"
2331            "  transaction-flags         : %08x\n"
2332            "  refresh-rate              : %f fps\n"
2333            "  x-dpi                     : %f\n"
2334            "  y-dpi                     : %f\n"
2335            "  EGL_NATIVE_VISUAL_ID      : %d\n"
2336            "  gpu_to_cpu_unsupported    : %d\n"
2337            ,
2338            mLastSwapBufferTime/1000.0,
2339            mLastTransactionTime/1000.0,
2340            mTransactionFlags,
2341            1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2342            hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2343            hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2344            mEGLNativeVisualId,
2345            !mGpuToCpuSupported);
2346
2347    result.appendFormat("  eglSwapBuffers time: %f us\n",
2348            inSwapBuffersDuration/1000.0);
2349
2350    result.appendFormat("  transaction time: %f us\n",
2351            inTransactionDuration/1000.0);
2352
2353    /*
2354     * VSYNC state
2355     */
2356    mEventThread->dump(result);
2357
2358    /*
2359     * Dump HWComposer state
2360     */
2361    colorizer.bold(result);
2362    result.append("h/w composer state:\n");
2363    colorizer.reset(result);
2364    result.appendFormat("  h/w composer %s and %s\n",
2365            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2366                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2367    hwc.dump(result);
2368
2369    /*
2370     * Dump gralloc state
2371     */
2372    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2373    alloc.dump(result);
2374}
2375
2376const Vector< sp<Layer> >&
2377SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2378    // Note: mStateLock is held here
2379    wp<IBinder> dpy;
2380    for (size_t i=0 ; i<mDisplays.size() ; i++) {
2381        if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2382            dpy = mDisplays.keyAt(i);
2383            break;
2384        }
2385    }
2386    if (dpy == NULL) {
2387        ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2388        // Just use the primary display so we have something to return
2389        dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2390    }
2391    return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2392}
2393
2394bool SurfaceFlinger::startDdmConnection()
2395{
2396    void* libddmconnection_dso =
2397            dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2398    if (!libddmconnection_dso) {
2399        return false;
2400    }
2401    void (*DdmConnection_start)(const char* name);
2402    DdmConnection_start =
2403            (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2404    if (!DdmConnection_start) {
2405        dlclose(libddmconnection_dso);
2406        return false;
2407    }
2408    (*DdmConnection_start)(getServiceName());
2409    return true;
2410}
2411
2412status_t SurfaceFlinger::onTransact(
2413    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2414{
2415    switch (code) {
2416        case CREATE_CONNECTION:
2417        case CREATE_DISPLAY:
2418        case SET_TRANSACTION_STATE:
2419        case BOOT_FINISHED:
2420        case BLANK:
2421        case UNBLANK:
2422        {
2423            // codes that require permission check
2424            IPCThreadState* ipc = IPCThreadState::self();
2425            const int pid = ipc->getCallingPid();
2426            const int uid = ipc->getCallingUid();
2427            if ((uid != AID_GRAPHICS) &&
2428                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2429                ALOGE("Permission Denial: "
2430                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2431                return PERMISSION_DENIED;
2432            }
2433            break;
2434        }
2435        case CAPTURE_SCREEN:
2436        {
2437            // codes that require permission check
2438            IPCThreadState* ipc = IPCThreadState::self();
2439            const int pid = ipc->getCallingPid();
2440            const int uid = ipc->getCallingUid();
2441            if ((uid != AID_GRAPHICS) &&
2442                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2443                ALOGE("Permission Denial: "
2444                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2445                return PERMISSION_DENIED;
2446            }
2447            break;
2448        }
2449    }
2450
2451    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2452    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2453        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2454        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2455            IPCThreadState* ipc = IPCThreadState::self();
2456            const int pid = ipc->getCallingPid();
2457            const int uid = ipc->getCallingUid();
2458            ALOGE("Permission Denial: "
2459                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2460            return PERMISSION_DENIED;
2461        }
2462        int n;
2463        switch (code) {
2464            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2465            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2466                return NO_ERROR;
2467            case 1002:  // SHOW_UPDATES
2468                n = data.readInt32();
2469                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2470                invalidateHwcGeometry();
2471                repaintEverything();
2472                return NO_ERROR;
2473            case 1004:{ // repaint everything
2474                repaintEverything();
2475                return NO_ERROR;
2476            }
2477            case 1005:{ // force transaction
2478                setTransactionFlags(
2479                        eTransactionNeeded|
2480                        eDisplayTransactionNeeded|
2481                        eTraversalNeeded);
2482                return NO_ERROR;
2483            }
2484            case 1006:{ // send empty update
2485                signalRefresh();
2486                return NO_ERROR;
2487            }
2488            case 1008:  // toggle use of hw composer
2489                n = data.readInt32();
2490                mDebugDisableHWC = n ? 1 : 0;
2491                invalidateHwcGeometry();
2492                repaintEverything();
2493                return NO_ERROR;
2494            case 1009:  // toggle use of transform hint
2495                n = data.readInt32();
2496                mDebugDisableTransformHint = n ? 1 : 0;
2497                invalidateHwcGeometry();
2498                repaintEverything();
2499                return NO_ERROR;
2500            case 1010:  // interrogate.
2501                reply->writeInt32(0);
2502                reply->writeInt32(0);
2503                reply->writeInt32(mDebugRegion);
2504                reply->writeInt32(0);
2505                reply->writeInt32(mDebugDisableHWC);
2506                return NO_ERROR;
2507            case 1013: {
2508                Mutex::Autolock _l(mStateLock);
2509                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2510                reply->writeInt32(hw->getPageFlipCount());
2511            }
2512            return NO_ERROR;
2513        }
2514    }
2515    return err;
2516}
2517
2518void SurfaceFlinger::repaintEverything() {
2519    android_atomic_or(1, &mRepaintEverything);
2520    signalTransaction();
2521}
2522
2523// ---------------------------------------------------------------------------
2524// Capture screen into an IGraphiBufferProducer
2525// ---------------------------------------------------------------------------
2526
2527/* The code below is here to handle b/8734824
2528 *
2529 * We create a IGraphicBufferProducer wrapper that forwards all calls
2530 * to the calling binder thread, where they are executed. This allows
2531 * the calling thread to be reused (on the other side) and not
2532 * depend on having "enough" binder threads to handle the requests.
2533 *
2534 */
2535
2536class GraphicProducerWrapper : public BBinder, public MessageHandler {
2537    sp<IGraphicBufferProducer> impl;
2538    sp<Looper> looper;
2539    status_t result;
2540    bool exitPending;
2541    bool exitRequested;
2542    mutable Barrier barrier;
2543    volatile int32_t memoryBarrier;
2544    uint32_t code;
2545    Parcel const* data;
2546    Parcel* reply;
2547
2548    enum {
2549        MSG_API_CALL,
2550        MSG_EXIT
2551    };
2552
2553    /*
2554     * this is called by our "fake" BpGraphicBufferProducer. We package the
2555     * data and reply Parcel and forward them to the calling thread.
2556     */
2557    virtual status_t transact(uint32_t code,
2558            const Parcel& data, Parcel* reply, uint32_t flags) {
2559        this->code = code;
2560        this->data = &data;
2561        this->reply = reply;
2562        android_atomic_acquire_store(0, &memoryBarrier);
2563        if (exitPending) {
2564            // if we've exited, we run the message synchronously right here
2565            handleMessage(Message(MSG_API_CALL));
2566        } else {
2567            barrier.close();
2568            looper->sendMessage(this, Message(MSG_API_CALL));
2569            barrier.wait();
2570        }
2571        return NO_ERROR;
2572    }
2573
2574    /*
2575     * here we run on the binder calling thread. All we've got to do is
2576     * call the real BpGraphicBufferProducer.
2577     */
2578    virtual void handleMessage(const Message& message) {
2579        android_atomic_release_load(&memoryBarrier);
2580        if (message.what == MSG_API_CALL) {
2581            impl->asBinder()->transact(code, data[0], reply);
2582            barrier.open();
2583        } else if (message.what == MSG_EXIT) {
2584            exitRequested = true;
2585        }
2586    }
2587
2588public:
2589    GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) :
2590        impl(impl), looper(new Looper(true)), result(NO_ERROR),
2591        exitPending(false), exitRequested(false) {
2592    }
2593
2594    status_t waitForResponse() {
2595        do {
2596            looper->pollOnce(-1);
2597        } while (!exitRequested);
2598        return result;
2599    }
2600
2601    void exit(status_t result) {
2602        this->result = result;
2603        exitPending = true;
2604        looper->sendMessage(this, Message(MSG_EXIT));
2605    }
2606};
2607
2608
2609status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2610        const sp<IGraphicBufferProducer>& producer,
2611        uint32_t reqWidth, uint32_t reqHeight,
2612        uint32_t minLayerZ, uint32_t maxLayerZ) {
2613
2614    if (CC_UNLIKELY(display == 0))
2615        return BAD_VALUE;
2616
2617    if (CC_UNLIKELY(producer == 0))
2618        return BAD_VALUE;
2619
2620    // if we have secure windows on this display, never allow the screen capture
2621    // unless the producer interface is local (i.e.: we can take a screenshot for
2622    // ourselves).
2623    if (!producer->asBinder()->localBinder()) {
2624        Mutex::Autolock _l(mStateLock);
2625        sp<const DisplayDevice> hw(getDisplayDevice(display));
2626        if (hw->getSecureLayerVisible()) {
2627            ALOGW("FB is protected: PERMISSION_DENIED");
2628            return PERMISSION_DENIED;
2629        }
2630    }
2631
2632    class MessageCaptureScreen : public MessageBase {
2633        SurfaceFlinger* flinger;
2634        sp<IBinder> display;
2635        sp<IGraphicBufferProducer> producer;
2636        uint32_t reqWidth, reqHeight;
2637        uint32_t minLayerZ,maxLayerZ;
2638        status_t result;
2639    public:
2640        MessageCaptureScreen(SurfaceFlinger* flinger,
2641                const sp<IBinder>& display,
2642                const sp<IGraphicBufferProducer>& producer,
2643                uint32_t reqWidth, uint32_t reqHeight,
2644                uint32_t minLayerZ, uint32_t maxLayerZ)
2645            : flinger(flinger), display(display), producer(producer),
2646              reqWidth(reqWidth), reqHeight(reqHeight),
2647              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2648              result(PERMISSION_DENIED)
2649        {
2650        }
2651        status_t getResult() const {
2652            return result;
2653        }
2654        virtual bool handler() {
2655            Mutex::Autolock _l(flinger->mStateLock);
2656            sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
2657            result = flinger->captureScreenImplLocked(hw,
2658                    producer, reqWidth, reqHeight, minLayerZ, maxLayerZ);
2659            static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
2660            return true;
2661        }
2662    };
2663
2664    // make sure to process transactions before screenshots -- a transaction
2665    // might already be pending but scheduled for VSYNC; this guarantees we
2666    // will handle it before the screenshot. When VSYNC finally arrives
2667    // the scheduled transaction will be a no-op. If no transactions are
2668    // scheduled at this time, this will end-up being a no-op as well.
2669    mEventQueue.invalidateTransactionNow();
2670
2671    // this creates a "fake" BBinder which will serve as a "fake" remote
2672    // binder to receive the marshaled calls and forward them to the
2673    // real remote (a BpGraphicBufferProducer)
2674    sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
2675
2676    // the asInterface() call below creates our "fake" BpGraphicBufferProducer
2677    // which does the marshaling work forwards to our "fake remote" above.
2678    sp<MessageBase> msg = new MessageCaptureScreen(this,
2679            display, IGraphicBufferProducer::asInterface( wrapper ),
2680            reqWidth, reqHeight, minLayerZ, maxLayerZ);
2681
2682    status_t res = postMessageAsync(msg);
2683    if (res == NO_ERROR) {
2684        res = wrapper->waitForResponse();
2685    }
2686    return res;
2687}
2688
2689
2690void SurfaceFlinger::renderScreenImplLocked(
2691        const sp<const DisplayDevice>& hw,
2692        uint32_t reqWidth, uint32_t reqHeight,
2693        uint32_t minLayerZ, uint32_t maxLayerZ,
2694        bool yswap)
2695{
2696    ATRACE_CALL();
2697    RenderEngine& engine(getRenderEngine());
2698
2699    // get screen geometry
2700    const uint32_t hw_w = hw->getWidth();
2701    const uint32_t hw_h = hw->getHeight();
2702    const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
2703
2704    // make sure to clear all GL error flags
2705    engine.checkErrors();
2706
2707    // set-up our viewport
2708    engine.setViewportAndProjection(reqWidth, reqHeight, hw_w, hw_h, yswap);
2709    engine.disableTexturing();
2710
2711    // redraw the screen entirely...
2712    engine.clearWithColor(0, 0, 0, 1);
2713
2714    const LayerVector& layers( mDrawingState.layersSortedByZ );
2715    const size_t count = layers.size();
2716    for (size_t i=0 ; i<count ; ++i) {
2717        const sp<Layer>& layer(layers[i]);
2718        const Layer::State& state(layer->getDrawingState());
2719        if (state.layerStack == hw->getLayerStack()) {
2720            if (state.z >= minLayerZ && state.z <= maxLayerZ) {
2721                if (layer->isVisible()) {
2722                    if (filtering) layer->setFiltering(true);
2723                    layer->draw(hw);
2724                    if (filtering) layer->setFiltering(false);
2725                }
2726            }
2727        }
2728    }
2729
2730    // compositionComplete is needed for older driver
2731    hw->compositionComplete();
2732}
2733
2734
2735status_t SurfaceFlinger::captureScreenImplLocked(
2736        const sp<const DisplayDevice>& hw,
2737        const sp<IGraphicBufferProducer>& producer,
2738        uint32_t reqWidth, uint32_t reqHeight,
2739        uint32_t minLayerZ, uint32_t maxLayerZ)
2740{
2741    ATRACE_CALL();
2742
2743    // get screen geometry
2744    const uint32_t hw_w = hw->getWidth();
2745    const uint32_t hw_h = hw->getHeight();
2746
2747    if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
2748        ALOGE("size mismatch (%d, %d) > (%d, %d)",
2749                reqWidth, reqHeight, hw_w, hw_h);
2750        return BAD_VALUE;
2751    }
2752
2753    reqWidth  = (!reqWidth)  ? hw_w : reqWidth;
2754    reqHeight = (!reqHeight) ? hw_h : reqHeight;
2755
2756    // create a surface (because we're a producer, and we need to
2757    // dequeue/queue a buffer)
2758    sp<Surface> sur = new Surface(producer);
2759    ANativeWindow* window = sur.get();
2760
2761    status_t result = NO_ERROR;
2762    if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
2763        uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
2764                        GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
2765
2766        int err = 0;
2767        err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
2768        err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
2769        err |= native_window_set_usage(window, usage);
2770
2771        if (err == NO_ERROR) {
2772            ANativeWindowBuffer* buffer;
2773            /* TODO: Once we have the sync framework everywhere this can use
2774             * server-side waits on the fence that dequeueBuffer returns.
2775             */
2776            result = native_window_dequeue_buffer_and_wait(window,  &buffer);
2777            if (result == NO_ERROR) {
2778                // create an EGLImage from the buffer so we can later
2779                // turn it into a texture
2780                EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
2781                        EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
2782                if (image != EGL_NO_IMAGE_KHR) {
2783                    // this binds the given EGLImage as a framebuffer for the
2784                    // duration of this scope.
2785                    RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
2786                    if (imageBond.getStatus() == NO_ERROR) {
2787                        // this will in fact render into our dequeued buffer
2788                        // via an FBO, which means we didn't have to create
2789                        // an EGLSurface and therefore we're not
2790                        // dependent on the context's EGLConfig.
2791                        renderScreenImplLocked(hw, reqWidth, reqHeight,
2792                                minLayerZ, maxLayerZ, true);
2793                    } else {
2794                        ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
2795                        result = INVALID_OPERATION;
2796                    }
2797                    // destroy our image
2798                    eglDestroyImageKHR(mEGLDisplay, image);
2799                } else {
2800                    result = BAD_VALUE;
2801                }
2802                window->queueBuffer(window, buffer, -1);
2803            }
2804        } else {
2805            result = BAD_VALUE;
2806        }
2807        native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
2808    }
2809
2810    hw->setViewportAndProjection();
2811
2812    return result;
2813}
2814
2815void SurfaceFlinger::checkScreenshot(const sp<GraphicBuffer>& buf, void const* vaddr,
2816        const sp<const DisplayDevice>& hw,
2817        uint32_t minLayerZ, uint32_t maxLayerZ) {
2818    if (DEBUG_SCREENSHOTS) {
2819        for (ssize_t y=0 ; y<buf->height ; y++) {
2820            uint32_t const * p = (uint32_t const *)vaddr + y*buf->stride;
2821            for (ssize_t x=0 ; x<buf->width ; x++) {
2822                if (p[x] != 0xFF000000) return;
2823            }
2824        }
2825        ALOGE("*** we just took a black screenshot ***\n"
2826                "requested minz=%d, maxz=%d, layerStack=%d",
2827                minLayerZ, maxLayerZ, hw->getLayerStack());
2828        const LayerVector& layers( mDrawingState.layersSortedByZ );
2829        const size_t count = layers.size();
2830        for (size_t i=0 ; i<count ; ++i) {
2831            const sp<Layer>& layer(layers[i]);
2832            const Layer::State& state(layer->getDrawingState());
2833            const bool visible = (state.layerStack == hw->getLayerStack())
2834                                && (state.z >= minLayerZ && state.z <= maxLayerZ)
2835                                && (layer->isVisible());
2836            ALOGE("%c index=%d, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
2837                    visible ? '+' : '-',
2838                            i, layer->getName().string(), state.layerStack, state.z,
2839                            layer->isVisible(), state.flags, state.alpha);
2840        }
2841    }
2842}
2843
2844// ---------------------------------------------------------------------------
2845
2846SurfaceFlinger::LayerVector::LayerVector() {
2847}
2848
2849SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2850    : SortedVector<sp<Layer> >(rhs) {
2851}
2852
2853int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2854    const void* rhs) const
2855{
2856    // sort layers per layer-stack, then by z-order and finally by sequence
2857    const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
2858    const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
2859
2860    uint32_t ls = l->getCurrentState().layerStack;
2861    uint32_t rs = r->getCurrentState().layerStack;
2862    if (ls != rs)
2863        return ls - rs;
2864
2865    uint32_t lz = l->getCurrentState().z;
2866    uint32_t rz = r->getCurrentState().z;
2867    if (lz != rz)
2868        return lz - rz;
2869
2870    return l->sequence - r->sequence;
2871}
2872
2873// ---------------------------------------------------------------------------
2874
2875SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2876    : type(DisplayDevice::DISPLAY_ID_INVALID) {
2877}
2878
2879SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2880    : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0) {
2881    viewport.makeInvalid();
2882    frame.makeInvalid();
2883}
2884
2885// ---------------------------------------------------------------------------
2886
2887}; // namespace android
2888
2889
2890#if defined(__gl_h_)
2891#error "don't include gl/gl.h in this file"
2892#endif
2893
2894#if defined(__gl2_h_)
2895#error "don't include gl2/gl2.h in this file"
2896#endif
2897