Merge commit '801439d8aafef69d027ec417919d128a58e1c42f' into HEAD
diff --git a/include/hardware/bluetooth.h b/include/hardware/bluetooth.h
index 683e369..7772b38 100644
--- a/include/hardware/bluetooth.h
+++ b/include/hardware/bluetooth.h
@@ -107,6 +107,12 @@
     uint64_t energy_used;   /* a product of mA, V and ms */
 } __attribute__((packed))bt_activity_energy_info;
 
+typedef struct {
+    int32_t app_uid;
+    uint64_t tx_bytes;
+    uint64_t rx_bytes;
+} __attribute__((packed))bt_uid_traffic_t;
+
 /** Bluetooth Adapter Discovery state */
 typedef enum {
     BT_DISCOVERY_STOPPED,
@@ -378,8 +384,12 @@
  * If the ctrl_state value is 0, it means the API call failed
  * Time values-In milliseconds as returned by the controller
  * Energy used-Value as returned by the controller
- * Status-Provides the status of the read_energy_info API call */
-typedef void (*energy_info_callback)(bt_activity_energy_info *energy_info);
+ * Status-Provides the status of the read_energy_info API call
+ * uid_data provides an array of bt_uid_traffic_t, where the array is terminated by an element with
+ * app_uid set to -1.
+ */
+typedef void (*energy_info_callback)(bt_activity_energy_info *energy_info,
+                                     bt_uid_traffic_t *uid_data);
 
 /** TODO: Add callbacks for Link Up/Down and other generic
   *  notifications/callbacks */
@@ -557,14 +567,27 @@
     /**
      * Native support for dumpsys function
      * Function is synchronous and |fd| is owned by caller.
+     * |arguments| are arguments which may affect the output, encoded as
+     * UTF-8 strings.
      */
-    void (*dump)(int fd);
+    void (*dump)(int fd, const char **arguments);
 
     /**
      * Clear /data/misc/bt_config.conf and erase all stored connections
      */
     int (*config_clear)(void);
 
+    /**
+     * Clear (reset) the dynamic portion of the device interoperability database.
+     */
+    void (*interop_database_clear)(void);
+
+    /**
+     * Add a new device interoperability workaround for a remote device whose
+     * first |len| bytes of the its device address match |addr|.
+     * NOTE: |feature| has to match an item defined in interop_feature_t (interop.h).
+     */
+    void (*interop_database_add)(uint16_t feature, const bt_bdaddr_t *addr, size_t len);
 } bt_interface_t;
 
 /** TODO: Need to add APIs for Service Discovery, Service authorization and
diff --git a/include/hardware/bt_av.h b/include/hardware/bt_av.h
index 5252a17..5f7601e 100644
--- a/include/hardware/bt_av.h
+++ b/include/hardware/bt_av.h
@@ -38,13 +38,13 @@
 /** Callback for connection state change.
  *  state will have one of the values from btav_connection_state_t
  */
-typedef void (* btav_connection_state_callback)(btav_connection_state_t state, 
+typedef void (* btav_connection_state_callback)(btav_connection_state_t state,
                                                     bt_bdaddr_t *bd_addr);
 
 /** Callback for audiopath state change.
  *  state will have one of the values from btav_audio_state_t
  */
-typedef void (* btav_audio_state_callback)(btav_audio_state_t state, 
+typedef void (* btav_audio_state_callback)(btav_audio_state_t state,
                                                bt_bdaddr_t *bd_addr);
 
 /** Callback for audio configuration change.
@@ -57,6 +57,13 @@
                                                 uint32_t sample_rate,
                                                 uint8_t channel_count);
 
+/*
+ * Callback for audio focus request to be used only in
+ * case of A2DP Sink. This is required because we are using
+ * AudioTrack approach for audio data rendering.
+ */
+typedef void (* btav_audio_focus_request_callback)(bt_bdaddr_t *bd_addr);
+
 /** BT-AV callback structure. */
 typedef struct {
     /** set to sizeof(btav_callbacks_t) */
@@ -64,17 +71,18 @@
     btav_connection_state_callback  connection_state_cb;
     btav_audio_state_callback audio_state_cb;
     btav_audio_config_callback audio_config_cb;
+    btav_audio_focus_request_callback audio_focus_request_cb;
 } btav_callbacks_t;
 
-/** 
+/**
  * NOTE:
  *
  * 1. AVRCP 1.0 shall be supported initially. AVRCP passthrough commands
- *    shall be handled internally via uinput 
+ *    shall be handled internally via uinput
  *
  * 2. A2DP data path shall be handled via a socket pipe between the AudioFlinger
  *    android_audio_hw library and the Bluetooth stack.
- * 
+ *
  */
 /** Represents the standard BT-AV interface.
  *  Used for both the A2DP source and sink interfaces.
@@ -96,6 +104,9 @@
 
     /** Closes the interface. */
     void  (*cleanup)( void );
+
+    /** Sends Audio Focus State. */
+    void  (*audio_focus_state)( int focus_state );
 } btav_interface_t;
 
 __END_DECLS
diff --git a/include/hardware/bt_common_types.h b/include/hardware/bt_common_types.h
index e30ac24..77c845b 100644
--- a/include/hardware/bt_common_types.h
+++ b/include/hardware/bt_common_types.h
@@ -41,4 +41,35 @@
     uint8_t  *p_scan_rsp_data;
 } btgatt_track_adv_info_t;
 
+typedef enum
+{
+    BTGATT_DB_PRIMARY_SERVICE,
+    BTGATT_DB_SECONDARY_SERVICE,
+    BTGATT_DB_INCLUDED_SERVICE,
+    BTGATT_DB_CHARACTERISTIC,
+    BTGATT_DB_DESCRIPTOR,
+} bt_gatt_db_attribute_type_t;
+
+typedef struct
+{
+    uint8_t             id;
+    bt_uuid_t           uuid;
+    bt_gatt_db_attribute_type_t type;
+    uint16_t            attribute_handle;
+
+    /*
+     * If |type| is |BTGATT_DB_PRIMARY_SERVICE|, or
+     * |BTGATT_DB_SECONDARY_SERVICE|, this contains the start and end attribute
+     * handles.
+     */
+    uint16_t            start_handle;
+    uint16_t            end_handle;
+
+    /*
+     * If |type| is |BTGATT_DB_CHARACTERISTIC|, this contains the properties of
+     * the characteristic.
+     */
+    uint8_t             properties;
+} btgatt_db_element_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 e7e8e82..3462f51 100644
--- a/include/hardware/bt_gatt_client.h
+++ b/include/hardware/bt_gatt_client.h
@@ -245,6 +245,15 @@
 typedef void (*scan_parameter_setup_completed_callback)(int client_if,
                                                         btgattc_error_t status);
 
