Merge "add zone_type definition to zoned properties"
diff --git a/include/hardware/bluetooth.h b/include/hardware/bluetooth.h
index 8ddc251..93aa8e5 100644
--- a/include/hardware/bluetooth.h
+++ b/include/hardware/bluetooth.h
@@ -567,8 +567,10 @@
     /**
      * 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
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..45e8b26 100644
--- a/include/hardware/bt_gatt_client.h
+++ b/include/hardware/bt_gatt_client.h
@@ -245,6 +245,9 @@
 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);
+
 typedef struct {
     register_client_callback            register_client_cb;
     scan_result_callback                scan_result_cb;
@@ -279,6 +282,7 @@
     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;
 } btgatt_client_callbacks_t;
 
 /** Represents the standard BT-GATT client interface. */
@@ -448,6 +452,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/context_hub.h b/include/hardware/context_hub.h
new file mode 100644
index 0000000..f026b08
--- /dev/null
+++ b/include/hardware/context_hub.h
@@ -0,0 +1,288 @@
+/*
+ * 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.
+ */
+
+#ifndef CONTEXT_HUB_H
+#define CONTEXT_HUB_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#include <hardware/hardware.h>
+
+/**
+ * This header file defines the interface of a Context Hub Implementation to
+ * the Android service exposing Context hub capabilities to applications.
+ * The Context hub is expected to a low power compute domain with the following
+ * defining charecteristics -
+ *
+ *    1) Access to sensors like accelerometer, gyroscope, magenetometer.
+ *    2) Access to radios like GPS, Wifi, Bluetooth etc.
+ *    3) Access to low power audio sensing.
+ *
+ * Implementations of this HAL can add additional sensors not defined by the
+ * Android API. Such information sources shall be private to the implementation.
+ *
+ * The Context Hub HAL exposes the construct of code download. A piece of binary
+ * code can be pushed to the context hub through the supported APIs.
+ *
+ * This version of the HAL designs in the possibility of multiple context hubs.
+ */
+
+__BEGIN_DECLS
+
+/*****************************************************************************/
+
+#define CONTEXT_HUB_HEADER_VERSION          1
+#define CONTEXT_HUB_DEVICE_API_VERSION_1_0  HARDWARE_DEVICE_API_VERSION_2(1, 0, CONTEXT_HUB_HEADER_VERSION)
+
+/**
+ * The id of this module
+ */
+#define CONTEXT_HUB_MODULE_ID         "context_hub"
+
+/**
+ * Name of the device to open
+ */
+#define CONTEXT_HUB_HARDWARE_POLL     "ctxt_poll"
+
+/**
+ * Memory types for code upload. Device-specific. At least HUB_MEM_TYPE_MAIN must be supported
+ */
+#define HUB_MEM_TYPE_MAIN             0
+#define HUB_MEM_TYPE_SECONDARY        1
+#define HUB_MEM_TYPE_TCM              2
+
+
+#define HUB_MEM_TYPE_FIRST_VENDOR     0x80000000ul
+
+
+/**
+ * Other memory types (likely not writeable, informational only)
+ */
+#define HUB_MEM_TYPE_BOOTLOADER       0xfffffffful
+#define HUB_MEM_TYPE_OS               0xfffffffeul
+#define HUB_MEM_TYPE_EEDATA           0xfffffffdul
+#define HUB_MEM_TYPE_RAM              0xfffffffcul
+
+/**
+ * Types of memory blocks on the context hub
+ * */
+#define MEM_FLAG_READ  0x1  // Memory can be written to
+#define MEM_FLAG_WRITE 0x2  // Memory can be written to
+#define MEM_FLAG_EXEC  0x4  // Memory can be executed from
+
+/**
+ * The following structure defines each memory block in detail
+ */
+struct mem_range_t {
+    uint32_t total_bytes;
+    uint32_t free_bytes;
+    uint32_t type;        // HUB_MEM_TYPE_*
+    uint32_t mem_flags;   // MEM_FLAG_*
+};
+
+
+/**
+ * App names may be strings, bytes, uints, etc. This caovers all types of app names
+ */
+struct hub_app_name_t {
+    uint32_t app_name_len;
+    const void *app_name;
+};
+
+struct hub_app_info {
+    const struct hub_app_name_t *name;
+    uint32_t version;
+    uint32_t num_mem_ranges;
+    const struct mem_range_t *mem_usage;
+};
+
+/**
+ * Following enum defines the types of sensors that a hub may declare support
+ * for. Declaration for support would mean that the hub can access and process
+ * data from that particular sensor type.
+ */
+
+typedef enum {
+    CONTEXT_SENSOR_RESERVED,             // 0
+    CONTEXT_SENSOR_ACCELEROMETER,        // 1
+    CONTEXT_SENSOR_GYROSCOPE,            // 2
+    CONTEXT_SENSOR_MAGNETOMETER,         // 3
+    CONTEXT_SENSOR_BAROMETER,            // 4
+    CONTEXT_SENSOR_PROXIMITY_SENSOR,     // 5
+    CONTEXT_SENSOR_AMBIENT_LIGHT_SENSOR, // 6
+
+    CONTEXT_SENSOR_GPS = 0x100,          // 0x100
+    // Reserving this space for variants on GPS
+    CONTEXT_SENSOR_WIFI = 0x200,         // 0x200
+    // Reserving this space for variants on WIFI
+    CONTEXT_SENSOR_AUDIO = 0x300,        // 0x300
+    // Reserving this space for variants on Audio
+    CONTEXT_SENSOR_CAMERA = 0x400,       // 0x400
+    // Reserving this space for variants on Camera
+    CONTEXT_SENSOR_BLE = 0x500,          // 0x500
+
+    CONTEXT_SENSOR_MAX = 0xffffffff,     //make sure enum size is set
+} context_sensor_e;
+
+/**
+ * Sensor types beyond CONTEXT_HUB_TYPE_PRIVATE_SENSOR_BASE are custom types
+ */
+#define CONTEXT_HUB_TYPE_PRIVATE_SENSOR_BASE 0x10000
+
+/**
+ * The following structure describes a sensor
+ */
+struct physical_sensor_description_t {
+    uint32_t sensor_type;           // From the definitions above eg: 100
+    const char *type_string;        // Type as a string. eg: "GPS"
+    const char *name;               // Identifier eg: "Bosch BMI160"
+    const char *vendor;             // Vendor : eg "STM"
+    uint32_t version;               // Version : eg 0x1001
+    uint32_t fifo_reserverd_count;  // Batching possible in hardware. Please
+                                    // note that here hardware does not include
+                                    // the context hub itslef. Thus, this
+                                    // definition may be different from say the
+                                    // number advertised in the sensors HAL
+                                    // which allows for batching in a hub.
+    uint32_t fifo_max_count;        // maximum number of batchable events.
+    uint64_t min_delay_ms;          // in milliseconds, corresponding to highest
+                                    // sampling freq.
+    uint64_t max_delay_ms;          // in milliseconds, corresponds to minimum
+                                    // sampling frequency
+    float peak_power_mw;            // At max frequency & no batching, power
+                                    // in milliwatts
+};
+
+struct connected_sensor_t {
+    uint32_t sensor_id;             // identifier for this sensor
+
+    /* This union may be extended to other sensor types */
+    union {
+        struct physical_sensor_description_t physical_sensor;
+    };
+};
+
+
+
+/**
+ * Messages of this length or less must be supported by all implementations,
+ * longer lengths are supported up to max_supported_msg_len. This is exposed
+ * to third party apps, and since we do not know their msg data formats we
+ * cannot fragment for them. Our own messages are allowed to be bigger and
+ * this HAL will fragment as needed. "Our own" messages are messaegs defined
+ * in this file.
+ */
+#define HUB_REQUIRED_SUPPORTED_MSG_LEN  128
+
+struct hub_message_t {
+    const struct hub_app_name_t *app; /* To/From this nanoapp */
+    uint32_t message_type;
+    uint32_t message_len;
+    const void *message;
+};
+
+
+/**
+ * Definition of a context hub. A device may contain more than one low
+ * power domain. In that case, please add an entry for each hub. However,
+ * it is perfectly OK for a device to declare one context hub and manage
+ * them internally as several
+ */
+
+struct context_hub_t {
+    const char *name;                // descriptive name eg: "Awesome Hub #1"
+    const char *vendor;              // hub hardware vendor eg: "Qualcomm"
+    const char *toolchain;           // toolchain to make binaries eg:"gcc ARM"
+    uint32_t platform_version;       // Version of the hardware : eg 0x20
+    uint32_t toolchain_version;      // Version of the toolchain : eg: 0x484
+    uint32_t hub_id;                 // a device unique id for this hub
+
+    float peak_mips;                 // Peak MIPS platform can deliver
+    float stopped_power_draw_mw;     // if stopped, retention power, milliwatts
+    float sleep_power_draw_mw;       // if sleeping, retention power, milliwatts
+    float peak_power_draw_mw;        // for a busy CPUm power in milliwatts
+
+    const struct connected_sensor_t *connected_sensors; // array of connected sensors
+    uint32_t num_connected_sensors;  // number of connected sensors
+
+    uint32_t max_supported_msg_len;
+    const struct hub_app_name_t *os_app_name; /* send msgs here for OS functions */
+};
+
+/**
+ * All communication between the context hubs and the Context Hub Service is in
+ * the form of messages. Some message types are distinguished and their
+ * Semantics shall be well defined.
+ * Custom message types should be defined starting above
+ * CONTEXT_HUB_PRIVATE_MSG_BASE
+ */
+
+typedef enum {
+    CONTEXT_HUB_APPS_ENABLE = 1, // 1: Enables the loaded nano-apps
+    CONTEXT_HUB_APPS_DISABLE,    // 2: Disables any loaded nano-apps
+    CONTEXT_HUB_LOAD_APP,        // 3: Load a supplied app
+    CONTEXT_HUB_UNLOAD_APP,      // 4: Unload a specified app
+    CONTEXT_HUB_QUERY_APPS,      // 5: Query for apps info on hub (gets struct hub_app_info[])
+    CONTEXT_HUB_QUERY_MEMORY,    // 5: Query for memory info (gets struct mem_range_t[])
+    CONTEXT_HUB_LOAD_OS,         // 6: Load up OS update
+} hub_messages_e;
+
+#define CONTEXT_HUB_TYPE_PRIVATE_MSG_BASE 0x10000
+
+
+/**
+ * A callback registers with the context hub service to pass messages
+ * coming from the hub to the service/clients.
+ */
+typedef int context_hub_callback(uint32_t hub_id, const struct hub_message_t *rxed_msg, void *cookie);
+
+
+/**
+ * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM
+ * and the fields of this data structure must begin with hw_module_t
+ * followed by module specific information.
+ */
+struct context_hub_module_t {
+    struct hw_module_t common;
+
+    /**
+     * Enumerate all available hubs.The list is returned in "list".
+     * @return result : number of hubs in list or error  (negative)
+     *
+     * This method shall be called at device bootup.
+     */
+    int (*get_hubs)(struct context_hub_module_t* module, const struct context_hub_t ** list);
+
+    /**
+     * Registers a callback for the HAL implementation to communicate
+     * with the context hub service.
+     * @return result : 0 if successful, error code otherwise
+     */
+    int (*subscribe_messages)(uint32_t hub_id, context_hub_callback cbk, void *cookie);
+
+    /**
+     * Send a message to a hub
+     * @return result : 0 if successful, error code otherwise
+     */
+    int (*send_message)(uint32_t hub_id, const struct hub_message_t *msg);
+
+};
+
+__END_DECLS
+
+#endif  // CONTEXT_HUB_SENSORS_INTERFACE_H
diff --git a/include/hardware/gps.h b/include/hardware/gps.h
index 76b6cb7..6fd47a9 100644
--- a/include/hardware/gps.h
+++ b/include/hardware/gps.h
@@ -53,7 +53,7 @@
 #define GPS_POSITION_MODE_MS_BASED      1
 /**
  * AGPS MS-Assisted mode. This mode is not maintained by the platform anymore.
- * It is strongly recommended to use GPS_POSITION_MODE_MS_BASE instead.
+ * It is strongly recommended to use GPS_POSITION_MODE_MS_BASED instead.
  */
 #define GPS_POSITION_MODE_MS_ASSISTED   2
 
@@ -98,28 +98,31 @@
 
 /** Flags for the gps_set_capabilities callback. */
 
-/** GPS HAL schedules fixes for GPS_POSITION_RECURRENCE_PERIODIC mode.
-    If this is not set, then the framework will use 1000ms for min_interval
-    and will start and call start() and stop() to schedule the GPS.
+/**
+ * GPS HAL schedules fixes for GPS_POSITION_RECURRENCE_PERIODIC mode. If this is
+ * not set, then the framework will use 1000ms for min_interval and will start
+ * and call start() and stop() to schedule the GPS.
  */
-#define GPS_CAPABILITY_SCHEDULING       0x0000001
+#define GPS_CAPABILITY_SCHEDULING       (1 << 0)
 /** GPS supports MS-Based AGPS mode */
-#define GPS_CAPABILITY_MSB              0x0000002
+#define GPS_CAPABILITY_MSB              (1 << 1)
 /** GPS supports MS-Assisted AGPS mode */
-#define GPS_CAPABILITY_MSA              0x0000004
+#define GPS_CAPABILITY_MSA              (1 << 2)
 /** GPS supports single-shot fixes */
-#define GPS_CAPABILITY_SINGLE_SHOT      0x0000008
+#define GPS_CAPABILITY_SINGLE_SHOT      (1 << 3)
 /** GPS supports on demand time injection */
-#define GPS_CAPABILITY_ON_DEMAND_TIME   0x0000010
+#define GPS_CAPABILITY_ON_DEMAND_TIME   (1 << 4)
 /** GPS supports Geofencing  */
-#define GPS_CAPABILITY_GEOFENCING       0x0000020
+#define GPS_CAPABILITY_GEOFENCING       (1 << 5)
 /** GPS supports Measurements */
-#define GPS_CAPABILITY_MEASUREMENTS     0x0000040
+#define GPS_CAPABILITY_MEASUREMENTS     (1 << 6)
 /** GPS supports Navigation Messages */
-#define GPS_CAPABILITY_NAV_MESSAGES     0x0000080
+#define GPS_CAPABILITY_NAV_MESSAGES     (1 << 7)
 
-/** Flags used to specify which aiding data to delete
-    when calling delete_aiding_data(). */
+/**
+ * Flags used to specify which aiding data to delete when calling
+ * delete_aiding_data().
+ */
 typedef uint16_t GpsAidingData;
 // IMPORTANT: Note that the following values must match
 // constants in GpsLocationProvider.java.
@@ -210,9 +213,11 @@
 /** AGPS data connection failed */
 #define GPS_AGPS_DATA_CONN_FAILED   5
 
+typedef uint16_t AGpsRefLocationType;
 #define AGPS_REF_LOCATION_TYPE_GSM_CELLID   1
 #define AGPS_REF_LOCATION_TYPE_UMTS_CELLID  2
 #define AGPS_REG_LOCATION_TYPE_MAC          3
+#define AGPS_REF_LOCATION_TYPE_LTE_CELLID   4
 
 /** Network types for update_network_state "type" parameter */
 #define AGPS_RIL_NETWORK_TYPE_MOBILE        0
@@ -246,9 +251,14 @@
  * Enumeration of the available values for the GPS Clock type.
  */
 typedef uint8_t GpsClockType;
-/** The type is not available ot it is unknown. */
+/** The type is not available or it is unknown. */
 #define GPS_CLOCK_TYPE_UNKNOWN                  0
-/** The source of the time value reported by GPS clock is the local hardware clock. */
+/**
+ * The source of the time value reported by GPS clock is the local hardware
+ * clock. This is a mandatory flag. When the GpsSystemInfo's year_of_hw is 2016
+ * or higher, it is mandatory that 'time' is populated with the local hardware
+ * clock value, and this flag must always be set.
+ */
 #define GPS_CLOCK_TYPE_LOCAL_HW_TIME            1
 /**
  * The source of the time value reported by GPS clock is the GPS time derived from satellites
@@ -296,7 +306,12 @@
 #define GPS_MEASUREMENT_HAS_DOPPLER_SHIFT_UNCERTAINTY         (1<<16)
 /** A valid 'used in fix' flag is stored in the data structure. */
 #define GPS_MEASUREMENT_HAS_USED_IN_FIX                       (1<<17)
-/** The value of 'pseudorange rate' is uncorrected. */
+/**
+ * The value of 'pseudorange rate' is uncorrected.
+ * This is a mandatory flag. It is mandatory that 'pseudorange rate' is
+ * populated with the uncorrected value, and this flag must always be set.
+ * See comments of GpsMeasurement::pseudorange_rate_mps for more details.
+ */
 #define GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE      (1<<18)
 
 /**
@@ -316,9 +331,9 @@
 typedef uint8_t GpsMultipathIndicator;
 /** The indicator is not available or unknown. */
 #define GPS_MULTIPATH_INDICATOR_UNKNOWN                 0
-/** The measurement has been indicated to use multipath. */
+/** The measurement is indicated to be affected by multipath. */
 #define GPS_MULTIPATH_INDICATOR_DETECTED                1
-/** The measurement has been indicated Not to use multipath. */
+/** The measurement is indicated to be not affected by multipath. */
 #define GPS_MULTIPATH_INDICATOR_NOT_USED                2
 
 /**
@@ -377,6 +392,27 @@
 #define NAV_MESSAGE_STATUS_PARITY_REBUILT  (1<<1)
 
 /**
+ * Flag that indicates which extra data GnssSvInfo includes.
+ */
+typedef uint8_t                                 GnssSvFlags;
+#define GNSS_SV_FLAGS_NONE                      0
+#define GNSS_SV_FLAGS_HAS_EPHEMERIS_DATA        (1 << 0)
+#define GNSS_SV_FLAGS_HAS_ALMANAC_DATA          (1 << 1)
+#define GNSS_SV_FLAGS_USED_IN_FIX               (1 << 2)
+
+/**
+ * Constellation type of GnssSvInfo
+ */
+typedef uint8_t                         GnssConstellationType;
+#define GNSS_CONSTELLATION_UNKNOWN      0
+#define GNSS_CONSTELLATION_GPS          1
+#define GNSS_CONSTELLATION_SBAS         2
+#define GNSS_CONSTELLATION_GLONASS      3
+#define GNSS_CONSTELLATION_QZSS         4
+#define GNSS_CONSTELLATION_BEIDOU       5
+#define GNSS_CONSTELLATION_GALILEO      6
+
+/**
  * Name for the GPS XTRA interface.
  */
 #define GPS_XTRA_INTERFACE      "gps-xtra"
@@ -437,8 +473,9 @@
     double          latitude;
     /** Represents longitude in degrees. */
     double          longitude;
-    /** Represents altitude in meters above the WGS 84 reference
-     * ellipsoid. */
+    /**
+     * Represents altitude in meters above the WGS 84 reference ellipsoid.
+     */
     double          altitude;
     /** Represents speed in meters per second. */
     float           speed;
@@ -471,43 +508,124 @@
     float   azimuth;
 } GpsSvInfo;
 
-/** Represents SV status. */
 typedef struct {
-    /** set to sizeof(GpsSvStatus) */
-    size_t          size;
-
-    /** Number of SVs currently visible. */
-    int         num_svs;
-
-    /** Contains an array of SV information. */
-    GpsSvInfo   sv_list[GPS_MAX_SVS];
-
-    /** Represents a bit mask indicating which SVs
-     * have ephemeris data.
-     */
-    uint32_t    ephemeris_mask;
-
-    /** Represents a bit mask indicating which SVs
-     * have almanac data.
-     */
-    uint32_t    almanac_mask;
+    /** set to sizeof(GnssSvInfo) */
+    size_t size;
 
     /**
-     * Represents a bit mask indicating which SVs
-     * were used for computing the most recent position fix.
+     * Pseudo-random number for the SV, or Amanac/slot number for Glonass. The
+     * distinction is made by looking at constellation field. Values should be
+     * in the range of:
+     *
+     * - GPS:     1-32
+     * - SBAS:    120-151, 183-192
+     * - GLONASS: 1-24 (slot number)
+     * - QZSS:    193-200
+     * - Galileo: 1-25
+     * - Beidou:  1-35
      */
-    uint32_t    used_in_fix_mask;
+    int prn;
+
+    /** Signal to noise ratio. */
+    float snr;
+
+    /** Elevation of SV in degrees. */
+    float elevation;
+
+    /** Azimuth of SV in degrees. */
+    float azimuth;
+
+    /**
+     * Contains additional data about the given SV. Value should be one of those
+     * GNSS_SV_FLAGS_* constants
+     */
+    GnssSvFlags flags;
+
+    /**
+     * Defines the constellation of the given SV. Value should be one of those
+     * GNSS_CONSTELLATION_* constants
+     */
+    GnssConstellationType constellation;
+
+} GnssSvInfo;
+
+/**
+ * Represents SV status.
+ *
+ * When switching from pre-N to N version of GpsSvStatus:
+ *
+ * 1) Fill in the fields from num_svs through used_in_fix_mask the same way as
+ * was done before, e.g. using the range of 65-88 to report Glonass info,
+ * 201-235 for Beidou, etc. (but with no used_in_fix_mask info - those are
+ * index by prn, and thus for GPS only). This will help ensure compatibility
+ * when a newer GPS HAL is used with an older version of Android.
+ *
+ * 2) Fill in the gnss_sv_list with information about SVs from all
+ * constellations (GPS & other GNSS's) - when this is filled in, this will be
+ * the only source of information about satellite status (e.g. for working with
+ * GpsStatus facing applications), the earlier fields will be ignored.
+ */
+typedef struct {
+    /** set to sizeof(GpsSvStatus) */
+    size_t size;
+
+    /** Number of GPS SVs currently visible, refers to the SVs stored in sv_list */
+    int num_svs;
+
+    /** Contains an array of GPS SV information in legacy GPS format. */
+    GpsSvInfo sv_list[GPS_MAX_SVS];
+
+    /**
+     * Represents a bit mask indicating which GPS SVs have ephemeris data,
+     * refers to sv_list.
+     */
+    uint32_t ephemeris_mask;
+
+    /**
+     * Represents a bit mask indicating which GPS SVs have almanac data, refers
+     * to sv_list.
+     */
+    uint32_t almanac_mask;
+
+    /**
+     * Represents a bit mask indicating which GPS SVs
+     * were used for computing the most recent position fix,
+     * refers to sv_list.
+     */
+    uint32_t used_in_fix_mask;
+
+    /**
+     * Size of the array which contains SV info for all GNSS constellation
+     * except for GPS.
+     */
+    size_t gnss_sv_list_size;
+
+    /**
+     * Pointer to an array of SVs information for all GNSS constellations,
+     * except GPS, which is reported using sv_list
+     */
+    GnssSvInfo* gnss_sv_list;
+
 } GpsSvStatus;
 
