am 888e507b: (-s ours) snap to klp-dev-plus-aosp 19b13b9 with history

* commit '888e507b9756d0a572944ee81e80ffa08797b79d':
diff --git a/include/hardware/audio_effect.h b/include/hardware/audio_effect.h
index b49d02d..ee48e4c 100644
--- a/include/hardware/audio_effect.h
+++ b/include/hardware/audio_effect.h
@@ -815,7 +815,7 @@
     uint32_t   samplingRate;    // sampling rate
     uint32_t   channels;        // channel mask (see audio_channel_mask_t in audio.h)
     buffer_provider_t bufferProvider;   // buffer provider
-    uint8_t    format;          // Audio format  (see see audio_format_t in audio.h)
+    uint8_t    format;          // Audio format (see audio_format_t in audio.h)
     uint8_t    accessMode;      // read/write or accumulate in buffer (effect_buffer_access_e)
     uint16_t   mask;            // indicates which of the above fields is valid
 } buffer_config_t;
diff --git a/include/hardware/gps.h b/include/hardware/gps.h
index 458b5b4..4167793 100644
--- a/include/hardware/gps.h
+++ b/include/hardware/gps.h
@@ -221,6 +221,11 @@
 #define AGPS_INTERFACE      "agps"
 
 /**
+ * Name of the Supl Certificate interface.
+ */
+#define SUPL_CERTIFICATE_INTERFACE  "supl-certificate"
+
+/**
  * Name for NI interface
  */
 #define GPS_NI_INTERFACE "gps-ni"
@@ -507,7 +512,7 @@
      */
     void  (*init)( AGpsCallbacks* callbacks );
     /**
-     * Notifies that a data connection is available and sets 
+     * Notifies that a data connection is available and sets
      * the name of the APN to be used for SUPL.
      */
     int  (*data_conn_open)( const char* apn );
@@ -516,7 +521,7 @@
      */
     int  (*data_conn_closed)();
     /**
-     * Notifies that a data connection is not available for AGPS. 
+     * Notifies that a data connection is not available for AGPS.
      */
     int  (*data_conn_failed)();
     /**
@@ -525,6 +530,72 @@
     int  (*set_server)( AGpsType type, const char* hostname, int port );
 } AGpsInterface;
 
+/** Error codes associated with certificate operations */
+#define AGPS_CERTIFICATE_OPERATION_SUCCESS               0
+#define AGPS_CERTIFICATE_ERROR_GENERIC                -100
+#define AGPS_CERTIFICATE_ERROR_TOO_MANY_CERTIFICATES  -101
+
+/** A data structure that represents an X.509 certificate using DER encoding */
+typedef struct {
+    size_t  length;
+    u_char* data;
+} DerEncodedCertificate;
+
+/**
+ * A type definition for SHA1 Fingerprints used to identify X.509 Certificates
+ * The Fingerprint is a digest of the DER Certificate that uniquely identifies it.
+ */
+typedef struct {
+    u_char data[20];
+} Sha1CertificateFingerprint;
+
+/** AGPS Inteface to handle SUPL certificate operations */
+typedef struct {
+    /** set to sizeof(SuplCertificateInterface) */
+    size_t size;
+
+    /**
+     * Installs a set of Certificates used for SUPL connections to the AGPS server.
+     * If needed the HAL should find out internally any certificates that need to be removed to
+     * accommodate the certificates to install.
+     * The certificates installed represent a full set of valid certificates needed to connect to
+     * AGPS SUPL servers.
+     * The list of certificates is required, and all must be available at the same time, when trying
+     * to establish a connection with the AGPS Server.
+     *
+     * Parameters:
+     *      certificates - A pointer to an array of DER encoded certificates that are need to be
+     *                     installed in the HAL.
+     *      length - The number of certificates to install.
+     * Returns:
+     *      AGPS_CERTIFICATE_OPERATION_SUCCESS if the operation is completed successfully
+     *      AGPS_CERTIFICATE_ERROR_TOO_MANY_CERTIFICATES if the HAL cannot store the number of
+     *          certificates attempted to be installed, the state of the certificates stored should
+     *          remain the same as before on this error case.
+     *
+     * IMPORTANT:
+     *      If needed the HAL should find out internally the set of certificates that need to be
+     *      removed to accommodate the certificates to install.
+     */
+    int  (*install_certificates) ( const DerEncodedCertificate* certificates, size_t length );
+
+    /**
+     * Notifies the HAL that a list of certificates used for SUPL connections are revoked. It is
+     * expected that the given set of certificates is removed from the internal store of the HAL.
+     *
+     * Parameters:
+     *      fingerprints - A pointer to an array of SHA1 Fingerprints to identify the set of
+     *                     certificates to revoke.
+     *      length - The number of fingerprints provided.
+     * Returns:
+     *      AGPS_CERTIFICATE_OPERATION_SUCCESS if the operation is completed successfully.
+     *
+     * IMPORTANT:
+     *      If any of the certificates provided (through its fingerprint) is not known by the HAL,
+     *      it should be ignored and continue revoking/deleting the rest of them.
+     */
+    int  (*revoke_certificates) ( const Sha1CertificateFingerprint* fingerprints, size_t length );
+} SuplCertificateInterface;
 
 /** Represents an NI request */
 typedef struct {
diff --git a/include/hardware/hardware.h b/include/hardware/hardware.h
index 416ae39..74f57aa 100644
--- a/include/hardware/hardware.h
+++ b/include/hardware/hardware.h
@@ -144,8 +144,12 @@
     /** module's dso */
     void* dso;
 
+#ifdef __LP64__
+    uint64_t reserved[32-7];
+#else
     /** padding to 128 bytes, reserved for future use */
     uint32_t reserved[32-7];
+#endif
 
 } hw_module_t;
 
@@ -186,7 +190,11 @@
     struct hw_module_t* module;
 
     /** padding reserved for future use */
+#ifdef __LP64__
+    uint64_t reserved[12];
+#else
     uint32_t reserved[12];
+#endif
 
     /** Close this device */
     int (*close)(struct hw_device_t* device);
diff --git a/include/hardware/hwcomposer.h b/include/hardware/hwcomposer.h
index 86479d3..82e7671 100644
--- a/include/hardware/hwcomposer.h
+++ b/include/hardware/hwcomposer.h
@@ -262,7 +262,7 @@
     };
 
     /* Allow for expansion w/o breaking binary compatibility.
-     * Pad layer to 96 bytes, assuming 32-bit pointers.
+     * Pad layer to 96 bytes.
      */
     int32_t reserved[24 - 19];
 
diff --git a/include/hardware/nfc_tag.h b/include/hardware/nfc_tag.h
new file mode 100644
index 0000000..72028f4
--- /dev/null
+++ b/include/hardware/nfc_tag.h
@@ -0,0 +1,83 @@
+/*
+ * 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_NFC_TAG_HAL_INTERFACE_H
+#define ANDROID_NFC_TAG_HAL_INTERFACE_H
+
+#include <stdint.h>
+
+#include <hardware/hardware.h>
+
+__BEGIN_DECLS
+
+/*
+ * HAL for programmable NFC tags.
+ *
+ */
+
+#define NFC_TAG_HARDWARE_MODULE_ID "nfc_tag"
+#define NFC_TAG_ID "tag"
+
+typedef struct nfc_tag_module_t {
+    struct hw_module_t common;
+} nfc_tag_module_t;
+
+typedef struct nfc_tag_device {
+    struct hw_device_t common;
+
+    /**
+     * Initialize the NFC tag.
+     *
+     * The driver must:
+     *   * Set the static lock bytes to read only
+     *   * Configure the Capability Container to disable write acess
+     *         eg: 0xE1 0x10 <size> 0x0F
+     *
+     * This function is called once before any calls to setContent().
+     *
+     * Return 0 on success or -errno on error.
+     */
+    int (*init)(const struct nfc_tag_device *dev);
+
+    /**
+     * Set the NFC tag content.
+     *
+     * The driver must write <data> in the data area of the tag starting at
+     * byte 0 of block 4 and zero the rest of the data area.
+     *
+     * Returns 0 on success or -errno on error.
+     */
+    int (*setContent)(const struct nfc_tag_device *dev, const uint8_t *data, size_t len);
+
+    /**
+     * Returns the memory size of the data area.
+     */
+    int (*getMemorySize)(const struct nfc_tag_device *dev);
+} nfc_tag_device_t;
+
+static inline int nfc_tag_open(const struct hw_module_t* module,
+                               nfc_tag_device_t** dev) {
+    return module->methods->open(module, NFC_TAG_ID,
+                                 (struct hw_device_t**)dev);
+}
+
+static inline int nfc_tag_close(nfc_tag_device_t* dev) {
+    return dev->common.close(&dev->common);
+}
+
+__END_DECLS
+
+#endif // ANDROID_NFC_TAG_HAL_INTERFACE_H
diff --git a/modules/Android.mk b/modules/Android.mk
index b2d5a2a..1935b11 100644
--- a/modules/Android.mk
+++ b/modules/Android.mk
@@ -1,3 +1,3 @@
 hardware_modules := gralloc hwcomposer audio nfc nfc-nci local_time \
-	power usbaudio audio_remote_submix camera consumerir
+	power usbaudio audio_remote_submix camera consumerir sensors
 include $(call all-named-subdir-makefiles,$(hardware_modules))
diff --git a/modules/camera/Android.mk b/modules/camera/Android.mk
index e02a143..02d8a33 100644
--- a/modules/camera/Android.mk
+++ b/modules/camera/Android.mk
@@ -26,14 +26,17 @@
 LOCAL_SRC_FILES := \
 	CameraHAL.cpp \
 	Camera.cpp \
+	ExampleCamera.cpp \
 	Metadata.cpp \
 	Stream.cpp \
+	VendorTags.cpp \
 
 LOCAL_SHARED_LIBRARIES := \
 	libcamera_metadata \
 	libcutils \
 	liblog \
 	libsync \
+	libutils \
 
 LOCAL_CFLAGS += -Wall -Wextra -fvisibility=hidden
 
diff --git a/modules/camera/Camera.cpp b/modules/camera/Camera.cpp
index 973380e..57cdb47 100644
--- a/modules/camera/Camera.cpp
+++ b/modules/camera/Camera.cpp
@@ -15,11 +15,12 @@
  */
 
 #include <cstdlib>
-#include <pthread.h>
+#include <stdio.h>
 #include <hardware/camera3.h>
 #include <sync/sync.h>
 #include <system/camera_metadata.h>
 #include <system/graphics.h>
+#include <utils/Mutex.h>
 #include "CameraHAL.h"
 #include "Metadata.h"
 #include "Stream.h"
@@ -29,15 +30,12 @@
 #include <cutils/log.h>
 
 #define ATRACE_TAG (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
-#include <cutils/trace.h>
-#include "ScopedTrace.h"
+#include <utils/Trace.h>
 
 #include "Camera.h"
 
 #define CAMERA_SYNC_TIMEOUT 5000 // in msecs
 
