Merge "Remove NativeWindow and unused DVR functions"
diff --git a/cmds/installd/tests/installd_utils_test.cpp b/cmds/installd/tests/installd_utils_test.cpp
index 4b68574..6a8755e 100644
--- a/cmds/installd/tests/installd_utils_test.cpp
+++ b/cmds/installd/tests/installd_utils_test.cpp
@@ -321,6 +321,7 @@
     size_t pkgnameSize = PKG_NAME_MAX;
     char pkgname[pkgnameSize + 1];
     memset(pkgname, 'a', pkgnameSize);
+    pkgname[1] = '.';
     pkgname[pkgnameSize] = '\0';
 
     EXPECT_EQ(0, create_pkg_path(path, pkgname, "", 0))
@@ -512,5 +513,22 @@
             create_data_user_ce_package_path("57f8f4bc-abf4-655f-bf67-946fc0f9f25b", 10, "com.example"));
 }
 
+TEST_F(UtilsTest, IsValidPackageName) {
+    EXPECT_EQ(true, is_valid_package_name("com.example"));
+    EXPECT_EQ(true, is_valid_package_name("com.example-1"));
+    EXPECT_EQ(true, is_valid_package_name("com.example-1024"));
+    EXPECT_EQ(true, is_valid_package_name("com.example.foo---KiJFj4a_tePVw95pSrjg=="));
+    EXPECT_EQ(true, is_valid_package_name("really_LONG.a1234.package_name"));
+
+    EXPECT_EQ(false, is_valid_package_name("1234.package"));
+    EXPECT_EQ(false, is_valid_package_name("com.1234.package"));
+    EXPECT_EQ(false, is_valid_package_name("package"));
+    EXPECT_EQ(false, is_valid_package_name(""));
+    EXPECT_EQ(false, is_valid_package_name("."));
+    EXPECT_EQ(false, is_valid_package_name("com.example/../com.evil/"));
+    EXPECT_EQ(false, is_valid_package_name("com.example-1/../com.evil/"));
+    EXPECT_EQ(false, is_valid_package_name("/com.evil"));
+}
+
 }  // namespace installd
 }  // namespace android
