Merge "Update HWC dump format"
diff --git a/include/android/sensor.h b/include/android/sensor.h
index b4e7ebe..86de930 100644
--- a/include/android/sensor.h
+++ b/include/android/sensor.h
@@ -157,7 +157,9 @@
             uint64_t        step_counter;
         } u64;
     };
-    int32_t reserved1[4];
+
+    uint32_t flags;
+    int32_t reserved1[3];
 } ASensorEvent;
 
 struct ASensorManager;
diff --git a/include/gui/BufferQueue.h b/include/gui/BufferQueue.h
index 311926d..3297b10 100644
--- a/include/gui/BufferQueue.h
+++ b/include/gui/BufferQueue.h
@@ -17,59 +17,22 @@
 #ifndef ANDROID_GUI_BUFFERQUEUE_H
 #define ANDROID_GUI_BUFFERQUEUE_H
 
-#include <gui/BufferQueueProducer.h>
-#include <gui/BufferQueueConsumer.h>
+#include <gui/BufferQueueDefs.h>
+#include <gui/IGraphicBufferConsumer.h>
+#include <gui/IGraphicBufferProducer.h>
 #include <gui/IConsumerListener.h>
 
 // These are only required to keep other parts of the framework with incomplete
 // dependencies building successfully
 #include <gui/IGraphicBufferAlloc.h>
 
-#include <binder/IBinder.h>
-
 namespace android {
 
-// BQProducer and BQConsumer are thin shim classes to allow methods with the
-// same signature in both IGraphicBufferProducer and IGraphicBufferConsumer.
-// This will stop being an issue when we deprecate creating BufferQueues
-// directly (as opposed to using the *Producer and *Consumer interfaces).
-class BQProducer : public BnGraphicBufferProducer {
-public:
-    virtual status_t detachProducerBuffer(int slot) = 0;
-    virtual status_t attachProducerBuffer(int* slot,
-            const sp<GraphicBuffer>& buffer) = 0;
-
-    virtual status_t detachBuffer(int slot) {
-        return detachProducerBuffer(slot);
-    }
-
-    virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer) {
-        return attachProducerBuffer(slot, buffer);
-    }
-};
-
-class BQConsumer : public BnGraphicBufferConsumer {
-public:
-    virtual status_t detachConsumerBuffer(int slot) = 0;
-    virtual status_t attachConsumerBuffer(int* slot,
-            const sp<GraphicBuffer>& buffer) = 0;
-
-    virtual status_t detachBuffer(int slot) {
-        return detachConsumerBuffer(slot);
-    }
-
-    virtual status_t attachBuffer(int* slot, const sp<GraphicBuffer>& buffer) {
-        return attachConsumerBuffer(slot, buffer);
-    }
-};
-
-class BufferQueue : public BQProducer,
-                    public BQConsumer,
-                    private IBinder::DeathRecipient {
+class BufferQueue {
 public:
     // BufferQueue will keep track of at most this value of buffers.
     // Attempts at runtime to increase the number of buffers past this will fail.
-    enum { NUM_BUFFER_SLOTS = 32 };
+    enum { NUM_BUFFER_SLOTS = BufferQueueDefs::NUM_BUFFER_SLOTS };
     // Used as a placeholder slot# when the value isn't pointing to an existing buffer.
     enum { INVALID_BUFFER_SLOT = IGraphicBufferConsumer::BufferItem::INVALID_BUFFER_SLOT };
     // Alias to <IGraphicBufferConsumer.h> -- please scope from there in future code!
@@ -84,6 +47,7 @@
 
     // for backward source compatibility
     typedef ::android::ConsumerListener ConsumerListener;
+    typedef IGraphicBufferConsumer::BufferItem BufferItem;
 
     // ProxyConsumerListener is a ConsumerListener implementation that keeps a weak
     // reference to the actual consumer object.  It forwards all calls to that
@@ -110,272 +74,12 @@
     // BufferQueue manages a pool of gralloc memory slots to be used by
     // producers and consumers. allocator is used to allocate all the
     // needed gralloc buffers.
-    BufferQueue(const sp<IGraphicBufferAlloc>& allocator = NULL);
-
     static void createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
             sp<IGraphicBufferConsumer>* outConsumer,
             const sp<IGraphicBufferAlloc>& allocator = NULL);
 
-    virtual ~BufferQueue();
-
-    /*
-     * IBinder::DeathRecipient interface
-     */
-
-    virtual void binderDied(const wp<IBinder>& who);
-
-    /*
-     * IGraphicBufferProducer interface
-     */
-
-    // Query native window attributes.  The "what" values are enumerated in
-    // window.h (e.g. NATIVE_WINDOW_FORMAT).
-    virtual int query(int what, int* value);
-
-    // setBufferCount updates the number of available buffer slots.  If this
-    // method succeeds, buffer slots will be both unallocated and owned by
-    // the BufferQueue object (i.e. they are not owned by the producer or
-    // consumer).
-    //
-    // This will fail if the producer has dequeued any buffers, or if
-    // bufferCount is invalid.  bufferCount must generally be a value
-    // between the minimum undequeued buffer count (exclusive) and NUM_BUFFER_SLOTS
-    // (inclusive).  It may also be set to zero (the default) to indicate
-    // that the producer does not wish to set a value.  The minimum value
-    // can be obtained by calling query(NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
-    // ...).
-    //
-    // This may only be called by the producer.  The consumer will be told
-    // to discard buffers through the onBuffersReleased callback.
-    virtual status_t setBufferCount(int bufferCount);
-
-    // requestBuffer returns the GraphicBuffer for slot N.
-    //
-    // In normal operation, this is called the first time slot N is returned
-    // by dequeueBuffer.  It must be called again if dequeueBuffer returns
-    // flags indicating that previously-returned buffers are no longer valid.
-    virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
-
-    // dequeueBuffer gets the next buffer slot index for the producer to use.
-    // If a buffer slot is available then that slot index is written to the
-    // location pointed to by the buf argument and a status of OK is returned.
-    // If no slot is available then a status of -EBUSY is returned and buf is
-    // unmodified.
-    //
-    // The fence parameter will be updated to hold the fence associated with
-    // the buffer. The contents of the buffer must not be overwritten until the
-    // fence signals. If the fence is Fence::NO_FENCE, the buffer may be
-    // written immediately.
-    //
-    // The width and height parameters must be no greater than the minimum of
-    // GL_MAX_VIEWPORT_DIMS and GL_MAX_TEXTURE_SIZE (see: glGetIntegerv).
-    // An error due to invalid dimensions might not be reported until
-    // 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.
-    //
-    // The usage argument specifies gralloc buffer usage flags.  The values
-    // are enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER.  These
-    // will be merged with the usage flags specified by setConsumerUsageBits.
-    //
-    // The return value may be a negative error value or a non-negative
-    // collection of flags.  If the flags are set, the return values are
-    // valid, but additional actions must be performed.
-    //
-    // If IGraphicBufferProducer::BUFFER_NEEDS_REALLOCATION is set, the
-    // producer must discard cached GraphicBuffer references for the slot
-    // returned in buf.
-    // If IGraphicBufferProducer::RELEASE_ALL_BUFFERS is set, the producer
-    // must discard cached GraphicBuffer references for all slots.
-    //
-    // In both cases, the producer will need to call requestBuffer to get a
-    // GraphicBuffer handle for the returned slot.
-    virtual status_t dequeueBuffer(int *buf, sp<Fence>* fence, bool async,
-            uint32_t width, uint32_t height, uint32_t format, uint32_t usage);
-
-    // See IGraphicBufferProducer::detachBuffer
-    virtual status_t detachProducerBuffer(int slot);
-
-    // See IGraphicBufferProducer::detachNextBuffer
-    virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
-            sp<Fence>* outFence);
-
-    // See IGraphicBufferProducer::attachBuffer
-    virtual status_t attachProducerBuffer(int* slot,
-            const sp<GraphicBuffer>& buffer);
-
-    // queueBuffer returns a filled buffer to the BufferQueue.
-    //
-    // Additional data is provided in the QueueBufferInput struct.  Notably,
-    // a timestamp must be provided for the buffer. The timestamp is in
-    // nanoseconds, and must be monotonically increasing. Its other semantics
-    // (zero point, etc) are producer-specific and should be documented by the
-    // producer.
-    //
-    // The caller may provide a fence that signals when all rendering
-    // operations have completed.  Alternatively, NO_FENCE may be used,
-    // indicating that the buffer is ready immediately.
-    //
-    // Some values are returned in the output struct: the current settings
-    // for default width and height, the current transform hint, and the
-    // number of queued buffers.
-    virtual status_t queueBuffer(int buf,
-            const QueueBufferInput& input, QueueBufferOutput* output);
-
-    // cancelBuffer returns a dequeued buffer to the BufferQueue, but doesn't
-    // queue it for use by the consumer.
-    //
-    // The buffer will not be overwritten until the fence signals.  The fence
-    // will usually be the one obtained from dequeueBuffer.
-    virtual void cancelBuffer(int buf, const sp<Fence>& fence);
-
-    // See IGraphicBufferProducer::connect
-    virtual status_t connect(const sp<IProducerListener>& listener,
-            int api, bool producerControlledByApp, QueueBufferOutput* output);
-
-    // disconnect attempts to disconnect a producer API from the BufferQueue.
-    // Calling this method will cause any subsequent calls to other
-    // IGraphicBufferProducer methods to fail except for getAllocator and connect.
-    // Successfully calling connect after this will allow the other methods to
-    // succeed again.
-    //
-    // This method will fail if the the BufferQueue is not currently
-    // connected to the specified producer API.
-    virtual status_t disconnect(int api);
-
-    // Attaches a sideband buffer stream to the BufferQueue.
-    //
-    // A sideband stream is a device-specific mechanism for passing buffers
-    // from the producer to the consumer without using dequeueBuffer/
-    // queueBuffer. If a sideband stream is present, the consumer can choose
-    // whether to acquire buffers from the sideband stream or from the queued
-    // buffers.
-    //
-    // Passing NULL or a different stream handle will detach the previous
-    // handle if any.
-    virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
-
-    /*
-     * IGraphicBufferConsumer interface
-     */
-
-    // acquireBuffer attempts to acquire ownership of the next pending buffer in
-    // the BufferQueue.  If no buffer is pending then it returns NO_BUFFER_AVAILABLE. If a
-    // buffer is successfully acquired, the information about the buffer is
-    // returned in BufferItem.  If the buffer returned had previously been
-    // acquired then the BufferItem::mGraphicBuffer field of buffer is set to
-    // NULL and it is assumed that the consumer still holds a reference to the
-    // buffer.
-    //
-    // If presentWhen is nonzero, it indicates the time when the buffer will
-    // be displayed on screen.  If the buffer's timestamp is farther in the
-    // future, the buffer won't be acquired, and PRESENT_LATER will be
-    // returned.  The presentation time is in nanoseconds, and the time base
-    // is CLOCK_MONOTONIC.
-    virtual status_t acquireBuffer(BufferItem* buffer, nsecs_t presentWhen);
-
-    // See IGraphicBufferConsumer::detachBuffer
-    virtual status_t detachConsumerBuffer(int slot);
-
-    // See IGraphicBufferConsumer::attachBuffer
-    virtual status_t attachConsumerBuffer(int* slot,
-            const sp<GraphicBuffer>& buffer);
-
-    // releaseBuffer releases a buffer slot from the consumer back to the
-    // BufferQueue.  This may be done while the buffer's contents are still
-    // being accessed.  The fence will signal when the buffer is no longer
-    // in use. frameNumber is used to indentify the exact buffer returned.
-    //
-    // If releaseBuffer returns STALE_BUFFER_SLOT, then the consumer must free
-    // any references to the just-released buffer that it might have, as if it
-    // had received a onBuffersReleased() call with a mask set for the released
-    // buffer.
-    //
-    // Note that the dependencies on EGL will be removed once we switch to using
-    // the Android HW Sync HAL.
-    virtual status_t releaseBuffer(int buf, uint64_t frameNumber,
-            EGLDisplay display, EGLSyncKHR fence,
-            const sp<Fence>& releaseFence);
-
-    // consumerConnect connects a consumer to the BufferQueue.  Only one
-    // consumer may be connected, and when that consumer disconnects the
-    // BufferQueue is placed into the "abandoned" state, causing most
-    // interactions with the BufferQueue by the producer to fail.
-    // controlledByApp indicates whether the consumer is controlled by
-    // the application.
-    //
-    // consumer may not be NULL.
-    virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp);
-
-    // consumerDisconnect disconnects a consumer from the BufferQueue. All
-    // buffers will be freed and the BufferQueue is placed in the "abandoned"
-    // state, causing most interactions with the BufferQueue by the producer to
-    // fail.
-    virtual status_t consumerDisconnect();
-
-    // getReleasedBuffers sets the value pointed to by slotMask to a bit mask
-    // indicating which buffer slots have been released by the BufferQueue
-    // but have not yet been released by the consumer.
-    //
-    // This should be called from the onBuffersReleased() callback.
-    virtual status_t getReleasedBuffers(uint32_t* slotMask);
-
-    // setDefaultBufferSize is used to set the size of buffers returned by
-    // dequeueBuffer when a width and height of zero is requested.  Default
-    // is 1x1.
-    virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h);
-
-    // setDefaultMaxBufferCount sets the default value for the maximum buffer
-    // count (the initial default is 2). If the producer has requested a
-    // buffer count using setBufferCount, the default buffer count will only
-    // take effect if the producer sets the count back to zero.
-    //
-    // The count must be between 2 and NUM_BUFFER_SLOTS, inclusive.
-    virtual status_t setDefaultMaxBufferCount(int bufferCount);
-
-    // disableAsyncBuffer disables the extra buffer used in async mode
-    // (when both producer and consumer have set their "isControlledByApp"
-    // flag) and has dequeueBuffer() return WOULD_BLOCK instead.
-    //
-    // This can only be called before consumerConnect().
-    virtual status_t disableAsyncBuffer();
-
-    // setMaxAcquiredBufferCount sets the maximum number of buffers that can
-    // be acquired by the consumer at one time (default 1).  This call will
-    // fail if a producer is connected to the BufferQueue.
-    virtual status_t setMaxAcquiredBufferCount(int maxAcquiredBuffers);
-
-    // setConsumerName sets the name used in logging
-    virtual void setConsumerName(const String8& name);
-
-    // setDefaultBufferFormat allows the BufferQueue to create
-    // GraphicBuffers of a defaultFormat if no format is specified
-    // in dequeueBuffer.  Formats are enumerated in graphics.h; the
-    // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
-    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat);
-
-    // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
-    // These are merged with the bits passed to dequeueBuffer.  The values are
-    // enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER; the default is 0.
-    virtual status_t setConsumerUsageBits(uint32_t usage);
-
-    // setTransformHint bakes in rotation to buffers so overlays can be used.
-    // The values are enumerated in window.h, e.g.
-    // NATIVE_WINDOW_TRANSFORM_ROT_90.  The default is 0 (no transform).
-    virtual status_t setTransformHint(uint32_t hint);
-
-    // Retrieve the BufferQueue's sideband stream, if any.
-    virtual sp<NativeHandle> getSidebandStream() const;
-
-    // dump our state in a String
-    virtual void dump(String8& result, const char* prefix) const;
-
 private:
