

#include "internal/quic_txp.h"
#include "internal/quic_fifd.h"
#include "internal/quic_stream_map.h"
#include "internal/quic_error.h"
#include "internal/common.h"
#include <openssl/err.h>

#define MIN_CRYPTO_HDR_SIZE             3

#define MIN_FRAME_SIZE_HANDSHAKE_DONE   1
#define MIN_FRAME_SIZE_MAX_DATA         2
#define MIN_FRAME_SIZE_ACK              5
#define MIN_FRAME_SIZE_CRYPTO           (MIN_CRYPTO_HDR_SIZE + 1)
#define MIN_FRAME_SIZE_STREAM           3 
#define MIN_FRAME_SIZE_MAX_STREAMS_BIDI 2
#define MIN_FRAME_SIZE_MAX_STREAMS_UNI  2




#define TX_PACKETISER_ARCHETYPE_NORMAL              0


#define TX_PACKETISER_ARCHETYPE_PROBE               1


#define TX_PACKETISER_ARCHETYPE_ACK_ONLY            2

#define TX_PACKETISER_ARCHETYPE_NUM                 3

struct ossl_quic_tx_packetiser_st {
    OSSL_QUIC_TX_PACKETISER_ARGS args;

    
    const unsigned char             *initial_token;
    size_t                          initial_token_len;
    ossl_quic_initial_token_free_fn *initial_token_free_cb;
    void                            *initial_token_free_cb_arg;

    
    QUIC_FIFD       fifd;       

    
    uint64_t        next_pn[QUIC_PN_SPACE_NUM]; 
    OSSL_TIME       last_tx_time;               

    
    unsigned int    want_handshake_done     : 1;
    unsigned int    want_max_data           : 1;
    unsigned int    want_max_streams_bidi   : 1;
    unsigned int    want_max_streams_uni    : 1;

    
    unsigned int    want_ack                : QUIC_PN_SPACE_NUM;
    unsigned int    force_ack_eliciting     : QUIC_PN_SPACE_NUM;

    
    unsigned int    want_conn_close         : 1;

    
    unsigned int    handshake_complete      : 1;

    OSSL_QUIC_FRAME_CONN_CLOSE  conn_close_frame;

    
    uint64_t                        closing_bytes_recv;
    uint64_t                        closing_bytes_xmit;

    
    struct txp_el {
        unsigned char   *scratch;       
        size_t          scratch_len;    
        OSSL_QTX_IOVEC  *iovec;         
        size_t          alloc_iovec;    
    } el[QUIC_ENC_LEVEL_NUM];

    
    ossl_msg_cb msg_callback;
    void *msg_callback_arg;
    SSL *msg_callback_ssl;

    
    void            (*ack_tx_cb)(const OSSL_QUIC_FRAME_ACK *ack,
                                 uint32_t pn_space,
                                 void *arg);
    void            *ack_tx_cb_arg;
};


struct tx_helper {
    OSSL_QUIC_TX_PACKETISER *txp;
    
    size_t max_ppl;
    
    size_t bytes_appended;
    
    size_t scratch_bytes;
    
    size_t reserve;
    
    size_t num_iovec;
    
    uint32_t enc_level;
    
    unsigned int reserve_allowed : 1;
    
    unsigned int done_implicit : 1;
    struct {
        
        unsigned char   *data;
        WPACKET         wpkt;
        unsigned int    active : 1;
    } txn;
};

static void tx_helper_rollback(struct tx_helper *h);
static int txp_el_ensure_iovec(struct txp_el *el, size_t num);


static int tx_helper_init(struct tx_helper *h, OSSL_QUIC_TX_PACKETISER *txp,
                          uint32_t enc_level, size_t max_ppl, size_t reserve)
{
    if (reserve > max_ppl)
        return 0;

    h->txp                  = txp;
    h->enc_level            = enc_level;
    h->max_ppl              = max_ppl;
    h->reserve              = reserve;
    h->num_iovec            = 0;
    h->bytes_appended       = 0;
    h->scratch_bytes        = 0;
    h->reserve_allowed      = 0;
    h->done_implicit        = 0;
    h->txn.data             = NULL;
    h->txn.active           = 0;

    if (max_ppl > h->txp->el[enc_level].scratch_len) {
        unsigned char *scratch;

        scratch = OPENSSL_realloc(h->txp->el[enc_level].scratch, max_ppl);
        if (scratch == NULL)
            return 0;

        h->txp->el[enc_level].scratch     = scratch;
        h->txp->el[enc_level].scratch_len = max_ppl;
    }

    return 1;
}

static void tx_helper_cleanup(struct tx_helper *h)
{
    if (h->txn.active)
        tx_helper_rollback(h);

    h->txp = NULL;
}

static void tx_helper_unrestrict(struct tx_helper *h)
{
    h->reserve_allowed = 1;
}


static int tx_helper_append_iovec(struct tx_helper *h,
                                  const unsigned char *buf,
                                  size_t buf_len)
{
    struct txp_el *el = &h->txp->el[h->enc_level];

    if (buf_len == 0)
        return 1;

    if (!ossl_assert(!h->done_implicit))
        return 0;

    if (!txp_el_ensure_iovec(el, h->num_iovec + 1))
        return 0;

    el->iovec[h->num_iovec].buf     = buf;
    el->iovec[h->num_iovec].buf_len = buf_len;

    ++h->num_iovec;
    h->bytes_appended += buf_len;
    return 1;
}


static size_t tx_helper_get_space_left(struct tx_helper *h)
{
    return h->max_ppl
        - (h->reserve_allowed ? 0 : h->reserve) - h->bytes_appended;
}


static WPACKET *tx_helper_begin(struct tx_helper *h)
{
    size_t space_left, len;
    unsigned char *data;
    struct txp_el *el = &h->txp->el[h->enc_level];

    if (!ossl_assert(!h->txn.active))
        return NULL;

    if (!ossl_assert(!h->done_implicit))
        return NULL;

    data = (unsigned char *)el->scratch + h->scratch_bytes;
    len  = el->scratch_len - h->scratch_bytes;

    space_left = tx_helper_get_space_left(h);
    if (!ossl_assert(space_left <= len))
        return NULL;

    if (!WPACKET_init_static_len(&h->txn.wpkt, data, len, 0))
        return NULL;

    if (!WPACKET_set_max_size(&h->txn.wpkt, space_left)) {
        WPACKET_cleanup(&h->txn.wpkt);
        return NULL;
    }

    h->txn.data     = data;
    h->txn.active   = 1;
    return &h->txn.wpkt;
}

static void tx_helper_end(struct tx_helper *h, int success)
{
    if (success)
        WPACKET_finish(&h->txn.wpkt);
    else
        WPACKET_cleanup(&h->txn.wpkt);

    h->txn.active       = 0;
    h->txn.data         = NULL;
}


static void tx_helper_rollback(struct tx_helper *h)
{
    if (!h->txn.active)
        return;

    tx_helper_end(h, 0);
}


static int tx_helper_commit(struct tx_helper *h)
{
    size_t l = 0;

    if (!h->txn.active)
        return 0;

    if (!WPACKET_get_total_written(&h->txn.wpkt, &l)) {
        tx_helper_end(h, 0);
        return 0;
    }

    if (!tx_helper_append_iovec(h, h->txn.data, l)) {
        tx_helper_end(h, 0);
        return 0;
    }

    if (h->txp->msg_callback != NULL && l > 0) {
        uint64_t ftype;
        int ctype = SSL3_RT_QUIC_FRAME_FULL;
        PACKET pkt;

        if (!PACKET_buf_init(&pkt, h->txn.data, l)
                || !ossl_quic_wire_peek_frame_header(&pkt, &ftype, NULL)) {
            tx_helper_end(h, 0);
            return 0;
        }

        if (ftype == OSSL_QUIC_FRAME_TYPE_PADDING)
            ctype = SSL3_RT_QUIC_FRAME_PADDING;
        else if (OSSL_QUIC_FRAME_TYPE_IS_STREAM(ftype)
                || ftype == OSSL_QUIC_FRAME_TYPE_CRYPTO)
            ctype = SSL3_RT_QUIC_FRAME_HEADER;

        h->txp->msg_callback(1, OSSL_QUIC1_VERSION, ctype, h->txn.data, l,
                             h->txp->msg_callback_ssl,
                             h->txp->msg_callback_arg);
    }

    h->scratch_bytes += l;
    tx_helper_end(h, 1);
    return 1;
}

struct archetype_data {
    unsigned int allow_ack                  : 1;
    unsigned int allow_ping                 : 1;
    unsigned int allow_crypto               : 1;
    unsigned int allow_handshake_done       : 1;
    unsigned int allow_path_challenge       : 1;
    unsigned int allow_path_response        : 1;
    unsigned int allow_new_conn_id          : 1;
    unsigned int allow_retire_conn_id       : 1;
    unsigned int allow_stream_rel           : 1;
    unsigned int allow_conn_fc              : 1;
    unsigned int allow_conn_close           : 1;
    unsigned int allow_cfq_other            : 1;
    unsigned int allow_new_token            : 1;
    unsigned int allow_force_ack_eliciting  : 1;
    unsigned int allow_padding              : 1;
    unsigned int require_ack_eliciting      : 1;
    unsigned int bypass_cc                  : 1;
};

