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