am 105aa28e: am b275b4dc: am 3949f664: Merge "SurfaceFlinger: Fix null pointer exception"

* commit '105aa28eeff9d31eebc7645aecb7630918a09b2a':
  SurfaceFlinger: Fix null pointer exception
diff --git a/cmds/dumpstate/dumpstate.c b/cmds/dumpstate/dumpstate.c
index 84f079d..0cad9d8 100644
--- a/cmds/dumpstate/dumpstate.c
+++ b/cmds/dumpstate/dumpstate.c
@@ -245,8 +245,6 @@
     run_command("LAST LOGCAT", 10, "logcat", "-L", "-v", "threadtime",
                                              "-b", "all", "-d", "*:v", NULL);
 
-    for_each_userid(do_dump_settings, NULL);
-
     /* The following have a tendency to get wedged when wifi drivers/fw goes belly-up. */
 
     run_command("NETWORK INTERFACES", 10, "ip", "link", NULL);
diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h
index d17a677..8335e26 100644
--- a/cmds/dumpstate/dumpstate.h
+++ b/cmds/dumpstate/dumpstate.h
@@ -26,7 +26,6 @@
 
 typedef void (for_each_pid_func)(int, const char *);
 typedef void (for_each_tid_func)(int, int, const char *);
-typedef void (for_each_userid_func)(int);
 
 /* prints the contents of a file */
 int dump_file(const char *title, const char *path);
@@ -57,9 +56,6 @@
 /* for each thread in the system, run the specified function */
 void for_each_tid(for_each_tid_func func, const char *header);
 
-/* for each user id in the system, run the specified function */
-void for_each_userid(for_each_userid_func func, const char *header);
-
 /* Displays a blocked processes in-kernel wait channel */
 void show_wchan(int pid, int tid, const char *name);
 
@@ -69,9 +65,6 @@
 /* Gets the dmesg output for the kernel */
 void do_dmesg();
 
-/* Dumps settings for a given user id */
-void do_dump_settings(int userid);
-
 /* Prints the contents of all the routing tables, both IPv4 and IPv6. */
 void dump_route_tables();
 
diff --git a/cmds/dumpstate/utils.c b/cmds/dumpstate/utils.c
index 27b9fb1..48f59e1 100644
--- a/cmds/dumpstate/utils.c
+++ b/cmds/dumpstate/utils.c
@@ -206,22 +206,6 @@
     return;
 }
 
-void do_dump_settings(int userid) {
-    char title[255];
-    char dbpath[255];
-    char sql[255];
-    sprintf(title, "SYSTEM SETTINGS (user %d)", userid);
-    if (userid == 0) {
-        strcpy(dbpath, "/data/data/com.android.providers.settings/databases/settings.db");
-        strcpy(sql, "pragma user_version; select * from system; select * from secure; select * from global;");
-    } else {
-        sprintf(dbpath, "/data/system/users/%d/settings.db", userid);
-        strcpy(sql, "pragma user_version; select * from system; select * from secure;");
-    }
-    run_command(title, 20, SU_PATH, "root", "sqlite3", dbpath, sql, NULL);
-    return;
-}
-
 void do_dmesg() {
     printf("------ KERNEL LOG (dmesg) ------\n");
     /* Get size of kernel buffer */
diff --git a/include/binder/IProcessInfoService.h b/include/binder/IProcessInfoService.h
new file mode 100644
index 0000000..dc62f45
--- /dev/null
+++ b/include/binder/IProcessInfoService.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2015 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_I_PROCESS_INFO_SERVICE_H
+#define ANDROID_I_PROCESS_INFO_SERVICE_H
+
+#include <binder/IInterface.h>
+
+namespace android {
+
+// ----------------------------------------------------------------------
+
+class IProcessInfoService : public IInterface {
+public:
+    DECLARE_META_INTERFACE(ProcessInfoService);
+
+    virtual status_t    getProcessStatesFromPids( size_t length,
+                                                  /*in*/ int32_t* pids,
+                                                  /*out*/ int32_t* states) = 0;
+
+    enum {
+        GET_PROCESS_STATES_FROM_PIDS = IBinder::FIRST_CALL_TRANSACTION,
+    };
+};
+
+// ----------------------------------------------------------------------
+
+class BnProcessInfoService : public BnInterface<IProcessInfoService> {
+public:
+    virtual status_t    onTransact( uint32_t code,
+                                    const Parcel& data,
+                                    Parcel* reply,
+                                    uint32_t flags = 0);
+};
+
+// ----------------------------------------------------------------------
+
+}; // namespace android
+
+#endif // ANDROID_I_PROCESS_INFO_SERVICE_H
diff --git a/include/binder/ProcessInfoService.h b/include/binder/ProcessInfoService.h
new file mode 100644
index 0000000..c5ead20
--- /dev/null
+++ b/include/binder/ProcessInfoService.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2015 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_PROCESS_INFO_SERVICE_H
+#define ANDROID_PROCESS_INFO_SERVICE_H
+
+#include <binder/IProcessInfoService.h>
+#include <utils/Errors.h>
+#include <utils/Singleton.h>
+#include <sys/types.h>
+
+namespace android {
+
+// ----------------------------------------------------------------------
+
+class ProcessInfoService : public Singleton<ProcessInfoService> {
+
+    friend class Singleton<ProcessInfoService>;
+    sp<IProcessInfoService> mProcessInfoService;
+    Mutex mProcessInfoLock;
+
+    ProcessInfoService();
+
+    status_t getProcessStatesImpl(size_t length, /*in*/ int32_t* pids, /*out*/ int32_t* states);
+    void updateBinderLocked();
+
+    static const int BINDER_ATTEMPT_LIMIT = 5;
+
+public:
+
+    /**
+     * For each PID in the given "pids" input array, write the current process state
+     * for that process into the "states" output array, or
+     * ActivityManager.PROCESS_STATE_NONEXISTENT * to indicate that no process with the given PID
+     * exists.
+     *
+     * Returns NO_ERROR if this operation was successful, or a negative error code otherwise.
+     */
+    static status_t getProcessStatesFromPids(size_t length, /*in*/ int32_t* pids,
+            /*out*/ int32_t* states) {
+        return ProcessInfoService::getInstance().getProcessStatesImpl(length, /*in*/ pids,
+                /*out*/ states);
+    }
+
+};
+
+// ----------------------------------------------------------------------
+
+}; // namespace android
+
+#endif // ANDROID_PROCESS_INFO_SERVICE_H
+
diff --git a/include/gui/BufferItem.h b/include/gui/BufferItem.h
index 01b6ff4..c7a8bc9 100644
--- a/include/gui/BufferItem.h
+++ b/include/gui/BufferItem.h
@@ -78,6 +78,11 @@
     // automatically when the buffer was queued.
     bool mIsAutoTimestamp;
 
+    // mDataSpace is the current dataSpace value for this buffer slot. This gets
+    // set by queueBuffer each time this slot is queued. The meaning of the
+    // dataSpace is format-dependent.
+    android_dataspace mDataSpace;
+
     // mFrameNumber is the number of the queued frame for this slot.
     uint64_t mFrameNumber;
 
diff --git a/include/gui/BufferItemConsumer.h b/include/gui/BufferItemConsumer.h
index 5494ff1..45f329e 100644
--- a/include/gui/BufferItemConsumer.h
+++ b/include/gui/BufferItemConsumer.h
@@ -95,7 +95,14 @@
     // setDefaultBufferFormat allows the BufferQueue to create
     // GraphicBuffers of a defaultFormat if no format is specified
     // in dequeueBuffer
-    status_t setDefaultBufferFormat(uint32_t defaultFormat);
+    status_t setDefaultBufferFormat(PixelFormat defaultFormat);
+
+    // setDefaultBufferDataSpace allows the BufferQueue to create
+    // GraphicBuffers of a defaultDataSpace if no data space is specified
+    // in queueBuffer.
+    // The initial default is HAL_DATASPACE_UNKNOWN
+    status_t setDefaultBufferDataSpace(android_dataspace defaultDataSpace);
+
 };
 
 } // namespace android
diff --git a/include/gui/BufferQueueConsumer.h b/include/gui/BufferQueueConsumer.h
index 1912ed0..9c91fc7 100644
--- a/include/gui/BufferQueueConsumer.h
+++ b/include/gui/BufferQueueConsumer.h
@@ -125,9 +125,15 @@
 
     // setDefaultBufferFormat allows the BufferQueue to create
     // GraphicBuffers of a defaultFormat if no format is specified
-    // in dequeueBuffer.  Formats are enumerated in graphics.h; the
-    // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
-    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat);
+    // in dequeueBuffer. The initial default is HAL_PIXEL_FORMAT_RGBA_8888.
+    virtual status_t setDefaultBufferFormat(PixelFormat defaultFormat);
+
+    // setDefaultBufferDataSpace allows the BufferQueue to create
+    // GraphicBuffers of a defaultDataSpace if no data space is specified
+    // in queueBuffer.
+    // The initial default is HAL_DATASPACE_UNKNOWN
+    virtual status_t setDefaultBufferDataSpace(
+            android_dataspace defaultDataSpace);
 
     // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
     // These are merged with the bits passed to dequeueBuffer.  The values are
diff --git a/include/gui/BufferQueueCore.h b/include/gui/BufferQueueCore.h
index 1d975c0..797a108 100644
--- a/include/gui/BufferQueueCore.h
+++ b/include/gui/BufferQueueCore.h
@@ -199,15 +199,20 @@
 
     // mDefaultBufferFormat can be set so it will override the buffer format
     // when it isn't specified in dequeueBuffer.
-    uint32_t mDefaultBufferFormat;
+    PixelFormat mDefaultBufferFormat;
 
     // mDefaultWidth holds the default width of allocated buffers. It is used
     // in dequeueBuffer if a width and height of 0 are specified.
-    int mDefaultWidth;
+    uint32_t mDefaultWidth;
 
     // mDefaultHeight holds the default height of allocated buffers. It is used
     // in dequeueBuffer if a width and height of 0 are specified.
-    int mDefaultHeight;
+    uint32_t mDefaultHeight;
+
+    // mDefaultBufferDataSpace holds the default dataSpace of queued buffers.
+    // It is used in queueBuffer if a dataspace of 0 (HAL_DATASPACE_UNKNOWN)
+    // is specified.
+    android_dataspace mDefaultBufferDataSpace;
 
     // mDefaultMaxBufferCount is the default limit on the number of buffers that
     // will be allocated at one time. This default limit is set by the consumer.
diff --git a/include/gui/BufferQueueProducer.h b/include/gui/BufferQueueProducer.h
index ed1056a..f794ea3 100644
--- a/include/gui/BufferQueueProducer.h
+++ b/include/gui/BufferQueueProducer.h
@@ -73,9 +73,7 @@
     // updateTexImage() is called.  If width and height are both zero, the
     // default values specified by setDefaultBufferSize() are used instead.
     //
-    // The pixel formats are enumerated in graphics.h, e.g.
-    // HAL_PIXEL_FORMAT_RGBA_8888.  If the format is 0, the default format
-    // will be used.
+    // If the format is 0, the default format will be used.
     //
     // The usage argument specifies gralloc buffer usage flags.  The values
     // are enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER.  These
@@ -93,8 +91,9 @@
     //
     // In both cases, the producer will need to call requestBuffer to get a
     // GraphicBuffer handle for the returned slot.
-    virtual status_t dequeueBuffer(int *outSlot, sp<Fence>* outFence, bool async,
-            uint32_t width, uint32_t height, uint32_t format, uint32_t usage);
+    virtual status_t dequeueBuffer(int *outSlot, sp<Fence>* outFence,
+            bool async, uint32_t width, uint32_t height, PixelFormat format,
+            uint32_t usage);
 
     // See IGraphicBufferProducer::detachBuffer
     virtual status_t detachBuffer(int slot);
@@ -171,7 +170,7 @@
 
     // See IGraphicBufferProducer::allocateBuffers
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage);
+            PixelFormat format, uint32_t usage);
 
 private:
     // This is required by the IBinder::DeathRecipient interface
diff --git a/include/gui/CpuConsumer.h b/include/gui/CpuConsumer.h
index 4c6822a..c99ab29 100644
--- a/include/gui/CpuConsumer.h
+++ b/include/gui/CpuConsumer.h
@@ -53,6 +53,7 @@
         uint32_t    transform;
         uint32_t    scalingMode;
         int64_t     timestamp;
+        android_dataspace dataSpace;
         uint64_t    frameNumber;
         // this is the same as format, except for formats that are compatible with
         // a flexible format (e.g. HAL_PIXEL_FORMAT_YCbCr_420_888). In the latter
@@ -71,7 +72,7 @@
     // Create a new CPU consumer. The maxLockedBuffers parameter specifies
     // how many buffers can be locked for user access at the same time.
     CpuConsumer(const sp<IGraphicBufferConsumer>& bq,
-            uint32_t maxLockedBuffers, bool controlledByApp = false);
+            size_t maxLockedBuffers, bool controlledByApp = false);
 
     virtual ~CpuConsumer();
 
@@ -86,10 +87,15 @@
     status_t setDefaultBufferSize(uint32_t width, uint32_t height);
 
     // setDefaultBufferFormat allows CpuConsumer's BufferQueue to create buffers
-    // of a defaultFormat if no format is specified by producer. Formats are
-    // enumerated in graphics.h; the initial default is
-    // HAL_PIXEL_FORMAT_RGBA_8888.
-    status_t setDefaultBufferFormat(uint32_t defaultFormat);
+    // of a defaultFormat if no format is specified by producer.
+    // The initial default is PIXEL_FORMAT_RGBA_8888.
+    status_t setDefaultBufferFormat(PixelFormat defaultFormat);
+
+    // setDefaultBufferDataSpace allows the BufferQueue to create
+    // GraphicBuffers of a defaultDataSpace if no data space is specified
+    // in queueBuffer.
+    // The initial default is HAL_DATASPACE_UNKNOWN
+    status_t setDefaultBufferDataSpace(android_dataspace defaultDataSpace);
 
     // Gets the next graphics buffer from the producer and locks it for CPU use,
     // filling out the passed-in locked buffer structure with the native pointer
@@ -110,9 +116,9 @@
 
   private:
     // Maximum number of buffers that can be locked at a time
-    uint32_t mMaxLockedBuffers;
+    size_t mMaxLockedBuffers;
 
-    status_t releaseAcquiredBufferLocked(int lockedIdx);
+    status_t releaseAcquiredBufferLocked(size_t lockedIdx);
 
     virtual void freeBufferLocked(int slotIndex);
 
@@ -133,7 +139,7 @@
     Vector<AcquiredBuffer> mAcquiredBuffers;
 
     // Count of currently locked buffers
-    uint32_t mCurrentLockedBuffers;
+    size_t mCurrentLockedBuffers;
 
 };
 
diff --git a/include/gui/GLConsumer.h b/include/gui/GLConsumer.h
index f91fe46..bf9eb24 100644
--- a/include/gui/GLConsumer.h
+++ b/include/gui/GLConsumer.h
@@ -150,7 +150,7 @@
     //
     // The frame number is an incrementing counter set to 0 at the creation of
     // the BufferQueue associated with this consumer.
-    int64_t getFrameNumber();
+    uint64_t getFrameNumber();
 
     // setDefaultBufferSize is used to set the size of buffers returned by
     // requestBuffers when a with and height of zero is requested.
@@ -197,7 +197,8 @@
 
     // These functions call the corresponding BufferQueue implementation
     // so the refactoring can proceed smoothly
-    status_t setDefaultBufferFormat(uint32_t defaultFormat);
+    status_t setDefaultBufferFormat(PixelFormat defaultFormat);
+    status_t setDefaultBufferDataSpace(android_dataspace defaultDataSpace);
     status_t setConsumerUsageBits(uint32_t usage);
     status_t setTransformHint(uint32_t hint);
 
@@ -254,7 +255,7 @@
         return releaseBufferLocked(slot, graphicBuffer, mEglDisplay, eglFence);
     }
 
-    static bool isExternalFormat(uint32_t format);
+    static bool isExternalFormat(PixelFormat format);
 
     // This releases the buffer in the slot referenced by mCurrentTexture,
     // then updates state to refer to the BufferItem, which must be a
@@ -391,7 +392,7 @@
 
     // mCurrentFrameNumber is the frame counter for the current texture.
     // It gets set each time updateTexImage is called.
-    int64_t mCurrentFrameNumber;
+    uint64_t mCurrentFrameNumber;
 
     uint32_t mDefaultWidth, mDefaultHeight;
 
diff --git a/include/gui/GraphicBufferAlloc.h b/include/gui/GraphicBufferAlloc.h
index b08750c..69fe51e 100644
--- a/include/gui/GraphicBufferAlloc.h
+++ b/include/gui/GraphicBufferAlloc.h
@@ -33,8 +33,9 @@
 public:
     GraphicBufferAlloc();
     virtual ~GraphicBufferAlloc();
-    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
-        PixelFormat format, uint32_t usage, status_t* error);
+    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t width,
+            uint32_t height, PixelFormat format, uint32_t usage,
+            status_t* error);
 };
 
 
diff --git a/include/gui/IGraphicBufferAlloc.h b/include/gui/IGraphicBufferAlloc.h
index cee41d9..f3c46ec 100644
--- a/include/gui/IGraphicBufferAlloc.h
+++ b/include/gui/IGraphicBufferAlloc.h
@@ -45,10 +45,10 @@
 class BnGraphicBufferAlloc : public BnInterface<IGraphicBufferAlloc>
 {
 public:
-    virtual status_t    onTransact( uint32_t code,
-                                    const Parcel& data,
-                                    Parcel* reply,
-                                    uint32_t flags = 0);
+    virtual status_t onTransact(uint32_t code,
+                                const Parcel& data,
+                                Parcel* reply,
+                                uint32_t flags = 0);
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/IGraphicBufferConsumer.h b/include/gui/IGraphicBufferConsumer.h
index 15f51fe..53b4e75 100644
--- a/include/gui/IGraphicBufferConsumer.h
+++ b/include/gui/IGraphicBufferConsumer.h
@@ -25,6 +25,7 @@
 #include <utils/Timers.h>
 
 #include <binder/IInterface.h>
+#include <ui/PixelFormat.h>
 #include <ui/Rect.h>
 
 #include <EGL/egl.h>
@@ -85,6 +86,10 @@
         // automatically when the buffer was queued.
         bool mIsAutoTimestamp;
 
+        // mDataSpace is the current dataSpace for this buffer slot. This gets
+        // set by queueBuffer each time this slot is queued.
+        android_dataspace mDataSpace;
+
         // mFrameNumber is the number of the queued frame for this slot.
         uint64_t mFrameNumber;
 
@@ -280,11 +285,19 @@
 
     // setDefaultBufferFormat allows the BufferQueue to create
     // GraphicBuffers of a defaultFormat if no format is specified
-    // in dequeueBuffer.  Formats are enumerated in graphics.h; the
-    // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
+    // in dequeueBuffer.
+    // The initial default is PIXEL_FORMAT_RGBA_8888.
     //
     // Return of a value other than NO_ERROR means an unknown error has occurred.
-    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat) = 0;
+    virtual status_t setDefaultBufferFormat(PixelFormat defaultFormat) = 0;
+
+    // setDefaultBufferDataSpace is a request to the producer to provide buffers
+    // of the indicated dataSpace. The producer may ignore this request.
+    // The initial default is HAL_DATASPACE_UNKNOWN.
+    //
+    // Return of a value other than NO_ERROR means an unknown error has occurred.
+    virtual status_t setDefaultBufferDataSpace(
+            android_dataspace defaultDataSpace) = 0;
 
     // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
     // These are merged with the bits passed to dequeueBuffer.  The values are
diff --git a/include/gui/IGraphicBufferProducer.h b/include/gui/IGraphicBufferProducer.h
index 4e9e810..374245a 100644
--- a/include/gui/IGraphicBufferProducer.h
+++ b/include/gui/IGraphicBufferProducer.h
@@ -134,9 +134,7 @@
     // updateTexImage() is called.  If width and height are both zero, the
     // default values specified by setDefaultBufferSize() are used instead.
     //
-    // The pixel formats are enumerated in <graphics.h>, e.g.
-    // HAL_PIXEL_FORMAT_RGBA_8888.  If the format is 0, the default format
-    // will be used.
+    // If the format is 0, the default format will be used.
     //
     // The usage argument specifies gralloc buffer usage flags.  The values
     // are enumerated in <gralloc.h>, e.g. GRALLOC_USAGE_HW_RENDER.  These
@@ -167,7 +165,7 @@
     // All other negative values are an unknown error returned downstream
     // from the graphics allocator (typically errno).
     virtual status_t dequeueBuffer(int* slot, sp<Fence>* fence, bool async,
-            uint32_t w, uint32_t h, uint32_t format, uint32_t usage) = 0;
+            uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) = 0;
 
     // detachBuffer attempts to remove all ownership of the buffer in the given
     // slot from the buffer queue. If this call succeeds, the slot will be
@@ -267,6 +265,7 @@
         inline QueueBufferInput(const Parcel& parcel);
         // timestamp - a monotonically increasing value in nanoseconds
         // isAutoTimestamp - if the timestamp was synthesized at queue time
+        // dataSpace - description of the contents, interpretation depends on format
         // crop - a crop rectangle that's used as a hint to the consumer
         // scalingMode - a set of flags from NATIVE_WINDOW_SCALING_* in <window.h>
         // transform - a set of flags from NATIVE_WINDOW_TRANSFORM_* in <window.h>
@@ -276,17 +275,21 @@
         // sticky - the sticky transform set in Surface (only used by the LEGACY
         //          camera mode).
         inline QueueBufferInput(int64_t timestamp, bool isAutoTimestamp,
-                const Rect& crop, int scalingMode, uint32_t transform, bool async,
-                const sp<Fence>& fence, uint32_t sticky = 0)
-        : timestamp(timestamp), isAutoTimestamp(isAutoTimestamp), crop(crop),
-          scalingMode(scalingMode), transform(transform), stickyTransform(sticky),
-          async(async), fence(fence) { }
+                android_dataspace dataSpace, const Rect& crop, int scalingMode,
+                uint32_t transform, bool async, const sp<Fence>& fence,
+                uint32_t sticky = 0)
+                : timestamp(timestamp), isAutoTimestamp(isAutoTimestamp),
+                  dataSpace(dataSpace), crop(crop), scalingMode(scalingMode),
+                  transform(transform), stickyTransform(sticky),
+                  async(async), fence(fence) { }
         inline void deflate(int64_t* outTimestamp, bool* outIsAutoTimestamp,
-                Rect* outCrop, int* outScalingMode, uint32_t* outTransform,
-                bool* outAsync, sp<Fence>* outFence,
+                android_dataspace* outDataSpace,
+                Rect* outCrop, int* outScalingMode,
+                uint32_t* outTransform, bool* outAsync, sp<Fence>* outFence,
                 uint32_t* outStickyTransform = NULL) const {
             *outTimestamp = timestamp;
             *outIsAutoTimestamp = bool(isAutoTimestamp);
+            *outDataSpace = dataSpace;
             *outCrop = crop;
             *outScalingMode = scalingMode;
             *outTransform = transform;
@@ -306,6 +309,7 @@
     private:
         int64_t timestamp;
         int isAutoTimestamp;
+        android_dataspace dataSpace;
         Rect crop;
         int scalingMode;
         uint32_t transform;
@@ -448,7 +452,7 @@
     // dequeueBuffer. If there are already the maximum number of buffers
     // allocated, this function has no effect.
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage) = 0;
+            PixelFormat format, uint32_t usage) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/ISurfaceComposer.h b/include/gui/ISurfaceComposer.h
index f04a848..8c3d49e 100644
--- a/include/gui/ISurfaceComposer.h
+++ b/include/gui/ISurfaceComposer.h
@@ -28,7 +28,6 @@
 #include <binder/IInterface.h>
 
 #include <ui/FrameStats.h>
-#include <ui/PixelFormat.h>
 
 #include <gui/IGraphicBufferAlloc.h>
 #include <gui/ISurfaceComposerClient.h>
diff --git a/include/gui/Sensor.h b/include/gui/Sensor.h
index 59b4d4d..27a215e 100644
--- a/include/gui/Sensor.h
+++ b/include/gui/Sensor.h
@@ -67,12 +67,12 @@
     int32_t getMinDelay() const;
     nsecs_t getMinDelayNs() const;
     int32_t getVersion() const;
-    int32_t getFifoReservedEventCount() const;
-    int32_t getFifoMaxEventCount() const;
+    uint32_t getFifoReservedEventCount() const;
+    uint32_t getFifoMaxEventCount() const;
     const String8& getStringType() const;
     const String8& getRequiredPermission() const;
     int32_t getMaxDelay() const;
