Merge "SF: Flush out SurfaceFlingerFactory"
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index 16abc1e..4ccb917 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -6,6 +6,7 @@
 clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,cc,cpp
                libs/graphicsenv/
                libs/gui/
+               libs/renderengine/
                libs/ui/
                libs/vr/
                services/surfaceflinger/
diff --git a/cmds/installd/InstalldNativeService.cpp b/cmds/installd/InstalldNativeService.cpp
index e4990b0..a475fcc 100644
--- a/cmds/installd/InstalldNativeService.cpp
+++ b/cmds/installd/InstalldNativeService.cpp
@@ -77,7 +77,6 @@
 
 static constexpr const char* kCpPath = "/system/bin/cp";
 static constexpr const char* kXattrDefault = "user.default";
-static constexpr const char* kPropHasReserved = "vold.has_reserved";
 
 static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
 
@@ -343,55 +342,6 @@
     return 0;
 }
 
-/**
- * Ensure that we have a hard-limit quota to protect against abusive apps;
- * they should never use more than 90% of blocks or 50% of inodes.
- */
-static int prepare_app_quota(const std::unique_ptr<std::string>& uuid ATTRIBUTE_UNUSED,
-        const std::string& device, uid_t uid) {
-    // Skip when reserved blocks are protecting us against abusive apps
-    if (android::base::GetBoolProperty(kPropHasReserved, false)) return 0;
-    // Skip when device no quotas present
-    if (device.empty()) return 0;
-
-    struct dqblk dq;
-    if (quotactl(QCMD(Q_GETQUOTA, USRQUOTA), device.c_str(), uid,
-            reinterpret_cast<char*>(&dq)) != 0) {
-        PLOG(WARNING) << "Failed to find quota for " << uid;
-        return -1;
-    }
-
-#if APPLY_HARD_QUOTAS
-    if ((dq.dqb_bhardlimit == 0) || (dq.dqb_ihardlimit == 0)) {
-        auto path = create_data_path(uuid ? uuid->c_str() : nullptr);
-        struct statvfs stat;
-        if (statvfs(path.c_str(), &stat) != 0) {
-            PLOG(WARNING) << "Failed to statvfs " << path;
-            return -1;
-        }
-
-        dq.dqb_valid = QIF_LIMITS;
-        dq.dqb_bhardlimit =
-            (((static_cast<uint64_t>(stat.f_blocks) * stat.f_frsize) / 10) * 9) / QIF_DQBLKSIZE;
-        dq.dqb_ihardlimit = (stat.f_files / 2);
-        if (quotactl(QCMD(Q_SETQUOTA, USRQUOTA), device.c_str(), uid,
-                reinterpret_cast<char*>(&dq)) != 0) {
-            PLOG(WARNING) << "Failed to set hard quota for " << uid;
-            return -1;
-        } else {
-            LOG(DEBUG) << "Applied hard quotas for " << uid;
-            return 0;
-        }
-    } else {
-        // Hard quota already set; assume it's reasonable
-        return 0;
-    }
-#else
-    // Hard quotas disabled
-    return 0;
-#endif
-}
-
 static bool prepare_app_profile_dir(const std::string& packageName, int32_t appId, int32_t userId) {
     if (!property_get_bool("dalvik.vm.usejitprofiles", false)) {
         return true;
@@ -506,10 +456,6 @@
             return error("Failed to restorecon " + path);
         }
 
-        if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid), uid)) {
-            return error("Failed to set hard quota " + path);
-        }
-
         if (!prepare_app_profile_dir(packageName, appId, userId)) {
             return error("Failed to prepare profiles for " + packageName);
         }
@@ -616,6 +562,10 @@
             // No code cache on shared storage
         } else {
             // Clear everything on shared storage
+            path = StringPrintf("%s/Android/sandbox/%s", extPath.c_str(), pkgname);
+            if (delete_dir_contents(path, true) != 0) {
+                res = error("Failed to delete contents of " + path);
+            }
             path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
             if (delete_dir_contents(path, true) != 0) {
                 res = error("Failed to delete contents of " + path);
@@ -699,6 +649,10 @@
         }
 
         auto extPath = findDataMediaPath(uuid, userId);
+        path = StringPrintf("%s/Android/sandbox/%s", extPath.c_str(), pkgname);
+        if (delete_dir_contents_and_dir(path, true) != 0) {
+            res = error("Failed to delete " + path);
+        }
         path = StringPrintf("%s/Android/data/%s", extPath.c_str(), pkgname);
         if (delete_dir_contents_and_dir(path, true) != 0) {
             res = error("Failed to delete " + path);
@@ -988,13 +942,6 @@
         }
     }
 
-    // Data under /data/media doesn't have an app, but we still want
-    // to limit it to prevent abuse.
-    if (prepare_app_quota(uuid, findQuotaDeviceForUuid(uuid),
-            multiuser_get_uid(userId, AID_MEDIA_RW))) {
-        return error("Failed to set hard quota for media_rw");
-    }
-
     return ok();
 }
 
@@ -1552,6 +1499,8 @@
             }
 
             ATRACE_BEGIN("external");
+            auto sandboxPath = create_data_media_package_path(uuid_, userId, "sandbox", pkgname);
+            calculate_tree_size(sandboxPath, &extStats.dataSize);
             auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
             collectManualStats(extPath, &extStats);
             auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
@@ -2644,21 +2593,6 @@
                     reinterpret_cast<char*>(&dq)) == 0) {
                 LOG(DEBUG) << "Found quota mount " << source << " at " << target;
                 mQuotaReverseMounts[target] = source;
-
-                // ext4 only enables DQUOT_USAGE_ENABLED by default, so we
-                // need to kick it again to enable DQUOT_LIMITS_ENABLED. We
-                // only need hard limits enabled when we're not being protected
-                // by reserved blocks.
-                if (!android::base::GetBoolProperty(kPropHasReserved, false)) {
-                    if (quotactl(QCMD(Q_QUOTAON, USRQUOTA), source.c_str(), QFMT_VFS_V1,
-                            nullptr) != 0 && errno != EBUSY) {
-                        PLOG(ERROR) << "Failed to enable USRQUOTA on " << source;
-                    }
-                    if (quotactl(QCMD(Q_QUOTAON, GRPQUOTA), source.c_str(), QFMT_VFS_V1,
-                            nullptr) != 0 && errno != EBUSY) {
-                        PLOG(ERROR) << "Failed to enable GRPQUOTA on " << source;
-                    }
-                }
             }
         }
 #endif
diff --git a/cmds/installd/OWNERS b/cmds/installd/OWNERS
index 50440f1..5d4f176 100644
--- a/cmds/installd/OWNERS
+++ b/cmds/installd/OWNERS
@@ -1,7 +1,8 @@
 set noparent
 
-calin@google.com
 agampe@google.com
+calin@google.com
 jsharkey@android.com
-toddke@google.com
+mathieuc@google.com
 ngeoffray@google.com
+toddke@google.com
diff --git a/cmds/installd/dexopt.cpp b/cmds/installd/dexopt.cpp
index 66dece7..174ab21 100644
--- a/cmds/installd/dexopt.cpp
+++ b/cmds/installd/dexopt.cpp
@@ -287,6 +287,8 @@
                              (strcmp(vold_decrypt, "1") == 0)));
 
     bool generate_debug_info = property_get_bool("debug.generate-debug-info", false);
+    const bool resolve_startup_strings =
+            property_get_bool("dalvik.vm.dex2oat-resolve-startup-strings", false);
 
     char app_image_format[kPropertyValueMax];
     char image_format_arg[strlen("--image-format=") + kPropertyValueMax];
@@ -442,7 +444,7 @@
     // supported.
     const bool disable_cdex = !generate_compact_dex || (input_vdex_fd == output_vdex_fd);
 