+/** GATT get database callback */
+typedef void (*get_gatt_db_callback)(int conn_id, btgatt_db_element_t *db, int count);
+
+/** GATT services between start_handle and end_handle were removed */
+typedef void (*services_removed_callback)(int conn_id, uint16_t start_handle, uint16_t end_handle);
+
+/** GATT services were added */
+typedef void (*services_added_callback)(int conn_id, btgatt_db_element_t *added, int added_count);
+
 typedef struct {
     register_client_callback            register_client_cb;
     scan_result_callback                scan_result_cb;
@@ -279,6 +288,9 @@
     batchscan_threshold_callback        batchscan_threshold_cb;
     track_adv_event_callback            track_adv_event_cb;
     scan_parameter_setup_completed_callback scan_parameter_setup_completed_cb;
+    get_gatt_db_callback                get_gatt_db_cb;
+    services_removed_callback           services_removed_cb;
+    services_added_callback             services_added_cb;
 } btgatt_client_callbacks_t;
 
 /** Represents the standard BT-GATT client interface. */
@@ -448,6 +460,9 @@
     /** Test mode interface */
     bt_status_t (*test_command)( int command, btgatt_test_params_t* params);
 
+    /** Get gatt db content */
+    bt_status_t (*get_gatt_db)( int conn_id);
+
 } btgatt_client_interface_t;
 
 __END_DECLS
diff --git a/include/hardware/bt_rc.h b/include/hardware/bt_rc.h
index c565c48..1e2c293 100644
--- a/include/hardware/bt_rc.h
+++ b/include/hardware/bt_rc.h
@@ -103,6 +103,36 @@
     uint8_t attr_values[BTRC_MAX_APP_SETTINGS];
 } btrc_player_settings_t;
 
+typedef struct {
+    uint8_t   val;
+    uint16_t  charset_id;
+    uint16_t  str_len;
+    uint8_t   *p_str;
+} btrc_player_app_ext_attr_val_t;
+
+typedef struct {
+    uint8_t   attr_id;
+    uint16_t  charset_id;
+    uint16_t  str_len;
+    uint8_t   *p_str;
+    uint8_t   num_val;
+    btrc_player_app_ext_attr_val_t ext_attr_val[BTRC_MAX_APP_ATTR_SIZE];
+} btrc_player_app_ext_attr_t;
+
+typedef struct {
+    uint8_t attr_id;
+    uint8_t num_val;
+    uint8_t attr_val[BTRC_MAX_APP_ATTR_SIZE];
+} btrc_player_app_attr_t;
+
+typedef struct {
+    uint32_t start_item;
+    uint32_t end_item;
+    uint32_t size;
+    uint32_t attrs[BTRC_MAX_ELEM_ATTR_SIZE];
+    uint8_t  attr_count;
+} btrc_getfolderitem_t;
+
 typedef union
 {
     btrc_play_status_t play_status;
@@ -264,14 +294,53 @@
 
 typedef void (* btrc_passthrough_rsp_callback) (int id, int key_state);
 
+typedef void (* btrc_groupnavigation_rsp_callback) (int id, int key_state);
+
 typedef void (* btrc_connection_state_callback) (bool state, bt_bdaddr_t *bd_addr);
 
+typedef void (* btrc_ctrl_getrcfeatures_callback) (bt_bdaddr_t *bd_addr, int features);
+
+typedef void (* btrc_ctrl_setabsvol_cmd_callback) (bt_bdaddr_t *bd_addr, uint8_t abs_vol, uint8_t label);
+
+typedef void (* btrc_ctrl_registernotification_abs_vol_callback) (bt_bdaddr_t *bd_addr, uint8_t label);
+
+typedef void (* btrc_ctrl_setplayerapplicationsetting_rsp_callback) (bt_bdaddr_t *bd_addr,
+                                                                          uint8_t accepted);
+
+typedef void (* btrc_ctrl_playerapplicationsetting_callback)(bt_bdaddr_t *bd_addr,
+                                                                 uint8_t num_attr,
+                                                                 btrc_player_app_attr_t *app_attrs,
+                                                                 uint8_t num_ext_attr,
+                                                                 btrc_player_app_ext_attr_t *ext_attrs);
+
+typedef void (* btrc_ctrl_playerapplicationsetting_changed_callback)(bt_bdaddr_t *bd_addr,
+                                                                          btrc_player_settings_t *p_vals);
+
+typedef void (* btrc_ctrl_track_changed_callback)(bt_bdaddr_t *bd_addr, uint8_t num_attr,
+                                                     btrc_element_attr_val_t *p_attrs);
+
+typedef void (* btrc_ctrl_play_position_changed_callback)(bt_bdaddr_t *bd_addr,
+                                                              uint32_t song_len, uint32_t song_pos);
+
+typedef void (* btrc_ctrl_play_status_changed_callback)(bt_bdaddr_t *bd_addr,
+                                                            btrc_play_status_t play_status);
+
 /** BT-RC Controller callback structure. */
 typedef struct {
     /** set to sizeof(BtRcCallbacks) */
     size_t      size;
-    btrc_passthrough_rsp_callback               passthrough_rsp_cb;
-    btrc_connection_state_callback              connection_state_cb;
+    btrc_passthrough_rsp_callback                               passthrough_rsp_cb;
+    btrc_groupnavigation_rsp_callback                           groupnavigation_rsp_cb;
+    btrc_connection_state_callback                              connection_state_cb;
+    btrc_ctrl_getrcfeatures_callback                            getrcfeatures_cb;
+    btrc_ctrl_setplayerapplicationsetting_rsp_callback          setplayerappsetting_rsp_cb;
+    btrc_ctrl_playerapplicationsetting_callback                 playerapplicationsetting_cb;
+    btrc_ctrl_playerapplicationsetting_changed_callback         playerapplicationsetting_changed_cb;
+    btrc_ctrl_setabsvol_cmd_callback                            setabsvol_cmd_cb;
+    btrc_ctrl_registernotification_abs_vol_callback             registernotification_absvol_cb;
+    btrc_ctrl_track_changed_callback                            track_changed_cb;
+    btrc_ctrl_play_position_changed_callback                    play_position_changed_cb;
+    btrc_ctrl_play_status_changed_callback                      play_status_changed_cb;
 } btrc_ctrl_callbacks_t;
 
 /** Represents the standard BT-RC AVRCP Controller interface. */
@@ -285,7 +354,23 @@
     bt_status_t (*init)( btrc_ctrl_callbacks_t* callbacks );
 
     /** send pass through command to target */
-    bt_status_t (*send_pass_through_cmd) ( bt_bdaddr_t *bd_addr, uint8_t key_code, uint8_t key_state );
+    bt_status_t (*send_pass_through_cmd) (bt_bdaddr_t *bd_addr, uint8_t key_code,
+            uint8_t key_state );
+
+    /** send group navigation command to target */
+    bt_status_t (*send_group_navigation_cmd) (bt_bdaddr_t *bd_addr, uint8_t key_code,
+            uint8_t key_state );
+
+    /** send command to set player applicaiton setting attributes to target */
+    bt_status_t (*set_player_app_setting_cmd) (bt_bdaddr_t *bd_addr, uint8_t num_attrib,
+            uint8_t* attrib_ids, uint8_t* attrib_vals);
+
+    /** send rsp to set_abs_vol received from target */
+    bt_status_t (*set_volume_rsp) (bt_bdaddr_t *bd_addr, uint8_t abs_vol, uint8_t label);
+
+    /** send notificaiton rsp for abs vol to target */
+    bt_status_t (*register_abs_vol_rsp) (bt_bdaddr_t *bd_addr, btrc_notification_type_t rsp_type,
+            uint8_t abs_vol, uint8_t label);
 
     /** Closes the interface. */
     void  (*cleanup)( void );
diff --git a/include/hardware/bt_sock.h b/include/hardware/bt_sock.h
index 5d206d7..8d1a9e0 100644
--- a/include/hardware/bt_sock.h
+++ b/include/hardware/bt_sock.h
@@ -56,16 +56,20 @@
      * 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.
+     * The callingUid is the UID of the application which is requesting the socket. This is
+     * used for traffic accounting purposes.
      */
     bt_status_t (*listen)(btsock_type_t type, const char* service_name,
-            const uint8_t* service_uuid, int channel, int* sock_fd, int flags);
+            const uint8_t* service_uuid, int channel, int* sock_fd, int flags, int callingUid);
 
     /**
      * 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
+     * the btsock_connect_signal and a new socket fd to be accepted can be read out when connected.
+     * The callingUid is the UID of the application which is requesting the socket. This is
+     * used for traffic accounting purposes.
      */
     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);
