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