am b96f1083: Merge "Move libhardware of <asm/page.h>."

* commit 'b96f1083b8d10f3e33b64f0da943dedfdb25b557':
  Move libhardware of <asm/page.h>.
diff --git a/include/hardware/bt_gatt_client.h b/include/hardware/bt_gatt_client.h
index d6b0cb4..cf4fabe 100644
--- a/include/hardware/bt_gatt_client.h
+++ b/include/hardware/bt_gatt_client.h
@@ -278,7 +278,9 @@
     /** Set the advertising data or scan response data */
     bt_status_t (*set_adv_data)(int server_if, bool set_scan_rsp, bool include_name,
                     bool include_txpower, int min_interval, int max_interval, int appearance,
-                    uint16_t manufacturer_len, char* manufacturer_data);
+                    uint16_t manufacturer_len, char* manufacturer_data,
+                    uint16_t service_data_len, char* service_data,
+                    uint16_t service_uuid_len, char* service_uuid);
 
     /** Test mode interface */
     bt_status_t (*test_command)( int command, btgatt_test_params_t* params);
diff --git a/include/hardware/hdmi_cec.h b/include/hardware/hdmi_cec.h
new file mode 100644
index 0000000..938e9dc
--- /dev/null
+++ b/include/hardware/hdmi_cec.h
@@ -0,0 +1,282 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_HDMI_CEC_H
+#define ANDROID_INCLUDE_HARDWARE_HDMI_CEC_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+
+#include <hardware/hardware.h>
+
+__BEGIN_DECLS
+
+#define HDMI_CEC_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0)
+#define HDMI_CEC_MODULE_API_VERSION_CURRENT HDMI_MODULE_API_VERSION_1_0
+
+#define HDMI_CEC_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0)
+#define HDMI_CEC_DEVICE_API_VERSION_CURRENT HDMI_DEVICE_API_VERSION_1_0
+
+#define HDMI_CEC_HARDWARE_MODULE_ID "hdmi_cec"
+#define HDMI_CEC_HARDWARE_INTERFACE "hdmi_cec_hw_if"
+
+typedef enum cec_device_type {
+    CEC_DEVICE_TV = 0,
+    CEC_DEVICE_RECORDER = 1,
+    CEC_DEVICE_RESERVED = 2,
+    CEC_DEVICE_TUNER = 3,
+    CEC_DEVICE_PLAYBACK = 4,
+    CEC_DEVICE_AUDIO_SYSTEM = 5,
+    CEC_DEVICE_MAX = CEC_DEVICE_AUDIO_SYSTEM
+} cec_device_type_t;
+
+typedef enum cec_logical_address {
+    CEC_ADDR_TV = 0,
+    CEC_ADDR_RECORDER_1 = 1,
+    CEC_ADDR_RECORDER_2 = 2,
+    CEC_ADDR_TUNER_1 = 3,
+    CEC_ADDR_PLAYBACK_1 = 4,
+    CEC_ADDR_AUDIO_SYSTEM = 5,
+    CEC_ADDR_TUNER_2 = 6,
+    CEC_ADDR_TUNER_3 = 7,
+    CEC_ADDR_PLAYBACK_2 = 8,
+    CEC_ADDR_RECORDER_3 = 9,
+    CEC_ADDR_TUNER_4 = 10,
+    CEC_ADDR_PLAYBACK_3 = 11,
+    CEC_ADDR_RESERVED_1 = 12,
+    CEC_ADDR_RESERVED_2 = 13,
+    CEC_ADDR_FREE_USE = 14,
+    CEC_ADDR_UNREGISTERED = 15,
+    CEC_ADDR_BROADCAST = 15
+} cec_logical_address_t;
+
+/*
+ * HDMI CEC messages
+ */
+enum cec_message_type {
+    CEC_MESSAGE_FEATURE_ABORT = 0x00,
+    CEC_MESSAGE_IMAGE_VIEW_ON = 0x04,
+    CEC_MESSAGE_TUNER_STEP_INCREMENT = 0x05,
+    CEC_MESSAGE_TUNER_STEP_DECREMENT = 0x06,
+    CEC_MESSAGE_TUNER_DEVICE_STATUS = 0x07,
+    CEC_MESSAGE_GIVE_TUNER_DEVICE_STATUS = 0x08,
+    CEC_MESSAGE_RECORD_ON = 0x09,
+    CEC_MESSAGE_RECORD_STATUS = 0x0A,
+    CEC_MESSAGE_RECORD_OFF = 0x0B,
+    CEC_MESSAGE_TEXT_VIEW_ON = 0x0D,
+    CEC_MESSAGE_RECORD_TV_SCREEN = 0x0F,
+    CEC_MESSAGE_GIVE_DECK_STATUS = 0x1A,
+    CEC_MESSAGE_DECK_STATUS = 0x1B,
+    CEC_MESSAGE_SET_MENU_LANGUAGE = 0x32,
+    CEC_MESSAGE_CLEAR_ANALOG_TIMER = 0x33,
+    CEC_MESSAGE_SET_ANALOG_TIMER = 0x34,
+    CEC_MESSAGE_TIMER_STATUS = 0x35,
+    CEC_MESSAGE_STANDBY = 0x36,
+    CEC_MESSAGE_PLAY = 0x41,
+    CEC_MESSAGE_DECK_CONTROL = 0x42,
+    CEC_MESSAGE_TIMER_CLEARED_STATUS = 0x043,
+    CEC_MESSAGE_USER_CONTROL_PRESSED = 0x44,
+    CEC_MESSAGE_USER_CONTROL_RELEASED = 0x45,
+    CEC_MESSAGE_GET_OSD_NAME = 0x46,
+    CEC_MESSAGE_SET_OSD_NAME = 0x47,
+    CEC_MESSAGE_SET_OSD_STRING = 0x64,
+    CEC_MESSAGE_SET_TIMER_PROGRAM_TITLE = 0x67,
+    CEC_MESSAGE_SYSTEM_AUDIO_MODE_REQUEST = 0x70,
+    CEC_MESSAGE_GIVE_AUDIO_STATUS = 0x71,
+    CEC_MESSAGE_SET_SYSTEM_AUDIO_MODE = 0x72,
+    CEC_MESSAGE_REPORT_AUDIO_STATUS = 0x7A,
+    CEC_MESSAGE_GIVE_SYSTEM_AUDIO_MODE_STATUS = 0x7D,
+    CEC_MESSAGE_SYSTEM_AUDIO_MODE_STATUS = 0x7E,
+    CEC_MESSAGE_ROUTING_CHANGE = 0x80,
+    CEC_MESSAGE_ROUTING_INFORMATION = 0x81,
+    CEC_MESSAGE_ACTIVE_SOURCE = 0x82,
+    CEC_MESSAGE_GIVE_PHYSICAL_ADDRESS = 0x83,
+    CEC_MESSAGE_REPORT_PHYSICAL_ADDRESS = 0x84,
+    CEC_MESSAGE_REQUEST_ACTIVE_SOURCE = 0x85,
+    CEC_MESSAGE_SET_STREAM_PATH = 0x86,
+    CEC_MESSAGE_DEVICE_VENDOR_ID = 0x87,
+    CEC_MESSAGE_VENDOR_COMMAND = 0x89,
+    CEC_MESSAGE_VENDOR_REMOTE_BUTTON_DOWN = 0x8A,
+    CEC_MESSAGE_VENDOR_REMOTE_BUTTON_UP = 0x8B,
+    CEC_MESSAGE_GIVE_DEVICE_VENDOR_ID = 0x8C,
+    CEC_MESSAGE_MENU_REQUEST = 0x8D,
+    CEC_MESSAGE_MENU_STATUS = 0x8E,
+    CEC_MESSAGE_GIVE_DEVICE_POWER_STATUS = 0x8F,
+    CEC_MESSAGE_REPORT_POWER_STATUS = 0x90,
+    CEC_MESSAGE_GET_MENU_LANGUAGE = 0x91,
+    CEC_MESSAGE_SELECT_ANALOG_SERVICE = 0x92,
+    CEC_MESSAGE_SELECT_DIGITAL_SERVICE = 0x93,
+    CEC_MESSAGE_SET_DIGITAL_TIMER = 0x97,
+    CEC_MESSAGE_CLEAR_DIGITAL_TIMER = 0x99,
+    CEC_MESSAGE_SET_AUDIO_RATE = 0x9A,
+    CEC_MESSAGE_INACTIVE_SOURCE = 0x9D,
+    CEC_MESSAGE_CEC_VERSION = 0x9E,
+    CEC_MESSAGE_GET_CEC_VERSION = 0x9F,
+    CEC_MESSAGE_VENDOR_COMMAND_WITH_ID = 0xA0,
+    CEC_MESSAGE_CLEAR_EXTERNAL_TIMER = 0xA1,
+    CEC_MESSAGE_SET_EXTERNAL_TIMER = 0xA2
+};
+
+/*
+ * HDMI event type. used for hdmi_event_t.
+ */
+enum {
+    HDMI_EVENT_CEC_MESSAGE = 1,
+    HDMI_EVENT_HOT_PLUG = 2
+};
+
+/*
+ * HDMI hotplug event type. Used when the event
+ * type is HDMI_EVENT_HOT_PLUG.
+ */
+enum {
+    HDMI_NOT_CONNECTED = 0,
+    HDMI_CONNECTED = 1
+};
+
+/*
+ * Maximum length in bytes of cec message body (exclude header block),
+ * should not exceed 16 (spec CEC 6 Frame Description)
+ */
+#define CEC_MESSAGE_BODY_MAX_LENGTH 16
+
+typedef struct cec_message {
+    /*
+     * logical address of sender
+     */
+    cec_logical_address_t initiator;
+
+    /*
+     * logical address of receiver
+     */
+    cec_logical_address_t destination;
+
+    /*
+     * length in bytes of body, range [0, CEC_MESSAGE_BODY_MAX_LENGTH]
+     */
+    size_t length;
+    unsigned char body[CEC_MESSAGE_BODY_MAX_LENGTH];
+} cec_message_t;
+
+typedef struct hotplug_event {
+    /*
+     * true if the cable is connected; otherwise false.
+     */
+    int connected;
+} hotplug_event_t;
+
+/*
+ * HDMI event generated from HAL.
+ */
+typedef struct hdmi_event {
+    int type;
+    struct hdmi_cec_device* dev;
+    union {
+        cec_message_t cec;
+        hotplug_event_t hotplug;
+    };
+} hdmi_event_t;
+
+/*
+ * Callback function type that will be called by HAL implementation.
+ * Services can not close/open the device in the callback.
+ */
+typedef void (*event_callback_t)(const hdmi_event_t* event);
+
+typedef struct hdmi_cec_module {
+    struct hw_module_t common;
+} hdmi_module_t;
+
+/*
+ * HDMI-CEC HAL interface definition.
+ */
+typedef struct hdmi_cec_device {
+    struct hw_device_t common;
+
+    /*
+     * (*allocate_logical_address)() allocates a new logical address
+     * for a given device type. The address is written to addr. The HAL
+     * implementation is also expected to configure itself to start receiving
+     * the messages addressed to the allocated one. If allocation
+     * is not successful the addr will be set to CEC_ADDR_UNREGISTERED.
+     *
+     * Returns 0 on success or -errno on error.
+     *
+     */
+    int (*allocate_logical_address)(const struct hdmi_cec_device* dev,
+            int device_type, cec_logical_address_t* addr);
+
+    /*
+     * (*get_physical_address)() returns the CEC physical address. The
+     * address is written to addr.
+     *
+     * The physical address depends on the topology of the network formed
+     * by connected HDMI devices. It is therefore likely to change if the cable
+     * is plugged off and on again. It is advised to call get_physical_address
+     * to get the updated address when hot plug event takes place.
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int (*get_physical_address)(const struct hdmi_cec_device* dev, uint16_t* addr);
+
+    /*
+     * (*send_message)() transmits HDMI-CEC message to other HDMI device.
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int (*send_message)(const struct hdmi_cec_device* dev,
+            const cec_message_t *);
+
+    /*
+     * (*register_event_callback)() registers a callback that HDMI-CEC HAL
+     * can later use for incoming CEC messages or internal HDMI events.
+     */
+    void (*register_event_callback)(const struct hdmi_cec_device* dev,
+            event_callback_t callback);
+
+    /*
+     * (*get_version)() returns the CEC version supported by underlying
+     * hardware. The version this HAL interface is based on is 0x04,
+     * which corresponds to 1.3a.
+     */
+    void (*get_version)(const struct hdmi_cec_device* dev, int* version);
+
+    /*
+     * (*get_vendor_id)() returns the identifier of the vendor. It is
+     * the 24-bit unique company ID obtained from the IEEE Registration
+     * Authority Committee (RAC).
+     */
+    void (*get_vendor_id)(const struct hdmi_cec_device* dev, uint32_t* vendor_id);
+
+    /* Reserved for future use to maximum 16 functions. Must be NULL. */
+    void* reserved[16 - 6];
+} hdmi_cec_device_t;
+
+/** convenience API for opening and closing a device */
+
+static inline int hdmi_cec_open(const struct hw_module_t* module,
+        struct hdmi_cec_device** device) {
+    return module->methods->open(module,
+            HDMI_CEC_HARDWARE_INTERFACE, (struct hw_device_t**)device);
+}
+
+static inline int hdmi_cec_close(struct hdmi_cec_device* device) {
+    return device->common.close(&device->common);
+}
+
+__END_DECLS
+
+#endif /* ANDROID_INCLUDE_HARDWARE_HDMI_CEC_H */
diff --git a/include/hardware/mcu.h b/include/hardware/mcu.h
new file mode 100644
index 0000000..6fe2cfe
--- /dev/null
+++ b/include/hardware/mcu.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_MCU_H
+#define ANDROID_INCLUDE_HARDWARE_MCU_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#include <hardware/hardware.h>
+
+__BEGIN_DECLS
+
+#define MCU_MODULE_API_VERSION_0_1  HARDWARE_MODULE_API_VERSION(0, 1)
+
+/*
+ * The id of this module
+ */
+#define MCU_HARDWARE_MODULE_ID "mcu"
+
+/*
+ * MCU message keys passed to (*sendMessage)
+ */
+#define MCU_PARAMETER_MSG_ENABLE_MCU "enable_mcu"
+
+/*
+ * MCU message values passed to (*sendMessage)
+ */
+#define MCU_PARAMETER_ARG_ON "on"
+#define MCU_PARAMETER_ARG_OFF "off"
+
+/*
+ * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM
+ * and the fields of this data structure must begin with hw_module_t
+ * followed by module specific information.
+ */
+typedef struct mcu_module {
+    struct hw_module_t common;
+
+    /*
+     * (*init)() performs MCU module setup actions at runtime startup, such
+     * as to initialize an external MCU. This is called only by the MCU HAL
+     * instance loaded by PowerManagerService.
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int (*init)(struct mcu_module *module);
+
+    /*
+     * (*sendMessage)() passes a message/argument pair to the MCU to execute
+     * a function. msg is NULL-terminated. If arg is text, then arg_len must
+     * reflect the string length. result is a heap-allocated buffer that the
+     * caller must free. If there is no result, then *result will be NULL and
+     * *result_len will be 0.
+     *
+     * Returns 0 on success or -errno in case of error (for example, if the
+     * MCU does not support the specified message.)
+     *
+     */
+    int (*sendMessage)(struct mcu_module *module, const char *msg,
+                        const void *arg, size_t arg_len, void **result,
+                        size_t *result_len);
+
+} mcu_module_t;
+
+__END_DECLS
+
+#endif  // ANDROID_INCLUDE_HARDWARE_MCU_H
diff --git a/modules/Android.mk b/modules/Android.mk
index de41f6f..f1a6c1c 100644
--- a/modules/Android.mk
+++ b/modules/Android.mk
@@ -1,3 +1,4 @@
 hardware_modules := gralloc hwcomposer audio nfc nfc-nci local_time \
