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