+            int channel, int* sock_fd, int flags, int callingUid);
 } btsock_interface_t;
 
 __END_DECLS
diff --git a/include/hardware/keymaster2.h b/include/hardware/keymaster2.h
new file mode 100644
index 0000000..dcde30e
--- /dev/null
+++ b/include/hardware/keymaster2.h
@@ -0,0 +1,452 @@
+/*
+ * 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_KEYMASTER2_H
+#define ANDROID_HARDWARE_KEYMASTER2_H
+
+#include <hardware/keymaster_common.h>
+#include <hardware/keymaster_defs.h>
+
+__BEGIN_DECLS
+
+/**
+ * Keymaster2 device definition
+ */
+struct keymaster2_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;
+
+    void* context;
+
+    /**
+     * See flags defined for keymaster0_devices::flags in keymaster_common.h.  Used only for
+     * backward compatibility; keymaster2 hardware devices must set this to zero.
+     */
+    uint32_t flags;
+
+    /**
+     * 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 keymaster2_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; and
+     * - (KM_TAG_USER_SECURE_ID and KM_TAG_USER_AUTH_TYPE) or KM_TAG_NO_AUTH_REQUIRED.
+     *
+     * 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 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 param
+     *
+     * \param[out] key_blob returns the generated key. \p key_blob must not be NULL.  The caller
+     * assumes ownership key_blob->key_material and must free() it.
+     *
+     * \param[out] characteristics returns the characteristics of the key that was, generated, if
+     * non-NULL.  If non-NULL, the caller assumes ownership and must deallocate 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 keymaster2_device* dev,
+                                      const keymaster_key_param_set_t* params,
+                                      keymaster_key_blob_t* key_blob,
+                                      keymaster_key_characteristics_t* characteristics);
+
+    /**
+     * Returns the characteristics of the specified key, or KM_ERROR_INVALID_KEY_BLOB 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, or empty if KM_TAG_APPLICATION_ID and/or KM_TAG_APPLICATION_DATA were not provided
+     * during generation.  Those values are not included in the returned characteristics.  The
+     * caller assumes ownership of the allocated characteristics object, which must be deallocated
+     * with keymaster_free_characteristics().
+     *
+     * Note that 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. Must not be NULL.  The caller assumes
+     * ownership of the contents and must deallocate with keymaster_free_characteristics().
+     */
+    keymaster_error_t (*get_key_characteristics)(const struct keymaster2_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);
+
+    /**
+     * 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.  Values that are always required for import of useful
+     * keys are:
+     *
+     * - KM_TAG_ALGORITHM;
+     * - KM_TAG_PURPOSE; and
+     * - (KM_TAG_USER_SECURE_ID and KM_TAG_USER_AUTH_TYPE) or KM_TAG_NO_AUTH_REQUIRED.
+     *
+     * KM_TAG_AUTH_TIMEOUT should generally be specified. If unspecified, the user will have to
+     * authenticate for every use.
+     *
+     * The following tags will take default values if unspecified:
+     *
+     * - KM_TAG_KEY_SIZE will default to the size of the key provided.
+     * - KM_TAG_RSA_PUBLIC_EXPONENT will default to the value in the key provided (for RSA keys)
+     *
+     * 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 of the contents and must deallocate with keymaster_free_characteristics().  Note
+     * that KM_TAG_APPLICATION_ID and KM_TAG_APPLICATION_DATA are never returned.
+     */
+    keymaster_error_t (*import_key)(const struct keymaster2_device* dev,
+                                    const keymaster_key_param_set_t* params,
+                                    keymaster_key_format_t key_format,
+                                    const keymaster_blob_t* key_data,
+                                    keymaster_key_blob_t* key_blob,
+                                    keymaster_key_characteristics_t* characteristics);
+
+    /**
+     * Exports a public or symmetric key, returning a byte array in the specified format.
+     *
+     * Note that symmetric key export is allowed only if the key was created with KM_TAG_EXPORTABLE,
+     * and only if all of the requirements for key usage (e.g. authentication) are met.
+     *
+     * \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[in] client_id Client ID blob, which must match the blob provided in
+     * KM_TAG_APPLICATION_ID during key generation (if any).
+     *
+     * \param[in] app_data Appliation data blob, which must match the blob provided in
+     * KM_TAG_APPLICATION_DATA during key generation (if any).
+     *
+     * \param[out] export_data The exported key material.  The caller assumes ownership.
+     */
+    keymaster_error_t (*export_key)(const struct keymaster2_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,
+                                    keymaster_blob_t* export_data);
+
+    /**
+     * Derives a shared secret key from \p key, which must be an EC key, and the public key found in
+     * /p other_key_certificate, an X.509 certificate containing a compatible EC public key.  The
+     * derived key's characteristics are described in \p new_key_params, which must include
+     * algorithm (KM_TAG_ALGORITHM), key size (KM_TAG_KEY_SIZE) and KDF (KM_TAG_KDF) as well as
+     * other desired key characteristics.  The resulting key material is not returned directly, but
+     * instead a new keymaster key is created and the associated blob returned in \p key_blob.  If
+     * \p characteristics is non-NULL, the new key's characteristics are placed there.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] key The keymaster key to use for key agreement. This must be an EC key with the
+     * KM_PURPOSE_DERIVE_KEY purpose.
+     *
+     * \param[in] other_key_certificate An X.509 certificate or certificate fragment containing a
+     * SubjectPublicKey field containing an EC public key on the same curve as \p key.
+     *
+     * \param[in] new_key_params A set of parameters to define/describe the newly-derived symmetric
+     * key. The parameters will define how the key may be used. The set must include KM_TAG_KDF to
+     * specify how the raw agreed key bytes will be transformed to produce the key material.
+     *
+     * \param[out] key_blob The key blob containing the newly-derived key.  The caller takes
+     * ownership of the returned blob.
+     *
+     * \param[out] characteristics. If non-null, will be used to return the characteristics of the
+     * new key blob, which will have KM_TAG_ORIGIN set to KM_ORIGIN_DERIVED.  The caller takes
+     * ownership of the returned characteristics and must deallocate with
+     * keymaster_free_characteristics().
+     */
+    keymaster_error_t (*agree_key)(const struct keymaster2_device* dev,
+                                   const keymaster_key_blob_t* key,
+                                   const keymaster_blob_t* other_key_certificate,
+                                   const keymaster_key_param_set_t* new_key_params,
+                                   keymaster_key_blob_t* new_key_blob,
+                                   keymaster_key_characteristics_t* characteristics);
+
+    /**
+     * Generates a signed X.509 certificate chain attesting to the presence of \p key_to_attest in
+     * keymaster (TODO(swillden): Describe certificate contents in more detail).  The certificate
+     * will contain an extension with OID 1.3.6.1.4.1.11129.2.1.17 and value defined in
+     * <TODO:swillden -- insert link here> which contains the key description.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] key_to_attest The keymaster key for which the attestation certificate will be
+     * generated.
+     *
+     * \param[in] attest_params Parameters defining how to do the attestation.  At present the only
+     * parameter is KM_TAG_ALGORITHM, which must be either KM_ALGORITHM_EC or KM_ALGORITHM_RSA.
+     * This selects which of the provisioned attestation keys will be used to sign the certificate.
+     *
+     * \param[out] cert_chain An array of DER-encoded X.509 certificates. The first will be the
+     * certificate for \p key_to_attest.  The remaining entries will chain back to the root.  The
+     * caller takes ownership and must deallocate with keymaster_free_cert_chain.
+     */
+    keymaster_error_t (*attest_key)(const struct keymaster2_device* dev,
+                                    const keymaster_key_blob_t* key_to_attest,
+                                    const keymaster_key_param_set_t* attest_params,
+                                    keymaster_cert_chain_t* cert_chain);
+
+    /**
+     * Upgrades an old key.  Keys can become "old" in two ways: Keymaster can be upgraded to a new
+     * version, or the system can be updated to invalidate the OS version and/or patch level.  In
+     * either case, attempts to use an old key will result in keymaster returning
+     * KM_ERROR_KEY_REQUIRES_UPGRADE.  This method should then be called to upgrade the key.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] key_to_upgrade The keymaster key to upgrade.
+     *
+     * \param[in] upgrade_params Parameters needed to complete the upgrade. In particular,
+     * KM_TAG_APPLICATION_ID and KM_TAG_APPLICATION_DATA will be required if they were defined for
+     * the key.
+     *
+     * \param[out] upgraded_key The upgraded key blob.
+     */
+    keymaster_error_t (*upgrade_key)(const struct keymaster2_device* dev,
+                                     const keymaster_key_blob_t* key_to_upgrade,
+                                     const keymaster_key_param_set_t* upgrade_params,
+                                     keymaster_key_blob_t* upgraded_key);
+
+    /**
+     * 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.  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 keymaster2_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 keymaster2_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 may leak internal state space or other internal resources and may
+     * eventually cause begin() to return KM_ERROR_TOO_MANY_OPERATIONS when it runs out of space for
+     * operations.  Any result other than KM_ERROR_OK from begin(), update() or finish() implicitly
+     * aborts the operation, in which case abort() need not be called (and will return
+     * KM_ERROR_INVALID_OPERATION_HANDLE if called).
+     *
+     * \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, but should be
+     * specified as KM_PURPOSE_ENCRYPT and KM_PURPOSE_DECRYPT.
+     *
+     * \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] in_params Additional parameters for the operation.  This is typically used to
+     * provide authentication data, with KM_TAG_AUTH_TOKEN.  If KM_TAG_APPLICATION_ID or
+     * KM_TAG_APPLICATION_DATA were provided during generation, they must be provided here, or the
+     * operation will fail with KM_ERROR_INVALID_KEY_BLOB.  For operations that require a nonce or
+     * IV, on keys that were generated with KM_TAG_CALLER_NONCE, in_params may contain a tag
+     * KM_TAG_NONCE.
+     *
+     * \param[out] out_params Output parameters.  Used to return additional data from the operation
+     * initialization, notably to return the IV or nonce from operations that generate an IV or
+     * nonce.  The caller takes ownership of the output parameters array and must free it with
+     * keymaster_free_param_set().  out_params may be set to NULL if no output parameters are
+     * expected.  If out_params is NULL, and output paramaters are generated, begin() will return
+     * KM_ERROR_OUTPUT_PARAMETER_NULL.
+     *
+     * \param[out] operation_handle The newly-created operation handle which must be passed to
+     * update(), finish() or abort().  If operation_handle is NULL, begin() will return
+     * KM_ERROR_OUTPUT_PARAMETER_NULL.
+     */
+    keymaster_error_t (*begin)(const struct keymaster2_device* dev, keymaster_purpose_t purpose,
+                               const keymaster_key_blob_t* key,
+                               const keymaster_key_param_set_t* in_params,
+                               keymaster_key_param_set_t* out_params,
+                               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.
+     *
+     * update() may not consume all of the data provided in the data buffer.  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] in_params Additional parameters for the operation.  For AEAD modes, this is used
+     * to specify KM_TAG_ADDITIONAL_DATA.  Note that additional data may be provided in multiple
+     * calls to update(), but only until input data has been provided.
+     *
+     * \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 input_consumed.
+     *
+     * \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] out_params Output parameters.  Used to return additional data from the operation
+     * The caller takes ownership of the output parameters array and must free it with
+     * keymaster_free_param_set().  out_params may be set to NULL if no output parameters are
+     * expected.  If out_params is NULL, and output paramaters are generated, begin() will return
+     * KM_ERROR_OUTPUT_PARAMETER_NULL.
+     *
+     * \param[out] output The output data, if any.  The caller assumes ownership of the allocated
+     * buffer.  output must not be NULL.
+     *
+     * Note that update() may not provide any output, in which case output->data_length will be
+     * zero, and output->data may be either NULL or zero-length (so the caller should always free()
+     * it).
+     */
+    keymaster_error_t (*update)(const struct keymaster2_device* dev,
+                                keymaster_operation_handle_t operation_handle,
+                                const keymaster_key_param_set_t* in_params,
+                                const keymaster_blob_t* input, size_t* input_consumed,
+                                keymaster_key_param_set_t* out_params, keymaster_blob_t* output);
+
+    /**
+     * Finalizes a cryptographic operation begun with begin() and invalidates \p operation_handle.
+     *
+     * \param[in] dev The keymaster device structure.
+     *
+     * \param[in] operation_handle The operation handle returned by begin().  This handle will be
+     * invalidated.
+     *
+     * \param[in] in_params Additional parameters for the operation.  For AEAD modes, this is used
+     * to specify KM_TAG_ADDITIONAL_DATA, but only if no input data was provided to update().
+     *
+     * \param[in] input Data to be processed, per the parameters established in the call to
+     * begin(). finish() must consume all provided data or return KM_ERROR_INVALID_INPUT_LENGTH.
+     *
+     * \param[in] signature The signature to be verified if the purpose specified in the begin()
+     * call was KM_PURPOSE_VERIFY.
+     *
+     * \param[out] output The output data, if any.  The caller assumes ownership of the allocated
+     * 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 keymaster2_device* dev,
+                                keymaster_operation_handle_t operation_handle,
+                                const keymaster_key_param_set_t* in_params,
+                                const keymaster_blob_t* input, const keymaster_blob_t* signature,
+                                keymaster_key_param_set_t* out_params, keymaster_blob_t* output);
+
+    /**
+     * Aborts a cryptographic operation begun with begin(), freeing all internal resources and
+     * invalidating \p operation_handle.
+     */
+    keymaster_error_t (*abort)(const struct keymaster2_device* dev,
+                               keymaster_operation_handle_t operation_handle);
+};
+typedef struct keymaster2_device keymaster2_device_t;
+
+/* Convenience API for opening and closing keymaster devices */
+
+static inline int keymaster2_open(const struct hw_module_t* module, keymaster2_device_t** device) {
+    return module->methods->open(module, KEYSTORE_KEYMASTER, (struct hw_device_t**)device);
+}
+
+static inline int keymaster2_close(keymaster2_device_t* device) {
+    return device->common.close(&device->common);
+}
+
+__END_DECLS
+
+#endif  // ANDROID_HARDWARE_KEYMASTER2_H
diff --git a/include/hardware/keymaster_common.h b/include/hardware/keymaster_common.h
index 772d7e4..c79c122 100644
--- a/include/hardware/keymaster_common.h
+++ b/include/hardware/keymaster_common.h
@@ -54,6 +54,12 @@
 #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)
 