struct txp_pkt_geom {
    size_t                  cmpl, cmppl, hwm, pkt_overhead;
    uint32_t                archetype;
    struct archetype_data   adata;
};

struct txp_pkt {
    struct tx_helper    h;
    int                 h_valid;
    QUIC_TXPIM_PKT      *tpkt;
    QUIC_STREAM         *stream_head;
    QUIC_PKT_HDR        phdr;
    struct txp_pkt_geom geom;
    int                 force_pad;
};

static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space,
                                       void *arg);
static void on_regen_notify(uint64_t frame_type, uint64_t stream_id,
                            QUIC_TXPIM_PKT *pkt, void *arg);
static void on_confirm_notify(uint64_t frame_type, uint64_t stream_id,
                              QUIC_TXPIM_PKT *pkt, void *arg);
static void on_sstream_updated(uint64_t stream_id, void *arg);
static int sstream_is_pending(QUIC_SSTREAM *sstream);
static int txp_should_try_staging(OSSL_QUIC_TX_PACKETISER *txp,
                                  uint32_t enc_level,
                                  uint32_t archetype,
                                  uint64_t cc_limit,
                                  uint32_t *conn_close_enc_level);
static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp);
static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp,
                                     size_t pl,
                                     uint32_t enc_level,
                                     size_t hdr_len,
                                     size_t *r);
static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp);
static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp,
                               struct txp_pkt *pkt,
                               int chosen_for_conn_close);
static int txp_pkt_init(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp,
                        uint32_t enc_level, uint32_t archetype,
                        size_t running_total);
static void txp_pkt_cleanup(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp);
static int txp_pkt_postgen_update_pkt_overhead(struct txp_pkt *pkt,
                                               OSSL_QUIC_TX_PACKETISER *txp);
static int txp_pkt_append_padding(struct txp_pkt *pkt,
                                  OSSL_QUIC_TX_PACKETISER *txp, size_t num_bytes);
static int txp_pkt_commit(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt,
                          uint32_t archetype, int *txpim_pkt_reffed);
static uint32_t txp_determine_archetype(OSSL_QUIC_TX_PACKETISER *txp,
                                        uint64_t cc_limit);

OSSL_QUIC_TX_PACKETISER *ossl_quic_tx_packetiser_new(const OSSL_QUIC_TX_PACKETISER_ARGS *args)
{
    OSSL_QUIC_TX_PACKETISER *txp;

    if (args == NULL
        || args->qtx == NULL
        || args->txpim == NULL
        || args->cfq == NULL
        || args->ackm == NULL
        || args->qsm == NULL
        || args->conn_txfc == NULL
        || args->conn_rxfc == NULL
        || args->max_streams_bidi_rxfc == NULL
        || args->max_streams_uni_rxfc == NULL) {
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
        return NULL;
    }

    txp = OPENSSL_zalloc(sizeof(*txp));
    if (txp == NULL)
        return NULL;

    txp->args           = *args;
    txp->last_tx_time   = ossl_time_zero();

    if (!ossl_quic_fifd_init(&txp->fifd,
                             txp->args.cfq, txp->args.ackm, txp->args.txpim,
                             get_sstream_by_id, txp,
                             on_regen_notify, txp,
                             on_confirm_notify, txp,
                             on_sstream_updated, txp,
                             args->get_qlog_cb,
                             args->get_qlog_cb_arg)) {
        OPENSSL_free(txp);
        return NULL;
    }

    return txp;
}

void ossl_quic_tx_packetiser_free(OSSL_QUIC_TX_PACKETISER *txp)
{
    uint32_t enc_level;

    if (txp == NULL)
        return;

    ossl_quic_tx_packetiser_set_initial_token(txp, NULL, 0, NULL, NULL);
    ossl_quic_fifd_cleanup(&txp->fifd);
    OPENSSL_free(txp->conn_close_frame.reason);

    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
         enc_level < QUIC_ENC_LEVEL_NUM;
         ++enc_level) {
        OPENSSL_free(txp->el[enc_level].iovec);
        OPENSSL_free(txp->el[enc_level].scratch);
    }

    OPENSSL_free(txp);
}


#define TXP_REQUIRED_TOKEN_MARGIN       160

static int txp_check_token_len(size_t token_len, size_t mdpl)
{
    if (token_len == 0)
        return 1;

    if (token_len >= mdpl)
        return 0;

    if (TXP_REQUIRED_TOKEN_MARGIN >= mdpl)
        
        return 0;

    if (token_len > mdpl - TXP_REQUIRED_TOKEN_MARGIN)
        return 0;

    return 1;
}

int ossl_quic_tx_packetiser_set_initial_token(OSSL_QUIC_TX_PACKETISER *txp,
                                              const unsigned char *token,
                                              size_t token_len,
                                              ossl_quic_initial_token_free_fn *free_cb,
                                              void *free_cb_arg)
{
    if (!txp_check_token_len(token_len, txp_get_mdpl(txp)))
        return 0;

    if (txp->initial_token != NULL && txp->initial_token_free_cb != NULL)
        txp->initial_token_free_cb(txp->initial_token, txp->initial_token_len,
                                   txp->initial_token_free_cb_arg);

    txp->initial_token              = token;
    txp->initial_token_len          = token_len;
    txp->initial_token_free_cb      = free_cb;
    txp->initial_token_free_cb_arg  = free_cb_arg;
    return 1;
}

int ossl_quic_tx_packetiser_set_cur_dcid(OSSL_QUIC_TX_PACKETISER *txp,
                                         const QUIC_CONN_ID *dcid)
{
    if (dcid == NULL) {
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
        return 0;
    }

    txp->args.cur_dcid = *dcid;
    return 1;
}

int ossl_quic_tx_packetiser_set_cur_scid(OSSL_QUIC_TX_PACKETISER *txp,
                                         const QUIC_CONN_ID *scid)
{
    if (scid == NULL) {
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
        return 0;
    }

    txp->args.cur_scid = *scid;
    return 1;
}


int ossl_quic_tx_packetiser_set_peer(OSSL_QUIC_TX_PACKETISER *txp,
                                     const BIO_ADDR *peer)
{
    if (peer == NULL) {
        BIO_ADDR_clear(&txp->args.peer);
        return 1;
    }

    txp->args.peer = *peer;
    return 1;
}

void ossl_quic_tx_packetiser_set_ack_tx_cb(OSSL_QUIC_TX_PACKETISER *txp,
                                           void (*cb)(const OSSL_QUIC_FRAME_ACK *ack,
                                                      uint32_t pn_space,
                                                      void *arg),
                                           void *cb_arg)
{
    txp->ack_tx_cb      = cb;
    txp->ack_tx_cb_arg  = cb_arg;
}

void ossl_quic_tx_packetiser_set_qlog_cb(OSSL_QUIC_TX_PACKETISER *txp,
                                         QLOG *(*get_qlog_cb)(void *arg),
                                         void *get_qlog_cb_arg)
{
    ossl_quic_fifd_set_qlog_cb(&txp->fifd, get_qlog_cb, get_qlog_cb_arg);

}

int ossl_quic_tx_packetiser_discard_enc_level(OSSL_QUIC_TX_PACKETISER *txp,
                                              uint32_t enc_level)
{
    if (enc_level >= QUIC_ENC_LEVEL_NUM) {
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
        return 0;
    }

    if (enc_level != QUIC_ENC_LEVEL_0RTT)
        txp->args.crypto[ossl_quic_enc_level_to_pn_space(enc_level)] = NULL;

    return 1;
}

void ossl_quic_tx_packetiser_notify_handshake_complete(OSSL_QUIC_TX_PACKETISER *txp)
{
    txp->handshake_complete = 1;
}

void ossl_quic_tx_packetiser_schedule_handshake_done(OSSL_QUIC_TX_PACKETISER *txp)
{
    txp->want_handshake_done = 1;
}

void ossl_quic_tx_packetiser_schedule_ack_eliciting(OSSL_QUIC_TX_PACKETISER *txp,
                                                    uint32_t pn_space)
{
    txp->force_ack_eliciting |= (1UL << pn_space);
}

void ossl_quic_tx_packetiser_schedule_ack(OSSL_QUIC_TX_PACKETISER *txp,
                                          uint32_t pn_space)
{
    txp->want_ack |= (1UL << pn_space);
}

#define TXP_ERR_INTERNAL     0  
#define TXP_ERR_SUCCESS      1  
#define TXP_ERR_SPACE        2  
#define TXP_ERR_INPUT        3  


