Merge "utils: fix warnings for unused parameters"
diff --git a/cmds/atrace/Android.mk b/cmds/atrace/Android.mk
index 12526d0..028ca8f 100644
--- a/cmds/atrace/Android.mk
+++ b/cmds/atrace/Android.mk
@@ -3,15 +3,18 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= atrace.c
+LOCAL_SRC_FILES:= atrace.cpp
 
 LOCAL_C_INCLUDES += external/zlib
-LOCAL_CFLAGS += -std=c99
 
 LOCAL_MODULE:= atrace
 
 LOCAL_MODULE_TAGS:= optional
 
-LOCAL_SHARED_LIBRARIES := libz
+LOCAL_SHARED_LIBRARIES := \
+    libbinder \
+    libcutils \
+    libutils \
+    libz \
 
 include $(BUILD_EXECUTABLE)
diff --git a/cmds/atrace/atrace.c b/cmds/atrace/atrace.c
deleted file mode 100644
index 64f13e4..0000000
--- a/cmds/atrace/atrace.c
+++ /dev/null
@@ -1,643 +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.
- */
-
-#include <errno.h>
-#include <fcntl.h>
-#include <getopt.h>
-#include <signal.h>
-#include <stdarg.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/sendfile.h>
-#include <time.h>
-#include <zlib.h>
-
-#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
-
-/* Command line options */
-static int g_traceDurationSeconds = 5;
-static bool g_traceSchedSwitch = false;
-static bool g_traceFrequency = false;
-static bool g_traceBusUtilization = false;
-static bool g_traceCpuIdle = false;
-static bool g_traceDisk = false;
-static bool g_traceGovernorLoad = false;
-static bool g_traceSync = false;
-static bool g_traceWorkqueue = false;
-static bool g_traceOverwrite = false;
-static int g_traceBufferSizeKB = 2048;
-static bool g_compress = false;
-static bool g_nohup = false;
-static int g_initialSleepSecs = 0;
-
-/* Global state */
-static bool g_traceAborted = false;
-
-/* Sys file paths */
-static const char* k_traceClockPath =
-    "/sys/kernel/debug/tracing/trace_clock";
-
-static const char* k_traceBufferSizePath =
-    "/sys/kernel/debug/tracing/buffer_size_kb";
-
-static const char* k_tracingOverwriteEnablePath =
-    "/sys/kernel/debug/tracing/options/overwrite";
-
-static const char* k_schedSwitchEnablePath =
-    "/sys/kernel/debug/tracing/events/sched/sched_switch/enable";
-
-static const char* k_schedWakeupEnablePath =
-    "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable";
-
-static const char* k_memoryBusEnablePath =
-    "/sys/kernel/debug/tracing/events/memory_bus/enable";
-
-static const char* k_cpuFreqEnablePath =
-    "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable";
-
-static const char *k_clockSetRateEnablePath =
-    "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable";
-
-static const char* k_cpuIdleEnablePath =
-    "/sys/kernel/debug/tracing/events/power/cpu_idle/enable";
-
-static const char* k_governorLoadEnablePath =
-    "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable";
-
-static const char* k_syncEnablePath =
-    "/sys/kernel/debug/tracing/events/sync/enable";
-
-static const char* k_workqueueEnablePath =
-    "/sys/kernel/debug/tracing/events/workqueue/enable";
-
-static const char* k_diskEnablePaths[] = {
-        "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable",
-        "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable",
-        "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable",
-        "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable",
-};
-
-static const char* k_tracingOnPath =
-    "/sys/kernel/debug/tracing/tracing_on";
-
-static const char* k_tracePath =
-    "/sys/kernel/debug/tracing/trace";
-
-static const char* k_traceMarkerPath =
-    "/sys/kernel/debug/tracing/trace_marker";
-
-// Check whether a file exists.
-static bool fileExists(const char* filename) {
-    return access(filename, F_OK) != -1;
-}
-
-// Write a string to a file, returning true if the write was successful.
-bool writeStr(const char* filename, const char* str)
-{
-    int fd = open(filename, O_WRONLY);
-    if (fd == -1) {
-        fprintf(stderr, "error opening %s: %s (%d)\n", filename,
-                strerror(errno), errno);
-        return false;
-    }
-
-    bool ok = true;
-    ssize_t len = strlen(str);
-    if (write(fd, str, len) != len) {
-        fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
-                strerror(errno), errno);
-        ok = false;
-    }
-
-    close(fd);
-
-    return ok;
-}
-
-// Enable or disable a kernel option by writing a "1" or a "0" into a /sys file.
-static bool setKernelOptionEnable(const char* filename, bool enable)
-{
-    return writeStr(filename, enable ? "1" : "0");
-}
-
-// Enable or disable a collection of kernel options by writing a "1" or a "0" into each /sys file.
-static bool setMultipleKernelOptionsEnable(const char** filenames, size_t count, bool enable)
-{
-    bool result = true;
-    for (size_t i = 0; i < count; i++) {
-        result &= setKernelOptionEnable(filenames[i], enable);
-    }
-    return result;
-}
-
-// Enable or disable overwriting of the kernel trace buffers.  Disabling this
-// will cause tracing to stop once the trace buffers have filled up.
-static bool setTraceOverwriteEnable(bool enable)
-{
-    return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
-}
-
-// Enable or disable tracing of the kernel scheduler switching.
-static bool setSchedSwitchTracingEnable(bool enable)
-{
-    bool ok = true;
-    ok &= setKernelOptionEnable(k_schedSwitchEnablePath, enable);
-    ok &= setKernelOptionEnable(k_schedWakeupEnablePath, enable);
-    return ok;
-}
-
-// Enable or disable tracing of the Bus utilization.
-static bool setBusUtilizationTracingEnable(bool enable)
-{
-    bool ok = true, oneSet = false;
-    // these can be platform specific so make sure that at least
-    // one succeeds.
-    if (fileExists(k_memoryBusEnablePath)) {
-        ok &= setKernelOptionEnable(k_memoryBusEnablePath, enable);
-        oneSet |= ok;
-    }
-    return ok && (oneSet || !enable);
-}
-
-// Enable or disable tracing of the CPU clock frequency.
-static bool setFrequencyTracingEnable(bool enable)
-{
-    bool ok = true;
-    ok &= setKernelOptionEnable(k_cpuFreqEnablePath, enable);
-    if (fileExists(k_clockSetRateEnablePath)) {
-        ok &= setKernelOptionEnable(k_clockSetRateEnablePath, enable);
-    }
-    return ok;
-}
-
-// Enable or disable tracing of CPU idle events.
-static bool setCpuIdleTracingEnable(bool enable)
-{
-    return setKernelOptionEnable(k_cpuIdleEnablePath, enable);
-}
-
-// Enable or disable tracing of the interactive CPU frequency governor's idea of
-// the CPU load.
-static bool setGovernorLoadTracingEnable(bool enable)
-{
-    bool ok = true;
-    if (fileExists(k_governorLoadEnablePath) || enable) {
-        ok &= setKernelOptionEnable(k_governorLoadEnablePath, enable);
-    }
-    return ok;
-}
-
-// Enable or disable tracing of sync timelines and waits.
-static bool setSyncTracingEnabled(bool enable)
-{
-    bool ok = true;
-    if (fileExists(k_syncEnablePath) || enable) {
-        ok &= setKernelOptionEnable(k_syncEnablePath, enable);
-    }
-    return ok;
-}
-
-// Enable or disable tracing of the kernel workqueues.
-static bool setWorkqueueTracingEnabled(bool enable)
-{
-    return setKernelOptionEnable(k_workqueueEnablePath, enable);
-}
-
-// Enable or disable tracing of disk I/O.
-static bool setDiskTracingEnabled(bool enable)
-{
-    return setMultipleKernelOptionsEnable(k_diskEnablePaths, NELEM(k_diskEnablePaths), enable);
-}
-
-// Enable or disable kernel tracing.
-static bool setTracingEnabled(bool enable)
-{
-    return setKernelOptionEnable(k_tracingOnPath, enable);
-}
-
-// Clear the contents of the kernel trace.
-static bool clearTrace()
-{
-    int traceFD = creat(k_tracePath, 0);
-    if (traceFD == -1) {
-        fprintf(stderr, "error truncating %s: %s (%d)\n", k_tracePath,
-                strerror(errno), errno);
-        return false;
-    }
-
-    close(traceFD);
-
-    return true;
-}
-
-// Set the size of the kernel's trace buffer in kilobytes.
-static bool setTraceBufferSizeKB(int size)
-{
-    char str[32] = "1";
-    int len;
-    if (size < 1) {
-        size = 1;
-    }
-    snprintf(str, 32, "%d", size);
-    return writeStr(k_traceBufferSizePath, str);
-}
-
-// Enable or disable the kernel's use of the global clock.  Disabling the global
-// clock will result in the kernel using a per-CPU local clock.
-static bool setGlobalClockEnable(bool enable)
-{
-    return writeStr(k_traceClockPath, enable ? "global" : "local");
-}
-
-// Enable tracing in the kernel.
-static bool startTrace(bool isRoot)
-{
-    bool ok = true;
-
-    // Set up the tracing options that don't require root.
-    ok &= setTraceOverwriteEnable(g_traceOverwrite);
-    ok &= setSchedSwitchTracingEnable(g_traceSchedSwitch);
-    ok &= setFrequencyTracingEnable(g_traceFrequency);
-    ok &= setCpuIdleTracingEnable(g_traceCpuIdle);
-    ok &= setGovernorLoadTracingEnable(g_traceGovernorLoad);
-    ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
-    ok &= setGlobalClockEnable(true);
-
-    // Set up the tracing options that do require root.  The options that
-    // require root should have errored out earlier if we're not running as
-    // root.
-    if (isRoot) {
-        ok &= setBusUtilizationTracingEnable(g_traceBusUtilization);
-        ok &= setSyncTracingEnabled(g_traceSync);
-        ok &= setWorkqueueTracingEnabled(g_traceWorkqueue);
-        ok &= setDiskTracingEnabled(g_traceDisk);
-    }
-
-    // Enable tracing.
-    ok &= setTracingEnabled(true);
-
-    if (!ok) {
-        fprintf(stderr, "error: unable to start trace\n");
-    }
-
-    return ok;
-}
-
-// Disable tracing in the kernel.
-static void stopTrace(bool isRoot)
-{
-    // Disable tracing.
-    setTracingEnabled(false);
-
-    // Set the options back to their defaults.
-    setTraceOverwriteEnable(true);
-    setSchedSwitchTracingEnable(false);
-    setFrequencyTracingEnable(false);
-    setGovernorLoadTracingEnable(false);
-    setGlobalClockEnable(false);
-
-    if (isRoot) {
-        setBusUtilizationTracingEnable(false);
-        setSyncTracingEnabled(false);
-        setWorkqueueTracingEnabled(false);
-        setDiskTracingEnabled(false);
-    }
-
-    // Note that we can't reset the trace buffer size here because that would
-    // clear the trace before we've read it.
-}
-
-// Read the current kernel trace and write it to stdout.
-static void dumpTrace()
-{
-    int traceFD = open(k_tracePath, O_RDWR);
-    if (traceFD == -1) {
-        fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
-                strerror(errno), errno);
-        return;
-    }
-
-    if (g_compress) {
-        z_stream zs;
-        uint8_t *in, *out;
-        int result, flush;
-
-        bzero(&zs, sizeof(zs));
-        result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
-        if (result != Z_OK) {
-            fprintf(stderr, "error initializing zlib: %d\n", result);
-            close(traceFD);
-            return;
-        }
-
-        const size_t bufSize = 64*1024;
-        in = (uint8_t*)malloc(bufSize);
-        out = (uint8_t*)malloc(bufSize);
-        flush = Z_NO_FLUSH;
-
-        zs.next_out = out;
-        zs.avail_out = bufSize;
-
-        do {
-
-            if (zs.avail_in == 0) {
-                // More input is needed.
-                result = read(traceFD, in, bufSize);
-                if (result < 0) {
-                    fprintf(stderr, "error reading trace: %s (%d)\n",
-                            strerror(errno), errno);
-                    result = Z_STREAM_END;
-                    break;
-                } else if (result == 0) {
-                    flush = Z_FINISH;
-                } else {
-                    zs.next_in = in;
-                    zs.avail_in = result;
-                }
-            }
-
-            if (zs.avail_out == 0) {
-                // Need to write the output.
-                result = write(STDOUT_FILENO, out, bufSize);
-                if ((size_t)result < bufSize) {
-                    fprintf(stderr, "error writing deflated trace: %s (%d)\n",
-                            strerror(errno), errno);
-                    result = Z_STREAM_END; // skip deflate error message
-                    zs.avail_out = bufSize; // skip the final write
-                    break;
-                }
-                zs.next_out = out;
-                zs.avail_out = bufSize;
-            }
-
-        } while ((result = deflate(&zs, flush)) == Z_OK);
-
-        if (result != Z_STREAM_END) {
-            fprintf(stderr, "error deflating trace: %s\n", zs.msg);
-        }
-
-        if (zs.avail_out < bufSize) {
-            size_t bytes = bufSize - zs.avail_out;
-            result = write(STDOUT_FILENO, out, bytes);
-            if ((size_t)result < bytes) {
-                fprintf(stderr, "error writing deflated trace: %s (%d)\n",
-                        strerror(errno), errno);
-            }
-        }
-
-        result = deflateEnd(&zs);
-        if (result != Z_OK) {
-            fprintf(stderr, "error cleaning up zlib: %d\n", result);
-        }
-
-        free(in);
-        free(out);
-    } else {
-        ssize_t sent = 0;
-        while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
-        if (sent == -1) {
-            fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
-                    errno);
-        }
-    }
-
-    close(traceFD);
-}
-
-// Print the command usage help to stderr.
-static void showHelp(const char *cmd)
-{
-    fprintf(stderr, "usage: %s [options]\n", cmd);
-    fprintf(stderr, "options include:\n"
-                    "  -b N            use a trace buffer size of N KB\n"
-                    "  -c              trace into a circular buffer\n"
-                    "  -d              trace disk I/O\n"
-                    "  -f              trace clock frequency changes\n"
-                    "  -l              trace CPU frequency governor load\n"
-                    "  -s              trace the kernel scheduler switches\n"
-                    "  -t N            trace for N seconds [defualt 5]\n"
-                    "  -u              trace bus utilization\n"
-                    "  -w              trace the kernel workqueue\n"
-                    "  -y              trace sync timelines and waits\n"
-                    "  -z              compress the trace dump\n"
-                    "  --async_start   start circular trace and return immediatly\n"
-                    "  --async_dump    dump the current contents of circular trace buffer\n"
-                    "  --async_stop    stop tracing and dump the current contents of circular\n"
-                    "                    trace buffer\n"
-            );
-}
-
-static void handleSignal(int signo) {
-    if (!g_nohup) {
-        g_traceAborted = true;
-    }
-}
-
-static void registerSigHandler() {
-    struct sigaction sa;
-    sigemptyset(&sa.sa_mask);
-    sa.sa_flags = 0;
-    sa.sa_handler = handleSignal;
-    sigaction(SIGHUP, &sa, NULL);
-    sigaction(SIGINT, &sa, NULL);
-    sigaction(SIGQUIT, &sa, NULL);
-    sigaction(SIGTERM, &sa, NULL);
-}
-
-int main(int argc, char **argv)
-{
-    bool isRoot = (getuid() == 0);
-    bool async = false;
-    bool traceStart = true;
-    bool traceStop = true;
-    bool traceDump = true;
-
-    if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
-        showHelp(argv[0]);
-        exit(0);
-    }
-
-    for (;;) {
-        int ret;
-        int option_index = 0;
-        static struct option long_options[] = {
-            {"async_start",     no_argument, 0,  0 },
-            {"async_stop",      no_argument, 0,  0 },
-            {"async_dump",      no_argument, 0,  0 },
-            {0,         0,                 0,  0 }
-        };
-
-        ret = getopt_long(argc, argv, "b:cidflst:uwyznS:",
-                          long_options, &option_index);
-
-        if (ret < 0) {
-            break;
-        }
-
-        switch(ret) {
-            case 'b':
-                g_traceBufferSizeKB = atoi(optarg);
-            break;
-
-            case 'c':
-                g_traceOverwrite = true;
-            break;
-
-            case 'i':
-                g_traceCpuIdle = true;
-            break;
-
-            case 'l':
-                g_traceGovernorLoad = true;
-            break;
-
-            case 'd':
-                if (!isRoot) {
-                    fprintf(stderr, "error: tracing disk activity requires root privileges\n");
-                    exit(1);
-                }
-                g_traceDisk = true;
-            break;
-
-            case 'f':
-                g_traceFrequency = true;
-            break;
-
-            case 'n':
-                g_nohup = true;
-                break;
-
-            case 's':
-                g_traceSchedSwitch = true;
-            break;
-
-            case 'S':
-                g_initialSleepSecs = atoi(optarg);
-            break;
-
-            case 't':
-                g_traceDurationSeconds = atoi(optarg);
-            break;
-
-            case 'u':
-                if (!isRoot) {
-                    fprintf(stderr, "error: tracing bus utilization requires root privileges\n");
-                    exit(1);
-                }
-                g_traceBusUtilization = true;
-            break;
-
-            case 'w':
-                if (!isRoot) {
-                    fprintf(stderr, "error: tracing kernel work queues requires root privileges\n");
-                    exit(1);
-                }
-                g_traceWorkqueue = true;
-            break;
-
-            case 'y':
-                if (!isRoot) {
-                    fprintf(stderr, "error: tracing sync requires root privileges\n");
-                    exit(1);
-                }
-                g_traceSync = true;
-            break;
-
-            case 'z':
-                g_compress = true;
-            break;
-
-            case 0:
-                if (!strcmp(long_options[option_index].name, "async_start")) {
-                    async = true;
-                    traceStop = false;
-                    traceDump = false;
-                    g_traceOverwrite = true;
-                } else if (!strcmp(long_options[option_index].name, "async_stop")) {
-                    async = true;
-                    traceStop = false;
-                } else if (!strcmp(long_options[option_index].name, "async_dump")) {
-                    async = true;
-                    traceStart = false;
-                    traceStop = false;
-                }
-                break;
-
-            default:
-                fprintf(stderr, "\n");
-                showHelp(argv[0]);
-                exit(-1);
-            break;
-        }
-    }
-
-    registerSigHandler();
-
-    if (g_initialSleepSecs > 0) {
-        sleep(g_initialSleepSecs);
-    }
-
-    bool ok = startTrace(isRoot);
-
-    if (ok && traceStart) {
-        printf("capturing trace...");
-        fflush(stdout);
-
-        // We clear the trace after starting it because tracing gets enabled for
-        // each CPU individually in the kernel. Having the beginning of the trace
-        // contain entries from only one CPU can cause "begin" entries without a
-        // matching "end" entry to show up if a task gets migrated from one CPU to
-        // another.
-        ok = clearTrace();
-
-        if (ok && !async) {
-            // Sleep to allow the trace to be captured.
-            struct timespec timeLeft;
-            timeLeft.tv_sec = g_traceDurationSeconds;
-            timeLeft.tv_nsec = 0;
-            do {
-                if (g_traceAborted) {
-                    break;
-                }
-            } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
-        }
-    }
-
-    // Stop the trace and restore the default settings.
-    if (traceStop)
-        stopTrace(isRoot);
-
-    if (ok && traceDump) {
-        if (!g_traceAborted) {
-            printf(" done\nTRACE:\n");
-            fflush(stdout);
-            dumpTrace();
-        } else {
-            printf("\ntrace aborted.\n");
-            fflush(stdout);
-        }
-        clearTrace();
-    } else if (!ok) {
-        fprintf(stderr, "unable to start tracing\n");
-    }
-
-    // Reset the trace buffer size to 1.
-    if (traceStop)
-        setTraceBufferSizeKB(1);
-
-    return g_traceAborted ? 1 : 0;
-}
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
new file mode 100644
index 0000000..c6b3dce
--- /dev/null
+++ b/cmds/atrace/atrace.cpp
@@ -0,0 +1,713 @@
+/*
+ * 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.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/sendfile.h>
+#include <time.h>
+#include <zlib.h>
+
+#include <binder/IBinder.h>
+#include <binder/IServiceManager.h>
+#include <binder/Parcel.h>
+
+#include <cutils/properties.h>
+
+#include <utils/String8.h>
+#include <utils/Trace.h>
+
+using namespace android;
+
+#define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
+
+enum { MAX_SYS_FILES = 8 };
+
+const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
+
+typedef enum { OPT, REQ } requiredness  ;
+
+struct TracingCategory {
+    // The name identifying the category.
+    const char* name;
+
+    // A longer description of the category.
+    const char* longname;
+
+    // The userland tracing tags that the category enables.
+    uint64_t tags;
+
+    // The fname==NULL terminated list of /sys/ files that the category
+    // enables.
+    struct {
+        // Whether the file must be writable in order to enable the tracing
+        // category.
+        requiredness required;
+
+        // The path to the enable file.
+        const char* path;
+    } sysfiles[MAX_SYS_FILES];
+};
+
+/* Tracing categories */
+static const TracingCategory k_categories[] = {
+    { "gfx",    "Graphics",         ATRACE_TAG_GRAPHICS, { } },
+    { "input",  "Input",            ATRACE_TAG_INPUT, { } },
+    { "view",   "View System",      ATRACE_TAG_VIEW, { } },
+    { "wm",     "Window Manager",   ATRACE_TAG_WINDOW_MANAGER, { } },
+    { "am",     "Activity Manager", ATRACE_TAG_ACTIVITY_MANAGER, { } },
+    { "audio",  "Audio",            ATRACE_TAG_AUDIO, { } },
+    { "video",  "Video",            ATRACE_TAG_VIDEO, { } },
+    { "camera", "Camera",           ATRACE_TAG_CAMERA, { } },
+    { "sched",  "CPU Scheduling",   0, {
+        { REQ,  "/sys/kernel/debug/tracing/events/sched/sched_switch/enable" },
+        { REQ,  "/sys/kernel/debug/tracing/events/sched/sched_wakeup/enable" },
+    } },
+    { "freq",   "CPU Frequency",    0, {
+        { REQ,  "/sys/kernel/debug/tracing/events/power/cpu_frequency/enable" },
+        { OPT, "/sys/kernel/debug/tracing/events/power/clock_set_rate/enable" },
+    } },
+    { "membus", "Memory Bus Utilization", 0, {
+        { REQ,  "/sys/kernel/debug/tracing/events/memory_bus/enable" },
+    } },
+    { "idle",   "CPU Idle",         0, {
+        { REQ,  "/sys/kernel/debug/tracing/events/power/cpu_idle/enable" },
+    } },
+    { "disk",   "Disk I/O",         0, {
+        { REQ,  "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_enter/enable" },
+        { REQ,  "/sys/kernel/debug/tracing/events/ext4/ext4_sync_file_exit/enable" },
+        { REQ,  "/sys/kernel/debug/tracing/events/block/block_rq_issue/enable" },
+        { REQ,  "/sys/kernel/debug/tracing/events/block/block_rq_complete/enable" },
+    } },
+    { "load",   "CPU Load",         0, {
+        { REQ,  "/sys/kernel/debug/tracing/events/cpufreq_interactive/enable" },
+    } },
+    { "sync",   "Synchronization",  0, {
+        { REQ,  "/sys/kernel/debug/tracing/events/sync/enable" },
+    } },
+    { "workq",  "Kernel Workqueues", 0, {
+        { REQ,  "/sys/kernel/debug/tracing/events/workqueue/enable" },
+    } },
+};
+
+/* Command line options */
+static int g_traceDurationSeconds = 5;
+static bool g_traceOverwrite = false;
+static int g_traceBufferSizeKB = 2048;
+static bool g_compress = false;
+static bool g_nohup = false;
+static int g_initialSleepSecs = 0;
+
+/* Global state */
+static bool g_traceAborted = false;
+static bool g_categoryEnables[NELEM(k_categories)] = {};
+
+/* Sys file paths */
+static const char* k_traceClockPath =
+    "/sys/kernel/debug/tracing/trace_clock";
+
+static const char* k_traceBufferSizePath =
+    "/sys/kernel/debug/tracing/buffer_size_kb";
+
+static const char* k_tracingOverwriteEnablePath =
+    "/sys/kernel/debug/tracing/options/overwrite";
+
+static const char* k_tracingOnPath =
+    "/sys/kernel/debug/tracing/tracing_on";
+
+static const char* k_tracePath =
+    "/sys/kernel/debug/tracing/trace";
+
+// Check whether a file exists.
+static bool fileExists(const char* filename) {
+    return access(filename, F_OK) != -1;
+}
+
+// Check whether a file is writable.
+static bool fileIsWritable(const char* filename) {
+    return access(filename, W_OK) != -1;
+}
+
+// Write a string to a file, returning true if the write was successful.
+static bool writeStr(const char* filename, const char* str)
+{
+    int fd = open(filename, O_WRONLY);
+    if (fd == -1) {
+        fprintf(stderr, "error opening %s: %s (%d)\n", filename,
+                strerror(errno), errno);
+        return false;
+    }
+
+    bool ok = true;
+    ssize_t len = strlen(str);
+    if (write(fd, str, len) != len) {
+        fprintf(stderr, "error writing to %s: %s (%d)\n", filename,
+                strerror(errno), errno);
+        ok = false;
+    }
+
+    close(fd);
+
+    return ok;
+}
+
+// Enable or disable a kernel option by writing a "1" or a "0" into a /sys
+// file.
+static bool setKernelOptionEnable(const char* filename, bool enable)
+{
+    return writeStr(filename, enable ? "1" : "0");
+}
+
+// Check whether the category is supported on the device with the current
+// rootness.  A category is supported only if all its required /sys/ files are
+// writable and if enabling the category will enable one or more tracing tags
+// or /sys/ files.
+static bool isCategorySupported(const TracingCategory& category)
+{
+    bool ok = category.tags != 0;
+    for (int i = 0; i < MAX_SYS_FILES; i++) {
+        const char* path = category.sysfiles[i].path;
+        bool req = category.sysfiles[i].required == REQ;
+        if (path != NULL) {
+            if (req) {
+                if (!fileIsWritable(path)) {
+                    return false;
+                } else {
+                    ok = true;
+                }
+            } else {
+                ok |= fileIsWritable(path);
+            }
+        }
+    }
+    return ok;
+}
+
+// Check whether the category would be supported on the device if the user
+// were root.  This function assumes that root is able to write to any file
+// that exists.  It performs the same logic as isCategorySupported, but it
+// uses file existance rather than writability in the /sys/ file checks.
+static bool isCategorySupportedForRoot(const TracingCategory& category)
+{
+    bool ok = category.tags != 0;
+    for (int i = 0; i < MAX_SYS_FILES; i++) {
+        const char* path = category.sysfiles[i].path;
+        bool req = category.sysfiles[i].required == REQ;
+        if (path != NULL) {
+            if (req) {
+                if (!fileExists(path)) {
+                    return false;
+                } else {
+                    ok = true;
+                }
+            } else {
+                ok |= fileExists(path);
+            }
+        }
+    }
+    return ok;
+}
+
+// Enable or disable overwriting of the kernel trace buffers.  Disabling this
+// will cause tracing to stop once the trace buffers have filled up.
+static bool setTraceOverwriteEnable(bool enable)
+{
+    return setKernelOptionEnable(k_tracingOverwriteEnablePath, enable);
+}
+
+// Enable or disable kernel tracing.
+static bool setTracingEnabled(bool enable)
+{
+    return setKernelOptionEnable(k_tracingOnPath, enable);
+}
+
+// Clear the contents of the kernel trace.
+static bool clearTrace()
+{
+    int traceFD = creat(k_tracePath, 0);
+    if (traceFD == -1) {
+        fprintf(stderr, "error truncating %s: %s (%d)\n", k_tracePath,
+                strerror(errno), errno);
+        return false;
+    }
+
+    close(traceFD);
+
+    return true;
+}
+
+// Set the size of the kernel's trace buffer in kilobytes.
+static bool setTraceBufferSizeKB(int size)
+{
+    char str[32] = "1";
+    int len;
+    if (size < 1) {
+        size = 1;
+    }
+    snprintf(str, 32, "%d", size);
+    return writeStr(k_traceBufferSizePath, str);
+}
+
+// Enable or disable the kernel's use of the global clock.  Disabling the global
+// clock will result in the kernel using a per-CPU local clock.
+static bool setGlobalClockEnable(bool enable)
+{
+    return writeStr(k_traceClockPath, enable ? "global" : "local");
+}
+
+// Poke all the binder-enabled processes in the system to get them to re-read
+// their system properties.
+static bool pokeBinderServices()
+{
+    sp<IServiceManager> sm = defaultServiceManager();
+    Vector<String16> services = sm->listServices();
+    for (size_t i = 0; i < services.size(); i++) {
+        sp<IBinder> obj = sm->checkService(services[i]);
+        if (obj != NULL) {
+            Parcel data;
+            if (obj->transact(IBinder::SYSPROPS_TRANSACTION, data,
+                    NULL, 0) != OK) {
+                if (false) {
+                    // XXX: For some reason this fails on tablets trying to
+                    // poke the "phone" service.  It's not clear whether some
+                    // are expected to fail.
+                    String8 svc(services[i]);
+                    fprintf(stderr, "error poking binder service %s\n",
+                        svc.string());
+                    return false;
+                }
+            }
+        }
+    }
+    return true;
+}
+
+// Set the trace tags that userland tracing uses, and poke the running
+// processes to pick up the new value.
+static bool setTagsProperty(uint64_t tags)
+{
+    char buf[64];
+    snprintf(buf, 64, "%#llx", tags);
+    if (property_set(k_traceTagsProperty, buf) < 0) {
+        fprintf(stderr, "error setting trace tags system property\n");
+        return false;
+    }
+    return pokeBinderServices();
+}
+
+// Disable all /sys/ enable files.
+static bool disableKernelTraceEvents() {
+    bool ok = true;
+    for (int i = 0; i < NELEM(k_categories); i++) {
+        const TracingCategory &c = k_categories[i];
+        for (int j = 0; j < MAX_SYS_FILES; j++) {
+            const char* path = c.sysfiles[j].path;
+            if (path != NULL && fileIsWritable(path)) {
+                ok &= setKernelOptionEnable(path, false);
+            }
+        }
+    }
+    return ok;
+}
+
+// Enable tracing in the kernel.
+static bool startTrace()
+{
+    bool ok = true;
+
+    // Set up the tracing options.
+    ok &= setTraceOverwriteEnable(g_traceOverwrite);
+    ok &= setTraceBufferSizeKB(g_traceBufferSizeKB);
+    ok &= setGlobalClockEnable(true);
+
+    // Set up the tags property.
+    uint64_t tags = 0;
+    for (int i = 0; i < NELEM(k_categories); i++) {
+        if (g_categoryEnables[i]) {
+            const TracingCategory &c = k_categories[i];
+            tags |= c.tags;
+        }
+    }
+    ok &= setTagsProperty(tags);
+
+    // Disable all the sysfs enables.  This is done as a separate loop from
+    // the enables to allow the same enable to exist in multiple categories.
+    ok &= disableKernelTraceEvents();
+
+    // Enable all the sysfs enables that are in an enabled category.
+    for (int i = 0; i < NELEM(k_categories); i++) {
+        if (g_categoryEnables[i]) {
+            const TracingCategory &c = k_categories[i];
+            for (int j = 0; j < MAX_SYS_FILES; j++) {
+                const char* path = c.sysfiles[j].path;
+                bool required = c.sysfiles[j].required == REQ;
+                if (path != NULL) {
+                    if (fileIsWritable(path)) {
+                        ok &= setKernelOptionEnable(path, true);
+                    } else if (required) {
+                        fprintf(stderr, "error writing file %s\n", path);
+                        ok = false;
+                    }
+                }
+            }
+        }
+    }
+
+    // Enable tracing.
+    ok &= setTracingEnabled(true);
+
+    return ok;
+}
+
+// Disable tracing in the kernel.
+static void stopTrace()
+{
+    // Disable tracing.
+    setTracingEnabled(false);
+
+    // Disable all tracing that we're able to.
+    disableKernelTraceEvents();
+
+    // Disable all the trace tags.
+    setTagsProperty(0);
+
+    // Set the options back to their defaults.
+    setTraceOverwriteEnable(true);
+    setGlobalClockEnable(false);
+
+    // Note that we can't reset the trace buffer size here because that would
+    // clear the trace before we've read it.
+}
+
+// Read the current kernel trace and write it to stdout.
+static void dumpTrace()
+{
+    int traceFD = open(k_tracePath, O_RDWR);
+    if (traceFD == -1) {
+        fprintf(stderr, "error opening %s: %s (%d)\n", k_tracePath,
+                strerror(errno), errno);
+        return;
+    }
+
+    if (g_compress) {
+        z_stream zs;
+        uint8_t *in, *out;
+        int result, flush;
+
+        bzero(&zs, sizeof(zs));
+        result = deflateInit(&zs, Z_DEFAULT_COMPRESSION);
+        if (result != Z_OK) {
+            fprintf(stderr, "error initializing zlib: %d\n", result);
+            close(traceFD);
+            return;
+        }
+
+        const size_t bufSize = 64*1024;
+        in = (uint8_t*)malloc(bufSize);
+        out = (uint8_t*)malloc(bufSize);
+        flush = Z_NO_FLUSH;
+
+        zs.next_out = out;
+        zs.avail_out = bufSize;
+
+        do {
+
+            if (zs.avail_in == 0) {
+                // More input is needed.
+                result = read(traceFD, in, bufSize);
+                if (result < 0) {
+                    fprintf(stderr, "error reading trace: %s (%d)\n",
+                            strerror(errno), errno);
+                    result = Z_STREAM_END;
+                    break;
+                } else if (result == 0) {
+                    flush = Z_FINISH;
+                } else {
+                    zs.next_in = in;
+                    zs.avail_in = result;
+                }
+            }
+
+            if (zs.avail_out == 0) {
+                // Need to write the output.
+                result = write(STDOUT_FILENO, out, bufSize);
+                if ((size_t)result < bufSize) {
+                    fprintf(stderr, "error writing deflated trace: %s (%d)\n",
+                            strerror(errno), errno);
+                    result = Z_STREAM_END; // skip deflate error message
+                    zs.avail_out = bufSize; // skip the final write
+                    break;
+                }
+                zs.next_out = out;
+                zs.avail_out = bufSize;
+            }
+
+        } while ((result = deflate(&zs, flush)) == Z_OK);
+
+        if (result != Z_STREAM_END) {
+            fprintf(stderr, "error deflating trace: %s\n", zs.msg);
+        }
+
+        if (zs.avail_out < bufSize) {
+            size_t bytes = bufSize - zs.avail_out;
+            result = write(STDOUT_FILENO, out, bytes);
+            if ((size_t)result < bytes) {
+                fprintf(stderr, "error writing deflated trace: %s (%d)\n",
+                        strerror(errno), errno);
+            }
+        }
+
+        result = deflateEnd(&zs);
+        if (result != Z_OK) {
+            fprintf(stderr, "error cleaning up zlib: %d\n", result);
+        }
+
+        free(in);
+        free(out);
+    } else {
+        ssize_t sent = 0;
+        while ((sent = sendfile(STDOUT_FILENO, traceFD, NULL, 64*1024*1024)) > 0);
+        if (sent == -1) {
+            fprintf(stderr, "error dumping trace: %s (%d)\n", strerror(errno),
+                    errno);
+        }
+    }
+
+    close(traceFD);
+}
+
+static void handleSignal(int signo)
+{
+    if (!g_nohup) {
+        g_traceAborted = true;
+    }
+}
+
+static void registerSigHandler()
+{
+    struct sigaction sa;
+    sigemptyset(&sa.sa_mask);
+    sa.sa_flags = 0;
+    sa.sa_handler = handleSignal;
+    sigaction(SIGHUP, &sa, NULL);
+    sigaction(SIGINT, &sa, NULL);
+    sigaction(SIGQUIT, &sa, NULL);
+    sigaction(SIGTERM, &sa, NULL);
+}
+
+static bool setCategoryEnable(const char* name, bool enable)
+{
+    for (int i = 0; i < NELEM(k_categories); i++) {
+        const TracingCategory& c = k_categories[i];
+        if (strcmp(name, c.name) == 0) {
+            if (isCategorySupported(c)) {
+                g_categoryEnables[i] = enable;
+                return true;
+            } else {
+                if (isCategorySupportedForRoot(c)) {
+                    fprintf(stderr, "error: category \"%s\" requires root "
+                            "privileges.\n", name);
+                } else {
+                    fprintf(stderr, "error: category \"%s\" is not supported "
+                            "on this device.\n", name);
+                }
+                return false;
+            }
+        }
+    }
+    fprintf(stderr, "error: unknown tracing category \"%s\"\n", name);
+    return false;
+}
+
+static void listSupportedCategories()
+{
+    for (int i = 0; i < NELEM(k_categories); i++) {
+        const TracingCategory& c = k_categories[i];
+        if (isCategorySupported(c)) {
+            printf("  %10s - %s\n", c.name, c.longname);
+        }
+    }
+}
+
+// Print the command usage help to stderr.
+static void showHelp(const char *cmd)
+{
+    fprintf(stderr, "usage: %s [options] [categories...]\n", cmd);
+    fprintf(stderr, "options include:\n"
+                    "  -b N            use a trace buffer size of N KB\n"
+                    "  -c              trace into a circular buffer\n"
+                    "  -n              ignore signals\n"
+                    "  -s N            sleep for N seconds before tracing [default 0]\n"
+                    "  -t N            trace for N seconds [defualt 5]\n"
+                    "  -z              compress the trace dump\n"
+                    "  --async_start   start circular trace and return immediatly\n"
+                    "  --async_dump    dump the current contents of circular trace buffer\n"
+                    "  --async_stop    stop tracing and dump the current contents of circular\n"
+                    "                    trace buffer\n"
+                    "  --list_categories\n"
+                    "                  list the available tracing categories\n"
+            );
+}
+
+int main(int argc, char **argv)
+{
+    bool async = false;
+    bool traceStart = true;
+    bool traceStop = true;
+    bool traceDump = true;
+
+    if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
+        showHelp(argv[0]);
+        exit(0);
+    }
+
+    for (;;) {
+        int ret;
+        int option_index = 0;
+        static struct option long_options[] = {
+            {"async_start",     no_argument, 0,  0 },
+            {"async_stop",      no_argument, 0,  0 },
+            {"async_dump",      no_argument, 0,  0 },
+            {"list_categories", no_argument, 0,  0 },
+            {           0,                0, 0,  0 }
+        };
+
+        ret = getopt_long(argc, argv, "b:cns:t:z",
+                          long_options, &option_index);
+
+        if (ret < 0) {
+            for (int i = optind; i < argc; i++) {
+                if (!setCategoryEnable(argv[i], true)) {
+                    fprintf(stderr, "error enabling tracing category \"%s\"\n", argv[i]);
+                    exit(1);
+                }
+            }
+            break;
+        }
+
+        switch(ret) {
+            case 'b':
+                g_traceBufferSizeKB = atoi(optarg);
+            break;
+
+            case 'c':
+                g_traceOverwrite = true;
+            break;
+
+            case 'n':
+                g_nohup = true;
+                break;
+
+            case 's':
+                g_initialSleepSecs = atoi(optarg);
+            break;
+
+            case 't':
+                g_traceDurationSeconds = atoi(optarg);
+            break;
+
+            case 'z':
+                g_compress = true;
+            break;
+
+            case 0:
+                if (!strcmp(long_options[option_index].name, "async_start")) {
+                    async = true;
+                    traceStop = false;
+                    traceDump = false;
+                    g_traceOverwrite = true;
+                } else if (!strcmp(long_options[option_index].name, "async_stop")) {
+                    async = true;
+                    traceStop = false;
+                } else if (!strcmp(long_options[option_index].name, "async_dump")) {
+                    async = true;
+                    traceStart = false;
+                    traceStop = false;
+                } else if (!strcmp(long_options[option_index].name, "list_categories")) {
+                    listSupportedCategories();
+                    exit(0);
+                }
+                break;
+
+            default:
+                fprintf(stderr, "\n");
+                showHelp(argv[0]);
+                exit(-1);
+            break;
+        }
+    }
+
+    registerSigHandler();
+
+    if (g_initialSleepSecs > 0) {
+        sleep(g_initialSleepSecs);
+    }
+
+    bool ok = startTrace();
+
+    if (ok && traceStart) {
+        printf("capturing trace...");
+        fflush(stdout);
+
+        // We clear the trace after starting it because tracing gets enabled for
+        // each CPU individually in the kernel. Having the beginning of the trace
+        // contain entries from only one CPU can cause "begin" entries without a
+        // matching "end" entry to show up if a task gets migrated from one CPU to
+        // another.
+        ok = clearTrace();
+
+        if (ok && !async) {
+            // Sleep to allow the trace to be captured.
+            struct timespec timeLeft;
+            timeLeft.tv_sec = g_traceDurationSeconds;
+            timeLeft.tv_nsec = 0;
+            do {
+                if (g_traceAborted) {
+                    break;
+                }
+            } while (nanosleep(&timeLeft, &timeLeft) == -1 && errno == EINTR);
+        }
+    }
+
+    // Stop the trace and restore the default settings.
+    if (traceStop)
+        stopTrace();
+
+    if (ok && traceDump) {
+        if (!g_traceAborted) {
+            printf(" done\nTRACE:\n");
+            fflush(stdout);
+            dumpTrace();
+        } else {
+            printf("\ntrace aborted.\n");
+            fflush(stdout);
+        }
+        clearTrace();
+    } else if (!ok) {
+        fprintf(stderr, "unable to start tracing\n");
+    }
+
+    // Reset the trace buffer size to 1.
+    if (traceStop)
+        setTraceBufferSizeKB(1);
+
+    return g_traceAborted ? 1 : 0;
+}
diff --git a/cmds/installd/commands.c b/cmds/installd/commands.c
index 2a54710..c272e47 100644
--- a/cmds/installd/commands.c
+++ b/cmds/installd/commands.c
@@ -283,53 +283,6 @@
     return 0;
 }
 