-	power usbaudio audio_remote_submix camera consumerir vibrator
+	power usbaudio audio_remote_submix camera consumerir sensors vibrator \
+	mcu
 include $(call all-named-subdir-makefiles,$(hardware_modules))
diff --git a/modules/mcu/Android.mk b/modules/mcu/Android.mk
new file mode 100644
index 0000000..ec40e3a
--- /dev/null
+++ b/modules/mcu/Android.mk
@@ -0,0 +1,25 @@
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := mcu.default
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := mcu.c
+LOCAL_SHARED_LIBRARIES := liblog
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/modules/mcu/mcu.c b/modules/mcu/mcu.c
new file mode 100644
index 0000000..47300f9
--- /dev/null
+++ b/modules/mcu/mcu.c
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <errno.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#define LOG_TAG "Legacy MCU HAL"
+#include <utils/Log.h>
+
+#include <hardware/hardware.h>
+#include <hardware/mcu.h>
+
+static int mcu_init(struct mcu_module *module)
+{
+    return 0;
+}
+
+static int mcu_send_message(struct mcu_module *module, const char *msg,
+                            const void *arg, size_t arg_len, void **result,
+                            size_t *result_len)
+{
+    return 0;
+}
+
+static struct hw_module_methods_t mcu_module_methods = {
+    .open = NULL,
+};
+
+struct mcu_module HAL_MODULE_INFO_SYM = {
+    .common = {
+        .tag = HARDWARE_MODULE_TAG,
+        .module_api_version = MCU_MODULE_API_VERSION_0_1,
+        .hal_api_version = HARDWARE_HAL_API_VERSION,
+        .id = MCU_HARDWARE_MODULE_ID,
+        .name = "Default MCU HAL",
+        .author = "The Android Open Source Project",
+        .methods = &mcu_module_methods,
+    },
+
+    .init = mcu_init,
+    .sendMessage = mcu_send_message,
+};
diff --git a/modules/sensors/Android.mk b/modules/sensors/Android.mk
new file mode 100644
index 0000000..5b787d4
--- /dev/null
+++ b/modules/sensors/Android.mk
@@ -0,0 +1,52 @@
+#
+# Copyright (C) 2013 The Android Open-Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+LOCAL_PATH := $(call my-dir)
+
+ifeq ($(USE_SENSOR_MULTI_HAL),true)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := sensors.$(TARGET_DEVICE)
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/hw
+
+LOCAL_CFLAGS := -DLOG_TAG=\"MultiHal\"
+
+LOCAL_SRC_FILES := \
+    multihal.cpp \
+    SensorEventQueue.h \
+    SensorEventQueue.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    libcutils \
+    libdl \
+    liblog \
+    libstlport \
+    libutils \
+
+LOCAL_PRELINK_MODULE := false
+LOCAL_STRIP_MODULE := false
+
+LOCAL_C_INCLUDES := \
+    external/stlport/stlport \
+    bionic \
+
+include $(BUILD_SHARED_LIBRARY)
+
+endif # USE_SENSOR_MULTI_HAL
+
+include $(call all-subdir-makefiles)
diff --git a/modules/sensors/SensorEventQueue.cpp b/modules/sensors/SensorEventQueue.cpp
new file mode 100644
index 0000000..f6144f8
--- /dev/null
+++ b/modules/sensors/SensorEventQueue.cpp
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <hardware/sensors.h>
+#include <algorithm>
+#include <pthread.h>
+#include <cutils/log.h>
+
+#include "SensorEventQueue.h"
+
+SensorEventQueue::SensorEventQueue(int capacity) {
+    mCapacity = capacity;
+
+    mStart = 0;
+    mSize = 0;
+    mData = new sensors_event_t[mCapacity];
+    pthread_cond_init(&mSpaceAvailableCondition, NULL);
+}
+
+SensorEventQueue::~SensorEventQueue() {
+    delete[] mData;
+    mData = NULL;
+    pthread_cond_destroy(&mSpaceAvailableCondition);
+}
+
+int SensorEventQueue::getWritableRegion(int requestedLength, sensors_event_t** out) {
+    if (mSize == mCapacity || requestedLength <= 0) {
+        *out = NULL;
+        return 0;
+    }
+    // Start writing after the last readable record.
+    int firstWritable = (mStart + mSize) % mCapacity;
+
+    int lastWritable = firstWritable + requestedLength - 1;
+
+    // Don't go past the end of the data array.
+    if (lastWritable > mCapacity - 1) {
+        lastWritable = mCapacity - 1;
+    }
+    // Don't go into the readable region.
+    if (firstWritable < mStart && lastWritable >= mStart) {
+        lastWritable = mStart - 1;
+    }
+    *out = &mData[firstWritable];
+    return lastWritable - firstWritable + 1;
+}
+
+void SensorEventQueue::markAsWritten(int count) {
+    mSize += count;
+}
+
+int SensorEventQueue::getSize() {
+    return mSize;
+}
+
+sensors_event_t* SensorEventQueue::peek() {
+    if (mSize == 0) return NULL;
+    return &mData[mStart];
+}
+
+void SensorEventQueue::dequeue() {
+    if (mSize == 0) return;
+    if (mSize == mCapacity) {
+        pthread_cond_broadcast(&mSpaceAvailableCondition);
+    }
+    mSize--;
+    mStart = (mStart + 1) % mCapacity;
+}
+
+// returns true if it waited, or false if it was a no-op.
+bool SensorEventQueue::waitForSpace(pthread_mutex_t* mutex) {
+    bool waited = false;
+    while (mSize == mCapacity) {
+        waited = true;
+        pthread_cond_wait(&mSpaceAvailableCondition, mutex);
+    }
+    return waited;
+}
diff --git a/modules/sensors/SensorEventQueue.h b/modules/sensors/SensorEventQueue.h
new file mode 100644
index 0000000..11e1f41
--- /dev/null
+++ b/modules/sensors/SensorEventQueue.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef SENSOREVENTQUEUE_H_
+#define SENSOREVENTQUEUE_H_
+
+#include <hardware/sensors.h>
+#include <pthread.h>
+
+/*
+ * Fixed-size circular queue, with an API developed around the sensor HAL poll() method.
+ * Poll() takes a pointer to a buffer, which is written by poll() before it returns.
+ * This class can provide a pointer to a spot in its internal buffer for poll() to
+ * write to, instead of using an intermediate buffer and a memcpy.
+ *
+ * Thread safety:
+ * Reading can be done safely after grabbing the mutex lock, while poll() writing in a separate
+ * thread without a mutex lock. But there can only be one writer at a time.
+ */
+class SensorEventQueue {
+    int mCapacity;
+    int mStart; // start of readable region
+    int mSize; // number of readable items
+    sensors_event_t* mData;
+    pthread_cond_t mSpaceAvailableCondition;
+
+public:
+    SensorEventQueue(int capacity);
+    ~SensorEventQueue();
+
+    // Returns length of region, between zero and min(capacity, requestedLength). If there is any
+    // writable space, it will return a region of at least one. Because it must return
+    // a pointer to a contiguous region, it may return smaller regions as we approach the end of
+    // the data array.
+    // Only call while holding the lock.
+    // The region is not marked internally in any way. Subsequent calls may return overlapping
+    // regions. This class expects there to be exactly one writer at a time.
+    int getWritableRegion(int requestedLength, sensors_event_t** out);
+
+    // After writing to the region returned by getWritableRegion(), call this to indicate how
+    // many records were actually written.
+    // This increases size() by count.
+    // Only call while holding the lock.
+    void markAsWritten(int count);
+
+    // Gets the number of readable records.
+    // Only call while holding the lock.
+    int getSize();
+
+    // Returns pointer to the first readable record, or NULL if size() is zero.
+    // Only call this while holding the lock.
+    sensors_event_t* peek();
+
+    // This will decrease the size by one, freeing up the oldest readable event's slot for writing.
+    // Only call while holding the lock.
+    void dequeue();
+
+    // Blocks until space is available. No-op if there is already space.
+    // Returns true if it had to wait.
+    bool waitForSpace(pthread_mutex_t* mutex);
+};
+
+#endif // SENSOREVENTQUEUE_H_
diff --git a/modules/sensors/multihal.cpp b/modules/sensors/multihal.cpp
new file mode 100644
index 0000000..a145c37
--- /dev/null
+++ b/modules/sensors/multihal.cpp
@@ -0,0 +1,586 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <hardware/sensors.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <dirent.h>
+#include <math.h>
+#include <poll.h>
+#include <pthread.h>
+#include <cutils/atomic.h>
+
+#define LOG_NDEBUG 1
+#include <cutils/log.h>
+
+#include <vector>
+#include <map>
+
+#include <stdio.h>
+#include <dlfcn.h>
+#include <SensorEventQueue.h>
+
+
+static const char* CONFIG_FILENAME = "/system/etc/sensors/hals.conf";
+static const char* LEGAL_SUBHAL_PATH_PREFIX = "/system/lib/hw/";
+static const int MAX_CONF_LINE_LENGTH = 1024;
+
+static pthread_mutex_t init_modules_mutex = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t init_sensors_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+// This mutex is shared by all queues
+static pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+// Used to pause the multihal poll(). Broadcasted by sub-polling tasks if waiting_for_data.
+static pthread_cond_t data_available_cond = PTHREAD_COND_INITIALIZER;
+bool waiting_for_data = false;
+
+/*
+ * Vector of sub modules, whose indexes are referred to ni this file as module_index.
+ */
+static std::vector<hw_module_t *> *sub_hw_modules = NULL;
+
+/*
+ * Comparable class that globally identifies a sensor, by module index and local handle.
+ * A module index is the module's index in sub_hw_modules.
+ * A local handle is the handle the sub-module assigns to a sensor.
+ */
+struct FullHandle {
+    int moduleIndex;
+    int localHandle;
+
+    bool operator<(const FullHandle &that) const {
+        if (moduleIndex < that.moduleIndex) {
+            return true;
+        }
+        if (moduleIndex > that.moduleIndex) {
+            return false;
+        }
+        return localHandle < that.localHandle;
+    }
+
+    bool operator==(const FullHandle &that) const {
+        return moduleIndex == that.moduleIndex && localHandle == that.localHandle;
+    }
+};
+
+std::map<int, FullHandle> global_to_full;
+std::map<FullHandle, int> full_to_global;
+int next_global_handle = 1;
+
+static int assign_global_handle(int module_index, int local_handle) {
+    int global_handle = next_global_handle++;
+    FullHandle full_handle;
+    full_handle.moduleIndex = module_index;
+    full_handle.localHandle = local_handle;
+    full_to_global[full_handle] = global_handle;
+    global_to_full[global_handle] = full_handle;
+    return global_handle;
+}
+
+static int get_local_handle(int global_handle) {
+    return global_to_full[global_handle].localHandle;
+}
+
+static int get_module_index(int global_handle) {
+    FullHandle f = global_to_full[global_handle];
+    ALOGV("FullHandle for global_handle %d: moduleIndex %d, localHandle %d",
+            global_handle, f.moduleIndex, f.localHandle);
+    return f.moduleIndex;
+}
+
+static const int SENSOR_EVENT_QUEUE_CAPACITY = 20;
+
+struct TaskContext {
+  sensors_poll_device_t* device;
+  SensorEventQueue* queue;
+};
+
+void *writerTask(void* ptr) {
+    ALOGV("writerTask STARTS");
+    TaskContext* ctx = (TaskContext*)ptr;
+    sensors_poll_device_t* device = ctx->device;
+    SensorEventQueue* queue = ctx->queue;
+    sensors_event_t* buffer;
+    int eventsPolled;
+    while (1) {
+        pthread_mutex_lock(&queue_mutex);
+        if (queue->waitForSpace(&queue_mutex)) {
+            ALOGV("writerTask waited for space");
+        }
+        int bufferSize = queue->getWritableRegion(SENSOR_EVENT_QUEUE_CAPACITY, &buffer);
+        // Do blocking poll outside of lock
+        pthread_mutex_unlock(&queue_mutex);
+
+        ALOGV("writerTask before poll() - bufferSize = %d", bufferSize);
+        eventsPolled = device->poll(device, buffer, bufferSize);
+        ALOGV("writerTask poll() got %d events.", eventsPolled);
+        if (eventsPolled == 0) {
+            continue;
+        }
+        pthread_mutex_lock(&queue_mutex);
+        queue->markAsWritten(eventsPolled);
+        ALOGV("writerTask wrote %d events", eventsPolled);
+        if (waiting_for_data) {
+            ALOGV("writerTask - broadcast data_available_cond");
+            pthread_cond_broadcast(&data_available_cond);
+        }
+        pthread_mutex_unlock(&queue_mutex);
+    }
+    // never actually returns
+    return NULL;
+}
+
+/*
+ * Cache of all sensors, with original handles replaced by global handles.
+ * This will be handled to get_sensors_list() callers.
+ */
+static struct sensor_t const* global_sensors_list = NULL;
+static int global_sensors_count = -1;
+
+/*
+ * Extends a sensors_poll_device_1 by including all the sub-module's devices.
+ */
+struct sensors_poll_context_t {
+    /*
+     * This is the device that SensorDevice.cpp uses to make API calls
+     * to the multihal, which fans them out to sub-HALs.
+     */
+    sensors_poll_device_1 proxy_device; // must be first
+
+    void addSubHwDevice(struct hw_device_t*);
+
+    int activate(int handle, int enabled);
+    int setDelay(int handle, int64_t ns);
+    int poll(sensors_event_t* data, int count);
+    int batch(int handle, int flags, int64_t period_ns, int64_t timeout);
+    int flush(int handle);
+    int close();
+
+    std::vector<hw_device_t*> sub_hw_devices;
+    std::vector<SensorEventQueue*> queues;
+    std::vector<pthread_t> threads;
+    int nextReadIndex;
+
+    sensors_poll_device_t* get_v0_device_by_handle(int global_handle);
+    sensors_poll_device_1_t* get_v1_device_by_handle(int global_handle);
+    int get_device_version_by_handle(int global_handle);
+
+    void copy_event_remap_handle(sensors_event_t* src, sensors_event_t* dest, int sub_index);
+};
+
+void sensors_poll_context_t::addSubHwDevice(struct hw_device_t* sub_hw_device) {
+    ALOGV("addSubHwDevice");
+    this->sub_hw_devices.push_back(sub_hw_device);
+
+    SensorEventQueue *queue = new SensorEventQueue(SENSOR_EVENT_QUEUE_CAPACITY);
+    this->queues.push_back(queue);
+
+    TaskContext* taskContext = new TaskContext();
+    taskContext->device = (sensors_poll_device_t*) sub_hw_device;
+    taskContext->queue = queue;
+
+    pthread_t writerThread;
+    pthread_create(&writerThread, NULL, writerTask, taskContext);
+    this->threads.push_back(writerThread);
+}
+
+sensors_poll_device_t* sensors_poll_context_t::get_v0_device_by_handle(int handle) {
+    int sub_index = get_module_index(handle);
+    return (sensors_poll_device_t*) this->sub_hw_devices[sub_index];
+}
+
+sensors_poll_device_1_t* sensors_poll_context_t::get_v1_device_by_handle(int handle) {
+    int sub_index = get_module_index(handle);
+    return (sensors_poll_device_1_t*) this->sub_hw_devices[sub_index];
+}
+
+int sensors_poll_context_t::get_device_version_by_handle(int handle) {
+    sensors_poll_device_t* v0 = this->get_v0_device_by_handle(handle);
+    return v0->common.version;
+}
+
+int sensors_poll_context_t::activate(int handle, int enabled) {
+    ALOGV("activate");
+    sensors_poll_device_t* v0 = this->get_v0_device_by_handle(handle);
+    int retval = v0->activate(v0, get_local_handle(handle), enabled);
+    ALOGV("retval %d", retval);
+    return retval;
+}
+
+int sensors_poll_context_t::setDelay(int handle, int64_t ns) {
+    ALOGV("setDelay");
+    sensors_poll_device_t* v0 = this->get_v0_device_by_handle(handle);
+    int retval = v0->setDelay(v0, get_local_handle(handle), ns);
+    ALOGV("retval %d", retval);
+    return retval;
+}
+
+void sensors_poll_context_t::copy_event_remap_handle(sensors_event_t* dest, sensors_event_t* src,
+        int sub_index) {
+    memcpy(dest, src, sizeof(struct sensors_event_t));
+    // A normal event's "sensor" field is a local handle. Convert it to a global handle.
+    // A meta-data event must have its sensor set to 0, but it has a nested event
+    // with a local handle that needs to be converted to a global handle.
+    FullHandle full_handle;
+    full_handle.moduleIndex = sub_index;
+    // If it's a metadata event, rewrite the inner payload, not the sensor field.
+    if (dest->type == SENSOR_TYPE_META_DATA) {
+        full_handle.localHandle = dest->meta_data.sensor;
+        dest->meta_data.sensor = full_to_global[full_handle];
+    } else {
+        full_handle.localHandle = dest->sensor;
+        dest->sensor = full_to_global[full_handle];
+    }
+}
+
+int sensors_poll_context_t::poll(sensors_event_t *data, int maxReads) {
+    ALOGV("poll");
+    int empties = 0;
+    int queueCount = (int)this->queues.size();
+    int eventsRead = 0;
+
+    pthread_mutex_lock(&queue_mutex);
+    while (eventsRead == 0) {
+        while (empties < queueCount && eventsRead < maxReads) {
+            SensorEventQueue* queue = this->queues.at(this->nextReadIndex);
+            sensors_event_t* event = queue->peek();
+            if (event == NULL) {
+                empties++;
+            } else {
+                empties = 0;
+                this->copy_event_remap_handle(&data[eventsRead++], event, nextReadIndex);
+                queue->dequeue();
+            }
+            this->nextReadIndex = (this->nextReadIndex + 1) % queueCount;
+        }
+        if (eventsRead == 0) {
+            // The queues have been scanned and none contain data, so wait.
+            ALOGV("poll stopping to wait for data");
+            waiting_for_data = true;
+            pthread_cond_wait(&data_available_cond, &queue_mutex);
+            waiting_for_data = false;
+            empties = 0;
+        }
+    }
+    pthread_mutex_unlock(&queue_mutex);
+    ALOGV("poll returning %d events.", eventsRead);
+
+    return eventsRead;
+}
+
+int sensors_poll_context_t::batch(int handle, int flags, int64_t period_ns, int64_t timeout) {
+    ALOGV("batch");
+    int retval = -EINVAL;
+    int version = this->get_device_version_by_handle(handle);
+    if (version >= SENSORS_DEVICE_API_VERSION_1_0) {
+        sensors_poll_device_1_t* v1 = this->get_v1_device_by_handle(handle);
+        retval = v1->batch(v1, get_local_handle(handle), flags, period_ns, timeout);
+    }
+    ALOGV("retval %d", retval);
+    return retval;
+}
+
+int sensors_poll_context_t::flush(int handle) {
+    ALOGV("flush");
+    int retval = -EINVAL;
+    int version = this->get_device_version_by_handle(handle);
+    if (version >= SENSORS_DEVICE_API_VERSION_1_0) {
+        sensors_poll_device_1_t* v1 = this->get_v1_device_by_handle(handle);
+        retval = v1->flush(v1, get_local_handle(handle));
+    }
+    ALOGV("retval %d", retval);
+    return retval;
+}
+
+int sensors_poll_context_t::close() {
+    ALOGV("close");
+    for (std::vector<hw_device_t*>::iterator it = this->sub_hw_devices.begin();
+            it != this->sub_hw_devices.end(); it++) {
+        hw_device_t* dev = *it;
+        int retval = dev->close(dev);
+        ALOGV("retval %d", retval);
+    }
+    return 0;
+}
+
+
+static int device__close(struct hw_device_t *dev) {
+    sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
+    if (ctx != NULL) {
+        int retval = ctx->close();
+        delete ctx;
+    }
+    return 0;
+}
+
+static int device__activate(struct sensors_poll_device_t *dev, int handle,
+        int enabled) {
+    sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
+    return ctx->activate(handle, enabled);
+}
+
+static int device__setDelay(struct sensors_poll_device_t *dev, int handle,
+        int64_t ns) {
+    sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
+    return ctx->setDelay(handle, ns);
+}
+
+static int device__poll(struct sensors_poll_device_t *dev, sensors_event_t* data,
+        int count) {
+    sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
+    return ctx->poll(data, count);
+}
+
+static int device__batch(struct sensors_poll_device_1 *dev, int handle,
+        int flags, int64_t period_ns, int64_t timeout) {
+    sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
+    return ctx->batch(handle, flags, period_ns, timeout);
+}
+
+static int device__flush(struct sensors_poll_device_1 *dev, int handle) {
+    sensors_poll_context_t* ctx = (sensors_poll_context_t*) dev;
+    return ctx->flush(handle);
+}
+
+static int open_sensors(const struct hw_module_t* module, const char* name,
+        struct hw_device_t** device);
+
+static bool starts_with(const char* s, const char* prefix) {
+    if (s == NULL || prefix == NULL) {
+        return false;
+    }
+    size_t s_size = strlen(s);
+    size_t prefix_size = strlen(prefix);
+    return s_size >= prefix_size && strncmp(s, prefix, prefix_size) == 0;
+}
+
+/*
+ * Adds valid paths from the config file to the vector passed in.
+ * The vector must not be null.
+ */
+static void get_so_paths(std::vector<char*> *so_paths) {
+    FILE *conf_file = fopen(CONFIG_FILENAME, "r");
+    if (conf_file == NULL) {
+        ALOGW("No multihal config file found at %s", CONFIG_FILENAME);
+        return;
+    }
+    ALOGI("Multihal config file found at %s", CONFIG_FILENAME);
+    char *line = NULL;
+    size_t len = 0;
+    int line_count = 0;
+    while (getline(&line, &len, conf_file) != -1) {
+        // overwrite trailing eoln with null char
+        char* pch = strchr(line, '\n');
+        if (pch != NULL) {
+            *pch = '\0';
+        }
+        ALOGV("config file line #%d: '%s'", ++line_count, line);
+        char *real_path = realpath(line, NULL);
+        if (starts_with(real_path, LEGAL_SUBHAL_PATH_PREFIX)) {
+            ALOGI("accepting valid path '%s'", real_path);
+            char* compact_line = new char[strlen(real_path) + 1];
+            strcpy(compact_line, real_path);
+            so_paths->push_back(compact_line);
+        } else {
+            ALOGW("rejecting path '%s' because it does not start with '%s'",
+                    real_path, LEGAL_SUBHAL_PATH_PREFIX);
+        }
+        free(real_path);
+    }
+    free(line);
+    fclose(conf_file);
+    ALOGV("hals.conf contained %d lines", line_count);
+}
+
+/*
+ * Ensures that the sub-module array is initialized.
+ * This can be first called from get_sensors_list or from open_sensors.
+ */
+static void lazy_init_modules() {
+    pthread_mutex_lock(&init_modules_mutex);
+    if (sub_hw_modules != NULL) {
+        pthread_mutex_unlock(&init_modules_mutex);
+        return;
+    }
+    std::vector<char*> *so_paths = new std::vector<char*>();
+    get_so_paths(so_paths);
+
+    // dlopen the module files and cache their module symbols in sub_hw_modules
+    sub_hw_modules = new std::vector<hw_module_t *>();
+    dlerror(); // clear any old errors
+    const char* sym = HAL_MODULE_INFO_SYM_AS_STR;
+    for (std::vector<char*>::iterator it = so_paths->begin(); it != so_paths->end(); it++) {
+        char* path = *it;
+        void* lib_handle = dlopen(path, RTLD_LAZY);
+        if (lib_handle == NULL) {
+            ALOGW("dlerror(): %s", dlerror());
+        } else {
+            ALOGI("hal lib was loaded: %s", path);
+            ALOGV("Opening symbol \"%s\"", sym);
+            // clear old errors
+            dlerror();
+            struct hw_module_t* module = (hw_module_t*) dlsym(lib_handle, sym);
+            const char* error;
+            if ((error = dlerror()) != NULL) {
+                ALOGW("Error calling dlsym: %s", error);
+            } else if (module == NULL) {
+                ALOGW("module == NULL");
+            } else {
+                ALOGI("OK, dlsym()'ed \"%s\"", sym);
+                sub_hw_modules->push_back(module);
+            }
+        }
+    }
+    pthread_mutex_unlock(&init_modules_mutex);
+}
+
+/*
+ * Lazy-initializes global_sensors_count, global_sensors_list, and module_sensor_handles.
+ */
+static void lazy_init_sensors_list() {
+    ALOGV("lazy_init_sensors_list");
+    pthread_mutex_lock(&init_sensors_mutex);
+    if (global_sensors_list != NULL) {
+        // already initialized
+        pthread_mutex_unlock(&init_sensors_mutex);
+        ALOGV("lazy_init_sensors_list - early return");
+        return;
+    }
+
+    ALOGV("lazy_init_sensors_list needs to do work");
+    lazy_init_modules();
+
+    // Count all the sensors, then allocate an array of blanks.
+    global_sensors_count = 0;
+    const struct sensor_t *subhal_sensors_list;
+    for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
+            it != sub_hw_modules->end(); it++) {
+        struct sensors_module_t *module = (struct sensors_module_t*) *it;
+        global_sensors_count += module->get_sensors_list(module, &subhal_sensors_list);
+        ALOGV("increased global_sensors_count to %d", global_sensors_count);
+    }
+
+    // The global_sensors_list is full of consts.
+    // Manipulate this non-const list, and point the const one to it when we're done.
+    sensor_t* mutable_sensor_list = new sensor_t[global_sensors_count];
+
+    // index of the next sensor to set in mutable_sensor_list
+    int mutable_sensor_index = 0;
+    int module_index = 0;
+
+    for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
+            it != sub_hw_modules->end(); it++) {
+        hw_module_t *hw_module = *it;
+        ALOGV("examine one module");
+        // Read the sub-module's sensor list.
+        struct sensors_module_t *module = (struct sensors_module_t*) hw_module;
+        int module_sensor_count = module->get_sensors_list(module, &subhal_sensors_list);
+        ALOGV("the module has %d sensors", module_sensor_count);
+
+        // Copy the HAL's sensor list into global_sensors_list,
+        // with the handle changed to be a global handle.
+        for (int i = 0; i < module_sensor_count; i++) {
+            ALOGV("examining one sensor");
+            const struct sensor_t *local_sensor = &subhal_sensors_list[i];
+            int local_handle = local_sensor->handle;
+            memcpy(&mutable_sensor_list[mutable_sensor_index], local_sensor,
+                sizeof(struct sensor_t));
+
+            // Overwrite the global version's handle with a global handle.
+            int global_handle = assign_global_handle(module_index, local_handle);
+
+            mutable_sensor_list[mutable_sensor_index].handle = global_handle;
+            ALOGI("module_index %d, local_handle %d, global_handle %d",
+                    module_index, local_handle, global_handle);
+
+            mutable_sensor_index++;
+        }
+        module_index++;
+    }
+    // Set the const static global_sensors_list to the mutable one allocated by this function.
+    global_sensors_list = mutable_sensor_list;
+
+    pthread_mutex_unlock(&init_sensors_mutex);
+    ALOGV("end lazy_init_sensors_list");
+}
+
+static int module__get_sensors_list(struct sensors_module_t* module,
+        struct sensor_t const** list) {
+    ALOGV("module__get_sensors_list start");
+    lazy_init_sensors_list();
+    *list = global_sensors_list;
+    ALOGV("global_sensors_count: %d", global_sensors_count);
+    for (int i = 0; i < global_sensors_count; i++) {
+        ALOGV("sensor type: %d", global_sensors_list[i].type);
+    }
+    return global_sensors_count;
+}
+
+static struct hw_module_methods_t sensors_module_methods = {
+    open : open_sensors
+};
+
+struct sensors_module_t HAL_MODULE_INFO_SYM = {
+    common :{
+        tag : HARDWARE_MODULE_TAG,
+        version_major : 1,
+        version_minor : 0,
+        id : SENSORS_HARDWARE_MODULE_ID,
+        name : "MultiHal Sensor Module",
+        author : "Google, Inc",
+        methods : &sensors_module_methods,
+        dso : NULL,
+        reserved : {0},
+    },
+    get_sensors_list : module__get_sensors_list
+};
+
+static int open_sensors(const struct hw_module_t* hw_module, const char* name,
+        struct hw_device_t** hw_device_out) {
+    ALOGI("open_sensors begin...");
+
+    lazy_init_modules();
+
+    // Create proxy device, to return later.
+    sensors_poll_context_t *dev = new sensors_poll_context_t();
+    memset(dev, 0, sizeof(sensors_poll_device_1_t));
+    dev->proxy_device.common.tag = HARDWARE_DEVICE_TAG;
+    dev->proxy_device.common.version = SENSORS_DEVICE_API_VERSION_1_0;
+    dev->proxy_device.common.module = const_cast<hw_module_t*>(hw_module);
+    dev->proxy_device.common.close = device__close;
+    dev->proxy_device.activate = device__activate;
+    dev->proxy_device.setDelay = device__setDelay;
+    dev->proxy_device.poll = device__poll;
+    dev->proxy_device.batch = device__batch;
+    dev->proxy_device.flush = device__flush;
+
+    dev->nextReadIndex = 0;
+
+    // Open() the subhal modules. Remember their devices in a vector parallel to sub_hw_modules.
+    for (std::vector<hw_module_t*>::iterator it = sub_hw_modules->begin();
+            it != sub_hw_modules->end(); it++) {
+        sensors_module_t *sensors_module = (sensors_module_t*) *it;
+        struct hw_device_t* sub_hw_device;
+        int sub_open_result = sensors_module->common.methods->open(*it, name, &sub_hw_device);
+        dev->addSubHwDevice(sub_hw_device);
+    }
+
+    // Prepare the output param and return
+    *hw_device_out = &dev->proxy_device.common;
+    ALOGI("...open_sensors end");
+    return 0;
+}
diff --git a/modules/sensors/tests/Android.mk b/modules/sensors/tests/Android.mk
new file mode 100644
index 0000000..010bb90
--- /dev/null
+++ b/modules/sensors/tests/Android.mk
@@ -0,0 +1,17 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+	SensorEventQueue_test.cpp
+
+#LOCAL_CFLAGS := -g
+LOCAL_MODULE := sensorstests
+
+LOCAL_STATIC_LIBRARIES := libcutils libutils
+
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/.. bionic
+
+LOCAL_LDLIBS += -lpthread
+
+include $(BUILD_HOST_EXECUTABLE)
diff --git a/modules/sensors/tests/SensorEventQueue_test.cpp b/modules/sensors/tests/SensorEventQueue_test.cpp
new file mode 100644
index 0000000..3218bb9
--- /dev/null
+++ b/modules/sensors/tests/SensorEventQueue_test.cpp
@@ -0,0 +1,199 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <hardware/sensors.h>
+#include <pthread.h>
+#include <cutils/atomic.h>
+
+#include "SensorEventQueue.cpp"
+
+// Unit tests for the SensorEventQueue.
+
+// Run it like this:
+//
+// make sensorstests -j32 && \
+// out/host/linux-x86/obj/EXECUTABLES/sensorstests_intermediates/sensorstests
+
+bool checkWritableBufferSize(SensorEventQueue* queue, int requested, int expected) {
+    sensors_event_t* buffer;
+    int actual = queue->getWritableRegion(requested, &buffer);
+    if (actual != expected) {
+        printf("Expected buffer size was %d; actual was %d\n", expected, actual);
+        return false;
+    }
+    return true;
+}
+
+bool checkSize(SensorEventQueue* queue, int expected) {
+    int actual = queue->getSize();
+    if (actual != expected) {
+        printf("Expected queue size was %d; actual was %d\n", expected, actual);
+        return false;
+    }
+    return true;
+}
+
+bool checkInt(char* msg, int expected, int actual) {
+    if (actual != expected) {
+        printf("%s; expected %d; actual was %d\n", msg, expected, actual);
+        return false;
+    }
+    return true;
+}
+
+bool testSimpleWriteSizeCounts() {
+    printf("testSimpleWriteSizeCounts\n");
+    SensorEventQueue* queue = new SensorEventQueue(10);
+    if (!checkSize(queue, 0)) return false;
+    if (!checkWritableBufferSize(queue, 11, 10)) return false;
+    if (!checkWritableBufferSize(queue, 10, 10)) return false;
+    if (!checkWritableBufferSize(queue, 9, 9)) return false;
+
+    queue->markAsWritten(7);
+    if (!checkSize(queue, 7)) return false;
+    if (!checkWritableBufferSize(queue, 4, 3)) return false;
+    if (!checkWritableBufferSize(queue, 3, 3)) return false;
+    if (!checkWritableBufferSize(queue, 2, 2)) return false;
+
+    queue->markAsWritten(3);
+    if (!checkSize(queue, 10)) return false;
+    if (!checkWritableBufferSize(queue, 1, 0)) return false;
+
+    printf("passed\n");
+    return true;
+}
+
+bool testWrappingWriteSizeCounts() {
+    printf("testWrappingWriteSizeCounts\n");
+    SensorEventQueue* queue = new SensorEventQueue(10);
+    queue->markAsWritten(9);
+    if (!checkSize(queue, 9)) return false;
+
+    // dequeue from the front
+    queue->dequeue();
+    queue->dequeue();
+    if (!checkSize(queue, 7)) return false;
+    if (!checkWritableBufferSize(queue, 100, 1)) return false;
+
+    // Write all the way to the end.
+    queue->markAsWritten(1);
+    if (!checkSize(queue, 8)) return false;
+    // Now the two free spots in the front are available.
+    if (!checkWritableBufferSize(queue, 100, 2)) return false;
+
+    // Fill the queue again
+    queue->markAsWritten(2);
+    if (!checkSize(queue, 10)) return false;
+
+    printf("passed\n");
+    return true;
+}
+
+
+
+struct TaskContext {
+  bool success;
+  SensorEventQueue* queue;
+};
+
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t dataAvailableCond = PTHREAD_COND_INITIALIZER;
+
+int FULL_QUEUE_CAPACITY = 5;
+int FULL_QUEUE_EVENT_COUNT = 31;
+
+void *fullQueueWriterTask(void* ptr) {
+    TaskContext* ctx = (TaskContext*)ptr;
+    SensorEventQueue* queue = ctx->queue;
+    ctx->success = true;
+    int totalWaits = 0;
+    int totalWrites = 0;
+    sensors_event_t* buffer;
+
+    while (totalWrites < FULL_QUEUE_EVENT_COUNT) {
+        pthread_mutex_lock(&mutex);
+        if (queue->waitForSpace(&mutex)) {
+            totalWaits++;
+            printf(".");
+        }
+        int writableSize = queue->getWritableRegion(FULL_QUEUE_CAPACITY, &buffer);
+        queue->markAsWritten(writableSize);
+        totalWrites += writableSize;
+        for (int i = 0; i < writableSize; i++) {
+            printf("w");
+        }
+        pthread_cond_broadcast(&dataAvailableCond);
+        pthread_mutex_unlock(&mutex);
+    }
+    printf("\n");
+
+    ctx->success =
+            checkInt("totalWrites", FULL_QUEUE_EVENT_COUNT, totalWrites) &&
+            checkInt("totalWaits", FULL_QUEUE_EVENT_COUNT - FULL_QUEUE_CAPACITY, totalWaits);
+    return NULL;
+}
+
+bool fullQueueReaderShouldRead(int queueSize, int totalReads) {
+    if (queueSize == 0) {
+        return false;
+    }
+    int totalWrites = totalReads + queueSize;
+    return queueSize == FULL_QUEUE_CAPACITY || totalWrites == FULL_QUEUE_EVENT_COUNT;
+}
+
+void* fullQueueReaderTask(void* ptr) {
+    TaskContext* ctx = (TaskContext*)ptr;
+    SensorEventQueue* queue = ctx->queue;
+    int totalReads = 0;
+    while (totalReads < FULL_QUEUE_EVENT_COUNT) {
+        pthread_mutex_lock(&mutex);
+        // Only read if there are events,
+        // and either the queue is full, or if we're reading the last few events.
+        while (!fullQueueReaderShouldRead(queue->getSize(), totalReads)) {
+            pthread_cond_wait(&dataAvailableCond, &mutex);
+        }
+        queue->dequeue();
+        totalReads++;
+        printf("r");
+        pthread_mutex_unlock(&mutex);
+    }
+    printf("\n");
+    ctx->success = ctx->success && checkInt("totalreads", FULL_QUEUE_EVENT_COUNT, totalReads);
+    return NULL;
+}
+
+// Test internal queue-full waiting and broadcasting.
+bool testFullQueueIo() {
+    printf("testFullQueueIo\n");
+    SensorEventQueue* queue = new SensorEventQueue(FULL_QUEUE_CAPACITY);
+
+    TaskContext readerCtx;
+    readerCtx.success = true;
+    readerCtx.queue = queue;
+
+    TaskContext writerCtx;
+    writerCtx.success = true;
+    writerCtx.queue = queue;
+
+    pthread_t writer, reader;
+    pthread_create(&reader, NULL, fullQueueReaderTask, &readerCtx);
+    pthread_create(&writer, NULL, fullQueueWriterTask, &writerCtx);
+
+    pthread_join(writer, NULL);
+    pthread_join(reader, NULL);
+
+    if (!readerCtx.success || !writerCtx.success) return false;
+    printf("passed\n");
+    return true;
+}
+
+
+int main(int argc, char **argv) {
+    if (testSimpleWriteSizeCounts() &&
+            testWrappingWriteSizeCounts() &&
+            testFullQueueIo()) {
+        printf("ALL PASSED\n");
+    } else {
+        printf("SOMETHING FAILED\n");
+    }
+    return EXIT_SUCCESS;
+}
diff --git a/tests/camera3/Android.mk b/tests/camera3/Android.mk
new file mode 100644
index 0000000..652851a
--- /dev/null
+++ b/tests/camera3/Android.mk
@@ -0,0 +1,20 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:= \
+    camera3tests.cpp \
+
+LOCAL_SHARED_LIBRARIES := \
+    liblog \
+    libhardware \
+    libcamera_metadata \
+
+LOCAL_C_INCLUDES += \
+    system/media/camera/include \
+
+LOCAL_CFLAGS += -Wall -Wextra
+
+LOCAL_MODULE:= camera3_tests
+LOCAL_MODULE_TAGS := tests
+
+include $(BUILD_NATIVE_TEST)
diff --git a/tests/camera3/camera3test_fixtures.h b/tests/camera3/camera3test_fixtures.h
new file mode 100644
index 0000000..81d1997
--- /dev/null
+++ b/tests/camera3/camera3test_fixtures.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __ANDROID_HAL_CAMERA3_TEST_COMMON__
+#define __ANDROID_HAL_CAMERA3_TEST_COMMON__
+
+#include <gtest/gtest.h>
+#include <hardware/hardware.h>
+#include <hardware/camera3.h>
+
+namespace tests {
+
+static const int kMmaxCams = 2;
+static const uint16_t kVersion3_0 = HARDWARE_MODULE_API_VERSION(3, 0);
+
+class Camera3Module : public testing::Test {
+ public:
+    Camera3Module() :
+        num_cams_(0),
+        cam_module_(NULL) {}
+    ~Camera3Module() {}
+ protected:
+    virtual void SetUp() {
+        const hw_module_t *hw_module = NULL;
+        ASSERT_EQ(0, hw_get_module(CAMERA_HARDWARE_MODULE_ID, &hw_module))
+                    << "Can't get camera module";
+        ASSERT_TRUE(NULL != hw_module)
+                    << "hw_get_module didn't return a valid camera module";
+
+        cam_module_ = reinterpret_cast<const camera_module_t*>(hw_module);
+        ASSERT_TRUE(NULL != cam_module_->get_number_of_cameras)
+                    << "get_number_of_cameras is not implemented";
+        num_cams_ = cam_module_->get_number_of_cameras();
+    }
+    int num_cams() { return num_cams_; }
+    const camera_module_t * cam_module() { return cam_module_; }
+ private:
+    int num_cams_;
+    const camera_module_t *cam_module_;
+};
+
+class Camera3Device : public Camera3Module {
+ public:
+    Camera3Device() :
+        cam_device_(NULL) {}
+    ~Camera3Device() {}
+ protected:
+    virtual void SetUp() {
+        Camera3Module::SetUp();
+        hw_device_t *device = NULL;
+        ASSERT_TRUE(NULL != cam_module()->common.methods->open)
+                    << "Camera open() is unimplemented";
+        ASSERT_EQ(0, cam_module()->common.methods->open(
+            (const hw_module_t*)cam_module(), "0", &device))
+                << "Can't open camera device";
+        ASSERT_TRUE(NULL != device)
+                    << "Camera open() returned a NULL device";
+        ASSERT_EQ(kVersion3_0, device->version)
+                    << "The device does not support HAL3";
+        cam_device_ = reinterpret_cast<camera3_device_t*>(device);
+    }
+    camera3_device_t* cam_device() { return cam_device_; }
+ private:
+    camera3_device *cam_device_;
+};
+
+}  // namespace tests
+
+#endif  // __ANDROID_HAL_CAMERA3_TEST_COMMON__
diff --git a/tests/camera3/camera3tests.cpp b/tests/camera3/camera3tests.cpp
new file mode 100644
index 0000000..5dbe588
--- /dev/null
+++ b/tests/camera3/camera3tests.cpp
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+#include "camera3test_fixtures.h"
+
+namespace tests {
+
+TEST_F(Camera3Module, NumberOfCameras) {
+    ASSERT_LT(0, num_cams()) << "No cameras found";
+    ASSERT_GE(kMmaxCams, num_cams()) << "Too many cameras found";
+}
+
+TEST_F(Camera3Module, IsActiveArraySizeSubsetPixelArraySize) {
+    for (int i = 0; i < num_cams(); ++i) {
+        ASSERT_TRUE(NULL != cam_module()->get_camera_info)
+            << "get_camera_info is not implemented";
+
+        camera_info info;
+        ASSERT_EQ(0, cam_module()->get_camera_info(i, &info))
+                    << "Can't get camera info for" << i;
+
+        camera_metadata_entry entry;
+        ASSERT_EQ(0, find_camera_metadata_entry(
+                    const_cast<camera_metadata_t*>(
+                        info.static_camera_characteristics),
+                        ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE, &entry))
+                            << "Can't find the sensor pixel array size.";
+        int pixel_array_w = entry.data.i32[0];
+        int pixel_array_h = entry.data.i32[1];
+
+        ASSERT_EQ(0, find_camera_metadata_entry(
+                    const_cast<camera_metadata_t*>(
+                        info.static_camera_characteristics),
+                        ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE, &entry))
+                            << "Can't find the sensor active array size.";
+        int active_array_w = entry.data.i32[0];
+        int active_array_h = entry.data.i32[1];
+
+        EXPECT_LE(active_array_h, pixel_array_h);
+        EXPECT_LE(active_array_w, pixel_array_w);
+    }
+}
+
+TEST_F(Camera3Device, DefaultSettingsStillCaptureHasAndroidControlMode) {
+    ASSERT_TRUE(NULL != cam_device()->ops) << "Camera device ops are NULL";
+    const camera_metadata_t *default_settings =
+        cam_device()->ops->construct_default_request_settings(cam_device(),
+            CAMERA3_TEMPLATE_STILL_CAPTURE);
+    ASSERT_TRUE(NULL != default_settings) << "Camera default settings are NULL";
+    camera_metadata_entry entry;
+    ASSERT_EQ(0, find_camera_metadata_entry(
+                const_cast<camera_metadata_t*>(default_settings),
+                ANDROID_CONTROL_MODE, &entry))
+                    << "Can't find ANDROID_CONTROL_MODE in default settings.";
+}
+
+}  // namespace tests