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