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