Trusty API reference

Trusty provides APIs for developing two classes of apps and services:

  • Trusted apps and services that run on the TEE processor
  • Normal and untrusted apps that run on the main processor and use the services provided by trusted apps

The Trusty API generally describes the Trusty inter-process communication (IPC) system, including communications with the non-secure world. Software running on the main processor can use Trusty APIs to connect to trusted apps and services and exchange arbitrary messages with them just like a network service over IP. It is up to the app to determine the data format and semantics of these messages using an app-level protocol. Reliable delivery of messages is guaranteed by the underlying Trusty infrastructure (in the form of drivers running on the main processor), and the communication is completely asynchronous.

Ports and channels

Ports are used by Trusty apps to expose service end-points in the form of a named path to which clients connect. This gives a simple, string-based service ID for clients to use. The naming convention is reverse-DNS-style naming, e.g. com.google.servicename.

When a client connects to a port, the client receives a channel for interacting with a service. The service must accept an incoming connection, and when it does, it too receives a channel. In essence, ports are used to look up services and then communication occurs over a pair of connected channels (i.e., connection instances on a port). When a client connects to a port, a symmetric, bi-directional connection is established. Using this full-duplex path, clients and servers can exchange arbitrary messages until either side decides to tear down the connection.

Only secure-side trusted apps or Trusty kernel modules can create ports. Apps running on the non-secure side (in the normal world) can only connect to services published by the secure side.

Depending on requirements, a trusted app can be both a client and a server at the same time. A trusted app that publishes a service (as a server) might need to connect to other services (as a client).

Handle API

Handles are unsigned integers representing resources such as ports and channels, similar to file descriptors in UNIX. After handles are created, they are placed into an app-specific handle table and can be referenced later.

A caller can associate private data with a handle by using the set_cookie() method.

Methods in the Handle API

Handles are only valid in the context of an app. An app should not pass the value of a handle to other apps unless explicitly specified. A handle value only should be interpreted by comparing it with the INVALID_IPC_HANDLE #define, which an app can use as an indication that a handle is invalid or unset.

Associates the caller-provided private data with a specified handle.

long set_cookie(uint32_t handle, void *cookie)

[in] handle: Any handle returned by one of the API calls

[in] cookie: Pointer to arbitrary user-space data in the Trusty app

[retval]: NO_ERROR on success, < 0 error code otherwise

This call is useful for handling events when they occur at a later time after the handle has been created. The event-handling mechanism supplies the handle and its cookie back to the event handler.

Handles can be waited upon for events by using the wait() call.

wait()

Waits for an event to occur on a given handle for specified period of time.

long wait(uint32_t handle_id, uevent_t *event, unsigned long timeout_msecs)

[in] handle_id: Any handle returned by one of the API calls

[out] event: A pointer to the structure representing an event that occurred on this handle

[in] timeout_msecs: A timeout value in milliseconds; a value of -1 is an infinite timeout

[retval]: NO_ERROR if a valid event occurred within a specified timeout interval; ERR_TIMED_OUT if a specified timeout elapsed but no event has occurred; < 0 for other errors

Upon success (retval == NO_ERROR), the wait() call fills a specified uevent_t structure with information about the event that occurred.

typedef struct uevent {
    uint32_t handle; /* handle this event is related to */
    uint32_t event;  /* combination of IPC_HANDLE_POLL_XXX flags */
    void    *cookie; /* cookie associated with this handle */
} uevent_t;

The event field contains a combination of the following values:

enum {
  IPC_HANDLE_POLL_NONE    = 0x0,
  IPC_HANDLE_POLL_READY   = 0x1,
  IPC_HANDLE_POLL_ERROR   = 0x2,
  IPC_HANDLE_POLL_HUP     = 0x4,
  IPC_HANDLE_POLL_MSG     = 0x8,
  IPC_HANDLE_POLL_SEND_UNBLOCKED = 0x10,
  … more values[TBD]
};

IPC_HANDLE_POLL_NONE - no events are actually pending, caller should restart the wait

