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