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