Add guest mode functionality (1/3) am: 4e10135ef4 am: 6e98ba09a2
am: 4137555a77

* commit '4137555a77c5fd68eedbf63a0a351599edcbbcac':
  Add guest mode functionality (1/3)

Change-Id: I5cc9b7d8082908d2c64012b63e5183365366ed1e
diff --git a/hardware.c b/hardware.c
index 6713ea0..79d0a2f 100644
--- a/hardware.c
+++ b/hardware.c
@@ -67,9 +67,9 @@
         const char *path,
         const struct hw_module_t **pHmi)
 {
-    int status;
-    void *handle;
-    struct hw_module_t *hmi;
+    int status = -EINVAL;
+    void *handle = NULL;
+    struct hw_module_t *hmi = NULL;
 
     /*
      * load the symbols resolving undefined symbols before
@@ -145,11 +145,12 @@
 int hw_get_module_by_class(const char *class_id, const char *inst,
                            const struct hw_module_t **module)
 {
-    int i;
-    char prop[PATH_MAX];
-    char path[PATH_MAX];
-    char name[PATH_MAX];
-    char prop_name[PATH_MAX];
+    int i = 0;
+    char prop[PATH_MAX] = {0};
+    char path[PATH_MAX] = {0};
+    char name[PATH_MAX] = {0};
+    char prop_name[PATH_MAX] = {0};
+
 
     if (inst)
         snprintf(name, PATH_MAX, "%s.%s", class_id, inst);
diff --git a/include/hardware/bluetooth.h b/include/hardware/bluetooth.h
index 3c9a352..524de14 100644
--- a/include/hardware/bluetooth.h
+++ b/include/hardware/bluetooth.h
@@ -46,7 +46,7 @@
 #define BT_PROFILE_HIDHOST_ID "hidhost"
 #define BT_PROFILE_PAN_ID "pan"
 #define BT_PROFILE_MAP_CLIENT_ID "map_client"
-
+#define BT_PROFILE_SDP_CLIENT_ID "sdp"
 #define BT_PROFILE_GATT_ID "gatt"
 #define BT_PROFILE_AV_RC_ID "avrcp"
 #define BT_PROFILE_AV_RC_CTRL_ID "avrcp_ctrl"
@@ -143,14 +143,15 @@
 
 typedef struct
 {
+    uint16_t version_supported;
     uint8_t local_privacy_enabled;
     uint8_t max_adv_instance;
     uint8_t rpa_offload_supported;
     uint8_t max_irk_list_size;
     uint8_t max_adv_filter_supported;
-    uint8_t scan_result_storage_size_lobyte;
-    uint8_t scan_result_storage_size_hibyte;
     uint8_t activity_energy_info_supported;
+    uint16_t scan_result_storage_size;
+    uint16_t total_trackable_advertisers;
 }bt_local_le_features_t;
 
 /* Bluetooth Adapter and Remote Device property types */
@@ -545,6 +546,8 @@
 } bluetooth_device_t;
 
 typedef bluetooth_device_t bluetooth_module_t;
+
+
 __END_DECLS
 
 #endif /* ANDROID_INCLUDE_BLUETOOTH_H */
diff --git a/include/hardware/bt_common_types.h b/include/hardware/bt_common_types.h
new file mode 100644
index 0000000..e30ac24
--- /dev/null
+++ b/include/hardware/bt_common_types.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2015 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.
+ */
+
+/******************************************************************************
+ *
+ *  This file contains constants and definitions that can be used commonly between JNI and stack layer
+ *
+ ******************************************************************************/
+#ifndef ANDROID_INCLUDE_BT_COMMON_TYPES_H
+#define ANDROID_INCLUDE_BT_COMMON_TYPES_H
+
+#include "bluetooth.h"
+
+typedef struct
+{
+    uint8_t  client_if;
+    uint8_t  filt_index;
+    uint8_t  advertiser_state;
+    uint8_t  advertiser_info_present;
+    uint8_t  addr_type;
+    uint8_t  tx_power;
+    int8_t  rssi_value;
+    uint16_t time_stamp;
+    bt_bdaddr_t bd_addr;
+    uint8_t  adv_pkt_len;
+    uint8_t  *p_adv_pkt_data;
+    uint8_t  scan_rsp_len;
+    uint8_t  *p_scan_rsp_data;
+} btgatt_track_adv_info_t;
+
+#endif  /* ANDROID_INCLUDE_BT_COMMON_TYPES_H */
diff --git a/include/hardware/bt_gatt_client.h b/include/hardware/bt_gatt_client.h
index 8073dd1..7881dc8 100644
--- a/include/hardware/bt_gatt_client.h
+++ b/include/hardware/bt_gatt_client.h
@@ -20,6 +20,7 @@
 
 #include <stdint.h>
 #include "bt_gatt_types.h"
+#include "bt_common_types.h"
 
 __BEGIN_DECLS
 
@@ -69,6 +70,23 @@
 
 typedef struct
 {
+    uint8_t  client_if;
+    uint8_t  action;
+    uint8_t  filt_index;
+    uint16_t feat_seln;
+    uint16_t list_logic_type;
+    uint8_t  filt_logic_type;
+    uint8_t  rssi_high_thres;
+    uint8_t  rssi_low_thres;
+    uint8_t  dely_mode;
+    uint16_t found_timeout;
+    uint16_t lost_timeout;
+    uint8_t  found_timeout_cnt;
+    uint16_t  num_of_tracking_entries;
+} btgatt_filt_param_setup_t;
+
+typedef struct
+{
     bt_bdaddr_t        *bda1;
     bt_uuid_t          *uuid1;
     uint16_t            u1;
@@ -202,8 +220,7 @@
 typedef void (*batchscan_threshold_callback)(int client_if);
 
 /** Track ADV VSE callback invoked when tracked device is found or lost */
-typedef void (*track_adv_event_callback)(int client_if, int filt_index, int addr_type,
-                                             bt_bdaddr_t* bda, int adv_state);
+typedef void (*track_adv_event_callback)(btgatt_track_adv_info_t *p_track_adv_info);
 
 typedef struct {
     register_client_callback            register_client_cb;
@@ -336,10 +353,7 @@
     bt_status_t (*read_remote_rssi)( int client_if, const bt_bdaddr_t *bd_addr);
 
     /** Setup scan filter params */
-    bt_status_t (*scan_filter_param_setup)(int client_if, int action, int filt_index, int feat_seln,
-                                      int list_logic_type, int filt_logic_type, int rssi_high_thres,
-                                      int rssi_low_thres, int dely_mode, int found_timeout,
-                                      int lost_timeout, int found_timeout_cnt);
+    bt_status_t (*scan_filter_param_setup)(btgatt_filt_param_setup_t filt_param);
 
 
     /** Configure a scan filter condition  */
diff --git a/include/hardware/bt_sdp.h b/include/hardware/bt_sdp.h
new file mode 100644
index 0000000..d298ad6
--- /dev/null
+++ b/include/hardware/bt_sdp.h
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "bluetooth.h"
+
+#define SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH 15
+
+__BEGIN_DECLS
+
+/**
+ * These events are handled by the state machine
+ */
+typedef enum {
+    SDP_TYPE_RAW, // Used to carry raw SDP search data for unknown UUID's 
+    SDP_TYPE_MAP_MAS,
+    SDP_TYPE_MAP_MNS,
+    SDP_TYPE_PBAP_PSE,
+    SDP_TYPE_PBAP_PCE,
+    SDP_TYPE_OPP_SERVER
+} bluetooth_sdp_types;
+
+typedef struct _bluetooth_sdp_hdr {
+    bluetooth_sdp_types type;
+    bt_uuid_t   uuid;
+    uint32_t    service_name_length;
+    char       *service_name;
+    int32_t     rfcomm_channel_number;
+    int32_t     l2cap_psm;
+    int32_t     profile_version;
+} bluetooth_sdp_hdr;
+
+/**
+ * Some signals need additional pointers, hence we introduce a
+ * generic way to handle these pointers.
+ */
+typedef struct _bluetooth_sdp_hdr_overlay {
+    bluetooth_sdp_types type;
+    bt_uuid_t   uuid;
+    uint32_t    service_name_length;
+    char       *service_name;
+    int32_t     rfcomm_channel_number;
+    int32_t     l2cap_psm;
+    int32_t     profile_version;
+
+    // User pointers, only used for some signals - see bluetooth_sdp_ops_record
+    int         user1_ptr_len;
+    uint8_t    *user1_ptr;
+    int         user2_ptr_len;
+    uint8_t    *user2_ptr;
+} bluetooth_sdp_hdr_overlay;
+
+typedef struct _bluetooth_sdp_mas_record {
+    bluetooth_sdp_hdr_overlay hdr;
+    uint32_t    mas_instance_id;
+    uint32_t    supported_features;
+    uint32_t    supported_message_types;
+} bluetooth_sdp_mas_record;
+
+typedef struct _bluetooth_sdp_mns_record {
+    bluetooth_sdp_hdr_overlay hdr;
+    uint32_t    supported_features;
+} bluetooth_sdp_mns_record;
+
+typedef struct _bluetooth_sdp_pse_record {
+    bluetooth_sdp_hdr_overlay hdr;
+    uint32_t    supported_features;
+    uint32_t    supported_repositories;
+} bluetooth_sdp_pse_record;
+
+typedef struct _bluetooth_sdp_pce_record {
+    bluetooth_sdp_hdr_overlay hdr;
+} bluetooth_sdp_pce_record;
+
+typedef struct _bluetooth_sdp_ops_record {
+    bluetooth_sdp_hdr_overlay hdr;
+    int         supported_formats_list_len;
+    uint8_t     supported_formats_list[SDP_OPP_SUPPORTED_FORMATS_MAX_LENGTH];
+} bluetooth_sdp_ops_record;
+
+typedef union {
+    bluetooth_sdp_hdr_overlay   hdr;
+    bluetooth_sdp_mas_record    mas;
+    bluetooth_sdp_mns_record    mns;
+    bluetooth_sdp_pse_record    pse;
+    bluetooth_sdp_pce_record    pce;
+    bluetooth_sdp_ops_record    ops;
+} bluetooth_sdp_record;
+
+
+/** Callback for SDP search */
+typedef void (*btsdp_search_callback)(bt_status_t status, bt_bdaddr_t *bd_addr, uint8_t* uuid, int num_records, bluetooth_sdp_record *records);
+
+typedef struct {
+    /** Set to sizeof(btsdp_callbacks_t) */
+    size_t      size;
+    btsdp_search_callback  sdp_search_cb;
+} btsdp_callbacks_t;
+
+typedef struct {
+    /** Set to size of this struct */
+    size_t size;
+
+    /** Register BT SDP search callbacks */
+    bt_status_t (*init)(btsdp_callbacks_t *callbacks);
+
+    /** Unregister BT SDP */
+    bt_status_t (*deinit)();
+
+    /** Search for SDP records with specific uuid on remote device */
+    bt_status_t (*sdp_search)(bt_bdaddr_t *bd_addr,  const uint8_t* uuid);
+
+    /**
+     * Use listen in the socket interface to create rfcomm and/or l2cap PSM channels,
+     * (without UUID and service_name and set the BTSOCK_FLAG_NO_SDP flag in flags).
+     * Then use createSdpRecord to create the SDP record associated with the rfcomm/l2cap channels.
+     *
+     * Returns a handle to the SDP record, which can be parsed to remove_sdp_record.
+     *
+     * record           (in) The SDP record to create
+     * record_handle    (out)The corresponding record handle will be written to this pointer.
+     */
+    bt_status_t (*create_sdp_record)(bluetooth_sdp_record *record, int* record_handle);
+
+    /** Remove a SDP record created by createSdpRecord */
+    bt_status_t (*remove_sdp_record)(int sdp_handle);
+} btsdp_interface_t;
+
+__END_DECLS
+
diff --git a/include/hardware/bt_sock.h b/include/hardware/bt_sock.h
index a4aa046..1c937d8 100644
--- a/include/hardware/bt_sock.h
+++ b/include/hardware/bt_sock.h
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-#ifndef ANDROID_INCLUDE_BT_SOCK_H
-#define ANDROID_INCLUDE_BT_SOCK_H
+#pragma once
 
 __BEGIN_DECLS
 
 #define BTSOCK_FLAG_ENCRYPT 1
 #define BTSOCK_FLAG_AUTH (1 << 1)
+#define BTSOCK_FLAG_NO_SDP (1 << 2)
 
 typedef enum {
     BTSOCK_RFCOMM = 1,
@@ -34,25 +34,37 @@
     bt_bdaddr_t bd_addr;
     int channel;
     int status;
+    
+    // The writer must make writes using a buffer of this maximum size
+    // to avoid loosing data. (L2CAP only)
+    unsigned short max_tx_packet_size;
+ 
+    // The reader must read using a buffer of at least this size to avoid
+    // loosing data. (L2CAP only)
+    unsigned short max_rx_packet_size;
 } __attribute__((packed)) sock_connect_signal_t;
 
 typedef struct {
-
     /** set to size of this struct*/
     size_t          size;
+
     /**
-     * listen to a rfcomm uuid or channel. It returns the socket fd from which
-     * btsock_connect_signal can be read out when a remote device connected
+     * Listen to a RFCOMM UUID or channel. It returns the socket fd from which
+     * btsock_connect_signal can be read out when a remote device connected.
+     * If neither a UUID nor a channel is provided, a channel will be allocated
+     * and a service record can be created providing the channel number to
+     * create_sdp_record(...) in bt_sdp.
      */
-    bt_status_t (*listen)(btsock_type_t type, const char* service_name, const uint8_t* service_uuid, int channel, int* sock_fd, int flags);
-    /*
-     * connect to a rfcomm uuid channel of remote device, It returns the socket fd from which
+    bt_status_t (*listen)(btsock_type_t type, const char* service_name,
+            const uint8_t* service_uuid, int channel, int* sock_fd, int flags);
+
+    /**
+     * Connect to a RFCOMM UUID channel of remote device, It returns the socket fd from which
      * the btsock_connect_signal and a new socket fd to be accepted can be read out when connected
      */
-    bt_status_t (*connect)(const bt_bdaddr_t *bd_addr, btsock_type_t type, const uint8_t* uuid, int channel, int* sock_fd, int flags);
-
+    bt_status_t (*connect)(const bt_bdaddr_t *bd_addr, btsock_type_t type, const uint8_t* uuid,
+            int channel, int* sock_fd, int flags);
 } btsock_interface_t;
 
 __END_DECLS
 
-#endif /* ANDROID_INCLUDE_BT_SOCK_H */
diff --git a/include/hardware/hw_auth_token.h b/include/hardware/hw_auth_token.h
new file mode 100644
index 0000000..40283cb
--- /dev/null
+++ b/include/hardware/hw_auth_token.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <stdint.h>
+
+#ifndef ANDROID_HARDWARE_HW_AUTH_TOKEN_H
+#define ANDROID_HARDWARE_HW_AUTH_TOKEN_H
+
+#ifndef __cplusplus
+extern "C" {
+#endif  // __cplusplus
+
+const uint8_t HW_AUTH_TOKEN_VERSION = 0;
+
+typedef enum {
+    HW_AUTH_NONE = 0,
+    HW_AUTH_PASSWORD = 1 << 0,
+    HW_AUTH_FINGERPRINT = 1 << 1,
+    // Additional entries should be powers of 2.
+    HW_AUTH_ANY = UINT32_MAX,
+} hw_authenticator_type_t;
+
+/**
+ * Data format for an authentication record used to prove successful authentication.
+ */
+typedef struct __attribute__((__packed__)) {
+    uint8_t version;  // Current version is 0
+    uint64_t challenge;
+    uint64_t user_id;             // secure user ID, not Android user ID
+    uint64_t authenticator_id;    // secure authenticator ID
+    uint32_t authenticator_type;  // hw_authenticator_type_t, in network order
+    uint64_t timestamp;           // in network order
+    uint8_t hmac[32];
+} hw_auth_token_t;
+
+#ifndef __cplusplus
+}  // extern "C"
+#endif  // __cplusplus
+
+#endif  // ANDROID_HARDWARE_HW_AUTH_TOKEN_H
diff --git a/include/hardware/hwcomposer.h b/include/hardware/hwcomposer.h
index 3dfb4fd..aa466b3 100644
--- a/include/hardware/hwcomposer.h
+++ b/include/hardware/hwcomposer.h
@@ -299,8 +299,29 @@
              */
             uint8_t planeAlpha;
 
-            /* reserved for future use */
+            /* Pad to 32 bits */
             uint8_t _pad[3];
+
+            /*
+             * Availability: HWC_DEVICE_API_VERSION_1_5
+             *
+             * This defines the region of the source buffer that has been
+             * modified since the last frame.
+             *
+             * If surfaceDamage.numRects > 0, then it may be assumed that any
+             * portion of the source buffer not covered by one of the rects has
+             * not been modified this frame. If surfaceDamage.numRects == 0,
+             * then the whole source buffer must be treated as if it had been
+             * modified.
+             *
+             * If the layer's contents are not modified relative to the prior
+             * prepare/set cycle, surfaceDamage will contain exactly one empty
+             * rect ([0, 0, 0, 0]).
+             *
+             * The damage rects are relative to the pre-transformed buffer, and
+             * their origin is the top-left corner.
+             */
+            hwc_region_t surfaceDamage;
         };
     };
 