+/**
+ * Keymaster 2.0 module version provides third API, slightly modified and extended from 1.0.
+ */
+#define KEYMASTER_MODULE_API_VERSION_2_0 HARDWARE_MODULE_API_VERSION(2, 0)
+#define KEYMASTER_DEVICE_API_VERSION_2_0 HARDWARE_DEVICE_API_VERSION(2, 0)
+
 struct keystore_module {
     /**
      * Common methods of the keystore module.  This *must* be the first member of keystore_module as
diff --git a/include/hardware/keymaster_defs.h b/include/hardware/keymaster_defs.h
index bf09e23..fd53adf 100644
--- a/include/hardware/keymaster_defs.h
+++ b/include/hardware/keymaster_defs.h
@@ -52,22 +52,25 @@
      */
 
     /* 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_UINT | 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_CALLER_NONCE = KM_BOOL | 7,     /* Allow caller to specify nonce or IV. */
-    KM_TAG_MIN_MAC_LENGTH = KM_UINT | 8,   /* Minimum length of MAC or AEAD authentication tag in
-                                            * bits. */
-    KM_TAG_KDF = KM_ENUM | 9,              /* keymaster_kdf_t */
-    KM_TAG_EC_CURVE = KM_ENUM | 10,        /* keymaster_ec_curve_t */
+    KM_TAG_PURPOSE = KM_ENUM_REP | 1,    /* keymaster_purpose_t. */
+    KM_TAG_ALGORITHM = KM_ENUM | 2,      /* keymaster_algorithm_t. */
+    KM_TAG_KEY_SIZE = KM_UINT | 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_CALLER_NONCE = KM_BOOL | 7,   /* Allow caller to specify nonce or IV. */
+    KM_TAG_MIN_MAC_LENGTH = KM_UINT | 8, /* Minimum length of MAC or AEAD authentication tag in
+                                          * bits. */
+    KM_TAG_KDF = KM_ENUM_REP | 9,        /* keymaster_kdf_t (keymaster2) */
+    KM_TAG_EC_CURVE = KM_ENUM | 10,      /* keymaster_ec_curve_t (keymaster2) */
 
     /* Algorithm-specific. */
     KM_TAG_RSA_PUBLIC_EXPONENT = KM_ULONG | 200,
     KM_TAG_ECIES_SINGLE_HASH_MODE = KM_BOOL | 201, /* Whether the ephemeral public key is fed into
-                                                    *  the KDF, see 10.2 in http://goo.gl/WbmSSO */
+                                                    * the KDF */
+    KM_TAG_INCLUDE_UNIQUE_ID = KM_BOOL | 202,      /* If true, attestation certificates for this key
+                                                    * will contain an application-scoped and
+                                                    * time-bounded device-unique ID. (keymaster2) */
 
     /* Other hardware-enforced. */
     KM_TAG_BLOB_USAGE_REQUIREMENTS = KM_ENUM | 301, /* keymaster_key_blob_usage_requirements_t */
@@ -106,10 +109,18 @@
                                                    If absent, authentication is required for every
                                                    use.  Authentication state is lost when the
                                                    device is powered off. */
+    KM_TAG_ALLOW_WHILE_ON_BODY = KM_BOOL | 506, /* Allow key to be used after authentication timeout
+                                                 * if device is still on-body (requires secure
+                                                 * on-body sensor. */
 
     /* Application access control */
-    KM_TAG_ALL_APPLICATIONS = KM_BOOL | 600, /* Reserved for future use -- ignore */
-    KM_TAG_APPLICATION_ID = KM_BYTES | 601,  /* Reserved for fugure use -- ignore */
+    KM_TAG_ALL_APPLICATIONS = KM_BOOL | 600, /* Specified to indicate key is usable by all
+                                              * applications. */
+    KM_TAG_APPLICATION_ID = KM_BYTES | 601,  /* Byte string identifying the authorized
+                                              * application. */
+    KM_TAG_EXPORTABLE = KM_BOOL | 602,       /* If true, private/secret key can be exported, but
+                                              * only if all access control requirements for use are
+                                              * met. (keymaster2) */
 
     /*
      * Semantically unenforceable tags, either because they have no specific meaning or because
@@ -120,6 +131,9 @@
     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. */
+    KM_TAG_OS_VERSION = KM_UINT | 705,         /* Version of system (keymaster2) */
+    KM_TAG_OS_PATCHLEVEL = KM_UINT | 706,      /* Patch level of system (keymaster2) */
+    KM_TAG_UNIQUE_ID = KM_BYTES | 707,         /* Used to provide unique ID in attestation */
 
     /* 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. */
@@ -127,7 +141,12 @@
     KM_TAG_AUTH_TOKEN = KM_BYTES | 1002,      /* 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_UINT | 1003,       /* MAC or AEAD authentication tag length in bits. */
+    KM_TAG_MAC_LENGTH = KM_UINT | 1003,       /* MAC or AEAD authentication tag length in
+                                               * bits. */
+
+    KM_TAG_RESET_SINCE_ID_ROTATION = KM_BOOL | 1004, /* Whether the device has beeen factory reset
+                                                        since the last unique ID rotation.  Used for
+                                                        key attestation. */
 } keymaster_tag_t;
 
 /**
@@ -195,16 +214,18 @@
  * Key derivation functions, mostly used in ECIES.
  */
 typedef enum {
+    /* Do not apply a key derivation function; use the raw agreed key */
+    KM_KDF_NONE = 0,
     /* HKDF defined in RFC 5869 with SHA256 */
-    KM_KDF_RFC5869_SHA256 = 0,
+    KM_KDF_RFC5869_SHA256 = 1,
     /* KDF1 defined in ISO 18033-2 with SHA1 */
-    KM_KDF_ISO18033_1_KDF2_SHA1 = 1,
+    KM_KDF_ISO18033_2_KDF1_SHA1 = 2,
     /* KDF1 defined in ISO 18033-2 with SHA256 */
-    KM_KDF_ISO18033_1_KDF1_SHA256 = 2,
+    KM_KDF_ISO18033_2_KDF1_SHA256 = 3,
     /* KDF2 defined in ISO 18033-2 with SHA1 */
-    KM_KDF_ISO18033_2_KDF2_SHA1 = 3,
+    KM_KDF_ISO18033_2_KDF2_SHA1 = 4,
     /* KDF2 defined in ISO 18033-2 with SHA256 */
-    KM_KDF_ISO18033_2_KDF2_SHA256 = 4,
+    KM_KDF_ISO18033_2_KDF2_SHA256 = 5,
 } keymaster_kdf_t;
 
 /**
@@ -224,8 +245,9 @@
  * 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_GENERATED = 0, /* Generated in keymaster.  Should not exist outside the TEE. */
