# surface_aggregator

---

# Surface System Aggregator Module (SSAM)

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> Reference for Surface System Aggregator Module (SSAM).

<a id="rst-surface-system-aggregator-module-ssam"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

- [Overview](</kernel/hardware/driver-api/surface-aggregator/overview.md>)
- [Writing Client Drivers](</kernel/hardware/driver-api/surface-aggregator/client.md>)
- [Client Driver Documentation](</kernel/hardware/driver-api/surface-aggregator-clients/index.md>)
- [Surface Serial Hub Protocol](</kernel/hardware/driver-api/surface-aggregator/ssh.md>)
- [Core Driver Internals](</kernel/hardware/driver-api/surface-aggregator/internal.md>)

---

# Client Driver API Documentation

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> Serial Hub Communication

<a id="rst-client-driver-api-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<a id="rst-contents"></a>



<a id="rst-serial-hub-communication"></a>

## Serial Hub Communication


#### <a id="c-enum-ssh_frame_type"></a>`enum ssh_frame_type`

Frame types for SSH frames.

**Constants**

- `SSH_FRAME_TYPE_DATA_SEQ`: Indicates a data frame, followed by a payload with the length specified
  in the `struct ssh_frame.len` field. This frame is sequenced, meaning
  that an ACK is required.
- `SSH_FRAME_TYPE_DATA_NSQ`: Same as `SSH_FRAME_TYPE_DATA_SEQ`, but unsequenced, meaning that the
  message does not have to be ACKed.
- `SSH_FRAME_TYPE_ACK`: Indicates an ACK message.
- `SSH_FRAME_TYPE_NAK`: Indicates an error response for previously sent frame. In general, this
  means that the frame and/or payload is malformed, e.g. a CRC is wrong.
  For command-type payloads, this can also mean that the command is
  invalid.

#### <a id="c-struct-ssh_frame"></a>`struct ssh_frame`

SSH communication frame.

**Definition**

```c
struct ssh_frame {
    u8 type;
    __le16 len;
    u8 seq;
};
```

**Members**