-    sp<BufferQueueProducer> mProducer;
-    sp<BufferQueueConsumer> mConsumer;
+    BufferQueue(); // Create through createBufferQueue
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/BufferQueueConsumer.h b/include/gui/BufferQueueConsumer.h
index 7f24c83..1912ed0 100644
--- a/include/gui/BufferQueueConsumer.h
+++ b/include/gui/BufferQueueConsumer.h
@@ -93,7 +93,7 @@
     // but have not yet been released by the consumer.
     //
     // This should be called from the onBuffersReleased() callback.
-    virtual status_t getReleasedBuffers(uint32_t* outSlotMask);
+    virtual status_t getReleasedBuffers(uint64_t* outSlotMask);
 
     // setDefaultBufferSize is used to set the size of buffers returned by
     // dequeueBuffer when a width and height of zero is requested.  Default
diff --git a/include/gui/BufferQueueDefs.h b/include/gui/BufferQueueDefs.h
index bccc881..83e9580 100644
--- a/include/gui/BufferQueueDefs.h
+++ b/include/gui/BufferQueueDefs.h
@@ -26,7 +26,7 @@
         // BufferQueue will keep track of at most this value of buffers.
         // Attempts at runtime to increase the number of buffers past this
         // will fail.
-        enum { NUM_BUFFER_SLOTS = 32 };
+        enum { NUM_BUFFER_SLOTS = 64 };
 
         typedef BufferSlot SlotsType[NUM_BUFFER_SLOTS];
     } // namespace BufferQueueDefs
diff --git a/include/gui/IGraphicBufferConsumer.h b/include/gui/IGraphicBufferConsumer.h
index e58612f..15f51fe 100644
--- a/include/gui/IGraphicBufferConsumer.h
+++ b/include/gui/IGraphicBufferConsumer.h
@@ -233,7 +233,7 @@
     //
     // Return of a value other than NO_ERROR means an error has occurred:
     // * NO_INIT - the buffer queue has been abandoned.