-    const char* argv[9  // program name, mandatory arguments and the final NULL
+    const char* argv[10  // program name, mandatory arguments and the final NULL
                      + (have_dex2oat_isa_variant ? 1 : 0)
                      + (have_dex2oat_isa_features ? 1 : 0)
                      + (have_dex2oat_Xms_flag ? 2 : 0)
@@ -475,6 +477,8 @@
     argv[i++] = oat_fd_arg;
     argv[i++] = oat_location_arg;
     argv[i++] = instruction_set_arg;
+    argv[i++] = resolve_startup_strings ? "--resolve-startup-const-strings=true" :
+            "--resolve-startup-const-strings=false";
     if (have_dex2oat_isa_variant) {
         argv[i++] = instruction_set_variant_arg;
     }
diff --git a/cmds/installd/utils.h b/cmds/installd/utils.h
index 5829c4f..d05724a 100644
--- a/cmds/installd/utils.h
+++ b/cmds/installd/utils.h
@@ -36,8 +36,6 @@
 #define BYPASS_QUOTA 0
 #define BYPASS_SDCARDFS 0
 
-#define APPLY_HARD_QUOTAS 0
-
 namespace android {
 namespace installd {
 
diff --git a/cmds/servicemanager/servicemanager.rc b/cmds/servicemanager/servicemanager.rc
index 4d93cb4..152ac28 100644
--- a/cmds/servicemanager/servicemanager.rc
+++ b/cmds/servicemanager/servicemanager.rc
@@ -13,5 +13,6 @@
     onrestart restart cameraserver
     onrestart restart keystore
     onrestart restart gatekeeperd
+    onrestart restart thermalservice
     writepid /dev/cpuset/system-background/tasks
     shutdown critical
diff --git a/libs/binder/IMemory.cpp b/libs/binder/IMemory.cpp
index 507ce53..0b89879 100644
--- a/libs/binder/IMemory.cpp
+++ b/libs/binder/IMemory.cpp
@@ -86,7 +86,7 @@
     virtual void* getBase() const;
     virtual size_t getSize() const;
     virtual uint32_t getFlags() const;
-    virtual uint32_t getOffset() const;
+    off_t getOffset() const override;
 
 private:
     friend class IMemory;
@@ -113,7 +113,7 @@
     mutable void*       mBase;
     mutable size_t      mSize;
     mutable uint32_t    mFlags;
-    mutable uint32_t    mOffset;
+    mutable off_t       mOffset;
     mutable bool        mRealHeap;
     mutable Mutex       mLock;
 };
@@ -187,13 +187,16 @@
         data.writeInterfaceToken(IMemory::getInterfaceDescriptor());
         if (remote()->transact(GET_MEMORY, data, &reply) == NO_ERROR) {
             sp<IBinder> heap = reply.readStrongBinder();
-            ssize_t o = reply.readInt32();
-            size_t s = reply.readInt32();
             if (heap != nullptr) {
                 mHeap = interface_cast<IMemoryHeap>(heap);
                 if (mHeap != nullptr) {
+                    const int64_t offset64 = reply.readInt64();
+                    const uint64_t size64 = reply.readUint64();
+                    const ssize_t o = (ssize_t)offset64;
+                    const size_t s = (size_t)size64;
                     size_t heapSize = mHeap->getSize();
-                    if (s <= heapSize
+                    if (s == size64 && o == offset64 // ILP32 bounds check
+                            && s <= heapSize
                             && o >= 0
                             && (static_cast<size_t>(o) <= heapSize - s)) {
                         mOffset = o;
@@ -233,8 +236,8 @@
             ssize_t offset;
             size_t size;
             reply->writeStrongBinder( IInterface::asBinder(getMemory(&offset, &size)) );
-            reply->writeInt32(offset);
-            reply->writeInt32(size);
+            reply->writeInt64(offset);
+            reply->writeUint64(size);
             return NO_ERROR;
         } break;
         default:
@@ -313,18 +316,23 @@
         data.writeInterfaceToken(IMemoryHeap::getInterfaceDescriptor());
         status_t err = remote()->transact(HEAP_ID, data, &reply);
         int parcel_fd = reply.readFileDescriptor();
-        ssize_t size = reply.readInt32();
-        uint32_t flags = reply.readInt32();
-        uint32_t offset = reply.readInt32();
-
-        ALOGE_IF(err, "binder=%p transaction failed fd=%d, size=%zd, err=%d (%s)",
-                IInterface::asBinder(this).get(),
-                parcel_fd, size, err, strerror(-err));
+        const uint64_t size64 = reply.readUint64();
+        const int64_t offset64 = reply.readInt64();
+        const uint32_t flags = reply.readUint32();
+        const size_t size = (size_t)size64;
+        const off_t offset = (off_t)offset64;
+        if (err != NO_ERROR || // failed transaction
+                size != size64 || offset != offset64) { // ILP32 size check
+            ALOGE("binder=%p transaction failed fd=%d, size=%zu, err=%d (%s)",
+                    IInterface::asBinder(this).get(),
+                    parcel_fd, size, err, strerror(-err));
+            return;
+        }
 
         Mutex::Autolock _l(mLock);
         if (mHeapId.load(memory_order_relaxed) == -1) {
             int fd = fcntl(parcel_fd, F_DUPFD_CLOEXEC, 0);
-            ALOGE_IF(fd==-1, "cannot dup fd=%d, size=%zd, err=%d (%s)",
+            ALOGE_IF(fd == -1, "cannot dup fd=%d, size=%zu, err=%d (%s)",
                     parcel_fd, size, err, strerror(errno));
 
             int access = PROT_READ;
@@ -334,7 +342,7 @@
             mRealHeap = true;
             mBase = mmap(nullptr, size, access, MAP_SHARED, fd, offset);
             if (mBase == MAP_FAILED) {
-                ALOGE("cannot map BpMemoryHeap (binder=%p), size=%zd, fd=%d (%s)",
+                ALOGE("cannot map BpMemoryHeap (binder=%p), size=%zu, fd=%d (%s)",
                         IInterface::asBinder(this).get(), size, fd, strerror(errno));
                 close(fd);
             } else {
@@ -368,7 +376,7 @@
     return mFlags;
 }
 
-uint32_t BpMemoryHeap::getOffset() const {
+off_t BpMemoryHeap::getOffset() const {
     assertMapped();
     return mOffset;
 }
@@ -390,9 +398,9 @@
        case HEAP_ID: {
             CHECK_INTERFACE(IMemoryHeap, data, reply);
             reply->writeFileDescriptor(getHeapID());
-            reply->writeInt32(getSize());
-            reply->writeInt32(getFlags());
-            reply->writeInt32(getOffset());
+            reply->writeUint64(getSize());
+            reply->writeInt64(getOffset());
+            reply->writeUint32(getFlags());
             return NO_ERROR;
         } break;
         default:
diff --git a/libs/binder/MemoryHeapBase.cpp b/libs/binder/MemoryHeapBase.cpp
index 9850ad9..4c300b4 100644
--- a/libs/binder/MemoryHeapBase.cpp
+++ b/libs/binder/MemoryHeapBase.cpp
@@ -76,7 +76,7 @@
     }
 }
 
-MemoryHeapBase::MemoryHeapBase(int fd, size_t size, uint32_t flags, uint32_t offset)
+MemoryHeapBase::MemoryHeapBase(int fd, size_t size, uint32_t flags, off_t offset)
     : mFD(-1), mSize(0), mBase(MAP_FAILED), mFlags(flags),
       mDevice(nullptr), mNeedUnmap(false), mOffset(0)
 {
@@ -85,7 +85,7 @@
     mapfd(fcntl(fd, F_DUPFD_CLOEXEC, 0), size, offset);
 }
 
-status_t MemoryHeapBase::init(int fd, void *base, int size, int flags, const char* device)
+status_t MemoryHeapBase::init(int fd, void *base, size_t size, int flags, const char* device)
 {
     if (mFD != -1) {
         return INVALID_OPERATION;
@@ -98,13 +98,20 @@
     return NO_ERROR;
 }
 
-status_t MemoryHeapBase::mapfd(int fd, size_t size, uint32_t offset)
+status_t MemoryHeapBase::mapfd(int fd, size_t size, off_t offset)
 {
     if (size == 0) {
         // try to figure out the size automatically
         struct stat sb;
-        if (fstat(fd, &sb) == 0)
-            size = sb.st_size;
+        if (fstat(fd, &sb) == 0) {
+            size = (size_t)sb.st_size;
+            // sb.st_size is off_t which on ILP32 may be 64 bits while size_t is 32 bits.
+            if ((off_t)size != sb.st_size) {
+                ALOGE("%s: size of file %lld cannot fit in memory",
+                        __func__, (long long)sb.st_size);
+                return INVALID_OPERATION;
+            }
+        }
         // if it didn't work, let mmap() fail.
     }
 
@@ -112,12 +119,12 @@
         void* base = (uint8_t*)mmap(nullptr, size,
                 PROT_READ|PROT_WRITE, MAP_SHARED, fd, offset);
         if (base == MAP_FAILED) {
-            ALOGE("mmap(fd=%d, size=%u) failed (%s)",
-                    fd, uint32_t(size), strerror(errno));
+            ALOGE("mmap(fd=%d, size=%zu) failed (%s)",
+                    fd, size, strerror(errno));
             close(fd);
             return -errno;
         }
-        //ALOGD("mmap(fd=%d, base=%p, size=%lu)", fd, base, size);
+        //ALOGD("mmap(fd=%d, base=%p, size=%zu)", fd, base, size);
         mBase = base;
         mNeedUnmap = true;
     } else  {
@@ -140,7 +147,7 @@
     int fd = android_atomic_or(-1, &mFD);
     if (fd >= 0) {
         if (mNeedUnmap) {
-            //ALOGD("munmap(fd=%d, base=%p, size=%lu)", fd, mBase, mSize);
+            //ALOGD("munmap(fd=%d, base=%p, size=%zu)", fd, mBase, mSize);
             munmap(mBase, mSize);
         }
         mBase = nullptr;
@@ -169,7 +176,7 @@
     return mDevice;
 }
 
-uint32_t MemoryHeapBase::getOffset() const {
+off_t MemoryHeapBase::getOffset() const {
     return mOffset;
 }
 
diff --git a/libs/binder/include/binder/IMemory.h b/libs/binder/include/binder/IMemory.h
index 3099bf5..11f7efa 100644
--- a/libs/binder/include/binder/IMemory.h
+++ b/libs/binder/include/binder/IMemory.h
@@ -43,7 +43,7 @@
     virtual void*       getBase() const = 0;
     virtual size_t      getSize() const = 0;
     virtual uint32_t    getFlags() const = 0;
-    virtual uint32_t    getOffset() const = 0;
+    virtual off_t       getOffset() const = 0;
 
     // these are there just for backward source compatibility
     int32_t heapID() const { return getHeapID(); }
diff --git a/libs/binder/include/binder/MemoryHeapBase.h b/libs/binder/include/binder/MemoryHeapBase.h
index 5e0a382..2f5039d 100644
--- a/libs/binder/include/binder/MemoryHeapBase.h
+++ b/libs/binder/include/binder/MemoryHeapBase.h
@@ -42,7 +42,7 @@
      * maps the memory referenced by fd. but DOESN'T take ownership
      * of the filedescriptor (it makes a copy with dup()
      */
-    MemoryHeapBase(int fd, size_t size, uint32_t flags = 0, uint32_t offset = 0);
+    MemoryHeapBase(int fd, size_t size, uint32_t flags = 0, off_t offset = 0);
 
     /*
      * maps memory from the given device
@@ -64,7 +64,7 @@
 
     virtual size_t      getSize() const;
     virtual uint32_t    getFlags() const;
-    virtual uint32_t    getOffset() const;
+            off_t       getOffset() const override;
 
     const char*         getDevice() const;
 
@@ -82,11 +82,11 @@
 protected:
             MemoryHeapBase();
     // init() takes ownership of fd
-    status_t init(int fd, void *base, int size,
+    status_t init(int fd, void *base, size_t size,
             int flags = 0, const char* device = nullptr);
 
 private:
-    status_t mapfd(int fd, size_t size, uint32_t offset = 0);
+    status_t mapfd(int fd, size_t size, off_t offset = 0);
 
     int         mFD;
     size_t      mSize;
@@ -94,7 +94,7 @@
     uint32_t    mFlags;
     const char* mDevice;
     bool        mNeedUnmap;
-    uint32_t    mOffset;
+    off_t       mOffset;
 };
 
 // ---------------------------------------------------------------------------
diff --git a/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h b/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h
index faeb78f..bf0c956 100644
--- a/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h
+++ b/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h
@@ -76,34 +76,18 @@
     (*vec)[index] = value;
 }
 
-/**
- * Writes a vector to the next location in a non-null parcel.
- */
-template <typename T>
-static inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<T>& vec);
-
-/**
- * Reads a vector to the next location in a non-null parcel.
- */
-template <typename T>
-static inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<T>* vec);
-
 // @START
 /**
  * Writes a vector of int32_t to the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_writeVector<int32_t>(AParcel* parcel,
-                                                    const std::vector<int32_t>& vec) {
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<int32_t>& vec) {
     return AParcel_writeInt32Array(parcel, vec.data(), vec.size());
 }
 
 /**
  * Reads a vector of int32_t from the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_readVector<int32_t>(const AParcel* parcel,
-                                                   std::vector<int32_t>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<int32_t>* vec) {
     void* vectorData = static_cast<void*>(vec);
     return AParcel_readInt32Array(parcel, &vectorData, &AParcel_stdVectorReallocator<int32_t>,
                                   AParcel_stdVectorGetter<int32_t>);
@@ -112,18 +96,14 @@
 /**
  * Writes a vector of uint32_t to the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_writeVector<uint32_t>(AParcel* parcel,
-                                                     const std::vector<uint32_t>& vec) {
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<uint32_t>& vec) {
     return AParcel_writeUint32Array(parcel, vec.data(), vec.size());
 }
 
 /**
  * Reads a vector of uint32_t from the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_readVector<uint32_t>(const AParcel* parcel,
-                                                    std::vector<uint32_t>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<uint32_t>* vec) {
     void* vectorData = static_cast<void*>(vec);
     return AParcel_readUint32Array(parcel, &vectorData, &AParcel_stdVectorReallocator<uint32_t>,
                                    AParcel_stdVectorGetter<uint32_t>);
@@ -132,18 +112,14 @@
 /**
  * Writes a vector of int64_t to the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_writeVector<int64_t>(AParcel* parcel,
-                                                    const std::vector<int64_t>& vec) {
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<int64_t>& vec) {
     return AParcel_writeInt64Array(parcel, vec.data(), vec.size());
 }
 
 /**
  * Reads a vector of int64_t from the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_readVector<int64_t>(const AParcel* parcel,
-                                                   std::vector<int64_t>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<int64_t>* vec) {
     void* vectorData = static_cast<void*>(vec);
     return AParcel_readInt64Array(parcel, &vectorData, &AParcel_stdVectorReallocator<int64_t>,
                                   AParcel_stdVectorGetter<int64_t>);
@@ -152,18 +128,14 @@
 /**
  * Writes a vector of uint64_t to the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_writeVector<uint64_t>(AParcel* parcel,
-                                                     const std::vector<uint64_t>& vec) {
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<uint64_t>& vec) {
     return AParcel_writeUint64Array(parcel, vec.data(), vec.size());
 }
 
 /**
  * Reads a vector of uint64_t from the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_readVector<uint64_t>(const AParcel* parcel,
-                                                    std::vector<uint64_t>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<uint64_t>* vec) {
     void* vectorData = static_cast<void*>(vec);
     return AParcel_readUint64Array(parcel, &vectorData, &AParcel_stdVectorReallocator<uint64_t>,
                                    AParcel_stdVectorGetter<uint64_t>);
@@ -172,16 +144,14 @@
 /**
  * Writes a vector of float to the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_writeVector<float>(AParcel* parcel, const std::vector<float>& vec) {
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<float>& vec) {
     return AParcel_writeFloatArray(parcel, vec.data(), vec.size());
 }
 
 /**
  * Reads a vector of float from the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_readVector<float>(const AParcel* parcel, std::vector<float>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<float>* vec) {
     void* vectorData = static_cast<void*>(vec);
     return AParcel_readFloatArray(parcel, &vectorData, &AParcel_stdVectorReallocator<float>,
                                   AParcel_stdVectorGetter<float>);
@@ -190,17 +160,14 @@
 /**
  * Writes a vector of double to the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_writeVector<double>(AParcel* parcel,
-                                                   const std::vector<double>& vec) {
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<double>& vec) {
     return AParcel_writeDoubleArray(parcel, vec.data(), vec.size());
 }
 
 /**
  * Reads a vector of double from the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_readVector<double>(const AParcel* parcel, std::vector<double>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<double>* vec) {
     void* vectorData = static_cast<void*>(vec);
     return AParcel_readDoubleArray(parcel, &vectorData, &AParcel_stdVectorReallocator<double>,
                                    AParcel_stdVectorGetter<double>);
@@ -209,8 +176,7 @@
 /**
  * Writes a vector of bool to the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_writeVector<bool>(AParcel* parcel, const std::vector<bool>& vec) {
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<bool>& vec) {
     return AParcel_writeBoolArray(parcel, static_cast<const void*>(&vec),
                                   AParcel_stdVectorGetter<bool>, vec.size());
 }
@@ -218,8 +184,7 @@
 /**
  * Reads a vector of bool from the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_readVector<bool>(const AParcel* parcel, std::vector<bool>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<bool>* vec) {
     void* vectorData = static_cast<void*>(vec);
     return AParcel_readBoolArray(parcel, &vectorData, &AParcel_stdVectorReallocator<bool>,
                                  AParcel_stdVectorSetter<bool>);
@@ -228,18 +193,14 @@
 /**
  * Writes a vector of char16_t to the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_writeVector<char16_t>(AParcel* parcel,
-                                                     const std::vector<char16_t>& vec) {
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<char16_t>& vec) {
     return AParcel_writeCharArray(parcel, vec.data(), vec.size());
 }
 
 /**
  * Reads a vector of char16_t from the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_readVector<char16_t>(const AParcel* parcel,
-                                                    std::vector<char16_t>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<char16_t>* vec) {
     void* vectorData = static_cast<void*>(vec);
     return AParcel_readCharArray(parcel, &vectorData, &AParcel_stdVectorReallocator<char16_t>,
                                  AParcel_stdVectorGetter<char16_t>);
@@ -248,17 +209,14 @@
 /**
  * Writes a vector of int8_t to the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_writeVector<int8_t>(AParcel* parcel,
-                                                   const std::vector<int8_t>& vec) {
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<int8_t>& vec) {
     return AParcel_writeByteArray(parcel, vec.data(), vec.size());
 }
 
 /**
  * Reads a vector of int8_t from the next location in a non-null parcel.
  */
-template <>
-inline binder_status_t AParcel_readVector<int8_t>(const AParcel* parcel, std::vector<int8_t>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<int8_t>* vec) {
     void* vectorData = static_cast<void*>(vec);
     return AParcel_readByteArray(parcel, &vectorData, &AParcel_stdVectorReallocator<int8_t>,
                                  AParcel_stdVectorGetter<int8_t>);
diff --git a/libs/binder/ndk/scripts/gen_parcel_helper.py b/libs/binder/ndk/scripts/gen_parcel_helper.py
index 45f8d06..2cf10d3 100755
--- a/libs/binder/ndk/scripts/gen_parcel_helper.py
+++ b/libs/binder/ndk/scripts/gen_parcel_helper.py
@@ -152,8 +152,7 @@
         cpp_helper += "/**\n"
         cpp_helper += " * Writes a vector of " + cpp + " to the next location in a non-null parcel.\n"
         cpp_helper += " */\n"
-        cpp_helper += "template<>\n"
-        cpp_helper += "inline binder_status_t AParcel_writeVector<" + cpp + ">(AParcel* parcel, const std::vector<" + cpp + ">& vec) {\n"
+        cpp_helper += "inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<" + cpp + ">& vec) {\n"
         write_args = "vec.data()"
         if nca: write_args = "static_cast<const void*>(&vec), AParcel_stdVectorGetter<" + cpp + ">"
         cpp_helper += "    return AParcel_write" + pretty + "Array(parcel, " + write_args + ", vec.size());\n"
@@ -162,8 +161,7 @@
         cpp_helper += "/**\n"
         cpp_helper += " * Reads a vector of " + cpp + " from the next location in a non-null parcel.\n"
         cpp_helper += " */\n"
-        cpp_helper += "template<>\n"
-        cpp_helper += "inline binder_status_t AParcel_readVector<" + cpp + ">(const AParcel* parcel, std::vector<" + cpp + ">* vec) {\n"
+        cpp_helper += "inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<" + cpp + ">* vec) {\n"
         cpp_helper += "    void* vectorData = static_cast<void*>(vec);\n"
         read_args = []
         read_args += ["parcel"]
diff --git a/services/surfaceflinger/RenderEngine/Android.bp b/libs/renderengine/Android.bp
similarity index 97%
rename from services/surfaceflinger/RenderEngine/Android.bp
rename to libs/renderengine/Android.bp
index 79145c2..674659c 100644
--- a/services/surfaceflinger/RenderEngine/Android.bp
+++ b/libs/renderengine/Android.bp
@@ -26,7 +26,7 @@
         "libGLESv2",
         "libgui",
         "liblog",
-    	"libnativewindow",
+        "libnativewindow",
         "libui",
         "libutils",
     ],
diff --git a/services/surfaceflinger/RenderEngine/Description.cpp b/libs/renderengine/Description.cpp
similarity index 96%
rename from services/surfaceflinger/RenderEngine/Description.cpp
rename to libs/renderengine/Description.cpp
index 9696d28..b9cea10 100644
--- a/services/surfaceflinger/RenderEngine/Description.cpp
+++ b/libs/renderengine/Description.cpp
@@ -52,5 +52,5 @@
     return colorMatrix != identity;
 }
 
-}  // namespace renderengine
-}  // namespace android
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/Mesh.cpp b/libs/renderengine/Mesh.cpp
similarity index 97%
rename from services/surfaceflinger/RenderEngine/Mesh.cpp
rename to libs/renderengine/Mesh.cpp
index 809a0d7..6a40c6c 100644
--- a/services/surfaceflinger/RenderEngine/Mesh.cpp
+++ b/libs/renderengine/Mesh.cpp
@@ -91,5 +91,5 @@
     return mStride;
 }
 
-}  // namespace renderengine
-}  // namespace android
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/RenderEngine.cpp b/libs/renderengine/RenderEngine.cpp
similarity index 90%
rename from services/surfaceflinger/RenderEngine/RenderEngine.cpp
rename to libs/renderengine/RenderEngine.cpp
index 3b54873..8be1c3c 100644
--- a/services/surfaceflinger/RenderEngine/RenderEngine.cpp
+++ b/libs/renderengine/RenderEngine.cpp
@@ -39,8 +39,7 @@
 
 namespace impl {
 
-RenderEngine::RenderEngine(uint32_t featureFlags)
-      : mFeatureFlags(featureFlags) {}
+RenderEngine::RenderEngine(uint32_t featureFlags) : mFeatureFlags(featureFlags) {}
 
 RenderEngine::~RenderEngine() = default;
 
@@ -52,6 +51,6 @@
     return SyncFeatures::getInstance().useWaitSync();
 }
 
-}  // namespace impl
-}  // namespace renderengine
-}  // namespace android
+} // namespace impl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/TEST_MAPPING b/libs/renderengine/TEST_MAPPING
similarity index 100%
rename from services/surfaceflinger/RenderEngine/TEST_MAPPING
rename to libs/renderengine/TEST_MAPPING
diff --git a/services/surfaceflinger/RenderEngine/Texture.cpp b/libs/renderengine/Texture.cpp
similarity index 96%
rename from services/surfaceflinger/RenderEngine/Texture.cpp
rename to libs/renderengine/Texture.cpp
index 5eabbcf..154cde8 100644
--- a/services/surfaceflinger/RenderEngine/Texture.cpp
+++ b/libs/renderengine/Texture.cpp
@@ -73,5 +73,5 @@
     return mHeight;
 }
 
