SurfaceFlinger.cpp revision 7306c670eb3ddb471d983a7458eb9f522afd0763
194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood/*
294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * Copyright (C) 2007 The Android Open Source Project
394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood *
494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * Licensed under the Apache License, Version 2.0 (the "License");
594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * you may not use this file except in compliance with the License.
694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * You may obtain a copy of the License at
794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood *
894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood *      http://www.apache.org/licenses/LICENSE-2.0
994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood *
1094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * Unless required by applicable law or agreed to in writing, software
1194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * distributed under the License is distributed on an "AS IS" BASIS,
1294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * See the License for the specific language governing permissions and
1494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * limitations under the License.
1594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood */
1694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
1794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#define ATRACE_TAG ATRACE_TAG_GRAPHICS
1894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
1994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <stdint.h>
2094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <sys/types.h>
2194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <errno.h>
2294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <math.h>
2394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <dlfcn.h>
2494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <inttypes.h>
2594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <stdatomic.h>
2694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
2794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <EGL/egl.h>
2894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
2994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <cutils/log.h>
3094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <cutils/properties.h>
3194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
3294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <binder/IPCThreadState.h>
3394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <binder/IServiceManager.h>
3494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <binder/MemoryHeapBase.h>
3594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <binder/PermissionCache.h>
3694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
3794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <ui/DisplayInfo.h>
3894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
3994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <gui/BitTube.h>
4094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <gui/BufferQueue.h>
4194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <gui/GuiConfig.h>
4294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <gui/IDisplayEventConnection.h>
4394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <gui/Surface.h>
4494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <gui/GraphicBufferAlloc.h>
4594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
4694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <ui/GraphicBufferAllocator.h>
4794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <ui/PixelFormat.h>
4894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <ui/UiConfig.h>
4994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
5094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <utils/misc.h>
5194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <utils/String8.h>
5294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <utils/String16.h>
5394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <utils/StopWatch.h>
5494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <utils/Trace.h>
5594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
5694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <private/android_filesystem_config.h>
5794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <private/gui/SyncFeatures.h>
5894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
5994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "Client.h"
6094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "clz.h"
6194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "Colorizer.h"
6294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "DdmConnection.h"
6394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "DisplayDevice.h"
6494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "DispSync.h"
6594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "EventControlThread.h"
6694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "EventThread.h"
6794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "Layer.h"
6894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "LayerDim.h"
6994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "SurfaceFlinger.h"
7094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
7194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "DisplayHardware/FramebufferSurface.h"
7294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "DisplayHardware/HWComposer.h"
7394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "DisplayHardware/VirtualDisplaySurface.h"
7494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
7594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "Effects/Daltonizer.h"
7694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
7794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include "RenderEngine/RenderEngine.h"
7894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#include <cutils/compiler.h>
7994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
8094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#define DISPLAY_COUNT       1
8194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
8294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood/*
8394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
8494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood * black pixels.
8594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood */
8694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood#define DEBUG_SCREENSHOTS   false
8794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
8894afecf4b6f437b3ee9a076242402e421c6c07a6Mike LockwoodEGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
8994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
9094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodnamespace android {
9194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
9294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// This is the phase offset in nanoseconds of the software vsync event
9394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// relative to the vsync event reported by HWComposer.  The software vsync
9494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// event is when SurfaceFlinger and Choreographer-based applications run each
9594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// frame.
9694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood//
9794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// This phase offset allows adjustment of the minimum latency from application
9894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// wake-up (by Choregographer) time to the time at which the resulting window
9994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// image is displayed.  This value may be either positive (after the HW vsync)
10094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// or negative (before the HW vsync).  Setting it to 0 will result in a
10194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// minimum latency of two vsync periods because the app and SurfaceFlinger
10294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// will run just after the HW vsync.  Setting it to a positive number will
10394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// result in the minimum latency being:
10494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood//
10594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood//     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
10694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood//
10794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// Note that reducing this latency makes it more likely for the applications
10894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// to not have their window content image ready in time.  When this happens
10994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// the latency will end up being an additional vsync period, and animations
11094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// will hiccup.  Therefore, this latency should be tuned somewhat
11194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// conservatively (or at least with awareness of the trade-off being made).
11294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodstatic const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
11394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
11494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// This is the phase offset at which SurfaceFlinger's composition runs.
11594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodstatic const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
11694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
11794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// ---------------------------------------------------------------------------
11894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
11994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodconst String16 sHardwareTest("android.permission.HARDWARE_TEST");
12094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodconst String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
12194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodconst String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
12294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodconst String16 sDump("android.permission.DUMP");
12394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
12494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// ---------------------------------------------------------------------------
12594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
12694afecf4b6f437b3ee9a076242402e421c6c07a6Mike LockwoodSurfaceFlinger::SurfaceFlinger()
12794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    :   BnSurfaceComposer(),
12894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mTransactionFlags(0),
12994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mTransactionPending(false),
13094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mAnimTransactionPending(false),
13194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mLayersRemoved(false),
13294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mRepaintEverything(0),
13394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mRenderEngine(NULL),
13494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mBootTime(systemTime()),
13594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mVisibleRegionsDirty(false),
13694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mHwWorkListDirty(false),
13794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mAnimCompositionPending(false),
13894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mDebugRegion(0),
13994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mDebugDDMS(0),
14094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mDebugDisableHWC(0),
14194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mDebugDisableTransformHint(0),
14294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mDebugInSwapBuffers(0),
14394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mLastSwapBufferTime(0),
14494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mDebugInTransaction(0),
14594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mLastTransactionTime(0),
14694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mBootFinished(false),
14794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mPrimaryHWVsyncEnabled(false),
14894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mHWVsyncAvailable(false),
14994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mDaltonize(false),
15094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mHasColorMatrix(false)
15194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
15294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    ALOGI("SurfaceFlinger is starting");
15394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
15494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // debugging stuff...
15594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    char value[PROPERTY_VALUE_MAX];
15694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
15794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
15894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mGpuToCpuSupported = !atoi(value);
15994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
16094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    property_get("debug.sf.showupdates", value, "0");
16194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mDebugRegion = atoi(value);
16294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
16394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    property_get("debug.sf.ddms", value, "0");
16494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mDebugDDMS = atoi(value);
16594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (mDebugDDMS) {
16694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        if (!startDdmConnection()) {
16794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            // start failed, and DDMS debugging not enabled
16894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            mDebugDDMS = 0;
16994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
17094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
17194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    ALOGI_IF(mDebugRegion, "showupdates enabled");
17294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
17394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
17494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
17594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid SurfaceFlinger::onFirstRef()
17694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
17794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mEventQueue.init(this);
17894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
17994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
18094afecf4b6f437b3ee9a076242402e421c6c07a6Mike LockwoodSurfaceFlinger::~SurfaceFlinger()
18194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
18294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
18394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
18494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    eglTerminate(display);
18594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
18694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
18794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
18894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
18994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // the window manager died on us. prepare its eulogy.
19094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
19194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // restore initial conditions (default device unblank, etc)
19294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    initializeDisplays();
19394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
19494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // restart the boot-animation
19594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    startBootAnim();
19694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
19794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
19894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodsp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
19994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
20094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    sp<ISurfaceComposerClient> bclient;
20194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    sp<Client> client(new Client(this));
20294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    status_t err = client->initCheck();
20394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (err == NO_ERROR) {
20494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        bclient = client;
20594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
20694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return bclient;
20794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
20894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
20994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodsp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
21094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        bool secure)
21194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
21294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    class DisplayToken : public BBinder {
21394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        sp<SurfaceFlinger> flinger;
21494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        virtual ~DisplayToken() {
21594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood             // no more references, this display must be terminated
21694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood             Mutex::Autolock _l(flinger->mStateLock);
21794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood             flinger->mCurrentState.displays.removeItem(this);
21894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood             flinger->setTransactionFlags(eDisplayTransactionNeeded);
21994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood         }
22094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood     public:
22194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        DisplayToken(const sp<SurfaceFlinger>& flinger)
22294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            : flinger(flinger) {
22394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
22494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    };
22594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
22694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    sp<BBinder> token = new DisplayToken(this);
22794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
22894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    Mutex::Autolock _l(mStateLock);
22994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
23094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    info.displayName = displayName;
23194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    info.isSecure = secure;
23294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mCurrentState.displays.add(token, info);
23394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
23494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return token;
23594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
23694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
23794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
23894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    Mutex::Autolock _l(mStateLock);
23994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
24094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    ssize_t idx = mCurrentState.displays.indexOfKey(display);
24194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (idx < 0) {
24294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        ALOGW("destroyDisplay: invalid display token");
24394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        return;
24494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
24594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
24694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
24794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (!info.isVirtualDisplay()) {
24894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        ALOGE("destroyDisplay called for non-virtual display");
24994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        return;
25094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
25194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
25294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mCurrentState.displays.removeItemsAt(idx);
25394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    setTransactionFlags(eDisplayTransactionNeeded);
25494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
25594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
25694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
25794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    ALOGW_IF(mBuiltinDisplays[type],
25894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            "Overwriting display token for display type %d", type);
25994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mBuiltinDisplays[type] = new BBinder();
26094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    DisplayDeviceState info(type);
26194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // All non-virtual displays are currently considered secure.
26294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    info.isSecure = true;
26394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mCurrentState.displays.add(mBuiltinDisplays[type], info);
26494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
26594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
26694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodsp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
26794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
26894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
26994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        return NULL;
27094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
27194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return mBuiltinDisplays[id];
27294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
27394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
27494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodsp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
27594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
27694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
27794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return gba;
27894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
27994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
28094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid SurfaceFlinger::bootFinished()
28194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood{
28294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    const nsecs_t now = systemTime();
28394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    const nsecs_t duration = now - mBootTime;
28494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
28594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mBootFinished = true;
28694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
28794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // wait patiently for the window manager death
28894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    const String16 name("window");
28994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    sp<IBinder> window(defaultServiceManager()->getService(name));
29094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (window != 0) {
29194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
29294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
29394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
29494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // stop boot animation
29594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // formerly we would just kill the process, but we now ask it to exit so it
29694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // can choose where to stop the animation.
29794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    property_set("service.bootanim.exit", "1");
29894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
29994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
30094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
30194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    class MessageDestroyGLTexture : public MessageBase {
30294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        RenderEngine& engine;
30394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        uint32_t texture;
30494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    public:
30594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
30694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            : engine(engine), texture(texture) {
30794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
30894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        virtual bool handler() {
30994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            engine.deleteTextures(1, &texture);
31094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            return true;
31194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
31294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    };
31394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
31494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
31594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
31694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodclass DispSyncSource : public VSyncSource, private DispSync::Callback {
31794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodpublic:
31894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
31994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        const char* label) :
32094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            mValue(0),
32194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            mPhaseOffset(phaseOffset),
32294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            mTraceVsync(traceVsync),
32394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
32494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            mVsyncEventLabel(String8::format("VSYNC-%s", label)),
32594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            mDispSync(dispSync) {}
32694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
32794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    virtual ~DispSyncSource() {}
32894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
32994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    virtual void setVSyncEnabled(bool enable) {
33094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // Do NOT lock the mutex here so as to avoid any mutex ordering issues
33194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // with locking it in the onDispSyncEvent callback.
33294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        if (enable) {
33394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            status_t err = mDispSync->addEventListener(mPhaseOffset,
33494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                    static_cast<DispSync::Callback*>(this));
33594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            if (err != NO_ERROR) {
33694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                ALOGE("error registering vsync callback: %s (%d)",
33794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                        strerror(-err), err);
33894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
33994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            //ATRACE_INT(mVsyncOnLabel.string(), 1);
34094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        } else {
34194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            status_t err = mDispSync->removeEventListener(
34294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                    static_cast<DispSync::Callback*>(this));
34394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            if (err != NO_ERROR) {
34494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                ALOGE("error unregistering vsync callback: %s (%d)",
34594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                        strerror(-err), err);
34694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
34794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            //ATRACE_INT(mVsyncOnLabel.string(), 0);
34894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
34994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
35094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
35194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
35294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        Mutex::Autolock lock(mMutex);
35394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mCallback = callback;
35494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
35594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
35694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodprivate:
35794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    virtual void onDispSyncEvent(nsecs_t when) {
35894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        sp<VSyncSource::Callback> callback;
35994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        {
36094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            Mutex::Autolock lock(mMutex);
36194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            callback = mCallback;
36294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
36394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            if (mTraceVsync) {
36494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                mValue = (mValue + 1) % 2;
36594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                ATRACE_INT(mVsyncEventLabel.string(), mValue);
36694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
36794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
36894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
36994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        if (callback != NULL) {
37094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            callback->onVSyncEvent(when);
37194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
37294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
37394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
37494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    int mValue;
37594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
37694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    const nsecs_t mPhaseOffset;
37794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    const bool mTraceVsync;
37894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    const String8 mVsyncOnLabel;
37994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    const String8 mVsyncEventLabel;
38094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
38194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    DispSync* mDispSync;
38294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    sp<VSyncSource::Callback> mCallback;
38394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    Mutex mMutex;
38494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood};
38594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
38694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid SurfaceFlinger::init() {
38794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    ALOGI(  "SurfaceFlinger's main thread ready to run. "
38894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            "Initializing graphics H/W...");
38994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
39094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    status_t err;
39194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    Mutex::Autolock _l(mStateLock);
39294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
39394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // initialize EGL for the default display
39494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
39594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    eglInitialize(mEGLDisplay, NULL, NULL);
39694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
39794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // Initialize the H/W composer object.  There may or may not be an
39894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // actual hardware composer underneath.
39994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mHwc = new HWComposer(this,
40094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            *static_cast<HWComposer::EventHandler *>(this));
40194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
40294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // get a RenderEngine for the given display / config (can't fail)
40394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
40494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
40594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // retrieve the EGL context that was selected/created
40694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mEGLContext = mRenderEngine->getEGLContext();
40794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
40894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
40994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            "couldn't create EGLContext");
41094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
41194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // initialize our non-virtual displays
41294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
41394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
41494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // set-up the displays that are already connected
41594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
41694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            // All non-virtual displays are currently considered secure.
41794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            bool isSecure = true;
41894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            createBuiltinDisplayLocked(type);
41994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            wp<IBinder> token = mBuiltinDisplays[i];
42094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
42194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            sp<IGraphicBufferProducer> producer;
42294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            sp<IGraphicBufferConsumer> consumer;
42394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            BufferQueue::createBufferQueue(&producer, &consumer,
42494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                    new GraphicBufferAlloc());
42594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
42694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
42794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                    consumer);
42894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            int32_t hwcId = allocateHwcDisplayId(type);
42994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            sp<DisplayDevice> hw = new DisplayDevice(this,
43094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                    type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
43194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                    fbs, producer,
43294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                    mRenderEngine->getEGLConfig());
43394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            if (i > DisplayDevice::DISPLAY_PRIMARY) {
43494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                // FIXME: currently we don't get blank/unblank requests
43594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                // for displays other than the main display, so we always
43694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                // assume a connected display is unblanked.
43794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                ALOGD("marking display %zu as acquired/unblanked", i);
43894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                hw->setPowerMode(HWC_POWER_MODE_NORMAL);
43994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
44094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            mDisplays.add(token, hw);
44194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
44294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
44394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
44494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // make the GLContext current so that we can create textures when creating Layers
44594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // (which may happens before we render something)
44694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
44794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
44894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // start the EventThread
44994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
45094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            vsyncPhaseOffsetNs, true, "app");
45194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mEventThread = new EventThread(vsyncSrc);
45294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
45394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            sfVsyncPhaseOffsetNs, true, "sf");
45494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mSFEventThread = new EventThread(sfVsyncSrc);
45594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mEventQueue.setEventThread(mSFEventThread);
45694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
45794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mEventControlThread = new EventControlThread(this);
45894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
45994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
46094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // set a fake vsync period if there is no HWComposer
46194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (mHwc->initCheck() != NO_ERROR) {
46294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        mPrimaryDispSync.setPeriod(16666667);
46394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
46494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
46594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // initialize our drawing state
46694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    mDrawingState = mCurrentState;
46794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
46894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // set initial conditions (e.g. unblank default device)
46994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    initializeDisplays();
47094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
47194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // start boot animation
47294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    startBootAnim();
47394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
47494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
47594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodint32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
47694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
47794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            type : mHwc->allocateDisplayId();
47894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
47994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
48094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid SurfaceFlinger::startBootAnim() {
48194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // start boot animation
48294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    property_set("service.bootanim.exit", "0");
48394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    property_set("ctl.start", "bootanim");
48494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
48594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
48694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodsize_t SurfaceFlinger::getMaxTextureSize() const {
48794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return mRenderEngine->getMaxTextureSize();
48894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
48994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
49094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodsize_t SurfaceFlinger::getMaxViewportDims() const {
49194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return mRenderEngine->getMaxViewportDims();
49294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
49394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
49494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood// ----------------------------------------------------------------------------
49594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
49694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodbool SurfaceFlinger::authenticateSurfaceTexture(
49794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        const sp<IGraphicBufferProducer>& bufferProducer) const {
49894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    Mutex::Autolock _l(mStateLock);
49994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
50094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
50194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
50294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
50394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodstatus_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
50494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        Vector<DisplayInfo>* configs) {
50594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (configs == NULL) {
50694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        return BAD_VALUE;
50794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
50894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
50994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    int32_t type = NAME_NOT_FOUND;
51094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
51194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        if (display == mBuiltinDisplays[i]) {
51294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            type = i;
51394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            break;
51494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
51594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
51694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
51794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (type < 0) {
51894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        return type;
51994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
52094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
52194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    // TODO: Not sure if display density should handled by SF any longer
52294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    class Density {
52394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        static int getDensityFromProperty(char const* propName) {
52494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            char property[PROPERTY_VALUE_MAX];
52594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            int density = 0;
52694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            if (property_get(propName, property, NULL) > 0) {
52794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                density = atoi(property);
52894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
52994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            return density;
53094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
53194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    public:
53294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        static int getEmuDensity() {
53394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            return getDensityFromProperty("qemu.sf.lcd_density"); }
53494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        static int getBuildDensity()  {
53594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            return getDensityFromProperty("ro.sf.lcd_density"); }
53694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    };
53794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
53894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    configs->clear();
53994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
54094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    const Vector<HWComposer::DisplayConfig>& hwConfigs =
54194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            getHwComposer().getConfigs(type);
54294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    for (size_t c = 0; c < hwConfigs.size(); ++c) {
54394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
54494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        DisplayInfo info = DisplayInfo();
54594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
54694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        float xdpi = hwConfig.xdpi;
54794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        float ydpi = hwConfig.ydpi;
54894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
54994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        if (type == DisplayDevice::DISPLAY_PRIMARY) {
55094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            // The density of the device is provided by a build property
55194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            float density = Density::getBuildDensity() / 160.0f;
55294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            if (density == 0) {
55394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                // the build doesn't provide a density -- this is wrong!
55494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                // use xdpi instead
55594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                ALOGE("ro.sf.lcd_density must be defined as a build property");
55694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                density = xdpi / 160.0f;
55794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
55894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            if (Density::getEmuDensity()) {
55994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                // if "qemu.sf.lcd_density" is specified, it overrides everything
56094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                xdpi = ydpi = density = Density::getEmuDensity();
56194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                density /= 160.0f;
56294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            }
56394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            info.density = density;
56494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
56594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            // TODO: this needs to go away (currently needed only by webkit)
56694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            sp<const DisplayDevice> hw(getDefaultDisplayDevice());
56794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            info.orientation = hw->getOrientation();
56894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        } else {
56994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            // TODO: where should this value come from?
57094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            static const int TV_DENSITY = 213;
57194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            info.density = TV_DENSITY / 160.0f;
57294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood            info.orientation = 0;
57394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        }
57494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
57594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        info.w = hwConfig.width;
57694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        info.h = hwConfig.height;
57794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        info.xdpi = xdpi;
57894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        info.ydpi = ydpi;
57994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        info.fps = float(1e9 / hwConfig.refresh);
58094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
58194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
58294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // This is how far in advance a buffer must be queued for
58394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // presentation at a given time.  If you want a buffer to appear
58494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // on the screen at time N, you must submit the buffer before
58594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // (N - presentationDeadline).
58694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        //
58794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // Normally it's one full refresh period (to give SF a chance to
58894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // latch the buffer), but this can be reduced by configuring a
58994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // DispSync offset.  Any additional delays introduced by the hardware
59094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // composer or panel must be accounted for here.
59194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        //
59294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // We add an additional 1ms to allow for processing time and
59394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // differences between the ideal and actual refresh rate.
59494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        info.presentationDeadline =
59594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood                hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
59694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
59794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        // All non-virtual displays are currently considered secure.
59894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        info.secure = true;
59994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
60094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood        configs->push_back(info);
60194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    }
60294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
60394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return NO_ERROR;
60494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
60594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
60694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodint SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
60794afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    return getDisplayDevice(display)->getActiveConfig();
60894afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood}
60994afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
61094afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwoodvoid SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
61194afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
61294afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood          this);
61394afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    int32_t type = hw->getDisplayType();
61494afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    int currentMode = hw->getActiveConfig();
61594afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood
61694afecf4b6f437b3ee9a076242402e421c6c07a6Mike Lockwood    if (mode == currentMode) {
617        ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
618        return;
619    }
620
621    if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
622        ALOGW("Trying to set config for virtual display");
623        return;
624    }
625
626    hw->setActiveConfig(mode);
627    getHwComposer().setActiveConfig(type, mode);
628}
629
630status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
631    class MessageSetActiveConfig: public MessageBase {
632        SurfaceFlinger& mFlinger;
633        sp<IBinder> mDisplay;
634        int mMode;
635    public:
636        MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
637                               int mode) :
638            mFlinger(flinger), mDisplay(disp) { mMode = mode; }
639        virtual bool handler() {
640            Vector<DisplayInfo> configs;
641            mFlinger.getDisplayConfigs(mDisplay, &configs);
642            if(mMode < 0 || mMode >= configs.size()) {
643                ALOGE("Attempt to set active config = %d for display with %d configs",
644                        mMode, configs.size());
645            }
646            sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
647            if (hw == NULL) {
648                ALOGE("Attempt to set active config = %d for null display %p",
649                        mMode, mDisplay.get());
650            } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
651                ALOGW("Attempt to set active config = %d for virtual display",
652                        mMode);
653            } else {
654                mFlinger.setActiveConfigInternal(hw, mMode);
655            }
656            return true;
657        }
658    };
659    sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
660    postMessageSync(msg);
661    return NO_ERROR;
662}
663
664status_t SurfaceFlinger::clearAnimationFrameStats() {
665    Mutex::Autolock _l(mStateLock);
666    mAnimFrameTracker.clearStats();
667    return NO_ERROR;
668}
669
670status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
671    Mutex::Autolock _l(mStateLock);
672    mAnimFrameTracker.getStats(outStats);
673    return NO_ERROR;
674}
675
676// ----------------------------------------------------------------------------
677
678sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
679    return mEventThread->createEventConnection();
680}
681
682// ----------------------------------------------------------------------------
683
684void SurfaceFlinger::waitForEvent() {
685    mEventQueue.waitMessage();
686}
687
688void SurfaceFlinger::signalTransaction() {
689    mEventQueue.invalidate();
690}
691
692void SurfaceFlinger::signalLayerUpdate() {
693    mEventQueue.invalidate();
694}
695
696void SurfaceFlinger::signalRefresh() {
697    mEventQueue.refresh();
698}
699
700status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
701        nsecs_t reltime, uint32_t /* flags */) {
702    return mEventQueue.postMessage(msg, reltime);
703}
704
705status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
706        nsecs_t reltime, uint32_t /* flags */) {
707    status_t res = mEventQueue.postMessage(msg, reltime);
708    if (res == NO_ERROR) {
709        msg->wait();
710    }
711    return res;
712}
713
714void SurfaceFlinger::run() {
715    do {
716        waitForEvent();
717    } while (true);
718}
719
720void SurfaceFlinger::enableHardwareVsync() {
721    Mutex::Autolock _l(mHWVsyncLock);
722    if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
723        mPrimaryDispSync.beginResync();
724        //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
725        mEventControlThread->setVsyncEnabled(true);
726        mPrimaryHWVsyncEnabled = true;
727    }
728}
729
730void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
731    Mutex::Autolock _l(mHWVsyncLock);
732
733    if (makeAvailable) {
734        mHWVsyncAvailable = true;
735    } else if (!mHWVsyncAvailable) {
736        ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
737        return;
738    }
739
740    const nsecs_t period =
741            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
742
743    mPrimaryDispSync.reset();
744    mPrimaryDispSync.setPeriod(period);
745
746    if (!mPrimaryHWVsyncEnabled) {
747        mPrimaryDispSync.beginResync();
748        //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
749        mEventControlThread->setVsyncEnabled(true);
750        mPrimaryHWVsyncEnabled = true;
751    }
752}
753
754void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
755    Mutex::Autolock _l(mHWVsyncLock);
756    if (mPrimaryHWVsyncEnabled) {
757        //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
758        mEventControlThread->setVsyncEnabled(false);
759        mPrimaryDispSync.endResync();
760        mPrimaryHWVsyncEnabled = false;
761    }
762    if (makeUnavailable) {
763        mHWVsyncAvailable = false;
764    }
765}
766
767void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
768    bool needsHwVsync = false;
769
770    { // Scope for the lock
771        Mutex::Autolock _l(mHWVsyncLock);
772        if (type == 0 && mPrimaryHWVsyncEnabled) {
773            needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
774        }
775    }
776
777    if (needsHwVsync) {
778        enableHardwareVsync();
779    } else {
780        disableHardwareVsync(false);
781    }
782}
783
784void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
785    if (mEventThread == NULL) {
786        // This is a temporary workaround for b/7145521.  A non-null pointer
787        // does not mean EventThread has finished initializing, so this
788        // is not a correct fix.
789        ALOGW("WARNING: EventThread not started, ignoring hotplug");
790        return;
791    }
792
793    if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
794        Mutex::Autolock _l(mStateLock);
795        if (connected) {
796            createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
797        } else {
798            mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
799            mBuiltinDisplays[type].clear();
800        }
801        setTransactionFlags(eDisplayTransactionNeeded);
802
803        // Defer EventThread notification until SF has updated mDisplays.
804    }
805}
806
807void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
808    ATRACE_CALL();
809    getHwComposer().eventControl(disp, event, enabled);
810}
811
812void SurfaceFlinger::onMessageReceived(int32_t what) {
813    ATRACE_CALL();
814    switch (what) {
815    case MessageQueue::TRANSACTION:
816        handleMessageTransaction();
817        break;
818    case MessageQueue::INVALIDATE:
819        handleMessageTransaction();
820        handleMessageInvalidate();
821        signalRefresh();
822        break;
823    case MessageQueue::REFRESH:
824        handleMessageRefresh();
825        break;
826    }
827}
828
829void SurfaceFlinger::handleMessageTransaction() {
830    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
831    if (transactionFlags) {
832        handleTransaction(transactionFlags);
833    }
834}
835
836void SurfaceFlinger::handleMessageInvalidate() {
837    ATRACE_CALL();
838    handlePageFlip();
839}
840
841void SurfaceFlinger::handleMessageRefresh() {
842    ATRACE_CALL();
843    preComposition();
844    rebuildLayerStacks();
845    setUpHWComposer();
846    doDebugFlashRegions();
847    doComposition();
848    postComposition();
849}
850
851void SurfaceFlinger::doDebugFlashRegions()
852{
853    // is debugging enabled
854    if (CC_LIKELY(!mDebugRegion))
855        return;
856
857    const bool repaintEverything = mRepaintEverything;
858    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
859        const sp<DisplayDevice>& hw(mDisplays[dpy]);
860        if (hw->isDisplayOn()) {
861            // transform the dirty region into this screen's coordinate space
862            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
863            if (!dirtyRegion.isEmpty()) {
864                // redraw the whole screen
865                doComposeSurfaces(hw, Region(hw->bounds()));
866
867                // and draw the dirty region
868                const int32_t height = hw->getHeight();
869                RenderEngine& engine(getRenderEngine());
870                engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
871
872                hw->compositionComplete();
873                hw->swapBuffers(getHwComposer());
874            }
875        }
876    }
877
878    postFramebuffer();
879
880    if (mDebugRegion > 1) {
881        usleep(mDebugRegion * 1000);
882    }
883
884    HWComposer& hwc(getHwComposer());
885    if (hwc.initCheck() == NO_ERROR) {
886        status_t err = hwc.prepare();
887        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
888    }
889}
890
891void SurfaceFlinger::preComposition()
892{
893    bool needExtraInvalidate = false;
894    const LayerVector& layers(mDrawingState.layersSortedByZ);
895    const size_t count = layers.size();
896    for (size_t i=0 ; i<count ; i++) {
897        if (layers[i]->onPreComposition()) {
898            needExtraInvalidate = true;
899        }
900    }
901    if (needExtraInvalidate) {
902        signalLayerUpdate();
903    }
904}
905
906void SurfaceFlinger::postComposition()
907{
908    const LayerVector& layers(mDrawingState.layersSortedByZ);
909    const size_t count = layers.size();
910    for (size_t i=0 ; i<count ; i++) {
911        layers[i]->onPostComposition();
912    }
913
914    const HWComposer& hwc = getHwComposer();
915    sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
916
917    if (presentFence->isValid()) {
918        if (mPrimaryDispSync.addPresentFence(presentFence)) {
919            enableHardwareVsync();
920        } else {
921            disableHardwareVsync(false);
922        }
923    }
924
925    if (kIgnorePresentFences) {
926        const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
927        if (hw->isDisplayOn()) {
928            enableHardwareVsync();
929        }
930    }
931
932    if (mAnimCompositionPending) {
933        mAnimCompositionPending = false;
934
935        if (presentFence->isValid()) {
936            mAnimFrameTracker.setActualPresentFence(presentFence);
937        } else {
938            // The HWC doesn't support present fences, so use the refresh
939            // timestamp instead.
940            nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
941            mAnimFrameTracker.setActualPresentTime(presentTime);
942        }
943        mAnimFrameTracker.advanceFrame();
944    }
945}
946
947void SurfaceFlinger::rebuildLayerStacks() {
948    // rebuild the visible layer list per screen
949    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
950        ATRACE_CALL();
951        mVisibleRegionsDirty = false;
952        invalidateHwcGeometry();
953
954        const LayerVector& layers(mDrawingState.layersSortedByZ);
955        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
956            Region opaqueRegion;
957            Region dirtyRegion;
958            Vector< sp<Layer> > layersSortedByZ;
959            const sp<DisplayDevice>& hw(mDisplays[dpy]);
960            const Transform& tr(hw->getTransform());
961            const Rect bounds(hw->getBounds());
962            if (hw->isDisplayOn()) {
963                SurfaceFlinger::computeVisibleRegions(layers,
964                        hw->getLayerStack(), dirtyRegion, opaqueRegion);
965
966                const size_t count = layers.size();
967                for (size_t i=0 ; i<count ; i++) {
968                    const sp<Layer>& layer(layers[i]);
969                    const Layer::State& s(layer->getDrawingState());
970                    if (s.layerStack == hw->getLayerStack()) {
971                        Region drawRegion(tr.transform(
972                                layer->visibleNonTransparentRegion));
973                        drawRegion.andSelf(bounds);
974                        if (!drawRegion.isEmpty()) {
975                            layersSortedByZ.add(layer);
976                        }
977                    }
978                }
979            }
980            hw->setVisibleLayersSortedByZ(layersSortedByZ);
981            hw->undefinedRegion.set(bounds);
982            hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
983            hw->dirtyRegion.orSelf(dirtyRegion);
984        }
985    }
986}
987
988void SurfaceFlinger::setUpHWComposer() {
989    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
990        bool mustRecompose =
991                !(mDisplays[dpy]->getDirtyRegion(false).isEmpty());
992        mDisplays[dpy]->beginFrame(mustRecompose);
993    }
994
995    HWComposer& hwc(getHwComposer());
996    if (hwc.initCheck() == NO_ERROR) {
997        // build the h/w work list
998        if (CC_UNLIKELY(mHwWorkListDirty)) {
999            mHwWorkListDirty = false;
1000            for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1001                sp<const DisplayDevice> hw(mDisplays[dpy]);
1002                const int32_t id = hw->getHwcDisplayId();
1003                if (id >= 0) {
1004                    const Vector< sp<Layer> >& currentLayers(
1005                        hw->getVisibleLayersSortedByZ());
1006                    const size_t count = currentLayers.size();
1007                    if (hwc.createWorkList(id, count) == NO_ERROR) {
1008                        HWComposer::LayerListIterator cur = hwc.begin(id);
1009                        const HWComposer::LayerListIterator end = hwc.end(id);
1010                        for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1011                            const sp<Layer>& layer(currentLayers[i]);
1012                            layer->setGeometry(hw, *cur);
1013                            if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1014                                cur->setSkip(true);
1015                            }
1016                        }
1017                    }
1018                }
1019            }
1020        }
1021
1022        // set the per-frame data
1023        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1024            sp<const DisplayDevice> hw(mDisplays[dpy]);
1025            const int32_t id = hw->getHwcDisplayId();
1026            if (id >= 0) {
1027                const Vector< sp<Layer> >& currentLayers(
1028                    hw->getVisibleLayersSortedByZ());
1029                const size_t count = currentLayers.size();
1030                HWComposer::LayerListIterator cur = hwc.begin(id);
1031                const HWComposer::LayerListIterator end = hwc.end(id);
1032                for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1033                    /*
1034                     * update the per-frame h/w composer data for each layer
1035                     * and build the transparent region of the FB
1036                     */
1037                    const sp<Layer>& layer(currentLayers[i]);
1038                    layer->setPerFrameData(hw, *cur);
1039                }
1040            }
1041        }
1042
1043        // If possible, attempt to use the cursor overlay on each display.
1044        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1045            sp<const DisplayDevice> hw(mDisplays[dpy]);
1046            const int32_t id = hw->getHwcDisplayId();
1047            if (id >= 0) {
1048                const Vector< sp<Layer> >& currentLayers(
1049                    hw->getVisibleLayersSortedByZ());
1050                const size_t count = currentLayers.size();
1051                HWComposer::LayerListIterator cur = hwc.begin(id);
1052                const HWComposer::LayerListIterator end = hwc.end(id);
1053                for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1054                    const sp<Layer>& layer(currentLayers[i]);
1055                    if (layer->isPotentialCursor()) {
1056                        cur->setIsCursorLayerHint();
1057                        break;
1058                    }
1059                }
1060            }
1061        }
1062
1063        status_t err = hwc.prepare();
1064        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1065
1066        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1067            sp<const DisplayDevice> hw(mDisplays[dpy]);
1068            hw->prepareFrame(hwc);
1069        }
1070    }
1071}
1072
1073void SurfaceFlinger::doComposition() {
1074    ATRACE_CALL();
1075    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1076    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1077        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1078        if (hw->isDisplayOn()) {
1079            // transform the dirty region into this screen's coordinate space
1080            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1081
1082            // repaint the framebuffer (if needed)
1083            doDisplayComposition(hw, dirtyRegion);
1084
1085            hw->dirtyRegion.clear();
1086            hw->flip(hw->swapRegion);
1087            hw->swapRegion.clear();
1088        }
1089        // inform the h/w that we're done compositing
1090        hw->compositionComplete();
1091    }
1092    postFramebuffer();
1093}
1094
1095void SurfaceFlinger::postFramebuffer()
1096{
1097    ATRACE_CALL();
1098
1099    const nsecs_t now = systemTime();
1100    mDebugInSwapBuffers = now;
1101
1102    HWComposer& hwc(getHwComposer());
1103    if (hwc.initCheck() == NO_ERROR) {
1104        if (!hwc.supportsFramebufferTarget()) {
1105            // EGL spec says:
1106            //   "surface must be bound to the calling thread's current context,
1107            //    for the current rendering API."
1108            getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1109        }
1110        hwc.commit();
1111    }
1112
1113    // make the default display current because the VirtualDisplayDevice code cannot
1114    // deal with dequeueBuffer() being called outside of the composition loop; however
1115    // the code below can call glFlush() which is allowed (and does in some case) call
1116    // dequeueBuffer().
1117    getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1118
1119    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1120        sp<const DisplayDevice> hw(mDisplays[dpy]);
1121        const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1122        hw->onSwapBuffersCompleted(hwc);
1123        const size_t count = currentLayers.size();
1124        int32_t id = hw->getHwcDisplayId();
1125        if (id >=0 && hwc.initCheck() == NO_ERROR) {
1126            HWComposer::LayerListIterator cur = hwc.begin(id);
1127            const HWComposer::LayerListIterator end = hwc.end(id);
1128            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1129                currentLayers[i]->onLayerDisplayed(hw, &*cur);
1130            }
1131        } else {
1132            for (size_t i = 0; i < count; i++) {
1133                currentLayers[i]->onLayerDisplayed(hw, NULL);
1134            }
1135        }
1136    }
1137
1138    mLastSwapBufferTime = systemTime() - now;
1139    mDebugInSwapBuffers = 0;
1140
1141    uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1142    if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1143        logFrameStats();
1144    }
1145}
1146
1147void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1148{
1149    ATRACE_CALL();
1150
1151    // here we keep a copy of the drawing state (that is the state that's
1152    // going to be overwritten by handleTransactionLocked()) outside of
1153    // mStateLock so that the side-effects of the State assignment
1154    // don't happen with mStateLock held (which can cause deadlocks).
1155    State drawingState(mDrawingState);
1156
1157    Mutex::Autolock _l(mStateLock);
1158    const nsecs_t now = systemTime();
1159    mDebugInTransaction = now;
1160
1161    // Here we're guaranteed that some transaction flags are set
1162    // so we can call handleTransactionLocked() unconditionally.
1163    // We call getTransactionFlags(), which will also clear the flags,
1164    // with mStateLock held to guarantee that mCurrentState won't change
1165    // until the transaction is committed.
1166
1167    transactionFlags = getTransactionFlags(eTransactionMask);
1168    handleTransactionLocked(transactionFlags);
1169
1170    mLastTransactionTime = systemTime() - now;
1171    mDebugInTransaction = 0;
1172    invalidateHwcGeometry();
1173    // here the transaction has been committed
1174}
1175
1176void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1177{
1178    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1179    const size_t count = currentLayers.size();
1180
1181    /*
1182     * Traversal of the children
1183     * (perform the transaction for each of them if needed)
1184     */
1185
1186    if (transactionFlags & eTraversalNeeded) {
1187        for (size_t i=0 ; i<count ; i++) {
1188            const sp<Layer>& layer(currentLayers[i]);
1189            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1190            if (!trFlags) continue;
1191
1192            const uint32_t flags = layer->doTransaction(0);
1193            if (flags & Layer::eVisibleRegion)
1194                mVisibleRegionsDirty = true;
1195        }
1196    }
1197
1198    /*
1199     * Perform display own transactions if needed
1200     */
1201
1202    if (transactionFlags & eDisplayTransactionNeeded) {
1203        // here we take advantage of Vector's copy-on-write semantics to
1204        // improve performance by skipping the transaction entirely when
1205        // know that the lists are identical
1206        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1207        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1208        if (!curr.isIdenticalTo(draw)) {
1209            mVisibleRegionsDirty = true;
1210            const size_t cc = curr.size();
1211                  size_t dc = draw.size();
1212
1213            // find the displays that were removed
1214            // (ie: in drawing state but not in current state)
1215            // also handle displays that changed
1216            // (ie: displays that are in both lists)
1217            for (size_t i=0 ; i<dc ; i++) {
1218                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1219                if (j < 0) {
1220                    // in drawing state but not in current state
1221                    if (!draw[i].isMainDisplay()) {
1222                        // Call makeCurrent() on the primary display so we can
1223                        // be sure that nothing associated with this display
1224                        // is current.
1225                        const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1226                        defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1227                        sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1228                        if (hw != NULL)
1229                            hw->disconnect(getHwComposer());
1230                        if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1231                            mEventThread->onHotplugReceived(draw[i].type, false);
1232                        mDisplays.removeItem(draw.keyAt(i));
1233                    } else {
1234                        ALOGW("trying to remove the main display");
1235                    }
1236                } else {
1237                    // this display is in both lists. see if something changed.
1238                    const DisplayDeviceState& state(curr[j]);
1239                    const wp<IBinder>& display(curr.keyAt(j));
1240                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1241                        // changing the surface is like destroying and
1242                        // recreating the DisplayDevice, so we just remove it
1243                        // from the drawing state, so that it get re-added
1244                        // below.
1245                        sp<DisplayDevice> hw(getDisplayDevice(display));
1246                        if (hw != NULL)
1247                            hw->disconnect(getHwComposer());
1248                        mDisplays.removeItem(display);
1249                        mDrawingState.displays.removeItemsAt(i);
1250                        dc--; i--;
1251                        // at this point we must loop to the next item
1252                        continue;
1253                    }
1254
1255                    const sp<DisplayDevice> disp(getDisplayDevice(display));
1256                    if (disp != NULL) {
1257                        if (state.layerStack != draw[i].layerStack) {
1258                            disp->setLayerStack(state.layerStack);
1259                        }
1260                        if ((state.orientation != draw[i].orientation)
1261                                || (state.viewport != draw[i].viewport)
1262                                || (state.frame != draw[i].frame))
1263                        {
1264                            disp->setProjection(state.orientation,
1265                                    state.viewport, state.frame);
1266                        }
1267                        if (state.width != draw[i].width || state.height != draw[i].height) {
1268                            disp->setDisplaySize(state.width, state.height);
1269                        }
1270                    }
1271                }
1272            }
1273
1274            // find displays that were added
1275            // (ie: in current state but not in drawing state)
1276            for (size_t i=0 ; i<cc ; i++) {
1277                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1278                    const DisplayDeviceState& state(curr[i]);
1279
1280                    sp<DisplaySurface> dispSurface;
1281                    sp<IGraphicBufferProducer> producer;
1282                    sp<IGraphicBufferProducer> bqProducer;
1283                    sp<IGraphicBufferConsumer> bqConsumer;
1284                    BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1285                            new GraphicBufferAlloc());
1286
1287                    int32_t hwcDisplayId = -1;
1288                    if (state.isVirtualDisplay()) {
1289                        // Virtual displays without a surface are dormant:
1290                        // they have external state (layer stack, projection,
1291                        // etc.) but no internal state (i.e. a DisplayDevice).
1292                        if (state.surface != NULL) {
1293
1294                            hwcDisplayId = allocateHwcDisplayId(state.type);
1295                            sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1296                                    *mHwc, hwcDisplayId, state.surface,
1297                                    bqProducer, bqConsumer, state.displayName);
1298
1299                            dispSurface = vds;
1300                            producer = vds;
1301                        }
1302                    } else {
1303                        ALOGE_IF(state.surface!=NULL,
1304                                "adding a supported display, but rendering "
1305                                "surface is provided (%p), ignoring it",
1306                                state.surface.get());
1307                        hwcDisplayId = allocateHwcDisplayId(state.type);
1308                        // for supported (by hwc) displays we provide our
1309                        // own rendering surface
1310                        dispSurface = new FramebufferSurface(*mHwc, state.type,
1311                                bqConsumer);
1312                        producer = bqProducer;
1313                    }
1314
1315                    const wp<IBinder>& display(curr.keyAt(i));
1316                    if (dispSurface != NULL) {
1317                        sp<DisplayDevice> hw = new DisplayDevice(this,
1318                                state.type, hwcDisplayId,
1319                                mHwc->getFormat(hwcDisplayId), state.isSecure,
1320                                display, dispSurface, producer,
1321                                mRenderEngine->getEGLConfig());
1322                        hw->setLayerStack(state.layerStack);
1323                        hw->setProjection(state.orientation,
1324                                state.viewport, state.frame);
1325                        hw->setDisplayName(state.displayName);
1326                        mDisplays.add(display, hw);
1327                        if (state.isVirtualDisplay()) {
1328                            if (hwcDisplayId >= 0) {
1329                                mHwc->setVirtualDisplayProperties(hwcDisplayId,
1330                                        hw->getWidth(), hw->getHeight(),
1331                                        hw->getFormat());
1332                            }
1333                        } else {
1334                            mEventThread->onHotplugReceived(state.type, true);
1335                        }
1336                    }
1337                }
1338            }
1339        }
1340    }
1341
1342    if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1343        // The transform hint might have changed for some layers
1344        // (either because a display has changed, or because a layer
1345        // as changed).
1346        //
1347        // Walk through all the layers in currentLayers,
1348        // and update their transform hint.
1349        //
1350        // If a layer is visible only on a single display, then that
1351        // display is used to calculate the hint, otherwise we use the
1352        // default display.
1353        //
1354        // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1355        // the hint is set before we acquire a buffer from the surface texture.
1356        //
1357        // NOTE: layer transactions have taken place already, so we use their
1358        // drawing state. However, SurfaceFlinger's own transaction has not
1359        // happened yet, so we must use the current state layer list
1360        // (soon to become the drawing state list).
1361        //
1362        sp<const DisplayDevice> disp;
1363        uint32_t currentlayerStack = 0;
1364        for (size_t i=0; i<count; i++) {
1365            // NOTE: we rely on the fact that layers are sorted by
1366            // layerStack first (so we don't have to traverse the list
1367            // of displays for every layer).
1368            const sp<Layer>& layer(currentLayers[i]);
1369            uint32_t layerStack = layer->getDrawingState().layerStack;
1370            if (i==0 || currentlayerStack != layerStack) {
1371                currentlayerStack = layerStack;
1372                // figure out if this layerstack is mirrored
1373                // (more than one display) if so, pick the default display,
1374                // if not, pick the only display it's on.
1375                disp.clear();
1376                for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1377                    sp<const DisplayDevice> hw(mDisplays[dpy]);
1378                    if (hw->getLayerStack() == currentlayerStack) {
1379                        if (disp == NULL) {
1380                            disp = hw;
1381                        } else {
1382                            disp = NULL;
1383                            break;
1384                        }
1385                    }
1386                }
1387            }
1388            if (disp == NULL) {
1389                // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1390                // redraw after transform hint changes. See bug 8508397.
1391
1392                // could be null when this layer is using a layerStack
1393                // that is not visible on any display. Also can occur at
1394                // screen off/on times.
1395                disp = getDefaultDisplayDevice();
1396            }
1397            layer->updateTransformHint(disp);
1398        }
1399    }
1400
1401
1402    /*
1403     * Perform our own transaction if needed
1404     */
1405
1406    const LayerVector& layers(mDrawingState.layersSortedByZ);
1407    if (currentLayers.size() > layers.size()) {
1408        // layers have been added
1409        mVisibleRegionsDirty = true;
1410    }
1411
1412    // some layers might have been removed, so
1413    // we need to update the regions they're exposing.
1414    if (mLayersRemoved) {
1415        mLayersRemoved = false;
1416        mVisibleRegionsDirty = true;
1417        const size_t count = layers.size();
1418        for (size_t i=0 ; i<count ; i++) {
1419            const sp<Layer>& layer(layers[i]);
1420            if (currentLayers.indexOf(layer) < 0) {
1421                // this layer is not visible anymore
1422                // TODO: we could traverse the tree from front to back and
1423                //       compute the actual visible region
1424                // TODO: we could cache the transformed region
1425                const Layer::State& s(layer->getDrawingState());
1426                Region visibleReg = s.transform.transform(
1427                        Region(Rect(s.active.w, s.active.h)));
1428                invalidateLayerStack(s.layerStack, visibleReg);
1429            }
1430        }
1431    }
1432
1433    commitTransaction();
1434
1435    updateCursorAsync();
1436}
1437
1438void SurfaceFlinger::updateCursorAsync()
1439{
1440    HWComposer& hwc(getHwComposer());
1441    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1442        sp<const DisplayDevice> hw(mDisplays[dpy]);
1443        const int32_t id = hw->getHwcDisplayId();
1444        if (id < 0) {
1445            continue;
1446        }
1447        const Vector< sp<Layer> >& currentLayers(
1448            hw->getVisibleLayersSortedByZ());
1449        const size_t count = currentLayers.size();
1450        HWComposer::LayerListIterator cur = hwc.begin(id);
1451        const HWComposer::LayerListIterator end = hwc.end(id);
1452        for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1453            if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1454                continue;
1455            }
1456            const sp<Layer>& layer(currentLayers[i]);
1457            Rect cursorPos = layer->getPosition(hw);
1458            hwc.setCursorPositionAsync(id, cursorPos);
1459            break;
1460        }
1461    }
1462}
1463
1464void SurfaceFlinger::commitTransaction()
1465{
1466    if (!mLayersPendingRemoval.isEmpty()) {
1467        // Notify removed layers now that they can't be drawn from
1468        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1469            mLayersPendingRemoval[i]->onRemoved();
1470        }
1471        mLayersPendingRemoval.clear();
1472    }
1473
1474    // If this transaction is part of a window animation then the next frame
1475    // we composite should be considered an animation as well.
1476    mAnimCompositionPending = mAnimTransactionPending;
1477
1478    mDrawingState = mCurrentState;
1479    mTransactionPending = false;
1480    mAnimTransactionPending = false;
1481    mTransactionCV.broadcast();
1482}
1483
1484void SurfaceFlinger::computeVisibleRegions(
1485        const LayerVector& currentLayers, uint32_t layerStack,
1486        Region& outDirtyRegion, Region& outOpaqueRegion)
1487{
1488    ATRACE_CALL();
1489
1490    Region aboveOpaqueLayers;
1491    Region aboveCoveredLayers;
1492    Region dirty;
1493
1494    outDirtyRegion.clear();
1495
1496    size_t i = currentLayers.size();
1497    while (i--) {
1498        const sp<Layer>& layer = currentLayers[i];
1499
1500        // start with the whole surface at its current location
1501        const Layer::State& s(layer->getDrawingState());
1502
1503        // only consider the layers on the given layer stack
1504        if (s.layerStack != layerStack)
1505            continue;
1506
1507        /*
1508         * opaqueRegion: area of a surface that is fully opaque.
1509         */
1510        Region opaqueRegion;
1511
1512        /*
1513         * visibleRegion: area of a surface that is visible on screen
1514         * and not fully transparent. This is essentially the layer's
1515         * footprint minus the opaque regions above it.
1516         * Areas covered by a translucent surface are considered visible.
1517         */
1518        Region visibleRegion;
1519
1520        /*
1521         * coveredRegion: area of a surface that is covered by all
1522         * visible regions above it (which includes the translucent areas).
1523         */
1524        Region coveredRegion;
1525
1526        /*
1527         * transparentRegion: area of a surface that is hinted to be completely
1528         * transparent. This is only used to tell when the layer has no visible
1529         * non-transparent regions and can be removed from the layer list. It
1530         * does not affect the visibleRegion of this layer or any layers
1531         * beneath it. The hint may not be correct if apps don't respect the
1532         * SurfaceView restrictions (which, sadly, some don't).
1533         */
1534        Region transparentRegion;
1535
1536
1537        // handle hidden surfaces by setting the visible region to empty
1538        if (CC_LIKELY(layer->isVisible())) {
1539            const bool translucent = !layer->isOpaque(s);
1540            Rect bounds(s.transform.transform(layer->computeBounds()));
1541            visibleRegion.set(bounds);
1542            if (!visibleRegion.isEmpty()) {
1543                // Remove the transparent area from the visible region
1544                if (translucent) {
1545                    const Transform tr(s.transform);
1546                    if (tr.transformed()) {
1547                        if (tr.preserveRects()) {
1548                            // transform the transparent region
1549                            transparentRegion = tr.transform(s.activeTransparentRegion);
1550                        } else {
1551                            // transformation too complex, can't do the
1552                            // transparent region optimization.
1553                            transparentRegion.clear();
1554                        }
1555                    } else {
1556                        transparentRegion = s.activeTransparentRegion;
1557                    }
1558                }
1559
1560                // compute the opaque region
1561                const int32_t layerOrientation = s.transform.getOrientation();
1562                if (s.alpha==255 && !translucent &&
1563                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1564                    // the opaque region is the layer's footprint
1565                    opaqueRegion = visibleRegion;
1566                }
1567            }
1568        }
1569
1570        // Clip the covered region to the visible region
1571        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1572
1573        // Update aboveCoveredLayers for next (lower) layer
1574        aboveCoveredLayers.orSelf(visibleRegion);
1575
1576        // subtract the opaque region covered by the layers above us
1577        visibleRegion.subtractSelf(aboveOpaqueLayers);
1578
1579        // compute this layer's dirty region
1580        if (layer->contentDirty) {
1581            // we need to invalidate the whole region
1582            dirty = visibleRegion;
1583            // as well, as the old visible region
1584            dirty.orSelf(layer->visibleRegion);
1585            layer->contentDirty = false;
1586        } else {
1587            /* compute the exposed region:
1588             *   the exposed region consists of two components:
1589             *   1) what's VISIBLE now and was COVERED before
1590             *   2) what's EXPOSED now less what was EXPOSED before
1591             *
1592             * note that (1) is conservative, we start with the whole
1593             * visible region but only keep what used to be covered by
1594             * something -- which mean it may have been exposed.
1595             *
1596             * (2) handles areas that were not covered by anything but got
1597             * exposed because of a resize.
1598             */
1599            const Region newExposed = visibleRegion - coveredRegion;
1600            const Region oldVisibleRegion = layer->visibleRegion;
1601            const Region oldCoveredRegion = layer->coveredRegion;
1602            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1603            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1604        }
1605        dirty.subtractSelf(aboveOpaqueLayers);
1606
1607        // accumulate to the screen dirty region
1608        outDirtyRegion.orSelf(dirty);
1609
1610        // Update aboveOpaqueLayers for next (lower) layer
1611        aboveOpaqueLayers.orSelf(opaqueRegion);
1612
1613        // Store the visible region in screen space
1614        layer->setVisibleRegion(visibleRegion);
1615        layer->setCoveredRegion(coveredRegion);
1616        layer->setVisibleNonTransparentRegion(
1617                visibleRegion.subtract(transparentRegion));
1618    }
1619
1620    outOpaqueRegion = aboveOpaqueLayers;
1621}
1622
1623void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1624        const Region& dirty) {
1625    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1626        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1627        if (hw->getLayerStack() == layerStack) {
1628            hw->dirtyRegion.orSelf(dirty);
1629        }
1630    }
1631}
1632
1633void SurfaceFlinger::handlePageFlip()
1634{
1635    Region dirtyRegion;
1636
1637    bool visibleRegions = false;
1638    const LayerVector& layers(mDrawingState.layersSortedByZ);
1639    const size_t count = layers.size();
1640    for (size_t i=0 ; i<count ; i++) {
1641        const sp<Layer>& layer(layers[i]);
1642        const Region dirty(layer->latchBuffer(visibleRegions));
1643        const Layer::State& s(layer->getDrawingState());
1644        invalidateLayerStack(s.layerStack, dirty);
1645    }
1646
1647    mVisibleRegionsDirty |= visibleRegions;
1648}
1649
1650void SurfaceFlinger::invalidateHwcGeometry()
1651{
1652    mHwWorkListDirty = true;
1653}
1654
1655
1656void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1657        const Region& inDirtyRegion)
1658{
1659    // We only need to actually compose the display if:
1660    // 1) It is being handled by hardware composer, which may need this to
1661    //    keep its virtual display state machine in sync, or
1662    // 2) There is work to be done (the dirty region isn't empty)
1663    bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1664    if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1665        return;
1666    }
1667
1668    Region dirtyRegion(inDirtyRegion);
1669
1670    // compute the invalid region
1671    hw->swapRegion.orSelf(dirtyRegion);
1672
1673    uint32_t flags = hw->getFlags();
1674    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1675        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1676        // takes a rectangle, we must make sure to update that whole
1677        // rectangle in that case
1678        dirtyRegion.set(hw->swapRegion.bounds());
1679    } else {
1680        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1681            // We need to redraw the rectangle that will be updated
1682            // (pushed to the framebuffer).
1683            // This is needed because PARTIAL_UPDATES only takes one
1684            // rectangle instead of a region (see DisplayDevice::flip())
1685            dirtyRegion.set(hw->swapRegion.bounds());
1686        } else {
1687            // we need to redraw everything (the whole screen)
1688            dirtyRegion.set(hw->bounds());
1689            hw->swapRegion = dirtyRegion;
1690        }
1691    }
1692
1693    if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1694        doComposeSurfaces(hw, dirtyRegion);
1695    } else {
1696        RenderEngine& engine(getRenderEngine());
1697        mat4 colorMatrix = mColorMatrix;
1698        if (mDaltonize) {
1699            colorMatrix = colorMatrix * mDaltonizer();
1700        }
1701        engine.beginGroup(colorMatrix);
1702        doComposeSurfaces(hw, dirtyRegion);
1703        engine.endGroup();
1704    }
1705
1706    // update the swap region and clear the dirty region
1707    hw->swapRegion.orSelf(dirtyRegion);
1708
1709    // swap buffers (presentation)
1710    hw->swapBuffers(getHwComposer());
1711}
1712
1713void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1714{
1715    RenderEngine& engine(getRenderEngine());
1716    const int32_t id = hw->getHwcDisplayId();
1717    HWComposer& hwc(getHwComposer());
1718    HWComposer::LayerListIterator cur = hwc.begin(id);
1719    const HWComposer::LayerListIterator end = hwc.end(id);
1720
1721    bool hasGlesComposition = hwc.hasGlesComposition(id);
1722    if (hasGlesComposition) {
1723        if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1724            ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1725                  hw->getDisplayName().string());
1726            return;
1727        }
1728
1729        // Never touch the framebuffer if we don't have any framebuffer layers
1730        const bool hasHwcComposition = hwc.hasHwcComposition(id);
1731        if (hasHwcComposition) {
1732            // when using overlays, we assume a fully transparent framebuffer
1733            // NOTE: we could reduce how much we need to clear, for instance
1734            // remove where there are opaque FB layers. however, on some
1735            // GPUs doing a "clean slate" clear might be more efficient.
1736            // We'll revisit later if needed.
1737            engine.clearWithColor(0, 0, 0, 0);
1738        } else {
1739            // we start with the whole screen area
1740            const Region bounds(hw->getBounds());
1741
1742            // we remove the scissor part
1743            // we're left with the letterbox region
1744            // (common case is that letterbox ends-up being empty)
1745            const Region letterbox(bounds.subtract(hw->getScissor()));
1746
1747            // compute the area to clear
1748            Region region(hw->undefinedRegion.merge(letterbox));
1749
1750            // but limit it to the dirty region
1751            region.andSelf(dirty);
1752
1753            // screen is already cleared here
1754            if (!region.isEmpty()) {
1755                // can happen with SurfaceView
1756                drawWormhole(hw, region);
1757            }
1758        }
1759
1760        if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1761            // just to be on the safe side, we don't set the
1762            // scissor on the main display. It should never be needed
1763            // anyways (though in theory it could since the API allows it).
1764            const Rect& bounds(hw->getBounds());
1765            const Rect& scissor(hw->getScissor());
1766            if (scissor != bounds) {
1767                // scissor doesn't match the screen's dimensions, so we
1768                // need to clear everything outside of it and enable
1769                // the GL scissor so we don't draw anything where we shouldn't
1770
1771                // enable scissor for this frame
1772                const uint32_t height = hw->getHeight();
1773                engine.setScissor(scissor.left, height - scissor.bottom,
1774                        scissor.getWidth(), scissor.getHeight());
1775            }
1776        }
1777    }
1778
1779    /*
1780     * and then, render the layers targeted at the framebuffer
1781     */
1782
1783    const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1784    const size_t count = layers.size();
1785    const Transform& tr = hw->getTransform();
1786    if (cur != end) {
1787        // we're using h/w composer
1788        for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1789            const sp<Layer>& layer(layers[i]);
1790            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1791            if (!clip.isEmpty()) {
1792                switch (cur->getCompositionType()) {
1793                    case HWC_CURSOR_OVERLAY:
1794                    case HWC_OVERLAY: {
1795                        const Layer::State& state(layer->getDrawingState());
1796                        if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1797                                && i
1798                                && layer->isOpaque(state) && (state.alpha == 0xFF)
1799                                && hasGlesComposition) {
1800                            // never clear the very first layer since we're
1801                            // guaranteed the FB is already cleared
1802                            layer->clearWithOpenGL(hw, clip);
1803                        }
1804                        break;
1805                    }
1806                    case HWC_FRAMEBUFFER: {
1807                        layer->draw(hw, clip);
1808                        break;
1809                    }
1810                    case HWC_FRAMEBUFFER_TARGET: {
1811                        // this should not happen as the iterator shouldn't
1812                        // let us get there.
1813                        ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
1814                        break;
1815                    }
1816                }
1817            }
1818            layer->setAcquireFence(hw, *cur);
1819        }
1820    } else {
1821        // we're not using h/w composer
1822        for (size_t i=0 ; i<count ; ++i) {
1823            const sp<Layer>& layer(layers[i]);
1824            const Region clip(dirty.intersect(
1825                    tr.transform(layer->visibleRegion)));
1826            if (!clip.isEmpty()) {
1827                layer->draw(hw, clip);
1828            }
1829        }
1830    }
1831
1832    // disable scissor at the end of the frame
1833    engine.disableScissor();
1834}
1835
1836void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
1837    const int32_t height = hw->getHeight();
1838    RenderEngine& engine(getRenderEngine());
1839    engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
1840}
1841
1842void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1843        const sp<IBinder>& handle,
1844        const sp<IGraphicBufferProducer>& gbc,
1845        const sp<Layer>& lbc)
1846{
1847    // attach this layer to the client
1848    client->attachLayer(handle, lbc);
1849
1850    // add this layer to the current state list
1851    Mutex::Autolock _l(mStateLock);
1852    mCurrentState.layersSortedByZ.add(lbc);
1853    mGraphicBufferProducerList.add(gbc->asBinder());
1854}
1855
1856status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
1857    Mutex::Autolock _l(mStateLock);
1858    ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1859    if (index >= 0) {
1860        mLayersPendingRemoval.push(layer);
1861        mLayersRemoved = true;
1862        setTransactionFlags(eTransactionNeeded);
1863        return NO_ERROR;
1864    }
1865    return status_t(index);
1866}
1867
1868uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
1869    return android_atomic_release_load(&mTransactionFlags);
1870}
1871
1872uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
1873    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1874}
1875
1876uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
1877    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1878    if ((old & flags)==0) { // wake the server up
1879        signalTransaction();
1880    }
1881    return old;
1882}
1883
1884void SurfaceFlinger::setTransactionState(
1885        const Vector<ComposerState>& state,
1886        const Vector<DisplayState>& displays,
1887        uint32_t flags)
1888{
1889    ATRACE_CALL();
1890    Mutex::Autolock _l(mStateLock);
1891    uint32_t transactionFlags = 0;
1892
1893    if (flags & eAnimation) {
1894        // For window updates that are part of an animation we must wait for
1895        // previous animation "frames" to be handled.
1896        while (mAnimTransactionPending) {
1897            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1898            if (CC_UNLIKELY(err != NO_ERROR)) {
1899                // just in case something goes wrong in SF, return to the
1900                // caller after a few seconds.
1901                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1902                        "waiting for previous animation frame");
1903                mAnimTransactionPending = false;
1904                break;
1905            }
1906        }
1907    }
1908
1909    size_t count = displays.size();
1910    for (size_t i=0 ; i<count ; i++) {
1911        const DisplayState& s(displays[i]);
1912        transactionFlags |= setDisplayStateLocked(s);
1913    }
1914
1915    count = state.size();
1916    for (size_t i=0 ; i<count ; i++) {
1917        const ComposerState& s(state[i]);
1918        // Here we need to check that the interface we're given is indeed
1919        // one of our own. A malicious client could give us a NULL
1920        // IInterface, or one of its own or even one of our own but a
1921        // different type. All these situations would cause us to crash.
1922        //
1923        // NOTE: it would be better to use RTTI as we could directly check
1924        // that we have a Client*. however, RTTI is disabled in Android.
1925        if (s.client != NULL) {
1926            sp<IBinder> binder = s.client->asBinder();
1927            if (binder != NULL) {
1928                String16 desc(binder->getInterfaceDescriptor());
1929                if (desc == ISurfaceComposerClient::descriptor) {
1930                    sp<Client> client( static_cast<Client *>(s.client.get()) );
1931                    transactionFlags |= setClientStateLocked(client, s.state);
1932                }
1933            }
1934        }
1935    }
1936
1937    if (transactionFlags) {
1938        // this triggers the transaction
1939        setTransactionFlags(transactionFlags);
1940
1941        // if this is a synchronous transaction, wait for it to take effect
1942        // before returning.
1943        if (flags & eSynchronous) {
1944            mTransactionPending = true;
1945        }
1946        if (flags & eAnimation) {
1947            mAnimTransactionPending = true;
1948        }
1949        while (mTransactionPending) {
1950            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1951            if (CC_UNLIKELY(err != NO_ERROR)) {
1952                // just in case something goes wrong in SF, return to the
1953                // called after a few seconds.
1954                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1955                mTransactionPending = false;
1956                break;
1957            }
1958        }
1959    }
1960}
1961
1962uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1963{
1964    ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1965    if (dpyIdx < 0)
1966        return 0;
1967
1968    uint32_t flags = 0;
1969    DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1970    if (disp.isValid()) {
1971        const uint32_t what = s.what;
1972        if (what & DisplayState::eSurfaceChanged) {
1973            if (disp.surface->asBinder() != s.surface->asBinder()) {
1974                disp.surface = s.surface;
1975                flags |= eDisplayTransactionNeeded;
1976            }
1977        }
1978        if (what & DisplayState::eLayerStackChanged) {
1979            if (disp.layerStack != s.layerStack) {
1980                disp.layerStack = s.layerStack;
1981                flags |= eDisplayTransactionNeeded;
1982            }
1983        }
1984        if (what & DisplayState::eDisplayProjectionChanged) {
1985            if (disp.orientation != s.orientation) {
1986                disp.orientation = s.orientation;
1987                flags |= eDisplayTransactionNeeded;
1988            }
1989            if (disp.frame != s.frame) {
1990                disp.frame = s.frame;
1991                flags |= eDisplayTransactionNeeded;
1992            }
1993            if (disp.viewport != s.viewport) {
1994                disp.viewport = s.viewport;
1995                flags |= eDisplayTransactionNeeded;
1996            }
1997        }
1998        if (what & DisplayState::eDisplaySizeChanged) {
1999            if (disp.width != s.width) {
2000                disp.width = s.width;
2001                flags |= eDisplayTransactionNeeded;
2002            }
2003            if (disp.height != s.height) {
2004                disp.height = s.height;
2005                flags |= eDisplayTransactionNeeded;
2006            }
2007        }
2008    }
2009    return flags;
2010}
2011
2012uint32_t SurfaceFlinger::setClientStateLocked(
2013        const sp<Client>& client,
2014        const layer_state_t& s)
2015{
2016    uint32_t flags = 0;
2017    sp<Layer> layer(client->getLayerUser(s.surface));
2018    if (layer != 0) {
2019        const uint32_t what = s.what;
2020        if (what & layer_state_t::ePositionChanged) {
2021            if (layer->setPosition(s.x, s.y))
2022                flags |= eTraversalNeeded;
2023        }
2024        if (what & layer_state_t::eLayerChanged) {
2025            // NOTE: index needs to be calculated before we update the state
2026            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2027            if (layer->setLayer(s.z)) {
2028                mCurrentState.layersSortedByZ.removeAt(idx);
2029                mCurrentState.layersSortedByZ.add(layer);
2030                // we need traversal (state changed)
2031                // AND transaction (list changed)
2032                flags |= eTransactionNeeded|eTraversalNeeded;
2033            }
2034        }
2035        if (what & layer_state_t::eSizeChanged) {
2036            if (layer->setSize(s.w, s.h)) {
2037                flags |= eTraversalNeeded;
2038            }
2039        }
2040        if (what & layer_state_t::eAlphaChanged) {
2041            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2042                flags |= eTraversalNeeded;
2043        }
2044        if (what & layer_state_t::eMatrixChanged) {
2045            if (layer->setMatrix(s.matrix))
2046                flags |= eTraversalNeeded;
2047        }
2048        if (what & layer_state_t::eTransparentRegionChanged) {
2049            if (layer->setTransparentRegionHint(s.transparentRegion))
2050                flags |= eTraversalNeeded;
2051        }
2052        if ((what & layer_state_t::eVisibilityChanged) ||
2053                (what & layer_state_t::eOpacityChanged)) {
2054            // TODO: should we just use an eFlagsChanged for this?
2055            if (layer->setFlags(s.flags, s.mask))
2056                flags |= eTraversalNeeded;
2057        }
2058        if (what & layer_state_t::eCropChanged) {
2059            if (layer->setCrop(s.crop))
2060                flags |= eTraversalNeeded;
2061        }
2062        if (what & layer_state_t::eLayerStackChanged) {
2063            // NOTE: index needs to be calculated before we update the state
2064            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2065            if (layer->setLayerStack(s.layerStack)) {
2066                mCurrentState.layersSortedByZ.removeAt(idx);
2067                mCurrentState.layersSortedByZ.add(layer);
2068                // we need traversal (state changed)
2069                // AND transaction (list changed)
2070                flags |= eTransactionNeeded|eTraversalNeeded;
2071            }
2072        }
2073    }
2074    return flags;
2075}
2076
2077status_t SurfaceFlinger::createLayer(
2078        const String8& name,
2079        const sp<Client>& client,
2080        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2081        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2082{
2083    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2084    if (int32_t(w|h) < 0) {
2085        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2086                int(w), int(h));
2087        return BAD_VALUE;
2088    }
2089
2090    status_t result = NO_ERROR;
2091
2092    sp<Layer> layer;
2093
2094    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2095        case ISurfaceComposerClient::eFXSurfaceNormal:
2096            result = createNormalLayer(client,
2097                    name, w, h, flags, format,
2098                    handle, gbp, &layer);
2099            break;
2100        case ISurfaceComposerClient::eFXSurfaceDim:
2101            result = createDimLayer(client,
2102                    name, w, h, flags,
2103                    handle, gbp, &layer);
2104            break;
2105        default:
2106            result = BAD_VALUE;
2107            break;
2108    }
2109
2110    if (result == NO_ERROR) {
2111        addClientLayer(client, *handle, *gbp, layer);
2112        setTransactionFlags(eTransactionNeeded);
2113    }
2114    return result;
2115}
2116
2117status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2118        const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2119        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2120{
2121    // initialize the surfaces
2122    switch (format) {
2123    case PIXEL_FORMAT_TRANSPARENT:
2124    case PIXEL_FORMAT_TRANSLUCENT:
2125        format = PIXEL_FORMAT_RGBA_8888;
2126        break;
2127    case PIXEL_FORMAT_OPAQUE:
2128        format = PIXEL_FORMAT_RGBX_8888;
2129        break;
2130    }
2131
2132    *outLayer = new Layer(this, client, name, w, h, flags);
2133    status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2134    if (err == NO_ERROR) {
2135        *handle = (*outLayer)->getHandle();
2136        *gbp = (*outLayer)->getProducer();
2137    }
2138
2139    ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2140    return err;
2141}
2142
2143status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2144        const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2145        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2146{
2147    *outLayer = new LayerDim(this, client, name, w, h, flags);
2148    *handle = (*outLayer)->getHandle();
2149    *gbp = (*outLayer)->getProducer();
2150    return NO_ERROR;
2151}
2152
2153status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2154{
2155    // called by the window manager when it wants to remove a Layer
2156    status_t err = NO_ERROR;
2157    sp<Layer> l(client->getLayerUser(handle));
2158    if (l != NULL) {
2159        err = removeLayer(l);
2160        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2161                "error removing layer=%p (%s)", l.get(), strerror(-err));
2162    }
2163    return err;
2164}
2165
2166status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2167{
2168    // called by ~LayerCleaner() when all references to the IBinder (handle)
2169    // are gone
2170    status_t err = NO_ERROR;
2171    sp<Layer> l(layer.promote());
2172    if (l != NULL) {
2173        err = removeLayer(l);
2174        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2175                "error removing layer=%p (%s)", l.get(), strerror(-err));
2176    }
2177    return err;
2178}
2179
2180// ---------------------------------------------------------------------------
2181
2182void SurfaceFlinger::onInitializeDisplays() {
2183    // reset screen orientation and use primary layer stack
2184    Vector<ComposerState> state;
2185    Vector<DisplayState> displays;
2186    DisplayState d;
2187    d.what = DisplayState::eDisplayProjectionChanged |
2188             DisplayState::eLayerStackChanged;
2189    d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2190    d.layerStack = 0;
2191    d.orientation = DisplayState::eOrientationDefault;
2192    d.frame.makeInvalid();
2193    d.viewport.makeInvalid();
2194    d.width = 0;
2195    d.height = 0;
2196    displays.add(d);
2197    setTransactionState(state, displays, 0);
2198    setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2199
2200    const nsecs_t period =
2201            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2202    mAnimFrameTracker.setDisplayRefreshPeriod(period);
2203}
2204
2205void SurfaceFlinger::initializeDisplays() {
2206    class MessageScreenInitialized : public MessageBase {
2207        SurfaceFlinger* flinger;
2208    public:
2209        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2210        virtual bool handler() {
2211            flinger->onInitializeDisplays();
2212            return true;
2213        }
2214    };
2215    sp<MessageBase> msg = new MessageScreenInitialized(this);
2216    postMessageAsync(msg);  // we may be called from main thread, use async message
2217}
2218
2219void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2220        int mode) {
2221    ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2222            this);
2223    int32_t type = hw->getDisplayType();
2224    int currentMode = hw->getPowerMode();
2225
2226    if (mode == currentMode) {
2227        ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2228        return;
2229    }
2230
2231    hw->setPowerMode(mode);
2232    if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2233        ALOGW("Trying to set power mode for virtual display");
2234        return;
2235    }
2236
2237    if (currentMode == HWC_POWER_MODE_OFF) {
2238        getHwComposer().setPowerMode(type, mode);
2239        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2240            // FIXME: eventthread only knows about the main display right now
2241            mEventThread->onScreenAcquired();
2242            resyncToHardwareVsync(true);
2243        }
2244
2245        mVisibleRegionsDirty = true;
2246        repaintEverything();
2247    } else if (mode == HWC_POWER_MODE_OFF) {
2248        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2249            disableHardwareVsync(true); // also cancels any in-progress resync
2250
2251            // FIXME: eventthread only knows about the main display right now
2252            mEventThread->onScreenReleased();
2253        }
2254
2255        getHwComposer().setPowerMode(type, mode);
2256        mVisibleRegionsDirty = true;
2257        // from this point on, SF will stop drawing on this display
2258    } else {
2259        getHwComposer().setPowerMode(type, mode);
2260    }
2261}
2262
2263void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2264    class MessageSetPowerMode: public MessageBase {
2265        SurfaceFlinger& mFlinger;
2266        sp<IBinder> mDisplay;
2267        int mMode;
2268    public:
2269        MessageSetPowerMode(SurfaceFlinger& flinger,
2270                const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2271                    mDisplay(disp) { mMode = mode; }
2272        virtual bool handler() {
2273            sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2274            if (hw == NULL) {
2275                ALOGE("Attempt to set power mode = %d for null display %p",
2276                        mMode, mDisplay.get());
2277            } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2278                ALOGW("Attempt to set power mode = %d for virtual display",
2279                        mMode);
2280            } else {
2281                mFlinger.setPowerModeInternal(hw, mMode);
2282            }
2283            return true;
2284        }
2285    };
2286    sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2287    postMessageSync(msg);
2288}
2289
2290// ---------------------------------------------------------------------------
2291
2292status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2293{
2294    String8 result;
2295
2296    IPCThreadState* ipc = IPCThreadState::self();
2297    const int pid = ipc->getCallingPid();
2298    const int uid = ipc->getCallingUid();
2299    if ((uid != AID_SHELL) &&
2300            !PermissionCache::checkPermission(sDump, pid, uid)) {
2301        result.appendFormat("Permission Denial: "
2302                "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2303    } else {
2304        // Try to get the main lock, but don't insist if we can't
2305        // (this would indicate SF is stuck, but we want to be able to
2306        // print something in dumpsys).
2307        int retry = 3;
2308        while (mStateLock.tryLock()<0 && --retry>=0) {
2309            usleep(1000000);
2310        }
2311        const bool locked(retry >= 0);
2312        if (!locked) {
2313            result.append(
2314                    "SurfaceFlinger appears to be unresponsive, "
2315                    "dumping anyways (no locks held)\n");
2316        }
2317
2318        bool dumpAll = true;
2319        size_t index = 0;
2320        size_t numArgs = args.size();
2321        if (numArgs) {
2322            if ((index < numArgs) &&
2323                    (args[index] == String16("--list"))) {
2324                index++;
2325                listLayersLocked(args, index, result);
2326                dumpAll = false;
2327            }
2328
2329            if ((index < numArgs) &&
2330                    (args[index] == String16("--latency"))) {
2331                index++;
2332                dumpStatsLocked(args, index, result);
2333                dumpAll = false;
2334            }
2335
2336            if ((index < numArgs) &&
2337                    (args[index] == String16("--latency-clear"))) {
2338                index++;
2339                clearStatsLocked(args, index, result);
2340                dumpAll = false;
2341            }
2342
2343            if ((index < numArgs) &&
2344                    (args[index] == String16("--dispsync"))) {
2345                index++;
2346                mPrimaryDispSync.dump(result);
2347                dumpAll = false;
2348            }
2349        }
2350
2351        if (dumpAll) {
2352            dumpAllLocked(args, index, result);
2353        }
2354
2355        if (locked) {
2356            mStateLock.unlock();
2357        }
2358    }
2359    write(fd, result.string(), result.size());
2360    return NO_ERROR;
2361}
2362
2363void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2364        size_t& /* index */, String8& result) const
2365{
2366    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2367    const size_t count = currentLayers.size();
2368    for (size_t i=0 ; i<count ; i++) {
2369        const sp<Layer>& layer(currentLayers[i]);
2370        result.appendFormat("%s\n", layer->getName().string());
2371    }
2372}
2373
2374void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2375        String8& result) const
2376{
2377    String8 name;
2378    if (index < args.size()) {
2379        name = String8(args[index]);
2380        index++;
2381    }
2382
2383    const nsecs_t period =
2384            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2385    result.appendFormat("%" PRId64 "\n", period);
2386
2387    if (name.isEmpty()) {
2388        mAnimFrameTracker.dumpStats(result);
2389    } else {
2390        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2391        const size_t count = currentLayers.size();
2392        for (size_t i=0 ; i<count ; i++) {
2393            const sp<Layer>& layer(currentLayers[i]);
2394            if (name == layer->getName()) {
2395                layer->dumpFrameStats(result);
2396            }
2397        }
2398    }
2399}
2400
2401void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2402        String8& /* result */)
2403{
2404    String8 name;
2405    if (index < args.size()) {
2406        name = String8(args[index]);
2407        index++;
2408    }
2409
2410    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2411    const size_t count = currentLayers.size();
2412    for (size_t i=0 ; i<count ; i++) {
2413        const sp<Layer>& layer(currentLayers[i]);
2414        if (name.isEmpty() || (name == layer->getName())) {
2415            layer->clearFrameStats();
2416        }
2417    }
2418
2419    mAnimFrameTracker.clearStats();
2420}
2421
2422// This should only be called from the main thread.  Otherwise it would need
2423// the lock and should use mCurrentState rather than mDrawingState.
2424void SurfaceFlinger::logFrameStats() {
2425    const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2426    const size_t count = drawingLayers.size();
2427    for (size_t i=0 ; i<count ; i++) {
2428        const sp<Layer>& layer(drawingLayers[i]);
2429        layer->logFrameStats();
2430    }
2431
2432    mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2433}
2434
2435/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2436{
2437    static const char* config =
2438            " [sf"
2439#ifdef HAS_CONTEXT_PRIORITY
2440            " HAS_CONTEXT_PRIORITY"
2441#endif
2442#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2443            " NEVER_DEFAULT_TO_ASYNC_MODE"
2444#endif
2445#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2446            " TARGET_DISABLE_TRIPLE_BUFFERING"
2447#endif
2448            "]";
2449    result.append(config);
2450}
2451
2452void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2453        String8& result) const
2454{
2455    bool colorize = false;
2456    if (index < args.size()
2457            && (args[index] == String16("--color"))) {
2458        colorize = true;
2459        index++;
2460    }
2461
2462    Colorizer colorizer(colorize);
2463
2464    // figure out if we're stuck somewhere
2465    const nsecs_t now = systemTime();
2466    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2467    const nsecs_t inTransaction(mDebugInTransaction);
2468    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2469    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2470
2471    /*
2472     * Dump library configuration.
2473     */
2474
2475    colorizer.bold(result);
2476    result.append("Build configuration:");
2477    colorizer.reset(result);
2478    appendSfConfigString(result);
2479    appendUiConfigString(result);
2480    appendGuiConfigString(result);
2481    result.append("\n");
2482
2483    colorizer.bold(result);
2484    result.append("Sync configuration: ");
2485    colorizer.reset(result);
2486    result.append(SyncFeatures::getInstance().toString());
2487    result.append("\n");
2488
2489    colorizer.bold(result);
2490    result.append("DispSync configuration: ");
2491    colorizer.reset(result);
2492    result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2493            "present offset %d ns (refresh %" PRId64 " ns)",
2494        vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2495        mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2496    result.append("\n");
2497
2498    /*
2499     * Dump the visible layer list
2500     */
2501    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2502    const size_t count = currentLayers.size();
2503    colorizer.bold(result);
2504    result.appendFormat("Visible layers (count = %zu)\n", count);
2505    colorizer.reset(result);
2506    for (size_t i=0 ; i<count ; i++) {
2507        const sp<Layer>& layer(currentLayers[i]);
2508        layer->dump(result, colorizer);
2509    }
2510
2511    /*
2512     * Dump Display state
2513     */
2514
2515    colorizer.bold(result);
2516    result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2517    colorizer.reset(result);
2518    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2519        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2520        hw->dump(result);
2521    }
2522
2523    /*
2524     * Dump SurfaceFlinger global state
2525     */
2526
2527    colorizer.bold(result);
2528    result.append("SurfaceFlinger global state:\n");
2529    colorizer.reset(result);
2530
2531    HWComposer& hwc(getHwComposer());
2532    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2533
2534    colorizer.bold(result);
2535    result.appendFormat("EGL implementation : %s\n",
2536            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2537    colorizer.reset(result);
2538    result.appendFormat("%s\n",
2539            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2540
2541    mRenderEngine->dump(result);
2542
2543    hw->undefinedRegion.dump(result, "undefinedRegion");
2544    result.appendFormat("  orientation=%d, isDisplayOn=%d\n",
2545            hw->getOrientation(), hw->isDisplayOn());
2546    result.appendFormat(
2547            "  last eglSwapBuffers() time: %f us\n"
2548            "  last transaction time     : %f us\n"
2549            "  transaction-flags         : %08x\n"
2550            "  refresh-rate              : %f fps\n"
2551            "  x-dpi                     : %f\n"
2552            "  y-dpi                     : %f\n"
2553            "  gpu_to_cpu_unsupported    : %d\n"
2554            ,
2555            mLastSwapBufferTime/1000.0,
2556            mLastTransactionTime/1000.0,
2557            mTransactionFlags,
2558            1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2559            hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2560            hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2561            !mGpuToCpuSupported);
2562
2563    result.appendFormat("  eglSwapBuffers time: %f us\n",
2564            inSwapBuffersDuration/1000.0);
2565
2566    result.appendFormat("  transaction time: %f us\n",
2567            inTransactionDuration/1000.0);
2568
2569    /*
2570     * VSYNC state
2571     */
2572    mEventThread->dump(result);
2573
2574    /*
2575     * Dump HWComposer state
2576     */
2577    colorizer.bold(result);
2578    result.append("h/w composer state:\n");
2579    colorizer.reset(result);
2580    result.appendFormat("  h/w composer %s and %s\n",
2581            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2582                    (mDebugDisableHWC || mDebugRegion || mDaltonize
2583                            || mHasColorMatrix) ? "disabled" : "enabled");
2584    hwc.dump(result);
2585
2586    /*
2587     * Dump gralloc state
2588     */
2589    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2590    alloc.dump(result);
2591}
2592
2593const Vector< sp<Layer> >&
2594SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2595    // Note: mStateLock is held here
2596    wp<IBinder> dpy;
2597    for (size_t i=0 ; i<mDisplays.size() ; i++) {
2598        if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2599            dpy = mDisplays.keyAt(i);
2600            break;
2601        }
2602    }
2603    if (dpy == NULL) {
2604        ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2605        // Just use the primary display so we have something to return
2606        dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2607    }
2608    return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2609}
2610
2611bool SurfaceFlinger::startDdmConnection()
2612{
2613    void* libddmconnection_dso =
2614            dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2615    if (!libddmconnection_dso) {
2616        return false;
2617    }
2618    void (*DdmConnection_start)(const char* name);
2619    DdmConnection_start =
2620            (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2621    if (!DdmConnection_start) {
2622        dlclose(libddmconnection_dso);
2623        return false;
2624    }
2625    (*DdmConnection_start)(getServiceName());
2626    return true;
2627}
2628
2629status_t SurfaceFlinger::onTransact(
2630    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2631{
2632    switch (code) {
2633        case CREATE_CONNECTION:
2634        case CREATE_DISPLAY:
2635        case SET_TRANSACTION_STATE:
2636        case BOOT_FINISHED:
2637        case CLEAR_ANIMATION_FRAME_STATS:
2638        case GET_ANIMATION_FRAME_STATS:
2639        case SET_POWER_MODE:
2640        {
2641            // codes that require permission check
2642            IPCThreadState* ipc = IPCThreadState::self();
2643            const int pid = ipc->getCallingPid();
2644            const int uid = ipc->getCallingUid();
2645            if ((uid != AID_GRAPHICS) &&
2646                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2647                ALOGE("Permission Denial: "
2648                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2649                return PERMISSION_DENIED;
2650            }
2651            break;
2652        }
2653        case CAPTURE_SCREEN:
2654        {
2655            // codes that require permission check
2656            IPCThreadState* ipc = IPCThreadState::self();
2657            const int pid = ipc->getCallingPid();
2658            const int uid = ipc->getCallingUid();
2659            if ((uid != AID_GRAPHICS) &&
2660                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2661                ALOGE("Permission Denial: "
2662                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2663                return PERMISSION_DENIED;
2664            }
2665            break;
2666        }
2667    }
2668
2669    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2670    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2671        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2672        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2673            IPCThreadState* ipc = IPCThreadState::self();
2674            const int pid = ipc->getCallingPid();
2675            const int uid = ipc->getCallingUid();
2676            ALOGE("Permission Denial: "
2677                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2678            return PERMISSION_DENIED;
2679        }
2680        int n;
2681        switch (code) {
2682            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2683            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2684                return NO_ERROR;
2685            case 1002:  // SHOW_UPDATES
2686                n = data.readInt32();
2687                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2688                invalidateHwcGeometry();
2689                repaintEverything();
2690                return NO_ERROR;
2691            case 1004:{ // repaint everything
2692                repaintEverything();
2693                return NO_ERROR;
2694            }
2695            case 1005:{ // force transaction
2696                setTransactionFlags(
2697                        eTransactionNeeded|
2698                        eDisplayTransactionNeeded|
2699                        eTraversalNeeded);
2700                return NO_ERROR;
2701            }
2702            case 1006:{ // send empty update
2703                signalRefresh();
2704                return NO_ERROR;
2705            }
2706            case 1008:  // toggle use of hw composer
2707                n = data.readInt32();
2708                mDebugDisableHWC = n ? 1 : 0;
2709                invalidateHwcGeometry();
2710                repaintEverything();
2711                return NO_ERROR;
2712            case 1009:  // toggle use of transform hint
2713                n = data.readInt32();
2714                mDebugDisableTransformHint = n ? 1 : 0;
2715                invalidateHwcGeometry();
2716                repaintEverything();
2717                return NO_ERROR;
2718            case 1010:  // interrogate.
2719                reply->writeInt32(0);
2720                reply->writeInt32(0);
2721                reply->writeInt32(mDebugRegion);
2722                reply->writeInt32(0);
2723                reply->writeInt32(mDebugDisableHWC);
2724                return NO_ERROR;
2725            case 1013: {
2726                Mutex::Autolock _l(mStateLock);
2727                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2728                reply->writeInt32(hw->getPageFlipCount());
2729                return NO_ERROR;
2730            }
2731            case 1014: {
2732                // daltonize
2733                n = data.readInt32();
2734                switch (n % 10) {
2735                    case 1: mDaltonizer.setType(Daltonizer::protanomaly);   break;
2736                    case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2737                    case 3: mDaltonizer.setType(Daltonizer::tritanomaly);   break;
2738                }
2739                if (n >= 10) {
2740                    mDaltonizer.setMode(Daltonizer::correction);
2741                } else {
2742                    mDaltonizer.setMode(Daltonizer::simulation);
2743                }
2744                mDaltonize = n > 0;
2745                invalidateHwcGeometry();
2746                repaintEverything();
2747                return NO_ERROR;
2748            }
2749            case 1015: {
2750                // apply a color matrix
2751                n = data.readInt32();
2752                mHasColorMatrix = n ? 1 : 0;
2753                if (n) {
2754                    // color matrix is sent as mat3 matrix followed by vec3
2755                    // offset, then packed into a mat4 where the last row is
2756                    // the offset and extra values are 0
2757                    for (size_t i = 0 ; i < 4; i++) {
2758                      for (size_t j = 0; j < 4; j++) {
2759                          mColorMatrix[i][j] = data.readFloat();
2760                      }
2761                    }
2762                } else {
2763                    mColorMatrix = mat4();
2764                }
2765                invalidateHwcGeometry();
2766                repaintEverything();
2767                return NO_ERROR;
2768            }
2769            // This is an experimental interface
2770            // Needs to be shifted to proper binder interface when we productize
2771            case 1016: {
2772                n = data.readInt32();
2773                mPrimaryDispSync.setRefreshSkipCount(n);
2774                return NO_ERROR;
2775            }
2776        }
2777    }
2778    return err;
2779}
2780
2781void SurfaceFlinger::repaintEverything() {
2782    android_atomic_or(1, &mRepaintEverything);
2783    signalTransaction();
2784}
2785
2786// ---------------------------------------------------------------------------
2787// Capture screen into an IGraphiBufferProducer
2788// ---------------------------------------------------------------------------
2789
2790/* The code below is here to handle b/8734824
2791 *
2792 * We create a IGraphicBufferProducer wrapper that forwards all calls
2793 * from the surfaceflinger thread to the calling binder thread, where they
2794 * are executed. This allows the calling thread in the calling process to be
2795 * reused and not depend on having "enough" binder threads to handle the
2796 * requests.
2797 */
2798class GraphicProducerWrapper : public BBinder, public MessageHandler {
2799    /* Parts of GraphicProducerWrapper are run on two different threads,
2800     * communicating by sending messages via Looper but also by shared member
2801     * data. Coherence maintenance is subtle and in places implicit (ugh).
2802     *
2803     * Don't rely on Looper's sendMessage/handleMessage providing
2804     * release/acquire semantics for any data not actually in the Message.
2805     * Data going from surfaceflinger to binder threads needs to be
2806     * synchronized explicitly.
2807     *
2808     * Barrier open/wait do provide release/acquire semantics. This provides
2809     * implicit synchronization for data coming back from binder to
2810     * surfaceflinger threads.
2811     */
2812
2813    sp<IGraphicBufferProducer> impl;
2814    sp<Looper> looper;
2815    status_t result;
2816    bool exitPending;
2817    bool exitRequested;
2818    Barrier barrier;
2819    uint32_t code;
2820    Parcel const* data;
2821    Parcel* reply;
2822
2823    enum {
2824        MSG_API_CALL,
2825        MSG_EXIT
2826    };
2827
2828    /*
2829     * Called on surfaceflinger thread. This is called by our "fake"
2830     * BpGraphicBufferProducer. We package the data and reply Parcel and
2831     * forward them to the binder thread.
2832     */
2833    virtual status_t transact(uint32_t code,
2834            const Parcel& data, Parcel* reply, uint32_t /* flags */) {
2835        this->code = code;
2836        this->data = &data;
2837        this->reply = reply;
2838        if (exitPending) {
2839            // if we've exited, we run the message synchronously right here.
2840            // note (JH): as far as I can tell from looking at the code, this
2841            // never actually happens. if it does, i'm not sure if it happens
2842            // on the surfaceflinger or binder thread.
2843            handleMessage(Message(MSG_API_CALL));
2844        } else {
2845            barrier.close();
2846            // Prevent stores to this->{code, data, reply} from being
2847            // reordered later than the construction of Message.
2848            atomic_thread_fence(memory_order_release);
2849            looper->sendMessage(this, Message(MSG_API_CALL));
2850            barrier.wait();
2851        }
2852        return result;
2853    }
2854
2855    /*
2856     * here we run on the binder thread. All we've got to do is
2857     * call the real BpGraphicBufferProducer.
2858     */
2859    virtual void handleMessage(const Message& message) {
2860        int what = message.what;
2861        // Prevent reads below from happening before the read from Message
2862        atomic_thread_fence(memory_order_acquire);
2863        if (what == MSG_API_CALL) {
2864            result = impl->asBinder()->transact(code, data[0], reply);
2865            barrier.open();
2866        } else if (what == MSG_EXIT) {
2867            exitRequested = true;
2868        }
2869    }
2870
2871public:
2872    GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
2873    :   impl(impl),
2874        looper(new Looper(true)),
2875        exitPending(false),
2876        exitRequested(false)
2877    {}
2878
2879    // Binder thread
2880    status_t waitForResponse() {
2881        do {
2882            looper->pollOnce(-1);
2883        } while (!exitRequested);
2884        return result;
2885    }
2886
2887    // Client thread
2888    void exit(status_t result) {
2889        this->result = result;
2890        exitPending = true;
2891        // Ensure this->result is visible to the binder thread before it
2892        // handles the message.
2893        atomic_thread_fence(memory_order_release);
2894        looper->sendMessage(this, Message(MSG_EXIT));
2895    }
2896};
2897
2898
2899status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2900        const sp<IGraphicBufferProducer>& producer,
2901        Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
2902        uint32_t minLayerZ, uint32_t maxLayerZ,
2903        bool useIdentityTransform) {
2904
2905    if (CC_UNLIKELY(display == 0))
2906        return BAD_VALUE;
2907
2908    if (CC_UNLIKELY(producer == 0))
2909        return BAD_VALUE;
2910
2911    // if we have secure windows on this display, never allow the screen capture
2912    // unless the producer interface is local (i.e.: we can take a screenshot for
2913    // ourselves).
2914    if (!producer->asBinder()->localBinder()) {
2915        Mutex::Autolock _l(mStateLock);
2916        sp<const DisplayDevice> hw(getDisplayDevice(display));
2917        if (hw->getSecureLayerVisible()) {
2918            ALOGW("FB is protected: PERMISSION_DENIED");
2919            return PERMISSION_DENIED;
2920        }
2921    }
2922
2923    class MessageCaptureScreen : public MessageBase {
2924        SurfaceFlinger* flinger;
2925        sp<IBinder> display;
2926        sp<IGraphicBufferProducer> producer;
2927        Rect sourceCrop;
2928        uint32_t reqWidth, reqHeight;
2929        uint32_t minLayerZ,maxLayerZ;
2930        bool useIdentityTransform;
2931        status_t result;
2932    public:
2933        MessageCaptureScreen(SurfaceFlinger* flinger,
2934                const sp<IBinder>& display,
2935                const sp<IGraphicBufferProducer>& producer,
2936                Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
2937                uint32_t minLayerZ, uint32_t maxLayerZ,
2938                bool useIdentityTransform)
2939            : flinger(flinger), display(display), producer(producer),
2940              sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
2941              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2942              useIdentityTransform(useIdentityTransform),
2943              result(PERMISSION_DENIED)
2944        {
2945        }
2946        status_t getResult() const {
2947            return result;
2948        }
2949        virtual bool handler() {
2950            Mutex::Autolock _l(flinger->mStateLock);
2951            sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
2952            result = flinger->captureScreenImplLocked(hw, producer,
2953                    sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
2954                    useIdentityTransform);
2955            static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
2956            return true;
2957        }
2958    };
2959
2960    // make sure to process transactions before screenshots -- a transaction
2961    // might already be pending but scheduled for VSYNC; this guarantees we
2962    // will handle it before the screenshot. When VSYNC finally arrives
2963    // the scheduled transaction will be a no-op. If no transactions are
2964    // scheduled at this time, this will end-up being a no-op as well.
2965    mEventQueue.invalidateTransactionNow();
2966
2967    // this creates a "fake" BBinder which will serve as a "fake" remote
2968    // binder to receive the marshaled calls and forward them to the
2969    // real remote (a BpGraphicBufferProducer)
2970    sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
2971
2972    // the asInterface() call below creates our "fake" BpGraphicBufferProducer
2973    // which does the marshaling work forwards to our "fake remote" above.
2974    sp<MessageBase> msg = new MessageCaptureScreen(this,
2975            display, IGraphicBufferProducer::asInterface( wrapper ),
2976            sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
2977            useIdentityTransform);
2978
2979    status_t res = postMessageAsync(msg);
2980    if (res == NO_ERROR) {
2981        res = wrapper->waitForResponse();
2982    }
2983    return res;
2984}
2985
2986
2987void SurfaceFlinger::renderScreenImplLocked(
2988        const sp<const DisplayDevice>& hw,
2989        Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
2990        uint32_t minLayerZ, uint32_t maxLayerZ,
2991        bool yswap, bool useIdentityTransform)
2992{
2993    ATRACE_CALL();
2994    RenderEngine& engine(getRenderEngine());
2995
2996    // get screen geometry
2997    const uint32_t hw_w = hw->getWidth();
2998    const uint32_t hw_h = hw->getHeight();
2999    const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
3000
3001    // if a default or invalid sourceCrop is passed in, set reasonable values
3002    if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3003            !sourceCrop.isValid()) {
3004        sourceCrop.setLeftTop(Point(0, 0));
3005        sourceCrop.setRightBottom(Point(hw_w, hw_h));
3006    }
3007
3008    // ensure that sourceCrop is inside screen
3009    if (sourceCrop.left < 0) {
3010        ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3011    }
3012    if (sourceCrop.right > hw_w) {
3013        ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3014    }
3015    if (sourceCrop.top < 0) {
3016        ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3017    }
3018    if (sourceCrop.bottom > hw_h) {
3019        ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3020    }
3021
3022    // make sure to clear all GL error flags
3023    engine.checkErrors();
3024
3025    // set-up our viewport
3026    engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, hw_h, yswap);
3027    engine.disableTexturing();
3028
3029    // redraw the screen entirely...
3030    engine.clearWithColor(0, 0, 0, 1);
3031
3032    const LayerVector& layers( mDrawingState.layersSortedByZ );
3033    const size_t count = layers.size();
3034    for (size_t i=0 ; i<count ; ++i) {
3035        const sp<Layer>& layer(layers[i]);
3036        const Layer::State& state(layer->getDrawingState());
3037        if (state.layerStack == hw->getLayerStack()) {
3038            if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3039                if (layer->isVisible()) {
3040                    if (filtering) layer->setFiltering(true);
3041                    layer->draw(hw, useIdentityTransform);
3042                    if (filtering) layer->setFiltering(false);
3043                }
3044            }
3045        }
3046    }
3047
3048    // compositionComplete is needed for older driver
3049    hw->compositionComplete();
3050    hw->setViewportAndProjection();
3051}
3052
3053
3054status_t SurfaceFlinger::captureScreenImplLocked(
3055        const sp<const DisplayDevice>& hw,
3056        const sp<IGraphicBufferProducer>& producer,
3057        Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3058        uint32_t minLayerZ, uint32_t maxLayerZ,
3059        bool useIdentityTransform)
3060{
3061    ATRACE_CALL();
3062
3063    // get screen geometry
3064    const uint32_t hw_w = hw->getWidth();
3065    const uint32_t hw_h = hw->getHeight();
3066
3067    if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3068        ALOGE("size mismatch (%d, %d) > (%d, %d)",
3069                reqWidth, reqHeight, hw_w, hw_h);
3070        return BAD_VALUE;
3071    }
3072
3073    reqWidth  = (!reqWidth)  ? hw_w : reqWidth;
3074    reqHeight = (!reqHeight) ? hw_h : reqHeight;
3075
3076    // create a surface (because we're a producer, and we need to
3077    // dequeue/queue a buffer)
3078    sp<Surface> sur = new Surface(producer, false);
3079    ANativeWindow* window = sur.get();
3080
3081    status_t result = NO_ERROR;
3082    if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
3083        uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3084                        GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3085
3086        int err = 0;
3087        err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3088        err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3089        err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3090        err |= native_window_set_usage(window, usage);
3091
3092        if (err == NO_ERROR) {
3093            ANativeWindowBuffer* buffer;
3094            /* TODO: Once we have the sync framework everywhere this can use
3095             * server-side waits on the fence that dequeueBuffer returns.
3096             */
3097            result = native_window_dequeue_buffer_and_wait(window,  &buffer);
3098            if (result == NO_ERROR) {
3099                // create an EGLImage from the buffer so we can later
3100                // turn it into a texture
3101                EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3102                        EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3103                if (image != EGL_NO_IMAGE_KHR) {
3104                    // this binds the given EGLImage as a framebuffer for the
3105                    // duration of this scope.
3106                    RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3107                    if (imageBond.getStatus() == NO_ERROR) {
3108                        // this will in fact render into our dequeued buffer
3109                        // via an FBO, which means we didn't have to create
3110                        // an EGLSurface and therefore we're not
3111                        // dependent on the context's EGLConfig.
3112                        renderScreenImplLocked(hw, sourceCrop, reqWidth, reqHeight,
3113                                minLayerZ, maxLayerZ, true, useIdentityTransform);
3114
3115                        // Create a sync point and wait on it, so we know the buffer is
3116                        // ready before we pass it along.  We can't trivially call glFlush(),
3117                        // so we use a wait flag instead.
3118                        // TODO: pass a sync fd to queueBuffer() and let the consumer wait.
3119                        EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3120                        if (sync != EGL_NO_SYNC_KHR) {
3121                            EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3122                                    EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3123                            EGLint eglErr = eglGetError();
3124                            eglDestroySyncKHR(mEGLDisplay, sync);
3125                            if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3126                                ALOGW("captureScreen: fence wait timed out");
3127                            } else {
3128                                ALOGW_IF(eglErr != EGL_SUCCESS,
3129                                        "captureScreen: error waiting on EGL fence: %#x", eglErr);
3130                            }
3131                        } else {
3132                            ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3133                            // not fatal
3134                        }
3135
3136                        if (DEBUG_SCREENSHOTS) {
3137                            uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3138                            getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3139                            checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3140                                    hw, minLayerZ, maxLayerZ);
3141                            delete [] pixels;
3142                        }
3143
3144                    } else {
3145                        ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3146                        result = INVALID_OPERATION;
3147                    }
3148                    // destroy our image
3149                    eglDestroyImageKHR(mEGLDisplay, image);
3150                } else {
3151                    result = BAD_VALUE;
3152                }
3153                window->queueBuffer(window, buffer, -1);
3154            }
3155        } else {
3156            result = BAD_VALUE;
3157        }
3158        native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3159    }
3160
3161    return result;
3162}
3163
3164void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3165        const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3166    if (DEBUG_SCREENSHOTS) {
3167        for (size_t y=0 ; y<h ; y++) {
3168            uint32_t const * p = (uint32_t const *)vaddr + y*s;
3169            for (size_t x=0 ; x<w ; x++) {
3170                if (p[x] != 0xFF000000) return;
3171            }
3172        }
3173        ALOGE("*** we just took a black screenshot ***\n"
3174                "requested minz=%d, maxz=%d, layerStack=%d",
3175                minLayerZ, maxLayerZ, hw->getLayerStack());
3176        const LayerVector& layers( mDrawingState.layersSortedByZ );
3177        const size_t count = layers.size();
3178        for (size_t i=0 ; i<count ; ++i) {
3179            const sp<Layer>& layer(layers[i]);
3180            const Layer::State& state(layer->getDrawingState());
3181            const bool visible = (state.layerStack == hw->getLayerStack())
3182                                && (state.z >= minLayerZ && state.z <= maxLayerZ)
3183                                && (layer->isVisible());
3184            ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3185                    visible ? '+' : '-',
3186                            i, layer->getName().string(), state.layerStack, state.z,
3187                            layer->isVisible(), state.flags, state.alpha);
3188        }
3189    }
3190}
3191
3192// ---------------------------------------------------------------------------
3193
3194SurfaceFlinger::LayerVector::LayerVector() {
3195}
3196
3197SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3198    : SortedVector<sp<Layer> >(rhs) {
3199}
3200
3201int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3202    const void* rhs) const
3203{
3204    // sort layers per layer-stack, then by z-order and finally by sequence
3205    const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3206    const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3207
3208    uint32_t ls = l->getCurrentState().layerStack;
3209    uint32_t rs = r->getCurrentState().layerStack;
3210    if (ls != rs)
3211        return ls - rs;
3212
3213    uint32_t lz = l->getCurrentState().z;
3214    uint32_t rz = r->getCurrentState().z;
3215    if (lz != rz)
3216        return lz - rz;
3217
3218    return l->sequence - r->sequence;
3219}
3220
3221// ---------------------------------------------------------------------------
3222
3223SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3224    : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
3225}
3226
3227SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3228    : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
3229    viewport.makeInvalid();
3230    frame.makeInvalid();
3231}
3232
3233// ---------------------------------------------------------------------------
3234
3235}; // namespace android
3236
3237
3238#if defined(__gl_h_)
3239#error "don't include gl/gl.h in this file"
3240#endif
3241
3242#if defined(__gl2_h_)
3243#error "don't include gl2/gl2.h in this file"
3244#endif
3245