surface_aggregator
Single-page view · as markdown
Surface System Aggregator Module (SSAM)
Peios Kernel / Hardware and drivers / Driver development / surface_aggregator
Client Driver API Documentation
Peios Kernel / Hardware and drivers / Driver development / surface_aggregator
Serial Hub Communication #
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 thestruct ssh_frame.lenfield. This frame is sequenced, meaning that an ACK is required.SSH_FRAME_TYPE_DATA_NSQ: Same asSSH_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.
struct ssh_frame #
SSH communication frame.
Definition
;
Members
type: The type of the frame. Seeenum 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.
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.
struct ssh_command #
Payload of a command-type frame.
Definition
;
Members
type: The type of the payload. Seeenum 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.
SSH_MESSAGE_LENGTH() #
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.
SSH_COMMAND_MESSAGE_LENGTH() #
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.
SSH_MSGOFFSET_FRAME() #
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 field in the
raw SSH message data as. Takes SYN bytes (u16) preceding the frame into
account.
SSH_MSGOFFSET_COMMAND() #
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 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.
ssh_crc() #
u16 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.
ssh_rqid_next_valid() #
u16 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.
ssh_rqid_to_event() #
u16 Convert request ID to its corresponding event ID.
Parameters
u16 rqid: The request ID to convert.
ssh_rqid_is_event() #
bool Check if given request ID is a valid event ID.
Parameters
u16 rqid: The request ID to check.
ssh_tc_to_rqid() #
u16 Convert target category to its corresponding request ID.
Parameters
u8 tc: The target category to convert.
ssh_tid_to_index() #
u8 Convert target ID to its corresponding target index.
Parameters
u8 tid: The target ID to convert.
ssh_tid_is_valid() #
bool Check if target ID is valid/supported.
Parameters
u8 tid: The target ID to check.
struct ssam_span #
Reference to a buffer region.
Definition
;
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.
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.
enum ssh_packet_base_priority #
Base priorities for 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.
SSH_PACKET_PRIORITY() #
Compute packet priority from base priority and number of tries.
Parameters
base: The base priority as suffix ofenum ssh_packet_base_priority, e.g.FLUSH,DATA,ACK, orNAK.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.
ssh_packet_priority_get_try() #
u8 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.
ssh_packet_priority_get_base() #
u8 Get base priority from packet priority.
Parameters
u8 priority: The packet priority.
Return
Returns the base priority encoded in the given packet priority.
struct ssh_packet_ops #
Callback operations for a SSH packet.
Definition
;
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.
struct ssh_packet #
SSH transport packet.
Definition
;
Members
ptl: Pointer to the packet transport layer. May beNULLif the packet (or enclosing request) has not been submitted yet.refcnt: Reference count of the packet.priority: Priority of the packet. Must be computed viaSSH_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). Seeenum ssh_packet_flagsfor possible options.timestamp: Timestamp specifying when the latest transmission of a currently pending packet has been started. May beKTIME_MAXbefore 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.
ssh_packet_set_data() #
void 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.
struct ssh_request_ops #
Callback operations for a SSH request.
Definition
;
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 thestruct ssh_commandparameter (cmd), the command payload of the request response via thestruct ssh_spanparameter (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.
struct ssh_request #
SSH transport request.
Definition
;
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). Seeenum ssh_request_flagsfor 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 beKTIME_MAXbefore that, or when the request does not expect a response. Used for the request timeout implementation.ops: Request Operations.
to_ssh_request() #
struct ssh_request * 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 to its enclosing struct ssh_request.
The caller is responsible for making sure that the packet is actually
wrapped in a struct ssh_request.
Return
Returns the struct ssh_request wrapping the provided packet.
ssh_request_get() #
struct ssh_request * 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, enclosed in it.
See also ssh_request_put(), ssh_packet_get().
Return
Returns the request provided as input.
ssh_request_put() #
void 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, enclosed in it. If
the reference count reaches zero, the release callback specified in the
request's struct ssh_request_ops, i.e. r->ops->release, will be
called.
See also ssh_request_get(), ssh_packet_put().
ssh_request_set_data() #
void 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() for more details.
ssh_packet_get() #
struct ssh_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()
for the counter-part of this function.
Return
Returns the packet provided as input.
ssh_packet_put() #
void 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, i.e. packet->ops->release, will be
called.
See ssh_packet_get() for the counter-part of this function.
Controller and Core Interface #
enum ssam_event_flags #
Flags for enabling/disabling SAM events
Constants
SSAM_EVENT_SEQUENCED: The event will be sent via a sequenced data frame.
struct ssam_event #
SAM event sent from the EC to the host.
Definition
;
Members
target_category: Target category of the event source. Seeenum 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.
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 theSSAM_REQUEST_HAS_RESPONSEflag are mutually exclusive.
struct ssam_request #
SAM request description.
Definition
;
Members
target_category: Category of the request's target. Seeenum 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. Seeenum 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,
and specifically its raw message data via ssam_request_write_data().
struct ssam_response #
Response buffer for SAM request.
Definition
;
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.
struct ssam_request_sync #
Synchronous SAM request struct.
Definition
;
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.
ssam_request_sync_set_data() #
void 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.
ssam_request_sync_set_resp() #
void 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.
ssam_request_sync_wait() #
int 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.
ssam_request_do_sync_onstack() #
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().
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.
__ssam_retry() #
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.
ssam_retry() #
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() for a more generic macro for this purpose.
Return
Returns the return value of the last execution of request.
struct ssam_request_spec #
Blue-print specification of SAM request.
Definition
;
Members
target_category: Category of the request's target. Seeenum 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. Seeenum 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.
struct ssam_request_spec_md #
Blue-print specification for multi-device SAM request.
Definition
;
Members
target_category: Category of the request's target. Seeenum ssam_ssh_tc.command_id: Command ID of the request.flags: Flags for the request. Seeenum 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.
SSAM_DEFINE_SYNC_REQUEST_N() #
Define synchronous SAM request function with neither argument nor return value.
Parameters
name: Name of the generated function.spec...: Specification (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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_W() #
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) 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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_R() #
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) 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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_WR() #
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) 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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_MD_N() #
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) 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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_MD_W() #
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) 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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_MD_R() #
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) 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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_MD_WR() #
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) 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() for more details on the behavior of
the generated function.
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 whenssam_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.
struct ssam_notifier_block #
Base notifier block for SSAM event notifications.
Definition
;
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 inenum ssam_notif_flags, converted from a standard error value viassam_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.
ssam_notifier_from_errno() #
u32 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.
ssam_notifier_to_errno() #
int 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.
struct ssam_event_registry #
Registry specification used for enabling events.
Definition
;
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.
struct ssam_event_id #
Unique event ID used for enabling events.
Definition
;
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.
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.
SSAM_EVENT_REGISTRY() #
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 specified by the given
parameters.
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.
struct ssam_event_notifier #
Notifier block for SSAM events.
Definition
;
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 (seeenum ssam_event_notifier_flags).
ssam_notifier_unregister() #
int 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.
ssam_controller_device() #
struct device * Get the struct device associated with this controller.
Parameters
struct ssam_controller *c: The controller for which to get the device.
Return
Returns the struct device associated with this controller,
providing its lower-level transport.
ssam_controller_get() #
struct ssam_controller * Increment reference count of controller.
Parameters
struct ssam_controller *c: The controller.
Return
Returns the controller provided as input.
ssam_controller_put() #
void Decrement reference count of controller.
Parameters
struct ssam_controller *c: The controller.
ssam_controller_statelock() #
void 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()
and ssam_controller_unlock() for that).
See ssam_controller_stateunlock() for the corresponding unlock function.
ssam_controller_stateunlock() #
void Unlock controller state transitions.
Parameters
struct ssam_controller *c: The controller to unlock.
Description
See ssam_controller_statelock() for the corresponding lock function.
ssam_request_write_data() #
ssize_t 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() 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.
ssam_request_sync_alloc() #
int 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() before
it can be submitted, and the message buffer data must still be set to the
returned buffer via 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(). The buffer must not be freed separately.
Return
Returns zero on success, -ENOMEM if the request could not be
allocated.
ssam_request_sync_free() #
void 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(). 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().
ssam_request_sync_init() #
int 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() and the actual message data has to be written
via ssam_request_write_data().
Return
Returns zero on success or -EINVAL if the given flags are invalid.
ssam_request_sync_submit() #
int 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() 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.
ssam_request_do_sync() #
int 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(), 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.
ssam_request_do_sync_with_buffer() #
int 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() macro can be used to compute the required
message buffer size.
This function does essentially the same as 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.
ssam_notifier_register() #
int 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.
__ssam_notifier_unregister() #
int 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.
ssam_controller_event_enable() #
int 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() 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.
ssam_controller_event_disable() #
int 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()/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.
ssam_get_controller() #
struct ssam_controller * 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()
is called when it doesn't need the controller any more.
ssam_client_link() #
int 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.
ssam_client_bind() #
struct ssam_controller * 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(), 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(). 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.
Client Bus and Client Device API #
enum ssam_device_domain #
SAM device domain.
Constants
SSAM_DOMAIN_VIRTUAL: Virtual device.SSAM_DOMAIN_SERIALHUB: Physical device connected via Surface Serial Hub.
enum ssam_virtual_tc #
Target categories for the virtual SAM domain.
Constants
SSAM_VIRTUAL_TC_HUB: Device hub category.
struct ssam_device_uid #
Unique identifier for SSAM device.
Definition
;
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.
SSAM_DEVICE() #
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 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.
SSAM_VDEV() #
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 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.
SSAM_SDEV() #
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 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.
struct ssam_device #
SSAM client device.
Definition
;
Members
dev: Driver model representation of the device.ctrl: SSAM controller managing this device.uid: UID identifying the device.flags: Device state flags, seeenum ssam_device_flags.
struct ssam_device_driver #
SSAM client device driver.
Definition
;
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.
is_ssam_device() #
bool 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, i.e. the device type points to ssam_device_type, and false
otherwise.
to_ssam_device() #
Casts the given device to a SSAM client device.
Parameters
d: The device to cast.
Description
Casts the given struct device to a struct ssam_device. The caller has to
ensure that the given device is actually enclosed in a struct ssam_device,
e.g. by calling is_ssam_device().
Return
Returns a pointer to the struct ssam_device wrapping the given
device d.
to_ssam_device_driver() #
Casts the given device driver to a SSAM client device driver.
Parameters
d: The driver to cast.
Description
Casts the given struct device_driver to a struct ssam_device_driver. The
caller has to ensure that the given driver is actually enclosed in a
struct ssam_device_driver.
Return
Returns the pointer to the struct ssam_device_driver wrapping the
given device driver d.
ssam_device_mark_hot_removed() #
void 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.
ssam_device_is_hot_removed() #
bool 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() for more details.
Return
Returns true if the device has been marked as hot-removed.
ssam_device_get() #
struct ssam_device * 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 via
get_device().
See ssam_device_put() for the counter-part of this function.
Return
Returns the device provided as input.
ssam_device_put() #
void 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 via
put_device().
See ssam_device_get() for the counter-part of this function.
ssam_device_get_drvdata() #
void * 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().
ssam_device_set_drvdata() #
void 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.
ssam_device_driver_register() #
Register a SSAM client device driver.
Parameters
drv: The driver to register.
module_ssam_device_driver() #
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() and
module_exit(). This macro may only be used once per module and replaces the
aforementioned definitions.
ssam_register_clients() #
int 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() for details.
Return
Returns zero on success, nonzero on failure.
ssam_device_register_clients() #
int 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() for details.
Return
Returns zero on success, nonzero on failure.
SSAM_DEFINE_SYNC_REQUEST_CL_N() #
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) 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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_CL_W() #
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) 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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_CL_R() #
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) 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() for more details on the behavior of
the generated function.
SSAM_DEFINE_SYNC_REQUEST_CL_WR() #
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) 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() for more details on the behavior of
the generated function.
ssam_device_notifier_register() #
int 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.
ssam_device_notifier_unregister() #
int 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.
ssam_device_alloc() #
struct ssam_device * 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().
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.
ssam_device_add() #
int 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() 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() and 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.
ssam_device_remove() #
void Remove a SSAM client device.
Parameters
struct ssam_device *sdev: The device to remove.
Description
Removes and unregisters the provided SSAM client device.
ssam_device_id_match() #
const struct ssam_device_id * 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.
ssam_device_get_match() #
const struct ssam_device_id * 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() 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.
ssam_device_get_match_data() #
const void * 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() 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.
__ssam_device_driver_register() #
int 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() macro for the normal way
to register a driver from inside its owning module.
ssam_device_driver_unregister() #
void Unregister a SSAM device driver.
Parameters
struct ssam_device_driver *sdrv: The driver to unregister.
__ssam_register_clients() #
int 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() for details.
Note that, generally, the use of either ssam_device_register_clients() or
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.
ssam_remove_clients() #
void 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()/ssam_device_remove() for more details.
Writing Client Drivers
Peios Kernel / Hardware and drivers / Driver development / surface_aggregator
For the API documentation, refer to:
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.
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:
static int
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.
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.
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.
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.
int
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:
;
This example defines a function
static int ;
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:
;
This invocation of the macro defines a function
static int ;
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()
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:
u32
int
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 #
struct sshp_buf #
Parser buffer for SSH messages.
Definition
;
Members
ptr: Pointer to the beginning of the buffer.len: Number of bytes used in the buffer.cap: Maximum capacity of the buffer.
sshp_buf_init() #
void 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.
sshp_buf_alloc() #
int 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.
sshp_buf_free() #
void 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().
sshp_buf_drop() #
void 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.
sshp_buf_read_from_fifo() #
size_t 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.
sshp_buf_span_from() #
void 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.
sshp_validate_crc() #
bool 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.
sshp_starts_with_syn() #
bool Check if the given data starts with SSH SYN bytes.
Parameters
const struct ssam_span *src: The data span to check the start of.
sshp_find_syn() #
bool 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.
sshp_parse_frame() #
int 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.
sshp_parse_command() #
int 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() 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.
struct msgbuf #
Buffer struct to construct SSH messages.
Definition
;
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.
msgb_init() #
void Initialize the given message buffer struct.
Parameters
struct msgbuf *msgb: The buffer struct to initializeu8 *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.
msgb_bytes_used() #
size_t Return the current number of bytes used in the buffer.
Parameters
const struct msgbuf *msgb: The message buffer.
msgb_push_u16() #
void Push a u16 value to the buffer.
Parameters
struct msgbuf *msgb: The message buffer.u16 value: The value to push to the buffer.
msgb_push_syn() #
void Push SSH SYN bytes to the buffer.
Parameters
struct msgbuf *msgb: The message buffer.
msgb_push_buf() #
void 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.
msgb_push_crc() #
void 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.
msgb_push_frame() #
void Push a SSH message frame header to the buffer.
Parameters
struct msgbuf *msgb: The message bufferu8 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.
msgb_push_ack() #
void Push a SSH ACK frame to the buffer.
Parameters
struct msgbuf *msgb: The message bufferu8 seq: The sequence ID of the frame/packet to be ACKed.
msgb_push_nak() #
void Push a SSH NAK frame to the buffer.
Parameters
struct msgbuf *msgb: The message buffer
msgb_push_cmd() #
void 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.
enum ssh_ptl_state_flags #
State-flags for 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.
struct ssh_ptl_ops #
Callback operations for packet transport layer.
Definition
;
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.
struct ssh_ptl #
SSH packet transport layer.
Definition
;
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.
ssh_ptl_get_device() #
struct device * 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.
ssh_ptl_tx_wakeup_transfer() #
void 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.
ssh_ptl_should_drop_ack_packet() #
bool 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.
ssh_ptl_should_drop_nak_packet() #
bool 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.
ssh_ptl_should_drop_dsq_packet() #
bool 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.
ssh_ptl_should_fail_write() #
int 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.
ssh_ptl_should_corrupt_tx_data() #
bool 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.
ssh_ptl_should_corrupt_rx_syn() #
bool 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.
ssh_ptl_should_corrupt_rx_data() #
bool 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.
ssh_packet_init() #
void 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. SeeSSH_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() before
submission, and must contain a valid SSH message, i.e. frame with optional
payload of any type.
ssh_ctrl_packet_cache_init() #
int Initialize the control packet cache.
Parameters
void: no arguments
ssh_ctrl_packet_cache_destroy() #
void Deinitialize the control packet cache.
Parameters
void: no arguments
ssh_ctrl_packet_alloc() #
int 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(), 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.
ssh_ctrl_packet_free() #
void Free packet allocated from control packet cache.
Parameters
struct ssh_packet *p: The packet to free.
ssh_ptl_tx_wakeup_packet() #
void 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.
ssh_ptl_tx_start() #
int Start packet transmitter thread.
Parameters
struct ssh_ptl *ptl: The packet transport layer.
Return
Returns zero on success, a negative error code on failure.
ssh_ptl_tx_stop() #
int Stop packet transmitter thread.
Parameters
struct ssh_ptl *ptl: The packet transport layer.
Return
Returns zero on success, a negative error code on failure.
ssh_ptl_submit() #
int 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.
ssh_ptl_cancel() #
void 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.
ssh_ptl_rx_start() #
int 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.
ssh_ptl_rx_stop() #
int 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.
ssh_ptl_rx_rcvbuf() #
ssize_t 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.
ssh_ptl_shutdown() #
void 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.
ssh_ptl_init() #
int 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() and
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.
ssh_ptl_destroy() #
void 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() before
this function can be called.
Request Transport Layer #
enum ssh_rtl_state_flags #
State-flags for 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.
struct ssh_rtl_ops #
Callback operations for request transport layer.
Definition
;
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 (notNULL).
struct ssh_rtl #
SSH request transport layer.
Definition
;
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.
ssh_rtl_get_device() #
struct device * 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.
ssh_request_rtl() #
struct ssh_rtl * 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 associated with the given SSH request.
ssh_rtl_should_drop_response() #
bool 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.
ssh_rtl_submit() #
int 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.
ssh_rtl_cancel() #
bool 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.
ssh_request_init() #
int 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() before submission and
must contain a valid SSH request message.
Return
Returns zero on success or -EINVAL if the given flags are invalid.
ssh_rtl_init() #
int 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(), 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.
ssh_rtl_destroy() #
void 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() before
this function can be called.
ssh_rtl_start() #
int 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.
ssh_rtl_flush() #
int Flush the request transport layer.
Parameters
struct ssh_rtl *rtl: request transport layerunsigned 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.
ssh_rtl_shutdown() #
void 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.
Controller #
struct ssh_seq_counter #
Safe counter for SSH sequence IDs.
Definition
;
Members
value: The current counter value.
struct ssh_rqid_counter #
Safe counter for SSH request IDs.
Definition
;
Members
value: The current counter value.
struct ssam_nf_head #
Notifier head for SSAM events.
Definition
;
Members
srcu: The SRCU struct for synchronization.head: List-head for notifier blocks registered under this head.
struct ssam_nf #
Notifier callback- and activation-registry for SSAM events.
Definition
;
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.
struct ssam_event_item #
Struct for event queuing and completion.
Definition
;
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.
struct ssam_event_queue #
Queue for completing received events.
Definition
;
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: Thestruct work_structperforming completion work for this queue.
struct ssam_event_target #
Set of queues for a single SSH target ID.
Definition
;
Members
queue: The array of queues, one queue per event ID.
struct ssam_cplt #
SSAM event/async request completion system.
Definition
;
Members
dev: The device with which this system is associated. Only used for logging.wq: Thestruct workqueue_structon which all completion work items are queued.event: Event completion management.event.target: Array ofstruct ssam_event_target, one for each target.event.notif: Notifier callbacks and event activation reference counting.
enum ssam_controller_state #
State values for 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.
struct ssam_controller_caps #
Controller device capabilities.
Definition
;
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.
struct ssam_controller #
SSAM controller device.
Definition
;
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.
ssam_controller_receive_buf() #
ssize_t 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.
ssam_controller_write_wakeup() #
void Notify the controller that the underlying device has space available for data to be written.
Parameters
struct ssam_controller *ctrl: The controller.
ssh_seq_reset() #
void Reset/initialize sequence ID counter.
Parameters
struct ssh_seq_counter *c: The counter to reset.
ssh_seq_next() #
u8 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.
ssh_rqid_reset() #
void Reset/initialize request ID counter.
Parameters
struct ssh_rqid_counter *c: The counter to reset.
ssh_rqid_next() #
u16 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.
ssam_event_matches_notifier() #
bool 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.
ssam_nfblk_call_chain() #
int 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() 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() to convert this value to the original error
value.
ssam_nfblk_insert() #
int 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.
ssam_nfblk_find() #
bool 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.
ssam_nfblk_remove() #
void 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() with nh->srcu after leaving the critical section, to
ensure that the removed notifier block is not in use any more.
ssam_nf_head_init() #
int Initialize the given notifier head.
Parameters
struct ssam_nf_head *nh: The notifier head to initialize.
ssam_nf_head_destroy() #
void Deinitialize the given notifier head.
Parameters
struct ssam_nf_head *nh: The notifier head to deinitialize.
struct ssam_nf_refcount_key #
Key used for event activation reference counting.
Definition
;
Members
reg: The registry via which the event is enabled/disabled.id: The ID uniquely describing the event.
struct ssam_nf_refcount_entry #
RB-tree entry for reference counting event activations.
Definition
;
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.
ssam_nf_refcount_inc() #
struct ssam_nf_refcount_entry * 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.
ssam_nf_refcount_dec() #
struct ssam_nf_refcount_entry * 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().
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.
ssam_nf_refcount_dec_free() #
void 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.
ssam_nf_refcount_empty() #
bool Test if the notification system has any enabled/active events.
Parameters
struct ssam_nf *nf: The notification system.
ssam_nf_call() #
void Call notification callbacks for the provided event.
Parameters
struct ssam_nf *nf: The notifier systemstruct 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() 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.
ssam_nf_init() #
int Initialize the notifier system.
Parameters
struct ssam_nf *nf: The notifier system to initialize.
ssam_nf_destroy() #
void Deinitialize the notifier system.
Parameters
struct ssam_nf *nf: The notifier system to deinitialize.
ssam_event_item_cache_init() #
int Initialize the event item cache.
Parameters
void: no arguments
ssam_event_item_cache_destroy() #
void Deinitialize the event item cache.
Parameters
void: no arguments
ssam_event_item_free() #
void Free the provided event item.
Parameters
struct ssam_event_item *item: The event item to free.
ssam_event_item_alloc() #
struct ssam_event_item * 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.
ssam_event_queue_push() #
void 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.
ssam_event_queue_pop() #
struct ssam_event_item * 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.
ssam_event_queue_is_empty() #
bool Check if the event queue is empty.
Parameters
struct ssam_event_queue *q: The event queue.
ssam_cplt_get_event_queue() #
struct ssam_event_queue * 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).
ssam_cplt_submit() #
bool 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.
ssam_cplt_submit_event() #
int 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.
ssam_cplt_flush() #
void 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.
ssam_event_queue_init() #
void 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.
ssam_cplt_init() #
int Initialize completion system.
Parameters
struct ssam_cplt *cplt: The completion system to initialize.struct device *dev: The device used for logging.
ssam_cplt_destroy() #
void 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.
ssam_controller_lock() #
void 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()
for more details on controller locking.
See ssam_controller_unlock() for the corresponding unlock function.
ssam_controller_caps_load_from_acpi() #
int 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.
ssam_controller_caps_load_from_of() #
int Load controller capabilities from OF/DT.
Parameters
struct device *dev: A pointer to the controller devicestruct ssam_controller_caps *caps: Where to store the capabilities in.
Return
Returns zero on success, a negative error code on failure.
ssam_controller_caps_load() #
int Load controller capabilities
Parameters
struct device *dev: A pointer to the controller devicestruct ssam_controller_caps *caps: Where to store the capabilities in.
Return
Returns zero on success, a negative error code on failure.
ssam_controller_init() #
int 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() and ssam_controller_write_wakeup(). Once the
controller has been hooked up, transmitter and receiver threads may be
started via ssam_controller_start(). These setup steps need to be completed
before controller can be used for requests.
ssam_controller_start() #
int 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() for more details on controller initialization.
This function must be called with the main controller lock held (i.e. by
calling ssam_controller_lock()).
ssam_controller_shutdown() #
void 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().
This function must be called with the main controller lock held (i.e. by
calling ssam_controller_lock()).
ssam_controller_destroy() #
void 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(). 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()).
ssam_controller_suspend() #
int 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() for the corresponding resume function.
Return
Returns -EINVAL if the controller is currently not in the
"started" state.
ssam_controller_resume() #
int 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(). 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.
struct ssh_notification_params #
Command payload to enable/disable SSH notifications.
Definition
;
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.
ssam_ssh_event_enable() #
int 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.
ssam_ssh_event_disable() #
int 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.
ssam_get_firmware_version() #
int 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.
ssam_ctrl_notif_display_off() #
int 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(), 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() 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.
ssam_ctrl_notif_display_on() #
int 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() 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() 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.
ssam_ctrl_notif_d0_exit() #
int 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() 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.
ssam_ctrl_notif_d0_entry() #
int 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() 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.
ssam_nf_refcount_enable() #
int 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() / 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.
ssam_nf_refcount_disable_free() #
int 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() / 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.
ssam_notifier_disable_registered() #
int 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() 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().
Return
Returns zero on success. In case of failure returns the error code returned by the failed EC command to disable an event.
ssam_notifier_restore_registered() #
void 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() for the counter part
disabling the events and more details.
ssam_notifier_is_empty() #
bool 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.
ssam_notifier_unregister_all() #
void 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.
ssam_irq_setup() #
int 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() and 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(). On teardown, the IRQ
should be freed via ssam_irq_free().
ssam_irq_free() #
void 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().
ssam_irq_arm_for_wakeup() #
int 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() 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() and ssam_irq_disarm_wakeup() must
be balanced.
ssam_irq_disarm_wakeup() #
void 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().
This function is intended to disarm the IRQ after exiting S2idle suspend.
Note
calls to ssam_irq_arm_for_wakeup() and ssam_irq_disarm_wakeup() must
be balanced.
Client Device Bus #
ssam_device_id_compatible() #
bool 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.
ssam_device_id_is_null() #
bool 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.
ssam_bus_register() #
int Register and set-up the SSAM client device bus.
Parameters
void: no arguments
ssam_bus_unregister() #
void Unregister the SSAM client device bus.
Parameters
void: no arguments
Core #
ssam_try_set_controller() #
int 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.
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.
Trace Helpers #
ssam_trace_ptr_uid() #
void 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.
ssam_trace_get_packet_seq() #
u16 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).
ssam_trace_get_request_id() #
u32 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).
ssam_trace_get_request_tid() #
u32 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).
ssam_trace_get_request_sid() #
u32 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).
ssam_trace_get_request_tc() #
u32 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:
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 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 before continuing with the architectural overview below.
Packet Transport Layer #
The packet transport layer is represented via struct ssh_ptl <ssh_ptl> and is structured around the following key concepts:
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 thecomplete()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.
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.
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.
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 for the reasoning behind this). Control packets (i.e. ACK and NAK) can always be transmitted.
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.
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.
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).
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:
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 thecomplete()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.
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.
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).
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.
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.
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.
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.
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.
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>).
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.
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.
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 responsibilities and feature-set have since been expanded significantly with the following generations.
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.
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.
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 for a more technical protocol documentation and Documentation/driver-api/surface_aggregator/internal.rst 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 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.
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:
|
Field |
Type |
Description |
|---|---|---|
|
|
|
Type identifier of the frame. |
|
|
|
Length of the payload associated with the frame. |
|
|
|
Sequence ID (see explanation below). |
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:
|
Name |
Value |
Description |
|---|---|---|
|
|
|
Synchronization bytes. |
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>):
|
Name |
Value |
Short Description |
|---|---|---|
|
|
|
Sent on error in previously received message. |
|
|
|
Sent to acknowledge receival of |
|
|
|
Sent to transfer data. Sequenced. |
|
|
|
Same as |
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.
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:
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:
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:
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.
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:
|
Field |
Type |
Description |
|---|---|---|
|
|
|
Type of the payload. For commands always |
|
|
|
Target category. |
|
|
|
Target ID for commands/messages. |
|
|
|
Source ID for commands/messages. |
|
|
|
Instance ID. |
|
|
|
Request ID. |
|
|
|
Command ID. |
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.
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.