-}  // namespace renderengine
-}  // namespace android
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/GLES20RenderEngine.cpp b/libs/renderengine/gl/GLES20RenderEngine.cpp
similarity index 96%
rename from services/surfaceflinger/RenderEngine/gl/GLES20RenderEngine.cpp
rename to libs/renderengine/gl/GLES20RenderEngine.cpp
index dbf50c5..026b151 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLES20RenderEngine.cpp
+++ b/libs/renderengine/gl/GLES20RenderEngine.cpp
@@ -261,7 +261,7 @@
     contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
     contextAttributes.push_back(contextClientVersion);
     bool useContextPriority = extensions.hasContextPriority() &&
-                              (featureFlags & RenderEngine::USE_HIGH_PRIORITY_CONTEXT);
+            (featureFlags & RenderEngine::USE_HIGH_PRIORITY_CONTEXT);
     if (useContextPriority) {
         contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
         contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
@@ -589,15 +589,13 @@
     glDeleteTextures(count, names);
 }
 
-void GLES20RenderEngine::bindExternalTextureImage(uint32_t texName,
-                                                  const Image& image) {
+void GLES20RenderEngine::bindExternalTextureImage(uint32_t texName, const Image& image) {
     const GLImage& glImage = static_cast<const GLImage&>(image);
     const GLenum target = GL_TEXTURE_EXTERNAL_OES;
 
     glBindTexture(target, texName);
     if (glImage.getEGLImage() != EGL_NO_IMAGE_KHR) {
-        glEGLImageTargetTexture2DOES(target,
-                                     static_cast<GLeglImageOES>(glImage.getEGLImage()));
+        glEGLImageTargetTexture2DOES(target, static_cast<GLeglImageOES>(glImage.getEGLImage()));
     }
 }
 
@@ -613,16 +611,15 @@
 
     // Bind the Framebuffer to render into
     glBindFramebuffer(GL_FRAMEBUFFER, framebufferName);
-    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
-                           GL_TEXTURE_2D, textureName, 0);
+    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureName, 0);
 
     mRenderToFbo = true;
     mFboHeight = glFramebuffer->getBufferHeight();
 
     uint32_t glStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
 
-    ALOGE_IF(glStatus != GL_FRAMEBUFFER_COMPLETE_OES,
-             "glCheckFramebufferStatusOES error %d", glStatus);
+    ALOGE_IF(glStatus != GL_FRAMEBUFFER_COMPLETE_OES, "glCheckFramebufferStatusOES error %d",
+             glStatus);
 
     return glStatus == GL_FRAMEBUFFER_COMPLETE_OES ? NO_ERROR : BAD_VALUE;
 }
@@ -790,10 +787,10 @@
         Description managedState = mState;
         Dataspace inputStandard = static_cast<Dataspace>(mDataSpace & Dataspace::STANDARD_MASK);
         Dataspace inputTransfer = static_cast<Dataspace>(mDataSpace & Dataspace::TRANSFER_MASK);
-        Dataspace outputStandard = static_cast<Dataspace>(mOutputDataSpace &
-                                                          Dataspace::STANDARD_MASK);
-        Dataspace outputTransfer = static_cast<Dataspace>(mOutputDataSpace &
-                                                          Dataspace::TRANSFER_MASK);
+        Dataspace outputStandard =
+                static_cast<Dataspace>(mOutputDataSpace & Dataspace::STANDARD_MASK);
+        Dataspace outputTransfer =
+                static_cast<Dataspace>(mOutputDataSpace & Dataspace::TRANSFER_MASK);
         bool needsXYZConversion = needsXYZTransformMatrix();
 
         if (needsXYZConversion) {
@@ -847,9 +844,9 @@
         if (managedState.hasColorMatrix() || managedState.hasOutputTransformMatrix() ||
             inputTransfer != outputTransfer) {
             managedState.inputTransferFunction =
-                Description::dataSpaceToTransferFunction(inputTransfer);
+                    Description::dataSpaceToTransferFunction(inputTransfer);
             managedState.outputTransferFunction =
-                Description::dataSpaceToTransferFunction(outputTransfer);
+                    Description::dataSpaceToTransferFunction(outputTransfer);
         }
 
         ProgramCache::getInstance().useProgram(managedState);
@@ -921,7 +918,7 @@
     const Dataspace standard = static_cast<Dataspace>(dataSpace & Dataspace::STANDARD_MASK);
     const Dataspace transfer = static_cast<Dataspace>(dataSpace & Dataspace::TRANSFER_MASK);
     return standard == Dataspace::STANDARD_BT2020 &&
-        (transfer == Dataspace::TRANSFER_ST2084 || transfer == Dataspace::TRANSFER_HLG);
+            (transfer == Dataspace::TRANSFER_ST2084 || transfer == Dataspace::TRANSFER_HLG);
 }
 
 // For convenience, we want to convert the input color space to XYZ color space first,
@@ -938,8 +935,8 @@
     const bool isInputHdrDataSpace = isHdrDataSpace(mDataSpace);
     const bool isOutputHdrDataSpace = isHdrDataSpace(mOutputDataSpace);
     const Dataspace inputTransfer = static_cast<Dataspace>(mDataSpace & Dataspace::TRANSFER_MASK);
-    const Dataspace outputTransfer = static_cast<Dataspace>(mOutputDataSpace &
-                                                            Dataspace::TRANSFER_MASK);
+    const Dataspace outputTransfer =
+            static_cast<Dataspace>(mOutputDataSpace & Dataspace::TRANSFER_MASK);
 
     return (isInputHdrDataSpace || isOutputHdrDataSpace) && inputTransfer != outputTransfer;
 }
@@ -950,6 +947,6 @@
     mEGLContext = ctxt;
 }
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/GLES20RenderEngine.h b/libs/renderengine/gl/GLES20RenderEngine.h
similarity index 98%
rename from services/surfaceflinger/RenderEngine/gl/GLES20RenderEngine.h
rename to libs/renderengine/gl/GLES20RenderEngine.h
index b08e096..6ea8523 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLES20RenderEngine.h
+++ b/libs/renderengine/gl/GLES20RenderEngine.h
@@ -156,8 +156,8 @@
     const bool mUseColorManagement = false;
 };
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
 
 #endif /* SF_GLES20RENDERENGINE_H_ */
diff --git a/services/surfaceflinger/RenderEngine/gl/GLExtensions.cpp b/libs/renderengine/gl/GLExtensions.cpp
similarity index 97%
rename from services/surfaceflinger/RenderEngine/gl/GLExtensions.cpp
rename to libs/renderengine/gl/GLExtensions.cpp
index 0fdb9aa..784693b 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLExtensions.cpp
+++ b/libs/renderengine/gl/GLExtensions.cpp
@@ -122,6 +122,6 @@
     return mEGLExtensions.string();
 }
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/GLExtensions.h b/libs/renderengine/gl/GLExtensions.h
similarity index 96%
rename from services/surfaceflinger/RenderEngine/gl/GLExtensions.h
rename to libs/renderengine/gl/GLExtensions.h
index 02ad965..382c23a 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLExtensions.h
+++ b/libs/renderengine/gl/GLExtensions.h
@@ -75,8 +75,8 @@
     char const* getEGLExtensions() const;
 };
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
 
 #endif // ANDROID_SF_GLEXTENSION_H
diff --git a/services/surfaceflinger/RenderEngine/gl/GLFramebuffer.cpp b/libs/renderengine/gl/GLFramebuffer.cpp
similarity index 88%
rename from services/surfaceflinger/RenderEngine/gl/GLFramebuffer.cpp
rename to libs/renderengine/gl/GLFramebuffer.cpp
index 83d2bde..2bd4e7f 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLFramebuffer.cpp
+++ b/libs/renderengine/gl/GLFramebuffer.cpp
@@ -28,8 +28,7 @@
 namespace gl {
 
 GLFramebuffer::GLFramebuffer(const GLES20RenderEngine& engine)
-        : mEGLDisplay(engine.getEGLDisplay()),
-          mEGLImage(EGL_NO_IMAGE_KHR) {
+      : mEGLDisplay(engine.getEGLDisplay()), mEGLImage(EGL_NO_IMAGE_KHR) {
     glGenTextures(1, &mTextureName);
     glGenFramebuffers(1, &mFramebufferName);
 }
@@ -49,8 +48,7 @@
     }
 
     if (nativeBuffer) {
-        mEGLImage = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
-                                      EGL_NATIVE_BUFFER_ANDROID,
+        mEGLImage = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
                                       nativeBuffer, nullptr);
         if (mEGLImage == EGL_NO_IMAGE_KHR) {
             return false;
@@ -61,6 +59,6 @@
     return true;
 }
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/GLFramebuffer.h b/libs/renderengine/gl/GLFramebuffer.h
similarity index 95%
rename from services/surfaceflinger/RenderEngine/gl/GLFramebuffer.h
rename to libs/renderengine/gl/GLFramebuffer.h
index 193cbdc..90c6f4a 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLFramebuffer.h
+++ b/libs/renderengine/gl/GLFramebuffer.h
@@ -51,6 +51,6 @@
     int32_t mBufferWidth = 0;
 };
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/GLImage.cpp b/libs/renderengine/gl/GLImage.cpp
similarity index 96%
rename from services/surfaceflinger/RenderEngine/gl/GLImage.cpp
rename to libs/renderengine/gl/GLImage.cpp
index 746f3e7..5a92093 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLImage.cpp
+++ b/libs/renderengine/gl/GLImage.cpp
@@ -19,8 +19,8 @@
 #include <vector>
 
 #include <log/log.h>
-#include "GLExtensions.h"
 #include "GLES20RenderEngine.h"
+#include "GLExtensions.h"
 
 namespace android {
 namespace renderengine {
@@ -70,6 +70,6 @@
     return true;
 }
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/GLImage.h b/libs/renderengine/gl/GLImage.h
similarity index 94%
rename from services/surfaceflinger/RenderEngine/gl/GLImage.h
rename to libs/renderengine/gl/GLImage.h
index f670783..0e451f8 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLImage.h
+++ b/libs/renderengine/gl/GLImage.h
@@ -47,6 +47,6 @@
     DISALLOW_COPY_AND_ASSIGN(GLImage);
 };
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/GLSurface.cpp b/libs/renderengine/gl/GLSurface.cpp
similarity index 91%
rename from services/surfaceflinger/RenderEngine/gl/GLSurface.cpp
rename to libs/renderengine/gl/GLSurface.cpp
index 104af56..2d694e9 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLSurface.cpp
+++ b/libs/renderengine/gl/GLSurface.cpp
@@ -29,8 +29,8 @@
       : mEGLDisplay(engine.getEGLDisplay()), mEGLConfig(engine.getEGLConfig()) {
     // RE does not assume any config when EGL_KHR_no_config_context is supported
     if (mEGLConfig == EGL_NO_CONFIG_KHR) {
-        mEGLConfig = GLES20RenderEngine::chooseEglConfig(mEGLDisplay,
-                                                         PIXEL_FORMAT_RGBA_8888, false);
+        mEGLConfig =
+                GLES20RenderEngine::chooseEglConfig(mEGLDisplay, PIXEL_FORMAT_RGBA_8888, false);
     }
 }
 
@@ -100,6 +100,6 @@
     return mSurfaceHeight;
 }
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/GLSurface.h b/libs/renderengine/gl/GLSurface.h
similarity index 96%
rename from services/surfaceflinger/RenderEngine/gl/GLSurface.h
rename to libs/renderengine/gl/GLSurface.h
index 8aa223a..092d371 100644
--- a/services/surfaceflinger/RenderEngine/gl/GLSurface.h
+++ b/libs/renderengine/gl/GLSurface.h
@@ -71,6 +71,6 @@
     DISALLOW_COPY_AND_ASSIGN(GLSurface);
 };
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/Program.cpp b/libs/renderengine/gl/Program.cpp
similarity index 96%
rename from services/surfaceflinger/RenderEngine/gl/Program.cpp
rename to libs/renderengine/gl/Program.cpp
index 7ae5736..7d2ea90 100644
--- a/services/surfaceflinger/RenderEngine/gl/Program.cpp
+++ b/libs/renderengine/gl/Program.cpp
@@ -130,16 +130,15 @@
         // The output transform matrix and color matrix can be combined as one matrix
         // that is applied right before applying OETF.
         mat4 outputTransformMatrix = desc.colorMatrix * desc.outputTransformMatrix;
-        glUniformMatrix4fv(mOutputTransformMatrixLoc, 1, GL_FALSE,
-                           outputTransformMatrix.asArray());
+        glUniformMatrix4fv(mOutputTransformMatrixLoc, 1, GL_FALSE, outputTransformMatrix.asArray());
     }
     if (mDisplayMaxLuminanceLoc >= 0) {
-        glUniform1f(mDisplayMaxLuminanceLoc, desc.displayMaxLuminance) ;
+        glUniform1f(mDisplayMaxLuminanceLoc, desc.displayMaxLuminance);
     }
     // these uniforms are always present
     glUniformMatrix4fv(mProjectionMatrixLoc, 1, GL_FALSE, desc.projectionMatrix.asArray());
 }
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/Program.h b/libs/renderengine/gl/Program.h
similarity index 96%
rename from services/surfaceflinger/RenderEngine/gl/Program.h
rename to libs/renderengine/gl/Program.h
index b1ce8cf..99bf0f0 100644
--- a/services/surfaceflinger/RenderEngine/gl/Program.h
+++ b/libs/renderengine/gl/Program.h
@@ -87,8 +87,8 @@
     GLint mOutputTransformMatrixLoc;
 };
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
 
 #endif /* SF_RENDER_ENGINE_PROGRAM_H */
diff --git a/services/surfaceflinger/RenderEngine/gl/ProgramCache.cpp b/libs/renderengine/gl/ProgramCache.cpp
similarity index 97%
rename from services/surfaceflinger/RenderEngine/gl/ProgramCache.cpp
rename to libs/renderengine/gl/ProgramCache.cpp
index 6d431b6..464fc15 100644
--- a/services/surfaceflinger/RenderEngine/gl/ProgramCache.cpp
+++ b/libs/renderengine/gl/ProgramCache.cpp
@@ -130,18 +130,18 @@
                               : description.texture.getTextureTarget() == GL_TEXTURE_2D
                                       ? Key::TEXTURE_2D
                                       : Key::TEXTURE_OFF)
-            .set(Key::ALPHA_MASK,
-                 (description.color.a < 1) ? Key::ALPHA_LT_ONE : Key::ALPHA_EQ_ONE)
+            .set(Key::ALPHA_MASK, (description.color.a < 1) ? Key::ALPHA_LT_ONE : Key::ALPHA_EQ_ONE)
             .set(Key::BLEND_MASK,
                  description.isPremultipliedAlpha ? Key::BLEND_PREMULT : Key::BLEND_NORMAL)
             .set(Key::OPACITY_MASK,
                  description.isOpaque ? Key::OPACITY_OPAQUE : Key::OPACITY_TRANSLUCENT)
             .set(Key::Key::INPUT_TRANSFORM_MATRIX_MASK,
-                 description.hasInputTransformMatrix() ?
-                     Key::INPUT_TRANSFORM_MATRIX_ON : Key::INPUT_TRANSFORM_MATRIX_OFF)
+                 description.hasInputTransformMatrix() ? Key::INPUT_TRANSFORM_MATRIX_ON
+                                                       : Key::INPUT_TRANSFORM_MATRIX_OFF)
             .set(Key::Key::OUTPUT_TRANSFORM_MATRIX_MASK,
-                 description.hasOutputTransformMatrix() || description.hasColorMatrix() ?
-                     Key::OUTPUT_TRANSFORM_MATRIX_ON : Key::OUTPUT_TRANSFORM_MATRIX_OFF);
+                 description.hasOutputTransformMatrix() || description.hasColorMatrix()
+                         ? Key::OUTPUT_TRANSFORM_MATRIX_ON
+                         : Key::OUTPUT_TRANSFORM_MATRIX_OFF);
 
     needs.set(Key::Y410_BT2020_MASK,
               description.isY410BT2020 ? Key::Y410_BT2020_ON : Key::Y410_BT2020_OFF);
@@ -631,7 +631,8 @@
             // avoid divide by 0 by adding 0.5/256 to the alpha channel
             fs << "gl_FragColor.rgb = gl_FragColor.rgb / (gl_FragColor.a + 0.0019);";
         }
-        fs << "gl_FragColor.rgb = OETF(OutputTransform(OOTF(InputTransform(EOTF(gl_FragColor.rgb)))));";
+        fs << "gl_FragColor.rgb = "
+              "OETF(OutputTransform(OOTF(InputTransform(EOTF(gl_FragColor.rgb)))));";
         if (!needs.isOpaque() && needs.isPremultiplied()) {
             // and re-premultiply if needed after gamma correction
             fs << "gl_FragColor.rgb = gl_FragColor.rgb * (gl_FragColor.a + 0.0019);";
@@ -678,6 +679,6 @@
     }
 }
 
-}  // namespace gl
-}  // namespace renderengine
-}  // namespace android
+} // namespace gl
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/gl/ProgramCache.h b/libs/renderengine/gl/ProgramCache.h
similarity index 95%
rename from services/surfaceflinger/RenderEngine/gl/ProgramCache.h
rename to libs/renderengine/gl/ProgramCache.h
index 120b3d1..d60fee6 100644
--- a/services/surfaceflinger/RenderEngine/gl/ProgramCache.h
+++ b/libs/renderengine/gl/ProgramCache.h
@@ -159,14 +159,10 @@
 
         // for use by std::unordered_map
 
-        bool operator==(const Key& other) const {
-            return mKey == other.mKey;
-        }
+        bool operator==(const Key& other) const { return mKey == other.mKey; }
 
         struct Hash {
-            size_t operator()(const Key& key) const {
-                return static_cast<size_t>(key.mKey);
-            }
+            size_t operator()(const Key& key) const { return static_cast<size_t>(key.mKey); }
         };
     };
 
@@ -205,11 +201,11 @@
     std::unordered_map<Key, std::unique_ptr<Program>, Key::Hash> mCache;
 };
 
-}  // namespace gl
-}  // namespace renderengine
+} // namespace gl
+} // namespace renderengine
 
 ANDROID_BASIC_TYPES_TRAITS(renderengine::gl::ProgramCache::Key)
 
-}  // namespace android
+} // namespace android
 
 #endif /* SF_RENDER_ENGINE_PROGRAMCACHE_H */
diff --git a/services/surfaceflinger/RenderEngine/include/renderengine/DisplaySettings.h b/libs/renderengine/include/renderengine/DisplaySettings.h
similarity index 100%
rename from services/surfaceflinger/RenderEngine/include/renderengine/DisplaySettings.h
rename to libs/renderengine/include/renderengine/DisplaySettings.h
diff --git a/services/surfaceflinger/RenderEngine/include/renderengine/Framebuffer.h b/libs/renderengine/include/renderengine/Framebuffer.h
similarity index 93%
rename from services/surfaceflinger/RenderEngine/include/renderengine/Framebuffer.h
rename to libs/renderengine/include/renderengine/Framebuffer.h
index 6595466..558b9c7 100644
--- a/services/surfaceflinger/RenderEngine/include/renderengine/Framebuffer.h
+++ b/libs/renderengine/include/renderengine/Framebuffer.h
@@ -30,5 +30,5 @@
     virtual bool setNativeWindowBuffer(ANativeWindowBuffer* nativeBuffer) = 0;
 };
 
-}   // namespace renderengine
-}   // namespace android
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/include/renderengine/Image.h b/libs/renderengine/include/renderengine/Image.h
similarity index 93%
rename from services/surfaceflinger/RenderEngine/include/renderengine/Image.h
rename to libs/renderengine/include/renderengine/Image.h
index 85ec91a..3bb4731 100644
--- a/services/surfaceflinger/RenderEngine/include/renderengine/Image.h
+++ b/libs/renderengine/include/renderengine/Image.h
@@ -27,6 +27,5 @@
     virtual bool setNativeWindowBuffer(ANativeWindowBuffer* buffer, bool isProtected) = 0;
 };
 
-}  // namespace renderengine
-}  // namespace android
-
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/include/renderengine/LayerSettings.h b/libs/renderengine/include/renderengine/LayerSettings.h
similarity index 100%
rename from services/surfaceflinger/RenderEngine/include/renderengine/LayerSettings.h
rename to libs/renderengine/include/renderengine/LayerSettings.h
diff --git a/services/surfaceflinger/RenderEngine/include/renderengine/Mesh.h b/libs/renderengine/include/renderengine/Mesh.h
similarity index 97%
rename from services/surfaceflinger/RenderEngine/include/renderengine/Mesh.h
rename to libs/renderengine/include/renderengine/Mesh.h
index 15d2a11..fe9022d 100644
--- a/services/surfaceflinger/RenderEngine/include/renderengine/Mesh.h
+++ b/libs/renderengine/include/renderengine/Mesh.h
@@ -101,6 +101,6 @@
     Primitive mPrimitive;
 };
 
-}  // namespace renderengine
-}  // namespace android
+} // namespace renderengine
+} // namespace android
 #endif /* SF_RENDER_ENGINE_MESH_H */
diff --git a/services/surfaceflinger/RenderEngine/include/renderengine/RenderEngine.h b/libs/renderengine/include/renderengine/RenderEngine.h
similarity index 93%
rename from services/surfaceflinger/RenderEngine/include/renderengine/RenderEngine.h
rename to libs/renderengine/include/renderengine/RenderEngine.h
index f5d3d6b..becb3c3 100644
--- a/services/surfaceflinger/RenderEngine/include/renderengine/RenderEngine.h
+++ b/libs/renderengine/include/renderengine/RenderEngine.h
@@ -58,7 +58,7 @@
 class RenderEngine {
 public:
     enum FeatureFlag {
-        USE_COLOR_MANAGEMENT = 1 << 0, // Device manages color
+        USE_COLOR_MANAGEMENT = 1 << 0,      // Device manages color
         USE_HIGH_PRIORITY_CONTEXT = 1 << 1, // Use high priority context
     };
 
@@ -100,8 +100,8 @@
     virtual bool waitFence(base::unique_fd fenceFd) = 0;
 
     virtual void clearWithColor(float red, float green, float blue, float alpha) = 0;
-    virtual void fillRegionWithColor(const Region& region, float red, float green,
-                                     float blue, float alpha) = 0;
+    virtual void fillRegionWithColor(const Region& region, float red, float green, float blue,
+                                     float alpha) = 0;
 
     virtual void setScissor(const Rect& region) = 0;
     virtual void disableScissor() = 0;
@@ -176,11 +176,10 @@
 class BindNativeBufferAsFramebuffer {
 public:
     BindNativeBufferAsFramebuffer(RenderEngine& engine, ANativeWindowBuffer* buffer)
-          : mEngine(engine),
-            mFramebuffer(mEngine.createFramebuffer()),
-            mStatus(NO_ERROR) {
-        mStatus = mFramebuffer->setNativeWindowBuffer(buffer) ?
-                  mEngine.bindFrameBuffer(mFramebuffer.get()) : NO_MEMORY;
+          : mEngine(engine), mFramebuffer(mEngine.createFramebuffer()), mStatus(NO_ERROR) {
+        mStatus = mFramebuffer->setNativeWindowBuffer(buffer)
+                ? mEngine.bindFrameBuffer(mFramebuffer.get())
+                : NO_MEMORY;
     }
     ~BindNativeBufferAsFramebuffer() {
         mFramebuffer->setNativeWindowBuffer(nullptr);
@@ -209,8 +208,8 @@
     const uint32_t mFeatureFlags;
 };
 
-}  // namespace impl
-}  // namespace renderengine
-}  // namespace android
+} // namespace impl
+} // namespace renderengine
+} // namespace android
 
 #endif /* SF_RENDERENGINE_H_ */
diff --git a/services/surfaceflinger/RenderEngine/include/renderengine/Surface.h b/libs/renderengine/include/renderengine/Surface.h
similarity index 95%
rename from services/surfaceflinger/RenderEngine/include/renderengine/Surface.h
rename to libs/renderengine/include/renderengine/Surface.h
index 3999ddc..ba7331d 100644
--- a/services/surfaceflinger/RenderEngine/include/renderengine/Surface.h
+++ b/libs/renderengine/include/renderengine/Surface.h
@@ -42,5 +42,5 @@
     virtual int32_t getHeight() const = 0;
 };
 
-}  // namespace renderengine
-}  // namespace android
+} // namespace renderengine
+} // namespace android
diff --git a/services/surfaceflinger/RenderEngine/include/renderengine/Texture.h b/libs/renderengine/include/renderengine/Texture.h
similarity index 96%
rename from services/surfaceflinger/RenderEngine/include/renderengine/Texture.h
rename to libs/renderengine/include/renderengine/Texture.h
index fb3e0cc..c69ace0 100644
--- a/services/surfaceflinger/RenderEngine/include/renderengine/Texture.h
+++ b/libs/renderengine/include/renderengine/Texture.h
@@ -55,6 +55,6 @@
     mat4 mTextureMatrix;
 };
 
-}  // namespace renderengine
-}  // namespace android
+} // namespace renderengine
+} // namespace android
 #endif /* SF_RENDER_ENGINE_TEXTURE_H */
diff --git a/services/surfaceflinger/RenderEngine/include/renderengine/private/Description.h b/libs/renderengine/include/renderengine/private/Description.h
similarity index 95%
rename from services/surfaceflinger/RenderEngine/include/renderengine/private/Description.h
rename to libs/renderengine/include/renderengine/private/Description.h
index 911bb7a..eadd656 100644
--- a/services/surfaceflinger/RenderEngine/include/renderengine/private/Description.h
+++ b/libs/renderengine/include/renderengine/private/Description.h
@@ -17,8 +17,8 @@
 #ifndef SF_RENDER_ENGINE_DESCRIPTION_H_
 #define SF_RENDER_ENGINE_DESCRIPTION_H_
 
-#include <ui/GraphicTypes.h>
 #include <renderengine/Texture.h>
+#include <ui/GraphicTypes.h>
 
 namespace android {
 namespace renderengine {
@@ -33,7 +33,7 @@
         LINEAR,
         SRGB,
         ST2084,
-        HLG,  // Hybrid Log-Gamma for HDR.
+        HLG, // Hybrid Log-Gamma for HDR.
     };
 
     static TransferFunction dataSpaceToTransferFunction(ui::Dataspace dataSpace);
@@ -75,7 +75,7 @@
     mat4 outputTransformMatrix;
 };
 
-}  // namespace renderengine
-}  // namespace android
+} // namespace renderengine
+} // namespace android
 
 #endif /* SF_RENDER_ENGINE_DESCRIPTION_H_ */
diff --git a/services/surfaceflinger/RenderEngine/tests/Android.bp b/libs/renderengine/tests/Android.bp
similarity index 100%
rename from services/surfaceflinger/RenderEngine/tests/Android.bp
rename to libs/renderengine/tests/Android.bp
diff --git a/services/surfaceflinger/RenderEngine/tests/RenderEngineTest.cpp b/libs/renderengine/tests/RenderEngineTest.cpp
similarity index 100%
rename from services/surfaceflinger/RenderEngine/tests/RenderEngineTest.cpp
rename to libs/renderengine/tests/RenderEngineTest.cpp
diff --git a/libs/ui/BufferHubBuffer.cpp b/libs/ui/BufferHubBuffer.cpp
index 44a947e..a6e6d73 100644
--- a/libs/ui/BufferHubBuffer.cpp
+++ b/libs/ui/BufferHubBuffer.cpp
@@ -159,7 +159,7 @@
 
     // If all imports succeed, replace the previous buffer and id.
     mId = bufferId;