int ossl_quic_tx_packetiser_generate(OSSL_QUIC_TX_PACKETISER *txp,
                                     QUIC_TXP_STATUS *status)
{
    
    int res = 0, rc;
    uint32_t archetype, enc_level;
    uint32_t conn_close_enc_level = QUIC_ENC_LEVEL_NUM;
    struct txp_pkt pkt[QUIC_ENC_LEVEL_NUM];
    size_t pkts_done = 0;
    uint64_t cc_limit = txp->args.cc_method->get_tx_allowance(txp->args.cc_data);
    int need_padding = 0, txpim_pkt_reffed;

    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
         enc_level < QUIC_ENC_LEVEL_NUM;
         ++enc_level)
        pkt[enc_level].h_valid = 0;

    memset(status, 0, sizeof(*status));

    
    ossl_qtx_finish_dgram(txp->args.qtx);

    
    archetype = txp_determine_archetype(txp, cc_limit);

    
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
         enc_level < QUIC_ENC_LEVEL_NUM;
         ++enc_level) {
        size_t running_total = (enc_level > QUIC_ENC_LEVEL_INITIAL)
            ? pkt[enc_level - 1].geom.hwm : 0;

        pkt[enc_level].geom.hwm = running_total;

        if (!txp_should_try_staging(txp, enc_level, archetype, cc_limit,
                                    &conn_close_enc_level))
            continue;

        if (!txp_pkt_init(&pkt[enc_level], txp, enc_level, archetype,
                          running_total))
            
            break;

        rc = txp_generate_for_el(txp, &pkt[enc_level],
                                 conn_close_enc_level == enc_level);
        if (rc != TXP_ERR_SUCCESS)
            goto out;

        if (pkt[enc_level].force_pad)
            
            need_padding = 1;

        pkt[enc_level].geom.hwm = running_total
            + pkt[enc_level].h.bytes_appended
            + pkt[enc_level].geom.pkt_overhead;
    }

    
    if (pkt[QUIC_ENC_LEVEL_INITIAL].h_valid
        && pkt[QUIC_ENC_LEVEL_INITIAL].h.bytes_appended > 0)
        
        need_padding = 1;

    if (need_padding) {
        size_t total_dgram_size = 0;
        const size_t min_dpl = QUIC_MIN_INITIAL_DGRAM_LEN;
        uint32_t pad_el = QUIC_ENC_LEVEL_NUM;

        for (enc_level = QUIC_ENC_LEVEL_INITIAL;
             enc_level < QUIC_ENC_LEVEL_NUM;
             ++enc_level)
            if (pkt[enc_level].h_valid && pkt[enc_level].h.bytes_appended > 0) {
                if (pad_el == QUIC_ENC_LEVEL_NUM
                    
                    && pkt[enc_level].geom.adata.allow_padding
                    && !pkt[enc_level].h.done_implicit)
                    pad_el = enc_level;

                txp_pkt_postgen_update_pkt_overhead(&pkt[enc_level], txp);
                total_dgram_size += pkt[enc_level].geom.pkt_overhead
                    + pkt[enc_level].h.bytes_appended;
            }

        if (pad_el != QUIC_ENC_LEVEL_NUM && total_dgram_size < min_dpl) {
            size_t deficit = min_dpl - total_dgram_size;

            if (!txp_pkt_append_padding(&pkt[pad_el], txp, deficit))
                goto out;

            total_dgram_size += deficit;

            
            pkt[pad_el].tpkt->ackm_pkt.is_inflight = 1;
        }

        
        if (total_dgram_size < min_dpl) {
            res = 1;
            goto out;
        }
    }

    
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
         enc_level < QUIC_ENC_LEVEL_NUM;
         ++enc_level) {

        if (!pkt[enc_level].h_valid)
            
            continue;

        if (pkt[enc_level].h.bytes_appended == 0)
            
            continue;

        rc = txp_pkt_commit(txp, &pkt[enc_level], archetype,
                            &txpim_pkt_reffed);
        if (rc) {
            status->sent_ack_eliciting
                = status->sent_ack_eliciting
                || pkt[enc_level].tpkt->ackm_pkt.is_ack_eliciting;

            if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE)
                status->sent_handshake
                    = (pkt[enc_level].h_valid
                       && pkt[enc_level].h.bytes_appended > 0);
        }

        if (txpim_pkt_reffed)
            pkt[enc_level].tpkt = NULL; 

        if (!rc)
            goto out;

        ++pkts_done;
    }

    
    res = 1;
out:
    ossl_qtx_finish_dgram(txp->args.qtx);

    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
         enc_level < QUIC_ENC_LEVEL_NUM;
         ++enc_level)
        txp_pkt_cleanup(&pkt[enc_level], txp);

    status->sent_pkt = pkts_done;

    return res;
}

static const struct archetype_data archetypes[QUIC_ENC_LEVEL_NUM][TX_PACKETISER_ARCHETYPE_NUM] = {
    
    {
        
        {
             1,
             1,
             1,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             1,
             0,
             0,
             1,
             1,
             0,
             0,
        },
        
        {
             1,
             1,
             1,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             1,
             0,
             0,
             1,
             1,
             1,
             1,
        },
        
        {
             1,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             1,
             0,
             0,
             1,
        },
    },
    
    {
        
        {
             1,
             1,
             1,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             1,
             0,
             0,
             1,
             1,
             0,
             0,
        },
        
        {
             1,
             1,
             1,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             1,
             0,
             0,
             1,
             1,
             1,
             1,
        },
        
        {
             1,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             1,
             0,
             0,
             1,
        },
    },
    
    {
        
        {
             0,
             1,
             0,
             0,
             0,
             0,
             1,
             1,
             1,
             1,
             1,
             0,
             0,
             0,
             1,
             0,
             0,
        },
        
        {
             0,
             1,
             0,
             0,
             0,
             0,
             1,
             1,
             1,
             1,
             1,
             0,
             0,
             0,
             1,
             1,
             1,
        },
        
        {
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             1,
        },
    },
    
    {
        
        {
             1,
             1,
             1,
             1,
             0,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
             0,
             0,
        },
        
        {
             1,
             1,
             1,
             1,
             0,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
             1,
        },
        
        {
             1,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             0,
             1,
             0,
             0,
             1,
        }
    }
};

static int txp_get_archetype_data(uint32_t enc_level,
                                  uint32_t archetype,
                                  struct archetype_data *a)
{
    if (enc_level >= QUIC_ENC_LEVEL_NUM
        || archetype >= TX_PACKETISER_ARCHETYPE_NUM)
        return 0;

    
    *a = archetypes[enc_level][archetype];
    return 1;
}

static int txp_determine_geometry(OSSL_QUIC_TX_PACKETISER *txp,
                                  uint32_t archetype,
                                  uint32_t enc_level,
                                  size_t running_total,
                                  QUIC_PKT_HDR *phdr,
                                  struct txp_pkt_geom *geom)
{
    size_t mdpl, cmpl, hdr_len;

    
    if (!txp_get_archetype_data(enc_level, archetype, &geom->adata))
       return 0;

    
    phdr->type          = ossl_quic_enc_level_to_pkt_type(enc_level);
    phdr->spin_bit      = 0;
    phdr->pn_len        = txp_determine_pn_len(txp);
    phdr->partial       = 0;
    phdr->fixed         = 1;
    phdr->reserved      = 0;
    phdr->version       = QUIC_VERSION_1;
    phdr->dst_conn_id   = txp->args.cur_dcid;
    phdr->src_conn_id   = txp->args.cur_scid;

    
    phdr->len           = OSSL_QUIC_VLINT_2B_MAX - phdr->pn_len;

    if (enc_level == QUIC_ENC_LEVEL_INITIAL) {
        phdr->token     = txp->initial_token;
        phdr->token_len = txp->initial_token_len;
    } else {
        phdr->token     = NULL;
        phdr->token_len = 0;
    }

    hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(phdr->dst_conn_id.id_len,
                                                     phdr);
    if (hdr_len == 0)
        return 0;

    
    mdpl = txp_get_mdpl(txp);

    
    if (running_total > mdpl)
        
        cmpl = 0;
    else
        cmpl = mdpl - running_total;

    
    if (!txp_determine_ppl_from_pl(txp, cmpl, enc_level, hdr_len, &geom->cmppl))
        return 0;

    geom->cmpl                  = cmpl;
    geom->pkt_overhead          = cmpl - geom->cmppl;
    geom->archetype             = archetype;
    return 1;
}

static uint32_t txp_determine_archetype(OSSL_QUIC_TX_PACKETISER *txp,
                                        uint64_t cc_limit)
{
    OSSL_ACKM_PROBE_INFO *probe_info
        = ossl_ackm_get0_probe_request(txp->args.ackm);
    uint32_t pn_space;

    
    if (probe_info->anti_deadlock_initial > 0
        || probe_info->anti_deadlock_handshake > 0)
        return TX_PACKETISER_ARCHETYPE_PROBE;

    for (pn_space = QUIC_PN_SPACE_INITIAL;
         pn_space < QUIC_PN_SPACE_NUM;
         ++pn_space)
        if (probe_info->pto[pn_space] > 0)
            return TX_PACKETISER_ARCHETYPE_PROBE;

    
    if (cc_limit == 0)
        return TX_PACKETISER_ARCHETYPE_ACK_ONLY;

    
    return TX_PACKETISER_ARCHETYPE_NORMAL;
}