-
-/* 2G and 3G */
-/* In 3G lac is discarded */
+/* CellID for 2G, 3G and LTE, used in AGPS. */
 typedef struct {
-    uint16_t type;
+    AGpsRefLocationType type;
+    /** Mobile Country Code. */
     uint16_t mcc;
+    /** Mobile Network Code .*/
     uint16_t mnc;
+    /** Location Area Code in 2G, 3G and LTE. In 3G lac is discarded. In LTE,
+     * lac is populated with tac, to ensure that we don't break old clients that
+     * might rely in the old (wrong) behavior.
+     */
     uint16_t lac;
+    /** Cell id in 2G. Utran Cell id in 3G. Cell Global Id EUTRA in LTE. */
     uint32_t cid;
+    /** Tracking Area Code in LTE. */
+    uint16_t tac;
+    /** Physical Cell id in LTE (not used in 2G and 3G) */
+    uint16_t pcid;
 } AGpsRefLocationCellID;
 
 typedef struct {
@@ -516,20 +634,22 @@
 
 /** Represents ref locations */
 typedef struct {
-    uint16_t type;
+    AGpsRefLocationType type;
     union {
         AGpsRefLocationCellID   cellID;
         AGpsRefLocationMac      mac;
     } u;
 } AGpsRefLocation;
 
-/** Callback with location information.
- *  Can only be called from a thread created by create_thread_cb.
+/**
+ * Callback with location information. Can only be called from a thread created
+ * by create_thread_cb.
  */
 typedef void (* gps_location_callback)(GpsLocation* location);
 
-/** Callback with status information.
- *  Can only be called from a thread created by create_thread_cb.
+/**
+ * Callback with status information. Can only be called from a thread created by
+ * create_thread_cb.
  */
 typedef void (* gps_status_callback)(GpsStatus* status);
 
@@ -539,18 +659,21 @@
  */
 typedef void (* gps_sv_status_callback)(GpsSvStatus* sv_info);
 
-/** Callback for reporting NMEA sentences.
- *  Can only be called from a thread created by create_thread_cb.
+/**
+ * Callback for reporting NMEA sentences. Can only be called from a thread
+ * created by create_thread_cb.
  */
 typedef void (* gps_nmea_callback)(GpsUtcTime timestamp, const char* nmea, int length);
 
-/** Callback to inform framework of the GPS engine's capabilities.
- *  Capability parameter is a bit field of GPS_CAPABILITY_* flags.
+/**
+ * Callback to inform framework of the GPS engine's capabilities. Capability
+ * parameter is a bit field of GPS_CAPABILITY_* flags.
  */
 typedef void (* gps_set_capabilities)(uint32_t capabilities);
 
-/** Callback utility for acquiring the GPS wakelock.
- *  This can be used to prevent the CPU from suspending while handling GPS events.
+/**
+ * Callback utility for acquiring the GPS wakelock. This can be used to prevent
+ * the CPU from suspending while handling GPS events.
  */
 typedef void (* gps_acquire_wakelock)();
 
@@ -560,12 +683,57 @@
 /** Callback for requesting NTP time */
 typedef void (* gps_request_utc_time)();
 
-/** Callback for creating a thread that can call into the Java framework code.
- *  This must be used to create any threads that report events up to the framework.
+/**
+ * Callback for creating a thread that can call into the Java framework code.
+ * This must be used to create any threads that report events up to the
+ * framework.
  */
 typedef pthread_t (* gps_create_thread)(const char* name, void (*start)(void *), void* arg);
 
-/** GPS callback structure. */
+/**
+ * Provides information about how new the underlying GPS/GNSS hardware and
+ * software is.
+ *
+ * This information will be available for Android Test Applications. If a GPS
+ * HAL does not provide this information, it will be considered "2015 or
+ * earlier".
+ *
+ * If a GPS HAL does provide this information, then newer years will need to
+ * meet newer CTS standards. E.g. if the date are 2016 or above, then N+ level
+ * GpsMeasurement support will be verified.
+ */
+typedef struct {
+    /** Set to sizeof(GpsSystemInfo) */
+    size_t   size;
+    /* year in which the last update was made to the underlying hardware/firmware
+     * used to capture GNSS signals, e.g. 2016 */
+    uint16_t year_of_hw;
+} GpsSystemInfo;
+
+/**
+ * Callback to inform framework of the engine's hardware version information.
+ */
+typedef void (*gps_set_system_info)(const GpsSystemInfo* info);
+
+/**
+ * Legacy GPS callback structure.
+ * See GpsCallbacks for more information.
+ */
+typedef struct {
+    /** set to sizeof(GpsCallbacks_v1) */
+    size_t      size;
+    gps_location_callback location_cb;
+    gps_status_callback status_cb;
+    gps_sv_status_callback sv_status_cb;
+    gps_nmea_callback nmea_cb;
+    gps_set_capabilities set_capabilities_cb;
+    gps_acquire_wakelock acquire_wakelock_cb;
+    gps_release_wakelock release_wakelock_cb;
+    gps_create_thread create_thread_cb;
+    gps_request_utc_time request_utc_time_cb;
+} GpsCallbacks_v1;
+
+/** New GPS callback structure. */
 typedef struct {
     /** set to sizeof(GpsCallbacks) */
     size_t      size;
@@ -578,8 +746,17 @@
     gps_release_wakelock release_wakelock_cb;
     gps_create_thread create_thread_cb;
     gps_request_utc_time request_utc_time_cb;
-} GpsCallbacks;
 
+    /**
+     * Callback for the chipset to report system information.
+     *
+     * This field is newly introduced since N. The driver implementation must
+     * check 'size' field against 'sizeof(GpsCallbacks)' and
+     * 'sizeof(GpsCallbacks_v1)' to decide whether the new field is valid before
+     * calling it.
+     */
+    gps_set_system_info set_system_info_cb;
+} GpsCallbacks;
 
 /** Represents the standard GPS interface. */
 typedef struct {
@@ -604,10 +781,10 @@
     int   (*inject_time)(GpsUtcTime time, int64_t timeReference,
                          int uncertainty);
 
-    /** Injects current location from another location provider
-     *  (typically cell ID).
-     *  latitude and longitude are measured in degrees
-     *  expected accuracy is measured in meters
+    /**
+     * Injects current location from another location provider (typically cell
+     * ID). Latitude and longitude are measured in degrees expected accuracy is
+     * measured in meters
      */
     int  (*inject_location)(double latitude, double longitude, float accuracy);
 
@@ -623,10 +800,10 @@
      * preferred_accuracy represents the requested fix accuracy in meters.
      * preferred_time represents the requested time to first fix in milliseconds.
      *
-     * 'mode' parameter should be one of GPS_POSITION_MODE_MS_BASE
+     * 'mode' parameter should be one of GPS_POSITION_MODE_MS_BASED
      * or GPS_POSITION_MODE_STANDALONE.
      * It is allowed by the platform (and it is recommended) to fallback to
-     * GPS_POSITION_MODE_MS_BASE if GPS_POSITION_MODE_MS_ASSISTED is passed in, and
+     * GPS_POSITION_MODE_MS_BASED if GPS_POSITION_MODE_MS_ASSISTED is passed in, and
      * GPS_POSITION_MODE_MS_BASED is supported.
      */
     int   (*set_position_mode)(GpsPositionMode mode, GpsPositionRecurrence recurrence,
@@ -636,9 +813,10 @@
     const void* (*get_extension)(const char* name);
 } GpsInterface;
 
-/** Callback to request the client to download XTRA data.
- *  The client should download XTRA data and inject it by calling inject_xtra_data().
- *  Can only be called from a thread created by create_thread_cb.
+/**
+ * Callback to request the client to download XTRA data. The client should
+ * download XTRA data and inject it by calling inject_xtra_data(). Can only be
+ * called from a thread created by create_thread_cb.
  */
 typedef void (* gps_xtra_download_request)();
 
@@ -673,36 +851,11 @@
     size_t (*get_internal_state)(char* buffer, size_t bufferSize);
 } GpsDebugInterface;
 
-#pragma pack(push,4)
-// We need to keep the alignment of this data structure to 4-bytes, to ensure that in 64-bit
-// environments the size of this legacy definition does not collide with _v2. Implementations should
-// be using _v2 and _v3, so it's OK to pay the 'unaligned' penalty in 64-bit if an old
-// implementation is still in use.
-
-/** Represents the status of AGPS. */
+/*
+ * Represents the status of AGPS augmented to support IPv4 and IPv6.
+ */
 typedef struct {
-    /** set to sizeof(AGpsStatus_v1) */
-    size_t          size;
-
-    AGpsType        type;
-    AGpsStatusValue status;
-} AGpsStatus_v1;
-
-#pragma pack(pop)
-
-/** Represents the status of AGPS augmented with a IPv4 address field. */
-typedef struct {
-    /** set to sizeof(AGpsStatus_v2) */
-    size_t          size;
-
-    AGpsType        type;
-    AGpsStatusValue status;
-    uint32_t        ipaddr;
-} AGpsStatus_v2;
-
-/* Represents the status of AGPS augmented to support IPv4 and IPv6. */
-typedef struct {
-    /** set to sizeof(AGpsStatus_v3) */
+    /** set to sizeof(AGpsStatus) */
     size_t                  size;
 
     AGpsType                type;
@@ -717,14 +870,13 @@
     /**
      * Must contain the IPv4 (AF_INET) or IPv6 (AF_INET6) address to report.
      * Any other value of addr.ss_family will be rejected.
-     * */
+     */
     struct sockaddr_storage addr;
-} AGpsStatus_v3;
+} AGpsStatus;
 
-typedef AGpsStatus_v3     AGpsStatus;
-
-/** Callback with AGPS status information.
- *  Can only be called from a thread created by create_thread_cb.
+/**
+ * Callback with AGPS status information. Can only be called from a thread
+ * created by create_thread_cb.
  */
 typedef void (* agps_status_callback)(AGpsStatus* status);
 
@@ -734,42 +886,12 @@
     gps_create_thread create_thread_cb;
 } AGpsCallbacks;
 
-
-/** Extended interface for AGPS support. */
-typedef struct {
-    /** set to sizeof(AGpsInterface_v1) */
-    size_t          size;
-
-    /**
-     * Opens the AGPS interface and provides the callback routines
-     * to the implementation of this interface.
-     */
-    void  (*init)( AGpsCallbacks* callbacks );
-    /**
-     * Notifies that a data connection is available and sets
-     * the name of the APN to be used for SUPL.
-     */
-    int  (*data_conn_open)( const char* apn );
-    /**
-     * Notifies that the AGPS data connection has been closed.
-     */
-    int  (*data_conn_closed)();
-    /**
-     * Notifies that a data connection is not available for AGPS.
-     */
-    int  (*data_conn_failed)();
-    /**
-     * Sets the hostname and port for the AGPS server.
-     */
-    int  (*set_server)( AGpsType type, const char* hostname, int port );
-} AGpsInterface_v1;
-
 /**
  * Extended interface for AGPS support, it is augmented to enable to pass
  * extra APN data.
  */
 typedef struct {
-    /** set to sizeof(AGpsInterface_v2) */
+    /** set to sizeof(AGpsInterface) */
     size_t size;
 
     /**
@@ -803,9 +925,7 @@
     int (*data_conn_open_with_apn_ip_type)(
             const char* apn,
             ApnIpType apnIpType);
-} AGpsInterface_v2;
-
-typedef AGpsInterface_v2    AGpsInterface;
+} AGpsInterface;
 
 /** Error codes associated with certificate operations */
 #define AGPS_CERTIFICATE_OPERATION_SUCCESS               0
@@ -936,8 +1056,9 @@
 
 } GpsNiNotification;
 
-/** Callback with NI notification.
- *  Can only be called from a thread created by create_thread_cb.
+/**
+ * Callback with NI notification. Can only be called from a thread created by
+ * create_thread_cb.
  */
 typedef void (*gps_ni_notify_callback)(GpsNiNotification *notification);
 
@@ -1280,7 +1401,6 @@
    void (*remove_geofence_area) (int32_t geofence_id);
 } GpsGeofencingInterface;
 
-
 /**
  * Represents an estimate of the GPS clock time.
  */
@@ -1302,7 +1422,7 @@
 
     /**
      * Indicates the type of time reported by the 'time_ns' field.
-     * This is a Mandatory field.
+     * This is a mandatory field.
      */
     GpsClockType type;
 
@@ -1321,7 +1441,11 @@
      * Sub-nanosecond accuracy can be provided by means of the 'bias' field.
      * The value contains the 'time uncertainty' in it.
      *
-     * This is a Mandatory field.
+     * This field is mandatory.
+     *
+     * For devices where GpsSystemInfo's year_of_hw is set to 2016+, it is
+     * mandatory that it contains the value from the 'local hardware clock, and
+     * thus GPS_CLOCK_TYPE_LOCAL_HW_TIME must be set in 'type' field.
      */
     int64_t time_ns;
 
@@ -1329,8 +1453,9 @@
      * 1-Sigma uncertainty associated with the clock's time in nanoseconds.
      * The uncertainty is represented as an absolute (single sided) value.
      *
-     * This value should be set if GPS_CLOCK_TYPE_GPS_TIME is set.
-     * If the data is available 'flags' must contain GPS_CLOCK_HAS_TIME_UNCERTAINTY.
+     * If the data is available, 'flags' must contain
+     * GPS_CLOCK_HAS_TIME_UNCERTAINTY. If GPS has computed a position fix, this
+     * field is mandatory and must be populated.
      */
     double time_uncertainty_ns;
 
@@ -1345,8 +1470,9 @@
      *      true time (GPS time) = time_ns + (full_bias_ns + bias_ns)
      *
      * This value contains the 'bias uncertainty' in it.
-     * If the data is available 'flags' must contain GPS_CLOCK_HAS_FULL_BIAS.
-
+     * If GPS has computed a position fix this field is mandatory and must be
+     * populated. If the data is available 'flags' must contain
+     * GPS_CLOCK_HAS_FULL_BIAS.
      */
     int64_t full_bias_ns;
 
@@ -1354,7 +1480,9 @@
      * Sub-nanosecond bias.
      * The value contains the 'bias uncertainty' in it.
      *
-     * If the data is available 'flags' must contain GPS_CLOCK_HAS_BIAS.
+     * If the data is available 'flags' must contain GPS_CLOCK_HAS_BIAS. If GPS
+     * has computed a position fix, this field is mandatory and must be
+     * populated.
      */
     double bias_ns;
 
@@ -1362,7 +1490,9 @@
      * 1-Sigma uncertainty associated with the clock's bias in nanoseconds.
      * The uncertainty is represented as an absolute (single sided) value.
      *
-     * If the data is available 'flags' must contain GPS_CLOCK_HAS_BIAS_UNCERTAINTY.
+     * If the data is available 'flags' must contain
+     * GPS_CLOCK_HAS_BIAS_UNCERTAINTY. If GPS has computed a position fix this
+     * field is mandatory and must be populated.
      */
     double bias_uncertainty_ns;
 
@@ -1373,8 +1503,10 @@
      * The value contains the 'drift uncertainty' in it.
      * If the data is available 'flags' must contain GPS_CLOCK_HAS_DRIFT.
      *
-     * If GpsMeasurement's 'flags' field contains GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE,
-     * it is encouraged that this field is also provided.
+     * If GpsMeasurement's 'flags' field contains
+     * GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE, it is encouraged that
+     * this field is also provided. If GPS has computed a position fix this
+     * field is mandatory and must be populated.
      */
     double drift_nsps;
 
@@ -1382,9 +1514,30 @@
      * 1-Sigma uncertainty associated with the clock's drift in nanoseconds (per second).
      * The uncertainty is represented as an absolute (single sided) value.
      *
-     * If the data is available 'flags' must contain GPS_CLOCK_HAS_DRIFT_UNCERTAINTY.
+     * If the data is available 'flags' must contain
+     * GPS_CLOCK_HAS_DRIFT_UNCERTAINTY. If GPS has computed a position fix this
+     * field is mandatory and must be populated.
      */
     double drift_uncertainty_nsps;
+
+    /**
+     * When the GPS_CLOCK_TYPE_LOCAL_HW_TIME is set, this field is mandatory.
+     *
+     * A "discontinuity" is meant to cover the case of a switch from one source
+     * of clock to another.  A single free-running crystal oscillator (XO)
+     * should generally not have any discontinuities, and this can be set to 0.
+     * If, however, the time_ns value (HW clock) is derived from a composite of
+     * sources, that is not as smooth as a typical XO, then this value shall be
+     * set to the time_ns value since which the time_ns has been derived from a
+     * single, high quality clock (XO like, or better, that's typically used
+     * during continuous GPS signal sampling.)
+     *
+     * It is expected, esp. during periods where there are few GNSS signals
+     * available, that the HW clock be discontinuity-free as long as possible,
+     * as this avoids the need to use (waste) a GPS measurement to fully
+     * re-solve for the clock bias and drift.
+     */
+    int64_t time_of_last_hw_clock_discontinuity_ns;
 } GpsClock;
 
 /**
@@ -1399,7 +1552,7 @@
 
     /**
      * Pseudo-random number in the range of [1, 32]
-     * This is a Mandatory value.
+     * This is a mandatory value.
      */
     int8_t prn;
 
@@ -1412,7 +1565,7 @@
      *      measurement time = GpsClock::time_ns + time_offset_ns
      *
      * It provides an individual time-stamp for the measurement, and allows sub-nanosecond accuracy.
-     * This is a Mandatory value.
+     * This is a mandatory value.
      */
     double time_offset_ns;
 
@@ -1420,7 +1573,7 @@
      * Per satellite sync state. It represents the current sync state for the associated satellite.
      * Based on the sync state, the 'received GPS tow' field should be interpreted accordingly.
      *
-     * This is a Mandatory value.
+     * This is a mandatory value.
      */
     GpsMeasurementState state;
 
@@ -1454,7 +1607,7 @@
      * Carrier-to-noise density in dB-Hz, in the range [0, 63].
      * It contains the measured C/N0 value for the signal at the antenna input.
      *
-     * This is a Mandatory value.
+     * This is a mandatory value.
      */
     double c_n0_dbhz;
 
@@ -1463,13 +1616,9 @@
      * The correction of a given Pseudorange Rate value includes corrections for receiver and
      * satellite clock frequency errors.
      *
-     * If GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE is set in 'flags' field, this field must
-     * be populated with the 'uncorrected' reading.
-     * If GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE is not set in 'flags' field, this field
-     * must be populated with the 'corrected' reading. This is the default behavior.
-     *
      * It is encouraged to provide the 'uncorrected' 'pseudorange rate', and provide GpsClock's
-     * 'drift' field as well.
+     * 'drift' field as well. When providing the uncorrected pseudorange rate,
+     * do not apply the corrections described above.
      *
      * The value includes the 'pseudorange rate uncertainty' in it.
      * A positive 'uncorrected' value indicates that the SV is moving away from the receiver.
@@ -1478,15 +1627,22 @@
      * shift' is given by the equation:
      *      pseudorange rate = -k * doppler shift   (where k is a constant)
      *
-     * This is a Mandatory value.
+     * This field should be based on the signal energy doppler measurement. (See
+     * also pseudorate_rate_carrier_mps for a similar field, based on carrier
+     * phase changes.)
+     *
+     * This is a mandatory value. It is mandatory (and expected) that it
+     * contains the 'uncorrected' reading, and
+     * GPS_MEASUREMENT_HAS_UNCORRECTED_PSEUDORANGE_RATE must be set in 'flags'
+     * field.
      */
     double pseudorange_rate_mps;
 
     /**
-     * 1-Sigma uncertainty of the pseudurange rate in m/s.
+     * 1-Sigma uncertainty of the pseudorange_rate_mps.
      * The uncertainty is represented as an absolute (single sided) value.
      *
-     * This is a Mandatory value.
+     * This is a mandatory value.
      */
     double pseudorange_rate_uncertainty_mps;
 
@@ -1494,7 +1650,7 @@
      * Accumulated delta range's state. It indicates whether ADR is reset or there is a cycle slip
      * (indicating loss of lock).
      *
-     * This is a Mandatory value.
+     * This is a mandatory value.
      */
     GpsAccumulatedDeltaRangeState accumulated_delta_range_state;
 
@@ -1651,7 +1807,7 @@
      * Azimuth in degrees, in the range [0, 360).
      * The value contains the 'azimuth uncertainty' in it.
      * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_AZIMUTH.
-     *  */
+     */
     double azimuth_deg;
 
     /**
@@ -1667,6 +1823,41 @@
      * If the data is available, 'flags' must contain GPS_MEASUREMENT_HAS_USED_IN_FIX.
      */
     bool used_in_fix;
+
+    /**
+     * Pseudorange rate (based on carrier phase changes) at the timestamp in m/s.
+     *
+     * The correction of a given Pseudorange Rate value includes corrections for
+     * receiver and satellite clock frequency errors.
+     *
+     * It is mandatory to provide the 'uncorrected' 'pseudorange rate' in this
+     * field. (Do not apply the corrections described above.)
+     *
+     * The value includes the 'pseudorange rate (carrier) uncertainty' in it. A
+     * positive 'uncorrected' value indicates that the SV is moving away from
+     * the receiver.
+     *
+     * The sign of the 'uncorrected' 'pseudorange rate' and its relation to the
+     * sign of 'doppler shift' is given by the equation:
+     *
+     *      pseudorange rate = -k * doppler shift   (where k is a constant)
+     *
+     * This field must be based on changes in the carrier phase measurement.
+     * (See pseudorange_rate_mps for a similar field, based on signal energy
+     * doppler.)
+     *
+     * It is mandatory that this value be provided, when signals are
+     * sufficiently strong, e.g. signals from a GPS simulator at >= 30 dB-Hz.
+     */
+    double pseudorange_rate_carrier_mps;
+    /**
+     * 1-Sigma uncertainty of the pseudorange_rate_carrier_mps.
+     * The uncertainty is represented as an absolute (single sided) value.
+     *
+     * This is a mandatory value when pseudorange_rate_carrier_mps is provided.
+     */
+    double pseudorange_rate_carrier_uncertainty_mps;
+
 } GpsMeasurement;
 
 /** Represents a reading of GPS measurements. */
@@ -1740,13 +1931,13 @@
 
     /**
      * Pseudo-random number in the range of [1, 32]
-     * This is a Mandatory value.
+     * This is a mandatory value.
      */
     int8_t prn;
 
     /**
      * The type of message contained in the structure.
-     * This is a Mandatory value.
+     * This is a mandatory value.
      */
     GpsNavigationMessageType type;
 
