Merge "atrace.rc: move to post-fs trigger"
diff --git a/Android.bp b/Android.bp
index 086a2c6..cd05b21 100644
--- a/Android.bp
+++ b/Android.bp
@@ -3,6 +3,7 @@
     from: "include/android",
     to: "android",
     srcs: ["include/android/**/*.h"],
+    license: "NOTICE",
 }
 
 subdirs = [
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index e3c1f57..ad06e30 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -13,6 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+#define LOG_TAG "dumpstate"
 
 #include <dirent.h>
 #include <errno.h>
@@ -38,10 +39,8 @@
 #include <android-base/unique_fd.h>
 #include <cutils/properties.h>
 
-#include "private/android_filesystem_config.h"
-
-#define LOG_TAG "dumpstate"
-#include <cutils/log.h>
+#include <private/android_filesystem_config.h>
+#include <private/android_logger.h>
 
 #include "dumpstate.h"
 #include "ziparchive/zip_writer.h"
@@ -401,102 +400,14 @@
     return 0;
 }
 
-/* Copied policy from system/core/logd/LogBuffer.cpp */
-
-#define LOG_BUFFER_SIZE (256 * 1024)
-#define LOG_BUFFER_MIN_SIZE (64 * 1024UL)
-#define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL)
-
-static bool valid_size(unsigned long value) {
-    if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) {
-        return false;
-    }
-
-    long pages = sysconf(_SC_PHYS_PAGES);
-    if (pages < 1) {
-        return true;
-    }
-
-    long pagesize = sysconf(_SC_PAGESIZE);
-    if (pagesize <= 1) {
-        pagesize = PAGE_SIZE;
-    }
-
-    // maximum memory impact a somewhat arbitrary ~3%
-    pages = (pages + 31) / 32;
-    unsigned long maximum = pages * pagesize;
-
-    if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) {
-        return true;
-    }
-
-    return value <= maximum;
-}
-
-static unsigned long property_get_size(const char *key) {
-    unsigned long value;
-    char *cp, property[PROPERTY_VALUE_MAX];
-
-    property_get(key, property, "");
-    value = strtoul(property, &cp, 10);
-
-    switch(*cp) {
-    case 'm':
-    case 'M':
-        value *= 1024;
-    /* FALLTHRU */
-    case 'k':
-    case 'K':
-        value *= 1024;
-    /* FALLTHRU */
-    case '\0':
-        break;
-
-    default:
-        value = 0;
-    }
-
-    if (!valid_size(value)) {
-        value = 0;
-    }
-
-    return value;
-}
-
 /* timeout in ms */
 static unsigned long logcat_timeout(const char *name) {
-    static const char global_tuneable[] = "persist.logd.size"; // Settings App
-    static const char global_default[] = "ro.logd.size";       // BoardConfig.mk
-    char key[PROP_NAME_MAX];
-    unsigned long property_size, default_size;
-
-    default_size = property_get_size(global_tuneable);
-    if (!default_size) {
-        default_size = property_get_size(global_default);
-    }
-
-    snprintf(key, sizeof(key), "%s.%s", global_tuneable, name);
-    property_size = property_get_size(key);
-
-    if (!property_size) {
-        snprintf(key, sizeof(key), "%s.%s", global_default, name);
-        property_size = property_get_size(key);
-    }
-
-    if (!property_size) {
-        property_size = default_size;
-    }
-
-    if (!property_size) {
-        property_size = LOG_BUFFER_SIZE;
-    }
-
+    log_id_t id = android_name_to_log_id(name);
+    unsigned long property_size = __android_logger_get_buffer_size(id);
     /* Engineering margin is ten-fold our guess */
     return 10 * (property_size + worst_write_perf) / worst_write_perf;
 }
 
-/* End copy from system/core/logd/LogBuffer.cpp */
-
 /* dumps the current system state to stdout */
 static void print_header(std::string version) {
     char build[PROPERTY_VALUE_MAX], fingerprint[PROPERTY_VALUE_MAX];
@@ -665,7 +576,7 @@
     run_command("LIBRANK", 10, SU_PATH, "root", "librank", NULL);
 
     run_command("PRINTENV", 10, "printenv", NULL);
-    run_command("NETSTAT", 10, "netstat", "-n", NULL);
+    run_command("NETSTAT", 10, "netstat", "-nW", NULL);
     run_command("LSMOD", 10, "lsmod", NULL);
 
     do_dmesg();
diff --git a/cmds/installd/commands.cpp b/cmds/installd/commands.cpp
index 4fde1ee..781e20e 100644
--- a/cmds/installd/commands.cpp
+++ b/cmds/installd/commands.cpp
@@ -722,7 +722,7 @@
     ALOGE("execv(%s) failed: %s\n", PATCHOAT_BIN, strerror(errno));
 }
 
