HWComposer.cpp revision afaf14b9fbfe8943d845e2f01e8a401ad7a4d854
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 virtual displays, the framebufferTarget buffer also serves as
661        // the HWC output buffer, so we need to copy the buffer handle and
662        // dup() the acquire fence.
663        for (size_t i=VIRTUAL_DISPLAY_ID_BASE; i<mNumDisplays; i++) {
664            DisplayData& disp(mDisplayData[i]);
665            if (disp.framebufferTarget) {
666                mLists[i]->outbuf = disp.framebufferTarget->handle;
667                mLists[i]->outbufAcquireFenceFd =
668                        dup(disp.framebufferTarget->acquireFenceFd);
669            }
670        }
671
672        err = mHwc->set(mHwc, mNumDisplays, mLists);
673
674        for (size_t i=0 ; i<mNumDisplays ; i++) {
675            DisplayData& disp(mDisplayData[i]);
676            disp.lastDisplayFence = disp.lastRetireFence;
677            disp.lastRetireFence = Fence::NO_FENCE;
678            if (disp.list) {
679                if (disp.list->retireFenceFd != -1) {
680                    disp.lastRetireFence = new Fence(disp.list->retireFenceFd);
681                    disp.list->retireFenceFd = -1;
682                }
683                disp.list->flags &= ~HWC_GEOMETRY_CHANGED;
684            }
685        }
686    }
687    return (status_t)err;
688}
689
690status_t HWComposer::release(int disp) {
691    LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
692    if (mHwc) {
693        eventControl(disp, HWC_EVENT_VSYNC, 0);
694        return (status_t)mHwc->blank(mHwc, disp, 1);
695    }
696    return NO_ERROR;
697}
698
699status_t HWComposer::acquire(int disp) {
700    LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
701    if (mHwc) {
702        return (status_t)mHwc->blank(mHwc, disp, 0);
703    }
704    return NO_ERROR;
705}
706
707void HWComposer::disconnectDisplay(int disp) {
708    LOG_ALWAYS_FATAL_IF(disp < 0 || disp == HWC_DISPLAY_PRIMARY);
709    if (disp >= HWC_NUM_DISPLAY_TYPES) {
710        // nothing to do for these yet
711        return;
712    }
713    DisplayData& dd(mDisplayData[disp]);
714    if (dd.list != NULL) {
715        free(dd.list);
716        dd.list = NULL;
717        dd.framebufferTarget = NULL;    // points into dd.list
718        dd.fbTargetHandle = NULL;
719    }
720}
721
722int HWComposer::getVisualID() const {
723    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
724        // FIXME: temporary hack until HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED
725        // is supported by the implementation. we can only be in this case
726        // if we have HWC 1.1
727        return HAL_PIXEL_FORMAT_RGBA_8888;
728        //return HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
729    } else {
730        return mFbDev->format;
731    }
732}
733
734bool HWComposer::supportsFramebufferTarget() const {
735    return (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
736}
737
738int HWComposer::fbPost(int32_t id,
739        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buffer) {
740    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
741        return setFramebufferTarget(id, acquireFence, buffer);
742    } else {
743        acquireFence->waitForever(1000, "HWComposer::fbPost");
744        return mFbDev->post(mFbDev, buffer->handle);
745    }
746}
747
748int HWComposer::fbCompositionComplete() {
749    if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
750        return NO_ERROR;
751
752    if (mFbDev->compositionComplete) {
753        return mFbDev->compositionComplete(mFbDev);
754    } else {
755        return INVALID_OPERATION;
756    }
757}
758
759void HWComposer::fbDump(String8& result) {
760    if (mFbDev && mFbDev->common.version >= 1 && mFbDev->dump) {
761        const size_t SIZE = 4096;
762        char buffer[SIZE];
763        mFbDev->dump(mFbDev, buffer, SIZE);
764        result.append(buffer);
765    }
766}
767
768/*
769 * Helper template to implement a concrete HWCLayer
770 * This holds the pointer to the concrete hwc layer type
771 * and implements the "iterable" side of HWCLayer.
772 */
773template<typename CONCRETE, typename HWCTYPE>
774class Iterable : public HWComposer::HWCLayer {
775protected:
776    HWCTYPE* const mLayerList;
777    HWCTYPE* mCurrentLayer;
778    Iterable(HWCTYPE* layer) : mLayerList(layer), mCurrentLayer(layer) { }
779    inline HWCTYPE const * getLayer() const { return mCurrentLayer; }
780    inline HWCTYPE* getLayer() { return mCurrentLayer; }
781    virtual ~Iterable() { }
782private:
783    // returns a copy of ourselves
784    virtual HWComposer::HWCLayer* dup() {
785        return new CONCRETE( static_cast<const CONCRETE&>(*this) );
786    }
787    virtual status_t setLayer(size_t index) {
788        mCurrentLayer = &mLayerList[index];
789        return NO_ERROR;
790    }
791};
792
793/*
794 * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_1_0.
795 * This implements the HWCLayer side of HWCIterableLayer.
796 */
797class HWCLayerVersion1 : public Iterable<HWCLayerVersion1, hwc_layer_1_t> {
798    struct hwc_composer_device_1* mHwc;
799public:
800    HWCLayerVersion1(struct hwc_composer_device_1* hwc, hwc_layer_1_t* layer)
801        : Iterable<HWCLayerVersion1, hwc_layer_1_t>(layer), mHwc(hwc) { }
802
803    virtual int32_t getCompositionType() const {
804        return getLayer()->compositionType;
805    }
806    virtual uint32_t getHints() const {
807        return getLayer()->hints;
808    }
809    virtual sp<Fence> getAndResetReleaseFence() {
810        int fd = getLayer()->releaseFenceFd;
811        getLayer()->releaseFenceFd = -1;
812        return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
813    }
814    virtual void setAcquireFenceFd(int fenceFd) {
815        getLayer()->acquireFenceFd = fenceFd;
816    }
817    virtual void setPerFrameDefaultState() {
818        //getLayer()->compositionType = HWC_FRAMEBUFFER;
819    }
820    virtual void setPlaneAlpha(uint8_t alpha) {
821        if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_2)) {
822            getLayer()->planeAlpha = alpha;
823        } else {
824            if (alpha < 0xFF) {
825                getLayer()->flags |= HWC_SKIP_LAYER;
826            }
827        }
828    }
829    virtual void setDefaultState() {
830        hwc_layer_1_t* const l = getLayer();
831        l->compositionType = HWC_FRAMEBUFFER;
832        l->hints = 0;
833        l->flags = HWC_SKIP_LAYER;
834        l->handle = 0;
835        l->transform = 0;
836        l->blending = HWC_BLENDING_NONE;
837        l->visibleRegionScreen.numRects = 0;
838        l->visibleRegionScreen.rects = NULL;
839        l->acquireFenceFd = -1;
840        l->releaseFenceFd = -1;
841        l->planeAlpha = 0xFF;
842    }
843    virtual void setSkip(bool skip) {
844        if (skip) {
845            getLayer()->flags |= HWC_SKIP_LAYER;
846        } else {
847            getLayer()->flags &= ~HWC_SKIP_LAYER;
848        }
849    }
850    virtual void setBlending(uint32_t blending) {
851        getLayer()->blending = blending;
852    }
853    virtual void setTransform(uint32_t transform) {
854        getLayer()->transform = transform;
855    }
856    virtual void setFrame(const Rect& frame) {
857        reinterpret_cast<Rect&>(getLayer()->displayFrame) = frame;
858    }
859    virtual void setCrop(const Rect& crop) {
860        reinterpret_cast<Rect&>(getLayer()->sourceCrop) = crop;
861    }
862    virtual void setVisibleRegionScreen(const Region& reg) {
863        // Region::getSharedBuffer creates a reference to the underlying
864        // SharedBuffer of this Region, this reference is freed
865        // in onDisplayed()
866        hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
867        SharedBuffer const* sb = reg.getSharedBuffer(&visibleRegion.numRects);
868        visibleRegion.rects = reinterpret_cast<hwc_rect_t const *>(sb->data());
869    }
870    virtual void setBuffer(const sp<GraphicBuffer>& buffer) {
871        if (buffer == 0 || buffer->handle == 0) {
872            getLayer()->compositionType = HWC_FRAMEBUFFER;
873            getLayer()->flags |= HWC_SKIP_LAYER;
874            getLayer()->handle = 0;
875        } else {
876            getLayer()->handle = buffer->handle;
877        }
878    }
879    virtual void onDisplayed() {
880        hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
881        SharedBuffer const* sb = SharedBuffer::bufferFromData(visibleRegion.rects);
882        if (sb) {
883            sb->release();
884            // not technically needed but safer
885            visibleRegion.numRects = 0;
886            visibleRegion.rects = NULL;
887        }
888
889        getLayer()->acquireFenceFd = -1;
890    }
891};
892
893/*
894 * returns an iterator initialized at a given index in the layer list
895 */
896HWComposer::LayerListIterator HWComposer::getLayerIterator(int32_t id, size_t index) {
897    if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
898        return LayerListIterator();
899    }
900    const DisplayData& disp(mDisplayData[id]);
901    if (!mHwc || !disp.list || index > disp.list->numHwLayers) {
902        return LayerListIterator();
903    }
904    return LayerListIterator(new HWCLayerVersion1(mHwc, disp.list->hwLayers), index);
905}
906
907/*
908 * returns an iterator on the beginning of the layer list
909 */
910HWComposer::LayerListIterator HWComposer::begin(int32_t id) {
911    return getLayerIterator(id, 0);
912}
913
914/*
915 * returns an iterator on the end of the layer list
916 */
917HWComposer::LayerListIterator HWComposer::end(int32_t id) {
918    size_t numLayers = 0;
919    if (uint32_t(id) <= 31 && mAllocatedDisplayIDs.hasBit(id)) {
920        const DisplayData& disp(mDisplayData[id]);
921        if (mHwc && disp.list) {
922            numLayers = disp.list->numHwLayers;
923            if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
924                // with HWC 1.1, the last layer is always the HWC_FRAMEBUFFER_TARGET,
925                // which we ignore when iterating through the layer list.
926                ALOGE_IF(!numLayers, "mDisplayData[%d].list->numHwLayers is 0", id);
927                if (numLayers) {
928                    numLayers--;
929                }
930            }
931        }
932    }
933    return getLayerIterator(id, numLayers);
934}
935
936void HWComposer::dump(String8& result, char* buffer, size_t SIZE) const {
937    if (mHwc) {
938        result.appendFormat("Hardware Composer state (version %8x):\n", hwcApiVersion(mHwc));
939        result.appendFormat("  mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync);
940        for (size_t i=0 ; i<mNumDisplays ; i++) {
941            const DisplayData& disp(mDisplayData[i]);
942
943            const Vector< sp<Layer> >& visibleLayersSortedByZ =
944                    mFlinger->getLayerSortedByZForHwcDisplay(i);
945
946            if (disp.connected) {
947                result.appendFormat(
948                        "  Display[%d] : %ux%u, xdpi=%f, ydpi=%f, refresh=%lld\n",
949                        i, disp.width, disp.height, disp.xdpi, disp.ydpi, disp.refresh);
950            }
951
952            if (disp.list && disp.connected) {
953                result.appendFormat(
954                        "  numHwLayers=%u, flags=%08x\n",
955                        disp.list->numHwLayers, disp.list->flags);
956
957                result.append(
958                        "    type    |  handle  |   hints  |   flags  | tr | blend |  format  |       source crop         |           frame           name \n"
959                        "------------+----------+----------+----------+----+-------+----------+---------------------------+--------------------------------\n");
960                //      " __________ | ________ | ________ | ________ | __ | _____ | ________ | [_____,_____,_____,_____] | [_____,_____,_____,_____]
961                for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
962                    const hwc_layer_1_t&l = disp.list->hwLayers[i];
963                    int32_t format = -1;
964                    String8 name("unknown");
965
966                    if (i < visibleLayersSortedByZ.size()) {
967                        const sp<Layer>& layer(visibleLayersSortedByZ[i]);
968                        const sp<GraphicBuffer>& buffer(
969                                layer->getActiveBuffer());
970                        if (buffer != NULL) {
971                            format = buffer->getPixelFormat();
972                        }
973                        name = layer->getName();
974                    }
975
976                    int type = l.compositionType;
977                    if (type == HWC_FRAMEBUFFER_TARGET) {
978                        name = "HWC_FRAMEBUFFER_TARGET";
979                        format = disp.format;
980                    }
981
982                    static char const* compositionTypeName[] = {
983                            "GLES",
984                            "HWC",
985                            "BACKGROUND",
986                            "FB TARGET",
987                            "UNKNOWN"};
988                    if (type >= NELEM(compositionTypeName))
989                        type = NELEM(compositionTypeName) - 1;
990
991                    result.appendFormat(
992                            " %10s | %08x | %08x | %08x | %02x | %05x | %08x | [%5d,%5d,%5d,%5d] | [%5d,%5d,%5d,%5d] %s\n",
993                                    compositionTypeName[type],
994                                    intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, format,
995                                    l.sourceCrop.left, l.sourceCrop.top, l.sourceCrop.right, l.sourceCrop.bottom,
996                                    l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
997                                    name.string());
998                }
999            }
1000        }
1001    }
1002
1003    if (mHwc && mHwc->dump) {
1004        mHwc->dump(mHwc, buffer, SIZE);
1005        result.append(buffer);
1006    }
1007}
1008
1009// ---------------------------------------------------------------------------
1010
1011HWComposer::VSyncThread::VSyncThread(HWComposer& hwc)
1012    : mHwc(hwc), mEnabled(false),
1013      mNextFakeVSync(0),
1014      mRefreshPeriod(hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY))
1015{
1016}
1017
1018void HWComposer::VSyncThread::setEnabled(bool enabled) {
1019    Mutex::Autolock _l(mLock);
1020    if (mEnabled != enabled) {
1021        mEnabled = enabled;
1022        mCondition.signal();
1023    }
1024}
1025
1026void HWComposer::VSyncThread::onFirstRef() {
1027    run("VSyncThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
1028}
1029
1030bool HWComposer::VSyncThread::threadLoop() {
1031    { // scope for lock
1032        Mutex::Autolock _l(mLock);
1033        while (!mEnabled) {
1034            mCondition.wait(mLock);
1035        }
1036    }
1037
1038    const nsecs_t period = mRefreshPeriod;
1039    const nsecs_t now = systemTime(CLOCK_MONOTONIC);
1040    nsecs_t next_vsync = mNextFakeVSync;
1041    nsecs_t sleep = next_vsync - now;
1042    if (sleep < 0) {
1043        // we missed, find where the next vsync should be
1044        sleep = (period - ((now - next_vsync) % period));
1045        next_vsync = now + sleep;
1046    }
1047    mNextFakeVSync = next_vsync + period;
1048
1049    struct timespec spec;
1050    spec.tv_sec  = next_vsync / 1000000000;
1051    spec.tv_nsec = next_vsync % 1000000000;
1052
1053    int err;
1054    do {
1055        err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
1056    } while (err<0 && errno == EINTR);
1057
1058    if (err == 0) {
1059        mHwc.mEventHandler.onVSyncReceived(0, next_vsync);
1060    }
1061
1062    return true;
1063}
1064
1065HWComposer::DisplayData::DisplayData()
1066:   width(0), height(0), format(0),
1067    xdpi(0.0f), ydpi(0.0f),
1068    refresh(0),
1069    connected(false),
1070    hasFbComp(false), hasOvComp(false),
1071    capacity(0), list(NULL),
1072    framebufferTarget(NULL), fbTargetHandle(0),
1073    lastRetireFence(Fence::NO_FENCE), lastDisplayFence(Fence::NO_FENCE),
1074    events(0)
1075{}
1076
1077HWComposer::DisplayData::~DisplayData() {
1078    free(list);
1079}
1080
1081// ---------------------------------------------------------------------------
1082}; // namespace android
1083