static int txp_should_try_staging(OSSL_QUIC_TX_PACKETISER *txp,
                                  uint32_t enc_level,
                                  uint32_t archetype,
                                  uint64_t cc_limit,
                                  uint32_t *conn_close_enc_level)
{
    struct archetype_data a;
    uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
    QUIC_CFQ_ITEM *cfq_item;

    if (!ossl_qtx_is_enc_level_provisioned(txp->args.qtx, enc_level))
        return 0;

    if (!txp_get_archetype_data(enc_level, archetype, &a))
        return 0;

    if (!a.bypass_cc && cc_limit == 0)
        
        return 0;

    
    if (*conn_close_enc_level > enc_level
        && *conn_close_enc_level != QUIC_ENC_LEVEL_1RTT)
        *conn_close_enc_level = enc_level;

    
    if (a.allow_force_ack_eliciting) {
        OSSL_ACKM_PROBE_INFO *probe_info
            = ossl_ackm_get0_probe_request(txp->args.ackm);

        if ((enc_level == QUIC_ENC_LEVEL_INITIAL
             && probe_info->anti_deadlock_initial > 0)
            || (enc_level == QUIC_ENC_LEVEL_HANDSHAKE
                && probe_info->anti_deadlock_handshake > 0)
            || probe_info->pto[pn_space] > 0)
            return 1;
    }

    
    if (a.allow_crypto && sstream_is_pending(txp->args.crypto[pn_space]))
        return 1;

    
    if (a.allow_ack && (ossl_ackm_is_ack_desired(txp->args.ackm, pn_space)
                        || (txp->want_ack & (1UL << pn_space)) != 0))
        return 1;

    
    if (a.allow_force_ack_eliciting
        && (txp->force_ack_eliciting & (1UL << pn_space)) != 0)
        return 1;

    
    if (a.allow_conn_fc && (txp->want_max_data
        || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0)))
        return 1;

    
    if (a.allow_conn_fc
        && (txp->want_max_streams_bidi
            || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc,
                                              0)
            || txp->want_max_streams_uni
            || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc,
                                              0)))
        return 1;

    
    if (a.allow_handshake_done && txp->want_handshake_done)
        return 1;

    
    if (a.allow_conn_close && txp->want_conn_close &&
        *conn_close_enc_level == enc_level)
        
        return 1;

    
    if (enc_level != QUIC_ENC_LEVEL_0RTT)
        for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space);
             cfq_item != NULL;
             cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) {
            uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item);

            switch (frame_type) {
            case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
                if (a.allow_new_conn_id)
                    return 1;
                break;
            case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
                if (a.allow_retire_conn_id)
                    return 1;
                break;
            case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
                if (a.allow_new_token)
                    return 1;
                break;
            case OSSL_QUIC_FRAME_TYPE_PATH_RESPONSE:
                if (a.allow_path_response)
                    return 1;
                break;
            default:
                if (a.allow_cfq_other)
                    return 1;
                break;
            }
       }

    if (a.allow_stream_rel && txp->handshake_complete) {
        QUIC_STREAM_ITER it;

        
        ossl_quic_stream_iter_init(&it, txp->args.qsm, 0);
        if (it.stream != NULL)
            return 1;
    }

    return 0;
}

static int sstream_is_pending(QUIC_SSTREAM *sstream)
{
    OSSL_QUIC_FRAME_STREAM hdr;
    OSSL_QTX_IOVEC iov[2];
    size_t num_iov = OSSL_NELEM(iov);

    return ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov);
}


static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp)
{
    return 4; 
}


static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp,
                                     size_t pl,
                                     uint32_t enc_level,
                                     size_t hdr_len,
                                     size_t *r)
{
    if (pl < hdr_len)
        return 0;

    pl -= hdr_len;

    if (!ossl_qtx_calculate_plaintext_payload_len(txp->args.qtx, enc_level,
                                                  pl, &pl))
        return 0;

    *r = pl;
    return 1;
}

static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp)
{
    return ossl_qtx_get_mdpl(txp->args.qtx);
}

static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space,
                                       void *arg)
{
    OSSL_QUIC_TX_PACKETISER *txp = arg;
    QUIC_STREAM *s;

    if (stream_id == UINT64_MAX)
        return txp->args.crypto[pn_space];

    s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
    if (s == NULL)
        return NULL;

    return s->sstream;
}

static void on_regen_notify(uint64_t frame_type, uint64_t stream_id,
                            QUIC_TXPIM_PKT *pkt, void *arg)
{
    OSSL_QUIC_TX_PACKETISER *txp = arg;

    switch (frame_type) {
        case OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE:
            txp->want_handshake_done = 1;
            break;
        case OSSL_QUIC_FRAME_TYPE_MAX_DATA:
            txp->want_max_data = 1;
            break;
        case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI:
            txp->want_max_streams_bidi = 1;
            break;
        case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI:
            txp->want_max_streams_uni = 1;
            break;
        case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN:
            txp->want_ack |= (1UL << pkt->ackm_pkt.pkt_space);
            break;
        case OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA:
            {
                QUIC_STREAM *s
                    = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);

                if (s == NULL)
                    return;

                s->want_max_stream_data = 1;
                ossl_quic_stream_map_update_state(txp->args.qsm, s);
            }
            break;
        case OSSL_QUIC_FRAME_TYPE_STOP_SENDING:
            {
                QUIC_STREAM *s
                    = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);

                if (s == NULL)
                    return;

                ossl_quic_stream_map_schedule_stop_sending(txp->args.qsm, s);
            }
            break;
        case OSSL_QUIC_FRAME_TYPE_RESET_STREAM:
            {
                QUIC_STREAM *s
                    = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);

                if (s == NULL)
                    return;

                s->want_reset_stream = 1;
                ossl_quic_stream_map_update_state(txp->args.qsm, s);
            }
            break;
        default:
            assert(0);
            break;
    }
}

static int txp_pkt_init(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp,
                        uint32_t enc_level, uint32_t archetype,
                        size_t running_total)
{
    if (!txp_determine_geometry(txp, archetype, enc_level,
                                running_total, &pkt->phdr, &pkt->geom))
        return 0;

    
    if (!tx_helper_init(&pkt->h, txp, enc_level,
                        pkt->geom.cmppl,
                        pkt->geom.adata.require_ack_eliciting ? 1 : 0))
        return 0;

    pkt->h_valid            = 1;
    pkt->tpkt               = NULL;
    pkt->stream_head        = NULL;
    pkt->force_pad          = 0;
    return 1;
}

static void txp_pkt_cleanup(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp)
{
    if (!pkt->h_valid)
        return;

    tx_helper_cleanup(&pkt->h);
    pkt->h_valid = 0;

    if (pkt->tpkt != NULL) {
        ossl_quic_txpim_pkt_release(txp->args.txpim, pkt->tpkt);
        pkt->tpkt = NULL;
    }
}

static int txp_pkt_postgen_update_pkt_overhead(struct txp_pkt *pkt,
                                               OSSL_QUIC_TX_PACKETISER *txp)
{
    
    size_t hdr_len, ciphertext_len;

    if (pkt->h.enc_level == QUIC_ENC_LEVEL_INITIAL)
        
        return 1;

    if (!ossl_qtx_calculate_ciphertext_payload_len(txp->args.qtx, pkt->h.enc_level,
                                                   pkt->h.bytes_appended,
                                                   &ciphertext_len))
        return 0;

    pkt->phdr.len = ciphertext_len;

    hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(pkt->phdr.dst_conn_id.id_len,
                                                     &pkt->phdr);

    pkt->geom.pkt_overhead = hdr_len + ciphertext_len - pkt->h.bytes_appended;
    return 1;
}

static void on_confirm_notify(uint64_t frame_type, uint64_t stream_id,
                              QUIC_TXPIM_PKT *pkt, void *arg)
{
    OSSL_QUIC_TX_PACKETISER *txp = arg;

    switch (frame_type) {
        case OSSL_QUIC_FRAME_TYPE_STOP_SENDING:
            {
                QUIC_STREAM *s
                    = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);

                if (s == NULL)
                    return;

                s->acked_stop_sending = 1;
                ossl_quic_stream_map_update_state(txp->args.qsm, s);
            }
            break;
        case OSSL_QUIC_FRAME_TYPE_RESET_STREAM:
            {
                QUIC_STREAM *s
                    = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);

                if (s == NULL)
                    return;

                
                ossl_quic_stream_map_notify_reset_stream_acked(txp->args.qsm, s);
                ossl_quic_stream_map_update_state(txp->args.qsm, s);
            }
            break;
        default:
            assert(0);
            break;
    }
}

static int txp_pkt_append_padding(struct txp_pkt *pkt,
                                  OSSL_QUIC_TX_PACKETISER *txp, size_t num_bytes)
{
    WPACKET *wpkt;

    if (num_bytes == 0)
        return 1;

    if (!ossl_assert(pkt->h_valid))
        return 0;

    if (!ossl_assert(pkt->tpkt != NULL))
        return 0;

    wpkt = tx_helper_begin(&pkt->h);
    if (wpkt == NULL)
        return 0;

    if (!ossl_quic_wire_encode_padding(wpkt, num_bytes)) {
        tx_helper_rollback(&pkt->h);
        return 0;
    }

    if (!tx_helper_commit(&pkt->h))
        return 0;

    pkt->tpkt->ackm_pkt.num_bytes      += num_bytes;
    
    pkt->tpkt->ackm_pkt.is_inflight     = 1;
    return 1;
}