-    virtual status_t getReleasedBuffers(uint32_t* slotMask) = 0;
+    virtual status_t getReleasedBuffers(uint64_t* slotMask) = 0;
 
     // setDefaultBufferSize is used to set the size of buffers returned by
     // dequeueBuffer when a width and height of zero is requested.  Default
diff --git a/include/gui/ISensorEventConnection.h b/include/gui/ISensorEventConnection.h
index f64c6b8..b296797 100644
--- a/include/gui/ISensorEventConnection.h
+++ b/include/gui/ISensorEventConnection.h
@@ -40,6 +40,7 @@
                                    nsecs_t maxBatchReportLatencyNs, int reservedFlags) = 0;
     virtual status_t setEventRate(int handle, nsecs_t ns) = 0;
     virtual status_t flush() = 0;
+    virtual void decreaseWakeLockRefCount() = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/Sensor.h b/include/gui/Sensor.h
index 033b262..41a6cc6 100644
--- a/include/gui/Sensor.h
+++ b/include/gui/Sensor.h
@@ -71,6 +71,7 @@
     int32_t getFifoMaxEventCount() const;
     const String8& getStringType() const;
     const String8& getRequiredPermission() const;
+    bool isWakeUpSensor() const;
 
     // LightFlattenable protocol
     inline bool isFixedSize() const { return false; }
@@ -93,6 +94,8 @@
     int32_t mFifoMaxEventCount;
     String8 mStringType;
     String8 mRequiredPermission;
+    // Todo: Surface this in java SDK.
+    bool    mWakeUpSensor;
     static void flattenString8(void*& buffer, size_t& size, const String8& string8);
     static bool unflattenString8(void const*& buffer, size_t& size, String8& outputString8);
 };
diff --git a/include/gui/SensorEventQueue.h b/include/gui/SensorEventQueue.h
index 0bfc7a0..4e8a2d2 100644
--- a/include/gui/SensorEventQueue.h
+++ b/include/gui/SensorEventQueue.h
@@ -27,7 +27,7 @@
 #include <gui/BitTube.h>
 
 // ----------------------------------------------------------------------------
-
+#define WAKE_UP_SENSOR_EVENT_NEEDS_ACK (1 << 31)
 struct ALooper;
 struct ASensorEvent;
 
@@ -75,7 +75,8 @@
                           int reservedFlags) const;
     status_t disableSensor(int32_t handle) const;
     status_t flush() const;
-
+    // Send an ack for every wake_up sensor event that is set to WAKE_UP_SENSOR_EVENT_NEEDS_ACK.
+    void sendAck(const ASensorEvent* events, int count);
 private:
     sp<Looper> getLooper() const;
     sp<ISensorEventConnection> mSensorEventConnection;
diff --git a/include/media/openmax/OMX_IndexExt.h b/include/media/openmax/OMX_IndexExt.h
index ffcd4f3..c503dcf 100644
--- a/include/media/openmax/OMX_IndexExt.h
+++ b/include/media/openmax/OMX_IndexExt.h
@@ -71,6 +71,7 @@
     OMX_IndexParamVideoVp8,                         /**< reference: OMX_VIDEO_PARAM_VP8TYPE */
     OMX_IndexConfigVideoVp8ReferenceFrame,          /**< reference: OMX_VIDEO_VP8REFERENCEFRAMETYPE */
     OMX_IndexConfigVideoVp8ReferenceFrameType,      /**< reference: OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE */
+    OMX_IndexParamVideoAndroidVp8Encoder,           /**< reference: OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE */
 
     /* Image & Video common configurations */
     OMX_IndexExtCommonStartUnused = OMX_IndexKhronosExtensions + 0x00700000,
diff --git a/include/media/openmax/OMX_VideoExt.h b/include/media/openmax/OMX_VideoExt.h
index fa24168..3f18b43 100644
--- a/include/media/openmax/OMX_VideoExt.h
+++ b/include/media/openmax/OMX_VideoExt.h
@@ -108,6 +108,43 @@
     OMX_BOOL bIsGoldenOrAlternateFrame;
 } OMX_VIDEO_VP8REFERENCEFRAMEINFOTYPE;
 
+/** Maximum number of VP8 temporal layers */
+#define OMX_VIDEO_ANDROID_MAXVP8TEMPORALLAYERS 3
+
+/** VP8 temporal layer patterns */
+typedef enum OMX_VIDEO_ANDROID_VPXTEMPORALLAYERPATTERNTYPE {
+    OMX_VIDEO_VPXTemporalLayerPatternNone = 0,
+    OMX_VIDEO_VPXTemporalLayerPatternWebRTC = 1,
+    OMX_VIDEO_VPXTemporalLayerPatternMax = 0x7FFFFFFF
+} OMX_VIDEO_ANDROID_VPXTEMPORALLAYERPATTERNTYPE;
+
+/**
+ * Android specific VP8 encoder params
+ *
+ * STRUCT MEMBERS:
+ *  nSize                      : Size of the structure in bytes
+ *  nVersion                   : OMX specification version information
+ *  nPortIndex                 : Port that this structure applies to
+ *  nKeyFrameInterval          : Key frame interval in frames
+ *  eTemporalPattern           : Type of temporal layer pattern
+ *  nTemporalLayerCount        : Number of temporal coding layers
+ *  nTemporalLayerBitrateRatio : Bitrate ratio allocation between temporal
+ *                               streams in percentage
+ *  nMinQuantizer              : Minimum (best quality) quantizer
+ *  nMaxQuantizer              : Maximum (worst quality) quantizer
+ */
+typedef struct OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE {
+    OMX_U32 nSize;
+    OMX_VERSIONTYPE nVersion;
+    OMX_U32 nPortIndex;
+    OMX_U32 nKeyFrameInterval;
+    OMX_VIDEO_ANDROID_VPXTEMPORALLAYERPATTERNTYPE eTemporalPattern;
+    OMX_U32 nTemporalLayerCount;
+    OMX_U32 nTemporalLayerBitrateRatio[OMX_VIDEO_ANDROID_MAXVP8TEMPORALLAYERS];
+    OMX_U32 nMinQuantizer;
+    OMX_U32 nMaxQuantizer;
+};
+
 
 #ifdef __cplusplus
 }
diff --git a/libs/gui/BufferQueue.cpp b/libs/gui/BufferQueue.cpp
index da980a7..c49a886 100644
--- a/libs/gui/BufferQueue.cpp
+++ b/libs/gui/BufferQueue.cpp
@@ -19,7 +19,9 @@
 //#define LOG_NDEBUG 0
 
 #include <gui/BufferQueue.h>
+#include <gui/BufferQueueConsumer.h>
 #include <gui/BufferQueueCore.h>
+#include <gui/BufferQueueProducer.h>
 
 namespace android {
 
@@ -43,6 +45,13 @@
     }
 }
 
+void BufferQueue::ProxyConsumerListener::onSidebandStreamChanged() {
+    sp<ConsumerListener> listener(mConsumerListener.promote());
+    if (listener != NULL) {
+        listener->onSidebandStreamChanged();
+    }
+}
+
 void BufferQueue::createBufferQueue(sp<IGraphicBufferProducer>* outProducer,
         sp<IGraphicBufferConsumer>* outConsumer,
         const sp<IGraphicBufferAlloc>& allocator) {
@@ -67,151 +76,4 @@
     *outConsumer = consumer;
 }
 
