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