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#ifdef HAVE_ANDROID_OS      // just want PAGE_SIZE define
19# include <asm/page.h>
20#else
21# include <sys/user.h>
22#endif
23#include <cutils/ashmem.h>
24#include <unistd.h>
25#include <errno.h>
26#include <dlfcn.h>
27#include <sys/mman.h>
28#include "gralloc_cb.h"
29#include "HostConnection.h"
30#include "glUtils.h"
31#include <cutils/log.h>
32#include <cutils/properties.h>
33
34/* Set to 1 or 2 to enable debug traces */
35#define DEBUG  0
36
37#if DEBUG >= 1
38#  define D(...)   ALOGD(__VA_ARGS__)
39#else
40#  define D(...)   ((void)0)
41#endif
42
43#if DEBUG >= 2
44#  define DD(...)  ALOGD(__VA_ARGS__)
45#else
46#  define DD(...)  ((void)0)
47#endif
48
49#define DBG_FUNC DBG("%s\n", __FUNCTION__)
50//
51// our private gralloc module structure
52//
53struct private_module_t {
54    gralloc_module_t base;
55};
56
57/* If not NULL, this is a pointer to the fallback module.
58 * This really is gralloc.default, which we'll use if we detect
59 * that the emulator we're running in does not support GPU emulation.
60 */
61static gralloc_module_t*  sFallback;
62static pthread_once_t     sFallbackOnce = PTHREAD_ONCE_INIT;
63
64static void fallback_init(void);  // forward
65
66
67typedef struct _alloc_list_node {
68    buffer_handle_t handle;
69    _alloc_list_node *next;
70    _alloc_list_node *prev;
71} AllocListNode;
72
73//
74// Our gralloc device structure (alloc interface)
75//
76struct gralloc_device_t {
77    alloc_device_t  device;
78
79    AllocListNode *allocListHead;    // double linked list of allocated buffers
80    pthread_mutex_t lock;
81};
82
83//
84// Our framebuffer device structure
85//
86struct fb_device_t {
87    framebuffer_device_t  device;
88};
89
90static int map_buffer(cb_handle_t *cb, void **vaddr)
91{
92    if (cb->fd < 0 || cb->ashmemSize <= 0) {
93        return -EINVAL;
94    }
95
96    void *addr = mmap(0, cb->ashmemSize, PROT_READ | PROT_WRITE,
97                      MAP_SHARED, cb->fd, 0);
98    if (addr == MAP_FAILED) {
99        return -errno;
100    }
101
102    cb->ashmemBase = intptr_t(addr);
103    cb->ashmemBasePid = getpid();
104
105    *vaddr = addr;
106    return 0;
107}
108
109#define DEFINE_HOST_CONNECTION \
110    HostConnection *hostCon = HostConnection::get(); \
111    renderControl_encoder_context_t *rcEnc = (hostCon ? hostCon->rcEncoder() : NULL)
112
113#define DEFINE_AND_VALIDATE_HOST_CONNECTION \
114    HostConnection *hostCon = HostConnection::get(); \
115    if (!hostCon) { \
116        ALOGE("gralloc: Failed to get host connection\n"); \
117        return -EIO; \
118    } \
119    renderControl_encoder_context_t *rcEnc = hostCon->rcEncoder(); \
120    if (!rcEnc) { \
121        ALOGE("gralloc: Failed to get renderControl encoder context\n"); \
122        return -EIO; \
123    }
124
125
126//
127// gralloc device functions (alloc interface)
128//
129static int gralloc_alloc(alloc_device_t* dev,
130                         int w, int h, int format, int usage,
131                         buffer_handle_t* pHandle, int* pStride)
132{
133    D("gralloc_alloc w=%d h=%d usage=0x%x\n", w, h, usage);
134
135    gralloc_device_t *grdev = (gralloc_device_t *)dev;
136    if (!grdev || !pHandle || !pStride) {
137        ALOGE("gralloc_alloc: Bad inputs (grdev: %p, pHandle: %p, pStride: %p",
138                grdev, pHandle, pStride);
139        return -EINVAL;
140    }
141
142    //
143    // Validate usage: buffer cannot be written both by s/w and h/w access.
144    //
145    bool sw_write = (0 != (usage & GRALLOC_USAGE_SW_WRITE_MASK));
146    bool hw_write = (usage & GRALLOC_USAGE_HW_RENDER);
147    if (hw_write && sw_write) {
148        ALOGE("gralloc_alloc: Mismatched usage flags: %d x %d, usage %x",
149                w, h, usage);
150        return -EINVAL;
151    }
152    bool sw_read = (0 != (usage & GRALLOC_USAGE_SW_READ_MASK));
153    bool hw_cam_write = usage & GRALLOC_USAGE_HW_CAMERA_WRITE;
154    bool hw_cam_read = usage & GRALLOC_USAGE_HW_CAMERA_READ;
155    bool hw_vid_enc_read = usage & GRALLOC_USAGE_HW_VIDEO_ENCODER;
156
157    // Pick the right concrete pixel format given the endpoints as encoded in
158    // the usage bits.  Every end-point pair needs explicit listing here.
159    if (format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
160        // Camera as producer
161        if (usage & GRALLOC_USAGE_HW_CAMERA_WRITE) {
162            if (usage & GRALLOC_USAGE_HW_TEXTURE) {
163                // Camera-to-display is RGBA
164                format = HAL_PIXEL_FORMAT_RGBA_8888;
165            } else if (usage & GRALLOC_USAGE_HW_VIDEO_ENCODER) {
166                // Camera-to-encoder is NV21
167                format = HAL_PIXEL_FORMAT_YCrCb_420_SP;
168            } else if ((usage & GRALLOC_USAGE_HW_CAMERA_MASK) ==
169                    GRALLOC_USAGE_HW_CAMERA_ZSL) {
170                // Camera-to-ZSL-queue is RGB_888
171                format = HAL_PIXEL_FORMAT_RGB_888;
172            }
173        }
174
175        if (format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
176            ALOGE("gralloc_alloc: Requested auto format selection, "
177                    "but no known format for this usage: %d x %d, usage %x",
178                    w, h, usage);
179            return -EINVAL;
180        }
181    }
182
183    bool yuv_format = false;
184
185    int ashmem_size = 0;
186    int stride = w;
187
188    GLenum glFormat = 0;
189    GLenum glType = 0;
190
191    int bpp = 0;
192    int align = 1;
193    switch (format) {
194        case HAL_PIXEL_FORMAT_RGBA_8888:
195        case HAL_PIXEL_FORMAT_RGBX_8888:
196        case HAL_PIXEL_FORMAT_BGRA_8888:
197            bpp = 4;
198            glFormat = GL_RGBA;
199            glType = GL_UNSIGNED_BYTE;
200            break;
201        case HAL_PIXEL_FORMAT_RGB_888:
202            bpp = 3;
203            glFormat = GL_RGB;
204            glType = GL_UNSIGNED_BYTE;
205            break;
206        case HAL_PIXEL_FORMAT_RGB_565:
207            bpp = 2;
208            glFormat = GL_RGB;
209            glType = GL_UNSIGNED_SHORT_5_6_5;
210            break;
211        case HAL_PIXEL_FORMAT_RGBA_5551:
212            bpp = 2;
213            glFormat = GL_RGB5_A1_OES;
214            glType = GL_UNSIGNED_SHORT_5_5_5_1;
215            break;
216        case HAL_PIXEL_FORMAT_RGBA_4444:
217            bpp = 2;
218            glFormat = GL_RGBA4_OES;
219            glType = GL_UNSIGNED_SHORT_4_4_4_4;
220            break;
221        case HAL_PIXEL_FORMAT_RAW_SENSOR:
222            bpp = 2;
223            align = 16*bpp;
224            if (! ((sw_read || hw_cam_read) && (sw_write || hw_cam_write) ) ) {
225                // Raw sensor data only goes between camera and CPU
226                return -EINVAL;
227            }
228            // Not expecting to actually create any GL surfaces for this
229            glFormat = GL_LUMINANCE;
230            glType = GL_UNSIGNED_SHORT;
231            break;
232        case HAL_PIXEL_FORMAT_BLOB:
233            bpp = 1;
234            if (! (sw_read && hw_cam_write) ) {
235                // Blob data cannot be used by HW other than camera emulator
236                return -EINVAL;
237            }
238            // Not expecting to actually create any GL surfaces for this
239            glFormat = GL_LUMINANCE;
240            glType = GL_UNSIGNED_BYTE;
241            break;
242        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
243            align = 1;
244            bpp = 1; // per-channel bpp
245            yuv_format = true;
246            // Not expecting to actually create any GL surfaces for this
247            break;
248        case HAL_PIXEL_FORMAT_YV12:
249            align = 16;
250            bpp = 1; // per-channel bpp
251            yuv_format = true;
252            // Not expecting to actually create any GL surfaces for this
253            break;
254        default:
255            ALOGE("gralloc_alloc: Unknown format %d", format);
256            return -EINVAL;
257    }
258
259    if (usage & GRALLOC_USAGE_HW_FB) {
260        // keep space for postCounter
261        ashmem_size += sizeof(uint32_t);
262    }
263
264    if (sw_read || sw_write || hw_cam_write || hw_vid_enc_read) {
265        // keep space for image on guest memory if SW access is needed
266        // or if the camera is doing writing
267        if (yuv_format) {
268            size_t yStride = (w*bpp + (align - 1)) & ~(align-1);
269            size_t uvStride = (yStride / 2 + (align - 1)) & ~(align-1);
270            size_t uvHeight = h / 2;
271            ashmem_size += yStride * h + 2 * (uvHeight * uvStride);
272            stride = yStride / bpp;
273        } else {
274            size_t bpr = (w*bpp + (align-1)) & ~(align-1);
275            ashmem_size += (bpr * h);
276            stride = bpr / bpp;
277        }
278    }
279
280    D("gralloc_alloc format=%d, ashmem_size=%d, stride=%d, tid %d\n", format,
281            ashmem_size, stride, gettid());
282
283    //
284    // Allocate space in ashmem if needed
285    //
286    int fd = -1;
287    if (ashmem_size > 0) {
288        // round to page size;
289        ashmem_size = (ashmem_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
290
291        fd = ashmem_create_region("gralloc-buffer", ashmem_size);
292        if (fd < 0) {
293            ALOGE("gralloc_alloc failed to create ashmem region: %s\n",
294                    strerror(errno));
295            return -errno;
296        }
297    }
298
299    cb_handle_t *cb = new cb_handle_t(fd, ashmem_size, usage,
300                                      w, h, format, glFormat, glType);
301
302    if (ashmem_size > 0) {
303        //
304        // map ashmem region if exist
305        //
306        void *vaddr;
307        int err = map_buffer(cb, &vaddr);
308        if (err) {
309            close(fd);
310            delete cb;
311            return err;
312        }
313
314        cb->setFd(fd);
315    }
316
317    //
318    // Allocate ColorBuffer handle on the host (only if h/w access is allowed)
319    // Only do this for some h/w usages, not all.
320    //
321    if (usage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
322                    GRALLOC_USAGE_HW_2D | GRALLOC_USAGE_HW_COMPOSER |
323                    GRALLOC_USAGE_HW_FB) ) {
324        DEFINE_HOST_CONNECTION;
325        if (hostCon && rcEnc) {
326            cb->hostHandle = rcEnc->rcCreateColorBuffer(rcEnc, w, h, glFormat);
327            D("Created host ColorBuffer 0x%x\n", cb->hostHandle);
328        }
329
330        if (!cb->hostHandle) {
331           // Could not create colorbuffer on host !!!
332           close(fd);
333           delete cb;
334           return -EIO;
335        }
336    }
337
338    //
339    // alloc succeeded - insert the allocated handle to the allocated list
340    //
341    AllocListNode *node = new AllocListNode();
342    pthread_mutex_lock(&grdev->lock);
343    node->handle = cb;
344    node->next =  grdev->allocListHead;
345    node->prev =  NULL;
346    if (grdev->allocListHead) {
347        grdev->allocListHead->prev = node;
348    }
349    grdev->allocListHead = node;
350    pthread_mutex_unlock(&grdev->lock);
351
352    *pHandle = cb;
353    *pStride = stride;
354    return 0;
355}
356
357static int gralloc_free(alloc_device_t* dev,
358                        buffer_handle_t handle)
359{
360    const cb_handle_t *cb = (const cb_handle_t *)handle;
361    if (!cb_handle_t::validate((cb_handle_t*)cb)) {
362        ERR("gralloc_free: invalid handle");
363        return -EINVAL;
364    }
365
366    if (cb->hostHandle != 0) {
367        DEFINE_AND_VALIDATE_HOST_CONNECTION;
368        D("Closing host ColorBuffer 0x%x\n", cb->hostHandle);
369        rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
370    }
371
372    //
373    // detach and unmap ashmem area if present
374    //
375    if (cb->fd > 0) {
376        if (cb->ashmemSize > 0 && cb->ashmemBase) {
377            munmap((void *)cb->ashmemBase, cb->ashmemSize);
378        }
379        close(cb->fd);
380    }
381
382    // remove it from the allocated list
383    gralloc_device_t *grdev = (gralloc_device_t *)dev;
384    pthread_mutex_lock(&grdev->lock);
385    AllocListNode *n = grdev->allocListHead;
386    while( n && n->handle != cb ) {
387        n = n->next;
388    }
389    if (n) {
390       // buffer found on list - remove it from list
391       if (n->next) {
392           n->next->prev = n->prev;
393       }
394       if (n->prev) {
395           n->prev->next = n->next;
396       }
397       else {
398           grdev->allocListHead = n->next;
399       }
400
401       delete n;
402    }
403    pthread_mutex_unlock(&grdev->lock);
404
405    delete cb;
406
407    return 0;
408}
409
410static int gralloc_device_close(struct hw_device_t *dev)
411{
412    gralloc_device_t* d = reinterpret_cast<gralloc_device_t*>(dev);
413    if (d) {
414
415        // free still allocated buffers
416        while( d->allocListHead != NULL ) {
417            gralloc_free(&d->device, d->allocListHead->handle);
418        }
419
420        // free device
421        free(d);
422    }
423    return 0;
424}
425
426static int fb_compositionComplete(struct framebuffer_device_t* dev)
427{
428    return 0;
429}
430
431//
432// Framebuffer device functions
433//
434static int fb_post(struct framebuffer_device_t* dev, buffer_handle_t buffer)
435{
436    fb_device_t *fbdev = (fb_device_t *)dev;
437    cb_handle_t *cb = (cb_handle_t *)buffer;
438
439    if (!fbdev || !cb_handle_t::validate(cb) || !cb->canBePosted()) {
440        return -EINVAL;
441    }
442
443    // Make sure we have host connection
444    DEFINE_AND_VALIDATE_HOST_CONNECTION;
445
446    // increment the post count of the buffer
447    uint32_t *postCountPtr = (uint32_t *)cb->ashmemBase;
448    if (!postCountPtr) {
449        // This should not happen
450        return -EINVAL;
451    }
452    (*postCountPtr)++;
453
454    // send post request to host
455    rcEnc->rcFBPost(rcEnc, cb->hostHandle);
456    hostCon->flush();
457
458    return 0;
459}
460
461static int fb_setUpdateRect(struct framebuffer_device_t* dev,
462        int l, int t, int w, int h)
463{
464    fb_device_t *fbdev = (fb_device_t *)dev;
465
466    if (!fbdev) {
467        return -EINVAL;
468    }
469
470    // Make sure we have host connection
471    DEFINE_AND_VALIDATE_HOST_CONNECTION;
472
473    // send request to host
474    // TODO: XXX - should be implemented
475    //rcEnc->rc_XXX
476
477    return 0;
478}
479
480static int fb_setSwapInterval(struct framebuffer_device_t* dev,
481            int interval)
482{
483    fb_device_t *fbdev = (fb_device_t *)dev;
484
485    if (!fbdev) {
486        return -EINVAL;
487    }
488
489    // Make sure we have host connection
490    DEFINE_AND_VALIDATE_HOST_CONNECTION;
491
492    // send request to host
493    rcEnc->rcFBSetSwapInterval(rcEnc, interval);
494    hostCon->flush();
495
496    return 0;
497}
498
499static int fb_close(struct hw_device_t *dev)
500{
501    fb_device_t *fbdev = (fb_device_t *)dev;
502
503    delete fbdev;
504
505    return 0;
506}
507
508
509//
510// gralloc module functions - refcount + locking interface
511//
512static int gralloc_register_buffer(gralloc_module_t const* module,
513                                   buffer_handle_t handle)
514{
515    pthread_once(&sFallbackOnce, fallback_init);
516    if (sFallback != NULL) {
517        return sFallback->registerBuffer(sFallback, handle);
518    }
519
520    D("gralloc_register_buffer(%p) called", handle);
521
522    private_module_t *gr = (private_module_t *)module;
523    cb_handle_t *cb = (cb_handle_t *)handle;
524    if (!gr || !cb_handle_t::validate(cb)) {
525        ERR("gralloc_register_buffer(%p): invalid buffer", cb);
526        return -EINVAL;
527    }
528
529    if (cb->hostHandle != 0) {
530        DEFINE_AND_VALIDATE_HOST_CONNECTION;
531        D("Opening host ColorBuffer 0x%x\n", cb->hostHandle);
532        rcEnc->rcOpenColorBuffer(rcEnc, cb->hostHandle);
533    }
534
535    //
536    // if the color buffer has ashmem region and it is not mapped in this
537    // process map it now.
538    //
539    if (cb->ashmemSize > 0 && cb->mappedPid != getpid()) {
540        void *vaddr;
541        int err = map_buffer(cb, &vaddr);
542        if (err) {
543            ERR("gralloc_register_buffer(%p): map failed: %s", cb, strerror(-err));
544            return -err;
545        }
546        cb->mappedPid = getpid();
547    }
548
549    return 0;
550}
551
552static int gralloc_unregister_buffer(gralloc_module_t const* module,
553                                     buffer_handle_t handle)
554{
555    if (sFallback != NULL) {
556        return sFallback->unregisterBuffer(sFallback, handle);
557    }
558
559    private_module_t *gr = (private_module_t *)module;
560    cb_handle_t *cb = (cb_handle_t *)handle;
561    if (!gr || !cb_handle_t::validate(cb)) {
562        ERR("gralloc_unregister_buffer(%p): invalid buffer", cb);
563        return -EINVAL;
564    }
565
566    if (cb->hostHandle != 0) {
567        DEFINE_AND_VALIDATE_HOST_CONNECTION;
568        D("Closing host ColorBuffer 0x%x\n", cb->hostHandle);
569        rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
570    }
571
572    //
573    // unmap ashmem region if it was previously mapped in this process
574    // (through register_buffer)
575    //
576    if (cb->ashmemSize > 0 && cb->mappedPid == getpid()) {
577        void *vaddr;
578        int err = munmap((void *)cb->ashmemBase, cb->ashmemSize);
579        if (err) {
580            ERR("gralloc_unregister_buffer(%p): unmap failed", cb);
581            return -EINVAL;
582        }
583        cb->ashmemBase = NULL;
584        cb->mappedPid = 0;
585    }
586
587    D("gralloc_unregister_buffer(%p) done\n", cb);
588
589    return 0;
590}
591
592static int gralloc_lock(gralloc_module_t const* module,
593                        buffer_handle_t handle, int usage,
594                        int l, int t, int w, int h,
595                        void** vaddr)
596{
597    if (sFallback != NULL) {
598        return sFallback->lock(sFallback, handle, usage, l, t, w, h, vaddr);
599    }
600
601    private_module_t *gr = (private_module_t *)module;
602    cb_handle_t *cb = (cb_handle_t *)handle;
603    if (!gr || !cb_handle_t::validate(cb)) {
604        ALOGE("gralloc_lock bad handle\n");
605        return -EINVAL;
606    }
607
608    // Validate usage,
609    //   1. cannot be locked for hw access
610    //   2. lock for either sw read or write.
611    //   3. locked sw access must match usage during alloc time.
612    bool sw_read = (0 != (usage & GRALLOC_USAGE_SW_READ_MASK));
613    bool sw_write = (0 != (usage & GRALLOC_USAGE_SW_WRITE_MASK));
614    bool hw_read = (usage & GRALLOC_USAGE_HW_TEXTURE);
615    bool hw_write = (usage & GRALLOC_USAGE_HW_RENDER);
616    bool hw_vid_enc_read = (usage & GRALLOC_USAGE_HW_VIDEO_ENCODER);
617    bool hw_cam_write = (usage & GRALLOC_USAGE_HW_CAMERA_WRITE);
618    bool hw_cam_read = (usage & GRALLOC_USAGE_HW_CAMERA_READ);
619    bool sw_read_allowed = (0 != (cb->usage & GRALLOC_USAGE_SW_READ_MASK));
620    bool sw_write_allowed = (0 != (cb->usage & GRALLOC_USAGE_SW_WRITE_MASK));
621
622    if ( (hw_read || hw_write) ||
623         (!sw_read && !sw_write &&
624                 !hw_cam_write && !hw_cam_read &&
625                 !hw_vid_enc_read) ||
626         (sw_read && !sw_read_allowed) ||
627         (sw_write && !sw_write_allowed) ) {
628        ALOGE("gralloc_lock usage mismatch usage=0x%x cb->usage=0x%x\n", usage,
629                cb->usage);
630        return -EINVAL;
631    }
632
633    EGLint postCount = 0;
634    void *cpu_addr = NULL;
635
636    //
637    // make sure ashmem area is mapped if needed
638    //
639    if (cb->canBePosted() || sw_read || sw_write ||
640            hw_cam_write || hw_cam_read ||
641            hw_vid_enc_read) {
642        if (cb->ashmemBasePid != getpid() || !cb->ashmemBase) {
643            return -EACCES;
644        }
645
646        if (cb->canBePosted()) {
647            postCount = *((int *)cb->ashmemBase);
648            cpu_addr = (void *)(cb->ashmemBase + sizeof(int));
649        }
650        else {
651            cpu_addr = (void *)(cb->ashmemBase);
652        }
653    }
654
655    if (cb->hostHandle) {
656        // Make sure we have host connection
657        DEFINE_AND_VALIDATE_HOST_CONNECTION;
658
659        //
660        // flush color buffer write cache on host and get its sync status.
661        //
662        int hostSyncStatus = rcEnc->rcColorBufferCacheFlush(rcEnc, cb->hostHandle,
663                                                            postCount,
664                                                            sw_read);
665        if (hostSyncStatus < 0) {
666            // host failed the color buffer sync - probably since it was already
667            // locked for write access. fail the lock.
668            ALOGE("gralloc_lock cacheFlush failed postCount=%d sw_read=%d\n",
669                 postCount, sw_read);
670            return -EBUSY;
671        }
672
673    }
674
675    //
676    // is virtual address required ?
677    //
678    if (sw_read || sw_write || hw_cam_write || hw_cam_read || hw_vid_enc_read) {
679        *vaddr = cpu_addr;
680    }
681
682    if (sw_write || hw_cam_write) {
683        //
684        // Keep locked region if locked for s/w write access.
685        //
686        cb->lockedLeft = l;
687        cb->lockedTop = t;
688        cb->lockedWidth = w;
689        cb->lockedHeight = h;
690    }
691
692    DD("gralloc_lock success. vaddr: %p, *vaddr: %p, usage: %x, cpu_addr: %p",
693            vaddr, vaddr ? *vaddr : 0, usage, cpu_addr);
694
695    return 0;
696}
697
698static int gralloc_unlock(gralloc_module_t const* module,
699                          buffer_handle_t handle)
700{
701    if (sFallback != NULL) {
702        return sFallback->unlock(sFallback, handle);
703    }
704
705    private_module_t *gr = (private_module_t *)module;
706    cb_handle_t *cb = (cb_handle_t *)handle;
707    if (!gr || !cb_handle_t::validate(cb)) {
708        return -EINVAL;
709    }
710
711    //
712    // if buffer was locked for s/w write, we need to update the host with
713    // the updated data
714    //
715    if (cb->lockedWidth > 0 && cb->lockedHeight > 0 && cb->hostHandle) {
716
717        // Make sure we have host connection
718        DEFINE_AND_VALIDATE_HOST_CONNECTION;
719
720        void *cpu_addr;
721        if (cb->canBePosted()) {
722            cpu_addr = (void *)(cb->ashmemBase + sizeof(int));
723        }
724        else {
725            cpu_addr = (void *)(cb->ashmemBase);
726        }
727
728        if (cb->lockedWidth < cb->width || cb->lockedHeight < cb->height) {
729            int bpp = glUtilsPixelBitSize(cb->glFormat, cb->glType) >> 3;
730            char *tmpBuf = new char[cb->lockedWidth * cb->lockedHeight * bpp];
731
732            int dst_line_len = cb->lockedWidth * bpp;
733            int src_line_len = cb->width * bpp;
734            char *src = (char *)cpu_addr + cb->lockedTop*src_line_len + cb->lockedLeft*bpp;
735            char *dst = tmpBuf;
736            for (int y=0; y<cb->lockedHeight; y++) {
737                memcpy(dst, src, dst_line_len);
738                src += src_line_len;
739                dst += dst_line_len;
740            }
741
742            rcEnc->rcUpdateColorBuffer(rcEnc, cb->hostHandle,
743                                       cb->lockedLeft, cb->lockedTop,
744                                       cb->lockedWidth, cb->lockedHeight,
745                                       cb->glFormat, cb->glType,
746                                       tmpBuf);
747
748            delete [] tmpBuf;
749        }
750        else {
751            rcEnc->rcUpdateColorBuffer(rcEnc, cb->hostHandle, 0, 0,
752                                       cb->width, cb->height,
753                                       cb->glFormat, cb->glType,
754                                       cpu_addr);
755        }
756    }
757
758    cb->lockedWidth = cb->lockedHeight = 0;
759    return 0;
760}
761
762
763static int gralloc_device_open(const hw_module_t* module,
764                               const char* name,
765                               hw_device_t** device)
766{
767    int status = -EINVAL;
768
769    D("gralloc_device_open %s\n", name);
770
771    pthread_once( &sFallbackOnce, fallback_init );
772    if (sFallback != NULL) {
773        return sFallback->common.methods->open(&sFallback->common, name, device);
774    }
775
776    if (!strcmp(name, GRALLOC_HARDWARE_GPU0)) {
777
778        // Create host connection and keep it in the TLS.
779        // return error if connection with host can not be established
780        HostConnection *hostCon = HostConnection::get();
781        if (!hostCon) {
782            ALOGE("gralloc: failed to get host connection while opening %s\n", name);
783            return -EIO;
784        }
785
786        //
787        // Allocate memory for the gralloc device (alloc interface)
788        //
789        gralloc_device_t *dev;
790        dev = (gralloc_device_t*)malloc(sizeof(gralloc_device_t));
791        if (NULL == dev) {
792            return -ENOMEM;
793        }
794
795        // Initialize our device structure
796        //
797        dev->device.common.tag = HARDWARE_DEVICE_TAG;
798        dev->device.common.version = 0;
799        dev->device.common.module = const_cast<hw_module_t*>(module);
800        dev->device.common.close = gralloc_device_close;
801
802        dev->device.alloc   = gralloc_alloc;
803        dev->device.free    = gralloc_free;
804        dev->allocListHead  = NULL;
805        pthread_mutex_init(&dev->lock, NULL);
806
807        *device = &dev->device.common;
808        status = 0;
809    }
810    else if (!strcmp(name, GRALLOC_HARDWARE_FB0)) {
811
812        // return error if connection with host can not be established
813        DEFINE_AND_VALIDATE_HOST_CONNECTION;
814
815        //
816        // Query the host for Framebuffer attributes
817        //
818        D("gralloc: query Frabuffer attribs\n");
819        EGLint width = rcEnc->rcGetFBParam(rcEnc, FB_WIDTH);
820        D("gralloc: width=%d\n", width);
821        EGLint height = rcEnc->rcGetFBParam(rcEnc, FB_HEIGHT);
822        D("gralloc: height=%d\n", height);
823        EGLint xdpi = rcEnc->rcGetFBParam(rcEnc, FB_XDPI);
824        D("gralloc: xdpi=%d\n", xdpi);
825        EGLint ydpi = rcEnc->rcGetFBParam(rcEnc, FB_YDPI);
826        D("gralloc: ydpi=%d\n", ydpi);
827        EGLint fps = rcEnc->rcGetFBParam(rcEnc, FB_FPS);
828        D("gralloc: fps=%d\n", fps);
829        EGLint min_si = rcEnc->rcGetFBParam(rcEnc, FB_MIN_SWAP_INTERVAL);
830        D("gralloc: min_swap=%d\n", min_si);
831        EGLint max_si = rcEnc->rcGetFBParam(rcEnc, FB_MAX_SWAP_INTERVAL);
832        D("gralloc: max_swap=%d\n", max_si);
833
834        //
835        // Allocate memory for the framebuffer device
836        //
837        fb_device_t *dev;
838        dev = (fb_device_t*)malloc(sizeof(fb_device_t));
839        if (NULL == dev) {
840            return -ENOMEM;
841        }
842        memset(dev, 0, sizeof(fb_device_t));
843
844        // Initialize our device structure
845        //
846        dev->device.common.tag = HARDWARE_DEVICE_TAG;
847        dev->device.common.version = 0;
848        dev->device.common.module = const_cast<hw_module_t*>(module);
849        dev->device.common.close = fb_close;
850        dev->device.setSwapInterval = fb_setSwapInterval;
851        dev->device.post            = fb_post;
852        dev->device.setUpdateRect   = 0; //fb_setUpdateRect;
853        dev->device.compositionComplete = fb_compositionComplete; //XXX: this is a dummy
854
855        const_cast<uint32_t&>(dev->device.flags) = 0;
856        const_cast<uint32_t&>(dev->device.width) = width;
857        const_cast<uint32_t&>(dev->device.height) = height;
858        const_cast<int&>(dev->device.stride) = width;
859        const_cast<int&>(dev->device.format) = HAL_PIXEL_FORMAT_RGBA_8888;
860        const_cast<float&>(dev->device.xdpi) = xdpi;
861        const_cast<float&>(dev->device.ydpi) = ydpi;
862        const_cast<float&>(dev->device.fps) = fps;
863        const_cast<int&>(dev->device.minSwapInterval) = min_si;
864        const_cast<int&>(dev->device.maxSwapInterval) = max_si;
865        *device = &dev->device.common;
866
867        status = 0;
868    }
869
870    return status;
871}
872
873//
874// define the HMI symbol - our module interface
875//
876static struct hw_module_methods_t gralloc_module_methods = {
877        open: gralloc_device_open
878};
879
880struct private_module_t HAL_MODULE_INFO_SYM = {
881    base: {
882        common: {
883            tag: HARDWARE_MODULE_TAG,
884            version_major: 1,
885            version_minor: 0,
886            id: GRALLOC_HARDWARE_MODULE_ID,
887            name: "Graphics Memory Allocator Module",
888            author: "The Android Open Source Project",
889            methods: &gralloc_module_methods,
890            dso: NULL,
891            reserved: {0, }
892        },
893        registerBuffer: gralloc_register_buffer,
894        unregisterBuffer: gralloc_unregister_buffer,
895        lock: gralloc_lock,
896        unlock: gralloc_unlock,
897        perform: NULL,
898        reserved_proc : {NULL, }
899    }
900};
901
902/* This function is called once to detect whether the emulator supports
903 * GPU emulation (this is done by looking at the qemu.gles kernel
904 * parameter, which must be > 0 if this is the case).
905 *
906 * If not, then load gralloc.default instead as a fallback.
907 */
908static void
909fallback_init(void)
910{
911    char  prop[PROPERTY_VALUE_MAX];
912    void* module;
913
914    property_get("ro.kernel.qemu.gles", prop, "0");
915    if (atoi(prop) > 0) {
916        return;
917    }
918    ALOGD("Emulator without GPU emulation detected.");
919    module = dlopen("/system/lib/hw/gralloc.default.so", RTLD_LAZY|RTLD_LOCAL);
920    if (module != NULL) {
921        sFallback = reinterpret_cast<gralloc_module_t*>(dlsym(module, HAL_MODULE_INFO_SYM_AS_STR));
922        if (sFallback == NULL) {
923            dlclose(module);
924        }
925    }
926    if (sFallback == NULL) {
927        ALOGE("Could not find software fallback module!?");
928    }
929}
930