-    int32_t getFlags() const;
+    uint32_t getFlags() const;
     bool isWakeUpSensor() const;
     int32_t getReportingMode() const;
 
@@ -93,8 +93,8 @@
     float   mPower;
     int32_t mMinDelay;
     int32_t mVersion;
-    int32_t mFifoReservedEventCount;
-    int32_t mFifoMaxEventCount;
+    uint32_t mFifoReservedEventCount;
+    uint32_t mFifoMaxEventCount;
     String8 mStringType;
     String8 mRequiredPermission;
     int32_t mMaxDelay;
diff --git a/include/gui/Surface.h b/include/gui/Surface.h
index f2cf018..40e2fc1 100644
--- a/include/gui/Surface.h
+++ b/include/gui/Surface.h
@@ -146,6 +146,7 @@
     int dispatchLock(va_list args);
     int dispatchUnlockAndPost(va_list args);
     int dispatchSetSidebandStream(va_list args);
+    int dispatchSetBuffersDataSpace(va_list args);
 
 protected:
     virtual int dequeueBuffer(ANativeWindowBuffer** buffer, int* fenceFd);
@@ -157,16 +158,18 @@
 
     virtual int lockBuffer_DEPRECATED(ANativeWindowBuffer* buffer);
 
+    virtual int connect(int api, const sp<IProducerListener>& listener);
     virtual int connect(int api);
     virtual int disconnect(int api);
     virtual int setBufferCount(int bufferCount);
-    virtual int setBuffersDimensions(int w, int h);
-    virtual int setBuffersUserDimensions(int w, int h);
-    virtual int setBuffersFormat(int format);
+    virtual int setBuffersDimensions(uint32_t width, uint32_t height);
+    virtual int setBuffersUserDimensions(uint32_t width, uint32_t height);
+    virtual int setBuffersFormat(PixelFormat format);
     virtual int setScalingMode(int mode);
-    virtual int setBuffersTransform(int transform);
-    virtual int setBuffersStickyTransform(int transform);
+    virtual int setBuffersTransform(uint32_t transform);
+    virtual int setBuffersStickyTransform(uint32_t transform);
     virtual int setBuffersTimestamp(int64_t timestamp);
+    virtual int setBuffersDataSpace(android_dataspace dataSpace);
     virtual int setCrop(Rect const* rect);
     virtual int setUsage(uint32_t reqUsage);
 
@@ -211,7 +214,7 @@
 
     // mReqFormat is the buffer pixel format that will be requested at the next
     // deuque operation. It is initialized to PIXEL_FORMAT_RGBA_8888.
-    uint32_t mReqFormat;
+    PixelFormat mReqFormat;
 
     // mReqUsage is the set of buffer usage flags that will be requested
     // at the next deuque operation. It is initialized to 0.
@@ -222,6 +225,11 @@
     // a timestamp is auto-generated when queueBuffer is called.
     int64_t mTimestamp;
 
+    // mDataSpace is the buffer dataSpace that will be used for the next buffer
+    // queue operation. It defaults to HAL_DATASPACE_UNKNOWN, which
+    // means that the buffer contains some type of color data.
+    android_dataspace mDataSpace;
+
     // mCrop is the crop rectangle that will be used for the next buffer
     // that gets queued. It is set by calling setCrop.
     Rect mCrop;
@@ -240,23 +248,23 @@
     // from being set by the compositor.
     uint32_t mStickyTransform;
 
-     // mDefaultWidth is default width of the buffers, regardless of the
-     // native_window_set_buffers_dimensions call.
-     uint32_t mDefaultWidth;
+    // mDefaultWidth is default width of the buffers, regardless of the
+    // native_window_set_buffers_dimensions call.
+    uint32_t mDefaultWidth;
 
-     // mDefaultHeight is default height of the buffers, regardless of the
-     // native_window_set_buffers_dimensions call.
-     uint32_t mDefaultHeight;
+    // mDefaultHeight is default height of the buffers, regardless of the
+    // native_window_set_buffers_dimensions call.
+    uint32_t mDefaultHeight;
 
-     // mUserWidth, if non-zero, is an application-specified override
-     // of mDefaultWidth.  This is lower priority than the width set by
-     // native_window_set_buffers_dimensions.
-     uint32_t mUserWidth;
+    // mUserWidth, if non-zero, is an application-specified override
+    // of mDefaultWidth.  This is lower priority than the width set by
+    // native_window_set_buffers_dimensions.
+    uint32_t mUserWidth;
 
-     // mUserHeight, if non-zero, is an application-specified override
-     // of mDefaultHeight.  This is lower priority than the height set
-     // by native_window_set_buffers_dimensions.
-     uint32_t mUserHeight;
+    // mUserHeight, if non-zero, is an application-specified override
+    // of mDefaultHeight.  This is lower priority than the height set
+    // by native_window_set_buffers_dimensions.
+    uint32_t mUserHeight;
 
     // mTransformHint is the transform probably applied to buffers of this
     // window. this is only a hint, actual transform may differ.
diff --git a/include/gui/SurfaceComposerClient.h b/include/gui/SurfaceComposerClient.h
index 4cbfc09..37d953e 100644
--- a/include/gui/SurfaceComposerClient.h
+++ b/include/gui/SurfaceComposerClient.h
@@ -127,7 +127,7 @@
     status_t    show(const sp<IBinder>& id);
     status_t    setFlags(const sp<IBinder>& id, uint32_t flags, uint32_t mask);
     status_t    setTransparentRegionHint(const sp<IBinder>& id, const Region& transparent);
-    status_t    setLayer(const sp<IBinder>& id, int32_t layer);
+    status_t    setLayer(const sp<IBinder>& id, uint32_t layer);
     status_t    setAlpha(const sp<IBinder>& id, float alpha=1.0f);
     status_t    setMatrix(const sp<IBinder>& id, float dsdx, float dtdx, float dsdy, float dtdy);
     status_t    setPosition(const sp<IBinder>& id, float x, float y);
diff --git a/include/gui/SurfaceControl.h b/include/gui/SurfaceControl.h
index 84fb9f9..9f62f7c 100644
--- a/include/gui/SurfaceControl.h
+++ b/include/gui/SurfaceControl.h
@@ -57,8 +57,8 @@
     // release surface data from java
     void        clear();
 
-    status_t    setLayerStack(int32_t layerStack);
-    status_t    setLayer(int32_t layer);
+    status_t    setLayerStack(uint32_t layerStack);
+    status_t    setLayer(uint32_t layer);
     status_t    setPosition(float x, float y);
     status_t    setSize(uint32_t w, uint32_t h);
     status_t    hide();
diff --git a/include/input/IInputFlinger.h b/include/input/IInputFlinger.h
new file mode 100644
index 0000000..629310f
--- /dev/null
+++ b/include/input/IInputFlinger.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBINPUT_IINPUT_FLINGER_H
+#define _LIBINPUT_IINPUT_FLINGER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <binder/IInterface.h>
+
+namespace android {
+
+/*
+ * This class defines the Binder IPC interface for accessing various
+ * InputFlinger features.
+ */
+class IInputFlinger : public IInterface {
+public:
+    DECLARE_META_INTERFACE(InputFlinger);
+};
+
+
+/**
+ * Binder implementation.
+ */
+class BnInputFlinger : public BnInterface<IInputFlinger> {
+public:
+    enum {
+        DO_SOMETHING_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
+    };
+
+    virtual status_t onTransact(uint32_t code, const Parcel& data,
+            Parcel* reply, uint32_t flags = 0);
+};
+
+} // namespace android
+
+#endif // _LIBINPUT_IINPUT_FLINGER_H
diff --git a/include/media/drm/DrmAPI.h b/include/media/drm/DrmAPI.h
index 49939fd..6e84ab4 100644
--- a/include/media/drm/DrmAPI.h
+++ b/include/media/drm/DrmAPI.h
@@ -80,7 +80,8 @@
             kDrmPluginEventProvisionRequired = 1,
             kDrmPluginEventKeyNeeded,
             kDrmPluginEventKeyExpired,
-            kDrmPluginEventVendorDefined
+            kDrmPluginEventVendorDefined,
+            kDrmPluginEventSessionReclaimed
         };
 
         // Drm keys can be for offline content or for online streaming.
diff --git a/include/media/openmax/OMX_IVCommon.h b/include/media/openmax/OMX_IVCommon.h
index a5b9d18..f9b6f4b 100644
--- a/include/media/openmax/OMX_IVCommon.h
+++ b/include/media/openmax/OMX_IVCommon.h
@@ -157,6 +157,7 @@
      * an acceptable range once that is done.
      * */
     OMX_COLOR_FormatAndroidOpaque = 0x7F000789,
+    OMX_COLOR_Format32BitRGBA8888 = 0x7F00A000,
     /** Flexible 8-bit YUV format.  Codec should report this format
      *  as being supported if it supports any YUV420 packed planar
      *  or semiplanar formats.  When port is set to use this format,
diff --git a/include/ui/PixelFormat.h b/include/ui/PixelFormat.h
index e7e8ffc..f26fecb 100644
--- a/include/ui/PixelFormat.h
+++ b/include/ui/PixelFormat.h
@@ -60,8 +60,6 @@
     PIXEL_FORMAT_BGRA_8888   = HAL_PIXEL_FORMAT_BGRA_8888,   // 4x8-bit BGRA
     PIXEL_FORMAT_RGBA_5551   = 6,                            // 16-bit ARGB
     PIXEL_FORMAT_RGBA_4444   = 7,                            // 16-bit ARGB
-    PIXEL_FORMAT_sRGB_A_8888 = HAL_PIXEL_FORMAT_sRGB_A_8888, // 4x8-bit sRGB + A
-    PIXEL_FORMAT_sRGB_X_8888 = HAL_PIXEL_FORMAT_sRGB_X_8888, // 4x8-bit sRGB, no A
 };
 
 typedef int32_t PixelFormat;
diff --git a/libs/binder/Android.mk b/libs/binder/Android.mk
index 79decfe..d5860ef 100644
--- a/libs/binder/Android.mk
+++ b/libs/binder/Android.mk
@@ -26,6 +26,8 @@
     IMemory.cpp \
     IPCThreadState.cpp \
     IPermissionController.cpp \
+    IProcessInfoService.cpp \
+    ProcessInfoService.cpp \
     IServiceManager.cpp \
     MemoryDealer.cpp \
     MemoryBase.cpp \
diff --git a/libs/binder/IProcessInfoService.cpp b/libs/binder/IProcessInfoService.cpp
new file mode 100644
index 0000000..d86eb27
--- /dev/null
+++ b/libs/binder/IProcessInfoService.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <binder/IProcessInfoService.h>
+#include <binder/Parcel.h>
+#include <utils/Errors.h>
+#include <sys/types.h>
+
+namespace android {
+
+// ----------------------------------------------------------------------
+
+class BpProcessInfoService : public BpInterface<IProcessInfoService> {
+public:
+    BpProcessInfoService(const sp<IBinder>& impl)
+        : BpInterface<IProcessInfoService>(impl) {}
+
+    virtual status_t getProcessStatesFromPids(size_t length, /*in*/ int32_t* pids,
+            /*out*/ int32_t* states)
+    {
+        Parcel data, reply;
+        data.writeInterfaceToken(IProcessInfoService::getInterfaceDescriptor());
+        data.writeInt32Array(length, pids);
+        data.writeInt32(length); // write length of output array, used by java AIDL stubs
+        status_t err = remote()->transact(GET_PROCESS_STATES_FROM_PIDS, data, &reply);
+        if (err != NO_ERROR || ((err = reply.readExceptionCode()) != NO_ERROR)) {
+            return err;
+        }
+        int32_t replyLen = reply.readInt32();
+        if (static_cast<size_t>(replyLen) != length) {
+            return NOT_ENOUGH_DATA;
+        }
+        if (replyLen > 0 && (err = reply.read(states, length * sizeof(*states))) != NO_ERROR) {
+            return err;
+        }
+        return reply.readInt32();
+    }
+
+};
+
+IMPLEMENT_META_INTERFACE(ProcessInfoService, "android.os.IProcessInfoService");
+
+// ----------------------------------------------------------------------
+
+status_t BnProcessInfoService::onTransact( uint32_t code, const Parcel& data, Parcel* reply,
+        uint32_t flags) {
+    switch(code) {
+        case GET_PROCESS_STATES_FROM_PIDS: {
+            CHECK_INTERFACE(IProcessInfoService, data, reply);
+            int32_t arrayLen = data.readInt32();
+            if (arrayLen <= 0) {
+                reply->writeNoException();
+                reply->writeInt32(0);
+                reply->writeInt32(NOT_ENOUGH_DATA);
+                return NO_ERROR;
+            }
+
+            size_t len = static_cast<size_t>(arrayLen);
+            int32_t pids[len];
+            status_t res = data.read(pids, len * sizeof(*pids));
+
+            // Ignore output array length returned in the parcel here, as the states array must
+            // always be the same length as the input PIDs array.
+            int32_t states[len];
+            for (size_t i = 0; i < len; i++) states[i] = -1;
+            if (res == NO_ERROR) {
+                res = getProcessStatesFromPids(len, /*in*/ pids, /*out*/ states);
+            }
+            reply->writeNoException();
+            reply->writeInt32Array(len, states);
+            reply->writeInt32(res);
+            return NO_ERROR;
+        } break;
+        default:
+            return BBinder::onTransact(code, data, reply, flags);
+    }
+}
+
+// ----------------------------------------------------------------------
+
+}; // namespace android
diff --git a/libs/binder/ProcessInfoService.cpp b/libs/binder/ProcessInfoService.cpp
new file mode 100644
index 0000000..fb28643
--- /dev/null
+++ b/libs/binder/ProcessInfoService.cpp
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <binder/ProcessInfoService.h>
+#include <binder/IServiceManager.h>
+
+#include <utils/Log.h>
+#include <utils/String16.h>
+
+namespace android {
+
+ProcessInfoService::ProcessInfoService() {
+    updateBinderLocked();
+}
+
+status_t ProcessInfoService::getProcessStatesImpl(size_t length, /*in*/ int32_t* pids,
+        /*out*/ int32_t* states) {
+    status_t err = NO_ERROR;
+    sp<IProcessInfoService> pis;
+    mProcessInfoLock.lock();
+    pis = mProcessInfoService;
+    mProcessInfoLock.unlock();
+
+    for (int i = 0; i < BINDER_ATTEMPT_LIMIT; i++) {
+
+        if (pis != NULL) {
+            err = pis->getProcessStatesFromPids(length, /*in*/ pids, /*out*/ states);
+            if (err == NO_ERROR) return NO_ERROR; // success
+            if (IInterface::asBinder(pis)->isBinderAlive()) return err;
+        }
+        sleep(1);
+
+        mProcessInfoLock.lock();
+        if (pis == mProcessInfoService) {
+            updateBinderLocked();
+        }
+        pis = mProcessInfoService;
+        mProcessInfoLock.unlock();
+    }
+
+    ALOGW("%s: Could not retrieve process states from ProcessInfoService after %d retries.",
+            __FUNCTION__, BINDER_ATTEMPT_LIMIT);
+
+    return TIMED_OUT;
+}
+
+void ProcessInfoService::updateBinderLocked() {
+    const sp<IServiceManager> sm(defaultServiceManager());
+    if (sm != NULL) {
+        const String16 name("processinfo");
+        mProcessInfoService = interface_cast<IProcessInfoService>(sm->checkService(name));
+    }
+}
+
+ANDROID_SINGLETON_STATIC_INSTANCE(ProcessInfoService);
+
+}; // namespace android
diff --git a/libs/gui/Android.mk b/libs/gui/Android.mk
index fffe28a..8a965dd 100644
--- a/libs/gui/Android.mk
+++ b/libs/gui/Android.mk
@@ -1,8 +1,40 @@
+# Copyright 2010 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
 LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
 LOCAL_CLANG := true
-LOCAL_CPPFLAGS := -std=c++11
+LOCAL_CPPFLAGS := -std=c++1y -Weverything -Werror
+
+# The static constructors and destructors in this library have not been noted to
+# introduce significant overheads
+LOCAL_CPPFLAGS += -Wno-exit-time-destructors
+LOCAL_CPPFLAGS += -Wno-global-constructors
+
+# We only care about compiling as C++14
+LOCAL_CPPFLAGS += -Wno-c++98-compat-pedantic
+
+# We don't need to enumerate every case in a switch as long as a default case
+# is present
+LOCAL_CPPFLAGS += -Wno-switch-enum
+
+# Allow calling variadic macros without a __VA_ARGS__ list
+LOCAL_CPPFLAGS += -Wno-gnu-zero-variadic-macro-arguments
+
+# Don't warn about struct padding
+LOCAL_CPPFLAGS += -Wno-padded
 
 LOCAL_SRC_FILES := \
 	IGraphicBufferConsumer.cpp \
diff --git a/libs/gui/BitTube.cpp b/libs/gui/BitTube.cpp
index 3ed1f37..b653c5b 100644
--- a/libs/gui/BitTube.cpp
+++ b/libs/gui/BitTube.cpp
@@ -149,12 +149,12 @@
     ssize_t size = tube->write(vaddr, count*objSize);
 
     // should never happen because of SOCK_SEQPACKET
-    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % objSize),
+    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % static_cast<ssize_t>(objSize)),
             "BitTube::sendObjects(count=%zu, size=%zu), res=%zd (partial events were sent!)",
             count, objSize, size);
 
     //ALOGE_IF(size<0, "error %d sending %d events", size, count);
-    return size < 0 ? size : size / objSize;
+    return size < 0 ? size : size / static_cast<ssize_t>(objSize);
 }
 
 ssize_t BitTube::recvObjects(const sp<BitTube>& tube,
@@ -164,12 +164,12 @@
     ssize_t size = tube->read(vaddr, count*objSize);
 
     // should never happen because of SOCK_SEQPACKET
-    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % objSize),
+    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % static_cast<ssize_t>(objSize)),
             "BitTube::recvObjects(count=%zu, size=%zu), res=%zd (partial events were received!)",
             count, objSize, size);
 
     //ALOGE_IF(size<0, "error %d receiving %d events", size, count);
-    return size < 0 ? size : size / objSize;
+    return size < 0 ? size : size / static_cast<ssize_t>(objSize);
 }
 
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/BufferItem.cpp b/libs/gui/BufferItem.cpp
index e6fc791..f3a37ca 100644
--- a/libs/gui/BufferItem.cpp
+++ b/libs/gui/BufferItem.cpp
@@ -28,6 +28,7 @@
     mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
     mTimestamp(0),
     mIsAutoTimestamp(false),
+    mDataSpace(HAL_DATASPACE_UNKNOWN),
     mFrameNumber(0),
     mSlot(INVALID_BUFFER_SLOT),
     mIsDroppable(false),
@@ -47,6 +48,7 @@
     bufferItem.mScalingMode = mScalingMode;
     bufferItem.mTimestamp = mTimestamp;
     bufferItem.mIsAutoTimestamp = mIsAutoTimestamp;
+    bufferItem.mDataSpace = mDataSpace;
     bufferItem.mFrameNumber = mFrameNumber;
     bufferItem.mBuf = mSlot;
     bufferItem.mIsDroppable = mIsDroppable;
@@ -61,6 +63,7 @@
             sizeof(mScalingMode) +
             sizeof(mTimestamp) +
             sizeof(mIsAutoTimestamp) +
+            sizeof(mDataSpace) +
             sizeof(mFrameNumber) +
             sizeof(mSlot) +
             sizeof(mIsDroppable) +
@@ -131,6 +134,7 @@
     FlattenableUtils::write(buffer, size, mScalingMode);
     FlattenableUtils::write(buffer, size, mTimestamp);
     FlattenableUtils::write(buffer, size, mIsAutoTimestamp);
+    FlattenableUtils::write(buffer, size, mDataSpace);
     FlattenableUtils::write(buffer, size, mFrameNumber);
     FlattenableUtils::write(buffer, size, mSlot);
     FlattenableUtils::write(buffer, size, mIsDroppable);
@@ -173,6 +177,7 @@
     FlattenableUtils::read(buffer, size, mScalingMode);
     FlattenableUtils::read(buffer, size, mTimestamp);
     FlattenableUtils::read(buffer, size, mIsAutoTimestamp);
+    FlattenableUtils::read(buffer, size, mDataSpace);
     FlattenableUtils::read(buffer, size, mFrameNumber);
     FlattenableUtils::read(buffer, size, mSlot);
     FlattenableUtils::read(buffer, size, mIsDroppable);
diff --git a/libs/gui/BufferItemConsumer.cpp b/libs/gui/BufferItemConsumer.cpp
index 2d976e5..655bfe6 100644
--- a/libs/gui/BufferItemConsumer.cpp
+++ b/libs/gui/BufferItemConsumer.cpp
@@ -16,15 +16,15 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "BufferItemConsumer"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
+//#define ATRACE_TAG ATRACE_TAG_GRAPHICS
 #include <utils/Log.h>
 
 #include <gui/BufferItemConsumer.h>
 
-#define BI_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define BI_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define BI_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define BI_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define BI_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define BI_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define BI_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define BI_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
 #define BI_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
 
 namespace android {
@@ -44,8 +44,7 @@
     }
 }
 
-BufferItemConsumer::~BufferItemConsumer() {
-}
+BufferItemConsumer::~BufferItemConsumer() {}
 
 void BufferItemConsumer::setName(const String8& name) {
     Mutex::Autolock _l(mMutex);
@@ -105,9 +104,15 @@
     return mConsumer->setDefaultBufferSize(w, h);
 }
 
-status_t BufferItemConsumer::setDefaultBufferFormat(uint32_t defaultFormat) {
+status_t BufferItemConsumer::setDefaultBufferFormat(PixelFormat defaultFormat) {
     Mutex::Autolock _l(mMutex);
     return mConsumer->setDefaultBufferFormat(defaultFormat);
 }
 
+status_t BufferItemConsumer::setDefaultBufferDataSpace(
+        android_dataspace defaultDataSpace) {
+    Mutex::Autolock _l(mMutex);
+    return mConsumer->setDefaultBufferDataSpace(defaultDataSpace);
+}
+
 } // namespace android
diff --git a/libs/gui/BufferQueueConsumer.cpp b/libs/gui/BufferQueueConsumer.cpp
index 36e3c06..526c3b7 100644
--- a/libs/gui/BufferQueueConsumer.cpp
+++ b/libs/gui/BufferQueueConsumer.cpp
@@ -488,7 +488,7 @@
     mConsumerName = name;
 }
 
-status_t BufferQueueConsumer::setDefaultBufferFormat(uint32_t defaultFormat) {
+status_t BufferQueueConsumer::setDefaultBufferFormat(PixelFormat defaultFormat) {
     ATRACE_CALL();
     BQ_LOGV("setDefaultBufferFormat: %u", defaultFormat);
     Mutex::Autolock lock(mCore->mMutex);
@@ -496,6 +496,15 @@
     return NO_ERROR;
 }
 
+status_t BufferQueueConsumer::setDefaultBufferDataSpace(
+        android_dataspace defaultDataSpace) {
+    ATRACE_CALL();
+    BQ_LOGV("setDefaultBufferDataSpace: %u", defaultDataSpace);
+    Mutex::Autolock lock(mCore->mMutex);
+    mCore->mDefaultBufferDataSpace = defaultDataSpace;
+    return NO_ERROR;
+}
+
 status_t BufferQueueConsumer::setConsumerUsageBits(uint32_t usage) {
     ATRACE_CALL();
     BQ_LOGV("setConsumerUsageBits: %#x", usage);
diff --git a/libs/gui/BufferQueueCore.cpp b/libs/gui/BufferQueueCore.cpp
index ec1e631..edebc45 100644
--- a/libs/gui/BufferQueueCore.cpp
+++ b/libs/gui/BufferQueueCore.cpp
@@ -60,6 +60,7 @@
     mDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888),
     mDefaultWidth(1),
     mDefaultHeight(1),
+    mDefaultBufferDataSpace(HAL_DATASPACE_UNKNOWN),
     mDefaultMaxBufferCount(2),
     mMaxAcquiredBufferCount(1),
     mBufferHasBeenQueued(false),
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index bf9c84d..4c22ba3 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -250,7 +250,7 @@
 
 status_t BufferQueueProducer::dequeueBuffer(int *outSlot,
         sp<android::Fence> *outFence, bool async,
-        uint32_t width, uint32_t height, uint32_t format, uint32_t usage) {
+        uint32_t width, uint32_t height, PixelFormat format, uint32_t usage) {
     ATRACE_CALL();
     { // Autolock scope
         Mutex::Autolock lock(mCore->mMutex);
@@ -311,7 +311,7 @@
         if ((buffer == NULL) ||
                 (static_cast<uint32_t>(buffer->width) != width) ||
                 (static_cast<uint32_t>(buffer->height) != height) ||
-                (static_cast<uint32_t>(buffer->format) != format) ||
+                (buffer->format != format) ||
                 ((static_cast<uint32_t>(buffer->usage) & usage) != usage))
         {
             mSlots[found].mAcquireCalled = false;
@@ -341,7 +341,7 @@
         status_t error;
         BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
         sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
-                    width, height, format, usage, &error));
+                width, height, format, usage, &error));
         if (graphicBuffer == NULL) {
             BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
             return error;
@@ -516,14 +516,15 @@
 
     int64_t timestamp;
     bool isAutoTimestamp;
+    android_dataspace dataSpace;
     Rect crop;
     int scalingMode;
     uint32_t transform;
     uint32_t stickyTransform;
     bool async;
     sp<Fence> fence;
-    input.deflate(&timestamp, &isAutoTimestamp, &crop, &scalingMode, &transform,
-            &async, &fence, &stickyTransform);
+    input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop, &scalingMode,
+            &transform, &async, &fence, &stickyTransform);
 
     if (fence == NULL) {
         BQ_LOGE("queueBuffer: fence is NULL");
@@ -579,11 +580,11 @@
             return BAD_VALUE;
         }
 