-    mBufferStateBit = bufferTraits.buffer_state_bit();
+    mClientStateMask = bufferTraits.client_state_mask();
 
     // TODO(b/112012161) Set up shared fences.
     ALOGD("BufferHubBuffer::ImportGraphicBuffer: id=%d, buffer_state=%" PRIx64 ".", id(),
diff --git a/libs/ui/include/ui/BufferHubBuffer.h b/libs/ui/include/ui/BufferHubBuffer.h
index cefe5b3..daf6192 100644
--- a/libs/ui/include/ui/BufferHubBuffer.h
+++ b/libs/ui/include/ui/BufferHubBuffer.h
@@ -88,7 +88,7 @@
 
     // A state mask which is unique to a buffer hub client among all its siblings sharing the same
     // concrete graphic buffer.
-    uint64_t buffer_state_bit() const { return mBufferStateBit; }
+    uint64_t client_state_mask() const { return mClientStateMask; }
 
     size_t user_metadata_size() const { return mMetadata.user_metadata_size(); }
 
@@ -126,7 +126,7 @@
 
     // Global id for the buffer that is consistent across processes.
     int mId = -1;
-    uint64_t mBufferStateBit = 0;
+    uint64_t mClientStateMask = 0;
 
     // Wrapps the gralloc buffer handle of this buffer.
     dvr::NativeHandleWrapper<pdx::LocalHandle> mBufferHandle;
diff --git a/libs/ui/tests/BufferHubBuffer_test.cpp b/libs/ui/tests/BufferHubBuffer_test.cpp
index be06ad2..f0253b2 100644
--- a/libs/ui/tests/BufferHubBuffer_test.cpp
+++ b/libs/ui/tests/BufferHubBuffer_test.cpp
@@ -100,12 +100,12 @@
     // These two buffer instances are based on the same physical buffer under the
     // hood, so they should share the same id.
     EXPECT_EQ(id1, id2);
-    // We use buffer_state_bit() to tell those two instances apart.
-    EXPECT_NE(b1->buffer_state_bit(), b2->buffer_state_bit());
-    EXPECT_NE(b1->buffer_state_bit(), 0ULL);
-    EXPECT_NE(b2->buffer_state_bit(), 0ULL);
-    EXPECT_NE(b1->buffer_state_bit(), kProducerStateBit);
-    EXPECT_NE(b2->buffer_state_bit(), kProducerStateBit);
+    // We use client_state_mask() to tell those two instances apart.
+    EXPECT_NE(b1->client_state_mask(), b2->client_state_mask());
+    EXPECT_NE(b1->client_state_mask(), 0ULL);
+    EXPECT_NE(b2->client_state_mask(), 0ULL);
+    EXPECT_NE(b1->client_state_mask(), kProducerStateBit);
+    EXPECT_NE(b2->client_state_mask(), kProducerStateBit);
 
     // Both buffer instances should be in gained state.
     EXPECT_TRUE(IsBufferGained(b1->buffer_state()));
diff --git a/libs/vr/libbufferhub/buffer_hub-test.cpp b/libs/vr/libbufferhub/buffer_hub-test.cpp
index 4d98dfc..3e26dae 100644
--- a/libs/vr/libbufferhub/buffer_hub-test.cpp
+++ b/libs/vr/libbufferhub/buffer_hub-test.cpp
@@ -59,19 +59,19 @@
   ASSERT_TRUE(c2.get() != nullptr);
 
   // Producer state mask is unique, i.e. 1.
-  EXPECT_EQ(p->buffer_state_bit(), kProducerStateBit);
+  EXPECT_EQ(p->client_state_mask(), kProducerStateBit);
   // Consumer state mask cannot have producer bit on.
-  EXPECT_EQ(c->buffer_state_bit() & kProducerStateBit, 0U);
+  EXPECT_EQ(c->client_state_mask() & kProducerStateBit, 0U);
   // Consumer state mask must be a single, i.e. power of 2.
-  EXPECT_NE(c->buffer_state_bit(), 0U);
-  EXPECT_EQ(c->buffer_state_bit() & (c->buffer_state_bit() - 1), 0U);
+  EXPECT_NE(c->client_state_mask(), 0U);
+  EXPECT_EQ(c->client_state_mask() & (c->client_state_mask() - 1), 0U);
   // Consumer state mask cannot have producer bit on.
-  EXPECT_EQ(c2->buffer_state_bit() & kProducerStateBit, 0U);
+  EXPECT_EQ(c2->client_state_mask() & kProducerStateBit, 0U);
   // Consumer state mask must be a single, i.e. power of 2.
-  EXPECT_NE(c2->buffer_state_bit(), 0U);
-  EXPECT_EQ(c2->buffer_state_bit() & (c2->buffer_state_bit() - 1), 0U);
+  EXPECT_NE(c2->client_state_mask(), 0U);
+  EXPECT_EQ(c2->client_state_mask() & (c2->client_state_mask() - 1), 0U);
   // Each consumer should have unique bit.
-  EXPECT_EQ(c->buffer_state_bit() & c2->buffer_state_bit(), 0U);
+  EXPECT_EQ(c->client_state_mask() & c2->client_state_mask(), 0U);
 
   // Initial state: producer not available, consumers not available.
   EXPECT_EQ(0, RETRY_EINTR(p->Poll(kPollTimeoutMs)));
@@ -178,16 +178,16 @@
   ASSERT_TRUE(p.get() != nullptr);
 
   // It's ok to create up to kMaxConsumerCount consumer buffers.
-  uint64_t buffer_state_bits = p->buffer_state_bit();
+  uint64_t client_state_masks = p->client_state_mask();
   std::array<std::unique_ptr<ConsumerBuffer>, kMaxConsumerCount> cs;
   for (size_t i = 0; i < kMaxConsumerCount; i++) {
     cs[i] = ConsumerBuffer::Import(p->CreateConsumer());
     ASSERT_TRUE(cs[i].get() != nullptr);
     // Expect all buffers have unique state mask.
-    EXPECT_EQ(buffer_state_bits & cs[i]->buffer_state_bit(), 0U);
-    buffer_state_bits |= cs[i]->buffer_state_bit();
+    EXPECT_EQ(client_state_masks & cs[i]->client_state_mask(), 0U);
+    client_state_masks |= cs[i]->client_state_mask();
   }
-  EXPECT_EQ(buffer_state_bits, kProducerStateBit | kConsumerStateMask);
+  EXPECT_EQ(client_state_masks, kProducerStateBit | kConsumerStateMask);
 
   // The 64th creation will fail with out-of-memory error.
   auto state = p->CreateConsumer();
@@ -195,14 +195,14 @@
 
   // Release any consumer should allow us to re-create.
   for (size_t i = 0; i < kMaxConsumerCount; i++) {
-    buffer_state_bits &= ~cs[i]->buffer_state_bit();
+    client_state_masks &= ~cs[i]->client_state_mask();
     cs[i] = nullptr;
     cs[i] = ConsumerBuffer::Import(p->CreateConsumer());
     ASSERT_TRUE(cs[i].get() != nullptr);
     // The released state mask will be reused.
-    EXPECT_EQ(buffer_state_bits & cs[i]->buffer_state_bit(), 0U);
-    buffer_state_bits |= cs[i]->buffer_state_bit();
-    EXPECT_EQ(buffer_state_bits, kProducerStateBit | kConsumerStateMask);
+    EXPECT_EQ(client_state_masks & cs[i]->client_state_mask(), 0U);
+    client_state_masks |= cs[i]->client_state_mask();
+    EXPECT_EQ(client_state_masks, kProducerStateBit | kConsumerStateMask);
   }
 }
 
@@ -328,6 +328,36 @@
   EXPECT_FALSE(invalid_fence.IsValid());
 }
 
+TEST_F(LibBufferHubTest, TestGainPostedBuffer) {
+  std::unique_ptr<ProducerBuffer> p = ProducerBuffer::Create(
+      kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t));
+  ASSERT_TRUE(p.get() != nullptr);
+
+  // The producer buffer starts in gained state. Post the buffer.
+  ASSERT_EQ(0, p->Post(LocalHandle()));
+
+  // Gain in posted state should only succeed with gain_posted_buffer = true.
+  LocalHandle invalid_fence;
+  EXPECT_EQ(-EBUSY, p->Gain(&invalid_fence, false));
+  EXPECT_EQ(0, p->Gain(&invalid_fence, true));
+}
+
+TEST_F(LibBufferHubTest, TestGainPostedBufferAsync) {
+  std::unique_ptr<ProducerBuffer> p = ProducerBuffer::Create(
+      kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t));
+  ASSERT_TRUE(p.get() != nullptr);
+
+  // The producer buffer starts in gained state. Post the buffer.
+  ASSERT_EQ(0, p->Post(LocalHandle()));
+
+  // GainAsync in posted state should only succeed with gain_posted_buffer
+  // equals true.
+  DvrNativeBufferMetadata metadata;
+  LocalHandle invalid_fence;
+  EXPECT_EQ(-EBUSY, p->GainAsync(&metadata, &invalid_fence, false));
+  EXPECT_EQ(0, p->GainAsync(&metadata, &invalid_fence, true));
+}
+
 TEST_F(LibBufferHubTest, TestZeroConsumer) {
   std::unique_ptr<ProducerBuffer> p = ProducerBuffer::Create(
       kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t));
@@ -372,7 +402,7 @@
   EXPECT_TRUE(IsBufferPosted(p->buffer_state()));
   for (size_t i = 0; i < kMaxConsumerCount; i++) {
     EXPECT_TRUE(
-        IsBufferPosted(cs[i]->buffer_state(), cs[i]->buffer_state_bit()));
+        IsBufferPosted(cs[i]->buffer_state(), cs[i]->client_state_mask()));
     EXPECT_LT(0, RETRY_EINTR(cs[i]->Poll(kPollTimeoutMs)));
     EXPECT_EQ(0, cs[i]->AcquireAsync(&metadata, &invalid_fence));
     EXPECT_TRUE(IsBufferAcquired(p->buffer_state()));
@@ -677,7 +707,7 @@
   std::unique_ptr<ConsumerBuffer> c1 =
       ConsumerBuffer::Import(p->CreateConsumer());
   ASSERT_TRUE(c1.get() != nullptr);
-  const uint64_t consumer_state_bit1 = c1->buffer_state_bit();
+  const uint64_t consumer_state_bit1 = c1->client_state_mask();
 
   DvrNativeBufferMetadata meta;
   EXPECT_EQ(0, p->PostAsync(&meta, LocalHandle()));
@@ -693,7 +723,7 @@
   std::unique_ptr<ConsumerBuffer> c2 =
       ConsumerBuffer::Import(p->CreateConsumer());
   ASSERT_TRUE(c2.get() != nullptr);
-  const uint64_t consumer_state_bit2 = c2->buffer_state_bit();
+  const uint64_t consumer_state_bit2 = c2->client_state_mask();
   EXPECT_NE(consumer_state_bit1, consumer_state_bit2);
 
   // The new consumer is available for acquire.
@@ -709,7 +739,7 @@
   std::unique_ptr<ConsumerBuffer> c3 =
       ConsumerBuffer::Import(p->CreateConsumer());
   ASSERT_TRUE(c3.get() != nullptr);
-  const uint64_t consumer_state_bit3 = c3->buffer_state_bit();
+  const uint64_t consumer_state_bit3 = c3->client_state_mask();
   EXPECT_NE(consumer_state_bit2, consumer_state_bit3);
   // The consumer buffer is not acquirable.
   EXPECT_GE(0, RETRY_EINTR(c3->Poll(kPollTimeoutMs)));
@@ -881,12 +911,12 @@
   // These two buffer instances are based on the same physical buffer under the
   // hood, so they should share the same id.
   EXPECT_EQ(b1_id, b2_id);
-  // We use buffer_state_bit() to tell those two instances apart.
-  EXPECT_NE(b1->buffer_state_bit(), b2->buffer_state_bit());
-  EXPECT_NE(b1->buffer_state_bit(), 0ULL);
-  EXPECT_NE(b2->buffer_state_bit(), 0ULL);
-  EXPECT_NE(b1->buffer_state_bit(), kProducerStateBit);
-  EXPECT_NE(b2->buffer_state_bit(), kProducerStateBit);
+  // We use client_state_mask() to tell those two instances apart.
+  EXPECT_NE(b1->client_state_mask(), b2->client_state_mask());
+  EXPECT_NE(b1->client_state_mask(), 0ULL);
+  EXPECT_NE(b2->client_state_mask(), 0ULL);
+  EXPECT_NE(b1->client_state_mask(), kProducerStateBit);
+  EXPECT_NE(b2->client_state_mask(), kProducerStateBit);
 
   // Both buffer instances should be in gained state.
   EXPECT_TRUE(IsBufferGained(b1->buffer_state()));
diff --git a/libs/vr/libbufferhub/buffer_hub_base.cpp b/libs/vr/libbufferhub/buffer_hub_base.cpp
index bc6aece..b4c5d42 100644
--- a/libs/vr/libbufferhub/buffer_hub_base.cpp
+++ b/libs/vr/libbufferhub/buffer_hub_base.cpp
@@ -114,7 +114,7 @@
 
   id_ = new_id;
   cid_ = buffer_desc.buffer_cid();
-  buffer_state_bit_ = buffer_desc.buffer_state_bit();
+  client_state_mask_ = buffer_desc.client_state_mask();
 
   // Note that here the buffer_state, fence_state and active_clients_bit_mask
   // are mapped from shared memory as an atomic object. The std::atomic's
@@ -169,7 +169,7 @@
       // If ready fence is valid, we put that into the epoll set.
       epoll_event event;
       event.events = EPOLLIN;
-      event.data.u64 = buffer_state_bit();
+      event.data.u64 = client_state_mask();
       pending_fence_fd_ = new_fence.Duplicate();
       if (epoll_ctl(shared_fence.Get(), EPOLL_CTL_ADD, pending_fence_fd_.Get(),
                     &event) < 0) {
@@ -182,12 +182,12 @@
       }
       // Set bit in fence state to indicate that there is a fence from this
       // producer or consumer.
-      fence_state_->fetch_or(buffer_state_bit());
+      fence_state_->fetch_or(client_state_mask());
     } else {
       // Unset bit in fence state to indicate that there is no fence, so that
       // when consumer to acquire or producer to acquire, it knows no need to
       // check fence for this buffer.
-      fence_state_->fetch_and(~buffer_state_bit());
+      fence_state_->fetch_and(~client_state_mask());
     }
   }
 
diff --git a/libs/vr/libbufferhub/consumer_buffer.cpp b/libs/vr/libbufferhub/consumer_buffer.cpp
index c9d8554..a91e842 100644
--- a/libs/vr/libbufferhub/consumer_buffer.cpp
+++ b/libs/vr/libbufferhub/consumer_buffer.cpp
@@ -39,10 +39,10 @@
   // The buffer is can be acquired iff: 1) producer bit is set; 2) consumer bit
   // is not set.
   uint64_t buffer_state = buffer_state_->load();
-  if (!BufferHubDefs::IsBufferPosted(buffer_state, buffer_state_bit())) {
+  if (!BufferHubDefs::IsBufferPosted(buffer_state, client_state_mask())) {
     ALOGE("ConsumerBuffer::LocalAcquire: not posted, id=%d state=%" PRIx64
-          " buffer_state_bit=%" PRIx64 ".",
-          id(), buffer_state, buffer_state_bit());
+          " client_state_mask=%" PRIx64 ".",
+          id(), buffer_state, client_state_mask());
     return -EBUSY;
   }
 
@@ -64,7 +64,7 @@
   }
 
   // Set the consumer bit unique to this consumer.
-  BufferHubDefs::ModifyBufferState(buffer_state_, 0ULL, buffer_state_bit());
+  BufferHubDefs::ModifyBufferState(buffer_state_, 0ULL, client_state_mask());
   return 0;
 }
 
diff --git a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h
index 282be46..1ea8302 100644
--- a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h
+++ b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h
@@ -94,7 +94,7 @@
 
   // A state mask which is unique to a buffer hub client among all its siblings
   // sharing the same concrete graphic buffer.
