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