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