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