@@ -309,13 +330,13 @@
      * For 64-bit mode, this struct is 120 bytes (and 8-byte aligned), and needs
      * to be padded as such to maintain binary compatibility.
      */
-    uint8_t reserved[120 - 96];
+    uint8_t reserved[120 - 112];
 #else
     /*
      * For 32-bit mode, this struct is 96 bytes, and needs to be padded as such
      * to maintain binary compatibility.
      */
-    uint8_t reserved[96 - 76];
+    uint8_t reserved[96 - 84];
 #endif
 
 } hwc_layer_1_t;
diff --git a/include/hardware/hwcomposer_defs.h b/include/hardware/hwcomposer_defs.h
index 9a52436..e650bd2 100644
--- a/include/hardware/hwcomposer_defs.h
+++ b/include/hardware/hwcomposer_defs.h
@@ -37,6 +37,7 @@
 #define HWC_DEVICE_API_VERSION_1_2  HARDWARE_DEVICE_API_VERSION_2(1, 2, HWC_HEADER_VERSION)
 #define HWC_DEVICE_API_VERSION_1_3  HARDWARE_DEVICE_API_VERSION_2(1, 3, HWC_HEADER_VERSION)
 #define HWC_DEVICE_API_VERSION_1_4  HARDWARE_DEVICE_API_VERSION_2(1, 4, HWC_HEADER_VERSION)