IPC_HANDLE_POLL_ERROR - an unspecified internal error has occurred

IPC_HANDLE_POLL_READY - depends on the handle type, as follows:

  • For ports, this value indicates that there is a pending connection
  • For channels, this value indicates that an asynchronous connection (see connect()) was established

The following events are only relevant for channels:

  • IPC_HANDLE_POLL_HUP - indicates that a channel has been closed by a peer
  • IPC_HANDLE_POLL_MSG - indicates that there is a pending message for this channel
  • IPC_HANDLE_POLL_SEND_UNBLOCKED - indicates that a previously send-blocked caller may attempt to send a message again (see the description of send_msg() for details)

An event handler should be prepared to handle a combination of specified events, as multiple bits might be set at the same time. For example, for a channel, it is possible to have pending messages, and a connection closed by a peer at the same time.

Most events are sticky. They persist as long as the underlying condition persists (for example all pending messages are received and pending connection requests are handled). The exception is the case of the IPC_HANDLE_POLL_SEND_UNBLOCKED event, which is cleared upon a read and the app has only one chance to handle it.

Handles can be destroyed by calling the close() method.

close()

Destroys the resource associated with the specified handle and removes it from the handle table.

long close(uint32_t handle_id);

[in] handle_id: Handle to destroy

[retval]: 0 if success; a negative error otherwise

Server API

A server begins by creating one or more named ports representing its service end-points. Each port is represented by a handle.

Methods in the Server API

port_create()

Creates a named service port.

long port_create (const char *path, uint num_recv_bufs, size_t recv_buf_size,
uint32_t flags)

[in] path: The string name of the port (as described above). This name should be unique across the system; attempts to create a duplicate fail.

[in] num_recv_bufs: The maximum number of buffers that a channel on this port can pre-allocate to facilitate the exchange of data with the client. Buffers are counted separately for data going in both directions, so specifying 1 here would mean 1 send and 1 receive buffer are preallocated. In general, the number of buffers required depends on the higher-level protocol agreement between the client and server. The number can be as little as 1 in case of a very synchronous protocol (send message, receive reply before sending another). But the number can be more if the client expects to send more than one message before a reply can appear (e.g, one message as a prologue and another as the actual command). The allocated buffer sets are per channel, so two separate connections (channels) would have separate buffer sets.

[in] recv_buf_size: Maximum size of each individual buffer in the above buffer set. This value is protocol-dependent and effectively limits maximum message size you can exchange with peer

[in] flags: A combination of flags that specifies additional port behavior

This value should be a combination of the following values:

IPC_PORT_ALLOW_TA_CONNECT - allows a connection from other secure apps

IPC_PORT_ALLOW_NS_CONNECT - allows a connection from the non-secure world

[retval]: Handle to the port created if non-negative or a specific error if negative

The server then polls the list of port handles for incoming connections using wait() call. Upon receiving a connection request indicated by the IPC_HANDLE_POLL_READY bit set in the event field of the uevent_t structure, the server should call accept() to finish establishing a connection and create a channel (represented by another handle) that can then be polled for incoming messages.

accept()

Accepts an incoming connection and gets a handle to a channel.

long accept(uint32_t handle_id, uuid_t *peer_uuid);

[in] handle_id: Handle representing the port to which a client has connected

[out] peer_uuid: Pointer to a uuid_t structure to be filled with the UUID of the connecting client app. It is set to all zeros if the connection originated from the nonsecure world

[retval]: Handle to a channel (if non-negative) on which the server can exchange messages with the client (or an error code otherwise)

Client API

This section contains the methods in the Client API.

Methods in the Client API

connect()

Initiates a connection to a port specified by name.

long connect(const char *path, uint flags);

[in] path: Name of a port published by a Trusty app

[in] flags: Specifies additional, optional behavior

[retval]: Handle to a channel over which messages can be exchanged with the server; error if negative

If no flags are specified (the flags parameter is set to 0), calling connect() initiates a synchronous connection to a specified port that immediately returns an error if the port doesn't exist, and creates a block until the server otherwise accepts a connection.