-#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
-
 namespace default_camera_hal {
 
 extern "C" {
@@ -59,9 +57,7 @@
     mNumStreams(0),
     mSettings(NULL)
 {
-    pthread_mutex_init(&mMutex, NULL);
-    pthread_mutex_init(&mStaticInfoMutex, NULL);
-
+    memset(&mTemplates, 0, sizeof(mTemplates));
     memset(&mDevice, 0, sizeof(mDevice));
     mDevice.common.tag    = HARDWARE_DEVICE_TAG;
     mDevice.common.version = CAMERA_DEVICE_API_VERSION_3_0;
@@ -72,17 +68,18 @@
 
 Camera::~Camera()
 {
-    pthread_mutex_destroy(&mMutex);
-    pthread_mutex_destroy(&mStaticInfoMutex);
+    if (mStaticInfo != NULL) {
+        free_camera_metadata(mStaticInfo);
+    }
 }
 
 int Camera::open(const hw_module_t *module, hw_device_t **device)
 {
     ALOGI("%s:%d: Opening camera device", __func__, mId);
-    CAMTRACE_CALL();
-    pthread_mutex_lock(&mMutex);
+    ATRACE_CALL();
+    android::Mutex::Autolock al(mDeviceLock);
+
     if (mBusy) {
-        pthread_mutex_unlock(&mMutex);
         ALOGE("%s:%d: Error! Camera device already opened", __func__, mId);
         return -EBUSY;
     }
@@ -91,217 +88,62 @@
     mBusy = true;
     mDevice.common.module = const_cast<hw_module_t*>(module);
     *device = &mDevice.common;
-
-    pthread_mutex_unlock(&mMutex);
     return 0;
 }
 
 int Camera::getInfo(struct camera_info *info)
 {
+    android::Mutex::Autolock al(mStaticInfoLock);
+
     info->facing = CAMERA_FACING_FRONT;
     info->orientation = 0;
     info->device_version = mDevice.common.version;
-
-    pthread_mutex_lock(&mStaticInfoMutex);
     if (mStaticInfo == NULL) {
         mStaticInfo = initStaticInfo();
     }
-    pthread_mutex_unlock(&mStaticInfoMutex);
-
     info->static_camera_characteristics = mStaticInfo;
-
     return 0;
 }
 
 int Camera::close()
 {
     ALOGI("%s:%d: Closing camera device", __func__, mId);
-    CAMTRACE_CALL();
-    pthread_mutex_lock(&mMutex);
+    ATRACE_CALL();
+    android::Mutex::Autolock al(mDeviceLock);
+
     if (!mBusy) {
-        pthread_mutex_unlock(&mMutex);
         ALOGE("%s:%d: Error! Camera device not open", __func__, mId);
         return -EINVAL;
     }
 
     // TODO: close camera dev nodes, etc
     mBusy = false;
-
-    pthread_mutex_unlock(&mMutex);
     return 0;
 }
 
 int Camera::initialize(const camera3_callback_ops_t *callback_ops)
 {
+    int res;
+
     ALOGV("%s:%d: callback_ops=%p", __func__, mId, callback_ops);
     mCallbackOps = callback_ops;
-    // Create standard settings templates
-    // 0 is invalid as template
-    mTemplates[0] = NULL;
-    // CAMERA3_TEMPLATE_PREVIEW = 1
-    mTemplates[1] = new Metadata(ANDROID_CONTROL_MODE_OFF,
-            ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW);
-    // CAMERA3_TEMPLATE_STILL_CAPTURE = 2
-    mTemplates[2] = new Metadata(ANDROID_CONTROL_MODE_OFF,
-            ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE);
-    // CAMERA3_TEMPLATE_VIDEO_RECORD = 3
-    mTemplates[3] = new Metadata(ANDROID_CONTROL_MODE_OFF,
-            ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD);
-    // CAMERA3_TEMPLATE_VIDEO_SNAPSHOT = 4
-    mTemplates[4] = new Metadata(ANDROID_CONTROL_MODE_OFF,
-            ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT);
-    // CAMERA3_TEMPLATE_STILL_ZERO_SHUTTER_LAG = 5
-    mTemplates[5] = new Metadata(ANDROID_CONTROL_MODE_OFF,
-            ANDROID_CONTROL_CAPTURE_INTENT_ZERO_SHUTTER_LAG);
-    // Pre-generate metadata structures
-    for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
-        mTemplates[i]->generate();
+    // per-device specific initialization
+    res = initDevice();
+    if (res != 0) {
+        ALOGE("%s:%d: Failed to initialize device!", __func__, mId);
+        return res;
     }
-    // TODO: create vendor templates
     return 0;
 }
 
-camera_metadata_t *Camera::initStaticInfo()
-{
-    /*
-     * Setup static camera info.  This will have to customized per camera
-     * device.
-     */
-    Metadata m;
-
-    /* android.control */
-    int32_t android_control_ae_available_target_fps_ranges[] = {30, 30};
-    m.addInt32(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES,
-            ARRAY_SIZE(android_control_ae_available_target_fps_ranges),
-            android_control_ae_available_target_fps_ranges);
-
-    int32_t android_control_ae_compensation_range[] = {-4, 4};
-    m.addInt32(ANDROID_CONTROL_AE_COMPENSATION_RANGE,
-            ARRAY_SIZE(android_control_ae_compensation_range),
-            android_control_ae_compensation_range);
-
-    camera_metadata_rational_t android_control_ae_compensation_step[] = {{2,1}};
-    m.addRational(ANDROID_CONTROL_AE_COMPENSATION_STEP,
-            ARRAY_SIZE(android_control_ae_compensation_step),
-            android_control_ae_compensation_step);
-
-    int32_t android_control_max_regions[] = {1};
-    m.addInt32(ANDROID_CONTROL_MAX_REGIONS,
-            ARRAY_SIZE(android_control_max_regions),
-            android_control_max_regions);
-
-    /* android.jpeg */
-    int32_t android_jpeg_available_thumbnail_sizes[] = {0, 0, 128, 96};
-    m.addInt32(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES,
-            ARRAY_SIZE(android_jpeg_available_thumbnail_sizes),
-            android_jpeg_available_thumbnail_sizes);
-
-    /* android.lens */
-    float android_lens_info_available_focal_lengths[] = {1.0};
-    m.addFloat(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS,
-            ARRAY_SIZE(android_lens_info_available_focal_lengths),
-            android_lens_info_available_focal_lengths);
-
-    /* android.request */
-    int32_t android_request_max_num_output_streams[] = {0, 3, 1};
-    m.addInt32(ANDROID_REQUEST_MAX_NUM_OUTPUT_STREAMS,
-            ARRAY_SIZE(android_request_max_num_output_streams),
-            android_request_max_num_output_streams);
-
-    /* android.scaler */
-    int32_t android_scaler_available_formats[] = {
-            HAL_PIXEL_FORMAT_RAW_SENSOR,
-            HAL_PIXEL_FORMAT_BLOB,
-            HAL_PIXEL_FORMAT_RGBA_8888,
-            HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,
-            // These are handled by YCbCr_420_888
-            //        HAL_PIXEL_FORMAT_YV12,
-            //        HAL_PIXEL_FORMAT_YCrCb_420_SP,
-            HAL_PIXEL_FORMAT_YCbCr_420_888};
-    m.addInt32(ANDROID_SCALER_AVAILABLE_FORMATS,
-            ARRAY_SIZE(android_scaler_available_formats),
-            android_scaler_available_formats);
-
-    int64_t android_scaler_available_jpeg_min_durations[] = {1};
-    m.addInt64(ANDROID_SCALER_AVAILABLE_JPEG_MIN_DURATIONS,
-            ARRAY_SIZE(android_scaler_available_jpeg_min_durations),
-            android_scaler_available_jpeg_min_durations);
-
-    int32_t android_scaler_available_jpeg_sizes[] = {640, 480};
-    m.addInt32(ANDROID_SCALER_AVAILABLE_JPEG_SIZES,
-            ARRAY_SIZE(android_scaler_available_jpeg_sizes),
-            android_scaler_available_jpeg_sizes);
-
-    float android_scaler_available_max_digital_zoom[] = {1};
-    m.addFloat(ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM,
-            ARRAY_SIZE(android_scaler_available_max_digital_zoom),
-            android_scaler_available_max_digital_zoom);
-
-    int64_t android_scaler_available_processed_min_durations[] = {1};
-    m.addInt64(ANDROID_SCALER_AVAILABLE_PROCESSED_MIN_DURATIONS,
-            ARRAY_SIZE(android_scaler_available_processed_min_durations),
-            android_scaler_available_processed_min_durations);
-
-    int32_t android_scaler_available_processed_sizes[] = {640, 480};
-    m.addInt32(ANDROID_SCALER_AVAILABLE_PROCESSED_SIZES,
-            ARRAY_SIZE(android_scaler_available_processed_sizes),
-            android_scaler_available_processed_sizes);
-
-    int64_t android_scaler_available_raw_min_durations[] = {1};
-    m.addInt64(ANDROID_SCALER_AVAILABLE_RAW_MIN_DURATIONS,
-            ARRAY_SIZE(android_scaler_available_raw_min_durations),
-            android_scaler_available_raw_min_durations);
-
-    int32_t android_scaler_available_raw_sizes[] = {640, 480};
-    m.addInt32(ANDROID_SCALER_AVAILABLE_RAW_SIZES,
-            ARRAY_SIZE(android_scaler_available_raw_sizes),
-            android_scaler_available_raw_sizes);
-
-    /* android.sensor */
-
-    int32_t android_sensor_info_active_array_size[] = {0, 0, 640, 480};
-    m.addInt32(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE,
-            ARRAY_SIZE(android_sensor_info_active_array_size),
-            android_sensor_info_active_array_size);
-
-    int32_t android_sensor_info_sensitivity_range[] =
-            {100, 1600};
-    m.addInt32(ANDROID_SENSOR_INFO_SENSITIVITY_RANGE,
-            ARRAY_SIZE(android_sensor_info_sensitivity_range),
-            android_sensor_info_sensitivity_range);
-
-    int64_t android_sensor_info_max_frame_duration[] = {30000000000};
-    m.addInt64(ANDROID_SENSOR_INFO_MAX_FRAME_DURATION,
-            ARRAY_SIZE(android_sensor_info_max_frame_duration),
-            android_sensor_info_max_frame_duration);
-
-    float android_sensor_info_physical_size[] = {3.2, 2.4};
-    m.addFloat(ANDROID_SENSOR_INFO_PHYSICAL_SIZE,
-            ARRAY_SIZE(android_sensor_info_physical_size),
-            android_sensor_info_physical_size);
-
-    int32_t android_sensor_info_pixel_array_size[] = {640, 480};
-    m.addInt32(ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE,
-            ARRAY_SIZE(android_sensor_info_pixel_array_size),
-            android_sensor_info_pixel_array_size);
-
-    int32_t android_sensor_orientation[] = {0};
-    m.addInt32(ANDROID_SENSOR_ORIENTATION,
-            ARRAY_SIZE(android_sensor_orientation),
-            android_sensor_orientation);
-
-    /* End of static camera characteristics */
-
-    return clone_camera_metadata(m.generate());
-}
-
 int Camera::configureStreams(camera3_stream_configuration_t *stream_config)
 {
     camera3_stream_t *astream;
     Stream **newStreams = NULL;
 
-    CAMTRACE_CALL();
     ALOGV("%s:%d: stream_config=%p", __func__, mId, stream_config);
+    ATRACE_CALL();
+    android::Mutex::Autolock al(mDeviceLock);
 
     if (stream_config == NULL) {
         ALOGE("%s:%d: NULL stream configuration array", __func__, mId);
@@ -317,8 +159,6 @@
     ALOGV("%s:%d: Number of Streams: %d", __func__, mId,
             stream_config->num_streams);
 
-    pthread_mutex_lock(&mMutex);
-
     // Mark all current streams unused for now
     for (int i = 0; i < mNumStreams; i++)
         mStreams[i]->mReuse = false;
@@ -356,14 +196,11 @@
 
     // Clear out last seen settings metadata
     setSettings(NULL);
-
-    pthread_mutex_unlock(&mMutex);
     return 0;
 
 err_out:
     // Clean up temporary streams, preserve existing mStreams/mNumStreams
     destroyStreams(newStreams, stream_config->num_streams);
-    pthread_mutex_unlock(&mMutex);
     return -EINVAL;
 }
 
@@ -469,15 +306,20 @@
     return stream->registerBuffers(buf_set);
 }
 
+bool Camera::isValidTemplateType(int type)
+{
+    return type < 1 || type >= CAMERA3_TEMPLATE_COUNT;
+}
+
 const camera_metadata_t* Camera::constructDefaultRequestSettings(int type)
 {
     ALOGV("%s:%d: type=%d", __func__, mId, type);
 
-    if (type < 1 || type >= CAMERA3_TEMPLATE_COUNT) {
+    if (!isValidTemplateType(type)) {
         ALOGE("%s:%d: Invalid template request type: %d", __func__, mId, type);
         return NULL;
     }
-    return mTemplates[type]->generate();
+    return mTemplates[type];
 }
 
 int Camera::processCaptureRequest(camera3_capture_request_t *request)
@@ -485,7 +327,7 @@
     camera3_capture_result result;
 
     ALOGV("%s:%d: request=%p", __func__, mId, request);
-    CAMTRACE_CALL();
+    ATRACE_CALL();
 
     if (request == NULL) {
         ALOGE("%s:%d: NULL request recieved", __func__, mId);
@@ -565,12 +407,6 @@
         mSettings = clone_camera_metadata(new_settings);
 }
 
-bool Camera::isValidCaptureSettings(const camera_metadata_t* /*settings*/)
-{
-    // TODO: reject settings that cannot be captured
-    return true;
-}
-
 bool Camera::isValidReprocessSettings(const camera_metadata_t* /*settings*/)
 {
     // TODO: reject settings that cannot be reprocessed
@@ -640,7 +476,62 @@
 void Camera::dump(int fd)
 {
     ALOGV("%s:%d: Dumping to fd %d", __func__, mId, fd);
-    // TODO: dprintf all relevant state to fd
+    ATRACE_CALL();
+    android::Mutex::Autolock al(mDeviceLock);
+
+    fdprintf(fd, "Camera ID: %d (Busy: %d)\n", mId, mBusy);
+
+    // TODO: dump all settings
+    fdprintf(fd, "Most Recent Settings: (%p)\n", mSettings);
+
+    fdprintf(fd, "Number of streams: %d\n", mNumStreams);
+    for (int i = 0; i < mNumStreams; i++) {
+        fdprintf(fd, "Stream %d/%d:\n", i, mNumStreams);
+        mStreams[i]->dump(fd);
+    }
+}
+
+const char* Camera::templateToString(int type)
+{
+    switch (type) {
+    case CAMERA3_TEMPLATE_PREVIEW:
+        return "CAMERA3_TEMPLATE_PREVIEW";
+    case CAMERA3_TEMPLATE_STILL_CAPTURE:
+        return "CAMERA3_TEMPLATE_STILL_CAPTURE";
+    case CAMERA3_TEMPLATE_VIDEO_RECORD:
+        return "CAMERA3_TEMPLATE_VIDEO_RECORD";
+    case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
+        return "CAMERA3_TEMPLATE_VIDEO_SNAPSHOT";
+    case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
+        return "CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG";
+    }
+    // TODO: support vendor templates
+    return "Invalid template type!";
+}
+
+int Camera::setTemplate(int type, camera_metadata_t *settings)
+{
+    android::Mutex::Autolock al(mDeviceLock);
+
+    if (!isValidTemplateType(type)) {
+        ALOGE("%s:%d: Invalid template request type: %d", __func__, mId, type);
+        return -EINVAL;
+    }
+
+    if (mTemplates[type] != NULL) {
+        ALOGE("%s:%d: Setting already constructed template type %s(%d)",
+                __func__, mId, templateToString(type), type);
+        return -EINVAL;
+    }
+
+    // Make a durable copy of the underlying metadata
+    mTemplates[type] = clone_camera_metadata(settings);
+    if (mTemplates[type] == NULL) {
+        ALOGE("%s:%d: Failed to clone metadata %p for template type %s(%d)",
+                __func__, mId, settings, templateToString(type), type);
+        return -EINVAL;
+    }
+    return 0;
 }
 
 extern "C" {
diff --git a/modules/camera/Camera.h b/modules/camera/Camera.h
index be672f9..f1f33b1 100644
--- a/modules/camera/Camera.h
+++ b/modules/camera/Camera.h
@@ -17,9 +17,9 @@
 #ifndef CAMERA_H_
 #define CAMERA_H_
 
-#include <pthread.h>
 #include <hardware/hardware.h>
 #include <hardware/camera3.h>
+#include <utils/Mutex.h>
 #include "Metadata.h"
 #include "Stream.h"
 
@@ -28,12 +28,14 @@
 // This is constructed when the HAL module is loaded, one per physical camera.
 // It is opened by the framework, and must be closed before it can be opened
 // again.
+// This is an abstract class, containing all logic and data shared between all
+// camera devices (front, back, etc) and common to the ISP.
 class Camera {
     public:
         // id is used to distinguish cameras. 0 <= id < NUM_CAMERAS.
         // module is a handle to the HAL module, used when the device is opened.
         Camera(int id);
-        ~Camera();
+        virtual ~Camera();
 
         // Common Camera Device Operations (see <hardware/camera_common.h>)
         int open(const hw_module_t *module, hw_device_t **device);
@@ -49,12 +51,22 @@
         void getMetadataVendorTagOps(vendor_tag_query_ops_t *ops);
         void dump(int fd);
 
-        // Camera device handle returned to framework for use
-        camera3_device_t mDevice;
+
+    protected:
+        // Initialize static camera characteristics for individual device
+        virtual camera_metadata_t *initStaticInfo() = 0;
+        // Verify settings are valid for a capture
+        virtual bool isValidCaptureSettings(const camera_metadata_t *) = 0;
+        // Separate initialization method for individual devices when opened
+        virtual int initDevice() = 0;
+        // Accessor used by initDevice() to set the templates' metadata
+        int setTemplate(int type, camera_metadata_t *static_info);
+        // Prettyprint template names
+        const char* templateToString(int type);
 
     private:
-        // Separate initialization method for static metadata
-        camera_metadata_t *initStaticInfo();
+        // Camera device handle returned to framework for use
+        camera3_device_t mDevice;
         // Reuse a stream already created by this device
         Stream *reuseStream(camera3_stream_t *astream);
         // Destroy all streams in a stream array, and the array itself
@@ -65,8 +77,6 @@
         void setupStreams(Stream **array, int count);
         // Copy new settings for re-use and clean up old settings.
         void setSettings(const camera_metadata_t *new_settings);
-        // Verify settings are valid for a capture
-        bool isValidCaptureSettings(const camera_metadata_t *settings);
         // Verify settings are valid for reprocessing an input buffer
         bool isValidReprocessSettings(const camera_metadata_t *settings);
         // Process an output buffer
@@ -74,6 +84,8 @@
                 camera3_stream_buffer_t *out);
         // Send a shutter notify message with start of exposure time
         void notifyShutter(uint32_t frame_number, uint64_t timestamp);
+        // Is type a valid template type (and valid index into mTemplates)
+        bool isValidTemplateType(int type);
 
         // Identifier used by framework to distinguish cameras
         const int mId;
@@ -88,16 +100,16 @@
         // Methods used to call back into the framework
         const camera3_callback_ops_t *mCallbackOps;
         // Lock protecting the Camera object for modifications
-        pthread_mutex_t mMutex;
+        android::Mutex mDeviceLock;
         // Lock protecting only static camera characteristics, which may
         // be accessed without the camera device open
-        pthread_mutex_t mStaticInfoMutex;
+        android::Mutex mStaticInfoLock;
         // Array of handles to streams currently in use by the device
         Stream **mStreams;
         // Number of streams in mStreams
         int mNumStreams;
         // Static array of standard camera settings templates
-        Metadata *mTemplates[CAMERA3_TEMPLATE_COUNT];
+        camera_metadata_t *mTemplates[CAMERA3_TEMPLATE_COUNT];
         // Most recent request settings seen, memoized to be reused
         camera_metadata_t *mSettings;
 };
diff --git a/modules/camera/CameraHAL.cpp b/modules/camera/CameraHAL.cpp
index dfbbe4c..148f99c 100644
--- a/modules/camera/CameraHAL.cpp
+++ b/modules/camera/CameraHAL.cpp
@@ -17,7 +17,8 @@
 #include <cstdlib>
 #include <hardware/camera_common.h>
 #include <hardware/hardware.h>
-#include "Camera.h"
+#include "ExampleCamera.h"
+#include "VendorTags.h"
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "DefaultCameraHAL"
@@ -38,25 +39,24 @@
 
 // Default Camera HAL has 2 cameras, front and rear.
 static CameraHAL gCameraHAL(2);
+// Handle containing vendor tag functionality
+static VendorTags gVendorTags;
 
 CameraHAL::CameraHAL(int num_cameras)
   : mNumberOfCameras(num_cameras),
     mCallbacks(NULL)
 {
-    int i;
-
     // Allocate camera array and instantiate camera devices
     mCameras = new Camera*[mNumberOfCameras];
-    for (i = 0; i < mNumberOfCameras; i++) {
-        mCameras[i] = new Camera(i);
-    }
+    // Rear camera
+    mCameras[0] = new ExampleCamera(0);
+    // Front camera
+    mCameras[1] = new ExampleCamera(1);
 }
 
 CameraHAL::~CameraHAL()
 {
-    int i;
-
-    for (i = 0; i < mNumberOfCameras; i++) {
+    for (int i = 0; i < mNumberOfCameras; i++) {
         delete mCameras[i];
     }
     delete [] mCameras;
@@ -124,6 +124,41 @@
     return gCameraHAL.setCallbacks(callbacks);
 }
 
+static int get_tag_count(const vendor_tag_ops_t* ops)
+{
+    return gVendorTags.getTagCount(ops);
+}
+
+static void get_all_tags(const vendor_tag_ops_t* ops, uint32_t* tag_array)
+{
+    gVendorTags.getAllTags(ops, tag_array);
+}
+
+static const char* get_section_name(const vendor_tag_ops_t* ops, uint32_t tag)
+{
+    return gVendorTags.getSectionName(ops, tag);
+}
+
+static const char* get_tag_name(const vendor_tag_ops_t* ops, uint32_t tag)
+{
+    return gVendorTags.getTagName(ops, tag);
+}
+
+static int get_tag_type(const vendor_tag_ops_t* ops, uint32_t tag)
+{
+    return gVendorTags.getTagType(ops, tag);
+}
+
+static void get_vendor_tag_ops(vendor_tag_ops_t* ops)
+{
+    ALOGV("%s : ops=%p", __func__, ops);
+    ops->get_tag_count      = get_tag_count;
+    ops->get_all_tags       = get_all_tags;
+    ops->get_section_name   = get_section_name;
+    ops->get_tag_name       = get_tag_name;
+    ops->get_tag_type       = get_tag_type;
+}
+
 static int open_dev(const hw_module_t* mod, const char* name, hw_device_t** dev)
 {
     return gCameraHAL.open(mod, name, dev);
@@ -136,7 +171,7 @@
 camera_module_t HAL_MODULE_INFO_SYM __attribute__ ((visibility("default"))) = {
     common : {
         tag                : HARDWARE_MODULE_TAG,
-        module_api_version : CAMERA_MODULE_API_VERSION_2_0,
+        module_api_version : CAMERA_MODULE_API_VERSION_2_2,
         hal_api_version    : HARDWARE_HAL_API_VERSION,
         id                 : CAMERA_HARDWARE_MODULE_ID,
         name               : "Default Camera HAL",
@@ -147,7 +182,8 @@
     },
     get_number_of_cameras : get_number_of_cameras,
     get_camera_info       : get_camera_info,
-    set_callbacks         : set_callbacks
+    set_callbacks         : set_callbacks,
+    get_vendor_tag_ops    : get_vendor_tag_ops
 };
 } // extern "C"
 
diff --git a/modules/camera/CameraHAL.h b/modules/camera/CameraHAL.h
index ba0db4e..a5edc85 100644
--- a/modules/camera/CameraHAL.h
+++ b/modules/camera/CameraHAL.h
@@ -21,6 +21,7 @@
 #include <hardware/hardware.h>
 #include <hardware/camera_common.h>
 #include "Camera.h"
+#include "VendorTags.h"
 
 namespace default_camera_hal {
 // CameraHAL contains all module state that isn't specific to an individual
@@ -34,6 +35,7 @@
         int getNumberOfCameras();
         int getCameraInfo(int camera_id, struct camera_info *info);
         int setCallbacks(const camera_module_callbacks_t *callbacks);
+        void getVendorTagOps(vendor_tag_ops_t* ops);
 
         // Hardware Module Interface (see <hardware/hardware.h>)
         int open(const hw_module_t* mod, const char* name, hw_device_t** dev);
diff --git a/modules/camera/ExampleCamera.cpp b/modules/camera/ExampleCamera.cpp
new file mode 100644
index 0000000..16e1e02
--- /dev/null
+++ b/modules/camera/ExampleCamera.cpp
@@ -0,0 +1,261 @@
+/*
+ * 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 <system/camera_metadata.h>
+#include "Camera.h"
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "ExampleCamera"
+#include <cutils/log.h>
+
+#define ATRACE_TAG (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
+#include <utils/Trace.h>
+
+#include "ExampleCamera.h"
+
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
+
+namespace default_camera_hal {
+
+ExampleCamera::ExampleCamera(int id) : Camera(id)
+{
+}
+
+ExampleCamera::~ExampleCamera()
+{
+}
+
+camera_metadata_t *ExampleCamera::initStaticInfo()
+{
+    /*
+     * Setup static camera info.  This will have to customized per camera
+     * device.
+     */
+    Metadata m;
+
+    /* android.control */
+    int32_t android_control_ae_available_target_fps_ranges[] = {30, 30};
+    m.addInt32(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES,
+            ARRAY_SIZE(android_control_ae_available_target_fps_ranges),
+            android_control_ae_available_target_fps_ranges);
+
+    int32_t android_control_ae_compensation_range[] = {-4, 4};
+    m.addInt32(ANDROID_CONTROL_AE_COMPENSATION_RANGE,
+            ARRAY_SIZE(android_control_ae_compensation_range),
+            android_control_ae_compensation_range);
+
+    camera_metadata_rational_t android_control_ae_compensation_step[] = {{2,1}};
+    m.addRational(ANDROID_CONTROL_AE_COMPENSATION_STEP,
+            ARRAY_SIZE(android_control_ae_compensation_step),
+            android_control_ae_compensation_step);
+
+    int32_t android_control_max_regions[] = {1};
+    m.addInt32(ANDROID_CONTROL_MAX_REGIONS,
+            ARRAY_SIZE(android_control_max_regions),
+            android_control_max_regions);
+
+    /* android.jpeg */
+    int32_t android_jpeg_available_thumbnail_sizes[] = {0, 0, 128, 96};
+    m.addInt32(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES,
+            ARRAY_SIZE(android_jpeg_available_thumbnail_sizes),
+            android_jpeg_available_thumbnail_sizes);
+
+    int32_t android_jpeg_max_size[] = {13 * 1024 * 1024}; // 13MB
+    m.addInt32(ANDROID_JPEG_MAX_SIZE,
+            ARRAY_SIZE(android_jpeg_max_size),
+            android_jpeg_max_size);
+
+    /* android.lens */
+    float android_lens_info_available_focal_lengths[] = {1.0};
+    m.addFloat(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS,
+            ARRAY_SIZE(android_lens_info_available_focal_lengths),
+            android_lens_info_available_focal_lengths);
+
+    /* android.request */
+    int32_t android_request_max_num_output_streams[] = {0, 3, 1};
+    m.addInt32(ANDROID_REQUEST_MAX_NUM_OUTPUT_STREAMS,
+            ARRAY_SIZE(android_request_max_num_output_streams),
+            android_request_max_num_output_streams);
+
+    /* android.scaler */
+    int32_t android_scaler_available_formats[] = {
+            HAL_PIXEL_FORMAT_RAW_SENSOR,
+            HAL_PIXEL_FORMAT_BLOB,
+            HAL_PIXEL_FORMAT_RGBA_8888,
+            HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,
+            // These are handled by YCbCr_420_888
+            //        HAL_PIXEL_FORMAT_YV12,
+            //        HAL_PIXEL_FORMAT_YCrCb_420_SP,
+            HAL_PIXEL_FORMAT_YCbCr_420_888};
+    m.addInt32(ANDROID_SCALER_AVAILABLE_FORMATS,
+            ARRAY_SIZE(android_scaler_available_formats),
+            android_scaler_available_formats);
+
+    int64_t android_scaler_available_jpeg_min_durations[] = {1};
+    m.addInt64(ANDROID_SCALER_AVAILABLE_JPEG_MIN_DURATIONS,
+            ARRAY_SIZE(android_scaler_available_jpeg_min_durations),
+            android_scaler_available_jpeg_min_durations);
+
+    int32_t android_scaler_available_jpeg_sizes[] = {640, 480};
+    m.addInt32(ANDROID_SCALER_AVAILABLE_JPEG_SIZES,
+            ARRAY_SIZE(android_scaler_available_jpeg_sizes),
+            android_scaler_available_jpeg_sizes);
+
+    float android_scaler_available_max_digital_zoom[] = {1};
+    m.addFloat(ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM,
+            ARRAY_SIZE(android_scaler_available_max_digital_zoom),
+            android_scaler_available_max_digital_zoom);
+
+    int64_t android_scaler_available_processed_min_durations[] = {1};
+    m.addInt64(ANDROID_SCALER_AVAILABLE_PROCESSED_MIN_DURATIONS,
+            ARRAY_SIZE(android_scaler_available_processed_min_durations),
+            android_scaler_available_processed_min_durations);
+
+    int32_t android_scaler_available_processed_sizes[] = {640, 480};
+    m.addInt32(ANDROID_SCALER_AVAILABLE_PROCESSED_SIZES,
+            ARRAY_SIZE(android_scaler_available_processed_sizes),
+            android_scaler_available_processed_sizes);
+
+    int64_t android_scaler_available_raw_min_durations[] = {1};
+    m.addInt64(ANDROID_SCALER_AVAILABLE_RAW_MIN_DURATIONS,
+            ARRAY_SIZE(android_scaler_available_raw_min_durations),
+            android_scaler_available_raw_min_durations);
+
+    int32_t android_scaler_available_raw_sizes[] = {640, 480};
+    m.addInt32(ANDROID_SCALER_AVAILABLE_RAW_SIZES,
+            ARRAY_SIZE(android_scaler_available_raw_sizes),
+            android_scaler_available_raw_sizes);
+
+    /* android.sensor */
+
+    int32_t android_sensor_info_active_array_size[] = {0, 0, 640, 480};
+    m.addInt32(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE,
+            ARRAY_SIZE(android_sensor_info_active_array_size),
+            android_sensor_info_active_array_size);
+
+    int32_t android_sensor_info_sensitivity_range[] =
+            {100, 1600};
+    m.addInt32(ANDROID_SENSOR_INFO_SENSITIVITY_RANGE,
+            ARRAY_SIZE(android_sensor_info_sensitivity_range),
+            android_sensor_info_sensitivity_range);
+
+    int64_t android_sensor_info_max_frame_duration[] = {30000000000};
+    m.addInt64(ANDROID_SENSOR_INFO_MAX_FRAME_DURATION,
+            ARRAY_SIZE(android_sensor_info_max_frame_duration),
+            android_sensor_info_max_frame_duration);
+
+    float android_sensor_info_physical_size[] = {3.2, 2.4};
+    m.addFloat(ANDROID_SENSOR_INFO_PHYSICAL_SIZE,
+            ARRAY_SIZE(android_sensor_info_physical_size),
+            android_sensor_info_physical_size);
+
+    int32_t android_sensor_info_pixel_array_size[] = {640, 480};
+    m.addInt32(ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE,
+            ARRAY_SIZE(android_sensor_info_pixel_array_size),
+            android_sensor_info_pixel_array_size);
+
+    int32_t android_sensor_orientation[] = {0};
+    m.addInt32(ANDROID_SENSOR_ORIENTATION,
+            ARRAY_SIZE(android_sensor_orientation),
+            android_sensor_orientation);
+
+    /* End of static camera characteristics */
+
+    return clone_camera_metadata(m.get());
+}
+
+int ExampleCamera::initDevice()
+{
+    int res;
+    Metadata base;
+
+    // Create standard settings templates from copies of base metadata
+    // TODO: use vendor tags in base metadata
+    if (res = base.add1UInt8(ANDROID_CONTROL_MODE, ANDROID_CONTROL_MODE_OFF))
+        return res;
+
+    // Use base settings to create all other templates and set them
+    if (res = setPreviewTemplate(base)) return res;
+    if (res = setStillTemplate(base)) return res;
+    if (res = setRecordTemplate(base)) return res;
+    if (res = setSnapshotTemplate(base)) return res;
+    if (res = setZslTemplate(base)) return res;
+
+    return 0;
+}
+
+int ExampleCamera::setPreviewTemplate(Metadata m)
+{
+    int res;
+    // Setup default preview controls
+    if (res = m.add1UInt8(ANDROID_CONTROL_CAPTURE_INTENT,
+            ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW))
+        return res;
+    // TODO: set fast auto-focus, auto-whitebalance, auto-exposure, auto flash
+    return setTemplate(CAMERA3_TEMPLATE_PREVIEW, m.get());
+}
+
+int ExampleCamera::setStillTemplate(Metadata m)
+{
+    int res;
+    // Setup default still capture controls
+    if (res = m.add1UInt8(ANDROID_CONTROL_CAPTURE_INTENT,
+            ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE))
+        return res;
+    // TODO: set fast auto-focus, auto-whitebalance, auto-exposure, auto flash
+    return setTemplate(CAMERA3_TEMPLATE_STILL_CAPTURE, m.get());
+}
+
+int ExampleCamera::setRecordTemplate(Metadata m)
+{
+    int res;
+    // Setup default video record controls
+    if (res = m.add1UInt8(ANDROID_CONTROL_CAPTURE_INTENT,
+            ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD))
+        return res;
+    // TODO: set slow auto-focus, auto-whitebalance, auto-exposure, flash off
+    return setTemplate(CAMERA3_TEMPLATE_VIDEO_RECORD, m.get());
+}
+
+int ExampleCamera::setSnapshotTemplate(Metadata m)
+{
+    int res;
+    // Setup default video snapshot controls
+    if (res = m.add1UInt8(ANDROID_CONTROL_CAPTURE_INTENT,
+            ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT))
+        return res;
+    // TODO: set slow auto-focus, auto-whitebalance, auto-exposure, flash off 
+    return setTemplate(CAMERA3_TEMPLATE_VIDEO_SNAPSHOT, m.get());
+}
+
+int ExampleCamera::setZslTemplate(Metadata m)
+{
+    int res;
+    // Setup default zero shutter lag controls
+    if (res = m.add1UInt8(ANDROID_CONTROL_CAPTURE_INTENT,
+            ANDROID_CONTROL_CAPTURE_INTENT_ZERO_SHUTTER_LAG))
+        return res;
+    // TODO: set reprocessing parameters for zsl input queue
+    return setTemplate(CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG, m.get());
+}
+
+bool ExampleCamera::isValidCaptureSettings(const camera_metadata_t* settings)
+{
+    // TODO: reject settings that cannot be captured
+    return true;
+}
+
+} // namespace default_camera_hal
diff --git a/modules/camera/ExampleCamera.h b/modules/camera/ExampleCamera.h
new file mode 100644
index 0000000..45c4a94
--- /dev/null
+++ b/modules/camera/ExampleCamera.h
@@ -0,0 +1,49 @@
+/*
+ * 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 EXAMPLE_CAMERA_H_
+#define EXAMPLE_CAMERA_H_
+
+#include <system/camera_metadata.h>
+#include "Camera.h"
+
+namespace default_camera_hal {
+// ExampleCamera is an example for a specific camera device. The Camera object
+// contains all logic common between all cameras (e.g. front and back cameras),
+// while a specific camera device (e.g. ExampleCamera) holds all specific
+// metadata and logic about that device.
+class ExampleCamera : public Camera {
+    public:
+        ExampleCamera(int id);
+        ~ExampleCamera();
+
+    private:
+        // Initialize static camera characteristics for individual device
+        camera_metadata_t *initStaticInfo();
+        // Initialize whole device (templates/etc) when opened
+        int initDevice();
+        // Initialize each template metadata controls
+        int setPreviewTemplate(Metadata m);
+        int setStillTemplate(Metadata m);
+        int setRecordTemplate(Metadata m);
+        int setSnapshotTemplate(Metadata m);
+        int setZslTemplate(Metadata m);
+        // Verify settings are valid for a capture with this device
+        bool isValidCaptureSettings(const camera_metadata_t* settings);
+};
+} // namespace default_camera_hal
+
+#endif // CAMERA_H_
diff --git a/modules/camera/Metadata.cpp b/modules/camera/Metadata.cpp
index d5854f9..72314d5 100644
--- a/modules/camera/Metadata.cpp
+++ b/modules/camera/Metadata.cpp
@@ -14,7 +14,6 @@
  * limitations under the License.
  */
 
-#include <pthread.h>
 #include <system/camera_metadata.h>
 
 //#define LOG_NDEBUG 0
@@ -22,102 +21,85 @@
 #include <cutils/log.h>
 
 #define ATRACE_TAG (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
-#include <cutils/trace.h>
-#include "ScopedTrace.h"
+#include <utils/Trace.h>
 
 #include "Metadata.h"
 
 namespace default_camera_hal {
 
-Metadata::Metadata()
-  : mHead(NULL),
-    mTail(NULL),
-    mEntryCount(0),
-    mDataCount(0),
-    mGenerated(NULL),
-    mDirty(true)
+Metadata::Metadata():
+    mData(NULL)
 {
-    // NULL (default) pthread mutex attributes
-    pthread_mutex_init(&mMutex, NULL);
 }
 
 Metadata::~Metadata()
 {
-    Entry *current = mHead;
-
-    while (current != NULL) {
-        Entry *tmp = current;
-        current = current->mNext;
-        delete tmp;
-    }
-
-    if (mGenerated != NULL)
-        free_camera_metadata(mGenerated);
-
-    pthread_mutex_destroy(&mMutex);
+    replace(NULL);
 }
 
-Metadata::Metadata(uint8_t mode, uint8_t intent)
-  : mHead(NULL),
-    mTail(NULL),
-    mEntryCount(0),
-    mDataCount(0),
-    mGenerated(NULL),
-    mDirty(true)
+void Metadata::replace(camera_metadata_t *m)
 {
-    pthread_mutex_init(&mMutex, NULL);
-
-    if (validate(ANDROID_CONTROL_MODE, TYPE_BYTE, 1)) {
-        int res = add(ANDROID_CONTROL_MODE, 1, &mode);
-        if (res != 0) {
-            ALOGE("%s: Unable to add mode to template!", __func__);
-        }
-    } else {
-        ALOGE("%s: Invalid mode constructing template!", __func__);
+    if (m == mData) {
+        ALOGE("%s: Replacing metadata with itself?!", __func__);
+        return;
     }
-
-    if (validate(ANDROID_CONTROL_CAPTURE_INTENT, TYPE_BYTE, 1)) {
-        int res = add(ANDROID_CONTROL_CAPTURE_INTENT, 1, &intent);
-        if (res != 0) {
-            ALOGE("%s: Unable to add capture intent to template!", __func__);
-        }
-    } else {
-        ALOGE("%s: Invalid capture intent constructing template!", __func__);
-    }
+    if (mData)
+        free_camera_metadata(mData);
+    mData = m;
 }
 
-int Metadata::addUInt8(uint32_t tag, int count, uint8_t *data)
+int Metadata::init(const camera_metadata_t *metadata)
+{
+    camera_metadata_t* tmp;
+
+    if (!validate_camera_metadata_structure(metadata, NULL))
+        return -EINVAL;
+
+    tmp = clone_camera_metadata(metadata);
+    if (tmp == NULL)
+        return -EINVAL;
+
+    replace(tmp);
+    return 0;
+}
+
+int Metadata::addUInt8(uint32_t tag, int count, const uint8_t *data)
 {
     if (!validate(tag, TYPE_BYTE, count)) return -EINVAL;
     return add(tag, count, data);
 }
 
-int Metadata::addInt32(uint32_t tag, int count, int32_t *data)
+int Metadata::add1UInt8(uint32_t tag, const uint8_t data)
+{
+    return addUInt8(tag, 1, &data);
+}
+
+int Metadata::addInt32(uint32_t tag, int count, const int32_t *data)
 {
     if (!validate(tag, TYPE_INT32, count)) return -EINVAL;
     return add(tag, count, data);
 }
 
-int Metadata::addFloat(uint32_t tag, int count, float *data)
+int Metadata::addFloat(uint32_t tag, int count, const float *data)
 {
     if (!validate(tag, TYPE_FLOAT, count)) return -EINVAL;
     return add(tag, count, data);
 }
 
-int Metadata::addInt64(uint32_t tag, int count, int64_t *data)
+int Metadata::addInt64(uint32_t tag, int count, const int64_t *data)
 {
     if (!validate(tag, TYPE_INT64, count)) return -EINVAL;
     return add(tag, count, data);
 }
 
-int Metadata::addDouble(uint32_t tag, int count, double *data)
+int Metadata::addDouble(uint32_t tag, int count, const double *data)
 {
     if (!validate(tag, TYPE_DOUBLE, count)) return -EINVAL;
     return add(tag, count, data);
 }
 
 int Metadata::addRational(uint32_t tag, int count,
-        camera_metadata_rational_t *data)
+        const camera_metadata_rational_t *data)
 {
     if (!validate(tag, TYPE_RATIONAL, count)) return -EINVAL;
     return add(tag, count, data);
@@ -145,102 +127,46 @@
     return true;
 }
 
-int Metadata::add(uint32_t tag, int count, void *tag_data)
+int Metadata::add(uint32_t tag, int count, const void *tag_data)
 {
+    int res;
+    camera_metadata_t* tmp;
     int tag_type = get_camera_metadata_tag_type(tag);
-    size_t type_sz = camera_metadata_type_size[tag_type];
+    size_t size = calculate_camera_metadata_entry_data_size(tag_type, count);
+    size_t entry_capacity = get_camera_metadata_entry_count(mData) + 1;
+    size_t data_capacity = get_camera_metadata_data_count(mData) + size;
 
-    // Allocate array to hold new metadata
-    void *data = malloc(count * type_sz);
-    if (data == NULL)
+    // Opportunistically attempt to add if metadata has room for it
+    if (!add_camera_metadata_entry(mData, tag, tag_data, count))
+        return 0;
+
+    // Double new dimensions to minimize future reallocations
+    tmp = allocate_camera_metadata(entry_capacity * 2, data_capacity * 2);
+    if (tmp == NULL) {
+        ALOGE("%s: Failed to allocate new metadata with %d entries, %d data",
+                __func__, entry_capacity, data_capacity);
         return -ENOMEM;
-    memcpy(data, tag_data, count * type_sz);
+    }
+    // Append the current metadata to the new (empty) metadata
+    if (res = append_camera_metadata(tmp, mData)) {
+        ALOGE("%s: Failed to append old metadata %p to new %p",
+                __func__, mData, tmp);
+        return res;
+    }
+    // Add the remaining new item
+    if (res = add_camera_metadata_entry(tmp, tag, tag_data, count)) {
+        ALOGE("%s: Failed to add new entry (%d, %p, %d) to metadata %p",
+                __func__, tag, tag_data, count, tmp);
+        return res;
+    }
 
-    pthread_mutex_lock(&mMutex);
-    mEntryCount++;
-    mDataCount += calculate_camera_metadata_entry_data_size(tag_type, count);
-    push(new Entry(tag, data, count));
-    mDirty = true;
-    pthread_mutex_unlock(&mMutex);
+    replace(tmp);
     return 0;
 }
 
-camera_metadata_t* Metadata::generate()
+camera_metadata_t* Metadata::get()
 {
-    pthread_mutex_lock(&mMutex);
-    // Reuse if old generated metadata still valid
-    if (!mDirty && mGenerated != NULL) {
-        ALOGV("%s: Reusing generated metadata at %p", __func__, mGenerated);
-        goto out;
-    }
-    // Destroy old metadata
-    if (mGenerated != NULL) {
-        ALOGV("%s: Freeing generated metadata at %p", __func__, mGenerated);
-        free_camera_metadata(mGenerated);
-        mGenerated = NULL;
-    }
-    // Generate new metadata structure
-    ALOGV("%s: Generating new camera metadata structure, Entries:%d Data:%d",
-            __func__, mEntryCount, mDataCount);
-    mGenerated = allocate_camera_metadata(mEntryCount, mDataCount);
-    if (mGenerated == NULL) {
-        ALOGE("%s: Failed to allocate metadata (%d entries %d data)",
-                __func__, mEntryCount, mDataCount);
-        goto out;
-    }
-    // Walk list of entries adding each one to newly allocated metadata
-    for (Entry *current = mHead; current != NULL; current = current->mNext) {
-        int res = add_camera_metadata_entry(mGenerated, current->mTag,
-                current->mData, current->mCount);
-        if (res != 0) {
-            ALOGE("%s: Failed to add camera metadata: %d", __func__, res);
-            free_camera_metadata(mGenerated);
-            mGenerated = NULL;
-            goto out;
-        }
-    }
-
-out:
-    pthread_mutex_unlock(&mMutex);
-    return mGenerated;
-}
-
-Metadata::Entry::Entry(uint32_t tag, void *data, int count)
-  : mNext(NULL),
-    mPrev(NULL),
-    mTag(tag),
-    mData(data),
-    mCount(count)
-{
-}
-
-void Metadata::push(Entry *e)
-{
-    if (mHead == NULL) {
-        mHead = mTail = e;
-    } else {
-        mTail->insertAfter(e);
-        mTail = e;
-    }
-}
-
-Metadata::Entry::~Entry()
-{
-    if (mNext != NULL)
-        mNext->mPrev = mPrev;
-    if (mPrev != NULL)
-        mPrev->mNext = mNext;
-}
-
-void Metadata::Entry::insertAfter(Entry *e)
-{
-    if (e == NULL)
-        return;
-    if (mNext != NULL)
-        mNext->mPrev = e;
-    e->mNext = mNext;
-    e->mPrev = this;
-    mNext = e;
+    return mData;
 }
 
 } // namespace default_camera_hal
diff --git a/modules/camera/Metadata.h b/modules/camera/Metadata.h
index 22d2f22..f432d04 100644
--- a/modules/camera/Metadata.h
+++ b/modules/camera/Metadata.h
@@ -17,10 +17,9 @@
 #ifndef METADATA_H_
 #define METADATA_H_
 
+#include <stdint.h>
 #include <hardware/camera3.h>
-#include <hardware/gralloc.h>
 #include <system/camera_metadata.h>
-#include <system/graphics.h>
 
 namespace default_camera_hal {
 // Metadata is a convenience class for dealing with libcamera_metadata
@@ -28,51 +27,32 @@
     public:
         Metadata();
         ~Metadata();
-        // Constructor used for request metadata templates
-        Metadata(uint8_t mode, uint8_t intent);
+        // Initialize with framework metadata
+        int init(const camera_metadata_t *metadata);
 
-        // Parse and add an entry
-        int addUInt8(uint32_t tag, int count, uint8_t *data);
-        int addInt32(uint32_t tag, int count, int32_t *data);
-        int addFloat(uint32_t tag, int count, float *data);
-        int addInt64(uint32_t tag, int count, int64_t *data);
-        int addDouble(uint32_t tag, int count, double *data);
+        // Parse and add an entry. Allocates and copies new storage for *data.
+        int addUInt8(uint32_t tag, int count, const uint8_t *data);
+        int add1UInt8(uint32_t tag, const uint8_t data);
+        int addInt32(uint32_t tag, int count, const int32_t *data);
+        int addFloat(uint32_t tag, int count, const float *data);
+        int addInt64(uint32_t tag, int count, const int64_t *data);
+        int addDouble(uint32_t tag, int count, const double *data);
         int addRational(uint32_t tag, int count,
-                camera_metadata_rational_t *data);
-        // Generate a camera_metadata structure and fill it with internal data
-        camera_metadata_t *generate();
+                const camera_metadata_rational_t *data);
+
+        // Get a handle to the current metadata
+        // This is not a durable handle, and may be destroyed by add*/init
+        camera_metadata_t* get();
 
     private:
+        // Actual internal storage
+        camera_metadata_t* mData;
+        // Destroy old metadata and replace with new
+        void replace(camera_metadata_t *m);
         // Validate the tag, type and count for a metadata entry
         bool validate(uint32_t tag, int tag_type, int count);
-        // Add a verified tag with data to this Metadata structure
-        int add(uint32_t tag, int count, void *tag_data);
-
-        class Entry {
-            public:
-                Entry(uint32_t tag, void *data, int count);
-                ~Entry();
-                Entry *mNext;
-                Entry *mPrev;
-                const uint32_t mTag;
-                const void *mData;
-                const int mCount;
-                void insertAfter(Entry *e);
-        };
-        // List ends
-        Entry *mHead;
-        Entry *mTail;
-        // Append entry to list
-        void push(Entry *e);
-        // Total of entries and entry data size
-        int mEntryCount;
-        int mDataCount;
-        // Save generated metadata, invalidated on update
-        camera_metadata_t *mGenerated;
-        // Flag to force metadata regeneration
-        bool mDirty;
-        // Lock protecting the Metadata object for modifications
-        pthread_mutex_t mMutex;
+        // Add a verified tag with data
+        int add(uint32_t tag, int count, const void *tag_data);
 };
 } // namespace default_camera_hal
 
diff --git a/modules/camera/ScopedTrace.h b/modules/camera/ScopedTrace.h
deleted file mode 100644
index ed00570..0000000
--- a/modules/camera/ScopedTrace.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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 CAMERA_SCOPED_TRACE_H
-#define CAMERA_SCOPED_TRACE_H
-
-#include <stdint.h>
-#include <cutils/trace.h>
-
-// See <cutils/trace.h> for more tracing macros.
-
-// CAMTRACE_NAME traces the beginning and end of the current scope.  To trace
-// the correct start and end times this macro should be declared first in the
-// scope body.
-#define CAMTRACE_NAME(name) ScopedTrace ___tracer(ATRACE_TAG, name)
-// CAMTRACE_CALL is an ATRACE_NAME that uses the current function name.
-#define CAMTRACE_CALL() CAMTRACE_NAME(__FUNCTION__)
-
-namespace default_camera_hal {
-
-class ScopedTrace {
-public:
-inline ScopedTrace(uint64_t tag, const char* name)
-    : mTag(tag) {
-    atrace_begin(mTag,name);
-}
-
-inline ~ScopedTrace() {
-    atrace_end(mTag);
-}
-
-private:
-    uint64_t mTag;
-};
-
-}; // namespace default_camera_hal
-
-#endif // CAMERA_SCOPED_TRACE_H
diff --git a/modules/camera/Stream.cpp b/modules/camera/Stream.cpp
index aae7adb..9b9ab98 100644
--- a/modules/camera/Stream.cpp
+++ b/modules/camera/Stream.cpp
@@ -14,18 +14,18 @@
  * limitations under the License.
  */
 
-#include <pthread.h>
+#include <stdio.h>
 #include <hardware/camera3.h>
 #include <hardware/gralloc.h>
 #include <system/graphics.h>
+#include <utils/Mutex.h>
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "Stream"
 #include <cutils/log.h>
 
 #define ATRACE_TAG (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
-#include <cutils/trace.h>
-#include "ScopedTrace.h"
+#include <utils/Trace.h>
 
 #include "Stream.h"
 
@@ -45,37 +45,32 @@
     mBuffers(0),
     mNumBuffers(0)
 {
-    // NULL (default) pthread mutex attributes
-    pthread_mutex_init(&mMutex, NULL);
 }
 
 Stream::~Stream()
 {
-    pthread_mutex_lock(&mMutex);
+    android::Mutex::Autolock al(mLock);
     unregisterBuffers_L();
-    pthread_mutex_unlock(&mMutex);
 }
 
 void Stream::setUsage(uint32_t usage)
 {
-    pthread_mutex_lock(&mMutex);
+    android::Mutex::Autolock al(mLock);
     if (usage != mUsage) {
         mUsage = usage;
         mStream->usage = usage;
         unregisterBuffers_L();
     }
-    pthread_mutex_unlock(&mMutex);
 }
 
 void Stream::setMaxBuffers(uint32_t max_buffers)
 {
-    pthread_mutex_lock(&mMutex);
+    android::Mutex::Autolock al(mLock);
     if (max_buffers != mMaxBuffers) {
         mMaxBuffers = max_buffers;
         mStream->max_buffers = max_buffers;
         unregisterBuffers_L();
     }
-    pthread_mutex_unlock(&mMutex);
 }
 
 int Stream::getType()
@@ -95,6 +90,61 @@
         mType == CAMERA3_STREAM_BIDIRECTIONAL;
 }
 
+const char* Stream::typeToString(int type)
+{
+    switch (type) {
+    case CAMERA3_STREAM_INPUT:
+        return "CAMERA3_STREAM_INPUT";
+    case CAMERA3_STREAM_OUTPUT:
+        return "CAMERA3_STREAM_OUTPUT";
+    case CAMERA3_STREAM_BIDIRECTIONAL:
+        return "CAMERA3_STREAM_BIDIRECTIONAL";
+    }
+    return "Invalid stream type!";
+}
+
+const char* Stream::formatToString(int format)
+{
+    // See <system/graphics.h> for full list
+    switch (format) {
+    case HAL_PIXEL_FORMAT_BGRA_8888:
+        return "BGRA 8888";
+    case HAL_PIXEL_FORMAT_RGBA_8888:
+        return "RGBA 8888";
+    case HAL_PIXEL_FORMAT_RGBX_8888:
+        return "RGBX 8888";
+    case HAL_PIXEL_FORMAT_RGB_888:
+        return "RGB 888";
+    case HAL_PIXEL_FORMAT_RGB_565:
+        return "RGB 565";
+    case HAL_PIXEL_FORMAT_sRGB_A_8888:
+        return "sRGB A 8888";
+    case HAL_PIXEL_FORMAT_sRGB_X_8888:
+        return "sRGB B 8888";
+    case HAL_PIXEL_FORMAT_Y8:
+        return "Y8";
+    case HAL_PIXEL_FORMAT_Y16:
+        return "Y16";
+    case HAL_PIXEL_FORMAT_YV12:
+        return "YV12";
+    case HAL_PIXEL_FORMAT_YCbCr_422_SP:
+        return "NV16";
+    case HAL_PIXEL_FORMAT_YCrCb_420_SP:
+        return "NV21";
+    case HAL_PIXEL_FORMAT_YCbCr_422_I:
+        return "YUY2";
+    case HAL_PIXEL_FORMAT_RAW_SENSOR:
+        return "RAW SENSOR";
+    case HAL_PIXEL_FORMAT_BLOB:
+        return "BLOB";
+    case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
+        return "IMPLEMENTATION DEFINED";
+    case HAL_PIXEL_FORMAT_YCbCr_420_888:
+        return "FLEXIBLE YCbCr 420 888";
+    }
+    return "Invalid stream format!";
+}
+
 bool Stream::isRegistered()
 {
     return mRegistered;
@@ -113,15 +163,15 @@
         return false;
     }
     if (s->stream_type != mType) {
-        // TODO: prettyprint type string
-        ALOGE("%s:%d: Mismatched type in reused stream. Got %d expect %d",
-                __func__, mId, s->stream_type, mType);
+        ALOGE("%s:%d: Mismatched type in reused stream. Got %s(%d) "
+                "expect %s(%d)", __func__, mId, typeToString(s->stream_type),
+                s->stream_type, typeToString(mType), mType);
         return false;
     }
     if (s->format != mFormat) {
-        // TODO: prettyprint format string
-        ALOGE("%s:%d: Mismatched format in reused stream. Got %d expect %d",
-                __func__, mId, s->format, mFormat);
+        ALOGE("%s:%d: Mismatched format in reused stream. Got %s(%d) "
+                "expect %s(%d)", __func__, mId, formatToString(s->format),
+                s->format, formatToString(mFormat), mFormat);
         return false;
     }
     if (s->width != mWidth) {
@@ -139,7 +189,8 @@
 
 int Stream::registerBuffers(const camera3_stream_buffer_set_t *buf_set)
 {
-    CAMTRACE_CALL();
+    ATRACE_CALL();
+    android::Mutex::Autolock al(mLock);
 
     if (buf_set->stream != mStream) {
         ALOGE("%s:%d: Buffer set for invalid stream. Got %p expect %p",
@@ -147,8 +198,6 @@
         return -EINVAL;
     }
 
-    pthread_mutex_lock(&mMutex);
-
     mNumBuffers = buf_set->num_buffers;
     mBuffers = new buffer_handle_t*[mNumBuffers];
 
@@ -160,12 +209,10 @@
     }
     mRegistered = true;
 
-    pthread_mutex_unlock(&mMutex);
-
     return 0;
 }
 
-// This must only be called with mMutex held
+// This must only be called with mLock held
 void Stream::unregisterBuffers_L()
 {
     mRegistered = false;
@@ -174,4 +221,22 @@
     // TODO: unregister buffers from hw
 }
 
+void Stream::dump(int fd)
+{
+    android::Mutex::Autolock al(mLock);
+
+    fdprintf(fd, "Stream ID: %d (%p)\n", mId, mStream);
+    fdprintf(fd, "Stream Type: %s (%d)\n", typeToString(mType), mType);
+    fdprintf(fd, "Width: %u Height: %u\n", mWidth, mHeight);
+    fdprintf(fd, "Stream Format: %s (%d)", formatToString(mFormat), mFormat);
+    // ToDo: prettyprint usage mask flags
+    fdprintf(fd, "Gralloc Usage Mask: 0x%x\n", mUsage);
+    fdprintf(fd, "Max Buffer Count: %d\n", mMaxBuffers);
+    fdprintf(fd, "Buffers Registered: %s\n", mRegistered ? "true" : "false");
+    fdprintf(fd, "Number of Buffers: %d\n", mNumBuffers);
+    for (int i = 0; i < mNumBuffers; i++) {
+        fdprintf(fd, "Buffer %d/%d: %p\n", i, mNumBuffers, mBuffers[i]);
+    }
+}
+
 } // namespace default_camera_hal
diff --git a/modules/camera/Stream.h b/modules/camera/Stream.h
index 34abd95..5efbc52 100644
--- a/modules/camera/Stream.h
+++ b/modules/camera/Stream.h
@@ -20,6 +20,7 @@
 #include <hardware/camera3.h>
 #include <hardware/gralloc.h>
 #include <system/graphics.h>
+#include <utils/Mutex.h>
 
 namespace default_camera_hal {
 // Stream represents a single input or output stream for a camera device.
@@ -41,12 +42,15 @@
         bool isInputType();
         bool isOutputType();
         bool isRegistered();
+        const char* typeToString(int type);
+        const char* formatToString(int format);
+        void dump(int fd);
 
         // This stream is being reused. Used in stream configuration passes
         bool mReuse;
 
     private:
-        // Clean up buffer state. must be called with mMutex held.
+        // Clean up buffer state. must be called with mLock held.
         void unregisterBuffers_L();
 
         // The camera device id this stream belongs to
@@ -72,7 +76,7 @@
         // Number of buffers in mBuffers
         unsigned int mNumBuffers;
         // Lock protecting the Stream object for modifications
-        pthread_mutex_t mMutex;
+        android::Mutex mLock;
 };
 } // namespace default_camera_hal
 
diff --git a/modules/camera/VendorTags.cpp b/modules/camera/VendorTags.cpp
new file mode 100644
index 0000000..58bd606
--- /dev/null
+++ b/modules/camera/VendorTags.cpp
@@ -0,0 +1,188 @@
+/*
+ * 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 <system/camera_metadata.h>
+#include "Metadata.h"
+
+//#define LOG_NDEBUG 0
+#define LOG_TAG "VendorTags"
+#include <cutils/log.h>
+
+#define ATRACE_TAG (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
+#include <utils/Trace.h>
+
+#include "VendorTags.h"
+
+namespace default_camera_hal {
+
+// Internal representations of vendor tags for convenience.
+// Other classes must access this data via public interfaces.
+// Structured to be easy to extend and contain complexity.
+namespace {
+// Describes a single vendor tag entry
+struct Entry {
+    const char* name;
+    uint8_t     type;
+};
+// Describes a vendor tag section
+struct Section {
+    const char* name;
+    uint32_t start;
+    uint32_t end;
+    const Entry* tags;
+};
+
+// Entry arrays for each section
+const Entry DemoWizardry[DEMO_WIZARDRY_END - DEMO_WIZARDRY_START] = {
+    [DEMO_WIZARDRY_DIMENSION_SIZE - DEMO_WIZARDRY_START] =
+        {"dimensionSize",   TYPE_INT32},
+    [DEMO_WIZARDRY_DIMENSIONS - DEMO_WIZARDRY_START] =
+        {"dimensions",      TYPE_INT32},
+    [DEMO_WIZARDRY_FAMILIAR - DEMO_WIZARDRY_START] =
+        {"familiar",        TYPE_BYTE},
+    [DEMO_WIZARDRY_FIRE - DEMO_WIZARDRY_START] =
+        {"fire",            TYPE_RATIONAL}
+};
+
+const Entry DemoSorcery[DEMO_SORCERY_END - DEMO_SORCERY_START] = {
+    [DEMO_SORCERY_DIFFICULTY - DEMO_SORCERY_START] =
+        {"difficulty",      TYPE_INT64},
+    [DEMO_SORCERY_LIGHT - DEMO_SORCERY_START] =
+        {"light",           TYPE_BYTE}
+};
+
+const Entry DemoMagic[DEMO_MAGIC_END - DEMO_MAGIC_START] = {
+    [DEMO_MAGIC_CARD_TRICK - DEMO_MAGIC_START] =
+        {"cardTrick",       TYPE_DOUBLE},
+    [DEMO_MAGIC_LEVITATION - DEMO_MAGIC_START] =
+        {"levitation",      TYPE_FLOAT}
+};
+
+// Array of all sections
+const Section DemoSections[DEMO_SECTION_COUNT] = {
+    [DEMO_WIZARDRY] = { "demo.wizardry",
+                        DEMO_WIZARDRY_START,
+                        DEMO_WIZARDRY_END,
+                        DemoWizardry },
+    [DEMO_SORCERY]  = { "demo.sorcery",
+                        DEMO_SORCERY_START,
+                        DEMO_SORCERY_END,
+                        DemoSorcery },
+    [DEMO_MAGIC]    = { "demo.magic",
+                        DEMO_MAGIC_START,
+                        DEMO_MAGIC_END,
+                        DemoMagic }
+};
+
+// Get a static handle to a specific vendor tag section
+const Section* getSection(uint32_t tag)
+{
+    uint32_t section = (tag - VENDOR_SECTION_START) >> 16;
+
+    if (tag < VENDOR_SECTION_START) {
+        ALOGE("%s: Tag 0x%x before vendor section", __func__, tag);
+        return NULL;
+    }
+
+    if (section >= DEMO_SECTION_COUNT) {
+        ALOGE("%s: Tag 0x%x after vendor section", __func__, tag);
+        return NULL;
+    }
+
+    return &DemoSections[section];
+}
+
+// Get a static handle to a specific vendor tag entry
+const Entry* getEntry(uint32_t tag)
+{
+    const Section* section = getSection(tag);
+    int index;
+
+    if (section == NULL)
+        return NULL;
+
+    if (tag >= section->end) {
+        ALOGE("%s: Tag 0x%x outside section", __func__, tag);
+        return NULL;
+    }
+
+    index = tag - section->start;
+    return &section->tags[index];
+}
+} // namespace
+
+VendorTags::VendorTags()
+  : mTagCount(0)
+{
+    for (int i = 0; i < DEMO_SECTION_COUNT; i++) {
+        mTagCount += DemoSections[i].end - DemoSections[i].start;
+    }
+}
+
+VendorTags::~VendorTags()
+{
+}
+
+int VendorTags::getTagCount(const vendor_tag_ops_t* ops)
+{
+    return mTagCount;
+}
+
+void VendorTags::getAllTags(const vendor_tag_ops_t* ops, uint32_t* tag_array)
+{
+    if (tag_array == NULL) {
+        ALOGE("%s: NULL tag_array", __func__);
+        return;
+    }
+
+    for (int i = 0; i < DEMO_SECTION_COUNT; i++) {
+        for (uint32_t tag = DemoSections[i].start;
+                tag < DemoSections[i].end; tag++) {
+            *tag_array++ = tag;
+        }
+    }
+}
+
+const char* VendorTags::getSectionName(const vendor_tag_ops_t* ops, uint32_t tag)
+{
+    const Section* section = getSection(tag);
+
+    if (section == NULL)
+        return NULL;
+
+    return section->name;
+}
+
+const char* VendorTags::getTagName(const vendor_tag_ops_t* ops, uint32_t tag)
+{
+    const Entry* entry = getEntry(tag);
+
+    if (entry == NULL)
+        return NULL;
+
+    return entry->name;
+}
+
+int VendorTags::getTagType(const vendor_tag_ops_t* ops, uint32_t tag)
+{
+    const Entry* entry = getEntry(tag);
+
+    if (entry == NULL)
+        return -1;
+
+    return entry->type;
+}
+} // namespace default_camera_hal
diff --git a/modules/camera/VendorTags.h b/modules/camera/VendorTags.h
new file mode 100644
index 0000000..9af9f7d
--- /dev/null
+++ b/modules/camera/VendorTags.h
@@ -0,0 +1,77 @@
+/*
+ * 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 VENDOR_TAGS_H_
+#define VENDOR_TAGS_H_
+
+#include <hardware/camera_common.h>
+#include <system/camera_metadata.h>
+
+namespace default_camera_hal {
+
+// VendorTags contains all vendor-specific metadata tag functionality
+class VendorTags {
+    public:
+        VendorTags();
+        ~VendorTags();
+
+        // Vendor Tags Operations (see <hardware/camera_common.h>)
+        int getTagCount(const vendor_tag_ops_t* ops);
+        void getAllTags(const vendor_tag_ops_t* ops, uint32_t* tag_array);
+        const char* getSectionName(const vendor_tag_ops_t* ops, uint32_t tag);
+        const char* getTagName(const vendor_tag_ops_t* ops, uint32_t tag);
+        int getTagType(const vendor_tag_ops_t* ops, uint32_t tag);
+
+    private:
+        // Total number of vendor tags
+        int mTagCount;
+};
+
+// Tag sections start at the beginning of vendor tags (0x8000_0000)
+// See <system/camera_metadata.h>
+enum {
+    DEMO_WIZARDRY,
+    DEMO_SORCERY,
+    DEMO_MAGIC,
+    DEMO_SECTION_COUNT
+};
+
+// Each section starts at increments of 0x1_0000
+enum {
+    DEMO_WIZARDRY_START = (DEMO_WIZARDRY + VENDOR_SECTION) << 16,
+    DEMO_SORCERY_START  = (DEMO_SORCERY  + VENDOR_SECTION) << 16,
+    DEMO_MAGIC_START    = (DEMO_MAGIC    + VENDOR_SECTION) << 16,
+};
+
+// Vendor Tag values, start value begins each section
+enum {
+    DEMO_WIZARDRY_DIMENSION_SIZE = DEMO_WIZARDRY_START,
+    DEMO_WIZARDRY_DIMENSIONS,
+    DEMO_WIZARDRY_FAMILIAR,
+    DEMO_WIZARDRY_FIRE,
+    DEMO_WIZARDRY_END,
+
+    DEMO_SORCERY_DIFFICULTY = DEMO_SORCERY_START,
+    DEMO_SORCERY_LIGHT,
+    DEMO_SORCERY_END,
+
+    DEMO_MAGIC_CARD_TRICK = DEMO_MAGIC_START,
+    DEMO_MAGIC_LEVITATION,
+    DEMO_MAGIC_END,
+};
+} // namespace default_camera_hal
+
+#endif // VENDOR_TAGS_H_
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/hardware/Android.mk b/tests/hardware/Android.mk
new file mode 100644
index 0000000..02540c9
--- /dev/null
+++ b/tests/hardware/Android.mk
@@ -0,0 +1,12 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := static-hal-check
+LOCAL_SRC_FILES := struct-size.cpp struct-offset.cpp struct-last.cpp
+LOCAL_SHARED_LIBRARIES := libhardware
+LOCAL_CFLAGS := -std=gnu++11 -O0
+
+LOCAL_C_INCLUDES += \
+    system/media/camera/include
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/tests/hardware/struct-last.cpp b/tests/hardware/struct-last.cpp
new file mode 100644
index 0000000..44a7b2d
--- /dev/null
+++ b/tests/hardware/struct-last.cpp
@@ -0,0 +1,69 @@
+/*
+ * 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 <cstddef>
+#include <system/window.h>
+#include <hardware/hardware.h>
+#include <hardware/sensors.h>
+#include <hardware/fb.h>
+#include <hardware/hwcomposer.h>
+#include <hardware/gralloc.h>
+#include <hardware/consumerir.h>
+#include <hardware/camera_common.h>
+#include <hardware/camera3.h>
+
+#define GET_PADDING(align, size) (((align) - ((size) % (align))) % (align))
+
+#define CHECK_LAST_MEMBER(type, member) \
+do { \
+static constexpr size_t calc_size = offsetof(type, member) + sizeof(((type *)0)->member); \
+static_assert(sizeof(type) == calc_size + GET_PADDING(alignof(type), calc_size), \
+"" #member " is not the last element of " #type); \
+} while (0)
+
+void CheckSizes(void) {
+    //Types defined in hardware.h
+    CHECK_LAST_MEMBER(hw_module_t, reserved);
+    CHECK_LAST_MEMBER(hw_device_t, close);
+
+    //Types defined in sensors.h
+    CHECK_LAST_MEMBER(sensors_vec_t, reserved);
+    CHECK_LAST_MEMBER(sensors_event_t, reserved1);
+    CHECK_LAST_MEMBER(struct sensor_t, reserved);
+    CHECK_LAST_MEMBER(sensors_poll_device_1_t, reserved_procs);
+
+    //Types defined in fb.h
+    CHECK_LAST_MEMBER(framebuffer_device_t, reserved_proc);
+
+    //Types defined in hwcomposer.h
+    CHECK_LAST_MEMBER(hwc_layer_1_t, reserved);
+    CHECK_LAST_MEMBER(hwc_composer_device_1_t, reserved_proc);
+
+    //Types defined in gralloc.h
+    CHECK_LAST_MEMBER(gralloc_module_t, reserved_proc);
+    CHECK_LAST_MEMBER(alloc_device_t, reserved_proc);
+
+    //Types defined in consumerir.h
+    CHECK_LAST_MEMBER(consumerir_device_t, reserved);
+
+    //Types defined in camera_common.h
+    CHECK_LAST_MEMBER(vendor_tag_ops_t, reserved);
+    CHECK_LAST_MEMBER(camera_module_t, reserved);
+
+    //Types defined in camera3.h
+    CHECK_LAST_MEMBER(camera3_device_ops_t, reserved);
+}
+
diff --git a/tests/hardware/struct-offset.cpp b/tests/hardware/struct-offset.cpp
new file mode 100644
index 0000000..0a1338a
--- /dev/null
+++ b/tests/hardware/struct-offset.cpp
@@ -0,0 +1,216 @@
+/*
+ * 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 <cstddef>
+#include <system/window.h>
+#include <hardware/hardware.h>
+#include <hardware/sensors.h>
+#include <hardware/fb.h>
+#include <hardware/hwcomposer.h>
+#include <hardware/gralloc.h>
+#include <hardware/consumerir.h>
+#include <hardware/camera_common.h>
+#include <hardware/camera3.h>
+
+//Ideally this would print type.member instead we need to rely on the line number from the output
+template <size_t actual, size_t expected> void check_member(void) {
+    static_assert(actual == expected, "");
+}
+
+#ifdef __LP64__
+#define CHECK_MEMBER_AT(type, member, off32, off64) \
+    check_member<offsetof(type, member), off64>()
+#else
+#define CHECK_MEMBER_AT(type, member, off32, off64) \
+    check_member<offsetof(type, member), off32>()
+#endif
+
+void CheckOffsets(void) {
+    //Types defined in hardware.h
+    CHECK_MEMBER_AT(hw_module_t, tag, 0, 0);
+    CHECK_MEMBER_AT(hw_module_t, module_api_version, 4, 4);
+    CHECK_MEMBER_AT(hw_module_t, hal_api_version, 6, 6);
+    CHECK_MEMBER_AT(hw_module_t, id, 8, 8);
+    CHECK_MEMBER_AT(hw_module_t, name, 12, 16);
+    CHECK_MEMBER_AT(hw_module_t, author, 16, 24);
+    CHECK_MEMBER_AT(hw_module_t, methods, 20, 32);
+    CHECK_MEMBER_AT(hw_module_t, dso, 24, 40);
+    CHECK_MEMBER_AT(hw_module_t, reserved, 28, 48);
+
+    CHECK_MEMBER_AT(hw_device_t, tag, 0, 0);
+    CHECK_MEMBER_AT(hw_device_t, version, 4, 4);
+    CHECK_MEMBER_AT(hw_device_t, module, 8, 8);
+    CHECK_MEMBER_AT(hw_device_t, reserved, 12, 16);
+    CHECK_MEMBER_AT(hw_device_t, close, 60, 112);
+
+    //Types defined in sensors.h
+    CHECK_MEMBER_AT(sensors_vec_t, v, 0, 0);
+    CHECK_MEMBER_AT(sensors_vec_t, x, 0, 0);
+    CHECK_MEMBER_AT(sensors_vec_t, y, 4, 4);
+    CHECK_MEMBER_AT(sensors_vec_t, z, 8, 8);
+    CHECK_MEMBER_AT(sensors_vec_t, azimuth, 0, 0);
+    CHECK_MEMBER_AT(sensors_vec_t, pitch, 4, 4);
+    CHECK_MEMBER_AT(sensors_vec_t, roll, 8, 8);
+    CHECK_MEMBER_AT(sensors_vec_t, status, 12, 12);
+    CHECK_MEMBER_AT(sensors_vec_t, reserved, 13, 13);
+
+    CHECK_MEMBER_AT(sensors_event_t, version, 0, 0);
+    CHECK_MEMBER_AT(sensors_event_t, sensor, 4, 4);
+    CHECK_MEMBER_AT(sensors_event_t, type, 8, 8);
+    CHECK_MEMBER_AT(sensors_event_t, reserved0, 12, 12);
+    CHECK_MEMBER_AT(sensors_event_t, timestamp, 16, 16);
+    CHECK_MEMBER_AT(sensors_event_t, data, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, acceleration, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, magnetic, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, orientation, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, gyro, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, temperature, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, distance, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, light, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, pressure, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, relative_humidity, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, uncalibrated_gyro, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, uncalibrated_magnetic, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, meta_data, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, u64, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, u64.data, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, u64.step_counter, 24, 24);
+    CHECK_MEMBER_AT(sensors_event_t, reserved1, 88, 88);
+
+    CHECK_MEMBER_AT(struct sensor_t, name, 0, 0);
+    CHECK_MEMBER_AT(struct sensor_t, vendor, 4, 8);
+    CHECK_MEMBER_AT(struct sensor_t, version, 8, 16);
+    CHECK_MEMBER_AT(struct sensor_t, handle, 12, 20);
+    CHECK_MEMBER_AT(struct sensor_t, type, 16, 24);
+    CHECK_MEMBER_AT(struct sensor_t, maxRange, 20, 28);
+    CHECK_MEMBER_AT(struct sensor_t, resolution, 24, 32);
+    CHECK_MEMBER_AT(struct sensor_t, power, 28, 36);
+    CHECK_MEMBER_AT(struct sensor_t, minDelay, 32, 40);
+    CHECK_MEMBER_AT(struct sensor_t, fifoReservedEventCount, 36, 44);
+    CHECK_MEMBER_AT(struct sensor_t, fifoMaxEventCount, 40, 48);
+    CHECK_MEMBER_AT(struct sensor_t, reserved, 44, 56);
+
+    CHECK_MEMBER_AT(sensors_poll_device_1_t, v0, 0, 0);
+    CHECK_MEMBER_AT(sensors_poll_device_1_t, common, 0, 0);
+    CHECK_MEMBER_AT(sensors_poll_device_1_t, activate, 64, 120);
+    CHECK_MEMBER_AT(sensors_poll_device_1_t, setDelay, 68, 128);
+    CHECK_MEMBER_AT(sensors_poll_device_1_t, poll, 72, 136);
+    CHECK_MEMBER_AT(sensors_poll_device_1_t, batch, 76, 144);
+    CHECK_MEMBER_AT(sensors_poll_device_1_t, flush, 80, 152);
+    CHECK_MEMBER_AT(sensors_poll_device_1_t, reserved_procs, 84, 160);
+
+    //Types defined in fb.h
+    CHECK_MEMBER_AT(framebuffer_device_t, common, 0, 0);
+    CHECK_MEMBER_AT(framebuffer_device_t, flags, 64, 120);
+    CHECK_MEMBER_AT(framebuffer_device_t, width, 68, 124);
+    CHECK_MEMBER_AT(framebuffer_device_t, height, 72, 128);
+    CHECK_MEMBER_AT(framebuffer_device_t, stride, 76, 132);
+    CHECK_MEMBER_AT(framebuffer_device_t, format, 80, 136);
+    CHECK_MEMBER_AT(framebuffer_device_t, xdpi, 84, 140);
+    CHECK_MEMBER_AT(framebuffer_device_t, ydpi, 88, 144);
+    CHECK_MEMBER_AT(framebuffer_device_t, fps, 92, 148);
+    CHECK_MEMBER_AT(framebuffer_device_t, minSwapInterval, 96, 152);
+    CHECK_MEMBER_AT(framebuffer_device_t, maxSwapInterval, 100, 156);
+    CHECK_MEMBER_AT(framebuffer_device_t, numFramebuffers, 104, 160);
+    CHECK_MEMBER_AT(framebuffer_device_t, reserved, 108, 164);
+    CHECK_MEMBER_AT(framebuffer_device_t, setSwapInterval, 136, 192);
+    CHECK_MEMBER_AT(framebuffer_device_t, setUpdateRect, 140, 200);
+    CHECK_MEMBER_AT(framebuffer_device_t, post, 144, 208);
+    CHECK_MEMBER_AT(framebuffer_device_t, compositionComplete, 148, 216);
+    CHECK_MEMBER_AT(framebuffer_device_t, dump, 152, 224);
+    CHECK_MEMBER_AT(framebuffer_device_t, enableScreen, 156, 232);
+    CHECK_MEMBER_AT(framebuffer_device_t, reserved_proc, 160, 240);
+
+    //Types defined in hwcomposer.h
+    CHECK_MEMBER_AT(hwc_layer_1_t, compositionType, 0, 0);
+    CHECK_MEMBER_AT(hwc_layer_1_t, hints, 4, 4);
+    CHECK_MEMBER_AT(hwc_layer_1_t, flags, 8, 8);
+    CHECK_MEMBER_AT(hwc_layer_1_t, backgroundColor, 12, 16);
+    CHECK_MEMBER_AT(hwc_layer_1_t, handle, 12, 16);
+    CHECK_MEMBER_AT(hwc_layer_1_t, transform, 16, 24);
+    CHECK_MEMBER_AT(hwc_layer_1_t, blending, 20, 28);
+    CHECK_MEMBER_AT(hwc_layer_1_t, sourceCropi, 24, 32);
+    CHECK_MEMBER_AT(hwc_layer_1_t, sourceCrop, 24, 32);
+    CHECK_MEMBER_AT(hwc_layer_1_t, sourceCropf, 24, 32);
+    CHECK_MEMBER_AT(hwc_layer_1_t, displayFrame, 40, 48);
+    CHECK_MEMBER_AT(hwc_layer_1_t, visibleRegionScreen, 56, 64);
+    CHECK_MEMBER_AT(hwc_layer_1_t, acquireFenceFd, 64, 80);
+    CHECK_MEMBER_AT(hwc_layer_1_t, releaseFenceFd, 68, 84);
+    CHECK_MEMBER_AT(hwc_layer_1_t, planeAlpha, 72, 88);
+    CHECK_MEMBER_AT(hwc_layer_1_t, _pad, 73, 89);
+
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, common, 0, 0);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, prepare, 64, 120);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, set, 68, 128);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, eventControl, 72, 136);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, blank, 76, 144);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, query, 80, 152);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, registerProcs, 84, 160);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, dump, 88, 168);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, getDisplayConfigs, 92, 176);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, getDisplayAttributes, 96, 184);
+    CHECK_MEMBER_AT(hwc_composer_device_1_t, reserved_proc, 100, 192);
+
+    //Types defined in gralloc.h
+    CHECK_MEMBER_AT(gralloc_module_t, common, 0, 0);
+    CHECK_MEMBER_AT(gralloc_module_t, registerBuffer, 128, 248);
+    CHECK_MEMBER_AT(gralloc_module_t, unregisterBuffer, 132, 256);
+    CHECK_MEMBER_AT(gralloc_module_t, lock, 136, 264);
+    CHECK_MEMBER_AT(gralloc_module_t, unlock, 140, 272);
+    CHECK_MEMBER_AT(gralloc_module_t, perform, 144, 280);
+    CHECK_MEMBER_AT(gralloc_module_t, lock_ycbcr, 148, 288);
+    CHECK_MEMBER_AT(gralloc_module_t, reserved_proc, 152, 296);
+
+    CHECK_MEMBER_AT(alloc_device_t, common, 0, 0);
+    CHECK_MEMBER_AT(alloc_device_t, alloc, 64, 120);
+    CHECK_MEMBER_AT(alloc_device_t, free, 68, 128);
+    CHECK_MEMBER_AT(alloc_device_t, dump, 72, 136);
+    CHECK_MEMBER_AT(alloc_device_t, reserved_proc, 76, 144);
+
+    //Types defined in consumerir.h
+    CHECK_MEMBER_AT(consumerir_device_t, common, 0, 0);
+    CHECK_MEMBER_AT(consumerir_device_t, transmit, 64, 120);
+    CHECK_MEMBER_AT(consumerir_device_t, get_num_carrier_freqs, 68, 128);
+    CHECK_MEMBER_AT(consumerir_device_t, get_carrier_freqs, 72, 136);
+    CHECK_MEMBER_AT(consumerir_device_t, reserved, 76, 144);
+
+    //Types defined in camera_common.h
+    CHECK_MEMBER_AT(vendor_tag_ops_t, get_tag_count, 0, 0);
+    CHECK_MEMBER_AT(vendor_tag_ops_t, get_all_tags, 4, 8);
+    CHECK_MEMBER_AT(vendor_tag_ops_t, get_section_name, 8, 16);
+    CHECK_MEMBER_AT(vendor_tag_ops_t, get_tag_name, 12, 24);
+    CHECK_MEMBER_AT(vendor_tag_ops_t, get_tag_type, 16, 32);
+    CHECK_MEMBER_AT(vendor_tag_ops_t, reserved, 20, 40);
+
+    CHECK_MEMBER_AT(camera_module_t, common, 0, 0);
+    CHECK_MEMBER_AT(camera_module_t, get_number_of_cameras, 128, 248);
+    CHECK_MEMBER_AT(camera_module_t, get_camera_info, 132, 256);
+    CHECK_MEMBER_AT(camera_module_t, set_callbacks, 136, 264);
+    CHECK_MEMBER_AT(camera_module_t, get_vendor_tag_ops, 140, 272);
+    CHECK_MEMBER_AT(camera_module_t, reserved, 144, 280);
+
+    //Types defined in camera3.h
+    CHECK_MEMBER_AT(camera3_device_ops_t, initialize, 0, 0);
+    CHECK_MEMBER_AT(camera3_device_ops_t, configure_streams, 4, 8);
+    CHECK_MEMBER_AT(camera3_device_ops_t, register_stream_buffers, 8, 16);
+    CHECK_MEMBER_AT(camera3_device_ops_t, construct_default_request_settings, 12, 24);
+    CHECK_MEMBER_AT(camera3_device_ops_t, process_capture_request, 16, 32);
+    CHECK_MEMBER_AT(camera3_device_ops_t, get_metadata_vendor_tag_ops, 20, 40);
+    CHECK_MEMBER_AT(camera3_device_ops_t, dump, 24, 48);
+    CHECK_MEMBER_AT(camera3_device_ops_t, flush, 28, 56);
+    CHECK_MEMBER_AT(camera3_device_ops_t, reserved, 32, 64);
+}
+
diff --git a/tests/hardware/struct-size.cpp b/tests/hardware/struct-size.cpp
new file mode 100644
index 0000000..4207ea8
--- /dev/null
+++ b/tests/hardware/struct-size.cpp
@@ -0,0 +1,76 @@
+/*
+ * 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 <system/window.h>
+#include <hardware/hardware.h>
+#include <hardware/sensors.h>
+#include <hardware/fb.h>
+#include <hardware/hwcomposer.h>
+#include <hardware/gralloc.h>
+#include <hardware/consumerir.h>
+#include <hardware/camera_common.h>
+#include <hardware/camera3.h>
+
+template<size_t> static constexpr size_t CheckSizeHelper(size_t, size_t);
+
+template<> constexpr size_t CheckSizeHelper<4>(size_t size32, size_t size64) {
+    return size32;
+}
+
+template<> constexpr size_t CheckSizeHelper<8>(size_t size32, size_t size64) {
+    return size64;
+}
+
+template<typename T, size_t size32, size_t size64> static void CheckTypeSize() {
+    const size_t mySize = CheckSizeHelper<sizeof(void *)>(size32, size64);
+
+    static_assert(sizeof(T) == mySize, "struct is the wrong size");
+}
+
+void CheckSizes(void) {
+    //Types defined in hardware.h
+    CheckTypeSize<hw_module_t, 128, 248>();
+    CheckTypeSize<hw_device_t, 64, 120>();
+
+    //Types defined in sensors.h
+    CheckTypeSize<sensors_vec_t, 16, 16>();
+    CheckTypeSize<sensors_event_t, 104, 104>();
+    CheckTypeSize<struct sensor_t, 68, 104>();
+    CheckTypeSize<sensors_poll_device_1_t, 116, 224>();
+
+    //Types defined in fb.h
+    CheckTypeSize<framebuffer_device_t, 184, 288>();
+
+    //Types defined in hwcomposer.h
+    CheckTypeSize<hwc_layer_1_t, 96, 120>();
+    CheckTypeSize<hwc_composer_device_1_t, 116, 224>();
+
+    //Types defined in gralloc.h
+    CheckTypeSize<gralloc_module_t, 176, 344>();
+    CheckTypeSize<alloc_device_t, 104, 200>();
+
+    //Types defined in consumerir.h
+    CheckTypeSize<consumerir_device_t, 96, 184>();
+
+    //Types defined in camera_common.h
+    CheckTypeSize<vendor_tag_ops_t, 52, 104>();
+    CheckTypeSize<camera_module_t, 176, 344>();
+
+    //Types defined in camera3.h
+    CheckTypeSize<camera3_device_ops_t, 64, 128>();
+}
+