gralloc.cpp revision a60007873dfb12ae4ecea59678dab01a5e179de6
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    // Keep around original requested format for later validation
158    int frameworkFormat = format;
159    // Pick the right concrete pixel format given the endpoints as encoded in
160    // the usage bits.  Every end-point pair needs explicit listing here.
161    if (format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
162        // Camera as producer
163        if (usage & GRALLOC_USAGE_HW_CAMERA_WRITE) {
164            if (usage & GRALLOC_USAGE_HW_TEXTURE) {
165                // Camera-to-display is RGBA
166                format = HAL_PIXEL_FORMAT_RGBA_8888;
167            } else if (usage & GRALLOC_USAGE_HW_VIDEO_ENCODER) {
168                // Camera-to-encoder is NV21
169                format = HAL_PIXEL_FORMAT_YCrCb_420_SP;
170            } else if ((usage & GRALLOC_USAGE_HW_CAMERA_MASK) ==
171                    GRALLOC_USAGE_HW_CAMERA_ZSL) {
172                // Camera-to-ZSL-queue is RGB_888
173                format = HAL_PIXEL_FORMAT_RGB_888;
174            }
175        }
176
177        if (format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
178            ALOGE("gralloc_alloc: Requested auto format selection, "
179                    "but no known format for this usage: %d x %d, usage %x",
180                    w, h, usage);
181            return -EINVAL;
182        }
183    } else if (format == HAL_PIXEL_FORMAT_YCbCr_420_888) {
184        // Flexible framework-accessible YUV format; map to NV21 for now
185        if (usage & GRALLOC_USAGE_HW_CAMERA_WRITE) {
186            format = HAL_PIXEL_FORMAT_YCrCb_420_SP;
187        }
188        if (format == HAL_PIXEL_FORMAT_YCbCr_420_888) {
189            ALOGE("gralloc_alloc: Requested YCbCr_420_888, but no known "
190                    "specific format for this usage: %d x %d, usage %x",
191                    w, h, usage);
192        }
193    }
194    bool yuv_format = false;
195
196    int ashmem_size = 0;
197    int stride = w;
198
199    GLenum glFormat = 0;
200    GLenum glType = 0;
201
202    int bpp = 0;
203    int align = 1;
204    switch (format) {
205        case HAL_PIXEL_FORMAT_RGBA_8888:
206        case HAL_PIXEL_FORMAT_RGBX_8888:
207        case HAL_PIXEL_FORMAT_BGRA_8888:
208            bpp = 4;
209            glFormat = GL_RGBA;
210            glType = GL_UNSIGNED_BYTE;
211            break;
212        case HAL_PIXEL_FORMAT_RGB_888:
213            bpp = 3;
214            glFormat = GL_RGB;
215            glType = GL_UNSIGNED_BYTE;
216            break;
217        case HAL_PIXEL_FORMAT_RGB_565:
218            bpp = 2;
219            glFormat = GL_RGB;
220            glType = GL_UNSIGNED_SHORT_5_6_5;
221            break;
222        case HAL_PIXEL_FORMAT_RGBA_5551:
223            bpp = 2;
224            glFormat = GL_RGB5_A1_OES;
225            glType = GL_UNSIGNED_SHORT_5_5_5_1;
226            break;
227        case HAL_PIXEL_FORMAT_RGBA_4444:
228            bpp = 2;
229            glFormat = GL_RGBA4_OES;
230            glType = GL_UNSIGNED_SHORT_4_4_4_4;
231            break;
232        case HAL_PIXEL_FORMAT_RAW_SENSOR:
233            bpp = 2;
234            align = 16*bpp;
235            if (! ((sw_read || hw_cam_read) && (sw_write || hw_cam_write) ) ) {
236                // Raw sensor data only goes between camera and CPU
237                return -EINVAL;
238            }
239            // Not expecting to actually create any GL surfaces for this
240            glFormat = GL_LUMINANCE;
241            glType = GL_UNSIGNED_SHORT;
242            break;
243        case HAL_PIXEL_FORMAT_BLOB:
244            bpp = 1;
245            if (! (sw_read && hw_cam_write) ) {
246                // Blob data cannot be used by HW other than camera emulator
247                return -EINVAL;
248            }
249            // Not expecting to actually create any GL surfaces for this
250            glFormat = GL_LUMINANCE;
251            glType = GL_UNSIGNED_BYTE;
252            break;
253        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
254            align = 1;
255            bpp = 1; // per-channel bpp
256            yuv_format = true;
257            // Not expecting to actually create any GL surfaces for this
258            break;
259        case HAL_PIXEL_FORMAT_YV12:
260            align = 16;
261            bpp = 1; // per-channel bpp
262            yuv_format = true;
263            // Not expecting to actually create any GL surfaces for this
264            break;
265        default:
266            ALOGE("gralloc_alloc: Unknown format %d", format);
267            return -EINVAL;
268    }
269
270    if (usage & GRALLOC_USAGE_HW_FB) {
271        // keep space for postCounter
272        ashmem_size += sizeof(uint32_t);
273    }
274
275    if (sw_read || sw_write || hw_cam_write || hw_vid_enc_read) {
276        // keep space for image on guest memory if SW access is needed
277        // or if the camera is doing writing
278        if (yuv_format) {
279            size_t yStride = (w*bpp + (align - 1)) & ~(align-1);
280            size_t uvStride = (yStride / 2 + (align - 1)) & ~(align-1);
281            size_t uvHeight = h / 2;
282            ashmem_size += yStride * h + 2 * (uvHeight * uvStride);
283            stride = yStride / bpp;
284        } else {
285            size_t bpr = (w*bpp + (align-1)) & ~(align-1);
286            ashmem_size += (bpr * h);
287            stride = bpr / bpp;
288        }
289    }
290
291    D("gralloc_alloc format=%d, ashmem_size=%d, stride=%d, tid %d\n", format,
292            ashmem_size, stride, gettid());
293
294    //
295    // Allocate space in ashmem if needed
296    //
297    int fd = -1;
298    if (ashmem_size > 0) {
299        // round to page size;
300        ashmem_size = (ashmem_size + (PAGE_SIZE-1)) & ~(PAGE_SIZE-1);
301
302        fd = ashmem_create_region("gralloc-buffer", ashmem_size);
303        if (fd < 0) {
304            ALOGE("gralloc_alloc failed to create ashmem region: %s\n",
305                    strerror(errno));
306            return -errno;
307        }
308    }
309
310    cb_handle_t *cb = new cb_handle_t(fd, ashmem_size, usage,
311                                      w, h, frameworkFormat, format,
312                                      glFormat, glType);
313
314    if (ashmem_size > 0) {
315        //
316        // map ashmem region if exist
317        //
318        void *vaddr;
319        int err = map_buffer(cb, &vaddr);
320        if (err) {
321            close(fd);
322            delete cb;
323            return err;
324        }
325
326        cb->setFd(fd);
327    }
328
329    //
330    // Allocate ColorBuffer handle on the host (only if h/w access is allowed)
331    // Only do this for some h/w usages, not all.
332    //
333    if (usage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
334                    GRALLOC_USAGE_HW_2D | GRALLOC_USAGE_HW_COMPOSER |
335                    GRALLOC_USAGE_HW_FB) ) {
336        DEFINE_HOST_CONNECTION;
337        if (hostCon && rcEnc) {
338            cb->hostHandle = rcEnc->rcCreateColorBuffer(rcEnc, w, h, glFormat);
339            D("Created host ColorBuffer 0x%x\n", cb->hostHandle);
340        }
341
342        if (!cb->hostHandle) {
343           // Could not create colorbuffer on host !!!
344           close(fd);
345           delete cb;
346           return -EIO;
347        }
348    }
349
350    //
351    // alloc succeeded - insert the allocated handle to the allocated list
352    //
353    AllocListNode *node = new AllocListNode();
354    pthread_mutex_lock(&grdev->lock);
355    node->handle = cb;
356    node->next =  grdev->allocListHead;
357    node->prev =  NULL;
358    if (grdev->allocListHead) {
359        grdev->allocListHead->prev = node;
360    }
361    grdev->allocListHead = node;
362    pthread_mutex_unlock(&grdev->lock);
363
364    *pHandle = cb;
365    if (frameworkFormat == HAL_PIXEL_FORMAT_YCbCr_420_888) {
366        *pStride = 0;
367    } else {
368        *pStride = stride;
369    }
370    return 0;
371}
372
373static int gralloc_free(alloc_device_t* dev,
374                        buffer_handle_t handle)
375{
376    const cb_handle_t *cb = (const cb_handle_t *)handle;
377    if (!cb_handle_t::validate((cb_handle_t*)cb)) {
378        ERR("gralloc_free: invalid handle");
379        return -EINVAL;
380    }
381
382    if (cb->hostHandle != 0) {
383        DEFINE_AND_VALIDATE_HOST_CONNECTION;
384        D("Closing host ColorBuffer 0x%x\n", cb->hostHandle);
385        rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
386    }
387
388    //
389    // detach and unmap ashmem area if present
390    //
391    if (cb->fd > 0) {
392        if (cb->ashmemSize > 0 && cb->ashmemBase) {
393            munmap((void *)cb->ashmemBase, cb->ashmemSize);
394        }
395        close(cb->fd);
396    }
397
398    // remove it from the allocated list
399    gralloc_device_t *grdev = (gralloc_device_t *)dev;
400    pthread_mutex_lock(&grdev->lock);
401    AllocListNode *n = grdev->allocListHead;
402    while( n && n->handle != cb ) {
403        n = n->next;
404    }
405    if (n) {
406       // buffer found on list - remove it from list
407       if (n->next) {
408           n->next->prev = n->prev;
409       }
410       if (n->prev) {
411           n->prev->next = n->next;
412       }
413       else {
414           grdev->allocListHead = n->next;
415       }
416
417       delete n;
418    }
419    pthread_mutex_unlock(&grdev->lock);
420
421    delete cb;
422
423    return 0;
424}
425
426static int gralloc_device_close(struct hw_device_t *dev)
427{
428    gralloc_device_t* d = reinterpret_cast<gralloc_device_t*>(dev);
429    if (d) {
430
431        // free still allocated buffers
432        while( d->allocListHead != NULL ) {
433            gralloc_free(&d->device, d->allocListHead->handle);
434        }
435
436        // free device
437        free(d);
438    }
439    return 0;
440}
441
442static int fb_compositionComplete(struct framebuffer_device_t* dev)
443{
444    return 0;
445}
446
447//
448// Framebuffer device functions
449//
450static int fb_post(struct framebuffer_device_t* dev, buffer_handle_t buffer)
451{
452    fb_device_t *fbdev = (fb_device_t *)dev;
453    cb_handle_t *cb = (cb_handle_t *)buffer;
454
455    if (!fbdev || !cb_handle_t::validate(cb) || !cb->canBePosted()) {
456        return -EINVAL;
457    }
458
459    // Make sure we have host connection
460    DEFINE_AND_VALIDATE_HOST_CONNECTION;
461
462    // increment the post count of the buffer
463    uint32_t *postCountPtr = (uint32_t *)cb->ashmemBase;
464    if (!postCountPtr) {
465        // This should not happen
466        return -EINVAL;
467    }
468    (*postCountPtr)++;
469
470    // send post request to host
471    rcEnc->rcFBPost(rcEnc, cb->hostHandle);
472    hostCon->flush();
473
474    return 0;
475}
476
477static int fb_setUpdateRect(struct framebuffer_device_t* dev,
478        int l, int t, int w, int h)
479{
480    fb_device_t *fbdev = (fb_device_t *)dev;
481
482    if (!fbdev) {
483        return -EINVAL;
484    }
485
486    // Make sure we have host connection
487    DEFINE_AND_VALIDATE_HOST_CONNECTION;
488
489    // send request to host
490    // TODO: XXX - should be implemented
491    //rcEnc->rc_XXX
492
493    return 0;
494}
495
496static int fb_setSwapInterval(struct framebuffer_device_t* dev,
497            int interval)
498{
499    fb_device_t *fbdev = (fb_device_t *)dev;
500
501    if (!fbdev) {
502        return -EINVAL;
503    }
504
505    // Make sure we have host connection
506    DEFINE_AND_VALIDATE_HOST_CONNECTION;
507
508    // send request to host
509    rcEnc->rcFBSetSwapInterval(rcEnc, interval);
510    hostCon->flush();
511
512    return 0;
513}
514
515static int fb_close(struct hw_device_t *dev)
516{
517    fb_device_t *fbdev = (fb_device_t *)dev;
518
519    delete fbdev;
520
521    return 0;
522}
523
524
525//
526// gralloc module functions - refcount + locking interface
527//
528static int gralloc_register_buffer(gralloc_module_t const* module,
529                                   buffer_handle_t handle)
530{
531    pthread_once(&sFallbackOnce, fallback_init);
532    if (sFallback != NULL) {
533        return sFallback->registerBuffer(sFallback, handle);
534    }
535
536    D("gralloc_register_buffer(%p) called", handle);
537
538    private_module_t *gr = (private_module_t *)module;
539    cb_handle_t *cb = (cb_handle_t *)handle;
540    if (!gr || !cb_handle_t::validate(cb)) {
541        ERR("gralloc_register_buffer(%p): invalid buffer", cb);
542        return -EINVAL;
543    }
544
545    if (cb->hostHandle != 0) {
546        DEFINE_AND_VALIDATE_HOST_CONNECTION;
547        D("Opening host ColorBuffer 0x%x\n", cb->hostHandle);
548        rcEnc->rcOpenColorBuffer(rcEnc, cb->hostHandle);
549    }
550
551    //
552    // if the color buffer has ashmem region and it is not mapped in this
553    // process map it now.
554    //
555    if (cb->ashmemSize > 0 && cb->mappedPid != getpid()) {
556        void *vaddr;
557        int err = map_buffer(cb, &vaddr);
558        if (err) {
559            ERR("gralloc_register_buffer(%p): map failed: %s", cb, strerror(-err));
560            return -err;
561        }
562        cb->mappedPid = getpid();
563    }
564
565    return 0;
566}
567
568static int gralloc_unregister_buffer(gralloc_module_t const* module,
569                                     buffer_handle_t handle)
570{
571    if (sFallback != NULL) {
572        return sFallback->unregisterBuffer(sFallback, handle);
573    }
574
575    private_module_t *gr = (private_module_t *)module;
576    cb_handle_t *cb = (cb_handle_t *)handle;
577    if (!gr || !cb_handle_t::validate(cb)) {
578        ERR("gralloc_unregister_buffer(%p): invalid buffer", cb);
579        return -EINVAL;
580    }
581
582    if (cb->hostHandle != 0) {
583        DEFINE_AND_VALIDATE_HOST_CONNECTION;
584        D("Closing host ColorBuffer 0x%x\n", cb->hostHandle);
585        rcEnc->rcCloseColorBuffer(rcEnc, cb->hostHandle);
586    }
587
588    //
589    // unmap ashmem region if it was previously mapped in this process
590    // (through register_buffer)
591    //
592    if (cb->ashmemSize > 0 && cb->mappedPid == getpid()) {
593        void *vaddr;
594        int err = munmap((void *)cb->ashmemBase, cb->ashmemSize);
595        if (err) {
596            ERR("gralloc_unregister_buffer(%p): unmap failed", cb);
597            return -EINVAL;
598        }
599        cb->ashmemBase = 0;
600        cb->mappedPid = 0;
601    }
602
603    D("gralloc_unregister_buffer(%p) done\n", cb);
604
605    return 0;
606}
607
608static int gralloc_lock(gralloc_module_t const* module,
609                        buffer_handle_t handle, int usage,
610                        int l, int t, int w, int h,
611                        void** vaddr)
612{
613    if (sFallback != NULL) {
614        return sFallback->lock(sFallback, handle, usage, l, t, w, h, vaddr);
615    }
616
617    private_module_t *gr = (private_module_t *)module;
618    cb_handle_t *cb = (cb_handle_t *)handle;
619    if (!gr || !cb_handle_t::validate(cb)) {
620        ALOGE("gralloc_lock bad handle\n");
621        return -EINVAL;
622    }
623
624    // validate format
625    if (cb->frameworkFormat == HAL_PIXEL_FORMAT_YCbCr_420_888) {
626        ALOGE("gralloc_lock can't be used with YCbCr_420_888 format");
627        return -EINVAL;
628    }
629
630    // Validate usage,
631    //   1. cannot be locked for hw access
632    //   2. lock for either sw read or write.
633    //   3. locked sw access must match usage during alloc time.
634    bool sw_read = (0 != (usage & GRALLOC_USAGE_SW_READ_MASK));
635    bool sw_write = (0 != (usage & GRALLOC_USAGE_SW_WRITE_MASK));
636    bool hw_read = (usage & GRALLOC_USAGE_HW_TEXTURE);
637    bool hw_write = (usage & GRALLOC_USAGE_HW_RENDER);
638    bool hw_vid_enc_read = (usage & GRALLOC_USAGE_HW_VIDEO_ENCODER);
639    bool hw_cam_write = (usage & GRALLOC_USAGE_HW_CAMERA_WRITE);
640    bool hw_cam_read = (usage & GRALLOC_USAGE_HW_CAMERA_READ);
641    bool sw_read_allowed = (0 != (cb->usage & GRALLOC_USAGE_SW_READ_MASK));
642    bool sw_write_allowed = (0 != (cb->usage & GRALLOC_USAGE_SW_WRITE_MASK));
643
644    if ( (hw_read || hw_write) ||
645         (!sw_read && !sw_write &&
646                 !hw_cam_write && !hw_cam_read &&
647                 !hw_vid_enc_read) ||
648         (sw_read && !sw_read_allowed) ||
649         (sw_write && !sw_write_allowed) ) {
650        ALOGE("gralloc_lock usage mismatch usage=0x%x cb->usage=0x%x\n", usage,
651                cb->usage);
652        return -EINVAL;
653    }
654
655    EGLint postCount = 0;
656    void *cpu_addr = NULL;
657
658    //
659    // make sure ashmem area is mapped if needed
660    //
661    if (cb->canBePosted() || sw_read || sw_write ||
662            hw_cam_write || hw_cam_read ||
663            hw_vid_enc_read) {
664        if (cb->ashmemBasePid != getpid() || !cb->ashmemBase) {
665            return -EACCES;
666        }
667
668        if (cb->canBePosted()) {
669            postCount = *((int *)cb->ashmemBase);
670            cpu_addr = (void *)(cb->ashmemBase + sizeof(int));
671        }
672        else {
673            cpu_addr = (void *)(cb->ashmemBase);
674        }
675    }
676
677    if (cb->hostHandle) {
678        // Make sure we have host connection
679        DEFINE_AND_VALIDATE_HOST_CONNECTION;
680
681        //
682        // flush color buffer write cache on host and get its sync status.
683        //
684        int hostSyncStatus = rcEnc->rcColorBufferCacheFlush(rcEnc, cb->hostHandle,
685                                                            postCount,
686                                                            sw_read);
687        if (hostSyncStatus < 0) {
688            // host failed the color buffer sync - probably since it was already
689            // locked for write access. fail the lock.
690            ALOGE("gralloc_lock cacheFlush failed postCount=%d sw_read=%d\n",
691                 postCount, sw_read);
692            return -EBUSY;
693        }
694
695    }
696
697    //
698    // is virtual address required ?
699    //
700    if (sw_read || sw_write || hw_cam_write || hw_cam_read || hw_vid_enc_read) {
701        *vaddr = cpu_addr;
702    }
703
704    if (sw_write || hw_cam_write) {
705        //
706        // Keep locked region if locked for s/w write access.
707        //
708        cb->lockedLeft = l;
709        cb->lockedTop = t;
710        cb->lockedWidth = w;
711        cb->lockedHeight = h;
712    }
713
714    DD("gralloc_lock success. vaddr: %p, *vaddr: %p, usage: %x, cpu_addr: %p",
715            vaddr, vaddr ? *vaddr : 0, usage, cpu_addr);
716
717    return 0;
718}
719
720static int gralloc_unlock(gralloc_module_t const* module,
721                          buffer_handle_t handle)
722{
723    if (sFallback != NULL) {
724        return sFallback->unlock(sFallback, handle);
725    }
726
727    private_module_t *gr = (private_module_t *)module;
728    cb_handle_t *cb = (cb_handle_t *)handle;
729    if (!gr || !cb_handle_t::validate(cb)) {
730        return -EINVAL;
731    }
732
733    //
734    // if buffer was locked for s/w write, we need to update the host with
735    // the updated data
736    //
737    if (cb->lockedWidth > 0 && cb->lockedHeight > 0 && cb->hostHandle) {
738
739        // Make sure we have host connection
740        DEFINE_AND_VALIDATE_HOST_CONNECTION;
741
742        void *cpu_addr;
743        if (cb->canBePosted()) {
744            cpu_addr = (void *)(cb->ashmemBase + sizeof(int));
745        }
746        else {
747            cpu_addr = (void *)(cb->ashmemBase);
748        }
749
750        if (cb->lockedWidth < cb->width || cb->lockedHeight < cb->height) {
751            int bpp = glUtilsPixelBitSize(cb->glFormat, cb->glType) >> 3;
752            char *tmpBuf = new char[cb->lockedWidth * cb->lockedHeight * bpp];
753
754            int dst_line_len = cb->lockedWidth * bpp;
755            int src_line_len = cb->width * bpp;
756            char *src = (char *)cpu_addr + cb->lockedTop*src_line_len + cb->lockedLeft*bpp;
757            char *dst = tmpBuf;
758            for (int y=0; y<cb->lockedHeight; y++) {
759                memcpy(dst, src, dst_line_len);
760                src += src_line_len;
761                dst += dst_line_len;
762            }
763
764            rcEnc->rcUpdateColorBuffer(rcEnc, cb->hostHandle,
765                                       cb->lockedLeft, cb->lockedTop,
766                                       cb->lockedWidth, cb->lockedHeight,
767                                       cb->glFormat, cb->glType,
768                                       tmpBuf);
769
770            delete [] tmpBuf;
771        }
772        else {
773            rcEnc->rcUpdateColorBuffer(rcEnc, cb->hostHandle, 0, 0,
774                                       cb->width, cb->height,
775                                       cb->glFormat, cb->glType,
776                                       cpu_addr);
777        }
778    }
779
780    cb->lockedWidth = cb->lockedHeight = 0;
781    return 0;
782}
783
784static int gralloc_lock_ycbcr(gralloc_module_t const* module,
785                        buffer_handle_t handle, int usage,
786                        int l, int t, int w, int h,
787                        android_ycbcr *ycbcr)
788{
789    // Not supporting fallback module for YCbCr
790    if (sFallback != NULL) {
791        return -EINVAL;
792    }
793
794    if (!ycbcr) {
795        ALOGE("gralloc_lock_ycbcr got NULL ycbcr struct");
796        return -EINVAL;
797    }
798
799    private_module_t *gr = (private_module_t *)module;
800    cb_handle_t *cb = (cb_handle_t *)handle;
801    if (!gr || !cb_handle_t::validate(cb)) {
802        ALOGE("gralloc_lock_ycbcr bad handle\n");
803        return -EINVAL;
804    }
805
806    if (cb->frameworkFormat != HAL_PIXEL_FORMAT_YCbCr_420_888) {
807        ALOGE("gralloc_lock_ycbcr can only be used with "
808                "HAL_PIXEL_FORMAT_YCbCr_420_888, got %x instead",
809                cb->frameworkFormat);
810        return -EINVAL;
811    }
812
813    // Validate usage
814    // For now, only allow camera write, software read.
815    bool sw_read = (0 != (usage & GRALLOC_USAGE_SW_READ_MASK));
816    bool hw_cam_write = (usage & GRALLOC_USAGE_HW_CAMERA_WRITE);
817    bool sw_read_allowed = (0 != (cb->usage & GRALLOC_USAGE_SW_READ_MASK));
818
819    if ( (!hw_cam_write && !sw_read) ||
820            (sw_read && !sw_read_allowed) ) {
821        ALOGE("gralloc_lock_ycbcr usage mismatch usage:0x%x cb->usage:0x%x\n",
822                usage, cb->usage);
823        return -EINVAL;
824    }
825
826    // Make sure memory is mapped, get address
827    if (cb->ashmemBasePid != getpid() || !cb->ashmemBase) {
828        return -EACCES;
829    }
830
831    uint8_t *cpu_addr = NULL;
832
833    if (cb->canBePosted()) {
834        cpu_addr = (uint8_t *)(cb->ashmemBase + sizeof(int));
835    }
836    else {
837        cpu_addr = (uint8_t *)(cb->ashmemBase);
838    }
839
840    // Calculate offsets to underlying YUV data
841    size_t yStride;
842    size_t cStride;
843    size_t yOffset;
844    size_t uOffset;
845    size_t vOffset;
846    size_t cStep;
847    switch (cb->format) {
848        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
849            yStride = cb->width;
850            cStride = cb->width;
851            yOffset = 0;
852            vOffset = yStride * cb->height;
853            uOffset = vOffset + 1;
854            cStep = 2;
855            break;
856        default:
857            ALOGE("gralloc_lock_ycbcr unexpected internal format %x",
858                    cb->format);
859            return -EINVAL;
860    }
861
862    ycbcr->y = cpu_addr + yOffset;
863    ycbcr->cb = cpu_addr + uOffset;
864    ycbcr->cr = cpu_addr + vOffset;
865    ycbcr->ystride = yStride;
866    ycbcr->cstride = cStride;
867    ycbcr->chroma_step = cStep;
868
869    // Zero out reserved fields
870    memset(ycbcr->reserved, 0, sizeof(ycbcr->reserved));
871
872    //
873    // Keep locked region if locked for s/w write access.
874    //
875    cb->lockedLeft = l;
876    cb->lockedTop = t;
877    cb->lockedWidth = w;
878    cb->lockedHeight = h;
879
880    DD("gralloc_lock_ycbcr success. usage: %x, ycbcr.y: %p, .cb: %p, .cr: %p, "
881            ".ystride: %d , .cstride: %d, .chroma_step: %d", usage,
882            ycbcr->y, ycbcr->cb, ycbcr->cr, ycbcr->ystride, ycbcr->cstride,
883            ycbcr->chroma_step);
884
885    return 0;
886}
887
888static int gralloc_device_open(const hw_module_t* module,
889                               const char* name,
890                               hw_device_t** device)
891{
892    int status = -EINVAL;
893
894    D("gralloc_device_open %s\n", name);
895
896    pthread_once( &sFallbackOnce, fallback_init );
897    if (sFallback != NULL) {
898        return sFallback->common.methods->open(&sFallback->common, name, device);
899    }
900
901    if (!strcmp(name, GRALLOC_HARDWARE_GPU0)) {
902
903        // Create host connection and keep it in the TLS.
904        // return error if connection with host can not be established
905        HostConnection *hostCon = HostConnection::get();
906        if (!hostCon) {
907            ALOGE("gralloc: failed to get host connection while opening %s\n", name);
908            return -EIO;
909        }
910
911        //
912        // Allocate memory for the gralloc device (alloc interface)
913        //
914        gralloc_device_t *dev;
915        dev = (gralloc_device_t*)malloc(sizeof(gralloc_device_t));
916        if (NULL == dev) {
917            return -ENOMEM;
918        }
919
920        // Initialize our device structure
921        //
922        dev->device.common.tag = HARDWARE_DEVICE_TAG;
923        dev->device.common.version = 0;
924        dev->device.common.module = const_cast<hw_module_t*>(module);
925        dev->device.common.close = gralloc_device_close;
926
927        dev->device.alloc   = gralloc_alloc;
928        dev->device.free    = gralloc_free;
929        dev->allocListHead  = NULL;
930        pthread_mutex_init(&dev->lock, NULL);
931
932        *device = &dev->device.common;
933        status = 0;
934    }
935    else if (!strcmp(name, GRALLOC_HARDWARE_FB0)) {
936
937        // return error if connection with host can not be established
938        DEFINE_AND_VALIDATE_HOST_CONNECTION;
939
940        //
941        // Query the host for Framebuffer attributes
942        //
943        D("gralloc: query Frabuffer attribs\n");
944        EGLint width = rcEnc->rcGetFBParam(rcEnc, FB_WIDTH);
945        D("gralloc: width=%d\n", width);
946        EGLint height = rcEnc->rcGetFBParam(rcEnc, FB_HEIGHT);
947        D("gralloc: height=%d\n", height);
948        EGLint xdpi = rcEnc->rcGetFBParam(rcEnc, FB_XDPI);
949        D("gralloc: xdpi=%d\n", xdpi);
950        EGLint ydpi = rcEnc->rcGetFBParam(rcEnc, FB_YDPI);
951        D("gralloc: ydpi=%d\n", ydpi);
952        EGLint fps = rcEnc->rcGetFBParam(rcEnc, FB_FPS);
953        D("gralloc: fps=%d\n", fps);
954        EGLint min_si = rcEnc->rcGetFBParam(rcEnc, FB_MIN_SWAP_INTERVAL);
955        D("gralloc: min_swap=%d\n", min_si);
956        EGLint max_si = rcEnc->rcGetFBParam(rcEnc, FB_MAX_SWAP_INTERVAL);
957        D("gralloc: max_swap=%d\n", max_si);
958
959        //
960        // Allocate memory for the framebuffer device
961        //
962        fb_device_t *dev;
963        dev = (fb_device_t*)malloc(sizeof(fb_device_t));
964        if (NULL == dev) {
965            return -ENOMEM;
966        }
967        memset(dev, 0, sizeof(fb_device_t));
968
969        // Initialize our device structure
970        //
971        dev->device.common.tag = HARDWARE_DEVICE_TAG;
972        dev->device.common.version = 0;
973        dev->device.common.module = const_cast<hw_module_t*>(module);
974        dev->device.common.close = fb_close;
975        dev->device.setSwapInterval = fb_setSwapInterval;
976        dev->device.post            = fb_post;
977        dev->device.setUpdateRect   = 0; //fb_setUpdateRect;
978        dev->device.compositionComplete = fb_compositionComplete; //XXX: this is a dummy
979
980        const_cast<uint32_t&>(dev->device.flags) = 0;
981        const_cast<uint32_t&>(dev->device.width) = width;
982        const_cast<uint32_t&>(dev->device.height) = height;
983        const_cast<int&>(dev->device.stride) = width;
984        const_cast<int&>(dev->device.format) = HAL_PIXEL_FORMAT_RGBA_8888;
985        const_cast<float&>(dev->device.xdpi) = xdpi;
986        const_cast<float&>(dev->device.ydpi) = ydpi;
987        const_cast<float&>(dev->device.fps) = fps;
988        const_cast<int&>(dev->device.minSwapInterval) = min_si;
989        const_cast<int&>(dev->device.maxSwapInterval) = max_si;
990        *device = &dev->device.common;
991
992        status = 0;
993    }
994
995    return status;
996}
997
998//
999// define the HMI symbol - our module interface
1000//
1001static struct hw_module_methods_t gralloc_module_methods = {
1002        open: gralloc_device_open
1003};
1004
1005struct private_module_t HAL_MODULE_INFO_SYM = {
1006    base: {
1007        common: {
1008            tag: HARDWARE_MODULE_TAG,
1009            module_api_version: GRALLOC_MODULE_API_VERSION_0_2,
1010            hal_api_version: 0,
1011            id: GRALLOC_HARDWARE_MODULE_ID,
1012            name: "Graphics Memory Allocator Module",
1013            author: "The Android Open Source Project",
1014            methods: &gralloc_module_methods,
1015            dso: NULL,
1016            reserved: {0, }
1017        },
1018        registerBuffer: gralloc_register_buffer,
1019        unregisterBuffer: gralloc_unregister_buffer,
1020        lock: gralloc_lock,
1021        unlock: gralloc_unlock,
1022        perform: NULL,
1023        lock_ycbcr: gralloc_lock_ycbcr,
1024        reserved_proc: {0, }
1025    }
1026};
1027
1028/* This function is called once to detect whether the emulator supports
1029 * GPU emulation (this is done by looking at the qemu.gles kernel
1030 * parameter, which must be > 0 if this is the case).
1031 *
1032 * If not, then load gralloc.default instead as a fallback.
1033 */
1034static void
1035fallback_init(void)
1036{
1037    char  prop[PROPERTY_VALUE_MAX];
1038    void* module;
1039
1040    property_get("ro.kernel.qemu.gles", prop, "0");
1041    if (atoi(prop) > 0) {
1042        return;
1043    }
1044    ALOGD("Emulator without GPU emulation detected.");
1045    module = dlopen("/system/lib/hw/gralloc.default.so", RTLD_LAZY|RTLD_LOCAL);
1046    if (module != NULL) {
1047        sFallback = reinterpret_cast<gralloc_module_t*>(dlsym(module, HAL_MODULE_INFO_SYM_AS_STR));
1048        if (sFallback == NULL) {
1049            dlclose(module);
1050        }
1051    }
1052    if (sFallback == NULL) {
1053        ALOGE("Could not find software fallback module!?");
1054    }
1055}
1056