This behavior can be altered by specifying a combination of two values, described below:

enum {
IPC_CONNECT_WAIT_FOR_PORT = 0x1,
IPC_CONNECT_ASYNC = 0x2,
};

IPC_CONNECT_WAIT_FOR_PORT - forces a connect() call to wait if the specified port doesn't immediately exist at execution, instead of failing immediately.

IPC_CONNECT_ASYNC - if set, initiates an asynchronous connection. An app has to poll for the returned handle by calling wait() for a connection completion event indicated by the IPC_HANDLE_POLL_READY bit set in the event field of the uevent_t structure before starting normal operation.

Messaging API

The Messaging API calls enable the sending and reading of messages over a previously established connection (channel). The Messaging API calls are the same for servers and clients.

A client receives a handle to a channel by issuing a connect() call, and a server gets a channel handle from an accept() call, described above.

Structure of a Trusty message

As shown in the following, messages exchanged by the Trusty API have a minimal structure, leaving it to the server and client to agree on the semantics of the actual contents:

/*
 *  IPC message
 */
typedef struct iovec {
        void   *base;
        size_t  len;
} iovec_t;

typedef struct ipc_msg {
        uint     num_iov; /* number of iovs in this message */
        iovec_t  *iov;    /* pointer to iov array */

        uint     num_handles; /* reserved, currently not supported */
        handle_t *handles;    /* reserved, currently not supported */
} ipc_msg_t;

A message can be composed of one or more non-contiguous buffers represented by an array of iovec_t structures. Trusty performs scatter-gather reads and writes to these blocks using the iov array. The content of buffers that can be described by the iov array is completely arbitrary.

Methods in the Messaging API

send_msg()

Sends a message over a specified channel.

long send_msg(uint32_t handle, ipc_msg_t *msg);

[in] handle: Handle to the channel over which to send the message

[in] msg: Pointer to the ipc_msg_t structure describing the message

[retval]: Total number of bytes sent on success; a negative error otherwise

If the client (or server) is trying to send a message over the channel and there is no space in the destination peer message queue, the channel might enter a send-blocked state (this should never happen for a simple synchronous request/reply protocol but might happen in more complicated cases) that is indicated by returning an ERR_NOT_ENOUGH_BUFFER error code. In such a case the caller must wait until the peer frees some space in its receive queue by retrieving the handling and retiring messages, indicated by the IPC_HANDLE_POLL_SEND_UNBLOCKED bit set in the event field of the uevent_t structure returned by the wait() call.

get_msg()

Gets meta-information about the next message in an incoming message queue

of a specified channel.

long get_msg(uint32_t handle, ipc_msg_info_t *msg_info);

[in] handle: Handle of the channel on which a new message must be retrieved

[out] msg_info: Message information structure described as follows:

typedef struct ipc_msg_info {
        size_t    len;  /* total message length */
        uint32_t  id;   /* message id */
} ipc_msg_info_t;

Each message is assigned a unique ID across the set of outstanding messages, and the total length of each message is filled in. If configured and allowed by the protocol, there can be multiple outstanding (opened) messages at once for a particular channel.

[retval]: NO_ERROR on success; a negative error otherwise

read_msg()

Reads the content of the message with the specified ID starting from the specified offset.

long read_msg(uint32_t handle, uint32_t msg_id, uint32_t offset, ipc_msg_t
*msg);

[in] handle: Handle of the channel from which to read the message

[in] msg_id: ID of the message to read

[in] offset: Offset into the message from which to start reading

[out] msg: Pointer to the ipc_msg_t structure describing a set of buffers into which to store incoming message data

[retval]: Total number of bytes stored in the msg buffers on success; a negative error otherwise

The read_msg method can be called multiple times starting at a different (not necessarily sequential) offset as needed.

put_msg()

Retires a message with a specified ID.

long put_msg(uint32_t handle, uint32_t msg_id);

[in] handle: Handle of the channel on which the message has arrived

[in] msg_id: ID of message being retired

[retval]: NO_ERROR on success; a negative error otherwise