+    KM_ORIGIN_DERIVED = 1,   /* Derived inside keymaster.  Likely exists off-device. */
+    KM_ORIGIN_IMPORTED = 2,  /* Imported into keymaster.  Existed as cleartext in Android. */
     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
@@ -237,7 +259,7 @@
  * 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.
+ * as needed for implementations.
  */
 typedef enum {
     KM_BLOB_STANDALONE = 0,
@@ -245,13 +267,14 @@
 } keymaster_key_blob_usage_requirements_t;
 
 /**
- * Possible purposes of a key (or pair). This type is new in 0_4.
+ * Possible purposes of a key (or pair).
  */
 typedef enum {
-    KM_PURPOSE_ENCRYPT = 0,
-    KM_PURPOSE_DECRYPT = 1,
-    KM_PURPOSE_SIGN = 2,
-    KM_PURPOSE_VERIFY = 3,
+    KM_PURPOSE_ENCRYPT = 0,    /* Usable with RSA, EC and AES keys. */
+    KM_PURPOSE_DECRYPT = 1,    /* Usable with RSA, EC and AES keys. */
+    KM_PURPOSE_SIGN = 2,       /* Usable with RSA, EC and HMAC keys. */
+    KM_PURPOSE_VERIFY = 3,     /* Usable with RSA, EC and HMAC keys. */
+    KM_PURPOSE_DERIVE_KEY = 4, /* Usable with EC keys. */
 } keymaster_purpose_t;
 
 typedef struct {
@@ -293,14 +316,18 @@
     size_t key_material_size;
 } keymaster_key_blob_t;
 
