libdmabufheap: Do not fallback to ion when dma-buf exists am: d7fd440294 am: 0f1d4f9e68 am: d4ff3d3037

Original change: https://android-review.googlesource.com/c/platform/system/memory/libdmabufheap/+/2819907

Change-Id: I0c03ba9138c4d784de7f46db6d9448ec0e45b97e
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
diff --git a/BufferAllocator.cpp b/BufferAllocator.cpp
index a360cfd..0c625f6 100644
--- a/BufferAllocator.cpp
+++ b/BufferAllocator.cpp
@@ -210,8 +210,7 @@
     return ret;
 }
 
-int BufferAllocator::DmabufAlloc(const std::string& heap_name, size_t len) {
-    int fd = OpenDmabufHeap(heap_name);
+int BufferAllocator::DmabufAlloc(const std::string& heap_name, size_t len, int fd) {
     if (fd < 0) return fd;
 
     struct dma_heap_allocation_data heap_data{
@@ -263,12 +262,14 @@
 
 int BufferAllocator::Alloc(const std::string& heap_name, size_t len,
                            unsigned int heap_flags, size_t legacy_align) {
-    int fd = DmabufAlloc(heap_name, len);
+    int dma_buf_heap_fd = OpenDmabufHeap(heap_name);
+    if (dma_buf_heap_fd >= 0) return DmabufAlloc(heap_name, len, dma_buf_heap_fd);
 
-    if (fd < 0)
-        fd = IonAlloc(heap_name, len, heap_flags, legacy_align);
-
-    return fd;
+    /*
+     * Swap back to ion only if we failed to allocate for a dma-buffer heap
+     * that doesn't exist.
+     */
+    return IonAlloc(heap_name, len, heap_flags, legacy_align);
 }
 
 int BufferAllocator::AllocSystem(bool cpu_access_needed, size_t len, unsigned int heap_flags,
@@ -283,8 +284,12 @@
             return (dmabuf_heap_list.find(kDmabufSystemUncachedHeapName) != dmabuf_heap_list.end());
         }();
 
-        if (uncached_dmabuf_system_heap_support)
-            return DmabufAlloc(kDmabufSystemUncachedHeapName, len);
+        if (uncached_dmabuf_system_heap_support) {
+            int dma_buf_heap_fd = OpenDmabufHeap(kDmabufSystemUncachedHeapName);
+            return (dma_buf_heap_fd < 0)
+                           ? dma_buf_heap_fd
+                           : DmabufAlloc(kDmabufSystemUncachedHeapName, len, dma_buf_heap_fd);
+        }
 
         static bool uncached_ion_system_heap_support = [this]() -> bool {
             IonHeapConfig heap_config;
diff --git a/include/BufferAllocator/BufferAllocator.h b/include/BufferAllocator/BufferAllocator.h
index 95ffdf5..bcc63a0 100644
--- a/include/BufferAllocator/BufferAllocator.h
+++ b/include/BufferAllocator/BufferAllocator.h
@@ -195,7 +195,7 @@
                          unsigned int ion_heap_flags = 0);
     void LogInterface(const std::string& interface);
     int IonAlloc(const std::string& heap_name, size_t len, unsigned int heap_flags = 0, size_t legacy_align = 0);
-    int DmabufAlloc(const std::string& heap_name, size_t len);
+    int DmabufAlloc(const std::string& heap_name, size_t len, int fd);
 
     struct IonHeapConfig {
         unsigned int mask;