static void on_sstream_updated(uint64_t stream_id, void *arg)
{
    OSSL_QUIC_TX_PACKETISER *txp = arg;
    QUIC_STREAM *s;

    s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
    if (s == NULL)
        return;

    ossl_quic_stream_map_update_state(txp->args.qsm, s);
}


static int try_commit_conn_close(OSSL_QUIC_TX_PACKETISER *txp, size_t n)
{
    int res;

    
    if (txp->closing_bytes_recv == 0)
        return 1;

    
    res = txp->closing_bytes_xmit + n <= txp->closing_bytes_recv * 3;

    
    if (res && txp->closing_bytes_recv != 0)
        txp->closing_bytes_xmit += n;
    return res;
}

void ossl_quic_tx_packetiser_record_received_closing_bytes(
        OSSL_QUIC_TX_PACKETISER *txp, size_t n)
{
    txp->closing_bytes_recv += n;
}

static int txp_generate_pre_token(OSSL_QUIC_TX_PACKETISER *txp,
                                  struct txp_pkt *pkt,
                                  int chosen_for_conn_close,
                                  int *can_be_non_inflight)
{
    const uint32_t enc_level = pkt->h.enc_level;
    const uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
    const struct archetype_data *a = &pkt->geom.adata;
    QUIC_TXPIM_PKT *tpkt = pkt->tpkt;
    struct tx_helper *h = &pkt->h;
    const OSSL_QUIC_FRAME_ACK *ack;
    OSSL_QUIC_FRAME_ACK ack2;

    tpkt->ackm_pkt.largest_acked = QUIC_PN_INVALID;

    
    if (a->allow_ack
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_ACK
        && (((txp->want_ack & (1UL << pn_space)) != 0)
            || ossl_ackm_is_ack_desired(txp->args.ackm, pn_space))
        && (ack = ossl_ackm_get_ack_frame(txp->args.ackm, pn_space)) != NULL) {
        WPACKET *wpkt = tx_helper_begin(h);

        if (wpkt == NULL)
            return 0;

        
        ack2 = *ack;
        ack2.ecn_present = 0;

        if (ossl_quic_wire_encode_frame_ack(wpkt,
                                            txp->args.ack_delay_exponent,
                                            &ack2)) {
            if (!tx_helper_commit(h))
                return 0;

            tpkt->had_ack_frame = 1;

            if (ack->num_ack_ranges > 0)
                tpkt->ackm_pkt.largest_acked = ack->ack_ranges[0].end;

            if (txp->ack_tx_cb != NULL)
                txp->ack_tx_cb(&ack2, pn_space, txp->ack_tx_cb_arg);
        } else {
            tx_helper_rollback(h);
        }
    }

    
    if (a->allow_conn_close && txp->want_conn_close && chosen_for_conn_close) {
        WPACKET *wpkt = tx_helper_begin(h);
        OSSL_QUIC_FRAME_CONN_CLOSE f, *pf = &txp->conn_close_frame;
        size_t l;

        if (wpkt == NULL)
            return 0;

        
        if (pn_space != QUIC_PN_SPACE_APP && pf->is_app) {
            pf = &f;
            pf->is_app      = 0;
            pf->frame_type  = 0;
            pf->error_code  = OSSL_QUIC_ERR_APPLICATION_ERROR;
            pf->reason      = NULL;
            pf->reason_len  = 0;
        }

        if (ossl_quic_wire_encode_frame_conn_close(wpkt, pf)
                && WPACKET_get_total_written(wpkt, &l)
                && try_commit_conn_close(txp, l)) {
            if (!tx_helper_commit(h))
                return 0;

            tpkt->had_conn_close = 1;
            *can_be_non_inflight = 0;
        } else {
            tx_helper_rollback(h);
        }
    }

    return 1;
}

static int try_len(size_t space_left, size_t orig_len,
                   size_t base_hdr_len, size_t lenbytes,
                   uint64_t maxn, size_t *hdr_len, size_t *payload_len)
{
    size_t n;
    size_t maxn_ = maxn > SIZE_MAX ? SIZE_MAX : (size_t)maxn;

    *hdr_len = base_hdr_len + lenbytes;

    if (orig_len == 0 && space_left >= *hdr_len) {
        *payload_len = 0;
        return 1;
    }

    n = orig_len;
    if (n > maxn_)
        n = maxn_;
    if (n + *hdr_len > space_left)
        n = (space_left >= *hdr_len) ? space_left - *hdr_len : 0;

    *payload_len = n;
    return n > 0;
}

static int determine_len(size_t space_left, size_t orig_len,
                         size_t base_hdr_len,
                         uint64_t *hlen, uint64_t *len)
{
    int ok = 0;
    size_t chosen_payload_len = 0;
    size_t chosen_hdr_len     = 0;
    size_t payload_len[4], hdr_len[4];
    int i, valid[4] = {0};

    valid[0] = try_len(space_left, orig_len, base_hdr_len,
                       1, OSSL_QUIC_VLINT_1B_MAX,
                       &hdr_len[0], &payload_len[0]);
    valid[1] = try_len(space_left, orig_len, base_hdr_len,
                       2, OSSL_QUIC_VLINT_2B_MAX,
                       &hdr_len[1], &payload_len[1]);
    valid[2] = try_len(space_left, orig_len, base_hdr_len,
                       4, OSSL_QUIC_VLINT_4B_MAX,
                       &hdr_len[2], &payload_len[2]);
    valid[3] = try_len(space_left, orig_len, base_hdr_len,
                       8, OSSL_QUIC_VLINT_8B_MAX,
                       &hdr_len[3], &payload_len[3]);

   for (i = OSSL_NELEM(valid) - 1; i >= 0; --i)
        if (valid[i] && payload_len[i] >= chosen_payload_len) {
            chosen_payload_len = payload_len[i];
            chosen_hdr_len     = hdr_len[i];
            ok                 = 1;
        }

    *hlen = chosen_hdr_len;
    *len  = chosen_payload_len;
    return ok;
}


static int determine_crypto_len(struct tx_helper *h,
                                OSSL_QUIC_FRAME_CRYPTO *chdr,
                                size_t space_left,
                                uint64_t *hlen,
                                uint64_t *len)
{
    size_t orig_len;
    size_t base_hdr_len; 

    if (chdr->len > SIZE_MAX)
        return 0;

    orig_len = (size_t)chdr->len;

    chdr->len = 0;
    base_hdr_len = ossl_quic_wire_get_encoded_frame_len_crypto_hdr(chdr);
    chdr->len = orig_len;
    if (base_hdr_len == 0)
        return 0;

    --base_hdr_len;

    return determine_len(space_left, orig_len, base_hdr_len, hlen, len);
}

static int determine_stream_len(struct tx_helper *h,
                                OSSL_QUIC_FRAME_STREAM *shdr,
                                size_t space_left,
                                uint64_t *hlen,
                                uint64_t *len)
{
    size_t orig_len;
    size_t base_hdr_len; 

    if (shdr->len > SIZE_MAX)
        return 0;

    orig_len = (size_t)shdr->len;

    shdr->len = 0;
    base_hdr_len = ossl_quic_wire_get_encoded_frame_len_stream_hdr(shdr);
    shdr->len = orig_len;
    if (base_hdr_len == 0)
        return 0;

    if (shdr->has_explicit_len)
        --base_hdr_len;

    return determine_len(space_left, orig_len, base_hdr_len, hlen, len);
}

static int txp_generate_crypto_frames(OSSL_QUIC_TX_PACKETISER *txp,
                                      struct txp_pkt *pkt,
                                      int *have_ack_eliciting)
{
    const uint32_t enc_level = pkt->h.enc_level;
    const uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
    QUIC_TXPIM_PKT *tpkt = pkt->tpkt;
    struct tx_helper *h = &pkt->h;
    size_t num_stream_iovec;
    OSSL_QUIC_FRAME_STREAM shdr = {0};
    OSSL_QUIC_FRAME_CRYPTO chdr = {0};
    OSSL_QTX_IOVEC iov[2];
    uint64_t hdr_bytes;
    WPACKET *wpkt;
    QUIC_TXPIM_CHUNK chunk = {0};
    size_t i, space_left;

    for (i = 0;; ++i) {
        space_left = tx_helper_get_space_left(h);

        if (space_left < MIN_FRAME_SIZE_CRYPTO)
            return 1; 

        
        num_stream_iovec = OSSL_NELEM(iov);
        if (!ossl_quic_sstream_get_stream_frame(txp->args.crypto[pn_space],
                                                i, &shdr, iov,
                                                &num_stream_iovec))
            return 1; 

        
        chdr.offset = shdr.offset;
        chdr.len    = shdr.len;

        if (chdr.len == 0)
            return 1; 

        
        if (!determine_crypto_len(h, &chdr, space_left, &hdr_bytes,
                                  &chdr.len))
            return 1; 

        
        ossl_quic_sstream_adjust_iov((size_t)chdr.len, iov, num_stream_iovec);

        
        if (!txp_el_ensure_iovec(&txp->el[enc_level], h->num_iovec + 3))
            return 0; 

        
        wpkt = tx_helper_begin(h);
        if (wpkt == NULL)
            return 0; 

        if (!ossl_quic_wire_encode_frame_crypto_hdr(wpkt, &chdr)) {
            tx_helper_rollback(h);
            return 1; 
        }

        if (!tx_helper_commit(h))
            return 0; 

        
        for (i = 0; i < num_stream_iovec; ++i)
            tx_helper_append_iovec(h, iov[i].buf, iov[i].buf_len);

        *have_ack_eliciting = 1;
        tx_helper_unrestrict(h); 

        
        chunk.stream_id = UINT64_MAX; 
        chunk.start     = chdr.offset;
        chunk.end       = chdr.offset + chdr.len - 1;
        chunk.has_fin   = 0; 
        if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
            return 0; 
    }
}

