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 >= 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    // Do not teardown or recreate the primary display
315    if (disp != HWC_DISPLAY_PRIMARY) {
316        mEventHandler.onHotplugReceived(disp, bool(connected));
317    }
318}
319
320static float getDefaultDensity(uint32_t width, uint32_t height) {
321    // Default density is based on TVs: 1080p displays get XHIGH density,
322    // lower-resolution displays get TV density. Maybe eventually we'll need
323    // to update it for 4K displays, though hopefully those just report
324    // accurate DPI information to begin with. This is also used for virtual
325    // displays and even primary displays with older hwcomposers, so be
326    // careful about orientation.
327
328    uint32_t h = width < height ? width : height;
329    if (h >= 1080) return ACONFIGURATION_DENSITY_XHIGH;
330    else           return ACONFIGURATION_DENSITY_TV;
331}
332
333static const uint32_t DISPLAY_ATTRIBUTES[] = {
334    HWC_DISPLAY_VSYNC_PERIOD,
335    HWC_DISPLAY_WIDTH,
336    HWC_DISPLAY_HEIGHT,
337    HWC_DISPLAY_DPI_X,
338    HWC_DISPLAY_DPI_Y,
339    HWC_DISPLAY_COLOR_TRANSFORM,
340    HWC_DISPLAY_NO_ATTRIBUTE,
341};
342#define NUM_DISPLAY_ATTRIBUTES (sizeof(DISPLAY_ATTRIBUTES) / sizeof(DISPLAY_ATTRIBUTES)[0])
343
344static const uint32_t PRE_HWC15_DISPLAY_ATTRIBUTES[] = {
345    HWC_DISPLAY_VSYNC_PERIOD,
346    HWC_DISPLAY_WIDTH,
347    HWC_DISPLAY_HEIGHT,
348    HWC_DISPLAY_DPI_X,
349    HWC_DISPLAY_DPI_Y,
350    HWC_DISPLAY_NO_ATTRIBUTE,
351};
352
353status_t HWComposer::queryDisplayProperties(int disp) {
354
355    LOG_ALWAYS_FATAL_IF(!mHwc || !hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
356
357    // use zero as default value for unspecified attributes
358    int32_t values[NUM_DISPLAY_ATTRIBUTES - 1];
359    memset(values, 0, sizeof(values));
360
361    const size_t MAX_NUM_CONFIGS = 128;
362    uint32_t configs[MAX_NUM_CONFIGS] = {0};
363    size_t numConfigs = MAX_NUM_CONFIGS;
364    status_t err = mHwc->getDisplayConfigs(mHwc, disp, configs, &numConfigs);
365    if (err != NO_ERROR) {
366        // this can happen if an unpluggable display is not connected
367        mDisplayData[disp].connected = false;
368        return err;
369    }
370
371    mDisplayData[disp].currentConfig = 0;
372    for (size_t c = 0; c < numConfigs; ++c) {
373        err = mHwc->getDisplayAttributes(mHwc, disp, configs[c],
374                DISPLAY_ATTRIBUTES, values);
375        // If this is a pre-1.5 HWC, it may not know about color transform, so
376        // try again with a smaller set of attributes
377        if (err != NO_ERROR) {
378            err = mHwc->getDisplayAttributes(mHwc, disp, configs[c],
379                    PRE_HWC15_DISPLAY_ATTRIBUTES, values);
380        }
381        if (err != NO_ERROR) {
382            // we can't get this display's info. turn it off.
383            mDisplayData[disp].connected = false;
384            return err;
385        }
386
387        DisplayConfig config = DisplayConfig();
388        for (size_t i = 0; i < NUM_DISPLAY_ATTRIBUTES - 1; i++) {
389            switch (DISPLAY_ATTRIBUTES[i]) {
390                case HWC_DISPLAY_VSYNC_PERIOD:
391                    config.refresh = nsecs_t(values[i]);
392                    break;
393                case HWC_DISPLAY_WIDTH:
394                    config.width = values[i];
395                    break;
396                case HWC_DISPLAY_HEIGHT:
397                    config.height = values[i];
398                    break;
399                case HWC_DISPLAY_DPI_X:
400                    config.xdpi = values[i] / 1000.0f;
401                    break;
402                case HWC_DISPLAY_DPI_Y:
403                    config.ydpi = values[i] / 1000.0f;
404                    break;
405                case HWC_DISPLAY_COLOR_TRANSFORM:
406                    config.colorTransform = values[i];
407                    break;
408                default:
409                    ALOG_ASSERT(false, "unknown display attribute[%zu] %#x",
410                            i, DISPLAY_ATTRIBUTES[i]);
411                    break;
412            }
413        }
414
415        if (config.xdpi == 0.0f || config.ydpi == 0.0f) {
416            float dpi = getDefaultDensity(config.width, config.height);
417            config.xdpi = dpi;
418            config.ydpi = dpi;
419        }
420
421        mDisplayData[disp].configs.push_back(config);
422    }
423
424    // FIXME: what should we set the format to?
425    mDisplayData[disp].format = HAL_PIXEL_FORMAT_RGBA_8888;
426    mDisplayData[disp].connected = true;
427    return NO_ERROR;
428}
429
430status_t HWComposer::setVirtualDisplayProperties(int32_t id,
431        uint32_t w, uint32_t h, uint32_t format) {
432    if (id < VIRTUAL_DISPLAY_ID_BASE || id >= int32_t(mNumDisplays) ||
433            !mAllocatedDisplayIDs.hasBit(id)) {
434        return BAD_INDEX;
435    }
436    size_t configId = mDisplayData[id].currentConfig;
437    mDisplayData[id].format = format;
438    DisplayConfig& config = mDisplayData[id].configs.editItemAt(configId);
439    config.width = w;
440    config.height = h;
441    config.xdpi = config.ydpi = getDefaultDensity(w, h);
442    return NO_ERROR;
443}
444
445int32_t HWComposer::allocateDisplayId() {
446    if (mAllocatedDisplayIDs.count() >= mNumDisplays) {
447        return NO_MEMORY;
448    }
449    int32_t id = mAllocatedDisplayIDs.firstUnmarkedBit();
450    mAllocatedDisplayIDs.markBit(id);
451    mDisplayData[id].connected = true;
452    mDisplayData[id].configs.resize(1);
453    mDisplayData[id].currentConfig = 0;
454    return id;
455}
456
457status_t HWComposer::freeDisplayId(int32_t id) {
458    if (id < NUM_BUILTIN_DISPLAYS) {
459        // cannot free the reserved IDs
460        return BAD_VALUE;
461    }
462    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
463        return BAD_INDEX;
464    }
465    mAllocatedDisplayIDs.clearBit(id);
466    mDisplayData[id].connected = false;
467    return NO_ERROR;
468}
469
470nsecs_t HWComposer::getRefreshTimestamp(int disp) const {
471    // this returns the last refresh timestamp.
472    // if the last one is not available, we estimate it based on
473    // the refresh period and whatever closest timestamp we have.
474    Mutex::Autolock _l(mLock);
475    nsecs_t now = systemTime(CLOCK_MONOTONIC);
476    size_t configId = mDisplayData[disp].currentConfig;
477    return now - ((now - mLastHwVSync[disp]) %
478            mDisplayData[disp].configs[configId].refresh);
479}
480
481sp<Fence> HWComposer::getDisplayFence(int disp) const {
482    return mDisplayData[disp].lastDisplayFence;
483}
484
485uint32_t HWComposer::getFormat(int disp) const {
486    if (static_cast<uint32_t>(disp) >= MAX_HWC_DISPLAYS || !mAllocatedDisplayIDs.hasBit(disp)) {
487        return HAL_PIXEL_FORMAT_RGBA_8888;
488    } else {
489        return mDisplayData[disp].format;
490    }
491}
492
493bool HWComposer::isConnected(int disp) const {
494    return mDisplayData[disp].connected;
495}
496
497uint32_t HWComposer::getWidth(int disp) const {
498    size_t currentConfig = mDisplayData[disp].currentConfig;
499    return mDisplayData[disp].configs[currentConfig].width;
500}
501
502uint32_t HWComposer::getHeight(int disp) const {
503    size_t currentConfig = mDisplayData[disp].currentConfig;
504    return mDisplayData[disp].configs[currentConfig].height;
505}
506
507float HWComposer::getDpiX(int disp) const {
508    size_t currentConfig = mDisplayData[disp].currentConfig;
509    return mDisplayData[disp].configs[currentConfig].xdpi;
510}
511
512float HWComposer::getDpiY(int disp) const {
513    size_t currentConfig = mDisplayData[disp].currentConfig;
514    return mDisplayData[disp].configs[currentConfig].ydpi;
515}
516
517nsecs_t HWComposer::getRefreshPeriod(int disp) const {
518    size_t currentConfig = mDisplayData[disp].currentConfig;
519    return mDisplayData[disp].configs[currentConfig].refresh;
520}
521
522const Vector<HWComposer::DisplayConfig>& HWComposer::getConfigs(int disp) const {
523    return mDisplayData[disp].configs;
524}
525
526size_t HWComposer::getCurrentConfig(int disp) const {
527    return mDisplayData[disp].currentConfig;
528}
529
530void HWComposer::eventControl(int disp, int event, int enabled) {
531    if (uint32_t(disp)>31 || !mAllocatedDisplayIDs.hasBit(disp)) {
532        ALOGD("eventControl ignoring event %d on unallocated disp %d (en=%d)",
533              event, disp, enabled);
534        return;
535    }
536    if (event != EVENT_VSYNC) {
537        ALOGW("eventControl got unexpected event %d (disp=%d en=%d)",
538              event, disp, enabled);
539        return;
540    }
541    status_t err = NO_ERROR;
542    if (mHwc && !mDebugForceFakeVSync) {
543        // NOTE: we use our own internal lock here because we have to call
544        // into the HWC with the lock held, and we want to make sure
545        // that even if HWC blocks (which it shouldn't), it won't
546        // affect other threads.
547        Mutex::Autolock _l(mEventControlLock);
548        const int32_t eventBit = 1UL << event;
549        const int32_t newValue = enabled ? eventBit : 0;
550        const int32_t oldValue = mDisplayData[disp].events & eventBit;
551        if (newValue != oldValue) {
552            ATRACE_CALL();
553            err = mHwc->eventControl(mHwc, disp, event, enabled);
554            if (!err) {
555                int32_t& events(mDisplayData[disp].events);
556                events = (events & ~eventBit) | newValue;
557
558                char tag[16];
559                snprintf(tag, sizeof(tag), "HW_VSYNC_ON_%1u", disp);
560                ATRACE_INT(tag, enabled);
561            }
562        }
563        // error here should not happen -- not sure what we should
564        // do if it does.
565        ALOGE_IF(err, "eventControl(%d, %d) failed %s",
566                event, enabled, strerror(-err));
567    }
568
569    if (err == NO_ERROR && mVSyncThread != NULL) {
570        mVSyncThread->setEnabled(enabled);
571    }
572}
573
574status_t HWComposer::createWorkList(int32_t id, size_t numLayers) {
575    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
576        return BAD_INDEX;
577    }
578
579    if (mHwc) {
580        DisplayData& disp(mDisplayData[id]);
581        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
582            // we need space for the HWC_FRAMEBUFFER_TARGET
583            numLayers++;
584        }
585        if (disp.capacity < numLayers || disp.list == NULL) {
586            size_t size = sizeof(hwc_display_contents_1_t)
587                    + numLayers * sizeof(hwc_layer_1_t);
588            free(disp.list);
589            disp.list = (hwc_display_contents_1_t*)malloc(size);
590            disp.capacity = numLayers;
591        }
592        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
593            disp.framebufferTarget = &disp.list->hwLayers[numLayers - 1];
594            memset(disp.framebufferTarget, 0, sizeof(hwc_layer_1_t));
595            const DisplayConfig& currentConfig =
596                    disp.configs[disp.currentConfig];
597            const hwc_rect_t r = { 0, 0,
598                    (int) currentConfig.width, (int) currentConfig.height };
599            disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
600            disp.framebufferTarget->hints = 0;
601            disp.framebufferTarget->flags = 0;
602            disp.framebufferTarget->handle = disp.fbTargetHandle;
603            disp.framebufferTarget->transform = 0;
604            disp.framebufferTarget->blending = HWC_BLENDING_PREMULT;
605            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
606                disp.framebufferTarget->sourceCropf.left = 0;
607                disp.framebufferTarget->sourceCropf.top = 0;
608                disp.framebufferTarget->sourceCropf.right =
609                        currentConfig.width;
610                disp.framebufferTarget->sourceCropf.bottom =
611                        currentConfig.height;
612            } else {
613                disp.framebufferTarget->sourceCrop = r;
614            }
615            disp.framebufferTarget->displayFrame = r;
616            disp.framebufferTarget->visibleRegionScreen.numRects = 1;
617            disp.framebufferTarget->visibleRegionScreen.rects =
618                &disp.framebufferTarget->displayFrame;
619            disp.framebufferTarget->acquireFenceFd = -1;
620            disp.framebufferTarget->releaseFenceFd = -1;
621            disp.framebufferTarget->planeAlpha = 0xFF;
622        }
623        disp.list->retireFenceFd = -1;
624        disp.list->flags = HWC_GEOMETRY_CHANGED;
625        disp.list->numHwLayers = numLayers;
626    }
627    return NO_ERROR;
628}
629
630status_t HWComposer::setFramebufferTarget(int32_t id,
631        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buf) {
632    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
633        return BAD_INDEX;
634    }
635    DisplayData& disp(mDisplayData[id]);
636    if (!disp.framebufferTarget) {
637        // this should never happen, but apparently eglCreateWindowSurface()
638        // triggers a Surface::queueBuffer()  on some
639        // devices (!?) -- log and ignore.
640        ALOGE("HWComposer: framebufferTarget is null");
641        return NO_ERROR;
642    }
643
644    int acquireFenceFd = -1;
645    if (acquireFence->isValid()) {
646        acquireFenceFd = acquireFence->dup();
647    }
648
649    // ALOGD("fbPost: handle=%p, fence=%d", buf->handle, acquireFenceFd);
650    disp.fbTargetHandle = buf->handle;
651    disp.framebufferTarget->handle = disp.fbTargetHandle;
652    disp.framebufferTarget->acquireFenceFd = acquireFenceFd;
653    return NO_ERROR;
654}
655
656status_t HWComposer::prepare() {
657    Mutex::Autolock _l(mDisplayLock);
658    for (size_t i=0 ; i<mNumDisplays ; i++) {
659        DisplayData& disp(mDisplayData[i]);
660        if (disp.framebufferTarget) {
661            // make sure to reset the type to HWC_FRAMEBUFFER_TARGET
662            // DO NOT reset the handle field to NULL, because it's possible
663            // that we have nothing to redraw (eg: eglSwapBuffers() not called)
664            // in which case, we should continue to use the same buffer.
665            LOG_FATAL_IF(disp.list == NULL);
666            disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
667        }
668        if (!disp.connected && disp.list != NULL) {
669            ALOGW("WARNING: disp %zu: connected, non-null list, layers=%zu",
670                  i, disp.list->numHwLayers);
671        }
672        mLists[i] = disp.list;
673        if (mLists[i]) {
674            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
675                mLists[i]->outbuf = disp.outbufHandle;
676                mLists[i]->outbufAcquireFenceFd = -1;
677            } else if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
678                // garbage data to catch improper use
679                mLists[i]->dpy = (hwc_display_t)0xDEADBEEF;
680                mLists[i]->sur = (hwc_surface_t)0xDEADBEEF;
681            } else {
682                mLists[i]->dpy = EGL_NO_DISPLAY;
683                mLists[i]->sur = EGL_NO_SURFACE;
684            }
685        }
686    }
687
688    int err = mHwc->prepare(mHwc, mNumDisplays, mLists);
689    ALOGE_IF(err, "HWComposer: prepare failed (%s)", strerror(-err));
690
691    if (err == NO_ERROR) {
692        // here we're just making sure that "skip" layers are set
693        // to HWC_FRAMEBUFFER and we're also counting how many layers
694        // we have of each type.
695        //
696        // If there are no window layers, we treat the display has having FB
697        // composition, because SurfaceFlinger will use GLES to draw the
698        // wormhole region.
699        for (size_t i=0 ; i<mNumDisplays ; i++) {
700            DisplayData& disp(mDisplayData[i]);
701            disp.hasFbComp = false;
702            disp.hasOvComp = false;
703            if (disp.list) {
704                for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
705                    hwc_layer_1_t& l = disp.list->hwLayers[i];
706
707                    //ALOGD("prepare: %d, type=%d, handle=%p",
708                    //        i, l.compositionType, l.handle);
709
710                    if (l.flags & HWC_SKIP_LAYER) {
711                        l.compositionType = HWC_FRAMEBUFFER;
712                    }
713                    if (l.compositionType == HWC_FRAMEBUFFER) {
714                        disp.hasFbComp = true;
715                    }
716                    if (l.compositionType == HWC_OVERLAY) {
717                        disp.hasOvComp = true;
718                    }
719                    if (l.compositionType == HWC_CURSOR_OVERLAY) {
720                        disp.hasOvComp = true;
721                    }
722                }
723                if (disp.list->numHwLayers == (disp.framebufferTarget ? 1 : 0)) {
724                    disp.hasFbComp = true;
725                }
726            } else {
727                disp.hasFbComp = true;
728            }
729        }
730    }
731    return (status_t)err;
732}
733
734bool HWComposer::hasHwcComposition(int32_t id) const {
735    if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
736        return false;
737    return mDisplayData[id].hasOvComp;
738}
739
740bool HWComposer::hasGlesComposition(int32_t id) const {
741    if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
742        return true;
743    return mDisplayData[id].hasFbComp;
744}
745
746sp<Fence> HWComposer::getAndResetReleaseFence(int32_t id) {
747    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
748        return Fence::NO_FENCE;
749
750    int fd = INVALID_OPERATION;
751    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
752        const DisplayData& disp(mDisplayData[id]);
753        if (disp.framebufferTarget) {
754            fd = disp.framebufferTarget->releaseFenceFd;
755            disp.framebufferTarget->acquireFenceFd = -1;
756            disp.framebufferTarget->releaseFenceFd = -1;
757        }
758    }
759    return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
760}
761
762status_t HWComposer::commit() {
763    int err = NO_ERROR;
764    if (mHwc) {
765        if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
766            // On version 1.0, the OpenGL ES target surface is communicated
767            // by the (dpy, sur) fields and we are guaranteed to have only
768            // a single display.
769            mLists[0]->dpy = eglGetCurrentDisplay();
770            mLists[0]->sur = eglGetCurrentSurface(EGL_DRAW);
771        }
772
773        for (size_t i=VIRTUAL_DISPLAY_ID_BASE; i<mNumDisplays; i++) {
774            DisplayData& disp(mDisplayData[i]);
775            if (disp.outbufHandle) {
776                mLists[i]->outbuf = disp.outbufHandle;
777                mLists[i]->outbufAcquireFenceFd =
778                        disp.outbufAcquireFence->dup();
779            }
780        }
781
782        err = mHwc->set(mHwc, mNumDisplays, mLists);
783
784        for (size_t i=0 ; i<mNumDisplays ; i++) {
785            DisplayData& disp(mDisplayData[i]);
786            disp.lastDisplayFence = disp.lastRetireFence;
787            disp.lastRetireFence = Fence::NO_FENCE;
788            if (disp.list) {
789                if (disp.list->retireFenceFd != -1) {
790                    disp.lastRetireFence = new Fence(disp.list->retireFenceFd);
791                    disp.list->retireFenceFd = -1;
792                }
793                disp.list->flags &= ~HWC_GEOMETRY_CHANGED;
794            }
795        }
796    }
797    return (status_t)err;
798}
799
800status_t HWComposer::setPowerMode(int disp, int mode) {
801    LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
802    if (mHwc) {
803        if (mode == HWC_POWER_MODE_OFF) {
804            eventControl(disp, HWC_EVENT_VSYNC, 0);
805        }
806        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
807            return (status_t)mHwc->setPowerMode(mHwc, disp, mode);
808        } else {
809            return (status_t)mHwc->blank(mHwc, disp,
810                    mode == HWC_POWER_MODE_OFF ? 1 : 0);
811        }
812    }
813    return NO_ERROR;
814}
815
816status_t HWComposer::setActiveConfig(int disp, int mode) {
817    LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
818    DisplayData& dd(mDisplayData[disp]);
819    dd.currentConfig = mode;
820    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
821        return (status_t)mHwc->setActiveConfig(mHwc, disp, mode);
822    } else {
823        LOG_FATAL_IF(mode != 0);
824    }
825    return NO_ERROR;
826}
827
828void HWComposer::disconnectDisplay(int disp) {
829    LOG_ALWAYS_FATAL_IF(disp < 0 || disp == HWC_DISPLAY_PRIMARY);
830    DisplayData& dd(mDisplayData[disp]);
831    free(dd.list);
832    dd.list = NULL;
833    dd.framebufferTarget = NULL;    // points into dd.list
834    dd.fbTargetHandle = NULL;
835    dd.outbufHandle = NULL;
836    dd.lastRetireFence = Fence::NO_FENCE;
837    dd.lastDisplayFence = Fence::NO_FENCE;
838    dd.outbufAcquireFence = Fence::NO_FENCE;
839    // clear all the previous configs and repopulate when a new
840    // device is added
841    dd.configs.clear();
842}
843
844int HWComposer::getVisualID() const {
845    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
846        // FIXME: temporary hack until HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED
847        // is supported by the implementation. we can only be in this case
848        // if we have HWC 1.1
849        return HAL_PIXEL_FORMAT_RGBA_8888;
850        //return HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
851    } else {
852        return mFbDev->format;
853    }
854}
855
856bool HWComposer::supportsFramebufferTarget() const {
857    return (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
858}
859
860int HWComposer::fbPost(int32_t id,
861        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buffer) {
862    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
863        return setFramebufferTarget(id, acquireFence, buffer);
864    } else {
865        acquireFence->waitForever("HWComposer::fbPost");
866        return mFbDev->post(mFbDev, buffer->handle);
867    }
868}
869
870int HWComposer::fbCompositionComplete() {
871    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
872        return NO_ERROR;
873
874    if (mFbDev->compositionComplete) {
875        return mFbDev->compositionComplete(mFbDev);
876    } else {
877        return INVALID_OPERATION;
878    }
879}
880
881void HWComposer::fbDump(String8& result) {
882    if (mFbDev && mFbDev->common.version >= 1 && mFbDev->dump) {
883        const size_t SIZE = 4096;
884        char buffer[SIZE];
885        mFbDev->dump(mFbDev, buffer, SIZE);
886        result.append(buffer);
887    }
888}
889
890status_t HWComposer::setOutputBuffer(int32_t id, const sp<Fence>& acquireFence,
891        const sp<GraphicBuffer>& buf) {
892    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
893        return BAD_INDEX;
894    if (id < VIRTUAL_DISPLAY_ID_BASE)
895        return INVALID_OPERATION;
896
897    DisplayData& disp(mDisplayData[id]);
898    disp.outbufHandle = buf->handle;
899    disp.outbufAcquireFence = acquireFence;
900    return NO_ERROR;
901}
902
903sp<Fence> HWComposer::getLastRetireFence(int32_t id) const {
904    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
905        return Fence::NO_FENCE;
906    return mDisplayData[id].lastRetireFence;
907}
908
909status_t HWComposer::setCursorPositionAsync(int32_t id, const Rect& pos)
910{
911    if (mHwc->setCursorPositionAsync) {
912        return (status_t)mHwc->setCursorPositionAsync(mHwc, id, pos.left, pos.top);
913    }
914    else {
915        return NO_ERROR;
916    }
917}
918
919/*
920 * Helper template to implement a concrete HWCLayer
921 * This holds the pointer to the concrete hwc layer type
922 * and implements the "iterable" side of HWCLayer.
923 */
924template<typename CONCRETE, typename HWCTYPE>
925class Iterable : public HWComposer::HWCLayer {
926protected:
927    HWCTYPE* const mLayerList;
928    HWCTYPE* mCurrentLayer;
929    Iterable(HWCTYPE* layer) : mLayerList(layer), mCurrentLayer(layer),
930            mIndex(0) { }
931    inline HWCTYPE const * getLayer() const { return mCurrentLayer; }
932    inline HWCTYPE* getLayer() { return mCurrentLayer; }
933    virtual ~Iterable() { }
934    size_t mIndex;
935private:
936    // returns a copy of ourselves
937    virtual HWComposer::HWCLayer* dup() {
938        return new CONCRETE( static_cast<const CONCRETE&>(*this) );
939    }
940    virtual status_t setLayer(size_t index) {
941        mIndex = index;
942        mCurrentLayer = &mLayerList[index];
943        return NO_ERROR;
944    }
945};
946
947/*
948 * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_1_0.
949 * This implements the HWCLayer side of HWCIterableLayer.
950 */
951class HWCLayerVersion1 : public Iterable<HWCLayerVersion1, hwc_layer_1_t> {
952    struct hwc_composer_device_1* mHwc;
953public:
954    HWCLayerVersion1(struct hwc_composer_device_1* hwc, hwc_layer_1_t* layer,
955            Vector<Region>* visibleRegions,
956            Vector<Region>* surfaceDamageRegions)
957        : Iterable<HWCLayerVersion1, hwc_layer_1_t>(layer), mHwc(hwc),
958          mVisibleRegions(visibleRegions),
959          mSurfaceDamageRegions(surfaceDamageRegions) {}
960
961    virtual int32_t getCompositionType() const {
962        return getLayer()->compositionType;
963    }
964    virtual uint32_t getHints() const {
965        return getLayer()->hints;
966    }
967    virtual sp<Fence> getAndResetReleaseFence() {
968        int fd = getLayer()->releaseFenceFd;
969        getLayer()->releaseFenceFd = -1;
970        return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
971    }
972    virtual void setAcquireFenceFd(int fenceFd) {
973        getLayer()->acquireFenceFd = fenceFd;
974    }
975    virtual void setPerFrameDefaultState() {
976        //getLayer()->compositionType = HWC_FRAMEBUFFER;
977    }
978    virtual void setPlaneAlpha(uint8_t alpha) {
979        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_2)) {
980            getLayer()->planeAlpha = alpha;
981        } else {
982            if (alpha < 0xFF) {
983                getLayer()->flags |= HWC_SKIP_LAYER;
984            }
985        }
986    }
987    virtual void setDefaultState() {
988        hwc_layer_1_t* const l = getLayer();
989        l->compositionType = HWC_FRAMEBUFFER;
990        l->hints = 0;
991        l->flags = HWC_SKIP_LAYER;
992        l->handle = 0;
993        l->transform = 0;
994        l->blending = HWC_BLENDING_NONE;
995        l->visibleRegionScreen.numRects = 0;
996        l->visibleRegionScreen.rects = NULL;
997        l->acquireFenceFd = -1;
998        l->releaseFenceFd = -1;
999        l->planeAlpha = 0xFF;
1000    }
1001    virtual void setSkip(bool skip) {
1002        if (skip) {
1003            getLayer()->flags |= HWC_SKIP_LAYER;
1004        } else {
1005            getLayer()->flags &= ~HWC_SKIP_LAYER;
1006        }
1007    }
1008    virtual void setIsCursorLayerHint(bool isCursor) {
1009        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
1010            if (isCursor) {
1011                getLayer()->flags |= HWC_IS_CURSOR_LAYER;
1012            }
1013            else {
1014                getLayer()->flags &= ~HWC_IS_CURSOR_LAYER;
1015            }
1016        }
1017    }
1018    virtual void setBlending(uint32_t blending) {
1019        getLayer()->blending = blending;
1020    }
1021    virtual void setTransform(uint32_t transform) {
1022        getLayer()->transform = transform;
1023    }
1024    virtual void setFrame(const Rect& frame) {
1025        getLayer()->displayFrame = reinterpret_cast<hwc_rect_t const&>(frame);
1026    }
1027    virtual void setCrop(const FloatRect& crop) {
1028        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
1029            getLayer()->sourceCropf = reinterpret_cast<hwc_frect_t const&>(crop);
1030        } else {
1031            /*
1032             * Since h/w composer didn't support a flot crop rect before version 1.3,
1033             * using integer coordinates instead produces a different output from the GL code in
1034             * Layer::drawWithOpenGL(). The difference can be large if the buffer crop to
1035             * window size ratio is large and a window crop is defined
1036             * (i.e.: if we scale the buffer a lot and we also crop it with a window crop).
1037             */
1038            hwc_rect_t& r = getLayer()->sourceCrop;
1039            r.left  = int(ceilf(crop.left));
1040            r.top   = int(ceilf(crop.top));
1041            r.right = int(floorf(crop.right));
1042            r.bottom= int(floorf(crop.bottom));
1043        }
1044    }
1045    virtual void setVisibleRegionScreen(const Region& reg) {
1046        hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
1047        mVisibleRegions->editItemAt(mIndex) = reg;
1048        visibleRegion.rects = reinterpret_cast<hwc_rect_t const *>(
1049                mVisibleRegions->itemAt(mIndex).getArray(
1050                &visibleRegion.numRects));
1051    }
1052    virtual void setSurfaceDamage(const Region& reg) {
1053        if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_5)) {
1054            return;
1055        }
1056        hwc_region_t& surfaceDamage = getLayer()->surfaceDamage;
1057        // We encode default full-screen damage as INVALID_RECT upstream, but as
1058        // 0 rects for HWComposer
1059        if (reg.isRect() && reg.getBounds() == Rect::INVALID_RECT) {
1060            surfaceDamage.numRects = 0;
1061            surfaceDamage.rects = NULL;
1062            return;
1063        }
1064        mSurfaceDamageRegions->editItemAt(mIndex) = reg;
1065        surfaceDamage.rects = reinterpret_cast<hwc_rect_t const *>(
1066                mSurfaceDamageRegions->itemAt(mIndex).getArray(
1067                &surfaceDamage.numRects));
1068    }
1069    virtual void setSidebandStream(const sp<NativeHandle>& stream) {
1070        ALOG_ASSERT(stream->handle() != NULL);
1071        getLayer()->compositionType = HWC_SIDEBAND;
1072        getLayer()->sidebandStream = stream->handle();
1073    }
1074    virtual void setBuffer(const sp<GraphicBuffer>& buffer) {
1075        if (buffer == 0 || buffer->handle == 0) {
1076            getLayer()->compositionType = HWC_FRAMEBUFFER;
1077            getLayer()->flags |= HWC_SKIP_LAYER;
1078            getLayer()->handle = 0;
1079        } else {
1080            if (getLayer()->compositionType == HWC_SIDEBAND) {
1081                // If this was a sideband layer but the stream was removed, reset
1082                // it to FRAMEBUFFER. The HWC can change it to OVERLAY in prepare.
1083                getLayer()->compositionType = HWC_FRAMEBUFFER;
1084            }
1085            getLayer()->handle = buffer->handle;
1086        }
1087    }
1088    virtual void onDisplayed() {
1089        getLayer()->acquireFenceFd = -1;
1090    }
1091
1092protected:
1093    // Pointers to the vectors of Region backing-memory held in DisplayData.
1094    // Only the Region at mIndex corresponds to this Layer.
1095    Vector<Region>* mVisibleRegions;
1096    Vector<Region>* mSurfaceDamageRegions;
1097};
1098
1099/*
1100 * returns an iterator initialized at a given index in the layer list
1101 */
1102HWComposer::LayerListIterator HWComposer::getLayerIterator(int32_t id, size_t index) {
1103    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
1104        return LayerListIterator();
1105    }
1106    DisplayData& disp(mDisplayData[id]);
1107    if (!mHwc || !disp.list || index > disp.list->numHwLayers) {
1108        return LayerListIterator();
1109    }
1110    if (disp.visibleRegions.size() < disp.list->numHwLayers) {
1111        disp.visibleRegions.resize(disp.list->numHwLayers);
1112    }
1113    if (disp.surfaceDamageRegions.size() < disp.list->numHwLayers) {
1114        disp.surfaceDamageRegions.resize(disp.list->numHwLayers);
1115    }
1116    return LayerListIterator(new HWCLayerVersion1(mHwc, disp.list->hwLayers,
1117            &disp.visibleRegions, &disp.surfaceDamageRegions), index);
1118}
1119
1120/*
1121 * returns an iterator on the beginning of the layer list
1122 */
1123HWComposer::LayerListIterator HWComposer::begin(int32_t id) {
1124    return getLayerIterator(id, 0);
1125}
1126
1127/*
1128 * returns an iterator on the end of the layer list
1129 */
1130HWComposer::LayerListIterator HWComposer::end(int32_t id) {
1131    size_t numLayers = 0;
1132    if (uint32_t(id) <= 31 && mAllocatedDisplayIDs.hasBit(id)) {
1133        const DisplayData& disp(mDisplayData[id]);
1134        if (mHwc && disp.list) {
1135            numLayers = disp.list->numHwLayers;
1136            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
1137                // with HWC 1.1, the last layer is always the HWC_FRAMEBUFFER_TARGET,
1138                // which we ignore when iterating through the layer list.
1139                ALOGE_IF(!numLayers, "mDisplayData[%d].list->numHwLayers is 0", id);
1140                if (numLayers) {
1141                    numLayers--;
1142                }
1143            }
1144        }
1145    }
1146    return getLayerIterator(id, numLayers);
1147}
1148
1149// Converts a PixelFormat to a human-readable string.  Max 11 chars.
1150// (Could use a table of prefab String8 objects.)
1151static String8 getFormatStr(PixelFormat format) {
1152    switch (format) {
1153    case PIXEL_FORMAT_RGBA_8888:    return String8("RGBA_8888");
1154    case PIXEL_FORMAT_RGBX_8888:    return String8("RGBx_8888");
1155    case PIXEL_FORMAT_RGB_888:      return String8("RGB_888");
1156    case PIXEL_FORMAT_RGB_565:      return String8("RGB_565");
1157    case PIXEL_FORMAT_BGRA_8888:    return String8("BGRA_8888");
1158    case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
1159                                    return String8("ImplDef");
1160    default:
1161        String8 result;
1162        result.appendFormat("? %08x", format);
1163        return result;
1164    }
1165}
1166
1167void HWComposer::dump(String8& result) const {
1168    Mutex::Autolock _l(mDisplayLock);
1169    if (mHwc) {
1170        result.appendFormat("Hardware Composer state (version %08x):\n", hwcApiVersion(mHwc));
1171        result.appendFormat("  mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync);
1172        for (size_t i=0 ; i<mNumDisplays ; i++) {
1173            const DisplayData& disp(mDisplayData[i]);
1174            if (!disp.connected)
1175                continue;
1176
1177            const Vector< sp<Layer> >& visibleLayersSortedByZ =
1178                    mFlinger->getLayerSortedByZForHwcDisplay(i);
1179
1180
1181            result.appendFormat("  Display[%zd] configurations (* current):\n", i);
1182            for (size_t c = 0; c < disp.configs.size(); ++c) {
1183                const DisplayConfig& config(disp.configs[c]);
1184                result.appendFormat("    %s%zd: %ux%u, xdpi=%f, ydpi=%f"
1185                        ", refresh=%" PRId64 ", colorTransform=%d\n",
1186                        c == disp.currentConfig ? "* " : "", c,
1187                        config.width, config.height, config.xdpi, config.ydpi,
1188                        config.refresh, config.colorTransform);
1189            }
1190
1191            if (disp.list) {
1192                result.appendFormat(
1193                        "  numHwLayers=%zu, flags=%08x\n",
1194                        disp.list->numHwLayers, disp.list->flags);
1195
1196                result.append(
1197                        "    type   |  handle  | hint | flag | tr | blnd |   format    |     source crop (l,t,r,b)      |          frame         | name \n"
1198                        "-----------+----------+------+------+----+------+-------------+--------------------------------+------------------------+------\n");
1199                //      " _________ | ________ | ____ | ____ | __ | ____ | ___________ |_____._,_____._,_____._,_____._ |_____,_____,_____,_____ | ___...
1200                for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
1201                    const hwc_layer_1_t&l = disp.list->hwLayers[i];
1202                    int32_t format = -1;
1203                    String8 name("unknown");
1204
1205                    if (i < visibleLayersSortedByZ.size()) {
1206                        const sp<Layer>& layer(visibleLayersSortedByZ[i]);
1207                        const sp<GraphicBuffer>& buffer(
1208                                layer->getActiveBuffer());
1209                        if (buffer != NULL) {
1210                            format = buffer->getPixelFormat();
1211                        }
1212                        name = layer->getName();
1213                    }
1214
1215                    int type = l.compositionType;
1216                    if (type == HWC_FRAMEBUFFER_TARGET) {
1217                        name = "HWC_FRAMEBUFFER_TARGET";
1218                        format = disp.format;
1219                    }
1220
1221                    static char const* compositionTypeName[] = {
1222                            "GLES",
1223                            "HWC",
1224                            "BKGND",
1225                            "FB TARGET",
1226                            "SIDEBAND",
1227                            "HWC_CURSOR",
1228                            "UNKNOWN"};
1229                    if (type >= NELEM(compositionTypeName))
1230                        type = NELEM(compositionTypeName) - 1;
1231
1232                    String8 formatStr = getFormatStr(format);
1233                    if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
1234                        result.appendFormat(
1235                                " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7.1f,%7.1f,%7.1f,%7.1f |%5d,%5d,%5d,%5d | %s\n",
1236                                        compositionTypeName[type],
1237                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
1238                                        l.sourceCropf.left, l.sourceCropf.top, l.sourceCropf.right, l.sourceCropf.bottom,
1239                                        l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1240                                        name.string());
1241                    } else {
1242                        result.appendFormat(
1243                                " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7d,%7d,%7d,%7d |%5d,%5d,%5d,%5d | %s\n",
1244                                        compositionTypeName[type],
1245                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
1246                                        l.sourceCrop.left, l.sourceCrop.top, l.sourceCrop.right, l.sourceCrop.bottom,
1247                                        l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1248                                        name.string());
1249                    }
1250                }
1251            }
1252        }
1253    }
1254
1255    if (mHwc && mHwc->dump) {
1256        const size_t SIZE = 4096;
1257        char buffer[SIZE];
1258        mHwc->dump(mHwc, buffer, SIZE);
1259        result.append(buffer);
1260    }
1261}
1262
1263// ---------------------------------------------------------------------------
1264
1265HWComposer::VSyncThread::VSyncThread(HWComposer& hwc)
1266    : mHwc(hwc), mEnabled(false),
1267      mNextFakeVSync(0),
1268      mRefreshPeriod(hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY))
1269{
1270}
1271
1272void HWComposer::VSyncThread::setEnabled(bool enabled) {
1273    Mutex::Autolock _l(mLock);
1274    if (mEnabled != enabled) {
1275        mEnabled = enabled;
1276        mCondition.signal();
1277    }
1278}
1279
1280void HWComposer::VSyncThread::onFirstRef() {
1281    run("VSyncThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
1282}
1283
1284bool HWComposer::VSyncThread::threadLoop() {
1285    { // scope for lock
1286        Mutex::Autolock _l(mLock);
1287        while (!mEnabled) {
1288            mCondition.wait(mLock);
1289        }
1290    }
1291
1292    const nsecs_t period = mRefreshPeriod;
1293    const nsecs_t now = systemTime(CLOCK_MONOTONIC);
1294    nsecs_t next_vsync = mNextFakeVSync;
1295    nsecs_t sleep = next_vsync - now;
1296    if (sleep < 0) {
1297        // we missed, find where the next vsync should be
1298        sleep = (period - ((now - next_vsync) % period));
1299        next_vsync = now + sleep;
1300    }
1301    mNextFakeVSync = next_vsync + period;
1302
1303    struct timespec spec;
1304    spec.tv_sec  = next_vsync / 1000000000;
1305    spec.tv_nsec = next_vsync % 1000000000;
1306
1307    int err;
1308    do {
1309        err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
1310    } while (err<0 && errno == EINTR);
1311
1312    if (err == 0) {
1313        mHwc.mEventHandler.onVSyncReceived(0, next_vsync);
1314    }
1315
1316    return true;
1317}
1318
1319HWComposer::DisplayData::DisplayData()
1320:   configs(),
1321    currentConfig(0),
1322    format(HAL_PIXEL_FORMAT_RGBA_8888),
1323    connected(false),
1324    hasFbComp(false), hasOvComp(false),
1325    capacity(0), list(NULL),
1326    framebufferTarget(NULL), fbTargetHandle(0),
1327    lastRetireFence(Fence::NO_FENCE), lastDisplayFence(Fence::NO_FENCE),
1328    outbufHandle(NULL), outbufAcquireFence(Fence::NO_FENCE),
1329    events(0)
1330{}
1331
1332HWComposer::DisplayData::~DisplayData() {
1333    free(list);
1334}
1335
1336// ---------------------------------------------------------------------------
1337}; // namespace android
1338