Merge "Add TYPE_MAGNIFICATION_OVERLAY to isTrustedOverlay"
diff --git a/cmds/installd/commands.c b/cmds/installd/commands.c
index 669f403..a86abe1 100644
--- a/cmds/installd/commands.c
+++ b/cmds/installd/commands.c
@@ -685,9 +685,13 @@
     /* Before anything else: is there a .odex file?  If so, we have
      * precompiled the apk and there is nothing to do here.
      */
-    sprintf(out_path, "%s%s", apk_path, ".odex");
-    if (stat(out_path, &dex_stat) == 0) {
-        return 0;
+    strcpy(out_path, apk_path);
+    end = strrchr(out_path, '.');
+    if (end != NULL) {
+        strcpy(end, ".odex");
+        if (stat(out_path, &dex_stat) == 0) {
+            return 0;
+        }
     }
 
     if (create_cache_path(out_path, apk_path)) {
diff --git a/data/etc/android.software.voice_recognizers.xml b/data/etc/android.software.voice_recognizers.xml
new file mode 100644
index 0000000..7e72177
--- /dev/null
+++ b/data/etc/android.software.voice_recognizers.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2014 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.
+-->
+
+<permissions>
+    <feature name="android.software.voice_recognizers" />
+</permissions>
diff --git a/data/etc/handheld_core_hardware.xml b/data/etc/handheld_core_hardware.xml
index 0bdadef..f0c9e67 100644
--- a/data/etc/handheld_core_hardware.xml
+++ b/data/etc/handheld_core_hardware.xml
@@ -36,6 +36,7 @@
 
     <!-- basic system services -->
     <feature name="android.software.app_widgets" />
+    <feature name="android.software.voice_recognizers" />
     <feature name="android.software.backup" />
     <feature name="android.software.home_screen" />
     <feature name="android.software.input_methods" />
diff --git a/data/etc/tablet_core_hardware.xml b/data/etc/tablet_core_hardware.xml
index 4f7465f..9d217ea 100644
--- a/data/etc/tablet_core_hardware.xml
+++ b/data/etc/tablet_core_hardware.xml
@@ -37,6 +37,7 @@
 
     <!-- basic system services -->
     <feature name="android.software.app_widgets" />
+    <feature name="android.software.voice_recognizers" />
     <feature name="android.software.backup" />
     <feature name="android.software.home_screen" />
     <feature name="android.software.input_methods" />
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/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/input/Input.h b/include/input/Input.h
index 077a03b..a4fa317 100644
--- a/include/input/Input.h
+++ b/include/input/Input.h
@@ -71,7 +71,7 @@
      * Constants for LEDs. Hidden from the API since we don't actually expose a way to interact
      * with LEDs to developers
      *
-     * NOTE: If you add LEDs here, you must also add them to KeycodeLabels.h
+     * NOTE: If you add LEDs here, you must also add them to InputEventLabels.h
      */
 
     ALED_NUM_LOCK = 0x00,
@@ -146,18 +146,12 @@
  */
 enum {
     /* These flags originate in RawEvents and are generally set in the key map.
-     * NOTE: If you edit these flags, also edit labels in KeycodeLabels.h. */
+     * NOTE: If you want a flag to be able to set in a keylayout file, then you must add it to
+     * InputEventLabels.h as well. */
 
     POLICY_FLAG_WAKE = 0x00000001,
-    POLICY_FLAG_WAKE_DROPPED = 0x00000002,
-    POLICY_FLAG_SHIFT = 0x00000004,
-    POLICY_FLAG_CAPS_LOCK = 0x00000008,
-    POLICY_FLAG_ALT = 0x00000010,
-    POLICY_FLAG_ALT_GR = 0x00000020,
-    POLICY_FLAG_MENU = 0x00000040,
-    POLICY_FLAG_LAUNCHER = 0x00000080,
-    POLICY_FLAG_VIRTUAL = 0x00000100,
-    POLICY_FLAG_FUNCTION = 0x00000200,
+    POLICY_FLAG_VIRTUAL = 0x00000002,
+    POLICY_FLAG_FUNCTION = 0x00000004,
 
     POLICY_FLAG_RAW_MASK = 0x0000ffff,
 
@@ -312,13 +306,8 @@
 
     inline nsecs_t getEventTime() const { return mEventTime; }
 
-    // Return true if this event may have a default action implementation.
-    static bool hasDefaultAction(int32_t keyCode);
-    bool hasDefaultAction() const;
-
-    // Return true if this event represents a system key.
-    static bool isSystemKey(int32_t keyCode);
-    bool isSystemKey() const;
+    static const char* getLabel(int32_t keyCode);
+    static int32_t getKeyCodeFromLabel(const char* label);
     
     void initialize(
             int32_t deviceId,
@@ -578,6 +567,9 @@
             return mSamplePointerCoords.array();
     }
 
+    static const char* getLabel(int32_t axis);
+    static int32_t getAxisFromLabel(const char* label);
+
 protected:
     int32_t mAction;
     int32_t mFlags;
diff --git a/include/input/InputEventLabels.h b/include/input/InputEventLabels.h
new file mode 100644
index 0000000..c6eef9b
--- /dev/null
+++ b/include/input/InputEventLabels.h
@@ -0,0 +1,396 @@
+/*
+ * Copyright (C) 2008 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBINPUT_INPUT_EVENT_LABELS_H
+#define _LIBINPUT_INPUT_EVENT_LABELS_H
+
+#include <input/Input.h>
+#include <android/keycodes.h>
+
+#define DEFINE_KEYCODE(key) { #key, AKEYCODE_##key }
+#define DEFINE_AXIS(axis) { #axis, AMOTION_EVENT_AXIS_##axis }
+#define DEFINE_LED(led) { #led, ALED_##led }
+#define DEFINE_FLAG(flag) { #flag, POLICY_FLAG_##flag }
+
+namespace android {
+
+template<typename T, size_t N>
+size_t size(T (&)[N]) { return N; }
+
+struct InputEventLabel {
+    const char *literal;
+    int value;
+};
+
+
+static const InputEventLabel KEYCODES[] = {
+    // NOTE: If you add a new keycode here you must also add it to several other files.
+    //       Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
+    DEFINE_KEYCODE(UNKNOWN),
+    DEFINE_KEYCODE(SOFT_LEFT),
+    DEFINE_KEYCODE(SOFT_RIGHT),
+    DEFINE_KEYCODE(HOME),
+    DEFINE_KEYCODE(BACK),
+    DEFINE_KEYCODE(CALL),
+    DEFINE_KEYCODE(ENDCALL),
+    DEFINE_KEYCODE(0),
+    DEFINE_KEYCODE(1),
+    DEFINE_KEYCODE(2),
+    DEFINE_KEYCODE(3),
+    DEFINE_KEYCODE(4),
+    DEFINE_KEYCODE(5),
+    DEFINE_KEYCODE(6),
+    DEFINE_KEYCODE(7),
+    DEFINE_KEYCODE(8),
+    DEFINE_KEYCODE(9),
+    DEFINE_KEYCODE(STAR),
+    DEFINE_KEYCODE(POUND),
+    DEFINE_KEYCODE(DPAD_UP),
+    DEFINE_KEYCODE(DPAD_DOWN),
+    DEFINE_KEYCODE(DPAD_LEFT),
+    DEFINE_KEYCODE(DPAD_RIGHT),
+    DEFINE_KEYCODE(DPAD_CENTER),
+    DEFINE_KEYCODE(VOLUME_UP),
+    DEFINE_KEYCODE(VOLUME_DOWN),
+    DEFINE_KEYCODE(POWER),
+    DEFINE_KEYCODE(CAMERA),
+    DEFINE_KEYCODE(CLEAR),
+    DEFINE_KEYCODE(A),
+    DEFINE_KEYCODE(B),
+    DEFINE_KEYCODE(C),
+    DEFINE_KEYCODE(D),
+    DEFINE_KEYCODE(E),
+    DEFINE_KEYCODE(F),
+    DEFINE_KEYCODE(G),
+    DEFINE_KEYCODE(H),
+    DEFINE_KEYCODE(I),
+    DEFINE_KEYCODE(J),
+    DEFINE_KEYCODE(K),
+    DEFINE_KEYCODE(L),
+    DEFINE_KEYCODE(M),
+    DEFINE_KEYCODE(N),
+    DEFINE_KEYCODE(O),
+    DEFINE_KEYCODE(P),
+    DEFINE_KEYCODE(Q),
+    DEFINE_KEYCODE(R),
+    DEFINE_KEYCODE(S),
+    DEFINE_KEYCODE(T),
+    DEFINE_KEYCODE(U),
+    DEFINE_KEYCODE(V),
+    DEFINE_KEYCODE(W),
+    DEFINE_KEYCODE(X),
+    DEFINE_KEYCODE(Y),
+    DEFINE_KEYCODE(Z),
+    DEFINE_KEYCODE(COMMA),
+    DEFINE_KEYCODE(PERIOD),
+    DEFINE_KEYCODE(ALT_LEFT),
+    DEFINE_KEYCODE(ALT_RIGHT),
+    DEFINE_KEYCODE(SHIFT_LEFT),
+    DEFINE_KEYCODE(SHIFT_RIGHT),
+    DEFINE_KEYCODE(TAB),
+    DEFINE_KEYCODE(SPACE),
+    DEFINE_KEYCODE(SYM),
+    DEFINE_KEYCODE(EXPLORER),
+    DEFINE_KEYCODE(ENVELOPE),
+    DEFINE_KEYCODE(ENTER),
+    DEFINE_KEYCODE(DEL),
+    DEFINE_KEYCODE(GRAVE),
+    DEFINE_KEYCODE(MINUS),
+    DEFINE_KEYCODE(EQUALS),
+    DEFINE_KEYCODE(LEFT_BRACKET),
+    DEFINE_KEYCODE(RIGHT_BRACKET),
+    DEFINE_KEYCODE(BACKSLASH),
+    DEFINE_KEYCODE(SEMICOLON),
+    DEFINE_KEYCODE(APOSTROPHE),
+    DEFINE_KEYCODE(SLASH),
+    DEFINE_KEYCODE(AT),
+    DEFINE_KEYCODE(NUM),
+    DEFINE_KEYCODE(HEADSETHOOK),
+    DEFINE_KEYCODE(FOCUS),   // *Camera* focus
+    DEFINE_KEYCODE(PLUS),
+    DEFINE_KEYCODE(MENU),
+    DEFINE_KEYCODE(NOTIFICATION),
+    DEFINE_KEYCODE(SEARCH),
+    DEFINE_KEYCODE(MEDIA_PLAY_PAUSE),
+    DEFINE_KEYCODE(MEDIA_STOP),
+    DEFINE_KEYCODE(MEDIA_NEXT),
+    DEFINE_KEYCODE(MEDIA_PREVIOUS),
+    DEFINE_KEYCODE(MEDIA_REWIND),
+    DEFINE_KEYCODE(MEDIA_FAST_FORWARD),
+    DEFINE_KEYCODE(MUTE),
+    DEFINE_KEYCODE(PAGE_UP),
+    DEFINE_KEYCODE(PAGE_DOWN),
+    DEFINE_KEYCODE(PICTSYMBOLS),
+    DEFINE_KEYCODE(SWITCH_CHARSET),
+    DEFINE_KEYCODE(BUTTON_A),
+    DEFINE_KEYCODE(BUTTON_B),
+    DEFINE_KEYCODE(BUTTON_C),
+    DEFINE_KEYCODE(BUTTON_X),
+    DEFINE_KEYCODE(BUTTON_Y),
+    DEFINE_KEYCODE(BUTTON_Z),
+    DEFINE_KEYCODE(BUTTON_L1),
+    DEFINE_KEYCODE(BUTTON_R1),
+    DEFINE_KEYCODE(BUTTON_L2),
+    DEFINE_KEYCODE(BUTTON_R2),
+    DEFINE_KEYCODE(BUTTON_THUMBL),
+    DEFINE_KEYCODE(BUTTON_THUMBR),
+    DEFINE_KEYCODE(BUTTON_START),
+    DEFINE_KEYCODE(BUTTON_SELECT),
+    DEFINE_KEYCODE(BUTTON_MODE),
+    DEFINE_KEYCODE(ESCAPE),
+    DEFINE_KEYCODE(FORWARD_DEL),
+    DEFINE_KEYCODE(CTRL_LEFT),
+    DEFINE_KEYCODE(CTRL_RIGHT),
+    DEFINE_KEYCODE(CAPS_LOCK),
+    DEFINE_KEYCODE(SCROLL_LOCK),
+    DEFINE_KEYCODE(META_LEFT),
+    DEFINE_KEYCODE(META_RIGHT),
+    DEFINE_KEYCODE(FUNCTION),
+    DEFINE_KEYCODE(SYSRQ),
+    DEFINE_KEYCODE(BREAK),
+    DEFINE_KEYCODE(MOVE_HOME),
+    DEFINE_KEYCODE(MOVE_END),
+    DEFINE_KEYCODE(INSERT),
+    DEFINE_KEYCODE(FORWARD),
+    DEFINE_KEYCODE(MEDIA_PLAY),
+    DEFINE_KEYCODE(MEDIA_PAUSE),
+    DEFINE_KEYCODE(MEDIA_CLOSE),
+    DEFINE_KEYCODE(MEDIA_EJECT),
+    DEFINE_KEYCODE(MEDIA_RECORD),
+    DEFINE_KEYCODE(F1),
+    DEFINE_KEYCODE(F2),
+    DEFINE_KEYCODE(F3),
+    DEFINE_KEYCODE(F4),
+    DEFINE_KEYCODE(F5),
+    DEFINE_KEYCODE(F6),
+    DEFINE_KEYCODE(F7),
+    DEFINE_KEYCODE(F8),
+    DEFINE_KEYCODE(F9),
+    DEFINE_KEYCODE(F10),
+    DEFINE_KEYCODE(F11),
+    DEFINE_KEYCODE(F12),
+    DEFINE_KEYCODE(NUM_LOCK),
+    DEFINE_KEYCODE(NUMPAD_0),
+    DEFINE_KEYCODE(NUMPAD_1),
+    DEFINE_KEYCODE(NUMPAD_2),
+    DEFINE_KEYCODE(NUMPAD_3),
+    DEFINE_KEYCODE(NUMPAD_4),
+    DEFINE_KEYCODE(NUMPAD_5),
+    DEFINE_KEYCODE(NUMPAD_6),
+    DEFINE_KEYCODE(NUMPAD_7),
+    DEFINE_KEYCODE(NUMPAD_8),
+    DEFINE_KEYCODE(NUMPAD_9),
+    DEFINE_KEYCODE(NUMPAD_DIVIDE),
+    DEFINE_KEYCODE(NUMPAD_MULTIPLY),
+    DEFINE_KEYCODE(NUMPAD_SUBTRACT),
+    DEFINE_KEYCODE(NUMPAD_ADD),
+    DEFINE_KEYCODE(NUMPAD_DOT),
+    DEFINE_KEYCODE(NUMPAD_COMMA),
+    DEFINE_KEYCODE(NUMPAD_ENTER),
+    DEFINE_KEYCODE(NUMPAD_EQUALS),
+    DEFINE_KEYCODE(NUMPAD_LEFT_PAREN),
+    DEFINE_KEYCODE(NUMPAD_RIGHT_PAREN),
+    DEFINE_KEYCODE(VOLUME_MUTE),
+    DEFINE_KEYCODE(INFO),
+    DEFINE_KEYCODE(CHANNEL_UP),
+    DEFINE_KEYCODE(CHANNEL_DOWN),
+    DEFINE_KEYCODE(ZOOM_IN),
+    DEFINE_KEYCODE(ZOOM_OUT),
+    DEFINE_KEYCODE(TV),
+    DEFINE_KEYCODE(WINDOW),
+    DEFINE_KEYCODE(GUIDE),
+    DEFINE_KEYCODE(DVR),
+    DEFINE_KEYCODE(BOOKMARK),
+    DEFINE_KEYCODE(CAPTIONS),
+    DEFINE_KEYCODE(SETTINGS),
+    DEFINE_KEYCODE(TV_POWER),
+    DEFINE_KEYCODE(TV_INPUT),
+    DEFINE_KEYCODE(STB_POWER),
+    DEFINE_KEYCODE(STB_INPUT),
+    DEFINE_KEYCODE(AVR_POWER),
+    DEFINE_KEYCODE(AVR_INPUT),
+    DEFINE_KEYCODE(PROG_RED),
+    DEFINE_KEYCODE(PROG_GREEN),
+    DEFINE_KEYCODE(PROG_YELLOW),
+    DEFINE_KEYCODE(PROG_BLUE),
+    DEFINE_KEYCODE(APP_SWITCH),
+    DEFINE_KEYCODE(BUTTON_1),
+    DEFINE_KEYCODE(BUTTON_2),
+    DEFINE_KEYCODE(BUTTON_3),
+    DEFINE_KEYCODE(BUTTON_4),
+    DEFINE_KEYCODE(BUTTON_5),
+    DEFINE_KEYCODE(BUTTON_6),
+    DEFINE_KEYCODE(BUTTON_7),
+    DEFINE_KEYCODE(BUTTON_8),
+    DEFINE_KEYCODE(BUTTON_9),
+    DEFINE_KEYCODE(BUTTON_10),
+    DEFINE_KEYCODE(BUTTON_11),
+    DEFINE_KEYCODE(BUTTON_12),
+    DEFINE_KEYCODE(BUTTON_13),
+    DEFINE_KEYCODE(BUTTON_14),
+    DEFINE_KEYCODE(BUTTON_15),
+    DEFINE_KEYCODE(BUTTON_16),
+    DEFINE_KEYCODE(LANGUAGE_SWITCH),
+    DEFINE_KEYCODE(MANNER_MODE),
+    DEFINE_KEYCODE(3D_MODE),
+    DEFINE_KEYCODE(CONTACTS),
+    DEFINE_KEYCODE(CALENDAR),
+    DEFINE_KEYCODE(MUSIC),
+    DEFINE_KEYCODE(CALCULATOR),
+    DEFINE_KEYCODE(ZENKAKU_HANKAKU),
+    DEFINE_KEYCODE(EISU),
+    DEFINE_KEYCODE(MUHENKAN),
+    DEFINE_KEYCODE(HENKAN),
+    DEFINE_KEYCODE(KATAKANA_HIRAGANA),
+    DEFINE_KEYCODE(YEN),
+    DEFINE_KEYCODE(RO),
+    DEFINE_KEYCODE(KANA),
+    DEFINE_KEYCODE(ASSIST),
+    DEFINE_KEYCODE(BRIGHTNESS_DOWN),
+    DEFINE_KEYCODE(BRIGHTNESS_UP),
+    DEFINE_KEYCODE(MEDIA_AUDIO_TRACK),
+    DEFINE_KEYCODE(SLEEP),
+    DEFINE_KEYCODE(WAKEUP),
+
+    { NULL, 0 }
+};
+
+static const InputEventLabel AXES[] = {
+    DEFINE_AXIS(X),
+    DEFINE_AXIS(Y),
+    DEFINE_AXIS(PRESSURE),
+    DEFINE_AXIS(SIZE),
+    DEFINE_AXIS(TOUCH_MAJOR),
+    DEFINE_AXIS(TOUCH_MINOR),
+    DEFINE_AXIS(TOOL_MAJOR),
+    DEFINE_AXIS(TOOL_MINOR),
+    DEFINE_AXIS(ORIENTATION),
+    DEFINE_AXIS(VSCROLL),
+    DEFINE_AXIS(HSCROLL),
+    DEFINE_AXIS(Z),
+    DEFINE_AXIS(RX),
+    DEFINE_AXIS(RY),
+    DEFINE_AXIS(RZ),
+    DEFINE_AXIS(HAT_X),
+    DEFINE_AXIS(HAT_Y),
+    DEFINE_AXIS(LTRIGGER),
+    DEFINE_AXIS(RTRIGGER),
+    DEFINE_AXIS(THROTTLE),
+    DEFINE_AXIS(RUDDER),
+    DEFINE_AXIS(WHEEL),
+    DEFINE_AXIS(GAS),
+    DEFINE_AXIS(BRAKE),
+    DEFINE_AXIS(DISTANCE),
+    DEFINE_AXIS(TILT),
+    DEFINE_AXIS(GENERIC_1),
+    DEFINE_AXIS(GENERIC_2),
+    DEFINE_AXIS(GENERIC_3),
+    DEFINE_AXIS(GENERIC_4),
+    DEFINE_AXIS(GENERIC_5),
+    DEFINE_AXIS(GENERIC_6),
+    DEFINE_AXIS(GENERIC_7),
+    DEFINE_AXIS(GENERIC_8),
+    DEFINE_AXIS(GENERIC_9),
+    DEFINE_AXIS(GENERIC_10),
+    DEFINE_AXIS(GENERIC_11),
+    DEFINE_AXIS(GENERIC_12),
+    DEFINE_AXIS(GENERIC_13),
+    DEFINE_AXIS(GENERIC_14),
+    DEFINE_AXIS(GENERIC_15),
+    DEFINE_AXIS(GENERIC_16),
+
+    // NOTE: If you add a new axis here you must also add it to several other files.
+    //       Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list.
+    { NULL, 0 }
+};
+
+static const InputEventLabel LEDS[] = {
+    DEFINE_LED(NUM_LOCK),
+    DEFINE_LED(CAPS_LOCK),
+    DEFINE_LED(SCROLL_LOCK),
+    DEFINE_LED(COMPOSE),
+    DEFINE_LED(KANA),
+    DEFINE_LED(SLEEP),
+    DEFINE_LED(SUSPEND),
+    DEFINE_LED(MUTE),
+    DEFINE_LED(MISC),
+    DEFINE_LED(MAIL),
+    DEFINE_LED(CHARGING),
+    DEFINE_LED(CONTROLLER_1),
+    DEFINE_LED(CONTROLLER_2),
+    DEFINE_LED(CONTROLLER_3),
+    DEFINE_LED(CONTROLLER_4),
+
+    // NOTE: If you add new LEDs here, you must also add them to Input.h
+    { NULL, 0 }
+};
+
+static const InputEventLabel FLAGS[] = {
+    DEFINE_FLAG(FUNCTION),
+
+    { NULL, 0 }
+};
+
+static int lookupValueByLabel(const char* literal, const InputEventLabel *list) {
+    while (list->literal) {
+        if (strcmp(literal, list->literal) == 0) {
+            return list->value;
+        }
+        list++;
+    }
+    return list->value;
+}
+
+static const char* lookupLabelByValue(int value, const InputEventLabel* list) {
+    while (list->literal) {
+        if (list->value == value) {
+            return list->literal;
+        }
+        list++;
+    }
+    return NULL;
+}
+
+static int32_t getKeyCodeByLabel(const char* label) {
+    return int32_t(lookupValueByLabel(label, KEYCODES));
+}
+
+static const char* getLabelByKeyCode(int32_t keyCode) {
+    if (keyCode >= 0 && keyCode < size(KEYCODES)) {
+        return KEYCODES[keyCode].literal;
+    }
+    return NULL;
+}
+
+static uint32_t getKeyFlagByLabel(const char* label) {
+    return uint32_t(lookupValueByLabel(label, FLAGS));
+}
+
+static int32_t getAxisByLabel(const char* label) {
+    return int32_t(lookupValueByLabel(label, AXES));
+}
+
+static const char* getAxisLabel(int32_t axisId) {
+    return lookupLabelByValue(axisId, AXES);
+}
+
+static int32_t getLedByLabel(const char* label) {
+    return int32_t(lookupValueByLabel(label, LEDS));
+}
+
+
+} // namespace android
+#endif // _LIBINPUT_INPUT_EVENT_LABELS_H
diff --git a/include/input/Keyboard.h b/include/input/Keyboard.h
index 25b2f07..519bb22 100644
--- a/include/input/Keyboard.h
+++ b/include/input/Keyboard.h
@@ -19,6 +19,7 @@
 
 #include <input/Input.h>
 #include <input/InputDevice.h>
+#include <input/InputEventLabels.h>
 #include <utils/Errors.h>
 #include <utils/String8.h>
 #include <utils/PropertyMap.h>
@@ -82,36 +83,6 @@
         const PropertyMap* deviceConfiguration, const KeyMap* keyMap);
 
 /**
- * Gets a key code by its short form label, eg. "HOME".
- * Returns 0 if unknown.
- */
-extern int32_t getKeyCodeByLabel(const char* label);
-
-/**
- * Gets a key flag by its short form label, eg. "WAKE".
- * Returns 0 if unknown.
- */
-extern uint32_t getKeyFlagByLabel(const char* label);
-
-/**
- * Gets an axis by its short form label, eg. "X".
- * Returns -1 if unknown.
- */
-extern int32_t getAxisByLabel(const char* label);
-
-/**
- * Gets an axis label by its id.
- * Returns NULL if unknown.
- */
-extern const char* getAxisLabel(int32_t axisId);
-
-/**
- * Gets an LED by its short form label, eg. "CAPS_LOCK".
- * Returns -1 if unknown.
- */
-extern int32_t getLedByLabel(const char* label);
-
-/**
  * Updates a meta state field when a key is pressed or released.
  */
 extern int32_t updateMetaState(int32_t keyCode, bool down, int32_t oldMetaState);
diff --git a/include/input/KeycodeLabels.h b/include/input/KeycodeLabels.h
deleted file mode 100644
index a8d63da..0000000
--- a/include/input/KeycodeLabels.h
+++ /dev/null
@@ -1,346 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _LIBINPUT_KEYCODE_LABELS_H
-#define _LIBINPUT_KEYCODE_LABELS_H
-
-#include <android/keycodes.h>
-
-struct KeycodeLabel {
-    const char *literal;
-    int value;
-};
-
-static const KeycodeLabel KEYCODES[] = {
-    { "SOFT_LEFT", 1 },
-    { "SOFT_RIGHT", 2 },
-    { "HOME", 3 },
-    { "BACK", 4 },
-    { "CALL", 5 },
-    { "ENDCALL", 6 },
-    { "0", 7 },
-    { "1", 8 },
-    { "2", 9 },
-    { "3", 10 },
-    { "4", 11 },
-    { "5", 12 },
-    { "6", 13 },
-    { "7", 14 },
-    { "8", 15 },
-    { "9", 16 },
-    { "STAR", 17 },
-    { "POUND", 18 },
-    { "DPAD_UP", 19 },
-    { "DPAD_DOWN", 20 },
-    { "DPAD_LEFT", 21 },
-    { "DPAD_RIGHT", 22 },
-    { "DPAD_CENTER", 23 },
-    { "VOLUME_UP", 24 },
-    { "VOLUME_DOWN", 25 },
-    { "POWER", 26 },
-    { "CAMERA", 27 },
-    { "CLEAR", 28 },
-    { "A", 29 },
-    { "B", 30 },
-    { "C", 31 },
-    { "D", 32 },
-    { "E", 33 },
-    { "F", 34 },
-    { "G", 35 },
-    { "H", 36 },
-    { "I", 37 },
-    { "J", 38 },
-    { "K", 39 },
-    { "L", 40 },
-    { "M", 41 },
-    { "N", 42 },
-    { "O", 43 },
-    { "P", 44 },
-    { "Q", 45 },
-    { "R", 46 },
-    { "S", 47 },
-    { "T", 48 },
-    { "U", 49 },
-    { "V", 50 },
-    { "W", 51 },
-    { "X", 52 },
-    { "Y", 53 },
-    { "Z", 54 },
-    { "COMMA", 55 },
-    { "PERIOD", 56 },
-    { "ALT_LEFT", 57 },
-    { "ALT_RIGHT", 58 },
-    { "SHIFT_LEFT", 59 },
-    { "SHIFT_RIGHT", 60 },
-    { "TAB", 61 },
-    { "SPACE", 62 },
-    { "SYM", 63 },
-    { "EXPLORER", 64 },
-    { "ENVELOPE", 65 },
-    { "ENTER", 66 },
-    { "DEL", 67 },
-    { "GRAVE", 68 },
-    { "MINUS", 69 },
-    { "EQUALS", 70 },
-    { "LEFT_BRACKET", 71 },
-    { "RIGHT_BRACKET", 72 },
-    { "BACKSLASH", 73 },
-    { "SEMICOLON", 74 },
-    { "APOSTROPHE", 75 },
-    { "SLASH", 76 },
-    { "AT", 77 },
-    { "NUM", 78 },
-    { "HEADSETHOOK", 79 },
-    { "FOCUS", 80 },
-    { "PLUS", 81 },
-    { "MENU", 82 },
-    { "NOTIFICATION", 83 },
-    { "SEARCH", 84 },
-    { "MEDIA_PLAY_PAUSE", 85 },
-    { "MEDIA_STOP", 86 },
-    { "MEDIA_NEXT", 87 },
-    { "MEDIA_PREVIOUS", 88 },
-    { "MEDIA_REWIND", 89 },
-    { "MEDIA_FAST_FORWARD", 90 },
-    { "MUTE", 91 },
-    { "PAGE_UP", 92 },
-    { "PAGE_DOWN", 93 },
-    { "PICTSYMBOLS", 94 },
-    { "SWITCH_CHARSET", 95 },
-    { "BUTTON_A", 96 },
-    { "BUTTON_B", 97 },
-    { "BUTTON_C", 98 },
-    { "BUTTON_X", 99 },
-    { "BUTTON_Y", 100 },
-    { "BUTTON_Z", 101 },
-    { "BUTTON_L1", 102 },
-    { "BUTTON_R1", 103 },
-    { "BUTTON_L2", 104 },
-    { "BUTTON_R2", 105 },
-    { "BUTTON_THUMBL", 106 },
-    { "BUTTON_THUMBR", 107 },
-    { "BUTTON_START", 108 },
-    { "BUTTON_SELECT", 109 },
-    { "BUTTON_MODE", 110 },
-    { "ESCAPE", 111 },
-    { "FORWARD_DEL", 112 },
-    { "CTRL_LEFT", 113 },
-    { "CTRL_RIGHT", 114 },
-    { "CAPS_LOCK", 115 },
-    { "SCROLL_LOCK", 116 },
-    { "META_LEFT", 117 },
-    { "META_RIGHT", 118 },
-    { "FUNCTION", 119 },
-    { "SYSRQ", 120 },
-    { "BREAK", 121 },
-    { "MOVE_HOME", 122 },
-    { "MOVE_END", 123 },
-    { "INSERT", 124 },
-    { "FORWARD", 125 },
-    { "MEDIA_PLAY", 126 },
-    { "MEDIA_PAUSE", 127 },
-    { "MEDIA_CLOSE", 128 },
-    { "MEDIA_EJECT", 129 },
-    { "MEDIA_RECORD", 130 },
-    { "F1", 131 },
-    { "F2", 132 },
-    { "F3", 133 },
-    { "F4", 134 },
-    { "F5", 135 },
-    { "F6", 136 },
-    { "F7", 137 },
-    { "F8", 138 },
-    { "F9", 139 },
-    { "F10", 140 },
-    { "F11", 141 },
-    { "F12", 142 },
-    { "NUM_LOCK", 143 },
-    { "NUMPAD_0", 144 },
-    { "NUMPAD_1", 145 },
-    { "NUMPAD_2", 146 },
-    { "NUMPAD_3", 147 },
-    { "NUMPAD_4", 148 },
-    { "NUMPAD_5", 149 },
-    { "NUMPAD_6", 150 },
-    { "NUMPAD_7", 151 },
-    { "NUMPAD_8", 152 },
-    { "NUMPAD_9", 153 },
-    { "NUMPAD_DIVIDE", 154 },
-    { "NUMPAD_MULTIPLY", 155 },
-    { "NUMPAD_SUBTRACT", 156 },
-    { "NUMPAD_ADD", 157 },
-    { "NUMPAD_DOT", 158 },
-    { "NUMPAD_COMMA", 159 },
-    { "NUMPAD_ENTER", 160 },
-    { "NUMPAD_EQUALS", 161 },
-    { "NUMPAD_LEFT_PAREN", 162 },
-    { "NUMPAD_RIGHT_PAREN", 163 },
-    { "VOLUME_MUTE", 164 },
-    { "INFO", 165 },
-    { "CHANNEL_UP", 166 },
-    { "CHANNEL_DOWN", 167 },
-    { "ZOOM_IN", 168 },
-    { "ZOOM_OUT", 169 },
-    { "TV", 170 },
-    { "WINDOW", 171 },
-    { "GUIDE", 172 },
-    { "DVR", 173 },
-    { "BOOKMARK", 174 },
-    { "CAPTIONS", 175 },
-    { "SETTINGS", 176 },
-    { "TV_POWER", 177 },
-    { "TV_INPUT", 178 },
-    { "STB_POWER", 179 },
-    { "STB_INPUT", 180 },
-    { "AVR_POWER", 181 },
-    { "AVR_INPUT", 182 },
-    { "PROG_RED", 183 },
-    { "PROG_GREEN", 184 },
-    { "PROG_YELLOW", 185 },
-    { "PROG_BLUE", 186 },
-    { "APP_SWITCH", 187 },
-    { "BUTTON_1", 188 },
-    { "BUTTON_2", 189 },
-    { "BUTTON_3", 190 },
-    { "BUTTON_4", 191 },
-    { "BUTTON_5", 192 },
-    { "BUTTON_6", 193 },
-    { "BUTTON_7", 194 },
-    { "BUTTON_8", 195 },
-    { "BUTTON_9", 196 },
-    { "BUTTON_10", 197 },
-    { "BUTTON_11", 198 },
-    { "BUTTON_12", 199 },
-    { "BUTTON_13", 200 },
-    { "BUTTON_14", 201 },
-    { "BUTTON_15", 202 },
-    { "BUTTON_16", 203 },
-    { "LANGUAGE_SWITCH", 204 },
-    { "MANNER_MODE", 205 },
-    { "3D_MODE", 206 },
-    { "CONTACTS", 207 },
-    { "CALENDAR", 208 },
-    { "MUSIC", 209 },
-    { "CALCULATOR", 210 },
-    { "ZENKAKU_HANKAKU", 211 },
-    { "EISU", 212 },
-    { "MUHENKAN", 213 },
-    { "HENKAN", 214 },
-    { "KATAKANA_HIRAGANA", 215 },
-    { "YEN", 216 },
-    { "RO", 217 },
-    { "KANA", 218 },
-    { "ASSIST", 219 },
-    { "BRIGHTNESS_DOWN", 220 },
-    { "BRIGHTNESS_UP", 221 },
-    { "MEDIA_AUDIO_TRACK", 222 },
-    { "SLEEP", 223 },
-    { "WAKEUP", 224 },
-
-    // NOTE: If you add a new keycode here you must also add it to several other files.
-    //       Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
-
-    { NULL, 0 }
-};
-
-// NOTE: If you edit these flags, also edit policy flags in Input.h.
-static const KeycodeLabel FLAGS[] = {
-    { "WAKE", 0x00000001 },
-    { "WAKE_DROPPED", 0x00000002 },
-    { "SHIFT", 0x00000004 },
-    { "CAPS_LOCK", 0x00000008 },
-    { "ALT", 0x00000010 },
-    { "ALT_GR", 0x00000020 },
-    { "MENU", 0x00000040 },
-    { "LAUNCHER", 0x00000080 },
-    { "VIRTUAL", 0x00000100 },
-    { "FUNCTION", 0x00000200 },
-    { NULL, 0 }
-};
-
-static const KeycodeLabel AXES[] = {
-    { "X", 0 },
-    { "Y", 1 },
-    { "PRESSURE", 2 },
-    { "SIZE", 3 },
-    { "TOUCH_MAJOR", 4 },
-    { "TOUCH_MINOR", 5 },
-    { "TOOL_MAJOR", 6 },
-    { "TOOL_MINOR", 7 },
-    { "ORIENTATION", 8 },
-    { "VSCROLL", 9 },
-    { "HSCROLL", 10 },
-    { "Z", 11 },
-    { "RX", 12 },
-    { "RY", 13 },
-    { "RZ", 14 },
-    { "HAT_X", 15 },
-    { "HAT_Y", 16 },
-    { "LTRIGGER", 17 },
-    { "RTRIGGER", 18 },
-    { "THROTTLE", 19 },
-    { "RUDDER", 20 },
-    { "WHEEL", 21 },
-    { "GAS", 22 },
-    { "BRAKE", 23 },
-    { "DISTANCE", 24 },
-    { "TILT", 25 },
-    { "GENERIC_1", 32 },
-    { "GENERIC_2", 33 },
-    { "GENERIC_3", 34 },
-    { "GENERIC_4", 35 },
-    { "GENERIC_5", 36 },
-    { "GENERIC_6", 37 },
-    { "GENERIC_7", 38 },
-    { "GENERIC_8", 39 },
-    { "GENERIC_9", 40 },
-    { "GENERIC_10", 41 },
-    { "GENERIC_11", 42 },
-    { "GENERIC_12", 43 },
-    { "GENERIC_13", 44 },
-    { "GENERIC_14", 45 },
-    { "GENERIC_15", 46 },
-    { "GENERIC_16", 47 },
-
-    // NOTE: If you add a new axis here you must also add it to several other files.
-    //       Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list.
-
-    { NULL, -1 }
-};
-
-static const KeycodeLabel LEDS[] = {
-    { "NUM_LOCK", 0x00 },
-    { "CAPS_LOCK", 0x01 },
-    { "SCROLL_LOCK", 0x02 },
-    { "COMPOSE", 0x03 },
-    { "KANA", 0x04 },
-    { "SLEEP", 0x05 },
-    { "SUSPEND", 0x06 },
-    { "MUTE", 0x07 },
-    { "MISC", 0x08 },
-    { "MAIL", 0x09 },
-    { "CHARGING", 0x0a },
-    { "CONTROLLER_1", 0x10 },
-    { "CONTROLLER_2", 0x11 },
-    { "CONTROLLER_3", 0x12 },
-    { "CONTROLLER_4", 0x13 },
-
-    // NOTE: If you add new LEDs here, you must also add them to Input.h
-
-    { NULL, -1 }
-};
-
-#endif // _LIBINPUT_KEYCODE_LABELS_H
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/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/libs/input/Input.cpp b/libs/input/Input.cpp
index d9f22e9..3a7afe9 100644
--- a/libs/input/Input.cpp
+++ b/libs/input/Input.cpp
@@ -21,6 +21,7 @@
 #include <limits.h>
 
 #include <input/Input.h>
+#include <input/InputEventLabels.h>
 
 #ifdef HAVE_ANDROID_OS
 #include <binder/Parcel.h>
@@ -42,82 +43,12 @@
 
 // --- KeyEvent ---
 
-bool KeyEvent::hasDefaultAction(int32_t keyCode) {
-    switch (keyCode) {
-        case AKEYCODE_HOME:
-        case AKEYCODE_BACK:
-        case AKEYCODE_CALL:
-        case AKEYCODE_ENDCALL:
-        case AKEYCODE_VOLUME_UP:
-        case AKEYCODE_VOLUME_DOWN:
-        case AKEYCODE_VOLUME_MUTE:
-        case AKEYCODE_POWER:
-        case AKEYCODE_CAMERA:
-        case AKEYCODE_HEADSETHOOK:
-        case AKEYCODE_MENU:
-        case AKEYCODE_NOTIFICATION:
-        case AKEYCODE_FOCUS:
-        case AKEYCODE_SEARCH:
-        case AKEYCODE_MEDIA_PLAY:
-        case AKEYCODE_MEDIA_PAUSE:
-        case AKEYCODE_MEDIA_PLAY_PAUSE:
-        case AKEYCODE_MEDIA_STOP:
-        case AKEYCODE_MEDIA_NEXT:
-        case AKEYCODE_MEDIA_PREVIOUS:
-        case AKEYCODE_MEDIA_REWIND:
-        case AKEYCODE_MEDIA_RECORD:
-        case AKEYCODE_MEDIA_FAST_FORWARD:
-        case AKEYCODE_MUTE:
-        case AKEYCODE_BRIGHTNESS_DOWN:
-        case AKEYCODE_BRIGHTNESS_UP:
-        case AKEYCODE_MEDIA_AUDIO_TRACK:
-            return true;
-    }
-    
-    return false;
+const char* KeyEvent::getLabel(int32_t keyCode) {
+    return getLabelByKeyCode(keyCode);
 }
 
-bool KeyEvent::hasDefaultAction() const {
-    return hasDefaultAction(getKeyCode());
-}
-
-bool KeyEvent::isSystemKey(int32_t keyCode) {
-    switch (keyCode) {
-        case AKEYCODE_MENU:
-        case AKEYCODE_SOFT_RIGHT:
-        case AKEYCODE_HOME:
-        case AKEYCODE_BACK:
-        case AKEYCODE_CALL:
-        case AKEYCODE_ENDCALL:
-        case AKEYCODE_VOLUME_UP:
-        case AKEYCODE_VOLUME_DOWN:
-        case AKEYCODE_VOLUME_MUTE:
-        case AKEYCODE_MUTE:
-        case AKEYCODE_POWER:
-        case AKEYCODE_HEADSETHOOK:
-        case AKEYCODE_MEDIA_PLAY:
-        case AKEYCODE_MEDIA_PAUSE:
-        case AKEYCODE_MEDIA_PLAY_PAUSE:
-        case AKEYCODE_MEDIA_STOP:
-        case AKEYCODE_MEDIA_NEXT:
-        case AKEYCODE_MEDIA_PREVIOUS:
-        case AKEYCODE_MEDIA_REWIND:
-        case AKEYCODE_MEDIA_RECORD:
-        case AKEYCODE_MEDIA_FAST_FORWARD:
-        case AKEYCODE_CAMERA:
-        case AKEYCODE_FOCUS:
-        case AKEYCODE_SEARCH:
-        case AKEYCODE_BRIGHTNESS_DOWN:
-        case AKEYCODE_BRIGHTNESS_UP:
-        case AKEYCODE_MEDIA_AUDIO_TRACK:
-            return true;
-    }
-    
-    return false;
-}
-
-bool KeyEvent::isSystemKey() const {
-    return isSystemKey(getKeyCode());
+int32_t KeyEvent::getKeyCodeFromLabel(const char* label) {
+    return getKeyCodeByLabel(label);
 }
 
 void KeyEvent::initialize(
@@ -591,6 +522,14 @@
     return false;
 }
 
+const char* MotionEvent::getLabel(int32_t axis) {
+    return getAxisLabel(axis);
+}
+
+int32_t MotionEvent::getAxisFromLabel(const char* label) {
+    return getAxisByLabel(label);
+}
+
 
 // --- PooledInputEventFactory ---
 
diff --git a/libs/input/InputTransport.cpp b/libs/input/InputTransport.cpp
index 09b2e7c..a73780d 100644
--- a/libs/input/InputTransport.cpp
+++ b/libs/input/InputTransport.cpp
@@ -312,7 +312,7 @@
     }
 
     if (pointerCount > MAX_POINTERS || pointerCount < 1) {
-        ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %d.",
+        ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %zu.",
                 mChannel->getName().string(), pointerCount);
         return BAD_VALUE;
     }
diff --git a/libs/input/KeyCharacterMap.cpp b/libs/input/KeyCharacterMap.cpp
index 15a877447..b03e01e 100644
--- a/libs/input/KeyCharacterMap.cpp
+++ b/libs/input/KeyCharacterMap.cpp
@@ -24,6 +24,7 @@
 #endif
 
 #include <android/keycodes.h>
+#include <input/InputEventLabels.h>
 #include <input/Keyboard.h>
 #include <input/KeyCharacterMap.h>
 
diff --git a/libs/input/KeyLayoutMap.cpp b/libs/input/KeyLayoutMap.cpp
index 0800a31..2b2f13e 100644
--- a/libs/input/KeyLayoutMap.cpp
+++ b/libs/input/KeyLayoutMap.cpp
@@ -19,6 +19,7 @@
 #include <stdlib.h>
 
 #include <android/keycodes.h>
+#include <input/InputEventLabels.h>
 #include <input/Keyboard.h>
 #include <input/KeyLayoutMap.h>
 #include <utils/Log.h>
diff --git a/libs/input/Keyboard.cpp b/libs/input/Keyboard.cpp
index 7d4ac92..f4d9507 100644
--- a/libs/input/Keyboard.cpp
+++ b/libs/input/Keyboard.cpp
@@ -21,7 +21,7 @@
 #include <limits.h>
 
 #include <input/Keyboard.h>
-#include <input/KeycodeLabels.h>
+#include <input/InputEventLabels.h>
 #include <input/KeyLayoutMap.h>
 #include <input/KeyCharacterMap.h>
 #include <input/InputDevice.h>
@@ -167,46 +167,6 @@
     return strstr(deviceIdentifier.name.string(), "-keypad");
 }
 
-static int lookupValueByLabel(const char* literal, const KeycodeLabel *list) {
-    while (list->literal) {
-        if (strcmp(literal, list->literal) == 0) {
-            return list->value;
-        }
-        list++;
-    }
-    return list->value;
-}
-
-static const char* lookupLabelByValue(int value, const KeycodeLabel *list) {
-    while (list->literal) {
-        if (list->value == value) {
-            return list->literal;
-        }
-        list++;
-    }
-    return NULL;
-}
-
-int32_t getKeyCodeByLabel(const char* label) {
-    return int32_t(lookupValueByLabel(label, KEYCODES));
-}
-
-uint32_t getKeyFlagByLabel(const char* label) {
-    return uint32_t(lookupValueByLabel(label, FLAGS));
-}
-
-int32_t getAxisByLabel(const char* label) {
-    return int32_t(lookupValueByLabel(label, AXES));
-}
-
-const char* getAxisLabel(int32_t axisId) {
-    return lookupLabelByValue(axisId, AXES);
-}
-
-int32_t getLedByLabel(const char* label) {
-    return int32_t(lookupValueByLabel(label, LEDS));
-}
-
 static int32_t setEphemeralMetaState(int32_t mask, bool down, int32_t oldMetaState) {
     int32_t newMetaState;
     if (down) {
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/services/inputflinger/InputDispatcher.cpp b/services/inputflinger/InputDispatcher.cpp
index f219f95..0bae399 100644
--- a/services/inputflinger/InputDispatcher.cpp
+++ b/services/inputflinger/InputDispatcher.cpp
@@ -2360,18 +2360,6 @@
         policyFlags |= POLICY_FLAG_VIRTUAL;
         flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
     }
-    if (policyFlags & POLICY_FLAG_ALT) {
-        metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;
-    }
-    if (policyFlags & POLICY_FLAG_ALT_GR) {
-        metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;
-    }
-    if (policyFlags & POLICY_FLAG_SHIFT) {
-        metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;
-    }
-    if (policyFlags & POLICY_FLAG_CAPS_LOCK) {
-        metaState |= AMETA_CAPS_LOCK_ON;
-    }
     if (policyFlags & POLICY_FLAG_FUNCTION) {
         metaState |= AMETA_FUNCTION_ON;
     }
diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp
index f27ba96..8295c4c 100644
--- a/services/inputflinger/InputReader.cpp
+++ b/services/inputflinger/InputReader.cpp
@@ -2167,9 +2167,8 @@
     // For internal keyboards, the key layout file should specify the policy flags for
     // each wake key individually.
     // TODO: Use the input device configuration to control this behavior more finely.
-    if (down && getDevice()->isExternal()
-            && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {
-        policyFlags |= POLICY_FLAG_WAKE_DROPPED;
+    if (down && getDevice()->isExternal()) {
+        policyFlags |= POLICY_FLAG_WAKE;
     }
 
     if (mParameters.handlesKeyRepeat) {
@@ -2510,7 +2509,7 @@
     // TODO: Use the input device configuration to control this behavior more finely.
     uint32_t policyFlags = 0;
     if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
-        policyFlags |= POLICY_FLAG_WAKE_DROPPED;
+        policyFlags |= POLICY_FLAG_WAKE;
     }
 
     // Synthesize key down from buttons if needed.
@@ -3787,7 +3786,7 @@
             }
 
             if (mParameters.wake) {
-                policyFlags |= POLICY_FLAG_WAKE_DROPPED;
+                policyFlags |= POLICY_FLAG_WAKE;
             }
         }
 
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/HWComposer.cpp b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
index a6f8d15..c4ea8cc 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
@@ -1020,9 +1020,27 @@
     return getLayerIterator(id, numLayers);
 }
 
+// Converts a PixelFormat to a human-readable string.  Max 11 chars.
+// (Could use a table of prefab String8 objects.)
+static String8 getFormatStr(PixelFormat format) {
+    switch (format) {
+    case PIXEL_FORMAT_RGBA_8888:    return String8("RGBA_8888");
+    case PIXEL_FORMAT_RGBX_8888:    return String8("RGBx_8888");
+    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");
+    default:
+        String8 result;
+        result.appendFormat("? %08x", format);
+        return result;
+    }
+}
+
 void HWComposer::dump(String8& result) const {
     if (mHwc) {
-        result.appendFormat("Hardware Composer state (version %8x):\n", hwcApiVersion(mHwc));
+        result.appendFormat("Hardware Composer state (version %08x):\n", hwcApiVersion(mHwc));
         result.appendFormat("  mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync);
         for (size_t i=0 ; i<mNumDisplays ; i++) {
             const DisplayData& disp(mDisplayData[i]);
@@ -1042,9 +1060,9 @@
                         disp.list->numHwLayers, disp.list->flags);
 
                 result.append(
-                        "    type    |  handle  |   hints  |   flags  | tr | blend |  format  |          source crop            |           frame           name \n"
-                        "------------+----------+----------+----------+----+-------+----------+---------------------------------+--------------------------------\n");
-                //      " __________ | ________ | ________ | ________ | __ | _____ | ________ | [_____._,_____._,_____._,_____._] | [_____,_____,_____,_____]
+                        "    type   |  handle  | hint | flag | tr | blnd |   format    |     source crop (l,t,r,b)      |          frame         | name \n"
+                        "-----------+----------+------+------+----+------+-------------+--------------------------------+------------------------+------\n");
+                //      " _________ | ________ | ____ | ____ | __ | ____ | ___________ |_____._,_____._,_____._,_____._ |_____,_____,_____,_____ | ___...
                 for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
                     const hwc_layer_1_t&l = disp.list->hwLayers[i];
                     int32_t format = -1;
@@ -1069,25 +1087,26 @@
                     static char const* compositionTypeName[] = {
                             "GLES",
                             "HWC",
-                            "BACKGROUND",
+                            "BKGND",
                             "FB TARGET",
                             "UNKNOWN"};
                     if (type >= NELEM(compositionTypeName))
                         type = NELEM(compositionTypeName) - 1;
 
+                    String8 formatStr = getFormatStr(format);
                     if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
                         result.appendFormat(
-                                " %10s | %08" PRIxPTR " | %08x | %08x | %02x | %05x | %08x | [%7.1f,%7.1f,%7.1f,%7.1f] | [%5d,%5d,%5d,%5d] %s\n",
+                                " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7.1f,%7.1f,%7.1f,%7.1f |%5d,%5d,%5d,%5d | %s\n",
                                         compositionTypeName[type],
-                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, format,
+                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
                                         l.sourceCropf.left, l.sourceCropf.top, l.sourceCropf.right, l.sourceCropf.bottom,
                                         l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
                                         name.string());
                     } else {
                         result.appendFormat(
-                                " %10s | %08" PRIxPTR " | %08x | %08x | %02x | %05x | %08x | [%7d,%7d,%7d,%7d] | [%5d,%5d,%5d,%5d] %s\n",
+                                " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7d,%7d,%7d,%7d |%5d,%5d,%5d,%5d | %s\n",
                                         compositionTypeName[type],
-                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, format,
+                                        intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
                                         l.sourceCrop.left, l.sourceCrop.top, l.sourceCrop.right, l.sourceCrop.bottom,
                                         l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
                                         name.string());
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index 62970c3..ee9f8a0 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -76,6 +76,10 @@
     Region visibleRegion;
     Region coveredRegion;
     Region visibleNonTransparentRegion;
+
+    // Layer serial number.  This gives layers an explicit ordering, so we
+    // have a stable sort order when their layer stack and Z-order are
+    // the same.
     int32_t sequence;
 
     enum { // flags for doTransaction()
@@ -341,7 +345,7 @@
     // constants
     sp<SurfaceFlingerConsumer> mSurfaceFlingerConsumer;
     sp<IGraphicBufferProducer> mProducer;
-    uint32_t mTextureName;
+    uint32_t mTextureName;      // from GLES
     bool mPremultipliedAlpha;
     String8 mName;
     mutable bool mDebug;
@@ -372,7 +376,7 @@
     bool mNeedsFiltering;
     // The mesh used to draw the layer in GLES composition mode
     mutable Mesh mMesh;
-    // The mesh used to draw the layer in GLES composition mode
+    // The texture used to draw the layer in GLES composition mode
     mutable Texture mTexture;
 
     // page-flip thread (currently main thread)