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