+#define HWC_DEVICE_API_VERSION_1_5  HARDWARE_DEVICE_API_VERSION_2(1, 5, HWC_HEADER_VERSION)
 
 enum {
     /* hwc_composer_device_t::set failed in EGL */
diff --git a/include/hardware/keymaster.h b/include/hardware/keymaster.h
deleted file mode 100644
index 8c5ff14..0000000
--- a/include/hardware/keymaster.h
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright (C) 2011 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_HARDWARE_KEYMASTER_H
-#define ANDROID_HARDWARE_KEYMASTER_H
-
-#include <stdint.h>
-#include <sys/cdefs.h>
-#include <sys/types.h>
-
-#include <hardware/hardware.h>
-
-__BEGIN_DECLS
-
-/**
- * The id of this module
- */
-#define KEYSTORE_HARDWARE_MODULE_ID "keystore"
-
-#define KEYSTORE_KEYMASTER "keymaster"
-
-/**
- * Settings for "module_api_version" and "hal_api_version"
- * fields in the keymaster_module initialization.
- */
-#define KEYMASTER_HEADER_VERSION 3
-
-#define KEYMASTER_MODULE_API_VERSION_0_2  HARDWARE_MODULE_API_VERSION(0, 2)
-#define KEYMASTER_DEVICE_API_VERSION_0_2  HARDWARE_DEVICE_API_VERSION_2(0, 2, KEYMASTER_HEADER_VERSION)
-
-#define KEYMASTER_MODULE_API_VERSION_0_3  HARDWARE_MODULE_API_VERSION(0, 3)
-#define KEYMASTER_DEVICE_API_VERSION_0_3  HARDWARE_DEVICE_API_VERSION_2(0, 3, KEYMASTER_HEADER_VERSION)
-
-/**
- * Flags for keymaster_device::flags
- */
-enum {
-    /*
-     * Indicates this keymaster implementation does not have hardware that
-     * keeps private keys out of user space.
-     *
-     * This should not be implemented on anything other than the default
-     * implementation.
-     */
-    KEYMASTER_SOFTWARE_ONLY = 1 << 0,
-
-    /*
-     * This indicates that the key blobs returned via all the primitives
-     * are sufficient to operate on their own without the trusted OS
-     * querying userspace to retrieve some other data. Key blobs of
-     * this type are normally returned encrypted with a
-     * Key Encryption Key (KEK).
-     *
-     * This is currently used by "vold" to know whether the whole disk
-     * encryption secret can be unwrapped without having some external
-     * service started up beforehand since the "/data" partition will
-     * be unavailable at that point.
-     */
-    KEYMASTER_BLOBS_ARE_STANDALONE = 1 << 1,
-
-    /*
-     * Indicates that the keymaster module supports DSA keys.
-     */
-    KEYMASTER_SUPPORTS_DSA = 1 << 2,
-
-    /*
-     * Indicates that the keymaster module supports EC keys.
-     */
-    KEYMASTER_SUPPORTS_EC = 1 << 3,
-};
-
-struct keystore_module {
-    /**
-     * Common methods of the keystore module.  This *must* be the first member of
-     * keystore_module as users of this structure will cast a hw_module_t to
-     * keystore_module pointer in contexts where it's known the hw_module_t references a
-     * keystore_module.
-     */
-    hw_module_t common;
-};
-
-/**
- * Asymmetric key pair types.
- */
-typedef enum {
-    TYPE_RSA = 1,
-    TYPE_DSA = 2,
-    TYPE_EC = 3,
-} keymaster_keypair_t;
-
-/**
- * Parameters needed to generate an RSA key.
- */
-typedef struct {
-    uint32_t modulus_size;
-    uint64_t public_exponent;
-} keymaster_rsa_keygen_params_t;
-
-/**
- * Parameters needed to generate a DSA key.
- */
-typedef struct {
-    uint32_t key_size;
-    uint32_t generator_len;
-    uint32_t prime_p_len;
-    uint32_t prime_q_len;
-    const uint8_t* generator;
-    const uint8_t* prime_p;
-    const uint8_t* prime_q;
-} keymaster_dsa_keygen_params_t;
-
-/**
- * Parameters needed to generate an EC key.
- *
- * Field size is the only parameter in version 2. The sizes correspond to these required curves:
- *
- * 192 = NIST P-192
- * 224 = NIST P-224
- * 256 = NIST P-256
- * 384 = NIST P-384
- * 521 = NIST P-521
- *
- * The parameters for these curves are available at: http://www.nsa.gov/ia/_files/nist-routines.pdf
- * in Chapter 4.
- */
-typedef struct {
-    uint32_t field_size;
-} keymaster_ec_keygen_params_t;
-
-/**
- * Digest type.
- */
-typedef enum {
-    DIGEST_NONE,
-} keymaster_digest_t;
-
-/**
- * Type of padding used for RSA operations.
- */
-typedef enum {
-    PADDING_NONE,
-} keymaster_rsa_padding_t;
-
-
-typedef struct {
-    keymaster_digest_t digest_type;
-} keymaster_dsa_sign_params_t;
-
-typedef struct {
-    keymaster_digest_t digest_type;
-} keymaster_ec_sign_params_t;
-
-typedef struct {
-    keymaster_digest_t digest_type;
-    keymaster_rsa_padding_t padding_type;
-} keymaster_rsa_sign_params_t;
-
-/**
- * The parameters that can be set for a given keymaster implementation.
- */
-struct keymaster_device {
-    /**
-     * Common methods of the keymaster device.  This *must* be the first member of
-     * keymaster_device as users of this structure will cast a hw_device_t to
-     * keymaster_device pointer in contexts where it's known the hw_device_t references a
-     * keymaster_device.
-     */
-    struct hw_device_t common;
-
-    /**
-     * THIS IS DEPRECATED. Use the new "module_api_version" and "hal_api_version"
-     * fields in the keymaster_module initialization instead.
-     */
-    uint32_t client_version;
-
-    /**
-     * See flags defined for keymaster_device::flags above.
-     */
-    uint32_t flags;
-
-    void* context;
-
-    /**
-     * Generates a public and private key. The key-blob returned is opaque
-     * and must subsequently provided for signing and verification.
-     *
-     * Returns: 0 on success or an error code less than 0.
-     */
-    int (*generate_keypair)(const struct keymaster_device* dev,
-            const keymaster_keypair_t key_type, const void* key_params,
-            uint8_t** key_blob, size_t* key_blob_length);
-
-    /**
-     * Imports a public and private key pair. The imported keys will be in
-     * PKCS#8 format with DER encoding (Java standard). The key-blob
-     * returned is opaque and will be subsequently provided for signing
-     * and verification.
-     *
-     * Returns: 0 on success or an error code less than 0.
-     */
-    int (*import_keypair)(const struct keymaster_device* dev,
-            const uint8_t* key, const size_t key_length,
-            uint8_t** key_blob, size_t* key_blob_length);
-
-    /**
-     * Gets the public key part of a key pair. The public key must be in
-     * X.509 format (Java standard) encoded byte array.
-     *
-     * Returns: 0 on success or an error code less than 0.
-     * On error, x509_data should not be allocated.
-     */
-    int (*get_keypair_public)(const struct keymaster_device* dev,
-            const uint8_t* key_blob, const size_t key_blob_length,
-            uint8_t** x509_data, size_t* x509_data_length);
-
-    /**
-     * Deletes the key pair associated with the key blob.
-     *
-     * This function is optional and should be set to NULL if it is not
-     * implemented.
-     *
-     * Returns 0 on success or an error code less than 0.
-     */
-    int (*delete_keypair)(const struct keymaster_device* dev,
-            const uint8_t* key_blob, const size_t key_blob_length);
-
-    /**
-     * Deletes all keys in the hardware keystore. Used when keystore is
-     * reset completely.
-     *
-     * This function is optional and should be set to NULL if it is not
-     * implemented.
-     *
-     * Returns 0 on success or an error code less than 0.
-     */
-    int (*delete_all)(const struct keymaster_device* dev);
-
-    /**
-     * Signs data using a key-blob generated before. This can use either
-     * an asymmetric key or a secret key.
-     *
-     * Returns: 0 on success or an error code less than 0.
-     */
-    int (*sign_data)(const struct keymaster_device* dev,
-            const void* signing_params,
-            const uint8_t* key_blob, const size_t key_blob_length,
-            const uint8_t* data, const size_t data_length,
-            uint8_t** signed_data, size_t* signed_data_length);
-
-    /**
-     * Verifies data signed with a key-blob. This can use either
-     * an asymmetric key or a secret key.
-     *
-     * Returns: 0 on successful verification or an error code less than 0.
-     */
-    int (*verify_data)(const struct keymaster_device* dev,
-            const void* signing_params,
-            const uint8_t* key_blob, const size_t key_blob_length,
-            const uint8_t* signed_data, const size_t signed_data_length,
-            const uint8_t* signature, const size_t signature_length);
-};
-typedef struct keymaster_device keymaster_device_t;
-
-
-/* Convenience API for opening and closing keymaster devices */
-
-static inline int keymaster_open(const struct hw_module_t* module,
-        keymaster_device_t** device)
-{
-    int rc = module->methods->open(module, KEYSTORE_KEYMASTER,
-            (struct hw_device_t**) device);
-
-    return rc;
-}
-
-static inline int keymaster_close(keymaster_device_t* device)
-{
-    return device->common.close(&device->common);
-}
-
-__END_DECLS
-
-#endif  // ANDROID_HARDWARE_KEYMASTER_H
diff --git a/include/hardware/keymaster0.h b/include/hardware/keymaster0.h
new file mode 100644
index 0000000..f020e5b
--- /dev/null
+++ b/include/hardware/keymaster0.h
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2011 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_HARDWARE_KEYMASTER_0_H
+#define ANDROID_HARDWARE_KEYMASTER_0_H
+
+#include <hardware/keymaster_common.h>
+
+__BEGIN_DECLS
+
+/**
+ * Keymaster0 device definition.
+ */
+struct keymaster0_device {
+    /**
+     * Common methods of the keymaster device.  This *must* be the first member of
+     * keymaster0_device as users of this structure will cast a hw_device_t to
+     * keymaster0_device pointer in contexts where it's known the hw_device_t references a
+     * keymaster0_device.
+     */
+    struct hw_device_t common;
+
+    /**
+     * THIS IS DEPRECATED. Use the new "module_api_version" and "hal_api_version"
+     * fields in the keymaster_module initialization instead.
+     */
+    uint32_t client_version;
+
+    /**
+     * See flags defined for keymaster0_device::flags in keymaster_common.h
+     */
+    uint32_t flags;
+
+    void* context;
+
+    /**
+     * Generates a public and private key. The key-blob returned is opaque
+     * and must subsequently provided for signing and verification.
+     *
+     * Returns: 0 on success or an error code less than 0.
+     */
+    int (*generate_keypair)(const struct keymaster0_device* dev,
+            const keymaster_keypair_t key_type, const void* key_params,
+            uint8_t** key_blob, size_t* key_blob_length);
+
+    /**
+     * Imports a public and private key pair. The imported keys will be in
+     * PKCS#8 format with DER encoding (Java standard). The key-blob
+     * returned is opaque and will be subsequently provided for signing
+     * and verification.
+     *
+     * Returns: 0 on success or an error code less than 0.
+     */
+    int (*import_keypair)(const struct keymaster0_device* dev,
+            const uint8_t* key, const size_t key_length,
+            uint8_t** key_blob, size_t* key_blob_length);
+
+    /**
+     * Gets the public key part of a key pair. The public key must be in
+     * X.509 format (Java standard) encoded byte array.
+     *
+     * Returns: 0 on success or an error code less than 0.
+     * On error, x509_data should not be allocated.
+     */
+    int (*get_keypair_public)(const struct keymaster0_device* dev,
+            const uint8_t* key_blob, const size_t key_blob_length,
+            uint8_t** x509_data, size_t* x509_data_length);
+
+    /**
+     * Deletes the key pair associated with the key blob.
+     *
+     * This function is optional and should be set to NULL if it is not
+     * implemented.
+     *
+     * Returns 0 on success or an error code less than 0.
+     */
+    int (*delete_keypair)(const struct keymaster0_device* dev,
+            const uint8_t* key_blob, const size_t key_blob_length);
+
+    /**
+     * Deletes all keys in the hardware keystore. Used when keystore is
+     * reset completely.
+     *
+     * This function is optional and should be set to NULL if it is not
+     * implemented.
+     *
+     * Returns 0 on success or an error code less than 0.
+     */
+    int (*delete_all)(const struct keymaster0_device* dev);
+
+    /**
+     * Signs data using a key-blob generated before. This can use either
+     * an asymmetric key or a secret key.
+     *
+     * Returns: 0 on success or an error code less than 0.
+     */
+    int (*sign_data)(const struct keymaster0_device* dev,
+            const void* signing_params,
+            const uint8_t* key_blob, const size_t key_blob_length,
+            const uint8_t* data, const size_t data_length,
+            uint8_t** signed_data, size_t* signed_data_length);
+
+    /**
+     * Verifies data signed with a key-blob. This can use either
+     * an asymmetric key or a secret key.
+     *
+     * Returns: 0 on successful verification or an error code less than 0.
+     */
+    int (*verify_data)(const struct keymaster0_device* dev,
+            const void* signing_params,
+            const uint8_t* key_blob, const size_t key_blob_length,
+            const uint8_t* signed_data, const size_t signed_data_length,
+            const uint8_t* signature, const size_t signature_length);
+};
+typedef struct keymaster0_device keymaster0_device_t;
+
+
+/* Convenience API for opening and closing keymaster devices */
+
+static inline int keymaster0_open(const struct hw_module_t* module,
+        keymaster0_device_t** device)
+{
+    int rc = module->methods->open(module, KEYSTORE_KEYMASTER,
+            (struct hw_device_t**) device);
+
+    return rc;
+}
+
+static inline int keymaster0_close(keymaster0_device_t* device)
+{
+    return device->common.close(&device->common);
+}
+
+__END_DECLS
+
+#endif  // ANDROID_HARDWARE_KEYMASTER_0_H
diff --git a/include/hardware/keymaster1.h b/include/hardware/keymaster1.h
new file mode 100644
index 0000000..4227f57
--- /dev/null
+++ b/include/hardware/keymaster1.h
@@ -0,0 +1,615 @@
+/*
+ * Copyright (C) 2015 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_HARDWARE_KEYMASTER1_H
+#define ANDROID_HARDWARE_KEYMASTER1_H
+
+#include <hardware/keymaster_common.h>
+#include <hardware/keymaster_defs.h>
+
+__BEGIN_DECLS
+
+/**
+ * Keymaster1 device definition
+ */
+struct keymaster1_device {
+    /**
+     * Common methods of the keymaster device.  This *must* be the first member of
+     * keymaster_device as users of this structure will cast a hw_device_t to
+     * keymaster_device pointer in contexts where it's known the hw_device_t references a
+     * keymaster_device.
+     */
+    struct hw_device_t common;
+
+    /**
+     * THIS IS DEPRECATED. Use the new "module_api_version" and "hal_api_version"
+     * fields in the keymaster_module initialization instead.
+     */
+    uint32_t client_version;
+
+    /**
+     * See flags defined for keymaster0_devices::flags in keymaster_common.h
+     */
+    uint32_t flags;
+
+    void* context;
+
+    /**
+     * \deprecated Generates a public and private key. The key-blob returned is opaque and must
+     * subsequently provided for signing and verification.
+     *
+     * Returns: 0 on success or an error code less than 0.
+     */
+    int (*generate_keypair)(const struct keymaster1_device* dev, const keymaster_keypair_t key_type,
+                            const void* key_params, uint8_t** key_blob, size_t* key_blob_length);
+
+    /**
+     * \deprecated Imports a public and private key pair. The imported keys will be in PKCS#8 format
+     * with DER encoding (Java standard). The key-blob returned is opaque and will be subsequently
+     * provided for signing and verification.
+     *
+     * Returns: 0 on success or an error code less than 0.
+     */
+    int (*import_keypair)(const struct keymaster1_device* dev, const uint8_t* key,
+                          const size_t key_length, uint8_t** key_blob, size_t* key_blob_length);
+
+    /**
+     * \deprecated Gets the public key part of a key pair. The public key must be in X.509 format
+     * (Java standard) encoded byte array.
+     *
+     * Returns: 0 on success or an error code less than 0.  On error, x509_data
+     * should not be allocated.
+     */
+    int (*get_keypair_public)(const struct keymaster1_device* dev, const uint8_t* key_blob,
+                              const size_t key_blob_length, uint8_t** x509_data,
+                              size_t* x509_data_length);
+
+    /**
+     * \deprecated Deletes the key pair associated with the key blob.
+     *
+     * This function is optional and should be set to NULL if it is not
+     * implemented.
+     *
+     * Returns 0 on success or an error code less than 0.
+     */
+    int (*delete_keypair)(const struct keymaster1_device* dev, const uint8_t* key_blob,
+                          const size_t key_blob_length);
+
+    /**
+     * \deprecated Deletes all keys in the hardware keystore. Used when keystore is reset
+     * completely.
+     *
+     * This function is optional and should be set to NULL if it is not
+     * implemented.
+     *
+     * Returns 0 on success or an error code less than 0.
+     */
+    int (*delete_all)(const struct keymaster1_device* dev);
+
+    /**
+     * \deprecated Signs data using a key-blob generated before. This can use either an asymmetric
+     * key or a secret key.
+     *
+     * Returns: 0 on success or an error code less than 0.
+     */
+    int (*sign_data)(const struct keymaster1_device* dev, const void* signing_params,
+                     const uint8_t* key_blob, const size_t key_blob_length, const uint8_t* data,
+                     const size_t data_length, uint8_t** signed_data, size_t* signed_data_length);
+
+    /**
+     * \deprecated Verifies data signed with a key-blob. This can use either an asymmetric key or a
+     * secret key.
+     *
+     * Returns: 0 on successful verification or an error code less than 0.
+     */
+    int (*verify_data)(const struct keymaster1_device* dev, const void* signing_params,
+                       const uint8_t* key_blob, const size_t key_blob_length,
+                       const uint8_t* signed_data, const size_t signed_data_length,
+                       const uint8_t* signature, const size_t signature_length);
+
+    /**
+     * Gets algorithms supported.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[out] algorithms Array of algorithms supported.  The caller takes ownership of the
+     * array and must free() it.
+     *
+     * \param[out] algorithms_length Length of \p algorithms.
+     */
+    keymaster_error_t (*get_supported_algorithms)(const struct keymaster1_device* dev,
+                                                  keymaster_algorithm_t** algorithms,
+                                                  size_t* algorithms_length);
+
+    /**
+     * Gets the block modes supported for the specified algorithm.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] algorithm The algorithm for which supported modes will be returned.
+     *
+     * \param[out] modes Array of modes supported.  The caller takes ownership of the array and must
+     * free() it.
+     *
+     * \param[out] modes_length Length of \p modes.
+     */
+    keymaster_error_t (*get_supported_block_modes)(const struct keymaster1_device* dev,
+                                                   keymaster_algorithm_t algorithm,
+                                                   keymaster_purpose_t purpose,
+                                                   keymaster_block_mode_t** modes,
+                                                   size_t* modes_length);
+
+    /**
+     * Gets the padding modes supported for the specified algorithm.  Caller assumes ownership of
+     * the allocated array.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] algorithm The algorithm for which supported padding modes will be returned.
+     *
+     * \param[out] modes Array of padding modes supported.  The caller takes ownership of the array
+     * and must free() it.
+     *
+     * \param[out] modes_length Length of \p modes.
+     */
+    keymaster_error_t (*get_supported_padding_modes)(const struct keymaster1_device* dev,
+                                                     keymaster_algorithm_t algorithm,
+                                                     keymaster_purpose_t purpose,
+                                                     keymaster_padding_t** modes,
+                                                     size_t* modes_length);
+
+    /**
+     * Gets the digests supported for the specified algorithm.  Caller assumes ownership of the
+     * allocated array.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] algorithm The algorithm for which supported digests will be returned.
+     *
+     * \param[out] digests Array of digests supported.  The caller takes ownership of the array and
+     * must free() it.
+     *
+     * \param[out] digests_length Length of \p digests.
+     */
+    keymaster_error_t (*get_supported_digests)(const struct keymaster1_device* dev,
+                                               keymaster_algorithm_t algorithm,
+                                               keymaster_purpose_t purpose,
+                                               keymaster_digest_t** digests,
+                                               size_t* digests_length);
+
+    /**
+     * Gets the key import formats supported for keys of the specified algorithm.  Caller assumes
+     * ownership of the allocated array.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] algorithm The algorithm for which supported formats will be returned.
+     *
+     * \param[out] formats Array of formats supported.  The caller takes ownership of the array and
+     * must free() it.
+     *
+     * \param[out] formats_length Length of \p formats.
+     */
+    keymaster_error_t (*get_supported_import_formats)(const struct keymaster1_device* dev,
+                                                      keymaster_algorithm_t algorithm,
+                                                      keymaster_key_format_t** formats,
+                                                      size_t* formats_length);
+
+    /**
+     * Gets the key export formats supported for keys of the specified algorithm.  Caller assumes
+     * ownership of the allocated array.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] algorithm The algorithm for which supported formats will be returned.
+     *
+     * \param[out] formats Array of formats supported.  The caller takes ownership of the array and
+     * must free() it.
+     *
+     * \param[out] formats_length Length of \p formats.
+     */
+    keymaster_error_t (*get_supported_export_formats)(const struct keymaster1_device* dev,
+                                                      keymaster_algorithm_t algorithm,
+                                                      keymaster_key_format_t** formats,
+                                                      size_t* formats_length);
+
+    /**
+     * Adds entropy to the RNG used by keymaster.  Entropy added through this method is guaranteed
+     * not to be the only source of entropy used, and the mixing function is required to be secure,
+     * in the sense that if the RNG is seeded (from any source) with any data the attacker cannot
+     * predict (or control), then the RNG output is indistinguishable from random.  Thus, if the
+     * entropy from any source is good, the output will be good.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] data Random data to be mixed in.
+     *
+     * \param[in] data_length Length of \p data.
+     */
+    keymaster_error_t (*add_rng_entropy)(const struct keymaster1_device* dev, const uint8_t* data,
+                                         size_t data_length);
+
+    /**
+     * Generates a key, or key pair, returning a key blob and/or a description of the key.
+     *
+     * Key generation parameters are defined as keymaster tag/value pairs, provided in \p params.
+     * See keymaster_tag_t for the full list.  Some values that are always required for generation
+     * of useful keys are:
+     *
+     * - KM_TAG_ALGORITHM;
+     * - KM_TAG_PURPOSE;
+     * - KM_TAG_USER_ID or KM_TAG_ALL_USERS;
+     * - KM_TAG_USER_AUTH_ID or KM_TAG_NO_AUTH_REQUIRED;
+     * - KM_TAG_APPLICATION_ID or KM_TAG_ALL_APPLICATIONS; and
+     * - KM_TAG_ORIGINATION_EXPIRE_DATETIME
+     *
+     * KM_TAG_AUTH_TIMEOUT should generally be specified unless KM_TAG_NO_AUTH_REQUIRED is present,
+     * or the user will have to authenticate for every use.
+     *
+     * KM_TAG_BLOCK_MODE, KM_TAG_PADDING, KM_TAG_MAC_LENGTH and KM_TAG_DIGEST must be specified for
+     * algorithms that require them.
+     *
+     * The following tags will take default values if unspecified:
+     *
+     * - KM_TAG_KEY_SIZE defaults to a recommended key size for the  specified algorithm.
+     *
+     * - KM_TAG_USAGE_EXPIRE_DATETIME defaults to the value of KM_TAG_ORIGINATION_EXPIRE_DATETIME.
+     *
+     * - KM_TAG_ACTIVE_DATETIME will default to the value of KM_TAG_CREATION_DATETIME
+     *
+     * - KM_TAG_ROOT_OF_TRUST will default to the current root of trust.
+     *
+     * - KM_TAG_{RSA|DSA|DH}_* will default to values appropriate for the specified key size.
+     *
+     * The following tags may not be specified; their values will be provided by the implementation.
+     *
+     * - KM_TAG_ORIGIN,
+     *
+     * - KM_TAG_ROLLBACK_RESISTANT,
+     *
+     * - KM_TAG_CREATION_DATETIME,
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] params Array of key generation parameters.
+     *
+     * \param[in] params_count Length of \p params.
+     *
+     * \param[out] key_blob returns the generated key. If \p key_blob is NULL, no key is generated,
+     * but the characteristics of the key that would be generated are returned.  The caller assumes
+     * ownership key_blob->key_material and must free() it.
+     *
+     * \param[out] characteristics returns the characteristics of the key that was, or would be,
+     * generated, if non-NULL.  The caller assumes ownership, and the object must be freed with
+     * keymaster_free_characteristics().  Note that KM_TAG_ROOT_OF_TRUST, KM_TAG_APPLICATION_ID and
+     * KM_TAG_APPLICATION_DATA are never returned.
+     */
+    keymaster_error_t (*generate_key)(const struct keymaster1_device* dev,
+                                      const keymaster_key_param_t* params, size_t params_count,
+                                      keymaster_key_blob_t* key_blob,
+                                      keymaster_key_characteristics_t** characteristics);
+
+    /**
+     * Returns the characteristics of the specified key, or NULL if the key_blob is invalid
+     * (implementations must fully validate the integrity of the key).  client_id and app_data must
+     * be the ID and data provided when the key was generated or imported.  Those values are not
+     * included in the returned characteristics.  Caller assumes ownership of the allocated
+     * characteristics object, which must be deallocated with keymaster_free_characteristics().
+     *
+     * Note that KM_TAG_ROOT_OF_TRUST, KM_TAG_APPLICATION_ID and KM_TAG_APPLICATION_DATA are never
+     * returned.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] key_blob The key to retreive characteristics from.
+     *
+     * \param[in] client_id The client ID data, or NULL if none associated.
+     *
+     * \param[in] app_id The app data, or NULL if none associated.
+     *
+     * \param[out] characteristics The key characteristics.
+     */
+    keymaster_error_t (*get_key_characteristics)(const struct keymaster1_device* dev,
+                                                 const keymaster_key_blob_t* key_blob,
+                                                 const keymaster_blob_t* client_id,
+                                                 const keymaster_blob_t* app_data,
+                                                 keymaster_key_characteristics_t** characteristics);
+
+    /**
+     * Change a key's authorizations.
+     *
+     * Update the authorizations associated with key_blob to the list specified in new_params, which
+     * must contain the complete set of authorizations desired (hw_enforced and sw_enforced).  Tags
+     * will be added, removed and/or updated only if the appropriate KM_TAG_RESCOPING_ADD and
+     * KM_TAG_RESCOPING_DEL tags exist in the key's authorizations, otherwise
+     * KM_ERROR_INVALID_RESCOPING will be returned and no changes will be made.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] new_params The new authorization list to be associated with the key.
+     *
+     * \param[in] new_params_count The number of entries in \p new_params.
+     *
+     * \param[in] key_blob The key to update.
+     *
+     * \param[in] client_id The client ID associated with the key, or NULL if none is associated.
+     *
+     * \param[in] app_data The application data associated with the key, or NULL if none is
+     * associated.
+     *
+     * \param[out] rescoped_key_blob The key blob with the updated authorizations, if successful.
+     * The caller assumes ownership of rescoped_key_blob->key_material and must free() it.
+     *
+     * \param[out] characteristics If not null will contain the new key authorizations, divided into
+     * hw_enforced and sw_enforced lists.  The caller takes ownership and must call
+     * keymaster_free_characteristics() to free.
+     */
+    keymaster_error_t (*rescope)(const struct keymaster1_device* dev,
+                                 const keymaster_key_param_t* new_params, size_t new_params_count,
+                                 const keymaster_key_blob_t* key_blob,
+                                 const keymaster_blob_t* client_id,
+                                 const keymaster_blob_t* app_data,
+                                 keymaster_key_blob_t* rescoped_key_blob,
+                                 keymaster_key_characteristics_t** characteristics);
+
+    /**
+     * Imports a key, or key pair, returning a key blob and/or a description of the key.
+     *
+     * Most key import parameters are defined as keymaster tag/value pairs, provided in "params".
+     * See keymaster_tag_t for the full list.  Some values that are always required for import of
+     * useful keys are:
+     *
+     * - KM_TAG_PURPOSE;
+     *
+     * - KM_TAG_USER_ID
+     *
+     * - KM_TAG_USER_AUTH_ID;
+     *
+     * - KM_TAG_APPLICATION_ID or KM_TAG_ALL_APPLICATIONS;
+     *
+     * - KM_TAG_PRIVKEY_EXPIRE_DATETIME.
+     *
+     * KM_TAG_AUTH_TIMEOUT should generally be specified. If unspecified, the user will have to
+     * authenticate for every use, unless KM_TAG_USER_AUTH_ID is set to
+     * KM_NO_AUTHENTICATION_REQUIRED.
+     *
+     * The following tags will take default values if unspecified:
+     *
+     * - KM_TAG_PUBKEY_EXPIRE_DATETIME will default to the value for KM_TAG_PRIVKEY_EXPIRE_DATETIME.
+     *
+     * - KM_TAG_ACTIVE_DATETIME will default to the value of KM_TAG_CREATION_DATETIME
+     *
+     * - KM_TAG_ROOT_OF_TRUST will default to the current root of trust.
+     *
+     * The following tags may not be specified; their values will be provided by the implementation.
+     *
+     * - KM_TAG_ORIGIN,
+     *
+     * - KM_TAG_ROLLBACK_RESISTANT,
+     *
+     * - KM_TAG_CREATION_DATETIME,
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] params Parameters defining the imported key.
+     *
+     * \param[in] params_count The number of entries in \p params.
+     *
+     * \param[in] key_format specifies the format of the key data in key_data.
+     *
+     * \param[out] key_blob Used to return the opaque key blob.  Must be non-NULL.  The caller
+     * assumes ownership of the contained key_material.
+     *
+     * \param[out] characteristics Used to return the characteristics of the imported key.  May be
+     * NULL, in which case no characteristics will be returned.  If non-NULL, the caller assumes
+     * ownership and must deallocate with keymaster_free_characteristics().
+     */
+    keymaster_error_t (*import_key)(const struct keymaster1_device* dev,
+                                    const keymaster_key_param_t* params, size_t params_count,
+                                    keymaster_key_format_t key_format, const uint8_t* key_data,
+                                    size_t key_data_length, keymaster_key_blob_t* key_blob,
+                                    keymaster_key_characteristics_t** characteristics);
+
+    /**
+     * Exports a public key, returning a byte array in the specified format.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] export_format The format to be used for exporting the key.
+     *
+     * \param[in] key_to_export The key to export.
+     *
+     * \param[out] export_data The exported key material.  The caller assumes ownership.
+     *
+     * \param[out] export_data_length The length of \p export_data.
+     */
+    keymaster_error_t (*export_key)(const struct keymaster1_device* dev,
+                                    keymaster_key_format_t export_format,
+                                    const keymaster_key_blob_t* key_to_export,
+                                    const keymaster_blob_t* client_id,
+                                    const keymaster_blob_t* app_data, uint8_t** export_data,
+                                    size_t* export_data_length);
+
+    /**
+     * Deletes the key, or key pair, associated with the key blob.  After calling this function it
+     * will be impossible to use the key for any other operations (though rescoped versions may
+     * exist, and if so will be usable).  May be applied to keys from foreign roots of trust (keys
+     * not usable under the current root of trust).
+     *
+     * This function is optional and should be set to NULL if it is not implemented.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] key The key to be deleted.
+     */
+    keymaster_error_t (*delete_key)(const struct keymaster1_device* dev,
+                                    const keymaster_key_blob_t* key);
+
+    /**
+     * Deletes all keys in the hardware keystore. Used when keystore is reset completely.  After
+     * calling this function it will be impossible to use any previously generated or imported key
+     * blobs for any operations.
+     *
+     * This function is optional and should be set to NULL if it is not implemented.
+     *
+     * \param[in] dev The keymaster device structure.
+     */
+    keymaster_error_t (*delete_all_keys)(const struct keymaster1_device* dev);
+
+    /**
+     * Begins a cryptographic operation using the specified key.  If all is well, begin() will
+     * return KM_ERROR_OK and create an operation handle which must be passed to subsequent calls to
+     * update(), finish() or abort().
+     *
+     * It is critical that each call to begin() be paired with a subsequent call to finish() or
+     * abort(), to allow the keymaster implementation to clean up any internal operation state.
+     * Failure to do this will leak internal state space or other internal resources and will
+     * eventually cause begin() to return KM_ERROR_TOO_MANY_OPERATIONS when it runs out of space for
+     * operations.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] purpose The purpose of the operation, one of KM_PURPOSE_ENCRYPT,
+     * KM_PURPOSE_DECRYPT, KM_PURPOSE_SIGN or KM_PURPOSE_VERIFY. Note that for AEAD modes,
+     * encryption and decryption imply signing and verification, respectively.
+     *
+     * \param[in] key The key to be used for the operation. \p key must have a purpose compatible
+     * with \p purpose and all of its usage requirements must be satisfied, or begin() will return
+     * an appropriate error code.
+     *
+     * \param[in] params Additional parameters for the operation.  This is typically used to provide
+     * client ID information, with tags KM_TAG_APPLICATION_ID and KM_TAG_APPLICATION_DATA.  If the
+     * client information associated with the key is not provided, begin() will fail and return
+     * KM_ERROR_INVALID_KEY_BLOB.  For operations that require a nonce or IV, this must contain a
+     * tag KM_TAG_NONCE.  For AEAD operations KM_TAG_CHUNK_SIZE is specified here.
+     *
+     * \param[in] params_count The number of entries in \p params.
+     *
+     * \param[out] out_params Array of output parameters.  The caller takes ownership of the output
+     * parametes array and must free it.  out_params may be set to NULL if no output parameters are
+     * expected.  If NULL, and output paramaters are generated, begin() will return
+     * KM_ERROR_OUTPUT_PARAMETER_NULL.
+     *
+     * \param[out] out_params_count The length of out_params.
+     *
+     * \param[out] operation_handle The newly-created operation handle which must be passed to
+     * update(), finish() or abort().
+     */
+    keymaster_error_t (*begin)(const struct keymaster1_device* dev, keymaster_purpose_t purpose,
+                               const keymaster_key_blob_t* key, const keymaster_key_param_t* params,
+                               size_t params_count, keymaster_key_param_t** out_params,
+                               size_t* out_params_count,
+                               keymaster_operation_handle_t* operation_handle);
+
+    /**
+     * Provides data to, and possibly receives output from, an ongoing cryptographic operation begun
+     * with begin().
+     *
+     * If operation_handle is invalid, update() will return KM_ERROR_INVALID_OPERATION_HANDLE.
+     *
+     * Not all of the data provided in the data buffer may be consumed.  update() will return the
+     * amount consumed in *data_consumed.  The caller should provide the unconsumed data in a
+     * subsequent call.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] operation_handle The operation handle returned by begin().
+     *
+     * \param[in] params Additional parameters for the operation.  For AEAD modes, this is used to
+     * specify KM_TAG_ADDITIONAL_DATA.
+     *
+     * \param[in] params_count Length of \p params.
+     *
+     * \param[in] input Data to be processed, per the parameters established in the call to begin().
+     * Note that update() may or may not consume all of the data provided.  See \p data_consumed.
+     *
+     * \param[in] input_length Length of \p input.
+     *
+     * \param[out] input_consumed Amount of data that was consumed by update().  If this is less
+     * than the amount provided, the caller should provide the remainder in a subsequent call to
+     * update().
+     *
+     * \param[out] output The output data, if any.  The caller assumes ownership of the allocated
+     * buffer.  If output is NULL then NO input data is consumed and no output is produced, but
+     * *output_length is set to an estimate of the size that would have been produced by this
+     * update() and a subsequent finish().
+     *
+     * \param[out] output_length The length of the output buffer.
+     *
+     * Note that update() may not provide any output, in which case *output_length will be zero, and
+     * *output may be either NULL or zero-length (so the caller should always free() it).
+     */
+    keymaster_error_t (*update)(const struct keymaster1_device* dev,
+                                keymaster_operation_handle_t operation_handle,
+                                const keymaster_key_param_t* params, size_t params_count,
+                                const uint8_t* input, size_t input_length, size_t* input_consumed,
+                                uint8_t** output, size_t* output_length);
+
+    /**
+     * Finalizes a cryptographic operation begun with begin() and invalidates operation_handle
+     * (except in the insufficient buffer case, detailed below).
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] operation_handle The operation handle returned by begin().  This handle will be
+     * invalidated.
+     *
+     * \param[in] params Additional parameters for the operation.  For AEAD modes, this is used to
+     * specify KM_TAG_ADDITIONAL_DATA.
+     *
+     * \param[in] params_count Length of \p params.
+     *
+     * \param[in] signature The signature to be verified if the purpose specified in the begin()
+     * call was KM_PURPOSE_VERIFY.
+     *
+     * \param[in] signature_length The length of \p signature.
+     *
+     * \param[out] output The output data, if any.  The caller assumes ownership of the allocated
+     * buffer.
+     *
+     * \param[out] output_length The length of the output buffer.
+     *
+     * If the operation being finished is a signature verification or an AEAD-mode decryption and
+     * verification fails then finish() will return KM_ERROR_VERIFICATION_FAILED.
+     */
+    keymaster_error_t (*finish)(const struct keymaster1_device* dev,
+                                keymaster_operation_handle_t operation_handle,
+                                const keymaster_key_param_t* params, size_t params_count,
+                                const uint8_t* signature, size_t signature_length, uint8_t** output,
+                                size_t* output_length);
+
+    /**
+     * Aborts a cryptographic operation begun with begin(), freeing all internal resources and
+     * invalidating operation_handle.
+     */
+    keymaster_error_t (*abort)(const struct keymaster1_device* dev,
+                               keymaster_operation_handle_t operation_handle);
+};
+typedef struct keymaster1_device keymaster1_device_t;
+
+/* Convenience API for opening and closing keymaster devices */
+
+static inline int keymaster1_open(const struct hw_module_t* module, keymaster1_device_t** device) {
+    return module->methods->open(module, KEYSTORE_KEYMASTER, (struct hw_device_t**)device);
+}
+
+static inline int keymaster1_close(keymaster1_device_t* device) {
+    return device->common.close(&device->common);
+}
+
+__END_DECLS
+
+#endif  // ANDROID_HARDWARE_KEYMASTER1_H
diff --git a/include/hardware/keymaster_common.h b/include/hardware/keymaster_common.h
new file mode 100644
index 0000000..772d7e4
--- /dev/null
+++ b/include/hardware/keymaster_common.h
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2015 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_HARDWARE_KEYMASTER_COMMON_H
+#define ANDROID_HARDWARE_KEYMASTER_COMMON_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#include <hardware/hardware.h>
+
+__BEGIN_DECLS
+
+/**
+ * The id of this module
+ */
+#define KEYSTORE_HARDWARE_MODULE_ID "keystore"
+
+#define KEYSTORE_KEYMASTER "keymaster"
+
+
+/**
+ * Settings for "module_api_version" and "hal_api_version"
+ * fields in the keymaster_module initialization.
+ */
+
+/**
+ * Keymaster 0.X module version provide the same APIs, but later versions add more options
+ * for algorithms and flags.
+ */
+#define KEYMASTER_MODULE_API_VERSION_0_2 HARDWARE_MODULE_API_VERSION(0, 2)
+#define KEYMASTER_DEVICE_API_VERSION_0_2 HARDWARE_DEVICE_API_VERSION(0, 2)
+
+#define KEYMASTER_MODULE_API_VERSION_0_3 HARDWARE_MODULE_API_VERSION(0, 3)
+#define KEYMASTER_DEVICE_API_VERSION_0_3 HARDWARE_DEVICE_API_VERSION(0, 3)
+
+/**
+ * Keymaster 1.0 module version provides a completely different API, incompatible with 0.X.
+ */
+#define KEYMASTER_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0)
+#define KEYMASTER_DEVICE_API_VERSION_1_0 HARDWARE_DEVICE_API_VERSION(1, 0)
+
+struct keystore_module {
+    /**
+     * Common methods of the keystore module.  This *must* be the first member of keystore_module as
+     * users of this structure will cast a hw_module_t to keystore_module pointer in contexts where
+     * it's known the hw_module_t references a keystore_module.
+     */
+    hw_module_t common;
+
+    /* There are no keystore module methods other than the common ones. */
+};
+
+/**
+ * Flags for keymaster0_device::flags
+ */
+enum {
+    /*
+     * Indicates this keymaster implementation does not have hardware that
+     * keeps private keys out of user space.
+     *
+     * This should not be implemented on anything other than the default
+     * implementation.
+     */
+    KEYMASTER_SOFTWARE_ONLY = 1 << 0,
+
+    /*
+     * This indicates that the key blobs returned via all the primitives
+     * are sufficient to operate on their own without the trusted OS
+     * querying userspace to retrieve some other data. Key blobs of
+     * this type are normally returned encrypted with a
+     * Key Encryption Key (KEK).
+     *
+     * This is currently used by "vold" to know whether the whole disk
+     * encryption secret can be unwrapped without having some external
+     * service started up beforehand since the "/data" partition will
+     * be unavailable at that point.
+     */
+    KEYMASTER_BLOBS_ARE_STANDALONE = 1 << 1,
+
+    /*
+     * Indicates that the keymaster module supports DSA keys.
+     */
+    KEYMASTER_SUPPORTS_DSA = 1 << 2,
+
+    /*
+     * Indicates that the keymaster module supports EC keys.
+     */
+    KEYMASTER_SUPPORTS_EC = 1 << 3,
+};
+
+/**
+ * Asymmetric key pair types.
+ */
+typedef enum {
+    TYPE_RSA = 1,
+    TYPE_DSA = 2,
+    TYPE_EC = 3,
+} keymaster_keypair_t;
+
+/**
+ * Parameters needed to generate an RSA key.
+ */
+typedef struct {
+    uint32_t modulus_size;
+    uint64_t public_exponent;
+} keymaster_rsa_keygen_params_t;
+
+/**
+ * Parameters needed to generate a DSA key.
+ */
+typedef struct {
+    uint32_t key_size;
+    uint32_t generator_len;
+    uint32_t prime_p_len;
+    uint32_t prime_q_len;
+    const uint8_t* generator;
+    const uint8_t* prime_p;
+    const uint8_t* prime_q;
+} keymaster_dsa_keygen_params_t;
+
+/**
+ * Parameters needed to generate an EC key.
+ *
+ * Field size is the only parameter in version 2. The sizes correspond to these required curves:
+ *
+ * 192 = NIST P-192
+ * 224 = NIST P-224
+ * 256 = NIST P-256
+ * 384 = NIST P-384
+ * 521 = NIST P-521
+ *
+ * The parameters for these curves are available at: http://www.nsa.gov/ia/_files/nist-routines.pdf
+ * in Chapter 4.
+ */
+typedef struct {
+    uint32_t field_size;
+} keymaster_ec_keygen_params_t;
+
+
+/**
+ * Digest type.
+ */
+typedef enum {
+    DIGEST_NONE,
+} keymaster_digest_algorithm_t;
+
+/**
+ * Type of padding used for RSA operations.
+ */
+typedef enum {
+    PADDING_NONE,
+} keymaster_rsa_padding_t;
+
+
+typedef struct {
+    keymaster_digest_algorithm_t digest_type;
+} keymaster_dsa_sign_params_t;
+
+typedef struct {
+    keymaster_digest_algorithm_t digest_type;
+} keymaster_ec_sign_params_t;
+
+typedef struct {
+    keymaster_digest_algorithm_t digest_type;
+    keymaster_rsa_padding_t padding_type;
+} keymaster_rsa_sign_params_t;
+
+__END_DECLS
+
+#endif  // ANDROID_HARDWARE_KEYMASTER_COMMON_H
diff --git a/include/hardware/keymaster_defs.h b/include/hardware/keymaster_defs.h
new file mode 100644
index 0000000..2b43f2c
--- /dev/null
+++ b/include/hardware/keymaster_defs.h
@@ -0,0 +1,525 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_HARDWARE_KEYMASTER_DEFS_H
+#define ANDROID_HARDWARE_KEYMASTER_DEFS_H
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifndef __cplusplus
+extern "C" {
+#endif  // __cplusplus
+
+/**
+ * Authorization tags each have an associated type.  This enumeration facilitates tagging each with
+ * a type, by using the high four bits (of an implied 32-bit unsigned enum value) to specify up to
+ * 16 data types.  These values are ORed with tag IDs to generate the final tag ID values.
+ */
+typedef enum {
+    KM_INVALID = 0 << 28, /* Invalid type, used to designate a tag as uninitialized */
+    KM_ENUM = 1 << 28,
+    KM_ENUM_REP = 2 << 28, /* Repeatable enumeration value. */
+    KM_INT = 3 << 28,
+    KM_INT_REP = 4 << 28, /* Repeatable integer value */
+    KM_LONG = 5 << 28,
+    KM_DATE = 6 << 28,
+    KM_BOOL = 7 << 28,
+    KM_BIGNUM = 8 << 28,
+    KM_BYTES = 9 << 28,
+    KM_LONG_REP = 10 << 28, /* Repeatable long value */
+} keymaster_tag_type_t;
+
+typedef enum {
+    KM_TAG_INVALID = KM_INVALID | 0,
+
+    /*
+     * Tags that must be semantically enforced by hardware and software implementations.
+     */
+
+    /* Crypto parameters */
+    KM_TAG_PURPOSE = KM_ENUM_REP | 1,     /* keymaster_purpose_t. */
+    KM_TAG_ALGORITHM = KM_ENUM | 2,       /* keymaster_algorithm_t. */
+    KM_TAG_KEY_SIZE = KM_INT | 3,         /* Key size in bits. */
+    KM_TAG_BLOCK_MODE = KM_ENUM_REP | 4,  /* keymaster_block_mode_t. */
+    KM_TAG_DIGEST = KM_ENUM_REP | 5,      /* keymaster_digest_t. */
+    KM_TAG_PADDING = KM_ENUM_REP | 6,     /* keymaster_padding_t. */
+    KM_TAG_RETURN_UNAUTHED = KM_BOOL | 7, /* Allow AEAD decryption to return plaintext before it has
+                                             been authenticated.  WARNING: Not recommended. */
+    KM_TAG_CALLER_NONCE = KM_BOOL | 8,    /* Allow caller to specify nonce or IV. */
+
+    /* Other hardware-enforced. */
+    KM_TAG_RESCOPING_ADD = KM_ENUM_REP | 101, /* Tags authorized for addition via rescoping. */
+    KM_TAG_RESCOPING_DEL = KM_ENUM_REP | 102, /* Tags authorized for removal via rescoping. */
+    KM_TAG_BLOB_USAGE_REQUIREMENTS = KM_ENUM | 705, /* keymaster_key_blob_usage_requirements_t */
+
+    /* Algorithm-specific. */
+    KM_TAG_RSA_PUBLIC_EXPONENT = KM_LONG | 200, /* Defaults to 2^16+1 */
+
+    /*
+     * Tags that should be semantically enforced by hardware if possible and will otherwise be
+     * enforced by software (keystore).
+     */
+
+    /* Key validity period */
+    KM_TAG_ACTIVE_DATETIME = KM_DATE | 400,             /* Start of validity */
+    KM_TAG_ORIGINATION_EXPIRE_DATETIME = KM_DATE | 401, /* Date when new "messages" should no
+                                                           longer be created. */
+    KM_TAG_USAGE_EXPIRE_DATETIME = KM_DATE | 402,       /* Date when existing "messages" should no
+                                                           longer be trusted. */
+    KM_TAG_MIN_SECONDS_BETWEEN_OPS = KM_INT | 403,      /* Minimum elapsed time between
+                                                           cryptographic operations with the key. */
+    KM_TAG_MAX_USES_PER_BOOT = KM_INT | 404,            /* Number of times the key can be used per
+                                                           boot. */
+
+    /* User authentication */
+    KM_TAG_ALL_USERS = KM_BOOL | 500,          /* If key is usable by all users. */
+    KM_TAG_USER_ID = KM_INT | 501,             /* ID of authorized user.  Disallowed if
+                                                  KM_TAG_ALL_USERS is present. */
+    KM_TAG_USER_SECURE_ID = KM_LONG_REP | 502, /* Secure ID of authorized user or authenticator(s).
+                                                  Disallowed if KM_TAG_ALL_USERS or
+                                                  KM_TAG_NO_AUTH_REQUIRED is present. */
+    KM_TAG_NO_AUTH_REQUIRED = KM_BOOL | 503,   /* If key is usable without authentication. */
+    KM_TAG_USER_AUTH_TYPE = KM_ENUM | 504,     /* Bitmask of authenticator types allowed when
+                                                * KM_TAG_USER_SECURE_ID contains a secure user ID,
+                                                * rather than a secure authenticator ID.  Defined in
+                                                * hw_authenticator_type_t in hw_auth_token.h. */
+    KM_TAG_AUTH_TIMEOUT = KM_INT | 505,        /* Required freshness of user authentication for
+                                                  private/secret key operations, in seconds.
+                                                  Public key operations require no authentication.
+                                                  If absent, authentication is required for every
+                                                  use.  Authentication state is lost when the
+                                                  device is powered off. */
+
+    /* Application access control */
+    KM_TAG_ALL_APPLICATIONS = KM_BOOL | 600, /* If key is usable by all applications. */
+    KM_TAG_APPLICATION_ID = KM_BYTES | 601,  /* ID of authorized application. Disallowed if
+                                                KM_TAG_ALL_APPLICATIONS is present. */
+
+    /*
+     * Semantically unenforceable tags, either because they have no specific meaning or because
+     * they're informational only.
+     */
+    KM_TAG_APPLICATION_DATA = KM_BYTES | 700,  /* Data provided by authorized application. */
+    KM_TAG_CREATION_DATETIME = KM_DATE | 701,  /* Key creation time */
+    KM_TAG_ORIGIN = KM_ENUM | 702,             /* keymaster_key_origin_t. */
+    KM_TAG_ROLLBACK_RESISTANT = KM_BOOL | 703, /* Whether key is rollback-resistant. */
+    KM_TAG_ROOT_OF_TRUST = KM_BYTES | 704,     /* Root of trust ID.  Empty array means usable by all
+                                                  roots. */
+
+    /* Tags used only to provide data to or receive data from operations */
+    KM_TAG_ASSOCIATED_DATA = KM_BYTES | 1000, /* Used to provide associated data for AEAD modes. */
+    KM_TAG_NONCE = KM_BYTES | 1001,           /* Nonce or Initialization Vector */
+    KM_TAG_CHUNK_LENGTH = KM_INT | 1002,      /* AEAD mode chunk size, in bytes.  0 means no limit,
+                                                 which requires KM_TAG_RETURN_UNAUTHED. */
+    KM_TAG_AUTH_TOKEN = KM_BYTES | 1003,      /* Authentication token that proves secure user
+                                                 authentication has been performed.  Structure
+                                                 defined in hw_auth_token_t in hw_auth_token.h. */
+    KM_TAG_MAC_LENGTH = KM_INT | 1004,        /* MAC or AEAD authentication tag length in bits. */
+} keymaster_tag_t;
+
+/**
+ * Algorithms that may be provided by keymaster implementations.  Those that must be provided by all
+ * implementations are tagged as "required".
+ */
+typedef enum {
+    /* Asymmetric algorithms. */
+    KM_ALGORITHM_RSA = 1,
+    // KM_ALGORITHM_DSA = 2, -- Removed, do not re-use value 2.
+    KM_ALGORITHM_EC = 3,
+
+    /* Block ciphers algorithms */
+    KM_ALGORITHM_AES = 32,
+
+    /* MAC algorithms */
+    KM_ALGORITHM_HMAC = 128,
+} keymaster_algorithm_t;
+
+/**
+ * Symmetric block cipher modes provided by keymaster implementations.
+ *
+ * KM_MODE_FIRST_UNAUTHENTICATED and KM_MODE_FIRST_AUTHENTICATED are not modes but markers used to
+ * separate the available modes into classes.
+ */
+typedef enum {
+    /* Unauthenticated modes, usable only for encryption/decryption and not generally recommended
+     * except for compatibility with existing other protocols. */
+    KM_MODE_FIRST_UNAUTHENTICATED = 1,
+    KM_MODE_ECB = KM_MODE_FIRST_UNAUTHENTICATED,
+    KM_MODE_CBC = 2,
+    KM_MODE_CTR = 4,
+
+    /* Authenticated modes, usable for encryption/decryption and signing/verification.  Recommended
+     * over unauthenticated modes for all purposes. */
+    KM_MODE_FIRST_AUTHENTICATED = 32,
+    KM_MODE_GCM = KM_MODE_FIRST_AUTHENTICATED,
+} keymaster_block_mode_t;
+
+/**
+ * Padding modes that may be applied to plaintext for encryption operations.  This list includes
+ * padding modes for both symmetric and asymmetric algorithms.  Note that implementations should not
+ * provide all possible combinations of algorithm and padding, only the
+ * cryptographically-appropriate pairs.
+ */
+typedef enum {
+    KM_PAD_NONE = 1, /* deprecated */
+    KM_PAD_RSA_OAEP = 2,
+    KM_PAD_RSA_PSS = 3,
+    KM_PAD_RSA_PKCS1_1_5_ENCRYPT = 4,
+    KM_PAD_RSA_PKCS1_1_5_SIGN = 5,
+    KM_PAD_PKCS7 = 64,
+} keymaster_padding_t;
+
+/**
+ * Digests provided by keymaster implementations.
+ */
+typedef enum {
+    KM_DIGEST_NONE = 0,
+    KM_DIGEST_MD5 = 1, /* Optional, may not be implemented in hardware, will be handled in software
+                        * if needed. */
+    KM_DIGEST_SHA1 = 2,
+    KM_DIGEST_SHA_2_224 = 3,
+    KM_DIGEST_SHA_2_256 = 4,
+    KM_DIGEST_SHA_2_384 = 5,
+    KM_DIGEST_SHA_2_512 = 6,
+} keymaster_digest_t;
+
+/**
+ * The origin of a key (or pair), i.e. where it was generated.  Note that KM_TAG_ORIGIN can be found
+ * in either the hardware-enforced or software-enforced list for a key, indicating whether the key
+ * is hardware or software-based.  Specifically, a key with KM_ORIGIN_GENERATED in the
+ * hardware-enforced list is guaranteed never to have existed outide the secure hardware.
+ */
+typedef enum {
+    KM_ORIGIN_GENERATED = 0, /* Generated in keymaster */
+    KM_ORIGIN_IMPORTED = 2,  /* Imported, origin unknown */
+    KM_ORIGIN_UNKNOWN = 3,   /* Keymaster did not record origin.  This value can only be seen on
+                              * keys in a keymaster0 implementation.  The keymaster0 adapter uses
+                              * this value to document the fact that it is unkown whether the key
+                              * was generated inside or imported into keymaster. */
+} keymaster_key_origin_t;
+
+/**
+ * Usability requirements of key blobs.  This defines what system functionality must be available
+ * for the key to function.  For example, key "blobs" which are actually handles referencing
+ * encrypted key material stored in the file system cannot be used until the file system is
+ * available, and should have BLOB_REQUIRES_FILE_SYSTEM.  Other requirements entries will be added
+ * as needed for implementations.  This type is new in 0_4.
+ */
+typedef enum {
+    KM_BLOB_STANDALONE = 0,
+    KM_BLOB_REQUIRES_FILE_SYSTEM = 1,
+} keymaster_key_blob_usage_requirements_t;
+
+/**
+ * Possible purposes of a key (or pair). This type is new in 0_4.
+ */
+typedef enum {
+    KM_PURPOSE_ENCRYPT = 0,
+    KM_PURPOSE_DECRYPT = 1,
+    KM_PURPOSE_SIGN = 2,
+    KM_PURPOSE_VERIFY = 3,
+} keymaster_purpose_t;
+
+typedef struct {
+    const uint8_t* data;
+    size_t data_length;
+} keymaster_blob_t;
+
+typedef struct {
+    keymaster_tag_t tag;
+    union {
+        uint32_t enumerated;   /* KM_ENUM and KM_ENUM_REP */
+        bool boolean;          /* KM_BOOL */
+        uint32_t integer;      /* KM_INT and KM_INT_REP */
+        uint64_t long_integer; /* KM_LONG */
+        uint64_t date_time;    /* KM_DATE */
+        keymaster_blob_t blob; /* KM_BIGNUM and KM_BYTES*/
+    };
+} keymaster_key_param_t;
+
+typedef struct {
+    keymaster_key_param_t* params; /* may be NULL if length == 0 */
+    size_t length;
+} keymaster_key_param_set_t;
+
+/**
+ * Parameters that define a key's characteristics, including authorized modes of usage and access
+ * control restrictions.  The parameters are divided into two categories, those that are enforced by
+ * secure hardware, and those that are not.  For a software-only keymaster implementation the
+ * enforced array must NULL.  Hardware implementations must enforce everything in the enforced
+ * array.
+ */
+typedef struct {
+    keymaster_key_param_set_t hw_enforced;
+    keymaster_key_param_set_t sw_enforced;
+} keymaster_key_characteristics_t;
+
+typedef struct {
+    const uint8_t* key_material;
+    size_t key_material_size;
+} keymaster_key_blob_t;
+
+/**
+ * Formats for key import and export.  At present, only asymmetric key import/export is supported.
+ * In the future this list will expand greatly to accommodate asymmetric key import/export.
+ */
+typedef enum {
+    KM_KEY_FORMAT_X509 = 0,   /* for public key export */
+    KM_KEY_FORMAT_PKCS8 = 1,  /* for asymmetric key pair import */
+    KM_KEY_FORMAT_RAW = 3,    /* for symmetric key import */
+} keymaster_key_format_t;
+
+/**
+ * The keymaster operation API consists of begin, update, finish and abort. This is the type of the
+ * handle used to tie the sequence of calls together.  A 64-bit value is used because it's important
+ * that handles not be predictable.  Implementations must use strong random numbers for handle
+ * values.
+ */
+typedef uint64_t keymaster_operation_handle_t;
+
+typedef enum {
+    KM_ERROR_OK = 0,
+    KM_ERROR_ROOT_OF_TRUST_ALREADY_SET = -1,
+    KM_ERROR_UNSUPPORTED_PURPOSE = -2,
+    KM_ERROR_INCOMPATIBLE_PURPOSE = -3,
+    KM_ERROR_UNSUPPORTED_ALGORITHM = -4,
+    KM_ERROR_INCOMPATIBLE_ALGORITHM = -5,
+    KM_ERROR_UNSUPPORTED_KEY_SIZE = -6,
+    KM_ERROR_UNSUPPORTED_BLOCK_MODE = -7,
+    KM_ERROR_INCOMPATIBLE_BLOCK_MODE = -8,
+    KM_ERROR_UNSUPPORTED_MAC_LENGTH = -9,
+    KM_ERROR_UNSUPPORTED_PADDING_MODE = -10,
+    KM_ERROR_INCOMPATIBLE_PADDING_MODE = -11,
+    KM_ERROR_UNSUPPORTED_DIGEST = -12,
+    KM_ERROR_INCOMPATIBLE_DIGEST = -13,
+    KM_ERROR_INVALID_EXPIRATION_TIME = -14,
+    KM_ERROR_INVALID_USER_ID = -15,
+    KM_ERROR_INVALID_AUTHORIZATION_TIMEOUT = -16,
+    KM_ERROR_UNSUPPORTED_KEY_FORMAT = -17,
+    KM_ERROR_INCOMPATIBLE_KEY_FORMAT = -18,
+    KM_ERROR_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM = -19,   /* For PKCS8 & PKCS12 */
+    KM_ERROR_UNSUPPORTED_KEY_VERIFICATION_ALGORITHM = -20, /* For PKCS8 & PKCS12 */
+    KM_ERROR_INVALID_INPUT_LENGTH = -21,
+    KM_ERROR_KEY_EXPORT_OPTIONS_INVALID = -22,
+    KM_ERROR_DELEGATION_NOT_ALLOWED = -23,
+    KM_ERROR_KEY_NOT_YET_VALID = -24,
+    KM_ERROR_KEY_EXPIRED = -25,
+    KM_ERROR_KEY_USER_NOT_AUTHENTICATED = -26,
+    KM_ERROR_OUTPUT_PARAMETER_NULL = -27,
+    KM_ERROR_INVALID_OPERATION_HANDLE = -28,
+    KM_ERROR_INSUFFICIENT_BUFFER_SPACE = -29,
+    KM_ERROR_VERIFICATION_FAILED = -30,
+    KM_ERROR_TOO_MANY_OPERATIONS = -31,
+    KM_ERROR_UNEXPECTED_NULL_POINTER = -32,
+    KM_ERROR_INVALID_KEY_BLOB = -33,
+    KM_ERROR_IMPORTED_KEY_NOT_ENCRYPTED = -34,
+    KM_ERROR_IMPORTED_KEY_DECRYPTION_FAILED = -35,
+    KM_ERROR_IMPORTED_KEY_NOT_SIGNED = -36,
+    KM_ERROR_IMPORTED_KEY_VERIFICATION_FAILED = -37,
+    KM_ERROR_INVALID_ARGUMENT = -38,
+    KM_ERROR_UNSUPPORTED_TAG = -39,
+    KM_ERROR_INVALID_TAG = -40,
+    KM_ERROR_MEMORY_ALLOCATION_FAILED = -41,
+    KM_ERROR_INVALID_RESCOPING = -42,
+    KM_ERROR_IMPORT_PARAMETER_MISMATCH = -44,
+    KM_ERROR_SECURE_HW_ACCESS_DENIED = -45,
+    KM_ERROR_OPERATION_CANCELLED = -46,
+    KM_ERROR_CONCURRENT_ACCESS_CONFLICT = -47,
+    KM_ERROR_SECURE_HW_BUSY = -48,
+    KM_ERROR_SECURE_HW_COMMUNICATION_FAILED = -49,
+    KM_ERROR_UNSUPPORTED_EC_FIELD = -50,
+    KM_ERROR_MISSING_NONCE = -51,
+    KM_ERROR_INVALID_NONCE = -52,
+    KM_ERROR_UNSUPPORTED_CHUNK_LENGTH = -53,
+    KM_ERROR_RESCOPABLE_KEY_NOT_USABLE = -54,
+
+    KM_ERROR_UNIMPLEMENTED = -100,
+    KM_ERROR_VERSION_MISMATCH = -101,
+
+    /* Additional error codes may be added by implementations, but implementers should coordinate
+     * with Google to avoid code collision. */
+    KM_ERROR_UNKNOWN_ERROR = -1000,
+} keymaster_error_t;
+
+/* Convenience functions for manipulating keymaster tag types */
+
+static inline keymaster_tag_type_t keymaster_tag_get_type(keymaster_tag_t tag) {
+    return (keymaster_tag_type_t)(tag & (0xF << 28));
+}
+
+static inline uint32_t keymaster_tag_mask_type(keymaster_tag_t tag) {
+    return tag & 0x0FFFFFFF;
+}
+
+static inline bool keymaster_tag_type_repeatable(keymaster_tag_type_t type) {
+    switch (type) {
+    case KM_INT_REP:
+    case KM_ENUM_REP:
+        return true;
+    default:
+        return false;
+    }
+}
+
+static inline bool keymaster_tag_repeatable(keymaster_tag_t tag) {
+    return keymaster_tag_type_repeatable(keymaster_tag_get_type(tag));
+}
+
+/* Convenience functions for manipulating keymaster_key_param_t structs */
+
+inline keymaster_key_param_t keymaster_param_enum(keymaster_tag_t tag, uint32_t value) {
+    // assert(keymaster_tag_get_type(tag) == KM_ENUM || keymaster_tag_get_type(tag) == KM_ENUM_REP);
+    keymaster_key_param_t param;
+    memset(&param, 0, sizeof(param));
+    param.tag = tag;
+    param.enumerated = value;
+    return param;
+}
+
+inline keymaster_key_param_t keymaster_param_int(keymaster_tag_t tag, uint32_t value) {
+    // assert(keymaster_tag_get_type(tag) == KM_INT || keymaster_tag_get_type(tag) == KM_INT_REP);
+    keymaster_key_param_t param;
+    memset(&param, 0, sizeof(param));
+    param.tag = tag;
+    param.integer = value;
+    return param;
+}
+
+inline keymaster_key_param_t keymaster_param_long(keymaster_tag_t tag, uint64_t value) {
+    // assert(keymaster_tag_get_type(tag) == KM_LONG);
+    keymaster_key_param_t param;
+    memset(&param, 0, sizeof(param));
+    param.tag = tag;
+    param.long_integer = value;
+    return param;
+}
+
+inline keymaster_key_param_t keymaster_param_blob(keymaster_tag_t tag, const uint8_t* bytes,
+                                                  size_t bytes_len) {
+    // assert(keymaster_tag_get_type(tag) == KM_BYTES || keymaster_tag_get_type(tag) == KM_BIGNUM);
+    keymaster_key_param_t param;
+    memset(&param, 0, sizeof(param));
+    param.tag = tag;
+    param.blob.data = (uint8_t*)bytes;
+    param.blob.data_length = bytes_len;
+    return param;
+}
+
+inline keymaster_key_param_t keymaster_param_bool(keymaster_tag_t tag) {
+    // assert(keymaster_tag_get_type(tag) == KM_BOOL);
+    keymaster_key_param_t param;
+    memset(&param, 0, sizeof(param));
+    param.tag = tag;
+    param.boolean = true;
+    return param;
+}
+
+inline keymaster_key_param_t keymaster_param_date(keymaster_tag_t tag, uint64_t value) {
+    // assert(keymaster_tag_get_type(tag) == KM_DATE);
+    keymaster_key_param_t param;
+    memset(&param, 0, sizeof(param));
+    param.tag = tag;
+    param.date_time = value;
+    return param;
+}
+
+#define KEYMASTER_SIMPLE_COMPARE(a, b) (a < b) ? -1 : ((a > b) ? 1 : 0)
+inline int keymaster_param_compare(const keymaster_key_param_t* a, const keymaster_key_param_t* b) {
+    int retval = KEYMASTER_SIMPLE_COMPARE(a->tag, b->tag);
+    if (retval != 0)
+        return retval;
+
+    switch (keymaster_tag_get_type(a->tag)) {
+    case KM_INVALID:
+    case KM_BOOL:
+        return 0;
+    case KM_ENUM:
+    case KM_ENUM_REP:
+        return KEYMASTER_SIMPLE_COMPARE(a->enumerated, b->enumerated);
+    case KM_INT:
+    case KM_INT_REP:
+        return KEYMASTER_SIMPLE_COMPARE(a->integer, b->integer);
+    case KM_LONG:
+    case KM_LONG_REP:
+        return KEYMASTER_SIMPLE_COMPARE(a->long_integer, b->long_integer);
+    case KM_DATE:
+        return KEYMASTER_SIMPLE_COMPARE(a->date_time, b->date_time);
+    case KM_BIGNUM:
+    case KM_BYTES:
+        // Handle the empty cases.
+        if (a->blob.data_length != 0 && b->blob.data_length == 0)
+            return -1;
+        if (a->blob.data_length == 0 && b->blob.data_length == 0)
+            return 0;
+        if (a->blob.data_length == 0 && b->blob.data_length > 0)
+            return 1;
+
+        retval = memcmp(a->blob.data, b->blob.data, a->blob.data_length < b->blob.data_length
+                                                        ? a->blob.data_length
+                                                        : b->blob.data_length);
+        if (retval != 0)
+            return retval;
+        else if (a->blob.data_length != b->blob.data_length) {
+            // Equal up to the common length; longer one is larger.
+            if (a->blob.data_length < b->blob.data_length)
+                return -1;
+            if (a->blob.data_length > b->blob.data_length)
+                return 1;
+        };
+    }
+
+    return 0;
+}
+#undef KEYMASTER_SIMPLE_COMPARE
+
+inline void keymaster_free_param_values(keymaster_key_param_t* param, size_t param_count) {
+    while (param_count-- > 0) {
+        switch (keymaster_tag_get_type(param->tag)) {
+        case KM_BIGNUM:
+        case KM_BYTES:
+            free((void*)param->blob.data);
+            param->blob.data = NULL;
+            break;
+        default:
+            // NOP
+            break;
+        }
+        ++param;
+    }
+}
+
+inline void keymaster_free_param_set(keymaster_key_param_set_t* set) {
+    if (set) {
+        keymaster_free_param_values(set->params, set->length);
+        free(set->params);
+        set->params = NULL;
+    }
+}
+
+inline void keymaster_free_characteristics(keymaster_key_characteristics_t* characteristics) {
+    if (characteristics) {
+        keymaster_free_param_set(&characteristics->hw_enforced);
+        keymaster_free_param_set(&characteristics->sw_enforced);
+    }
+}
+
+#ifndef __cplusplus
+}  // extern "C"
+#endif  // __cplusplus
+
+#endif  // ANDROID_HARDWARE_KEYMASTER_DEFS_H
diff --git a/include/hardware/qemu_pipe.h b/include/hardware/qemu_pipe.h
index 814b20b..53aec97 100644
--- a/include/hardware/qemu_pipe.h
+++ b/include/hardware/qemu_pipe.h
@@ -23,6 +23,7 @@
 #include <pthread.h>  /* for pthread_once() */
 #include <stdlib.h>
 #include <stdio.h>
+#include <string.h>
 #include <errno.h>
 
 #ifndef D
diff --git a/include/hardware/sensors.h b/include/hardware/sensors.h
index f0773d5..e917c0a 100644
--- a/include/hardware/sensors.h
+++ b/include/hardware/sensors.h
@@ -602,6 +602,22 @@
 #define SENSOR_TYPE_PICK_UP_GESTURE                            (25)
 #define SENSOR_STRING_TYPE_PICK_UP_GESTURE                     "android.sensor.pick_up_gesture"
 
+/*
+ * SENSOR_TYPE_WRIST_TILT_GESTURE
+ * trigger-mode: special
+ * wake-up sensor: yes
+ *
+ * A sensor of this type triggers an event each time a tilt of the wrist-worn
+ * device is detected.
+ *
+ * This sensor must be low power, as it is likely to be activated 24/7.
+ * The only allowed value to return is 1.0.
+ *
+ * Implement only the wake-up version of this sensor.
+ */
+#define SENSOR_TYPE_WRIST_TILT_GESTURE                         (26)
+#define SENSOR_STRING_TYPE_WRIST_TILT_GESTURE                  "android.sensor.wrist_tilt_gesture"
+
 /**
  * Values returned by the accelerometer in various locations in the universe.
  * all values are in SI units (m/s^2)
diff --git a/modules/audio/audio_hw.c b/modules/audio/audio_hw.c
index 18c0e59..637e3f4 100644
--- a/modules/audio/audio_hw.c
+++ b/modules/audio/audio_hw.c
@@ -18,6 +18,7 @@
 //#define LOG_NDEBUG 0
 
 #include <errno.h>
+#include <malloc.h>
 #include <pthread.h>
 #include <stdint.h>
 #include <sys/time.h>
diff --git a/modules/camera/Stream.cpp b/modules/camera/Stream.cpp
index 2db3ed2..90ad30b 100644
--- a/modules/camera/Stream.cpp
+++ b/modules/camera/Stream.cpp
@@ -227,15 +227,15 @@
 
     dprintf(fd, "Stream ID: %d (%p)\n", mId, mStream);
     dprintf(fd, "Stream Type: %s (%d)\n", typeToString(mType), mType);
-    dprintf(fd, "Width: %"PRIu32" Height: %"PRIu32"\n", mWidth, mHeight);
+    dprintf(fd, "Width: %" PRIu32 " Height: %" PRIu32 "\n", mWidth, mHeight);
     dprintf(fd, "Stream Format: %s (%d)", formatToString(mFormat), mFormat);
     // ToDo: prettyprint usage mask flags
-    dprintf(fd, "Gralloc Usage Mask: %#"PRIx32"\n", mUsage);
-    dprintf(fd, "Max Buffer Count: %"PRIu32"\n", mMaxBuffers);
+    dprintf(fd, "Gralloc Usage Mask: %#" PRIx32 "\n", mUsage);
+    dprintf(fd, "Max Buffer Count: %" PRIu32 "\n", mMaxBuffers);
     dprintf(fd, "Buffers Registered: %s\n", mRegistered ? "true" : "false");
-    dprintf(fd, "Number of Buffers: %"PRIu32"\n", mNumBuffers);
+    dprintf(fd, "Number of Buffers: %" PRIu32 "\n", mNumBuffers);
     for (uint32_t i = 0; i < mNumBuffers; i++) {
-        dprintf(fd, "Buffer %"PRIu32"/%"PRIu32": %p\n", i, mNumBuffers,
+        dprintf(fd, "Buffer %" PRIu32 "/%" PRIu32 ": %p\n", i, mNumBuffers,
                 mBuffers[i]);
     }
 }
diff --git a/modules/consumerir/consumerir.c b/modules/consumerir/consumerir.c
index 87039cc..f3eac0b 100644
--- a/modules/consumerir/consumerir.c
+++ b/modules/consumerir/consumerir.c
@@ -16,6 +16,7 @@
 #define LOG_TAG "ConsumerIrHal"
 
 #include <errno.h>
+#include <malloc.h>
 #include <string.h>
 #include <cutils/log.h>
 #include <hardware/hardware.h>
diff --git a/modules/fingerprint/fingerprint.c b/modules/fingerprint/fingerprint.c
index 14dac12..0346518 100644
--- a/modules/fingerprint/fingerprint.c
+++ b/modules/fingerprint/fingerprint.c
@@ -16,6 +16,7 @@
 #define LOG_TAG "FingerprintHal"
 
 #include <errno.h>
+#include <malloc.h>
 #include <string.h>
 #include <cutils/log.h>
 #include <hardware/hardware.h>
diff --git a/modules/gralloc/mapper.cpp b/modules/gralloc/mapper.cpp
index 5a882e2..20d9841 100644
--- a/modules/gralloc/mapper.cpp
+++ b/modules/gralloc/mapper.cpp
@@ -33,14 +33,6 @@
 #include "gralloc_priv.h"
 
 
-/* desktop Linux needs a little help with gettid() */
-#if defined(ARCH_X86) && !defined(HAVE_ANDROID_OS)
-#define __KERNEL__
-# include <linux/unistd.h>
-pid_t gettid() { return syscall(__NR_gettid);}
-#undef __KERNEL__
-#endif
-
 /*****************************************************************************/
 
 static int gralloc_map(gralloc_module_t const* /*module*/,
diff --git a/modules/hwcomposer/hwcomposer.cpp b/modules/hwcomposer/hwcomposer.cpp
index f0a5512..9d1aa34 100644
--- a/modules/hwcomposer/hwcomposer.cpp
+++ b/modules/hwcomposer/hwcomposer.cpp
@@ -16,8 +16,9 @@
 
 #include <hardware/hardware.h>
 
-#include <fcntl.h>
 #include <errno.h>
+#include <fcntl.h>
+#include <malloc.h>
 
 #include <cutils/log.h>
 #include <cutils/atomic.h>
diff --git a/modules/local_time/local_time_hw.c b/modules/local_time/local_time_hw.c
index 308f7d9..ac597f4 100644
--- a/modules/local_time/local_time_hw.c
+++ b/modules/local_time/local_time_hw.c
@@ -18,9 +18,10 @@
 //#define LOG_NDEBUG 0
 
 #include <errno.h>
+#include <malloc.h>
 #include <stdint.h>
+#include <string.h>
 #include <sys/time.h>
-#include <linux/time.h>
 
 #include <cutils/log.h>
 
diff --git a/modules/nfc-nci/nfc_nci_example.c b/modules/nfc-nci/nfc_nci_example.c
index 2514225..758c2b7 100644
--- a/modules/nfc-nci/nfc_nci_example.c
+++ b/modules/nfc-nci/nfc_nci_example.c
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 #include <errno.h>
+#include <malloc.h>
 #include <string.h>
 
 #include <cutils/log.h>
diff --git a/modules/nfc/nfc_pn544_example.c b/modules/nfc/nfc_pn544_example.c
index 54c9c56..71bfd6b 100644
--- a/modules/nfc/nfc_pn544_example.c
+++ b/modules/nfc/nfc_pn544_example.c
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 #include <errno.h>
+#include <malloc.h>
 #include <string.h>
 
 #include <hardware/hardware.h>
diff --git a/modules/sensors/Android.mk b/modules/sensors/Android.mk
index 65f699b..445f69e 100644
--- a/modules/sensors/Android.mk
+++ b/modules/sensors/Android.mk
@@ -35,16 +35,10 @@
     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
diff --git a/modules/tv_input/tv_input.cpp b/modules/tv_input/tv_input.cpp
index bc02786..114e80e 100644
--- a/modules/tv_input/tv_input.cpp
+++ b/modules/tv_input/tv_input.cpp
@@ -14,8 +14,9 @@
  * limitations under the License.
  */
 
-#include <fcntl.h>
 #include <errno.h>
+#include <fcntl.h>
+#include <malloc.h>
 
 #include <cutils/log.h>
 #include <cutils/native_handle.h>
diff --git a/modules/usbaudio/alsa_device_proxy.c b/modules/usbaudio/alsa_device_proxy.c
index 081c05b..676f288 100644
--- a/modules/usbaudio/alsa_device_proxy.c
+++ b/modules/usbaudio/alsa_device_proxy.c
@@ -20,6 +20,8 @@
 
 #include <log/log.h>
 
+#include <errno.h>
+
 #include "alsa_device_proxy.h"
 
 #include "logging.h"
diff --git a/modules/usbaudio/audio_hw.c b/modules/usbaudio/audio_hw.c
index 49c99af..ad01833 100644
--- a/modules/usbaudio/audio_hw.c
+++ b/modules/usbaudio/audio_hw.c
@@ -844,6 +844,8 @@
                 num_read_buff_bytes =
                     convert_32_to_16(read_buff, num_read_buff_bytes / 4, out_buff);
             } else {
+                LOG_ALWAYS_FATAL("Unsupported format");
+                num_read_buff_bytes = 0;
                 goto err;
             }
         }
