1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * Copyright (c) 2010-2016, 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#include <cutils/log.h>
21#include <sys/resource.h>
22#include <sys/prctl.h>
23
24#include <stdint.h>
25#include <string.h>
26#include <unistd.h>
27#include <errno.h>
28#include <fcntl.h>
29
30#include <sys/ioctl.h>
31#include <sys/types.h>
32#include <sys/mman.h>
33
34#include <linux/msm_kgsl.h>
35
36#include <EGL/eglplatform.h>
37#include <cutils/native_handle.h>
38
39#include <copybit.h>
40#include <alloc_controller.h>
41#include <memalloc.h>
42
43#include "c2d2.h"
44#include "software_converter.h"
45
46#include <dlfcn.h>
47
48using gralloc::IMemAlloc;
49using gralloc::IonController;
50using gralloc::alloc_data;
51
52C2D_STATUS (*LINK_c2dCreateSurface)( uint32 *surface_id,
53                                     uint32 surface_bits,
54                                     C2D_SURFACE_TYPE surface_type,
55                                     void *surface_definition );
56
57C2D_STATUS (*LINK_c2dUpdateSurface)( uint32 surface_id,
58                                     uint32 surface_bits,
59                                     C2D_SURFACE_TYPE surface_type,
60                                     void *surface_definition );
61
62C2D_STATUS (*LINK_c2dReadSurface)( uint32 surface_id,
63                                   C2D_SURFACE_TYPE surface_type,
64                                   void *surface_definition,
65                                   int32 x, int32 y );
66
67C2D_STATUS (*LINK_c2dDraw)( uint32 target_id,
68                            uint32 target_config, C2D_RECT *target_scissor,
69                            uint32 target_mask_id, uint32 target_color_key,
70                            C2D_OBJECT *objects_list, uint32 num_objects );
71
72C2D_STATUS (*LINK_c2dFinish)( uint32 target_id);
73
74C2D_STATUS (*LINK_c2dFlush)( uint32 target_id, c2d_ts_handle *timestamp);
75
76C2D_STATUS (*LINK_c2dWaitTimestamp)( c2d_ts_handle timestamp );
77
78C2D_STATUS (*LINK_c2dDestroySurface)( uint32 surface_id );
79
80C2D_STATUS (*LINK_c2dMapAddr) ( int mem_fd, void * hostptr, size_t len,
81                                size_t offset, uint32 flags, void ** gpuaddr);
82
83C2D_STATUS (*LINK_c2dUnMapAddr) ( void * gpuaddr);
84
85C2D_STATUS (*LINK_c2dGetDriverCapabilities) ( C2D_DRIVER_INFO * driver_info);
86
87/* create a fence fd for the timestamp */
88C2D_STATUS (*LINK_c2dCreateFenceFD) ( uint32 target_id, c2d_ts_handle timestamp,
89                                                            int32 *fd);
90
91C2D_STATUS (*LINK_c2dFillSurface) ( uint32 surface_id, uint32 fill_color,
92                                    C2D_RECT * fill_rect);
93
94/******************************************************************************/
95
96#if defined(COPYBIT_Z180)
97#define MAX_SCALE_FACTOR    (4096)
98#define MAX_DIMENSION       (4096)
99#else
100#error "Unsupported HW version"
101#endif
102
103// The following defines can be changed as required i.e. as we encounter
104// complex use cases.
105#define MAX_RGB_SURFACES 32       // Max. RGB layers currently supported per draw
106#define MAX_YUV_2_PLANE_SURFACES 4// Max. 2-plane YUV layers currently supported per draw
107#define MAX_YUV_3_PLANE_SURFACES 1// Max. 3-plane YUV layers currently supported per draw
108// +1 for the destination surface. We cannot have multiple destination surfaces.
109#define MAX_SURFACES (MAX_RGB_SURFACES + MAX_YUV_2_PLANE_SURFACES + MAX_YUV_3_PLANE_SURFACES + 1)
110#define NUM_SURFACE_TYPES 3      // RGB_SURFACE + YUV_SURFACE_2_PLANES + YUV_SURFACE_3_PLANES
111#define MAX_BLIT_OBJECT_COUNT 50 // Max. blit objects that can be passed per draw
112
113enum {
114    RGB_SURFACE,
115    YUV_SURFACE_2_PLANES,
116    YUV_SURFACE_3_PLANES
117};
118
119enum eConversionType {
120    CONVERT_TO_ANDROID_FORMAT,
121    CONVERT_TO_C2D_FORMAT
122};
123
124enum eC2DFlags {
125    FLAGS_PREMULTIPLIED_ALPHA  = 1<<0,
126    FLAGS_YUV_DESTINATION      = 1<<1,
127    FLAGS_TEMP_SRC_DST         = 1<<2
128};
129
130static gralloc::IAllocController* sAlloc = 0;
131/******************************************************************************/
132
133/** State information for each device instance */
134struct copybit_context_t {
135    struct copybit_device_t device;
136    // Templates for the various source surfaces. These templates are created
137    // to avoid the expensive create/destroy C2D Surfaces
138    C2D_OBJECT_STR blit_rgb_object[MAX_RGB_SURFACES];
139    C2D_OBJECT_STR blit_yuv_2_plane_object[MAX_YUV_2_PLANE_SURFACES];
140    C2D_OBJECT_STR blit_yuv_3_plane_object[MAX_YUV_3_PLANE_SURFACES];
141    C2D_OBJECT_STR blit_list[MAX_BLIT_OBJECT_COUNT]; // Z-ordered list of blit objects
142    C2D_DRIVER_INFO c2d_driver_info;
143    void *libc2d2;
144    alloc_data temp_src_buffer;
145    alloc_data temp_dst_buffer;
146    unsigned int dst[NUM_SURFACE_TYPES]; // dst surfaces
147    uintptr_t mapped_gpu_addr[MAX_SURFACES]; // GPU addresses mapped inside copybit
148    int blit_rgb_count;         // Total RGB surfaces being blit
149    int blit_yuv_2_plane_count; // Total 2 plane YUV surfaces being
150    int blit_yuv_3_plane_count; // Total 3 plane YUV  surfaces being blit
151    int blit_count;             // Total blit objects.
152    unsigned int trg_transform;      /* target transform */
153    int fb_width;
154    int fb_height;
155    int src_global_alpha;
156    int config_mask;
157    int dst_surface_type;
158    bool is_premultiplied_alpha;
159    void* time_stamp;
160    bool dst_surface_mapped; // Set when dst surface is mapped to GPU addr
161    void* dst_surface_base; // Stores the dst surface addr
162
163    // used for signaling the wait thread
164    bool wait_timestamp;
165    pthread_t wait_thread_id;
166    bool stop_thread;
167    pthread_mutex_t wait_cleanup_lock;
168    pthread_cond_t wait_cleanup_cond;
169
170};
171
172struct bufferInfo {
173    int width;
174    int height;
175    int format;
176};
177
178struct yuvPlaneInfo {
179    int yStride;       //luma stride
180    int plane1_stride;
181    int plane2_stride;
182    size_t plane1_offset;
183    size_t plane2_offset;
184};
185
186/**
187 * Common hardware methods
188 */
189
190static int open_copybit(const struct hw_module_t* module, const char* name,
191                        struct hw_device_t** device);
192
193static struct hw_module_methods_t copybit_module_methods = {
194    .open = open_copybit,
195};
196
197/*
198 * The COPYBIT Module
199 */
200struct copybit_module_t HAL_MODULE_INFO_SYM = {
201    .common = {
202        .tag =  HARDWARE_MODULE_TAG,
203        .version_major = 1,
204        .version_minor = 0,
205        .id = COPYBIT_HARDWARE_MODULE_ID,
206        .name = "QCT COPYBIT C2D 2.0 Module",
207        .author = "Qualcomm",
208        .methods =  &copybit_module_methods
209    }
210};
211
212
213/* thread function which waits on the timeStamp and cleans up the surfaces */
214static void* c2d_wait_loop(void* ptr) {
215    copybit_context_t* ctx = (copybit_context_t*)(ptr);
216    char thread_name[64] = "copybitWaitThr";
217    prctl(PR_SET_NAME, (unsigned long) &thread_name, 0, 0, 0);
218    setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
219
220    while(ctx->stop_thread == false) {
221        pthread_mutex_lock(&ctx->wait_cleanup_lock);
222        while(ctx->wait_timestamp == false && !ctx->stop_thread) {
223            pthread_cond_wait(&(ctx->wait_cleanup_cond),
224                              &(ctx->wait_cleanup_lock));
225        }
226        if(ctx->wait_timestamp) {
227            if(LINK_c2dWaitTimestamp(ctx->time_stamp)) {
228                ALOGE("%s: LINK_c2dWaitTimeStamp ERROR!!", __FUNCTION__);
229            }
230            ctx->wait_timestamp = false;
231            // Unmap any mapped addresses.
232            for (int i = 0; i < MAX_SURFACES; i++) {
233                if (ctx->mapped_gpu_addr[i]) {
234                    LINK_c2dUnMapAddr( (void*)ctx->mapped_gpu_addr[i]);
235                    ctx->mapped_gpu_addr[i] = 0;
236                }
237            }
238            // Reset the counts after the draw.
239            ctx->blit_rgb_count = 0;
240            ctx->blit_yuv_2_plane_count = 0;
241            ctx->blit_yuv_3_plane_count = 0;
242            ctx->blit_count = 0;
243            ctx->dst_surface_mapped = false;
244            ctx->dst_surface_base = 0;
245        }
246        pthread_mutex_unlock(&ctx->wait_cleanup_lock);
247        if(ctx->stop_thread)
248            break;
249    }
250    pthread_exit(NULL);
251    return NULL;
252}
253
254
255/* convert COPYBIT_FORMAT to C2D format */
256static int get_format(int format) {
257    switch (format) {
258        case HAL_PIXEL_FORMAT_RGB_565:        return C2D_COLOR_FORMAT_565_RGB;
259        case HAL_PIXEL_FORMAT_RGB_888:        return C2D_COLOR_FORMAT_888_RGB |
260                                              C2D_FORMAT_SWAP_RB;
261        case HAL_PIXEL_FORMAT_RGBX_8888:      return C2D_COLOR_FORMAT_8888_ARGB |
262                                              C2D_FORMAT_SWAP_RB |
263                                                  C2D_FORMAT_DISABLE_ALPHA;
264        case HAL_PIXEL_FORMAT_RGBA_8888:      return C2D_COLOR_FORMAT_8888_ARGB |
265                                              C2D_FORMAT_SWAP_RB;
266        case HAL_PIXEL_FORMAT_BGRA_8888:      return C2D_COLOR_FORMAT_8888_ARGB;
267        case HAL_PIXEL_FORMAT_YCbCr_420_SP:   return C2D_COLOR_FORMAT_420_NV12;
268        case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:return C2D_COLOR_FORMAT_420_NV12;
269        case HAL_PIXEL_FORMAT_YCrCb_420_SP:   return C2D_COLOR_FORMAT_420_NV21;
270        case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED: return C2D_COLOR_FORMAT_420_NV12 |
271                                                  C2D_FORMAT_MACROTILED;
272        default:                              ALOGE("%s: invalid format (0x%x",
273                                                     __FUNCTION__, format);
274                                              return -EINVAL;
275    }
276    return -EINVAL;
277}
278
279/* Get the C2D formats needed for conversion to YUV */
280static int get_c2d_format_for_yuv_destination(int halFormat) {
281    switch (halFormat) {
282        // We do not swap the RB when the target is YUV
283        case HAL_PIXEL_FORMAT_RGBX_8888:      return C2D_COLOR_FORMAT_8888_ARGB |
284                                              C2D_FORMAT_DISABLE_ALPHA;
285        case HAL_PIXEL_FORMAT_RGBA_8888:      return C2D_COLOR_FORMAT_8888_ARGB;
286        // The U and V need to be interchanged when the target is YUV
287        case HAL_PIXEL_FORMAT_YCbCr_420_SP:   return C2D_COLOR_FORMAT_420_NV21;
288        case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:return C2D_COLOR_FORMAT_420_NV21;
289        case HAL_PIXEL_FORMAT_YCrCb_420_SP:   return C2D_COLOR_FORMAT_420_NV12;
290        default:                              return get_format(halFormat);
291    }
292    return -EINVAL;
293}
294
295/* ------------------------------------------------------------------- *//*!
296 * \internal
297 * \brief Get the bpp for a particular color format
298 * \param color format
299 * \return bits per pixel
300 *//* ------------------------------------------------------------------- */
301int c2diGetBpp(int32 colorformat)
302{
303
304    int c2dBpp = 0;
305
306    switch(colorformat&0xFF)
307    {
308        case C2D_COLOR_FORMAT_4444_RGBA:
309        case C2D_COLOR_FORMAT_4444_ARGB:
310        case C2D_COLOR_FORMAT_1555_ARGB:
311        case C2D_COLOR_FORMAT_565_RGB:
312        case C2D_COLOR_FORMAT_5551_RGBA:
313            c2dBpp = 16;
314            break;
315        case C2D_COLOR_FORMAT_8888_RGBA:
316        case C2D_COLOR_FORMAT_8888_ARGB:
317            c2dBpp = 32;
318            break;
319        case C2D_COLOR_FORMAT_888_RGB:
320            c2dBpp = 24;
321            break;
322        case C2D_COLOR_FORMAT_8_L:
323        case C2D_COLOR_FORMAT_8_A:
324            c2dBpp = 8;
325            break;
326        case C2D_COLOR_FORMAT_4_A:
327            c2dBpp = 4;
328            break;
329        case C2D_COLOR_FORMAT_1:
330            c2dBpp = 1;
331            break;
332        default:
333            ALOGE("%s ERROR", __func__);
334            break;
335    }
336    return c2dBpp;
337}
338
339static size_t c2d_get_gpuaddr(copybit_context_t* ctx,
340                              struct private_handle_t *handle, int &mapped_idx)
341{
342    uint32 memtype;
343    size_t *gpuaddr = 0;
344    C2D_STATUS rc;
345    int freeindex = 0;
346    bool mapaddr = false;
347
348    if(!handle)
349        return 0;
350
351    if (handle->flags & (private_handle_t::PRIV_FLAGS_USES_PMEM |
352                         private_handle_t::PRIV_FLAGS_USES_PMEM_ADSP))
353        memtype = KGSL_USER_MEM_TYPE_PMEM;
354    else if (handle->flags & private_handle_t::PRIV_FLAGS_USES_ASHMEM)
355        memtype = KGSL_USER_MEM_TYPE_ASHMEM;
356    else if (handle->flags & private_handle_t::PRIV_FLAGS_USES_ION)
357        memtype = KGSL_USER_MEM_TYPE_ION;
358    else {
359        ALOGE("Invalid handle flags: 0x%x", handle->flags);
360        return 0;
361    }
362
363    // Check for a freeindex in the mapped_gpu_addr list
364    for (freeindex = 0; freeindex < MAX_SURFACES; freeindex++) {
365        if (ctx->mapped_gpu_addr[freeindex] == 0) {
366            // free index is available
367            // map GPU addr and use this as mapped_idx
368            mapaddr = true;
369            break;
370        }
371    }
372
373    if(mapaddr) {
374        rc = LINK_c2dMapAddr(handle->fd, (void*)handle->base, handle->size,
375                             handle->offset, memtype, (void**)&gpuaddr);
376
377        if (rc == C2D_STATUS_OK) {
378            // We have mapped the GPU address inside copybit. We need to unmap
379            // this address after the blit. Store this address
380            ctx->mapped_gpu_addr[freeindex] = (size_t)gpuaddr;
381            mapped_idx = freeindex;
382        }
383    }
384    return (size_t)gpuaddr;
385}
386
387static void unmap_gpuaddr(copybit_context_t* ctx, int mapped_idx)
388{
389    if (!ctx || (mapped_idx == -1))
390        return;
391
392    if (ctx->mapped_gpu_addr[mapped_idx]) {
393        LINK_c2dUnMapAddr( (void*)ctx->mapped_gpu_addr[mapped_idx]);
394        ctx->mapped_gpu_addr[mapped_idx] = 0;
395    }
396}
397
398static int is_supported_rgb_format(int format)
399{
400    switch(format) {
401        case HAL_PIXEL_FORMAT_RGBA_8888:
402        case HAL_PIXEL_FORMAT_RGBX_8888:
403        case HAL_PIXEL_FORMAT_RGB_888:
404        case HAL_PIXEL_FORMAT_RGB_565:
405        case HAL_PIXEL_FORMAT_BGRA_8888: {
406            return COPYBIT_SUCCESS;
407        }
408        default:
409            return COPYBIT_FAILURE;
410    }
411}
412
413static int get_num_planes(int format)
414{
415    switch(format) {
416        case HAL_PIXEL_FORMAT_YCbCr_420_SP:
417        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
418        case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
419        case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED: {
420            return 2;
421        }
422        case HAL_PIXEL_FORMAT_YV12: {
423            return 3;
424        }
425        default:
426            return COPYBIT_FAILURE;
427    }
428}
429
430static int is_supported_yuv_format(int format)
431{
432    switch(format) {
433        case HAL_PIXEL_FORMAT_YCbCr_420_SP:
434        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
435        case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
436        case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED: {
437            return COPYBIT_SUCCESS;
438        }
439        default:
440            return COPYBIT_FAILURE;
441    }
442}
443
444static int is_valid_destination_format(int format)
445{
446    if (format == HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED) {
447        // C2D does not support NV12Tile as a destination format.
448        return COPYBIT_FAILURE;
449    }
450    return COPYBIT_SUCCESS;
451}
452
453static int calculate_yuv_offset_and_stride(const bufferInfo& info,
454                                           yuvPlaneInfo& yuvInfo)
455{
456    int width  = info.width;
457    int height = info.height;
458    int format = info.format;
459
460    int aligned_height = 0;
461    int aligned_width = 0, size = 0;
462
463    switch (format) {
464        case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED: {
465            /* NV12 Tile buffers have their luma height aligned to 32bytes and width
466             * aligned to 128 bytes. The chroma offset starts at an 8K boundary
467             */
468            aligned_height = ALIGN(height, 32);
469            aligned_width  = ALIGN(width, 128);
470            size = aligned_width * aligned_height;
471            yuvInfo.plane1_offset = ALIGN(size,8192);
472            yuvInfo.yStride = aligned_width;
473            yuvInfo.plane1_stride = aligned_width;
474            break;
475        }
476        case HAL_PIXEL_FORMAT_YCbCr_420_SP:
477        case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
478        case HAL_PIXEL_FORMAT_YCrCb_420_SP: {
479            aligned_width = ALIGN(width, 32);
480            yuvInfo.yStride = aligned_width;
481            yuvInfo.plane1_stride = aligned_width;
482            if (HAL_PIXEL_FORMAT_NV12_ENCODEABLE == format) {
483                // The encoder requires a 2K aligned chroma offset
484                yuvInfo.plane1_offset = ALIGN(aligned_width * height, 2048);
485            } else
486                yuvInfo.plane1_offset = aligned_width * height;
487
488            break;
489        }
490        default: {
491            return COPYBIT_FAILURE;
492        }
493    }
494    return COPYBIT_SUCCESS;
495}
496
497/** create C2D surface from copybit image */
498static int set_image(copybit_context_t* ctx, uint32 surfaceId,
499                      const struct copybit_image_t *rhs,
500                      const eC2DFlags flags, int &mapped_idx)
501{
502    struct private_handle_t* handle = (struct private_handle_t*)rhs->handle;
503    C2D_SURFACE_TYPE surfaceType;
504    int status = COPYBIT_SUCCESS;
505    uint64_t gpuaddr = 0;
506    int c2d_format;
507    mapped_idx = -1;
508
509    if (flags & FLAGS_YUV_DESTINATION) {
510        c2d_format = get_c2d_format_for_yuv_destination(rhs->format);
511    } else {
512        c2d_format = get_format(rhs->format);
513    }
514
515    if(c2d_format == -EINVAL) {
516        ALOGE("%s: invalid format", __FUNCTION__);
517        return -EINVAL;
518    }
519
520    if(handle == NULL) {
521        ALOGE("%s: invalid handle", __func__);
522        return -EINVAL;
523    }
524
525    if (handle->gpuaddr == 0) {
526        gpuaddr = c2d_get_gpuaddr(ctx, handle, mapped_idx);
527        if(!gpuaddr) {
528            ALOGE("%s: c2d_get_gpuaddr failed", __FUNCTION__);
529            return COPYBIT_FAILURE;
530        }
531    } else {
532        gpuaddr = handle->gpuaddr;
533    }
534
535    /* create C2D surface */
536    if(is_supported_rgb_format(rhs->format) == COPYBIT_SUCCESS) {
537        /* RGB */
538        C2D_RGB_SURFACE_DEF surfaceDef;
539
540        surfaceType = (C2D_SURFACE_TYPE) (C2D_SURFACE_RGB_HOST | C2D_SURFACE_WITH_PHYS);
541
542        surfaceDef.phys = (void*) gpuaddr;
543        surfaceDef.buffer = (void*) (handle->base);
544
545        surfaceDef.format = c2d_format |
546            ((flags & FLAGS_PREMULTIPLIED_ALPHA) ? C2D_FORMAT_PREMULTIPLIED : 0);
547        surfaceDef.width = rhs->w;
548        surfaceDef.height = rhs->h;
549        int aligned_width = ALIGN((int)surfaceDef.width,32);
550        surfaceDef.stride = (aligned_width * c2diGetBpp(surfaceDef.format))>>3;
551
552        if(LINK_c2dUpdateSurface( surfaceId,C2D_TARGET | C2D_SOURCE, surfaceType,
553                                  &surfaceDef)) {
554            ALOGE("%s: RGB Surface c2dUpdateSurface ERROR", __FUNCTION__);
555            unmap_gpuaddr(ctx, mapped_idx);
556            status = COPYBIT_FAILURE;
557        }
558    } else if (is_supported_yuv_format(rhs->format) == COPYBIT_SUCCESS) {
559        C2D_YUV_SURFACE_DEF surfaceDef;
560        memset(&surfaceDef, 0, sizeof(surfaceDef));
561        surfaceType = (C2D_SURFACE_TYPE)(C2D_SURFACE_YUV_HOST | C2D_SURFACE_WITH_PHYS);
562        surfaceDef.format = c2d_format;
563
564        bufferInfo info;
565        info.width = rhs->w;
566        info.height = rhs->h;
567        info.format = rhs->format;
568
569        yuvPlaneInfo yuvInfo = {0};
570        status = calculate_yuv_offset_and_stride(info, yuvInfo);
571        if(status != COPYBIT_SUCCESS) {
572            ALOGE("%s: calculate_yuv_offset_and_stride error", __FUNCTION__);
573            unmap_gpuaddr(ctx, mapped_idx);
574        }
575
576        surfaceDef.width = rhs->w;
577        surfaceDef.height = rhs->h;
578        surfaceDef.plane0 = (void*) (handle->base);
579        surfaceDef.phys0 = (void*) (gpuaddr);
580        surfaceDef.stride0 = yuvInfo.yStride;
581
582        surfaceDef.plane1 = (void*) (handle->base + yuvInfo.plane1_offset);
583        surfaceDef.phys1 = (void*) (gpuaddr + yuvInfo.plane1_offset);
584        surfaceDef.stride1 = yuvInfo.plane1_stride;
585        if (3 == get_num_planes(rhs->format)) {
586            surfaceDef.plane2 = (void*) (handle->base + yuvInfo.plane2_offset);
587            surfaceDef.phys2 = (void*) (gpuaddr + yuvInfo.plane2_offset);
588            surfaceDef.stride2 = yuvInfo.plane2_stride;
589        }
590
591        if(LINK_c2dUpdateSurface( surfaceId,C2D_TARGET | C2D_SOURCE, surfaceType,
592                                  &surfaceDef)) {
593            ALOGE("%s: YUV Surface c2dUpdateSurface ERROR", __FUNCTION__);
594            unmap_gpuaddr(ctx, mapped_idx);
595            status = COPYBIT_FAILURE;
596        }
597    } else {
598        ALOGE("%s: invalid format 0x%x", __FUNCTION__, rhs->format);
599        unmap_gpuaddr(ctx, mapped_idx);
600        status = COPYBIT_FAILURE;
601    }
602
603    return status;
604}
605
606/** copy the bits */
607static int msm_copybit(struct copybit_context_t *ctx, unsigned int target)
608{
609    if (ctx->blit_count == 0) {
610        return COPYBIT_SUCCESS;
611    }
612
613    for (int i = 0; i < ctx->blit_count; i++)
614    {
615        ctx->blit_list[i].next = &(ctx->blit_list[i+1]);
616    }
617    ctx->blit_list[ctx->blit_count-1].next = NULL;
618    uint32_t target_transform = ctx->trg_transform;
619    if (ctx->c2d_driver_info.capabilities_mask &
620        C2D_DRIVER_SUPPORTS_OVERRIDE_TARGET_ROTATE_OP) {
621        // For A3xx - set 0x0 as the transform is set in the config_mask
622        target_transform = 0x0;
623    }
624    if(LINK_c2dDraw(target, target_transform, 0x0, 0, 0, ctx->blit_list,
625                    ctx->blit_count)) {
626        ALOGE("%s: LINK_c2dDraw ERROR", __FUNCTION__);
627        return COPYBIT_FAILURE;
628    }
629    return COPYBIT_SUCCESS;
630}
631
632
633
634static int flush_get_fence_copybit (struct copybit_device_t *dev, int* fd)
635{
636    struct copybit_context_t* ctx = (struct copybit_context_t*)dev;
637    int status = COPYBIT_FAILURE;
638    if (!ctx)
639        return COPYBIT_FAILURE;
640    pthread_mutex_lock(&ctx->wait_cleanup_lock);
641    status = msm_copybit(ctx, ctx->dst[ctx->dst_surface_type]);
642
643    if(LINK_c2dFlush(ctx->dst[ctx->dst_surface_type], &ctx->time_stamp)) {
644        ALOGE("%s: LINK_c2dFlush ERROR", __FUNCTION__);
645        // unlock the mutex and return failure
646        pthread_mutex_unlock(&ctx->wait_cleanup_lock);
647        return COPYBIT_FAILURE;
648    }
649    if(LINK_c2dCreateFenceFD(ctx->dst[ctx->dst_surface_type], ctx->time_stamp,
650                                                                        fd)) {
651        ALOGE("%s: LINK_c2dCreateFenceFD ERROR", __FUNCTION__);
652        status = COPYBIT_FAILURE;
653    }
654    if(status == COPYBIT_SUCCESS) {
655        //signal the wait_thread
656        ctx->wait_timestamp = true;
657        pthread_cond_signal(&ctx->wait_cleanup_cond);
658    }
659    pthread_mutex_unlock(&ctx->wait_cleanup_lock);
660    return status;
661}
662
663static int finish_copybit(struct copybit_device_t *dev)
664{
665    struct copybit_context_t* ctx = (struct copybit_context_t*)dev;
666    if (!ctx)
667        return COPYBIT_FAILURE;
668
669   int status = msm_copybit(ctx, ctx->dst[ctx->dst_surface_type]);
670
671   if(LINK_c2dFinish(ctx->dst[ctx->dst_surface_type])) {
672        ALOGE("%s: LINK_c2dFinish ERROR", __FUNCTION__);
673        return COPYBIT_FAILURE;
674    }
675
676    // Unmap any mapped addresses.
677    for (int i = 0; i < MAX_SURFACES; i++) {
678        if (ctx->mapped_gpu_addr[i]) {
679            LINK_c2dUnMapAddr( (void*)ctx->mapped_gpu_addr[i]);
680            ctx->mapped_gpu_addr[i] = 0;
681        }
682    }
683
684    // Reset the counts after the draw.
685    ctx->blit_rgb_count = 0;
686    ctx->blit_yuv_2_plane_count = 0;
687    ctx->blit_yuv_3_plane_count = 0;
688    ctx->blit_count = 0;
689    ctx->dst_surface_mapped = false;
690    ctx->dst_surface_base = 0;
691
692    return status;
693}
694
695static int clear_copybit(struct copybit_device_t *dev,
696                         struct copybit_image_t const *buf,
697                         struct copybit_rect_t *rect)
698{
699    int ret = COPYBIT_SUCCESS;
700    int flags = FLAGS_PREMULTIPLIED_ALPHA;
701    int mapped_dst_idx = -1;
702    struct copybit_context_t* ctx = (struct copybit_context_t*)dev;
703    C2D_RECT c2drect = {rect->l, rect->t, rect->r - rect->l, rect->b - rect->t};
704    pthread_mutex_lock(&ctx->wait_cleanup_lock);
705    if(!ctx->dst_surface_mapped) {
706        ret = set_image(ctx, ctx->dst[RGB_SURFACE], buf,
707                        (eC2DFlags)flags, mapped_dst_idx);
708        if(ret) {
709            ALOGE("%s: set_image error", __FUNCTION__);
710            unmap_gpuaddr(ctx, mapped_dst_idx);
711            pthread_mutex_unlock(&ctx->wait_cleanup_lock);
712            return COPYBIT_FAILURE;
713        }
714        //clear_copybit is the first call made by HWC for each composition
715        //with the dest surface, hence set dst_surface_mapped.
716        ctx->dst_surface_mapped = true;
717        ctx->dst_surface_base = buf->base;
718        ret = LINK_c2dFillSurface(ctx->dst[RGB_SURFACE], 0x0, &c2drect);
719    }
720    pthread_mutex_unlock(&ctx->wait_cleanup_lock);
721    return ret;
722}
723
724
725/** setup rectangles */
726static void set_rects(struct copybit_context_t *ctx,
727                      C2D_OBJECT *c2dObject,
728                      const struct copybit_rect_t *dst,
729                      const struct copybit_rect_t *src,
730                      const struct copybit_rect_t *scissor)
731{
732    // Set the target rect.
733    if((ctx->trg_transform & C2D_TARGET_ROTATE_90) &&
734       (ctx->trg_transform & C2D_TARGET_ROTATE_180)) {
735        /* target rotation is 270 */
736        c2dObject->target_rect.x        = (dst->t)<<16;
737        c2dObject->target_rect.y        = ctx->fb_width?
738                (ALIGN(ctx->fb_width,32)- dst->r):dst->r;
739        c2dObject->target_rect.y        = c2dObject->target_rect.y<<16;
740        c2dObject->target_rect.height   = ((dst->r) - (dst->l))<<16;
741        c2dObject->target_rect.width    = ((dst->b) - (dst->t))<<16;
742    } else if(ctx->trg_transform & C2D_TARGET_ROTATE_90) {
743        c2dObject->target_rect.x        = ctx->fb_height?(ctx->fb_height - dst->b):dst->b;
744        c2dObject->target_rect.x        = c2dObject->target_rect.x<<16;
745        c2dObject->target_rect.y        = (dst->l)<<16;
746        c2dObject->target_rect.height   = ((dst->r) - (dst->l))<<16;
747        c2dObject->target_rect.width    = ((dst->b) - (dst->t))<<16;
748    } else if(ctx->trg_transform & C2D_TARGET_ROTATE_180) {
749        c2dObject->target_rect.y        = ctx->fb_height?(ctx->fb_height - dst->b):dst->b;
750        c2dObject->target_rect.y        = c2dObject->target_rect.y<<16;
751        c2dObject->target_rect.x        = ctx->fb_width?
752                (ALIGN(ctx->fb_width,32) - dst->r):dst->r;
753        c2dObject->target_rect.x        = c2dObject->target_rect.x<<16;
754        c2dObject->target_rect.height   = ((dst->b) - (dst->t))<<16;
755        c2dObject->target_rect.width    = ((dst->r) - (dst->l))<<16;
756    } else {
757        c2dObject->target_rect.x        = (dst->l)<<16;
758        c2dObject->target_rect.y        = (dst->t)<<16;
759        c2dObject->target_rect.height   = ((dst->b) - (dst->t))<<16;
760        c2dObject->target_rect.width    = ((dst->r) - (dst->l))<<16;
761    }
762    c2dObject->config_mask |= C2D_TARGET_RECT_BIT;
763
764    // Set the source rect
765    c2dObject->source_rect.x        = (src->l)<<16;
766    c2dObject->source_rect.y        = (src->t)<<16;
767    c2dObject->source_rect.height   = ((src->b) - (src->t))<<16;
768    c2dObject->source_rect.width    = ((src->r) - (src->l))<<16;
769    c2dObject->config_mask |= C2D_SOURCE_RECT_BIT;
770
771    // Set the scissor rect
772    c2dObject->scissor_rect.x       = scissor->l;
773    c2dObject->scissor_rect.y       = scissor->t;
774    c2dObject->scissor_rect.height  = (scissor->b) - (scissor->t);
775    c2dObject->scissor_rect.width   = (scissor->r) - (scissor->l);
776    c2dObject->config_mask |= C2D_SCISSOR_RECT_BIT;
777}
778
779/*****************************************************************************/
780
781/** Set a parameter to value */
782static int set_parameter_copybit(
783    struct copybit_device_t *dev,
784    int name,
785    int value)
786{
787    struct copybit_context_t* ctx = (struct copybit_context_t*)dev;
788    int status = COPYBIT_SUCCESS;
789    if (!ctx) {
790        ALOGE("%s: null context", __FUNCTION__);
791        return -EINVAL;
792    }
793
794    pthread_mutex_lock(&ctx->wait_cleanup_lock);
795    switch(name) {
796        case COPYBIT_PLANE_ALPHA:
797        {
798            if (value < 0)      value = 0;
799            if (value >= 256)   value = 255;
800
801            ctx->src_global_alpha = value;
802            if (value < 255)
803                ctx->config_mask |= C2D_GLOBAL_ALPHA_BIT;
804            else
805                ctx->config_mask &= ~C2D_GLOBAL_ALPHA_BIT;
806        }
807        break;
808        case COPYBIT_BLEND_MODE:
809        {
810            if (value == COPYBIT_BLENDING_NONE) {
811                ctx->config_mask |= C2D_ALPHA_BLEND_NONE;
812                ctx->is_premultiplied_alpha = true;
813            } else if (value == COPYBIT_BLENDING_PREMULT) {
814                ctx->is_premultiplied_alpha = true;
815            } else {
816                ctx->config_mask &= ~C2D_ALPHA_BLEND_NONE;
817            }
818        }
819        break;
820        case COPYBIT_TRANSFORM:
821        {
822            unsigned int transform = 0;
823            uint32 config_mask = 0;
824            config_mask |= C2D_OVERRIDE_GLOBAL_TARGET_ROTATE_CONFIG;
825            if((value & 0x7) == COPYBIT_TRANSFORM_ROT_180) {
826                transform = C2D_TARGET_ROTATE_180;
827                config_mask |= C2D_OVERRIDE_TARGET_ROTATE_180;
828            } else if((value & 0x7) == COPYBIT_TRANSFORM_ROT_270) {
829                transform = C2D_TARGET_ROTATE_90;
830                config_mask |= C2D_OVERRIDE_TARGET_ROTATE_90;
831            } else if(value == COPYBIT_TRANSFORM_ROT_90) {
832                transform = C2D_TARGET_ROTATE_270;
833                config_mask |= C2D_OVERRIDE_TARGET_ROTATE_270;
834            } else {
835                config_mask |= C2D_OVERRIDE_TARGET_ROTATE_0;
836                if(value & COPYBIT_TRANSFORM_FLIP_H) {
837                    config_mask |= C2D_MIRROR_H_BIT;
838                } else if(value & COPYBIT_TRANSFORM_FLIP_V) {
839                    config_mask |= C2D_MIRROR_V_BIT;
840                }
841            }
842
843            if (ctx->c2d_driver_info.capabilities_mask &
844                C2D_DRIVER_SUPPORTS_OVERRIDE_TARGET_ROTATE_OP) {
845                ctx->config_mask |= config_mask;
846            } else {
847                // The transform for this surface does not match the current
848                // target transform. Draw all previous surfaces. This will be
849                // changed once we have a new mechanism to send different
850                // target rotations to c2d.
851                finish_copybit(dev);
852            }
853            ctx->trg_transform = transform;
854        }
855        break;
856        case COPYBIT_FRAMEBUFFER_WIDTH:
857            ctx->fb_width = value;
858            break;
859        case COPYBIT_FRAMEBUFFER_HEIGHT:
860            ctx->fb_height = value;
861            break;
862        case COPYBIT_ROTATION_DEG:
863        case COPYBIT_DITHER:
864        case COPYBIT_BLUR:
865        case COPYBIT_BLIT_TO_FRAMEBUFFER:
866            // Do nothing
867            break;
868        default:
869            ALOGE("%s: default case param=0x%x", __FUNCTION__, name);
870            status = -EINVAL;
871            break;
872    }
873    pthread_mutex_unlock(&ctx->wait_cleanup_lock);
874    return status;
875}
876
877/** Get a static info value */
878static int get(struct copybit_device_t *dev, int name)
879{
880    struct copybit_context_t* ctx = (struct copybit_context_t*)dev;
881    int value;
882
883    if (!ctx) {
884        ALOGE("%s: null context error", __FUNCTION__);
885        return -EINVAL;
886    }
887
888    switch(name) {
889        case COPYBIT_MINIFICATION_LIMIT:
890            value = MAX_SCALE_FACTOR;
891            break;
892        case COPYBIT_MAGNIFICATION_LIMIT:
893            value = MAX_SCALE_FACTOR;
894            break;
895        case COPYBIT_SCALING_FRAC_BITS:
896            value = 32;
897            break;
898        case COPYBIT_ROTATION_STEP_DEG:
899            value = 1;
900            break;
901        default:
902            ALOGE("%s: default case param=0x%x", __FUNCTION__, name);
903            value = -EINVAL;
904    }
905    return value;
906}
907
908/* Function to check if we need a temporary buffer for the blit.
909 * This would happen if the requested destination stride and the
910 * C2D stride do not match. We ignore RGB buffers, since their
911 * stride is always aligned to 32.
912 */
913static bool need_temp_buffer(struct copybit_image_t const *img)
914{
915    if (COPYBIT_SUCCESS == is_supported_rgb_format(img->format))
916        return false;
917
918    struct private_handle_t* handle = (struct private_handle_t*)img->handle;
919
920    // The width parameter in the handle contains the aligned_w. We check if we
921    // need to convert based on this param. YUV formats have bpp=1, so checking
922    // if the requested stride is aligned should suffice.
923    if (0 == (handle->width)%32) {
924        return false;
925    }
926
927    return true;
928}
929
930/* Function to extract the information from the copybit image and set the corresponding
931 * values in the bufferInfo struct.
932 */
933static void populate_buffer_info(struct copybit_image_t const *img, bufferInfo& info)
934{
935    info.width = img->w;
936    info.height = img->h;
937    info.format = img->format;
938}
939
940/* Function to get the required size for a particular format, inorder for C2D to perform
941 * the blit operation.
942 */
943static int get_size(const bufferInfo& info)
944{
945    int size = 0;
946    int w = info.width;
947    int h = info.height;
948    int aligned_w = ALIGN(w, 32);
949    switch(info.format) {
950        case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
951            {
952                // Chroma for this format is aligned to 2K.
953                size = ALIGN((aligned_w*h), 2048) +
954                        ALIGN(aligned_w/2, 32) * (h/2) *2;
955                size = ALIGN(size, 4096);
956            } break;
957        case HAL_PIXEL_FORMAT_YCbCr_420_SP:
958        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
959            {
960                size = aligned_w * h +
961                       ALIGN(aligned_w/2, 32) * (h/2) * 2;
962                size = ALIGN(size, 4096);
963            } break;
964        default: break;
965    }
966    return size;
967}
968
969/* Function to allocate memory for the temporary buffer. This memory is
970 * allocated from Ashmem. It is the caller's responsibility to free this
971 * memory.
972 */
973static int get_temp_buffer(const bufferInfo& info, alloc_data& data)
974{
975    ALOGD("%s E", __FUNCTION__);
976    // Alloc memory from system heap
977    data.base = 0;
978    data.fd = -1;
979    data.offset = 0;
980    data.size = get_size(info);
981    data.align = getpagesize();
982    data.uncached = true;
983    int allocFlags = GRALLOC_USAGE_PRIVATE_SYSTEM_HEAP;
984
985    if (sAlloc == 0) {
986        sAlloc = gralloc::IAllocController::getInstance();
987    }
988
989    if (sAlloc == 0) {
990        ALOGE("%s: sAlloc is still NULL", __FUNCTION__);
991        return COPYBIT_FAILURE;
992    }
993
994    int err = sAlloc->allocate(data, allocFlags);
995    if (0 != err) {
996        ALOGE("%s: allocate failed", __FUNCTION__);
997        return COPYBIT_FAILURE;
998    }
999
1000    ALOGD("%s X", __FUNCTION__);
1001    return err;
1002}
1003
1004/* Function to free the temporary allocated memory.*/
1005static void free_temp_buffer(alloc_data &data)
1006{
1007    if (-1 != data.fd) {
1008        IMemAlloc* memalloc = sAlloc->getAllocator(data.allocType);
1009        memalloc->free_buffer(data.base, data.size, 0, data.fd);
1010    }
1011}
1012
1013/* Function to perform the software color conversion. Convert the
1014 * C2D compatible format to the Android compatible format
1015 */
1016static int copy_image(private_handle_t *src_handle,
1017                      struct copybit_image_t const *rhs,
1018                      eConversionType conversionType)
1019{
1020    if (src_handle->fd == -1) {
1021        ALOGE("%s: src_handle fd is invalid", __FUNCTION__);
1022        return COPYBIT_FAILURE;
1023    }
1024
1025    // Copy the info.
1026    int ret = COPYBIT_SUCCESS;
1027    switch(rhs->format) {
1028        case HAL_PIXEL_FORMAT_NV12_ENCODEABLE:
1029        case HAL_PIXEL_FORMAT_YCbCr_420_SP:
1030        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
1031            {
1032                if (CONVERT_TO_ANDROID_FORMAT == conversionType) {
1033                    return convert_yuv_c2d_to_yuv_android(src_handle, rhs);
1034                } else {
1035                    return convert_yuv_android_to_yuv_c2d(src_handle, rhs);
1036                }
1037
1038            } break;
1039        default: {
1040            ALOGE("%s: invalid format 0x%x", __FUNCTION__, rhs->format);
1041            ret = COPYBIT_FAILURE;
1042        } break;
1043    }
1044    return ret;
1045}
1046
1047static void delete_handle(private_handle_t *handle)
1048{
1049    if (handle) {
1050        delete handle;
1051        handle = 0;
1052    }
1053}
1054
1055static bool need_to_execute_draw(eC2DFlags flags)
1056{
1057    if (flags & FLAGS_TEMP_SRC_DST) {
1058        return true;
1059    }
1060    if (flags & FLAGS_YUV_DESTINATION) {
1061        return true;
1062    }
1063    return false;
1064}
1065
1066/** do a stretch blit type operation */
1067static int stretch_copybit_internal(
1068    struct copybit_device_t *dev,
1069    struct copybit_image_t const *dst,
1070    struct copybit_image_t const *src,
1071    struct copybit_rect_t const *dst_rect,
1072    struct copybit_rect_t const *src_rect,
1073    struct copybit_region_t const *region,
1074    bool enableBlend)
1075{
1076    struct copybit_context_t* ctx = (struct copybit_context_t*)dev;
1077    int status = COPYBIT_SUCCESS;
1078    int flags = 0;
1079    int src_surface_type;
1080    int mapped_src_idx = -1, mapped_dst_idx = -1;
1081    C2D_OBJECT_STR src_surface;
1082
1083    if (!ctx) {
1084        ALOGE("%s: null context error", __FUNCTION__);
1085        return -EINVAL;
1086    }
1087
1088    if (src->w > MAX_DIMENSION || src->h > MAX_DIMENSION) {
1089        ALOGE("%s: src dimension error", __FUNCTION__);
1090        return -EINVAL;
1091    }
1092
1093    if (dst->w > MAX_DIMENSION || dst->h > MAX_DIMENSION) {
1094        ALOGE("%s : dst dimension error dst w %d h %d",  __FUNCTION__, dst->w,
1095                                                         dst->h);
1096        return -EINVAL;
1097    }
1098
1099    if (is_valid_destination_format(dst->format) == COPYBIT_FAILURE) {
1100        ALOGE("%s: Invalid destination format format = 0x%x", __FUNCTION__,
1101                                                              dst->format);
1102        return COPYBIT_FAILURE;
1103    }
1104
1105    int dst_surface_type;
1106    if (is_supported_rgb_format(dst->format) == COPYBIT_SUCCESS) {
1107        dst_surface_type = RGB_SURFACE;
1108        flags |= FLAGS_PREMULTIPLIED_ALPHA;
1109    } else if (is_supported_yuv_format(dst->format) == COPYBIT_SUCCESS) {
1110        int num_planes = get_num_planes(dst->format);
1111        flags |= FLAGS_YUV_DESTINATION;
1112        if (num_planes == 2) {
1113            dst_surface_type = YUV_SURFACE_2_PLANES;
1114        } else if (num_planes == 3) {
1115            dst_surface_type = YUV_SURFACE_3_PLANES;
1116        } else {
1117            ALOGE("%s: dst number of YUV planes is invalid dst format = 0x%x",
1118                  __FUNCTION__, dst->format);
1119            return COPYBIT_FAILURE;
1120        }
1121    } else {
1122        ALOGE("%s: Invalid dst surface format 0x%x", __FUNCTION__,
1123                                                     dst->format);
1124        return COPYBIT_FAILURE;
1125    }
1126
1127    if (ctx->blit_rgb_count == MAX_RGB_SURFACES ||
1128        ctx->blit_yuv_2_plane_count == MAX_YUV_2_PLANE_SURFACES ||
1129        ctx->blit_yuv_3_plane_count == MAX_YUV_2_PLANE_SURFACES ||
1130        ctx->blit_count == MAX_BLIT_OBJECT_COUNT ||
1131        ctx->dst_surface_type != dst_surface_type) {
1132        // we have reached the max. limits of our internal structures or
1133        // changed the target.
1134        // Draw the remaining surfaces. We need to do the finish here since
1135        // we need to free up the surface templates.
1136        finish_copybit(dev);
1137    }
1138
1139    ctx->dst_surface_type = dst_surface_type;
1140
1141    // Update the destination
1142    copybit_image_t dst_image;
1143    dst_image.w = dst->w;
1144    dst_image.h = dst->h;
1145    dst_image.format = dst->format;
1146    dst_image.handle = dst->handle;
1147    // Check if we need a temp. copy for the destination. We'd need this the destination
1148    // width is not aligned to 32. This case occurs for YUV formats. RGB formats are
1149    // aligned to 32.
1150    bool need_temp_dst = need_temp_buffer(dst);
1151    bufferInfo dst_info;
1152    populate_buffer_info(dst, dst_info);
1153    private_handle_t* dst_hnd = new private_handle_t(-1, 0, 0, 0, dst_info.format,
1154                                                     dst_info.width, dst_info.height);
1155    if (dst_hnd == NULL) {
1156        ALOGE("%s: dst_hnd is null", __FUNCTION__);
1157        return COPYBIT_FAILURE;
1158    }
1159    if (need_temp_dst) {
1160        if (get_size(dst_info) != (int) ctx->temp_dst_buffer.size) {
1161            free_temp_buffer(ctx->temp_dst_buffer);
1162            // Create a temp buffer and set that as the destination.
1163            if (COPYBIT_FAILURE == get_temp_buffer(dst_info, ctx->temp_dst_buffer)) {
1164                ALOGE("%s: get_temp_buffer(dst) failed", __FUNCTION__);
1165                delete_handle(dst_hnd);
1166                return COPYBIT_FAILURE;
1167            }
1168        }
1169        dst_hnd->fd = ctx->temp_dst_buffer.fd;
1170        dst_hnd->size = ctx->temp_dst_buffer.size;
1171        dst_hnd->flags = ctx->temp_dst_buffer.allocType;
1172        dst_hnd->base = (uintptr_t)(ctx->temp_dst_buffer.base);
1173        dst_hnd->offset = ctx->temp_dst_buffer.offset;
1174        dst_hnd->gpuaddr = 0;
1175        dst_image.handle = dst_hnd;
1176    }
1177    if(!ctx->dst_surface_mapped) {
1178        //map the destination surface to GPU address
1179        status = set_image(ctx, ctx->dst[ctx->dst_surface_type], &dst_image,
1180                           (eC2DFlags)flags, mapped_dst_idx);
1181        if(status) {
1182            ALOGE("%s: dst: set_image error", __FUNCTION__);
1183            delete_handle(dst_hnd);
1184            unmap_gpuaddr(ctx, mapped_dst_idx);
1185            return COPYBIT_FAILURE;
1186        }
1187        ctx->dst_surface_mapped = true;
1188        ctx->dst_surface_base = dst->base;
1189    } else if(ctx->dst_surface_mapped && ctx->dst_surface_base != dst->base) {
1190        // Destination surface for the operation should be same for multiple
1191        // requests, this check is catch if there is any case when the
1192        // destination changes
1193        ALOGE("%s: a different destination surface!!", __FUNCTION__);
1194    }
1195
1196    // Update the source
1197    flags = 0;
1198    if(is_supported_rgb_format(src->format) == COPYBIT_SUCCESS) {
1199        src_surface_type = RGB_SURFACE;
1200        src_surface = ctx->blit_rgb_object[ctx->blit_rgb_count];
1201    } else if (is_supported_yuv_format(src->format) == COPYBIT_SUCCESS) {
1202        int num_planes = get_num_planes(src->format);
1203        if (num_planes == 2) {
1204            src_surface_type = YUV_SURFACE_2_PLANES;
1205            src_surface = ctx->blit_yuv_2_plane_object[ctx->blit_yuv_2_plane_count];
1206        } else if (num_planes == 3) {
1207            src_surface_type = YUV_SURFACE_3_PLANES;
1208            src_surface = ctx->blit_yuv_3_plane_object[ctx->blit_yuv_2_plane_count];
1209        } else {
1210            ALOGE("%s: src number of YUV planes is invalid src format = 0x%x",
1211                  __FUNCTION__, src->format);
1212            delete_handle(dst_hnd);
1213            unmap_gpuaddr(ctx, mapped_dst_idx);
1214            return -EINVAL;
1215        }
1216    } else {
1217        ALOGE("%s: Invalid source surface format 0x%x", __FUNCTION__,
1218                                                        src->format);
1219        delete_handle(dst_hnd);
1220        unmap_gpuaddr(ctx, mapped_dst_idx);
1221        return -EINVAL;
1222    }
1223
1224    copybit_image_t src_image;
1225    src_image.w = src->w;
1226    src_image.h = src->h;
1227    src_image.format = src->format;
1228    src_image.handle = src->handle;
1229
1230    bool need_temp_src = need_temp_buffer(src);
1231    bufferInfo src_info;
1232    populate_buffer_info(src, src_info);
1233    private_handle_t* src_hnd = new private_handle_t(-1, 0, 0, 0, src_info.format,
1234                                                 src_info.width, src_info.height);
1235    if (NULL == src_hnd) {
1236        ALOGE("%s: src_hnd is null", __FUNCTION__);
1237        delete_handle(dst_hnd);
1238        unmap_gpuaddr(ctx, mapped_dst_idx);
1239        return COPYBIT_FAILURE;
1240    }
1241    if (need_temp_src) {
1242        if (get_size(src_info) != (int) ctx->temp_src_buffer.size) {
1243            free_temp_buffer(ctx->temp_src_buffer);
1244            // Create a temp buffer and set that as the destination.
1245            if (COPYBIT_SUCCESS != get_temp_buffer(src_info,
1246                                               ctx->temp_src_buffer)) {
1247                ALOGE("%s: get_temp_buffer(src) failed", __FUNCTION__);
1248                delete_handle(dst_hnd);
1249                delete_handle(src_hnd);
1250                unmap_gpuaddr(ctx, mapped_dst_idx);
1251                return COPYBIT_FAILURE;
1252            }
1253        }
1254        src_hnd->fd = ctx->temp_src_buffer.fd;
1255        src_hnd->size = ctx->temp_src_buffer.size;
1256        src_hnd->flags = ctx->temp_src_buffer.allocType;
1257        src_hnd->base = (uintptr_t)(ctx->temp_src_buffer.base);
1258        src_hnd->offset = ctx->temp_src_buffer.offset;
1259        src_hnd->gpuaddr = 0;
1260        src_image.handle = src_hnd;
1261
1262        // Copy the source.
1263        status = copy_image((private_handle_t *)src->handle, &src_image,
1264                                CONVERT_TO_C2D_FORMAT);
1265        if (status == COPYBIT_FAILURE) {
1266            ALOGE("%s:copy_image failed in temp source",__FUNCTION__);
1267            delete_handle(dst_hnd);
1268            delete_handle(src_hnd);
1269            unmap_gpuaddr(ctx, mapped_dst_idx);
1270            return status;
1271        }
1272
1273        // Clean the cache
1274        IMemAlloc* memalloc = sAlloc->getAllocator(src_hnd->flags);
1275        if (memalloc->clean_buffer((void *)(src_hnd->base), src_hnd->size,
1276                                   src_hnd->offset, src_hnd->fd,
1277                                   gralloc::CACHE_CLEAN)) {
1278            ALOGE("%s: clean_buffer failed", __FUNCTION__);
1279            delete_handle(dst_hnd);
1280            delete_handle(src_hnd);
1281            unmap_gpuaddr(ctx, mapped_dst_idx);
1282            return COPYBIT_FAILURE;
1283        }
1284    }
1285
1286    flags |= (ctx->is_premultiplied_alpha) ? FLAGS_PREMULTIPLIED_ALPHA : 0;
1287    flags |= (ctx->dst_surface_type != RGB_SURFACE) ? FLAGS_YUV_DESTINATION : 0;
1288    status = set_image(ctx, src_surface.surface_id, &src_image,
1289                       (eC2DFlags)flags, mapped_src_idx);
1290    if(status) {
1291        ALOGE("%s: set_image (src) error", __FUNCTION__);
1292        delete_handle(dst_hnd);
1293        delete_handle(src_hnd);
1294        unmap_gpuaddr(ctx, mapped_dst_idx);
1295        unmap_gpuaddr(ctx, mapped_src_idx);
1296        return COPYBIT_FAILURE;
1297    }
1298
1299    src_surface.config_mask = C2D_NO_ANTIALIASING_BIT | ctx->config_mask;
1300    src_surface.global_alpha = ctx->src_global_alpha;
1301    if (enableBlend) {
1302        if(src_surface.config_mask & C2D_GLOBAL_ALPHA_BIT) {
1303            src_surface.config_mask &= ~C2D_ALPHA_BLEND_NONE;
1304            if(!(src_surface.global_alpha)) {
1305                // src alpha is zero
1306                delete_handle(dst_hnd);
1307                delete_handle(src_hnd);
1308                unmap_gpuaddr(ctx, mapped_dst_idx);
1309                unmap_gpuaddr(ctx, mapped_src_idx);
1310                return COPYBIT_FAILURE;
1311            }
1312        }
1313    } else {
1314        src_surface.config_mask |= C2D_ALPHA_BLEND_NONE;
1315    }
1316
1317    if (src_surface_type == RGB_SURFACE) {
1318        ctx->blit_rgb_object[ctx->blit_rgb_count] = src_surface;
1319        ctx->blit_rgb_count++;
1320    } else if (src_surface_type == YUV_SURFACE_2_PLANES) {
1321        ctx->blit_yuv_2_plane_object[ctx->blit_yuv_2_plane_count] = src_surface;
1322        ctx->blit_yuv_2_plane_count++;
1323    } else {
1324        ctx->blit_yuv_3_plane_object[ctx->blit_yuv_3_plane_count] = src_surface;
1325        ctx->blit_yuv_3_plane_count++;
1326    }
1327
1328    struct copybit_rect_t clip;
1329    while ((status == 0) && region->next(region, &clip)) {
1330        set_rects(ctx, &(src_surface), dst_rect, src_rect, &clip);
1331        if (ctx->blit_count == MAX_BLIT_OBJECT_COUNT) {
1332            ALOGW("Reached end of blit count");
1333            finish_copybit(dev);
1334        }
1335        ctx->blit_list[ctx->blit_count] = src_surface;
1336        ctx->blit_count++;
1337    }
1338
1339    // Check if we need to perform an early draw-finish.
1340    flags |= (need_temp_dst || need_temp_src) ? FLAGS_TEMP_SRC_DST : 0;
1341    if (need_to_execute_draw((eC2DFlags)flags))
1342    {
1343        finish_copybit(dev);
1344    }
1345
1346    if (need_temp_dst) {
1347        // copy the temp. destination without the alignment to the actual
1348        // destination.
1349        status = copy_image(dst_hnd, dst, CONVERT_TO_ANDROID_FORMAT);
1350        if (status == COPYBIT_FAILURE) {
1351            ALOGE("%s:copy_image failed in temp Dest",__FUNCTION__);
1352            delete_handle(dst_hnd);
1353            delete_handle(src_hnd);
1354            unmap_gpuaddr(ctx, mapped_dst_idx);
1355            unmap_gpuaddr(ctx, mapped_src_idx);
1356            return status;
1357        }
1358        // Clean the cache.
1359        IMemAlloc* memalloc = sAlloc->getAllocator(dst_hnd->flags);
1360        memalloc->clean_buffer((void *)(dst_hnd->base), dst_hnd->size,
1361                               dst_hnd->offset, dst_hnd->fd,
1362                               gralloc::CACHE_CLEAN);
1363    }
1364    delete_handle(dst_hnd);
1365    delete_handle(src_hnd);
1366
1367    ctx->is_premultiplied_alpha = false;
1368    ctx->fb_width = 0;
1369    ctx->fb_height = 0;
1370    ctx->config_mask = 0;
1371    return status;
1372}
1373
1374static int set_sync_copybit(struct copybit_device_t *dev,
1375    int /*acquireFenceFd*/)
1376{
1377    if(!dev)
1378        return -EINVAL;
1379
1380    return 0;
1381}
1382
1383static int stretch_copybit(
1384    struct copybit_device_t *dev,
1385    struct copybit_image_t const *dst,
1386    struct copybit_image_t const *src,
1387    struct copybit_rect_t const *dst_rect,
1388    struct copybit_rect_t const *src_rect,
1389    struct copybit_region_t const *region)
1390{
1391    struct copybit_context_t* ctx = (struct copybit_context_t*)dev;
1392    int status = COPYBIT_SUCCESS;
1393    bool needsBlending = (ctx->src_global_alpha != 0);
1394    pthread_mutex_lock(&ctx->wait_cleanup_lock);
1395    status = stretch_copybit_internal(dev, dst, src, dst_rect, src_rect,
1396                                    region, needsBlending);
1397    pthread_mutex_unlock(&ctx->wait_cleanup_lock);
1398    return status;
1399}
1400
1401/** Perform a blit type operation */
1402static int blit_copybit(
1403    struct copybit_device_t *dev,
1404    struct copybit_image_t const *dst,
1405    struct copybit_image_t const *src,
1406    struct copybit_region_t const *region)
1407{
1408    int status = COPYBIT_SUCCESS;
1409    struct copybit_context_t* ctx = (struct copybit_context_t*)dev;
1410    struct copybit_rect_t dr = { 0, 0, (int)dst->w, (int)dst->h };
1411    struct copybit_rect_t sr = { 0, 0, (int)src->w, (int)src->h };
1412    pthread_mutex_lock(&ctx->wait_cleanup_lock);
1413    status = stretch_copybit_internal(dev, dst, src, &dr, &sr, region, false);
1414    pthread_mutex_unlock(&ctx->wait_cleanup_lock);
1415    return status;
1416}
1417
1418/** Fill the rect on dst with RGBA color **/
1419static int fill_color(struct copybit_device_t *dev,
1420                      struct copybit_image_t const *dst,
1421                      struct copybit_rect_t const *rect,
1422                      uint32_t /*color*/)
1423{
1424    // TODO: Implement once c2d driver supports color fill
1425    if(!dev || !dst || !rect)
1426       return -EINVAL;
1427
1428    return -EINVAL;
1429}
1430
1431/*****************************************************************************/
1432
1433static void clean_up(copybit_context_t* ctx)
1434{
1435    void* ret;
1436    if (!ctx)
1437        return;
1438
1439    // stop the wait_cleanup_thread
1440    pthread_mutex_lock(&ctx->wait_cleanup_lock);
1441    ctx->stop_thread = true;
1442    // Signal waiting thread
1443    pthread_cond_signal(&ctx->wait_cleanup_cond);
1444    pthread_mutex_unlock(&ctx->wait_cleanup_lock);
1445    // waits for the cleanup thread to exit
1446    pthread_join(ctx->wait_thread_id, &ret);
1447    pthread_mutex_destroy(&ctx->wait_cleanup_lock);
1448    pthread_cond_destroy (&ctx->wait_cleanup_cond);
1449
1450    for (int i = 0; i < NUM_SURFACE_TYPES; i++) {
1451        if (ctx->dst[i])
1452            LINK_c2dDestroySurface(ctx->dst[i]);
1453    }
1454
1455    for (int i = 0; i < MAX_RGB_SURFACES; i++) {
1456        if (ctx->blit_rgb_object[i].surface_id)
1457            LINK_c2dDestroySurface(ctx->blit_rgb_object[i].surface_id);
1458    }
1459
1460    for (int i = 0; i < MAX_YUV_2_PLANE_SURFACES; i++) {
1461        if (ctx->blit_yuv_2_plane_object[i].surface_id)
1462            LINK_c2dDestroySurface(ctx->blit_yuv_2_plane_object[i].surface_id);
1463    }
1464
1465    for (int i = 0; i < MAX_YUV_3_PLANE_SURFACES; i++) {
1466        if (ctx->blit_yuv_3_plane_object[i].surface_id)
1467            LINK_c2dDestroySurface(ctx->blit_yuv_3_plane_object[i].surface_id);
1468    }
1469
1470    if (ctx->libc2d2) {
1471        ::dlclose(ctx->libc2d2);
1472        ALOGV("dlclose(libc2d2)");
1473    }
1474
1475    free(ctx);
1476}
1477
1478/** Close the copybit device */
1479static int close_copybit(struct hw_device_t *dev)
1480{
1481    struct copybit_context_t* ctx = (struct copybit_context_t*)dev;
1482    if (ctx) {
1483        free_temp_buffer(ctx->temp_src_buffer);
1484        free_temp_buffer(ctx->temp_dst_buffer);
1485    }
1486    clean_up(ctx);
1487    return 0;
1488}
1489
1490/** Open a new instance of a copybit device using name */
1491static int open_copybit(const struct hw_module_t* module, const char* name,
1492                        struct hw_device_t** device)
1493{
1494    int status = COPYBIT_SUCCESS;
1495    if (strcmp(name, COPYBIT_HARDWARE_COPYBIT0)) {
1496        return COPYBIT_FAILURE;
1497    }
1498
1499    C2D_RGB_SURFACE_DEF surfDefinition = {0};
1500    C2D_YUV_SURFACE_DEF yuvSurfaceDef = {0} ;
1501    struct copybit_context_t *ctx;
1502
1503    ctx = (struct copybit_context_t *)malloc(sizeof(struct copybit_context_t));
1504    if(!ctx) {
1505        ALOGE("%s: malloc failed", __FUNCTION__);
1506        return COPYBIT_FAILURE;
1507    }
1508
1509    /* initialize drawstate */
1510    memset(ctx, 0, sizeof(*ctx));
1511    ctx->libc2d2 = ::dlopen("libC2D2.so", RTLD_NOW);
1512    if (!ctx->libc2d2) {
1513        ALOGE("FATAL ERROR: could not dlopen libc2d2.so: %s", dlerror());
1514        clean_up(ctx);
1515        status = COPYBIT_FAILURE;
1516        *device = NULL;
1517        return status;
1518    }
1519    *(void **)&LINK_c2dCreateSurface = ::dlsym(ctx->libc2d2,
1520                                               "c2dCreateSurface");
1521    *(void **)&LINK_c2dUpdateSurface = ::dlsym(ctx->libc2d2,
1522                                               "c2dUpdateSurface");
1523    *(void **)&LINK_c2dReadSurface = ::dlsym(ctx->libc2d2,
1524                                             "c2dReadSurface");
1525    *(void **)&LINK_c2dDraw = ::dlsym(ctx->libc2d2, "c2dDraw");
1526    *(void **)&LINK_c2dFlush = ::dlsym(ctx->libc2d2, "c2dFlush");
1527    *(void **)&LINK_c2dFinish = ::dlsym(ctx->libc2d2, "c2dFinish");
1528    *(void **)&LINK_c2dWaitTimestamp = ::dlsym(ctx->libc2d2,
1529                                               "c2dWaitTimestamp");
1530    *(void **)&LINK_c2dDestroySurface = ::dlsym(ctx->libc2d2,
1531                                                "c2dDestroySurface");
1532    *(void **)&LINK_c2dMapAddr = ::dlsym(ctx->libc2d2,
1533                                         "c2dMapAddr");
1534    *(void **)&LINK_c2dUnMapAddr = ::dlsym(ctx->libc2d2,
1535                                           "c2dUnMapAddr");
1536    *(void **)&LINK_c2dGetDriverCapabilities = ::dlsym(ctx->libc2d2,
1537                                           "c2dGetDriverCapabilities");
1538    *(void **)&LINK_c2dCreateFenceFD = ::dlsym(ctx->libc2d2,
1539                                           "c2dCreateFenceFD");
1540    *(void **)&LINK_c2dFillSurface = ::dlsym(ctx->libc2d2,
1541                                           "c2dFillSurface");
1542
1543    if (!LINK_c2dCreateSurface || !LINK_c2dUpdateSurface || !LINK_c2dReadSurface
1544        || !LINK_c2dDraw || !LINK_c2dFlush || !LINK_c2dWaitTimestamp ||
1545        !LINK_c2dFinish  || !LINK_c2dDestroySurface ||
1546        !LINK_c2dGetDriverCapabilities || !LINK_c2dCreateFenceFD ||
1547        !LINK_c2dFillSurface) {
1548        ALOGE("%s: dlsym ERROR", __FUNCTION__);
1549        clean_up(ctx);
1550        status = COPYBIT_FAILURE;
1551        *device = NULL;
1552        return status;
1553    }
1554
1555    ctx->device.common.tag = HARDWARE_DEVICE_TAG;
1556    ctx->device.common.version = 1;
1557    ctx->device.common.module = (hw_module_t*)(module);
1558    ctx->device.common.close = close_copybit;
1559    ctx->device.set_parameter = set_parameter_copybit;
1560    ctx->device.get = get;
1561    ctx->device.blit = blit_copybit;
1562    ctx->device.set_sync = set_sync_copybit;
1563    ctx->device.stretch = stretch_copybit;
1564    ctx->device.finish = finish_copybit;
1565    ctx->device.flush_get_fence = flush_get_fence_copybit;
1566    ctx->device.clear = clear_copybit;
1567    ctx->device.fill_color = fill_color;
1568
1569    /* Create RGB Surface */
1570    surfDefinition.buffer = (void*)0xdddddddd;
1571    surfDefinition.phys = (void*)0xdddddddd;
1572    surfDefinition.stride = 1 * 4;
1573    surfDefinition.width = 1;
1574    surfDefinition.height = 1;
1575    surfDefinition.format = C2D_COLOR_FORMAT_8888_ARGB;
1576    if (LINK_c2dCreateSurface(&(ctx->dst[RGB_SURFACE]), C2D_TARGET | C2D_SOURCE,
1577                              (C2D_SURFACE_TYPE)(C2D_SURFACE_RGB_HOST |
1578                                                 C2D_SURFACE_WITH_PHYS |
1579                                                 C2D_SURFACE_WITH_PHYS_DUMMY ),
1580                                                 &surfDefinition)) {
1581        ALOGE("%s: create ctx->dst_surface[RGB_SURFACE] failed", __FUNCTION__);
1582        ctx->dst[RGB_SURFACE] = 0;
1583        clean_up(ctx);
1584        status = COPYBIT_FAILURE;
1585        *device = NULL;
1586        return status;
1587    }
1588
1589    unsigned int surface_id = 0;
1590    for (int i = 0; i < MAX_RGB_SURFACES; i++)
1591    {
1592        if (LINK_c2dCreateSurface(&surface_id, C2D_TARGET | C2D_SOURCE,
1593                              (C2D_SURFACE_TYPE)(C2D_SURFACE_RGB_HOST |
1594                                                 C2D_SURFACE_WITH_PHYS |
1595                                                 C2D_SURFACE_WITH_PHYS_DUMMY ),
1596                                                 &surfDefinition)) {
1597            ALOGE("%s: create RGB source surface %d failed", __FUNCTION__, i);
1598            ctx->blit_rgb_object[i].surface_id = 0;
1599            status = COPYBIT_FAILURE;
1600            break;
1601        } else {
1602            ctx->blit_rgb_object[i].surface_id = surface_id;
1603            ALOGW("%s i = %d surface_id=%d",  __FUNCTION__, i,
1604                                          ctx->blit_rgb_object[i].surface_id);
1605        }
1606    }
1607
1608    if (status == COPYBIT_FAILURE) {
1609        clean_up(ctx);
1610        status = COPYBIT_FAILURE;
1611        *device = NULL;
1612        return status;
1613    }
1614
1615    // Create 2 plane YUV surfaces
1616    yuvSurfaceDef.format = C2D_COLOR_FORMAT_420_NV12;
1617    yuvSurfaceDef.width = 4;
1618    yuvSurfaceDef.height = 4;
1619    yuvSurfaceDef.plane0 = (void*)0xaaaaaaaa;
1620    yuvSurfaceDef.phys0 = (void*) 0xaaaaaaaa;
1621    yuvSurfaceDef.stride0 = 4;
1622
1623    yuvSurfaceDef.plane1 = (void*)0xaaaaaaaa;
1624    yuvSurfaceDef.phys1 = (void*) 0xaaaaaaaa;
1625    yuvSurfaceDef.stride1 = 4;
1626    if (LINK_c2dCreateSurface(&(ctx->dst[YUV_SURFACE_2_PLANES]),
1627                              C2D_TARGET | C2D_SOURCE,
1628                              (C2D_SURFACE_TYPE)(C2D_SURFACE_YUV_HOST |
1629                               C2D_SURFACE_WITH_PHYS |
1630                               C2D_SURFACE_WITH_PHYS_DUMMY),
1631                              &yuvSurfaceDef)) {
1632        ALOGE("%s: create ctx->dst[YUV_SURFACE_2_PLANES] failed", __FUNCTION__);
1633        ctx->dst[YUV_SURFACE_2_PLANES] = 0;
1634        clean_up(ctx);
1635        status = COPYBIT_FAILURE;
1636        *device = NULL;
1637        return status;
1638    }
1639
1640    for (int i=0; i < MAX_YUV_2_PLANE_SURFACES; i++)
1641    {
1642        if (LINK_c2dCreateSurface(&surface_id, C2D_TARGET | C2D_SOURCE,
1643                              (C2D_SURFACE_TYPE)(C2D_SURFACE_YUV_HOST |
1644                                                 C2D_SURFACE_WITH_PHYS |
1645                                                 C2D_SURFACE_WITH_PHYS_DUMMY ),
1646                              &yuvSurfaceDef)) {
1647            ALOGE("%s: create YUV source %d failed", __FUNCTION__, i);
1648            ctx->blit_yuv_2_plane_object[i].surface_id = 0;
1649            status = COPYBIT_FAILURE;
1650            break;
1651        } else {
1652            ctx->blit_yuv_2_plane_object[i].surface_id = surface_id;
1653            ALOGW("%s: 2 Plane YUV i=%d surface_id=%d",  __FUNCTION__, i,
1654                                   ctx->blit_yuv_2_plane_object[i].surface_id);
1655        }
1656    }
1657
1658    if (status == COPYBIT_FAILURE) {
1659        clean_up(ctx);
1660        status = COPYBIT_FAILURE;
1661        *device = NULL;
1662        return status;
1663    }
1664
1665    // Create YUV 3 plane surfaces
1666    yuvSurfaceDef.format = C2D_COLOR_FORMAT_420_YV12;
1667    yuvSurfaceDef.plane2 = (void*)0xaaaaaaaa;
1668    yuvSurfaceDef.phys2 = (void*) 0xaaaaaaaa;
1669    yuvSurfaceDef.stride2 = 4;
1670
1671    if (LINK_c2dCreateSurface(&(ctx->dst[YUV_SURFACE_3_PLANES]),
1672                              C2D_TARGET | C2D_SOURCE,
1673                              (C2D_SURFACE_TYPE)(C2D_SURFACE_YUV_HOST |
1674                                                 C2D_SURFACE_WITH_PHYS |
1675                                                 C2D_SURFACE_WITH_PHYS_DUMMY),
1676                              &yuvSurfaceDef)) {
1677        ALOGE("%s: create ctx->dst[YUV_SURFACE_3_PLANES] failed", __FUNCTION__);
1678        ctx->dst[YUV_SURFACE_3_PLANES] = 0;
1679        clean_up(ctx);
1680        status = COPYBIT_FAILURE;
1681        *device = NULL;
1682        return status;
1683    }
1684
1685    for (int i=0; i < MAX_YUV_3_PLANE_SURFACES; i++)
1686    {
1687        if (LINK_c2dCreateSurface(&(surface_id),
1688                              C2D_TARGET | C2D_SOURCE,
1689                              (C2D_SURFACE_TYPE)(C2D_SURFACE_YUV_HOST |
1690                                                 C2D_SURFACE_WITH_PHYS |
1691                                                 C2D_SURFACE_WITH_PHYS_DUMMY),
1692                              &yuvSurfaceDef)) {
1693            ALOGE("%s: create 3 plane YUV surface %d failed", __FUNCTION__, i);
1694            ctx->blit_yuv_3_plane_object[i].surface_id = 0;
1695            status = COPYBIT_FAILURE;
1696            break;
1697        } else {
1698            ctx->blit_yuv_3_plane_object[i].surface_id = surface_id;
1699            ALOGW("%s: 3 Plane YUV i=%d surface_id=%d",  __FUNCTION__, i,
1700                                   ctx->blit_yuv_3_plane_object[i].surface_id);
1701        }
1702    }
1703
1704    if (status == COPYBIT_FAILURE) {
1705        clean_up(ctx);
1706        status = COPYBIT_FAILURE;
1707        *device = NULL;
1708        return status;
1709    }
1710
1711    if (LINK_c2dGetDriverCapabilities(&(ctx->c2d_driver_info))) {
1712         ALOGE("%s: LINK_c2dGetDriverCapabilities failed", __FUNCTION__);
1713         clean_up(ctx);
1714         status = COPYBIT_FAILURE;
1715        *device = NULL;
1716        return status;
1717    }
1718    // Initialize context variables.
1719    ctx->trg_transform = C2D_TARGET_ROTATE_0;
1720
1721    ctx->temp_src_buffer.fd = -1;
1722    ctx->temp_src_buffer.base = 0;
1723    ctx->temp_src_buffer.size = 0;
1724
1725    ctx->temp_dst_buffer.fd = -1;
1726    ctx->temp_dst_buffer.base = 0;
1727    ctx->temp_dst_buffer.size = 0;
1728
1729    ctx->fb_width = 0;
1730    ctx->fb_height = 0;
1731
1732    ctx->blit_rgb_count = 0;
1733    ctx->blit_yuv_2_plane_count = 0;
1734    ctx->blit_yuv_3_plane_count = 0;
1735    ctx->blit_count = 0;
1736
1737    ctx->wait_timestamp = false;
1738    ctx->stop_thread = false;
1739    pthread_mutex_init(&(ctx->wait_cleanup_lock), NULL);
1740    pthread_cond_init(&(ctx->wait_cleanup_cond), NULL);
1741    /* Start the wait thread */
1742    pthread_attr_t attr;
1743    pthread_attr_init(&attr);
1744    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1745
1746    pthread_create(&ctx->wait_thread_id, &attr, &c2d_wait_loop,
1747                                                            (void *)ctx);
1748    pthread_attr_destroy(&attr);
1749
1750    *device = &ctx->device.common;
1751    return status;
1752}
1753