@@ -1778,7 +1969,7 @@
      * If this value is different from zero, 'data' must point to an array of the same size.
      * e.g. for L1 C/A the size of the sub-frame will be 40 bytes (10 words, 30 bits/word).
      *
-     * This is a Mandatory value.
+     * This is a mandatory value.
      */
     size_t data_length;
 
diff --git a/include/hardware/gps_internal.h b/include/hardware/gps_internal.h
new file mode 100644
index 0000000..cd83636
--- /dev/null
+++ b/include/hardware/gps_internal.h
@@ -0,0 +1,167 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_GPS_INTERNAL_H
+#define ANDROID_INCLUDE_HARDWARE_GPS_INTERNAL_H
+
+#include "hardware/gps.h"
+
+/****************************************************************************
+ * This file contains legacy structs that are deprecated/retired from gps.h *
+ ****************************************************************************/
+
+__BEGIN_DECLS
+
+/**
+ * Legacy struct to represent SV status.
+ * See GpsSvStatus_v2 for more information.
+ */
+typedef struct {
+    /** set to sizeof(GpsSvStatus_v1) */
+    size_t          size;
+    int         num_svs;
+    GpsSvInfo   sv_list[GPS_MAX_SVS];
+    uint32_t    ephemeris_mask;
+    uint32_t    almanac_mask;
+    uint32_t    used_in_fix_mask;
+} GpsSvStatus_v1;
+
+#pragma pack(push,4)
+// We need to keep the alignment of this data structure to 4-bytes, to ensure that in 64-bit
+// environments the size of this legacy definition does not collide with _v2. Implementations should
+// be using _v2 and _v3, so it's OK to pay the 'unaligned' penalty in 64-bit if an old
+// implementation is still in use.
+
+/**
+ * Legacy struct to represent the status of AGPS.
+ */
+typedef struct {
+    /** set to sizeof(AGpsStatus_v1) */
+    size_t          size;
+    AGpsType        type;
+    AGpsStatusValue status;
+} AGpsStatus_v1;
+
+#pragma pack(pop)
+
+/**
+ * Legacy struct to represent the status of AGPS augmented with a IPv4 address
+ * field.
+ */
+typedef struct {
+    /** set to sizeof(AGpsStatus_v2) */
+    size_t          size;
+    AGpsType        type;
+    AGpsStatusValue status;
+
+    /*-------------------- New fields in _v2 --------------------*/
+
+    uint32_t        ipaddr;
+} AGpsStatus_v2;
+
+/**
+ * Legacy extended interface for AGPS support.
+ * See AGpsInterface_v2 for more information.
+ */
+typedef struct {
+    /** set to sizeof(AGpsInterface_v1) */
+    size_t          size;
+    void  (*init)( AGpsCallbacks* callbacks );
+    int  (*data_conn_open)( const char* apn );
+    int  (*data_conn_closed)();
+    int  (*data_conn_failed)();
+    int  (*set_server)( AGpsType type, const char* hostname, int port );
+} AGpsInterface_v1;
+
+/**
+ * Legacy struct to represent an estimate of the GPS clock time.
+ * See GpsClock_v2 for more details.
+ */
+typedef struct {
+    /** set to sizeof(GpsClock_v1) */
+    size_t size;
+    GpsClockFlags flags;
+    int16_t leap_second;
+    GpsClockType type;
+    int64_t time_ns;
+    double time_uncertainty_ns;
+    int64_t full_bias_ns;
+    double bias_ns;
+    double bias_uncertainty_ns;
+    double drift_nsps;
+    double drift_uncertainty_nsps;
+} GpsClock_v1;
+
+/**
+ * Legacy struct to represent a GPS Measurement, it contains raw and computed
+ * information.
+ * See GpsMeasurement_v2 for more details.
+ */
+typedef struct {
+    /** set to sizeof(GpsMeasurement_v1) */
+    size_t size;
+    GpsMeasurementFlags flags;
+    int8_t prn;
+    double time_offset_ns;
+    GpsMeasurementState state;
+    int64_t received_gps_tow_ns;
+    int64_t received_gps_tow_uncertainty_ns;
+    double c_n0_dbhz;
+    double pseudorange_rate_mps;
+    double pseudorange_rate_uncertainty_mps;
+    GpsAccumulatedDeltaRangeState accumulated_delta_range_state;
+    double accumulated_delta_range_m;
+    double accumulated_delta_range_uncertainty_m;
+    double pseudorange_m;
+    double pseudorange_uncertainty_m;
+    double code_phase_chips;
+    double code_phase_uncertainty_chips;
+    float carrier_frequency_hz;
+    int64_t carrier_cycles;
+    double carrier_phase;
+    double carrier_phase_uncertainty;
+    GpsLossOfLock loss_of_lock;
+    int32_t bit_number;
+    int16_t time_from_last_bit_ms;
+    double doppler_shift_hz;
+    double doppler_shift_uncertainty_hz;
+    GpsMultipathIndicator multipath_indicator;
+    double snr_db;
+    double elevation_deg;
+    double elevation_uncertainty_deg;
+    double azimuth_deg;
+    double azimuth_uncertainty_deg;
+    bool used_in_fix;
+} GpsMeasurement_v1;
+
+/** Represents a reading of GPS measurements. */
+typedef struct {
+    /** set to sizeof(GpsData_v1) */
+    size_t size;
+
+    /** Number of measurements. */
+    size_t measurement_count;
+
+    /** The array of measurements. */
+    GpsMeasurement_v1 measurements[GPS_MAX_MEASUREMENT];
+
+    /** The GPS clock time reading. */
+    GpsClock_v1 clock;
+} GpsData_v1;
+
+__END_DECLS
+
+#endif /* ANDROID_INCLUDE_HARDWARE_GPS_INTERNAL_H */
diff --git a/include/hardware/hardware_properties.h b/include/hardware/hardware_properties.h
new file mode 100644
index 0000000..7c9bd4e
--- /dev/null
+++ b/include/hardware/hardware_properties.h
@@ -0,0 +1,92 @@
+/*
+ * 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_INCLUDE_HARDWARE_HARDWAREPROPERTIES_H
+#define ANDROID_INCLUDE_HARDWARE_HARDWAREPROPERTIES_H
+
+#include <stdint.h>
+#include <sys/cdefs.h>
+#include <sys/types.h>
+
+#include <hardware/hardware.h>
+
+__BEGIN_DECLS
+
+#define HARDWARE_PROPERTIES_HARDWARE_MODULE_API_VERSION_0_1 HARDWARE_MODULE_API_VERSION(0, 1)
+
+/**
+ * The id of this module
+ */
+#define HARDWARE_PROPERTIES_HARDWARE_MODULE_ID "hardware_properties"
+
+/**
+ * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM
+ * and the fields of this data structure must begin with hw_module_t
+ * followed by module specific information.
+ */
+typedef struct hardware_properties_module {
+    struct hw_module_t common;
+
+    /*
+     * (*getCpuTemperatures) is called to get CPU temperatures in Celsius of
+     * each core.
+     *
+     * Returns number of cores or negative value on error.
+     *
+     */
+    ssize_t (*getCpuTemperatures)(struct hardware_properties_module *module, float **temps);
+
+    /*
+     * (*getGpuTemperatures) is called to get GPU temperatures in Celsius of
+     * each GPU.
+     *
+     * Returns number of GPUs or negative value on error.
+     *
+     */
+    ssize_t (*getGpuTemperatures)(struct hardware_properties_module *module, float **temps);
+
+    /*
+     * (*getBatteryTemperatures) is called to get battery temperatures in
+     * Celsius.
+     *
+     * Returns number of battery temperatures or negative value on error.
+     *
+     */
+    ssize_t (*getBatteryTemperatures)(struct hardware_properties_module *module, float **temps);
+
+    /*
+     * (*getCpuUsages) is called to get CPU usage information of each core:
+     * active and total times in ms since first boot.
+     *
+     * Returns number of cores or negative value on error.
+     *
+     */
+    ssize_t (*getCpuUsages)(struct hardware_properties_module *module,
+                            int64_t **active_times, int64_t **total_times);
+
+    /*
+     * (*getFanSpeeds) is called to get the fan speeds in RPM of each fan.
+     *
+     * Returns number of fans or negative value on error.
+     *
+     */
+    ssize_t (*getFanSpeeds)(struct hardware_properties_module *module,
+                        float **fan_speeds);
+} hardware_properties_module_t;
+
+__END_DECLS
+
+#endif  // ANDROID_INCLUDE_HARDWARE_HARDWAREPROPERTIES_H
diff --git a/include/hardware/hwcomposer.h b/include/hardware/hwcomposer.h
index aa466b3..61218bb 100644
--- a/include/hardware/hwcomposer.h
+++ b/include/hardware/hwcomposer.h
@@ -37,42 +37,6 @@
 
 /*****************************************************************************/
 