@@ -867,8 +869,8 @@
         /* no need to acquire in->dev->lock to read mic_muted here as we don't change its state */
         if (num_read_buff_bytes > 0 && in->dev->mic_muted)
             memset(buffer, 0, num_read_buff_bytes);
-    } else if (ret == -ENODEV) {
-            num_read_buff_bytes = 0; //reset the  value after USB headset is unplugged
+    } else {
+        num_read_buff_bytes = 0; // reset the value after USB headset is unplugged
     }
 
 err:
diff --git a/modules/vibrator/vibrator.c b/modules/vibrator/vibrator.c
index ce4c03c..6b3ce57 100644
--- a/modules/vibrator/vibrator.c
+++ b/modules/vibrator/vibrator.c
@@ -19,6 +19,7 @@
 
 #include <cutils/log.h>
 
+#include <malloc.h>
 #include <stdio.h>
 #include <unistd.h>
 #include <fcntl.h>
diff --git a/tests/camera2/Android.mk b/tests/camera2/Android.mk
index 577ba0a..1128522 100644
--- a/tests/camera2/Android.mk
+++ b/tests/camera2/Android.mk
@@ -19,7 +19,6 @@
 	liblog \
 	libutils \
 	libcutils \
-	libstlport \
 	libhardware \
 	libcamera_metadata \
 	libcameraservice \