-int clone_persona_data(uid_t src_persona, uid_t target_persona, int copy)
-{
-    char src_data_dir[PKG_PATH_MAX];
-    char pkg_path[PKG_PATH_MAX];
-    DIR *d;
-    struct dirent *de;
-    struct stat s;
-    uid_t uid;
-
-    if (create_persona_path(src_data_dir, src_persona)) {
-        return -1;
-    }
-
-    d = opendir(src_data_dir);
-    if (d != NULL) {
-        while ((de = readdir(d))) {
-            const char *name = de->d_name;
-
-            if (de->d_type == DT_DIR) {
-                int subfd;
-                    /* always skip "." and ".." */
-                if (name[0] == '.') {
-                    if (name[1] == 0) continue;
-                    if ((name[1] == '.') && (name[2] == 0)) continue;
-                }
-                /* Create the full path to the package's data dir */
-                create_pkg_path(pkg_path, name, PKG_DIR_POSTFIX, src_persona);
-                /* Get the file stat */
-                if (stat(pkg_path, &s) < 0) continue;
-                /* Get the uid of the package */
-                ALOGI("Adding datadir for uid = %lu\n", s.st_uid);
-                uid = (uid_t) s.st_uid % PER_USER_RANGE;
-                /* Create the directory for the target */
-                make_user_data(name, uid + target_persona * PER_USER_RANGE,
-                               target_persona);
-            }
-        }
-        closedir(d);
-    }
-
-    if (ensure_media_user_dirs((userid_t) target_persona) == -1) {
-        return -1;
-    }
-
-    return 0;
-}
-
 int delete_cache(const char *pkgname, uid_t persona)
 {
     char cachedir[PKG_PATH_MAX];
diff --git a/cmds/installd/installd.c b/cmds/installd/installd.c
index 21d674a..2285e79 100644
--- a/cmds/installd/installd.c
+++ b/cmds/installd/installd.c
@@ -111,11 +111,6 @@
     return delete_persona(atoi(arg[0])); /* userid */
 }
 
