/*
 *  Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Contact: Krzysztof Dynowski <k.dynowski@samsung.com>
 *
 *  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
 */

/**
 * @file   tee_client_api.h
 * @brief  Client GlobalPlatform API.
 */

#ifndef TEE_CLIENT_API_H
#define TEE_CLIENT_API_H

#include <stdint.h>
#include <stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @addtogroup CAPI_TEF_MODULE
 * @{
 */

/*
 * @brief Defines the number of available memory references in an open session or
 * invoke command operation payload.
 *
 * @since_tizen 4.0
 */
#define TEEC_CONFIG_PAYLOAD_REF_COUNT 4

/**
 * @brief Defines the maximum size of a single shared memory block, in bytes, of both
 * API allocated and API registered memory. The size is currently set to
 * 512 * kB (512 * 1024).
 *
 * @since_tizen 4.0
 */
#define TEEC_CONFIG_SHAREDMEM_MAX_SIZE 0x80000

/**
 * @brief Flag constants indicating the type of parameters encoded inside the
 * operation payload (TEEC_Operation), Type is uint32_t.
 *
 * @since_tizen 4.0
 *
 * TEEC_NONE                   The Parameter is not used
 *
 * TEEC_VALUE_INPUT            The Parameter is a TEEC_Value tagged as input.
 *
 * TEEC_VALUE_OUTPUT           The Parameter is a TEEC_Value tagged as output.
 *
 * TEEC_VALUE_INOUT            The Parameter is a TEEC_Value tagged as both as
 *                             input and output, i.e., for which both the
 *                             behaviors of TEEC_VALUE_INPUT and
 *                             TEEC_VALUE_OUTPUT apply.
 *
 * TEEC_MEMREF_TEMP_INPUT      The Parameter is a TEEC_TempMemoryReference
 *                             describing a region of memory which needs to be
 *                             temporarily registered for the duration of the
 *                             Operation and is tagged as input.
 *
 * TEEC_MEMREF_TEMP_OUTPUT     Same as TEEC_MEMREF_TEMP_INPUT, but the Memory
 *                             Reference is tagged as output. The
 *                             Implementation may update the size field to
 *                             reflect the required output size in some use
 *                             cases.
 *
 * TEEC_MEMREF_TEMP_INOUT      A Temporary Memory Reference tagged as both
 *                             input and output, i.e., for which both the
 *                             behaviors of TEEC_MEMREF_TEMP_INPUT and
 *                             TEEC_MEMREF_TEMP_OUTPUT apply.
 *
 * TEEC_MEMREF_WHOLE           The Parameter is a Registered Memory Reference
 *                             that refers to the entirety of its parent Shared
 *                             Memory block. The parameter structure is a
 *                             TEEC_MemoryReference. In this structure, the
 *                             Implementation MUST read only the parent field
 *                             and MAY update the size field when the operation
 *                             completes.
 *
 * TEEC_MEMREF_PARTIAL_INPUT   A Registered Memory Reference structure that
 *                             refers to a partial region of its parent Shared
 *                             Memory block and is tagged as input.
 *
 * TEEC_MEMREF_PARTIAL_OUTPUT  Registered Memory Reference structure that
 *                             refers to a partial region of its parent Shared
 *                             Memory block and is tagged as output.
 *
 * TEEC_MEMREF_PARTIAL_INOUT   The Registered Memory Reference structure that
 *                             refers to a partial region of its parent Shared
 *                             Memory block and is tagged as both input and
 *                             output, i.e., for which both the behaviors of
 *                             TEEC_MEMREF_PARTIAL_INPUT and
 *                             TEEC_MEMREF_PARTIAL_OUTPUT apply.
 */
#define TEEC_NONE                   0x00000000
#define TEEC_VALUE_INPUT            0x00000001
#define TEEC_VALUE_OUTPUT           0x00000002
#define TEEC_VALUE_INOUT            0x00000003
#define TEEC_MEMREF_TEMP_INPUT      0x00000005
#define TEEC_MEMREF_TEMP_OUTPUT     0x00000006
#define TEEC_MEMREF_TEMP_INOUT      0x00000007
#define TEEC_MEMREF_WHOLE           0x0000000C
#define TEEC_MEMREF_PARTIAL_INPUT   0x0000000D
#define TEEC_MEMREF_PARTIAL_OUTPUT  0x0000000E
#define TEEC_MEMREF_PARTIAL_INOUT   0x0000000F

/**
 * @brief Flag constants indicating the data transfer direction of memory in
 * TEEC_Parameter. TEEC_MEM_INPUT signifies data transfer direction from the
 * client application to the TEE. TEEC_MEM_OUTPUT signifies data transfer
 * direction from the TEE to the client application. Type is uint32_t.
 *
 * @since_tizen 4.0
 *
 *
 * TEEC_MEM_INPUT   The Shared Memory can carry data from the client
 *                  application to the Trusted Application.
 * TEEC_MEM_OUTPUT  The Shared Memory can carry data from the Trusted
 *                  Application to the client application.
 */
#define TEEC_MEM_INPUT   0x00000001
#define TEEC_MEM_OUTPUT  0x00000002

/**
 * @brief Return values. Type is TEEC_Result
 *
 * @since_tizen 4.0
 *
 * TEEC_SUCCESS                 The operation was successful.
 * TEEC_ERROR_GENERIC           Non-specific cause.
 * TEEC_ERROR_ACCESS_DENIED     Access privileges are not sufficient.
 * TEEC_ERROR_CANCEL            The operation was canceled.
 * TEEC_ERROR_ACCESS_CONFLICT   Concurrent accesses caused conflict.
 * TEEC_ERROR_EXCESS_DATA       Too much data for the requested operation was
 *                              passed.
 * TEEC_ERROR_BAD_FORMAT        Input data was of invalid format.
 * TEEC_ERROR_BAD_PARAMETERS    Input parameters were invalid.
 * TEEC_ERROR_BAD_STATE         Operation is not valid in the current state.
 * TEEC_ERROR_ITEM_NOT_FOUND    The requested data item is not found.
 * TEEC_ERROR_NOT_IMPLEMENTED   The requested operation should exist but is not
 *                              yet implemented.
 * TEEC_ERROR_NOT_SUPPORTED     The requested operation is valid but is not
 *                              supported in this implementation.
 * TEEC_ERROR_NO_DATA           Expected data was missing.
 * TEEC_ERROR_OUT_OF_MEMORY     System ran out of resources.
 * TEEC_ERROR_BUSY              The system is busy working on something else.
 * TEEC_ERROR_COMMUNICATION     Communication with a remote party failed.
 * TEEC_ERROR_SECURITY          A security fault was detected.
 * TEEC_ERROR_SHORT_BUFFER      The supplied buffer is too short for the
 *                              generated output.
 * TEEC_ERROR_TARGET_DEAD       Trusted Application has panicked
 *                              during the operation.
 */

/**
 *  Standard defined error codes.
 */
#define TEEC_SUCCESS                0x00000000
#define TEEC_ERROR_GENERIC          0xFFFF0000
#define TEEC_ERROR_ACCESS_DENIED    0xFFFF0001
#define TEEC_ERROR_CANCEL           0xFFFF0002
#define TEEC_ERROR_ACCESS_CONFLICT  0xFFFF0003
#define TEEC_ERROR_EXCESS_DATA      0xFFFF0004
#define TEEC_ERROR_BAD_FORMAT       0xFFFF0005
#define TEEC_ERROR_BAD_PARAMETERS   0xFFFF0006
#define TEEC_ERROR_BAD_STATE        0xFFFF0007
#define TEEC_ERROR_ITEM_NOT_FOUND   0xFFFF0008
#define TEEC_ERROR_NOT_IMPLEMENTED  0xFFFF0009
#define TEEC_ERROR_NOT_SUPPORTED    0xFFFF000A
#define TEEC_ERROR_NO_DATA          0xFFFF000B
#define TEEC_ERROR_OUT_OF_MEMORY    0xFFFF000C
#define TEEC_ERROR_BUSY             0xFFFF000D
#define TEEC_ERROR_COMMUNICATION    0xFFFF000E
#define TEEC_ERROR_SECURITY         0xFFFF000F
#define TEEC_ERROR_SHORT_BUFFER     0xFFFF0010
#define TEEC_ERROR_EXTERNAL_CANCEL  0xFFFF0011
#define TEEC_ERROR_TARGET_DEAD      0xFFFF3024

/**
 * @brief Function error origins, of type TEEC_ErrorOrigin. These indicate where in
 * the software stack a particular return value originates from.
 *
 * @since_tizen 4.0
 *
 * TEEC_ORIGIN_API          The error originated within the TEE Client API
 *                          implementation.
 * TEEC_ORIGIN_COMMS        The error originated within the underlying
 *                          communications stack linking the rich OS with
 *                          the TEE.
 * TEEC_ORIGIN_TEE          The error originated within the common TEE code.
 * TEEC_ORIGIN_TRUSTED_APP  The error originated within the Trusted Application
 *                          code.
 */
#define TEEC_ORIGIN_API          0x00000001
#define TEEC_ORIGIN_COMMS        0x00000002
#define TEEC_ORIGIN_TEE          0x00000003
#define TEEC_ORIGIN_TRUSTED_APP  0x00000004

/**
 * @brief Session login methods, for use in TEEC_OpenSession() as parameter
 * connectionMethod. Type is uint32_t.
 *
 * @since_tizen 4.0
 *
 * TEEC_LOGIN_PUBLIC            No login data is provided.
 * TEEC_LOGIN_USER              Login data about the user running the Client
 *                              Application process is provided.
 * TEEC_LOGIN_GROUP             Login data about the group running the Client
 *                              Application process is provided.
 * TEEC_LOGIN_APPLICATION       Login data about the running Client Application
 *                              itself is provided.
 * TEEC_LOGIN_USER_APPLICATION  Login data about the user and the running
 *                              Client Application itself is provided.
 * TEEC_LOGIN_GROUP_APPLICATION Login data about the group and the running
 *                              Client Application itself is provided.
 */
#define TEEC_LOGIN_PUBLIC             0x00000000
#define TEEC_LOGIN_USER               0x00000001
#define TEEC_LOGIN_GROUP              0x00000002
#define TEEC_LOGIN_APPLICATION        0x00000004
#define TEEC_LOGIN_USER_APPLICATION   0x00000005
#define TEEC_LOGIN_GROUP_APPLICATION  0x00000006

/**
 * @brief Encode the paramTypes according to the supplied types.
 *
 * @since_tizen 4.0
 *
 * @param[in] p0 The first param type.
 * @param[in] p1 The second param type.
 * @param[in] p2 The third param type.
 * @param[in] p3 The fourth param type.
 */
#define TEEC_PARAM_TYPES(p0, p1, p2, p3) \
    ((p0) | ((p1) << 8) | ((p2) << 16) | ((p3) << 24))

/**
 * @brief Get the i_th param type from the paramType.
 *
 * @since_tizen 4.0
 *
 * @param p[in] The paramType.
 * @param i[in] The i-th parameter to get the type for.
 */
#define TEEC_PARAM_TYPE_GET(p, i) (((p) >> (i * 8)) & 0xF)

/**
 * @brief This type is used to contain return codes which are the results of invoking TEE Client API functions.
 */
typedef uint32_t TEEC_Result;

/**
 * @brief This type contains a Universally Unique Resource Identifier (UUID) type as
 * defined in RFC4122. These UUID values are used to identify Trusted Applications.
 *
 * @since_tizen 4.0
 */
typedef struct {
    uint32_t timeLow;
    uint16_t timeMid;
    uint16_t timeHiAndVersion;
    uint8_t clockSeqAndNode[8];
} TEEC_UUID;

/**
 * @brief Memory to transfer data between a client application and trusted code.
 *
 * @since_tizen 4.0
 *
 * A shared memory block is a region of memory allocated in the context of the
 * client application memory space that can be used to transfer data between
 * that client application and a trusted application. The user of this struct
 * is responsible to populate the buffer pointer.
 */
typedef struct {
    /** The memory buffer which is to be, or has been, shared with the TEE. */
    void *buffer;
    /** The size, in bytes, of the memory buffer. */
    size_t size;
    /** Bit-vector which holds properties of buffer.
     *  The bit-vector can contain either or both of the
     *  TEEC_MEM_INPUT and TEEC_MEM_OUTPUT flags.
     */
    uint32_t flags;
    /* Implementation defined */
    void *imp;
} TEEC_SharedMemory;

/**
 * @brief Temporary memory to transfer data between
 * a client application and trusted code, only used for the duration of the
 * operation.
 *
 * @since_tizen 4.0
 *
 * A memory buffer that is registered temporarily for the duration of the
 * operation to be called.
 */
typedef struct {
    /** The memory buffer which is to be, or has been shared with the TEE. */
    void *buffer;
    /** The size, in bytes, of the memory buffer. */
    size_t size;
} TEEC_TempMemoryReference;

/**
 * @brief Uses pre-registered or pre-allocated shared memory block of memory to transfer
 * data between a client application and trusted code.
 *
 * @since_tizen 4.0
 *
 */
typedef struct {
    /** Points to a shared memory structure. The memory reference
      * may utilize the whole shared memory or only a part of it. Must not be NULL
      */
    TEEC_SharedMemory *parent;
    /** The size, in bytes, of the memory buffer. */
    size_t size;
    /** The offset, in bytes, of the referenced memory region from
      * the start of the shared memory block.
      */
    size_t offset;
} TEEC_RegisteredMemoryReference;

/**
 * @brief Small raw data container
 *
 * @since_tizen 4.0
 *
 * Instead of allocating a shared memory buffer this structure can be used
 * to pass small raw data between a client application and trusted code.
 */
typedef struct {
    /** The first integer value. */
    uint32_t a;
    /** The second integer value. */
    uint32_t b;
} TEEC_Value;

/**
 * @brief Memory container to be used when passing data between
 * client application and trusted code.
 *
 * @since_tizen 4.0
 *
 * Either the client uses a shared memory reference, parts of it or a small raw
 * data container.
 */
typedef union {
    /** A temporary memory reference only valid for the duration of the operation. */
    TEEC_TempMemoryReference tmpref;
    /** The entire shared memory or parts of it. */
    TEEC_RegisteredMemoryReference memref;
    /** The small raw data container to use */
    TEEC_Value value;
} TEEC_Parameter;

/**
 * @brief Represents a connection between a client application and a TEE.
 *
 * @since_tizen 4.0
 */
typedef struct {
    /* Implementation defined */
    void *imp;
} TEEC_Context;

/**
 * @brief Represents a connection between a client application
 * and a trusted application.
 *
 * @since_tizen 4.0
 */
typedef struct {
    /* Implementation defined */
    void *imp;
} TEEC_Session;

/**
 * @brief Holds information and memory references used in TEEC_InvokeCommand().
 *
 * @since_tizen 4.0
 *
 */
typedef struct {
    /** Client must initialize to zero if it needs to cancel an operation about to be performed. */
    uint32_t started;
    /** Type of data passed. Use TEEC_PARAMS_TYPE macro to create the correct flags. */
    uint32_t paramTypes;
    /** Array of parameters of type TEEC_Parameter. */
    TEEC_Parameter params[TEEC_CONFIG_PAYLOAD_REF_COUNT];
    /* Implementation-Defined */
    void *imp;
} TEEC_Operation;

/**
 * @brief Initializes a context holding connection
 * information on the specific TEE, designated by the name string.
 *
 * @since_tizen 4.0
 *
 * @param[in] name     A zero-terminated string identifying the TEE to connect to.
 *                     If name is set to NULL, the default TEE is connected to. NULL
 *                     is the only supported value in this version of the API
 *                     implementation.
 * @param[out] context The context structure which is to be initialized.
 *
 * @return TEEC_SUCCESS on success, or another Return Code on failure
 */
TEEC_Result TEEC_InitializeContext(const char *name, TEEC_Context *context);

/**
 * @brief Destroys a context holding connection information
 * on the specific TEE.
 *
 * @since_tizen 4.0
 *
 * This function destroys an initialized TEE context, closing the connection
 * between the client application and the TEE. This function must only be
 * called when all sessions related to this TEE context have been closed and
 * all shared memory blocks have been released.
 *
 * @param[in] context       The context to be destroyed.
 */
void TEEC_FinalizeContext(TEEC_Context *context);

/**
 * @brief Opens a new session with the specified trusted application.
 *
 * @since_tizen 4.0
 *
 * @param[in] context            The initialized TEE context structure in which
 *                               scope to open the session.
 * @param[in] session            The session to initialize.
 * @param[in] destination        A structure identifying the trusted application
 *                               with which to open a session.
 *
 * @param[in] connectionMethod   The connection method to use.
 * @param[in] connectionData     Any data necessary to connect with the chosen
 *                               connection method. Not supported, should be set to NULL.
 * @param[in,out] operation      An operation structure to use in the session. May
 *                               be set to NULL to signify no operation structure needed.
 *
 * @param[out] returnOrigin      A parameter which will hold the error origin if
 *                               this function returns any value other than TEEC_SUCCESS.
 *
 * @return TEEC_SUCCESS on success, or another Return Code on failure
 *
 */
TEEC_Result TEEC_OpenSession(TEEC_Context *context,
                             TEEC_Session *session,
                             const TEEC_UUID *destination,
                             uint32_t connectionMethod,
                             const void *connectionData,
                             TEEC_Operation *operation,
                             uint32_t *returnOrigin);

/**
 * @brief Closes the session which has been opened with the
 * specific trusted application.
 *
 * @since_tizen 4.0
 *
 * @param[in] session The opened session to close.
 */
void TEEC_CloseSession(TEEC_Session *session);

/**
 * @brief Executes a command in the specified trusted application.
 *
 * @param[in] session        A handle to an open connection to the trusted application.
 * @param[in] commandID      Identifier of the command in the trusted application to invoke.
 * @param[in,out] operation  An operation structure to use in the invoke command.
 *                           May be set to NULL to signify no operation structure
 *                           needed.
 * @param[out] returnOrigin  A parameter which will hold the error origin if this
 *                           function returns any value other than TEEC_SUCCESS.
 *
 * @return TEEC_SUCCESS on success, or another Return Code on failure
 */
TEEC_Result TEEC_InvokeCommand(TEEC_Session *session,
                               uint32_t commandID,
                               TEEC_Operation *operation,
                               uint32_t *returnOrigin);

/**
 * @brief Registers a block of existing memory as a
 * shared block within the scope of the specified context.
 *
 * @since_tizen 4.0
 *
 * @param[in] context    The initialized TEE context structure in which scope to
 *                       open the session.
 * @param[in] sharedMem  pointer to the shared memory structure to register.
 *
 * @return TEEC_SUCCESS on success, or another Return Code on failure
 * @retval TEEC_ERROR_OUT_OF_MEMORY  Memory exhaustion.
 */
TEEC_Result TEEC_RegisterSharedMemory(TEEC_Context *context,
                                      TEEC_SharedMemory *sharedMem);

/**
 * @brief Allocates shared memory for TEE.
 *
 * @since_tizen 4.0
 *
 * @param[in] context     The initialized TEE context structure in which scope to
 *                        open the session.
 * @param[in,out] sharedMem   Pointer to the allocated shared memory.
 *
 * @return TEEC_SUCCESS on success, or another Return Code on failure
 * @retval TEEC_ERROR_OUT_OF_MEMORY  Memory exhaustion.
 */
TEEC_Result TEEC_AllocateSharedMemory(TEEC_Context *context,
                                      TEEC_SharedMemory *sharedMem);

/**
 * @brief Frees or deregisters the shared memory.
 *
 * @since_tizen 4.0
 *
 * @param[in] sharedMem  Pointer to the shared memory to be freed.
 */
void TEEC_ReleaseSharedMemory(TEEC_SharedMemory *sharedMemory);

/**
 * @brief Requests the cancellation of a pending open
 *        session or command invocation.
 *
 * @since_tizen 4.0
 *
 * @param[in] operation  Pointer to an operation previously passed to open session
 *                       or invoke.
 */
void TEEC_RequestCancellation(TEEC_Operation *operation);

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif
