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