struct chunk_info {
    OSSL_QUIC_FRAME_STREAM shdr;
    uint64_t orig_len;
    OSSL_QTX_IOVEC iov[2];
    size_t num_stream_iovec;
    int valid;
};

static int txp_plan_stream_chunk(OSSL_QUIC_TX_PACKETISER *txp,
                                 struct tx_helper *h,
                                 QUIC_SSTREAM *sstream,
                                 QUIC_TXFC *stream_txfc,
                                 size_t skip,
                                 struct chunk_info *chunk,
                                 uint64_t consumed)
{
    uint64_t fc_credit, fc_swm, fc_limit;

    chunk->num_stream_iovec = OSSL_NELEM(chunk->iov);
    chunk->valid = ossl_quic_sstream_get_stream_frame(sstream, skip,
                                                      &chunk->shdr,
                                                      chunk->iov,
                                                      &chunk->num_stream_iovec);
    if (!chunk->valid)
        return 1;

    if (!ossl_assert(chunk->shdr.len > 0 || chunk->shdr.is_fin))
        
        return 0;

    chunk->orig_len = chunk->shdr.len;

    
    fc_credit   = ossl_quic_txfc_get_credit(stream_txfc, consumed);
    fc_swm      = ossl_quic_txfc_get_swm(stream_txfc);
    fc_limit    = fc_swm + fc_credit;

    if (chunk->shdr.len > 0 && chunk->shdr.offset + chunk->shdr.len > fc_limit) {
        chunk->shdr.len = (fc_limit <= chunk->shdr.offset)
            ? 0 : fc_limit - chunk->shdr.offset;
        chunk->shdr.is_fin = 0;
    }

    if (chunk->shdr.len == 0 && !chunk->shdr.is_fin) {
        
        chunk->valid = 0;
        return 1;
    }

    return 1;
}


static int txp_generate_stream_frames(OSSL_QUIC_TX_PACKETISER *txp,
                                      struct txp_pkt *pkt,
                                      uint64_t id,
                                      QUIC_SSTREAM *sstream,
                                      QUIC_TXFC *stream_txfc,
                                      QUIC_STREAM *next_stream,
                                      int *have_ack_eliciting,
                                      int *packet_full,
                                      uint64_t *new_credit_consumed,
                                      uint64_t conn_consumed)
{
    int rc = 0;
    struct chunk_info chunks[2] = {0};
    const uint32_t enc_level = pkt->h.enc_level;
    QUIC_TXPIM_PKT *tpkt = pkt->tpkt;
    struct tx_helper *h = &pkt->h;
    OSSL_QUIC_FRAME_STREAM *shdr;
    WPACKET *wpkt;
    QUIC_TXPIM_CHUNK chunk;
    size_t i, j, space_left;
    int can_fill_payload, use_explicit_len;
    int could_have_following_chunk;
    uint64_t orig_len;
    uint64_t hdr_len_implicit, payload_len_implicit;
    uint64_t hdr_len_explicit, payload_len_explicit;
    uint64_t fc_swm, fc_new_hwm;

    fc_swm      = ossl_quic_txfc_get_swm(stream_txfc);
    fc_new_hwm  = fc_swm;

    
    for (i = 0; i < 2; ++i) {
        if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i, &chunks[i],
                                   conn_consumed))
            goto err;

        if (i == 0 && !chunks[i].valid) {
            
            rc = 1;
            goto err;
        }
    }

    for (i = 0;; ++i) {
        space_left = tx_helper_get_space_left(h);

        if (!chunks[i % 2].valid) {
            
            rc = 1;
            goto err;
        }

        if (space_left < MIN_FRAME_SIZE_STREAM) {
            *packet_full = 1;
            rc = 1;
            goto err;
        }

        if (!ossl_assert(!h->done_implicit))
            
            goto err;

        shdr = &chunks[i % 2].shdr;
        orig_len = chunks[i % 2].orig_len;
        if (i > 0)
            
            if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i + 1,
                                       &chunks[(i + 1) % 2], conn_consumed))
                goto err;

        
        shdr->has_explicit_len = 0;
        hdr_len_implicit = payload_len_implicit = 0;
        if (!determine_stream_len(h, shdr, space_left,
                                  &hdr_len_implicit, &payload_len_implicit)) {
            *packet_full = 1;
            rc = 1;
            goto err; 
        }

        
        can_fill_payload = (hdr_len_implicit + payload_len_implicit
                            >= space_left);

        
        could_have_following_chunk
            = (next_stream != NULL || chunks[(i + 1) % 2].valid);

        
        use_explicit_len = !((can_fill_payload || !could_have_following_chunk)
                             && !pkt->force_pad);

        if (use_explicit_len) {
            
            shdr->has_explicit_len = 1;
            hdr_len_explicit = payload_len_explicit = 0;
            if (!determine_stream_len(h, shdr, space_left,
                                      &hdr_len_explicit, &payload_len_explicit)) {
                *packet_full = 1;
                rc = 1;
                goto err; 
            }

            shdr->len = payload_len_explicit;
        } else {
            *packet_full = 1;
            shdr->has_explicit_len = 0;
            shdr->len = payload_len_implicit;
        }

        
        if (shdr->is_fin)
            chunks[(i + 1) % 2].valid = 0;

        
        if (shdr->len < orig_len)
            shdr->is_fin = 0;

        
        ossl_quic_sstream_adjust_iov((size_t)shdr->len, chunks[i % 2].iov,
                                     chunks[i % 2].num_stream_iovec);

        
        if (!txp_el_ensure_iovec(&txp->el[enc_level], h->num_iovec + 3))
            goto err; 

        
        wpkt = tx_helper_begin(h);
        if (wpkt == NULL)
            goto err; 

        shdr->stream_id = id;
        if (!ossl_assert(ossl_quic_wire_encode_frame_stream_hdr(wpkt, shdr))) {
            
            tx_helper_rollback(h);
            *packet_full = 1;
            rc = 1;
            goto err; 
        }

        if (!tx_helper_commit(h))
            goto err; 

        
        for (j = 0; j < chunks[i % 2].num_stream_iovec; ++j)
            tx_helper_append_iovec(h, chunks[i % 2].iov[j].buf,
                                   chunks[i % 2].iov[j].buf_len);

        *have_ack_eliciting = 1;
        tx_helper_unrestrict(h); 
        if (!shdr->has_explicit_len)
            h->done_implicit = 1;

        
        if (shdr->len > 0 && shdr->offset + shdr->len > fc_new_hwm)
            fc_new_hwm = shdr->offset + shdr->len;

        
        chunk.stream_id         = shdr->stream_id;
        chunk.start             = shdr->offset;
        chunk.end               = shdr->offset + shdr->len - 1;
        chunk.has_fin           = shdr->is_fin;
        chunk.has_stop_sending  = 0;
        chunk.has_reset_stream  = 0;
        if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
            goto err; 

        if (shdr->len < orig_len) {
            
            rc = 1;
            goto err;
        }
    }

err:
    *new_credit_consumed = fc_new_hwm - fc_swm;
    return rc;
}

static void txp_enlink_tmp(QUIC_STREAM **tmp_head, QUIC_STREAM *stream)
{
    stream->txp_next = *tmp_head;
    *tmp_head = stream;
}