-BufferQueue::BufferQueue(const sp<IGraphicBufferAlloc>& allocator) :
-    mProducer(),
-    mConsumer()
-{
-    sp<BufferQueueCore> core(new BufferQueueCore(allocator));
-    mProducer = new BufferQueueProducer(core);
-    mConsumer = new BufferQueueConsumer(core);
-}
-
-BufferQueue::~BufferQueue() {}
-
-void BufferQueue::binderDied(const wp<IBinder>& who) {
-    mProducer->binderDied(who);
-}
-
-int BufferQueue::query(int what, int* outValue) {
-    return mProducer->query(what, outValue);
-}
-
-status_t BufferQueue::setBufferCount(int bufferCount) {
-    return mProducer->setBufferCount(bufferCount);
-}
-
-status_t BufferQueue::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
-    return mProducer->requestBuffer(slot, buf);
-}
-
-status_t BufferQueue::dequeueBuffer(int *outBuf, sp<Fence>* outFence, bool async,
-        uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
-    return mProducer->dequeueBuffer(outBuf, outFence, async, w, h, format, usage);
-}
-
-status_t BufferQueue::detachProducerBuffer(int slot) {
-    return mProducer->detachBuffer(slot);
-}
-
-status_t BufferQueue::detachNextBuffer(sp<GraphicBuffer>* outBuffer,
-        sp<Fence>* outFence) {
-    return mProducer->detachNextBuffer(outBuffer, outFence);
-}
-
-status_t BufferQueue::attachProducerBuffer(int* slot,
-        const sp<GraphicBuffer>& buffer) {
-    return mProducer->attachBuffer(slot, buffer);
-}
-
-status_t BufferQueue::queueBuffer(int buf,
-        const QueueBufferInput& input, QueueBufferOutput* output) {
-    return mProducer->queueBuffer(buf, input, output);
-}
-
-void BufferQueue::cancelBuffer(int buf, const sp<Fence>& fence) {
-    mProducer->cancelBuffer(buf, fence);
-}
-
-status_t BufferQueue::connect(const sp<IProducerListener>& listener,
-        int api, bool producerControlledByApp, QueueBufferOutput* output) {
-    return mProducer->connect(listener, api, producerControlledByApp, output);
-}
-
-status_t BufferQueue::disconnect(int api) {
-    return mProducer->disconnect(api);
-}
-
-status_t BufferQueue::setSidebandStream(const sp<NativeHandle>& stream) {
-    return mProducer->setSidebandStream(stream);
-}
-
-status_t BufferQueue::acquireBuffer(BufferItem* buffer, nsecs_t presentWhen) {
-    return mConsumer->acquireBuffer(buffer, presentWhen);
-}
-
-status_t BufferQueue::detachConsumerBuffer(int slot) {
-    return mConsumer->detachBuffer(slot);
-}
-
-status_t BufferQueue::attachConsumerBuffer(int* slot,
-        const sp<GraphicBuffer>& buffer) {
-    return mConsumer->attachBuffer(slot, buffer);
-}
-
-status_t BufferQueue::releaseBuffer(
-        int buf, uint64_t frameNumber, EGLDisplay display,
-        EGLSyncKHR eglFence, const sp<Fence>& fence) {
-    return mConsumer->releaseBuffer(buf, frameNumber, fence, display, eglFence);
-}
-
-status_t BufferQueue::consumerConnect(const sp<IConsumerListener>& consumerListener,
-        bool controlledByApp) {
-    return mConsumer->connect(consumerListener, controlledByApp);
-}
-
-status_t BufferQueue::consumerDisconnect() {
-    return mConsumer->disconnect();
-}
-
-status_t BufferQueue::getReleasedBuffers(uint32_t* slotMask) {
-    return mConsumer->getReleasedBuffers(slotMask);
-}
-
-status_t BufferQueue::setDefaultBufferSize(uint32_t w, uint32_t h) {
-    return mConsumer->setDefaultBufferSize(w, h);
-}
-
-status_t BufferQueue::setDefaultMaxBufferCount(int bufferCount) {
-    return mConsumer->setDefaultMaxBufferCount(bufferCount);
-}
-
-status_t BufferQueue::disableAsyncBuffer() {
-    return mConsumer->disableAsyncBuffer();
-}
-
-status_t BufferQueue::setMaxAcquiredBufferCount(int maxAcquiredBuffers) {
-    return mConsumer->setMaxAcquiredBufferCount(maxAcquiredBuffers);
-}
-
-void BufferQueue::setConsumerName(const String8& name) {
-    mConsumer->setConsumerName(name);
-}
-
-status_t BufferQueue::setDefaultBufferFormat(uint32_t defaultFormat) {
-    return mConsumer->setDefaultBufferFormat(defaultFormat);
-}
-
-status_t BufferQueue::setConsumerUsageBits(uint32_t usage) {
-    return mConsumer->setConsumerUsageBits(usage);
-}
-
-status_t BufferQueue::setTransformHint(uint32_t hint) {
-    return mConsumer->setTransformHint(hint);
-}
-
-sp<NativeHandle> BufferQueue::getSidebandStream() const {
-    return mConsumer->getSidebandStream();
-}
-
-void BufferQueue::dump(String8& result, const char* prefix) const {
-    mConsumer->dump(result, prefix);
-}
-
-void BufferQueue::ProxyConsumerListener::onSidebandStreamChanged() {
-    sp<ConsumerListener> listener(mConsumerListener.promote());
-    if (listener != NULL) {
-        listener->onSidebandStreamChanged();
-    }
-}
-
 }; // namespace android
diff --git a/libs/gui/BufferQueueConsumer.cpp b/libs/gui/BufferQueueConsumer.cpp
index e811ee0..f3f26ac 100644
--- a/libs/gui/BufferQueueConsumer.cpp
+++ b/libs/gui/BufferQueueConsumer.cpp
@@ -160,8 +160,10 @@
     }
 
     mCore->mQueue.erase(front);
-    // TODO: Should this call be after we free a slot while dropping buffers?
-    // Simply acquiring the next buffer doesn't enable a producer to dequeue.
+
+    // We might have freed a slot while dropping old buffers, or the producer
+    // may be blocked waiting for the number of buffers in the queue to
+    // decrease.
     mCore->mDequeueCondition.broadcast();
 
     ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
@@ -373,7 +375,7 @@
     return NO_ERROR;
 }
 
-status_t BufferQueueConsumer::getReleasedBuffers(uint32_t *outSlotMask) {
+status_t BufferQueueConsumer::getReleasedBuffers(uint64_t *outSlotMask) {
     ATRACE_CALL();
 
     if (outSlotMask == NULL) {
@@ -388,10 +390,10 @@
         return NO_INIT;
     }
 
-    uint32_t mask = 0;
+    uint64_t mask = 0;
     for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
         if (!mSlots[s].mAcquireCalled) {
-            mask |= (1u << s);
+            mask |= (1ULL << s);
         }
     }
 
@@ -401,12 +403,12 @@
     BufferQueueCore::Fifo::iterator current(mCore->mQueue.begin());
     while (current != mCore->mQueue.end()) {
         if (current->mAcquireCalled) {
-            mask &= ~(1u << current->mSlot);
+            mask &= ~(1ULL << current->mSlot);
         }
         ++current;
     }
 
-    BQ_LOGV("getReleasedBuffers: returning mask %#x", mask);
+    BQ_LOGV("getReleasedBuffers: returning mask %#" PRIx64, mask);
     *outSlotMask = mask;
     return NO_ERROR;
 }
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index 61846dd..f536a59 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -205,9 +205,21 @@
             }
         }
 
-        // If no buffer is found, wait for a buffer to be released or for
-        // the max buffer count to change
-        tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT);
+        // If we disconnect and reconnect quickly, we can be in a state where
+        // our slots are empty but we have many buffers in the queue. This can
+        // cause us to run out of memory if we outrun the consumer. Wait here if
+        // it looks like we have too many buffers queued up.
+        bool tooManyBuffers = mCore->mQueue.size() > maxBufferCount;
+        if (tooManyBuffers) {
+            BQ_LOGV("%s: queue size is %d, waiting", caller,
+                    mCore->mQueue.size());
+        }
+
+        // If no buffer is found, or if the queue has too many buffers
+        // outstanding, wait for a buffer to be acquired or released, or for the
+        // max buffer count to change.
+        tryAgain = (*found == BufferQueueCore::INVALID_BUFFER_SLOT) ||
+                   tooManyBuffers;
         if (tryAgain) {
             // Return an error if we're in non-blocking mode (producer and
             // consumer are controlled by the application).
@@ -707,41 +719,25 @@
     BQ_LOGV("connect(P): api=%d producerControlledByApp=%s", api,
             producerControlledByApp ? "true" : "false");
 
-    // If we disconnect and reconnect quickly, we can be in a state where our
-    // slots are empty but we have many buffers in the queue. This can cause us
-    // to run out of memory if we outrun the consumer. Wait here if it looks
-    // like we have too many buffers queued up.
-    while (true) {
-        if (mCore->mIsAbandoned) {
-            BQ_LOGE("connect(P): BufferQueue has been abandoned");
-            return NO_INIT;
-        }
+    if (mCore->mIsAbandoned) {
+        BQ_LOGE("connect(P): BufferQueue has been abandoned");
+        return NO_INIT;
+    }
 
-        if (mCore->mConsumerListener == NULL) {
-            BQ_LOGE("connect(P): BufferQueue has no consumer");
-            return NO_INIT;
-        }
+    if (mCore->mConsumerListener == NULL) {
+        BQ_LOGE("connect(P): BufferQueue has no consumer");
+        return NO_INIT;
+    }
 
-        if (output == NULL) {
-            BQ_LOGE("connect(P): output was NULL");
-            return BAD_VALUE;
-        }
+    if (output == NULL) {
+        BQ_LOGE("connect(P): output was NULL");
+        return BAD_VALUE;
+    }
 
-        if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
-            BQ_LOGE("connect(P): already connected (cur=%d req=%d)",
-                    mCore->mConnectedApi, api);
-            return BAD_VALUE;
-        }
-
-        size_t maxBufferCount = mCore->getMaxBufferCountLocked(false);
-        if (mCore->mQueue.size() <= maxBufferCount) {
-            // The queue size seems small enough to proceed
-            // TODO: Make this bound tighter?
-            break;
-        }
-
-        BQ_LOGV("connect(P): queue size is %d, waiting", mCore->mQueue.size());
-        mCore->mDequeueCondition.wait(mCore->mMutex);
+    if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
+        BQ_LOGE("connect(P): already connected (cur=%d req=%d)",
+                mCore->mConnectedApi, api);
+        return BAD_VALUE;
     }
 
     int status = NO_ERROR;
