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