Message content can't be accessed after a message has been retired and the buffer it occupied has been freed.

File Descriptor API

The File Descriptor API includes read(), write(), and ioctl() calls. All of these calls can operate on a predefined (static) set of file descriptors traditionally represented by small numbers. In the current implementation, the file descriptor space is separate from the IPC handle space. The File Descriptor API in Trusty is similar to a traditional file descriptor-based API.

By default, there are 3 predefined (standard and well-known) file descriptors:

  • 0 - standard input. The default implementation of standard input fd is a no-op (as trusted apps aren't expected to have an interactive console) so reading, writing or invoking ioctl() on fd 0 should return an ERR_NOT_SUPPORTED error.
  • 1 - standard output. Data written to standard output can be routed (depending on the LK debug level) to UART and/or a memory log available on the non-secure side, depending on the platform and configuration. Non-critical debug logs and messages should go in standard output. The read() and ioctl() methods are no-ops and should return an ERR_NOT_SUPPORTED error.
  • 2 - standard error. Data written to standard error should be routed to the UART or memory log available on the non-secure side, depending on the platform and configuration. It is recommended to write only critical messages to standard error, as this stream is very likely to be unthrottled. The read() and ioctl() methods are no-ops and should return an ERR_NOT_SUPPORTED error.

Even though this set of file descriptors can be extended to implement more fds (to implement platform-specific extensions), extending file descriptors needs to be exercised with caution. Extending file descriptors is prone to create conflicts and isn't generally recommended.

Methods in the File Descriptor API

read()

Attempts to read up to count bytes of data from a specified file descriptor.

long read(uint32_t fd, void *buf, uint32_t count);

[in] fd: File descriptor from which to read

[out] buf: Pointer to a buffer into which to store data

[in] count: Maximum number of bytes to read

[retval]: Returned number of bytes read; a negative error otherwise

write()

Writes up to count bytes of data to specified file descriptor.

long write(uint32_t fd, void *buf, uint32_t count);

[in] fd: File descriptor to which to write

[out] buf: Pointer to data to write

[in] count: Maximum number of bytes to write

[retval]: Returned number of bytes written; a negative error otherwise

ioctl()

Invokes a specified ioctl command for a given file descriptor.

long ioctl(uint32_t fd, uint32_t cmd, void *args);

[in] fd: File descriptor on which to invoke ioctl()

[in] cmd: The ioctl command

[in/out] args: Pointer to ioctl() arguments

Miscellaneous API

Methods in the Miscellaneous API

gettime()

Returns the current system time (in nanoseconds).

long gettime(uint32_t clock_id, uint32_t flags, int64_t *time);

[in] clock_id: Platform-dependent; pass zero for default

[in] flags: Reserved, should be zero

[out] time: Pointer to an int64_t value to which to store the current time

[retval]: NO_ERROR on success; a negative error otherwise

nanosleep()

Suspends execution of the calling app for a specified period of time and resumes it after that period.

long nanosleep(uint32_t clock_id, uint32_t flags, uint64_t sleep_time)

[in] clock_id: Reserved, should be zero

[in] flags: Reserved, should be zero

[in] sleep_time: Sleep time in nanoseconds

[retval]: NO_ERROR on success; a negative error otherwise

Example of a trusted app server

The following sample app shows the usage of the above APIs. The sample creates an "echo" service that handles multiple incoming connections and reflects back to the caller all messages it receives from clients originated from the secure or non-secure side.

#include <uapi/err.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <trusty_ipc.h>
#define LOG_TAG "echo_srv"
#define TLOGE(fmt, ...) \
    fprintf(stderr, "%s: %d: " fmt, LOG_TAG, __LINE__, ##__VA_ARGS__)

# define MAX_ECHO_MSG_SIZE 64

static
const char * srv_name = "com.android.echo.srv.echo";

static uint8_t msg_buf[MAX_ECHO_MSG_SIZE];

/*
 *  Message handler
 */
static int handle_msg(handle_t chan) {
  int rc;
  struct iovec iov;
  ipc_msg_t msg;
  ipc_msg_info_t msg_inf;

  iov.iov_base = msg_buf;
  iov.iov_len = sizeof(msg_buf);

  msg.num_iov = 1;
  msg.iov = &iov;
  msg.num_handles = 0;
  msg.handles = NULL;

  /* get message info */
  rc = get_msg(chan, &msg_inf);
  if (rc == ERR_NO_MSG)
    return NO_ERROR; /* no new messages */

  if (rc != NO_ERROR) {
    TLOGE("failed (%d) to get_msg for chan (%d)\n",
      rc, chan);
    return rc;
  }

  /* read msg content */
  rc = read_msg(chan, msg_inf.id, 0, &msg);
  if (rc < 0) {
    TLOGE("failed (%d) to read_msg for chan (%d)\n",
      rc, chan);
    return rc;
  }

  /* update number of bytes received */
  iov.iov_len = (size_t) rc;

  /* send message back to the caller */
  rc = send_msg(chan, &msg);
  if (rc < 0) {
    TLOGE("failed (%d) to send_msg for chan (%d)\n",
      rc, chan);
    return rc;
  }

  /* retire message */
  rc = put_msg(chan, msg_inf.id);
  if (rc != NO_ERROR) {
    TLOGE("failed (%d) to put_msg for chan (%d)\n",
      rc, chan);
    return rc;
  }

  return NO_ERROR;
}

/*
 *  Channel event handler
 */
static void handle_channel_event(const uevent_t * ev) {
  int rc;

  if (ev->event & IPC_HANDLE_POLL_MSG) {
    rc = handle_msg(ev->handle);
    if (rc != NO_ERROR) {
      /* report an error and close channel */
      TLOGE("failed (%d) to handle event on channel %d\n",
        rc, ev->handle);
      close(ev->handle);
    }
    return;
  }
  if (ev->event & IPC_HANDLE_POLL_HUP) {
    /* closed by peer. */
    close(ev->handle);
    return;
  }
}

/*
 *  Port event handler
 */
static void handle_port_event(const uevent_t * ev) {
  uuid_t peer_uuid;

  if ((ev->event & IPC_HANDLE_POLL_ERROR) ||
    (ev->event & IPC_HANDLE_POLL_HUP) ||
    (ev->event & IPC_HANDLE_POLL_MSG) ||
    (ev->event & IPC_HANDLE_POLL_SEND_UNBLOCKED)) {
    /* should never happen with port handles */
    TLOGE("error event (0x%x) for port (%d)\n",
      ev->event, ev->handle);
    abort();
  }
  if (ev->event & IPC_HANDLE_POLL_READY) {
    /* incoming connection: accept it */
    int rc = accept(ev->handle, &peer_uuid);
    if (rc < 0) {
      TLOGE("failed (%d) to accept on port %d\n",
        rc, ev->handle);
      return;
    }
    handle_t chan = rc;
    while (true){
      struct uevent cev;

      rc = wait(chan, &cev, INFINITE_TIME);
      if (rc < 0) {
        TLOGE("wait returned (%d)\n", rc);
        abort();
      }
      handle_channel_event(&cev);
      if (cev.event & IPC_HANDLE_POLL_HUP) {
        return;
      }
    }
  }
}


/*
 *  Main app entry point
 */
int main(void) {
  int rc;
  handle_t port;

  /* Initialize service */
  rc = port_create(srv_name, 1, MAX_ECHO_MSG_SIZE,
    IPC_PORT_ALLOW_NS_CONNECT |
    IPC_PORT_ALLOW_TA_CONNECT);
  if (rc < 0) {
    TLOGE("Failed (%d) to create port %s\n",
      rc, srv_name);
    abort();
  }
  port = (handle_t) rc;

  /* enter main event loop */
  while (true) {
    uevent_t ev;

    ev.handle = INVALID_IPC_HANDLE;
    ev.event = 0;
    ev.cookie = NULL;

    /* wait forever */
    rc = wait(port, &ev, INFINITE_TIME);
    if (rc == NO_ERROR) {
      /* got an event */
      handle_port_event(&ev);
    } else {
      TLOGE("wait returned (%d)\n", rc);
      abort();
    }
  }
  return 0;
}

The run_end_to_end_msg_test() method sends 10,000 messages asynchronously to the "echo" service and handles replies.

static int run_echo_test(void)
{
  int rc;
  handle_t chan;
  uevent_t uevt;
  uint8_t tx_buf[64];
  uint8_t rx_buf[64];
  ipc_msg_info_t inf;
  ipc_msg_t   tx_msg;
  iovec_t     tx_iov;
  ipc_msg_t   rx_msg;
  iovec_t     rx_iov;

  /* prepare tx message buffer */
  tx_iov.base = tx_buf;
  tx_iov.len  = sizeof(tx_buf);
  tx_msg.num_iov = 1;
  tx_msg.iov     = &tx_iov;
  tx_msg.num_handles = 0;
  tx_msg.handles = NULL;

  memset (tx_buf, 0x55, sizeof(tx_buf));

  /* prepare rx message buffer */
  rx_iov.base = rx_buf;
  rx_iov.len  = sizeof(rx_buf);
  rx_msg.num_iov = 1;
  rx_msg.iov     = &rx_iov;
  rx_msg.num_handles = 0;
  rx_msg.handles = NULL;

  /* open connection to echo service */
  rc = sync_connect(srv_name, 1000);
  if(rc < 0)
    return rc;

  /* got channel */
  chan = (handle_t)rc;

  /* send/receive 10000 messages asynchronously. */
  uint tx_cnt = 10000;
  uint rx_cnt = 10000;

  while (tx_cnt || rx_cnt) {
    /* send messages until all buffers are full */
while (tx_cnt) {
    rc = send_msg(chan, &tx_msg);
      if (rc == ERR_NOT_ENOUGH_BUFFER)
      break;  /* no more space */
    if (rc != 64) {
      if (rc > 0) {
        /* incomplete send */
        rc = ERR_NOT_VALID;
}
      goto abort_test;
}
    tx_cnt--;
  }

  /* wait for reply msg or room */
  rc = wait(chan, &uevt, 1000);
  if (rc != NO_ERROR)
    goto abort_test;

  /* drain all messages */
  while (rx_cnt) {
    /* get a reply */
      rc = get_msg(chan, &inf);
    if (rc == ERR_NO_MSG)
        break;  /* no more messages  */
  if (rc != NO_ERROR)
goto abort_test;

  /* read reply data */
    rc = read_msg(chan, inf.id, 0, &rx_msg);
  if (rc != 64) {
    /* unexpected reply length */
    rc = ERR_NOT_VALID;
    goto abort_test;
}

  /* discard reply */
  rc = put_msg(chan, inf.id);
  if (rc != NO_ERROR)
    goto abort_test;
  rx_cnt--;
  }
}

abort_test:
  close(chan);
  return rc;
}

Non-secure world APIs and apps

A set of Trusty services, published from the secure side and marked with the IPC_PORT_ALLOW_NS_CONNECT attribute, are accessible to kernel and user space programs running on the non-secure side.

The execution environment on the non-secure side (kernel and user space) is drastically different from the execution environment on the secure-side. Therefore, rather than a single library for both environments, there are two different sets of APIs. In the kernel, the Client API is provided by the trusty-ipc kernel driver and registers a character device node that can be used by user space processes to communicate with services running on the secure side.

User space Trusty IPC Client API

The user space Trusty IPC Client API library is a thin layer on top of the device node fd.

A user space program starts a communication session by calling tipc_connect(), initializing a connection to a specified Trusty service. Internally, the tipc_connect() call opens a specified device node to obtain a file descriptor and invokes a TIPC_IOC_CONNECT ioctl() call with the argp parameter pointing to a string containing a service name to which to connect.

#define TIPC_IOC_MAGIC  'r'
#define TIPC_IOC_CONNECT  _IOW(TIPC_IOC_MAGIC, 0x80, char *)

The resulting file descriptor can only be used to communicate with the service for which it was created. The file descriptor should be closed by calling tipc_close() when the connection isn't required anymore.

The file descriptor obtained by the tipc_connect() call behaves as a typical character device node; the file descriptor:

  • Can be switched to non-blocking mode if needed
  • Can be written to using a standard write() call to send messages to the other side
  • Can be polled (using poll() calls or select() calls) for availability of incoming messages as a regular file descriptor
  • Can be read to retrieve incoming messages

A caller sends a message to the Trusty service by executing a write call for the specified fd. All data passed to the above write() call is transformed into a message by the trusty-ipc driver. The message is delivered to the secure side where the data is handled by the IPC subsystem in the Trusty kernel and routed to the proper destination and delivered to an app event loop as an IPC_HANDLE_POLL_MSG event on a particular channel handle. Depending on the particular, service-specific protocol, the Trusty service may send one or more reply messages that are delivered back to the non-secure side and placed in the appropriate channel file descriptor message queue to be retrieved by the user space app read() call.

tipc_connect()

Opens a specified tipc device node and initiates a connection to a specified Trusty service.

int tipc_connect(const char *dev_name, const char *srv_name);

[in] dev_name: Path to the Trusty IPC device node to open

[in] srv_name: Name of a published Trusty service to which to connect

[retval]: Valid file descriptor on success, -1 otherwise.

tipc_close()

Closes the connection to the Trusty service specified by a file descriptor.

int tipc_close(int fd);

[in] fd: File descriptor previously opened by a tipc_connect() call

Kernel Trusty IPC Client API

The kernel Trusty IPC Client API is available for kernel drivers. The user space Trusty IPC API is implemented on top of this API.

In general, typical usage of this API consists of a caller creating a struct tipc_chan object by using the tipc_create_channel() function and then using the tipc_chan_connect() call to initiate a connection to the Trusty IPC service running on the secure side. The connection to the remote side can be terminated by calling tipc_chan_shutdown() followed by tipc_chan_destroy() to clean up resources.

Upon receiving a notification (through the handle_event() callback) that a connection has been successfully established, a caller does the following:

  • Obtains a message buffer using the tipc_chan_get_txbuf_timeout() call
  • Composes a message, and
  • Queues the message using the tipc_chan_queue_msg() method for delivery to a Trusty service (on the secure side), to which the channel is connected

After queueing is successful, the caller should forget the message buffer because the message buffer eventually returns to the free buffer pool after processing by the remote side (for reuse later, for other messages). The user only needs to call tipc_chan_put_txbuf() if it fails to queue such buffer or it isn't required anymore.

An API user receives messages from the remote side by handling a handle_msg() notification callback (which is called in the context of the trusty-ipc rx workqueue) that provides a pointer to an rx buffer containing an incoming message to be handled.

It is expected that the handle_msg() callback implementation returns a pointer to a valid struct tipc_msg_buf. It can be the same as the incoming message buffer if it is handled locally and not required anymore. Alternatively, it can be a new buffer obtained by a tipc_chan_get_rxbuf() call if the incoming buffer is queued for further processing. A detached rx buffer must be tracked and eventually released using a tipc_chan_put_rxbuf() call when it is no longer needed.

Methods in the Kernel Trusty IPC Client API

tipc_create_channel()

Creates and configures an instance of a Trusty IPC channel for a particular trusty-ipc device.

struct tipc_chan *tipc_create_channel(struct device *dev,
                          const struct tipc_chan_ops *ops,
                              void *cb_arg);

[in] dev: Pointer to the trusty-ipc for which the device channel is created

[in] ops: Pointer to a struct tipc_chan_ops, with caller-specific callbacks filled in

[in] cb_arg: Pointer to data that is passed to tipc_chan_ops callbacks

[retval]: Pointer to a newly-created instance of struct tipc_chan on success, ERR_PTR(err) otherwise

In general, a caller must provide two callbacks that are asynchronously invoked when the corresponding activity is occurring.

The void (*handle_event)(void *cb_arg, int event)event is invoked to notify a caller about a channel state change.

[in] cb_arg: Pointer to data passed to a tipc_create_channel() call

[in] event: An event that can be one of the following values:

  • TIPC_CHANNEL_CONNECTED - indicates a successful connection to the remote side
  • TIPC_CHANNEL_DISCONNECTED - indicates the remote side denied the new connection request or requested disconnection for the previously connected channel
  • TIPC_CHANNEL_SHUTDOWN - indicates the remote side is shutting down, permanently terminating all connections

The struct tipc_msg_buf *(*handle_msg)(void *cb_arg, struct tipc_msg_buf *mb) callback is invoked to provide notification that a new message has been received over a specified channel:

  • [in] cb_arg: Pointer to data passed to the tipc_create_channel() call
  • [in] mb: Pointer to a struct tipc_msg_buf describing an incoming message
  • [retval]: The callback implementation is expected to return a pointer to a struct tipc_msg_buf that can be the same pointer received as an mb parameter if the message is handled locally and isn't required anymore (or it can be a new buffer obtained by the tipc_chan_get_rxbuf() call)

tipc_chan_connect()

Initiates a connection to the specified Trusty IPC service.

int tipc_chan_connect(struct tipc_chan *chan, const char *port);

[in] chan: Pointer to a channel returned by the tipc_create_chan() call

[in] port: Pointer to a string containing the service name to which to connect

[retval]: 0 on success, a negative error otherwise

The caller is notified when a connection is established by receiving a handle_event callback.

tipc_chan_shutdown()

Terminates a connection to the Trusty IPC service previously initiated by a tipc_chan_connect() call.

int tipc_chan_shutdown(struct tipc_chan *chan);

[in] chan: Pointer to a channel returned by a tipc_create_chan() call

tipc_chan_destroy()

Destroys a specified Trusty IPC channel.

void tipc_chan_destroy(struct tipc_chan *chan);

[in] chan: Pointer to a channel returned by the tipc_create_chan() call

tipc_chan_get_txbuf_timeout()

Obtains a message buffer that can be used to send data over a specified channel. If the buffer isn't immediately available the caller may be blocked for the specified timeout (in milliseconds).

struct tipc_msg_buf *
tipc_chan_get_txbuf_timeout(struct tipc_chan *chan, long timeout);

[in] chan: Pointer to the channel to which to queue a message

[in] chan: Maximum timeout to wait until the tx buffer becomes available

[retval]: A valid message buffer on success, ERR_PTR(err) on error

tipc_chan_queue_msg()

Queues a message to be sent over the specified Trusty IPC channels.

int tipc_chan_queue_msg(struct tipc_chan *chan, struct tipc_msg_buf *mb);

[in] chan: Pointer to the channel to which to queue the message

[in] mb: Pointer to the message to queue (obtained by a tipc_chan_get_txbuf_timeout() call)

[retval]: 0 on success, a negative error otherwise

tipc_chan_put_txbuf()

Releases the specified Tx message buffer previously obtained by a tipc_chan_get_txbuf_timeout() call.

void tipc_chan_put_txbuf(struct tipc_chan *chan,
                         struct tipc_msg_buf *mb);

[in] chan: Pointer to the channel to which this message buffer belongs

[in] mb: Pointer to the message buffer to release

[retval]: None

tipc_chan_get_rxbuf()

Obtains a new message buffer that can be used to receive messages over the specified channel.

struct tipc_msg_buf *tipc_chan_get_rxbuf(struct tipc_chan *chan);

[in] chan: Pointer to a channel to which this message buffer belongs

[retval]: A valid message buffer on success, ERR_PTR(err) on error

tipc_chan_put_rxbuf()

Releases a specified message buffer previously obtained by a tipc_chan_get_rxbuf() call.

void tipc_chan_put_rxbuf(struct tipc_chan *chan,
                         struct tipc_msg_buf *mb);

[in] chan: Pointer to a channel to which this message buffer belongs

[in] mb: Pointer to a message buffer to release

[retval]: None