-        BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64
+        BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64 " dataSpace=%d"
                 " crop=[%d,%d,%d,%d] transform=%#x scale=%s",
-                slot, mCore->mFrameCounter + 1, timestamp,
-                crop.left, crop.top, crop.right, crop.bottom,
-                transform, BufferItem::scalingModeName(scalingMode));
+                slot, mCore->mFrameCounter + 1, timestamp, dataSpace,
+                crop.left, crop.top, crop.right, crop.bottom, transform,
+                BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode)));
 
         const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
         Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
@@ -595,6 +596,11 @@
             return BAD_VALUE;
         }
 
+        // Override UNKNOWN dataspace with consumer default
+        if (dataSpace == HAL_DATASPACE_UNKNOWN) {
+            dataSpace = mCore->mDefaultBufferDataSpace;
+        }
+
         mSlots[slot].mFence = fence;
         mSlots[slot].mBufferState = BufferSlot::QUEUED;
         ++mCore->mFrameCounter;
@@ -603,12 +609,14 @@
         item.mAcquireCalled = mSlots[slot].mAcquireCalled;
         item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
         item.mCrop = crop;
-        item.mTransform = transform & ~NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
+        item.mTransform = transform &
+                ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
         item.mTransformToDisplayInverse =
-                bool(transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
-        item.mScalingMode = scalingMode;
+                (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
+        item.mScalingMode = static_cast<uint32_t>(scalingMode);
         item.mTimestamp = timestamp;
         item.mIsAutoTimestamp = isAutoTimestamp;
+        item.mDataSpace = dataSpace;
         item.mFrameNumber = mCore->mFrameCounter;
         item.mSlot = slot;
         item.mFence = fence;
@@ -647,7 +655,8 @@
         mCore->mDequeueCondition.broadcast();
 
         output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
-                mCore->mTransformHint, mCore->mQueue.size());
+                mCore->mTransformHint,
+                static_cast<uint32_t>(mCore->mQueue.size()));
 
         ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
 
@@ -736,25 +745,28 @@
     int value;
     switch (what) {
         case NATIVE_WINDOW_WIDTH:
-            value = mCore->mDefaultWidth;
+            value = static_cast<int32_t>(mCore->mDefaultWidth);
             break;
         case NATIVE_WINDOW_HEIGHT:
-            value = mCore->mDefaultHeight;
+            value = static_cast<int32_t>(mCore->mDefaultHeight);
             break;
         case NATIVE_WINDOW_FORMAT:
-            value = mCore->mDefaultBufferFormat;
+            value = static_cast<int32_t>(mCore->mDefaultBufferFormat);
             break;
         case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
             value = mCore->getMinUndequeuedBufferCountLocked(false);
             break;
         case NATIVE_WINDOW_STICKY_TRANSFORM:
-            value = static_cast<int>(mStickyTransform);
+            value = static_cast<int32_t>(mStickyTransform);
             break;
         case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
             value = (mCore->mQueue.size() > 1);
             break;
         case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
-            value = mCore->mConsumerUsageBits;
+            value = static_cast<int32_t>(mCore->mConsumerUsageBits);
+            break;
+        case NATIVE_WINDOW_DEFAULT_DATASPACE:
+            value = static_cast<int32_t>(mCore->mDefaultBufferDataSpace);
             break;
         default:
             return BAD_VALUE;
@@ -802,7 +814,8 @@
         case NATIVE_WINDOW_API_CAMERA:
             mCore->mConnectedApi = api;
             output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
-                    mCore->mTransformHint, mCore->mQueue.size());
+                    mCore->mTransformHint,
+                    static_cast<uint32_t>(mCore->mQueue.size()));
 
             // Set up a death notification so that we can disconnect
             // automatically if the remote producer dies