diff --git a/cmds/installd/utils.cpp b/cmds/installd/utils.cpp
index 2bf0171..b379037 100644
--- a/cmds/installd/utils.cpp
+++ b/cmds/installd/utils.cpp
@@ -350,46 +350,42 @@
  * 0 on success.
  */
 bool is_valid_package_name(const std::string& packageName) {
-    const char* pkgname = packageName.c_str();
-    const char *x = pkgname;
-    int alpha = -1;
+    // This logic is borrowed from PackageParser.java
+    bool hasSep = false;
+    bool front = true;
 
-    if (strlen(pkgname) > PKG_NAME_MAX) {
+    auto it = packageName.begin();
+    for (; it != packageName.end() && *it != '-'; it++) {
+        char c = *it;
+        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
+            front = false;
+            continue;
+        }
+        if (!front) {
+            if ((c >= '0' && c <= '9') || c == '_') {
+                continue;
+            }
+        }
+        if (c == '.') {
+            hasSep = true;
+            front = true;
+            continue;
+        }
+        LOG(WARNING) << "Bad package character " << c << " in " << packageName;
         return false;
     }
 
-    while (*x) {
-        if (isalnum(*x) || (*x == '_')) {
-                /* alphanumeric or underscore are fine */
-        } else if (*x == '.') {
-            if ((x == pkgname) || (x[1] == '.') || (x[1] == 0)) {
-                    /* periods must not be first, last, or doubled */
-                ALOGE("invalid package name '%s'\n", pkgname);
-                return false;
-            }
-        } else if (*x == '-') {
-            /* Suffix -X is fine to let versioning of packages.
-               But whatever follows should be alphanumeric.*/
-            alpha = 1;
-        } else {
-                /* anything not A-Z, a-z, 0-9, _, or . is invalid */
-            ALOGE("invalid package name '%s'\n", pkgname);
-            return false;
-        }
-
-        x++;
+    if (!hasSep || front) {
+        LOG(WARNING) << "Missing separator in " << packageName;
+        return false;
     }
 
-    if (alpha == 1) {
-        // Skip current character
-        x++;
-        while (*x) {
-            if (!isalnum(*x)) {
-                ALOGE("invalid package name '%s' should include only numbers after -\n", pkgname);
-                return false;
-            }
-            x++;
-        }
+    for (; it != packageName.end(); it++) {
+        char c = *it;
+        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) continue;
+        if ((c >= '0' && c <= '9') || c == '_' || c == '-' || c == '=') continue;
+        LOG(WARNING) << "Bad suffix character " << c << " in " << packageName;
+        return false;
     }
 
     return true;
diff --git a/include/android/sensor.h b/include/android/sensor.h
index a5e5c05..186f62c 100644
--- a/include/android/sensor.h
+++ b/include/android/sensor.h
@@ -48,22 +48,32 @@
  *
  */
 
-#include <sys/types.h>
-
 #include <android/looper.h>
 
+#include <sys/types.h>
+#include <math.h>
+#include <stdint.h>
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 typedef struct AHardwareBuffer AHardwareBuffer;
 
+#define ASENSOR_RESOLUTION_INVALID     (nanf(""))
+#define ASENSOR_FIFO_COUNT_INVALID     (-1)
+#define ASENSOR_DELAY_INVALID          INT32_MIN
+
 /**
  * Sensor types.
  * (keep in sync with hardware/sensors.h)
  */
 enum {
     /**
+     * Invalid sensor type. Returned by {@link ASensor_getType} as error value.
+     */
+    ASENSOR_TYPE_INVALID = -1,
+    /**
      * {@link ASENSOR_TYPE_ACCELEROMETER}
      * reporting-mode: continuous
      *
@@ -135,6 +145,8 @@
  * Sensor Reporting Modes.
  */
 enum {
+    /** invalid reporting mode */
+    AREPORTING_MODE_INVALID = -1,
     /** continuous reporting */
     AREPORTING_MODE_CONTINUOUS = 0,
     /** reporting on change */
@@ -397,8 +409,7 @@
  * Returns the default sensor with the given type and wakeUp properties or NULL if no sensor
  * of this type and wakeUp properties exists.
  */
-ASensor const* ASensorManager_getDefaultSensorEx(ASensorManager* manager, int type,
-        bool wakeUp);
+ASensor const* ASensorManager_getDefaultSensorEx(ASensorManager* manager, int type, bool wakeUp);
 #endif
 
 /**
@@ -516,7 +527,7 @@
  * Note: To disable the selected sensor, use ASensorEventQueue_disableSensor() same as before.
  */
 int ASensorEventQueue_registerSensor(ASensorEventQueue* queue, ASensor const* sensor,
-        int32_t samplingPeriodUs, int maxBatchReportLatencyUs);
+        int32_t samplingPeriodUs, int64_t maxBatchReportLatencyUs);
 
 /**
  * Enable the selected sensor. Returns a negative error code on failure.
@@ -557,8 +568,7 @@
  *   ssize_t numEvent = ASensorEventQueue_getEvents(queue, eventBuffer, 8);
  *
  */
-ssize_t ASensorEventQueue_getEvents(ASensorEventQueue* queue,
-                ASensorEvent* events, size_t count);
+ssize_t ASensorEventQueue_getEvents(ASensorEventQueue* queue, ASensorEvent* events, size_t count);
 
 
 /*****************************************************************************/
diff --git a/include/gui/BitTube.h b/include/private/gui/BitTube.h
similarity index 100%
rename from include/gui/BitTube.h
rename to include/private/gui/BitTube.h
diff --git a/libs/binder/ProcessState.cpp b/libs/binder/ProcessState.cpp
index fe28533..98107c5 100644
--- a/libs/binder/ProcessState.cpp
+++ b/libs/binder/ProcessState.cpp
@@ -40,7 +40,7 @@
 #include <sys/stat.h>
 #include <sys/types.h>
 
-#define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2))
+#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
 #define DEFAULT_MAX_BINDER_THREADS 15
 
 // -------------------------------------------------------------------------
diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp
index 8f9c38a..a1b4abc 100644
--- a/libs/gui/Android.bp
+++ b/libs/gui/Android.bp
@@ -38,10 +38,6 @@
         // Don't warn about struct padding
         "-Wno-padded",
 
-        // android/sensors.h uses nested anonymous unions and anonymous structs
-        "-Wno-nested-anon-types",
-        "-Wno-gnu-anonymous-struct",
-
         // We are aware of the risks inherent in comparing floats for equality
         "-Wno-float-equal",
 
@@ -61,8 +57,6 @@
     },
 
     srcs: [
-        "IGraphicBufferConsumer.cpp",
-        "IConsumerListener.cpp",
         "BitTube.cpp",
         "BufferItem.cpp",
         "BufferItemConsumer.cpp",
@@ -79,18 +73,15 @@
         "GraphicBufferAlloc.cpp",
         "GuiConfig.cpp",
         "IDisplayEventConnection.cpp",
+        "IConsumerListener.cpp",
         "IGraphicBufferAlloc.cpp",
+        "IGraphicBufferConsumer.cpp",
         "IGraphicBufferProducer.cpp",
         "IProducerListener.cpp",
-        "ISensorEventConnection.cpp",
-        "ISensorServer.cpp",
         "ISurfaceComposer.cpp",
         "ISurfaceComposerClient.cpp",
         "LayerState.cpp",
         "OccupancyTracker.cpp",
-        "Sensor.cpp",
-        "SensorEventQueue.cpp",
-        "SensorManager.cpp",
         "StreamSplitter.cpp",
         "Surface.cpp",
         "SurfaceControl.cpp",
diff --git a/libs/gui/BitTube.cpp b/libs/gui/BitTube.cpp
index b653c5b..51a8d67 100644
--- a/libs/gui/BitTube.cpp
+++ b/libs/gui/BitTube.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <private/gui/BitTube.h>
+
 #include <stdint.h>
 #include <sys/types.h>
 #include <sys/socket.h>
@@ -25,7 +27,6 @@
 
 #include <binder/Parcel.h>
 
-#include <gui/BitTube.h>
 
 namespace android {
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/DisplayEventReceiver.cpp b/libs/gui/DisplayEventReceiver.cpp
index 9973e8d..07e07e0 100644
--- a/libs/gui/DisplayEventReceiver.cpp
+++ b/libs/gui/DisplayEventReceiver.cpp
@@ -18,13 +18,14 @@
 
 #include <utils/Errors.h>
 
-#include <gui/BitTube.h>
 #include <gui/DisplayEventReceiver.h>
 #include <gui/IDisplayEventConnection.h>
 #include <gui/ISurfaceComposer.h>
 
 #include <private/gui/ComposerService.h>
 
+#include <private/gui/BitTube.h>
+
 // ---------------------------------------------------------------------------
 
 namespace android {
diff --git a/libs/gui/IDisplayEventConnection.cpp b/libs/gui/IDisplayEventConnection.cpp
index b1d3b00..e5c3c48 100644
--- a/libs/gui/IDisplayEventConnection.cpp
+++ b/libs/gui/IDisplayEventConnection.cpp
@@ -15,17 +15,15 @@
  */
 
 #include <stdint.h>
-#include <sys/types.h>
 
 #include <utils/Errors.h>
 #include <utils/RefBase.h>
-#include <utils/Timers.h>
 
 #include <binder/Parcel.h>
-#include <binder/IInterface.h>
 
 #include <gui/IDisplayEventConnection.h>
-#include <gui/BitTube.h>
+
+#include <private/gui/BitTube.h>
 
 namespace android {
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/tests/Android.bp b/libs/gui/tests/Android.bp
index 5944110..4492a08 100644
--- a/libs/gui/tests/Android.bp
+++ b/libs/gui/tests/Android.bp
@@ -14,7 +14,6 @@
         "GLTest.cpp",
         "IGraphicBufferProducer_test.cpp",
         "MultiTextureConsumer_test.cpp",
-        "Sensor_test.cpp",
         "StreamSplitter_test.cpp",
         "SurfaceTextureClient_test.cpp",
         "SurfaceTextureFBO_test.cpp",
diff --git a/libs/sensor/Android.bp b/libs/sensor/Android.bp
new file mode 100644
index 0000000..171a627
--- /dev/null
+++ b/libs/sensor/Android.bp
@@ -0,0 +1,61 @@
+// Copyright 2010 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+cc_library_shared {
+    name: "libsensor",
+
+    clang: true,
+    cppflags: [
+        "-Weverything",
+        "-Werror",
+
+        // The static constructors and destructors in this library have not been noted to
+        // introduce significant overheads
+        "-Wno-exit-time-destructors",
+        "-Wno-global-constructors",
+
+        // We only care about compiling as C++14
+        "-Wno-c++98-compat-pedantic",
+
+        // android/sensors.h uses nested anonymous unions and anonymous structs
+        "-Wno-nested-anon-types",
+        "-Wno-gnu-anonymous-struct",
+
+        // Don't warn about struct padding
+        "-Wno-padded",
+    ],
+
+    srcs: [
+        "BitTube.cpp",
+        "ISensorEventConnection.cpp",
+        "ISensorServer.cpp",
+        "Sensor.cpp",
+        "SensorEventQueue.cpp",
+        "SensorManager.cpp",
+    ],
+
+    shared_libs: [
+        "libbinder",
+        "libcutils",
+        "libutils",
+        "liblog",
+        "libhardware",
+    ],
+
+    export_include_dirs: ["include"],
+
+    export_shared_lib_headers: ["libbinder", "libhardware"],
+}
+
+subdirs = ["tests"]
diff --git a/libs/sensor/BitTube.cpp b/libs/sensor/BitTube.cpp
new file mode 100644
index 0000000..93555c8
--- /dev/null
+++ b/libs/sensor/BitTube.cpp
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <sensor/BitTube.h>
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <binder/Parcel.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+// Socket buffer size.  The default is typically about 128KB, which is much larger than
+// we really need.  So we make it smaller.
+static const size_t DEFAULT_SOCKET_BUFFER_SIZE = 4 * 1024;
+
+
+BitTube::BitTube()
+    : mSendFd(-1), mReceiveFd(-1)
+{
+    init(DEFAULT_SOCKET_BUFFER_SIZE, DEFAULT_SOCKET_BUFFER_SIZE);
+}
+
+BitTube::BitTube(size_t bufsize)
+    : mSendFd(-1), mReceiveFd(-1)
+{
+    init(bufsize, bufsize);
+}
+
+BitTube::BitTube(const Parcel& data)
+    : mSendFd(-1), mReceiveFd(-1)
+{
+    mReceiveFd = dup(data.readFileDescriptor());
+    if (mReceiveFd < 0) {
+        mReceiveFd = -errno;
+        ALOGE("BitTube(Parcel): can't dup filedescriptor (%s)",
+                strerror(-mReceiveFd));
+    }
+}
+
+BitTube::~BitTube()
+{
+    if (mSendFd >= 0)
+        close(mSendFd);
+
+    if (mReceiveFd >= 0)
+        close(mReceiveFd);
+}
+
+void BitTube::init(size_t rcvbuf, size_t sndbuf) {
+    int sockets[2];
+    if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets) == 0) {
+        size_t size = DEFAULT_SOCKET_BUFFER_SIZE;
+        setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
+        setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
+        // sine we don't use the "return channel", we keep it small...
+        setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &size, sizeof(size));
+        setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
+        fcntl(sockets[0], F_SETFL, O_NONBLOCK);
+        fcntl(sockets[1], F_SETFL, O_NONBLOCK);
+        mReceiveFd = sockets[0];
+        mSendFd = sockets[1];
+    } else {
+        mReceiveFd = -errno;
+        ALOGE("BitTube: pipe creation failed (%s)", strerror(-mReceiveFd));
+    }
+}
+
+status_t BitTube::initCheck() const
+{
+    if (mReceiveFd < 0) {
+        return status_t(mReceiveFd);
+    }
+    return NO_ERROR;
+}
+
+int BitTube::getFd() const
+{
+    return mReceiveFd;
+}
+
+int BitTube::getSendFd() const
+{
+    return mSendFd;
+}
+
+ssize_t BitTube::write(void const* vaddr, size_t size)
+{
+    ssize_t err, len;
+    do {
+        len = ::send(mSendFd, vaddr, size, MSG_DONTWAIT | MSG_NOSIGNAL);
+        // cannot return less than size, since we're using SOCK_SEQPACKET
+        err = len < 0 ? errno : 0;
+    } while (err == EINTR);
+    return err == 0 ? len : -err;
+}
+
+ssize_t BitTube::read(void* vaddr, size_t size)
+{
+    ssize_t err, len;
+    do {
+        len = ::recv(mReceiveFd, vaddr, size, MSG_DONTWAIT);
+        err = len < 0 ? errno : 0;
+    } while (err == EINTR);
+    if (err == EAGAIN || err == EWOULDBLOCK) {
+        // EAGAIN means that we have non-blocking I/O but there was
+        // no data to be read. Nothing the client should care about.
+        return 0;
+    }
+    return err == 0 ? len : -err;
+}
+
+status_t BitTube::writeToParcel(Parcel* reply) const
+{
+    if (mReceiveFd < 0)
+        return -EINVAL;
+
+    status_t result = reply->writeDupFileDescriptor(mReceiveFd);
+    close(mReceiveFd);
+    mReceiveFd = -1;
+    return result;
+}
+
+
+ssize_t BitTube::sendObjects(const sp<BitTube>& tube,
+        void const* events, size_t count, size_t objSize)
+{
+    const char* vaddr = reinterpret_cast<const char*>(events);
+    ssize_t size = tube->write(vaddr, count*objSize);
+
+    // should never happen because of SOCK_SEQPACKET
+    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % static_cast<ssize_t>(objSize)),
+            "BitTube::sendObjects(count=%zu, size=%zu), res=%zd (partial events were sent!)",
+            count, objSize, size);
+
+    //ALOGE_IF(size<0, "error %d sending %d events", size, count);
+    return size < 0 ? size : size / static_cast<ssize_t>(objSize);
+}
+
+ssize_t BitTube::recvObjects(const sp<BitTube>& tube,
+        void* events, size_t count, size_t objSize)
+{
+    char* vaddr = reinterpret_cast<char*>(events);
+    ssize_t size = tube->read(vaddr, count*objSize);
+
+    // should never happen because of SOCK_SEQPACKET
+    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % static_cast<ssize_t>(objSize)),
+            "BitTube::recvObjects(count=%zu, size=%zu), res=%zd (partial events were received!)",
+            count, objSize, size);
+
+    //ALOGE_IF(size<0, "error %d receiving %d events", size, count);
+    return size < 0 ? size : size / static_cast<ssize_t>(objSize);
+}
+
+// ----------------------------------------------------------------------------
+}; // namespace android
diff --git a/libs/gui/ISensorEventConnection.cpp b/libs/sensor/ISensorEventConnection.cpp
similarity index 98%
rename from libs/gui/ISensorEventConnection.cpp
rename to libs/sensor/ISensorEventConnection.cpp
index 8af51c5..8a3a623 100644
--- a/libs/gui/ISensorEventConnection.cpp
+++ b/libs/sensor/ISensorEventConnection.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <sensor/ISensorEventConnection.h>
+
 #include <stdint.h>
 #include <sys/types.h>
 