diff --git a/libs/gui/ConsumerBase.cpp b/libs/gui/ConsumerBase.cpp
index b6adc54..f1b8fa8 100644
--- a/libs/gui/ConsumerBase.cpp
+++ b/libs/gui/ConsumerBase.cpp
@@ -121,10 +121,10 @@
         return;
     }
 
-    uint32_t mask = 0;
+    uint64_t mask = 0;
     mConsumer->getReleasedBuffers(&mask);
     for (int i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
-        if (mask & (1 << i)) {
+        if (mask & (1ULL << i)) {
             freeBufferLocked(i);
         }
     }
diff --git a/libs/gui/IGraphicBufferConsumer.cpp b/libs/gui/IGraphicBufferConsumer.cpp
index 9ef2544..f6d087d 100644
--- a/libs/gui/IGraphicBufferConsumer.cpp
+++ b/libs/gui/IGraphicBufferConsumer.cpp
@@ -292,14 +292,18 @@
         return reply.readInt32();
     }
 
-    virtual status_t getReleasedBuffers(uint32_t* slotMask) {
+    virtual status_t getReleasedBuffers(uint64_t* slotMask) {
         Parcel data, reply;
+        if (slotMask == NULL) {
+            ALOGE("getReleasedBuffers: slotMask must not be NULL");
+            return BAD_VALUE;
+        }
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
         status_t result = remote()->transact(GET_RELEASED_BUFFERS, data, &reply);
         if (result != NO_ERROR) {
             return result;
         }
-        *slotMask = reply.readInt32();
+        *slotMask = reply.readInt64();
         return reply.readInt32();
     }
 
@@ -474,9 +478,9 @@
         } break;
         case GET_RELEASED_BUFFERS: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t slotMask;
+            uint64_t slotMask;
             status_t result = getReleasedBuffers(&slotMask);
-            reply->writeInt32(slotMask);
+            reply->writeInt64(slotMask);
             reply->writeInt32(result);
             return NO_ERROR;
         } break;
diff --git a/libs/gui/ISensorEventConnection.cpp b/libs/gui/ISensorEventConnection.cpp
index 28fcb53..8f88141 100644
--- a/libs/gui/ISensorEventConnection.cpp
+++ b/libs/gui/ISensorEventConnection.cpp
@@ -34,7 +34,8 @@
     GET_SENSOR_CHANNEL = IBinder::FIRST_CALL_TRANSACTION,
     ENABLE_DISABLE,
     SET_EVENT_RATE,
-    FLUSH_SENSOR
+    FLUSH_SENSOR,
+    DECREASE_WAKE_LOCK_REFCOUNT
 };
 
 class BpSensorEventConnection : public BpInterface<ISensorEventConnection>
@@ -83,6 +84,13 @@
         remote()->transact(FLUSH_SENSOR, data, &reply);
         return reply.readInt32();
     }
+
+    virtual void decreaseWakeLockRefCount() {
+        Parcel data, reply;
+        data.writeInterfaceToken(ISensorEventConnection::getInterfaceDescriptor());
+        remote()->transact(DECREASE_WAKE_LOCK_REFCOUNT, data, &reply, IBinder::FLAG_ONEWAY);
+        return;
+    }
 };
 
 IMPLEMENT_META_INTERFACE(SensorEventConnection, "android.gui.SensorEventConnection");
@@ -125,6 +133,11 @@
             reply->writeInt32(result);
             return NO_ERROR;
         } break;
+        case DECREASE_WAKE_LOCK_REFCOUNT: {
+            CHECK_INTERFACE(ISensorEventConnection, data, reply);
+            decreaseWakeLockRefCount();
+            return NO_ERROR;
+        } break;
     }
     return BBinder::onTransact(code, data, reply, flags);
 }
diff --git a/libs/gui/Sensor.cpp b/libs/gui/Sensor.cpp
index 6f1a3f2..b363411 100644
--- a/libs/gui/Sensor.cpp
+++ b/libs/gui/Sensor.cpp
@@ -32,7 +32,8 @@
 Sensor::Sensor()
     : mHandle(0), mType(0),
       mMinValue(0), mMaxValue(0), mResolution(0),
-      mPower(0), mMinDelay(0), mFifoReservedEventCount(0), mFifoMaxEventCount(0)
+      mPower(0), mMinDelay(0), mFifoReservedEventCount(0), mFifoMaxEventCount(0),
+      mWakeUpSensor(false)
 {
 }
 
@@ -48,6 +49,7 @@
     mResolution = hwSensor->resolution;
     mPower = hwSensor->power;
     mMinDelay = hwSensor->minDelay;
+    mWakeUpSensor = false;
 
     // Set fifo event count zero for older devices which do not support batching. Fused
     // sensors also have their fifo counts set to zero.
@@ -104,6 +106,7 @@
         break;
     case SENSOR_TYPE_PROXIMITY:
         mStringType = SENSOR_STRING_TYPE_PROXIMITY;
+        mWakeUpSensor = true;
         break;
     case SENSOR_TYPE_RELATIVE_HUMIDITY:
         mStringType = SENSOR_STRING_TYPE_RELATIVE_HUMIDITY;
@@ -113,6 +116,7 @@
         break;
     case SENSOR_TYPE_SIGNIFICANT_MOTION:
         mStringType = SENSOR_STRING_TYPE_SIGNIFICANT_MOTION;
+        mWakeUpSensor = true;
         break;
     case SENSOR_TYPE_STEP_COUNTER:
         mStringType = SENSOR_STRING_TYPE_STEP_COUNTER;
@@ -123,14 +127,93 @@
     case SENSOR_TYPE_TEMPERATURE:
         mStringType = SENSOR_STRING_TYPE_TEMPERATURE;
         break;
+    case SENSOR_TYPE_NON_WAKE_UP_PROXIMITY_SENSOR:
+        mStringType = SENSOR_STRING_TYPE_NON_WAKE_UP_PROXIMITY_SENSOR;
+        break;
+    case SENSOR_TYPE_WAKE_UP_ACCELEROMETER:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_ACCELEROMETER;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_MAGNETIC_FIELD:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_MAGNETIC_FIELD;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_ORIENTATION:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_ORIENTATION;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_GYROSCOPE:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_GYROSCOPE;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_LIGHT:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_LIGHT;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_PRESSURE:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_PRESSURE;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_GRAVITY:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_GRAVITY;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_LINEAR_ACCELERATION:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_LINEAR_ACCELERATION;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_ROTATION_VECTOR:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_ROTATION_VECTOR;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_RELATIVE_HUMIDITY:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_RELATIVE_HUMIDITY;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_AMBIENT_TEMPERATURE:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_AMBIENT_TEMPERATURE;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_MAGNETIC_FIELD_UNCALIBRATED:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_MAGNETIC_FIELD_UNCALIBRATED;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_GAME_ROTATION_VECTOR:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_GAME_ROTATION_VECTOR;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_GYROSCOPE_UNCALIBRATED:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_GYROSCOPE_UNCALIBRATED;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_STEP_DETECTOR:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_STEP_DETECTOR;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_STEP_COUNTER:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_STEP_COUNTER;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_GEOMAGNETIC_ROTATION_VECTOR:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_GEOMAGNETIC_ROTATION_VECTOR;
+        mWakeUpSensor = true;
+        break;
+    case SENSOR_TYPE_WAKE_UP_HEART_RATE:
+        mStringType = SENSOR_STRING_TYPE_WAKE_UP_HEART_RATE;
+        mRequiredPermission = SENSOR_PERMISSION_BODY_SENSORS;
+        mWakeUpSensor = true;
+        break;
     default:
-        // Only pipe the stringType and requiredPermission for custom sensors.
+        // Only pipe the stringType, requiredPermission and flags for custom sensors.
         if (halVersion >= SENSORS_DEVICE_API_VERSION_1_2 && hwSensor->stringType) {
             mStringType = hwSensor->stringType;
         }
         if (halVersion >= SENSORS_DEVICE_API_VERSION_1_2 && hwSensor->requiredPermission) {
             mRequiredPermission = hwSensor->requiredPermission;
         }
+        if (halVersion >= SENSORS_DEVICE_API_VERSION_1_3) {
+            mWakeUpSensor = hwSensor->flags & SENSOR_FLAG_WAKE_UP;
+        }
         break;
     }
 }
@@ -199,6 +282,10 @@
     return mRequiredPermission;
 }
 