@@ -29,21 +28,13 @@
 	libui \
 	libdl
 
-LOCAL_STATIC_LIBRARIES := \
-	libgtest
-
 LOCAL_C_INCLUDES += \
-	bionic \
-	bionic/libstdc++/include \
-	external/gtest/include \
-	external/stlport/stlport \
 	system/media/camera/include \
 	frameworks/av/include/ \
 	frameworks/av/services/camera/libcameraservice \
 	frameworks/native/include \
 
 LOCAL_CFLAGS += -Wall -Wextra
-
 LOCAL_MODULE:= camera2_test
 LOCAL_MODULE_STEM_32 := camera2_test
 LOCAL_MODULE_STEM_64 := camera2_test64
diff --git a/tests/camera2/CameraBurstTests.cpp b/tests/camera2/CameraBurstTests.cpp
index 8dcc2a2..198c0c1 100644
--- a/tests/camera2/CameraBurstTests.cpp
+++ b/tests/camera2/CameraBurstTests.cpp
@@ -49,7 +49,7 @@
 #define dout if (0) std::cout
 #endif
 
-#define WARN_UNLESS(condition) (!(condition) ? (std::cerr) : (std::ostream(NULL)) << "Warning: ")
+#define WARN_UNLESS(condition) if(!(condition)) std::cerr << "Warning: "
 #define WARN_LE(exp, act) WARN_UNLESS((exp) <= (act))
 #define WARN_LT(exp, act) WARN_UNLESS((exp) < (act))
 #define WARN_GT(exp, act) WARN_UNLESS((exp) > (act))
