HWComposer.cpp revision 258ee43fbcbc752cb08c134a12c08d5d99c4a866
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[%d] %#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        }
529        // error here should not happen -- not sure what we should
530        // do if it does.
531        ALOGE_IF(err, "eventControl(%d, %d) failed %s",
532                event, enabled, strerror(-err));
533    }
534
535    if (err == NO_ERROR && mVSyncThread != NULL) {
536        mVSyncThread->setEnabled(enabled);
537    }
538}
539
540status_t HWComposer::createWorkList(int32_t id, size_t numLayers) {
541    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
542        return BAD_INDEX;
543    }
544
545    if (mHwc) {
546        DisplayData& disp(mDisplayData[id]);
547        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
548            // we need space for the HWC_FRAMEBUFFER_TARGET
549            numLayers++;
550        }
551        if (disp.capacity < numLayers || disp.list == NULL) {
552            size_t size = sizeof(hwc_display_contents_1_t)
553                    + numLayers * sizeof(hwc_layer_1_t);
554            free(disp.list);
555            disp.list = (hwc_display_contents_1_t*)malloc(size);
556            disp.capacity = numLayers;
557        }
558        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
559            disp.framebufferTarget = &disp.list->hwLayers[numLayers - 1];
560            memset(disp.framebufferTarget, 0, sizeof(hwc_layer_1_t));
561            const DisplayConfig& currentConfig =
562                    disp.configs[disp.currentConfig];
563            const hwc_rect_t r = { 0, 0,
564                    (int) currentConfig.width, (int) currentConfig.height };
565            disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
566            disp.framebufferTarget->hints = 0;
567            disp.framebufferTarget->flags = 0;
568            disp.framebufferTarget->handle = disp.fbTargetHandle;
569            disp.framebufferTarget->transform = 0;
570            disp.framebufferTarget->blending = HWC_BLENDING_PREMULT;
571            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
572                disp.framebufferTarget->sourceCropf.left = 0;
573                disp.framebufferTarget->sourceCropf.top = 0;
574                disp.framebufferTarget->sourceCropf.right =
575                        currentConfig.width;
576                disp.framebufferTarget->sourceCropf.bottom =
577                        currentConfig.height;
578            } else {
579                disp.framebufferTarget->sourceCrop = r;
580            }
581            disp.framebufferTarget->displayFrame = r;
582            disp.framebufferTarget->visibleRegionScreen.numRects = 1;
583            disp.framebufferTarget->visibleRegionScreen.rects =
584                &disp.framebufferTarget->displayFrame;
585            disp.framebufferTarget->acquireFenceFd = -1;
586            disp.framebufferTarget->releaseFenceFd = -1;
587            disp.framebufferTarget->planeAlpha = 0xFF;
588        }
589        disp.list->retireFenceFd = -1;
590        disp.list->flags = HWC_GEOMETRY_CHANGED;
591        disp.list->numHwLayers = numLayers;
592    }
593    return NO_ERROR;
594}
595
596status_t HWComposer::setFramebufferTarget(int32_t id,
597        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buf) {
598    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
599        return BAD_INDEX;
600    }
601    DisplayData& disp(mDisplayData[id]);
602    if (!disp.framebufferTarget) {
603        // this should never happen, but apparently eglCreateWindowSurface()
604        // triggers a Surface::queueBuffer()  on some
605        // devices (!?) -- log and ignore.
606        ALOGE("HWComposer: framebufferTarget is null");
607        return NO_ERROR;
608    }
609
610    int acquireFenceFd = -1;
611    if (acquireFence->isValid()) {
612        acquireFenceFd = acquireFence->dup();
613    }
614
615    // ALOGD("fbPost: handle=%p, fence=%d", buf->handle, acquireFenceFd);
616    disp.fbTargetHandle = buf->handle;
617    disp.framebufferTarget->handle = disp.fbTargetHandle;
618    disp.framebufferTarget->acquireFenceFd = acquireFenceFd;
619    return NO_ERROR;
620}
621
622status_t HWComposer::prepare() {
623    for (size_t i=0 ; i<mNumDisplays ; i++) {
624        DisplayData& disp(mDisplayData[i]);
625        if (disp.framebufferTarget) {
626            // make sure to reset the type to HWC_FRAMEBUFFER_TARGET
627            // DO NOT reset the handle field to NULL, because it's possible
628            // that we have nothing to redraw (eg: eglSwapBuffers() not called)
629            // in which case, we should continue to use the same buffer.
630            LOG_FATAL_IF(disp.list == NULL);
631            disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
632        }
633        if (!disp.connected && disp.list != NULL) {
634            ALOGW("WARNING: disp %zu: connected, non-null list, layers=%zu",
635                  i, disp.list->numHwLayers);
636        }
637        mLists[i] = disp.list;
638        if (mLists[i]) {
639            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
640                mLists[i]->outbuf = disp.outbufHandle;
641                mLists[i]->outbufAcquireFenceFd = -1;
642            } else if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
643                // garbage data to catch improper use
644                mLists[i]->dpy = (hwc_display_t)0xDEADBEEF;
645                mLists[i]->sur = (hwc_surface_t)0xDEADBEEF;
646            } else {
647                mLists[i]->dpy = EGL_NO_DISPLAY;
648                mLists[i]->sur = EGL_NO_SURFACE;
649            }
650        }
651    }
652
653    int err = mHwc->prepare(mHwc, mNumDisplays, mLists);
654    ALOGE_IF(err, "HWComposer: prepare failed (%s)", strerror(-err));
655
656    if (err == NO_ERROR) {
657        // here we're just making sure that "skip" layers are set
658        // to HWC_FRAMEBUFFER and we're also counting how many layers
659        // we have of each type.
660        //
661        // If there are no window layers, we treat the display has having FB
662        // composition, because SurfaceFlinger will use GLES to draw the
663        // wormhole region.
664        for (size_t i=0 ; i<mNumDisplays ; i++) {
665            DisplayData& disp(mDisplayData[i]);
666            disp.hasFbComp = false;
667            disp.hasOvComp = false;
668            if (disp.list) {
669                for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
670                    hwc_layer_1_t& l = disp.list->hwLayers[i];
671
672                    //ALOGD("prepare: %d, type=%d, handle=%p",
673                    //        i, l.compositionType, l.handle);
674
675                    if (l.flags & HWC_SKIP_LAYER) {
676                        l.compositionType = HWC_FRAMEBUFFER;
677                    }
678                    if (l.compositionType == HWC_FRAMEBUFFER) {
679                        disp.hasFbComp = true;
680                    }
681                    if (l.compositionType == HWC_OVERLAY) {
682                        disp.hasOvComp = true;
683                    }
684                    if (l.compositionType == HWC_CURSOR_OVERLAY) {
685                        disp.hasOvComp = true;
686                    }
687                }
688                if (disp.list->numHwLayers == (disp.framebufferTarget ? 1 : 0)) {
689                    disp.hasFbComp = true;
690                }
691            } else {
692                disp.hasFbComp = true;
693            }
694        }
695    }
696    return (status_t)err;
697}
698
699bool HWComposer::hasHwcComposition(int32_t id) const {
700    if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
701        return false;
702    return mDisplayData[id].hasOvComp;
703}
704
705bool HWComposer::hasGlesComposition(int32_t id) const {
706    if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
707        return true;
708    return mDisplayData[id].hasFbComp;
709}
710
711sp<Fence> HWComposer::getAndResetReleaseFence(int32_t id) {
712    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
713        return Fence::NO_FENCE;
714
715    int fd = INVALID_OPERATION;
716    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
717        const DisplayData& disp(mDisplayData[id]);
718        if (disp.framebufferTarget) {
719            fd = disp.framebufferTarget->releaseFenceFd;
720            disp.framebufferTarget->acquireFenceFd = -1;
721            disp.framebufferTarget->releaseFenceFd = -1;
722        }
723    }
724    return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
725}
726
727status_t HWComposer::commit() {
728    int err = NO_ERROR;
729    if (mHwc) {
730        if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
731            // On version 1.0, the OpenGL ES target surface is communicated
732            // by the (dpy, sur) fields and we are guaranteed to have only
733            // a single display.
734            mLists[0]->dpy = eglGetCurrentDisplay();
735            mLists[0]->sur = eglGetCurrentSurface(EGL_DRAW);
736        }
737
738        for (size_t i=VIRTUAL_DISPLAY_ID_BASE; i<mNumDisplays; i++) {
739            DisplayData& disp(mDisplayData[i]);
740            if (disp.outbufHandle) {
741                mLists[i]->outbuf = disp.outbufHandle;
742                mLists[i]->outbufAcquireFenceFd =
743                        disp.outbufAcquireFence->dup();
744            }
745        }
746
747        err = mHwc->set(mHwc, mNumDisplays, mLists);
748
749        for (size_t i=0 ; i<mNumDisplays ; i++) {
750            DisplayData& disp(mDisplayData[i]);
751            disp.lastDisplayFence = disp.lastRetireFence;
752            disp.lastRetireFence = Fence::NO_FENCE;
753            if (disp.list) {
754                if (disp.list->retireFenceFd != -1) {
755                    disp.lastRetireFence = new Fence(disp.list->retireFenceFd);
756                    disp.list->retireFenceFd = -1;
757                }
758                disp.list->flags &= ~HWC_GEOMETRY_CHANGED;
759            }
760        }
761    }
762    return (status_t)err;
763}
764
765status_t HWComposer::setPowerMode(int disp, int mode) {
766    LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
767    if (mHwc) {
768        if (mode == HWC_POWER_MODE_OFF) {
769            eventControl(disp, HWC_EVENT_VSYNC, 0);
770        }
771        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
772            return (status_t)mHwc->setPowerMode(mHwc, disp, mode);
773        } else {
774            return (status_t)mHwc->blank(mHwc, disp,
775                    mode == HWC_POWER_MODE_OFF ? 1 : 0);
776        }
777    }
778    return NO_ERROR;
779}
780
781status_t HWComposer::setActiveConfig(int disp, int mode) {
782    LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
783    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
784        return (status_t)mHwc->setActiveConfig(mHwc, disp, mode);
785    } else {
786        LOG_FATAL_IF(mode != 0);
787    }
788    return NO_ERROR;
789}
790
791void HWComposer::disconnectDisplay(int disp) {
792    LOG_ALWAYS_FATAL_IF(disp < 0 || disp == HWC_DISPLAY_PRIMARY);
793    DisplayData& dd(mDisplayData[disp]);
794    free(dd.list);
795    dd.list = NULL;
796    dd.framebufferTarget = NULL;    // points into dd.list
797    dd.fbTargetHandle = NULL;
798    dd.outbufHandle = NULL;
799    dd.lastRetireFence = Fence::NO_FENCE;
800    dd.lastDisplayFence = Fence::NO_FENCE;
801    dd.outbufAcquireFence = Fence::NO_FENCE;
802}
803
804int HWComposer::getVisualID() const {
805    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
806        // FIXME: temporary hack until HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED
807        // is supported by the implementation. we can only be in this case
808        // if we have HWC 1.1
809        return HAL_PIXEL_FORMAT_RGBA_8888;
810        //return HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
811    } else {
812        return mFbDev->format;
813    }
814}
815
816bool HWComposer::supportsFramebufferTarget() const {
817    return (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
818}
819
820int HWComposer::fbPost(int32_t id,
821        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buffer) {
822    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
823        return setFramebufferTarget(id, acquireFence, buffer);
824    } else {
825        acquireFence->waitForever("HWComposer::fbPost");
826        return mFbDev->post(mFbDev, buffer->handle);
827    }
828}
829
830int HWComposer::fbCompositionComplete() {
831    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
832        return NO_ERROR;
833
834    if (mFbDev->compositionComplete) {
835        return mFbDev->compositionComplete(mFbDev);
836    } else {
837        return INVALID_OPERATION;
838    }
839}
840
841void HWComposer::fbDump(String8& result) {
842    if (mFbDev && mFbDev->common.version >= 1 && mFbDev->dump) {
843        const size_t SIZE = 4096;
844        char buffer[SIZE];
845        mFbDev->dump(mFbDev, buffer, SIZE);
846        result.append(buffer);
847    }
848}
849
850status_t HWComposer::setOutputBuffer(int32_t id, const sp<Fence>& acquireFence,
851        const sp<GraphicBuffer>& buf) {
852    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
853        return BAD_INDEX;
854    if (id < VIRTUAL_DISPLAY_ID_BASE)
855        return INVALID_OPERATION;
856
857    DisplayData& disp(mDisplayData[id]);
858    disp.outbufHandle = buf->handle;
859    disp.outbufAcquireFence = acquireFence;
860    return NO_ERROR;
861}
862
863sp<Fence> HWComposer::getLastRetireFence(int32_t id) const {
864    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
865        return Fence::NO_FENCE;
866    return mDisplayData[id].lastRetireFence;
867}
868
869status_t HWComposer::setCursorPositionAsync(int32_t id, const Rect& pos)
870{
871    if (mHwc->setCursorPositionAsync) {
872        return (status_t)mHwc->setCursorPositionAsync(mHwc, id, pos.left, pos.top);
873    }
874    else {
875        return NO_ERROR;
876    }
877}
878
879/*
880 * Helper template to implement a concrete HWCLayer
881 * This holds the pointer to the concrete hwc layer type
882 * and implements the "iterable" side of HWCLayer.
883 */
884template<typename CONCRETE, typename HWCTYPE>
885class Iterable : public HWComposer::HWCLayer {
886protected:
887    HWCTYPE* const mLayerList;
888    HWCTYPE* mCurrentLayer;
889    Iterable(HWCTYPE* layer) : mLayerList(layer), mCurrentLayer(layer) { }
890    inline HWCTYPE const * getLayer() const { return mCurrentLayer; }
891    inline HWCTYPE* getLayer() { return mCurrentLayer; }
892    virtual ~Iterable() { }
893private:
894    // returns a copy of ourselves
895    virtual HWComposer::HWCLayer* dup() {
896        return new CONCRETE( static_cast<const CONCRETE&>(*this) );
897    }
898    virtual status_t setLayer(size_t index) {
899        mCurrentLayer = &mLayerList[index];
900        return NO_ERROR;
901    }
902};
903
904/*
905 * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_1_0.
906 * This implements the HWCLayer side of HWCIterableLayer.
907 */
908class HWCLayerVersion1 : public Iterable<HWCLayerVersion1, hwc_layer_1_t> {
909    struct hwc_composer_device_1* mHwc;
910public:
911    HWCLayerVersion1(struct hwc_composer_device_1* hwc, hwc_layer_1_t* layer)
912        : Iterable<HWCLayerVersion1, hwc_layer_1_t>(layer), mHwc(hwc) { }
913
914    virtual int32_t getCompositionType() const {
915        return getLayer()->compositionType;
916    }
917    virtual uint32_t getHints() const {
918        return getLayer()->hints;
919    }
920    virtual sp<Fence> getAndResetReleaseFence() {
921        int fd = getLayer()->releaseFenceFd;
922        getLayer()->releaseFenceFd = -1;
923        return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
924    }
925    virtual void setAcquireFenceFd(int fenceFd) {
926        getLayer()->acquireFenceFd = fenceFd;
927    }
928    virtual void setPerFrameDefaultState() {
929        //getLayer()->compositionType = HWC_FRAMEBUFFER;
930    }
931    virtual void setPlaneAlpha(uint8_t alpha) {
932        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_2)) {
933            getLayer()->planeAlpha = alpha;
934        } else {
935            if (alpha < 0xFF) {
936                getLayer()->flags |= HWC_SKIP_LAYER;
937            }
938        }
939    }
940    virtual void setDefaultState() {
941        hwc_layer_1_t* const l = getLayer();
942        l->compositionType = HWC_FRAMEBUFFER;
943        l->hints = 0;
944        l->flags = HWC_SKIP_LAYER;
945        l->handle = 0;
946        l->transform = 0;
947        l->blending = HWC_BLENDING_NONE;
948        l->visibleRegionScreen.numRects = 0;
949        l->visibleRegionScreen.rects = NULL;
950        l->acquireFenceFd = -1;
951        l->releaseFenceFd = -1;
952        l->planeAlpha = 0xFF;
953    }
954    virtual void setSkip(bool skip) {
955        if (skip) {
956            getLayer()->flags |= HWC_SKIP_LAYER;
957        } else {
958            getLayer()->flags &= ~HWC_SKIP_LAYER;
959        }
960    }
961    virtual void setIsCursorLayerHint(bool isCursor) {
962        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
963            if (isCursor) {
964                getLayer()->flags |= HWC_IS_CURSOR_LAYER;
965            }
966            else {
967                getLayer()->flags &= ~HWC_IS_CURSOR_LAYER;
968            }
969        }
970    }
971    virtual void setBlending(uint32_t blending) {
972        getLayer()->blending = blending;
973    }
974    virtual void setTransform(uint32_t transform) {
975        getLayer()->transform = transform;
976    }
977    virtual void setFrame(const Rect& frame) {
978        getLayer()->displayFrame = reinterpret_cast<hwc_rect_t const&>(frame);
979    }
980    virtual void setCrop(const FloatRect& crop) {
981        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
982            getLayer()->sourceCropf = reinterpret_cast<hwc_frect_t const&>(crop);
983        } else {
984            /*
985             * Since h/w composer didn't support a flot crop rect before version 1.3,
986             * using integer coordinates instead produces a different output from the GL code in
987             * Layer::drawWithOpenGL(). The difference can be large if the buffer crop to
988             * window size ratio is large and a window crop is defined
989             * (i.e.: if we scale the buffer a lot and we also crop it with a window crop).
990             */
991            hwc_rect_t& r = getLayer()->sourceCrop;
992            r.left  = int(ceilf(crop.left));
993            r.top   = int(ceilf(crop.top));
994            r.right = int(floorf(crop.right));
995            r.bottom= int(floorf(crop.bottom));
996        }
997    }
998    virtual void setVisibleRegionScreen(const Region& reg) {
999        // Region::getSharedBuffer creates a reference to the underlying
1000        // SharedBuffer of this Region, this reference is freed
1001        // in onDisplayed()
1002        hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
1003        SharedBuffer const* sb = reg.getSharedBuffer(&visibleRegion.numRects);
1004        visibleRegion.rects = reinterpret_cast<hwc_rect_t const *>(sb->data());
1005    }
1006    virtual void setSidebandStream(const sp<NativeHandle>& stream) {
1007        ALOG_ASSERT(stream->handle() != NULL);
1008        getLayer()->compositionType = HWC_SIDEBAND;
1009        getLayer()->sidebandStream = stream->handle();
1010    }
1011    virtual void setBuffer(const sp<GraphicBuffer>& buffer) {
1012        if (buffer == 0 || buffer->handle == 0) {
1013            getLayer()->compositionType = HWC_FRAMEBUFFER;
1014            getLayer()->flags |= HWC_SKIP_LAYER;
1015            getLayer()->handle = 0;
1016        } else {
1017            if (getLayer()->compositionType == HWC_SIDEBAND) {
1018                // If this was a sideband layer but the stream was removed, reset
1019                // it to FRAMEBUFFER. The HWC can change it to OVERLAY in prepare.
1020                getLayer()->compositionType = HWC_FRAMEBUFFER;
1021            }
1022            getLayer()->handle = buffer->handle;
1023        }
1024    }
1025    virtual void onDisplayed() {
1026        hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
1027        SharedBuffer const* sb = SharedBuffer::bufferFromData(visibleRegion.rects);
1028        if (sb) {
1029            sb->release();
1030            // not technically needed but safer
1031            visibleRegion.numRects = 0;
1032            visibleRegion.rects = NULL;
1033        }
1034
1035        getLayer()->acquireFenceFd = -1;
1036    }
1037};
1038
1039/*
1040 * returns an iterator initialized at a given index in the layer list
1041 */
1042HWComposer::LayerListIterator HWComposer::getLayerIterator(int32_t id, size_t index) {
1043    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
1044        return LayerListIterator();
1045    }
1046    const DisplayData& disp(mDisplayData[id]);
1047    if (!mHwc || !disp.list || index > disp.list->numHwLayers) {
1048        return LayerListIterator();
1049    }
1050    return LayerListIterator(new HWCLayerVersion1(mHwc, disp.list->hwLayers), index);
1051}
1052
1053/*
1054 * returns an iterator on the beginning of the layer list
1055 */
1056HWComposer::LayerListIterator HWComposer::begin(int32_t id) {
1057    return getLayerIterator(id, 0);
1058}
1059
1060/*
1061 * returns an iterator on the end of the layer list
1062 */
1063HWComposer::LayerListIterator HWComposer::end(int32_t id) {
1064    size_t numLayers = 0;
1065    if (uint32_t(id) <= 31 && mAllocatedDisplayIDs.hasBit(id)) {
1066        const DisplayData& disp(mDisplayData[id]);
1067        if (mHwc && disp.list) {
1068            numLayers = disp.list->numHwLayers;
1069            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
1070                // with HWC 1.1, the last layer is always the HWC_FRAMEBUFFER_TARGET,
1071                // which we ignore when iterating through the layer list.
1072                ALOGE_IF(!numLayers, "mDisplayData[%d].list->numHwLayers is 0", id);
1073                if (numLayers) {
1074                    numLayers--;
1075                }
1076            }
1077        }
1078    }
1079    return getLayerIterator(id, numLayers);
1080}
1081
1082// Converts a PixelFormat to a human-readable string.  Max 11 chars.
1083// (Could use a table of prefab String8 objects.)
1084static String8 getFormatStr(PixelFormat format) {
1085    switch (format) {
1086    case PIXEL_FORMAT_RGBA_8888:    return String8("RGBA_8888");
1087    case PIXEL_FORMAT_RGBX_8888:    return String8("RGBx_8888");
1088    case PIXEL_FORMAT_RGB_888:      return String8("RGB_888");
1089    case PIXEL_FORMAT_RGB_565:      return String8("RGB_565");
1090    case PIXEL_FORMAT_BGRA_8888:    return String8("BGRA_8888");
1091    case PIXEL_FORMAT_sRGB_A_8888:  return String8("sRGB_A_8888");
1092    case PIXEL_FORMAT_sRGB_X_8888:  return String8("sRGB_x_8888");
1093    case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
1094                                    return String8("ImplDef");
1095    default:
1096        String8 result;
1097        result.appendFormat("? %08x", format);
1098        return result;
1099    }
1100}
1101
1102void HWComposer::dump(String8& result) const {
1103    if (mHwc) {
1104        result.appendFormat("Hardware Composer state (version %08x):\n", hwcApiVersion(mHwc));
1105        result.appendFormat("  mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync);
1106        for (size_t i=0 ; i<mNumDisplays ; i++) {
1107            const DisplayData& disp(mDisplayData[i]);
1108            if (!disp.connected)
1109                continue;
1110
1111            const Vector< sp<Layer> >& visibleLayersSortedByZ =
1112                    mFlinger->getLayerSortedByZForHwcDisplay(i);
1113
1114
1115            result.appendFormat("  Display[%zd] configurations (* current):\n", i);
1116            for (size_t c = 0; c < disp.configs.size(); ++c) {
1117                const DisplayConfig& config(disp.configs[c]);
1118                result.appendFormat("    %s%zd: %ux%u, xdpi=%f, ydpi=%f, refresh=%" PRId64 "\n",
1119                        c == disp.currentConfig ? "* " : "", c, config.width, config.height,
1120                        config.xdpi, config.ydpi, config.refresh);
1121            }
1122
1123            if (disp.list) {
1124                result.appendFormat(
1125                        "  numHwLayers=%zu, flags=%08x\n",
1126                        disp.list->numHwLayers, disp.list->flags);
1127
1128                result.append(
1129                        "    type   |  handle  | hint | flag | tr | blnd |   format    |     source crop (l,t,r,b)      |          frame         | name \n"
1130                        "-----------+----------+------+------+----+------+-------------+--------------------------------+------------------------+------\n");
1131                //      " _________ | ________ | ____ | ____ | __ | ____ | ___________ |_____._,_____._,_____._,_____._ |_____,_____,_____,_____ | ___...
1132                for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
1133                    const hwc_layer_1_t&l = disp.list->hwLayers[i];
1134                    int32_t format = -1;
1135                    String8 name("unknown");
1136
1137                    if (i < visibleLayersSortedByZ.size()) {
1138                        const sp<Layer>& layer(visibleLayersSortedByZ[i]);
1139                        const sp<GraphicBuffer>& buffer(
1140                                layer->getActiveBuffer());
1141                        if (buffer != NULL) {
1142                            format = buffer->getPixelFormat();
1143                        }
1144                        name = layer->getName();
1145                    }
1146
1147                    int type = l.compositionType;
1148                    if (type == HWC_FRAMEBUFFER_TARGET) {
1149                        name = "HWC_FRAMEBUFFER_TARGET";
1150                        format = disp.format;
1151                    }
1152
1153                    static char const* compositionTypeName[] = {
1154                            "GLES",
1155                            "HWC",
1156                            "BKGND",
1157                            "FB TARGET",
1158                            "SIDEBAND",
1159                            "HWC_CURSOR",
1160                            "UNKNOWN"};
1161                    if (type >= NELEM(compositionTypeName))
1162                        type = NELEM(compositionTypeName) - 1;
1163
1164                    String8 formatStr = getFormatStr(format);
1165                    if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
1166                        result.appendFormat(
1167                                " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7.1f,%7.1f,%7.1f,%7.1f |%5d,%5d,%5d,%5d | %s\n",
1168                                        compositionTypeName[type],
1169                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
1170                                        l.sourceCropf.left, l.sourceCropf.top, l.sourceCropf.right, l.sourceCropf.bottom,
1171                                        l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1172                                        name.string());
1173                    } else {
1174                        result.appendFormat(
1175                                " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7d,%7d,%7d,%7d |%5d,%5d,%5d,%5d | %s\n",
1176                                        compositionTypeName[type],
1177                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
1178                                        l.sourceCrop.left, l.sourceCrop.top, l.sourceCrop.right, l.sourceCrop.bottom,
1179                                        l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1180                                        name.string());
1181                    }
1182                }
1183            }
1184        }
1185    }
1186
1187    if (mHwc && mHwc->dump) {
1188        const size_t SIZE = 4096;
1189        char buffer[SIZE];
1190        mHwc->dump(mHwc, buffer, SIZE);
1191        result.append(buffer);
1192    }
1193}
1194
1195// ---------------------------------------------------------------------------
1196
1197HWComposer::VSyncThread::VSyncThread(HWComposer& hwc)
1198    : mHwc(hwc), mEnabled(false),
1199      mNextFakeVSync(0),
1200      mRefreshPeriod(hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY))
1201{
1202}
1203
1204void HWComposer::VSyncThread::setEnabled(bool enabled) {
1205    Mutex::Autolock _l(mLock);
1206    if (mEnabled != enabled) {
1207        mEnabled = enabled;
1208        mCondition.signal();
1209    }
1210}
1211
1212void HWComposer::VSyncThread::onFirstRef() {
1213    run("VSyncThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
1214}
1215
1216bool HWComposer::VSyncThread::threadLoop() {
1217    { // scope for lock
1218        Mutex::Autolock _l(mLock);
1219        while (!mEnabled) {
1220            mCondition.wait(mLock);
1221        }
1222    }
1223
1224    const nsecs_t period = mRefreshPeriod;
1225    const nsecs_t now = systemTime(CLOCK_MONOTONIC);
1226    nsecs_t next_vsync = mNextFakeVSync;
1227    nsecs_t sleep = next_vsync - now;
1228    if (sleep < 0) {
1229        // we missed, find where the next vsync should be
1230        sleep = (period - ((now - next_vsync) % period));
1231        next_vsync = now + sleep;
1232    }
1233    mNextFakeVSync = next_vsync + period;
1234
1235    struct timespec spec;
1236    spec.tv_sec  = next_vsync / 1000000000;
1237    spec.tv_nsec = next_vsync % 1000000000;
1238
1239    int err;
1240    do {
1241        err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
1242    } while (err<0 && errno == EINTR);
1243
1244    if (err == 0) {
1245        mHwc.mEventHandler.onVSyncReceived(0, next_vsync);
1246    }
1247
1248    return true;
1249}
1250
1251HWComposer::DisplayData::DisplayData()
1252:   configs(),
1253    currentConfig(0),
1254    format(HAL_PIXEL_FORMAT_RGBA_8888),
1255    connected(false),
1256    hasFbComp(false), hasOvComp(false),
1257    capacity(0), list(NULL),
1258    framebufferTarget(NULL), fbTargetHandle(0),
1259    lastRetireFence(Fence::NO_FENCE), lastDisplayFence(Fence::NO_FENCE),
1260    outbufHandle(NULL), outbufAcquireFence(Fence::NO_FENCE),
1261    events(0)
1262{}
1263
1264HWComposer::DisplayData::~DisplayData() {
1265    free(list);
1266}
1267
1268// ---------------------------------------------------------------------------
1269}; // namespace android
1270