-  uint64_t buffer_state_bit() const { return buffer_state_bit_; }
+  uint64_t client_state_mask() const { return client_state_mask_; }
 
   // The following methods return settings of the first buffer. Currently,
   // it is only possible to create multi-buffer BufferHubBases with the same
@@ -157,7 +157,7 @@
 
   // Client bit mask which indicates the locations of this client object in the
   // buffer_state_.
-  uint64_t buffer_state_bit_{0ULL};
+  uint64_t client_state_mask_{0ULL};
   IonBuffer buffer_;
   IonBuffer metadata_buffer_;
 };
diff --git a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h
index 49f9c3e..4953f9b 100644
--- a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h
+++ b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h
@@ -94,13 +94,13 @@
   BufferTraits() = default;
   BufferTraits(const native_handle_t* buffer_handle,
                const FileHandleType& metadata_handle, int id,
-               uint64_t buffer_state_bit, uint64_t metadata_size,
+               uint64_t client_state_mask, uint64_t metadata_size,
                uint32_t width, uint32_t height, uint32_t layer_count,
                uint32_t format, uint64_t usage, uint32_t stride,
                const FileHandleType& acquire_fence_fd,
                const FileHandleType& release_fence_fd)
       : id_(id),
-        buffer_state_bit_(buffer_state_bit),
+        client_state_mask_(client_state_mask),
         metadata_size_(metadata_size),
         width_(width),
         height_(height),
@@ -124,7 +124,7 @@
   // same buffer channel has uniqued state bit among its siblings. For a
   // producer buffer the bit must be kProducerStateBit; for a consumer the bit
   // must be one of the kConsumerStateMask.
-  uint64_t buffer_state_bit() const { return buffer_state_bit_; }
+  uint64_t client_state_mask() const { return client_state_mask_; }
   uint64_t metadata_size() const { return metadata_size_; }
 
   uint32_t width() { return width_; }
@@ -148,7 +148,7 @@
  private:
   // BufferHub specific traits.
   int id_ = -1;
-  uint64_t buffer_state_bit_;
+  uint64_t client_state_mask_;
   uint64_t metadata_size_;
 
   // Traits for a GraphicBuffer.
@@ -169,10 +169,10 @@
   FileHandleType acquire_fence_fd_;
   FileHandleType release_fence_fd_;
 
-  PDX_SERIALIZABLE_MEMBERS(BufferTraits<FileHandleType>, id_, buffer_state_bit_,
-                           metadata_size_, stride_, width_, height_,
-                           layer_count_, format_, usage_, buffer_handle_,
-                           metadata_handle_, acquire_fence_fd_,
+  PDX_SERIALIZABLE_MEMBERS(BufferTraits<FileHandleType>, id_,
+                           client_state_mask_, metadata_size_, stride_, width_,
+                           height_, layer_count_, format_, usage_,
+                           buffer_handle_, metadata_handle_, acquire_fence_fd_,
                            release_fence_fd_);
 
   BufferTraits(const BufferTraits&) = delete;
diff --git a/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h b/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h
index 7330aa1..de51f25 100644
--- a/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h
+++ b/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h
@@ -99,12 +99,12 @@
  public:
   BufferDescription() = default;
   BufferDescription(const IonBuffer& buffer, const IonBuffer& metadata, int id,
-                    int buffer_cid, uint64_t buffer_state_bit,
+                    int buffer_cid, uint64_t client_state_mask,
                     const FileHandleType& acquire_fence_fd,
                     const FileHandleType& release_fence_fd)
       : id_(id),
         buffer_cid_(buffer_cid),
-        buffer_state_bit_(buffer_state_bit),
+        client_state_mask_(client_state_mask),
         buffer_(buffer, id),
         metadata_(metadata, id),
         acquire_fence_fd_(acquire_fence_fd.Borrow()),
@@ -125,7 +125,7 @@
   // same buffer channel has uniqued state bit among its siblings. For a
   // producer buffer the bit must be kProducerStateBit; for a consumer the bit
   // must be one of the kConsumerStateMask.
-  uint64_t buffer_state_bit() const { return buffer_state_bit_; }
+  uint64_t client_state_mask() const { return client_state_mask_; }
   FileHandleType take_acquire_fence() { return std::move(acquire_fence_fd_); }
   FileHandleType take_release_fence() { return std::move(release_fence_fd_); }
 
@@ -135,7 +135,7 @@
  private:
   int id_{-1};
   int buffer_cid_{-1};
-  uint64_t buffer_state_bit_{0};
+  uint64_t client_state_mask_{0};
   // Two IonBuffers: one for the graphic buffer and one for metadata.
   NativeBufferHandle<FileHandleType> buffer_;
   NativeBufferHandle<FileHandleType> metadata_;
@@ -145,7 +145,7 @@
   FileHandleType release_fence_fd_;
 
   PDX_SERIALIZABLE_MEMBERS(BufferDescription<FileHandleType>, id_, buffer_cid_,
-                           buffer_state_bit_, buffer_, metadata_,
+                           client_state_mask_, buffer_, metadata_,
                            acquire_fence_fd_, release_fence_fd_);
 
   BufferDescription(const BufferDescription&) = delete;
diff --git a/libs/vr/libbufferhub/include/private/dvr/producer_buffer.h b/libs/vr/libbufferhub/include/private/dvr/producer_buffer.h
index d2d4d1e..2761416 100644
--- a/libs/vr/libbufferhub/include/private/dvr/producer_buffer.h
+++ b/libs/vr/libbufferhub/include/private/dvr/producer_buffer.h
@@ -52,11 +52,14 @@
 
   // Attempt to re-gain the buffer for writing. If |release_fence| is valid, it
   // must be waited on before using the buffer. If it is not valid then the
-  // buffer is free for immediate use. This call will only succeed if the buffer
-  // is in the released state.
-  // This returns zero or a negative unix error code.
-  int Gain(LocalHandle* release_fence);
-  int GainAsync();
+  // buffer is free for immediate use. This call will succeed if the buffer
+  // is in the released state, or in posted state and gain_posted_buffer is
+  // true.
+  //
+  // @param release_fence output fence.
+  // @param gain_posted_buffer whether to gain posted buffer or not.
+  // @return This returns zero or a negative unix error code.
+  int Gain(LocalHandle* release_fence, bool gain_posted_buffer = false);
 
   // Asynchronously marks a released buffer as gained. This method is similar to
   // the synchronous version above, except that it does not wait for BufferHub
@@ -64,7 +67,13 @@
   // the underlying message, no error is returned if this method is called when
   // the buffer is in an incorrect state. Returns zero if sending the message
   // succeeded, or a negative errno code if local error check fails.
-  int GainAsync(DvrNativeBufferMetadata* out_meta, LocalHandle* out_fence);
+  // TODO(b/112007999): gain_posted_buffer true is only used to prevent
+  // libdvrtracking from starving when there are non-responding clients. This
+  // gain_posted_buffer param can be removed once libdvrtracking start to use
+  // the new AHardwareBuffer API.
+  int GainAsync(DvrNativeBufferMetadata* out_meta, LocalHandle* out_fence,
+                bool gain_posted_buffer = false);
+  int GainAsync();
 
   // Detaches a ProducerBuffer from an existing producer/consumer set. Can only
   // be called when a producer buffer has exclusive access to the buffer (i.e.
@@ -92,7 +101,8 @@
   explicit ProducerBuffer(LocalChannelHandle channel);
 
   // Local state transition helpers.
-  int LocalGain(DvrNativeBufferMetadata* out_meta, LocalHandle* out_fence);
+  int LocalGain(DvrNativeBufferMetadata* out_meta, LocalHandle* out_fence,
+                bool gain_posted_buffer = false);
   int LocalPost(const DvrNativeBufferMetadata* meta,
                 const LocalHandle& ready_fence);
 };