@@ -904,14 +917,14 @@
 }
 
 void BufferQueueProducer::allocateBuffers(bool async, uint32_t width,
-        uint32_t height, uint32_t format, uint32_t usage) {
+        uint32_t height, PixelFormat format, uint32_t usage) {
     ATRACE_CALL();
     while (true) {
         Vector<int> freeSlots;
         size_t newBufferCount = 0;
         uint32_t allocWidth = 0;
         uint32_t allocHeight = 0;
-        uint32_t allocFormat = 0;
+        PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN;
         uint32_t allocUsage = 0;
         { // Autolock scope
             Mutex::Autolock lock(mCore->mMutex);
@@ -937,7 +950,8 @@
                     currentBufferCount, maxBufferCount);
             if (maxBufferCount <= currentBufferCount)
                 return;
-            newBufferCount = maxBufferCount - currentBufferCount;
+            newBufferCount =
+                    static_cast<size_t>(maxBufferCount - currentBufferCount);
             if (freeSlots.size() < newBufferCount) {
                 BQ_LOGE("allocateBuffers: ran out of free slots");
                 return;
@@ -950,7 +964,7 @@
             mCore->mIsAllocating = true;
         } // Autolock scope
 
-        Vector<sp<GraphicBuffer> > buffers;
+        Vector<sp<GraphicBuffer>> buffers;
         for (size_t i = 0; i <  newBufferCount; ++i) {
             status_t result = NO_ERROR;
             sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
@@ -970,7 +984,8 @@
             Mutex::Autolock lock(mCore->mMutex);
             uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
             uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
-            uint32_t checkFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
+            PixelFormat checkFormat = format != 0 ?
+                    format : mCore->mDefaultBufferFormat;
             uint32_t checkUsage = usage | mCore->mConsumerUsageBits;
             if (checkWidth != allocWidth || checkHeight != allocHeight ||
                 checkFormat != allocFormat || checkUsage != allocUsage) {
diff --git a/libs/gui/BufferSlot.cpp b/libs/gui/BufferSlot.cpp
index b8877fe..01595de 100644
--- a/libs/gui/BufferSlot.cpp
+++ b/libs/gui/BufferSlot.cpp
@@ -24,8 +24,8 @@
         case BufferSlot::QUEUED: return "QUEUED";
         case BufferSlot::FREE: return "FREE";
         case BufferSlot::ACQUIRED: return "ACQUIRED";
-        default: return "Unknown";
     }
+    return "Unknown";
 }
 
 } // namespace android
diff --git a/libs/gui/ConsumerBase.cpp b/libs/gui/ConsumerBase.cpp
index 95f5507..5fc83ee 100644
--- a/libs/gui/ConsumerBase.cpp
+++ b/libs/gui/ConsumerBase.cpp
@@ -40,9 +40,9 @@
 
 // Macros for including the ConsumerBase name in log messages
 #define CB_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CB_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CB_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CB_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CB_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CB_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CB_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
 #define CB_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
 
 namespace android {
diff --git a/libs/gui/CpuConsumer.cpp b/libs/gui/CpuConsumer.cpp
index c5b6dfe..a7ca055 100644
--- a/libs/gui/CpuConsumer.cpp
+++ b/libs/gui/CpuConsumer.cpp
@@ -16,22 +16,22 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "CpuConsumer"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
+//#define ATRACE_TAG ATRACE_TAG_GRAPHICS
 
 #include <cutils/compiler.h>
 #include <utils/Log.h>
 #include <gui/CpuConsumer.h>
 
 #define CC_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CC_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CC_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CC_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CC_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
 #define CC_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
 #define CC_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
 
 namespace android {
 
 CpuConsumer::CpuConsumer(const sp<IGraphicBufferConsumer>& bq,
-        uint32_t maxLockedBuffers, bool controlledByApp) :
+        size_t maxLockedBuffers, bool controlledByApp) :
     ConsumerBase(bq, controlledByApp),
     mMaxLockedBuffers(maxLockedBuffers),
     mCurrentLockedBuffers(0)
@@ -40,7 +40,7 @@
     mAcquiredBuffers.insertAt(0, maxLockedBuffers);
 
     mConsumer->setConsumerUsageBits(GRALLOC_USAGE_SW_READ_OFTEN);
-    mConsumer->setMaxAcquiredBufferCount(maxLockedBuffers);
+    mConsumer->setMaxAcquiredBufferCount(static_cast<int32_t>(maxLockedBuffers));
 }
 
 CpuConsumer::~CpuConsumer() {
@@ -61,24 +61,29 @@
     return mConsumer->setDefaultBufferSize(width, height);
 }
 
-status_t CpuConsumer::setDefaultBufferFormat(uint32_t defaultFormat)
+status_t CpuConsumer::setDefaultBufferFormat(PixelFormat defaultFormat)
 {
     Mutex::Autolock _l(mMutex);
     return mConsumer->setDefaultBufferFormat(defaultFormat);
 }
 
+status_t CpuConsumer::setDefaultBufferDataSpace(
+        android_dataspace defaultDataSpace)
+{
+    Mutex::Autolock _l(mMutex);
+    return mConsumer->setDefaultBufferDataSpace(defaultDataSpace);
+}
+
 static bool isPossiblyYUV(PixelFormat format) {
-    switch ((int)format) {
+    switch (static_cast<int>(format)) {
         case HAL_PIXEL_FORMAT_RGBA_8888:
         case HAL_PIXEL_FORMAT_RGBX_8888:
         case HAL_PIXEL_FORMAT_RGB_888:
         case HAL_PIXEL_FORMAT_RGB_565:
         case HAL_PIXEL_FORMAT_BGRA_8888:
-        case HAL_PIXEL_FORMAT_sRGB_A_8888:
-        case HAL_PIXEL_FORMAT_sRGB_X_8888:
         case HAL_PIXEL_FORMAT_Y8:
         case HAL_PIXEL_FORMAT_Y16:
-        case HAL_PIXEL_FORMAT_RAW16: // same as HAL_PIXEL_FORMAT_RAW_SENSOR
+        case HAL_PIXEL_FORMAT_RAW16:
         case HAL_PIXEL_FORMAT_RAW10:
         case HAL_PIXEL_FORMAT_RAW_OPAQUE:
         case HAL_PIXEL_FORMAT_BLOB:
@@ -100,7 +105,7 @@
 
     if (!nativeBuffer) return BAD_VALUE;
     if (mCurrentLockedBuffers == mMaxLockedBuffers) {
-        CC_LOGW("Max buffers have been locked (%d), cannot lock anymore.",
+        CC_LOGW("Max buffers have been locked (%zd), cannot lock anymore.",
                 mMaxLockedBuffers);
         return NOT_ENOUGH_DATA;
     }
@@ -173,7 +178,7 @@
     }
 
     size_t lockedIdx = 0;
-    for (; lockedIdx < mMaxLockedBuffers; lockedIdx++) {
+    for (; lockedIdx < static_cast<size_t>(mMaxLockedBuffers); lockedIdx++) {
         if (mAcquiredBuffers[lockedIdx].mSlot ==
                 BufferQueue::INVALID_BUFFER_SLOT) {
             break;
@@ -193,19 +198,20 @@
     nativeBuffer->format = format;
     nativeBuffer->flexFormat = flexFormat;
     nativeBuffer->stride = (ycbcr.y != NULL) ?
-            ycbcr.ystride :
+            static_cast<uint32_t>(ycbcr.ystride) :
             mSlots[buf].mGraphicBuffer->getStride();
 
     nativeBuffer->crop        = b.mCrop;
     nativeBuffer->transform   = b.mTransform;
     nativeBuffer->scalingMode = b.mScalingMode;
     nativeBuffer->timestamp   = b.mTimestamp;
+    nativeBuffer->dataSpace   = b.mDataSpace;
     nativeBuffer->frameNumber = b.mFrameNumber;
 
     nativeBuffer->dataCb       = reinterpret_cast<uint8_t*>(ycbcr.cb);
     nativeBuffer->dataCr       = reinterpret_cast<uint8_t*>(ycbcr.cr);
-    nativeBuffer->chromaStride = ycbcr.cstride;
-    nativeBuffer->chromaStep   = ycbcr.chroma_step;
+    nativeBuffer->chromaStride = static_cast<uint32_t>(ycbcr.cstride);
+    nativeBuffer->chromaStep   = static_cast<uint32_t>(ycbcr.chroma_step);
 
     mCurrentLockedBuffers++;
 
@@ -217,7 +223,7 @@
     size_t lockedIdx = 0;
 
     void *bufPtr = reinterpret_cast<void *>(nativeBuffer.data);
-    for (; lockedIdx < mMaxLockedBuffers; lockedIdx++) {
+    for (; lockedIdx < static_cast<size_t>(mMaxLockedBuffers); lockedIdx++) {
         if (bufPtr == mAcquiredBuffers[lockedIdx].mBufferPointer) break;
     }
     if (lockedIdx == mMaxLockedBuffers) {
@@ -228,13 +234,13 @@
     return releaseAcquiredBufferLocked(lockedIdx);
 }
 
-status_t CpuConsumer::releaseAcquiredBufferLocked(int lockedIdx) {
+status_t CpuConsumer::releaseAcquiredBufferLocked(size_t lockedIdx) {
     status_t err;
     int fd = -1;
 
     err = mAcquiredBuffers[lockedIdx].mGraphicBuffer->unlockAsync(&fd);
     if (err != OK) {
-        CC_LOGE("%s: Unable to unlock graphic buffer %d", __FUNCTION__,
+        CC_LOGE("%s: Unable to unlock graphic buffer %zd", __FUNCTION__,
                 lockedIdx);
         return err;
     }
diff --git a/libs/gui/GLConsumer.cpp b/libs/gui/GLConsumer.cpp
index b886c5b..21bb4c4 100644
--- a/libs/gui/GLConsumer.cpp
+++ b/libs/gui/GLConsumer.cpp
@@ -47,18 +47,28 @@
 namespace android {
 
 // Macros for including the GLConsumer name in log messages
-#define ST_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
+#define GLC_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
+#define GLC_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define GLC_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
+#define GLC_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
+#define GLC_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
 
 static const struct {
-    size_t width, height;
+    uint32_t width, height;
     char const* bits;
 } kDebugData = { 15, 12,
-    "___________________________________XX_XX_______X_X_____X_X____X_XXXXXXX_X____XXXXXXXXXXX__"
-    "___XX_XXX_XX_______XXXXXXX_________X___X_________X_____X__________________________________"
+    "_______________"
+    "_______________"
+    "_____XX_XX_____"
+    "__X_X_____X_X__"
+    "__X_XXXXXXX_X__"
+    "__XXXXXXXXXXX__"
+    "___XX_XXX_XX___"
+    "____XXXXXXX____"
+    "_____X___X_____"
+    "____X_____X____"
+    "_______________"
+    "_______________"
 };
 
 // Transform matrices
@@ -135,7 +145,7 @@
     mCurrentTexture(BufferQueue::INVALID_BUFFER_SLOT),
     mAttached(true)
 {
-    ST_LOGV("GLConsumer");
+    GLC_LOGV("GLConsumer");
 
     memcpy(mCurrentTransformMatrix, mtxIdentity,
             sizeof(mCurrentTransformMatrix));
@@ -154,7 +164,7 @@
     mDefaultWidth(1),
     mDefaultHeight(1),
     mFilteringEnabled(true),
-    mTexName(-1),
+    mTexName(0),
     mUseFenceSync(useFenceSync),
     mTexTarget(texTarget),
     mEglDisplay(EGL_NO_DISPLAY),
@@ -162,7 +172,7 @@
     mCurrentTexture(BufferQueue::INVALID_BUFFER_SLOT),
     mAttached(false)
 {
-    ST_LOGV("GLConsumer");
+    GLC_LOGV("GLConsumer");
 
     memcpy(mCurrentTransformMatrix, mtxIdentity,
             sizeof(mCurrentTransformMatrix));
@@ -186,11 +196,11 @@
 
 status_t GLConsumer::updateTexImage() {
     ATRACE_CALL();
-    ST_LOGV("updateTexImage");
+    GLC_LOGV("updateTexImage");
     Mutex::Autolock lock(mMutex);
 
     if (mAbandoned) {
-        ST_LOGE("updateTexImage: GLConsumer is abandoned!");
+        GLC_LOGE("updateTexImage: GLConsumer is abandoned!");
         return NO_INIT;
     }
 
@@ -209,11 +219,11 @@
     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");
+            GLC_LOGV("updateTexImage: no buffers were available");
             glBindTexture(mTexTarget, mTexName);
             err = NO_ERROR;
         } else {
-            ST_LOGE("updateTexImage: acquire failed: %s (%d)",
+            GLC_LOGE("updateTexImage: acquire failed: %s (%d)",
                 strerror(-err), err);
         }
         return err;
@@ -234,11 +244,11 @@
 
 status_t GLConsumer::releaseTexImage() {
     ATRACE_CALL();
-    ST_LOGV("releaseTexImage");
+    GLC_LOGV("releaseTexImage");
     Mutex::Autolock lock(mMutex);
 
     if (mAbandoned) {
-        ST_LOGE("releaseTexImage: GLConsumer is abandoned!");
+        GLC_LOGE("releaseTexImage: GLConsumer is abandoned!");
         return NO_INIT;
     }
 
@@ -258,13 +268,13 @@
     int buf = mCurrentTexture;
     if (buf != BufferQueue::INVALID_BUFFER_SLOT) {
 
-        ST_LOGV("releaseTexImage: (slot=%d, mAttached=%d)", buf, mAttached);
+        GLC_LOGV("releaseTexImage: (slot=%d, mAttached=%d)", buf, mAttached);
 
         if (mAttached) {
             // Do whatever sync ops we need to do before releasing the slot.
             err = syncForReleaseLocked(mEglDisplay);
             if (err != NO_ERROR) {
-                ST_LOGE("syncForReleaseLocked failed (slot=%d), err=%d", buf, err);
+                GLC_LOGE("syncForReleaseLocked failed (slot=%d), err=%d", buf, err);
                 return err;
             }
         } else {
@@ -274,7 +284,7 @@
 
         err = releaseBufferLocked(buf, mSlots[buf].mGraphicBuffer, mEglDisplay, EGL_NO_SYNC_KHR);
         if (err < NO_ERROR) {
-            ST_LOGE("releaseTexImage: failed to release buffer: %s (%d)",
+            GLC_LOGE("releaseTexImage: failed to release buffer: %s (%d)",
                     strerror(-err), err);
             return err;
         }
@@ -293,9 +303,9 @@
 
         if (mAttached) {
             // This binds a dummy buffer (mReleasedTexImage).
-            status_t err =  bindTextureImageLocked();
-            if (err != NO_ERROR) {
-                return err;
+            status_t result = bindTextureImageLocked();
+            if (result != NO_ERROR) {
+                return result;
             }
         } else {
             // detached, don't touch the texture (and we may not even have an
@@ -316,14 +326,15 @@
                 GraphicBuffer::USAGE_SW_WRITE_RARELY);
         uint32_t* bits;
         buffer->lock(GraphicBuffer::USAGE_SW_WRITE_RARELY, reinterpret_cast<void**>(&bits));
-        size_t w = buffer->getStride();
-        size_t h = buffer->getHeight();
-        memset(bits, 0, w*h*4);
-        for (size_t y=0 ; y<kDebugData.height ; y++) {
-            for (size_t x=0 ; x<kDebugData.width ; x++) {
-                bits[x] = (kDebugData.bits[y*kDebugData.width+x] == 'X') ? 0xFF000000 : 0xFFFFFFFF;
+        uint32_t stride = buffer->getStride();
+        uint32_t height = buffer->getHeight();
+        memset(bits, 0, stride * height * 4);
+        for (uint32_t y = 0; y < kDebugData.height; y++) {
+            for (uint32_t x = 0; x < kDebugData.width; x++) {
+                bits[x] = (kDebugData.bits[y + kDebugData.width + x] == 'X') ?
+                    0xFF000000 : 0xFFFFFFFF;
             }
-            bits += w;
+            bits += stride;
         }
         buffer->unlock();
         sReleasedTexImageBuffer = buffer;
@@ -369,7 +380,7 @@
     int buf = item.mBuf;
 
     if (!mAttached) {
-        ST_LOGE("updateAndRelease: GLConsumer is not attached to an OpenGL "
+        GLC_LOGE("updateAndRelease: GLConsumer is not attached to an OpenGL "
                 "ES context");
         releaseBufferLocked(buf, mSlots[buf].mGraphicBuffer,
                 mEglDisplay, EGL_NO_SYNC_KHR);
@@ -391,7 +402,7 @@
     // means the buffer was previously acquired).
     err = mEglSlots[buf].mEglImage->createIfNeeded(mEglDisplay, item.mCrop);
     if (err != NO_ERROR) {
-        ST_LOGW("updateAndRelease: unable to createImage on display=%p slot=%d",
+        GLC_LOGW("updateAndRelease: unable to createImage on display=%p slot=%d",
                 mEglDisplay, buf);
         releaseBufferLocked(buf, mSlots[buf].mGraphicBuffer,
                 mEglDisplay, EGL_NO_SYNC_KHR);
@@ -410,7 +421,7 @@
         return err;
     }
 
-    ST_LOGV("updateAndRelease: (slot=%d buf=%p) -> (slot=%d buf=%p)",
+    GLC_LOGV("updateAndRelease: (slot=%d buf=%p) -> (slot=%d buf=%p)",
             mCurrentTexture, mCurrentTextureImage != NULL ?
                     mCurrentTextureImage->graphicBufferHandle() : 0,
             buf, mSlots[buf].mGraphicBuffer->handle);
@@ -421,7 +432,7 @@
                 mCurrentTexture, mCurrentTextureImage->graphicBuffer(),
                 mEglDisplay, mEglSlots[mCurrentTexture].mEglFence);
         if (status < NO_ERROR) {
-            ST_LOGE("updateAndRelease: failed to release buffer: %s (%d)",
+            GLC_LOGE("updateAndRelease: failed to release buffer: %s (%d)",
                    strerror(-status), status);
             err = status;
             // keep going, with error raised [?]
@@ -449,22 +460,22 @@
         return INVALID_OPERATION;
     }
 
-    GLint error;
+    GLenum error;
     while ((error = glGetError()) != GL_NO_ERROR) {
-        ST_LOGW("bindTextureImage: clearing GL error: %#04x", error);
+        GLC_LOGW("bindTextureImage: clearing GL error: %#04x", error);
     }
 
     glBindTexture(mTexTarget, mTexName);
     if (mCurrentTexture == BufferQueue::INVALID_BUFFER_SLOT &&
             mCurrentTextureImage == NULL) {
-        ST_LOGE("bindTextureImage: no currently-bound texture");
+        GLC_LOGE("bindTextureImage: no currently-bound texture");
         return NO_INIT;
     }
 
     status_t err = mCurrentTextureImage->createIfNeeded(mEglDisplay,
                                                         mCurrentCrop);
     if (err != NO_ERROR) {
-        ST_LOGW("bindTextureImage: can't create image on display=%p slot=%d",
+        GLC_LOGW("bindTextureImage: can't create image on display=%p slot=%d",
                 mEglDisplay, mCurrentTexture);
         return UNKNOWN_ERROR;
     }
@@ -476,17 +487,17 @@
     // forcing the creation of a new image.
     if ((error = glGetError()) != GL_NO_ERROR) {
         glBindTexture(mTexTarget, mTexName);
-        status_t err = mCurrentTextureImage->createIfNeeded(mEglDisplay,
-                                                            mCurrentCrop,
-                                                            true);
-        if (err != NO_ERROR) {
-            ST_LOGW("bindTextureImage: can't create image on display=%p slot=%d",
+        status_t result = mCurrentTextureImage->createIfNeeded(mEglDisplay,
+                                                               mCurrentCrop,
+                                                               true);
+        if (result != NO_ERROR) {
+            GLC_LOGW("bindTextureImage: can't create image on display=%p slot=%d",
                     mEglDisplay, mCurrentTexture);
             return UNKNOWN_ERROR;
         }
         mCurrentTextureImage->bindToTextureTarget(mTexTarget);
         if ((error = glGetError()) != GL_NO_ERROR) {
-            ST_LOGE("bindTextureImage: error binding external image: %#04x", error);
+            GLC_LOGE("bindTextureImage: error binding external image: %#04x", error);
             return UNKNOWN_ERROR;
         }
     }
@@ -511,12 +522,12 @@
     }
 
     if (mEglDisplay != dpy || dpy == EGL_NO_DISPLAY) {
-        ST_LOGE("checkAndUpdateEglState: invalid current EGLDisplay");
+        GLC_LOGE("checkAndUpdateEglState: invalid current EGLDisplay");
         return INVALID_OPERATION;
     }
 
     if (mEglContext != ctx || ctx == EGL_NO_CONTEXT) {
-        ST_LOGE("checkAndUpdateEglState: invalid current EGLContext");
+        GLC_LOGE("checkAndUpdateEglState: invalid current EGLContext");
         return INVALID_OPERATION;
     }
 
@@ -531,7 +542,7 @@
         status_t err = addReleaseFence(mCurrentTexture,
                 mCurrentTextureImage->graphicBuffer(), fence);
         if (err != OK) {
-            ST_LOGE("setReleaseFence: failed to add the fence: %s (%d)",
+            GLC_LOGE("setReleaseFence: failed to add the fence: %s (%d)",
                     strerror(-err), err);
         }
     }
@@ -539,16 +550,16 @@
 
 status_t GLConsumer::detachFromContext() {
     ATRACE_CALL();
-    ST_LOGV("detachFromContext");
+    GLC_LOGV("detachFromContext");
     Mutex::Autolock lock(mMutex);
 
     if (mAbandoned) {
-        ST_LOGE("detachFromContext: abandoned GLConsumer");
+        GLC_LOGE("detachFromContext: abandoned GLConsumer");
         return NO_INIT;
     }
 
     if (!mAttached) {
-        ST_LOGE("detachFromContext: GLConsumer is not attached to a "
+        GLC_LOGE("detachFromContext: GLConsumer is not attached to a "
                 "context");
         return INVALID_OPERATION;
     }
@@ -557,12 +568,12 @@
     EGLContext ctx = eglGetCurrentContext();
 
     if (mEglDisplay != dpy && mEglDisplay != EGL_NO_DISPLAY) {
-        ST_LOGE("detachFromContext: invalid current EGLDisplay");
+        GLC_LOGE("detachFromContext: invalid current EGLDisplay");
         return INVALID_OPERATION;
     }
 
     if (mEglContext != ctx && mEglContext != EGL_NO_CONTEXT) {
-        ST_LOGE("detachFromContext: invalid current EGLContext");
+        GLC_LOGE("detachFromContext: invalid current EGLContext");
         return INVALID_OPERATION;
     }
 
@@ -584,16 +595,16 @@
 
 status_t GLConsumer::attachToContext(uint32_t tex) {
     ATRACE_CALL();
-    ST_LOGV("attachToContext");
+    GLC_LOGV("attachToContext");
     Mutex::Autolock lock(mMutex);
 
     if (mAbandoned) {
-        ST_LOGE("attachToContext: abandoned GLConsumer");
+        GLC_LOGE("attachToContext: abandoned GLConsumer");
         return NO_INIT;
     }
 
     if (mAttached) {
-        ST_LOGE("attachToContext: GLConsumer is already attached to a "
+        GLC_LOGE("attachToContext: GLConsumer is already attached to a "
                 "context");
         return INVALID_OPERATION;
     }
@@ -602,12 +613,12 @@
     EGLContext ctx = eglGetCurrentContext();
 
     if (dpy == EGL_NO_DISPLAY) {
-        ST_LOGE("attachToContext: invalid current EGLDisplay");
+        GLC_LOGE("attachToContext: invalid current EGLDisplay");
         return INVALID_OPERATION;
     }
 
     if (ctx == EGL_NO_CONTEXT) {
-        ST_LOGE("attachToContext: invalid current EGLContext");
+        GLC_LOGE("attachToContext: invalid current EGLContext");
         return INVALID_OPERATION;
     }
 
@@ -636,14 +647,14 @@
 
 
 status_t GLConsumer::syncForReleaseLocked(EGLDisplay dpy) {
-    ST_LOGV("syncForReleaseLocked");
+    GLC_LOGV("syncForReleaseLocked");
 
     if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
         if (SyncFeatures::getInstance().useNativeFenceSync()) {
             EGLSyncKHR sync = eglCreateSyncKHR(dpy,
                     EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
             if (sync == EGL_NO_SYNC_KHR) {
-                ST_LOGE("syncForReleaseLocked: error creating EGL fence: %#x",
+                GLC_LOGE("syncForReleaseLocked: error creating EGL fence: %#x",
                         eglGetError());
                 return UNKNOWN_ERROR;
             }
@@ -651,7 +662,7 @@
             int fenceFd = eglDupNativeFenceFDANDROID(dpy, sync);
             eglDestroySyncKHR(dpy, sync);
             if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
-                ST_LOGE("syncForReleaseLocked: error dup'ing native fence "
+                GLC_LOGE("syncForReleaseLocked: error dup'ing native fence "
                         "fd: %#x", eglGetError());
                 return UNKNOWN_ERROR;
             }
@@ -659,7 +670,7 @@
             status_t err = addReleaseFenceLocked(mCurrentTexture,
                     mCurrentTextureImage->graphicBuffer(), fence);
             if (err != OK) {
-                ST_LOGE("syncForReleaseLocked: error adding release fence: "
+                GLC_LOGE("syncForReleaseLocked: error adding release fence: "
                         "%s (%d)", strerror(-err), err);
                 return err;
             }
@@ -672,11 +683,11 @@
                 // before the producer accesses it.
                 EGLint result = eglClientWaitSyncKHR(dpy, fence, 0, 1000000000);
                 if (result == EGL_FALSE) {
-                    ST_LOGE("syncForReleaseLocked: error waiting for previous "
+                    GLC_LOGE("syncForReleaseLocked: error waiting for previous "
                             "fence: %#x", eglGetError());
                     return UNKNOWN_ERROR;
                 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
-                    ST_LOGE("syncForReleaseLocked: timeout waiting for previous "
+                    GLC_LOGE("syncForReleaseLocked: timeout waiting for previous "
                             "fence");
                     return TIMED_OUT;
                 }
@@ -687,7 +698,7 @@
             // OpenGL ES context.
             fence = eglCreateSyncKHR(dpy, EGL_SYNC_FENCE_KHR, NULL);
             if (fence == EGL_NO_SYNC_KHR) {
-                ST_LOGE("syncForReleaseLocked: error creating fence: %#x",
+                GLC_LOGE("syncForReleaseLocked: error creating fence: %#x",
                         eglGetError());
                 return UNKNOWN_ERROR;
             }
@@ -699,7 +710,7 @@
     return OK;
 }
 
-bool GLConsumer::isExternalFormat(uint32_t format)
+bool GLConsumer::isExternalFormat(PixelFormat format)
 {
     switch (format) {
     // supported YUV formats
@@ -730,14 +741,14 @@
 void GLConsumer::setFilteringEnabled(bool enabled) {
     Mutex::Autolock lock(mMutex);
     if (mAbandoned) {
-        ST_LOGE("setFilteringEnabled: GLConsumer is abandoned!");
+        GLC_LOGE("setFilteringEnabled: GLConsumer is abandoned!");
         return;
     }
     bool needsRecompute = mFilteringEnabled != enabled;
     mFilteringEnabled = enabled;
 
     if (needsRecompute && mCurrentTextureImage==NULL) {
-        ST_LOGD("setFilteringEnabled called with mCurrentTextureImage == NULL");
+        GLC_LOGD("setFilteringEnabled called with mCurrentTextureImage == NULL");
     }
 
     if (needsRecompute && mCurrentTextureImage != NULL) {
@@ -746,7 +757,7 @@
 }
 
 void GLConsumer::computeCurrentTransformMatrixLocked() {
-    ST_LOGV("computeCurrentTransformMatrixLocked");
+    GLC_LOGV("computeCurrentTransformMatrixLocked");
 
     float xform[16];
     for (int i = 0; i < 16; i++) {
@@ -778,7 +789,7 @@
             NULL : mCurrentTextureImage->graphicBuffer();
 
     if (buf == NULL) {
-        ST_LOGD("computeCurrentTransformMatrixLocked: mCurrentTextureImage is NULL");
+        GLC_LOGD("computeCurrentTransformMatrixLocked: mCurrentTextureImage is NULL");
     }
 
     float mtxBeforeFlipV[16];
@@ -850,13 +861,13 @@
 }
 
 nsecs_t GLConsumer::getTimestamp() {
-    ST_LOGV("getTimestamp");
+    GLC_LOGV("getTimestamp");
     Mutex::Autolock lock(mMutex);
     return mCurrentTimestamp;
 }
 
-nsecs_t GLConsumer::getFrameNumber() {
-    ST_LOGV("getFrameNumber");
+uint64_t GLConsumer::getFrameNumber() {
+    GLC_LOGV("getFrameNumber");
     Mutex::Autolock lock(mMutex);
     return mCurrentFrameNumber;
 }
@@ -872,30 +883,33 @@
 
     Rect outCrop = mCurrentCrop;
     if (mCurrentScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
-        int32_t newWidth = mCurrentCrop.width();
-        int32_t newHeight = mCurrentCrop.height();
+        uint32_t newWidth = static_cast<uint32_t>(mCurrentCrop.width());
+        uint32_t newHeight = static_cast<uint32_t>(mCurrentCrop.height());
 
         if (newWidth * mDefaultHeight > newHeight * mDefaultWidth) {
             newWidth = newHeight * mDefaultWidth / mDefaultHeight;
-            ST_LOGV("too wide: newWidth = %d", newWidth);
+            GLC_LOGV("too wide: newWidth = %d", newWidth);
         } else if (newWidth * mDefaultHeight < newHeight * mDefaultWidth) {
             newHeight = newWidth * mDefaultHeight / mDefaultWidth;
-            ST_LOGV("too tall: newHeight = %d", newHeight);
+            GLC_LOGV("too tall: newHeight = %d", newHeight);
         }
 
+        uint32_t currentWidth = static_cast<uint32_t>(mCurrentCrop.width());
+        uint32_t currentHeight = static_cast<uint32_t>(mCurrentCrop.height());
+
         // The crop is too wide
-        if (newWidth < mCurrentCrop.width()) {
-            int32_t dw = (newWidth - mCurrentCrop.width())/2;
-            outCrop.left -=dw;
-            outCrop.right += dw;
+        if (newWidth < currentWidth) {
+            uint32_t dw = (currentWidth - newWidth) / 2;
+            outCrop.left += dw;
+            outCrop.right -= dw;
         // The crop is too tall
-        } else if (newHeight < mCurrentCrop.height()) {
-            int32_t dh = (newHeight - mCurrentCrop.height())/2;
-            outCrop.top -= dh;
-            outCrop.bottom += dh;
+        } else if (newHeight < currentHeight) {
+            uint32_t dh = (currentHeight - newHeight) / 2;
+            outCrop.top += dh;
+            outCrop.bottom -= dh;
         }
 
-        ST_LOGV("getCurrentCrop final crop [%d,%d,%d,%d]",
+        GLC_LOGV("getCurrentCrop final crop [%d,%d,%d,%d]",
             outCrop.left, outCrop.top,
             outCrop.right,outCrop.bottom);
     }
@@ -929,12 +943,12 @@
     EGLContext ctx = eglGetCurrentContext();
 
     if (mEglDisplay != dpy || mEglDisplay == EGL_NO_DISPLAY) {
-        ST_LOGE("doGLFenceWait: invalid current EGLDisplay");
+        GLC_LOGE("doGLFenceWait: invalid current EGLDisplay");
         return INVALID_OPERATION;
     }
 
     if (mEglContext != ctx || mEglContext == EGL_NO_CONTEXT) {
-        ST_LOGE("doGLFenceWait: invalid current EGLContext");
+        GLC_LOGE("doGLFenceWait: invalid current EGLContext");
         return INVALID_OPERATION;
     }
 
@@ -943,7 +957,7 @@
             // Create an EGLSyncKHR from the current fence.
             int fenceFd = mCurrentFence->dup();
             if (fenceFd == -1) {
-                ST_LOGE("doGLFenceWait: error dup'ing fence fd: %d", errno);
+                GLC_LOGE("doGLFenceWait: error dup'ing fence fd: %d", errno);
                 return -errno;
             }
             EGLint attribs[] = {
@@ -954,7 +968,7 @@
                     EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
             if (sync == EGL_NO_SYNC_KHR) {
                 close(fenceFd);
-                ST_LOGE("doGLFenceWait: error creating EGL fence: %#x",
+                GLC_LOGE("doGLFenceWait: error creating EGL fence: %#x",
                         eglGetError());
                 return UNKNOWN_ERROR;
             }
@@ -966,7 +980,7 @@
             EGLint eglErr = eglGetError();
             eglDestroySyncKHR(dpy, sync);
             if (eglErr != EGL_SUCCESS) {
-                ST_LOGE("doGLFenceWait: error waiting for EGL fence: %#x",
+                GLC_LOGE("doGLFenceWait: error waiting for EGL fence: %#x",
                         eglErr);
                 return UNKNOWN_ERROR;
             }
@@ -974,7 +988,7 @@
             status_t err = mCurrentFence->waitForever(
                     "GLConsumer::doGLFenceWaitLocked");
             if (err != NO_ERROR) {
-                ST_LOGE("doGLFenceWait: error waiting for fence: %d", err);
+                GLC_LOGE("doGLFenceWait: error waiting for fence: %d", err);
                 return err;
             }
         }
@@ -984,7 +998,7 @@
 }
 
 void GLConsumer::freeBufferLocked(int slotIndex) {
-    ST_LOGV("freeBufferLocked: slotIndex=%d", slotIndex);
+    GLC_LOGV("freeBufferLocked: slotIndex=%d", slotIndex);
     if (slotIndex == mCurrentTexture) {
         mCurrentTexture = BufferQueue::INVALID_BUFFER_SLOT;
     }
@@ -993,7 +1007,7 @@
 }
 
 void GLConsumer::abandonLocked() {
-    ST_LOGV("abandonLocked");
+    GLC_LOGV("abandonLocked");
     mCurrentTextureImage.clear();
     ConsumerBase::abandonLocked();
 }
@@ -1004,11 +1018,17 @@
     mConsumer->setConsumerName(name);
 }
 
-status_t GLConsumer::setDefaultBufferFormat(uint32_t defaultFormat) {
+status_t GLConsumer::setDefaultBufferFormat(PixelFormat defaultFormat) {
     Mutex::Autolock lock(mMutex);
     return mConsumer->setDefaultBufferFormat(defaultFormat);
 }
 
+status_t GLConsumer::setDefaultBufferDataSpace(
+        android_dataspace defaultDataSpace) {
+    Mutex::Autolock lock(mMutex);
+    return mConsumer->setDefaultBufferDataSpace(defaultDataSpace);
+}
+
 status_t GLConsumer::setConsumerUsageBits(uint32_t usage) {
     Mutex::Autolock lock(mMutex);
     usage |= DEFAULT_USAGE_FLAGS;
@@ -1107,12 +1127,14 @@
 }
 
 void GLConsumer::EglImage::bindToTextureTarget(uint32_t texTarget) {
-    glEGLImageTargetTexture2DOES(texTarget, (GLeglImageOES)mEglImage);
+    glEGLImageTargetTexture2DOES(texTarget,
+            static_cast<GLeglImageOES>(mEglImage));
 }
 
 EGLImageKHR GLConsumer::EglImage::createImage(EGLDisplay dpy,
         const sp<GraphicBuffer>& graphicBuffer, const Rect& crop) {
-    EGLClientBuffer cbuf = (EGLClientBuffer)graphicBuffer->getNativeBuffer();
+    EGLClientBuffer cbuf =
+            static_cast<EGLClientBuffer>(graphicBuffer->getNativeBuffer());
     EGLint attrs[] = {
         EGL_IMAGE_PRESERVED_KHR,        EGL_TRUE,
         EGL_IMAGE_CROP_LEFT_ANDROID,    crop.left,
diff --git a/libs/gui/GraphicBufferAlloc.cpp b/libs/gui/GraphicBufferAlloc.cpp
index b360e81..9643402 100644
--- a/libs/gui/GraphicBufferAlloc.cpp
+++ b/libs/gui/GraphicBufferAlloc.cpp
@@ -31,9 +31,10 @@
 GraphicBufferAlloc::~GraphicBufferAlloc() {
 }
 
-sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
-        PixelFormat format, uint32_t usage, status_t* error) {
-    sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
+sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t width,
+        uint32_t height, PixelFormat format, uint32_t usage, status_t* error) {
+    sp<GraphicBuffer> graphicBuffer(
+            new GraphicBuffer(width, height, format, usage));
     status_t err = graphicBuffer->initCheck();
     *error = err;
     if (err != 0 || graphicBuffer->handle == 0) {
@@ -42,7 +43,7 @@
         }
         ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
              "failed (%s), handle=%p",
-                w, h, strerror(-err), graphicBuffer->handle);
+                width, height, strerror(-err), graphicBuffer->handle);
         return 0;
     }
     return graphicBuffer;
diff --git a/libs/gui/IConsumerListener.cpp b/libs/gui/IConsumerListener.cpp
index 409dfe4..cab7dc3 100644
--- a/libs/gui/IConsumerListener.cpp
+++ b/libs/gui/IConsumerListener.cpp
@@ -40,6 +40,8 @@
         : BpInterface<IConsumerListener>(impl) {
     }
 
+    virtual ~BpConsumerListener();
+
     virtual void onFrameAvailable(const BufferItem& item) {
         Parcel data, reply;
         data.writeInterfaceToken(IConsumerListener::getInterfaceDescriptor());
@@ -60,6 +62,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpConsumerListener::~BpConsumerListener() {}
+
 IMPLEMENT_META_INTERFACE(ConsumerListener, "android.gui.IConsumerListener");
 
 // ----------------------------------------------------------------------
diff --git a/libs/gui/IDisplayEventConnection.cpp b/libs/gui/IDisplayEventConnection.cpp
index 887d176..9890f44 100644
--- a/libs/gui/IDisplayEventConnection.cpp
+++ b/libs/gui/IDisplayEventConnection.cpp
@@ -44,6 +44,8 @@
     {
     }
 
+    virtual ~BpDisplayEventConnection();
+
     virtual sp<BitTube> getDataChannel() const
     {
         Parcel data, reply;
@@ -55,7 +57,7 @@
     virtual void setVsyncRate(uint32_t count) {
         Parcel data, reply;
         data.writeInterfaceToken(IDisplayEventConnection::getInterfaceDescriptor());
-        data.writeInt32(count);
+        data.writeUint32(count);
         remote()->transact(SET_VSYNC_RATE, data, &reply);
     }
 
@@ -66,6 +68,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpDisplayEventConnection::~BpDisplayEventConnection() {}
+
 IMPLEMENT_META_INTERFACE(DisplayEventConnection, "android.gui.DisplayEventConnection");
 
 // ----------------------------------------------------------------------------
@@ -79,17 +85,17 @@
             sp<BitTube> channel(getDataChannel());
             channel->writeToParcel(reply);
             return NO_ERROR;
-        } break;
+        }
         case SET_VSYNC_RATE: {
             CHECK_INTERFACE(IDisplayEventConnection, data, reply);
-            setVsyncRate(data.readInt32());
+            setVsyncRate(data.readUint32());
             return NO_ERROR;
-        } break;
+        }
         case REQUEST_NEXT_VSYNC: {
             CHECK_INTERFACE(IDisplayEventConnection, data, reply);
             requestNextVsync();
             return NO_ERROR;
-        } break;
+        }
     }
     return BBinder::onTransact(code, data, reply, flags);
 }
diff --git a/libs/gui/IGraphicBufferAlloc.cpp b/libs/gui/IGraphicBufferAlloc.cpp
index 139f219..09b63a1 100644
--- a/libs/gui/IGraphicBufferAlloc.cpp
+++ b/libs/gui/IGraphicBufferAlloc.cpp
@@ -42,14 +42,17 @@
     {
     }
 
-    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
-            PixelFormat format, uint32_t usage, status_t* error) {
+    virtual ~BpGraphicBufferAlloc();
+
+    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t width,
+            uint32_t height, PixelFormat format, uint32_t usage,
+            status_t* error) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferAlloc::getInterfaceDescriptor());
-        data.writeInt32(w);
-        data.writeInt32(h);
-        data.writeInt32(format);
-        data.writeInt32(usage);
+        data.writeUint32(width);
+        data.writeUint32(height);
+        data.writeInt32(static_cast<int32_t>(format));
+        data.writeUint32(usage);
         remote()->transact(CREATE_GRAPHIC_BUFFER, data, &reply);
         sp<GraphicBuffer> graphicBuffer;
         status_t result = reply.readInt32();
@@ -65,6 +68,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpGraphicBufferAlloc::~BpGraphicBufferAlloc() {}
+
 IMPLEMENT_META_INTERFACE(GraphicBufferAlloc, "android.ui.IGraphicBufferAlloc");
 
 // ----------------------------------------------------------------------
@@ -74,27 +81,26 @@
 {
     // codes that don't require permission check
 
-    /* BufferReference just keeps a strong reference to a
-     * GraphicBuffer until it is destroyed (that is, until
-     * no local or remote process have a reference to it).
-     */
+    // BufferReference just keeps a strong reference to a GraphicBuffer until it
+    // is destroyed (that is, until no local or remote process have a reference
+    // to it).
     class BufferReference : public BBinder {
-        sp<GraphicBuffer> buffer;
+        sp<GraphicBuffer> mBuffer;
     public:
-        BufferReference(const sp<GraphicBuffer>& buffer) : buffer(buffer) { }
+        BufferReference(const sp<GraphicBuffer>& buffer) : mBuffer(buffer) {}
     };
 
 
-    switch(code) {
+    switch (code) {
         case CREATE_GRAPHIC_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferAlloc, data, reply);
-            uint32_t w = data.readInt32();
-            uint32_t h = data.readInt32();
-            PixelFormat format = data.readInt32();
-            uint32_t usage = data.readInt32();
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            PixelFormat format = static_cast<PixelFormat>(data.readInt32());
+            uint32_t usage = data.readUint32();
             status_t error;
             sp<GraphicBuffer> result =
-                    createGraphicBuffer(w, h, format, usage, &error);
+                    createGraphicBuffer(width, height, format, usage, &error);
             reply->writeInt32(error);
             if (result != 0) {
                 reply->write(*result);
@@ -107,7 +113,7 @@
                 reply->writeStrongBinder( new BufferReference(result) );
             }
             return NO_ERROR;
-        } break;
+        }
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/libs/gui/IGraphicBufferConsumer.cpp b/libs/gui/IGraphicBufferConsumer.cpp
index cc581a3..f38abbe 100644
--- a/libs/gui/IGraphicBufferConsumer.cpp
+++ b/libs/gui/IGraphicBufferConsumer.cpp
@@ -39,6 +39,7 @@
     mScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
     mTimestamp(0),
     mIsAutoTimestamp(false),
+    mDataSpace(HAL_DATASPACE_UNKNOWN),
     mFrameNumber(0),
     mBuf(INVALID_BUFFER_SLOT),
     mIsDroppable(false),
@@ -53,6 +54,7 @@
             sizeof(mScalingMode) +
             sizeof(mTimestamp) +
             sizeof(mIsAutoTimestamp) +
+            sizeof(mDataSpace) +
             sizeof(mFrameNumber) +
             sizeof(mBuf) +
             sizeof(mIsDroppable) +
@@ -133,6 +135,7 @@
     FlattenableUtils::write(buffer, size, mScalingMode);
     FlattenableUtils::write(buffer, size, mTimestamp);
     writeBoolAsInt(buffer, size, mIsAutoTimestamp);
+    FlattenableUtils::write(buffer, size, mDataSpace);
     FlattenableUtils::write(buffer, size, mFrameNumber);
     FlattenableUtils::write(buffer, size, mBuf);
     writeBoolAsInt(buffer, size, mIsDroppable);
@@ -175,6 +178,7 @@
     FlattenableUtils::read(buffer, size, mScalingMode);
     FlattenableUtils::read(buffer, size, mTimestamp);
     mIsAutoTimestamp = readBoolFromInt(buffer, size);
+    FlattenableUtils::read(buffer, size, mDataSpace);
     FlattenableUtils::read(buffer, size, mFrameNumber);
     FlattenableUtils::read(buffer, size, mBuf);
     mIsDroppable = readBoolFromInt(buffer, size);
@@ -200,6 +204,7 @@
     SET_MAX_ACQUIRED_BUFFER_COUNT,
     SET_CONSUMER_NAME,
     SET_DEFAULT_BUFFER_FORMAT,
+    SET_DEFAULT_BUFFER_DATA_SPACE,
     SET_CONSUMER_USAGE_BITS,
     SET_TRANSFORM_HINT,
     GET_SIDEBAND_STREAM,
@@ -215,6 +220,8 @@
     {
     }
 
+    virtual ~BpGraphicBufferConsumer();
+
     virtual status_t acquireBuffer(BufferItem *buffer, nsecs_t presentWhen) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
@@ -261,7 +268,7 @@
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
         data.writeInt32(buf);
-        data.writeInt64(frameNumber);
+        data.writeInt64(static_cast<int64_t>(frameNumber));
         data.write(*releaseFence);
         status_t result = remote()->transact(RELEASE_BUFFER, data, &reply);
         if (result != NO_ERROR) {
@@ -303,15 +310,15 @@
         if (result != NO_ERROR) {
             return result;
         }
-        *slotMask = reply.readInt64();
+        *slotMask = static_cast<uint64_t>(reply.readInt64());
         return reply.readInt32();
     }
 
-    virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h) {
+    virtual status_t setDefaultBufferSize(uint32_t width, uint32_t height) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
-        data.writeInt32(w);
-        data.writeInt32(h);
+        data.writeUint32(width);
+        data.writeUint32(height);
         status_t result = remote()->transact(SET_DEFAULT_BUFFER_SIZE, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -358,10 +365,10 @@
         remote()->transact(SET_CONSUMER_NAME, data, &reply);
     }
 
-    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat) {
+    virtual status_t setDefaultBufferFormat(PixelFormat defaultFormat) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
-        data.writeInt32(defaultFormat);
+        data.writeInt32(static_cast<int32_t>(defaultFormat));
         status_t result = remote()->transact(SET_DEFAULT_BUFFER_FORMAT, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -369,10 +376,23 @@
         return reply.readInt32();
     }
 
+    virtual status_t setDefaultBufferDataSpace(
+            android_dataspace defaultDataSpace) {
+        Parcel data, reply;
+        data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
+        data.writeInt32(static_cast<int32_t>(defaultDataSpace));
+        status_t result = remote()->transact(SET_DEFAULT_BUFFER_DATA_SPACE,
+                data, &reply);
+        if (result != NO_ERROR) {
+            return result;
+        }
+        return reply.readInt32();
+    }
+
     virtual status_t setConsumerUsageBits(uint32_t usage) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
-        data.writeInt32(usage);
+        data.writeUint32(usage);
         status_t result = remote()->transact(SET_CONSUMER_USAGE_BITS, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -383,7 +403,7 @@
     virtual status_t setTransformHint(uint32_t hint) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
-        data.writeInt32(hint);
+        data.writeUint32(hint);
         status_t result = remote()->transact(SET_TRANSFORM_HINT, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -415,6 +435,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpGraphicBufferConsumer::~BpGraphicBufferConsumer() {}
+
 IMPLEMENT_META_INTERFACE(GraphicBufferConsumer, "android.gui.IGraphicBufferConsumer");
 
 // ----------------------------------------------------------------------
@@ -432,14 +456,14 @@
             if (err) return err;
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DETACH_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             int slot = data.readInt32();
             int result = detachBuffer(slot);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case ATTACH_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             sp<GraphicBuffer> buffer = new GraphicBuffer();
@@ -449,11 +473,11 @@
             reply->writeInt32(slot);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case RELEASE_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             int buf = data.readInt32();
-            uint64_t frameNumber = data.readInt64();
+            uint64_t frameNumber = static_cast<uint64_t>(data.readInt64());
             sp<Fence> releaseFence = new Fence();
             status_t err = data.read(*releaseFence);
             if (err) return err;
@@ -461,7 +485,7 @@
                     EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case CONSUMER_CONNECT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             sp<IConsumerListener> consumer = IConsumerListener::asInterface( data.readStrongBinder() );
@@ -469,75 +493,83 @@
             status_t result = consumerConnect(consumer, controlledByApp);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case CONSUMER_DISCONNECT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             status_t result = consumerDisconnect();
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case GET_RELEASED_BUFFERS: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             uint64_t slotMask;
             status_t result = getReleasedBuffers(&slotMask);
-            reply->writeInt64(slotMask);
+            reply->writeInt64(static_cast<int64_t>(slotMask));
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_DEFAULT_BUFFER_SIZE: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t w = data.readInt32();
-            uint32_t h = data.readInt32();
-            status_t result = setDefaultBufferSize(w, h);
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            status_t result = setDefaultBufferSize(width, height);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_DEFAULT_MAX_BUFFER_COUNT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t bufferCount = data.readInt32();
+            int bufferCount = data.readInt32();
             status_t result = setDefaultMaxBufferCount(bufferCount);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DISABLE_ASYNC_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             status_t result = disableAsyncBuffer();
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_MAX_ACQUIRED_BUFFER_COUNT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t maxAcquiredBuffers = data.readInt32();
+            int maxAcquiredBuffers = data.readInt32();
             status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_CONSUMER_NAME: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             setConsumerName( data.readString8() );
             return NO_ERROR;
-        } break;
+        }
         case SET_DEFAULT_BUFFER_FORMAT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t defaultFormat = data.readInt32();
+            PixelFormat defaultFormat = static_cast<PixelFormat>(data.readInt32());
             status_t result = setDefaultBufferFormat(defaultFormat);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
+        case SET_DEFAULT_BUFFER_DATA_SPACE: {
+            CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
+            android_dataspace defaultDataSpace =
+                    static_cast<android_dataspace>(data.readInt32());
+            status_t result = setDefaultBufferDataSpace(defaultDataSpace);
+            reply->writeInt32(result);
+            return NO_ERROR;
+        }
         case SET_CONSUMER_USAGE_BITS: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t usage = data.readInt32();
+            uint32_t usage = data.readUint32();
             status_t result = setConsumerUsageBits(usage);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_TRANSFORM_HINT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t hint = data.readInt32();
+            uint32_t hint = data.readUint32();
             status_t result = setTransformHint(hint);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DUMP: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             String8 result = data.readString8();
diff --git a/libs/gui/IGraphicBufferProducer.cpp b/libs/gui/IGraphicBufferProducer.cpp
index bcdf368..a3e6fb2 100644
--- a/libs/gui/IGraphicBufferProducer.cpp
+++ b/libs/gui/IGraphicBufferProducer.cpp
@@ -56,6 +56,8 @@
     {
     }
 
+    virtual ~BpGraphicBufferProducer();
+
     virtual status_t requestBuffer(int bufferIdx, sp<GraphicBuffer>* buf) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
@@ -91,14 +93,15 @@
     }
 
     virtual status_t dequeueBuffer(int *buf, sp<Fence>* fence, bool async,
-            uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
+            uint32_t width, uint32_t height, PixelFormat format,
+            uint32_t usage) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
-        data.writeInt32(async);
-        data.writeInt32(w);
-        data.writeInt32(h);
-        data.writeInt32(format);
-        data.writeInt32(usage);
+        data.writeInt32(static_cast<int32_t>(async));
+        data.writeUint32(width);
+        data.writeUint32(height);
+        data.writeInt32(static_cast<int32_t>(format));
+        data.writeUint32(usage);
         status_t result = remote()->transact(DEQUEUE_BUFFER, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -255,14 +258,14 @@
     }
 
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage) {
+            PixelFormat format, uint32_t usage) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
         data.writeInt32(static_cast<int32_t>(async));
-        data.writeInt32(static_cast<int32_t>(width));
-        data.writeInt32(static_cast<int32_t>(height));
+        data.writeUint32(width);
+        data.writeUint32(height);
         data.writeInt32(static_cast<int32_t>(format));
-        data.writeInt32(static_cast<int32_t>(usage));
+        data.writeUint32(usage);
         status_t result = remote()->transact(ALLOCATE_BUFFERS, data, &reply);
         if (result != NO_ERROR) {
             ALOGE("allocateBuffers failed to transact: %d", result);
@@ -270,6 +273,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpGraphicBufferProducer::~BpGraphicBufferProducer() {}
+
 IMPLEMENT_META_INTERFACE(GraphicBufferProducer, "android.gui.IGraphicBufferProducer");
 
 // ----------------------------------------------------------------------
@@ -289,24 +296,25 @@
             }
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_BUFFER_COUNT: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int bufferCount = data.readInt32();
             int result = setBufferCount(bufferCount);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DEQUEUE_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
-            bool async      = data.readInt32();
-            uint32_t w      = data.readInt32();
-            uint32_t h      = data.readInt32();
-            uint32_t format = data.readInt32();
-            uint32_t usage  = data.readInt32();
+            bool async = static_cast<bool>(data.readInt32());
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            PixelFormat format = static_cast<PixelFormat>(data.readInt32());
+            uint32_t usage = data.readUint32();
             int buf;
             sp<Fence> fence;
-            int result = dequeueBuffer(&buf, &fence, async, w, h, format, usage);
+            int result = dequeueBuffer(&buf, &fence, async, width, height,
+                    format, usage);
             reply->writeInt32(buf);
             reply->writeInt32(fence != NULL);
             if (fence != NULL) {
@@ -314,14 +322,14 @@
             }
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DETACH_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int slot = data.readInt32();
             int result = detachBuffer(slot);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DETACH_NEXT_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             sp<GraphicBuffer> buffer;
@@ -339,7 +347,7 @@
                 }
             }
             return NO_ERROR;
-        } break;
+        }
         case ATTACH_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             sp<GraphicBuffer> buffer = new GraphicBuffer();
@@ -349,7 +357,7 @@
             reply->writeInt32(slot);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case QUEUE_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int buf = data.readInt32();
@@ -360,7 +368,7 @@
             status_t result = queueBuffer(buf, input, output);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case CANCEL_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int buf = data.readInt32();
@@ -368,7 +376,7 @@
             data.read(*fence.get());
             cancelBuffer(buf, fence);
             return NO_ERROR;
-        } break;
+        }
         case QUERY: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int value;
@@ -377,7 +385,7 @@
             reply->writeInt32(value);
             reply->writeInt32(res);
             return NO_ERROR;
-        } break;
+        }
         case CONNECT: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             sp<IProducerListener> listener;
@@ -392,14 +400,14 @@
             status_t res = connect(listener, api, producerControlledByApp, output);
             reply->writeInt32(res);
             return NO_ERROR;
-        } break;
+        }
         case DISCONNECT: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int api = data.readInt32();
             status_t res = disconnect(api);
             reply->writeInt32(res);
             return NO_ERROR;
-        } break;
+        }
         case SET_SIDEBAND_STREAM: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             sp<NativeHandle> stream;
@@ -409,14 +417,14 @@
             status_t result = setSidebandStream(stream);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case ALLOCATE_BUFFERS:
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             bool async = static_cast<bool>(data.readInt32());
-            uint32_t width = static_cast<uint32_t>(data.readInt32());
-            uint32_t height = static_cast<uint32_t>(data.readInt32());
-            uint32_t format = static_cast<uint32_t>(data.readInt32());
-            uint32_t usage = static_cast<uint32_t>(data.readInt32());
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            PixelFormat format = static_cast<PixelFormat>(data.readInt32());
+            uint32_t usage = data.readUint32();
             allocateBuffers(async, width, height, format, usage);
             return NO_ERROR;
     }
@@ -432,6 +440,7 @@
 size_t IGraphicBufferProducer::QueueBufferInput::getFlattenedSize() const {
     return sizeof(timestamp)
          + sizeof(isAutoTimestamp)
+         + sizeof(dataSpace)
          + sizeof(crop)
          + sizeof(scalingMode)
          + sizeof(transform)
@@ -452,6 +461,7 @@
     }
     FlattenableUtils::write(buffer, size, timestamp);
     FlattenableUtils::write(buffer, size, isAutoTimestamp);
+    FlattenableUtils::write(buffer, size, dataSpace);
     FlattenableUtils::write(buffer, size, crop);
     FlattenableUtils::write(buffer, size, scalingMode);
     FlattenableUtils::write(buffer, size, transform);
@@ -466,6 +476,7 @@
     size_t minNeeded =
               sizeof(timestamp)
             + sizeof(isAutoTimestamp)
+            + sizeof(dataSpace)
             + sizeof(crop)
             + sizeof(scalingMode)
             + sizeof(transform)
@@ -478,6 +489,7 @@
 
     FlattenableUtils::read(buffer, size, timestamp);
     FlattenableUtils::read(buffer, size, isAutoTimestamp);
+    FlattenableUtils::read(buffer, size, dataSpace);
     FlattenableUtils::read(buffer, size, crop);
     FlattenableUtils::read(buffer, size, scalingMode);
     FlattenableUtils::read(buffer, size, transform);
diff --git a/libs/gui/IProducerListener.cpp b/libs/gui/IProducerListener.cpp
index efe4069..81adc95 100644
--- a/libs/gui/IProducerListener.cpp
+++ b/libs/gui/IProducerListener.cpp
@@ -30,6 +30,8 @@
     BpProducerListener(const sp<IBinder>& impl)
         : BpInterface<IProducerListener>(impl) {}
 
+    virtual ~BpProducerListener();
+
     virtual void onBufferReleased() {
         Parcel data, reply;
         data.writeInterfaceToken(IProducerListener::getInterfaceDescriptor());
@@ -37,6 +39,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpProducerListener::~BpProducerListener() {}
+
 IMPLEMENT_META_INTERFACE(ProducerListener, "android.gui.IProducerListener")
 
 status_t BnProducerListener::onTransact(uint32_t code, const Parcel& data,
diff --git a/libs/gui/ISensorEventConnection.cpp b/libs/gui/ISensorEventConnection.cpp
index 28fcb53..dc7a35c 100644
--- a/libs/gui/ISensorEventConnection.cpp
+++ b/libs/gui/ISensorEventConnection.cpp
@@ -45,6 +45,8 @@
     {
     }
 
+    virtual ~BpSensorEventConnection();
+
     virtual sp<BitTube> getSensorChannel() const
     {
         Parcel data, reply;
@@ -85,6 +87,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpSensorEventConnection::~BpSensorEventConnection() {}
+
 IMPLEMENT_META_INTERFACE(SensorEventConnection, "android.gui.SensorEventConnection");
 
 // ----------------------------------------------------------------------------
@@ -98,7 +104,7 @@
             sp<BitTube> channel(getSensorChannel());
             channel->writeToParcel(reply);
             return NO_ERROR;
-        } break;
+        }
         case ENABLE_DISABLE: {
             CHECK_INTERFACE(ISensorEventConnection, data, reply);
             int handle = data.readInt32();
@@ -110,21 +116,21 @@
                                             maxBatchReportLatencyNs, reservedFlags);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_EVENT_RATE: {
             CHECK_INTERFACE(ISensorEventConnection, data, reply);
             int handle = data.readInt32();
-            int ns = data.readInt64();
+            nsecs_t ns = data.readInt64();
             status_t result = setEventRate(handle, ns);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case FLUSH_SENSOR: {
             CHECK_INTERFACE(ISensorEventConnection, data, reply);
             status_t result = flush();
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
     }
     return BBinder::onTransact(code, data, reply, flags);
 }
diff --git a/libs/gui/ISensorServer.cpp b/libs/gui/ISensorServer.cpp
index a8464a2..8e09e7c 100644
--- a/libs/gui/ISensorServer.cpp
+++ b/libs/gui/ISensorServer.cpp
@@ -45,6 +45,8 @@
     {
     }
 
+    virtual ~BpSensorServer();
+
     virtual Vector<Sensor> getSensorList()
     {
         Parcel data, reply;
@@ -52,7 +54,7 @@
         remote()->transact(GET_SENSOR_LIST, data, &reply);
         Sensor s;
         Vector<Sensor> v;
-        int32_t n = reply.readInt32();
+        uint32_t n = reply.readUint32();
         v.setCapacity(n);
         while (n--) {
             reply.read(s);
@@ -70,6 +72,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpSensorServer::~BpSensorServer() {}
+
 IMPLEMENT_META_INTERFACE(SensorServer, "android.gui.SensorServer");
 
 // ----------------------------------------------------------------------
@@ -82,18 +88,18 @@
             CHECK_INTERFACE(ISensorServer, data, reply);
             Vector<Sensor> v(getSensorList());
             size_t n = v.size();
-            reply->writeInt32(n);
-            for (size_t i=0 ; i<n ; i++) {
+            reply->writeUint32(static_cast<uint32_t>(n));
+            for (size_t i = 0; i < n; i++) {
                 reply->write(v[i]);
             }
             return NO_ERROR;
-        } break;
+        }
         case CREATE_SENSOR_EVENT_CONNECTION: {
             CHECK_INTERFACE(ISensorServer, data, reply);
             sp<ISensorEventConnection> connection(createSensorEventConnection());
             reply->writeStrongBinder(IInterface::asBinder(connection));
             return NO_ERROR;
-        } break;
+        }
     }
     return BBinder::onTransact(code, data, reply, flags);
 }
diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp
index 00173c7..78886d5 100644
--- a/libs/gui/ISurfaceComposer.cpp
+++ b/libs/gui/ISurfaceComposer.cpp
@@ -51,6 +51,8 @@
     {
     }
 
+    virtual ~BpSurfaceComposer();
+
     virtual sp<ISurfaceComposerClient> createConnection()
     {
         Parcel data, reply;
@@ -74,23 +76,18 @@
     {
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
-        {
-            Vector<ComposerState>::const_iterator b(state.begin());
-            Vector<ComposerState>::const_iterator e(state.end());
-            data.writeInt32(state.size());
-            for ( ; b != e ; ++b ) {
-                b->write(data);
-            }
+
+        data.writeUint32(static_cast<uint32_t>(state.size()));
+        for (const auto& s : state) {
+            s.write(data);
         }
-        {
-            Vector<DisplayState>::const_iterator b(displays.begin());
-            Vector<DisplayState>::const_iterator e(displays.end());
-            data.writeInt32(displays.size());
-            for ( ; b != e ; ++b ) {
-                b->write(data);
-            }
+
+        data.writeUint32(static_cast<uint32_t>(displays.size()));
+        for (const auto& d : displays) {
+            d.write(data);
         }
-        data.writeInt32(flags);
+
+        data.writeUint32(flags);
         remote()->transact(BnSurfaceComposer::SET_TRANSACTION_STATE, data, &reply);
     }
 
@@ -113,10 +110,10 @@
         data.writeStrongBinder(display);
         data.writeStrongBinder(IInterface::asBinder(producer));
         data.write(sourceCrop);
-        data.writeInt32(reqWidth);
-        data.writeInt32(reqHeight);
-        data.writeInt32(minLayerZ);
-        data.writeInt32(maxLayerZ);
+        data.writeUint32(reqWidth);
+        data.writeUint32(reqHeight);
+        data.writeUint32(minLayerZ);
+        data.writeUint32(maxLayerZ);
         data.writeInt32(static_cast<int32_t>(useIdentityTransform));
         data.writeInt32(static_cast<int32_t>(rotation));
         remote()->transact(BnSurfaceComposer::CAPTURE_SCREEN, data, &reply);
@@ -224,7 +221,7 @@
         remote()->transact(BnSurfaceComposer::GET_DISPLAY_CONFIGS, data, &reply);
         status_t result = reply.readInt32();
         if (result == NO_ERROR) {
-            size_t numConfigs = static_cast<size_t>(reply.readInt32());
+            size_t numConfigs = reply.readUint32();
             configs->clear();
             configs->resize(numConfigs);
             for (size_t c = 0; c < numConfigs; ++c) {
@@ -287,6 +284,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpSurfaceComposer::~BpSurfaceComposer() {}
+
 IMPLEMENT_META_INTERFACE(SurfaceComposer, "android.ui.ISurfaceComposer");
 
 // ----------------------------------------------------------------------
@@ -309,34 +310,37 @@
         }
         case SET_TRANSACTION_STATE: {
             CHECK_INTERFACE(ISurfaceComposer, data, reply);
-            size_t count = data.readInt32();
+
+            size_t count = data.readUint32();
             if (count > data.dataSize()) {
                 return BAD_VALUE;
             }
             ComposerState s;
             Vector<ComposerState> state;
             state.setCapacity(count);
-            for (size_t i=0 ; i<count ; i++) {
+            for (size_t i = 0; i < count; i++) {
                 if (s.read(data) == BAD_VALUE) {
                     return BAD_VALUE;
                 }
                 state.add(s);
             }
-            count = data.readInt32();
+
+            count = data.readUint32();
             if (count > data.dataSize()) {
                 return BAD_VALUE;
             }
             DisplayState d;
             Vector<DisplayState> displays;
             displays.setCapacity(count);
-            for (size_t i=0 ; i<count ; i++) {
+            for (size_t i = 0; i < count; i++) {
                 if (d.read(data) == BAD_VALUE) {
                     return BAD_VALUE;
                 }
                 displays.add(d);
             }
-            uint32_t flags = data.readInt32();
-            setTransactionState(state, displays, flags);
+
+            uint32_t stateFlags = data.readUint32();
+            setTransactionState(state, displays, stateFlags);
             return NO_ERROR;
         }
         case BOOT_FINISHED: {
@@ -351,12 +355,12 @@
                     interface_cast<IGraphicBufferProducer>(data.readStrongBinder());
             Rect sourceCrop;
             data.read(sourceCrop);
-            uint32_t reqWidth = data.readInt32();
-            uint32_t reqHeight = data.readInt32();
-            uint32_t minLayerZ = data.readInt32();
-            uint32_t maxLayerZ = data.readInt32();
+            uint32_t reqWidth = data.readUint32();
+            uint32_t reqHeight = data.readUint32();
+            uint32_t minLayerZ = data.readUint32();
+            uint32_t maxLayerZ = data.readUint32();
             bool useIdentityTransform = static_cast<bool>(data.readInt32());
-            uint32_t rotation = data.readInt32();
+            int32_t rotation = data.readInt32();
 
             status_t res = captureScreen(display, producer,
                     sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
@@ -407,7 +411,7 @@
             status_t result = getDisplayConfigs(display, &configs);
             reply->writeInt32(result);
             if (result == NO_ERROR) {
-                reply->writeInt32(static_cast<int32_t>(configs.size()));
+                reply->writeUint32(static_cast<uint32_t>(configs.size()));
                 for (size_t c = 0; c < configs.size(); ++c) {
                     memcpy(reply->writeInplace(sizeof(DisplayInfo)),
                             &configs[c], sizeof(DisplayInfo));
@@ -467,8 +471,6 @@
             return BBinder::onTransact(code, data, reply, flags);
         }
     }
-    // should be unreachable
-    return NO_ERROR;
 }
 
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/ISurfaceComposerClient.cpp b/libs/gui/ISurfaceComposerClient.cpp
index de4d8c1..2ecb908 100644
--- a/libs/gui/ISurfaceComposerClient.cpp
+++ b/libs/gui/ISurfaceComposerClient.cpp
@@ -51,17 +51,19 @@
         : BpInterface<ISurfaceComposerClient>(impl) {
     }
 
-    virtual status_t createSurface(const String8& name, uint32_t w,
-            uint32_t h, PixelFormat format, uint32_t flags,
+    virtual ~BpSurfaceComposerClient();
+
+    virtual status_t createSurface(const String8& name, uint32_t width,
+            uint32_t height, PixelFormat format, uint32_t flags,
             sp<IBinder>* handle,
             sp<IGraphicBufferProducer>* gbp) {
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceComposerClient::getInterfaceDescriptor());
         data.writeString8(name);
-        data.writeInt32(w);
-        data.writeInt32(h);
-        data.writeInt32(format);
-        data.writeInt32(flags);
+        data.writeUint32(width);
+        data.writeUint32(height);
+        data.writeInt32(static_cast<int32_t>(format));
+        data.writeUint32(flags);
         remote()->transact(CREATE_SURFACE, data, &reply);
         *handle = reply.readStrongBinder();
         *gbp = interface_cast<IGraphicBufferProducer>(reply.readStrongBinder());
@@ -94,6 +96,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpSurfaceComposerClient::~BpSurfaceComposerClient() {}
+
 IMPLEMENT_META_INTERFACE(SurfaceComposerClient, "android.ui.ISurfaceComposerClient");
 
 // ----------------------------------------------------------------------
@@ -105,31 +111,31 @@
         case CREATE_SURFACE: {
             CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
             String8 name = data.readString8();
-            uint32_t w = data.readInt32();
-            uint32_t h = data.readInt32();
-            PixelFormat format = data.readInt32();
-            uint32_t flags = data.readInt32();
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            PixelFormat format = static_cast<PixelFormat>(data.readInt32());
+            uint32_t createFlags = data.readUint32();
             sp<IBinder> handle;
             sp<IGraphicBufferProducer> gbp;
-            status_t result = createSurface(name, w, h, format, flags,
-                    &handle, &gbp);
+            status_t result = createSurface(name, width, height, format,
+                    createFlags, &handle, &gbp);
             reply->writeStrongBinder(handle);
             reply->writeStrongBinder(IInterface::asBinder(gbp));
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DESTROY_SURFACE: {
             CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
             reply->writeInt32(destroySurface( data.readStrongBinder() ) );
             return NO_ERROR;
-        } break;
+        }
        case CLEAR_LAYER_FRAME_STATS: {
             CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
             sp<IBinder> handle = data.readStrongBinder();
             status_t result = clearLayerFrameStats(handle);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case GET_LAYER_FRAME_STATS: {
             CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
             sp<IBinder> handle = data.readStrongBinder();
@@ -138,7 +144,7 @@
             reply->write(stats);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/libs/gui/LayerState.cpp b/libs/gui/LayerState.cpp
index ccf8b78..00323dc 100644
--- a/libs/gui/LayerState.cpp
+++ b/libs/gui/LayerState.cpp
@@ -25,16 +25,16 @@
 status_t layer_state_t::write(Parcel& output) const
 {
     output.writeStrongBinder(surface);
-    output.writeInt32(what);
+    output.writeUint32(what);
     output.writeFloat(x);
     output.writeFloat(y);
-    output.writeInt32(z);
-    output.writeInt32(w);
-    output.writeInt32(h);
-    output.writeInt32(layerStack);
+    output.writeUint32(z);
+    output.writeUint32(w);
+    output.writeUint32(h);
+    output.writeUint32(layerStack);
     output.writeFloat(alpha);
-    output.writeInt32(flags);
-    output.writeInt32(mask);
+    output.writeUint32(flags);
+    output.writeUint32(mask);
     *reinterpret_cast<layer_state_t::matrix22_t *>(
             output.writeInplace(sizeof(layer_state_t::matrix22_t))) = matrix;
     output.write(crop);
@@ -45,16 +45,16 @@
 status_t layer_state_t::read(const Parcel& input)
 {
     surface = input.readStrongBinder();
-    what = input.readInt32();
+    what = input.readUint32();
     x = input.readFloat();
     y = input.readFloat();
-    z = input.readInt32();
-    w = input.readInt32();
-    h = input.readInt32();
-    layerStack = input.readInt32();
+    z = input.readUint32();
+    w = input.readUint32();
+    h = input.readUint32();
+    layerStack = input.readUint32();
     alpha = input.readFloat();
-    flags = input.readInt32();
-    mask = input.readInt32();
+    flags = static_cast<uint8_t>(input.readUint32());
+    mask = static_cast<uint8_t>(input.readUint32());
     const void* matrix_data = input.readInplace(sizeof(layer_state_t::matrix22_t));
     if (matrix_data) {
         matrix = *reinterpret_cast<layer_state_t::matrix22_t const *>(matrix_data);
@@ -80,26 +80,26 @@
 status_t DisplayState::write(Parcel& output) const {
     output.writeStrongBinder(token);
     output.writeStrongBinder(IInterface::asBinder(surface));
-    output.writeInt32(what);
-    output.writeInt32(layerStack);
-    output.writeInt32(orientation);
+    output.writeUint32(what);
+    output.writeUint32(layerStack);
+    output.writeUint32(orientation);
     output.write(viewport);
     output.write(frame);
-    output.writeInt32(width);
-    output.writeInt32(height);
+    output.writeUint32(width);
+    output.writeUint32(height);
     return NO_ERROR;
 }
 
 status_t DisplayState::read(const Parcel& input) {
     token = input.readStrongBinder();
     surface = interface_cast<IGraphicBufferProducer>(input.readStrongBinder());
-    what = input.readInt32();
-    layerStack = input.readInt32();
-    orientation = input.readInt32();
+    what = input.readUint32();
+    layerStack = input.readUint32();
+    orientation = input.readUint32();
     input.read(viewport);
     input.read(frame);
-    width = input.readInt32();
-    height = input.readInt32();
+    width = input.readUint32();
+    height = input.readUint32();
     return NO_ERROR;
 }
 
diff --git a/libs/gui/Sensor.cpp b/libs/gui/Sensor.cpp
index 41a45fc..35661f2 100644
--- a/libs/gui/Sensor.cpp
+++ b/libs/gui/Sensor.cpp
@@ -72,7 +72,7 @@
                   static_cast<int64_t>(hwSensor->maxDelay));
             mMaxDelay = INT_MAX;
         } else {
-            mMaxDelay = (int32_t) hwSensor->maxDelay;
+            mMaxDelay = static_cast<int32_t>(hwSensor->maxDelay);
         }
     } else {
         // For older hals set maxDelay to 0.
@@ -221,7 +221,7 @@
         }
 
         if (halVersion >= SENSORS_DEVICE_API_VERSION_1_3) {
-            mFlags = (int32_t) hwSensor->flags;
+            mFlags = static_cast<uint32_t>(hwSensor->flags);
         } else {
             // This is an OEM defined sensor on an older HAL. Use minDelay to determine the
             // reporting mode of the sensor.
@@ -302,11 +302,11 @@
     return mVersion;
 }
 
-int32_t Sensor::getFifoReservedEventCount() const {
+uint32_t Sensor::getFifoReservedEventCount() const {
     return mFifoReservedEventCount;
 }
 
-int32_t Sensor::getFifoMaxEventCount() const {
+uint32_t Sensor::getFifoMaxEventCount() const {
     return mFifoMaxEventCount;
 }
 
@@ -322,7 +322,7 @@
     return mMaxDelay;
 }
 
-int32_t Sensor::getFlags() const {
+uint32_t Sensor::getFlags() const {
     return mFlags;
 }
 
@@ -414,7 +414,7 @@
 
 void Sensor::flattenString8(void*& buffer, size_t& size,
         const String8& string8) {
-    uint32_t len = string8.length();
+    uint32_t len = static_cast<uint32_t>(string8.length());
     FlattenableUtils::write(buffer, size, len);
     memcpy(static_cast<char*>(buffer), string8.string(), len);
     FlattenableUtils::advance(buffer, size, FlattenableUtils::align<4>(len));
diff --git a/libs/gui/SensorEventQueue.cpp b/libs/gui/SensorEventQueue.cpp
index 6f5f204..76ae470 100644
--- a/libs/gui/SensorEventQueue.cpp
+++ b/libs/gui/SensorEventQueue.cpp
@@ -16,6 +16,7 @@
 
 #define LOG_TAG "Sensors"
 
+#include <algorithm>
 #include <stdint.h>
 #include <sys/types.h>
 #include <sys/socket.h>
@@ -31,6 +32,8 @@
 
 #include <android/sensor.h>
 
+using std::min;
+
 // ----------------------------------------------------------------------------
 namespace android {
 // ----------------------------------------------------------------------------
@@ -68,14 +71,14 @@
         if (err < 0) {
             return err;
         }
-        mAvailable = err;
+        mAvailable = static_cast<size_t>(err);
         mConsumed = 0;
     }
-    size_t count = numEvents < mAvailable ? numEvents : mAvailable;
-    memcpy(events, mRecBuffer + mConsumed, count*sizeof(ASensorEvent));
+    size_t count = min(numEvents, mAvailable);
+    memcpy(events, mRecBuffer + mConsumed, count * sizeof(ASensorEvent));
     mAvailable -= count;
     mConsumed += count;
-    return count;
+    return static_cast<ssize_t>(count);
 }
 
 sp<Looper> SensorEventQueue::getLooper() const
diff --git a/libs/gui/SensorManager.cpp b/libs/gui/SensorManager.cpp
index 17960ff..d6df404 100644
--- a/libs/gui/SensorManager.cpp
+++ b/libs/gui/SensorManager.cpp
@@ -90,7 +90,8 @@
 
         mSensors = mSensorServer->getSensorList();
         size_t count = mSensors.size();
-        mSensorList = (Sensor const**)malloc(count * sizeof(Sensor*));
+        mSensorList =
+                static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
         for (size_t i=0 ; i<count ; i++) {
             mSensorList[i] = mSensors.array() + i;
         }
@@ -106,10 +107,10 @@
     Mutex::Autolock _l(mLock);
     status_t err = assertStateLocked();
     if (err < 0) {
-        return ssize_t(err);
+        return static_cast<ssize_t>(err);
     }
     *list = mSensorList;
-    return mSensors.size();
+    return static_cast<ssize_t>(mSensors.size());
 }
 
 Sensor const* SensorManager::getDefaultSensor(int type)
diff --git a/libs/gui/StreamSplitter.cpp b/libs/gui/StreamSplitter.cpp
index 25e6cab..1461337 100644
--- a/libs/gui/StreamSplitter.cpp
+++ b/libs/gui/StreamSplitter.cpp
@@ -141,7 +141,8 @@
 
     IGraphicBufferProducer::QueueBufferInput queueInput(
             bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp,
-            bufferItem.mCrop, bufferItem.mScalingMode,
+            bufferItem.mDataSpace, bufferItem.mCrop,
+            static_cast<int32_t>(bufferItem.mScalingMode),
             bufferItem.mTransform, bufferItem.mIsDroppable,
             bufferItem.mFence);
 
diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp
index ab984de..aa6f97e 100644
--- a/libs/gui/Surface.cpp
+++ b/libs/gui/Surface.cpp
@@ -64,6 +64,7 @@
     mReqFormat = 0;
     mReqUsage = 0;
     mTimestamp = NATIVE_WINDOW_TIMESTAMP_AUTO;
+    mDataSpace = HAL_DATASPACE_UNKNOWN;
     mCrop.clear();
     mScalingMode = NATIVE_WINDOW_SCALING_MODE_FREEZE;
     mTransform = 0;
@@ -193,17 +194,17 @@
     ATRACE_CALL();
     ALOGV("Surface::dequeueBuffer");
 
-    int reqW;
-    int reqH;
+    uint32_t reqWidth;
+    uint32_t reqHeight;
     bool swapIntervalZero;
-    uint32_t reqFormat;
+    PixelFormat reqFormat;
     uint32_t reqUsage;
 
     {
         Mutex::Autolock lock(mMutex);
 
-        reqW = mReqWidth ? mReqWidth : mUserWidth;
-        reqH = mReqHeight ? mReqHeight : mUserHeight;
+        reqWidth = mReqWidth ? mReqWidth : mUserWidth;
+        reqHeight = mReqHeight ? mReqHeight : mUserHeight;
 
         swapIntervalZero = mSwapIntervalZero;
         reqFormat = mReqFormat;
@@ -213,12 +214,12 @@
     int buf = -1;
     sp<Fence> fence;
     status_t result = mGraphicBufferProducer->dequeueBuffer(&buf, &fence, swapIntervalZero,
-            reqW, reqH, reqFormat, reqUsage);
+            reqWidth, reqHeight, reqFormat, reqUsage);
 
     if (result < 0) {
         ALOGV("dequeueBuffer: IGraphicBufferProducer::dequeueBuffer(%d, %d, %d, %d, %d)"
-             "failed: %d", swapIntervalZero, reqW, reqH, reqFormat, reqUsage,
-             result);
+             "failed: %d", swapIntervalZero, reqWidth, reqHeight, reqFormat,
+             reqUsage, result);
         return result;
     }
 
@@ -317,8 +318,8 @@
     sp<Fence> fence(fenceFd >= 0 ? new Fence(fenceFd) : Fence::NO_FENCE);
     IGraphicBufferProducer::QueueBufferOutput output;
     IGraphicBufferProducer::QueueBufferInput input(timestamp, isAutoTimestamp,
-            crop, mScalingMode, mTransform ^ mStickyTransform, mSwapIntervalZero,
-            fence, mStickyTransform);
+            mDataSpace, crop, mScalingMode, mTransform ^ mStickyTransform,
+            mSwapIntervalZero, fence, mStickyTransform);
     status_t err = mGraphicBufferProducer->queueBuffer(i, input, &output);
     if (err != OK)  {
         ALOGE("queueBuffer: error queuing buffer to SurfaceTexture, %d", err);
@@ -346,7 +347,7 @@
         switch (what) {
             case NATIVE_WINDOW_FORMAT:
                 if (mReqFormat) {
-                    *value = mReqFormat;
+                    *value = static_cast<int>(mReqFormat);
                     return NO_ERROR;
                 }
                 break;
@@ -364,13 +365,15 @@
                 *value = NATIVE_WINDOW_SURFACE;
                 return NO_ERROR;
             case NATIVE_WINDOW_DEFAULT_WIDTH:
-                *value = mUserWidth ? mUserWidth : mDefaultWidth;
+                *value = static_cast<int>(
+                        mUserWidth ? mUserWidth : mDefaultWidth);
                 return NO_ERROR;
             case NATIVE_WINDOW_DEFAULT_HEIGHT:
-                *value = mUserHeight ? mUserHeight : mDefaultHeight;
+                *value = static_cast<int>(
+                        mUserHeight ? mUserHeight : mDefaultHeight);
                 return NO_ERROR;
             case NATIVE_WINDOW_TRANSFORM_HINT:
-                *value = mTransformHint;
+                *value = static_cast<int>(mTransformHint);
                 return NO_ERROR;
             case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND: {
                 status_t err = NO_ERROR;
@@ -447,6 +450,9 @@
     case NATIVE_WINDOW_SET_SIDEBAND_STREAM:
         res = dispatchSetSidebandStream(args);
         break;
+    case NATIVE_WINDOW_SET_BUFFERS_DATASPACE:
+        res = dispatchSetBuffersDataSpace(args);
+        break;
     default:
         res = NAME_NOT_FOUND;
         break;
@@ -466,7 +472,7 @@
 
 int Surface::dispatchSetUsage(va_list args) {
     int usage = va_arg(args, int);
-    return setUsage(usage);
+    return setUsage(static_cast<uint32_t>(usage));
 }
 
 int Surface::dispatchSetCrop(va_list args) {
@@ -476,49 +482,49 @@
 
 int Surface::dispatchSetBufferCount(va_list args) {
     size_t bufferCount = va_arg(args, size_t);
-    return setBufferCount(bufferCount);
+    return setBufferCount(static_cast<int32_t>(bufferCount));
 }
 
 int Surface::dispatchSetBuffersGeometry(va_list args) {
-    int w = va_arg(args, int);
-    int h = va_arg(args, int);
-    int f = va_arg(args, int);
-    int err = setBuffersDimensions(w, h);
+    uint32_t width = va_arg(args, uint32_t);
+    uint32_t height = va_arg(args, uint32_t);
+    PixelFormat format = va_arg(args, PixelFormat);
+    int err = setBuffersDimensions(width, height);
     if (err != 0) {
         return err;
     }
-    return setBuffersFormat(f);
+    return setBuffersFormat(format);
 }
 
 int Surface::dispatchSetBuffersDimensions(va_list args) {
-    int w = va_arg(args, int);
-    int h = va_arg(args, int);
-    return setBuffersDimensions(w, h);
+    uint32_t width = va_arg(args, uint32_t);
+    uint32_t height = va_arg(args, uint32_t);
+    return setBuffersDimensions(width, height);
 }
 
 int Surface::dispatchSetBuffersUserDimensions(va_list args) {
-    int w = va_arg(args, int);
-    int h = va_arg(args, int);
-    return setBuffersUserDimensions(w, h);
+    uint32_t width = va_arg(args, uint32_t);
+    uint32_t height = va_arg(args, uint32_t);
+    return setBuffersUserDimensions(width, height);
 }
 
 int Surface::dispatchSetBuffersFormat(va_list args) {
-    int f = va_arg(args, int);
-    return setBuffersFormat(f);
+    PixelFormat format = va_arg(args, PixelFormat);
+    return setBuffersFormat(format);
 }
 
 int Surface::dispatchSetScalingMode(va_list args) {
-    int m = va_arg(args, int);
-    return setScalingMode(m);
+    int mode = va_arg(args, int);
+    return setScalingMode(mode);
 }
 
 int Surface::dispatchSetBuffersTransform(va_list args) {
-    int transform = va_arg(args, int);
+    uint32_t transform = va_arg(args, uint32_t);
     return setBuffersTransform(transform);
 }
 
 int Surface::dispatchSetBuffersStickyTransform(va_list args) {
-    int transform = va_arg(args, int);
+    uint32_t transform = va_arg(args, uint32_t);
     return setBuffersStickyTransform(transform);
 }
 
@@ -544,10 +550,20 @@
     return OK;
 }
 
+int Surface::dispatchSetBuffersDataSpace(va_list args) {
+    android_dataspace dataspace =
+            static_cast<android_dataspace>(va_arg(args, int));
+    return setBuffersDataSpace(dataspace);
+}
+
 int Surface::connect(int api) {
+    static sp<IProducerListener> listener = new DummyProducerListener();
+    return connect(api, listener);
+}
+
+int Surface::connect(int api, const sp<IProducerListener>& listener) {
     ATRACE_CALL();
     ALOGV("Surface::connect");
-    static sp<IProducerListener> listener = new DummyProducerListener();
     Mutex::Autolock lock(mMutex);
     IGraphicBufferProducer::QueueBufferOutput output;
     int err = mGraphicBufferProducer->connect(listener, api, mProducerControlledByApp, &output);
@@ -638,47 +654,38 @@
     return err;
 }
 
-int Surface::setBuffersDimensions(int w, int h)
+int Surface::setBuffersDimensions(uint32_t width, uint32_t height)
 {
     ATRACE_CALL();
     ALOGV("Surface::setBuffersDimensions");
 
-    if (w<0 || h<0)
-        return BAD_VALUE;
-
-    if ((w && !h) || (!w && h))
+    if ((width && !height) || (!width && height))
         return BAD_VALUE;
 
     Mutex::Autolock lock(mMutex);
-    mReqWidth = w;
-    mReqHeight = h;
+    mReqWidth = width;
+    mReqHeight = height;
     return NO_ERROR;
 }
 
-int Surface::setBuffersUserDimensions(int w, int h)
+int Surface::setBuffersUserDimensions(uint32_t width, uint32_t height)
 {
     ATRACE_CALL();
     ALOGV("Surface::setBuffersUserDimensions");
 
-    if (w<0 || h<0)
-        return BAD_VALUE;
-
-    if ((w && !h) || (!w && h))
+    if ((width && !height) || (!width && height))
         return BAD_VALUE;
 
     Mutex::Autolock lock(mMutex);
-    mUserWidth = w;
-    mUserHeight = h;
+    mUserWidth = width;
+    mUserHeight = height;
     return NO_ERROR;
 }
 
-int Surface::setBuffersFormat(int format)
+int Surface::setBuffersFormat(PixelFormat format)
 {
     ALOGV("Surface::setBuffersFormat");
 
-    if (format<0)
-        return BAD_VALUE;
-
     Mutex::Autolock lock(mMutex);
     mReqFormat = format;
     return NO_ERROR;
@@ -704,7 +711,7 @@
     return NO_ERROR;
 }
 
-int Surface::setBuffersTransform(int transform)
+int Surface::setBuffersTransform(uint32_t transform)
 {
     ATRACE_CALL();
     ALOGV("Surface::setBuffersTransform");
@@ -713,7 +720,7 @@
     return NO_ERROR;
 }
 
-int Surface::setBuffersStickyTransform(int transform)
+int Surface::setBuffersStickyTransform(uint32_t transform)
 {
     ATRACE_CALL();
     ALOGV("Surface::setBuffersStickyTransform");
@@ -730,6 +737,14 @@
     return NO_ERROR;
 }
 
+int Surface::setBuffersDataSpace(android_dataspace dataSpace)
+{
+    ALOGV("Surface::setBuffersDataSpace");
+    Mutex::Autolock lock(mMutex);
+    mDataSpace = dataSpace;
+    return NO_ERROR;
+}
+
 void Surface::freeAllBuffers() {
     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
         mSlots[i].buffer = 0;
@@ -747,30 +762,34 @@
     // src and dst with, height and format must be identical. no verification
     // is done here.
     status_t err;
-    uint8_t const * src_bits = NULL;
-    err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(), (void**)&src_bits);
+    uint8_t* src_bits = NULL;
+    err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(),
+            reinterpret_cast<void**>(&src_bits));
     ALOGE_IF(err, "error locking src buffer %s", strerror(-err));
 
     uint8_t* dst_bits = NULL;
-    err = dst->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(), (void**)&dst_bits);
+    err = dst->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(),
+            reinterpret_cast<void**>(&dst_bits));
     ALOGE_IF(err, "error locking dst buffer %s", strerror(-err));
 
     Region::const_iterator head(reg.begin());
     Region::const_iterator tail(reg.end());
     if (head != tail && src_bits && dst_bits) {
         const size_t bpp = bytesPerPixel(src->format);
-        const size_t dbpr = dst->stride * bpp;
-        const size_t sbpr = src->stride * bpp;
+        const size_t dbpr = static_cast<uint32_t>(dst->stride) * bpp;
+        const size_t sbpr = static_cast<uint32_t>(src->stride) * bpp;
 
         while (head != tail) {
             const Rect& r(*head++);
-            ssize_t h = r.height();
+            int32_t h = r.height();
             if (h <= 0) continue;
-            size_t size = r.width() * bpp;
-            uint8_t const * s = src_bits + (r.left + src->stride * r.top) * bpp;
-            uint8_t       * d = dst_bits + (r.left + dst->stride * r.top) * bpp;
+            size_t size = static_cast<uint32_t>(r.width()) * bpp;
+            uint8_t const * s = src_bits +
+                    static_cast<uint32_t>(r.left + src->stride * r.top) * bpp;
+            uint8_t       * d = dst_bits +
+                    static_cast<uint32_t>(r.left + dst->stride * r.top) * bpp;
             if (dbpr==sbpr && size==sbpr) {
-                size *= h;
+                size *= static_cast<size_t>(h);
                 h = 1;
             }
             do {
diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp
index 1be7895..707a321 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -143,7 +143,7 @@
     status_t setSize(const sp<SurfaceComposerClient>& client, const sp<IBinder>& id,
             uint32_t w, uint32_t h);
     status_t setLayer(const sp<SurfaceComposerClient>& client, const sp<IBinder>& id,
-            int32_t z);
+            uint32_t z);
     status_t setFlags(const sp<SurfaceComposerClient>& client, const sp<IBinder>& id,
             uint32_t flags, uint32_t mask);
     status_t setTransparentRegionHint(
@@ -293,7 +293,7 @@
 }
 
 status_t Composer::setLayer(const sp<SurfaceComposerClient>& client,
-        const sp<IBinder>& id, int32_t z) {
+        const sp<IBinder>& id, uint32_t z) {
     Mutex::Autolock _l(mLock);
     layer_state_t* s = getLayerStateLocked(client, id);
     if (!s)
@@ -395,7 +395,7 @@
         s.what = 0;
         index = mDisplayStates.add(s);
     }
-    return mDisplayStates.editItemAt(index);
+    return mDisplayStates.editItemAt(static_cast<size_t>(index));
 }
 
 void Composer::setDisplaySurface(const sp<IBinder>& token,
@@ -571,7 +571,7 @@
     return getComposer().setSize(this, id, w, h);
 }
 
-status_t SurfaceComposerClient::setLayer(const sp<IBinder>& id, int32_t z) {
+status_t SurfaceComposerClient::setLayer(const sp<IBinder>& id, uint32_t z) {
     return getComposer().setLayer(this, id, z);
 }
 
@@ -657,7 +657,7 @@
         return NAME_NOT_FOUND;
     }
 
-    *info = configs[activeId];
+    *info = configs[static_cast<size_t>(activeId)];
     return NO_ERROR;
 }
 
diff --git a/libs/gui/SurfaceControl.cpp b/libs/gui/SurfaceControl.cpp
index 61011b9..1983027 100644
--- a/libs/gui/SurfaceControl.cpp
+++ b/libs/gui/SurfaceControl.cpp
@@ -89,12 +89,12 @@
     return lhs->mHandle == rhs->mHandle;
 }
 
-status_t SurfaceControl::setLayerStack(int32_t layerStack) {
+status_t SurfaceControl::setLayerStack(uint32_t layerStack) {
     status_t err = validate();
     if (err < 0) return err;
     return mClient->setLayerStack(mHandle, layerStack);
 }
-status_t SurfaceControl::setLayer(int32_t layer) {
+status_t SurfaceControl::setLayer(uint32_t layer) {
     status_t err = validate();
     if (err < 0) return err;
     return mClient->setLayer(mHandle, layer);
diff --git a/libs/gui/SyncFeatures.cpp b/libs/gui/SyncFeatures.cpp
index e5804a7..187b211 100644
--- a/libs/gui/SyncFeatures.cpp
+++ b/libs/gui/SyncFeatures.cpp
@@ -16,7 +16,6 @@
 
 #define LOG_TAG "GLConsumer"
 
-#define GL_GLEXT_PROTOTYPES
 #define EGL_EGLEXT_PROTOTYPES
 
 #include <EGL/egl.h>
@@ -78,10 +77,11 @@
     // on some devices it's better to not use EGL_KHR_fence_sync
     // even if they have it
     return false;
-#endif
+#else
     // currently we shall only attempt to use EGL_KHR_fence_sync if
     // USE_FENCE_SYNC is set in our makefile
     return !mHasNativeFenceSync && mHasFenceSync;
+#endif
 }
 bool SyncFeatures::useWaitSync() const {
     return (useNativeFenceSync() || useFenceSync()) && mHasWaitSync;
diff --git a/libs/gui/tests/BufferQueue_test.cpp b/libs/gui/tests/BufferQueue_test.cpp
index 838ad90..80119de 100644
--- a/libs/gui/tests/BufferQueue_test.cpp
+++ b/libs/gui/tests/BufferQueue_test.cpp
@@ -124,7 +124,8 @@
     *dataIn = 0x12345678;
     ASSERT_EQ(OK, buffer->unlock());
 
-    IGraphicBufferProducer::QueueBufferInput input(0, false, Rect(0, 0, 1, 1),
+    IGraphicBufferProducer::QueueBufferInput input(0, false,
+            HAL_DATASPACE_UNKNOWN, Rect(0, 0, 1, 1),
             NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false, Fence::NO_FENCE);
     ASSERT_EQ(OK, mProducer->queueBuffer(slot, input, &output));
 
@@ -150,7 +151,8 @@
     int slot;
     sp<Fence> fence;
     sp<GraphicBuffer> buf;
-    IGraphicBufferProducer::QueueBufferInput qbi(0, false, Rect(0, 0, 1, 1),
+    IGraphicBufferProducer::QueueBufferInput qbi(0, false,
+            HAL_DATASPACE_UNKNOWN, Rect(0, 0, 1, 1),
             NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false, Fence::NO_FENCE);
     BufferQueue::BufferItem item;
 
@@ -244,7 +246,8 @@
     ASSERT_EQ(BAD_VALUE, mProducer->attachBuffer(&newSlot, NULL));
 
     ASSERT_EQ(OK, mProducer->attachBuffer(&newSlot, buffer));
-    IGraphicBufferProducer::QueueBufferInput input(0, false, Rect(0, 0, 1, 1),
+    IGraphicBufferProducer::QueueBufferInput input(0, false,
+            HAL_DATASPACE_UNKNOWN, Rect(0, 0, 1, 1),
             NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false, Fence::NO_FENCE);
     ASSERT_EQ(OK, mProducer->queueBuffer(newSlot, input, &output));
 
@@ -273,7 +276,8 @@
             mProducer->dequeueBuffer(&slot, &fence, false, 0, 0, 0,
                     GRALLOC_USAGE_SW_WRITE_OFTEN));
     ASSERT_EQ(OK, mProducer->requestBuffer(slot, &buffer));
-    IGraphicBufferProducer::QueueBufferInput input(0, false, Rect(0, 0, 1, 1),
+    IGraphicBufferProducer::QueueBufferInput input(0, false,
+            HAL_DATASPACE_UNKNOWN, Rect(0, 0, 1, 1),
             NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false, Fence::NO_FENCE);
     ASSERT_EQ(OK, mProducer->queueBuffer(slot, input, &output));
 
@@ -338,7 +342,8 @@
     *dataIn = 0x12345678;
     ASSERT_EQ(OK, buffer->unlock());
 
-    IGraphicBufferProducer::QueueBufferInput input(0, false, Rect(0, 0, 1, 1),
+    IGraphicBufferProducer::QueueBufferInput input(0, false,
+            HAL_DATASPACE_UNKNOWN, Rect(0, 0, 1, 1),
             NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false, Fence::NO_FENCE);
     ASSERT_EQ(OK, mProducer->queueBuffer(slot, input, &output));
 
diff --git a/libs/gui/tests/CpuConsumer_test.cpp b/libs/gui/tests/CpuConsumer_test.cpp
index abd3724..0beca92 100644
--- a/libs/gui/tests/CpuConsumer_test.cpp
+++ b/libs/gui/tests/CpuConsumer_test.cpp
@@ -166,7 +166,7 @@
         uint32_t x, uint32_t y, uint32_t r, uint32_t g=0, uint32_t b=0) {
     // Ignores components that don't exist for given pixel
     switch(buf.format) {
-        case HAL_PIXEL_FORMAT_RAW_SENSOR: {
+        case HAL_PIXEL_FORMAT_RAW16: {
             String8 msg;
             uint16_t *bPtr = (uint16_t*)buf.data;
             bPtr += y * buf.stride + x;
@@ -429,7 +429,7 @@
 
 void checkAnyBuffer(const CpuConsumer::LockedBuffer &buf, int format) {
     switch (format) {
-        case HAL_PIXEL_FORMAT_RAW_SENSOR:
+        case HAL_PIXEL_FORMAT_RAW16:
             checkBayerRawBuffer(buf);
             break;
         case HAL_PIXEL_FORMAT_Y8:
@@ -505,7 +505,7 @@
         case HAL_PIXEL_FORMAT_YV12:
             fillYV12Buffer(img, params.width, params.height, *stride);
             break;
-        case HAL_PIXEL_FORMAT_RAW_SENSOR:
+        case HAL_PIXEL_FORMAT_RAW16:
             fillBayerRawBuffer(img, params.width, params.height, buf->getStride());
             break;
         case HAL_PIXEL_FORMAT_Y8:
@@ -537,7 +537,7 @@
     ASSERT_NO_ERROR(err, "queueBuffer error:");
 };
 
-// This test is disabled because the HAL_PIXEL_FORMAT_RAW_SENSOR format is not
+// This test is disabled because the HAL_PIXEL_FORMAT_RAW16 format is not
 // supported on all devices.
 TEST_P(CpuConsumerTest, FromCpuSingle) {
     status_t err;
@@ -571,7 +571,7 @@
     mCC->unlockBuffer(b);
 }
 
-// This test is disabled because the HAL_PIXEL_FORMAT_RAW_SENSOR format is not
+// This test is disabled because the HAL_PIXEL_FORMAT_RAW16 format is not
 // supported on all devices.
 TEST_P(CpuConsumerTest, FromCpuManyInQueue) {
     status_t err;
@@ -614,7 +614,7 @@
     }
 }
 
-// This test is disabled because the HAL_PIXEL_FORMAT_RAW_SENSOR format is not
+// This test is disabled because the HAL_PIXEL_FORMAT_RAW16 format is not
 // supported on all devices.
 TEST_P(CpuConsumerTest, FromCpuLockMax) {
     status_t err;
@@ -710,12 +710,12 @@
 };
 
 CpuConsumerTestParams rawTestSets[] = {
-    { 512,   512, 1, HAL_PIXEL_FORMAT_RAW_SENSOR},
-    { 512,   512, 3, HAL_PIXEL_FORMAT_RAW_SENSOR},
-    { 2608, 1960, 1, HAL_PIXEL_FORMAT_RAW_SENSOR},
-    { 2608, 1960, 3, HAL_PIXEL_FORMAT_RAW_SENSOR},
-    { 100,   100, 1, HAL_PIXEL_FORMAT_RAW_SENSOR},
-    { 100,   100, 3, HAL_PIXEL_FORMAT_RAW_SENSOR},
+    { 512,   512, 1, HAL_PIXEL_FORMAT_RAW16},
+    { 512,   512, 3, HAL_PIXEL_FORMAT_RAW16},
+    { 2608, 1960, 1, HAL_PIXEL_FORMAT_RAW16},
+    { 2608, 1960, 3, HAL_PIXEL_FORMAT_RAW16},
+    { 100,   100, 1, HAL_PIXEL_FORMAT_RAW16},
+    { 100,   100, 3, HAL_PIXEL_FORMAT_RAW16},
 };
 
 CpuConsumerTestParams rgba8888TestSets[] = {
diff --git a/libs/gui/tests/IGraphicBufferProducer_test.cpp b/libs/gui/tests/IGraphicBufferProducer_test.cpp
index 8d5fd8f..c904a6b 100644
--- a/libs/gui/tests/IGraphicBufferProducer_test.cpp
+++ b/libs/gui/tests/IGraphicBufferProducer_test.cpp
@@ -57,6 +57,7 @@
 // Parameters for a generic "valid" input for queueBuffer.
 const int64_t QUEUE_BUFFER_INPUT_TIMESTAMP = 1384888611;
 const bool QUEUE_BUFFER_INPUT_IS_AUTO_TIMESTAMP = false;
+const android_dataspace QUEUE_BUFFER_INPUT_DATASPACE = HAL_DATASPACE_UNKNOWN;
 const Rect QUEUE_BUFFER_INPUT_RECT = Rect(DEFAULT_WIDTH, DEFAULT_HEIGHT);
 const int QUEUE_BUFFER_INPUT_SCALING_MODE = 0;
 const int QUEUE_BUFFER_INPUT_TRANSFORM = 0;
@@ -126,6 +127,7 @@
         QueueBufferInputBuilder() {
            timestamp = QUEUE_BUFFER_INPUT_TIMESTAMP;
            isAutoTimestamp = QUEUE_BUFFER_INPUT_IS_AUTO_TIMESTAMP;
+           dataSpace = QUEUE_BUFFER_INPUT_DATASPACE;
            crop = QUEUE_BUFFER_INPUT_RECT;
            scalingMode = QUEUE_BUFFER_INPUT_SCALING_MODE;
            transform = QUEUE_BUFFER_INPUT_TRANSFORM;
@@ -137,6 +139,7 @@
             return IGraphicBufferProducer::QueueBufferInput(
                     timestamp,
                     isAutoTimestamp,
+                    dataSpace,
                     crop,
                     scalingMode,
                     transform,
@@ -154,6 +157,11 @@
             return *this;
         }
 
+        QueueBufferInputBuilder& setDataSpace(android_dataspace dataSpace) {
+            this->dataSpace = dataSpace;
+            return *this;
+        }
+
         QueueBufferInputBuilder& setCrop(Rect crop) {
             this->crop = crop;
             return *this;
@@ -182,6 +190,7 @@
     private:
         int64_t timestamp;
         bool isAutoTimestamp;
+        android_dataspace dataSpace;
         Rect crop;
         int scalingMode;
         uint32_t transform;
diff --git a/libs/gui/tests/SRGB_test.cpp b/libs/gui/tests/SRGB_test.cpp
index da2add7..e5907e7 100644
--- a/libs/gui/tests/SRGB_test.cpp
+++ b/libs/gui/tests/SRGB_test.cpp
@@ -214,10 +214,11 @@
         ASSERT_EQ(GL_NO_ERROR, glGetError());
     }
 
-    void checkLockedBuffer(PixelFormat format) {
+    void checkLockedBuffer(PixelFormat format, android_dataspace dataSpace) {
         ASSERT_EQ(mLockedBuffer.format, format);
         ASSERT_EQ(mLockedBuffer.width, DISPLAY_WIDTH);
         ASSERT_EQ(mLockedBuffer.height, DISPLAY_HEIGHT);
+        ASSERT_EQ(mLockedBuffer.dataSpace, dataSpace);
     }
 
     static bool withinTolerance(int a, int b) {
@@ -335,7 +336,8 @@
         if (mLockedBuffer.format == outBuffer.format) {
             memcpy(outBuffer.bits, mLockedBuffer.data, bufferSize);
         } else {
-            ASSERT_EQ(mLockedBuffer.format, PIXEL_FORMAT_sRGB_A_8888);
+            ASSERT_EQ(mLockedBuffer.format, PIXEL_FORMAT_RGBA_8888);
+            ASSERT_EQ(mLockedBuffer.dataSpace, HAL_DATASPACE_SRGB);
             ASSERT_EQ(outBuffer.format, PIXEL_FORMAT_RGBA_8888);
             uint8_t* outPointer = reinterpret_cast<uint8_t*>(outBuffer.bits);
             for (int y = 0; y < outBuffer.height; ++y) {
@@ -380,7 +382,8 @@
 
     // Lock
     ASSERT_EQ(NO_ERROR, mCpuConsumer->lockNextBuffer(&mLockedBuffer));
-    ASSERT_NO_FATAL_FAILURE(checkLockedBuffer(PIXEL_FORMAT_RGBA_8888));
+    ASSERT_NO_FATAL_FAILURE(
+        checkLockedBuffer(PIXEL_FORMAT_RGBA_8888, HAL_DATASPACE_UNKNOWN));
 
     // Compare a pixel in the middle of each texture
     int midSRGBOffset = (DISPLAY_HEIGHT / 4) * mLockedBuffer.stride *
@@ -411,7 +414,8 @@
 
     // Lock
     ASSERT_EQ(NO_ERROR, mCpuConsumer->lockNextBuffer(&mLockedBuffer));
-    ASSERT_NO_FATAL_FAILURE(checkLockedBuffer(PIXEL_FORMAT_RGBA_8888));
+    ASSERT_NO_FATAL_FAILURE(
+        checkLockedBuffer(PIXEL_FORMAT_RGBA_8888, HAL_DATASPACE_UNKNOWN));
 
     // Save the values of the middle pixel for later comparison against SRGB
     uint8_t values[PIXEL_SIZE] = {};
@@ -460,7 +464,8 @@
     ASSERT_EQ(NO_ERROR, mCpuConsumer->lockNextBuffer(&mLockedBuffer));
 
     // Make sure we actually got the SRGB buffer on the consumer side
-    ASSERT_NO_FATAL_FAILURE(checkLockedBuffer(PIXEL_FORMAT_sRGB_A_8888));
+    ASSERT_NO_FATAL_FAILURE(
+        checkLockedBuffer(PIXEL_FORMAT_RGBA_8888, HAL_DATASPACE_SRGB));
 
     // Verify that the stored value is the same, accounting for RGB/SRGB
     for (int c = 0; c < PIXEL_SIZE; ++c) {
diff --git a/libs/gui/tests/StreamSplitter_test.cpp b/libs/gui/tests/StreamSplitter_test.cpp
index 4e63a6f..429ab6c 100644
--- a/libs/gui/tests/StreamSplitter_test.cpp
+++ b/libs/gui/tests/StreamSplitter_test.cpp
@@ -111,6 +111,7 @@
     ASSERT_EQ(OK, buffer->unlock());
 
     IGraphicBufferProducer::QueueBufferInput qbInput(0, false,
+            HAL_DATASPACE_UNKNOWN,
             Rect(0, 0, 1, 1), NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false,
             Fence::NO_FENCE);
     ASSERT_EQ(OK, inputProducer->queueBuffer(slot, qbInput, &qbOutput));
@@ -177,6 +178,7 @@
     ASSERT_EQ(OK, buffer->unlock());
 
     IGraphicBufferProducer::QueueBufferInput qbInput(0, false,
+            HAL_DATASPACE_UNKNOWN,
             Rect(0, 0, 1, 1), NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false,
             Fence::NO_FENCE);
     ASSERT_EQ(OK, inputProducer->queueBuffer(slot, qbInput, &qbOutput));
@@ -234,6 +236,7 @@
     outputConsumer->consumerDisconnect();
 
     IGraphicBufferProducer::QueueBufferInput qbInput(0, false,
+            HAL_DATASPACE_UNKNOWN,
             Rect(0, 0, 1, 1), NATIVE_WINDOW_SCALING_MODE_FREEZE, 0, false,
             Fence::NO_FENCE);
     ASSERT_EQ(OK, inputProducer->queueBuffer(slot, qbInput, &qbOutput));
diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp
index 5e6aeef..4f87824 100644
--- a/libs/gui/tests/Surface_test.cpp
+++ b/libs/gui/tests/Surface_test.cpp
@@ -155,4 +155,26 @@
     ASSERT_EQ(TEST_USAGE_FLAGS, flags);
 }
 
+TEST_F(SurfaceTest, QueryDefaultBuffersDataSpace) {
+    const android_dataspace TEST_DATASPACE = HAL_DATASPACE_SRGB;
+    sp<IGraphicBufferProducer> producer;
+    sp<IGraphicBufferConsumer> consumer;
+    BufferQueue::createBufferQueue(&producer, &consumer);
+    sp<CpuConsumer> cpuConsumer = new CpuConsumer(consumer, 1);
+
+    cpuConsumer->setDefaultBufferDataSpace(TEST_DATASPACE);
+
+    sp<Surface> s = new Surface(producer);
+
+    sp<ANativeWindow> anw(s);
+
+    android_dataspace dataSpace;
+
+    int err = anw->query(anw.get(), NATIVE_WINDOW_DEFAULT_DATASPACE,
+            reinterpret_cast<int*>(&dataSpace));
+
+    ASSERT_EQ(NO_ERROR, err);
+    ASSERT_EQ(TEST_DATASPACE, dataSpace);
+}
+
 }
diff --git a/libs/input/Android.mk b/libs/input/Android.mk
index f1921a4..944ac7f 100644
--- a/libs/input/Android.mk
+++ b/libs/input/Android.mk
@@ -27,6 +27,7 @@
 
 deviceSources := \
     $(commonSources) \
+    IInputFlinger.cpp \
     InputTransport.cpp \
     VelocityControl.cpp \
     VelocityTracker.cpp
diff --git a/libs/input/IInputFlinger.cpp b/libs/input/IInputFlinger.cpp
new file mode 100644
index 0000000..e009731
--- /dev/null
+++ b/libs/input/IInputFlinger.cpp
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <binder/Parcel.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+
+#include <input/IInputFlinger.h>
+
+
+namespace android {
+
+class BpInputFlinger : public BpInterface<IInputFlinger> {
+public:
+    BpInputFlinger(const sp<IBinder>& impl) :
+            BpInterface<IInputFlinger>(impl) { }
+
+    virtual status_t doSomething() {
+        Parcel data, reply;
+        data.writeInterfaceToken(IInputFlinger::getInterfaceDescriptor());
+        remote()->transact(BnInputFlinger::DO_SOMETHING_TRANSACTION, data, &reply);
+        return reply.readInt32();
+    }
+};
+
+IMPLEMENT_META_INTERFACE(InputFlinger, "android.input.IInputFlinger");
+
+
+status_t BnInputFlinger::onTransact(
+        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
+    switch(code) {
+    case DO_SOMETHING_TRANSACTION: {
+        CHECK_INTERFACE(IInputFlinger, data, reply);
+        reply->writeInt32(0);
+        break;
+    }
+    default:
+        return BBinder::onTransact(code, data, reply, flags);
+    }
+    return NO_ERROR;
+}
+
+};
diff --git a/libs/ui/PixelFormat.cpp b/libs/ui/PixelFormat.cpp
index 99ed6f7..cab1dde 100644
--- a/libs/ui/PixelFormat.cpp
+++ b/libs/ui/PixelFormat.cpp
@@ -25,8 +25,6 @@
         case PIXEL_FORMAT_RGBA_8888:
         case PIXEL_FORMAT_RGBX_8888:
         case PIXEL_FORMAT_BGRA_8888:
-        case PIXEL_FORMAT_sRGB_A_8888:
-        case PIXEL_FORMAT_sRGB_X_8888:
             return 4;
         case PIXEL_FORMAT_RGB_888:
             return 3;
@@ -57,4 +55,3 @@
 // ----------------------------------------------------------------------------
 }; // namespace android
 // ----------------------------------------------------------------------------
-
diff --git a/opengl/libs/EGL/eglApi.cpp b/opengl/libs/EGL/eglApi.cpp
index ff08a6b..11a13c3 100644
--- a/opengl/libs/EGL/eglApi.cpp
+++ b/opengl/libs/EGL/eglApi.cpp
@@ -381,20 +381,15 @@
 // Turn linear formats into corresponding sRGB formats when colorspace is
 // EGL_GL_COLORSPACE_SRGB_KHR, or turn sRGB formats into corresponding linear
 // formats when colorspace is EGL_GL_COLORSPACE_LINEAR_KHR. In any cases where
-// the modification isn't possible, the original format is returned.
-static int modifyFormatColorspace(int fmt, EGLint colorspace) {
+// the modification isn't possible, the original dataSpace is returned.
+static android_dataspace modifyBufferDataspace( android_dataspace dataSpace,
+                                                EGLint colorspace) {
     if (colorspace == EGL_GL_COLORSPACE_LINEAR_KHR) {
-        switch (fmt) {
-            case HAL_PIXEL_FORMAT_sRGB_A_8888: return HAL_PIXEL_FORMAT_RGBA_8888;
-            case HAL_PIXEL_FORMAT_sRGB_X_8888: return HAL_PIXEL_FORMAT_RGBX_8888;
-        }
+        return HAL_DATASPACE_SRGB_LINEAR;
     } else if (colorspace == EGL_GL_COLORSPACE_SRGB_KHR) {
-        switch (fmt) {
-            case HAL_PIXEL_FORMAT_RGBA_8888: return HAL_PIXEL_FORMAT_sRGB_A_8888;
-            case HAL_PIXEL_FORMAT_RGBX_8888: return HAL_PIXEL_FORMAT_sRGB_X_8888;
-        }
+        return HAL_DATASPACE_SRGB;
     }
-    return fmt;
+    return dataSpace;
 }
 
 EGLSurface eglCreateWindowSurface(  EGLDisplay dpy, EGLConfig config,
@@ -424,6 +419,7 @@
 
         // by default, just pick RGBA_8888
         EGLint format = HAL_PIXEL_FORMAT_RGBA_8888;
+        android_dataspace dataSpace = HAL_DATASPACE_UNKNOWN;
 
         EGLint a = 0;
         cnx->egl.eglGetConfigAttrib(iDpy, config, EGL_ALPHA_SIZE, &a);
@@ -449,7 +445,7 @@
             for (const EGLint* attr = attrib_list; *attr != EGL_NONE; attr += 2) {
                 if (*attr == EGL_GL_COLORSPACE_KHR) {
                     if (ENABLE_EGL_KHR_GL_COLORSPACE) {
-                        format = modifyFormatColorspace(format, *(attr+1));
+                        dataSpace = modifyBufferDataspace(dataSpace, *(attr+1));
                     } else {
                         // Normally we'd pass through unhandled attributes to
                         // the driver. But in case the driver implements this
@@ -473,6 +469,16 @@
             }
         }
 
+        if (dataSpace != 0) {
+            int err = native_window_set_buffers_data_space(window, dataSpace);
+            if (err != 0) {
+                ALOGE("error setting native window pixel dataSpace: %s (%d)",
+                        strerror(-err), err);
+                native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
+                return setError(EGL_BAD_NATIVE_WINDOW, EGL_NO_SURFACE);
+            }
+        }
+
         // the EGL spec requires that a new EGLSurface default to swap interval
         // 1, so explicitly set that on the window here.
         ANativeWindow* anw = reinterpret_cast<ANativeWindow*>(window);
diff --git a/services/inputflinger/Android.mk b/services/inputflinger/Android.mk
index 1af59a3..ed867d8 100644
--- a/services/inputflinger/Android.mk
+++ b/services/inputflinger/Android.mk
@@ -45,3 +45,5 @@
 LOCAL_MODULE := libinputflinger
 
 include $(BUILD_SHARED_LIBRARY)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/services/inputflinger/host/Android.mk b/services/inputflinger/host/Android.mk
new file mode 100644
index 0000000..b828175
--- /dev/null
+++ b/services/inputflinger/host/Android.mk
@@ -0,0 +1,62 @@
+# Copyright (C) 2015 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_CLANG := true
+
+LOCAL_SRC_FILES:= \
+    InputFlinger.cpp \
+    InputDriver.cpp \
+    InputHost.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+    libbinder \
+    libcrypto \
+    libcutils \
+    libinput \
+    liblog \
+    libutils \
+    libhardware
+
+
+# TODO: Move inputflinger to its own process and mark it hidden
+#LOCAL_CFLAGS += -fvisibility=hidden
+
+LOCAL_CFLAGS += -Wno-unused-parameter
+
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)
+
+LOCAL_MODULE := libinputflingerhost
+
+include $(BUILD_SHARED_LIBRARY)
+
+########################################################################
+# build input flinger executable
+include $(CLEAR_VARS)
+
+LOCAL_CLANG := true
+
+LOCAL_SRC_FILES:= \
+	main.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+	libbinder \
+	libinputflingerhost \
+	libutils
+
+LOCAL_MODULE := inputflinger
+
+include $(BUILD_EXECUTABLE)
diff --git a/services/inputflinger/host/InputDriver.cpp b/services/inputflinger/host/InputDriver.cpp
new file mode 100644
index 0000000..ce84a6a
--- /dev/null
+++ b/services/inputflinger/host/InputDriver.cpp
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2015 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 <stdint.h>
+#include <sys/types.h>
+
+#define LOG_TAG "InputDriver"
+
+#define LOG_NDEBUG 0
+
+#include "InputDriver.h"
+#include "InputHost.h"
+
+#include <hardware/input.h>
+#include <utils/Log.h>
+#include <utils/String8.h>
+
+#define INDENT2 "    "
+
+namespace android {
+
+static input_host_callbacks_t kCallbacks = {
+    .create_device_identifier = create_device_identifier,
+    .create_device_definition = create_device_definition,
+    .create_input_report_definition = create_input_report_definition,
+    .create_output_report_definition = create_output_report_definition,
+    .input_device_definition_add_report = input_device_definition_add_report,
+    .input_report_definition_add_collection = input_report_definition_add_collection,
+    .input_report_definition_declare_usage_int = input_report_definition_declare_usage_int,
+    .input_report_definition_declare_usages_bool = input_report_definition_declare_usages_bool,
+    .register_device = register_device,
+    .input_allocate_report = input_allocate_report,
+    .report_event = report_event,
+};
+
+InputDriver::InputDriver(const char* name) : mName(String8(name)) {
+    const hw_module_t* module;
+    int err = input_open(&module, name);
+    LOG_ALWAYS_FATAL_IF(err != 0, "Input module %s not found", name);
+    mHal = reinterpret_cast<const input_module_t*>(module);
+}
+
+void InputDriver::init(InputHostInterface* host) {
+    mHal->init(mHal, static_cast<input_host_t*>(host), kCallbacks);
+}
+
+void InputDriver::dump(String8& result) {
+    result.appendFormat(INDENT2 "HAL Input Driver (%s)\n", mName.string());
+}
+
+
+// HAL wrapper functions
+
+input_device_identifier_t* create_device_identifier(input_host_t* host,
+        const char* name, int32_t product_id, int32_t vendor_id,
+        input_bus_t bus, const char* unique_id) {
+    return nullptr;
+}
+
+input_device_definition_t* create_device_definition(input_host_t* host) {
+    return nullptr;
+}
+
+input_report_definition_t* create_input_report_definition(input_host_t* host) {
+    return nullptr;
+}
+
+input_report_definition_t* create_output_report_definition(input_host_t* host) {
+    return nullptr;
+}
+
+void input_device_definition_add_report(input_host_t* host,
+        input_device_definition_t* d, input_report_definition_t* r) { }
+
+void input_report_definition_add_collection(input_host_t* host,
+        input_report_definition_t* report, input_collection_id_t id, int32_t arity) { }
+
+void input_report_definition_declare_usage_int(input_host_t* host,
+        input_report_definition_t* report, input_collection_id_t id,
+        input_usage_t usage, int32_t min, int32_t max, float resolution) { }
+
+void input_report_definition_declare_usages_bool(input_host_t* host,
+        input_report_definition_t* report, input_collection_id_t id,
+        input_usage_t* usage, size_t usage_count) { }
+
+
+input_device_handle_t* register_device(input_host_t* host,
+        input_device_identifier_t* id, input_device_definition_t* d) {
+    return nullptr;
+}
+
+input_report_t* input_allocate_report(input_host_t* host, input_report_definition_t* r) {
+    return nullptr;
+}
+
+void report_event(input_host_t* host, input_device_handle_t* d, input_report_t* report) { }
+
+
+} // namespace android
diff --git a/services/inputflinger/host/InputDriver.h b/services/inputflinger/host/InputDriver.h
new file mode 100644
index 0000000..c2268e2
--- /dev/null
+++ b/services/inputflinger/host/InputDriver.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2015 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_INPUT_DRIVER_H
+#define ANDROID_INPUT_DRIVER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include "InputHost.h"
+
+#include <hardware/input.h>
+#include <utils/RefBase.h>
+#include <utils/String8.h>
+
+namespace android {
+
+class InputHostInterface;
+
+class InputDriverInterface : public virtual RefBase {
+protected:
+    InputDriverInterface() = default;
+    virtual ~InputDriverInterface() = default;
+
+public:
+    virtual void init(InputHostInterface* host) = 0;
+
+    virtual void dump(String8& result) = 0;
+};
+
+class InputDriver : public InputDriverInterface {
+public:
+    InputDriver(const char* name);
+    virtual ~InputDriver() = default;
+
+    virtual void init(InputHostInterface* host) override;
+
+    virtual void dump(String8& result) override;
+
+private:
+    String8 mName;
+    const input_module_t* mHal;
+};
+
+
+extern "C" {
+
+input_device_identifier_t* create_device_identifier(input_host_t* host,
+        const char* name, int32_t product_id, int32_t vendor_id,
+        input_bus_t bus, const char* unique_id);
+
+input_device_definition_t* create_device_definition(input_host_t* host);
+
+input_report_definition_t* create_input_report_definition(input_host_t* host);
+
+input_report_definition_t* create_output_report_definition(input_host_t* host);
+
+void input_device_definition_add_report(input_host_t* host,
+        input_device_definition_t* d, input_report_definition_t* r);
+
+void input_report_definition_add_collection(input_host_t* host,
+        input_report_definition_t* report, input_collection_id_t id, int32_t arity);
+
+void input_report_definition_declare_usage_int(input_host_t* host,
+        input_report_definition_t* report, input_collection_id_t id,
+        input_usage_t usage, int32_t min, int32_t max, float resolution);
+
+void input_report_definition_declare_usages_bool(input_host_t* host,
+        input_report_definition_t* report, input_collection_id_t id,
+        input_usage_t* usage, size_t usage_count);
+
+
+input_device_handle_t* register_device(input_host_t* host,
+        input_device_identifier_t* id, input_device_definition_t* d);
+
+void unregister_device(input_host_t* host, input_device_handle_t* handle);
+
+input_report_t* input_allocate_report(input_host_t* host, input_report_definition_t* r);
+
+void report_event(input_host_t* host, input_device_handle_t* d, input_report_t* report);
+
+}
+
+} // namespace android
+#endif // ANDROID_INPUT_DRIVER_H
diff --git a/services/inputflinger/host/InputFlinger.cpp b/services/inputflinger/host/InputFlinger.cpp
new file mode 100644
index 0000000..859c3b8
--- /dev/null
+++ b/services/inputflinger/host/InputFlinger.cpp
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define LOG_TAG "InputFlinger"
+
+
+#include <stdint.h>
+#include <unistd.h>
+
+#include <sys/types.h>
+
+#include "InputFlinger.h"
+#include "InputDriver.h"
+
+#include <binder/IPCThreadState.h>
+#include <binder/PermissionCache.h>
+#include <hardware/input.h>
+#include <cutils/log.h>
+#include <private/android_filesystem_config.h>
+
+namespace android {
+
+const String16 sAccessInputFlingerPermission("android.permission.ACCESS_INPUT_FLINGER");
+const String16 sDumpPermission("android.permission.DUMP");
+
+
+InputFlinger::InputFlinger() :
+        BnInputFlinger() {
+    ALOGI("InputFlinger is starting");
+    mHost = new InputHost();
+    mHost->registerInputDriver(new InputDriver(INPUT_INSTANCE_EVDEV));
+}
+
+InputFlinger::~InputFlinger() {
+}
+
+status_t InputFlinger::dump(int fd, const Vector<String16>& args) {
+    String8 result;
+    const IPCThreadState* ipc = IPCThreadState::self();
+    const int pid = ipc->getCallingPid();
+    const int uid = ipc->getCallingUid();
+    if ((uid != AID_SHELL)
+            && !PermissionCache::checkPermission(sDumpPermission, pid, uid)) {
+        result.appendFormat("Permission Denial: "
+                "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
+    } else {
+        dumpInternal(result);
+    }
+    write(fd, result.string(), result.size());
+    return OK;
+}
+
+void InputFlinger::dumpInternal(String8& result) {
+    result.append("INPUT FLINGER (dumpsys inputflinger)\n");
+    mHost->dump(result);
+}
+
+}; // namespace android
diff --git a/services/inputflinger/host/InputFlinger.h b/services/inputflinger/host/InputFlinger.h
new file mode 100644
index 0000000..39e69e5
--- /dev/null
+++ b/services/inputflinger/host/InputFlinger.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_INPUT_FLINGER_H
+#define ANDROID_INPUT_FLINGER_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include "InputHost.h"
+
+#include <cutils/compiler.h>
+#include <input/IInputFlinger.h>
+#include <utils/String8.h>
+#include <utils/String16.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+
+class InputFlinger : public BnInputFlinger {
+public:
+    static char const* getServiceName() ANDROID_API {
+        return "inputflinger";
+    }
+
+    InputFlinger() ANDROID_API;
+
+    virtual status_t dump(int fd, const Vector<String16>& args);
+
+private:
+    virtual ~InputFlinger();
+
+    void dumpInternal(String8& result);
+
+    sp<InputHostInterface> mHost;
+};
+
+} // namespace android
+
+#endif // ANDROID_INPUT_FLINGER_H
diff --git a/services/inputflinger/host/InputHost.cpp b/services/inputflinger/host/InputHost.cpp
new file mode 100644
index 0000000..51d3e6b
--- /dev/null
+++ b/services/inputflinger/host/InputHost.cpp
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2015 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 <vector>
+
+#include "InputDriver.h"
+#include "InputHost.h"
+
+#include <utils/Log.h>
+#include <utils/String8.h>
+
+#define INDENT "  "
+
+namespace android {
+
+void InputHost::registerInputDriver(InputDriverInterface* driver) {
+    LOG_ALWAYS_FATAL_IF(driver == nullptr, "Cannot register a nullptr as an InputDriver!");
+    driver->init(this);
+    mDrivers.push_back(driver);
+}
+
+void InputHost::dump(String8& result) {
+    result.append(INDENT "Input Drivers:\n");
+    for (size_t i = 0; i < mDrivers.size(); i++) {
+        mDrivers[i]->dump(result);
+    }
+}
+
+} // namespace android
diff --git a/services/inputflinger/host/InputHost.h b/services/inputflinger/host/InputHost.h
new file mode 100644
index 0000000..42a66e0
--- /dev/null
+++ b/services/inputflinger/host/InputHost.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2015 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_INPUT_HOST_H
+#define ANDROID_INPUT_HOST_H
+
+#include <vector>
+
+#include <hardware/input.h>
+#include <utils/RefBase.h>
+#include <utils/String8.h>
+#include <utils/StrongPointer.h>
+
+#include "InputDriver.h"
+
+// Declare a concrete type for the HAL
+struct input_host {
+};
+
+namespace android {
+
+class InputDriverInterface;
+
+class InputHostInterface : public input_host_t, public virtual RefBase {
+protected:
+    InputHostInterface() = default;
+    virtual ~InputHostInterface() = default;
+
+public:
+
+    virtual void registerInputDriver(InputDriverInterface* driver) = 0;
+
+    virtual void dump(String8& result) = 0;
+};
+
+class InputHost : public InputHostInterface {
+public:
+    InputHost() = default;
+
+    virtual void registerInputDriver(InputDriverInterface* driver) override;
+
+    virtual void dump(String8& result) override;
+
+private:
+    std::vector<sp<InputDriverInterface>> mDrivers;
+};
+
+} // namespace android
+#endif // ANDRIOD_INPUT_HOST_H
diff --git a/services/inputflinger/host/main.cpp b/services/inputflinger/host/main.cpp
new file mode 100644
index 0000000..0a517cc
--- /dev/null
+++ b/services/inputflinger/host/main.cpp
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <binder/BinderService.h>
+#include "InputFlinger.h"
+
+using namespace android;
+
+int main(int, char**) {
+    ProcessState::self()->setThreadPoolMaxThreadCount(4);
+    BinderService<InputFlinger>::publishAndJoinThreadPool(true);
+    return 0;
+}
diff --git a/services/inputflinger/tests/Android.mk b/services/inputflinger/tests/Android.mk
index 0742a08..4c43392 100644
--- a/services/inputflinger/tests/Android.mk
+++ b/services/inputflinger/tests/Android.mk
@@ -10,7 +10,6 @@
 shared_libraries := \
     libcutils \
     liblog \
-    libandroidfw \
     libutils \
     libhardware \
     libhardware_legacy \
@@ -24,7 +23,7 @@
     external/skia/include/core
 
 
-module_tags := eng tests
+module_tags := tests
 
 $(foreach file,$(test_src_files), \
     $(eval include $(CLEAR_VARS)) \
diff --git a/services/surfaceflinger/DdmConnection.cpp b/services/surfaceflinger/DdmConnection.cpp
index a000a84..659c2c8 100644
--- a/services/surfaceflinger/DdmConnection.cpp
+++ b/services/surfaceflinger/DdmConnection.cpp
@@ -66,7 +66,7 @@
     jint (*registerNatives)(JNIEnv* env, jclass clazz);
     registerNatives = reinterpret_cast<decltype(registerNatives)>(
             dlsym(libandroid_runtime_dso,
-                  "Java_com_android_internal_util_WithFramework_registerNatives"));
+                "Java_com_android_internal_util_WithFramework_registerNatives"));
     ALOGE_IF(!registerNatives, "DdmConnection: %s", dlerror());
 
     if (!JNI_CreateJavaVM || !registerNatives) {
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.cpp b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
index edfed49..77a9a19 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
@@ -1105,8 +1105,6 @@
     case PIXEL_FORMAT_RGB_888:      return String8("RGB_888");
     case PIXEL_FORMAT_RGB_565:      return String8("RGB_565");
     case PIXEL_FORMAT_BGRA_8888:    return String8("BGRA_8888");
-    case PIXEL_FORMAT_sRGB_A_8888:  return String8("sRGB_A_8888");
-    case PIXEL_FORMAT_sRGB_X_8888:  return String8("sRGB_x_8888");
     case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
                                     return String8("ImplDef");
     default:
diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
index e0f32e9..aefa8fd 100644
--- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
+++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
@@ -234,6 +234,7 @@
             status_t result = mSource[SOURCE_SINK]->queueBuffer(sslot,
                     QueueBufferInput(
                         systemTime(), false /* isAutoTimestamp */,
+                        HAL_DATASPACE_UNKNOWN,
                         Rect(mSinkBufferWidth, mSinkBufferHeight),
                         NATIVE_WINDOW_SCALING_MODE_FREEZE, 0 /* transform */,
                         true /* async*/,
@@ -284,7 +285,7 @@
 }
 
 status_t VirtualDisplaySurface::dequeueBuffer(Source source,
-        uint32_t format, uint32_t usage, int* sslot, sp<Fence>* fence) {
+        PixelFormat format, uint32_t usage, int* sslot, sp<Fence>* fence) {
     LOG_FATAL_IF(mDisplayId < 0, "mDisplayId=%d but should not be < 0.", mDisplayId);
     // Don't let a slow consumer block us
     bool async = (source == SOURCE_SINK);
@@ -329,7 +330,7 @@
 }
 
 status_t VirtualDisplaySurface::dequeueBuffer(int* pslot, sp<Fence>* fence, bool async,
-        uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
+        uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) {
     if (mDisplayId < 0)
         return mSource[SOURCE_SINK]->dequeueBuffer(pslot, fence, async, w, h, format, usage);
 
@@ -364,7 +365,7 @@
         usage |= GRALLOC_USAGE_HW_COMPOSER;
         const sp<GraphicBuffer>& buf = mProducerBuffers[mOutputProducerSlot];
         if ((usage & ~buf->getUsage()) != 0 ||
-                (format != 0 && format != (uint32_t)buf->getPixelFormat()) ||
+                (format != 0 && format != buf->getPixelFormat()) ||
                 (w != 0 && w != mSinkBufferWidth) ||
                 (h != 0 && h != mSinkBufferHeight)) {
             VDS_LOGV("dequeueBuffer: dequeueing new output buffer: "
@@ -453,12 +454,13 @@
         // Extract the GLES release fence for HWC to acquire
         int64_t timestamp;
         bool isAutoTimestamp;
+        android_dataspace dataSpace;
         Rect crop;
         int scalingMode;
         uint32_t transform;
         bool async;
-        input.deflate(&timestamp, &isAutoTimestamp, &crop, &scalingMode,
-                &transform, &async, &mFbFence);
+        input.deflate(&timestamp, &isAutoTimestamp, &dataSpace, &crop,
+                &scalingMode, &transform, &async, &mFbFence);
 
         mFbProducerSlot = pslot;
         mOutputFence = mFbFence;
@@ -517,7 +519,7 @@
 }
 
 void VirtualDisplaySurface::allocateBuffers(bool /* async */,
-        uint32_t /* width */, uint32_t /* height */, uint32_t /* format */,
+        uint32_t /* width */, uint32_t /* height */, PixelFormat /* format */,
         uint32_t /* usage */) {
     // TODO: Should we actually allocate buffers for a virtual display?
 }
diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
index 2c14d6d..0a3f4a1 100644
--- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
+++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
@@ -100,7 +100,7 @@
     virtual status_t requestBuffer(int pslot, sp<GraphicBuffer>* outBuf);
     virtual status_t setBufferCount(int bufferCount);
     virtual status_t dequeueBuffer(int* pslot, sp<Fence>* fence, bool async,
-            uint32_t w, uint32_t h, uint32_t format, uint32_t usage);
+            uint32_t w, uint32_t h, PixelFormat format, uint32_t usage);
     virtual status_t detachBuffer(int slot);
     virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
             sp<Fence>* outFence);
@@ -114,13 +114,13 @@
     virtual status_t disconnect(int api);
     virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage);
+            PixelFormat format, uint32_t usage);
 
     //
     // Utility methods
     //
     static Source fbSourceForCompositionType(CompositionType type);
-    status_t dequeueBuffer(Source source, uint32_t format, uint32_t usage,
+    status_t dequeueBuffer(Source source, PixelFormat format, uint32_t usage,
             int* sslot, sp<Fence>* fence);
     void updateQueueBufferOutput(const QueueBufferOutput& qbo);
     void resetPerFrameState();
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 9da1efd..cf27945 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -764,7 +764,6 @@
     switch (format) {
         case HAL_PIXEL_FORMAT_RGBA_8888:
         case HAL_PIXEL_FORMAT_BGRA_8888:
-        case HAL_PIXEL_FORMAT_sRGB_A_8888:
             return false;
     }
     // in all other case, we have no blending (also for unknown formats)
diff --git a/services/surfaceflinger/MonitoredProducer.cpp b/services/surfaceflinger/MonitoredProducer.cpp
index 37a044e..e4e7d42 100644
--- a/services/surfaceflinger/MonitoredProducer.cpp
+++ b/services/surfaceflinger/MonitoredProducer.cpp
@@ -61,7 +61,7 @@
 }
 
 status_t MonitoredProducer::dequeueBuffer(int* slot, sp<Fence>* fence,
-        bool async, uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
+        bool async, uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) {
     return mProducer->dequeueBuffer(slot, fence, async, w, h, format, usage);
 }
 
@@ -106,7 +106,7 @@
 }
 
 void MonitoredProducer::allocateBuffers(bool async, uint32_t width,
-        uint32_t height, uint32_t format, uint32_t usage) {
+        uint32_t height, PixelFormat format, uint32_t usage) {
     mProducer->allocateBuffers(async, width, height, format, usage);
 }
 
diff --git a/services/surfaceflinger/MonitoredProducer.h b/services/surfaceflinger/MonitoredProducer.h
index f6ccc51..aec3e85 100644
--- a/services/surfaceflinger/MonitoredProducer.h
+++ b/services/surfaceflinger/MonitoredProducer.h
@@ -37,7 +37,7 @@
     virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
     virtual status_t setBufferCount(int bufferCount);
     virtual status_t dequeueBuffer(int* slot, sp<Fence>* fence, bool async,
-            uint32_t w, uint32_t h, uint32_t format, uint32_t usage);
+            uint32_t w, uint32_t h, PixelFormat format, uint32_t usage);
     virtual status_t detachBuffer(int slot);
     virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
             sp<Fence>* outFence);
@@ -52,7 +52,7 @@
     virtual status_t disconnect(int api);
     virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage);
+            PixelFormat format, uint32_t usage);
     virtual IBinder* onAsBinder();
 
 private:
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 7a1f243..a560ca3 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -148,7 +148,11 @@
         mPrimaryHWVsyncEnabled(false),
         mHWVsyncAvailable(false),
         mDaltonize(false),
-        mHasColorMatrix(false)
+        mHasColorMatrix(false),
+        mHasPoweredOff(false),
+        mFrameBuckets(),
+        mTotalTime(0),
+        mLastSwapTime(0)
 {
     ALOGI("SurfaceFlinger is starting");
 
@@ -953,8 +957,8 @@
         }
     }
 
+    const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
     if (kIgnorePresentFences) {
-        const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
         if (hw->isDisplayOn()) {
             enableHardwareVsync();
         }
@@ -973,6 +977,26 @@
         }
         mAnimFrameTracker.advanceFrame();
     }
+
+    if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
+        return;
+    }
+
+    nsecs_t currentTime = systemTime();
+    if (mHasPoweredOff) {
+        mHasPoweredOff = false;
+    } else {
+        nsecs_t period = mPrimaryDispSync.getPeriod();
+        nsecs_t elapsedTime = currentTime - mLastSwapTime;
+        size_t numPeriods = static_cast<size_t>(elapsedTime / period);
+        if (numPeriods < NUM_BUCKETS - 1) {
+            mFrameBuckets[numPeriods] += elapsedTime;
+        } else {
+            mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
+        }
+        mTotalTime += elapsedTime;
+    }
+    mLastSwapTime = currentTime;
 }
 
 void SurfaceFlinger::rebuildLayerStacks() {
@@ -2349,6 +2373,7 @@
         }
 
         mVisibleRegionsDirty = true;
+        mHasPoweredOff = true;
         repaintEverything();
     } else if (mode == HWC_POWER_MODE_OFF) {
         if (type == DisplayDevice::DISPLAY_PRIMARY) {
@@ -2449,6 +2474,13 @@
                 mPrimaryDispSync.dump(result);
                 dumpAll = false;
             }
+
+            if ((index < numArgs) &&
+                    (args[index] == String16("--static-screen"))) {
+                index++;
+                dumpStaticScreenStats(result);
+                dumpAll = false;
+            }
         }
 
         if (dumpAll) {
@@ -2552,6 +2584,23 @@
     result.append(config);
 }
 
+void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
+{
+    result.appendFormat("Static screen stats:\n");
+    for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
+        float bucketTimeSec = mFrameBuckets[b] / 1e9;
+        float percent = 100.0f *
+                static_cast<float>(mFrameBuckets[b]) / mTotalTime;
+        result.appendFormat("  < %zd frames: %.3f s (%.1f%%)\n",
+                b + 1, bucketTimeSec, percent);
+    }
+    float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
+    float percent = 100.0f *
+            static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
+    result.appendFormat("  %zd+ frames: %.3f s (%.1f%%)\n",
+            NUM_BUCKETS - 1, bucketTimeSec, percent);
+}
+
 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
         String8& result) const
 {
@@ -2598,6 +2647,11 @@
         mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
     result.append("\n");
 
+    // Dump static screen stats
+    result.append("\n");
+    dumpStaticScreenStats(result);
+    result.append("\n");
+
     /*
      * Dump the visible layer list
      */
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 4deb815..34f0aaa 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -416,6 +416,8 @@
 
     void logFrameStats();
 
+    void dumpStaticScreenStats(String8& result) const;
+
     /* ------------------------------------------------------------------------
      * Attributes
      */
@@ -493,6 +495,13 @@
 
     mat4 mColorMatrix;
     bool mHasColorMatrix;
+
+    // Static screen stats
+    bool mHasPoweredOff;
+    static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
+    nsecs_t mFrameBuckets[NUM_BUCKETS];
+    nsecs_t mTotalTime;
+    nsecs_t mLastSwapTime;
 };
 
 }; // namespace android