- `type`: The type of the frame. See [`enum ssh_frame_type`](#c-enum-ssh_frame_type).
- `len`: The length of the frame payload directly following the CRC for this
  frame. Does not include the final CRC for that payload.
- `seq`: The sequence number for this message/exchange.

#### <a id="c-enum-ssh_payload_type"></a>`enum ssh_payload_type`

Type indicator for the SSH payload.

**Constants**

- `SSH_PLD_TYPE_CMD`: The payload is a command structure with optional command
  payload.

#### <a id="c-struct-ssh_command"></a>`struct ssh_command`

Payload of a command-type frame.

**Definition**

```c
struct ssh_command {
    u8 type;
    u8 tc;
    u8 tid;
    u8 sid;
    u8 iid;
    __le16 rqid;
    u8 cid;
};
```

**Members**

- `type`: The type of the payload. See [`enum ssh_payload_type`](#c-enum-ssh_payload_type). Should be
  SSH_PLD_TYPE_CMD for this struct.
- `tc`: Command target category.
- `tid`: Target ID. Indicates the target of the message.
- `sid`: Source ID. Indicates the source of the message.
- `iid`: Instance ID.
- `rqid`: Request ID. Used to match requests with responses and differentiate
  between responses and events.
- `cid`: Command ID.

#### <a id="c-SSH_MESSAGE_LENGTH"></a>`SSH_MESSAGE_LENGTH()`

```c
SSH_MESSAGE_LENGTH(payload_size)
```

Compute length of SSH message.

**Parameters**

- `payload_size`: Length of the payload inside the SSH frame.

**Return**

Returns the length of a SSH message with payload of specified size.

#### <a id="c-SSH_COMMAND_MESSAGE_LENGTH"></a>`SSH_COMMAND_MESSAGE_LENGTH()`

```c
SSH_COMMAND_MESSAGE_LENGTH(payload_size)
```

Compute length of SSH command message.

**Parameters**

- `payload_size`: Length of the command payload.

**Return**

Returns the length of a SSH command message with command payload of
specified size.

#### <a id="c-SSH_MSGOFFSET_FRAME"></a>`SSH_MSGOFFSET_FRAME()`

```c
SSH_MSGOFFSET_FRAME(field)
```

Compute offset in SSH message to specified field in frame.

**Parameters**

- `field`: The field for which the offset should be computed.

**Return**

Returns the offset of the specified [`struct ssh_frame`](#c-struct-ssh_frame) field in the
raw SSH message data as. Takes SYN bytes (u16) preceding the frame into
account.

#### <a id="c-SSH_MSGOFFSET_COMMAND"></a>`SSH_MSGOFFSET_COMMAND()`

```c
SSH_MSGOFFSET_COMMAND(field)
```

Compute offset in SSH message to specified field in command.

**Parameters**

- `field`: The field for which the offset should be computed.

**Return**

Returns the offset of the specified [`struct ssh_command`](#c-struct-ssh_command) field in
the raw SSH message data. Takes SYN bytes (u16) preceding the frame and the
frame CRC (u16) between frame and command into account.

#### <a id="c-ssh_crc"></a>`ssh_crc()`

```c
u16 ssh_crc(const u8 *buf, size_t len)
```

Compute CRC for SSH messages.

**Parameters**

- `const u8 *buf`: The pointer pointing to the data for which the CRC should be computed.
- `size_t len`: The length of the data for which the CRC should be computed.

**Return**

Returns the CRC computed on the provided data, as used for SSH
messages.

#### <a id="c-ssh_rqid_next_valid"></a>`ssh_rqid_next_valid()`

```c
u16 ssh_rqid_next_valid(u16 rqid)
```

Return the next valid request ID.

**Parameters**

- `u16 rqid`: The current request ID.

**Return**

Returns the next valid request ID, following the current request ID
provided to this function. This function skips any request IDs reserved for
events.

#### <a id="c-ssh_rqid_to_event"></a>`ssh_rqid_to_event()`

```c
u16 ssh_rqid_to_event(u16 rqid)
```

Convert request ID to its corresponding event ID.

**Parameters**

- `u16 rqid`: The request ID to convert.

#### <a id="c-ssh_rqid_is_event"></a>`ssh_rqid_is_event()`

```c
bool ssh_rqid_is_event(u16 rqid)
```

Check if given request ID is a valid event ID.

**Parameters**

- `u16 rqid`: The request ID to check.

#### <a id="c-ssh_tc_to_rqid"></a>`ssh_tc_to_rqid()`

```c
u16 ssh_tc_to_rqid(u8 tc)
```

Convert target category to its corresponding request ID.

**Parameters**

- `u8 tc`: The target category to convert.

#### <a id="c-ssh_tid_to_index"></a>`ssh_tid_to_index()`

```c
u8 ssh_tid_to_index(u8 tid)
```

Convert target ID to its corresponding target index.

**Parameters**

- `u8 tid`: The target ID to convert.

#### <a id="c-ssh_tid_is_valid"></a>`ssh_tid_is_valid()`

```c
bool ssh_tid_is_valid(u8 tid)
```

Check if target ID is valid/supported.

**Parameters**

- `u8 tid`: The target ID to check.

#### <a id="c-struct-ssam_span"></a>`struct ssam_span`

Reference to a buffer region.

**Definition**

```c
struct ssam_span {
    u8 *ptr;
    size_t len;
};
```

**Members**

- `ptr`: Pointer to the buffer region.
- `len`: Length of the buffer region.

**Description**

A reference to a (non-owned) buffer segment, consisting of pointer and
length. Use of this struct indicates non-owned data, i.e. data of which the
life-time is managed (i.e. it is allocated/freed) via another pointer.

#### <a id="c-enum-ssam_ssh_tid"></a>`enum ssam_ssh_tid`

Target/source IDs for Serial Hub messages.

**Constants**

- `SSAM_SSH_TID_HOST`: We as the kernel Serial Hub driver.
- `SSAM_SSH_TID_SAM`: The Surface Aggregator EC.
- `SSAM_SSH_TID_KIP`: Keyboard and perihperal controller.
- `SSAM_SSH_TID_DEBUG`: Debug connector.
- `SSAM_SSH_TID_SURFLINK`: SurfLink connector.

#### <a id="c-enum-ssh_packet_base_priority"></a>`enum ssh_packet_base_priority`

Base priorities for [`struct ssh_packet`](#c-struct-ssh_packet).

**Constants**

- `SSH_PACKET_PRIORITY_FLUSH`: Base priority for flush packets.
- `SSH_PACKET_PRIORITY_DATA`: Base priority for normal data packets.
- `SSH_PACKET_PRIORITY_NAK`: Base priority for NAK packets.
- `SSH_PACKET_PRIORITY_ACK`: Base priority for ACK packets.

#### <a id="c-SSH_PACKET_PRIORITY"></a>`SSH_PACKET_PRIORITY()`

```c
SSH_PACKET_PRIORITY(base, try)
```

Compute packet priority from base priority and number of tries.

**Parameters**

- `base`: The base priority as suffix of [`enum ssh_packet_base_priority`](#c-enum-ssh_packet_base_priority), e.g.
  `FLUSH`, `DATA`, `ACK`, or `NAK`.
- `try`: The number of tries (must be less than 16).

**Description**

Compute the combined packet priority. The combined priority is dominated by
the base priority, whereas the number of (re-)tries decides the precedence
of packets with the same base priority, giving higher priority to packets
that already have more tries.

**Return**

Returns the computed priority as value fitting inside a `u8`. A
higher number means a higher priority.

#### <a id="c-ssh_packet_priority_get_try"></a>`ssh_packet_priority_get_try()`

```c
u8 ssh_packet_priority_get_try(u8 priority)
```

Get number of tries from packet priority.

**Parameters**

- `u8 priority`: The packet priority.

**Return**

Returns the number of tries encoded in the specified packet
priority.

#### <a id="c-ssh_packet_priority_get_base"></a>`ssh_packet_priority_get_base()`

```c
u8 ssh_packet_priority_get_base(u8 priority)
```

Get base priority from packet priority.

**Parameters**

- `u8 priority`: The packet priority.

**Return**

Returns the base priority encoded in the given packet priority.

#### <a id="c-struct-ssh_packet_ops"></a>`struct ssh_packet_ops`

Callback operations for a SSH packet.

**Definition**

```c
struct ssh_packet_ops {
    void (*release)(struct ssh_packet *p);
    void (*complete)(struct ssh_packet *p, int status);
};
```

**Members**

- `release`: Function called when the packet reference count reaches zero.
  This callback must be relied upon to ensure that the packet has
  left the transport system(s).
- `complete`: Function called when the packet is completed, either with
  success or failure. In case of failure, the reason for the
  failure is indicated by the value of the provided status code
  argument. This value will be zero in case of success. Note that
  a call to this callback does not guarantee that the packet is
  not in use by the transport system any more.

#### <a id="c-struct-ssh_packet"></a>`struct ssh_packet`

SSH transport packet.

**Definition**

```c
struct ssh_packet {
    struct ssh_ptl *ptl;
    struct kref refcnt;
    u8 priority;
    struct {
        size_t len;
        u8 *ptr;
    } data;
    unsigned long state;
    ktime_t timestamp;
    struct list_head queue_node;
    struct list_head pending_node;
    const struct ssh_packet_ops *ops;
};
```

**Members**

- `ptl`: Pointer to the packet transport layer. May be `NULL` if the packet
  (or enclosing request) has not been submitted yet.
- `refcnt`: Reference count of the packet.
- `priority`: Priority of the packet. Must be computed via
  [`SSH_PACKET_PRIORITY()`](#c-SSH_PACKET_PRIORITY). Must only be accessed while holding the
  queue lock after first submission.
- `data`: Raw message data.
- `data.len`: Length of the raw message data.
- `data.ptr`: Pointer to the raw message data buffer.
- `state`: State and type flags describing current packet state (dynamic)
  and type (static). See `enum ssh_packet_flags` for possible
  options.
- `timestamp`: Timestamp specifying when the latest transmission of a
  currently pending packet has been started. May be `KTIME_MAX`
  before or in-between transmission attempts. Used for the packet
  timeout implementation. Must only be accessed while holding the
  pending lock after first submission.
- `queue_node`: The list node for the packet queue.
- `pending_node`: The list node for the set of pending packets.
- `ops`: Packet operations.

#### <a id="c-ssh_packet_set_data"></a>`ssh_packet_set_data()`

```c
void ssh_packet_set_data(struct ssh_packet *p, u8 *ptr, size_t len)
```

Set raw message data of packet.

**Parameters**

- `struct ssh_packet *p`: The packet for which the message data should be set.
- `u8 *ptr`: Pointer to the memory holding the message data.
- `size_t len`: Length of the message data.

**Description**

Sets the raw message data buffer of the packet to the provided memory. The
memory is not copied. Instead, the caller is responsible for management
(i.e. allocation and deallocation) of the memory. The caller must ensure
that the provided memory is valid and contains a valid SSH message,
starting from the time of submission of the packet until the `release`
callback has been called. During this time, the memory may not be altered
in any way.

#### <a id="c-struct-ssh_request_ops"></a>`struct ssh_request_ops`

Callback operations for a SSH request.

**Definition**

```c
struct ssh_request_ops {
    void (*release)(struct ssh_request *rqst);
    void (*complete)(struct ssh_request *rqst, const struct ssh_command *cmd, const struct ssam_span *data, int status);
};
```

**Members**

- `release`: Function called when the request's reference count reaches zero.
  This callback must be relied upon to ensure that the request has
  left the transport systems (both, packet an request systems).
- `complete`: Function called when the request is completed, either with
  success or failure. The command data for the request response
  is provided via the [`struct ssh_command`](#c-struct-ssh_command) parameter (`cmd`),
  the command payload of the request response via the `struct ssh_span` parameter (`data`).

**Description**

If the request does not have any response or has not been
completed with success, both `cmd` and `data` parameters will
be NULL. If the request response does not have any command
payload, the `data` span will be an empty (zero-length) span.

In case of failure, the reason for the failure is indicated by
the value of the provided status code argument (`status`). This
value will be zero in case of success and a regular errno
otherwise.

Note that a call to this callback does not guarantee that the
request is not in use by the transport systems any more.

#### <a id="c-struct-ssh_request"></a>`struct ssh_request`

SSH transport request.

**Definition**

```c
struct ssh_request {
    struct ssh_packet packet;
    struct list_head node;
    unsigned long state;
    ktime_t timestamp;
    const struct ssh_request_ops *ops;
};
```

**Members**

- `packet`: The underlying SSH transport packet.
- `node`: List node for the request queue and pending set.
- `state`: State and type flags describing current request state (dynamic)
  and type (static). See `enum ssh_request_flags` for possible
  options.
- `timestamp`: Timestamp specifying when we start waiting on the response of
  the request. This is set once the underlying packet has been
  completed and may be `KTIME_MAX` before that, or when the request
  does not expect a response. Used for the request timeout
  implementation.
- `ops`: Request Operations.

#### <a id="c-to_ssh_request"></a>`to_ssh_request()`

```c
struct ssh_request * to_ssh_request(struct ssh_packet *p)
```

Cast a SSH packet to its enclosing SSH request.

**Parameters**

- `struct ssh_packet *p`: The packet to cast.

**Description**

Casts the given [`struct ssh_packet`](#c-struct-ssh_packet) to its enclosing [`struct ssh_request`](#c-struct-ssh_request).
The caller is responsible for making sure that the packet is actually
wrapped in a [`struct ssh_request`](#c-struct-ssh_request).

**Return**

Returns the [`struct ssh_request`](#c-struct-ssh_request) wrapping the provided packet.

#### <a id="c-ssh_request_get"></a>`ssh_request_get()`

```c
struct ssh_request * ssh_request_get(struct ssh_request *r)
```

Increment reference count of request.

**Parameters**

- `struct ssh_request *r`: The request to increment the reference count of.

**Description**

Increments the reference count of the given request by incrementing the
reference count of the underlying [`struct ssh_packet`](#c-struct-ssh_packet), enclosed in it.

See also [`ssh_request_put()`](#c-ssh_request_put), [`ssh_packet_get()`](#c-ssh_packet_get).

**Return**

Returns the request provided as input.

#### <a id="c-ssh_request_put"></a>`ssh_request_put()`

```c
void ssh_request_put(struct ssh_request *r)
```

Decrement reference count of request.

**Parameters**

- `struct ssh_request *r`: The request to decrement the reference count of.

**Description**

Decrements the reference count of the given request by decrementing the
reference count of the underlying [`struct ssh_packet`](#c-struct-ssh_packet), enclosed in it. If
the reference count reaches zero, the `release` callback specified in the
request's [`struct ssh_request_ops`](#c-struct-ssh_request_ops), i.e. `r->ops->release`, will be
called.

See also [`ssh_request_get()`](#c-ssh_request_get), [`ssh_packet_put()`](#c-ssh_packet_put).

#### <a id="c-ssh_request_set_data"></a>`ssh_request_set_data()`

```c
void ssh_request_set_data(struct ssh_request *r, u8 *ptr, size_t len)
```

Set raw message data of request.

**Parameters**

- `struct ssh_request *r`: The request for which the message data should be set.
- `u8 *ptr`: Pointer to the memory holding the message data.
- `size_t len`: Length of the message data.

**Description**

Sets the raw message data buffer of the underlying packet to the specified
buffer. Does not copy the actual message data, just sets the buffer pointer
and length. Refer to [`ssh_packet_set_data()`](#c-ssh_packet_set_data) for more details.



#### <a id="c-ssh_packet_get"></a>`ssh_packet_get()`

```c
struct ssh_packet * ssh_packet_get(struct ssh_packet *packet)
```

Increment reference count of packet.

**Parameters**

- `struct ssh_packet *packet`: The packet to increment the reference count of.

**Description**

Increments the reference count of the given packet. See [`ssh_packet_put()`](#c-ssh_packet_put)
for the counter-part of this function.

**Return**

Returns the packet provided as input.

#### <a id="c-ssh_packet_put"></a>`ssh_packet_put()`

```c
void ssh_packet_put(struct ssh_packet *packet)
```

Decrement reference count of packet.

**Parameters**

- `struct ssh_packet *packet`: The packet to decrement the reference count of.

**Description**

If the reference count reaches zero, the `release` callback specified in
the packet's [`struct ssh_packet_ops`](#c-struct-ssh_packet_ops), i.e. `packet->ops->release`, will be
called.

See [`ssh_packet_get()`](#c-ssh_packet_get) for the counter-part of this function.


<a id="rst-controller-and-core-interface"></a>

## Controller and Core Interface


#### <a id="c-enum-ssam_event_flags"></a>`enum ssam_event_flags`

Flags for enabling/disabling SAM events

**Constants**

- `SSAM_EVENT_SEQUENCED`: The event will be sent via a sequenced data frame.

#### <a id="c-struct-ssam_event"></a>`struct ssam_event`

SAM event sent from the EC to the host.

**Definition**

```c
struct ssam_event {
    u8 target_category;
    u8 target_id;
    u8 command_id;
    u8 instance_id;
    u16 length;
    u8 data[] ;
};
```

**Members**

- `target_category`: Target category of the event source. See `enum ssam_ssh_tc`.
- `target_id`: Target ID of the event source.
- `command_id`: Command ID of the event.
- `instance_id`: Instance ID of the event source.
- `length`: Length of the event payload in bytes.
- `data`: Event payload data.

#### <a id="c-enum-ssam_request_flags"></a>`enum ssam_request_flags`

Flags for SAM requests.

**Constants**

- `SSAM_REQUEST_HAS_RESPONSE`: Specifies that the request expects a response. If not set, the request
  will be directly completed after its underlying packet has been
  transmitted. If set, the request transport system waits for a response
  of the request.
- `SSAM_REQUEST_UNSEQUENCED`: Specifies that the request should be transmitted via an unsequenced
  packet. If set, the request must not have a response, meaning that this
  flag and the `SSAM_REQUEST_HAS_RESPONSE` flag are mutually exclusive.

#### <a id="c-struct-ssam_request"></a>`struct ssam_request`

SAM request description.

**Definition**

```c
struct ssam_request {
    u8 target_category;
    u8 target_id;
    u8 command_id;
    u8 instance_id;
    u16 flags;
    u16 length;
    const u8 *payload;
};
```

**Members**

- `target_category`: Category of the request's target. See `enum ssam_ssh_tc`.
- `target_id`: ID of the request's target.
- `command_id`: Command ID of the request.
- `instance_id`: Instance ID of the request's target.
- `flags`: Flags for the request. See [`enum ssam_request_flags`](#c-enum-ssam_request_flags).
- `length`: Length of the request payload in bytes.
- `payload`: Request payload data.

**Description**

This struct fully describes a SAM request with payload. It is intended to
help set up the actual transport struct, e.g. [`struct ssam_request_sync`](#c-struct-ssam_request_sync),
and specifically its raw message data via [`ssam_request_write_data()`](#c-ssam_request_write_data).

#### <a id="c-struct-ssam_response"></a>`struct ssam_response`

Response buffer for SAM request.

**Definition**

```c
struct ssam_response {
    size_t capacity;
    size_t length;
    u8 *pointer;
};
```

**Members**

- `capacity`: Capacity of the buffer, in bytes.
- `length`: Length of the actual data stored in the memory pointed to by
  **pointer**, in bytes. Set by the transport system.
- `pointer`: Pointer to the buffer's memory, storing the response payload data.

#### <a id="c-struct-ssam_request_sync"></a>`struct ssam_request_sync`

Synchronous SAM request struct.

**Definition**

```c
struct ssam_request_sync {
    struct ssh_request base;
    struct completion comp;
    struct ssam_response *resp;
    int status;
};
```

**Members**

- `base`: Underlying SSH request.
- `comp`: Completion used to signal full completion of the request. After the
  request has been submitted, this struct may only be modified or
  deallocated after the completion has been signaled.
  request has been submitted,
- `resp`: Buffer to store the response.
- `status`: Status of the request, set after the base request has been
  completed or has failed.

#### <a id="c-ssam_request_sync_set_data"></a>`ssam_request_sync_set_data()`

```c
void ssam_request_sync_set_data(struct ssam_request_sync *rqst, u8 *ptr, size_t len)
```

Set message data of a synchronous request.

**Parameters**

- `struct ssam_request_sync *rqst`: The request.
- `u8 *ptr`: Pointer to the request message data.
- `size_t len`: Length of the request message data.

**Description**

Set the request message data of a synchronous request. The provided buffer
needs to live until the request has been completed.

#### <a id="c-ssam_request_sync_set_resp"></a>`ssam_request_sync_set_resp()`

```c
void ssam_request_sync_set_resp(struct ssam_request_sync *rqst, struct ssam_response *resp)
```

Set response buffer of a synchronous request.

**Parameters**

- `struct ssam_request_sync *rqst`: The request.
- `struct ssam_response *resp`: The response buffer.

**Description**

Sets the response buffer of a synchronous request. This buffer will store
the response of the request after it has been completed. May be `NULL` if no
response is expected.

#### <a id="c-ssam_request_sync_wait"></a>`ssam_request_sync_wait()`

```c
int ssam_request_sync_wait(struct ssam_request_sync *rqst)
```

Wait for completion of a synchronous request.

**Parameters**

- `struct ssam_request_sync *rqst`: The request to wait for.

**Description**

Wait for completion and release of a synchronous request. After this
function terminates, the request is guaranteed to have left the transport
system. After successful submission of a request, this function must be
called before accessing the response of the request, freeing the request,
or freeing any of the buffers associated with the request.

This function must not be called if the request has not been submitted yet
and may lead to a deadlock/infinite wait if a subsequent request submission
fails in that case, due to the completion never triggering.

**Return**

Returns the status of the given request, which is set on completion
of the packet. This value is zero on success and negative on failure.

#### <a id="c-ssam_request_do_sync_onstack"></a>`ssam_request_do_sync_onstack()`

```c
ssam_request_do_sync_onstack(ctrl, rqst, rsp, payload_len)
```

Execute a synchronous request on the stack.

**Parameters**

- `ctrl`: The controller via which the request is submitted.
- `rqst`: The request specification.
- `rsp`: The response buffer.
- `payload_len`: The (maximum) request payload length.

**Description**

Allocates a synchronous request with specified payload length on the stack,
fully initializes it via the provided request specification, submits it,
and finally waits for its completion before returning its status. This
helper macro essentially allocates the request message buffer on the stack
and then calls [`ssam_request_do_sync_with_buffer()`](#c-ssam_request_do_sync_with_buffer).

**Note**

The **payload_len** parameter specifies the maximum payload length, used
for buffer allocation. The actual payload length may be smaller.

**Return**

Returns the status of the request or any failure during setup, i.e.
zero on success and a negative value on failure.

#### <a id="c-__ssam_retry"></a>`__ssam_retry()`

```c
__ssam_retry(request, n, args...)
```

Retry request in case of I/O errors or timeouts.

**Parameters**

- `request`: The request function to execute. Must return an integer.
- `n`: Number of tries.
- `args...`: Arguments for the request function.

**Description**

Executes the given request function, i.e. calls **request**. In case the
request returns `-EREMOTEIO` (indicates I/O error) or `-ETIMEDOUT` (request
or underlying packet timed out), **request** will be re-executed again, up to
**n** times in total.

**Return**

Returns the return value of the last execution of **request**.

#### <a id="c-ssam_retry"></a>`ssam_retry()`

```c
ssam_retry(request, args...)
```

Retry request in case of I/O errors or timeouts up to three times in total.

**Parameters**

- `request`: The request function to execute. Must return an integer.
- `args...`: Arguments for the request function.

**Description**

Executes the given request function, i.e. calls **request**. In case the
request returns `-EREMOTEIO` (indicates I/O error) or -`ETIMEDOUT` (request
or underlying packet timed out), **request** will be re-executed again, up to
three times in total.

See [`__ssam_retry()`](#c-__ssam_retry) for a more generic macro for this purpose.

**Return**

Returns the return value of the last execution of **request**.

#### <a id="c-struct-ssam_request_spec"></a>`struct ssam_request_spec`

Blue-print specification of SAM request.

**Definition**

```c
struct ssam_request_spec {
    u8 target_category;
    u8 target_id;
    u8 command_id;
    u8 instance_id;
    u8 flags;
};
```

**Members**

- `target_category`: Category of the request's target. See `enum ssam_ssh_tc`.
- `target_id`: ID of the request's target.
- `command_id`: Command ID of the request.
- `instance_id`: Instance ID of the request's target.
- `flags`: Flags for the request. See [`enum ssam_request_flags`](#c-enum-ssam_request_flags).

**Description**

Blue-print specification for a SAM request. This struct describes the
unique static parameters of a request (i.e. type) without specifying any of
its instance-specific data (e.g. payload). It is intended to be used as base
for defining simple request functions via the
`SSAM_DEFINE_SYNC_REQUEST_x()` family of macros.

#### <a id="c-struct-ssam_request_spec_md"></a>`struct ssam_request_spec_md`

Blue-print specification for multi-device SAM request.

**Definition**

```c
struct ssam_request_spec_md {
    u8 target_category;
    u8 command_id;
    u8 flags;
};
```

**Members**

- `target_category`: Category of the request's target. See `enum ssam_ssh_tc`.
- `command_id`: Command ID of the request.
- `flags`: Flags for the request. See [`enum ssam_request_flags`](#c-enum-ssam_request_flags).

**Description**

Blue-print specification for a multi-device SAM request, i.e. a request
that is applicable to multiple device instances, described by their
individual target and instance IDs. This struct describes the unique static
parameters of a request (i.e. type) without specifying any of its
instance-specific data (e.g. payload) and without specifying any of its
device specific IDs (i.e. target and instance ID). It is intended to be
used as base for defining simple multi-device request functions via the
`SSAM_DEFINE_SYNC_REQUEST_MD_x()` and `SSAM_DEFINE_SYNC_REQUEST_CL_x()`
families of macros.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_N"></a>`SSAM_DEFINE_SYNC_REQUEST_N()`

```c
SSAM_DEFINE_SYNC_REQUEST_N(name, spec...)
```

Define synchronous SAM request function with neither argument nor return value.

**Parameters**

- `name`: Name of the generated function.
- `spec...`: Specification ([`struct ssam_request_spec`](#c-struct-ssam_request_spec)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request having neither argument nor return value. The
generated function takes care of setting up the request struct and buffer
allocation, as well as execution of the request itself, returning once the
request has been fully completed. The required transport buffer will be
allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl)`, returning the status of the request, which is
zero on success and negative on failure. The `ctrl` parameter is the
controller via which the request is being sent.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_W"></a>`SSAM_DEFINE_SYNC_REQUEST_W()`

```c
SSAM_DEFINE_SYNC_REQUEST_W(name, atype, spec...)
```

Define synchronous SAM request function with argument.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `spec...`: Specification ([`struct ssam_request_spec`](#c-struct-ssam_request_spec)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking an argument of type **atype** and having no
return value. The generated function takes care of setting up the request
struct, buffer allocation, as well as execution of the request itself,
returning once the request has been fully completed. The required transport
buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, const atype *arg)`, returning the status of the
request, which is zero on success and negative on failure. The `ctrl`
parameter is the controller via which the request is sent. The request
argument is specified via the `arg` pointer.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_R"></a>`SSAM_DEFINE_SYNC_REQUEST_R()`

```c
SSAM_DEFINE_SYNC_REQUEST_R(name, rtype, spec...)
```

Define synchronous SAM request function with return value.

**Parameters**

- `name`: Name of the generated function.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec`](#c-struct-ssam_request_spec)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking no argument but having a return value of
type **rtype**. The generated function takes care of setting up the request
and response structs, buffer allocation, as well as execution of the
request itself, returning once the request has been fully completed. The
required transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, rtype *ret)`, returning the status of the request,
which is zero on success and negative on failure. The `ctrl` parameter is
the controller via which the request is sent. The request's return value is
written to the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_WR"></a>`SSAM_DEFINE_SYNC_REQUEST_WR()`

```c
SSAM_DEFINE_SYNC_REQUEST_WR(name, atype, rtype, spec...)
```

Define synchronous SAM request function with both argument and return value.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec`](#c-struct-ssam_request_spec)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by **spec**,
with the request taking an argument of type **atype** and having a return value
of type **rtype**. The generated function takes care of setting up the request
and response structs, buffer allocation, as well as execution of the request
itself, returning once the request has been fully completed. The required
transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, const atype *arg, rtype *ret)`, returning the status
of the request, which is zero on success and negative on failure. The
`ctrl` parameter is the controller via which the request is sent. The
request argument is specified via the `arg` pointer. The request's return
value is written to the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_MD_N"></a>`SSAM_DEFINE_SYNC_REQUEST_MD_N()`

```c
SSAM_DEFINE_SYNC_REQUEST_MD_N(name, spec...)
```

Define synchronous multi-device SAM request function with neither argument nor return value.

**Parameters**

- `name`: Name of the generated function.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request having neither argument nor return value. Device
specifying parameters are not hard-coded, but instead must be provided to
the function. The generated function takes care of setting up the request
struct, buffer allocation, as well as execution of the request itself,
returning once the request has been fully completed. The required transport
buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, u8 tid, u8 iid)`, returning the status of the
request, which is zero on success and negative on failure. The `ctrl`
parameter is the controller via which the request is sent, `tid` the
target ID for the request, and `iid` the instance ID.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_MD_W"></a>`SSAM_DEFINE_SYNC_REQUEST_MD_W()`

```c
SSAM_DEFINE_SYNC_REQUEST_MD_W(name, atype, spec...)
```

Define synchronous multi-device SAM request function with argument.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking an argument of type **atype** and having no
return value. Device specifying parameters are not hard-coded, but instead
must be provided to the function. The generated function takes care of
setting up the request struct, buffer allocation, as well as execution of
the request itself, returning once the request has been fully completed.
The required transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, u8 tid, u8 iid, const atype *arg)`, returning the
status of the request, which is zero on success and negative on failure.
The `ctrl` parameter is the controller via which the request is sent,
`tid` the target ID for the request, and `iid` the instance ID. The
request argument is specified via the `arg` pointer.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_MD_R"></a>`SSAM_DEFINE_SYNC_REQUEST_MD_R()`

```c
SSAM_DEFINE_SYNC_REQUEST_MD_R(name, rtype, spec...)
```

Define synchronous multi-device SAM request function with return value.

**Parameters**

- `name`: Name of the generated function.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking no argument but having a return value of
type **rtype**. Device specifying parameters are not hard-coded, but instead
must be provided to the function. The generated function takes care of
setting up the request and response structs, buffer allocation, as well as
execution of the request itself, returning once the request has been fully
completed. The required transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, u8 tid, u8 iid, rtype *ret)`, returning the status
of the request, which is zero on success and negative on failure. The
`ctrl` parameter is the controller via which the request is sent, `tid`
the target ID for the request, and `iid` the instance ID. The request's
return value is written to the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_MD_WR"></a>`SSAM_DEFINE_SYNC_REQUEST_MD_WR()`

```c
SSAM_DEFINE_SYNC_REQUEST_MD_WR(name, atype, rtype, spec...)
```

Define synchronous multi-device SAM request function with both argument and return value.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by **spec**,
with the request taking an argument of type **atype** and having a return value
of type **rtype**. Device specifying parameters are not hard-coded, but instead
must be provided to the function. The generated function takes care of
setting up the request and response structs, buffer allocation, as well as
execution of the request itself, returning once the request has been fully
completed. The required transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_controller *ctrl, u8 tid, u8 iid, const atype *arg, rtype *ret)`,
returning the status of the request, which is zero on success and negative
on failure. The `ctrl` parameter is the controller via which the request
is sent, `tid` the target ID for the request, and `iid` the instance ID.
The request argument is specified via the `arg` pointer. The request's
return value is written to the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-enum-ssam_notif_flags"></a>`enum ssam_notif_flags`

Flags used in return values from SSAM notifier callback functions.

**Constants**

- `SSAM_NOTIF_HANDLED`: Indicates that the notification has been handled. This flag should be
  set by the handler if the handler can act/has acted upon the event
  provided to it. This flag should not be set if the handler is not a
  primary handler intended for the provided event.
- `SSAM_NOTIF_STOP`: Indicates that the notifier traversal should stop. If this flag is
  returned from a notifier callback, notifier chain traversal will
  immediately stop and any remaining notifiers will not be called. This
  flag is automatically set when [`ssam_notifier_from_errno()`](#c-ssam_notifier_from_errno) is called
  with a negative error value.

**Description**

If this flag has not been set by any handler after the notifier chain
has been traversed, a warning will be emitted, stating that the event
has not been handled.

#### <a id="c-struct-ssam_notifier_block"></a>`struct ssam_notifier_block`

Base notifier block for SSAM event notifications.

**Definition**

```c
struct ssam_notifier_block {
    struct list_head node;
    ssam_notifier_fn_t fn;
    int priority;
};
```

**Members**

- `node`: The node for the list of notifiers.
- `fn`: The callback function of this notifier. This function takes the
  respective notifier block and event as input and should return
  a notifier value, which can either be obtained from the flags
  provided in [`enum ssam_notif_flags`](#c-enum-ssam_notif_flags), converted from a standard
  error value via [`ssam_notifier_from_errno()`](#c-ssam_notifier_from_errno), or a combination of
  both (e.g. `ssam_notifier_from_errno(e) | SSAM_NOTIF_HANDLED`).
- `priority`: Priority value determining the order in which notifier callbacks
  will be called. A higher value means higher priority, i.e. the
  associated callback will be executed earlier than other (lower
  priority) callbacks.

#### <a id="c-ssam_notifier_from_errno"></a>`ssam_notifier_from_errno()`

```c
u32 ssam_notifier_from_errno(int err)
```

Convert standard error value to notifier return code.

**Parameters**

- `int err`: The error code to convert, must be negative (in case of failure) or
  zero (in case of success).

**Return**

Returns the notifier return value obtained by converting the
specified **err** value. In case **err** is negative, the `SSAM_NOTIF_STOP` flag
will be set, causing notifier call chain traversal to abort.

#### <a id="c-ssam_notifier_to_errno"></a>`ssam_notifier_to_errno()`

```c
int ssam_notifier_to_errno(u32 ret)
```

Convert notifier return code to standard error value.

**Parameters**

- `u32 ret`: The notifier return value to convert.

**Return**

Returns the negative error value encoded in **ret** or zero if **ret**
indicates success.

#### <a id="c-struct-ssam_event_registry"></a>`struct ssam_event_registry`

Registry specification used for enabling events.

**Definition**

```c
struct ssam_event_registry {
    u8 target_category;
    u8 target_id;
    u8 cid_enable;
    u8 cid_disable;
};
```

**Members**

- `target_category`: Target category for the event registry requests.
- `target_id`: Target ID for the event registry requests.
- `cid_enable`: Command ID for the event-enable request.
- `cid_disable`: Command ID for the event-disable request.

**Description**

This struct describes a SAM event registry via the minimal collection of
SAM IDs specifying the requests to use for enabling and disabling an event.
The individual event to be enabled/disabled itself is specified via [`struct ssam_event_id`](#c-struct-ssam_event_id).

#### <a id="c-struct-ssam_event_id"></a>`struct ssam_event_id`

Unique event ID used for enabling events.

**Definition**

```c
struct ssam_event_id {
    u8 target_category;
    u8 instance;
};
```

**Members**

- `target_category`: Target category of the event source.
- `instance`: Instance ID of the event source.

**Description**

This struct specifies the event to be enabled/disabled via an externally
provided registry. It does not specify the registry to be used itself, this
is done via [`struct ssam_event_registry`](#c-struct-ssam_event_registry).

#### <a id="c-enum-ssam_event_mask"></a>`enum ssam_event_mask`

Flags specifying how events are matched to notifiers.

**Constants**

- `SSAM_EVENT_MASK_TARGET`: In addition to filtering by target category, only execute the notifier
  callback for events with a target ID matching to the one of the
  registry used for enabling/disabling the event.
- `SSAM_EVENT_MASK_INSTANCE`: In addition to filtering by target category, only execute the notifier
  callback for events with an instance ID matching to the instance ID
  used when enabling the event.
- `SSAM_EVENT_MASK_NONE`: Run the callback for any event with matching target category. Do not
  do any additional filtering.
- `SSAM_EVENT_MASK_STRICT`: Do all the filtering above.

#### <a id="c-SSAM_EVENT_REGISTRY"></a>`SSAM_EVENT_REGISTRY()`

```c
SSAM_EVENT_REGISTRY(tc, tid, cid_en, cid_dis)
```

Define a new event registry.

**Parameters**

- `tc`: Target category for the event registry requests.
- `tid`: Target ID for the event registry requests.
- `cid_en`: Command ID for the event-enable request.
- `cid_dis`: Command ID for the event-disable request.

**Return**

Returns the [`struct ssam_event_registry`](#c-struct-ssam_event_registry) specified by the given
parameters.

#### <a id="c-enum-ssam_event_notifier_flags"></a>`enum ssam_event_notifier_flags`

Flags for event notifiers.

**Constants**

- `SSAM_EVENT_NOTIFIER_OBSERVER`: The corresponding notifier acts as observer. Registering a notifier
  with this flag set will not attempt to enable any event. Equally,
  unregistering will not attempt to disable any event. Note that a
  notifier with this flag may not even correspond to a certain event at
  all, only to a specific event target category. Event matching will not
  be influenced by this flag.

#### <a id="c-struct-ssam_event_notifier"></a>`struct ssam_event_notifier`

Notifier block for SSAM events.

**Definition**

```c
struct ssam_event_notifier {
    struct ssam_notifier_block base;
    struct {
        struct ssam_event_registry reg;
        struct ssam_event_id id;
        enum ssam_event_mask mask;
        u8 flags;
    } event;
    unsigned long flags;
};
```

**Members**

- `base`: The base notifier block with callback function and priority.
- `event`: The event for which this block will receive notifications.
- `event.reg`: Registry via which the event will be enabled/disabled.
- `event.id`: ID specifying the event.
- `event.mask`: Flags determining how events are matched to the notifier.
- `event.flags`: Flags used for enabling the event.
- `flags`: Notifier flags (see [`enum ssam_event_notifier_flags`](#c-enum-ssam_event_notifier_flags)).

#### <a id="c-ssam_notifier_unregister"></a>`ssam_notifier_unregister()`

```c
int ssam_notifier_unregister(struct ssam_controller *ctrl, struct ssam_event_notifier *n)
```

Unregister an event notifier.

**Parameters**

- `struct ssam_controller *ctrl`: The controller the notifier has been registered on.
- `struct ssam_event_notifier *n`: The event notifier to unregister.

**Description**

Unregister an event notifier. Decrement the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the usage counter
reaches zero, the event will be disabled.

**Return**

Returns zero on success, `-ENOENT` if the given notifier block has
not been registered on the controller. If the given notifier block was the
last one associated with its specific event, returns the status of the
event-disable EC-command.



#### <a id="c-ssam_controller_device"></a>`ssam_controller_device()`

```c
struct device * ssam_controller_device(struct ssam_controller *c)
```

Get the [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) associated with this controller.

**Parameters**

- `struct ssam_controller *c`: The controller for which to get the device.

**Return**

Returns the [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) associated with this controller,
providing its lower-level transport.

#### <a id="c-ssam_controller_get"></a>`ssam_controller_get()`

```c
struct ssam_controller * ssam_controller_get(struct ssam_controller *c)
```

Increment reference count of controller.

**Parameters**

- `struct ssam_controller *c`: The controller.

**Return**

Returns the controller provided as input.

#### <a id="c-ssam_controller_put"></a>`ssam_controller_put()`

```c
void ssam_controller_put(struct ssam_controller *c)
```

Decrement reference count of controller.

**Parameters**

- `struct ssam_controller *c`: The controller.

#### <a id="c-ssam_controller_statelock"></a>`ssam_controller_statelock()`

```c
void ssam_controller_statelock(struct ssam_controller *c)
```

Lock the controller against state transitions.

**Parameters**

- `struct ssam_controller *c`: The controller to lock.

**Description**

Lock the controller against state transitions. Holding this lock guarantees
that the controller will not transition between states, i.e. if the
controller is in state "started", when this lock has been acquired, it will
remain in this state at least until the lock has been released.

Multiple clients may concurrently hold this lock. In other words: The
`statelock` functions represent the read-lock part of a r/w-semaphore.
Actions causing state transitions of the controller must be executed while
holding the write-part of this r/w-semaphore (see [`ssam_controller_lock()`](/kernel/hardware/driver-api/surface-aggregator/internal-api.md#c-ssam_controller_lock)
and `ssam_controller_unlock()` for that).

See [`ssam_controller_stateunlock()`](#c-ssam_controller_stateunlock) for the corresponding unlock function.

#### <a id="c-ssam_controller_stateunlock"></a>`ssam_controller_stateunlock()`

```c
void ssam_controller_stateunlock(struct ssam_controller *c)
```

Unlock controller state transitions.

**Parameters**

- `struct ssam_controller *c`: The controller to unlock.

**Description**

See [`ssam_controller_statelock()`](#c-ssam_controller_statelock) for the corresponding lock function.

#### <a id="c-ssam_request_write_data"></a>`ssam_request_write_data()`

```c
ssize_t ssam_request_write_data(struct ssam_span *buf, struct ssam_controller *ctrl, const struct ssam_request *spec)
```

Construct and write SAM request message to buffer.

**Parameters**

- `struct ssam_span *buf`: The buffer to write the data to.
- `struct ssam_controller *ctrl`: The controller via which the request will be sent.
- `const struct ssam_request *spec`: The request data and specification.

**Description**

Constructs a SAM/SSH request message and writes it to the provided buffer.
The request and transport counters, specifically RQID and SEQ, will be set
in this call. These counters are obtained from the controller. It is thus
only valid to send the resulting message via the controller specified here.

For calculation of the required buffer size, refer to the
[`SSH_COMMAND_MESSAGE_LENGTH()`](#c-SSH_COMMAND_MESSAGE_LENGTH) macro.

**Return**

Returns the number of bytes used in the buffer on success. Returns
`-EINVAL` if the payload length provided in the request specification is too
large (larger than `SSH_COMMAND_MAX_PAYLOAD_SIZE`) or if the provided buffer
is too small.

#### <a id="c-ssam_request_sync_alloc"></a>`ssam_request_sync_alloc()`

```c
int ssam_request_sync_alloc(size_t payload_len, gfp_t flags, struct ssam_request_sync **rqst, struct ssam_span *buffer)
```

Allocate a synchronous request.

**Parameters**

- `size_t payload_len`: The length of the request payload.
- `gfp_t flags`: Flags used for allocation.
- `struct ssam_request_sync **rqst`: Where to store the pointer to the allocated request.
- `struct ssam_span *buffer`: Where to store the buffer descriptor for the message buffer of
  the request.

**Description**

Allocates a synchronous request with corresponding message buffer. The
request still needs to be initialized [`ssam_request_sync_init()`](#c-ssam_request_sync_init) before
it can be submitted, and the message buffer data must still be set to the
returned buffer via [`ssam_request_sync_set_data()`](#c-ssam_request_sync_set_data) after it has been filled,
if need be with adjusted message length.

After use, the request and its corresponding message buffer should be freed
via [`ssam_request_sync_free()`](#c-ssam_request_sync_free). The buffer must not be freed separately.

**Return**

Returns zero on success, `-ENOMEM` if the request could not be
allocated.

#### <a id="c-ssam_request_sync_free"></a>`ssam_request_sync_free()`

```c
void ssam_request_sync_free(struct ssam_request_sync *rqst)
```

Free a synchronous request.

**Parameters**

- `struct ssam_request_sync *rqst`: The request to be freed.

**Description**

Free a synchronous request and its corresponding buffer allocated with
[`ssam_request_sync_alloc()`](#c-ssam_request_sync_alloc). Do not use for requests allocated on the stack
or via any other function.

Warning: The caller must ensure that the request is not in use any more.
I.e. the caller must ensure that it has the only reference to the request
and the request is not currently pending. This means that the caller has
either never submitted the request, request submission has failed, or the
caller has waited until the submitted request has been completed via
[`ssam_request_sync_wait()`](#c-ssam_request_sync_wait).

#### <a id="c-ssam_request_sync_init"></a>`ssam_request_sync_init()`

```c
int ssam_request_sync_init(struct ssam_request_sync *rqst, enum ssam_request_flags flags)
```

Initialize a synchronous request struct.

**Parameters**

- `struct ssam_request_sync *rqst`: The request to initialize.
- `enum ssam_request_flags flags`: The request flags.

**Description**

Initializes the given request struct. Does not initialize the request
message data. This has to be done explicitly after this call via
[`ssam_request_sync_set_data()`](#c-ssam_request_sync_set_data) and the actual message data has to be written
via [`ssam_request_write_data()`](#c-ssam_request_write_data).

**Return**

Returns zero on success or `-EINVAL` if the given flags are invalid.

#### <a id="c-ssam_request_sync_submit"></a>`ssam_request_sync_submit()`

```c
int ssam_request_sync_submit(struct ssam_controller *ctrl, struct ssam_request_sync *rqst)
```

Submit a synchronous request.

**Parameters**

- `struct ssam_controller *ctrl`: The controller with which to submit the request.
- `struct ssam_request_sync *rqst`: The request to submit.

**Description**

Submit a synchronous request. The request has to be initialized and
properly set up, including response buffer (may be `NULL` if no response is
expected) and command message data. This function does not wait for the
request to be completed.

If this function succeeds, [`ssam_request_sync_wait()`](#c-ssam_request_sync_wait) must be used to ensure
that the request has been completed before the response data can be
accessed and/or the request can be freed. On failure, the request may
immediately be freed.

This function may only be used if the controller is active, i.e. has been
initialized and not suspended.

#### <a id="c-ssam_request_do_sync"></a>`ssam_request_do_sync()`

```c
int ssam_request_do_sync(struct ssam_controller *ctrl, const struct ssam_request *spec, struct ssam_response *rsp)
```

Execute a synchronous request.

**Parameters**

- `struct ssam_controller *ctrl`: The controller via which the request will be submitted.
- `const struct ssam_request *spec`: The request specification and payload.
- `struct ssam_response *rsp`: The response buffer.

**Description**

Allocates a synchronous request with its message data buffer on the heap
via [`ssam_request_sync_alloc()`](#c-ssam_request_sync_alloc), fully initializes it via the provided
request specification, submits it, and finally waits for its completion
before freeing it and returning its status.

**Return**

Returns the status of the request or any failure during setup.

#### <a id="c-ssam_request_do_sync_with_buffer"></a>`ssam_request_do_sync_with_buffer()`

```c
int ssam_request_do_sync_with_buffer(struct ssam_controller *ctrl, const struct ssam_request *spec, struct ssam_response *rsp, struct ssam_span *buf)
```

Execute a synchronous request with the provided buffer as back-end for the message buffer.

**Parameters**

- `struct ssam_controller *ctrl`: The controller via which the request will be submitted.
- `const struct ssam_request *spec`: The request specification and payload.
- `struct ssam_response *rsp`: The response buffer.
- `struct ssam_span *buf`: The buffer for the request message data.

**Description**

Allocates a synchronous request struct on the stack, fully initializes it
using the provided buffer as message data buffer, submits it, and then
waits for its completion before returning its status. The
[`SSH_COMMAND_MESSAGE_LENGTH()`](#c-SSH_COMMAND_MESSAGE_LENGTH) macro can be used to compute the required
message buffer size.

This function does essentially the same as [`ssam_request_do_sync()`](#c-ssam_request_do_sync), but
instead of dynamically allocating the request and message data buffer, it
uses the provided message data buffer and stores the (small) request struct
on the heap.

**Return**

Returns the status of the request or any failure during setup.

#### <a id="c-ssam_notifier_register"></a>`ssam_notifier_register()`

```c
int ssam_notifier_register(struct ssam_controller *ctrl, struct ssam_event_notifier *n)
```

Register an event notifier.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to register the notifier on.
- `struct ssam_event_notifier *n`: The event notifier to register.

**Description**

Register an event notifier. Increment the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the event is not
marked as an observer and is currently not enabled, it will be enabled
during this call. If the notifier is marked as an observer, no attempt will
be made at enabling any event and no reference count will be modified.

Notifiers marked as observers do not need to be associated with one specific
event, i.e. as long as no event matching is performed, only the event target
category needs to be set.

**Return**

Returns zero on success, `-ENOSPC` if there have already been
`INT_MAX` notifiers for the event ID/type associated with the notifier block
registered, `-ENOMEM` if the corresponding event entry could not be
allocated. If this is the first time that a notifier block is registered
for the specific associated event, returns the status of the event-enable
EC-command.

#### <a id="c-__ssam_notifier_unregister"></a>`__ssam_notifier_unregister()`

```c
int __ssam_notifier_unregister(struct ssam_controller *ctrl, struct ssam_event_notifier *n, bool disable)
```

Unregister an event notifier.

**Parameters**

- `struct ssam_controller *ctrl`: The controller the notifier has been registered on.
- `struct ssam_event_notifier *n`: The event notifier to unregister.
- `bool disable`: Whether to disable the corresponding event on the EC.

**Description**

Unregister an event notifier. Decrement the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the usage counter
reaches zero and `disable` equals `true`, the event will be disabled.

Useful for hot-removable devices, where communication may fail once the
device has been physically removed. In that case, specifying `disable` as
`false` avoids communication with the EC.

**Return**

Returns zero on success, `-ENOENT` if the given notifier block has
not been registered on the controller. If the given notifier block was the
last one associated with its specific event, returns the status of the
event-disable EC-command.

#### <a id="c-ssam_controller_event_enable"></a>`ssam_controller_event_enable()`

```c
int ssam_controller_event_enable(struct ssam_controller *ctrl, struct ssam_event_registry reg, struct ssam_event_id id, u8 flags)
```

Enable the specified event.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to enable the event for.
- `struct ssam_event_registry reg`: The event registry to use for enabling the event.
- `struct ssam_event_id id`: The event ID specifying the event to be enabled.
- `u8 flags`: The SAM event flags used for enabling the event.

**Description**

Increment the event reference count of the specified event. If the event has
not been enabled previously, it will be enabled by this call.

**Note**

In general, [`ssam_notifier_register()`](#c-ssam_notifier_register) with a non-observer notifier
should be preferred for enabling/disabling events, as this will guarantee
proper ordering and event forwarding in case of errors during event
enabling/disabling.

**Return**

Returns zero on success, `-ENOSPC` if the reference count for the
specified event has reached its maximum, `-ENOMEM` if the corresponding event
entry could not be allocated. If this is the first time that this event has
been enabled (i.e. the reference count was incremented from zero to one by
this call), returns the status of the event-enable EC-command.

#### <a id="c-ssam_controller_event_disable"></a>`ssam_controller_event_disable()`

```c
int ssam_controller_event_disable(struct ssam_controller *ctrl, struct ssam_event_registry reg, struct ssam_event_id id, u8 flags)
```

Disable the specified event.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to disable the event for.
- `struct ssam_event_registry reg`: The event registry to use for disabling the event.
- `struct ssam_event_id id`: The event ID specifying the event to be disabled.
- `u8 flags`: The flags used when enabling the event.

**Description**

Decrement the reference count of the specified event. If the reference count
reaches zero, the event will be disabled.

**Note**

In general, [`ssam_notifier_register()`](#c-ssam_notifier_register)/[`ssam_notifier_unregister()`](#c-ssam_notifier_unregister) with a
non-observer notifier should be preferred for enabling/disabling events, as
this will guarantee proper ordering and event forwarding in case of errors
during event enabling/disabling.

**Return**

Returns zero on success, `-ENOENT` if the given event has not been
enabled on the controller. If the reference count of the event reaches zero
during this call, returns the status of the event-disable EC-command.



#### <a id="c-ssam_get_controller"></a>`ssam_get_controller()`

```c
struct ssam_controller * ssam_get_controller(void)
```

Get reference to SSAM controller.

**Parameters**

- `void`: no arguments

**Description**

Returns a reference to the SSAM controller of the system or `NULL` if there
is none, it hasn't been set up yet, or it has already been unregistered.
This function automatically increments the reference count of the
controller, thus the calling party must ensure that [`ssam_controller_put()`](#c-ssam_controller_put)
is called when it doesn't need the controller any more.

#### <a id="c-ssam_client_link"></a>`ssam_client_link()`

```c
int ssam_client_link(struct ssam_controller *c, struct device *client)
```

Link an arbitrary client device to the controller.

**Parameters**

- `struct ssam_controller *c`: The controller to link to.
- `struct device *client`: The client device.

**Description**

Link an arbitrary client device to the controller by creating a device link
between it as consumer and the controller device as provider. This function
can be used for non-SSAM devices (or SSAM devices not registered as child
under the controller) to guarantee that the controller is valid for as long
as the driver of the client device is bound, and that proper suspend and
resume ordering is guaranteed.

The device link does not have to be destructed manually. It is removed
automatically once the driver of the client device unbinds.

**Return**

Returns zero on success, `-ENODEV` if the controller is not ready or
going to be removed soon, or `-ENOMEM` if the device link could not be
created for other reasons.

#### <a id="c-ssam_client_bind"></a>`ssam_client_bind()`

```c
struct ssam_controller * ssam_client_bind(struct device *client)
```

Bind an arbitrary client device to the controller.

**Parameters**

- `struct device *client`: The client device.

**Description**

Link an arbitrary client device to the controller by creating a device link
between it as consumer and the main controller device as provider. This
function can be used for non-SSAM devices to guarantee that the controller
returned by this function is valid for as long as the driver of the client
device is bound, and that proper suspend and resume ordering is guaranteed.

This function does essentially the same as [`ssam_client_link()`](#c-ssam_client_link), except that
it first fetches the main controller reference, then creates the link, and
finally returns this reference. Note that this function does not increment
the reference counter of the controller, as, due to the link, the
controller lifetime is assured as long as the driver of the client device
is bound.

It is not valid to use the controller reference obtained by this method
outside of the driver bound to the client device at the time of calling
this function, without first incrementing the reference count of the
controller via [`ssam_controller_get()`](#c-ssam_controller_get). Even after doing this, care must be
taken that requests are only submitted and notifiers are only
(un-)registered when the controller is active and not suspended. In other
words: The device link only lives as long as the client driver is bound and
any guarantees enforced by this link (e.g. active controller state) can
only be relied upon as long as this link exists and may need to be enforced
in other ways afterwards.

The created device link does not have to be destructed manually. It is
removed automatically once the driver of the client device unbinds.

**Return**

Returns the controller on success, an error pointer with `-ENODEV`
if the controller is not present, not ready or going to be removed soon, or
`-ENOMEM` if the device link could not be created for other reasons.


<a id="rst-client-bus-and-client-device-api"></a>

## Client Bus and Client Device API


#### <a id="c-enum-ssam_device_domain"></a>`enum ssam_device_domain`

SAM device domain.

**Constants**

- `SSAM_DOMAIN_VIRTUAL`: Virtual device.
- `SSAM_DOMAIN_SERIALHUB`: Physical device connected via Surface Serial Hub.

#### <a id="c-enum-ssam_virtual_tc"></a>`enum ssam_virtual_tc`

Target categories for the virtual SAM domain.

**Constants**

- `SSAM_VIRTUAL_TC_HUB`: Device hub category.

#### <a id="c-struct-ssam_device_uid"></a>`struct ssam_device_uid`

Unique identifier for SSAM device.

**Definition**

```c
struct ssam_device_uid {
    u8 domain;
    u8 category;
    u8 target;
    u8 instance;
    u8 function;
};
```

**Members**

- `domain`: Domain of the device.
- `category`: Target category of the device.
- `target`: Target ID of the device.
- `instance`: Instance ID of the device.
- `function`: Sub-function of the device. This field can be used to split a
  single SAM device into multiple virtual subdevices to separate
  different functionality of that device and allow one driver per
  such functionality.

#### <a id="c-SSAM_DEVICE"></a>`SSAM_DEVICE()`

```c
SSAM_DEVICE(d, cat, tid, iid, fun)
```

Initialize a `struct ssam_device_id` with the given parameters.

**Parameters**

- `d`: Domain of the device.
- `cat`: Target category of the device.
- `tid`: Target ID of the device.
- `iid`: Instance ID of the device.
- `fun`: Sub-function of the device.

**Description**

Initializes a `struct ssam_device_id` with the given parameters. See [`struct ssam_device_uid`](#c-struct-ssam_device_uid) for details regarding the parameters. The special values
`SSAM_SSH_TID_ANY`, `SSAM_SSH_IID_ANY`, and `SSAM_SSH_FUN_ANY` can be used to specify that
matching should ignore target ID, instance ID, and/or sub-function,
respectively. This macro initializes the `match_flags` field based on the
given parameters.

**Note**

The parameters **d** and **cat** must be valid `u8` values, the parameters
**tid**, **iid**, and **fun** must be either valid `u8` values or `SSAM_SSH_TID_ANY`,
`SSAM_SSH_IID_ANY`, or `SSAM_SSH_FUN_ANY`, respectively. Other non-`u8` values are not
allowed.

#### <a id="c-SSAM_VDEV"></a>`SSAM_VDEV()`

```c
SSAM_VDEV(cat, tid, iid, fun)
```

Initialize a `struct ssam_device_id` as virtual device with the given parameters.

**Parameters**

- `cat`: Target category of the device.
- `tid`: Target ID of the device.
- `iid`: Instance ID of the device.
- `fun`: Sub-function of the device.

**Description**

Initializes a `struct ssam_device_id` with the given parameters in the
virtual domain. See [`struct ssam_device_uid`](#c-struct-ssam_device_uid) for details regarding the
parameters. The special values `SSAM_SSH_TID_ANY`, `SSAM_SSH_IID_ANY`, and
`SSAM_SSH_FUN_ANY` can be used to specify that matching should ignore target ID,
instance ID, and/or sub-function, respectively. This macro initializes the
`match_flags` field based on the given parameters.

**Note**

The parameter **cat** must be a valid `u8` value, the parameters **tid**,
**iid**, and **fun** must be either valid `u8` values or `SSAM_SSH_TID_ANY`,
`SSAM_SSH_IID_ANY`, or `SSAM_SSH_FUN_ANY`, respectively. Other non-`u8` values are not
allowed.

#### <a id="c-SSAM_SDEV"></a>`SSAM_SDEV()`

```c
SSAM_SDEV(cat, tid, iid, fun)
```

Initialize a `struct ssam_device_id` as physical SSH device with the given parameters.

**Parameters**

- `cat`: Target category of the device.
- `tid`: Target ID of the device.
- `iid`: Instance ID of the device.
- `fun`: Sub-function of the device.

**Description**

Initializes a `struct ssam_device_id` with the given parameters in the SSH
domain. See [`struct ssam_device_uid`](#c-struct-ssam_device_uid) for details regarding the parameters.
The special values `SSAM_SSH_TID_ANY`, `SSAM_SSH_IID_ANY`, and
`SSAM_SSH_FUN_ANY` can be used to specify that matching should ignore target
ID, instance ID, and/or sub-function, respectively. This macro initializes
the `match_flags` field based on the given parameters.

**Note**

The parameter **cat** must be a valid `u8` value, the parameters **tid**,
**iid**, and **fun** must be either valid `u8` values or `SSAM_SSH_TID_ANY`,
`SSAM_SSH_IID_ANY`, or `SSAM_SSH_FUN_ANY`, respectively. Other non-`u8` values
are not allowed.

#### <a id="c-struct-ssam_device"></a>`struct ssam_device`

SSAM client device.

**Definition**

```c
struct ssam_device {
    struct device dev;
    struct ssam_controller *ctrl;
    struct ssam_device_uid uid;
    unsigned long flags;
};
```

**Members**

- `dev`: Driver model representation of the device.
- `ctrl`: SSAM controller managing this device.
- `uid`: UID identifying the device.
- `flags`: Device state flags, see `enum ssam_device_flags`.

#### <a id="c-struct-ssam_device_driver"></a>`struct ssam_device_driver`

SSAM client device driver.

**Definition**

```c
struct ssam_device_driver {
    struct device_driver driver;
    const struct ssam_device_id *match_table;
    int (*probe)(struct ssam_device *sdev);
    void (*remove)(struct ssam_device *sdev);
};
```

**Members**

- `driver`: Base driver model structure.
- `match_table`: Match table specifying which devices the driver should bind to.
- `probe`: Called when the driver is being bound to a device.
- `remove`: Called when the driver is being unbound from the device.

#### <a id="c-is_ssam_device"></a>`is_ssam_device()`

```c
bool is_ssam_device(struct device *d)
```

Check if the given device is a SSAM client device.

**Parameters**

- `struct device *d`: The device to test the type of.

**Return**

Returns `true` if the specified device is of type [`struct ssam_device`](#c-struct-ssam_device), i.e. the device type points to `ssam_device_type`, and `false`
otherwise.

#### <a id="c-to_ssam_device"></a>`to_ssam_device()`

```c
to_ssam_device(d)
```

Casts the given device to a SSAM client device.

**Parameters**

- `d`: The device to cast.

**Description**

Casts the given [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) to a [`struct ssam_device`](#c-struct-ssam_device). The caller has to
ensure that the given device is actually enclosed in a [`struct ssam_device`](#c-struct-ssam_device),
e.g. by calling [`is_ssam_device()`](#c-is_ssam_device).

**Return**

Returns a pointer to the [`struct ssam_device`](#c-struct-ssam_device) wrapping the given
device **d**.

#### <a id="c-to_ssam_device_driver"></a>`to_ssam_device_driver()`

```c
to_ssam_device_driver(d)
```

Casts the given device driver to a SSAM client device driver.

**Parameters**

- `d`: The driver to cast.

**Description**

Casts the given [`struct device_driver`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device_driver) to a [`struct ssam_device_driver`](#c-struct-ssam_device_driver). The
caller has to ensure that the given driver is actually enclosed in a
[`struct ssam_device_driver`](#c-struct-ssam_device_driver).

**Return**

Returns the pointer to the [`struct ssam_device_driver`](#c-struct-ssam_device_driver) wrapping the
given device driver **d**.

#### <a id="c-ssam_device_mark_hot_removed"></a>`ssam_device_mark_hot_removed()`

```c
void ssam_device_mark_hot_removed(struct ssam_device *sdev)
```

Mark the given device as hot-removed.

**Parameters**

- `struct ssam_device *sdev`: The device to mark as hot-removed.

**Description**

Mark the device as having been hot-removed. This signals drivers using the
device that communication with the device should be avoided and may lead to
timeouts.

#### <a id="c-ssam_device_is_hot_removed"></a>`ssam_device_is_hot_removed()`

```c
bool ssam_device_is_hot_removed(struct ssam_device *sdev)
```

Check if the given device has been hot-removed.

**Parameters**

- `struct ssam_device *sdev`: The device to check.

**Description**

Checks if the given device has been marked as hot-removed. See
[`ssam_device_mark_hot_removed()`](#c-ssam_device_mark_hot_removed) for more details.

**Return**

Returns `true` if the device has been marked as hot-removed.

#### <a id="c-ssam_device_get"></a>`ssam_device_get()`

```c
struct ssam_device * ssam_device_get(struct ssam_device *sdev)
```

Increment reference count of SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to increment the reference count of.

**Description**

Increments the reference count of the given SSAM client device by
incrementing the reference count of the enclosed [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) via
[`get_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-get_device).

See [`ssam_device_put()`](#c-ssam_device_put) for the counter-part of this function.

**Return**

Returns the device provided as input.

#### <a id="c-ssam_device_put"></a>`ssam_device_put()`

```c
void ssam_device_put(struct ssam_device *sdev)
```

Decrement reference count of SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to decrement the reference count of.

**Description**

Decrements the reference count of the given SSAM client device by
decrementing the reference count of the enclosed [`struct device`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-struct-device) via
[`put_device()`](/kernel/hardware/driver-api/fundamentals/infrastructure.md#c-put_device).

See [`ssam_device_get()`](#c-ssam_device_get) for the counter-part of this function.

#### <a id="c-ssam_device_get_drvdata"></a>`ssam_device_get_drvdata()`

```c
void * ssam_device_get_drvdata(struct ssam_device *sdev)
```

Get driver-data of SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to get the driver-data from.

**Return**

Returns the driver-data of the given device, previously set via
[`ssam_device_set_drvdata()`](#c-ssam_device_set_drvdata).

#### <a id="c-ssam_device_set_drvdata"></a>`ssam_device_set_drvdata()`

```c
void ssam_device_set_drvdata(struct ssam_device *sdev, void *data)
```

Set driver-data of SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to set the driver-data of.
- `void *data`: The data to set the device's driver-data pointer to.

#### <a id="c-ssam_device_driver_register"></a>`ssam_device_driver_register()`

```c
ssam_device_driver_register(drv)
```

Register a SSAM client device driver.

**Parameters**

- `drv`: The driver to register.

#### <a id="c-module_ssam_device_driver"></a>`module_ssam_device_driver()`

```c
module_ssam_device_driver(drv)
```

Helper macro for SSAM device driver registration.

**Parameters**

- `drv`: The driver managed by this module.

**Description**

Helper macro to register a SSAM device driver via [`module_init()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_init) and
[`module_exit()`](/kernel/hardware/driver-api/fundamentals/basics.md#c-module_exit). This macro may only be used once per module and replaces the
aforementioned definitions.

#### <a id="c-ssam_register_clients"></a>`ssam_register_clients()`

```c
int ssam_register_clients(struct device *dev, struct ssam_controller *ctrl)
```

Register all client devices defined under the given parent device.

**Parameters**

- `struct device *dev`: The parent device under which clients should be registered.
- `struct ssam_controller *ctrl`: The controller with which client should be registered.

**Description**

Register all clients that have via firmware nodes been defined as children
of the given (parent) device. The respective child firmware nodes will be
associated with the correspondingly created child devices.

The given controller will be used to instantiate the new devices. See
[`ssam_device_add()`](#c-ssam_device_add) for details.

**Return**

Returns zero on success, nonzero on failure.

#### <a id="c-ssam_device_register_clients"></a>`ssam_device_register_clients()`

```c
int ssam_device_register_clients(struct ssam_device *sdev)
```

Register all client devices defined under the given SSAM parent device.

**Parameters**

- `struct ssam_device *sdev`: The parent device under which clients should be registered.

**Description**

Register all clients that have via firmware nodes been defined as children
of the given (parent) device. The respective child firmware nodes will be
associated with the correspondingly created child devices.

The controller used by the parent device will be used to instantiate the new
devices. See [`ssam_device_add()`](#c-ssam_device_add) for details.

**Return**

Returns zero on success, nonzero on failure.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_CL_N"></a>`SSAM_DEFINE_SYNC_REQUEST_CL_N()`

```c
SSAM_DEFINE_SYNC_REQUEST_CL_N(name, spec...)
```

Define synchronous client-device SAM request function with neither argument nor return value.

**Parameters**

- `name`: Name of the generated function.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request having neither argument nor return value. Device
specifying parameters are not hard-coded, but instead are provided via the
client device, specifically its UID, supplied when calling this function.
The generated function takes care of setting up the request struct, buffer
allocation, as well as execution of the request itself, returning once the
request has been fully completed. The required transport buffer will be
allocated on the stack.

The generated function is defined as `static int name(struct ssam_device *sdev)`, returning the status of the request, which is zero on success and
negative on failure. The `sdev` parameter specifies both the target
device of the request and by association the controller via which the
request is sent.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_CL_W"></a>`SSAM_DEFINE_SYNC_REQUEST_CL_W()`

```c
SSAM_DEFINE_SYNC_REQUEST_CL_W(name, atype, spec...)
```

Define synchronous client-device SAM request function with argument.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking an argument of type **atype** and having no
return value. Device specifying parameters are not hard-coded, but instead
are provided via the client device, specifically its UID, supplied when
calling this function. The generated function takes care of setting up the
request struct, buffer allocation, as well as execution of the request
itself, returning once the request has been fully completed. The required
transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_device *sdev, const atype *arg)`, returning the status of the request, which is
zero on success and negative on failure. The `sdev` parameter specifies
both the target device of the request and by association the controller via
which the request is sent. The request's argument is specified via the
`arg` pointer.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_CL_R"></a>`SSAM_DEFINE_SYNC_REQUEST_CL_R()`

```c
SSAM_DEFINE_SYNC_REQUEST_CL_R(name, rtype, spec...)
```

Define synchronous client-device SAM request function with return value.

**Parameters**

- `name`: Name of the generated function.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by
**spec**, with the request taking no argument but having a return value of
type **rtype**. Device specifying parameters are not hard-coded, but instead
are provided via the client device, specifically its UID, supplied when
calling this function. The generated function takes care of setting up the
request struct, buffer allocation, as well as execution of the request
itself, returning once the request has been fully completed. The required
transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_device *sdev, rtype *ret)`, returning the status of the request, which is zero on
success and negative on failure. The `sdev` parameter specifies both the
target device of the request and by association the controller via which
the request is sent. The request's return value is written to the memory
pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-SSAM_DEFINE_SYNC_REQUEST_CL_WR"></a>`SSAM_DEFINE_SYNC_REQUEST_CL_WR()`

```c
SSAM_DEFINE_SYNC_REQUEST_CL_WR(name, atype, rtype, spec...)
```

Define synchronous client-device SAM request function with argument and return value.

**Parameters**

- `name`: Name of the generated function.
- `atype`: Type of the request's argument.
- `rtype`: Type of the request's return value.
- `spec...`: Specification ([`struct ssam_request_spec_md`](#c-struct-ssam_request_spec_md)) defining the request.

**Description**

Defines a function executing the synchronous SAM request specified by **spec**,
with the request taking an argument of type **atype** and having a return value
of type **rtype**. Device specifying parameters are not hard-coded, but instead
are provided via the client device, specifically its UID, supplied when
calling this function. The generated function takes care of setting up the
request struct, buffer allocation, as well as execution of the request
itself, returning once the request has been fully completed. The required
transport buffer will be allocated on the stack.

The generated function is defined as `static int name(struct ssam_device *sdev, const atype *arg, rtype *ret)`, returning the status of the request,
which is zero on success and negative on failure. The `sdev` parameter
specifies both the target device of the request and by association the
controller via which the request is sent. The request's argument is
specified via the `arg` pointer. The request's return value is written to
the memory pointed to by the `ret` parameter.

Refer to [`ssam_request_do_sync_onstack()`](#c-ssam_request_do_sync_onstack) for more details on the behavior of
the generated function.

#### <a id="c-ssam_device_notifier_register"></a>`ssam_device_notifier_register()`

```c
int ssam_device_notifier_register(struct ssam_device *sdev, struct ssam_event_notifier *n)
```

Register an event notifier for the specified client device.

**Parameters**

- `struct ssam_device *sdev`: The device the notifier should be registered on.
- `struct ssam_event_notifier *n`: The event notifier to register.

**Description**

Register an event notifier. Increment the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the event is not
marked as an observer and is currently not enabled, it will be enabled
during this call. If the notifier is marked as an observer, no attempt will
be made at enabling any event and no reference count will be modified.

Notifiers marked as observers do not need to be associated with one specific
event, i.e. as long as no event matching is performed, only the event target
category needs to be set.

**Return**

Returns zero on success, `-ENOSPC` if there have already been
`INT_MAX` notifiers for the event ID/type associated with the notifier block
registered, `-ENOMEM` if the corresponding event entry could not be
allocated, `-ENODEV` if the device is marked as hot-removed. If this is the
first time that a notifier block is registered for the specific associated
event, returns the status of the event-enable EC-command.

#### <a id="c-ssam_device_notifier_unregister"></a>`ssam_device_notifier_unregister()`

```c
int ssam_device_notifier_unregister(struct ssam_device *sdev, struct ssam_event_notifier *n)
```

Unregister an event notifier for the specified client device.

**Parameters**

- `struct ssam_device *sdev`: The device the notifier has been registered on.
- `struct ssam_event_notifier *n`: The event notifier to unregister.

**Description**

Unregister an event notifier. Decrement the usage counter of the associated
SAM event if the notifier is not marked as an observer. If the usage counter
reaches zero, the event will be disabled.

In case the device has been marked as hot-removed, the event will not be
disabled on the EC, as in those cases any attempt at doing so may time out.

**Return**

Returns zero on success, `-ENOENT` if the given notifier block has
not been registered on the controller. If the given notifier block was the
last one associated with its specific event, returns the status of the
event-disable EC-command.



#### <a id="c-ssam_device_alloc"></a>`ssam_device_alloc()`

```c
struct ssam_device * ssam_device_alloc(struct ssam_controller *ctrl, struct ssam_device_uid uid)
```

Allocate and initialize a SSAM client device.

**Parameters**

- `struct ssam_controller *ctrl`: The controller under which the device should be added.
- `struct ssam_device_uid uid`: The UID of the device to be added.

**Description**

Allocates and initializes a new client device. The parent of the device
will be set to the controller device and the name will be set based on the
UID. Note that the device still has to be added via [`ssam_device_add()`](#c-ssam_device_add).
Refer to that function for more details.

**Return**

Returns the newly allocated and initialized SSAM client device, or
`NULL` if it could not be allocated.

#### <a id="c-ssam_device_add"></a>`ssam_device_add()`

```c
int ssam_device_add(struct ssam_device *sdev)
```

Add a SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The SSAM client device to be added.

**Description**

Added client devices must be guaranteed to always have a valid and active
controller. Thus, this function will fail with `-ENODEV` if the controller
of the device has not been initialized yet, has been suspended, or has been
shut down.

The caller of this function should ensure that the corresponding call to
[`ssam_device_remove()`](#c-ssam_device_remove) is issued before the controller is shut down. If the
added device is a direct child of the controller device (default), it will
be automatically removed when the controller is shut down.

By default, the controller device will become the parent of the newly
created client device. The parent may be changed before ssam_device_add is
called, but care must be taken that a) the correct suspend/resume ordering
is guaranteed and b) the client device does not outlive the controller,
i.e. that the device is removed before the controller is being shut down.
In case these guarantees have to be manually enforced, please refer to the
[`ssam_client_link()`](#c-ssam_client_link) and [`ssam_client_bind()`](#c-ssam_client_bind) functions, which are intended to
set up device-links for this purpose.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssam_device_remove"></a>`ssam_device_remove()`

```c
void ssam_device_remove(struct ssam_device *sdev)
```

Remove a SSAM client device.

**Parameters**

- `struct ssam_device *sdev`: The device to remove.

**Description**

Removes and unregisters the provided SSAM client device.

#### <a id="c-ssam_device_id_match"></a>`ssam_device_id_match()`

```c
const struct ssam_device_id * ssam_device_id_match(const struct ssam_device_id *table, const struct ssam_device_uid uid)
```

Find the matching ID table entry for the given UID.

**Parameters**

- `const struct ssam_device_id *table`: The table to search in.
- `const struct ssam_device_uid uid`: The UID to matched against the individual table entries.

**Description**

Find the first match for the provided device UID in the provided ID table
and return it. Returns `NULL` if no match could be found.

#### <a id="c-ssam_device_get_match"></a>`ssam_device_get_match()`

```c
const struct ssam_device_id * ssam_device_get_match(const struct ssam_device *dev)
```

Find and return the ID matching the device in the ID table of the bound driver.

**Parameters**

- `const struct ssam_device *dev`: The device for which to get the matching ID table entry.

**Description**

Find the fist match for the UID of the device in the ID table of the
currently bound driver and return it. Returns `NULL` if the device does not
have a driver bound to it, the driver does not have match_table (i.e. it is
`NULL`), or there is no match in the driver's match_table.

This function essentially calls [`ssam_device_id_match()`](#c-ssam_device_id_match) with the ID table of
the bound device driver and the UID of the device.

**Return**

Returns the first match for the UID of the device in the device
driver's match table, or `NULL` if no such match could be found.

#### <a id="c-ssam_device_get_match_data"></a>`ssam_device_get_match_data()`

```c
const void * ssam_device_get_match_data(const struct ssam_device *dev)
```

Find the ID matching the device in the ID table of the bound driver and return its `driver_data` member.

**Parameters**

- `const struct ssam_device *dev`: The device for which to get the match data.

**Description**

Find the fist match for the UID of the device in the ID table of the
corresponding driver and return its driver_data. Returns `NULL` if the
device does not have a driver bound to it, the driver does not have
match_table (i.e. it is `NULL`), there is no match in the driver's
match_table, or the match does not have any driver_data.

This function essentially calls [`ssam_device_get_match()`](#c-ssam_device_get_match) and, if any match
could be found, returns its `struct ssam_device_id.driver_data` member.

**Return**

Returns the driver data associated with the first match for the UID
of the device in the device driver's match table, or `NULL` if no such match
could be found.

#### <a id="c-__ssam_device_driver_register"></a>`__ssam_device_driver_register()`

```c
int __ssam_device_driver_register(struct ssam_device_driver *sdrv, struct module *owner)
```

Register a SSAM client device driver.

**Parameters**

- `struct ssam_device_driver *sdrv`: The driver to register.
- `struct module *owner`: The module owning the provided driver.

**Description**

Please refer to the [`ssam_device_driver_register()`](#c-ssam_device_driver_register) macro for the normal way
to register a driver from inside its owning module.

#### <a id="c-ssam_device_driver_unregister"></a>`ssam_device_driver_unregister()`

```c
void ssam_device_driver_unregister(struct ssam_device_driver *sdrv)
```

Unregister a SSAM device driver.

**Parameters**

- `struct ssam_device_driver *sdrv`: The driver to unregister.

#### <a id="c-__ssam_register_clients"></a>`__ssam_register_clients()`

```c
int __ssam_register_clients(struct device *parent, struct ssam_controller *ctrl, struct fwnode_handle *node)
```

Register client devices defined under the given firmware node as children of the given device.

**Parameters**

- `struct device *parent`: The parent device under which clients should be registered.
- `struct ssam_controller *ctrl`: The controller with which client should be registered.
- `struct fwnode_handle *node`: The firmware node holding definitions of the devices to be added.

**Description**

Register all clients that have been defined as children of the given root
firmware node as children of the given parent device. The respective child
firmware nodes will be associated with the correspondingly created child
devices.

The given controller will be used to instantiate the new devices. See
[`ssam_device_add()`](#c-ssam_device_add) for details.

Note that, generally, the use of either [`ssam_device_register_clients()`](#c-ssam_device_register_clients) or
[`ssam_register_clients()`](#c-ssam_register_clients) should be preferred as they directly use the
firmware node and/or controller associated with the given device. This
function is only intended for use when different device specifications (e.g.
ACPI and firmware nodes) need to be combined (as is done in the platform hub
of the device registry).

**Return**

Returns zero on success, nonzero on failure.

#### <a id="c-ssam_remove_clients"></a>`ssam_remove_clients()`

```c
void ssam_remove_clients(struct device *dev)
```

Remove SSAM client devices registered as direct children under the given parent device.

**Parameters**

- `struct device *dev`: The (parent) device to remove all direct clients for.

**Description**

Remove all SSAM client devices registered as direct children under the given
device. Note that this only accounts for direct children of the device.
Refer to [`ssam_device_add()`](#c-ssam_device_add)/[`ssam_device_remove()`](#c-ssam_device_remove) for more details.

---

# Writing Client Drivers

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> For the API documentation, refer to:

<a id="rst-writing-client-drivers"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

For the API documentation, refer to:

- [Client Driver API Documentation](</kernel/hardware/driver-api/surface-aggregator/client-api.md>)

<a id="rst-overview"></a>

## Overview

Client drivers can be set up in two main ways, depending on how the corresponding device is made available to the system. We specifically differentiate between devices that are presented to the system via one of the conventional ways, e.g. as platform devices via ACPI, and devices that are non-discoverable and instead need to be explicitly provided by some other mechanism, as discussed further below.

<a id="rst-non-ssam-client-drivers"></a>

## Non-SSAM Client Drivers

All communication with the SAM EC is handled via the `struct ssam_controller <ssam_controller>` representing that EC to the kernel. Drivers targeting a non-SSAM device (and thus not being a `struct ssam_device_driver <ssam_device_driver>`) need to explicitly establish a connection/relation to that controller. This can be done via the `ssam_client_bind()` function. Said function returns a reference to the SSAM controller, but, more importantly, also establishes a device link between client device and controller (this can also be done separate via `ssam_client_link()`). It is important to do this, as it, first, guarantees that the returned controller is valid for use in the client driver for as long as this driver is bound to its device, i.e. that the driver gets unbound before the controller ever becomes invalid, and, second, as it ensures correct suspend/resume ordering. This setup should be done in the driver's probe function, and may be used to defer probing in case the SSAM subsystem is not ready yet, for example:



```c
static int client_driver_probe(struct platform_device *pdev)
{
        struct ssam_controller *ctrl;

        ctrl = ssam_client_bind(&pdev->dev);
        if (IS_ERR(ctrl))
                return PTR_ERR(ctrl) == -ENODEV ? -EPROBE_DEFER : PTR_ERR(ctrl);

        // ...

        return 0;
}
```

The controller may be separately obtained via `ssam_get_controller()` and its lifetime be guaranteed via `ssam_controller_get()` and `ssam_controller_put()`. Note that none of these functions, however, guarantee that the controller will not be shut down or suspended. These functions essentially only operate on the reference, i.e. only guarantee a bare minimum of accessibility without any guarantees at all on practical operability.

<a id="rst-adding-ssam-devices"></a>

## Adding SSAM Devices

If a device does not already exist/is not already provided via conventional means, it should be provided as `struct ssam_device <ssam_device>` via the SSAM client device hub. New devices can be added to this hub by entering their UID into the corresponding registry. SSAM devices can also be manually allocated via `ssam_device_alloc()`, subsequently to which they have to be added via `ssam_device_add()` and eventually removed via `ssam_device_remove()`. By default, the parent of the device is set to the controller device provided for allocation, however this may be changed before the device is added. Note that, when changing the parent device, care must be taken to ensure that the controller lifetime and suspend/resume ordering guarantees, in the default setup provided through the parent-child relation, are preserved. If necessary, by use of `ssam_client_link()` as is done for non-SSAM client drivers and described in more detail above.

A client device must always be removed by the party which added the respective device before the controller shuts down. Such removal can be guaranteed by linking the driver providing the SSAM device to the controller via `ssam_client_link()`, causing it to unbind before the controller driver unbinds. Client devices registered with the controller as parent are automatically removed when the controller shuts down, but this should not be relied upon, especially as this does not extend to client devices with a different parent.

<a id="rst-ssam-client-drivers"></a>

## SSAM Client Drivers

SSAM client device drivers are, in essence, no different than other device driver types. They are represented via `struct ssam_device_driver <ssam_device_driver>` and bind to a `struct ssam_device <ssam_device>` via its UID (`struct ssam_device.uid <ssam_device>`) member and the match table (`struct ssam_device_driver.match_table <ssam_device_driver>`), which should be set when declaring the driver struct instance. Refer to the `SSAM_DEVICE()` macro documentation for more details on how to define members of the driver's match table.

The UID for SSAM client devices consists of a `domain`, a `category`, a `target`, an `instance`, and a `function`. The `domain` is used differentiate between physical SAM devices (`SSAM_DOMAIN_SERIALHUB <ssam_device_domain>`), i.e. devices that can be accessed via the Surface Serial Hub, and virtual ones (`SSAM_DOMAIN_VIRTUAL <ssam_device_domain>`), such as client-device hubs, that have no real representation on the SAM EC and are solely used on the kernel/driver-side. For physical devices, `category` represents the target category, `target` the target ID, and `instance` the instance ID used to access the physical SAM device. In addition, `function` references a specific device functionality, but has no meaning to the SAM EC. The (default) name of a client device is generated based on its UID.

A driver instance can be registered via `ssam_device_driver_register()` and unregistered via `ssam_device_driver_unregister()`. For convenience, the `module_ssam_device_driver()` macro may be used to define module init- and exit-functions registering the driver.

The controller associated with a SSAM client device can be found in its `struct ssam_device.ctrl <ssam_device>` member. This reference is guaranteed to be valid for at least as long as the client driver is bound, but should also be valid for as long as the client device exists. Note, however, that access outside of the bound client driver must ensure that the controller device is not suspended while making any requests or (un-)registering event notifiers (and thus should generally be avoided). This is guaranteed when the controller is accessed from inside the bound client driver.

<a id="rst-making-synchronous-requests"></a>

## Making Synchronous Requests

Synchronous requests are (currently) the main form of host-initiated communication with the EC. There are a couple of ways to define and execute such requests, however, most of them boil down to something similar as shown in the example below. This example defines a write-read request, meaning that the caller provides an argument to the SAM EC and receives a response. The caller needs to know the (maximum) length of the response payload and provide a buffer for it.

Care must be taken to ensure that any command payload data passed to the SAM EC is provided in little-endian format and, similarly, any response payload data received from it is converted from little-endian to host endianness.



```c
int perform_request(struct ssam_controller *ctrl, u32 arg, u32 *ret)
{
        struct ssam_request rqst;
        struct ssam_response resp;
        int status;

        /* Convert request argument to little-endian. */
        __le32 arg_le = cpu_to_le32(arg);
        __le32 ret_le = cpu_to_le32(0);

        /*
         * Initialize request specification. Replace this with your values.
         * The rqst.payload field may be NULL if rqst.length is zero,
         * indicating that the request does not have any argument.
         *
         * Note: The request parameters used here are not valid, i.e.
         *       they do not correspond to an actual SAM/EC request.
         */
        rqst.target_category = SSAM_SSH_TC_SAM;
        rqst.target_id = SSAM_SSH_TID_SAM;
        rqst.command_id = 0x02;
        rqst.instance_id = 0x03;
        rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
        rqst.length = sizeof(arg_le);
        rqst.payload = (u8 *)&arg_le;

        /* Initialize request response. */
        resp.capacity = sizeof(ret_le);
        resp.length = 0;
        resp.pointer = (u8 *)&ret_le;

        /*
         * Perform actual request. The response pointer may be null in case
         * the request does not have any response. This must be consistent
         * with the SSAM_REQUEST_HAS_RESPONSE flag set in the specification
         * above.
         */
        status = ssam_request_do_sync(ctrl, &rqst, &resp);

        /*
         * Alternatively use
         *
         *   ssam_request_do_sync_onstack(ctrl, &rqst, &resp, sizeof(arg_le));
         *
         * to perform the request, allocating the message buffer directly
         * on the stack as opposed to allocation via kzalloc().
         */

        /*
         * Convert request response back to native format. Note that in the
         * error case, this value is not touched by the SSAM core, i.e.
         * 'ret_le' will be zero as specified in its initialization.
         */
        *ret = le32_to_cpu(ret_le);

        return status;
}
```

Note that `ssam_request_do_sync()` in its essence is a wrapper over lower-level request primitives, which may also be used to perform requests. Refer to its implementation and documentation for more details.

An arguably more user-friendly way of defining such functions is by using one of the generator macros, for example via:



```c
SSAM_DEFINE_SYNC_REQUEST_W(__ssam_tmp_perf_mode_set, __le32, {
        .target_category = SSAM_SSH_TC_TMP,
        .target_id       = SSAM_SSH_TID_SAM,
        .command_id      = 0x03,
        .instance_id     = 0x00,
});
```

This example defines a function



```c
static int __ssam_tmp_perf_mode_set(struct ssam_controller *ctrl, const __le32 *arg);
```

executing the specified request, with the controller passed in when calling said function. In this example, the argument is provided via the `arg` pointer. Note that the generated function allocates the message buffer on the stack. Thus, if the argument provided via the request is large, these kinds of macros should be avoided. Also note that, in contrast to the previous non-macro example, this function does not do any endianness conversion, which has to be handled by the caller. Apart from those differences the function generated by the macro is similar to the one provided in the non-macro example above.

The full list of such function-generating macros is

- `SSAM_DEFINE_SYNC_REQUEST_N()` for requests without return value and without argument.

- `SSAM_DEFINE_SYNC_REQUEST_R()` for requests with return value but no argument.

- `SSAM_DEFINE_SYNC_REQUEST_W()` for requests without return value but with argument.

Refer to their respective documentation for more details. For each one of these macros, a special variant is provided, which targets request types applicable to multiple instances of the same device type:

- `SSAM_DEFINE_SYNC_REQUEST_MD_N()`

- `SSAM_DEFINE_SYNC_REQUEST_MD_R()`

- `SSAM_DEFINE_SYNC_REQUEST_MD_W()`

The difference of those macros to the previously mentioned versions is, that the device target and instance IDs are not fixed for the generated function, but instead have to be provided by the caller of said function.

Additionally, variants for direct use with client devices, i.e. `struct ssam_device <ssam_device>`, are also provided. These can, for example, be used as follows:



```c
SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_sta, __le32, {
        .target_category = SSAM_SSH_TC_BAT,
        .command_id      = 0x01,
});
```

This invocation of the macro defines a function



```c
static int ssam_bat_get_sta(struct ssam_device *sdev, __le32 *ret);
```

executing the specified request, using the device IDs and controller given in the client device. The full list of such macros for client devices is:

- `SSAM_DEFINE_SYNC_REQUEST_CL_N()`

- `SSAM_DEFINE_SYNC_REQUEST_CL_R()`

- `SSAM_DEFINE_SYNC_REQUEST_CL_W()`

<a id="rst-handling-events"></a>

## Handling Events

To receive events from the SAM EC, an event notifier must be registered for the desired event via `ssam_notifier_register()`. The notifier must be unregistered via `ssam_notifier_unregister()` once it is not required any more. For `struct ssam_device <ssam_device>` type clients, the `ssam_device_notifier_register()` and `ssam_device_notifier_unregister()` wrappers should be preferred as they properly handle hot-removal of client devices.

Event notifiers are registered by providing (at minimum) a callback to call in case an event has been received, the registry specifying how the event should be enabled, an event ID specifying for which target category and, optionally and depending on the registry used, for which instance ID events should be enabled, and finally, flags describing how the EC will send these events. If the specific registry does not enable events by instance ID, the instance ID must be set to zero. Additionally, a priority for the respective notifier may be specified, which determines its order in relation to any other notifier registered for the same target category.

By default, event notifiers will receive all events for the specific target category, regardless of the instance ID specified when registering the notifier. The core may be instructed to only call a notifier if the target ID or instance ID (or both) of the event match the ones implied by the notifier IDs (in case of target ID, the target ID of the registry), by providing an event mask (see `enum ssam_event_mask <ssam_event_mask>`).

In general, the target ID of the registry is also the target ID of the enabled event (with the notable exception being keyboard input events on the Surface Laptop 1 and 2, which are enabled via a registry with target ID 1, but provide events with target ID 2).

A full example for registering an event notifier and handling received events is provided below:



```c
u32 notifier_callback(struct ssam_event_notifier *nf,
                      const struct ssam_event *event)
{
        int status = ...

        /* Handle the event here ... */

        /* Convert return value and indicate that we handled the event. */
        return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
}

int setup_notifier(struct ssam_device *sdev,
                   struct ssam_event_notifier *nf)
{
        /* Set priority wrt. other handlers of same target category. */
        nf->base.priority = 1;

        /* Set event/notifier callback. */
        nf->base.fn = notifier_callback;

        /* Specify event registry, i.e. how events get enabled/disabled. */
        nf->event.reg = SSAM_EVENT_REGISTRY_KIP;

        /* Specify which event to enable/disable */
        nf->event.id.target_category = sdev->uid.category;
        nf->event.id.instance = sdev->uid.instance;

        /*
         * Specify for which events the notifier callback gets executed.
         * This essentially tells the core if it can skip notifiers that
         * don't have target or instance IDs matching those of the event.
         */
        nf->event.mask = SSAM_EVENT_MASK_STRICT;

        /* Specify event flags. */
        nf->event.flags = SSAM_EVENT_SEQUENCED;

        return ssam_notifier_register(sdev->ctrl, nf);
}
```

Multiple event notifiers can be registered for the same event. The event handler core takes care of enabling and disabling events when notifiers are registered and unregistered, by keeping track of how many notifiers for a specific event (combination of registry, event target category, and event instance ID) are currently registered. This means that a specific event will be enabled when the first notifier for it is being registered and disabled when the last notifier for it is being unregistered. Note that the event flags are therefore only used on the first registered notifier, however, one should take care that notifiers for a specific event are always registered with the same flag and it is considered a bug to do otherwise.

---

# Internal API Documentation

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> Packet Transport Layer

<a id="rst-internal-api-documentation"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

<a id="rst-contents"></a>



<a id="rst-packet-transport-layer"></a>

## Packet Transport Layer


#### <a id="c-struct-sshp_buf"></a>`struct sshp_buf`

Parser buffer for SSH messages.

**Definition**

```c
struct sshp_buf {
    u8 *ptr;
    size_t len;
    size_t cap;
};
```

**Members**

- `ptr`: Pointer to the beginning of the buffer.
- `len`: Number of bytes used in the buffer.
- `cap`: Maximum capacity of the buffer.

#### <a id="c-sshp_buf_init"></a>`sshp_buf_init()`

```c
void sshp_buf_init(struct sshp_buf *buf, u8 *ptr, size_t cap)
```

Initialize a SSH parser buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to initialize.
- `u8 *ptr`: The memory backing the buffer.
- `size_t cap`: The length of the memory backing the buffer, i.e. its capacity.

**Description**

Initializes the buffer with the given memory as backing and set its used
length to zero.

#### <a id="c-sshp_buf_alloc"></a>`sshp_buf_alloc()`

```c
int sshp_buf_alloc(struct sshp_buf *buf, size_t cap, gfp_t flags)
```

Allocate and initialize a SSH parser buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to initialize/allocate to.
- `size_t cap`: The desired capacity of the buffer.
- `gfp_t flags`: The flags used for allocating the memory.

**Description**

Allocates **cap** bytes and initializes the provided buffer struct with the
allocated memory.

**Return**

Returns zero on success and `-ENOMEM` if allocation failed.

#### <a id="c-sshp_buf_free"></a>`sshp_buf_free()`

```c
void sshp_buf_free(struct sshp_buf *buf)
```

Free a SSH parser buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to free.

**Description**

Frees a SSH parser buffer by freeing the memory backing it and then
resetting its pointer to `NULL` and length and capacity to zero. Intended to
free a buffer previously allocated with [`sshp_buf_alloc()`](#c-sshp_buf_alloc).

#### <a id="c-sshp_buf_drop"></a>`sshp_buf_drop()`

```c
void sshp_buf_drop(struct sshp_buf *buf, size_t n)
```

Drop data from the beginning of the buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to drop data from.
- `size_t n`: The number of bytes to drop.

**Description**

Drops the first **n** bytes from the buffer. Re-aligns any remaining data to
the beginning of the buffer.

#### <a id="c-sshp_buf_read_from_fifo"></a>`sshp_buf_read_from_fifo()`

```c
size_t sshp_buf_read_from_fifo(struct sshp_buf *buf, struct kfifo *fifo)
```

Transfer data from a fifo to the buffer.

**Parameters**

- `struct sshp_buf *buf`: The buffer to write the data into.
- `struct kfifo *fifo`: The fifo to read the data from.

**Description**

Transfers the data contained in the fifo to the buffer, removing it from
the fifo. This function will try to transfer as much data as possible,
limited either by the remaining space in the buffer or by the number of
bytes available in the fifo.

**Return**

Returns the number of bytes transferred.

#### <a id="c-sshp_buf_span_from"></a>`sshp_buf_span_from()`

```c
void sshp_buf_span_from(struct sshp_buf *buf, size_t offset, struct ssam_span *span)
```

Initialize a span from the given buffer and offset.

**Parameters**

- `struct sshp_buf *buf`: The buffer to create the span from.
- `size_t offset`: The offset in the buffer at which the span should start.
- `struct ssam_span *span`: The span to initialize (output).

**Description**

Initializes the provided span to point to the memory at the given offset in
the buffer, with the length of the span being capped by the number of bytes
used in the buffer after the offset (i.e. bytes remaining after the
offset).

Warning: This function does not validate that **offset** is less than or equal
to the number of bytes used in the buffer or the buffer capacity. This must
be guaranteed by the caller.



#### <a id="c-sshp_validate_crc"></a>`sshp_validate_crc()`

```c
bool sshp_validate_crc(const struct ssam_span *src, const u8 *crc)
```

Validate a CRC in raw message data.

**Parameters**

- `const struct ssam_span *src`: The span of data over which the CRC should be computed.
- `const u8 *crc`: The pointer to the expected u16 CRC value.

**Description**

Computes the CRC of the provided data span (**src**), compares it to the CRC
stored at the given address (**crc**), and returns the result of this
comparison, i.e. `true` if equal. This function is intended to run on raw
input/message data.

**Return**

Returns `true` if the computed CRC matches the stored CRC, `false`
otherwise.

#### <a id="c-sshp_starts_with_syn"></a>`sshp_starts_with_syn()`

```c
bool sshp_starts_with_syn(const struct ssam_span *src)
```

Check if the given data starts with SSH SYN bytes.

**Parameters**

- `const struct ssam_span *src`: The data span to check the start of.

#### <a id="c-sshp_find_syn"></a>`sshp_find_syn()`

```c
bool sshp_find_syn(const struct ssam_span *src, struct ssam_span *rem)
```

Find SSH SYN bytes in the given data span.

**Parameters**

- `const struct ssam_span *src`: The data span to search in.
- `struct ssam_span *rem`: The span (output) indicating the remaining data, starting with SSH
  SYN bytes, if found.

**Description**

Search for SSH SYN bytes in the given source span. If found, set the **rem**
span to the remaining data, starting with the first SYN bytes and capped by
the source span length, and return `true`. This function does not copy any
data, but rather only sets pointers to the respective start addresses and
length values.

If no SSH SYN bytes could be found, set the **rem** span to the zero-length
span at the end of the source span and return `false`.

If partial SSH SYN bytes could be found at the end of the source span, set
the **rem** span to cover these partial SYN bytes, capped by the end of the
source span, and return `false`. This function should then be re-run once
more data is available.

**Return**

Returns `true` if a complete SSH SYN sequence could be found,
`false` otherwise.

#### <a id="c-sshp_parse_frame"></a>`sshp_parse_frame()`

```c
int sshp_parse_frame(const struct device *dev, const struct ssam_span *source, struct ssh_frame **frame, struct ssam_span *payload, size_t maxlen)
```

Parse SSH frame.

**Parameters**

- `const struct device *dev`: The device used for logging.
- `const struct ssam_span *source`: The source to parse from.
- `struct ssh_frame **frame`: The parsed frame (output).
- `struct ssam_span *payload`: The parsed payload (output).
- `size_t maxlen`: The maximum supported message length.

**Description**

Parses and validates a SSH frame, including its payload, from the given
source. Sets the provided **frame** pointer to the start of the frame and
writes the limits of the frame payload to the provided **payload** span
pointer.

This function does not copy any data, but rather only validates the message
data and sets pointers (and length values) to indicate the respective parts.

If no complete SSH frame could be found, the frame pointer will be set to
the `NULL` pointer and the payload span will be set to the null span (start
pointer `NULL`, size zero).

**Return**

Returns zero on success or if the frame is incomplete, `-ENOMSG` if
the start of the message is invalid, `-EBADMSG` if any (frame-header or
payload) CRC is invalid, or `-EMSGSIZE` if the SSH message is bigger than
the maximum message length specified in the **maxlen** parameter.

#### <a id="c-sshp_parse_command"></a>`sshp_parse_command()`

```c
int sshp_parse_command(const struct device *dev, const struct ssam_span *source, struct ssh_command **command, struct ssam_span *command_data)
```

Parse SSH command frame payload.

**Parameters**

- `const struct device *dev`: The device used for logging.
- `const struct ssam_span *source`: The source to parse from.
- `struct ssh_command **command`: The parsed command (output).
- `struct ssam_span *command_data`: The parsed command data/payload (output).

**Description**

Parses and validates a SSH command frame payload. Sets the **command** pointer
to the command header and the **command_data** span to the command data (i.e.
payload of the command). This will result in a zero-length span if the
command does not have any associated data/payload. This function does not
check the frame-payload-type field, which should be checked by the caller
before calling this function.

The **source** parameter should be the complete frame payload, e.g. returned
by the [`sshp_parse_frame()`](#c-sshp_parse_frame) command.

This function does not copy any data, but rather only validates the frame
payload data and sets pointers (and length values) to indicate the
respective parts.

**Return**

Returns zero on success or `-ENOMSG` if **source** does not represent a
valid command-type frame payload, i.e. is too short.



#### <a id="c-struct-msgbuf"></a>`struct msgbuf`

Buffer struct to construct SSH messages.

**Definition**

```c
struct msgbuf {
    u8 *begin;
    u8 *end;
    u8 *ptr;
};
```

**Members**

- `begin`: Pointer to the beginning of the allocated buffer space.
- `end`: Pointer to the end (one past last element) of the allocated buffer
  space.
- `ptr`: Pointer to the first free element in the buffer.

#### <a id="c-msgb_init"></a>`msgb_init()`

```c
void msgb_init(struct msgbuf *msgb, u8 *ptr, size_t cap)
```

Initialize the given message buffer struct.

**Parameters**

- `struct msgbuf *msgb`: The buffer struct to initialize
- `u8 *ptr`: Pointer to the underlying memory by which the buffer will be backed.
- `size_t cap`: Size of the underlying memory.

**Description**

Initialize the given message buffer struct using the provided memory as
backing.

#### <a id="c-msgb_bytes_used"></a>`msgb_bytes_used()`

```c
size_t msgb_bytes_used(const struct msgbuf *msgb)
```

Return the current number of bytes used in the buffer.

**Parameters**

- `const struct msgbuf *msgb`: The message buffer.

#### <a id="c-msgb_push_u16"></a>`msgb_push_u16()`

```c
void msgb_push_u16(struct msgbuf *msgb, u16 value)
```

Push a u16 value to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.
- `u16 value`: The value to push to the buffer.

#### <a id="c-msgb_push_syn"></a>`msgb_push_syn()`

```c
void msgb_push_syn(struct msgbuf *msgb)
```

Push SSH SYN bytes to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.

#### <a id="c-msgb_push_buf"></a>`msgb_push_buf()`

```c
void msgb_push_buf(struct msgbuf *msgb, const u8 *buf, size_t len)
```

Push raw data to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.
- `const u8 *buf`: The data to push to the buffer.
- `size_t len`: The length of the data to push to the buffer.

#### <a id="c-msgb_push_crc"></a>`msgb_push_crc()`

```c
void msgb_push_crc(struct msgbuf *msgb, const u8 *buf, size_t len)
```

Compute CRC and push it to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.
- `const u8 *buf`: The data for which the CRC should be computed.
- `size_t len`: The length of the data for which the CRC should be computed.

#### <a id="c-msgb_push_frame"></a>`msgb_push_frame()`

```c
void msgb_push_frame(struct msgbuf *msgb, u8 ty, u16 len, u8 seq)
```

Push a SSH message frame header to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer
- `u8 ty`: The type of the frame.
- `u16 len`: The length of the payload of the frame.
- `u8 seq`: The sequence ID of the frame/packet.

#### <a id="c-msgb_push_ack"></a>`msgb_push_ack()`

```c
void msgb_push_ack(struct msgbuf *msgb, u8 seq)
```

Push a SSH ACK frame to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer
- `u8 seq`: The sequence ID of the frame/packet to be ACKed.

#### <a id="c-msgb_push_nak"></a>`msgb_push_nak()`

```c
void msgb_push_nak(struct msgbuf *msgb)
```

Push a SSH NAK frame to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer

#### <a id="c-msgb_push_cmd"></a>`msgb_push_cmd()`

```c
void msgb_push_cmd(struct msgbuf *msgb, u8 seq, u16 rqid, const struct ssam_request *rqst)
```

Push a SSH command frame with payload to the buffer.

**Parameters**

- `struct msgbuf *msgb`: The message buffer.
- `u8 seq`: The sequence ID (SEQ) of the frame/packet.
- `u16 rqid`: The request ID (RQID) of the request contained in the frame.
- `const struct ssam_request *rqst`: The request to wrap in the frame.



#### <a id="c-enum-ssh_ptl_state_flags"></a>`enum ssh_ptl_state_flags`

State-flags for [`struct ssh_ptl`](#c-struct-ssh_ptl).

**Constants**

- `SSH_PTL_SF_SHUTDOWN_BIT`: Indicates that the packet transport layer has been shut down or is
  being shut down and should not accept any new packets/data.

#### <a id="c-struct-ssh_ptl_ops"></a>`struct ssh_ptl_ops`

Callback operations for packet transport layer.

**Definition**

```c
struct ssh_ptl_ops {
    void (*data_received)(struct ssh_ptl *p, const struct ssam_span *data);
};
```

**Members**

- `data_received`: Function called when a data-packet has been received. Both,
  the packet layer on which the packet has been received and
  the packet's payload data are provided to this function.

#### <a id="c-struct-ssh_ptl"></a>`struct ssh_ptl`

SSH packet transport layer.

**Definition**

```c
struct ssh_ptl {
    struct serdev_device *serdev;
    unsigned long state;
    struct {
        spinlock_t lock;
        struct list_head head;
    } queue;
    struct {
        spinlock_t lock;
        struct list_head head;
        atomic_t count;
    } pending;
    struct {
        atomic_t running;
        struct task_struct *thread;
        struct completion thread_cplt_tx;
        struct completion thread_cplt_pkt;
        struct wait_queue_head packet_wq;
    } tx;
    struct {
        struct task_struct *thread;
        struct wait_queue_head wq;
        struct kfifo fifo;
        struct sshp_buf buf;
        struct {
            u16 seqs[8];
            u16 offset;
        } blocked;
    } rx;
    struct {
        spinlock_t lock;
        ktime_t timeout;
        ktime_t expires;
        struct delayed_work reaper;
    } rtx_timeout;
    struct ssh_ptl_ops ops;
};
```

**Members**

- `serdev`: Serial device providing the underlying data transport.
- `state`: State(-flags) of the transport layer.
- `queue`: Packet submission queue.
- `queue.lock`: Lock for modifying the packet submission queue.
- `queue.head`: List-head of the packet submission queue.
- `pending`: Set/list of pending packets.
- `pending.lock`: Lock for modifying the pending set.
- `pending.head`: List-head of the pending set/list.
- `pending.count`: Number of currently pending packets.
- `tx`: Transmitter subsystem.
- `tx.running`: Flag indicating (desired) transmitter thread state.
- `tx.thread`: Transmitter thread.
- `tx.thread_cplt_tx`: Completion for transmitter thread waiting on transfer.
- `tx.thread_cplt_pkt`: Completion for transmitter thread waiting on packets.
- `tx.packet_wq`: Waitqueue-head for packet transmit completion.
- `rx`: Receiver subsystem.
- `rx.thread`: Receiver thread.
- `rx.wq`: Waitqueue-head for receiver thread.
- `rx.fifo`: Buffer for receiving data/pushing data to receiver thread.
- `rx.buf`: Buffer for evaluating data on receiver thread.
- `rx.blocked`: List of recent/blocked sequence IDs to detect retransmission.
- `rx.blocked.seqs`: Array of blocked sequence IDs.
- `rx.blocked.offset`: Offset indicating where a new ID should be inserted.
- `rtx_timeout`: Retransmission timeout subsystem.
- `rtx_timeout.lock`: Lock for modifying the retransmission timeout reaper.
- `rtx_timeout.timeout`: Timeout interval for retransmission.
- `rtx_timeout.expires`: Time specifying when the reaper work is next scheduled.
- `rtx_timeout.reaper`: Work performing timeout checks and subsequent actions.
- `ops`: Packet layer operations.

#### <a id="c-ssh_ptl_get_device"></a>`ssh_ptl_get_device()`

```c
struct device * ssh_ptl_get_device(struct ssh_ptl *ptl)
```

Get device associated with packet transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns the device on which the given packet transport layer builds
upon.

#### <a id="c-ssh_ptl_tx_wakeup_transfer"></a>`ssh_ptl_tx_wakeup_transfer()`

```c
void ssh_ptl_tx_wakeup_transfer(struct ssh_ptl *ptl)
```

Wake up packet transmitter thread for transfer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Description**

Wakes up the packet transmitter thread, notifying it that the underlying
transport has more space for data to be transmitted. If the packet
transport layer has been shut down, calls to this function will be ignored.



#### <a id="c-ssh_ptl_should_drop_ack_packet"></a>`ssh_ptl_should_drop_ack_packet()`

```c
bool ssh_ptl_should_drop_ack_packet(void)
```

Error injection hook to drop ACK packets.

**Parameters**

- `void`: no arguments

**Description**

Useful to test detection and handling of automated re-transmits by the EC.
Specifically of packets that the EC considers not-ACKed but the driver
already considers ACKed (due to dropped ACK). In this case, the EC
re-transmits the packet-to-be-ACKed and the driver should detect it as
duplicate/already handled. Note that the driver should still send an ACK
for the re-transmitted packet.

#### <a id="c-ssh_ptl_should_drop_nak_packet"></a>`ssh_ptl_should_drop_nak_packet()`

```c
bool ssh_ptl_should_drop_nak_packet(void)
```

Error injection hook to drop NAK packets.

**Parameters**

- `void`: no arguments

**Description**

Useful to test/force automated (timeout-based) re-transmit by the EC.
Specifically, packets that have not reached the driver completely/with valid
checksums. Only useful in combination with receival of (injected) bad data.

#### <a id="c-ssh_ptl_should_drop_dsq_packet"></a>`ssh_ptl_should_drop_dsq_packet()`

```c
bool ssh_ptl_should_drop_dsq_packet(void)
```

Error injection hook to drop sequenced data packet.

**Parameters**

- `void`: no arguments

**Description**

Useful to test re-transmit timeout of the driver. If the data packet has not
been ACKed after a certain time, the driver should re-transmit the packet up
to limited number of times defined in SSH_PTL_MAX_PACKET_TRIES.

#### <a id="c-ssh_ptl_should_fail_write"></a>`ssh_ptl_should_fail_write()`

```c
int ssh_ptl_should_fail_write(void)
```

Error injection hook to make `serdev_device_write()` fail.

**Parameters**

- `void`: no arguments

**Description**

Hook to simulate errors in serdev_device_write when transmitting packets.

#### <a id="c-ssh_ptl_should_corrupt_tx_data"></a>`ssh_ptl_should_corrupt_tx_data()`

```c
bool ssh_ptl_should_corrupt_tx_data(void)
```

Error injection hook to simulate invalid data being sent to the EC.

**Parameters**

- `void`: no arguments

**Description**

Hook to simulate corrupt/invalid data being sent from host (driver) to EC.
Causes the packet data to be actively corrupted by overwriting it with
pre-defined values, such that it becomes invalid, causing the EC to respond
with a NAK packet. Useful to test handling of NAK packets received by the
driver.

#### <a id="c-ssh_ptl_should_corrupt_rx_syn"></a>`ssh_ptl_should_corrupt_rx_syn()`

```c
bool ssh_ptl_should_corrupt_rx_syn(void)
```

Error injection hook to simulate invalid data being sent by the EC.

**Parameters**

- `void`: no arguments

**Description**

Hook to simulate invalid SYN bytes, i.e. an invalid start of messages and
test handling thereof in the driver.

#### <a id="c-ssh_ptl_should_corrupt_rx_data"></a>`ssh_ptl_should_corrupt_rx_data()`

```c
bool ssh_ptl_should_corrupt_rx_data(void)
```

Error injection hook to simulate invalid data being sent by the EC.

**Parameters**

- `void`: no arguments

**Description**

Hook to simulate invalid data/checksum of the message frame and test handling
thereof in the driver.

#### <a id="c-ssh_packet_init"></a>`ssh_packet_init()`

```c
void ssh_packet_init(struct ssh_packet *packet, unsigned long type, u8 priority, const struct ssh_packet_ops *ops)
```

Initialize SSH packet.

**Parameters**

- `struct ssh_packet *packet`: The packet to initialize.
- `unsigned long type`: Type-flags of the packet.
- `u8 priority`: Priority of the packet. See [`SSH_PACKET_PRIORITY()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-SSH_PACKET_PRIORITY) for details.
- `const struct ssh_packet_ops *ops`: Packet operations.

**Description**

Initializes the given SSH packet. Sets the transmission buffer pointer to
`NULL` and the transmission buffer length to zero. For data-type packets,
this buffer has to be set separately via [`ssh_packet_set_data()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssh_packet_set_data) before
submission, and must contain a valid SSH message, i.e. frame with optional
payload of any type.

#### <a id="c-ssh_ctrl_packet_cache_init"></a>`ssh_ctrl_packet_cache_init()`

```c
int ssh_ctrl_packet_cache_init(void)
```

Initialize the control packet cache.

**Parameters**

- `void`: no arguments

#### <a id="c-ssh_ctrl_packet_cache_destroy"></a>`ssh_ctrl_packet_cache_destroy()`

```c
void ssh_ctrl_packet_cache_destroy(void)
```

Deinitialize the control packet cache.

**Parameters**

- `void`: no arguments

#### <a id="c-ssh_ctrl_packet_alloc"></a>`ssh_ctrl_packet_alloc()`

```c
int ssh_ctrl_packet_alloc(struct ssh_packet **packet, struct ssam_span *buffer, gfp_t flags)
```

Allocate packet from control packet cache.

**Parameters**

- `struct ssh_packet **packet`: Where the pointer to the newly allocated packet should be stored.
- `struct ssam_span *buffer`: The buffer corresponding to this packet.
- `gfp_t flags`: Flags used for allocation.

**Description**

Allocates a packet and corresponding transport buffer from the control
packet cache. Sets the packet's buffer reference to the allocated buffer.
The packet must be freed via [`ssh_ctrl_packet_free()`](#c-ssh_ctrl_packet_free), which will also free
the corresponding buffer. The corresponding buffer must not be freed
separately. Intended to be used with `ssh_ptl_ctrl_packet_ops` as packet
operations.

**Return**

Returns zero on success, `-ENOMEM` if the allocation failed.

#### <a id="c-ssh_ctrl_packet_free"></a>`ssh_ctrl_packet_free()`

```c
void ssh_ctrl_packet_free(struct ssh_packet *p)
```

Free packet allocated from control packet cache.

**Parameters**

- `struct ssh_packet *p`: The packet to free.

#### <a id="c-ssh_ptl_tx_wakeup_packet"></a>`ssh_ptl_tx_wakeup_packet()`

```c
void ssh_ptl_tx_wakeup_packet(struct ssh_ptl *ptl)
```

Wake up packet transmitter thread for new packet.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Description**

Wakes up the packet transmitter thread, notifying it that a new packet has
arrived and is ready for transfer. If the packet transport layer has been
shut down, calls to this function will be ignored.

#### <a id="c-ssh_ptl_tx_start"></a>`ssh_ptl_tx_start()`

```c
int ssh_ptl_tx_start(struct ssh_ptl *ptl)
```

Start packet transmitter thread.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_ptl_tx_stop"></a>`ssh_ptl_tx_stop()`

```c
int ssh_ptl_tx_stop(struct ssh_ptl *ptl)
```

Stop packet transmitter thread.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_ptl_submit"></a>`ssh_ptl_submit()`

```c
int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *p)
```

Submit a packet to the transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer to submit the packet to.
- `struct ssh_packet *p`: The packet to submit.

**Description**

Submits a new packet to the transport layer, queuing it to be sent. This
function should not be used for re-submission.

**Return**

Returns zero on success, `-EINVAL` if a packet field is invalid or
the packet has been canceled prior to submission, `-EALREADY` if the packet
has already been submitted, or `-ESHUTDOWN` if the packet transport layer
has been shut down.

#### <a id="c-ssh_ptl_cancel"></a>`ssh_ptl_cancel()`

```c
void ssh_ptl_cancel(struct ssh_packet *p)
```

Cancel a packet.

**Parameters**

- `struct ssh_packet *p`: The packet to cancel.

**Description**

Cancels a packet. There are no guarantees on when completion and release
callbacks will be called. This may occur during execution of this function
or may occur at any point later.

Note that it is not guaranteed that the packet will actually be canceled if
the packet is concurrently completed by another process. The only guarantee
of this function is that the packet will be completed (with success,
failure, or cancellation) and released from the transport layer in a
reasonable time-frame.

May be called before the packet has been submitted, in which case any later
packet submission fails.

#### <a id="c-ssh_ptl_rx_start"></a>`ssh_ptl_rx_start()`

```c
int ssh_ptl_rx_start(struct ssh_ptl *ptl)
```

Start packet transport layer receiver thread.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_ptl_rx_stop"></a>`ssh_ptl_rx_stop()`

```c
int ssh_ptl_rx_stop(struct ssh_ptl *ptl)
```

Stop packet transport layer receiver thread.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_ptl_rx_rcvbuf"></a>`ssh_ptl_rx_rcvbuf()`

```c
ssize_t ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n)
```

Push data from lower-layer transport to the packet layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.
- `const u8 *buf`: Pointer to the data to push to the layer.
- `size_t n`: Size of the data to push to the layer, in bytes.

**Description**

Pushes data from a lower-layer transport to the receiver fifo buffer of the
packet layer and notifies the receiver thread. Calls to this function are
ignored once the packet layer has been shut down.

**Return**

Returns the number of bytes transferred (positive or zero) on
success. Returns `-ESHUTDOWN` if the packet layer has been shut down.

#### <a id="c-ssh_ptl_shutdown"></a>`ssh_ptl_shutdown()`

```c
void ssh_ptl_shutdown(struct ssh_ptl *ptl)
```

Shut down the packet transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer.

**Description**

Shuts down the packet transport layer, removing and canceling all queued
and pending packets. Packets canceled by this operation will be completed
with `-ESHUTDOWN` as status. Receiver and transmitter threads will be
stopped.

As a result of this function, the transport layer will be marked as shut
down. Submission of packets after the transport layer has been shut down
will fail with `-ESHUTDOWN`.

#### <a id="c-ssh_ptl_init"></a>`ssh_ptl_init()`

```c
int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev, struct ssh_ptl_ops *ops)
```

Initialize packet transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer to initialize.
- `struct serdev_device *serdev`: The underlying serial device, i.e. the lower-level transport.
- `struct ssh_ptl_ops *ops`: Packet layer operations.

**Description**

Initializes the given packet transport layer. Transmitter and receiver
threads must be started separately via [`ssh_ptl_tx_start()`](#c-ssh_ptl_tx_start) and
[`ssh_ptl_rx_start()`](#c-ssh_ptl_rx_start), after the packet-layer has been initialized and the
lower-level transport layer has been set up.

**Return**

Returns zero on success and a nonzero error code on failure.

#### <a id="c-ssh_ptl_destroy"></a>`ssh_ptl_destroy()`

```c
void ssh_ptl_destroy(struct ssh_ptl *ptl)
```

Deinitialize packet transport layer.

**Parameters**

- `struct ssh_ptl *ptl`: The packet transport layer to deinitialize.

**Description**

Deinitializes the given packet transport layer and frees resources
associated with it. If receiver and/or transmitter threads have been
started, the layer must first be shut down via [`ssh_ptl_shutdown()`](#c-ssh_ptl_shutdown) before
this function can be called.


<a id="rst-request-transport-layer"></a>

## Request Transport Layer


#### <a id="c-enum-ssh_rtl_state_flags"></a>`enum ssh_rtl_state_flags`

State-flags for [`struct ssh_rtl`](#c-struct-ssh_rtl).

**Constants**

- `SSH_RTL_SF_SHUTDOWN_BIT`: Indicates that the request transport layer has been shut down or is
  being shut down and should not accept any new requests.

#### <a id="c-struct-ssh_rtl_ops"></a>`struct ssh_rtl_ops`

Callback operations for request transport layer.

**Definition**

```c
struct ssh_rtl_ops {
    void (*handle_event)(struct ssh_rtl *rtl, const struct ssh_command *cmd, const struct ssam_span *data);
};
```

**Members**

- `handle_event`: Function called when a SSH event has been received. The
  specified function takes the request layer, received command
  struct, and corresponding payload as arguments. If the event
  has no payload, the payload span is empty (not `NULL`).

#### <a id="c-struct-ssh_rtl"></a>`struct ssh_rtl`

SSH request transport layer.

**Definition**

```c
struct ssh_rtl {
    struct ssh_ptl ptl;
    unsigned long state;
    struct {
        spinlock_t lock;
        struct list_head head;
    } queue;
    struct {
        spinlock_t lock;
        struct list_head head;
        atomic_t count;
    } pending;
    struct {
        struct work_struct work;
    } tx;
    struct {
        spinlock_t lock;
        ktime_t timeout;
        ktime_t expires;
        struct delayed_work reaper;
    } rtx_timeout;
    struct ssh_rtl_ops ops;
};
```

**Members**

- `ptl`: Underlying packet transport layer.
- `state`: State(-flags) of the transport layer.
- `queue`: Request submission queue.
- `queue.lock`: Lock for modifying the request submission queue.
- `queue.head`: List-head of the request submission queue.
- `pending`: Set/list of pending requests.
- `pending.lock`: Lock for modifying the request set.
- `pending.head`: List-head of the pending set/list.
- `pending.count`: Number of currently pending requests.
- `tx`: Transmitter subsystem.
- `tx.work`: Transmitter work item.
- `rtx_timeout`: Retransmission timeout subsystem.
- `rtx_timeout.lock`: Lock for modifying the retransmission timeout reaper.
- `rtx_timeout.timeout`: Timeout interval for retransmission.
- `rtx_timeout.expires`: Time specifying when the reaper work is next scheduled.
- `rtx_timeout.reaper`: Work performing timeout checks and subsequent actions.
- `ops`: Request layer operations.

#### <a id="c-ssh_rtl_get_device"></a>`ssh_rtl_get_device()`

```c
struct device * ssh_rtl_get_device(struct ssh_rtl *rtl)
```

Get device associated with request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer.

**Return**

Returns the device on which the given request transport layer
builds upon.

#### <a id="c-ssh_request_rtl"></a>`ssh_request_rtl()`

```c
struct ssh_rtl * ssh_request_rtl(struct ssh_request *rqst)
```

Get request transport layer associated with request.

**Parameters**

- `struct ssh_request *rqst`: The request to get the request transport layer reference for.

**Return**

Returns the [`struct ssh_rtl`](#c-struct-ssh_rtl) associated with the given SSH request.



#### <a id="c-ssh_rtl_should_drop_response"></a>`ssh_rtl_should_drop_response()`

```c
bool ssh_rtl_should_drop_response(void)
```

Error injection hook to drop request responses.

**Parameters**

- `void`: no arguments

**Description**

Useful to cause request transmission timeouts in the driver by dropping the
response to a request.

#### <a id="c-ssh_rtl_submit"></a>`ssh_rtl_submit()`

```c
int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst)
```

Submit a request to the transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer.
- `struct ssh_request *rqst`: The request to submit.

**Description**

Submits a request to the transport layer. A single request may not be
submitted multiple times without reinitializing it.

**Return**

Returns zero on success, `-EINVAL` if the request type is invalid or
the request has been canceled prior to submission, `-EALREADY` if the
request has already been submitted, or `-ESHUTDOWN` in case the request
transport layer has been shut down.

#### <a id="c-ssh_rtl_cancel"></a>`ssh_rtl_cancel()`

```c
bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending)
```

Cancel request.

**Parameters**

- `struct ssh_request *rqst`: The request to cancel.
- `bool pending`: Whether to also cancel pending requests.

**Description**

Cancels the given request. If **pending** is `false`, this will not cancel
pending requests, i.e. requests that have already been submitted to the
packet layer but not been completed yet. If **pending** is `true`, this will
cancel the given request regardless of the state it is in.

If the request has been canceled by calling this function, both completion
and release callbacks of the request will be executed in a reasonable
time-frame. This may happen during execution of this function, however,
there is no guarantee for this. For example, a request currently
transmitting will be canceled/completed only after transmission has
completed, and the respective callbacks will be executed on the transmitter
thread, which may happen during, but also some time after execution of the
cancel function.

**Return**

Returns `true` if the given request has been canceled or completed,
either by this function or prior to calling this function, `false`
otherwise. If **pending** is `true`, this function will always return `true`.

#### <a id="c-ssh_request_init"></a>`ssh_request_init()`

```c
int ssh_request_init(struct ssh_request *rqst, enum ssam_request_flags flags, const struct ssh_request_ops *ops)
```

Initialize SSH request.

**Parameters**

- `struct ssh_request *rqst`: The request to initialize.
- `enum ssam_request_flags flags`: Request flags, determining the type of the request.
- `const struct ssh_request_ops *ops`: Request operations.

**Description**

Initializes the given SSH request and underlying packet. Sets the message
buffer pointer to `NULL` and the message buffer length to zero. This buffer
has to be set separately via [`ssh_request_set_data()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssh_request_set_data) before submission and
must contain a valid SSH request message.

**Return**

Returns zero on success or `-EINVAL` if the given flags are invalid.

#### <a id="c-ssh_rtl_init"></a>`ssh_rtl_init()`

```c
int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev, const struct ssh_rtl_ops *ops)
```

Initialize request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer to initialize.
- `struct serdev_device *serdev`: The underlying serial device, i.e. the lower-level transport.
- `const struct ssh_rtl_ops *ops`: Request transport layer operations.

**Description**

Initializes the given request transport layer and associated packet
transport layer. Transmitter and receiver threads must be started
separately via [`ssh_rtl_start()`](#c-ssh_rtl_start), after the request-layer has been
initialized and the lower-level serial device layer has been set up.

**Return**

Returns zero on success and a nonzero error code on failure.

#### <a id="c-ssh_rtl_destroy"></a>`ssh_rtl_destroy()`

```c
void ssh_rtl_destroy(struct ssh_rtl *rtl)
```

Deinitialize request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer to deinitialize.

**Description**

Deinitializes the given request transport layer and frees resources
associated with it. If receiver and/or transmitter threads have been
started, the layer must first be shut down via [`ssh_rtl_shutdown()`](#c-ssh_rtl_shutdown) before
this function can be called.

#### <a id="c-ssh_rtl_start"></a>`ssh_rtl_start()`

```c
int ssh_rtl_start(struct ssh_rtl *rtl)
```

Start request transmitter and receiver.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssh_rtl_flush"></a>`ssh_rtl_flush()`

```c
int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout)
```

Flush the request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: request transport layer
- `unsigned long timeout`: timeout for the flush operation in jiffies

**Description**

Queue a special flush request and wait for its completion. This request
will be completed after all other currently queued and pending requests
have been completed. Instead of a normal data packet, this request submits
a special flush packet, meaning that upon completion, also the underlying
packet transport layer has been flushed.

Flushing the request layer guarantees that all previously submitted
requests have been fully completed before this call returns. Additionally,
flushing blocks execution of all later submitted requests until the flush
has been completed.

If the caller ensures that no new requests are submitted after a call to
this function, the request transport layer is guaranteed to have no
remaining requests when this call returns. The same guarantee does not hold
for the packet layer, on which control packets may still be queued after
this call.

**Return**

Returns zero on success, `-ETIMEDOUT` if the flush timed out and has
been canceled as a result of the timeout, or `-ESHUTDOWN` if the packet
and/or request transport layer has been shut down before this call. May
also return `-EINTR` if the underlying packet transmission has been
interrupted.

#### <a id="c-ssh_rtl_shutdown"></a>`ssh_rtl_shutdown()`

```c
void ssh_rtl_shutdown(struct ssh_rtl *rtl)
```

Shut down request transport layer.

**Parameters**

- `struct ssh_rtl *rtl`: The request transport layer.

**Description**

Shuts down the request transport layer, removing and canceling all queued
and pending requests. Requests canceled by this operation will be completed
with `-ESHUTDOWN` as status. Receiver and transmitter threads will be
stopped, the lower-level packet layer will be shutdown.

As a result of this function, the transport layer will be marked as shut
down. Submission of requests after the transport layer has been shut down
will fail with `-ESHUTDOWN`.


<a id="rst-controller"></a>

## Controller


#### <a id="c-struct-ssh_seq_counter"></a>`struct ssh_seq_counter`

Safe counter for SSH sequence IDs.

**Definition**

```c
struct ssh_seq_counter {
    u8 value;
};
```

**Members**

- `value`: The current counter value.

#### <a id="c-struct-ssh_rqid_counter"></a>`struct ssh_rqid_counter`

Safe counter for SSH request IDs.

**Definition**

```c
struct ssh_rqid_counter {
    u16 value;
};
```

**Members**

- `value`: The current counter value.

#### <a id="c-struct-ssam_nf_head"></a>`struct ssam_nf_head`

Notifier head for SSAM events.

**Definition**

```c
struct ssam_nf_head {
    struct srcu_struct srcu;
    struct list_head head;
};
```

**Members**

- `srcu`: The SRCU struct for synchronization.
- `head`: List-head for notifier blocks registered under this head.

#### <a id="c-struct-ssam_nf"></a>`struct ssam_nf`

Notifier callback- and activation-registry for SSAM events.

**Definition**

```c
struct ssam_nf {
    struct mutex lock;
    struct rb_root refcount;
    struct ssam_nf_head head[SSH_NUM_EVENTS];
};
```

**Members**

- `lock`: Lock guarding (de-)registration of notifier blocks. Note: This
  lock does not need to be held for notifier calls, only
  registration and deregistration.
- `refcount`: The root of the RB-tree used for reference-counting enabled
  events/notifications.
- `head`: The list of notifier heads for event/notification callbacks.

#### <a id="c-struct-ssam_event_item"></a>`struct ssam_event_item`

Struct for event queuing and completion.

**Definition**

```c
struct ssam_event_item {
    struct list_head node;
    u16 rqid;
    struct {
        void (*free)(struct ssam_event_item *event);
    } ops;
    struct ssam_event event;
};
```

**Members**

- `node`: The node in the queue.
- `rqid`: The request ID of the event.
- `ops`: Instance specific functions.
- `ops.free`: Callback for freeing this event item.
- `event`: Actual event data.

#### <a id="c-struct-ssam_event_queue"></a>`struct ssam_event_queue`

Queue for completing received events.

**Definition**

```c
struct ssam_event_queue {
    struct ssam_cplt *cplt;
    spinlock_t lock;
    struct list_head head;
    struct work_struct work;
};
```

**Members**

- `cplt`: Reference to the completion system on which this queue is active.
- `lock`: The lock for any operation on the queue.
- `head`: The list-head of the queue.
- `work`: The `struct work_struct` performing completion work for this queue.

#### <a id="c-struct-ssam_event_target"></a>`struct ssam_event_target`

Set of queues for a single SSH target ID.

**Definition**

```c
struct ssam_event_target {
    struct ssam_event_queue queue[SSH_NUM_EVENTS];
};
```

**Members**

- `queue`: The array of queues, one queue per event ID.

#### <a id="c-struct-ssam_cplt"></a>`struct ssam_cplt`

SSAM event/async request completion system.

**Definition**

```c
struct ssam_cplt {
    struct device *dev;
    struct workqueue_struct *wq;
    struct {
        struct ssam_event_target target[SSH_NUM_TARGETS];
        struct ssam_nf notif;
    } event;
};
```

**Members**

- `dev`: The device with which this system is associated. Only used
  for logging.
- `wq`: The `struct workqueue_struct` on which all completion work
  items are queued.
- `event`: Event completion management.
- `event.target`: Array of [`struct ssam_event_target`](#c-struct-ssam_event_target), one for each target.
- `event.notif`: Notifier callbacks and event activation reference counting.

#### <a id="c-enum-ssam_controller_state"></a>`enum ssam_controller_state`

State values for [`struct ssam_controller`](#c-struct-ssam_controller).

**Constants**

- `SSAM_CONTROLLER_UNINITIALIZED`: The controller has not been initialized yet or has been deinitialized.
- `SSAM_CONTROLLER_INITIALIZED`: The controller is initialized, but has not been started yet.
- `SSAM_CONTROLLER_STARTED`: The controller has been started and is ready to use.
- `SSAM_CONTROLLER_STOPPED`: The controller has been stopped.
- `SSAM_CONTROLLER_SUSPENDED`: The controller has been suspended.

#### <a id="c-struct-ssam_controller_caps"></a>`struct ssam_controller_caps`

Controller device capabilities.

**Definition**

```c
struct ssam_controller_caps {
    u32 ssh_power_profile;
    u32 ssh_buffer_size;
    u32 screen_on_sleep_idle_timeout;
    u32 screen_off_sleep_idle_timeout;
    u32 d3_closes_handle:1;
};
```

**Members**

- `ssh_power_profile`: SSH power profile.
- `ssh_buffer_size`: SSH driver UART buffer size.
- `screen_on_sleep_idle_timeout`: SAM UART screen-on sleep idle timeout.
- `screen_off_sleep_idle_timeout`: SAM UART screen-off sleep idle timeout.
- `d3_closes_handle`: SAM closes UART handle in D3.

**Description**

Controller and SSH device capabilities found in ACPI.

#### <a id="c-struct-ssam_controller"></a>`struct ssam_controller`

SSAM controller device.

**Definition**

```c
struct ssam_controller {
    struct kref kref;
    struct rw_semaphore lock;
    enum ssam_controller_state state;
    struct ssh_rtl rtl;
    struct ssam_cplt cplt;
    struct {
        struct ssh_seq_counter seq;
        struct ssh_rqid_counter rqid;
    } counter;
    struct {
        int num;
        bool wakeup_enabled;
    } irq;
    struct ssam_controller_caps caps;
};
```

**Members**

- `kref`: Reference count of the controller.
- `lock`: Main lock for the controller, used to guard state changes.
- `state`: Controller state.
- `rtl`: Request transport layer for SSH I/O.
- `cplt`: Completion system for SSH/SSAM events and asynchronous requests.
- `counter`: Safe SSH message ID counters.
- `counter.seq`: Sequence ID counter.
- `counter.rqid`: Request ID counter.
- `irq`: Wakeup IRQ resources.
- `irq.num`: The wakeup IRQ number.
- `irq.wakeup_enabled`: Whether wakeup by IRQ is enabled during suspend.
- `caps`: The controller device capabilities.

#### <a id="c-ssam_controller_receive_buf"></a>`ssam_controller_receive_buf()`

```c
ssize_t ssam_controller_receive_buf(struct ssam_controller *ctrl, const u8 *buf, size_t n)
```

Provide input-data to the controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.
- `const u8 *buf`: The input buffer.
- `size_t n`: The number of bytes in the input buffer.

**Description**

Provide input data to be evaluated by the controller, which has been
received via the lower-level transport.

**Return**

Returns the number of bytes consumed, or, if the packet transport
layer of the controller has been shut down, `-ESHUTDOWN`.

#### <a id="c-ssam_controller_write_wakeup"></a>`ssam_controller_write_wakeup()`

```c
void ssam_controller_write_wakeup(struct ssam_controller *ctrl)
```

Notify the controller that the underlying device has space available for data to be written.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.



#### <a id="c-ssh_seq_reset"></a>`ssh_seq_reset()`

```c
void ssh_seq_reset(struct ssh_seq_counter *c)
```

Reset/initialize sequence ID counter.

**Parameters**

- `struct ssh_seq_counter *c`: The counter to reset.

#### <a id="c-ssh_seq_next"></a>`ssh_seq_next()`

```c
u8 ssh_seq_next(struct ssh_seq_counter *c)
```

Get next sequence ID.

**Parameters**

- `struct ssh_seq_counter *c`: The counter providing the sequence IDs.

**Return**

Returns the next sequence ID of the counter.

#### <a id="c-ssh_rqid_reset"></a>`ssh_rqid_reset()`

```c
void ssh_rqid_reset(struct ssh_rqid_counter *c)
```

Reset/initialize request ID counter.

**Parameters**

- `struct ssh_rqid_counter *c`: The counter to reset.

#### <a id="c-ssh_rqid_next"></a>`ssh_rqid_next()`

```c
u16 ssh_rqid_next(struct ssh_rqid_counter *c)
```

Get next request ID.

**Parameters**

- `struct ssh_rqid_counter *c`: The counter providing the request IDs.

**Return**

Returns the next request ID of the counter, skipping any reserved
request IDs.

#### <a id="c-ssam_event_matches_notifier"></a>`ssam_event_matches_notifier()`

```c
bool ssam_event_matches_notifier(const struct ssam_event_notifier *n, const struct ssam_event *event)
```

Test if an event matches a notifier.

**Parameters**

- `const struct ssam_event_notifier *n`: The event notifier to test against.
- `const struct ssam_event *event`: The event to test.

**Return**

Returns `true` if the given event matches the given notifier
according to the rules set in the notifier's event mask, `false` otherwise.

#### <a id="c-ssam_nfblk_call_chain"></a>`ssam_nfblk_call_chain()`

```c
int ssam_nfblk_call_chain(struct ssam_nf_head *nh, struct ssam_event *event)
```

Call event notifier callbacks of the given chain.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head for which the notifier callbacks should be called.
- `struct ssam_event *event`: The event data provided to the callbacks.

**Description**

Call all registered notifier callbacks in order of their priority until
either no notifier is left or a notifier returns a value with the
`SSAM_NOTIF_STOP` bit set. Note that this bit is automatically set via
[`ssam_notifier_from_errno()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssam_notifier_from_errno) on any non-zero error value.

**Return**

Returns the notifier status value, which contains the notifier
status bits (`SSAM_NOTIF_HANDLED` and `SSAM_NOTIF_STOP`) as well as a
potential error value returned from the last executed notifier callback.
Use [`ssam_notifier_to_errno()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssam_notifier_to_errno) to convert this value to the original error
value.

#### <a id="c-ssam_nfblk_insert"></a>`ssam_nfblk_insert()`

```c
int ssam_nfblk_insert(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
```

Insert a new notifier block into the given notifier list.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head into which the block should be inserted.
- `struct ssam_notifier_block *nb`: The notifier block to add.

**Note**

This function must be synchronized by the caller with respect to other
insert, find, and/or remove calls by holding `struct ssam_nf.lock`.

**Return**

Returns zero on success, `-EEXIST` if the notifier block has already
been registered.

#### <a id="c-ssam_nfblk_find"></a>`ssam_nfblk_find()`

```c
bool ssam_nfblk_find(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
```

Check if a notifier block is registered on the given notifier head. list.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head on which to search.
- `struct ssam_notifier_block *nb`: The notifier block to search for.

**Note**

This function must be synchronized by the caller with respect to other
insert, find, and/or remove calls by holding `struct ssam_nf.lock`.

**Return**

Returns true if the given notifier block is registered on the given
notifier head, false otherwise.

#### <a id="c-ssam_nfblk_remove"></a>`ssam_nfblk_remove()`

```c
void ssam_nfblk_remove(struct ssam_notifier_block *nb)
```

Remove a notifier block from its notifier list.

**Parameters**

- `struct ssam_notifier_block *nb`: The notifier block to be removed.

**Note**

This function must be synchronized by the caller with respect to
other insert, find, and/or remove calls by holding `struct ssam_nf.lock`.
Furthermore, the caller _must_ ensure SRCU synchronization by calling
[`synchronize_srcu()`](/kernel/internals/core-api/kernel-api.md#c-synchronize_srcu) with `nh->srcu` after leaving the critical section, to
ensure that the removed notifier block is not in use any more.

#### <a id="c-ssam_nf_head_init"></a>`ssam_nf_head_init()`

```c
int ssam_nf_head_init(struct ssam_nf_head *nh)
```

Initialize the given notifier head.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head to initialize.

#### <a id="c-ssam_nf_head_destroy"></a>`ssam_nf_head_destroy()`

```c
void ssam_nf_head_destroy(struct ssam_nf_head *nh)
```

Deinitialize the given notifier head.

**Parameters**

- `struct ssam_nf_head *nh`: The notifier head to deinitialize.

#### <a id="c-struct-ssam_nf_refcount_key"></a>`struct ssam_nf_refcount_key`

Key used for event activation reference counting.

**Definition**

```c
struct ssam_nf_refcount_key {
    struct ssam_event_registry reg;
    struct ssam_event_id id;
};
```

**Members**

- `reg`: The registry via which the event is enabled/disabled.
- `id`: The ID uniquely describing the event.

#### <a id="c-struct-ssam_nf_refcount_entry"></a>`struct ssam_nf_refcount_entry`

RB-tree entry for reference counting event activations.

**Definition**

```c
struct ssam_nf_refcount_entry {
    struct rb_node node;
    struct ssam_nf_refcount_key key;
    int refcount;
    u8 flags;
};
```

**Members**

- `node`: The node of this entry in the rb-tree.
- `key`: The key of the event.
- `refcount`: The reference-count of the event.
- `flags`: The flags used when enabling the event.

#### <a id="c-ssam_nf_refcount_inc"></a>`ssam_nf_refcount_inc()`

```c
struct ssam_nf_refcount_entry * ssam_nf_refcount_inc(struct ssam_nf *nf, struct ssam_event_registry reg, struct ssam_event_id id)
```

Increment reference-/activation-count of the given event.

**Parameters**

- `struct ssam_nf *nf`: The notifier system reference.
- `struct ssam_event_registry reg`: The registry used to enable/disable the event.
- `struct ssam_event_id id`: The event ID.

**Description**

Increments the reference-/activation-count associated with the specified
event type/ID, allocating a new entry for this event ID if necessary. A
newly allocated entry will have a refcount of one.

**Note**

`nf->lock` must be held when calling this function.

**Return**

Returns the refcount entry on success. Returns an error pointer
with `-ENOSPC` if there have already been `INT_MAX` events of the specified
ID and type registered, or `-ENOMEM` if the entry could not be allocated.

#### <a id="c-ssam_nf_refcount_dec"></a>`ssam_nf_refcount_dec()`

```c
struct ssam_nf_refcount_entry * ssam_nf_refcount_dec(struct ssam_nf *nf, struct ssam_event_registry reg, struct ssam_event_id id)
```

Decrement reference-/activation-count of the given event.

**Parameters**

- `struct ssam_nf *nf`: The notifier system reference.
- `struct ssam_event_registry reg`: The registry used to enable/disable the event.
- `struct ssam_event_id id`: The event ID.

**Description**

Decrements the reference-/activation-count of the specified event,
returning its entry. If the returned entry has a refcount of zero, the
caller is responsible for freeing it using [`kfree()`](/kernel/internals/core-api/mm-api.md#c-kfree).

**Note**

`nf->lock` must be held when calling this function.

**Return**

Returns the refcount entry on success or `NULL` if the entry has not
been found.

#### <a id="c-ssam_nf_refcount_dec_free"></a>`ssam_nf_refcount_dec_free()`

```c
void ssam_nf_refcount_dec_free(struct ssam_nf *nf, struct ssam_event_registry reg, struct ssam_event_id id)
```

Decrement reference-/activation-count of the given event and free its entry if the reference count reaches zero.

**Parameters**

- `struct ssam_nf *nf`: The notifier system reference.
- `struct ssam_event_registry reg`: The registry used to enable/disable the event.
- `struct ssam_event_id id`: The event ID.

**Description**

Decrements the reference-/activation-count of the specified event, freeing
its entry if it reaches zero.

**Note**

`nf->lock` must be held when calling this function.

#### <a id="c-ssam_nf_refcount_empty"></a>`ssam_nf_refcount_empty()`

```c
bool ssam_nf_refcount_empty(struct ssam_nf *nf)
```

Test if the notification system has any enabled/active events.

**Parameters**

- `struct ssam_nf *nf`: The notification system.

#### <a id="c-ssam_nf_call"></a>`ssam_nf_call()`

```c
void ssam_nf_call(struct ssam_nf *nf, struct device *dev, u16 rqid, struct ssam_event *event)
```

Call notification callbacks for the provided event.

**Parameters**

- `struct ssam_nf *nf`: The notifier system
- `struct device *dev`: The associated device, only used for logging.
- `u16 rqid`: The request ID of the event.
- `struct ssam_event *event`: The event provided to the callbacks.

**Description**

Execute registered callbacks in order of their priority until either no
callback is left or a callback returns a value with the `SSAM_NOTIF_STOP`
bit set. Note that this bit is set automatically when converting non-zero
error values via [`ssam_notifier_from_errno()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssam_notifier_from_errno) to notifier values.

Also note that any callback that could handle an event should return a value
with bit `SSAM_NOTIF_HANDLED` set, indicating that the event does not go
unhandled/ignored. In case no registered callback could handle an event,
this function will emit a warning.

In case a callback failed, this function will emit an error message.

#### <a id="c-ssam_nf_init"></a>`ssam_nf_init()`

```c
int ssam_nf_init(struct ssam_nf *nf)
```

Initialize the notifier system.

**Parameters**

- `struct ssam_nf *nf`: The notifier system to initialize.

#### <a id="c-ssam_nf_destroy"></a>`ssam_nf_destroy()`

```c
void ssam_nf_destroy(struct ssam_nf *nf)
```

Deinitialize the notifier system.

**Parameters**

- `struct ssam_nf *nf`: The notifier system to deinitialize.

#### <a id="c-ssam_event_item_cache_init"></a>`ssam_event_item_cache_init()`

```c
int ssam_event_item_cache_init(void)
```

Initialize the event item cache.

**Parameters**

- `void`: no arguments

#### <a id="c-ssam_event_item_cache_destroy"></a>`ssam_event_item_cache_destroy()`

```c
void ssam_event_item_cache_destroy(void)
```

Deinitialize the event item cache.

**Parameters**

- `void`: no arguments

#### <a id="c-ssam_event_item_free"></a>`ssam_event_item_free()`

```c
void ssam_event_item_free(struct ssam_event_item *item)
```

Free the provided event item.

**Parameters**

- `struct ssam_event_item *item`: The event item to free.

#### <a id="c-ssam_event_item_alloc"></a>`ssam_event_item_alloc()`

```c
struct ssam_event_item * ssam_event_item_alloc(size_t len, gfp_t flags)
```

Allocate an event item with the given payload size.

**Parameters**

- `size_t len`: The event payload length.
- `gfp_t flags`: The flags used for allocation.

**Description**

Allocate an event item with the given payload size, preferring allocation
from the event item cache if the payload is small enough (i.e. smaller than
`SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN`). Sets the item operations and payload
length values. The item free callback (`ops.free`) should not be
overwritten after this call.

**Return**

Returns the newly allocated event item.

#### <a id="c-ssam_event_queue_push"></a>`ssam_event_queue_push()`

```c
void ssam_event_queue_push(struct ssam_event_queue *q, struct ssam_event_item *item)
```

Push an event item to the event queue.

**Parameters**

- `struct ssam_event_queue *q`: The event queue.
- `struct ssam_event_item *item`: The item to add.

#### <a id="c-ssam_event_queue_pop"></a>`ssam_event_queue_pop()`

```c
struct ssam_event_item * ssam_event_queue_pop(struct ssam_event_queue *q)
```

Pop the next event item from the event queue.

**Parameters**

- `struct ssam_event_queue *q`: The event queue.

**Description**

Returns and removes the next event item from the queue. Returns `NULL` If
there is no event item left.

#### <a id="c-ssam_event_queue_is_empty"></a>`ssam_event_queue_is_empty()`

```c
bool ssam_event_queue_is_empty(struct ssam_event_queue *q)
```

Check if the event queue is empty.

**Parameters**

- `struct ssam_event_queue *q`: The event queue.

#### <a id="c-ssam_cplt_get_event_queue"></a>`ssam_cplt_get_event_queue()`

```c
struct ssam_event_queue * ssam_cplt_get_event_queue(struct ssam_cplt *cplt, u8 tid, u16 rqid)
```

Get the event queue for the given parameters.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system on which to look for the queue.
- `u8 tid`: The target ID of the queue.
- `u16 rqid`: The request ID representing the event ID for which to get the queue.

**Return**

Returns the event queue corresponding to the event type described
by the given parameters. If the request ID does not represent an event,
this function returns `NULL`. If the target ID is not supported, this
function will fall back to the default target ID (`tid = 1`).

#### <a id="c-ssam_cplt_submit"></a>`ssam_cplt_submit()`

```c
bool ssam_cplt_submit(struct ssam_cplt *cplt, struct work_struct *work)
```

Submit a work item to the completion system workqueue.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system.
- `struct work_struct *work`: The work item to submit.

#### <a id="c-ssam_cplt_submit_event"></a>`ssam_cplt_submit_event()`

```c
int ssam_cplt_submit_event(struct ssam_cplt *cplt, struct ssam_event_item *item)
```

Submit an event to the completion system.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system.
- `struct ssam_event_item *item`: The event item to submit.

**Description**

Submits the event to the completion system by queuing it on the event item
queue and queuing the respective event queue work item on the completion
workqueue, which will eventually complete the event.

**Return**

Returns zero on success, `-EINVAL` if there is no event queue that
can handle the given event item.

#### <a id="c-ssam_cplt_flush"></a>`ssam_cplt_flush()`

```c
void ssam_cplt_flush(struct ssam_cplt *cplt)
```

Flush the completion system.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system.

**Description**

Flush the completion system by waiting until all currently submitted work
items have been completed.

**Note**

This function does not guarantee that all events will have been
handled once this call terminates. In case of a larger number of
to-be-completed events, the event queue work function may re-schedule its
work item, which this flush operation will ignore.

This operation is only intended to, during normal operation prior to
shutdown, try to complete most events and requests to get them out of the
system while the system is still fully operational. It does not aim to
provide any guarantee that all of them have been handled.

#### <a id="c-ssam_event_queue_init"></a>`ssam_event_queue_init()`

```c
void ssam_event_queue_init(struct ssam_cplt *cplt, struct ssam_event_queue *evq)
```

Initialize an event queue.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system on which the queue resides.
- `struct ssam_event_queue *evq`: The event queue to initialize.

#### <a id="c-ssam_cplt_init"></a>`ssam_cplt_init()`

```c
int ssam_cplt_init(struct ssam_cplt *cplt, struct device *dev)
```

Initialize completion system.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system to initialize.
- `struct device *dev`: The device used for logging.

#### <a id="c-ssam_cplt_destroy"></a>`ssam_cplt_destroy()`

```c
void ssam_cplt_destroy(struct ssam_cplt *cplt)
```

Deinitialize the completion system.

**Parameters**

- `struct ssam_cplt *cplt`: The completion system to deinitialize.

**Description**

Deinitialize the given completion system and ensure that all pending, i.e.
yet-to-be-completed, event items and requests have been handled.

#### <a id="c-ssam_controller_lock"></a>`ssam_controller_lock()`

```c
void ssam_controller_lock(struct ssam_controller *c)
```

Acquire the main controller lock.

**Parameters**

- `struct ssam_controller *c`: The controller to lock.

**Description**

This lock must be held for any state transitions, including transition to
suspend/resumed states and during shutdown. See [`ssam_controller_statelock()`](/kernel/hardware/driver-api/surface-aggregator/client-api.md#c-ssam_controller_statelock)
for more details on controller locking.

See `ssam_controller_unlock()` for the corresponding unlock function.

#### <a id="c-ssam_controller_caps_load_from_acpi"></a>`ssam_controller_caps_load_from_acpi()`

```c
int ssam_controller_caps_load_from_acpi(acpi_handle handle, struct ssam_controller_caps *caps)
```

Load controller capabilities from ACPI _DSM.

**Parameters**

- `acpi_handle handle`: The handle of the ACPI controller/SSH device.
- `struct ssam_controller_caps *caps`: Where to store the capabilities in.

**Description**

Initializes the given controller capabilities with default values, then
checks and, if the respective _DSM functions are available, loads the
actual capabilities from the _DSM.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssam_controller_caps_load_from_of"></a>`ssam_controller_caps_load_from_of()`

```c
int ssam_controller_caps_load_from_of(struct device *dev, struct ssam_controller_caps *caps)
```

Load controller capabilities from OF/DT.

**Parameters**

- `struct device *dev`: A pointer to the controller device
- `struct ssam_controller_caps *caps`: Where to store the capabilities in.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssam_controller_caps_load"></a>`ssam_controller_caps_load()`

```c
int ssam_controller_caps_load(struct device *dev, struct ssam_controller_caps *caps)
```

Load controller capabilities

**Parameters**

- `struct device *dev`: A pointer to the controller device
- `struct ssam_controller_caps *caps`: Where to store the capabilities in.

**Return**

Returns zero on success, a negative error code on failure.

#### <a id="c-ssam_controller_init"></a>`ssam_controller_init()`

```c
int ssam_controller_init(struct ssam_controller *ctrl, struct serdev_device *serdev)
```

Initialize SSAM controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to initialize.
- `struct serdev_device *serdev`: The serial device representing the underlying data transport.

**Description**

Initializes the given controller. Does neither start receiver nor
transmitter threads. After this call, the controller has to be hooked up to
the serdev core separately via `struct serdev_device_ops`, relaying calls to
[`ssam_controller_receive_buf()`](#c-ssam_controller_receive_buf) and [`ssam_controller_write_wakeup()`](#c-ssam_controller_write_wakeup). Once the
controller has been hooked up, transmitter and receiver threads may be
started via [`ssam_controller_start()`](#c-ssam_controller_start). These setup steps need to be completed
before controller can be used for requests.

#### <a id="c-ssam_controller_start"></a>`ssam_controller_start()`

```c
int ssam_controller_start(struct ssam_controller *ctrl)
```

Start the receiver and transmitter threads of the controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Note**

When this function is called, the controller should be properly
hooked up to the serdev core via `struct serdev_device_ops`. Please refer
to [`ssam_controller_init()`](#c-ssam_controller_init) for more details on controller initialization.

This function must be called with the main controller lock held (i.e. by
calling [`ssam_controller_lock()`](#c-ssam_controller_lock)).

#### <a id="c-ssam_controller_shutdown"></a>`ssam_controller_shutdown()`

```c
void ssam_controller_shutdown(struct ssam_controller *ctrl)
```

Shut down the controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Description**

Shuts down the controller by flushing all pending requests and stopping the
transmitter and receiver threads. All requests submitted after this call
will fail with `-ESHUTDOWN`. While it is discouraged to do so, this function
is safe to use in parallel with ongoing request submission.

In the course of this shutdown procedure, all currently registered
notifiers will be unregistered. It is, however, strongly recommended to not
rely on this behavior, and instead the party registering the notifier
should unregister it before the controller gets shut down, e.g. via the
SSAM bus which guarantees client devices to be removed before a shutdown.

Note that events may still be pending after this call, but, due to the
notifiers being unregistered, these events will be dropped when the
controller is subsequently destroyed via [`ssam_controller_destroy()`](#c-ssam_controller_destroy).

This function must be called with the main controller lock held (i.e. by
calling [`ssam_controller_lock()`](#c-ssam_controller_lock)).

#### <a id="c-ssam_controller_destroy"></a>`ssam_controller_destroy()`

```c
void ssam_controller_destroy(struct ssam_controller *ctrl)
```

Destroy the controller and free its resources.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Description**

Ensures that all resources associated with the controller get freed. This
function should only be called after the controller has been stopped via
[`ssam_controller_shutdown()`](#c-ssam_controller_shutdown). In general, this function should not be called
directly. The only valid place to call this function directly is during
initialization, before the controller has been fully initialized and passed
to other processes. This function is called automatically when the
reference count of the controller reaches zero.

This function must be called with the main controller lock held (i.e. by
calling [`ssam_controller_lock()`](#c-ssam_controller_lock)).

#### <a id="c-ssam_controller_suspend"></a>`ssam_controller_suspend()`

```c
int ssam_controller_suspend(struct ssam_controller *ctrl)
```

Suspend the controller.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to suspend.

**Description**

Marks the controller as suspended. Note that display-off and D0-exit
notifications have to be sent manually before transitioning the controller
into the suspended state via this function.

See [`ssam_controller_resume()`](#c-ssam_controller_resume) for the corresponding resume function.

**Return**

Returns `-EINVAL` if the controller is currently not in the
"started" state.

#### <a id="c-ssam_controller_resume"></a>`ssam_controller_resume()`

```c
int ssam_controller_resume(struct ssam_controller *ctrl)
```

Resume the controller from suspend.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to resume.

**Description**

Resume the controller from the suspended state it was put into via
[`ssam_controller_suspend()`](#c-ssam_controller_suspend). This function does not issue display-on and
D0-entry notifications. If required, those have to be sent manually after
this call.

**Return**

Returns `-EINVAL` if the controller is currently not suspended.

#### <a id="c-struct-ssh_notification_params"></a>`struct ssh_notification_params`

Command payload to enable/disable SSH notifications.

**Definition**

```c
struct ssh_notification_params {
    u8 target_category;
    u8 flags;
    __le16 request_id;
    u8 instance_id;
};
```

**Members**

- `target_category`: The target category for which notifications should be
  enabled/disabled.
- `flags`: Flags determining how notifications are being sent.
- `request_id`: The request ID that is used to send these notifications.
- `instance_id`: The specific instance in the given target category for
  which notifications should be enabled.

#### <a id="c-ssam_ssh_event_enable"></a>`ssam_ssh_event_enable()`

```c
int ssam_ssh_event_enable(struct ssam_controller *ctrl, struct ssam_event_registry reg, struct ssam_event_id id, u8 flags)
```

Enable SSH event.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which to enable the event.
- `struct ssam_event_registry reg`: The event registry describing what request to use for enabling and
  disabling the event.
- `struct ssam_event_id id`: The event identifier.
- `u8 flags`: The event flags.

**Description**

Enables the specified event on the EC. This function does not manage
reference counting of enabled events and is basically only a wrapper for
the raw EC request. If the specified event is already enabled, the EC will
ignore this request.

**Return**

Returns the status of the executed SAM request (zero on success and
negative on direct failure) or `-EPROTO` if the request response indicates a
failure.

#### <a id="c-ssam_ssh_event_disable"></a>`ssam_ssh_event_disable()`

```c
int ssam_ssh_event_disable(struct ssam_controller *ctrl, struct ssam_event_registry reg, struct ssam_event_id id, u8 flags)
```

Disable SSH event.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which to disable the event.
- `struct ssam_event_registry reg`: The event registry describing what request to use for enabling and
  disabling the event (must be same as used when enabling the event).
- `struct ssam_event_id id`: The event identifier.
- `u8 flags`: The event flags (likely ignored for disabling of events).

**Description**

Disables the specified event on the EC. This function does not manage
reference counting of enabled events and is basically only a wrapper for
the raw EC request. If the specified event is already disabled, the EC will
ignore this request.

**Return**

Returns the status of the executed SAM request (zero on success and
negative on direct failure) or `-EPROTO` if the request response indicates a
failure.

#### <a id="c-ssam_get_firmware_version"></a>`ssam_get_firmware_version()`

```c
int ssam_get_firmware_version(struct ssam_controller *ctrl, u32 *version)
```

Get the SAM/EC firmware version.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.
- `u32 *version`: Where to store the version number.

**Return**

Returns zero on success or the status of the executed SAM request
if that request failed.

#### <a id="c-ssam_ctrl_notif_display_off"></a>`ssam_ctrl_notif_display_off()`

```c
int ssam_ctrl_notif_display_off(struct ssam_controller *ctrl)
```

Notify EC that the display has been turned off.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Description**

Notify the EC that the display has been turned off and the driver may enter
a lower-power state. This will prevent events from being sent directly.
Rather, the EC signals an event by pulling the wakeup GPIO high for as long
as there are pending events. The events then need to be manually released,
one by one, via the GPIO callback request. All pending events accumulated
during this state can also be released by issuing the display-on
notification, e.g. via [`ssam_ctrl_notif_display_on()`](#c-ssam_ctrl_notif_display_on), which will also reset
the GPIO.

On some devices, specifically ones with an integrated keyboard, the keyboard
backlight will be turned off by this call.

This function will only send the display-off notification command if
display notifications are supported by the EC. Currently all known devices
support these notifications.

Use [`ssam_ctrl_notif_display_on()`](#c-ssam_ctrl_notif_display_on) to reverse the effects of this function.

**Return**

Returns zero on success or if no request has been executed, the
status of the executed SAM request if that request failed, or `-EPROTO` if
an unexpected response has been received.

#### <a id="c-ssam_ctrl_notif_display_on"></a>`ssam_ctrl_notif_display_on()`

```c
int ssam_ctrl_notif_display_on(struct ssam_controller *ctrl)
```

Notify EC that the display has been turned on.

**Parameters**

- `struct ssam_controller *ctrl`: The controller.

**Description**

Notify the EC that the display has been turned back on and the driver has
exited its lower-power state. This notification is the counterpart to the
display-off notification sent via [`ssam_ctrl_notif_display_off()`](#c-ssam_ctrl_notif_display_off) and will
reverse its effects, including resetting events to their default behavior.

This function will only send the display-on notification command if display
notifications are supported by the EC. Currently all known devices support
these notifications.

See [`ssam_ctrl_notif_display_off()`](#c-ssam_ctrl_notif_display_off) for more details.

**Return**

Returns zero on success or if no request has been executed, the
status of the executed SAM request if that request failed, or `-EPROTO` if
an unexpected response has been received.

#### <a id="c-ssam_ctrl_notif_d0_exit"></a>`ssam_ctrl_notif_d0_exit()`

```c
int ssam_ctrl_notif_d0_exit(struct ssam_controller *ctrl)
```

Notify EC that the driver/device exits the D0 power state.

**Parameters**

- `struct ssam_controller *ctrl`: The controller

**Description**

Notifies the EC that the driver prepares to exit the D0 power state in
favor of a lower-power state. Exact effects of this function related to the
EC are currently unknown.

This function will only send the D0-exit notification command if D0-state
notifications are supported by the EC. Only newer Surface generations
support these notifications.

Use [`ssam_ctrl_notif_d0_entry()`](#c-ssam_ctrl_notif_d0_entry) to reverse the effects of this function.

**Return**

Returns zero on success or if no request has been executed, the
status of the executed SAM request if that request failed, or `-EPROTO` if
an unexpected response has been received.

#### <a id="c-ssam_ctrl_notif_d0_entry"></a>`ssam_ctrl_notif_d0_entry()`

```c
int ssam_ctrl_notif_d0_entry(struct ssam_controller *ctrl)
```

Notify EC that the driver/device enters the D0 power state.

**Parameters**

- `struct ssam_controller *ctrl`: The controller

**Description**

Notifies the EC that the driver has exited a lower-power state and entered
the D0 power state. Exact effects of this function related to the EC are
currently unknown.

This function will only send the D0-entry notification command if D0-state
notifications are supported by the EC. Only newer Surface generations
support these notifications.

See [`ssam_ctrl_notif_d0_exit()`](#c-ssam_ctrl_notif_d0_exit) for more details.

**Return**

Returns zero on success or if no request has been executed, the
status of the executed SAM request if that request failed, or `-EPROTO` if
an unexpected response has been received.

#### <a id="c-ssam_nf_refcount_enable"></a>`ssam_nf_refcount_enable()`

```c
int ssam_nf_refcount_enable(struct ssam_controller *ctrl, struct ssam_nf_refcount_entry *entry, u8 flags)
```

Enable event for reference count entry if it has not already been enabled.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to enable the event on.
- `struct ssam_nf_refcount_entry *entry`: The reference count entry for the event to be enabled.
- `u8 flags`: The flags used for enabling the event on the EC.

**Description**

Enable the event associated with the given reference count entry if the
reference count equals one, i.e. the event has not previously been enabled.
If the event has already been enabled (i.e. reference count not equal to
one), check that the flags used for enabling match and warn about this if
they do not.

This does not modify the reference count itself, which is done with
[`ssam_nf_refcount_inc()`](#c-ssam_nf_refcount_inc) / [`ssam_nf_refcount_dec()`](#c-ssam_nf_refcount_dec).

**Note**

`nf->lock` must be held when calling this function.

**Return**

Returns zero on success. If the event is enabled by this call,
returns the status of the event-enable EC command.

#### <a id="c-ssam_nf_refcount_disable_free"></a>`ssam_nf_refcount_disable_free()`

```c
int ssam_nf_refcount_disable_free(struct ssam_controller *ctrl, struct ssam_nf_refcount_entry *entry, u8 flags, bool ec)
```

Disable event for reference count entry if it is no longer in use and free the corresponding entry.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to disable the event on.
- `struct ssam_nf_refcount_entry *entry`: The reference count entry for the event to be disabled.
- `u8 flags`: The flags used for enabling the event on the EC.
- `bool ec`: Flag specifying if the event should actually be disabled on the EC.

**Description**

If `ec` equals `true` and the reference count equals zero (i.e. the
event is no longer requested by any client), the specified event will be
disabled on the EC via the corresponding request.

If `ec` equals `false`, no request will be sent to the EC and the event
can be considered in a detached state (i.e. no longer used but still
enabled). Disabling an event via this method may be required for
hot-removable devices, where event disable requests may time out after the
device has been physically removed.

In both cases, if the reference count equals zero, the corresponding
reference count entry will be freed. The reference count entry must not be
used any more after a call to this function.

Also checks if the flags used for disabling the event match the flags used
for enabling the event and warns if they do not (regardless of reference
count).

This does not modify the reference count itself, which is done with
[`ssam_nf_refcount_inc()`](#c-ssam_nf_refcount_inc) / [`ssam_nf_refcount_dec()`](#c-ssam_nf_refcount_dec).

**Note**

`nf->lock` must be held when calling this function.

**Return**

Returns zero on success. If the event is disabled by this call,
returns the status of the event-enable EC command.

#### <a id="c-ssam_notifier_disable_registered"></a>`ssam_notifier_disable_registered()`

```c
int ssam_notifier_disable_registered(struct ssam_controller *ctrl)
```

Disable events for all registered notifiers.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which to disable the notifiers/events.

**Description**

Disables events for all currently registered notifiers. In case of an error
(EC command failing), all previously disabled events will be restored and
the error code returned.

This function is intended to disable all events prior to hibernation entry.
See [`ssam_notifier_restore_registered()`](#c-ssam_notifier_restore_registered) to restore/re-enable all events
disabled with this function.

Note that this function will not disable events for notifiers registered
after calling this function. It should thus be made sure that no new
notifiers are going to be added after this call and before the corresponding
call to [`ssam_notifier_restore_registered()`](#c-ssam_notifier_restore_registered).

**Return**

Returns zero on success. In case of failure returns the error code
returned by the failed EC command to disable an event.

#### <a id="c-ssam_notifier_restore_registered"></a>`ssam_notifier_restore_registered()`

```c
void ssam_notifier_restore_registered(struct ssam_controller *ctrl)
```

Restore/re-enable events for all registered notifiers.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which to restore the notifiers/events.

**Description**

Restores/re-enables all events for which notifiers have been registered on
the given controller. In case of a failure, the error is logged and the
function continues to try and enable the remaining events.

This function is intended to restore/re-enable all registered events after
hibernation. See [`ssam_notifier_disable_registered()`](#c-ssam_notifier_disable_registered) for the counter part
disabling the events and more details.

#### <a id="c-ssam_notifier_is_empty"></a>`ssam_notifier_is_empty()`

```c
bool ssam_notifier_is_empty(struct ssam_controller *ctrl)
```

Check if there are any registered notifiers.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to check on.

**Return**

Returns `true` if there are currently no notifiers registered on the
controller, `false` otherwise.

#### <a id="c-ssam_notifier_unregister_all"></a>`ssam_notifier_unregister_all()`

```c
void ssam_notifier_unregister_all(struct ssam_controller *ctrl)
```

Unregister all currently registered notifiers.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to unregister the notifiers on.

**Description**

Unregisters all currently registered notifiers. This function is used to
ensure that all notifiers will be unregistered and associated
entries/resources freed when the controller is being shut down.

#### <a id="c-ssam_irq_setup"></a>`ssam_irq_setup()`

```c
int ssam_irq_setup(struct ssam_controller *ctrl)
```

Set up SAM EC wakeup-GPIO interrupt.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which the IRQ should be set up.

**Description**

Set up an IRQ for the wakeup-GPIO pin of the SAM EC. This IRQ can be used
to wake the device from a low power state.

Note that this IRQ can only be triggered while the EC is in the display-off
state. In this state, events are not sent to the host in the usual way.
Instead the wakeup-GPIO gets pulled to "high" as long as there are pending
events and these events need to be released one-by-one via the GPIO
callback request, either until there are no events left and the GPIO is
reset, or all at once by transitioning the EC out of the display-off state,
which will also clear the GPIO.

Not all events, however, should trigger a full system wakeup. Instead the
driver should, if necessary, inspect and forward each event to the
corresponding subsystem, which in turn should decide if the system needs to
be woken up. This logic has not been implemented yet, thus wakeup by this
IRQ should be disabled by default to avoid spurious wake-ups, caused, for
example, by the remaining battery percentage changing. Refer to comments in
this function and comments in the corresponding IRQ handler for more
details on how this should be implemented.

See also [`ssam_ctrl_notif_display_off()`](#c-ssam_ctrl_notif_display_off) and [`ssam_ctrl_notif_display_off()`](#c-ssam_ctrl_notif_display_off)
for functions to transition the EC into and out of the display-off state as
well as more details on it.

The IRQ is disabled by default and has to be enabled before it can wake up
the device from suspend via [`ssam_irq_arm_for_wakeup()`](#c-ssam_irq_arm_for_wakeup). On teardown, the IRQ
should be freed via [`ssam_irq_free()`](#c-ssam_irq_free).

#### <a id="c-ssam_irq_free"></a>`ssam_irq_free()`

```c
void ssam_irq_free(struct ssam_controller *ctrl)
```

Free SAM EC wakeup-GPIO interrupt.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which the IRQ should be freed.

**Description**

Free the wakeup-GPIO IRQ previously set-up via [`ssam_irq_setup()`](#c-ssam_irq_setup).

#### <a id="c-ssam_irq_arm_for_wakeup"></a>`ssam_irq_arm_for_wakeup()`

```c
int ssam_irq_arm_for_wakeup(struct ssam_controller *ctrl)
```

Arm the EC IRQ for wakeup, if enabled.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which the IRQ should be armed.

**Description**

Sets up the IRQ so that it can be used to wake the device. Specifically,
this function enables the irq and then, if the device is allowed to wake up
the system, calls `enable_irq_wake()`. See [`ssam_irq_disarm_wakeup()`](#c-ssam_irq_disarm_wakeup) for the
corresponding function to disable the IRQ.

This function is intended to arm the IRQ before entering S2idle suspend.

**Note**

calls to [`ssam_irq_arm_for_wakeup()`](#c-ssam_irq_arm_for_wakeup) and [`ssam_irq_disarm_wakeup()`](#c-ssam_irq_disarm_wakeup) must
be balanced.

#### <a id="c-ssam_irq_disarm_wakeup"></a>`ssam_irq_disarm_wakeup()`

```c
void ssam_irq_disarm_wakeup(struct ssam_controller *ctrl)
```

Disarm the wakeup IRQ.

**Parameters**

- `struct ssam_controller *ctrl`: The controller for which the IRQ should be disarmed.

**Description**

Disarm the IRQ previously set up for wake via [`ssam_irq_arm_for_wakeup()`](#c-ssam_irq_arm_for_wakeup).

This function is intended to disarm the IRQ after exiting S2idle suspend.

**Note**

calls to [`ssam_irq_arm_for_wakeup()`](#c-ssam_irq_arm_for_wakeup) and [`ssam_irq_disarm_wakeup()`](#c-ssam_irq_disarm_wakeup) must
be balanced.


<a id="rst-client-device-bus"></a>

## Client Device Bus


#### <a id="c-ssam_device_id_compatible"></a>`ssam_device_id_compatible()`

```c
bool ssam_device_id_compatible(const struct ssam_device_id *id, struct ssam_device_uid uid)
```

Check if a device ID matches a UID.

**Parameters**

- `const struct ssam_device_id *id`: The device ID as potential match.
- `struct ssam_device_uid uid`: The device UID matching against.

**Description**

Check if the given ID is a match for the given UID, i.e. if a device with
the provided UID is compatible to the given ID following the match rules
described in its `ssam_device_id.match_flags` member.

**Return**

Returns `true` if the given UID is compatible to the match rule
described by the given ID, `false` otherwise.

#### <a id="c-ssam_device_id_is_null"></a>`ssam_device_id_is_null()`

```c
bool ssam_device_id_is_null(const struct ssam_device_id *id)
```

Check if a device ID is null.

**Parameters**

- `const struct ssam_device_id *id`: The device ID to check.

**Description**

Check if a given device ID is null, i.e. all zeros. Used to check for the
end of `MODULE_DEVICE_TABLE(ssam, ...)` or similar lists.

**Return**

Returns `true` if the given ID represents a null ID, `false`
otherwise.

#### <a id="c-ssam_bus_register"></a>`ssam_bus_register()`

```c
int ssam_bus_register(void)
```

Register and set-up the SSAM client device bus.

**Parameters**

- `void`: no arguments

#### <a id="c-ssam_bus_unregister"></a>`ssam_bus_unregister()`

```c
void ssam_bus_unregister(void)
```

Unregister the SSAM client device bus.

**Parameters**

- `void`: no arguments


<a id="rst-core"></a>

## Core


#### <a id="c-ssam_try_set_controller"></a>`ssam_try_set_controller()`

```c
int ssam_try_set_controller(struct ssam_controller *ctrl)
```

Try to set the main controller reference.

**Parameters**

- `struct ssam_controller *ctrl`: The controller to which the reference should point.

**Description**

Set the main controller reference to the given pointer if the reference
hasn't been set already.

**Return**

Returns zero on success or `-EEXIST` if the reference has already
been set.

#### <a id="c-ssam_clear_controller"></a>`ssam_clear_controller()`

```c
void ssam_clear_controller(void)
```

Remove/clear the main controller reference.

**Parameters**

- `void`: no arguments

**Description**

Clears the main controller reference, i.e. sets it to `NULL`. This function
should be called before the controller is shut down.


<a id="rst-trace-helpers"></a>

## Trace Helpers


#### <a id="c-ssam_trace_ptr_uid"></a>`ssam_trace_ptr_uid()`

```c
void ssam_trace_ptr_uid(const void *ptr, char *uid_str)
```

Convert the pointer to a non-pointer UID string.

**Parameters**

- `const void *ptr`: The pointer to convert.
- `char *uid_str`: A buffer of length SSAM_PTR_UID_LEN where the UID will be stored.

**Description**

Converts the given pointer into a UID string that is safe to be shared
with userspace and logs, i.e. doesn't give away the real memory location.

#### <a id="c-ssam_trace_get_packet_seq"></a>`ssam_trace_get_packet_seq()`

```c
u16 ssam_trace_get_packet_seq(const struct ssh_packet *p)
```

Read the packet's sequence ID.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's sequence ID (SEQ) field if present, or
`SSAM_SEQ_NOT_APPLICABLE` if not (e.g. flush packet).

#### <a id="c-ssam_trace_get_request_id"></a>`ssam_trace_get_request_id()`

```c
u32 ssam_trace_get_request_id(const struct ssh_packet *p)
```

Read the packet's request ID.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's request ID (RQID) field if the packet
represents a request with command data, or `SSAM_RQID_NOT_APPLICABLE` if not
(e.g. flush request, control packet).

#### <a id="c-ssam_trace_get_request_tid"></a>`ssam_trace_get_request_tid()`

```c
u32 ssam_trace_get_request_tid(const struct ssh_packet *p)
```

Read the packet's request target ID.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's request target ID (TID) field if the packet
represents a request with command data, or `SSAM_SSH_TID_NOT_APPLICABLE`
if not (e.g. flush request, control packet).

#### <a id="c-ssam_trace_get_request_sid"></a>`ssam_trace_get_request_sid()`

```c
u32 ssam_trace_get_request_sid(const struct ssh_packet *p)
```

Read the packet's request source ID.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's request source ID (SID) field if the packet
represents a request with command data, or `SSAM_SSH_TID_NOT_APPLICABLE`
if not (e.g. flush request, control packet).

#### <a id="c-ssam_trace_get_request_tc"></a>`ssam_trace_get_request_tc()`

```c
u32 ssam_trace_get_request_tc(const struct ssh_packet *p)
```

Read the packet's request target category.

**Parameters**

- `const struct ssh_packet *p`: The packet.

**Return**

Returns the packet's request target category (TC) field if the
packet represents a request with command data, or `SSAM_SSH_TC_NOT_APPLICABLE`
if not (e.g. flush request, control packet).

---

# Core Driver Internals

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> Architectural overview of the Surface System Aggregator Module (SSAM) core and Surface Serial Hub (SSH) driver. For the API documentation, refer to:

<a id="rst-core-driver-internals"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

Architectural overview of the Surface System Aggregator Module (SSAM) core and Surface Serial Hub (SSH) driver. For the API documentation, refer to:

- [Internal API Documentation](</kernel/hardware/driver-api/surface-aggregator/internal-api.md>)

<a id="rst-overview"></a>

## Overview

The SSAM core implementation is structured in layers, somewhat following the SSH protocol structure:

Lower-level packet transport is implemented in the *packet transport layer (PTL)*, directly building on top of the serial device (serdev) infrastructure of the kernel. As the name indicates, this layer deals with the packet transport logic and handles things like packet validation, packet acknowledgment (ACKing), packet (retransmission) timeouts, and relaying packet payloads to higher-level layers.

Above this sits the *request transport layer (RTL)*. This layer is centered around command-type packet payloads, i.e. requests (sent from host to EC), responses of the EC to those requests, and events (sent from EC to host). It, specifically, distinguishes events from request responses, matches responses to their corresponding requests, and implements request timeouts.

The *controller* layer is building on top of this and essentially decides how request responses and, especially, events are dealt with. It provides an event notifier system, handles event activation/deactivation, provides a workqueue for event and asynchronous request completion, and also manages the message counters required for building command messages (`SEQ`, `RQID`). This layer basically provides a fundamental interface to the SAM EC for use in other kernel drivers.

While the controller layer already provides an interface for other kernel drivers, the client *bus* extends this interface to provide support for native SSAM devices, i.e. devices that are not defined in ACPI and not implemented as platform devices, via `struct ssam_device <ssam_device>` and `struct ssam_device_driver <ssam_device_driver>` simplify management of client devices and client drivers.

Refer to [Documentation/driver-api/surface_aggregator/client.rst](/kernel/hardware/driver-api/surface-aggregator/client.md) for documentation regarding the client device/driver API and interface options for other kernel drivers. It is recommended to familiarize oneself with that chapter and the [Documentation/driver-api/surface_aggregator/ssh.rst](/kernel/hardware/driver-api/surface-aggregator/ssh.md) before continuing with the architectural overview below.

<a id="rst-packet-transport-layer"></a>

## Packet Transport Layer

The packet transport layer is represented via `struct ssh_ptl <ssh_ptl>` and is structured around the following key concepts:

<a id="rst-packets"></a>

### Packets

Packets are the fundamental transmission unit of the SSH protocol. They are managed by the packet transport layer, which is essentially the lowest layer of the driver and is built upon by other components of the SSAM core. Packets to be transmitted by the SSAM core are represented via `struct ssh_packet <ssh_packet>` (in contrast, packets received by the core do not have any specific structure and are managed entirely via the raw `struct ssh_frame <ssh_frame>`).

This structure contains the required fields to manage the packet inside the transport layer, as well as a reference to the buffer containing the data to be transmitted (i.e. the message wrapped in `struct ssh_frame <ssh_frame>`). Most notably, it contains an internal reference count, which is used for managing its lifetime (accessible via `ssh_packet_get()` and `ssh_packet_put()`). When this counter reaches zero, the `release()` callback provided to the packet via its `struct ssh_packet_ops <ssh_packet_ops>` reference is executed, which may then deallocate the packet or its enclosing structure (e.g. `struct ssh_request <ssh_request>`).

In addition to the `release` callback, the `struct ssh_packet_ops <ssh_packet_ops>` reference also provides a `complete()` callback, which is run once the packet has been completed and provides the status of this completion, i.e. zero on success or a negative errno value in case of an error. Once the packet has been submitted to the packet transport layer, the `complete()` callback is always guaranteed to be executed before the `release()` callback, i.e. the packet will always be completed, either successfully, with an error, or due to cancellation, before it will be released.

The state of a packet is managed via its `state` flags (`enum ssh_packet_flags <ssh_packet_flags>`), which also contains the packet type. In particular, the following bits are noteworthy:

- `SSH_PACKET_SF_LOCKED_BIT`: This bit is set when completion, either through error or success, is imminent. It indicates that no further references of the packet should be taken and any existing references should be dropped as soon as possible. The process setting this bit is responsible for removing any references to this packet from the packet queue and pending set.

- `SSH_PACKET_SF_COMPLETED_BIT`: This bit is set by the process running the `complete()` callback and is used to ensure that this callback only runs once.

- `SSH_PACKET_SF_QUEUED_BIT`: This bit is set when the packet is queued on the packet queue and cleared when it is dequeued.

- `SSH_PACKET_SF_PENDING_BIT`: This bit is set when the packet is added to the pending set and cleared when it is removed from it.

<a id="rst-packet-queue"></a>

### Packet Queue

The packet queue is the first of the two fundamental collections in the packet transport layer. It is a priority queue, with priority of the respective packets based on the packet type (major) and number of tries (minor). See `SSH_PACKET_PRIORITY()` for more details on the priority value.

All packets to be transmitted by the transport layer must be submitted to this queue via `ssh_ptl_submit()`. Note that this includes control packets sent by the transport layer itself. Internally, data packets can be re-submitted to this queue due to timeouts or NAK packets sent by the EC.

<a id="rst-pending-set"></a>

### Pending Set

The pending set is the second of the two fundamental collections in the packet transport layer. It stores references to packets that have already been transmitted, but wait for acknowledgment (e.g. the corresponding ACK packet) by the EC.

Note that a packet may both be pending and queued if it has been re-submitted due to a packet acknowledgment timeout or NAK. On such a re-submission, packets are not removed from the pending set.

<a id="rst-transmitter-thread"></a>

### Transmitter Thread

The transmitter thread is responsible for most of the actual work regarding packet transmission. In each iteration, it (waits for and) checks if the next packet on the queue (if any) can be transmitted and, if so, removes it from the queue and increments its counter for the number of transmission attempts, i.e. tries. If the packet is sequenced, i.e. requires an ACK by the EC, the packet is added to the pending set. Next, the packet's data is submitted to the serdev subsystem. In case of an error or timeout during this submission, the packet is completed by the transmitter thread with the status value of the callback set accordingly. In case the packet is unsequenced, i.e. does not require an ACK by the EC, the packet is completed with success on the transmitter thread.

Transmission of sequenced packets is limited by the number of concurrently pending packets, i.e. a limit on how many packets may be waiting for an ACK from the EC in parallel. This limit is currently set to one (see [Documentation/driver-api/surface_aggregator/ssh.rst](/kernel/hardware/driver-api/surface-aggregator/ssh.md) for the reasoning behind this). Control packets (i.e. ACK and NAK) can always be transmitted.

<a id="rst-receiver-thread"></a>

### Receiver Thread

Any data received from the EC is put into a FIFO buffer for further processing. This processing happens on the receiver thread. The receiver thread parses and validates the received message into its `struct ssh_frame <ssh_frame>` and corresponding payload. It prepares and submits the necessary ACK (and on validation error or invalid data NAK) packets for the received messages.

This thread also handles further processing, such as matching ACK messages to the corresponding pending packet (via sequence ID) and completing it, as well as initiating re-submission of all currently pending packets on receival of a NAK message (re-submission in case of a NAK is similar to re-submission due to timeout, see below for more details on that). Note that the successful completion of a sequenced packet will always run on the receiver thread (whereas any failure-indicating completion will run on the process where the failure occurred).

Any payload data is forwarded via a callback to the next upper layer, i.e. the request transport layer.

<a id="rst-timeout-reaper"></a>

### Timeout Reaper

The packet acknowledgment timeout is a per-packet timeout for sequenced packets, started when the respective packet begins (re-)transmission (i.e. this timeout is armed once per transmission attempt on the transmitter thread). It is used to trigger re-submission or, when the number of tries has been exceeded, cancellation of the packet in question.

This timeout is handled via a dedicated reaper task, which is essentially a work item (re-)scheduled to run when the next packet is set to time out. The work item then checks the set of pending packets for any packets that have exceeded the timeout and, if there are any remaining packets, re-schedules itself to the next appropriate point in time.

If a timeout has been detected by the reaper, the packet will either be re-submitted if it still has some remaining tries left, or completed with `-ETIMEDOUT` as status if not. Note that re-submission, in this case and triggered by receival of a NAK, means that the packet is added to the queue with a now incremented number of tries, yielding a higher priority. The timeout for the packet will be disabled until the next transmission attempt and the packet remains on the pending set.

Note that due to transmission and packet acknowledgment timeouts, the packet transport layer is always guaranteed to make progress, if only through timing out packets, and will never fully block.

<a id="rst-concurrency-and-locking"></a>

### Concurrency and Locking

There are two main locks in the packet transport layer: One guarding access to the packet queue and one guarding access to the pending set. These collections may only be accessed and modified under the respective lock. If access to both collections is needed, the pending lock must be acquired before the queue lock to avoid deadlocks.

In addition to guarding the collections, after initial packet submission certain packet fields may only be accessed under one of the locks. Specifically, the packet priority must only be accessed while holding the queue lock and the packet timestamp must only be accessed while holding the pending lock.

Other parts of the packet transport layer are guarded independently. State flags are managed by atomic bit operations and, if necessary, memory barriers. Modifications to the timeout reaper work item and expiration date are guarded by their own lock.

The reference of the packet to the packet transport layer (`ptl`) is somewhat special. It is either set when the upper layer request is submitted or, if there is none, when the packet is first submitted. After it is set, it will not change its value. Functions that may run concurrently with submission, i.e. cancellation, can not rely on the `ptl` reference to be set. Access to it in these functions is guarded by `READ_ONCE()`, whereas setting `ptl` is equally guarded with `WRITE_ONCE()` for symmetry.

Some packet fields may be read outside of the respective locks guarding them, specifically priority and state for tracing. In those cases, proper access is ensured by employing `WRITE_ONCE()` and `READ_ONCE()`. Such read-only access is only allowed when stale values are not critical.

With respect to the interface for higher layers, packet submission (`ssh_ptl_submit()`), packet cancellation (`ssh_ptl_cancel()`), data receival (`ssh_ptl_rx_rcvbuf()`), and layer shutdown (`ssh_ptl_shutdown()`) may always be executed concurrently with respect to each other. Note that packet submission may not run concurrently with itself for the same packet. Equally, shutdown and data receival may also not run concurrently with themselves (but may run concurrently with each other).

<a id="rst-request-transport-layer"></a>

## Request Transport Layer

The request transport layer is represented via `struct ssh_rtl <ssh_rtl>` and builds on top of the packet transport layer. It deals with requests, i.e. SSH packets sent by the host containing a `struct ssh_command <ssh_command>` as frame payload. This layer separates responses to requests from events, which are also sent by the EC via a `struct ssh_command <ssh_command>` payload. While responses are handled in this layer, events are relayed to the next upper layer, i.e. the controller layer, via the corresponding callback. The request transport layer is structured around the following key concepts:

<a id="rst-request"></a>

### Request

Requests are packets with a command-type payload, sent from host to EC to query data from or trigger an action on it (or both simultaneously). They are represented by `struct ssh_request <ssh_request>`, wrapping the underlying `struct ssh_packet <ssh_packet>` storing its message data (i.e. SSH frame with command payload). Note that all top-level representations, e.g. `struct ssam_request_sync <ssam_request_sync>` are built upon this struct.

As `struct ssh_request <ssh_request>` extends `struct ssh_packet <ssh_packet>`, its lifetime is also managed by the reference counter inside the packet struct (which can be accessed via `ssh_request_get()` and `ssh_request_put()`). Once the counter reaches zero, the `release()` callback of the `struct ssh_request_ops <ssh_request_ops>` reference of the request is called.

Requests can have an optional response that is equally sent via a SSH message with command-type payload (from EC to host). The party constructing the request must know if a response is expected and mark this in the request flags provided to `ssh_request_init()`, so that the request transport layer can wait for this response.

Similar to `struct ssh_packet <ssh_packet>`, `struct ssh_request <ssh_request>` also has a `complete()` callback provided via its request ops reference and is guaranteed to be completed before it is released once it has been submitted to the request transport layer via `ssh_rtl_submit()`. For a request without a response, successful completion will occur once the underlying packet has been successfully transmitted by the packet transport layer (i.e. from within the packet completion callback). For a request with response, successful completion will occur once the response has been received and matched to the request via its request ID (which happens on the packet layer's data-received callback running on the receiver thread). If the request is completed with an error, the status value will be set to the corresponding (negative) errno value.

The state of a request is again managed via its `state` flags (`enum ssh_request_flags <ssh_request_flags>`), which also encode the request type. In particular, the following bits are noteworthy:

- `SSH_REQUEST_SF_LOCKED_BIT`: This bit is set when completion, either through error or success, is imminent. It indicates that no further references of the request should be taken and any existing references should be dropped as soon as possible. The process setting this bit is responsible for removing any references to this request from the request queue and pending set.

- `SSH_REQUEST_SF_COMPLETED_BIT`: This bit is set by the process running the `complete()` callback and is used to ensure that this callback only runs once.

- `SSH_REQUEST_SF_QUEUED_BIT`: This bit is set when the request is queued on the request queue and cleared when it is dequeued.

- `SSH_REQUEST_SF_PENDING_BIT`: This bit is set when the request is added to the pending set and cleared when it is removed from it.

<a id="rst-request-queue"></a>

### Request Queue

The request queue is the first of the two fundamental collections in the request transport layer. In contrast to the packet queue of the packet transport layer, it is not a priority queue and the simple first come first serve principle applies.

All requests to be transmitted by the request transport layer must be submitted to this queue via `ssh_rtl_submit()`. Once submitted, requests may not be re-submitted, and will not be re-submitted automatically on timeout. Instead, the request is completed with a timeout error. If desired, the caller can create and submit a new request for another try, but it must not submit the same request again.

<a id="rst-pending-set-1"></a>

### Pending Set

The pending set is the second of the two fundamental collections in the request transport layer. This collection stores references to all pending requests, i.e. requests awaiting a response from the EC (similar to what the pending set of the packet transport layer does for packets).

<a id="rst-transmitter-task"></a>

### Transmitter Task

The transmitter task is scheduled when a new request is available for transmission. It checks if the next request on the request queue can be transmitted and, if so, submits its underlying packet to the packet transport layer. This check ensures that only a limited number of requests can be pending, i.e. waiting for a response, at the same time. If the request requires a response, the request is added to the pending set before its packet is submitted.

<a id="rst-packet-completion-callback"></a>

### Packet Completion Callback

The packet completion callback is executed once the underlying packet of a request has been completed. In case of an error completion, the corresponding request is completed with the error value provided in this callback.

On successful packet completion, further processing depends on the request. If the request expects a response, it is marked as transmitted and the request timeout is started. If the request does not expect a response, it is completed with success.

<a id="rst-data-received-callback"></a>

### Data-Received Callback

The data received callback notifies the request transport layer of data being received by the underlying packet transport layer via a data-type frame. In general, this is expected to be a command-type payload.

If the request ID of the command is one of the request IDs reserved for events (one to `SSH_NUM_EVENTS`, inclusively), it is forwarded to the event callback registered in the request transport layer. If the request ID indicates a response to a request, the respective request is looked up in the pending set and, if found and marked as transmitted, completed with success.

<a id="rst-timeout-reaper-1"></a>

### Timeout Reaper

The request-response-timeout is a per-request timeout for requests expecting a response. It is used to ensure that a request does not wait indefinitely on a response from the EC and is started after the underlying packet has been successfully completed.

This timeout is, similar to the packet acknowledgment timeout on the packet transport layer, handled via a dedicated reaper task. This task is essentially a work-item (re-)scheduled to run when the next request is set to time out. The work item then scans the set of pending requests for any requests that have timed out and completes them with `-ETIMEDOUT` as status. Requests will not be re-submitted automatically. Instead, the issuer of the request must construct and submit a new request, if so desired.

Note that this timeout, in combination with packet transmission and acknowledgment timeouts, guarantees that the request layer will always make progress, even if only through timing out packets, and never fully block.

<a id="rst-concurrency-and-locking-1"></a>

### Concurrency and Locking

Similar to the packet transport layer, there are two main locks in the request transport layer: One guarding access to the request queue and one guarding access to the pending set. These collections may only be accessed and modified under the respective lock.

Other parts of the request transport layer are guarded independently. State flags are (again) managed by atomic bit operations and, if necessary, memory barriers. Modifications to the timeout reaper work item and expiration date are guarded by their own lock.

Some request fields may be read outside of the respective locks guarding them, specifically the state for tracing. In those cases, proper access is ensured by employing `WRITE_ONCE()` and `READ_ONCE()`. Such read-only access is only allowed when stale values are not critical.

With respect to the interface for higher layers, request submission (`ssh_rtl_submit()`), request cancellation (`ssh_rtl_cancel()`), and layer shutdown (`ssh_rtl_shutdown()`) may always be executed concurrently with respect to each other. Note that request submission may not run concurrently with itself for the same request (and also may only be called once per request). Equally, shutdown may also not run concurrently with itself.

<a id="rst-controller-layer"></a>

## Controller Layer

The controller layer extends on the request transport layer to provide an easy-to-use interface for client drivers. It is represented by `struct ssam_controller <ssam_controller>` and the SSH driver. While the lower level transport layers take care of transmitting and handling packets and requests, the controller layer takes on more of a management role. Specifically, it handles device initialization, power management, and event handling, including event delivery and registration via the (event) completion system (`struct ssam_cplt <ssam_cplt>`).

<a id="rst-event-registration"></a>

### Event Registration

In general, an event (or rather a class of events) has to be explicitly requested by the host before the EC will send it (HID input events seem to be the exception). This is done via an event-enable request (similarly, events should be disabled via an event-disable request once no longer desired).

The specific request used to enable (or disable) an event is given via an event registry, i.e. the governing authority of this event (so to speak), represented by `struct ssam_event_registry <ssam_event_registry>`. As parameters to this request, the target category and, depending on the event registry, instance ID of the event to be enabled must be provided. This (optional) instance ID must be zero if the registry does not use it. Together, target category and instance ID form the event ID, represented by `struct ssam_event_id <ssam_event_id>`. In short, both, event registry and event ID, are required to uniquely identify a respective class of events.

Note that a further *request ID* parameter must be provided for the enable-event request. This parameter does not influence the class of events being enabled, but instead is set as the request ID (RQID) on each event of this class sent by the EC. It is used to identify events (as a limited number of request IDs is reserved for use in events only, specifically one to `SSH_NUM_EVENTS` inclusively) and also map events to their specific class. Currently, the controller always sets this parameter to the target category specified in `struct ssam_event_id <ssam_event_id>`.

As multiple client drivers may rely on the same (or overlapping) classes of events and enable/disable calls are strictly binary (i.e. on/off), the controller has to manage access to these events. It does so via reference counting, storing the counter inside an RB-tree based mapping with event registry and ID as key (there is no known list of valid event registry and event ID combinations). See `struct ssam_nf <ssam_nf>`, `ssam_nf_refcount_inc()`, and `ssam_nf_refcount_dec()` for details.

This management is done together with notifier registration (described in the next section) via the top-level `ssam_notifier_register()` and `ssam_notifier_unregister()` functions.

<a id="rst-event-delivery"></a>

### Event Delivery

To receive events, a client driver has to register an event notifier via `ssam_notifier_register()`. This increments the reference counter for that specific class of events (as detailed in the previous section), enables the class on the EC (if it has not been enabled already), and installs the provided notifier callback.

Notifier callbacks are stored in lists, with one (RCU) list per target category (provided via the event ID; NB: there is a fixed known number of target categories). There is no known association from the combination of event registry and event ID to the command data (target ID, target category, command ID, and instance ID) that can be provided by an event class, apart from target category and instance ID given via the event ID.

Note that due to the way notifiers are (or rather have to be) stored, client drivers may receive events that they have not requested and need to account for them. Specifically, they will, by default, receive all events from the same target category. To simplify dealing with this, filtering of events by target ID (provided via the event registry) and instance ID (provided via the event ID) can be requested when registering a notifier. This filtering is applied when iterating over the notifiers at the time they are executed.

All notifier callbacks are executed on a dedicated workqueue, the so-called completion workqueue. After an event has been received via the callback installed in the request layer (running on the receiver thread of the packet transport layer), it will be put on its respective event queue (`struct ssam_event_queue <ssam_event_queue>`). From this event queue the completion work item of that queue (running on the completion workqueue) will pick up the event and execute the notifier callback. This is done to avoid blocking on the receiver thread.

There is one event queue per combination of target ID and target category. This is done to ensure that notifier callbacks are executed in sequence for events of the same target ID and target category. Callbacks can be executed in parallel for events with a different combination of target ID and target category.

<a id="rst-concurrency-and-locking-2"></a>

### Concurrency and Locking

Most of the concurrency related safety guarantees of the controller are provided by the lower-level request transport layer. In addition to this, event (un-)registration is guarded by its own lock.

Access to the controller state is guarded by the state lock. This lock is a read/write semaphore. The reader part can be used to ensure that the state does not change while functions depending on the state to stay the same (e.g. `ssam_notifier_register()`, `ssam_notifier_unregister()`, `ssam_request_sync_submit()`, and derivatives) are executed and this guarantee is not already provided otherwise (e.g. through `ssam_client_bind()` or `ssam_client_link()`). The writer part guards any transitions that will change the state, i.e. initialization, destruction, suspension, and resumption.

The controller state may be accessed (read-only) outside the state lock for smoke-testing against invalid API usage (e.g. in `ssam_request_sync_submit()`). Note that such checks are not supposed to (and will not) protect against all invalid usages, but rather aim to help catch them. In those cases, proper variable access is ensured by employing `WRITE_ONCE()` and `READ_ONCE()`.

Assuming any preconditions on the state not changing have been satisfied, all non-initialization and non-shutdown functions may run concurrently with each other. This includes `ssam_notifier_register()`, `ssam_notifier_unregister()`, `ssam_request_sync_submit()`, as well as all functions building on top of those.

---

# Overview

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> The Surface/System Aggregator Module (SAM, SSAM) is an (arguably the) embedded controller (EC) on Microsoft Surface devices. It has been originally introduced on 4th generation devices (Surface Pro 4, Surface Book 1), but its…

<a id="rst-overview"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

The Surface/System Aggregator Module (SAM, SSAM) is an (arguably *the*) embedded controller (EC) on Microsoft Surface devices. It has been originally introduced on 4th generation devices (Surface Pro 4, Surface Book 1), but its responsibilities and feature-set have since been expanded significantly with the following generations.

<a id="rst-features-and-integration"></a>

## Features and Integration

Not much is currently known about SAM on 4th generation devices (Surface Pro 4, Surface Book 1), due to the use of a different communication interface between host and EC (as detailed below). On 5th (Surface Pro 2017, Surface Book 2, Surface Laptop 1) and later generation devices, SAM is responsible for providing battery information (both current status and static values, such as maximum capacity etc.), as well as an assortment of temperature sensors (e.g. skin temperature) and cooling/performance-mode setting to the host. On the Surface Book 2, specifically, it additionally provides an interface for properly handling clipboard detachment (i.e. separating the display part from the keyboard part of the device), on the Surface Laptop 1 and 2 it is required for keyboard HID input. This HID subsystem has been restructured for 7th generation devices and on those, specifically Surface Laptop 3 and Surface Book 3, is responsible for all major HID input (i.e. keyboard and touchpad).

While features have not changed much on a coarse level since the 5th generation, internal interfaces have undergone some rather large changes. On 5th and 6th generation devices, both battery and temperature information is exposed to ACPI via a shim driver (referred to as Surface ACPI Notify, or SAN), translating ACPI generic serial bus write-/read-accesses to SAM requests. On 7th generation devices, this additional layer is gone and these devices require a driver hooking directly into the SAM interface. Equally, on newer generations, less devices are declared in ACPI, making them a bit harder to discover and requiring us to hard-code a sort of device registry. Due to this, a SSAM bus and subsystem with client devices (`struct ssam_device <ssam_device>`) has been implemented.

<a id="rst-communication"></a>

## Communication

The type of communication interface between host and EC depends on the generation of the Surface device. On 4th generation devices, host and EC communicate via HID, specifically using a HID-over-I2C device, whereas on 5th and later generations, communication takes place via a USART serial device. In accordance to the drivers found on other operating systems, we refer to the serial device and its driver as Surface Serial Hub (SSH). When needed, we differentiate between both types of SAM by referring to them as SAM-over-SSH and SAM-over-HID.

Currently, this subsystem only supports SAM-over-SSH. The SSH communication interface is described in more detail below. The HID interface has not been reverse engineered yet and it is, at the moment, unclear how many (and which) concepts of the SSH interface detailed below can be transferred to it.

<a id="rst-surface-serial-hub"></a>

### Surface Serial Hub

As already elaborated above, the Surface Serial Hub (SSH) is the communication interface for SAM on 5th- and all later-generation Surface devices. On the highest level, communication can be separated into two main types: Requests, messages sent from host to EC that may trigger a direct response from the EC (explicitly associated with the request), and events (sometimes also referred to as notifications), sent from EC to host without being a direct response to a previous request. We may also refer to requests without response as commands. In general, events need to be enabled via one of multiple dedicated requests before they are sent by the EC.

See [Documentation/driver-api/surface_aggregator/ssh.rst](/kernel/hardware/driver-api/surface-aggregator/ssh.md) for a more technical protocol documentation and [Documentation/driver-api/surface_aggregator/internal.rst](/kernel/hardware/driver-api/surface-aggregator/internal.md) for an overview of the internal driver architecture.

---

# Surface Serial Hub Protocol

_Peios Kernel / Hardware and drivers / Driver development / surface_aggregator_

> The Surface Serial Hub (SSH) is the central communication interface for the embedded Surface Aggregator Module controller (SAM or EC), found on newer Surface generations. We will refer to this protocol and interface as SAM-over-SSH, as…

<a id="rst-surface-serial-hub-protocol"></a>

<!-- SPDX-License-Identifier: GPL-2.0+ -->

The Surface Serial Hub (SSH) is the central communication interface for the embedded Surface Aggregator Module controller (SAM or EC), found on newer Surface generations. We will refer to this protocol and interface as SAM-over-SSH, as opposed to SAM-over-HID for the older generations.

On Surface devices with SAM-over-SSH, SAM is connected to the host via UART and defined in ACPI as device with ID `MSHW0084`. On these devices, significant functionality is provided via SAM, including access to battery and power information and events, thermal read-outs and events, and many more. For Surface Laptops, keyboard input is handled via HID directed through SAM, on the Surface Laptop 3 and Surface Book 3 this also includes touchpad input.

Note that the standard disclaimer for this subsystem also applies to this document: All of this has been reverse-engineered and may thus be erroneous and/or incomplete.

All CRCs used in the following are two-byte `crc_itu_t(0xffff, ...)`. All multi-byte values are little-endian, there is no implicit padding between values.

<a id="rst-ssh-packet-protocol-definitions"></a>

## SSH Packet Protocol: Definitions

The fundamental communication unit of the SSH protocol is a frame (`struct ssh_frame <ssh_frame>`). A frame consists of the following fields, packed together and in order:


<table>
<caption>SSH Frame</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Type

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`TYPE`

</td>
<td>


`u8 <u8>`

</td>
<td>


Type identifier of the frame.

</td>
</tr>
<tr>
<td>


`LEN`

</td>
<td>


`u16 <u16>`

</td>
<td>


Length of the payload associated with the frame.

</td>
</tr>
<tr>
<td>


`SEQ`

</td>
<td>


`u8 <u8>`

</td>
<td>


Sequence ID (see explanation below).

</td>
</tr>
</tbody>
</table>

Each frame structure is followed by a CRC over this structure. The CRC over the frame structure (`TYPE`, `LEN`, and `SEQ` fields) is placed directly after the frame structure and before the payload. The payload is followed by its own CRC (over all payload bytes). If the payload is not present (i.e. the frame has `LEN=0`), the CRC of the payload is still present and will evaluate to `0xffff`. The `LEN` field does not include any of the CRCs, it equals the number of bytes between the CRC of the frame and the CRC of the payload.

Additionally, the following fixed two-byte sequences are used:


<table>
<caption>SSH Byte Sequences</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


Value

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`SYN`

</td>
<td>


`[0xAA, 0x55]`

</td>
<td>


Synchronization bytes.

</td>
</tr>
</tbody>
</table>

A message consists of `SYN`, followed by the frame (`TYPE`, `LEN`, `SEQ` and CRC) and, if specified in the frame (i.e. `LEN > 0`), payload bytes, followed finally, regardless if the payload is present, the payload CRC. The messages corresponding to an exchange are, in part, identified by having the same sequence ID (`SEQ`), stored inside the frame (more on this in the next section). The sequence ID is a wrapping counter.

A frame can have the following types (`enum ssh_frame_type <ssh_frame_type>`):


<table>
<caption>SSH Frame Types</caption>
<thead>
<tr>
<th>


Name

</th>
<th>


Value

</th>
<th>


Short Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`NAK`

</td>
<td>


`0x04`

</td>
<td>


Sent on error in previously received message.

</td>
</tr>
<tr>
<td>


`ACK`

</td>
<td>


`0x40`

</td>
<td>


Sent to acknowledge receival of `DATA` frame.

</td>
</tr>
<tr>
<td>


`DATA_SEQ`

</td>
<td>


`0x80`

</td>
<td>


Sent to transfer data. Sequenced.

</td>
</tr>
<tr>
<td>


`DATA_NSQ`

</td>
<td>


`0x00`

</td>
<td>


Same as `DATA_SEQ`, but does not need to be ACKed.

</td>
</tr>
</tbody>
</table>

Both `NAK`- and `ACK`-type frames are used to control flow of messages and thus do not carry a payload. `DATA_SEQ`- and `DATA_NSQ`-type frames on the other hand must carry a payload. The flow sequence and interaction of different frame types will be described in more depth in the next section.

<a id="rst-ssh-packet-protocol-flow-sequence"></a>

## SSH Packet Protocol: Flow Sequence

Each exchange begins with `SYN`, followed by a `DATA_SEQ`- or `DATA_NSQ`-type frame, followed by its CRC, payload, and payload CRC. In case of a `DATA_NSQ`-type frame, the exchange is then finished. In case of a `DATA_SEQ`-type frame, the receiving party has to acknowledge receival of the frame by responding with a message containing an `ACK`-type frame with the same sequence ID of the `DATA` frame. In other words, the sequence ID of the `ACK` frame specifies the `DATA` frame to be acknowledged. In case of an error, e.g. an invalid CRC, the receiving party responds with a message containing an `NAK`-type frame. As the sequence ID of the previous data frame, for which an error is indicated via the `NAK` frame, cannot be relied upon, the sequence ID of the `NAK` frame should not be used and is set to zero. After receival of an `NAK` frame, the sending party should re-send all outstanding (non-ACKed) messages.

Sequence IDs are not synchronized between the two parties, meaning that they are managed independently for each party. Identifying the messages corresponding to a single exchange thus relies on the sequence ID as well as the type of the message, and the context. Specifically, the sequence ID is used to associate an `ACK` with its `DATA_SEQ`-type frame, but not `DATA_SEQ`- or `DATA_NSQ`-type frames with other `DATA`- type frames.

An example exchange might look like this:



```text
tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
rx: ------------------------------------- SYN FRAME(A) CRC(F) CRC(P) --
```

where both frames have the same sequence ID (`SEQ`). Here, `FRAME(D)` indicates a `DATA_SEQ`-type frame, `FRAME(A)` an `ACK`-type frame, `CRC(F)` the CRC over the previous frame, `CRC(P)` the CRC over the previous payload. In case of an error, the exchange would look like this:



```text
tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
rx: ------------------------------------- SYN FRAME(N) CRC(F) CRC(P) --
```

upon which the sender should re-send the message. `FRAME(N)` indicates an `NAK`-type frame. Note that the sequence ID of the `NAK`-type frame is fixed to zero. For `DATA_NSQ`-type frames, both exchanges are the same:



```text
tx: -- SYN FRAME(DATA_NSQ) CRC(F) PAYLOAD CRC(P) ----------------------
rx: -------------------------------------------------------------------
```

Here, an error can be detected, but not corrected or indicated to the sending party. These exchanges are symmetric, i.e. switching `rx` and `tx` results again in a valid exchange. Currently, no longer exchanges are known.

<a id="rst-commands-requests-responses-and-events"></a>

## Commands: Requests, Responses, and Events

Commands are sent as payload inside a data frame. Currently, this is the only known payload type of `DATA` frames, with a payload-type value of `0x80` (`SSH_PLD_TYPE_CMD <ssh_payload_type>`).

The command-type payload (`struct ssh_command <ssh_command>`) consists of an eight-byte command structure, followed by optional and variable length command data. The length of this optional data is derived from the frame payload length given in the corresponding frame, i.e. it is `frame.len - sizeof(struct ssh_command)`. The command struct contains the following fields, packed together and in order:


<table>
<caption>SSH Command</caption>
<thead>
<tr>
<th>


Field

</th>
<th>


Type

</th>
<th>


Description

</th>
</tr>
</thead>
<tbody>
<tr>
<td>


`TYPE`

</td>
<td>


`u8 <u8>`

</td>
<td>


Type of the payload. For commands always `0x80`.

</td>
</tr>
<tr>
<td>


`TC`

</td>
<td>


`u8 <u8>`

</td>
<td>


Target category.

</td>
</tr>
<tr>
<td>


`TID`

</td>
<td>


`u8 <u8>`

</td>
<td>


Target ID for commands/messages.

</td>
</tr>
<tr>
<td>


`SID`

</td>
<td>


`u8 <u8>`

</td>
<td>


Source ID for commands/messages.

</td>
</tr>
<tr>
<td>


`IID`

</td>
<td>


`u8 <u8>`

</td>
<td>


Instance ID.

</td>
</tr>
<tr>
<td>


`RQID`

</td>
<td>


`u16 <u16>`

</td>
<td>


Request ID.

</td>
</tr>
<tr>
<td>


`CID`

</td>
<td>


`u8 <u8>`

</td>
<td>


Command ID.

</td>
</tr>
</tbody>
</table>

The command struct and data, in general, does not contain any failure detection mechanism (e.g. CRCs), this is solely done on the frame level.

Command-type payloads are used by the host to send commands and requests to the EC as well as by the EC to send responses and events back to the host. We differentiate between requests (sent by the host), responses (sent by the EC in response to a request), and events (sent by the EC without a preceding request).

Commands and events are uniquely identified by their target category (`TC`) and command ID (`CID`). The target category specifies a general category for the command (e.g. system in general, vs. battery and AC, vs. temperature, and so on), while the command ID specifies the command inside that category. Only the combination of `TC` + `CID` is unique. Additionally, commands have an instance ID (`IID`), which is used to differentiate between different sub-devices. For example `TC=3` `CID=1` is a request to get the temperature on a thermal sensor, where `IID` specifies the respective sensor. If the instance ID is not used, it should be set to zero. If instance IDs are used, they, in general, start with a value of one, whereas zero may be used for instance independent queries, if applicable. A response to a request should have the same target category, command ID, and instance ID as the corresponding request.

Responses are matched to their corresponding request via the request ID (`RQID`) field. This is a 16 bit wrapping counter similar to the sequence ID on the frames. Note that the sequence ID of the frames for a request-response pair does not match. Only the request ID has to match. Frame-protocol wise these are two separate exchanges, and may even be separated, e.g. by an event being sent after the request but before the response. Not all commands produce a response, and this is not detectable by `TC` + `CID`. It is the responsibility of the issuing party to wait for a response (or signal this to the communication framework, as is done in SAN/ACPI via the `SNC` flag).

Events are identified by unique and reserved request IDs. These IDs should not be used by the host when sending a new request. They are used on the host to, first, detect events and, second, match them with a registered event handler. Request IDs for events are chosen by the host and directed to the EC when setting up and enabling an event source (via the enable-event-source request). The EC then uses the specified request ID for events sent from the respective source. Note that an event should still be identified by its target category, command ID, and, if applicable, instance ID, as a single event source can send multiple different event types. In general, however, a single target category should map to a single reserved event request ID.

Furthermore, requests, responses, and events have an associated target ID (`TID`) and source ID (`SID`). These two fields indicate where a message originates from (`SID`) and what the intended target of the message is (`TID`). Note that a response to a specific request therefore has the source and target IDs swapped when compared to the original request (i.e. the request target is the response source and the request source is the response target). See (`enum ssh_request_id <ssh_request_id>`) for possible values of both.

Note that, even though requests and events should be uniquely identifiable by target category and command ID alone, the EC may require specific target ID and instance ID values to accept a command. A command that is accepted for `TID=1`, for example, may not be accepted for `TID=2` and vice versa. While this may not always hold in reality, you can think of different target/source IDs indicating different physical ECs with potentially different feature sets.

<a id="rst-limitations-and-observations"></a>

## Limitations and Observations

The protocol can, in theory, handle up to `U8_MAX` frames in parallel, with up to `U16_MAX` pending requests (neglecting request IDs reserved for events). In practice, however, this is more limited. From our testing (although via a python and thus a user-space program), it seems that the EC can handle up to four requests (mostly) reliably in parallel at a certain time. With five or more requests in parallel, consistent discarding of commands (ACKed frame but no command response) has been observed. For five simultaneous commands, this reproducibly resulted in one command being dropped and four commands being handled.

However, it has also been noted that, even with three requests in parallel, occasional frame drops happen. Apart from this, with a limit of three pending requests, no dropped commands (i.e. command being dropped but frame carrying command being ACKed) have been observed. In any case, frames (and possibly also commands) should be re-sent by the host if a certain timeout is exceeded. This is done by the EC for frames with a timeout of one second, up to two re-tries (i.e. three transmissions in total). The limit of re-tries also applies to received NAKs, and, in a worst case scenario, can lead to entire messages being dropped.

While this also seems to work fine for pending data frames as long as no transmission failures occur, implementation and handling of these seems to depend on the assumption that there is only one non-acknowledged data frame. In particular, the detection of repeated frames relies on the last sequence number. This means that, if a frame that has been successfully received by the EC is sent again, e.g. due to the host not receiving an `ACK`, the EC will only detect this if it has the sequence ID of the last frame received by the EC. As an example: Sending two frames with `SEQ=0` and `SEQ=1` followed by a repetition of `SEQ=0` will not detect the second `SEQ=0` frame as such, and thus execute the command in this frame each time it has been received, i.e. twice in this example. Sending `SEQ=0`, `SEQ=1` and then repeating `SEQ=1` will detect the second `SEQ=1` as repetition of the first one and ignore it, thus executing the contained command only once.

In conclusion, this suggests a limit of at most one pending un-ACKed frame (per party, effectively leading to synchronous communication regarding frames) and at most three pending commands. The limit to synchronous frame transfers seems to be consistent with behavior observed on Windows.