-static int do_clone_user_data(char **arg, char reply[REPLY_MAX])
-{
-    return clone_persona_data(atoi(arg[0]), atoi(arg[1]), atoi(arg[2]));
-}
-
 static int do_movefiles(char **arg, char reply[REPLY_MAX])
 {
     return movefiles();
@@ -149,7 +144,6 @@
     { "linklib",              3, do_linklib },
     { "mkuserdata",           3, do_mk_user_data },
     { "rmuser",               1, do_rm_user },
-    { "cloneuserdata",        3, do_clone_user_data },
 };
 
 static int readx(int s, void *_buf, int count)
diff --git a/cmds/installd/installd.h b/cmds/installd/installd.h
index 0500c23..efd3aa7 100644
--- a/cmds/installd/installd.h
+++ b/cmds/installd/installd.h
@@ -199,7 +199,6 @@
 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 clone_persona_data(uid_t src_persona, uid_t target_persona, int copy);
 int delete_cache(const char *pkgname, uid_t persona);
 int move_dex(const char *src, const char *dst);
 int rm_dex(const char *path);
diff --git a/include/gui/BufferQueue.h b/include/gui/BufferQueue.h
index 9e265ba..88bcd8f 100644
--- a/include/gui/BufferQueue.h
+++ b/include/gui/BufferQueue.h
@@ -182,8 +182,9 @@
            mBuf(INVALID_BUFFER_SLOT) {
              mCrop.makeInvalid();
          }