+typedef struct {
+    keymaster_blob_t* entries;
+    size_t entry_count;
+} keymaster_cert_chain_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.
+ * Formats for key import and 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 */
+    KM_KEY_FORMAT_RAW = 3,   /* for symmetric key import and export*/
 } keymaster_key_format_t;
 
 /**
@@ -372,6 +399,7 @@
     KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH = -59,
     KM_ERROR_UNSUPPORTED_KDF = -60,
     KM_ERROR_UNSUPPORTED_EC_CURVE = -61,
+    KM_ERROR_KEY_REQUIRES_UPGRADE = -62,
 
     KM_ERROR_UNIMPLEMENTED = -100,
     KM_ERROR_VERSION_MISMATCH = -101,
@@ -541,6 +569,19 @@
     }
 }
 
+inline void keymaster_free_cert_chain(keymaster_cert_chain_t* chain) {
+    if (chain) {
+        for (size_t i = 0; i < chain->entry_count; ++i) {
+            free((uint8_t*)chain->entries[i].data);
+            chain->entries[i].data = NULL;
+            chain->entries[i].data_length = 0;
+        }
+        free(chain->entries);
+        chain->entries = NULL;
+        chain->entry_count = 0;
+    }
+}
+
 #ifdef __cplusplus
 }  // extern "C"
 #endif  // __cplusplus
diff --git a/include/hardware/nvram.h b/include/hardware/nvram.h
new file mode 100644
index 0000000..0af5073
--- /dev/null
+++ b/include/hardware/nvram.h
@@ -0,0 +1,327 @@
+/*
+ * 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_NVRAM_H
+#define ANDROID_HARDWARE_NVRAM_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+
+#include <hardware/hardware.h>
+#include <hardware/nvram_defs.h>
+
+__BEGIN_DECLS
+
+/* The id of this module. */
+#define NVRAM_HARDWARE_MODULE_ID "nvram"
+#define NVRAM_HARDWARE_DEVICE_ID "nvram-dev"
+
+/* The version of this module. */
+#define NVRAM_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1)
+#define NVRAM_DEVICE_API_VERSION_0_1 HARDWARE_DEVICE_API_VERSION(0, 1)
+
+struct nvram_module {
+    /**
+     * Common methods of the nvram_module. This *must* be the first member of
+     * nvram_module as users of this structure will cast a hw_module_t to
+     * nvram_module pointer in contexts where it's known the hw_module_t
+     * references a nvram_module.
+     */
+    hw_module_t common;
+
+    /* There are no module methods other than the common ones. */
+};
+
+struct nvram_device {
+    /**
+     * Common methods of the nvram_device.  This *must* be the first member of
+     * nvram_device as users of this structure will cast a hw_device_t to
+     * nvram_device pointer in contexts where it's known the hw_device_t
+     * references a nvram_device.
+     */
+    struct hw_device_t common;
+
+    /**
+     * Outputs the total number of bytes available in NVRAM. This will
+     * always be at least 2048. If an implementation does not know the
+     * total size it may provide an estimate or 2048.
+     *
+     *   device - The nvram_device instance.
+     *   total_size - Receives the output. Cannot be NULL.
+     */
+    nvram_result_t (*get_total_size_in_bytes)(const struct nvram_device* device,
+                                              uint64_t* total_size);
+
+    /**
+     * Outputs the unallocated number of bytes available in NVRAM. If an
+     * implementation does not know the available size it may provide an
+     * estimate or the total size.
+     *
+     *   device - The nvram_device instance.
+     *   available_size - Receives the output. Cannot be NULL.
+     */
+    nvram_result_t (*get_available_size_in_bytes)(
+        const struct nvram_device* device, uint64_t* available_size);
+
+    /**
+     * Outputs the maximum total number of spaces that may be allocated.
+     * This will always be at least 8. Outputs NV_UNLIMITED_SPACES if any
+     * number of spaces are supported (limited only to available NVRAM
+     * bytes).
+     *
+     *   device - The nvram_device instance.
+     *   num_spaces - Receives the output. Cannot be NULL.
+     */
+    nvram_result_t (*get_max_spaces)(const struct nvram_device* device,
+                                     uint32_t* num_spaces);
+
+    /**
+     * Outputs a list of created space indices. If |max_list_size| is
+     * 0, only |list_size| is populated.
+     *
+     *   device - The nvram_device instance.
+     *   max_list_size - The number of items in the |space_index_list|
+     *                   array.
+     *   space_index_list - Receives the list of created spaces up to the
+     *                      given |max_list_size|. May be NULL if
+     *                      |max_list_size| is 0.
+     *   list_size - Receives the number of items populated in
+     *               |space_index_list|, or the number of items available
+     *               if |space_index_list| is NULL.
+     */
+    nvram_result_t (*get_space_list)(const struct nvram_device* device,
+                                     uint32_t max_list_size,
+                                     uint32_t* space_index_list,
+                                     uint32_t* list_size);
+
+    /**
+     * Outputs the size, in bytes, of a given space.
+     *
+     *   device - The nvram_device instance.
+     *   index - The space index.
+     *   size - Receives the output. Cannot be NULL.
+     */
+    nvram_result_t (*get_space_size)(const struct nvram_device* device,
+                                     uint32_t index, uint64_t* size);
+
+    /**
+     * Outputs the list of controls associated with a given space.
+     *
+     *   device - The nvram_device instance.
+     *   index - The space index.
+     *   max_list_size - The number of items in the |control_list| array.
+     *   control_list - Receives the list of controls up to the given
+     *                  |max_list_size|. May be NULL if |max_list_size|
+     *                  is 0.
+     *   list_size - Receives the number of items populated in
+     *               |control_list|, or the number of items available if
+     *               |control_list| is NULL.
+     */
+    nvram_result_t (*get_space_controls)(const struct nvram_device* device,
+                                         uint32_t index, uint32_t max_list_size,
+                                         nvram_control_t* control_list,
+                                         uint32_t* list_size);
+
+    /**
+     * Outputs whether locks are enabled for the given space. When a lock
+     * is enabled, the operation is disabled and any attempt to perform that
+     * operation will result in NV_RESULT_OPERATION_DISABLED.
+     *
+     *   device - The nvram_device instance.
+     *   index - The space index.
+     *   write_lock_enabled - Will be set to non-zero iff write
+     *                        operations are currently disabled.
+     *   read_lock_enabled - Will be set to non-zero iff read operations
+     *                       are currently disabled.
+     */
+    nvram_result_t (*is_space_locked)(const struct nvram_device* device,
+                                      uint32_t index, int* write_lock_enabled,
+                                      int* read_lock_enabled);
+
+    /**
+     * Creates a new space with the given index, size, controls, and
+     * authorization value.
+     *
+     *   device - The nvram_device instance.
+     *   index - An index for the new space. The index can be any 32-bit
+     *           value but must not already be assigned to an existing
+     *           space.
+     *   size_in_bytes - The number of bytes to allocate for the space.
+     *   control_list - An array of controls to enforce for the space.
+     *   list_size - The number of items in |control_list|.
+     *   authorization_value - If |control_list| contains
+     *                         NV_CONTROL_READ_AUTHORIZATION and / or
+     *                         NV_CONTROL_WRITE_AUTHORIZATION, then this
+     *                         parameter provides the authorization value
+     *                         for these policies (if both controls are
+     *                         set then this value applies to both).
+     *                         Otherwise, this value is ignored and may
+     *                         be NULL.
+     *   authorization_value_size - The number of bytes in
+     *                              |authorization_value|.
+     */
+    nvram_result_t (*create_space)(const struct nvram_device* device,
+                                   uint32_t index, uint64_t size_in_bytes,
+                                   const nvram_control_t* control_list,
+                                   uint32_t list_size,
+                                   const uint8_t* authorization_value,
+                                   uint32_t authorization_value_size);
+
+    /**
+     * Deletes a space.
+     *
+     *   device - The nvram_device instance.
+     *   index - The space index.
+     *   authorization_value - If the space has the
+     *                         NV_CONTROL_WRITE_AUTHORIZATION policy,
+     *                         then this parameter provides the
+     *                         authorization value. Otherwise, this value
+     *                         is ignored and may be NULL.
+     *   authorization_value_size - The number of bytes in
+     *                              |authorization_value|.
+     */
+    nvram_result_t (*delete_space)(const struct nvram_device* device,
+                                   uint32_t index,
+                                   const uint8_t* authorization_value,
+                                   uint32_t authorization_value_size);
+
+    /**
+     * Disables any further creation of spaces until the next full device
+     * reset (as in factory reset, not reboot). Subsequent calls to
+     * NV_CreateSpace should return NV_RESULT_OPERATION_DISABLED.
+     *
+     *   device - The nvram_device instance.
+     */
+    nvram_result_t (*disable_create)(const struct nvram_device* device);
+
+    /**
+     * Writes the contents of a space. If the space is configured with
+     * NV_CONTROL_WRITE_EXTEND then the input data is used to extend the
+     * current data.
+     *
+     *   device - The nvram_device instance.
+     *   index - The space index.
+     *   buffer - The data to write.
+     *   buffer_size - The number of bytes in |buffer|. If this is less
+     *                 than the size of the space, the remaining bytes
+     *                 will be set to 0x00. If this is more than the size
+     *                 of the space, returns NV_RESULT_INVALID_PARAMETER.
+     *   authorization_value - If the space has the
+     *                         NV_CONTROL_WRITE_AUTHORIZATION policy,
+     *                         then this parameter provides the
+     *                         authorization value. Otherwise, this value
+     *                         is ignored and may be NULL.
+     *   authorization_value_size - The number of bytes in
+     *                              |authorization_value|.
+     */
+    nvram_result_t (*write_space)(const struct nvram_device* device,
+                                  uint32_t index, const uint8_t* buffer,
+                                  uint64_t buffer_size,
+                                  const uint8_t* authorization_value,
+                                  uint32_t authorization_value_size);
+
+    /**
+     * Reads the contents of a space. If the space has never been
+     * written, all bytes read will be 0x00.
+     *
+     *   device - The nvram_device instance.
+     *   index - The space index.
+     *   num_bytes_to_read - The number of bytes to read; |buffer| must
+     *                       be large enough to hold this many bytes. If
+     *                       this is more than the size of the space, the
+     *                       entire space is read. If this is less than
+     *                       the size of the space, the first bytes in
+     *                       the space are read.
+     *   authorization_value - If the space has the
+     *                         NV_CONTROL_READ_AUTHORIZATION policy, then
+     *                         this parameter provides the authorization
+     *                         value. Otherwise, this value is ignored
+     *                         and may be NULL.
+     *   authorization_value_size - The number of bytes in
+     *                              |authorization_value|.
+     *   buffer - Receives the data read from the space. Must be at least
+     *            |num_bytes_to_read| bytes in size.
+     *   bytes_read - The number of bytes read. If NV_RESULT_SUCCESS is
+     *                returned this will be set to the smaller of
+     *                |num_bytes_to_read| or the size of the space.
+     */
+    nvram_result_t (*read_space)(const struct nvram_device* device,
+                                 uint32_t index, uint64_t num_bytes_to_read,
+                                 const uint8_t* authorization_value,
+                                 uint32_t authorization_value_size,
+                                 uint8_t* buffer, uint64_t* bytes_read);
+
+    /**
+     * Enables a write lock for the given space according to its policy.
+     * If the space does not have NV_CONTROL_PERSISTENT_WRITE_LOCK or
+     * NV_CONTROL_BOOT_WRITE_LOCK set then this function has no effect
+     * and may return an error.
+     *
+     *   device - The nvram_device instance.
+     *   index - The space index.
+     *   authorization_value - If the space has the
+     *                         NV_CONTROL_WRITE_AUTHORIZATION policy,
+     *                         then this parameter provides the
+     *                         authorization value. Otherwise, this value
+     *                         is ignored and may be NULL.
+     *   authorization_value_size - The number of bytes in
+     *                              |authorization_value|.
+     */
+    nvram_result_t (*enable_write_lock)(const struct nvram_device* device,
+                                        uint32_t index,
+                                        const uint8_t* authorization_value,
+                                        uint32_t authorization_value_size);
+
+    /**
+     * Enables a read lock for the given space according to its policy.
+     * If the space does not have NV_CONTROL_BOOT_READ_LOCK set then this
+     * function has no effect and may return an error.
+     *
+     *   device - The nvram_device instance.
+     *   index - The space index.
+     *   authorization_value - If the space has the
+     *                         NV_CONTROL_READ_AUTHORIZATION policy, then
+     *                         this parameter provides the authorization
+     *                         value. (Note that there is no requirement
+     *                         for write access in order to lock for
+     *                         reading. A read lock is always volatile.)
+     *                         Otherwise, this value is ignored and may
+     *                         be NULL.
+     *   authorization_value_size - The number of bytes in
+     *                              |authorization_value|.
+     */
+    nvram_result_t (*enable_read_lock)(const struct nvram_device* device,
+                                       uint32_t index,
+                                       const uint8_t* authorization_value,
+                                       uint32_t authorization_value_size);
+};
+
+typedef struct nvram_device nvram_device_t;
+
+/* Convenience API for opening and closing nvram devices. */
+static inline int nvram_open(const struct hw_module_t* module,
+                             nvram_device_t** device) {
+    return module->methods->open(module, NVRAM_HARDWARE_DEVICE_ID,
+                                 (struct hw_device_t**)device);
+}
+
+static inline int nvram_close(nvram_device_t* device) {
+    return device->common.close(&device->common);
+}
+
+__END_DECLS
+
+#endif  // ANDROID_HARDWARE_NVRAM_H
diff --git a/include/hardware/nvram_defs.h b/include/hardware/nvram_defs.h
new file mode 100644
index 0000000..0256a3c
--- /dev/null
+++ b/include/hardware/nvram_defs.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2016 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 data type definitions and constants that are useful to
+ * code interacting with and implementing the NVRAM HAL, even though it doesn't
+ * use the actual NVRAM HAL module interface. Keeping this in a separate file
+ * simplifies inclusion in low-level code which can't easily include the heavier
+ * hardware.h due to lacking standard headers.
+ */
+
+#ifndef ANDROID_HARDWARE_NVRAM_DEFS_H
+#define ANDROID_HARDWARE_NVRAM_DEFS_H
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif  // __cplusplus
+
+/* Values returned by nvram_device methods. */
+typedef uint32_t nvram_result_t;
+
+const nvram_result_t NV_RESULT_SUCCESS = 0;
+const nvram_result_t NV_RESULT_INTERNAL_ERROR = 1;
+const nvram_result_t NV_RESULT_ACCESS_DENIED = 2;
+const nvram_result_t NV_RESULT_INVALID_PARAMETER = 3;
+const nvram_result_t NV_RESULT_SPACE_DOES_NOT_EXIST = 4;
+const nvram_result_t NV_RESULT_SPACE_ALREADY_EXISTS = 5;
+const nvram_result_t NV_RESULT_OPERATION_DISABLED = 6;
+
+/* Values describing available access controls. */
+typedef uint32_t nvram_control_t;
+
+const nvram_control_t NV_CONTROL_PERSISTENT_WRITE_LOCK = 1;
+const nvram_control_t NV_CONTROL_BOOT_WRITE_LOCK = 2;
+const nvram_control_t NV_CONTROL_BOOT_READ_LOCK = 3;
+const nvram_control_t NV_CONTROL_WRITE_AUTHORIZATION = 4;
+const nvram_control_t NV_CONTROL_READ_AUTHORIZATION = 5;
+const nvram_control_t NV_CONTROL_WRITE_EXTEND = 6;
+
+const uint32_t NV_UNLIMITED_SPACES = 0xFFFFFFFF;
+
+#ifdef __cplusplus
+}  // extern "C"
+#endif  // __cplusplus
+
+#endif  // ANDROID_HARDWARE_NVRAM_DEFS_H
diff --git a/modules/sensors/Android.mk b/modules/sensors/Android.mk
index 94d100b..bf377c9 100644
--- a/modules/sensors/Android.mk
+++ b/modules/sensors/Android.mk
@@ -28,7 +28,6 @@
 
 LOCAL_SRC_FILES := \
     multihal.cpp \
-    SensorEventQueue.h \
     SensorEventQueue.cpp \
 
 LOCAL_SHARED_LIBRARIES := \