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