am 23c2fcbb: (-s ours) am c0af9caf: am b14d72bc: am d070009e: am df6774c9: am 7c1cdbdd: am e23f8b8f: am 1f70863d: am 37b44969: Add support for writing byte arrays to parcels

* commit '23c2fcbbf4be87580e64132150aa554b764425c2':
  Add support for writing byte arrays to parcels
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index 1911839..b500a6b 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -82,6 +82,7 @@
     { "hal",        "Hardware Modules", ATRACE_TAG_HAL, { } },
     { "res",        "Resource Loading", ATRACE_TAG_RESOURCES, { } },
     { "dalvik",     "Dalvik VM",        ATRACE_TAG_DALVIK, { } },
+    { "rs",         "RenderScript",     ATRACE_TAG_RS, { } },
     { "sched",      "CPU Scheduling",   0, {
         { REQ,      "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
         { REQ,      "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
@@ -102,6 +103,9 @@
         { REQ,      "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
         { REQ,      "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
     } },
+    { "mmc",        "eMMC commands",    0, {
+        { REQ,      "/sys/kernel/debug/tracing/events/mmc/enable" },
+    } },
     { "load",       "CPU Load",         0, {
         { REQ,      "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
     } },
diff --git a/cmds/dumpstate/Android.mk b/cmds/dumpstate/Android.mk
index 3194dbf..9065ee1 100644
--- a/cmds/dumpstate/Android.mk
+++ b/cmds/dumpstate/Android.mk
@@ -1,5 +1,10 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
+LOCAL_SRC_FILES := libdumpstate_default.c
+LOCAL_MODULE := libdumpstate.default
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
 
 ifdef BOARD_WLAN_DEVICE
 LOCAL_CFLAGS := -DFWDUMP_$(BOARD_WLAN_DEVICE)
@@ -10,12 +15,7 @@
 LOCAL_MODULE := dumpstate
 
 LOCAL_SHARED_LIBRARIES := libcutils liblog libselinux
-
-ifdef BOARD_LIB_DUMPSTATE
-LOCAL_STATIC_LIBRARIES := $(BOARD_LIB_DUMPSTATE)
-LOCAL_CFLAGS += -DBOARD_HAS_DUMPSTATE
-endif
-
+LOCAL_HAL_STATIC_LIBRARIES := libdumpstate
 LOCAL_CFLAGS += -Wall -Wno-unused-parameter -std=gnu99
 
 include $(BUILD_EXECUTABLE)
diff --git a/cmds/dumpstate/dumpstate.c b/cmds/dumpstate/dumpstate.c
index 89bea91..3c79ae9 100644
--- a/cmds/dumpstate/dumpstate.c
+++ b/cmds/dumpstate/dumpstate.c
@@ -33,7 +33,7 @@
 #include "private/android_filesystem_config.h"
 
 #define LOG_TAG "dumpstate"
-#include <utils/Log.h>
+#include <cutils/log.h>
 
 #include "dumpstate.h"
 
@@ -95,6 +95,7 @@
 
     run_command("PROCESSES", 10, "ps", "-P", NULL);
     run_command("PROCESSES AND THREADS", 10, "ps", "-t", "-p", "-P", NULL);
+    run_command("PROCESSES (SELINUX LABELS)", 10, "ps", "-Z", NULL);
     run_command("LIBRANK", 10, "librank", NULL);
 
     do_dmesg();
@@ -186,7 +187,7 @@
     run_command("IP6TABLE RAW", 10, SU_PATH, "root", "ip6tables", "-t", "raw", "-L", "-nvx", NULL);
 
     run_command("WIFI NETWORKS", 20,
-            SU_PATH, "root", "wpa_cli", "list_networks", NULL);
+            SU_PATH, "root", "wpa_cli", "IFNAME=wlan0", "list_networks", NULL);
 
 #ifdef FWDUMP_bcmdhd
     run_command("DUMP WIFI INTERNAL COUNTERS", 20,
@@ -243,14 +244,12 @@
     dump_file("BINDER STATS", "/sys/kernel/debug/binder/stats");
     dump_file("BINDER STATE", "/sys/kernel/debug/binder/state");
 
-#ifdef BOARD_HAS_DUMPSTATE
     printf("========================================================\n");
     printf("== Board\n");
     printf("========================================================\n");
 
     dumpstate_board();
     printf("\n");
-#endif
 
     /* Migrate the ril_dumpstate to a dumpstate_board()? */
     char ril_dumpstate_timeout[PROPERTY_VALUE_MAX] = {0};
@@ -278,6 +277,16 @@
     run_command("DUMPSYS", 60, "dumpsys", NULL);
 
     printf("========================================================\n");
+    printf("== Checkins\n");
+    printf("========================================================\n");
+
+    run_command("CHECKIN BATTERYSTATS", 30, "dumpsys", "batterystats", "-c", NULL);
+    run_command("CHECKIN MEMINFO", 30, "dumpsys", "meminfo", "--checkin", NULL);
+    run_command("CHECKIN NETSTATS", 30, "dumpsys", "netstats", "--checkin", NULL);
+    run_command("CHECKIN PROCSTATS", 30, "dumpsys", "procstats", "-c", NULL);
+    run_command("CHECKIN USAGESTATS", 30, "dumpsys", "usagestats", "-c", NULL);
+
+    printf("========================================================\n");
     printf("== Running Application Activities\n");
     printf("========================================================\n");
 
diff --git a/libs/utils/Flattenable.cpp b/cmds/dumpstate/libdumpstate_default.c
similarity index 77%
rename from libs/utils/Flattenable.cpp
rename to cmds/dumpstate/libdumpstate_default.c
index 1f2ffaa..fd840df 100644
--- a/libs/utils/Flattenable.cpp
+++ b/cmds/dumpstate/libdumpstate_default.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006 The Android Open Source Project
+ * Copyright (C) 2013 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.
@@ -14,11 +14,9 @@
  * limitations under the License.
  */
 
-#include <utils/Flattenable.h>
+#include "dumpstate.h"
 
-namespace android {
-
-Flattenable::~Flattenable() {
+void dumpstate_board(void)
+{
 }
 
-}; // namespace android
diff --git a/cmds/dumpsys/dumpsys.cpp b/cmds/dumpsys/dumpsys.cpp
index c9fcc00..ce8993d 100644
--- a/cmds/dumpsys/dumpsys.cpp
+++ b/cmds/dumpsys/dumpsys.cpp
@@ -9,7 +9,7 @@
 #include <binder/Parcel.h>
 #include <binder/ProcessState.h>
 #include <binder/IServiceManager.h>
-#include <utils/TextOutput.h>
+#include <binder/TextOutput.h>
 #include <utils/Vector.h>
 
 #include <getopt.h>
@@ -39,7 +39,11 @@
 
     Vector<String16> services;
     Vector<String16> args;
-    if (argc == 1) {
+    bool showListOnly = false;
+    if ((argc == 2) && (strcmp(argv[1], "-l") == 0)) {
+        showListOnly = true;
+    }
+    if ((argc == 1) || showListOnly) {
         services = sm->listServices();
         services.sort(sort_func);
         args.add(String16("-a"));
@@ -64,6 +68,10 @@
         }
     }
 
+    if (showListOnly) {
+        return 0;
+    }
+
     for (size_t i=0; i<N; i++) {
         sp<IBinder> service = sm->checkService(services[i]);
         if (service != NULL) {
diff --git a/cmds/flatland/Composers.cpp b/cmds/flatland/Composers.cpp
index 8365a31..15cdb29 100644
--- a/cmds/flatland/Composers.cpp
+++ b/cmds/flatland/Composers.cpp
@@ -14,6 +14,9 @@
  * limitations under the License.
  */
 
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
 #include "Flatland.h"
 #include "GLHelper.h"
 
diff --git a/cmds/flatland/GLHelper.cpp b/cmds/flatland/GLHelper.cpp
index 4f7697f..42694b3 100644
--- a/cmds/flatland/GLHelper.cpp
+++ b/cmds/flatland/GLHelper.cpp
@@ -14,6 +14,9 @@
  * limitations under the License.
  */
 
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
 #include <ui/DisplayInfo.h>
 #include <gui/SurfaceComposerClient.h>
 
@@ -198,9 +201,9 @@
 
 bool GLHelper::createNamedSurfaceTexture(GLuint name, uint32_t w, uint32_t h,
         sp<GLConsumer>* glConsumer, EGLSurface* surface) {
-    sp<BufferQueue> bq = new BufferQueue(true, mGraphicBufferAlloc);
-    sp<GLConsumer> glc = new GLConsumer(name, true,
-            GL_TEXTURE_EXTERNAL_OES, false, bq);
+    sp<BufferQueue> bq = new BufferQueue(mGraphicBufferAlloc);
+    sp<GLConsumer> glc = new GLConsumer(bq, name,
+            GL_TEXTURE_EXTERNAL_OES, false);
     glc->setDefaultBufferSize(w, h);
     glc->setDefaultMaxBufferCount(3);
     glc->setConsumerUsageBits(GRALLOC_USAGE_HW_COMPOSER);
diff --git a/cmds/flatland/Main.cpp b/cmds/flatland/Main.cpp
index 99715d3..d6ac3d2 100644
--- a/cmds/flatland/Main.cpp
+++ b/cmds/flatland/Main.cpp
@@ -56,7 +56,7 @@
 
 static const BenchmarkDesc benchmarks[] = {
     { "16:10 Single Static Window",
-        2560, 1600, { 800, 1600, 2400 },
+        2560, 1600, { 800, 1200, 1600, 2400 },
         {
             {   // Window
                 0, staticGradient, opaque,
@@ -73,8 +73,26 @@
         },
     },
 
+    { "3:2 Single Static Window",
+        2048, 1536, { 1536 },
+        {
+            {   // Window
+                0, staticGradient, opaque,
+                0,    50,     2048,   1440,
+            },
+            {   // Status bar
+                0, staticGradient, opaque,
+                0,    0,      2048,   50,
+            },
+            {   // Navigation bar
+                0, staticGradient, opaque,
+                0,    1440,   2048,   96,
+            },
+        },
+    },
+
     { "16:10 App -> Home Transition",
-        2560, 1600, { 800, 1600, 2400 },
+        2560, 1600, { 800, 1200, 1600, 2400 },
         {
             {   // Wallpaper
                 0, staticGradient, opaque,
@@ -99,8 +117,34 @@
         },
     },
 
+    { "3:2 App -> Home Transition",
+        2048, 1536, { 1536 },
+        {
+            {   // Wallpaper
+                0, staticGradient, opaque,
+                0,    50,     2048,   1440,
+            },
+            {   // Launcher
+                0, staticGradient, blend,
+                0,    50,     2048,   1440,
+            },
+            {   // Outgoing activity
+                0, staticGradient, blendShrink,
+                20,    70,     2048,   1400,
+            },
+            {   // Status bar
+                0, staticGradient, opaque,
+                0,    0,      2048,   50,
+            },
+            {   // Navigation bar
+                0, staticGradient, opaque,
+                0,    1440,   2048,   96,
+            },
+        },
+    },
+
     { "16:10 SurfaceView -> Home Transition",
-        2560, 1600, { 800, 1600, 2400 },
+        2560, 1600, { 800, 1200, 1600, 2400 },
         {
             {   // Wallpaper
                 0, staticGradient, opaque,
@@ -128,6 +172,36 @@
             },
         },
     },
+
+    { "3:2 SurfaceView -> Home Transition",
+        2048, 1536, { 1536 },
+        {
+            {   // Wallpaper
+                0, staticGradient, opaque,
+                0,    50,     2048,   1440,
+            },
+            {   // Launcher
+                0, staticGradient, blend,
+                0,    50,     2048,   1440,
+            },
+            {   // Outgoing SurfaceView
+                0, staticGradient, blendShrink,
+                20,    70,     2048,   1400,
+            },
+            {   // Outgoing activity
+                0, staticGradient, blendShrink,
+                20,    70,     2048,   1400,
+            },
+            {   // Status bar
+                0, staticGradient, opaque,
+                0,    0,      2048,   50,
+            },
+            {   // Navigation bar
+                0, staticGradient, opaque,
+                0,    1440,   2048,   96,
+            },
+        },
+    },
 };
 
 static const ShaderDesc shaders[] = {
diff --git a/cmds/installd/commands.c b/cmds/installd/commands.c
index 8e14a2c..84ad204 100644
--- a/cmds/installd/commands.c
+++ b/cmds/installd/commands.c
@@ -108,11 +108,11 @@
     return 0;
 }
 
-int uninstall(const char *pkgname, uid_t persona)
+int uninstall(const char *pkgname, userid_t userid)
 {
     char pkgdir[PKG_PATH_MAX];
 
-    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, persona))
+    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, userid))
         return -1;
 
     /* delete contents AND directory, no exceptions */
@@ -173,18 +173,18 @@
     return 0;
 }
 
-int delete_user_data(const char *pkgname, uid_t persona)
+int delete_user_data(const char *pkgname, userid_t userid)
 {
     char pkgdir[PKG_PATH_MAX];
 
-    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, persona))
+    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, userid))
         return -1;
 
     /* delete contents, excluding "lib", but not the directory itself */
     return delete_dir_contents(pkgdir, 0, "lib");
 }
 
-int make_user_data(const char *pkgname, uid_t uid, uid_t persona)
+int make_user_data(const char *pkgname, uid_t uid, userid_t userid)
 {
     char pkgdir[PKG_PATH_MAX];
     char applibdir[PKG_PATH_MAX];
@@ -192,10 +192,10 @@
     struct stat libStat;
 
     // Create the data dir for the package
-    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, persona)) {
+    if (create_pkg_path(pkgdir, pkgname, PKG_DIR_POSTFIX, userid)) {
         return -1;
     }
-    if (create_pkg_path(libsymlink, pkgname, PKG_LIB_POSTFIX, persona)) {
+    if (create_pkg_path(libsymlink, pkgname, PKG_LIB_POSTFIX, userid)) {
         ALOGE("cannot create package lib symlink origin path\n");
         return -1;
     }
@@ -262,10 +262,10 @@
     return 0;
 }
 
-int delete_persona(uid_t persona)
+int delete_user(userid_t userid)
 {
     char data_path[PKG_PATH_MAX];
-    if (create_persona_path(data_path, persona)) {
+    if (create_user_path(data_path, userid)) {
         return -1;
     }
     if (delete_dir_contents(data_path, 1, NULL)) {
@@ -273,7 +273,7 @@
     }
 
     char media_path[PATH_MAX];
-    if (create_persona_media_path(media_path, (userid_t) persona) == -1) {
+    if (create_user_media_path(media_path, userid) == -1) {
         return -1;
     }
     if (delete_dir_contents(media_path, 1, NULL) == -1) {
@@ -283,11 +283,11 @@
     return 0;
 }
 
-int delete_cache(const char *pkgname, uid_t persona)
+int delete_cache(const char *pkgname, userid_t userid)
 {
     char cachedir[PKG_PATH_MAX];
 
-    if (create_pkg_path(cachedir, pkgname, CACHE_DIR_POSTFIX, persona))
+    if (create_pkg_path(cachedir, pkgname, CACHE_DIR_POSTFIX, userid))
         return -1;
 
         /* delete contents, not the directory, no exceptions */
@@ -319,7 +319,7 @@
     cache = start_cache_collection();
 
     // Collect cache files for primary user.
-    if (create_persona_path(tmpdir, 0) == 0) {
+    if (create_user_path(tmpdir, 0) == 0) {
         //ALOGI("adding cache files from %s\n", tmpdir);
         add_cache_files(cache, tmpdir, "cache");
     }
@@ -420,7 +420,7 @@
     }
 }
 
-int get_size(const char *pkgname, int persona, const char *apkpath,
+int get_size(const char *pkgname, userid_t userid, const char *apkpath,
              const char *libdirpath, const char *fwdlock_apkpath, const char *asecpath,
              int64_t *_codesize, int64_t *_datasize, int64_t *_cachesize,
              int64_t* _asecsize)
@@ -477,7 +477,7 @@
         }
     }
 
-    if (create_pkg_path(path, pkgname, PKG_DIR_POSTFIX, persona)) {
+    if (create_pkg_path(path, pkgname, PKG_DIR_POSTFIX, userid)) {
         goto done;
     }
 
@@ -540,7 +540,6 @@
 }
 
 
-/* a simpler version of dexOptGenerateCacheFileName() */
 int create_cache_path(char path[PKG_PATH_MAX], const char *src)
 {
     char *tmp;
@@ -580,7 +579,7 @@
 }
 
 static void run_dexopt(int zip_fd, int odex_fd, const char* input_file_name,
-    const char* dexopt_flags)
+    const char* output_file_name, const char* dexopt_flags)
 {
     static const char* DEX_OPT_BIN = "/system/bin/dexopt";
     static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
@@ -590,11 +589,35 @@
     sprintf(zip_num, "%d", zip_fd);
     sprintf(odex_num, "%d", odex_fd);
 
+    ALOGV("Running %s in=%s out=%s\n", DEX_OPT_BIN, input_file_name, output_file_name);
     execl(DEX_OPT_BIN, DEX_OPT_BIN, "--zip", zip_num, odex_num, input_file_name,
         dexopt_flags, (char*) NULL);
     ALOGE("execl(%s) failed: %s\n", DEX_OPT_BIN, strerror(errno));
 }
 
+static void run_dex2oat(int zip_fd, int oat_fd, const char* input_file_name,
+    const char* output_file_name, const char* dexopt_flags)
+{
+    static const char* DEX2OAT_BIN = "/system/bin/dex2oat";
+    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
+    char zip_fd_arg[strlen("--zip-fd=") + MAX_INT_LEN];
+    char zip_location_arg[strlen("--zip-location=") + PKG_PATH_MAX];
+    char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
+    char oat_location_arg[strlen("--oat-name=") + PKG_PATH_MAX];
+
+    sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
+    sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
+    sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
+    sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
+
+    ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
+    execl(DEX2OAT_BIN, DEX2OAT_BIN,
+          zip_fd_arg, zip_location_arg,
+          oat_fd_arg, oat_location_arg,
+          (char*) NULL);
+    ALOGE("execl(%s) failed: %s\n", DEX2OAT_BIN, strerror(errno));
+}
+
 static int wait_dexopt(pid_t pid, const char* apk_path)
 {
     int status;
@@ -631,31 +654,32 @@
 {
     struct utimbuf ut;
     struct stat apk_stat, dex_stat;
-    char dex_path[PKG_PATH_MAX];
+    char out_path[PKG_PATH_MAX];
     char dexopt_flags[PROPERTY_VALUE_MAX];
+    char persist_sys_dalvik_vm_lib[PROPERTY_VALUE_MAX];
     char *end;
-    int res, zip_fd=-1, odex_fd=-1;
+    int res, zip_fd=-1, out_fd=-1;
 
-        /* Before anything else: is there a .odex file?  If so, we have
-         * pre-optimized the apk and there is nothing to do here.
-         */
     if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
         return -1;
     }
 
     /* platform-specific flags affecting optimization and verification */
     property_get("dalvik.vm.dexopt-flags", dexopt_flags, "");
+    ALOGV("dalvik.vm.dexopt_flags=%s\n", dexopt_flags);
 
-    strcpy(dex_path, apk_path);
-    end = strrchr(dex_path, '.');
-    if (end != NULL) {
-        strcpy(end, ".odex");
-        if (stat(dex_path, &dex_stat) == 0) {
-            return 0;
-        }
+    /* The command to run depend ones the value of persist.sys.dalvik.vm.lib */
+    property_get("persist.sys.dalvik.vm.lib", persist_sys_dalvik_vm_lib, "libdvm.so");
+
+    /* Before anything else: is there a .odex file?  If so, we have
+     * precompiled the apk and there is nothing to do here.
+     */
+    sprintf(out_path, "%s%s", apk_path, ".odex");
+    if (stat(out_path, &dex_stat) == 0) {
+        return 0;
     }
 
-    if (create_cache_path(dex_path, apk_path)) {
+    if (create_cache_path(out_path, apk_path)) {
         return -1;
     }
 
@@ -664,24 +688,24 @@
 
     zip_fd = open(apk_path, O_RDONLY, 0);
     if (zip_fd < 0) {
-        ALOGE("dexopt cannot open '%s' for input\n", apk_path);
+        ALOGE("installd cannot open '%s' for input during dexopt\n", apk_path);
         return -1;
     }
 
-    unlink(dex_path);
-    odex_fd = open(dex_path, O_RDWR | O_CREAT | O_EXCL, 0644);
-    if (odex_fd < 0) {
-        ALOGE("dexopt cannot open '%s' for output\n", dex_path);
+    unlink(out_path);
+    out_fd = open(out_path, O_RDWR | O_CREAT | O_EXCL, 0644);
+    if (out_fd < 0) {
+        ALOGE("installd cannot open '%s' for output during dexopt\n", out_path);
         goto fail;
     }
-    if (fchmod(odex_fd,
+    if (fchmod(out_fd,
                S_IRUSR|S_IWUSR|S_IRGRP |
                (is_public ? S_IROTH : 0)) < 0) {
-        ALOGE("dexopt cannot chmod '%s'\n", dex_path);
+        ALOGE("installd cannot chmod '%s' during dexopt\n", out_path);
         goto fail;
     }
-    if (fchown(odex_fd, AID_SYSTEM, uid) < 0) {
-        ALOGE("dexopt cannot chown '%s'\n", dex_path);
+    if (fchown(out_fd, AID_SYSTEM, uid) < 0) {
+        ALOGE("installd cannot chown '%s' during dexopt\n", out_path);
         goto fail;
     }
 
@@ -692,11 +716,11 @@
     if (pid == 0) {
         /* child -- drop privileges before continuing */
         if (setgid(uid) != 0) {
-            ALOGE("setgid(%d) failed during dexopt\n", uid);
+            ALOGE("setgid(%d) failed in installd during dexopt\n", uid);
             exit(64);
         }
         if (setuid(uid) != 0) {
-            ALOGE("setuid(%d) during dexopt\n", uid);
+            ALOGE("setuid(%d) failed in installd during dexopt\n", uid);
             exit(65);
         }
         // drop capabilities
@@ -709,33 +733,39 @@
             ALOGE("capset failed: %s\n", strerror(errno));
             exit(66);
         }
-        if (flock(odex_fd, LOCK_EX | LOCK_NB) != 0) {
-            ALOGE("flock(%s) failed: %s\n", dex_path, strerror(errno));
+        if (flock(out_fd, LOCK_EX | LOCK_NB) != 0) {
+            ALOGE("flock(%s) failed: %s\n", out_path, strerror(errno));
             exit(67);
         }
 
-        run_dexopt(zip_fd, odex_fd, apk_path, dexopt_flags);
+        if (strncmp(persist_sys_dalvik_vm_lib, "libdvm", 6) == 0) {
+            run_dexopt(zip_fd, out_fd, apk_path, out_path, dexopt_flags);
+        } else if (strncmp(persist_sys_dalvik_vm_lib, "libart", 6) == 0) {
+            run_dex2oat(zip_fd, out_fd, apk_path, out_path, dexopt_flags);
+        } else {
+            exit(69);   /* Unexpected persist.sys.dalvik.vm.lib value */
+        }
         exit(68);   /* only get here on exec failure */
     } else {
         res = wait_dexopt(pid, apk_path);
         if (res != 0) {
-            ALOGE("dexopt failed on '%s' res = %d\n", dex_path, res);
+            ALOGE("dexopt in='%s' out='%s' res=%d\n", apk_path, out_path, res);
             goto fail;
         }
     }
 
     ut.actime = apk_stat.st_atime;
     ut.modtime = apk_stat.st_mtime;
-    utime(dex_path, &ut);
-    
-    close(odex_fd);
+    utime(out_path, &ut);
+
+    close(out_fd);
     close(zip_fd);
     return 0;
 
 fail:
-    if (odex_fd >= 0) {
-        close(odex_fd);
-        unlink(dex_path);
+    if (out_fd >= 0) {
+        close(out_fd);
+        unlink(out_path);
     }
     if (zip_fd >= 0) {
         close(zip_fd);
diff --git a/cmds/installd/installd.c b/cmds/installd/installd.c
index c918633..1904408 100644
--- a/cmds/installd/installd.c
+++ b/cmds/installd/installd.c
@@ -83,7 +83,7 @@
     int64_t asecsize = 0;
     int res = 0;
 
-        /* pkgdir, persona, apkpath */
+        /* pkgdir, userid, apkpath */
     res = get_size(arg[0], atoi(arg[1]), arg[2], arg[3], arg[4], arg[5],
             &codesize, &datasize, &cachesize, &asecsize);
 
@@ -108,7 +108,7 @@
 
 static int do_rm_user(char **arg, char reply[REPLY_MAX])
 {
-    return delete_persona(atoi(arg[0])); /* userid */
+    return delete_user(atoi(arg[0])); /* userid */
 }
 
 static int do_movefiles(char **arg, char reply[REPLY_MAX])
@@ -198,7 +198,7 @@
     unsigned short count;
     int ret = -1;
 
-//    ALOGI("execute('%s')\n", cmd);
+    // ALOGI("execute('%s')\n", cmd);
 
         /* default reply is "" */
     reply[0] = 0;
@@ -240,7 +240,7 @@
     if (n > BUFFER_MAX) n = BUFFER_MAX;
     count = n;
 
-//    ALOGI("reply: '%s'\n", cmd);
+    // ALOGI("reply: '%s'\n", cmd);
     if (writex(s, &count, sizeof(count))) return -1;
     if (writex(s, cmd, count)) return -1;
     return 0;
diff --git a/cmds/installd/installd.h b/cmds/installd/installd.h
index fbfc876..635b07c 100644
--- a/cmds/installd/installd.h
+++ b/cmds/installd/installd.h
@@ -78,9 +78,6 @@
 #define PKG_NAME_MAX  128   /* largest allowed package name */
 #define PKG_PATH_MAX  256   /* max size of any path we use */
 
-#define PER_USER_RANGE ((uid_t)100000)   /* range of uids per user
-                                            uid = persona * PER_USER_RANGE + appid */
-
 /* data structures */
 
 typedef struct {
@@ -138,17 +135,17 @@
 int create_pkg_path(char path[PKG_PATH_MAX],
                     const char *pkgname,
                     const char *postfix,
-                    uid_t persona);
+                    userid_t userid);
 
-int create_persona_path(char path[PKG_PATH_MAX],
-                    uid_t persona);
+int create_user_path(char path[PKG_PATH_MAX],
+                    userid_t userid);
 
-int create_persona_media_path(char path[PKG_PATH_MAX], userid_t userid);
+int create_user_media_path(char path[PKG_PATH_MAX], userid_t userid);
 
 int create_move_path(char path[PKG_PATH_MAX],
                      const char* pkgname,
                      const char* leaf,
-                     uid_t persona);
+                     userid_t userid);
 
 int is_valid_package_name(const char* pkgname);
 
@@ -193,17 +190,17 @@
 /* commands.c */
 
 int install(const char *pkgname, uid_t uid, gid_t gid, const char *seinfo);
-int uninstall(const char *pkgname, uid_t persona);
+int uninstall(const char *pkgname, userid_t userid);
 int renamepkg(const char *oldpkgname, const char *newpkgname);
 int fix_uid(const char *pkgname, uid_t uid, gid_t gid);
-int delete_user_data(const char *pkgname, uid_t persona);
-int make_user_data(const char *pkgname, uid_t uid, uid_t persona);
-int delete_persona(uid_t persona);
-int delete_cache(const char *pkgname, uid_t persona);
+int delete_user_data(const char *pkgname, userid_t userid);
+int make_user_data(const char *pkgname, uid_t uid, userid_t userid);
+int delete_user(userid_t userid);
+int delete_cache(const char *pkgname, userid_t userid);
 int move_dex(const char *src, const char *dst);
 int rm_dex(const char *path);
 int protect(char *pkgname, gid_t gid);
-int get_size(const char *pkgname, int persona, const char *apkpath, const char *libdirpath,
+int get_size(const char *pkgname, userid_t userid, const char *apkpath, const char *libdirpath,
              const char *fwdlock_apkpath, const char *asecpath, int64_t *codesize,
              int64_t *datasize, int64_t *cachesize, int64_t *asecsize);
 int free_cache(int64_t free_size);
diff --git a/cmds/installd/tests/installd_utils_test.cpp b/cmds/installd/tests/installd_utils_test.cpp
index 7cb9b37..0b182af 100644
--- a/cmds/installd/tests/installd_utils_test.cpp
+++ b/cmds/installd/tests/installd_utils_test.cpp
@@ -340,7 +340,7 @@
 TEST_F(UtilsTest, CreatePersonaPath_Primary) {
     char path[PKG_PATH_MAX];
 
-    EXPECT_EQ(0, create_persona_path(path, 0))
+    EXPECT_EQ(0, create_user_path(path, 0))
             << "Should successfully build primary user path.";
 
     EXPECT_STREQ("/data/data/", path)
@@ -350,7 +350,7 @@
 TEST_F(UtilsTest, CreatePersonaPath_Secondary) {
     char path[PKG_PATH_MAX];
 
-    EXPECT_EQ(0, create_persona_path(path, 1))
+    EXPECT_EQ(0, create_user_path(path, 1))
             << "Should successfully build primary user path.";
 
     EXPECT_STREQ("/data/user/1/", path)
diff --git a/cmds/installd/utils.c b/cmds/installd/utils.c
index 625a35e..ef634c6 100644
--- a/cmds/installd/utils.c
+++ b/cmds/installd/utils.c
@@ -53,38 +53,39 @@
 
 /**
  * Create the package path name for a given package name with a postfix for
- * a certain persona. Returns 0 on success, and -1 on failure.
+ * a certain userid. Returns 0 on success, and -1 on failure.
  */
 int create_pkg_path(char path[PKG_PATH_MAX],
                     const char *pkgname,
                     const char *postfix,
-                    uid_t persona)
+                    userid_t userid)
 {
-    size_t uid_len;
-    char* persona_prefix;
-    if (persona == 0) {
-        persona_prefix = PRIMARY_USER_PREFIX;
-        uid_len = 0;
+    size_t userid_len;
+    char* userid_prefix;
+    if (userid == 0) {
+        userid_prefix = PRIMARY_USER_PREFIX;
+        userid_len = 0;
     } else {
-        persona_prefix = SECONDARY_USER_PREFIX;
-        uid_len = snprintf(NULL, 0, "%d", persona);
+        userid_prefix = SECONDARY_USER_PREFIX;
+        userid_len = snprintf(NULL, 0, "%d", userid);
     }
 
-    const size_t prefix_len = android_data_dir.len + strlen(persona_prefix) + uid_len + 1 /*slash*/;
+    const size_t prefix_len = android_data_dir.len + strlen(userid_prefix)
+            + userid_len + 1 /*slash*/;
     char prefix[prefix_len + 1];
 
     char *dst = prefix;
     size_t dst_size = sizeof(prefix);
 
     if (append_and_increment(&dst, android_data_dir.path, &dst_size) < 0
-            || append_and_increment(&dst, persona_prefix, &dst_size) < 0) {
+            || append_and_increment(&dst, userid_prefix, &dst_size) < 0) {
         ALOGE("Error building prefix for APK path");
         return -1;
     }
 
-    if (persona != 0) {
-        int ret = snprintf(dst, dst_size, "%d/", persona);
-        if (ret < 0 || (size_t) ret != uid_len + 1) {
+    if (userid != 0) {
+        int ret = snprintf(dst, dst_size, "%d/", userid);
+        if (ret < 0 || (size_t) ret != userid_len + 1) {
             ALOGW("Error appending UID to APK path");
             return -1;
         }
@@ -98,39 +99,39 @@
 }
 
 /**
- * Create the path name for user data for a certain persona.
+ * Create the path name for user data for a certain userid.
  * Returns 0 on success, and -1 on failure.
  */
-int create_persona_path(char path[PKG_PATH_MAX],
-                    uid_t persona)
+int create_user_path(char path[PKG_PATH_MAX],
+                    userid_t userid)
 {
-    size_t uid_len;
-    char* persona_prefix;
-    if (persona == 0) {
-        persona_prefix = PRIMARY_USER_PREFIX;
-        uid_len = 0;
+    size_t userid_len;
+    char* userid_prefix;
+    if (userid == 0) {
+        userid_prefix = PRIMARY_USER_PREFIX;
+        userid_len = 0;
     } else {
-        persona_prefix = SECONDARY_USER_PREFIX;
-        uid_len = snprintf(NULL, 0, "%d/", persona);
+        userid_prefix = SECONDARY_USER_PREFIX;
+        userid_len = snprintf(NULL, 0, "%d/", userid);
     }
 
     char *dst = path;
     size_t dst_size = PKG_PATH_MAX;
 
     if (append_and_increment(&dst, android_data_dir.path, &dst_size) < 0
-            || append_and_increment(&dst, persona_prefix, &dst_size) < 0) {
+            || append_and_increment(&dst, userid_prefix, &dst_size) < 0) {
         ALOGE("Error building prefix for user path");
         return -1;
     }
 
-    if (persona != 0) {
-        if (dst_size < uid_len + 1) {
+    if (userid != 0) {
+        if (dst_size < userid_len + 1) {
             ALOGE("Error building user path");
             return -1;
         }
-        int ret = snprintf(dst, dst_size, "%d/", persona);
-        if (ret < 0 || (size_t) ret != uid_len) {
-            ALOGE("Error appending persona id to path");
+        int ret = snprintf(dst, dst_size, "%d/", userid);
+        if (ret < 0 || (size_t) ret != userid_len) {
+            ALOGE("Error appending userid to path");
             return -1;
         }
     }
@@ -138,10 +139,10 @@
 }
 
 /**
- * Create the path name for media for a certain persona.
+ * Create the path name for media for a certain userid.
  * Returns 0 on success, and -1 on failure.
  */
-int create_persona_media_path(char path[PATH_MAX], userid_t userid) {
+int create_user_media_path(char path[PATH_MAX], userid_t userid) {
     if (snprintf(path, PATH_MAX, "%s%d", android_media_dir.path, userid) > PATH_MAX) {
         return -1;
     }
@@ -151,7 +152,7 @@
 int create_move_path(char path[PKG_PATH_MAX],
     const char* pkgname,
     const char* leaf,
-    uid_t persona)
+    userid_t userid)
 {
     if ((android_data_dir.len + strlen(PRIMARY_USER_PREFIX) + strlen(pkgname) + strlen(leaf) + 1)
             >= PKG_PATH_MAX) {
@@ -997,7 +998,7 @@
     char path[PATH_MAX];
 
     // Ensure /data/media/<userid> exists
-    create_persona_media_path(media_user_path, userid);
+    create_user_media_path(media_user_path, userid);
     if (fs_prepare_dir(media_user_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW) == -1) {
         return -1;
     }
diff --git a/cmds/rawbu/backup.cpp b/cmds/rawbu/backup.cpp
index 70e7b57..ff6719f 100644
--- a/cmds/rawbu/backup.cpp
+++ b/cmds/rawbu/backup.cpp
@@ -639,6 +639,12 @@
     fprintf(stderr, "options include:\n"
                     "  -h              Show this help text.\n"
                     "  -a              Backup all files.\n");
+    fprintf(stderr, "\n backup-file-path Defaults to /sdcard/backup.dat .\n"
+                    "                  On devices that emulate the sdcard, you will need to\n"
+                    "                  explicitly specify the directory it is mapped to,\n"
+                    "                  to avoid recursive backup or deletion of the backup file\n"
+                    "                  during restore.\n\n"
+                    "                  Eg. /data/media/0/backup.dat\n");
     fprintf(stderr, "\nThe %s command allows you to perform low-level\n"
                     "backup and restore of the /data partition.  This is\n"
                     "where all user data is kept, allowing for a fairly\n"
diff --git a/cmds/sensorservice/Android.mk b/cmds/sensorservice/Android.mk
deleted file mode 100644
index 0811be5..0000000
--- a/cmds/sensorservice/Android.mk
+++ /dev/null
@@ -1,19 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-	main_sensorservice.cpp
-
-LOCAL_SHARED_LIBRARIES := \
-	libsensorservice \
-	libbinder \
-	libutils
-
-LOCAL_C_INCLUDES := \
-	$(LOCAL_PATH)/../../services/sensorservice
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_MODULE:= sensorservice
-
-include $(BUILD_EXECUTABLE)
diff --git a/cmds/service/service.cpp b/cmds/service/service.cpp
index 32db83b..97fc47c 100644
--- a/cmds/service/service.cpp
+++ b/cmds/service/service.cpp
@@ -1,12 +1,23 @@
 /*
- * Command line access to services.
+ * Copyright 2013 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 <binder/Parcel.h>
 #include <binder/ProcessState.h>
 #include <binder/IServiceManager.h>
-#include <utils/TextOutput.h>
+#include <binder/TextOutput.h>
 
 #include <getopt.h>
 #include <stdlib.h>
diff --git a/cmds/surfaceflinger/Android.mk b/cmds/surfaceflinger/Android.mk
deleted file mode 100644
index 1df32bb..0000000
--- a/cmds/surfaceflinger/Android.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-	main_surfaceflinger.cpp 
-
-LOCAL_SHARED_LIBRARIES := \
-	libsurfaceflinger \
-	libbinder \
-	libutils
-
-LOCAL_C_INCLUDES := \
-	$(LOCAL_PATH)/../../services/surfaceflinger
-
-LOCAL_MODULE:= surfaceflinger
-
-include $(BUILD_EXECUTABLE)
diff --git a/cmds/surfaceflinger/main_surfaceflinger.cpp b/cmds/surfaceflinger/main_surfaceflinger.cpp
deleted file mode 100644
index ce7fde0..0000000
--- a/cmds/surfaceflinger/main_surfaceflinger.cpp
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#include <binder/BinderService.h>
-#include <SurfaceFlinger.h>
-
-using namespace android;
-
-int main(int argc, char** argv) {
-    // When SF is launched in its own process, limit the number of
-    // binder threads to 4.
-    ProcessState::self()->setThreadPoolMaxThreadCount(4);
-    SurfaceFlinger::publishAndJoinThreadPool(true);
-    return 0;
-}
diff --git a/data/etc/android.hardware.consumerir.xml b/data/etc/android.hardware.consumerir.xml
new file mode 100644
index 0000000..adba2f9
--- /dev/null
+++ b/data/etc/android.hardware.consumerir.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2013 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.
+-->
+
+<!-- This is the standard feature indicating that the device can communicate
+     using Near-Field Communications (NFC). -->
+<permissions>
+    <feature name="android.hardware.consumerir" />
+</permissions>
diff --git a/data/etc/android.hardware.nfc.hce.xml b/data/etc/android.hardware.nfc.hce.xml
new file mode 100644
index 0000000..10b96b1
--- /dev/null
+++ b/data/etc/android.hardware.nfc.hce.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2013 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.
+-->
+
+<!-- This feature indicates that the device supports host-based
+     NFC card emulation -->
+<permissions>
+    <feature name="android.hardware.nfc.hce" />
+</permissions>
diff --git a/data/etc/android.hardware.sensor.stepcounter.xml b/data/etc/android.hardware.sensor.stepcounter.xml
new file mode 100644
index 0000000..401ae92
--- /dev/null
+++ b/data/etc/android.hardware.sensor.stepcounter.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2013 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.
+-->
+
+<!-- Feature for devices with a hardware step counter. -->
+<permissions>
+    <feature name="android.hardware.sensor.stepcounter" />
+</permissions>
diff --git a/data/etc/android.hardware.sensor.stepdetector.xml b/data/etc/android.hardware.sensor.stepdetector.xml
new file mode 100644
index 0000000..7037b9a
--- /dev/null
+++ b/data/etc/android.hardware.sensor.stepdetector.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2013 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.
+-->
+
+<!-- Feature for devices with a step detector. -->
+<permissions>
+    <feature name="android.hardware.sensor.stepdetector" />
+</permissions>
diff --git a/data/etc/handheld_core_hardware.xml b/data/etc/handheld_core_hardware.xml
index 290afc2..4a9f2dd 100644
--- a/data/etc/handheld_core_hardware.xml
+++ b/data/etc/handheld_core_hardware.xml
@@ -36,6 +36,8 @@
     <feature name="android.software.app_widgets" />
     <feature name="android.software.home_screen" />
     <feature name="android.software.input_methods" />
+    <!-- Feature to specify if the device supports adding device admins. -->
+    <feature name="android.software.device_admin" />
     <!-- devices with GPS must include android.hardware.location.gps.xml -->
     <!-- devices with an autofocus camera and/or flash must include either
          android.hardware.camera.autofocus.xml or 
diff --git a/data/etc/tablet_core_hardware.xml b/data/etc/tablet_core_hardware.xml
index 207fc9a..78b9736 100644
--- a/data/etc/tablet_core_hardware.xml
+++ b/data/etc/tablet_core_hardware.xml
@@ -37,6 +37,8 @@
     <feature name="android.software.app_widgets" />
     <feature name="android.software.home_screen" />
     <feature name="android.software.input_methods" />
+    <!-- Feature to specify if the device supports adding device admins. -->
+    <feature name="android.software.device_admin" />
     <!-- devices with GPS must include android.hardware.location.gps.xml -->
     <!-- devices with a rear-facing camera must include one of these as appropriate:
          android.hardware.camera.xml or 
diff --git a/include/android/keycodes.h b/include/android/keycodes.h
index cf38d1a..1ca1332 100644
--- a/include/android/keycodes.h
+++ b/include/android/keycodes.h
@@ -265,6 +265,7 @@
     AKEYCODE_ASSIST          = 219,
     AKEYCODE_BRIGHTNESS_DOWN = 220,
     AKEYCODE_BRIGHTNESS_UP   = 221,
+    AKEYCODE_MEDIA_AUDIO_TRACK = 222,
 
     // NOTE: If you add a new keycode here you must also add it to several other files.
     //       Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
diff --git a/include/android/sensor.h b/include/android/sensor.h
index f163f18..129ea3e 100644
--- a/include/android/sensor.h
+++ b/include/android/sensor.h
@@ -106,6 +106,30 @@
     uint8_t reserved[3];
 } ASensorVector;
 
+typedef struct AMetaDataEvent {
+    int32_t what;
+    int32_t sensor;
+} AMetaDataEvent;
+
+typedef struct AUncalibratedEvent {
+  union {
+    float uncalib[3];
+    struct {
+      float x_uncalib;
+      float y_uncalib;
+      float z_uncalib;
+    };
+  };
+  union {
+    float bias[3];
+    struct {
+      float x_bias;
+      float y_bias;
+      float z_bias;
+    };
+  };
+} AUncalibratedEvent;
+
 /* NOTE: Must match hardware/sensors.h */
 typedef struct ASensorEvent {
     int32_t version; /* sizeof(struct ASensorEvent) */
@@ -114,19 +138,28 @@
     int32_t reserved0;
     int64_t timestamp;
     union {
-        float           data[16];
-        ASensorVector   vector;
-        ASensorVector   acceleration;
-        ASensorVector   magnetic;
-        float           temperature;
-        float           distance;
-        float           light;
-        float           pressure;
+        union {
+            float           data[16];
+            ASensorVector   vector;
+            ASensorVector   acceleration;
+            ASensorVector   magnetic;
+            float           temperature;
+            float           distance;
+            float           light;
+            float           pressure;
+            float           relative_humidity;
+            AUncalibratedEvent uncalibrated_gyro;
+            AUncalibratedEvent uncalibrated_magnetic;
+            AMetaDataEvent meta_data;
+        };
+        union {
+            uint64_t        data[8];
+            uint64_t        step_counter;
+        } u64;
     };
     int32_t reserved1[4];
 } ASensorEvent;
 
-
 struct ASensorManager;
 typedef struct ASensorManager ASensorManager;
 
diff --git a/include/batteryservice/BatteryService.h b/include/batteryservice/BatteryService.h
new file mode 100644
index 0000000..829061a
--- /dev/null
+++ b/include/batteryservice/BatteryService.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2013 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_BATTERYSERVICE_H
+#define ANDROID_BATTERYSERVICE_H
+
+#include <binder/Parcel.h>
+#include <utils/Errors.h>
+#include <utils/String8.h>
+
+namespace android {
+
+// must be kept in sync with definitions in BatteryManager.java
+enum {
+    BATTERY_STATUS_UNKNOWN = 1, // equals BatteryManager.BATTERY_STATUS_UNKNOWN constant
+    BATTERY_STATUS_CHARGING = 2, // equals BatteryManager.BATTERY_STATUS_CHARGING constant
+    BATTERY_STATUS_DISCHARGING = 3, // equals BatteryManager.BATTERY_STATUS_DISCHARGING constant
+    BATTERY_STATUS_NOT_CHARGING = 4, // equals BatteryManager.BATTERY_STATUS_NOT_CHARGING constant
+    BATTERY_STATUS_FULL = 5, // equals BatteryManager.BATTERY_STATUS_FULL constant
+};
+
+// must be kept in sync with definitions in BatteryManager.java
+enum {
+    BATTERY_HEALTH_UNKNOWN = 1, // equals BatteryManager.BATTERY_HEALTH_UNKNOWN constant
+    BATTERY_HEALTH_GOOD = 2, // equals BatteryManager.BATTERY_HEALTH_GOOD constant
+    BATTERY_HEALTH_OVERHEAT = 3, // equals BatteryManager.BATTERY_HEALTH_OVERHEAT constant
+    BATTERY_HEALTH_DEAD = 4, // equals BatteryManager.BATTERY_HEALTH_DEAD constant
+    BATTERY_HEALTH_OVER_VOLTAGE = 5, // equals BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE constant
+    BATTERY_HEALTH_UNSPECIFIED_FAILURE = 6, // equals BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE constant
+    BATTERY_HEALTH_COLD = 7, // equals BatteryManager.BATTERY_HEALTH_COLD constant
+};
+
+struct BatteryProperties {
+    bool chargerAcOnline;
+    bool chargerUsbOnline;
+    bool chargerWirelessOnline;
+    int batteryStatus;
+    int batteryHealth;
+    bool batteryPresent;
+    int batteryLevel;
+    int batteryVoltage;
+    int batteryCurrentNow;
+    int batteryChargeCounter;
+    int batteryTemperature;
+    String8 batteryTechnology;
+
+    status_t writeToParcel(Parcel* parcel) const;
+    status_t readFromParcel(Parcel* parcel);
+};
+
+}; // namespace android
+
+#endif // ANDROID_BATTERYSERVICE_H
diff --git a/include/batteryservice/IBatteryPropertiesListener.h b/include/batteryservice/IBatteryPropertiesListener.h
new file mode 100644
index 0000000..b02d8e9
--- /dev/null
+++ b/include/batteryservice/IBatteryPropertiesListener.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2013 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_IBATTERYPROPERTIESLISTENER_H
+#define ANDROID_IBATTERYPROPERTIESLISTENER_H
+
+#include <binder/IBinder.h>
+#include <binder/IInterface.h>
+
+#include <batteryservice/BatteryService.h>
+
+namespace android {
+
+// must be kept in sync with interface defined in IBatteryPropertiesListener.aidl
+enum {
+        TRANSACT_BATTERYPROPERTIESCHANGED = IBinder::FIRST_CALL_TRANSACTION,
+};
+
+// ----------------------------------------------------------------------------
+
+class IBatteryPropertiesListener : public IInterface {
+public:
+    DECLARE_META_INTERFACE(BatteryPropertiesListener);
+
+    virtual void batteryPropertiesChanged(struct BatteryProperties props) = 0;
+};
+
+// ----------------------------------------------------------------------------
+
+}; // namespace android
+
+#endif // ANDROID_IBATTERYPROPERTIESLISTENER_H
diff --git a/include/batteryservice/IBatteryPropertiesRegistrar.h b/include/batteryservice/IBatteryPropertiesRegistrar.h
new file mode 100644
index 0000000..8d28b1d
--- /dev/null
+++ b/include/batteryservice/IBatteryPropertiesRegistrar.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2013 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_IBATTERYPROPERTIESREGISTRAR_H
+#define ANDROID_IBATTERYPROPERTIESREGISTRAR_H
+
+#include <binder/IInterface.h>
+#include <batteryservice/IBatteryPropertiesListener.h>
+
+namespace android {
+
+// must be kept in sync with interface defined in IBatteryPropertiesRegistrar.aidl
+enum {
+    REGISTER_LISTENER = IBinder::FIRST_CALL_TRANSACTION,
+    UNREGISTER_LISTENER,
+};
+
+class IBatteryPropertiesRegistrar : public IInterface {
+public:
+    DECLARE_META_INTERFACE(BatteryPropertiesRegistrar);
+
+    virtual void registerListener(const sp<IBatteryPropertiesListener>& listener) = 0;
+    virtual void unregisterListener(const sp<IBatteryPropertiesListener>& listener) = 0;
+};
+
+class BnBatteryPropertiesRegistrar : public BnInterface<IBatteryPropertiesRegistrar> {
+public:
+    virtual status_t onTransact(uint32_t code, const Parcel& data,
+                                Parcel* reply, uint32_t flags = 0);
+};
+
+}; // namespace android
+
+#endif // ANDROID_IBATTERYPROPERTIESREGISTRAR_H
diff --git a/include/binder/BinderService.h b/include/binder/BinderService.h
index 5ac36d9..ef703bd 100644
--- a/include/binder/BinderService.h
+++ b/include/binder/BinderService.h
@@ -42,19 +42,20 @@
     }
 
     static void publishAndJoinThreadPool(bool allowIsolated = false) {
-        sp<IServiceManager> sm(defaultServiceManager());
-        sm->addService(
-                String16(SERVICE::getServiceName()),
-                new SERVICE(), allowIsolated);
-        ProcessState::self()->startThreadPool();
-        ProcessState::self()->giveThreadPoolName();
-        IPCThreadState::self()->joinThreadPool();
+        publish(allowIsolated);
+        joinThreadPool();
     }
 
     static void instantiate() { publish(); }
 
-    static status_t shutdown() {
-        return NO_ERROR;
+    static status_t shutdown() { return NO_ERROR; }
+
+private:
+    static void joinThreadPool() {
+        sp<ProcessState> ps(ProcessState::self());
+        ps->startThreadPool();
+        ps->giveThreadPoolName();
+        IPCThreadState::self()->joinThreadPool();
     }
 };
 
diff --git a/include/utils/BufferedTextOutput.h b/include/binder/BufferedTextOutput.h
similarity index 96%
rename from include/utils/BufferedTextOutput.h
rename to include/binder/BufferedTextOutput.h
index 69c6240..9a7c43b 100644
--- a/include/utils/BufferedTextOutput.h
+++ b/include/binder/BufferedTextOutput.h
@@ -17,9 +17,9 @@
 #ifndef ANDROID_BUFFEREDTEXTOUTPUT_H
 #define ANDROID_BUFFEREDTEXTOUTPUT_H
 
-#include <utils/TextOutput.h>
+#include <binder/TextOutput.h>
 #include <utils/threads.h>
-#include <cutils/uio.h>
+#include <sys/uio.h>
 
 // ---------------------------------------------------------------------------
 namespace android {
diff --git a/include/utils/Debug.h b/include/binder/Debug.h
similarity index 62%
rename from include/utils/Debug.h
rename to include/binder/Debug.h
index d9ed32d..f6a3355 100644
--- a/include/utils/Debug.h
+++ b/include/binder/Debug.h
@@ -14,8 +14,8 @@
  * limitations under the License.
  */
 
-#ifndef ANDROID_DEBUG_H
-#define ANDROID_DEBUG_H
+#ifndef ANDROID_BINDER_DEBUG_H
+#define ANDROID_BINDER_DEBUG_H
 
 #include <stdint.h>
 #include <sys/types.h>
@@ -24,27 +24,6 @@
 // ---------------------------------------------------------------------------
 
 #ifdef __cplusplus
-template<bool> struct CompileTimeAssert;
-template<> struct CompileTimeAssert<true> {};
-#define COMPILE_TIME_ASSERT(_exp) \
-    template class CompileTimeAssert< (_exp) >;
-#endif
-#define COMPILE_TIME_ASSERT_FUNCTION_SCOPE(_exp) \
-    CompileTimeAssert<( _exp )>();
-
-// ---------------------------------------------------------------------------
-
-#ifdef __cplusplus
-template<bool C, typename LSH, typename RHS> struct CompileTimeIfElse;
-template<typename LHS, typename RHS> 
-struct CompileTimeIfElse<true,  LHS, RHS> { typedef LHS TYPE; };
-template<typename LHS, typename RHS> 
-struct CompileTimeIfElse<false, LHS, RHS> { typedef RHS TYPE; };
-#endif
-
-// ---------------------------------------------------------------------------
-
-#ifdef __cplusplus
 extern "C" {
 #endif
 
@@ -67,4 +46,4 @@
 // ---------------------------------------------------------------------------
 }; // namespace android
 
-#endif // ANDROID_DEBUG_H
+#endif // ANDROID_BINDER_DEBUG_H
diff --git a/include/binder/IAppOpsService.h b/include/binder/IAppOpsService.h
index 7cb55e5..193e9cc 100644
--- a/include/binder/IAppOpsService.h
+++ b/include/binder/IAppOpsService.h
@@ -32,11 +32,14 @@
 
     virtual int32_t checkOperation(int32_t code, int32_t uid, const String16& packageName) = 0;
     virtual int32_t noteOperation(int32_t code, int32_t uid, const String16& packageName) = 0;
-    virtual int32_t startOperation(int32_t code, int32_t uid, const String16& packageName) = 0;
-    virtual void finishOperation(int32_t code, int32_t uid, const String16& packageName) = 0;
+    virtual int32_t startOperation(const sp<IBinder>& token, int32_t code, int32_t uid,
+            const String16& packageName) = 0;
+    virtual void finishOperation(const sp<IBinder>& token, int32_t code, int32_t uid,
+            const String16& packageName) = 0;
     virtual void startWatchingMode(int32_t op, const String16& packageName,
             const sp<IAppOpsCallback>& callback) = 0;
     virtual void stopWatchingMode(const sp<IAppOpsCallback>& callback) = 0;
+    virtual sp<IBinder> getToken(const sp<IBinder>& clientToken) = 0;
 
     enum {
         CHECK_OPERATION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
@@ -44,7 +47,8 @@
         START_OPERATION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+2,
         FINISH_OPERATION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+3,
         START_WATCHING_MODE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+4,
-        STOP_WATCHING_MODE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+5
+        STOP_WATCHING_MODE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+5,
+        GET_TOKEN_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION+6,
     };
 
     enum {
diff --git a/include/binder/IPCThreadState.h b/include/binder/IPCThreadState.h
index 3378d97..5bc123e 100644
--- a/include/binder/IPCThreadState.h
+++ b/include/binder/IPCThreadState.h
@@ -39,8 +39,8 @@
             
             status_t            clearLastError();
 
-            int                 getCallingPid();
-            int                 getCallingUid();
+            int                 getCallingPid() const;
+            int                 getCallingUid() const;
 
             void                setStrictModePolicy(int32_t policy);
             int32_t             getStrictModePolicy() const;
@@ -51,6 +51,8 @@
             int64_t             clearCallingIdentity();
             void                restoreCallingIdentity(int64_t token);
             
+            int                 setupPolling(int* fd);
+            status_t            handlePolledCommands();
             void                flushCommands();
 
             void                joinThreadPool(bool isMain = true);
@@ -96,7 +98,9 @@
                                                      uint32_t code,
                                                      const Parcel& data,
                                                      status_t* statusBuffer);
+            status_t            getAndExecuteCommand();
             status_t            executeCommand(int32_t command);
+            void                processPendingDerefs();
             
             void                clearCaller();
             
diff --git a/include/binder/Parcel.h b/include/binder/Parcel.h
index 40ba529..98f20de 100644
--- a/include/binder/Parcel.h
+++ b/include/binder/Parcel.h
@@ -27,8 +27,8 @@
 // ---------------------------------------------------------------------------
 namespace android {
 
+template <typename T> class Flattenable;
 template <typename T> class LightFlattenable;
-class Flattenable;
 class IBinder;
 class IPCThreadState;
 class ProcessState;
@@ -37,8 +37,7 @@
 
 struct flat_binder_object;  // defined in support_p/binder_module.h
 
-class Parcel
-{
+class Parcel {
 public:
     class ReadableBlob;
     class WritableBlob;
@@ -102,10 +101,13 @@
     status_t            writeString16(const char16_t* str, size_t len);
     status_t            writeStrongBinder(const sp<IBinder>& val);
     status_t            writeWeakBinder(const wp<IBinder>& val);
-    status_t            write(const Flattenable& val);
+    status_t            writeInt32Array(size_t len, const int32_t *val);
     status_t            writeByteArray(size_t len, const uint8_t *val);
 
     template<typename T>
+    status_t            write(const Flattenable<T>& val);
+
+    template<typename T>
     status_t            write(const LightFlattenable<T>& val);
 
 
@@ -158,7 +160,9 @@
     const char16_t*     readString16Inplace(size_t* outLen) const;
     sp<IBinder>         readStrongBinder() const;
     wp<IBinder>         readWeakBinder() const;
-    status_t            read(Flattenable& val) const;
+
+    template<typename T>
+    status_t            read(Flattenable<T>& val) const;
 
     template<typename T>
     status_t            read(LightFlattenable<T>& val) const;
@@ -261,6 +265,39 @@
         size_t mSize;
     };
 
+    class FlattenableHelperInterface {
+    protected:
+        ~FlattenableHelperInterface() { }
+    public:
+        virtual size_t getFlattenedSize() const = 0;
+        virtual size_t getFdCount() const = 0;
+        virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const = 0;
+        virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) = 0;
+    };
+
+    template<typename T>
+    class FlattenableHelper : public FlattenableHelperInterface {
+        friend class Parcel;
+        const Flattenable<T>& val;
+        explicit FlattenableHelper(const Flattenable<T>& val) : val(val) { }
+
+    public:
+        virtual size_t getFlattenedSize() const {
+            return val.getFlattenedSize();
+        }
+        virtual size_t getFdCount() const {
+            return val.getFdCount();
+        }
+        virtual status_t flatten(void* buffer, size_t size, int* fds, size_t count) const {
+            return val.flatten(buffer, size, fds, count);
+        }
+        virtual status_t unflatten(void const* buffer, size_t size, int const* fds, size_t count) {
+            return const_cast<Flattenable<T>&>(val).unflatten(buffer, size, fds, count);
+        }
+    };
+    status_t write(const FlattenableHelperInterface& val);
+    status_t read(FlattenableHelperInterface& val) const;
+
 public:
     class ReadableBlob : public Blob {
         friend class Parcel;
@@ -278,8 +315,14 @@
 // ---------------------------------------------------------------------------
 
 template<typename T>
+status_t Parcel::write(const Flattenable<T>& val) {
+    const FlattenableHelper<T> helper(val);
+    return write(helper);
+}
+
+template<typename T>
 status_t Parcel::write(const LightFlattenable<T>& val) {
-    size_t size(val.getSize());
+    size_t size(val.getFlattenedSize());
     if (!val.isFixedSize()) {
         status_t err = writeInt32(size);
         if (err != NO_ERROR) {
@@ -288,17 +331,24 @@
     }
     if (size) {
         void* buffer = writeInplace(size);
-        return buffer == NULL ? NO_MEMORY :
-                val.flatten(buffer);
+        if (buffer == NULL)
+            return NO_MEMORY;
+        return val.flatten(buffer, size);
     }
     return NO_ERROR;
 }
 
 template<typename T>
+status_t Parcel::read(Flattenable<T>& val) const {
+    FlattenableHelper<T> helper(val);
+    return read(helper);
+}
+
+template<typename T>
 status_t Parcel::read(LightFlattenable<T>& val) const {
     size_t size;
     if (val.isFixedSize()) {
-        size = val.getSize();
+        size = val.getFlattenedSize();
     } else {
         int32_t s;
         status_t err = readInt32(&s);
diff --git a/include/utils/TextOutput.h b/include/binder/TextOutput.h
similarity index 96%
rename from include/utils/TextOutput.h
rename to include/binder/TextOutput.h
index de2fbbe..974a194 100644
--- a/include/utils/TextOutput.h
+++ b/include/binder/TextOutput.h
@@ -25,6 +25,9 @@
 // ---------------------------------------------------------------------------
 namespace android {
 
+class String8;
+class String16;
+
 class TextOutput
 {
 public:
@@ -76,6 +79,8 @@
 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);
 
 class TypeCode 
 {
diff --git a/include/cpustats/CentralTendencyStatistics.h b/include/cpustats/CentralTendencyStatistics.h
deleted file mode 100644
index 21b6981..0000000
--- a/include/cpustats/CentralTendencyStatistics.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2011 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 _CENTRAL_TENDENCY_STATISTICS_H
-#define _CENTRAL_TENDENCY_STATISTICS_H
-
-#include <math.h>
-
-// Not multithread safe
-class CentralTendencyStatistics {
-
-public:
-
-    CentralTendencyStatistics() :
-            mMean(NAN), mMedian(NAN), mMinimum(INFINITY), mMaximum(-INFINITY), mN(0), mM2(0),
-            mVariance(NAN), mVarianceKnownForN(0), mStddev(NAN), mStddevKnownForN(0) { }
-
-    ~CentralTendencyStatistics() { }
-
-    // add x to the set of samples
-    void sample(double x);
-
-    // return the arithmetic mean of all samples so far
-    double mean() const { return mMean; }
-
-    // return the minimum of all samples so far
-    double minimum() const { return mMinimum; }
-
-    // return the maximum of all samples so far
-    double maximum() const { return mMaximum; }
-
-    // return the variance of all samples so far
-    double variance() const;
-
-    // return the standard deviation of all samples so far
-    double stddev() const;
-
-    // return the number of samples added so far
-    unsigned n() const { return mN; }
-
-    // reset the set of samples to be empty
-    void reset();
-
-private:
-    double mMean;
-    double mMedian;
-    double mMinimum;
-    double mMaximum;
-    unsigned mN;    // number of samples so far
-    double mM2;
-
-    // cached variance, and n at time of caching
-    mutable double mVariance;
-    mutable unsigned mVarianceKnownForN;
-
-    // cached standard deviation, and n at time of caching
-    mutable double mStddev;
-    mutable unsigned mStddevKnownForN;
-
-};
-
-#endif // _CENTRAL_TENDENCY_STATISTICS_H
diff --git a/include/cpustats/README.txt b/include/cpustats/README.txt
deleted file mode 100644
index 14439f0..0000000
--- a/include/cpustats/README.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-This is a static library of CPU usage statistics, originally written
-for audio but most are not actually specific to audio.
-
-Requirements to be here:
- * should be related to CPU usage statistics
- * should be portable to host; avoid Android OS dependencies without a conditional
diff --git a/include/cpustats/ThreadCpuUsage.h b/include/cpustats/ThreadCpuUsage.h
deleted file mode 100644
index 9756844..0000000
--- a/include/cpustats/ThreadCpuUsage.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2011 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 _THREAD_CPU_USAGE_H
-#define _THREAD_CPU_USAGE_H
-
-#include <fcntl.h>
-#include <pthread.h>
-
-namespace android {
-
-// Track CPU usage for the current thread.
-// Units are in per-thread CPU ns, as reported by
-// clock_gettime(CLOCK_THREAD_CPUTIME_ID).  Simple usage: for cyclic
-// threads where you want to measure the execution time of the whole
-// cycle, just call sampleAndEnable() at the start of each cycle.
-// For acyclic threads, or for cyclic threads where you want to measure/track
-// only part of each cycle, call enable(), disable(), and/or setEnabled()
-// to demarcate the region(s) of interest, and then call sample() periodically.
-// This class is not thread-safe for concurrent calls from multiple threads;
-// the methods of this class may only be called by the current thread
-// which constructed the object.
-
-class ThreadCpuUsage
-{
-
-public:
-    ThreadCpuUsage() :
-        mIsEnabled(false),
-        mWasEverEnabled(false),
-        mAccumulator(0),
-        // mPreviousTs
-        // mMonotonicTs
-        mMonotonicKnown(false)
-        {
-            (void) pthread_once(&sOnceControl, &init);
-            for (int i = 0; i < sKernelMax; ++i) {
-                mCurrentkHz[i] = (uint32_t) ~0;   // unknown
-            }
-        }
-
-    ~ThreadCpuUsage() { }
-
-    // Return whether currently tracking CPU usage by current thread
-    bool isEnabled() const  { return mIsEnabled; }
-
-    // Enable tracking of CPU usage by current thread;
-    // any CPU used from this point forward will be tracked.
-    // Returns the previous enabled status.
-    bool enable()       { return setEnabled(true); }
-
-    // Disable tracking of CPU usage by current thread;
-    // any CPU used from this point forward will be ignored.
-    // Returns the previous enabled status.
-    bool disable()      { return setEnabled(false); }
-
-    // Set the enabled status and return the previous enabled status.
-    // This method is intended to be used for safe nested enable/disabling.
-    bool setEnabled(bool isEnabled);
-
-    // Add a sample point, and also enable tracking if needed.
-    // If tracking has never been enabled, then this call enables tracking but
-    // does _not_ add a sample -- it is not possible to add a sample the
-    // first time because there is no previous point to subtract from.
-    // Otherwise, if tracking is enabled,
-    // then adds a sample for tracked CPU ns since the previous
-    // sample, or since the first call to sampleAndEnable(), enable(), or
-    // setEnabled(true).  If there was a previous sample but tracking is
-    // now disabled, then adds a sample for the tracked CPU ns accumulated
-    // up until the most recent disable(), resets this accumulator, and then
-    // enables tracking.  Calling this method rather than enable() followed
-    // by sample() avoids a race condition for the first sample.
-    // Returns true if the sample 'ns' is valid, or false if invalid.
-    // Note that 'ns' is an output parameter passed by reference.
-    // The caller does not need to initialize this variable.
-    // The units are CPU nanoseconds consumed by current thread.
-    bool sampleAndEnable(double& ns);
-
-    // Add a sample point, but do not
-    // change the tracking enabled status.  If tracking has either never been
-    // enabled, or has never been enabled since the last sample, then log a warning
-    // and don't add sample.  Otherwise, adds a sample for tracked CPU ns since
-    // the previous sample or since the first call to sampleAndEnable(),
-    // enable(), or setEnabled(true) if no previous sample.
-    // Returns true if the sample is valid, or false if invalid.
-    // Note that 'ns' is an output parameter passed by reference.
-    // The caller does not need to initialize this variable.
-    // The units are CPU nanoseconds consumed by current thread.
-    bool sample(double& ns);
-
-    // Return the elapsed delta wall clock ns since initial enable or reset,
-    // as reported by clock_gettime(CLOCK_MONOTONIC).
-    long long elapsed() const;
-
-    // Reset elapsed wall clock.  Has no effect on tracking or accumulator.
-    void resetElapsed();
-
-    // Return current clock frequency for specified CPU, in kHz.
-    // You can get your CPU number using sched_getcpu(2).  Note that, unless CPU affinity
-    // has been configured appropriately, the CPU number can change.
-    // Also note that, unless the CPU governor has been configured appropriately,
-    // the CPU frequency can change.  And even if the CPU frequency is locked down
-    // to a particular value, that the frequency might still be adjusted
-    // to prevent thermal overload.  Therefore you should poll for your thread's
-    // current CPU number and clock frequency periodically.
-    uint32_t getCpukHz(int cpuNum);
-
-private:
-    bool mIsEnabled;                // whether tracking is currently enabled
-    bool mWasEverEnabled;           // whether tracking was ever enabled
-    long long mAccumulator;         // accumulated thread CPU time since last sample, in ns
-    struct timespec mPreviousTs;    // most recent thread CPU time, valid only if mIsEnabled is true
-    struct timespec mMonotonicTs;   // most recent monotonic time
-    bool mMonotonicKnown;           // whether mMonotonicTs has been set
-
-    static const int MAX_CPU = 8;
-    static int sScalingFds[MAX_CPU];// file descriptor per CPU for reading scaling_cur_freq
-    uint32_t mCurrentkHz[MAX_CPU];  // current CPU frequency in kHz, not static to avoid a race
-    static pthread_once_t sOnceControl;
-    static int sKernelMax;          // like MAX_CPU, but determined at runtime == cpu/kernel_max + 1
-    static void init();             // called once at first ThreadCpuUsage construction
-    static pthread_mutex_t sMutex;  // protects sScalingFds[] after initialization
-};
-
-}   // namespace android
-
-#endif //  _THREAD_CPU_USAGE_H
diff --git a/include/gui/BitTube.h b/include/gui/BitTube.h
index 3022d05..d32df84 100644
--- a/include/gui/BitTube.h
+++ b/include/gui/BitTube.h
@@ -33,30 +33,49 @@
 {
 public:
 
-            BitTube();
-            BitTube(const Parcel& data);
+    // creates a BitTube with a default (4KB) send buffer
+    BitTube();
+
+    // creates a BitTube with a a specified send and receive buffer size
+    explicit BitTube(size_t bufsize);
+
+    explicit BitTube(const Parcel& data);
     virtual ~BitTube();
 
+    // check state after construction
     status_t initCheck() const;
+
+    // get receive file-descriptor
     int getFd() const;
-    ssize_t write(void const* vaddr, size_t size);
-    ssize_t read(void* vaddr, size_t size);
 
-    status_t writeToParcel(Parcel* reply) const;
-
+    // send objects (sized blobs). All objects are guaranteed to be written or the call fails.
     template <typename T>
     static ssize_t sendObjects(const sp<BitTube>& tube,
             T const* events, size_t count) {
         return sendObjects(tube, events, count, sizeof(T));
     }
 
+    // receive objects (sized blobs). If the receiving buffer isn't large enough,
+    // excess messages are silently discarded.
     template <typename T>
     static ssize_t recvObjects(const sp<BitTube>& tube,
             T* events, size_t count) {
         return recvObjects(tube, events, count, sizeof(T));
     }
 
+    // parcels this BitTube
+    status_t writeToParcel(Parcel* reply) const;
+
 private:
+    void init(size_t rcvbuf, size_t sndbuf);
+
+    // send a message. The write is guaranteed to send the whole message or fail.
+    ssize_t write(void const* vaddr, size_t size);
+
+    // receive a message. the passed buffer must be at least as large as the
+    // write call used to send the message, excess data is silently discarded.
+    ssize_t read(void* vaddr, size_t size);
+
     int mSendFd;
     mutable int mReceiveFd;
 
diff --git a/include/gui/BufferItemConsumer.h b/include/gui/BufferItemConsumer.h
index 98b450c..52edf17 100644
--- a/include/gui/BufferItemConsumer.h
+++ b/include/gui/BufferItemConsumer.h
@@ -29,6 +29,8 @@
 
 namespace android {
 
+class BufferQueue;
+
 /**
  * BufferItemConsumer is a BufferQueue consumer endpoint that allows clients
  * access to the whole BufferItem entry from BufferQueue. Multiple buffers may
@@ -49,9 +51,11 @@
     // the consumer usage flags passed to the graphics allocator. The
     // bufferCount parameter specifies how many buffers can be locked for user
     // access at the same time.
-    BufferItemConsumer(uint32_t consumerUsage,
+    // controlledByApp tells whether this consumer is controlled by the
+    // application.
+    BufferItemConsumer(const sp<BufferQueue>& bq, uint32_t consumerUsage,
             int bufferCount = BufferQueue::MIN_UNDEQUEUED_BUFFERS,
-            bool synchronousMode = false);
+            bool controlledByApp = false);
 
     virtual ~BufferItemConsumer();
 
@@ -71,7 +75,8 @@
     //
     // If waitForFence is true, and the acquired BufferItem has a valid fence object,
     // acquireBuffer will wait on the fence with no timeout before returning.
-    status_t acquireBuffer(BufferItem *item, bool waitForFence = true);
+    status_t acquireBuffer(BufferItem *item, nsecs_t presentWhen,
+        bool waitForFence = true);
 
     // Returns an acquired buffer to the queue, allowing it to be reused. Since
     // only a fixed number of buffers may be acquired at a time, old buffers
@@ -82,8 +87,6 @@
     status_t releaseBuffer(const BufferItem &item,
             const sp<Fence>& releaseFence = Fence::NO_FENCE);
 
-    sp<IGraphicBufferProducer> getProducerInterface() const { return getBufferQueue(); }
-
     // setDefaultBufferSize is used to set the size of buffers returned by
     // requestBuffers when a with and height of zero is requested.
     status_t setDefaultBufferSize(uint32_t w, uint32_t h);
diff --git a/include/gui/BufferQueue.h b/include/gui/BufferQueue.h
index 6c1b691..408956b 100644
--- a/include/gui/BufferQueue.h
+++ b/include/gui/BufferQueue.h
@@ -20,8 +20,12 @@
 #include <EGL/egl.h>
 #include <EGL/eglext.h>
 
+#include <binder/IBinder.h>
+
+#include <gui/IConsumerListener.h>
 #include <gui/IGraphicBufferAlloc.h>
 #include <gui/IGraphicBufferProducer.h>
+#include <gui/IGraphicBufferConsumer.h>
 
 #include <ui/Fence.h>
 #include <ui/GraphicBuffer.h>
@@ -33,43 +37,22 @@
 namespace android {
 // ----------------------------------------------------------------------------
 
-class BufferQueue : public BnGraphicBufferProducer {
+class BufferQueue : public BnGraphicBufferProducer,
+                    public BnGraphicBufferConsumer,
+                    private IBinder::DeathRecipient {
 public:
     enum { MIN_UNDEQUEUED_BUFFERS = 2 };
     enum { NUM_BUFFER_SLOTS = 32 };
     enum { NO_CONNECTED_API = 0 };
     enum { INVALID_BUFFER_SLOT = -1 };
-    enum { STALE_BUFFER_SLOT = 1, NO_BUFFER_AVAILABLE };
+    enum { STALE_BUFFER_SLOT = 1, NO_BUFFER_AVAILABLE, PRESENT_LATER };
 
     // When in async mode we reserve two slots in order to guarantee that the
     // producer and consumer can run asynchronously.
     enum { MAX_MAX_ACQUIRED_BUFFERS = NUM_BUFFER_SLOTS - 2 };
 
-    // ConsumerListener is the interface through which the BufferQueue notifies
-    // the consumer of events that the consumer may wish to react to.  Because
-    // the consumer will generally have a mutex that is locked during calls from
-    // the consumer to the BufferQueue, these calls from the BufferQueue to the
-    // consumer *MUST* be called only when the BufferQueue mutex is NOT locked.
-    struct ConsumerListener : public virtual RefBase {
-        // onFrameAvailable is called from queueBuffer each time an additional
-        // frame becomes available for consumption. This means that frames that
-        // are queued while in asynchronous mode only trigger the callback if no
-        // previous frames are pending. Frames queued while in synchronous mode
-        // always trigger the callback.
-        //
-        // This is called without any lock held and can be called concurrently
-        // by multiple threads.
-        virtual void onFrameAvailable() = 0;
-
-        // onBuffersReleased is called to notify the buffer consumer that the
-        // BufferQueue has released its references to one or more GraphicBuffers
-        // contained in its slots.  The buffer consumer should then call
-        // BufferQueue::getReleasedBuffers to retrieve the list of buffers
-        //
-        // This is called without any lock held and can be called concurrently
-        // by multiple threads.
-        virtual void onBuffersReleased() = 0;
-    };
+    // for backward source compatibility
+    typedef ::android::ConsumerListener ConsumerListener;
 
     // ProxyConsumerListener is a ConsumerListener implementation that keeps a weak
     // reference to the actual consumer object.  It forwards all calls to that
@@ -80,30 +63,35 @@
     // reference in the BufferQueue class is because we're planning to expose the
     // consumer side of a BufferQueue as a binder interface, which doesn't support
     // weak references.
-    class ProxyConsumerListener : public BufferQueue::ConsumerListener {
+    class ProxyConsumerListener : public BnConsumerListener {
     public:
-
-        ProxyConsumerListener(const wp<BufferQueue::ConsumerListener>& consumerListener);
+        ProxyConsumerListener(const wp<ConsumerListener>& consumerListener);
         virtual ~ProxyConsumerListener();
         virtual void onFrameAvailable();
         virtual void onBuffersReleased();
-
     private:
-
-        // mConsumerListener is a weak reference to the ConsumerListener.  This is
+        // mConsumerListener is a weak reference to the IConsumerListener.  This is
         // the raison d'etre of ProxyConsumerListener.
-        wp<BufferQueue::ConsumerListener> mConsumerListener;
+        wp<ConsumerListener> mConsumerListener;
     };
 
 
     // BufferQueue manages a pool of gralloc memory slots to be used by
-    // producers and consumers. allowSynchronousMode specifies whether or not
-    // synchronous mode can be enabled by the producer. allocator is used to
-    // allocate all the needed gralloc buffers.
-    BufferQueue(bool allowSynchronousMode = true,
-            const sp<IGraphicBufferAlloc>& allocator = NULL);
+    // producers and consumers. allocator is used to allocate all the
+    // needed gralloc buffers.
+    BufferQueue(const sp<IGraphicBufferAlloc>& allocator = NULL);
     virtual ~BufferQueue();
 
+    /*
+     * IBinder::DeathRecipient interface
+     */
+
+    virtual void binderDied(const wp<IBinder>& who);
+
+    /*
+     * IGraphicBufferProducer interface
+     */
+
     // Query native window attributes.  The "what" values are enumerated in
     // window.h (e.g. NATIVE_WINDOW_FORMAT).
     virtual int query(int what, int* value);
@@ -169,7 +157,7 @@
     //
     // In both cases, the producer will need to call requestBuffer to get a
     // GraphicBuffer handle for the returned slot.
-    virtual status_t dequeueBuffer(int *buf, sp<Fence>* fence,
+    virtual status_t dequeueBuffer(int *buf, sp<Fence>* fence, bool async,
             uint32_t width, uint32_t height, uint32_t format, uint32_t usage);
 
     // queueBuffer returns a filled buffer to the BufferQueue.
@@ -197,15 +185,6 @@
     // will usually be the one obtained from dequeueBuffer.
     virtual void cancelBuffer(int buf, const sp<Fence>& fence);
 
-    // setSynchronousMode sets whether dequeueBuffer is synchronous or
-    // asynchronous. In synchronous mode, dequeueBuffer blocks until
-    // a buffer is available, the currently bound buffer can be dequeued and
-    // queued buffers will be acquired in order.  In asynchronous mode,
-    // a queued buffer may be replaced by a subsequently queued buffer.
-    //
-    // The default mode is asynchronous.
-    virtual status_t setSynchronousMode(bool enabled);
-
     // connect attempts to connect a producer API to the BufferQueue.  This
     // must be called before any other IGraphicBufferProducer methods are
     // called except for getAllocator.  A consumer must already be connected.
@@ -215,7 +194,8 @@
     // it's still connected to a producer).
     //
     // APIs are enumerated in window.h (e.g. NATIVE_WINDOW_API_CPU).
-    virtual status_t connect(int api, QueueBufferOutput* output);
+    virtual status_t connect(const sp<IBinder>& token,
+            int api, bool producerControlledByApp, QueueBufferOutput* output);
 
     // disconnect attempts to disconnect a producer API from the BufferQueue.
     // Calling this method will cause any subsequent calls to other
@@ -227,51 +207,9 @@
     // connected to the specified producer API.
     virtual status_t disconnect(int api);
 
-    // dump our state in a String
-    virtual void dump(String8& result) const;
-    virtual void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
-
-    // public facing structure for BufferSlot
-    struct BufferItem {
-
-        BufferItem()
-         :
-           mTransform(0),
-           mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
-           mTimestamp(0),
-           mFrameNumber(0),
-           mBuf(INVALID_BUFFER_SLOT) {
-             mCrop.makeInvalid();
-        }
-        // mGraphicBuffer points to the buffer allocated for this slot, or is NULL
-        // if the buffer in this slot has been acquired in the past (see
-        // BufferSlot.mAcquireCalled).
-        sp<GraphicBuffer> mGraphicBuffer;
-
-        // mCrop is the current crop rectangle for this buffer slot.
-        Rect mCrop;
-
-        // mTransform is the current transform flags for this buffer slot.
-        uint32_t mTransform;
-
-        // mScalingMode is the current scaling mode for this buffer slot.
-        uint32_t mScalingMode;
-
-        // mTimestamp is the current timestamp for this buffer slot. This gets
-        // to set by queueBuffer each time this slot is queued.
-        int64_t mTimestamp;
-
-        // mFrameNumber is the number of the queued frame for this slot.
-        uint64_t mFrameNumber;
-
-        // mBuf is the slot index of this buffer
-        int mBuf;
-
-        // mFence is a fence that will signal when the buffer is idle.
-        sp<Fence> mFence;
-    };
-
-    // The following public functions are the consumer-facing interface
+    /*
+     * IGraphicBufferConsumer interface
+     */
 
     // acquireBuffer attempts to acquire ownership of the next pending buffer in
     // the BufferQueue.  If no buffer is pending then it returns -EINVAL.  If a
@@ -280,12 +218,18 @@
     // acquired then the BufferItem::mGraphicBuffer field of buffer is set to
     // NULL and it is assumed that the consumer still holds a reference to the
     // buffer.
-    status_t acquireBuffer(BufferItem *buffer);
+    //
+    // If presentWhen is nonzero, it indicates the time when the buffer will
+    // be displayed on screen.  If the buffer's timestamp is farther in the
+    // future, the buffer won't be acquired, and PRESENT_LATER will be
+    // returned.  The presentation time is in nanoseconds, and the time base
+    // is CLOCK_MONOTONIC.
+    virtual status_t acquireBuffer(BufferItem *buffer, nsecs_t presentWhen);
 
     // releaseBuffer releases a buffer slot from the consumer back to the
     // BufferQueue.  This may be done while the buffer's contents are still
     // being accessed.  The fence will signal when the buffer is no longer
-    // in use.
+    // in use. frameNumber is used to indentify the exact buffer returned.
     //
     // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
     // any references to the just-released buffer that it might have, as if it
@@ -294,34 +238,37 @@
     //
     // Note that the dependencies on EGL will be removed once we switch to using
     // the Android HW Sync HAL.
-    status_t releaseBuffer(int buf, EGLDisplay display, EGLSyncKHR fence,
+    virtual status_t releaseBuffer(int buf, uint64_t frameNumber,
+            EGLDisplay display, EGLSyncKHR fence,
             const sp<Fence>& releaseFence);
 
     // consumerConnect connects a consumer to the BufferQueue.  Only one
     // consumer may be connected, and when that consumer disconnects the
     // BufferQueue is placed into the "abandoned" state, causing most
     // interactions with the BufferQueue by the producer to fail.
+    // controlledByApp indicates whether the consumer is controlled by
+    // the application.
     //
     // consumer may not be NULL.
-    status_t consumerConnect(const sp<ConsumerListener>& consumer);
+    virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp);
 
     // consumerDisconnect disconnects a consumer from the BufferQueue. All
     // buffers will be freed and the BufferQueue is placed in the "abandoned"
     // state, causing most interactions with the BufferQueue by the producer to
     // fail.
-    status_t consumerDisconnect();
+    virtual status_t consumerDisconnect();
 
     // getReleasedBuffers sets the value pointed to by slotMask to a bit mask
     // indicating which buffer slots have been released by the BufferQueue
     // but have not yet been released by the consumer.
     //
     // This should be called from the onBuffersReleased() callback.
-    status_t getReleasedBuffers(uint32_t* slotMask);
+    virtual status_t getReleasedBuffers(uint32_t* slotMask);
 
     // setDefaultBufferSize is used to set the size of buffers returned by
     // dequeueBuffer when a width and height of zero is requested.  Default
     // is 1x1.
-    status_t setDefaultBufferSize(uint32_t w, uint32_t h);
+    virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h);
 
     // setDefaultMaxBufferCount sets the default value for the maximum buffer
     // count (the initial default is 2). If the producer has requested a
@@ -329,35 +276,42 @@
     // take effect if the producer sets the count back to zero.
     //
     // The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
-    status_t setDefaultMaxBufferCount(int bufferCount);
+    virtual status_t setDefaultMaxBufferCount(int bufferCount);
+
+    // disableAsyncBuffer disables the extra buffer used in async mode
+    // (when both producer and consumer have set their "isControlledByApp"
+    // flag) and has dequeueBuffer() return WOULD_BLOCK instead.
+    //
+    // This can only be called before consumerConnect().
+    virtual status_t disableAsyncBuffer();
 
     // setMaxAcquiredBufferCount sets the maximum number of buffers that can
     // be acquired by the consumer at one time (default 1).  This call will
     // fail if a producer is connected to the BufferQueue.
-    status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers);
-
-    // isSynchronousMode returns whether the BufferQueue is currently in
-    // synchronous mode.
-    bool isSynchronousMode() const;
+    virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers);
 
     // setConsumerName sets the name used in logging
-    void setConsumerName(const String8& name);
+    virtual void setConsumerName(const String8& name);
 
     // setDefaultBufferFormat allows the BufferQueue to create
     // GraphicBuffers of a defaultFormat if no format is specified
     // in dequeueBuffer.  Formats are enumerated in graphics.h; the
     // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
-    status_t setDefaultBufferFormat(uint32_t defaultFormat);
+    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat);
 
     // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
     // These are merged with the bits passed to dequeueBuffer.  The values are
     // enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
-    status_t setConsumerUsageBits(uint32_t usage);
+    virtual status_t setConsumerUsageBits(uint32_t usage);
 
     // setTransformHint bakes in rotation to buffers so overlays can be used.
     // The values are enumerated in window.h, e.g.
     // NATIVE_WINDOW_TRANSFORM_ROT_90.  The default is 0 (no transform).
-    status_t setTransformHint(uint32_t hint);
+    virtual status_t setTransformHint(uint32_t hint);
+
+    // dump our state in a String
+    virtual void dump(String8& result, const char* prefix) const;
+
 
 private:
     // freeBufferLocked frees the GraphicBuffer and sync resources for the
@@ -368,47 +322,39 @@
     // all slots.
     void freeAllBuffersLocked();
 
-    // freeAllBuffersExceptHeadLocked frees the GraphicBuffer and sync
-    // resources for all slots except the head of mQueue.
-    void freeAllBuffersExceptHeadLocked();
-
-    // drainQueueLocked waits for the buffer queue to empty if we're in
-    // synchronous mode, or returns immediately otherwise. It returns NO_INIT
-    // if the BufferQueue is abandoned (consumer disconnected) or disconnected
-    // (producer disconnected) during the call.
-    status_t drainQueueLocked();
-
-    // drainQueueAndFreeBuffersLocked drains the buffer queue if we're in
-    // synchronous mode and free all buffers. In asynchronous mode, all buffers
-    // are freed except the currently queued buffer (if it exists).
-    status_t drainQueueAndFreeBuffersLocked();
-
     // setDefaultMaxBufferCountLocked sets the maximum number of buffer slots
     // that will be used if the producer does not override the buffer slot
     // count.  The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
     // The initial default is 2.
     status_t setDefaultMaxBufferCountLocked(int count);
 
+    // getMinUndequeuedBufferCount returns the minimum number of buffers
+    // that must remain in a state other than DEQUEUED.
+    // The async parameter tells whether we're in asynchronous mode.
+    int getMinUndequeuedBufferCount(bool async) const;
+
     // getMinBufferCountLocked returns the minimum number of buffers allowed
     // given the current BufferQueue state.
-    int getMinMaxBufferCountLocked() const;
-
-    // getMinUndequeuedBufferCountLocked returns the minimum number of buffers
-    // that must remain in a state other than DEQUEUED.
-    int getMinUndequeuedBufferCountLocked() const;
+    // The async parameter tells whether we're in asynchronous mode.
+    int getMinMaxBufferCountLocked(bool async) const;
 
     // getMaxBufferCountLocked returns the maximum number of buffers that can
     // be allocated at once.  This value depends upon the following member
     // variables:
     //
-    //      mSynchronousMode
+    //      mDequeueBufferCannotBlock
     //      mMaxAcquiredBufferCount
     //      mDefaultMaxBufferCount
     //      mOverrideMaxBufferCount
+    //      async parameter
     //
     // Any time one of these member variables is changed while a producer is
     // connected, mDequeueCondition must be broadcast.
-    int getMaxBufferCountLocked() const;
+    int getMaxBufferCountLocked(bool async) const;
+
+    // stillTracking returns true iff the buffer item is still being tracked
+    // in one of the slots.
+    bool stillTracking(const BufferItem *item) const;
 
     struct BufferSlot {
 
@@ -416,14 +362,10 @@
         : mEglDisplay(EGL_NO_DISPLAY),
           mBufferState(BufferSlot::FREE),
           mRequestBufferCalled(false),
-          mTransform(0),
-          mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
-          mTimestamp(0),
           mFrameNumber(0),
           mEglFence(EGL_NO_SYNC_KHR),
           mAcquireCalled(false),
           mNeedsCleanupOnRelease(false) {
-            mCrop.makeInvalid();
         }
 
         // mGraphicBuffer points to the buffer allocated for this slot or is NULL
@@ -482,21 +424,6 @@
         // needed but useful for debugging and catching producer bugs.
         bool mRequestBufferCalled;
 
-        // mCrop is the current crop rectangle for this buffer slot.
-        Rect mCrop;
-
-        // mTransform is the current transform flags for this buffer slot.
-        // (example: NATIVE_WINDOW_TRANSFORM_ROT_90)
-        uint32_t mTransform;
-
-        // mScalingMode is the current scaling mode for this buffer slot.
-        // (example: NATIVE_WINDOW_SCALING_MODE_FREEZE)
-        uint32_t mScalingMode;
-
-        // mTimestamp is the current timestamp for this buffer slot. This gets
-        // to set by queueBuffer each time this slot is queued.
-        int64_t mTimestamp;
-
         // mFrameNumber is the number of the queued frame for this slot.  This
         // is used to dequeue buffers in LRU order (useful because buffers
         // may be released before their release fence is signaled).
@@ -574,14 +501,20 @@
     // mConsumerListener is used to notify the connected consumer of
     // asynchronous events that it may wish to react to.  It is initially set
     // to NULL and is written by consumerConnect and consumerDisconnect.
-    sp<ConsumerListener> mConsumerListener;
+    sp<IConsumerListener> mConsumerListener;
 
-    // mSynchronousMode whether we're in synchronous mode or not
-    bool mSynchronousMode;
+    // mConsumerControlledByApp whether the connected consumer is controlled by the
+    // application.
+    bool mConsumerControlledByApp;
 
-    // mAllowSynchronousMode whether we allow synchronous mode or not.  Set
-    // when the BufferQueue is created (by the consumer).
-    const bool mAllowSynchronousMode;
+    // mDequeueBufferCannotBlock whether dequeueBuffer() isn't allowed to block.
+    // this flag is set during connect() when both consumer and producer are controlled
+    // by the application.
+    bool mDequeueBufferCannotBlock;
+
+    // mUseAsyncBuffer whether an extra buffer is used in async mode to prevent
+    // dequeueBuffer() from ever blocking.
+    bool mUseAsyncBuffer;
 
     // mConnectedApi indicates the producer API that is currently connected
     // to this BufferQueue.  It defaults to NO_CONNECTED_API (= 0), and gets
@@ -592,7 +525,7 @@
     mutable Condition mDequeueCondition;
 
     // mQueue is a FIFO of queued buffers used in synchronous mode
-    typedef Vector<int> Fifo;
+    typedef Vector<BufferItem> Fifo;
     Fifo mQueue;
 
     // mAbandoned indicates that the BufferQueue will no longer be used to
@@ -613,7 +546,7 @@
     mutable Mutex mMutex;
 
     // mFrameCounter is the free running counter, incremented on every
-    // successful queueBuffer call.
+    // successful queueBuffer call, and buffer allocation.
     uint64_t mFrameCounter;
 
     // mBufferHasBeenQueued is true once a buffer has been queued.  It is
@@ -630,6 +563,9 @@
 
     // mTransformHint is used to optimize for screen rotations
     uint32_t mTransformHint;
+
+    // mConnectedProducerToken is used to set a binder death notification on the producer
+    sp<IBinder> mConnectedProducerToken;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/ConsumerBase.h b/include/gui/ConsumerBase.h
index 8a7545d..fb21185 100644
--- a/include/gui/ConsumerBase.h
+++ b/include/gui/ConsumerBase.h
@@ -24,6 +24,7 @@
 #include <utils/String8.h>
 #include <utils/Vector.h>
 #include <utils/threads.h>
+#include <gui/IConsumerListener.h>
 
 namespace android {
 // ----------------------------------------------------------------------------
@@ -34,7 +35,7 @@
 // handles common tasks like management of the connection to the BufferQueue
 // and the buffer pool.
 class ConsumerBase : public virtual RefBase,
-        protected BufferQueue::ConsumerListener {
+        protected ConsumerListener {
 public:
     struct FrameAvailableListener : public virtual RefBase {
         // onFrameAvailable() is called each time an additional frame becomes
@@ -65,15 +66,11 @@
     // log messages.
     void setName(const String8& name);
 
-    // getBufferQueue returns the BufferQueue object to which this
-    // ConsumerBase is connected.
-    sp<BufferQueue> getBufferQueue() const;
-
     // dump writes the current state to a string. Child classes should add
     // their state to the dump by overriding the dumpLocked method, which is
     // called by these methods after locking the mutex.
     void dump(String8& result) const;
-    void dump(String8& result, const char* prefix, char* buffer, size_t SIZE) const;
+    void dump(String8& result, const char* prefix) const;
 
     // setFrameAvailableListener sets the listener object that will be notified
     // when a new frame becomes available.
@@ -84,10 +81,11 @@
     void operator=(const ConsumerBase&);
 
 protected:
-
     // ConsumerBase constructs a new ConsumerBase object to consume image
-    // buffers from the given BufferQueue.
-    ConsumerBase(const sp<BufferQueue> &bufferQueue);
+    // buffers from the given IGraphicBufferConsumer.
+    // The controlledByApp flag indicates that this consumer is under the application's
+    // control.
+    ConsumerBase(const sp<IGraphicBufferConsumer>& consumer, bool controlledByApp = false);
 
     // onLastStrongRef gets called by RefBase just before the dtor of the most
     // derived class.  It is used to clean up the buffers so that ConsumerBase
@@ -101,7 +99,7 @@
     // from the derived class.
     virtual void onLastStrongRef(const void* id);
 
-    // Implementation of the BufferQueue::ConsumerListener interface.  These
+    // Implementation of the IConsumerListener interface.  These
     // calls are used to notify the ConsumerBase of asynchronous events in the
     // BufferQueue.  These methods should not need to be overridden by derived
     // classes, but if they are overridden the ConsumerBase implementation
@@ -143,8 +141,7 @@
     // should call ConsumerBase::dumpLocked.
     //
     // This method must be called with mMutex locked.
-    virtual void dumpLocked(String8& result, const char* prefix, char* buffer,
-            size_t size) const;
+    virtual void dumpLocked(String8& result, const char* prefix) const;
 
     // acquireBufferLocked fetches the next buffer from the BufferQueue and
     // updates the buffer slot for the buffer returned.
@@ -153,7 +150,8 @@
     // initialization that must take place the first time a buffer is assigned
     // to a slot.  If it is overridden the derived class's implementation must
     // call ConsumerBase::acquireBufferLocked.
-    virtual status_t acquireBufferLocked(BufferQueue::BufferItem *item);
+    virtual status_t acquireBufferLocked(IGraphicBufferConsumer::BufferItem *item,
+        nsecs_t presentWhen);
 
     // releaseBufferLocked relinquishes control over a buffer, returning that
     // control to the BufferQueue.
@@ -161,17 +159,23 @@
     // Derived classes should override this method to perform any cleanup that
     // must take place when a buffer is released back to the BufferQueue.  If
     // it is overridden the derived class's implementation must call
-    // ConsumerBase::releaseBufferLocked.
-    virtual status_t releaseBufferLocked(int buf, EGLDisplay display,
-           EGLSyncKHR eglFence);
+    // ConsumerBase::releaseBufferLocked.e
+    virtual status_t releaseBufferLocked(int slot,
+            const sp<GraphicBuffer> graphicBuffer,
+            EGLDisplay display, EGLSyncKHR eglFence);
+
+    // returns true iff the slot still has the graphicBuffer in it.
+    bool stillTracking(int slot, const sp<GraphicBuffer> graphicBuffer);
 
     // addReleaseFence* adds the sync points associated with a fence to the set
     // of sync points that must be reached before the buffer in the given slot
     // may be used after the slot has been released.  This should be called by
     // derived classes each time some asynchronous work is kicked off that
     // references the buffer.
-    status_t addReleaseFence(int slot, const sp<Fence>& fence);
-    status_t addReleaseFenceLocked(int slot, const sp<Fence>& fence);
+    status_t addReleaseFence(int slot,
+            const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence);
+    status_t addReleaseFenceLocked(int slot,
+            const sp<GraphicBuffer> graphicBuffer, const sp<Fence>& fence);
 
     // Slot contains the information and object references that
     // ConsumerBase maintains about a BufferQueue buffer slot.
@@ -185,6 +189,9 @@
         // overwritten. The buffer can be dequeued before the fence signals;
         // the producer is responsible for delaying writes until it signals.
         sp<Fence> mFence;
+
+        // the frame number of the last acquired frame for this slot
+        uint64_t mFrameNumber;
     };
 
     // mSlots stores the buffers that have been allocated by the BufferQueue
@@ -214,7 +221,7 @@
 
     // The ConsumerBase has-a BufferQueue and is responsible for creating this object
     // if none is supplied
-    sp<BufferQueue> mBufferQueue;
+    sp<IGraphicBufferConsumer> mConsumer;
 
     // mMutex is the mutex used to prevent concurrent access to the member
     // variables of ConsumerBase objects. It must be locked whenever the
diff --git a/include/gui/CpuConsumer.h b/include/gui/CpuConsumer.h
index bf9918e..6f4c2ec 100644
--- a/include/gui/CpuConsumer.h
+++ b/include/gui/CpuConsumer.h
@@ -25,10 +25,11 @@
 #include <utils/Vector.h>
 #include <utils/threads.h>
 
-#define ANDROID_GRAPHICS_CPUCONSUMER_JNI_ID "mCpuConsumer"
 
 namespace android {
 
+class BufferQueue;
+
 /**
  * CpuConsumer is a BufferQueue consumer endpoint that allows direct CPU
  * access to the underlying gralloc buffers provided by BufferQueue. Multiple
@@ -65,7 +66,8 @@
 
     // Create a new CPU consumer. The maxLockedBuffers parameter specifies
     // how many buffers can be locked for user access at the same time.
-    CpuConsumer(uint32_t maxLockedBuffers, bool synchronousMode = true);
+    CpuConsumer(const sp<IGraphicBufferConsumer>& bq,
+            uint32_t maxLockedBuffers, bool controlledByApp = false);
 
     virtual ~CpuConsumer();
 
@@ -73,10 +75,22 @@
     // log messages.
     void setName(const String8& name);
 
+    // setDefaultBufferSize is used to set the size of buffers returned by
+    // requestBuffers when a width and height of zero is requested.
+    // A call to setDefaultBufferSize() may trigger requestBuffers() to
+    // be called from the client. Default size is 1x1.
+    status_t setDefaultBufferSize(uint32_t width, uint32_t height);
+
+    // setDefaultBufferFormat allows CpuConsumer's BufferQueue to create buffers
+    // of a defaultFormat if no format is specified by producer. Formats are
+    // enumerated in graphics.h; the initial default is
+    // HAL_PIXEL_FORMAT_RGBA_8888.
+    status_t setDefaultBufferFormat(uint32_t defaultFormat);
+
     // Gets the next graphics buffer from the producer and locks it for CPU use,
     // filling out the passed-in locked buffer structure with the native pointer
     // and metadata. Returns BAD_VALUE if no new buffer is available, and
-    // INVALID_OPERATION if the maximum number of buffers is already locked.
+    // NOT_ENOUGH_DATA if the maximum number of buffers is already locked.
     //
     // Only a fixed number of buffers can be locked at a time, determined by the
     // construction-time maxLockedBuffers parameter. If INVALID_OPERATION is
@@ -90,8 +104,6 @@
     // lockNextBuffer.
     status_t unlockBuffer(const LockedBuffer &nativeBuffer);
 
-    sp<IGraphicBufferProducer> getProducerInterface() const { return getBufferQueue(); }
-
   private:
     // Maximum number of buffers that can be locked at a time
     uint32_t mMaxLockedBuffers;
diff --git a/include/gui/DummyConsumer.h b/include/gui/DummyConsumer.h
deleted file mode 100644
index 08e8ec8..0000000
--- a/include/gui/DummyConsumer.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2012 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_GUI_DUMMYCONSUMER_H
-#define ANDROID_GUI_DUMMYCONSUMER_H
-
-#include <gui/BufferQueue.h>
-
-namespace android {
-// ----------------------------------------------------------------------------
-
-
-// The DummyConsumer does not keep a reference to BufferQueue
-// unlike GLConsumer.  This prevents a circular reference from
-// forming without having to use a ProxyConsumerListener
-class DummyConsumer : public BufferQueue::ConsumerListener {
-public:
-    DummyConsumer();
-    virtual ~DummyConsumer();
-protected:
-
-    // Implementation of the BufferQueue::ConsumerListener interface.  These
-    // calls are used to notify the GLConsumer of asynchronous events in the
-    // BufferQueue.
-    virtual void onFrameAvailable();
-    virtual void onBuffersReleased();
-
-};
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-
-#endif // ANDROID_GUI_DUMMYCONSUMER_H
diff --git a/include/gui/GLConsumer.h b/include/gui/GLConsumer.h
index 1ef54f5..a5fdfb9 100644
--- a/include/gui/GLConsumer.h
+++ b/include/gui/GLConsumer.h
@@ -19,8 +19,6 @@
 
 #include <EGL/egl.h>
 #include <EGL/eglext.h>
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
 
 #include <gui/IGraphicBufferProducer.h>
 #include <gui/BufferQueue.h>
@@ -32,10 +30,6 @@
 #include <utils/Vector.h>
 #include <utils/threads.h>
 
-#define ANDROID_GRAPHICS_SURFACETEXTURE_JNI_ID "mSurfaceTexture"
-#define ANDROID_GRAPHICS_FRAMEAVAILABLELISTENER_JNI_ID \
-                                         "mFrameAvailableListener"
-
 namespace android {
 // ----------------------------------------------------------------------------
 
@@ -58,6 +52,8 @@
  * This class was previously called SurfaceTexture.
  */
 class GLConsumer : public ConsumerBase {
+protected:
+    enum { TEXTURE_EXTERNAL = 0x8D65 }; // GL_TEXTURE_EXTERNAL_OES
 public:
     typedef ConsumerBase::FrameAvailableListener FrameAvailableListener;
 
@@ -85,12 +81,9 @@
     // purely to allow a GLConsumer to be transferred from one consumer
     // context to another. If such a transfer is not needed there is no
     // requirement that either of these methods be called.
-    GLConsumer(const sp<BufferQueue>& bq,
-            GLuint tex, GLenum texTarget = GL_TEXTURE_EXTERNAL_OES,
-            bool useFenceSync = true);
-    GLConsumer(GLuint tex, bool allowSynchronousMode = true,
-            GLenum texTarget = GL_TEXTURE_EXTERNAL_OES, bool useFenceSync = true,
-            const sp<BufferQueue> &bufferQueue = 0);
+    GLConsumer(const sp<IGraphicBufferConsumer>& bq,
+            uint32_t tex, uint32_t texureTarget = TEXTURE_EXTERNAL,
+            bool useFenceSync = true, bool isControlledByApp = false);
 
     // updateTexImage acquires the most recently queued buffer, and sets the
     // image contents of the target texture to it.
@@ -101,6 +94,13 @@
     // This calls doGLFenceWait to ensure proper synchronization.
     status_t updateTexImage();
 
+    // releaseTexImage releases the texture acquired in updateTexImage().
+    // This is intended to be used in single buffer mode.
+    //
+    // This call may only be made while the OpenGL ES context to which the
+    // target texture belongs is bound to the calling thread.
+    status_t releaseTexImage();
+
     // setReleaseFence stores a fence that will signal when the current buffer
     // is no longer being read. This fence will be returned to the producer
     // when the current buffer is released by updateTexImage(). Multiple
@@ -141,6 +141,13 @@
     // documented by the source.
     int64_t getTimestamp();
 
+    // getFrameNumber retrieves the frame number associated with the texture
+    // image set by the most recent call to updateTexImage.
+    //
+    // The frame number is an incrementing counter set to 0 at the creation of
+    // the BufferQueue associated with this consumer.
+    int64_t getFrameNumber();
+
     // setDefaultBufferSize is used to set the size of buffers returned by
     // requestBuffers when a with and height of zero is requested.
     // A call to setDefaultBufferSize() may trigger requestBuffers() to
@@ -160,7 +167,7 @@
 
     // getCurrentTextureTarget returns the texture target of the current
     // texture as returned by updateTexImage().
-    GLenum getCurrentTextureTarget() const;
+    uint32_t getCurrentTextureTarget() const;
 
     // getCurrentCrop returns the cropping rectangle of the current buffer.
     Rect getCurrentCrop() const;
@@ -180,10 +187,6 @@
     // current texture buffer.
     status_t doGLFenceWait() const;
 
-    // isSynchronousMode returns whether the GLConsumer is currently in
-    // synchronous mode.
-    bool isSynchronousMode() const;
-
     // set the name of the GLConsumer that will be used to identify it in
     // log messages.
     void setName(const String8& name);
@@ -193,13 +196,6 @@
     status_t setDefaultBufferFormat(uint32_t defaultFormat);
     status_t setConsumerUsageBits(uint32_t usage);
     status_t setTransformHint(uint32_t hint);
-    virtual status_t setSynchronousMode(bool enabled);
-
-    // getBufferQueue returns the BufferQueue object to which this
-    // GLConsumer is connected.
-    sp<BufferQueue> getBufferQueue() const {
-        return mBufferQueue;
-    }
 
     // detachFromContext detaches the GLConsumer from the calling thread's
     // current OpenGL ES context.  This context must be the same as the context
@@ -226,7 +222,7 @@
     // call to attachToContext will result in this texture object being bound to
     // the texture target and populated with the image contents that were
     // current at the time of the last call to detachFromContext.
-    status_t attachToContext(GLuint tex);
+    status_t attachToContext(uint32_t tex);
 
 protected:
 
@@ -236,20 +232,22 @@
 
     // dumpLocked overrides the ConsumerBase method to dump GLConsumer-
     // specific info in addition to the ConsumerBase behavior.
-    virtual void dumpLocked(String8& result, const char* prefix, char* buffer,
-           size_t size) const;
+    virtual void dumpLocked(String8& result, const char* prefix) const;
 
     // acquireBufferLocked overrides the ConsumerBase method to update the
     // mEglSlots array in addition to the ConsumerBase behavior.
-    virtual status_t acquireBufferLocked(BufferQueue::BufferItem *item);
+    virtual status_t acquireBufferLocked(BufferQueue::BufferItem *item,
+        nsecs_t presentWhen);
 
     // releaseBufferLocked overrides the ConsumerBase method to update the
     // mEglSlots array in addition to the ConsumerBase.
-    virtual status_t releaseBufferLocked(int buf, EGLDisplay display,
-           EGLSyncKHR eglFence);
+    virtual status_t releaseBufferLocked(int slot,
+            const sp<GraphicBuffer> graphicBuffer,
+            EGLDisplay display, EGLSyncKHR eglFence);
 
-    status_t releaseBufferLocked(int buf, EGLSyncKHR eglFence) {
-        return releaseBufferLocked(buf, mEglDisplay, eglFence);
+    status_t releaseBufferLocked(int slot,
+            const sp<GraphicBuffer> graphicBuffer, EGLSyncKHR eglFence) {
+        return releaseBufferLocked(slot, graphicBuffer, mEglDisplay, eglFence);
     }
 
     static bool isExternalFormat(uint32_t format);
@@ -257,7 +255,7 @@
     // This releases the buffer in the slot referenced by mCurrentTexture,
     // then updates state to refer to the BufferItem, which must be a
     // newly-acquired buffer.
-    status_t releaseAndUpdateLocked(const BufferQueue::BufferItem& item);
+    status_t updateAndReleaseLocked(const BufferQueue::BufferItem& item);
 
     // Binds mTexName and the current buffer to mTexTarget.  Uses
     // mCurrentTexture if it's set, mCurrentTextureBuf if not.  If the
@@ -268,12 +266,14 @@
     // to mEglDisplay and mEglContext.  If the fields have been previously
     // set, the values must match; if not, the fields are set to the current
     // values.
-    status_t checkAndUpdateEglStateLocked();
+    // The contextCheck argument is used to ensure that a GL context is
+    // properly set; when set to false, the check is not performed.
+    status_t checkAndUpdateEglStateLocked(bool contextCheck = false);
 
 private:
     // createImage creates a new EGLImage from a GraphicBuffer.
     EGLImageKHR createImage(EGLDisplay dpy,
-            const sp<GraphicBuffer>& graphicBuffer);
+            const sp<GraphicBuffer>& graphicBuffer, const Rect& crop);
 
     // freeBufferLocked frees up the given buffer slot.  If the slot has been
     // initialized this will release the reference to the GraphicBuffer in that
@@ -306,6 +306,9 @@
     // binding the buffer without touching the EglSlots.
     status_t bindUnslottedBufferLocked(EGLDisplay dpy);
 
+    // returns a graphic buffer used when the texture image has been released
+    static sp<GraphicBuffer> getDebugTexImageBuffer();
+
     // The default consumer usage flags that GLConsumer always sets on its
     // BufferQueue instance; these will be OR:d with any additional flags passed
     // from the GLConsumer user. In particular, GLConsumer will always
@@ -341,6 +344,10 @@
     // gets set each time updateTexImage is called.
     int64_t mCurrentTimestamp;
 
+    // mCurrentFrameNumber is the frame counter for the current texture.
+    // It gets set each time updateTexImage is called.
+    int64_t mCurrentFrameNumber;
+
     uint32_t mDefaultWidth, mDefaultHeight;
 
     // mFilteringEnabled indicates whether the transform matrix is computed for
@@ -351,7 +358,7 @@
     // mTexName is the name of the OpenGL texture to which streamed images will
     // be bound when updateTexImage is called. It is set at construction time
     // and can be changed with a call to attachToContext.
-    GLuint mTexName;
+    uint32_t mTexName;
 
     // mUseFenceSync indicates whether creation of the EGL_KHR_fence_sync
     // extension should be used to prevent buffers from being dequeued before
@@ -366,7 +373,7 @@
     // glCopyTexSubImage to read from the texture.  This is a hack to work
     // around a GL driver limitation on the number of FBO attachments, which the
     // browser's tile cache exceeds.
-    const GLenum mTexTarget;
+    const uint32_t mTexTarget;
 
     // EGLSlot contains the information and object references that
     // GLConsumer maintains about a BufferQueue buffer slot.
@@ -379,6 +386,10 @@
         // mEglImage is the EGLImage created from mGraphicBuffer.
         EGLImageKHR mEglImage;
 
+        // mCropRect is the crop rectangle passed to EGL when mEglImage was
+        // created.
+        Rect mCropRect;
+
         // mFence is the EGL sync object that must signal before the buffer
         // associated with this buffer slot may be dequeued. It is initialized
         // to EGL_NO_SYNC_KHR when the buffer is created and (optionally, based
@@ -422,6 +433,13 @@
     // It is set to false by detachFromContext, and then set to true again by
     // attachToContext.
     bool mAttached;
+
+    // protects static initialization
+    static Mutex sStaticInitLock;
+
+    // mReleasedTexImageBuffer is a dummy buffer used when in single buffer
+    // mode and releaseTexImage() has been called
+    static sp<GraphicBuffer> sReleasedTexImageBuffer;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/IConsumerListener.h b/include/gui/IConsumerListener.h
new file mode 100644
index 0000000..ac2f9bb
--- /dev/null
+++ b/include/gui/IConsumerListener.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2013 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_GUI_ICONSUMERLISTENER_H
+#define ANDROID_GUI_ICONSUMERLISTENER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+
+#include <binder/IInterface.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+// ConsumerListener is the interface through which the BufferQueue notifies
+// the consumer of events that the consumer may wish to react to.  Because
+// the consumer will generally have a mutex that is locked during calls from
+// the consumer to the BufferQueue, these calls from the BufferQueue to the
+// consumer *MUST* be called only when the BufferQueue mutex is NOT locked.
+
+class ConsumerListener : public virtual RefBase {
+public:
+    ConsumerListener() { }
+    virtual ~ConsumerListener() { }
+
+    // onFrameAvailable is called from queueBuffer each time an additional
+    // frame becomes available for consumption. This means that frames that
+    // are queued while in asynchronous mode only trigger the callback if no
+    // previous frames are pending. Frames queued while in synchronous mode
+    // always trigger the callback.
+    //
+    // This is called without any lock held and can be called concurrently
+    // by multiple threads.
+    virtual void onFrameAvailable() = 0; /* Asynchronous */
+
+    // onBuffersReleased is called to notify the buffer consumer that the
+    // BufferQueue has released its references to one or more GraphicBuffers
+    // contained in its slots.  The buffer consumer should then call
+    // BufferQueue::getReleasedBuffers to retrieve the list of buffers
+    //
+    // This is called without any lock held and can be called concurrently
+    // by multiple threads.
+    virtual void onBuffersReleased() = 0; /* Asynchronous */
+};
+
+
+class IConsumerListener : public ConsumerListener, public IInterface
+{
+public:
+    DECLARE_META_INTERFACE(ConsumerListener);
+};
+
+// ----------------------------------------------------------------------------
+
+class BnConsumerListener : public BnInterface<IConsumerListener>
+{
+public:
+    virtual status_t    onTransact( uint32_t code,
+                                    const Parcel& data,
+                                    Parcel* reply,
+                                    uint32_t flags = 0);
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_GUI_ICONSUMERLISTENER_H
diff --git a/include/gui/IGraphicBufferConsumer.h b/include/gui/IGraphicBufferConsumer.h
new file mode 100644
index 0000000..0e35f13
--- /dev/null
+++ b/include/gui/IGraphicBufferConsumer.h
@@ -0,0 +1,220 @@
+/*
+ * Copyright (C) 2013 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_GUI_IGRAPHICBUFFERCONSUMER_H
+#define ANDROID_GUI_IGRAPHICBUFFERCONSUMER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+#include <utils/Timers.h>
+
+#include <binder/IInterface.h>
+#include <ui/Rect.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+class IConsumerListener;
+class GraphicBuffer;
+class Fence;
+
+class IGraphicBufferConsumer : public IInterface {
+
+public:
+
+    // public facing structure for BufferSlot
+    class BufferItem : public Flattenable<BufferItem> {
+        friend class Flattenable<BufferItem>;
+        size_t getPodSize() const;
+        size_t getFlattenedSize() const;
+        size_t getFdCount() const;
+        status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
+        status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
+
+    public:
+        enum { INVALID_BUFFER_SLOT = -1 };
+        BufferItem();
+
+        // mGraphicBuffer points to the buffer allocated for this slot, or is NULL
+        // if the buffer in this slot has been acquired in the past (see
+        // BufferSlot.mAcquireCalled).
+        sp<GraphicBuffer> mGraphicBuffer;
+
+        // mFence is a fence that will signal when the buffer is idle.
+        sp<Fence> mFence;
+
+        // mCrop is the current crop rectangle for this buffer slot.
+        Rect mCrop;
+
+        // mTransform is the current transform flags for this buffer slot.
+        uint32_t mTransform;
+
+        // mScalingMode is the current scaling mode for this buffer slot.
+        uint32_t mScalingMode;
+
+        // mTimestamp is the current timestamp for this buffer slot. This gets
+        // to set by queueBuffer each time this slot is queued.
+        int64_t mTimestamp;
+
+        // mIsAutoTimestamp indicates whether mTimestamp was generated
+        // automatically when the buffer was queued.
+        bool mIsAutoTimestamp;
+
+        // mFrameNumber is the number of the queued frame for this slot.
+        uint64_t mFrameNumber;
+
+        // mBuf is the slot index of this buffer
+        int mBuf;
+
+        // mIsDroppable whether this buffer was queued with the
+        // property that it can be replaced by a new buffer for the purpose of
+        // making sure dequeueBuffer() won't block.
+        // i.e.: was the BufferQueue in "mDequeueBufferCannotBlock" when this buffer
+        // was queued.
+        bool mIsDroppable;
+
+        // Indicates whether this buffer has been seen by a consumer yet
+        bool mAcquireCalled;
+
+        // Indicates this buffer must be transformed by the inverse transform of the screen
+        // it is displayed onto. This is applied after mTransform.
+        bool mTransformToDisplayInverse;
+    };
+
+
+    // acquireBuffer attempts to acquire ownership of the next pending buffer in
+    // the BufferQueue.  If no buffer is pending then it returns -EINVAL.  If a
+    // buffer is successfully acquired, the information about the buffer is
+    // returned in BufferItem.  If the buffer returned had previously been
+    // acquired then the BufferItem::mGraphicBuffer field of buffer is set to
+    // NULL and it is assumed that the consumer still holds a reference to the
+    // buffer.
+    //
+    // If presentWhen is nonzero, it indicates the time when the buffer will
+    // be displayed on screen.  If the buffer's timestamp is farther in the
+    // future, the buffer won't be acquired, and PRESENT_LATER will be
+    // returned.  The presentation time is in nanoseconds, and the time base
+    // is CLOCK_MONOTONIC.
+    virtual status_t acquireBuffer(BufferItem *buffer, nsecs_t presentWhen) = 0;
+
+    // releaseBuffer releases a buffer slot from the consumer back to the
+    // BufferQueue.  This may be done while the buffer's contents are still
+    // being accessed.  The fence will signal when the buffer is no longer
+    // in use. frameNumber is used to indentify the exact buffer returned.
+    //
+    // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
+    // any references to the just-released buffer that it might have, as if it
+    // had received a onBuffersReleased() call with a mask set for the released
+    // buffer.
+    //
+    // Note that the dependencies on EGL will be removed once we switch to using
+    // the Android HW Sync HAL.
+    virtual status_t releaseBuffer(int buf, uint64_t frameNumber,
+            EGLDisplay display, EGLSyncKHR fence,
+            const sp<Fence>& releaseFence) = 0;
+
+    // consumerConnect connects a consumer to the BufferQueue.  Only one
+    // consumer may be connected, and when that consumer disconnects the
+    // BufferQueue is placed into the "abandoned" state, causing most
+    // interactions with the BufferQueue by the producer to fail.
+    // controlledByApp indicates whether the consumer is controlled by
+    // the application.
+    //
+    // consumer may not be NULL.
+    virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp) = 0;
+
+    // consumerDisconnect disconnects a consumer from the BufferQueue. All
+    // buffers will be freed and the BufferQueue is placed in the "abandoned"
+    // state, causing most interactions with the BufferQueue by the producer to
+    // fail.
+    virtual status_t consumerDisconnect() = 0;
+
+    // getReleasedBuffers sets the value pointed to by slotMask to a bit mask
+    // indicating which buffer slots have been released by the BufferQueue
+    // but have not yet been released by the consumer.
+    //
+    // This should be called from the onBuffersReleased() callback.
+    virtual status_t getReleasedBuffers(uint32_t* slotMask) = 0;
+
+    // setDefaultBufferSize is used to set the size of buffers returned by
+    // dequeueBuffer when a width and height of zero is requested.  Default
+    // is 1x1.
+    virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h) = 0;
+
+    // setDefaultMaxBufferCount sets the default value for the maximum buffer
+    // count (the initial default is 2). If the producer has requested a
+    // buffer count using setBufferCount, the default buffer count will only
+    // take effect if the producer sets the count back to zero.
+    //
+    // The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
+    virtual status_t setDefaultMaxBufferCount(int bufferCount) = 0;
+
+    // disableAsyncBuffer disables the extra buffer used in async mode
+    // (when both producer and consumer have set their "isControlledByApp"
+    // flag) and has dequeueBuffer() return WOULD_BLOCK instead.
+    //
+    // This can only be called before consumerConnect().
+    virtual status_t disableAsyncBuffer() = 0;
+
+    // setMaxAcquiredBufferCount sets the maximum number of buffers that can
+    // be acquired by the consumer at one time (default 1).  This call will
+    // fail if a producer is connected to the BufferQueue.
+    virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers) = 0;
+
+    // setConsumerName sets the name used in logging
+    virtual void setConsumerName(const String8& name) = 0;
+
+    // setDefaultBufferFormat allows the BufferQueue to create
+    // GraphicBuffers of a defaultFormat if no format is specified
+    // in dequeueBuffer.  Formats are enumerated in graphics.h; the
+    // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
+    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat) = 0;
+
+    // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
+    // These are merged with the bits passed to dequeueBuffer.  The values are
+    // enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
+    virtual status_t setConsumerUsageBits(uint32_t usage) = 0;
+
+    // setTransformHint bakes in rotation to buffers so overlays can be used.
+    // The values are enumerated in window.h, e.g.
+    // NATIVE_WINDOW_TRANSFORM_ROT_90.  The default is 0 (no transform).
+    virtual status_t setTransformHint(uint32_t hint) = 0;
+
+    // dump state into a string
+    virtual void dump(String8& result, const char* prefix) const = 0;
+
+public:
+    DECLARE_META_INTERFACE(GraphicBufferConsumer);
+};
+
+// ----------------------------------------------------------------------------
+
+class BnGraphicBufferConsumer : public BnInterface<IGraphicBufferConsumer>
+{
+public:
+    virtual status_t    onTransact( uint32_t code,
+                                    const Parcel& data,
+                                    Parcel* reply,
+                                    uint32_t flags = 0);
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_GUI_IGRAPHICBUFFERCONSUMER_H
diff --git a/include/gui/IGraphicBufferProducer.h b/include/gui/IGraphicBufferProducer.h
index 29c7ff3..342ba08 100644
--- a/include/gui/IGraphicBufferProducer.h
+++ b/include/gui/IGraphicBufferProducer.h
@@ -84,7 +84,10 @@
     // the buffer. The contents of the buffer must not be overwritten until the
     // fence signals. If the fence is NULL, the buffer may be written
     // immediately.
-    virtual status_t dequeueBuffer(int *slot, sp<Fence>* fence,
+    //
+    // The async parameter sets whether we're in asynchrnous mode for this
+    // deququeBuffer() call.
+    virtual status_t dequeueBuffer(int *slot, sp<Fence>* fence, bool async,
             uint32_t w, uint32_t h, uint32_t format, uint32_t usage) = 0;
 
     // queueBuffer indicates that the client has finished filling in the
@@ -96,40 +99,46 @@
     // must be monotonically increasing. Its other properties (zero point, etc)
     // are client-dependent, and should be documented by the client.
     //
+    // The async parameter sets whether we're queuing a buffer in asynchronous mode.
+    //
     // outWidth, outHeight and outTransform are filled with the default width
     // and height of the window and current transform applied to buffers,
     // respectively.
 
-    struct QueueBufferInput : public Flattenable {
+    struct QueueBufferInput : public Flattenable<QueueBufferInput> {
+        friend class Flattenable<QueueBufferInput>;
         inline QueueBufferInput(const Parcel& parcel);
-        inline QueueBufferInput(int64_t timestamp,
-                const Rect& crop, int scalingMode, uint32_t transform,
-                sp<Fence> fence)
-        : timestamp(timestamp), crop(crop), scalingMode(scalingMode),
-          transform(transform), fence(fence) { }
-        inline void deflate(int64_t* outTimestamp, Rect* outCrop,
-                int* outScalingMode, uint32_t* outTransform,
-                sp<Fence>* outFence) const {
+        inline QueueBufferInput(int64_t timestamp, bool isAutoTimestamp,
+                const Rect& crop, int scalingMode, uint32_t transform, bool async,
+                const sp<Fence>& fence)
+        : timestamp(timestamp), isAutoTimestamp(isAutoTimestamp), crop(crop),
+          scalingMode(scalingMode), transform(transform), async(async),
+          fence(fence) { }
+        inline void deflate(int64_t* outTimestamp, bool* outIsAutoTimestamp,
+                Rect* outCrop, int* outScalingMode, uint32_t* outTransform,
+                bool* outAsync, sp<Fence>* outFence) const {
             *outTimestamp = timestamp;
+            *outIsAutoTimestamp = bool(isAutoTimestamp);
             *outCrop = crop;
             *outScalingMode = scalingMode;
             *outTransform = transform;
+            *outAsync = bool(async);
             *outFence = fence;
         }
 
-        // Flattenable interface
-        virtual size_t getFlattenedSize() const;
-        virtual size_t getFdCount() const;
-        virtual status_t flatten(void* buffer, size_t size,
-                int fds[], size_t count) const;
-        virtual status_t unflatten(void const* buffer, size_t size,
-                int fds[], size_t count);
+        // Flattenable protocol
+        size_t getFlattenedSize() const;
+        size_t getFdCount() const;
+        status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
+        status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
 
     private:
         int64_t timestamp;
+        int isAutoTimestamp;
         Rect crop;
         int scalingMode;
         uint32_t transform;
+        int async;
         sp<Fence> fence;
     };
 
@@ -171,13 +180,6 @@
     // 'what' tokens allowed are that of android_natives.h
     virtual int query(int what, int* value) = 0;
 
-    // setSynchronousMode set whether dequeueBuffer is synchronous or
-    // asynchronous. In synchronous mode, dequeueBuffer blocks until
-    // a buffer is available, the currently bound buffer can be dequeued and
-    // queued buffers will be retired in order.
-    // The default mode is asynchronous.
-    virtual status_t setSynchronousMode(bool enabled) = 0;
-
     // connect attempts to connect a client API to the IGraphicBufferProducer.
     // This must be called before any other IGraphicBufferProducer methods are
     // called except for getAllocator.
@@ -187,8 +189,11 @@
     //
     // outWidth, outHeight and outTransform are filled with the default width
     // and height of the window and current transform applied to buffers,
-    // respectively.
-    virtual status_t connect(int api, QueueBufferOutput* output) = 0;
+    // respectively. The token needs to be any binder object that lives in the
+    // producer process -- it is solely used for obtaining a death notification
+    // when the producer is killed.
+    virtual status_t connect(const sp<IBinder>& token,
+            int api, bool producerControlledByApp, QueueBufferOutput* output) = 0;
 
     // disconnect attempts to disconnect a client API from the
     // IGraphicBufferProducer.  Calling this method will cause any subsequent
diff --git a/include/gui/ISensorEventConnection.h b/include/gui/ISensorEventConnection.h
index 749065e..f64c6b8 100644
--- a/include/gui/ISensorEventConnection.h
+++ b/include/gui/ISensorEventConnection.h
@@ -36,8 +36,10 @@
     DECLARE_META_INTERFACE(SensorEventConnection);
 
     virtual sp<BitTube> getSensorChannel() const = 0;
-    virtual status_t enableDisable(int handle, bool enabled) = 0;
+    virtual status_t enableDisable(int handle, bool enabled, nsecs_t samplingPeriodNs,
+                                   nsecs_t maxBatchReportLatencyNs, int reservedFlags) = 0;
     virtual status_t setEventRate(int handle, nsecs_t ns) = 0;
+    virtual status_t flush() = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/ISurfaceComposer.h b/include/gui/ISurfaceComposer.h
index 9018b87..5c3c99c 100644
--- a/include/gui/ISurfaceComposer.h
+++ b/include/gui/ISurfaceComposer.h
@@ -70,12 +70,17 @@
     /* return an IDisplayEventConnection */
     virtual sp<IDisplayEventConnection> createDisplayEventConnection() = 0;
 
-    /* create a display
+    /* create a virtual display
      * requires ACCESS_SURFACE_FLINGER permission.
      */
     virtual sp<IBinder> createDisplay(const String8& displayName,
             bool secure) = 0;
 
+    /* destroy a virtual display
+     * requires ACCESS_SURFACE_FLINGER permission.
+     */
+    virtual void destroyDisplay(const sp<IBinder>& display) = 0;
+
     /* get the token for the existing default displays. possible values
      * for id are eDisplayIdMain and eDisplayIdHdmi.
      */
@@ -115,8 +120,7 @@
     virtual status_t captureScreen(const sp<IBinder>& display,
             const sp<IGraphicBufferProducer>& producer,
             uint32_t reqWidth, uint32_t reqHeight,
-            uint32_t minLayerZ, uint32_t maxLayerZ,
-            bool isCpuConsumer) = 0;
+            uint32_t minLayerZ, uint32_t maxLayerZ) = 0;
 };
 
 // ----------------------------------------------------------------------------
@@ -131,6 +135,7 @@
         CREATE_GRAPHIC_BUFFER_ALLOC,
         CREATE_DISPLAY_EVENT_CONNECTION,
         CREATE_DISPLAY,
+        DESTROY_DISPLAY,
         GET_BUILT_IN_DISPLAY,
         SET_TRANSACTION_STATE,
         AUTHENTICATE_SURFACE,
diff --git a/include/gui/Sensor.h b/include/gui/Sensor.h
index 2af2307..0c81426 100644
--- a/include/gui/Sensor.h
+++ b/include/gui/Sensor.h
@@ -53,7 +53,7 @@
     };
 
             Sensor();
-            Sensor(struct sensor_t const* hwSensor);
+            Sensor(struct sensor_t const* hwSensor, int halVersion = 0);
             ~Sensor();
 
     const String8& getName() const;
@@ -67,11 +67,13 @@
     int32_t getMinDelay() const;
     nsecs_t getMinDelayNs() const;
     int32_t getVersion() const;
+    int32_t getFifoReservedEventCount() const;
+    int32_t getFifoMaxEventCount() const;
 
     // LightFlattenable protocol
     inline bool isFixedSize() const { return false; }
-    size_t getSize() const;
-    status_t flatten(void* buffer) const;
+    size_t getFlattenedSize() const;
+    status_t flatten(void* buffer, size_t size) const;
     status_t unflatten(void const* buffer, size_t size);
 
 private:
@@ -85,6 +87,8 @@
     float   mPower;
     int32_t mMinDelay;
     int32_t mVersion;
+    int32_t mFifoReservedEventCount;
+    int32_t mFifoMaxEventCount;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/SensorEventQueue.h b/include/gui/SensorEventQueue.h
index 759b5cb..0bfc7a0 100644
--- a/include/gui/SensorEventQueue.h
+++ b/include/gui/SensorEventQueue.h
@@ -49,6 +49,9 @@
 class SensorEventQueue : public ASensorEventQueue, public RefBase
 {
 public:
+
+    enum { MAX_RECEIVE_BUFFER_EVENT_COUNT = 256 };
+
             SensorEventQueue(const sp<ISensorEventConnection>& connection);
     virtual ~SensorEventQueue();
     virtual void onFirstRef();
@@ -68,8 +71,10 @@
     status_t setEventRate(Sensor const* sensor, nsecs_t ns) const;
 
     // these are here only to support SensorManager.java
-    status_t enableSensor(int32_t handle, int32_t us) const;
+    status_t enableSensor(int32_t handle, int32_t samplingPeriodUs, int maxBatchReportLatencyUs,
+                          int reservedFlags) const;
     status_t disableSensor(int32_t handle) const;
+    status_t flush() const;
 
 private:
     sp<Looper> getLooper() const;
@@ -77,6 +82,9 @@
     sp<BitTube> mSensorChannel;
     mutable Mutex mLock;
     mutable sp<Looper> mLooper;
+    ASensorEvent* mRecBuffer;
+    size_t mAvailable;
+    size_t mConsumed;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/Surface.h b/include/gui/Surface.h
index c25847c..6f8a97c 100644
--- a/include/gui/Surface.h
+++ b/include/gui/Surface.h
@@ -18,7 +18,6 @@
 #define ANDROID_GUI_SURFACE_H
 
 #include <gui/IGraphicBufferProducer.h>
-#include <gui/GLConsumer.h>
 #include <gui/BufferQueue.h>
 
 #include <ui/ANativeObjectBase.h>
@@ -61,8 +60,11 @@
      * However, once a Surface is connected, it'll prevent other Surfaces
      * referring to the same IGraphicBufferProducer to become connected and
      * therefore prevent them to be used as actual producers of buffers.
+     *
+     * the controlledByApp flag indicates that this Surface (producer) is
+     * controlled by the application. This flag is used at connect time.
      */
-    Surface(const sp<IGraphicBufferProducer>& bufferProducer);
+    Surface(const sp<IGraphicBufferProducer>& bufferProducer, bool controlledByApp = false);
 
     /* getIGraphicBufferProducer() returns the IGraphicBufferProducer this
      * Surface was created with. Usually it's an error to use the
@@ -228,6 +230,14 @@
     // window. this is only a hint, actual transform may differ.
     uint32_t mTransformHint;
 
+    // mProducerControlledByApp whether this buffer producer is controlled
+    // by the application
+    bool mProducerControlledByApp;
+
+    // mSwapIntervalZero set if we should drop buffers at queue() time to
+    // achieve an asynchronous swap interval
+    bool mSwapIntervalZero;
+
     // mConsumerRunningBehind whether the consumer is running more than
     // one buffer behind the producer.
     mutable bool mConsumerRunningBehind;
diff --git a/include/gui/SurfaceComposerClient.h b/include/gui/SurfaceComposerClient.h
index 6bf5b47..e982bcd 100644
--- a/include/gui/SurfaceComposerClient.h
+++ b/include/gui/SurfaceComposerClient.h
@@ -48,7 +48,7 @@
 class SurfaceComposerClient : public RefBase
 {
     friend class Composer;
-public:    
+public:
                 SurfaceComposerClient();
     virtual     ~SurfaceComposerClient();
 
@@ -57,7 +57,7 @@
 
     // Return the connection of this client
     sp<IBinder> connection() const;
-    
+
     // Forcibly remove connection before all references have gone away.
     void        dispose();
 
@@ -86,9 +86,12 @@
             uint32_t flags = 0  // usage flags
     );
 
-    //! Create a display
+    //! Create a virtual display
     static sp<IBinder> createDisplay(const String8& displayName, bool secure);
 
+    //! Destroy a virtual display
+    static void destroyDisplay(const sp<IBinder>& display);
+
     //! Get the token for the existing default displays.
     //! Possible values for id are eDisplayIdMain and eDisplayIdHdmi.
     static sp<IBinder> getBuiltInDisplay(int32_t id);
@@ -165,6 +168,7 @@
 
 private:
     mutable sp<CpuConsumer> mCpuConsumer;
+    mutable sp<BufferQueue> mBufferQueue;
     CpuConsumer::LockedBuffer mBuffer;
     bool mHaveBuffer;
 
diff --git a/include/input/Input.h b/include/input/Input.h
new file mode 100644
index 0000000..e778076
--- /dev/null
+++ b/include/input/Input.h
@@ -0,0 +1,620 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef _LIBINPUT_INPUT_H
+#define _LIBINPUT_INPUT_H
+
+/**
+ * Native input event structures.
+ */
+
+#include <android/input.h>
+#include <utils/Vector.h>
+#include <utils/KeyedVector.h>
+#include <utils/Timers.h>
+#include <utils/RefBase.h>
+#include <utils/String8.h>
+
+/*
+ * Additional private constants not defined in ndk/ui/input.h.
+ */
+enum {
+    /* Signifies that the key is being predispatched */
+    AKEY_EVENT_FLAG_PREDISPATCH = 0x20000000,
+
+    /* Private control to determine when an app is tracking a key sequence. */
+    AKEY_EVENT_FLAG_START_TRACKING = 0x40000000,
+
+    /* Key event is inconsistent with previously sent key events. */
+    AKEY_EVENT_FLAG_TAINTED = 0x80000000,
+};
+
+enum {
+    /* Motion event is inconsistent with previously sent motion events. */
+    AMOTION_EVENT_FLAG_TAINTED = 0x80000000,
+};
+
+enum {
+    /* Used when a motion event is not associated with any display.
+     * Typically used for non-pointer events. */
+    ADISPLAY_ID_NONE = -1,
+
+    /* The default display id. */
+    ADISPLAY_ID_DEFAULT = 0,
+};
+
+enum {
+    /*
+     * Indicates that an input device has switches.
+     * This input source flag is hidden from the API because switches are only used by the system
+     * and applications have no way to interact with them.
+     */
+    AINPUT_SOURCE_SWITCH = 0x80000000,
+};
+
+/*
+ * SystemUiVisibility constants from View.
+ */
+enum {
+    ASYSTEM_UI_VISIBILITY_STATUS_BAR_VISIBLE = 0,
+    ASYSTEM_UI_VISIBILITY_STATUS_BAR_HIDDEN = 0x00000001,
+};
+
+/*
+ * Maximum number of pointers supported per motion event.
+ * Smallest number of pointers is 1.
+ * (We want at least 10 but some touch controllers obstensibly configured for 10 pointers
+ * will occasionally emit 11.  There is not much harm making this constant bigger.)
+ */
+#define MAX_POINTERS 16
+
+/*
+ * Maximum pointer id value supported in a motion event.
+ * Smallest pointer id is 0.
+ * (This is limited by our use of BitSet32 to track pointer assignments.)
+ */
+#define MAX_POINTER_ID 31
+
+/*
+ * Declare a concrete type for the NDK's input event forward declaration.
+ */
+struct AInputEvent {
+    virtual ~AInputEvent() { }
+};
+
+/*
+ * Declare a concrete type for the NDK's input device forward declaration.
+ */
+struct AInputDevice {
+    virtual ~AInputDevice() { }
+};
+
+
+namespace android {
+
+#ifdef HAVE_ANDROID_OS
+class Parcel;
+#endif
+
+/*
+ * Flags that flow alongside events in the input dispatch system to help with certain
+ * policy decisions such as waking from device sleep.
+ *
+ * These flags are also defined in frameworks/base/core/java/android/view/WindowManagerPolicy.java.
+ */
+enum {
+    /* These flags originate in RawEvents and are generally set in the key map.
+     * NOTE: If you edit these flags, also edit labels in KeycodeLabels.h. */
+
+    POLICY_FLAG_WAKE = 0x00000001,
+    POLICY_FLAG_WAKE_DROPPED = 0x00000002,
+    POLICY_FLAG_SHIFT = 0x00000004,
+    POLICY_FLAG_CAPS_LOCK = 0x00000008,
+    POLICY_FLAG_ALT = 0x00000010,
+    POLICY_FLAG_ALT_GR = 0x00000020,
+    POLICY_FLAG_MENU = 0x00000040,
+    POLICY_FLAG_LAUNCHER = 0x00000080,
+    POLICY_FLAG_VIRTUAL = 0x00000100,
+    POLICY_FLAG_FUNCTION = 0x00000200,
+
+    POLICY_FLAG_RAW_MASK = 0x0000ffff,
+
+    /* These flags are set by the input dispatcher. */
+
+    // Indicates that the input event was injected.
+    POLICY_FLAG_INJECTED = 0x01000000,
+
+    // Indicates that the input event is from a trusted source such as a directly attached
+    // input device or an application with system-wide event injection permission.
+    POLICY_FLAG_TRUSTED = 0x02000000,
+
+    // Indicates that the input event has passed through an input filter.
+    POLICY_FLAG_FILTERED = 0x04000000,
+
+    // Disables automatic key repeating behavior.
+    POLICY_FLAG_DISABLE_KEY_REPEAT = 0x08000000,
+
+    /* These flags are set by the input reader policy as it intercepts each event. */
+
+    // Indicates that the screen was off when the event was received and the event
+    // should wake the device.
+    POLICY_FLAG_WOKE_HERE = 0x10000000,
+
+    // Indicates that the screen was dim when the event was received and the event
+    // should brighten the device.
+    POLICY_FLAG_BRIGHT_HERE = 0x20000000,
+
+    // Indicates that the event should be dispatched to applications.
+    // The input event should still be sent to the InputDispatcher so that it can see all
+    // input events received include those that it will not deliver.
+    POLICY_FLAG_PASS_TO_USER = 0x40000000,
+};
+
+/*
+ * Pointer coordinate data.
+ */
+struct PointerCoords {
+    enum { MAX_AXES = 14 }; // 14 so that sizeof(PointerCoords) == 64
+
+    // Bitfield of axes that are present in this structure.
+    uint64_t bits;
+
+    // Values of axes that are stored in this structure packed in order by axis id
+    // for each axis that is present in the structure according to 'bits'.
+    float values[MAX_AXES];
+
+    inline void clear() {
+        bits = 0;
+    }
+
+    float getAxisValue(int32_t axis) const;
+    status_t setAxisValue(int32_t axis, float value);
+
+    void scale(float scale);
+
+    inline float getX() const {
+        return getAxisValue(AMOTION_EVENT_AXIS_X);
+    }
+
+    inline float getY() const {
+        return getAxisValue(AMOTION_EVENT_AXIS_Y);
+    }
+
+#ifdef HAVE_ANDROID_OS
+    status_t readFromParcel(Parcel* parcel);
+    status_t writeToParcel(Parcel* parcel) const;
+#endif
+
+    bool operator==(const PointerCoords& other) const;
+    inline bool operator!=(const PointerCoords& other) const {
+        return !(*this == other);
+    }
+
+    void copyFrom(const PointerCoords& other);
+
+private:
+    void tooManyAxes(int axis);
+};
+
+/*
+ * Pointer property data.
+ */
+struct PointerProperties {
+    // The id of the pointer.
+    int32_t id;
+
+    // The pointer tool type.
+    int32_t toolType;
+
+    inline void clear() {
+        id = -1;
+        toolType = 0;
+    }
+
+    bool operator==(const PointerProperties& other) const;
+    inline bool operator!=(const PointerProperties& other) const {
+        return !(*this == other);
+    }
+
+    void copyFrom(const PointerProperties& other);
+};
+
+/*
+ * Input events.
+ */
+class InputEvent : public AInputEvent {
+public:
+    virtual ~InputEvent() { }
+
+    virtual int32_t getType() const = 0;
+
+    inline int32_t getDeviceId() const { return mDeviceId; }
+
+    inline int32_t getSource() const { return mSource; }
+
+    inline void setSource(int32_t source) { mSource = source; }
+
+protected:
+    void initialize(int32_t deviceId, int32_t source);
+    void initialize(const InputEvent& from);
+
+    int32_t mDeviceId;
+    int32_t mSource;
+};
+
+/*
+ * Key events.
+ */
+class KeyEvent : public InputEvent {
+public:
+    virtual ~KeyEvent() { }
+
+    virtual int32_t getType() const { return AINPUT_EVENT_TYPE_KEY; }
+
+    inline int32_t getAction() const { return mAction; }
+
+    inline int32_t getFlags() const { return mFlags; }
+
+    inline void setFlags(int32_t flags) { mFlags = flags; }
+
+    inline int32_t getKeyCode() const { return mKeyCode; }
+
+    inline int32_t getScanCode() const { return mScanCode; }
+
+    inline int32_t getMetaState() const { return mMetaState; }
+
+    inline int32_t getRepeatCount() const { return mRepeatCount; }
+
+    inline nsecs_t getDownTime() const { return mDownTime; }
+
+    inline nsecs_t getEventTime() const { return mEventTime; }
+
+    // Return true if this event may have a default action implementation.
+    static bool hasDefaultAction(int32_t keyCode);
+    bool hasDefaultAction() const;
+
+    // Return true if this event represents a system key.
+    static bool isSystemKey(int32_t keyCode);
+    bool isSystemKey() const;
+    
+    void initialize(
+            int32_t deviceId,
+            int32_t source,
+            int32_t action,
+            int32_t flags,
+            int32_t keyCode,
+            int32_t scanCode,
+            int32_t metaState,
+            int32_t repeatCount,
+            nsecs_t downTime,
+            nsecs_t eventTime);
+    void initialize(const KeyEvent& from);
+
+protected:
+    int32_t mAction;
+    int32_t mFlags;
+    int32_t mKeyCode;
+    int32_t mScanCode;
+    int32_t mMetaState;
+    int32_t mRepeatCount;
+    nsecs_t mDownTime;
+    nsecs_t mEventTime;
+};
+
+/*
+ * Motion events.
+ */
+class MotionEvent : public InputEvent {
+public:
+    virtual ~MotionEvent() { }
+
+    virtual int32_t getType() const { return AINPUT_EVENT_TYPE_MOTION; }
+
+    inline int32_t getAction() const { return mAction; }
+
+    inline int32_t getActionMasked() const { return mAction & AMOTION_EVENT_ACTION_MASK; }
+
+    inline int32_t getActionIndex() const {
+        return (mAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
+                >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
+    }
+
+    inline void setAction(int32_t action) { mAction = action; }
+
+    inline int32_t getFlags() const { return mFlags; }
+
+    inline void setFlags(int32_t flags) { mFlags = flags; }
+
+    inline int32_t getEdgeFlags() const { return mEdgeFlags; }
+
+    inline void setEdgeFlags(int32_t edgeFlags) { mEdgeFlags = edgeFlags; }
+
+    inline int32_t getMetaState() const { return mMetaState; }
+
+    inline void setMetaState(int32_t metaState) { mMetaState = metaState; }
+
+    inline int32_t getButtonState() const { return mButtonState; }
+
+    inline float getXOffset() const { return mXOffset; }
+
+    inline float getYOffset() const { return mYOffset; }
+
+    inline float getXPrecision() const { return mXPrecision; }
+
+    inline float getYPrecision() const { return mYPrecision; }
+
+    inline nsecs_t getDownTime() const { return mDownTime; }
+
+    inline void setDownTime(nsecs_t downTime) { mDownTime = downTime; }
+
+    inline size_t getPointerCount() const { return mPointerProperties.size(); }
+
+    inline const PointerProperties* getPointerProperties(size_t pointerIndex) const {
+        return &mPointerProperties[pointerIndex];
+    }
+
+    inline int32_t getPointerId(size_t pointerIndex) const {
+        return mPointerProperties[pointerIndex].id;
+    }
+
+    inline int32_t getToolType(size_t pointerIndex) const {
+        return mPointerProperties[pointerIndex].toolType;
+    }
+
+    inline nsecs_t getEventTime() const { return mSampleEventTimes[getHistorySize()]; }
+
+    const PointerCoords* getRawPointerCoords(size_t pointerIndex) const;
+
+    float getRawAxisValue(int32_t axis, size_t pointerIndex) const;
+
+    inline float getRawX(size_t pointerIndex) const {
+        return getRawAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
+    }
+
+    inline float getRawY(size_t pointerIndex) const {
+        return getRawAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
+    }
+
+    float getAxisValue(int32_t axis, size_t pointerIndex) const;
+
+    inline float getX(size_t pointerIndex) const {
+        return getAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
+    }
+
+    inline float getY(size_t pointerIndex) const {
+        return getAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
+    }
+
+    inline float getPressure(size_t pointerIndex) const {
+        return getAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pointerIndex);
+    }
+
+    inline float getSize(size_t pointerIndex) const {
+        return getAxisValue(AMOTION_EVENT_AXIS_SIZE, pointerIndex);
+    }
+
+    inline float getTouchMajor(size_t pointerIndex) const {
+        return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex);
+    }
+
+    inline float getTouchMinor(size_t pointerIndex) const {
+        return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex);
+    }
+
+    inline float getToolMajor(size_t pointerIndex) const {
+        return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex);
+    }
+
+    inline float getToolMinor(size_t pointerIndex) const {
+        return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex);
+    }
+
+    inline float getOrientation(size_t pointerIndex) const {
+        return getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex);
+    }
+
+    inline size_t getHistorySize() const { return mSampleEventTimes.size() - 1; }
+
+    inline nsecs_t getHistoricalEventTime(size_t historicalIndex) const {
+        return mSampleEventTimes[historicalIndex];
+    }
+
+    const PointerCoords* getHistoricalRawPointerCoords(
+            size_t pointerIndex, size_t historicalIndex) const;
+
+    float getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
+            size_t historicalIndex) const;
+
+    inline float getHistoricalRawX(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalRawAxisValue(
+                AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
+    }
+
+    inline float getHistoricalRawY(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalRawAxisValue(
+                AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
+    }
+
+    float getHistoricalAxisValue(int32_t axis, size_t pointerIndex, size_t historicalIndex) const;
+
+    inline float getHistoricalX(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalAxisValue(
+                AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
+    }
+
+    inline float getHistoricalY(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalAxisValue(
+                AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
+    }
+
+    inline float getHistoricalPressure(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalAxisValue(
+                AMOTION_EVENT_AXIS_PRESSURE, pointerIndex, historicalIndex);
+    }
+
+    inline float getHistoricalSize(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalAxisValue(
+                AMOTION_EVENT_AXIS_SIZE, pointerIndex, historicalIndex);
+    }
+
+    inline float getHistoricalTouchMajor(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalAxisValue(
+                AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex, historicalIndex);
+    }
+
+    inline float getHistoricalTouchMinor(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalAxisValue(
+                AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex, historicalIndex);
+    }
+
+    inline float getHistoricalToolMajor(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalAxisValue(
+                AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex, historicalIndex);
+    }
+
+    inline float getHistoricalToolMinor(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalAxisValue(
+                AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex, historicalIndex);
+    }
+
+    inline float getHistoricalOrientation(size_t pointerIndex, size_t historicalIndex) const {
+        return getHistoricalAxisValue(
+                AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex, historicalIndex);
+    }
+
+    ssize_t findPointerIndex(int32_t pointerId) const;
+
+    void initialize(
+            int32_t deviceId,
+            int32_t source,
+            int32_t action,
+            int32_t flags,
+            int32_t edgeFlags,
+            int32_t metaState,
+            int32_t buttonState,
+            float xOffset,
+            float yOffset,
+            float xPrecision,
+            float yPrecision,
+            nsecs_t downTime,
+            nsecs_t eventTime,
+            size_t pointerCount,
+            const PointerProperties* pointerProperties,
+            const PointerCoords* pointerCoords);
+
+    void copyFrom(const MotionEvent* other, bool keepHistory);
+
+    void addSample(
+            nsecs_t eventTime,
+            const PointerCoords* pointerCoords);
+
+    void offsetLocation(float xOffset, float yOffset);
+
+    void scale(float scaleFactor);
+
+    // Apply 3x3 perspective matrix transformation.
+    // Matrix is in row-major form and compatible with SkMatrix.
+    void transform(const float matrix[9]);
+
+#ifdef HAVE_ANDROID_OS
+    status_t readFromParcel(Parcel* parcel);
+    status_t writeToParcel(Parcel* parcel) const;
+#endif
+
+    static bool isTouchEvent(int32_t source, int32_t action);
+    inline bool isTouchEvent() const {
+        return isTouchEvent(mSource, mAction);
+    }
+
+    // Low-level accessors.
+    inline const PointerProperties* getPointerProperties() const {
+        return mPointerProperties.array();
+    }
+    inline const nsecs_t* getSampleEventTimes() const { return mSampleEventTimes.array(); }
+    inline const PointerCoords* getSamplePointerCoords() const {
+            return mSamplePointerCoords.array();
+    }
+
+protected:
+    int32_t mAction;
+    int32_t mFlags;
+    int32_t mEdgeFlags;
+    int32_t mMetaState;
+    int32_t mButtonState;
+    float mXOffset;
+    float mYOffset;
+    float mXPrecision;
+    float mYPrecision;
+    nsecs_t mDownTime;
+    Vector<PointerProperties> mPointerProperties;
+    Vector<nsecs_t> mSampleEventTimes;
+    Vector<PointerCoords> mSamplePointerCoords;
+};
+
+/*
+ * Input event factory.
+ */
+class InputEventFactoryInterface {
+protected:
+    virtual ~InputEventFactoryInterface() { }
+
+public:
+    InputEventFactoryInterface() { }
+
+    virtual KeyEvent* createKeyEvent() = 0;
+    virtual MotionEvent* createMotionEvent() = 0;
+};
+
+/*
+ * A simple input event factory implementation that uses a single preallocated instance
+ * of each type of input event that are reused for each request.
+ */
+class PreallocatedInputEventFactory : public InputEventFactoryInterface {
+public:
+    PreallocatedInputEventFactory() { }
+    virtual ~PreallocatedInputEventFactory() { }
+
+    virtual KeyEvent* createKeyEvent() { return & mKeyEvent; }
+    virtual MotionEvent* createMotionEvent() { return & mMotionEvent; }
+
+private:
+    KeyEvent mKeyEvent;
+    MotionEvent mMotionEvent;
+};
+
+/*
+ * An input event factory implementation that maintains a pool of input events.
+ */
+class PooledInputEventFactory : public InputEventFactoryInterface {
+public:
+    PooledInputEventFactory(size_t maxPoolSize = 20);
+    virtual ~PooledInputEventFactory();
+
+    virtual KeyEvent* createKeyEvent();
+    virtual MotionEvent* createMotionEvent();
+
+    void recycle(InputEvent* event);
+
+private:
+    const size_t mMaxPoolSize;
+
+    Vector<KeyEvent*> mKeyEventPool;
+    Vector<MotionEvent*> mMotionEventPool;
+};
+
+} // namespace android
+
+#endif // _LIBINPUT_INPUT_H
diff --git a/include/input/InputDevice.h b/include/input/InputDevice.h
new file mode 100644
index 0000000..1419b45
--- /dev/null
+++ b/include/input/InputDevice.h
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2012 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 _LIBINPUT_INPUT_DEVICE_H
+#define _LIBINPUT_INPUT_DEVICE_H
+
+#include <input/Input.h>
+#include <input/KeyCharacterMap.h>
+
+namespace android {
+
+/*
+ * Identifies a device.
+ */
+struct InputDeviceIdentifier {
+    inline InputDeviceIdentifier() :
+            bus(0), vendor(0), product(0), version(0) {
+    }
+
+    // Information provided by the kernel.
+    String8 name;
+    String8 location;
+    String8 uniqueId;
+    uint16_t bus;
+    uint16_t vendor;
+    uint16_t product;
+    uint16_t version;
+
+    // A composite input device descriptor string that uniquely identifies the device
+    // even across reboots or reconnections.  The value of this field is used by
+    // upper layers of the input system to associate settings with individual devices.
+    // It is hashed from whatever kernel provided information is available.
+    // Ideally, the way this value is computed should not change between Android releases
+    // because that would invalidate persistent settings that rely on it.
+    String8 descriptor;
+};
+
+/*
+ * Describes the characteristics and capabilities of an input device.
+ */
+class InputDeviceInfo {
+public:
+    InputDeviceInfo();
+    InputDeviceInfo(const InputDeviceInfo& other);
+    ~InputDeviceInfo();
+
+    struct MotionRange {
+        int32_t axis;
+        uint32_t source;
+        float min;
+        float max;
+        float flat;
+        float fuzz;
+        float resolution;
+    };
+
+    void initialize(int32_t id, int32_t generation, int32_t controllerNumber,
+            const InputDeviceIdentifier& identifier, const String8& alias, bool isExternal);
+
+    inline int32_t getId() const { return mId; }
+    inline int32_t getControllerNumber() const { return mControllerNumber; }
+    inline int32_t getGeneration() const { return mGeneration; }
+    inline const InputDeviceIdentifier& getIdentifier() const { return mIdentifier; }
+    inline const String8& getAlias() const { return mAlias; }
+    inline const String8& getDisplayName() const {
+        return mAlias.isEmpty() ? mIdentifier.name : mAlias;
+    }
+    inline bool isExternal() const { return mIsExternal; }
+    inline uint32_t getSources() const { return mSources; }
+
+    const MotionRange* getMotionRange(int32_t axis, uint32_t source) const;
+
+    void addSource(uint32_t source);
+    void addMotionRange(int32_t axis, uint32_t source,
+            float min, float max, float flat, float fuzz, float resolution);
+    void addMotionRange(const MotionRange& range);
+
+    inline void setKeyboardType(int32_t keyboardType) { mKeyboardType = keyboardType; }
+    inline int32_t getKeyboardType() const { return mKeyboardType; }
+
+    inline void setKeyCharacterMap(const sp<KeyCharacterMap>& value) {
+        mKeyCharacterMap = value;
+    }
+
+    inline sp<KeyCharacterMap> getKeyCharacterMap() const {
+        return mKeyCharacterMap;
+    }
+
+    inline void setVibrator(bool hasVibrator) { mHasVibrator = hasVibrator; }
+    inline bool hasVibrator() const { return mHasVibrator; }
+
+    inline void setButtonUnderPad(bool hasButton) { mHasButtonUnderPad = hasButton; }
+    inline bool hasButtonUnderPad() const { return mHasButtonUnderPad; }
+
+    inline const Vector<MotionRange>& getMotionRanges() const {
+        return mMotionRanges;
+    }
+
+private:
+    int32_t mId;
+    int32_t mGeneration;
+    int32_t mControllerNumber;
+    InputDeviceIdentifier mIdentifier;
+    String8 mAlias;
+    bool mIsExternal;
+    uint32_t mSources;
+    int32_t mKeyboardType;
+    sp<KeyCharacterMap> mKeyCharacterMap;
+    bool mHasVibrator;
+    bool mHasButtonUnderPad;
+
+    Vector<MotionRange> mMotionRanges;
+};
+
+/* Types of input device configuration files. */
+enum InputDeviceConfigurationFileType {
+    INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION = 0,     /* .idc file */
+    INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_LAYOUT = 1,        /* .kl file */
+    INPUT_DEVICE_CONFIGURATION_FILE_TYPE_KEY_CHARACTER_MAP = 2, /* .kcm file */
+};
+
+/*
+ * Gets the path of an input device configuration file, if one is available.
+ * Considers both system provided and user installed configuration files.
+ *
+ * The device identifier is used to construct several default configuration file
+ * names to try based on the device name, vendor, product, and version.
+ *
+ * Returns an empty string if not found.
+ */
+extern String8 getInputDeviceConfigurationFilePathByDeviceIdentifier(
+        const InputDeviceIdentifier& deviceIdentifier,
+        InputDeviceConfigurationFileType type);
+
+/*
+ * Gets the path of an input device configuration file, if one is available.
+ * Considers both system provided and user installed configuration files.
+ *
+ * The name is case-sensitive and is used to construct the filename to resolve.
+ * All characters except 'a'-'z', 'A'-'Z', '0'-'9', '-', and '_' are replaced by underscores.
+ *
+ * Returns an empty string if not found.
+ */
+extern String8 getInputDeviceConfigurationFilePathByName(
+        const String8& name, InputDeviceConfigurationFileType type);
+
+} // namespace android
+
+#endif // _LIBINPUT_INPUT_DEVICE_H
diff --git a/include/input/InputTransport.h b/include/input/InputTransport.h
new file mode 100644
index 0000000..609b679
--- /dev/null
+++ b/include/input/InputTransport.h
@@ -0,0 +1,443 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef _LIBINPUT_INPUT_TRANSPORT_H
+#define _LIBINPUT_INPUT_TRANSPORT_H
+
+/**
+ * Native input transport.
+ *
+ * The InputChannel provides a mechanism for exchanging InputMessage structures across processes.
+ *
+ * The InputPublisher and InputConsumer each handle one end-point of an input channel.
+ * The InputPublisher is used by the input dispatcher to send events to the application.
+ * The InputConsumer is used by the application to receive events from the input dispatcher.
+ */
+
+#include <input/Input.h>
+#include <utils/Errors.h>
+#include <utils/Timers.h>
+#include <utils/RefBase.h>
+#include <utils/String8.h>
+#include <utils/Vector.h>
+#include <utils/BitSet.h>
+
+namespace android {
+
+/*
+ * Intermediate representation used to send input events and related signals.
+ */
+struct InputMessage {
+    enum {
+        TYPE_KEY = 1,
+        TYPE_MOTION = 2,
+        TYPE_FINISHED = 3,
+    };
+
+    struct Header {
+        uint32_t type;
+        uint32_t padding; // 8 byte alignment for the body that follows
+    } header;
+
+    union Body {
+        struct Key {
+            uint32_t seq;
+            nsecs_t eventTime;
+            int32_t deviceId;
+            int32_t source;
+            int32_t action;
+            int32_t flags;
+            int32_t keyCode;
+            int32_t scanCode;
+            int32_t metaState;
+            int32_t repeatCount;
+            nsecs_t downTime;
+
+            inline size_t size() const {
+                return sizeof(Key);
+            }
+        } key;
+
+        struct Motion {
+            uint32_t seq;
+            nsecs_t eventTime;
+            int32_t deviceId;
+            int32_t source;
+            int32_t action;
+            int32_t flags;
+            int32_t metaState;
+            int32_t buttonState;
+            int32_t edgeFlags;
+            nsecs_t downTime;
+            float xOffset;
+            float yOffset;
+            float xPrecision;
+            float yPrecision;
+            size_t pointerCount;
+            struct Pointer {
+                PointerProperties properties;
+                PointerCoords coords;
+            } pointers[MAX_POINTERS];
+
+            int32_t getActionId() const {
+                uint32_t index = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
+                        >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
+                return pointers[index].properties.id;
+            }
+
+            inline size_t size() const {
+                return sizeof(Motion) - sizeof(Pointer) * MAX_POINTERS
+                        + sizeof(Pointer) * pointerCount;
+            }
+        } motion;
+
+        struct Finished {
+            uint32_t seq;
+            bool handled;
+
+            inline size_t size() const {
+                return sizeof(Finished);
+            }
+        } finished;
+    } body;
+
+    bool isValid(size_t actualSize) const;
+    size_t size() const;
+};
+
+/*
+ * An input channel consists of a local unix domain socket used to send and receive
+ * input messages across processes.  Each channel has a descriptive name for debugging purposes.
+ *
+ * Each endpoint has its own InputChannel object that specifies its file descriptor.
+ *
+ * The input channel is closed when all references to it are released.
+ */
+class InputChannel : public RefBase {
+protected:
+    virtual ~InputChannel();
+
+public:
+    InputChannel(const String8& name, int fd);
+
+    /* Creates a pair of input channels.
+     *
+     * Returns OK on success.
+     */
+    static status_t openInputChannelPair(const String8& name,
+            sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel);
+
+    inline String8 getName() const { return mName; }
+    inline int getFd() const { return mFd; }
+
+    /* Sends a message to the other endpoint.
+     *
+     * If the channel is full then the message is guaranteed not to have been sent at all.
+     * Try again after the consumer has sent a finished signal indicating that it has
+     * consumed some of the pending messages from the channel.
+     *
+     * Returns OK on success.
+     * Returns WOULD_BLOCK if the channel is full.
+     * Returns DEAD_OBJECT if the channel's peer has been closed.
+     * Other errors probably indicate that the channel is broken.
+     */
+    status_t sendMessage(const InputMessage* msg);
+
+    /* Receives a message sent by the other endpoint.
+     *
+     * If there is no message present, try again after poll() indicates that the fd
+     * is readable.
+     *
+     * Returns OK on success.
+     * Returns WOULD_BLOCK if there is no message present.
+     * Returns DEAD_OBJECT if the channel's peer has been closed.
+     * Other errors probably indicate that the channel is broken.
+     */
+    status_t receiveMessage(InputMessage* msg);
+
+    /* Returns a new object that has a duplicate of this channel's fd. */
+    sp<InputChannel> dup() const;
+
+private:
+    String8 mName;
+    int mFd;
+};
+
+/*
+ * Publishes input events to an input channel.
+ */
+class InputPublisher {
+public:
+    /* Creates a publisher associated with an input channel. */
+    explicit InputPublisher(const sp<InputChannel>& channel);
+
+    /* Destroys the publisher and releases its input channel. */
+    ~InputPublisher();
+
+    /* Gets the underlying input channel. */
+    inline sp<InputChannel> getChannel() { return mChannel; }
+
+    /* Publishes a key event to the input channel.
+     *
+     * Returns OK on success.
+     * Returns WOULD_BLOCK if the channel is full.
+     * Returns DEAD_OBJECT if the channel's peer has been closed.
+     * Returns BAD_VALUE if seq is 0.
+     * Other errors probably indicate that the channel is broken.
+     */
+    status_t publishKeyEvent(
+            uint32_t seq,
+            int32_t deviceId,
+            int32_t source,
+            int32_t action,
+            int32_t flags,
+            int32_t keyCode,
+            int32_t scanCode,
+            int32_t metaState,
+            int32_t repeatCount,
+            nsecs_t downTime,
+            nsecs_t eventTime);
+
+    /* Publishes a motion event to the input channel.
+     *
+     * Returns OK on success.
+     * Returns WOULD_BLOCK if the channel is full.
+     * Returns DEAD_OBJECT if the channel's peer has been closed.
+     * Returns BAD_VALUE if seq is 0 or if pointerCount is less than 1 or greater than MAX_POINTERS.
+     * Other errors probably indicate that the channel is broken.
+     */
+    status_t publishMotionEvent(
+            uint32_t seq,
+            int32_t deviceId,
+            int32_t source,
+            int32_t action,
+            int32_t flags,
+            int32_t edgeFlags,
+            int32_t metaState,
+            int32_t buttonState,
+            float xOffset,
+            float yOffset,
+            float xPrecision,
+            float yPrecision,
+            nsecs_t downTime,
+            nsecs_t eventTime,
+            size_t pointerCount,
+            const PointerProperties* pointerProperties,
+            const PointerCoords* pointerCoords);
+
+    /* Receives the finished signal from the consumer in reply to the original dispatch signal.
+     * If a signal was received, returns the message sequence number,
+     * and whether the consumer handled the message.
+     *
+     * The returned sequence number is never 0 unless the operation failed.
+     *
+     * Returns OK on success.
+     * Returns WOULD_BLOCK if there is no signal present.
+     * Returns DEAD_OBJECT if the channel's peer has been closed.
+     * Other errors probably indicate that the channel is broken.
+     */
+    status_t receiveFinishedSignal(uint32_t* outSeq, bool* outHandled);
+
+private:
+    sp<InputChannel> mChannel;
+};
+
+/*
+ * Consumes input events from an input channel.
+ */
+class InputConsumer {
+public:
+    /* Creates a consumer associated with an input channel. */
+    explicit InputConsumer(const sp<InputChannel>& channel);
+
+    /* Destroys the consumer and releases its input channel. */
+    ~InputConsumer();
+
+    /* Gets the underlying input channel. */
+    inline sp<InputChannel> getChannel() { return mChannel; }
+
+    /* Consumes an input event from the input channel and copies its contents into
+     * an InputEvent object created using the specified factory.
+     *
+     * Tries to combine a series of move events into larger batches whenever possible.
+     *
+     * If consumeBatches is false, then defers consuming pending batched events if it
+     * is possible for additional samples to be added to them later.  Call hasPendingBatch()
+     * to determine whether a pending batch is available to be consumed.
+     *
+     * If consumeBatches is true, then events are still batched but they are consumed
+     * immediately as soon as the input channel is exhausted.
+     *
+     * The frameTime parameter specifies the time when the current display frame started
+     * rendering in the CLOCK_MONOTONIC time base, or -1 if unknown.
+     *
+     * The returned sequence number is never 0 unless the operation failed.
+     *
+     * Returns OK on success.
+     * Returns WOULD_BLOCK if there is no event present.
+     * Returns DEAD_OBJECT if the channel's peer has been closed.
+     * Returns NO_MEMORY if the event could not be created.
+     * Other errors probably indicate that the channel is broken.
+     */
+    status_t consume(InputEventFactoryInterface* factory, bool consumeBatches,
+            nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
+
+    /* Sends a finished signal to the publisher to inform it that the message
+     * with the specified sequence number has finished being process and whether
+     * the message was handled by the consumer.
+     *
+     * Returns OK on success.
+     * Returns BAD_VALUE if seq is 0.
+     * Other errors probably indicate that the channel is broken.
+     */
+    status_t sendFinishedSignal(uint32_t seq, bool handled);
+
+    /* Returns true if there is a deferred event waiting.
+     *
+     * Should be called after calling consume() to determine whether the consumer
+     * has a deferred event to be processed.  Deferred events are somewhat special in
+     * that they have already been removed from the input channel.  If the input channel
+     * becomes empty, the client may need to do extra work to ensure that it processes
+     * the deferred event despite the fact that the input channel's file descriptor
+     * is not readable.
+     *
+     * One option is simply to call consume() in a loop until it returns WOULD_BLOCK.
+     * This guarantees that all deferred events will be processed.
+     *
+     * Alternately, the caller can call hasDeferredEvent() to determine whether there is
+     * a deferred event waiting and then ensure that its event loop wakes up at least
+     * one more time to consume the deferred event.
+     */
+    bool hasDeferredEvent() const;
+
+    /* Returns true if there is a pending batch.
+     *
+     * Should be called after calling consume() with consumeBatches == false to determine
+     * whether consume() should be called again later on with consumeBatches == true.
+     */
+    bool hasPendingBatch() const;
+
+private:
+    // True if touch resampling is enabled.
+    const bool mResampleTouch;
+
+    // The input channel.
+    sp<InputChannel> mChannel;
+
+    // The current input message.
+    InputMessage mMsg;
+
+    // True if mMsg contains a valid input message that was deferred from the previous
+    // call to consume and that still needs to be handled.
+    bool mMsgDeferred;
+
+    // Batched motion events per device and source.
+    struct Batch {
+        Vector<InputMessage> samples;
+    };
+    Vector<Batch> mBatches;
+
+    // Touch state per device and source, only for sources of class pointer.
+    struct History {
+        nsecs_t eventTime;
+        BitSet32 idBits;
+        int32_t idToIndex[MAX_POINTER_ID + 1];
+        PointerCoords pointers[MAX_POINTERS];
+
+        void initializeFrom(const InputMessage* msg) {
+            eventTime = msg->body.motion.eventTime;
+            idBits.clear();
+            for (size_t i = 0; i < msg->body.motion.pointerCount; i++) {
+                uint32_t id = msg->body.motion.pointers[i].properties.id;
+                idBits.markBit(id);
+                idToIndex[id] = i;
+                pointers[i].copyFrom(msg->body.motion.pointers[i].coords);
+            }
+        }
+
+        const PointerCoords& getPointerById(uint32_t id) const {
+            return pointers[idToIndex[id]];
+        }
+    };
+    struct TouchState {
+        int32_t deviceId;
+        int32_t source;
+        size_t historyCurrent;
+        size_t historySize;
+        History history[2];
+        History lastResample;
+
+        void initialize(int32_t deviceId, int32_t source) {
+            this->deviceId = deviceId;
+            this->source = source;
+            historyCurrent = 0;
+            historySize = 0;
+            lastResample.eventTime = 0;
+            lastResample.idBits.clear();
+        }
+
+        void addHistory(const InputMessage* msg) {
+            historyCurrent ^= 1;
+            if (historySize < 2) {
+                historySize += 1;
+            }
+            history[historyCurrent].initializeFrom(msg);
+        }
+
+        const History* getHistory(size_t index) const {
+            return &history[(historyCurrent + index) & 1];
+        }
+    };
+    Vector<TouchState> mTouchStates;
+
+    // Chain of batched sequence numbers.  When multiple input messages are combined into
+    // a batch, we append a record here that associates the last sequence number in the
+    // batch with the previous one.  When the finished signal is sent, we traverse the
+    // chain to individually finish all input messages that were part of the batch.
+    struct SeqChain {
+        uint32_t seq;   // sequence number of batched input message
+        uint32_t chain; // sequence number of previous batched input message
+    };
+    Vector<SeqChain> mSeqChains;
+
+    status_t consumeBatch(InputEventFactoryInterface* factory,
+            nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent);
+    status_t consumeSamples(InputEventFactoryInterface* factory,
+            Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent);
+
+    void updateTouchState(InputMessage* msg);
+    void rewriteMessage(const TouchState& state, InputMessage* msg);
+    void resampleTouchState(nsecs_t frameTime, MotionEvent* event,
+            const InputMessage *next);
+
+    ssize_t findBatch(int32_t deviceId, int32_t source) const;
+    ssize_t findTouchState(int32_t deviceId, int32_t source) const;
+
+    status_t sendUnchainedFinishedSignal(uint32_t seq, bool handled);
+
+    static void initializeKeyEvent(KeyEvent* event, const InputMessage* msg);
+    static void initializeMotionEvent(MotionEvent* event, const InputMessage* msg);
+    static void addSample(MotionEvent* event, const InputMessage* msg);
+    static bool canAddSample(const Batch& batch, const InputMessage* msg);
+    static ssize_t findSampleNoLaterThan(const Batch& batch, nsecs_t time);
+    static bool shouldResampleTool(int32_t toolType);
+
+    static bool isTouchResamplingEnabled();
+};
+
+} // namespace android
+
+#endif // _LIBINPUT_INPUT_TRANSPORT_H
diff --git a/include/input/KeyCharacterMap.h b/include/input/KeyCharacterMap.h
new file mode 100644
index 0000000..e70666a
--- /dev/null
+++ b/include/input/KeyCharacterMap.h
@@ -0,0 +1,257 @@
+/*
+ * Copyright (C) 2008 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 _LIBINPUT_KEY_CHARACTER_MAP_H
+#define _LIBINPUT_KEY_CHARACTER_MAP_H
+
+#include <stdint.h>
+
+#if HAVE_ANDROID_OS
+#include <binder/IBinder.h>
+#endif
+
+#include <input/Input.h>
+#include <utils/Errors.h>
+#include <utils/KeyedVector.h>
+#include <utils/Tokenizer.h>
+#include <utils/String8.h>
+#include <utils/Unicode.h>
+#include <utils/RefBase.h>
+
+namespace android {
+
+/**
+ * Describes a mapping from Android key codes to characters.
+ * Also specifies other functions of the keyboard such as the keyboard type
+ * and key modifier semantics.
+ *
+ * This object is immutable after it has been loaded.
+ */
+class KeyCharacterMap : public RefBase {
+public:
+    enum KeyboardType {
+        KEYBOARD_TYPE_UNKNOWN = 0,
+        KEYBOARD_TYPE_NUMERIC = 1,
+        KEYBOARD_TYPE_PREDICTIVE = 2,
+        KEYBOARD_TYPE_ALPHA = 3,
+        KEYBOARD_TYPE_FULL = 4,
+        KEYBOARD_TYPE_SPECIAL_FUNCTION = 5,
+        KEYBOARD_TYPE_OVERLAY = 6,
+    };
+
+    enum Format {
+        // Base keyboard layout, may contain device-specific options, such as "type" declaration.
+        FORMAT_BASE = 0,
+        // Overlay keyboard layout, more restrictive, may be published by applications,
+        // cannot override device-specific options.
+        FORMAT_OVERLAY = 1,
+        // Either base or overlay layout ok.
+        FORMAT_ANY = 2,
+    };
+
+    // Substitute key code and meta state for fallback action.
+    struct FallbackAction {
+        int32_t keyCode;
+        int32_t metaState;
+    };
+
+    /* Loads a key character map from a file. */
+    static status_t load(const String8& filename, Format format, sp<KeyCharacterMap>* outMap);
+
+    /* Loads a key character map from its string contents. */
+    static status_t loadContents(const String8& filename,
+            const char* contents, Format format, sp<KeyCharacterMap>* outMap);
+
+    /* Combines a base key character map and an overlay. */
+    static sp<KeyCharacterMap> combine(const sp<KeyCharacterMap>& base,
+            const sp<KeyCharacterMap>& overlay);
+
+    /* Returns an empty key character map. */
+    static sp<KeyCharacterMap> empty();
+
+    /* Gets the keyboard type. */
+    int32_t getKeyboardType() const;
+
+    /* Gets the primary character for this key as in the label physically printed on it.
+     * Returns 0 if none (eg. for non-printing keys). */
+    char16_t getDisplayLabel(int32_t keyCode) const;
+
+    /* Gets the Unicode character for the number or symbol generated by the key
+     * when the keyboard is used as a dialing pad.
+     * Returns 0 if no number or symbol is generated.
+     */
+    char16_t getNumber(int32_t keyCode) const;
+
+    /* Gets the Unicode character generated by the key and meta key modifiers.
+     * Returns 0 if no character is generated.
+     */
+    char16_t getCharacter(int32_t keyCode, int32_t metaState) const;
+
+    /* Gets the fallback action to use by default if the application does not
+     * handle the specified key.
+     * Returns true if an action was available, false if none.
+     */
+    bool getFallbackAction(int32_t keyCode, int32_t metaState,
+            FallbackAction* outFallbackAction) const;
+
+    /* Gets the first matching Unicode character that can be generated by the key,
+     * preferring the one with the specified meta key modifiers.
+     * Returns 0 if no matching character is generated.
+     */
+    char16_t getMatch(int32_t keyCode, const char16_t* chars,
+            size_t numChars, int32_t metaState) const;
+
+    /* Gets a sequence of key events that could plausibly generate the specified
+     * character sequence.  Returns false if some of the characters cannot be generated.
+     */
+    bool getEvents(int32_t deviceId, const char16_t* chars, size_t numChars,
+            Vector<KeyEvent>& outEvents) const;
+
+    /* Maps a scan code and usage code to a key code, in case this key map overrides
+     * the mapping in some way. */
+    status_t mapKey(int32_t scanCode, int32_t usageCode, int32_t* outKeyCode) const;
+
+#if HAVE_ANDROID_OS
+    /* Reads a key map from a parcel. */
+    static sp<KeyCharacterMap> readFromParcel(Parcel* parcel);
+
+    /* Writes a key map to a parcel. */
+    void writeToParcel(Parcel* parcel) const;
+#endif
+
+protected:
+    virtual ~KeyCharacterMap();
+
+private:
+    struct Behavior {
+        Behavior();
+        Behavior(const Behavior& other);
+
+        /* The next behavior in the list, or NULL if none. */
+        Behavior* next;
+
+        /* The meta key modifiers for this behavior. */
+        int32_t metaState;
+
+        /* The character to insert. */
+        char16_t character;
+
+        /* The fallback keycode if the key is not handled. */
+        int32_t fallbackKeyCode;
+    };
+
+    struct Key {
+        Key();
+        Key(const Key& other);
+        ~Key();
+
+        /* The single character label printed on the key, or 0 if none. */
+        char16_t label;
+
+        /* The number or symbol character generated by the key, or 0 if none. */
+        char16_t number;
+
+        /* The list of key behaviors sorted from most specific to least specific
+         * meta key binding. */
+        Behavior* firstBehavior;
+    };
+
+    class Parser {
+        enum State {
+            STATE_TOP = 0,
+            STATE_KEY = 1,
+        };
+
+        enum {
+            PROPERTY_LABEL = 1,
+            PROPERTY_NUMBER = 2,
+            PROPERTY_META = 3,
+        };
+
+        struct Property {
+            inline Property(int32_t property = 0, int32_t metaState = 0) :
+                    property(property), metaState(metaState) { }
+
+            int32_t property;
+            int32_t metaState;
+        };
+
+        KeyCharacterMap* mMap;
+        Tokenizer* mTokenizer;
+        Format mFormat;
+        State mState;
+        int32_t mKeyCode;
+
+    public:
+        Parser(KeyCharacterMap* map, Tokenizer* tokenizer, Format format);
+        ~Parser();
+        status_t parse();
+
+    private:
+        status_t parseType();
+        status_t parseMap();
+        status_t parseMapKey();
+        status_t parseKey();
+        status_t parseKeyProperty();
+        status_t finishKey(Key* key);
+        status_t parseModifier(const String8& token, int32_t* outMetaState);
+        status_t parseCharacterLiteral(char16_t* outCharacter);
+    };
+
+    static sp<KeyCharacterMap> sEmpty;
+
+    KeyedVector<int32_t, Key*> mKeys;
+    int mType;
+
+    KeyedVector<int32_t, int32_t> mKeysByScanCode;
+    KeyedVector<int32_t, int32_t> mKeysByUsageCode;
+
+    KeyCharacterMap();
+    KeyCharacterMap(const KeyCharacterMap& other);
+
+    bool getKey(int32_t keyCode, const Key** outKey) const;
+    bool getKeyBehavior(int32_t keyCode, int32_t metaState,
+            const Key** outKey, const Behavior** outBehavior) const;
+    static bool matchesMetaState(int32_t eventMetaState, int32_t behaviorMetaState);
+
+    bool findKey(char16_t ch, int32_t* outKeyCode, int32_t* outMetaState) const;
+
+    static status_t load(Tokenizer* tokenizer, Format format, sp<KeyCharacterMap>* outMap);
+
+    static void addKey(Vector<KeyEvent>& outEvents,
+            int32_t deviceId, int32_t keyCode, int32_t metaState, bool down, nsecs_t time);
+    static void addMetaKeys(Vector<KeyEvent>& outEvents,
+            int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
+            int32_t* currentMetaState);
+    static bool addSingleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
+            int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
+            int32_t keyCode, int32_t keyMetaState,
+            int32_t* currentMetaState);
+    static void addDoubleEphemeralMetaKey(Vector<KeyEvent>& outEvents,
+            int32_t deviceId, int32_t metaState, bool down, nsecs_t time,
+            int32_t leftKeyCode, int32_t leftKeyMetaState,
+            int32_t rightKeyCode, int32_t rightKeyMetaState,
+            int32_t eitherKeyMetaState,
+            int32_t* currentMetaState);
+    static void addLockedMetaKey(Vector<KeyEvent>& outEvents,
+            int32_t deviceId, int32_t metaState, nsecs_t time,
+            int32_t keyCode, int32_t keyMetaState,
+            int32_t* currentMetaState);
+};
+
+} // namespace android
+
+#endif // _LIBINPUT_KEY_CHARACTER_MAP_H
diff --git a/include/input/KeyLayoutMap.h b/include/input/KeyLayoutMap.h
new file mode 100644
index 0000000..eec11cf
--- /dev/null
+++ b/include/input/KeyLayoutMap.h
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2008 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 _LIBINPUT_KEY_LAYOUT_MAP_H
+#define _LIBINPUT_KEY_LAYOUT_MAP_H
+
+#include <stdint.h>
+#include <utils/Errors.h>
+#include <utils/KeyedVector.h>
+#include <utils/Tokenizer.h>
+#include <utils/RefBase.h>
+
+namespace android {
+
+struct AxisInfo {
+    enum Mode {
+        // Axis value is reported directly.
+        MODE_NORMAL = 0,
+        // Axis value should be inverted before reporting.
+        MODE_INVERT = 1,
+        // Axis value should be split into two axes
+        MODE_SPLIT = 2,
+    };
+
+    // Axis mode.
+    Mode mode;
+
+    // Axis id.
+    // When split, this is the axis used for values smaller than the split position.
+    int32_t axis;
+
+    // When split, this is the axis used for values after higher than the split position.
+    int32_t highAxis;
+
+    // The split value, or 0 if not split.
+    int32_t splitValue;
+
+    // The flat value, or -1 if none.
+    int32_t flatOverride;
+
+    AxisInfo() : mode(MODE_NORMAL), axis(-1), highAxis(-1), splitValue(0), flatOverride(-1) {
+    }
+};
+
+/**
+ * Describes a mapping from keyboard scan codes and joystick axes to Android key codes and axes.
+ *
+ * This object is immutable after it has been loaded.
+ */
+class KeyLayoutMap : public RefBase {
+public:
+    static status_t load(const String8& filename, sp<KeyLayoutMap>* outMap);
+
+    status_t mapKey(int32_t scanCode, int32_t usageCode,
+            int32_t* outKeyCode, uint32_t* outFlags) const;
+    status_t findScanCodesForKey(int32_t keyCode, Vector<int32_t>* outScanCodes) const;
+
+    status_t mapAxis(int32_t scanCode, AxisInfo* outAxisInfo) const;
+
+protected:
+    virtual ~KeyLayoutMap();
+
+private:
+    struct Key {
+        int32_t keyCode;
+        uint32_t flags;
+    };
+
+    KeyedVector<int32_t, Key> mKeysByScanCode;
+    KeyedVector<int32_t, Key> mKeysByUsageCode;
+    KeyedVector<int32_t, AxisInfo> mAxes;
+
+    KeyLayoutMap();
+
+    const Key* getKey(int32_t scanCode, int32_t usageCode) const;
+
+    class Parser {
+        KeyLayoutMap* mMap;
+        Tokenizer* mTokenizer;
+
+    public:
+        Parser(KeyLayoutMap* map, Tokenizer* tokenizer);
+        ~Parser();
+        status_t parse();
+
+    private:
+        status_t parseKey();
+        status_t parseAxis();
+    };
+};
+
+} // namespace android
+
+#endif // _LIBINPUT_KEY_LAYOUT_MAP_H
diff --git a/include/input/Keyboard.h b/include/input/Keyboard.h
new file mode 100644
index 0000000..846cb0c
--- /dev/null
+++ b/include/input/Keyboard.h
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef _LIBINPUT_KEYBOARD_H
+#define _LIBINPUT_KEYBOARD_H
+
+#include <input/Input.h>
+#include <input/InputDevice.h>
+#include <utils/Errors.h>
+#include <utils/String8.h>
+#include <utils/PropertyMap.h>
+
+namespace android {
+
+enum {
+    /* Device id of the built in keyboard. */
+    DEVICE_ID_BUILT_IN_KEYBOARD = 0,
+
+    /* Device id of a generic virtual keyboard with a full layout that can be used
+     * to synthesize key events. */
+    DEVICE_ID_VIRTUAL_KEYBOARD = -1,
+};
+
+class KeyLayoutMap;
+class KeyCharacterMap;
+
+/**
+ * Loads the key layout map and key character map for a keyboard device.
+ */
+class KeyMap {
+public:
+    String8 keyLayoutFile;
+    sp<KeyLayoutMap> keyLayoutMap;
+
+    String8 keyCharacterMapFile;
+    sp<KeyCharacterMap> keyCharacterMap;
+
+    KeyMap();
+    ~KeyMap();
+
+    status_t load(const InputDeviceIdentifier& deviceIdenfier,
+            const PropertyMap* deviceConfiguration);
+
+    inline bool haveKeyLayout() const {
+        return !keyLayoutFile.isEmpty();
+    }
+
+    inline bool haveKeyCharacterMap() const {
+        return !keyCharacterMapFile.isEmpty();
+    }
+
+    inline bool isComplete() const {
+        return haveKeyLayout() && haveKeyCharacterMap();
+    }
+
+private:
+    bool probeKeyMap(const InputDeviceIdentifier& deviceIdentifier, const String8& name);
+    status_t loadKeyLayout(const InputDeviceIdentifier& deviceIdentifier, const String8& name);
+    status_t loadKeyCharacterMap(const InputDeviceIdentifier& deviceIdentifier,
+            const String8& name);
+    String8 getPath(const InputDeviceIdentifier& deviceIdentifier,
+            const String8& name, InputDeviceConfigurationFileType type);
+};
+
+/**
+ * Returns true if the keyboard is eligible for use as a built-in keyboard.
+ */
+extern bool isEligibleBuiltInKeyboard(const InputDeviceIdentifier& deviceIdentifier,
+        const PropertyMap* deviceConfiguration, const KeyMap* keyMap);
+
+/**
+ * Gets a key code by its short form label, eg. "HOME".
+ * Returns 0 if unknown.
+ */
+extern int32_t getKeyCodeByLabel(const char* label);
+
+/**
+ * Gets a key flag by its short form label, eg. "WAKE".
+ * Returns 0 if unknown.
+ */
+extern uint32_t getKeyFlagByLabel(const char* label);
+
+/**
+ * Gets a axis by its short form label, eg. "X".
+ * Returns -1 if unknown.
+ */
+extern int32_t getAxisByLabel(const char* label);
+
+/**
+ * Gets a axis label by its id.
+ * Returns NULL if unknown.
+ */
+extern const char* getAxisLabel(int32_t axisId);
+
+/**
+ * Updates a meta state field when a key is pressed or released.
+ */
+extern int32_t updateMetaState(int32_t keyCode, bool down, int32_t oldMetaState);
+
+/**
+ * Returns true if a key is a meta key like ALT or CAPS_LOCK.
+ */
+extern bool isMetaKey(int32_t keyCode);
+
+} // namespace android
+
+#endif // _LIBINPUT_KEYBOARD_H
diff --git a/include/input/KeycodeLabels.h b/include/input/KeycodeLabels.h
index 1e91ea8..c64c5d8 100644
--- a/include/input/KeycodeLabels.h
+++ b/include/input/KeycodeLabels.h
@@ -1,6 +1,322 @@
+/*
+ * Copyright (C) 2008 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 _LIBINPUT_KEYCODE_LABELS_H
 #define _LIBINPUT_KEYCODE_LABELS_H
 
-#include <androidfw/KeycodeLabels.h>
+#include <android/keycodes.h>
+
+struct KeycodeLabel {
+    const char *literal;
+    int value;
+};
+
+static const KeycodeLabel KEYCODES[] = {
+    { "SOFT_LEFT", 1 },
+    { "SOFT_RIGHT", 2 },
+    { "HOME", 3 },
+    { "BACK", 4 },
+    { "CALL", 5 },
+    { "ENDCALL", 6 },
+    { "0", 7 },
+    { "1", 8 },
+    { "2", 9 },
+    { "3", 10 },
+    { "4", 11 },
+    { "5", 12 },
+    { "6", 13 },
+    { "7", 14 },
+    { "8", 15 },
+    { "9", 16 },
+    { "STAR", 17 },
+    { "POUND", 18 },
+    { "DPAD_UP", 19 },
+    { "DPAD_DOWN", 20 },
+    { "DPAD_LEFT", 21 },
+    { "DPAD_RIGHT", 22 },
+    { "DPAD_CENTER", 23 },
+    { "VOLUME_UP", 24 },
+    { "VOLUME_DOWN", 25 },
+    { "POWER", 26 },
+    { "CAMERA", 27 },
+    { "CLEAR", 28 },
+    { "A", 29 },
+    { "B", 30 },
+    { "C", 31 },
+    { "D", 32 },
+    { "E", 33 },
+    { "F", 34 },
+    { "G", 35 },
+    { "H", 36 },
+    { "I", 37 },
+    { "J", 38 },
+    { "K", 39 },
+    { "L", 40 },
+    { "M", 41 },
+    { "N", 42 },
+    { "O", 43 },
+    { "P", 44 },
+    { "Q", 45 },
+    { "R", 46 },
+    { "S", 47 },
+    { "T", 48 },
+    { "U", 49 },
+    { "V", 50 },
+    { "W", 51 },
+    { "X", 52 },
+    { "Y", 53 },
+    { "Z", 54 },
+    { "COMMA", 55 },
+    { "PERIOD", 56 },
+    { "ALT_LEFT", 57 },
+    { "ALT_RIGHT", 58 },
+    { "SHIFT_LEFT", 59 },
+    { "SHIFT_RIGHT", 60 },
+    { "TAB", 61 },
+    { "SPACE", 62 },
+    { "SYM", 63 },
+    { "EXPLORER", 64 },
+    { "ENVELOPE", 65 },
+    { "ENTER", 66 },
+    { "DEL", 67 },
+    { "GRAVE", 68 },
+    { "MINUS", 69 },
+    { "EQUALS", 70 },
+    { "LEFT_BRACKET", 71 },
+    { "RIGHT_BRACKET", 72 },
+    { "BACKSLASH", 73 },
+    { "SEMICOLON", 74 },
+    { "APOSTROPHE", 75 },
+    { "SLASH", 76 },
+    { "AT", 77 },
+    { "NUM", 78 },
+    { "HEADSETHOOK", 79 },
+    { "FOCUS", 80 },
+    { "PLUS", 81 },
+    { "MENU", 82 },
+    { "NOTIFICATION", 83 },
+    { "SEARCH", 84 },
+    { "MEDIA_PLAY_PAUSE", 85 },
+    { "MEDIA_STOP", 86 },
+    { "MEDIA_NEXT", 87 },
+    { "MEDIA_PREVIOUS", 88 },
+    { "MEDIA_REWIND", 89 },
+    { "MEDIA_FAST_FORWARD", 90 },
+    { "MUTE", 91 },
+    { "PAGE_UP", 92 },
+    { "PAGE_DOWN", 93 },
+    { "PICTSYMBOLS", 94 },
+    { "SWITCH_CHARSET", 95 },
+    { "BUTTON_A", 96 },
+    { "BUTTON_B", 97 },
+    { "BUTTON_C", 98 },
+    { "BUTTON_X", 99 },
+    { "BUTTON_Y", 100 },
+    { "BUTTON_Z", 101 },
+    { "BUTTON_L1", 102 },
+    { "BUTTON_R1", 103 },
+    { "BUTTON_L2", 104 },
+    { "BUTTON_R2", 105 },
+    { "BUTTON_THUMBL", 106 },
+    { "BUTTON_THUMBR", 107 },
+    { "BUTTON_START", 108 },
+    { "BUTTON_SELECT", 109 },
+    { "BUTTON_MODE", 110 },
+    { "ESCAPE", 111 },
+    { "FORWARD_DEL", 112 },
+    { "CTRL_LEFT", 113 },
+    { "CTRL_RIGHT", 114 },
+    { "CAPS_LOCK", 115 },
+    { "SCROLL_LOCK", 116 },
+    { "META_LEFT", 117 },
+    { "META_RIGHT", 118 },
+    { "FUNCTION", 119 },
+    { "SYSRQ", 120 },
+    { "BREAK", 121 },
+    { "MOVE_HOME", 122 },
+    { "MOVE_END", 123 },
+    { "INSERT", 124 },
+    { "FORWARD", 125 },
+    { "MEDIA_PLAY", 126 },
+    { "MEDIA_PAUSE", 127 },
+    { "MEDIA_CLOSE", 128 },
+    { "MEDIA_EJECT", 129 },
+    { "MEDIA_RECORD", 130 },
+    { "F1", 131 },
+    { "F2", 132 },
+    { "F3", 133 },
+    { "F4", 134 },
+    { "F5", 135 },
+    { "F6", 136 },
+    { "F7", 137 },
+    { "F8", 138 },
+    { "F9", 139 },
+    { "F10", 140 },
+    { "F11", 141 },
+    { "F12", 142 },
+    { "NUM_LOCK", 143 },
+    { "NUMPAD_0", 144 },
+    { "NUMPAD_1", 145 },
+    { "NUMPAD_2", 146 },
+    { "NUMPAD_3", 147 },
+    { "NUMPAD_4", 148 },
+    { "NUMPAD_5", 149 },
+    { "NUMPAD_6", 150 },
+    { "NUMPAD_7", 151 },
+    { "NUMPAD_8", 152 },
+    { "NUMPAD_9", 153 },
+    { "NUMPAD_DIVIDE", 154 },
+    { "NUMPAD_MULTIPLY", 155 },
+    { "NUMPAD_SUBTRACT", 156 },
+    { "NUMPAD_ADD", 157 },
+    { "NUMPAD_DOT", 158 },
+    { "NUMPAD_COMMA", 159 },
+    { "NUMPAD_ENTER", 160 },
+    { "NUMPAD_EQUALS", 161 },
+    { "NUMPAD_LEFT_PAREN", 162 },
+    { "NUMPAD_RIGHT_PAREN", 163 },
+    { "VOLUME_MUTE", 164 },
+    { "INFO", 165 },
+    { "CHANNEL_UP", 166 },
+    { "CHANNEL_DOWN", 167 },
+    { "ZOOM_IN", 168 },
+    { "ZOOM_OUT", 169 },
+    { "TV", 170 },
+    { "WINDOW", 171 },
+    { "GUIDE", 172 },
+    { "DVR", 173 },
+    { "BOOKMARK", 174 },
+    { "CAPTIONS", 175 },
+    { "SETTINGS", 176 },
+    { "TV_POWER", 177 },
+    { "TV_INPUT", 178 },
+    { "STB_POWER", 179 },
+    { "STB_INPUT", 180 },
+    { "AVR_POWER", 181 },
+    { "AVR_INPUT", 182 },
+    { "PROG_RED", 183 },
+    { "PROG_GREEN", 184 },
+    { "PROG_YELLOW", 185 },
+    { "PROG_BLUE", 186 },
+    { "APP_SWITCH", 187 },
+    { "BUTTON_1", 188 },
+    { "BUTTON_2", 189 },
+    { "BUTTON_3", 190 },
+    { "BUTTON_4", 191 },
+    { "BUTTON_5", 192 },
+    { "BUTTON_6", 193 },
+    { "BUTTON_7", 194 },
+    { "BUTTON_8", 195 },
+    { "BUTTON_9", 196 },
+    { "BUTTON_10", 197 },
+    { "BUTTON_11", 198 },
+    { "BUTTON_12", 199 },
+    { "BUTTON_13", 200 },
+    { "BUTTON_14", 201 },
+    { "BUTTON_15", 202 },
+    { "BUTTON_16", 203 },
+    { "LANGUAGE_SWITCH", 204 },
+    { "MANNER_MODE", 205 },
+    { "3D_MODE", 206 },
+    { "CONTACTS", 207 },
+    { "CALENDAR", 208 },
+    { "MUSIC", 209 },
+    { "CALCULATOR", 210 },
+    { "ZENKAKU_HANKAKU", 211 },
+    { "EISU", 212 },
+    { "MUHENKAN", 213 },
+    { "HENKAN", 214 },
+    { "KATAKANA_HIRAGANA", 215 },
+    { "YEN", 216 },
+    { "RO", 217 },
+    { "KANA", 218 },
+    { "ASSIST", 219 },
+    { "BRIGHTNESS_DOWN", 220 },
+    { "BRIGHTNESS_UP", 221 },
+    { "MEDIA_AUDIO_TRACK", 222 },
+
+    // NOTE: If you add a new keycode here you must also add it to several other files.
+    //       Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
+
+    { NULL, 0 }
+};
+
+// NOTE: If you edit these flags, also edit policy flags in Input.h.
+static const KeycodeLabel FLAGS[] = {
+    { "WAKE", 0x00000001 },
+    { "WAKE_DROPPED", 0x00000002 },
+    { "SHIFT", 0x00000004 },
+    { "CAPS_LOCK", 0x00000008 },
+    { "ALT", 0x00000010 },
+    { "ALT_GR", 0x00000020 },
+    { "MENU", 0x00000040 },
+    { "LAUNCHER", 0x00000080 },
+    { "VIRTUAL", 0x00000100 },
+    { "FUNCTION", 0x00000200 },
+    { NULL, 0 }
+};
+
+static const KeycodeLabel AXES[] = {
+    { "X", 0 },
+    { "Y", 1 },
+    { "PRESSURE", 2 },
+    { "SIZE", 3 },
+    { "TOUCH_MAJOR", 4 },
+    { "TOUCH_MINOR", 5 },
+    { "TOOL_MAJOR", 6 },
+    { "TOOL_MINOR", 7 },
+    { "ORIENTATION", 8 },
+    { "VSCROLL", 9 },
+    { "HSCROLL", 10 },
+    { "Z", 11 },
+    { "RX", 12 },
+    { "RY", 13 },
+    { "RZ", 14 },
+    { "HAT_X", 15 },
+    { "HAT_Y", 16 },
+    { "LTRIGGER", 17 },
+    { "RTRIGGER", 18 },
+    { "THROTTLE", 19 },
+    { "RUDDER", 20 },
+    { "WHEEL", 21 },
+    { "GAS", 22 },
+    { "BRAKE", 23 },
+    { "DISTANCE", 24 },
+    { "TILT", 25 },
+    { "GENERIC_1", 32 },
+    { "GENERIC_2", 33 },
+    { "GENERIC_3", 34 },
+    { "GENERIC_4", 35 },
+    { "GENERIC_5", 36 },
+    { "GENERIC_6", 37 },
+    { "GENERIC_7", 38 },
+    { "GENERIC_8", 39 },
+    { "GENERIC_9", 40 },
+    { "GENERIC_10", 41 },
+    { "GENERIC_11", 42 },
+    { "GENERIC_12", 43 },
+    { "GENERIC_13", 44 },
+    { "GENERIC_14", 45 },
+    { "GENERIC_15", 46 },
+    { "GENERIC_16", 47 },
+
+    // NOTE: If you add a new axis here you must also add it to several other files.
+    //       Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list.
+
+    { NULL, -1 }
+};
 
 #endif // _LIBINPUT_KEYCODE_LABELS_H
diff --git a/include/input/VelocityControl.h b/include/input/VelocityControl.h
new file mode 100644
index 0000000..1acc2ae
--- /dev/null
+++ b/include/input/VelocityControl.h
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2012 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 _LIBINPUT_VELOCITY_CONTROL_H
+#define _LIBINPUT_VELOCITY_CONTROL_H
+
+#include <input/Input.h>
+#include <input/VelocityTracker.h>
+#include <utils/Timers.h>
+
+namespace android {
+
+/*
+ * Specifies parameters that govern pointer or wheel acceleration.
+ */
+struct VelocityControlParameters {
+    // A scale factor that is multiplied with the raw velocity deltas
+    // prior to applying any other velocity control factors.  The scale
+    // factor should be used to adapt the input device resolution
+    // (eg. counts per inch) to the output device resolution (eg. pixels per inch).
+    //
+    // Must be a positive value.
+    // Default is 1.0 (no scaling).
+    float scale;
+
+    // The scaled speed at which acceleration begins to be applied.
+    // This value establishes the upper bound of a low speed regime for
+    // small precise motions that are performed without any acceleration.
+    //
+    // Must be a non-negative value.
+    // Default is 0.0 (no low threshold).
+    float lowThreshold;
+
+    // The scaled speed at which maximum acceleration is applied.
+    // The difference between highThreshold and lowThreshold controls
+    // the range of speeds over which the acceleration factor is interpolated.
+    // The wider the range, the smoother the acceleration.
+    //
+    // Must be a non-negative value greater than or equal to lowThreshold.
+    // Default is 0.0 (no high threshold).
+    float highThreshold;
+
+    // The acceleration factor.
+    // When the speed is above the low speed threshold, the velocity will scaled
+    // by an interpolated value between 1.0 and this amount.
+    //
+    // Must be a positive greater than or equal to 1.0.
+    // Default is 1.0 (no acceleration).
+    float acceleration;
+
+    VelocityControlParameters() :
+            scale(1.0f), lowThreshold(0.0f), highThreshold(0.0f), acceleration(1.0f) {
+    }
+
+    VelocityControlParameters(float scale, float lowThreshold,
+            float highThreshold, float acceleration) :
+            scale(scale), lowThreshold(lowThreshold),
+            highThreshold(highThreshold), acceleration(acceleration) {
+    }
+};
+
+/*
+ * Implements mouse pointer and wheel speed control and acceleration.
+ */
+class VelocityControl {
+public:
+    VelocityControl();
+
+    /* Sets the various parameters. */
+    void setParameters(const VelocityControlParameters& parameters);
+
+    /* Resets the current movement counters to zero.
+     * This has the effect of nullifying any acceleration. */
+    void reset();
+
+    /* Translates a raw movement delta into an appropriately
+     * scaled / accelerated delta based on the current velocity. */
+    void move(nsecs_t eventTime, float* deltaX, float* deltaY);
+
+private:
+    // If no movements are received within this amount of time,
+    // we assume the movement has stopped and reset the movement counters.
+    static const nsecs_t STOP_TIME = 500 * 1000000; // 500 ms
+
+    VelocityControlParameters mParameters;
+
+    nsecs_t mLastMovementTime;
+    VelocityTracker::Position mRawPosition;
+    VelocityTracker mVelocityTracker;
+};
+
+} // namespace android
+
+#endif // _LIBINPUT_VELOCITY_CONTROL_H
diff --git a/include/input/VelocityTracker.h b/include/input/VelocityTracker.h
new file mode 100644
index 0000000..795f575
--- /dev/null
+++ b/include/input/VelocityTracker.h
@@ -0,0 +1,269 @@
+/*
+ * Copyright (C) 2012 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 _LIBINPUT_VELOCITY_TRACKER_H
+#define _LIBINPUT_VELOCITY_TRACKER_H
+
+#include <input/Input.h>
+#include <utils/Timers.h>
+#include <utils/BitSet.h>
+
+namespace android {
+
+class VelocityTrackerStrategy;
+
+/*
+ * Calculates the velocity of pointer movements over time.
+ */
+class VelocityTracker {
+public:
+    struct Position {
+        float x, y;
+    };
+
+    struct Estimator {
+        static const size_t MAX_DEGREE = 4;
+
+        // Estimator time base.
+        nsecs_t time;
+
+        // Polynomial coefficients describing motion in X and Y.
+        float xCoeff[MAX_DEGREE + 1], yCoeff[MAX_DEGREE + 1];
+
+        // Polynomial degree (number of coefficients), or zero if no information is
+        // available.
+        uint32_t degree;
+
+        // Confidence (coefficient of determination), between 0 (no fit) and 1 (perfect fit).
+        float confidence;
+
+        inline void clear() {
+            time = 0;
+            degree = 0;
+            confidence = 0;
+            for (size_t i = 0; i <= MAX_DEGREE; i++) {
+                xCoeff[i] = 0;
+                yCoeff[i] = 0;
+            }
+        }
+    };
+
+    // Creates a velocity tracker using the specified strategy.
+    // If strategy is NULL, uses the default strategy for the platform.
+    VelocityTracker(const char* strategy = NULL);
+
+    ~VelocityTracker();
+
+    // Resets the velocity tracker state.
+    void clear();
+
+    // Resets the velocity tracker state for specific pointers.
+    // Call this method when some pointers have changed and may be reusing
+    // an id that was assigned to a different pointer earlier.
+    void clearPointers(BitSet32 idBits);
+
+    // Adds movement information for a set of pointers.
+    // The idBits bitfield specifies the pointer ids of the pointers whose positions
+    // are included in the movement.
+    // The positions array contains position information for each pointer in order by
+    // increasing id.  Its size should be equal to the number of one bits in idBits.
+    void addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions);
+
+    // Adds movement information for all pointers in a MotionEvent, including historical samples.
+    void addMovement(const MotionEvent* event);
+
+    // Gets the velocity of the specified pointer id in position units per second.
+    // Returns false and sets the velocity components to zero if there is
+    // insufficient movement information for the pointer.
+    bool getVelocity(uint32_t id, float* outVx, float* outVy) const;
+
+    // Gets an estimator for the recent movements of the specified pointer id.
+    // Returns false and clears the estimator if there is no information available
+    // about the pointer.
+    bool getEstimator(uint32_t id, Estimator* outEstimator) const;
+
+    // Gets the active pointer id, or -1 if none.
+    inline int32_t getActivePointerId() const { return mActivePointerId; }
+
+    // Gets a bitset containing all pointer ids from the most recent movement.
+    inline BitSet32 getCurrentPointerIdBits() const { return mCurrentPointerIdBits; }
+
+private:
+    static const char* DEFAULT_STRATEGY;
+
+    nsecs_t mLastEventTime;
+    BitSet32 mCurrentPointerIdBits;
+    int32_t mActivePointerId;
+    VelocityTrackerStrategy* mStrategy;
+
+    bool configureStrategy(const char* strategy);
+
+    static VelocityTrackerStrategy* createStrategy(const char* strategy);
+};
+
+
+/*
+ * Implements a particular velocity tracker algorithm.
+ */
+class VelocityTrackerStrategy {
+protected:
+    VelocityTrackerStrategy() { }
+
+public:
+    virtual ~VelocityTrackerStrategy() { }
+
+    virtual void clear() = 0;
+    virtual void clearPointers(BitSet32 idBits) = 0;
+    virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
+            const VelocityTracker::Position* positions) = 0;
+    virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const = 0;
+};
+
+
+/*
+ * Velocity tracker algorithm based on least-squares linear regression.
+ */
+class LeastSquaresVelocityTrackerStrategy : public VelocityTrackerStrategy {
+public:
+    enum Weighting {
+        // No weights applied.  All data points are equally reliable.
+        WEIGHTING_NONE,
+
+        // Weight by time delta.  Data points clustered together are weighted less.
+        WEIGHTING_DELTA,
+
+        // Weight such that points within a certain horizon are weighed more than those
+        // outside of that horizon.
+        WEIGHTING_CENTRAL,
+
+        // Weight such that points older than a certain amount are weighed less.
+        WEIGHTING_RECENT,
+    };
+
+    // Degree must be no greater than Estimator::MAX_DEGREE.
+    LeastSquaresVelocityTrackerStrategy(uint32_t degree, Weighting weighting = WEIGHTING_NONE);
+    virtual ~LeastSquaresVelocityTrackerStrategy();
+
+    virtual void clear();
+    virtual void clearPointers(BitSet32 idBits);
+    virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
+            const VelocityTracker::Position* positions);
+    virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
+
+private:
+    // Sample horizon.
+    // We don't use too much history by default since we want to react to quick
+    // changes in direction.
+    static const nsecs_t HORIZON = 100 * 1000000; // 100 ms
+
+    // Number of samples to keep.
+    static const uint32_t HISTORY_SIZE = 20;
+
+    struct Movement {
+        nsecs_t eventTime;
+        BitSet32 idBits;
+        VelocityTracker::Position positions[MAX_POINTERS];
+
+        inline const VelocityTracker::Position& getPosition(uint32_t id) const {
+            return positions[idBits.getIndexOfBit(id)];
+        }
+    };
+
+    float chooseWeight(uint32_t index) const;
+
+    const uint32_t mDegree;
+    const Weighting mWeighting;
+    uint32_t mIndex;
+    Movement mMovements[HISTORY_SIZE];
+};
+
+
+/*
+ * Velocity tracker algorithm that uses an IIR filter.
+ */
+class IntegratingVelocityTrackerStrategy : public VelocityTrackerStrategy {
+public:
+    // Degree must be 1 or 2.
+    IntegratingVelocityTrackerStrategy(uint32_t degree);
+    ~IntegratingVelocityTrackerStrategy();
+
+    virtual void clear();
+    virtual void clearPointers(BitSet32 idBits);
+    virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
+            const VelocityTracker::Position* positions);
+    virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
+
+private:
+    // Current state estimate for a particular pointer.
+    struct State {
+        nsecs_t updateTime;
+        uint32_t degree;
+
+        float xpos, xvel, xaccel;
+        float ypos, yvel, yaccel;
+    };
+
+    const uint32_t mDegree;
+    BitSet32 mPointerIdBits;
+    State mPointerState[MAX_POINTER_ID + 1];
+
+    void initState(State& state, nsecs_t eventTime, float xpos, float ypos) const;
+    void updateState(State& state, nsecs_t eventTime, float xpos, float ypos) const;
+    void populateEstimator(const State& state, VelocityTracker::Estimator* outEstimator) const;
+};
+
+
+/*
+ * Velocity tracker strategy used prior to ICS.
+ */
+class LegacyVelocityTrackerStrategy : public VelocityTrackerStrategy {
+public:
+    LegacyVelocityTrackerStrategy();
+    virtual ~LegacyVelocityTrackerStrategy();
+
+    virtual void clear();
+    virtual void clearPointers(BitSet32 idBits);
+    virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
+            const VelocityTracker::Position* positions);
+    virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
+
+private:
+    // Oldest sample to consider when calculating the velocity.
+    static const nsecs_t HORIZON = 200 * 1000000; // 100 ms
+
+    // Number of samples to keep.
+    static const uint32_t HISTORY_SIZE = 20;
+
+    // The minimum duration between samples when estimating velocity.
+    static const nsecs_t MIN_DURATION = 10 * 1000000; // 10 ms
+
+    struct Movement {
+        nsecs_t eventTime;
+        BitSet32 idBits;
+        VelocityTracker::Position positions[MAX_POINTERS];
+
+        inline const VelocityTracker::Position& getPosition(uint32_t id) const {
+            return positions[idBits.getIndexOfBit(id)];
+        }
+    };
+
+    uint32_t mIndex;
+    Movement mMovements[HISTORY_SIZE];
+};
+
+} // namespace android
+
+#endif // _LIBINPUT_VELOCITY_TRACKER_H
diff --git a/include/input/VirtualKeyMap.h b/include/input/VirtualKeyMap.h
new file mode 100644
index 0000000..e245ead
--- /dev/null
+++ b/include/input/VirtualKeyMap.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 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.
+ */
+
+#ifndef _LIBINPUT_VIRTUAL_KEY_MAP_H
+#define _LIBINPUT_VIRTUAL_KEY_MAP_H
+
+#include <stdint.h>
+
+#include <input/Input.h>
+#include <utils/Errors.h>
+#include <utils/KeyedVector.h>
+#include <utils/Tokenizer.h>
+#include <utils/String8.h>
+#include <utils/Unicode.h>
+
+namespace android {
+
+/* Describes a virtual key. */
+struct VirtualKeyDefinition {
+    int32_t scanCode;
+
+    // configured position data, specified in display coords
+    int32_t centerX;
+    int32_t centerY;
+    int32_t width;
+    int32_t height;
+};
+
+
+/**
+ * Describes a collection of virtual keys on a touch screen in terms of
+ * virtual scan codes and hit rectangles.
+ *
+ * This object is immutable after it has been loaded.
+ */
+class VirtualKeyMap {
+public:
+    ~VirtualKeyMap();
+
+    static status_t load(const String8& filename, VirtualKeyMap** outMap);
+
+    inline const Vector<VirtualKeyDefinition>& getVirtualKeys() const {
+        return mVirtualKeys;
+    }
+
+private:
+    class Parser {
+        VirtualKeyMap* mMap;
+        Tokenizer* mTokenizer;
+
+    public:
+        Parser(VirtualKeyMap* map, Tokenizer* tokenizer);
+        ~Parser();
+        status_t parse();
+
+    private:
+        bool consumeFieldDelimiterAndSkipWhitespace();
+        bool parseNextIntField(int32_t* outValue);
+    };
+
+    Vector<VirtualKeyDefinition> mVirtualKeys;
+
+    VirtualKeyMap();
+};
+
+} // namespace android
+
+#endif // _LIBINPUT_KEY_CHARACTER_MAP_H
diff --git a/include/media/drm/DrmAPI.h b/include/media/drm/DrmAPI.h
index fbf93bc..95bdf77 100644
--- a/include/media/drm/DrmAPI.h
+++ b/include/media/drm/DrmAPI.h
@@ -60,6 +60,11 @@
         // given crypto scheme, which is specified by a UUID.
         virtual bool isCryptoSchemeSupported(const uint8_t uuid[16]) = 0;
 
+        // DrmFactory::isContentTypeSupported can be called to determine
+        // if the plugin factory is able to construct plugins that support a
+        // given media container format specified by mimeType
+        virtual bool isContentTypeSupported(const String8 &mimeType) = 0;
+
         // Construct a DrmPlugin for the crypto scheme specified by UUID.
         virtual status_t createDrmPlugin(
                 const uint8_t uuid[16], DrmPlugin **plugin) = 0;
diff --git a/include/media/hardware/HDCPAPI.h b/include/media/hardware/HDCPAPI.h
index 147448e..d4abb3f 100644
--- a/include/media/hardware/HDCPAPI.h
+++ b/include/media/hardware/HDCPAPI.h
@@ -19,6 +19,7 @@
 #define HDCP_API_H_
 
 #include <utils/Errors.h>
+#include <system/window.h>
 
 namespace android {
 
@@ -56,6 +57,19 @@
         HDCP_SESSION_ESTABLISHED,
     };
 
+    // HDCPModule capability bit masks
+    enum {
+        // HDCP_CAPS_ENCRYPT: mandatory, meaning the HDCP module can encrypt
+        // from an input byte-array buffer to an output byte-array buffer
+        HDCP_CAPS_ENCRYPT = (1 << 0),
+        // HDCP_CAPS_ENCRYPT_NATIVE: the HDCP module supports encryption from
+        // a native buffer to an output byte-array buffer. The format of the
+        // input native buffer is specific to vendor's encoder implementation.
+        // It is the same format as that used by the encoder when
+        // "storeMetaDataInBuffers" extension is enabled on its output port.
+        HDCP_CAPS_ENCRYPT_NATIVE = (1 << 1),
+    };
+
     // Module can call the notification function to signal completion/failure
     // of asynchronous operations (such as initialization) or out of band
     // events.
@@ -90,6 +104,20 @@
         return INVALID_OPERATION;
     }
 
+    // Encrypt data according to the HDCP spec. "size" bytes of data starting
+    // at location "offset" are available in "buffer" (buffer handle). "size"
+    // may not be a multiple of 128 bits (16 bytes). An equal number of
+    // encrypted bytes should be written to the buffer at "outData" (virtual
+    // address). This operation is to be synchronous, i.e. this call does not
+    // return until outData contains size bytes of encrypted data.
+    // streamCTR will be assigned by the caller (to 0 for the first PES stream,
+    // 1 for the second and so on)
+    // inputCTR _will_be_maintained_by_the_callee_ for each PES stream.
+    virtual status_t encryptNative(
+            buffer_handle_t buffer, size_t offset, size_t size,
+            uint32_t streamCTR, uint64_t *outInputCTR, void *outData) {
+        return INVALID_OPERATION;
+    }
     // DECRYPTION only:
     // Decrypt data according to the HDCP spec.
     // "size" bytes of encrypted data are available at "inData"
diff --git a/include/media/hardware/HardwareAPI.h b/include/media/hardware/HardwareAPI.h
index cc43bf6..de3aeb1 100644
--- a/include/media/hardware/HardwareAPI.h
+++ b/include/media/hardware/HardwareAPI.h
@@ -18,7 +18,8 @@
 
 #define HARDWARE_API_H_
 
-#include <OMXPluginBase.h>
+#include <media/hardware/OMXPluginBase.h>
+#include <media/hardware/MetadataBufferType.h>
 #include <system/window.h>
 #include <utils/RefBase.h>
 
@@ -37,9 +38,13 @@
 //
 // When Android native buffer use has been enabled for a given port, the video
 // color format for the port is to be interpreted as an Android pixel format
-// rather than an OMX color format.  The node should then expect to receive
-// UseAndroidNativeBuffer calls (via OMX_SetParameter) rather than UseBuffer
-// calls for that port.
+// rather than an OMX color format.  Enabling Android native buffers may also
+// change how the component receives the native buffers.  If store-metadata-mode
+// is enabled on the port, the component will receive the buffers as specified
+// in the section below. Otherwise, unless the node supports the
+// 'OMX.google.android.index.useAndroidNativeBuffer2' extension, it should
+// expect to receive UseAndroidNativeBuffer calls (via OMX_SetParameter) rather
+// than UseBuffer calls for that port.
 struct EnableAndroidNativeBuffersParams {
     OMX_U32 nSize;
     OMX_VERSIONTYPE nVersion;
@@ -61,11 +66,15 @@
 //
 // Currently, this is specifically used to pass meta data from video source
 // (camera component, for instance) to video encoder to avoid memcpying of
-// input video frame data. To do this, bStoreMetaDta is set to OMX_TRUE.
+// input video frame data. To do this, bStoreMetaData is set to OMX_TRUE.
 // If bStoreMetaData is set to false, real YUV frame data will be stored
 // in the buffers. In addition, if no OMX_SetParameter() call is made
 // with the corresponding extension index, real YUV data is stored
 // in the buffers.
+//
+// For video decoder output port, the metadata buffer layout is defined below.
+//
+// Metadata buffers are registered with the component using UseBuffer calls.
 struct StoreMetaDataInBuffersParams {
     OMX_U32 nSize;
     OMX_VERSIONTYPE nVersion;
@@ -73,6 +82,38 @@
     OMX_BOOL bStoreMetaData;
 };
 
+// Meta data buffer layout used to transport output frames to the decoder for
+// dynamic buffer handling.
+struct VideoDecoderOutputMetaData {
+  MetadataBufferType eType;
+  buffer_handle_t pHandle;
+};
+
+// A pointer to this struct is passed to OMX_SetParameter() when the extension
+// index "OMX.google.android.index.prepareForAdaptivePlayback" is given.
+//
+// This method is used to signal a video decoder, that the user has requested
+// seamless resolution change support (if bEnable is set to OMX_TRUE).
+// nMaxFrameWidth and nMaxFrameHeight are the dimensions of the largest
+// anticipated frames in the video.  If bEnable is OMX_FALSE, no resolution
+// change is expected, and the nMaxFrameWidth/Height fields are unused.
+//
+// If the decoder supports dynamic output buffers, it may ignore this
+// request.  Otherwise, it shall request resources in such a way so that it
+// avoids full port-reconfiguration (due to output port-definition change)
+// during resolution changes.
+//
+// DO NOT USE THIS STRUCTURE AS IT WILL BE REMOVED.  INSTEAD, IMPLEMENT
+// METADATA SUPPORT FOR VIDEO DECODERS.
+struct PrepareForAdaptivePlaybackParams {
+    OMX_U32 nSize;
+    OMX_VERSIONTYPE nVersion;
+    OMX_U32 nPortIndex;
+    OMX_BOOL bEnable;
+    OMX_U32 nMaxFrameWidth;
+    OMX_U32 nMaxFrameHeight;
+};
+
 // A pointer to this struct is passed to OMX_SetParameter when the extension
 // index for the 'OMX.google.android.index.useAndroidNativeBuffer' extension is
 // given.  This call will only be performed if a prior call was made with the
diff --git a/include/media/openmax/OMX_IVCommon.h b/include/media/openmax/OMX_IVCommon.h
index 85bf00d..96a4396 100644
--- a/include/media/openmax/OMX_IVCommon.h
+++ b/include/media/openmax/OMX_IVCommon.h
@@ -161,6 +161,7 @@
     OMX_QCOM_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00,
     OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka = 0x7FA30C03,
     OMX_SEC_COLOR_FormatNV12Tiled = 0x7FC00002,
+    OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar32m = 0x7FA30C04,
     OMX_COLOR_FormatMax = 0x7FFFFFFF
 } OMX_COLOR_FORMATTYPE;
 
diff --git a/include/media/openmax/OMX_Video.h b/include/media/openmax/OMX_Video.h
index 4f8485d..4441a7a 100644
--- a/include/media/openmax/OMX_Video.h
+++ b/include/media/openmax/OMX_Video.h
@@ -85,7 +85,8 @@
     OMX_VIDEO_CodingRV,         /**< all versions of Real Video */
     OMX_VIDEO_CodingAVC,        /**< H.264/AVC */
     OMX_VIDEO_CodingMJPEG,      /**< Motion JPEG */
-    OMX_VIDEO_CodingVPX,        /**< Google VPX, formerly known as On2 VP8 */
+    OMX_VIDEO_CodingVP8,        /**< Google VP8, formerly known as On2 VP8 */
+    OMX_VIDEO_CodingVP9,        /**< Google VP9 */
     OMX_VIDEO_CodingKhronosExtensions = 0x6F000000, /**< Reserved region for introducing Khronos Standard Extensions */ 
     OMX_VIDEO_CodingVendorStartUnused = 0x7F000000, /**< Reserved region for introducing Vendor Extensions */
     OMX_VIDEO_CodingMax = 0x7FFFFFFF
diff --git a/include/media/openmax/OMX_VideoExt.h b/include/media/openmax/OMX_VideoExt.h
index 5e79b47..fa24168 100644
--- a/include/media/openmax/OMX_VideoExt.h
+++ b/include/media/openmax/OMX_VideoExt.h
@@ -58,12 +58,6 @@
     OMX_NALUFORMATSTYPE eNaluFormat;
 } OMX_NALSTREAMFORMATTYPE;
 
-/** Enum for standard video codingtype extensions */
-typedef enum OMX_VIDEO_CODINGEXTTYPE {
-    OMX_VIDEO_ExtCodingUnused = OMX_VIDEO_CodingKhronosExtensions,
-    OMX_VIDEO_CodingVP8,        /**< VP8/WebM */
-} OMX_VIDEO_CODINGEXTTYPE;
-
 /** VP8 profiles */
 typedef enum OMX_VIDEO_VP8PROFILETYPE {
     OMX_VIDEO_VP8ProfileMain = 0x01,
diff --git a/include/powermanager/IPowerManager.h b/include/powermanager/IPowerManager.h
index 1723f04..d85003f 100644
--- a/include/powermanager/IPowerManager.h
+++ b/include/powermanager/IPowerManager.h
@@ -30,8 +30,12 @@
 public:
     DECLARE_META_INTERFACE(PowerManager);
 
-    virtual status_t acquireWakeLock(int flags, const sp<IBinder>& lock, const String16& tag) = 0;
+    virtual status_t acquireWakeLock(int flags, const sp<IBinder>& lock, const String16& tag,
+            const String16& packageName) = 0;
+    virtual status_t acquireWakeLockWithUid(int flags, const sp<IBinder>& lock, const String16& tag,
+            const String16& packageName, int uid) = 0;
     virtual status_t releaseWakeLock(const sp<IBinder>& lock, int flags) = 0;
+    virtual status_t updateWakeLockUids(const sp<IBinder>& lock, int len, const int *uids) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/private/binder/Static.h b/include/private/binder/Static.h
index 5b0f9fc..6a03594 100644
--- a/include/private/binder/Static.h
+++ b/include/private/binder/Static.h
@@ -27,6 +27,9 @@
 
 namespace android {
 
+// For TextStream.cpp
+extern Vector<int32_t> gTextBuffers;
+
 // For ProcessState.cpp
 extern Mutex gProcessMutex;
 extern sp<ProcessState> gProcess;
diff --git a/include/private/utils/Static.h b/include/private/utils/Static.h
deleted file mode 100644
index d95ae0d..0000000
--- a/include/private/utils/Static.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2008 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.
- */
-
-// All static variables go here, to control initialization and
-// destruction order in the library.
-
-#include <utils/threads.h>
-#include <utils/KeyedVector.h>
-
-namespace android {
-// For TextStream.cpp
-extern Vector<int32_t> gTextBuffers;
-
-// For String8.cpp
-extern void initialize_string8();
-extern void terminate_string8();
-
-// For String16.cpp
-extern void initialize_string16();
-extern void terminate_string16();
-
-}   // namespace android
diff --git a/include/ui/DisplayInfo.h b/include/ui/DisplayInfo.h
index c3a4d6b..2853e06 100644
--- a/include/ui/DisplayInfo.h
+++ b/include/ui/DisplayInfo.h
@@ -34,8 +34,6 @@
     uint8_t orientation;
     bool secure;
     uint8_t reserved[2];
-    // TODO: this needs to go away (currently needed only by webkit)
-    PixelFormatInfo pixelFormatInfo;
 };
 
 /* Display orientations as defined in Surface.java and ISurfaceComposer.h. */
diff --git a/include/ui/Fence.h b/include/ui/Fence.h
index 60156e7..20466b6 100644
--- a/include/ui/Fence.h
+++ b/include/ui/Fence.h
@@ -36,7 +36,7 @@
 // ===========================================================================
 
 class Fence
-    : public LightRefBase<Fence>, public Flattenable
+    : public LightRefBase<Fence>, public Flattenable<Fence>
 {
 public:
     static const sp<Fence> NO_FENCE;
@@ -96,15 +96,13 @@
     // Flattenable interface
     size_t getFlattenedSize() const;
     size_t getFdCount() const;
-    status_t flatten(void* buffer, size_t size,
-            int fds[], size_t count) const;
-    status_t unflatten(void const* buffer, size_t size,
-            int fds[], size_t count);
+    status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
+    status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
 
 private:
     // Only allow instantiation using ref counting.
     friend class LightRefBase<Fence>;
-    virtual ~Fence();
+    ~Fence();
 
     // Disallow copying
     Fence(const Fence& rhs);
diff --git a/include/ui/GraphicBuffer.h b/include/ui/GraphicBuffer.h
index e5ad1e0..3cf628c 100644
--- a/include/ui/GraphicBuffer.h
+++ b/include/ui/GraphicBuffer.h
@@ -39,8 +39,9 @@
 
 class GraphicBuffer
     : public ANativeObjectBase< ANativeWindowBuffer, GraphicBuffer, RefBase >,
-      public Flattenable
+      public Flattenable<GraphicBuffer>
 {
+    friend class Flattenable<GraphicBuffer>;
 public:
 
     enum {
@@ -98,15 +99,18 @@
     status_t unlock();
 
     ANativeWindowBuffer* getNativeBuffer() const;
-    
-    void setIndex(int index);
-    int getIndex() const;
 
     // for debugging
     static void dumpAllocationsToSystemLog();
 
+    // Flattenable protocol
+    size_t getFlattenedSize() const;
+    size_t getFdCount() const;
+    status_t flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const;
+    status_t unflatten(void const*& buffer, size_t& size, int const*& fds, size_t& count);
+
 private:
-    virtual ~GraphicBuffer();
+    ~GraphicBuffer();
 
     enum {
         ownNone   = 0,
@@ -136,18 +140,8 @@
 
     void free_handle();
 
-    // Flattenable interface
-    size_t getFlattenedSize() const;
-    size_t getFdCount() const;
-    status_t flatten(void* buffer, size_t size,
-            int fds[], size_t count) const;
-    status_t unflatten(void const* buffer, size_t size,
-            int fds[], size_t count);
-
-
     GraphicBufferMapper& mBufferMapper;
     ssize_t mInitCheck;
-    int mIndex;
 
     // If we're wrapping another buffer then this reference will make sure it
     // doesn't get freed.
diff --git a/include/ui/PixelFormat.h b/include/ui/PixelFormat.h
index 9f3e267..627cfb6 100644
--- a/include/ui/PixelFormat.h
+++ b/include/ui/PixelFormat.h
@@ -61,67 +61,14 @@
     PIXEL_FORMAT_RGB_888     = HAL_PIXEL_FORMAT_RGB_888,    // 3x8-bit RGB
     PIXEL_FORMAT_RGB_565     = HAL_PIXEL_FORMAT_RGB_565,    // 16-bit RGB
     PIXEL_FORMAT_BGRA_8888   = HAL_PIXEL_FORMAT_BGRA_8888,  // 4x8-bit BGRA
-    PIXEL_FORMAT_RGBA_5551   = HAL_PIXEL_FORMAT_RGBA_5551,  // 16-bit ARGB
-    PIXEL_FORMAT_RGBA_4444   = HAL_PIXEL_FORMAT_RGBA_4444,  // 16-bit ARGB
-    PIXEL_FORMAT_A_8         = 8,                           // 8-bit A
+    PIXEL_FORMAT_RGBA_5551   = 6,                           // 16-bit ARGB
+    PIXEL_FORMAT_RGBA_4444   = 7,                           // 16-bit ARGB
 };
 
 typedef int32_t PixelFormat;
 
-struct PixelFormatInfo {
-    enum {
-        INDEX_ALPHA   = 0,
-        INDEX_RED     = 1,
-        INDEX_GREEN   = 2,
-        INDEX_BLUE    = 3
-    };
-
-    enum { // components
-        ALPHA   = 1,
-        RGB     = 2,
-        RGBA    = 3,
-        L       = 4,
-        LA      = 5,
-        OTHER   = 0xFF
-    };
-
-    struct szinfo {
-        uint8_t h;
-        uint8_t l;
-    };
-
-    inline PixelFormatInfo() : version(sizeof(PixelFormatInfo)) { }
-    size_t getScanlineSize(unsigned int width) const;
-    size_t getSize(size_t ci) const {
-        return (ci <= 3) ? (cinfo[ci].h - cinfo[ci].l) : 0;
-    }
-    size_t      version;
-    PixelFormat format;
-    size_t      bytesPerPixel;
-    size_t      bitsPerPixel;
-    union {
-        szinfo      cinfo[4];
-        struct {
-            uint8_t     h_alpha;
-            uint8_t     l_alpha;
-            uint8_t     h_red;
-            uint8_t     l_red;
-            uint8_t     h_green;
-            uint8_t     l_green;
-            uint8_t     h_blue;
-            uint8_t     l_blue;
-        };
-    };
-    uint8_t     components;
-    uint8_t     reserved0[3];
-    uint32_t    reserved1;
-};
-
-// Consider caching the results of these functions are they're not
-// guaranteed to be fast.
-ssize_t     bytesPerPixel(PixelFormat format);
-ssize_t     bitsPerPixel(PixelFormat format);
-status_t    getPixelFormatInfo(PixelFormat format, PixelFormatInfo* info);
+ssize_t bytesPerPixel(PixelFormat format);
+ssize_t bitsPerPixel(PixelFormat format);
 
 }; // namespace android
 
diff --git a/include/ui/Rect.h b/include/ui/Rect.h
index 47d37b6..6cf64eb 100644
--- a/include/ui/Rect.h
+++ b/include/ui/Rect.h
@@ -35,14 +35,25 @@
 
     inline Rect() {
     }
+
     inline Rect(int32_t w, int32_t h) {
-        left = top = 0; right = w; bottom = h;
+        left = top = 0;
+        right = w;
+        bottom = h;
     }
+
     inline Rect(int32_t l, int32_t t, int32_t r, int32_t b) {
-        left = l; top = t; right = r; bottom = b;
+        left = l;
+        top = t;
+        right = r;
+        bottom = b;
     }
+
     inline Rect(const Point& lt, const Point& rb) {
-        left = lt.x; top = lt.y; right = rb.x; bottom = rb.y;
+        left = lt.x;
+        top = lt.y;
+        right = rb.x;
+        bottom = rb.y;
     }
 
     void makeInvalid();
@@ -53,43 +64,36 @@
 
     // a valid rectangle has a non negative width and height
     inline bool isValid() const {
-        return (width()>=0) && (height()>=0);
+        return (getWidth() >= 0) && (getHeight() >= 0);
     }
 
     // an empty rect has a zero width or height, or is invalid
     inline bool isEmpty() const {
-        return (width()<=0) || (height()<=0);
-    }
-
-    inline void set(const Rect& rhs) {
-        operator = (rhs);
+        return (getWidth() <= 0) || (getHeight() <= 0);
     }
 
     // rectangle's width
     inline int32_t getWidth() const {
-        return right-left;
+        return right - left;
     }
-    
+
     // rectangle's height
     inline int32_t getHeight() const {
-        return bottom-top;
+        return bottom - top;
     }
 
     inline Rect getBounds() const {
-        return Rect(right-left, bottom-top);
+        return Rect(right - left, bottom - top);
     }
 
-    inline int32_t width() const { return getWidth(); }
-    inline int32_t height() const { return getHeight(); }
-
     void setLeftTop(const Point& lt) {
         left = lt.x;
-        top  = lt.y;
+        top = lt.y;
     }
 
     void setRightBottom(const Point& rb) {
         right = rb.x;
-        bottom  = rb.y;
+        bottom = rb.y;
     }
     
     // the following 4 functions return the 4 corners of the rect as Point
@@ -120,6 +124,16 @@
     // vectors.
     bool operator < (const Rect& rhs) const;
 
+    const Rect operator + (const Point& rhs) const;
+    const Rect operator - (const Point& rhs) const;
+
+    Rect& operator += (const Point& rhs) {
+        return offsetBy(rhs.x, rhs.y);
+    }
+    Rect& operator -= (const Point& rhs) {
+        return offsetBy(-rhs.x, -rhs.y);
+    }
+
     Rect& offsetToOrigin() {
         right -= left;
         bottom -= top;
@@ -132,22 +146,11 @@
     Rect& offsetBy(const Point& dp) {
         return offsetBy(dp.x, dp.y);
     }
-    Rect& operator += (const Point& rhs) {
-        return offsetBy(rhs.x, rhs.y);
-    }
-    Rect& operator -= (const Point& rhs) {
-        return offsetBy(-rhs.x, -rhs.y);
-    }
-    const Rect operator + (const Point& rhs) const;
-    const Rect operator - (const Point& rhs) const;
 
-    void translate(int32_t dx, int32_t dy) { // legacy, don't use.
-        offsetBy(dx, dy);
-    }
+    Rect& offsetTo(int32_t x, int32_t y);
+    Rect& offsetBy(int32_t x, int32_t y);
 
-    Rect&   offsetTo(int32_t x, int32_t y);
-    Rect&   offsetBy(int32_t x, int32_t y);
-    bool    intersect(const Rect& with, Rect* result) const;
+    bool intersect(const Rect& with, Rect* result) const;
 
     // Create a new Rect by transforming this one using a graphics HAL
     // transform.  This rectangle is defined in a coordinate space starting at
@@ -156,6 +159,15 @@
     // (height, width).  Otherwise the output rectangle is in the same space as
     // the input.
     Rect transform(uint32_t xform, int32_t width, int32_t height) const;
+
+    // this calculates (Region(*this) - exclude).bounds() efficiently
+    Rect reduce(const Rect& exclude) const;
+
+
+    // for backward compatibility
+    inline int32_t width() const { return getWidth(); }
+    inline int32_t height() const { return getHeight(); }
+    inline void set(const Rect& rhs) { operator = (rhs); }
 };
 
 ANDROID_BASIC_TYPES_TRAITS(Rect)
diff --git a/include/ui/Region.h b/include/ui/Region.h
index ce91f3b..d906dbb 100644
--- a/include/ui/Region.h
+++ b/include/ui/Region.h
@@ -136,8 +136,8 @@
             void        addRectUnchecked(int l, int t, int r, int b);
 
     inline  bool        isFixedSize() const { return false; }
-            size_t      getSize() const;
-            status_t    flatten(void* buffer) const;
+            size_t      getFlattenedSize() const;
+            status_t    flatten(void* buffer, size_t size) const;
             status_t    unflatten(void const* buffer, size_t size);
 
     void        dump(String8& out, const char* what, uint32_t flags=0) const;
diff --git a/include/ui/TMatHelpers.h b/include/ui/TMatHelpers.h
new file mode 100644
index 0000000..a6aadca
--- /dev/null
+++ b/include/ui/TMatHelpers.h
@@ -0,0 +1,257 @@
+/*
+ * Copyright 2013 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 TMAT_IMPLEMENTATION
+#error "Don't include TMatHelpers.h directly. use ui/mat*.h instead"
+#else
+#undef TMAT_IMPLEMENTATION
+#endif
+
+
+#ifndef UI_TMAT_HELPERS_H
+#define UI_TMAT_HELPERS_H
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <math.h>
+#include <utils/Debug.h>
+#include <utils/String8.h>
+
+#define PURE __attribute__((pure))
+
+namespace android {
+// -------------------------------------------------------------------------------------
+
+/*
+ * No user serviceable parts here.
+ *
+ * Don't use this file directly, instead include ui/mat*.h
+ */
+
+
+/*
+ * Matrix utilities
+ */
+
+namespace matrix {
+
+inline int     PURE transpose(int v)    { return v; }
+inline float   PURE transpose(float v)  { return v; }
+inline double  PURE transpose(double v) { return v; }
+
+inline int     PURE trace(int v)    { return v; }
+inline float   PURE trace(float v)  { return v; }
+inline double  PURE trace(double v) { return v; }
+
+template<typename MATRIX>
+MATRIX PURE inverse(const MATRIX& src) {
+
+    COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX::COL_SIZE == MATRIX::ROW_SIZE );
+
+    typename MATRIX::value_type t;
+    const size_t N = MATRIX::col_size();
+    size_t swap;
+    MATRIX tmp(src);
+    MATRIX inverse(1);
+
+    for (size_t i=0 ; i<N ; i++) {
+        // look for largest element in column
+        swap = i;
+        for (size_t j=i+1 ; j<N ; j++) {
+            if (fabs(tmp[j][i]) > fabs(tmp[i][i])) {
+                swap = j;
+            }
+        }
+
+        if (swap != i) {
+            /* swap rows. */
+            for (size_t k=0 ; k<N ; k++) {
+                t = tmp[i][k];
+                tmp[i][k] = tmp[swap][k];
+                tmp[swap][k] = t;
+
+                t = inverse[i][k];
+                inverse[i][k] = inverse[swap][k];
+                inverse[swap][k] = t;
+            }
+        }
+
+        t = 1 / tmp[i][i];
+        for (size_t k=0 ; k<N ; k++) {
+            tmp[i][k] *= t;
+            inverse[i][k] *= t;
+        }
+        for (size_t j=0 ; j<N ; j++) {
+            if (j != i) {
+                t = tmp[j][i];
+                for (size_t k=0 ; k<N ; k++) {
+                    tmp[j][k] -= tmp[i][k] * t;
+                    inverse[j][k] -= inverse[i][k] * t;
+                }
+            }
+        }
+    }
+    return inverse;
+}
+
+template<typename MATRIX_R, typename MATRIX_A, typename MATRIX_B>
+MATRIX_R PURE multiply(const MATRIX_A& lhs, const MATRIX_B& rhs) {
+    // pre-requisite:
+    //  lhs : D columns, R rows
+    //  rhs : C columns, D rows
+    //  res : C columns, R rows
+
+    COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX_A::ROW_SIZE == MATRIX_B::COL_SIZE );
+    COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX_R::ROW_SIZE == MATRIX_B::ROW_SIZE );
+    COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX_R::COL_SIZE == MATRIX_A::COL_SIZE );
+
+    MATRIX_R res(MATRIX_R::NO_INIT);
+    for (size_t r=0 ; r<MATRIX_R::row_size() ; r++) {
+        res[r] = lhs * rhs[r];
+    }
+    return res;
+}
+
+// transpose. this handles matrices of matrices
+template <typename MATRIX>
+MATRIX PURE transpose(const MATRIX& m) {
+    // for now we only handle square matrix transpose
+    COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX::ROW_SIZE == MATRIX::COL_SIZE );
+    MATRIX result(MATRIX::NO_INIT);
+    for (size_t r=0 ; r<MATRIX::row_size() ; r++)
+        for (size_t c=0 ; c<MATRIX::col_size() ; c++)
+            result[c][r] = transpose(m[r][c]);
+    return result;
+}
+
+// trace. this handles matrices of matrices
+template <typename MATRIX>
+typename MATRIX::value_type PURE trace(const MATRIX& m) {
+    COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX::ROW_SIZE == MATRIX::COL_SIZE );
+    typename MATRIX::value_type result(0);
+    for (size_t r=0 ; r<MATRIX::row_size() ; r++)
+        result += trace(m[r][r]);
+    return result;
+}
+
+// trace. this handles matrices of matrices
+template <typename MATRIX>
+typename MATRIX::col_type PURE diag(const MATRIX& m) {
+    COMPILE_TIME_ASSERT_FUNCTION_SCOPE( MATRIX::ROW_SIZE == MATRIX::COL_SIZE );
+    typename MATRIX::col_type result(MATRIX::col_type::NO_INIT);
+    for (size_t r=0 ; r<MATRIX::row_size() ; r++)
+        result[r] = m[r][r];
+    return result;
+}
+
+template <typename MATRIX>
+String8 asString(const MATRIX& m) {
+    String8 s;
+    for (size_t c=0 ; c<MATRIX::col_size() ; c++) {
+        s.append("|  ");
+        for (size_t r=0 ; r<MATRIX::row_size() ; r++) {
+            s.appendFormat("%7.2f  ", m[r][c]);
+        }
+        s.append("|\n");
+    }
+    return s;
+}
+
+}; // namespace matrix
+
+// -------------------------------------------------------------------------------------
+
+/*
+ * TMatProductOperators implements basic arithmetic and basic compound assignments
+ * operators on a vector of type BASE<T>.
+ *
+ * BASE only needs to implement operator[] and size().
+ * By simply inheriting from TMatProductOperators<BASE, T> BASE will automatically
+ * get all the functionality here.
+ */
+
+template <template<typename T> class BASE, typename T>
+class TMatProductOperators {
+public:
+    // multiply by a scalar
+    BASE<T>& operator *= (T v) {
+        BASE<T>& lhs(static_cast< BASE<T>& >(*this));
+        for (size_t r=0 ; r<lhs.row_size() ; r++) {
+            lhs[r] *= v;
+        }
+        return lhs;
+    }
+
+    // divide by a scalar
+    BASE<T>& operator /= (T v) {
+        BASE<T>& lhs(static_cast< BASE<T>& >(*this));
+        for (size_t r=0 ; r<lhs.row_size() ; r++) {
+            lhs[r] /= v;
+        }
+        return lhs;
+    }
+
+    // matrix * matrix, result is a matrix of the same type than the lhs matrix
+    template<typename U>
+    friend BASE<T> PURE operator *(const BASE<T>& lhs, const BASE<U>& rhs) {
+        return matrix::multiply<BASE<T> >(lhs, rhs);
+    }
+};
+
+
+/*
+ * TMatSquareFunctions implements functions on a matrix of type BASE<T>.
+ *
+ * BASE only needs to implement:
+ *  - operator[]
+ *  - col_type
+ *  - row_type
+ *  - COL_SIZE
+ *  - ROW_SIZE
+ *
+ * By simply inheriting from TMatSquareFunctions<BASE, T> BASE will automatically
+ * get all the functionality here.
+ */
+
+template<template<typename U> class BASE, typename T>
+class TMatSquareFunctions {
+public:
+    /*
+     * NOTE: the functions below ARE NOT member methods. They are friend functions
+     * with they definition inlined with their declaration. This makes these
+     * template functions available to the compiler when (and only when) this class
+     * is instantiated, at which point they're only templated on the 2nd parameter
+     * (the first one, BASE<T> being known).
+     */
+    friend BASE<T> PURE inverse(const BASE<T>& m)   { return matrix::inverse(m); }
+    friend BASE<T> PURE transpose(const BASE<T>& m) { return matrix::transpose(m); }
+    friend T       PURE trace(const BASE<T>& m)     { return matrix::trace(m); }
+};
+
+template <template<typename T> class BASE, typename T>
+class TMatDebug {
+public:
+    String8 asString() const {
+        return matrix::asString( static_cast< const BASE<T>& >(*this) );
+    }
+};
+
+// -------------------------------------------------------------------------------------
+}; // namespace android
+
+#undef PURE
+
+#endif /* UI_TMAT_HELPERS_H */
diff --git a/include/ui/TVecHelpers.h b/include/ui/TVecHelpers.h
new file mode 100644
index 0000000..bb7dbfc
--- /dev/null
+++ b/include/ui/TVecHelpers.h
@@ -0,0 +1,381 @@
+/*
+ * Copyright 2013 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 TVEC_IMPLEMENTATION
+#error "Don't include TVecHelpers.h directly. use ui/vec*.h instead"
+#else
+#undef TVEC_IMPLEMENTATION
+#endif
+
+
+#ifndef UI_TVEC_HELPERS_H
+#define UI_TVEC_HELPERS_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#define PURE __attribute__((pure))
+
+namespace android {
+// -------------------------------------------------------------------------------------
+
+/*
+ * No user serviceable parts here.
+ *
+ * Don't use this file directly, instead include ui/vec{2|3|4}.h
+ */
+
+/*
+ * This class casts itself into anything and assign itself from anything!
+ * Use with caution!
+ */
+template <typename TYPE>
+struct Impersonator {
+    Impersonator& operator = (const TYPE& rhs) {
+        reinterpret_cast<TYPE&>(*this) = rhs;
+        return *this;
+    }
+    operator TYPE& () {
+        return reinterpret_cast<TYPE&>(*this);
+    }
+    operator TYPE const& () const {
+        return reinterpret_cast<TYPE const&>(*this);
+    }
+};
+
+/*
+ * TVec{Add|Product}Operators implements basic arithmetic and basic compound assignments
+ * operators on a vector of type BASE<T>.
+ *
+ * BASE only needs to implement operator[] and size().
+ * By simply inheriting from TVec{Add|Product}Operators<BASE, T> BASE will automatically
+ * get all the functionality here.
+ */
+
+template <template<typename T> class BASE, typename T>
+class TVecAddOperators {
+public:
+    /* compound assignment from a another vector of the same size but different
+     * element type.
+     */
+    template <typename OTHER>
+    BASE<T>& operator += (const BASE<OTHER>& v) {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            rhs[i] += v[i];
+        }
+        return rhs;
+    }
+    template <typename OTHER>
+    BASE<T>& operator -= (const BASE<OTHER>& v) {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            rhs[i] -= v[i];
+        }
+        return rhs;
+    }
+
+    /* compound assignment from a another vector of the same type.
+     * These operators can be used for implicit conversion and  handle operations
+     * like "vector *= scalar" by letting the compiler implicitly convert a scalar
+     * to a vector (assuming the BASE<T> allows it).
+     */
+    BASE<T>& operator += (const BASE<T>& v) {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            rhs[i] += v[i];
+        }
+        return rhs;
+    }
+    BASE<T>& operator -= (const BASE<T>& v) {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            rhs[i] -= v[i];
+        }
+        return rhs;
+    }
+
+    /*
+     * NOTE: the functions below ARE NOT member methods. They are friend functions
+     * with they definition inlined with their declaration. This makes these
+     * template functions available to the compiler when (and only when) this class
+     * is instantiated, at which point they're only templated on the 2nd parameter
+     * (the first one, BASE<T> being known).
+     */
+
+    /* The operators below handle operation between vectors of the same side
+     * but of a different element type.
+     */
+    template<typename RT>
+    friend inline
+    BASE<T> PURE operator +(const BASE<T>& lv, const BASE<RT>& rv) {
+        return BASE<T>(lv) += rv;
+    }
+    template<typename RT>
+    friend inline
+    BASE<T> PURE operator -(const BASE<T>& lv, const BASE<RT>& rv) {
+        return BASE<T>(lv) -= rv;
+    }
+
+    /* The operators below (which are not templates once this class is instanced,
+     * i.e.: BASE<T> is known) can be used for implicit conversion on both sides.
+     * These handle operations like "vector * scalar" and "scalar * vector" by
+     * letting the compiler implicitly convert a scalar to a vector (assuming
+     * the BASE<T> allows it).
+     */
+    friend inline
+    BASE<T> PURE operator +(const BASE<T>& lv, const BASE<T>& rv) {
+        return BASE<T>(lv) += rv;
+    }
+    friend inline
+    BASE<T> PURE operator -(const BASE<T>& lv, const BASE<T>& rv) {
+        return BASE<T>(lv) -= rv;
+    }
+};
+
+template <template<typename T> class BASE, typename T>
+class TVecProductOperators {
+public:
+    /* compound assignment from a another vector of the same size but different
+     * element type.
+     */
+    template <typename OTHER>
+    BASE<T>& operator *= (const BASE<OTHER>& v) {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            rhs[i] *= v[i];
+        }
+        return rhs;
+    }
+    template <typename OTHER>
+    BASE<T>& operator /= (const BASE<OTHER>& v) {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            rhs[i] /= v[i];
+        }
+        return rhs;
+    }
+
+    /* compound assignment from a another vector of the same type.
+     * These operators can be used for implicit conversion and  handle operations
+     * like "vector *= scalar" by letting the compiler implicitly convert a scalar
+     * to a vector (assuming the BASE<T> allows it).
+     */
+    BASE<T>& operator *= (const BASE<T>& v) {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            rhs[i] *= v[i];
+        }
+        return rhs;
+    }
+    BASE<T>& operator /= (const BASE<T>& v) {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            rhs[i] /= v[i];
+        }
+        return rhs;
+    }
+
+    /*
+     * NOTE: the functions below ARE NOT member methods. They are friend functions
+     * with they definition inlined with their declaration. This makes these
+     * template functions available to the compiler when (and only when) this class
+     * is instantiated, at which point they're only templated on the 2nd parameter
+     * (the first one, BASE<T> being known).
+     */
+
+    /* The operators below handle operation between vectors of the same side
+     * but of a different element type.
+     */
+    template<typename RT>
+    friend inline
+    BASE<T> PURE operator *(const BASE<T>& lv, const BASE<RT>& rv) {
+        return BASE<T>(lv) *= rv;
+    }
+    template<typename RT>
+    friend inline
+    BASE<T> PURE operator /(const BASE<T>& lv, const BASE<RT>& rv) {
+        return BASE<T>(lv) /= rv;
+    }
+
+    /* The operators below (which are not templates once this class is instanced,
+     * i.e.: BASE<T> is known) can be used for implicit conversion on both sides.
+     * These handle operations like "vector * scalar" and "scalar * vector" by
+     * letting the compiler implicitly convert a scalar to a vector (assuming
+     * the BASE<T> allows it).
+     */
+    friend inline
+    BASE<T> PURE operator *(const BASE<T>& lv, const BASE<T>& rv) {
+        return BASE<T>(lv) *= rv;
+    }
+    friend inline
+    BASE<T> PURE operator /(const BASE<T>& lv, const BASE<T>& rv) {
+        return BASE<T>(lv) /= rv;
+    }
+};
+
+/*
+ * TVecUnaryOperators implements unary operators on a vector of type BASE<T>.
+ *
+ * BASE only needs to implement operator[] and size().
+ * By simply inheriting from TVecUnaryOperators<BASE, T> BASE will automatically
+ * get all the functionality here.
+ *
+ * These operators are implemented as friend functions of TVecUnaryOperators<BASE, T>
+ */
+template <template<typename T> class BASE, typename T>
+class TVecUnaryOperators {
+public:
+    BASE<T>& operator ++ () {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            ++rhs[i];
+        }
+        return rhs;
+    }
+    BASE<T>& operator -- () {
+        BASE<T>& rhs = static_cast<BASE<T>&>(*this);
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            --rhs[i];
+        }
+        return rhs;
+    }
+    BASE<T> operator - () const {
+        BASE<T> r(BASE<T>::NO_INIT);
+        BASE<T> const& rv(static_cast<BASE<T> const&>(*this));
+        for (size_t i=0 ; i<BASE<T>::size() ; i++) {
+            r[i] = -rv[i];
+        }
+        return r;
+    }
+};
+
+
+/*
+ * TVecComparisonOperators implements relational/comparison operators
+ * on a vector of type BASE<T>.
+ *
+ * BASE only needs to implement operator[] and size().
+ * By simply inheriting from TVecComparisonOperators<BASE, T> BASE will automatically
+ * get all the functionality here.
+ */
+template <template<typename T> class BASE, typename T>
+class TVecComparisonOperators {
+public:
+    /*
+     * NOTE: the functions below ARE NOT member methods. They are friend functions
+     * with they definition inlined with their declaration. This makes these
+     * template functions available to the compiler when (and only when) this class
+     * is instantiated, at which point they're only templated on the 2nd parameter
+     * (the first one, BASE<T> being known).
+     */
+    template<typename RT>
+    friend inline
+    bool PURE operator ==(const BASE<T>& lv, const BASE<RT>& rv) {
+        for (size_t i = 0; i < BASE<T>::size(); i++)
+            if (lv[i] != rv[i])
+                return false;
+        return true;
+    }
+
+    template<typename RT>
+    friend inline
+    bool PURE operator !=(const BASE<T>& lv, const BASE<RT>& rv) {
+        return !operator ==(lv, rv);
+    }
+
+    template<typename RT>
+    friend inline
+    bool PURE operator >(const BASE<T>& lv, const BASE<RT>& rv) {
+        for (size_t i = 0; i < BASE<T>::size(); i++)
+            if (lv[i] <= rv[i])
+                return false;
+        return true;
+    }
+
+    template<typename RT>
+    friend inline
+    bool PURE operator <=(const BASE<T>& lv, const BASE<RT>& rv) {
+        return !(lv > rv);
+    }
+
+    template<typename RT>
+    friend inline
+    bool PURE operator <(const BASE<T>& lv, const BASE<RT>& rv) {
+        for (size_t i = 0; i < BASE<T>::size(); i++)
+            if (lv[i] >= rv[i])
+                return false;
+        return true;
+    }
+
+    template<typename RT>
+    friend inline
+    bool PURE operator >=(const BASE<T>& lv, const BASE<RT>& rv) {
+        return !(lv < rv);
+    }
+};
+
+
+/*
+ * TVecFunctions implements functions on a vector of type BASE<T>.
+ *
+ * BASE only needs to implement operator[] and size().
+ * By simply inheriting from TVecFunctions<BASE, T> BASE will automatically
+ * get all the functionality here.
+ */
+template <template<typename T> class BASE, typename T>
+class TVecFunctions {
+public:
+    /*
+     * NOTE: the functions below ARE NOT member methods. They are friend functions
+     * with they definition inlined with their declaration. This makes these
+     * template functions available to the compiler when (and only when) this class
+     * is instantiated, at which point they're only templated on the 2nd parameter
+     * (the first one, BASE<T> being known).
+     */
+    template<typename RT>
+    friend inline
+    T PURE dot(const BASE<T>& lv, const BASE<RT>& rv) {
+        T r(0);
+        for (size_t i = 0; i < BASE<T>::size(); i++)
+            r += lv[i]*rv[i];
+        return r;
+    }
+
+    friend inline
+    T PURE length(const BASE<T>& lv) {
+        return sqrt( dot(lv, lv) );
+    }
+
+    template<typename RT>
+    friend inline
+    T PURE distance(const BASE<T>& lv, const BASE<RT>& rv) {
+        return length(rv - lv);
+    }
+
+    friend inline
+    BASE<T> PURE normalize(const BASE<T>& lv) {
+        return lv * (1 / length(lv));
+    }
+};
+
+#undef PURE
+
+// -------------------------------------------------------------------------------------
+}; // namespace android
+
+
+#endif /* UI_TVEC_HELPERS_H */
diff --git a/include/ui/mat4.h b/include/ui/mat4.h
new file mode 100644
index 0000000..d9647cc
--- /dev/null
+++ b/include/ui/mat4.h
@@ -0,0 +1,394 @@
+/*
+ * Copyright 2013 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 UI_MAT4_H
+#define UI_MAT4_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <ui/vec4.h>
+#include <utils/String8.h>
+
+#define TMAT_IMPLEMENTATION
+#include <ui/TMatHelpers.h>
+
+#define PURE __attribute__((pure))
+
+namespace android {
+// -------------------------------------------------------------------------------------
+
+template <typename T>
+class tmat44 :  public TVecUnaryOperators<tmat44, T>,
+                public TVecComparisonOperators<tmat44, T>,
+                public TVecAddOperators<tmat44, T>,
+                public TMatProductOperators<tmat44, T>,
+                public TMatSquareFunctions<tmat44, T>,
+                public TMatDebug<tmat44, T>
+{
+public:
+    enum no_init { NO_INIT };
+    typedef T value_type;
+    typedef T& reference;
+    typedef T const& const_reference;
+    typedef size_t size_type;
+    typedef tvec4<T> col_type;
+    typedef tvec4<T> row_type;
+
+    // size of a column (i.e.: number of rows)
+    enum { COL_SIZE = col_type::SIZE };
+    static inline size_t col_size() { return COL_SIZE; }
+
+    // size of a row (i.e.: number of columns)
+    enum { ROW_SIZE = row_type::SIZE };
+    static inline size_t row_size() { return ROW_SIZE; }
+    static inline size_t size()     { return row_size(); }  // for TVec*<>
+
+private:
+
+    /*
+     *  <--  N columns  -->
+     *
+     *  a00 a10 a20 ... aN0    ^
+     *  a01 a11 a21 ... aN1    |
+     *  a02 a12 a22 ... aN2  M rows
+     *  ...                    |
+     *  a0M a1M a2M ... aNM    v
+     *
+     *  COL_SIZE = M
+     *  ROW_SIZE = N
+     *  m[0] = [a00 a01 a02 ... a01M]
+     */
+
+    col_type mValue[ROW_SIZE];
+
+public:
+    // array access
+    inline col_type const& operator [] (size_t i) const { return mValue[i]; }
+    inline col_type&       operator [] (size_t i)       { return mValue[i]; }
+
+    T const* asArray() const { return &mValue[0][0]; }
+
+    // -----------------------------------------------------------------------
+    // we don't provide copy-ctor and operator= on purpose
+    // because we want the compiler generated versions
+
+    /*
+     *  constructors
+     */
+
+    // leaves object uninitialized. use with caution.
+    explicit tmat44(no_init) { }
+
+    // initialize to identity
+    tmat44();
+
+    // initialize to Identity*scalar.
+    template<typename U>
+    explicit tmat44(U v);
+
+    // sets the diagonal to the passed vector
+    template <typename U>
+    explicit tmat44(const tvec4<U>& rhs);
+
+    // construct from another matrix of the same size
+    template <typename U>
+    explicit tmat44(const tmat44<U>& rhs);
+
+    // construct from 4 column vectors
+    template <typename A, typename B, typename C, typename D>
+    tmat44(const tvec4<A>& v0, const tvec4<B>& v1, const tvec4<C>& v2, const tvec4<D>& v3);
+
+    // construct from 16 scalars
+    template <
+        typename A, typename B, typename C, typename D,
+        typename E, typename F, typename G, typename H,
+        typename I, typename J, typename K, typename L,
+        typename M, typename N, typename O, typename P>
+    tmat44( A m00, B m01, C m02, D m03,
+            E m10, F m11, G m12, H m13,
+            I m20, J m21, K m22, L m23,
+            M m30, N m31, O m32, P m33);
+
+    // construct from a C array
+    template <typename U>
+    explicit tmat44(U const* rawArray);
+
+    /*
+     *  helpers
+     */
+
+    static tmat44 ortho(T left, T right, T bottom, T top, T near, T far);
+
+    static tmat44 frustum(T left, T right, T bottom, T top, T near, T far);
+
+    template <typename A, typename B, typename C>
+    static tmat44 lookAt(const tvec3<A>& eye, const tvec3<B>& center, const tvec3<C>& up);
+
+    template <typename A>
+    static tmat44 translate(const tvec4<A>& t);
+
+    template <typename A>
+    static tmat44 scale(const tvec4<A>& s);
+
+    template <typename A, typename B>
+    static tmat44 rotate(A radian, const tvec3<B>& about);
+};
+
+// ----------------------------------------------------------------------------------------
+// Constructors
+// ----------------------------------------------------------------------------------------
+
+/*
+ * Since the matrix code could become pretty big quickly, we don't inline most
+ * operations.
+ */
+
+template <typename T>
+tmat44<T>::tmat44() {
+    mValue[0] = col_type(1,0,0,0);
+    mValue[1] = col_type(0,1,0,0);
+    mValue[2] = col_type(0,0,1,0);
+    mValue[3] = col_type(0,0,0,1);
+}
+
+template <typename T>
+template <typename U>
+tmat44<T>::tmat44(U v) {
+    mValue[0] = col_type(v,0,0,0);
+    mValue[1] = col_type(0,v,0,0);
+    mValue[2] = col_type(0,0,v,0);
+    mValue[3] = col_type(0,0,0,v);
+}
+
+template<typename T>
+template<typename U>
+tmat44<T>::tmat44(const tvec4<U>& v) {
+    mValue[0] = col_type(v.x,0,0,0);
+    mValue[1] = col_type(0,v.y,0,0);
+    mValue[2] = col_type(0,0,v.z,0);
+    mValue[3] = col_type(0,0,0,v.w);
+}
+
+// construct from 16 scalars
+template<typename T>
+template <
+    typename A, typename B, typename C, typename D,
+    typename E, typename F, typename G, typename H,
+    typename I, typename J, typename K, typename L,
+    typename M, typename N, typename O, typename P>
+tmat44<T>::tmat44(  A m00, B m01, C m02, D m03,
+                    E m10, F m11, G m12, H m13,
+                    I m20, J m21, K m22, L m23,
+                    M m30, N m31, O m32, P m33) {
+    mValue[0] = col_type(m00, m01, m02, m03);
+    mValue[1] = col_type(m10, m11, m12, m13);
+    mValue[2] = col_type(m20, m21, m22, m23);
+    mValue[3] = col_type(m30, m31, m32, m33);
+}
+
+template <typename T>
+template <typename U>
+tmat44<T>::tmat44(const tmat44<U>& rhs) {
+    for (size_t r=0 ; r<row_size() ; r++)
+        mValue[r] = rhs[r];
+}
+
+template <typename T>
+template <typename A, typename B, typename C, typename D>
+tmat44<T>::tmat44(const tvec4<A>& v0, const tvec4<B>& v1, const tvec4<C>& v2, const tvec4<D>& v3) {
+    mValue[0] = v0;
+    mValue[1] = v1;
+    mValue[2] = v2;
+    mValue[3] = v3;
+}
+
+template <typename T>
+template <typename U>
+tmat44<T>::tmat44(U const* rawArray) {
+    for (size_t r=0 ; r<row_size() ; r++)
+        for (size_t c=0 ; c<col_size() ; c++)
+            mValue[r][c] = *rawArray++;
+}
+
+// ----------------------------------------------------------------------------------------
+// Helpers
+// ----------------------------------------------------------------------------------------
+
+template <typename T>
+tmat44<T> tmat44<T>::ortho(T left, T right, T bottom, T top, T near, T far) {
+    tmat44<T> m;
+    m[0][0] =  2 / (right - left);
+    m[1][1] =  2 / (top   - bottom);
+    m[2][2] = -2 / (far   - near);
+    m[3][0] = -(right + left)   / (right - left);
+    m[3][1] = -(top   + bottom) / (top   - bottom);
+    m[3][2] = -(far   + near)   / (far   - near);
+    return m;
+}
+
+template <typename T>
+tmat44<T> tmat44<T>::frustum(T left, T right, T bottom, T top, T near, T far) {
+    tmat44<T> m;
+    T A = (right + left)   / (right - left);
+    T B = (top   + bottom) / (top   - bottom);
+    T C = (far   + near)   / (far   - near);
+    T D = (2 * far * near) / (far   - near);
+    m[0][0] = (2 * near) / (right - left);
+    m[1][1] = (2 * near) / (top   - bottom);
+    m[2][0] = A;
+    m[2][1] = B;
+    m[2][2] = C;
+    m[2][3] =-1;
+    m[3][2] = D;
+    m[3][3] = 0;
+    return m;
+}
+
+template <typename T>
+template <typename A, typename B, typename C>
+tmat44<T> tmat44<T>::lookAt(const tvec3<A>& eye, const tvec3<B>& center, const tvec3<C>& up) {
+    tvec3<T> L(normalize(center - eye));
+    tvec3<T> S(normalize( cross(L, up) ));
+    tvec3<T> U(cross(S, L));
+    return tmat44<T>(
+            tvec4<T>( S, 0),
+            tvec4<T>( U, 0),
+            tvec4<T>(-L, 0),
+            tvec4<T>(-eye, 1));
+}
+
+template <typename T>
+template <typename A>
+tmat44<T> tmat44<T>::translate(const tvec4<A>& t) {
+    tmat44<T> r;
+    r[3] = t;
+    return r;
+}
+
+template <typename T>
+template <typename A>
+tmat44<T> tmat44<T>::scale(const tvec4<A>& s) {
+    tmat44<T> r;
+    r[0][0] = s[0];
+    r[1][1] = s[1];
+    r[2][2] = s[2];
+    r[3][3] = s[3];
+    return r;
+}
+
+template <typename T>
+template <typename A, typename B>
+tmat44<T> tmat44<T>::rotate(A radian, const tvec3<B>& about) {
+    tmat44<T> rotation;
+    T* r = const_cast<T*>(rotation.asArray());
+    T c = cos(radian);
+    T s = sin(radian);
+    if (about.x==1 && about.y==0 && about.z==0) {
+        r[5] = c;   r[10]= c;
+        r[6] = s;   r[9] = -s;
+    } else if (about.x==0 && about.y==1 && about.z==0) {
+        r[0] = c;   r[10]= c;
+        r[8] = s;   r[2] = -s;
+    } else if (about.x==0 && about.y==0 && about.z==1) {
+        r[0] = c;   r[5] = c;
+        r[1] = s;   r[4] = -s;
+    } else {
+        tvec3<B> nabout = normalize(about);
+        B x = nabout.x;
+        B y = nabout.y;
+        B z = nabout.z;
+        T nc = 1 - c;
+        T xy = x * y;
+        T yz = y * z;
+        T zx = z * x;
+        T xs = x * s;
+        T ys = y * s;
+        T zs = z * s;
+        r[ 0] = x*x*nc +  c;    r[ 4] =  xy*nc - zs;    r[ 8] =  zx*nc + ys;
+        r[ 1] =  xy*nc + zs;    r[ 5] = y*y*nc +  c;    r[ 9] =  yz*nc - xs;
+        r[ 2] =  zx*nc - ys;    r[ 6] =  yz*nc + xs;    r[10] = z*z*nc +  c;
+    }
+}
+
+// ----------------------------------------------------------------------------------------
+// Arithmetic operators outside of class
+// ----------------------------------------------------------------------------------------
+
+/* We use non-friend functions here to prevent the compiler from using
+ * implicit conversions, for instance of a scalar to a vector. The result would
+ * not be what the caller expects.
+ *
+ * Also note that the order of the arguments in the inner loop is important since
+ * it determines the output type (only relevant when T != U).
+ */
+
+// matrix * vector, result is a vector of the same type than the input vector
+template <typename T, typename U>
+typename tmat44<U>::col_type PURE operator *(const tmat44<T>& lv, const tvec4<U>& rv) {
+    typename tmat44<U>::col_type result;
+    for (size_t r=0 ; r<tmat44<T>::row_size() ; r++)
+        result += rv[r]*lv[r];
+    return result;
+}
+
+// vector * matrix, result is a vector of the same type than the input vector
+template <typename T, typename U>
+typename tmat44<U>::row_type PURE operator *(const tvec4<U>& rv, const tmat44<T>& lv) {
+    typename tmat44<U>::row_type result(tmat44<U>::row_type::NO_INIT);
+    for (size_t r=0 ; r<tmat44<T>::row_size() ; r++)
+        result[r] = dot(rv, lv[r]);
+    return result;
+}
+
+// matrix * scalar, result is a matrix of the same type than the input matrix
+template <typename T, typename U>
+tmat44<T> PURE operator *(const tmat44<T>& lv, U rv) {
+    tmat44<T> result(tmat44<T>::NO_INIT);
+    for (size_t r=0 ; r<tmat44<T>::row_size() ; r++)
+        result[r] = lv[r]*rv;
+    return result;
+}
+
+// scalar * matrix, result is a matrix of the same type than the input matrix
+template <typename T, typename U>
+tmat44<T> PURE operator *(U rv, const tmat44<T>& lv) {
+    tmat44<T> result(tmat44<T>::NO_INIT);
+    for (size_t r=0 ; r<tmat44<T>::row_size() ; r++)
+        result[r] = lv[r]*rv;
+    return result;
+}
+
+// ----------------------------------------------------------------------------------------
+
+/* FIXME: this should go into TMatSquareFunctions<> but for some reason
+ * BASE<T>::col_type is not accessible from there (???)
+ */
+template<typename T>
+typename tmat44<T>::col_type PURE diag(const tmat44<T>& m) {
+    return matrix::diag(m);
+}
+
+// ----------------------------------------------------------------------------------------
+
+typedef tmat44<float> mat4;
+
+// ----------------------------------------------------------------------------------------
+}; // namespace android
+
+#undef PURE
+
+#endif /* UI_MAT4_H */
diff --git a/include/ui/vec2.h b/include/ui/vec2.h
new file mode 100644
index 0000000..c31d0e4
--- /dev/null
+++ b/include/ui/vec2.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2013 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 UI_VEC2_H
+#define UI_VEC2_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#define TVEC_IMPLEMENTATION
+#include <ui/TVecHelpers.h>
+
+namespace android {
+// -------------------------------------------------------------------------------------
+
+template <typename T>
+class tvec2 :   public TVecProductOperators<tvec2, T>,
+                public TVecAddOperators<tvec2, T>,
+                public TVecUnaryOperators<tvec2, T>,
+                public TVecComparisonOperators<tvec2, T>,
+                public TVecFunctions<tvec2, T>
+{
+public:
+    enum no_init { NO_INIT };
+    typedef T value_type;
+    typedef T& reference;
+    typedef T const& const_reference;
+    typedef size_t size_type;
+
+    union {
+        struct { T x, y; };
+        struct { T s, t; };
+        struct { T r, g; };
+    };
+
+    enum { SIZE = 2 };
+    inline static size_type size() { return SIZE; }
+
+    // array access
+    inline T const& operator [] (size_t i) const { return (&x)[i]; }
+    inline T&       operator [] (size_t i)       { return (&x)[i]; }
+
+    // -----------------------------------------------------------------------
+    // we don't provide copy-ctor and operator= on purpose
+    // because we want the compiler generated versions
+
+    // constructors
+
+    // leaves object uninitialized. use with caution.
+    explicit tvec2(no_init) { }
+
+    // default constructor
+    tvec2() : x(0), y(0) { }
+
+    // handles implicit conversion to a tvec4. must not be explicit.
+    template<typename A>
+    tvec2(A v) : x(v), y(v) { }
+
+    template<typename A, typename B>
+    tvec2(A x, B y) : x(x), y(y) { }
+
+    template<typename A>
+    explicit tvec2(const tvec2<A>& v) : x(v.x), y(v.y) { }
+
+    template<typename A>
+    tvec2(const Impersonator< tvec2<A> >& v)
+        : x(((const tvec2<A>&)v).x),
+          y(((const tvec2<A>&)v).y) { }
+};
+
+// ----------------------------------------------------------------------------------------
+
+typedef tvec2<float> vec2;
+
+// ----------------------------------------------------------------------------------------
+}; // namespace android
+
+#endif /* UI_VEC4_H */
diff --git a/include/ui/vec3.h b/include/ui/vec3.h
new file mode 100644
index 0000000..dde59a9
--- /dev/null
+++ b/include/ui/vec3.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2013 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 UI_VEC3_H
+#define UI_VEC3_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <ui/vec2.h>
+
+namespace android {
+// -------------------------------------------------------------------------------------
+
+template <typename T>
+class tvec3 :   public TVecProductOperators<tvec3, T>,
+                public TVecAddOperators<tvec3, T>,
+                public TVecUnaryOperators<tvec3, T>,
+                public TVecComparisonOperators<tvec3, T>,
+                public TVecFunctions<tvec3, T>
+{
+public:
+    enum no_init { NO_INIT };
+    typedef T value_type;
+    typedef T& reference;
+    typedef T const& const_reference;
+    typedef size_t size_type;
+
+    union {
+        struct { T x, y, z; };
+        struct { T s, t, p; };
+        struct { T r, g, b; };
+        Impersonator< tvec2<T> > xy;
+        Impersonator< tvec2<T> > st;
+        Impersonator< tvec2<T> > rg;
+    };
+
+    enum { SIZE = 3 };
+    inline static size_type size() { return SIZE; }
+
+    // array access
+    inline T const& operator [] (size_t i) const { return (&x)[i]; }
+    inline T&       operator [] (size_t i)       { return (&x)[i]; }
+
+    // -----------------------------------------------------------------------
+    // we don't provide copy-ctor and operator= on purpose
+    // because we want the compiler generated versions
+
+    // constructors
+    // leaves object uninitialized. use with caution.
+    explicit tvec3(no_init) { }
+
+    // default constructor
+    tvec3() : x(0), y(0), z(0) { }
+
+    // handles implicit conversion to a tvec4. must not be explicit.
+    template<typename A>
+    tvec3(A v) : x(v), y(v), z(v) { }
+
+    template<typename A, typename B, typename C>
+    tvec3(A x, B y, C z) : x(x), y(y), z(z) { }
+
+    template<typename A, typename B>
+    tvec3(const tvec2<A>& v, B z) : x(v.x), y(v.y), z(z) { }
+
+    template<typename A>
+    explicit tvec3(const tvec3<A>& v) : x(v.x), y(v.y), z(v.z) { }
+
+    template<typename A>
+    tvec3(const Impersonator< tvec3<A> >& v)
+        : x(((const tvec3<A>&)v).x),
+          y(((const tvec3<A>&)v).y),
+          z(((const tvec3<A>&)v).z) { }
+
+    template<typename A, typename B>
+    tvec3(const Impersonator< tvec2<A> >& v, B z)
+        : x(((const tvec2<A>&)v).x),
+          y(((const tvec2<A>&)v).y),
+          z(z) { }
+
+    // cross product works only on vectors of size 3
+    template <typename RT>
+    friend inline
+    tvec3 __attribute__((pure)) cross(const tvec3& u, const tvec3<RT>& v) {
+        return tvec3(
+                u.y*v.z - u.z*v.y,
+                u.z*v.x - u.x*v.z,
+                u.x*v.y - u.y*v.x);
+    }
+};
+
+
+// ----------------------------------------------------------------------------------------
+
+typedef tvec3<float> vec3;
+
+// ----------------------------------------------------------------------------------------
+}; // namespace android
+
+#endif /* UI_VEC4_H */
diff --git a/include/ui/vec4.h b/include/ui/vec4.h
new file mode 100644
index 0000000..e03d331
--- /dev/null
+++ b/include/ui/vec4.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright 2013 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 UI_VEC4_H
+#define UI_VEC4_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <ui/vec3.h>
+
+namespace android {
+// -------------------------------------------------------------------------------------
+
+template <typename T>
+class tvec4 :   public TVecProductOperators<tvec4, T>,
+                public TVecAddOperators<tvec4, T>,
+                public TVecUnaryOperators<tvec4, T>,
+                public TVecComparisonOperators<tvec4, T>,
+                public TVecFunctions<tvec4, T>
+{
+public:
+    enum no_init { NO_INIT };
+    typedef T value_type;
+    typedef T& reference;
+    typedef T const& const_reference;
+    typedef size_t size_type;
+
+    union {
+        struct { T x, y, z, w; };
+        struct { T s, t, p, q; };
+        struct { T r, g, b, a; };
+        Impersonator< tvec2<T> > xy;
+        Impersonator< tvec2<T> > st;
+        Impersonator< tvec2<T> > rg;
+        Impersonator< tvec3<T> > xyz;
+        Impersonator< tvec3<T> > stp;
+        Impersonator< tvec3<T> > rgb;
+    };
+
+    enum { SIZE = 4 };
+    inline static size_type size() { return SIZE; }
+
+    // array access
+    inline T const& operator [] (size_t i) const { return (&x)[i]; }
+    inline T&       operator [] (size_t i)       { return (&x)[i]; }
+
+    // -----------------------------------------------------------------------
+    // we don't provide copy-ctor and operator= on purpose
+    // because we want the compiler generated versions
+
+    // constructors
+
+    // leaves object uninitialized. use with caution.
+    explicit tvec4(no_init) { }
+
+    // default constructor
+    tvec4() : x(0), y(0), z(0), w(0) { }
+
+    // handles implicit conversion to a tvec4. must not be explicit.
+    template<typename A>
+    tvec4(A v) : x(v), y(v), z(v), w(v) { }
+
+    template<typename A, typename B, typename C, typename D>
+    tvec4(A x, B y, C z, D w) : x(x), y(y), z(z), w(w) { }
+
+    template<typename A, typename B, typename C>
+    tvec4(const tvec2<A>& v, B z, C w) : x(v.x), y(v.y), z(z), w(w) { }
+
+    template<typename A, typename B>
+    tvec4(const tvec3<A>& v, B w) : x(v.x), y(v.y), z(v.z), w(w) { }
+
+    template<typename A>
+    explicit tvec4(const tvec4<A>& v) : x(v.x), y(v.y), z(v.z), w(v.w) { }
+
+    template<typename A>
+    tvec4(const Impersonator< tvec4<A> >& v)
+        : x(((const tvec4<A>&)v).x),
+          y(((const tvec4<A>&)v).y),
+          z(((const tvec4<A>&)v).z),
+          w(((const tvec4<A>&)v).w) { }
+
+    template<typename A, typename B>
+    tvec4(const Impersonator< tvec3<A> >& v, B w)
+        : x(((const tvec3<A>&)v).x),
+          y(((const tvec3<A>&)v).y),
+          z(((const tvec3<A>&)v).z),
+          w(w) { }
+
+    template<typename A, typename B, typename C>
+    tvec4(const Impersonator< tvec2<A> >& v, B z, C w)
+        : x(((const tvec2<A>&)v).x),
+          y(((const tvec2<A>&)v).y),
+          z(z),
+          w(w) { }
+};
+
+// ----------------------------------------------------------------------------------------
+
+typedef tvec4<float> vec4;
+
+// ----------------------------------------------------------------------------------------
+}; // namespace android
+
+#endif /* UI_VEC4_H */
diff --git a/include/utils/AndroidThreads.h b/include/utils/AndroidThreads.h
deleted file mode 100644
index 4eee14d..0000000
--- a/include/utils/AndroidThreads.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2007 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 _LIBS_UTILS_ANDROID_THREADS_H
-#define _LIBS_UTILS_ANDROID_THREADS_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#if defined(HAVE_PTHREADS)
-# include <pthread.h>
-#endif
-
-#include <utils/ThreadDefs.h>
-
-// ---------------------------------------------------------------------------
-// C API
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-// Create and run a new thread.
-extern int androidCreateThread(android_thread_func_t, void *);
-
-// Create thread with lots of parameters
-extern int androidCreateThreadEtc(android_thread_func_t entryFunction,
-                                  void *userData,
-                                  const char* threadName,
-                                  int32_t threadPriority,
-                                  size_t threadStackSize,
-                                  android_thread_id_t *threadId);
-
-// Get some sort of unique identifier for the current thread.
-extern android_thread_id_t androidGetThreadId();
-
-// Low-level thread creation -- never creates threads that can
-// interact with the Java VM.
-extern int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
-                                     void *userData,
-                                     const char* threadName,
-                                     int32_t threadPriority,
-                                     size_t threadStackSize,
-                                     android_thread_id_t *threadId);
-
-// set the same of the running thread
-extern void androidSetThreadName(const char* name);
-
-// Used by the Java Runtime to control how threads are created, so that
-// they can be proper and lovely Java threads.
-typedef int (*android_create_thread_fn)(android_thread_func_t entryFunction,
-                                        void *userData,
-                                        const char* threadName,
-                                        int32_t threadPriority,
-                                        size_t threadStackSize,
-                                        android_thread_id_t *threadId);
-
-extern void androidSetCreateThreadFunc(android_create_thread_fn func);
-
-// ------------------------------------------------------------------
-// Extra functions working with raw pids.
-
-// Get pid for the current thread.
-extern pid_t androidGetTid();
-
-#ifdef HAVE_ANDROID_OS
-// Change the priority AND scheduling group of a particular thread.  The priority
-// should be one of the ANDROID_PRIORITY constants.  Returns INVALID_OPERATION
-// if the priority set failed, else another value if just the group set failed;
-// in either case errno is set.  Thread ID zero means current thread.
-extern int androidSetThreadPriority(pid_t tid, int prio);
-
-// Get the current priority of a particular thread. Returns one of the
-// ANDROID_PRIORITY constants or a negative result in case of error.
-extern int androidGetThreadPriority(pid_t tid);
-#endif
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
-// ----------------------------------------------------------------------------
-// C++ API
-#ifdef __cplusplus
-namespace android {
-// ----------------------------------------------------------------------------
-
-// Create and run a new thread.
-inline bool createThread(thread_func_t f, void *a) {
-    return androidCreateThread(f, a) ? true : false;
-}
-
-// Create thread with lots of parameters
-inline bool createThreadEtc(thread_func_t entryFunction,
-                            void *userData,
-                            const char* threadName = "android:unnamed_thread",
-                            int32_t threadPriority = PRIORITY_DEFAULT,
-                            size_t threadStackSize = 0,
-                            thread_id_t *threadId = 0)
-{
-    return androidCreateThreadEtc(entryFunction, userData, threadName,
-        threadPriority, threadStackSize, threadId) ? true : false;
-}
-
-// Get some sort of unique identifier for the current thread.
-inline thread_id_t getThreadId() {
-    return androidGetThreadId();
-}
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-#endif  // __cplusplus
-// ----------------------------------------------------------------------------
-
-#endif // _LIBS_UTILS_ANDROID_THREADS_H
diff --git a/include/utils/Atomic.h b/include/utils/Atomic.h
deleted file mode 100644
index 7eb476c..0000000
--- a/include/utils/Atomic.h
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2005 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_UTILS_ATOMIC_H
-#define ANDROID_UTILS_ATOMIC_H
-
-#include <cutils/atomic.h>
-
-#endif // ANDROID_UTILS_ATOMIC_H
diff --git a/include/utils/BasicHashtable.h b/include/utils/BasicHashtable.h
deleted file mode 100644
index 7a6c96c..0000000
--- a/include/utils/BasicHashtable.h
+++ /dev/null
@@ -1,401 +0,0 @@
-/*
- * Copyright (C) 2011 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_BASIC_HASHTABLE_H
-#define ANDROID_BASIC_HASHTABLE_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <utils/SharedBuffer.h>
-#include <utils/TypeHelpers.h>
-
-namespace android {
-
-/* Implementation type.  Nothing to see here. */
-class BasicHashtableImpl {
-protected:
-    struct Bucket {
-        // The collision flag indicates that the bucket is part of a collision chain
-        // such that at least two entries both hash to this bucket.  When true, we
-        // may need to seek further along the chain to find the entry.
-        static const uint32_t COLLISION = 0x80000000UL;
-
-        // The present flag indicates that the bucket contains an initialized entry value.
-        static const uint32_t PRESENT   = 0x40000000UL;
-
-        // Mask for 30 bits worth of the hash code that are stored within the bucket to
-        // speed up lookups and rehashing by eliminating the need to recalculate the
-        // hash code of the entry's key.
-        static const uint32_t HASH_MASK = 0x3fffffffUL;
-
-        // Combined value that stores the collision and present flags as well as
-        // a 30 bit hash code.
-        uint32_t cookie;
-
-        // Storage for the entry begins here.
-        char entry[0];
-    };
-
-    BasicHashtableImpl(size_t entrySize, bool hasTrivialDestructor,
-            size_t minimumInitialCapacity, float loadFactor);
-    BasicHashtableImpl(const BasicHashtableImpl& other);
-
-    void dispose();
-
-    inline void edit() {
-        if (mBuckets && !SharedBuffer::bufferFromData(mBuckets)->onlyOwner()) {
-            clone();
-        }
-    }
-
-    void setTo(const BasicHashtableImpl& other);
-    void clear();
-
-    ssize_t next(ssize_t index) const;
-    ssize_t find(ssize_t index, hash_t hash, const void* __restrict__ key) const;
-    size_t add(hash_t hash, const void* __restrict__ entry);
-    void removeAt(size_t index);
-    void rehash(size_t minimumCapacity, float loadFactor);
-
-    const size_t mBucketSize; // number of bytes per bucket including the entry
-    const bool mHasTrivialDestructor; // true if the entry type does not require destruction
-    size_t mCapacity;         // number of buckets that can be filled before exceeding load factor
-    float mLoadFactor;        // load factor
-    size_t mSize;             // number of elements actually in the table
-    size_t mFilledBuckets;    // number of buckets for which collision or present is true
-    size_t mBucketCount;      // number of slots in the mBuckets array
-    void* mBuckets;           // array of buckets, as a SharedBuffer
-
-    inline const Bucket& bucketAt(const void* __restrict__ buckets, size_t index) const {
-        return *reinterpret_cast<const Bucket*>(
-                static_cast<const uint8_t*>(buckets) + index * mBucketSize);
-    }
-
-    inline Bucket& bucketAt(void* __restrict__ buckets, size_t index) const {
-        return *reinterpret_cast<Bucket*>(static_cast<uint8_t*>(buckets) + index * mBucketSize);
-    }
-
-    virtual bool compareBucketKey(const Bucket& bucket, const void* __restrict__ key) const = 0;
-    virtual void initializeBucketEntry(Bucket& bucket, const void* __restrict__ entry) const = 0;
-    virtual void destroyBucketEntry(Bucket& bucket) const = 0;
-
-private:
-    void clone();
-
-    // Allocates a bucket array as a SharedBuffer.
-    void* allocateBuckets(size_t count) const;
-
-    // Releases a bucket array's associated SharedBuffer.
-    void releaseBuckets(void* __restrict__ buckets, size_t count) const;
-
-    // Destroys the contents of buckets (invokes destroyBucketEntry for each
-    // populated bucket if needed).
-    void destroyBuckets(void* __restrict__ buckets, size_t count) const;
-
-    // Copies the content of buckets (copies the cookie and invokes copyBucketEntry
-    // for each populated bucket if needed).
-    void copyBuckets(const void* __restrict__ fromBuckets,
-            void* __restrict__ toBuckets, size_t count) const;
-
-    // Determines the appropriate size of a bucket array to store a certain minimum
-    // number of entries and returns its effective capacity.
-    static void determineCapacity(size_t minimumCapacity, float loadFactor,
-            size_t* __restrict__ outBucketCount, size_t* __restrict__ outCapacity);
-
-    // Trim a hash code to 30 bits to match what we store in the bucket's cookie.
-    inline static hash_t trimHash(hash_t hash) {
-        return (hash & Bucket::HASH_MASK) ^ (hash >> 30);
-    }
-
-    // Returns the index of the first bucket that is in the collision chain
-    // for the specified hash code, given the total number of buckets.
-    // (Primary hash)
-    inline static size_t chainStart(hash_t hash, size_t count) {
-        return hash % count;
-    }
-
-    // Returns the increment to add to a bucket index to seek to the next bucket
-    // in the collision chain for the specified hash code, given the total number of buckets.
-    // (Secondary hash)
-    inline static size_t chainIncrement(hash_t hash, size_t count) {
-        return ((hash >> 7) | (hash << 25)) % (count - 1) + 1;
-    }
-
-    // Returns the index of the next bucket that is in the collision chain
-    // that is defined by the specified increment, given the total number of buckets.
-    inline static size_t chainSeek(size_t index, size_t increment, size_t count) {
-        return (index + increment) % count;
-    }
-};
-
-/*
- * A BasicHashtable stores entries that are indexed by hash code in place
- * within an array.  The basic operations are finding entries by key,
- * adding new entries and removing existing entries.
- *
- * This class provides a very limited set of operations with simple semantics.
- * It is intended to be used as a building block to construct more complex
- * and interesting data structures such as HashMap.  Think very hard before
- * adding anything extra to BasicHashtable, it probably belongs at a
- * higher level of abstraction.
- *
- * TKey: The key type.
- * TEntry: The entry type which is what is actually stored in the array.
- *
- * TKey must support the following contract:
- *     bool operator==(const TKey& other) const;  // return true if equal
- *     bool operator!=(const TKey& other) const;  // return true if unequal
- *
- * TEntry must support the following contract:
- *     const TKey& getKey() const;  // get the key from the entry
- *
- * This class supports storing entries with duplicate keys.  Of course, it can't
- * tell them apart during removal so only the first entry will be removed.
- * We do this because it means that operations like add() can't fail.
- */
-template <typename TKey, typename TEntry>
-class BasicHashtable : private BasicHashtableImpl {
-public:
-    /* Creates a hashtable with the specified minimum initial capacity.
-     * The underlying array will be created when the first entry is added.
-     *
-     * minimumInitialCapacity: The minimum initial capacity for the hashtable.
-     *     Default is 0.
-     * loadFactor: The desired load factor for the hashtable, between 0 and 1.
-     *     Default is 0.75.
-     */
-    BasicHashtable(size_t minimumInitialCapacity = 0, float loadFactor = 0.75f);
-
-    /* Copies a hashtable.
-     * The underlying storage is shared copy-on-write.
-     */
-    BasicHashtable(const BasicHashtable& other);
-
-    /* Clears and destroys the hashtable.
-     */
-    virtual ~BasicHashtable();
-
-    /* Making this hashtable a copy of the other hashtable.
-     * The underlying storage is shared copy-on-write.
-     *
-     * other: The hashtable to copy.
-     */
-    inline BasicHashtable<TKey, TEntry>& operator =(const BasicHashtable<TKey, TEntry> & other) {
-        setTo(other);
-        return *this;
-    }
-
-    /* Returns the number of entries in the hashtable.
-     */
-    inline size_t size() const {
-        return mSize;
-    }
-
-    /* Returns the capacity of the hashtable, which is the number of elements that can
-     * added to the hashtable without requiring it to be grown.
-     */
-    inline size_t capacity() const {
-        return mCapacity;
-    }
-
-    /* Returns the number of buckets that the hashtable has, which is the size of its
-     * underlying array.
-     */
-    inline size_t bucketCount() const {
-        return mBucketCount;
-    }
-
-    /* Returns the load factor of the hashtable. */
-    inline float loadFactor() const {
-        return mLoadFactor;
-    };
-
-    /* Returns a const reference to the entry at the specified index.
-     *
-     * index:   The index of the entry to retrieve.  Must be a valid index within
-     *          the bounds of the hashtable.
-     */
-    inline const TEntry& entryAt(size_t index) const {
-        return entryFor(bucketAt(mBuckets, index));
-    }
-
-    /* Returns a non-const reference to the entry at the specified index.
-     *
-     * index: The index of the entry to edit.  Must be a valid index within
-     *        the bounds of the hashtable.
-     */
-    inline TEntry& editEntryAt(size_t index) {
-        edit();
-        return entryFor(bucketAt(mBuckets, index));
-    }
-
-    /* Clears the hashtable.
-     * All entries in the hashtable are destroyed immediately.
-     * If you need to do something special with the entries in the hashtable then iterate
-     * over them and do what you need before clearing the hashtable.
-     */
-    inline void clear() {
-        BasicHashtableImpl::clear();
-    }
-
-    /* Returns the index of the next entry in the hashtable given the index of a previous entry.
-     * If the given index is -1, then returns the index of the first entry in the hashtable,
-     * if there is one, or -1 otherwise.
-     * If the given index is not -1, then returns the index of the next entry in the hashtable,
-     * in strictly increasing order, or -1 if there are none left.
-     *
-     * index:   The index of the previous entry that was iterated, or -1 to begin
-     *          iteration at the beginning of the hashtable.
-     */
-    inline ssize_t next(ssize_t index) const {
-        return BasicHashtableImpl::next(index);
-    }
-
-    /* Finds the index of an entry with the specified key.
-     * If the given index is -1, then returns the index of the first matching entry,
-     * otherwise returns the index of the next matching entry.
-     * If the hashtable contains multiple entries with keys that match the requested
-     * key, then the sequence of entries returned is arbitrary.
-     * Returns -1 if no entry was found.
-     *
-     * index:   The index of the previous entry with the specified key, or -1 to
-     *          find the first matching entry.
-     * hash:    The hashcode of the key.
-     * key:     The key.
-     */
-    inline ssize_t find(ssize_t index, hash_t hash, const TKey& key) const {
-        return BasicHashtableImpl::find(index, hash, &key);
-    }
-
-    /* Adds the entry to the hashtable.
-     * Returns the index of the newly added entry.
-     * If an entry with the same key already exists, then a duplicate entry is added.
-     * If the entry will not fit, then the hashtable's capacity is increased and
-     * its contents are rehashed.  See rehash().
-     *
-     * hash:    The hashcode of the key.
-     * entry:   The entry to add.
-     */
-    inline size_t add(hash_t hash, const TEntry& entry) {
-        return BasicHashtableImpl::add(hash, &entry);
-    }
-
-    /* Removes the entry with the specified index from the hashtable.
-     * The entry is destroyed immediately.
-     * The index must be valid.
-     *
-     * The hashtable is not compacted after an item is removed, so it is legal
-     * to continue iterating over the hashtable using next() or find().
-     *
-     * index:   The index of the entry to remove.  Must be a valid index within the
-     *          bounds of the hashtable, and it must refer to an existing entry.
-     */
-    inline void removeAt(size_t index) {
-        BasicHashtableImpl::removeAt(index);
-    }
-
-    /* Rehashes the contents of the hashtable.
-     * Grows the hashtable to at least the specified minimum capacity or the
-     * current number of elements, whichever is larger.
-     *
-     * Rehashing causes all entries to be copied and the entry indices may change.
-     * Although the hash codes are cached by the hashtable, rehashing can be an
-     * expensive operation and should be avoided unless the hashtable's size
-     * needs to be changed.
-     *
-     * Rehashing is the only way to change the capacity or load factor of the
-     * hashtable once it has been created.  It can be used to compact the
-     * hashtable by choosing a minimum capacity that is smaller than the current
-     * capacity (such as 0).
-     *
-     * minimumCapacity: The desired minimum capacity after rehashing.
-     * loadFactor: The desired load factor after rehashing.
-     */
-    inline void rehash(size_t minimumCapacity, float loadFactor) {
-        BasicHashtableImpl::rehash(minimumCapacity, loadFactor);
-    }
-
-    /* Determines whether there is room to add another entry without rehashing.
-     * When this returns true, a subsequent add() operation is guaranteed to
-     * complete without performing a rehash.
-     */
-    inline bool hasMoreRoom() const {
-        return mCapacity > mFilledBuckets;
-    }
-
-protected:
-    static inline const TEntry& entryFor(const Bucket& bucket) {
-        return reinterpret_cast<const TEntry&>(bucket.entry);
-    }
-
-    static inline TEntry& entryFor(Bucket& bucket) {
-        return reinterpret_cast<TEntry&>(bucket.entry);
-    }
-
-    virtual bool compareBucketKey(const Bucket& bucket, const void* __restrict__ key) const;
-    virtual void initializeBucketEntry(Bucket& bucket, const void* __restrict__ entry) const;
-    virtual void destroyBucketEntry(Bucket& bucket) const;
-
-private:
-    // For dumping the raw contents of a hashtable during testing.
-    friend class BasicHashtableTest;
-    inline uint32_t cookieAt(size_t index) const {
-        return bucketAt(mBuckets, index).cookie;
-    }
-};
-
-template <typename TKey, typename TEntry>
-BasicHashtable<TKey, TEntry>::BasicHashtable(size_t minimumInitialCapacity, float loadFactor) :
-        BasicHashtableImpl(sizeof(TEntry), traits<TEntry>::has_trivial_dtor,
-                minimumInitialCapacity, loadFactor) {
-}
-
-template <typename TKey, typename TEntry>
-BasicHashtable<TKey, TEntry>::BasicHashtable(const BasicHashtable<TKey, TEntry>& other) :
-        BasicHashtableImpl(other) {
-}
-
-template <typename TKey, typename TEntry>
-BasicHashtable<TKey, TEntry>::~BasicHashtable() {
-    dispose();
-}
-
-template <typename TKey, typename TEntry>
-bool BasicHashtable<TKey, TEntry>::compareBucketKey(const Bucket& bucket,
-        const void* __restrict__ key) const {
-    return entryFor(bucket).getKey() == *static_cast<const TKey*>(key);
-}
-
-template <typename TKey, typename TEntry>
-void BasicHashtable<TKey, TEntry>::initializeBucketEntry(Bucket& bucket,
-        const void* __restrict__ entry) const {
-    if (!traits<TEntry>::has_trivial_copy) {
-        new (&entryFor(bucket)) TEntry(*(static_cast<const TEntry*>(entry)));
-    } else {
-        memcpy(&entryFor(bucket), entry, sizeof(TEntry));
-    }
-}
-
-template <typename TKey, typename TEntry>
-void BasicHashtable<TKey, TEntry>::destroyBucketEntry(Bucket& bucket) const {
-    if (!traits<TEntry>::has_trivial_dtor) {
-        entryFor(bucket).~TEntry();
-    }
-}
-
-}; // namespace android
-
-#endif // ANDROID_BASIC_HASHTABLE_H
diff --git a/include/utils/BitSet.h b/include/utils/BitSet.h
deleted file mode 100644
index e189d0c..0000000
--- a/include/utils/BitSet.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef UTILS_BITSET_H
-#define UTILS_BITSET_H
-
-#include <stdint.h>
-#include <utils/TypeHelpers.h>
-
-/*
- * Contains some bit manipulation helpers.
- */
-
-namespace android {
-
-// A simple set of 32 bits that can be individually marked or cleared.
-struct BitSet32 {
-    uint32_t value;
-
-    inline BitSet32() : value(0) { }
-    explicit inline BitSet32(uint32_t value) : value(value) { }
-
-    // Gets the value associated with a particular bit index.
-    static inline uint32_t valueForBit(uint32_t n) { return 0x80000000 >> n; }
-
-    // Clears the bit set.
-    inline void clear() { value = 0; }
-
-    // Returns the number of marked bits in the set.
-    inline uint32_t count() const { return __builtin_popcount(value); }
-
-    // Returns true if the bit set does not contain any marked bits.
-    inline bool isEmpty() const { return ! value; }
-
-    // Returns true if the bit set does not contain any unmarked bits.
-    inline bool isFull() const { return value == 0xffffffff; }
-
-    // Returns true if the specified bit is marked.
-    inline bool hasBit(uint32_t n) const { return value & valueForBit(n); }
-
-    // Marks the specified bit.
-    inline void markBit(uint32_t n) { value |= valueForBit(n); }
-
-    // Clears the specified bit.
-    inline void clearBit(uint32_t n) { value &= ~ valueForBit(n); }
-
-    // Finds the first marked bit in the set.
-    // Result is undefined if all bits are unmarked.
-    inline uint32_t firstMarkedBit() const { return __builtin_clz(value); }
-
-    // Finds the first unmarked bit in the set.
-    // Result is undefined if all bits are marked.
-    inline uint32_t firstUnmarkedBit() const { return __builtin_clz(~ value); }
-
-    // Finds the last marked bit in the set.
-    // Result is undefined if all bits are unmarked.
-    inline uint32_t lastMarkedBit() const { return 31 - __builtin_ctz(value); }
-
-    // Finds the first marked bit in the set and clears it.  Returns the bit index.
-    // Result is undefined if all bits are unmarked.
-    inline uint32_t clearFirstMarkedBit() {
-        uint32_t n = firstMarkedBit();
-        clearBit(n);
-        return n;
-    }
-
-    // Finds the first unmarked bit in the set and marks it.  Returns the bit index.
-    // Result is undefined if all bits are marked.
-    inline uint32_t markFirstUnmarkedBit() {
-        uint32_t n = firstUnmarkedBit();
-        markBit(n);
-        return n;
-    }
-
-    // Finds the last marked bit in the set and clears it.  Returns the bit index.
-    // Result is undefined if all bits are unmarked.
-    inline uint32_t clearLastMarkedBit() {
-        uint32_t n = lastMarkedBit();
-        clearBit(n);
-        return n;
-    }
-
-    // Gets the index of the specified bit in the set, which is the number of
-    // marked bits that appear before the specified bit.
-    inline uint32_t getIndexOfBit(uint32_t n) const {
-        return __builtin_popcount(value & ~(0xffffffffUL >> n));
-    }
-
-    inline bool operator== (const BitSet32& other) const { return value == other.value; }
-    inline bool operator!= (const BitSet32& other) const { return value != other.value; }
-};
-
-ANDROID_BASIC_TYPES_TRAITS(BitSet32)
-
-} // namespace android
-
-#endif // UTILS_BITSET_H
diff --git a/include/utils/BlobCache.h b/include/utils/BlobCache.h
deleted file mode 100644
index 4f342a2..0000000
--- a/include/utils/BlobCache.h
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- ** Copyright 2011, 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_BLOB_CACHE_H
-#define ANDROID_BLOB_CACHE_H
-
-#include <stddef.h>
-
-#include <utils/Flattenable.h>
-#include <utils/RefBase.h>
-#include <utils/SortedVector.h>
-#include <utils/threads.h>
-
-namespace android {
-
-// A BlobCache is an in-memory cache for binary key/value pairs.  A BlobCache
-// does NOT provide any thread-safety guarantees.
-//
-// The cache contents can be serialized to an in-memory buffer or mmap'd file
-// and then reloaded in a subsequent execution of the program.  This
-// serialization is non-portable and the data should only be used by the device
-// that generated it.
-class BlobCache : public RefBase, public Flattenable {
-public:
-
-    // Create an empty blob cache. The blob cache will cache key/value pairs
-    // with key and value sizes less than or equal to maxKeySize and
-    // maxValueSize, respectively. The total combined size of ALL cache entries
-    // (key sizes plus value sizes) will not exceed maxTotalSize.
-    BlobCache(size_t maxKeySize, size_t maxValueSize, size_t maxTotalSize);
-
-    // set inserts a new binary value into the cache and associates it with the
-    // given binary key.  If the key or value are too large for the cache then
-    // the cache remains unchanged.  This includes the case where a different
-    // value was previously associated with the given key - the old value will
-    // remain in the cache.  If the given key and value are small enough to be
-    // put in the cache (based on the maxKeySize, maxValueSize, and maxTotalSize
-    // values specified to the BlobCache constructor), then the key/value pair
-    // will be in the cache after set returns.  Note, however, that a subsequent
-    // call to set may evict old key/value pairs from the cache.
-    //
-    // Preconditions:
-    //   key != NULL
-    //   0 < keySize
-    //   value != NULL
-    //   0 < valueSize
-    void set(const void* key, size_t keySize, const void* value,
-            size_t valueSize);
-
-    // get retrieves from the cache the binary value associated with a given
-    // binary key.  If the key is present in the cache then the length of the
-    // binary value associated with that key is returned.  If the value argument
-    // is non-NULL and the size of the cached value is less than valueSize bytes
-    // then the cached value is copied into the buffer pointed to by the value
-    // argument.  If the key is not present in the cache then 0 is returned and
-    // the buffer pointed to by the value argument is not modified.
-    //
-    // Note that when calling get multiple times with the same key, the later
-    // calls may fail, returning 0, even if earlier calls succeeded.  The return
-    // value must be checked for each call.
-    //
-    // Preconditions:
-    //   key != NULL
-    //   0 < keySize
-    //   0 <= valueSize
-    size_t get(const void* key, size_t keySize, void* value, size_t valueSize);
-
-    // getFlattenedSize returns the number of bytes needed to store the entire
-    // serialized cache.
-    virtual size_t getFlattenedSize() const;
-
-    // getFdCount returns the number of file descriptors that will result from
-    // flattening the cache.  This will always return 0 so as to allow the
-    // flattened cache to be saved to disk and then later restored.
-    virtual size_t getFdCount() const;
-
-    // flatten serializes the current contents of the cache into the memory
-    // pointed to by 'buffer'.  The serialized cache contents can later be
-    // loaded into a BlobCache object using the unflatten method.  The contents
-    // of the BlobCache object will not be modified.
-    //
-    // Preconditions:
-    //   size >= this.getFlattenedSize()
-    //   count == 0
-    virtual status_t flatten(void* buffer, size_t size, int fds[],
-            size_t count) const;
-
-    // unflatten replaces the contents of the cache with the serialized cache
-    // contents in the memory pointed to by 'buffer'.  The previous contents of
-    // the BlobCache will be evicted from the cache.  If an error occurs while
-    // unflattening the serialized cache contents then the BlobCache will be
-    // left in an empty state.
-    //
-    // Preconditions:
-    //   count == 0
-    virtual status_t unflatten(void const* buffer, size_t size, int fds[],
-            size_t count);
-
-private:
-    // Copying is disallowed.
-    BlobCache(const BlobCache&);
-    void operator=(const BlobCache&);
-
-    // A random function helper to get around MinGW not having nrand48()
-    long int blob_random();
-
-    // clean evicts a randomly chosen set of entries from the cache such that
-    // the total size of all remaining entries is less than mMaxTotalSize/2.
-    void clean();
-
-    // isCleanable returns true if the cache is full enough for the clean method
-    // to have some effect, and false otherwise.
-    bool isCleanable() const;
-
-    // A Blob is an immutable sized unstructured data blob.
-    class Blob : public RefBase {
-    public:
-        Blob(const void* data, size_t size, bool copyData);
-        ~Blob();
-
-        bool operator<(const Blob& rhs) const;
-
-        const void* getData() const;
-        size_t getSize() const;
-
-    private:
-        // Copying is not allowed.
-        Blob(const Blob&);
-        void operator=(const Blob&);
-
-        // mData points to the buffer containing the blob data.
-        const void* mData;
-
-        // mSize is the size of the blob data in bytes.
-        size_t mSize;
-
-        // mOwnsData indicates whether or not this Blob object should free the
-        // memory pointed to by mData when the Blob gets destructed.
-        bool mOwnsData;
-    };
-
-    // A CacheEntry is a single key/value pair in the cache.
-    class CacheEntry {
-    public:
-        CacheEntry();
-        CacheEntry(const sp<Blob>& key, const sp<Blob>& value);
-        CacheEntry(const CacheEntry& ce);
-
-        bool operator<(const CacheEntry& rhs) const;
-        const CacheEntry& operator=(const CacheEntry&);
-
-        sp<Blob> getKey() const;
-        sp<Blob> getValue() const;
-
-        void setValue(const sp<Blob>& value);
-
-    private:
-
-        // mKey is the key that identifies the cache entry.
-        sp<Blob> mKey;
-
-        // mValue is the cached data associated with the key.
-        sp<Blob> mValue;
-    };
-
-    // A Header is the header for the entire BlobCache serialization format. No
-    // need to make this portable, so we simply write the struct out.
-    struct Header {
-        // mMagicNumber is the magic number that identifies the data as
-        // serialized BlobCache contents.  It must always contain 'Blb$'.
-        uint32_t mMagicNumber;
-
-        // mBlobCacheVersion is the serialization format version.
-        uint32_t mBlobCacheVersion;
-
-        // mDeviceVersion is the device-specific version of the cache.  This can
-        // be used to invalidate the cache.
-        uint32_t mDeviceVersion;
-
-        // mNumEntries is number of cache entries following the header in the
-        // data.
-        size_t mNumEntries;
-    };
-
-    // An EntryHeader is the header for a serialized cache entry.  No need to
-    // make this portable, so we simply write the struct out.  Each EntryHeader
-    // is followed imediately by the key data and then the value data.
-    //
-    // The beginning of each serialized EntryHeader is 4-byte aligned, so the
-    // number of bytes that a serialized cache entry will occupy is:
-    //
-    //   ((sizeof(EntryHeader) + keySize + valueSize) + 3) & ~3
-    //
-    struct EntryHeader {
-        // mKeySize is the size of the entry key in bytes.
-        size_t mKeySize;
-
-        // mValueSize is the size of the entry value in bytes.
-        size_t mValueSize;
-
-        // mData contains both the key and value data for the cache entry.  The
-        // key comes first followed immediately by the value.
-        uint8_t mData[];
-    };
-
-    // mMaxKeySize is the maximum key size that will be cached. Calls to
-    // BlobCache::set with a keySize parameter larger than mMaxKeySize will
-    // simply not add the key/value pair to the cache.
-    const size_t mMaxKeySize;
-
-    // mMaxValueSize is the maximum value size that will be cached. Calls to
-    // BlobCache::set with a valueSize parameter larger than mMaxValueSize will
-    // simply not add the key/value pair to the cache.
-    const size_t mMaxValueSize;
-
-    // mMaxTotalSize is the maximum size that all cache entries can occupy. This
-    // includes space for both keys and values. When a call to BlobCache::set
-    // would otherwise cause this limit to be exceeded, either the key/value
-    // pair passed to BlobCache::set will not be cached or other cache entries
-    // will be evicted from the cache to make room for the new entry.
-    const size_t mMaxTotalSize;
-
-    // mTotalSize is the total combined size of all keys and values currently in
-    // the cache.
-    size_t mTotalSize;
-
-    // mRandState is the pseudo-random number generator state. It is passed to
-    // nrand48 to generate random numbers when needed.
-    unsigned short mRandState[3];
-
-    // mCacheEntries stores all the cache entries that are resident in memory.
-    // Cache entries are added to it by the 'set' method.
-    SortedVector<CacheEntry> mCacheEntries;
-};
-
-}
-
-#endif // ANDROID_BLOB_CACHE_H
diff --git a/include/utils/ByteOrder.h b/include/utils/ByteOrder.h
deleted file mode 100644
index baa3a83..0000000
--- a/include/utils/ByteOrder.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2006 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 _LIBS_UTILS_BYTE_ORDER_H
-#define _LIBS_UTILS_BYTE_ORDER_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#ifdef HAVE_WINSOCK
-#include <winsock2.h>
-#else
-#include <netinet/in.h>
-#endif
-
-/*
- * These macros are like the hton/ntoh byte swapping macros,
- * except they allow you to swap to and from the "device" byte
- * order.  The device byte order is the endianness of the target
- * device -- for the ARM CPUs we use today, this is little endian.
- *
- * Note that the byte swapping functions have not been optimized
- * much; performance is currently not an issue for them since the
- * intent is to allow us to avoid byte swapping on the device.
- */
-
-static inline uint32_t android_swap_long(uint32_t v)
-{
-    return (v<<24) | ((v<<8)&0x00FF0000) | ((v>>8)&0x0000FF00) | (v>>24);
-}
-
-static inline uint16_t android_swap_short(uint16_t v)
-{
-    return (v<<8) | (v>>8);
-}
-
-#define DEVICE_BYTE_ORDER LITTLE_ENDIAN
-
-#if BYTE_ORDER == DEVICE_BYTE_ORDER
-
-#define	dtohl(x)	(x)
-#define	dtohs(x)	(x)
-#define	htodl(x)	(x)
-#define	htods(x)	(x)
-
-#else
-
-#define	dtohl(x)	(android_swap_long(x))
-#define	dtohs(x)	(android_swap_short(x))
-#define	htodl(x)	(android_swap_long(x))
-#define	htods(x)	(android_swap_short(x))
-
-#endif
-
-#if BYTE_ORDER == LITTLE_ENDIAN
-#define fromlel(x) (x)
-#define fromles(x) (x)
-#define tolel(x) (x)
-#define toles(x) (x)
-#else
-#define fromlel(x) (android_swap_long(x))
-#define fromles(x) (android_swap_short(x))
-#define tolel(x) (android_swap_long(x))
-#define toles(x) (android_swap_short(x))
-#endif
-
-#endif // _LIBS_UTILS_BYTE_ORDER_H
diff --git a/include/utils/CallStack.h b/include/utils/CallStack.h
deleted file mode 100644
index 61dc832..0000000
--- a/include/utils/CallStack.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2007 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_CALLSTACK_H
-#define ANDROID_CALLSTACK_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/String8.h>
-#include <corkscrew/backtrace.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-class CallStack
-{
-public:
-    enum {
-        MAX_DEPTH = 31
-    };
-
-    CallStack();
-    CallStack(const char* logtag, int32_t ignoreDepth=1,
-            int32_t maxDepth=MAX_DEPTH);
-    CallStack(const CallStack& rhs);
-    ~CallStack();
-
-    CallStack& operator = (const CallStack& rhs);
-    
-    bool operator == (const CallStack& rhs) const;
-    bool operator != (const CallStack& rhs) const;
-    bool operator < (const CallStack& rhs) const;
-    bool operator >= (const CallStack& rhs) const;
-    bool operator > (const CallStack& rhs) const;
-    bool operator <= (const CallStack& rhs) const;
-    
-    const void* operator [] (int index) const;
-    
-    void clear();
-
-    void update(int32_t ignoreDepth=1, int32_t maxDepth=MAX_DEPTH);
-
-    // Dump a stack trace to the log using the supplied logtag
-    void dump(const char* logtag, const char* prefix = 0) const;
-
-    // Return a string (possibly very long) containing the complete stack trace
-    String8 toString(const char* prefix = 0) const;
-    
-    size_t size() const { return mCount; }
-
-private:
-    size_t mCount;
-    backtrace_frame_t mStack[MAX_DEPTH];
-};
-
-}; // namespace android
-
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_CALLSTACK_H
diff --git a/include/utils/Compat.h b/include/utils/Compat.h
deleted file mode 100644
index fb7748e..0000000
--- a/include/utils/Compat.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef __LIB_UTILS_COMPAT_H
-#define __LIB_UTILS_COMPAT_H
-
-#include <unistd.h>
-
-/* Compatibility definitions for non-Linux (i.e., BSD-based) hosts. */
-#ifndef HAVE_OFF64_T
-#if _FILE_OFFSET_BITS < 64
-#error "_FILE_OFFSET_BITS < 64; large files are not supported on this platform"
-#endif /* _FILE_OFFSET_BITS < 64 */
-
-typedef off_t off64_t;
-
-static inline off64_t lseek64(int fd, off64_t offset, int whence) {
-    return lseek(fd, offset, whence);
-}
-
-#ifdef HAVE_PREAD
-static inline ssize_t pread64(int fd, void* buf, size_t nbytes, off64_t offset) {
-    return pread(fd, buf, nbytes, offset);
-}
-#endif
-
-#endif /* !HAVE_OFF64_T */
-
-#if HAVE_PRINTF_ZD
-#  define ZD "%zd"
-#  define ZD_TYPE ssize_t
-#else
-#  define ZD "%ld"
-#  define ZD_TYPE long
-#endif
-
-/*
- * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
- * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's
- * not already defined, then define it here.
- */
-#ifndef TEMP_FAILURE_RETRY
-/* Used to retry syscalls that can return EINTR. */
-#define TEMP_FAILURE_RETRY(exp) ({         \
-    typeof (exp) _rc;                      \
-    do {                                   \
-        _rc = (exp);                       \
-    } while (_rc == -1 && errno == EINTR); \
-    _rc; })
-#endif
-
-#endif /* __LIB_UTILS_COMPAT_H */
diff --git a/include/utils/Condition.h b/include/utils/Condition.h
deleted file mode 100644
index e63ba7e..0000000
--- a/include/utils/Condition.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2007 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 _LIBS_UTILS_CONDITION_H
-#define _LIBS_UTILS_CONDITION_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <time.h>
-
-#if defined(HAVE_PTHREADS)
-# include <pthread.h>
-#endif
-
-#include <utils/Errors.h>
-#include <utils/Mutex.h>
-#include <utils/Timers.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-/*
- * Condition variable class.  The implementation is system-dependent.
- *
- * Condition variables are paired up with mutexes.  Lock the mutex,
- * call wait(), then either re-wait() if things aren't quite what you want,
- * or unlock the mutex and continue.  All threads calling wait() must
- * use the same mutex for a given Condition.
- */
-class Condition {
-public:
-    enum {
-        PRIVATE = 0,
-        SHARED = 1
-    };
-
-    enum WakeUpType {
-        WAKE_UP_ONE = 0,
-        WAKE_UP_ALL = 1
-    };
-
-    Condition();
-    Condition(int type);
-    ~Condition();
-    // Wait on the condition variable.  Lock the mutex before calling.
-    status_t wait(Mutex& mutex);
-    // same with relative timeout
-    status_t waitRelative(Mutex& mutex, nsecs_t reltime);
-    // Signal the condition variable, allowing one thread to continue.
-    void signal();
-    // Signal the condition variable, allowing one or all threads to continue.
-    void signal(WakeUpType type) {
-        if (type == WAKE_UP_ONE) {
-            signal();
-        } else {
-            broadcast();
-        }
-    }
-    // Signal the condition variable, allowing all threads to continue.
-    void broadcast();
-
-private:
-#if defined(HAVE_PTHREADS)
-    pthread_cond_t mCond;
-#else
-    void*   mState;
-#endif
-};
-
-// ---------------------------------------------------------------------------
-
-#if defined(HAVE_PTHREADS)
-
-inline Condition::Condition() {
-    pthread_cond_init(&mCond, NULL);
-}
-inline Condition::Condition(int type) {
-    if (type == SHARED) {
-        pthread_condattr_t attr;
-        pthread_condattr_init(&attr);
-        pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
-        pthread_cond_init(&mCond, &attr);
-        pthread_condattr_destroy(&attr);
-    } else {
-        pthread_cond_init(&mCond, NULL);
-    }
-}
-inline Condition::~Condition() {
-    pthread_cond_destroy(&mCond);
-}
-inline status_t Condition::wait(Mutex& mutex) {
-    return -pthread_cond_wait(&mCond, &mutex.mMutex);
-}
-inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) {
-#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)
-    struct timespec ts;
-    ts.tv_sec  = reltime/1000000000;
-    ts.tv_nsec = reltime%1000000000;
-    return -pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts);
-#else // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
-    struct timespec ts;
-#if defined(HAVE_POSIX_CLOCKS)
-    clock_gettime(CLOCK_REALTIME, &ts);
-#else // HAVE_POSIX_CLOCKS
-    // we don't support the clocks here.
-    struct timeval t;
-    gettimeofday(&t, NULL);
-    ts.tv_sec = t.tv_sec;
-    ts.tv_nsec= t.tv_usec*1000;
-#endif // HAVE_POSIX_CLOCKS
-    ts.tv_sec += reltime/1000000000;
-    ts.tv_nsec+= reltime%1000000000;
-    if (ts.tv_nsec >= 1000000000) {
-        ts.tv_nsec -= 1000000000;
-        ts.tv_sec  += 1;
-    }
-    return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts);
-#endif // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
-}
-inline void Condition::signal() {
-    pthread_cond_signal(&mCond);
-}
-inline void Condition::broadcast() {
-    pthread_cond_broadcast(&mCond);
-}
-
-#endif // HAVE_PTHREADS
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // _LIBS_UTILS_CONDITON_H
diff --git a/include/utils/Endian.h b/include/utils/Endian.h
deleted file mode 100644
index 19f2504..0000000
--- a/include/utils/Endian.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Android endian-ness defines.
-//
-#ifndef _LIBS_UTILS_ENDIAN_H
-#define _LIBS_UTILS_ENDIAN_H
-
-#if defined(HAVE_ENDIAN_H)
-
-#include <endian.h>
-
-#else /*not HAVE_ENDIAN_H*/
-
-#define __BIG_ENDIAN 0x1000
-#define __LITTLE_ENDIAN 0x0001
-
-#if defined(HAVE_LITTLE_ENDIAN)
-# define __BYTE_ORDER __LITTLE_ENDIAN
-#else
-# define __BYTE_ORDER __BIG_ENDIAN
-#endif
-
-#endif /*not HAVE_ENDIAN_H*/
-
-#endif /*_LIBS_UTILS_ENDIAN_H*/
diff --git a/include/utils/Errors.h b/include/utils/Errors.h
deleted file mode 100644
index 0b75b19..0000000
--- a/include/utils/Errors.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2007 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_ERRORS_H
-#define ANDROID_ERRORS_H
-
-#include <sys/types.h>
-#include <errno.h>
-
-namespace android {
-
-// use this type to return error codes
-#ifdef HAVE_MS_C_RUNTIME
-typedef int         status_t;
-#else
-typedef int32_t     status_t;
-#endif
-
-/* the MS C runtime lacks a few error codes */
-
-/*
- * Error codes. 
- * All error codes are negative values.
- */
-
-// Win32 #defines NO_ERROR as well.  It has the same value, so there's no
-// real conflict, though it's a bit awkward.
-#ifdef _WIN32
-# undef NO_ERROR
-#endif
- 
-enum {
-    OK                = 0,    // Everything's swell.
-    NO_ERROR          = 0,    // No errors.
-    
-    UNKNOWN_ERROR       = 0x80000000,
-
-    NO_MEMORY           = -ENOMEM,
-    INVALID_OPERATION   = -ENOSYS,
-    BAD_VALUE           = -EINVAL,
-    BAD_TYPE            = 0x80000001,
-    NAME_NOT_FOUND      = -ENOENT,
-    PERMISSION_DENIED   = -EPERM,
-    NO_INIT             = -ENODEV,
-    ALREADY_EXISTS      = -EEXIST,
-    DEAD_OBJECT         = -EPIPE,
-    FAILED_TRANSACTION  = 0x80000002,
-    JPARKS_BROKE_IT     = -EPIPE,
-#if !defined(HAVE_MS_C_RUNTIME)
-    BAD_INDEX           = -EOVERFLOW,
-    NOT_ENOUGH_DATA     = -ENODATA,
-    WOULD_BLOCK         = -EWOULDBLOCK, 
-    TIMED_OUT           = -ETIMEDOUT,
-    UNKNOWN_TRANSACTION = -EBADMSG,
-#else    
-    BAD_INDEX           = -E2BIG,
-    NOT_ENOUGH_DATA     = 0x80000003,
-    WOULD_BLOCK         = 0x80000004,
-    TIMED_OUT           = 0x80000005,
-    UNKNOWN_TRANSACTION = 0x80000006,
-#endif    
-    FDS_NOT_ALLOWED     = 0x80000007,
-};
-
-// Restore define; enumeration is in "android" namespace, so the value defined
-// there won't work for Win32 code in a different namespace.
-#ifdef _WIN32
-# define NO_ERROR 0L
-#endif
-
-}; // namespace android
-    
-// ---------------------------------------------------------------------------
-    
-#endif // ANDROID_ERRORS_H
diff --git a/include/utils/FileMap.h b/include/utils/FileMap.h
deleted file mode 100644
index dfe6d51..0000000
--- a/include/utils/FileMap.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2006 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.
- */
-
-//
-// Encapsulate a shared file mapping.
-//
-#ifndef __LIBS_FILE_MAP_H
-#define __LIBS_FILE_MAP_H
-
-#include <sys/types.h>
-
-#include <utils/Compat.h>
-
-#ifdef HAVE_WIN32_FILEMAP
-#include <windows.h>
-#endif
-
-namespace android {
-
-/*
- * This represents a memory-mapped file.  It might be the entire file or
- * only part of it.  This requires a little bookkeeping because the mapping
- * needs to be aligned on page boundaries, and in some cases we'd like to
- * have multiple references to the mapped area without creating additional
- * maps.
- *
- * This always uses MAP_SHARED.
- *
- * TODO: we should be able to create a new FileMap that is a subset of
- * an existing FileMap and shares the underlying mapped pages.  Requires
- * completing the refcounting stuff and possibly introducing the notion
- * of a FileMap hierarchy.
- */
-class FileMap {
-public:
-    FileMap(void);
-
-    /*
-     * Create a new mapping on an open file.
-     *
-     * Closing the file descriptor does not unmap the pages, so we don't
-     * claim ownership of the fd.
-     *
-     * Returns "false" on failure.
-     */
-    bool create(const char* origFileName, int fd,
-                off64_t offset, size_t length, bool readOnly);
-
-    /*
-     * Return the name of the file this map came from, if known.
-     */
-    const char* getFileName(void) const { return mFileName; }
-    
-    /*
-     * Get a pointer to the piece of the file we requested.
-     */
-    void* getDataPtr(void) const { return mDataPtr; }
-
-    /*
-     * Get the length we requested.
-     */
-    size_t getDataLength(void) const { return mDataLength; }
-
-    /*
-     * Get the data offset used to create this map.
-     */
-    off64_t getDataOffset(void) const { return mDataOffset; }
-
-    /*
-     * Get a "copy" of the object.
-     */
-    FileMap* acquire(void) { mRefCount++; return this; }
-
-    /*
-     * Call this when mapping is no longer needed.
-     */
-    void release(void) {
-        if (--mRefCount <= 0)
-            delete this;
-    }
-
-    /*
-     * This maps directly to madvise() values, but allows us to avoid
-     * including <sys/mman.h> everywhere.
-     */
-    enum MapAdvice {
-        NORMAL, RANDOM, SEQUENTIAL, WILLNEED, DONTNEED
-    };
-
-    /*
-     * Apply an madvise() call to the entire file.
-     *
-     * Returns 0 on success, -1 on failure.
-     */
-    int advise(MapAdvice advice);
-
-protected:
-    // don't delete objects; call release()
-    ~FileMap(void);
-
-private:
-    // these are not implemented
-    FileMap(const FileMap& src);
-    const FileMap& operator=(const FileMap& src);
-
-    int         mRefCount;      // reference count
-    char*       mFileName;      // original file name, if known
-    void*       mBasePtr;       // base of mmap area; page aligned
-    size_t      mBaseLength;    // length, measured from "mBasePtr"
-    off64_t     mDataOffset;    // offset used when map was created
-    void*       mDataPtr;       // start of requested data, offset from base
-    size_t      mDataLength;    // length, measured from "mDataPtr"
-#ifdef HAVE_WIN32_FILEMAP
-    HANDLE      mFileHandle;    // Win32 file handle
-    HANDLE      mFileMapping;   // Win32 file mapping handle
-#endif
-
-    static long mPageSize;
-};
-
-}; // namespace android
-
-#endif // __LIBS_FILE_MAP_H
diff --git a/include/utils/Flattenable.h b/include/utils/Flattenable.h
deleted file mode 100644
index e40d289..0000000
--- a/include/utils/Flattenable.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef ANDROID_UTILS_FLATTENABLE_H
-#define ANDROID_UTILS_FLATTENABLE_H
-
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <utils/Errors.h>
-
-namespace android {
-
-/*
- * The Flattenable interface allows an object to serialize itself out
- * to a byte-buffer and an array of file descriptors.
- */
-
-class Flattenable
-{
-public:
-    // size in bytes of the flattened object
-    virtual size_t getFlattenedSize() const = 0;
-
-    // number of file descriptors to flatten
-    virtual size_t getFdCount() const = 0;
-
-    // flattens the object into buffer.
-    // size should be at least of getFlattenedSize()
-    // file descriptors are written in the fds[] array but ownership is
-    // not transfered (ie: they must be dupped by the caller of
-    // flatten() if needed).
-    virtual status_t flatten(void* buffer, size_t size,
-            int fds[], size_t count) const = 0;
-
-    // unflattens the object from buffer.
-    // size should be equal to the value of getFlattenedSize() when the
-    // object was flattened.
-    // unflattened file descriptors are found in the fds[] array and
-    // don't need to be dupped(). ie: the caller of unflatten doesn't
-    // keep ownership. If a fd is not retained by unflatten() it must be
-    // explicitly closed.
-    virtual status_t unflatten(void const* buffer, size_t size,
-            int fds[], size_t count) = 0;
-
-protected:
-    virtual ~Flattenable() = 0;
-
-};
-
-/*
- * LightFlattenable is a protocol allowing object to serialize themselves out
- * to a byte-buffer.
- *
- * LightFlattenable objects must implement this protocol.
- *
- * LightFlattenable doesn't require the object to be virtual.
- */
-template <typename T>
-class LightFlattenable {
-public:
-    // returns whether this object always flatten into the same size.
-    // for efficiency, this should always be inline.
-    inline bool isFixedSize() const;
-
-    // returns size in bytes of the flattened object. must be a constant.
-    inline size_t getSize() const;
-
-    // flattens the object into buffer.
-    inline status_t flatten(void* buffer) const;
-
-    // unflattens the object from buffer of given size.
-    inline status_t unflatten(void const* buffer, size_t size);
-};
-
-template <typename T>
-inline bool LightFlattenable<T>::isFixedSize() const {
-    return static_cast<T const*>(this)->T::isFixedSize();
-}
-template <typename T>
-inline size_t LightFlattenable<T>::getSize() const {
-    return static_cast<T const*>(this)->T::getSize();
-}
-template <typename T>
-inline status_t LightFlattenable<T>::flatten(void* buffer) const {
-    return static_cast<T const*>(this)->T::flatten(buffer);
-}
-template <typename T>
-inline status_t LightFlattenable<T>::unflatten(void const* buffer, size_t size) {
-    return static_cast<T*>(this)->T::unflatten(buffer, size);
-}
-
-/*
- * LightFlattenablePod is an implementation of the LightFlattenable protocol
- * for POD (plain-old-data) objects.
- */
-template <typename T>
-class LightFlattenablePod : public LightFlattenable<T> {
-public:
-    inline bool isFixedSize() const {
-        return true;
-    }
-
-    inline size_t getSize() const {
-        return sizeof(T);
-    }
-    inline status_t flatten(void* buffer) const {
-        *reinterpret_cast<T*>(buffer) = *static_cast<T const*>(this);
-        return NO_ERROR;
-    }
-    inline status_t unflatten(void const* buffer, size_t) {
-        *static_cast<T*>(this) = *reinterpret_cast<T const*>(buffer);
-        return NO_ERROR;
-    }
-};
-
-
-}; // namespace android
-
-
-#endif /* ANDROID_UTILS_FLATTENABLE_H */
diff --git a/include/utils/Functor.h b/include/utils/Functor.h
deleted file mode 100644
index e24ded4..0000000
--- a/include/utils/Functor.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2011 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_FUNCTOR_H
-#define ANDROID_FUNCTOR_H
-
-#include <utils/Errors.h>
-
-namespace  android {
-
-class Functor {
-public:
-    Functor() {}
-    virtual ~Functor() {}
-    virtual status_t operator ()(int what, void* data) { return NO_ERROR; }
-};
-
-}; // namespace android
-
-#endif // ANDROID_FUNCTOR_H
diff --git a/include/utils/GenerationCache.h b/include/utils/GenerationCache.h
deleted file mode 100644
index 40722d1..0000000
--- a/include/utils/GenerationCache.h
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef ANDROID_UTILS_GENERATION_CACHE_H
-#define ANDROID_UTILS_GENERATION_CACHE_H
-
-#include <utils/KeyedVector.h>
-#include <utils/RefBase.h>
-
-namespace android {
-
-/**
- * GenerationCache callback used when an item is removed
- */
-template<typename EntryKey, typename EntryValue>
-class OnEntryRemoved {
-public:
-    virtual ~OnEntryRemoved() { };
-    virtual void operator()(EntryKey& key, EntryValue& value) = 0;
-}; // class OnEntryRemoved
-
-template<typename EntryKey, typename EntryValue>
-struct Entry: public LightRefBase<Entry<EntryKey, EntryValue> > {
-    Entry(const Entry<EntryKey, EntryValue>& e) :
-            key(e.key), value(e.value),
-            parent(e.parent), child(e.child) { }
-    Entry(const EntryKey& key, const EntryValue& value) :
-            key(key), value(value) { }
-
-    EntryKey key;
-    EntryValue value;
-
-    sp<Entry<EntryKey, EntryValue> > parent; // next older entry
-    sp<Entry<EntryKey, EntryValue> > child;  // next younger entry
-}; // struct Entry
-
-/**
- * A LRU type cache
- */
-template<typename K, typename V>
-class GenerationCache {
-public:
-    GenerationCache(uint32_t maxCapacity);
-    virtual ~GenerationCache();
-
-    enum Capacity {
-        kUnlimitedCapacity,
-    };
-
-    void setOnEntryRemovedListener(OnEntryRemoved<K, V>* listener);
-
-    size_t size() const;
-
-    void clear();
-
-    bool contains(const K& key) const;
-    const K& getKeyAt(size_t index) const;
-    const V& getValueAt(size_t index) const;
-
-    const V& get(const K& key);
-    bool put(const K& key, const V& value);
-
-    void removeAt(ssize_t index);
-    bool remove(const K& key);
-    bool removeOldest();
-
-private:
-    KeyedVector<K, sp<Entry<K, V> > > mCache;
-    uint32_t mMaxCapacity;
-
-    OnEntryRemoved<K, V>* mListener;
-
-    sp<Entry<K, V> > mOldest;
-    sp<Entry<K, V> > mYoungest;
-
-    void attachToCache(const sp<Entry<K, V> >& entry);
-    void detachFromCache(const sp<Entry<K, V> >& entry);
-
-    const V mNullValue;
-}; // class GenerationCache
-
-template<typename K, typename V>
-GenerationCache<K, V>::GenerationCache(uint32_t maxCapacity): mMaxCapacity(maxCapacity),
-    mListener(NULL), mNullValue(NULL) {
-};
-
-template<typename K, typename V>
-GenerationCache<K, V>::~GenerationCache() {
-    clear();
-};
-
-template<typename K, typename V>
-uint32_t GenerationCache<K, V>::size() const {
-    return mCache.size();
-}
-
-/**
- * Should be set by the user of the Cache so that the callback is called whenever an item is
- * removed from the cache
- */
-template<typename K, typename V>
-void GenerationCache<K, V>::setOnEntryRemovedListener(OnEntryRemoved<K, V>* listener) {
-    mListener = listener;
-}
-
-template<typename K, typename V>
-void GenerationCache<K, V>::clear() {
-    if (mListener) {
-        for (uint32_t i = 0; i < mCache.size(); i++) {
-            sp<Entry<K, V> > entry = mCache.valueAt(i);
-            if (mListener) {
-                (*mListener)(entry->key, entry->value);
-            }
-        }
-    }
-    mCache.clear();
-    mYoungest.clear();
-    mOldest.clear();
-}
-
-template<typename K, typename V>
-bool GenerationCache<K, V>::contains(const K& key) const {
-    return mCache.indexOfKey(key) >= 0;
-}
-
-template<typename K, typename V>
-const K& GenerationCache<K, V>::getKeyAt(size_t index) const {
-    return mCache.keyAt(index);
-}
-
-template<typename K, typename V>
-const V& GenerationCache<K, V>::getValueAt(size_t index) const {
-    return mCache.valueAt(index)->value;
-}
-
-template<typename K, typename V>
-const V& GenerationCache<K, V>::get(const K& key) {
-    ssize_t index = mCache.indexOfKey(key);
-    if (index >= 0) {
-        const sp<Entry<K, V> >& entry = mCache.valueAt(index);
-        detachFromCache(entry);
-        attachToCache(entry);
-        return entry->value;
-    }
-
-    return mNullValue;
-}
-
-template<typename K, typename V>
-bool GenerationCache<K, V>::put(const K& key, const V& value) {
-    if (mMaxCapacity != kUnlimitedCapacity && mCache.size() >= mMaxCapacity) {
-        removeOldest();
-    }
-
-    ssize_t index = mCache.indexOfKey(key);
-    if (index < 0) {
-        sp<Entry<K, V> > entry = new Entry<K, V>(key, value);
-        mCache.add(key, entry);
-        attachToCache(entry);
-        return true;
-    }
-
-    return false;
-}
-
-template<typename K, typename V>
-bool GenerationCache<K, V>::remove(const K& key) {
-    ssize_t index = mCache.indexOfKey(key);
-    if (index >= 0) {
-        removeAt(index);
-        return true;
-    }
-
-    return false;
-}
-
-template<typename K, typename V>
-void GenerationCache<K, V>::removeAt(ssize_t index) {
-    sp<Entry<K, V> > entry = mCache.valueAt(index);
-    if (mListener) {
-        (*mListener)(entry->key, entry->value);
-    }
-    mCache.removeItemsAt(index, 1);
-    detachFromCache(entry);
-}
-
-template<typename K, typename V>
-bool GenerationCache<K, V>::removeOldest() {
-    if (mOldest.get()) {
-        ssize_t index = mCache.indexOfKey(mOldest->key);
-        if (index >= 0) {
-            removeAt(index);
-            return true;
-        }
-        ALOGE("GenerationCache: removeOldest failed to find the item in the cache "
-                "with the given key, but we know it must be in there.  "
-                "Is the key comparator kaput?");
-    }
-
-    return false;
-}
-
-template<typename K, typename V>
-void GenerationCache<K, V>::attachToCache(const sp<Entry<K, V> >& entry) {
-    if (!mYoungest.get()) {
-        mYoungest = mOldest = entry;
-    } else {
-        entry->parent = mYoungest;
-        mYoungest->child = entry;
-        mYoungest = entry;
-    }
-}
-
-template<typename K, typename V>
-void GenerationCache<K, V>::detachFromCache(const sp<Entry<K, V> >& entry) {
-    if (entry->parent.get()) {
-        entry->parent->child = entry->child;
-    } else {
-        mOldest = entry->child;
-    }
-
-    if (entry->child.get()) {
-        entry->child->parent = entry->parent;
-    } else {
-        mYoungest = entry->parent;
-    }
-
-    entry->parent.clear();
-    entry->child.clear();
-}
-
-}; // namespace android
-
-#endif // ANDROID_UTILS_GENERATION_CACHE_H
diff --git a/include/utils/JenkinsHash.h b/include/utils/JenkinsHash.h
deleted file mode 100644
index 7da5dbd..0000000
--- a/include/utils/JenkinsHash.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2012 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.
- */
-
-/* Implementation of Jenkins one-at-a-time hash function. These choices are
- * optimized for code size and portability, rather than raw speed. But speed
- * should still be quite good.
- **/
-
-#ifndef ANDROID_JENKINS_HASH_H
-#define ANDROID_JENKINS_HASH_H
-
-#include <utils/TypeHelpers.h>
-
-namespace android {
-
-/* The Jenkins hash of a sequence of 32 bit words A, B, C is:
- * Whiten(Mix(Mix(Mix(0, A), B), C)) */
-
-inline uint32_t JenkinsHashMix(uint32_t hash, uint32_t data) {
-    hash += data;
-    hash += (hash << 10);
-    hash ^= (hash >> 6);
-    return hash;
-}
-
-hash_t JenkinsHashWhiten(uint32_t hash);
-
-/* Helpful utility functions for hashing data in 32 bit chunks */
-uint32_t JenkinsHashMixBytes(uint32_t hash, const uint8_t* bytes, size_t size);
-
-uint32_t JenkinsHashMixShorts(uint32_t hash, const uint16_t* shorts, size_t size);
-
-}
-
-#endif // ANDROID_JENKINS_HASH_H
diff --git a/include/utils/KeyedVector.h b/include/utils/KeyedVector.h
deleted file mode 100644
index c4faae0..0000000
--- a/include/utils/KeyedVector.h
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2005 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_KEYED_VECTOR_H
-#define ANDROID_KEYED_VECTOR_H
-
-#include <assert.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <cutils/log.h>
-
-#include <utils/SortedVector.h>
-#include <utils/TypeHelpers.h>
-#include <utils/Errors.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-template <typename KEY, typename VALUE>
-class KeyedVector
-{
-public:
-    typedef KEY    key_type;
-    typedef VALUE  value_type;
-
-    inline                  KeyedVector();
-
-    /*
-     * empty the vector
-     */
-
-    inline  void            clear()                     { mVector.clear(); }
-
-    /*! 
-     * vector stats
-     */
-
-    //! returns number of items in the vector
-    inline  size_t          size() const                { return mVector.size(); }
-    //! returns whether or not the vector is empty
-    inline  bool            isEmpty() const             { return mVector.isEmpty(); }
-    //! returns how many items can be stored without reallocating the backing store
-    inline  size_t          capacity() const            { return mVector.capacity(); }
-    //! sets the capacity. capacity can never be reduced less than size()
-    inline ssize_t          setCapacity(size_t size)    { return mVector.setCapacity(size); }
-
-    // returns true if the arguments is known to be identical to this vector
-    inline bool isIdenticalTo(const KeyedVector& rhs) const;
-
-    /*! 
-     * accessors
-     */
-            const VALUE&    valueFor(const KEY& key) const;
-            const VALUE&    valueAt(size_t index) const;
-            const KEY&      keyAt(size_t index) const;
-            ssize_t         indexOfKey(const KEY& key) const;
-            const VALUE&    operator[] (size_t index) const;
-
-    /*!
-     * modifying the array
-     */
-
-            VALUE&          editValueFor(const KEY& key);
-            VALUE&          editValueAt(size_t index);
-
-            /*! 
-             * add/insert/replace items
-             */
-             
-            ssize_t         add(const KEY& key, const VALUE& item);
-            ssize_t         replaceValueFor(const KEY& key, const VALUE& item);
-            ssize_t         replaceValueAt(size_t index, const VALUE& item);
-
-    /*!
-     * remove items
-     */
-
-            ssize_t         removeItem(const KEY& key);
-            ssize_t         removeItemsAt(size_t index, size_t count = 1);
-            
-private:
-            SortedVector< key_value_pair_t<KEY, VALUE> >    mVector;
-};
-
-// KeyedVector<KEY, VALUE> can be trivially moved using memcpy() because its
-// underlying SortedVector can be trivially moved.
-template<typename KEY, typename VALUE> struct trait_trivial_move<KeyedVector<KEY, VALUE> > {
-    enum { value = trait_trivial_move<SortedVector< key_value_pair_t<KEY, VALUE> > >::value };
-};
-
-
-// ---------------------------------------------------------------------------
-
-/**
- * Variation of KeyedVector that holds a default value to return when
- * valueFor() is called with a key that doesn't exist.
- */
-template <typename KEY, typename VALUE>
-class DefaultKeyedVector : public KeyedVector<KEY, VALUE>
-{
-public:
-    inline                  DefaultKeyedVector(const VALUE& defValue = VALUE());
-            const VALUE&    valueFor(const KEY& key) const;
-
-private:
-            VALUE                                           mDefault;
-};
-
-// ---------------------------------------------------------------------------
-
-template<typename KEY, typename VALUE> inline
-KeyedVector<KEY,VALUE>::KeyedVector()
-{
-}
-
-template<typename KEY, typename VALUE> inline
-bool KeyedVector<KEY,VALUE>::isIdenticalTo(const KeyedVector<KEY,VALUE>& rhs) const {
-    return mVector.array() == rhs.mVector.array();
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::indexOfKey(const KEY& key) const {
-    return mVector.indexOf( key_value_pair_t<KEY,VALUE>(key) );
-}
-
-template<typename KEY, typename VALUE> inline
-const VALUE& KeyedVector<KEY,VALUE>::valueFor(const KEY& key) const {
-    ssize_t i = this->indexOfKey(key);
-    LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__);
-    return mVector.itemAt(i).value;
-}
-
-template<typename KEY, typename VALUE> inline
-const VALUE& KeyedVector<KEY,VALUE>::valueAt(size_t index) const {
-    return mVector.itemAt(index).value;
-}
-
-template<typename KEY, typename VALUE> inline
-const VALUE& KeyedVector<KEY,VALUE>::operator[] (size_t index) const {
-    return valueAt(index);
-}
-
-template<typename KEY, typename VALUE> inline
-const KEY& KeyedVector<KEY,VALUE>::keyAt(size_t index) const {
-    return mVector.itemAt(index).key;
-}
-
-template<typename KEY, typename VALUE> inline
-VALUE& KeyedVector<KEY,VALUE>::editValueFor(const KEY& key) {
-    ssize_t i = this->indexOfKey(key);
-    LOG_ALWAYS_FATAL_IF(i<0, "%s: key not found", __PRETTY_FUNCTION__);
-    return mVector.editItemAt(i).value;
-}
-
-template<typename KEY, typename VALUE> inline
-VALUE& KeyedVector<KEY,VALUE>::editValueAt(size_t index) {
-    return mVector.editItemAt(index).value;
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::add(const KEY& key, const VALUE& value) {
-    return mVector.add( key_value_pair_t<KEY,VALUE>(key, value) );
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::replaceValueFor(const KEY& key, const VALUE& value) {
-    key_value_pair_t<KEY,VALUE> pair(key, value);
-    mVector.remove(pair);
-    return mVector.add(pair);
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::replaceValueAt(size_t index, const VALUE& item) {
-    if (index<size()) {
-        mVector.editItemAt(index).value = item;
-        return index;
-    }
-    return BAD_INDEX;
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY,VALUE>::removeItem(const KEY& key) {
-    return mVector.remove(key_value_pair_t<KEY,VALUE>(key));
-}
-
-template<typename KEY, typename VALUE> inline
-ssize_t KeyedVector<KEY, VALUE>::removeItemsAt(size_t index, size_t count) {
-    return mVector.removeItemsAt(index, count);
-}
-
-// ---------------------------------------------------------------------------
-
-template<typename KEY, typename VALUE> inline
-DefaultKeyedVector<KEY,VALUE>::DefaultKeyedVector(const VALUE& defValue)
-    : mDefault(defValue)
-{
-}
-
-template<typename KEY, typename VALUE> inline
-const VALUE& DefaultKeyedVector<KEY,VALUE>::valueFor(const KEY& key) const {
-    ssize_t i = this->indexOfKey(key);
-    return i >= 0 ? KeyedVector<KEY,VALUE>::valueAt(i) : mDefault;
-}
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_KEYED_VECTOR_H
diff --git a/include/utils/LinearAllocator.h b/include/utils/LinearAllocator.h
deleted file mode 100644
index 4772bc8..0000000
--- a/include/utils/LinearAllocator.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright 2012, The Android Open Source Project
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ANDROID_LINEARALLOCATOR_H
-#define ANDROID_LINEARALLOCATOR_H
-
-#include <stddef.h>
-
-namespace android {
-
-/**
- * A memory manager that internally allocates multi-kbyte buffers for placing objects in. It avoids
- * the overhead of malloc when many objects are allocated. It is most useful when creating many
- * small objects with a similar lifetime, and doesn't add significant overhead for large
- * allocations.
- */
-class LinearAllocator {
-public:
-    LinearAllocator();
-    ~LinearAllocator();
-
-    /**
-     * Reserves and returns a region of memory of at least size 'size', aligning as needed.
-     * Typically this is used in an object's overridden new() method or as a replacement for malloc.
-     *
-     * The lifetime of the returned buffers is tied to that of the LinearAllocator. If calling
-     * delete() on an object stored in a buffer is needed, it should be overridden to use
-     * rewindIfLastAlloc()
-     */
-    void* alloc(size_t size);
-
-    /**
-     * Attempt to deallocate the given buffer, with the LinearAllocator attempting to rewind its
-     * state if possible. No destructors are called.
-     */
-    void rewindIfLastAlloc(void* ptr, size_t allocSize);
-
-    /**
-     * Dump memory usage statistics to the log (allocated and wasted space)
-     */
-    void dumpMemoryStats(const char* prefix = "");
-
-    /**
-     * The number of bytes used for buffers allocated in the LinearAllocator (does not count space
-     * wasted)
-     */
-    size_t usedSize() const { return mTotalAllocated - mWastedSpace; }
-
-private:
-    LinearAllocator(const LinearAllocator& other);
-
-    class Page;
-
-    Page* newPage(size_t pageSize);
-    bool fitsInCurrentPage(size_t size);
-    void ensureNext(size_t size);
-    void* start(Page *p);
-    void* end(Page* p);
-
-    size_t mPageSize;
-    size_t mMaxAllocSize;
-    void* mNext;
-    Page* mCurrentPage;
-    Page* mPages;
-
-    // Memory usage tracking
-    size_t mTotalAllocated;
-    size_t mWastedSpace;
-    size_t mPageCount;
-    size_t mDedicatedPageCount;
-};
-
-}; // namespace android
-
-#endif // ANDROID_LINEARALLOCATOR_H
diff --git a/include/utils/LinearTransform.h b/include/utils/LinearTransform.h
deleted file mode 100644
index 04cb355..0000000
--- a/include/utils/LinearTransform.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2011 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 _LIBS_UTILS_LINEAR_TRANSFORM_H
-#define _LIBS_UTILS_LINEAR_TRANSFORM_H
-
-#include <stdint.h>
-
-namespace android {
-
-// LinearTransform defines a structure which hold the definition of a
-// transformation from single dimensional coordinate system A into coordinate
-// system B (and back again).  Values in A and in B are 64 bit, the linear
-// scale factor is expressed as a rational number using two 32 bit values.
-//
-// Specifically, let
-// f(a) = b
-// F(b) = f^-1(b) = a
-// then
-//
-// f(a) = (((a - a_zero) * a_to_b_numer) / a_to_b_denom) + b_zero;
-//
-// and
-//
-// F(b) = (((b - b_zero) * a_to_b_denom) / a_to_b_numer) + a_zero;
-//
-struct LinearTransform {
-  int64_t  a_zero;
-  int64_t  b_zero;
-  int32_t  a_to_b_numer;
-  uint32_t a_to_b_denom;
-
-  // Transform from A->B
-  // Returns true on success, or false in the case of a singularity or an
-  // overflow.
-  bool doForwardTransform(int64_t a_in, int64_t* b_out) const;
-
-  // Transform from B->A
-  // Returns true on success, or false in the case of a singularity or an
-  // overflow.
-  bool doReverseTransform(int64_t b_in, int64_t* a_out) const;
-
-  // Helpers which will reduce the fraction N/D using Euclid's method.
-  template <class T> static void reduce(T* N, T* D);
-  static void reduce(int32_t* N, uint32_t* D);
-};
-
-
-}
-
-#endif  // _LIBS_UTILS_LINEAR_TRANSFORM_H
diff --git a/include/utils/List.h b/include/utils/List.h
deleted file mode 100644
index 403cd7f..0000000
--- a/include/utils/List.h
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Templated list class.  Normally we'd use STL, but we don't have that.
-// This class mimics STL's interfaces.
-//
-// Objects are copied into the list with the '=' operator or with copy-
-// construction, so if the compiler's auto-generated versions won't work for
-// you, define your own.
-//
-// The only class you want to use from here is "List".
-//
-#ifndef _LIBS_UTILS_LIST_H
-#define _LIBS_UTILS_LIST_H
-
-#include <stddef.h>
-#include <stdint.h>
-
-namespace android {
-
-/*
- * Doubly-linked list.  Instantiate with "List<MyClass> myList".
- *
- * Objects added to the list are copied using the assignment operator,
- * so this must be defined.
- */
-template<typename T> 
-class List 
-{
-protected:
-    /*
-     * One element in the list.
-     */
-    class _Node {
-    public:
-        explicit _Node(const T& val) : mVal(val) {}
-        ~_Node() {}
-        inline T& getRef() { return mVal; }
-        inline const T& getRef() const { return mVal; }
-        inline _Node* getPrev() const { return mpPrev; }
-        inline _Node* getNext() const { return mpNext; }
-        inline void setVal(const T& val) { mVal = val; }
-        inline void setPrev(_Node* ptr) { mpPrev = ptr; }
-        inline void setNext(_Node* ptr) { mpNext = ptr; }
-    private:
-        friend class List;
-        friend class _ListIterator;
-        T           mVal;
-        _Node*      mpPrev;
-        _Node*      mpNext;
-    };
-
-    /*
-     * Iterator for walking through the list.
-     */
-    
-    template <typename TYPE>
-    struct CONST_ITERATOR {
-        typedef _Node const * NodePtr;
-        typedef const TYPE Type;
-    };
-    
-    template <typename TYPE>
-    struct NON_CONST_ITERATOR {
-        typedef _Node* NodePtr;
-        typedef TYPE Type;
-    };
-    
-    template<
-        typename U,
-        template <class> class Constness
-    > 
-    class _ListIterator {
-        typedef _ListIterator<U, Constness>     _Iter;
-        typedef typename Constness<U>::NodePtr  _NodePtr;
-        typedef typename Constness<U>::Type     _Type;
-
-        explicit _ListIterator(_NodePtr ptr) : mpNode(ptr) {}
-
-    public:
-        _ListIterator() {}
-        _ListIterator(const _Iter& rhs) : mpNode(rhs.mpNode) {}
-        ~_ListIterator() {}
-        
-        // this will handle conversions from iterator to const_iterator
-        // (and also all convertible iterators)
-        // Here, in this implementation, the iterators can be converted
-        // if the nodes can be converted
-        template<typename V> explicit 
-        _ListIterator(const V& rhs) : mpNode(rhs.mpNode) {}
-        
-
-        /*
-         * Dereference operator.  Used to get at the juicy insides.
-         */
-        _Type& operator*() const { return mpNode->getRef(); }
-        _Type* operator->() const { return &(mpNode->getRef()); }
-
-        /*
-         * Iterator comparison.
-         */
-        inline bool operator==(const _Iter& right) const { 
-            return mpNode == right.mpNode; }
-        
-        inline bool operator!=(const _Iter& right) const { 
-            return mpNode != right.mpNode; }
-
-        /*
-         * handle comparisons between iterator and const_iterator
-         */
-        template<typename OTHER>
-        inline bool operator==(const OTHER& right) const { 
-            return mpNode == right.mpNode; }
-        
-        template<typename OTHER>
-        inline bool operator!=(const OTHER& right) const { 
-            return mpNode != right.mpNode; }
-
-        /*
-         * Incr/decr, used to move through the list.
-         */
-        inline _Iter& operator++() {     // pre-increment
-            mpNode = mpNode->getNext();
-            return *this;
-        }
-        const _Iter operator++(int) {    // post-increment
-            _Iter tmp(*this);
-            mpNode = mpNode->getNext();
-            return tmp;
-        }
-        inline _Iter& operator--() {     // pre-increment
-            mpNode = mpNode->getPrev();
-            return *this;
-        }
-        const _Iter operator--(int) {   // post-increment
-            _Iter tmp(*this);
-            mpNode = mpNode->getPrev();
-            return tmp;
-        }
-
-        inline _NodePtr getNode() const { return mpNode; }
-
-        _NodePtr mpNode;    /* should be private, but older gcc fails */
-    private:
-        friend class List;
-    };
-
-public:
-    List() {
-        prep();
-    }
-    List(const List<T>& src) {      // copy-constructor
-        prep();
-        insert(begin(), src.begin(), src.end());
-    }
-    virtual ~List() {
-        clear();
-        delete[] (unsigned char*) mpMiddle;
-    }
-
-    typedef _ListIterator<T, NON_CONST_ITERATOR> iterator;
-    typedef _ListIterator<T, CONST_ITERATOR> const_iterator;
-
-    List<T>& operator=(const List<T>& right);
-
-    /* returns true if the list is empty */
-    inline bool empty() const { return mpMiddle->getNext() == mpMiddle; }
-
-    /* return #of elements in list */
-    size_t size() const {
-        return size_t(distance(begin(), end()));
-    }
-
-    /*
-     * Return the first element or one past the last element.  The
-     * _Node* we're returning is converted to an "iterator" by a
-     * constructor in _ListIterator.
-     */
-    inline iterator begin() { 
-        return iterator(mpMiddle->getNext()); 
-    }
-    inline const_iterator begin() const { 
-        return const_iterator(const_cast<_Node const*>(mpMiddle->getNext())); 
-    }
-    inline iterator end() { 
-        return iterator(mpMiddle); 
-    }
-    inline const_iterator end() const { 
-        return const_iterator(const_cast<_Node const*>(mpMiddle)); 
-    }
-
-    /* add the object to the head or tail of the list */
-    void push_front(const T& val) { insert(begin(), val); }
-    void push_back(const T& val) { insert(end(), val); }
-
-    /* insert before the current node; returns iterator at new node */
-    iterator insert(iterator posn, const T& val) 
-    {
-        _Node* newNode = new _Node(val);        // alloc & copy-construct
-        newNode->setNext(posn.getNode());
-        newNode->setPrev(posn.getNode()->getPrev());
-        posn.getNode()->getPrev()->setNext(newNode);
-        posn.getNode()->setPrev(newNode);
-        return iterator(newNode);
-    }
-
-    /* insert a range of elements before the current node */
-    void insert(iterator posn, const_iterator first, const_iterator last) {
-        for ( ; first != last; ++first)
-            insert(posn, *first);
-    }
-
-    /* remove one entry; returns iterator at next node */
-    iterator erase(iterator posn) {
-        _Node* pNext = posn.getNode()->getNext();
-        _Node* pPrev = posn.getNode()->getPrev();
-        pPrev->setNext(pNext);
-        pNext->setPrev(pPrev);
-        delete posn.getNode();
-        return iterator(pNext);
-    }
-
-    /* remove a range of elements */
-    iterator erase(iterator first, iterator last) {
-        while (first != last)
-            erase(first++);     // don't erase than incr later!
-        return iterator(last);
-    }
-
-    /* remove all contents of the list */
-    void clear() {
-        _Node* pCurrent = mpMiddle->getNext();
-        _Node* pNext;
-
-        while (pCurrent != mpMiddle) {
-            pNext = pCurrent->getNext();
-            delete pCurrent;
-            pCurrent = pNext;
-        }
-        mpMiddle->setPrev(mpMiddle);
-        mpMiddle->setNext(mpMiddle);
-    }
-
-    /*
-     * Measure the distance between two iterators.  On exist, "first"
-     * will be equal to "last".  The iterators must refer to the same
-     * list.
-     *
-     * FIXME: This is actually a generic iterator function. It should be a 
-     * template function at the top-level with specializations for things like
-     * vector<>, which can just do pointer math). Here we limit it to
-     * _ListIterator of the same type but different constness.
-     */
-    template<
-        typename U,
-        template <class> class CL,
-        template <class> class CR
-    > 
-    ptrdiff_t distance(
-            _ListIterator<U, CL> first, _ListIterator<U, CR> last) const 
-    {
-        ptrdiff_t count = 0;
-        while (first != last) {
-            ++first;
-            ++count;
-        }
-        return count;
-    }
-
-private:
-    /*
-     * I want a _Node but don't need it to hold valid data.  More
-     * to the point, I don't want T's constructor to fire, since it
-     * might have side-effects or require arguments.  So, we do this
-     * slightly uncouth storage alloc.
-     */
-    void prep() {
-        mpMiddle = (_Node*) new unsigned char[sizeof(_Node)];
-        mpMiddle->setPrev(mpMiddle);
-        mpMiddle->setNext(mpMiddle);
-    }
-
-    /*
-     * This node plays the role of "pointer to head" and "pointer to tail".
-     * It sits in the middle of a circular list of nodes.  The iterator
-     * runs around the circle until it encounters this one.
-     */
-    _Node*      mpMiddle;
-};
-
-/*
- * Assignment operator.
- *
- * The simplest way to do this would be to clear out the target list and
- * fill it with the source.  However, we can speed things along by
- * re-using existing elements.
- */
-template<class T>
-List<T>& List<T>::operator=(const List<T>& right)
-{
-    if (this == &right)
-        return *this;       // self-assignment
-    iterator firstDst = begin();
-    iterator lastDst = end();
-    const_iterator firstSrc = right.begin();
-    const_iterator lastSrc = right.end();
-    while (firstSrc != lastSrc && firstDst != lastDst)
-        *firstDst++ = *firstSrc++;
-    if (firstSrc == lastSrc)        // ran out of elements in source?
-        erase(firstDst, lastDst);   // yes, erase any extras
-    else
-        insert(lastDst, firstSrc, lastSrc);     // copy remaining over
-    return *this;
-}
-
-}; // namespace android
-
-#endif // _LIBS_UTILS_LIST_H
diff --git a/include/utils/Log.h b/include/utils/Log.h
deleted file mode 100644
index 4259c86..0000000
--- a/include/utils/Log.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// C/C++ logging functions.  See the logging documentation for API details.
-//
-// We'd like these to be available from C code (in case we import some from
-// somewhere), so this has a C interface.
-//
-// The output will be correct when the log file is shared between multiple
-// threads and/or multiple processes so long as the operating system
-// supports O_APPEND.  These calls have mutex-protected data structures
-// and so are NOT reentrant.  Do not use LOG in a signal handler.
-//
-#ifndef _LIBS_UTILS_LOG_H
-#define _LIBS_UTILS_LOG_H
-
-#include <cutils/log.h>
-#include <sys/types.h>
-
-#ifdef __cplusplus
-
-namespace android {
-
-/*
- * A very simple utility that yells in the log when an operation takes too long.
- */
-class LogIfSlow {
-public:
-    LogIfSlow(const char* tag, android_LogPriority priority,
-            int timeoutMillis, const char* message);
-    ~LogIfSlow();
-
-private:
-    const char* const mTag;
-    const android_LogPriority mPriority;
-    const int mTimeoutMillis;
-    const char* const mMessage;
-    const int64_t mStart;
-};
-
-/*
- * Writes the specified debug log message if this block takes longer than the
- * specified number of milliseconds to run.  Includes the time actually taken.
- *
- * {
- *     ALOGD_IF_SLOW(50, "Excessive delay doing something.");
- *     doSomething();
- * }
- */
-#define ALOGD_IF_SLOW(timeoutMillis, message) \
-    android::LogIfSlow _logIfSlow(LOG_TAG, ANDROID_LOG_DEBUG, timeoutMillis, message);
-
-} // namespace android
-
-#endif // __cplusplus
-
-#endif // _LIBS_UTILS_LOG_H
diff --git a/include/utils/Looper.h b/include/utils/Looper.h
deleted file mode 100644
index d4a0067..0000000
--- a/include/utils/Looper.h
+++ /dev/null
@@ -1,377 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef UTILS_LOOPER_H
-#define UTILS_LOOPER_H
-
-#include <utils/threads.h>
-#include <utils/RefBase.h>
-#include <utils/KeyedVector.h>
-#include <utils/Timers.h>
-
-#include <android/looper.h>
-
-#include <sys/epoll.h>
-
-/*
- * Declare a concrete type for the NDK's looper forward declaration.
- */
-struct ALooper {
-};
-
-namespace android {
-
-/**
- * A message that can be posted to a Looper.
- */
-struct Message {
-    Message() : what(0) { }
-    Message(int what) : what(what) { }
-
-    /* The message type. (interpretation is left up to the handler) */
-    int what;
-};
-
-
-/**
- * Interface for a Looper message handler.
- *
- * The Looper holds a strong reference to the message handler whenever it has
- * a message to deliver to it.  Make sure to call Looper::removeMessages
- * to remove any pending messages destined for the handler so that the handler
- * can be destroyed.
- */
-class MessageHandler : public virtual RefBase {
-protected:
-    virtual ~MessageHandler() { }
-
-public:
-    /**
-     * Handles a message.
-     */
-    virtual void handleMessage(const Message& message) = 0;
-};
-
-
-/**
- * A simple proxy that holds a weak reference to a message handler.
- */
-class WeakMessageHandler : public MessageHandler {
-protected:
-    virtual ~WeakMessageHandler();
-
-public:
-    WeakMessageHandler(const wp<MessageHandler>& handler);
-    virtual void handleMessage(const Message& message);
-
-private:
-    wp<MessageHandler> mHandler;
-};
-
-
-/**
- * A looper callback.
- */
-class LooperCallback : public virtual RefBase {
-protected:
-    virtual ~LooperCallback() { }
-
-public:
-    /**
-     * Handles a poll event for the given file descriptor.
-     * It is given the file descriptor it is associated with,
-     * a bitmask of the poll events that were triggered (typically ALOOPER_EVENT_INPUT),
-     * and the data pointer that was originally supplied.
-     *
-     * Implementations should return 1 to continue receiving callbacks, or 0
-     * to have this file descriptor and callback unregistered from the looper.
-     */
-    virtual int handleEvent(int fd, int events, void* data) = 0;
-};
-
-
-/**
- * Wraps a ALooper_callbackFunc function pointer.
- */
-class SimpleLooperCallback : public LooperCallback {
-protected:
-    virtual ~SimpleLooperCallback();
-
-public:
-    SimpleLooperCallback(ALooper_callbackFunc callback);
-    virtual int handleEvent(int fd, int events, void* data);
-
-private:
-    ALooper_callbackFunc mCallback;
-};
-
-
-/**
- * A polling loop that supports monitoring file descriptor events, optionally
- * using callbacks.  The implementation uses epoll() internally.
- *
- * A looper can be associated with a thread although there is no requirement that it must be.
- */
-class Looper : public ALooper, public RefBase {
-protected:
-    virtual ~Looper();
-
-public:
-    /**
-     * Creates a looper.
-     *
-     * If allowNonCallbaks is true, the looper will allow file descriptors to be
-     * registered without associated callbacks.  This assumes that the caller of
-     * pollOnce() is prepared to handle callback-less events itself.
-     */
-    Looper(bool allowNonCallbacks);
-
-    /**
-     * Returns whether this looper instance allows the registration of file descriptors
-     * using identifiers instead of callbacks.
-     */
-    bool getAllowNonCallbacks() const;
-
-    /**
-     * Waits for events to be available, with optional timeout in milliseconds.
-     * Invokes callbacks for all file descriptors on which an event occurred.
-     *
-     * If the timeout is zero, returns immediately without blocking.
-     * If the timeout is negative, waits indefinitely until an event appears.
-     *
-     * Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before
-     * the timeout expired and no callbacks were invoked and no other file
-     * descriptors were ready.
-     *
-     * Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked.
-     *
-     * Returns ALOOPER_POLL_TIMEOUT if there was no data before the given
-     * timeout expired.
-     *
-     * Returns ALOOPER_POLL_ERROR if an error occurred.
-     *
-     * Returns a value >= 0 containing an identifier if its file descriptor has data
-     * and it has no callback function (requiring the caller here to handle it).
-     * In this (and only this) case outFd, outEvents and outData will contain the poll
-     * events and data associated with the fd, otherwise they will be set to NULL.
-     *
-     * This method does not return until it has finished invoking the appropriate callbacks
-     * for all file descriptors that were signalled.
-     */
-    int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
-    inline int pollOnce(int timeoutMillis) {
-        return pollOnce(timeoutMillis, NULL, NULL, NULL);
-    }
-
-    /**
-     * Like pollOnce(), but performs all pending callbacks until all
-     * data has been consumed or a file descriptor is available with no callback.
-     * This function will never return ALOOPER_POLL_CALLBACK.
-     */
-    int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
-    inline int pollAll(int timeoutMillis) {
-        return pollAll(timeoutMillis, NULL, NULL, NULL);
-    }
-
-    /**
-     * Wakes the poll asynchronously.
-     *
-     * This method can be called on any thread.
-     * This method returns immediately.
-     */
-    void wake();
-
-    /**
-     * Adds a new file descriptor to be polled by the looper.
-     * If the same file descriptor was previously added, it is replaced.
-     *
-     * "fd" is the file descriptor to be added.
-     * "ident" is an identifier for this event, which is returned from pollOnce().
-     * The identifier must be >= 0, or ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
-     * "events" are the poll events to wake up on.  Typically this is ALOOPER_EVENT_INPUT.
-     * "callback" is the function to call when there is an event on the file descriptor.
-     * "data" is a private data pointer to supply to the callback.
-     *
-     * There are two main uses of this function:
-     *
-     * (1) If "callback" is non-NULL, then this function will be called when there is
-     * data on the file descriptor.  It should execute any events it has pending,
-     * appropriately reading from the file descriptor.  The 'ident' is ignored in this case.
-     *
-     * (2) If "callback" is NULL, the 'ident' will be returned by ALooper_pollOnce
-     * when its file descriptor has data available, requiring the caller to take
-     * care of processing it.
-     *
-     * Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
-     *
-     * This method can be called on any thread.
-     * This method may block briefly if it needs to wake the poll.
-     *
-     * The callback may either be specified as a bare function pointer or as a smart
-     * pointer callback object.  The smart pointer should be preferred because it is
-     * easier to avoid races when the callback is removed from a different thread.
-     * See removeFd() for details.
-     */
-    int addFd(int fd, int ident, int events, ALooper_callbackFunc callback, void* data);
-    int addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data);
-
-    /**
-     * Removes a previously added file descriptor from the looper.
-     *
-     * When this method returns, it is safe to close the file descriptor since the looper
-     * will no longer have a reference to it.  However, it is possible for the callback to
-     * already be running or for it to run one last time if the file descriptor was already
-     * signalled.  Calling code is responsible for ensuring that this case is safely handled.
-     * For example, if the callback takes care of removing itself during its own execution either
-     * by returning 0 or by calling this method, then it can be guaranteed to not be invoked
-     * again at any later time unless registered anew.
-     *
-     * A simple way to avoid this problem is to use the version of addFd() that takes
-     * a sp<LooperCallback> instead of a bare function pointer.  The LooperCallback will
-     * be released at the appropriate time by the Looper.
-     *
-     * Returns 1 if the file descriptor was removed, 0 if none was previously registered.
-     *
-     * This method can be called on any thread.
-     * This method may block briefly if it needs to wake the poll.
-     */
-    int removeFd(int fd);
-
-    /**
-     * Enqueues a message to be processed by the specified handler.
-     *
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void sendMessage(const sp<MessageHandler>& handler, const Message& message);
-
-    /**
-     * Enqueues a message to be processed by the specified handler after all pending messages
-     * after the specified delay.
-     *
-     * The time delay is specified in uptime nanoseconds.
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void sendMessageDelayed(nsecs_t uptimeDelay, const sp<MessageHandler>& handler,
-            const Message& message);
-
-    /**
-     * Enqueues a message to be processed by the specified handler after all pending messages
-     * at the specified time.
-     *
-     * The time is specified in uptime nanoseconds.
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void sendMessageAtTime(nsecs_t uptime, const sp<MessageHandler>& handler,
-            const Message& message);
-
-    /**
-     * Removes all messages for the specified handler from the queue.
-     *
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void removeMessages(const sp<MessageHandler>& handler);
-
-    /**
-     * Removes all messages of a particular type for the specified handler from the queue.
-     *
-     * The handler must not be null.
-     * This method can be called on any thread.
-     */
-    void removeMessages(const sp<MessageHandler>& handler, int what);
-
-    /**
-     * Prepares a looper associated with the calling thread, and returns it.
-     * If the thread already has a looper, it is returned.  Otherwise, a new
-     * one is created, associated with the thread, and returned.
-     *
-     * The opts may be ALOOPER_PREPARE_ALLOW_NON_CALLBACKS or 0.
-     */
-    static sp<Looper> prepare(int opts);
-
-    /**
-     * Sets the given looper to be associated with the calling thread.
-     * If another looper is already associated with the thread, it is replaced.
-     *
-     * If "looper" is NULL, removes the currently associated looper.
-     */
-    static void setForThread(const sp<Looper>& looper);
-
-    /**
-     * Returns the looper associated with the calling thread, or NULL if
-     * there is not one.
-     */
-    static sp<Looper> getForThread();
-
-private:
-    struct Request {
-        int fd;
-        int ident;
-        sp<LooperCallback> callback;
-        void* data;
-    };
-
-    struct Response {
-        int events;
-        Request request;
-    };
-
-    struct MessageEnvelope {
-        MessageEnvelope() : uptime(0) { }
-
-        MessageEnvelope(nsecs_t uptime, const sp<MessageHandler> handler,
-                const Message& message) : uptime(uptime), handler(handler), message(message) {
-        }
-
-        nsecs_t uptime;
-        sp<MessageHandler> handler;
-        Message message;
-    };
-
-    const bool mAllowNonCallbacks; // immutable
-
-    int mWakeReadPipeFd;  // immutable
-    int mWakeWritePipeFd; // immutable
-    Mutex mLock;
-
-    Vector<MessageEnvelope> mMessageEnvelopes; // guarded by mLock
-    bool mSendingMessage; // guarded by mLock
-
-    int mEpollFd; // immutable
-
-    // Locked list of file descriptor monitoring requests.
-    KeyedVector<int, Request> mRequests;  // guarded by mLock
-
-    // This state is only used privately by pollOnce and does not require a lock since
-    // it runs on a single thread.
-    Vector<Response> mResponses;
-    size_t mResponseIndex;
-    nsecs_t mNextMessageUptime; // set to LLONG_MAX when none
-
-    int pollInner(int timeoutMillis);
-    void awoken();
-    void pushResponse(int events, const Request& request);
-
-    static void initTLSKey();
-    static void threadDestructor(void *st);
-};
-
-} // namespace android
-
-#endif // UTILS_LOOPER_H
diff --git a/include/utils/LruCache.h b/include/utils/LruCache.h
deleted file mode 100644
index 302b929..0000000
--- a/include/utils/LruCache.h
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (C) 2012 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_UTILS_LRU_CACHE_H
-#define ANDROID_UTILS_LRU_CACHE_H
-
-#include <utils/BasicHashtable.h>
-#include <utils/GenerationCache.h>
-#include <utils/UniquePtr.h>
-
-namespace android {
-
-// OnEntryRemoved is defined in GenerationCache.h, but maybe should move here.
-
-template <typename TKey, typename TValue>
-class LruCache {
-public:
-    explicit LruCache(uint32_t maxCapacity);
-
-    enum Capacity {
-        kUnlimitedCapacity,
-    };
-
-    void setOnEntryRemovedListener(OnEntryRemoved<TKey, TValue>* listener);
-    size_t size() const;
-    const TValue& get(const TKey& key);
-    bool put(const TKey& key, const TValue& value);
-    bool remove(const TKey& key);
-    bool removeOldest();
-    void clear();
-
-    class Iterator {
-    public:
-        Iterator(const LruCache<TKey, TValue>& cache): mCache(cache), mIndex(-1) {
-        }
-
-        bool next() {
-            mIndex = mCache.mTable->next(mIndex);
-            return mIndex != -1;
-        }
-
-        size_t index() const {
-            return mIndex;
-        }
-
-        const TValue& value() const {
-            return mCache.mTable->entryAt(mIndex).value;
-        }
-
-        const TKey& key() const {
-            return mCache.mTable->entryAt(mIndex).key;
-        }
-    private:
-        const LruCache<TKey, TValue>& mCache;
-        size_t mIndex;
-    };
-
-private:
-    LruCache(const LruCache& that);  // disallow copy constructor
-
-    struct Entry {
-        TKey key;
-        TValue value;
-        Entry* parent;
-        Entry* child;
-
-        Entry(TKey key_, TValue value_) : key(key_), value(value_), parent(NULL), child(NULL) {
-        }
-        const TKey& getKey() const { return key; }
-    };
-
-    void attachToCache(Entry& entry);
-    void detachFromCache(Entry& entry);
-    void rehash(size_t newCapacity);
-
-    UniquePtr<BasicHashtable<TKey, Entry> > mTable;
-    OnEntryRemoved<TKey, TValue>* mListener;
-    Entry* mOldest;
-    Entry* mYoungest;
-    uint32_t mMaxCapacity;
-    TValue mNullValue;
-};
-
-// Implementation is here, because it's fully templated
-template <typename TKey, typename TValue>
-LruCache<TKey, TValue>::LruCache(uint32_t maxCapacity): mMaxCapacity(maxCapacity),
-    mNullValue(NULL), mTable(new BasicHashtable<TKey, Entry>), mYoungest(NULL), mOldest(NULL),
-    mListener(NULL) {
-};
-
-template<typename K, typename V>
-void LruCache<K, V>::setOnEntryRemovedListener(OnEntryRemoved<K, V>* listener) {
-    mListener = listener;
-}
-
-template <typename TKey, typename TValue>
-size_t LruCache<TKey, TValue>::size() const {
-    return mTable->size();
-}
-
-template <typename TKey, typename TValue>
-const TValue& LruCache<TKey, TValue>::get(const TKey& key) {
-    hash_t hash = hash_type(key);
-    ssize_t index = mTable->find(-1, hash, key);
-    if (index == -1) {
-        return mNullValue;
-    }
-    Entry& entry = mTable->editEntryAt(index);
-    detachFromCache(entry);
-    attachToCache(entry);
-    return entry.value;
-}
-
-template <typename TKey, typename TValue>
-bool LruCache<TKey, TValue>::put(const TKey& key, const TValue& value) {
-    if (mMaxCapacity != kUnlimitedCapacity && size() >= mMaxCapacity) {
-        removeOldest();
-    }
-
-    hash_t hash = hash_type(key);
-    ssize_t index = mTable->find(-1, hash, key);
-    if (index >= 0) {
-        return false;
-    }
-    if (!mTable->hasMoreRoom()) {
-        rehash(mTable->capacity() * 2);
-    }
-
-    // Would it be better to initialize a blank entry and assign key, value?
-    Entry initEntry(key, value);
-    index = mTable->add(hash, initEntry);
-    Entry& entry = mTable->editEntryAt(index);
-    attachToCache(entry);
-    return true;
-}
-
-template <typename TKey, typename TValue>
-bool LruCache<TKey, TValue>::remove(const TKey& key) {
-    hash_t hash = hash_type(key);
-    ssize_t index = mTable->find(-1, hash, key);
-    if (index < 0) {
-        return false;
-    }
-    Entry& entry = mTable->editEntryAt(index);
-    if (mListener) {
-        (*mListener)(entry.key, entry.value);
-    }
-    detachFromCache(entry);
-    mTable->removeAt(index);
-    return true;
-}
-
-template <typename TKey, typename TValue>
-bool LruCache<TKey, TValue>::removeOldest() {
-    if (mOldest != NULL) {
-        return remove(mOldest->key);
-        // TODO: should probably abort if false
-    }
-    return false;
-}
-
-template <typename TKey, typename TValue>
-void LruCache<TKey, TValue>::clear() {
-    if (mListener) {
-        for (Entry* p = mOldest; p != NULL; p = p->child) {
-            (*mListener)(p->key, p->value);
-        }
-    }
-    mYoungest = NULL;
-    mOldest = NULL;
-    mTable->clear();
-}
-
-template <typename TKey, typename TValue>
-void LruCache<TKey, TValue>::attachToCache(Entry& entry) {
-    if (mYoungest == NULL) {
-        mYoungest = mOldest = &entry;
-    } else {
-        entry.parent = mYoungest;
-        mYoungest->child = &entry;
-        mYoungest = &entry;
-    }
-}
-
-template <typename TKey, typename TValue>
-void LruCache<TKey, TValue>::detachFromCache(Entry& entry) {
-    if (entry.parent != NULL) {
-        entry.parent->child = entry.child;
-    } else {
-        mOldest = entry.child;
-    }
-    if (entry.child != NULL) {
-        entry.child->parent = entry.parent;
-    } else {
-        mYoungest = entry.parent;
-    }
-
-    entry.parent = NULL;
-    entry.child = NULL;
-}
-
-template <typename TKey, typename TValue>
-void LruCache<TKey, TValue>::rehash(size_t newCapacity) {
-    UniquePtr<BasicHashtable<TKey, Entry> > oldTable(mTable.release());
-    Entry* oldest = mOldest;
-
-    mOldest = NULL;
-    mYoungest = NULL;
-    mTable.reset(new BasicHashtable<TKey, Entry>(newCapacity));
-    for (Entry* p = oldest; p != NULL; p = p->child) {
-        put(p->key, p->value);
-    }
-}
-
-}
-
-#endif // ANDROID_UTILS_LRU_CACHE_H
diff --git a/include/utils/Mutex.h b/include/utils/Mutex.h
deleted file mode 100644
index dd201c8..0000000
--- a/include/utils/Mutex.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2007 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 _LIBS_UTILS_MUTEX_H
-#define _LIBS_UTILS_MUTEX_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <time.h>
-
-#if defined(HAVE_PTHREADS)
-# include <pthread.h>
-#endif
-
-#include <utils/Errors.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-class Condition;
-
-/*
- * Simple mutex class.  The implementation is system-dependent.
- *
- * The mutex must be unlocked by the thread that locked it.  They are not
- * recursive, i.e. the same thread can't lock it multiple times.
- */
-class Mutex {
-public:
-    enum {
-        PRIVATE = 0,
-        SHARED = 1
-    };
-    
-                Mutex();
-                Mutex(const char* name);
-                Mutex(int type, const char* name = NULL);
-                ~Mutex();
-
-    // lock or unlock the mutex
-    status_t    lock();
-    void        unlock();
-
-    // lock if possible; returns 0 on success, error otherwise
-    status_t    tryLock();
-
-    // Manages the mutex automatically. It'll be locked when Autolock is
-    // constructed and released when Autolock goes out of scope.
-    class Autolock {
-    public:
-        inline Autolock(Mutex& mutex) : mLock(mutex)  { mLock.lock(); }
-        inline Autolock(Mutex* mutex) : mLock(*mutex) { mLock.lock(); }
-        inline ~Autolock() { mLock.unlock(); }
-    private:
-        Mutex& mLock;
-    };
-
-private:
-    friend class Condition;
-    
-    // A mutex cannot be copied
-                Mutex(const Mutex&);
-    Mutex&      operator = (const Mutex&);
-    
-#if defined(HAVE_PTHREADS)
-    pthread_mutex_t mMutex;
-#else
-    void    _init();
-    void*   mState;
-#endif
-};
-
-// ---------------------------------------------------------------------------
-
-#if defined(HAVE_PTHREADS)
-
-inline Mutex::Mutex() {
-    pthread_mutex_init(&mMutex, NULL);
-}
-inline Mutex::Mutex(__attribute__((unused)) const char* name) {
-    pthread_mutex_init(&mMutex, NULL);
-}
-inline Mutex::Mutex(int type, __attribute__((unused)) const char* name) {
-    if (type == SHARED) {
-        pthread_mutexattr_t attr;
-        pthread_mutexattr_init(&attr);
-        pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
-        pthread_mutex_init(&mMutex, &attr);
-        pthread_mutexattr_destroy(&attr);
-    } else {
-        pthread_mutex_init(&mMutex, NULL);
-    }
-}
-inline Mutex::~Mutex() {
-    pthread_mutex_destroy(&mMutex);
-}
-inline status_t Mutex::lock() {
-    return -pthread_mutex_lock(&mMutex);
-}
-inline void Mutex::unlock() {
-    pthread_mutex_unlock(&mMutex);
-}
-inline status_t Mutex::tryLock() {
-    return -pthread_mutex_trylock(&mMutex);
-}
-
-#endif // HAVE_PTHREADS
-
-// ---------------------------------------------------------------------------
-
-/*
- * Automatic mutex.  Declare one of these at the top of a function.
- * When the function returns, it will go out of scope, and release the
- * mutex.
- */
- 
-typedef Mutex::Autolock AutoMutex;
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // _LIBS_UTILS_MUTEX_H
diff --git a/include/utils/PropertyMap.h b/include/utils/PropertyMap.h
deleted file mode 100644
index a9e674f..0000000
--- a/include/utils/PropertyMap.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef _UTILS_PROPERTY_MAP_H
-#define _UTILS_PROPERTY_MAP_H
-
-#include <utils/KeyedVector.h>
-#include <utils/String8.h>
-#include <utils/Errors.h>
-#include <utils/Tokenizer.h>
-
-namespace android {
-
-/*
- * Provides a mechanism for passing around string-based property key / value pairs
- * and loading them from property files.
- *
- * The property files have the following simple structure:
- *
- * # Comment
- * key = value
- *
- * Keys and values are any sequence of printable ASCII characters.
- * The '=' separates the key from the value.
- * The key and value may not contain whitespace.
- *
- * The '\' character is reserved for escape sequences and is not currently supported.
- * The '"" character is reserved for quoting and is not currently supported.
- * Files that contain the '\' or '"' character will fail to parse.
- *
- * The file must not contain duplicate keys.
- *
- * TODO Support escape sequences and quoted values when needed.
- */
-class PropertyMap {
-public:
-    /* Creates an empty property map. */
-    PropertyMap();
-    ~PropertyMap();
-
-    /* Clears the property map. */
-    void clear();
-
-    /* Adds a property.
-     * Replaces the property with the same key if it is already present.
-     */
-    void addProperty(const String8& key, const String8& value);
-
-    /* Returns true if the property map contains the specified key. */
-    bool hasProperty(const String8& key) const;
-
-    /* Gets the value of a property and parses it.
-     * Returns true and sets outValue if the key was found and its value was parsed successfully.
-     * Otherwise returns false and does not modify outValue.  (Also logs a warning.)
-     */
-    bool tryGetProperty(const String8& key, String8& outValue) const;
-    bool tryGetProperty(const String8& key, bool& outValue) const;
-    bool tryGetProperty(const String8& key, int32_t& outValue) const;
-    bool tryGetProperty(const String8& key, float& outValue) const;
-
-    /* Adds all values from the specified property map. */
-    void addAll(const PropertyMap* map);
-
-    /* Gets the underlying property map. */
-    inline const KeyedVector<String8, String8>& getProperties() const { return mProperties; }
-
-    /* Loads a property map from a file. */
-    static status_t load(const String8& filename, PropertyMap** outMap);
-
-private:
-    class Parser {
-        PropertyMap* mMap;
-        Tokenizer* mTokenizer;
-
-    public:
-        Parser(PropertyMap* map, Tokenizer* tokenizer);
-        ~Parser();
-        status_t parse();
-
-    private:
-        status_t parseType();
-        status_t parseKey();
-        status_t parseKeyProperty();
-        status_t parseModifier(const String8& token, int32_t* outMetaState);
-        status_t parseCharacterLiteral(char16_t* outCharacter);
-    };
-
-    KeyedVector<String8, String8> mProperties;
-};
-
-} // namespace android
-
-#endif // _UTILS_PROPERTY_MAP_H
diff --git a/include/utils/RWLock.h b/include/utils/RWLock.h
deleted file mode 100644
index 90beb5f..0000000
--- a/include/utils/RWLock.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2007 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 _LIBS_UTILS_RWLOCK_H
-#define _LIBS_UTILS_RWLOCK_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#if defined(HAVE_PTHREADS)
-# include <pthread.h>
-#endif
-
-#include <utils/Errors.h>
-#include <utils/ThreadDefs.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-#if defined(HAVE_PTHREADS)
-
-/*
- * Simple mutex class.  The implementation is system-dependent.
- *
- * The mutex must be unlocked by the thread that locked it.  They are not
- * recursive, i.e. the same thread can't lock it multiple times.
- */
-class RWLock {
-public:
-    enum {
-        PRIVATE = 0,
-        SHARED = 1
-    };
-
-                RWLock();
-                RWLock(const char* name);
-                RWLock(int type, const char* name = NULL);
-                ~RWLock();
-
-    status_t    readLock();
-    status_t    tryReadLock();
-    status_t    writeLock();
-    status_t    tryWriteLock();
-    void        unlock();
-
-    class AutoRLock {
-    public:
-        inline AutoRLock(RWLock& rwlock) : mLock(rwlock)  { mLock.readLock(); }
-        inline ~AutoRLock() { mLock.unlock(); }
-    private:
-        RWLock& mLock;
-    };
-
-    class AutoWLock {
-    public:
-        inline AutoWLock(RWLock& rwlock) : mLock(rwlock)  { mLock.writeLock(); }
-        inline ~AutoWLock() { mLock.unlock(); }
-    private:
-        RWLock& mLock;
-    };
-
-private:
-    // A RWLock cannot be copied
-                RWLock(const RWLock&);
-   RWLock&      operator = (const RWLock&);
-
-   pthread_rwlock_t mRWLock;
-};
-
-inline RWLock::RWLock() {
-    pthread_rwlock_init(&mRWLock, NULL);
-}
-inline RWLock::RWLock(__attribute__((unused)) const char* name) {
-    pthread_rwlock_init(&mRWLock, NULL);
-}
-inline RWLock::RWLock(int type, __attribute__((unused)) const char* name) {
-    if (type == SHARED) {
-        pthread_rwlockattr_t attr;
-        pthread_rwlockattr_init(&attr);
-        pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
-        pthread_rwlock_init(&mRWLock, &attr);
-        pthread_rwlockattr_destroy(&attr);
-    } else {
-        pthread_rwlock_init(&mRWLock, NULL);
-    }
-}
-inline RWLock::~RWLock() {
-    pthread_rwlock_destroy(&mRWLock);
-}
-inline status_t RWLock::readLock() {
-    return -pthread_rwlock_rdlock(&mRWLock);
-}
-inline status_t RWLock::tryReadLock() {
-    return -pthread_rwlock_tryrdlock(&mRWLock);
-}
-inline status_t RWLock::writeLock() {
-    return -pthread_rwlock_wrlock(&mRWLock);
-}
-inline status_t RWLock::tryWriteLock() {
-    return -pthread_rwlock_trywrlock(&mRWLock);
-}
-inline void RWLock::unlock() {
-    pthread_rwlock_unlock(&mRWLock);
-}
-
-#endif // HAVE_PTHREADS
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-// ---------------------------------------------------------------------------
-
-#endif // _LIBS_UTILS_RWLOCK_H
diff --git a/include/utils/RefBase.h b/include/utils/RefBase.h
deleted file mode 100644
index 033fe67..0000000
--- a/include/utils/RefBase.h
+++ /dev/null
@@ -1,546 +0,0 @@
-/*
- * Copyright (C) 2005 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_REF_BASE_H
-#define ANDROID_REF_BASE_H
-
-#include <cutils/atomic.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <utils/StrongPointer.h>
-#include <utils/TypeHelpers.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-
-class TextOutput;
-TextOutput& printWeakPointer(TextOutput& to, const void* val);
-
-// ---------------------------------------------------------------------------
-
-#define COMPARE_WEAK(_op_)                                      \
-inline bool operator _op_ (const sp<T>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-inline bool operator _op_ (const T* o) const {                  \
-    return m_ptr _op_ o;                                        \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const sp<U>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const U* o) const {                  \
-    return m_ptr _op_ o;                                        \
-}
-
-// ---------------------------------------------------------------------------
-
-class ReferenceRenamer {
-protected:
-    // destructor is purposedly not virtual so we avoid code overhead from
-    // subclasses; we have to make it protected to guarantee that it
-    // cannot be called from this base class (and to make strict compilers
-    // happy).
-    ~ReferenceRenamer() { }
-public:
-    virtual void operator()(size_t i) const = 0;
-};
-
-// ---------------------------------------------------------------------------
-
-class RefBase
-{
-public:
-            void            incStrong(const void* id) const;
-            void            decStrong(const void* id) const;
-    
-            void            forceIncStrong(const void* id) const;
-
-            //! DEBUGGING ONLY: Get current strong ref count.
-            int32_t         getStrongCount() const;
-
-    class weakref_type
-    {
-    public:
-        RefBase*            refBase() const;
-        
-        void                incWeak(const void* id);
-        void                decWeak(const void* id);
-        
-        // acquires a strong reference if there is already one.
-        bool                attemptIncStrong(const void* id);
-        
-        // acquires a weak reference if there is already one.
-        // This is not always safe. see ProcessState.cpp and BpBinder.cpp
-        // for proper use.
-        bool                attemptIncWeak(const void* id);
-
-        //! DEBUGGING ONLY: Get current weak ref count.
-        int32_t             getWeakCount() const;
-
-        //! DEBUGGING ONLY: Print references held on object.
-        void                printRefs() const;
-
-        //! DEBUGGING ONLY: Enable tracking for this object.
-        // enable -- enable/disable tracking
-        // retain -- when tracking is enable, if true, then we save a stack trace
-        //           for each reference and dereference; when retain == false, we
-        //           match up references and dereferences and keep only the 
-        //           outstanding ones.
-        
-        void                trackMe(bool enable, bool retain);
-    };
-    
-            weakref_type*   createWeak(const void* id) const;
-            
-            weakref_type*   getWeakRefs() const;
-
-            //! DEBUGGING ONLY: Print references held on object.
-    inline  void            printRefs() const { getWeakRefs()->printRefs(); }
-
-            //! DEBUGGING ONLY: Enable tracking of object.
-    inline  void            trackMe(bool enable, bool retain)
-    { 
-        getWeakRefs()->trackMe(enable, retain); 
-    }
-
-    typedef RefBase basetype;
-
-protected:
-                            RefBase();
-    virtual                 ~RefBase();
-
-    //! Flags for extendObjectLifetime()
-    enum {
-        OBJECT_LIFETIME_STRONG  = 0x0000,
-        OBJECT_LIFETIME_WEAK    = 0x0001,
-        OBJECT_LIFETIME_MASK    = 0x0001
-    };
-    
-            void            extendObjectLifetime(int32_t mode);
-            
-    //! Flags for onIncStrongAttempted()
-    enum {
-        FIRST_INC_STRONG = 0x0001
-    };
-    
-    virtual void            onFirstRef();
-    virtual void            onLastStrongRef(const void* id);
-    virtual bool            onIncStrongAttempted(uint32_t flags, const void* id);
-    virtual void            onLastWeakRef(const void* id);
-
-private:
-    friend class weakref_type;
-    class weakref_impl;
-    
-                            RefBase(const RefBase& o);
-            RefBase&        operator=(const RefBase& o);
-
-private:
-    friend class ReferenceMover;
-
-    static void renameRefs(size_t n, const ReferenceRenamer& renamer);
-
-    static void renameRefId(weakref_type* ref,
-            const void* old_id, const void* new_id);
-
-    static void renameRefId(RefBase* ref,
-            const void* old_id, const void* new_id);
-
-        weakref_impl* const mRefs;
-};
-
-// ---------------------------------------------------------------------------
-
-template <class T>
-class LightRefBase
-{
-public:
-    inline LightRefBase() : mCount(0) { }
-    inline void incStrong(__attribute__((unused)) const void* id) const {
-        android_atomic_inc(&mCount);
-    }
-    inline void decStrong(__attribute__((unused)) const void* id) const {
-        if (android_atomic_dec(&mCount) == 1) {
-            delete static_cast<const T*>(this);
-        }
-    }
-    //! DEBUGGING ONLY: Get current strong ref count.
-    inline int32_t getStrongCount() const {
-        return mCount;
-    }
-
-    typedef LightRefBase<T> basetype;
-
-protected:
-    inline ~LightRefBase() { }
-
-private:
-    friend class ReferenceMover;
-    inline static void renameRefs(size_t n, const ReferenceRenamer& renamer) { }
-    inline static void renameRefId(T* ref,
-            const void* old_id, const void* new_id) { }
-
-private:
-    mutable volatile int32_t mCount;
-};
-
-// ---------------------------------------------------------------------------
-
-template <typename T>
-class wp
-{
-public:
-    typedef typename RefBase::weakref_type weakref_type;
-    
-    inline wp() : m_ptr(0) { }
-
-    wp(T* other);
-    wp(const wp<T>& other);
-    wp(const sp<T>& other);
-    template<typename U> wp(U* other);
-    template<typename U> wp(const sp<U>& other);
-    template<typename U> wp(const wp<U>& other);
-
-    ~wp();
-    
-    // Assignment
-
-    wp& operator = (T* other);
-    wp& operator = (const wp<T>& other);
-    wp& operator = (const sp<T>& other);
-    
-    template<typename U> wp& operator = (U* other);
-    template<typename U> wp& operator = (const wp<U>& other);
-    template<typename U> wp& operator = (const sp<U>& other);
-    
-    void set_object_and_refs(T* other, weakref_type* refs);
-
-    // promotion to sp
-    
-    sp<T> promote() const;
-
-    // Reset
-    
-    void clear();
-
-    // Accessors
-    
-    inline  weakref_type* get_refs() const { return m_refs; }
-    
-    inline  T* unsafe_get() const { return m_ptr; }
-
-    // Operators
-
-    COMPARE_WEAK(==)
-    COMPARE_WEAK(!=)
-    COMPARE_WEAK(>)
-    COMPARE_WEAK(<)
-    COMPARE_WEAK(<=)
-    COMPARE_WEAK(>=)
-
-    inline bool operator == (const wp<T>& o) const {
-        return (m_ptr == o.m_ptr) && (m_refs == o.m_refs);
-    }
-    template<typename U>
-    inline bool operator == (const wp<U>& o) const {
-        return m_ptr == o.m_ptr;
-    }
-
-    inline bool operator > (const wp<T>& o) const {
-        return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
-    }
-    template<typename U>
-    inline bool operator > (const wp<U>& o) const {
-        return (m_ptr == o.m_ptr) ? (m_refs > o.m_refs) : (m_ptr > o.m_ptr);
-    }
-
-    inline bool operator < (const wp<T>& o) const {
-        return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
-    }
-    template<typename U>
-    inline bool operator < (const wp<U>& o) const {
-        return (m_ptr == o.m_ptr) ? (m_refs < o.m_refs) : (m_ptr < o.m_ptr);
-    }
-                         inline bool operator != (const wp<T>& o) const { return m_refs != o.m_refs; }
-    template<typename U> inline bool operator != (const wp<U>& o) const { return !operator == (o); }
-                         inline bool operator <= (const wp<T>& o) const { return !operator > (o); }
-    template<typename U> inline bool operator <= (const wp<U>& o) const { return !operator > (o); }
-                         inline bool operator >= (const wp<T>& o) const { return !operator < (o); }
-    template<typename U> inline bool operator >= (const wp<U>& o) const { return !operator < (o); }
-
-private:
-    template<typename Y> friend class sp;
-    template<typename Y> friend class wp;
-
-    T*              m_ptr;
-    weakref_type*   m_refs;
-};
-
-template <typename T>
-TextOutput& operator<<(TextOutput& to, const wp<T>& val);
-
-#undef COMPARE_WEAK
-
-// ---------------------------------------------------------------------------
-// No user serviceable parts below here.
-
-template<typename T>
-wp<T>::wp(T* other)
-    : m_ptr(other)
-{
-    if (other) m_refs = other->createWeak(this);
-}
-
-template<typename T>
-wp<T>::wp(const wp<T>& other)
-    : m_ptr(other.m_ptr), m_refs(other.m_refs)
-{
-    if (m_ptr) m_refs->incWeak(this);
-}
-
-template<typename T>
-wp<T>::wp(const sp<T>& other)
-    : m_ptr(other.m_ptr)
-{
-    if (m_ptr) {
-        m_refs = m_ptr->createWeak(this);
-    }
-}
-
-template<typename T> template<typename U>
-wp<T>::wp(U* other)
-    : m_ptr(other)
-{
-    if (other) m_refs = other->createWeak(this);
-}
-
-template<typename T> template<typename U>
-wp<T>::wp(const wp<U>& other)
-    : m_ptr(other.m_ptr)
-{
-    if (m_ptr) {
-        m_refs = other.m_refs;
-        m_refs->incWeak(this);
-    }
-}
-
-template<typename T> template<typename U>
-wp<T>::wp(const sp<U>& other)
-    : m_ptr(other.m_ptr)
-{
-    if (m_ptr) {
-        m_refs = m_ptr->createWeak(this);
-    }
-}
-
-template<typename T>
-wp<T>::~wp()
-{
-    if (m_ptr) m_refs->decWeak(this);
-}
-
-template<typename T>
-wp<T>& wp<T>::operator = (T* other)
-{
-    weakref_type* newRefs =
-        other ? other->createWeak(this) : 0;
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = other;
-    m_refs = newRefs;
-    return *this;
-}
-
-template<typename T>
-wp<T>& wp<T>::operator = (const wp<T>& other)
-{
-    weakref_type* otherRefs(other.m_refs);
-    T* otherPtr(other.m_ptr);
-    if (otherPtr) otherRefs->incWeak(this);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = otherPtr;
-    m_refs = otherRefs;
-    return *this;
-}
-
-template<typename T>
-wp<T>& wp<T>::operator = (const sp<T>& other)
-{
-    weakref_type* newRefs =
-        other != NULL ? other->createWeak(this) : 0;
-    T* otherPtr(other.m_ptr);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = otherPtr;
-    m_refs = newRefs;
-    return *this;
-}
-
-template<typename T> template<typename U>
-wp<T>& wp<T>::operator = (U* other)
-{
-    weakref_type* newRefs =
-        other ? other->createWeak(this) : 0;
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = other;
-    m_refs = newRefs;
-    return *this;
-}
-
-template<typename T> template<typename U>
-wp<T>& wp<T>::operator = (const wp<U>& other)
-{
-    weakref_type* otherRefs(other.m_refs);
-    U* otherPtr(other.m_ptr);
-    if (otherPtr) otherRefs->incWeak(this);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = otherPtr;
-    m_refs = otherRefs;
-    return *this;
-}
-
-template<typename T> template<typename U>
-wp<T>& wp<T>::operator = (const sp<U>& other)
-{
-    weakref_type* newRefs =
-        other != NULL ? other->createWeak(this) : 0;
-    U* otherPtr(other.m_ptr);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = otherPtr;
-    m_refs = newRefs;
-    return *this;
-}
-
-template<typename T>
-void wp<T>::set_object_and_refs(T* other, weakref_type* refs)
-{
-    if (other) refs->incWeak(this);
-    if (m_ptr) m_refs->decWeak(this);
-    m_ptr = other;
-    m_refs = refs;
-}
-
-template<typename T>
-sp<T> wp<T>::promote() const
-{
-    sp<T> result;
-    if (m_ptr && m_refs->attemptIncStrong(&result)) {
-        result.set_pointer(m_ptr);
-    }
-    return result;
-}
-
-template<typename T>
-void wp<T>::clear()
-{
-    if (m_ptr) {
-        m_refs->decWeak(this);
-        m_ptr = 0;
-    }
-}
-
-template <typename T>
-inline TextOutput& operator<<(TextOutput& to, const wp<T>& val)
-{
-    return printWeakPointer(to, val.unsafe_get());
-}
-
-// ---------------------------------------------------------------------------
-
-// this class just serves as a namespace so TYPE::moveReferences can stay
-// private.
-class ReferenceMover {
-public:
-    // it would be nice if we could make sure no extra code is generated
-    // for sp<TYPE> or wp<TYPE> when TYPE is a descendant of RefBase:
-    // Using a sp<RefBase> override doesn't work; it's a bit like we wanted
-    // a template<typename TYPE inherits RefBase> template...
-
-    template<typename TYPE> static inline
-    void move_references(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
-
-        class Renamer : public ReferenceRenamer {
-            sp<TYPE>* d;
-            sp<TYPE> const* s;
-            virtual void operator()(size_t i) const {
-                // The id are known to be the sp<>'s this pointer
-                TYPE::renameRefId(d[i].get(), &s[i], &d[i]);
-            }
-        public:
-            Renamer(sp<TYPE>* d, sp<TYPE> const* s) : s(s), d(d) { }
-        };
-
-        memmove(d, s, n*sizeof(sp<TYPE>));
-        TYPE::renameRefs(n, Renamer(d, s));
-    }
-
-
-    template<typename TYPE> static inline
-    void move_references(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
-
-        class Renamer : public ReferenceRenamer {
-            wp<TYPE>* d;
-            wp<TYPE> const* s;
-            virtual void operator()(size_t i) const {
-                // The id are known to be the wp<>'s this pointer
-                TYPE::renameRefId(d[i].get_refs(), &s[i], &d[i]);
-            }
-        public:
-            Renamer(wp<TYPE>* d, wp<TYPE> const* s) : s(s), d(d) { }
-        };
-
-        memmove(d, s, n*sizeof(wp<TYPE>));
-        TYPE::renameRefs(n, Renamer(d, s));
-    }
-};
-
-// specialization for moving sp<> and wp<> types.
-// these are used by the [Sorted|Keyed]Vector<> implementations
-// sp<> and wp<> need to be handled specially, because they do not
-// have trivial copy operation in the general case (see RefBase.cpp
-// when DEBUG ops are enabled), but can be implemented very
-// efficiently in most cases.
-
-template<typename TYPE> inline
-void move_forward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
-    ReferenceMover::move_references(d, s, n);
-}
-
-template<typename TYPE> inline
-void move_backward_type(sp<TYPE>* d, sp<TYPE> const* s, size_t n) {
-    ReferenceMover::move_references(d, s, n);
-}
-
-template<typename TYPE> inline
-void move_forward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
-    ReferenceMover::move_references(d, s, n);
-}
-
-template<typename TYPE> inline
-void move_backward_type(wp<TYPE>* d, wp<TYPE> const* s, size_t n) {
-    ReferenceMover::move_references(d, s, n);
-}
-
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_REF_BASE_H
diff --git a/include/utils/SharedBuffer.h b/include/utils/SharedBuffer.h
deleted file mode 100644
index b670953..0000000
--- a/include/utils/SharedBuffer.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2005 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_SHARED_BUFFER_H
-#define ANDROID_SHARED_BUFFER_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-class SharedBuffer
-{
-public:
-
-    /* flags to use with release() */
-    enum {
-        eKeepStorage = 0x00000001
-    };
-
-    /*! allocate a buffer of size 'size' and acquire() it.
-     *  call release() to free it.
-     */
-    static          SharedBuffer*           alloc(size_t size);
-    
-    /*! free the memory associated with the SharedBuffer.
-     * Fails if there are any users associated with this SharedBuffer.
-     * In other words, the buffer must have been release by all its
-     * users.
-     */
-    static          ssize_t                 dealloc(const SharedBuffer* released);
-
-    //! access the data for read
-    inline          const void*             data() const;
-    
-    //! access the data for read/write
-    inline          void*                   data();
-
-    //! get size of the buffer
-    inline          size_t                  size() const;
- 
-    //! get back a SharedBuffer object from its data
-    static  inline  SharedBuffer*           bufferFromData(void* data);
-    
-    //! get back a SharedBuffer object from its data
-    static  inline  const SharedBuffer*     bufferFromData(const void* data);
-
-    //! get the size of a SharedBuffer object from its data
-    static  inline  size_t                  sizeFromData(const void* data);
-    
-    //! edit the buffer (get a writtable, or non-const, version of it)
-                    SharedBuffer*           edit() const;
-
-    //! edit the buffer, resizing if needed
-                    SharedBuffer*           editResize(size_t size) const;
-
-    //! like edit() but fails if a copy is required
-                    SharedBuffer*           attemptEdit() const;
-    
-    //! resize and edit the buffer, loose it's content.
-                    SharedBuffer*           reset(size_t size) const;
-
-    //! acquire/release a reference on this buffer
-                    void                    acquire() const;
-                    
-    /*! release a reference on this buffer, with the option of not
-     * freeing the memory associated with it if it was the last reference
-     * returns the previous reference count
-     */     
-                    int32_t                 release(uint32_t flags = 0) const;
-    
-    //! returns wether or not we're the only owner
-    inline          bool                    onlyOwner() const;
-    
-
-private:
-        inline SharedBuffer() { }
-        inline ~SharedBuffer() { }
-        SharedBuffer(const SharedBuffer&);
-        SharedBuffer& operator = (const SharedBuffer&);
- 
-        // 16 bytes. must be sized to preserve correct alignment.
-        mutable int32_t        mRefs;
-                size_t         mSize;
-                uint32_t       mReserved[2];
-};
-
-// ---------------------------------------------------------------------------
-
-const void* SharedBuffer::data() const {
-    return this + 1;
-}
-
-void* SharedBuffer::data() {
-    return this + 1;
-}
-
-size_t SharedBuffer::size() const {
-    return mSize;
-}
-
-SharedBuffer* SharedBuffer::bufferFromData(void* data) {
-    return data ? static_cast<SharedBuffer *>(data)-1 : 0;
-}
-    
-const SharedBuffer* SharedBuffer::bufferFromData(const void* data) {
-    return data ? static_cast<const SharedBuffer *>(data)-1 : 0;
-}
-
-size_t SharedBuffer::sizeFromData(const void* data) {
-    return data ? bufferFromData(data)->mSize : 0;
-}
-
-bool SharedBuffer::onlyOwner() const {
-    return (mRefs == 1);
-}
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_VECTOR_H
diff --git a/include/utils/Singleton.h b/include/utils/Singleton.h
deleted file mode 100644
index c60680e..0000000
--- a/include/utils/Singleton.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2007 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_UTILS_SINGLETON_H
-#define ANDROID_UTILS_SINGLETON_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <utils/threads.h>
-#include <cutils/compiler.h>
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-template <typename TYPE>
-class ANDROID_API Singleton
-{
-public:
-    static TYPE& getInstance() {
-        Mutex::Autolock _l(sLock);
-        TYPE* instance = sInstance;
-        if (instance == 0) {
-            instance = new TYPE();
-            sInstance = instance;
-        }
-        return *instance;
-    }
-
-    static bool hasInstance() {
-        Mutex::Autolock _l(sLock);
-        return sInstance != 0;
-    }
-    
-protected:
-    ~Singleton() { };
-    Singleton() { };
-
-private:
-    Singleton(const Singleton&);
-    Singleton& operator = (const Singleton&);
-    static Mutex sLock;
-    static TYPE* sInstance;
-};
-
-/*
- * use ANDROID_SINGLETON_STATIC_INSTANCE(TYPE) in your implementation file
- * (eg: <TYPE>.cpp) to create the static instance of Singleton<>'s attributes,
- * and avoid to have a copy of them in each compilation units Singleton<TYPE>
- * is used.
- * NOTE: we use a version of Mutex ctor that takes a parameter, because
- * for some unknown reason using the default ctor doesn't emit the variable!
- */
-
-#define ANDROID_SINGLETON_STATIC_INSTANCE(TYPE)                 \
-    template<> Mutex Singleton< TYPE >::sLock(Mutex::PRIVATE);  \
-    template<> TYPE* Singleton< TYPE >::sInstance(0);           \
-    template class Singleton< TYPE >;
-
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-
-#endif // ANDROID_UTILS_SINGLETON_H
-
diff --git a/include/utils/SortedVector.h b/include/utils/SortedVector.h
deleted file mode 100644
index 2d3e82a..0000000
--- a/include/utils/SortedVector.h
+++ /dev/null
@@ -1,282 +0,0 @@
-/*
- * Copyright (C) 2005 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_SORTED_VECTOR_H
-#define ANDROID_SORTED_VECTOR_H
-
-#include <assert.h>
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <cutils/log.h>
-
-#include <utils/Vector.h>
-#include <utils/VectorImpl.h>
-#include <utils/TypeHelpers.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-template <class TYPE>
-class SortedVector : private SortedVectorImpl
-{
-    friend class Vector<TYPE>;
-
-public:
-            typedef TYPE    value_type;
-    
-    /*! 
-     * Constructors and destructors
-     */
-    
-                            SortedVector();
-                            SortedVector(const SortedVector<TYPE>& rhs);
-    virtual                 ~SortedVector();
-
-    /*! copy operator */
-    const SortedVector<TYPE>&   operator = (const SortedVector<TYPE>& rhs) const;    
-    SortedVector<TYPE>&         operator = (const SortedVector<TYPE>& rhs);    
-
-    /*
-     * empty the vector
-     */
-
-    inline  void            clear()             { VectorImpl::clear(); }
-
-    /*! 
-     * vector stats
-     */
-
-    //! returns number of items in the vector
-    inline  size_t          size() const                { return VectorImpl::size(); }
-    //! returns whether or not the vector is empty
-    inline  bool            isEmpty() const             { return VectorImpl::isEmpty(); }
-    //! returns how many items can be stored without reallocating the backing store
-    inline  size_t          capacity() const            { return VectorImpl::capacity(); }
-    //! sets the capacity. capacity can never be reduced less than size()
-    inline  ssize_t         setCapacity(size_t size)    { return VectorImpl::setCapacity(size); }
-
-    /*! 
-     * C-style array access
-     */
-     
-    //! read-only C-style access 
-    inline  const TYPE*     array() const;
-
-    //! read-write C-style access. BE VERY CAREFUL when modifying the array
-    //! you must keep it sorted! You usually don't use this function.
-            TYPE*           editArray();
-
-            //! finds the index of an item
-            ssize_t         indexOf(const TYPE& item) const;
-            
-            //! finds where this item should be inserted
-            size_t          orderOf(const TYPE& item) const;
-            
-    
-    /*! 
-     * accessors
-     */
-
-    //! read-only access to an item at a given index
-    inline  const TYPE&     operator [] (size_t index) const;
-    //! alternate name for operator []
-    inline  const TYPE&     itemAt(size_t index) const;
-    //! stack-usage of the vector. returns the top of the stack (last element)
-            const TYPE&     top() const;
-
-    /*!
-     * modifying the array
-     */
-
-            //! add an item in the right place (and replace the one that is there)
-            ssize_t         add(const TYPE& item);
-            
-            //! editItemAt() MUST NOT change the order of this item
-            TYPE&           editItemAt(size_t index) {
-                return *( static_cast<TYPE *>(VectorImpl::editItemLocation(index)) );
-            }
-
-            //! merges a vector into this one
-            ssize_t         merge(const Vector<TYPE>& vector);
-            ssize_t         merge(const SortedVector<TYPE>& vector);
-            
-            //! removes an item
-            ssize_t         remove(const TYPE&);
-
-    //! remove several items
-    inline  ssize_t         removeItemsAt(size_t index, size_t count = 1);
-    //! remove one item
-    inline  ssize_t         removeAt(size_t index)  { return removeItemsAt(index); }
-            
-protected:
-    virtual void    do_construct(void* storage, size_t num) const;
-    virtual void    do_destroy(void* storage, size_t num) const;
-    virtual void    do_copy(void* dest, const void* from, size_t num) const;
-    virtual void    do_splat(void* dest, const void* item, size_t num) const;
-    virtual void    do_move_forward(void* dest, const void* from, size_t num) const;
-    virtual void    do_move_backward(void* dest, const void* from, size_t num) const;
-    virtual int     do_compare(const void* lhs, const void* rhs) const;
-};
-
-// SortedVector<T> can be trivially moved using memcpy() because moving does not
-// require any change to the underlying SharedBuffer contents or reference count.
-template<typename T> struct trait_trivial_move<SortedVector<T> > { enum { value = true }; };
-
-// ---------------------------------------------------------------------------
-// No user serviceable parts from here...
-// ---------------------------------------------------------------------------
-
-template<class TYPE> inline
-SortedVector<TYPE>::SortedVector()
-    : SortedVectorImpl(sizeof(TYPE),
-                ((traits<TYPE>::has_trivial_ctor   ? HAS_TRIVIAL_CTOR   : 0)
-                |(traits<TYPE>::has_trivial_dtor   ? HAS_TRIVIAL_DTOR   : 0)
-                |(traits<TYPE>::has_trivial_copy   ? HAS_TRIVIAL_COPY   : 0))
-                )
-{
-}
-
-template<class TYPE> inline
-SortedVector<TYPE>::SortedVector(const SortedVector<TYPE>& rhs)
-    : SortedVectorImpl(rhs) {
-}
-
-template<class TYPE> inline
-SortedVector<TYPE>::~SortedVector() {
-    finish_vector();
-}
-
-template<class TYPE> inline
-SortedVector<TYPE>& SortedVector<TYPE>::operator = (const SortedVector<TYPE>& rhs) {
-    SortedVectorImpl::operator = (rhs);
-    return *this; 
-}
-
-template<class TYPE> inline
-const SortedVector<TYPE>& SortedVector<TYPE>::operator = (const SortedVector<TYPE>& rhs) const {
-    SortedVectorImpl::operator = (rhs);
-    return *this; 
-}
-
-template<class TYPE> inline
-const TYPE* SortedVector<TYPE>::array() const {
-    return static_cast<const TYPE *>(arrayImpl());
-}
-
-template<class TYPE> inline
-TYPE* SortedVector<TYPE>::editArray() {
-    return static_cast<TYPE *>(editArrayImpl());
-}
-
-
-template<class TYPE> inline
-const TYPE& SortedVector<TYPE>::operator[](size_t index) const {
-    LOG_FATAL_IF(index>=size(),
-            "%s: index=%u out of range (%u)", __PRETTY_FUNCTION__,
-            int(index), int(size()));
-    return *(array() + index);
-}
-
-template<class TYPE> inline
-const TYPE& SortedVector<TYPE>::itemAt(size_t index) const {
-    return operator[](index);
-}
-
-template<class TYPE> inline
-const TYPE& SortedVector<TYPE>::top() const {
-    return *(array() + size() - 1);
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::add(const TYPE& item) {
-    return SortedVectorImpl::add(&item);
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::indexOf(const TYPE& item) const {
-    return SortedVectorImpl::indexOf(&item);
-}
-
-template<class TYPE> inline
-size_t SortedVector<TYPE>::orderOf(const TYPE& item) const {
-    return SortedVectorImpl::orderOf(&item);
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::merge(const Vector<TYPE>& vector) {
-    return SortedVectorImpl::merge(reinterpret_cast<const VectorImpl&>(vector));
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::merge(const SortedVector<TYPE>& vector) {
-    return SortedVectorImpl::merge(reinterpret_cast<const SortedVectorImpl&>(vector));
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::remove(const TYPE& item) {
-    return SortedVectorImpl::remove(&item);
-}
-
-template<class TYPE> inline
-ssize_t SortedVector<TYPE>::removeItemsAt(size_t index, size_t count) {
-    return VectorImpl::removeItemsAt(index, count);
-}
-
-// ---------------------------------------------------------------------------
-
-template<class TYPE>
-void SortedVector<TYPE>::do_construct(void* storage, size_t num) const {
-    construct_type( reinterpret_cast<TYPE*>(storage), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_destroy(void* storage, size_t num) const {
-    destroy_type( reinterpret_cast<TYPE*>(storage), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_copy(void* dest, const void* from, size_t num) const {
-    copy_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_splat(void* dest, const void* item, size_t num) const {
-    splat_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(item), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_move_forward(void* dest, const void* from, size_t num) const {
-    move_forward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
-}
-
-template<class TYPE>
-void SortedVector<TYPE>::do_move_backward(void* dest, const void* from, size_t num) const {
-    move_backward_type( reinterpret_cast<TYPE*>(dest), reinterpret_cast<const TYPE*>(from), num );
-}
-
-template<class TYPE>
-int SortedVector<TYPE>::do_compare(const void* lhs, const void* rhs) const {
-    return compare_type( *reinterpret_cast<const TYPE*>(lhs), *reinterpret_cast<const TYPE*>(rhs) );
-}
-
-}; // namespace android
-
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_SORTED_VECTOR_H
diff --git a/include/utils/StopWatch.h b/include/utils/StopWatch.h
deleted file mode 100644
index 693dd3c..0000000
--- a/include/utils/StopWatch.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2005 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_STOPWATCH_H
-#define ANDROID_STOPWATCH_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <utils/Timers.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-class StopWatch
-{
-public:
-        StopWatch(  const char *name,
-                    int clock = SYSTEM_TIME_MONOTONIC,
-                    uint32_t flags = 0);
-        ~StopWatch();
-        
-        const char* name() const;
-        nsecs_t     lap();
-        nsecs_t     elapsedTime() const;
-
-        void        reset();
-        
-private:
-    const char*     mName;
-    int             mClock;
-    uint32_t        mFlags;
-    
-    struct lap_t {
-        nsecs_t     soFar;
-        nsecs_t     thisLap;
-    };
-    
-    nsecs_t         mStartTime;
-    lap_t           mLaps[8];
-    int             mNumLaps;
-};
-
-
-}; // namespace android
-
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_STOPWATCH_H
diff --git a/include/utils/String16.h b/include/utils/String16.h
deleted file mode 100644
index fe06c57..0000000
--- a/include/utils/String16.h
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Copyright (C) 2005 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_STRING16_H
-#define ANDROID_STRING16_H
-
-#include <utils/Errors.h>
-#include <utils/SharedBuffer.h>
-#include <utils/Unicode.h>
-#include <utils/TypeHelpers.h>
-
-// ---------------------------------------------------------------------------
-
-extern "C" {
-
-}
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-// ---------------------------------------------------------------------------
-
-class String8;
-class TextOutput;
-
-//! This is a string holding UTF-16 characters.
-class String16
-{
-public:
-                                String16();
-                                String16(const String16& o);
-                                String16(const String16& o,
-                                         size_t len,
-                                         size_t begin=0);
-    explicit                    String16(const char16_t* o);
-    explicit                    String16(const char16_t* o, size_t len);
-    explicit                    String16(const String8& o);
-    explicit                    String16(const char* o);
-    explicit                    String16(const char* o, size_t len);
-
-                                ~String16();
-    
-    inline  const char16_t*     string() const;
-    inline  size_t              size() const;
-    
-    inline  const SharedBuffer* sharedBuffer() const;
-    
-            void                setTo(const String16& other);
-            status_t            setTo(const char16_t* other);
-            status_t            setTo(const char16_t* other, size_t len);
-            status_t            setTo(const String16& other,
-                                      size_t len,
-                                      size_t begin=0);
-    
-            status_t            append(const String16& other);
-            status_t            append(const char16_t* other, size_t len);
-            
-    inline  String16&           operator=(const String16& other);
-    
-    inline  String16&           operator+=(const String16& other);
-    inline  String16            operator+(const String16& other) const;
-
-            status_t            insert(size_t pos, const char16_t* chrs);
-            status_t            insert(size_t pos,
-                                       const char16_t* chrs, size_t len);
-
-            ssize_t             findFirst(char16_t c) const;
-            ssize_t             findLast(char16_t c) const;
-
-            bool                startsWith(const String16& prefix) const;
-            bool                startsWith(const char16_t* prefix) const;
-            
-            status_t            makeLower();
-
-            status_t            replaceAll(char16_t replaceThis,
-                                           char16_t withThis);
-
-            status_t            remove(size_t len, size_t begin=0);
-
-    inline  int                 compare(const String16& other) const;
-
-    inline  bool                operator<(const String16& other) const;
-    inline  bool                operator<=(const String16& other) const;
-    inline  bool                operator==(const String16& other) const;
-    inline  bool                operator!=(const String16& other) const;
-    inline  bool                operator>=(const String16& other) const;
-    inline  bool                operator>(const String16& other) const;
-    
-    inline  bool                operator<(const char16_t* other) const;
-    inline  bool                operator<=(const char16_t* other) const;
-    inline  bool                operator==(const char16_t* other) const;
-    inline  bool                operator!=(const char16_t* other) const;
-    inline  bool                operator>=(const char16_t* other) const;
-    inline  bool                operator>(const char16_t* other) const;
-    
-    inline                      operator const char16_t*() const;
-    
-private:
-            const char16_t*     mString;
-};
-
-// String16 can be trivially moved using memcpy() because moving does not
-// require any change to the underlying SharedBuffer contents or reference count.
-ANDROID_TRIVIAL_MOVE_TRAIT(String16)
-
-TextOutput& operator<<(TextOutput& to, const String16& val);
-
-// ---------------------------------------------------------------------------
-// No user servicable parts below.
-
-inline int compare_type(const String16& lhs, const String16& rhs)
-{
-    return lhs.compare(rhs);
-}
-
-inline int strictly_order_type(const String16& lhs, const String16& rhs)
-{
-    return compare_type(lhs, rhs) < 0;
-}
-
-inline const char16_t* String16::string() const
-{
-    return mString;
-}
-
-inline size_t String16::size() const
-{
-    return SharedBuffer::sizeFromData(mString)/sizeof(char16_t)-1;
-}
-
-inline const SharedBuffer* String16::sharedBuffer() const
-{
-    return SharedBuffer::bufferFromData(mString);
-}
-
-inline String16& String16::operator=(const String16& other)
-{
-    setTo(other);
-    return *this;
-}
-
-inline String16& String16::operator+=(const String16& other)
-{
-    append(other);
-    return *this;
-}
-
-inline String16 String16::operator+(const String16& other) const
-{
-    String16 tmp(*this);
-    tmp += other;
-    return tmp;
-}
-
-inline int String16::compare(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size());
-}
-
-inline bool String16::operator<(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) < 0;
-}
-
-inline bool String16::operator<=(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) <= 0;
-}
-
-inline bool String16::operator==(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) == 0;
-}
-
-inline bool String16::operator!=(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) != 0;
-}
-
-inline bool String16::operator>=(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) >= 0;
-}
-
-inline bool String16::operator>(const String16& other) const
-{
-    return strzcmp16(mString, size(), other.mString, other.size()) > 0;
-}
-
-inline bool String16::operator<(const char16_t* other) const
-{
-    return strcmp16(mString, other) < 0;
-}
-
-inline bool String16::operator<=(const char16_t* other) const
-{
-    return strcmp16(mString, other) <= 0;
-}
-
-inline bool String16::operator==(const char16_t* other) const
-{
-    return strcmp16(mString, other) == 0;
-}
-
-inline bool String16::operator!=(const char16_t* other) const
-{
-    return strcmp16(mString, other) != 0;
-}
-
-inline bool String16::operator>=(const char16_t* other) const
-{
-    return strcmp16(mString, other) >= 0;
-}
-
-inline bool String16::operator>(const char16_t* other) const
-{
-    return strcmp16(mString, other) > 0;
-}
-
-inline String16::operator const char16_t*() const
-{
-    return mString;
-}
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_STRING16_H
diff --git a/include/utils/String8.h b/include/utils/String8.h
deleted file mode 100644
index 335e7f1..0000000
--- a/include/utils/String8.h
+++ /dev/null
@@ -1,388 +0,0 @@
-/*
- * Copyright (C) 2005 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_STRING8_H
-#define ANDROID_STRING8_H
-
-#include <utils/Errors.h>
-#include <utils/SharedBuffer.h>
-#include <utils/Unicode.h>
-#include <utils/TypeHelpers.h>
-
-#include <string.h> // for strcmp
-#include <stdarg.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-class String16;
-class TextOutput;
-
-//! This is a string holding UTF-8 characters. Does not allow the value more
-// than 0x10FFFF, which is not valid unicode codepoint.
-class String8
-{
-public:
-                                String8();
-                                String8(const String8& o);
-    explicit                    String8(const char* o);
-    explicit                    String8(const char* o, size_t numChars);
-    
-    explicit                    String8(const String16& o);
-    explicit                    String8(const char16_t* o);
-    explicit                    String8(const char16_t* o, size_t numChars);
-    explicit                    String8(const char32_t* o);
-    explicit                    String8(const char32_t* o, size_t numChars);
-                                ~String8();
-
-    static inline const String8 empty();
-
-    static String8              format(const char* fmt, ...) __attribute__((format (printf, 1, 2)));
-    static String8              formatV(const char* fmt, va_list args);
-
-    inline  const char*         string() const;
-    inline  size_t              size() const;
-    inline  size_t              length() const;
-    inline  size_t              bytes() const;
-    inline  bool                isEmpty() const;
-    
-    inline  const SharedBuffer* sharedBuffer() const;
-    
-            void                clear();
-
-            void                setTo(const String8& other);
-            status_t            setTo(const char* other);
-            status_t            setTo(const char* other, size_t numChars);
-            status_t            setTo(const char16_t* other, size_t numChars);
-            status_t            setTo(const char32_t* other,
-                                      size_t length);
-
-            status_t            append(const String8& other);
-            status_t            append(const char* other);
-            status_t            append(const char* other, size_t numChars);
-
-            status_t            appendFormat(const char* fmt, ...)
-                    __attribute__((format (printf, 2, 3)));
-            status_t            appendFormatV(const char* fmt, va_list args);
-
-            // Note that this function takes O(N) time to calculate the value.
-            // No cache value is stored.
-            size_t              getUtf32Length() const;
-            int32_t             getUtf32At(size_t index,
-                                           size_t *next_index) const;
-            void                getUtf32(char32_t* dst) const;
-
-    inline  String8&            operator=(const String8& other);
-    inline  String8&            operator=(const char* other);
-    
-    inline  String8&            operator+=(const String8& other);
-    inline  String8             operator+(const String8& other) const;
-    
-    inline  String8&            operator+=(const char* other);
-    inline  String8             operator+(const char* other) const;
-
-    inline  int                 compare(const String8& other) const;
-
-    inline  bool                operator<(const String8& other) const;
-    inline  bool                operator<=(const String8& other) const;
-    inline  bool                operator==(const String8& other) const;
-    inline  bool                operator!=(const String8& other) const;
-    inline  bool                operator>=(const String8& other) const;
-    inline  bool                operator>(const String8& other) const;
-    
-    inline  bool                operator<(const char* other) const;
-    inline  bool                operator<=(const char* other) const;
-    inline  bool                operator==(const char* other) const;
-    inline  bool                operator!=(const char* other) const;
-    inline  bool                operator>=(const char* other) const;
-    inline  bool                operator>(const char* other) const;
-    
-    inline                      operator const char*() const;
-    
-            char*               lockBuffer(size_t size);
-            void                unlockBuffer();
-            status_t            unlockBuffer(size_t size);
-            
-            // return the index of the first byte of other in this at or after
-            // start, or -1 if not found
-            ssize_t             find(const char* other, size_t start = 0) const;
-
-            void                toLower();
-            void                toLower(size_t start, size_t numChars);
-            void                toUpper();
-            void                toUpper(size_t start, size_t numChars);
-
-    /*
-     * These methods operate on the string as if it were a path name.
-     */
-
-    /*
-     * Set the filename field to a specific value.
-     *
-     * Normalizes the filename, removing a trailing '/' if present.
-     */
-    void setPathName(const char* name);
-    void setPathName(const char* name, size_t numChars);
-
-    /*
-     * Get just the filename component.
-     *
-     * "/tmp/foo/bar.c" --> "bar.c"
-     */
-    String8 getPathLeaf(void) const;
-
-    /*
-     * Remove the last (file name) component, leaving just the directory
-     * name.
-     *
-     * "/tmp/foo/bar.c" --> "/tmp/foo"
-     * "/tmp" --> "" // ????? shouldn't this be "/" ???? XXX
-     * "bar.c" --> ""
-     */
-    String8 getPathDir(void) const;
-
-    /*
-     * Retrieve the front (root dir) component.  Optionally also return the
-     * remaining components.
-     *
-     * "/tmp/foo/bar.c" --> "tmp" (remain = "foo/bar.c")
-     * "/tmp" --> "tmp" (remain = "")
-     * "bar.c" --> "bar.c" (remain = "")
-     */
-    String8 walkPath(String8* outRemains = NULL) const;
-
-    /*
-     * Return the filename extension.  This is the last '.' and any number
-     * of characters that follow it.  The '.' is included in case we
-     * decide to expand our definition of what constitutes an extension.
-     *
-     * "/tmp/foo/bar.c" --> ".c"
-     * "/tmp" --> ""
-     * "/tmp/foo.bar/baz" --> ""
-     * "foo.jpeg" --> ".jpeg"
-     * "foo." --> ""
-     */
-    String8 getPathExtension(void) const;
-
-    /*
-     * Return the path without the extension.  Rules for what constitutes
-     * an extension are described in the comment for getPathExtension().
-     *
-     * "/tmp/foo/bar.c" --> "/tmp/foo/bar"
-     */
-    String8 getBasePath(void) const;
-
-    /*
-     * Add a component to the pathname.  We guarantee that there is
-     * exactly one path separator between the old path and the new.
-     * If there is no existing name, we just copy the new name in.
-     *
-     * If leaf is a fully qualified path (i.e. starts with '/', it
-     * replaces whatever was there before.
-     */
-    String8& appendPath(const char* leaf);
-    String8& appendPath(const String8& leaf)  { return appendPath(leaf.string()); }
-
-    /*
-     * Like appendPath(), but does not affect this string.  Returns a new one instead.
-     */
-    String8 appendPathCopy(const char* leaf) const
-                                             { String8 p(*this); p.appendPath(leaf); return p; }
-    String8 appendPathCopy(const String8& leaf) const { return appendPathCopy(leaf.string()); }
-
-    /*
-     * Converts all separators in this string to /, the default path separator.
-     *
-     * If the default OS separator is backslash, this converts all
-     * backslashes to slashes, in-place. Otherwise it does nothing.
-     * Returns self.
-     */
-    String8& convertToResPath();
-
-private:
-            status_t            real_append(const char* other, size_t numChars);
-            char*               find_extension(void) const;
-
-            const char* mString;
-};
-
-// String8 can be trivially moved using memcpy() because moving does not
-// require any change to the underlying SharedBuffer contents or reference count.
-ANDROID_TRIVIAL_MOVE_TRAIT(String8)
-
-TextOutput& operator<<(TextOutput& to, const String16& val);
-
-// ---------------------------------------------------------------------------
-// No user servicable parts below.
-
-inline int compare_type(const String8& lhs, const String8& rhs)
-{
-    return lhs.compare(rhs);
-}
-
-inline int strictly_order_type(const String8& lhs, const String8& rhs)
-{
-    return compare_type(lhs, rhs) < 0;
-}
-
-inline const String8 String8::empty() {
-    return String8();
-}
-
-inline const char* String8::string() const
-{
-    return mString;
-}
-
-inline size_t String8::length() const
-{
-    return SharedBuffer::sizeFromData(mString)-1;
-}
-
-inline size_t String8::size() const
-{
-    return length();
-}
-
-inline bool String8::isEmpty() const
-{
-    return length() == 0;
-}
-
-inline size_t String8::bytes() const
-{
-    return SharedBuffer::sizeFromData(mString)-1;
-}
-
-inline const SharedBuffer* String8::sharedBuffer() const
-{
-    return SharedBuffer::bufferFromData(mString);
-}
-
-inline String8& String8::operator=(const String8& other)
-{
-    setTo(other);
-    return *this;
-}
-
-inline String8& String8::operator=(const char* other)
-{
-    setTo(other);
-    return *this;
-}
-
-inline String8& String8::operator+=(const String8& other)
-{
-    append(other);
-    return *this;
-}
-
-inline String8 String8::operator+(const String8& other) const
-{
-    String8 tmp(*this);
-    tmp += other;
-    return tmp;
-}
-
-inline String8& String8::operator+=(const char* other)
-{
-    append(other);
-    return *this;
-}
-
-inline String8 String8::operator+(const char* other) const
-{
-    String8 tmp(*this);
-    tmp += other;
-    return tmp;
-}
-
-inline int String8::compare(const String8& other) const
-{
-    return strcmp(mString, other.mString);
-}
-
-inline bool String8::operator<(const String8& other) const
-{
-    return strcmp(mString, other.mString) < 0;
-}
-
-inline bool String8::operator<=(const String8& other) const
-{
-    return strcmp(mString, other.mString) <= 0;
-}
-
-inline bool String8::operator==(const String8& other) const
-{
-    return strcmp(mString, other.mString) == 0;
-}
-
-inline bool String8::operator!=(const String8& other) const
-{
-    return strcmp(mString, other.mString) != 0;
-}
-
-inline bool String8::operator>=(const String8& other) const
-{
-    return strcmp(mString, other.mString) >= 0;
-}
-
-inline bool String8::operator>(const String8& other) const
-{
-    return strcmp(mString, other.mString) > 0;
-}
-
-inline bool String8::operator<(const char* other) const
-{
-    return strcmp(mString, other) < 0;
-}
-
-inline bool String8::operator<=(const char* other) const
-{
-    return strcmp(mString, other) <= 0;
-}
-
-inline bool String8::operator==(const char* other) const
-{
-    return strcmp(mString, other) == 0;
-}
-
-inline bool String8::operator!=(const char* other) const
-{
-    return strcmp(mString, other) != 0;
-}
-
-inline bool String8::operator>=(const char* other) const
-{
-    return strcmp(mString, other) >= 0;
-}
-
-inline bool String8::operator>(const char* other) const
-{
-    return strcmp(mString, other) > 0;
-}
-
-inline String8::operator const char*() const
-{
-    return mString;
-}
-
-}  // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_STRING8_H
diff --git a/include/utils/StringArray.h b/include/utils/StringArray.h
deleted file mode 100644
index c2445871..0000000
--- a/include/utils/StringArray.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2009 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.
- */
-
-//
-// Sortable array of strings.  STL-ish, but STL-free.
-//  
-#ifndef _LIBS_UTILS_STRING_ARRAY_H
-#define _LIBS_UTILS_STRING_ARRAY_H
-
-#include <stdlib.h>
-#include <string.h>
-
-namespace android {
-
-//
-// An expanding array of strings.  Add, get, sort, delete.
-//
-class StringArray {
-public:
-    StringArray();
-    virtual ~StringArray();
-
-    //
-    // Add a string.  A copy of the string is made.
-    //
-    bool push_back(const char* str);
-
-    //
-    // Delete an entry.
-    //
-    void erase(int idx);
-
-    //
-    // Sort the array.
-    //
-    void sort(int (*compare)(const void*, const void*));
-    
-    //
-    // Pass this to the sort routine to do an ascending alphabetical sort.
-    //
-    static int cmpAscendingAlpha(const void* pstr1, const void* pstr2);
-    
-    //
-    // Get the #of items in the array.
-    //
-    inline int size(void) const { return mCurrent; }
-
-    //
-    // Return entry N.
-    // [should use operator[] here]
-    //
-    const char* getEntry(int idx) const {
-        return (unsigned(idx) >= unsigned(mCurrent)) ? NULL : mArray[idx];
-    }
-
-    //
-    // Set entry N to specified string.
-    // [should use operator[] here]
-    //
-    void setEntry(int idx, const char* str);
-
-private:
-    int     mMax;
-    int     mCurrent;
-    char**  mArray;
-};
-
-}; // namespace android
-
-#endif // _LIBS_UTILS_STRING_ARRAY_H
diff --git a/include/utils/StrongPointer.h b/include/utils/StrongPointer.h
deleted file mode 100644
index 49fa3a8..0000000
--- a/include/utils/StrongPointer.h
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Copyright (C) 2005 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_STRONG_POINTER_H
-#define ANDROID_STRONG_POINTER_H
-
-#include <cutils/atomic.h>
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <stdlib.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-
-class TextOutput;
-TextOutput& printStrongPointer(TextOutput& to, const void* val);
-
-template<typename T> class wp;
-
-// ---------------------------------------------------------------------------
-
-#define COMPARE(_op_)                                           \
-inline bool operator _op_ (const sp<T>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-inline bool operator _op_ (const T* o) const {                  \
-    return m_ptr _op_ o;                                        \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const sp<U>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const U* o) const {                  \
-    return m_ptr _op_ o;                                        \
-}                                                               \
-inline bool operator _op_ (const wp<T>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}                                                               \
-template<typename U>                                            \
-inline bool operator _op_ (const wp<U>& o) const {              \
-    return m_ptr _op_ o.m_ptr;                                  \
-}
-
-// ---------------------------------------------------------------------------
-
-template <typename T>
-class sp
-{
-public:
-    inline sp() : m_ptr(0) { }
-
-    sp(T* other);
-    sp(const sp<T>& other);
-    template<typename U> sp(U* other);
-    template<typename U> sp(const sp<U>& other);
-
-    ~sp();
-
-    // Assignment
-
-    sp& operator = (T* other);
-    sp& operator = (const sp<T>& other);
-
-    template<typename U> sp& operator = (const sp<U>& other);
-    template<typename U> sp& operator = (U* other);
-
-    //! Special optimization for use by ProcessState (and nobody else).
-    void force_set(T* other);
-
-    // Reset
-
-    void clear();
-
-    // Accessors
-
-    inline  T&      operator* () const  { return *m_ptr; }
-    inline  T*      operator-> () const { return m_ptr;  }
-    inline  T*      get() const         { return m_ptr; }
-
-    // Operators
-
-    COMPARE(==)
-    COMPARE(!=)
-    COMPARE(>)
-    COMPARE(<)
-    COMPARE(<=)
-    COMPARE(>=)
-
-private:    
-    template<typename Y> friend class sp;
-    template<typename Y> friend class wp;
-    void set_pointer(T* ptr);
-    T* m_ptr;
-};
-
-#undef COMPARE
-
-template <typename T>
-TextOutput& operator<<(TextOutput& to, const sp<T>& val);
-
-// ---------------------------------------------------------------------------
-// No user serviceable parts below here.
-
-template<typename T>
-sp<T>::sp(T* other)
-: m_ptr(other)
-  {
-    if (other) other->incStrong(this);
-  }
-
-template<typename T>
-sp<T>::sp(const sp<T>& other)
-: m_ptr(other.m_ptr)
-  {
-    if (m_ptr) m_ptr->incStrong(this);
-  }
-
-template<typename T> template<typename U>
-sp<T>::sp(U* other) : m_ptr(other)
-{
-    if (other) ((T*)other)->incStrong(this);
-}
-
-template<typename T> template<typename U>
-sp<T>::sp(const sp<U>& other)
-: m_ptr(other.m_ptr)
-  {
-    if (m_ptr) m_ptr->incStrong(this);
-  }
-
-template<typename T>
-sp<T>::~sp()
-{
-    if (m_ptr) m_ptr->decStrong(this);
-}
-
-template<typename T>
-sp<T>& sp<T>::operator = (const sp<T>& other) {
-    T* otherPtr(other.m_ptr);
-    if (otherPtr) otherPtr->incStrong(this);
-    if (m_ptr) m_ptr->decStrong(this);
-    m_ptr = otherPtr;
-    return *this;
-}
-
-template<typename T>
-sp<T>& sp<T>::operator = (T* other)
-{
-    if (other) other->incStrong(this);
-    if (m_ptr) m_ptr->decStrong(this);
-    m_ptr = other;
-    return *this;
-}
-
-template<typename T> template<typename U>
-sp<T>& sp<T>::operator = (const sp<U>& other)
-{
-    T* otherPtr(other.m_ptr);
-    if (otherPtr) otherPtr->incStrong(this);
-    if (m_ptr) m_ptr->decStrong(this);
-    m_ptr = otherPtr;
-    return *this;
-}
-
-template<typename T> template<typename U>
-sp<T>& sp<T>::operator = (U* other)
-{
-    if (other) ((T*)other)->incStrong(this);
-    if (m_ptr) m_ptr->decStrong(this);
-    m_ptr = other;
-    return *this;
-}
-
-template<typename T>    
-void sp<T>::force_set(T* other)
-{
-    other->forceIncStrong(this);
-    m_ptr = other;
-}
-
-template<typename T>
-void sp<T>::clear()
-{
-    if (m_ptr) {
-        m_ptr->decStrong(this);
-        m_ptr = 0;
-    }
-}
-
-template<typename T>
-void sp<T>::set_pointer(T* ptr) {
-    m_ptr = ptr;
-}
-
-template <typename T>
-inline TextOutput& operator<<(TextOutput& to, const sp<T>& val)
-{
-    return printStrongPointer(to, val.get());
-}
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-
-#endif // ANDROID_STRONG_POINTER_H
diff --git a/include/utils/SystemClock.h b/include/utils/SystemClock.h
deleted file mode 100644
index d75264c..0000000
--- a/include/utils/SystemClock.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2008 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_UTILS_SYSTEMCLOCK_H
-#define ANDROID_UTILS_SYSTEMCLOCK_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-namespace android {
-
-int setCurrentTimeMillis(int64_t millis);
-int64_t uptimeMillis();
-int64_t elapsedRealtime();
-int64_t elapsedRealtimeNano();
-
-}; // namespace android
-
-#endif // ANDROID_UTILS_SYSTEMCLOCK_H
-
diff --git a/include/utils/Thread.h b/include/utils/Thread.h
deleted file mode 100644
index df30611..0000000
--- a/include/utils/Thread.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2007 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 _LIBS_UTILS_THREAD_H
-#define _LIBS_UTILS_THREAD_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <time.h>
-
-#if defined(HAVE_PTHREADS)
-# include <pthread.h>
-#endif
-
-#include <utils/Condition.h>
-#include <utils/Errors.h>
-#include <utils/Mutex.h>
-#include <utils/RefBase.h>
-#include <utils/Timers.h>
-#include <utils/ThreadDefs.h>
-
-// ---------------------------------------------------------------------------
-namespace android {
-// ---------------------------------------------------------------------------
-
-class Thread : virtual public RefBase
-{
-public:
-    // Create a Thread object, but doesn't create or start the associated
-    // thread. See the run() method.
-                        Thread(bool canCallJava = true);
-    virtual             ~Thread();
-
-    // Start the thread in threadLoop() which needs to be implemented.
-    virtual status_t    run(    const char* name = 0,
-                                int32_t priority = PRIORITY_DEFAULT,
-                                size_t stack = 0);
-    
-    // Ask this object's thread to exit. This function is asynchronous, when the
-    // function returns the thread might still be running. Of course, this
-    // function can be called from a different thread.
-    virtual void        requestExit();
-
-    // Good place to do one-time initializations
-    virtual status_t    readyToRun();
-    
-    // Call requestExit() and wait until this object's thread exits.
-    // BE VERY CAREFUL of deadlocks. In particular, it would be silly to call
-    // this function from this object's thread. Will return WOULD_BLOCK in
-    // that case.
-            status_t    requestExitAndWait();
-
-    // Wait until this object's thread exits. Returns immediately if not yet running.
-    // Do not call from this object's thread; will return WOULD_BLOCK in that case.
-            status_t    join();
-
-    // Indicates whether this thread is running or not.
-            bool        isRunning() const;
-
-#ifdef HAVE_ANDROID_OS
-    // Return the thread's kernel ID, same as the thread itself calling gettid() or
-    // androidGetTid(), or -1 if the thread is not running.
-            pid_t       getTid() const;
-#endif
-
-protected:
-    // exitPending() returns true if requestExit() has been called.
-            bool        exitPending() const;
-    
-private:
-    // Derived class must implement threadLoop(). The thread starts its life
-    // here. There are two ways of using the Thread object:
-    // 1) loop: if threadLoop() returns true, it will be called again if
-    //          requestExit() wasn't called.
-    // 2) once: if threadLoop() returns false, the thread will exit upon return.
-    virtual bool        threadLoop() = 0;
-
-private:
-    Thread& operator=(const Thread&);
-    static  int             _threadLoop(void* user);
-    const   bool            mCanCallJava;
-    // always hold mLock when reading or writing
-            thread_id_t     mThread;
-    mutable Mutex           mLock;
-            Condition       mThreadExitedCondition;
-            status_t        mStatus;
-    // note that all accesses of mExitPending and mRunning need to hold mLock
-    volatile bool           mExitPending;
-    volatile bool           mRunning;
-            sp<Thread>      mHoldSelf;
-#ifdef HAVE_ANDROID_OS
-    // legacy for debugging, not used by getTid() as it is set by the child thread
-    // and so is not initialized until the child reaches that point
-            pid_t           mTid;
-#endif
-};
-
-
-}; // namespace android
-
-// ---------------------------------------------------------------------------
-#endif // _LIBS_UTILS_THREAD_H
-// ---------------------------------------------------------------------------
diff --git a/include/utils/ThreadDefs.h b/include/utils/ThreadDefs.h
deleted file mode 100644
index a8f8eb3..0000000
--- a/include/utils/ThreadDefs.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2007 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 _LIBS_UTILS_THREAD_DEFS_H
-#define _LIBS_UTILS_THREAD_DEFS_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <system/graphics.h>
-
-// ---------------------------------------------------------------------------
-// C API
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef void* android_thread_id_t;
-
-typedef int (*android_thread_func_t)(void*);
-
-enum {
-    /*
-     * ***********************************************
-     * ** Keep in sync with android.os.Process.java **
-     * ***********************************************
-     * 
-     * This maps directly to the "nice" priorities we use in Android.
-     * A thread priority should be chosen inverse-proportionally to
-     * the amount of work the thread is expected to do. The more work
-     * a thread will do, the less favorable priority it should get so that 
-     * it doesn't starve the system. Threads not behaving properly might
-     * be "punished" by the kernel.
-     * Use the levels below when appropriate. Intermediate values are
-     * acceptable, preferably use the {MORE|LESS}_FAVORABLE constants below.
-     */
-    ANDROID_PRIORITY_LOWEST         =  19,
-
-    /* use for background tasks */
-    ANDROID_PRIORITY_BACKGROUND     =  10,
-    
-    /* most threads run at normal priority */
-    ANDROID_PRIORITY_NORMAL         =   0,
-    
-    /* threads currently running a UI that the user is interacting with */
-    ANDROID_PRIORITY_FOREGROUND     =  -2,
-
-    /* the main UI thread has a slightly more favorable priority */
-    ANDROID_PRIORITY_DISPLAY        =  -4,
-    
-    /* ui service treads might want to run at a urgent display (uncommon) */
-    ANDROID_PRIORITY_URGENT_DISPLAY =  HAL_PRIORITY_URGENT_DISPLAY,
-    
-    /* all normal audio threads */
-    ANDROID_PRIORITY_AUDIO          = -16,
-    
-    /* service audio threads (uncommon) */
-    ANDROID_PRIORITY_URGENT_AUDIO   = -19,
-
-    /* should never be used in practice. regular process might not 
-     * be allowed to use this level */
-    ANDROID_PRIORITY_HIGHEST        = -20,
-
-    ANDROID_PRIORITY_DEFAULT        = ANDROID_PRIORITY_NORMAL,
-    ANDROID_PRIORITY_MORE_FAVORABLE = -1,
-    ANDROID_PRIORITY_LESS_FAVORABLE = +1,
-};
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
-// ---------------------------------------------------------------------------
-// C++ API
-#ifdef __cplusplus
-namespace android {
-// ---------------------------------------------------------------------------
-
-typedef android_thread_id_t thread_id_t;
-typedef android_thread_func_t thread_func_t;
-
-enum {
-    PRIORITY_LOWEST         = ANDROID_PRIORITY_LOWEST,
-    PRIORITY_BACKGROUND     = ANDROID_PRIORITY_BACKGROUND,
-    PRIORITY_NORMAL         = ANDROID_PRIORITY_NORMAL,
-    PRIORITY_FOREGROUND     = ANDROID_PRIORITY_FOREGROUND,
-    PRIORITY_DISPLAY        = ANDROID_PRIORITY_DISPLAY,
-    PRIORITY_URGENT_DISPLAY = ANDROID_PRIORITY_URGENT_DISPLAY,
-    PRIORITY_AUDIO          = ANDROID_PRIORITY_AUDIO,
-    PRIORITY_URGENT_AUDIO   = ANDROID_PRIORITY_URGENT_AUDIO,
-    PRIORITY_HIGHEST        = ANDROID_PRIORITY_HIGHEST,
-    PRIORITY_DEFAULT        = ANDROID_PRIORITY_DEFAULT,
-    PRIORITY_MORE_FAVORABLE = ANDROID_PRIORITY_MORE_FAVORABLE,
-    PRIORITY_LESS_FAVORABLE = ANDROID_PRIORITY_LESS_FAVORABLE,
-};
-
-// ---------------------------------------------------------------------------
-}; // namespace android
-#endif  // __cplusplus
-// ---------------------------------------------------------------------------
-
-
-#endif // _LIBS_UTILS_THREAD_DEFS_H
diff --git a/include/utils/Timers.h b/include/utils/Timers.h
deleted file mode 100644
index 92f66c9..0000000
--- a/include/utils/Timers.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2005 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.
- */
-
-//
-// Timer functions.
-//
-#ifndef _LIBS_UTILS_TIMERS_H
-#define _LIBS_UTILS_TIMERS_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <sys/time.h>
-
-// ------------------------------------------------------------------
-// C API
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef int64_t nsecs_t;       // nano-seconds
-
-static inline nsecs_t seconds_to_nanoseconds(nsecs_t secs)
-{
-    return secs*1000000000;
-}
-
-static inline nsecs_t milliseconds_to_nanoseconds(nsecs_t secs)
-{
-    return secs*1000000;
-}
-
-static inline nsecs_t microseconds_to_nanoseconds(nsecs_t secs)
-{
-    return secs*1000;
-}
-
-static inline nsecs_t nanoseconds_to_seconds(nsecs_t secs)
-{
-    return secs/1000000000;
-}
-
-static inline nsecs_t nanoseconds_to_milliseconds(nsecs_t secs)
-{
-    return secs/1000000;
-}
-
-static inline nsecs_t nanoseconds_to_microseconds(nsecs_t secs)
-{
-    return secs/1000;
-}
-
-static inline nsecs_t s2ns(nsecs_t v)  {return seconds_to_nanoseconds(v);}
-static inline nsecs_t ms2ns(nsecs_t v) {return milliseconds_to_nanoseconds(v);}
-static inline nsecs_t us2ns(nsecs_t v) {return microseconds_to_nanoseconds(v);}
-static inline nsecs_t ns2s(nsecs_t v)  {return nanoseconds_to_seconds(v);}
-static inline nsecs_t ns2ms(nsecs_t v) {return nanoseconds_to_milliseconds(v);}
-static inline nsecs_t ns2us(nsecs_t v) {return nanoseconds_to_microseconds(v);}
-
-static inline nsecs_t seconds(nsecs_t v)      { return s2ns(v); }
-static inline nsecs_t milliseconds(nsecs_t v) { return ms2ns(v); }
-static inline nsecs_t microseconds(nsecs_t v) { return us2ns(v); }
-
-enum {
-    SYSTEM_TIME_REALTIME = 0,  // system-wide realtime clock
-    SYSTEM_TIME_MONOTONIC = 1, // monotonic time since unspecified starting point
-    SYSTEM_TIME_PROCESS = 2,   // high-resolution per-process clock
-    SYSTEM_TIME_THREAD = 3,    // high-resolution per-thread clock
-    SYSTEM_TIME_BOOTTIME = 4   // same as SYSTEM_TIME_MONOTONIC, but including CPU suspend time
-};
-
-// return the system-time according to the specified clock
-#ifdef __cplusplus
-nsecs_t systemTime(int clock = SYSTEM_TIME_MONOTONIC);
-#else
-nsecs_t systemTime(int clock);
-#endif // def __cplusplus
-
-/**
- * Returns the number of milliseconds to wait between the reference time and the timeout time.
- * If the timeout is in the past relative to the reference time, returns 0.
- * If the timeout is more than INT_MAX milliseconds in the future relative to the reference time,
- * such as when timeoutTime == LLONG_MAX, returns -1 to indicate an infinite timeout delay.
- * Otherwise, returns the difference between the reference time and timeout time
- * rounded up to the next millisecond.
- */
-int toMillisecondTimeoutDelay(nsecs_t referenceTime, nsecs_t timeoutTime);
-
-#ifdef __cplusplus
-} // extern "C"
-#endif
-
-// ------------------------------------------------------------------
-// C++ API
-
-#ifdef __cplusplus
-
-namespace android {
-/*
- * Time the duration of something.
- *
- * Includes some timeval manipulation functions.
- */
-class DurationTimer {
-public:
-    DurationTimer() {}
-    ~DurationTimer() {}
-
-    // Start the timer.
-    void start();
-    // Stop the timer.
-    void stop();
-    // Get the duration in microseconds.
-    long long durationUsecs() const;
-
-    // Subtract two timevals.  Returns the difference (ptv1-ptv2) in
-    // microseconds.
-    static long long subtractTimevals(const struct timeval* ptv1,
-        const struct timeval* ptv2);
-
-    // Add the specified amount of time to the timeval.
-    static void addToTimeval(struct timeval* ptv, long usec);
-
-private:
-    struct timeval  mStartWhen;
-    struct timeval  mStopWhen;
-};
-
-}; // android
-#endif // def __cplusplus
-
-#endif // _LIBS_UTILS_TIMERS_H
diff --git a/include/utils/Tokenizer.h b/include/utils/Tokenizer.h
deleted file mode 100644
index bb25f37..0000000
--- a/include/utils/Tokenizer.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 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.
- */
-
-#ifndef _UTILS_TOKENIZER_H
-#define _UTILS_TOKENIZER_H
-
-#include <assert.h>
-#include <utils/Errors.h>
-#include <utils/FileMap.h>
-#include <utils/String8.h>
-
-namespace android {
-
-/**
- * A simple tokenizer for loading and parsing ASCII text files line by line.
- */
-class Tokenizer {
-    Tokenizer(const String8& filename, FileMap* fileMap, char* buffer,
-            bool ownBuffer, size_t length);
-
-public:
-    ~Tokenizer();
-
-    /**
-     * Opens a file and maps it into memory.
-     *
-     * Returns NO_ERROR and a tokenizer for the file, if successful.
-     * Otherwise returns an error and sets outTokenizer to NULL.
-     */
-    static status_t open(const String8& filename, Tokenizer** outTokenizer);
-
-    /**
-     * Prepares to tokenize the contents of a string.
-     *
-     * Returns NO_ERROR and a tokenizer for the string, if successful.
-     * Otherwise returns an error and sets outTokenizer to NULL.
-     */
-    static status_t fromContents(const String8& filename,
-            const char* contents, Tokenizer** outTokenizer);
-
-    /**
-     * Returns true if at the end of the file.
-     */
-    inline bool isEof() const { return mCurrent == getEnd(); }
-
-    /**
-     * Returns true if at the end of the line or end of the file.
-     */
-    inline bool isEol() const { return isEof() || *mCurrent == '\n'; }
-
-    /**
-     * Gets the name of the file.
-     */
-    inline String8 getFilename() const { return mFilename; }
-
-    /**
-     * Gets a 1-based line number index for the current position.
-     */
-    inline int32_t getLineNumber() const { return mLineNumber; }
-
-    /**
-     * Formats a location string consisting of the filename and current line number.
-     * Returns a string like "MyFile.txt:33".
-     */
-    String8 getLocation() const;
-
-    /**
-     * Gets the character at the current position.
-     * Returns null at end of file.
-     */
-    inline char peekChar() const { return isEof() ? '\0' : *mCurrent; }
-
-    /**
-     * Gets the remainder of the current line as a string, excluding the newline character.
-     */
-    String8 peekRemainderOfLine() const;
-
-    /**
-     * Gets the character at the current position and advances past it.
-     * Returns null at end of file.
-     */
-    inline char nextChar() { return isEof() ? '\0' : *(mCurrent++); }
-
-    /**
-     * Gets the next token on this line stopping at the specified delimiters
-     * or the end of the line whichever comes first and advances past it.
-     * Also stops at embedded nulls.
-     * Returns the token or an empty string if the current character is a delimiter
-     * or is at the end of the line.
-     */
-    String8 nextToken(const char* delimiters);
-
-    /**
-     * Advances to the next line.
-     * Does nothing if already at the end of the file.
-     */
-    void nextLine();
-
-    /**
-     * Skips over the specified delimiters in the line.
-     * Also skips embedded nulls.
-     */
-    void skipDelimiters(const char* delimiters);
-
-private:
-    Tokenizer(const Tokenizer& other); // not copyable
-
-    String8 mFilename;
-    FileMap* mFileMap;
-    char* mBuffer;
-    bool mOwnBuffer;
-    size_t mLength;
-
-    const char* mCurrent;
-    int32_t mLineNumber;
-
-    inline const char* getEnd() const { return mBuffer + mLength; }
-
-};
-
-} // namespace android
-
-#endif // _UTILS_TOKENIZER_H
diff --git a/include/utils/Trace.h b/include/utils/Trace.h
deleted file mode 100644
index 49578c4..0000000
--- a/include/utils/Trace.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2012 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_TRACE_H
-#define ANDROID_TRACE_H
-
-#include <fcntl.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <cutils/compiler.h>
-#include <utils/threads.h>
-#include <cutils/trace.h>
-
-// See <cutils/trace.h> for more ATRACE_* macros.
-
-// ATRACE_NAME traces the beginning and end of the current scope.  To trace
-// the correct start and end times this macro should be declared first in the
-// scope body.
-#define ATRACE_NAME(name) android::ScopedTrace ___tracer(ATRACE_TAG, name)
-// ATRACE_CALL is an ATRACE_NAME that uses the current function name.
-#define ATRACE_CALL() ATRACE_NAME(__FUNCTION__)
-
-namespace android {
-
-class ScopedTrace {
-public:
-inline ScopedTrace(uint64_t tag, const char* name)
-    : mTag(tag) {
-    atrace_begin(mTag,name);
-}
-
-inline ~ScopedTrace() {
-    atrace_end(mTag);
-}
-
-private:
-    uint64_t mTag;
-};
-
-}; // namespace android
-
-#endif // ANDROID_TRACE_H
diff --git a/include/utils/TypeHelpers.h b/include/utils/TypeHelpers.h
deleted file mode 100644
index 13c9081..0000000
--- a/include/utils/TypeHelpers.h
+++ /dev/null
@@ -1,302 +0,0 @@
-/*
- * Copyright (C) 2005 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_TYPE_HELPERS_H
-#define ANDROID_TYPE_HELPERS_H
-
-#include <new>
-#include <stdint.h>
-#include <string.h>
-#include <sys/types.h>
-
-// ---------------------------------------------------------------------------
-
-namespace android {
-
-/*
- * Types traits
- */
-
-template <typename T> struct trait_trivial_ctor { enum { value = false }; };
-template <typename T> struct trait_trivial_dtor { enum { value = false }; };
-template <typename T> struct trait_trivial_copy { enum { value = false }; };
-template <typename T> struct trait_trivial_move { enum { value = false }; };
-template <typename T> struct trait_pointer      { enum { value = false }; };    
-template <typename T> struct trait_pointer<T*>  { enum { value = true }; };
-
-template <typename TYPE>
-struct traits {
-    enum {
-        // whether this type is a pointer
-        is_pointer          = trait_pointer<TYPE>::value,
-        // whether this type's constructor is a no-op
-        has_trivial_ctor    = is_pointer || trait_trivial_ctor<TYPE>::value,
-        // whether this type's destructor is a no-op
-        has_trivial_dtor    = is_pointer || trait_trivial_dtor<TYPE>::value,
-        // whether this type type can be copy-constructed with memcpy
-        has_trivial_copy    = is_pointer || trait_trivial_co