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