+bool Sensor::isWakeUpSensor() const {
+    return mWakeUpSensor;
+}
+
 size_t Sensor::getFlattenedSize() const
 {
     size_t fixedSize =
diff --git a/libs/gui/SensorEventQueue.cpp b/libs/gui/SensorEventQueue.cpp
index c365671..c2eaf4e 100644
--- a/libs/gui/SensorEventQueue.cpp
+++ b/libs/gui/SensorEventQueue.cpp
@@ -144,6 +144,15 @@
     return mSensorEventConnection->setEventRate(sensor->getHandle(), ns);
 }
 
+void SensorEventQueue::sendAck(const ASensorEvent* events, int count) {
+    for (int i = 0; i < count; ++i) {
+        if (events[i].flags & WAKE_UP_SENSOR_EVENT_NEEDS_ACK) {
+            mSensorEventConnection->decreaseWakeLockRefCount();
+        }
+    }
+    return;
+}
+
 // ----------------------------------------------------------------------------
 }; // namespace android
 
diff --git a/opengl/libs/EGL/Loader.cpp b/opengl/libs/EGL/Loader.cpp
index e528831..1fcc048 100644
--- a/opengl/libs/EGL/Loader.cpp
+++ b/opengl/libs/EGL/Loader.cpp
@@ -188,12 +188,17 @@
     LOG_ALWAYS_FATAL_IF(!hnd, "couldn't find an OpenGL ES implementation");
 
 #if defined(__LP64__)
+    cnx->libEgl   = load_wrapper("/system/lib64/libEGL.so");
     cnx->libGles2 = load_wrapper("/system/lib64/libGLESv2.so");
     cnx->libGles1 = load_wrapper("/system/lib64/libGLESv1_CM.so");
 #else
+    cnx->libEgl   = load_wrapper("/system/lib/libEGL.so");
     cnx->libGles2 = load_wrapper("/system/lib/libGLESv2.so");
     cnx->libGles1 = load_wrapper("/system/lib/libGLESv1_CM.so");
 #endif
+    LOG_ALWAYS_FATAL_IF(!cnx->libEgl,
+            "couldn't load system EGL wrapper libraries");
+
     LOG_ALWAYS_FATAL_IF(!cnx->libGles2 || !cnx->libGles1,
             "couldn't load system OpenGL ES wrapper libraries");
 
diff --git a/opengl/libs/EGL/egl.cpp b/opengl/libs/EGL/egl.cpp
index 44b5560..67fbae5 100644
--- a/opengl/libs/EGL/egl.cpp
+++ b/opengl/libs/EGL/egl.cpp
@@ -222,7 +222,7 @@
         }
         char value[PROPERTY_VALUE_MAX];
         property_get("debug.egl.callstack", value, "0");
-        if (true || atoi(value)) {
+        if (atoi(value)) {
             CallStack stack(LOG_TAG);
         }
     }
diff --git a/opengl/libs/EGL/eglApi.cpp b/opengl/libs/EGL/eglApi.cpp
index b6ffdb2..6e77e45 100644
--- a/opengl/libs/EGL/eglApi.cpp
+++ b/opengl/libs/EGL/eglApi.cpp
@@ -879,11 +879,14 @@
     return err;
 }
 
-static __eglMustCastToProperFunctionPointerType findBuiltinGLWrapper(
+static __eglMustCastToProperFunctionPointerType findBuiltinWrapper(
         const char* procname) {
     const egl_connection_t* cnx = &gEGLImpl;
     void* proc = NULL;
 
+    proc = dlsym(cnx->libEgl, procname);
+    if (proc) return (__eglMustCastToProperFunctionPointerType)proc;
+
     proc = dlsym(cnx->libGles2, procname);
     if (proc) return (__eglMustCastToProperFunctionPointerType)proc;
 
@@ -914,7 +917,7 @@
     addr = findProcAddress(procname, sExtensionMap, NELEM(sExtensionMap));
     if (addr) return addr;
 
-    addr = findBuiltinGLWrapper(procname);
+    addr = findBuiltinWrapper(procname);
     if (addr) return addr;
 
     // this protects accesses to sGLExtentionMap and sGLExtentionSlot
diff --git a/opengl/libs/EGL/egldefs.h b/opengl/libs/EGL/egldefs.h
index b905ea0..9858276 100644
--- a/opengl/libs/EGL/egldefs.h
+++ b/opengl/libs/EGL/egldefs.h
@@ -44,6 +44,7 @@
     EGLint              minor;
     egl_t               egl;
 
+    void*               libEgl;
     void*               libGles1;
     void*               libGles2;
 };
diff --git a/services/sensorservice/SensorDevice.cpp b/services/sensorservice/SensorDevice.cpp
index 3b64f0a..01dbdfb 100644
--- a/services/sensorservice/SensorDevice.cpp
+++ b/services/sensorservice/SensorDevice.cpp
@@ -309,7 +309,7 @@
     return mSensorDevice->common.version;
 }
 
-status_t SensorDevice::flush(void* /*ident*/, int handle) {
+status_t SensorDevice::flush(void* ident, int handle) {
     if (getHalDeviceVersion() < SENSORS_DEVICE_API_VERSION_1_1) {
         return INVALID_OPERATION;
     }
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index 8837a4d..aff4e9a 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -164,6 +164,7 @@
                 fclose(fp);
             }
 
+            mWakeLockAcquired = false;
             run("SensorService", PRIORITY_URGENT_DISPLAY);
             mInitCheck = NO_ERROR;
         }
@@ -284,6 +285,7 @@
         }
 
         result.appendFormat("%zu Max Socket Buffer size\n", mSocketBufferSize);
+        result.appendFormat("WakeLock Status: %s \n", mWakeLockAcquired ? "acquired" : "not held");
         result.appendFormat("%zd active connections\n", mActiveConnections.size());
 
         for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
@@ -298,7 +300,7 @@
     return NO_ERROR;
 }
 
-void SensorService::cleanupAutoDisabledSensor(const sp<SensorEventConnection>& connection,
+void SensorService::cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
         sensors_event_t const* buffer, const int count) {
     SensorInterface* sensor;
     status_t err = NO_ERROR;
@@ -311,7 +313,7 @@
                 if (sensor != NULL) {
                     sensor->autoDisable(connection.get(), handle);
                 }
-                cleanupWithoutDisable(connection, handle);
+                cleanupWithoutDisableLocked(connection, handle);
             }
         }
     }
@@ -333,7 +335,6 @@
     const size_t vcount = mVirtualSensorList.size();
 
     ssize_t count;
-    bool wakeLockAcquired = false;
     const int halVersion = device.getHalDeviceVersion();
     do {
         count = device.poll(buffer, numEventMax);
@@ -341,26 +342,31 @@
             ALOGE("sensor poll failed (%s)", strerror(-count));
             break;
         }
-
-        // Poll has returned. Hold a wakelock.
-        // Todo(): add a flag to the sensors definitions to indicate
-        // the sensors which can wake up the AP
+        Mutex::Autolock _l(mLock);
+        // Poll has returned. Hold a wakelock if one of the events is from a wake up sensor. The
+        // rest of this loop is under a critical section protected by mLock. Acquiring a wakeLock,
+        // sending events to clients (incrementing SensorEventConnection::mWakeLockRefCount) should
+        // not be interleaved with decrementing SensorEventConnection::mWakeLockRefCount and
+        // releasing the wakelock.
+        bool bufferHasWakeUpEvent = false;
         for (int i = 0; i < count; i++) {
-            if (buffer[i].type == SENSOR_TYPE_SIGNIFICANT_MOTION) {
-                 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
-                 wakeLockAcquired = true;
-                 break;
+            if (isWakeUpSensorEvent(buffer[i])) {
+                bufferHasWakeUpEvent = true;
+                break;
             }
         }
 
-        recordLastValue(buffer, count);
+        if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
+            acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
+            mWakeLockAcquired = true;
+            ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock %s", WAKE_LOCK_NAME);
+        }
+        recordLastValueLocked(buffer, count);
 
         // handle virtual sensors
         if (count && vcount) {
             sensors_event_t const * const event = buffer;
-            const DefaultKeyedVector<int, SensorInterface*> virtualSensors(
-                    getActiveVirtualSensors());
-            const size_t activeVirtualSensorCount = virtualSensors.size();
+            const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
             if (activeVirtualSensorCount) {
                 size_t k = 0;
                 SensorFusion& fusion(SensorFusion::getInstance());
@@ -378,7 +384,7 @@
                             break;
                         }
                         sensors_event_t out;
-                        SensorInterface* si = virtualSensors.valueAt(j);
+                        SensorInterface* si = mActiveVirtualSensors.valueAt(j);
                         if (si->process(&out, event[i])) {
                             buffer[count + k] = out;
                             k++;
@@ -387,7 +393,7 @@
                 }
                 if (k) {
                     // record the last synthesized values
-                    recordLastValue(&buffer[count], k);
+                    recordLastValueLocked(&buffer[count], k);
                     count += k;
                     // sort the buffer by time-stamps
                     sortEventBuffer(buffer, count);
@@ -406,22 +412,24 @@
             }
         }
 
