Home | History | Annotate | Download | only in DisplayHardware
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
     18 
     19 #include <inttypes.h>
     20 #include <math.h>
     21 #include <stdint.h>
     22 #include <stdio.h>
     23 #include <stdlib.h>
     24 #include <string.h>
     25 #include <sys/types.h>
     26 
     27 #include <utils/Errors.h>
     28 #include <utils/misc.h>
     29 #include <utils/NativeHandle.h>
     30 #include <utils/String8.h>
     31 #include <utils/Thread.h>
     32 #include <utils/Trace.h>
     33 #include <utils/Vector.h>
     34 
     35 #include <ui/GraphicBuffer.h>
     36 
     37 #include <hardware/hardware.h>
     38 #include <hardware/hwcomposer.h>
     39 
     40 #include <android/configuration.h>
     41 
     42 #include <cutils/log.h>
     43 #include <cutils/properties.h>
     44 
     45 #include <system/graphics.h>
     46 
     47 #include "HWComposer.h"
     48 
     49 #include "../Layer.h"           // needed only for debugging
     50 #include "../SurfaceFlinger.h"
     51 
     52 namespace android {
     53 
     54 #define MIN_HWC_HEADER_VERSION HWC_HEADER_VERSION
     55 
     56 static uint32_t hwcApiVersion(const hwc_composer_device_1_t* hwc) {
     57     uint32_t hwcVersion = hwc->common.version;
     58     return hwcVersion & HARDWARE_API_VERSION_2_MAJ_MIN_MASK;
     59 }
     60 
     61 static uint32_t hwcHeaderVersion(const hwc_composer_device_1_t* hwc) {
     62     uint32_t hwcVersion = hwc->common.version;
     63     return hwcVersion & HARDWARE_API_VERSION_2_HEADER_MASK;
     64 }
     65 
     66 static bool hwcHasApiVersion(const hwc_composer_device_1_t* hwc,
     67         uint32_t version) {
     68     return hwcApiVersion(hwc) >= (version & HARDWARE_API_VERSION_2_MAJ_MIN_MASK);
     69 }
     70 
     71 // ---------------------------------------------------------------------------
     72 
     73 struct HWComposer::cb_context {
     74     struct callbacks : public hwc_procs_t {
     75         // these are here to facilitate the transition when adding
     76         // new callbacks (an implementation can check for NULL before
     77         // calling a new callback).
     78         void (*zero[4])(void);
     79     };
     80     callbacks procs;
     81     HWComposer* hwc;
     82 };
     83 
     84 // ---------------------------------------------------------------------------
     85 
     86 HWComposer::HWComposer(
     87         const sp<SurfaceFlinger>& flinger,
     88         EventHandler& handler)
     89     : mFlinger(flinger),
     90       mFbDev(0), mHwc(0), mNumDisplays(1),
     91       mCBContext(new cb_context),
     92       mEventHandler(handler),
     93       mDebugForceFakeVSync(false)
     94 {
     95     for (size_t i =0 ; i<MAX_HWC_DISPLAYS ; i++) {
     96         mLists[i] = 0;
     97     }
     98 
     99     for (size_t i=0 ; i<HWC_NUM_PHYSICAL_DISPLAY_TYPES ; i++) {
    100         mLastHwVSync[i] = 0;
    101         mVSyncCounts[i] = 0;
    102     }
    103 
    104     char value[PROPERTY_VALUE_MAX];
    105     property_get("debug.sf.no_hw_vsync", value, "0");
    106     mDebugForceFakeVSync = atoi(value);
    107 
    108     bool needVSyncThread = true;
    109 
    110     // Note: some devices may insist that the FB HAL be opened before HWC.
    111     int fberr = loadFbHalModule();
    112     loadHwcModule();
    113 
    114     if (mFbDev && mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
    115         // close FB HAL if we don't needed it.
    116         // FIXME: this is temporary until we're not forced to open FB HAL
    117         // before HWC.
    118         framebuffer_close(mFbDev);
    119         mFbDev = NULL;
    120     }
    121 
    122     // If we have no HWC, or a pre-1.1 HWC, an FB dev is mandatory.
    123     if ((!mHwc || !hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
    124             && !mFbDev) {
    125         ALOGE("ERROR: failed to open framebuffer (%s), aborting",
    126                 strerror(-fberr));
    127         abort();
    128     }
    129 
    130     // these display IDs are always reserved
    131     for (size_t i=0 ; i<NUM_BUILTIN_DISPLAYS ; i++) {
    132         mAllocatedDisplayIDs.markBit(i);
    133     }
    134 
    135     if (mHwc) {
    136         ALOGI("Using %s version %u.%u", HWC_HARDWARE_COMPOSER,
    137               (hwcApiVersion(mHwc) >> 24) & 0xff,
    138               (hwcApiVersion(mHwc) >> 16) & 0xff);
    139         if (mHwc->registerProcs) {
    140             mCBContext->hwc = this;
    141             mCBContext->procs.invalidate = &hook_invalidate;
    142             mCBContext->procs.vsync = &hook_vsync;
    143             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
    144                 mCBContext->procs.hotplug = &hook_hotplug;
    145             else
    146                 mCBContext->procs.hotplug = NULL;
    147             memset(mCBContext->procs.zero, 0, sizeof(mCBContext->procs.zero));
    148             mHwc->registerProcs(mHwc, &mCBContext->procs);
    149         }
    150 
    151         // don't need a vsync thread if we have a hardware composer
    152         needVSyncThread = false;
    153         // always turn vsync off when we start
    154         eventControl(HWC_DISPLAY_PRIMARY, HWC_EVENT_VSYNC, 0);
    155 
    156         // the number of displays we actually have depends on the
    157         // hw composer version
    158         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
    159             // 1.3 adds support for virtual displays
    160             mNumDisplays = MAX_HWC_DISPLAYS;
    161         } else if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
    162             // 1.1 adds support for multiple displays
    163             mNumDisplays = NUM_BUILTIN_DISPLAYS;
    164         } else {
    165             mNumDisplays = 1;
    166         }
    167     }
    168 
    169     if (mFbDev) {
    170         ALOG_ASSERT(!(mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)),
    171                 "should only have fbdev if no hwc or hwc is 1.0");
    172 
    173         DisplayData& disp(mDisplayData[HWC_DISPLAY_PRIMARY]);
    174         disp.connected = true;
    175         disp.format = mFbDev->format;
    176         DisplayConfig config = DisplayConfig();
    177         config.width = mFbDev->width;
    178         config.height = mFbDev->height;
    179         config.xdpi = mFbDev->xdpi;
    180         config.ydpi = mFbDev->ydpi;
    181         config.refresh = nsecs_t(1e9 / mFbDev->fps);
    182         disp.configs.push_back(config);
    183         disp.currentConfig = 0;
    184     } else if (mHwc) {
    185         // here we're guaranteed to have at least HWC 1.1
    186         for (size_t i =0 ; i<NUM_BUILTIN_DISPLAYS ; i++) {
    187             queryDisplayProperties(i);
    188         }
    189     }
    190 
    191     if (needVSyncThread) {
    192         // we don't have VSYNC support, we need to fake it
    193         mVSyncThread = new VSyncThread(*this);
    194     }
    195 }
    196 
    197 HWComposer::~HWComposer() {
    198     if (mHwc) {
    199         eventControl(HWC_DISPLAY_PRIMARY, HWC_EVENT_VSYNC, 0);
    200     }
    201     if (mVSyncThread != NULL) {
    202         mVSyncThread->requestExitAndWait();
    203     }
    204     if (mHwc) {
    205         hwc_close_1(mHwc);
    206     }
    207     if (mFbDev) {
    208         framebuffer_close(mFbDev);
    209     }
    210     delete mCBContext;
    211 }
    212 
    213 // Load and prepare the hardware composer module.  Sets mHwc.
    214 void HWComposer::loadHwcModule()
    215 {
    216     hw_module_t const* module;
    217 
    218     if (hw_get_module(HWC_HARDWARE_MODULE_ID, &module) != 0) {
    219         ALOGE("%s module not found", HWC_HARDWARE_MODULE_ID);
    220         return;
    221     }
    222 
    223     int err = hwc_open_1(module, &mHwc);
    224     if (err) {
    225         ALOGE("%s device failed to initialize (%s)",
    226               HWC_HARDWARE_COMPOSER, strerror(-err));
    227         return;
    228     }
    229 
    230     if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_0) ||
    231             hwcHeaderVersion(mHwc) < MIN_HWC_HEADER_VERSION ||
    232             hwcHeaderVersion(mHwc) > HWC_HEADER_VERSION) {
    233         ALOGE("%s device version %#x unsupported, will not be used",
    234               HWC_HARDWARE_COMPOSER, mHwc->common.version);
    235         hwc_close_1(mHwc);
    236         mHwc = NULL;
    237         return;
    238     }
    239 }
    240 
    241 // Load and prepare the FB HAL, which uses the gralloc module.  Sets mFbDev.
    242 int HWComposer::loadFbHalModule()
    243 {
    244     hw_module_t const* module;
    245 
    246     int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
    247     if (err != 0) {
    248         ALOGE("%s module not found", GRALLOC_HARDWARE_MODULE_ID);
    249         return err;
    250     }
    251 
    252     return framebuffer_open(module, &mFbDev);
    253 }
    254 
    255 status_t HWComposer::initCheck() const {
    256     return mHwc ? NO_ERROR : NO_INIT;
    257 }
    258 
    259 void HWComposer::hook_invalidate(const struct hwc_procs* procs) {
    260     cb_context* ctx = reinterpret_cast<cb_context*>(
    261             const_cast<hwc_procs_t*>(procs));
    262     ctx->hwc->invalidate();
    263 }
    264 
    265 void HWComposer::hook_vsync(const struct hwc_procs* procs, int disp,
    266         int64_t timestamp) {
    267     cb_context* ctx = reinterpret_cast<cb_context*>(
    268             const_cast<hwc_procs_t*>(procs));
    269     ctx->hwc->vsync(disp, timestamp);
    270 }
    271 
    272 void HWComposer::hook_hotplug(const struct hwc_procs* procs, int disp,
    273         int connected) {
    274     cb_context* ctx = reinterpret_cast<cb_context*>(
    275             const_cast<hwc_procs_t*>(procs));
    276     ctx->hwc->hotplug(disp, connected);
    277 }
    278 
    279 void HWComposer::invalidate() {
    280     mFlinger->repaintEverything();
    281 }
    282 
    283 void HWComposer::vsync(int disp, int64_t timestamp) {
    284     if (uint32_t(disp) < HWC_NUM_PHYSICAL_DISPLAY_TYPES) {
    285         {
    286             Mutex::Autolock _l(mLock);
    287 
    288             // There have been reports of HWCs that signal several vsync events
    289             // with the same timestamp when turning the display off and on. This
    290             // is a bug in the HWC implementation, but filter the extra events
    291             // out here so they don't cause havoc downstream.
    292             if (timestamp == mLastHwVSync[disp]) {
    293                 ALOGW("Ignoring duplicate VSYNC event from HWC (t=%" PRId64 ")",
    294                         timestamp);
    295                 return;
    296             }
    297 
    298             mLastHwVSync[disp] = timestamp;
    299         }
    300 
    301         char tag[16];
    302         snprintf(tag, sizeof(tag), "HW_VSYNC_%1u", disp);
    303         ATRACE_INT(tag, ++mVSyncCounts[disp] & 1);
    304 
    305         mEventHandler.onVSyncReceived(disp, timestamp);
    306     }
    307 }
    308 
    309 void HWComposer::hotplug(int disp, int connected) {
    310     if (disp >= VIRTUAL_DISPLAY_ID_BASE) {
    311         ALOGE("hotplug event received for invalid display: disp=%d connected=%d",
    312                 disp, connected);
    313         return;
    314     }
    315     queryDisplayProperties(disp);
    316     // Do not teardown or recreate the primary display
    317     if (disp != HWC_DISPLAY_PRIMARY) {
    318         mEventHandler.onHotplugReceived(disp, bool(connected));
    319     }
    320 }
    321 
    322 static float getDefaultDensity(uint32_t width, uint32_t height) {
    323     // Default density is based on TVs: 1080p displays get XHIGH density,
    324     // lower-resolution displays get TV density. Maybe eventually we'll need
    325     // to update it for 4K displays, though hopefully those just report
    326     // accurate DPI information to begin with. This is also used for virtual
    327     // displays and even primary displays with older hwcomposers, so be
    328     // careful about orientation.
    329 
    330     uint32_t h = width < height ? width : height;
    331     if (h >= 1080) return ACONFIGURATION_DENSITY_XHIGH;
    332     else           return ACONFIGURATION_DENSITY_TV;
    333 }
    334 
    335 static const uint32_t DISPLAY_ATTRIBUTES[] = {
    336     HWC_DISPLAY_VSYNC_PERIOD,
    337     HWC_DISPLAY_WIDTH,
    338     HWC_DISPLAY_HEIGHT,
    339     HWC_DISPLAY_DPI_X,
    340     HWC_DISPLAY_DPI_Y,
    341     HWC_DISPLAY_COLOR_TRANSFORM,
    342     HWC_DISPLAY_NO_ATTRIBUTE,
    343 };
    344 #define NUM_DISPLAY_ATTRIBUTES (sizeof(DISPLAY_ATTRIBUTES) / sizeof(DISPLAY_ATTRIBUTES)[0])
    345 
    346 static const uint32_t PRE_HWC15_DISPLAY_ATTRIBUTES[] = {
    347     HWC_DISPLAY_VSYNC_PERIOD,
    348     HWC_DISPLAY_WIDTH,
    349     HWC_DISPLAY_HEIGHT,
    350     HWC_DISPLAY_DPI_X,
    351     HWC_DISPLAY_DPI_Y,
    352     HWC_DISPLAY_NO_ATTRIBUTE,
    353 };
    354 
    355 status_t HWComposer::queryDisplayProperties(int disp) {
    356 
    357     LOG_ALWAYS_FATAL_IF(!mHwc || !hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
    358 
    359     // use zero as default value for unspecified attributes
    360     int32_t values[NUM_DISPLAY_ATTRIBUTES - 1];
    361     memset(values, 0, sizeof(values));
    362 
    363     const size_t MAX_NUM_CONFIGS = 128;
    364     uint32_t configs[MAX_NUM_CONFIGS] = {0};
    365     size_t numConfigs = MAX_NUM_CONFIGS;
    366     status_t err = mHwc->getDisplayConfigs(mHwc, disp, configs, &numConfigs);
    367     if (err != NO_ERROR) {
    368         // this can happen if an unpluggable display is not connected
    369         mDisplayData[disp].connected = false;
    370         return err;
    371     }
    372 
    373     mDisplayData[disp].currentConfig = 0;
    374     for (size_t c = 0; c < numConfigs; ++c) {
    375         err = mHwc->getDisplayAttributes(mHwc, disp, configs[c],
    376                 DISPLAY_ATTRIBUTES, values);
    377         // If this is a pre-1.5 HWC, it may not know about color transform, so
    378         // try again with a smaller set of attributes
    379         if (err != NO_ERROR) {
    380             err = mHwc->getDisplayAttributes(mHwc, disp, configs[c],
    381                     PRE_HWC15_DISPLAY_ATTRIBUTES, values);
    382         }
    383         if (err != NO_ERROR) {
    384             // we can't get this display's info. turn it off.
    385             mDisplayData[disp].connected = false;
    386             return err;
    387         }
    388 
    389         DisplayConfig config = DisplayConfig();
    390         for (size_t i = 0; i < NUM_DISPLAY_ATTRIBUTES - 1; i++) {
    391             switch (DISPLAY_ATTRIBUTES[i]) {
    392                 case HWC_DISPLAY_VSYNC_PERIOD:
    393                     config.refresh = nsecs_t(values[i]);
    394                     break;
    395                 case HWC_DISPLAY_WIDTH:
    396                     config.width = values[i];
    397                     break;
    398                 case HWC_DISPLAY_HEIGHT:
    399                     config.height = values[i];
    400                     break;
    401                 case HWC_DISPLAY_DPI_X:
    402                     config.xdpi = values[i] / 1000.0f;
    403                     break;
    404                 case HWC_DISPLAY_DPI_Y:
    405                     config.ydpi = values[i] / 1000.0f;
    406                     break;
    407                 case HWC_DISPLAY_COLOR_TRANSFORM:
    408                     config.colorMode = static_cast<android_color_mode_t>(values[i]);
    409                     break;
    410                 default:
    411                     ALOG_ASSERT(false, "unknown display attribute[%zu] %#x",
    412                             i, DISPLAY_ATTRIBUTES[i]);
    413                     break;
    414             }
    415         }
    416 
    417         if (config.xdpi == 0.0f || config.ydpi == 0.0f) {
    418             float dpi = getDefaultDensity(config.width, config.height);
    419             config.xdpi = dpi;
    420             config.ydpi = dpi;
    421         }
    422 
    423         mDisplayData[disp].configs.push_back(config);
    424     }
    425 
    426     // FIXME: what should we set the format to?
    427     mDisplayData[disp].format = HAL_PIXEL_FORMAT_RGBA_8888;
    428     mDisplayData[disp].connected = true;
    429     return NO_ERROR;
    430 }
    431 
    432 status_t HWComposer::setVirtualDisplayProperties(int32_t id,
    433         uint32_t w, uint32_t h, uint32_t format) {
    434     if (id < VIRTUAL_DISPLAY_ID_BASE || id >= int32_t(mNumDisplays) ||
    435             !mAllocatedDisplayIDs.hasBit(id)) {
    436         return BAD_INDEX;
    437     }
    438     size_t configId = mDisplayData[id].currentConfig;
    439     mDisplayData[id].format = format;
    440     DisplayConfig& config = mDisplayData[id].configs.editItemAt(configId);
    441     config.width = w;
    442     config.height = h;
    443     config.xdpi = config.ydpi = getDefaultDensity(w, h);
    444     return NO_ERROR;
    445 }
    446 
    447 int32_t HWComposer::allocateDisplayId() {
    448     if (mAllocatedDisplayIDs.count() >= mNumDisplays) {
    449         return NO_MEMORY;
    450     }
    451     int32_t id = mAllocatedDisplayIDs.firstUnmarkedBit();
    452     mAllocatedDisplayIDs.markBit(id);
    453     mDisplayData[id].connected = true;
    454     mDisplayData[id].configs.resize(1);
    455     mDisplayData[id].currentConfig = 0;
    456     return id;
    457 }
    458 
    459 status_t HWComposer::freeDisplayId(int32_t id) {
    460     if (id < NUM_BUILTIN_DISPLAYS) {
    461         // cannot free the reserved IDs
    462         return BAD_VALUE;
    463     }
    464     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
    465         return BAD_INDEX;
    466     }
    467     mAllocatedDisplayIDs.clearBit(id);
    468     mDisplayData[id].connected = false;
    469     return NO_ERROR;
    470 }
    471 
    472 nsecs_t HWComposer::getRefreshTimestamp(int disp) const {
    473     // this returns the last refresh timestamp.
    474     // if the last one is not available, we estimate it based on
    475     // the refresh period and whatever closest timestamp we have.
    476     Mutex::Autolock _l(mLock);
    477     nsecs_t now = systemTime(CLOCK_MONOTONIC);
    478     size_t configId = mDisplayData[disp].currentConfig;
    479     return now - ((now - mLastHwVSync[disp]) %
    480             mDisplayData[disp].configs[configId].refresh);
    481 }
    482 
    483 sp<Fence> HWComposer::getDisplayFence(int disp) const {
    484     return mDisplayData[disp].lastDisplayFence;
    485 }
    486 
    487 uint32_t HWComposer::getFormat(int disp) const {
    488     if (static_cast<uint32_t>(disp) >= MAX_HWC_DISPLAYS || !mAllocatedDisplayIDs.hasBit(disp)) {
    489         return HAL_PIXEL_FORMAT_RGBA_8888;
    490     } else {
    491         return mDisplayData[disp].format;
    492     }
    493 }
    494 
    495 bool HWComposer::isConnected(int disp) const {
    496     return mDisplayData[disp].connected;
    497 }
    498 
    499 uint32_t HWComposer::getWidth(int disp) const {
    500     size_t currentConfig = mDisplayData[disp].currentConfig;
    501     return mDisplayData[disp].configs[currentConfig].width;
    502 }
    503 
    504 uint32_t HWComposer::getHeight(int disp) const {
    505     size_t currentConfig = mDisplayData[disp].currentConfig;
    506     return mDisplayData[disp].configs[currentConfig].height;
    507 }
    508 
    509 float HWComposer::getDpiX(int disp) const {
    510     size_t currentConfig = mDisplayData[disp].currentConfig;
    511     return mDisplayData[disp].configs[currentConfig].xdpi;
    512 }
    513 
    514 float HWComposer::getDpiY(int disp) const {
    515     size_t currentConfig = mDisplayData[disp].currentConfig;
    516     return mDisplayData[disp].configs[currentConfig].ydpi;
    517 }
    518 
    519 nsecs_t HWComposer::getRefreshPeriod(int disp) const {
    520     size_t currentConfig = mDisplayData[disp].currentConfig;
    521     return mDisplayData[disp].configs[currentConfig].refresh;
    522 }
    523 
    524 android_color_mode_t HWComposer::getColorMode(int disp) const {
    525     size_t currentConfig = mDisplayData[disp].currentConfig;
    526     return mDisplayData[disp].configs[currentConfig].colorMode;
    527 }
    528 
    529 const Vector<HWComposer::DisplayConfig>& HWComposer::getConfigs(int disp) const {
    530     return mDisplayData[disp].configs;
    531 }
    532 
    533 size_t HWComposer::getCurrentConfig(int disp) const {
    534     return mDisplayData[disp].currentConfig;
    535 }
    536 
    537 void HWComposer::eventControl(int disp, int event, int enabled) {
    538     if (uint32_t(disp)>31 || !mAllocatedDisplayIDs.hasBit(disp)) {
    539         ALOGD("eventControl ignoring event %d on unallocated disp %d (en=%d)",
    540               event, disp, enabled);
    541         return;
    542     }
    543     if (event != EVENT_VSYNC) {
    544         ALOGW("eventControl got unexpected event %d (disp=%d en=%d)",
    545               event, disp, enabled);
    546         return;
    547     }
    548     status_t err = NO_ERROR;
    549     if (mHwc && !mDebugForceFakeVSync) {
    550         // NOTE: we use our own internal lock here because we have to call
    551         // into the HWC with the lock held, and we want to make sure
    552         // that even if HWC blocks (which it shouldn't), it won't
    553         // affect other threads.
    554         Mutex::Autolock _l(mEventControlLock);
    555         const int32_t eventBit = 1UL << event;
    556         const int32_t newValue = enabled ? eventBit : 0;
    557         const int32_t oldValue = mDisplayData[disp].events & eventBit;
    558         if (newValue != oldValue) {
    559             ATRACE_CALL();
    560             err = mHwc->eventControl(mHwc, disp, event, enabled);
    561             if (!err) {
    562                 int32_t& events(mDisplayData[disp].events);
    563                 events = (events & ~eventBit) | newValue;
    564 
    565                 char tag[16];
    566                 snprintf(tag, sizeof(tag), "HW_VSYNC_ON_%1u", disp);
    567                 ATRACE_INT(tag, enabled);
    568             }
    569         }
    570         // error here should not happen -- not sure what we should
    571         // do if it does.
    572         ALOGE_IF(err, "eventControl(%d, %d) failed %s",
    573                 event, enabled, strerror(-err));
    574     }
    575 
    576     if (err == NO_ERROR && mVSyncThread != NULL) {
    577         mVSyncThread->setEnabled(enabled);
    578     }
    579 }
    580 
    581 status_t HWComposer::createWorkList(int32_t id, size_t numLayers) {
    582     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
    583         return BAD_INDEX;
    584     }
    585 
    586     if (mHwc) {
    587         DisplayData& disp(mDisplayData[id]);
    588         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
    589             // we need space for the HWC_FRAMEBUFFER_TARGET
    590             numLayers++;
    591         }
    592         if (disp.capacity < numLayers || disp.list == NULL) {
    593             size_t size = sizeof(hwc_display_contents_1_t)
    594                     + numLayers * sizeof(hwc_layer_1_t);
    595             free(disp.list);
    596             disp.list = (hwc_display_contents_1_t*)malloc(size);
    597             disp.capacity = numLayers;
    598         }
    599         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
    600             disp.framebufferTarget = &disp.list->hwLayers[numLayers - 1];
    601             memset(disp.framebufferTarget, 0, sizeof(hwc_layer_1_t));
    602             const DisplayConfig& currentConfig =
    603                     disp.configs[disp.currentConfig];
    604             const hwc_rect_t r = { 0, 0,
    605                     (int) currentConfig.width, (int) currentConfig.height };
    606             disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
    607             disp.framebufferTarget->hints = 0;
    608             disp.framebufferTarget->flags = 0;
    609             disp.framebufferTarget->handle = disp.fbTargetHandle;
    610             disp.framebufferTarget->transform = 0;
    611             disp.framebufferTarget->blending = HWC_BLENDING_PREMULT;
    612             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
    613                 disp.framebufferTarget->sourceCropf.left = 0;
    614                 disp.framebufferTarget->sourceCropf.top = 0;
    615                 disp.framebufferTarget->sourceCropf.right =
    616                         currentConfig.width;
    617                 disp.framebufferTarget->sourceCropf.bottom =
    618                         currentConfig.height;
    619             } else {
    620                 disp.framebufferTarget->sourceCrop = r;
    621             }
    622             disp.framebufferTarget->displayFrame = r;
    623             disp.framebufferTarget->visibleRegionScreen.numRects = 1;
    624             disp.framebufferTarget->visibleRegionScreen.rects =
    625                 &disp.framebufferTarget->displayFrame;
    626             disp.framebufferTarget->acquireFenceFd = -1;
    627             disp.framebufferTarget->releaseFenceFd = -1;
    628             disp.framebufferTarget->planeAlpha = 0xFF;
    629         }
    630         disp.list->retireFenceFd = -1;
    631         disp.list->flags = HWC_GEOMETRY_CHANGED;
    632         disp.list->numHwLayers = numLayers;
    633     }
    634     return NO_ERROR;
    635 }
    636 
    637 status_t HWComposer::setFramebufferTarget(int32_t id,
    638         const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buf) {
    639     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
    640         return BAD_INDEX;
    641     }
    642     DisplayData& disp(mDisplayData[id]);
    643     if (!disp.framebufferTarget) {
    644         // this should never happen, but apparently eglCreateWindowSurface()
    645         // triggers a Surface::queueBuffer()  on some
    646         // devices (!?) -- log and ignore.
    647         ALOGE("HWComposer: framebufferTarget is null");
    648         return NO_ERROR;
    649     }
    650 
    651     int acquireFenceFd = -1;
    652     if (acquireFence->isValid()) {
    653         acquireFenceFd = acquireFence->dup();
    654     }
    655 
    656     // ALOGD("fbPost: handle=%p, fence=%d", buf->handle, acquireFenceFd);
    657     disp.fbTargetHandle = buf->handle;
    658     disp.framebufferTarget->handle = disp.fbTargetHandle;
    659     disp.framebufferTarget->acquireFenceFd = acquireFenceFd;
    660     return NO_ERROR;
    661 }
    662 
    663 status_t HWComposer::prepare() {
    664     Mutex::Autolock _l(mDisplayLock);
    665     for (size_t i=0 ; i<mNumDisplays ; i++) {
    666         DisplayData& disp(mDisplayData[i]);
    667         if (disp.framebufferTarget) {
    668             // make sure to reset the type to HWC_FRAMEBUFFER_TARGET
    669             // DO NOT reset the handle field to NULL, because it's possible
    670             // that we have nothing to redraw (eg: eglSwapBuffers() not called)
    671             // in which case, we should continue to use the same buffer.
    672             LOG_FATAL_IF(disp.list == NULL);
    673             disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
    674         }
    675         if (!disp.connected && disp.list != NULL) {
    676             ALOGW("WARNING: disp %zu: connected, non-null list, layers=%zu",
    677                   i, disp.list->numHwLayers);
    678         }
    679         mLists[i] = disp.list;
    680         if (mLists[i]) {
    681             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
    682                 mLists[i]->outbuf = disp.outbufHandle;
    683                 mLists[i]->outbufAcquireFenceFd = -1;
    684             } else if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
    685                 // garbage data to catch improper use
    686                 mLists[i]->dpy = (hwc_display_t)0xDEADBEEF;
    687                 mLists[i]->sur = (hwc_surface_t)0xDEADBEEF;
    688             } else {
    689                 mLists[i]->dpy = EGL_NO_DISPLAY;
    690                 mLists[i]->sur = EGL_NO_SURFACE;
    691             }
    692         }
    693     }
    694 
    695     int err = mHwc->prepare(mHwc, mNumDisplays, mLists);
    696     ALOGE_IF(err, "HWComposer: prepare failed (%s)", strerror(-err));
    697 
    698     if (err == NO_ERROR) {
    699         // here we're just making sure that "skip" layers are set
    700         // to HWC_FRAMEBUFFER and we're also counting how many layers
    701         // we have of each type.
    702         //
    703         // If there are no window layers, we treat the display has having FB
    704         // composition, because SurfaceFlinger will use GLES to draw the
    705         // wormhole region.
    706         for (size_t i=0 ; i<mNumDisplays ; i++) {
    707             DisplayData& disp(mDisplayData[i]);
    708             disp.hasFbComp = false;
    709             disp.hasOvComp = false;
    710             if (disp.list) {
    711                 for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
    712                     hwc_layer_1_t& l = disp.list->hwLayers[i];
    713 
    714                     //ALOGD("prepare: %d, type=%d, handle=%p",
    715                     //        i, l.compositionType, l.handle);
    716 
    717                     if (l.flags & HWC_SKIP_LAYER) {
    718                         l.compositionType = HWC_FRAMEBUFFER;
    719                     }
    720                     if (l.compositionType == HWC_FRAMEBUFFER) {
    721                         disp.hasFbComp = true;
    722                     }
    723                     if (l.compositionType == HWC_OVERLAY) {
    724                         disp.hasOvComp = true;
    725                     }
    726                     if (l.compositionType == HWC_CURSOR_OVERLAY) {
    727                         disp.hasOvComp = true;
    728                     }
    729                 }
    730                 if (disp.list->numHwLayers == (disp.framebufferTarget ? 1 : 0)) {
    731                     disp.hasFbComp = true;
    732                 }
    733             } else {
    734                 disp.hasFbComp = true;
    735             }
    736         }
    737     }
    738     return (status_t)err;
    739 }
    740 
    741 bool HWComposer::hasHwcComposition(int32_t id) const {
    742     if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
    743         return false;
    744     return mDisplayData[id].hasOvComp;
    745 }
    746 
    747 bool HWComposer::hasGlesComposition(int32_t id) const {
    748     if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
    749         return true;
    750     return mDisplayData[id].hasFbComp;
    751 }
    752 
    753 sp<Fence> HWComposer::getAndResetReleaseFence(int32_t id) {
    754     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
    755         return Fence::NO_FENCE;
    756 
    757     int fd = INVALID_OPERATION;
    758     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
    759         const DisplayData& disp(mDisplayData[id]);
    760         if (disp.framebufferTarget) {
    761             fd = disp.framebufferTarget->releaseFenceFd;
    762             disp.framebufferTarget->acquireFenceFd = -1;
    763             disp.framebufferTarget->releaseFenceFd = -1;
    764         }
    765     }
    766     return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
    767 }
    768 
    769 status_t HWComposer::commit() {
    770     int err = NO_ERROR;
    771     if (mHwc) {
    772         if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
    773             // On version 1.0, the OpenGL ES target surface is communicated
    774             // by the (dpy, sur) fields and we are guaranteed to have only
    775             // a single display.
    776             mLists[0]->dpy = eglGetCurrentDisplay();
    777             mLists[0]->sur = eglGetCurrentSurface(EGL_DRAW);
    778         }
    779 
    780         for (size_t i=VIRTUAL_DISPLAY_ID_BASE; i<mNumDisplays; i++) {
    781             DisplayData& disp(mDisplayData[i]);
    782             if (disp.outbufHandle) {
    783                 mLists[i]->outbuf = disp.outbufHandle;
    784                 mLists[i]->outbufAcquireFenceFd =
    785                         disp.outbufAcquireFence->dup();
    786             }
    787         }
    788 
    789         err = mHwc->set(mHwc, mNumDisplays, mLists);
    790 
    791         for (size_t i=0 ; i<mNumDisplays ; i++) {
    792             DisplayData& disp(mDisplayData[i]);
    793             disp.lastDisplayFence = disp.lastRetireFence;
    794             disp.lastRetireFence = Fence::NO_FENCE;
    795             if (disp.list) {
    796                 if (disp.list->retireFenceFd != -1) {
    797                     disp.lastRetireFence = new Fence(disp.list->retireFenceFd);
    798                     disp.list->retireFenceFd = -1;
    799                 }
    800                 disp.list->flags &= ~HWC_GEOMETRY_CHANGED;
    801             }
    802         }
    803     }
    804     return (status_t)err;
    805 }
    806 
    807 status_t HWComposer::setPowerMode(int disp, int mode) {
    808     LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
    809     if (mHwc) {
    810         if (mode == HWC_POWER_MODE_OFF) {
    811             eventControl(disp, HWC_EVENT_VSYNC, 0);
    812         }
    813         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
    814             return (status_t)mHwc->setPowerMode(mHwc, disp, mode);
    815         } else {
    816             return (status_t)mHwc->blank(mHwc, disp,
    817                     mode == HWC_POWER_MODE_OFF ? 1 : 0);
    818         }
    819     }
    820     return NO_ERROR;
    821 }
    822 
    823 status_t HWComposer::setActiveConfig(int disp, int mode) {
    824     LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
    825     DisplayData& dd(mDisplayData[disp]);
    826     dd.currentConfig = mode;
    827     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
    828         return (status_t)mHwc->setActiveConfig(mHwc, disp, mode);
    829     } else {
    830         LOG_FATAL_IF(mode != 0);
    831     }
    832     return NO_ERROR;
    833 }
    834 
    835 void HWComposer::disconnectDisplay(int disp) {
    836     LOG_ALWAYS_FATAL_IF(disp < 0 || disp == HWC_DISPLAY_PRIMARY);
    837     DisplayData& dd(mDisplayData[disp]);
    838     free(dd.list);
    839     dd.list = NULL;
    840     dd.framebufferTarget = NULL;    // points into dd.list
    841     dd.fbTargetHandle = NULL;
    842     dd.outbufHandle = NULL;
    843     dd.lastRetireFence = Fence::NO_FENCE;
    844     dd.lastDisplayFence = Fence::NO_FENCE;
    845     dd.outbufAcquireFence = Fence::NO_FENCE;
    846     // clear all the previous configs and repopulate when a new
    847     // device is added
    848     dd.configs.clear();
    849 }
    850 
    851 int HWComposer::getVisualID() const {
    852     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
    853         // FIXME: temporary hack until HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED
    854         // is supported by the implementation. we can only be in this case
    855         // if we have HWC 1.1
    856         return HAL_PIXEL_FORMAT_RGBA_8888;
    857         //return HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
    858     } else {
    859         return mFbDev->format;
    860     }
    861 }
    862 
    863 bool HWComposer::supportsFramebufferTarget() const {
    864     return (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
    865 }
    866 
    867 int HWComposer::fbPost(int32_t id,
    868         const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buffer) {
    869     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
    870         return setFramebufferTarget(id, acquireFence, buffer);
    871     } else {
    872         acquireFence->waitForever("HWComposer::fbPost");
    873         return mFbDev->post(mFbDev, buffer->handle);
    874     }
    875 }
    876 
    877 int HWComposer::fbCompositionComplete() {
    878     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
    879         return NO_ERROR;
    880 
    881     if (mFbDev->compositionComplete) {
    882         return mFbDev->compositionComplete(mFbDev);
    883     } else {
    884         return INVALID_OPERATION;
    885     }
    886 }
    887 
    888 void HWComposer::fbDump(String8& result) {
    889     if (mFbDev && mFbDev->common.version >= 1 && mFbDev->dump) {
    890         const size_t SIZE = 4096;
    891         char buffer[SIZE];
    892         mFbDev->dump(mFbDev, buffer, SIZE);
    893         result.append(buffer);
    894     }
    895 }
    896 
    897 status_t HWComposer::setOutputBuffer(int32_t id, const sp<Fence>& acquireFence,
    898         const sp<GraphicBuffer>& buf) {
    899     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
    900         return BAD_INDEX;
    901     if (id < VIRTUAL_DISPLAY_ID_BASE)
    902         return INVALID_OPERATION;
    903 
    904     DisplayData& disp(mDisplayData[id]);
    905     disp.outbufHandle = buf->handle;
    906     disp.outbufAcquireFence = acquireFence;
    907     return NO_ERROR;
    908 }
    909 
    910 sp<Fence> HWComposer::getLastRetireFence(int32_t id) const {
    911     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
    912         return Fence::NO_FENCE;
    913     return mDisplayData[id].lastRetireFence;
    914 }
    915 
    916 status_t HWComposer::setCursorPositionAsync(int32_t id, const Rect& pos)
    917 {
    918     if (mHwc->setCursorPositionAsync) {
    919         return (status_t)mHwc->setCursorPositionAsync(mHwc, id, pos.left, pos.top);
    920     }
    921     else {
    922         return NO_ERROR;
    923     }
    924 }
    925 
    926 /*
    927  * Helper template to implement a concrete HWCLayer
    928  * This holds the pointer to the concrete hwc layer type
    929  * and implements the "iterable" side of HWCLayer.
    930  */
    931 template<typename CONCRETE, typename HWCTYPE>
    932 class Iterable : public HWComposer::HWCLayer {
    933 protected:
    934     HWCTYPE* const mLayerList;
    935     HWCTYPE* mCurrentLayer;
    936     Iterable(HWCTYPE* layer) : mLayerList(layer), mCurrentLayer(layer),
    937             mIndex(0) { }
    938     inline HWCTYPE const * getLayer() const { return mCurrentLayer; }
    939     inline HWCTYPE* getLayer() { return mCurrentLayer; }
    940     virtual ~Iterable() { }
    941     size_t mIndex;
    942 private:
    943     // returns a copy of ourselves
    944     virtual HWComposer::HWCLayer* dup() {
    945         return new CONCRETE( static_cast<const CONCRETE&>(*this) );
    946     }
    947     virtual status_t setLayer(size_t index) {
    948         mIndex = index;
    949         mCurrentLayer = &mLayerList[index];
    950         return NO_ERROR;
    951     }
    952 };
    953 
    954 /*
    955  * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_1_0.
    956  * This implements the HWCLayer side of HWCIterableLayer.
    957  */
    958 class HWCLayerVersion1 : public Iterable<HWCLayerVersion1, hwc_layer_1_t> {
    959     struct hwc_composer_device_1* mHwc;
    960 public:
    961     HWCLayerVersion1(struct hwc_composer_device_1* hwc, hwc_layer_1_t* layer,
    962             Vector<Region>* visibleRegions,
    963             Vector<Region>* surfaceDamageRegions)
    964         : Iterable<HWCLayerVersion1, hwc_layer_1_t>(layer), mHwc(hwc),
    965           mVisibleRegions(visibleRegions),
    966           mSurfaceDamageRegions(surfaceDamageRegions) {}
    967 
    968     virtual int32_t getCompositionType() const {
    969         return getLayer()->compositionType;
    970     }
    971     virtual uint32_t getHints() const {
    972         return getLayer()->hints;
    973     }
    974     virtual sp<Fence> getAndResetReleaseFence() {
    975         int fd = getLayer()->releaseFenceFd;
    976         getLayer()->releaseFenceFd = -1;
    977         return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
    978     }
    979     virtual void setAcquireFenceFd(int fenceFd) {
    980         getLayer()->acquireFenceFd = fenceFd;
    981     }
    982     virtual void setPerFrameDefaultState() {
    983         //getLayer()->compositionType = HWC_FRAMEBUFFER;
    984     }
    985     virtual void setPlaneAlpha(uint8_t alpha) {
    986         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_2)) {
    987             getLayer()->planeAlpha = alpha;
    988         } else {
    989             if (alpha < 0xFF) {
    990                 getLayer()->flags |= HWC_SKIP_LAYER;
    991             }
    992         }
    993     }
    994     virtual void setDefaultState() {
    995         hwc_layer_1_t* const l = getLayer();
    996         l->compositionType = HWC_FRAMEBUFFER;
    997         l->hints = 0;
    998         l->flags = HWC_SKIP_LAYER;
    999         l->handle = 0;
   1000         l->transform = 0;
   1001         l->blending = HWC_BLENDING_NONE;
   1002         l->visibleRegionScreen.numRects = 0;
   1003         l->visibleRegionScreen.rects = NULL;
   1004         l->acquireFenceFd = -1;
   1005         l->releaseFenceFd = -1;
   1006         l->planeAlpha = 0xFF;
   1007     }
   1008     virtual void setSkip(bool skip) {
   1009         if (skip) {
   1010             getLayer()->flags |= HWC_SKIP_LAYER;
   1011         } else {
   1012             getLayer()->flags &= ~HWC_SKIP_LAYER;
   1013         }
   1014     }
   1015     virtual void setIsCursorLayerHint(bool isCursor) {
   1016         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
   1017             if (isCursor) {
   1018                 getLayer()->flags |= HWC_IS_CURSOR_LAYER;
   1019             }
   1020             else {
   1021                 getLayer()->flags &= ~HWC_IS_CURSOR_LAYER;
   1022             }
   1023         }
   1024     }
   1025     virtual void setBlending(uint32_t blending) {
   1026         getLayer()->blending = blending;
   1027     }
   1028     virtual void setTransform(uint32_t transform) {
   1029         getLayer()->transform = transform;
   1030     }
   1031     virtual void setFrame(const Rect& frame) {
   1032         getLayer()->displayFrame = reinterpret_cast<hwc_rect_t const&>(frame);
   1033     }
   1034     virtual void setCrop(const FloatRect& crop) {
   1035         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
   1036             getLayer()->sourceCropf = reinterpret_cast<hwc_frect_t const&>(crop);
   1037         } else {
   1038             /*
   1039              * Since h/w composer didn't support a flot crop rect before version 1.3,
   1040              * using integer coordinates instead produces a different output from the GL code in
   1041              * Layer::drawWithOpenGL(). The difference can be large if the buffer crop to
   1042              * window size ratio is large and a window crop is defined
   1043              * (i.e.: if we scale the buffer a lot and we also crop it with a window crop).
   1044              */
   1045             hwc_rect_t& r = getLayer()->sourceCrop;
   1046             r.left  = int(ceilf(crop.left));
   1047             r.top   = int(ceilf(crop.top));
   1048             r.right = int(floorf(crop.right));
   1049             r.bottom= int(floorf(crop.bottom));
   1050         }
   1051     }
   1052     virtual void setVisibleRegionScreen(const Region& reg) {
   1053         hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
   1054         mVisibleRegions->editItemAt(mIndex) = reg;
   1055         visibleRegion.rects = reinterpret_cast<hwc_rect_t const *>(
   1056                 mVisibleRegions->itemAt(mIndex).getArray(
   1057                 &visibleRegion.numRects));
   1058     }
   1059     virtual void setSurfaceDamage(const Region& reg) {
   1060         if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_5)) {
   1061             return;
   1062         }
   1063         hwc_region_t& surfaceDamage = getLayer()->surfaceDamage;
   1064         // We encode default full-screen damage as INVALID_RECT upstream, but as
   1065         // 0 rects for HWComposer
   1066         if (reg.isRect() && reg.getBounds() == Rect::INVALID_RECT) {
   1067             surfaceDamage.numRects = 0;
   1068             surfaceDamage.rects = NULL;
   1069             return;
   1070         }
   1071         mSurfaceDamageRegions->editItemAt(mIndex) = reg;
   1072         surfaceDamage.rects = reinterpret_cast<hwc_rect_t const *>(
   1073                 mSurfaceDamageRegions->itemAt(mIndex).getArray(
   1074                 &surfaceDamage.numRects));
   1075     }
   1076     virtual void setSidebandStream(const sp<NativeHandle>& stream) {
   1077         ALOG_ASSERT(stream->handle() != NULL);
   1078         getLayer()->compositionType = HWC_SIDEBAND;
   1079         getLayer()->sidebandStream = stream->handle();
   1080     }
   1081     virtual void setBuffer(const sp<GraphicBuffer>& buffer) {
   1082         if (buffer == 0 || buffer->handle == 0) {
   1083             getLayer()->compositionType = HWC_FRAMEBUFFER;
   1084             getLayer()->flags |= HWC_SKIP_LAYER;
   1085             getLayer()->handle = 0;
   1086         } else {
   1087             if (getLayer()->compositionType == HWC_SIDEBAND) {
   1088                 // If this was a sideband layer but the stream was removed, reset
   1089                 // it to FRAMEBUFFER. The HWC can change it to OVERLAY in prepare.
   1090                 getLayer()->compositionType = HWC_FRAMEBUFFER;
   1091             }
   1092             getLayer()->handle = buffer->handle;
   1093         }
   1094     }
   1095     virtual void onDisplayed() {
   1096         getLayer()->acquireFenceFd = -1;
   1097     }
   1098 
   1099 protected:
   1100     // Pointers to the vectors of Region backing-memory held in DisplayData.
   1101     // Only the Region at mIndex corresponds to this Layer.
   1102     Vector<Region>* mVisibleRegions;
   1103     Vector<Region>* mSurfaceDamageRegions;
   1104 };
   1105 
   1106 /*
   1107  * returns an iterator initialized at a given index in the layer list
   1108  */
   1109 HWComposer::LayerListIterator HWComposer::getLayerIterator(int32_t id, size_t index) {
   1110     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
   1111         return LayerListIterator();
   1112     }
   1113     DisplayData& disp(mDisplayData[id]);
   1114     if (!mHwc || !disp.list || index > disp.list->numHwLayers) {
   1115         return LayerListIterator();
   1116     }
   1117     if (disp.visibleRegions.size() < disp.list->numHwLayers) {
   1118         disp.visibleRegions.resize(disp.list->numHwLayers);
   1119     }
   1120     if (disp.surfaceDamageRegions.size() < disp.list->numHwLayers) {
   1121         disp.surfaceDamageRegions.resize(disp.list->numHwLayers);
   1122     }
   1123     return LayerListIterator(new HWCLayerVersion1(mHwc, disp.list->hwLayers,
   1124             &disp.visibleRegions, &disp.surfaceDamageRegions), index);
   1125 }
   1126 
   1127 /*
   1128  * returns an iterator on the beginning of the layer list
   1129  */
   1130 HWComposer::LayerListIterator HWComposer::begin(int32_t id) {
   1131     return getLayerIterator(id, 0);
   1132 }
   1133 
   1134 /*
   1135  * returns an iterator on the end of the layer list
   1136  */
   1137 HWComposer::LayerListIterator HWComposer::end(int32_t id) {
   1138     size_t numLayers = 0;
   1139     if (uint32_t(id) <= 31 && mAllocatedDisplayIDs.hasBit(id)) {
   1140         const DisplayData& disp(mDisplayData[id]);
   1141         if (mHwc && disp.list) {
   1142             numLayers = disp.list->numHwLayers;
   1143             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
   1144                 // with HWC 1.1, the last layer is always the HWC_FRAMEBUFFER_TARGET,
   1145                 // which we ignore when iterating through the layer list.
   1146                 ALOGE_IF(!numLayers, "mDisplayData[%d].list->numHwLayers is 0", id);
   1147                 if (numLayers) {
   1148                     numLayers--;
   1149                 }
   1150             }
   1151         }
   1152     }
   1153     return getLayerIterator(id, numLayers);
   1154 }
   1155 
   1156 // Converts a PixelFormat to a human-readable string.  Max 11 chars.
   1157 // (Could use a table of prefab String8 objects.)
   1158 static String8 getFormatStr(PixelFormat format) {
   1159     switch (format) {
   1160     case PIXEL_FORMAT_RGBA_8888:    return String8("RGBA_8888");
   1161     case PIXEL_FORMAT_RGBX_8888:    return String8("RGBx_8888");
   1162     case PIXEL_FORMAT_RGB_888:      return String8("RGB_888");
   1163     case PIXEL_FORMAT_RGB_565:      return String8("RGB_565");
   1164     case PIXEL_FORMAT_BGRA_8888:    return String8("BGRA_8888");
   1165     case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
   1166                                     return String8("ImplDef");
   1167     default:
   1168         String8 result;
   1169         result.appendFormat("? %08x", format);
   1170         return result;
   1171     }
   1172 }
   1173 
   1174 void HWComposer::dump(String8& result) const {
   1175     Mutex::Autolock _l(mDisplayLock);
   1176     if (mHwc) {
   1177         result.appendFormat("Hardware Composer state (version %08x):\n", hwcApiVersion(mHwc));
   1178         result.appendFormat("  mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync);
   1179         for (size_t i=0 ; i<mNumDisplays ; i++) {
   1180             const DisplayData& disp(mDisplayData[i]);
   1181             if (!disp.connected)
   1182                 continue;
   1183 
   1184             const Vector< sp<Layer> >& visibleLayersSortedByZ =
   1185                     mFlinger->getLayerSortedByZForHwcDisplay(i);
   1186 
   1187 
   1188             result.appendFormat("  Display[%zd] configurations (* current):\n", i);
   1189             for (size_t c = 0; c < disp.configs.size(); ++c) {
   1190                 const DisplayConfig& config(disp.configs[c]);
   1191                 result.appendFormat("    %s%zd: %ux%u, xdpi=%f, ydpi=%f"
   1192                         ", refresh=%" PRId64 ", colorMode=%d\n",
   1193                         c == disp.currentConfig ? "* " : "", c,
   1194                         config.width, config.height, config.xdpi, config.ydpi,
   1195                         config.refresh, config.colorMode);
   1196             }
   1197 
   1198             if (disp.list) {
   1199                 result.appendFormat(
   1200                         "  numHwLayers=%zu, flags=%08x\n",
   1201                         disp.list->numHwLayers, disp.list->flags);
   1202 
   1203                 result.append(
   1204                         "    type   |  handle  | hint | flag | tr | blnd |   format    |     source crop (l,t,r,b)      |          frame         | name \n"
   1205                         "-----------+----------+------+------+----+------+-------------+--------------------------------+------------------------+------\n");
   1206                 //      " _________ | ________ | ____ | ____ | __ | ____ | ___________ |_____._,_____._,_____._,_____._ |_____,_____,_____,_____ | ___...
   1207                 for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
   1208                     const hwc_layer_1_t&l = disp.list->hwLayers[i];
   1209                     int32_t format = -1;
   1210                     String8 name("unknown");
   1211 
   1212                     if (i < visibleLayersSortedByZ.size()) {
   1213                         const sp<Layer>& layer(visibleLayersSortedByZ[i]);
   1214                         const sp<GraphicBuffer>& buffer(
   1215                                 layer->getActiveBuffer());
   1216                         if (buffer != NULL) {
   1217                             format = buffer->getPixelFormat();
   1218                         }
   1219                         name = layer->getName();
   1220                     }
   1221 
   1222                     int type = l.compositionType;
   1223                     if (type == HWC_FRAMEBUFFER_TARGET) {
   1224                         name = "HWC_FRAMEBUFFER_TARGET";
   1225                         format = disp.format;
   1226                     }
   1227 
   1228                     static char const* compositionTypeName[] = {
   1229                             "GLES",
   1230                             "HWC",
   1231                             "BKGND",
   1232                             "FB TARGET",
   1233                             "SIDEBAND",
   1234                             "HWC_CURSOR",
   1235                             "UNKNOWN"};
   1236                     if (type >= NELEM(compositionTypeName))
   1237                         type = NELEM(compositionTypeName) - 1;
   1238 
   1239                     String8 formatStr = getFormatStr(format);
   1240                     if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
   1241                         result.appendFormat(
   1242                                 " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7.1f,%7.1f,%7.1f,%7.1f |%5d,%5d,%5d,%5d | %s\n",
   1243                                         compositionTypeName[type],
   1244                                         intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
   1245                                         l.sourceCropf.left, l.sourceCropf.top, l.sourceCropf.right, l.sourceCropf.bottom,
   1246                                         l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
   1247                                         name.string());
   1248                     } else {
   1249                         result.appendFormat(
   1250                                 " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7d,%7d,%7d,%7d |%5d,%5d,%5d,%5d | %s\n",
   1251                                         compositionTypeName[type],
   1252                                         intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
   1253                                         l.sourceCrop.left, l.sourceCrop.top, l.sourceCrop.right, l.sourceCrop.bottom,
   1254                                         l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
   1255                                         name.string());
   1256                     }
   1257                 }
   1258             }
   1259         }
   1260     }
   1261 
   1262     if (mHwc && mHwc->dump) {
   1263         const size_t SIZE = 4096;
   1264         char buffer[SIZE];
   1265         mHwc->dump(mHwc, buffer, SIZE);
   1266         result.append(buffer);
   1267     }
   1268 }
   1269 
   1270 // ---------------------------------------------------------------------------
   1271 
   1272 HWComposer::VSyncThread::VSyncThread(HWComposer& hwc)
   1273     : mHwc(hwc), mEnabled(false),
   1274       mNextFakeVSync(0),
   1275       mRefreshPeriod(hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY))
   1276 {
   1277 }
   1278 
   1279 void HWComposer::VSyncThread::setEnabled(bool enabled) {
   1280     Mutex::Autolock _l(mLock);
   1281     if (mEnabled != enabled) {
   1282         mEnabled = enabled;
   1283         mCondition.signal();
   1284     }
   1285 }
   1286 
   1287 void HWComposer::VSyncThread::onFirstRef() {
   1288     run("VSyncThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
   1289 }
   1290 
   1291 bool HWComposer::VSyncThread::threadLoop() {
   1292     { // scope for lock
   1293         Mutex::Autolock _l(mLock);
   1294         while (!mEnabled) {
   1295             mCondition.wait(mLock);
   1296         }
   1297     }
   1298 
   1299     const nsecs_t period = mRefreshPeriod;
   1300     const nsecs_t now = systemTime(CLOCK_MONOTONIC);
   1301     nsecs_t next_vsync = mNextFakeVSync;
   1302     nsecs_t sleep = next_vsync - now;
   1303     if (sleep < 0) {
   1304         // we missed, find where the next vsync should be
   1305         sleep = (period - ((now - next_vsync) % period));
   1306         next_vsync = now + sleep;
   1307     }
   1308     mNextFakeVSync = next_vsync + period;
   1309 
   1310     struct timespec spec;
   1311     spec.tv_sec  = next_vsync / 1000000000;
   1312     spec.tv_nsec = next_vsync % 1000000000;
   1313 
   1314     int err;
   1315     do {
   1316         err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
   1317     } while (err<0 && errno == EINTR);
   1318 
   1319     if (err == 0) {
   1320         mHwc.mEventHandler.onVSyncReceived(0, next_vsync);
   1321     }
   1322 
   1323     return true;
   1324 }
   1325 
   1326 HWComposer::DisplayData::DisplayData()
   1327 :   configs(),
   1328     currentConfig(0),
   1329     format(HAL_PIXEL_FORMAT_RGBA_8888),
   1330     connected(false),
   1331     hasFbComp(false), hasOvComp(false),
   1332     capacity(0), list(NULL),
   1333     framebufferTarget(NULL), fbTargetHandle(0),
   1334     lastRetireFence(Fence::NO_FENCE), lastDisplayFence(Fence::NO_FENCE),
   1335     outbufHandle(NULL), outbufAcquireFence(Fence::NO_FENCE),
   1336     events(0)
   1337 {}
   1338 
   1339 HWComposer::DisplayData::~DisplayData() {
   1340     free(list);
   1341 }
   1342 
   1343 // ---------------------------------------------------------------------------
   1344 }; // namespace android
   1345