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