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