@@ -219,7 +219,7 @@
         CameraMetadata tmpRequest = previewRequest;
         ASSERT_EQ(OK, tmpRequest.update(ANDROID_SENSOR_EXPOSURE_TIME,
                                         &exposures[i], 1));
-        ALOGV("Submitting capture request %d with exposure %"PRId64, i,
+        ALOGV("Submitting capture request %d with exposure %" PRId64, i,
             exposures[i]);
         dout << "Capture request " << i << " exposure is "
              << (exposures[i]/1e6f) << std::endl;
@@ -231,7 +231,7 @@
     float brightnesses[CAMERA_FRAME_BURST_COUNT];
     // Get each frame (metadata) and then the buffer. Calculate brightness.
     for (int i = 0; i < CAMERA_FRAME_BURST_COUNT; ++i) {
-        ALOGV("Reading capture request %d with exposure %"PRId64, i, exposures[i]);
+        ALOGV("Reading capture request %d with exposure %" PRId64, i, exposures[i]);
         ASSERT_EQ(OK, mDevice->waitForNextFrame(CAMERA_FRAME_TIMEOUT));
         ALOGV("Reading capture request-1 %d", i);
         CaptureResult result;
@@ -618,7 +618,7 @@
                                         &durationList[i], 1));
         ASSERT_EQ(OK, tmpRequest.update(ANDROID_SENSOR_SENSITIVITY,
                                         &sensitivityList[i], 1));