-/**
- * The id of this module
- */
-#define HWC_HARDWARE_MODULE_ID "hwcomposer"
-
-/**
- * Name of the sensors device to open
- */
-#define HWC_HARDWARE_COMPOSER   "composer"
-
-typedef struct hwc_rect {
-    int left;
-    int top;
-    int right;
-    int bottom;
-} hwc_rect_t;
-
-typedef struct hwc_frect {
-    float left;
-    float top;
-    float right;
-    float bottom;
-} hwc_frect_t;
-
-typedef struct hwc_region {
-    size_t numRects;
-    hwc_rect_t const* rects;
-} hwc_region_t;
-
-typedef struct hwc_color {
-    uint8_t r;
-    uint8_t g;
-    uint8_t b;
-    uint8_t a;
-} hwc_color_t;
-
 typedef struct hwc_layer_1 {
     /*
      * compositionType is used to specify this layer's type and is set by either
diff --git a/include/hardware/hwcomposer2.h b/include/hardware/hwcomposer2.h
new file mode 100644
index 0000000..e6aac8d
--- /dev/null
+++ b/include/hardware/hwcomposer2.h
@@ -0,0 +1,1900 @@
+/*
+ * Copyright 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_HWCOMPOSER2_H
+#define ANDROID_HARDWARE_HWCOMPOSER2_H
+
+#include <hardware/hardware.h>
+
+#include "hwcomposer_defs.h"
+
+__BEGIN_DECLS
+
+/*
+ * Enums
+ *
+ * For most of these enums, there is an invalid value defined to be 0. This is
+ * an attempt to catch uninitialized fields, and these values should not be
+ * used.
+ */
+
+/* Display attributes queryable through getDisplayAttribute */
+typedef enum {
+    HWC2_ATTRIBUTE_INVALID = 0,
+
+    /* Dimensions in pixels */
+    HWC2_ATTRIBUTE_WIDTH = 1,
+    HWC2_ATTRIBUTE_HEIGHT = 2,
+
+    /* Vsync period in nanoseconds */
+    HWC2_ATTRIBUTE_VSYNC_PERIOD = 3,
+
+    /* Dots per thousand inches (DPI * 1000). Scaling by 1000 allows these
+     * numbers to be stored in an int32_t without losing too much precision. If
+     * the DPI for a configuration is unavailable or is considered unreliable,
+     * the device may return -1 instead */
+    HWC2_ATTRIBUTE_DPI_X = 4,
+    HWC2_ATTRIBUTE_DPI_Y = 5,
+} hwc2_attribute_t;
+
+/* Blend modes, settable per layer */
+typedef enum {
+    HWC2_BLEND_MODE_INVALID = 0,
+
+    /* colorOut = colorSrc */
+    HWC2_BLEND_MODE_NONE = 1,
+
+    /* colorOut = colorSrc + colorDst * (1 - alphaSrc) */
+    HWC2_BLEND_MODE_PREMULTIPLIED = 2,
+
+    /* colorOut = colorSrc * alphaSrc + colorDst * (1 - alphaSrc) */
+    HWC2_BLEND_MODE_COVERAGE = 3,
+} hwc2_blend_mode_t;
+
+/* See the 'Callbacks' section for more detailed descriptions of what these
+ * functions do */
+typedef enum {
+    HWC2_CALLBACK_INVALID = 0,
+    HWC2_CALLBACK_HOTPLUG = 1,
+    HWC2_CALLBACK_REFRESH = 2,
+    HWC2_CALLBACK_VSYNC = 3,
+} hwc2_callback_descriptor_t;
+
+/* Optional capabilities which may be supported by some devices. The particular
+ * set of supported capabilities for a given device may be retrieved using
+ * getCapabilities. */
+typedef enum {
+    HWC2_CAPABILITY_INVALID = 0,
+
+    /* Specifies that the device supports sideband stream layers, for which
+     * buffer content updates and other synchronization will not be provided
+     * through the usual validate/present cycle and must be handled by an
+     * external implementation-defined mechanism. Only changes to layer state
+     * (such as position, size, etc.) need to be performed through the
+     * validate/present cycle. */
+    HWC2_CAPABILITY_SIDEBAND_STREAM = 1,
+} hwc2_capability_t;
+
+/* Possible composition types for a given layer */
+typedef enum {
+    HWC2_COMPOSITION_INVALID = 0,
+
+    /* The client will composite this layer into the client target buffer
+     * (provided to the device through setClientTarget).
+     *
+     * The device must not request any composition type changes for layers of
+     * this type. */
+    HWC2_COMPOSITION_CLIENT = 1,
+
+    /* The device will handle the composition of this layer through a hardware
+     * overlay or other similar means.
+     *
+     * Upon validateDisplay, the device may request a change from this type to
+     * HWC2_COMPOSITION_CLIENT. */
+    HWC2_COMPOSITION_DEVICE = 2,
+
+    /* The device will render this layer using the color set through
+     * setLayerColor. If this functionality is not supported on a layer that the
+     * client sets to HWC2_COMPOSITION_SOLID_COLOR, the device must request that
+     * the composition type of that layer is changed to HWC2_COMPOSITION_CLIENT
+     * upon the next call to validateDisplay.
+     *
+     * Upon validateDisplay, the device may request a change from this type to
+     * HWC2_COMPOSITION_CLIENT. */
+    HWC2_COMPOSITION_SOLID_COLOR = 3,
+
+    /* Similar to DEVICE, but the position of this layer may also be set
+     * asynchronously through setCursorPosition. If this functionality is not
+     * supported on a layer that the client sets to HWC2_COMPOSITION_CURSOR, the
+     * device must request that the composition type of that layer is changed to
+     * HWC2_COMPOSITION_CLIENT upon the next call to validateDisplay.
+     *
+     * Upon validateDisplay, the device may request a change from this type to
+     * either HWC2_COMPOSITION_DEVICE or HWC2_COMPOSITION_CLIENT. Changing to
+     * HWC2_COMPOSITION_DEVICE will prevent the use of setCursorPosition but
+     * still permit the device to composite the layer. */
+    HWC2_COMPOSITION_CURSOR = 4,
+
+    /* The device will handle the composition of this layer, as well as its
+     * buffer updates and content synchronization. Only supported on devices
+     * which provide HWC2_CAPABILITY_SIDEBAND_STREAM.
+     *
+     * Upon validateDisplay, the device may request a change from this type to
+     * either HWC2_COMPOSITION_DEVICE or HWC2_COMPOSITION_CLIENT, but it is
+     * unlikely that content will display correctly in these cases. */
+    HWC2_COMPOSITION_SIDEBAND = 5,
+} hwc2_composition_t;
+
+/* Possible connection options from the hotplug callback */
+typedef enum {
+    HWC2_CONNECTION_INVALID = 0,
+
+    /* The display has been connected */
+    HWC2_CONNECTION_CONNECTED = 1,
+
+    /* The display has been disconnected */
+    HWC2_CONNECTION_DISCONNECTED = 2,
+} hwc2_connection_t;
+
+/* Display requests returned by getDisplayRequests */
+typedef enum {
+    /* Instructs the client to provide a new client target buffer, even if no
+     * layers are marked for client composition. */
+    HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET = 1 << 0,
+
+    /* Instructs the client to write the result of client composition directly
+     * into the virtual display output buffer. If any of the layers are not
+     * marked as HWC2_COMPOSITION_CLIENT or the given display is not a virtual
+     * display, this request has no effect. */
+    HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT = 1 << 1,
+} hwc2_display_request_t;
+
+/* Display types returned by getDisplayType */
+typedef enum {
+    HWC2_DISPLAY_TYPE_INVALID = 0,
+
+    /* All physical displays, including both internal displays and hotpluggable
+     * external displays */
+    HWC2_DISPLAY_TYPE_PHYSICAL = 1,
+
+    /* Virtual displays created by createVirtualDisplay */
+    HWC2_DISPLAY_TYPE_VIRTUAL = 2,
+} hwc2_display_type_t;
+
+/* Return codes from all functions */
+typedef enum {
+    HWC2_ERROR_NONE = 0,
+    HWC2_ERROR_BAD_CONFIG,
+    HWC2_ERROR_BAD_DISPLAY,
+    HWC2_ERROR_BAD_LAYER,
+    HWC2_ERROR_BAD_PARAMETER,
+    HWC2_ERROR_HAS_CHANGES,
+    HWC2_ERROR_NO_RESOURCES,
+    HWC2_ERROR_NOT_VALIDATED,
+    HWC2_ERROR_UNSUPPORTED,
+} hwc2_error_t;
+
+/* Function descriptors for use with getFunction */
+typedef enum {
+    HWC2_FUNCTION_INVALID = 0,
+    HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES,
+    HWC2_FUNCTION_CREATE_LAYER,
+    HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY,
+    HWC2_FUNCTION_DESTROY_LAYER,
+    HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY,
+    HWC2_FUNCTION_DUMP,
+    HWC2_FUNCTION_GET_ACTIVE_CONFIG,
+    HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES,
+    HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT,
+    HWC2_FUNCTION_GET_COLOR_MODES,
+    HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE,
+    HWC2_FUNCTION_GET_DISPLAY_CONFIGS,
+    HWC2_FUNCTION_GET_DISPLAY_NAME,
+    HWC2_FUNCTION_GET_DISPLAY_REQUESTS,
+    HWC2_FUNCTION_GET_DISPLAY_TYPE,
+    HWC2_FUNCTION_GET_DOZE_SUPPORT,
+    HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT,
+    HWC2_FUNCTION_GET_RELEASE_FENCES,
+    HWC2_FUNCTION_PRESENT_DISPLAY,
+    HWC2_FUNCTION_REGISTER_CALLBACK,
+    HWC2_FUNCTION_SET_ACTIVE_CONFIG,
+    HWC2_FUNCTION_SET_CLIENT_TARGET,
+    HWC2_FUNCTION_SET_COLOR_MODE,
+    HWC2_FUNCTION_SET_COLOR_TRANSFORM,
+    HWC2_FUNCTION_SET_CURSOR_POSITION,
+    HWC2_FUNCTION_SET_LAYER_BLEND_MODE,
+    HWC2_FUNCTION_SET_LAYER_BUFFER,
+    HWC2_FUNCTION_SET_LAYER_COLOR,
+    HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE,
+    HWC2_FUNCTION_SET_LAYER_DATASPACE,
+    HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME,
+    HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA,
+    HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM,
+    HWC2_FUNCTION_SET_LAYER_SOURCE_CROP,
+    HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE,
+    HWC2_FUNCTION_SET_LAYER_TRANSFORM,
+    HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION,
+    HWC2_FUNCTION_SET_LAYER_Z_ORDER,
+    HWC2_FUNCTION_SET_OUTPUT_BUFFER,
+    HWC2_FUNCTION_SET_POWER_MODE,
+    HWC2_FUNCTION_SET_VSYNC_ENABLED,
+    HWC2_FUNCTION_VALIDATE_DISPLAY,
+} hwc2_function_descriptor_t;
+
+/* Layer requests returned from getDisplayRequests. */
+typedef enum {
+    /* The client should clear its target with transparent pixels where this
+     * layer would be. The client may ignore this request if the layer must be
+     * blended. */
+    HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET = 1 << 0,
+} hwc2_layer_request_t;
+
+/* Power modes for use with setPowerMode */
+typedef enum {
+    /* The display is fully off (blanked) */
+    HWC2_POWER_MODE_OFF = 0,
+
+    /* These are optional low power modes. getDozeSupport may be called to
+     * determine whether a given display supports these modes. */
+
+    /* The display is turned on and configured in a low power state that is
+     * suitable for presenting ambient information to the user, possibly with
+     * lower fidelity than HWC2_POWER_MODE_ON, but with greater efficiency. */
+    HWC2_POWER_MODE_DOZE = 1,
+
+    /* The display is configured as in HWC2_POWER_MODE_DOZE but may stop
+     * applying display updates from the client. This is effectively a hint to
+     * the device that drawing to the display has been suspended and that the
+     * the device should remain on in a low power state and continue displaying
+     * its current contents indefinitely until the power mode changes.
+     *
+     * This mode may also be used as a signal to enable hardware-based doze
+     * functionality. In this case, the device is free to take over the display
+     * and manage it autonomously to implement a low power always-on display. */
+    HWC2_POWER_MODE_DOZE_SUSPEND = 3,
+
+    /* The display is fully on */
+    HWC2_POWER_MODE_ON = 2,
+} hwc2_power_mode_t;
+
+/* Vsync values passed to setVsyncEnabled */
+typedef enum {
+    HWC2_VSYNC_INVALID = 0,
+
+    /* Enable vsync */
+    HWC2_VSYNC_ENABLE = 1,
+
+    /* Disable vsync */
+    HWC2_VSYNC_DISABLE = 2,
+} hwc2_vsync_t;
+
+/*
+ * Stringification Functions
+ */
+
+#ifdef HWC2_INCLUDE_STRINGIFICATION
+
+static inline const char* getAttributeName(hwc2_attribute_t attribute) {
+    switch (attribute) {
+        case HWC2_ATTRIBUTE_INVALID: return "Invalid";
+        case HWC2_ATTRIBUTE_WIDTH: return "Width";
+        case HWC2_ATTRIBUTE_HEIGHT: return "Height";
+        case HWC2_ATTRIBUTE_VSYNC_PERIOD: return "VsyncPeriod";
+        case HWC2_ATTRIBUTE_DPI_X: return "DpiX";
+        case HWC2_ATTRIBUTE_DPI_Y: return "DpiY";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getBlendModeName(hwc2_blend_mode_t mode) {
+    switch (mode) {
+        case HWC2_BLEND_MODE_INVALID: return "Invalid";
+        case HWC2_BLEND_MODE_NONE: return "None";
+        case HWC2_BLEND_MODE_PREMULTIPLIED: return "Premultiplied";
+        case HWC2_BLEND_MODE_COVERAGE: return "Coverage";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getCallbackDescriptorName(
+        hwc2_callback_descriptor_t desc) {
+    switch (desc) {
+        case HWC2_CALLBACK_INVALID: return "Invalid";
+        case HWC2_CALLBACK_HOTPLUG: return "Hotplug";
+        case HWC2_CALLBACK_REFRESH: return "Refresh";
+        case HWC2_CALLBACK_VSYNC: return "Vsync";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getCapabilityName(hwc2_capability_t capability) {
+    switch (capability) {
+        case HWC2_CAPABILITY_INVALID: return "Invalid";
+        case HWC2_CAPABILITY_SIDEBAND_STREAM: return "SidebandStream";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getCompositionName(hwc2_composition_t composition) {
+    switch (composition) {
+        case HWC2_COMPOSITION_INVALID: return "Invalid";
+        case HWC2_COMPOSITION_CLIENT: return "Client";
+        case HWC2_COMPOSITION_DEVICE: return "Device";
+        case HWC2_COMPOSITION_SOLID_COLOR: return "SolidColor";
+        case HWC2_COMPOSITION_CURSOR: return "Cursor";
+        case HWC2_COMPOSITION_SIDEBAND: return "Sideband";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getConnectionName(hwc2_connection_t connection) {
+    switch (connection) {
+        case HWC2_CONNECTION_INVALID: return "Invalid";
+        case HWC2_CONNECTION_CONNECTED: return "Connected";
+        case HWC2_CONNECTION_DISCONNECTED: return "Disconnected";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getDisplayRequestName(
+        hwc2_display_request_t request) {
+    switch (request) {
+        case 0: return "None";
+        case HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET: return "FlipClientTarget";
+        case HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT:
+            return "WriteClientTargetToOutput";
+        case HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET |
+                HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT:
+            return "FlipClientTarget|WriteClientTargetToOutput";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getDisplayTypeName(hwc2_display_type_t type) {
+    switch (type) {
+        case HWC2_DISPLAY_TYPE_INVALID: return "Invalid";
+        case HWC2_DISPLAY_TYPE_PHYSICAL: return "Physical";
+        case HWC2_DISPLAY_TYPE_VIRTUAL: return "Virtual";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getErrorName(hwc2_error_t error) {
+    switch (error) {
+        case HWC2_ERROR_NONE: return "None";
+        case HWC2_ERROR_BAD_CONFIG: return "BadConfig";
+        case HWC2_ERROR_BAD_DISPLAY: return "BadDisplay";
+        case HWC2_ERROR_BAD_LAYER: return "BadLayer";
+        case HWC2_ERROR_BAD_PARAMETER: return "BadParameter";
+        case HWC2_ERROR_HAS_CHANGES: return "HasChanges";
+        case HWC2_ERROR_NO_RESOURCES: return "NoResources";
+        case HWC2_ERROR_NOT_VALIDATED: return "NotValidated";
+        case HWC2_ERROR_UNSUPPORTED: return "Unsupported";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getFunctionDescriptorName(
+        hwc2_function_descriptor_t desc) {
+    switch (desc) {
+        case HWC2_FUNCTION_INVALID: return "Invalid";
+        case HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES:
+            return "AcceptDisplayChanges";
+        case HWC2_FUNCTION_CREATE_LAYER: return "CreateLayer";
+        case HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY:
+            return "CreateVirtualDisplay";
+        case HWC2_FUNCTION_DESTROY_LAYER: return "DestroyLayer";
+        case HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY:
+            return "DestroyVirtualDisplay";
+        case HWC2_FUNCTION_DUMP: return "Dump";
+        case HWC2_FUNCTION_GET_ACTIVE_CONFIG: return "GetActiveConfig";
+        case HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES:
+            return "GetChangedCompositionTypes";
+        case HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT:
+            return "GetClientTargetSupport";
+        case HWC2_FUNCTION_GET_COLOR_MODES: return "GetColorModes";
+        case HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE: return "GetDisplayAttribute";
+        case HWC2_FUNCTION_GET_DISPLAY_CONFIGS: return "GetDisplayConfigs";
+        case HWC2_FUNCTION_GET_DISPLAY_NAME: return "GetDisplayName";
+        case HWC2_FUNCTION_GET_DISPLAY_REQUESTS: return "GetDisplayRequests";
+        case HWC2_FUNCTION_GET_DISPLAY_TYPE: return "GetDisplayType";
+        case HWC2_FUNCTION_GET_DOZE_SUPPORT: return "GetDozeSupport";
+        case HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT:
+            return "GetMaxVirtualDisplayCount";
+        case HWC2_FUNCTION_GET_RELEASE_FENCES: return "GetReleaseFences";
+        case HWC2_FUNCTION_PRESENT_DISPLAY: return "PresentDisplay";
+        case HWC2_FUNCTION_REGISTER_CALLBACK: return "RegisterCallback";
+        case HWC2_FUNCTION_SET_ACTIVE_CONFIG: return "SetActiveConfig";
+        case HWC2_FUNCTION_SET_CLIENT_TARGET: return "SetClientTarget";
+        case HWC2_FUNCTION_SET_COLOR_MODE: return "SetColorMode";
+        case HWC2_FUNCTION_SET_COLOR_TRANSFORM: return "SetColorTransform";
+        case HWC2_FUNCTION_SET_CURSOR_POSITION: return "SetCursorPosition";
+        case HWC2_FUNCTION_SET_LAYER_BLEND_MODE: return "SetLayerBlendMode";
+        case HWC2_FUNCTION_SET_LAYER_BUFFER: return "SetLayerBuffer";
+        case HWC2_FUNCTION_SET_LAYER_COLOR: return "SetLayerColor";
+        case HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE:
+            return "SetLayerCompositionType";
+        case HWC2_FUNCTION_SET_LAYER_DATASPACE: return "SetLayerDataspace";
+        case HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME:
+            return "SetLayerDisplayFrame";
+        case HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA: return "SetLayerPlaneAlpha";
+        case HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM:
+            return "SetLayerSidebandStream";
+        case HWC2_FUNCTION_SET_LAYER_SOURCE_CROP: return "SetLayerSourceCrop";
+        case HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE:
+            return "SetLayerSurfaceDamage";
+        case HWC2_FUNCTION_SET_LAYER_TRANSFORM: return "SetLayerTransform";
+        case HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION:
+            return "SetLayerVisibleRegion";
+        case HWC2_FUNCTION_SET_LAYER_Z_ORDER: return "SetLayerZOrder";
+        case HWC2_FUNCTION_SET_OUTPUT_BUFFER: return "SetOutputBuffer";
+        case HWC2_FUNCTION_SET_POWER_MODE: return "SetPowerMode";
+        case HWC2_FUNCTION_SET_VSYNC_ENABLED: return "SetVsyncEnabled";
+        case HWC2_FUNCTION_VALIDATE_DISPLAY: return "ValidateDisplay";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getLayerRequestName(hwc2_layer_request_t request) {
+    switch (request) {
+        case 0: return "None";
+        case HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET: return "ClearClientTarget";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getPowerModeName(hwc2_power_mode_t mode) {
+    switch (mode) {
+        case HWC2_POWER_MODE_OFF: return "Off";
+        case HWC2_POWER_MODE_DOZE_SUSPEND: return "DozeSuspend";
+        case HWC2_POWER_MODE_DOZE: return "Doze";
+        case HWC2_POWER_MODE_ON: return "On";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getTransformName(hwc_transform_t transform) {
+    switch (transform) {
+        case 0: return "None";
+        case HWC_TRANSFORM_FLIP_H: return "FlipH";
+        case HWC_TRANSFORM_FLIP_V: return "FlipV";
+        case HWC_TRANSFORM_ROT_90: return "Rotate90";
+        case HWC_TRANSFORM_ROT_180: return "Rotate180";
+        case HWC_TRANSFORM_ROT_270: return "Rotate270";
+        case HWC_TRANSFORM_FLIP_H_ROT_90: return "FlipHRotate90";
+        case HWC_TRANSFORM_FLIP_V_ROT_90: return "FlipVRotate90";
+        default: return "Unknown";
+    }
+}
+
+static inline const char* getVsyncName(hwc2_vsync_t vsync) {
+    switch (vsync) {
+        case HWC2_VSYNC_INVALID: return "Invalid";
+        case HWC2_VSYNC_ENABLE: return "Enable";
+        case HWC2_VSYNC_DISABLE: return "Disable";
+        default: return "Unknown";
+    }
+}
+
+#define TO_STRING(E, T, printer) \
+    inline std::string to_string(E value) { return printer(value); } \
+    inline std::string to_string(T value) { return to_string(static_cast<E>(value)); }
+#else // !HWC2_INCLUDE_STRINGIFICATION
+#define TO_STRING(name, printer)
+#endif // HWC2_INCLUDE_STRINGIFICATION
+
+/*
+ * C++11 features
+ */
+
+#ifdef HWC2_USE_CPP11
+__END_DECLS
+
+#ifdef HWC2_INCLUDE_STRINGIFICATION
+#include <string>
+#endif
+
+namespace HWC2 {
+
+enum class Attribute : int32_t {
+    Invalid = HWC2_ATTRIBUTE_INVALID,
+    Width = HWC2_ATTRIBUTE_WIDTH,
+    Height = HWC2_ATTRIBUTE_HEIGHT,
+    VsyncPeriod = HWC2_ATTRIBUTE_VSYNC_PERIOD,
+    DpiX = HWC2_ATTRIBUTE_DPI_X,
+    DpiY = HWC2_ATTRIBUTE_DPI_Y,
+};
+TO_STRING(hwc2_attribute_t, Attribute, getAttributeName)
+
+enum class BlendMode : int32_t {
+    Invalid = HWC2_BLEND_MODE_INVALID,
+    None = HWC2_BLEND_MODE_NONE,
+    Premultiplied = HWC2_BLEND_MODE_PREMULTIPLIED,
+    Coverage = HWC2_BLEND_MODE_COVERAGE,
+};
+TO_STRING(hwc2_blend_mode_t, BlendMode, getBlendModeName)
+
+enum class Callback : int32_t {
+    Invalid = HWC2_CALLBACK_INVALID,
+    Hotplug = HWC2_CALLBACK_HOTPLUG,
+    Refresh = HWC2_CALLBACK_REFRESH,
+    Vsync = HWC2_CALLBACK_VSYNC,
+};
+TO_STRING(hwc2_callback_descriptor_t, Callback, getCallbackDescriptorName)
+
+enum class Capability : int32_t {
+    Invalid = HWC2_CAPABILITY_INVALID,
+    SidebandStream = HWC2_CAPABILITY_SIDEBAND_STREAM,
+};
+TO_STRING(hwc2_capability_t, Capability, getCapabilityName)
+
+enum class Composition : int32_t {
+    Invalid = HWC2_COMPOSITION_INVALID,
+    Client = HWC2_COMPOSITION_CLIENT,
+    Device = HWC2_COMPOSITION_DEVICE,
+    SolidColor = HWC2_COMPOSITION_SOLID_COLOR,
+    Cursor = HWC2_COMPOSITION_CURSOR,
+    Sideband = HWC2_COMPOSITION_SIDEBAND,
+};
+TO_STRING(hwc2_composition_t, Composition, getCompositionName)
+
+enum class Connection : int32_t {
+    Invalid = HWC2_CONNECTION_INVALID,
+    Connected = HWC2_CONNECTION_CONNECTED,
+    Disconnected = HWC2_CONNECTION_DISCONNECTED,
+};
+TO_STRING(hwc2_connection_t, Connection, getConnectionName)
+
+enum class DisplayRequest : int32_t {
+    FlipClientTarget = HWC2_DISPLAY_REQUEST_FLIP_CLIENT_TARGET,
+    WriteClientTargetToOutput =
+        HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT,
+};
+TO_STRING(hwc2_display_request_t, DisplayRequest, getDisplayRequestName)
+
+enum class DisplayType : int32_t {
+    Invalid = HWC2_DISPLAY_TYPE_INVALID,
+    Physical = HWC2_DISPLAY_TYPE_PHYSICAL,
+    Virtual = HWC2_DISPLAY_TYPE_VIRTUAL,
+};
+TO_STRING(hwc2_display_type_t, DisplayType, getDisplayTypeName)
+
+enum class Error : int32_t {
+    None = HWC2_ERROR_NONE,
+    BadConfig = HWC2_ERROR_BAD_CONFIG,
+    BadDisplay = HWC2_ERROR_BAD_DISPLAY,
+    BadLayer = HWC2_ERROR_BAD_LAYER,
+    BadParameter = HWC2_ERROR_BAD_PARAMETER,
+    HasChanges = HWC2_ERROR_HAS_CHANGES,
+    NoResources = HWC2_ERROR_NO_RESOURCES,
+    NotValidated = HWC2_ERROR_NOT_VALIDATED,
+    Unsupported = HWC2_ERROR_UNSUPPORTED,
+};
+TO_STRING(hwc2_error_t, Error, getErrorName)
+
+enum class FunctionDescriptor : int32_t {
+    Invalid = HWC2_FUNCTION_INVALID,
+    AcceptDisplayChanges = HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES,
+    CreateLayer = HWC2_FUNCTION_CREATE_LAYER,
+    CreateVirtualDisplay = HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY,
+    DestroyLayer = HWC2_FUNCTION_DESTROY_LAYER,
+    DestroyVirtualDisplay = HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY,
+    Dump = HWC2_FUNCTION_DUMP,
+    GetActiveConfig = HWC2_FUNCTION_GET_ACTIVE_CONFIG,
+    GetChangedCompositionTypes = HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES,
+    GetClientTargetSupport = HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT,
+    GetColorModes = HWC2_FUNCTION_GET_COLOR_MODES,
+    GetDisplayAttribute = HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE,
+    GetDisplayConfigs = HWC2_FUNCTION_GET_DISPLAY_CONFIGS,
+    GetDisplayName = HWC2_FUNCTION_GET_DISPLAY_NAME,
+    GetDisplayRequests = HWC2_FUNCTION_GET_DISPLAY_REQUESTS,
+    GetDisplayType = HWC2_FUNCTION_GET_DISPLAY_TYPE,
+    GetDozeSupport = HWC2_FUNCTION_GET_DOZE_SUPPORT,
+    GetMaxVirtualDisplayCount = HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT,
+    GetReleaseFences = HWC2_FUNCTION_GET_RELEASE_FENCES,
+    PresentDisplay = HWC2_FUNCTION_PRESENT_DISPLAY,
+    RegisterCallback = HWC2_FUNCTION_REGISTER_CALLBACK,
+    SetActiveConfig = HWC2_FUNCTION_SET_ACTIVE_CONFIG,
+    SetClientTarget = HWC2_FUNCTION_SET_CLIENT_TARGET,
+    SetColorMode = HWC2_FUNCTION_SET_COLOR_MODE,
+    SetColorTransform = HWC2_FUNCTION_SET_COLOR_TRANSFORM,
+    SetCursorPosition = HWC2_FUNCTION_SET_CURSOR_POSITION,
+    SetLayerBlendMode = HWC2_FUNCTION_SET_LAYER_BLEND_MODE,
+    SetLayerBuffer = HWC2_FUNCTION_SET_LAYER_BUFFER,
+    SetLayerColor = HWC2_FUNCTION_SET_LAYER_COLOR,
+    SetLayerCompositionType = HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE,
+    SetLayerDataspace = HWC2_FUNCTION_SET_LAYER_DATASPACE,
+    SetLayerDisplayFrame = HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME,
+    SetLayerPlaneAlpha = HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA,
+    SetLayerSidebandStream = HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM,
+    SetLayerSourceCrop = HWC2_FUNCTION_SET_LAYER_SOURCE_CROP,
+    SetLayerSurfaceDamage = HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE,
+    SetLayerTransform = HWC2_FUNCTION_SET_LAYER_TRANSFORM,
+    SetLayerVisibleRegion = HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION,
+    SetLayerZOrder = HWC2_FUNCTION_SET_LAYER_Z_ORDER,
+    SetOutputBuffer = HWC2_FUNCTION_SET_OUTPUT_BUFFER,
+    SetPowerMode = HWC2_FUNCTION_SET_POWER_MODE,
+    SetVsyncEnabled = HWC2_FUNCTION_SET_VSYNC_ENABLED,
+    ValidateDisplay = HWC2_FUNCTION_VALIDATE_DISPLAY,
+};
+TO_STRING(hwc2_function_descriptor_t, FunctionDescriptor,
+        getFunctionDescriptorName)
+
+enum class LayerRequest : int32_t {
+    ClearClientTarget = HWC2_LAYER_REQUEST_CLEAR_CLIENT_TARGET,
+};
+TO_STRING(hwc2_layer_request_t, LayerRequest, getLayerRequestName)
+
+enum class PowerMode : int32_t {
+    Off = HWC2_POWER_MODE_OFF,
+    DozeSuspend = HWC2_POWER_MODE_DOZE_SUSPEND,
+    Doze = HWC2_POWER_MODE_DOZE,
+    On = HWC2_POWER_MODE_ON,
+};
+TO_STRING(hwc2_power_mode_t, PowerMode, getPowerModeName)
+
+enum class Transform : int32_t {
+    None = 0,
+    FlipH = HWC_TRANSFORM_FLIP_H,
+    FlipV = HWC_TRANSFORM_FLIP_V,
+    Rotate90 = HWC_TRANSFORM_ROT_90,
+    Rotate180 = HWC_TRANSFORM_ROT_180,
+    Rotate270 = HWC_TRANSFORM_ROT_270,
+    FlipHRotate90 = HWC_TRANSFORM_FLIP_H_ROT_90,
+    FlipVRotate90 = HWC_TRANSFORM_FLIP_V_ROT_90,
+};
+TO_STRING(hwc_transform_t, Transform, getTransformName)
+
+enum class Vsync : int32_t {
+    Invalid = HWC2_VSYNC_INVALID,
+    Enable = HWC2_VSYNC_ENABLE,
+    Disable = HWC2_VSYNC_DISABLE,
+};
+TO_STRING(hwc2_vsync_t, Vsync, getVsyncName)
+
+} // namespace HWC2
+
+__BEGIN_DECLS
+#endif // HWC2_USE_CPP11
+
+/*
+ * Typedefs
+ */
+
+typedef void (*hwc2_function_pointer_t)();
+
+typedef void* hwc2_callback_data_t;
+typedef uint32_t hwc2_config_t;
+typedef uint64_t hwc2_display_t;
+typedef uint64_t hwc2_layer_t;
+
+/*
+ * Device Struct
+ */
+
+typedef struct hwc2_device {
+    /* Must be the first member of this struct, since a pointer to this struct
+     * will be generated by casting from a hw_device_t* */
+    struct hw_device_t common;
+
+    /* getCapabilities(..., outCount, outCapabilities)
+     *
+     * Provides a list of capabilities (described in the definition of
+     * hwc2_capability_t above) supported by this device. This list must
+     * not change after the device has been loaded.
+     *
+     * Parameters:
+     *   outCount - if outCapabilities was NULL, the number of capabilities
+     *       which would have been returned; if outCapabilities was not NULL,
+     *       the number of capabilities returned, which must not exceed the
+     *       value stored in outCount prior to the call
+     *   outCapabilities - a list of capabilities supported by this device; may
+     *       be NULL, in which case this function must write into outCount the
+     *       number of capabilities which would have been written into
+     *       outCapabilities
+     */
+    void (*getCapabilities)(struct hwc2_device* device, uint32_t* outCount,
+            int32_t* /*hwc2_capability_t*/ outCapabilities);
+
+    /* getFunction(..., descriptor)
+     *
+     * Returns a function pointer which implements the requested description.
+     *
+     * Parameters:
+     *   descriptor - the function to return
+     *
+     * Returns either a function pointer implementing the requested descriptor
+     *   or NULL if the described function is not supported by this device.
+     */
+    hwc2_function_pointer_t (*getFunction)(struct hwc2_device* device,
+            int32_t /*hwc2_function_descriptor_t*/ descriptor);
+} hwc2_device_t;
+
+static inline int hwc2_open(const struct hw_module_t* module,
+        hwc2_device_t** device) {
+    return module->methods->open(module, HWC_HARDWARE_COMPOSER,
+            (struct hw_device_t**) device);
+}
+
+static inline int hwc2_close(hwc2_device_t* device) {
+    return device->common.close(&device->common);
+}
+
+/*
+ * Callbacks
+ *
+ * All of these callbacks take as their first parameter the callbackData which
+ * was provided at the time of callback registration, so this parameter is
+ * omitted from the described parameter lists.
+ */
+
+/* hotplug(..., display, connected)
+ * Descriptor: HWC2_CALLBACK_HOTPLUG
+ * Will be provided to all HWC2 devices
+ *
+ * Notifies the client that the given display has either been connected or
+ * disconnected. Every active display (even a built-in physical display) must
+ * trigger at least one hotplug notification, even if it only occurs immediately
+ * after callback registration.
+ *
+ * The client may call back into the device on the same thread to query display
+ * properties (such as width, height, and vsync period), and other threads may
+ * call into the device while the callback is in progress. The device must
+ * serialize calls to this callback such that only one thread is calling it at a
+ * time.
+ *
+ * Displays which have been connected are assumed to be in HWC2_POWER_MODE_OFF,
+ * and the vsync callback should not be called for a display until vsync has
+ * been enabled with setVsyncEnabled.
+ *
+ * Parameters:
+ *   display - the display which has been hotplugged
+ *   connected - whether the display has been connected or disconnected
+ */
+typedef void (*HWC2_PFN_HOTPLUG)(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, int32_t /*hwc2_connection_t*/ connected);
+
+/* refresh(..., display)
+ * Descriptor: HWC2_CALLBACK_REFRESH
+ * Will be provided to all HWC2 devices
+ *
+ * Notifies the client to trigger a screen refresh. This forces all layer state
+ * for this display to be resent, and the display to be validated and presented,
+ * even if there have been no changes.
+ *
+ * This refresh will occur some time after the callback is initiated, but not
+ * necessarily before it returns. This thread, however, is guaranteed not to
+ * call back into the device, thus it is safe to trigger this callback from
+ * other functions which call into the device.
+ *
+ * Parameters:
+ *   display - the display to refresh
+ */
+typedef void (*HWC2_PFN_REFRESH)(hwc2_callback_data_t callbackData,
+        hwc2_display_t display);
+
+/* vsync(..., display, timestamp)
+ * Descriptor: HWC2_CALLBACK_VSYNC
+ * Will be provided to all HWC2 devices
+ *
+ * Notifies the client that a vsync event has occurred. This callback must
+ * only be triggered when vsync is enabled for this display (through
+ * setVsyncEnabled).
+ *
+ * This callback should be triggered from a thread of at least
+ * HAL_PRIORITY_URGENT_DISPLAY with as little latency as possible, typically
+ * less than 0.5 ms. This thread is guaranteed not to call back into the device.
+ *
+ * Parameters:
+ *   display - the display which has received a vsync event
+ *   timestamp - the CLOCK_MONOTONIC time at which the vsync event occurred, in
+ *       nanoseconds
+ */
+typedef void (*HWC2_PFN_VSYNC)(hwc2_callback_data_t callbackData,
+        hwc2_display_t display, int64_t timestamp);
+
+/*
+ * Device Functions
+ *
+ * All of these functions take as their first parameter a device pointer, so
+ * this parameter is omitted from the described parameter lists.
+ */
+
+/* createVirtualDisplay(..., width, height, outDisplay)
+ * Descriptor: HWC2_FUNCTION_CREATE_VIRTUAL_DISPLAY
+ * Must be provided by all HWC2 devices
+ *
+ * Creates a new virtual display with the given width and height. The display
+ * will be assumed to be on from the time the first frame is presented until the
+ * display is destroyed.
+ *
+ * Parameters:
+ *   width - width in pixels
+ *   height - height in pixels
+ *   outDisplay - the newly-created virtual display; pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_UNSUPPORTED - the width or height is too large for the device to
+ *       be able to create a virtual display
+ *   HWC2_ERROR_NO_RESOURCES - the device is unable to create a new virtual
+ *       display at this time
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_CREATE_VIRTUAL_DISPLAY)(
+        hwc2_device_t* device, uint32_t width, uint32_t height,
+        hwc2_display_t* outDisplay);
+
+/* destroyVirtualDisplay(..., display)
+ * Descriptor: HWC2_FUNCTION_DESTROY_VIRTUAL_DISPLAY
+ * Must be provided by all HWC2 devices
+ *
+ * Destroys a virtual display. After this call all resources consumed by this
+ * display may be freed by the device and any operations performed on this
+ * display should fail.
+ *
+ * Parameters:
+ *   display - the virtual display to destroy
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - the display handle which was passed in does not
+ *       refer to a virtual display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_DESTROY_VIRTUAL_DISPLAY)(
+        hwc2_device_t* device, hwc2_display_t display);
+
+/* dump(..., outSize, outBuffer)
+ * Descriptor: HWC2_FUNCTION_DUMP
+ * Must be provided by all HWC2 devices
+ *
+ * Retrieves implementation-defined debug information, which will be displayed
+ * during, for example, `dumpsys SurfaceFlinger`.
+ *
+ * If called with outBuffer == NULL, the device should store a copy of the
+ * desired output and return its length in bytes in outSize. If the device
+ * already has a stored copy, that copy should be purged and replaced with a
+ * fresh copy.
+ *
+ * If called with outBuffer != NULL, the device should copy its stored version
+ * of the output into outBuffer and store how many bytes of data it copied into
+ * outSize. Prior to this call, the client will have populated outSize with the
+ * maximum number of bytes outBuffer can hold. The device must not write more
+ * than this amount into outBuffer. If the device does not currently have a
+ * stored copy, then it should return 0 in outSize.
+ *
+ * Any data written into outBuffer need not be null-terminated.
+ *
+ * Parameters:
+ *   outSize - if outBuffer was NULL, the number of bytes needed to copy the
+ *       device's stored output; if outBuffer was not NULL, the number of bytes
+ *       written into it, which must not exceed the value stored in outSize
+ *       prior to the call; pointer will be non-NULL
+ *   outBuffer - the buffer to write the dump output into; may be NULL as
+ *       described above; data written into this buffer need not be
+ *       null-terminated
+ */
+typedef void (*HWC2_PFN_DUMP)(hwc2_device_t* device, uint32_t* outSize,
+        char* outBuffer);
+
+/* getMaxVirtualDisplayCount(...)
+ * Descriptor: HWC2_FUNCTION_GET_MAX_VIRTUAL_DISPLAY_COUNT
+ * Must be provided by all HWC2 devices
+ *
+ * Returns the maximum number of virtual displays supported by this device
+ * (which may be 0). The client will not attempt to create more than this many
+ * virtual displays on this device. This number must not change for the lifetime
+ * of the device.
+ */
+typedef uint32_t (*HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT)(
+        hwc2_device_t* device);
+
+/* registerCallback(..., descriptor, callbackData, pointer)
+ * Descriptor: HWC2_FUNCTION_REGISTER_CALLBACK
+ * Must be provided by all HWC2 devices
+ *
+ * Provides a callback for the device to call. All callbacks take a callbackData
+ * item as the first parameter, so this value should be stored with the callback
+ * for later use. The callbackData may differ from one callback to another. If
+ * this function is called multiple times with the same descriptor, later
+ * callbacks replace earlier ones.
+ *
+ * Parameters:
+ *   descriptor - which callback should be set
+ *   callBackdata - opaque data which must be passed back through the callback
+ *   pointer - a non-NULL function pointer corresponding to the descriptor
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_PARAMETER - descriptor was invalid
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_REGISTER_CALLBACK)(
+        hwc2_device_t* device,
+        int32_t /*hwc2_callback_descriptor_t*/ descriptor,
+        hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer);
+
+/*
+ * Display Functions
+ *
+ * All of these functions take as their first two parameters a device pointer
+ * and a display handle, so these parameters are omitted from the described
+ * parameter lists.
+ */
+
+/* acceptDisplayChanges(...)
+ * Descriptor: HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES
+ * Must be provided by all HWC2 devices
+ *
+ * Accepts the changes required by the device from the previous validateDisplay
+ * call (which may be queried using getChangedCompositionTypes) and revalidates
+ * the display. This function is equivalent to requesting the changed types from
+ * getChangedCompositionTypes, setting those types on the corresponding layers,
+ * and then calling validateDisplay again.
+ *
+ * After this call it must be valid to present this display. Calling this after
+ * validateDisplay returns 0 changes must succeed with HWC2_ERROR_NONE, but
+ * should have no other effect.
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_ACCEPT_DISPLAY_CHANGES)(
+        hwc2_device_t* device, hwc2_display_t display);
+
+/* createLayer(..., outLayer)
+ * Descriptor: HWC2_FUNCTION_CREATE_LAYER
+ * Must be provided by all HWC2 devices
+ *
+ * Creates a new layer on the given display.
+ *
+ * Parameters:
+ *   outLayer - the handle of the new layer; pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NO_RESOURCES - the device was unable to create this layer
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_CREATE_LAYER)(hwc2_device_t* device,
+        hwc2_display_t display, hwc2_layer_t* outLayer);
+
+/* destroyLayer(..., layer)
+ * Descriptor: HWC2_FUNCTION_DESTROY_LAYER
+ * Must be provided by all HWC2 devices
+ *
+ * Destroys the given layer.
+ *
+ * Parameters:
+ *   layer - the handle of the layer to destroy
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_DESTROY_LAYER)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer);
+
+/* getActiveConfig(..., outConfig)
+ * Descriptor: HWC2_FUNCTION_GET_ACTIVE_CONFIG
+ * Must be provided by all HWC2 devices
+ *
+ * Retrieves which display configuration is currently active.
+ *
+ * If no display configuration is currently active, this function must return
+ * HWC2_ERROR_BAD_CONFIG and place no configuration handle in outConfig. It is
+ * the responsibility of the client to call setActiveConfig with a valid
+ * configuration before attempting to present anything on the display.
+ *
+ * Parameters:
+ *   outConfig - the currently active display configuration; pointer will be
+ *       non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_CONFIG - no configuration is currently active
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_ACTIVE_CONFIG)(
+        hwc2_device_t* device, hwc2_display_t display,
+        hwc2_config_t* outConfig);
+
+/* getChangedCompositionTypes(..., outNumElements, outLayers, outTypes)
+ * Descriptor: HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES
+ * Must be provided by all HWC2 devices
+ *
+ * Retrieves the layers for which the device requires a different composition
+ * type than had been set prior to the last call to validateDisplay. The client
+ * will either update its state with these types and call acceptDisplayChanges,
+ * or will set new types and attempt to validate the display again.
+ *
+ * outLayers and outTypes may be NULL to retrieve the number of elements which
+ * will be returned. The number of elements returned must be the same as the
+ * value returned in outNumTypes from the last call to validateDisplay.
+ *
+ * Parameters:
+ *   outNumElements - if outLayers or outTypes were NULL, the number of layers
+ *       and types which would have been returned; if both were non-NULL, the
+ *       number of elements returned in outLayers and outTypes, which must not
+ *       exceed the value stored in outNumElements prior to the call; pointer
+ *       will be non-NULL
+ *   outLayers - an array of layer handles
+ *   outTypes - an array of composition types, each corresponding to an element
+ *       of outLayers
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called for this
+ *       display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES)(
+        hwc2_device_t* device, hwc2_display_t display,
+        uint32_t* outNumElements, hwc2_layer_t* outLayers,
+        int32_t* /*hwc2_composition_t*/ outTypes);
+
+/* getClientTargetSupport(..., width, height, format, dataspace)
+ * Descriptor: HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT
+ * Must be provided by all HWC2 devices
+ *
+ * Returns whether a client target with the given properties can be handled by
+ * the device.
+ *
+ * The valid formats can be found in android_pixel_format_t in
+ * <system/graphics.h>.
+ *
+ * For more about dataspaces, see setLayerDataspace.
+ *
+ * This function must return true for a client target with width and height
+ * equal to the active display configuration dimensions,
+ * HAL_PIXEL_FORMAT_RGBA_8888, and HAL_DATASPACE_UNKNOWN. It is not required to
+ * return true for any other configuration.
+ *
+ * Parameters:
+ *   width - client target width in pixels
+ *   height - client target height in pixels
+ *   format - client target format
+ *   dataspace - client target dataspace, as described in setLayerDataspace
+ *
+ * Returns HWC2_ERROR_NONE if the given configuration is supported or one of the
+ * following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_UNSUPPORTED - the given configuration is not supported
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_CLIENT_TARGET_SUPPORT)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t width,
+        uint32_t height, int32_t /*android_pixel_format_t*/ format,
+        int32_t /*android_dataspace_t*/ dataspace);
+
+/* getColorModes(..., outNumModes, outModes)
+ * Descriptor: HWC2_FUNCTION_GET_COLOR_MODES
+ * Must be provided by all HWC2 devices
+ *
+ * Returns the color modes supported on this display.
+ *
+ * The valid color modes can be found in android_color_mode_t in
+ * <system/graphics.h>. All HWC2 devices must support at least
+ * HAL_COLOR_MODE_NATIVE.
+ *
+ * outNumModes may be NULL to retrieve the number of modes which will be
+ * returned.
+ *
+ * Parameters:
+ *   outNumModes - if outModes was NULL, the number of modes which would have
+ *       been returned; if outModes was not NULL, the number of modes returned,
+ *       which must not exceed the value stored in outNumModes prior to the
+ *       call; pointer will be non-NULL
+ *   outModes - an array of color modes
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_COLOR_MODES)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumModes,
+        int32_t* /*android_color_mode_t*/ outModes);
+
+/* getDisplayAttribute(..., config, attribute, outValue)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE
+ * Must be provided by all HWC2 devices
+ *
+ * Returns a display attribute value for a particular display configuration.
+ *
+ * Any attribute which is not supported or for which the value is unknown by the
+ * device must return a value of -1.
+ *
+ * Parameters:
+ *   config - the display configuration for which to return attribute values
+ *   attribute - the attribute to query
+ *   outValue - the value of the attribute; the pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_CONFIG - config does not name a valid configuration for this
+ *       display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_ATTRIBUTE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config,
+        int32_t /*hwc2_attribute_t*/ attribute, int32_t* outValue);
+
+/* getDisplayConfigs(..., outNumConfigs, outConfigs)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CONFIGS
+ * Must be provided by all HWC2 devices
+ *
+ * Returns handles for all of the valid display configurations on this display.
+ *
+ * outConfigs may be NULL to retrieve the number of elements which will be
+ * returned.
+ *
+ * Parameters:
+ *   outNumConfigs - if outConfigs was NULL, the number of configurations which
+ *       would have been returned; if outConfigs was not NULL, the number of
+ *       configurations returned, which must not exceed the value stored in
+ *       outNumConfigs prior to the call; pointer will be non-NULL
+ *   outConfigs - an array of configuration handles
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_CONFIGS)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumConfigs,
+        hwc2_config_t* outConfigs);
+
+/* getDisplayName(..., outSize, outName)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_NAME
+ * Must be provided by all HWC2 devices
+ *
+ * Returns a human-readable version of the display's name.
+ *
+ * outName may be NULL to retrieve the length of the name.
+ *
+ * Parameters:
+ *   outSize - if outName was NULL, the number of bytes needed to return the
+ *       name if outName was not NULL, the number of bytes written into it,
+ *       which must not exceed the value stored in outSize prior to the call;
+ *       pointer will be non-NULL
+ *   outName - the display's name
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_NAME)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outSize,
+        char* outName);
+
+/* getDisplayRequests(..., outDisplayRequests, outNumElements, outLayers,
+ *     outLayerRequests)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_REQUESTS
+ * Must be provided by all HWC2 devices
+ *
+ * Returns the display requests and the layer requests required for the last
+ * validated configuration.
+ *
+ * Display requests provide information about how the client should handle the
+ * client target. Layer requests provide information about how the client
+ * should handle an individual layer.
+ *
+ * If outLayers or outLayerRequests is NULL, the required number of layers and
+ * requests must be returned in outNumElements, but this number may also be
+ * obtained from validateDisplay as outNumRequests (outNumElements must be equal
+ * to the value returned in outNumRequests from the last call to
+ * validateDisplay).
+ *
+ * Parameters:
+ *   outDisplayRequests - the display requests for the current validated state
+ *   outNumElements - if outLayers or outLayerRequests were NULL, the number of
+ *       elements which would have been returned, which must be equal to the
+ *       value returned in outNumRequests from the last validateDisplay call on
+ *       this display; if both were not NULL, the number of elements in
+ *       outLayers and outLayerRequests, which must not exceed the value stored
+ *       in outNumElements prior to the call; pointer will be non-NULL
+ *   outLayers - an array of layers which all have at least one request
+ *   outLayerRequests - the requests corresponding to each element of outLayers
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called for this
+ *       display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_REQUESTS)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t* /*hwc2_display_request_t*/ outDisplayRequests,
+        uint32_t* outNumElements, hwc2_layer_t* outLayers,
+        int32_t* /*hwc2_layer_request_t*/ outLayerRequests);
+
+/* getDisplayType(..., outType)
+ * Descriptor: HWC2_FUNCTION_GET_DISPLAY_TYPE
+ * Must be provided by all HWC2 devices
+ *
+ * Returns whether the given display is a physical or virtual display.
+ *
+ * Parameters:
+ *   outType - the type of the display; pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DISPLAY_TYPE)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t* /*hwc2_display_type_t*/ outType);
+
+/* getDozeSupport(..., outSupport)
+ * Descriptor: HWC2_FUNCTION_GET_DOZE_SUPPORT
+ * Must be provided by all HWC2 devices
+ *
+ * Returns whether the given display supports HWC2_POWER_MODE_DOZE and
+ * HWC2_POWER_MODE_DOZE_SUSPEND. DOZE_SUSPEND may not provide any benefit over
+ * DOZE (see the definition of hwc2_power_mode_t for more information), but if
+ * both DOZE and DOZE_SUSPEND are no different from HWC2_POWER_MODE_ON, the
+ * device should not claim support.
+ *
+ * Parameters:
+ *   outSupport - whether the display supports doze modes (1 for yes, 0 for no);
+ *       pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_DOZE_SUPPORT)(
+        hwc2_device_t* device, hwc2_display_t display, int32_t* outSupport);
+
+/* getReleaseFences(..., outNumElements, outLayers, outFences)
+ * Descriptor: HWC2_FUNCTION_GET_RELEASE_FENCES
+ * Must be provided by all HWC2 devices
+ *
+ * Retrieves the release fences for device layers on this display which will
+ * receive new buffer contents this frame.
+ *
+ * A release fence is a file descriptor referring to a sync fence object which
+ * will be signaled after the device has finished reading from the buffer
+ * presented in the prior frame. This indicates that it is safe to start writing
+ * to the buffer again. If a given layer's fence is not returned from this
+ * function, it will be assumed that the buffer presented on the previous frame
+ * is ready to be written.
+ *
+ * The fences returned by this function should be unique for each layer (even if
+ * they point to the same underlying sync object), and ownership of the fences
+ * is transferred to the client, which is responsible for closing them.
+ *
+ * If outLayers or outFences is NULL, the required number of layers and fences
+ * must be returned in outNumElements.
+ *
+ * Parameters:
+ *   outNumElements - if outLayers or outFences were NULL, the number of
+ *       elements which would have been returned; if both were not NULL, the
+ *       number of elements in outLayers and outFences, which must not exceed
+ *       the value stored in outNumElements prior to the call; pointer will be
+ *       non-NULL
+ *   outLayers - an array of layer handles
+ *   outFences - an array of sync fence file descriptors as described above,
+ *       each corresponding to an element of outLayers
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_GET_RELEASE_FENCES)(
+        hwc2_device_t* device, hwc2_display_t display, uint32_t* outNumElements,
+        hwc2_layer_t* outLayers, int32_t* outFences);
+
+/* presentDisplay(..., outRetireFence)
+ * Descriptor: HWC2_FUNCTION_PRESENT_DISPLAY
+ * Must be provided by all HWC2 devices
+ *
+ * Presents the current display contents on the screen (or in the case of
+ * virtual displays, into the output buffer).
+ *
+ * Prior to calling this function, the display must be successfully validated
+ * with validateDisplay. Note that setLayerBuffer and setLayerSurfaceDamage
+ * specifically do not count as layer state, so if there are no other changes
+ * to the layer state (or to the buffer's properties as described in
+ * setLayerBuffer), then it is safe to call this function without first
+ * validating the display.
+ *
+ * If this call succeeds, outRetireFence will be populated with a file
+ * descriptor referring to a retire sync fence object. For physical displays,
+ * this fence will be signaled when the result of composition of the prior frame
+ * is no longer necessary (because it has been copied or replaced by this
+ * frame). For virtual displays, this fence will be signaled when writes to the
+ * output buffer have completed and it is safe to read from it.
+ *
+ * Parameters:
+ *   outRetireFence - a sync fence file descriptor as described above; pointer
+ *       will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_NO_RESOURCES - no valid output buffer has been set for a virtual
+ *       display
+ *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not successfully been called
+ *       for this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_PRESENT_DISPLAY)(
+        hwc2_device_t* device, hwc2_display_t display, int32_t* outRetireFence);
+
+/* setActiveConfig(..., config)
+ * Descriptor: HWC2_FUNCTION_SET_ACTIVE_CONFIG
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the active configuration for this display. Upon returning, the given
+ * display configuration should be active and remain so until either this
+ * function is called again or the display is disconnected.
+ *
+ * Parameters:
+ *   config - the new display configuration
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_CONFIG - the configuration handle passed in is not valid for
+ *       this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_ACTIVE_CONFIG)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_config_t config);
+
+/* setClientTarget(..., target, acquireFence, dataspace)
+ * Descriptor: HWC2_FUNCTION_SET_CLIENT_TARGET
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the buffer handle which will receive the output of client composition.
+ * Layers marked as HWC2_COMPOSITION_CLIENT will be composited into this buffer
+ * prior to the call to presentDisplay, and layers not marked as
+ * HWC2_COMPOSITION_CLIENT should be composited with this buffer by the device.
+ *
+ * Also provides a file descriptor referring to an acquire sync fence object,
+ * which will be signaled when it is safe to read from the client target buffer.
+ * If it is already safe to read from this buffer, -1 may be passed instead.
+ * The device must ensure that it is safe for the client to close this file
+ * descriptor at any point after this function is called.
+ *
+ * For more about dataspaces, see setLayerDataspace.
+ *
+ * Will be called before presentDisplay if any of the layers are marked as
+ * HWC2_COMPOSITION_CLIENT. If no layers are so marked, then it is not
+ * necessary to call this function. It is not necessary to call validateDisplay
+ * after changing the target through this function.
+ *
+ * Parameters:
+ *   target - the new target buffer
+ *   acquireFence - a sync fence file descriptor as described above
+ *   dataspace - the dataspace of the buffer, as described in setLayerDataspace
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - the new target handle was invalid
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_CLIENT_TARGET)(
+        hwc2_device_t* device, hwc2_display_t display, buffer_handle_t target,
+        int32_t acquireFence, int32_t /*android_dataspace_t*/ dataspace);
+
+/* setColorTransform(..., matrix, hint)
+ * Descriptor: HWC2_FUNCTION_SET_COLOR_TRANSFORM
+ * Must be provided by all HWC2 devices
+ *
+ * Sets a color transform which will be applied after composition.
+ *
+ * If hint is not HAL_COLOR_TRANSFORM_ARBITRARY, then the device may use the
+ * hint to apply the desired color transform instead of using the color matrix
+ * directly.
+ *
+ * If the device is not capable of either using the hint or the matrix to apply
+ * the desired color transform, it should force all layers to client composition
+ * during validateDisplay.
+ *
+ * The matrix provided is an affine color transformation of the following form:
+ *
+ * |r.r r.g r.b 0|
+ * |g.r g.g g.b 0|
+ * |b.r b.g b.b 0|
+ * |Tr  Tg  Tb  1|
+ *
+ * This matrix will be provided in row-major form: {r.r, r.g, r.b, 0, g.r, ...}.
+ *
+ * Given a matrix of this form and an input color [R_in, G_in, B_in], the output
+ * color [R_out, G_out, B_out] will be:
+ *
+ * R_out = R_in * r.r + G_in * g.r + B_in * b.r + Tr
+ * G_out = G_in * r.g + G_in * g.g + B_in * b.g + Tg
+ * B_out = B_in * r.b + G_in * g.b + B_in * b.b + Tb
+ *
+ * Parameters:
+ *   matrix - a 4x4 transform matrix (16 floats) as described above
+ *   hint - a hint value which may be used instead of the given matrix unless it
+ *       is HAL_COLOR_TRANSFORM_ARBITRARY
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - hint is not a valid color transform hint
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_COLOR_TRANSFORM)(
+        hwc2_device_t* device, hwc2_display_t display, float* matrix,
+        int32_t /*android_color_transform_t*/ hint);
+
+/* setColorMode(..., mode)
+ * Descriptor: HWC2_FUNCTION_SET_COLOR_MODE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the color mode of the given display.
+ *
+ * Upon returning from this function, the color mode change must have fully
+ * taken effect.
+ *
+ * The valid color modes can be found in android_color_mode_t in
+ * <system/graphics.h>. All HWC2 devices must support at least
+ * HAL_COLOR_MODE_NATIVE, and displays are assumed to be in this mode upon
+ * hotplug.
+ *
+ * Parameters:
+ *   mode - the mode to set
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - mode is not a valid color mode
+ *   HWC2_ERROR_UNSUPPORTED - mode is not supported on this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_COLOR_MODE)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t /*android_color_mode_t*/ mode);
+
+/* setOutputBuffer(..., buffer, releaseFence)
+ * Descriptor: HWC2_FUNCTION_SET_OUTPUT_BUFFER
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the output buffer for a virtual display. That is, the buffer to which
+ * the composition result will be written.
+ *
+ * Also provides a file descriptor referring to a release sync fence object,
+ * which will be signaled when it is safe to write to the output buffer. If it
+ * is already safe to write to the output buffer, -1 may be passed instead. The
+ * device must ensure that it is safe for the client to close this file
+ * descriptor at any point after this function is called.
+ *
+ * Must be called at least once before presentDisplay, but does not have any
+ * interaction with layer state or display validation.
+ *
+ * Parameters:
+ *   buffer - the new output buffer
+ *   releaseFence - a sync fence file descriptor as described above
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - the new output buffer handle was invalid
+ *   HWC2_ERROR_UNSUPPORTED - display does not refer to a virtual display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_OUTPUT_BUFFER)(
+        hwc2_device_t* device, hwc2_display_t display, buffer_handle_t buffer,
+        int32_t releaseFence);
+
+/* setPowerMode(..., mode)
+ * Descriptor: HWC2_FUNCTION_SET_POWER_MODE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the power mode of the given display. The transition must be complete
+ * when this function returns. It is valid to call this function multiple times
+ * with the same power mode.
+ *
+ * All displays must support HWC2_POWER_MODE_ON and HWC2_POWER_MODE_OFF. Whether
+ * a display supports HWC2_POWER_MODE_DOZE or HWC2_POWER_MODE_DOZE_SUSPEND may
+ * be queried using getDozeSupport.
+ *
+ * Parameters:
+ *   mode - the new power mode
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - mode was not a valid power mode
+ *   HWC2_ERROR_UNSUPPORTED - mode was a valid power mode, but is not supported
+ *       on this display
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_POWER_MODE)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t /*hwc2_power_mode_t*/ mode);
+
+/* setVsyncEnabled(..., enabled)
+ * Descriptor: HWC2_FUNCTION_SET_VSYNC_ENABLED
+ * Must be provided by all HWC2 devices
+ *
+ * Enables or disables the vsync signal for the given display. Virtual displays
+ * never generate vsync callbacks, and any attempt to enable vsync for a virtual
+ * display though this function must return HWC2_ERROR_NONE and have no other
+ * effect.
+ *
+ * Parameters:
+ *   enabled - whether to enable or disable vsync
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - enabled was an invalid value
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_VSYNC_ENABLED)(
+        hwc2_device_t* device, hwc2_display_t display,
+        int32_t /*hwc2_vsync_t*/ enabled);
+
+/* validateDisplay(..., outNumTypes, outNumRequests)
+ * Descriptor: HWC2_FUNCTION_VALIDATE_DISPLAY
+ * Must be provided by all HWC2 devices
+ *
+ * Instructs the device to inspect all of the layer state and determine if
+ * there are any composition type changes necessary before presenting the
+ * display. Permitted changes are described in the definition of
+ * hwc2_composition_t above.
+ *
+ * Also returns the number of layer requests required
+ * by the given layer configuration.
+ *
+ * Parameters:
+ *   outNumTypes - the number of composition type changes required by the
+ *       device; if greater than 0, the client must either set and validate new
+ *       types, or call acceptDisplayChanges to accept the changes returned by
+ *       getChangedCompositionTypes; must be the same as the number of changes
+ *       returned by getChangedCompositionTypes (see the declaration of that
+ *       function for more information); pointer will be non-NULL
+ *   outNumRequests - the number of layer requests required by this layer
+ *       configuration; must be equal to the number of layer requests returned
+ *       by getDisplayRequests (see the declaration of that function for
+ *       more information); pointer will be non-NULL
+ *
+ * Returns HWC2_ERROR_NONE if no changes are necessary and it is safe to present
+ * the display using the current layer state. Otherwise returns one of the
+ * following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_HAS_CHANGES - outNumTypes was greater than 0 (see parameter list
+ *       for more information)
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_VALIDATE_DISPLAY)(
+        hwc2_device_t* device, hwc2_display_t display,
+        uint32_t* outNumTypes, uint32_t* outNumRequests);
+
+/*
+ * Layer Functions
+ *
+ * These are functions which operate on layers, but which do not modify state
+ * that must be validated before use. See also 'Layer State Functions' below.
+ *
+ * All of these functions take as their first three parameters a device pointer,
+ * a display handle for the display which contains the layer, and a layer
+ * handle, so these parameters are omitted from the described parameter lists.
+ */
+
+/* setCursorPosition(..., x, y)
+ * Descriptor: HWC2_FUNCTION_SET_CURSOR_POSITION
+ * Must be provided by all HWC2 devices
+ *
+ * Asynchonously sets the position of a cursor layer.
+ *
+ * Prior to validateDisplay, a layer may be marked as HWC2_COMPOSITION_CURSOR.
+ * If validation succeeds (i.e., the device does not request a composition
+ * change for that layer), then once a buffer has been set for the layer and it
+ * has been presented, its position may be set by this function at any time
+ * between presentDisplay and any subsequent validateDisplay calls for this
+ * display.
+ *
+ * Once validateDisplay is called, this function will not be called again until
+ * the validate/present sequence is completed.
+ *
+ * May be called from any thread so long as it is not interleaved with the
+ * validate/present sequence as described above.
+ *
+ * Parameters:
+ *   x - the new x coordinate (in pixels from the left of the screen)
+ *   y - the new y coordinate (in pixels from the top of the screen)
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
+ *   HWC2_ERROR_BAD_LAYER - the layer is invalid or is not currently marked as
+ *       HWC2_COMPOSITION_CURSOR
+ *   HWC2_ERROR_NOT_VALIDATED - the device is currently in the middle of the
+ *       validate/present sequence
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_CURSOR_POSITION)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t x, int32_t y);
+
+/* setLayerBuffer(..., buffer, acquireFence)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_BUFFER
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the buffer handle to be displayed for this layer. If the buffer
+ * properties set at allocation time (width, height, format, and usage) have not
+ * changed since the previous frame, it is not necessary to call validateDisplay
+ * before calling presentDisplay unless new state needs to be validated in the
+ * interim.
+ *
+ * Also provides a file descriptor referring to an acquire sync fence object,
+ * which will be signaled when it is safe to read from the given buffer. If it
+ * is already safe to read from the buffer, -1 may be passed instead. The
+ * device must ensure that it is safe for the client to close this file
+ * descriptor at any point after this function is called.
+ *
+ * This function must return HWC2_ERROR_NONE and have no other effect if called
+ * for a layer with a composition type of HWC2_COMPOSITION_SOLID_COLOR (because
+ * it has no buffer) or HWC2_COMPOSITION_SIDEBAND or HWC2_COMPOSITION_CLIENT
+ * (because synchronization and buffer updates for these layers are handled
+ * elsewhere).
+ *
+ * Parameters:
+ *   buffer - the buffer handle to set
+ *   acquireFence - a sync fence file descriptor as described above
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - the buffer handle passed in was invalid
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_BUFFER)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        buffer_handle_t buffer, int32_t acquireFence);
+
+/* setLayerSurfaceDamage(..., damage)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_SURFACE_DAMAGE
+ * Must be provided by all HWC2 devices
+ *
+ * Provides the region of the source buffer which has been modified since the
+ * last frame. This region does not need to be validated before calling
+ * presentDisplay.
+ *
+ * Once set through this function, the damage region remains the same until a
+ * subsequent call to this function.
+ *
+ * If damage.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
+ * damage.numRects == 0, then the whole source buffer must be treated as if it
+ * has been modified.
+ *
+ * If the layer's contents are not modified relative to the prior frame, damage
+ * 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. They will not exceed the dimensions of the latched
+ * buffer.
+ *
+ * Parameters:
+ *   damage - the new surface damage region
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_SURFACE_DAMAGE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_region_t damage);
+
+/*
+ * Layer State Functions
+ *
+ * These functions modify the state of a given layer. They do not take effect
+ * until the display configuration is successfully validated with
+ * validateDisplay and the display contents are presented with presentDisplay.
+ *
+ * All of these functions take as their first three parameters a device pointer,
+ * a display handle for the display which contains the layer, and a layer
+ * handle, so these parameters are omitted from the described parameter lists.
+ */
+
+/* setLayerBlendMode(..., mode)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_BLEND_MODE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the blend mode of the given layer.
+ *
+ * Parameters:
+ *   mode - the new blend mode
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - an invalid blend mode was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_BLEND_MODE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t /*hwc2_blend_mode_t*/ mode);
+
+/* setLayerColor(..., color)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_COLOR
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the color of the given layer. If the composition type of the layer is
+ * not HWC2_COMPOSITION_SOLID_COLOR, this call must return HWC2_ERROR_NONE and
+ * have no other effect.
+ *
+ * Parameters:
+ *   color - the new color
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_COLOR)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_color_t color);
+
+/* setLayerCompositionType(..., type)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_COMPOSITION_TYPE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the desired composition type of the given layer. During validateDisplay,
+ * the device may request changes to the composition types of any of the layers
+ * as described in the definition of hwc2_composition_t above.
+ *
+ * Parameters:
+ *   type - the new composition type
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - an invalid composition type was passed in
+ *   HWC2_ERROR_UNSUPPORTED - a valid composition type was passed in, but it is
+ *       not supported by this device
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_COMPOSITION_TYPE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t /*hwc2_composition_t*/ type);
+
+/* setLayerDataspace(..., dataspace)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_DATASPACE
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the dataspace that the current buffer on this layer is in.
+ *
+ * The dataspace provides more information about how to interpret the buffer
+ * contents, such as the encoding standard and color transform.
+ *
+ * See the values of android_dataspace_t in <system/graphics.h> for more
+ * information.
+ *
+ * Parameters:
+ *   dataspace - the new dataspace
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_DATASPACE)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t /*android_dataspace_t*/ dataspace);
+
+/* setLayerDisplayFrame(..., frame)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_DISPLAY_FRAME
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the display frame (the portion of the display covered by a layer) of the
+ * given layer. This frame will not exceed the display dimensions.
+ *
+ * Parameters:
+ *   frame - the new display frame
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_DISPLAY_FRAME)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_rect_t frame);
+
+/* setLayerPlaneAlpha(..., alpha)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_PLANE_ALPHA
+ * Must be provided by all HWC2 devices
+ *
+ * Sets an alpha value (a floating point value in the range [0.0, 1.0]) which
+ * will be applied to the whole layer. It can be conceptualized as a
+ * preprocessing step which applies the following function:
+ *   if (blendMode == HWC2_BLEND_MODE_PREMULTIPLIED)
+ *       out.rgb = in.rgb * planeAlpha
+ *   out.a = in.a * planeAlpha
+ *
+ * If the device does not support this operation on a layer which is marked
+ * HWC2_COMPOSITION_DEVICE, it must request a composition type change to
+ * HWC2_COMPOSITION_CLIENT upon the next validateDisplay call.
+ *
+ * Parameters:
+ *   alpha - the plane alpha value to apply
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_PLANE_ALPHA)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        float alpha);
+
+/* setLayerSidebandStream(..., stream)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_SIDEBAND_STREAM
+ * Provided by HWC2 devices which support HWC2_CAPABILITY_SIDEBAND_STREAM
+ *
+ * Sets the sideband stream for this layer. If the composition type of the given
+ * layer is not HWC2_COMPOSITION_SIDEBAND, this call must return HWC2_ERROR_NONE
+ * and have no other effect.
+ *
+ * Parameters:
+ *   stream - the new sideband stream
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - an invalid sideband stream was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_SIDEBAND_STREAM)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        const native_handle_t* stream);
+
+/* setLayerSourceCrop(..., crop)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_SOURCE_CROP
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the source crop (the portion of the source buffer which will fill the
+ * display frame) of the given layer. This crop rectangle will not exceed the
+ * dimensions of the latched buffer.
+ *
+ * If the device is not capable of supporting a true float source crop (i.e., it
+ * will truncate or round the floats to integers), it should set this layer to
+ * HWC2_COMPOSITION_CLIENT when crop is non-integral for the most accurate
+ * rendering.
+ *
+ * If the device cannot support float source crops, but still wants to handle
+ * the layer, it should use the following code (or similar) to convert to
+ * an integer crop:
+ *   intCrop.left = (int) ceilf(crop.left);
+ *   intCrop.top = (int) ceilf(crop.top);
+ *   intCrop.right = (int) floorf(crop.right);
+ *   intCrop.bottom = (int) floorf(crop.bottom);
+ *
+ * Parameters:
+ *   crop - the new source crop
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_SOURCE_CROP)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_frect_t crop);
+
+/* setLayerTransform(..., transform)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_TRANSFORM
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the transform (rotation/flip) of the given layer.
+ *
+ * Parameters:
+ *   transform - the new transform
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ *   HWC2_ERROR_BAD_PARAMETER - an invalid transform was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_TRANSFORM)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        int32_t /*hwc_transform_t*/ transform);
+
+/* setLayerVisibleRegion(..., visible)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_VISIBLE_REGION
+ * Must be provided by all HWC2 devices
+ *
+ * Specifies the portion of the layer that is visible, including portions under
+ * translucent areas of other layers. The region is in screen space, and will
+ * not exceed the dimensions of the screen.
+ *
+ * Parameters:
+ *   visible - the new visible region, in screen space
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_VISIBLE_REGION)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        hwc_region_t visible);
+
+/* setLayerZOrder(..., z)
+ * Descriptor: HWC2_FUNCTION_SET_LAYER_Z_ORDER
+ * Must be provided by all HWC2 devices
+ *
+ * Sets the desired Z order (height) of the given layer. A layer with a greater
+ * Z value occludes a layer with a lesser Z value.
+ *
+ * Parameters:
+ *   z - the new Z order
+ *
+ * Returns HWC2_ERROR_NONE or one of the following errors:
+ *   HWC2_ERROR_BAD_LAYER - an invalid layer handle was passed in
+ */
+typedef int32_t /*hwc2_error_t*/ (*HWC2_PFN_SET_LAYER_Z_ORDER)(
+        hwc2_device_t* device, hwc2_display_t display, hwc2_layer_t layer,
+        uint32_t z);
+
+__END_DECLS
+
+#endif
diff --git a/include/hardware/hwcomposer_defs.h b/include/hardware/hwcomposer_defs.h
index a19a26c..18b30bc 100644
--- a/include/hardware/hwcomposer_defs.h
+++ b/include/hardware/hwcomposer_defs.h
@@ -26,7 +26,7 @@
 
 __BEGIN_DECLS
 
-/*****************************************************************************/
+/* Shared by HWC1 and HWC2 */
 
 #define HWC_HEADER_VERSION          1
 
@@ -39,6 +39,69 @@
 #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)
 
+#define HWC_DEVICE_API_VERSION_2_0  HARDWARE_DEVICE_API_VERSION_2(2, 0, HWC_HEADER_VERSION)
+
+/**
+ * The id of this module
+ */
+#define HWC_HARDWARE_MODULE_ID "hwcomposer"
+
+/**
+ * Name of the sensors device to open
+ */
+#define HWC_HARDWARE_COMPOSER "composer"
+
+typedef struct hwc_color {
+    uint8_t r;
+    uint8_t g;
+    uint8_t b;
+    uint8_t a;
+} hwc_color_t;
+
+typedef struct hwc_frect {
+    float left;
+    float top;
+    float right;
+    float bottom;
+} hwc_frect_t;
+
+typedef struct hwc_rect {
+    int left;
+    int top;
+    int right;
+    int bottom;
+} hwc_rect_t;
+
+typedef struct hwc_region {
+    size_t numRects;
+    hwc_rect_t const* rects;
+} hwc_region_t;
+
+/*
+ * hwc_layer_t::transform values
+ */
+typedef enum {
+    /* flip source image horizontally */
+    HWC_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H,
+    /* flip source image vertically */
+    HWC_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V,
+    /* rotate source image 90 degrees clock-wise */
+    HWC_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90,
+    /* rotate source image 180 degrees */
+    HWC_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180,
+    /* rotate source image 270 degrees clock-wise */
+    HWC_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270,
+    /* flip source image horizontally, the rotate 90 degrees clock-wise */
+    HWC_TRANSFORM_FLIP_H_ROT_90 = HAL_TRANSFORM_FLIP_H | HAL_TRANSFORM_ROT_90,
+    /* flip source image vertically, the rotate 90 degrees clock-wise */
+    HWC_TRANSFORM_FLIP_V_ROT_90 = HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_ROT_90,
+} hwc_transform_t;
+
+/*******************************************************************************
+ * Beyond this point are things only used by HWC1, which should be ignored when
+ * implementing a HWC2 device
+ ******************************************************************************/
+
 enum {
     /* hwc_composer_device_t::set failed in EGL */
     HWC_EGL_ERROR = -1
@@ -132,22 +195,6 @@
     HWC_BLENDING_COVERAGE = 0x0405
 };
 
-/*
- * hwc_layer_t::transform values
- */
-enum {
-    /* flip source image horizontally */
-    HWC_TRANSFORM_FLIP_H = HAL_TRANSFORM_FLIP_H,
-    /* flip source image vertically */
-    HWC_TRANSFORM_FLIP_V = HAL_TRANSFORM_FLIP_V,
-    /* rotate source image 90 degrees clock-wise */
-    HWC_TRANSFORM_ROT_90 = HAL_TRANSFORM_ROT_90,
-    /* rotate source image 180 degrees */
-    HWC_TRANSFORM_ROT_180 = HAL_TRANSFORM_ROT_180,
-    /* rotate source image 270 degrees clock-wise */
-    HWC_TRANSFORM_ROT_270 = HAL_TRANSFORM_ROT_270,
-};
-
 /* attributes queriable with query() */
 enum {
     /*
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 27cef37..80b2318 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,
@@ -542,6 +570,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..a1868b5
--- /dev/null
+++ b/include/hardware/nvram.h
@@ -0,0 +1,349 @@
+/*
+ * 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>
+
+__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)
+
+/* 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;
+
+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/power.h b/include/hardware/power.h
index 10612f3..29ef4dc 100644
--- a/include/hardware/power.h
+++ b/include/hardware/power.h
@@ -28,6 +28,7 @@
 #define POWER_MODULE_API_VERSION_0_1  HARDWARE_MODULE_API_VERSION(0, 1)
 #define POWER_MODULE_API_VERSION_0_2  HARDWARE_MODULE_API_VERSION(0, 2)
 #define POWER_MODULE_API_VERSION_0_3  HARDWARE_MODULE_API_VERSION(0, 3)
+#define POWER_MODULE_API_VERSION_0_4  HARDWARE_MODULE_API_VERSION(0, 4)
 
 /**
  * The id of this module
@@ -46,7 +47,8 @@
      */
     POWER_HINT_VIDEO_ENCODE = 0x00000003,
     POWER_HINT_VIDEO_DECODE = 0x00000004,
-    POWER_HINT_LOW_POWER = 0x00000005
+    POWER_HINT_LOW_POWER = 0x00000005,
+    POWER_HINT_SUSTAINED_PERFORMANCE = 0x00000006
 } power_hint_t;
 
 typedef enum {
@@ -126,6 +128,14 @@
      *     parameter is non-zero when low power mode is activated, and zero
      *     when deactivated.
      *
+     * POWER_HINT_SUSTAINED_PERFORMANCE
+     *
+     *     Sustained Performance mode is actived or deactivated. Sustained
+     *     performance mode is intended to provide a consistent level of
+     *     performance for a prolonged amount of time. The data parameter is
+     *     non-zero when sustained performance mode is activated, and zero
+     *     when deactivated.
+     *
      * A particular platform may choose to ignore any hint.
      *
      * availability: version 0.2
diff --git a/include/hardware/sensors.h b/include/hardware/sensors.h
index 4bd6c3c..a2d9b2e 100644
--- a/include/hardware/sensors.h
+++ b/include/hardware/sensors.h
@@ -691,6 +691,148 @@
 #define SENSOR_TYPE_DEVICE_ORIENTATION                 (27)
 #define SENSOR_STRING_TYPE_DEVICE_ORIENTATION          "android.sensor.device_orientation"
 
+/*
+ * SENSOR_TYPE_POSE_6DOF
+ * trigger-mode: continuous
+ *
+ * A sensor of this type returns the pose of the device.
+ * Pose of the device is defined as the orientation of the device from a
+ * Earth Centered Earth Fixed frame and the translation from an arbitrary
+ * point at subscription.
+ *
+ * This sensor can be high power. It can use any and all of the following
+ *           . Accelerometer
+ *           . Gyroscope
+ *           . Camera
+ *           . Depth Camera
+ *
+ */
+#define SENSOR_TYPE_POSE_6DOF                         (28)
+#define SENSOR_STRING_TYPE_POSE_6DOF                  "android.sensor.pose_6dof"
+
+/*
+ * SENSOR_TYPE_STATIONARY_DETECT
+ * trigger mode: one shot
+ *
+ * A sensor of this type returns an event if the device is still/stationary for
+ * a while. The period of time to monitor for statinarity should be greater than
+ * 5 seconds, and less than 10 seconds.
+ *
+ * Stationarity here refers to absolute stationarity. eg: device on desk.
+ *
+ * The only allowed value to return is 1.0.
+ */
+#define SENSOR_TYPE_STATIONARY_DETECT                   (29)
+#define SENSOR_STRING_TYPE_STATIONARY_DETECT            "android.sensor.stationary_detect"
+
+/*
+ * SENSOR_TYPE_MOTION_DETECT
+ * trigger mode: one shot
+ *
+ * A sensor of this type returns an event if the device is not still for
+ * a while. The period of time to monitor for statinarity should be greater than
+ * 5 seconds, and less than 10 seconds.
+ *
+ * Motion here refers to any mechanism in which the device is causes to be
+ * moved in its inertial frame. eg: Pickin up the device and walking with it
+ * to a nearby room may trigger motion wherewas keeping the device on a table
+ * on a smooth train moving at constant velocity may not trigger motion.
+ *
+ * The only allowed value to return is 1.0.
+ */
+#define SENSOR_TYPE_MOTION_DETECT                       (30)
+#define SENSOR_STRING_TYPE_MOTION_DETECT                "android.sensor.motion_detect"
+
+/*
+ * SENSOR_TYPE_HEART_BEAT
+ * trigger mode: continuous
+ *
+ * A sensor of this type returns an event everytime a hear beat peak is
+ * detected.
+ *
+ * Peak here ideally corresponds to the positive peak in the QRS complex of
+ * and ECG signal.
+ *
+ * The sensor is not expected to be optimized for latency. As a guide, a
+ * latency of up to 10 seconds is acceptable. However the timestamp attached
+ * to the event should be accurate and should correspond to the time the peak
+ * occured.
+ *
+ * The sensor event contains a parameter for the confidence in the detection
+ * of the peak where 0.0 represent no information at all, and 1.0 represents
+ * certainty.
+ */
+#define SENSOR_TYPE_HEART_BEAT                          (31)
+#define SENSOR_STRING_TYPE_HEART_BEAT                   "android.sensor.heart_beat"
+
+/**
+ * SENSOR_TYPE_DYNAMIC_SENSOR_META
+ * trigger-mode: special
+ *
+ * A sensor event of this type is received when a dynamic sensor is added to or removed from the
+ * system. At most one sensor of this type can be present in one sensor HAL implementation and
+ * presence of a sensor of this type in sensor HAL implementation indicates that this sensor HAL
+ * supports dynamic sensor feature. Operations, such as batch, activate and setDelay, to this
+ * special purpose sensor should be treated as no-op and return successful.
+ *
+ * A dynamic sensor connection indicates connection of a physical device or instantiation of a
+ * virtual sensor backed by algorithm; and a dynamic sensor disconnection indicates the the
+ * opposite. A sensor event of SENSOR_TYPE_DYNAMIC_SENSOR_META type should be delivered regardless
+ * of the activation status of the sensor in the event of dynamic sensor connection and
+ * disconnection. In the sensor event, besides the common data entries, "dynamic_sensor_meta", which
+ * includes fields for connection status, handle of the sensor involved, pointer to sensor_t
+ * structure and a uuid field, should be populated.
+ *
+ * At a dynamic sensor connection event, fields of sensor_t structure referenced by a pointer in
+ * dynamic_sensor_meta should be filled as if it was regular sensors. Sensor HAL is responsible for
+ * recovery of memory if the corresponding data is dynamicially allocated. However, the the pointer
+ * must be valid until the first activate call to the sensor reported in this connection event. At a
+ * dynamic sensor disconnection, the sensor_t pointer should be NULL.
+ *
+ * The sensor handle assigned to dynamic sensors should never be the same as that of any regular
+ * static sensors, and should be unique until next boot. In another word, if a handle h is used for
+ * a dynamic sensor A, that same number cannot be used for the same dynamic sensor A or another
+ * dynamic sensor B even after disconnection of A until reboot.
+ *
+ * The UUID field will be used for identifying the sensor in addition to name, vendor and version
+ * and type. For physical sensors of the same model, all sensors will have the same values in
+ * sensor_t, but the UUID should be unique and persistent for each individual unit. An all zero UUID
+ * indicates it is not possible to differentiate individual sensor unit.
+ *
+ */
+#define SENSOR_TYPE_DYNAMIC_SENSOR_META                         (32)
+#define SENSOR_STRING_TYPE_DYNAMIC_SENSOR_META                  "android.sensor.dynamic_sensor_meta"
+
+/**
+ * SENSOR_TYPE_ADDITIONAL_INFO
+ * reporting-mode: N/A
+ *
+ * This sensor type is for delivering additional sensor information aside from sensor event data.
+ * Additional information may include sensor front-end group delay, internal calibration parameters,
+ * noise level metrics, device internal temperature, etc.
+ *
+ * This type will never bind to a sensor. In other words, no sensor in the sensor list should be of
+ * the type SENSOR_TYPE_ADDITIONAL_INFO. If a sensor HAL supports sensor additional information
+ * feature, it reports sensor_event_t with "sensor" field set to handle of the reporting sensor and
+ * "type" field set to SENSOR_TYPE_ADDITIONAL_INFO. Delivery of additional information events is
+ * triggered under two conditions: an enable activate() call or a flush() call to the corresponding
+ * sensor.
+ *
+ * A single additional information report consists of multiple frames. Sequences of these frames are
+ * ordered using timestamps, which means the timestamps of sequential frames have to be at least 1
+ * nanosecond apart from each other. Each frame is a sensor_event_t delivered through the HAL
+ * interface, with related data stored in the "additional_info" field, which is of type
+ * additional_info_event_t.  The "type" field of additional_info_event_t denotes the nature of the
+ * payload data (see additional_info_type_t).  The "serial" field is used to keep the sequence of
+ * payload data that spans multiple frames. The first frame of the entire report is always of type
+ * AINFO_BEGIN, and the last frame is always AINFO_END.
+ *
+ * All additional information frames have to be delivered after flush complete event if flush() was
+ * triggering the report.
+ */
+#define SENSOR_TYPE_ADDITIONAL_INFO                       (33)
+#define SENSOR_STRING_TYPE_ADDITIONAL_INFO                "android.sensor.additional_info"
+
 /**
  * Values returned by the accelerometer in various locations in the universe.
  * all values are in SI units (m/s^2)
@@ -713,6 +855,9 @@
 #define SENSOR_STATUS_ACCURACY_MEDIUM   2
 #define SENSOR_STATUS_ACCURACY_HIGH     3
 
+
+struct sensor_t;
+
 /**
  * sensor event data
  */
@@ -765,6 +910,17 @@
 } meta_data_event_t;
 
 /**
+ * Dynamic sensor meta event. See the description of SENSOR_TYPE_DYNAMIC_SENSOR_META type for
+ * details.
+ */
+typedef struct dynamic_sensor_meta_event {
+    int32_t  connected;
+    int32_t  handle;
+    const struct sensor_t * sensor; // should be NULL if connected == false
+    uint8_t uuid[16];               // UUID of a dynamic sensor (use platform endianess).
+} dynamic_sensor_meta_event_t;
+
+/**
  * Heart rate event data
  */
 typedef struct {
@@ -778,6 +934,85 @@
   int8_t status;
 } heart_rate_event_t;
 
+typedef struct {
+    int32_t type;                           // type of payload data, see additional_info_type_t
+    int32_t serial;                         // sequence number of this frame for this type
+    union {
+        // for each frame, a single data type, either int32_t or float, should be used.
+        int32_t data_int32[14];
+        float   data_float[14];
+    };
+} additional_info_event_t;
+
+typedef enum additional_info_type {
+    //
+    AINFO_BEGIN = 0x0,                      // Marks the beginning of additional information frames
+    AINFO_END   = 0x1,                      // Marks the end of additional information frames
+    // Basic information
+    AINFO_UNTRACKED_DELAY =  0x10000,       // Estimation of the delay that is not tracked by sensor
+                                            // timestamps. This includes delay introduced by
+                                            // sensor front-end filtering, data transport, etc.
+                                            // float[2]: delay in seconds
+                                            //           standard deviation of estimated value
+                                            //
+    AINFO_INTERNAL_TEMPERATURE,             // float: Celsius temperature.
+                                            //
+    AINFO_VEC3_CALIBRATION,                 // First three rows of a homogeneous matrix, which
+                                            // represents calibration to a three-element vector
+                                            // raw sensor reading.
+                                            // float[12]: 3x4 matrix in row major order
+                                            //
+    AINFO_SENSOR_PLACEMENT,                 // Location and orientation of sensor element in the
+                                            // device frame: origin is the geometric center of the
+                                            // mobile device screen surface; the axis definition
+                                            // corresponds to Android sensor definitions.
+                                            // float[12]: 3x4 matrix in row major order
+                                            //
+    AINFO_SAMPLING,                         // float[2]: raw sample period in seconds,
+                                            //           standard deviation of sampling period
+
+    // Sampling channel modeling information
+    AINFO_CHANNEL_NOISE = 0x20000,          // int32_t: noise type
+                                            // float[n]: parameters
+                                            //
+    AINFO_CHANNEL_SAMPLER,                  // float[3]: sample period
+                                            //           standard deviation of sample period,
+                                            //           quantization unit
+                                            //
+    AINFO_CHANNEL_FILTER,                   // Represents a filter:
+                                            //      \sum_j a_j y[n-j] == \sum_i b_i x[n-i]
+                                            //
+                                            // int32_t[3]: number of feedforward coefficients, M,
+                                            //             number of feedback coefficients, N, for
+                                            //               FIR filter, N=1.
+                                            //             bit mask that represents which element to
+                                            //               which the filter is applied, bit 0 == 1
+                                            //               means this filter applies to vector
+                                            //               element 0.
+                                            // float[M+N]: filter coefficients (b0, b1, ..., BM-1),
+                                            //             then (a0, a1, ..., aN-1), a0 is always 1.
+                                            //             Multiple frames may be needed for higher
+                                            //             number of taps.
+                                            //
+    AINFO_CHANNEL_LINEAR_TRANSFORM,         // int32_t[2]: size in (row, column) ... 1st frame
+                                            // float[n]: matrix element values in row major order.
+                                            //
+    AINFO_CHANNEL_NONLINEAR_MAP,            // int32_t[2]: extrapolate method
+                                            //             interpolate method
+                                            // float[n]: mapping key points in pairs, (in, out)...
+                                            //           (may be used to model saturation)
+                                            //
+    AINFO_CHANNEL_RESAMPLER,                // int32_t:  resample method (0-th order, 1st order...)
+                                            // float[1]: resample ratio (upsampling if < 1.0;
+                                            //           downsampling if > 1.0).
+                                            //
+
+    // Custom information
+    AINFO_CUSTOM_START =    0x10000000,     //
+    // Debugging
+    AINFO_DEBUGGING_START = 0x40000000,     //
+} additional_info_type_t;
+
 /**
  * Union of the various types of sensor data
  * that can be returned.
@@ -843,6 +1078,15 @@
              * SENSOR_TYPE_META_DATA. The handle is ignored and must be zero.
              */
             meta_data_event_t meta_data;
+
+            /* dynamic sensor meta event. See SENSOR_TYPE_DYNAMIC_SENSOR_META type for details */
+            dynamic_sensor_meta_event_t dynamic_sensor_meta;
+
+            /*
+             * special additional sensor information frame, see
+             * SENSOR_TYPE_ADDITIONAL_INFO for details.
+             */
+            additional_info_event_t additional_info;
         };
 
         union {
@@ -864,8 +1108,6 @@
 typedef sensors_event_t sensors_meta_data_event_t;
 
 
-struct sensor_t;
-
 /**
  * Every hardware module must have a data structure named HAL_MODULE_INFO_SYM
  * and the fields of this data structure must begin with hw_module_t
@@ -885,7 +1127,7 @@
      *  Place the module in a specific mode. The following modes are defined
      *
      *  0 - Normal operation. Default state of the module.
-     *  1 - Loopback mode. Data is injected for the the supported
+     *  1 - Loopback mode. Data is injected for the supported
      *      sensors by the sensor service in this mode.
      * @return 0 on success
      *         -EINVAL if requested mode is not supported
diff --git a/include/hardware/vehicle.h b/include/hardware/vehicle.h
index 36d6cdb..df4753a 100644
--- a/include/hardware/vehicle.h
+++ b/include/hardware/vehicle.h
@@ -896,20 +896,20 @@
  *  include config_string of "com.XYZ.some_further_details".
  *  @range_start
  */
-#define VEHICLE_PROPERTY_CUSTOM_START                       (0xf0000000)
+#define VEHICLE_PROPERTY_CUSTOM_START                       (0x70000000)
 /** @range_end */
-#define VEHICLE_PROPERTY_CUSTOM_END                         (0xf7ffffff)
+#define VEHICLE_PROPERTY_CUSTOM_END                         (0x73ffffff)
 
 /**
  * Property range allocated for system's internal usage like testing. HAL should never declare
  * property in this range.
  * @range_start
  */
-#define VEHICLE_PROPERTY_INTERNAL_START                     (0xf8000000)
+#define VEHICLE_PROPERTY_INTERNAL_START                     (0x74000000)
 /**
  * @range_end
  */
-#define VEHICLE_PROPERTY_INTERNAL_END                       (0xf8ffffff)
+#define VEHICLE_PROPERTY_INTERNAL_END                       (0x74ffffff)
 
 /**
  * Value types for various properties.
diff --git a/include/hardware/vr.h b/include/hardware/vr.h
new file mode 100644
index 0000000..494f016
--- /dev/null
+++ b/include/hardware/vr.h
@@ -0,0 +1,104 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_INCLUDE_HARDWARE_VR_H
+#define ANDROID_INCLUDE_HARDWARE_VR_H
+
+#include <stdbool.h>
+#include <sys/cdefs.h>
+#include <hardware/hardware.h>
+
+__BEGIN_DECLS
+
+#define VR_HARDWARE_MODULE_ID "vr_module"
+
+#define VR_MODULE_API_VERSION_1_0 HARDWARE_MODULE_API_VERSION(1, 0)
+
+/**
+ * Implement this HAL to receive callbacks when a virtual reality (VR)
+ * application is being used.  VR applications characteristically have a number
+ * of special display and performance requirements, including:
+ * - Low sensor latency - Total end-to-end latency from the IMU, accelerometer,
+ *   and gyro to an application-visible callback must be extremely low (<5ms
+ *   typically).  This is required for HIFI sensor support.
+ * - Low display latency - Total end-to-end latency from the GPU draw calls to
+ *   the actual display update must be as low as possible.  This is typically
+ *   achieved by using SurfaceFlinger in a single-buffered mode, and assuring
+ *   that draw calls are synchronized with the display scanout correctly.  Any
+ *   GPU settings required to allow consistent performance of this operation
+ *   are required, including the EGL extensions: EGL_IMG_context_priority, and
+ *   EGL_XXX_set_render_buffer_mode.
+ * - Low-persistence display - Display persistence settings must be set as low as
+ *   possible while still maintaining a reasonable brightness.  For a typical
+ *   display running at 60Hz, pixels should be illuminated for <4ms to be
+ *   considered low-persistence (<2ms is desirable).  This avoids ghosting
+ *   during movements in a VR setting.
+ * - Consistent performance of the GPU and CPU - When given a mixed GPU/CPU
+ *   workload for a VR application with bursts of work at regular intervals
+ *   several times a frame.  CPU scheduling should ensure that the application
+ *   render thread is run consistently within 1ms of when required for the
+ *   draw window, and an appropriate clockrate is maintained to ensure the
+ *   workload finishes within the time alloted to the draw window.  Likewise,
+ *   GPU scheduling should ensure that work from the application render thread
+ *   is given priority over other GPU work, and that a high enough clockrate can
+ *   be maintained to ensure that this completes within the draw window.  CTS
+ *   tests with example VR workloads will be available to assess performance
+ *   tuning.
+ *
+ * Vendors implementing this HAL are expected to use set_vr_mode as a hint to
+ * enable VR-specific performance tuning, and to turn on any device features
+ * optimal for VR display modes (or do nothing if none are available). Devices
+ * that advertise FEATURE_VR_MODE_HIGH_PERFORMANCE are must pass the additional
+ * CTS performance tests required for this feature and follow the additional
+ * guidelines for hardware implementation for "VR Ready" devices.
+ *
+ * No methods in this HAL will be called concurrently from the Android framework.
+ */
+typedef struct vr_module {
+    /**
+     * Common methods of the  module.  This *must* be the first member of
+     * vr_module as users of * this structure will cast a hw_module_t to a
+     * vr_module pointer in contexts where it's known that the hw_module_t
+     * references a vr_module.
+     */
+    struct hw_module_t common;
+
+    /**
+     * Convenience method for the HAL implementation to set up any state needed
+     * at runtime startup.  This is called once from the VrManagerService during
+     * its boot phase.  No methods from this HAL will be called before init.
+     */
+    void (*init)(struct vr_module *module);
+
+    /**
+     * Set the VR mode state.  Possible states of the enabled parameter are:
+     * false - VR mode is disabled, turn off all VR-specific settings.
+     * true - VR mode is enabled, turn on all VR-specific settings.
+     *
+     * This is called from the VrManagerService whenever the application(s)
+     * currently in use enters or leaves VR mode. This will typically occur
+     * when the user switches or from an application that has indicated to
+     * system_server that it should run in VR mode.
+     */
+    void (*set_vr_mode)(struct vr_module *module, bool enabled);
+
+    /* Reserved for future use. Must be NULL. */
+    void* reserved[8 - 2];
+} vr_module_t;
+
+__END_DECLS
+
+#endif /* ANDROID_INCLUDE_HARDWARE_VR_H */
diff --git a/modules/Android.mk b/modules/Android.mk
index 4f30d3c..3dc4ca6 100644
--- a/modules/Android.mk
+++ b/modules/Android.mk
@@ -1,4 +1,4 @@
 hardware_modules := gralloc hwcomposer audio nfc nfc-nci local_time \
 	power usbaudio audio_remote_submix camera usbcamera consumerir sensors vibrator \
-	tv_input fingerprint input vehicle
+	tv_input fingerprint input vehicle hardware_properties vr
 include $(call all-named-subdir-makefiles,$(hardware_modules))
diff --git a/modules/audio_remote_submix/audio_hw.cpp b/modules/audio_remote_submix/audio_hw.cpp
index ed3d311..d94834d 100644
--- a/modules/audio_remote_submix/audio_hw.cpp
+++ b/modules/audio_remote_submix/audio_hw.cpp
@@ -823,7 +823,7 @@
                 const size_t flush_size = min(frames_to_flush_from_source, flushBufferSizeFrames);
                 frames_to_flush_from_source -= flush_size;
                 // read does not block
-                source->read(flush_buffer, flush_size, AudioBufferProvider::kInvalidPTS);
+                source->read(flush_buffer, flush_size);
             }
         }
     }
@@ -1192,7 +1192,7 @@
 
             SUBMIX_ALOGV("in_read(): frames available to read %zd", source->availableToRead());
 
-            frames_read = source->read(buff, read_frames, AudioBufferProvider::kInvalidPTS);
+            frames_read = source->read(buff, read_frames);
 
             SUBMIX_ALOGV("in_read(): frames read %zd", frames_read);
 
diff --git a/modules/hardware_properties/Android.mk b/modules/hardware_properties/Android.mk
new file mode 100644
index 0000000..41c02ea
--- /dev/null
+++ b/modules/hardware_properties/Android.mk
@@ -0,0 +1,25 @@
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := hardware_properties.default
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := hardware_properties.c
+LOCAL_SHARED_LIBRARIES := liblog
+LOCAL_MODULE_TAGS := optional
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/modules/hardware_properties/hardware_properties.c b/modules/hardware_properties/hardware_properties.c
new file mode 100644
index 0000000..89ef423
--- /dev/null
+++ b/modules/hardware_properties/hardware_properties.c
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ */
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define LOG_TAG "HardwarePropertiesHAL"
+#include <utils/Log.h>
+
+#include <hardware/hardware.h>
+#include <hardware/hardware_properties.h>
+
+static ssize_t get_device_temperatures(
+    struct hardware_properties_module *module, float **temps) {
+    *temps = NULL;
+    errno = ENOSYS;
+    ALOGE("getDeviceTemperatures: %s", strerror(errno));
+    return -1;
+}
+
+static ssize_t get_cpu_usages(struct hardware_properties_module *module,
+                              int64_t **active_times, int64_t **total_times) {
+    *active_times = NULL;
+    *total_times = NULL;
+    errno = ENOSYS;
+    ALOGE("getCpuUsages: %s", strerror(errno));
+    return -1;
+}
+
+static ssize_t get_fan_speeds(struct hardware_properties_module *module,
+                              float **fan_speeds) {
+    *fan_speeds = NULL;
+    errno = ENOSYS;
+    ALOGE("getFanSpeeds: %s", strerror(errno));
+    return -1;
+}
+
+static struct hw_module_methods_t hardware_properties_module_methods = {
+    .open = NULL,
+};
+
+struct hardware_properties_module HAL_MODULE_INFO_SYM = {
+    .common = {
+        .tag = HARDWARE_MODULE_TAG,
+        .module_api_version = HARDWARE_PROPERTIES_HARDWARE_MODULE_API_VERSION_0_1,
+        .hal_api_version = HARDWARE_HAL_API_VERSION,
+        .id = HARDWARE_PROPERTIES_HARDWARE_MODULE_ID,
+        .name = "Default Hardware Properties HAL",
+        .author = "The Android Open Source Project",
+        .methods = &hardware_properties_module_methods,
+    },
+
+    .getCpuTemperatures = get_device_temperatures,
+    .getGpuTemperatures = get_device_temperatures,
+    .getBatteryTemperatures = get_device_temperatures,
+    .getCpuUsages = get_cpu_usages,
+    .getFanSpeeds = get_fan_speeds,
+};
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 := \
diff --git a/modules/soundtrigger/sound_trigger_hw.c b/modules/soundtrigger/sound_trigger_hw.c
index e7f9baf..2c1cc9c 100644
--- a/modules/soundtrigger/sound_trigger_hw.c
+++ b/modules/soundtrigger/sound_trigger_hw.c
@@ -14,10 +14,35 @@
  * limitations under the License.
  */
 
+
+/* This HAL simulates triggers from the DSP.
+ * To send a trigger from the command line you can type:
+ *
+ * adb forward tcp:14035 tcp:14035
+ * echo $'\001' | nc -q -1 localhost 14035
+ *
+ * $'\001' corresponds to the index_position of loaded sound
+ * model, you can also send $'\002' etc. $'\000' is the kill
+ * signal for the trigger listening thread.
+ *
+ * To enable this file, you can make with command line parameter
+ * SOUND_TRIGGER_USE_STUB_MODULE=1
+ */
+
 #define LOG_TAG "sound_trigger_hw_default"
 /*#define LOG_NDEBUG 0*/
 
 #include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <arpa/inet.h>
+#include <sys/types.h>
+#include <netinet/in.h>
+#include <sys/socket.h>
+
+#include <errno.h>
 #include <pthread.h>
 #include <sys/prctl.h>
 #include <cutils/log.h>
@@ -26,12 +51,16 @@
 #include <system/sound_trigger.h>
 #include <hardware/sound_trigger.h>
 
+/* Although max_sound_models is specified in sound_trigger_properties, having a maximum maximum
+allows a dramatic simplification of data structures in this file */
+#define MAX_MAX_SOUND_MODELS 5
+
 static const struct sound_trigger_properties hw_properties = {
         "The Android Open Source Project", // implementor
         "Sound Trigger stub HAL", // description
         1, // version
         { 0xed7a7d60, 0xc65e, 0x11e3, 0x9be4, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } }, // uuid
-        1, // max_sound_models
+        2, // max_sound_models
         1, // max_key_phrases
         1, // max_users
         RECOGNITION_MODE_VOICE_TRIGGER, // recognition_modes
@@ -42,68 +71,207 @@
         0 // power_consumption_mw
 };
 
-struct stub_sound_trigger_device {
-    struct sound_trigger_hw_device device;
-    sound_model_handle_t model_handle;
-    recognition_callback_t recognition_callback;
-    void *recognition_cookie;
+struct recognition_context {
+      /* Sound Model Information Modified On Load */
+    sound_model_handle_t loaded_sound_model;
     sound_model_callback_t sound_model_callback;
     void *sound_model_cookie;
-    pthread_t callback_thread;
-    pthread_mutex_t lock;
-    pthread_cond_t  cond;
+
+    /* Sound Model Information Modified On Recognition Start */
+    struct sound_trigger_recognition_config *config;
+    recognition_callback_t recognition_callback;
+    void *recognition_cookie;
 };
 
+struct stub_sound_trigger_device {
+    struct sound_trigger_hw_device device;
+    pthread_mutex_t lock;
+    pthread_t callback_thread;
 
-static void *callback_thread_loop(void *context)
-{
+    struct recognition_context model_context[MAX_MAX_SOUND_MODELS];
+
+    int next_sound_model_id;
+};
+
+/* Will reuse ids when overflow occurs */
+static unsigned int generate_sound_model_id(const struct sound_trigger_hw_device *dev) {
+    struct stub_sound_trigger_device *stdev = (struct stub_sound_trigger_device *)dev;
+    int new_id = stdev->next_sound_model_id;
+    ++stdev->next_sound_model_id;
+    if (stdev->next_sound_model_id == 0) {
+        stdev->next_sound_model_id = 1;
+    }
+    return new_id;
+}
+
+static char *sound_trigger_event_alloc(struct stub_sound_trigger_device *stdev,
+                                       sound_model_handle_t handle) {
+    struct sound_trigger_phrase_recognition_event *event;
+    char *data;
+    data = (char *)calloc(1, sizeof(struct sound_trigger_phrase_recognition_event));
+    if (!data)
+        return NULL;
+
+    unsigned int model_index;
+    bool found = false;
+    for(model_index = 0; model_index < hw_properties.max_sound_models; model_index++) {
+        if (stdev->model_context[model_index].loaded_sound_model == handle) {
+            found = true;
+            break;
+        }
+    }
+    if (found == false) {
+        ALOGW("Can't find model");
+        return NULL;
+    }
+
+    event = (struct sound_trigger_phrase_recognition_event *)data;
+    event->common.status = RECOGNITION_STATUS_SUCCESS;
+    event->common.type = SOUND_MODEL_TYPE_KEYPHRASE;
+    event->common.model = handle;
+
+    if (stdev->model_context[model_index].config) {
+        unsigned int i;
+
+        event->num_phrases = stdev->model_context[model_index].config->num_phrases;
+        if (event->num_phrases > SOUND_TRIGGER_MAX_PHRASES)
+            event->num_phrases = SOUND_TRIGGER_MAX_PHRASES;
+        for (i=0; i < event->num_phrases; i++)
+            memcpy(&event->phrase_extras[i], &stdev->model_context[model_index].config->phrases[i],
+                   sizeof(struct sound_trigger_phrase_recognition_extra));
+    }
+
+    event->num_phrases = 1;
+    event->phrase_extras[0].confidence_level = 100;
+    event->phrase_extras[0].num_levels = 1;
+    event->phrase_extras[0].levels[0].level = 100;
+    event->phrase_extras[0].levels[0].user_id = 0;
+    // Signify that all the data is comming through streaming, not through the buffer.
+    event->common.capture_available = true;
+
+    event->common.audio_config = AUDIO_CONFIG_INITIALIZER;
+    event->common.audio_config.sample_rate = 16000;
+    event->common.audio_config.channel_mask = AUDIO_CHANNEL_IN_MONO;
+    event->common.audio_config.format = AUDIO_FORMAT_PCM_16_BIT;
+
+    return data;
+}
+
+static void *callback_thread_loop(void *context) {
     struct stub_sound_trigger_device *stdev = (struct stub_sound_trigger_device *)context;
-    ALOGI("%s", __func__);
+    struct sockaddr_in incoming_info;
+    struct sockaddr_in self_info;
+    int self_socket;
+    socklen_t sock_size = sizeof(struct sockaddr_in);
+    memset(&self_info, 0, sizeof(self_info));
+    self_info.sin_family = AF_INET;
+    self_info.sin_addr.s_addr = htonl(INADDR_ANY);
+    self_info.sin_port = htons(14035);
 
-    prctl(PR_SET_NAME, (unsigned long)"sound trigger callback", 0, 0, 0);
+    bool exit = false;
+    while(!exit) {
+        int received_count;
+        int requested_count = 1;
+        char buffer[requested_count];
+        ALOGE("Opening socket");
+        self_socket = socket(AF_INET, SOCK_STREAM, 0);
+        if (self_socket < 0) {
+            ALOGE("Error on socket creation");
+            exit = true;
+        } else {
+            ALOGI("Socket created");
+        }
 
-    pthread_mutex_lock(&stdev->lock);
-    if (stdev->recognition_callback == NULL) {
-        goto exit;
+        int reuse = 1;
+        if (setsockopt(self_socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0) {
+            ALOGE("setsockopt(SO_REUSEADDR) failed");
+        }
+
+        int bind_result = bind(self_socket, (struct sockaddr *)&self_info, sizeof(struct sockaddr));
+        if (bind_result < 0) {
+            ALOGE("Error on bind");
+            exit = true;
+        }
+
+        int listen_result = listen(self_socket, 1);
+        if (listen_result < 0) {
+            ALOGE("Error on Listen");
+            exit = true;
+        }
+
+        while(!exit) {
+            int con_socket = accept(self_socket, (struct sockaddr *)&incoming_info, &sock_size);
+            if (!con_socket) {
+                ALOGE("Lost socket, cannot send trigger");
+                break;
+            }
+            ALOGI("Connection from %s", inet_ntoa(incoming_info.sin_addr));
+            received_count = recv(con_socket, buffer, requested_count, 0);
+            unsigned int index = buffer[0] - 1;
+            ALOGI("Received data");
+            pthread_mutex_lock(&stdev->lock);
+            if (received_count > 0) {
+                if (buffer[0] == 0) {
+                    ALOGI("Received kill signal: stop listening to incoming server messages");
+                    exit = true;
+                } else if (index < hw_properties.max_sound_models) {
+                    ALOGI("Going to send trigger for model #%d", index );
+                    if (stdev->model_context[index].recognition_callback != NULL) {
+                        sound_model_handle_t handle = stdev->model_context[index].loaded_sound_model;
+                        if (handle == 0) {
+                            ALOGW("This trigger is not loaded");
+                        } else {
+                            struct sound_trigger_phrase_recognition_event *event;
+                            event = (struct sound_trigger_phrase_recognition_event *)
+                                   sound_trigger_event_alloc(stdev, handle);
+                            if (event) {
+                               ALOGI("%s send callback model %d", __func__, index);
+                               stdev->model_context[index].recognition_callback(&event->common,
+                                                     stdev->model_context[index].recognition_cookie);
+                               free(event);
+                               stdev->model_context[index].recognition_callback = NULL;
+                            }
+                            exit = true;
+                        }
+                    } else {
+                       ALOGI("%s No matching callback for %d", __func__, index);
+                    }
+                } else {
+                    ALOGI("Data is not recognized: %d", index);
+                }
+            } else {
+                ALOGI("Received sata is size 0");
+            }
+            pthread_mutex_unlock(&stdev->lock);
+            close(con_socket);
+        }
+        ALOGE("Closing socket");
+        close(self_socket);
     }
-    struct timespec ts;
-    clock_gettime(CLOCK_REALTIME, &ts);
-    ts.tv_sec += 3;
-    ALOGI("%s wait 3 sec", __func__);
-    int rc = pthread_cond_timedwait(&stdev->cond, &stdev->lock, &ts);
-    if (rc == ETIMEDOUT && stdev->recognition_callback != NULL) {
-        char *data = (char *)calloc(1, sizeof(struct sound_trigger_phrase_recognition_event) + 1);
-        struct sound_trigger_phrase_recognition_event *event =
-                (struct sound_trigger_phrase_recognition_event *)data;
-        event->common.status = RECOGNITION_STATUS_SUCCESS;
-        event->common.type = SOUND_MODEL_TYPE_KEYPHRASE;
-        event->common.model = stdev->model_handle;
-        event->num_phrases = 1;
-        event->phrase_extras[0].recognition_modes = RECOGNITION_MODE_VOICE_TRIGGER;
-        event->phrase_extras[0].confidence_level = 100;
-        event->phrase_extras[0].num_levels = 1;
-        event->phrase_extras[0].levels[0].level = 100;
-        event->phrase_extras[0].levels[0].user_id = 0;
-        event->common.data_offset = sizeof(struct sound_trigger_phrase_recognition_event);
-        event->common.data_size = 1;
-        data[event->common.data_offset] = 8;
-        ALOGI("%s send callback model %d", __func__, stdev->model_handle);
-        stdev->recognition_callback(&event->common, stdev->recognition_cookie);
-        free(data);
-    } else {
-        ALOGI("%s abort recognition model %d", __func__, stdev->model_handle);
-    }
-    stdev->recognition_callback = NULL;
-
-exit:
-    pthread_mutex_unlock(&stdev->lock);
 
     return NULL;
 }
 
+static void send_loop_kill_signal() {
+    ALOGI("Sending loop thread kill signal");
+    int self_socket = socket(AF_INET, SOCK_STREAM, 0);
+    struct sockaddr_in remote_info;
+    memset(&remote_info, 0, sizeof(remote_info));
+    remote_info.sin_family = AF_INET;
+    remote_info.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+    remote_info.sin_port = htons(14035);
+    if (connect(self_socket, (struct sockaddr *)&remote_info, sizeof(struct sockaddr)) == 0) {
+        char msg[] = {0};
+        send(self_socket, msg, 1, 0);
+    } else {
+        ALOGI("Could not connect");
+    }
+    close(self_socket);
+    ALOGI("Sent loop thread kill signal");
+}
+
 static int stdev_get_properties(const struct sound_trigger_hw_device *dev,
-                                struct sound_trigger_properties *properties)
-{
+                                struct sound_trigger_properties *properties) {
     struct stub_sound_trigger_device *stdev = (struct stub_sound_trigger_device *)dev;
 
     ALOGI("%s", __func__);
@@ -117,140 +285,197 @@
                                   struct sound_trigger_sound_model *sound_model,
                                   sound_model_callback_t callback,
                                   void *cookie,
-                                  sound_model_handle_t *handle)
-{
+                                  sound_model_handle_t *handle) {
     struct stub_sound_trigger_device *stdev = (struct stub_sound_trigger_device *)dev;
     int status = 0;
 
     ALOGI("%s stdev %p", __func__, stdev);
     pthread_mutex_lock(&stdev->lock);
+
     if (handle == NULL || sound_model == NULL) {
-        status = -EINVAL;
-        goto exit;
+        pthread_mutex_unlock(&stdev->lock);
+        return -EINVAL;
     }
     if (sound_model->data_size == 0 ||
             sound_model->data_offset < sizeof(struct sound_trigger_sound_model)) {
-        status = -EINVAL;
-        goto exit;
+        pthread_mutex_unlock(&stdev->lock);
+        return -EINVAL;
     }
 
-    if (stdev->model_handle == 1) {
-        status = -ENOSYS;
-        goto exit;
+    /* Find if there is space for this sound model */
+    unsigned int model_index;
+    bool found = false;
+    for(model_index = 0; model_index < hw_properties.max_sound_models; model_index++) {
+        if (stdev->model_context[model_index].loaded_sound_model == 0) {
+            found = true;
+            break;
+        }
     }
+    if (found == false) {
+        ALOGW("Can't load model: reached max sound model limit");
+        pthread_mutex_unlock(&stdev->lock);
+        return -ENOSYS;
+    }
+
+    stdev->model_context[model_index].loaded_sound_model = generate_sound_model_id(dev);
+    *handle = stdev->model_context[model_index].loaded_sound_model;
+
     char *data = (char *)sound_model + sound_model->data_offset;
     ALOGI("%s data size %d data %d - %d", __func__,
           sound_model->data_size, data[0], data[sound_model->data_size - 1]);
-    stdev->model_handle = 1;
-    stdev->sound_model_callback = callback;
-    stdev->sound_model_cookie = cookie;
+    stdev->model_context[model_index].sound_model_callback = callback;
+    stdev->model_context[model_index].sound_model_cookie = cookie;
 
-    *handle = stdev->model_handle;
-
-exit:
     pthread_mutex_unlock(&stdev->lock);
     return status;
 }
 
 static int stdev_unload_sound_model(const struct sound_trigger_hw_device *dev,
-                                    sound_model_handle_t handle)
-{
+                                    sound_model_handle_t handle) {
     struct stub_sound_trigger_device *stdev = (struct stub_sound_trigger_device *)dev;
     int status = 0;
-
-    ALOGI("%s handle %d", __func__, handle);
+    ALOGI("unload_sound_model");
     pthread_mutex_lock(&stdev->lock);
-    if (handle != 1) {
-        status = -EINVAL;
-        goto exit;
+
+    unsigned int i;
+    unsigned int model_index;
+    bool found = false;
+    bool other_callbacks_found = false;
+    for(i = 0; i < hw_properties.max_sound_models; i++) {
+        if (stdev->model_context[i].loaded_sound_model == handle) {
+            found = true;
+            model_index = i;
+            break;
+        } else if (stdev->model_context[i].recognition_callback != NULL) {
+            other_callbacks_found = true;
+        }
     }
-    if (stdev->model_handle == 0) {
-        status = -ENOSYS;
-        goto exit;
-    }
-    stdev->model_handle = 0;
-    if (stdev->recognition_callback != NULL) {
-        stdev->recognition_callback = NULL;
-        pthread_cond_signal(&stdev->cond);
+    if (found == false) {
+        ALOGW("Can't sound model %d in registered list", handle);
         pthread_mutex_unlock(&stdev->lock);
-        pthread_join(stdev->callback_thread, (void **) NULL);
-        pthread_mutex_lock(&stdev->lock);
+        return -ENOSYS;
     }
 
-exit:
-    pthread_mutex_unlock(&stdev->lock);
+    stdev->model_context[i].loaded_sound_model = 0;
+    stdev->model_context[i].sound_model_callback = NULL;
+    stdev->model_context[i].sound_model_cookie = NULL;
+
+    free(stdev->model_context[i].config);
+    stdev->model_context[i].config = NULL;
+    stdev->model_context[i].recognition_callback = NULL;
+    stdev->model_context[i].recognition_cookie = NULL;
+
+    /* If no more models running with callbacks, stop trigger thread */
+    if (!other_callbacks_found) {
+        send_loop_kill_signal();
+        pthread_mutex_unlock(&stdev->lock);
+        pthread_join(stdev->callback_thread, (void **)NULL);
+    } else {
+        pthread_mutex_unlock(&stdev->lock);
+    }
+
     return status;
 }
 
 static int stdev_start_recognition(const struct sound_trigger_hw_device *dev,
-                                   sound_model_handle_t sound_model_handle,
+                                   sound_model_handle_t handle,
                                    const struct sound_trigger_recognition_config *config,
                                    recognition_callback_t callback,
-                                   void *cookie)
-{
+                                   void *cookie) {
+    ALOGI("%s", __func__);
     struct stub_sound_trigger_device *stdev = (struct stub_sound_trigger_device *)dev;
-    int status = 0;
-    ALOGI("%s sound model %d", __func__, sound_model_handle);
     pthread_mutex_lock(&stdev->lock);
-    if (stdev->model_handle != sound_model_handle) {
-        status = -ENOSYS;
-        goto exit;
+    unsigned int i;
+    bool found = false;
+    for(i = 0; i < hw_properties.max_sound_models; i++) {
+        if (stdev->model_context[i].loaded_sound_model == handle) {
+            found = true;
+            break;
+        }
     }
-    if (stdev->recognition_callback != NULL) {
-        status = -ENOSYS;
-        goto exit;
-    }
-    if (config->data_size != 0) {
-        char *data = (char *)config + config->data_offset;
-        ALOGI("%s data size %d data %d - %d", __func__,
-              config->data_size, data[0], data[config->data_size - 1]);
+    if (found == false) {
+        ALOGW("Can't sound model %d in registered list", handle);
+        pthread_mutex_unlock(&stdev->lock);
+        return -ENOSYS;
     }
 
-    stdev->recognition_callback = callback;
-    stdev->recognition_cookie = cookie;
+    free(stdev->model_context[i].config);
+    stdev->model_context[i].config = NULL;
+    if (config) {
+        stdev->model_context[i].config = malloc(sizeof(*config));
+        if (!stdev->model_context[i].config) {
+            pthread_mutex_unlock(&stdev->lock);
+            return -ENOMEM;
+        }
+        memcpy(stdev->model_context[i].config, config, sizeof(*config));
+    }
+    stdev->model_context[i].recognition_callback = callback;
+    stdev->model_context[i].recognition_cookie = cookie;
+
     pthread_create(&stdev->callback_thread, (const pthread_attr_t *) NULL,
                         callback_thread_loop, stdev);
-exit:
     pthread_mutex_unlock(&stdev->lock);
-    return status;
+    return 0;
 }
 
 static int stdev_stop_recognition(const struct sound_trigger_hw_device *dev,
-                                 sound_model_handle_t sound_model_handle)
-{
+                                 sound_model_handle_t handle) {
     struct stub_sound_trigger_device *stdev = (struct stub_sound_trigger_device *)dev;
-    int status = 0;
-    ALOGI("%s sound model %d", __func__, sound_model_handle);
+    ALOGI("%s", __func__);
     pthread_mutex_lock(&stdev->lock);
-    if (stdev->model_handle != sound_model_handle) {
-        status = -ENOSYS;
-        goto exit;
+
+    unsigned int i;
+    bool found = false;
+    for(i = 0; i < hw_properties.max_sound_models; i++) {
+        if (stdev->model_context[i].loaded_sound_model == handle) {
+            found = true;
+            break;
+        }
     }
-    if (stdev->recognition_callback == NULL) {
-        status = -ENOSYS;
-        goto exit;
+    if (found == false) {
+        ALOGW("Can't sound model %d in registered list", handle);
+        pthread_mutex_unlock(&stdev->lock);
+        return -ENOSYS;
     }
-    stdev->recognition_callback = NULL;
-    pthread_cond_signal(&stdev->cond);
+
+    free(stdev->model_context[i].config);
+    stdev->model_context[i].config = NULL;
+    stdev->model_context[i].recognition_callback = NULL;
+    stdev->model_context[i].recognition_cookie = NULL;
+
+    send_loop_kill_signal();
     pthread_mutex_unlock(&stdev->lock);
     pthread_join(stdev->callback_thread, (void **) NULL);
-    pthread_mutex_lock(&stdev->lock);
-
-exit:
-    pthread_mutex_unlock(&stdev->lock);
-    return status;
+    return 0;
 }
 
-
-static int stdev_close(hw_device_t *device)
+__attribute__ ((visibility ("default")))
+int sound_trigger_open_for_streaming()
 {
+    int ret = 0;
+    return ret;
+}
+
+__attribute__ ((visibility ("default")))
+size_t sound_trigger_read_samples(int audio_handle, void *buffer, size_t  buffer_len)
+{
+    size_t ret = 0;
+    return ret;
+}
+
+__attribute__ ((visibility ("default")))
+int sound_trigger_close_for_streaming(int audio_handle __unused)
+{
+    return 0;
+}
+
+static int stdev_close(hw_device_t *device) {
     free(device);
     return 0;
 }
 
 static int stdev_open(const hw_module_t* module, const char* name,
-                     hw_device_t** device)
-{
+                     hw_device_t** device) {
     struct stub_sound_trigger_device *stdev;
     int ret;
 
@@ -261,6 +486,22 @@
     if (!stdev)
         return -ENOMEM;
 
+    if (MAX_MAX_SOUND_MODELS < hw_properties.max_sound_models) {
+        ALOGW("max_sound_models is greater than the allowed %d", MAX_MAX_SOUND_MODELS);
+        return -EINVAL;
+    }
+
+    stdev->next_sound_model_id = 1;
+    unsigned int i;
+    for(i = 0; i < hw_properties.max_sound_models; i++) {
+        stdev->model_context[i].loaded_sound_model = 0;
+        stdev->model_context[i].sound_model_callback = NULL;
+        stdev->model_context[i].sound_model_cookie = NULL;
+        stdev->model_context[i].config = NULL;
+        stdev->model_context[i].recognition_callback = NULL;
+        stdev->model_context[i].recognition_cookie = NULL;
+    }
+
     stdev->device.common.tag = HARDWARE_DEVICE_TAG;
     stdev->device.common.version = SOUND_TRIGGER_DEVICE_API_VERSION_1_0;
     stdev->device.common.module = (struct hw_module_t *) module;
@@ -272,7 +513,6 @@
     stdev->device.stop_recognition = stdev_stop_recognition;
 
     pthread_mutex_init(&stdev->lock, (const pthread_mutexattr_t *) NULL);
-    pthread_cond_init(&stdev->cond, (const pthread_condattr_t *) NULL);
 
     *device = &stdev->device.common;
 
diff --git a/modules/vr/Android.mk b/modules/vr/Android.mk
new file mode 100644
index 0000000..43c8e92
--- /dev/null
+++ b/modules/vr/Android.mk
@@ -0,0 +1,26 @@
+# 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := vr.default
+LOCAL_MODULE_RELATIVE_PATH := hw
+LOCAL_SRC_FILES := vr.c
+LOCAL_SHARED_LIBRARIES := libcutils
+LOCAL_MODULE_TAGS := optional
+LOCAL_CFLAGS += -Wno-unused-parameter
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/modules/vr/vr.c b/modules/vr/vr.c
new file mode 100644
index 0000000..c5af593
--- /dev/null
+++ b/modules/vr/vr.c
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+#define LOG_TAG "VrHal"
+
+#include <hardware/vr.h>
+#include <hardware/hardware.h>
+
+static void vr_init(struct vr_module *module) {
+    // NOOP
+}
+
+static void vr_set_vr_mode(struct vr_module *module, bool enabled) {
+    // NOOP
+}
+
+static struct hw_module_methods_t vr_module_methods = {
+    .open = NULL,
+};
+
+
+vr_module_t HAL_MODULE_INFO_SYM = {
+    .common = {
+        .tag                = HARDWARE_MODULE_TAG,
+        .module_api_version = VR_MODULE_API_VERSION_1_0,
+        .hal_api_version    = HARDWARE_HAL_API_VERSION,
+        .id                 = VR_HARDWARE_MODULE_ID,
+        .name               = "Demo VR HAL",
+        .author             = "The Android Open Source Project",
+        .methods            = &vr_module_methods,
+    },
+
+    .init = vr_init,
+    .set_vr_mode = vr_set_vr_mode,
+};