HWComposer.cpp revision 8f63c2049b93819c41d390fc4222b9307e3a61c7
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        char tag[16];
288        snprintf(tag, sizeof(tag), "VSYNC_%1u", disp);
289        ATRACE_INT(tag, ++mVSyncCounts[disp] & 1);
290
291        mEventHandler.onVSyncReceived(disp, timestamp);
292        Mutex::Autolock _l(mLock);
293        mLastHwVSync[disp] = timestamp;
294    }
295}
296
297void HWComposer::hotplug(int disp, int connected) {
298    if (disp == HWC_DISPLAY_PRIMARY || disp >= VIRTUAL_DISPLAY_ID_BASE) {
299        ALOGE("hotplug event received for invalid display: disp=%d connected=%d",
300                disp, connected);
301        return;
302    }
303    queryDisplayProperties(disp);
304    mEventHandler.onHotplugReceived(disp, bool(connected));
305}
306
307static float getDefaultDensity(uint32_t height) {
308    if (height >= 1080) return ACONFIGURATION_DENSITY_XHIGH;
309    else                return ACONFIGURATION_DENSITY_TV;
310}
311
312static const uint32_t DISPLAY_ATTRIBUTES[] = {
313    HWC_DISPLAY_VSYNC_PERIOD,
314    HWC_DISPLAY_WIDTH,
315    HWC_DISPLAY_HEIGHT,
316    HWC_DISPLAY_DPI_X,
317    HWC_DISPLAY_DPI_Y,
318    HWC_DISPLAY_NO_ATTRIBUTE,
319};
320#define NUM_DISPLAY_ATTRIBUTES (sizeof(DISPLAY_ATTRIBUTES) / sizeof(DISPLAY_ATTRIBUTES)[0])
321
322status_t HWComposer::queryDisplayProperties(int disp) {
323
324    LOG_ALWAYS_FATAL_IF(!mHwc || !hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
325
326    // use zero as default value for unspecified attributes
327    int32_t values[NUM_DISPLAY_ATTRIBUTES - 1];
328    memset(values, 0, sizeof(values));
329
330    uint32_t config;
331    size_t numConfigs = 1;
332    status_t err = mHwc->getDisplayConfigs(mHwc, disp, &config, &numConfigs);
333    if (err != NO_ERROR) {
334        // this can happen if an unpluggable display is not connected
335        mDisplayData[disp].connected = false;
336        return err;
337    }
338
339    err = mHwc->getDisplayAttributes(mHwc, disp, config, DISPLAY_ATTRIBUTES, values);
340    if (err != NO_ERROR) {
341        // we can't get this display's info. turn it off.
342        mDisplayData[disp].connected = false;
343        return err;
344    }
345
346    int32_t w = 0, h = 0;
347    for (size_t i = 0; i < NUM_DISPLAY_ATTRIBUTES - 1; i++) {
348        switch (DISPLAY_ATTRIBUTES[i]) {
349        case HWC_DISPLAY_VSYNC_PERIOD:
350            mDisplayData[disp].refresh = nsecs_t(values[i]);
351            break;
352        case HWC_DISPLAY_WIDTH:
353            mDisplayData[disp].width = values[i];
354            break;
355        case HWC_DISPLAY_HEIGHT:
356            mDisplayData[disp].height = values[i];
357            break;
358        case HWC_DISPLAY_DPI_X:
359            mDisplayData[disp].xdpi = values[i] / 1000.0f;
360            break;
361        case HWC_DISPLAY_DPI_Y:
362            mDisplayData[disp].ydpi = values[i] / 1000.0f;
363            break;
364        default:
365            ALOG_ASSERT(false, "unknown display attribute[%d] %#x",
366                    i, DISPLAY_ATTRIBUTES[i]);
367            break;
368        }
369    }
370
371    // FIXME: what should we set the format to?
372    mDisplayData[disp].format = HAL_PIXEL_FORMAT_RGBA_8888;
373    mDisplayData[disp].connected = true;
374    if (mDisplayData[disp].xdpi == 0.0f || mDisplayData[disp].ydpi == 0.0f) {
375        float dpi = getDefaultDensity(h);
376        mDisplayData[disp].xdpi = dpi;
377        mDisplayData[disp].ydpi = dpi;
378    }
379    return NO_ERROR;
380}
381
382status_t HWComposer::setVirtualDisplayProperties(int32_t id,
383        uint32_t w, uint32_t h, uint32_t format) {
384    if (id < VIRTUAL_DISPLAY_ID_BASE || id >= int32_t(mNumDisplays) ||
385            !mAllocatedDisplayIDs.hasBit(id)) {
386        return BAD_INDEX;
387    }
388    mDisplayData[id].width = w;
389    mDisplayData[id].height = h;
390    mDisplayData[id].format = format;
391    mDisplayData[id].xdpi = mDisplayData[id].ydpi = getDefaultDensity(h);
392    return NO_ERROR;
393}
394
395int32_t HWComposer::allocateDisplayId() {
396    if (mAllocatedDisplayIDs.count() >= mNumDisplays) {
397        return NO_MEMORY;
398    }
399    int32_t id = mAllocatedDisplayIDs.firstUnmarkedBit();
400    mAllocatedDisplayIDs.markBit(id);
401    mDisplayData[id].connected = true;
402    return id;
403}
404
405status_t HWComposer::freeDisplayId(int32_t id) {
406    if (id < NUM_BUILTIN_DISPLAYS) {
407        // cannot free the reserved IDs
408        return BAD_VALUE;
409    }
410    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
411        return BAD_INDEX;
412    }
413    mAllocatedDisplayIDs.clearBit(id);
414    mDisplayData[id].connected = false;
415    return NO_ERROR;
416}
417
418nsecs_t HWComposer::getRefreshPeriod(int disp) const {
419    return mDisplayData[disp].refresh;
420}
421
422nsecs_t HWComposer::getRefreshTimestamp(int disp) const {
423    // this returns the last refresh timestamp.
424    // if the last one is not available, we estimate it based on
425    // the refresh period and whatever closest timestamp we have.
426    Mutex::Autolock _l(mLock);
427    nsecs_t now = systemTime(CLOCK_MONOTONIC);
428    return now - ((now - mLastHwVSync[disp]) %  mDisplayData[disp].refresh);
429}
430
431sp<Fence> HWComposer::getDisplayFence(int disp) const {
432    return mDisplayData[disp].lastDisplayFence;
433}
434
435uint32_t HWComposer::getWidth(int disp) const {
436    return mDisplayData[disp].width;
437}
438
439uint32_t HWComposer::getHeight(int disp) const {
440    return mDisplayData[disp].height;
441}
442
443uint32_t HWComposer::getFormat(int disp) const {
444    return mDisplayData[disp].format;
445}
446
447float HWComposer::getDpiX(int disp) const {
448    return mDisplayData[disp].xdpi;
449}
450
451float HWComposer::getDpiY(int disp) const {
452    return mDisplayData[disp].ydpi;
453}
454
455bool HWComposer::isConnected(int disp) const {
456    return mDisplayData[disp].connected;
457}
458
459void HWComposer::eventControl(int disp, int event, int enabled) {
460    if (uint32_t(disp)>31 || !mAllocatedDisplayIDs.hasBit(disp)) {
461        ALOGD("eventControl ignoring event %d on unallocated disp %d (en=%d)",
462              event, disp, enabled);
463        return;
464    }
465    if (event != EVENT_VSYNC) {
466        ALOGW("eventControl got unexpected event %d (disp=%d en=%d)",
467              event, disp, enabled);
468        return;
469    }
470    status_t err = NO_ERROR;
471    if (mHwc && !mDebugForceFakeVSync) {
472        // NOTE: we use our own internal lock here because we have to call
473        // into the HWC with the lock held, and we want to make sure
474        // that even if HWC blocks (which it shouldn't), it won't
475        // affect other threads.
476        Mutex::Autolock _l(mEventControlLock);
477        const int32_t eventBit = 1UL << event;
478        const int32_t newValue = enabled ? eventBit : 0;
479        const int32_t oldValue = mDisplayData[disp].events & eventBit;
480        if (newValue != oldValue) {
481            ATRACE_CALL();
482            err = mHwc->eventControl(mHwc, disp, event, enabled);
483            if (!err) {
484                int32_t& events(mDisplayData[disp].events);
485                events = (events & ~eventBit) | newValue;
486            }
487        }
488        // error here should not happen -- not sure what we should
489        // do if it does.
490        ALOGE_IF(err, "eventControl(%d, %d) failed %s",
491                event, enabled, strerror(-err));
492    }
493
494    if (err == NO_ERROR && mVSyncThread != NULL) {
495        mVSyncThread->setEnabled(enabled);
496    }
497}
498
499status_t HWComposer::createWorkList(int32_t id, size_t numLayers) {
500    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
501        return BAD_INDEX;
502    }
503
504    if (mHwc) {
505        DisplayData& disp(mDisplayData[id]);
506        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
507            // we need space for the HWC_FRAMEBUFFER_TARGET
508            numLayers++;
509        }
510        if (disp.capacity < numLayers || disp.list == NULL) {
511            size_t size = sizeof(hwc_display_contents_1_t)
512                    + numLayers * sizeof(hwc_layer_1_t);
513            free(disp.list);
514            disp.list = (hwc_display_contents_1_t*)malloc(size);
515            disp.capacity = numLayers;
516        }
517        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
518            disp.framebufferTarget = &disp.list->hwLayers[numLayers - 1];
519            memset(disp.framebufferTarget, 0, sizeof(hwc_layer_1_t));
520            const hwc_rect_t r = { 0, 0, (int) disp.width, (int) disp.height };
521            disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
522            disp.framebufferTarget->hints = 0;
523            disp.framebufferTarget->flags = 0;
524            disp.framebufferTarget->handle = disp.fbTargetHandle;
525            disp.framebufferTarget->transform = 0;
526            disp.framebufferTarget->blending = HWC_BLENDING_PREMULT;
527            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
528                disp.framebufferTarget->sourceCropf.left = 0;
529                disp.framebufferTarget->sourceCropf.top = 0;
530                disp.framebufferTarget->sourceCropf.right = disp.width;
531                disp.framebufferTarget->sourceCropf.bottom = disp.height;
532            } else {
533                disp.framebufferTarget->sourceCrop = r;
534            }
535            disp.framebufferTarget->displayFrame = r;
536            disp.framebufferTarget->visibleRegionScreen.numRects = 1;
537            disp.framebufferTarget->visibleRegionScreen.rects =
538                &disp.framebufferTarget->displayFrame;
539            disp.framebufferTarget->acquireFenceFd = -1;
540            disp.framebufferTarget->releaseFenceFd = -1;
541            disp.framebufferTarget->planeAlpha = 0xFF;
542        }
543        disp.list->retireFenceFd = -1;
544        disp.list->flags = HWC_GEOMETRY_CHANGED;
545        disp.list->numHwLayers = numLayers;
546    }
547    return NO_ERROR;
548}
549
550status_t HWComposer::setFramebufferTarget(int32_t id,
551        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buf) {
552    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
553        return BAD_INDEX;
554    }
555    DisplayData& disp(mDisplayData[id]);
556    if (!disp.framebufferTarget) {
557        // this should never happen, but apparently eglCreateWindowSurface()
558        // triggers a Surface::queueBuffer()  on some
559        // devices (!?) -- log and ignore.
560        ALOGE("HWComposer: framebufferTarget is null");
561        return NO_ERROR;
562    }
563
564    int acquireFenceFd = -1;
565    if (acquireFence->isValid()) {
566        acquireFenceFd = acquireFence->dup();
567    }
568
569    // ALOGD("fbPost: handle=%p, fence=%d", buf->handle, acquireFenceFd);
570    disp.fbTargetHandle = buf->handle;
571    disp.framebufferTarget->handle = disp.fbTargetHandle;
572    disp.framebufferTarget->acquireFenceFd = acquireFenceFd;
573    return NO_ERROR;
574}
575
576status_t HWComposer::prepare() {
577    for (size_t i=0 ; i<mNumDisplays ; i++) {
578        DisplayData& disp(mDisplayData[i]);
579        if (disp.framebufferTarget) {
580            // make sure to reset the type to HWC_FRAMEBUFFER_TARGET
581            // DO NOT reset the handle field to NULL, because it's possible
582            // that we have nothing to redraw (eg: eglSwapBuffers() not called)
583            // in which case, we should continue to use the same buffer.
584            LOG_FATAL_IF(disp.list == NULL);
585            disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
586        }
587        if (!disp.connected && disp.list != NULL) {
588            ALOGW("WARNING: disp %d: connected, non-null list, layers=%d",
589                  i, disp.list->numHwLayers);
590        }
591        mLists[i] = disp.list;
592        if (mLists[i]) {
593            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
594                mLists[i]->outbuf = NULL;
595                mLists[i]->outbufAcquireFenceFd = -1;
596            } else if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
597                // garbage data to catch improper use
598                mLists[i]->dpy = (hwc_display_t)0xDEADBEEF;
599                mLists[i]->sur = (hwc_surface_t)0xDEADBEEF;
600            } else {
601                mLists[i]->dpy = EGL_NO_DISPLAY;
602                mLists[i]->sur = EGL_NO_SURFACE;
603            }
604        }
605    }
606
607    int err = mHwc->prepare(mHwc, mNumDisplays, mLists);
608    ALOGE_IF(err, "HWComposer: prepare failed (%s)", strerror(-err));
609
610    if (err == NO_ERROR) {
611        // here we're just making sure that "skip" layers are set
612        // to HWC_FRAMEBUFFER and we're also counting how many layers
613        // we have of each type.
614        for (size_t i=0 ; i<mNumDisplays ; i++) {
615            DisplayData& disp(mDisplayData[i]);
616            disp.hasFbComp = false;
617            disp.hasOvComp = false;
618            if (disp.list) {
619                for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
620                    hwc_layer_1_t& l = disp.list->hwLayers[i];
621
622                    //ALOGD("prepare: %d, type=%d, handle=%p",
623                    //        i, l.compositionType, l.handle);
624
625                    if (l.flags & HWC_SKIP_LAYER) {
626                        l.compositionType = HWC_FRAMEBUFFER;
627                    }
628                    if (l.compositionType == HWC_FRAMEBUFFER) {
629                        disp.hasFbComp = true;
630                    }
631                    if (l.compositionType == HWC_OVERLAY) {
632                        disp.hasOvComp = true;
633                    }
634                }
635            }
636        }
637    }
638    return (status_t)err;
639}
640
641bool HWComposer::hasHwcComposition(int32_t id) const {
642    if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
643        return false;
644    return mDisplayData[id].hasOvComp;
645}
646
647bool HWComposer::hasGlesComposition(int32_t id) const {
648    if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
649        return true;
650    return mDisplayData[id].hasFbComp;
651}
652
653sp<Fence> HWComposer::getAndResetReleaseFence(int32_t id) {
654    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
655        return Fence::NO_FENCE;
656
657    int fd = INVALID_OPERATION;
658    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
659        const DisplayData& disp(mDisplayData[id]);
660        if (disp.framebufferTarget) {
661            fd = disp.framebufferTarget->releaseFenceFd;
662            disp.framebufferTarget->acquireFenceFd = -1;
663            disp.framebufferTarget->releaseFenceFd = -1;
664        }
665    }
666    return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
667}
668
669status_t HWComposer::commit() {
670    int err = NO_ERROR;
671    if (mHwc) {
672        if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
673            // On version 1.0, the OpenGL ES target surface is communicated
674            // by the (dpy, sur) fields and we are guaranteed to have only
675            // a single display.
676            mLists[0]->dpy = eglGetCurrentDisplay();
677            mLists[0]->sur = eglGetCurrentSurface(EGL_DRAW);
678        }
679
680        for (size_t i=VIRTUAL_DISPLAY_ID_BASE; i<mNumDisplays; i++) {
681            DisplayData& disp(mDisplayData[i]);
682            if (disp.outbufHandle) {
683                mLists[i]->outbuf = disp.outbufHandle;
684                mLists[i]->outbufAcquireFenceFd =
685                        disp.outbufAcquireFence->dup();
686            }
687        }
688
689        err = mHwc->set(mHwc, mNumDisplays, mLists);
690
691        for (size_t i=0 ; i<mNumDisplays ; i++) {
692            DisplayData& disp(mDisplayData[i]);
693            disp.lastDisplayFence = disp.lastRetireFence;
694            disp.lastRetireFence = Fence::NO_FENCE;
695            if (disp.list) {
696                if (disp.list->retireFenceFd != -1) {
697                    disp.lastRetireFence = new Fence(disp.list->retireFenceFd);
698                    disp.list->retireFenceFd = -1;
699                }
700                disp.list->flags &= ~HWC_GEOMETRY_CHANGED;
701            }
702        }
703    }
704    return (status_t)err;
705}
706
707status_t HWComposer::release(int disp) {
708    LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
709    if (mHwc) {
710        eventControl(disp, HWC_EVENT_VSYNC, 0);
711        return (status_t)mHwc->blank(mHwc, disp, 1);
712    }
713    return NO_ERROR;
714}
715
716status_t HWComposer::acquire(int disp) {
717    LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
718    if (mHwc) {
719        return (status_t)mHwc->blank(mHwc, disp, 0);
720    }
721    return NO_ERROR;
722}
723
724void HWComposer::disconnectDisplay(int disp) {
725    LOG_ALWAYS_FATAL_IF(disp < 0 || disp == HWC_DISPLAY_PRIMARY);
726    DisplayData& dd(mDisplayData[disp]);
727    free(dd.list);
728    dd.list = NULL;
729    dd.framebufferTarget = NULL;    // points into dd.list
730    dd.fbTargetHandle = NULL;
731    dd.outbufHandle = NULL;
732    dd.lastRetireFence = Fence::NO_FENCE;
733    dd.lastDisplayFence = Fence::NO_FENCE;
734    dd.outbufAcquireFence = Fence::NO_FENCE;
735}
736
737int HWComposer::getVisualID() const {
738    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
739        // FIXME: temporary hack until HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED
740        // is supported by the implementation. we can only be in this case
741        // if we have HWC 1.1
742        return HAL_PIXEL_FORMAT_RGBA_8888;
743        //return HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
744    } else {
745        return mFbDev->format;
746    }
747}
748
749bool HWComposer::supportsFramebufferTarget() const {
750    return (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
751}
752
753int HWComposer::fbPost(int32_t id,
754        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buffer) {
755    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
756        return setFramebufferTarget(id, acquireFence, buffer);
757    } else {
758        acquireFence->waitForever("HWComposer::fbPost");
759        return mFbDev->post(mFbDev, buffer->handle);
760    }
761}
762
763int HWComposer::fbCompositionComplete() {
764    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
765        return NO_ERROR;
766
767    if (mFbDev->compositionComplete) {
768        return mFbDev->compositionComplete(mFbDev);
769    } else {
770        return INVALID_OPERATION;
771    }
772}
773
774void HWComposer::fbDump(String8& result) {
775    if (mFbDev && mFbDev->common.version >= 1 && mFbDev->dump) {
776        const size_t SIZE = 4096;
777        char buffer[SIZE];
778        mFbDev->dump(mFbDev, buffer, SIZE);
779        result.append(buffer);
780    }
781}
782
783status_t HWComposer::setOutputBuffer(int32_t id, const sp<Fence>& acquireFence,
784        const sp<GraphicBuffer>& buf) {
785    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
786        return BAD_INDEX;
787    if (id < VIRTUAL_DISPLAY_ID_BASE)
788        return INVALID_OPERATION;
789
790    DisplayData& disp(mDisplayData[id]);
791    disp.outbufHandle = buf->handle;
792    disp.outbufAcquireFence = acquireFence;
793    return NO_ERROR;
794}
795
796sp<Fence> HWComposer::getLastRetireFence(int32_t id) {
797    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
798        return Fence::NO_FENCE;
799    return mDisplayData[id].lastRetireFence;
800}
801
802/*
803 * Helper template to implement a concrete HWCLayer
804 * This holds the pointer to the concrete hwc layer type
805 * and implements the "iterable" side of HWCLayer.
806 */
807template<typename CONCRETE, typename HWCTYPE>
808class Iterable : public HWComposer::HWCLayer {
809protected:
810    HWCTYPE* const mLayerList;
811    HWCTYPE* mCurrentLayer;
812    Iterable(HWCTYPE* layer) : mLayerList(layer), mCurrentLayer(layer) { }
813    inline HWCTYPE const * getLayer() const { return mCurrentLayer; }
814    inline HWCTYPE* getLayer() { return mCurrentLayer; }
815    virtual ~Iterable() { }
816private:
817    // returns a copy of ourselves
818    virtual HWComposer::HWCLayer* dup() {
819        return new CONCRETE( static_cast<const CONCRETE&>(*this) );
820    }
821    virtual status_t setLayer(size_t index) {
822        mCurrentLayer = &mLayerList[index];
823        return NO_ERROR;
824    }
825};
826
827/*
828 * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_1_0.
829 * This implements the HWCLayer side of HWCIterableLayer.
830 */
831class HWCLayerVersion1 : public Iterable<HWCLayerVersion1, hwc_layer_1_t> {
832    struct hwc_composer_device_1* mHwc;
833public:
834    HWCLayerVersion1(struct hwc_composer_device_1* hwc, hwc_layer_1_t* layer)
835        : Iterable<HWCLayerVersion1, hwc_layer_1_t>(layer), mHwc(hwc) { }
836
837    virtual int32_t getCompositionType() const {
838        return getLayer()->compositionType;
839    }
840    virtual uint32_t getHints() const {
841        return getLayer()->hints;
842    }
843    virtual sp<Fence> getAndResetReleaseFence() {
844        int fd = getLayer()->releaseFenceFd;
845        getLayer()->releaseFenceFd = -1;
846        return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
847    }
848    virtual void setAcquireFenceFd(int fenceFd) {
849        getLayer()->acquireFenceFd = fenceFd;
850    }
851    virtual void setPerFrameDefaultState() {
852        //getLayer()->compositionType = HWC_FRAMEBUFFER;
853    }
854    virtual void setPlaneAlpha(uint8_t alpha) {
855        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_2)) {
856            getLayer()->planeAlpha = alpha;
857        } else {
858            if (alpha < 0xFF) {
859                getLayer()->flags |= HWC_SKIP_LAYER;
860            }
861        }
862    }
863    virtual void setDefaultState() {
864        hwc_layer_1_t* const l = getLayer();
865        l->compositionType = HWC_FRAMEBUFFER;
866        l->hints = 0;
867        l->flags = HWC_SKIP_LAYER;
868        l->handle = 0;
869        l->transform = 0;
870        l->blending = HWC_BLENDING_NONE;
871        l->visibleRegionScreen.numRects = 0;
872        l->visibleRegionScreen.rects = NULL;
873        l->acquireFenceFd = -1;
874        l->releaseFenceFd = -1;
875        l->planeAlpha = 0xFF;
876    }
877    virtual void setSkip(bool skip) {
878        if (skip) {
879            getLayer()->flags |= HWC_SKIP_LAYER;
880        } else {
881            getLayer()->flags &= ~HWC_SKIP_LAYER;
882        }
883    }
884    virtual void setBlending(uint32_t blending) {
885        getLayer()->blending = blending;
886    }
887    virtual void setTransform(uint32_t transform) {
888        getLayer()->transform = transform;
889    }
890    virtual void setFrame(const Rect& frame) {
891        getLayer()->displayFrame = reinterpret_cast<hwc_rect_t const&>(frame);
892    }
893    virtual void setCrop(const FloatRect& crop) {
894        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
895            getLayer()->sourceCropf = reinterpret_cast<hwc_frect_t const&>(crop);
896        } else {
897            /*
898             * Since h/w composer didn't support a flot crop rect before version 1.3,
899             * using integer coordinates instead produces a different output from the GL code in
900             * Layer::drawWithOpenGL(). The difference can be large if the buffer crop to
901             * window size ratio is large and a window crop is defined
902             * (i.e.: if we scale the buffer a lot and we also crop it with a window crop).
903             */
904            hwc_rect_t& r = getLayer()->sourceCrop;
905            r.left  = int(ceilf(crop.left));
906            r.top   = int(ceilf(crop.top));
907            r.right = int(floorf(crop.right));
908            r.bottom= int(floorf(crop.bottom));
909        }
910    }
911    virtual void setVisibleRegionScreen(const Region& reg) {
912        // Region::getSharedBuffer creates a reference to the underlying
913        // SharedBuffer of this Region, this reference is freed
914        // in onDisplayed()
915        hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
916        SharedBuffer const* sb = reg.getSharedBuffer(&visibleRegion.numRects);
917        visibleRegion.rects = reinterpret_cast<hwc_rect_t const *>(sb->data());
918    }
919    virtual void setBuffer(const sp<GraphicBuffer>& buffer) {
920        if (buffer == 0 || buffer->handle == 0) {
921            getLayer()->compositionType = HWC_FRAMEBUFFER;
922            getLayer()->flags |= HWC_SKIP_LAYER;
923            getLayer()->handle = 0;
924        } else {
925            getLayer()->handle = buffer->handle;
926        }
927    }
928    virtual void onDisplayed() {
929        hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
930        SharedBuffer const* sb = SharedBuffer::bufferFromData(visibleRegion.rects);
931        if (sb) {
932            sb->release();
933            // not technically needed but safer
934            visibleRegion.numRects = 0;
935            visibleRegion.rects = NULL;
936        }
937
938        getLayer()->acquireFenceFd = -1;
939    }
940};
941
942/*
943 * returns an iterator initialized at a given index in the layer list
944 */
945HWComposer::LayerListIterator HWComposer::getLayerIterator(int32_t id, size_t index) {
946    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
947        return LayerListIterator();
948    }
949    const DisplayData& disp(mDisplayData[id]);
950    if (!mHwc || !disp.list || index > disp.list->numHwLayers) {
951        return LayerListIterator();
952    }
953    return LayerListIterator(new HWCLayerVersion1(mHwc, disp.list->hwLayers), index);
954}
955
956/*
957 * returns an iterator on the beginning of the layer list
958 */
959HWComposer::LayerListIterator HWComposer::begin(int32_t id) {
960    return getLayerIterator(id, 0);
961}
962
963/*
964 * returns an iterator on the end of the layer list
965 */
966HWComposer::LayerListIterator HWComposer::end(int32_t id) {
967    size_t numLayers = 0;
968    if (uint32_t(id) <= 31 && mAllocatedDisplayIDs.hasBit(id)) {
969        const DisplayData& disp(mDisplayData[id]);
970        if (mHwc && disp.list) {
971            numLayers = disp.list->numHwLayers;
972            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
973                // with HWC 1.1, the last layer is always the HWC_FRAMEBUFFER_TARGET,
974                // which we ignore when iterating through the layer list.
975                ALOGE_IF(!numLayers, "mDisplayData[%d].list->numHwLayers is 0", id);
976                if (numLayers) {
977                    numLayers--;
978                }
979            }
980        }
981    }
982    return getLayerIterator(id, numLayers);
983}
984
985void HWComposer::dump(String8& result) const {
986    if (mHwc) {
987        result.appendFormat("Hardware Composer state (version %8x):\n", hwcApiVersion(mHwc));
988        result.appendFormat("  mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync);
989        for (size_t i=0 ; i<mNumDisplays ; i++) {
990            const DisplayData& disp(mDisplayData[i]);
991            if (!disp.connected)
992                continue;
993
994            const Vector< sp<Layer> >& visibleLayersSortedByZ =
995                    mFlinger->getLayerSortedByZForHwcDisplay(i);
996
997            result.appendFormat(
998                    "  Display[%d] : %ux%u, xdpi=%f, ydpi=%f, refresh=%lld\n",
999                    i, disp.width, disp.height, disp.xdpi, disp.ydpi, disp.refresh);
1000
1001            if (disp.list) {
1002                result.appendFormat(
1003                        "  numHwLayers=%u, flags=%08x\n",
1004                        disp.list->numHwLayers, disp.list->flags);
1005
1006                result.append(
1007                        "    type    |  handle  |   hints  |   flags  | tr | blend |  format  |          source crop            |           frame           name \n"
1008                        "------------+----------+----------+----------+----+-------+----------+---------------------------------+--------------------------------\n");
1009                //      " __________ | ________ | ________ | ________ | __ | _____ | ________ | [_____._,_____._,_____._,_____._] | [_____,_____,_____,_____]
1010                for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
1011                    const hwc_layer_1_t&l = disp.list->hwLayers[i];
1012                    int32_t format = -1;
1013                    String8 name("unknown");
1014
1015                    if (i < visibleLayersSortedByZ.size()) {
1016                        const sp<Layer>& layer(visibleLayersSortedByZ[i]);
1017                        const sp<GraphicBuffer>& buffer(
1018                                layer->getActiveBuffer());
1019                        if (buffer != NULL) {
1020                            format = buffer->getPixelFormat();
1021                        }
1022                        name = layer->getName();
1023                    }
1024
1025                    int type = l.compositionType;
1026                    if (type == HWC_FRAMEBUFFER_TARGET) {
1027                        name = "HWC_FRAMEBUFFER_TARGET";
1028                        format = disp.format;
1029                    }
1030
1031                    static char const* compositionTypeName[] = {
1032                            "GLES",
1033                            "HWC",
1034                            "BACKGROUND",
1035                            "FB TARGET",
1036                            "UNKNOWN"};
1037                    if (type >= NELEM(compositionTypeName))
1038                        type = NELEM(compositionTypeName) - 1;
1039
1040                    if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
1041                        result.appendFormat(
1042                                " %10s | %08x | %08x | %08x | %02x | %05x | %08x | [%7.1f,%7.1f,%7.1f,%7.1f] | [%5d,%5d,%5d,%5d] %s\n",
1043                                        compositionTypeName[type],
1044                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, format,
1045                                        l.sourceCropf.left, l.sourceCropf.top, l.sourceCropf.right, l.sourceCropf.bottom,
1046                                        l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1047                                        name.string());
1048                    } else {
1049                        result.appendFormat(
1050                                " %10s | %08x | %08x | %08x | %02x | %05x | %08x | [%7d,%7d,%7d,%7d] | [%5d,%5d,%5d,%5d] %s\n",
1051                                        compositionTypeName[type],
1052                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, format,
1053                                        l.sourceCrop.left, l.sourceCrop.top, l.sourceCrop.right, l.sourceCrop.bottom,
1054                                        l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1055                                        name.string());
1056                    }
1057                }
1058            }
1059        }
1060    }
1061
1062    if (mHwc && mHwc->dump) {
1063        const size_t SIZE = 4096;
1064        char buffer[SIZE];
1065        mHwc->dump(mHwc, buffer, SIZE);
1066        result.append(buffer);
1067    }
1068}
1069
1070// ---------------------------------------------------------------------------
1071
1072HWComposer::VSyncThread::VSyncThread(HWComposer& hwc)
1073    : mHwc(hwc), mEnabled(false),
1074      mNextFakeVSync(0),
1075      mRefreshPeriod(hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY))
1076{
1077}
1078
1079void HWComposer::VSyncThread::setEnabled(bool enabled) {
1080    Mutex::Autolock _l(mLock);
1081    if (mEnabled != enabled) {
1082        mEnabled = enabled;
1083        mCondition.signal();
1084    }
1085}
1086
1087void HWComposer::VSyncThread::onFirstRef() {
1088    run("VSyncThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
1089}
1090
1091bool HWComposer::VSyncThread::threadLoop() {
1092    { // scope for lock
1093        Mutex::Autolock _l(mLock);
1094        while (!mEnabled) {
1095            mCondition.wait(mLock);
1096        }
1097    }
1098
1099    const nsecs_t period = mRefreshPeriod;
1100    const nsecs_t now = systemTime(CLOCK_MONOTONIC);
1101    nsecs_t next_vsync = mNextFakeVSync;
1102    nsecs_t sleep = next_vsync - now;
1103    if (sleep < 0) {
1104        // we missed, find where the next vsync should be
1105        sleep = (period - ((now - next_vsync) % period));
1106        next_vsync = now + sleep;
1107    }
1108    mNextFakeVSync = next_vsync + period;
1109
1110    struct timespec spec;
1111    spec.tv_sec  = next_vsync / 1000000000;
1112    spec.tv_nsec = next_vsync % 1000000000;
1113
1114    int err;
1115    do {
1116        err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
1117    } while (err<0 && errno == EINTR);
1118
1119    if (err == 0) {
1120        mHwc.mEventHandler.onVSyncReceived(0, next_vsync);
1121    }
1122
1123    return true;
1124}
1125
1126HWComposer::DisplayData::DisplayData()
1127:   width(0), height(0), format(0),
1128    xdpi(0.0f), ydpi(0.0f),
1129    refresh(0),
1130    connected(false),
1131    hasFbComp(false), hasOvComp(false),
1132    capacity(0), list(NULL),
1133    framebufferTarget(NULL), fbTargetHandle(0),
1134    lastRetireFence(Fence::NO_FENCE), lastDisplayFence(Fence::NO_FENCE),
1135    outbufHandle(NULL), outbufAcquireFence(Fence::NO_FENCE),
1136    events(0)
1137{}
1138
1139HWComposer::DisplayData::~DisplayData() {
1140    free(list);
1141}
1142
1143// ---------------------------------------------------------------------------
1144}; // namespace android
1145