-        // send our events to clients...
-        const SortedVector< wp<SensorEventConnection> > activeConnections(
-                getActiveConnections());
-        size_t numConnections = activeConnections.size();
-        for (size_t i=0 ; i<numConnections ; i++) {
-            sp<SensorEventConnection> connection(
-                    activeConnections[i].promote());
+        // Send our events to clients. Check the state of wake lock for each client and release the
+        // lock if none of the clients need it.
+        bool needsWakeLock = false;
+        for (size_t i=0 ; i < mActiveConnections.size(); i++) {
+            sp<SensorEventConnection> connection(mActiveConnections[i].promote());
             if (connection != 0) {
                 connection->sendEvents(buffer, count, scratch);
+                needsWakeLock |= connection->needsWakeLock();
                 // Some sensors need to be auto disabled after the trigger
-                cleanupAutoDisabledSensor(connection, buffer, count);
+                cleanupAutoDisabledSensorLocked(connection, buffer, count);
             }
         }
 
-        // We have read the data, upper layers should hold the wakelock.
-        if (wakeLockAcquired) release_wake_lock(WAKE_LOCK_NAME);
+        if (mWakeLockAcquired && !needsWakeLock) {
+            release_wake_lock(WAKE_LOCK_NAME);
+            mWakeLockAcquired = false;
+            ALOGD_IF(DEBUG_CONNECTIONS, "released wakelock %s", WAKE_LOCK_NAME);
+        }
     } while (count >= 0 || Thread::exitPending());
 
     ALOGW("Exiting SensorService::threadLoop => aborting...");
@@ -429,9 +437,8 @@
     return false;
 }
 
-void SensorService::recordLastValue(
+void SensorService::recordLastValueLocked(
         const sensors_event_t* buffer, size_t count) {
-    Mutex::Autolock _l(mLock);
     const sensors_event_t* last = NULL;
     for (size_t i = 0; i < count; i++) {
         const sensors_event_t* event = &buffer[i];
@@ -459,20 +466,6 @@
     qsort(buffer, count, sizeof(sensors_event_t), compar::cmp);
 }
 
-SortedVector< wp<SensorService::SensorEventConnection> >
-SensorService::getActiveConnections() const
-{
-    Mutex::Autolock _l(mLock);
-    return mActiveConnections;
-}
-
-DefaultKeyedVector<int, SensorInterface*>
-SensorService::getActiveVirtualSensors() const
-{
-    Mutex::Autolock _l(mLock);
-    return mActiveVirtualSensors;
-}
-
 String8 SensorService::getSensorName(int handle) const {
     size_t count = mUserSensorList.size();
     for (size_t i=0 ; i<count ; i++) {
@@ -490,6 +483,11 @@
     return sensor->isVirtual();
 }
 
+bool SensorService::isWakeUpSensorEvent(const sensors_event_t& event) const {
+    SensorInterface* sensor = mSensorMap.valueFor(event.sensor);
+    return sensor->getSensor().isWakeUpSensor();
+}
+
 Vector<Sensor> SensorService::getSensorList()
 {
     char value[PROPERTY_VALUE_MAX];
@@ -554,6 +552,9 @@
     }
     mActiveConnections.remove(connection);
     BatteryService::cleanup(c->getUid());
+    if (c->needsWakeLock()) {
+        checkWakeLockStateLocked();
+    }
 }
 
 Sensor SensorService::getSensorFromHandle(int handle) const {
@@ -585,15 +586,24 @@
         }
     } else {
         if (rec->addConnection(connection)) {
-            // this sensor is already activated, but we are adding a
-            // connection that uses it. Immediately send down the last
-            // known value of the requested sensor if it's not a
+            // this sensor is already activated, but we are adding a connection that uses it.
+            // Immediately send down the last known value of the requested sensor if it's not a
             // "continuous" sensor.
             if (sensor->getSensor().getMinDelay() == 0) {
-                sensors_event_t scratch;
+                // NOTE: The wake_up flag of this event may get set to
+                // WAKE_UP_SENSOR_EVENT_NEEDS_ACK if this is a wake_up event.
                 sensors_event_t& event(mLastEventSeen.editValueFor(handle));
                 if (event.version == sizeof(sensors_event_t)) {
-                    connection->sendEvents(&event, 1);
+                    if (isWakeUpSensorEvent(event) && !mWakeLockAcquired) {
+                        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
+                        mWakeLockAcquired = true;
+                        ALOGD_IF(DEBUG_CONNECTIONS, "acquired wakelock for on_change sensor %s",
+                                                        WAKE_LOCK_NAME);
+                    }
+                    connection->sendEvents(&event, 1, NULL);
+                    if (!connection->needsWakeLock() && mWakeLockAcquired) {
+                        checkWakeLockStateLocked();
+                    }
                 }
             }
         }
@@ -751,6 +761,31 @@
     }
 }
 
