1/*
2* Copyright (C) 2011 The Android Open Source Project
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16#include <string.h>
17#include <pthread.h>
18#include <limits.h>
19#include <cutils/ashmem.h>
20#include <unistd.h>
21#include <errno.h>
22#include <dlfcn.h>
23#include <sys/mman.h>
24#include "gralloc_cb.h"
25#include "goldfish_dma.h"
26#include "FormatConversions.h"
27#include "HostConnection.h"
28#include "ProcessPipe.h"
29#include "glUtils.h"
30#include <cutils/log.h>
31#include <cutils/properties.h>
32
33#include <set>
34#include <string>
35#include <sstream>
36
37/* Set to 1 or 2 to enable debug traces */
38#define DEBUG  0
39
40#if DEBUG >= 1
41#  define D(...)   ALOGD(__VA_ARGS__)
42#else
43#  define D(...)   ((void)0)
44#endif
45
46#if DEBUG >= 2
47#  define DD(...)  ALOGD(__VA_ARGS__)
48#else
49#  define DD(...)  ((void)0)
50#endif
51
52#define DBG_FUNC DBG("%s\n", __FUNCTION__)
53
54#ifdef GOLDFISH_HIDL_GRALLOC
55static bool isHidlGralloc = true;
56#else
57static bool isHidlGralloc = false;
58#endif
59
60int32_t* getOpenCountPtr(cb_handle_t* cb) {
61    return ((int32_t*)cb->ashmemBase) + 1;
62}
63
64uint32_t getAshmemColorOffset(cb_handle_t* cb) {
65    uint32_t res = 0;
66    if (cb->canBePosted()) res = sizeof(intptr_t);
67    if (isHidlGralloc) res = sizeof(intptr_t) * 2;
68    return res;
69}
70
71//
72// our private gralloc module structure
73//
74struct private_module_t {
75    gralloc_module_t base;
76};
77
78/* If not NULL, this is a pointer to the fallback module.
79 * This really is gralloc.default, which we'll use if we detect
80 * that the emulator we're running in does not support GPU emulation.
81 */
82static gralloc_module_t*  sFallback;
83static pthread_once_t     sFallbackOnce = PTHREAD_ONCE_INIT;
84
85static void fallback_init(void);  // forward
86
87typedef struct _alloc_list_node {
88    buffer_handle_t handle;
89    _alloc_list_node *next;
90    _alloc_list_node *prev;
91} AllocListNode;
92
93struct MemRegionInfo {
94    void* ashmemBase;
95    mutable uint32_t refCount;
96};
97
98struct MemRegionInfoCmp {
99    bool operator()(const MemRegionInfo& a, const MemRegionInfo& b) const {
100        return a.ashmemBase < b.ashmemBase;
101    }
102};
103
104typedef std::set<MemRegionInfo, MemRegionInfoCmp> MemRegionSet;
105typedef MemRegionSet::iterator mem_region_handle_t;
106
107//
108// Our gralloc device structure (alloc interface)
109//
110struct gralloc_device_t {
111    alloc_device_t  device;
112
113    AllocListNode *allocListHead;    // double linked list of allocated buffers
114    MemRegionSet ashmemRegions; // to track allocations of each ashmem region
115    pthread_mutex_t lock;
116};
117
118struct gralloc_memregions_t {
119    MemRegionSet ashmemRegions;
120};
121
122#define INITIAL_DMA_REGION_SIZE 4096
123struct gralloc_dmaregion_t {
124    goldfish_dma_context goldfish_dma;
125    uint32_t sz;
126    uint32_t refcount;
127    pthread_mutex_t lock;
128};
129
130// global device instance
131static gralloc_memregions_t* s_grdev = NULL;
132static gralloc_dmaregion_t* s_grdma = NULL;
133
134void init_gralloc_memregions() {
135    if (s_grdev) return;
136    s_grdev = new gralloc_memregions_t;
137}
138
139void init_gralloc_dmaregion() {
140    D("%s: call\n", __FUNCTION__);
141    if (s_grdma) return;
142
143    s_grdma = new gralloc_dmaregion_t;
144    s_grdma->sz = INITIAL_DMA_REGION_SIZE;
145    s_grdma->refcount = 0;
146
147    pthread_mutex_init(&s_grdma->lock, NULL);
148    pthread_mutex_lock(&s_grdma->lock);
149    goldfish_dma_create_region(s_grdma->sz, &s_grdma->goldfish_dma);
150    pthread_mutex_unlock(&s_grdma->lock);
151}
152
153void get_gralloc_dmaregion() {
154    if (!s_grdma) return;
155    pthread_mutex_lock(&s_grdma->lock);
156    s_grdma->refcount++;
157    D("%s: call. refcount: %u\n", __FUNCTION__, s_grdma->refcount);
158    pthread_mutex_unlock(&s_grdma->lock);
159}
160
161static void resize_gralloc_dmaregion_locked(uint32_t new_sz) {
162    if (!s_grdma) return;
163    if (s_grdma->goldfish_dma.mapped) {
164        goldfish_dma_unmap(&s_grdma->goldfish_dma);
165    }
166    close(s_grdma->goldfish_dma.fd);
167    goldfish_dma_create_region(new_sz, &s_grdma->goldfish_dma);
168    s_grdma->sz = new_sz;
169}
170
171bool put_gralloc_dmaregion() {
172    if (!s_grdma) return false;
173    pthread_mutex_lock(&s_grdma->lock);
174    D("%s: call. refcount before: %u\n", __FUNCTION__, s_grdma->refcount);
175    s_grdma->refcount--;
176    bool shouldDelete = !s_grdma->refcount;
177    if (shouldDelete) {
178        D("%s: should delete!\n", __FUNCTION__);
179        resize_gralloc_dmaregion_locked(INITIAL_DMA_REGION_SIZE);
180        D("%s: done\n", __FUNCTION__);
181    }
182    pthread_mutex_unlock(&s_grdma->lock);
183    D("%s: exit\n", __FUNCTION__);
184    return shouldDelete;
185}
186
187void gralloc_dmaregion_register_ashmem(uint32_t sz) {
188    if (!s_grdma) return;
189    pthread_mutex_lock(&s_grdma->lock);
190    D("%s: for sz %u, refcount %u", __FUNCTION__, sz, s_grdma->refcount);
191    uint32_t new_sz = std::max(s_grdma->sz, sz);
192    if (new_sz != s_grdma->sz) {
193        D("%s: change sz from %u to %u", __FUNCTION__, s_grdma->sz, sz);
194        resize_gralloc_dmaregion_locked(new_sz);
195    }
196    if (!s_grdma->goldfish_dma.mapped) {
197        goldfish_dma_map(&s_grdma->goldfish_dma);
198    }
199    pthread_mutex_unlock(&s_grdma->lock);
200}
201
202void get_mem_region(void* ashmemBase) {
203    init_gralloc_memregions();
204    D("%s: call for %p", __FUNCTION__, ashmemBase);
205    MemRegionInfo lookup;
206    lookup.ashmemBase = ashmemBase;
207    mem_region_handle_t handle = s_grdev->ashmemRegions.find(lookup);
208    if (handle == s_grdev->ashmemRegions.end()) {
209        MemRegionInfo newRegion;
210        newRegion.ashmemBase = ashmemBase;
211        newRegion.refCount = 1;
212        s_grdev->ashmemRegions.insert(newRegion);
213    } else {
214        handle->refCount++;
215    }
216}
217
218bool put_mem_region(void* ashmemBase) {
219    init_gralloc_memregions();
220    D("%s: call for %p", __FUNCTION__, ashmemBase);
221    MemRegionInfo lookup;
222    lookup.ashmemBase = ashmemBase;
223    mem_region_handle_t handle = s_grdev->ashmemRegions.find(lookup);
224    if (handle == s_grdev->ashmemRegions.end()) {
225        ALOGE("%s: error: tried to put nonexistent mem region!", __FUNCTION__);
226        return true;
227    } else {
228        handle->refCount--;
229        bool shouldRemove = !handle->refCount;
230        if (shouldRemove) {
231            s_grdev->ashmemRegions.erase(lookup);
232        }
233        return shouldRemove;
234    }
235}
236
237void dump_regions() {
238    init_gralloc_memregions();
239    mem_region_handle_t curr = s_grdev->ashmemRegions.begin();
240    std::stringstream res;
241    for (; curr != s_grdev->ashmemRegions.end(); curr++) {
242        res << "\tashmem base " << curr->ashmemBase << " refcount " << curr->refCount << "\n";
243    }
244    ALOGD("ashmem region dump [\n%s]", res.str().c_str());
245}
246
247#if DEBUG
248
249#define GET_ASHMEM_REGION(cb) \
250    dump_regions(); \
251    get_mem_region((void*)cb->ashmemBase); \
252    dump_regions(); \
253
254#define PUT_ASHMEM_REGION(cb) \
255    dump_regions(); \
256    bool SHOULD_UNMAP = put_mem_region((void*)cb->ashmemBase); \
257    dump_regions(); \
258
259#else
260
261#define GET_ASHMEM_REGION(cb) \
262    get_mem_region((void*)cb->ashmemBase); \
263
264#define PUT_ASHMEM_REGION(cb) \
265    bool SHOULD_UNMAP = put_mem_region((void*)cb->ashmemBase); \
266
267#endif
268
269//
270// Our framebuffer device structure
271//
272struct fb_device_t {
273    framebuffer_device_t  device;
274};
275
276static int map_buffer(cb_handle_t *cb, void **vaddr)
277{
278    if (cb->fd < 0 || cb->ashmemSize <= 0) {
279        return -EINVAL;
280    }
281
282    int map_flags = MAP_SHARED;
283    if (isHidlGralloc) map_flags |= MAP_ANONYMOUS;
284
285    void *addr = mmap(0, cb->ashmemSize, PROT_READ | PROT_WRITE,
286                      MAP_SHARED, cb->fd, 0);
287    if (addr == MAP_FAILED) {
288        ALOGE("%s: failed to map ashmem region!", __FUNCTION__);
289        return -errno;
290    }
291
292    cb->ashmemBase = intptr_t(addr);
293    cb->ashmemBasePid = getpid();
294    D("%s: %p mapped ashmem base %p size %d\n", __FUNCTION__,
295      cb, cb->ashmemBase, cb->ashmemSize);
296
297    *vaddr = addr;
298    return 0;
299}
300
301#define DEFINE_HOST_CONNECTION \
302    HostConnection *hostCon = HostConnection::get(); \
303    ExtendedRCEncoderContext *rcEnc = (hostCon ? hostCon->rcEncoder() : NULL)
304
305#define DEFINE_AND_VALIDATE_HOST_CONNECTION \
306    HostConnection *hostCon = HostConnection::get(); \
307    if (!hostCon) { \
308        ALOGE("gralloc: Failed to get host connection\n"); \
309        return -EIO; \
310    } \
311    ExtendedRCEncoderContext *rcEnc = hostCon->rcEncoder(); \
312    if (!rcEnc) { \
313        ALOGE("gralloc: Failed to get renderControl encoder context\n"); \
314        return -EIO; \
315    }
316
317#if PLATFORM_SDK_VERSION < 18
318// On older APIs, just define it as a value no one is going to use.
319#define HAL_PIXEL_FORMAT_YCbCr_420_888 0xFFFFFFFF
320#endif
321
322static void updateHostColorBuffer(cb_handle_t* cb,
323                              bool doLocked,
324                              char* pixels) {
325    D("%s: call. doLocked=%d", __FUNCTION__, doLocked);
326    DEFINE_HOST_CONNECTION;
327    int bpp = glUtilsPixelBitSize(cb->glFormat, cb->glType) >> 3;
328    int left = doLocked ? cb->lockedLeft : 0;
329    int top = doLocked ? cb->lockedTop : 0;
330    int width = doLocked ? cb->lockedWidth : cb->width;
331    int height = doLocked ? cb->lockedHeight : cb->height;
332
333    char* to_send = pixels;
334    uint32_t rgbSz = width * height * bpp;
335    uint32_t send_buffer_size = rgbSz;
336    bool is_rgb_format =
337        cb->frameworkFormat != HAL_PIXEL_FORMAT_YV12 &&
338        cb->frameworkFormat != HAL_PIXEL_FORMAT_YCbCr_420_888;
339
340    char* convertedBuf = NULL;
341    if ((doLocked && is_rgb_format) ||
342        (!s_grdma &&
343         (doLocked || !is_rgb_format))) {
344        convertedBuf = new char[rgbSz];
345        to_send = convertedBuf;
346        send_buffer_size = rgbSz;
347    }
348
349    if (doLocked && is_rgb_format) {
350        copy_rgb_buffer_from_unlocked(
351                to_send, pixels,
352                cb->width,
353                width, height, top, left, bpp);
354    }
355
356    if (s_grdma) {
357        if (cb->frameworkFormat == HAL_PIXEL_FORMAT_YV12) {
358            get_yv12_offsets(width, height, NULL, NULL,
359                             &send_buffer_size);
360        }
361        if (cb->frameworkFormat == HAL_PIXEL_FORMAT_YCbCr_420_888) {
362            get_yuv420p_offsets(width, height, NULL, NULL,
363                                &send_buffer_size);
364        }
365
366        rcEnc->bindDmaContext(&s_grdma->goldfish_dma);
367        D("%s: call. dma update with sz=%u", __FUNCTION__, send_buffer_size);
368        pthread_mutex_lock(&s_grdma->lock);
369        rcEnc->rcUpdateColorBufferDMA(rcEnc, cb->hostHandle,
370                left, top, width, height,
371                cb->glFormat, cb->glType,
372                to_send, send_buffer_size);
373        pthread_mutex_unlock(&s_grdma->lock);
374    } else {
375        if (cb->frameworkFormat == HAL_PIXEL_FORMAT_YV12) {
376            yv12_to_rgb888(to_send, pixels,
377                           width, height, left, top,
378                           left + width - 1, top + height - 1);
379        }
380        if (cb->frameworkFormat == HAL_PIXEL_FORMAT_YCbCr_420_888) {
381            yuv420p_to_rgb888(to_send, pixels,
382                              width, height, left, top,
383                              left + width - 1, top + height - 1);
384        }
385        rcEnc->rcUpdateColorBuffer(rcEnc, cb->hostHandle,
386                left, top, width, height,
387                cb->glFormat, cb->glType, to_send);
388    }
389
390    if (convertedBuf) delete [] convertedBuf;
391}
392
393//
394// gralloc device functions (alloc interface)
395//
396static int gralloc_alloc(alloc_device_t* dev,
397                         int w, int h, int format, int usage,
398                         buffer_handle_t* pHandle, int* pStride)
399{
400    D("gralloc_alloc w=%d h=%d usage=0x%x format=0x%x\n", w, h, usage, format);
401
402    gralloc_device_t *grdev = (gralloc_device_t *)dev;
403    if (!grdev || !pHandle || !pStride) {
404        ALOGE("gralloc_alloc: Bad inputs (grdev: %p, pHandle: %p, pStride: %p",
405                grdev, pHandle, pStride);
406        return -EINVAL;
407    }
408
409    //
410    // Note: in screen capture mode, both sw_write and hw_write will be on
411    // and this is a valid usage
412    //
413    bool sw_write = (0 != (usage & GRALLOC_USAGE_SW_WRITE_MASK));
414    bool hw_write = (usage & GRALLOC_USAGE_HW_RENDER);
415    bool sw_read = (0 != (usage & GRALLOC_USAGE_SW_READ_MASK));
416#if PLATFORM_SDK_VERSION >= 17
417    bool hw_cam_write = (usage & GRALLOC_USAGE_HW_CAMERA_WRITE);
418    bool hw_cam_read = (usage & GRALLOC_USAGE_HW_CAMERA_READ);
419#else // PLATFORM_SDK_VERSION
420    bool hw_cam_write = false;
421    bool hw_cam_read = false;
422#endif // PLATFORM_SDK_VERSION
423#if PLATFORM_SDK_VERSION >= 15
424    bool hw_vid_enc_read = usage & GRALLOC_USAGE_HW_VIDEO_ENCODER;
425#else // PLATFORM_SDK_VERSION
426    bool hw_vid_enc_read = false;
427#endif // PLATFORM_SDK_VERSION
428
429    // Keep around original requested format for later validation
430    int frameworkFormat = format;
431    // Pick the right concrete pixel format given the endpoints as encoded in
432    // the usage bits.  Every end-point pair needs explicit listing here.
433#if PLATFORM_SDK_VERSION >= 17
434    if (format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
435        // Camera as producer
436        if (usage & GRALLOC_USAGE_HW_CAMERA_WRITE) {
437            if (usage & GRALLOC_USAGE_HW_TEXTURE) {
438                // Camera-to-display is RGBA
439                format = HAL_PIXEL_FORMAT_RGBA_8888;
440            } else if (usage & GRALLOC_USAGE_HW_VIDEO_ENCODER) {
441                // Camera-to-encoder is NV21
442                format = HAL_PIXEL_FORMAT_YCrCb_420_SP;
443            } else if ((usage & GRALLOC_USAGE_HW_CAMERA_MASK) ==
444                    GRALLOC_USAGE_HW_CAMERA_ZSL) {
445                // Camera-to-ZSL-queue is RGB_888
446                format = HAL_PIXEL_FORMAT_RGB_888;
447            }
448        }
449
450        if (format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
451            ALOGE("gralloc_alloc: Requested auto format selection, "
452                    "but no known format for this usage: %d x %d, usage %x",
453                    w, h, usage);
454            return -EINVAL;
455        }
456    }
457    else if (format == HAL_PIXEL_FORMAT_YCbCr_420_888) {
458        ALOGW("gralloc_alloc: Requested YCbCr_420_888, taking experimental path. "
459                "usage: %d x %d, usage %x",
460                w, h, usage);
461    }
462#endif // PLATFORM_SDK_VERSION >= 17
463    bool yuv_format = false;
464
465    int ashmem_size = 0;
466    int stride = w;
467
468    GLenum glFormat = 0;
469    GLenum glType = 0;
470    EmulatorFrameworkFormat selectedEmuFrameworkFormat = FRAMEWORK_FORMAT_GL_COMPATIBLE;
471
472    int bpp = 0;
473    int align = 1;
474    switch (format) {
475        case HAL_PIXEL_FORMAT_RGBA_8888:
476        case HAL_PIXEL_FORMAT_RGBX_8888:
477        case HAL_PIXEL_FORMAT_BGRA_8888:
478            bpp = 4;
479            glFormat = GL_RGBA;
480            glType = GL_UNSIGNED_BYTE;
481            break;
482        case HAL_PIXEL_FORMAT_RGB_888:
483            bpp = 3;
484            glFormat = GL_RGB;
485            glType = GL_UNSIGNED_BYTE;
486            break;
487        case HAL_PIXEL_FORMAT_RGB_565:
488            bpp = 2;
489            glFormat = GL_RGB;
490            glType = GL_UNSIGNED_SHORT_5_6_5;
491            break;
492#if PLATFORM_SDK_VERSION >= 21
493        case HAL_PIXEL_FORMAT_RAW16:
494        case HAL_PIXEL_FORMAT_Y16:
495#elif PLATFORM_SDK_VERSION >= 16
496        case HAL_PIXEL_FORMAT_RAW_SENSOR:
497#endif
498            bpp = 2;
499            align = 16*bpp;
500            if (! ((sw_read || hw_cam_read) && (sw_write || hw_cam_write) ) ) {
501                // Raw sensor data or Y16 only goes between camera and CPU
502                return -EINVAL;
503            }
504            // Not expecting to actually create any GL surfaces for this
505            glFormat = GL_LUMINANCE;
506            glType = GL_UNSIGNED_SHORT;
507            break;
508#if PLATFORM_SDK_VERSION >= 17
509        case HAL_PIXEL_FORMAT_BLOB:
510            bpp = 1;
511            if (! (sw_read && hw_cam_write) ) {
512                // Blob data cannot be used by HW other than camera emulator
513                return -EINVAL;
514            }
515            // Not expecting to actually create any GL surfaces for this
516            glFormat = GL_LUMINANCE;
517            glType = GL_UNSIGNED_BYTE;
518            break;
519#endif // PLATFORM_SDK_VERSION >= 17
520        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
521            align = 1;
522            bpp = 1; // per-channel bpp
523            yuv_format = true;
524            // Not expecting to actually create any GL surfaces for this
525            break;
526        case HAL_PIXEL_FORMAT_YV12:
527            align = 16;
528            bpp = 1; // per-channel bpp
529            yuv_format = true;
530            // We are going to use RGB888 on the host
531            glFormat = GL_RGB;
532            glType = GL_UNSIGNED_BYTE;
533            selectedEmuFrameworkFormat = FRAMEWORK_FORMAT_YV12;
534            break;
535        case HAL_PIXEL_FORMAT_YCbCr_420_888:
536            align = 1;
537            bpp = 1; // per-channel bpp
538            yuv_format = true;
539            // We are going to use RGB888 on the host
540            glFormat = GL_RGB;
541            glType = GL_UNSIGNED_BYTE;
542            selectedEmuFrameworkFormat = FRAMEWORK_FORMAT_YUV_420_888;
543            break;
544        default:
545            ALOGE("gralloc_alloc: Unknown format %d", format);
546            return -EINVAL;
547    }
548
549    //
550    // Allocate ColorBuffer handle on the host (only if h/w access is allowed)
551    // Only do this for some h/w usages, not all.
552    // Also do this if we need to read from the surface, in this case the
553    // rendering will still happen on the host but we also need to be able to
554    // read back from the color buffer, which requires that there is a buffer
555    //
556    bool needHostCb = (!yuv_format ||
557                       frameworkFormat == HAL_PIXEL_FORMAT_YV12 ||
558                       frameworkFormat == HAL_PIXEL_FORMAT_YCbCr_420_888) &&
559#if PLATFORM_SDK_VERSION >= 15
560                      (usage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
561                                GRALLOC_USAGE_HW_2D | GRALLOC_USAGE_HW_COMPOSER |
562                                GRALLOC_USAGE_HW_VIDEO_ENCODER |
563                                GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_SW_READ_MASK))
564#else // PLATFORM_SDK_VERSION
565                      (usage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
566                                GRALLOC_USAGE_HW_2D |
567                                GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_SW_READ_MASK))
568#endif // PLATFORM_SDK_VERSION
569                      ;
570
571    if (isHidlGralloc) {
572        if (needHostCb || (usage & GRALLOC_USAGE_HW_FB)) {
573            // keep space for postCounter
574            // AND openCounter for all host cb
575            ashmem_size += sizeof(uint32_t) * 2;
576        }
577    } else {
578        if (usage & GRALLOC_USAGE_HW_FB) {
579            // keep space for postCounter
580            ashmem_size += sizeof(uint32_t) * 1;
581        }
582    }
583
584    if (sw_read || sw_write || hw_cam_write || hw_vid_enc_read) {
585        // keep space for image on guest memory if SW access is needed
586        // or if the camera is doing writing
587        if (yuv_format) {
588            size_t yStride = (w*bpp + (align - 1)) & ~(align-1);
589            size_t uvStride = (yStride / 2 + (align - 1)) & ~(align-1);
590            size_t uvHeight = h / 2;
591            ashmem_size += yStride * h + 2 * (uvHeight * uvStride);
592            stride = yStride / bpp;
593        } else {
594            size_t bpr = (w*bpp + (align-1)) & ~(align-1);
595            ashmem_size += (bpr * h);
596            stride = bpr / bpp;
597        }
598    }
599
600    D("gralloc_alloc format=%d, ashmem_size=%d, stride=%d, tid %d\n", format,
601            ashmem_size, stride, gettid());
602
603    //
604    // Allocate space in ashmem if needed
605    //
606    int fd = -1;
607    if (ashmem_size > 0) {
608        // round to page size;
609        ashmem_size = (ashmem_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
610
611        ALOGD("%s: Creating ashmem region of size %lu\n", __FUNCTION__, ashmem_size);
612        fd = ashmem_create_region("gralloc-buffer", ashmem_size);
613        if (fd < 0) {
614            ALOGE("gralloc_alloc failed to create ashmem region: %s\n",
615                    strerror(errno));
616            return -errno;
617        }
618    }
619
620    cb_handle_t *cb = new cb_handle_t(fd, ashmem_size, usage,
621                                      w, h, frameworkFormat, format,
622                                      glFormat, glType, selectedEmuFrameworkFormat);
623
624    DEFINE_HOST_CONNECTION;
625    if (ashmem_size > 0) {
626
627        //
628        // map ashmem region if exist
629        //
630        void *vaddr;
631        int err = map_buffer(cb, &vaddr);
632        if (err) {
633            close(fd);
634            delete cb;
635            return err;
636        }
637
638        cb->setFd(fd);
639
640        if (rcEnc->getDmaVersion() > 0) {
641            D("%s: creating goldfish dma region of size %lu (cb fd %d)\n", __FUNCTION__, ashmem_size, cb->fd);
642            init_gralloc_dmaregion();
643            get_gralloc_dmaregion();
644        } else {
645            cb->goldfish_dma.fd = -1;
646        }
647    } else {
648        cb->goldfish_dma.fd = -1;
649    }
650
651    if (needHostCb) {
652        if (hostCon && rcEnc) {
653            if (s_grdma) {
654                cb->hostHandle = rcEnc->rcCreateColorBufferDMA(rcEnc, w, h, glFormat, cb->emuFrameworkFormat);
655            } else {
656                cb->hostHandle = rcEnc->rcCreateColorBuffer(rcEnc, w, h, glFormat);
657            }
658            D("Created host ColorBuffer 0x%x\n", cb->hostHandle);
659        }
660
661        if (!cb->hostHandle) {
662            // Could not create colorbuffer on host !!!
663            close(fd);
664            delete cb;
665            ALOGD("%s: failed to create host cb! -EIO", __FUNCTION__);
666            return -EIO;
667        }
668
669        if (isHidlGralloc) { *getOpenCountPtr(cb) = 0; }
670    }
671
672    //
673    // alloc succeeded - insert the allocated handle to the allocated list
674    //
675    AllocListNode *node = new AllocListNode();
676    pthread_mutex_lock(&grdev->lock);
677    node->handle = cb;
678    node->next =  grdev->allocListHead;
679    node->prev =  NULL;
680    if (grdev->allocListHead) {
681        grdev->allocListHead->prev = node;
682    }
683    grdev->allocListHead = node;
684    pthread_mutex_unlock(&grdev->lock);
685
686    *pHandle = cb;
687    D("%s: alloc succeded, new ashmem base and size: %p %d handle: %p",
688      __FUNCTION__, cb->ashmemBase, cb->ashmemSize, cb);
689    switch (frameworkFormat) {
690    case HAL_PIXEL_FORMAT_YCbCr_420_888:
691        *pStride = 0;
692        break;
693    default:
694        *pStride = stride;
695        break;
696    }
697    return 0;
698}
699
700static int gralloc_free(alloc_device_t* dev,
701                        buffer_handle_t handle)
702{
703    cb_handle_t *cb = (cb_handle_t *)handle;
704    if (!cb_handle_t::validate((cb_handle_t*)cb)) {
705        ERR("gralloc_free: invalid handle");
706        return -EINVAL;
707    }
708
709    D("%s: for buf %p ptr %p size %d\n",
710      __FUNCTION__, handle, cb->ashmemBase, cb->ashmemSize);
711
712    if (cb->hostHandle) {
713        int32_t openCount = 1;
714        int32_t* openCountPtr = &openCount;
715
716        if (isHidlGralloc) { openCountPtr = getOpenCountPtr(cb); }
717
718        if (*openCountPtr > 0) {
719            DEFINE_AND_VALIDATE_HOST_CONNECTION;
720            D("Closing host ColorBuffer 0x%x\n", cb->hostHandle);
721            rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
722        } else {
723            D("A rcCloseColorBuffer is owed!!! sdk ver: %d", PLATFORM_SDK_VERSION);
724            *openCountPtr = -1;
725        }
726    }
727
728    //
729    // detach and unmap ashmem area if present
730    //
731    if (cb->fd > 0) {
732        if (cb->ashmemSize > 0 && cb->ashmemBase) {
733            D("%s: unmapped %p", __FUNCTION__, cb->ashmemBase);
734            munmap((void *)cb->ashmemBase, cb->ashmemSize);
735            put_gralloc_dmaregion();
736        }
737        close(cb->fd);
738    }
739
740    D("%s: done", __FUNCTION__);
741    // remove it from the allocated list
742    gralloc_device_t *grdev = (gralloc_device_t *)dev;
743    pthread_mutex_lock(&grdev->lock);
744    AllocListNode *n = grdev->allocListHead;
745    while( n && n->handle != cb ) {
746        n = n->next;
747    }
748    if (n) {
749       // buffer found on list - remove it from list
750       if (n->next) {
751           n->next->prev = n->prev;
752       }
753       if (n->prev) {
754           n->prev->next = n->next;
755       }
756       else {
757           grdev->allocListHead = n->next;
758       }
759
760       delete n;
761    }
762    pthread_mutex_unlock(&grdev->lock);
763
764    delete cb;
765
766    D("%s: exit", __FUNCTION__);
767    return 0;
768}
769
770static int gralloc_device_close(struct hw_device_t *dev)
771{
772    gralloc_device_t* d = reinterpret_cast<gralloc_device_t*>(dev);
773    if (d) {
774
775        // free still allocated buffers
776        while( d->allocListHead != NULL ) {
777            gralloc_free(&d->device, d->allocListHead->handle);
778        }
779
780        // free device
781        free(d);
782    }
783    return 0;
784}
785
786static int fb_compositionComplete(struct framebuffer_device_t* dev)
787{
788    (void)dev;
789
790    return 0;
791}
792
793//
794// Framebuffer device functions
795//
796static int fb_post(struct framebuffer_device_t* dev, buffer_handle_t buffer)
797{
798    fb_device_t *fbdev = (fb_device_t *)dev;
799    cb_handle_t *cb = (cb_handle_t *)buffer;
800
801    if (!fbdev || !cb_handle_t::validate(cb) || !cb->canBePosted()) {
802        return -EINVAL;
803    }
804
805    // Make sure we have host connection
806    DEFINE_AND_VALIDATE_HOST_CONNECTION;
807
808    // increment the post count of the buffer
809    intptr_t *postCountPtr = (intptr_t *)cb->ashmemBase;
810    if (!postCountPtr) {
811        // This should not happen
812        return -EINVAL;
813    }
814    (*postCountPtr)++;
815
816    // send post request to host
817    rcEnc->rcFBPost(rcEnc, cb->hostHandle);
818    hostCon->flush();
819
820    return 0;
821}
822
823static int fb_setUpdateRect(struct framebuffer_device_t* dev,
824        int l, int t, int w, int h)
825{
826    fb_device_t *fbdev = (fb_device_t *)dev;
827
828    (void)l;
829    (void)t;
830    (void)w;
831    (void)h;
832
833    if (!fbdev) {
834        return -EINVAL;
835    }
836
837    // Make sure we have host connection
838    DEFINE_AND_VALIDATE_HOST_CONNECTION;
839
840    // send request to host
841    // TODO: XXX - should be implemented
842    //rcEnc->rc_XXX
843
844    return 0;
845}
846
847static int fb_setSwapInterval(struct framebuffer_device_t* dev,
848            int interval)
849{
850    fb_device_t *fbdev = (fb_device_t *)dev;
851
852    if (!fbdev) {
853        return -EINVAL;
854    }
855
856    // Make sure we have host connection
857    DEFINE_AND_VALIDATE_HOST_CONNECTION;
858
859    // send request to host
860    rcEnc->rcFBSetSwapInterval(rcEnc, interval);
861    hostCon->flush();
862
863    return 0;
864}
865
866static int fb_close(struct hw_device_t *dev)
867{
868    fb_device_t *fbdev = (fb_device_t *)dev;
869
870    delete fbdev;
871
872    return 0;
873}
874
875
876//
877// gralloc module functions - refcount + locking interface
878//
879static int gralloc_register_buffer(gralloc_module_t const* module,
880                                   buffer_handle_t handle)
881{
882
883    D("%s: start", __FUNCTION__);
884    pthread_once(&sFallbackOnce, fallback_init);
885    if (sFallback != NULL) {
886        return sFallback->registerBuffer(sFallback, handle);
887    }
888
889    D("gralloc_register_buffer(%p) called", handle);
890
891    private_module_t *gr = (private_module_t *)module;
892    cb_handle_t *cb = (cb_handle_t *)handle;
893
894    if (!gr || !cb_handle_t::validate(cb)) {
895        ERR("gralloc_register_buffer(%p): invalid buffer", cb);
896        return -EINVAL;
897    }
898
899    if (cb->hostHandle != 0) {
900        DEFINE_AND_VALIDATE_HOST_CONNECTION;
901        D("Opening host ColorBuffer 0x%x\n", cb->hostHandle);
902        rcEnc->rcOpenColorBuffer2(rcEnc, cb->hostHandle);
903    }
904
905    //
906    // if the color buffer has ashmem region and it is not mapped in this
907    // process map it now.
908    //
909    if (cb->ashmemSize > 0 && cb->mappedPid != getpid()) {
910        void *vaddr;
911        int err = map_buffer(cb, &vaddr);
912        if (err) {
913            ERR("gralloc_register_buffer(%p): map failed: %s", cb, strerror(-err));
914            return -err;
915        }
916        cb->mappedPid = getpid();
917
918        if (isHidlGralloc) {
919            int32_t* openCountPtr = getOpenCountPtr(cb);
920            if (!*openCountPtr) *openCountPtr = 1;
921        }
922
923        DEFINE_AND_VALIDATE_HOST_CONNECTION;
924        if (rcEnc->getDmaVersion() > 0) {
925            init_gralloc_dmaregion();
926            gralloc_dmaregion_register_ashmem(cb->ashmemSize);
927        }
928
929    }
930
931    if (cb->ashmemSize > 0) {
932        GET_ASHMEM_REGION(cb);
933        get_gralloc_dmaregion();
934    }
935
936    return 0;
937}
938
939static int gralloc_unregister_buffer(gralloc_module_t const* module,
940                                     buffer_handle_t handle)
941{
942    if (sFallback != NULL) {
943        return sFallback->unregisterBuffer(sFallback, handle);
944    }
945
946    private_module_t *gr = (private_module_t *)module;
947    cb_handle_t *cb = (cb_handle_t *)handle;
948
949    if (!gr || !cb_handle_t::validate(cb)) {
950        ERR("gralloc_unregister_buffer(%p): invalid buffer", cb);
951        return -EINVAL;
952    }
953
954
955    if (cb->hostHandle) {
956        D("Closing host ColorBuffer 0x%x\n", cb->hostHandle);
957        DEFINE_AND_VALIDATE_HOST_CONNECTION;
958        rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
959
960        if (isHidlGralloc) {
961            // Queue up another rcCloseColorBuffer if applicable.
962            // invariant: have ashmem.
963            if (cb->ashmemSize > 0 && cb->mappedPid == getpid()) {
964                int32_t* openCountPtr = getOpenCountPtr(cb);
965                if (*openCountPtr == -1) {
966                    D("%s: revenge of the rcCloseColorBuffer!", __func__);
967                    rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
968                    *openCountPtr = -2;
969                }
970            }
971        }
972    }
973
974    //
975    // unmap ashmem region if it was previously mapped in this process
976    // (through register_buffer)
977    //
978    if (cb->ashmemSize > 0 && cb->mappedPid == getpid()) {
979
980        PUT_ASHMEM_REGION(cb);
981        put_gralloc_dmaregion();
982
983        if (!SHOULD_UNMAP) goto done;
984
985        DEFINE_AND_VALIDATE_HOST_CONNECTION;
986
987        void *vaddr;
988        int err = munmap((void *)cb->ashmemBase, cb->ashmemSize);
989        if (err) {
990            ERR("gralloc_unregister_buffer(%p): unmap failed", cb);
991            return -EINVAL;
992        }
993        cb->ashmemBase = 0;
994        cb->mappedPid = 0;
995        D("%s: Unregister buffer previous mapped to pid %d", __FUNCTION__, getpid());
996    }
997
998done:
999    D("gralloc_unregister_buffer(%p) done\n", cb);
1000    return 0;
1001}
1002
1003
1004
1005static int gralloc_lock(gralloc_module_t const* module,
1006                        buffer_handle_t handle, int usage,
1007                        int l, int t, int w, int h,
1008                        void** vaddr)
1009{
1010    if (sFallback != NULL) {
1011        return sFallback->lock(sFallback, handle, usage, l, t, w, h, vaddr);
1012    }
1013
1014    private_module_t *gr = (private_module_t *)module;
1015    cb_handle_t *cb = (cb_handle_t *)handle;
1016
1017    if (!gr || !cb_handle_t::validate(cb)) {
1018        ALOGE("gralloc_lock bad handle\n");
1019        return -EINVAL;
1020    }
1021
1022    // Validate usage,
1023    //   1. cannot be locked for hw access
1024    //   2. lock for either sw read or write.
1025    //   3. locked sw access must match usage during alloc time.
1026    bool sw_read = (0 != (usage & GRALLOC_USAGE_SW_READ_MASK));
1027    bool sw_write = (0 != (usage & GRALLOC_USAGE_SW_WRITE_MASK));
1028    bool hw_read = (usage & GRALLOC_USAGE_HW_TEXTURE);
1029    bool hw_write = (usage & GRALLOC_USAGE_HW_RENDER);
1030#if PLATFORM_SDK_VERSION >= 17
1031    bool hw_cam_write = (usage & GRALLOC_USAGE_HW_CAMERA_WRITE);
1032    bool hw_cam_read = (usage & GRALLOC_USAGE_HW_CAMERA_READ);
1033#else // PLATFORM_SDK_VERSION
1034    bool hw_cam_write = false;
1035    bool hw_cam_read = false;
1036#endif // PLATFORM_SDK_VERSION
1037
1038#if PLATFORM_SDK_VERSION >= 15
1039    bool hw_vid_enc_read = (usage & GRALLOC_USAGE_HW_VIDEO_ENCODER);
1040#else // PLATFORM_SDK_VERSION
1041    bool hw_vid_enc_read = false;
1042#endif // PLATFORM_SDK_VERSION
1043
1044    bool sw_read_allowed = (0 != (cb->usage & GRALLOC_USAGE_SW_READ_MASK));
1045
1046#if PLATFORM_SDK_VERSION >= 15
1047    // bug: 30088791
1048    // a buffer was created for GRALLOC_USAGE_HW_VIDEO_ENCODER usage but
1049    // later a software encoder is reading this buffer: this is actually
1050    // legit usage.
1051    sw_read_allowed = sw_read_allowed || (cb->usage & GRALLOC_USAGE_HW_VIDEO_ENCODER);
1052#endif // PLATFORM_SDK_VERSION >= 15
1053
1054    bool sw_write_allowed = (0 != (cb->usage & GRALLOC_USAGE_SW_WRITE_MASK));
1055
1056    if ( (hw_read || hw_write) ||
1057         (!sw_read && !sw_write &&
1058                 !hw_cam_write && !hw_cam_read &&
1059                 !hw_vid_enc_read) ||
1060         (sw_read && !sw_read_allowed) ||
1061         (sw_write && !sw_write_allowed) ) {
1062        ALOGE("gralloc_lock usage mismatch usage=0x%x cb->usage=0x%x\n", usage,
1063                cb->usage);
1064        //This is not exactly an error and loose it up.
1065        //bug: 30784436
1066        //return -EINVAL;
1067    }
1068
1069    intptr_t postCount = 0;
1070    void *cpu_addr = NULL;
1071
1072    //
1073    // make sure ashmem area is mapped if needed
1074    //
1075    if (cb->canBePosted() || sw_read || sw_write ||
1076            hw_cam_write || hw_cam_read ||
1077            hw_vid_enc_read) {
1078        if (cb->ashmemBasePid != getpid() || !cb->ashmemBase) {
1079            return -EACCES;
1080        }
1081
1082        cpu_addr = (void *)(cb->ashmemBase + getAshmemColorOffset(cb));
1083    }
1084
1085    if (cb->hostHandle) {
1086        // Make sure we have host connection
1087        DEFINE_AND_VALIDATE_HOST_CONNECTION;
1088
1089        //
1090        // flush color buffer write cache on host and get its sync status.
1091        //
1092        int hostSyncStatus = rcEnc->rcColorBufferCacheFlush(rcEnc, cb->hostHandle,
1093                                                            postCount,
1094                                                            sw_read);
1095        if (hostSyncStatus < 0) {
1096            // host failed the color buffer sync - probably since it was already
1097            // locked for write access. fail the lock.
1098            ALOGE("gralloc_lock cacheFlush failed postCount=%d sw_read=%d\n",
1099                 postCount, sw_read);
1100            return -EBUSY;
1101        }
1102
1103        if (sw_read) {
1104            void* rgb_addr = cpu_addr;
1105            char* tmpBuf = 0;
1106            if (cb->frameworkFormat == HAL_PIXEL_FORMAT_YV12 ||
1107                cb->frameworkFormat == HAL_PIXEL_FORMAT_YCbCr_420_888) {
1108                // We are using RGB888
1109                tmpBuf = new char[cb->width * cb->height * 3];
1110                rgb_addr = tmpBuf;
1111            }
1112            D("gralloc_lock read back color buffer %d %d ashmem base %p sz %d\n",
1113              cb->width, cb->height, cb->ashmemBase, cb->ashmemSize);
1114            rcEnc->rcReadColorBuffer(rcEnc, cb->hostHandle,
1115                    0, 0, cb->width, cb->height, cb->glFormat, cb->glType, rgb_addr);
1116            if (tmpBuf) {
1117                if (cb->frameworkFormat == HAL_PIXEL_FORMAT_YV12) {
1118                    rgb888_to_yv12((char*)cpu_addr, tmpBuf, cb->width, cb->height, l, t, l+w-1, t+h-1);
1119                } else if (cb->frameworkFormat == HAL_PIXEL_FORMAT_YCbCr_420_888) {
1120                    rgb888_to_yuv420p((char*)cpu_addr, tmpBuf, cb->width, cb->height, l, t, l+w-1, t+h-1);
1121                }
1122                delete [] tmpBuf;
1123            }
1124        }
1125    }
1126
1127    //
1128    // is virtual address required ?
1129    //
1130    if (sw_read || sw_write || hw_cam_write || hw_cam_read || hw_vid_enc_read) {
1131        *vaddr = cpu_addr;
1132    }
1133
1134    if (sw_write || hw_cam_write) {
1135        //
1136        // Keep locked region if locked for s/w write access.
1137        //
1138        cb->lockedLeft = l;
1139        cb->lockedTop = t;
1140        cb->lockedWidth = w;
1141        cb->lockedHeight = h;
1142    }
1143
1144    DD("gralloc_lock success. vaddr: %p, *vaddr: %p, usage: %x, cpu_addr: %p",
1145            vaddr, vaddr ? *vaddr : 0, usage, cpu_addr);
1146
1147    return 0;
1148}
1149
1150static int gralloc_unlock(gralloc_module_t const* module,
1151                          buffer_handle_t handle)
1152{
1153    if (sFallback != NULL) {
1154        return sFallback->unlock(sFallback, handle);
1155    }
1156
1157    private_module_t *gr = (private_module_t *)module;
1158    cb_handle_t *cb = (cb_handle_t *)handle;
1159
1160    if (!gr || !cb_handle_t::validate(cb)) {
1161        ALOGD("%s: invalid gr or cb handle. -EINVAL", __FUNCTION__);
1162        return -EINVAL;
1163    }
1164
1165    //
1166    // if buffer was locked for s/w write, we need to update the host with
1167    // the updated data
1168    //
1169    if (cb->hostHandle) {
1170
1171        // Make sure we have host connection
1172        DEFINE_AND_VALIDATE_HOST_CONNECTION;
1173
1174        void *cpu_addr = (void *)(cb->ashmemBase + getAshmemColorOffset(cb));
1175
1176        char* rgb_addr = (char *)cpu_addr;
1177        if (cb->lockedWidth < cb->width || cb->lockedHeight < cb->height) {
1178            updateHostColorBuffer(cb, true, rgb_addr);
1179        }
1180        else {
1181            updateHostColorBuffer(cb, false, rgb_addr);
1182        }
1183
1184        DD("gralloc_unlock success. cpu_addr: %p", cpu_addr);
1185    }
1186
1187    cb->lockedWidth = cb->lockedHeight = 0;
1188    return 0;
1189}
1190
1191#if PLATFORM_SDK_VERSION >= 18
1192static int gralloc_lock_ycbcr(gralloc_module_t const* module,
1193                        buffer_handle_t handle, int usage,
1194                        int l, int t, int w, int h,
1195                        android_ycbcr *ycbcr)
1196{
1197    // Not supporting fallback module for YCbCr
1198    if (sFallback != NULL) {
1199        ALOGD("%s: has fallback, return -EINVAL", __FUNCTION__);
1200        return -EINVAL;
1201    }
1202
1203    if (!ycbcr) {
1204        ALOGE("%s: got NULL ycbcr struct! -EINVAL", __FUNCTION__);
1205        return -EINVAL;
1206    }
1207
1208    private_module_t *gr = (private_module_t *)module;
1209    cb_handle_t *cb = (cb_handle_t *)handle;
1210    if (!gr || !cb_handle_t::validate(cb)) {
1211        ALOGE("%s: bad colorbuffer handle. -EINVAL", __FUNCTION__);
1212        return -EINVAL;
1213    }
1214
1215    if (cb->frameworkFormat != HAL_PIXEL_FORMAT_YV12 &&
1216        cb->frameworkFormat != HAL_PIXEL_FORMAT_YCbCr_420_888) {
1217        ALOGE("gralloc_lock_ycbcr can only be used with "
1218                "HAL_PIXEL_FORMAT_YCbCr_420_888 or HAL_PIXEL_FORMAT_YV12, got %x instead. "
1219                "-EINVAL",
1220                cb->frameworkFormat);
1221        return -EINVAL;
1222    }
1223
1224    // Make sure memory is mapped, get address
1225    if (cb->ashmemBasePid != getpid() || !cb->ashmemBase) {
1226        ALOGD("%s: ashmembase not mapped. -EACCESS", __FUNCTION__);
1227        return -EACCES;
1228    }
1229
1230    uint8_t *cpu_addr = NULL;
1231    cpu_addr = (uint8_t *)(cb->ashmemBase) + getAshmemColorOffset(cb);
1232
1233    // Calculate offsets to underlying YUV data
1234    size_t yStride;
1235    size_t cStride;
1236    size_t cSize;
1237    size_t yOffset;
1238    size_t uOffset;
1239    size_t vOffset;
1240    size_t cStep;
1241    size_t align;
1242    switch (cb->format) {
1243        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
1244            yStride = cb->width;
1245            cStride = cb->width;
1246            yOffset = 0;
1247            vOffset = yStride * cb->height;
1248            uOffset = vOffset + 1;
1249            cStep = 2;
1250            break;
1251        case HAL_PIXEL_FORMAT_YV12:
1252            // https://developer.android.com/reference/android/graphics/ImageFormat.html#YV12
1253            align = 16;
1254            yStride = (cb->width + (align -1)) & ~(align-1);
1255            cStride = (yStride / 2 + (align - 1)) & ~(align-1);
1256            yOffset = 0;
1257            cSize = cStride * cb->height/2;
1258            vOffset = yStride * cb->height;
1259            uOffset = vOffset + cSize;
1260            cStep = 1;
1261            break;
1262        case HAL_PIXEL_FORMAT_YCbCr_420_888:
1263            align = 1;
1264            yStride = cb->width;
1265            cStride = yStride / 2;
1266            yOffset = 0;
1267            cSize = cStride * cb->height/2;
1268            uOffset = yStride * cb->height;
1269            vOffset = uOffset + cSize;
1270            cStep = 1;
1271            break;
1272        default:
1273            ALOGE("gralloc_lock_ycbcr unexpected internal format %x",
1274                    cb->format);
1275            return -EINVAL;
1276    }
1277
1278    ycbcr->y = cpu_addr + yOffset;
1279    ycbcr->cb = cpu_addr + uOffset;
1280    ycbcr->cr = cpu_addr + vOffset;
1281    ycbcr->ystride = yStride;
1282    ycbcr->cstride = cStride;
1283    ycbcr->chroma_step = cStep;
1284
1285    // Zero out reserved fields
1286    memset(ycbcr->reserved, 0, sizeof(ycbcr->reserved));
1287
1288    //
1289    // Keep locked region if locked for s/w write access.
1290    //
1291    cb->lockedLeft = l;
1292    cb->lockedTop = t;
1293    cb->lockedWidth = w;
1294    cb->lockedHeight = h;
1295
1296    DD("gralloc_lock_ycbcr success. usage: %x, ycbcr.y: %p, .cb: %p, .cr: %p, "
1297            ".ystride: %d , .cstride: %d, .chroma_step: %d", usage,
1298            ycbcr->y, ycbcr->cb, ycbcr->cr, ycbcr->ystride, ycbcr->cstride,
1299            ycbcr->chroma_step);
1300
1301    return 0;
1302}
1303#endif // PLATFORM_SDK_VERSION >= 18
1304
1305static int gralloc_device_open(const hw_module_t* module,
1306                               const char* name,
1307                               hw_device_t** device)
1308{
1309    int status = -EINVAL;
1310
1311    D("gralloc_device_open %s\n", name);
1312
1313    pthread_once( &sFallbackOnce, fallback_init );
1314    if (sFallback != NULL) {
1315        return sFallback->common.methods->open(&sFallback->common, name, device);
1316    }
1317
1318    if (!strcmp(name, GRALLOC_HARDWARE_GPU0)) {
1319
1320        // Create host connection and keep it in the TLS.
1321        // return error if connection with host can not be established
1322        HostConnection *hostCon = HostConnection::get();
1323        if (!hostCon) {
1324            ALOGE("gralloc: failed to get host connection while opening %s\n", name);
1325            return -EIO;
1326        }
1327
1328        //
1329        // Allocate memory for the gralloc device (alloc interface)
1330        //
1331        gralloc_device_t *dev;
1332        dev = (gralloc_device_t*)malloc(sizeof(gralloc_device_t));
1333        if (NULL == dev) {
1334            return -ENOMEM;
1335        }
1336        memset(dev, 0, sizeof(gralloc_device_t));
1337
1338        // Initialize our device structure
1339        //
1340        dev->device.common.tag = HARDWARE_DEVICE_TAG;
1341        dev->device.common.version = 0;
1342        dev->device.common.module = const_cast<hw_module_t*>(module);
1343        dev->device.common.close = gralloc_device_close;
1344
1345        dev->device.alloc   = gralloc_alloc;
1346        dev->device.free    = gralloc_free;
1347        dev->allocListHead  = NULL;
1348        pthread_mutex_init(&dev->lock, NULL);
1349
1350        *device = &dev->device.common;
1351        status = 0;
1352    }
1353    else if (!strcmp(name, GRALLOC_HARDWARE_FB0)) {
1354
1355        // return error if connection with host can not be established
1356        DEFINE_AND_VALIDATE_HOST_CONNECTION;
1357
1358        //
1359        // Query the host for Framebuffer attributes
1360        //
1361        D("gralloc: query Frabuffer attribs\n");
1362        EGLint width = rcEnc->rcGetFBParam(rcEnc, FB_WIDTH);
1363        D("gralloc: width=%d\n", width);
1364        EGLint height = rcEnc->rcGetFBParam(rcEnc, FB_HEIGHT);
1365        D("gralloc: height=%d\n", height);
1366        EGLint xdpi = rcEnc->rcGetFBParam(rcEnc, FB_XDPI);
1367        D("gralloc: xdpi=%d\n", xdpi);
1368        EGLint ydpi = rcEnc->rcGetFBParam(rcEnc, FB_YDPI);
1369        D("gralloc: ydpi=%d\n", ydpi);
1370        EGLint fps = rcEnc->rcGetFBParam(rcEnc, FB_FPS);
1371        D("gralloc: fps=%d\n", fps);
1372        EGLint min_si = rcEnc->rcGetFBParam(rcEnc, FB_MIN_SWAP_INTERVAL);
1373        D("gralloc: min_swap=%d\n", min_si);
1374        EGLint max_si = rcEnc->rcGetFBParam(rcEnc, FB_MAX_SWAP_INTERVAL);
1375        D("gralloc: max_swap=%d\n", max_si);
1376
1377        //
1378        // Allocate memory for the framebuffer device
1379        //
1380        fb_device_t *dev;
1381        dev = (fb_device_t*)malloc(sizeof(fb_device_t));
1382        if (NULL == dev) {
1383            return -ENOMEM;
1384        }
1385        memset(dev, 0, sizeof(fb_device_t));
1386
1387        // Initialize our device structure
1388        //
1389        dev->device.common.tag = HARDWARE_DEVICE_TAG;
1390        dev->device.common.version = 0;
1391        dev->device.common.module = const_cast<hw_module_t*>(module);
1392        dev->device.common.close = fb_close;
1393        dev->device.setSwapInterval = fb_setSwapInterval;
1394        dev->device.post            = fb_post;
1395        dev->device.setUpdateRect   = 0; //fb_setUpdateRect;
1396        dev->device.compositionComplete = fb_compositionComplete; //XXX: this is a dummy
1397
1398        const_cast<uint32_t&>(dev->device.flags) = 0;
1399        const_cast<uint32_t&>(dev->device.width) = width;
1400        const_cast<uint32_t&>(dev->device.height) = height;
1401        const_cast<int&>(dev->device.stride) = width;
1402        const_cast<int&>(dev->device.format) = HAL_PIXEL_FORMAT_RGBA_8888;
1403        const_cast<float&>(dev->device.xdpi) = xdpi;
1404        const_cast<float&>(dev->device.ydpi) = ydpi;
1405        const_cast<float&>(dev->device.fps) = fps;
1406        const_cast<int&>(dev->device.minSwapInterval) = min_si;
1407        const_cast<int&>(dev->device.maxSwapInterval) = max_si;
1408        *device = &dev->device.common;
1409
1410        status = 0;
1411    }
1412
1413    return status;
1414}
1415
1416//
1417// define the HMI symbol - our module interface
1418//
1419static struct hw_module_methods_t gralloc_module_methods = {
1420        open: gralloc_device_open
1421};
1422
1423struct private_module_t HAL_MODULE_INFO_SYM = {
1424    base: {
1425        common: {
1426            tag: HARDWARE_MODULE_TAG,
1427#if PLATFORM_SDK_VERSION >= 18
1428            module_api_version: GRALLOC_MODULE_API_VERSION_0_2,
1429            hal_api_version: 0,
1430#elif PLATFORM_SDK_VERSION >= 16
1431            module_api_version: 1,
1432            hal_api_version: 0,
1433#else // PLATFORM_SDK_VERSION
1434            version_major: 1,
1435            version_minor: 0,
1436#endif // PLATFORM_SDK_VERSION
1437            id: GRALLOC_HARDWARE_MODULE_ID,
1438            name: "Graphics Memory Allocator Module",
1439            author: "The Android Open Source Project",
1440            methods: &gralloc_module_methods,
1441            dso: NULL,
1442            reserved: {0, }
1443        },
1444        registerBuffer: gralloc_register_buffer,
1445        unregisterBuffer: gralloc_unregister_buffer,
1446        lock: gralloc_lock,
1447        unlock: gralloc_unlock,
1448        perform: NULL,
1449#if PLATFORM_SDK_VERSION >= 18
1450        lock_ycbcr: gralloc_lock_ycbcr,
1451#endif // PLATFORM_SDK_VERSION >= 18
1452    }
1453};
1454
1455/* This function is called once to detect whether the emulator supports
1456 * GPU emulation (this is done by looking at the qemu.gles kernel
1457 * parameter, which must be == 1 if this is the case).
1458 *
1459 * If not, then load gralloc.default instead as a fallback.
1460 */
1461static void
1462fallback_init(void)
1463{
1464    char  prop[PROPERTY_VALUE_MAX];
1465    void* module;
1466
1467    // qemu.gles=0 -> no GLES 2.x support (only 1.x through software).
1468    // qemu.gles=1 -> host-side GPU emulation through EmuGL
1469    // qemu.gles=2 -> guest-side GPU emulation.
1470    property_get("ro.kernel.qemu.gles", prop, "0");
1471    if (atoi(prop) == 1) {
1472        return;
1473    }
1474    ALOGD("Emulator without host-side GPU emulation detected.");
1475#if __LP64__
1476    module = dlopen("/vendor/lib64/hw/gralloc.default.so", RTLD_LAZY|RTLD_LOCAL);
1477#else
1478    module = dlopen("/vendor/lib/hw/gralloc.default.so", RTLD_LAZY|RTLD_LOCAL);
1479#endif
1480    if (module != NULL) {
1481        sFallback = reinterpret_cast<gralloc_module_t*>(dlsym(module, HAL_MODULE_INFO_SYM_AS_STR));
1482        if (sFallback == NULL) {
1483            dlclose(module);
1484        }
1485    }
1486    if (sFallback == NULL) {
1487        ALOGE("Could not find software fallback module!?");
1488    }
1489}
1490