static int txp_generate_stream_related(OSSL_QUIC_TX_PACKETISER *txp,
                                       struct txp_pkt *pkt,
                                       int *have_ack_eliciting,
                                       QUIC_STREAM **tmp_head)
{
    QUIC_STREAM_ITER it;
    WPACKET *wpkt;
    uint64_t cwm;
    QUIC_STREAM *stream, *snext;
    struct tx_helper *h = &pkt->h;
    uint64_t conn_consumed = 0;

    for (ossl_quic_stream_iter_init(&it, txp->args.qsm, 1);
         it.stream != NULL;) {

        stream = it.stream;
        ossl_quic_stream_iter_next(&it);
        snext = it.stream;

        stream->txp_sent_fc                  = 0;
        stream->txp_sent_stop_sending        = 0;
        stream->txp_sent_reset_stream        = 0;
        stream->txp_blocked                  = 0;
        stream->txp_txfc_new_credit_consumed = 0;

        
        if (stream->want_stop_sending) {
            OSSL_QUIC_FRAME_STOP_SENDING f;

            wpkt = tx_helper_begin(h);
            if (wpkt == NULL)
                return 0; 

            f.stream_id         = stream->id;
            f.app_error_code    = stream->stop_sending_aec;
            if (!ossl_quic_wire_encode_frame_stop_sending(wpkt, &f)) {
                tx_helper_rollback(h); 
                txp_enlink_tmp(tmp_head, stream);
                break;
            }

            if (!tx_helper_commit(h))
                return 0; 

            *have_ack_eliciting = 1;
            tx_helper_unrestrict(h); 
            stream->txp_sent_stop_sending = 1;
        }

        if (stream->want_reset_stream) {
            OSSL_QUIC_FRAME_RESET_STREAM f;

            if (!ossl_assert(stream->send_state == QUIC_SSTREAM_STATE_RESET_SENT))
                return 0;

            wpkt = tx_helper_begin(h);
            if (wpkt == NULL)
                return 0; 

            f.stream_id         = stream->id;
            f.app_error_code    = stream->reset_stream_aec;
            if (!ossl_quic_stream_send_get_final_size(stream, &f.final_size))
                return 0; 

            if (!ossl_quic_wire_encode_frame_reset_stream(wpkt, &f)) {
                tx_helper_rollback(h); 
                txp_enlink_tmp(tmp_head, stream);
                break;
            }

            if (!tx_helper_commit(h))
                return 0; 

            *have_ack_eliciting = 1;
            tx_helper_unrestrict(h); 
            stream->txp_sent_reset_stream = 1;

            
            if (!ossl_assert(f.final_size <= ossl_quic_txfc_get_swm(&stream->txfc)))
                return 0;

            stream->txp_txfc_new_credit_consumed
                = f.final_size - ossl_quic_txfc_get_swm(&stream->txfc);
        }

        
        if (stream->recv_state == QUIC_RSTREAM_STATE_RECV
            && (stream->want_max_stream_data
                || ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 0))) {

            wpkt = tx_helper_begin(h);
            if (wpkt == NULL)
                return 0; 

            cwm = ossl_quic_rxfc_get_cwm(&stream->rxfc);

            if (!ossl_quic_wire_encode_frame_max_stream_data(wpkt, stream->id,
                                                             cwm)) {
                tx_helper_rollback(h); 
                txp_enlink_tmp(tmp_head, stream);
                break;
            }

            if (!tx_helper_commit(h))
                return 0; 

            *have_ack_eliciting = 1;
            tx_helper_unrestrict(h); 
            stream->txp_sent_fc = 1;
        }

        
        if (ossl_quic_stream_has_send_buffer(stream)
            && !ossl_quic_stream_send_is_reset(stream)) {
            int packet_full = 0;

            if (!ossl_assert(!stream->want_reset_stream))
                return 0;

            if (!txp_generate_stream_frames(txp, pkt,
                                            stream->id, stream->sstream,
                                            &stream->txfc,
                                            snext,
                                            have_ack_eliciting,
                                            &packet_full,
                                            &stream->txp_txfc_new_credit_consumed,
                                            conn_consumed)) {
                
                txp_enlink_tmp(tmp_head, stream);
                return 0;
            }
            conn_consumed += stream->txp_txfc_new_credit_consumed;

            if (packet_full) {
                txp_enlink_tmp(tmp_head, stream);
                break;
            }
        }

        txp_enlink_tmp(tmp_head, stream);
    }

    return 1;
}

static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp,
                               struct txp_pkt *pkt,
                               int chosen_for_conn_close)
{
    int rc = TXP_ERR_SUCCESS;
    const uint32_t enc_level = pkt->h.enc_level;
    const uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
    int have_ack_eliciting = 0, done_pre_token = 0;
    const struct archetype_data a = pkt->geom.adata;
    
    int can_be_non_inflight = 1;
    QUIC_CFQ_ITEM *cfq_item;
    QUIC_TXPIM_PKT *tpkt = NULL;
    struct tx_helper *h = &pkt->h;

    
    if (!ossl_quic_pn_valid(txp->next_pn[pn_space]))
        goto fatal_err;

    if (!ossl_assert(pkt->tpkt == NULL))
        goto fatal_err;

    if ((pkt->tpkt = tpkt = ossl_quic_txpim_pkt_alloc(txp->args.txpim)) == NULL)
        goto fatal_err;

    

    
    if (a.allow_handshake_done && txp->want_handshake_done
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_HANDSHAKE_DONE) {
        WPACKET *wpkt = tx_helper_begin(h);

        if (wpkt == NULL)
            goto fatal_err;

        if (ossl_quic_wire_encode_frame_handshake_done(wpkt)) {
            tpkt->had_handshake_done_frame = 1;
            have_ack_eliciting             = 1;

            if (!tx_helper_commit(h))
                goto fatal_err;

            tx_helper_unrestrict(h); 
        } else {
            tx_helper_rollback(h);
        }
    }

    
    if (a.allow_conn_fc
        && (txp->want_max_data
            || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0))
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_MAX_DATA) {
        WPACKET *wpkt = tx_helper_begin(h);
        uint64_t cwm = ossl_quic_rxfc_get_cwm(txp->args.conn_rxfc);

        if (wpkt == NULL)
            goto fatal_err;

        if (ossl_quic_wire_encode_frame_max_data(wpkt, cwm)) {
            tpkt->had_max_data_frame = 1;
            have_ack_eliciting       = 1;

            if (!tx_helper_commit(h))
                goto fatal_err;

            tx_helper_unrestrict(h); 
        } else {
            tx_helper_rollback(h);
        }
    }

    
    if (a.allow_conn_fc
        && (txp->want_max_streams_bidi
            || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 0))
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_MAX_STREAMS_BIDI) {
        WPACKET *wpkt = tx_helper_begin(h);
        uint64_t max_streams
            = ossl_quic_rxfc_get_cwm(txp->args.max_streams_bidi_rxfc);

        if (wpkt == NULL)
            goto fatal_err;

        if (ossl_quic_wire_encode_frame_max_streams(wpkt, 0,
                                                    max_streams)) {
            tpkt->had_max_streams_bidi_frame = 1;
            have_ack_eliciting               = 1;

            if (!tx_helper_commit(h))
                goto fatal_err;

            tx_helper_unrestrict(h); 
        } else {
            tx_helper_rollback(h);
        }
    }

    
    if (a.allow_conn_fc
        && (txp->want_max_streams_uni
            || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 0))
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_MAX_STREAMS_UNI) {
        WPACKET *wpkt = tx_helper_begin(h);
        uint64_t max_streams
            = ossl_quic_rxfc_get_cwm(txp->args.max_streams_uni_rxfc);

        if (wpkt == NULL)
            goto fatal_err;

        if (ossl_quic_wire_encode_frame_max_streams(wpkt, 1,
                                                    max_streams)) {
            tpkt->had_max_streams_uni_frame = 1;
            have_ack_eliciting              = 1;

            if (!tx_helper_commit(h))
                goto fatal_err;

            tx_helper_unrestrict(h); 
        } else {
            tx_helper_rollback(h);
        }
    }

    
    for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space);
         cfq_item != NULL;
         cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) {
        uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item);
        const unsigned char *encoded = ossl_quic_cfq_item_get_encoded(cfq_item);
        size_t encoded_len = ossl_quic_cfq_item_get_encoded_len(cfq_item);

        switch (frame_type) {
            case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
                if (!a.allow_new_conn_id)
                    continue;
                break;
            case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
                if (!a.allow_retire_conn_id)
                    continue;
                break;
            case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
                if (!a.allow_new_token)
                    continue;

                
                if (!done_pre_token)
                    if (txp_generate_pre_token(txp, pkt,
                                               chosen_for_conn_close,
                                               &can_be_non_inflight))
                        done_pre_token = 1;

                break;
            case OSSL_QUIC_FRAME_TYPE_PATH_RESPONSE:
                if (!a.allow_path_response)
                    continue;

                
                pkt->force_pad = 1;
                break;
            default:
                if (!a.allow_cfq_other)
                    continue;
                break;
        }

        
        if (encoded_len > tx_helper_get_space_left(h))
            break;

        if (!tx_helper_append_iovec(h, encoded, encoded_len))
            goto fatal_err;

        ossl_quic_txpim_pkt_add_cfq_item(tpkt, cfq_item);

        if (ossl_quic_frame_type_is_ack_eliciting(frame_type)) {
            have_ack_eliciting = 1;
            tx_helper_unrestrict(h); 
        }
    }

    
    if (!done_pre_token)
        if (txp_generate_pre_token(txp, pkt,
                                   chosen_for_conn_close,
                                   &can_be_non_inflight))
            done_pre_token = 1;

    
    if (a.allow_crypto)
        if (!txp_generate_crypto_frames(txp, pkt, &have_ack_eliciting))
            goto fatal_err;

    
    if (a.allow_stream_rel && txp->handshake_complete)
        if (!txp_generate_stream_related(txp, pkt,
                                         &have_ack_eliciting,
                                         &pkt->stream_head))
            goto fatal_err;

    
    tx_helper_unrestrict(h);

    if ((a.require_ack_eliciting
         || (txp->force_ack_eliciting & (1UL << pn_space)) != 0)
        && !have_ack_eliciting && a.allow_ping) {
        WPACKET *wpkt;

        wpkt = tx_helper_begin(h);
        if (wpkt == NULL)
            goto fatal_err;

        if (!ossl_quic_wire_encode_frame_ping(wpkt)
            || !tx_helper_commit(h))
            
            goto fatal_err;

        have_ack_eliciting = 1;
    }

    

    
    if (have_ack_eliciting)
        can_be_non_inflight = 0;

    
    tpkt->ackm_pkt.num_bytes        = h->bytes_appended + pkt->geom.pkt_overhead;
    tpkt->ackm_pkt.pkt_num          = txp->next_pn[pn_space];
    
    tpkt->ackm_pkt.pkt_space        = pn_space;
    tpkt->ackm_pkt.is_inflight      = !can_be_non_inflight;
    tpkt->ackm_pkt.is_ack_eliciting = have_ack_eliciting;
    tpkt->ackm_pkt.is_pto_probe     = 0;
    tpkt->ackm_pkt.is_mtu_probe     = 0;
    tpkt->ackm_pkt.time             = txp->args.now(txp->args.now_arg);
    tpkt->pkt_type                  = pkt->phdr.type;

    
    return rc;