-static void run_dex2oat(int zip_fd, int oat_fd, int vdex_fd, int image_fd,
+static void run_dex2oat(int zip_fd, int oat_fd, int input_vdex_fd, int output_vdex_fd, int image_fd,
         const char* input_file_name, const char* output_file_name, int swap_fd,
         const char *instruction_set, const char* compiler_filter, bool vm_safe_mode,
         bool debuggable, bool post_bootcomplete, int profile_fd, const char* shared_libraries) {
@@ -806,7 +806,8 @@
 
     char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
     char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
-    char vdex_fd_arg[strlen("--vdex-fd=") + MAX_INT_LEN];
+    char input_vdex_fd_arg[strlen("--input-vdex-fd=") + MAX_INT_LEN];
+    char output_vdex_fd_arg[strlen("--output-vdex-fd=") + MAX_INT_LEN];
     char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
     char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
     char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
@@ -822,7 +823,8 @@
 
     sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
     sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
-    sprintf(vdex_fd_arg, "--vdex-fd=%d", vdex_fd);
+    sprintf(input_vdex_fd_arg, "--input-vdex-fd=%d", input_vdex_fd);
+    sprintf(output_vdex_fd_arg, "--output-vdex-fd=%d", output_vdex_fd);
     sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
     sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
     sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
@@ -885,7 +887,7 @@
 
     ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
 
-    const char* argv[8  // program name, mandatory arguments and the final NULL
+    const char* argv[9  // 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)
@@ -906,7 +908,8 @@
     argv[i++] = DEX2OAT_BIN;
     argv[i++] = zip_fd_arg;
     argv[i++] = zip_location_arg;
-    argv[i++] = vdex_fd_arg;
+    argv[i++] = input_vdex_fd_arg;
+    argv[i++] = output_vdex_fd_arg;
     argv[i++] = oat_fd_arg;
     argv[i++] = oat_location_arg;
     argv[i++] = instruction_set_arg;
@@ -1432,6 +1435,14 @@
     return true;
 }
 
+static bool IsOutputDalvikCache(const char* oat_dir) {
+  // InstallerConnection.java (which invokes installd) transforms Java null arguments
+  // into '!'. Play it safe by handling it both.
+  // TODO: ensure we never get null.
+  // TODO: pass a flag instead of inferring if the output is dalvik cache.
+  return oat_dir == nullptr || oat_dir[0] == '!';
+}
+
 static bool create_oat_out_path(const char* apk_path, const char* instruction_set,
             const char* oat_dir, /*out*/ char* out_oat_path) {
     // Early best-effort check whether we can fit the the path into our buffers.
@@ -1443,9 +1454,9 @@
         return false;
     }
 
-    if (oat_dir != NULL && oat_dir[0] != '!') {
+    if (!IsOutputDalvikCache(oat_dir)) {
         if (validate_apk_path(oat_dir)) {
-            ALOGE("invalid oat_dir '%s'\n", oat_dir);
+            ALOGE("cannot validate apk path with oat_dir '%s'\n", oat_dir);
             return false;
         }
         if (!calculate_oat_file_path(out_oat_path, oat_dir, apk_path, instruction_set)) {
@@ -1634,22 +1645,6 @@
         return -1;
     }
 
-    // If invoking patchoat, open the VDEX associated with the OAT too.
-    std::string in_vdex_path_str;
-    base::unique_fd input_vdex_fd;
-    if (dexopt_needed == DEXOPT_PATCHOAT_NEEDED
-        || dexopt_needed == DEXOPT_SELF_PATCHOAT_NEEDED) {
-        in_vdex_path_str = create_vdex_filename(input_file);
-        if (in_vdex_path_str.empty()) {
-            return -1;
-        }
-        input_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
-        if (input_vdex_fd.get() < 0) {
-            ALOGE("installd cannot open '%s' for input during dexopt\n", in_vdex_path_str.c_str());
-            return -1;
-        }
-    }
-
     // Create the output OAT file.
     const std::string out_oat_path_str(out_oat_path);
     Dex2oatFileWrapper<std::function<void ()>> out_oat_fd(
@@ -1663,6 +1658,47 @@
         return -1;
     }
 
+    // Open the existing VDEX. We do this before creating the new output VDEX, which will
+    // unlink the old one.
+    base::unique_fd in_vdex_fd;
+    std::string in_vdex_path_str;
+    if (dexopt_needed == DEXOPT_PATCHOAT_NEEDED
+        || dexopt_needed == DEXOPT_SELF_PATCHOAT_NEEDED) {
+        // `input_file` is the OAT file to be relocated. The VDEX has to be there as well.
+        in_vdex_path_str = create_vdex_filename(input_file);
+        if (in_vdex_path_str.empty()) {
+            ALOGE("installd cannot compute input vdex location for '%s'\n", input_file);
+            return -1;
+        }
+        in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
+        if (in_vdex_fd.get() < 0) {
+            ALOGE("installd cannot open '%s' for input during dexopt: %s\n",
+                in_vdex_path_str.c_str(), strerror(errno));
+            return -1;
+        }
+    } else {
+        // Open the possibly existing vdex in the `out_oat_path`. If none exist, we pass -1
+        // to dex2oat for input-vdex-fd.
+        in_vdex_path_str = create_vdex_filename(out_oat_path);
+        if (in_vdex_path_str.empty()) {
+            ALOGE("installd cannot compute input vdex location for '%s'\n", out_oat_path);
+            return -1;
+        }
+        in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
+        // If there is no vdex file in out_oat_path, check if we have a vdex
+        // file next to the odex file. For other failures, we will just pass a -1 fd.
+        if (in_vdex_fd.get() < 0 && (errno == ENOENT) && IsOutputDalvikCache(oat_dir)) {
+            if (calculate_odex_file_path(in_odex_path, apk_path, instruction_set)) {
+              in_vdex_path_str = create_vdex_filename(std::string(in_odex_path));
+              if (in_vdex_path_str.empty()) {
+                  ALOGE("installd cannot compute input vdex location for '%s'\n", in_odex_path);
+                  return -1;
+              }
+              in_vdex_fd.reset(open(in_vdex_path_str.c_str(), O_RDONLY, 0));
+            }
+        }
+    }
+
     // Infer the name of the output VDEX and create it.
     const std::string out_vdex_path_str = create_vdex_filename(out_oat_path_str);
     if (out_vdex_path_str.empty()) {
@@ -1757,7 +1793,7 @@
         if (dexopt_needed == DEXOPT_PATCHOAT_NEEDED
             || dexopt_needed == DEXOPT_SELF_PATCHOAT_NEEDED) {
             run_patchoat(input_fd.get(),
-                         input_vdex_fd.get(),
+                         in_vdex_fd.get(),
                          out_oat_fd.get(),
                          out_vdex_fd.get(),
                          input_file,
@@ -1771,6 +1807,7 @@
             const char *input_file_name = get_location_from_path(input_file);
             run_dex2oat(input_fd.get(),
                         out_oat_fd.get(),
+                        in_vdex_fd.get(),
                         out_vdex_fd.get(),
                         image_fd.get(),
                         input_file_name,
diff --git a/data/etc/android.hardware.wifi.nan.xml b/data/etc/android.hardware.wifi.aware.xml
similarity index 90%
rename from data/etc/android.hardware.wifi.nan.xml
rename to data/etc/android.hardware.wifi.aware.xml
index e557610..ae6272e 100644
--- a/data/etc/android.hardware.wifi.nan.xml
+++ b/data/etc/android.hardware.wifi.aware.xml
@@ -14,7 +14,7 @@
      limitations under the License.
 -->
 
-<!-- This is the standard feature indicating that the device includes WiFi NAN. -->
+<!-- This is the standard feature indicating that the device includes WiFi Aware. -->
 <permissions>
-    <feature name="android.hardware.wifi.nan" />
+    <feature name="android.hardware.wifi.aware" />
 </permissions>
diff --git a/include/binder/TextOutput.h b/include/binder/TextOutput.h
index 974a194..851e01f 100644
--- a/include/binder/TextOutput.h
+++ b/include/binder/TextOutput.h
@@ -18,16 +18,15 @@
 #define ANDROID_TEXTOUTPUT_H
 
 #include <utils/Errors.h>
+#include <utils/String8.h>
 
 #include <stdint.h>
 #include <string.h>
+#include <sstream>
 
 // ---------------------------------------------------------------------------
 namespace android {
 
-class String8;
-class String16;
-
 class TextOutput
 {
 public:
@@ -66,30 +65,26 @@
 TextOutput& indent(TextOutput& to);
 TextOutput& dedent(TextOutput& to);
 
-TextOutput& operator<<(TextOutput& to, const char* str);
-TextOutput& operator<<(TextOutput& to, char);     // writes raw character
-TextOutput& operator<<(TextOutput& to, bool);
-TextOutput& operator<<(TextOutput& to, int);
-TextOutput& operator<<(TextOutput& to, long);
-TextOutput& operator<<(TextOutput& to, unsigned int);
-TextOutput& operator<<(TextOutput& to, unsigned long);
-TextOutput& operator<<(TextOutput& to, long long);
-TextOutput& operator<<(TextOutput& to, unsigned long long);
-TextOutput& operator<<(TextOutput& to, float);
-TextOutput& operator<<(TextOutput& to, double);
-TextOutput& operator<<(TextOutput& to, TextOutputManipFunc func);
-TextOutput& operator<<(TextOutput& to, const void*);
-TextOutput& operator<<(TextOutput& to, const String8& val);
-TextOutput& operator<<(TextOutput& to, const String16& val);
+template<typename T>
+TextOutput& operator<<(TextOutput& to, const T& val)
+{
+    std::stringstream strbuf;
+    strbuf << val;
+    std::string str = strbuf.str();
+    to.print(str.c_str(), str.size());
+    return to;
+}
 
-class TypeCode 
+TextOutput& operator<<(TextOutput& to, TextOutputManipFunc func);
+
+class TypeCode
 {
 public:
     inline TypeCode(uint32_t code);
     inline ~TypeCode();
 
     inline uint32_t typeCode() const;
-    
+
 private:
     uint32_t mCode;
 };
@@ -124,6 +119,32 @@
 };
 
 TextOutput& operator<<(TextOutput& to, const HexDump& val);
+inline TextOutput& operator<<(TextOutput& to,
+                              decltype(std::endl<char,
+                                       std::char_traits<char>>)
+                              /*val*/) {
+    endl(to);
+    return to;
+}
+
+inline TextOutput& operator<<(TextOutput& to, const char &c)
+{
+    to.print(&c, 1);
+    return to;
+}
+
+inline TextOutput& operator<<(TextOutput& to, const bool &val)
+{
+    if (val) to.print("true", 4);
+    else to.print("false", 5);
+    return to;
+}
+
+inline TextOutput& operator<<(TextOutput& to, const String16& val)
+{
+    to << String8(val).string();
+    return to;
+}
 
 // ---------------------------------------------------------------------------
 // No user servicable parts below.
@@ -146,18 +167,6 @@
     return to;
 }
 
-inline TextOutput& operator<<(TextOutput& to, const char* str)
-{
-    to.print(str, strlen(str));
-    return to;
-}
-
-inline TextOutput& operator<<(TextOutput& to, char c)
-{
-    to.print(&c, 1);
-    return to;
-}
-
 inline TextOutput& operator<<(TextOutput& to, TextOutputManipFunc func)
 {
     return (*func)(to);
diff --git a/libs/binder/IPCThreadState.cpp b/libs/binder/IPCThreadState.cpp
index 9b5f0d7..02b4232 100644
--- a/libs/binder/IPCThreadState.cpp
+++ b/libs/binder/IPCThreadState.cpp
@@ -64,10 +64,6 @@
 
 namespace android {
 
-static const char* getReturnString(size_t idx);
-static const void* printReturnCommand(TextOutput& out, const void* _cmd);
-static const void* printCommand(TextOutput& out, const void* _cmd);
-
 // Static const and functions will be optimized out if not used,
 // when LOG_NDEBUG and references in IF_LOG_COMMANDS() are optimized out.
 static const char *kReturnStrings[] = {
@@ -111,8 +107,9 @@
     "BC_DEAD_BINDER_DONE"
 };
 
-static const char* getReturnString(size_t idx)
+static const char* getReturnString(uint32_t cmd)
 {
+    size_t idx = cmd & 0xff;
     if (idx < sizeof(kReturnStrings) / sizeof(kReturnStrings[0]))
         return kReturnStrings[idx];
     else
@@ -526,8 +523,8 @@
         }
     } while (result != -ECONNREFUSED && result != -EBADF);
 
-    LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%p\n",
-        (void*)pthread_self(), getpid(), (void*)result);
+    LOG_THREADPOOL("**** THREAD %p (PID %d) IS LEAVING THE THREAD POOL err=%d\n",
+        (void*)pthread_self(), getpid(), result);
     
     mOut.writeInt32(BC_EXIT_LOOPER);
     talkWithDriver(false);
@@ -669,7 +666,7 @@
     waitForResponse(NULL, &result);
     
 #if LOG_REFCOUNTS
-    printf("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
+    ALOGV("IPCThreadState::attemptIncStrongHandle(%ld) = %s\n",
         handle, result == NO_ERROR ? "SUCCESS" : "FAILURE");
 #endif
     
@@ -684,7 +681,7 @@
 void IPCThreadState::expungeHandle(int32_t handle, IBinder* binder)
 {
 #if LOG_REFCOUNTS
-    printf("IPCThreadState::expungeHandle(%ld)\n", handle);
+    ALOGV("IPCThreadState::expungeHandle(%ld)\n", handle);
 #endif
     self()->mProcess->expungeHandle(handle, binder);
 }
@@ -1171,7 +1168,7 @@
         break;
         
     default:
-        printf("*** BAD COMMAND %d received from Binder driver\n", cmd);
+        ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);
         result = UNKNOWN_ERROR;
         break;
     }
diff --git a/libs/binder/TextOutput.cpp b/libs/binder/TextOutput.cpp
index 2ed5188..101eba3 100644
--- a/libs/binder/TextOutput.cpp
+++ b/libs/binder/TextOutput.cpp
@@ -29,111 +29,14 @@
 
 // ---------------------------------------------------------------------------
 
-TextOutput::TextOutput() { 
+TextOutput::TextOutput() {
 }
 
-TextOutput::~TextOutput() { 
+TextOutput::~TextOutput() {
 }
 
 // ---------------------------------------------------------------------------
 
-TextOutput& operator<<(TextOutput& to, bool val)
-{
-    if (val) to.print("true", 4);
-    else to.print("false", 5);
-    return to;
-}
-
-TextOutput& operator<<(TextOutput& to, int val)
-{
-    char buf[16];
-    sprintf(buf, "%d", val);
-    to.print(buf, strlen(buf));
-    return to;
-}
-
-TextOutput& operator<<(TextOutput& to, long val)
-{
-    char buf[16];
-    sprintf(buf, "%ld", val);
-    to.print(buf, strlen(buf));
-    return to;
-}
-
-TextOutput& operator<<(TextOutput& to, unsigned int val)
-{
-    char buf[16];
-    sprintf(buf, "%u", val);
-    to.print(buf, strlen(buf));
-    return to;
-}
-
-TextOutput& operator<<(TextOutput& to, unsigned long val)
-{
-    char buf[16];
-    sprintf(buf, "%lu", val);
-    to.print(buf, strlen(buf));
-    return to;
-}
-
-TextOutput& operator<<(TextOutput& to, long long val)
-{
-    char buf[32];
-    sprintf(buf, "%Ld", val);
-    to.print(buf, strlen(buf));
-    return to;
-}
-
-TextOutput& operator<<(TextOutput& to, unsigned long long val)
-{
-    char buf[32];
-    sprintf(buf, "%Lu", val);
-    to.print(buf, strlen(buf));
-    return to;
-}
-
-static TextOutput& print_float(TextOutput& to, double value)
-{
-    char buf[64];
-    sprintf(buf, "%g", value);
-    if( !strchr(buf, '.') && !strchr(buf, 'e') &&
-        !strchr(buf, 'E') ) {
-        strncat(buf, ".0", sizeof(buf)-1);
-    }
-    to.print(buf, strlen(buf));
-    return to;
-}
-
-TextOutput& operator<<(TextOutput& to, float val)
-{
-    return print_float(to,val);
-}
-
-TextOutput& operator<<(TextOutput& to, double val)
-{
-    return print_float(to,val);
-}
-
-TextOutput& operator<<(TextOutput& to, const void* val)
-{
-    char buf[32];
-    snprintf(buf, sizeof(buf), "%p", val);
-    to.print(buf, strlen(buf));
-    return to;
-}
-
-TextOutput& operator<<(TextOutput& to, const String8& val)
-{
-    to << val.string();
-    return to;
-}
-
-TextOutput& operator<<(TextOutput& to, const String16& val)
-{
-    to << String8(val).string();
-    return to;
-}
-
 static void textOutputPrinter(void* cookie, const char* txt)
 {
     ((TextOutput*)cookie)->print(txt, strlen(txt));
diff --git a/libs/binder/tests/Android.bp b/libs/binder/tests/Android.bp
index 4f77eed..2152206 100644
--- a/libs/binder/tests/Android.bp
+++ b/libs/binder/tests/Android.bp
@@ -51,3 +51,13 @@
         "-O3",
     ],
 }
+
+cc_test {
+    name: "binderTextOutputTest",
+    srcs: ["binderTextOutputTest.cpp"],
+    shared_libs: [
+        "libbinder",
+        "libutils",
+        "libbase",
+    ],
+}
diff --git a/libs/binder/tests/binderDriverInterfaceTest.cpp b/libs/binder/tests/binderDriverInterfaceTest.cpp
index e02844e..ff5912f 100644
--- a/libs/binder/tests/binderDriverInterfaceTest.cpp
+++ b/libs/binder/tests/binderDriverInterfaceTest.cpp
@@ -229,7 +229,9 @@
             .sender_euid = 0,
             .data_size = 0,
             .offsets_size = 0,
-            .data = {0, 0},
+            .data = {
+                .ptr = {0, 0},
+            },
         },
     };
     struct {
@@ -350,4 +352,3 @@
 
     return RUN_ALL_TESTS();
 }
-
diff --git a/libs/binder/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp
index 17479ca..54e12b6 100644
--- a/libs/binder/tests/binderLibTest.cpp
+++ b/libs/binder/tests/binderLibTest.cpp
@@ -34,6 +34,7 @@
 
 static testing::Environment* binder_env;
 static char *binderservername;
+static char *binderserversuffix;
 static char binderserverarg[] = "--binderserver";
 
 static String16 binderLibTestServiceName = String16("test.binderLib");
@@ -70,6 +71,7 @@
         binderserverarg,
         stri,
         strpipefd1,
+        binderserversuffix,
         NULL
     };
 
@@ -898,6 +900,8 @@
 
 int run_server(int index, int readypipefd)
 {
+    binderLibTestServiceName += String16(binderserversuffix);
+
     status_t ret;
     sp<IServiceManager> sm = defaultServiceManager();
     {
@@ -928,15 +932,19 @@
 int main(int argc, char **argv) {
     int ret;
 
-    if (argc == 3 && !strcmp(argv[1], "--servername")) {
+    if (argc == 4 && !strcmp(argv[1], "--servername")) {
         binderservername = argv[2];
     } else {
         binderservername = argv[0];
     }
 
-    if (argc == 4 && !strcmp(argv[1], binderserverarg)) {
+    if (argc == 5 && !strcmp(argv[1], binderserverarg)) {
+        binderserversuffix = argv[4];
         return run_server(atoi(argv[2]), atoi(argv[3]));
     }
+    binderserversuffix = new char[16];
+    snprintf(binderserversuffix, 16, "%d", getpid());
+    binderLibTestServiceName += String16(binderserversuffix);
 
     ::testing::InitGoogleTest(&argc, argv);
     binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
diff --git a/libs/binder/tests/binderTextOutputTest.cpp b/libs/binder/tests/binderTextOutputTest.cpp
new file mode 100644
index 0000000..f6dd22d
--- /dev/null
+++ b/libs/binder/tests/binderTextOutputTest.cpp
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <limits>
+#include <cstddef>
+
+#include "android-base/file.h"
+#include "android-base/test_utils.h"
+#include <gtest/gtest.h>
+
+#include <binder/Parcel.h>
+#include <binder/TextOutput.h>
+#include <binder/Debug.h>
+
+static void CheckMessage(const CapturedStderr& cap,
+                         const char* expected,
+                         bool singleline) {
+    std::string output;
+    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
+    android::base::ReadFdToString(cap.fd(), &output);
+    if (singleline)
+        output.erase(std::remove(output.begin(), output.end(), '\n'));
+    ASSERT_STREQ(output.c_str(), expected);
+}
+
+#define CHECK_LOG_(input, expect, singleline)    \
+{                                                \
+    CapturedStderr cap;                          \
+    android::aerr << input << android::endl;     \
+    CheckMessage(cap, expect, singleline);       \
+}                                                \
+
+#define CHECK_VAL_(val, singleline)              \
+{                                                \
+    std::stringstream ss;                        \
+    ss << val;                                   \
+    std::string s = ss.str();                    \
+    CHECK_LOG_(val, s.c_str(), singleline);      \
+}                                                \
+
+#define CHECK_LOG(input, expect) CHECK_LOG_(input, expect, true)
+#define CHECK_VAL(val) CHECK_VAL_(val, true)
+
+TEST(TextOutput, HandlesStdEndl) {
+    CapturedStderr cap;
+    android::aerr << "foobar" << std::endl;
+    std::string output;
+    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
+    android::base::ReadFdToString(cap.fd(), &output);
+    ASSERT_STREQ(output.c_str(), "foobar\n");
+}
+
+TEST(TextOutput, HandlesCEndl) {
+    CapturedStderr cap;
+    android::aerr << "foobar" << "\n";
+    std::string output;
+    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
+    android::base::ReadFdToString(cap.fd(), &output);
+    ASSERT_STREQ(output.c_str(), "foobar\n");
+}
+
+TEST(TextOutput, HandlesAndroidEndl) {
+    CapturedStderr cap;
+    android::aerr << "foobar" << android::endl;
+    std::string output;
+    ASSERT_EQ(0, lseek(cap.fd(), 0, SEEK_SET));
+    android::base::ReadFdToString(cap.fd(), &output);
+    ASSERT_STREQ(output.c_str(), "foobar\n");
+}
+
+TEST(TextOutput, HandleEmptyString) {
+    CHECK_LOG("", "");
+}
+
+TEST(TextOutput, HandleString) {
+    CHECK_LOG("foobar", "foobar");
+}
+
+TEST(TextOutput, HandleNum) {
+    CHECK_LOG(12345, "12345");
+}
+
+TEST(TextOutput, HandleBool) {
+    CHECK_LOG(false, "false");
+}
+
+TEST(TextOutput, HandleChar) {
+    CHECK_LOG('T', "T");
+}
+
+TEST(TextOutput, HandleParcel) {
+    android::Parcel val;
+    CHECK_LOG(val, "Parcel(NULL)");
+}
+
+TEST(TextOutput, HandleHexDump) {
+    const char buf[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
+    android::HexDump val(buf, sizeof(buf));
+    CHECK_LOG(val, "03020100 07060504 0b0a0908 0f0e0d0c '................'");
+}
+
+TEST(TextOutput, HandleHexDumpCustom) {
+    const char buf[4] = {0x11,0x22,0x33,0x44};
+    android::HexDump val(buf, sizeof(buf), 4);
+    CHECK_LOG(val, "11 22 33 44 '.\"3D'");
+}
+
+TEST(TextOutput, HandleTypeCode) {
+    android::TypeCode val(1234);
+    CHECK_LOG(val, "'\\x04\\xd2'");
+}
+
+TEST(TextOutput, HandleCookie) {
+    int32_t val = 321; //0x141
+    CHECK_LOG((void*)(long)val, "0x141");
+}
+
+TEST(TextOutput, HandleString8) {
+    android::String8 val("foobar");
+    CHECK_LOG(val, "foobar");
+}
+
+TEST(TextOutput, HandleString16) {
+    android::String16 val("foobar");
+    CHECK_LOG(val, "foobar");
+}
+
+template <typename T>
+class TextTest : public testing::Test {};
+
+typedef testing::Types<short, unsigned short,
+                       int, unsigned int,
+                       long, unsigned long,
+                       long long, unsigned long long,
+                       float, double, long double> TestTypes;
+TYPED_TEST_CASE(TextTest, TestTypes);
+
+TYPED_TEST(TextTest, TextMax)
+{
+    TypeParam max = std::numeric_limits<TypeParam>::max();
+    CHECK_VAL(max);
+}
+
+TYPED_TEST(TextTest, TestMin)
+{
+    TypeParam min = std::numeric_limits<TypeParam>::min();
+    CHECK_VAL(min);
+}
+
+TYPED_TEST(TextTest, TestDenom)
+{
+    TypeParam min = std::numeric_limits<TypeParam>::denorm_min();
+    CHECK_VAL(min);
+}
+
+TYPED_TEST(TextTest, TestEpsilon)
+{
+    TypeParam eps = std::numeric_limits<TypeParam>::epsilon();
+    CHECK_VAL(eps);
+}
diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp
new file mode 100644
index 0000000..b558ec9
--- /dev/null
+++ b/libs/gui/Android.bp
@@ -0,0 +1,110 @@
+// Copyright 2010 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.
+
+cc_library_shared {
+    name: "libgui",
+
+    clang: true,
+    cppflags: [
+        "-Weverything",
+        "-Werror",
+
+        // The static constructors and destructors in this library have not been noted to
+        // introduce significant overheads
+        "-Wno-exit-time-destructors",
+        "-Wno-global-constructors",
+
+        // We only care about compiling as C++14
+        "-Wno-c++98-compat-pedantic",
+
+        // We don't need to enumerate every case in a switch as long as a default case
+        // is present
+        "-Wno-switch-enum",
+
+        // Allow calling variadic macros without a __VA_ARGS__ list
+        "-Wno-gnu-zero-variadic-macro-arguments",
+
+        // Don't warn about struct padding
+        "-Wno-padded",
+
+        // android/sensors.h uses nested anonymous unions and anonymous structs
+        "-Wno-nested-anon-types",
+        "-Wno-gnu-anonymous-struct",
+
+        "-DDEBUG_ONLY_CODE=0",
+    ],
+
+    product_variables: {
+        brillo: {
+            cflags: ["-DHAVE_NO_SURFACE_FLINGER"],
+        },
+        debuggable: {
+            cppflags: [
+                "-UDEBUG_ONLY_CODE",
+                "-DDEBUG_ONLY_CODE=1",
+            ],
+        },
+    },
+
+    srcs: [
+        "IGraphicBufferConsumer.cpp",
+        "IConsumerListener.cpp",
+        "BitTube.cpp",
+        "BufferItem.cpp",
+        "BufferItemConsumer.cpp",
+        "BufferQueue.cpp",
+        "BufferQueueConsumer.cpp",
+        "BufferQueueCore.cpp",
+        "BufferQueueProducer.cpp",
+        "BufferSlot.cpp",
+        "ConsumerBase.cpp",
+        "CpuConsumer.cpp",
+        "DisplayEventReceiver.cpp",
+        "GLConsumer.cpp",
+        "GraphicBufferAlloc.cpp",
+        "GuiConfig.cpp",
+        "IDisplayEventConnection.cpp",
+        "IGraphicBufferAlloc.cpp",
+        "IGraphicBufferProducer.cpp",
+        "IProducerListener.cpp",
+        "ISensorEventConnection.cpp",
+        "ISensorServer.cpp",
+        "ISurfaceComposer.cpp",
+        "ISurfaceComposerClient.cpp",
+        "LayerState.cpp",
+        "Sensor.cpp",
+        "SensorEventQueue.cpp",
+        "SensorManager.cpp",
+        "StreamSplitter.cpp",
+        "Surface.cpp",
+        "SurfaceControl.cpp",
+        "SurfaceComposerClient.cpp",
+        "SyncFeatures.cpp",
+    ],
+
+    shared_libs: [
+        "libbinder",
+        "libcutils",
+        "libEGL",
+        "libGLESv2",
+        "libsync",
+        "libui",
+        "libutils",
+        "liblog",
+    ],
+
+    export_shared_lib_headers: ["libbinder"],
+}
+
+subdirs = ["tests"]
diff --git a/libs/gui/Android.mk b/libs/gui/Android.mk
deleted file mode 100644
index 909ca67..0000000
--- a/libs/gui/Android.mk
+++ /dev/null
@@ -1,108 +0,0 @@
-# Copyright 2010 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.
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_CLANG := true
-LOCAL_CPPFLAGS := -Weverything -Werror
-
-# The static constructors and destructors in this library have not been noted to
-# introduce significant overheads
-LOCAL_CPPFLAGS += -Wno-exit-time-destructors
-LOCAL_CPPFLAGS += -Wno-global-constructors
-
-# We only care about compiling as C++14
-LOCAL_CPPFLAGS += -Wno-c++98-compat-pedantic
-
-# We don't need to enumerate every case in a switch as long as a default case
-# is present
-LOCAL_CPPFLAGS += -Wno-switch-enum
-
-# Allow calling variadic macros without a __VA_ARGS__ list
-LOCAL_CPPFLAGS += -Wno-gnu-zero-variadic-macro-arguments
-
-# Don't warn about struct padding
-LOCAL_CPPFLAGS += -Wno-padded
-
-# android/sensors.h uses nested anonymous unions and anonymous structs
-LOCAL_CPPFLAGS += -Wno-nested-anon-types -Wno-gnu-anonymous-struct
-
-LOCAL_CPPFLAGS += -DDEBUG_ONLY_CODE=$(if $(filter userdebug eng,$(TARGET_BUILD_VARIANT)),1,0)
-
-LOCAL_SRC_FILES := \
-	IGraphicBufferConsumer.cpp \
-	IConsumerListener.cpp \
-	BitTube.cpp \
-	BufferItem.cpp \
-	BufferItemConsumer.cpp \
-	BufferQueue.cpp \
-	BufferQueueConsumer.cpp \
-	BufferQueueCore.cpp \
-	BufferQueueProducer.cpp \
-	BufferSlot.cpp \
-	ConsumerBase.cpp \
-	CpuConsumer.cpp \
-	DisplayEventReceiver.cpp \
-	GLConsumer.cpp \
-	GraphicBufferAlloc.cpp \
-	GuiConfig.cpp \
-	IDisplayEventConnection.cpp \
-	IGraphicBufferAlloc.cpp \
-	IGraphicBufferProducer.cpp \
-	IProducerListener.cpp \
-	ISensorEventConnection.cpp \
-	ISensorServer.cpp \
-	ISurfaceComposer.cpp \
-	ISurfaceComposerClient.cpp \
-	LayerState.cpp \
-	Sensor.cpp \
-	SensorEventQueue.cpp \
-	SensorManager.cpp \
-	StreamSplitter.cpp \
-	Surface.cpp \
-	SurfaceControl.cpp \
-	SurfaceComposerClient.cpp \
-	SyncFeatures.cpp \
-
-LOCAL_SHARED_LIBRARIES := \
-	libbinder \
-	libcutils \
-	libEGL \
-	libGLESv2 \
-	libsync \
-	libui \
-	libutils \
-	liblog
-
-LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := libbinder
-
-LOCAL_MODULE := libgui
-
-ifeq ($(TARGET_BOARD_PLATFORM), tegra)
-	LOCAL_CFLAGS += -DDONT_USE_FENCE_SYNC
-endif
-ifeq ($(TARGET_BOARD_PLATFORM), tegra3)
-	LOCAL_CFLAGS += -DDONT_USE_FENCE_SYNC
-endif
-
-ifeq ($(TARGET_BOARD_HAS_NO_SURFACE_FLINGER), true)
-	LOCAL_CFLAGS += -DHAVE_NO_SURFACE_FLINGER
-endif
-
-include $(BUILD_SHARED_LIBRARY)
-
-ifeq (,$(ONE_SHOT_MAKEFILE))
-include $(call first-makefiles-under,$(LOCAL_PATH))
-endif
diff --git a/libs/gui/GLConsumer.cpp b/libs/gui/GLConsumer.cpp
index aa0db45..10e999c 100644
--- a/libs/gui/GLConsumer.cpp
+++ b/libs/gui/GLConsumer.cpp
@@ -1228,14 +1228,19 @@
         EGL_NONE,
     };
     if (!crop.isValid()) {
-        // No crop rect to set, so terminate the attrib array before the crop.
-        attrs[2] = EGL_NONE;
+        // No crop rect to set, so leave the crop out of the attrib array. Make
+        // sure to propagate the protected content attrs if they are set.
+        attrs[2] = attrs[10];
+        attrs[3] = attrs[11];
+        attrs[4] = EGL_NONE;
     } else if (!isEglImageCroppable(crop)) {
         // The crop rect is not at the origin, so we can't set the crop on the
         // EGLImage because that's not allowed by the EGL_ANDROID_image_crop
         // extension.  In the future we can add a layered extension that
         // removes this restriction if there is hardware that can support it.
-        attrs[2] = EGL_NONE;
+        attrs[2] = attrs[10];
+        attrs[3] = attrs[11];
+        attrs[4] = EGL_NONE;
     }
     eglInitialize(dpy, 0, 0);
     EGLImageKHR image = eglCreateImageKHR(dpy, EGL_NO_CONTEXT,
diff --git a/libs/gui/tests/Android.bp b/libs/gui/tests/Android.bp
new file mode 100644
index 0000000..3c7958f
--- /dev/null
+++ b/libs/gui/tests/Android.bp
@@ -0,0 +1,42 @@
+// Build the unit tests,
+
+// Build the binary to $(TARGET_OUT_DATA_NATIVE_TESTS)/$(LOCAL_MODULE)
+// to integrate with auto-test framework.
+cc_test {
+    name: "libgui_test",
+
+    clang: true,
+
+    srcs: [
+        "BufferQueue_test.cpp",
+        "CpuConsumer_test.cpp",
+        "FillBuffer.cpp",
+        "GLTest.cpp",
+        "IGraphicBufferProducer_test.cpp",
+        "MultiTextureConsumer_test.cpp",
+        "Sensor_test.cpp",
+        "SRGB_test.cpp",
+        "StreamSplitter_test.cpp",
+        "SurfaceTextureClient_test.cpp",
+        "SurfaceTextureFBO_test.cpp",
+        "SurfaceTextureGLThreadToGL_test.cpp",
+        "SurfaceTextureGLToGL_test.cpp",
+        "SurfaceTextureGL_test.cpp",
+        "SurfaceTextureMultiContextGL_test.cpp",
+        "Surface_test.cpp",
+        "TextureRenderer.cpp",
+    ],
+
+    shared_libs: [
+        "liblog",
+        "libEGL",
+        "libGLESv1_CM",
+        "libGLESv2",
+        "libbinder",
+        "libcutils",
+        "libgui",
+        "libsync",
+        "libui",
+        "libutils",
+    ],
+}
diff --git a/libs/gui/tests/Android.mk b/libs/gui/tests/Android.mk
deleted file mode 100644
index efae7f6..0000000
--- a/libs/gui/tests/Android.mk
+++ /dev/null
@@ -1,54 +0,0 @@
-# Build the unit tests,
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-
-LOCAL_CLANG := true
-
-LOCAL_MODULE := libgui_test
-
-LOCAL_MODULE_TAGS := tests
-
-LOCAL_SRC_FILES := \
-    BufferQueue_test.cpp \
-    CpuConsumer_test.cpp \
-    FillBuffer.cpp \
-    GLTest.cpp \
-    IGraphicBufferProducer_test.cpp \
-    MultiTextureConsumer_test.cpp \
-    Sensor_test.cpp \
-    SRGB_test.cpp \
-    StreamSplitter_test.cpp \
-    SurfaceTextureClient_test.cpp \
-    SurfaceTextureFBO_test.cpp \
-    SurfaceTextureGLThreadToGL_test.cpp \
-    SurfaceTextureGLToGL_test.cpp \
-    SurfaceTextureGL_test.cpp \
-    SurfaceTextureMultiContextGL_test.cpp \
-    Surface_test.cpp \
-    TextureRenderer.cpp \
-
-LOCAL_SHARED_LIBRARIES := \
-	liblog \
-	libEGL \
-	libGLESv1_CM \
-	libGLESv2 \
-	libbinder \
-	libcutils \
-	libgui \
-	libsync \
-	libui \
-	libutils \
-
-# Build the binary to $(TARGET_OUT_DATA_NATIVE_TESTS)/$(LOCAL_MODULE)
-# to integrate with auto-test framework.
-include $(BUILD_NATIVE_TEST)
-
-# Include subdirectory makefiles
-# ============================================================
-
-# If we're building with ONE_SHOT_MAKEFILE (mm, mmm), then what the framework
-# team really wants is to build the stuff defined by this makefile.
-ifeq (,$(ONE_SHOT_MAKEFILE))
-include $(call first-makefiles-under,$(LOCAL_PATH))
-endif
diff --git a/opengl/Android.bp b/opengl/Android.bp
index 164be20..c520bda 100644
--- a/opengl/Android.bp
+++ b/opengl/Android.bp
@@ -17,6 +17,7 @@
     from: "include",
     to: "",
     srcs: ["include/EGL/**/*.h"],
+    license: "include/EGL/NOTICE",
 }
 
 ndk_headers {
@@ -24,6 +25,7 @@
     from: "include",
     to: "",
     srcs: ["include/GLES/**/*.h"],
+    license: "include/GLES/NOTICE",
 }
 
 ndk_headers {
@@ -31,6 +33,7 @@
     from: "include",
     to: "",
     srcs: ["include/GLES2/**/*.h"],
+    license: "include/GLES2/NOTICE",
 }
 
 ndk_headers {
@@ -38,6 +41,7 @@
     from: "include",
     to: "",
     srcs: ["include/GLES3/**/*.h"],
+    license: "include/GLES3/NOTICE",
 }
 
 ndk_headers {
@@ -45,6 +49,7 @@
     from: "include",
     to: "",
     srcs: ["include/KHR/**/*.h"],
+    license: "include/KHR/NOTICE",
 }
 
 subdirs = [
diff --git a/opengl/include/EGL/NOTICE b/opengl/include/EGL/NOTICE
new file mode 100644
index 0000000..55f5efa
--- /dev/null
+++ b/opengl/include/EGL/NOTICE
@@ -0,0 +1,20 @@
+Copyright (c) 2007-2009 The Khronos Group Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and/or associated documentation files (the
+"Materials"), to deal in the Materials without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Materials, and to
+permit persons to whom the Materials are furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Materials.
+
+THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
diff --git a/opengl/include/EGL/egl.h b/opengl/include/EGL/egl.h
index 99ea342..ccb54ea 100644
--- a/opengl/include/EGL/egl.h
+++ b/opengl/include/EGL/egl.h
@@ -65,13 +65,13 @@
 #define EGL_TRUE			1
 
 /* Out-of-band handle values */
-#define EGL_DEFAULT_DISPLAY		((EGLNativeDisplayType)0)
-#define EGL_NO_CONTEXT			((EGLContext)0)
-#define EGL_NO_DISPLAY			((EGLDisplay)0)
-#define EGL_NO_SURFACE			((EGLSurface)0)
+#define EGL_DEFAULT_DISPLAY		EGL_CAST(EGLNativeDisplayType, 0)
+#define EGL_NO_CONTEXT			EGL_CAST(EGLContext, 0)
+#define EGL_NO_DISPLAY			EGL_CAST(EGLDisplay, 0)
+#define EGL_NO_SURFACE			EGL_CAST(EGLSurface, 0)
 
 /* Out-of-band attribute value */
-#define EGL_DONT_CARE			((EGLint)-1)
+#define EGL_DONT_CARE			EGL_CAST(EGLint, -1)
 
 /* Errors / GetError return values */
 #define EGL_SUCCESS			0x3000
@@ -198,7 +198,7 @@
 #define EGL_DISPLAY_SCALING		10000
 
 /* Unknown display resolution/aspect ratio */
-#define EGL_UNKNOWN			((EGLint)-1)
+#define EGL_UNKNOWN			EGL_CAST(EGLint, -1)
 
 /* Back buffer swap behaviors */
 #define EGL_BUFFER_PRESERVED		0x3094	/* EGL_SWAP_BEHAVIOR value */
diff --git a/opengl/include/EGL/eglext.h b/opengl/include/EGL/eglext.h
index c72388a..0a14138 100644
--- a/opengl/include/EGL/eglext.h
+++ b/opengl/include/EGL/eglext.h
@@ -79,7 +79,7 @@
 #define EGL_KHR_image 1
 #define EGL_NATIVE_PIXMAP_KHR			0x30B0	/* eglCreateImageKHR target */
 typedef void *EGLImageKHR;
-#define EGL_NO_IMAGE_KHR			((EGLImageKHR)0)
+#define EGL_NO_IMAGE_KHR			EGL_CAST(EGLImageKHR, 0)
 #ifdef EGL_EGLEXT_PROTOTYPES
 EGLAPI EGLImageKHR EGLAPIENTRY eglCreateImageKHR (EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLint *attrib_list);
 EGLAPI EGLBoolean EGLAPIENTRY eglDestroyImageKHR (EGLDisplay dpy, EGLImageKHR image);
@@ -143,7 +143,7 @@
 #define EGL_SYNC_REUSABLE_KHR			0x30FA
 #define EGL_SYNC_FLUSH_COMMANDS_BIT_KHR		0x0001	/* eglClientWaitSyncKHR <flags> bitfield */
 #define EGL_FOREVER_KHR				0xFFFFFFFFFFFFFFFFull
-#define EGL_NO_SYNC_KHR				((EGLSyncKHR)0)
+#define EGL_NO_SYNC_KHR				EGL_CAST(EGLSyncKHR, 0)
 #ifdef EGL_EGLEXT_PROTOTYPES
 EGLAPI EGLSyncKHR EGLAPIENTRY eglCreateSyncKHR(EGLDisplay dpy, EGLenum type, const EGLint *attrib_list);
 EGLAPI EGLBoolean EGLAPIENTRY eglDestroySyncKHR(EGLDisplay dpy, EGLSyncKHR sync);
@@ -220,7 +220,7 @@
 #define EGL_SYNC_TYPE_NV			0x30ED
 #define EGL_SYNC_CONDITION_NV			0x30EE
 #define EGL_SYNC_FENCE_NV			0x30EF
-#define EGL_NO_SYNC_NV				((EGLSyncNV)0)
+#define EGL_NO_SYNC_NV				EGL_CAST(EGLSyncNV, 0)
 typedef void* EGLSyncNV;
 typedef khronos_utime_nanoseconds_t EGLTimeNV;
 #ifdef EGL_EGLEXT_PROTOTYPES
@@ -346,7 +346,7 @@
 #define EGL_KHR_stream 1
 typedef void* EGLStreamKHR;
 typedef khronos_uint64_t EGLuint64KHR;
-#define EGL_NO_STREAM_KHR			((EGLStreamKHR)0)
+#define EGL_NO_STREAM_KHR			EGL_CAST(EGLStreamKHR, 0)
 #define EGL_CONSUMER_LATENCY_USEC_KHR		0x3210
 #define EGL_PRODUCER_FRAME_KHR			0x3212
 #define EGL_CONSUMER_FRAME_KHR			0x3213
@@ -473,7 +473,7 @@
 #ifndef EGL_KHR_stream_cross_process_fd
 #define EGL_KHR_stream_cross_process_fd 1
 typedef int EGLNativeFileDescriptorKHR;
-#define EGL_NO_FILE_DESCRIPTOR_KHR		((EGLNativeFileDescriptorKHR)(-1))
+#define EGL_NO_FILE_DESCRIPTOR_KHR		EGL_CAST(EGLNativeFileDescriptorKHR, -1)
 #ifdef EGL_EGLEXT_PROTOTYPES
 EGLAPI EGLNativeFileDescriptorKHR EGLAPIENTRY eglGetStreamFileDescriptorKHR(EGLDisplay dpy, EGLStreamKHR stream);
 EGLAPI EGLStreamKHR EGLAPIENTRY eglCreateStreamFromFileDescriptorKHR(EGLDisplay dpy, EGLNativeFileDescriptorKHR file_descriptor);
@@ -614,7 +614,7 @@
 #ifdef EGL_EGLEXT_PROTOTYPES
 EGLAPI EGLClientBuffer eglCreateNativeClientBufferANDROID (const EGLint *attrib_list);
 #else
-typedef EGLAPI EGLClientBuffer (EGLAPIENTRYP PFNEGLCREATENATIVECLIENTBUFFERANDROID) (const EGLint *attrib_list);
+typedef EGLClientBuffer (EGLAPIENTRYP PFNEGLCREATENATIVECLIENTBUFFERANDROID) (const EGLint *attrib_list);
 #endif
 #endif
 
diff --git a/opengl/include/EGL/eglplatform.h b/opengl/include/EGL/eglplatform.h
index 354ac22..54011c8 100644
--- a/opengl/include/EGL/eglplatform.h
+++ b/opengl/include/EGL/eglplatform.h
@@ -121,4 +121,10 @@
  */
 typedef khronos_int32_t EGLint;
 
+#if defined(__cplusplus)
+#define EGL_CAST(type, value) (static_cast<type>(value))
+#else
+#define EGL_CAST(type, value) ((type) (value))
+#endif
+
 #endif /* __eglplatform_h */
diff --git a/opengl/include/GLES/NOTICE b/opengl/include/GLES/NOTICE
new file mode 100644
index 0000000..4dc6614
--- /dev/null
+++ b/opengl/include/GLES/NOTICE
@@ -0,0 +1,2 @@
+This document is licensed under the SGI Free Software B License Version 2.0.
+For details, see http://oss.sgi.com/projects/FreeB/ .
diff --git a/opengl/include/GLES2/NOTICE b/opengl/include/GLES2/NOTICE
new file mode 100644
index 0000000..7a94373
--- /dev/null
+++ b/opengl/include/GLES2/NOTICE
@@ -0,0 +1,20 @@
+Copyright (c) 2013-2015 The Khronos Group Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and/or associated documentation files (the
+"Materials"), to deal in the Materials without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Materials, and to
+permit persons to whom the Materials are furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Materials.
+
+THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
diff --git a/opengl/include/GLES3/NOTICE b/opengl/include/GLES3/NOTICE
new file mode 100644
index 0000000..7a94373
--- /dev/null
+++ b/opengl/include/GLES3/NOTICE
@@ -0,0 +1,20 @@
+Copyright (c) 2013-2015 The Khronos Group Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and/or associated documentation files (the
+"Materials"), to deal in the Materials without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Materials, and to
+permit persons to whom the Materials are furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Materials.
+
+THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
diff --git a/opengl/include/KHR/NOTICE b/opengl/include/KHR/NOTICE
new file mode 100644
index 0000000..36796e8
--- /dev/null
+++ b/opengl/include/KHR/NOTICE
@@ -0,0 +1,20 @@
+Copyright (c) 2008-2009 The Khronos Group Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and/or associated documentation files (the
+"Materials"), to deal in the Materials without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Materials, and to
+permit persons to whom the Materials are furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Materials.
+
+THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
diff --git a/opengl/libs/Android.bp b/opengl/libs/Android.bp
index bdd5152..6a8aac8 100644
--- a/opengl/libs/Android.bp
+++ b/opengl/libs/Android.bp
@@ -45,3 +45,116 @@
     symbol_file: "libGLESv3.map.txt",
     first_version: "18",
 }
+
+cc_defaults {
+    name: "gl_libs_defaults",
+    cflags: [
+        "-DGL_GLEXT_PROTOTYPES",
+        "-DEGL_EGLEXT_PROTOTYPES",
+        "-fvisibility=hidden",
+    ],
+    shared_libs: [
+        "libcutils",
+        "liblog",
+        "libdl",
+    ],
+
+    // we need to access the private Bionic header <bionic_tls.h>
+    include_dirs: ["bionic/libc/private"],
+}
+
+//##############################################################################
+// Build META EGL library
+//
+cc_defaults {
+    name: "egl_libs_defaults",
+    defaults: ["gl_libs_defaults"],
+    cflags: [
+        "-DLOG_TAG=\"libEGL\"",
+    ],
+    shared_libs: [
+        "libbinder",
+        "libutils",
+        "libui",
+    ],
+}
+
+cc_library_static {
+    name: "libEGL_getProcAddress",
+    defaults: ["egl_libs_defaults"],
+    srcs: ["EGL/getProcAddress.cpp"],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+        },
+    },
+}
+
+cc_library_shared {
+    name: "libEGL",
+    defaults: ["egl_libs_defaults"],
+    srcs: [
+        "EGL/egl_tls.cpp",
+        "EGL/egl_cache.cpp",
+        "EGL/egl_display.cpp",
+        "EGL/egl_object.cpp",
+        "EGL/egl.cpp",
+        "EGL/eglApi.cpp",
+        "EGL/Loader.cpp",
+    ],
+    static_libs: ["libEGL_getProcAddress"],
+    ldflags: ["-Wl,--exclude-libs=ALL"],
+
+    required: ["egl.cfg"],
+}
+
+cc_defaults {
+    name: "gles_libs_defaults",
+    defaults: ["gl_libs_defaults"],
+    arch: {
+        arm: {
+            instruction_set: "arm",
+
+            // TODO: This is to work around b/20093774. Remove after root cause is fixed
+            ldflags: ["-Wl,--hash-style,both"],
+        },
+    },
+    shared_libs: ["libEGL"],
+}
+
+//##############################################################################
+// Build the wrapper OpenGL ES 1.x library
+//
+cc_library_shared {
+    name: "libGLESv1_CM",
+    defaults: ["gles_libs_defaults"],
+    srcs: ["GLES_CM/gl.cpp"],
+
+    cflags: ["-DLOG_TAG=\"libGLESv1\""],
+}
+
+//##############################################################################
+// Build the wrapper OpenGL ES 2.x library
+//
+cc_library_shared {
+    name: "libGLESv2",
+    defaults: ["gles_libs_defaults"],
+    srcs: ["GLES2/gl2.cpp"],
+
+    shared_libs: ["libutils"],
+
+    cflags: ["-DLOG_TAG=\"libGLESv2\""],
+}
+
+//##############################################################################
+// Build the wrapper OpenGL ES 3.x library (this is just different name for v2)
+//
+cc_library_shared {
+    name: "libGLESv3",
+    defaults: ["gles_libs_defaults"],
+    srcs: ["GLES2/gl2.cpp"],
+
+    shared_libs: ["libutils"],
+
+    cflags: ["-DLOG_TAG=\"libGLESv3\""],
+}
diff --git a/opengl/libs/Android.mk b/opengl/libs/Android.mk
index f0ba728..21e76f5 100644
--- a/opengl/libs/Android.mk
+++ b/opengl/libs/Android.mk
@@ -1,13 +1,7 @@
 LOCAL_PATH:= $(call my-dir)
 
-###############################################################################
-# Build META EGL library
-#
-
-egl.cfg_config_module :=
 # OpenGL drivers config file
 ifneq ($(BOARD_EGL_CFG),)
-
 include $(CLEAR_VARS)
 LOCAL_MODULE := egl.cfg
 LOCAL_MODULE_TAGS := optional
@@ -15,136 +9,4 @@
 LOCAL_MODULE_PATH := $(TARGET_OUT)/lib/egl
 LOCAL_SRC_FILES := ../../../../$(BOARD_EGL_CFG)
 include $(BUILD_PREBUILT)
-egl.cfg_config_module := $(LOCAL_MODULE)
 endif
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= 	       \
-	EGL/egl_tls.cpp        \
-	EGL/egl_cache.cpp      \
-	EGL/egl_display.cpp    \
-	EGL/egl_object.cpp     \
-	EGL/egl.cpp 	       \
-	EGL/eglApi.cpp 	       \
-	EGL/getProcAddress.cpp.arm \
-	EGL/Loader.cpp 	       \
-#
-
-LOCAL_SHARED_LIBRARIES += libbinder libcutils libutils liblog libui
-LOCAL_MODULE:= libEGL
-LOCAL_LDFLAGS += -Wl,--exclude-libs=ALL
-LOCAL_SHARED_LIBRARIES += libdl
-# we need to access the private Bionic header <bionic_tls.h>
-LOCAL_C_INCLUDES += bionic/libc/private
-
-LOCAL_CFLAGS += -DLOG_TAG=\"libEGL\"
-LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
-LOCAL_CFLAGS += -fvisibility=hidden
-
-ifeq ($(BOARD_ALLOW_EGL_HIBERNATION),true)
-  LOCAL_CFLAGS += -DBOARD_ALLOW_EGL_HIBERNATION
-endif
-ifneq ($(MAX_EGL_CACHE_ENTRY_SIZE),)
-  LOCAL_CFLAGS += -DMAX_EGL_CACHE_ENTRY_SIZE=$(MAX_EGL_CACHE_ENTRY_SIZE)
-endif
-
-ifneq ($(MAX_EGL_CACHE_KEY_SIZE),)
-  LOCAL_CFLAGS += -DMAX_EGL_CACHE_KEY_SIZE=$(MAX_EGL_CACHE_KEY_SIZE)
-endif
-
-ifneq ($(MAX_EGL_CACHE_SIZE),)
-  LOCAL_CFLAGS += -DMAX_EGL_CACHE_SIZE=$(MAX_EGL_CACHE_SIZE)
-endif
-
-ifneq ($(filter address,$(SANITIZE_TARGET)),)
-  LOCAL_CFLAGS_32 += -DEGL_WRAPPER_DIR=\"/$(TARGET_COPY_OUT_DATA)/lib\"
-  LOCAL_CFLAGS_64 += -DEGL_WRAPPER_DIR=\"/$(TARGET_COPY_OUT_DATA)/lib64\"
-endif
-
-LOCAL_REQUIRED_MODULES := $(egl.cfg_config_module)
-egl.cfg_config_module :=
-
-include $(BUILD_SHARED_LIBRARY)
-
-###############################################################################
-# Build the wrapper OpenGL ES 1.x library
-#
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= 		\
-	GLES_CM/gl.cpp.arm 	\
-#
-
-LOCAL_SHARED_LIBRARIES += libcutils liblog libEGL
-LOCAL_MODULE:= libGLESv1_CM
-
-LOCAL_SHARED_LIBRARIES += libdl
-# we need to access the private Bionic header <bionic_tls.h>
-LOCAL_C_INCLUDES += bionic/libc/private
-
-LOCAL_CFLAGS += -DLOG_TAG=\"libGLESv1\"
-LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
-LOCAL_CFLAGS += -fvisibility=hidden
-
-# TODO: This is to work around b/20093774. Remove after root cause is fixed
-LOCAL_LDFLAGS_arm += -Wl,--hash-style,both
-
-include $(BUILD_SHARED_LIBRARY)
-
-
-###############################################################################
-# Build the wrapper OpenGL ES 2.x library
-#
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-	GLES2/gl2.cpp   \
-#
-
-LOCAL_ARM_MODE := arm
-LOCAL_SHARED_LIBRARIES += libcutils libutils liblog libEGL
-LOCAL_MODULE:= libGLESv2
-
-LOCAL_SHARED_LIBRARIES += libdl
-# we need to access the private Bionic header <bionic_tls.h>
-LOCAL_C_INCLUDES += bionic/libc/private
-
-LOCAL_CFLAGS += -DLOG_TAG=\"libGLESv2\"
-LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
-LOCAL_CFLAGS += -fvisibility=hidden
-
-# TODO: This is to work around b/20093774. Remove after root cause is fixed
-LOCAL_LDFLAGS_arm += -Wl,--hash-style,both
-
-include $(BUILD_SHARED_LIBRARY)
-
-###############################################################################
-# Build the wrapper OpenGL ES 3.x library (this is just different name for v2)
-#
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-	GLES2/gl2.cpp   \
-#
-
-LOCAL_ARM_MODE := arm
-LOCAL_SHARED_LIBRARIES += libcutils libutils liblog libEGL
-LOCAL_MODULE:= libGLESv3
-LOCAL_SHARED_LIBRARIES += libdl
-# we need to access the private Bionic header <bionic_tls.h>
-LOCAL_C_INCLUDES += bionic/libc/private
-
-LOCAL_CFLAGS += -DLOG_TAG=\"libGLESv3\"
-LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
-LOCAL_CFLAGS += -fvisibility=hidden
-
-# TODO: This is to work around b/20093774. Remove after root cause is fixed
-LOCAL_LDFLAGS_arm += -Wl,--hash-style,both
-
-include $(BUILD_SHARED_LIBRARY)
-
-include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/opengl/libs/EGL/egl_cache.cpp b/opengl/libs/EGL/egl_cache.cpp
index 8c135c8..1fe322d 100644
--- a/opengl/libs/EGL/egl_cache.cpp
+++ b/opengl/libs/EGL/egl_cache.cpp
@@ -27,22 +27,10 @@
 #include <sys/types.h>
 #include <unistd.h>
 
-#ifndef MAX_EGL_CACHE_ENTRY_SIZE
-#define MAX_EGL_CACHE_ENTRY_SIZE (16 * 1024);
-#endif
-
-#ifndef MAX_EGL_CACHE_KEY_SIZE
-#define MAX_EGL_CACHE_KEY_SIZE (1024);
-#endif
-
-#ifndef MAX_EGL_CACHE_SIZE
-#define MAX_EGL_CACHE_SIZE (64 * 1024);
-#endif
-
 // Cache size limits.
-static const size_t maxKeySize = MAX_EGL_CACHE_KEY_SIZE;
-static const size_t maxValueSize = MAX_EGL_CACHE_ENTRY_SIZE;
-static const size_t maxTotalSize = MAX_EGL_CACHE_SIZE;
+static const size_t maxKeySize = 12 * 1024;
+static const size_t maxValueSize = 64 * 1024;
+static const size_t maxTotalSize = 2 * 1024 * 1024;
 
 // Cache file header
 static const char* cacheFileMagic = "EGL$";
diff --git a/opengl/libs/EGL/egl_display.cpp b/opengl/libs/EGL/egl_display.cpp
index e335a6c..10523f5 100644
--- a/opengl/libs/EGL/egl_display.cpp
+++ b/opengl/libs/EGL/egl_display.cpp
@@ -212,8 +212,6 @@
             *major = VERSION_MAJOR;
         if (minor != NULL)
             *minor = VERSION_MINOR;
-
-        mHibernation.setDisplayValid(true);
     }
 
     {
@@ -262,8 +260,6 @@
             res = EGL_TRUE;
         }
 
-        mHibernation.setDisplayValid(false);
-
         // Reset the extension string since it will be regenerated if we get
         // reinitialized.
         mExtensionString.setTo("");
@@ -342,16 +338,12 @@
                     disp.dpy, impl_draw, impl_read, impl_ctx);
             if (result == EGL_TRUE) {
                 c->onMakeCurrent(draw, read);
-                if (!cur_c) {
-                    mHibernation.incWakeCount(HibernationMachine::STRONG);
-                }
             }
         } else {
             result = cur_c->cnx->egl.eglMakeCurrent(
                     disp.dpy, impl_draw, impl_read, impl_ctx);
             if (result == EGL_TRUE) {
                 cur_c->onLooseCurrent();
-                mHibernation.decWakeCount(HibernationMachine::STRONG);
             }
         }
     }
@@ -376,63 +368,5 @@
 }
 
 // ----------------------------------------------------------------------------
-
-bool egl_display_t::HibernationMachine::incWakeCount(WakeRefStrength strength) {
-    Mutex::Autolock _l(mLock);
-    ALOGE_IF(mWakeCount < 0 || mWakeCount == INT32_MAX,
-             "Invalid WakeCount (%d) on enter\n", mWakeCount);
-
-    mWakeCount++;
-    if (strength == STRONG)
-        mAttemptHibernation = false;
-
-    if (CC_UNLIKELY(mHibernating)) {
-        ALOGV("Awakening\n");
-        egl_connection_t* const cnx = &gEGLImpl;
-
-        // These conditions should be guaranteed before entering hibernation;
-        // we don't want to get into a state where we can't wake up.
-        ALOGD_IF(!mDpyValid || !cnx->egl.eglAwakenProcessIMG,
-                 "Invalid hibernation state, unable to awaken\n");
-
-        if (!cnx->egl.eglAwakenProcessIMG()) {
-            ALOGE("Failed to awaken EGL implementation\n");
-            return false;
-        }
-        mHibernating = false;
-    }
-    return true;
-}
-
-void egl_display_t::HibernationMachine::decWakeCount(WakeRefStrength strength) {
-    Mutex::Autolock _l(mLock);
-    ALOGE_IF(mWakeCount <= 0, "Invalid WakeCount (%d) on leave\n", mWakeCount);
-
-    mWakeCount--;
-    if (strength == STRONG)
-        mAttemptHibernation = true;
-
-    if (mWakeCount == 0 && CC_UNLIKELY(mAttemptHibernation)) {
-        egl_connection_t* const cnx = &gEGLImpl;
-        mAttemptHibernation = false;
-        if (mAllowHibernation && mDpyValid &&
-                cnx->egl.eglHibernateProcessIMG &&
-                cnx->egl.eglAwakenProcessIMG) {
-            ALOGV("Hibernating\n");
-            if (!cnx->egl.eglHibernateProcessIMG()) {
-                ALOGE("Failed to hibernate EGL implementation\n");
-                return;
-            }
-            mHibernating = true;
-        }
-    }
-}
-
-void egl_display_t::HibernationMachine::setDisplayValid(bool valid) {
-    Mutex::Autolock _l(mLock);
-    mDpyValid = valid;
-}
-
-// ----------------------------------------------------------------------------
 }; // namespace android
 // ----------------------------------------------------------------------------
diff --git a/opengl/libs/EGL/egl_display.h b/opengl/libs/EGL/egl_display.h
index 2d86295..e17558c 100644
--- a/opengl/libs/EGL/egl_display.h
+++ b/opengl/libs/EGL/egl_display.h
@@ -68,20 +68,6 @@
     // add reference to this object. returns true if this is a valid object.
     bool getObject(egl_object_t* object) const;
 
-    // These notifications allow the display to keep track of how many window
-    // surfaces exist, which it uses to decide whether to hibernate the
-    // underlying EGL implementation. They can be called by any thread without
-    // holding a lock, but must be called via egl_display_ptr to ensure
-    // proper hibernate/wakeup sequencing. If a surface destruction triggers
-    // hibernation, hibernation will be delayed at least until the calling
-    // thread's egl_display_ptr is destroyed.
-    void onWindowSurfaceCreated() {
-        mHibernation.incWakeCount(HibernationMachine::STRONG);
-    }
-    void onWindowSurfaceDestroyed() {
-        mHibernation.decWakeCount(HibernationMachine::STRONG);
-    }
-
     static egl_display_t* get(EGLDisplay dpy);
     static EGLDisplay getFromNativeDisplay(EGLNativeDisplayType disp);
 
@@ -127,8 +113,6 @@
 
 private:
     friend class egl_display_ptr;
-    bool enter() { return mHibernation.incWakeCount(HibernationMachine::WEAK); }
-    void leave() { return mHibernation.decWakeCount(HibernationMachine::WEAK); }
 
             uint32_t                    refs;
             bool                        eglIsInitialized;
@@ -139,47 +123,6 @@
             String8 mVersionString;
             String8 mClientApiString;
             String8 mExtensionString;
-
-    // HibernationMachine uses its own internal mutex to protect its own data.
-    // The owning egl_display_t's lock may be but is not required to be held
-    // when calling HibernationMachine methods. As a result, nothing in this
-    // class may call back up to egl_display_t directly or indirectly.
-    class HibernationMachine {
-    public:
-        // STRONG refs cancel (inc) or initiate (dec) a hibernation attempt
-        // the next time the wakecount reaches zero. WEAK refs don't affect
-        // whether a hibernation attempt will be made. Use STRONG refs only
-        // for infrequent/heavy changes that are likely to indicate the
-        // EGLDisplay is entering or leaving a long-term idle state.
-        enum WakeRefStrength {
-            WEAK   = 0,
-            STRONG = 1,
-        };
-
-        HibernationMachine(): mWakeCount(0), mHibernating(false),
-                mAttemptHibernation(false), mDpyValid(false),
-#if BOARD_ALLOW_EGL_HIBERNATION
-                mAllowHibernation(true)
-#else
-                mAllowHibernation(false)
-#endif
-        {}
-        ~HibernationMachine() {}
-
-        bool incWakeCount(WakeRefStrength strenth);
-        void decWakeCount(WakeRefStrength strenth);
-
-        void setDisplayValid(bool valid);
-
-    private:
-        Mutex      mLock;
-        int32_t    mWakeCount;
-        bool       mHibernating;
-        bool       mAttemptHibernation;
-        bool       mDpyValid;
-        const bool mAllowHibernation;
-    };
-    HibernationMachine mHibernation;
 };
 
 // ----------------------------------------------------------------------------
@@ -190,13 +133,7 @@
 // as the egl_display_ptr exists.
 class egl_display_ptr {
 public:
-    explicit egl_display_ptr(egl_display_t* dpy): mDpy(dpy) {
-        if (mDpy) {
-            if (CC_UNLIKELY(!mDpy->enter())) {
-                mDpy = NULL;
-            }
-        }
-    }
+    explicit egl_display_ptr(egl_display_t* dpy): mDpy(dpy) {}
 
     // We only really need a C++11 move constructor, not a copy constructor.
     // A move constructor would save an enter()/leave() pair on every EGL API
@@ -208,17 +145,9 @@
     //     other.mDpy = NULL;
     // }
     //
-    egl_display_ptr(const egl_display_ptr& other): mDpy(other.mDpy) {
-        if (mDpy) {
-            mDpy->enter();
-        }
-    }
+    egl_display_ptr(const egl_display_ptr& other): mDpy(other.mDpy) {}
 
-    ~egl_display_ptr() {
-        if (mDpy) {
-            mDpy->leave();
-        }
-    }
+    ~egl_display_ptr() {}
 
     const egl_display_t* operator->() const { return mDpy; }
           egl_display_t* operator->()       { return mDpy; }
diff --git a/opengl/libs/EGL/egl_object.cpp b/opengl/libs/EGL/egl_object.cpp
index 90f27d1..7fc5609 100644
--- a/opengl/libs/EGL/egl_object.cpp
+++ b/opengl/libs/EGL/egl_object.cpp
@@ -69,17 +69,12 @@
         egl_connection_t const* cnx) :
     egl_object_t(dpy), surface(surface), config(config), win(win), cnx(cnx),
     connected(true)
-{
-    if (win) {
-        getDisplay()->onWindowSurfaceCreated();
-    }
-}
+{}
 
 egl_surface_t::~egl_surface_t() {
     ANativeWindow* const window = win.get();
     if (window != NULL) {
         disconnect();
-        getDisplay()->onWindowSurfaceDestroyed();
     }
 }
 
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 47f5401..dd5b034 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -90,19 +90,6 @@
 
 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
 
-// Workaround for b/30067360: /proc/self/environ inaccessible in SurfaceFlinger
-// => ASan fails to read ASAN_OPTIONS => alloc-dealloc-mismatch bug is not
-// suppressed and prevents the device from booting.
-#ifndef __has_feature
-#define __has_feature(x) 0
-#endif
-#if __has_feature(address_sanitizer)
-__attribute__((visibility("default")))
-extern "C" const char* __asan_default_options() {
-  return "alloc_dealloc_mismatch=0";
-}
-#endif
-
 namespace android {
 
 // This is the phase offset in nanoseconds of the software vsync event
diff --git a/services/surfaceflinger/SurfaceFlingerConsumer.cpp b/services/surfaceflinger/SurfaceFlingerConsumer.cpp
index c71b3bc..edd53a3 100644
--- a/services/surfaceflinger/SurfaceFlingerConsumer.cpp
+++ b/services/surfaceflinger/SurfaceFlingerConsumer.cpp
@@ -69,6 +69,14 @@
         return err;
     }
 
+    if (autoRefresh) {
+        *autoRefresh = item.mAutoRefresh;
+    }
+
+    if (queuedBuffer) {
+        *queuedBuffer = item.mQueuedBuffer;
+    }
+
     // We call the rejecter here, in case the caller has a reason to
     // not accept this buffer.  This is used by SurfaceFlinger to
     // reject buffers which have the wrong size
@@ -78,14 +86,6 @@
         return BUFFER_REJECTED;
     }
 
-    if (autoRefresh) {
-        *autoRefresh = item.mAutoRefresh;
-    }
-
-    if (queuedBuffer) {
-        *queuedBuffer = item.mQueuedBuffer;
-    }
-
     // Release the previous buffer.
 #ifdef USE_HWC2
     err = updateAndReleaseLocked(item, &mPendingRelease);
diff --git a/vulkan/Android.bp b/vulkan/Android.bp
index 97d99d0..d97cf5e 100644
--- a/vulkan/Android.bp
+++ b/vulkan/Android.bp
@@ -17,6 +17,7 @@
     from: "include",
     to: "",
     srcs: ["include/vulkan/**/*.h"],
+    license: "include/vulkan/NOTICE",
 }
 
 subdirs = [
diff --git a/vulkan/include/vulkan/NOTICE b/vulkan/include/vulkan/NOTICE
new file mode 100644
index 0000000..c958fba
--- /dev/null
+++ b/vulkan/include/vulkan/NOTICE
@@ -0,0 +1,13 @@
+Copyright (c) 2015-2016 The Khronos Group Inc.
+
+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.