+void SensorService::checkWakeLockState() {
+    Mutex::Autolock _l(mLock);
+    checkWakeLockStateLocked();
+}
+
+void SensorService::checkWakeLockStateLocked() {
+    if (!mWakeLockAcquired) {
+        return;
+    }
+    bool releaseLock = true;
+    for (size_t i=0 ; i<mActiveConnections.size() ; i++) {
+        sp<SensorEventConnection> connection(mActiveConnections[i].promote());
+        if (connection != 0) {
+            if (connection->needsWakeLock()) {
+                releaseLock = false;
+                break;
+            }
+        }
+    }
+    if (releaseLock) {
+        ALOGD_IF(DEBUG_CONNECTIONS, "releasing wakelock %s", WAKE_LOCK_NAME);
+        release_wake_lock(WAKE_LOCK_NAME);
+        mWakeLockAcquired = false;
+    }
+}
 // ---------------------------------------------------------------------------
 
 SensorService::SensorRecord::SensorRecord(
@@ -783,7 +818,7 @@
 
 SensorService::SensorEventConnection::SensorEventConnection(
         const sp<SensorService>& service, uid_t uid)
-    : mService(service), mUid(uid)
+    : mService(service), mUid(uid), mWakeLockRefCount(0)
 {
     const SensorDevice& device(SensorDevice::getInstance());
     if (device.getHalDeviceVersion() >= SENSORS_DEVICE_API_VERSION_1_1) {
@@ -804,8 +839,14 @@
 {
 }
 
+bool SensorService::SensorEventConnection::needsWakeLock() {
+    Mutex::Autolock _l(mConnectionLock);
+    return mWakeLockRefCount > 0;
+}
+
 void SensorService::SensorEventConnection::dump(String8& result) {
     Mutex::Autolock _l(mConnectionLock);
+    result.appendFormat("%d WakeLockRefCount\n", mWakeLockRefCount);
     for (size_t i = 0; i < mSensorInfo.size(); ++i) {
         const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
         result.appendFormat("\t %s | status: %s | pending flush events %d | uid %d\n",
@@ -863,9 +904,8 @@
 {
     // filter out events not for this connection
     size_t count = 0;
-
+    Mutex::Autolock _l(mConnectionLock);
     if (scratch) {
-        Mutex::Autolock _l(mConnectionLock);
         size_t i=0;
         while (i<numEvents) {
             int32_t curr = buffer[i].sensor;
@@ -905,7 +945,6 @@
         ASensorEvent flushCompleteEvent;
         flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
         flushCompleteEvent.sensor = 0;
-        Mutex::Autolock _l(mConnectionLock);
         // Loop through all the sensors for this connection and check if there are any pending
         // flush complete events to be sent.
         for (size_t i = 0; i < mSensorInfo.size(); ++i) {
@@ -930,6 +969,7 @@
         return status_t(NO_ERROR);
     }
 
+    int numWakeUpSensorEvents = countWakeUpSensorEventsLocked(scratch, count);
     // NOTE: ASensorEvent and sensors_event_t are the same type
     ssize_t size = SensorEventQueue::write(mChannel,
             reinterpret_cast<ASensorEvent const*>(scratch), count);
@@ -937,11 +977,10 @@
         // the destination doesn't accept events anymore, it's probably
         // full. For now, we just drop the events on the floor.
         // ALOGW("dropping %d events on the floor", count);
-        Mutex::Autolock _l(mConnectionLock);
         countFlushCompleteEventsLocked(scratch, count);
+        mWakeLockRefCount -= numWakeUpSensorEvents;
         return size;
     }
-
     return size < 0 ? status_t(size) : status_t(NO_ERROR);
 }
 
@@ -961,6 +1000,18 @@
     return;
 }
 
+int SensorService::SensorEventConnection::countWakeUpSensorEventsLocked(
+                       sensors_event_t* scratch, const int count) {
+    for (int i = 0; i < count; ++i) {
+        if (mService->isWakeUpSensorEvent(scratch[i])) {
+            scratch[i].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
+            ++mWakeLockRefCount;
+            return 1;
+        }
+    }
+    return 0;
+}
+
 sp<BitTube> SensorService::SensorEventConnection::getSensorChannel() const
 {
     return mChannel;
@@ -1010,6 +1061,17 @@
     return err;
 }
 
+void SensorService::SensorEventConnection::decreaseWakeLockRefCount() {
+    {
+        Mutex::Autolock _l(mConnectionLock);
+        --mWakeLockRefCount;
+    }
+    // Release the lock before calling checkWakeLockState which also needs the same connectionLock.
+    if (mWakeLockRefCount == 0) {
+        mService->checkWakeLockState();
+    }
+}
+
 // ---------------------------------------------------------------------------
 }; // namespace android
 
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
index e88ffc8..5fd56b8 100644
--- a/services/sensorservice/SensorService.h
+++ b/services/sensorservice/SensorService.h
@@ -41,6 +41,7 @@
 // Max size is 1 MB which is enough to accept a batch of about 10k events.
 #define MAX_SOCKET_BUFFER_SIZE_BATCHED 1024 * 1024
 #define SOCKET_BUFFER_SIZE_NON_BATCHED 4 * 1024
+#define WAKE_UP_SENSOR_EVENT_NEEDS_ACK (1 << 31)
 
 struct sensors_poll_device_t;
 struct sensors_module_t;
@@ -71,7 +72,6 @@
     virtual sp<ISensorEventConnection> createSensorEventConnection();
     virtual status_t dump(int fd, const Vector<String16>& args);
 
-
     class SensorEventConnection : public BnSensorEventConnection {
         virtual ~SensorEventConnection();
         virtual void onFirstRef();
@@ -80,15 +80,26 @@
                                        nsecs_t maxBatchReportLatencyNs, int reservedFlags);
         virtual status_t setEventRate(int handle, nsecs_t samplingPeriodNs);
         virtual status_t flush();
+        void decreaseWakeLockRefCount();
         // Count the number of flush complete events which are about to be dropped in the buffer.
         // Increment mPendingFlushEventsToSend in mSensorInfo. These flush complete events will be
         // sent separately before the next batch of events.
         void countFlushCompleteEventsLocked(sensors_event_t* scratch, int numEventsDropped);
 
+        // Check if there are any wake up events in the buffer. If yes, increment the ref count.
+        // Increment it by exactly one unit for each packet sent on the socket. SOCK_SEQPACKET for
+        // the socket ensures that either the entire packet is read or dropped.
+        // Return 1 if mWakeLockRefCount has been incremented, zero if not.
+        int countWakeUpSensorEventsLocked(sensors_event_t* scratch, const int count);
+
         sp<SensorService> const mService;
         sp<BitTube> mChannel;
         uid_t mUid;
         mutable Mutex mConnectionLock;
+        // Number of events from wake up sensors which are still pending and haven't been delivered
+        // to the corresponding application. It is incremented by one unit for each write to the
+        // socket.
+        int mWakeLockRefCount;
 
         struct FlushInfo {
             // The number of flush complete events dropped for this sensor is stored here.
@@ -106,13 +117,14 @@
         SensorEventConnection(const sp<SensorService>& service, uid_t uid);
 
         status_t sendEvents(sensors_event_t const* buffer, size_t count,
-                sensors_event_t* scratch = NULL);
+                sensors_event_t* scratch);
         bool hasSensor(int32_t handle) const;
         bool hasAnySensor() const;
         bool addSensor(int32_t handle);
         bool removeSensor(int32_t handle);
         void setFirstFlushPending(int32_t handle, bool value);
         void dump(String8& result);
+        bool needsWakeLock();
 
         uid_t getUid() const { return mUid; }
     };
@@ -126,13 +138,11 @@
         size_t getNumConnections() const { return mConnections.size(); }
     };
 
-    SortedVector< wp<SensorEventConnection> > getActiveConnections() const;
-    DefaultKeyedVector<int, SensorInterface*> getActiveVirtualSensors() const;
-
     String8 getSensorName(int handle) const;
     bool isVirtualSensor(int handle) const;
     Sensor getSensorFromHandle(int handle) const;
-    void recordLastValue(const sensors_event_t* buffer, size_t count);
+    bool isWakeUpSensor(int type) const;
+    void recordLastValueLocked(const sensors_event_t* buffer, size_t count);
     static void sortEventBuffer(sensors_event_t* buffer, size_t count);
     Sensor registerSensor(SensorInterface* sensor);
     Sensor registerVirtualSensor(SensorInterface* sensor);
@@ -140,10 +150,16 @@
             const sp<SensorEventConnection>& connection, int handle);
     status_t cleanupWithoutDisableLocked(
             const sp<SensorEventConnection>& connection, int handle);
-    void cleanupAutoDisabledSensor(const sp<SensorEventConnection>& connection,
+    void cleanupAutoDisabledSensorLocked(const sp<SensorEventConnection>& connection,
             sensors_event_t const* buffer, const int count);
     static bool canAccessSensor(const Sensor& sensor);
     static bool verifyCanAccessSensor(const Sensor& sensor, const char* operation);
+    // SensorService acquires a partial wakelock for delivering events from wake up sensors. This
+    // method checks whether all the events from these wake up sensors have been delivered to the
+    // corresponding applications, if yes the wakelock is released.
+    void checkWakeLockState();
+    void checkWakeLockStateLocked();
+    bool isWakeUpSensorEvent(const sensors_event_t& event) const;
     // constants
     Vector<Sensor> mSensorList;
     Vector<Sensor> mUserSensorListDebug;
@@ -158,6 +174,7 @@
     DefaultKeyedVector<int, SensorRecord*> mActiveSensors;
     DefaultKeyedVector<int, SensorInterface*> mActiveVirtualSensors;
     SortedVector< wp<SensorEventConnection> > mActiveConnections;
+    bool mWakeLockAcquired;
 
     // The size of this vector is constant, only the items are mutable
     KeyedVector<int32_t, sensors_event_t> mLastEventSeen;
diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
index 85e2ee5..1362ae8 100644
--- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
+++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
@@ -256,7 +256,7 @@
     resetPerFrameState();
 }
 
-void VirtualDisplaySurface::dump(String8& result) const {
+void VirtualDisplaySurface::dump(String8& /* result */) const {
 }
 
 status_t VirtualDisplaySurface::requestBuffer(int pslot,
@@ -285,19 +285,19 @@
     int pslot = mapSource2ProducerSlot(source, *sslot);
     VDS_LOGV("dequeueBuffer(%s): sslot=%d pslot=%d result=%d",
             dbgSourceStr(source), *sslot, pslot, result);
-    uint32_t sourceBit = static_cast<uint32_t>(source) << pslot;
+    uint64_t sourceBit = static_cast<uint64_t>(source) << pslot;
 
-    if ((mProducerSlotSource & (1u << pslot)) != sourceBit) {
+    if ((mProducerSlotSource & (1ULL << pslot)) != sourceBit) {
         // This slot was previously dequeued from the other source; must
         // re-request the buffer.
         result |= BUFFER_NEEDS_REALLOCATION;
-        mProducerSlotSource &= ~(1u << pslot);
+        mProducerSlotSource &= ~(1ULL << pslot);
         mProducerSlotSource |= sourceBit;
     }
 
     if (result & RELEASE_ALL_BUFFERS) {
         for (uint32_t i = 0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
-            if ((mProducerSlotSource & (1u << i)) == sourceBit)
+            if ((mProducerSlotSource & (1ULL << i)) == sourceBit)
                 mProducerBuffers[i].clear();
         }
     }
diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
index 144f871..0ae9804 100644
--- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
+++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
@@ -155,10 +155,10 @@
     // Since we present a single producer interface to the GLES driver, but
     // are internally muxing between the sink and scratch producers, we have
     // to keep track of which source last returned each producer slot from
-    // dequeueBuffer. Each bit in mLastSlotSource corresponds to a producer
+    // dequeueBuffer. Each bit in mProducerSlotSource corresponds to a producer
     // slot. Both mProducerSlotSource and mProducerBuffers are indexed by a
     // "producer slot"; see the mapSlot*() functions.
-    uint32_t mProducerSlotSource;
+    uint64_t mProducerSlotSource;
     sp<GraphicBuffer> mProducerBuffers[BufferQueue::NUM_BUFFER_SLOTS];
 
     // The QueueBufferOutput with the latest info from the sink, and with the