-        ALOGV("Submitting capture %zu with exposure %"PRId64", frame duration %"PRId64", sensitivity %d",
+        ALOGV("Submitting capture %zu with exposure %" PRId64 ", frame duration %" PRId64 ", sensitivity %d",
                 i, expList[i], durationList[i], sensitivityList[i]);
         dout << "Capture request " << i <<
                 ": exposure is " << (expList[i]/1e6f) << " ms" <<
diff --git a/tests/camera2/CameraMultiStreamTests.cpp b/tests/camera2/CameraMultiStreamTests.cpp
index b92d8cc..df8e623 100644
--- a/tests/camera2/CameraMultiStreamTests.cpp
+++ b/tests/camera2/CameraMultiStreamTests.cpp
@@ -356,7 +356,7 @@
             ASSERT_EQ(OK, request.update(ANDROID_SENSOR_EXPOSURE_TIME, &exposures[i], 1));
             ASSERT_EQ(OK, request.update(ANDROID_SENSOR_SENSITIVITY, &sensitivities[i], 1));
             ASSERT_EQ(OK, mDevice->capture(request));
-            ALOGV("Submitting request with: id %d with exposure %"PRId64", sensitivity %d",
+            ALOGV("Submitting request with: id %d with exposure %" PRId64 ", sensitivity %d",
                     *requestIdStart, exposures[i], sensitivities[i]);
             if (CAMERA_MULTI_STREAM_DEBUGGING) {
                 request.dump(STDOUT_FILENO);
@@ -554,7 +554,7 @@
         minFrameDuration = DEFAULT_FRAME_DURATION;
     }
 
-    ALOGV("targeted minimal frame duration is: %"PRId64"ns", minFrameDuration);
+    ALOGV("targeted minimal frame duration is: %" PRId64 "ns", minFrameDuration);
 
     GetMaxSize(jpegData, jpegCount, &jpegMaxSize, &maxIdx);
     ALOGV("Found Jpeg size max idx = %d", maxIdx);
@@ -672,7 +672,7 @@
         ASSERT_EQ(OK, previewRequest.update(
                 ANDROID_SENSOR_EXPOSURE_TIME,
                 &exposures[i], 1));
-        ALOGV("Submitting preview request %zu with exposure %"PRId64,
+        ALOGV("Submitting preview request %zu with exposure %" PRId64,
                 i, exposures[i]);
 
         ASSERT_EQ(OK, mDevice->setStreamingRequest(previewRequest));
diff --git a/tests/keymaster/Android.mk b/tests/keymaster/Android.mk
index e53e67f..0c11795 100644
--- a/tests/keymaster/Android.mk
+++ b/tests/keymaster/Android.mk
@@ -6,26 +6,14 @@
 LOCAL_SRC_FILES:= \
     keymaster_test.cpp
 
-# Note that "bionic" is needed because of stlport
-LOCAL_C_INCLUDES := \
-    bionic \
-    external/gtest/include \
-    external/openssl/include \
-    external/stlport/stlport
-
 LOCAL_SHARED_LIBRARIES := \
     liblog \
     libutils \
     libcrypto \
-    libstlport \
-    libhardware
-
-LOCAL_STATIC_LIBRARIES := \
-    libgtest \
-    libgtest_main
+    libhardware \
 
 LOCAL_MODULE := keymaster_test
 
 LOCAL_MODULE_TAGS := tests
 
-include $(BUILD_EXECUTABLE)
+include $(BUILD_NATIVE_TEST)
diff --git a/tests/keymaster/keymaster_test.cpp b/tests/keymaster/keymaster_test.cpp
index 6b76ccb..e5e1dfd 100644
--- a/tests/keymaster/keymaster_test.cpp
+++ b/tests/keymaster/keymaster_test.cpp
@@ -35,7 +35,7 @@
 
 #include <UniquePtr.h>
 
-#include <hardware/keymaster.h>
+#include <hardware/keymaster0.h>
 
 namespace android {
 
@@ -92,13 +92,13 @@
 
 class UniqueKey : public UniqueBlob {
 public:
-    UniqueKey(keymaster_device_t** dev, uint8_t* bytes, size_t length) :
+    UniqueKey(keymaster0_device_t** dev, uint8_t* bytes, size_t length) :
             UniqueBlob(bytes, length), mDevice(dev) {
     }
 
     ~UniqueKey() {
         if (mDevice != NULL && *mDevice != NULL) {
-            keymaster_device_t* dev = *mDevice;
+            keymaster0_device_t* dev = *mDevice;
             if (dev->delete_keypair != NULL) {
                 dev->delete_keypair(dev, get(), length());
             }
@@ -106,7 +106,7 @@
     }
 
 private:
-    keymaster_device_t** mDevice;
+    keymaster0_device_t** mDevice;
 };
 
 class UniqueReadOnlyBlob {
@@ -341,7 +341,7 @@
 
         std::cout << "Using keymaster module: " << mod->name << std::endl;
 
-        ASSERT_EQ(0, keymaster_open(mod, &sDevice))
+        ASSERT_EQ(0, keymaster0_open(mod, &sDevice))
                 << "Should be able to open the keymaster device";
 
         ASSERT_EQ(KEYMASTER_MODULE_API_VERSION_0_2, mod->module_api_version)
@@ -364,14 +364,14 @@
     }
 
     static void TearDownTestCase() {
-        ASSERT_EQ(0, keymaster_close(sDevice));
+        ASSERT_EQ(0, keymaster0_close(sDevice));
     }
 
 protected:
-    static keymaster_device_t* sDevice;
+    static keymaster0_device_t* sDevice;
 };
 
-keymaster_device_t* KeymasterBaseTest::sDevice = NULL;
+keymaster0_device_t* KeymasterBaseTest::sDevice = NULL;
 
 class KeymasterTest : public KeymasterBaseTest {
 };