-        // mGraphicBuffer points to the buffer allocated for this slot or is NULL
-        // if no buffer has been allocated.
+        // 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.
diff --git a/services/surfaceflinger/DisplayHardware/GraphicBufferAlloc.h b/include/gui/GraphicBufferAlloc.h
similarity index 100%
rename from services/surfaceflinger/DisplayHardware/GraphicBufferAlloc.h
rename to include/gui/GraphicBufferAlloc.h
diff --git a/include/gui/SurfaceTexture.h b/include/gui/SurfaceTexture.h
index b498a5c..ae5d57a 100644
--- a/include/gui/SurfaceTexture.h
+++ b/include/gui/SurfaceTexture.h
@@ -74,14 +74,13 @@
             GLenum texTarget = GL_TEXTURE_EXTERNAL_OES, bool useFenceSync = true,
             const sp<BufferQueue> &bufferQueue = 0);
 
-    // updateTexImage sets the image contents of the target texture to that of
-    // the most recently queued buffer.
+    // updateTexImage acquires the most recently queued buffer, and sets the
+    // image contents of the target texture to it.
     //
     // This call may only be made while the OpenGL ES context to which the
     // target texture belongs is bound to the calling thread.
     //
-    // After calling this method the doGLFenceWait method must be called
-    // before issuing OpenGL ES commands that access the texture contents.
+    // This calls doGLFenceWait to ensure proper synchronization.
     status_t updateTexImage();
 
     // setReleaseFence stores a fence file descriptor that will signal when the
@@ -161,8 +160,7 @@
 
     // doGLFenceWait inserts a wait command into the OpenGL ES command stream
     // to ensure that it is safe for future OpenGL ES commands to access the
-    // current texture buffer.  This must be called each time updateTexImage
-    // is called before issuing OpenGL ES commands that access the texture.
+    // current texture buffer.
     status_t doGLFenceWait() const;
 
     // isSynchronousMode returns whether the SurfaceTexture is currently in
@@ -233,23 +231,33 @@
     virtual status_t releaseBufferLocked(int buf, EGLDisplay display,
            EGLSyncKHR eglFence);
 
+    status_t releaseBufferLocked(int buf, EGLSyncKHR eglFence) {
+        return releaseBufferLocked(buf, mEglDisplay, eglFence);
+    }
+
     static bool isExternalFormat(uint32_t format);
 
-private:
-    // this version of updateTexImage() takes a functor used to reject or not
-    // the newly acquired buffer.
-    // this API is TEMPORARY and intended to be used by SurfaceFlinger only,
-    // which is why class Layer is made a friend of SurfaceTexture below.
-    class BufferRejecter {
-        friend class SurfaceTexture;
-        virtual bool reject(const sp<GraphicBuffer>& buf,
-                const BufferQueue::BufferItem& item) = 0;
-    protected:
-        virtual ~BufferRejecter() { }
-    };
-    friend class Layer;
-    status_t updateTexImage(BufferRejecter* rejecter, bool skipSync);
+    // 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);
 
+    // Binds mTexName and the current buffer to mTexTarget.  Uses
+    // mCurrentTexture if it's set, mCurrentTextureBuf if not.  If the
+    // bind succeeds, this calls doGLFenceWait.
+    status_t bindTextureImageLocked();
+
+    // Gets the current EGLDisplay and EGLContext values, and compares them
+    // 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();
+
+    // If set, SurfaceTexture will use the EGL_ANDROID_native_fence_sync
+    // extension to create Android native fences for GLES activity.
+    static const bool sUseNativeFenceSync;
+
+private:
     // createImage creates a new EGLImage from a GraphicBuffer.
     EGLImageKHR createImage(EGLDisplay dpy,
             const sp<GraphicBuffer>& graphicBuffer);
@@ -269,9 +277,7 @@
 
     // doGLFenceWaitLocked inserts a wait command into the OpenGL ES command
     // stream to ensure that it is safe for future OpenGL ES commands to
-    // access the current texture buffer.  This must be called each time
-    // updateTexImage is called before issuing OpenGL ES commands that access
-    // the texture.
+    // access the current texture buffer.
     status_t doGLFenceWaitLocked() const;
 
     // syncForReleaseLocked performs the synchronization needed to release the
@@ -280,6 +286,13 @@
     // before the outstanding accesses have completed.
     status_t syncForReleaseLocked(EGLDisplay dpy);
 
+    // Normally, when we bind a buffer to a texture target, we bind a buffer
+    // that is referenced by an entry in mEglSlots.  In some situations we
+    // have a buffer in mCurrentTextureBuf, but no corresponding entry for
+    // it in our slot array.  bindUnslottedBuffer handles that situation by
+    // binding the buffer without touching the EglSlots.
+    status_t bindUnslottedBufferLocked(EGLDisplay dpy);
+
     // The default consumer usage flags that SurfaceTexture always sets on its
     // BufferQueue instance; these will be OR:d with any additional flags passed
     // from the SurfaceTexture user. In particular, SurfaceTexture will always
@@ -344,8 +357,8 @@
 
     // EGLSlot contains the information and object references that
     // SurfaceTexture maintains about a BufferQueue buffer slot.