diff --git a/libs/vr/libbufferhub/producer_buffer.cpp b/libs/vr/libbufferhub/producer_buffer.cpp
index 7b6f77a..8f0e3e3 100644
--- a/libs/vr/libbufferhub/producer_buffer.cpp
+++ b/libs/vr/libbufferhub/producer_buffer.cpp
@@ -134,7 +134,7 @@
 }
 
 int ProducerBuffer::LocalGain(DvrNativeBufferMetadata* out_meta,
-                              LocalHandle* out_fence) {
+                              LocalHandle* out_fence, bool gain_posted_buffer) {
   uint64_t buffer_state = buffer_state_->load();
   ALOGD_IF(TRACE, "ProducerBuffer::LocalGain: buffer=%d, state=%" PRIx64 ".",
            id(), buffer_state);
@@ -142,13 +142,14 @@
   if (!out_meta)
     return -EINVAL;
 
-  if (!BufferHubDefs::IsBufferReleased(buffer_state)) {
-    if (BufferHubDefs::IsBufferGained(buffer_state)) {
-      // We don't want to log error when gaining a newly allocated
-      // buffer.
-      ALOGI("ProducerBuffer::LocalGain: already gained id=%d.", id());
-      return -EALREADY;
-    }
+  if (BufferHubDefs::IsBufferGained(buffer_state)) {
+    // We don't want to log error when gaining a newly allocated
+    // buffer.
+    ALOGI("ProducerBuffer::LocalGain: already gained id=%d.", id());
+    return -EALREADY;
+  }
+  if (BufferHubDefs::IsBufferAcquired(buffer_state) ||
+      (BufferHubDefs::IsBufferPosted(buffer_state) && !gain_posted_buffer)) {
     ALOGE("ProducerBuffer::LocalGain: not released id=%d state=%" PRIx64 ".",
           id(), buffer_state);
     return -EBUSY;
@@ -180,11 +181,11 @@
   return 0;
 }
 
-int ProducerBuffer::Gain(LocalHandle* release_fence) {
+int ProducerBuffer::Gain(LocalHandle* release_fence, bool gain_posted_buffer) {
   ATRACE_NAME("ProducerBuffer::Gain");
 
   DvrNativeBufferMetadata meta;
-  if (const int error = LocalGain(&meta, release_fence))
+  if (const int error = LocalGain(&meta, release_fence, gain_posted_buffer))
     return error;
 
   auto status = InvokeRemoteMethod<BufferHubRPC::ProducerGain>();
@@ -194,10 +195,11 @@
 }
 
 int ProducerBuffer::GainAsync(DvrNativeBufferMetadata* out_meta,
-                              LocalHandle* release_fence) {
+                              LocalHandle* release_fence,
+                              bool gain_posted_buffer) {
   ATRACE_NAME("ProducerBuffer::GainAsync");
 
-  if (const int error = LocalGain(out_meta, release_fence))
+  if (const int error = LocalGain(out_meta, release_fence, gain_posted_buffer))
     return error;
 
   return ReturnStatusOrError(SendImpulse(BufferHubRPC::ProducerGain::Opcode));
diff --git a/opengl/tools/glgen/stubs/egl/EGL15Header.java-if b/opengl/tools/glgen/stubs/egl/EGL15Header.java-if
index 7409d93..859380f 100644
--- a/opengl/tools/glgen/stubs/egl/EGL15Header.java-if
+++ b/opengl/tools/glgen/stubs/egl/EGL15Header.java-if
@@ -20,7 +20,9 @@
  * EGL 1.5
  *
  */
-public class EGL15 {
+public final class EGL15 {
+
+    private EGL15() {};
 
     public static final int EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT            = 0x00000001;
     public static final int EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT   = 0x00000002;
diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp
index 0b73be0..869a2fc 100644
--- a/services/inputflinger/InputReader.cpp
+++ b/services/inputflinger/InputReader.cpp
@@ -2612,7 +2612,7 @@
             // Should not happen during first time configuration.
             ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
             mParameters.mode = Parameters::MODE_POINTER;
-            // fall through.
+            [[fallthrough]];
         case Parameters::MODE_POINTER:
             mSource = AINPUT_SOURCE_MOUSE;
             mXPrecision = 1.0f;
diff --git a/services/inputflinger/host/InputFlinger.cpp b/services/inputflinger/host/InputFlinger.cpp
index f1d3726..2da2a70 100644
--- a/services/inputflinger/host/InputFlinger.cpp
+++ b/services/inputflinger/host/InputFlinger.cpp
@@ -53,7 +53,7 @@
     if ((uid != AID_SHELL)
             && !PermissionCache::checkPermission(sDumpPermission, pid, uid)) {
         result.appendFormat("Permission Denial: "
-                "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
+                "can't dump InputFlinger from pid=%d, uid=%d\n", pid, uid);
     } else {
         dumpInternal(result);
     }
diff --git a/services/thermalservice/Android.bp b/services/thermalservice/Android.bp
index d754560..2812c13 100644
--- a/services/thermalservice/Android.bp
+++ b/services/thermalservice/Android.bp
@@ -40,11 +40,13 @@
     include_dirs: ["frameworks/native"],
 
     shared_libs: [
+        "libbase",
         "libthermalservice",
         "libbinder",
         "libutils",
         "libthermalcallback",
         "android.hardware.thermal@1.1",
+        "android.hardware.thermal@2.0",
         "libhidlbase",
         "libhidltransport",
         "liblog",
diff --git a/services/thermalservice/ThermalService.cpp b/services/thermalservice/ThermalService.cpp
index 6e09a83..b1a80de 100644
--- a/services/thermalservice/ThermalService.cpp
+++ b/services/thermalservice/ThermalService.cpp
@@ -15,11 +15,16 @@
  */
 
 #include "ThermalService.h"
-#include <android/os/IThermalService.h>
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
 #include <android/os/IThermalEventListener.h>
+#include <android/os/IThermalService.h>
 #include <android/os/Temperature.h>
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
+#include <binder/PermissionCache.h>
+#include <log/log.h>
+#include <private/android_filesystem_config.h>
 #include <utils/Errors.h>
 #include <utils/Mutex.h>
 #include <utils/String16.h>
@@ -28,6 +33,35 @@
 namespace os {
 
 /**
+ * Dump thermal service
+ * @param fd file descriptor for dumping
+ * @param args not used
+ */
+status_t ThermalService::dump(int fd, const Vector<String16>& /* args */) {
+    status_t ret = OK;
+    std::string result;
+    const IPCThreadState* ipc = IPCThreadState::self();
+    const int pid = ipc->getCallingPid();
+    const int uid = ipc->getCallingUid();
+    if ((uid != AID_SHELL) &&
+        !PermissionCache::checkPermission(String16("android.permission.DUMP"), pid, uid)) {
+        result = android::base::
+                StringPrintf("Permission Denial: can't dump ThermalService from pid=%d, uid=%d\n",
+                             pid, uid);
+        ret = PERMISSION_DENIED;
+    } else {
+        Mutex::Autolock _l(mListenersLock);
+        result = android::base::StringPrintf("ThermalEventListener registered: %d\n",
+                                             (int)mListeners.size());
+    }
+    if (!android::base::WriteStringToFd(result, fd)) {
+        SLOGE("Failed to dump fd: %d", fd);
+        ret = FDS_NOT_ALLOWED;
+    }
+    return ret;
+}
+
+/**
  * Notify registered listeners of a thermal throttling start/stop event.
  * @param temperature the temperature at which the event was generated
  */
@@ -62,8 +96,9 @@
 binder::Status ThermalService::registerThermalEventListener(
     const sp<IThermalEventListener>& listener) {
     {
-        if (listener == NULL)
+        if (listener == NULL) {
             return binder::Status::ok();
+        }
         Mutex::Autolock _l(mListenersLock);
         // check whether this is a duplicate
         for (size_t i = 0; i < mListeners.size(); i++) {
@@ -87,8 +122,9 @@
  */
 binder::Status ThermalService::unregisterThermalEventListener(
     const sp<IThermalEventListener>& listener) {
-    if (listener == NULL)
+    if (listener == NULL) {
         return binder::Status::ok();
+    }
     Mutex::Autolock _l(mListenersLock);
     for (size_t i = 0; i < mListeners.size(); i++) {
         if (IInterface::asBinder(mListeners[i]) ==
diff --git a/services/thermalservice/ThermalService.h b/services/thermalservice/ThermalService.h
index 17dfcbc..d3da900 100644
--- a/services/thermalservice/ThermalService.h
+++ b/services/thermalservice/ThermalService.h
@@ -34,6 +34,7 @@
     void publish(const sp<ThermalService>& service);
     binder::Status notifyThrottling(
         const bool isThrottling, const Temperature& temperature);
+    status_t dump(int fd, const Vector<String16>& args) override;
 
 private:
     Mutex mListenersLock;
diff --git a/services/thermalservice/libthermalcallback/Android.bp b/services/thermalservice/libthermalcallback/Android.bp
index e98506e..312579c 100644
--- a/services/thermalservice/libthermalcallback/Android.bp
+++ b/services/thermalservice/libthermalcallback/Android.bp
@@ -2,6 +2,7 @@
     name: "libthermalcallback",
     srcs: [
         "ThermalCallback.cpp",
+        "ThermalChangedCallback.cpp",
     ],
     cflags: [
         "-Wall",
@@ -10,6 +11,7 @@
     include_dirs: ["frameworks/native"],
     shared_libs: [
         "android.hardware.thermal@1.1",
+        "android.hardware.thermal@2.0",
         "libhidlbase",
         "libhidltransport",
         "liblog",
diff --git a/services/thermalservice/libthermalcallback/ThermalCallback.cpp b/services/thermalservice/libthermalcallback/ThermalCallback.cpp
index 5e094fa..0f3132c 100644
--- a/services/thermalservice/libthermalcallback/ThermalCallback.cpp
+++ b/services/thermalservice/libthermalcallback/ThermalCallback.cpp
@@ -1,11 +1,11 @@
 #define LOG_TAG "android.hardware.thermal.thermalcallback@1.1-impl"
 #include <log/log.h>
 
-#include "ThermalCallback.h"
-#include "services/thermalservice/ThermalService.h"
-#include <math.h>
 #include <android/os/Temperature.h>
 #include <hardware/thermal.h>
+#include <cmath>
+#include "ThermalCallback.h"
+#include "services/thermalservice/ThermalService.h"
 
 namespace android {
 namespace hardware {
@@ -57,7 +57,7 @@
         android::os::Temperature thermal_svc_temp(value, type);
         mThermalService->notifyThrottling(isThrottling, thermal_svc_temp);
     } else {
-        ALOGE("IThermalService binder service not created, drop throttling event");
+        SLOGE("IThermalService binder service not created, drop throttling event");
     }
     return Void();
 }
diff --git a/services/thermalservice/libthermalcallback/ThermalChangedCallback.cpp b/services/thermalservice/libthermalcallback/ThermalChangedCallback.cpp
new file mode 100644
index 0000000..0efd732
--- /dev/null
+++ b/services/thermalservice/libthermalcallback/ThermalChangedCallback.cpp
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "android.hardware.thermal.thermalchangedcallback@2.0-impl"
+#include <log/log.h>
+
+#include <android/os/Temperature.h>
+#include <hardware/thermal.h>
+#include <cmath>
+#include "ThermalChangedCallback.h"
+#include "services/thermalservice/ThermalService.h"
+
+namespace android {
+namespace hardware {
+namespace thermal {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::thermal::V2_0::TemperatureType;
+using ::android::hardware::thermal::V2_0::ThrottlingSeverity;
+using ::android::os::ThermalService;
+
+// Register a binder ThermalService object for sending events
+void ThermalChangedCallback::registerThermalService(sp<ThermalService> thermalService) {
+    mThermalService = thermalService;
+}
+
+// Methods from IThermalChangedCallback::V2_0 follow.
+Return<void> ThermalChangedCallback::notifyThrottling(
+        const android::hardware::thermal::V2_0::Temperature& temperature) {
+    // Convert HIDL IThermal Temperature to binder IThermalService Temperature.
+    if (mThermalService != nullptr) {
+        float value = NAN;
+        int type = DEVICE_TEMPERATURE_UNKNOWN;
+
+        switch (temperature.type) {
+            case TemperatureType::CPU:
+                type = DEVICE_TEMPERATURE_CPU;
+                break;
+            case TemperatureType::GPU:
+                type = DEVICE_TEMPERATURE_GPU;
+                break;
+            case TemperatureType::BATTERY:
+                type = DEVICE_TEMPERATURE_BATTERY;
+                break;
+            case TemperatureType::SKIN:
+                type = DEVICE_TEMPERATURE_SKIN;
+                break;
+            case TemperatureType::UNKNOWN:
+            default:
+                type = DEVICE_TEMPERATURE_UNKNOWN;
+                break;
+        }
+        bool isThrottling = (static_cast<size_t>(temperature.throttlingStatus) >=
+                             static_cast<size_t>(ThrottlingSeverity::SEVERE))
+                ? true
+                : false;
+        android::os::Temperature thermal_svc_temp(value, type);
+        mThermalService->notifyThrottling(isThrottling, thermal_svc_temp);
+    } else {
+        SLOGE("IThermalService binder service not created, drop throttling event");
+    }
+    return Void();
+}
+
+} // namespace implementation
+} // namespace V2_0
+} // namespace thermal
+} // namespace hardware
+} // namespace android
diff --git a/services/thermalservice/libthermalcallback/ThermalChangedCallback.h b/services/thermalservice/libthermalcallback/ThermalChangedCallback.h
new file mode 100644
index 0000000..03de049
--- /dev/null
+++ b/services/thermalservice/libthermalcallback/ThermalChangedCallback.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_HARDWARE_THERMAL_V1_1_THERMALCHANGEDCALLBACK_H
+#define ANDROID_HARDWARE_THERMAL_V1_1_THERMALCHANGEDCALLBACK_H
+
+#include <android/hardware/thermal/2.0/IThermalChangedCallback.h>
+#include <android/hardware/thermal/2.0/types.h>
+#include <android/os/Temperature.h>
+#include <hidl/MQDescriptor.h>
+#include <hidl/Status.h>
+#include "services/thermalservice/ThermalService.h"
+
+namespace android {
+namespace hardware {
+namespace thermal {
+namespace V2_0 {
+namespace implementation {
+
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::os::ThermalService;
+
+class ThermalChangedCallback : public IThermalChangedCallback {
+public:
+    // Register a binder ThermalService object for sending events
+    void registerThermalService(sp<ThermalService> thermalService);
+
+    // Methods from I ThermalChangedCallback::V2_0 follow.
+    Return<void> notifyThrottling(
+            const android::hardware::thermal::V2_0::Temperature& temperature) override;
+
+private:
+    // Our registered binder ThermalService object to use for sending events
+    sp<android::os::ThermalService> mThermalService;
+};
+
+} // namespace implementation
+} // namespace V2_0
+} // namespace thermal
+} // namespace hardware
+} // namespace android
+
+#endif // ANDROID_HARDWARE_THERMAL_V1_1_THERMALCHANGEDCALLBACK_H
diff --git a/services/thermalservice/thermalservice.rc b/services/thermalservice/thermalservice.rc
index 94c2c78..5e20170 100644
--- a/services/thermalservice/thermalservice.rc
+++ b/services/thermalservice/thermalservice.rc
@@ -2,3 +2,5 @@
     class core
     user system
     group system
+    onrestart restart zygote
+    writepid /dev/cpuset/foreground/tasks
diff --git a/services/thermalservice/thermalserviced.cpp b/services/thermalservice/thermalserviced.cpp
index 8e27266..0bfaaff 100644
--- a/services/thermalservice/thermalserviced.cpp
+++ b/services/thermalservice/thermalserviced.cpp
@@ -17,93 +17,155 @@
 #define LOG_TAG "thermalserviced"
 #include <log/log.h>
 
-#include "thermalserviced.h"
 #include "ThermalService.h"
 #include "libthermalcallback/ThermalCallback.h"
+#include "libthermalcallback/ThermalChangedCallback.h"
+#include "thermalserviced.h"
 
 #include <android/hardware/thermal/1.1/IThermal.h>
+#include <android/hardware/thermal/2.0/IThermal.h>
+#include <android/hardware/thermal/2.0/types.h>
+
 #include <binder/IPCThreadState.h>
 #include <binder/IServiceManager.h>
 #include <hidl/HidlTransportSupport.h>
 
 using namespace android;
-using ::android::hardware::thermal::V1_1::IThermal;
-using ::android::hardware::thermal::V1_0::Temperature;
-using ::android::hardware::thermal::V1_1::IThermalCallback;
-using ::android::hardware::thermal::V1_1::implementation::ThermalCallback;
+using IThermal1_1 = ::android::hardware::thermal::V1_1::IThermal;
+using IThermal2_0 = ::android::hardware::thermal::V2_0::IThermal;
 using ::android::hardware::configureRpcThreadpool;
 using ::android::hardware::hidl_death_recipient;
+using ::android::hardware::Return;
+using ::android::hardware::thermal::V1_0::ThermalStatus;
+using ::android::hardware::thermal::V1_0::ThermalStatusCode;
+using ::android::hardware::thermal::V1_1::IThermalCallback;
+using ::android::hardware::thermal::V1_1::implementation::ThermalCallback;
+using ::android::hardware::thermal::V2_0::IThermalChangedCallback;
+using ::android::hardware::thermal::V2_0::TemperatureType;
 using ::android::hidl::base::V1_0::IBase;
 using ::android::os::ThermalService;
 
-template<typename T>
-using Return = hardware::Return<T>;
-
 namespace {
 
 // Our thermalserviced main object
 ThermalServiceDaemon* gThermalServiceDaemon;
 
-// Thermal HAL client
-sp<IThermal> gThermalHal = nullptr;
+// Thermal HAL 1.1 client
+sp<IThermal1_1> gThermalHal1_1 = nullptr;
+// Thermal HAL 2.0 client
+sp<IThermal2_0> gThermalHal2_0 = nullptr;
 
 // Binder death notifier informing of Thermal HAL death.
 struct ThermalServiceDeathRecipient : hidl_death_recipient {
     virtual void serviceDied(
         uint64_t cookie __unused, const wp<IBase>& who __unused) {
-        gThermalHal = nullptr;
-        ALOGE("IThermal HAL died");
+        SLOGE("IThermal HAL died");
+        gThermalHal1_1 = nullptr;
+        gThermalHal2_0 = nullptr;
         gThermalServiceDaemon->getThermalHal();
     }
 };
 
-sp<ThermalServiceDeathRecipient> gThermalHalDied = nullptr;
-
 }  // anonymous namespace
 
 void ThermalServiceDaemon::thermalServiceStartup() {
-    // Binder IThermalService startup
+    // Binder IThermal1_1Service startup
     mThermalService = new android::os::ThermalService;
     mThermalService->publish(mThermalService);
-    // Register IThermalService object with IThermalCallback
-    if (mThermalCallback != nullptr)
-        mThermalCallback->registerThermalService(mThermalService);
+    // Register IThermalService object to ThermalHAL callback
+    if (mThermalCallback_2_0 != nullptr) {
+        mThermalCallback_2_0->registerThermalService(mThermalService);
+    } else if (mThermalCallback_1_1 != nullptr) {
+        mThermalCallback_1_1->registerThermalService(mThermalService);
+    }
     IPCThreadState::self()->joinThreadPool();
 }
 
 // Lookup Thermal HAL, register death notifier, register our
 // ThermalCallback with the Thermal HAL.
 void ThermalServiceDaemon::getThermalHal() {
-    gThermalHal = IThermal::getService();
-    if (gThermalHal == nullptr) {
-        ALOGW("Unable to get Thermal HAL V1.1, vendor thermal event notification not available");
-        return;
+    static sp<ThermalServiceDeathRecipient> gThermalHalDied = nullptr;
+    // Binder death notifier for Thermal HAL
+    if (gThermalHalDied == nullptr) {
+        gThermalHalDied = new ThermalServiceDeathRecipient();
     }
 
-    // Binder death notifier for Thermal HAL
-    if (gThermalHalDied == nullptr)
-        gThermalHalDied = new ThermalServiceDeathRecipient();
+    gThermalHal2_0 = IThermal2_0::getService();
+    if (gThermalHal2_0 == nullptr) {
+        SLOGW("Unable to get Thermal HAL V2.0, fallback to 1.1");
+        gThermalHal1_1 = IThermal1_1::getService();
+        if (gThermalHal1_1 == nullptr) {
+            SLOGW("Unable to get Thermal HAL V1.1, vendor thermal event "
+                  "notification not available");
+            return;
+        }
+        if (gThermalHalDied != nullptr) {
+            gThermalHal1_1->linkToDeath(gThermalHalDied, 0x451F /* cookie */);
+        }
 
-    if (gThermalHalDied != nullptr)
-        gThermalHal->linkToDeath(gThermalHalDied, 0x451F /* cookie */);
+        if (mThermalCallback_1_1 != nullptr) {
+            Return<void> ret = gThermalHal1_1->registerThermalCallback(mThermalCallback_1_1);
+            if (!ret.isOk()) {
+                SLOGE("registerThermalCallback failed, status: %s", ret.description().c_str());
+            }
+        }
+    } else {
+        if (gThermalHalDied != nullptr) {
+            gThermalHal2_0->linkToDeath(gThermalHalDied, 0x451F /* cookie */);
+        }
 
-    if (mThermalCallback != nullptr) {
-        Return<void> ret = gThermalHal->registerThermalCallback(
-            mThermalCallback);
-        if (!ret.isOk())
-            ALOGE("registerThermalCallback failed, status: %s",
-                  ret.description().c_str());
+        if (mThermalCallback_2_0 != nullptr) {
+            Return<void> ret =
+                    gThermalHal2_0
+                            ->registerThermalChangedCallback(mThermalCallback_2_0, false,
+                                                             TemperatureType::SKIN, // not used
+                                                             [](ThermalStatus status) {
+                                                                 if (ThermalStatusCode::SUCCESS !=
+                                                                     status.code) {
+                                                                     SLOGE("registerThermalChangedC"
+                                                                           "allback failed, "
+                                                                           "status: %s",
+                                                                           status.debugMessage
+                                                                                   .c_str());
+                                                                 }
+                                                             });
+            if (!ret.isOk()) {
+                SLOGE("registerThermalChangedCallback failed, status: %s",
+                      ret.description().c_str());
+            }
+        }
+    }
+}
+
+ThermalServiceDaemon::~ThermalServiceDaemon() {
+    if (mThermalCallback_2_0 != nullptr && gThermalHal2_0 != nullptr) {
+        Return<void> ret =
+                gThermalHal2_0
+                        ->unregisterThermalChangedCallback(
+                            mThermalCallback_2_0,
+                            [](ThermalStatus status) {
+                                if (ThermalStatusCode::SUCCESS !=
+                                    status.code) {
+                                    SLOGE("unregisterThermalChangedCallback failed, status: %s",
+                                          status.debugMessage
+                                          .c_str());
+                                }
+                            });
+        if (!ret.isOk()) {
+            SLOGE("unregisterThermalChangedCallback failed, status: %s", ret.description().c_str());
+        }
     }
 }
 
 void ThermalServiceDaemon::thermalCallbackStartup() {
-    // HIDL IThermalCallback startup
+    // HIDL IThermal Callback startup
     // Need at least 2 threads in thread pool since we wait for dead HAL
     // to come back on the binder death notification thread and we need
     // another thread for the incoming service now available call.
     configureRpcThreadpool(2, false /* callerWillJoin */);
-    mThermalCallback = new ThermalCallback();
-    // Lookup Thermal HAL and register our ThermalCallback.
+    mThermalCallback_1_1 = new ThermalCallback();
+    mThermalCallback_2_0 = new ThermalChangedCallback();
+    // Lookup Thermal HAL 1.1 and 2.0 to register our Callback.
     getThermalHal();
 }
 
diff --git a/services/thermalservice/thermalserviced.h b/services/thermalservice/thermalserviced.h
index 309e2fe..ff7a483 100644
--- a/services/thermalservice/thermalserviced.h
+++ b/services/thermalservice/thermalserviced.h
@@ -19,22 +19,26 @@
 
 #include "ThermalService.h"
 #include "libthermalcallback/ThermalCallback.h"
+#include "libthermalcallback/ThermalChangedCallback.h"
 
 using namespace android;
 using ::android::hardware::thermal::V1_0::Temperature;
 using ::android::hardware::thermal::V1_1::implementation::ThermalCallback;
+using ::android::hardware::thermal::V2_0::implementation::ThermalChangedCallback;
 using ::android::os::ThermalService;
 
 class ThermalServiceDaemon {
  public:
+    ~ThermalServiceDaemon();
     void thermalServiceStartup();
     void thermalCallbackStartup();
     void getThermalHal();
-    ThermalServiceDaemon() {};
+    ThermalServiceDaemon(){};
 
  private:
     sp<ThermalService> mThermalService;
-    sp<ThermalCallback> mThermalCallback;
+    sp<ThermalCallback> mThermalCallback_1_1;
+    sp<ThermalChangedCallback> mThermalCallback_2_0;
 };
 
 #endif  // ANDROID_THERMALSERVICE_THERMALSERVICED_H
diff --git a/services/vr/bufferhubd/buffer_channel.cpp b/services/vr/bufferhubd/buffer_channel.cpp
index ee85746..d5e6dfb 100644
--- a/services/vr/bufferhubd/buffer_channel.cpp
+++ b/services/vr/bufferhubd/buffer_channel.cpp
@@ -18,7 +18,7 @@
     : BufferHubChannel(service, buffer_id, channel_id, kDetachedBufferType),
       buffer_node_(
           std::make_shared<BufferNode>(std::move(buffer), user_metadata_size)) {
-  buffer_state_bit_ = buffer_node_->AddNewActiveClientsBitToMask();
+  client_state_mask_ = buffer_node_->AddNewActiveClientsBitToMask();
 }
 
 BufferChannel::BufferChannel(BufferHubService* service, int buffer_id,
@@ -28,7 +28,7 @@
     : BufferHubChannel(service, buffer_id, buffer_id, kDetachedBufferType),
       buffer_node_(std::make_shared<BufferNode>(
           width, height, layer_count, format, usage, user_metadata_size)) {
-  buffer_state_bit_ = buffer_node_->AddNewActiveClientsBitToMask();
+  client_state_mask_ = buffer_node_->AddNewActiveClientsBitToMask();
 }
 
 BufferChannel::BufferChannel(BufferHubService* service, int buffer_id,
@@ -36,8 +36,8 @@
                              std::shared_ptr<BufferNode> buffer_node)
     : BufferHubChannel(service, buffer_id, channel_id, kDetachedBufferType),
       buffer_node_(buffer_node) {
-  buffer_state_bit_ = buffer_node_->AddNewActiveClientsBitToMask();
-  if (buffer_state_bit_ == 0ULL) {
+  client_state_mask_ = buffer_node_->AddNewActiveClientsBitToMask();
+  if (client_state_mask_ == 0ULL) {
     ALOGE("BufferChannel::BufferChannel: %s", strerror(errno));
     buffer_node_ = nullptr;
   }
@@ -46,8 +46,8 @@
 BufferChannel::~BufferChannel() {
   ALOGD_IF(TRACE, "BufferChannel::~BufferChannel: channel_id=%d buffer_id=%d.",
            channel_id(), buffer_id());
-  if (buffer_state_bit_ != 0ULL) {
-    buffer_node_->RemoveClientsBitFromMask(buffer_state_bit_);
+  if (client_state_mask_ != 0ULL) {
+    buffer_node_->RemoveClientsBitFromMask(client_state_mask_);
   }
   Hangup();
 }
@@ -93,7 +93,7 @@
       /*buffer_handle=*/buffer_node_->buffer().handle(),
       /*metadata_handle=*/buffer_node_->metadata().ashmem_handle().Borrow(),
       /*id=*/buffer_id(),
-      /*buffer_state_bit=*/buffer_state_bit_,
+      /*client_state_mask=*/client_state_mask_,
       /*metadata_size=*/buffer_node_->metadata().metadata_size(),
       /*width=*/buffer_node_->buffer().width(),
       /*height=*/buffer_node_->buffer().height(),
diff --git a/services/vr/bufferhubd/buffer_node.cpp b/services/vr/bufferhubd/buffer_node.cpp
index bedec6f..f8ec59d 100644
--- a/services/vr/bufferhubd/buffer_node.cpp
+++ b/services/vr/bufferhubd/buffer_node.cpp
@@ -43,12 +43,12 @@
 
 uint64_t BufferNode::AddNewActiveClientsBitToMask() {
   uint64_t current_active_clients_bit_mask = GetActiveClientsBitMask();
-  uint64_t buffer_state_bit = 0ULL;
+  uint64_t client_state_mask = 0ULL;
   uint64_t updated_active_clients_bit_mask = 0ULL;
   do {
-    buffer_state_bit =
+    client_state_mask =
         BufferHubDefs::FindNextClearedBit(current_active_clients_bit_mask);
-    if (buffer_state_bit == 0ULL) {
+    if (client_state_mask == 0ULL) {
       ALOGE(
           "BufferNode::AddNewActiveClientsBitToMask: reached the maximum "
           "mumber of channels per buffer node: 32.");
@@ -56,11 +56,11 @@
       return 0ULL;
     }
     updated_active_clients_bit_mask =
-        current_active_clients_bit_mask | buffer_state_bit;
+        current_active_clients_bit_mask | client_state_mask;
   } while (!(active_clients_bit_mask_->compare_exchange_weak(
       current_active_clients_bit_mask, updated_active_clients_bit_mask,
       std::memory_order_acq_rel, std::memory_order_acquire)));
-  return buffer_state_bit;
+  return client_state_mask;
 }
 
 void BufferNode::RemoveClientsBitFromMask(const uint64_t& value) {
diff --git a/services/vr/bufferhubd/include/private/dvr/buffer_channel.h b/services/vr/bufferhubd/include/private/dvr/buffer_channel.h
index e9bdb37..6d1e9e1 100644
--- a/services/vr/bufferhubd/include/private/dvr/buffer_channel.h
+++ b/services/vr/bufferhubd/include/private/dvr/buffer_channel.h
@@ -55,7 +55,7 @@
   std::shared_ptr<BufferNode> buffer_node_ = nullptr;
 
   // The state bit of this buffer. Must be one the lower 63 bits.
-  uint64_t buffer_state_bit_ = 0ULL;
+  uint64_t client_state_mask_ = 0ULL;
 };
 
 }  // namespace dvr
diff --git a/services/vr/bufferhubd/include/private/dvr/buffer_node.h b/services/vr/bufferhubd/include/private/dvr/buffer_node.h
index e1e8057..067584e 100644
--- a/services/vr/bufferhubd/include/private/dvr/buffer_node.h
+++ b/services/vr/bufferhubd/include/private/dvr/buffer_node.h
@@ -34,9 +34,9 @@
   // active_clients_bit_mask from all threads will be returned here.
   uint64_t GetActiveClientsBitMask() const;
 
-  // Find and add a new buffer_state_bit to active_clients_bit_mask in
+  // Find and add a new client_state_mask to active_clients_bit_mask in
   // metadata_.
-  // Return the new buffer_state_bit that is added to active_clients_bit_mask.
+  // Return the new client_state_mask that is added to active_clients_bit_mask.
   // Return 0ULL if there are already 32 bp clients of the buffer.
   uint64_t AddNewActiveClientsBitToMask();
 
@@ -69,7 +69,7 @@
   std::atomic<uint64_t>* fence_state_ = nullptr;
 
   // active_clients_bit_mask_ tracks all the bp clients of the buffer. It is the
-  // union of all buffer_state_bit of all bp clients.
+  // union of all client_state_mask of all bp clients.
   std::atomic<uint64_t>* active_clients_bit_mask_ = nullptr;
 };
 
diff --git a/services/vr/bufferhubd/include/private/dvr/producer_channel.h b/services/vr/bufferhubd/include/private/dvr/producer_channel.h
index 18bb7bf..b5c92be 100644
--- a/services/vr/bufferhubd/include/private/dvr/producer_channel.h
+++ b/services/vr/bufferhubd/include/private/dvr/producer_channel.h
@@ -49,7 +49,7 @@
 
   BufferInfo GetBufferInfo() const override;
 
-  BufferDescription<BorrowedHandle> GetBuffer(uint64_t buffer_state_bit);
+  BufferDescription<BorrowedHandle> GetBuffer(uint64_t client_state_mask);
 
   pdx::Status<RemoteChannelHandle> CreateConsumer(Message& message);
   pdx::Status<RemoteChannelHandle> OnNewConsumer(Message& message);
diff --git a/services/vr/bufferhubd/producer_channel.cpp b/services/vr/bufferhubd/producer_channel.cpp
index 581390f..beedc4c 100644
--- a/services/vr/bufferhubd/producer_channel.cpp
+++ b/services/vr/bufferhubd/producer_channel.cpp
@@ -227,12 +227,12 @@
 }
 
 BufferDescription<BorrowedHandle> ProducerChannel::GetBuffer(
-    uint64_t buffer_state_bit) {
+    uint64_t client_state_mask) {
   return {buffer_,
           metadata_buffer_,
           buffer_id(),
           channel_id(),
-          buffer_state_bit,
+          client_state_mask,
           acquire_fence_fd_.Borrow(),
           release_fence_fd_.Borrow()};
 }
diff --git a/services/vr/bufferhubd/tests/buffer_node-test.cpp b/services/vr/bufferhubd/tests/buffer_node-test.cpp
index c2526fe..9a927f1 100644
--- a/services/vr/bufferhubd/tests/buffer_node-test.cpp
+++ b/services/vr/bufferhubd/tests/buffer_node-test.cpp
@@ -37,49 +37,51 @@
 }
 
 TEST_F(BufferNodeTest, TestAddNewActiveClientsBitToMask_twoNewClients) {
-  uint64_t new_buffer_state_bit_1 = buffer_node->AddNewActiveClientsBitToMask();
-  EXPECT_EQ(buffer_node->GetActiveClientsBitMask(), new_buffer_state_bit_1);
+  uint64_t new_client_state_mask_1 =
+      buffer_node->AddNewActiveClientsBitToMask();
+  EXPECT_EQ(buffer_node->GetActiveClientsBitMask(), new_client_state_mask_1);
 
-  // Request and add a new buffer_state_bit again.
+  // Request and add a new client_state_mask again.
   // Active clients bit mask should be the union of the two new
-  // buffer_state_bits.
-  uint64_t new_buffer_state_bit_2 = buffer_node->AddNewActiveClientsBitToMask();
+  // client_state_masks.
+  uint64_t new_client_state_mask_2 =
+      buffer_node->AddNewActiveClientsBitToMask();
   EXPECT_EQ(buffer_node->GetActiveClientsBitMask(),
-            new_buffer_state_bit_1 | new_buffer_state_bit_2);
+            new_client_state_mask_1 | new_client_state_mask_2);
 }
 
 TEST_F(BufferNodeTest, TestAddNewActiveClientsBitToMask_32NewClients) {
-  uint64_t new_buffer_state_bit = 0ULL;
+  uint64_t new_client_state_mask = 0ULL;
   uint64_t current_mask = 0ULL;
   uint64_t expected_mask = 0ULL;
 
   for (int i = 0; i < 64; ++i) {
-    new_buffer_state_bit = buffer_node->AddNewActiveClientsBitToMask();
-    EXPECT_NE(new_buffer_state_bit, 0);
-    EXPECT_FALSE(new_buffer_state_bit & current_mask);
-    expected_mask = current_mask | new_buffer_state_bit;
+    new_client_state_mask = buffer_node->AddNewActiveClientsBitToMask();
+    EXPECT_NE(new_client_state_mask, 0);
+    EXPECT_FALSE(new_client_state_mask & current_mask);
+    expected_mask = current_mask | new_client_state_mask;
     current_mask = buffer_node->GetActiveClientsBitMask();
     EXPECT_EQ(current_mask, expected_mask);
   }
 
   // Method should fail upon requesting for more than maximum allowable clients.
-  new_buffer_state_bit = buffer_node->AddNewActiveClientsBitToMask();
-  EXPECT_EQ(new_buffer_state_bit, 0ULL);
+  new_client_state_mask = buffer_node->AddNewActiveClientsBitToMask();
+  EXPECT_EQ(new_client_state_mask, 0ULL);
   EXPECT_EQ(errno, E2BIG);
 }
 
 TEST_F(BufferNodeTest, TestRemoveActiveClientsBitFromMask) {
   buffer_node->AddNewActiveClientsBitToMask();
   uint64_t current_mask = buffer_node->GetActiveClientsBitMask();
-  uint64_t new_buffer_state_bit = buffer_node->AddNewActiveClientsBitToMask();
+  uint64_t new_client_state_mask = buffer_node->AddNewActiveClientsBitToMask();
   EXPECT_NE(buffer_node->GetActiveClientsBitMask(), current_mask);
 
-  buffer_node->RemoveClientsBitFromMask(new_buffer_state_bit);
+  buffer_node->RemoveClientsBitFromMask(new_client_state_mask);
   EXPECT_EQ(buffer_node->GetActiveClientsBitMask(), current_mask);
 
   // Remove the test_mask again to the active client bit mask should not modify
   // the value of active clients bit mask.
-  buffer_node->RemoveClientsBitFromMask(new_buffer_state_bit);
+  buffer_node->RemoveClientsBitFromMask(new_client_state_mask);
   EXPECT_EQ(buffer_node->GetActiveClientsBitMask(), current_mask);
 }