@@ -24,8 +26,7 @@
 #include <binder/Parcel.h>
 #include <binder/IInterface.h>
 
-#include <gui/ISensorEventConnection.h>
-#include <gui/BitTube.h>
+#include <sensor/BitTube.h>
 
 namespace android {
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/ISensorServer.cpp b/libs/sensor/ISensorServer.cpp
similarity index 98%
rename from libs/gui/ISensorServer.cpp
rename to libs/sensor/ISensorServer.cpp
index aea7403..f41f187 100644
--- a/libs/gui/ISensorServer.cpp
+++ b/libs/sensor/ISensorServer.cpp
@@ -14,6 +14,8 @@
  * limitations under the License.
  */
 
+#include <sensor/ISensorServer.h>
+
 #include <stdint.h>
 #include <sys/types.h>
 
@@ -26,9 +28,8 @@
 #include <binder/Parcel.h>
 #include <binder/IInterface.h>
 
-#include <gui/Sensor.h>
-#include <gui/ISensorServer.h>
-#include <gui/ISensorEventConnection.h>
+#include <sensor/Sensor.h>
+#include <sensor/ISensorEventConnection.h>
 
 namespace android {
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/Sensor.cpp b/libs/sensor/Sensor.cpp
similarity index 98%
rename from libs/gui/Sensor.cpp
rename to libs/sensor/Sensor.cpp
index e2f733a..c2d477e 100644
--- a/libs/gui/Sensor.cpp
+++ b/libs/sensor/Sensor.cpp
@@ -14,19 +14,13 @@
  * limitations under the License.
  */
 
+#include <sensor/Sensor.h>
+
 #include <inttypes.h>
-#include <stdint.h>
-#include <sys/limits.h>
-#include <sys/types.h>
 
 #include <binder/AppOpsManager.h>
+#include <binder/IPermissionController.h>
 #include <binder/IServiceManager.h>
-#include <gui/Sensor.h>
-#include <hardware/sensors.h>
-#include <log/log.h>
-#include <utils/Errors.h>
-#include <utils/String8.h>
-#include <utils/Flattenable.h>
 
 // ----------------------------------------------------------------------------
 namespace android {
@@ -51,7 +45,7 @@
     mHandle = hwSensor.handle;
     mType = hwSensor.type;
     mMinValue = 0;                      // FIXME: minValue
-    mMaxValue = hwSensor.maxRange;     // FIXME: maxValue
+    mMaxValue = hwSensor.maxRange;      // FIXME: maxValue
     mResolution = hwSensor.resolution;
     mPower = hwSensor.power;
     mMinDelay = hwSensor.minDelay;
diff --git a/libs/gui/SensorEventQueue.cpp b/libs/sensor/SensorEventQueue.cpp
similarity index 94%
rename from libs/gui/SensorEventQueue.cpp
rename to libs/sensor/SensorEventQueue.cpp
index 6d69839..6f68fb5 100644
--- a/libs/gui/SensorEventQueue.cpp
+++ b/libs/sensor/SensorEventQueue.cpp
@@ -16,20 +16,17 @@
 
 #define LOG_TAG "Sensors"
 
-#include <algorithm>
-#include <stdint.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <linux/errno.h>
+#include <sensor/SensorEventQueue.h>
 
-#include <utils/Errors.h>
+#include <algorithm>
+#include <sys/socket.h>
+
 #include <utils/RefBase.h>
 #include <utils/Looper.h>
 
-#include <gui/Sensor.h>
-#include <gui/BitTube.h>
-#include <gui/SensorEventQueue.h>
-#include <gui/ISensorEventConnection.h>
+#include <sensor/Sensor.h>
+#include <sensor/BitTube.h>
+#include <sensor/ISensorEventConnection.h>
 
 #include <android/sensor.h>
 
@@ -138,7 +135,7 @@
 }
 
 status_t SensorEventQueue::enableSensor(int32_t handle, int32_t samplingPeriodUs,
-                                        int maxBatchReportLatencyUs, int reservedFlags) const {
+                                        int64_t maxBatchReportLatencyUs, int reservedFlags) const {
     return mSensorEventConnection->enableDisable(handle, true, us2ns(samplingPeriodUs),
                                                  us2ns(maxBatchReportLatencyUs), reservedFlags);
 }
diff --git a/libs/gui/SensorManager.cpp b/libs/sensor/SensorManager.cpp
similarity index 89%
rename from libs/gui/SensorManager.cpp
rename to libs/sensor/SensorManager.cpp
index 513b889..9309275 100644
--- a/libs/gui/SensorManager.cpp
+++ b/libs/sensor/SensorManager.cpp
@@ -16,6 +16,8 @@
 
 #define LOG_TAG "Sensors"
 
+#include <sensor/SensorManager.h>
+
 #include <stdint.h>
 #include <sys/types.h>
 
@@ -27,11 +29,10 @@
 #include <binder/IBinder.h>
 #include <binder/IServiceManager.h>
 
-#include <gui/ISensorServer.h>
-#include <gui/ISensorEventConnection.h>
-#include <gui/Sensor.h>
-#include <gui/SensorManager.h>
-#include <gui/SensorEventQueue.h>
+#include <sensor/ISensorServer.h>
+#include <sensor/ISensorEventConnection.h>
+#include <sensor/Sensor.h>
+#include <sensor/SensorEventQueue.h>
 
 // ----------------------------------------------------------------------------
 namespace android {
@@ -246,27 +247,24 @@
         return NO_INIT;
     }
 
-    switch (channelType) {
-        case SENSOR_DIRECT_MEM_TYPE_ASHMEM: {
-            sp<ISensorEventConnection> conn =
-                      mSensorServer->createSensorDirectConnection(mOpPackageName,
-                          static_cast<uint32_t>(size),
-                          static_cast<int32_t>(channelType),
-                          SENSOR_DIRECT_FMT_SENSORS_EVENT, resourceHandle);
-            if (conn == nullptr) {
-                return NO_MEMORY;
-            }
-            int nativeHandle = mDirectConnectionHandle++;
-            mDirectConnection.emplace(nativeHandle, conn);
-            return nativeHandle;
-        }
-        case SENSOR_DIRECT_MEM_TYPE_GRALLOC:
-            LOG_FATAL("%s: Finish implementation of ION and GRALLOC or remove", __FUNCTION__);
-            return BAD_VALUE;
-        default:
-            ALOGE("Bad channel shared memory type %d", channelType);
-            return BAD_VALUE;
+    if (channelType != SENSOR_DIRECT_MEM_TYPE_ASHMEM
+            && channelType != SENSOR_DIRECT_MEM_TYPE_GRALLOC) {
+        ALOGE("Bad channel shared memory type %d", channelType);
+        return BAD_VALUE;
     }
+
+    sp<ISensorEventConnection> conn =
+              mSensorServer->createSensorDirectConnection(mOpPackageName,
+                  static_cast<uint32_t>(size),
+                  static_cast<int32_t>(channelType),
+                  SENSOR_DIRECT_FMT_SENSORS_EVENT, resourceHandle);
+    if (conn == nullptr) {
+        return NO_MEMORY;
+    }
+
+    int nativeHandle = mDirectConnectionHandle++;
+    mDirectConnection.emplace(nativeHandle, conn);
+    return nativeHandle;
 }
 
 void SensorManager::destroyDirectChannel(int channelNativeHandle) {
diff --git a/libs/sensor/include/sensor/BitTube.h b/libs/sensor/include/sensor/BitTube.h
new file mode 100644
index 0000000..c1fabe8
--- /dev/null
+++ b/libs/sensor/include/sensor/BitTube.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2010 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+class Parcel;
+
+class BitTube : public RefBase
+{
+public:
+
+    // creates a BitTube with a default (4KB) send buffer
+    BitTube();
+
+    // creates a BitTube with a a specified send and receive buffer size
+    explicit BitTube(size_t bufsize);
+
+    explicit BitTube(const Parcel& data);
+    virtual ~BitTube();
+
+    // check state after construction
+    status_t initCheck() const;
+
+    // get receive file-descriptor
+    int getFd() const;
+
+    // get the send file-descriptor.
+    int getSendFd() const;
+
+    // send objects (sized blobs). All objects are guaranteed to be written or the call fails.
+    template <typename T>
+    static ssize_t sendObjects(const sp<BitTube>& tube,
+            T const* events, size_t count) {
+        return sendObjects(tube, events, count, sizeof(T));
+    }
+
+    // receive objects (sized blobs). If the receiving buffer isn't large enough,
+    // excess messages are silently discarded.
+    template <typename T>
+    static ssize_t recvObjects(const sp<BitTube>& tube,
+            T* events, size_t count) {
+        return recvObjects(tube, events, count, sizeof(T));
+    }
+
+    // parcels this BitTube
+    status_t writeToParcel(Parcel* reply) const;
+
+private:
+    void init(size_t rcvbuf, size_t sndbuf);
+
+    // send a message. The write is guaranteed to send the whole message or fail.
+    ssize_t write(void const* vaddr, size_t size);
+
+    // receive a message. the passed buffer must be at least as large as the
+    // write call used to send the message, excess data is silently discarded.
+    ssize_t read(void* vaddr, size_t size);
+
+    int mSendFd;
+    mutable int mReceiveFd;
+
+    static ssize_t sendObjects(const sp<BitTube>& tube,
+            void const* events, size_t count, size_t objSize);
+
+    static ssize_t recvObjects(const sp<BitTube>& tube,
+            void* events, size_t count, size_t objSize);
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
diff --git a/include/gui/ISensorEventConnection.h b/libs/sensor/include/sensor/ISensorEventConnection.h
similarity index 91%
rename from include/gui/ISensorEventConnection.h
rename to libs/sensor/include/sensor/ISensorEventConnection.h
index 2ccd832..07cc7e8 100644
--- a/include/gui/ISensorEventConnection.h
+++ b/libs/sensor/include/sensor/ISensorEventConnection.h
@@ -14,14 +14,14 @@
  * limitations under the License.
  */
 
-#ifndef ANDROID_GUI_ISENSOR_EVENT_CONNECTION_H
-#define ANDROID_GUI_ISENSOR_EVENT_CONNECTION_H
+#pragma once
 
 #include <stdint.h>
 #include <sys/types.h>
 
 #include <utils/Errors.h>
-#include <utils/RefBase.h>
+#include <utils/StrongPointer.h>
+#include <utils/Timers.h>
 
 #include <binder/IInterface.h>
 
@@ -29,6 +29,7 @@
 // ----------------------------------------------------------------------------
 
 class BitTube;
+class Parcel;
 
 class ISensorEventConnection : public IInterface
 {
@@ -56,5 +57,3 @@
 
 // ----------------------------------------------------------------------------
 }; // namespace android
-
-#endif // ANDROID_GUI_ISENSOR_EVENT_CONNECTION_H
diff --git a/include/gui/ISensorServer.h b/libs/sensor/include/sensor/ISensorServer.h
similarity index 93%
rename from include/gui/ISensorServer.h
rename to libs/sensor/include/sensor/ISensorServer.h
index 0c36c99..f922307 100644
--- a/include/gui/ISensorServer.h
+++ b/libs/sensor/include/sensor/ISensorServer.h
@@ -14,14 +14,14 @@
  * limitations under the License.
  */
 
-#ifndef ANDROID_GUI_ISENSORSERVER_H
-#define ANDROID_GUI_ISENSORSERVER_H
+#pragma once
 
 #include <stdint.h>
 #include <sys/types.h>
 
 #include <utils/Errors.h>
-#include <utils/RefBase.h>
+#include <utils/StrongPointer.h>
+#include <utils/Vector.h>
 
 #include <binder/IInterface.h>
 
@@ -30,9 +30,11 @@
 namespace android {
 // ----------------------------------------------------------------------------
 
-class Sensor;
 class ISensorEventConnection;
+class Parcel;
+class Sensor;
 class String8;
+class String16;
 
 class ISensorServer : public IInterface
 {
@@ -63,5 +65,3 @@
 
 // ----------------------------------------------------------------------------
 }; // namespace android
-
-#endif // ANDROID_GUI_ISENSORSERVER_H
diff --git a/include/gui/Sensor.h b/libs/sensor/include/sensor/Sensor.h
similarity index 97%
rename from include/gui/Sensor.h
rename to libs/sensor/include/sensor/Sensor.h
index d886b2b..043e635 100644
--- a/include/gui/Sensor.h
+++ b/libs/sensor/include/sensor/Sensor.h
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef ANDROID_GUI_SENSOR_H
-#define ANDROID_GUI_SENSOR_H
+#pragma once
 
 #include <stdint.h>
 #include <sys/types.h>
@@ -25,10 +24,11 @@
 #include <utils/String8.h>
 #include <utils/Timers.h>
 
-#include <hardware/sensors.h>
-
+// FIXME: including from android/ breaks layering, as libandroid ultimately depends on libsensors
 #include <android/sensor.h>
 
+#include <hardware/sensors.h>
+
 // ----------------------------------------------------------------------------
 // Concrete types for the NDK
 struct ASensor { };
@@ -138,5 +138,3 @@
 
 // ----------------------------------------------------------------------------
 }; // namespace android
-
-#endif // ANDROID_GUI_SENSOR_H
diff --git a/include/gui/SensorEventQueue.h b/libs/sensor/include/sensor/SensorEventQueue.h
similarity index 94%
rename from include/gui/SensorEventQueue.h
rename to libs/sensor/include/sensor/SensorEventQueue.h
index 4ee7c02..a03c7ee 100644
--- a/include/gui/SensorEventQueue.h
+++ b/libs/sensor/include/sensor/SensorEventQueue.h
@@ -14,8 +14,7 @@
  * limitations under the License.
  */
 
-#ifndef ANDROID_SENSOR_EVENT_QUEUE_H
-#define ANDROID_SENSOR_EVENT_QUEUE_H
+#pragma once
 
 #include <stdint.h>
 #include <sys/types.h>
@@ -23,9 +22,9 @@
 #include <utils/Errors.h>
 #include <utils/RefBase.h>
 #include <utils/Timers.h>
-#include <utils/String16.h>
+#include <utils/Mutex.h>
 
-#include <gui/BitTube.h>
+#include <sensor/BitTube.h>
 
 // ----------------------------------------------------------------------------
 #define WAKE_UP_SENSOR_EVENT_NEEDS_ACK (1U << 31)
@@ -85,7 +84,7 @@
     status_t setEventRate(Sensor const* sensor, nsecs_t ns) const;
 
     // these are here only to support SensorManager.java
-    status_t enableSensor(int32_t handle, int32_t samplingPeriodUs, int maxBatchReportLatencyUs,
+    status_t enableSensor(int32_t handle, int32_t samplingPeriodUs, int64_t maxBatchReportLatencyUs,
                           int reservedFlags) const;
     status_t disableSensor(int32_t handle) const;
     status_t flush() const;
@@ -107,5 +106,3 @@
 
 // ----------------------------------------------------------------------------
 }; // namespace android
-
-#endif // ANDROID_SENSOR_EVENT_QUEUE_H
diff --git a/include/gui/SensorManager.h b/libs/sensor/include/sensor/SensorManager.h
similarity index 94%
rename from include/gui/SensorManager.h
rename to libs/sensor/include/sensor/SensorManager.h
index 5b34ff4..a3d9741 100644
--- a/include/gui/SensorManager.h
+++ b/libs/sensor/include/sensor/SensorManager.h
@@ -18,6 +18,7 @@
 #define ANDROID_GUI_SENSOR_MANAGER_H
 
 #include <map>
+#include <unordered_map>
 
 #include <stdint.h>
 #include <sys/types.h>
@@ -27,14 +28,11 @@
 #include <binder/IServiceManager.h>
 
 #include <utils/Errors.h>
-#include <utils/RefBase.h>
-#include <utils/Singleton.h>
+#include <utils/StrongPointer.h>
 #include <utils/Vector.h>
 #include <utils/String8.h>
 
-#include <gui/SensorEventQueue.h>
-
-#include <unordered_map>
+#include <sensor/SensorEventQueue.h>
 
 // ----------------------------------------------------------------------------
 // Concrete types for the NDK
@@ -52,8 +50,7 @@
 class SensorEventQueue;
 // ----------------------------------------------------------------------------
 
-class SensorManager :
-    public ASensorManager
+class SensorManager : public ASensorManager
 {
 public:
     static SensorManager& getInstanceForPackage(const String16& packageName);
diff --git a/libs/sensor/tests/Android.bp b/libs/sensor/tests/Android.bp
new file mode 100644
index 0000000..9d530fc
--- /dev/null
+++ b/libs/sensor/tests/Android.bp
@@ -0,0 +1,29 @@
+// Copyright 2017 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.
+
+cc_test {
+    name: "libsensor_test",
+
+    clang: true,
+
+    srcs: [
+        "Sensor_test.cpp",
+    ],
+
+    shared_libs: [
+        "liblog",
+        "libsensor",
+        "libutils",
+    ],
+}
diff --git a/libs/gui/tests/Sensor_test.cpp b/libs/sensor/tests/Sensor_test.cpp
similarity index 98%
rename from libs/gui/tests/Sensor_test.cpp
rename to libs/sensor/tests/Sensor_test.cpp
index fbf282d..ede20c9 100644
--- a/libs/gui/tests/Sensor_test.cpp
+++ b/libs/sensor/tests/Sensor_test.cpp
@@ -16,7 +16,7 @@
 
 #define LOG_TAG "Sensor_test"
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 #include <hardware/sensors.h>
 #include <utils/Errors.h>
 
diff --git a/libs/vr/libdvrcommon/tests/numeric_test.cpp b/libs/vr/libdvrcommon/tests/numeric_test.cpp
index 1ee1447..a6a2182 100644
--- a/libs/vr/libdvrcommon/tests/numeric_test.cpp
+++ b/libs/vr/libdvrcommon/tests/numeric_test.cpp
@@ -1,5 +1,6 @@
 #include <gtest/gtest.h>
 
+#define EIGEN_NO_STATIC_ASSERT
 #include <private/dvr/numeric.h>
 
 using TestTypes = ::testing::Types<float, double, int>;
diff --git a/services/sensorservice/Android.mk b/services/sensorservice/Android.mk
index d61f26f..cfb7231 100644
--- a/services/sensorservice/Android.mk
+++ b/services/sensorservice/Android.mk
@@ -33,8 +33,7 @@
     libutils \
     liblog \
     libbinder \
-    libui \
-    libgui \
+    libsensor \
     libcrypto \
     libbase \
     libhidlbase \
@@ -45,6 +44,10 @@
 LOCAL_STATIC_LIBRARIES := \
     android.hardware.sensors@1.0-convert
 
+# our public headers depend on libsensor
+LOCAL_EXPORT_SHARED_LIBRARY_HEADERS := \
+    libsensor \
+
 LOCAL_MODULE:= libsensorservice
 
 include $(BUILD_SHARED_LIBRARY)
diff --git a/services/sensorservice/CorrectedGyroSensor.h b/services/sensorservice/CorrectedGyroSensor.h
index 68acd43..1d49e01 100644
--- a/services/sensorservice/CorrectedGyroSensor.h
+++ b/services/sensorservice/CorrectedGyroSensor.h
@@ -20,7 +20,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 
 #include "SensorInterface.h"
 
diff --git a/services/sensorservice/GravitySensor.h b/services/sensorservice/GravitySensor.h
index 8e33a73..483f468 100644
--- a/services/sensorservice/GravitySensor.h
+++ b/services/sensorservice/GravitySensor.h
@@ -20,7 +20,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 
 #include "SensorInterface.h"
 
diff --git a/services/sensorservice/LinearAccelerationSensor.h b/services/sensorservice/LinearAccelerationSensor.h
index 428baa6..aa4e54a 100644
--- a/services/sensorservice/LinearAccelerationSensor.h
+++ b/services/sensorservice/LinearAccelerationSensor.h
@@ -20,7 +20,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 
 #include "SensorInterface.h"
 #include "GravitySensor.h"
diff --git a/services/sensorservice/OrientationSensor.h b/services/sensorservice/OrientationSensor.h
index 30ff226..a3f2a99 100644
--- a/services/sensorservice/OrientationSensor.h
+++ b/services/sensorservice/OrientationSensor.h
@@ -20,7 +20,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 
 #include "SensorInterface.h"
 
diff --git a/services/sensorservice/RotationVectorSensor.h b/services/sensorservice/RotationVectorSensor.h
index 265b4c4..34deaa9 100644
--- a/services/sensorservice/RotationVectorSensor.h
+++ b/services/sensorservice/RotationVectorSensor.h
@@ -20,7 +20,7 @@
 #include <stdint.h>
 #include <sys/types.h>
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 
 #include "SensorDevice.h"
 #include "SensorInterface.h"
diff --git a/services/sensorservice/SensorDevice.h b/services/sensorservice/SensorDevice.h
index 55a745f..03552f6 100644
--- a/services/sensorservice/SensorDevice.h
+++ b/services/sensorservice/SensorDevice.h
@@ -19,7 +19,7 @@
 
 #include "SensorServiceUtils.h"
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 #include <stdint.h>
 #include <sys/types.h>
 #include <utils/KeyedVector.h>
diff --git a/services/sensorservice/SensorDirectConnection.h b/services/sensorservice/SensorDirectConnection.h
index 692ef0d..27458d4 100644
--- a/services/sensorservice/SensorDirectConnection.h
+++ b/services/sensorservice/SensorDirectConnection.h
@@ -22,10 +22,10 @@
 
 #include <binder/BinderService.h>
 
-#include <gui/Sensor.h>
-#include <gui/BitTube.h>
-#include <gui/ISensorServer.h>
-#include <gui/ISensorEventConnection.h>
+#include <sensor/Sensor.h>
+#include <sensor/BitTube.h>
+#include <sensor/ISensorServer.h>
+#include <sensor/ISensorEventConnection.h>
 
 #include "SensorService.h"
 
diff --git a/services/sensorservice/SensorEventConnection.cpp b/services/sensorservice/SensorEventConnection.cpp
index d84d36e..fad046c 100644
--- a/services/sensorservice/SensorEventConnection.cpp
+++ b/services/sensorservice/SensorEventConnection.cpp
@@ -17,7 +17,7 @@
 #include <sys/socket.h>
 #include <utils/threads.h>
 
-#include <gui/SensorEventQueue.h>
+#include <sensor/SensorEventQueue.h>
 
 #include "vec.h"
 #include "SensorEventConnection.h"
diff --git a/services/sensorservice/SensorEventConnection.h b/services/sensorservice/SensorEventConnection.h
index cd81ddd..c81e015 100644
--- a/services/sensorservice/SensorEventConnection.h
+++ b/services/sensorservice/SensorEventConnection.h
@@ -31,10 +31,10 @@
 
 #include <binder/BinderService.h>
 
-#include <gui/Sensor.h>
-#include <gui/BitTube.h>
-#include <gui/ISensorServer.h>
-#include <gui/ISensorEventConnection.h>
+#include <sensor/Sensor.h>
+#include <sensor/BitTube.h>
+#include <sensor/ISensorServer.h>
+#include <sensor/ISensorEventConnection.h>
 
 #include "SensorService.h"
 
diff --git a/services/sensorservice/SensorFusion.h b/services/sensorservice/SensorFusion.h
index ad636d5..8c0fbf9 100644
--- a/services/sensorservice/SensorFusion.h
+++ b/services/sensorservice/SensorFusion.h
@@ -24,7 +24,7 @@
 #include <utils/Singleton.h>
 #include <utils/String8.h>
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 
 #include "Fusion.h"
 
diff --git a/services/sensorservice/SensorInterface.h b/services/sensorservice/SensorInterface.h
index 0867dc2..b5375cb 100644
--- a/services/sensorservice/SensorInterface.h
+++ b/services/sensorservice/SensorInterface.h
@@ -17,7 +17,7 @@
 #ifndef ANDROID_SENSOR_INTERFACE_H
 #define ANDROID_SENSOR_INTERFACE_H
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 #include <utils/RefBase.h>
 
 // ---------------------------------------------------------------------------
diff --git a/services/sensorservice/SensorList.cpp b/services/sensorservice/SensorList.cpp
index 31c8251..ab08cac 100644
--- a/services/sensorservice/SensorList.cpp
+++ b/services/sensorservice/SensorList.cpp
@@ -190,6 +190,7 @@
                 if (s.isDirectChannelTypeSupported(SENSOR_DIRECT_MEM_TYPE_GRALLOC)) {
                     result.append("gralloc, ");
                 }
+                result.appendFormat("flag =0x%08x", static_cast<int>(s.getFlags()));
                 result.append("\n");
             }
             return true;
diff --git a/services/sensorservice/SensorList.h b/services/sensorservice/SensorList.h
index 8209d96..6b90ad9 100644
--- a/services/sensorservice/SensorList.h
+++ b/services/sensorservice/SensorList.h
@@ -20,7 +20,7 @@
 #include "SensorInterface.h"
 #include "SensorServiceUtils.h"
 
-#include <gui/Sensor.h>
+#include <sensor/Sensor.h>
 #include <utils/String8.h>
 #include <utils/Vector.h>
 
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index 143a3c5..c11df13 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -22,7 +22,7 @@
 #include <binder/PermissionCache.h>
 
 #include <cutils/ashmem.h>
-#include <gui/SensorEventQueue.h>
+#include <sensor/SensorEventQueue.h>
 
 #include <hardware/sensors.h>
 #include <hardware_legacy/power.h>
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
index eeedd4a..5583dad 100644
--- a/services/sensorservice/SensorService.h
+++ b/services/sensorservice/SensorService.h
@@ -22,9 +22,9 @@
 
 #include <binder/BinderService.h>
 #include <cutils/compiler.h>
-#include <gui/ISensorServer.h>
-#include <gui/ISensorEventConnection.h>
-#include <gui/Sensor.h>
+#include <sensor/ISensorServer.h>
+#include <sensor/ISensorEventConnection.h>
+#include <sensor/Sensor.h>
 
 #include <utils/AndroidThreads.h>
 #include <utils/KeyedVector.h>
diff --git a/services/sensorservice/tests/Android.mk b/services/sensorservice/tests/Android.mk
index 45296dd..e894655 100644
--- a/services/sensorservice/tests/Android.mk
+++ b/services/sensorservice/tests/Android.mk
@@ -5,7 +5,7 @@
 	sensorservicetest.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-	libcutils libutils libui libgui
+	libutils libsensor libandroid
 
 LOCAL_MODULE:= test-sensorservice
 
diff --git a/services/sensorservice/tests/sensorservicetest.cpp b/services/sensorservice/tests/sensorservicetest.cpp
index 186b60c..1cb0489 100644
--- a/services/sensorservice/tests/sensorservicetest.cpp
+++ b/services/sensorservice/tests/sensorservicetest.cpp
@@ -16,9 +16,9 @@
 
 #include <inttypes.h>
 #include <android/sensor.h>
-#include <gui/Sensor.h>
-#include <gui/SensorManager.h>
-#include <gui/SensorEventQueue.h>
+#include <sensor/Sensor.h>
+#include <sensor/SensorManager.h>
+#include <sensor/SensorEventQueue.h>
 #include <utils/Looper.h>
 
 using namespace android;
diff --git a/services/surfaceflinger/Android.mk b/services/surfaceflinger/Android.mk
index afaccd2..a317ea2 100644
--- a/services/surfaceflinger/Android.mk
+++ b/services/surfaceflinger/Android.mk
@@ -26,6 +26,7 @@
     DisplayHardware/FramebufferSurface.cpp \
     DisplayHardware/HWC2.cpp \
     DisplayHardware/HWC2On1Adapter.cpp \
+    DisplayHardware/MiniFence.cpp \
     DisplayHardware/PowerHAL.cpp \
     DisplayHardware/VirtualDisplaySurface.cpp \
     Effects/Daltonizer.cpp \
diff --git a/services/surfaceflinger/DisplayHardware/HWC2On1Adapter.cpp b/services/surfaceflinger/DisplayHardware/HWC2On1Adapter.cpp
index 4187890..13bf0b5 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2On1Adapter.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWC2On1Adapter.cpp
@@ -724,7 +724,7 @@
         }
 
         auto releaseFence = layer->getReleaseFence();
-        if (releaseFence != Fence::NO_FENCE) {
+        if (releaseFence != MiniFence::NO_FENCE) {
             if (outputsNonNull) {
                 outLayers[numWritten] = layer->getId();
                 outFences[numWritten] = releaseFence->dup();
@@ -2003,7 +2003,7 @@
     mReleaseFence.add(fenceFd);
 }
 
-const sp<Fence>& HWC2On1Adapter::Layer::getReleaseFence() const {
+const sp<MiniFence>& HWC2On1Adapter::Layer::getReleaseFence() const {
     return mReleaseFence.get();
 }
 
diff --git a/services/surfaceflinger/DisplayHardware/HWC2On1Adapter.h b/services/surfaceflinger/DisplayHardware/HWC2On1Adapter.h
index 408bc41..a1d2c88 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2On1Adapter.h
+++ b/services/surfaceflinger/DisplayHardware/HWC2On1Adapter.h
@@ -23,7 +23,7 @@
 #undef HWC2_INCLUDE_STRINGIFICATION
 #undef HWC2_USE_CPP11
 
-#include <ui/Fence.h>
+#include "MiniFence.h"
 
 #include <atomic>
 #include <map>
@@ -155,35 +155,35 @@
     class DeferredFence {
         public:
             DeferredFence()
-              : mFences({Fence::NO_FENCE, Fence::NO_FENCE}) {}
+              : mFences({MiniFence::NO_FENCE, MiniFence::NO_FENCE}) {}
 
             void add(int32_t fenceFd) {
-                mFences.emplace(new Fence(fenceFd));
+                mFences.emplace(new MiniFence(fenceFd));
                 mFences.pop();
             }
 
-            const sp<Fence>& get() const {
+            const sp<MiniFence>& get() const {
                 return mFences.front();
             }
 
         private:
             // There are always two fences in this queue.
-            std::queue<sp<Fence>> mFences;
+            std::queue<sp<MiniFence>> mFences;
     };
 
     class FencedBuffer {
         public:
-            FencedBuffer() : mBuffer(nullptr), mFence(Fence::NO_FENCE) {}
+            FencedBuffer() : mBuffer(nullptr), mFence(MiniFence::NO_FENCE) {}
 
             void setBuffer(buffer_handle_t buffer) { mBuffer = buffer; }
-            void setFence(int fenceFd) { mFence = new Fence(fenceFd); }
+            void setFence(int fenceFd) { mFence = new MiniFence(fenceFd); }
 
             buffer_handle_t getBuffer() const { return mBuffer; }
             int getFence() const { return mFence->dup(); }
 
         private:
             buffer_handle_t mBuffer;
-            sp<Fence> mFence;
+            sp<MiniFence> mFence;
     };
 
     class Display {
@@ -552,7 +552,7 @@
             uint32_t getZ() const { return mZ; }
 
             void addReleaseFence(int fenceFd);
-            const sp<Fence>& getReleaseFence() const;
+            const sp<MiniFence>& getReleaseFence() const;
 
             void setHwc1Id(size_t id) { mHwc1Id = id; }
             size_t getHwc1Id() const { return mHwc1Id; }
diff --git a/services/surfaceflinger/DisplayHardware/MiniFence.cpp b/services/surfaceflinger/DisplayHardware/MiniFence.cpp
new file mode 100644
index 0000000..ecfb063
--- /dev/null
+++ b/services/surfaceflinger/DisplayHardware/MiniFence.cpp
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "MiniFence.h"
+
+#include <unistd.h>
+
+namespace android {
+
+const sp<MiniFence> MiniFence::NO_FENCE = sp<MiniFence>(new MiniFence);
+
+MiniFence::MiniFence() :
+    mFenceFd(-1) {
+}
+
+MiniFence::MiniFence(int fenceFd) :
+    mFenceFd(fenceFd) {
+}
+
+MiniFence::~MiniFence() {
+    if (mFenceFd != -1) {
+        close(mFenceFd);
+    }
+}
+
+int MiniFence::dup() const {
+    return ::dup(mFenceFd);
+}
+}
diff --git a/services/surfaceflinger/DisplayHardware/MiniFence.h b/services/surfaceflinger/DisplayHardware/MiniFence.h
new file mode 100644
index 0000000..75de764
--- /dev/null
+++ b/services/surfaceflinger/DisplayHardware/MiniFence.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2017 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 MINIFENCE_H
+#define MINIFENCE_H
+
+#include <utils/RefBase.h>
+
+namespace android {
+
+/* MiniFence is a minimal re-implementation of Fence from libui. It exists to
+ * avoid linking the HWC2on1Adapter to libui and satisfy Treble requirements.
+ */
+class MiniFence : public LightRefBase<MiniFence> {
+public:
+    static const sp<MiniFence> NO_FENCE;
+
+    // Construct a new MiniFence object with an invalid file descriptor.
+    MiniFence();
+
+    // Construct a new MiniFence object to manage a given fence file descriptor.
+    // When the new MiniFence object is destructed the file descriptor will be
+    // closed.
+    explicit MiniFence(int fenceFd);
+
+    // Not copyable or movable.
+    MiniFence(const MiniFence& rhs) = delete;
+    MiniFence& operator=(const MiniFence& rhs) = delete;
+    MiniFence(MiniFence&& rhs) = delete;
+    MiniFence& operator=(MiniFence&& rhs) = delete;
+
+    // Return a duplicate of the fence file descriptor. The caller is
+    // responsible for closing the returned file descriptor. On error, -1 will
+    // be returned and errno will indicate the problem.
+    int dup() const;
+
+private:
+    // Only allow instantiation using ref counting.
+    friend class LightRefBase<MiniFence>;
+    ~MiniFence();
+
+    int mFenceFd;
+
+};
+}
+#endif //MINIFENCE_H
diff --git a/services/surfaceflinger/EventThread.cpp b/services/surfaceflinger/EventThread.cpp
index d1bc7eb..486bce4 100644
--- a/services/surfaceflinger/EventThread.cpp
+++ b/services/surfaceflinger/EventThread.cpp
@@ -21,7 +21,7 @@
 
 #include <cutils/compiler.h>
 
-#include <gui/BitTube.h>
+#include <private/gui/BitTube.h>
 #include <gui/IDisplayEventConnection.h>
 #include <gui/DisplayEventReceiver.h>
 
diff --git a/services/surfaceflinger/MessageQueue.cpp b/services/surfaceflinger/MessageQueue.cpp
index 974c7a3..debea58 100644
--- a/services/surfaceflinger/MessageQueue.cpp
+++ b/services/surfaceflinger/MessageQueue.cpp
@@ -25,7 +25,7 @@
 #include <utils/Log.h>
 
 #include <gui/IDisplayEventConnection.h>
-#include <gui/BitTube.h>
+#include <private/gui/BitTube.h>
 
 #include "MessageQueue.h"
 #include "EventThread.h"
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index daeac27..46f5a1f 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -40,7 +40,6 @@
 #include <ui/DisplayInfo.h>
 #include <ui/DisplayStatInfo.h>
 
-#include <gui/BitTube.h>
 #include <gui/BufferQueue.h>
 #include <gui/GuiConfig.h>
 #include <gui/IDisplayEventConnection.h>
@@ -1595,6 +1594,9 @@
                                     nullptr);
                         }
                     } else {
+                        // WM changes displayDevice->layerStack upon sleep/awake.
+                        // Here we make sure we delete the HWC layers even if
+                        // WM changed their layer stack.
                         layer->setHwcLayer(displayDevice->getHwcDisplayId(),
                                 nullptr);
                     }
diff --git a/services/surfaceflinger/SurfaceFlinger_hwc1.cpp b/services/surfaceflinger/SurfaceFlinger_hwc1.cpp
index fe8dd0c..6cd7152 100644
--- a/services/surfaceflinger/SurfaceFlinger_hwc1.cpp
+++ b/services/surfaceflinger/SurfaceFlinger_hwc1.cpp
@@ -38,7 +38,6 @@
 #include <ui/DisplayInfo.h>
 #include <ui/DisplayStatInfo.h>
 
-#include <gui/BitTube.h>
 #include <gui/BufferQueue.h>
 #include <gui/GuiConfig.h>
 #include <gui/IDisplayEventConnection.h>
diff --git a/services/vr/virtual_touchpad/VirtualTouchpadClient.cpp b/services/vr/virtual_touchpad/VirtualTouchpadClient.cpp
index 23a2e31..175173f 100644
--- a/services/vr/virtual_touchpad/VirtualTouchpadClient.cpp
+++ b/services/vr/virtual_touchpad/VirtualTouchpadClient.cpp
@@ -12,19 +12,20 @@
  public:
   VirtualTouchpadClientImpl(sp<IVirtualTouchpadService> service)
       : service_(service) {}
-  ~VirtualTouchpadClientImpl() {}
+  ~VirtualTouchpadClientImpl() override {}
 
-  status_t Touch(float x, float y, float pressure) override {
+  status_t Touch(int touchpad,
+                 float x, float y, float pressure) override {
     if (service_ == nullptr) {
       return NO_INIT;
     }
-    return service_->touch(x, y, pressure).transactionError();
+    return service_->touch(touchpad, x, y, pressure).transactionError();
   }
-  status_t ButtonState(int buttons) override {
+  status_t ButtonState(int touchpad, int buttons) override {
     if (service_ == nullptr) {
       return NO_INIT;
     }
-    return service_->buttonState(buttons).transactionError();
+    return service_->buttonState(touchpad, buttons).transactionError();
   }
 
  private:
diff --git a/services/vr/virtual_touchpad/VirtualTouchpadEvdev.cpp b/services/vr/virtual_touchpad/VirtualTouchpadEvdev.cpp
index ae31156..f25a2ad 100644
--- a/services/vr/virtual_touchpad/VirtualTouchpadEvdev.cpp
+++ b/services/vr/virtual_touchpad/VirtualTouchpadEvdev.cpp
@@ -56,15 +56,17 @@
   return injector_->GetError();
 }
 
-int VirtualTouchpadEvdev::Touch(float x, float y, float pressure) {
+int VirtualTouchpadEvdev::Touch(int touchpad, float x, float y,
+                                float pressure) {
+  (void)touchpad; // TODO(b/35992608) Support multiple virtual touchpad devices.
   if ((x < 0.0f) || (x >= 1.0f) || (y < 0.0f) || (y >= 1.0f)) {
     return EINVAL;
   }
   int32_t device_x = x * kWidth;
   int32_t device_y = y * kHeight;
   touches_ = ((touches_ & 1) << 1) | (pressure > 0);
-  ALOGV("(%f,%f) %f -> (%" PRId32 ",%" PRId32 ") %d",
-        x, y, pressure, device_x, device_y, touches_);
+  ALOGV("(%f,%f) %f -> (%" PRId32 ",%" PRId32 ") %d", x, y, pressure, device_x,
+        device_y, touches_);
 
   if (!injector_) {
     return EvdevInjector::ERROR_SEQUENCING;
@@ -101,7 +103,8 @@
   return injector_->GetError();
 }
 
-int VirtualTouchpadEvdev::ButtonState(int buttons) {
+int VirtualTouchpadEvdev::ButtonState(int touchpad, int buttons) {
+  (void)touchpad; // TODO(b/35992608) Support multiple virtual touchpad devices.
   const int changes = last_motion_event_buttons_ ^ buttons;
   if (!changes) {
     return 0;
@@ -117,10 +120,9 @@
   }
   injector_->ResetError();
   if (changes & AMOTION_EVENT_BUTTON_BACK) {
-    injector_->SendKey(BTN_BACK,
-                       (buttons & AMOTION_EVENT_BUTTON_BACK)
-                           ? EvdevInjector::KEY_PRESS
-                           : EvdevInjector::KEY_RELEASE);
+    injector_->SendKey(BTN_BACK, (buttons & AMOTION_EVENT_BUTTON_BACK)
+                                     ? EvdevInjector::KEY_PRESS
+                                     : EvdevInjector::KEY_RELEASE);
   }
   last_motion_event_buttons_ = buttons;
   return injector_->GetError();
diff --git a/services/vr/virtual_touchpad/VirtualTouchpadEvdev.h b/services/vr/virtual_touchpad/VirtualTouchpadEvdev.h
index c763529..ec8006b 100644
--- a/services/vr/virtual_touchpad/VirtualTouchpadEvdev.h
+++ b/services/vr/virtual_touchpad/VirtualTouchpadEvdev.h
@@ -18,12 +18,12 @@
   static sp<VirtualTouchpad> Create();
 
   // VirtualTouchpad implementation:
-  status_t Touch(float x, float y, float pressure) override;
-  status_t ButtonState(int buttons) override;
+  status_t Touch(int touchpad, float x, float y, float pressure) override;
+  status_t ButtonState(int touchpad, int buttons) override;
 
  protected:
   VirtualTouchpadEvdev() {}
-  ~VirtualTouchpadEvdev() {}
+  ~VirtualTouchpadEvdev() override {}
   status_t Initialize();
 
   // Must be called only between construction and Initialize().
diff --git a/services/vr/virtual_touchpad/VirtualTouchpadService.cpp b/services/vr/virtual_touchpad/VirtualTouchpadService.cpp
index 3fcb8fc..a1f281c 100644
--- a/services/vr/virtual_touchpad/VirtualTouchpadService.cpp
+++ b/services/vr/virtual_touchpad/VirtualTouchpadService.cpp
@@ -8,16 +8,15 @@
 namespace android {
 namespace dvr {
 
-binder::Status VirtualTouchpadService::touch(float x, float y, float pressure) {
-  const status_t error = touchpad_->Touch(x, y, pressure);
-  return error ? binder::Status::fromStatusT(error)
-               : binder::Status::ok();
+binder::Status VirtualTouchpadService::touch(int touchpad,
+                                             float x, float y, float pressure) {
+  const status_t error = touchpad_->Touch(touchpad, x, y, pressure);
+  return error ? binder::Status::fromStatusT(error) : binder::Status::ok();
 }
 
-binder::Status VirtualTouchpadService::buttonState(int buttons) {
-  const status_t error = touchpad_->ButtonState(buttons);
-  return error ? binder::Status::fromStatusT(error)
-               : binder::Status::ok();
+binder::Status VirtualTouchpadService::buttonState(int touchpad, int buttons) {
+  const status_t error = touchpad_->ButtonState(touchpad, buttons);
+  return error ? binder::Status::fromStatusT(error) : binder::Status::ok();
 }
 
 }  // namespace dvr
diff --git a/services/vr/virtual_touchpad/VirtualTouchpadService.h b/services/vr/virtual_touchpad/VirtualTouchpadService.h
index b832c8f..9b880b2 100644
--- a/services/vr/virtual_touchpad/VirtualTouchpadService.h
+++ b/services/vr/virtual_touchpad/VirtualTouchpadService.h
@@ -15,11 +15,12 @@
  public:
   VirtualTouchpadService(sp<VirtualTouchpad> touchpad)
       : touchpad_(touchpad) {}
+  ~VirtualTouchpadService() override {}
 
  protected:
   // Implements IVirtualTouchpadService.
-  binder::Status touch(float x, float y, float pressure) override;
-  binder::Status buttonState(int buttons) override;
+  binder::Status touch(int touchpad, float x, float y, float pressure) override;
+  binder::Status buttonState(int touchpad, int buttons) override;
 
  private:
   sp<VirtualTouchpad> touchpad_;
diff --git a/services/vr/virtual_touchpad/aidl/android/dvr/VirtualTouchpadService.aidl b/services/vr/virtual_touchpad/aidl/android/dvr/VirtualTouchpadService.aidl
index c2044da..496c5e2 100644
--- a/services/vr/virtual_touchpad/aidl/android/dvr/VirtualTouchpadService.aidl
+++ b/services/vr/virtual_touchpad/aidl/android/dvr/VirtualTouchpadService.aidl
@@ -8,18 +8,20 @@
   /**
    * Generate a simulated touch event.
    *
+   * @param touchpad Selects touchpad.
    * @param x Horizontal touch position.
    * @param y Vertical touch position.
    * @param pressure Touch pressure; use 0.0 for no touch (lift or hover).
    *
    * Position values in the range [0.0, 1.0) map to the screen.
    */
-  void touch(float x, float y, float pressure);
+  void touch(int touchpad, float x, float y, float pressure);
 
   /**
    * Generate a simulated touchpad button state event.
    *
+   * @param touchpad Selects touchpad.
    * @param buttons A union of MotionEvent BUTTON_* values.
    */
-  void buttonState(int buttons);
+  void buttonState(int touchpad, int buttons);
 }
diff --git a/services/vr/virtual_touchpad/include/VirtualTouchpad.h b/services/vr/virtual_touchpad/include/VirtualTouchpad.h
index bbaf69b..d24d121 100644
--- a/services/vr/virtual_touchpad/include/VirtualTouchpad.h
+++ b/services/vr/virtual_touchpad/include/VirtualTouchpad.h
@@ -12,6 +12,11 @@
 //
 class VirtualTouchpad : public RefBase {
  public:
+  enum : int {
+    PRIMARY = 0,
+    VIRTUAL = 1,
+  };
+
   // Create a virtual touchpad.
   // Implementations should provide this, and hide their constructors.
   // For the user, switching implementations should be as simple as changing
@@ -22,6 +27,7 @@
 
   // Generate a simulated touch event.
   //
+  // @param touchpad Touchpad selector index.
   // @param x Horizontal touch position.
   // @param y Vertical touch position.
   //            Values must be in the range [0.0, 1.0).
@@ -30,21 +36,22 @@
   //            is binary. Use 0.0f for no contact.
   // @returns OK on success.
   //
-  virtual status_t Touch(float x, float y, float pressure) = 0;
+  virtual status_t Touch(int touchpad, float x, float y, float pressure) = 0;
 
   // Generate a simulated touchpad button state.
   //
+  // @param touchpad Touchpad selector index.
   // @param buttons A union of MotionEvent BUTTON_* values.
   // @returns OK on success.
   //
   // Currently only BUTTON_BACK is supported, as the implementation
   // restricts itself to operations actually required by VrWindowManager.
   //
-  virtual status_t ButtonState(int buttons) = 0;
+  virtual status_t ButtonState(int touchpad, int buttons) = 0;
 
  protected:
   VirtualTouchpad() {}
-  virtual ~VirtualTouchpad() {}
+  ~VirtualTouchpad() override {}
 
  private:
   VirtualTouchpad(const VirtualTouchpad&) = delete;
diff --git a/services/vr/virtual_touchpad/include/VirtualTouchpadClient.h b/services/vr/virtual_touchpad/include/VirtualTouchpadClient.h
index 46bec0e..dd9c265 100644
--- a/services/vr/virtual_touchpad/include/VirtualTouchpadClient.h
+++ b/services/vr/virtual_touchpad/include/VirtualTouchpadClient.h
@@ -13,12 +13,12 @@
  public:
   // VirtualTouchpad implementation:
   static sp<VirtualTouchpad> Create();
-  status_t Touch(float x, float y, float pressure) override;
-  status_t ButtonState(int buttons) override;
+  status_t Touch(int touchpad, float x, float y, float pressure) override;
+  status_t ButtonState(int touchpad, int buttons) override;
 
  protected:
   VirtualTouchpadClient() {}
-  virtual ~VirtualTouchpadClient() {}
+  ~VirtualTouchpadClient() override {}
 
  private:
   VirtualTouchpadClient(const VirtualTouchpadClient&) = delete;
diff --git a/services/vr/virtual_touchpad/tests/VirtualTouchpad_test.cpp b/services/vr/virtual_touchpad/tests/VirtualTouchpad_test.cpp
index b448fd1..469a2d0 100644
--- a/services/vr/virtual_touchpad/tests/VirtualTouchpad_test.cpp
+++ b/services/vr/virtual_touchpad/tests/VirtualTouchpad_test.cpp
@@ -15,6 +15,7 @@
 
 class UInputForTesting : public EvdevInjector::UInput {
  public:
+  ~UInputForTesting() override {}
   void WriteInputEvent(uint16_t type, uint16_t code, int32_t value) {
     struct input_event event;
     memset(&event, 0, sizeof(event));
@@ -30,7 +31,7 @@
 class UInputRecorder : public UInputForTesting {
  public:
   UInputRecorder() {}
-  virtual ~UInputRecorder() {}
+  ~UInputRecorder() override {}
 
   const std::string& GetString() const { return s_; }
   void Reset() { s_.clear(); }
@@ -157,7 +158,7 @@
 
   expect.Reset();
   record.Reset();
-  int touch_status = touchpad->Touch(0, 0, 0);
+  int touch_status = touchpad->Touch(VirtualTouchpad::PRIMARY, 0, 0, 0);
   EXPECT_EQ(0, touch_status);
   expect.WriteInputEvent(EV_ABS, ABS_MT_SLOT, 0);
   expect.WriteInputEvent(EV_ABS, ABS_MT_TRACKING_ID, 0);
@@ -168,7 +169,7 @@
 
   expect.Reset();
   record.Reset();
-  touch_status = touchpad->Touch(0.25f, 0.75f, 0.5f);
+  touch_status = touchpad->Touch(VirtualTouchpad::PRIMARY, 0.25f, 0.75f, 0.5f);
   EXPECT_EQ(0, touch_status);
   expect.WriteInputEvent(EV_ABS, ABS_MT_TRACKING_ID, 0);
   expect.WriteInputEvent(EV_ABS, ABS_MT_POSITION_X, 0.25f * width);
@@ -179,7 +180,7 @@
 
   expect.Reset();
   record.Reset();
-  touch_status = touchpad->Touch(1.0f, 1.0f, 1.0f);
+  touch_status = touchpad->Touch(VirtualTouchpad::PRIMARY, 1.0f, 1.0f, 1.0f);
   EXPECT_EQ(0, touch_status);
   expect.WriteInputEvent(EV_ABS, ABS_MT_TRACKING_ID, 0);
   expect.WriteInputEvent(EV_ABS, ABS_MT_POSITION_X, width);
@@ -189,7 +190,8 @@
 
   expect.Reset();
   record.Reset();
-  touch_status = touchpad->Touch(0.25f, 0.75f, -0.01f);
+  touch_status =
+      touchpad->Touch(VirtualTouchpad::PRIMARY, 0.25f, 0.75f, -0.01f);
   EXPECT_EQ(0, touch_status);
   expect.WriteInputEvent(EV_KEY, BTN_TOUCH, EvdevInjector::KEY_RELEASE);
   expect.WriteInputEvent(EV_ABS, ABS_MT_TRACKING_ID, -1);
@@ -198,7 +200,8 @@
 
   expect.Reset();
   record.Reset();
-  touch_status = touchpad->ButtonState(AMOTION_EVENT_BUTTON_BACK);
+  touch_status = touchpad->ButtonState(VirtualTouchpad::PRIMARY,
+                                       AMOTION_EVENT_BUTTON_BACK);
   EXPECT_EQ(0, touch_status);
   expect.WriteInputEvent(EV_KEY, BTN_BACK, EvdevInjector::KEY_PRESS);
   expect.WriteInputEvent(EV_SYN, SYN_REPORT, 0);
@@ -206,13 +209,14 @@
 
   expect.Reset();
   record.Reset();
-  touch_status = touchpad->ButtonState(AMOTION_EVENT_BUTTON_BACK);
+  touch_status = touchpad->ButtonState(VirtualTouchpad::PRIMARY,
+                                       AMOTION_EVENT_BUTTON_BACK);
   EXPECT_EQ(0, touch_status);
   EXPECT_EQ(expect.GetString(), record.GetString());
 
   expect.Reset();
   record.Reset();
-  touch_status = touchpad->ButtonState(0);
+  touch_status = touchpad->ButtonState(VirtualTouchpad::PRIMARY, 0);
   EXPECT_EQ(0, touch_status);
   expect.WriteInputEvent(EV_KEY, BTN_BACK, EvdevInjector::KEY_RELEASE);
   expect.WriteInputEvent(EV_SYN, SYN_REPORT, 0);
@@ -226,20 +230,21 @@
   UInputRecorder expect;
   UInputRecorder record;
   EvdevInjectorForTesting injector(record);
-  sp<VirtualTouchpad> touchpad(
-      VirtualTouchpadForTesting::Create(injector));
+  sp<VirtualTouchpad> touchpad(VirtualTouchpadForTesting::Create(injector));
 
   // Touch off-screen should return an error,
   // and should not result in any system calls.
   expect.Reset();
   record.Reset();
-  status_t touch_status = touchpad->Touch(-0.25f, 0.75f, 1.0f);
+  status_t touch_status =
+      touchpad->Touch(VirtualTouchpad::PRIMARY, -0.25f, 0.75f, 1.0f);
   EXPECT_NE(OK, touch_status);
-  touch_status = touchpad->Touch(0.25f, -0.75f, 1.0f);
+  touch_status =
+      touchpad->Touch(VirtualTouchpad::PRIMARY, 0.25f, -0.75f, 1.0f);
   EXPECT_NE(OK, touch_status);
-  touch_status = touchpad->Touch(1.25f, 0.75f, 1.0f);
+  touch_status = touchpad->Touch(VirtualTouchpad::PRIMARY, 1.25f, 0.75f, 1.0f);
   EXPECT_NE(OK, touch_status);
-  touch_status = touchpad->Touch(0.25f, 1.75f, 1.0f);
+  touch_status = touchpad->Touch(VirtualTouchpad::PRIMARY, 0.25f, 1.75f, 1.0f);
   EXPECT_NE(OK, touch_status);
   EXPECT_EQ(expect.GetString(), record.GetString());
 
@@ -247,7 +252,8 @@
   // and should not result in any system calls.
   expect.Reset();
   record.Reset();
-  touch_status = touchpad->ButtonState(AMOTION_EVENT_BUTTON_FORWARD);
+  touch_status = touchpad->ButtonState(VirtualTouchpad::PRIMARY,
+                                       AMOTION_EVENT_BUTTON_FORWARD);
   EXPECT_NE(OK, touch_status);
   EXPECT_EQ(expect.GetString(), record.GetString());
 }
diff --git a/services/vr/vr_window_manager/application.cpp b/services/vr/vr_window_manager/application.cpp
index dba797f..24087c9 100644
--- a/services/vr/vr_window_manager/application.cpp
+++ b/services/vr/vr_window_manager/application.cpp
@@ -294,7 +294,10 @@
   bool changed = is_visible_ != visible;
   if (changed) {
     is_visible_ = visible;
-    dvrGraphicsSurfaceSetVisible(graphics_context_, is_visible_);
+    // TODO (alexst): b/36036583 Disable vr_wm visibility until we figure out
+    // why it's always on top. Still make it visible in debug mode.
+    if (debug_mode_)
+      dvrGraphicsSurfaceSetVisible(graphics_context_, is_visible_);
     OnVisibilityChanged(is_visible_);
   }
 }
diff --git a/services/vr/vr_window_manager/shell_view.cpp b/services/vr/vr_window_manager/shell_view.cpp
index 7321ed0..fae1dd9 100644
--- a/services/vr/vr_window_manager/shell_view.cpp
+++ b/services/vr/vr_window_manager/shell_view.cpp
@@ -721,6 +721,7 @@
   }
 
   const android::status_t status = virtual_touchpad_->Touch(
+      VirtualTouchpad::PRIMARY,
       hit_location_in_window_coord_.x() / size_.x(),
       hit_location_in_window_coord_.y() / size_.y(),
       is_touching_ ? 1.0f : 0.0f);
@@ -747,8 +748,8 @@
     return false;
   }
 
-  const android::status_t status =
-      virtual_touchpad_->ButtonState(touchpad_buttons_);
+  const android::status_t status = virtual_touchpad_->ButtonState(
+      VirtualTouchpad::PRIMARY, touchpad_buttons_);
   if (status != OK) {
     ALOGE("touchpad button failed: %d %d", touchpad_buttons_, status);
   }