Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0+
0002 /*
0003  * SSH packet transport layer.
0004  *
0005  * Copyright (C) 2019-2022 Maximilian Luz <luzmaximilian@gmail.com>
0006  */
0007 
0008 #include <asm/unaligned.h>
0009 #include <linux/atomic.h>
0010 #include <linux/error-injection.h>
0011 #include <linux/jiffies.h>
0012 #include <linux/kfifo.h>
0013 #include <linux/kref.h>
0014 #include <linux/kthread.h>
0015 #include <linux/ktime.h>
0016 #include <linux/limits.h>
0017 #include <linux/list.h>
0018 #include <linux/lockdep.h>
0019 #include <linux/serdev.h>
0020 #include <linux/slab.h>
0021 #include <linux/spinlock.h>
0022 #include <linux/workqueue.h>
0023 
0024 #include <linux/surface_aggregator/serial_hub.h>
0025 
0026 #include "ssh_msgb.h"
0027 #include "ssh_packet_layer.h"
0028 #include "ssh_parser.h"
0029 
0030 #include "trace.h"
0031 
0032 /*
0033  * To simplify reasoning about the code below, we define a few concepts. The
0034  * system below is similar to a state-machine for packets, however, there are
0035  * too many states to explicitly write them down. To (somewhat) manage the
0036  * states and packets we rely on flags, reference counting, and some simple
0037  * concepts. State transitions are triggered by actions.
0038  *
0039  * >> Actions <<
0040  *
0041  * - submit
0042  * - transmission start (process next item in queue)
0043  * - transmission finished (guaranteed to never be parallel to transmission
0044  *   start)
0045  * - ACK received
0046  * - NAK received (this is equivalent to issuing re-submit for all pending
0047  *   packets)
0048  * - timeout (this is equivalent to re-issuing a submit or canceling)
0049  * - cancel (non-pending and pending)
0050  *
0051  * >> Data Structures, Packet Ownership, General Overview <<
0052  *
0053  * The code below employs two main data structures: The packet queue,
0054  * containing all packets scheduled for transmission, and the set of pending
0055  * packets, containing all packets awaiting an ACK.
0056  *
0057  * Shared ownership of a packet is controlled via reference counting. Inside
0058  * the transport system are a total of five packet owners:
0059  *
0060  * - the packet queue,
0061  * - the pending set,
0062  * - the transmitter thread,
0063  * - the receiver thread (via ACKing), and
0064  * - the timeout work item.
0065  *
0066  * Normal operation is as follows: The initial reference of the packet is
0067  * obtained by submitting the packet and queuing it. The receiver thread takes
0068  * packets from the queue. By doing this, it does not increment the refcount
0069  * but takes over the reference (removing it from the queue). If the packet is
0070  * sequenced (i.e. needs to be ACKed by the client), the transmitter thread
0071  * sets-up the timeout and adds the packet to the pending set before starting
0072  * to transmit it. As the timeout is handled by a reaper task, no additional
0073  * reference for it is needed. After the transmit is done, the reference held
0074  * by the transmitter thread is dropped. If the packet is unsequenced (i.e.
0075  * does not need an ACK), the packet is completed by the transmitter thread
0076  * before dropping that reference.
0077  *
0078  * On receival of an ACK, the receiver thread removes and obtains the
0079  * reference to the packet from the pending set. The receiver thread will then
0080  * complete the packet and drop its reference.
0081  *
0082  * On receival of a NAK, the receiver thread re-submits all currently pending
0083  * packets.
0084  *
0085  * Packet timeouts are detected by the timeout reaper. This is a task,
0086  * scheduled depending on the earliest packet timeout expiration date,
0087  * checking all currently pending packets if their timeout has expired. If the
0088  * timeout of a packet has expired, it is re-submitted and the number of tries
0089  * of this packet is incremented. If this number reaches its limit, the packet
0090  * will be completed with a failure.
0091  *
0092  * On transmission failure (such as repeated packet timeouts), the completion
0093  * callback is immediately run by on thread on which the error was detected.
0094  *
0095  * To ensure that a packet eventually leaves the system it is marked as
0096  * "locked" directly before it is going to be completed or when it is
0097  * canceled. Marking a packet as "locked" has the effect that passing and
0098  * creating new references of the packet is disallowed. This means that the
0099  * packet cannot be added to the queue, the pending set, and the timeout, or
0100  * be picked up by the transmitter thread or receiver thread. To remove a
0101  * packet from the system it has to be marked as locked and subsequently all
0102  * references from the data structures (queue, pending) have to be removed.
0103  * References held by threads will eventually be dropped automatically as
0104  * their execution progresses.
0105  *
0106  * Note that the packet completion callback is, in case of success and for a
0107  * sequenced packet, guaranteed to run on the receiver thread, thus providing
0108  * a way to reliably identify responses to the packet. The packet completion
0109  * callback is only run once and it does not indicate that the packet has
0110  * fully left the system (for this, one should rely on the release method,
0111  * triggered when the reference count of the packet reaches zero). In case of
0112  * re-submission (and with somewhat unlikely timing), it may be possible that
0113  * the packet is being re-transmitted while the completion callback runs.
0114  * Completion will occur both on success and internal error, as well as when
0115  * the packet is canceled.
0116  *
0117  * >> Flags <<
0118  *
0119  * Flags are used to indicate the state and progression of a packet. Some flags
0120  * have stricter guarantees than other:
0121  *
0122  * - locked
0123  *   Indicates if the packet is locked. If the packet is locked, passing and/or
0124  *   creating additional references to the packet is forbidden. The packet thus
0125  *   may not be queued, dequeued, or removed or added to the pending set. Note
0126  *   that the packet state flags may still change (e.g. it may be marked as
0127  *   ACKed, transmitted, ...).
0128  *
0129  * - completed
0130  *   Indicates if the packet completion callback has been executed or is about
0131  *   to be executed. This flag is used to ensure that the packet completion
0132  *   callback is only run once.
0133  *
0134  * - queued
0135  *   Indicates if a packet is present in the submission queue or not. This flag
0136  *   must only be modified with the queue lock held, and must be coherent to the
0137  *   presence of the packet in the queue.
0138  *
0139  * - pending
0140  *   Indicates if a packet is present in the set of pending packets or not.
0141  *   This flag must only be modified with the pending lock held, and must be
0142  *   coherent to the presence of the packet in the pending set.
0143  *
0144  * - transmitting
0145  *   Indicates if the packet is currently transmitting. In case of
0146  *   re-transmissions, it is only safe to wait on the "transmitted" completion
0147  *   after this flag has been set. The completion will be set both in success
0148  *   and error case.
0149  *
0150  * - transmitted
0151  *   Indicates if the packet has been transmitted. This flag is not cleared by
0152  *   the system, thus it indicates the first transmission only.
0153  *
0154  * - acked
0155  *   Indicates if the packet has been acknowledged by the client. There are no
0156  *   other guarantees given. For example, the packet may still be canceled
0157  *   and/or the completion may be triggered an error even though this bit is
0158  *   set. Rely on the status provided to the completion callback instead.
0159  *
0160  * - canceled
0161  *   Indicates if the packet has been canceled from the outside. There are no
0162  *   other guarantees given. Specifically, the packet may be completed by
0163  *   another part of the system before the cancellation attempts to complete it.
0164  *
0165  * >> General Notes <<
0166  *
0167  * - To avoid deadlocks, if both queue and pending locks are required, the
0168  *   pending lock must be acquired before the queue lock.
0169  *
0170  * - The packet priority must be accessed only while holding the queue lock.
0171  *
0172  * - The packet timestamp must be accessed only while holding the pending
0173  *   lock.
0174  */
0175 
0176 /*
0177  * SSH_PTL_MAX_PACKET_TRIES - Maximum transmission attempts for packet.
0178  *
0179  * Maximum number of transmission attempts per sequenced packet in case of
0180  * time-outs. Must be smaller than 16. If the packet times out after this
0181  * amount of tries, the packet will be completed with %-ETIMEDOUT as status
0182  * code.
0183  */
0184 #define SSH_PTL_MAX_PACKET_TRIES        3
0185 
0186 /*
0187  * SSH_PTL_TX_TIMEOUT - Packet transmission timeout.
0188  *
0189  * Timeout in jiffies for packet transmission via the underlying serial
0190  * device. If transmitting the packet takes longer than this timeout, the
0191  * packet will be completed with -ETIMEDOUT. It will not be re-submitted.
0192  */
0193 #define SSH_PTL_TX_TIMEOUT          HZ
0194 
0195 /*
0196  * SSH_PTL_PACKET_TIMEOUT - Packet response timeout.
0197  *
0198  * Timeout as ktime_t delta for ACKs. If we have not received an ACK in this
0199  * time-frame after starting transmission, the packet will be re-submitted.
0200  */
0201 #define SSH_PTL_PACKET_TIMEOUT          ms_to_ktime(1000)
0202 
0203 /*
0204  * SSH_PTL_PACKET_TIMEOUT_RESOLUTION - Packet timeout granularity.
0205  *
0206  * Time-resolution for timeouts. Should be larger than one jiffy to avoid
0207  * direct re-scheduling of reaper work_struct.
0208  */
0209 #define SSH_PTL_PACKET_TIMEOUT_RESOLUTION   ms_to_ktime(max(2000 / HZ, 50))
0210 
0211 /*
0212  * SSH_PTL_MAX_PENDING - Maximum number of pending packets.
0213  *
0214  * Maximum number of sequenced packets concurrently waiting for an ACK.
0215  * Packets marked as blocking will not be transmitted while this limit is
0216  * reached.
0217  */
0218 #define SSH_PTL_MAX_PENDING         1
0219 
0220 /*
0221  * SSH_PTL_RX_BUF_LEN - Evaluation-buffer size in bytes.
0222  */
0223 #define SSH_PTL_RX_BUF_LEN          4096
0224 
0225 /*
0226  * SSH_PTL_RX_FIFO_LEN - Fifo input-buffer size in bytes.
0227  */
0228 #define SSH_PTL_RX_FIFO_LEN         4096
0229 
0230 #ifdef CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION
0231 
0232 /**
0233  * ssh_ptl_should_drop_ack_packet() - Error injection hook to drop ACK packets.
0234  *
0235  * Useful to test detection and handling of automated re-transmits by the EC.
0236  * Specifically of packets that the EC considers not-ACKed but the driver
0237  * already considers ACKed (due to dropped ACK). In this case, the EC
0238  * re-transmits the packet-to-be-ACKed and the driver should detect it as
0239  * duplicate/already handled. Note that the driver should still send an ACK
0240  * for the re-transmitted packet.
0241  */
0242 static noinline bool ssh_ptl_should_drop_ack_packet(void)
0243 {
0244     return false;
0245 }
0246 ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_ack_packet, TRUE);
0247 
0248 /**
0249  * ssh_ptl_should_drop_nak_packet() - Error injection hook to drop NAK packets.
0250  *
0251  * Useful to test/force automated (timeout-based) re-transmit by the EC.
0252  * Specifically, packets that have not reached the driver completely/with valid
0253  * checksums. Only useful in combination with receival of (injected) bad data.
0254  */
0255 static noinline bool ssh_ptl_should_drop_nak_packet(void)
0256 {
0257     return false;
0258 }
0259 ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_nak_packet, TRUE);
0260 
0261 /**
0262  * ssh_ptl_should_drop_dsq_packet() - Error injection hook to drop sequenced
0263  * data packet.
0264  *
0265  * Useful to test re-transmit timeout of the driver. If the data packet has not
0266  * been ACKed after a certain time, the driver should re-transmit the packet up
0267  * to limited number of times defined in SSH_PTL_MAX_PACKET_TRIES.
0268  */
0269 static noinline bool ssh_ptl_should_drop_dsq_packet(void)
0270 {
0271     return false;
0272 }
0273 ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_dsq_packet, TRUE);
0274 
0275 /**
0276  * ssh_ptl_should_fail_write() - Error injection hook to make
0277  * serdev_device_write() fail.
0278  *
0279  * Hook to simulate errors in serdev_device_write when transmitting packets.
0280  */
0281 static noinline int ssh_ptl_should_fail_write(void)
0282 {
0283     return 0;
0284 }
0285 ALLOW_ERROR_INJECTION(ssh_ptl_should_fail_write, ERRNO);
0286 
0287 /**
0288  * ssh_ptl_should_corrupt_tx_data() - Error injection hook to simulate invalid
0289  * data being sent to the EC.
0290  *
0291  * Hook to simulate corrupt/invalid data being sent from host (driver) to EC.
0292  * Causes the packet data to be actively corrupted by overwriting it with
0293  * pre-defined values, such that it becomes invalid, causing the EC to respond
0294  * with a NAK packet. Useful to test handling of NAK packets received by the
0295  * driver.
0296  */
0297 static noinline bool ssh_ptl_should_corrupt_tx_data(void)
0298 {
0299     return false;
0300 }
0301 ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_tx_data, TRUE);
0302 
0303 /**
0304  * ssh_ptl_should_corrupt_rx_syn() - Error injection hook to simulate invalid
0305  * data being sent by the EC.
0306  *
0307  * Hook to simulate invalid SYN bytes, i.e. an invalid start of messages and
0308  * test handling thereof in the driver.
0309  */
0310 static noinline bool ssh_ptl_should_corrupt_rx_syn(void)
0311 {
0312     return false;
0313 }
0314 ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_syn, TRUE);
0315 
0316 /**
0317  * ssh_ptl_should_corrupt_rx_data() - Error injection hook to simulate invalid
0318  * data being sent by the EC.
0319  *
0320  * Hook to simulate invalid data/checksum of the message frame and test handling
0321  * thereof in the driver.
0322  */
0323 static noinline bool ssh_ptl_should_corrupt_rx_data(void)
0324 {
0325     return false;
0326 }
0327 ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_data, TRUE);
0328 
0329 static bool __ssh_ptl_should_drop_ack_packet(struct ssh_packet *packet)
0330 {
0331     if (likely(!ssh_ptl_should_drop_ack_packet()))
0332         return false;
0333 
0334     trace_ssam_ei_tx_drop_ack_packet(packet);
0335     ptl_info(packet->ptl, "packet error injection: dropping ACK packet %p\n",
0336          packet);
0337 
0338     return true;
0339 }
0340 
0341 static bool __ssh_ptl_should_drop_nak_packet(struct ssh_packet *packet)
0342 {
0343     if (likely(!ssh_ptl_should_drop_nak_packet()))
0344         return false;
0345 
0346     trace_ssam_ei_tx_drop_nak_packet(packet);
0347     ptl_info(packet->ptl, "packet error injection: dropping NAK packet %p\n",
0348          packet);
0349 
0350     return true;
0351 }
0352 
0353 static bool __ssh_ptl_should_drop_dsq_packet(struct ssh_packet *packet)
0354 {
0355     if (likely(!ssh_ptl_should_drop_dsq_packet()))
0356         return false;
0357 
0358     trace_ssam_ei_tx_drop_dsq_packet(packet);
0359     ptl_info(packet->ptl,
0360          "packet error injection: dropping sequenced data packet %p\n",
0361          packet);
0362 
0363     return true;
0364 }
0365 
0366 static bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
0367 {
0368     /* Ignore packets that don't carry any data (i.e. flush). */
0369     if (!packet->data.ptr || !packet->data.len)
0370         return false;
0371 
0372     switch (packet->data.ptr[SSH_MSGOFFSET_FRAME(type)]) {
0373     case SSH_FRAME_TYPE_ACK:
0374         return __ssh_ptl_should_drop_ack_packet(packet);
0375 
0376     case SSH_FRAME_TYPE_NAK:
0377         return __ssh_ptl_should_drop_nak_packet(packet);
0378 
0379     case SSH_FRAME_TYPE_DATA_SEQ:
0380         return __ssh_ptl_should_drop_dsq_packet(packet);
0381 
0382     default:
0383         return false;
0384     }
0385 }
0386 
0387 static int ssh_ptl_write_buf(struct ssh_ptl *ptl, struct ssh_packet *packet,
0388                  const unsigned char *buf, size_t count)
0389 {
0390     int status;
0391 
0392     status = ssh_ptl_should_fail_write();
0393     if (unlikely(status)) {
0394         trace_ssam_ei_tx_fail_write(packet, status);
0395         ptl_info(packet->ptl,
0396              "packet error injection: simulating transmit error %d, packet %p\n",
0397              status, packet);
0398 
0399         return status;
0400     }
0401 
0402     return serdev_device_write_buf(ptl->serdev, buf, count);
0403 }
0404 
0405 static void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
0406 {
0407     /* Ignore packets that don't carry any data (i.e. flush). */
0408     if (!packet->data.ptr || !packet->data.len)
0409         return;
0410 
0411     /* Only allow sequenced data packets to be modified. */
0412     if (packet->data.ptr[SSH_MSGOFFSET_FRAME(type)] != SSH_FRAME_TYPE_DATA_SEQ)
0413         return;
0414 
0415     if (likely(!ssh_ptl_should_corrupt_tx_data()))
0416         return;
0417 
0418     trace_ssam_ei_tx_corrupt_data(packet);
0419     ptl_info(packet->ptl,
0420          "packet error injection: simulating invalid transmit data on packet %p\n",
0421          packet);
0422 
0423     /*
0424      * NB: The value 0xb3 has been chosen more or less randomly so that it
0425      * doesn't have any (major) overlap with the SYN bytes (aa 55) and is
0426      * non-trivial (i.e. non-zero, non-0xff).
0427      */
0428     memset(packet->data.ptr, 0xb3, packet->data.len);
0429 }
0430 
0431 static void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
0432                       struct ssam_span *data)
0433 {
0434     struct ssam_span frame;
0435 
0436     /* Check if there actually is something to corrupt. */
0437     if (!sshp_find_syn(data, &frame))
0438         return;
0439 
0440     if (likely(!ssh_ptl_should_corrupt_rx_syn()))
0441         return;
0442 
0443     trace_ssam_ei_rx_corrupt_syn(data->len);
0444 
0445     data->ptr[1] = 0xb3;    /* Set second byte of SYN to "random" value. */
0446 }
0447 
0448 static void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
0449                        struct ssam_span *frame)
0450 {
0451     size_t payload_len, message_len;
0452     struct ssh_frame *sshf;
0453 
0454     /* Ignore incomplete messages, will get handled once it's complete. */
0455     if (frame->len < SSH_MESSAGE_LENGTH(0))
0456         return;
0457 
0458     /* Ignore incomplete messages, part 2. */
0459     payload_len = get_unaligned_le16(&frame->ptr[SSH_MSGOFFSET_FRAME(len)]);
0460     message_len = SSH_MESSAGE_LENGTH(payload_len);
0461     if (frame->len < message_len)
0462         return;
0463 
0464     if (likely(!ssh_ptl_should_corrupt_rx_data()))
0465         return;
0466 
0467     sshf = (struct ssh_frame *)&frame->ptr[SSH_MSGOFFSET_FRAME(type)];
0468     trace_ssam_ei_rx_corrupt_data(sshf);
0469 
0470     /*
0471      * Flip bits in first byte of payload checksum. This is basically
0472      * equivalent to a payload/frame data error without us having to worry
0473      * about (the, arguably pretty small, probability of) accidental
0474      * checksum collisions.
0475      */
0476     frame->ptr[frame->len - 2] = ~frame->ptr[frame->len - 2];
0477 }
0478 
0479 #else /* CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION */
0480 
0481 static inline bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
0482 {
0483     return false;
0484 }
0485 
0486 static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
0487                     struct ssh_packet *packet,
0488                     const unsigned char *buf,
0489                     size_t count)
0490 {
0491     return serdev_device_write_buf(ptl->serdev, buf, count);
0492 }
0493 
0494 static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
0495 {
0496 }
0497 
0498 static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
0499                          struct ssam_span *data)
0500 {
0501 }
0502 
0503 static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
0504                           struct ssam_span *frame)
0505 {
0506 }
0507 
0508 #endif /* CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION */
0509 
0510 static void __ssh_ptl_packet_release(struct kref *kref)
0511 {
0512     struct ssh_packet *p = container_of(kref, struct ssh_packet, refcnt);
0513 
0514     trace_ssam_packet_release(p);
0515 
0516     ptl_dbg_cond(p->ptl, "ptl: releasing packet %p\n", p);
0517     p->ops->release(p);
0518 }
0519 
0520 /**
0521  * ssh_packet_get() - Increment reference count of packet.
0522  * @packet: The packet to increment the reference count of.
0523  *
0524  * Increments the reference count of the given packet. See ssh_packet_put()
0525  * for the counter-part of this function.
0526  *
0527  * Return: Returns the packet provided as input.
0528  */
0529 struct ssh_packet *ssh_packet_get(struct ssh_packet *packet)
0530 {
0531     if (packet)
0532         kref_get(&packet->refcnt);
0533     return packet;
0534 }
0535 EXPORT_SYMBOL_GPL(ssh_packet_get);
0536 
0537 /**
0538  * ssh_packet_put() - Decrement reference count of packet.
0539  * @packet: The packet to decrement the reference count of.
0540  *
0541  * If the reference count reaches zero, the ``release`` callback specified in
0542  * the packet's &struct ssh_packet_ops, i.e. ``packet->ops->release``, will be
0543  * called.
0544  *
0545  * See ssh_packet_get() for the counter-part of this function.
0546  */
0547 void ssh_packet_put(struct ssh_packet *packet)
0548 {
0549     if (packet)
0550         kref_put(&packet->refcnt, __ssh_ptl_packet_release);
0551 }
0552 EXPORT_SYMBOL_GPL(ssh_packet_put);
0553 
0554 static u8 ssh_packet_get_seq(struct ssh_packet *packet)
0555 {
0556     return packet->data.ptr[SSH_MSGOFFSET_FRAME(seq)];
0557 }
0558 
0559 /**
0560  * ssh_packet_init() - Initialize SSH packet.
0561  * @packet:   The packet to initialize.
0562  * @type:     Type-flags of the packet.
0563  * @priority: Priority of the packet. See SSH_PACKET_PRIORITY() for details.
0564  * @ops:      Packet operations.
0565  *
0566  * Initializes the given SSH packet. Sets the transmission buffer pointer to
0567  * %NULL and the transmission buffer length to zero. For data-type packets,
0568  * this buffer has to be set separately via ssh_packet_set_data() before
0569  * submission, and must contain a valid SSH message, i.e. frame with optional
0570  * payload of any type.
0571  */
0572 void ssh_packet_init(struct ssh_packet *packet, unsigned long type,
0573              u8 priority, const struct ssh_packet_ops *ops)
0574 {
0575     kref_init(&packet->refcnt);
0576 
0577     packet->ptl = NULL;
0578     INIT_LIST_HEAD(&packet->queue_node);
0579     INIT_LIST_HEAD(&packet->pending_node);
0580 
0581     packet->state = type & SSH_PACKET_FLAGS_TY_MASK;
0582     packet->priority = priority;
0583     packet->timestamp = KTIME_MAX;
0584 
0585     packet->data.ptr = NULL;
0586     packet->data.len = 0;
0587 
0588     packet->ops = ops;
0589 }
0590 
0591 static struct kmem_cache *ssh_ctrl_packet_cache;
0592 
0593 /**
0594  * ssh_ctrl_packet_cache_init() - Initialize the control packet cache.
0595  */
0596 int ssh_ctrl_packet_cache_init(void)
0597 {
0598     const unsigned int size = sizeof(struct ssh_packet) + SSH_MSG_LEN_CTRL;
0599     const unsigned int align = __alignof__(struct ssh_packet);
0600     struct kmem_cache *cache;
0601 
0602     cache = kmem_cache_create("ssam_ctrl_packet", size, align, 0, NULL);
0603     if (!cache)
0604         return -ENOMEM;
0605 
0606     ssh_ctrl_packet_cache = cache;
0607     return 0;
0608 }
0609 
0610 /**
0611  * ssh_ctrl_packet_cache_destroy() - Deinitialize the control packet cache.
0612  */
0613 void ssh_ctrl_packet_cache_destroy(void)
0614 {
0615     kmem_cache_destroy(ssh_ctrl_packet_cache);
0616     ssh_ctrl_packet_cache = NULL;
0617 }
0618 
0619 /**
0620  * ssh_ctrl_packet_alloc() - Allocate packet from control packet cache.
0621  * @packet: Where the pointer to the newly allocated packet should be stored.
0622  * @buffer: The buffer corresponding to this packet.
0623  * @flags:  Flags used for allocation.
0624  *
0625  * Allocates a packet and corresponding transport buffer from the control
0626  * packet cache. Sets the packet's buffer reference to the allocated buffer.
0627  * The packet must be freed via ssh_ctrl_packet_free(), which will also free
0628  * the corresponding buffer. The corresponding buffer must not be freed
0629  * separately. Intended to be used with %ssh_ptl_ctrl_packet_ops as packet
0630  * operations.
0631  *
0632  * Return: Returns zero on success, %-ENOMEM if the allocation failed.
0633  */
0634 static int ssh_ctrl_packet_alloc(struct ssh_packet **packet,
0635                  struct ssam_span *buffer, gfp_t flags)
0636 {
0637     *packet = kmem_cache_alloc(ssh_ctrl_packet_cache, flags);
0638     if (!*packet)
0639         return -ENOMEM;
0640 
0641     buffer->ptr = (u8 *)(*packet + 1);
0642     buffer->len = SSH_MSG_LEN_CTRL;
0643 
0644     trace_ssam_ctrl_packet_alloc(*packet, buffer->len);
0645     return 0;
0646 }
0647 
0648 /**
0649  * ssh_ctrl_packet_free() - Free packet allocated from control packet cache.
0650  * @p: The packet to free.
0651  */
0652 static void ssh_ctrl_packet_free(struct ssh_packet *p)
0653 {
0654     trace_ssam_ctrl_packet_free(p);
0655     kmem_cache_free(ssh_ctrl_packet_cache, p);
0656 }
0657 
0658 static const struct ssh_packet_ops ssh_ptl_ctrl_packet_ops = {
0659     .complete = NULL,
0660     .release = ssh_ctrl_packet_free,
0661 };
0662 
0663 static void ssh_ptl_timeout_reaper_mod(struct ssh_ptl *ptl, ktime_t now,
0664                        ktime_t expires)
0665 {
0666     unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
0667     ktime_t aexp = ktime_add(expires, SSH_PTL_PACKET_TIMEOUT_RESOLUTION);
0668 
0669     spin_lock(&ptl->rtx_timeout.lock);
0670 
0671     /* Re-adjust / schedule reaper only if it is above resolution delta. */
0672     if (ktime_before(aexp, ptl->rtx_timeout.expires)) {
0673         ptl->rtx_timeout.expires = expires;
0674         mod_delayed_work(system_wq, &ptl->rtx_timeout.reaper, delta);
0675     }
0676 
0677     spin_unlock(&ptl->rtx_timeout.lock);
0678 }
0679 
0680 /* Must be called with queue lock held. */
0681 static void ssh_packet_next_try(struct ssh_packet *p)
0682 {
0683     u8 base = ssh_packet_priority_get_base(p->priority);
0684     u8 try = ssh_packet_priority_get_try(p->priority);
0685 
0686     lockdep_assert_held(&p->ptl->queue.lock);
0687 
0688     /*
0689      * Ensure that we write the priority in one go via WRITE_ONCE() so we
0690      * can access it via READ_ONCE() for tracing. Note that other access
0691      * is guarded by the queue lock, so no need to use READ_ONCE() there.
0692      */
0693     WRITE_ONCE(p->priority, __SSH_PACKET_PRIORITY(base, try + 1));
0694 }
0695 
0696 /* Must be called with queue lock held. */
0697 static struct list_head *__ssh_ptl_queue_find_entrypoint(struct ssh_packet *p)
0698 {
0699     struct list_head *head;
0700     struct ssh_packet *q;
0701 
0702     lockdep_assert_held(&p->ptl->queue.lock);
0703 
0704     /*
0705      * We generally assume that there are less control (ACK/NAK) packets
0706      * and re-submitted data packets as there are normal data packets (at
0707      * least in situations in which many packets are queued; if there
0708      * aren't many packets queued the decision on how to iterate should be
0709      * basically irrelevant; the number of control/data packets is more or
0710      * less limited via the maximum number of pending packets). Thus, when
0711      * inserting a control or re-submitted data packet, (determined by
0712      * their priority), we search from front to back. Normal data packets
0713      * are, usually queued directly at the tail of the queue, so for those
0714      * search from back to front.
0715      */
0716 
0717     if (p->priority > SSH_PACKET_PRIORITY(DATA, 0)) {
0718         list_for_each(head, &p->ptl->queue.head) {
0719             q = list_entry(head, struct ssh_packet, queue_node);
0720 
0721             if (q->priority < p->priority)
0722                 break;
0723         }
0724     } else {
0725         list_for_each_prev(head, &p->ptl->queue.head) {
0726             q = list_entry(head, struct ssh_packet, queue_node);
0727 
0728             if (q->priority >= p->priority) {
0729                 head = head->next;
0730                 break;
0731             }
0732         }
0733     }
0734 
0735     return head;
0736 }
0737 
0738 /* Must be called with queue lock held. */
0739 static int __ssh_ptl_queue_push(struct ssh_packet *packet)
0740 {
0741     struct ssh_ptl *ptl = packet->ptl;
0742     struct list_head *head;
0743 
0744     lockdep_assert_held(&ptl->queue.lock);
0745 
0746     if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
0747         return -ESHUTDOWN;
0748 
0749     /* Avoid further transitions when canceling/completing. */
0750     if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state))
0751         return -EINVAL;
0752 
0753     /* If this packet has already been queued, do not add it. */
0754     if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state))
0755         return -EALREADY;
0756 
0757     head = __ssh_ptl_queue_find_entrypoint(packet);
0758 
0759     list_add_tail(&ssh_packet_get(packet)->queue_node, head);
0760     return 0;
0761 }
0762 
0763 static int ssh_ptl_queue_push(struct ssh_packet *packet)
0764 {
0765     int status;
0766 
0767     spin_lock(&packet->ptl->queue.lock);
0768     status = __ssh_ptl_queue_push(packet);
0769     spin_unlock(&packet->ptl->queue.lock);
0770 
0771     return status;
0772 }
0773 
0774 static void ssh_ptl_queue_remove(struct ssh_packet *packet)
0775 {
0776     struct ssh_ptl *ptl = packet->ptl;
0777 
0778     spin_lock(&ptl->queue.lock);
0779 
0780     if (!test_and_clear_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
0781         spin_unlock(&ptl->queue.lock);
0782         return;
0783     }
0784 
0785     list_del(&packet->queue_node);
0786 
0787     spin_unlock(&ptl->queue.lock);
0788     ssh_packet_put(packet);
0789 }
0790 
0791 static void ssh_ptl_pending_push(struct ssh_packet *p)
0792 {
0793     struct ssh_ptl *ptl = p->ptl;
0794     const ktime_t timestamp = ktime_get_coarse_boottime();
0795     const ktime_t timeout = ptl->rtx_timeout.timeout;
0796 
0797     /*
0798      * Note: We can get the time for the timestamp before acquiring the
0799      * lock as this is the only place we're setting it and this function
0800      * is called only from the transmitter thread. Thus it is not possible
0801      * to overwrite the timestamp with an outdated value below.
0802      */
0803 
0804     spin_lock(&ptl->pending.lock);
0805 
0806     /* If we are canceling/completing this packet, do not add it. */
0807     if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state)) {
0808         spin_unlock(&ptl->pending.lock);
0809         return;
0810     }
0811 
0812     /*
0813      * On re-submission, the packet has already been added the pending
0814      * set. We still need to update the timestamp as the packet timeout is
0815      * reset for each (re-)submission.
0816      */
0817     p->timestamp = timestamp;
0818 
0819     /* In case it is already pending (e.g. re-submission), do not add it. */
0820     if (!test_and_set_bit(SSH_PACKET_SF_PENDING_BIT, &p->state)) {
0821         atomic_inc(&ptl->pending.count);
0822         list_add_tail(&ssh_packet_get(p)->pending_node, &ptl->pending.head);
0823     }
0824 
0825     spin_unlock(&ptl->pending.lock);
0826 
0827     /* Arm/update timeout reaper. */
0828     ssh_ptl_timeout_reaper_mod(ptl, timestamp, timestamp + timeout);
0829 }
0830 
0831 static void ssh_ptl_pending_remove(struct ssh_packet *packet)
0832 {
0833     struct ssh_ptl *ptl = packet->ptl;
0834 
0835     spin_lock(&ptl->pending.lock);
0836 
0837     if (!test_and_clear_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state)) {
0838         spin_unlock(&ptl->pending.lock);
0839         return;
0840     }
0841 
0842     list_del(&packet->pending_node);
0843     atomic_dec(&ptl->pending.count);
0844 
0845     spin_unlock(&ptl->pending.lock);
0846 
0847     ssh_packet_put(packet);
0848 }
0849 
0850 /* Warning: Does not check/set "completed" bit. */
0851 static void __ssh_ptl_complete(struct ssh_packet *p, int status)
0852 {
0853     struct ssh_ptl *ptl = READ_ONCE(p->ptl);
0854 
0855     trace_ssam_packet_complete(p, status);
0856     ptl_dbg_cond(ptl, "ptl: completing packet %p (status: %d)\n", p, status);
0857 
0858     if (p->ops->complete)
0859         p->ops->complete(p, status);
0860 }
0861 
0862 static void ssh_ptl_remove_and_complete(struct ssh_packet *p, int status)
0863 {
0864     /*
0865      * A call to this function should in general be preceded by
0866      * set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->flags) to avoid re-adding the
0867      * packet to the structures it's going to be removed from.
0868      *
0869      * The set_bit call does not need explicit memory barriers as the
0870      * implicit barrier of the test_and_set_bit() call below ensure that the
0871      * flag is visible before we actually attempt to remove the packet.
0872      */
0873 
0874     if (test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
0875         return;
0876 
0877     ssh_ptl_queue_remove(p);
0878     ssh_ptl_pending_remove(p);
0879 
0880     __ssh_ptl_complete(p, status);
0881 }
0882 
0883 static bool ssh_ptl_tx_can_process(struct ssh_packet *packet)
0884 {
0885     struct ssh_ptl *ptl = packet->ptl;
0886 
0887     if (test_bit(SSH_PACKET_TY_FLUSH_BIT, &packet->state))
0888         return !atomic_read(&ptl->pending.count);
0889 
0890     /* We can always process non-blocking packets. */
0891     if (!test_bit(SSH_PACKET_TY_BLOCKING_BIT, &packet->state))
0892         return true;
0893 
0894     /* If we are already waiting for this packet, send it again. */
0895     if (test_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state))
0896         return true;
0897 
0898     /* Otherwise: Check if we have the capacity to send. */
0899     return atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING;
0900 }
0901 
0902 static struct ssh_packet *ssh_ptl_tx_pop(struct ssh_ptl *ptl)
0903 {
0904     struct ssh_packet *packet = ERR_PTR(-ENOENT);
0905     struct ssh_packet *p, *n;
0906 
0907     spin_lock(&ptl->queue.lock);
0908     list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
0909         /*
0910          * If we are canceling or completing this packet, ignore it.
0911          * It's going to be removed from this queue shortly.
0912          */
0913         if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
0914             continue;
0915 
0916         /*
0917          * Packets should be ordered non-blocking/to-be-resent first.
0918          * If we cannot process this packet, assume that we can't
0919          * process any following packet either and abort.
0920          */
0921         if (!ssh_ptl_tx_can_process(p)) {
0922             packet = ERR_PTR(-EBUSY);
0923             break;
0924         }
0925 
0926         /*
0927          * We are allowed to change the state now. Remove it from the
0928          * queue and mark it as being transmitted.
0929          */
0930 
0931         list_del(&p->queue_node);
0932 
0933         set_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state);
0934         /* Ensure that state never gets zero. */
0935         smp_mb__before_atomic();
0936         clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
0937 
0938         /*
0939          * Update number of tries. This directly influences the
0940          * priority in case the packet is re-submitted (e.g. via
0941          * timeout/NAK). Note that all reads and writes to the
0942          * priority after the first submission are guarded by the
0943          * queue lock.
0944          */
0945         ssh_packet_next_try(p);
0946 
0947         packet = p;
0948         break;
0949     }
0950     spin_unlock(&ptl->queue.lock);
0951 
0952     return packet;
0953 }
0954 
0955 static struct ssh_packet *ssh_ptl_tx_next(struct ssh_ptl *ptl)
0956 {
0957     struct ssh_packet *p;
0958 
0959     p = ssh_ptl_tx_pop(ptl);
0960     if (IS_ERR(p))
0961         return p;
0962 
0963     if (test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &p->state)) {
0964         ptl_dbg(ptl, "ptl: transmitting sequenced packet %p\n", p);
0965         ssh_ptl_pending_push(p);
0966     } else {
0967         ptl_dbg(ptl, "ptl: transmitting non-sequenced packet %p\n", p);
0968     }
0969 
0970     return p;
0971 }
0972 
0973 static void ssh_ptl_tx_compl_success(struct ssh_packet *packet)
0974 {
0975     struct ssh_ptl *ptl = packet->ptl;
0976 
0977     ptl_dbg(ptl, "ptl: successfully transmitted packet %p\n", packet);
0978 
0979     /* Transition state to "transmitted". */
0980     set_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state);
0981     /* Ensure that state never gets zero. */
0982     smp_mb__before_atomic();
0983     clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
0984 
0985     /* If the packet is unsequenced, we're done: Lock and complete. */
0986     if (!test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &packet->state)) {
0987         set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
0988         ssh_ptl_remove_and_complete(packet, 0);
0989     }
0990 
0991     /*
0992      * Notify that a packet transmission has finished. In general we're only
0993      * waiting for one packet (if any), so wake_up_all should be fine.
0994      */
0995     wake_up_all(&ptl->tx.packet_wq);
0996 }
0997 
0998 static void ssh_ptl_tx_compl_error(struct ssh_packet *packet, int status)
0999 {
1000     /* Transmission failure: Lock the packet and try to complete it. */
1001     set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
1002     /* Ensure that state never gets zero. */
1003     smp_mb__before_atomic();
1004     clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
1005 
1006     ptl_err(packet->ptl, "ptl: transmission error: %d\n", status);
1007     ptl_dbg(packet->ptl, "ptl: failed to transmit packet: %p\n", packet);
1008 
1009     ssh_ptl_remove_and_complete(packet, status);
1010 
1011     /*
1012      * Notify that a packet transmission has finished. In general we're only
1013      * waiting for one packet (if any), so wake_up_all should be fine.
1014      */
1015     wake_up_all(&packet->ptl->tx.packet_wq);
1016 }
1017 
1018 static long ssh_ptl_tx_wait_packet(struct ssh_ptl *ptl)
1019 {
1020     int status;
1021 
1022     status = wait_for_completion_interruptible(&ptl->tx.thread_cplt_pkt);
1023     reinit_completion(&ptl->tx.thread_cplt_pkt);
1024 
1025     /*
1026      * Ensure completion is cleared before continuing to avoid lost update
1027      * problems.
1028      */
1029     smp_mb__after_atomic();
1030 
1031     return status;
1032 }
1033 
1034 static long ssh_ptl_tx_wait_transfer(struct ssh_ptl *ptl, long timeout)
1035 {
1036     long status;
1037 
1038     status = wait_for_completion_interruptible_timeout(&ptl->tx.thread_cplt_tx,
1039                                timeout);
1040     reinit_completion(&ptl->tx.thread_cplt_tx);
1041 
1042     /*
1043      * Ensure completion is cleared before continuing to avoid lost update
1044      * problems.
1045      */
1046     smp_mb__after_atomic();
1047 
1048     return status;
1049 }
1050 
1051 static int ssh_ptl_tx_packet(struct ssh_ptl *ptl, struct ssh_packet *packet)
1052 {
1053     long timeout = SSH_PTL_TX_TIMEOUT;
1054     size_t offset = 0;
1055 
1056     /* Note: Flush-packets don't have any data. */
1057     if (unlikely(!packet->data.ptr))
1058         return 0;
1059 
1060     /* Error injection: drop packet to simulate transmission problem. */
1061     if (ssh_ptl_should_drop_packet(packet))
1062         return 0;
1063 
1064     /* Error injection: simulate invalid packet data. */
1065     ssh_ptl_tx_inject_invalid_data(packet);
1066 
1067     ptl_dbg(ptl, "tx: sending data (length: %zu)\n", packet->data.len);
1068     print_hex_dump_debug("tx: ", DUMP_PREFIX_OFFSET, 16, 1,
1069                  packet->data.ptr, packet->data.len, false);
1070 
1071     do {
1072         ssize_t status, len;
1073         u8 *buf;
1074 
1075         buf = packet->data.ptr + offset;
1076         len = packet->data.len - offset;
1077 
1078         status = ssh_ptl_write_buf(ptl, packet, buf, len);
1079         if (status < 0)
1080             return status;
1081 
1082         if (status == len)
1083             return 0;
1084 
1085         offset += status;
1086 
1087         timeout = ssh_ptl_tx_wait_transfer(ptl, timeout);
1088         if (kthread_should_stop() || !atomic_read(&ptl->tx.running))
1089             return -ESHUTDOWN;
1090 
1091         if (timeout < 0)
1092             return -EINTR;
1093 
1094         if (timeout == 0)
1095             return -ETIMEDOUT;
1096     } while (true);
1097 }
1098 
1099 static int ssh_ptl_tx_threadfn(void *data)
1100 {
1101     struct ssh_ptl *ptl = data;
1102 
1103     while (!kthread_should_stop() && atomic_read(&ptl->tx.running)) {
1104         struct ssh_packet *packet;
1105         int status;
1106 
1107         /* Try to get the next packet. */
1108         packet = ssh_ptl_tx_next(ptl);
1109 
1110         /* If no packet can be processed, we are done. */
1111         if (IS_ERR(packet)) {
1112             ssh_ptl_tx_wait_packet(ptl);
1113             continue;
1114         }
1115 
1116         /* Transfer and complete packet. */
1117         status = ssh_ptl_tx_packet(ptl, packet);
1118         if (status)
1119             ssh_ptl_tx_compl_error(packet, status);
1120         else
1121             ssh_ptl_tx_compl_success(packet);
1122 
1123         ssh_packet_put(packet);
1124     }
1125 
1126     return 0;
1127 }
1128 
1129 /**
1130  * ssh_ptl_tx_wakeup_packet() - Wake up packet transmitter thread for new
1131  * packet.
1132  * @ptl: The packet transport layer.
1133  *
1134  * Wakes up the packet transmitter thread, notifying it that a new packet has
1135  * arrived and is ready for transfer. If the packet transport layer has been
1136  * shut down, calls to this function will be ignored.
1137  */
1138 static void ssh_ptl_tx_wakeup_packet(struct ssh_ptl *ptl)
1139 {
1140     if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
1141         return;
1142 
1143     complete(&ptl->tx.thread_cplt_pkt);
1144 }
1145 
1146 /**
1147  * ssh_ptl_tx_start() - Start packet transmitter thread.
1148  * @ptl: The packet transport layer.
1149  *
1150  * Return: Returns zero on success, a negative error code on failure.
1151  */
1152 int ssh_ptl_tx_start(struct ssh_ptl *ptl)
1153 {
1154     atomic_set_release(&ptl->tx.running, 1);
1155 
1156     ptl->tx.thread = kthread_run(ssh_ptl_tx_threadfn, ptl, "ssam_serial_hub-tx");
1157     if (IS_ERR(ptl->tx.thread))
1158         return PTR_ERR(ptl->tx.thread);
1159 
1160     return 0;
1161 }
1162 
1163 /**
1164  * ssh_ptl_tx_stop() - Stop packet transmitter thread.
1165  * @ptl: The packet transport layer.
1166  *
1167  * Return: Returns zero on success, a negative error code on failure.
1168  */
1169 int ssh_ptl_tx_stop(struct ssh_ptl *ptl)
1170 {
1171     int status = 0;
1172 
1173     if (!IS_ERR_OR_NULL(ptl->tx.thread)) {
1174         /* Tell thread to stop. */
1175         atomic_set_release(&ptl->tx.running, 0);
1176 
1177         /*
1178          * Wake up thread in case it is paused. Do not use wakeup
1179          * helpers as this may be called when the shutdown bit has
1180          * already been set.
1181          */
1182         complete(&ptl->tx.thread_cplt_pkt);
1183         complete(&ptl->tx.thread_cplt_tx);
1184 
1185         /* Finally, wait for thread to stop. */
1186         status = kthread_stop(ptl->tx.thread);
1187         ptl->tx.thread = NULL;
1188     }
1189 
1190     return status;
1191 }
1192 
1193 static struct ssh_packet *ssh_ptl_ack_pop(struct ssh_ptl *ptl, u8 seq_id)
1194 {
1195     struct ssh_packet *packet = ERR_PTR(-ENOENT);
1196     struct ssh_packet *p, *n;
1197 
1198     spin_lock(&ptl->pending.lock);
1199     list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
1200         /*
1201          * We generally expect packets to be in order, so first packet
1202          * to be added to pending is first to be sent, is first to be
1203          * ACKed.
1204          */
1205         if (unlikely(ssh_packet_get_seq(p) != seq_id))
1206             continue;
1207 
1208         /*
1209          * In case we receive an ACK while handling a transmission
1210          * error completion. The packet will be removed shortly.
1211          */
1212         if (unlikely(test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
1213             packet = ERR_PTR(-EPERM);
1214             break;
1215         }
1216 
1217         /*
1218          * Mark the packet as ACKed and remove it from pending by
1219          * removing its node and decrementing the pending counter.
1220          */
1221         set_bit(SSH_PACKET_SF_ACKED_BIT, &p->state);
1222         /* Ensure that state never gets zero. */
1223         smp_mb__before_atomic();
1224         clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
1225 
1226         atomic_dec(&ptl->pending.count);
1227         list_del(&p->pending_node);
1228         packet = p;
1229 
1230         break;
1231     }
1232     spin_unlock(&ptl->pending.lock);
1233 
1234     return packet;
1235 }
1236 
1237 static void ssh_ptl_wait_until_transmitted(struct ssh_packet *packet)
1238 {
1239     wait_event(packet->ptl->tx.packet_wq,
1240            test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state) ||
1241            test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state));
1242 }
1243 
1244 static void ssh_ptl_acknowledge(struct ssh_ptl *ptl, u8 seq)
1245 {
1246     struct ssh_packet *p;
1247 
1248     p = ssh_ptl_ack_pop(ptl, seq);
1249     if (IS_ERR(p)) {
1250         if (PTR_ERR(p) == -ENOENT) {
1251             /*
1252              * The packet has not been found in the set of pending
1253              * packets.
1254              */
1255             ptl_warn(ptl, "ptl: received ACK for non-pending packet\n");
1256         } else {
1257             /*
1258              * The packet is pending, but we are not allowed to take
1259              * it because it has been locked.
1260              */
1261             WARN_ON(PTR_ERR(p) != -EPERM);
1262         }
1263         return;
1264     }
1265 
1266     ptl_dbg(ptl, "ptl: received ACK for packet %p\n", p);
1267 
1268     /*
1269      * It is possible that the packet has been transmitted, but the state
1270      * has not been updated from "transmitting" to "transmitted" yet.
1271      * In that case, we need to wait for this transition to occur in order
1272      * to determine between success or failure.
1273      *
1274      * On transmission failure, the packet will be locked after this call.
1275      * On success, the transmitted bit will be set.
1276      */
1277     ssh_ptl_wait_until_transmitted(p);
1278 
1279     /*
1280      * The packet will already be locked in case of a transmission error or
1281      * cancellation. Let the transmitter or cancellation issuer complete the
1282      * packet.
1283      */
1284     if (unlikely(test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
1285         if (unlikely(!test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &p->state)))
1286             ptl_err(ptl, "ptl: received ACK before packet had been fully transmitted\n");
1287 
1288         ssh_packet_put(p);
1289         return;
1290     }
1291 
1292     ssh_ptl_remove_and_complete(p, 0);
1293     ssh_packet_put(p);
1294 
1295     if (atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING)
1296         ssh_ptl_tx_wakeup_packet(ptl);
1297 }
1298 
1299 /**
1300  * ssh_ptl_submit() - Submit a packet to the transport layer.
1301  * @ptl: The packet transport layer to submit the packet to.
1302  * @p:   The packet to submit.
1303  *
1304  * Submits a new packet to the transport layer, queuing it to be sent. This
1305  * function should not be used for re-submission.
1306  *
1307  * Return: Returns zero on success, %-EINVAL if a packet field is invalid or
1308  * the packet has been canceled prior to submission, %-EALREADY if the packet
1309  * has already been submitted, or %-ESHUTDOWN if the packet transport layer
1310  * has been shut down.
1311  */
1312 int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *p)
1313 {
1314     struct ssh_ptl *ptl_old;
1315     int status;
1316 
1317     trace_ssam_packet_submit(p);
1318 
1319     /* Validate packet fields. */
1320     if (test_bit(SSH_PACKET_TY_FLUSH_BIT, &p->state)) {
1321         if (p->data.ptr || test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &p->state))
1322             return -EINVAL;
1323     } else if (!p->data.ptr) {
1324         return -EINVAL;
1325     }
1326 
1327     /*
1328      * The ptl reference only gets set on or before the first submission.
1329      * After the first submission, it has to be read-only.
1330      *
1331      * Note that ptl may already be set from upper-layer request
1332      * submission, thus we cannot expect it to be NULL.
1333      */
1334     ptl_old = READ_ONCE(p->ptl);
1335     if (!ptl_old)
1336         WRITE_ONCE(p->ptl, ptl);
1337     else if (WARN_ON(ptl_old != ptl))
1338         return -EALREADY;   /* Submitted on different PTL. */
1339 
1340     status = ssh_ptl_queue_push(p);
1341     if (status)
1342         return status;
1343 
1344     if (!test_bit(SSH_PACKET_TY_BLOCKING_BIT, &p->state) ||
1345         (atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING))
1346         ssh_ptl_tx_wakeup_packet(ptl);
1347 
1348     return 0;
1349 }
1350 
1351 /*
1352  * __ssh_ptl_resubmit() - Re-submit a packet to the transport layer.
1353  * @packet: The packet to re-submit.
1354  *
1355  * Re-submits the given packet: Checks if it can be re-submitted and queues it
1356  * if it can, resetting the packet timestamp in the process. Must be called
1357  * with the pending lock held.
1358  *
1359  * Return: Returns %-ECANCELED if the packet has exceeded its number of tries,
1360  * %-EINVAL if the packet has been locked, %-EALREADY if the packet is already
1361  * on the queue, and %-ESHUTDOWN if the transmission layer has been shut down.
1362  */
1363 static int __ssh_ptl_resubmit(struct ssh_packet *packet)
1364 {
1365     int status;
1366     u8 try;
1367 
1368     lockdep_assert_held(&packet->ptl->pending.lock);
1369 
1370     trace_ssam_packet_resubmit(packet);
1371 
1372     spin_lock(&packet->ptl->queue.lock);
1373 
1374     /* Check if the packet is out of tries. */
1375     try = ssh_packet_priority_get_try(packet->priority);
1376     if (try >= SSH_PTL_MAX_PACKET_TRIES) {
1377         spin_unlock(&packet->ptl->queue.lock);
1378         return -ECANCELED;
1379     }
1380 
1381     status = __ssh_ptl_queue_push(packet);
1382     if (status) {
1383         /*
1384          * An error here indicates that the packet has either already
1385          * been queued, been locked, or the transport layer is being
1386          * shut down. In all cases: Ignore the error.
1387          */
1388         spin_unlock(&packet->ptl->queue.lock);
1389         return status;
1390     }
1391 
1392     packet->timestamp = KTIME_MAX;
1393 
1394     spin_unlock(&packet->ptl->queue.lock);
1395     return 0;
1396 }
1397 
1398 static void ssh_ptl_resubmit_pending(struct ssh_ptl *ptl)
1399 {
1400     struct ssh_packet *p;
1401     bool resub = false;
1402 
1403     /*
1404      * Note: We deliberately do not remove/attempt to cancel and complete
1405      * packets that are out of tires in this function. The packet will be
1406      * eventually canceled and completed by the timeout. Removing the packet
1407      * here could lead to overly eager cancellation if the packet has not
1408      * been re-transmitted yet but the tries-counter already updated (i.e
1409      * ssh_ptl_tx_next() removed the packet from the queue and updated the
1410      * counter, but re-transmission for the last try has not actually
1411      * started yet).
1412      */
1413 
1414     spin_lock(&ptl->pending.lock);
1415 
1416     /* Re-queue all pending packets. */
1417     list_for_each_entry(p, &ptl->pending.head, pending_node) {
1418         /*
1419          * Re-submission fails if the packet is out of tries, has been
1420          * locked, is already queued, or the layer is being shut down.
1421          * No need to re-schedule tx-thread in those cases.
1422          */
1423         if (!__ssh_ptl_resubmit(p))
1424             resub = true;
1425     }
1426 
1427     spin_unlock(&ptl->pending.lock);
1428 
1429     if (resub)
1430         ssh_ptl_tx_wakeup_packet(ptl);
1431 }
1432 
1433 /**
1434  * ssh_ptl_cancel() - Cancel a packet.
1435  * @p: The packet to cancel.
1436  *
1437  * Cancels a packet. There are no guarantees on when completion and release
1438  * callbacks will be called. This may occur during execution of this function
1439  * or may occur at any point later.
1440  *
1441  * Note that it is not guaranteed that the packet will actually be canceled if
1442  * the packet is concurrently completed by another process. The only guarantee
1443  * of this function is that the packet will be completed (with success,
1444  * failure, or cancellation) and released from the transport layer in a
1445  * reasonable time-frame.
1446  *
1447  * May be called before the packet has been submitted, in which case any later
1448  * packet submission fails.
1449  */
1450 void ssh_ptl_cancel(struct ssh_packet *p)
1451 {
1452     if (test_and_set_bit(SSH_PACKET_SF_CANCELED_BIT, &p->state))
1453         return;
1454 
1455     trace_ssam_packet_cancel(p);
1456 
1457     /*
1458      * Lock packet and commit with memory barrier. If this packet has
1459      * already been locked, it's going to be removed and completed by
1460      * another party, which should have precedence.
1461      */
1462     if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
1463         return;
1464 
1465     /*
1466      * By marking the packet as locked and employing the implicit memory
1467      * barrier of test_and_set_bit, we have guaranteed that, at this point,
1468      * the packet cannot be added to the queue any more.
1469      *
1470      * In case the packet has never been submitted, packet->ptl is NULL. If
1471      * the packet is currently being submitted, packet->ptl may be NULL or
1472      * non-NULL. Due marking the packet as locked above and committing with
1473      * the memory barrier, we have guaranteed that, if packet->ptl is NULL,
1474      * the packet will never be added to the queue. If packet->ptl is
1475      * non-NULL, we don't have any guarantees.
1476      */
1477 
1478     if (READ_ONCE(p->ptl)) {
1479         ssh_ptl_remove_and_complete(p, -ECANCELED);
1480 
1481         if (atomic_read(&p->ptl->pending.count) < SSH_PTL_MAX_PENDING)
1482             ssh_ptl_tx_wakeup_packet(p->ptl);
1483 
1484     } else if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
1485         __ssh_ptl_complete(p, -ECANCELED);
1486     }
1487 }
1488 
1489 /* Must be called with pending lock held */
1490 static ktime_t ssh_packet_get_expiration(struct ssh_packet *p, ktime_t timeout)
1491 {
1492     lockdep_assert_held(&p->ptl->pending.lock);
1493 
1494     if (p->timestamp != KTIME_MAX)
1495         return ktime_add(p->timestamp, timeout);
1496     else
1497         return KTIME_MAX;
1498 }
1499 
1500 static void ssh_ptl_timeout_reap(struct work_struct *work)
1501 {
1502     struct ssh_ptl *ptl = to_ssh_ptl(work, rtx_timeout.reaper.work);
1503     struct ssh_packet *p, *n;
1504     LIST_HEAD(claimed);
1505     ktime_t now = ktime_get_coarse_boottime();
1506     ktime_t timeout = ptl->rtx_timeout.timeout;
1507     ktime_t next = KTIME_MAX;
1508     bool resub = false;
1509     int status;
1510 
1511     trace_ssam_ptl_timeout_reap(atomic_read(&ptl->pending.count));
1512 
1513     /*
1514      * Mark reaper as "not pending". This is done before checking any
1515      * packets to avoid lost-update type problems.
1516      */
1517     spin_lock(&ptl->rtx_timeout.lock);
1518     ptl->rtx_timeout.expires = KTIME_MAX;
1519     spin_unlock(&ptl->rtx_timeout.lock);
1520 
1521     spin_lock(&ptl->pending.lock);
1522 
1523     list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
1524         ktime_t expires = ssh_packet_get_expiration(p, timeout);
1525 
1526         /*
1527          * Check if the timeout hasn't expired yet. Find out next
1528          * expiration date to be handled after this run.
1529          */
1530         if (ktime_after(expires, now)) {
1531             next = ktime_before(expires, next) ? expires : next;
1532             continue;
1533         }
1534 
1535         trace_ssam_packet_timeout(p);
1536 
1537         status = __ssh_ptl_resubmit(p);
1538 
1539         /*
1540          * Re-submission fails if the packet is out of tries, has been
1541          * locked, is already queued, or the layer is being shut down.
1542          * No need to re-schedule tx-thread in those cases.
1543          */
1544         if (!status)
1545             resub = true;
1546 
1547         /* Go to next packet if this packet is not out of tries. */
1548         if (status != -ECANCELED)
1549             continue;
1550 
1551         /* No more tries left: Cancel the packet. */
1552 
1553         /*
1554          * If someone else has locked the packet already, don't use it
1555          * and let the other party complete it.
1556          */
1557         if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
1558             continue;
1559 
1560         /*
1561          * We have now marked the packet as locked. Thus it cannot be
1562          * added to the pending list again after we've removed it here.
1563          * We can therefore re-use the pending_node of this packet
1564          * temporarily.
1565          */
1566 
1567         clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
1568 
1569         atomic_dec(&ptl->pending.count);
1570         list_move_tail(&p->pending_node, &claimed);
1571     }
1572 
1573     spin_unlock(&ptl->pending.lock);
1574 
1575     /* Cancel and complete the packet. */
1576     list_for_each_entry_safe(p, n, &claimed, pending_node) {
1577         if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
1578             ssh_ptl_queue_remove(p);
1579             __ssh_ptl_complete(p, -ETIMEDOUT);
1580         }
1581 
1582         /*
1583          * Drop the reference we've obtained by removing it from
1584          * the pending set.
1585          */
1586         list_del(&p->pending_node);
1587         ssh_packet_put(p);
1588     }
1589 
1590     /* Ensure that reaper doesn't run again immediately. */
1591     next = max(next, ktime_add(now, SSH_PTL_PACKET_TIMEOUT_RESOLUTION));
1592     if (next != KTIME_MAX)
1593         ssh_ptl_timeout_reaper_mod(ptl, now, next);
1594 
1595     if (resub)
1596         ssh_ptl_tx_wakeup_packet(ptl);
1597 }
1598 
1599 static bool ssh_ptl_rx_retransmit_check(struct ssh_ptl *ptl, u8 seq)
1600 {
1601     int i;
1602 
1603     /*
1604      * Check if SEQ has been seen recently (i.e. packet was
1605      * re-transmitted and we should ignore it).
1606      */
1607     for (i = 0; i < ARRAY_SIZE(ptl->rx.blocked.seqs); i++) {
1608         if (likely(ptl->rx.blocked.seqs[i] != seq))
1609             continue;
1610 
1611         ptl_dbg(ptl, "ptl: ignoring repeated data packet\n");
1612         return true;
1613     }
1614 
1615     /* Update list of blocked sequence IDs. */
1616     ptl->rx.blocked.seqs[ptl->rx.blocked.offset] = seq;
1617     ptl->rx.blocked.offset = (ptl->rx.blocked.offset + 1)
1618                   % ARRAY_SIZE(ptl->rx.blocked.seqs);
1619 
1620     return false;
1621 }
1622 
1623 static void ssh_ptl_rx_dataframe(struct ssh_ptl *ptl,
1624                  const struct ssh_frame *frame,
1625                  const struct ssam_span *payload)
1626 {
1627     if (ssh_ptl_rx_retransmit_check(ptl, frame->seq))
1628         return;
1629 
1630     ptl->ops.data_received(ptl, payload);
1631 }
1632 
1633 static void ssh_ptl_send_ack(struct ssh_ptl *ptl, u8 seq)
1634 {
1635     struct ssh_packet *packet;
1636     struct ssam_span buf;
1637     struct msgbuf msgb;
1638     int status;
1639 
1640     status = ssh_ctrl_packet_alloc(&packet, &buf, GFP_KERNEL);
1641     if (status) {
1642         ptl_err(ptl, "ptl: failed to allocate ACK packet\n");
1643         return;
1644     }
1645 
1646     ssh_packet_init(packet, 0, SSH_PACKET_PRIORITY(ACK, 0),
1647             &ssh_ptl_ctrl_packet_ops);
1648 
1649     msgb_init(&msgb, buf.ptr, buf.len);
1650     msgb_push_ack(&msgb, seq);
1651     ssh_packet_set_data(packet, msgb.begin, msgb_bytes_used(&msgb));
1652 
1653     ssh_ptl_submit(ptl, packet);
1654     ssh_packet_put(packet);
1655 }
1656 
1657 static void ssh_ptl_send_nak(struct ssh_ptl *ptl)
1658 {
1659     struct ssh_packet *packet;
1660     struct ssam_span buf;
1661     struct msgbuf msgb;
1662     int status;
1663 
1664     status = ssh_ctrl_packet_alloc(&packet, &buf, GFP_KERNEL);
1665     if (status) {
1666         ptl_err(ptl, "ptl: failed to allocate NAK packet\n");
1667         return;
1668     }
1669 
1670     ssh_packet_init(packet, 0, SSH_PACKET_PRIORITY(NAK, 0),
1671             &ssh_ptl_ctrl_packet_ops);
1672 
1673     msgb_init(&msgb, buf.ptr, buf.len);
1674     msgb_push_nak(&msgb);
1675     ssh_packet_set_data(packet, msgb.begin, msgb_bytes_used(&msgb));
1676 
1677     ssh_ptl_submit(ptl, packet);
1678     ssh_packet_put(packet);
1679 }
1680 
1681 static size_t ssh_ptl_rx_eval(struct ssh_ptl *ptl, struct ssam_span *source)
1682 {
1683     struct ssh_frame *frame;
1684     struct ssam_span payload;
1685     struct ssam_span aligned;
1686     bool syn_found;
1687     int status;
1688 
1689     /* Error injection: Modify data to simulate corrupt SYN bytes. */
1690     ssh_ptl_rx_inject_invalid_syn(ptl, source);
1691 
1692     /* Find SYN. */
1693     syn_found = sshp_find_syn(source, &aligned);
1694 
1695     if (unlikely(aligned.ptr != source->ptr)) {
1696         /*
1697          * We expect aligned.ptr == source->ptr. If this is not the
1698          * case, then aligned.ptr > source->ptr and we've encountered
1699          * some unexpected data where we'd expect the start of a new
1700          * message (i.e. the SYN sequence).
1701          *
1702          * This can happen when a CRC check for the previous message
1703          * failed and we start actively searching for the next one
1704          * (via the call to sshp_find_syn() above), or the first bytes
1705          * of a message got dropped or corrupted.
1706          *
1707          * In any case, we issue a warning, send a NAK to the EC to
1708          * request re-transmission of any data we haven't acknowledged
1709          * yet, and finally, skip everything up to the next SYN
1710          * sequence.
1711          */
1712 
1713         ptl_warn(ptl, "rx: parser: invalid start of frame, skipping\n");
1714 
1715         /*
1716          * Notes:
1717          * - This might send multiple NAKs in case the communication
1718          *   starts with an invalid SYN and is broken down into multiple
1719          *   pieces. This should generally be handled fine, we just
1720          *   might receive duplicate data in this case, which is
1721          *   detected when handling data frames.
1722          * - This path will also be executed on invalid CRCs: When an
1723          *   invalid CRC is encountered, the code below will skip data
1724          *   until directly after the SYN. This causes the search for
1725          *   the next SYN, which is generally not placed directly after
1726          *   the last one.
1727          *
1728          *   Open question: Should we send this in case of invalid
1729          *   payload CRCs if the frame-type is non-sequential (current
1730          *   implementation) or should we drop that frame without
1731          *   telling the EC?
1732          */
1733         ssh_ptl_send_nak(ptl);
1734     }
1735 
1736     if (unlikely(!syn_found))
1737         return aligned.ptr - source->ptr;
1738 
1739     /* Error injection: Modify data to simulate corruption. */
1740     ssh_ptl_rx_inject_invalid_data(ptl, &aligned);
1741 
1742     /* Parse and validate frame. */
1743     status = sshp_parse_frame(&ptl->serdev->dev, &aligned, &frame, &payload,
1744                   SSH_PTL_RX_BUF_LEN);
1745     if (status) /* Invalid frame: skip to next SYN. */
1746         return aligned.ptr - source->ptr + sizeof(u16);
1747     if (!frame) /* Not enough data. */
1748         return aligned.ptr - source->ptr;
1749 
1750     trace_ssam_rx_frame_received(frame);
1751 
1752     switch (frame->type) {
1753     case SSH_FRAME_TYPE_ACK:
1754         ssh_ptl_acknowledge(ptl, frame->seq);
1755         break;
1756 
1757     case SSH_FRAME_TYPE_NAK:
1758         ssh_ptl_resubmit_pending(ptl);
1759         break;
1760 
1761     case SSH_FRAME_TYPE_DATA_SEQ:
1762         ssh_ptl_send_ack(ptl, frame->seq);
1763         fallthrough;
1764 
1765     case SSH_FRAME_TYPE_DATA_NSQ:
1766         ssh_ptl_rx_dataframe(ptl, frame, &payload);
1767         break;
1768 
1769     default:
1770         ptl_warn(ptl, "ptl: received frame with unknown type %#04x\n",
1771              frame->type);
1772         break;
1773     }
1774 
1775     return aligned.ptr - source->ptr + SSH_MESSAGE_LENGTH(payload.len);
1776 }
1777 
1778 static int ssh_ptl_rx_threadfn(void *data)
1779 {
1780     struct ssh_ptl *ptl = data;
1781 
1782     while (true) {
1783         struct ssam_span span;
1784         size_t offs = 0;
1785         size_t n;
1786 
1787         wait_event_interruptible(ptl->rx.wq,
1788                      !kfifo_is_empty(&ptl->rx.fifo) ||
1789                      kthread_should_stop());
1790         if (kthread_should_stop())
1791             break;
1792 
1793         /* Copy from fifo to evaluation buffer. */
1794         n = sshp_buf_read_from_fifo(&ptl->rx.buf, &ptl->rx.fifo);
1795 
1796         ptl_dbg(ptl, "rx: received data (size: %zu)\n", n);
1797         print_hex_dump_debug("rx: ", DUMP_PREFIX_OFFSET, 16, 1,
1798                      ptl->rx.buf.ptr + ptl->rx.buf.len - n,
1799                      n, false);
1800 
1801         /* Parse until we need more bytes or buffer is empty. */
1802         while (offs < ptl->rx.buf.len) {
1803             sshp_buf_span_from(&ptl->rx.buf, offs, &span);
1804             n = ssh_ptl_rx_eval(ptl, &span);
1805             if (n == 0)
1806                 break;  /* Need more bytes. */
1807 
1808             offs += n;
1809         }
1810 
1811         /* Throw away the evaluated parts. */
1812         sshp_buf_drop(&ptl->rx.buf, offs);
1813     }
1814 
1815     return 0;
1816 }
1817 
1818 static void ssh_ptl_rx_wakeup(struct ssh_ptl *ptl)
1819 {
1820     wake_up(&ptl->rx.wq);
1821 }
1822 
1823 /**
1824  * ssh_ptl_rx_start() - Start packet transport layer receiver thread.
1825  * @ptl: The packet transport layer.
1826  *
1827  * Return: Returns zero on success, a negative error code on failure.
1828  */
1829 int ssh_ptl_rx_start(struct ssh_ptl *ptl)
1830 {
1831     if (ptl->rx.thread)
1832         return 0;
1833 
1834     ptl->rx.thread = kthread_run(ssh_ptl_rx_threadfn, ptl,
1835                      "ssam_serial_hub-rx");
1836     if (IS_ERR(ptl->rx.thread))
1837         return PTR_ERR(ptl->rx.thread);
1838 
1839     return 0;
1840 }
1841 
1842 /**
1843  * ssh_ptl_rx_stop() - Stop packet transport layer receiver thread.
1844  * @ptl: The packet transport layer.
1845  *
1846  * Return: Returns zero on success, a negative error code on failure.
1847  */
1848 int ssh_ptl_rx_stop(struct ssh_ptl *ptl)
1849 {
1850     int status = 0;
1851 
1852     if (ptl->rx.thread) {
1853         status = kthread_stop(ptl->rx.thread);
1854         ptl->rx.thread = NULL;
1855     }
1856 
1857     return status;
1858 }
1859 
1860 /**
1861  * ssh_ptl_rx_rcvbuf() - Push data from lower-layer transport to the packet
1862  * layer.
1863  * @ptl: The packet transport layer.
1864  * @buf: Pointer to the data to push to the layer.
1865  * @n:   Size of the data to push to the layer, in bytes.
1866  *
1867  * Pushes data from a lower-layer transport to the receiver fifo buffer of the
1868  * packet layer and notifies the receiver thread. Calls to this function are
1869  * ignored once the packet layer has been shut down.
1870  *
1871  * Return: Returns the number of bytes transferred (positive or zero) on
1872  * success. Returns %-ESHUTDOWN if the packet layer has been shut down.
1873  */
1874 int ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n)
1875 {
1876     int used;
1877 
1878     if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
1879         return -ESHUTDOWN;
1880 
1881     used = kfifo_in(&ptl->rx.fifo, buf, n);
1882     if (used)
1883         ssh_ptl_rx_wakeup(ptl);
1884 
1885     return used;
1886 }
1887 
1888 /**
1889  * ssh_ptl_shutdown() - Shut down the packet transport layer.
1890  * @ptl: The packet transport layer.
1891  *
1892  * Shuts down the packet transport layer, removing and canceling all queued
1893  * and pending packets. Packets canceled by this operation will be completed
1894  * with %-ESHUTDOWN as status. Receiver and transmitter threads will be
1895  * stopped.
1896  *
1897  * As a result of this function, the transport layer will be marked as shut
1898  * down. Submission of packets after the transport layer has been shut down
1899  * will fail with %-ESHUTDOWN.
1900  */
1901 void ssh_ptl_shutdown(struct ssh_ptl *ptl)
1902 {
1903     LIST_HEAD(complete_q);
1904     LIST_HEAD(complete_p);
1905     struct ssh_packet *p, *n;
1906     int status;
1907 
1908     /* Ensure that no new packets (including ACK/NAK) can be submitted. */
1909     set_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state);
1910     /*
1911      * Ensure that the layer gets marked as shut-down before actually
1912      * stopping it. In combination with the check in ssh_ptl_queue_push(),
1913      * this guarantees that no new packets can be added and all already
1914      * queued packets are properly canceled. In combination with the check
1915      * in ssh_ptl_rx_rcvbuf(), this guarantees that received data is
1916      * properly cut off.
1917      */
1918     smp_mb__after_atomic();
1919 
1920     status = ssh_ptl_rx_stop(ptl);
1921     if (status)
1922         ptl_err(ptl, "ptl: failed to stop receiver thread\n");
1923 
1924     status = ssh_ptl_tx_stop(ptl);
1925     if (status)
1926         ptl_err(ptl, "ptl: failed to stop transmitter thread\n");
1927 
1928     cancel_delayed_work_sync(&ptl->rtx_timeout.reaper);
1929 
1930     /*
1931      * At this point, all threads have been stopped. This means that the
1932      * only references to packets from inside the system are in the queue
1933      * and pending set.
1934      *
1935      * Note: We still need locks here because someone could still be
1936      * canceling packets.
1937      *
1938      * Note 2: We can re-use queue_node (or pending_node) if we mark the
1939      * packet as locked an then remove it from the queue (or pending set
1940      * respectively). Marking the packet as locked avoids re-queuing
1941      * (which should already be prevented by having stopped the treads...)
1942      * and not setting QUEUED_BIT (or PENDING_BIT) prevents removal from a
1943      * new list via other threads (e.g. cancellation).
1944      *
1945      * Note 3: There may be overlap between complete_p and complete_q.
1946      * This is handled via test_and_set_bit() on the "completed" flag
1947      * (also handles cancellation).
1948      */
1949 
1950     /* Mark queued packets as locked and move them to complete_q. */
1951     spin_lock(&ptl->queue.lock);
1952     list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
1953         set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
1954         /* Ensure that state does not get zero. */
1955         smp_mb__before_atomic();
1956         clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
1957 
1958         list_move_tail(&p->queue_node, &complete_q);
1959     }
1960     spin_unlock(&ptl->queue.lock);
1961 
1962     /* Mark pending packets as locked and move them to complete_p. */
1963     spin_lock(&ptl->pending.lock);
1964     list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
1965         set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
1966         /* Ensure that state does not get zero. */
1967         smp_mb__before_atomic();
1968         clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
1969 
1970         list_move_tail(&p->pending_node, &complete_q);
1971     }
1972     atomic_set(&ptl->pending.count, 0);
1973     spin_unlock(&ptl->pending.lock);
1974 
1975     /* Complete and drop packets on complete_q. */
1976     list_for_each_entry(p, &complete_q, queue_node) {
1977         if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
1978             __ssh_ptl_complete(p, -ESHUTDOWN);
1979 
1980         ssh_packet_put(p);
1981     }
1982 
1983     /* Complete and drop packets on complete_p. */
1984     list_for_each_entry(p, &complete_p, pending_node) {
1985         if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
1986             __ssh_ptl_complete(p, -ESHUTDOWN);
1987 
1988         ssh_packet_put(p);
1989     }
1990 
1991     /*
1992      * At this point we have guaranteed that the system doesn't reference
1993      * any packets any more.
1994      */
1995 }
1996 
1997 /**
1998  * ssh_ptl_init() - Initialize packet transport layer.
1999  * @ptl:    The packet transport layer to initialize.
2000  * @serdev: The underlying serial device, i.e. the lower-level transport.
2001  * @ops:    Packet layer operations.
2002  *
2003  * Initializes the given packet transport layer. Transmitter and receiver
2004  * threads must be started separately via ssh_ptl_tx_start() and
2005  * ssh_ptl_rx_start(), after the packet-layer has been initialized and the
2006  * lower-level transport layer has been set up.
2007  *
2008  * Return: Returns zero on success and a nonzero error code on failure.
2009  */
2010 int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev,
2011          struct ssh_ptl_ops *ops)
2012 {
2013     int i, status;
2014 
2015     ptl->serdev = serdev;
2016     ptl->state = 0;
2017 
2018     spin_lock_init(&ptl->queue.lock);
2019     INIT_LIST_HEAD(&ptl->queue.head);
2020 
2021     spin_lock_init(&ptl->pending.lock);
2022     INIT_LIST_HEAD(&ptl->pending.head);
2023     atomic_set_release(&ptl->pending.count, 0);
2024 
2025     ptl->tx.thread = NULL;
2026     atomic_set(&ptl->tx.running, 0);
2027     init_completion(&ptl->tx.thread_cplt_pkt);
2028     init_completion(&ptl->tx.thread_cplt_tx);
2029     init_waitqueue_head(&ptl->tx.packet_wq);
2030 
2031     ptl->rx.thread = NULL;
2032     init_waitqueue_head(&ptl->rx.wq);
2033 
2034     spin_lock_init(&ptl->rtx_timeout.lock);
2035     ptl->rtx_timeout.timeout = SSH_PTL_PACKET_TIMEOUT;
2036     ptl->rtx_timeout.expires = KTIME_MAX;
2037     INIT_DELAYED_WORK(&ptl->rtx_timeout.reaper, ssh_ptl_timeout_reap);
2038 
2039     ptl->ops = *ops;
2040 
2041     /* Initialize list of recent/blocked SEQs with invalid sequence IDs. */
2042     for (i = 0; i < ARRAY_SIZE(ptl->rx.blocked.seqs); i++)
2043         ptl->rx.blocked.seqs[i] = U16_MAX;
2044     ptl->rx.blocked.offset = 0;
2045 
2046     status = kfifo_alloc(&ptl->rx.fifo, SSH_PTL_RX_FIFO_LEN, GFP_KERNEL);
2047     if (status)
2048         return status;
2049 
2050     status = sshp_buf_alloc(&ptl->rx.buf, SSH_PTL_RX_BUF_LEN, GFP_KERNEL);
2051     if (status)
2052         kfifo_free(&ptl->rx.fifo);
2053 
2054     return status;
2055 }
2056 
2057 /**
2058  * ssh_ptl_destroy() - Deinitialize packet transport layer.
2059  * @ptl: The packet transport layer to deinitialize.
2060  *
2061  * Deinitializes the given packet transport layer and frees resources
2062  * associated with it. If receiver and/or transmitter threads have been
2063  * started, the layer must first be shut down via ssh_ptl_shutdown() before
2064  * this function can be called.
2065  */
2066 void ssh_ptl_destroy(struct ssh_ptl *ptl)
2067 {
2068     kfifo_free(&ptl->rx.fifo);
2069     sshp_buf_free(&ptl->rx.buf);
2070 }