-    struct EGLSlot {
-        EGLSlot()
+    struct EglSlot {
+        EglSlot()
         : mEglImage(EGL_NO_IMAGE_KHR),
           mEglFence(EGL_NO_SYNC_KHR) {
         }
@@ -379,7 +392,7 @@
     // slot that has not yet been used. The buffer allocated to a slot will also
     // be replaced if the requested buffer usage or geometry differs from that
     // of the buffer allocated to a slot.
-    EGLSlot mEglSlots[BufferQueue::NUM_BUFFER_SLOTS];
+    EglSlot mEglSlots[BufferQueue::NUM_BUFFER_SLOTS];
 
     // mCurrentTexture is the buffer slot index of the buffer that is currently
     // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
diff --git a/include/gui/SurfaceTextureClient.h b/include/gui/SurfaceTextureClient.h
index 50fd1ba..56d861a 100644
--- a/include/gui/SurfaceTextureClient.h
+++ b/include/gui/SurfaceTextureClient.h
@@ -41,12 +41,6 @@
 
     SurfaceTextureClient(const sp<ISurfaceTexture>& surfaceTexture);
 
-    // SurfaceTextureClient is overloaded to assist in refactoring ST and BQ.
-    // SurfaceTexture is no longer an ISurfaceTexture, so client code
-    // calling the original constructor will fail. Thus this convenience method
-    // passes in the surfaceTexture's bufferQueue to the init method.
-    SurfaceTextureClient(const sp<SurfaceTexture>& surfaceTexture);
-
     sp<ISurfaceTexture> getISurfaceTexture() const;
 
 protected:
diff --git a/include/utils/LinearAllocator.h b/include/utils/LinearAllocator.h
new file mode 100644
index 0000000..4772bc8
--- /dev/null
+++ b/include/utils/LinearAllocator.h
@@ -0,0 +1,97 @@
+/*
+ * 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/libs/gui/Android.mk b/libs/gui/Android.mk
index d970a33..04444e9 100644
--- a/libs/gui/Android.mk
+++ b/libs/gui/Android.mk
@@ -3,29 +3,30 @@
 
 LOCAL_SRC_FILES:= \
 	BitTube.cpp \
+	BufferItemConsumer.cpp \
 	BufferQueue.cpp \
 	ConsumerBase.cpp \
+	CpuConsumer.cpp \
 	DisplayEventReceiver.cpp \
+	DummyConsumer.cpp \
+	GraphicBufferAlloc.cpp \
+	GuiConfig.cpp \
 	IDisplayEventConnection.cpp \
+	IGraphicBufferAlloc.cpp \
 	ISensorEventConnection.cpp \
 	ISensorServer.cpp \
+	ISurface.cpp \
+	ISurfaceComposer.cpp \
+	ISurfaceComposerClient.cpp \
 	ISurfaceTexture.cpp \
+	LayerState.cpp \
 	Sensor.cpp \
 	SensorEventQueue.cpp \
 	SensorManager.cpp \
-	SurfaceTexture.cpp \
-	SurfaceTextureClient.cpp \
-	ISurfaceComposer.cpp \
-	ISurface.cpp \
-	ISurfaceComposerClient.cpp \
-	IGraphicBufferAlloc.cpp \
-	LayerState.cpp \
 	Surface.cpp \
 	SurfaceComposerClient.cpp \
-	DummyConsumer.cpp \
-	CpuConsumer.cpp \
-	BufferItemConsumer.cpp \
-	GuiConfig.cpp
+	SurfaceTexture.cpp \
+	SurfaceTextureClient.cpp \
 
 LOCAL_SHARED_LIBRARIES := \
 	libbinder \
diff --git a/libs/gui/BufferQueue.cpp b/libs/gui/BufferQueue.cpp
index 086e298..609e7d2 100644
--- a/libs/gui/BufferQueue.cpp
+++ b/libs/gui/BufferQueue.cpp
@@ -29,7 +29,6 @@
 #include <private/gui/ComposerService.h>
 
 #include <utils/Log.h>
-#include <gui/SurfaceTexture.h>
 #include <utils/Trace.h>
 
 // Macros for including the BufferQueue name in log messages
diff --git a/services/surfaceflinger/DisplayHardware/GraphicBufferAlloc.cpp b/libs/gui/GraphicBufferAlloc.cpp
similarity index 96%
rename from services/surfaceflinger/DisplayHardware/GraphicBufferAlloc.cpp
rename to libs/gui/GraphicBufferAlloc.cpp
index 965ff01..b360e81 100644
--- a/services/surfaceflinger/DisplayHardware/GraphicBufferAlloc.cpp
+++ b/libs/gui/GraphicBufferAlloc.cpp
@@ -19,7 +19,7 @@
 
 #include <ui/GraphicBuffer.h>
 
-#include "DisplayHardware/GraphicBufferAlloc.h"
+#include <gui/GraphicBufferAlloc.h>
 
 // ----------------------------------------------------------------------------
 namespace android {
diff --git a/libs/gui/SurfaceTexture.cpp b/libs/gui/SurfaceTexture.cpp
index b4dfb5e..ee3079e 100644
--- a/libs/gui/SurfaceTexture.cpp
+++ b/libs/gui/SurfaceTexture.cpp
@@ -39,6 +39,8 @@
 #include <utils/String8.h>
 #include <utils/Trace.h>
 
+namespace android {
+
 // This compile option makes SurfaceTexture use the
 // EGL_ANDROID_native_fence_sync extension to create Android native fences to
 // signal when all GLES reads for a given buffer have completed.  It is not
@@ -48,9 +50,9 @@
 #ifdef USE_FENCE_SYNC
 #error "USE_NATIVE_FENCE_SYNC and USE_FENCE_SYNC are incompatible"
 #endif
-static const bool useNativeFenceSync = true;
+const bool SurfaceTexture::sUseNativeFenceSync = true;
 #else
-static const bool useNativeFenceSync = false;
+const bool SurfaceTexture::sUseNativeFenceSync = false;
 #endif
 
 // This compile option makes SurfaceTexture use the EGL_ANDROID_sync_wait
@@ -70,8 +72,6 @@
 #define ST_LOGW(x, ...) ALOGW("[%s] "x, mName.string(), ##__VA_ARGS__)
 #define ST_LOGE(x, ...) ALOGE("[%s] "x, mName.string(), ##__VA_ARGS__)
 
-namespace android {
-
 // Transform matrices
 static float mtxIdentity[16] = {
     1, 0, 0, 0,
@@ -154,7 +154,50 @@
 }
 
 status_t SurfaceTexture::updateTexImage() {
-    return SurfaceTexture::updateTexImage(NULL, false);
+    ATRACE_CALL();
+    ST_LOGV("updateTexImage");
+    Mutex::Autolock lock(mMutex);
+
+    if (mAbandoned) {
+        ST_LOGE("updateTexImage: SurfaceTexture is abandoned!");
+        return NO_INIT;
+    }
+
+    // Make sure the EGL state is the same as in previous calls.
+    status_t err = checkAndUpdateEglStateLocked();
+    if (err != NO_ERROR) {
+        return err;
+    }
+
+    BufferQueue::BufferItem item;
+
+    // Acquire the next buffer.
+    // In asynchronous mode the list is guaranteed to be one buffer
+    // deep, while in synchronous mode we use the oldest buffer.
+    err = acquireBufferLocked(&item);
+    if (err != NO_ERROR) {
+        if (err == BufferQueue::NO_BUFFER_AVAILABLE) {
+            // We always bind the texture even if we don't update its contents.
+            ST_LOGV("updateTexImage: no buffers were available");
+            glBindTexture(mTexTarget, mTexName);
+            err = NO_ERROR;
+        } else {
+            ST_LOGE("updateTexImage: acquire failed: %s (%d)",
+                strerror(-err), err);
+        }
+        return err;
+    }
+
+    // Release the previous buffer.
+    err = releaseAndUpdateLocked(item);
+    if (err != NO_ERROR) {
+        // We always bind the texture.
+        glBindTexture(mTexTarget, mTexName);
+        return err;
+    }
+
+    // Bind the new buffer to the GL texture, and wait until it's ready.
+    return bindTextureImageLocked();
 }
 
 status_t SurfaceTexture::acquireBufferLocked(BufferQueue::BufferItem *item) {
@@ -165,161 +208,162 @@
 
     int slot = item->mBuf;
     if (item->mGraphicBuffer != NULL) {
+        // This buffer has not been acquired before, so we must assume
+        // that any EGLImage in mEglSlots is stale.
         if (mEglSlots[slot].mEglImage != EGL_NO_IMAGE_KHR) {
-            eglDestroyImageKHR(mEglDisplay, mEglSlots[slot].mEglImage);
+            if (!eglDestroyImageKHR(mEglDisplay, mEglSlots[slot].mEglImage)) {
+                ST_LOGW("acquireBufferLocked: eglDestroyImageKHR failed for slot=%d",
+                      slot);
+                // keep going
+            }
             mEglSlots[slot].mEglImage = EGL_NO_IMAGE_KHR;
         }
     }
 
-    // Update the GL texture object. We may have to do this even when
-    // item.mGraphicBuffer == NULL, if we destroyed the EGLImage when
-    // detaching from a context but the buffer has not been re-allocated.
-    if (mEglSlots[slot].mEglImage == EGL_NO_IMAGE_KHR) {
-        EGLImageKHR image = createImage(mEglDisplay, mSlots[slot].mGraphicBuffer);
-        if (image == EGL_NO_IMAGE_KHR) {
-            return UNKNOWN_ERROR;
-        }
-        mEglSlots[slot].mEglImage = image;
-    }
-
     return NO_ERROR;
 }
 
 status_t SurfaceTexture::releaseBufferLocked(int buf, EGLDisplay display,
        EGLSyncKHR eglFence) {
-    status_t err = ConsumerBase::releaseBufferLocked(buf, mEglDisplay,
-           eglFence);
+    status_t err = ConsumerBase::releaseBufferLocked(buf, display, eglFence);
 
     mEglSlots[buf].mEglFence = EGL_NO_SYNC_KHR;
 
     return err;
 }
 
-status_t SurfaceTexture::updateTexImage(BufferRejecter* rejecter, bool skipSync) {
-    ATRACE_CALL();
-    ST_LOGV("updateTexImage");
-    Mutex::Autolock lock(mMutex);
-
+status_t SurfaceTexture::releaseAndUpdateLocked(const BufferQueue::BufferItem& item)
+{
     status_t err = NO_ERROR;
 
-    if (mAbandoned) {
-        ST_LOGE("updateTexImage: SurfaceTexture is abandoned!");
-        return NO_INIT;
-    }
-
     if (!mAttached) {
-        ST_LOGE("updateTexImage: SurfaceTexture is not attached to an OpenGL "
+        ST_LOGE("releaseAndUpdate: SurfaceTexture is not attached to an OpenGL "
                 "ES context");
         return INVALID_OPERATION;
     }
 
+    // Confirm state.
+    err = checkAndUpdateEglStateLocked();
+    if (err != NO_ERROR) {
+        return err;
+    }
+
+    int buf = item.mBuf;
+
+    // If the mEglSlot entry is empty, create an EGLImage for the gralloc
+    // buffer currently in the slot in ConsumerBase.
+    //
+    // We may have to do this even when item.mGraphicBuffer == NULL (which
+    // means the buffer was previously acquired), if we destroyed the
+    // EGLImage when detaching from a context but the buffer has not been
+    // re-allocated.
+    if (mEglSlots[buf].mEglImage == EGL_NO_IMAGE_KHR) {
+        EGLImageKHR image = createImage(mEglDisplay, mSlots[buf].mGraphicBuffer);
+        if (image == EGL_NO_IMAGE_KHR) {
+            ST_LOGW("releaseAndUpdate: unable to createImage on display=%p slot=%d",
+                  mEglDisplay, buf);
+            return UNKNOWN_ERROR;
+        }
+        mEglSlots[buf].mEglImage = image;
+    }
+
+    // Do whatever sync ops we need to do before releasing the old slot.
+    err = syncForReleaseLocked(mEglDisplay);
+    if (err != NO_ERROR) {
+        // Release the buffer we just acquired.  It's not safe to
+        // release the old buffer, so instead we just drop the new frame.
+        releaseBufferLocked(buf, mEglDisplay, EGL_NO_SYNC_KHR);
+        return err;
+    }
+
+    ST_LOGV("releaseAndUpdate: (slot=%d buf=%p) -> (slot=%d buf=%p)",
+            mCurrentTexture,
+            mCurrentTextureBuf != NULL ? mCurrentTextureBuf->handle : 0,
+            buf, mSlots[buf].mGraphicBuffer->handle);
+
+    // release old buffer
+    if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
+        status_t status = releaseBufferLocked(mCurrentTexture, mEglDisplay,
+                mEglSlots[mCurrentTexture].mEglFence);
+        if (status != NO_ERROR && status != BufferQueue::STALE_BUFFER_SLOT) {
+            ST_LOGE("releaseAndUpdate: failed to release buffer: %s (%d)",
+                   strerror(-status), status);
+            err = status;
+            // keep going, with error raised [?]
+        }
+    }
+
+    // Update the SurfaceTexture state.
+    mCurrentTexture = buf;
+    mCurrentTextureBuf = mSlots[buf].mGraphicBuffer;
+    mCurrentCrop = item.mCrop;
+    mCurrentTransform = item.mTransform;
+    mCurrentScalingMode = item.mScalingMode;
+    mCurrentTimestamp = item.mTimestamp;
+    mCurrentFence = item.mFence;
+
+    computeCurrentTransformMatrixLocked();
+
+    return err;
+}
+
+status_t SurfaceTexture::bindTextureImageLocked() {
+    if (mEglDisplay == EGL_NO_DISPLAY) {
+        ALOGE("bindTextureImage: invalid display");
+        return INVALID_OPERATION;
+    }
+
+    GLint error;
+    while ((error = glGetError()) != GL_NO_ERROR) {
+        ST_LOGW("bindTextureImage: clearing GL error: %#04x", error);
+    }
+
+    glBindTexture(mTexTarget, mTexName);
+    if (mCurrentTexture == BufferQueue::INVALID_BUFFER_SLOT) {
+        if (mCurrentTextureBuf == NULL) {
+            ST_LOGE("bindTextureImage: no currently-bound texture");
+            return NO_INIT;
+        }
+        status_t err = bindUnslottedBufferLocked(mEglDisplay);
+        if (err != NO_ERROR) {
+            return err;
+        }
+    } else {
+        EGLImageKHR image = mEglSlots[mCurrentTexture].mEglImage;
+
+        glEGLImageTargetTexture2DOES(mTexTarget, (GLeglImageOES)image);
+
+        while ((error = glGetError()) != GL_NO_ERROR) {
+            ST_LOGE("bindTextureImage: error binding external texture image %p"
+                    ": %#04x", image, error);
+            return UNKNOWN_ERROR;
+        }
+    }
+
+    // Wait for the new buffer to be ready.
+    return doGLFenceWaitLocked();
+
+}
+
+status_t SurfaceTexture::checkAndUpdateEglStateLocked() {
     EGLDisplay dpy = eglGetCurrentDisplay();
     EGLContext ctx = eglGetCurrentContext();
 
     if ((mEglDisplay != dpy && mEglDisplay != EGL_NO_DISPLAY) ||
             dpy == EGL_NO_DISPLAY) {
-        ST_LOGE("updateTexImage: invalid current EGLDisplay");
+        ST_LOGE("checkAndUpdateEglState: invalid current EGLDisplay");
         return INVALID_OPERATION;
     }
 
     if ((mEglContext != ctx && mEglContext != EGL_NO_CONTEXT) ||
             ctx == EGL_NO_CONTEXT) {
-        ST_LOGE("updateTexImage: invalid current EGLContext");
+        ST_LOGE("checkAndUpdateEglState: invalid current EGLContext");
         return INVALID_OPERATION;
     }
 
     mEglDisplay = dpy;
     mEglContext = ctx;
-
-    BufferQueue::BufferItem item;
-
-    // In asynchronous mode the list is guaranteed to be one buffer
-    // deep, while in synchronous mode we use the oldest buffer.
-    err = acquireBufferLocked(&item);
-    if (err == NO_ERROR) {
-        int buf = item.mBuf;
-
-        // we call the rejecter here, in case the caller has a reason to
-        // not accept this buffer. this is used by SurfaceFlinger to
-        // reject buffers which have the wrong size
-        if (rejecter && rejecter->reject(mSlots[buf].mGraphicBuffer, item)) {
-            releaseBufferLocked(buf, dpy, EGL_NO_SYNC_KHR);
-            glBindTexture(mTexTarget, mTexName);
-            return NO_ERROR;
-        }
-
-        GLint error;
-        while ((error = glGetError()) != GL_NO_ERROR) {
-            ST_LOGW("updateTexImage: clearing GL error: %#04x", error);
-        }
-
-        EGLImageKHR image = mEglSlots[buf].mEglImage;
-        glBindTexture(mTexTarget, mTexName);
-        glEGLImageTargetTexture2DOES(mTexTarget, (GLeglImageOES)image);
-
-        while ((error = glGetError()) != GL_NO_ERROR) {
-            ST_LOGE("updateTexImage: error binding external texture image %p "
-                    "(slot %d): %#04x", image, buf, error);
-            err = UNKNOWN_ERROR;
-        }
-
-        if (err == NO_ERROR) {
-            err = syncForReleaseLocked(dpy);
-        }
-
-        if (err != NO_ERROR) {
-            // Release the buffer we just acquired.  It's not safe to
-            // release the old buffer, so instead we just drop the new frame.
-            releaseBufferLocked(buf, dpy, EGL_NO_SYNC_KHR);
-            return err;
-        }
-
-        ST_LOGV("updateTexImage: (slot=%d buf=%p) -> (slot=%d buf=%p)",
-                mCurrentTexture,
-                mCurrentTextureBuf != NULL ? mCurrentTextureBuf->handle : 0,
-                buf, mSlots[buf].mGraphicBuffer->handle);
-
-        // release old buffer
-        if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
-            status_t status = releaseBufferLocked(mCurrentTexture, dpy,
-                    mEglSlots[mCurrentTexture].mEglFence);
-            if (status != NO_ERROR && status != BufferQueue::STALE_BUFFER_SLOT) {
-                ST_LOGE("updateTexImage: failed to release buffer: %s (%d)",
-                       strerror(-status), status);
-                err = status;
-            }
-        }
-
-        // Update the SurfaceTexture state.
-        mCurrentTexture = buf;
-        mCurrentTextureBuf = mSlots[buf].mGraphicBuffer;
-        mCurrentCrop = item.mCrop;
-        mCurrentTransform = item.mTransform;
-        mCurrentScalingMode = item.mScalingMode;
-        mCurrentTimestamp = item.mTimestamp;
-        mCurrentFence = item.mFence;
-        if (!skipSync) {
-            // SurfaceFlinger needs to lazily perform GLES synchronization
-            // only when it's actually going to use GLES for compositing.
-            // Eventually SurfaceFlinger should have its own consumer class,
-            // but for now we'll just hack it in to SurfaceTexture.
-            // SurfaceFlinger is responsible for calling doGLFenceWait before
-            // texturing from this SurfaceTexture.
-            doGLFenceWaitLocked();
-        }
-        computeCurrentTransformMatrixLocked();
-    } else  {
-        if (err < 0) {
-            ST_LOGE("updateTexImage: acquire failed: %s (%d)",
-                strerror(-err), err);
-            return err;
-        }
-        // We always bind the texture even if we don't update its contents.
-        glBindTexture(mTexTarget, mTexName);
-        return OK;
-    }
-
-    return err;
+    return NO_ERROR;
 }
 
 void SurfaceTexture::setReleaseFence(int fenceFd) {
@@ -427,30 +471,8 @@
         // The EGLImageKHR that was associated with the slot was destroyed when
         // the SurfaceTexture was detached from the old context, so we need to
         // recreate it here.
-        EGLImageKHR image = createImage(dpy, mCurrentTextureBuf);
-        if (image == EGL_NO_IMAGE_KHR) {
-            return UNKNOWN_ERROR;
-        }
-
-        // Attach the current buffer to the GL texture.
-        glEGLImageTargetTexture2DOES(mTexTarget, (GLeglImageOES)image);
-
-        GLint error;
-        status_t err = OK;
-        while ((error = glGetError()) != GL_NO_ERROR) {
-            ST_LOGE("attachToContext: error binding external texture image %p "
-                    "(slot %d): %#04x", image, mCurrentTexture, error);
-            err = UNKNOWN_ERROR;
-        }
-
-        // We destroy the EGLImageKHR here because the current buffer may no
-        // longer be associated with one of the buffer slots, so we have
-        // nowhere to to store it.  If the buffer is still associated with a
-        // slot then another EGLImageKHR will be created next time that buffer
-        // gets acquired in updateTexImage.
-        eglDestroyImageKHR(dpy, image);
-
-        if (err != OK) {
+        status_t err = bindUnslottedBufferLocked(dpy);
+        if (err != NO_ERROR) {
             return err;
         }
     }
@@ -463,11 +485,43 @@
     return OK;
 }
 
+status_t SurfaceTexture::bindUnslottedBufferLocked(EGLDisplay dpy) {
+    ST_LOGV("bindUnslottedBuffer ct=%d ctb=%p",
+            mCurrentTexture, mCurrentTextureBuf.get());
+
+    // Create a temporary EGLImageKHR.
+    EGLImageKHR image = createImage(dpy, mCurrentTextureBuf);
+    if (image == EGL_NO_IMAGE_KHR) {
+        return UNKNOWN_ERROR;
+    }
+
+    // Attach the current buffer to the GL texture.
+    glEGLImageTargetTexture2DOES(mTexTarget, (GLeglImageOES)image);
+
+    GLint error;
+    status_t err = OK;
+    while ((error = glGetError()) != GL_NO_ERROR) {
+        ST_LOGE("bindUnslottedBuffer: error binding external texture image %p "
+                "(slot %d): %#04x", image, mCurrentTexture, error);
+        err = UNKNOWN_ERROR;
+    }
+
+    // We destroy the EGLImageKHR here because the current buffer may no
+    // longer be associated with one of the buffer slots, so we have
+    // nowhere to to store it.  If the buffer is still associated with a
+    // slot then another EGLImageKHR will be created next time that buffer
+    // gets acquired in updateTexImage.
+    eglDestroyImageKHR(dpy, image);
+
+    return err;
+}
+
+
 status_t SurfaceTexture::syncForReleaseLocked(EGLDisplay dpy) {
     ST_LOGV("syncForReleaseLocked");
 
     if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
-        if (useNativeFenceSync) {
+        if (sUseNativeFenceSync) {
             EGLSyncKHR sync = eglCreateSyncKHR(dpy,
                     EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
             if (sync == EGL_NO_SYNC_KHR) {
diff --git a/libs/gui/SurfaceTextureClient.cpp b/libs/gui/SurfaceTextureClient.cpp
index afdbf04..7588b9e 100644
--- a/libs/gui/SurfaceTextureClient.cpp
+++ b/libs/gui/SurfaceTextureClient.cpp
@@ -41,14 +41,6 @@
     SurfaceTextureClient::setISurfaceTexture(surfaceTexture);
 }
 
-// see SurfaceTextureClient.h
-SurfaceTextureClient::SurfaceTextureClient(const
-         sp<SurfaceTexture>& surfaceTexture)
-{
-    SurfaceTextureClient::init();
-    SurfaceTextureClient::setISurfaceTexture(surfaceTexture->getBufferQueue());
-}
-
 SurfaceTextureClient::SurfaceTextureClient() {
     SurfaceTextureClient::init();
 }
diff --git a/libs/gui/tests/SurfaceTextureClient_test.cpp b/libs/gui/tests/SurfaceTextureClient_test.cpp
index ec14a0d..baeca06 100644
--- a/libs/gui/tests/SurfaceTextureClient_test.cpp
+++ b/libs/gui/tests/SurfaceTextureClient_test.cpp
@@ -41,7 +41,7 @@
                 testInfo->name());
 
         mST = new SurfaceTexture(123);
-        mSTC = new SurfaceTextureClient(mST);
+        mSTC = new SurfaceTextureClient(mST->getBufferQueue());
         mANW = mSTC;
 
         // We need a valid GL context so we can test updateTexImage()
@@ -686,7 +686,7 @@
 
         for (int i = 0; i < NUM_SURFACE_TEXTURES; i++) {
             sp<SurfaceTexture> st(new SurfaceTexture(i));
-            sp<SurfaceTextureClient> stc(new SurfaceTextureClient(st));
+            sp<SurfaceTextureClient> stc(new SurfaceTextureClient(st->getBufferQueue()));
             mEglSurfaces[i] = eglCreateWindowSurface(mEglDisplay, myConfig,
                     static_cast<ANativeWindow*>(stc.get()), NULL);
             ASSERT_EQ(EGL_SUCCESS, eglGetError());
diff --git a/libs/gui/tests/SurfaceTexture_test.cpp b/libs/gui/tests/SurfaceTexture_test.cpp
index d9b40cf..58976ad 100644
--- a/libs/gui/tests/SurfaceTexture_test.cpp
+++ b/libs/gui/tests/SurfaceTexture_test.cpp
@@ -385,7 +385,7 @@
     virtual void SetUp() {
         GLTest::SetUp();
         mST = new SurfaceTexture(TEX_ID);
-        mSTC = new SurfaceTextureClient(mST);
+        mSTC = new SurfaceTextureClient(mST->getBufferQueue());
         mANW = mSTC;
         mTextureRenderer = new TextureRenderer(TEX_ID, mST);
         ASSERT_NO_FATAL_FAILURE(mTextureRenderer->SetUp());
diff --git a/libs/utils/Android.mk b/libs/utils/Android.mk
index 73a98d5..cbfe7bd 100644
--- a/libs/utils/Android.mk
+++ b/libs/utils/Android.mk
@@ -26,6 +26,7 @@
 	FileMap.cpp \
 	Flattenable.cpp \
 	JenkinsHash.cpp \
+	LinearAllocator.cpp \
 	LinearTransform.cpp \
 	Log.cpp \
 	PropertyMap.cpp \
@@ -112,6 +113,10 @@
 LOCAL_LDLIBS += -lrt -ldl
 endif
 
+ifeq ($(TARGET_ARCH),mips)
+LOCAL_CFLAGS += -DALIGN_DOUBLE
+endif
+
 LOCAL_C_INCLUDES += \
 		bionic/libc/private \
 		external/zlib
diff --git a/libs/utils/LinearAllocator.cpp b/libs/utils/LinearAllocator.cpp
new file mode 100644
index 0000000..a07a291
--- /dev/null
+++ b/libs/utils/LinearAllocator.cpp
@@ -0,0 +1,227 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "LinearAllocator"
+#define LOG_NDEBUG 1
+
+#include <stdlib.h>
+#include <utils/LinearAllocator.h>
+#include <utils/Log.h>
+
+
+// The ideal size of a page allocation (these need to be multiples of 8)
+#define INITIAL_PAGE_SIZE ((size_t)4096) // 4kb
+#define MAX_PAGE_SIZE ((size_t)131072) // 128kb
+
+// The maximum amount of wasted space we can have per page
+// Allocations exceeding this will have their own dedicated page
+// If this is too low, we will malloc too much
+// Too high, and we may waste too much space
+// Must be smaller than INITIAL_PAGE_SIZE
+#define MAX_WASTE_SIZE ((size_t)1024)
+
+#if ALIGN_DOUBLE
+#define ALIGN_SZ (sizeof(double))
+#else
+#define ALIGN_SZ (sizeof(int))
+#endif
+
+#define ALIGN(x) ((x + ALIGN_SZ - 1 ) & ~(ALIGN_SZ - 1))
+#define ALIGN_PTR(p) ((void*)(ALIGN((size_t)p)))
+
+#if LOG_NDEBUG
+#define ADD_ALLOCATION(size)
+#define RM_ALLOCATION(size)
+#else
+#include <utils/Thread.h>
+#include <utils/Timers.h>
+static size_t s_totalAllocations = 0;
+static nsecs_t s_nextLog = 0;
+static android::Mutex s_mutex;
+
+static void _logUsageLocked() {
+    nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
+    if (now > s_nextLog) {
+        s_nextLog = now + milliseconds_to_nanoseconds(10);
+        ALOGV("Total memory usage: %zu kb", s_totalAllocations / 1024);
+    }
+}
+
+static void _addAllocation(size_t size) {
+    android::AutoMutex lock(s_mutex);
+    s_totalAllocations += size;
+    _logUsageLocked();
+}
+
+#define ADD_ALLOCATION(size) _addAllocation(size);
+#define RM_ALLOCATION(size) _addAllocation(-size);
+#endif
+
+#define min(x,y) (((x) < (y)) ? (x) : (y))
+
+namespace android {
+
+class LinearAllocator::Page {
+public:
+    Page* next() { return mNextPage; }
+    void setNext(Page* next) { mNextPage = next; }
+
+    Page()
+        : mNextPage(0)
+    {}
+
+    void* operator new(size_t size, void* buf) { return buf; }
+
+    void* start() {
+        return (void*) (((size_t)this) + sizeof(Page));
+    }
+
+    void* end(int pageSize) {
+        return (void*) (((size_t)start()) + pageSize);
+    }
+
+private:
+    Page(const Page& other) {}
+    Page* mNextPage;
+};
+
+LinearAllocator::LinearAllocator()
+    : mPageSize(INITIAL_PAGE_SIZE)
+    , mMaxAllocSize(MAX_WASTE_SIZE)
+    , mNext(0)
+    , mCurrentPage(0)
+    , mPages(0)
+    , mTotalAllocated(0)
+    , mWastedSpace(0)
+    , mPageCount(0)
+    , mDedicatedPageCount(0) {}
+
+LinearAllocator::~LinearAllocator(void) {
+    Page* p = mPages;
+    while (p) {
+        Page* next = p->next();
+        p->~Page();
+        free(p);
+        RM_ALLOCATION(mPageSize);
+        p = next;
+    }
+}
+
+void* LinearAllocator::start(Page* p) {
+    return ALIGN_PTR(((size_t*)p) + sizeof(Page));
+}
+
+void* LinearAllocator::end(Page* p) {
+    return ((char*)p) + mPageSize;
+}
+
+bool LinearAllocator::fitsInCurrentPage(size_t size) {
+    return mNext && ((char*)mNext + size) <= end(mCurrentPage);
+}
+
+void LinearAllocator::ensureNext(size_t size) {
+    if (fitsInCurrentPage(size)) return;
+
+    if (mCurrentPage && mPageSize < MAX_PAGE_SIZE) {
+        mPageSize = min(MAX_PAGE_SIZE, mPageSize * 2);
+        mPageSize = ALIGN(mPageSize);
+    }
+    mWastedSpace += mPageSize;
+    Page* p = newPage(mPageSize);
+    if (mCurrentPage) {
+        mCurrentPage->setNext(p);
+    }
+    mCurrentPage = p;
+    if (!mPages) {
+        mPages = mCurrentPage;
+    }
+    mNext = start(mCurrentPage);
+}
+
+void* LinearAllocator::alloc(size_t size) {
+    size = ALIGN(size);
+    if (size > mMaxAllocSize && !fitsInCurrentPage(size)) {
+        ALOGV("Exceeded max size %zu > %zu", size, mMaxAllocSize);
+        // Allocation is too large, create a dedicated page for the allocation
+        Page* page = newPage(size);
+        mDedicatedPageCount++;
+        page->setNext(mPages);
+        mPages = page;
+        if (!mCurrentPage)
+            mCurrentPage = mPages;
+        return start(page);
+    }
+    ensureNext(size);
+    void* ptr = mNext;
+    mNext = ((char*)mNext) + size;
+    mWastedSpace -= size;
+    return ptr;
+}
+
+void LinearAllocator::rewindIfLastAlloc(void* ptr, size_t allocSize) {
+    // Don't bother rewinding across pages
+    allocSize = ALIGN(allocSize);
+    if (ptr >= start(mCurrentPage) && ptr < end(mCurrentPage)
+            && ptr == ((char*)mNext - allocSize)) {
+        mTotalAllocated -= allocSize;
+        mWastedSpace += allocSize;
+        mNext = ptr;
+    }
+}
+
+LinearAllocator::Page* LinearAllocator::newPage(size_t pageSize) {
+    pageSize = ALIGN(pageSize + sizeof(LinearAllocator::Page));
+    ADD_ALLOCATION(pageSize);
+    mTotalAllocated += pageSize;
+    mPageCount++;
+    void* buf = malloc(pageSize);
+    return new (buf) Page();
+}
+
+static const char* toSize(size_t value, float& result) {
+    if (value < 2000) {
+        result = value;
+        return "B";
+    }
+    if (value < 2000000) {
+        result = value / 1024.0f;
+        return "KB";
+    }
+    result = value / 1048576.0f;
+    return "MB";
+}
+
+void LinearAllocator::dumpMemoryStats(const char* prefix) {
+    float prettySize;
+    const char* prettySuffix;
+    prettySuffix = toSize(mTotalAllocated, prettySize);
+    ALOGD("%sTotal allocated: %.2f%s", prefix, prettySize, prettySuffix);
+    prettySuffix = toSize(mWastedSpace, prettySize);
+    ALOGD("%sWasted space: %.2f%s (%.1f%%)", prefix, prettySize, prettySuffix,
+          (float) mWastedSpace / (float) mTotalAllocated * 100.0f);
+    ALOGD("%sPages %zu (dedicated %zu)", prefix, mPageCount, mDedicatedPageCount);
+}
+
+}; // namespace android
diff --git a/opengl/libs/Android.mk b/opengl/libs/Android.mk
index 31bfcd7..6c35355 100644
--- a/opengl/libs/Android.mk
+++ b/opengl/libs/Android.mk
@@ -4,6 +4,20 @@
 # Build META EGL library
 #
 
+egl.cfg_config_module :=
+# OpenGL drivers config file
+ifneq ($(BOARD_EGL_CFG),)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := egl.cfg
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_PATH := $(TARGET_OUT)/lib/egl
+LOCAL_SRC_FILES := ../../../../$(BOARD_EGL_CFG)
+include $(BUILD_PREBUILT)
+egl.cfg_config_module := $(LOCAL_MODULE)
+endif
+
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= 	       \
@@ -65,24 +79,10 @@
   LOCAL_CFLAGS += -DMAX_EGL_CACHE_SIZE=$(MAX_EGL_CACHE_SIZE)
 endif
 
+LOCAL_REQUIRED_MODULES := $(egl.cfg_config_module)
+egl.cfg_config_module :=
+
 include $(BUILD_SHARED_LIBRARY)
-installed_libEGL := $(LOCAL_INSTALLED_MODULE)
-
-# OpenGL drivers config file
-ifneq ($(BOARD_EGL_CFG),)
-
-include $(CLEAR_VARS)
-LOCAL_MODULE := egl.cfg
-LOCAL_MODULE_TAGS := optional
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT)/lib/egl
-LOCAL_SRC_FILES := ../../../../$(BOARD_EGL_CFG)
-include $(BUILD_PREBUILT)
-
-# make sure we depend on egl.cfg, so it gets installed
-$(installed_libEGL): | egl.cfg
-
-endif
 
 ###############################################################################
 # Build the wrapper OpenGL ES 1.x library
diff --git a/services/surfaceflinger/Android.mk b/services/surfaceflinger/Android.mk
index 329bbd5..b4b19b4 100644
--- a/services/surfaceflinger/Android.mk
+++ b/services/surfaceflinger/Android.mk
@@ -11,12 +11,12 @@
     LayerDim.cpp                            \
     LayerScreenshot.cpp                     \
     DisplayHardware/FramebufferSurface.cpp  \
-    DisplayHardware/GraphicBufferAlloc.cpp  \
     DisplayHardware/HWComposer.cpp          \
     DisplayHardware/PowerHAL.cpp            \
     GLExtensions.cpp                        \
     MessageQueue.cpp                        \
     SurfaceFlinger.cpp                      \
+    SurfaceFlingerConsumer.cpp              \
     SurfaceTextureLayer.cpp                 \
     Transform.cpp                           \
     
diff --git a/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
index 6c86a53..cccb29b 100644
--- a/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
+++ b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
@@ -30,10 +30,10 @@
 
 #include <hardware/hardware.h>
 #include <gui/SurfaceTextureClient.h>
+#include <gui/GraphicBufferAlloc.h>
 #include <ui/GraphicBuffer.h>
 
 #include "DisplayHardware/FramebufferSurface.h"
-#include "DisplayHardware/GraphicBufferAlloc.h"
 #include "DisplayHardware/HWComposer.h"
 
 #ifndef NUM_FRAMEBUFFER_SURFACE_BUFFERS
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 6bed20a..a1d46d9 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -73,7 +73,7 @@
         HWComposer::HWCLayerInterface* layer) {
     LayerBaseClient::onLayerDisplayed(hw, layer);
     if (layer) {
-        mSurfaceTexture->setReleaseFence(layer->getAndResetReleaseFenceFd());
+        mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFenceFd());
     }
 }
 
@@ -81,20 +81,20 @@
 {
     LayerBaseClient::onFirstRef();
 
-    // Creates a custom BufferQueue for SurfaceTexture to use
+    // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
     sp<BufferQueue> bq = new SurfaceTextureLayer();
-    mSurfaceTexture = new SurfaceTexture(mTextureName, true,
+    mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(mTextureName, true,
             GL_TEXTURE_EXTERNAL_OES, false, bq);
 
-    mSurfaceTexture->setConsumerUsageBits(getEffectiveUsage(0));
-    mSurfaceTexture->setFrameAvailableListener(this);
-    mSurfaceTexture->setSynchronousMode(true);
+    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
+    mSurfaceFlingerConsumer->setFrameAvailableListener(this);
+    mSurfaceFlingerConsumer->setSynchronousMode(true);
 
 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
 #warning "disabling triple buffering"
-    mSurfaceTexture->setDefaultMaxBufferCount(2);
+    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(2);
 #else
-    mSurfaceTexture->setDefaultMaxBufferCount(3);
+    mSurfaceFlingerConsumer->setDefaultMaxBufferCount(3);
 #endif
 
     const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
@@ -115,12 +115,12 @@
 // in the purgatory list
 void Layer::onRemoved()
 {
-    mSurfaceTexture->abandon();
+    mSurfaceFlingerConsumer->abandon();
 }
 
 void Layer::setName(const String8& name) {
     LayerBase::setName(name);
-    mSurfaceTexture->setName(name);
+    mSurfaceFlingerConsumer->setName(name);
 }
 
 sp<ISurface> Layer::createSurface()
@@ -131,7 +131,7 @@
             sp<ISurfaceTexture> res;
             sp<const Layer> that( mOwner.promote() );
             if (that != NULL) {
-                res = that->mSurfaceTexture->getBufferQueue();
+                res = that->mSurfaceFlingerConsumer->getBufferQueue();
             }
             return res;
         }
@@ -146,7 +146,7 @@
 
 wp<IBinder> Layer::getSurfaceTextureBinder() const
 {
-    return mSurfaceTexture->getBufferQueue()->asBinder();
+    return mSurfaceFlingerConsumer->getBufferQueue()->asBinder();
 }
 
 status_t Layer::setBuffers( uint32_t w, uint32_t h,
@@ -177,15 +177,15 @@
     mOpaqueLayer = (flags & ISurfaceComposerClient::eOpaque);
     mCurrentOpacity = getOpacityForFormat(format);
 
-    mSurfaceTexture->setDefaultBufferSize(w, h);
-    mSurfaceTexture->setDefaultBufferFormat(format);
-    mSurfaceTexture->setConsumerUsageBits(getEffectiveUsage(0));
+    mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
+    mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
+    mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
 
     return NO_ERROR;
 }
 
 Rect Layer::computeBufferCrop() const {
-    // Start with the SurfaceTexture's buffer crop...
+    // Start with the SurfaceFlingerConsumer's buffer crop...
     Rect crop;
     if (!mCurrentCrop.isEmpty()) {
         crop = mCurrentCrop;
@@ -202,7 +202,7 @@
     if (!s.active.crop.isEmpty()) {
         // Transform the window crop to match the buffer coordinate system,
         // which means using the inverse of the current transform set on the
-        // SurfaceTexture.
+        // SurfaceFlingerConsumer.
         uint32_t invTransform = mCurrentTransform;
         int winWidth = s.active.w;
         int winHeight = s.active.h;
@@ -284,7 +284,7 @@
     // acquire fence the first time a new buffer is acquired on EACH display.
 
     if (layer.getCompositionType() == HWC_OVERLAY) {
-        sp<Fence> fence = mSurfaceTexture->getCurrentFence();
+        sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
         if (fence.get()) {
             fenceFd = fence->dup();
             if (fenceFd == -1) {
@@ -327,9 +327,11 @@
         return;
     }
 
-    status_t err = mSurfaceTexture->doGLFenceWait();
-    if (err != OK) {
-        ALOGE("onDraw: failed waiting for fence: %d", err);
+    // Bind the current buffer to the GL texture, and wait for it to be
+    // ready for us to draw into.
+    status_t err = mSurfaceFlingerConsumer->bindTextureImage();
+    if (err != NO_ERROR) {
+        ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
         // Go ahead and draw the buffer anyway; no matter what we do the screen
         // is probably going to have something visibly wrong.
     }
@@ -342,8 +344,8 @@
 
         // Query the texture matrix given our current filtering mode.
         float textureMatrix[16];
-        mSurfaceTexture->setFilteringEnabled(useFiltering);
-        mSurfaceTexture->getTransformMatrix(textureMatrix);
+        mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
+        mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
 
         // Set things up for texturing.
         glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTextureName);
@@ -462,7 +464,7 @@
 
         // record the new size, form this point on, when the client request
         // a buffer, it'll get the new size.
-        mSurfaceTexture->setDefaultBufferSize(
+        mSurfaceFlingerConsumer->setDefaultBufferSize(
                 temp.requested.w, temp.requested.h);
     }
 
@@ -507,10 +509,10 @@
 
 void Layer::onPostComposition() {
     if (mFrameLatencyNeeded) {
-        nsecs_t desiredPresentTime = mSurfaceTexture->getTimestamp();
+        nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
         mFrameTracker.setDesiredPresentTime(desiredPresentTime);
 
-        sp<Fence> frameReadyFence = mSurfaceTexture->getCurrentFence();
+        sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
         if (frameReadyFence != NULL) {
             mFrameTracker.setFrameReadyFence(frameReadyFence);
         } else {
@@ -521,6 +523,9 @@
 
         const HWComposer& hwc = mFlinger->getHwComposer();
         sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
+        // XXX: Temporarily don't use the present fence from HWC to work
+        // around a driver bug.
+        presentFence.clear();
         if (presentFence != NULL) {
             mFrameTracker.setActualPresentFence(presentFence);
         } else {
@@ -564,7 +569,7 @@
             mFlinger->signalLayerUpdate();
         }
 
-        struct Reject : public SurfaceTexture::BufferRejecter {
+        struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
             Layer::State& front;
             Layer::State& current;
             bool& recomputeVisibleRegions;
@@ -649,14 +654,14 @@
 
         Reject r(mDrawingState, currentState(), recomputeVisibleRegions);
 
-        if (mSurfaceTexture->updateTexImage(&r, true) < NO_ERROR) {
+        if (mSurfaceFlingerConsumer->updateTexImage(&r) != NO_ERROR) {
             // something happened!
             recomputeVisibleRegions = true;
             return outDirtyRegion;
         }
 
         // update the active buffer
-        mActiveBuffer = mSurfaceTexture->getCurrentBuffer();
+        mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
         if (mActiveBuffer == NULL) {
             // this can only happen if the very first buffer was rejected.
             return outDirtyRegion;
@@ -670,9 +675,9 @@
             recomputeVisibleRegions = true;
          }
 
-        Rect crop(mSurfaceTexture->getCurrentCrop());
-        const uint32_t transform(mSurfaceTexture->getCurrentTransform());
-        const uint32_t scalingMode(mSurfaceTexture->getCurrentScalingMode());
+        Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
+        const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
+        const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
         if ((crop != mCurrentCrop) ||
             (transform != mCurrentTransform) ||
             (scalingMode != mCurrentScalingMode))
@@ -731,8 +736,8 @@
 
     result.append(buffer);
 
-    if (mSurfaceTexture != 0) {
-        mSurfaceTexture->dump(result, "            ", buffer, SIZE);
+    if (mSurfaceFlingerConsumer != 0) {
+        mSurfaceFlingerConsumer->dump(result, "            ", buffer, SIZE);
     }
 }
 
@@ -774,7 +779,7 @@
             orientation = 0;
         }
     }
-    mSurfaceTexture->setTransformHint(orientation);
+    mSurfaceFlingerConsumer->setTransformHint(orientation);
 }
 
 // ---------------------------------------------------------------------------
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index 5ea3eb4..2d4afc4 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -20,8 +20,6 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <gui/SurfaceTexture.h>
-
 #include <utils/Timers.h>
 
 #include <ui/GraphicBuffer.h>
@@ -34,6 +32,7 @@
 #include <GLES/gl.h>
 #include <GLES/glext.h>
 
+#include "SurfaceFlingerConsumer.h"
 #include "FrameTracker.h"
 #include "LayerBase.h"
 #include "SurfaceTextureLayer.h"
@@ -49,7 +48,7 @@
 // ---------------------------------------------------------------------------
 
 class Layer : public LayerBaseClient,
-              public SurfaceTexture::FrameAvailableListener
+              public SurfaceFlingerConsumer::FrameAvailableListener
 {
 public:
             Layer(SurfaceFlinger* flinger, const sp<Client>& client);
@@ -92,7 +91,7 @@
     // only for debugging
     inline const sp<GraphicBuffer>& getActiveBuffer() const { return mActiveBuffer; }
 
-    // Updates the transform hint in our SurfaceTexture to match
+    // Updates the transform hint in our SurfaceFlingerConsumer to match
     // the current orientation of the display device.
     virtual void updateTransformHint(const sp<const DisplayDevice>& hw) const;
 
@@ -110,13 +109,13 @@
     Rect computeBufferCrop() const;
     static bool getOpacityForFormat(uint32_t format);
 
-    // Interface implementation for SurfaceTexture::FrameAvailableListener
+    // Interface implementation for SurfaceFlingerConsumer::FrameAvailableListener
     virtual void onFrameAvailable();
 
     // -----------------------------------------------------------------------
 
     // constants
-    sp<SurfaceTexture> mSurfaceTexture;
+    sp<SurfaceFlingerConsumer> mSurfaceFlingerConsumer;
     GLuint mTextureName;
 
     // thread-safe
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 41c5cce..f65b82f 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -40,6 +40,7 @@
 #include <gui/GuiConfig.h>
 #include <gui/IDisplayEventConnection.h>
 #include <gui/SurfaceTextureClient.h>
+#include <gui/GraphicBufferAlloc.h>
 
 #include <ui/GraphicBufferAllocator.h>
 #include <ui/PixelFormat.h>
@@ -65,7 +66,6 @@
 #include "SurfaceFlinger.h"
 
 #include "DisplayHardware/FramebufferSurface.h"
-#include "DisplayHardware/GraphicBufferAlloc.h"
 #include "DisplayHardware/HWComposer.h"
 
 
diff --git a/services/surfaceflinger/SurfaceFlingerConsumer.cpp b/services/surfaceflinger/SurfaceFlingerConsumer.cpp
new file mode 100644
index 0000000..a316896
--- /dev/null
+++ b/services/surfaceflinger/SurfaceFlingerConsumer.cpp
@@ -0,0 +1,102 @@
+/*
+ * 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.
+ */
+
+#define ATRACE_TAG ATRACE_TAG_GRAPHICS
+
+#include "SurfaceFlingerConsumer.h"
+
+#include <utils/Trace.h>
+#include <utils/Errors.h>
+
+
+namespace android {
+
+// ---------------------------------------------------------------------------
+
+status_t SurfaceFlingerConsumer::updateTexImage(BufferRejecter* rejecter)
+{
+    ATRACE_CALL();
+    ALOGV("updateTexImage");
+    Mutex::Autolock lock(mMutex);
+
+    if (mAbandoned) {
+        ALOGE("updateTexImage: SurfaceTexture is abandoned!");
+        return NO_INIT;
+    }
+
+    // Make sure the EGL state is the same as in previous calls.
+    status_t err = checkAndUpdateEglStateLocked();
+    if (err != NO_ERROR) {
+        return err;
+    }
+
+    BufferQueue::BufferItem item;
+
+    // Acquire the next buffer.
+    // In asynchronous mode the list is guaranteed to be one buffer
+    // deep, while in synchronous mode we use the oldest buffer.
+    err = acquireBufferLocked(&item);
+    if (err != NO_ERROR) {
+        if (err == BufferQueue::NO_BUFFER_AVAILABLE) {
+            // This variant of updateTexImage does not guarantee that the
+            // texture is bound, so no need to call glBindTexture.
+            err = NO_ERROR;
+        } else {
+            ALOGE("updateTexImage: acquire failed: %s (%d)",
+                strerror(-err), err);
+        }
+        return err;
+    }
+
+
+    // We call the rejecter here, in case the caller has a reason to
+    // not accept this buffer.  This is used by SurfaceFlinger to
+    // reject buffers which have the wrong size
+    int buf = item.mBuf;
+    if (rejecter && rejecter->reject(mSlots[buf].mGraphicBuffer, item)) {
+        releaseBufferLocked(buf, EGL_NO_SYNC_KHR);
+        return NO_ERROR;
+    }
+
+    // Release the previous buffer.
+    err = releaseAndUpdateLocked(item);
+    if (err != NO_ERROR) {
+        return err;
+    }
+
+    if (!sUseNativeFenceSync) {
+        // Bind the new buffer to the GL texture.
+        //
+        // Older devices require the "implicit" synchronization provided
+        // by glEGLImageTargetTexture2DOES, which this method calls.  Newer
+        // devices will either call this in Layer::onDraw, or (if it's not
+        // a GL-composited layer) not at all.
+        err = bindTextureImageLocked();
+    }
+
+    return err;
+}
+
+status_t SurfaceFlingerConsumer::bindTextureImage()
+{
+    Mutex::Autolock lock(mMutex);
+
+    return bindTextureImageLocked();
+}
+
+// ---------------------------------------------------------------------------
+}; // namespace android
+
diff --git a/services/surfaceflinger/SurfaceFlingerConsumer.h b/services/surfaceflinger/SurfaceFlingerConsumer.h
new file mode 100644
index 0000000..308a288
--- /dev/null
+++ b/services/surfaceflinger/SurfaceFlingerConsumer.h
@@ -0,0 +1,59 @@
+/*
+ * 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_SURFACEFLINGERCONSUMER_H
+#define ANDROID_SURFACEFLINGERCONSUMER_H
+
+#include <gui/SurfaceTexture.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+/*
+ * This is a thin wrapper around SurfaceTexture.
+ */
+class SurfaceFlingerConsumer : public SurfaceTexture {
+public:
+    SurfaceFlingerConsumer(GLuint tex, bool allowSynchronousMode = true,
+            GLenum texTarget = GL_TEXTURE_EXTERNAL_OES, bool useFenceSync = true,
+            const sp<BufferQueue> &bufferQueue = 0)
+        : SurfaceTexture(tex, allowSynchronousMode, texTarget, useFenceSync,
+            bufferQueue)
+    {}
+
+    class BufferRejecter {
+        friend class SurfaceFlingerConsumer;
+        virtual bool reject(const sp<GraphicBuffer>& buf,
+                const BufferQueue::BufferItem& item) = 0;
+
+    protected:
+        virtual ~BufferRejecter() { }
+    };
+
+    // This version of updateTexImage() takes a functor that may be used to
+    // reject the newly acquired buffer.  Unlike the SurfaceTexture version,
+    // this does not guarantee that the buffer has been bound to the GL
+    // texture.
+    status_t updateTexImage(BufferRejecter* rejecter);
+
+    // See SurfaceTexture::bindTextureImageLocked().
+    status_t bindTextureImage();
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_SURFACEFLINGERCONSUMER_H