hwc_utils.cpp revision b8986cf8f2f7702e1d281bf67fd31f6be09eb287
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 * Copyright (C) 2012-2013, The Linux Foundation All rights reserved.
4 *
5 * Not a Contribution, Apache license notifications and license are retained
6 * for attribution purposes only.
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 *      http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20#define HWC_UTILS_DEBUG 0
21#include <sys/ioctl.h>
22#include <binder/IServiceManager.h>
23#include <EGL/egl.h>
24#include <cutils/properties.h>
25#include <gralloc_priv.h>
26#include <overlay.h>
27#include <overlayRotator.h>
28#include "hwc_utils.h"
29#include "hwc_mdpcomp.h"
30#include "hwc_fbupdate.h"
31#include "hwc_video.h"
32#include "mdp_version.h"
33#include "hwc_copybit.h"
34#include "external.h"
35#include "hwc_qclient.h"
36#include "QService.h"
37#include "comptype.h"
38
39using namespace qClient;
40using namespace qService;
41using namespace android;
42using namespace overlay;
43using namespace overlay::utils;
44namespace ovutils = overlay::utils;
45
46namespace qhwc {
47
48static int openFramebufferDevice(hwc_context_t *ctx)
49{
50    struct fb_fix_screeninfo finfo;
51    struct fb_var_screeninfo info;
52
53    int fb_fd = openFb(HWC_DISPLAY_PRIMARY);
54
55    if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &info) == -1)
56        return -errno;
57
58    if (int(info.width) <= 0 || int(info.height) <= 0) {
59        // the driver doesn't return that information
60        // default to 160 dpi
61        info.width  = ((info.xres * 25.4f)/160.0f + 0.5f);
62        info.height = ((info.yres * 25.4f)/160.0f + 0.5f);
63    }
64
65    float xdpi = (info.xres * 25.4f) / info.width;
66    float ydpi = (info.yres * 25.4f) / info.height;
67
68#ifdef MSMFB_METADATA_GET
69    struct msmfb_metadata metadata;
70    memset(&metadata, 0 , sizeof(metadata));
71    metadata.op = metadata_op_frame_rate;
72
73    if (ioctl(fb_fd, MSMFB_METADATA_GET, &metadata) == -1) {
74        ALOGE("Error retrieving panel frame rate");
75        return -errno;
76    }
77
78    float fps  = metadata.data.panel_frame_rate;
79#else
80    //XXX: Remove reserved field usage on all baselines
81    //The reserved[3] field is used to store FPS by the driver.
82    float fps  = info.reserved[3] & 0xFF;
83#endif
84
85    if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) == -1)
86        return -errno;
87
88    if (finfo.smem_len <= 0)
89        return -errno;
90
91    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = fb_fd;
92    //xres, yres may not be 32 aligned
93    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].stride = finfo.line_length /(info.xres/8);
94    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres = info.xres;
95    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].yres = info.yres;
96    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xdpi = xdpi;
97    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].ydpi = ydpi;
98    ctx->dpyAttr[HWC_DISPLAY_PRIMARY].vsync_period = 1000000000l / fps;
99
100    return 0;
101}
102
103void initContext(hwc_context_t *ctx)
104{
105    if(openFramebufferDevice(ctx) < 0) {
106        ALOGE("%s: failed to open framebuffer!!", __FUNCTION__);
107    }
108
109    overlay::Overlay::initOverlay();
110    ctx->mOverlay = overlay::Overlay::getInstance();
111    ctx->mRotMgr = new RotMgr();
112    ctx->mMDP.version = qdutils::MDPVersion::getInstance().getMDPVersion();
113    ctx->mMDP.hasOverlay = qdutils::MDPVersion::getInstance().hasOverlay();
114    ctx->mMDP.panel = qdutils::MDPVersion::getInstance().getPanelType();
115    overlay::Overlay::initOverlay();
116    ctx->mOverlay = overlay::Overlay::getInstance();
117    ctx->mRotMgr = new RotMgr();
118
119    //Is created and destroyed only once for primary
120    //For external it could get created and destroyed multiple times depending
121    //on what external we connect to.
122    ctx->mFBUpdate[HWC_DISPLAY_PRIMARY] =
123        IFBUpdate::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres,
124        HWC_DISPLAY_PRIMARY);
125
126    ctx->mVidOv[HWC_DISPLAY_PRIMARY] =
127        IVideoOverlay::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres,
128        HWC_DISPLAY_PRIMARY);
129
130    // Check if the target supports copybit compostion (dyn/mdp/c2d) to
131    // decide if we need to open the copybit module.
132    int compositionType =
133        qdutils::QCCompositionType::getInstance().getCompositionType();
134
135    if (compositionType & (qdutils::COMPOSITION_TYPE_DYN |
136                           qdutils::COMPOSITION_TYPE_MDP |
137                           qdutils::COMPOSITION_TYPE_C2D)) {
138            ctx->mCopyBit[HWC_DISPLAY_PRIMARY] = new CopyBit();
139    }
140
141    ctx->mExtDisplay = new ExternalDisplay(ctx);
142    for (uint32_t i = 0; i < MAX_DISPLAYS; i++) {
143        ctx->mLayerCache[i] = new LayerCache();
144        ctx->mLayerRotMap[i] = new LayerRotMap();
145    }
146
147    ctx->mMDPComp = MDPComp::getObject(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].xres);
148    MDPComp::init(ctx);
149
150    pthread_mutex_init(&(ctx->vstate.lock), NULL);
151    pthread_cond_init(&(ctx->vstate.cond), NULL);
152    ctx->vstate.enable = false;
153    ctx->vstate.fakevsync = false;
154    ctx->mExtDispConfiguring = false;
155    ctx->mBasePipeSetup = false;
156
157    //Right now hwc starts the service but anybody could do it, or it could be
158    //independent process as well.
159    QService::init();
160    sp<IQClient> client = new QClient(ctx);
161    interface_cast<IQService>(
162            defaultServiceManager()->getService(
163            String16("display.qservice")))->connect(client);
164
165    ALOGI("Initializing Qualcomm Hardware Composer");
166    ALOGI("MDP version: %d", ctx->mMDP.version);
167}
168
169void closeContext(hwc_context_t *ctx)
170{
171    if(ctx->mOverlay) {
172        delete ctx->mOverlay;
173        ctx->mOverlay = NULL;
174    }
175
176    if(ctx->mRotMgr) {
177        delete ctx->mRotMgr;
178        ctx->mRotMgr = NULL;
179    }
180
181    for(int i = 0; i < MAX_DISPLAYS; i++) {
182        if(ctx->mCopyBit[i]) {
183            delete ctx->mCopyBit[i];
184            ctx->mCopyBit[i] = NULL;
185        }
186    }
187
188    if(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd) {
189        close(ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd);
190        ctx->dpyAttr[HWC_DISPLAY_PRIMARY].fd = -1;
191    }
192
193    if(ctx->mExtDisplay) {
194        delete ctx->mExtDisplay;
195        ctx->mExtDisplay = NULL;
196    }
197
198    for(int i = 0; i < MAX_DISPLAYS; i++) {
199        if(ctx->mFBUpdate[i]) {
200            delete ctx->mFBUpdate[i];
201            ctx->mFBUpdate[i] = NULL;
202        }
203        if(ctx->mVidOv[i]) {
204            delete ctx->mVidOv[i];
205            ctx->mVidOv[i] = NULL;
206        }
207        if(ctx->mLayerRotMap[i]) {
208            delete ctx->mLayerRotMap[i];
209            ctx->mLayerRotMap[i] = NULL;
210        }
211    }
212
213    if(ctx->mMDPComp) {
214        delete ctx->mMDPComp;
215        ctx->mMDPComp = NULL;
216    }
217
218    pthread_mutex_destroy(&(ctx->vstate.lock));
219    pthread_cond_destroy(&(ctx->vstate.cond));
220}
221
222
223void dumpsys_log(android::String8& buf, const char* fmt, ...)
224{
225    va_list varargs;
226    va_start(varargs, fmt);
227    buf.appendFormatV(fmt, varargs);
228    va_end(varargs);
229}
230
231/* Calculates the destination position based on the action safe rectangle */
232void getActionSafePosition(hwc_context_t *ctx, int dpy, uint32_t& x,
233                           uint32_t& y, uint32_t& w, uint32_t& h) {
234
235    // if external supports underscan, do nothing
236    // it will be taken care in the driver
237    if(ctx->mExtDisplay->isCEUnderscanSupported())
238        return;
239
240    float wRatio = 1.0;
241    float hRatio = 1.0;
242    float xRatio = 1.0;
243    float yRatio = 1.0;
244
245    float fbWidth = ctx->dpyAttr[dpy].xres;
246    float fbHeight = ctx->dpyAttr[dpy].yres;
247
248    float asX = 0;
249    float asY = 0;
250    float asW = fbWidth;
251    float asH= fbHeight;
252    char value[PROPERTY_VALUE_MAX];
253
254    // Apply action safe parameters
255    property_get("hw.actionsafe.width", value, "0");
256    int asWidthRatio = atoi(value);
257    property_get("hw.actionsafe.height", value, "0");
258    int asHeightRatio = atoi(value);
259    // based on the action safe ratio, get the Action safe rectangle
260    asW = fbWidth * (1.0f -  asWidthRatio / 100.0f);
261    asH = fbHeight * (1.0f -  asHeightRatio / 100.0f);
262    asX = (fbWidth - asW) / 2;
263    asY = (fbHeight - asH) / 2;
264
265    // calculate the position ratio
266    xRatio = (float)x/fbWidth;
267    yRatio = (float)y/fbHeight;
268    wRatio = (float)w/fbWidth;
269    hRatio = (float)h/fbHeight;
270
271    //Calculate the position...
272    x = (xRatio * asW) + asX;
273    y = (yRatio * asH) + asY;
274    w = (wRatio * asW);
275    h = (hRatio * asH);
276
277    return;
278}
279
280bool needsScaling(hwc_layer_1_t const* layer) {
281    int dst_w, dst_h, src_w, src_h;
282
283    hwc_rect_t displayFrame  = layer->displayFrame;
284    hwc_rect_t sourceCrop = layer->sourceCrop;
285
286    dst_w = displayFrame.right - displayFrame.left;
287    dst_h = displayFrame.bottom - displayFrame.top;
288
289    src_w = sourceCrop.right - sourceCrop.left;
290    src_h = sourceCrop.bottom - sourceCrop.top;
291
292    if(((src_w != dst_w) || (src_h != dst_h)))
293        return true;
294
295    return false;
296}
297
298bool isAlphaScaled(hwc_layer_1_t const* layer) {
299    if(needsScaling(layer) && isAlphaPresent(layer)) {
300        return true;
301    }
302    return false;
303}
304
305bool isAlphaPresent(hwc_layer_1_t const* layer) {
306    private_handle_t *hnd = (private_handle_t *)layer->handle;
307    if(hnd) {
308        int format = hnd->format;
309        switch(format) {
310        case HAL_PIXEL_FORMAT_RGBA_8888:
311        case HAL_PIXEL_FORMAT_BGRA_8888:
312            // In any more formats with Alpha go here..
313            return true;
314        default : return false;
315        }
316    }
317    return false;
318}
319
320void setListStats(hwc_context_t *ctx,
321        const hwc_display_contents_1_t *list, int dpy) {
322
323    ctx->listStats[dpy].numAppLayers = list->numHwLayers - 1;
324    ctx->listStats[dpy].fbLayerIndex = list->numHwLayers - 1;
325    ctx->listStats[dpy].skipCount = 0;
326    ctx->listStats[dpy].needsAlphaScale = false;
327    ctx->listStats[dpy].preMultipliedAlpha = false;
328    ctx->listStats[dpy].yuvCount = 0;
329
330    for (size_t i = 0; i < list->numHwLayers; i++) {
331        hwc_layer_1_t const* layer = &list->hwLayers[i];
332        private_handle_t *hnd = (private_handle_t *)layer->handle;
333
334        //reset stored yuv index
335        ctx->listStats[dpy].yuvIndices[i] = -1;
336
337        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
338            continue;
339        //We disregard FB being skip for now! so the else if
340        } else if (isSkipLayer(&list->hwLayers[i])) {
341            ctx->listStats[dpy].skipCount++;
342        } else if (UNLIKELY(isYuvBuffer(hnd))) {
343            int& yuvCount = ctx->listStats[dpy].yuvCount;
344            ctx->listStats[dpy].yuvIndices[yuvCount] = i;
345            yuvCount++;
346
347            if(layer->transform & HWC_TRANSFORM_ROT_90)
348                ctx->mNeedsRotator = true;
349        }
350        if(layer->blending == HWC_BLENDING_PREMULT)
351            ctx->listStats[dpy].preMultipliedAlpha = true;
352
353        if(!ctx->listStats[dpy].needsAlphaScale)
354            ctx->listStats[dpy].needsAlphaScale = isAlphaScaled(layer);
355    }
356}
357
358
359static inline void calc_cut(float& leftCutRatio, float& topCutRatio,
360        float& rightCutRatio, float& bottomCutRatio, int orient) {
361    if(orient & HAL_TRANSFORM_FLIP_H) {
362        swap(leftCutRatio, rightCutRatio);
363    }
364    if(orient & HAL_TRANSFORM_FLIP_V) {
365        swap(topCutRatio, bottomCutRatio);
366    }
367    if(orient & HAL_TRANSFORM_ROT_90) {
368        //Anti clock swapping
369        float tmpCutRatio = leftCutRatio;
370        leftCutRatio = topCutRatio;
371        topCutRatio = rightCutRatio;
372        rightCutRatio = bottomCutRatio;
373        bottomCutRatio = tmpCutRatio;
374    }
375}
376
377bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer) {
378    if((ctx->mMDP.version < qdutils::MDSS_V5) &&
379       (ctx->mMDP.version > qdutils::MDP_V3_0) &&
380        ctx->mSecuring) {
381        return true;
382    }
383    //  On A-Family, Secure policy is applied system wide and not on
384    //  buffers.
385    if (isSecureModePolicy(ctx->mMDP.version)) {
386        private_handle_t *hnd = (private_handle_t *)layer->handle;
387        if(ctx->mSecureMode) {
388            if (! isSecureBuffer(hnd)) {
389                // This code path executes for the following usecase:
390                // Some Apps in which first few seconds, framework
391                // sends non-secure buffer and with out destroying
392                // surfaces, switches to secure buffer thereby exposing
393                // vulnerability on A-family devices. Catch this situation
394                // and handle it gracefully by allowing it to be composed by
395                // GPU.
396                ALOGD_IF(HWC_UTILS_DEBUG, "%s: Handle non-secure video layer"
397                         "during secure playback gracefully", __FUNCTION__);
398                return true;
399            }
400        } else {
401            if (isSecureBuffer(hnd)) {
402                // This code path executes for the following usecase:
403                // For some Apps, when User terminates playback, Framework
404                // doesnt destroy video surface and video surface still
405                // comes to Display HAL. This exposes vulnerability on
406                // A-family. Catch this situation and handle it gracefully
407                // by allowing it to be composed by GPU.
408                ALOGD_IF(HWC_UTILS_DEBUG, "%s: Handle secure video layer"
409                         "during non-secure playback gracefully", __FUNCTION__);
410                return true;
411            }
412        }
413    }
414    return false;
415}
416
417bool isSecureModePolicy(int mdpVersion) {
418    if (mdpVersion < qdutils::MDSS_V5)
419        return true;
420    else
421        return false;
422}
423
424//Crops source buffer against destination and FB boundaries
425void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
426                          const hwc_rect_t& scissor, int orient) {
427
428    int& crop_l = crop.left;
429    int& crop_t = crop.top;
430    int& crop_r = crop.right;
431    int& crop_b = crop.bottom;
432    int crop_w = crop.right - crop.left;
433    int crop_h = crop.bottom - crop.top;
434
435    int& dst_l = dst.left;
436    int& dst_t = dst.top;
437    int& dst_r = dst.right;
438    int& dst_b = dst.bottom;
439    int dst_w = abs(dst.right - dst.left);
440    int dst_h = abs(dst.bottom - dst.top);
441
442    const int& sci_l = scissor.left;
443    const int& sci_t = scissor.top;
444    const int& sci_r = scissor.right;
445    const int& sci_b = scissor.bottom;
446    int sci_w = abs(sci_r - sci_l);
447    int sci_h = abs(sci_b - sci_t);
448
449    float leftCutRatio = 0.0f, rightCutRatio = 0.0f, topCutRatio = 0.0f,
450            bottomCutRatio = 0.0f;
451
452    if(dst_l < sci_l) {
453        leftCutRatio = (float)(sci_l - dst_l) / (float)dst_w;
454        dst_l = sci_l;
455    }
456
457    if(dst_r > sci_r) {
458        rightCutRatio = (float)(dst_r - sci_r) / (float)dst_w;
459        dst_r = sci_r;
460    }
461
462    if(dst_t < sci_t) {
463        topCutRatio = (float)(sci_t - dst_t) / (float)dst_h;
464        dst_t = sci_t;
465    }
466
467    if(dst_b > sci_b) {
468        bottomCutRatio = (float)(dst_b - sci_b) / (float)dst_h;
469        dst_b = sci_b;
470    }
471
472    calc_cut(leftCutRatio, topCutRatio, rightCutRatio, bottomCutRatio, orient);
473    crop_l += crop_w * leftCutRatio;
474    crop_t += crop_h * topCutRatio;
475    crop_r -= crop_w * rightCutRatio;
476    crop_b -= crop_h * bottomCutRatio;
477}
478
479void getNonWormholeRegion(hwc_display_contents_1_t* list,
480                              hwc_rect_t& nwr)
481{
482    uint32_t last = list->numHwLayers - 1;
483    hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame;
484    //Initiliaze nwr to first frame
485    nwr.left =  list->hwLayers[0].displayFrame.left;
486    nwr.top =  list->hwLayers[0].displayFrame.top;
487    nwr.right =  list->hwLayers[0].displayFrame.right;
488    nwr.bottom =  list->hwLayers[0].displayFrame.bottom;
489
490    for (uint32_t i = 1; i < last; i++) {
491        hwc_rect_t displayFrame = list->hwLayers[i].displayFrame;
492        nwr.left   = min(nwr.left, displayFrame.left);
493        nwr.top    = min(nwr.top, displayFrame.top);
494        nwr.right  = max(nwr.right, displayFrame.right);
495        nwr.bottom = max(nwr.bottom, displayFrame.bottom);
496    }
497
498    //Intersect with the framebuffer
499    nwr.left   = max(nwr.left, fbDisplayFrame.left);
500    nwr.top    = max(nwr.top, fbDisplayFrame.top);
501    nwr.right  = min(nwr.right, fbDisplayFrame.right);
502    nwr.bottom = min(nwr.bottom, fbDisplayFrame.bottom);
503
504}
505
506bool isExternalActive(hwc_context_t* ctx) {
507    return ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive;
508}
509
510void closeAcquireFds(hwc_display_contents_1_t* list) {
511    for(uint32_t i = 0; list && i < list->numHwLayers; i++) {
512        //Close the acquireFenceFds
513        //HWC_FRAMEBUFFER are -1 already by SF, rest we close.
514        if(list->hwLayers[i].acquireFenceFd >= 0) {
515            close(list->hwLayers[i].acquireFenceFd);
516            list->hwLayers[i].acquireFenceFd = -1;
517        }
518    }
519}
520
521int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
522        int fd) {
523    int ret = 0;
524
525    int acquireFd[MAX_NUM_LAYERS];
526    int count = 0;
527    int releaseFd = -1;
528    int fbFd = -1;
529    int rotFd = -1;
530    bool swapzero = false;
531    int mdpVersion = qdutils::MDPVersion::getInstance().getMDPVersion();
532
533    struct mdp_buf_sync data;
534    memset(&data, 0, sizeof(data));
535    //Until B-family supports sync for rotator
536    if(mdpVersion >= qdutils::MDSS_V5) {
537        data.flags = MDP_BUF_SYNC_FLAG_WAIT;
538    }
539    data.acq_fen_fd = acquireFd;
540    data.rel_fen_fd = &releaseFd;
541
542    char property[PROPERTY_VALUE_MAX];
543    if(property_get("debug.egl.swapinterval", property, "1") > 0) {
544        if(atoi(property) == 0)
545            swapzero = true;
546    }
547
548    //Send acquireFenceFds to rotator
549    if(mdpVersion < qdutils::MDSS_V5) {
550        //A-family
551        int rotFd = ctx->mRotMgr->getRotDevFd();
552        struct msm_rotator_buf_sync rotData;
553
554        for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) {
555            memset(&rotData, 0, sizeof(rotData));
556            int& acquireFenceFd =
557                ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd;
558            rotData.acq_fen_fd = acquireFenceFd;
559            rotData.session_id = ctx->mLayerRotMap[dpy]->getRot(i)->getSessId();
560            ioctl(rotFd, MSM_ROTATOR_IOCTL_BUFFER_SYNC, &rotData);
561            close(acquireFenceFd);
562             //For MDP to wait on.
563            acquireFenceFd = dup(rotData.rel_fen_fd);
564            //A buffer is free to be used by producer as soon as its copied to
565            //rotator.
566            ctx->mLayerRotMap[dpy]->getLayer(i)->releaseFenceFd =
567                    rotData.rel_fen_fd;
568        }
569    } else {
570        //TODO B-family
571    }
572
573    //Accumulate acquireFenceFds for MDP
574    for(uint32_t i = 0; i < list->numHwLayers; i++) {
575        if(list->hwLayers[i].compositionType == HWC_OVERLAY &&
576                        list->hwLayers[i].acquireFenceFd >= 0) {
577            if(UNLIKELY(swapzero))
578                acquireFd[count++] = -1;
579            else
580                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
581        }
582        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
583            if(UNLIKELY(swapzero))
584                acquireFd[count++] = -1;
585            else if(fd >= 0) {
586                //set the acquireFD from fd - which is coming from c2d
587                acquireFd[count++] = fd;
588                // Buffer sync IOCTL should be async when using c2d fence is
589                // used
590                data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
591            } else if(list->hwLayers[i].acquireFenceFd >= 0)
592                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
593        }
594    }
595
596    data.acq_fen_fd_cnt = count;
597    fbFd = ctx->dpyAttr[dpy].fd;
598
599    //Waits for acquire fences, returns a release fence
600    if(LIKELY(!swapzero)) {
601        uint64_t start = systemTime();
602        ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
603        ALOGD_IF(HWC_UTILS_DEBUG, "%s: time taken for MSMFB_BUFFER_SYNC IOCTL = %d",
604                            __FUNCTION__, (size_t) ns2ms(systemTime() - start));
605    }
606
607    if(ret < 0) {
608        ALOGE("ioctl MSMFB_BUFFER_SYNC failed, err=%s",
609                strerror(errno));
610    }
611
612    for(uint32_t i = 0; i < list->numHwLayers; i++) {
613        if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
614           list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
615            //Populate releaseFenceFds.
616            if(UNLIKELY(swapzero)) {
617                list->hwLayers[i].releaseFenceFd = -1;
618            } else if(list->hwLayers[i].releaseFenceFd < 0) {
619                //If rotator has not already populated this field.
620                list->hwLayers[i].releaseFenceFd = dup(releaseFd);
621            }
622        }
623    }
624
625    if(fd >= 0) {
626        close(fd);
627        fd = -1;
628    }
629
630    if (ctx->mCopyBit[dpy])
631        ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
632
633    //A-family
634    if(mdpVersion < qdutils::MDSS_V5) {
635        //Signals when MDP finishes reading rotator buffers.
636        ctx->mLayerRotMap[dpy]->setReleaseFd(releaseFd);
637    }
638
639    if(UNLIKELY(swapzero)){
640        list->retireFenceFd = -1;
641        close(releaseFd);
642    } else {
643        list->retireFenceFd = releaseFd;
644    }
645
646    return ret;
647}
648
649void trimLayer(hwc_context_t *ctx, const int& dpy, const int& transform,
650        hwc_rect_t& crop, hwc_rect_t& dst) {
651    int hw_w = ctx->dpyAttr[dpy].xres;
652    int hw_h = ctx->dpyAttr[dpy].yres;
653    if(dst.left < 0 || dst.top < 0 ||
654            dst.right > hw_w || dst.bottom > hw_h) {
655        hwc_rect_t scissor = {0, 0, hw_w, hw_h };
656        qhwc::calculate_crop_rects(crop, dst, scissor, transform);
657    }
658}
659
660void setMdpFlags(hwc_layer_1_t *layer,
661        ovutils::eMdpFlags &mdpFlags,
662        int rotDownscale) {
663    private_handle_t *hnd = (private_handle_t *)layer->handle;
664    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
665    const int& transform = layer->transform;
666
667    if(layer->blending == HWC_BLENDING_PREMULT) {
668        ovutils::setMdpFlags(mdpFlags,
669                ovutils::OV_MDP_BLEND_FG_PREMULT);
670    }
671
672    if(isYuvBuffer(hnd)) {
673        if(isSecureBuffer(hnd)) {
674            ovutils::setMdpFlags(mdpFlags,
675                    ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
676        }
677        if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
678                metadata->interlaced) {
679            ovutils::setMdpFlags(mdpFlags,
680                    ovutils::OV_MDP_DEINTERLACE);
681        }
682        //Pre-rotation will be used using rotator.
683        if(transform & HWC_TRANSFORM_ROT_90) {
684            ovutils::setMdpFlags(mdpFlags,
685                    ovutils::OV_MDP_SOURCE_ROTATED_90);
686        }
687    }
688
689    //No 90 component and no rot-downscale then flips done by MDP
690    //If we use rot then it might as well do flips
691    if(!(layer->transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
692        if(layer->transform & HWC_TRANSFORM_FLIP_H) {
693            ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
694        }
695
696        if(layer->transform & HWC_TRANSFORM_FLIP_V) {
697            ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
698        }
699    }
700
701    if(metadata &&
702        ((metadata->operation & PP_PARAM_HSIC)
703        || (metadata->operation & PP_PARAM_IGC)
704        || (metadata->operation & PP_PARAM_SHARP2))) {
705        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
706    }
707}
708
709static inline int configRotator(Rotator *rot, const Whf& whf,
710        const eMdpFlags& mdpFlags, const eTransform& orient,
711        const int& downscale) {
712    rot->setSource(whf);
713    rot->setFlags(mdpFlags);
714    rot->setTransform(orient);
715    rot->setDownscale(downscale);
716    if(!rot->commit()) return -1;
717    return 0;
718}
719
720/*
721 * Sets up BORDERFILL as default base pipe and detaches RGB0.
722 * Framebuffer is always updated using PLAY ioctl.
723 */
724bool setupBasePipe(hwc_context_t *ctx) {
725    const int dpy = HWC_DISPLAY_PRIMARY;
726    int fb_stride = ctx->dpyAttr[dpy].stride;
727    int fb_width = ctx->dpyAttr[dpy].xres;
728    int fb_height = ctx->dpyAttr[dpy].yres;
729    int fb_fd = ctx->dpyAttr[dpy].fd;
730
731    mdp_overlay ovInfo;
732    msmfb_overlay_data ovData;
733    memset(&ovInfo, 0, sizeof(mdp_overlay));
734    memset(&ovData, 0, sizeof(msmfb_overlay_data));
735
736    ovInfo.src.format = MDP_RGB_BORDERFILL;
737    ovInfo.src.width  = fb_width;
738    ovInfo.src.height = fb_height;
739    ovInfo.src_rect.w = fb_width;
740    ovInfo.src_rect.h = fb_height;
741    ovInfo.dst_rect.w = fb_width;
742    ovInfo.dst_rect.h = fb_height;
743    ovInfo.id = MSMFB_NEW_REQUEST;
744
745    if (ioctl(fb_fd, MSMFB_OVERLAY_SET, &ovInfo) < 0) {
746        ALOGE("Failed to call ioctl MSMFB_OVERLAY_SET err=%s",
747                strerror(errno));
748        return false;
749    }
750
751    ovData.id = ovInfo.id;
752    if (ioctl(fb_fd, MSMFB_OVERLAY_PLAY, &ovData) < 0) {
753        ALOGE("Failed to call ioctl MSMFB_OVERLAY_PLAY err=%s",
754                strerror(errno));
755        return false;
756    }
757    ctx->mBasePipeSetup = true;
758    return true;
759}
760
761
762static inline int configMdp(Overlay *ov, const PipeArgs& parg,
763        const eTransform& orient, const hwc_rect_t& crop,
764        const hwc_rect_t& pos, const MetaData_t *metadata,
765        const eDest& dest) {
766    ov->setSource(parg, dest);
767    ov->setTransform(orient, dest);
768
769    int crop_w = crop.right - crop.left;
770    int crop_h = crop.bottom - crop.top;
771    Dim dcrop(crop.left, crop.top, crop_w, crop_h);
772    ov->setCrop(dcrop, dest);
773
774    int posW = pos.right - pos.left;
775    int posH = pos.bottom - pos.top;
776    Dim position(pos.left, pos.top, posW, posH);
777    ov->setPosition(position, dest);
778
779    if (metadata)
780        ov->setVisualParams(*metadata, dest);
781
782    if (!ov->commit(dest)) {
783        return -1;
784    }
785    return 0;
786}
787
788static inline void updateSource(eTransform& orient, Whf& whf,
789        hwc_rect_t& crop) {
790    Dim srcCrop(crop.left, crop.top,
791            crop.right - crop.left,
792            crop.bottom - crop.top);
793    //getMdpOrient will switch the flips if the source is 90 rotated.
794    //Clients in Android dont factor in 90 rotation while deciding the flip.
795    orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
796    preRotateSource(orient, whf, srcCrop);
797    crop.left = srcCrop.x;
798    crop.top = srcCrop.y;
799    crop.right = srcCrop.x + srcCrop.w;
800    crop.bottom = srcCrop.y + srcCrop.h;
801}
802
803int configureLowRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
804        const int& dpy, eMdpFlags& mdpFlags, const eZorder& z,
805        const eIsFg& isFg, const eDest& dest, Rotator **rot) {
806
807    private_handle_t *hnd = (private_handle_t *)layer->handle;
808    if(!hnd) {
809        ALOGE("%s: layer handle is NULL", __FUNCTION__);
810        return -1;
811    }
812
813    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
814
815    hwc_rect_t crop = layer->sourceCrop;
816    hwc_rect_t dst = layer->displayFrame;
817    int transform = layer->transform;
818    eTransform orient = static_cast<eTransform>(transform);
819    int downscale = 0;
820    int rotFlags = ovutils::ROT_FLAGS_NONE;
821    Whf whf(hnd->width, hnd->height,
822            getMdpFormat(hnd->format), hnd->size);
823
824    if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
825                ctx->mMDP.version < qdutils::MDSS_V5) {
826        downscale = getDownscaleFactor(
827                crop.right - crop.left,
828                crop.bottom - crop.top,
829                dst.right - dst.left,
830                dst.bottom - dst.top);
831        if(downscale) {
832            rotFlags = ROT_DOWNSCALE_ENABLED;
833        }
834    }
835
836    setMdpFlags(layer, mdpFlags, downscale);
837    trimLayer(ctx, dpy, transform, crop, dst);
838
839    if(isYuvBuffer(hnd) && //if 90 component or downscale, use rot
840            ((transform & HWC_TRANSFORM_ROT_90) || downscale)) {
841        *rot = ctx->mRotMgr->getNext();
842        if(*rot == NULL) return -1;
843        //Configure rotator for pre-rotation
844        if(configRotator(*rot, whf, mdpFlags, orient, downscale) < 0)
845            return -1;
846        ctx->mLayerRotMap[dpy]->add(layer, *rot);
847        whf.format = (*rot)->getDstFormat();
848        updateSource(orient, whf, crop);
849        rotFlags |= ovutils::ROT_PREROTATED;
850    }
851
852    //For the mdp, since either we are pre-rotating or MDP does flips
853    orient = OVERLAY_TRANSFORM_0;
854    transform = 0;
855
856    PipeArgs parg(mdpFlags, whf, z, isFg, static_cast<eRotFlags>(rotFlags));
857    if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
858        ALOGE("%s: commit failed for low res panel", __FUNCTION__);
859        return -1;
860    }
861    return 0;
862}
863
864int configureHighRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
865        const int& dpy, eMdpFlags& mdpFlagsL, const eZorder& z,
866        const eIsFg& isFg, const eDest& lDest, const eDest& rDest,
867        Rotator **rot) {
868    private_handle_t *hnd = (private_handle_t *)layer->handle;
869    if(!hnd) {
870        ALOGE("%s: layer handle is NULL", __FUNCTION__);
871        return -1;
872    }
873
874    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
875
876    int hw_w = ctx->dpyAttr[dpy].xres;
877    int hw_h = ctx->dpyAttr[dpy].yres;
878    hwc_rect_t crop = layer->sourceCrop;
879    hwc_rect_t dst = layer->displayFrame;
880    int transform = layer->transform;
881    eTransform orient = static_cast<eTransform>(transform);
882    const int downscale = 0;
883    int rotFlags = ROT_FLAGS_NONE;
884
885    Whf whf(hnd->width, hnd->height,
886            getMdpFormat(hnd->format), hnd->size);
887
888    setMdpFlags(layer, mdpFlagsL);
889    trimLayer(ctx, dpy, transform, crop, dst);
890
891    if(isYuvBuffer(hnd) && (transform & HWC_TRANSFORM_ROT_90)) {
892        (*rot) = ctx->mRotMgr->getNext();
893        if((*rot) == NULL) return -1;
894        //Configure rotator for pre-rotation
895        if(configRotator(*rot, whf, mdpFlagsL, orient, downscale) < 0)
896            return -1;
897        ctx->mLayerRotMap[dpy]->add(layer, *rot);
898        whf.format = (*rot)->getDstFormat();
899        updateSource(orient, whf, crop);
900        rotFlags |= ROT_PREROTATED;
901    }
902
903    eMdpFlags mdpFlagsR = mdpFlagsL;
904    setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
905
906    hwc_rect_t tmp_cropL, tmp_dstL;
907    hwc_rect_t tmp_cropR, tmp_dstR;
908
909    if(lDest != OV_INVALID) {
910        tmp_cropL = crop;
911        tmp_dstL = dst;
912        hwc_rect_t scissor = {0, 0, hw_w/2, hw_h };
913        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
914    }
915    if(rDest != OV_INVALID) {
916        tmp_cropR = crop;
917        tmp_dstR = dst;
918        hwc_rect_t scissor = {hw_w/2, 0, hw_w, hw_h };
919        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
920    }
921
922    //When buffer is flipped, contents of mixer config also needs to swapped.
923    //Not needed if the layer is confined to one half of the screen.
924    //If rotator has been used then it has also done the flips, so ignore them.
925    if((orient & OVERLAY_TRANSFORM_FLIP_V) && lDest != OV_INVALID
926            && rDest != OV_INVALID && rot == NULL) {
927        hwc_rect_t new_cropR;
928        new_cropR.left = tmp_cropL.left;
929        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
930
931        hwc_rect_t new_cropL;
932        new_cropL.left  = new_cropR.right;
933        new_cropL.right = tmp_cropR.right;
934
935        tmp_cropL.left =  new_cropL.left;
936        tmp_cropL.right =  new_cropL.right;
937
938        tmp_cropR.left = new_cropR.left;
939        tmp_cropR.right =  new_cropR.right;
940
941    }
942
943    //For the mdp, since either we are pre-rotating or MDP does flips
944    orient = OVERLAY_TRANSFORM_0;
945    transform = 0;
946
947    //configure left mixer
948    if(lDest != OV_INVALID) {
949        PipeArgs pargL(mdpFlagsL, whf, z, isFg,
950                static_cast<eRotFlags>(rotFlags));
951        if(configMdp(ctx->mOverlay, pargL, orient,
952                tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
953            ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
954            return -1;
955        }
956    }
957
958    //configure right mixer
959    if(rDest != OV_INVALID) {
960        PipeArgs pargR(mdpFlagsR, whf, z, isFg,
961                static_cast<eRotFlags>(rotFlags));
962        tmp_dstR.right = tmp_dstR.right - tmp_dstR.left;
963        tmp_dstR.left = 0;
964        if(configMdp(ctx->mOverlay, pargR, orient,
965                tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
966            ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
967            return -1;
968        }
969    }
970
971    return 0;
972}
973
974void LayerCache::resetLayerCache(int num) {
975    for(uint32_t i = 0; i < MAX_NUM_LAYERS; i++) {
976        hnd[i] = NULL;
977    }
978    numHwLayers = num;
979}
980
981void LayerCache::updateLayerCache(hwc_display_contents_1_t* list) {
982
983    int numFbLayers = 0;
984    int numCacheableLayers = 0;
985
986    canUseLayerCache = false;
987    //Bail if geometry changed or num of layers changed
988    if(list->flags & HWC_GEOMETRY_CHANGED ||
989       list->numHwLayers != numHwLayers ) {
990        resetLayerCache(list->numHwLayers);
991        return;
992    }
993
994    for(uint32_t i = 0; i < list->numHwLayers; i++) {
995        //Bail on skip layers
996        if(list->hwLayers[i].flags & HWC_SKIP_LAYER) {
997            resetLayerCache(list->numHwLayers);
998            return;
999        }
1000
1001        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER) {
1002            numFbLayers++;
1003            if(hnd[i] == NULL) {
1004                hnd[i] = list->hwLayers[i].handle;
1005            } else if (hnd[i] ==
1006                       list->hwLayers[i].handle) {
1007                numCacheableLayers++;
1008            } else {
1009                hnd[i] = NULL;
1010                return;
1011            }
1012        } else {
1013            hnd[i] = NULL;
1014        }
1015    }
1016    if(numFbLayers == numCacheableLayers)
1017        canUseLayerCache = true;
1018
1019    //XXX: The marking part is separate, if MDP comp wants
1020    // to use it in the future. Right now getting MDP comp
1021    // to use this is more trouble than it is worth.
1022    markCachedLayersAsOverlay(list);
1023}
1024
1025void LayerCache::markCachedLayersAsOverlay(hwc_display_contents_1_t* list) {
1026    //This optimization only works if ALL the layer handles
1027    //that were on the framebuffer didn't change.
1028    if(canUseLayerCache){
1029        for(uint32_t i = 0; i < list->numHwLayers; i++) {
1030            if (list->hwLayers[i].handle &&
1031                list->hwLayers[i].handle == hnd[i] &&
1032                list->hwLayers[i].compositionType != HWC_FRAMEBUFFER_TARGET)
1033            {
1034                list->hwLayers[i].compositionType = HWC_OVERLAY;
1035            }
1036        }
1037    }
1038}
1039
1040void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) {
1041    if(mCount >= MAX_SESS) return;
1042    mLayer[mCount] = layer;
1043    mRot[mCount] = rot;
1044    mCount++;
1045}
1046
1047void LayerRotMap::reset() {
1048    for (int i = 0; i < MAX_SESS; i++) {
1049        mLayer[i] = 0;
1050        mRot[i] = 0;
1051    }
1052    mCount = 0;
1053}
1054
1055void LayerRotMap::setReleaseFd(const int& fence) {
1056    for(uint32_t i = 0; i < mCount; i++) {
1057        mRot[i]->setReleaseFd(dup(fence));
1058    }
1059}
1060
1061};//namespace qhwc
1062