hwc_utils.cpp revision ac1391615c3d70676a31aae57e51e47db2ee57d8
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].planeAlpha = false;
329    ctx->listStats[dpy].yuvCount = 0;
330
331    for (size_t i = 0; i < list->numHwLayers; i++) {
332        hwc_layer_1_t const* layer = &list->hwLayers[i];
333        private_handle_t *hnd = (private_handle_t *)layer->handle;
334
335        //reset stored yuv index
336        ctx->listStats[dpy].yuvIndices[i] = -1;
337
338        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
339            continue;
340        //We disregard FB being skip for now! so the else if
341        } else if (isSkipLayer(&list->hwLayers[i])) {
342            ctx->listStats[dpy].skipCount++;
343        } else if (UNLIKELY(isYuvBuffer(hnd))) {
344            int& yuvCount = ctx->listStats[dpy].yuvCount;
345            ctx->listStats[dpy].yuvIndices[yuvCount] = i;
346            yuvCount++;
347
348            if(layer->transform & HWC_TRANSFORM_ROT_90)
349                ctx->mNeedsRotator = true;
350        }
351        if(layer->blending == HWC_BLENDING_PREMULT)
352            ctx->listStats[dpy].preMultipliedAlpha = true;
353        if(layer->planeAlpha < 0xFF)
354            ctx->listStats[dpy].planeAlpha = true;
355        if(!ctx->listStats[dpy].needsAlphaScale)
356            ctx->listStats[dpy].needsAlphaScale = isAlphaScaled(layer);
357    }
358}
359
360
361static inline void calc_cut(float& leftCutRatio, float& topCutRatio,
362        float& rightCutRatio, float& bottomCutRatio, int orient) {
363    if(orient & HAL_TRANSFORM_FLIP_H) {
364        swap(leftCutRatio, rightCutRatio);
365    }
366    if(orient & HAL_TRANSFORM_FLIP_V) {
367        swap(topCutRatio, bottomCutRatio);
368    }
369    if(orient & HAL_TRANSFORM_ROT_90) {
370        //Anti clock swapping
371        float tmpCutRatio = leftCutRatio;
372        leftCutRatio = topCutRatio;
373        topCutRatio = rightCutRatio;
374        rightCutRatio = bottomCutRatio;
375        bottomCutRatio = tmpCutRatio;
376    }
377}
378
379bool isSecuring(hwc_context_t* ctx, hwc_layer_1_t const* layer) {
380    if((ctx->mMDP.version < qdutils::MDSS_V5) &&
381       (ctx->mMDP.version > qdutils::MDP_V3_0) &&
382        ctx->mSecuring) {
383        return true;
384    }
385    //  On A-Family, Secure policy is applied system wide and not on
386    //  buffers.
387    if (isSecureModePolicy(ctx->mMDP.version)) {
388        private_handle_t *hnd = (private_handle_t *)layer->handle;
389        if(ctx->mSecureMode) {
390            if (! isSecureBuffer(hnd)) {
391                // This code path executes for the following usecase:
392                // Some Apps in which first few seconds, framework
393                // sends non-secure buffer and with out destroying
394                // surfaces, switches to secure buffer thereby exposing
395                // vulnerability on A-family devices. Catch this situation
396                // and handle it gracefully by allowing it to be composed by
397                // GPU.
398                ALOGD_IF(HWC_UTILS_DEBUG, "%s: Handle non-secure video layer"
399                         "during secure playback gracefully", __FUNCTION__);
400                return true;
401            }
402        } else {
403            if (isSecureBuffer(hnd)) {
404                // This code path executes for the following usecase:
405                // For some Apps, when User terminates playback, Framework
406                // doesnt destroy video surface and video surface still
407                // comes to Display HAL. This exposes vulnerability on
408                // A-family. Catch this situation and handle it gracefully
409                // by allowing it to be composed by GPU.
410                ALOGD_IF(HWC_UTILS_DEBUG, "%s: Handle secure video layer"
411                         "during non-secure playback gracefully", __FUNCTION__);
412                return true;
413            }
414        }
415    }
416    return false;
417}
418
419bool isSecureModePolicy(int mdpVersion) {
420    if (mdpVersion < qdutils::MDSS_V5)
421        return true;
422    else
423        return false;
424}
425
426int getBlending(int blending) {
427    switch(blending) {
428    case HWC_BLENDING_NONE:
429        return overlay::utils::OVERLAY_BLENDING_OPAQUE;
430    case HWC_BLENDING_PREMULT:
431        return overlay::utils::OVERLAY_BLENDING_PREMULT;
432    case HWC_BLENDING_COVERAGE :
433    default:
434        return overlay::utils::OVERLAY_BLENDING_COVERAGE;
435    }
436}
437
438//Crops source buffer against destination and FB boundaries
439void calculate_crop_rects(hwc_rect_t& crop, hwc_rect_t& dst,
440                          const hwc_rect_t& scissor, int orient) {
441
442    int& crop_l = crop.left;
443    int& crop_t = crop.top;
444    int& crop_r = crop.right;
445    int& crop_b = crop.bottom;
446    int crop_w = crop.right - crop.left;
447    int crop_h = crop.bottom - crop.top;
448
449    int& dst_l = dst.left;
450    int& dst_t = dst.top;
451    int& dst_r = dst.right;
452    int& dst_b = dst.bottom;
453    int dst_w = abs(dst.right - dst.left);
454    int dst_h = abs(dst.bottom - dst.top);
455
456    const int& sci_l = scissor.left;
457    const int& sci_t = scissor.top;
458    const int& sci_r = scissor.right;
459    const int& sci_b = scissor.bottom;
460    int sci_w = abs(sci_r - sci_l);
461    int sci_h = abs(sci_b - sci_t);
462
463    float leftCutRatio = 0.0f, rightCutRatio = 0.0f, topCutRatio = 0.0f,
464            bottomCutRatio = 0.0f;
465
466    if(dst_l < sci_l) {
467        leftCutRatio = (float)(sci_l - dst_l) / (float)dst_w;
468        dst_l = sci_l;
469    }
470
471    if(dst_r > sci_r) {
472        rightCutRatio = (float)(dst_r - sci_r) / (float)dst_w;
473        dst_r = sci_r;
474    }
475
476    if(dst_t < sci_t) {
477        topCutRatio = (float)(sci_t - dst_t) / (float)dst_h;
478        dst_t = sci_t;
479    }
480
481    if(dst_b > sci_b) {
482        bottomCutRatio = (float)(dst_b - sci_b) / (float)dst_h;
483        dst_b = sci_b;
484    }
485
486    calc_cut(leftCutRatio, topCutRatio, rightCutRatio, bottomCutRatio, orient);
487    crop_l += crop_w * leftCutRatio;
488    crop_t += crop_h * topCutRatio;
489    crop_r -= crop_w * rightCutRatio;
490    crop_b -= crop_h * bottomCutRatio;
491}
492
493void getNonWormholeRegion(hwc_display_contents_1_t* list,
494                              hwc_rect_t& nwr)
495{
496    uint32_t last = list->numHwLayers - 1;
497    hwc_rect_t fbDisplayFrame = list->hwLayers[last].displayFrame;
498    //Initiliaze nwr to first frame
499    nwr.left =  list->hwLayers[0].displayFrame.left;
500    nwr.top =  list->hwLayers[0].displayFrame.top;
501    nwr.right =  list->hwLayers[0].displayFrame.right;
502    nwr.bottom =  list->hwLayers[0].displayFrame.bottom;
503
504    for (uint32_t i = 1; i < last; i++) {
505        hwc_rect_t displayFrame = list->hwLayers[i].displayFrame;
506        nwr.left   = min(nwr.left, displayFrame.left);
507        nwr.top    = min(nwr.top, displayFrame.top);
508        nwr.right  = max(nwr.right, displayFrame.right);
509        nwr.bottom = max(nwr.bottom, displayFrame.bottom);
510    }
511
512    //Intersect with the framebuffer
513    nwr.left   = max(nwr.left, fbDisplayFrame.left);
514    nwr.top    = max(nwr.top, fbDisplayFrame.top);
515    nwr.right  = min(nwr.right, fbDisplayFrame.right);
516    nwr.bottom = min(nwr.bottom, fbDisplayFrame.bottom);
517
518}
519
520bool isExternalActive(hwc_context_t* ctx) {
521    return ctx->dpyAttr[HWC_DISPLAY_EXTERNAL].isActive;
522}
523
524void closeAcquireFds(hwc_display_contents_1_t* list) {
525    if(LIKELY(list)) {
526        for(uint32_t i = 0; i < list->numHwLayers; i++) {
527            //Close the acquireFenceFds
528            //HWC_FRAMEBUFFER are -1 already by SF, rest we close.
529            if(list->hwLayers[i].acquireFenceFd >= 0) {
530                close(list->hwLayers[i].acquireFenceFd);
531                list->hwLayers[i].acquireFenceFd = -1;
532            }
533        }
534
535        if (list->outbufAcquireFenceFd >= 0 ) {
536            close(list->outbufAcquireFenceFd);
537            list->outbufAcquireFenceFd = -1;
538        }
539    }
540}
541
542int hwc_sync(hwc_context_t *ctx, hwc_display_contents_1_t* list, int dpy,
543        int fd) {
544    int ret = 0;
545
546    int acquireFd[MAX_NUM_LAYERS];
547    int count = 0;
548    int releaseFd = -1;
549    int fbFd = -1;
550    int rotFd = -1;
551    bool swapzero = false;
552    int mdpVersion = qdutils::MDPVersion::getInstance().getMDPVersion();
553
554    struct mdp_buf_sync data;
555    memset(&data, 0, sizeof(data));
556    //Until B-family supports sync for rotator
557    if(mdpVersion >= qdutils::MDSS_V5) {
558        data.flags = MDP_BUF_SYNC_FLAG_WAIT;
559    }
560    data.acq_fen_fd = acquireFd;
561    data.rel_fen_fd = &releaseFd;
562
563    char property[PROPERTY_VALUE_MAX];
564    if(property_get("debug.egl.swapinterval", property, "1") > 0) {
565        if(atoi(property) == 0)
566            swapzero = true;
567    }
568
569#ifndef MDSS_TARGET
570    //Send acquireFenceFds to rotator
571    if(mdpVersion < qdutils::MDSS_V5) {
572        //A-family
573        int rotFd = ctx->mRotMgr->getRotDevFd();
574        struct msm_rotator_buf_sync rotData;
575
576        for(uint32_t i = 0; i < ctx->mLayerRotMap[dpy]->getCount(); i++) {
577            memset(&rotData, 0, sizeof(rotData));
578            int& acquireFenceFd =
579                ctx->mLayerRotMap[dpy]->getLayer(i)->acquireFenceFd;
580            rotData.acq_fen_fd = acquireFenceFd;
581            rotData.session_id = ctx->mLayerRotMap[dpy]->getRot(i)->getSessId();
582            ioctl(rotFd, MSM_ROTATOR_IOCTL_BUFFER_SYNC, &rotData);
583            close(acquireFenceFd);
584             //For MDP to wait on.
585            acquireFenceFd = dup(rotData.rel_fen_fd);
586            //A buffer is free to be used by producer as soon as its copied to
587            //rotator.
588            ctx->mLayerRotMap[dpy]->getLayer(i)->releaseFenceFd =
589                    rotData.rel_fen_fd;
590        }
591    } else {
592        //TODO B-family
593    }
594
595#endif
596    //Accumulate acquireFenceFds for MDP
597    for(uint32_t i = 0; i < list->numHwLayers; i++) {
598        if(list->hwLayers[i].compositionType == HWC_OVERLAY &&
599                        list->hwLayers[i].acquireFenceFd >= 0) {
600            if(UNLIKELY(swapzero))
601                acquireFd[count++] = -1;
602            else
603                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
604        }
605        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
606            if(UNLIKELY(swapzero))
607                acquireFd[count++] = -1;
608            else if(fd >= 0) {
609                //set the acquireFD from fd - which is coming from c2d
610                acquireFd[count++] = fd;
611                // Buffer sync IOCTL should be async when using c2d fence is
612                // used
613                data.flags &= ~MDP_BUF_SYNC_FLAG_WAIT;
614            } else if(list->hwLayers[i].acquireFenceFd >= 0)
615                acquireFd[count++] = list->hwLayers[i].acquireFenceFd;
616        }
617    }
618
619    data.acq_fen_fd_cnt = count;
620    fbFd = ctx->dpyAttr[dpy].fd;
621
622    //Waits for acquire fences, returns a release fence
623    if(LIKELY(!swapzero)) {
624        uint64_t start = systemTime();
625        ret = ioctl(fbFd, MSMFB_BUFFER_SYNC, &data);
626        ALOGD_IF(HWC_UTILS_DEBUG, "%s: time taken for MSMFB_BUFFER_SYNC IOCTL = %d",
627                            __FUNCTION__, (size_t) ns2ms(systemTime() - start));
628    }
629
630    if(ret < 0) {
631        ALOGE("ioctl MSMFB_BUFFER_SYNC failed, err=%s",
632                strerror(errno));
633    }
634
635    for(uint32_t i = 0; i < list->numHwLayers; i++) {
636        if(list->hwLayers[i].compositionType == HWC_OVERLAY ||
637           list->hwLayers[i].compositionType == HWC_FRAMEBUFFER_TARGET) {
638            //Populate releaseFenceFds.
639            if(UNLIKELY(swapzero)) {
640                list->hwLayers[i].releaseFenceFd = -1;
641            } else if(list->hwLayers[i].releaseFenceFd < 0) {
642                //If rotator has not already populated this field.
643                list->hwLayers[i].releaseFenceFd = dup(releaseFd);
644            }
645        }
646    }
647
648    if(fd >= 0) {
649        close(fd);
650        fd = -1;
651    }
652
653    if (ctx->mCopyBit[dpy])
654        ctx->mCopyBit[dpy]->setReleaseFd(releaseFd);
655
656    //A-family
657    if(mdpVersion < qdutils::MDSS_V5) {
658        //Signals when MDP finishes reading rotator buffers.
659        ctx->mLayerRotMap[dpy]->setReleaseFd(releaseFd);
660    }
661
662    if(UNLIKELY(swapzero)){
663        list->retireFenceFd = -1;
664        close(releaseFd);
665    } else {
666        list->retireFenceFd = releaseFd;
667    }
668
669    return ret;
670}
671
672void trimLayer(hwc_context_t *ctx, const int& dpy, const int& transform,
673        hwc_rect_t& crop, hwc_rect_t& dst) {
674    int hw_w = ctx->dpyAttr[dpy].xres;
675    int hw_h = ctx->dpyAttr[dpy].yres;
676    if(dst.left < 0 || dst.top < 0 ||
677            dst.right > hw_w || dst.bottom > hw_h) {
678        hwc_rect_t scissor = {0, 0, hw_w, hw_h };
679        qhwc::calculate_crop_rects(crop, dst, scissor, transform);
680    }
681}
682
683void setMdpFlags(hwc_layer_1_t *layer,
684        ovutils::eMdpFlags &mdpFlags,
685        int rotDownscale) {
686    private_handle_t *hnd = (private_handle_t *)layer->handle;
687    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
688    const int& transform = layer->transform;
689
690    if(layer->blending == HWC_BLENDING_PREMULT) {
691        ovutils::setMdpFlags(mdpFlags,
692                ovutils::OV_MDP_BLEND_FG_PREMULT);
693    }
694
695    if(isYuvBuffer(hnd)) {
696        if(isSecureBuffer(hnd)) {
697            ovutils::setMdpFlags(mdpFlags,
698                    ovutils::OV_MDP_SECURE_OVERLAY_SESSION);
699        }
700        if(metadata && (metadata->operation & PP_PARAM_INTERLACED) &&
701                metadata->interlaced) {
702            ovutils::setMdpFlags(mdpFlags,
703                    ovutils::OV_MDP_DEINTERLACE);
704        }
705        //Pre-rotation will be used using rotator.
706        if(transform & HWC_TRANSFORM_ROT_90) {
707            ovutils::setMdpFlags(mdpFlags,
708                    ovutils::OV_MDP_SOURCE_ROTATED_90);
709        }
710    }
711
712    //No 90 component and no rot-downscale then flips done by MDP
713    //If we use rot then it might as well do flips
714    if(!(layer->transform & HWC_TRANSFORM_ROT_90) && !rotDownscale) {
715        if(layer->transform & HWC_TRANSFORM_FLIP_H) {
716            ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_FLIP_H);
717        }
718
719        if(layer->transform & HWC_TRANSFORM_FLIP_V) {
720            ovutils::setMdpFlags(mdpFlags,  ovutils::OV_MDP_FLIP_V);
721        }
722    }
723
724    if(metadata &&
725        ((metadata->operation & PP_PARAM_HSIC)
726        || (metadata->operation & PP_PARAM_IGC)
727        || (metadata->operation & PP_PARAM_SHARP2))) {
728        ovutils::setMdpFlags(mdpFlags, ovutils::OV_MDP_PP_EN);
729    }
730}
731
732static inline int configRotator(Rotator *rot, const Whf& whf,
733        const eMdpFlags& mdpFlags, const eTransform& orient,
734        const int& downscale) {
735    rot->setSource(whf);
736    rot->setFlags(mdpFlags);
737    rot->setTransform(orient);
738    rot->setDownscale(downscale);
739    if(!rot->commit()) return -1;
740    return 0;
741}
742
743/*
744 * Sets up BORDERFILL as default base pipe and detaches RGB0.
745 * Framebuffer is always updated using PLAY ioctl.
746 */
747bool setupBasePipe(hwc_context_t *ctx) {
748    const int dpy = HWC_DISPLAY_PRIMARY;
749    int fb_stride = ctx->dpyAttr[dpy].stride;
750    int fb_width = ctx->dpyAttr[dpy].xres;
751    int fb_height = ctx->dpyAttr[dpy].yres;
752    int fb_fd = ctx->dpyAttr[dpy].fd;
753
754    mdp_overlay ovInfo;
755    msmfb_overlay_data ovData;
756    memset(&ovInfo, 0, sizeof(mdp_overlay));
757    memset(&ovData, 0, sizeof(msmfb_overlay_data));
758
759    ovInfo.src.format = MDP_RGB_BORDERFILL;
760    ovInfo.src.width  = fb_width;
761    ovInfo.src.height = fb_height;
762    ovInfo.src_rect.w = fb_width;
763    ovInfo.src_rect.h = fb_height;
764    ovInfo.dst_rect.w = fb_width;
765    ovInfo.dst_rect.h = fb_height;
766    ovInfo.id = MSMFB_NEW_REQUEST;
767
768    if (ioctl(fb_fd, MSMFB_OVERLAY_SET, &ovInfo) < 0) {
769        ALOGE("Failed to call ioctl MSMFB_OVERLAY_SET err=%s",
770                strerror(errno));
771        return false;
772    }
773
774    ovData.id = ovInfo.id;
775    if (ioctl(fb_fd, MSMFB_OVERLAY_PLAY, &ovData) < 0) {
776        ALOGE("Failed to call ioctl MSMFB_OVERLAY_PLAY err=%s",
777                strerror(errno));
778        return false;
779    }
780    ctx->mBasePipeSetup = true;
781    return true;
782}
783
784
785static inline int configMdp(Overlay *ov, const PipeArgs& parg,
786        const eTransform& orient, const hwc_rect_t& crop,
787        const hwc_rect_t& pos, const MetaData_t *metadata,
788        const eDest& dest) {
789    ov->setSource(parg, dest);
790    ov->setTransform(orient, dest);
791
792    int crop_w = crop.right - crop.left;
793    int crop_h = crop.bottom - crop.top;
794    Dim dcrop(crop.left, crop.top, crop_w, crop_h);
795    ov->setCrop(dcrop, dest);
796
797    int posW = pos.right - pos.left;
798    int posH = pos.bottom - pos.top;
799    Dim position(pos.left, pos.top, posW, posH);
800    ov->setPosition(position, dest);
801
802    if (metadata)
803        ov->setVisualParams(*metadata, dest);
804
805    if (!ov->commit(dest)) {
806        return -1;
807    }
808    return 0;
809}
810
811static inline void updateSource(eTransform& orient, Whf& whf,
812        hwc_rect_t& crop) {
813    Dim srcCrop(crop.left, crop.top,
814            crop.right - crop.left,
815            crop.bottom - crop.top);
816    //getMdpOrient will switch the flips if the source is 90 rotated.
817    //Clients in Android dont factor in 90 rotation while deciding the flip.
818    orient = static_cast<eTransform>(ovutils::getMdpOrient(orient));
819    preRotateSource(orient, whf, srcCrop);
820    crop.left = srcCrop.x;
821    crop.top = srcCrop.y;
822    crop.right = srcCrop.x + srcCrop.w;
823    crop.bottom = srcCrop.y + srcCrop.h;
824}
825
826int configureLowRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
827        const int& dpy, eMdpFlags& mdpFlags, const eZorder& z,
828        const eIsFg& isFg, const eDest& dest, Rotator **rot) {
829
830    private_handle_t *hnd = (private_handle_t *)layer->handle;
831    if(!hnd) {
832        ALOGE("%s: layer handle is NULL", __FUNCTION__);
833        return -1;
834    }
835
836    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
837
838    hwc_rect_t crop = layer->sourceCrop;
839    hwc_rect_t dst = layer->displayFrame;
840    int transform = layer->transform;
841    eTransform orient = static_cast<eTransform>(transform);
842    int downscale = 0;
843    int rotFlags = ovutils::ROT_FLAGS_NONE;
844    Whf whf(hnd->width, hnd->height,
845            getMdpFormat(hnd->format), hnd->size);
846
847    if(isYuvBuffer(hnd) && ctx->mMDP.version >= qdutils::MDP_V4_2 &&
848                ctx->mMDP.version < qdutils::MDSS_V5) {
849        downscale = getDownscaleFactor(
850                crop.right - crop.left,
851                crop.bottom - crop.top,
852                dst.right - dst.left,
853                dst.bottom - dst.top);
854        if(downscale) {
855            rotFlags = ROT_DOWNSCALE_ENABLED;
856        }
857    }
858
859    setMdpFlags(layer, mdpFlags, downscale);
860    trimLayer(ctx, dpy, transform, crop, dst);
861
862    if(isYuvBuffer(hnd) && //if 90 component or downscale, use rot
863            ((transform & HWC_TRANSFORM_ROT_90) || downscale)) {
864        *rot = ctx->mRotMgr->getNext();
865        if(*rot == NULL) return -1;
866        //Configure rotator for pre-rotation
867        if(configRotator(*rot, whf, mdpFlags, orient, downscale) < 0)
868            return -1;
869        ctx->mLayerRotMap[dpy]->add(layer, *rot);
870        whf.format = (*rot)->getDstFormat();
871        updateSource(orient, whf, crop);
872        rotFlags |= ovutils::ROT_PREROTATED;
873    }
874
875    //For the mdp, since either we are pre-rotating or MDP does flips
876    orient = OVERLAY_TRANSFORM_0;
877    transform = 0;
878
879    PipeArgs parg(mdpFlags, whf, z, isFg,
880                  static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
881                  (ovutils::eBlending) getBlending(layer->blending));
882
883    if(configMdp(ctx->mOverlay, parg, orient, crop, dst, metadata, dest) < 0) {
884        ALOGE("%s: commit failed for low res panel", __FUNCTION__);
885        return -1;
886    }
887    return 0;
888}
889
890int configureHighRes(hwc_context_t *ctx, hwc_layer_1_t *layer,
891        const int& dpy, eMdpFlags& mdpFlagsL, const eZorder& z,
892        const eIsFg& isFg, const eDest& lDest, const eDest& rDest,
893        Rotator **rot) {
894    private_handle_t *hnd = (private_handle_t *)layer->handle;
895    if(!hnd) {
896        ALOGE("%s: layer handle is NULL", __FUNCTION__);
897        return -1;
898    }
899
900    MetaData_t *metadata = (MetaData_t *)hnd->base_metadata;
901
902    int hw_w = ctx->dpyAttr[dpy].xres;
903    int hw_h = ctx->dpyAttr[dpy].yres;
904    hwc_rect_t crop = layer->sourceCrop;
905    hwc_rect_t dst = layer->displayFrame;
906    int transform = layer->transform;
907    eTransform orient = static_cast<eTransform>(transform);
908    const int downscale = 0;
909    int rotFlags = ROT_FLAGS_NONE;
910
911    Whf whf(hnd->width, hnd->height,
912            getMdpFormat(hnd->format), hnd->size);
913
914    setMdpFlags(layer, mdpFlagsL);
915    trimLayer(ctx, dpy, transform, crop, dst);
916
917    if(isYuvBuffer(hnd) && (transform & HWC_TRANSFORM_ROT_90)) {
918        (*rot) = ctx->mRotMgr->getNext();
919        if((*rot) == NULL) return -1;
920        //Configure rotator for pre-rotation
921        if(configRotator(*rot, whf, mdpFlagsL, orient, downscale) < 0)
922            return -1;
923        ctx->mLayerRotMap[dpy]->add(layer, *rot);
924        whf.format = (*rot)->getDstFormat();
925        updateSource(orient, whf, crop);
926        rotFlags |= ROT_PREROTATED;
927    }
928
929    eMdpFlags mdpFlagsR = mdpFlagsL;
930    setMdpFlags(mdpFlagsR, OV_MDSS_MDP_RIGHT_MIXER);
931
932    hwc_rect_t tmp_cropL, tmp_dstL;
933    hwc_rect_t tmp_cropR, tmp_dstR;
934
935    if(lDest != OV_INVALID) {
936        tmp_cropL = crop;
937        tmp_dstL = dst;
938        hwc_rect_t scissor = {0, 0, hw_w/2, hw_h };
939        qhwc::calculate_crop_rects(tmp_cropL, tmp_dstL, scissor, 0);
940    }
941    if(rDest != OV_INVALID) {
942        tmp_cropR = crop;
943        tmp_dstR = dst;
944        hwc_rect_t scissor = {hw_w/2, 0, hw_w, hw_h };
945        qhwc::calculate_crop_rects(tmp_cropR, tmp_dstR, scissor, 0);
946    }
947
948    //When buffer is flipped, contents of mixer config also needs to swapped.
949    //Not needed if the layer is confined to one half of the screen.
950    //If rotator has been used then it has also done the flips, so ignore them.
951    if((orient & OVERLAY_TRANSFORM_FLIP_V) && lDest != OV_INVALID
952            && rDest != OV_INVALID && rot == NULL) {
953        hwc_rect_t new_cropR;
954        new_cropR.left = tmp_cropL.left;
955        new_cropR.right = new_cropR.left + (tmp_cropR.right - tmp_cropR.left);
956
957        hwc_rect_t new_cropL;
958        new_cropL.left  = new_cropR.right;
959        new_cropL.right = tmp_cropR.right;
960
961        tmp_cropL.left =  new_cropL.left;
962        tmp_cropL.right =  new_cropL.right;
963
964        tmp_cropR.left = new_cropR.left;
965        tmp_cropR.right =  new_cropR.right;
966
967    }
968
969    //For the mdp, since either we are pre-rotating or MDP does flips
970    orient = OVERLAY_TRANSFORM_0;
971    transform = 0;
972
973    //configure left mixer
974    if(lDest != OV_INVALID) {
975        PipeArgs pargL(mdpFlagsL, whf, z, isFg,
976                       static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
977                       (ovutils::eBlending) getBlending(layer->blending));
978
979        if(configMdp(ctx->mOverlay, pargL, orient,
980                tmp_cropL, tmp_dstL, metadata, lDest) < 0) {
981            ALOGE("%s: commit failed for left mixer config", __FUNCTION__);
982            return -1;
983        }
984    }
985
986    //configure right mixer
987    if(rDest != OV_INVALID) {
988        PipeArgs pargR(mdpFlagsR, whf, z, isFg,
989                static_cast<eRotFlags>(rotFlags), layer->planeAlpha,
990                (ovutils::eBlending) getBlending(layer->blending));
991
992        tmp_dstR.right = tmp_dstR.right - tmp_dstR.left;
993        tmp_dstR.left = 0;
994        if(configMdp(ctx->mOverlay, pargR, orient,
995                tmp_cropR, tmp_dstR, metadata, rDest) < 0) {
996            ALOGE("%s: commit failed for right mixer config", __FUNCTION__);
997            return -1;
998        }
999    }
1000
1001    return 0;
1002}
1003
1004void LayerCache::resetLayerCache(int num) {
1005    for(uint32_t i = 0; i < MAX_NUM_LAYERS; i++) {
1006        hnd[i] = NULL;
1007    }
1008    numHwLayers = num;
1009}
1010
1011void LayerCache::updateLayerCache(hwc_display_contents_1_t* list) {
1012
1013    int numFbLayers = 0;
1014    int numCacheableLayers = 0;
1015
1016    canUseLayerCache = false;
1017    //Bail if geometry changed or num of layers changed
1018    if(list->flags & HWC_GEOMETRY_CHANGED ||
1019       list->numHwLayers != numHwLayers ) {
1020        resetLayerCache(list->numHwLayers);
1021        return;
1022    }
1023
1024    for(uint32_t i = 0; i < list->numHwLayers; i++) {
1025        //Bail on skip layers
1026        if(list->hwLayers[i].flags & HWC_SKIP_LAYER) {
1027            resetLayerCache(list->numHwLayers);
1028            return;
1029        }
1030
1031        if(list->hwLayers[i].compositionType == HWC_FRAMEBUFFER) {
1032            numFbLayers++;
1033            if(hnd[i] == NULL) {
1034                hnd[i] = list->hwLayers[i].handle;
1035            } else if (hnd[i] ==
1036                       list->hwLayers[i].handle) {
1037                numCacheableLayers++;
1038            } else {
1039                hnd[i] = NULL;
1040                return;
1041            }
1042        } else {
1043            hnd[i] = NULL;
1044        }
1045    }
1046    if(numFbLayers == numCacheableLayers)
1047        canUseLayerCache = true;
1048
1049    //XXX: The marking part is separate, if MDP comp wants
1050    // to use it in the future. Right now getting MDP comp
1051    // to use this is more trouble than it is worth.
1052    markCachedLayersAsOverlay(list);
1053}
1054
1055void LayerCache::markCachedLayersAsOverlay(hwc_display_contents_1_t* list) {
1056    //This optimization only works if ALL the layer handles
1057    //that were on the framebuffer didn't change.
1058    if(canUseLayerCache){
1059        for(uint32_t i = 0; i < list->numHwLayers; i++) {
1060            if (list->hwLayers[i].handle &&
1061                list->hwLayers[i].handle == hnd[i] &&
1062                list->hwLayers[i].compositionType != HWC_FRAMEBUFFER_TARGET)
1063            {
1064                list->hwLayers[i].compositionType = HWC_OVERLAY;
1065            }
1066        }
1067    }
1068}
1069
1070void LayerRotMap::add(hwc_layer_1_t* layer, Rotator *rot) {
1071    if(mCount >= MAX_SESS) return;
1072    mLayer[mCount] = layer;
1073    mRot[mCount] = rot;
1074    mCount++;
1075}
1076
1077void LayerRotMap::reset() {
1078    for (int i = 0; i < MAX_SESS; i++) {
1079        mLayer[i] = 0;
1080        mRot[i] = 0;
1081    }
1082    mCount = 0;
1083}
1084
1085void LayerRotMap::setReleaseFd(const int& fence) {
1086    for(uint32_t i = 0; i < mCount; i++) {
1087        mRot[i]->setReleaseFd(dup(fence));
1088    }
1089}
1090
1091};//namespace qhwc
1092