fatal_err:
    
    if (tpkt != NULL) {
        ossl_quic_txpim_pkt_release(txp->args.txpim, tpkt);
        pkt->tpkt = NULL;
    }
    return TXP_ERR_INTERNAL;
}


static int txp_pkt_commit(OSSL_QUIC_TX_PACKETISER *txp,
                          struct txp_pkt *pkt,
                          uint32_t archetype,
                          int *txpim_pkt_reffed)
{
    int rc = 1;
    uint32_t enc_level = pkt->h.enc_level;
    uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
    QUIC_TXPIM_PKT *tpkt = pkt->tpkt;
    QUIC_STREAM *stream;
    OSSL_QTX_PKT txpkt;
    struct archetype_data a;

    *txpim_pkt_reffed = 0;

    
    if (pkt->h.bytes_appended == 0)
        return 0;

    if (!txp_get_archetype_data(enc_level, archetype, &a))
        return 0;

    
    txpkt.hdr       = &pkt->phdr;
    txpkt.iovec     = txp->el[enc_level].iovec;
    txpkt.num_iovec = pkt->h.num_iovec;
    txpkt.local     = NULL;
    txpkt.peer      = BIO_ADDR_family(&txp->args.peer) == AF_UNSPEC
        ? NULL : &txp->args.peer;
    txpkt.pn        = txp->next_pn[pn_space];
    txpkt.flags     = OSSL_QTX_PKT_FLAG_COALESCE; 

    
    for (stream = pkt->stream_head; stream != NULL; stream = stream->txp_next)
        if (stream->txp_sent_stop_sending || stream->txp_sent_reset_stream) {
            
            QUIC_TXPIM_CHUNK chunk;

            chunk.stream_id         = stream->id;
            chunk.start             = UINT64_MAX;
            chunk.end               = 0;
            chunk.has_fin           = 0;
            chunk.has_stop_sending  = stream->txp_sent_stop_sending;
            chunk.has_reset_stream  = stream->txp_sent_reset_stream;
            if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
                return 0; 
        }

    
    if (!ossl_quic_fifd_pkt_commit(&txp->fifd, tpkt))
        return 0;

    
    ++txp->next_pn[pn_space];
    *txpim_pkt_reffed = 1;

    
    if (!ossl_qtx_write_pkt(txp->args.qtx, &txpkt))
        return 0;

    
    for (stream = pkt->stream_head; stream != NULL; stream = stream->txp_next) {
        if (stream->txp_sent_fc) {
            stream->want_max_stream_data = 0;
            ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 1);
        }

        if (stream->txp_sent_stop_sending)
            stream->want_stop_sending = 0;

        if (stream->txp_sent_reset_stream)
            stream->want_reset_stream = 0;

        if (stream->txp_txfc_new_credit_consumed > 0) {
            if (!ossl_assert(ossl_quic_txfc_consume_credit(&stream->txfc,
                                                           stream->txp_txfc_new_credit_consumed)))
                
                rc = 0;

            stream->txp_txfc_new_credit_consumed = 0;
        }

        
        ossl_quic_stream_map_update_state(txp->args.qsm, stream);

        if (ossl_quic_stream_has_send_buffer(stream)
            && !ossl_quic_sstream_has_pending(stream->sstream)
            && ossl_quic_sstream_get_final_size(stream->sstream, NULL))
            
            ossl_quic_stream_map_notify_all_data_sent(txp->args.qsm, stream);
    }

    
    if (tpkt->ackm_pkt.is_ack_eliciting)
        txp->force_ack_eliciting &= ~(1UL << pn_space);

    if (tpkt->had_handshake_done_frame)
        txp->want_handshake_done = 0;

    if (tpkt->had_max_data_frame) {
        txp->want_max_data = 0;
        ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 1);
    }

    if (tpkt->had_max_streams_bidi_frame) {
        txp->want_max_streams_bidi = 0;
        ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 1);
    }

    if (tpkt->had_max_streams_uni_frame) {
        txp->want_max_streams_uni = 0;
        ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 1);
    }

    if (tpkt->had_ack_frame)
        txp->want_ack &= ~(1UL << pn_space);

    if (tpkt->had_conn_close)
        txp->want_conn_close = 0;

    
    if (tpkt->ackm_pkt.is_ack_eliciting) {
        OSSL_ACKM_PROBE_INFO *probe_info
            = ossl_ackm_get0_probe_request(txp->args.ackm);

        if (enc_level == QUIC_ENC_LEVEL_INITIAL
            && probe_info->anti_deadlock_initial > 0)
            --probe_info->anti_deadlock_initial;

        if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE
            && probe_info->anti_deadlock_handshake > 0)
            --probe_info->anti_deadlock_handshake;

        if (a.allow_force_ack_eliciting 
            && probe_info->pto[pn_space] > 0)
            --probe_info->pto[pn_space];
    }

    return rc;
}


static int txp_el_ensure_iovec(struct txp_el *el, size_t num)
{
    OSSL_QTX_IOVEC *iovec;

    if (el->alloc_iovec >= num)
        return 1;

    num = el->alloc_iovec != 0 ? el->alloc_iovec * 2 : 8;

    iovec = OPENSSL_realloc(el->iovec, sizeof(OSSL_QTX_IOVEC) * num);
    if (iovec == NULL)
        return 0;

    el->iovec          = iovec;
    el->alloc_iovec    = num;
    return 1;
}

int ossl_quic_tx_packetiser_schedule_conn_close(OSSL_QUIC_TX_PACKETISER *txp,
                                                const OSSL_QUIC_FRAME_CONN_CLOSE *f)
{
    char *reason = NULL;
    size_t reason_len = f->reason_len;
    size_t max_reason_len = txp_get_mdpl(txp) / 2;

    if (txp->want_conn_close)
        return 0;

    
    if (reason_len > max_reason_len)
        reason_len = max_reason_len;

    if (reason_len > 0) {
        reason = OPENSSL_memdup(f->reason, reason_len);
        if (reason == NULL)
            return 0;
    }

    txp->conn_close_frame               = *f;
    txp->conn_close_frame.reason        = reason;
    txp->conn_close_frame.reason_len    = reason_len;
    txp->want_conn_close                = 1;
    return 1;
}

void ossl_quic_tx_packetiser_set_msg_callback(OSSL_QUIC_TX_PACKETISER *txp,
                                              ossl_msg_cb msg_callback,
                                              SSL *msg_callback_ssl)
{
    txp->msg_callback = msg_callback;
    txp->msg_callback_ssl = msg_callback_ssl;
}

void ossl_quic_tx_packetiser_set_msg_callback_arg(OSSL_QUIC_TX_PACKETISER *txp,
                                                  void *msg_callback_arg)
{
    txp->msg_callback_arg = msg_callback_arg;
}

QUIC_PN ossl_quic_tx_packetiser_get_next_pn(OSSL_QUIC_TX_PACKETISER *txp,
                                            uint32_t pn_space)
{
    if (pn_space >= QUIC_PN_SPACE_NUM)
        return UINT64_MAX;

    return txp->next_pn[pn_space];
}

OSSL_TIME ossl_quic_tx_packetiser_get_deadline(OSSL_QUIC_TX_PACKETISER *txp)
{
    
    OSSL_TIME deadline = ossl_time_infinite();
    uint32_t enc_level, pn_space;

    
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
         enc_level < QUIC_ENC_LEVEL_NUM;
         ++enc_level)
        if (ossl_qtx_is_enc_level_provisioned(txp->args.qtx, enc_level)) {
            pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
            deadline = ossl_time_min(deadline,
                                     ossl_ackm_get_ack_deadline(txp->args.ackm, pn_space));
        }

    
    if (txp->args.cc_method->get_tx_allowance(txp->args.cc_data) == 0)
        deadline = ossl_time_min(deadline,
                                 txp->args.cc_method->get_wakeup_deadline(txp->args.cc_data));

    return deadline;
}
