SurfaceFlinger.cpp revision 43601a2dc320a271ff8c3765ff61414a07221635
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#include <GLES/gl.h>
27
28#include <cutils/log.h>
29#include <cutils/properties.h>
30
31#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
33#include <binder/MemoryHeapBase.h>
34#include <binder/PermissionCache.h>
35
36#include <ui/DisplayInfo.h>
37
38#include <gui/BitTube.h>
39#include <gui/BufferQueue.h>
40#include <gui/IDisplayEventConnection.h>
41#include <gui/SurfaceTextureClient.h>
42
43#include <ui/GraphicBufferAllocator.h>
44#include <ui/PixelFormat.h>
45
46#include <utils/String8.h>
47#include <utils/String16.h>
48#include <utils/StopWatch.h>
49#include <utils/Trace.h>
50
51#include <private/android_filesystem_config.h>
52
53#include "clz.h"
54#include "DdmConnection.h"
55#include "DisplayDevice.h"
56#include "Client.h"
57#include "EventThread.h"
58#include "GLExtensions.h"
59#include "Layer.h"
60#include "LayerDim.h"
61#include "LayerScreenshot.h"
62#include "SurfaceFlinger.h"
63
64#include "DisplayHardware/FramebufferSurface.h"
65#include "DisplayHardware/HWComposer.h"
66
67
68#define EGL_VERSION_HW_ANDROID  0x3143
69
70#define DISPLAY_COUNT       1
71
72namespace android {
73// ---------------------------------------------------------------------------
74
75const String16 sHardwareTest("android.permission.HARDWARE_TEST");
76const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
77const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
78const String16 sDump("android.permission.DUMP");
79
80// ---------------------------------------------------------------------------
81
82SurfaceFlinger::SurfaceFlinger()
83    :   BnSurfaceComposer(), Thread(false),
84        mTransactionFlags(0),
85        mTransationPending(false),
86        mLayersRemoved(false),
87        mRepaintEverything(0),
88        mBootTime(systemTime()),
89        mVisibleRegionsDirty(false),
90        mHwWorkListDirty(false),
91        mDebugRegion(0),
92        mDebugDDMS(0),
93        mDebugDisableHWC(0),
94        mDebugDisableTransformHint(0),
95        mDebugInSwapBuffers(0),
96        mLastSwapBufferTime(0),
97        mDebugInTransaction(0),
98        mLastTransactionTime(0),
99        mBootFinished(false)
100{
101    ALOGI("SurfaceFlinger is starting");
102
103    // debugging stuff...
104    char value[PROPERTY_VALUE_MAX];
105
106    property_get("debug.sf.showupdates", value, "0");
107    mDebugRegion = atoi(value);
108
109    property_get("debug.sf.ddms", value, "0");
110    mDebugDDMS = atoi(value);
111    if (mDebugDDMS) {
112        if (!startDdmConnection()) {
113            // start failed, and DDMS debugging not enabled
114            mDebugDDMS = 0;
115        }
116    }
117    ALOGI_IF(mDebugRegion, "showupdates enabled");
118    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
119}
120
121void SurfaceFlinger::onFirstRef()
122{
123    mEventQueue.init(this);
124
125    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
126
127    // Wait for the main thread to be done with its initialization
128    mReadyToRunBarrier.wait();
129}
130
131
132SurfaceFlinger::~SurfaceFlinger()
133{
134    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
135    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
136    eglTerminate(display);
137}
138
139void SurfaceFlinger::binderDied(const wp<IBinder>& who)
140{
141    // the window manager died on us. prepare its eulogy.
142
143    // restore initial conditions (default device unblank, etc)
144    initializeDisplays();
145
146    // restart the boot-animation
147    startBootAnim();
148}
149
150sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
151{
152    sp<ISurfaceComposerClient> bclient;
153    sp<Client> client(new Client(this));
154    status_t err = client->initCheck();
155    if (err == NO_ERROR) {
156        bclient = client;
157    }
158    return bclient;
159}
160
161sp<IBinder> SurfaceFlinger::createDisplay()
162{
163    class DisplayToken : public BBinder {
164        sp<SurfaceFlinger> flinger;
165        virtual ~DisplayToken() {
166             // no more references, this display must be terminated
167             Mutex::Autolock _l(flinger->mStateLock);
168             flinger->mCurrentState.displays.removeItem(this);
169             flinger->setTransactionFlags(eDisplayTransactionNeeded);
170         }
171     public:
172        DisplayToken(const sp<SurfaceFlinger>& flinger)
173            : flinger(flinger) {
174        }
175    };
176
177    sp<BBinder> token = new DisplayToken(this);
178
179    Mutex::Autolock _l(mStateLock);
180    DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
181    mCurrentState.displays.add(token, info);
182
183    return token;
184}
185
186sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
187    if (uint32_t(id) >= DisplayDevice::NUM_DISPLAY_TYPES) {
188        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
189        return NULL;
190    }
191    return mDefaultDisplays[id];
192}
193
194sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
195{
196    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
197    return gba;
198}
199
200void SurfaceFlinger::bootFinished()
201{
202    const nsecs_t now = systemTime();
203    const nsecs_t duration = now - mBootTime;
204    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
205    mBootFinished = true;
206
207    // wait patiently for the window manager death
208    const String16 name("window");
209    sp<IBinder> window(defaultServiceManager()->getService(name));
210    if (window != 0) {
211        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
212    }
213
214    // stop boot animation
215    // formerly we would just kill the process, but we now ask it to exit so it
216    // can choose where to stop the animation.
217    property_set("service.bootanim.exit", "1");
218}
219
220void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
221    class MessageDestroyGLTexture : public MessageBase {
222        GLuint texture;
223    public:
224        MessageDestroyGLTexture(GLuint texture)
225            : texture(texture) {
226        }
227        virtual bool handler() {
228            glDeleteTextures(1, &texture);
229            return true;
230        }
231    };
232    postMessageAsync(new MessageDestroyGLTexture(texture));
233}
234
235status_t SurfaceFlinger::selectConfigForPixelFormat(
236        EGLDisplay dpy,
237        EGLint const* attrs,
238        PixelFormat format,
239        EGLConfig* outConfig)
240{
241    EGLConfig config = NULL;
242    EGLint numConfigs = -1, n=0;
243    eglGetConfigs(dpy, NULL, 0, &numConfigs);
244    EGLConfig* const configs = new EGLConfig[numConfigs];
245    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
246    for (int i=0 ; i<n ; i++) {
247        EGLint nativeVisualId = 0;
248        eglGetConfigAttrib(dpy, configs[i], EGL_NATIVE_VISUAL_ID, &nativeVisualId);
249        if (nativeVisualId>0 && format == nativeVisualId) {
250            *outConfig = configs[i];
251            delete [] configs;
252            return NO_ERROR;
253        }
254    }
255    delete [] configs;
256    return NAME_NOT_FOUND;
257}
258
259EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
260    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
261    // it is to be used with WIFI displays
262    EGLConfig config;
263    EGLint dummy;
264    status_t err;
265    EGLint attribs[] = {
266            EGL_SURFACE_TYPE,           EGL_WINDOW_BIT,
267            EGL_RECORDABLE_ANDROID,     EGL_TRUE,
268            EGL_NONE
269    };
270    err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
271    if (err) {
272        // maybe we failed because of EGL_RECORDABLE_ANDROID
273        ALOGW("couldn't find an EGLConfig with EGL_RECORDABLE_ANDROID");
274        attribs[2] = EGL_NONE;
275        err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
276    }
277    ALOGE_IF(err, "couldn't find an EGLConfig matching the screen format");
278    if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) {
279        ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
280    }
281    return config;
282}
283
284EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) {
285    // Also create our EGLContext
286    EGLint contextAttributes[] = {
287#ifdef EGL_IMG_context_priority
288#ifdef HAS_CONTEXT_PRIORITY
289#warning "using EGL_IMG_context_priority"
290            EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
291#endif
292#endif
293            EGL_NONE, EGL_NONE
294    };
295    EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
296    ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
297    return ctxt;
298}
299
300void SurfaceFlinger::initializeGL(EGLDisplay display, const sp<DisplayDevice>& hw) {
301    EGLBoolean result = DisplayDevice::makeCurrent(display, hw, mEGLContext);
302    if (!result) {
303        ALOGE("Couldn't create a working GLES context. check logs. exiting...");
304        exit(0);
305    }
306
307    GLExtensions& extensions(GLExtensions::getInstance());
308    extensions.initWithGLStrings(
309            glGetString(GL_VENDOR),
310            glGetString(GL_RENDERER),
311            glGetString(GL_VERSION),
312            glGetString(GL_EXTENSIONS),
313            eglQueryString(display, EGL_VENDOR),
314            eglQueryString(display, EGL_VERSION),
315            eglQueryString(display, EGL_EXTENSIONS));
316
317    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
318    glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
319
320    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
321    glPixelStorei(GL_PACK_ALIGNMENT, 4);
322    glEnableClientState(GL_VERTEX_ARRAY);
323    glShadeModel(GL_FLAT);
324    glDisable(GL_DITHER);
325    glDisable(GL_CULL_FACE);
326
327    struct pack565 {
328        inline uint16_t operator() (int r, int g, int b) const {
329            return (r<<11)|(g<<5)|b;
330        }
331    } pack565;
332
333    const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
334    glGenTextures(1, &mProtectedTexName);
335    glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
336    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
337    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
338    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
339    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
340    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
341            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
342
343    // print some debugging info
344    EGLint r,g,b,a;
345    eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE,   &r);
346    eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g);
347    eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE,  &b);
348    eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a);
349    ALOGI("EGL informations:");
350    ALOGI("vendor    : %s", extensions.getEglVendor());
351    ALOGI("version   : %s", extensions.getEglVersion());
352    ALOGI("extensions: %s", extensions.getEglExtension());
353    ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
354    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
355    ALOGI("OpenGL ES informations:");
356    ALOGI("vendor    : %s", extensions.getVendor());
357    ALOGI("renderer  : %s", extensions.getRenderer());
358    ALOGI("version   : %s", extensions.getVersion());
359    ALOGI("extensions: %s", extensions.getExtension());
360    ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
361    ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
362}
363
364status_t SurfaceFlinger::readyToRun()
365{
366    ALOGI(  "SurfaceFlinger's main thread ready to run. "
367            "Initializing graphics H/W...");
368
369    // initialize EGL for the default display
370    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
371    eglInitialize(mEGLDisplay, NULL, NULL);
372
373    // Initialize the H/W composer object.  There may or may not be an
374    // actual hardware composer underneath.
375    mHwc = new HWComposer(this,
376            *static_cast<HWComposer::EventHandler *>(this));
377
378    // Initialize the main display
379    // create native window to main display
380    sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc);
381    if (fbs == NULL) {
382        ALOGE("Display subsystem failed to initialize. check logs. exiting...");
383        exit(0);
384    }
385
386    sp<SurfaceTextureClient> stc(new SurfaceTextureClient(
387            static_cast<sp<ISurfaceTexture> >(fbs->getBufferQueue())));
388
389    // initialize the config and context
390    int format;
391    ANativeWindow* const anw = stc.get();
392    anw->query(anw, NATIVE_WINDOW_FORMAT, &format);
393    mEGLConfig  = selectEGLConfig(mEGLDisplay, format);
394    mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
395
396    // initialize our main display hardware
397
398    for (size_t i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
399        mDefaultDisplays[i] = new BBinder();
400        mCurrentState.displays.add(mDefaultDisplays[i],
401                DisplayDeviceState((DisplayDevice::DisplayType)i));
402    }
403    sp<DisplayDevice> hw = new DisplayDevice(this,
404            DisplayDevice::DISPLAY_PRIMARY,
405            mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY],
406            anw, fbs, mEGLConfig);
407    mDisplays.add(mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY], hw);
408
409    //  initialize OpenGL ES
410    initializeGL(mEGLDisplay, hw);
411
412    // start the EventThread
413    mEventThread = new EventThread(this);
414    mEventQueue.setEventThread(mEventThread);
415
416    // initialize our drawing state
417    mDrawingState = mCurrentState;
418
419    // We're now ready to accept clients...
420    mReadyToRunBarrier.open();
421
422    // set initial conditions (e.g. unblank default device)
423    initializeDisplays();
424
425    // start boot animation
426    startBootAnim();
427
428    return NO_ERROR;
429}
430
431int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
432    return (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) ?
433            type : mHwc->allocateDisplayId();
434}
435
436void SurfaceFlinger::startBootAnim() {
437    // start boot animation
438    property_set("service.bootanim.exit", "0");
439    property_set("ctl.start", "bootanim");
440}
441
442uint32_t SurfaceFlinger::getMaxTextureSize() const {
443    return mMaxTextureSize;
444}
445
446uint32_t SurfaceFlinger::getMaxViewportDims() const {
447    return mMaxViewportDims[0] < mMaxViewportDims[1] ?
448            mMaxViewportDims[0] : mMaxViewportDims[1];
449}
450
451// ----------------------------------------------------------------------------
452
453bool SurfaceFlinger::authenticateSurfaceTexture(
454        const sp<ISurfaceTexture>& surfaceTexture) const {
455    Mutex::Autolock _l(mStateLock);
456    sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
457
458    // Check the visible layer list for the ISurface
459    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
460    size_t count = currentLayers.size();
461    for (size_t i=0 ; i<count ; i++) {
462        const sp<LayerBase>& layer(currentLayers[i]);
463        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
464        if (lbc != NULL) {
465            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
466            if (lbcBinder == surfaceTextureBinder) {
467                return true;
468            }
469        }
470    }
471
472    // Check the layers in the purgatory.  This check is here so that if a
473    // SurfaceTexture gets destroyed before all the clients are done using it,
474    // the error will not be reported as "surface XYZ is not authenticated", but
475    // will instead fail later on when the client tries to use the surface,
476    // which should be reported as "surface XYZ returned an -ENODEV".  The
477    // purgatorized layers are no less authentic than the visible ones, so this
478    // should not cause any harm.
479    size_t purgatorySize =  mLayerPurgatory.size();
480    for (size_t i=0 ; i<purgatorySize ; i++) {
481        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
482        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
483        if (lbc != NULL) {
484            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
485            if (lbcBinder == surfaceTextureBinder) {
486                return true;
487            }
488        }
489    }
490
491    return false;
492}
493
494status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
495    // TODO: this is mostly here only for compatibility
496    //       the display size is needed but the display metrics should come from elsewhere
497    if (display != mDefaultDisplays[ISurfaceComposer::eDisplayIdMain]) {
498        // TODO: additional displays not yet supported
499        return BAD_INDEX;
500    }
501
502    const HWComposer& hwc(getHwComposer());
503    float xdpi = hwc.getDpiX(HWC_DISPLAY_PRIMARY);
504    float ydpi = hwc.getDpiY(HWC_DISPLAY_PRIMARY);
505
506    // TODO: Not sure if display density should handled by SF any longer
507    class Density {
508        static int getDensityFromProperty(char const* propName) {
509            char property[PROPERTY_VALUE_MAX];
510            int density = 0;
511            if (property_get(propName, property, NULL) > 0) {
512                density = atoi(property);
513            }
514            return density;
515        }
516    public:
517        static int getEmuDensity() {
518            return getDensityFromProperty("qemu.sf.lcd_density"); }
519        static int getBuildDensity()  {
520            return getDensityFromProperty("ro.sf.lcd_density"); }
521    };
522    // The density of the device is provided by a build property
523    float density = Density::getBuildDensity() / 160.0f;
524    if (density == 0) {
525        // the build doesn't provide a density -- this is wrong!
526        // use xdpi instead
527        ALOGE("ro.sf.lcd_density must be defined as a build property");
528        density = xdpi / 160.0f;
529    }
530    if (Density::getEmuDensity()) {
531        // if "qemu.sf.lcd_density" is specified, it overrides everything
532        xdpi = ydpi = density = Density::getEmuDensity();
533        density /= 160.0f;
534    }
535
536    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
537    info->w = hw->getWidth();
538    info->h = hw->getHeight();
539    info->xdpi = xdpi;
540    info->ydpi = ydpi;
541    info->fps = float(1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY));
542    info->density = density;
543    info->orientation = hw->getOrientation();
544    // TODO: this needs to go away (currently needed only by webkit)
545    getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo);
546    return NO_ERROR;
547}
548
549// ----------------------------------------------------------------------------
550
551sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
552    return mEventThread->createEventConnection();
553}
554
555void SurfaceFlinger::connectDisplay(const sp<ISurfaceTexture>& surface) {
556
557    sp<IBinder> token;
558    { // scope for the lock
559        Mutex::Autolock _l(mStateLock);
560        token = mExtDisplayToken;
561    }
562
563    if (token == 0) {
564        token = createDisplay();
565    }
566
567    { // scope for the lock
568        Mutex::Autolock _l(mStateLock);
569        if (surface == 0) {
570            // release our current display. we're guarantee to have
571            // a reference to it (token), while we hold the lock
572            mExtDisplayToken = 0;
573        } else {
574            mExtDisplayToken = token;
575        }
576
577        DisplayDeviceState& info(mCurrentState.displays.editValueFor(token));
578        info.surface = surface;
579        setTransactionFlags(eDisplayTransactionNeeded);
580    }
581}
582
583// ----------------------------------------------------------------------------
584
585void SurfaceFlinger::waitForEvent() {
586    mEventQueue.waitMessage();
587}
588
589void SurfaceFlinger::signalTransaction() {
590    mEventQueue.invalidate();
591}
592
593void SurfaceFlinger::signalLayerUpdate() {
594    mEventQueue.invalidate();
595}
596
597void SurfaceFlinger::signalRefresh() {
598    mEventQueue.refresh();
599}
600
601status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
602        nsecs_t reltime, uint32_t flags) {
603    return mEventQueue.postMessage(msg, reltime);
604}
605
606status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
607        nsecs_t reltime, uint32_t flags) {
608    status_t res = mEventQueue.postMessage(msg, reltime);
609    if (res == NO_ERROR) {
610        msg->wait();
611    }
612    return res;
613}
614
615bool SurfaceFlinger::threadLoop() {
616    waitForEvent();
617    return true;
618}
619
620void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
621    if (mEventThread == NULL) {
622        // This is a temporary workaround for b/7145521.  A non-null pointer
623        // does not mean EventThread has finished initializing, so this
624        // is not a correct fix.
625        ALOGW("WARNING: EventThread not started, ignoring vsync");
626        return;
627    }
628    if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
629        // we should only receive DisplayDevice::DisplayType from the vsync callback
630        const wp<IBinder>& token(mDefaultDisplays[type]);
631        mEventThread->onVSyncReceived(token, timestamp);
632    }
633}
634
635void SurfaceFlinger::eventControl(int event, int enabled) {
636    getHwComposer().eventControl(event, enabled);
637}
638
639void SurfaceFlinger::onMessageReceived(int32_t what) {
640    ATRACE_CALL();
641    switch (what) {
642    case MessageQueue::INVALIDATE:
643        handleMessageTransaction();
644        handleMessageInvalidate();
645        signalRefresh();
646        break;
647    case MessageQueue::REFRESH:
648        handleMessageRefresh();
649        break;
650    }
651}
652
653void SurfaceFlinger::handleMessageTransaction() {
654    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
655    if (transactionFlags) {
656        handleTransaction(transactionFlags);
657    }
658}
659
660void SurfaceFlinger::handleMessageInvalidate() {
661    ATRACE_CALL();
662    handlePageFlip();
663}
664
665void SurfaceFlinger::handleMessageRefresh() {
666    ATRACE_CALL();
667    preComposition();
668    rebuildLayerStacks();
669    setUpHWComposer();
670    doDebugFlashRegions();
671    doComposition();
672    postComposition();
673}
674
675void SurfaceFlinger::doDebugFlashRegions()
676{
677    // is debugging enabled
678    if (CC_LIKELY(!mDebugRegion))
679        return;
680
681    const bool repaintEverything = mRepaintEverything;
682    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
683        const sp<DisplayDevice>& hw(mDisplays[dpy]);
684        if (hw->canDraw()) {
685            // transform the dirty region into this screen's coordinate space
686            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
687            if (!dirtyRegion.isEmpty()) {
688                // redraw the whole screen
689                doComposeSurfaces(hw, Region(hw->bounds()));
690
691                // and draw the dirty region
692                glDisable(GL_TEXTURE_EXTERNAL_OES);
693                glDisable(GL_TEXTURE_2D);
694                glDisable(GL_BLEND);
695                glColor4f(1, 0, 1, 1);
696                const int32_t height = hw->getHeight();
697                Region::const_iterator it = dirtyRegion.begin();
698                Region::const_iterator const end = dirtyRegion.end();
699                while (it != end) {
700                    const Rect& r = *it++;
701                    GLfloat vertices[][2] = {
702                            { r.left,  height - r.top },
703                            { r.left,  height - r.bottom },
704                            { r.right, height - r.bottom },
705                            { r.right, height - r.top }
706                    };
707                    glVertexPointer(2, GL_FLOAT, 0, vertices);
708                    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
709                }
710                hw->compositionComplete();
711                // FIXME
712                if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
713                    eglSwapBuffers(mEGLDisplay, hw->getEGLSurface());
714                }
715            }
716        }
717    }
718
719    postFramebuffer();
720
721    if (mDebugRegion > 1) {
722        usleep(mDebugRegion * 1000);
723    }
724}
725
726void SurfaceFlinger::preComposition()
727{
728    bool needExtraInvalidate = false;
729    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
730    const size_t count = currentLayers.size();
731    for (size_t i=0 ; i<count ; i++) {
732        if (currentLayers[i]->onPreComposition()) {
733            needExtraInvalidate = true;
734        }
735    }
736    if (needExtraInvalidate) {
737        signalLayerUpdate();
738    }
739}
740
741void SurfaceFlinger::postComposition()
742{
743    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
744    const size_t count = currentLayers.size();
745    for (size_t i=0 ; i<count ; i++) {
746        currentLayers[i]->onPostComposition();
747    }
748}
749
750void SurfaceFlinger::rebuildLayerStacks() {
751    // rebuild the visible layer list per screen
752    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
753        ATRACE_CALL();
754        mVisibleRegionsDirty = false;
755        invalidateHwcGeometry();
756        const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
757        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
758            const sp<DisplayDevice>& hw(mDisplays[dpy]);
759            const Transform& tr(hw->getTransform());
760            const Rect bounds(hw->getBounds());
761
762            Region opaqueRegion;
763            Region dirtyRegion;
764            computeVisibleRegions(currentLayers,
765                    hw->getLayerStack(), dirtyRegion, opaqueRegion);
766
767            Vector< sp<LayerBase> > layersSortedByZ;
768            const size_t count = currentLayers.size();
769            for (size_t i=0 ; i<count ; i++) {
770                const sp<LayerBase>& layer(currentLayers[i]);
771                const Layer::State& s(layer->drawingState());
772                if (s.layerStack == hw->getLayerStack()) {
773                    Region visibleRegion(tr.transform(layer->visibleRegion));
774                    visibleRegion.andSelf(bounds);
775                    if (!visibleRegion.isEmpty()) {
776                        layersSortedByZ.add(layer);
777                    }
778                }
779            }
780            hw->setVisibleLayersSortedByZ(layersSortedByZ);
781            hw->undefinedRegion.set(bounds);
782            hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
783            hw->dirtyRegion.orSelf(dirtyRegion);
784        }
785    }
786}
787
788void SurfaceFlinger::setUpHWComposer() {
789    HWComposer& hwc(getHwComposer());
790    if (hwc.initCheck() == NO_ERROR) {
791        // build the h/w work list
792        const bool workListsDirty = mHwWorkListDirty;
793        mHwWorkListDirty = false;
794        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
795            sp<const DisplayDevice> hw(mDisplays[dpy]);
796            const int32_t id = hw->getHwcDisplayId();
797            if (id >= 0) {
798                const Vector< sp<LayerBase> >& currentLayers(
799                    hw->getVisibleLayersSortedByZ());
800                const size_t count = currentLayers.size();
801                if (hwc.createWorkList(id, count) >= 0) {
802                    HWComposer::LayerListIterator cur = hwc.begin(id);
803                    const HWComposer::LayerListIterator end = hwc.end(id);
804                    for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
805                        const sp<LayerBase>& layer(currentLayers[i]);
806
807                        if (CC_UNLIKELY(workListsDirty)) {
808                            layer->setGeometry(hw, *cur);
809                            if (mDebugDisableHWC || mDebugRegion) {
810                                cur->setSkip(true);
811                            }
812                        }
813
814                        /*
815                         * update the per-frame h/w composer data for each layer
816                         * and build the transparent region of the FB
817                         */
818                        layer->setPerFrameData(hw, *cur);
819                    }
820                }
821            }
822        }
823        status_t err = hwc.prepare();
824        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
825    }
826}
827
828void SurfaceFlinger::doComposition() {
829    ATRACE_CALL();
830    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
831    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
832        const sp<DisplayDevice>& hw(mDisplays[dpy]);
833        if (hw->canDraw()) {
834            // transform the dirty region into this screen's coordinate space
835            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
836            if (!dirtyRegion.isEmpty()) {
837                // repaint the framebuffer (if needed)
838                doDisplayComposition(hw, dirtyRegion);
839            }
840            hw->dirtyRegion.clear();
841            hw->flip(hw->swapRegion);
842            hw->swapRegion.clear();
843        }
844        // inform the h/w that we're done compositing
845        hw->compositionComplete();
846    }
847    postFramebuffer();
848}
849
850void SurfaceFlinger::postFramebuffer()
851{
852    ATRACE_CALL();
853
854    const nsecs_t now = systemTime();
855    mDebugInSwapBuffers = now;
856
857    HWComposer& hwc(getHwComposer());
858    if (hwc.initCheck() == NO_ERROR) {
859        // FIXME: EGL spec says:
860        //   "surface must be bound to the calling thread's current context,
861        //    for the current rendering API."
862        DisplayDevice::makeCurrent(mEGLDisplay, getDefaultDisplayDevice(), mEGLContext);
863        hwc.commit();
864    }
865
866    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
867        sp<const DisplayDevice> hw(mDisplays[dpy]);
868        const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
869        const size_t count = currentLayers.size();
870        int32_t id = hw->getHwcDisplayId();
871        if (id >=0 && hwc.initCheck() == NO_ERROR) {
872            HWComposer::LayerListIterator cur = hwc.begin(id);
873            const HWComposer::LayerListIterator end = hwc.end(id);
874            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
875                currentLayers[i]->onLayerDisplayed(hw, &*cur);
876            }
877        } else {
878            for (size_t i = 0; i < count; i++) {
879                currentLayers[i]->onLayerDisplayed(hw, NULL);
880            }
881        }
882    }
883
884    mLastSwapBufferTime = systemTime() - now;
885    mDebugInSwapBuffers = 0;
886}
887
888void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
889{
890    ATRACE_CALL();
891
892    Mutex::Autolock _l(mStateLock);
893    const nsecs_t now = systemTime();
894    mDebugInTransaction = now;
895
896    // Here we're guaranteed that some transaction flags are set
897    // so we can call handleTransactionLocked() unconditionally.
898    // We call getTransactionFlags(), which will also clear the flags,
899    // with mStateLock held to guarantee that mCurrentState won't change
900    // until the transaction is committed.
901
902    transactionFlags = getTransactionFlags(eTransactionMask);
903    handleTransactionLocked(transactionFlags);
904
905    mLastTransactionTime = systemTime() - now;
906    mDebugInTransaction = 0;
907    invalidateHwcGeometry();
908    // here the transaction has been committed
909}
910
911void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
912{
913    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
914    const size_t count = currentLayers.size();
915
916    /*
917     * Traversal of the children
918     * (perform the transaction for each of them if needed)
919     */
920
921    if (transactionFlags & eTraversalNeeded) {
922        for (size_t i=0 ; i<count ; i++) {
923            const sp<LayerBase>& layer = currentLayers[i];
924            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
925            if (!trFlags) continue;
926
927            const uint32_t flags = layer->doTransaction(0);
928            if (flags & Layer::eVisibleRegion)
929                mVisibleRegionsDirty = true;
930        }
931    }
932
933    /*
934     * Perform display own transactions if needed
935     */
936
937    if (transactionFlags & eDisplayTransactionNeeded) {
938        // here we take advantage of Vector's copy-on-write semantics to
939        // improve performance by skipping the transaction entirely when
940        // know that the lists are identical
941        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
942        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
943        if (!curr.isIdenticalTo(draw)) {
944            mVisibleRegionsDirty = true;
945            const size_t cc = curr.size();
946                  size_t dc = draw.size();
947
948            // find the displays that were removed
949            // (ie: in drawing state but not in current state)
950            // also handle displays that changed
951            // (ie: displays that are in both lists)
952            for (size_t i=0 ; i<dc ; i++) {
953                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
954                if (j < 0) {
955                    // in drawing state but not in current state
956                    if (!draw[i].isMainDisplay()) {
957                        mDisplays.removeItem(draw.keyAt(i));
958                    } else {
959                        ALOGW("trying to remove the main display");
960                    }
961                } else {
962                    // this display is in both lists. see if something changed.
963                    const DisplayDeviceState& state(curr[j]);
964                    const wp<IBinder>& display(curr.keyAt(j));
965                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
966                        // changing the surface is like destroying and
967                        // recreating the DisplayDevice, so we just remove it
968                        // from the drawing state, so that it get re-added
969                        // below.
970                        mDisplays.removeItem(display);
971                        mDrawingState.displays.removeItemsAt(i);
972                        dc--; i--;
973                        // at this point we must loop to the next item
974                        continue;
975                    }
976
977                    const sp<DisplayDevice>& disp(getDisplayDevice(display));
978                    if (disp != NULL) {
979                        if (state.layerStack != draw[i].layerStack) {
980                            disp->setLayerStack(state.layerStack);
981                        }
982                        if ((state.orientation != draw[i].orientation)
983                                || (state.viewport != draw[i].viewport)
984                                || (state.frame != draw[i].frame))
985                        {
986                            disp->setProjection(state.orientation,
987                                    state.viewport, state.frame);
988                        }
989                    }
990                }
991            }
992
993            // find displays that were added
994            // (ie: in current state but not in drawing state)
995            for (size_t i=0 ; i<cc ; i++) {
996                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
997                    const DisplayDeviceState& state(curr[i]);
998                    if (state.surface != NULL) {
999                        sp<SurfaceTextureClient> stc(
1000                                new SurfaceTextureClient(state.surface));
1001                        const wp<IBinder>& display(curr.keyAt(i));
1002                        sp<DisplayDevice> disp = new DisplayDevice(this,
1003                                state.type, display, stc, 0, mEGLConfig);
1004                        disp->setLayerStack(state.layerStack);
1005                        disp->setProjection(state.orientation,
1006                                state.viewport, state.frame);
1007                        mDisplays.add(display, disp);
1008                    }
1009                }
1010            }
1011        }
1012    }
1013
1014    /*
1015     * Perform our own transaction if needed
1016     */
1017
1018    const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
1019    if (currentLayers.size() > previousLayers.size()) {
1020        // layers have been added
1021        mVisibleRegionsDirty = true;
1022    }
1023
1024    // some layers might have been removed, so
1025    // we need to update the regions they're exposing.
1026    if (mLayersRemoved) {
1027        mLayersRemoved = false;
1028        mVisibleRegionsDirty = true;
1029        const size_t count = previousLayers.size();
1030        for (size_t i=0 ; i<count ; i++) {
1031            const sp<LayerBase>& layer(previousLayers[i]);
1032            if (currentLayers.indexOf(layer) < 0) {
1033                // this layer is not visible anymore
1034                // TODO: we could traverse the tree from front to back and
1035                //       compute the actual visible region
1036                // TODO: we could cache the transformed region
1037                const Layer::State& s(layer->drawingState());
1038                Region visibleReg = s.transform.transform(
1039                        Region(Rect(s.active.w, s.active.h)));
1040                invalidateLayerStack(s.layerStack, visibleReg);
1041            }
1042        }
1043    }
1044
1045    commitTransaction();
1046}
1047
1048void SurfaceFlinger::commitTransaction()
1049{
1050    if (!mLayersPendingRemoval.isEmpty()) {
1051        // Notify removed layers now that they can't be drawn from
1052        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1053            mLayersPendingRemoval[i]->onRemoved();
1054        }
1055        mLayersPendingRemoval.clear();
1056    }
1057
1058    mDrawingState = mCurrentState;
1059    mTransationPending = false;
1060    mTransactionCV.broadcast();
1061}
1062
1063void SurfaceFlinger::computeVisibleRegions(
1064        const LayerVector& currentLayers, uint32_t layerStack,
1065        Region& outDirtyRegion, Region& outOpaqueRegion)
1066{
1067    ATRACE_CALL();
1068
1069    Region aboveOpaqueLayers;
1070    Region aboveCoveredLayers;
1071    Region dirty;
1072
1073    outDirtyRegion.clear();
1074
1075    size_t i = currentLayers.size();
1076    while (i--) {
1077        const sp<LayerBase>& layer = currentLayers[i];
1078
1079        // start with the whole surface at its current location
1080        const Layer::State& s(layer->drawingState());
1081
1082        // only consider the layers on the given later stack
1083        if (s.layerStack != layerStack)
1084            continue;
1085
1086        /*
1087         * opaqueRegion: area of a surface that is fully opaque.
1088         */
1089        Region opaqueRegion;
1090
1091        /*
1092         * visibleRegion: area of a surface that is visible on screen
1093         * and not fully transparent. This is essentially the layer's
1094         * footprint minus the opaque regions above it.
1095         * Areas covered by a translucent surface are considered visible.
1096         */
1097        Region visibleRegion;
1098
1099        /*
1100         * coveredRegion: area of a surface that is covered by all
1101         * visible regions above it (which includes the translucent areas).
1102         */
1103        Region coveredRegion;
1104
1105
1106        // handle hidden surfaces by setting the visible region to empty
1107        if (CC_LIKELY(!(s.flags & layer_state_t::eLayerHidden) && s.alpha)) {
1108            const bool translucent = !layer->isOpaque();
1109            Rect bounds(layer->computeBounds());
1110            visibleRegion.set(bounds);
1111            if (!visibleRegion.isEmpty()) {
1112                // Remove the transparent area from the visible region
1113                if (translucent) {
1114                    Region transparentRegionScreen;
1115                    const Transform tr(s.transform);
1116                    if (tr.transformed()) {
1117                        if (tr.preserveRects()) {
1118                            // transform the transparent region
1119                            transparentRegionScreen = tr.transform(s.transparentRegion);
1120                        } else {
1121                            // transformation too complex, can't do the
1122                            // transparent region optimization.
1123                            transparentRegionScreen.clear();
1124                        }
1125                    } else {
1126                        transparentRegionScreen = s.transparentRegion;
1127                    }
1128                    visibleRegion.subtractSelf(transparentRegionScreen);
1129                }
1130
1131                // compute the opaque region
1132                const int32_t layerOrientation = s.transform.getOrientation();
1133                if (s.alpha==255 && !translucent &&
1134                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1135                    // the opaque region is the layer's footprint
1136                    opaqueRegion = visibleRegion;
1137                }
1138            }
1139        }
1140
1141        // Clip the covered region to the visible region
1142        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1143
1144        // Update aboveCoveredLayers for next (lower) layer
1145        aboveCoveredLayers.orSelf(visibleRegion);
1146
1147        // subtract the opaque region covered by the layers above us
1148        visibleRegion.subtractSelf(aboveOpaqueLayers);
1149
1150        // compute this layer's dirty region
1151        if (layer->contentDirty) {
1152            // we need to invalidate the whole region
1153            dirty = visibleRegion;
1154            // as well, as the old visible region
1155            dirty.orSelf(layer->visibleRegion);
1156            layer->contentDirty = false;
1157        } else {
1158            /* compute the exposed region:
1159             *   the exposed region consists of two components:
1160             *   1) what's VISIBLE now and was COVERED before
1161             *   2) what's EXPOSED now less what was EXPOSED before
1162             *
1163             * note that (1) is conservative, we start with the whole
1164             * visible region but only keep what used to be covered by
1165             * something -- which mean it may have been exposed.
1166             *
1167             * (2) handles areas that were not covered by anything but got
1168             * exposed because of a resize.
1169             */
1170            const Region newExposed = visibleRegion - coveredRegion;
1171            const Region oldVisibleRegion = layer->visibleRegion;
1172            const Region oldCoveredRegion = layer->coveredRegion;
1173            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1174            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1175        }
1176        dirty.subtractSelf(aboveOpaqueLayers);
1177
1178        // accumulate to the screen dirty region
1179        outDirtyRegion.orSelf(dirty);
1180
1181        // Update aboveOpaqueLayers for next (lower) layer
1182        aboveOpaqueLayers.orSelf(opaqueRegion);
1183
1184        // Store the visible region is screen space
1185        layer->setVisibleRegion(visibleRegion);
1186        layer->setCoveredRegion(coveredRegion);
1187    }
1188
1189    outOpaqueRegion = aboveOpaqueLayers;
1190}
1191
1192void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1193        const Region& dirty) {
1194    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1195        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1196        if (hw->getLayerStack() == layerStack) {
1197            hw->dirtyRegion.orSelf(dirty);
1198        }
1199    }
1200}
1201
1202void SurfaceFlinger::handlePageFlip()
1203{
1204    Region dirtyRegion;
1205
1206    bool visibleRegions = false;
1207    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1208    const size_t count = currentLayers.size();
1209    for (size_t i=0 ; i<count ; i++) {
1210        const sp<LayerBase>& layer(currentLayers[i]);
1211        const Region dirty(layer->latchBuffer(visibleRegions));
1212        const Layer::State& s(layer->drawingState());
1213        invalidateLayerStack(s.layerStack, dirty);
1214    }
1215
1216    mVisibleRegionsDirty |= visibleRegions;
1217}
1218
1219void SurfaceFlinger::invalidateHwcGeometry()
1220{
1221    mHwWorkListDirty = true;
1222}
1223
1224
1225void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1226        const Region& inDirtyRegion)
1227{
1228    Region dirtyRegion(inDirtyRegion);
1229
1230    // compute the invalid region
1231    hw->swapRegion.orSelf(dirtyRegion);
1232
1233    uint32_t flags = hw->getFlags();
1234    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1235        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1236        // takes a rectangle, we must make sure to update that whole
1237        // rectangle in that case
1238        dirtyRegion.set(hw->swapRegion.bounds());
1239    } else {
1240        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1241            // We need to redraw the rectangle that will be updated
1242            // (pushed to the framebuffer).
1243            // This is needed because PARTIAL_UPDATES only takes one
1244            // rectangle instead of a region (see DisplayDevice::flip())
1245            dirtyRegion.set(hw->swapRegion.bounds());
1246        } else {
1247            // we need to redraw everything (the whole screen)
1248            dirtyRegion.set(hw->bounds());
1249            hw->swapRegion = dirtyRegion;
1250        }
1251    }
1252
1253    doComposeSurfaces(hw, dirtyRegion);
1254
1255    // FIXME: we need to call eglSwapBuffers() on displays that have
1256    // GL composition and only on those.
1257    // however, currently hwc.commit() already does that for the main
1258    // display (if there is a hwc) and never for the other ones
1259    if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL ||
1260            getHwComposer().initCheck() != NO_ERROR) {
1261        // FIXME: EGL spec says:
1262        //   "surface must be bound to the calling thread's current context,
1263        //    for the current rendering API."
1264        eglSwapBuffers(mEGLDisplay, hw->getEGLSurface());
1265    }
1266
1267    // update the swap region and clear the dirty region
1268    hw->swapRegion.orSelf(dirtyRegion);
1269}
1270
1271void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1272{
1273    const int32_t id = hw->getHwcDisplayId();
1274    HWComposer& hwc(getHwComposer());
1275    HWComposer::LayerListIterator cur = hwc.begin(id);
1276    const HWComposer::LayerListIterator end = hwc.end(id);
1277
1278    const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1279    if (hasGlesComposition) {
1280        DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
1281
1282        // set the frame buffer
1283        glMatrixMode(GL_MODELVIEW);
1284        glLoadIdentity();
1285
1286        // Never touch the framebuffer if we don't have any framebuffer layers
1287        const bool hasHwcComposition = hwc.hasHwcComposition(id);
1288        if (hasHwcComposition) {
1289            // when using overlays, we assume a fully transparent framebuffer
1290            // NOTE: we could reduce how much we need to clear, for instance
1291            // remove where there are opaque FB layers. however, on some
1292            // GPUs doing a "clean slate" glClear might be more efficient.
1293            // We'll revisit later if needed.
1294            glClearColor(0, 0, 0, 0);
1295            glClear(GL_COLOR_BUFFER_BIT);
1296        } else {
1297            const Region region(hw->undefinedRegion.intersect(dirty));
1298            // screen is already cleared here
1299            if (!region.isEmpty()) {
1300                // can happen with SurfaceView
1301                drawWormhole(hw, region);
1302            }
1303        }
1304    }
1305
1306    /*
1307     * and then, render the layers targeted at the framebuffer
1308     */
1309
1310    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1311    const size_t count = layers.size();
1312    const Transform& tr = hw->getTransform();
1313    if (cur != end) {
1314        // we're using h/w composer
1315        for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1316            const sp<LayerBase>& layer(layers[i]);
1317            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1318            if (!clip.isEmpty()) {
1319                switch (cur->getCompositionType()) {
1320                    case HWC_OVERLAY: {
1321                        if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1322                                && i
1323                                && layer->isOpaque()
1324                                && hasGlesComposition) {
1325                            // never clear the very first layer since we're
1326                            // guaranteed the FB is already cleared
1327                            layer->clearWithOpenGL(hw, clip);
1328                        }
1329                        break;
1330                    }
1331                    case HWC_FRAMEBUFFER: {
1332                        layer->draw(hw, clip);
1333                        break;
1334                    }
1335                }
1336            }
1337            layer->setAcquireFence(hw, *cur);
1338        }
1339    } else {
1340        // we're not using h/w composer
1341        for (size_t i=0 ; i<count ; ++i) {
1342            const sp<LayerBase>& layer(layers[i]);
1343            const Region clip(dirty.intersect(
1344                    tr.transform(layer->visibleRegion)));
1345            if (!clip.isEmpty()) {
1346                layer->draw(hw, clip);
1347            }
1348        }
1349    }
1350}
1351
1352void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw,
1353        const Region& region) const
1354{
1355    glDisable(GL_TEXTURE_EXTERNAL_OES);
1356    glDisable(GL_TEXTURE_2D);
1357    glDisable(GL_BLEND);
1358    glColor4f(0,0,0,0);
1359
1360    const int32_t height = hw->getHeight();
1361    Region::const_iterator it = region.begin();
1362    Region::const_iterator const end = region.end();
1363    while (it != end) {
1364        const Rect& r = *it++;
1365        GLfloat vertices[][2] = {
1366                { r.left,  height - r.top },
1367                { r.left,  height - r.bottom },
1368                { r.right, height - r.bottom },
1369                { r.right, height - r.top }
1370        };
1371        glVertexPointer(2, GL_FLOAT, 0, vertices);
1372        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1373    }
1374}
1375
1376ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1377        const sp<LayerBaseClient>& lbc)
1378{
1379    // attach this layer to the client
1380    size_t name = client->attachLayer(lbc);
1381
1382    // add this layer to the current state list
1383    Mutex::Autolock _l(mStateLock);
1384    mCurrentState.layersSortedByZ.add(lbc);
1385
1386    return ssize_t(name);
1387}
1388
1389status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1390{
1391    Mutex::Autolock _l(mStateLock);
1392    status_t err = purgatorizeLayer_l(layer);
1393    if (err == NO_ERROR)
1394        setTransactionFlags(eTransactionNeeded);
1395    return err;
1396}
1397
1398status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1399{
1400    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1401    if (index >= 0) {
1402        mLayersRemoved = true;
1403        return NO_ERROR;
1404    }
1405    return status_t(index);
1406}
1407
1408status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1409{
1410    // First add the layer to the purgatory list, which makes sure it won't
1411    // go away, then remove it from the main list (through a transaction).
1412    ssize_t err = removeLayer_l(layerBase);
1413    if (err >= 0) {
1414        mLayerPurgatory.add(layerBase);
1415    }
1416
1417    mLayersPendingRemoval.push(layerBase);
1418
1419    // it's possible that we don't find a layer, because it might
1420    // have been destroyed already -- this is not technically an error
1421    // from the user because there is a race between Client::destroySurface(),
1422    // ~Client() and ~ISurface().
1423    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1424}
1425
1426uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1427{
1428    return android_atomic_release_load(&mTransactionFlags);
1429}
1430
1431uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1432{
1433    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1434}
1435
1436uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1437{
1438    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1439    if ((old & flags)==0) { // wake the server up
1440        signalTransaction();
1441    }
1442    return old;
1443}
1444
1445void SurfaceFlinger::setTransactionState(
1446        const Vector<ComposerState>& state,
1447        const Vector<DisplayState>& displays,
1448        uint32_t flags)
1449{
1450    Mutex::Autolock _l(mStateLock);
1451    uint32_t transactionFlags = 0;
1452
1453    size_t count = displays.size();
1454    for (size_t i=0 ; i<count ; i++) {
1455        const DisplayState& s(displays[i]);
1456        transactionFlags |= setDisplayStateLocked(s);
1457    }
1458
1459    count = state.size();
1460    for (size_t i=0 ; i<count ; i++) {
1461        const ComposerState& s(state[i]);
1462        sp<Client> client( static_cast<Client *>(s.client.get()) );
1463        transactionFlags |= setClientStateLocked(client, s.state);
1464    }
1465
1466    if (transactionFlags) {
1467        // this triggers the transaction
1468        setTransactionFlags(transactionFlags);
1469
1470        // if this is a synchronous transaction, wait for it to take effect
1471        // before returning.
1472        if (flags & eSynchronous) {
1473            mTransationPending = true;
1474        }
1475        while (mTransationPending) {
1476            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1477            if (CC_UNLIKELY(err != NO_ERROR)) {
1478                // just in case something goes wrong in SF, return to the
1479                // called after a few seconds.
1480                ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1481                mTransationPending = false;
1482                break;
1483            }
1484        }
1485    }
1486}
1487
1488uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1489{
1490    uint32_t flags = 0;
1491    DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token));
1492    if (disp.isValid()) {
1493        const uint32_t what = s.what;
1494        if (what & DisplayState::eSurfaceChanged) {
1495            if (disp.surface->asBinder() != s.surface->asBinder()) {
1496                disp.surface = s.surface;
1497                flags |= eDisplayTransactionNeeded;
1498            }
1499        }
1500        if (what & DisplayState::eLayerStackChanged) {
1501            if (disp.layerStack != s.layerStack) {
1502                disp.layerStack = s.layerStack;
1503                flags |= eDisplayTransactionNeeded;
1504            }
1505        }
1506        if (what & DisplayState::eDisplayProjectionChanged) {
1507            if (disp.orientation != s.orientation) {
1508                disp.orientation = s.orientation;
1509                flags |= eDisplayTransactionNeeded;
1510            }
1511            if (disp.frame != s.frame) {
1512                disp.frame = s.frame;
1513                flags |= eDisplayTransactionNeeded;
1514            }
1515            if (disp.viewport != s.viewport) {
1516                disp.viewport = s.viewport;
1517                flags |= eDisplayTransactionNeeded;
1518            }
1519        }
1520    }
1521    return flags;
1522}
1523
1524uint32_t SurfaceFlinger::setClientStateLocked(
1525        const sp<Client>& client,
1526        const layer_state_t& s)
1527{
1528    uint32_t flags = 0;
1529    sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1530    if (layer != 0) {
1531        const uint32_t what = s.what;
1532        if (what & layer_state_t::ePositionChanged) {
1533            if (layer->setPosition(s.x, s.y))
1534                flags |= eTraversalNeeded;
1535        }
1536        if (what & layer_state_t::eLayerChanged) {
1537            // NOTE: index needs to be calculated before we update the state
1538            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1539            if (layer->setLayer(s.z)) {
1540                mCurrentState.layersSortedByZ.removeAt(idx);
1541                mCurrentState.layersSortedByZ.add(layer);
1542                // we need traversal (state changed)
1543                // AND transaction (list changed)
1544                flags |= eTransactionNeeded|eTraversalNeeded;
1545            }
1546        }
1547        if (what & layer_state_t::eSizeChanged) {
1548            if (layer->setSize(s.w, s.h)) {
1549                flags |= eTraversalNeeded;
1550            }
1551        }
1552        if (what & layer_state_t::eAlphaChanged) {
1553            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1554                flags |= eTraversalNeeded;
1555        }
1556        if (what & layer_state_t::eMatrixChanged) {
1557            if (layer->setMatrix(s.matrix))
1558                flags |= eTraversalNeeded;
1559        }
1560        if (what & layer_state_t::eTransparentRegionChanged) {
1561            if (layer->setTransparentRegionHint(s.transparentRegion))
1562                flags |= eTraversalNeeded;
1563        }
1564        if (what & layer_state_t::eVisibilityChanged) {
1565            if (layer->setFlags(s.flags, s.mask))
1566                flags |= eTraversalNeeded;
1567        }
1568        if (what & layer_state_t::eCropChanged) {
1569            if (layer->setCrop(s.crop))
1570                flags |= eTraversalNeeded;
1571        }
1572        if (what & layer_state_t::eLayerStackChanged) {
1573            // NOTE: index needs to be calculated before we update the state
1574            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1575            if (layer->setLayerStack(s.layerStack)) {
1576                mCurrentState.layersSortedByZ.removeAt(idx);
1577                mCurrentState.layersSortedByZ.add(layer);
1578                // we need traversal (state changed)
1579                // AND transaction (list changed)
1580                flags |= eTransactionNeeded|eTraversalNeeded;
1581            }
1582        }
1583    }
1584    return flags;
1585}
1586
1587sp<ISurface> SurfaceFlinger::createLayer(
1588        ISurfaceComposerClient::surface_data_t* params,
1589        const String8& name,
1590        const sp<Client>& client,
1591       uint32_t w, uint32_t h, PixelFormat format,
1592        uint32_t flags)
1593{
1594    sp<LayerBaseClient> layer;
1595    sp<ISurface> surfaceHandle;
1596
1597    if (int32_t(w|h) < 0) {
1598        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1599                int(w), int(h));
1600        return surfaceHandle;
1601    }
1602
1603    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1604    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1605        case ISurfaceComposerClient::eFXSurfaceNormal:
1606            layer = createNormalLayer(client, w, h, flags, format);
1607            break;
1608        case ISurfaceComposerClient::eFXSurfaceBlur:
1609        case ISurfaceComposerClient::eFXSurfaceDim:
1610            layer = createDimLayer(client, w, h, flags);
1611            break;
1612        case ISurfaceComposerClient::eFXSurfaceScreenshot:
1613            layer = createScreenshotLayer(client, w, h, flags);
1614            break;
1615    }
1616
1617    if (layer != 0) {
1618        layer->initStates(w, h, flags);
1619        layer->setName(name);
1620        ssize_t token = addClientLayer(client, layer);
1621        surfaceHandle = layer->getSurface();
1622        if (surfaceHandle != 0) {
1623            params->token = token;
1624            params->identity = layer->getIdentity();
1625        }
1626        setTransactionFlags(eTransactionNeeded);
1627    }
1628
1629    return surfaceHandle;
1630}
1631
1632sp<Layer> SurfaceFlinger::createNormalLayer(
1633        const sp<Client>& client,
1634        uint32_t w, uint32_t h, uint32_t flags,
1635        PixelFormat& format)
1636{
1637    // initialize the surfaces
1638    switch (format) {
1639    case PIXEL_FORMAT_TRANSPARENT:
1640    case PIXEL_FORMAT_TRANSLUCENT:
1641        format = PIXEL_FORMAT_RGBA_8888;
1642        break;
1643    case PIXEL_FORMAT_OPAQUE:
1644#ifdef NO_RGBX_8888
1645        format = PIXEL_FORMAT_RGB_565;
1646#else
1647        format = PIXEL_FORMAT_RGBX_8888;
1648#endif
1649        break;
1650    }
1651
1652#ifdef NO_RGBX_8888
1653    if (format == PIXEL_FORMAT_RGBX_8888)
1654        format = PIXEL_FORMAT_RGBA_8888;
1655#endif
1656
1657    sp<Layer> layer = new Layer(this, client);
1658    status_t err = layer->setBuffers(w, h, format, flags);
1659    if (CC_LIKELY(err != NO_ERROR)) {
1660        ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1661        layer.clear();
1662    }
1663    return layer;
1664}
1665
1666sp<LayerDim> SurfaceFlinger::createDimLayer(
1667        const sp<Client>& client,
1668        uint32_t w, uint32_t h, uint32_t flags)
1669{
1670    sp<LayerDim> layer = new LayerDim(this, client);
1671    return layer;
1672}
1673
1674sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1675        const sp<Client>& client,
1676        uint32_t w, uint32_t h, uint32_t flags)
1677{
1678    sp<LayerScreenshot> layer = new LayerScreenshot(this, client);
1679    return layer;
1680}
1681
1682status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1683{
1684    /*
1685     * called by the window manager, when a surface should be marked for
1686     * destruction.
1687     *
1688     * The surface is removed from the current and drawing lists, but placed
1689     * in the purgatory queue, so it's not destroyed right-away (we need
1690     * to wait for all client's references to go away first).
1691     */
1692
1693    status_t err = NAME_NOT_FOUND;
1694    Mutex::Autolock _l(mStateLock);
1695    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1696
1697    if (layer != 0) {
1698        err = purgatorizeLayer_l(layer);
1699        if (err == NO_ERROR) {
1700            setTransactionFlags(eTransactionNeeded);
1701        }
1702    }
1703    return err;
1704}
1705
1706status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
1707{
1708    // called by ~ISurface() when all references are gone
1709    status_t err = NO_ERROR;
1710    sp<LayerBaseClient> l(layer.promote());
1711    if (l != NULL) {
1712        Mutex::Autolock _l(mStateLock);
1713        err = removeLayer_l(l);
1714        if (err == NAME_NOT_FOUND) {
1715            // The surface wasn't in the current list, which means it was
1716            // removed already, which means it is in the purgatory,
1717            // and need to be removed from there.
1718            ssize_t idx = mLayerPurgatory.remove(l);
1719            ALOGE_IF(idx < 0,
1720                    "layer=%p is not in the purgatory list", l.get());
1721        }
1722        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1723                "error removing layer=%p (%s)", l.get(), strerror(-err));
1724    }
1725    return err;
1726}
1727
1728// ---------------------------------------------------------------------------
1729
1730void SurfaceFlinger::onInitializeDisplays() {
1731    // reset screen orientation
1732    Vector<ComposerState> state;
1733    Vector<DisplayState> displays;
1734    DisplayState d;
1735    d.what = DisplayState::eDisplayProjectionChanged;
1736    d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY];
1737    d.orientation = DisplayState::eOrientationDefault;
1738    d.frame.makeInvalid();
1739    d.viewport.makeInvalid();
1740    displays.add(d);
1741    setTransactionState(state, displays, 0);
1742
1743    // XXX: this should init default device to "unblank" and all other devices to "blank"
1744    onScreenAcquired();
1745}
1746
1747void SurfaceFlinger::initializeDisplays() {
1748    class MessageScreenInitialized : public MessageBase {
1749        SurfaceFlinger* flinger;
1750    public:
1751        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
1752        virtual bool handler() {
1753            flinger->onInitializeDisplays();
1754            return true;
1755        }
1756    };
1757    sp<MessageBase> msg = new MessageScreenInitialized(this);
1758    postMessageAsync(msg);  // we may be called from main thread, use async message
1759}
1760
1761
1762void SurfaceFlinger::onScreenAcquired() {
1763    ALOGD("Screen about to return, flinger = %p", this);
1764    sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1765    getHwComposer().acquire();
1766    hw->acquireScreen();
1767    mEventThread->onScreenAcquired();
1768    mVisibleRegionsDirty = true;
1769    repaintEverything();
1770}
1771
1772void SurfaceFlinger::onScreenReleased() {
1773    ALOGD("About to give-up screen, flinger = %p", this);
1774    sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1775    if (hw->isScreenAcquired()) {
1776        mEventThread->onScreenReleased();
1777        hw->releaseScreen();
1778        getHwComposer().release();
1779        // from this point on, SF will stop drawing
1780    }
1781}
1782
1783void SurfaceFlinger::unblank() {
1784    class MessageScreenAcquired : public MessageBase {
1785        SurfaceFlinger* flinger;
1786    public:
1787        MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { }
1788        virtual bool handler() {
1789            flinger->onScreenAcquired();
1790            return true;
1791        }
1792    };
1793    sp<MessageBase> msg = new MessageScreenAcquired(this);
1794    postMessageSync(msg);
1795}
1796
1797void SurfaceFlinger::blank() {
1798    class MessageScreenReleased : public MessageBase {
1799        SurfaceFlinger* flinger;
1800    public:
1801        MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { }
1802        virtual bool handler() {
1803            flinger->onScreenReleased();
1804            return true;
1805        }
1806    };
1807    sp<MessageBase> msg = new MessageScreenReleased(this);
1808    postMessageSync(msg);
1809}
1810
1811// ---------------------------------------------------------------------------
1812
1813status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1814{
1815    const size_t SIZE = 4096;
1816    char buffer[SIZE];
1817    String8 result;
1818
1819    if (!PermissionCache::checkCallingPermission(sDump)) {
1820        snprintf(buffer, SIZE, "Permission Denial: "
1821                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1822                IPCThreadState::self()->getCallingPid(),
1823                IPCThreadState::self()->getCallingUid());
1824        result.append(buffer);
1825    } else {
1826        // Try to get the main lock, but don't insist if we can't
1827        // (this would indicate SF is stuck, but we want to be able to
1828        // print something in dumpsys).
1829        int retry = 3;
1830        while (mStateLock.tryLock()<0 && --retry>=0) {
1831            usleep(1000000);
1832        }
1833        const bool locked(retry >= 0);
1834        if (!locked) {
1835            snprintf(buffer, SIZE,
1836                    "SurfaceFlinger appears to be unresponsive, "
1837                    "dumping anyways (no locks held)\n");
1838            result.append(buffer);
1839        }
1840
1841        bool dumpAll = true;
1842        size_t index = 0;
1843        size_t numArgs = args.size();
1844        if (numArgs) {
1845            if ((index < numArgs) &&
1846                    (args[index] == String16("--list"))) {
1847                index++;
1848                listLayersLocked(args, index, result, buffer, SIZE);
1849                dumpAll = false;
1850            }
1851
1852            if ((index < numArgs) &&
1853                    (args[index] == String16("--latency"))) {
1854                index++;
1855                dumpStatsLocked(args, index, result, buffer, SIZE);
1856                dumpAll = false;
1857            }
1858
1859            if ((index < numArgs) &&
1860                    (args[index] == String16("--latency-clear"))) {
1861                index++;
1862                clearStatsLocked(args, index, result, buffer, SIZE);
1863                dumpAll = false;
1864            }
1865        }
1866
1867        if (dumpAll) {
1868            dumpAllLocked(result, buffer, SIZE);
1869        }
1870
1871        if (locked) {
1872            mStateLock.unlock();
1873        }
1874    }
1875    write(fd, result.string(), result.size());
1876    return NO_ERROR;
1877}
1878
1879void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
1880        String8& result, char* buffer, size_t SIZE) const
1881{
1882    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1883    const size_t count = currentLayers.size();
1884    for (size_t i=0 ; i<count ; i++) {
1885        const sp<LayerBase>& layer(currentLayers[i]);
1886        snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1887        result.append(buffer);
1888    }
1889}
1890
1891void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
1892        String8& result, char* buffer, size_t SIZE) const
1893{
1894    String8 name;
1895    if (index < args.size()) {
1896        name = String8(args[index]);
1897        index++;
1898    }
1899
1900    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1901    const size_t count = currentLayers.size();
1902    for (size_t i=0 ; i<count ; i++) {
1903        const sp<LayerBase>& layer(currentLayers[i]);
1904        if (name.isEmpty()) {
1905            snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1906            result.append(buffer);
1907        }
1908        if (name.isEmpty() || (name == layer->getName())) {
1909            layer->dumpStats(result, buffer, SIZE);
1910        }
1911    }
1912}
1913
1914void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
1915        String8& result, char* buffer, size_t SIZE) const
1916{
1917    String8 name;
1918    if (index < args.size()) {
1919        name = String8(args[index]);
1920        index++;
1921    }
1922
1923    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1924    const size_t count = currentLayers.size();
1925    for (size_t i=0 ; i<count ; i++) {
1926        const sp<LayerBase>& layer(currentLayers[i]);
1927        if (name.isEmpty() || (name == layer->getName())) {
1928            layer->clearStats();
1929        }
1930    }
1931}
1932
1933void SurfaceFlinger::dumpAllLocked(
1934        String8& result, char* buffer, size_t SIZE) const
1935{
1936    // figure out if we're stuck somewhere
1937    const nsecs_t now = systemTime();
1938    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1939    const nsecs_t inTransaction(mDebugInTransaction);
1940    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1941    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1942
1943    /*
1944     * Dump the visible layer list
1945     */
1946    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1947    const size_t count = currentLayers.size();
1948    snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1949    result.append(buffer);
1950    for (size_t i=0 ; i<count ; i++) {
1951        const sp<LayerBase>& layer(currentLayers[i]);
1952        layer->dump(result, buffer, SIZE);
1953    }
1954
1955    /*
1956     * Dump the layers in the purgatory
1957     */
1958
1959    const size_t purgatorySize = mLayerPurgatory.size();
1960    snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1961    result.append(buffer);
1962    for (size_t i=0 ; i<purgatorySize ; i++) {
1963        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1964        layer->shortDump(result, buffer, SIZE);
1965    }
1966
1967    /*
1968     * Dump Display state
1969     */
1970
1971    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1972        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
1973        snprintf(buffer, SIZE,
1974                "+ DisplayDevice[%u]\n"
1975                "   type=%x, layerStack=%u, (%4dx%4d), orient=%2d (type=%08x), "
1976                "flips=%u, secure=%d, numLayers=%u, v:[%d,%d,%d,%d], f:[%d,%d,%d,%d]\n",
1977                dpy,
1978                hw->getDisplayType(), hw->getLayerStack(),
1979                hw->getWidth(), hw->getHeight(),
1980                hw->getOrientation(), hw->getTransform().getType(),
1981                hw->getPageFlipCount(),
1982                hw->getSecureLayerVisible(),
1983                hw->getVisibleLayersSortedByZ().size(),
1984                hw->getViewport().left, hw->getViewport().top, hw->getViewport().right, hw->getViewport().bottom,
1985                hw->getFrame().left, hw->getFrame().top, hw->getFrame().right, hw->getFrame().bottom);
1986
1987        result.append(buffer);
1988    }
1989
1990    /*
1991     * Dump SurfaceFlinger global state
1992     */
1993
1994    snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
1995    result.append(buffer);
1996
1997    HWComposer& hwc(getHwComposer());
1998    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1999    const GLExtensions& extensions(GLExtensions::getInstance());
2000    snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
2001            extensions.getVendor(),
2002            extensions.getRenderer(),
2003            extensions.getVersion());
2004    result.append(buffer);
2005
2006    snprintf(buffer, SIZE, "EGL : %s\n",
2007            eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
2008    result.append(buffer);
2009
2010    snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
2011    result.append(buffer);
2012
2013    hw->undefinedRegion.dump(result, "undefinedRegion");
2014    snprintf(buffer, SIZE,
2015            "  orientation=%d, canDraw=%d\n",
2016            hw->getOrientation(), hw->canDraw());
2017    result.append(buffer);
2018    snprintf(buffer, SIZE,
2019            "  last eglSwapBuffers() time: %f us\n"
2020            "  last transaction time     : %f us\n"
2021            "  transaction-flags         : %08x\n"
2022            "  refresh-rate              : %f fps\n"
2023            "  x-dpi                     : %f\n"
2024            "  y-dpi                     : %f\n",
2025            mLastSwapBufferTime/1000.0,
2026            mLastTransactionTime/1000.0,
2027            mTransactionFlags,
2028            1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2029            hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2030            hwc.getDpiY(HWC_DISPLAY_PRIMARY));
2031    result.append(buffer);
2032
2033    snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
2034            inSwapBuffersDuration/1000.0);
2035    result.append(buffer);
2036
2037    snprintf(buffer, SIZE, "  transaction time: %f us\n",
2038            inTransactionDuration/1000.0);
2039    result.append(buffer);
2040
2041    /*
2042     * VSYNC state
2043     */
2044    mEventThread->dump(result, buffer, SIZE);
2045
2046    /*
2047     * Dump HWComposer state
2048     */
2049    snprintf(buffer, SIZE, "h/w composer state:\n");
2050    result.append(buffer);
2051    snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
2052            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2053                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2054    result.append(buffer);
2055    hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ());
2056
2057    /*
2058     * Dump gralloc state
2059     */
2060    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2061    alloc.dump(result);
2062    hw->dump(result);
2063}
2064
2065bool SurfaceFlinger::startDdmConnection()
2066{
2067    void* libddmconnection_dso =
2068            dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2069    if (!libddmconnection_dso) {
2070        return false;
2071    }
2072    void (*DdmConnection_start)(const char* name);
2073    DdmConnection_start =
2074            (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2075    if (!DdmConnection_start) {
2076        dlclose(libddmconnection_dso);
2077        return false;
2078    }
2079    (*DdmConnection_start)(getServiceName());
2080    return true;
2081}
2082
2083status_t SurfaceFlinger::onTransact(
2084    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2085{
2086    switch (code) {
2087        case CREATE_CONNECTION:
2088        case SET_TRANSACTION_STATE:
2089        case BOOT_FINISHED:
2090        case BLANK:
2091        case UNBLANK:
2092        {
2093            // codes that require permission check
2094            IPCThreadState* ipc = IPCThreadState::self();
2095            const int pid = ipc->getCallingPid();
2096            const int uid = ipc->getCallingUid();
2097            if ((uid != AID_GRAPHICS) &&
2098                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2099                ALOGE("Permission Denial: "
2100                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2101                return PERMISSION_DENIED;
2102            }
2103            break;
2104        }
2105        case CAPTURE_SCREEN:
2106        {
2107            // codes that require permission check
2108            IPCThreadState* ipc = IPCThreadState::self();
2109            const int pid = ipc->getCallingPid();
2110            const int uid = ipc->getCallingUid();
2111            if ((uid != AID_GRAPHICS) &&
2112                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2113                ALOGE("Permission Denial: "
2114                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2115                return PERMISSION_DENIED;
2116            }
2117            break;
2118        }
2119    }
2120
2121    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2122    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2123        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2124        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2125            IPCThreadState* ipc = IPCThreadState::self();
2126            const int pid = ipc->getCallingPid();
2127            const int uid = ipc->getCallingUid();
2128            ALOGE("Permission Denial: "
2129                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2130            return PERMISSION_DENIED;
2131        }
2132        int n;
2133        switch (code) {
2134            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2135            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2136                return NO_ERROR;
2137            case 1002:  // SHOW_UPDATES
2138                n = data.readInt32();
2139                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2140                invalidateHwcGeometry();
2141                repaintEverything();
2142                return NO_ERROR;
2143            case 1004:{ // repaint everything
2144                repaintEverything();
2145                return NO_ERROR;
2146            }
2147            case 1005:{ // force transaction
2148                setTransactionFlags(
2149                        eTransactionNeeded|
2150                        eDisplayTransactionNeeded|
2151                        eTraversalNeeded);
2152                return NO_ERROR;
2153            }
2154            case 1006:{ // send empty update
2155                signalRefresh();
2156                return NO_ERROR;
2157            }
2158            case 1008:  // toggle use of hw composer
2159                n = data.readInt32();
2160                mDebugDisableHWC = n ? 1 : 0;
2161                invalidateHwcGeometry();
2162                repaintEverything();
2163                return NO_ERROR;
2164            case 1009:  // toggle use of transform hint
2165                n = data.readInt32();
2166                mDebugDisableTransformHint = n ? 1 : 0;
2167                invalidateHwcGeometry();
2168                repaintEverything();
2169                return NO_ERROR;
2170            case 1010:  // interrogate.
2171                reply->writeInt32(0);
2172                reply->writeInt32(0);
2173                reply->writeInt32(mDebugRegion);
2174                reply->writeInt32(0);
2175                reply->writeInt32(mDebugDisableHWC);
2176                return NO_ERROR;
2177            case 1013: {
2178                Mutex::Autolock _l(mStateLock);
2179                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2180                reply->writeInt32(hw->getPageFlipCount());
2181            }
2182            return NO_ERROR;
2183        }
2184    }
2185    return err;
2186}
2187
2188void SurfaceFlinger::repaintEverything() {
2189    android_atomic_or(1, &mRepaintEverything);
2190    signalTransaction();
2191}
2192
2193// ---------------------------------------------------------------------------
2194
2195status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack,
2196        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2197{
2198    Mutex::Autolock _l(mStateLock);
2199    return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut);
2200}
2201
2202status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack,
2203        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2204{
2205    ATRACE_CALL();
2206
2207    if (!GLExtensions::getInstance().haveFramebufferObject())
2208        return INVALID_OPERATION;
2209
2210    // get screen geometry
2211    // FIXME: figure out what it means to have a screenshot texture w/ multi-display
2212    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2213    const uint32_t hw_w = hw->getWidth();
2214    const uint32_t hw_h = hw->getHeight();
2215    GLfloat u = 1;
2216    GLfloat v = 1;
2217
2218    // make sure to clear all GL error flags
2219    while ( glGetError() != GL_NO_ERROR ) ;
2220
2221    // create a FBO
2222    GLuint name, tname;
2223    glGenTextures(1, &tname);
2224    glBindTexture(GL_TEXTURE_2D, tname);
2225    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2226    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2227    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2228            hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2229    if (glGetError() != GL_NO_ERROR) {
2230        while ( glGetError() != GL_NO_ERROR ) ;
2231        GLint tw = (2 << (31 - clz(hw_w)));
2232        GLint th = (2 << (31 - clz(hw_h)));
2233        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2234                tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2235        u = GLfloat(hw_w) / tw;
2236        v = GLfloat(hw_h) / th;
2237    }
2238    glGenFramebuffersOES(1, &name);
2239    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2240    glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2241            GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2242
2243    // redraw the screen entirely...
2244    glDisable(GL_TEXTURE_EXTERNAL_OES);
2245    glDisable(GL_TEXTURE_2D);
2246    glClearColor(0,0,0,1);
2247    glClear(GL_COLOR_BUFFER_BIT);
2248    glMatrixMode(GL_MODELVIEW);
2249    glLoadIdentity();
2250    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2251    const size_t count = layers.size();
2252    for (size_t i=0 ; i<count ; ++i) {
2253        const sp<LayerBase>& layer(layers[i]);
2254        layer->draw(hw);
2255    }
2256
2257    hw->compositionComplete();
2258
2259    // back to main framebuffer
2260    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2261    glDeleteFramebuffersOES(1, &name);
2262
2263    *textureName = tname;
2264    *uOut = u;
2265    *vOut = v;
2266    return NO_ERROR;
2267}
2268
2269// ---------------------------------------------------------------------------
2270
2271status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display,
2272        sp<IMemoryHeap>* heap,
2273        uint32_t* w, uint32_t* h, PixelFormat* f,
2274        uint32_t sw, uint32_t sh,
2275        uint32_t minLayerZ, uint32_t maxLayerZ)
2276{
2277    ATRACE_CALL();
2278
2279    status_t result = PERMISSION_DENIED;
2280
2281    if (!GLExtensions::getInstance().haveFramebufferObject()) {
2282        return INVALID_OPERATION;
2283    }
2284
2285    // get screen geometry
2286    sp<const DisplayDevice> hw(getDisplayDevice(display));
2287    const uint32_t hw_w = hw->getWidth();
2288    const uint32_t hw_h = hw->getHeight();
2289
2290    // if we have secure windows on this display, never allow the screen capture
2291    if (hw->getSecureLayerVisible()) {
2292        ALOGW("FB is protected: PERMISSION_DENIED");
2293        return PERMISSION_DENIED;
2294    }
2295
2296    if ((sw > hw_w) || (sh > hw_h)) {
2297        ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h);
2298        return BAD_VALUE;
2299    }
2300
2301    sw = (!sw) ? hw_w : sw;
2302    sh = (!sh) ? hw_h : sh;
2303    const size_t size = sw * sh * 4;
2304    const bool filtering = sw != hw_w || sh != hw_h;
2305
2306//    ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2307//            sw, sh, minLayerZ, maxLayerZ);
2308
2309    // make sure to clear all GL error flags
2310    while ( glGetError() != GL_NO_ERROR ) ;
2311
2312    // create a FBO
2313    GLuint name, tname;
2314    glGenRenderbuffersOES(1, &tname);
2315    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2316    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2317
2318    glGenFramebuffersOES(1, &name);
2319    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2320    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2321            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2322
2323    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2324
2325    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2326
2327        // invert everything, b/c glReadPixel() below will invert the FB
2328        glViewport(0, 0, sw, sh);
2329        glMatrixMode(GL_PROJECTION);
2330        glPushMatrix();
2331        glLoadIdentity();
2332        glOrthof(0, hw_w, hw_h, 0, 0, 1);
2333        glMatrixMode(GL_MODELVIEW);
2334
2335        // redraw the screen entirely...
2336        glClearColor(0,0,0,1);
2337        glClear(GL_COLOR_BUFFER_BIT);
2338
2339        const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2340        const size_t count = layers.size();
2341        for (size_t i=0 ; i<count ; ++i) {
2342            const sp<LayerBase>& layer(layers[i]);
2343            const uint32_t z = layer->drawingState().z;
2344            if (z >= minLayerZ && z <= maxLayerZ) {
2345                if (filtering) layer->setFiltering(true);
2346                layer->draw(hw);
2347                if (filtering) layer->setFiltering(false);
2348            }
2349        }
2350
2351        // check for errors and return screen capture
2352        if (glGetError() != GL_NO_ERROR) {
2353            // error while rendering
2354            result = INVALID_OPERATION;
2355        } else {
2356            // allocate shared memory large enough to hold the
2357            // screen capture
2358            sp<MemoryHeapBase> base(
2359                    new MemoryHeapBase(size, 0, "screen-capture") );
2360            void* const ptr = base->getBase();
2361            if (ptr) {
2362                // capture the screen with glReadPixels()
2363                ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2364                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2365                if (glGetError() == GL_NO_ERROR) {
2366                    *heap = base;
2367                    *w = sw;
2368                    *h = sh;
2369                    *f = PIXEL_FORMAT_RGBA_8888;
2370                    result = NO_ERROR;
2371                }
2372            } else {
2373                result = NO_MEMORY;
2374            }
2375        }
2376        glViewport(0, 0, hw_w, hw_h);
2377        glMatrixMode(GL_PROJECTION);
2378        glPopMatrix();
2379        glMatrixMode(GL_MODELVIEW);
2380    } else {
2381        result = BAD_VALUE;
2382    }
2383
2384    // release FBO resources
2385    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2386    glDeleteRenderbuffersOES(1, &tname);
2387    glDeleteFramebuffersOES(1, &name);
2388
2389    hw->compositionComplete();
2390
2391//    ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2392
2393    return result;
2394}
2395
2396
2397status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2398        sp<IMemoryHeap>* heap,
2399        uint32_t* width, uint32_t* height, PixelFormat* format,
2400        uint32_t sw, uint32_t sh,
2401        uint32_t minLayerZ, uint32_t maxLayerZ)
2402{
2403    if (CC_UNLIKELY(display == 0))
2404        return BAD_VALUE;
2405
2406    if (!GLExtensions::getInstance().haveFramebufferObject())
2407        return INVALID_OPERATION;
2408
2409    class MessageCaptureScreen : public MessageBase {
2410        SurfaceFlinger* flinger;
2411        sp<IBinder> display;
2412        sp<IMemoryHeap>* heap;
2413        uint32_t* w;
2414        uint32_t* h;
2415        PixelFormat* f;
2416        uint32_t sw;
2417        uint32_t sh;
2418        uint32_t minLayerZ;
2419        uint32_t maxLayerZ;
2420        status_t result;
2421    public:
2422        MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display,
2423                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2424                uint32_t sw, uint32_t sh,
2425                uint32_t minLayerZ, uint32_t maxLayerZ)
2426            : flinger(flinger), display(display),
2427              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2428              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2429              result(PERMISSION_DENIED)
2430        {
2431        }
2432        status_t getResult() const {
2433            return result;
2434        }
2435        virtual bool handler() {
2436            Mutex::Autolock _l(flinger->mStateLock);
2437            result = flinger->captureScreenImplLocked(display,
2438                    heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2439            return true;
2440        }
2441    };
2442
2443    sp<MessageBase> msg = new MessageCaptureScreen(this,
2444            display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2445    status_t res = postMessageSync(msg);
2446    if (res == NO_ERROR) {
2447        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2448    }
2449    return res;
2450}
2451
2452// ---------------------------------------------------------------------------
2453
2454SurfaceFlinger::LayerVector::LayerVector() {
2455}
2456
2457SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2458    : SortedVector<sp<LayerBase> >(rhs) {
2459}
2460
2461int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2462    const void* rhs) const
2463{
2464    // sort layers per layer-stack, then by z-order and finally by sequence
2465    const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2466    const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2467
2468    uint32_t ls = l->currentState().layerStack;
2469    uint32_t rs = r->currentState().layerStack;
2470    if (ls != rs)
2471        return ls - rs;
2472
2473    uint32_t lz = l->currentState().z;
2474    uint32_t rz = r->currentState().z;
2475    if (lz != rz)
2476        return lz - rz;
2477
2478    return l->sequence - r->sequence;
2479}
2480
2481// ---------------------------------------------------------------------------
2482
2483SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2484    : type(DisplayDevice::DISPLAY_ID_INVALID) {
2485}
2486
2487SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2488    : type(type), layerStack(0), orientation(0) {
2489    viewport.makeInvalid();
2490    frame.makeInvalid();
2491}
2492
2493// ---------------------------------------------------------------------------
2494
2495GraphicBufferAlloc::GraphicBufferAlloc() {}
2496
2497GraphicBufferAlloc::~GraphicBufferAlloc() {}
2498
2499sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2500        PixelFormat format, uint32_t usage, status_t* error) {
2501    sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2502    status_t err = graphicBuffer->initCheck();
2503    *error = err;
2504    if (err != 0 || graphicBuffer->handle == 0) {
2505        if (err == NO_MEMORY) {
2506            GraphicBuffer::dumpAllocationsToSystemLog();
2507        }
2508        ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
2509             "failed (%s), handle=%p",
2510                w, h, strerror(-err), graphicBuffer->handle);
2511        return 0;
2512    }
2513    return graphicBuffer;
2514}
2515
2516// ---------------------------------------------------------------------------
2517
2518}; // namespace android
2519