net: introduce QUIC infrastructure and core subcomponents
Subsystems (6)
v3 cover net: introduce QUIC infrastructure and core subcomponents
Introduction
============
The QUIC protocol, defined in RFC 9000, is a secure, multiplexed transport built on top of UDP. It enables low-latency connection establishment, stream-based communication with flow control, and supports connection migration across network paths, while ensuring confidentiality, integrity, and availability.
This implementation introduces QUIC support in Linux Kernel, offering several key advantages:
- In-Kernel QUIC Support for Subsystems: Enables kernel subsystems such as SMB and NFS to operate over QUIC with minimal changes. Once the handshake is complete via the net/handshake APIs, data exchange proceeds over standard in-kernel transport interfaces.
- Standard Socket API Semantics: Implements core socket operations (listen(), accept(), connect(), sendmsg(), recvmsg(), close(), getsockopt(), setsockopt(), getsockname(), and getpeername()), allowing user space to interact with QUIC sockets in a familiar, POSIX-compliant way.
- ALPN-Based Connection Dispatching: Supports in-kernel ALPN (Application-Layer Protocol Negotiation) routing, allowing demultiplexing of QUIC connections across different user-space processes based on the ALPN identifiers.
- Performance Enhancements: Handles all control messages in-kernel to reduce syscall overhead, incorporates zero-copy mechanisms such as sendfile() minimize data movement, and is also structured to support future crypto hardware offloads.
This implementation offers fundamental support for the following RFCs:
- RFC9000 - QUIC: A UDP-Based Multiplexed and Secure Transport
- RFC9001 - Using TLS to Secure QUIC
- RFC9002 - QUIC Loss Detection and Congestion Control
- RFC9221 - An Unreliable Datagram Extension to QUIC
- RFC9287 - Greasing the QUIC Bit
- RFC9368 - Compatible Version Negotiation for QUIC
- RFC9369 - QUIC Version 2
The socket APIs for QUIC follow the RFC draft [1]:
- The Sockets API Extensions for In-kernel QUIC Implementations
Implementation
==============
The central design is to implement QUIC within the kernel while delegating the handshake to userspace.
Only the processing and creation of raw TLS Handshake Messages are handled in userspace, facilitated by a TLS library like GnuTLS. These messages are exchanged between kernel and userspace via sendmsg() and recvmsg(), with cryptographic details conveyed through control messages (cmsg).
The entire QUIC protocol, aside from the TLS Handshake Messages processing and creation, is managed within the kernel. Rather than using a Upper Layer Protocol (ULP) layer, this implementation establishes a socket of type IPPROTO_QUIC (similar to IPPROTO_MPTCP), operating over UDP tunnels.
For kernel consumers, they can initiate a handshake request from the kernel to userspace using the existing net/handshake netlink. The userspace component, such as tlshd service [2], then manages the processing of the QUIC handshake request.
- Handshake Architecture:
┌──────┐ ┌──────┐
│ APP1 │ │ APP2 │ ...
└──────┘ └──────┘
┌──────────────────────────────────────────┐
│ {quic_client/server_handshake()} │<─────────────┐
└──────────────────────────────────────────┘ ┌─────────────┐
{send/recvmsg()} {set/getsockopt()} │ tlshd │
[CMSG handshake_info] [SOCKOPT_CRYPTO_SECRET] └─────────────┘
[SOCKOPT_TRANSPORT_PARAM_EXT] │ ^
│ ^ │ ^ │ │
Userspace │ │ │ │ │ │
──────────────│─│──────────────────│─│──────────────────│───│───────
Kernel │ │ │ │ │ │
v │ v │ v │
┌──────────────────┬───────────────────────┐ ┌─────────────┐
│ protocol, timer, │ socket (IPPROTO_QUIC) │<──┐ │ handshake │
│ ├───────────────────────┤ │ │netlink APIs │
│ common, family, │ outqueue | inqueue │ │ └─────────────┘
│ ├───────────────────────┤ │ │ │
│ stream, connid, │ frame │ │ ┌─────┐ ┌─────┐
│ ├───────────────────────┤ │ │ │ │ │
│ path, pnspace, │ packet │ │───│ SMB │ │ NFS │...
│ ├───────────────────────┤ │ │ │ │ │
│ cong, crypto │ UDP tunnels │ │ └─────┘ └─────┘
└──────────────────┴───────────────────────┘ └──────┴───────┘- User Data Architecture:
┌──────┐ ┌──────┐
│ APP1 │ │ APP2 │ ...
└──────┘ └──────┘
{send/recvmsg()} {set/getsockopt()} {recvmsg()}
[CMSG stream_info] [SOCKOPT_KEY_UPDATE] [EVENT conn update]
[SOCKOPT_CONNECTION_MIGRATION] [EVENT stream update]
[SOCKOPT_STREAM_OPEN/RESET/STOP]
│ ^ │ ^ ^
Userspace │ │ │ │ │
──────────────│─│───────────────│─│─────────────────────│───────────
Kernel │ │ │ │ │
v │ v │ ┌──────────────────┘
┌──────────────────┬───────────────────────┐
│ protocol, timer, │ socket (IPPROTO_QUIC) │<──┐{kernel_send/recvmsg()}
│ ├───────────────────────┤ │{kernel_set/getsockopt()}
│ common, family, │ outqueue | inqueue │ │{kernel_recvmsg()}
│ ├───────────────────────┤ │
│ stream, connid, │ frame │ │ ┌─────┐ ┌─────┐
│ ├───────────────────────┤ │ │ │ │ │
│ path, pnspace, │ packet │ │───│ SMB │ │ NFS │...
│ ├───────────────────────┤ │ │ │ │ │
│ cong, crypto │ UDP tunnels │ │ └─────┘ └─────┘
└──────────────────┴───────────────────────┘ └──────┴───────┘Interface
=========
This implementation supports a mapping of QUIC into sockets APIs. Similar to TCP and SCTP, a typical Server and Client use the following system call sequence to communicate:
Client Server
────────────────────────────────────────────────────────────────────── sockfd = socket(IPPROTO_QUIC) listenfd = socket(IPPROTO_QUIC) bind(sockfd) bind(listenfd)
listen(listenfd)
connect(sockfd)
quic_client_handshake(sockfd)
sockfd = accept(listenfd) quic_server_handshake(sockfd, cert)
sendmsg(sockfd) recvmsg(sockfd)
close(sockfd) close(sockfd)
close(listenfd)
Please note that quic_client_handshake() and quic_server_handshake() functions are currently sourced from libquic [3]. These functions are responsible for receiving and processing the raw TLS handshake messages until the completion of the handshake process.
For utilization by kernel consumers, it is essential to have tlshd service [2] installed and running in userspace. This service receives and manages kernel handshake requests for kernel sockets. In the kernel, the APIs closely resemble those used in userspace:
Client Server
────────────────────────────────────────────────────────────────────────
__sock_create(IPPROTO_QUIC, &sock) __sock_create(IPPROTO_QUIC, &sock)
kernel_bind(sock) kernel_bind(sock)
kernel_listen(sock)
kernel_connect(sock)
tls_client_hello_x509(args:{sock})
kernel_accept(sock, &newsock)
tls_server_hello_x509(args:{newsock}) kernel_sendmsg(sock) kernel_recvmsg(newsock)
sock_release(sock) sock_release(newsock)
sock_release(sock)
Please be aware that tls_client_hello_x509() and tls_server_hello_x509() are APIs from net/handshake/. They are used to dispatch the handshake request to the userspace tlshd service and subsequently block until the handshake process is completed.
Use Cases
=========
- Samba
Stefan Metzmacher has integrated Linux QUIC into Samba for both client and server roles [4].
- tlshd
The tlshd daemon [2] facilitates Linux QUIC handshake requests from kernel sockets. This is essential for enabling protocols like SMB and NFS over QUIC.
- curl
Linux QUIC is being integrated into curl [5] for HTTP/3. Example usage:
# curl --http3-only https://nghttp2.org:4433/ # curl --http3-only https://www.google.com/ # curl --http3-only https://facebook.com/ # curl --http3-only https://outlook.office.com/ # curl --http3-only https://cloudflare-quic.com/
- httpd-portable
Moritz Buhl has deployed an HTTP/3 server over Linux QUIC [6] that is accessible via Firefox and curl:
Test Coverage
=============
The Coverage (gcov) of Functional and Interop Tests:
- Functional Tests
The libquic self-tests (make check) pass on all major architectures:
x86_64, i386, s390x, aarch64, ppc64le.
- Interop tests
Interoperability was validated using the QUIC Interop Runner [7] against all major userland QUIC stacks. Results are available at:
- Fuzzing via Syzkaller
Syzkaller has been running kernel fuzzing with QUIC for weeks using tests/syzkaller/ in libquic [3]..
- Performance Testing
Performance was benchmarked using iperf [8] over a 100G NIC with using various MTUs and packet sizes:
- QUIC vs. kTLS:
UNIT size:1024 size:4096 size:16384 size:65536
Gbits/sec QUIC | kTLS QUIC | kTLS QUIC | kTLS QUIC | kTLS
────────────────────────────────────────────────────────────────────
mtu:1500 2.27 | 3.26 3.02 | 6.97 3.36 | 9.74 3.48 | 10.8
────────────────────────────────────────────────────────────────────
mtu:9000 3.66 | 3.72 5.87 | 8.92 7.03 | 11.2 8.04 | 11.4 - QUIC(disable_1rtt_encryption) vs. TCP:
UNIT size:1024 size:4096 size:16384 size:65536
Gbits/sec QUIC | TCP QUIC | TCP QUIC | TCP QUIC | TCP
────────────────────────────────────────────────────────────────────
mtu:1500 3.09 | 4.59 4.46 | 14.2 5.07 | 21.3 5.18 | 23.9
────────────────────────────────────────────────────────────────────
mtu:9000 4.60 | 4.65 8.41 | 14.0 11.3 | 28.9 13.5 | 39.2The performance gap between QUIC and kTLS may be attributed to:
- The absence of Generic Segmentation Offload (GSO) for QUIC.
- An additional data copy on the transmission (TX) path.
- Extra encryption required for header protection in QUIC.
- A longer header length for the stream data in QUIC.
Patches
=======
Note: This implementation is organized into five parts and submitted across two patchsets for review. This patchset includes Parts 1–2, while Parts 3–5 will be submitted in a subsequent patchset. For complete series, see [9].
1. Infrastructure (2):
net: define IPPROTO_QUIC and SOL_QUIC constants
net: build socket infrastructure for QUIC protocol
2. Subcomponents (13):
quic: provide common utilities and data structures
quic: provide family ops for address and protocol
quic: provide quic.h header files for kernel and userspace
quic: add stream management
quic: add connection id management
quic: add path management
quic: add congestion control
quic: add packet number space
quic: add crypto key derivation and installation
quic: add crypto packet encryption and decryption
quic: add timer management
quic: add frame encoder and decoder base
quic: add packet builder and parser base
3. Data Processing (7):
quic: implement outqueue transmission and flow control
quic: implement outqueue sack and retransmission
quic: implement inqueue receiving and flow control
quic: implement frame creation functions
quic: implement frame processing functions
quic: implement packet creation functions
quic: implement packet processing functions
4. Socket APIs (6):
quic: support bind/listen/connect/accept/close()
quic: support sendmsg() and recvmsg()
quic: support socket options related to interaction after handshake
quic: support socket options related to settings prior to handshake
quic: support socket options related to setup during handshake
quic: support socket ioctls and socket dump via procfs
5. Example and Documentation (2):
quic: create sample test using handshake APIs for kernel consumers
Documentation: describe QUIC protocol interface in quic.rst
Notice: The QUIC module is currently labeled as "EXPERIMENTAL".
All contributors are recognized in the respective patches with the tag of 'Signed-off-by:'. Special thanks to Moritz Buhl and Stefan Metzmacher whose practical use cases and insightful feedback, which have been instrumental in shaping the design and advancing the development.
References
==========
[1] https://datatracker.ietf.org/doc/html/draft-lxin-quic-socket-apis
[2] https://github.com/oracle/ktls-utils
[3] https://github.com/lxin/quic
[4] https://gitlab.com/samba-team/samba/-/merge_requests/4019
[5] https://github.com/moritzbuhl/curl/tree/linux_curl
[6] https://github.com/moritzbuhl/httpd-portable
[7] https://github.com/quic-interop/quic-interop-runner
[8] https://github.com/lxin/iperf
[9] https://github.com/lxin/net-next/commits/quic/
Changes in v2, v3: See individual patch changelogs for details.
Xin Long (15):
net: define IPPROTO_QUIC and SOL_QUIC constants
net: build socket infrastructure for QUIC protocol
quic: provide common utilities and data structures
quic: provide family ops for address and protocol
quic: provide quic.h header files for kernel and userspace
quic: add stream management
quic: add connection id management
quic: add path management
quic: add congestion control
quic: add packet number space
quic: add crypto key derivation and installation
quic: add crypto packet encryption and decryption
quic: add timer management
quic: add frame encoder and decoder base
quic: add packet builder and parser base
include/linux/quic.h | 19 + include/linux/socket.h | 1 + include/uapi/linux/in.h | 2 + include/uapi/linux/quic.h | 236 ++++++++ net/Kconfig | 1 + net/Makefile | 1 + net/quic/Kconfig | 36 ++ net/quic/Makefile | 9 + net/quic/common.c | 594 ++++++++++++++++++ net/quic/common.h | 221 +++++++ net/quic/cong.c | 700 +++++++++++++++++++++ net/quic/cong.h | 120 ++++ net/quic/connid.c | 222 +++++++ net/quic/connid.h | 162 +++++ net/quic/crypto.c | 1203 +++++++++++++++++++++++++++++++++++++ net/quic/crypto.h | 83 +++ net/quic/family.c | 589 ++++++++++++++++++ net/quic/family.h | 41 ++ net/quic/frame.c | 558 +++++++++++++++++ net/quic/frame.h | 195 ++++++ net/quic/packet.c | 956 +++++++++++++++++++++++++++++ net/quic/packet.h | 130 ++++ net/quic/path.c | 502 ++++++++++++++++ net/quic/path.h | 167 +++++ net/quic/pnspace.c | 224 +++++++ net/quic/pnspace.h | 150 +++++ net/quic/protocol.c | 411 +++++++++++++ net/quic/protocol.h | 62 ++ net/quic/socket.c | 425 +++++++++++++ net/quic/socket.h | 214 +++++++ net/quic/stream.c | 509 ++++++++++++++++ net/quic/stream.h | 136 +++++ net/quic/timer.c | 196 ++++++ net/quic/timer.h | 47 ++ 34 files changed, 9122 insertions(+) create mode 100644 include/linux/quic.h create mode 100644 include/uapi/linux/quic.h create mode 100644 net/quic/Kconfig create mode 100644 net/quic/Makefile create mode 100644 net/quic/common.c create mode 100644 net/quic/common.h create mode 100644 net/quic/cong.c create mode 100644 net/quic/cong.h create mode 100644 net/quic/connid.c create mode 100644 net/quic/connid.h create mode 100644 net/quic/crypto.c create mode 100644 net/quic/crypto.h create mode 100644 net/quic/family.c create mode 100644 net/quic/family.h create mode 100644 net/quic/frame.c create mode 100644 net/quic/frame.h create mode 100644 net/quic/packet.c create mode 100644 net/quic/packet.h create mode 100644 net/quic/path.c create mode 100644 net/quic/path.h create mode 100644 net/quic/pnspace.c create mode 100644 net/quic/pnspace.h create mode 100644 net/quic/protocol.c create mode 100644 net/quic/protocol.h create mode 100644 net/quic/socket.c create mode 100644 net/quic/socket.h create mode 100644 net/quic/stream.c create mode 100644 net/quic/stream.h create mode 100644 net/quic/timer.c create mode 100644 net/quic/timer.h
Signature · 1 line
2.47.1
PATCH v3 1/15 net: define IPPROTO_QUIC and SOL_QUIC constants
This patch adds IPPROTO_QUIC and SOL_QUIC constants to the networking subsystem. These definitions are essential for applications to set socket options and protocol identifiers related to the QUIC protocol.
QUIC does not possess a protocol number allocated from IANA, and like IPPROTO_MPTCP, IPPROTO_QUIC is merely a value used when opening a QUIC socket with:
socket(AF_INET, SOCK_STREAM, IPPROTO_QUIC);
Note we did not opt for UDP ULP for QUIC implementation due to several considerations:
- QUIC's connection Migration requires at least 2 UDP sockets for one QUIC connection at the same time, not to mention the multipath feature in one of its draft RFCs.
- In-Kernel QUIC, as a Transport Protocol, wants to provide users with the TCP or SCTP like Socket APIs, like connect()/listen()/accept()... Note that a single UDP socket might even be used for multiple QUIC connections.
The use of IPPROTO_QUIC type sockets over UDP tunnel will effectively address these challenges and provides a more flexible and scalable solution.
--- include/linux/socket.h | 1 + include/uapi/linux/in.h | 2 ++ 2 files changed, 3 insertions(+)
include/linux/socket.h +1 -0
@@ -386,6 +386,7 @@ struct ucred {#define SOL_MCTP 285#define SOL_SMC 286#define SOL_VSOCK 287 +#define SOL_QUIC 288/* IPX options */ #define IPX_TYPE 1
include/uapi/linux/in.h +2 -0
@@ -85,6 +85,8 @@ enum {#define IPPROTO_RAW IPPROTO_RAW IPPROTO_SMC = 256, /* Shared Memory Communications */#define IPPROTO_SMC IPPROTO_SMC + IPPROTO_QUIC = 261, /* A UDP-Based Multiplexed and Secure Transport */ +#define IPPROTO_QUIC IPPROTO_QUIC IPPROTO_MPTCP = 262, /* Multipath TCP connection */#define IPPROTO_MPTCP IPPROTO_MPTCPIPPROTO_MAX
Signature · 1 line
2.47.1
PATCH v3 2/15 net: build socket infrastructure for QUIC protocol
In reply to Xin LongThis patch lays the groundwork for QUIC socket support in the kernel. It defines the core structures and protocol hooks needed to create QUIC sockets, without implementing any protocol behavior at this stage.
Basic integration is included to allow building the module via CONFIG_IP_QUIC=m.
This provides the scaffolding necessary for adding actual QUIC socket behavior in follow-up patches.
---
v3:
- Kconfig: add 'default n' for IP_QUIC (reported by Paolo).
- quic_disconnect(): return -EOPNOTSUPP (suggested by Paolo).
- quic_init/destroy_sock(): drop local_bh_disable/enable() calls (noted by Paolo).
- sysctl: add alpn_demux option to en/disable ALPN-based demux.
- SNMP: remove SNMP_MIB_SENTINEL, switch to snmp_get_cpu_field_batch_cnt() to align with latest net-next changes.
--- net/Kconfig | 1 + net/Makefile | 1 + net/quic/Kconfig | 36 +++++ net/quic/Makefile | 8 + net/quic/protocol.c | 379 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/protocol.h | 56 +++++++ net/quic/socket.c | 207 ++++++++++++++++++++++++ net/quic/socket.h | 79 +++++++++ 8 files changed, 767 insertions(+) create mode 100644 net/quic/Kconfig create mode 100644 net/quic/Makefile create mode 100644 net/quic/protocol.c create mode 100644 net/quic/protocol.h create mode 100644 net/quic/socket.c create mode 100644 net/quic/socket.h
net/Kconfig +1 -0
@@ -249,6 +249,7 @@ source "net/bridge/netfilter/Kconfig" endif # if NETFILTER +source "net/quic/Kconfig" source "net/sctp/Kconfig" source "net/rds/Kconfig" source "net/tipc/Kconfig"
net/Makefile +1 -0
@@ -42,6 +42,7 @@ obj-$(CONFIG_PHONET) += phonet/ ifneq ($(CONFIG_VLAN_8021Q),) obj-y += 8021q/ endif +obj-$(CONFIG_IP_QUIC) += quic/ obj-$(CONFIG_IP_SCTP) += sctp/ obj-$(CONFIG_RDS) += rds/ obj-$(CONFIG_WIRELESS) += wireless/
net/quic/Kconfig new file +36 -0
@@ -0,0 +1,36 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# QUIC configuration +# + +menuconfig IP_QUIC + tristate "QUIC: A UDP-Based Multiplexed and Secure Transport (Experimental)" + depends on INET + depends on IPV6 + select CRYPTO + select CRYPTO_HMAC + select CRYPTO_HKDF + select CRYPTO_AES + select CRYPTO_GCM + select CRYPTO_CCM + select CRYPTO_CHACHA20POLY1305 + select NET_UDP_TUNNEL + default n + help + QUIC: A UDP-Based Multiplexed and Secure Transport + + From rfc9000 <https://www.rfc-editor.org/rfc/rfc9000.html>. + + QUIC provides applications with flow-controlled streams for structured + communication, low-latency connection establishment, and network path + migration. QUIC includes security measures that ensure + confidentiality, integrity, and availability in a range of deployment + circumstances. Accompanying documents describe the integration of + TLS for key negotiation, loss detection, and an exemplary congestion + control algorithm. + + To compile this protocol support as a module, choose M here: the + module will be called quic. Debug messages are handled by the + kernel's dynamic debugging framework. + + If in doubt, say N.
net/quic/Makefile new file +8 -0
@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Makefile for QUIC support code. +# + +obj-$(CONFIG_IP_QUIC) += quic.o + +quic-y := protocol.o socket.o
net/quic/protocol.c new file +379 -0
379 lines not on this page · raw message
net/quic/protocol.h new file +56 -0
56 lines not on this page · raw message
net/quic/socket.c new file +207 -0
207 lines not on this page · raw message
net/quic/socket.h new file +79 -0
79 lines not on this page · raw message
Signature · 1 line
2.47.1
PATCH v3 3/15 quic: provide common utilities and data structures
In reply to Xin LongThis patch provides foundational data structures and utilities used throughout the QUIC stack.
It introduces packet header types, connection ID support, and address handling. Hash tables are added to manage socket lookup and connection ID mapping.
A flexible binary data type is provided, along with helpers for parsing, matching, and memory management. Helpers for encoding and decoding transport parameters and frames are also included.
---
v3:
- Rework hashtables: split into two types and size them based on totalram_pages(), similar to SCTP (reported by Paolo).
- struct quic_shash_table: use rwlock instead of spinlock.
- quic_data_from/to_string(): add safety and common-case checks (noted by Paolo).
--- net/quic/Makefile | 2 +- net/quic/common.c | 594 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/common.h | 221 ++++++++++++++++ net/quic/protocol.c | 6 + net/quic/socket.c | 4 + net/quic/socket.h | 21 ++ 6 files changed, 847 insertions(+), 1 deletion(-) create mode 100644 net/quic/common.c create mode 100644 net/quic/common.h
net/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := protocol.o socket.o +quic-y := common.o protocol.o socket.o
net/quic/common.c new file +594 -0
594 lines not on this page · raw message
net/quic/common.h new file +221 -0
221 lines not on this page · raw message
net/quic/protocol.c +6 -0
@@ -336,6 +336,9 @@ static __init int quic_init(void)if (err) goto err_percpu_counter; +if (quic_hash_tables_init ()) + goto err_hash; + err =register_pernet_subsys (&quic_net_ops);if (err) goto err_def_ops;
@@ -353,6 +356,8 @@ static __init int quic_init(void) err_protosw:unregister_pernet_subsys (&quic_net_ops); err_def_ops: +quic_hash_tables_destroy (); +err_hash:percpu_counter_destroy (&quic_sockets_allocated); err_percpu_counter:return err;
@@ -365,6 +370,7 @@ static __exit void quic_exit(void)#endif quic_protosw_exit ();unregister_pernet_subsys (&quic_net_ops); +quic_hash_tables_destroy ();percpu_counter_destroy (&quic_sockets_allocated);pr_info ("quic: exit\n" ); }
net/quic/socket.c +4 -0
@@ -52,6 +52,10 @@ static int quic_init_sock(struct sock *sk)static void quic_destroy_sock (struct sock *sk) { +quic_data_free (quic_ticket (sk)); +quic_data_free (quic_token (sk)); +quic_data_free (quic_alpn (sk)); +sk_sockets_allocated_dec (sk);sock_prot_inuse_add (sock_net (sk), sk->sk_prot,-1 ); }
net/quic/socket.h +21 -0
@@ -10,6 +10,8 @@#include <net/udp_tunnel.h> +#include "common.h" +#include "protocol.h" extern struct proto quic_prot;
@@ -25,6 +27,10 @@ enum quic_state {struct quic_sock {struct inet_sock inet;struct list_head reqs; + +struct quic_data ticket; +struct quic_data token; +struct quic_data alpn; };struct quic6_sock {
@@ -42,6 +48,21 @@ static inline struct list_head *quic_reqs(const struct sock *sk)return &quic_sk (sk)->reqs; } +static inline struct quic_data *quic_token (const struct sock *sk) +{ +return &quic_sk (sk)->token; +} + +static inline struct quic_data *quic_ticket (const struct sock *sk) +{ +return &quic_sk (sk)->ticket; +} + +static inline struct quic_data *quic_alpn (const struct sock *sk) +{ +return &quic_sk (sk)->alpn; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
Signature · 1 line
2.47.1
PATCH v3 4/15 quic: provide family ops for address and protocol
In reply to Xin LongIntroduce QUIC address and protocol family operations to handle IPv4/IPv6 specifics consistently, similar to SCTP. The new quic_family.{c,h} provide helpers for routing, address parsing, skb transmit handling, ECN, preferred address encoding, address comparison, and MTU reporting.
This consolidates protocol-family logic and enables cleaner dual-stack support in the QUIC socket implementation.
---
v2:
- Add more checks for addrs in .get_user_addr() and .get_pref_addr().
- Consider sk_bound_dev_if in .udp_conf_init() and .flow_route() to support vrf.
v3:
- Remove quic_addr_family/proto_ops abstraction; use if statements to reduce indirect call overhead (suggested by Paolo).
- quic_v6_set_sk_addr(): add quic_v6_copy_sk_addr() helper to avoid duplicate code (noted by Paolo).
- quic_v4_flow_route(): use flowi4_dscp per latest net-next changes.
--- net/quic/Makefile | 2 +- net/quic/family.c | 589 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/family.h | 41 +++ net/quic/protocol.c | 2 +- net/quic/socket.c | 4 +- net/quic/socket.h | 1 + 6 files changed, 635 insertions(+), 4 deletions(-) create mode 100644 net/quic/family.c create mode 100644 net/quic/family.h
net/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o protocol.o socket.o +quic-y := common.o family.o protocol.o socket.o
net/quic/family.c new file +589 -0
589 lines not on this page · raw message
net/quic/family.h new file +41 -0
41 lines not on this page · raw message
net/quic/protocol.c +1 -1
@@ -47,7 +47,7 @@ static int quic_inet_listen(struct socket *sock, int backlog)static int quic_inet_getname (struct socket *sock,struct sockaddr *uaddr,int peer) { -return -EOPNOTSUPP ; +return quic_get_sk_addr (sock, uaddr, peer); }static __poll_t quic_inet_poll (struct file *file,struct socket *sock,poll_table *wait)
net/quic/socket.c +2 -2
@@ -116,7 +116,7 @@ static int quic_setsockopt(struct sock *sk, int level, int optname, sockptr_t optval, unsigned int optlen) {if (level !=SOL_QUIC ) -return -EOPNOTSUPP ; +return quic_common_setsockopt (sk, level, optname, optval, optlen);return quic_do_setsockopt (sk, optname, optval, optlen); }
@@ -130,7 +130,7 @@ static int quic_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) {if (level !=SOL_QUIC ) -return -EOPNOTSUPP ; +return quic_common_getsockopt (sk, level, optname, optval, optlen);return quic_do_getsockopt (sk, optname,USER_SOCKPTR (optval),USER_SOCKPTR (optlen)); }
net/quic/socket.h +1 -0
@@ -11,6 +11,7 @@#include <net/udp_tunnel.h> #include "common.h" +#include "family.h" #include "protocol.h"
Signature · 1 line
2.47.1
PATCH v3 5/15 quic: provide quic.h header files for kernel and userspace
In reply to Xin LongThis commit adds quic.h to include/uapi/linux, providing the necessary definitions for the QUIC socket API. Exporting this header allows both user space applications and kernel subsystems to access QUIC-related control messages, socket options, and event/notification interfaces.
Since kernel_get/setsockopt() is no longer available to kernel consumers, a corresponding internal header, include/linux/quic.h, is added. This provides kernel subsystems with the necessary declarations to handle QUIC socket options directly.
Detailed descriptions of these structures are available in [1], and will be also provided when adding corresponding socket interfaces in the later patches.
[1] https://datatracker.ietf.org/doc/html/draft-lxin-quic-socket-apis
---
v2:
- Fix a kernel API description warning, found by Jakub.
- Replace uintN_t with __uN, capitalize _UAPI_LINUX_QUIC_H, and assign explicit values for QUIC_TRANSPORT_ERROR_ enum in UAPI quic.h, suggested by David Howells.
--- include/linux/quic.h | 19 +++ include/uapi/linux/quic.h | 236 ++++++++++++++++++++++++++++++++++++++ net/quic/socket.c | 38 ++++++ net/quic/socket.h | 7 ++ 4 files changed, 300 insertions(+) create mode 100644 include/linux/quic.h create mode 100644 include/uapi/linux/quic.h
include/linux/quic.h new file +19 -0
@@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#ifndef _LINUX_QUIC_H +#define _LINUX_QUIC_H + +#include <uapi/linux/quic.h> + +int quic_kernel_setsockopt (struct sock *sk,int optname,void *optval,unsigned int optlen); +int quic_kernel_getsockopt (struct sock *sk,int optname,void *optval,unsigned int *optlen); + +#endif
include/uapi/linux/quic.h new file +236 -0
236 lines not on this page · raw message
net/quic/socket.c +38 -0
@@ -121,6 +121,25 @@ static int quic_setsockopt(struct sock *sk, int level, int optname,return quic_do_setsockopt (sk, optname, optval, optlen); } +/** +* quic_kernel_setsockopt - set a QUIC socket option from within the kernel +* @sk: socket to configure +* @optname: option name (QUIC-level) +* @optval: pointer to the option value +* @optlen: size of the option value +* +* Sets a QUIC socket option on a kernel socket without involving user space. +* +* Return: +* - On success, 0 is returned. +* - On error, a negative error value is returned. +*/ +int quic_kernel_setsockopt (struct sock *sk,int optname,void *optval,unsigned int optlen) +{ +return quic_do_setsockopt (sk, optname,KERNEL_SOCKPTR (optval), optlen); +} +EXPORT_SYMBOL_GPL (quic_kernel_setsockopt); +static int quic_do_getsockopt (struct sock *sk,int optname,sockptr_t optval,sockptr_t optlen) {return -EOPNOTSUPP ;
@@ -135,6 +154,25 @@ static int quic_getsockopt(struct sock *sk, int level, int optname,return quic_do_getsockopt (sk, optname,USER_SOCKPTR (optval),USER_SOCKPTR (optlen)); } +/** +* quic_kernel_getsockopt - get a QUIC socket option from within the kernel +* @sk: socket to query +* @optname: option name (QUIC-level) +* @optval: pointer to the buffer to receive the option value +* @optlen: pointer to the size of the buffer; updated to actual length on return +* +* Gets a QUIC socket option from a kernel socket, bypassing user space. +* +* Return: +* - On success, 0 is returned. +* - On error, a negative error value is returned. +*/ +int quic_kernel_getsockopt (struct sock *sk,int optname,void *optval,unsigned int *optlen) +{ +return quic_do_getsockopt (sk, optname,KERNEL_SOCKPTR (optval),KERNEL_SOCKPTR (optlen)); +} +EXPORT_SYMBOL_GPL (quic_kernel_getsockopt); +static void quic_release_cb (struct sock *sk) { }
net/quic/socket.h +7 -0
@@ -9,6 +9,7 @@*/ #include <net/udp_tunnel.h> +#include <linux/quic.h> #include "common.h" #include "family.h"
@@ -29,6 +30,7 @@ struct quic_sock {struct inet_sock inet;struct list_head reqs; +struct quic_config config;struct quic_data ticket;struct quic_data token;struct quic_data alpn;
@@ -49,6 +51,11 @@ static inline struct list_head *quic_reqs(const struct sock *sk)return &quic_sk (sk)->reqs; } +static inline struct quic_config *quic_config (const struct sock *sk) +{ +return &quic_sk (sk)->config; +} +static inline struct quic_data *quic_token (const struct sock *sk) {return &quic_sk (sk)->token;
Signature · 1 line
2.47.1
PATCH v3 6/15 quic: add stream management
In reply to Xin LongThis patch introduces 'struct quic_stream_table' for managing QUIC streams, each represented by 'struct quic_stream'.
It implements mechanisms for acquiring and releasing streams on both the send and receive paths, ensuring efficient lifecycle management during transmission and reception.
- quic_stream_send_get(): Acquire a send-side stream by ID and flags during TX path.
- quic_stream_recv_get(): Acquire a receive-side stream by ID during RX path.
- quic_stream_send_put(): Release a send-side stream when sending is done.
- quic_stream_recv_put(): Release a receive-side stream when receiving is done.
It includes logic to detect when stream ID limits are reached and when control frames should be sent to update or request limits from the peer.
- quic_stream_id_send_exceeds(): Determines whether a STREAMS_BLOCKED_UNI/BIDI frame should be sent to the peer.
- quic_stream_max_streams_update(): Determines whether a MAX_STREAMS_UNI/BIDI frame should be sent to the peer.
Note stream hash table is per socket, the operations on it are always protected by the sock lock.
---
v3:
- Merge send/recv stream helpers into unified functions to reduce code:
* quic_stream_id_send/recv() → quic_stream_id_valid()
* quic_stream_id_send/recv_closed() → quic_stream_id_closed()
* quic_stream_id_send/recv_exceeds() → quic_stream_id_exceeds() (pointed out by Paolo).
- Clarify in changelog that stream hash table is always protected by sock lock (suggested by Paolo).
- quic_stream_init/free(): adjust for new hashtable type; call quic_stream_delete() in quic_stream_free() to avoid open-coded logic.
- Receiving streams: delete stream only when fully read or reset, instead of when no data was received. Prevents freeing a stream while a FIN with no data is still queued.
- Note: no memory accounting is done for stream objects yet, as their cost is minor compared to stream data. Will add if needed in the future.
--- net/quic/Makefile | 2 +- net/quic/socket.c | 5 + net/quic/socket.h | 8 + net/quic/stream.c | 509 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/stream.h | 136 +++++++++++++ 5 files changed, 659 insertions(+), 1 deletion(-) create mode 100644 net/quic/stream.c create mode 100644 net/quic/stream.h
net/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o +quic-y := common.o family.o protocol.o socket.o stream.o
net/quic/socket.c +5 -0
@@ -41,6 +41,9 @@ static int quic_init_sock(struct sock *sk) sk->sk_write_space = quic_write_space;sock_set_flag (sk,SOCK_USE_WRITE_QUEUE ); +if (quic_stream_init (quic_streams (sk))) +return -ENOMEM ; +WRITE_ONCE (sk->sk_sndbuf,READ_ONCE (sysctl_quic_wmem[1 ]));WRITE_ONCE (sk->sk_rcvbuf,READ_ONCE (sysctl_quic_rmem[1 ]));
@@ -52,6 +55,8 @@ static int quic_init_sock(struct sock *sk)static void quic_destroy_sock (struct sock *sk) { +quic_stream_free (quic_streams (sk)); +quic_data_free (quic_ticket (sk));quic_data_free (quic_token (sk));quic_data_free (quic_alpn (sk));
net/quic/socket.h +8 -0
@@ -13,6 +13,7 @@#include "common.h" #include "family.h" +#include "stream.h" #include "protocol.h"
@@ -34,6 +35,8 @@ struct quic_sock {struct quic_data ticket;struct quic_data token;struct quic_data alpn; + +struct quic_stream_table streams; };struct quic6_sock {
@@ -71,6 +74,11 @@ static inline struct quic_data *quic_alpn(const struct sock *sk)return &quic_sk (sk)->alpn; } +static inline struct quic_stream_table *quic_streams (const struct sock *sk) +{ +return &quic_sk (sk)->streams; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
net/quic/stream.c new file +509 -0
509 lines not on this page · raw message
net/quic/stream.h new file +136 -0
136 lines not on this page · raw message
Signature · 1 line
2.47.1
PATCH v3 7/15 quic: add connection id management
In reply to Xin LongThis patch introduces 'struct quic_conn_id_set' for managing Connection IDs (CIDs), which are represented by 'struct quic_source_conn_id' and 'struct quic_dest_conn_id'.
It provides helpers to add and remove CIDs from the set, and handles insertion of source CIDs into the global connection ID hash table when necessary.
- quic_conn_id_add(): Add a new Connection ID to the set, and inserts it to conn_id hash table if it is a source conn_id.
- quic_conn_id_remove(): Remove connection IDs the set with sequence numbers less than or equal to a number.
It also adds utilities to look up CIDs by value or sequence number, search the global hash table for incoming packets, and check for stateless reset tokens among destination CIDs. These functions are essential for RX path connection lookup and stateless reset processing.
- quic_conn_id_find(): Find a Connection ID in the set by seq number.
- quic_conn_id_lookup(): Lookup a Connection ID from global hash table using the ID value, typically used for socket lookup on the RX path.
- quic_conn_id_token_exists(): Check if a stateless reset token exists in any dest Connection ID (used during stateless reset processing).
Note source/dest conn_id set is per socket, the operations on it are always pretected by the sock lock.
---
v3:
- Clarify in changelog that conn_id set is always protected by sock lock (suggested by Paolo).
- Adjust global source conn_id hashtable operations for the new hashtable type.
--- net/quic/Makefile | 2 +- net/quic/connid.c | 222 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/connid.h | 162 +++++++++++++++++++++++++++++++++ net/quic/socket.c | 6 ++ net/quic/socket.h | 13 +++ 5 files changed, 404 insertions(+), 1 deletion(-) create mode 100644 net/quic/connid.c create mode 100644 net/quic/connid.h
net/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o stream.o +quic-y := common.o family.o protocol.o socket.o stream.o connid.o
net/quic/connid.c new file +222 -0
222 lines not on this page · raw message
net/quic/connid.h new file +162 -0
162 lines not on this page · raw message
net/quic/socket.c +6 -0
@@ -41,6 +41,9 @@ static int quic_init_sock(struct sock *sk) sk->sk_write_space = quic_write_space;sock_set_flag (sk,SOCK_USE_WRITE_QUEUE ); +quic_conn_id_set_init (quic_source (sk),1 ); +quic_conn_id_set_init (quic_dest (sk),0 ); +if (quic_stream_init (quic_streams (sk)))return -ENOMEM ;
@@ -55,6 +58,9 @@ static int quic_init_sock(struct sock *sk)static void quic_destroy_sock (struct sock *sk) { +quic_conn_id_set_free (quic_source (sk)); +quic_conn_id_set_free (quic_dest (sk)); +quic_stream_free (quic_streams (sk));quic_data_free (quic_ticket (sk));
net/quic/socket.h +13 -0
@@ -14,6 +14,7 @@#include "common.h" #include "family.h" #include "stream.h" +#include "connid.h" #include "protocol.h"
@@ -37,6 +38,8 @@ struct quic_sock {struct quic_data alpn;struct quic_stream_table streams; +struct quic_conn_id_set source; +struct quic_conn_id_set dest; };struct quic6_sock {
@@ -79,6 +82,16 @@ static inline struct quic_stream_table *quic_streams(const struct sock *sk)return &quic_sk (sk)->streams; } +static inline struct quic_conn_id_set *quic_source (const struct sock *sk) +{ +return &quic_sk (sk)->source; +} + +static inline struct quic_conn_id_set *quic_dest (const struct sock *sk) +{ +return &quic_sk (sk)->dest; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
Signature · 1 line
2.47.1
PATCH v3 8/15 quic: add path management
In reply to Xin LongThis patch introduces 'quic_path_group' for managing paths, represented by 'struct quic_path'. A connection may use two paths simultaneously for connection migration.
Each path is associated with a UDP tunnel socket (sk), and a single UDP tunnel socket can be related to multiple paths from different sockets. These UDP tunnel sockets are wrapped in 'quic_udp_sock' structures and stored in a hash table.
It includes mechanisms to bind and unbind paths, detect alternative paths for migration, and swap paths to support seamless transition between networks.
- quic_path_bind(): Bind a path to a port and associate it with a UDP sk.
- quic_path_free(): Unbind a path from a port and disassociate it from a UDP sk.
- quic_path_swap(): Swap two paths to facilitate connection migration.
- quic_path_detect_alt(): Determine if a packet is using an alternative path, used for connection migration.
It also integrates basic support for Packetization Layer Path MTU
Discovery (PLPMTUD), using PING frames and ICMP feedback to adjust path MTU and handle probe confirmation or resets during routing changes.
- quic_path_pl_recv(): state transition and pmtu update after the probe packet is acked.
- quic_path_pl_toobig(): state transition and pmtu update after receiving a toobig or needfrag icmp packet.
- quic_path_pl_send(): state transition and pmtu update after sending a probe packet.
- quic_path_pl_reset(): restart the probing when path routing changes.
- quic_path_pl_confirm(): check if probe packet gets acked.
---
v3:
- Fix annotation in quic_udp_sock_lookup() (noted by Paolo).
- Use inet_sk_get_local_port_range() instead of inet_get_local_port_range() (suggested by Paolo).
- Adjust global UDP tunnel socket hashtable operations for the new hashtable type.
- Delete quic_workqueue; use system_wq for UDP tunnel socket destroy.
--- net/quic/Makefile | 2 +- net/quic/path.c | 502 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/path.h | 167 +++++++++++++++ net/quic/socket.c | 3 + net/quic/socket.h | 21 +- 5 files changed, 692 insertions(+), 3 deletions(-) create mode 100644 net/quic/path.c create mode 100644 net/quic/path.h
net/quic/Makefile +1 -1
@@ -5,4 +5,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o stream.o connid.o +quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o
net/quic/path.c new file +502 -0
502 lines not on this page · raw message
net/quic/path.h new file +167 -0
167 lines not on this page · raw message
net/quic/socket.c +3 -0
@@ -58,6 +58,9 @@ static int quic_init_sock(struct sock *sk)static void quic_destroy_sock (struct sock *sk) { +quic_path_free (sk,quic_paths (sk),0 ); +quic_path_free (sk,quic_paths (sk),1 ); +quic_conn_id_set_free (quic_source (sk));quic_conn_id_set_free (quic_dest (sk));
net/quic/socket.h +19 -2
@@ -15,6 +15,7 @@#include "family.h" #include "stream.h" #include "connid.h" +#include "path.h" #include "protocol.h"
@@ -40,6 +41,7 @@ struct quic_sock {struct quic_stream_table streams;struct quic_conn_id_set source;struct quic_conn_id_set dest; +struct quic_path_group paths; };struct quic6_sock {
@@ -92,6 +94,16 @@ static inline struct quic_conn_id_set *quic_dest(const struct sock *sk)return &quic_sk (sk)->dest; } +static inline struct quic_path_group *quic_paths (const struct sock *sk) +{ +return &quic_sk (sk)->paths; +} + +static inline bool quic_is_serv (const struct sock *sk) +{ +return quic_paths (sk)->serv; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
@@ -115,14 +127,19 @@ static inline bool quic_is_closed(struct sock *sk)static inline void quic_set_state (struct sock *sk,int state) {struct net *net =sock_net (sk); +int mib;if (sk->sk_state == state)return ; -if (state ==QUIC_SS_ESTABLISHED ) +if (state ==QUIC_SS_ESTABLISHED ) { + mib =quic_is_serv (sk) ?QUIC_MIB_CONN_PASSIVEESTABS + :QUIC_MIB_CONN_ACTIVEESTABS ; +QUIC_INC_STATS (net, mib);QUIC_INC_STATS (net,QUIC_MIB_CONN_CURRENTESTABS ); -else if (quic_is_established (sk)) + }else if (quic_is_established (sk)) {QUIC_DEC_STATS (net,QUIC_MIB_CONN_CURRENTESTABS ); + }inet_sk_set_state (sk, state); sk->sk_state_change (sk);
Signature · 1 line
2.47.1
PATCH v3 9/15 quic: add congestion control
In reply to Xin LongThis patch introduces 'quic_cong' for RTT measurement and congestion control. The 'quic_cong_ops' is added to define the congestion control algorithm.
It implements a congestion control state machine with slow start, congestion avoidance, and recovery phases, and introduces the New Reno and CUBIC algorithms.
The implementation updates RTT estimates when packets are acknowledged, reacts to loss and ECN signals, and adjusts the congestion window accordingly during packet transmission and acknowledgment processing.
- quic_cong_rtt_update(): Performs RTT measurement, invoked when a packet is acknowledged by the largest number in the ACK frame.
- quic_cong_on_packet_acked(): Invoked when a packet is acknowledged.
- quic_cong_on_packet_lost(): Invoked when a packet is marked as lost.
- quic_cong_on_process_ecn(): Invoked when an ACK_ECN frame is received.
- quic_cong_on_packet_sent(): Invoked when a packet is transmitted.
- quic_cong_on_ack_recv(): Invoked when an ACK frame is received.
--- net/quic/Makefile | 3 +- net/quic/cong.c | 700 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/cong.h | 120 ++++++++ net/quic/socket.c | 1 + net/quic/socket.h | 7 + 5 files changed, 830 insertions(+), 1 deletion(-) create mode 100644 net/quic/cong.c create mode 100644 net/quic/cong.h
net/quic/Makefile +2 -1
@@ -5,4 +5,5 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o +quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ + cong.o
net/quic/cong.c new file +700 -0
700 lines not on this page · raw message
net/quic/cong.h new file +120 -0
120 lines not on this page · raw message
net/quic/socket.c +1 -0
@@ -43,6 +43,7 @@ static int quic_init_sock(struct sock *sk)quic_conn_id_set_init (quic_source (sk),1 );quic_conn_id_set_init (quic_dest (sk),0 ); +quic_cong_init (quic_cong (sk));if (quic_stream_init (quic_streams (sk)))return -ENOMEM ;
net/quic/socket.h +7 -0
@@ -16,6 +16,7 @@#include "stream.h" #include "connid.h" #include "path.h" +#include "cong.h" #include "protocol.h"
@@ -42,6 +43,7 @@ struct quic_sock {struct quic_conn_id_set source;struct quic_conn_id_set dest;struct quic_path_group paths; +struct quic_cong cong; };struct quic6_sock {
@@ -104,6 +106,11 @@ static inline bool quic_is_serv(const struct sock *sk)return quic_paths (sk)->serv; } +static inline struct quic_cong *quic_cong (const struct sock *sk) +{ +return &quic_sk (sk)->cong; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
Signature · 1 line
2.47.1
PATCH v3 10/15 quic: add packet number space
In reply to Xin LongThis patch introduces 'quic_pnspace', which manages per packet number space members.
It maintains the next packet number to assign, tracks the total length of frames currently in flight, and records the time when the next packet may be considered lost. It also keeps track of the largest acknowledged packet number, the time it was acknowledged, and when the most recent ack eliciting packet was sent. These fields are useful for loss detection, RTT estimation, and congestion control.
To support ACK frame generation, quic_pnspace includes a packet number acknowledgment map (pn_ack_map) that tracks received packet numbers. Supporting functions are provided to validate and mark received packet numbers and compute the number of gap blocks needed during ACK frame construction.
- quic_pnspace_check(): Validates a received packet number.
- quic_pnspace_mark(): Marks a received packet number in the ACK map.
- quic_pnspace_num_gabs(): Returns the gap ACK blocks for constructing ACK frames.
Note QUIC uses separate packet number spaces for each encryption level (APP, INITIAL, HANDSHAKE, EARLY) except EARLY and all generations of APP keys use the same packet number space, as describe in rfc9002#section-4.1.
--- net/quic/Makefile | 2 +- net/quic/pnspace.c | 224 +++++++++++++++++++++++++++++++++++++++++++++ net/quic/pnspace.h | 150 ++++++++++++++++++++++++++++++ net/quic/socket.c | 12 +++ net/quic/socket.h | 7 ++ 5 files changed, 394 insertions(+), 1 deletion(-) create mode 100644 net/quic/pnspace.c create mode 100644 net/quic/pnspace.h
net/quic/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ - cong.o + cong.o pnspace.o
net/quic/pnspace.c new file +224 -0
224 lines not on this page · raw message
net/quic/pnspace.h new file +150 -0
150 lines not on this page · raw message
net/quic/socket.c +12 -0
@@ -37,6 +37,8 @@ static void quic_write_space(struct sock *sk)static int quic_init_sock (struct sock *sk) { +u8 i; + sk->sk_destruct = inet_sock_destruct; sk->sk_write_space = quic_write_space;sock_set_flag (sk,SOCK_USE_WRITE_QUEUE );
@@ -48,6 +50,11 @@ static int quic_init_sock(struct sock *sk)if (quic_stream_init (quic_streams (sk)))return -ENOMEM ; +for (i =0 ; i <QUIC_PNSPACE_MAX ; i++) { +if (quic_pnspace_init (quic_pnspace (sk, i))) +return -ENOMEM ; + } +WRITE_ONCE (sk->sk_sndbuf,READ_ONCE (sysctl_quic_wmem[1 ]));WRITE_ONCE (sk->sk_rcvbuf,READ_ONCE (sysctl_quic_rmem[1 ]));
@@ -59,6 +66,11 @@ static int quic_init_sock(struct sock *sk)static void quic_destroy_sock (struct sock *sk) { +u8 i; + +for (i =0 ; i <QUIC_PNSPACE_MAX ; i++) +quic_pnspace_free (quic_pnspace (sk, i)); +quic_path_free (sk,quic_paths (sk),0 );quic_path_free (sk,quic_paths (sk),1 );
net/quic/socket.h +7 -0
@@ -11,6 +11,7 @@#include <net/udp_tunnel.h> #include <linux/quic.h> +#include "pnspace.h" #include "common.h" #include "family.h" #include "stream.h"
@@ -44,6 +45,7 @@ struct quic_sock {struct quic_conn_id_set dest;struct quic_path_group paths;struct quic_cong cong; +struct quic_pnspace space[QUIC_PNSPACE_MAX ]; };struct quic6_sock {
@@ -111,6 +113,11 @@ static inline struct quic_cong *quic_cong(const struct sock *sk)return &quic_sk (sk)->cong; } +static inline struct quic_pnspace *quic_pnspace (const struct sock *sk,u8 level) +{ +return &quic_sk (sk)->space[level %QUIC_CRYPTO_EARLY ]; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
Signature · 1 line
2.47.1
PATCH v3 11/15 quic: add crypto key derivation and installation
In reply to Xin LongThis patch introduces 'quic_crypto', a component responsible for QUIC encryption key derivation and installation across the various key
levels: Initial, Handshake, 0-RTT (Early), and 1-RTT (Application).
It provides helpers to derive and install initial secrets, set traffic secrets and install the corresponding keys, and perform key updates to enable forward secrecy. Additionally, it implements stateless reset token generation, used to support connection reset without state.
- quic_crypto_initial_keys_install(): Derive and install initial keys.
- quic_crypto_set_cipher(): Allocate all transforms based on the cipher type provided.
- quic_crypto_set_secret(): Set the traffic secret and install derived keys.
- quic_crypto_key_update(): Rekey and install new keys to the !phase side.
- quic_crypto_generate_stateless_reset_token(): Generate token for stateless reset.
These mechanisms are essential for establishing and maintaining secure communication throughout the QUIC connection lifecycle.
---
v3:
- Remove lock from quic_net, since Initial packet decryption for ALPN will be handled serially in a workqueue when ALPN demux is enabled.
--- net/quic/Makefile | 2 +- net/quic/crypto.c | 542 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/crypto.h | 73 ++++++ net/quic/protocol.c | 11 + net/quic/protocol.h | 1 + net/quic/socket.c | 2 + net/quic/socket.h | 7 + 7 files changed, 637 insertions(+), 1 deletion(-) create mode 100644 net/quic/crypto.c create mode 100644 net/quic/crypto.h
net/quic/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ - cong.o pnspace.o + cong.o pnspace.o crypto.o
net/quic/crypto.c new file +542 -0
542 lines not on this page · raw message
net/quic/crypto.h new file +73 -0
73 lines not on this page · raw message
net/quic/protocol.c +11 -0
@@ -267,9 +267,17 @@ static int __net_init quic_net_init(struct net *net)if (!qn->stat)return -ENOMEM ; + err =quic_crypto_set_cipher (&qn->crypto,TLS_CIPHER_AES_GCM_128 ,CRYPTO_ALG_ASYNC ); +if (err) { +free_percpu (qn->stat); + qn->stat =NULL ; +return err; + } +#ifdef CONFIG_PROC_FS err =quic_net_proc_init (net);if (err) { +quic_crypto_free (&qn->crypto);free_percpu (qn->stat); qn->stat =NULL ; }
@@ -284,6 +292,7 @@ static void __net_exit quic_net_exit(struct net *net)#ifdef CONFIG_PROC_FS quic_net_proc_exit (net);#endif +quic_crypto_free (&qn->crypto);free_percpu (qn->stat); qn->stat =NULL ; }
@@ -332,6 +341,8 @@ static __init int quic_init(void) sysctl_quic_wmem[1 ] =16 *1024 ; sysctl_quic_wmem[2 ] =max (64 *1024 , max_share); +quic_crypto_init (); + err =percpu_counter_init (&quic_sockets_allocated,0 ,GFP_KERNEL );if (err) goto err_percpu_counter;
net/quic/protocol.h +1 -0
@@ -48,6 +48,7 @@ struct quic_net {#ifdef CONFIG_PROC_FS struct proc_dir_entry *proc_net;/* procfs entry for dumping QUIC socket stats */ #endif +struct quic_crypto crypto;/* Context for decrypting Initial packets for ALPN */ };struct quic_net *quic_net (struct net *net);
net/quic/socket.c +2 -0
@@ -70,6 +70,8 @@ static void quic_destroy_sock(struct sock *sk)for (i =0 ; i <QUIC_PNSPACE_MAX ; i++)quic_pnspace_free (quic_pnspace (sk, i)); +for (i =0 ; i <QUIC_CRYPTO_MAX ; i++) +quic_crypto_free (quic_crypto (sk, i));quic_path_free (sk,quic_paths (sk),0 );quic_path_free (sk,quic_paths (sk),1 );
net/quic/socket.h +7 -0
@@ -16,6 +16,7 @@#include "family.h" #include "stream.h" #include "connid.h" +#include "crypto.h" #include "path.h" #include "cong.h"
@@ -46,6 +47,7 @@ struct quic_sock {struct quic_path_group paths;struct quic_cong cong;struct quic_pnspace space[QUIC_PNSPACE_MAX ]; +struct quic_crypto crypto[QUIC_CRYPTO_MAX ]; };struct quic6_sock {
@@ -118,6 +120,11 @@ static inline struct quic_pnspace *quic_pnspace(const struct sock *sk, u8 level)return &quic_sk (sk)->space[level %QUIC_CRYPTO_EARLY ]; } +static inline struct quic_crypto *quic_crypto (const struct sock *sk,u8 level) +{ +return &quic_sk (sk)->crypto[level]; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
Signature · 1 line
2.47.1
PATCH v3 12/15 quic: add crypto packet encryption and decryption
In reply to Xin LongThis patch adds core support for packet-level encryption and decryption using AEAD, including both payload protection and QUIC header protection. It introduces helpers to encrypt packets before transmission and to remove header protection and decrypt payloads upon reception, in line with QUIC's cryptographic requirements.
- quic_crypto_encrypt(): Perform header protection and payload encryption (TX).
- quic_crypto_decrypt(): Perform header protection removal and payload decryption (RX).
The patch also includes support for Retry token handling. It provides helpers to compute the Retry integrity tag, generate tokens for address validation, and verify tokens received from clients during the handshake phase.
- quic_crypto_get_retry_tag(): Compute tag for Retry packets.
- quic_crypto_generate_token(): Generate retry token.
- quic_crypto_verify_token(): Verify retry token.
These additions establish the cryptographic primitives necessary for secure QUIC packet exchange and address validation.
---
v3:
- quic_crypto_decrypt(): return -EKEYREVOKED to defer key updates to the workqueue when the packet is not marked backlog, since quic_crypto_key_update()/crypto_aead_setkey() must run in process context.
- Only perform header decryption if !cb->number_len to avoid double decryption when a key-update packet (with flipped key_phase) re-enters quic_crypto_decrypt() from the workqueue.
--- net/quic/crypto.c | 661 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/crypto.h | 10 + 2 files changed, 671 insertions(+)
net/quic/crypto.c +661 -0
@@ -201,6 +201,343 @@ static int quic_crypto_rx_keys_derive_and_install(struct quic_crypto *crypto)return 0 ; } +static void *quic_crypto_skcipher_mem_alloc (struct crypto_skcipher *tfm,u32 mask_size, +u8 **iv,struct skcipher_request **req) +{ +unsigned int iv_size, req_size; +unsigned int len; +u8 *mem; + + iv_size =crypto_skcipher_ivsize (tfm); + req_size =sizeof (**req) +crypto_skcipher_reqsize (tfm); + + len = mask_size; + len += iv_size; + len +=crypto_skcipher_alignmask (tfm) & ~(crypto_tfm_ctx_alignment () -1 ); + len =ALIGN (len,crypto_tfm_ctx_alignment ()); + len += req_size; + + mem =kzalloc (len,GFP_ATOMIC ); +if (!mem) +return NULL ; + + *iv = (u8 *)PTR_ALIGN (mem + mask_size,crypto_skcipher_alignmask (tfm) +1 ); + *req = (struct skcipher_request *)PTR_ALIGN (*iv + iv_size, +crypto_tfm_ctx_alignment ()); + +return (void *)mem; +} + +#define QUIC_SAMPLE_LEN 16 +#define QUIC_MAX_PN_LEN 4 + +#define QUIC_HEADER_FORM_BIT 0x80 +#define QUIC_LONG_HEADER_MASK 0x0f +#define QUIC_SHORT_HEADER_MASK 0x1f + +/* Header Protection. */ +static int quic_crypto_header_encrypt (struct crypto_skcipher *tfm,struct sk_buff *skb,bool chacha) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +struct skcipher_request *req; +struct scatterlist sg; +u8 *mask, *iv, *p; +int err, i; + + mask =quic_crypto_skcipher_mem_alloc (tfm,QUIC_SAMPLE_LEN , &iv, &req); +if (!mask) +return -ENOMEM ; + +/* rfc9001#section-5.4.2: Header Protection Sample: +* +* # pn_offset is the start of the Packet Number field. +* sample_offset = pn_offset + 4 +* +* sample = packet[sample_offset..sample_offset+sample_length] +* +* rfc9001#section-5.4.3: AES-Based Header Protection: +* +* header_protection(hp_key, sample): +* mask = AES-ECB(hp_key, sample) +* +* rfc9001#section-5.4.4: ChaCha20-Based Header Protection: +* +* header_protection(hp_key, sample): +* counter = sample[0..3] +* nonce = sample[4..15] +* mask = ChaCha20(hp_key, counter, nonce, {0,0,0,0,0}) +*/ +memcpy ((chacha ? iv : mask), skb->data + cb->number_offset +QUIC_MAX_PN_LEN , +QUIC_SAMPLE_LEN ); +sg_init_one (&sg, mask,QUIC_SAMPLE_LEN ); +skcipher_request_set_tfm (req, tfm); +skcipher_request_set_crypt (req, &sg, &sg,QUIC_SAMPLE_LEN , iv); + err =crypto_skcipher_encrypt (req); +if (err) + goto err; + +/* rfc9001#section-5.4.1: +* +* mask = header_protection(hp_key, sample) +* +* pn_length = (packet[0] & 0x03) + 1 +* if (packet[0] & 0x80) == 0x80: +* # Long header: 4 bits masked +* packet[0] ^= mask[0] & 0x0f +* else: +* # Short header: 5 bits masked +* packet[0] ^= mask[0] & 0x1f +* +* # pn_offset is the start of the Packet Number field. +* packet[pn_offset:pn_offset+pn_length] ^= mask[1:1+pn_length] +*/ + p = skb->data; + *p = (u8)(*p ^ (mask[0 ] & (((*p &QUIC_HEADER_FORM_BIT ) ==QUIC_HEADER_FORM_BIT ) ? +QUIC_LONG_HEADER_MASK :QUIC_SHORT_HEADER_MASK ))); + p = skb->data + cb->number_offset; +for (i =1 ; i <= cb->number_len; i++) + *p++ ^= mask[i]; +err: +kfree (mask); +return err; +} + +/* Extracts and reconstructs the packet number from an incoming QUIC packet. */ +static void quic_crypto_get_header (struct sk_buff *skb) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +struct quichdr *hdr =quic_hdr (skb); +u32 len =QUIC_MAX_PN_LEN ; +u8 *p = (u8 *)hdr; + +/* rfc9000#section-17.1: +* +* Once header protection is removed, the packet number is decoded by finding the packet +* number value that is closest to the next expected packet. The next expected packet is +* the highest received packet number plus one. +*/ + p += cb->number_offset; + cb->key_phase = hdr->key; + cb->number_len = hdr->pnl +1 ; +quic_get_int (&p, &len, &cb->number, cb->number_len); + cb->number =quic_get_num (cb->number_max, cb->number, cb->number_len); + +if (cb->number > cb->number_max) + cb->number_max = cb->number; +} + +#define QUIC_PN_LEN_BITS_MASK 0x03 + +static int quic_crypto_header_decrypt (struct crypto_skcipher *tfm,struct sk_buff *skb,bool chacha) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +struct quichdr *hdr =quic_hdr (skb); +int err, i, len = cb->length; +struct skcipher_request *req; +struct scatterlist sg; +u8 *mask, *iv, *p; + + mask =quic_crypto_skcipher_mem_alloc (tfm,QUIC_SAMPLE_LEN , &iv, &req); +if (!mask) +return -ENOMEM ; + +if (len <QUIC_MAX_PN_LEN +QUIC_SAMPLE_LEN ) { + err = -EINVAL ; + goto err; + } + +/* Similar logic to quic_crypto_header_encrypt(). */ + p = (u8 *)hdr + cb->number_offset; +memcpy ((chacha ? iv : mask), p +QUIC_MAX_PN_LEN ,QUIC_SAMPLE_LEN ); +sg_init_one (&sg, mask,QUIC_SAMPLE_LEN ); +skcipher_request_set_tfm (req, tfm); +skcipher_request_set_crypt (req, &sg, &sg,QUIC_SAMPLE_LEN , iv); + err =crypto_skcipher_encrypt (req); +if (err) + goto err; + + p = (u8 *)hdr; + *p = (u8)(*p ^ (mask[0 ] & (((*p &QUIC_HEADER_FORM_BIT ) ==QUIC_HEADER_FORM_BIT ) ? +QUIC_LONG_HEADER_MASK :QUIC_SHORT_HEADER_MASK ))); + cb->number_len = (*p &QUIC_PN_LEN_BITS_MASK ) +1 ; + p += cb->number_offset; +for (i =0 ; i < cb->number_len; ++i) + *(p + i) = *((u8 *)hdr + cb->number_offset + i) ^ mask[i +1 ]; +quic_crypto_get_header (skb); + +err: +kfree (mask); +return err; +} + +static void *quic_crypto_aead_mem_alloc (struct crypto_aead *tfm,u32 ctx_size, +u8 **iv,struct aead_request **req, +struct scatterlist **sg,u32 nsg) +{ +unsigned int iv_size, req_size; +unsigned int len; +u8 *mem; + + iv_size =crypto_aead_ivsize (tfm); + req_size =sizeof (**req) +crypto_aead_reqsize (tfm); + + len = ctx_size; + len += iv_size; + len +=crypto_aead_alignmask (tfm) & ~(crypto_tfm_ctx_alignment () -1 ); + len =ALIGN (len,crypto_tfm_ctx_alignment ()); + len += req_size; + len =ALIGN (len, __alignof__(struct scatterlist )); + len += nsg *sizeof (**sg); + + mem =kzalloc (len,GFP_ATOMIC ); +if (!mem) +return NULL ; + + *iv = (u8 *)PTR_ALIGN (mem + ctx_size,crypto_aead_alignmask (tfm) +1 ); + *req = (struct aead_request *)PTR_ALIGN (*iv + iv_size, +crypto_tfm_ctx_alignment ()); + *sg = (struct scatterlist *)PTR_ALIGN ((u8 *)*req + req_size, + __alignof__(struct scatterlist )); + +return (void *)mem; +} + +static void quic_crypto_destruct_skb (struct sk_buff *skb) +{ +kfree (skb_shinfo (skb)->destructor_arg); +sock_efree (skb); +} + +static void quic_crypto_done (void *data,int err) +{ +struct sk_buff *skb = data; + +QUIC_SKB_CB (skb)->crypto_done (skb, err); +} + +/* AEAD Usage. */ +static int quic_crypto_payload_encrypt (struct crypto_aead *tfm,struct sk_buff *skb, +u8 *tx_iv,bool ccm) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +struct quichdr *hdr =quic_hdr (skb); +u8 *iv, i, nonce[QUIC_IV_LEN ]; +struct aead_request *req; +struct sk_buff *trailer; +struct scatterlist *sg; +u32 nsg, hlen, len; +void *ctx; +__be64 n; +int err; + + len = skb->len; + err =skb_cow_data (skb,QUIC_TAG_LEN , &trailer); +if (err <0 ) +return err; + nsg = (u32 )err; +pskb_put (skb, trailer,QUIC_TAG_LEN ); + hdr->key = cb->key_phase; + + ctx =quic_crypto_aead_mem_alloc (tfm,0 , &iv, &req, &sg, nsg); +if (!ctx) +return -ENOMEM ; + +sg_init_table (sg, nsg); + err =skb_to_sgvec (skb, sg,0 , (int )skb->len); +if (err <0 ) + goto err; + +/* rfc9001#section-5.3: +* +* The associated data, A, for the AEAD is the contents of the QUIC header, +* starting from the first byte of either the short or long header, up to and +* including the unprotected packet number. +* +* The nonce, N, is formed by combining the packet protection IV with the packet +* number. The 62 bits of the reconstructed QUIC packet number in network byte +* order are left-padded with zeros to the size of the IV. The exclusive OR of the +* padded packet number and the IV forms the AEAD nonce. +*/ + hlen = cb->number_offset + cb->number_len; +memcpy (nonce, tx_iv,QUIC_IV_LEN ); + n =cpu_to_be64 (cb->number); +for (i =0 ; i <sizeof (n); i++) + nonce[QUIC_IV_LEN -sizeof (n) + i] ^= ((u8 *)&n)[i]; + +/* For CCM based ciphers, first byte of IV is a constant. */ + iv[0 ] =TLS_AES_CCM_IV_B0_BYTE ; +memcpy (&iv[ccm], nonce,QUIC_IV_LEN ); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, hlen); +aead_request_set_crypt (req, sg, sg, len - hlen, iv); +aead_request_set_callback (req,CRYPTO_TFM_REQ_MAY_BACKLOG , (void *)quic_crypto_done, skb); + + err =crypto_aead_encrypt (req); +if (err == -EINPROGRESS ) { +/* Will complete asynchronously; set destructor to free context. */ + skb->destructor = quic_crypto_destruct_skb; +skb_shinfo (skb)->destructor_arg = ctx; +return err; + } + +err: +kfree (ctx); +return err; +} + +static int quic_crypto_payload_decrypt (struct crypto_aead *tfm,struct sk_buff *skb, +u8 *rx_iv,bool ccm) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u8 *iv, i, nonce[QUIC_IV_LEN ]; +struct aead_request *req; +struct sk_buff *trailer; +int nsg, hlen, len, err; +struct scatterlist *sg; +void *ctx; +__be64 n; + + len = cb->length + cb->number_offset; + hlen = cb->number_offset + cb->number_len; +if (len - hlen <QUIC_TAG_LEN ) +return -EINVAL ; + nsg =skb_cow_data (skb,0 , &trailer); +if (nsg <0 ) +return nsg; + ctx =quic_crypto_aead_mem_alloc (tfm,0 , &iv, &req, &sg, nsg); +if (!ctx) +return -ENOMEM ; + +sg_init_table (sg, nsg); + err =skb_to_sgvec (skb, sg,0 , len); +if (err <0 ) + goto err; +skb_dst_force (skb); + +/* Similar logic to quic_crypto_payload_encrypt(). */ +memcpy (nonce, rx_iv,QUIC_IV_LEN ); + n =cpu_to_be64 (cb->number); +for (i =0 ; i <sizeof (n); i++) + nonce[QUIC_IV_LEN -sizeof (n) + i] ^= ((u8 *)&n)[i]; + + iv[0 ] =TLS_AES_CCM_IV_B0_BYTE ; +memcpy (&iv[ccm], nonce,QUIC_IV_LEN ); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, hlen); +aead_request_set_crypt (req, sg, sg, len - hlen, iv); +aead_request_set_callback (req,CRYPTO_TFM_REQ_MAY_BACKLOG , (void *)quic_crypto_done, skb); + + err =crypto_aead_decrypt (req); +if (err == -EINPROGRESS ) { + skb->destructor = quic_crypto_destruct_skb; +skb_shinfo (skb)->destructor_arg = ctx; +return err; + } +err: +kfree (ctx); +return err; +} +#define QUIC_CIPHER_MIN TLS_CIPHER_AES_GCM_128#define QUIC_CIPHER_MAX TLS_CIPHER_CHACHA20_POLY1305
@@ -225,6 +562,135 @@ static struct quic_cipher ciphers[QUIC_CIPHER_MAX + 1 - QUIC_CIPHER_MIN] = { "rfc7539(chacha20,poly1305)", "chacha20", "hmac(sha256)"), }; +static bool quic_crypto_is_cipher_ccm (struct quic_crypto *crypto) +{ +return crypto->cipher_type ==TLS_CIPHER_AES_CCM_128 ; +} + +static bool quic_crypto_is_cipher_chacha (struct quic_crypto *crypto) +{ +return crypto->cipher_type ==TLS_CIPHER_CHACHA20_POLY1305 ; +} + +/* Encrypts a QUIC packet before transmission. This function performs AEAD encryption of +* the packet payload and applies header protection. It handles key phase tracking and key +* update timing.. +* +* Return: 0 on success, or a negative error code. +*/ +int quic_crypto_encrypt (struct quic_crypto *crypto,struct sk_buff *skb) +{ +u8 *iv, cha, ccm, phase = crypto->key_phase; +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +int err; + + cb->key_phase = phase; + iv = crypto->tx_iv[phase]; +/* Packet payload is already encrypted (e.g., resumed from async), proceed to header +* protection only. +*/ +if (cb->resume) + goto out; + +/* If a key update is pending and this is the first packet using the new key, save the +* current time. Later used to clear old keys after some time has passed (see +* quic_crypto_decrypt()). +*/ +if (crypto->key_pending && !crypto->key_update_send_time) + crypto->key_update_send_time =jiffies_to_usecs (jiffies); + + ccm =quic_crypto_is_cipher_ccm (crypto); + err =quic_crypto_payload_encrypt (crypto->tx_tfm[phase], skb, iv, ccm); +if (err) +return err; +out: + cha =quic_crypto_is_cipher_chacha (crypto); +return quic_crypto_header_encrypt (crypto->tx_hp_tfm, skb, cha); +} + +/* Decrypts a QUIC packet after reception. This function removes header protection, +* decrypts the payload, and processes any key updates if the key phase bit changes. +* +* Return: 0 on success, or a negative error code. +*/ +int quic_crypto_decrypt (struct quic_crypto *crypto,struct sk_buff *skb) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u8 *iv, cha, ccm, phase; +int err =0 ; +u32 time; + +/* Payload was decrypted asynchronously. Proceed with parsing packet number and key +* phase. +*/ +if (cb->resume) { +quic_crypto_get_header (skb); + goto out; + } +if (!cb->number_len) {/* Packet header not yet decrypted. */ + cha =quic_crypto_is_cipher_chacha (crypto); + err =quic_crypto_header_decrypt (crypto->rx_hp_tfm, skb, cha); +if (err) { +pr_debug ("%s: hd decrypt err %d\n" , __func__, err); +return err; + } + } + +/* rfc9001#section-6: +* +* The Key Phase bit allows a recipient to detect a change in keying material without +* needing to receive the first packet that triggered the change. An endpoint that +* notices a changed Key Phase bit updates keys and decrypts the packet that contains +* the changed value. +*/ +if (cb->key_phase != crypto->key_phase && !crypto->key_pending) { +if (!crypto->send_ready)/* Not ready for key update. */ +return -EINVAL ; +if (!cb->backlog)/* Key update must be done in process context. */ +return -EKEYREVOKED ; + err =quic_crypto_key_update (crypto);/* Perform a key update. */ +if (err) { + cb->errcode =QUIC_TRANSPORT_ERROR_KEY_UPDATE ; +return err; + } + cb->key_update =1 ;/* Mark packet as triggering key update. */ + } + + phase = cb->key_phase; + iv = crypto->rx_iv[phase]; + ccm =quic_crypto_is_cipher_ccm (crypto); + err =quic_crypto_payload_decrypt (crypto->rx_tfm[phase], skb, iv, ccm); +if (err) { +if (err == -EINPROGRESS ) +return err; +/* When using the old keys can not decrypt the packets, the peer might +* start another key_update. Thus, clear the last key_pending so that +* next packets will trigger the new key-update. +*/ +if (crypto->key_pending && cb->key_phase != crypto->key_phase) { + crypto->key_pending =0 ; + crypto->key_update_time =0 ; + } +return err; + } + +out: +/* rfc9001#section-6.1: +* +* An endpoint MUST retain old keys until it has successfully unprotected a +* packet sent using the new keys. An endpoint SHOULD retain old keys for +* some time after unprotecting a packet sent using the new keys. +*/ +if (crypto->key_pending && cb->key_phase == crypto->key_phase) { + time = crypto->key_update_send_time; +if (time &&jiffies_to_usecs (jiffies) - time >= crypto->key_update_time) { + crypto->key_pending =0 ; + crypto->key_update_time =0 ; + } + } +return err; +} +int quic_crypto_set_cipher (struct quic_crypto *crypto,u32 type,u8 flag) {struct quic_cipher *cipher;
@@ -501,6 +967,201 @@ int quic_crypto_initial_keys_install(struct quic_crypto *crypto, struct quic_conreturn quic_crypto_set_secret (crypto, &srt, version,0 ); } +#define QUIC_RETRY_KEY_V1 "\xbe\x0c\x69\x0b\x9f\x66\x57\x5a\x1d\x76\x6b\x54\xe3\x68\xc8\x4e" +#define QUIC_RETRY_KEY_V2 "\x8f\xb4\xb0\x1b\x56\xac\x48\xe2\x60\xfb\xcb\xce\xad\x7c\xcc\x92" + +#define QUIC_RETRY_NONCE_V1 "\x46\x15\x99\xd3\x5d\x63\x2b\xf2\x23\x98\x25\xbb" +#define QUIC_RETRY_NONCE_V2 "\xd8\x69\x69\xbc\x2d\x7c\x6d\x99\x90\xef\xb0\x4a" + +/* Retry Packet Integrity. */ +int quic_crypto_get_retry_tag (struct quic_crypto *crypto,struct sk_buff *skb, +struct quic_conn_id *odcid,u32 version,u8 *tag) +{ +struct crypto_aead *tfm = crypto->tag_tfm; +u8 *pseudo_retry, *p, *iv, *key; +struct aead_request *req; +struct scatterlist *sg; +u32 plen; +int err; + +/* rfc9001#section-5.8: +* +* The Retry Integrity Tag is a 128-bit field that is computed as the output of +* AEAD_AES_128_GCM used with the following inputs: +* +* - The secret key, K, is 128 bits equal to 0xbe0c690b9f66575a1d766b54e368c84e. +* - The nonce, N, is 96 bits equal to 0x461599d35d632bf2239825bb. +* - The plaintext, P, is empty. +* - The associated data, A, is the contents of the Retry Pseudo-Packet, +* +* The Retry Pseudo-Packet is not sent over the wire. It is computed by taking the +* transmitted Retry packet, removing the Retry Integrity Tag, and prepending the +* two following fields: ODCID Length + Original Destination Connection ID (ODCID). +*/ + err =crypto_aead_setauthsize (tfm,QUIC_TAG_LEN ); +if (err) +return err; + key =QUIC_RETRY_KEY_V1 ; +if (version ==QUIC_VERSION_V2 ) + key =QUIC_RETRY_KEY_V2 ; + err =crypto_aead_setkey (tfm, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +if (err) +return err; + + plen =1 + odcid->len + skb->len -QUIC_TAG_LEN ; + pseudo_retry =quic_crypto_aead_mem_alloc (tfm, plen +QUIC_TAG_LEN , &iv, &req, &sg,1 ); +if (!pseudo_retry) +return -ENOMEM ; + + p = pseudo_retry; + p =quic_put_int (p, odcid->len,1 ); + p =quic_put_data (p, odcid->data, odcid->len); + p =quic_put_data (p, skb->data, skb->len -QUIC_TAG_LEN ); +sg_init_one (sg, pseudo_retry, plen +QUIC_TAG_LEN ); + +memcpy (iv,QUIC_RETRY_NONCE_V1 ,QUIC_IV_LEN ); +if (version ==QUIC_VERSION_V2 ) +memcpy (iv,QUIC_RETRY_NONCE_V2 ,QUIC_IV_LEN ); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, plen); +aead_request_set_crypt (req, sg, sg,0 , iv); + err =crypto_aead_encrypt (req); +if (!err) +memcpy (tag, p,QUIC_TAG_LEN ); +kfree (pseudo_retry); +return err; +} + +/* Generate a token for Retry or address validation. +* +* Builds a token with the format: [client address][timestamp][original DCID][auth tag] +* +* Encrypts the token (excluding the first flag byte) using AES-GCM with a key and IV +* derived via HKDF. The original DCID is stored to be recovered later from a Client +* Initial packet. Ensures the token is bound to the client address and time, preventing +* reuse or tampering. +* +* Returns 0 on success or a negative error code on failure. +*/ +int quic_crypto_generate_token (struct quic_crypto *crypto,void *addr,u32 addrlen, +struct quic_conn_id *conn_id,u8 *token,u32 *tlen) +{ +u8 key[TLS_CIPHER_AES_GCM_128_KEY_SIZE ], iv[QUIC_IV_LEN ], *retry_token, *tx_iv, *p; +struct crypto_aead *tfm = crypto->tag_tfm; +u32 ts =jiffies_to_usecs (jiffies), len; +struct quic_data srt = {}, k, i; +struct aead_request *req; +struct scatterlist *sg; +int err; + +quic_data (&srt, quic_random_data,QUIC_RANDOM_DATA_LEN ); +quic_data (&k, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +quic_data (&i, iv,QUIC_IV_LEN ); + err =quic_crypto_keys_derive (crypto->secret_tfm, &srt, &k, &i,NULL ,QUIC_VERSION_V1 ); +if (err) +return err; + err =crypto_aead_setauthsize (tfm,QUIC_TAG_LEN ); +if (err) +return err; + err =crypto_aead_setkey (tfm, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +if (err) +return err; + token++; + len = addrlen +sizeof (ts) + conn_id->len +QUIC_TAG_LEN ; + retry_token =quic_crypto_aead_mem_alloc (tfm, len, &tx_iv, &req, &sg,1 ); +if (!retry_token) +return -ENOMEM ; + + p = retry_token; + p =quic_put_data (p, addr, addrlen); + p =quic_put_int (p, ts,sizeof (ts)); +quic_put_data (p, conn_id->data, conn_id->len); +sg_init_one (sg, retry_token, len); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, addrlen); +aead_request_set_crypt (req, sg, sg, len - addrlen -QUIC_TAG_LEN , iv); + err =crypto_aead_encrypt (req); +if (!err) { +memcpy (token, retry_token, len); + *tlen = len +1 ; + } +kfree (retry_token); +return err; +} + +/* Validate a Retry or address validation token. +* +* Decrypts the token using derived key and IV. Checks that the decrypted address matches +* the provided address, validates the embedded timestamp against current time with a +* version-specific timeout. If applicable, it extracts and returns the original +* destination connection ID (ODCID) for Retry packets. +* +* Returns 0 if the token is valid, -EINVAL if invalid, or another negative error code. +*/ +int quic_crypto_verify_token (struct quic_crypto *crypto,void *addr,u32 addrlen, +struct quic_conn_id *conn_id,u8 *token,u32 len) +{ +u32 ts =jiffies_to_usecs (jiffies), timeout =QUIC_TOKEN_TIMEOUT_RETRY ; +u8 key[TLS_CIPHER_AES_GCM_128_KEY_SIZE ], iv[QUIC_IV_LEN ]; +u8 *retry_token, *rx_iv, *p, flag = *token; +struct crypto_aead *tfm = crypto->tag_tfm; +struct quic_data srt = {}, k, i; +struct aead_request *req; +struct scatterlist *sg; +int err; +u64 t; + +if (len <sizeof (flag) + addrlen +sizeof (ts) +QUIC_TAG_LEN ) +return -EINVAL ; +quic_data (&srt, quic_random_data,QUIC_RANDOM_DATA_LEN ); +quic_data (&k, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +quic_data (&i, iv,QUIC_IV_LEN ); + err =quic_crypto_keys_derive (crypto->secret_tfm, &srt, &k, &i,NULL ,QUIC_VERSION_V1 ); +if (err) +return err; + err =crypto_aead_setauthsize (tfm,QUIC_TAG_LEN ); +if (err) +return err; + err =crypto_aead_setkey (tfm, key,TLS_CIPHER_AES_GCM_128_KEY_SIZE ); +if (err) +return err; + len--; + token++; + retry_token =quic_crypto_aead_mem_alloc (tfm, len, &rx_iv, &req, &sg,1 ); +if (!retry_token) +return -ENOMEM ; + +memcpy (retry_token, token, len); +sg_init_one (sg, retry_token, len); +aead_request_set_tfm (req, tfm); +aead_request_set_ad (req, addrlen); +aead_request_set_crypt (req, sg, sg, len - addrlen, iv); + err =crypto_aead_decrypt (req); +if (err) + goto out; + + err = -EINVAL ; + p = retry_token; +if (memcmp (p, addr, addrlen)) + goto out; + p += addrlen; + len -= addrlen; +if (flag ==QUIC_TOKEN_FLAG_REGULAR ) + timeout =QUIC_TOKEN_TIMEOUT_REGULAR ; +if (!quic_get_int (&p, &len, &t,sizeof (ts)) || t + timeout < ts) + goto out; + len -=QUIC_TAG_LEN ; +if (len >QUIC_CONN_ID_MAX_LEN ) + goto out; + +if (flag ==QUIC_TOKEN_FLAG_RETRY ) +quic_conn_id_update (conn_id, p, len); + err =0 ; +out: +kfree (retry_token); +return err; +} +/* Generate a derived key using HKDF-Extract and HKDF-Expand with a given label. */ static int quic_crypto_generate_key (struct quic_crypto *crypto,void *data,u32 len,char *label,u8 *token,u32 key_len)
net/quic/crypto.h +10 -0
@@ -62,6 +62,9 @@ int quic_crypto_get_secret(struct quic_crypto *crypto, struct quic_crypto_secretint quic_crypto_set_cipher (struct quic_crypto *crypto,u32 type,u8 flag);int quic_crypto_key_update (struct quic_crypto *crypto); +int quic_crypto_encrypt (struct quic_crypto *crypto,struct sk_buff *skb); +int quic_crypto_decrypt (struct quic_crypto *crypto,struct sk_buff *skb); +int quic_crypto_initial_keys_install (struct quic_crypto *crypto,struct quic_conn_id *conn_id,u32 version,bool is_serv); int quic_crypto_generate_session_ticket_key(struct quic_crypto *crypto, void *data,
@@ -69,5 +72,12 @@ int quic_crypto_generate_session_ticket_key(struct quic_crypto *crypto, void *daint quic_crypto_generate_stateless_reset_token (struct quic_crypto *crypto,void *data,u32 len,u8 *key,u32 key_len); +int quic_crypto_generate_token (struct quic_crypto *crypto,void *addr,u32 addrlen, +struct quic_conn_id *conn_id,u8 *token,u32 *tlen); +int quic_crypto_get_retry_tag (struct quic_crypto *crypto,struct sk_buff *skb, +struct quic_conn_id *odcid,u32 version,u8 *tag); +int quic_crypto_verify_token (struct quic_crypto *crypto,void *addr,u32 addrlen, +struct quic_conn_id *conn_id,u8 *token,u32 len); +void quic_crypto_free (struct quic_crypto *crypto);void quic_crypto_init (void );
Signature · 1 line
2.47.1
PATCH v3 13/15 quic: add timer management
In reply to Xin LongThis patch introduces 'quic_timer' to unify and manage the five main timers used in QUIC: loss detection, delayed ACK, path validation, PMTU probing, and pacing. These timers are critical for driving retransmissions, connection liveness, and flow control.
Each timer type is initialized, started, reset, or stopped using a common set of operations.
- quic_timer_reset(): Reset a timer with type and timeout
- quic_timer_start(): Start a timer with type and timeout
- quic_timer_stop(): Stop a timer with type
Although handler functions for each timer are defined, they are currently placeholders; their logic will be implemented in upcoming patches for packet transmission and outqueue handling.
Deferred timer actions are also integrated through quic_release_cb(), which dispatches to the appropriate handler when timers expire.
--- net/quic/Makefile | 2 +- net/quic/socket.c | 33 ++++++++ net/quic/socket.h | 33 ++++++++ net/quic/timer.c | 196 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/timer.h | 47 +++++++++++ 5 files changed, 310 insertions(+), 1 deletion(-) create mode 100644 net/quic/timer.c create mode 100644 net/quic/timer.h
net/quic/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ - cong.o pnspace.o crypto.o + cong.o pnspace.o crypto.o timer.o
net/quic/socket.c +33 -0
@@ -47,6 +47,8 @@ static int quic_init_sock(struct sock *sk)quic_conn_id_set_init (quic_dest (sk),0 );quic_cong_init (quic_cong (sk)); +quic_timer_init (sk); +if (quic_stream_init (quic_streams (sk)))return -ENOMEM ;
@@ -68,6 +70,8 @@ static void quic_destroy_sock(struct sock *sk) {u8 i; +quic_timer_free (sk); +for (i =0 ; i <QUIC_PNSPACE_MAX ; i++)quic_pnspace_free (quic_pnspace (sk, i));for (i =0 ; i <QUIC_CRYPTO_MAX ; i++)
@@ -204,6 +208,35 @@ EXPORT_SYMBOL_GPL(quic_kernel_getsockopt);static void quic_release_cb (struct sock *sk) { +/* Similar to tcp_release_cb(). */ +unsigned long nflags, flags =smp_load_acquire (&sk->sk_tsq_flags); + +do { +if (!(flags &QUIC_DEFERRED_ALL )) +return ; + nflags = flags & ~QUIC_DEFERRED_ALL ; + }while (!try_cmpxchg (&sk->sk_tsq_flags, &flags, nflags)); + +if (flags &QUIC_F_LOSS_DEFERRED ) { +quic_timer_loss_handler (sk); +__sock_put (sk); + } +if (flags &QUIC_F_SACK_DEFERRED ) { +quic_timer_sack_handler (sk); +__sock_put (sk); + } +if (flags &QUIC_F_PATH_DEFERRED ) { +quic_timer_path_handler (sk); +__sock_put (sk); + } +if (flags &QUIC_F_PMTU_DEFERRED ) { +quic_timer_pmtu_handler (sk); +__sock_put (sk); + } +if (flags &QUIC_F_TSQ_DEFERRED ) { +quic_timer_pace_handler (sk); +__sock_put (sk); + } }static int quic_disconnect (struct sock *sk,int flags)
net/quic/socket.h +33 -0
@@ -21,6 +21,7 @@#include "cong.h" #include "protocol.h" +#include "timer.h" extern struct proto quic_prot;extern struct proto quicv6_prot;
@@ -32,6 +33,31 @@ enum quic_state { QUIC_SS_ESTABLISHED = TCP_ESTABLISHED, }; +enum quic_tsq_enum { +QUIC_MTU_REDUCED_DEFERRED , +QUIC_LOSS_DEFERRED , +QUIC_SACK_DEFERRED , +QUIC_PATH_DEFERRED , +QUIC_PMTU_DEFERRED , +QUIC_TSQ_DEFERRED , +}; + +enum quic_tsq_flags { +QUIC_F_MTU_REDUCED_DEFERRED =BIT (QUIC_MTU_REDUCED_DEFERRED ), +QUIC_F_LOSS_DEFERRED =BIT (QUIC_LOSS_DEFERRED ), +QUIC_F_SACK_DEFERRED =BIT (QUIC_SACK_DEFERRED ), +QUIC_F_PATH_DEFERRED =BIT (QUIC_PATH_DEFERRED ), +QUIC_F_PMTU_DEFERRED =BIT (QUIC_PMTU_DEFERRED ), +QUIC_F_TSQ_DEFERRED =BIT (QUIC_TSQ_DEFERRED ), +}; + +#define QUIC_DEFERRED_ALL (QUIC_F_MTU_REDUCED_DEFERRED | \ + QUIC_F_LOSS_DEFERRED | \ + QUIC_F_SACK_DEFERRED | \ + QUIC_F_PATH_DEFERRED | \ + QUIC_F_PMTU_DEFERRED | \ + QUIC_F_TSQ_DEFERRED) +struct quic_sock {struct inet_sock inet;struct list_head reqs;
@@ -48,6 +74,8 @@ struct quic_sock {struct quic_cong cong;struct quic_pnspace space[QUIC_PNSPACE_MAX ];struct quic_crypto crypto[QUIC_CRYPTO_MAX ]; + +struct quic_timer timers[QUIC_TIMER_MAX ]; };struct quic6_sock {
@@ -125,6 +153,11 @@ static inline struct quic_crypto *quic_crypto(const struct sock *sk, u8 level)return &quic_sk (sk)->crypto[level]; } +static inline void *quic_timer (const struct sock *sk,u8 type) +{ +return (void *)&quic_sk (sk)->timers[type]; +} +static inline bool quic_is_establishing (struct sock *sk) {return sk->sk_state ==QUIC_SS_ESTABLISHING ;
net/quic/timer.c new file +196 -0
196 lines not on this page · raw message
net/quic/timer.h new file +47 -0
47 lines not on this page · raw message
Signature · 1 line
2.47.1
PATCH v3 14/15 quic: add frame encoder and decoder base
In reply to Xin LongThis patch introduces 'quic_frame' to represent QUIC frames and 'quic_frame_ops' to define the associated operations for encoding, processing, and acknowledgment.
This abstraction sets the foundation for flexible and modular frame handling. While core operations are defined, actual implementation will follow in subsequent patches once packet handling and inqueue/outqueue infrastructure are in place.
The patch introduces hooks for invoking frame-specific logic:
- quic_frame_create(): Invoke the .create operation of the frame.
- quic_frame_process(): Invoke the .process operation of the frame.
- quic_frame_ack(): Invoke the .ack operation of the frame.
To manage frame lifecycles, reference counting is used, supported by
- quic_frame_get(): Increment the reference count of a frame.
- quic_frame_put(): Decrement the reference count of a frame.
- quic_frame_alloc(): Allocate a frame and set its data.
Frames are allocated through quic_frame_alloc(), and a dedicated kmem_cache (quic_frame_cachep) is added to optimize memory usage.
For STREAM frames, additional data can be appended using
- quic_frame_stream_append(): Append more data to a STREAM frame.
---
v2:
- Clarify the use of offset field with a union type in struct frame.
--- net/quic/Makefile | 2 +- net/quic/frame.c | 558 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/frame.h | 195 ++++++++++++++++ net/quic/protocol.c | 9 + net/quic/protocol.h | 1 + net/quic/socket.h | 2 + 6 files changed, 766 insertions(+), 1 deletion(-) create mode 100644 net/quic/frame.c create mode 100644 net/quic/frame.h
net/quic/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ - cong.o pnspace.o crypto.o timer.o + cong.o pnspace.o crypto.o timer.o frame.o
net/quic/frame.c new file +558 -0
558 lines not on this page · raw message
net/quic/frame.h new file +195 -0
195 lines not on this page · raw message
net/quic/protocol.c +9 -0
@@ -20,6 +20,7 @@static unsigned int quic_net_id__read_mostly ; +struct kmem_cache *quic_frame_cachep__read_mostly ;struct percpu_counter quic_sockets_allocated;long sysctl_quic_mem[3 ];
@@ -343,6 +344,11 @@ static __init int quic_init(void)quic_crypto_init (); + quic_frame_cachep =kmem_cache_create ("quic_frame" ,sizeof (struct quic_frame ), +0 ,SLAB_HWCACHE_ALIGN ,NULL ); +if (!quic_frame_cachep) + goto err; + err =percpu_counter_init (&quic_sockets_allocated,0 ,GFP_KERNEL );if (err) goto err_percpu_counter;
@@ -371,6 +377,8 @@ static __init int quic_init(void) err_hash:percpu_counter_destroy (&quic_sockets_allocated); err_percpu_counter: +kmem_cache_destroy (quic_frame_cachep); +err:return err; }
@@ -383,6 +391,7 @@ static __exit void quic_exit(void)unregister_pernet_subsys (&quic_net_ops);quic_hash_tables_destroy ();percpu_counter_destroy (&quic_sockets_allocated); +kmem_cache_destroy (quic_frame_cachep);pr_info ("quic: exit\n" ); }
net/quic/protocol.h +1 -0
@@ -8,6 +8,7 @@* Xin Long <[email protected]> */ +extern struct kmem_cache *quic_frame_cachep__read_mostly ;extern struct percpu_counter quic_sockets_allocated;extern long sysctl_quic_mem[3 ];
net/quic/socket.h +2 -0
@@ -20,6 +20,8 @@#include "path.h" #include "cong.h" +#include "frame.h" +#include "protocol.h" #include "timer.h"
Signature · 1 line
2.47.1
PATCH v3 15/15 quic: add packet builder and parser base
In reply to Xin LongThis patch introduces 'quic_packet' to handle packing and unpacking of QUIC packets on both the transmit (TX) and receive (RX) paths.
On the TX path, it provides functionality for frame packing and packet construction. The packet configuration includes setting the path, calculating overhead, and verifying routing. Frames are appended to the packet before it is created with the queued frames.
Once assembled, the packet is encrypted, bundled, and sent out. There is also support to flush the packet when no additional frames remain. Functions to create application (short) and handshake (long) packets are currently placeholders for future implementation.
- quic_packet_config(): Set the path, compute overhead, and verify routing.
- quic_packet_tail(): Append a frame to the packet for transmission.
- quic_packet_create(): Create the packet with the queued frames.
- quic_packet_xmit(): Encrypt, bundle, and send out the packet.
- quic_packet_flush(): Send the packet if there's nothing left to bundle.
On the RX side, the patch introduces mechanisms to parse the ALPN from client Initial packets to determine the correct listener socket. Received packets are then routed and processed accordingly. Similar to the TX path, handling for application and handshake packets is not yet implemented.
- quic_packet_parse_alpn()`: Parse the ALPN from a client Initial packet, then locate the appropriate listener using the ALPN.
- quic_packet_rcv(): Locate the appropriate socket to handle the packet via quic_packet_process().
- quic_packet_process()`: Process the received packet.
In addition to packet flow, this patch adds support for ICMP-based MTU updates by locating the relevant socket and updating the stored PMTU accordingly.
- quic_packet_rcv_err_pmtu(): Find the socket and update the PMTU via quic_packet_mss_update().
---
v3:
- Adjust global connection and listen socket hashtable operations based on the new hashtable type.
- Introduce quic_packet_backlog_schedule() to enqueue Initial packets to quic_net.backlog_list and defer their decryption for ALPN demux to quic_packet_backlog_work() on quic_net.work, since quic_crypto_initial_keys_install()/crypto_aead_setkey() must run in process context.
--- net/quic/Makefile | 2 +- net/quic/packet.c | 956 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/packet.h | 130 ++++++ net/quic/protocol.c | 6 + net/quic/protocol.h | 4 + net/quic/socket.c | 114 ++++++ net/quic/socket.h | 12 + 7 files changed, 1223 insertions(+), 1 deletion(-) create mode 100644 net/quic/packet.c create mode 100644 net/quic/packet.h
net/quic/Makefile +1 -1
@@ -6,4 +6,4 @@ obj-$(CONFIG_IP_QUIC) += quic.o quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ - cong.o pnspace.o crypto.o timer.o frame.o + cong.o pnspace.o crypto.o timer.o frame.o packet.o
net/quic/packet.c new file +956 -0
956 lines not on this page · raw message
net/quic/packet.h new file +130 -0
130 lines not on this page · raw message
net/quic/protocol.c +6 -0
@@ -275,6 +275,9 @@ static int __net_init quic_net_init(struct net *net)return err; } +INIT_WORK (&qn->work, quic_packet_backlog_work); +skb_queue_head_init (&qn->backlog_list); +#ifdef CONFIG_PROC_FS err =quic_net_proc_init (net);if (err) {
@@ -293,6 +296,8 @@ static void __net_exit quic_net_exit(struct net *net)#ifdef CONFIG_PROC_FS quic_net_proc_exit (net);#endif +skb_queue_purge (&qn->backlog_list); +cancel_work_sync (&qn->work);quic_crypto_free (&qn->crypto);free_percpu (qn->stat); qn->stat =NULL ;
@@ -342,6 +347,7 @@ static __init int quic_init(void) sysctl_quic_wmem[1 ] =16 *1024 ; sysctl_quic_wmem[2 ] =max (64 *1024 , max_share); +quic_path_init (quic_packet_rcv);quic_crypto_init (); quic_frame_cachep = kmem_cache_create("quic_frame", sizeof(struct quic_frame),
net/quic/protocol.h +4 -0
@@ -50,6 +50,10 @@ struct quic_net {struct proc_dir_entry *proc_net;/* procfs entry for dumping QUIC socket stats */ #endif struct quic_crypto crypto;/* Context for decrypting Initial packets for ALPN */ + +/* Queue of packets deferred for processing in process context */ +struct sk_buff_head backlog_list; +struct work_struct work;/* Work scheduled to drain and process backlog_list */ };struct quic_net *quic_net (struct net *net);
net/quic/socket.c +114 -0
144 lines not on this page · raw message
net/quic/socket.h +12 -0
@@ -20,6 +20,7 @@#include "path.h" #include "cong.h" +#include "packet.h" #include "frame.h" #include "protocol.h"
@@ -77,6 +78,7 @@ struct quic_sock {struct quic_pnspace space[QUIC_PNSPACE_MAX ];struct quic_crypto crypto[QUIC_CRYPTO_MAX ]; +struct quic_packet packet;struct quic_timer timers[QUIC_TIMER_MAX ]; };
@@ -155,6 +157,11 @@ static inline struct quic_crypto *quic_crypto(const struct sock *sk, u8 level)return &quic_sk (sk)->crypto[level]; } +static inline struct quic_packet *quic_packet (const struct sock *sk) +{ +return &quic_sk (sk)->packet; +} +static inline void *quic_timer (const struct sock *sk,u8 type) {return (void *)&quic_sk (sk)->timers[type];
@@ -200,3 +207,8 @@ static inline void quic_set_state(struct sock *sk, int state)inet_sk_set_state (sk, state); sk->sk_state_change (sk); } + +struct sock *quic_listen_sock_lookup (struct sk_buff *skb,union quic_addr *sa,union quic_addr *da, +struct quic_data *alpns); +struct sock *quic_sock_lookup (struct sk_buff *skb,union quic_addr *sa,union quic_addr *da, +struct quic_conn_id *dcid);
Signature · 1 line
2.47.1
Quoted 9 lines · Xin Long
Introduction
============The QUIC protocol, defined in RFC 9000, is a secure, multiplexed transport built on top of UDP. It enables low-latency connection establishment, stream-based communication with flow control, and supports connection migration across network paths, while ensuring confidentiality, integrity, and availability.
[ .. ]>
Quoted 14 lines
- Performance Testing
Performance was benchmarked using iperf [8] over a 100G NIC with using various MTUs and packet sizes:
- QUIC vs. kTLS: UNIT size:1024 size:4096 size:16384 size:65536 Gbits/sec QUIC | kTLS QUIC | kTLS QUIC | kTLS QUIC | kTLS ──────────────────────────────────────────────────────────────────── mtu:1500 2.27 | 3.26 3.02 | 6.97 3.36 | 9.74 3.48 | 10.8 ──────────────────────────────────────────────────────────────────── mtu:9000 3.66 | 3.72 5.87 | 8.92 7.03 | 11.2 8.04 | 11.4
Quoted 10 lines
- QUIC(disable_1rtt_encryption) vs. TCP:
UNIT size:1024 size:4096 size:16384 size:65536
Gbits/sec QUIC | TCP QUIC | TCP QUIC | TCP QUIC | TCP
────────────────────────────────────────────────────────────────────
mtu:1500 3.09 | 4.59 4.46 | 14.2 5.07 | 21.3 5.18 | 23.9
────────────────────────────────────────────────────────────────────
mtu:9000 4.60 | 4.65 8.41 | 14.0 11.3 | 28.9 13.5 | 39.2I have been following the QUIC implementation progress for quite some
while, and always found the performance impact rather frustrating.
At the onset it looks as if you would suffer heavily from the additional
complexity the QUIC protocol imposes up you.
But that would make the use of QUIC rather pointless for most use-cases.
So one wonders if this is not rather a problem of an unsuitable test
case. From my understanding QUIC is geared up for handling a multi-stream connection workload, so one should use an adequate test to simulate a multi-stream connection. Did you use the '-P' option for
iperf when running the tests?
And it might also be an idea to add QUIC support to iperf itself, especially transforming the '-P' option onto QUIC streams looks promising.
Cheers,
Hannes
Signature · 4 lines
Dr. Hannes Reinecke Kernel Storage Architect [email protected] +49 911 74053 688 SUSE Software Solutions GmbH, Frankenstr. 146, 90461 Nürnberg HRB 36809 (AG Nürnberg), GF: I. Totev, A. McDonald, W. Knoblich
Quoted 36 lines · Hannes Reinecke
Quoted 9 lines · Xin Long
Introduction
============The QUIC protocol, defined in RFC 9000, is a secure, multiplexed transport built on top of UDP. It enables low-latency connection establishment, stream-based communication with flow control, and supports connection migration across network paths, while ensuring confidentiality, integrity, and availability.
[ .. ]>
Quoted 14 lines
- Performance Testing
Performance was benchmarked using iperf [8] over a 100G NIC with using various MTUs and packet sizes:
- QUIC vs. kTLS: UNIT size:1024 size:4096 size:16384 size:65536 Gbits/sec QUIC | kTLS QUIC | kTLS QUIC | kTLS QUIC | kTLS ──────────────────────────────────────────────────────────────────── mtu:1500 2.27 | 3.26 3.02 | 6.97 3.36 | 9.74 3.48 | 10.8 ──────────────────────────────────────────────────────────────────── mtu:9000 3.66 | 3.72 5.87 | 8.92 7.03 | 11.2 8.04 | 11.4Quoted 10 lines
- QUIC(disable_1rtt_encryption) vs. TCP: UNIT size:1024 size:4096 size:16384 size:65536 Gbits/sec QUIC | TCP QUIC | TCP QUIC | TCP QUIC | TCP ──────────────────────────────────────────────────────────────────── mtu:1500 3.09 | 4.59 4.46 | 14.2 5.07 | 21.3 5.18 | 23.9 ──────────────────────────────────────────────────────────────────── mtu:9000 4.60 | 4.65 8.41 | 14.0 11.3 | 28.9 13.5 | 39.2
Quoted 6 lines
I have been following the QUIC implementation progress for quite some while, and always found the performance impact rather frustrating. At the onset it looks as if you would suffer heavily from the additional complexity the QUIC protocol imposes up you.
But that would make the use of QUIC rather pointless for most use-cases. So one wonders if this is not rather a problem of an unsuitable test
For fast networks, like the ones I used in my iperf tests, it’s expected that QUIC does not outperform TCP+TLS at the time, The main reason is that TCP has decades of kernel-level optimizations, including features like GSO/GRO and even hardware offload support, which I don't think QUIC can catch up due to its complexity.
That said, QUIC shows advantages in other scenarios web browsing or similar workloads. QUIC can outperform TCP+TLS because of:
- Faster connection setup: QUIC combines the transport and TLS handshakes, avoiding the extra round trips of TCP’s three-way handshake plus TLS negotiation.
- No head-of-line blocking across streams: QUIC multiplexes multiple streams over a single connection, so a single lost packet doesn’t stall unrelated streams, unlike TCP.
Quoted 9 lines
case. From my understanding QUIC is geared up for handling a multi-stream connection workload, so one should use an adequate test to simulate a multi-stream connection. Did you use the '-P' option for iperf when running the tests?
And it might also be an idea to add QUIC support to iperf itself, especially transforming the '-P' option onto QUIC streams looks promising.
Yes, we could add QUIC to iperf, but then testing would need to include packet loss and ensure the CPU isn’t the bottleneck, which moves away from a fast-network environment.
Thanks Hannes for your comment. I’d be glad to hear any further ideas on QUIC performance testing. So far, I haven’t seen a common method or tool adopted for it from the community.
Simon Horman
reviewerRe: [PATCH net-next v3 03/15] quic: provide common utilities and data structures
In reply to Xin Longnet/quic/protocol.c static __init int quic_init(void) · line 339
Quoted 8 lines · Xin Long
index
f79f43f0c17f..b54532916aa2100644net/quic/protocol.c +1
-0@@ -336,6 +336,9 @@ static __init int quic_init(void)if (err) goto err_percpu_counter; +if (quic_hash_tables_init ())
Hi Xin,
If we reach here then the function will return err, which is 0. So it seems that err should be set to a negative error value instead. Perhaps the return value of quic_hash_tables_init.
Flagged by Smatch.
Quoted 14 lines
net/quic/protocol.c +4
-0+ goto err_hash; + err =register_pernet_subsys (&quic_net_ops);if (err) goto err_def_ops;@@ -353,6 +356,8 @@ static __init int quic_init(void) err_protosw:unregister_pernet_subsys (&quic_net_ops); err_def_ops: +quic_hash_tables_destroy (); +err_hash:percpu_counter_destroy (&quic_sockets_allocated); err_percpu_counter:return err;
...
Simon Horman
reviewerRe: [PATCH net-next v3 06/15] quic: add stream management
In reply to Xin LongOn Thu, Sep 18, 2025 at 06:34:55PM -0400, Xin Long wrote:
...
Quoted 1 line
net/quic/stream.c +0
-0
...
Quoted 18 lines
net/quic/stream.c +18
-0+/* Create and register new streams for sending. */ +static struct quic_stream *quic_stream_send_create (struct quic_stream_table *streams, +s64 max_stream_id,u8 is_serv) +{ +struct quic_stream *stream; +s64 stream_id; + + stream_id = streams->send.next_bidi_stream_id; +if (quic_stream_id_uni (max_stream_id)) + stream_id = streams->send.next_uni_stream_id; + +/* rfc9000#section-2.1: A stream ID that is used out of order results in all streams +* of that type with lower-numbered stream IDs also being opened. +*/ +while (stream_id <= max_stream_id) { + stream =kzalloc (sizeof (*stream),GFP_KERNEL ); +if (!stream) +return NULL ;
...
net/quic/stream.c
Quoted 2 lines
net/quic/stream.c +2
-0+ } +return stream;
Hi Xin,
I'm unsure if can happen - actually I doubt it can - but if the loop above iterates zero times then stream will be used uninitialised here.
Likewise in quic_stream_recv_create().
Flagged by Smatch
...
Paolo Abeni
maintainerRe: [PATCH net-next v3 02/15] net: build socket infrastructure for QUIC protocol
In reply to Xin LongQuoted 152 lines · Xin Long
This patch lays the groundwork for QUIC socket support in the kernel. It defines the core structures and protocol hooks needed to create QUIC sockets, without implementing any protocol behavior at this stage.
Basic integration is included to allow building the module via
CONFIG_IP_QUIC=m.This provides the scaffolding necessary for adding actual QUIC socket behavior in follow-up patches.
Signed-off-by Pengtao He <[email protected]>Signed-off-by Xin Long <[email protected]>---
v3:
-Kconfig: add 'default n' forIP_QUIC(reported by Paolo).
-quic_disconnect(): return-EOPNOTSUPP(suggested by Paolo).
- quic_init/destroy_sock(): drop local_bh_disable/enable() calls (noted by Paolo).
- sysctl: addalpn_demuxoption to en/disable ALPN-based demux.
- SNMP: removeSNMP_MIB_SENTINEL, switch tosnmp_get_cpu_field_batch_cnt()to align with latest net-next changes.--- net/Kconfig | 1 + net/Makefile | 1 + net/quic/Kconfig | 36 +++++ net/quic/Makefile | 8 + net/quic/protocol.c | 379 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/protocol.h | 56 +++++++ net/quic/socket.c | 207 ++++++++++++++++++++++++ net/quic/socket.h | 79 +++++++++ 8 files changed, 767 insertions(+) create mode 100644 net/quic/Kconfig create mode 100644 net/quic/Makefile create mode 100644 net/quic/protocol.c create mode 100644 net/quic/protocol.h create mode 100644 net/quic/socket.c create mode 100644 net/quic/socket.hnet/Kconfig +1
-0@@ -249,6 +249,7 @@ source "net/bridge/netfilter/Kconfig" endif # if NETFILTER +source "net/quic/Kconfig" source "net/sctp/Kconfig" source "net/rds/Kconfig" source "net/tipc/Kconfig"net/Makefile +1
-0@@ -42,6 +42,7 @@ obj-$(CONFIG_PHONET) += phonet/ ifneq ($(CONFIG_VLAN_8021Q),) obj-y += 8021q/ endif +obj-$(CONFIG_IP_QUIC) += quic/ obj-$(CONFIG_IP_SCTP) += sctp/ obj-$(CONFIG_RDS) += rds/ obj-$(CONFIG_WIRELESS) += wireless/net/quic/Kconfig new file +36
-0@@ -0,0 +1,36 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# QUIC configuration +# + +menuconfig IP_QUIC + tristate "QUIC: A UDP-Based Multiplexed and Secure Transport (Experimental)" + depends on INET + depends on IPV6 + select CRYPTO + select CRYPTO_HMAC + select CRYPTO_HKDF + select CRYPTO_AES + select CRYPTO_GCM + select CRYPTO_CCM + select CRYPTO_CHACHA20POLY1305 + select NET_UDP_TUNNEL + default n + help + QUIC: A UDP-Based Multiplexed and Secure Transport + + From rfc9000 <https://www.rfc-editor.org/rfc/rfc9000.html>. + + QUIC provides applications with flow-controlled streams for structured + communication, low-latency connection establishment, and network path + migration. QUIC includes security measures that ensure + confidentiality, integrity, and availability in a range of deployment + circumstances. Accompanying documents describe the integration of + TLS for key negotiation, loss detection, and an exemplary congestion + control algorithm. + + To compile this protocol support as a module, choose M here: the + module will be called quic. Debug messages are handled by the + kernel's dynamic debugging framework. + + If in doubt, say N.net/quic/Makefile new file +8
-0@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Makefile for QUIC support code. +# + +obj-$(CONFIG_IP_QUIC) += quic.o + +quic-y := protocol.o socket.onet/quic/protocol.c new file +28
-0@@ -0,0 +1,379 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Initialization/cleanup for QUIC protocol support. +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <net/inet_common.h> +#include <linux/proc_fs.h> +#include <net/protocol.h> +#include <net/rps.h> +#include <net/tls.h> + +#include "socket.h" + +static unsigned int quic_net_id__read_mostly ; + +struct percpu_counter quic_sockets_allocated; + +long sysctl_quic_mem[3 ]; +int sysctl_quic_rmem[3 ]; +int sysctl_quic_wmem[3 ]; +int sysctl_quic_alpn_demux;
net/quic/protocol.c line 38
Quoted 10 lines
net/quic/protocol.c new file +10
-0+ +static int quic_inet_connect (struct socket *sock,struct sockaddr *addr,int addr_len,int flags) +{ +struct sock *sk = sock->sk; +const struct proto *prot; + +if (addr_len < (int )sizeof (addr->sa_family)) +return -EINVAL ; + + prot =READ_ONCE (sk->sk_prot);
Is the above _ONCE() annotation for ADDRFORM's sake? If so it should not be needed (only UDP and TCP sockets are affected).
Quoted 19 lines
net/quic/socket.h new file +13
-0@@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <net/udp_tunnel.h> + +#include "protocol.h"
net/quic/socket.h line 23
Quoted 10 lines
net/quic/socket.h new file +10
-0+ +extern struct proto quic_prot; +extern struct proto quicv6_prot; + +enum quic_state { +QUIC_SS_CLOSED =TCP_CLOSE , +QUIC_SS_LISTENING =TCP_LISTEN , +QUIC_SS_ESTABLISHING =TCP_SYN_RECV , +QUIC_SS_ESTABLISHED =TCP_ESTABLISHED , +};
Any special reason to define protocol-specific states? I guess you could re-use the TCP ones, as other protocols already do.
/P
Paolo Abeni
maintainerRe: [PATCH net-next v3 03/15] quic: provide common utilities and data structures
In reply to Xin LongQuoted 11 lines · Xin Long
This patch provides foundational data structures and utilities used throughout the QUIC stack.
It introduces packet header types, connection ID support, and address handling. Hash tables are added to manage socket lookup and connection ID mapping.
A flexible binary data type is provided, along with helpers for parsing, matching, and memory management. Helpers for encoding and decoding transport parameters and frames are also included.
Quoted 6 lines
Signed-off-by Xin Long <[email protected]>---
v3:
- Rework hashtables: split into two types and size them based ontotalram_pages(), similar to SCTP (reported by Paolo).
- structquic_shash_table: use rwlock instead of spinlock.
Why? rwlock usage should be avoided in networking (as it's unfair, see the many refactors replacing rwlock with rcu/plain spinlock)
[...]
net/quic/common.c line 144
Quoted 12 lines
net/quic/common.c new file +12
-0+ +static int quic_uhash_table_init (struct quic_uhash_table *ht,u32 max_size,int order) +{ +int i, max_order, size; + +/* Same sizing logic as in quic_shash_table_init(). */ + max_order =get_order (max_size *sizeof (struct quic_uhash_head )); + order =min (order, max_order); +do { + ht->hash = (struct quic_uhash_head *) +__get_free_pages (GFP_KERNEL | __GFP_NOWARN, order); + }while (!ht->hash && --order >0 );
You can avoid a little complexity, and see more consistent behaviour, using plain vmalloc() or alloc_large_system_hash() with no fallback.
Quoted 8 lines
net/quic/common.c new file +8
-0+/* rfc9000#section-a.3: DecodePacketNumber() +* +* Reconstructs the full packet number from a truncated one. +*/ +s64 quic_get_num (s64 max_pkt_num,s64 pkt_num,u32 n) +{ +s64 expected = max_pkt_num +1 ; +s64 win =BIT_ULL (n *8 );
net/quic/common.c line 428
Quoted 10 lines
net/quic/common.c new file +10
-0+s64 hwin = win /2 ; +s64 mask = win -1 ; +s64 cand; + + cand = (expected & ~mask) | pkt_num; +if (cand <= expected - hwin && cand < (1ULL <<62 ) - win) +return cand + win; +if (cand > expected + hwin && cand >= win) +return cand - win; +return cand;
The above is a bit obscure to me; replacing magic nubers (62) with macro could help. Some more comments also would do.
/P
Paolo Abeni
maintainerRe: [PATCH net-next v3 04/15] quic: provide family ops for address and protocol
In reply to Xin LongQuoted 8 lines · Xin Long
net/quic/family.c new file +8
-0+static int quic_v4_flow_route (struct sock *sk,union quic_addr *da,union quic_addr *sa, +struct flowi *fl) +{ +struct flowi4 *fl4; +struct rtable *rt; +struct flowi _fl; + +if (__sk_dst_check (sk,0 ))
net/quic/family.c line 76
Quoted 10 lines
net/quic/family.c new file +10
-0+return 1 ; + + fl4 = &_fl.u.ip4; +memset (&_fl,0x00 ,sizeof (_fl)); + fl4->saddr = sa->v4.sin_addr.s_addr; + fl4->fl4_sport = sa->v4.sin_port; + fl4->daddr = da->v4.sin_addr.s_addr; + fl4->fl4_dport = da->v4.sin_port; + fl4->flowi4_proto =IPPROTO_UDP ; + fl4->flowi4_oif = sk->sk_bound_dev_if;
Why you need a local variable? I think you could use the 'fl' argument directly.
Quoted 27 lines
net/quic/family.c new file +27
-0+ + fl4->flowi4_scope =ip_sock_rt_scope (sk); + fl4->flowi4_dscp =inet_sk_dscp (inet_sk (sk)); + + rt =ip_route_output_key (sock_net (sk), fl4); +if (IS_ERR (rt)) +return PTR_ERR (rt); + +if (!sa->v4.sin_family) { + sa->v4.sin_family =AF_INET ; + sa->v4.sin_addr.s_addr = fl4->saddr; + } +sk_setup_caps (sk, &rt->dst); +memcpy (fl, &_fl,sizeof (_fl)); +return 0 ; +} + +static int quic_v6_flow_route (struct sock *sk,union quic_addr *da,union quic_addr *sa, +struct flowi *fl) +{ +struct ipv6_pinfo *np =inet6_sk (sk); +struct ip6_flowlabel *flowlabel; +struct dst_entry *dst; +struct flowi6 *fl6; +struct flowi _fl; + +if (__sk_dst_check (sk, np->dst_cookie))
net/quic/family.c line 113
Quoted 10 lines
net/quic/family.c new file +10
-0+return 1 ; + + fl6 = &_fl.u.ip6; +memset (&_fl,0x0 ,sizeof (_fl)); + fl6->saddr = sa->v6.sin6_addr; + fl6->fl6_sport = sa->v6.sin6_port; + fl6->daddr = da->v6.sin6_addr; + fl6->fl6_dport = da->v6.sin6_port; + fl6->flowi6_proto =IPPROTO_UDP ; + fl6->flowi6_oif = sk->sk_bound_dev_if;
Same here.
Quoted 417 lines
net/quic/family.c new file +417
-0+ +if (inet6_test_bit (SNDFLOW , sk)) { + fl6->flowlabel = (da->v6.sin6_flowinfo &IPV6_FLOWINFO_MASK ); +if (fl6->flowlabel &IPV6_FLOWLABEL_MASK ) { + flowlabel =fl6_sock_lookup (sk, fl6->flowlabel); +if (IS_ERR (flowlabel)) +return -EINVAL ; +fl6_sock_release (flowlabel); + } + } + + dst =ip6_dst_lookup_flow (sock_net (sk), sk, fl6,NULL ); +if (IS_ERR (dst)) +return PTR_ERR (dst); + +if (!sa->v6.sin6_family) { + sa->v6.sin6_family =AF_INET6 ; + sa->v6.sin6_addr = fl6->saddr; + } +ip6_dst_store (sk, dst,NULL ,NULL ); +memcpy (fl, &_fl,sizeof (_fl)); +return 0 ; +} + +static void quic_v4_lower_xmit (struct sock *sk,struct sk_buff *skb,struct flowi *fl) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u8 tos = (inet_sk (sk)->tos | cb->ecn), ttl; +struct flowi4 *fl4 = &fl->u.ip4; +struct dst_entry *dst; +__be16 df =0 ; + +pr_debug ("%s: skb: %p, len: %d, num: %llu, %pI4:%d -> %pI4:%d\n" , __func__, + skb, skb->len, cb->number, &fl4->saddr,ntohs (fl4->fl4_sport), + &fl4->daddr,ntohs (fl4->fl4_dport)); + + dst =sk_dst_get (sk); +if (!dst) { +kfree_skb (skb); +return ; + } +if (ip_dont_fragment (sk, dst) && !skb->ignore_df) + df =htons (IP_DF ); + + ttl = (u8 )ip4_dst_hoplimit (dst); +udp_tunnel_xmit_skb ((struct rtable *)dst, sk, skb, fl4->saddr, fl4->daddr, + tos, ttl, df, fl4->fl4_sport, fl4->fl4_dport, false, false,0 ); +} + +static void quic_v6_lower_xmit (struct sock *sk,struct sk_buff *skb,struct flowi *fl) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u8 tc = (inet6_sk (sk)->tclass | cb->ecn), ttl; +struct flowi6 *fl6 = &fl->u.ip6; +struct dst_entry *dst; +__be32 label; + +pr_debug ("%s: skb: %p, len: %d, num: %llu, %pI6c:%d -> %pI6c:%d\n" , __func__, + skb, skb->len, cb->number, &fl6->saddr,ntohs (fl6->fl6_sport), + &fl6->daddr,ntohs (fl6->fl6_dport)); + + dst =sk_dst_get (sk); +if (!dst) { +kfree_skb (skb); +return ; + } + + ttl = (u8 )ip6_dst_hoplimit (dst); + label =ip6_make_flowlabel (sock_net (sk), skb, fl6->flowlabel, true, fl6); +udp_tunnel6_xmit_skb (dst, sk, skb,NULL , &fl6->saddr, &fl6->daddr, tc, + ttl, label, fl6->fl6_sport, fl6->fl6_dport, false,0 ); +} + +static void quic_v4_get_msg_addrs (struct sk_buff *skb,union quic_addr *da,union quic_addr *sa) +{ +struct udphdr *uh =quic_udphdr (skb); + + sa->v4.sin_family =AF_INET ; + sa->v4.sin_port = uh->source; + sa->v4.sin_addr.s_addr =ip_hdr (skb)->saddr; + + da->v4.sin_family =AF_INET ; + da->v4.sin_port = uh->dest; + da->v4.sin_addr.s_addr =ip_hdr (skb)->daddr; +} + +static void quic_v6_get_msg_addrs (struct sk_buff *skb,union quic_addr *da,union quic_addr *sa) +{ +struct udphdr *uh =quic_udphdr (skb); + + sa->v6.sin6_family =AF_INET6 ; + sa->v6.sin6_port = uh->source; + sa->v6.sin6_addr =ipv6_hdr (skb)->saddr; + + da->v6.sin6_family =AF_INET6 ; + da->v6.sin6_port = uh->dest; + da->v6.sin6_addr =ipv6_hdr (skb)->daddr; +} + +static int quic_v4_get_mtu_info (struct sk_buff *skb,u32 *info) +{ +struct icmphdr *hdr; + + hdr = (struct icmphdr *)(skb_network_header (skb) -sizeof (struct icmphdr )); +if (hdr->type ==ICMP_DEST_UNREACH && hdr->code ==ICMP_FRAG_NEEDED ) { + *info =ntohs (hdr->un.frag.mtu); +return 0 ; + } + +/* Defer other types' processing to UDP error handler. */ +return 1 ; +} + +static int quic_v6_get_mtu_info (struct sk_buff *skb,u32 *info) +{ +struct icmp6hdr *hdr; + + hdr = (struct icmp6hdr *)(skb_network_header (skb) -sizeof (struct icmp6hdr )); +if (hdr->icmp6_type ==ICMPV6_PKT_TOOBIG ) { + *info =ntohl (hdr->icmp6_mtu); +return 0 ; + } + +/* Defer other types' processing to UDP error handler. */ +return 1 ; +} + +static u8 quic_v4_get_msg_ecn (struct sk_buff *skb) +{ +return (ip_hdr (skb)->tos &INET_ECN_MASK ); +} + +static u8 quic_v6_get_msg_ecn (struct sk_buff *skb) +{ +return (ipv6_get_dsfield (ipv6_hdr (skb)) &INET_ECN_MASK ); +} + +static int quic_v4_get_user_addr (struct sock *sk,union quic_addr *a,struct sockaddr *addr, +int addr_len) +{ +u32 len =sizeof (struct sockaddr_in ); + +if (addr_len < len || addr->sa_family !=AF_INET ) +return 1 ; +if (ipv4_is_multicast (quic_addr (addr)->v4.sin_addr.s_addr)) +return 1 ; +memcpy (a, addr, len); +return 0 ; +} + +static int quic_v6_get_user_addr (struct sock *sk,union quic_addr *a,struct sockaddr *addr, +int addr_len) +{ +u32 len =sizeof (struct sockaddr_in ); +int type; + +if (addr_len < len) +return 1 ; + +if (addr->sa_family !=AF_INET6 ) { +if (ipv6_only_sock (sk)) +return 1 ; +return quic_v4_get_user_addr (sk, a, addr, addr_len); + } + + len =sizeof (struct sockaddr_in6 ); +if (addr_len < len) +return 1 ; + type =ipv6_addr_type (&quic_addr (addr)->v6.sin6_addr); +if (type !=IPV6_ADDR_ANY && !(type &IPV6_ADDR_UNICAST )) +return 1 ; +memcpy (a, addr, len); +return 0 ; +} + +static void quic_v4_get_pref_addr (struct sock *sk,union quic_addr *addr,u8 **pp,u32 *plen) +{ +u8 *p = *pp; + +memcpy (&addr->v4.sin_addr, p,QUIC_ADDR4_LEN ); + p +=QUIC_ADDR4_LEN ; +memcpy (&addr->v4.sin_port, p,QUIC_PORT_LEN ); + p +=QUIC_PORT_LEN ; + addr->v4.sin_family =AF_INET ; +/* Skip over IPv6 address and port, not used for AF_INET sockets. */ + p +=QUIC_ADDR6_LEN ; + p +=QUIC_PORT_LEN ; + +if (!addr->v4.sin_port ||quic_v4_is_any_addr (addr) || +ipv4_is_multicast (addr->v4.sin_addr.s_addr)) +memset (addr,0 ,sizeof (*addr)); + *plen -= (p - *pp); + *pp = p; +} + +static void quic_v6_get_pref_addr (struct sock *sk,union quic_addr *addr,u8 **pp,u32 *plen) +{ +u8 *p = *pp; +int type; + +/* Skip over IPv4 address and port. */ + p +=QUIC_ADDR4_LEN ; + p +=QUIC_PORT_LEN ; +/* Try to use IPv6 address and port first. */ +memcpy (&addr->v6.sin6_addr, p,QUIC_ADDR6_LEN ); + p +=QUIC_ADDR6_LEN ; +memcpy (&addr->v6.sin6_port, p,QUIC_PORT_LEN ); + p +=QUIC_PORT_LEN ; + addr->v6.sin6_family =AF_INET6 ; + + type =ipv6_addr_type (&addr->v6.sin6_addr); +if (!addr->v6.sin6_port || !(type &IPV6_ADDR_UNICAST )) { +memset (addr,0 ,sizeof (*addr)); +if (ipv6_only_sock (sk)) + goto out; +/* Fallback to IPv4 if IPv6 address is not usable. */ +return quic_v4_get_pref_addr (sk, addr, pp, plen); + } +out: + *plen -= (p - *pp); + *pp = p; +} + +static void quic_v4_set_pref_addr (struct sock *sk,u8 *p,union quic_addr *addr) +{ +memcpy (p, &addr->v4.sin_addr,QUIC_ADDR4_LEN ); + p +=QUIC_ADDR4_LEN ; +memcpy (p, &addr->v4.sin_port,QUIC_PORT_LEN ); + p +=QUIC_PORT_LEN ; +memset (p,0 ,QUIC_ADDR6_LEN ); + p +=QUIC_ADDR6_LEN ; +memset (p,0 ,QUIC_PORT_LEN ); +} + +static void quic_v6_set_pref_addr (struct sock *sk,u8 *p,union quic_addr *addr) +{ +if (addr->sa.sa_family ==AF_INET ) +return quic_v4_set_pref_addr (sk, p, addr); + +memset (p,0 ,QUIC_ADDR4_LEN ); + p +=QUIC_ADDR4_LEN ; +memset (p,0 ,QUIC_PORT_LEN ); + p +=QUIC_PORT_LEN ; +memcpy (p, &addr->v6.sin6_addr,QUIC_ADDR6_LEN ); + p +=QUIC_ADDR6_LEN ; +memcpy (p, &addr->v6.sin6_port,QUIC_PORT_LEN ); +} + +static bool quic_v4_cmp_sk_addr (struct sock *sk,union quic_addr *a,union quic_addr *addr) +{ +if (a->v4.sin_port != addr->v4.sin_port) +return false; +if (a->v4.sin_family != addr->v4.sin_family) +return false; +if (a->v4.sin_addr.s_addr ==htonl (INADDR_ANY ) || + addr->v4.sin_addr.s_addr ==htonl (INADDR_ANY )) +return true; +return a->v4.sin_addr.s_addr == addr->v4.sin_addr.s_addr; +} + +static bool quic_v6_cmp_sk_addr (struct sock *sk,union quic_addr *a,union quic_addr *addr) +{ +if (a->v4.sin_port != addr->v4.sin_port) +return false; + +if (a->sa.sa_family ==AF_INET && addr->sa.sa_family ==AF_INET ) { +if (a->v4.sin_addr.s_addr ==htonl (INADDR_ANY ) || + addr->v4.sin_addr.s_addr ==htonl (INADDR_ANY )) +return true; +return a->v4.sin_addr.s_addr == addr->v4.sin_addr.s_addr; + } + +if (a->sa.sa_family != addr->sa.sa_family) { +if (ipv6_only_sock (sk)) +return false; +if (a->sa.sa_family ==AF_INET6 &&ipv6_addr_any (&a->v6.sin6_addr)) +return true; +if (a->sa.sa_family ==AF_INET && addr->sa.sa_family ==AF_INET6 && +ipv6_addr_v4mapped (&addr->v6.sin6_addr) && + addr->v6.sin6_addr.s6_addr32[3 ] == a->v4.sin_addr.s_addr) +return true; +if (addr->sa.sa_family ==AF_INET && a->sa.sa_family ==AF_INET6 && +ipv6_addr_v4mapped (&a->v6.sin6_addr) && + a->v6.sin6_addr.s6_addr32[3 ] == addr->v4.sin_addr.s_addr) +return true; +return false; + } + +if (ipv6_addr_any (&a->v6.sin6_addr) ||ipv6_addr_any (&addr->v6.sin6_addr)) +return true; +return ipv6_addr_equal (&a->v6.sin6_addr, &addr->v6.sin6_addr); +} + +static int quic_v4_get_sk_addr (struct socket *sock,struct sockaddr *uaddr,int peer) +{ +return inet_getname (sock, uaddr, peer); +} + +static int quic_v6_get_sk_addr (struct socket *sock,struct sockaddr *uaddr,int peer) +{ +union quic_addr *a =quic_addr (uaddr); +int ret; + + ret =inet6_getname (sock, uaddr, peer); +if (ret <0 ) +return ret; + +if (a->sa.sa_family ==AF_INET6 &&ipv6_addr_v4mapped (&a->v6.sin6_addr)) { + a->v4.sin_family =AF_INET ; + a->v4.sin_port = a->v6.sin6_port; + a->v4.sin_addr.s_addr = a->v6.sin6_addr.s6_addr32[3 ]; + } + +if (a->sa.sa_family ==AF_INET ) { +memset (a->v4.sin_zero,0 ,sizeof (a->v4.sin_zero)); +return sizeof (struct sockaddr_in ); + } +return sizeof (struct sockaddr_in6 ); +} + +static void quic_v4_set_sk_addr (struct sock *sk,union quic_addr *a,bool src) +{ +if (src) { +inet_sk (sk)->inet_sport = a->v4.sin_port; +inet_sk (sk)->inet_saddr = a->v4.sin_addr.s_addr; + }else { +inet_sk (sk)->inet_dport = a->v4.sin_port; +inet_sk (sk)->inet_daddr = a->v4.sin_addr.s_addr; + } +} + +static void quic_v6_copy_sk_addr (struct in6_addr *skaddr,union quic_addr *a) +{ +if (a->sa.sa_family ==AF_INET ) { + skaddr->s6_addr32[0 ] =0 ; + skaddr->s6_addr32[1 ] =0 ; + skaddr->s6_addr32[2 ] =htonl (0x0000ffff ); + skaddr->s6_addr32[3 ] = a->v4.sin_addr.s_addr; + }else { + *skaddr = a->v6.sin6_addr; + } +} + +static void quic_v6_set_sk_addr (struct sock *sk,union quic_addr *a,bool src) +{ +if (src) { +inet_sk (sk)->inet_sport = a->v4.sin_port; +quic_v6_copy_sk_addr (&sk->sk_v6_rcv_saddr, a); + }else { +inet_sk (sk)->inet_dport = a->v4.sin_port; +quic_v6_copy_sk_addr (&sk->sk_v6_daddr, a); + } +} + +static void quic_v4_set_sk_ecn (struct sock *sk,u8 ecn) +{ +inet_sk (sk)->tos = ((inet_sk (sk)->tos & ~INET_ECN_MASK ) | ecn); +} + +static void quic_v6_set_sk_ecn (struct sock *sk,u8 ecn) +{ +quic_v4_set_sk_ecn (sk, ecn); +inet6_sk (sk)->tclass = ((inet6_sk (sk)->tclass & ~INET_ECN_MASK ) | ecn); +} + +#define quic_af_ipv4 (a) ((a)->sa.sa_family == AF_INET) + +u32 quic_encap_len (union quic_addr *a) +{ +return (quic_af_ipv4 (a) ?sizeof (struct iphdr ) :sizeof (struct ipv6hdr )) + +sizeof (struct udphdr ); +} + +int quic_is_any_addr (union quic_addr *a) +{ +return quic_af_ipv4 (a) ?quic_v4_is_any_addr (a) :quic_v6_is_any_addr (a); +} + +void quic_seq_dump_addr (struct seq_file *seq,union quic_addr *addr) +{ +quic_af_ipv4 (addr) ?quic_v4_seq_dump_addr (seq, addr) :quic_v6_seq_dump_addr (seq, addr); +} + +void quic_udp_conf_init (struct sock *sk,struct udp_port_cfg *conf,union quic_addr *a) +{ +quic_af_ipv4 (a) ?quic_v4_udp_conf_init (sk, conf, a) :quic_v6_udp_conf_init (sk, conf, a); +} + +int quic_flow_route (struct sock *sk,union quic_addr *da,union quic_addr *sa,struct flowi *fl) +{ +return quic_af_ipv4 (da) ?quic_v4_flow_route (sk, da, sa, fl) + :quic_v6_flow_route (sk, da, sa, fl); +} + +void quic_lower_xmit (struct sock *sk,struct sk_buff *skb,union quic_addr *da,struct flowi *fl) +{ +quic_af_ipv4 (da) ?quic_v4_lower_xmit (sk, skb, fl) :quic_v6_lower_xmit (sk, skb, fl); +} + +#define quic_skb_ipv4 (skb) (ip_hdr(skb)->version == 4) + +void quic_get_msg_addrs (struct sk_buff *skb,union quic_addr *da,union quic_addr *sa) +{ +memset (sa,0 ,sizeof (*sa)); +memset (da,0 ,sizeof (*da)); +quic_skb_ipv4 (skb) ?quic_v4_get_msg_addrs (skb, da, sa) + :quic_v6_get_msg_addrs (skb, da, sa); +} + +int quic_get_mtu_info (struct sk_buff *skb,u32 *info) +{ +return quic_skb_ipv4 (skb) ?quic_v4_get_mtu_info (skb, info) + :quic_v6_get_mtu_info (skb, info); +} + +u8 quic_get_msg_ecn (struct sk_buff *skb) +{
net/quic/family.c line 540
Quoted 10 lines
net/quic/family.c new file +10
-0+return quic_skb_ipv4 (skb) ?quic_v4_get_msg_ecn (skb) :quic_v6_get_msg_ecn (skb); +} + +#define quic_pf_ipv4 (sk) ((sk)->sk_family == PF_INET) + +int quic_get_user_addr (struct sock *sk,union quic_addr *a,struct sockaddr *addr,int addr_len) +{ +memset (a,0 ,sizeof (*a)); +return quic_pf_ipv4 (sk) ?quic_v4_get_user_addr (sk, a, addr, addr_len) + :quic_v6_get_user_addr (sk, a, addr, addr_len);
Minor nit: I think the most idiomatic way to express the abvoe is:
return quic_pf_ipv4(sk) ? quic_v4_get_user_addr(sk, a, addr, addr_len) :
quic_v6_get_user_addr(sk, a, addr, addr_len);
(other cases below)
/P
Paolo Abeni
maintainerRe: [PATCH net-next v3 06/15] quic: add stream management
In reply to Xin LongQuoted 8 lines · Xin Long
net/quic/stream.c new file +8
-0+/* Create and register new streams for sending. */ +static struct quic_stream *quic_stream_send_create (struct quic_stream_table *streams, +s64 max_stream_id,u8 is_serv) +{ +struct quic_stream *stream; +s64 stream_id; + + stream_id = streams->send.next_bidi_stream_id;
net/quic/stream.c line 88
Quoted 10 lines
net/quic/stream.c new file +10
-0+if (quic_stream_id_uni (max_stream_id)) + stream_id = streams->send.next_uni_stream_id; + +/* rfc9000#section-2.1: A stream ID that is used out of order results in all streams +* of that type with lower-numbered stream IDs also being opened. +*/ +while (stream_id <= max_stream_id) { + stream =kzalloc (sizeof (*stream),GFP_KERNEL ); +if (!stream) +return NULL ;
How many streams and connections ID do you foresee per socket? Could such number grow significantly (possibly under misuse/attack)? If so you you likely use GFP_KERNEL_ACCOUNT here (and in conn_id allocation).
/P
Quoted 563 lines
net/quic/stream.c new file +421
-0+ + stream->id = stream_id; +if (quic_stream_id_uni (stream_id)) { + stream->send.max_bytes = streams->send.max_stream_data_uni; + +if (streams->send.next_uni_stream_id < stream_id +QUIC_STREAM_ID_STEP ) + streams->send.next_uni_stream_id = stream_id +QUIC_STREAM_ID_STEP ; + streams->send.streams_uni++; + +quic_stream_add (streams, stream); + stream_id +=QUIC_STREAM_ID_STEP ; +continue ; + } + +if (streams->send.next_bidi_stream_id < stream_id +QUIC_STREAM_ID_STEP ) + streams->send.next_bidi_stream_id = stream_id +QUIC_STREAM_ID_STEP ; + streams->send.streams_bidi++; + +if (quic_stream_id_local (stream_id, is_serv)) { + stream->send.max_bytes = streams->send.max_stream_data_bidi_remote; + stream->recv.max_bytes = streams->recv.max_stream_data_bidi_local; + }else { + stream->send.max_bytes = streams->send.max_stream_data_bidi_local; + stream->recv.max_bytes = streams->recv.max_stream_data_bidi_remote; + } + stream->recv.window = stream->recv.max_bytes; + +quic_stream_add (streams, stream); + stream_id +=QUIC_STREAM_ID_STEP ; + } +return stream; +} + +/* Create and register new streams for receiving. */ +static struct quic_stream *quic_stream_recv_create (struct quic_stream_table *streams, +s64 max_stream_id,u8 is_serv) +{ +struct quic_stream *stream; +s64 stream_id; + + stream_id = streams->recv.next_bidi_stream_id; +if (quic_stream_id_uni (max_stream_id)) + stream_id = streams->recv.next_uni_stream_id; + +/* rfc9000#section-2.1: A stream ID that is used out of order results in all streams +* of that type with lower-numbered stream IDs also being opened. +*/ +while (stream_id <= max_stream_id) { + stream =kzalloc (sizeof (*stream),GFP_ATOMIC ); +if (!stream) +return NULL ; + + stream->id = stream_id; +if (quic_stream_id_uni (stream_id)) { + stream->recv.window = streams->recv.max_stream_data_uni; + stream->recv.max_bytes = stream->recv.window; + +if (streams->recv.next_uni_stream_id < stream_id +QUIC_STREAM_ID_STEP ) + streams->recv.next_uni_stream_id = stream_id +QUIC_STREAM_ID_STEP ; + streams->recv.streams_uni++; + +quic_stream_add (streams, stream); + stream_id +=QUIC_STREAM_ID_STEP ; +continue ; + } + +if (streams->recv.next_bidi_stream_id < stream_id +QUIC_STREAM_ID_STEP ) + streams->recv.next_bidi_stream_id = stream_id +QUIC_STREAM_ID_STEP ; + streams->recv.streams_bidi++; + +if (quic_stream_id_local (stream_id, is_serv)) { + stream->send.max_bytes = streams->send.max_stream_data_bidi_remote; + stream->recv.max_bytes = streams->recv.max_stream_data_bidi_local; + }else { + stream->send.max_bytes = streams->send.max_stream_data_bidi_local; + stream->recv.max_bytes = streams->recv.max_stream_data_bidi_remote; + } + stream->recv.window = stream->recv.max_bytes; + +quic_stream_add (streams, stream); + stream_id +=QUIC_STREAM_ID_STEP ; + } +return stream; +} + +/* Check if a send or receive stream ID is already closed. */ +static bool quic_stream_id_closed (struct quic_stream_table *streams,s64 stream_id,bool send) +{ +if (quic_stream_id_uni (stream_id)) { +if (send) +return stream_id < streams->send.next_uni_stream_id; +return stream_id < streams->recv.next_uni_stream_id; + } +if (send) +return stream_id < streams->send.next_bidi_stream_id; +return stream_id < streams->recv.next_bidi_stream_id; +} + +/* Check if a stream ID would exceed local (recv) or peer (send) limits. */ +bool quic_stream_id_exceeds (struct quic_stream_table *streams,s64 stream_id,bool send) +{ +u64 nstreams; + +if (!send) { +if (quic_stream_id_uni (stream_id)) +return stream_id > streams->recv.max_uni_stream_id; +return stream_id > streams->recv.max_bidi_stream_id; + } + +if (quic_stream_id_uni (stream_id)) { +if (stream_id > streams->send.max_uni_stream_id) +return true; + stream_id -= streams->send.next_uni_stream_id; + nstreams =quic_stream_id_to_streams (stream_id); +return nstreams + streams->send.streams_uni > streams->send.max_streams_uni; + } + +if (stream_id > streams->send.max_bidi_stream_id) +return true; + stream_id -= streams->send.next_bidi_stream_id; + nstreams =quic_stream_id_to_streams (stream_id); +return nstreams + streams->send.streams_bidi > streams->send.max_streams_bidi; +} + +/* Get or create a send stream by ID. */ +struct quic_stream *quic_stream_send_get (struct quic_stream_table *streams,s64 stream_id, +u32 flags,bool is_serv) +{ +struct quic_stream *stream; + +if (!quic_stream_id_valid (stream_id, is_serv, true)) +return ERR_PTR (-EINVAL ); + + stream =quic_stream_find (streams, stream_id); +if (stream) { +if ((flags &MSG_STREAM_NEW ) && + stream->send.state !=QUIC_STREAM_SEND_STATE_READY ) +return ERR_PTR (-EINVAL ); +return stream; + } + +if (quic_stream_id_closed (streams, stream_id, true)) +return ERR_PTR (-ENOSTR ); + +if (!(flags &MSG_STREAM_NEW )) +return ERR_PTR (-EINVAL ); + +if (quic_stream_id_exceeds (streams, stream_id, true)) +return ERR_PTR (-EAGAIN ); + + stream =quic_stream_send_create (streams, stream_id, is_serv); +if (!stream) +return ERR_PTR (-ENOSTR ); + streams->send.active_stream_id = stream_id; +return stream; +} + +/* Get or create a receive stream by ID. */ +struct quic_stream *quic_stream_recv_get (struct quic_stream_table *streams,s64 stream_id, +bool is_serv) +{ +struct quic_stream *stream; + +if (!quic_stream_id_valid (stream_id, is_serv, false)) +return ERR_PTR (-EINVAL ); + + stream =quic_stream_find (streams, stream_id); +if (stream) +return stream; + +if (quic_stream_id_local (stream_id, is_serv)) { +if (quic_stream_id_closed (streams, stream_id, true)) +return ERR_PTR (-ENOSTR ); +return ERR_PTR (-EINVAL ); + } + +if (quic_stream_id_closed (streams, stream_id, false)) +return ERR_PTR (-ENOSTR ); + +if (quic_stream_id_exceeds (streams, stream_id, false)) +return ERR_PTR (-EAGAIN ); + + stream =quic_stream_recv_create (streams, stream_id, is_serv); +if (!stream) +return ERR_PTR (-ENOSTR ); +if (quic_stream_id_valid (stream_id, is_serv, true)) + streams->send.active_stream_id = stream_id; +return stream; +} + +/* Release or clean up a send stream. This function updates stream counters and state when +* a send stream has either successfully sent all data or has been reset. +*/ +void quic_stream_send_put (struct quic_stream_table *streams,struct quic_stream *stream, +bool is_serv) +{ +if (quic_stream_id_uni (stream->id)) { +/* For unidirectional streams, decrement uni count and delete immediately. */ + streams->send.streams_uni--; +quic_stream_delete (stream); +return ; + } + +/* For bidi streams, only proceed if receive side is in a final state. */ +if (stream->recv.state !=QUIC_STREAM_RECV_STATE_RECVD && + stream->recv.state !=QUIC_STREAM_RECV_STATE_READ && + stream->recv.state !=QUIC_STREAM_RECV_STATE_RESET_RECVD ) +return ; + +if (quic_stream_id_local (stream->id, is_serv)) { +/* Local-initiated stream: mark send done and decrement send.bidi count. */ +if (!stream->send.done) { + stream->send.done =1 ; + streams->send.streams_bidi--; + } + goto out; + } +/* Remote-initiated stream: mark recv done and decrement recv bidi count. */ +if (!stream->recv.done) { + stream->recv.done =1 ; + streams->recv.streams_bidi--; + streams->recv.bidi_pending =1 ; + } +out: +/* Delete stream if fully read or reset. */ +if (stream->recv.state !=QUIC_STREAM_RECV_STATE_RECVD ) +quic_stream_delete (stream); +} + +/* Release or clean up a receive stream. This function updates stream counters and state when +* the receive side has either consumed all data or has been reset. +*/ +void quic_stream_recv_put (struct quic_stream_table *streams,struct quic_stream *stream, +bool is_serv) +{ +if (quic_stream_id_uni (stream->id)) { +/* For uni streams, decrement uni count and mark done. */ +if (!stream->recv.done) { + stream->recv.done =1 ; + streams->recv.streams_uni--; + streams->recv.uni_pending =1 ; + } + goto out; + } + +/* For bidi streams, only proceed if send side is in a final state. */ +if (stream->send.state !=QUIC_STREAM_SEND_STATE_RECVD && + stream->send.state !=QUIC_STREAM_SEND_STATE_RESET_RECVD ) +return ; + +if (quic_stream_id_local (stream->id, is_serv)) { +/* Local-initiated stream: mark send done and decrement send.bidi count. */ +if (!stream->send.done) { + stream->send.done =1 ; + streams->send.streams_bidi--; + } + goto out; + } +/* Remote-initiated stream: mark recv done and decrement recv bidi count. */ +if (!stream->recv.done) { + stream->recv.done =1 ; + streams->recv.streams_bidi--; + streams->recv.bidi_pending =1 ; + } +out: +/* Delete stream if fully read or reset. */ +if (stream->recv.state !=QUIC_STREAM_RECV_STATE_RECVD ) +quic_stream_delete (stream); +} + +/* Updates the maximum allowed incoming stream IDs if any streams were recently closed. +* Recalculates the max_uni and max_bidi stream ID limits based on the number of open +* streams and whether any were marked for deletion. +* +* Returns true if either max_uni or max_bidi was updated, indicating that a +* MAX_STREAMS_UNI or MAX_STREAMS_BIDI frame should be sent to the peer. +*/ +bool quic_stream_max_streams_update (struct quic_stream_table *streams,s64 *max_uni,s64 *max_bidi) +{ +if (streams->recv.uni_pending) { + streams->recv.max_uni_stream_id = + streams->recv.next_uni_stream_id -QUIC_STREAM_ID_STEP + + ((streams->recv.max_streams_uni - streams->recv.streams_uni) << +QUIC_STREAM_TYPE_BITS ); + *max_uni =quic_stream_id_to_streams (streams->recv.max_uni_stream_id); + streams->recv.uni_pending =0 ; + } +if (streams->recv.bidi_pending) { + streams->recv.max_bidi_stream_id = + streams->recv.next_bidi_stream_id -QUIC_STREAM_ID_STEP + + ((streams->recv.max_streams_bidi - streams->recv.streams_bidi) << +QUIC_STREAM_TYPE_BITS ); + *max_bidi =quic_stream_id_to_streams (streams->recv.max_bidi_stream_id); + streams->recv.bidi_pending =0 ; + } + +return *max_uni || *max_bidi; +} + +#define QUIC_STREAM_HT_SIZE 64 + +int quic_stream_init (struct quic_stream_table *streams) +{ +struct quic_shash_table *ht = &streams->ht; +int i, size =QUIC_STREAM_HT_SIZE ; +struct quic_shash_head *head; + + head =kmalloc_array (size,sizeof (*head),GFP_KERNEL ); +if (!head) +return -ENOMEM ; +for (i =0 ; i < size; i++) +INIT_HLIST_HEAD (&head[i].head); + ht->size = size; + ht->hash = head; +return 0 ; +} + +void quic_stream_free (struct quic_stream_table *streams) +{ +struct quic_shash_table *ht = &streams->ht; +struct quic_shash_head *head; +struct quic_stream *stream; +struct hlist_node *tmp; +int i; + +for (i =0 ; i < ht->size; i++) { + head = &ht->hash[i]; +hlist_for_each_entry_safe (stream, tmp, &head->head, node) +quic_stream_delete (stream); + } +kfree (ht->hash); +} + +/* Populate transport parameters from stream hash table. */ +void quic_stream_get_param (struct quic_stream_table *streams,struct quic_transport_param *p, +bool is_serv) +{ +if (p->remote) { + p->max_stream_data_bidi_remote = streams->send.max_stream_data_bidi_remote; + p->max_stream_data_bidi_local = streams->send.max_stream_data_bidi_local; + p->max_stream_data_uni = streams->send.max_stream_data_uni; + p->max_streams_bidi = streams->send.max_streams_bidi; + p->max_streams_uni = streams->send.max_streams_uni; +return ; + } + + p->max_stream_data_bidi_remote = streams->recv.max_stream_data_bidi_remote; + p->max_stream_data_bidi_local = streams->recv.max_stream_data_bidi_local; + p->max_stream_data_uni = streams->recv.max_stream_data_uni; + p->max_streams_bidi = streams->recv.max_streams_bidi; + p->max_streams_uni = streams->recv.max_streams_uni; +} + +/* Configure stream hashtable from transport parameters. */ +void quic_stream_set_param (struct quic_stream_table *streams,struct quic_transport_param *p, +bool is_serv) +{ +u8 type; + +if (p->remote) { + streams->send.max_stream_data_bidi_local = p->max_stream_data_bidi_local; + streams->send.max_stream_data_bidi_remote = p->max_stream_data_bidi_remote; + streams->send.max_stream_data_uni = p->max_stream_data_uni; + streams->send.max_streams_bidi = p->max_streams_bidi; + streams->send.max_streams_uni = p->max_streams_uni; + streams->send.active_stream_id =-1 ; + +if (is_serv) { + type =QUIC_STREAM_TYPE_SERVER_BIDI ; + streams->send.max_bidi_stream_id = +quic_stream_streams_to_id (p->max_streams_bidi, type); + streams->send.next_bidi_stream_id = type; + + type =QUIC_STREAM_TYPE_SERVER_UNI ; + streams->send.max_uni_stream_id = +quic_stream_streams_to_id (p->max_streams_uni, type); + streams->send.next_uni_stream_id = type; +return ; + } + + type =QUIC_STREAM_TYPE_CLIENT_BIDI ; + streams->send.max_bidi_stream_id = +quic_stream_streams_to_id (p->max_streams_bidi, type); + streams->send.next_bidi_stream_id = type; + + type =QUIC_STREAM_TYPE_CLIENT_UNI ; + streams->send.max_uni_stream_id = +quic_stream_streams_to_id (p->max_streams_uni, type); + streams->send.next_uni_stream_id = type; +return ; + } + + streams->recv.max_stream_data_bidi_local = p->max_stream_data_bidi_local; + streams->recv.max_stream_data_bidi_remote = p->max_stream_data_bidi_remote; + streams->recv.max_stream_data_uni = p->max_stream_data_uni; + streams->recv.max_streams_bidi = p->max_streams_bidi; + streams->recv.max_streams_uni = p->max_streams_uni; + +if (is_serv) { + type =QUIC_STREAM_TYPE_CLIENT_BIDI ; + streams->recv.max_bidi_stream_id = +quic_stream_streams_to_id (p->max_streams_bidi, type); + streams->recv.next_bidi_stream_id = type; + + type =QUIC_STREAM_TYPE_CLIENT_UNI ; + streams->recv.max_uni_stream_id = +quic_stream_streams_to_id (p->max_streams_uni, type); + streams->recv.next_uni_stream_id = type; +return ; + } + + type =QUIC_STREAM_TYPE_SERVER_BIDI ; + streams->recv.max_bidi_stream_id = +quic_stream_streams_to_id (p->max_streams_bidi, type); + streams->recv.next_bidi_stream_id = type; + + type =QUIC_STREAM_TYPE_SERVER_UNI ; + streams->recv.max_uni_stream_id = +quic_stream_streams_to_id (p->max_streams_uni, type); + streams->recv.next_uni_stream_id = type; +}net/quic/stream.h new file +136
-0@@ -0,0 +1,136 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#define QUIC_DEF_STREAMS 100 +#define QUIC_MAX_STREAMS 4096ULL + +/* +* rfc9000#section-2.1: +* +* The least significant bit (0x01) of the stream ID identifies the initiator of the stream. +* Client-initiated streams have even-numbered stream IDs (with the bit set to 0), and +* server-initiated streams have odd-numbered stream IDs (with the bit set to 1). +* +* The second least significant bit (0x02) of the stream ID distinguishes between bidirectional +* streams (with the bit set to 0) and unidirectional streams (with the bit set to 1). +*/ +#define QUIC_STREAM_TYPE_BITS 2 +#define QUIC_STREAM_ID_STEP BIT(QUIC_STREAM_TYPE_BITS) + +#define QUIC_STREAM_TYPE_CLIENT_BIDI 0x00 +#define QUIC_STREAM_TYPE_SERVER_BIDI 0x01 +#define QUIC_STREAM_TYPE_CLIENT_UNI 0x02 +#define QUIC_STREAM_TYPE_SERVER_UNI 0x03 + +struct quic_stream { +struct hlist_node node; +s64 id;/* Stream ID as defined in RFC 9000 Section 2.1 */ +struct { +/* Sending-side stream level flow control */ +u64 last_max_bytes;/* Maximum send offset advertised by peer at last update */ +u64 max_bytes;/* Current maximum offset we are allowed to send to */ +u64 bytes;/* Bytes already sent to peer */ + +u32 errcode;/* Application error code to send in RESET_STREAM */ +u32 frags;/* Number of sent STREAM frames not yet acknowledged */ +u8 state;/* Send stream state, per rfc9000#section-3.1 */ + +u8 data_blocked:1 ;/* True if flow control blocks sending more data */ +u8 done:1 ;/* True if application indicated end of stream (FIN sent) */ + } send; +struct { +/* Receiving-side stream level flow control */ +u64 max_bytes;/* Maximum offset peer is allowed to send to */ +u64 window;/* Remaining receive window before advertise a new limit */ +u64 bytes;/* Bytes consumed by application from the stream */ + +u64 highest;/* Highest received offset */ +u64 offset;/* Offset up to which data is in buffer or consumed */ +u64 finalsz;/* Final size of the stream if FIN received */ + +u32 frags;/* Number of received STREAM frames pending reassembly */ +u8 state;/* Receive stream state, per rfc9000#section-3.2 */ + +u8 stop_sent:1 ;/* True if STOP_SENDING has been sent */ +u8 done:1 ;/* True if FIN received and final size validated */ + } recv; +}; + +struct quic_stream_table { +struct quic_shash_table ht;/* Hash table storing all active streams */ + +struct { +/* Parameters received from peer, defined in rfc9000#section-18.2 */ +u64 max_stream_data_bidi_remote;/* initial_max_stream_data_bidi_remote */ +u64 max_stream_data_bidi_local;/* initial_max_stream_data_bidi_local */ +u64 max_stream_data_uni;/* initial_max_stream_data_uni */ +u64 max_streams_bidi;/* initial_max_streams_bidi */ +u64 max_streams_uni;/* initial_max_streams_uni */ + +s64 next_bidi_stream_id;/* Next bidi stream ID to be opened */ +s64 next_uni_stream_id;/* Next uni stream ID to be opened */ +s64 max_bidi_stream_id;/* Highest allowed bidi stream ID */ +s64 max_uni_stream_id;/* Highest allowed uni stream ID */ +s64 active_stream_id;/* Most recently opened stream ID */ + +u8 bidi_blocked:1 ;/* True if STREAMS_BLOCKED_BIDI was sent and not ACKed */ +u8 uni_blocked:1 ;/* True if STREAMS_BLOCKED_UNI was sent and not ACKed */ +u16 streams_bidi;/* Number of currently active bidi streams */ +u16 streams_uni;/* Number of currently active uni streams */ + } send; +struct { +/* Our advertised limits to the peer, per rfc9000#section-18.2 */ +u64 max_stream_data_bidi_remote;/* initial_max_stream_data_bidi_remote */ +u64 max_stream_data_bidi_local;/* initial_max_stream_data_bidi_local */ +u64 max_stream_data_uni;/* initial_max_stream_data_uni */ +u64 max_streams_bidi;/* initial_max_streams_bidi */ +u64 max_streams_uni;/* initial_max_streams_uni */ + +s64 next_bidi_stream_id;/* Next expected bidi stream ID from peer */ +s64 next_uni_stream_id;/* Next expected uni stream ID from peer */ +s64 max_bidi_stream_id;/* Current allowed bidi stream ID range */ +s64 max_uni_stream_id;/* Current allowed uni stream ID range */ + +u8 bidi_pending:1 ;/* True if MAX_STREAMS_BIDI needs to be sent */ +u8 uni_pending:1 ;/* True if MAX_STREAMS_UNI needs to be sent */ +u16 streams_bidi;/* Number of currently open bidi streams */ +u16 streams_uni;/* Number of currently open uni streams */ + } recv; +}; + +static inline u64 quic_stream_id_to_streams (s64 stream_id) +{ +return (u64)(stream_id >>QUIC_STREAM_TYPE_BITS ) +1 ; +} + +static inline s64 quic_stream_streams_to_id (u64 streams,u8 type) +{ +return (s64)((streams -1 ) <<QUIC_STREAM_TYPE_BITS ) | type; +} + +struct quic_stream *quic_stream_send_get (struct quic_stream_table *streams,s64 stream_id, +u32 flags,bool is_serv); +struct quic_stream *quic_stream_recv_get (struct quic_stream_table *streams,s64 stream_id, +bool is_serv); +void quic_stream_send_put (struct quic_stream_table *streams,struct quic_stream *stream, +bool is_serv); +void quic_stream_recv_put (struct quic_stream_table *streams,struct quic_stream *stream, +bool is_serv); + +bool quic_stream_max_streams_update (struct quic_stream_table *streams,s64 *max_uni,s64 *max_bidi); +bool quic_stream_id_exceeds (struct quic_stream_table *streams,s64 stream_id,bool send); +struct quic_stream *quic_stream_find (struct quic_stream_table *streams,s64 stream_id); + +void quic_stream_get_param (struct quic_stream_table *streams,struct quic_transport_param *p, +bool is_serv); +void quic_stream_set_param (struct quic_stream_table *streams,struct quic_transport_param *p, +bool is_serv); +void quic_stream_free (struct quic_stream_table *streams); +int quic_stream_init (struct quic_stream_table *streams);
Paolo Abeni
maintainerRe: [PATCH net-next v3 09/15] quic: add congestion control
In reply to Xin LongQuoted 7 lines · Xin Long
This patch introduces '
quic_cong' for RTT measurement and congestion control. The 'quic_cong_ops' is added to define the congestion control algorithm.It implements a congestion control state machine with slow start, congestion avoidance, and recovery phases, and introduces the New Reno and CUBIC algorithms.
To moderate the initial submission size, you could initially introduce just one of the above.
Quoted 99 lines
The implementation updates RTT estimates when packets are acknowledged, reacts to loss and ECN signals, and adjusts the congestion window accordingly during packet transmission and acknowledgment processing.
-
quic_cong_rtt_update(): Performs RTT measurement, invoked when a packet is acknowledged by the largest number in the ACK frame.-
quic_cong_on_packet_acked(): Invoked when a packet is acknowledged.-
quic_cong_on_packet_lost(): Invoked when a packet is marked as lost.-
quic_cong_on_process_ecn(): Invoked when anACK_ECNframe is received.-
quic_cong_on_packet_sent(): Invoked when a packet is transmitted.-
quic_cong_on_ack_recv(): Invoked when an ACK frame is received.Signed-off-by Xin Long <[email protected]>--- net/quic/Makefile | 3 +- net/quic/cong.c | 700 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/cong.h | 120 ++++++++ net/quic/socket.c | 1 + net/quic/socket.h | 7 + 5 files changed, 830 insertions(+), 1 deletion(-) create mode 100644 net/quic/cong.c create mode 100644 net/quic/cong.hnet/quic/Makefile +2
-1@@ -5,4 +5,5 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o +quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ + cong.onet/quic/cong.c new file +54
-0@@ -0,0 +1,700 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Initialization/cleanup for QUIC protocol support. +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <linux/jiffies.h> +#include <linux/quic.h> +#include <net/sock.h> + +#include "common.h" +#include "cong.h" + +/* CUBIC APIs */ +struct quic_cubic { +/* Variables of Interest in rfc9438#section-4.1.2 */ +u32 pending_w_add;/* Accumulate fractional increments to W_est */ +u32 origin_point;/* W_max */ +u32 epoch_start;/* t_epoch */ +u32 pending_add;/* Accumulates fractional additions to W_cubic */ +u32 w_last_max;/* last W_max */ +u32 w_tcp;/* W_est */ +u64 k;/* K */ + +/* HyStart++ variables in rfc9406#section-4.2 */ +u32 current_round_min_rtt;/* currentRoundMinRTT */ +u32 css_baseline_min_rtt;/* cssBaselineMinRtt */ +u32 last_round_min_rtt;/* lastRoundMinRTT */ +u16 rtt_sample_count;/* rttSampleCount */ +u16 css_rounds;/* Counter for consecutive rounds showing RTT increase */ +s64 window_end;/* End of current CSS round (packet number) */ +}; + +/* HyStart++ constants in rfc9406#section-4.3 */ +#define QUIC_HS_MIN_SSTHRESH 16 +#define QUIC_HS_N_RTT_SAMPLE 8 +#define QUIC_HS_MIN_ETA 4000 +#define QUIC_HS_MAX_ETA 16000 +#define QUIC_HS_MIN_RTT_DIVISOR 8 +#define QUIC_HS_CSS_GROWTH_DIVISOR 4 +#define QUIC_HS_CSS_ROUNDS 5 + +static u64 cubic_root (u64 n) +{ +u64 a, d; + +if (!n) +return 0 ;
net/quic/cong.c line 64
Quoted 10 lines
net/quic/cong.c new file +10
-0+ + d = (64 -__builtin_clzll (n)) /3 ; + a =BIT_ULL (d +1 ); + +for (; a * a * a > n;) { + d =div64_ul (n, a * a); + a =div64_ul (2 * a + d,3 ); + } +return a; +}
tcp_cubic() has already an helper to compute the square root. You could re-use that one.
Quoted 64 lines
net/quic/cong.c new file +64
-0+ +/* rfc9406#section-4: HyStart++ Algorithm */ +static void cubic_slow_start (struct quic_cong *cong,u32 bytes,s64 number) +{ +struct quic_cubic *cubic =quic_cong_priv (cong); +u32 eta; + +if (cubic->window_end <= number) + cubic->window_end =-1 ; + +/* cwnd = cwnd + (min(N, L * SMSS) / CSS_GROWTH_DIVISOR) */ +if (cubic->css_baseline_min_rtt !=U32_MAX ) + bytes = bytes /QUIC_HS_CSS_GROWTH_DIVISOR ; + cong->window =min_t (u32, cong->window + bytes, cong->max_window); + +if (cubic->css_baseline_min_rtt !=U32_MAX ) { +/* If CSS_ROUNDS rounds are complete, enter congestion avoidance. */ +if (++cubic->css_rounds >QUIC_HS_CSS_ROUNDS ) { + cubic->css_baseline_min_rtt =U32_MAX ; + cubic->w_last_max = cong->window; + cong->ssthresh = cong->window; + cubic->css_rounds =0 ; + } +return ; + } + +/* if ((rttSampleCount >= N_RTT_SAMPLE) AND +* (currentRoundMinRTT != infinity) AND +* (lastRoundMinRTT != infinity)) +* RttThresh = max(MIN_RTT_THRESH, +* min(lastRoundMinRTT / MIN_RTT_DIVISOR, MAX_RTT_THRESH)) +* if (currentRoundMinRTT >= (lastRoundMinRTT + RttThresh)) +* cssBaselineMinRtt = currentRoundMinRTT +* exit slow start and enter CSS +*/ +if (cubic->last_round_min_rtt !=U32_MAX && + cubic->current_round_min_rtt !=U32_MAX && + cong->window >=QUIC_HS_MIN_SSTHRESH * cong->mss && + cubic->rtt_sample_count >=QUIC_HS_N_RTT_SAMPLE ) { + eta = cubic->last_round_min_rtt /QUIC_HS_MIN_RTT_DIVISOR ; +if (eta <QUIC_HS_MIN_ETA ) + eta =QUIC_HS_MIN_ETA ; +else if (eta >QUIC_HS_MAX_ETA ) + eta =QUIC_HS_MAX_ETA ; + +pr_debug ("%s: current_round_min_rtt: %u, last_round_min_rtt: %u, eta: %u\n" , + __func__, cubic->current_round_min_rtt, cubic->last_round_min_rtt, eta); + +/* Delay increase triggers slow start exit and enter CSS. */ +if (cubic->current_round_min_rtt >= cubic->last_round_min_rtt + eta) + cubic->css_baseline_min_rtt = cubic->current_round_min_rtt; + } +} + +/* rfc9438#section-4: CUBIC Congestion Control */ +static void cubic_cong_avoid (struct quic_cong *cong,u32 bytes) +{ +struct quic_cubic *cubic =quic_cong_priv (cong); +u64 tx, kx, time_delta, delta, t; +u64 target_add, tcp_add =0 ; +u64 target, cwnd_thres, m; + +if (cubic->epoch_start ==U32_MAX ) { + cubic->epoch_start = cong->time;
net/quic/cong.c line 138
Quoted 10 lines
net/quic/cong.c new file +10
-0+if (cong->window < cubic->w_last_max) { +/* +* ┌────────────────┐ +* 3 │W - cwnd +* ╲ │ max epoch +* K = ╲ │──────────────── +* ╲│ C +*/ + cubic->k = cubic->w_last_max - cong->window; + cubic->k =cubic_root (div64_ul (cubic->k *10 , (u64 )cong->mss *4 ));
Can mss be 0 at this point? Why?
Quoted 58 lines
net/quic/cong.c new file +58
-0+ cubic->origin_point = cubic->w_last_max; + }else { + cubic->k =0 ; + cubic->origin_point = cong->window; + } + cubic->w_tcp = cong->window; + cubic->pending_add =0 ; + cubic->pending_w_add =0 ; + } + +/* +* t = t - t +* current epoch +*/ + t = cong->time - cubic->epoch_start; + tx =div64_ul (t <<10 ,USEC_PER_SEC ); + kx = (cubic->k <<10 ); +if (tx > kx) + time_delta = tx - kx; +else + time_delta = kx - tx; +/* +* 3 +* W (t) = C * (t - K) + W +* cubic max +*/ + delta = cong->mss * ((((time_delta * time_delta) >>10 ) * time_delta) >>10 ); + delta =div64_ul (delta *4 ,10 ) >>10 ; +if (tx > kx) + target = cubic->origin_point + delta; +else + target = cubic->origin_point - delta; + +/* +* W (t + RTT) +* cubic +*/ + cwnd_thres = (div64_ul ((t + cong->smoothed_rtt) <<10 ,USEC_PER_SEC ) * target) >>10 ; +pr_debug ("%s: tgt: %llu, thres: %llu, delta: %llu, t: %llu, srtt: %u, tx: %llu, kx: %llu\n" , + __func__, target, cwnd_thres, delta, t, cong->smoothed_rtt, tx, kx); +/* +* ⎧ +* ⎪cwnd if W (t + RTT) < cwnd +* ⎪ cubic +* ⎨1.5 * cwnd if W (t + RTT) > 1.5 * cwnd +* target = ⎪ cubic +* ⎪W (t + RTT) otherwise +* ⎩ cubic +*/ +if (cwnd_thres < cong->window) + target = cong->window; +else if (cwnd_thres *2 > (u64 )cong->window *3 ) + target = cong->window *3 /2 ; +else + target = cwnd_thres; + +/* +* target - cwnd
net/quic/cong.c line 206
Quoted 10 lines
net/quic/cong.c new file +10
-0+* ───────────── +* cwnd +*/ +if (target > cong->window) { + target_add = cubic->pending_add + cong->mss * (target - cong->window); + cubic->pending_add =do_div (target_add, cong->window); + }else { + target_add = cubic->pending_add + cong->mss; + cubic->pending_add =do_div (target_add,100 * cong->window); + }
Can window be 0 here? why?
Quoted 46 lines
net/quic/cong.c new file +46
-0+ +pr_debug ("%s: target: %llu, window: %u, target_add: %llu\n" , + __func__, target, cong->window, target_add); + +/* +* segments_acked +* W = W + α * ────────────── +* est est cubic cwnd +*/ + m = cubic->pending_w_add + cong->mss * bytes; + cubic->pending_w_add =do_div (m, cong->window); + cubic->w_tcp += m; + +if (cubic->w_tcp > cong->window) + tcp_add =div64_ul ((u64 )cong->mss * (cubic->w_tcp - cong->window), cong->window); + +pr_debug ("%s: w_tcp: %u, window: %u, tcp_add: %llu\n" , + __func__, cubic->w_tcp, cong->window, tcp_add); + +/* W_cubic(_t_) or _W_est_, whichever is bigger. */ + cong->window +=max (tcp_add, target_add); +} + +static void cubic_recovery (struct quic_cong *cong) +{ +struct quic_cubic *cubic =quic_cong_priv (cong); + + cong->recovery_time = cong->time; + cubic->epoch_start =U32_MAX ; + +/* rfc9438#section-3.4: +* CUBIC sets the multiplicative window decrease factor (β__cubic_) to 0.7, +* whereas Reno uses 0.5. +* +* rfc9438#section-4.6: +* ssthresh = flight_size * β new ssthresh +* +* Some implementations of CUBIC currently use _cwnd_ instead of _flight_size_ when +* calculating a new _ssthresh_. +* +* rfc9438#section-4.7: +* +* ⎧ 1 + β +* ⎪ cubic +* ⎪cwnd * ────────── if cwnd < W_max and fast convergence +* W = ⎨ 2
net/quic/cong.c line 262
Quoted 10 lines
net/quic/cong.c new file +10
-0+* max ⎪ enabled, further reduce W_max +* ⎪ +* ⎩cwnd otherwise, remember cwnd before reduction +*/ +if (cong->window < cubic->w_last_max) + cubic->w_last_max = cong->window *17 /10 /2 ; +else + cubic->w_last_max = cong->window; + + cong->ssthresh = cong->window *7 /10 ;
There are quite a bit of magic numbers that should be replaced by macros and/or associated with explainatory comments.
Quoted 40 lines
net/quic/cong.c new file +40
-0+ +/* rfc9002#section-5: Estimating the Round-Trip Time */ +void quic_cong_rtt_update (struct quic_cong *cong,u32 time,u32 ack_delay) +{ +u32 adjusted_rtt, rttvar_sample; + +/* Ignore RTT sample if ACK delay is suspiciously large. */ +if (ack_delay > cong->max_ack_delay *2 ) +return ; + +/* rfc9002#section-5.1: latest_rtt = ack_time - send_time_of_largest_acked */ + cong->latest_rtt = cong->time - time; + +/* rfc9002#section-5.2: Estimating min_rtt */ +if (!cong->min_rtt_valid) { + cong->min_rtt = cong->latest_rtt; + cong->min_rtt_valid =1 ; + } +if (cong->min_rtt > cong->latest_rtt) + cong->min_rtt = cong->latest_rtt; + +if (!cong->is_rtt_set) { +/* rfc9002#section-5.3: +* smoothed_rtt = latest_rtt +* rttvar = latest_rtt / 2 +*/ + cong->smoothed_rtt = cong->latest_rtt; + cong->rttvar = cong->smoothed_rtt /2 ; +quic_cong_pto_update (cong); + cong->is_rtt_set =1 ; +return ; + } + +/* rfc9002#section-5.3: +* adjusted_rtt = latest_rtt +* if (latest_rtt >= min_rtt + ack_delay): +* adjusted_rtt = latest_rtt - ack_delay +* smoothed_rtt = 7/8 * smoothed_rtt + 1/8 * adjusted_rtt +* rttvar_sample = abs(smoothed_rtt - adjusted_rtt) +* rttvar = 3/4 * rttvar + 1/4 * rttvar_sample
net/quic/cong.c line 663
Quoted 10 lines
net/quic/cong.c new file +10
-0+*/ + adjusted_rtt = cong->latest_rtt; +if (cong->latest_rtt >= cong->min_rtt + ack_delay) + adjusted_rtt = cong->latest_rtt - ack_delay; + + cong->smoothed_rtt = (cong->smoothed_rtt *7 + adjusted_rtt) /8 ; +if (cong->smoothed_rtt >= adjusted_rtt) + rttvar_sample = cong->smoothed_rtt - adjusted_rtt; +else + rttvar_sample = adjusted_rtt - cong->smoothed_rtt;
Here in a few other place before you could use abs_diff()
/P
Re: [PATCH net-next v3 02/15] net: build socket infrastructure for QUIC protocol
In reply to Paolo AbeniQuoted 159 lines · Paolo Abeni
Quoted 157 lines · Xin Long
This patch lays the groundwork for QUIC socket support in the kernel. It defines the core structures and protocol hooks needed to create QUIC sockets, without implementing any protocol behavior at this stage.
Basic integration is included to allow building the module via
CONFIG_IP_QUIC=m.This provides the scaffolding necessary for adding actual QUIC socket behavior in follow-up patches.
Signed-off-by Pengtao He <[email protected]>Signed-off-by Xin Long <[email protected]>---
v3:
-Kconfig: add 'default n' forIP_QUIC(reported by Paolo).
-quic_disconnect(): return-EOPNOTSUPP(suggested by Paolo).
- quic_init/destroy_sock(): drop local_bh_disable/enable() calls (noted by Paolo).
- sysctl: addalpn_demuxoption to en/disable ALPN-based demux.
- SNMP: removeSNMP_MIB_SENTINEL, switch tosnmp_get_cpu_field_batch_cnt()to align with latest net-next changes.--- net/Kconfig | 1 + net/Makefile | 1 + net/quic/Kconfig | 36 +++++ net/quic/Makefile | 8 + net/quic/protocol.c | 379 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/protocol.h | 56 +++++++ net/quic/socket.c | 207 ++++++++++++++++++++++++ net/quic/socket.h | 79 +++++++++ 8 files changed, 767 insertions(+) create mode 100644 net/quic/Kconfig create mode 100644 net/quic/Makefile create mode 100644 net/quic/protocol.c create mode 100644 net/quic/protocol.h create mode 100644 net/quic/socket.c create mode 100644 net/quic/socket.hnet/Kconfig +1
-0@@ -249,6 +249,7 @@ source "net/bridge/netfilter/Kconfig" endif # if NETFILTER +source "net/quic/Kconfig" source "net/sctp/Kconfig" source "net/rds/Kconfig" source "net/tipc/Kconfig"net/Makefile +1
-0@@ -42,6 +42,7 @@ obj-$(CONFIG_PHONET) += phonet/ ifneq ($(CONFIG_VLAN_8021Q),) obj-y += 8021q/ endif +obj-$(CONFIG_IP_QUIC) += quic/ obj-$(CONFIG_IP_SCTP) += sctp/ obj-$(CONFIG_RDS) += rds/ obj-$(CONFIG_WIRELESS) += wireless/net/quic/Kconfig new file +36
-0@@ -0,0 +1,36 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# QUIC configuration +# + +menuconfig IP_QUIC + tristate "QUIC: A UDP-Based Multiplexed and Secure Transport (Experimental)" + depends on INET + depends on IPV6 + select CRYPTO + select CRYPTO_HMAC + select CRYPTO_HKDF + select CRYPTO_AES + select CRYPTO_GCM + select CRYPTO_CCM + select CRYPTO_CHACHA20POLY1305 + select NET_UDP_TUNNEL + default n + help + QUIC: A UDP-Based Multiplexed and Secure Transport + + From rfc9000 <https://www.rfc-editor.org/rfc/rfc9000.html>. + + QUIC provides applications with flow-controlled streams for structured + communication, low-latency connection establishment, and network path + migration. QUIC includes security measures that ensure + confidentiality, integrity, and availability in a range of deployment + circumstances. Accompanying documents describe the integration of + TLS for key negotiation, loss detection, and an exemplary congestion + control algorithm. + + To compile this protocol support as a module, choose M here: the + module will be called quic. Debug messages are handled by the + kernel's dynamic debugging framework. + + If in doubt, say N.net/quic/Makefile new file +8
-0@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Makefile for QUIC support code. +# + +obj-$(CONFIG_IP_QUIC) += quic.o + +quic-y := protocol.o socket.onet/quic/protocol.c new file +33
-0@@ -0,0 +1,379 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Initialization/cleanup for QUIC protocol support. +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <net/inet_common.h> +#include <linux/proc_fs.h> +#include <net/protocol.h> +#include <net/rps.h> +#include <net/tls.h> + +#include "socket.h" + +static unsigned int quic_net_id__read_mostly ; + +struct percpu_counter quic_sockets_allocated; + +long sysctl_quic_mem[3 ]; +int sysctl_quic_rmem[3 ]; +int sysctl_quic_wmem[3 ]; +int sysctl_quic_alpn_demux; + +static int quic_inet_connect (struct socket *sock,struct sockaddr *addr,int addr_len,int flags) +{ +struct sock *sk = sock->sk; +const struct proto *prot;
Quoted 8 lines
net/quic/protocol.c line 38
Quoted 5 lines
net/quic/protocol.c new file +5
-0+ +if (addr_len < (int )sizeof (addr->sa_family)) +return -EINVAL ; + + prot =READ_ONCE (sk->sk_prot);Is the above
_ONCE()annotation for ADDRFORM's sake? If so it should not be needed (only UDP and TCP sockets are affected).
I will delete it.
Quoted 25 lines
Quoted 25 lines
net/quic/socket.h new file +18
-0@@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <net/udp_tunnel.h> + +#include "protocol.h" + +extern struct proto quic_prot; +extern struct proto quicv6_prot; + +enum quic_state {
Quoted 9 lines
net/quic/socket.h line 23
Quoted 5 lines
net/quic/socket.h new file +5
-0+QUIC_SS_CLOSED =TCP_CLOSE , +QUIC_SS_LISTENING =TCP_LISTEN , +QUIC_SS_ESTABLISHING =TCP_SYN_RECV , + QUIC_SS_ESTABLISHED = TCP_ESTABLISHED, +};Any special reason to define protocol-specific states? I guess you could re-use the TCP ones, as other protocols already do.
I know TIPC and SCTP define the states like this:
enum {
TIPC_LISTEN = TCP_LISTEN,
TIPC_ESTABLISHED = TCP_ESTABLISHED,
TIPC_OPEN = TCP_CLOSE,
TIPC_DISCONNECTING = TCP_CLOSE_WAIT,
TIPC_CONNECTING = TCP_SYN_SENT,
};
and
enum sctp_sock_state {
SCTP_SS_CLOSED = TCP_CLOSE,
SCTP_SS_LISTENING = TCP_LISTEN,
SCTP_SS_ESTABLISHING = TCP_SYN_SENT,
SCTP_SS_ESTABLISHED = TCP_ESTABLISHED,
SCTP_SS_CLOSING = TCP_CLOSE_WAIT,};
It should be fine to keep as is, or you have more and better examples from other protocols.
Thanks.
Re: [PATCH net-next v3 03/15] quic: provide common utilities and data structures
In reply to Simon HormanQuoted 10 lines · Simon Horman
Quoted 7 lines · Xin Long
index
f79f43f0c17f..b54532916aa2100644net/quic/protocol.c +0
-0@@ -336,6 +336,9 @@ static __init int quic_init(void)if (err) goto err_percpu_counter;
Quoted 7 lines
net/quic/protocol.c static __init int quic_init(void) · line 339
Quoted 1 line
net/quic/protocol.c +1
-0+if (quic_hash_tables_init ())Hi Xin,
If we reach here then the function will return err, which is 0. So it seems that err should be set to a negative error value instead. Perhaps the return value of
quic_hash_tables_init.
Good catch!
Re: [PATCH net-next v3 03/15] quic: provide common utilities and data structures
In reply to Paolo AbeniQuoted 20 lines · Paolo Abeni
Quoted 11 lines · Xin Long
This patch provides foundational data structures and utilities used throughout the QUIC stack.
It introduces packet header types, connection ID support, and address handling. Hash tables are added to manage socket lookup and connection ID mapping.
A flexible binary data type is provided, along with helpers for parsing, matching, and memory management. Helpers for encoding and decoding transport parameters and frames are also included.
Quoted 6 lines
Signed-off-by Xin Long <[email protected]>---
v3:
- Rework hashtables: split into two types and size them based ontotalram_pages(), similar to SCTP (reported by Paolo).
- structquic_shash_table: use rwlock instead of spinlock.
Quoted 2 lines
Why? rwlock usage should be avoided in networking (as it's unfair, see the many refactors replacing rwlock with rcu/plain spinlock)
Interesting, I thought rwlock works better than spinlock in this case. I will change back to spinlock.
Quoted 18 lines
[...]
net/quic/common.c line 144
Quoted 12 lines
net/quic/common.c new file +12
-0+ +static int quic_uhash_table_init (struct quic_uhash_table *ht,u32 max_size,int order) +{ +int i, max_order, size; + +/* Same sizing logic as in quic_shash_table_init(). */ + max_order =get_order (max_size *sizeof (struct quic_uhash_head )); + order =min (order, max_order); +do { + ht->hash = (struct quic_uhash_head *) +__get_free_pages (GFP_KERNEL | __GFP_NOWARN, order); + }while (!ht->hash && --order >0 );You can avoid a little complexity, and see more consistent behaviour, using plain
vmalloc()oralloc_large_system_hash()with no fallback.
I wanted to use alloc_large_system_hash(), but the memory allocated by it is usually NOT meant to be freed at runtime. I don't see a free_ function to do it either.
If QUIC works as a kernel module, what should I do with this memory in module_exit()?
Quoted 14 lines
Quoted 14 lines
net/quic/common.c new file +13
-0+/* rfc9000#section-a.3: DecodePacketNumber() +* +* Reconstructs the full packet number from a truncated one. +*/ +s64 quic_get_num (s64 max_pkt_num,s64 pkt_num,u32 n) +{ +s64 expected = max_pkt_num +1 ; +s64 win =BIT_ULL (n *8 ); +s64 hwin = win /2 ; +s64 mask = win -1 ; +s64 cand; + + cand = (expected & ~mask) | pkt_num;
Quoted 9 lines
net/quic/common.c line 428
Quoted 5 lines
net/quic/common.c new file +5
-0+if (cand <= expected - hwin && cand < (1ULL <<62 ) - win) +return cand + win; +if (cand > expected + hwin && cand >= win) +return cand - win; +return cand;The above is a bit obscure to me; replacing magic nubers (62) with macro could help. Some more comments also would do.
The code is exactly from the commented doc:
/* rfc9000#section-a.3: DecodePacketNumber()
See:
https://datatracker.ietf.org/doc/html/rfc9000#section-a.3
I will bring some comments from there.
Thanks.
Re: [PATCH net-next v3 04/15] quic: provide family ops for address and protocol
In reply to Paolo AbeniQuoted 15 lines · Paolo Abeni
Quoted 13 lines · Xin Long
net/quic/family.c new file +13
-0+static int quic_v4_flow_route (struct sock *sk,union quic_addr *da,union quic_addr *sa, +struct flowi *fl) +{ +struct flowi4 *fl4; +struct rtable *rt; +struct flowi _fl; + +if (__sk_dst_check (sk,0 )) +return 1 ; + + fl4 = &_fl.u.ip4; +memset (&_fl,0x00 ,sizeof (_fl)); + fl4->saddr = sa->v4.sin_addr.s_addr;
Quoted 8 lines
net/quic/family.c line 76
Quoted 5 lines
net/quic/family.c new file +5
-0+ fl4->fl4_sport = sa->v4.sin_port; + fl4->daddr = da->v4.sin_addr.s_addr; + fl4->fl4_dport = da->v4.sin_port; + fl4->flowi4_proto =IPPROTO_UDP ; + fl4->flowi4_oif = sk->sk_bound_dev_if;Why you need a local variable? I think you could use the 'fl' argument directly.
You're right, I don't really need this '_fl'.
Quoted 32 lines
Quoted 32 lines
net/quic/family.c new file +31
-0+ + fl4->flowi4_scope =ip_sock_rt_scope (sk); + fl4->flowi4_dscp =inet_sk_dscp (inet_sk (sk)); + + rt =ip_route_output_key (sock_net (sk), fl4); +if (IS_ERR (rt)) +return PTR_ERR (rt); + +if (!sa->v4.sin_family) { + sa->v4.sin_family =AF_INET ; + sa->v4.sin_addr.s_addr = fl4->saddr; + } +sk_setup_caps (sk, &rt->dst); +memcpy (fl, &_fl,sizeof (_fl)); +return 0 ; +} + +static int quic_v6_flow_route (struct sock *sk,union quic_addr *da,union quic_addr *sa, +struct flowi *fl) +{ +struct ipv6_pinfo *np =inet6_sk (sk); +struct ip6_flowlabel *flowlabel; +struct dst_entry *dst; +struct flowi6 *fl6; +struct flowi _fl; + +if (__sk_dst_check (sk, np->dst_cookie)) +return 1 ; + + fl6 = &_fl.u.ip6; +memset (&_fl,0x0 ,sizeof (_fl));
Quoted 8 lines
net/quic/family.c line 113
Quoted 6 lines
net/quic/family.c new file +6
-0+ fl6->saddr = sa->v6.sin6_addr; + fl6->fl6_sport = sa->v6.sin6_port; + fl6->daddr = da->v6.sin6_addr; + fl6->fl6_dport = da->v6.sin6_port; + fl6->flowi6_proto =IPPROTO_UDP ; + fl6->flowi6_oif = sk->sk_bound_dev_if;Same here.
Yes.
Quoted 431 lines
Quoted 418 lines
net/quic/family.c new file +417
-0+ +if (inet6_test_bit (SNDFLOW , sk)) { + fl6->flowlabel = (da->v6.sin6_flowinfo &IPV6_FLOWINFO_MASK ); +if (fl6->flowlabel &IPV6_FLOWLABEL_MASK ) { + flowlabel =fl6_sock_lookup (sk, fl6->flowlabel); +if (IS_ERR (flowlabel)) +return -EINVAL ; +fl6_sock_release (flowlabel); + } + } + + dst =ip6_dst_lookup_flow (sock_net (sk), sk, fl6,NULL ); +if (IS_ERR (dst)) +return PTR_ERR (dst); + +if (!sa->v6.sin6_family) { + sa->v6.sin6_family =AF_INET6 ; + sa->v6.sin6_addr = fl6->saddr; + } +ip6_dst_store (sk, dst,NULL ,NULL ); +memcpy (fl, &_fl,sizeof (_fl)); +return 0 ; +} + +static void quic_v4_lower_xmit (struct sock *sk,struct sk_buff *skb,struct flowi *fl) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u8 tos = (inet_sk (sk)->tos | cb->ecn), ttl; +struct flowi4 *fl4 = &fl->u.ip4; +struct dst_entry *dst; +__be16 df =0 ; + +pr_debug ("%s: skb: %p, len: %d, num: %llu, %pI4:%d -> %pI4:%d\n" , __func__, + skb, skb->len, cb->number, &fl4->saddr,ntohs (fl4->fl4_sport), + &fl4->daddr,ntohs (fl4->fl4_dport)); + + dst =sk_dst_get (sk); +if (!dst) { +kfree_skb (skb); +return ; + } +if (ip_dont_fragment (sk, dst) && !skb->ignore_df) + df =htons (IP_DF ); + + ttl = (u8 )ip4_dst_hoplimit (dst); +udp_tunnel_xmit_skb ((struct rtable *)dst, sk, skb, fl4->saddr, fl4->daddr, + tos, ttl, df, fl4->fl4_sport, fl4->fl4_dport, false, false,0 ); +} + +static void quic_v6_lower_xmit (struct sock *sk,struct sk_buff *skb,struct flowi *fl) +{ +struct quic_skb_cb *cb =QUIC_SKB_CB (skb); +u8 tc = (inet6_sk (sk)->tclass | cb->ecn), ttl; +struct flowi6 *fl6 = &fl->u.ip6; +struct dst_entry *dst; +__be32 label; + +pr_debug ("%s: skb: %p, len: %d, num: %llu, %pI6c:%d -> %pI6c:%d\n" , __func__, + skb, skb->len, cb->number, &fl6->saddr,ntohs (fl6->fl6_sport), + &fl6->daddr,ntohs (fl6->fl6_dport)); + + dst =sk_dst_get (sk); +if (!dst) { +kfree_skb (skb); +return ; + } + + ttl = (u8 )ip6_dst_hoplimit (dst); + label =ip6_make_flowlabel (sock_net (sk), skb, fl6->flowlabel, true, fl6); +udp_tunnel6_xmit_skb (dst, sk, skb,NULL , &fl6->saddr, &fl6->daddr, tc, + ttl, label, fl6->fl6_sport, fl6->fl6_dport, false,0 ); +} + +static void quic_v4_get_msg_addrs (struct sk_buff *skb,union quic_addr *da,union quic_addr *sa) +{ +struct udphdr *uh =quic_udphdr (skb); + + sa->v4.sin_family =AF_INET ; + sa->v4.sin_port = uh->source; + sa->v4.sin_addr.s_addr =ip_hdr (skb)->saddr; + + da->v4.sin_family =AF_INET ; + da->v4.sin_port = uh->dest; + da->v4.sin_addr.s_addr =ip_hdr (skb)->daddr; +} + +static void quic_v6_get_msg_addrs (struct sk_buff *skb,union quic_addr *da,union quic_addr *sa) +{ +struct udphdr *uh =quic_udphdr (skb); + + sa->v6.sin6_family =AF_INET6 ; + sa->v6.sin6_port = uh->source; + sa->v6.sin6_addr =ipv6_hdr (skb)->saddr; + + da->v6.sin6_family =AF_INET6 ; + da->v6.sin6_port = uh->dest; + da->v6.sin6_addr =ipv6_hdr (skb)->daddr; +} + +static int quic_v4_get_mtu_info (struct sk_buff *skb,u32 *info) +{ +struct icmphdr *hdr; + + hdr = (struct icmphdr *)(skb_network_header (skb) -sizeof (struct icmphdr )); +if (hdr->type ==ICMP_DEST_UNREACH && hdr->code ==ICMP_FRAG_NEEDED ) { + *info =ntohs (hdr->un.frag.mtu); +return 0 ; + } + +/* Defer other types' processing to UDP error handler. */ +return 1 ; +} + +static int quic_v6_get_mtu_info (struct sk_buff *skb,u32 *info) +{ +struct icmp6hdr *hdr; + + hdr = (struct icmp6hdr *)(skb_network_header (skb) -sizeof (struct icmp6hdr )); +if (hdr->icmp6_type ==ICMPV6_PKT_TOOBIG ) { + *info =ntohl (hdr->icmp6_mtu); +return 0 ; + } + +/* Defer other types' processing to UDP error handler. */ +return 1 ; +} + +static u8 quic_v4_get_msg_ecn (struct sk_buff *skb) +{ +return (ip_hdr (skb)->tos &INET_ECN_MASK ); +} + +static u8 quic_v6_get_msg_ecn (struct sk_buff *skb) +{ +return (ipv6_get_dsfield (ipv6_hdr (skb)) &INET_ECN_MASK ); +} + +static int quic_v4_get_user_addr (struct sock *sk,union quic_addr *a,struct sockaddr *addr, +int addr_len) +{ +u32 len =sizeof (struct sockaddr_in ); + +if (addr_len < len || addr->sa_family !=AF_INET ) +return 1 ; +if (ipv4_is_multicast (quic_addr (addr)->v4.sin_addr.s_addr)) +return 1 ; +memcpy (a, addr, len); +return 0 ; +} + +static int quic_v6_get_user_addr (struct sock *sk,union quic_addr *a,struct sockaddr *addr, +int addr_len) +{ +u32 len =sizeof (struct sockaddr_in ); +int type; + +if (addr_len < len) +return 1 ; + +if (addr->sa_family !=AF_INET6 ) { +if (ipv6_only_sock (sk)) +return 1 ; +return quic_v4_get_user_addr (sk, a, addr, addr_len); + } + + len =sizeof (struct sockaddr_in6 ); +if (addr_len < len) +return 1 ; + type =ipv6_addr_type (&quic_addr (addr)->v6.sin6_addr); +if (type !=IPV6_ADDR_ANY && !(type &IPV6_ADDR_UNICAST )) +return 1 ; +memcpy (a, addr, len); +return 0 ; +} + +static void quic_v4_get_pref_addr (struct sock *sk,union quic_addr *addr,u8 **pp,u32 *plen) +{ +u8 *p = *pp; + +memcpy (&addr->v4.sin_addr, p,QUIC_ADDR4_LEN ); + p +=QUIC_ADDR4_LEN ; +memcpy (&addr->v4.sin_port, p,QUIC_PORT_LEN ); + p +=QUIC_PORT_LEN ; + addr->v4.sin_family =AF_INET ; +/* Skip over IPv6 address and port, not used for AF_INET sockets. */ + p +=QUIC_ADDR6_LEN ; + p +=QUIC_PORT_LEN ; + +if (!addr->v4.sin_port ||quic_v4_is_any_addr (addr) || +ipv4_is_multicast (addr->v4.sin_addr.s_addr)) +memset (addr,0 ,sizeof (*addr)); + *plen -= (p - *pp); + *pp = p; +} + +static void quic_v6_get_pref_addr (struct sock *sk,union quic_addr *addr,u8 **pp,u32 *plen) +{ +u8 *p = *pp; +int type; + +/* Skip over IPv4 address and port. */ + p +=QUIC_ADDR4_LEN ; + p +=QUIC_PORT_LEN ; +/* Try to use IPv6 address and port first. */ +memcpy (&addr->v6.sin6_addr, p,QUIC_ADDR6_LEN ); + p +=QUIC_ADDR6_LEN ; +memcpy (&addr->v6.sin6_port, p,QUIC_PORT_LEN ); + p +=QUIC_PORT_LEN ; + addr->v6.sin6_family =AF_INET6 ; + + type =ipv6_addr_type (&addr->v6.sin6_addr); +if (!addr->v6.sin6_port || !(type &IPV6_ADDR_UNICAST )) { +memset (addr,0 ,sizeof (*addr)); +if (ipv6_only_sock (sk)) + goto out; +/* Fallback to IPv4 if IPv6 address is not usable. */ +return quic_v4_get_pref_addr (sk, addr, pp, plen); + } +out: + *plen -= (p - *pp); + *pp = p; +} + +static void quic_v4_set_pref_addr (struct sock *sk,u8 *p,union quic_addr *addr) +{ +memcpy (p, &addr->v4.sin_addr,QUIC_ADDR4_LEN ); + p +=QUIC_ADDR4_LEN ; +memcpy (p, &addr->v4.sin_port,QUIC_PORT_LEN ); + p +=QUIC_PORT_LEN ; +memset (p,0 ,QUIC_ADDR6_LEN ); + p +=QUIC_ADDR6_LEN ; +memset (p,0 ,QUIC_PORT_LEN ); +} + +static void quic_v6_set_pref_addr (struct sock *sk,u8 *p,union quic_addr *addr) +{ +if (addr->sa.sa_family ==AF_INET ) +return quic_v4_set_pref_addr (sk, p, addr); + +memset (p,0 ,QUIC_ADDR4_LEN ); + p +=QUIC_ADDR4_LEN ; +memset (p,0 ,QUIC_PORT_LEN ); + p +=QUIC_PORT_LEN ; +memcpy (p, &addr->v6.sin6_addr,QUIC_ADDR6_LEN ); + p +=QUIC_ADDR6_LEN ; +memcpy (p, &addr->v6.sin6_port,QUIC_PORT_LEN ); +} + +static bool quic_v4_cmp_sk_addr (struct sock *sk,union quic_addr *a,union quic_addr *addr) +{ +if (a->v4.sin_port != addr->v4.sin_port) +return false; +if (a->v4.sin_family != addr->v4.sin_family) +return false; +if (a->v4.sin_addr.s_addr ==htonl (INADDR_ANY ) || + addr->v4.sin_addr.s_addr ==htonl (INADDR_ANY )) +return true; +return a->v4.sin_addr.s_addr == addr->v4.sin_addr.s_addr; +} + +static bool quic_v6_cmp_sk_addr (struct sock *sk,union quic_addr *a,union quic_addr *addr) +{ +if (a->v4.sin_port != addr->v4.sin_port) +return false; + +if (a->sa.sa_family ==AF_INET && addr->sa.sa_family ==AF_INET ) { +if (a->v4.sin_addr.s_addr ==htonl (INADDR_ANY ) || + addr->v4.sin_addr.s_addr ==htonl (INADDR_ANY )) +return true; +return a->v4.sin_addr.s_addr == addr->v4.sin_addr.s_addr; + } + +if (a->sa.sa_family != addr->sa.sa_family) { +if (ipv6_only_sock (sk)) +return false; +if (a->sa.sa_family ==AF_INET6 &&ipv6_addr_any (&a->v6.sin6_addr)) +return true; +if (a->sa.sa_family ==AF_INET && addr->sa.sa_family ==AF_INET6 && +ipv6_addr_v4mapped (&addr->v6.sin6_addr) && + addr->v6.sin6_addr.s6_addr32[3 ] == a->v4.sin_addr.s_addr) +return true; +if (addr->sa.sa_family ==AF_INET && a->sa.sa_family ==AF_INET6 && +ipv6_addr_v4mapped (&a->v6.sin6_addr) && + a->v6.sin6_addr.s6_addr32[3 ] == addr->v4.sin_addr.s_addr) +return true; +return false; + } + +if (ipv6_addr_any (&a->v6.sin6_addr) ||ipv6_addr_any (&addr->v6.sin6_addr)) +return true; +return ipv6_addr_equal (&a->v6.sin6_addr, &addr->v6.sin6_addr); +} + +static int quic_v4_get_sk_addr (struct socket *sock,struct sockaddr *uaddr,int peer) +{ +return inet_getname (sock, uaddr, peer); +} + +static int quic_v6_get_sk_addr (struct socket *sock,struct sockaddr *uaddr,int peer) +{ +union quic_addr *a =quic_addr (uaddr); +int ret; + + ret =inet6_getname (sock, uaddr, peer); +if (ret <0 ) +return ret; + +if (a->sa.sa_family ==AF_INET6 &&ipv6_addr_v4mapped (&a->v6.sin6_addr)) { + a->v4.sin_family =AF_INET ; + a->v4.sin_port = a->v6.sin6_port; + a->v4.sin_addr.s_addr = a->v6.sin6_addr.s6_addr32[3 ]; + } + +if (a->sa.sa_family ==AF_INET ) { +memset (a->v4.sin_zero,0 ,sizeof (a->v4.sin_zero)); +return sizeof (struct sockaddr_in ); + } +return sizeof (struct sockaddr_in6 ); +} + +static void quic_v4_set_sk_addr (struct sock *sk,union quic_addr *a,bool src) +{ +if (src) { +inet_sk (sk)->inet_sport = a->v4.sin_port; +inet_sk (sk)->inet_saddr = a->v4.sin_addr.s_addr; + }else { +inet_sk (sk)->inet_dport = a->v4.sin_port; +inet_sk (sk)->inet_daddr = a->v4.sin_addr.s_addr; + } +} + +static void quic_v6_copy_sk_addr (struct in6_addr *skaddr,union quic_addr *a) +{ +if (a->sa.sa_family ==AF_INET ) { + skaddr->s6_addr32[0 ] =0 ; + skaddr->s6_addr32[1 ] =0 ; + skaddr->s6_addr32[2 ] =htonl (0x0000ffff ); + skaddr->s6_addr32[3 ] = a->v4.sin_addr.s_addr; + }else { + *skaddr = a->v6.sin6_addr; + } +} + +static void quic_v6_set_sk_addr (struct sock *sk,union quic_addr *a,bool src) +{ +if (src) { +inet_sk (sk)->inet_sport = a->v4.sin_port; +quic_v6_copy_sk_addr (&sk->sk_v6_rcv_saddr, a); + }else { +inet_sk (sk)->inet_dport = a->v4.sin_port; +quic_v6_copy_sk_addr (&sk->sk_v6_daddr, a); + } +} + +static void quic_v4_set_sk_ecn (struct sock *sk,u8 ecn) +{ +inet_sk (sk)->tos = ((inet_sk (sk)->tos & ~INET_ECN_MASK ) | ecn); +} + +static void quic_v6_set_sk_ecn (struct sock *sk,u8 ecn) +{ +quic_v4_set_sk_ecn (sk, ecn); +inet6_sk (sk)->tclass = ((inet6_sk (sk)->tclass & ~INET_ECN_MASK ) | ecn); +} + +#define quic_af_ipv4 (a) ((a)->sa.sa_family == AF_INET) + +u32 quic_encap_len (union quic_addr *a) +{ +return (quic_af_ipv4 (a) ?sizeof (struct iphdr ) :sizeof (struct ipv6hdr )) + +sizeof (struct udphdr ); +} + +int quic_is_any_addr (union quic_addr *a) +{ +return quic_af_ipv4 (a) ?quic_v4_is_any_addr (a) :quic_v6_is_any_addr (a); +} + +void quic_seq_dump_addr (struct seq_file *seq,union quic_addr *addr) +{ +quic_af_ipv4 (addr) ?quic_v4_seq_dump_addr (seq, addr) :quic_v6_seq_dump_addr (seq, addr); +} + +void quic_udp_conf_init (struct sock *sk,struct udp_port_cfg *conf,union quic_addr *a) +{ +quic_af_ipv4 (a) ?quic_v4_udp_conf_init (sk, conf, a) :quic_v6_udp_conf_init (sk, conf, a); +} + +int quic_flow_route (struct sock *sk,union quic_addr *da,union quic_addr *sa,struct flowi *fl) +{ +return quic_af_ipv4 (da) ?quic_v4_flow_route (sk, da, sa, fl) + :quic_v6_flow_route (sk, da, sa, fl); +} + +void quic_lower_xmit (struct sock *sk,struct sk_buff *skb,union quic_addr *da,struct flowi *fl) +{ +quic_af_ipv4 (da) ?quic_v4_lower_xmit (sk, skb, fl) :quic_v6_lower_xmit (sk, skb, fl); +} + +#define quic_skb_ipv4 (skb) (ip_hdr(skb)->version == 4) + +void quic_get_msg_addrs (struct sk_buff *skb,union quic_addr *da,union quic_addr *sa) +{ +memset (sa,0 ,sizeof (*sa)); +memset (da,0 ,sizeof (*da)); +quic_skb_ipv4 (skb) ?quic_v4_get_msg_addrs (skb, da, sa) + :quic_v6_get_msg_addrs (skb, da, sa); +} + +int quic_get_mtu_info (struct sk_buff *skb,u32 *info) +{ +return quic_skb_ipv4 (skb) ?quic_v4_get_mtu_info (skb, info) + :quic_v6_get_mtu_info (skb, info); +} + +u8 quic_get_msg_ecn (struct sk_buff *skb) +{net/quic/family.c line 540
Quoted 10 lines
net/quic/family.c new file +10
-0+return quic_skb_ipv4 (skb) ?quic_v4_get_msg_ecn (skb) :quic_v6_get_msg_ecn (skb); +} + +#define quic_pf_ipv4 (sk) ((sk)->sk_family == PF_INET) + +int quic_get_user_addr (struct sock *sk,union quic_addr *a,struct sockaddr *addr,int addr_len) +{ +memset (a,0 ,sizeof (*a)); +return quic_pf_ipv4 (sk) ?quic_v4_get_user_addr (sk, a, addr, addr_len) + :quic_v6_get_user_addr (sk, a, addr, addr_len);Minor nit: I think the most idiomatic way to express the abvoe is:
Quoted 3 lines
return
quic_pf_ipv4(sk)?quic_v4_get_user_addr(sk, a, addr, addr_len):quic_v6_get_user_addr(sk, a, addr, addr_len);
I somehow have been following the style of aligning the ? and : . will change to the most idiomatic way. :-)
Thanks.
Re: [PATCH net-next v3 06/15] quic: add stream management
In reply to Simon HormanQuoted 30 lines · Simon Horman
On Thu, Sep 18, 2025 at 06:34:55PM -0400, Xin Long wrote:
...
Quoted 1 line
net/quic/stream.c +0
-0...
Quoted 18 lines
net/quic/stream.c +18
-0+/* Create and register new streams for sending. */ +static struct quic_stream *quic_stream_send_create (struct quic_stream_table *streams, +s64 max_stream_id,u8 is_serv) +{ +struct quic_stream *stream; +s64 stream_id; + + stream_id = streams->send.next_bidi_stream_id; +if (quic_stream_id_uni (max_stream_id)) + stream_id = streams->send.next_uni_stream_id; + +/* rfc9000#section-2.1: A stream ID that is used out of order results in all streams +* of that type with lower-numbered stream IDs also being opened. +*/ +while (stream_id <= max_stream_id) { + stream =kzalloc (sizeof (*stream),GFP_KERNEL ); +if (!stream) +return NULL ;...
Quoted 8 lines
net/quic/stream.c
Quoted 2 lines
net/quic/stream.c +2
-0+ } +return stream;Hi Xin,
I'm unsure if can happen - actually I doubt it can - but if the loop above iterates zero times then stream will be used uninitialised here.
This can't happen.
But it's better to initialize it to NULL. Othersize, it always looks like a potential issue.
Thanks.
Quoted 6 lines
Likewise in
quic_stream_recv_create().Flagged by Smatch
...
Re: [PATCH net-next v3 06/15] quic: add stream management
In reply to Paolo AbeniQuoted 16 lines · Paolo Abeni
Quoted 14 lines · Xin Long
net/quic/stream.c new file +14
-0+/* Create and register new streams for sending. */ +static struct quic_stream *quic_stream_send_create (struct quic_stream_table *streams, +s64 max_stream_id,u8 is_serv) +{ +struct quic_stream *stream; +s64 stream_id; + + stream_id = streams->send.next_bidi_stream_id; +if (quic_stream_id_uni (max_stream_id)) + stream_id = streams->send.next_uni_stream_id; + +/* rfc9000#section-2.1: A stream ID that is used out of order results in all streams +* of that type with lower-numbered stream IDs also being opened. +*/
Quoted 8 lines
net/quic/stream.c line 88
Quoted 4 lines
net/quic/stream.c new file +4
-0+while (stream_id <= max_stream_id) { + stream =kzalloc (sizeof (*stream),GFP_KERNEL ); +if (!stream) +return NULL ;How many streams and connections ID do you foresee per socket? Could such number grow significantly (possibly under misuse/attack)? If so you you likely use
GFP_KERNEL_ACCOUNThere (and inconn_idallocation).
connections ID: 8 (QUIC_CONN_ID_LIMIT) at most per socket.
streams: 4096 (QUIC_MAX_STREAMS) at most per socket.
I can switch to GFP_KERNEL_ACCOUNT in quic_stream_send_create().
For quic_stream_recv_create(), it’s typically invoked in atomic context. Since there’s no predefined GFP_ATOMIC_ACCOUNT, I assume using (GFP_ATOMIC | __GFP_ACCOUNT) should be acceptable.
Thanks.
Quoted 567 lines
/P
Quoted 563 lines
net/quic/stream.c new file +421
-0+ + stream->id = stream_id; +if (quic_stream_id_uni (stream_id)) { + stream->send.max_bytes = streams->send.max_stream_data_uni; + +if (streams->send.next_uni_stream_id < stream_id +QUIC_STREAM_ID_STEP ) + streams->send.next_uni_stream_id = stream_id +QUIC_STREAM_ID_STEP ; + streams->send.streams_uni++; + +quic_stream_add (streams, stream); + stream_id +=QUIC_STREAM_ID_STEP ; +continue ; + } + +if (streams->send.next_bidi_stream_id < stream_id +QUIC_STREAM_ID_STEP ) + streams->send.next_bidi_stream_id = stream_id +QUIC_STREAM_ID_STEP ; + streams->send.streams_bidi++; + +if (quic_stream_id_local (stream_id, is_serv)) { + stream->send.max_bytes = streams->send.max_stream_data_bidi_remote; + stream->recv.max_bytes = streams->recv.max_stream_data_bidi_local; + }else { + stream->send.max_bytes = streams->send.max_stream_data_bidi_local; + stream->recv.max_bytes = streams->recv.max_stream_data_bidi_remote; + } + stream->recv.window = stream->recv.max_bytes; + +quic_stream_add (streams, stream); + stream_id +=QUIC_STREAM_ID_STEP ; + } +return stream; +} + +/* Create and register new streams for receiving. */ +static struct quic_stream *quic_stream_recv_create (struct quic_stream_table *streams, +s64 max_stream_id,u8 is_serv) +{ +struct quic_stream *stream; +s64 stream_id; + + stream_id = streams->recv.next_bidi_stream_id; +if (quic_stream_id_uni (max_stream_id)) + stream_id = streams->recv.next_uni_stream_id; + +/* rfc9000#section-2.1: A stream ID that is used out of order results in all streams +* of that type with lower-numbered stream IDs also being opened. +*/ +while (stream_id <= max_stream_id) { + stream =kzalloc (sizeof (*stream),GFP_ATOMIC ); +if (!stream) +return NULL ; + + stream->id = stream_id; +if (quic_stream_id_uni (stream_id)) { + stream->recv.window = streams->recv.max_stream_data_uni; + stream->recv.max_bytes = stream->recv.window; + +if (streams->recv.next_uni_stream_id < stream_id +QUIC_STREAM_ID_STEP ) + streams->recv.next_uni_stream_id = stream_id +QUIC_STREAM_ID_STEP ; + streams->recv.streams_uni++; + +quic_stream_add (streams, stream); + stream_id +=QUIC_STREAM_ID_STEP ; +continue ; + } + +if (streams->recv.next_bidi_stream_id < stream_id +QUIC_STREAM_ID_STEP ) + streams->recv.next_bidi_stream_id = stream_id +QUIC_STREAM_ID_STEP ; + streams->recv.streams_bidi++; + +if (quic_stream_id_local (stream_id, is_serv)) { + stream->send.max_bytes = streams->send.max_stream_data_bidi_remote; + stream->recv.max_bytes = streams->recv.max_stream_data_bidi_local; + }else { + stream->send.max_bytes = streams->send.max_stream_data_bidi_local; + stream->recv.max_bytes = streams->recv.max_stream_data_bidi_remote; + } + stream->recv.window = stream->recv.max_bytes; + +quic_stream_add (streams, stream); + stream_id +=QUIC_STREAM_ID_STEP ; + } +return stream; +} + +/* Check if a send or receive stream ID is already closed. */ +static bool quic_stream_id_closed (struct quic_stream_table *streams,s64 stream_id,bool send) +{ +if (quic_stream_id_uni (stream_id)) { +if (send) +return stream_id < streams->send.next_uni_stream_id; +return stream_id < streams->recv.next_uni_stream_id; + } +if (send) +return stream_id < streams->send.next_bidi_stream_id; +return stream_id < streams->recv.next_bidi_stream_id; +} + +/* Check if a stream ID would exceed local (recv) or peer (send) limits. */ +bool quic_stream_id_exceeds (struct quic_stream_table *streams,s64 stream_id,bool send) +{ +u64 nstreams; + +if (!send) { +if (quic_stream_id_uni (stream_id)) +return stream_id > streams->recv.max_uni_stream_id; +return stream_id > streams->recv.max_bidi_stream_id; + } + +if (quic_stream_id_uni (stream_id)) { +if (stream_id > streams->send.max_uni_stream_id) +return true; + stream_id -= streams->send.next_uni_stream_id; + nstreams =quic_stream_id_to_streams (stream_id); +return nstreams + streams->send.streams_uni > streams->send.max_streams_uni; + } + +if (stream_id > streams->send.max_bidi_stream_id) +return true; + stream_id -= streams->send.next_bidi_stream_id; + nstreams =quic_stream_id_to_streams (stream_id); +return nstreams + streams->send.streams_bidi > streams->send.max_streams_bidi; +} + +/* Get or create a send stream by ID. */ +struct quic_stream *quic_stream_send_get (struct quic_stream_table *streams,s64 stream_id, +u32 flags,bool is_serv) +{ +struct quic_stream *stream; + +if (!quic_stream_id_valid (stream_id, is_serv, true)) +return ERR_PTR (-EINVAL ); + + stream =quic_stream_find (streams, stream_id); +if (stream) { +if ((flags &MSG_STREAM_NEW ) && + stream->send.state !=QUIC_STREAM_SEND_STATE_READY ) +return ERR_PTR (-EINVAL ); +return stream; + } + +if (quic_stream_id_closed (streams, stream_id, true)) +return ERR_PTR (-ENOSTR ); + +if (!(flags &MSG_STREAM_NEW )) +return ERR_PTR (-EINVAL ); + +if (quic_stream_id_exceeds (streams, stream_id, true)) +return ERR_PTR (-EAGAIN ); + + stream =quic_stream_send_create (streams, stream_id, is_serv); +if (!stream) +return ERR_PTR (-ENOSTR ); + streams->send.active_stream_id = stream_id; +return stream; +} + +/* Get or create a receive stream by ID. */ +struct quic_stream *quic_stream_recv_get (struct quic_stream_table *streams,s64 stream_id, +bool is_serv) +{ +struct quic_stream *stream; + +if (!quic_stream_id_valid (stream_id, is_serv, false)) +return ERR_PTR (-EINVAL ); + + stream =quic_stream_find (streams, stream_id); +if (stream) +return stream; + +if (quic_stream_id_local (stream_id, is_serv)) { +if (quic_stream_id_closed (streams, stream_id, true)) +return ERR_PTR (-ENOSTR ); +return ERR_PTR (-EINVAL ); + } + +if (quic_stream_id_closed (streams, stream_id, false)) +return ERR_PTR (-ENOSTR ); + +if (quic_stream_id_exceeds (streams, stream_id, false)) +return ERR_PTR (-EAGAIN ); + + stream =quic_stream_recv_create (streams, stream_id, is_serv); +if (!stream) +return ERR_PTR (-ENOSTR ); +if (quic_stream_id_valid (stream_id, is_serv, true)) + streams->send.active_stream_id = stream_id; +return stream; +} + +/* Release or clean up a send stream. This function updates stream counters and state when +* a send stream has either successfully sent all data or has been reset. +*/ +void quic_stream_send_put (struct quic_stream_table *streams,struct quic_stream *stream, +bool is_serv) +{ +if (quic_stream_id_uni (stream->id)) { +/* For unidirectional streams, decrement uni count and delete immediately. */ + streams->send.streams_uni--; +quic_stream_delete (stream); +return ; + } + +/* For bidi streams, only proceed if receive side is in a final state. */ +if (stream->recv.state !=QUIC_STREAM_RECV_STATE_RECVD && + stream->recv.state !=QUIC_STREAM_RECV_STATE_READ && + stream->recv.state !=QUIC_STREAM_RECV_STATE_RESET_RECVD ) +return ; + +if (quic_stream_id_local (stream->id, is_serv)) { +/* Local-initiated stream: mark send done and decrement send.bidi count. */ +if (!stream->send.done) { + stream->send.done =1 ; + streams->send.streams_bidi--; + } + goto out; + } +/* Remote-initiated stream: mark recv done and decrement recv bidi count. */ +if (!stream->recv.done) { + stream->recv.done =1 ; + streams->recv.streams_bidi--; + streams->recv.bidi_pending =1 ; + } +out: +/* Delete stream if fully read or reset. */ +if (stream->recv.state !=QUIC_STREAM_RECV_STATE_RECVD ) +quic_stream_delete (stream); +} + +/* Release or clean up a receive stream. This function updates stream counters and state when +* the receive side has either consumed all data or has been reset. +*/ +void quic_stream_recv_put (struct quic_stream_table *streams,struct quic_stream *stream, +bool is_serv) +{ +if (quic_stream_id_uni (stream->id)) { +/* For uni streams, decrement uni count and mark done. */ +if (!stream->recv.done) { + stream->recv.done =1 ; + streams->recv.streams_uni--; + streams->recv.uni_pending =1 ; + } + goto out; + } + +/* For bidi streams, only proceed if send side is in a final state. */ +if (stream->send.state !=QUIC_STREAM_SEND_STATE_RECVD && + stream->send.state !=QUIC_STREAM_SEND_STATE_RESET_RECVD ) +return ; + +if (quic_stream_id_local (stream->id, is_serv)) { +/* Local-initiated stream: mark send done and decrement send.bidi count. */ +if (!stream->send.done) { + stream->send.done =1 ; + streams->send.streams_bidi--; + } + goto out; + } +/* Remote-initiated stream: mark recv done and decrement recv bidi count. */ +if (!stream->recv.done) { + stream->recv.done =1 ; + streams->recv.streams_bidi--; + streams->recv.bidi_pending =1 ; + } +out: +/* Delete stream if fully read or reset. */ +if (stream->recv.state !=QUIC_STREAM_RECV_STATE_RECVD ) +quic_stream_delete (stream); +} + +/* Updates the maximum allowed incoming stream IDs if any streams were recently closed. +* Recalculates the max_uni and max_bidi stream ID limits based on the number of open +* streams and whether any were marked for deletion. +* +* Returns true if either max_uni or max_bidi was updated, indicating that a +* MAX_STREAMS_UNI or MAX_STREAMS_BIDI frame should be sent to the peer. +*/ +bool quic_stream_max_streams_update (struct quic_stream_table *streams,s64 *max_uni,s64 *max_bidi) +{ +if (streams->recv.uni_pending) { + streams->recv.max_uni_stream_id = + streams->recv.next_uni_stream_id -QUIC_STREAM_ID_STEP + + ((streams->recv.max_streams_uni - streams->recv.streams_uni) << +QUIC_STREAM_TYPE_BITS ); + *max_uni =quic_stream_id_to_streams (streams->recv.max_uni_stream_id); + streams->recv.uni_pending =0 ; + } +if (streams->recv.bidi_pending) { + streams->recv.max_bidi_stream_id = + streams->recv.next_bidi_stream_id -QUIC_STREAM_ID_STEP + + ((streams->recv.max_streams_bidi - streams->recv.streams_bidi) << +QUIC_STREAM_TYPE_BITS ); + *max_bidi =quic_stream_id_to_streams (streams->recv.max_bidi_stream_id); + streams->recv.bidi_pending =0 ; + } + +return *max_uni || *max_bidi; +} + +#define QUIC_STREAM_HT_SIZE 64 + +int quic_stream_init (struct quic_stream_table *streams) +{ +struct quic_shash_table *ht = &streams->ht; +int i, size =QUIC_STREAM_HT_SIZE ; +struct quic_shash_head *head; + + head =kmalloc_array (size,sizeof (*head),GFP_KERNEL ); +if (!head) +return -ENOMEM ; +for (i =0 ; i < size; i++) +INIT_HLIST_HEAD (&head[i].head); + ht->size = size; + ht->hash = head; +return 0 ; +} + +void quic_stream_free (struct quic_stream_table *streams) +{ +struct quic_shash_table *ht = &streams->ht; +struct quic_shash_head *head; +struct quic_stream *stream; +struct hlist_node *tmp; +int i; + +for (i =0 ; i < ht->size; i++) { + head = &ht->hash[i]; +hlist_for_each_entry_safe (stream, tmp, &head->head, node) +quic_stream_delete (stream); + } +kfree (ht->hash); +} + +/* Populate transport parameters from stream hash table. */ +void quic_stream_get_param (struct quic_stream_table *streams,struct quic_transport_param *p, +bool is_serv) +{ +if (p->remote) { + p->max_stream_data_bidi_remote = streams->send.max_stream_data_bidi_remote; + p->max_stream_data_bidi_local = streams->send.max_stream_data_bidi_local; + p->max_stream_data_uni = streams->send.max_stream_data_uni; + p->max_streams_bidi = streams->send.max_streams_bidi; + p->max_streams_uni = streams->send.max_streams_uni; +return ; + } + + p->max_stream_data_bidi_remote = streams->recv.max_stream_data_bidi_remote; + p->max_stream_data_bidi_local = streams->recv.max_stream_data_bidi_local; + p->max_stream_data_uni = streams->recv.max_stream_data_uni; + p->max_streams_bidi = streams->recv.max_streams_bidi; + p->max_streams_uni = streams->recv.max_streams_uni; +} + +/* Configure stream hashtable from transport parameters. */ +void quic_stream_set_param (struct quic_stream_table *streams,struct quic_transport_param *p, +bool is_serv) +{ +u8 type; + +if (p->remote) { + streams->send.max_stream_data_bidi_local = p->max_stream_data_bidi_local; + streams->send.max_stream_data_bidi_remote = p->max_stream_data_bidi_remote; + streams->send.max_stream_data_uni = p->max_stream_data_uni; + streams->send.max_streams_bidi = p->max_streams_bidi; + streams->send.max_streams_uni = p->max_streams_uni; + streams->send.active_stream_id =-1 ; + +if (is_serv) { + type =QUIC_STREAM_TYPE_SERVER_BIDI ; + streams->send.max_bidi_stream_id = +quic_stream_streams_to_id (p->max_streams_bidi, type); + streams->send.next_bidi_stream_id = type; + + type =QUIC_STREAM_TYPE_SERVER_UNI ; + streams->send.max_uni_stream_id = +quic_stream_streams_to_id (p->max_streams_uni, type); + streams->send.next_uni_stream_id = type; +return ; + } + + type =QUIC_STREAM_TYPE_CLIENT_BIDI ; + streams->send.max_bidi_stream_id = +quic_stream_streams_to_id (p->max_streams_bidi, type); + streams->send.next_bidi_stream_id = type; + + type =QUIC_STREAM_TYPE_CLIENT_UNI ; + streams->send.max_uni_stream_id = +quic_stream_streams_to_id (p->max_streams_uni, type); + streams->send.next_uni_stream_id = type; +return ; + } + + streams->recv.max_stream_data_bidi_local = p->max_stream_data_bidi_local; + streams->recv.max_stream_data_bidi_remote = p->max_stream_data_bidi_remote; + streams->recv.max_stream_data_uni = p->max_stream_data_uni; + streams->recv.max_streams_bidi = p->max_streams_bidi; + streams->recv.max_streams_uni = p->max_streams_uni; + +if (is_serv) { + type =QUIC_STREAM_TYPE_CLIENT_BIDI ; + streams->recv.max_bidi_stream_id = +quic_stream_streams_to_id (p->max_streams_bidi, type); + streams->recv.next_bidi_stream_id = type; + + type =QUIC_STREAM_TYPE_CLIENT_UNI ; + streams->recv.max_uni_stream_id = +quic_stream_streams_to_id (p->max_streams_uni, type); + streams->recv.next_uni_stream_id = type; +return ; + } + + type =QUIC_STREAM_TYPE_SERVER_BIDI ; + streams->recv.max_bidi_stream_id = +quic_stream_streams_to_id (p->max_streams_bidi, type); + streams->recv.next_bidi_stream_id = type; + + type =QUIC_STREAM_TYPE_SERVER_UNI ; + streams->recv.max_uni_stream_id = +quic_stream_streams_to_id (p->max_streams_uni, type); + streams->recv.next_uni_stream_id = type; +}net/quic/stream.h new file +136
-0@@ -0,0 +1,136 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#define QUIC_DEF_STREAMS 100 +#define QUIC_MAX_STREAMS 4096ULL + +/* +* rfc9000#section-2.1: +* +* The least significant bit (0x01) of the stream ID identifies the initiator of the stream. +* Client-initiated streams have even-numbered stream IDs (with the bit set to 0), and +* server-initiated streams have odd-numbered stream IDs (with the bit set to 1). +* +* The second least significant bit (0x02) of the stream ID distinguishes between bidirectional +* streams (with the bit set to 0) and unidirectional streams (with the bit set to 1). +*/ +#define QUIC_STREAM_TYPE_BITS 2 +#define QUIC_STREAM_ID_STEP BIT(QUIC_STREAM_TYPE_BITS) + +#define QUIC_STREAM_TYPE_CLIENT_BIDI 0x00 +#define QUIC_STREAM_TYPE_SERVER_BIDI 0x01 +#define QUIC_STREAM_TYPE_CLIENT_UNI 0x02 +#define QUIC_STREAM_TYPE_SERVER_UNI 0x03 + +struct quic_stream { +struct hlist_node node; +s64 id;/* Stream ID as defined in RFC 9000 Section 2.1 */ +struct { +/* Sending-side stream level flow control */ +u64 last_max_bytes;/* Maximum send offset advertised by peer at last update */ +u64 max_bytes;/* Current maximum offset we are allowed to send to */ +u64 bytes;/* Bytes already sent to peer */ + +u32 errcode;/* Application error code to send in RESET_STREAM */ +u32 frags;/* Number of sent STREAM frames not yet acknowledged */ +u8 state;/* Send stream state, per rfc9000#section-3.1 */ + +u8 data_blocked:1 ;/* True if flow control blocks sending more data */ +u8 done:1 ;/* True if application indicated end of stream (FIN sent) */ + } send; +struct { +/* Receiving-side stream level flow control */ +u64 max_bytes;/* Maximum offset peer is allowed to send to */ +u64 window;/* Remaining receive window before advertise a new limit */ +u64 bytes;/* Bytes consumed by application from the stream */ + +u64 highest;/* Highest received offset */ +u64 offset;/* Offset up to which data is in buffer or consumed */ +u64 finalsz;/* Final size of the stream if FIN received */ + +u32 frags;/* Number of received STREAM frames pending reassembly */ +u8 state;/* Receive stream state, per rfc9000#section-3.2 */ + +u8 stop_sent:1 ;/* True if STOP_SENDING has been sent */ +u8 done:1 ;/* True if FIN received and final size validated */ + } recv; +}; + +struct quic_stream_table { +struct quic_shash_table ht;/* Hash table storing all active streams */ + +struct { +/* Parameters received from peer, defined in rfc9000#section-18.2 */ +u64 max_stream_data_bidi_remote;/* initial_max_stream_data_bidi_remote */ +u64 max_stream_data_bidi_local;/* initial_max_stream_data_bidi_local */ +u64 max_stream_data_uni;/* initial_max_stream_data_uni */ +u64 max_streams_bidi;/* initial_max_streams_bidi */ +u64 max_streams_uni;/* initial_max_streams_uni */ + +s64 next_bidi_stream_id;/* Next bidi stream ID to be opened */ +s64 next_uni_stream_id;/* Next uni stream ID to be opened */ +s64 max_bidi_stream_id;/* Highest allowed bidi stream ID */ +s64 max_uni_stream_id;/* Highest allowed uni stream ID */ +s64 active_stream_id;/* Most recently opened stream ID */ + +u8 bidi_blocked:1 ;/* True if STREAMS_BLOCKED_BIDI was sent and not ACKed */ +u8 uni_blocked:1 ;/* True if STREAMS_BLOCKED_UNI was sent and not ACKed */ +u16 streams_bidi;/* Number of currently active bidi streams */ +u16 streams_uni;/* Number of currently active uni streams */ + } send; +struct { +/* Our advertised limits to the peer, per rfc9000#section-18.2 */ +u64 max_stream_data_bidi_remote;/* initial_max_stream_data_bidi_remote */ +u64 max_stream_data_bidi_local;/* initial_max_stream_data_bidi_local */ +u64 max_stream_data_uni;/* initial_max_stream_data_uni */ +u64 max_streams_bidi;/* initial_max_streams_bidi */ +u64 max_streams_uni;/* initial_max_streams_uni */ + +s64 next_bidi_stream_id;/* Next expected bidi stream ID from peer */ +s64 next_uni_stream_id;/* Next expected uni stream ID from peer */ +s64 max_bidi_stream_id;/* Current allowed bidi stream ID range */ +s64 max_uni_stream_id;/* Current allowed uni stream ID range */ + +u8 bidi_pending:1 ;/* True if MAX_STREAMS_BIDI needs to be sent */ +u8 uni_pending:1 ;/* True if MAX_STREAMS_UNI needs to be sent */ +u16 streams_bidi;/* Number of currently open bidi streams */ +u16 streams_uni;/* Number of currently open uni streams */ + } recv; +}; + +static inline u64 quic_stream_id_to_streams (s64 stream_id) +{ +return (u64)(stream_id >>QUIC_STREAM_TYPE_BITS ) +1 ; +} + +static inline s64 quic_stream_streams_to_id (u64 streams,u8 type) +{ +return (s64)((streams -1 ) <<QUIC_STREAM_TYPE_BITS ) | type; +} + +struct quic_stream *quic_stream_send_get (struct quic_stream_table *streams,s64 stream_id, +u32 flags,bool is_serv); +struct quic_stream *quic_stream_recv_get (struct quic_stream_table *streams,s64 stream_id, +bool is_serv); +void quic_stream_send_put (struct quic_stream_table *streams,struct quic_stream *stream, +bool is_serv); +void quic_stream_recv_put (struct quic_stream_table *streams,struct quic_stream *stream, +bool is_serv); + +bool quic_stream_max_streams_update (struct quic_stream_table *streams,s64 *max_uni,s64 *max_bidi); +bool quic_stream_id_exceeds (struct quic_stream_table *streams,s64 stream_id,bool send); +struct quic_stream *quic_stream_find (struct quic_stream_table *streams,s64 stream_id); + +void quic_stream_get_param (struct quic_stream_table *streams,struct quic_transport_param *p, +bool is_serv); +void quic_stream_set_param (struct quic_stream_table *streams,struct quic_transport_param *p, +bool is_serv); +void quic_stream_free (struct quic_stream_table *streams); +int quic_stream_init (struct quic_stream_table *streams);
Re: [PATCH net-next v3 09/15] quic: add congestion control
In reply to Paolo AbeniQuoted 6 lines · Paolo Abeni
Quoted 4 lines · Xin Long
This patch introduces '
quic_cong' for RTT measurement and congestion control. The 'quic_cong_ops' is added to define the congestion control algorithm.
Quoted 6 lines
Quoted 3 lines
It implements a congestion control state machine with slow start, congestion avoidance, and recovery phases, and introduces the New Reno and CUBIC algorithms.
To moderate the initial submission size, you could initially introduce just one of the above.
That sounds like a good idea, and I will keep the one specified in rfc9002: the New Reno, and remove the CUBIC.
Quoted 182 lines
Quoted 100 lines
The implementation updates RTT estimates when packets are acknowledged, reacts to loss and ECN signals, and adjusts the congestion window accordingly during packet transmission and acknowledgment processing.
-
quic_cong_rtt_update(): Performs RTT measurement, invoked when a packet is acknowledged by the largest number in the ACK frame.-
quic_cong_on_packet_acked(): Invoked when a packet is acknowledged.-
quic_cong_on_packet_lost(): Invoked when a packet is marked as lost.-
quic_cong_on_process_ecn(): Invoked when anACK_ECNframe is received.-
quic_cong_on_packet_sent(): Invoked when a packet is transmitted.-
quic_cong_on_ack_recv(): Invoked when an ACK frame is received.Signed-off-by Xin Long <[email protected]>--- net/quic/Makefile | 3 +- net/quic/cong.c | 700 ++++++++++++++++++++++++++++++++++++++++++++++ net/quic/cong.h | 120 ++++++++ net/quic/socket.c | 1 + net/quic/socket.h | 7 + 5 files changed, 830 insertions(+), 1 deletion(-) create mode 100644 net/quic/cong.c create mode 100644 net/quic/cong.hnet/quic/Makefile +2
-1@@ -5,4 +5,5 @@ obj-$(CONFIG_IP_QUIC) += quic.o -quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o +quic-y := common.o family.o protocol.o socket.o stream.o connid.o path.o \ + cong.onet/quic/cong.c new file +54
-0@@ -0,0 +1,700 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Initialization/cleanup for QUIC protocol support. +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <linux/jiffies.h> +#include <linux/quic.h> +#include <net/sock.h> + +#include "common.h" +#include "cong.h" + +/* CUBIC APIs */ +struct quic_cubic { +/* Variables of Interest in rfc9438#section-4.1.2 */ +u32 pending_w_add;/* Accumulate fractional increments to W_est */ +u32 origin_point;/* W_max */ +u32 epoch_start;/* t_epoch */ +u32 pending_add;/* Accumulates fractional additions to W_cubic */ +u32 w_last_max;/* last W_max */ +u32 w_tcp;/* W_est */ +u64 k;/* K */ + +/* HyStart++ variables in rfc9406#section-4.2 */ +u32 current_round_min_rtt;/* currentRoundMinRTT */ +u32 css_baseline_min_rtt;/* cssBaselineMinRtt */ +u32 last_round_min_rtt;/* lastRoundMinRTT */ +u16 rtt_sample_count;/* rttSampleCount */ +u16 css_rounds;/* Counter for consecutive rounds showing RTT increase */ +s64 window_end;/* End of current CSS round (packet number) */ +}; + +/* HyStart++ constants in rfc9406#section-4.3 */ +#define QUIC_HS_MIN_SSTHRESH 16 +#define QUIC_HS_N_RTT_SAMPLE 8 +#define QUIC_HS_MIN_ETA 4000 +#define QUIC_HS_MAX_ETA 16000 +#define QUIC_HS_MIN_RTT_DIVISOR 8 +#define QUIC_HS_CSS_GROWTH_DIVISOR 4 +#define QUIC_HS_CSS_ROUNDS 5 + +static u64 cubic_root (u64 n) +{ +u64 a, d; + +if (!n) +return 0 ;net/quic/cong.c line 64
Quoted 10 lines
net/quic/cong.c new file +10
-0+ + d = (64 -__builtin_clzll (n)) /3 ; + a =BIT_ULL (d +1 ); + +for (; a * a * a > n;) { + d =div64_ul (n, a * a); + a =div64_ul (2 * a + d,3 ); + } +return a; +}
tcp_cubic()has already an helper to compute the square root. You could re-use that one.Quoted 68 lines
net/quic/cong.c new file +68
-0+ +/* rfc9406#section-4: HyStart++ Algorithm */ +static void cubic_slow_start (struct quic_cong *cong,u32 bytes,s64 number) +{ +struct quic_cubic *cubic =quic_cong_priv (cong); +u32 eta; + +if (cubic->window_end <= number) + cubic->window_end =-1 ; + +/* cwnd = cwnd + (min(N, L * SMSS) / CSS_GROWTH_DIVISOR) */ +if (cubic->css_baseline_min_rtt !=U32_MAX ) + bytes = bytes /QUIC_HS_CSS_GROWTH_DIVISOR ; + cong->window =min_t (u32, cong->window + bytes, cong->max_window); + +if (cubic->css_baseline_min_rtt !=U32_MAX ) { +/* If CSS_ROUNDS rounds are complete, enter congestion avoidance. */ +if (++cubic->css_rounds >QUIC_HS_CSS_ROUNDS ) { + cubic->css_baseline_min_rtt =U32_MAX ; + cubic->w_last_max = cong->window; + cong->ssthresh = cong->window; + cubic->css_rounds =0 ; + } +return ; + } + +/* if ((rttSampleCount >= N_RTT_SAMPLE) AND +* (currentRoundMinRTT != infinity) AND +* (lastRoundMinRTT != infinity)) +* RttThresh = max(MIN_RTT_THRESH, +* min(lastRoundMinRTT / MIN_RTT_DIVISOR, MAX_RTT_THRESH)) +* if (currentRoundMinRTT >= (lastRoundMinRTT + RttThresh)) +* cssBaselineMinRtt = currentRoundMinRTT +* exit slow start and enter CSS +*/ +if (cubic->last_round_min_rtt !=U32_MAX && + cubic->current_round_min_rtt !=U32_MAX && + cong->window >=QUIC_HS_MIN_SSTHRESH * cong->mss && + cubic->rtt_sample_count >=QUIC_HS_N_RTT_SAMPLE ) { + eta = cubic->last_round_min_rtt /QUIC_HS_MIN_RTT_DIVISOR ; +if (eta <QUIC_HS_MIN_ETA ) + eta =QUIC_HS_MIN_ETA ; +else if (eta >QUIC_HS_MAX_ETA ) + eta =QUIC_HS_MAX_ETA ; + +pr_debug ("%s: current_round_min_rtt: %u, last_round_min_rtt: %u, eta: %u\n" , + __func__, cubic->current_round_min_rtt, cubic->last_round_min_rtt, eta); + +/* Delay increase triggers slow start exit and enter CSS. */ +if (cubic->current_round_min_rtt >= cubic->last_round_min_rtt + eta) + cubic->css_baseline_min_rtt = cubic->current_round_min_rtt; + } +} + +/* rfc9438#section-4: CUBIC Congestion Control */ +static void cubic_cong_avoid (struct quic_cong *cong,u32 bytes) +{ +struct quic_cubic *cubic =quic_cong_priv (cong); +u64 tx, kx, time_delta, delta, t; +u64 target_add, tcp_add =0 ; +u64 target, cwnd_thres, m; + +if (cubic->epoch_start ==U32_MAX ) { + cubic->epoch_start = cong->time; +if (cong->window < cubic->w_last_max) { +/* +* ┌────────────────┐ +* 3 │W - cwnd
Quoted 8 lines
net/quic/cong.c line 138
Quoted 6 lines
net/quic/cong.c new file +6
-0+* ╲ │ max epoch +* K = ╲ │──────────────── +* ╲│ C +*/ + cubic->k = cubic->w_last_max - cong->window; + cubic->k =cubic_root (div64_ul (cubic->k *10 , (u64 )cong->mss *4 ));Can
mssbe 0 at this point? Why?
There is QUIC_PATH_MIN_PMTU (1200) defined. quic_flow_route() must be done and mss is calculated to set cong->mss via quic_cong_set_mss() based on pmtu before coming to this place.
It should be ensured on the 2nd patchset, I will double check it.
Quoted 63 lines
Quoted 63 lines
net/quic/cong.c new file +62
-0+ cubic->origin_point = cubic->w_last_max; + }else { + cubic->k =0 ; + cubic->origin_point = cong->window; + } + cubic->w_tcp = cong->window; + cubic->pending_add =0 ; + cubic->pending_w_add =0 ; + } + +/* +* t = t - t +* current epoch +*/ + t = cong->time - cubic->epoch_start; + tx =div64_ul (t <<10 ,USEC_PER_SEC ); + kx = (cubic->k <<10 ); +if (tx > kx) + time_delta = tx - kx; +else + time_delta = kx - tx; +/* +* 3 +* W (t) = C * (t - K) + W +* cubic max +*/ + delta = cong->mss * ((((time_delta * time_delta) >>10 ) * time_delta) >>10 ); + delta =div64_ul (delta *4 ,10 ) >>10 ; +if (tx > kx) + target = cubic->origin_point + delta; +else + target = cubic->origin_point - delta; + +/* +* W (t + RTT) +* cubic +*/ + cwnd_thres = (div64_ul ((t + cong->smoothed_rtt) <<10 ,USEC_PER_SEC ) * target) >>10 ; +pr_debug ("%s: tgt: %llu, thres: %llu, delta: %llu, t: %llu, srtt: %u, tx: %llu, kx: %llu\n" , + __func__, target, cwnd_thres, delta, t, cong->smoothed_rtt, tx, kx); +/* +* ⎧ +* ⎪cwnd if W (t + RTT) < cwnd +* ⎪ cubic +* ⎨1.5 * cwnd if W (t + RTT) > 1.5 * cwnd +* target = ⎪ cubic +* ⎪W (t + RTT) otherwise +* ⎩ cubic +*/ +if (cwnd_thres < cong->window) + target = cong->window; +else if (cwnd_thres *2 > (u64 )cong->window *3 ) + target = cong->window *3 /2 ; +else + target = cwnd_thres; + +/* +* target - cwnd +* ───────────── +* cwnd +*/ +if (target > cong->window) {
Quoted 8 lines
net/quic/cong.c line 206
Quoted 6 lines
net/quic/cong.c new file +6
-0+ target_add = cubic->pending_add + cong->mss * (target - cong->window); + cubic->pending_add =do_div (target_add, cong->window); + }else { + target_add = cubic->pending_add + cong->mss; + cubic->pending_add =do_div (target_add,100 * cong->window); + }Can
windowbe 0 here? why?
It should not. When changing cong->window, there's always a check to cong->min_window, which is set via quic_cong_set_mss().
Quoted 52 lines
Quoted 52 lines
net/quic/cong.c new file +51
-0+ +pr_debug ("%s: target: %llu, window: %u, target_add: %llu\n" , + __func__, target, cong->window, target_add); + +/* +* segments_acked +* W = W + α * ────────────── +* est est cubic cwnd +*/ + m = cubic->pending_w_add + cong->mss * bytes; + cubic->pending_w_add =do_div (m, cong->window); + cubic->w_tcp += m; + +if (cubic->w_tcp > cong->window) + tcp_add =div64_ul ((u64 )cong->mss * (cubic->w_tcp - cong->window), cong->window); + +pr_debug ("%s: w_tcp: %u, window: %u, tcp_add: %llu\n" , + __func__, cubic->w_tcp, cong->window, tcp_add); + +/* W_cubic(_t_) or _W_est_, whichever is bigger. */ + cong->window +=max (tcp_add, target_add); +} + +static void cubic_recovery (struct quic_cong *cong) +{ +struct quic_cubic *cubic =quic_cong_priv (cong); + + cong->recovery_time = cong->time; + cubic->epoch_start =U32_MAX ; + +/* rfc9438#section-3.4: +* CUBIC sets the multiplicative window decrease factor (β__cubic_) to 0.7, +* whereas Reno uses 0.5. +* +* rfc9438#section-4.6: +* ssthresh = flight_size * β new ssthresh +* +* Some implementations of CUBIC currently use _cwnd_ instead of _flight_size_ when +* calculating a new _ssthresh_. +* +* rfc9438#section-4.7: +* +* ⎧ 1 + β +* ⎪ cubic +* ⎪cwnd * ────────── if cwnd < W_max and fast convergence +* W = ⎨ 2 +* max ⎪ enabled, further reduce W_max +* ⎪ +* ⎩cwnd otherwise, remember cwnd before reduction +*/ +if (cong->window < cubic->w_last_max)
Quoted 8 lines
net/quic/cong.c line 262
Quoted 5 lines
net/quic/cong.c new file +5
-0+ cubic->w_last_max = cong->window *17 /10 /2 ; + else + cubic->w_last_max = cong->window; + + cong->ssthresh = cong->window *7 /10 ;There are quite a bit of magic numbers that should be replaced by macros and/or associated with explainatory comments.
Yes, better to use macros.
I was expecting people to understand if from the comment I put in above.
Quoted 45 lines
Quoted 45 lines
net/quic/cong.c new file +44
-0+ +/* rfc9002#section-5: Estimating the Round-Trip Time */ +void quic_cong_rtt_update (struct quic_cong *cong,u32 time,u32 ack_delay) +{ +u32 adjusted_rtt, rttvar_sample; + +/* Ignore RTT sample if ACK delay is suspiciously large. */ +if (ack_delay > cong->max_ack_delay *2 ) +return ; + +/* rfc9002#section-5.1: latest_rtt = ack_time - send_time_of_largest_acked */ + cong->latest_rtt = cong->time - time; + +/* rfc9002#section-5.2: Estimating min_rtt */ +if (!cong->min_rtt_valid) { + cong->min_rtt = cong->latest_rtt; + cong->min_rtt_valid =1 ; + } +if (cong->min_rtt > cong->latest_rtt) + cong->min_rtt = cong->latest_rtt; + +if (!cong->is_rtt_set) { +/* rfc9002#section-5.3: +* smoothed_rtt = latest_rtt +* rttvar = latest_rtt / 2 +*/ + cong->smoothed_rtt = cong->latest_rtt; + cong->rttvar = cong->smoothed_rtt /2 ; +quic_cong_pto_update (cong); + cong->is_rtt_set =1 ; +return ; + } + +/* rfc9002#section-5.3: +* adjusted_rtt = latest_rtt +* if (latest_rtt >= min_rtt + ack_delay): +* adjusted_rtt = latest_rtt - ack_delay +* smoothed_rtt = 7/8 * smoothed_rtt + 1/8 * adjusted_rtt +* rttvar_sample = abs(smoothed_rtt - adjusted_rtt) +* rttvar = 3/4 * rttvar + 1/4 * rttvar_sample +*/ + adjusted_rtt = cong->latest_rtt; +if (cong->latest_rtt >= cong->min_rtt + ack_delay) + adjusted_rtt = cong->latest_rtt - ack_delay;
Quoted 8 lines
net/quic/cong.c line 663
Quoted 6 lines
net/quic/cong.c new file +6
-0+ + cong->smoothed_rtt = (cong->smoothed_rtt *7 + adjusted_rtt) /8 ; +if (cong->smoothed_rtt >= adjusted_rtt) + rttvar_sample = cong->smoothed_rtt - adjusted_rtt; +else + rttvar_sample = adjusted_rtt - cong->smoothed_rtt;Here in a few other place before you could use
abs_diff()
Sure.
Thanks.
Paolo Abeni
maintainerRe: [PATCH net-next v3 03/15] quic: provide common utilities and data structures
In reply to Xin LongQuoted 17 lines · Xin Long
Quoted 16 lines · Paolo Abeni
net/quic/common.c line 144
Quoted 11 lines · Xin Long
net/quic/common.c new file +11
-0+static int quic_uhash_table_init (struct quic_uhash_table *ht,u32 max_size,int order) +{ +int i, max_order, size; + +/* Same sizing logic as in quic_shash_table_init(). */ + max_order =get_order (max_size *sizeof (struct quic_uhash_head )); + order =min (order, max_order); +do { + ht->hash = (struct quic_uhash_head *) +__get_free_pages (GFP_KERNEL | __GFP_NOWARN, order); + }while (!ht->hash && --order >0 );You can avoid a little complexity, and see more consistent behaviour, using plain
vmalloc()oralloc_large_system_hash()with no fallback.
Quoted 6 lines
I wanted to use
alloc_large_system_hash(), but the memory allocated by it is usually NOT meant to be freed at runtime. I don't see afree_function to do it either.If QUIC works as a kernel module, what should I do with this memory in
module_exit()?
Right, I did not think about such case. I suggest using a plain vmalloc() without the loop than.
Quoted 22 lines
Quoted 13 lines
Quoted 13 lines
net/quic/common.c new file +13
-0+/* rfc9000#section-a.3: DecodePacketNumber() +* +* Reconstructs the full packet number from a truncated one. +*/ +s64 quic_get_num (s64 max_pkt_num,s64 pkt_num,u32 n) +{ +s64 expected = max_pkt_num +1 ; +s64 win =BIT_ULL (n *8 ); +s64 hwin = win /2 ; +s64 mask = win -1 ; +s64 cand; + + cand = (expected & ~mask) | pkt_num;Quoted 9 lines
net/quic/common.c line 428
Quoted 5 lines
net/quic/common.c new file +5
-0+if (cand <= expected - hwin && cand < (1ULL <<62 ) - win) +return cand + win; +if (cand > expected + hwin && cand >= win) +return cand - win; +return cand;The above is a bit obscure to me; replacing magic nubers (62) with macro could help. Some more comments also would do.
Quoted 7 lines
The code is exactly from the commented doc:
/* rfc9000#section-a.3:DecodePacketNumber()See:
https://datatracker.ietf.org/doc/html/rfc9000#section-a.3I will bring some comments from there.
You can quote or make a synopsis of the RFC where it makes sense. In any case, please try to reduce magic numbers usage.
Thanks,
Paolo
Paolo Abeni
maintainerRe: [PATCH net-next v3 02/15] net: build socket infrastructure for QUIC protocol
In reply to Xin LongQuoted 222 lines · Xin Long
Quoted 159 lines · Paolo Abeni
Quoted 157 lines · Xin Long
This patch lays the groundwork for QUIC socket support in the kernel. It defines the core structures and protocol hooks needed to create QUIC sockets, without implementing any protocol behavior at this stage.
Basic integration is included to allow building the module via
CONFIG_IP_QUIC=m.This provides the scaffolding necessary for adding actual QUIC socket behavior in follow-up patches.
Signed-off-by Pengtao He <[email protected]>Signed-off-by Xin Long <[email protected]>---
v3:
-Kconfig: add 'default n' forIP_QUIC(reported by Paolo).
-quic_disconnect(): return-EOPNOTSUPP(suggested by Paolo).
- quic_init/destroy_sock(): drop local_bh_disable/enable() calls (noted by Paolo).
- sysctl: addalpn_demuxoption to en/disable ALPN-based demux.
- SNMP: removeSNMP_MIB_SENTINEL, switch tosnmp_get_cpu_field_batch_cnt()to align with latest net-next changes.--- net/Kconfig | 1 + net/Makefile | 1 + net/quic/Kconfig | 36 +++++ net/quic/Makefile | 8 + net/quic/protocol.c | 379 ++++++++++++++++++++++++++++++++++++++++++++ net/quic/protocol.h | 56 +++++++ net/quic/socket.c | 207 ++++++++++++++++++++++++ net/quic/socket.h | 79 +++++++++ 8 files changed, 767 insertions(+) create mode 100644 net/quic/Kconfig create mode 100644 net/quic/Makefile create mode 100644 net/quic/protocol.c create mode 100644 net/quic/protocol.h create mode 100644 net/quic/socket.c create mode 100644 net/quic/socket.hnet/Kconfig +1
-0@@ -249,6 +249,7 @@ source "net/bridge/netfilter/Kconfig" endif # if NETFILTER +source "net/quic/Kconfig" source "net/sctp/Kconfig" source "net/rds/Kconfig" source "net/tipc/Kconfig"net/Makefile +1
-0@@ -42,6 +42,7 @@ obj-$(CONFIG_PHONET) += phonet/ ifneq ($(CONFIG_VLAN_8021Q),) obj-y += 8021q/ endif +obj-$(CONFIG_IP_QUIC) += quic/ obj-$(CONFIG_IP_SCTP) += sctp/ obj-$(CONFIG_RDS) += rds/ obj-$(CONFIG_WIRELESS) += wireless/net/quic/Kconfig new file +36
-0@@ -0,0 +1,36 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# QUIC configuration +# + +menuconfig IP_QUIC + tristate "QUIC: A UDP-Based Multiplexed and Secure Transport (Experimental)" + depends on INET + depends on IPV6 + select CRYPTO + select CRYPTO_HMAC + select CRYPTO_HKDF + select CRYPTO_AES + select CRYPTO_GCM + select CRYPTO_CCM + select CRYPTO_CHACHA20POLY1305 + select NET_UDP_TUNNEL + default n + help + QUIC: A UDP-Based Multiplexed and Secure Transport + + From rfc9000 <https://www.rfc-editor.org/rfc/rfc9000.html>. + + QUIC provides applications with flow-controlled streams for structured + communication, low-latency connection establishment, and network path + migration. QUIC includes security measures that ensure + confidentiality, integrity, and availability in a range of deployment + circumstances. Accompanying documents describe the integration of + TLS for key negotiation, loss detection, and an exemplary congestion + control algorithm. + + To compile this protocol support as a module, choose M here: the + module will be called quic. Debug messages are handled by the + kernel's dynamic debugging framework. + + If in doubt, say N.net/quic/Makefile new file +8
-0@@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Makefile for QUIC support code. +# + +obj-$(CONFIG_IP_QUIC) += quic.o + +quic-y := protocol.o socket.onet/quic/protocol.c new file +33
-0@@ -0,0 +1,379 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Initialization/cleanup for QUIC protocol support. +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <net/inet_common.h> +#include <linux/proc_fs.h> +#include <net/protocol.h> +#include <net/rps.h> +#include <net/tls.h> + +#include "socket.h" + +static unsigned int quic_net_id__read_mostly ; + +struct percpu_counter quic_sockets_allocated; + +long sysctl_quic_mem[3 ]; +int sysctl_quic_rmem[3 ]; +int sysctl_quic_wmem[3 ]; +int sysctl_quic_alpn_demux; + +static int quic_inet_connect (struct socket *sock,struct sockaddr *addr,int addr_len,int flags) +{ +struct sock *sk = sock->sk; +const struct proto *prot;Quoted 8 lines
net/quic/protocol.c line 38
Quoted 5 lines
net/quic/protocol.c new file +5
-0+ +if (addr_len < (int )sizeof (addr->sa_family)) +return -EINVAL ; + + prot =READ_ONCE (sk->sk_prot);Is the above
_ONCE()annotation for ADDRFORM's sake? If so it should not be needed (only UDP and TCP sockets are affected).I will delete it.
Quoted 25 lines
Quoted 25 lines
net/quic/socket.h new file +18
-0@@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* QUIC kernel implementation +* (C) Copyright Red Hat Corp. 2023 +* +* This file is part of the QUIC kernel implementation +* +* Written or modified by: +* Xin Long <[email protected]> +*/ + +#include <net/udp_tunnel.h> + +#include "protocol.h" + +extern struct proto quic_prot; +extern struct proto quicv6_prot; + +enum quic_state {Quoted 9 lines
net/quic/socket.h line 23
Quoted 5 lines
net/quic/socket.h new file +5
-0+QUIC_SS_CLOSED =TCP_CLOSE , +QUIC_SS_LISTENING =TCP_LISTEN , +QUIC_SS_ESTABLISHING =TCP_SYN_RECV , + QUIC_SS_ESTABLISHED = TCP_ESTABLISHED, +};Any special reason to define protocol-specific states? I guess you could re-use the TCP ones, as other protocols already do.
I know TIPC and SCTP define the states like this:
enum {
TIPC_LISTEN=TCP_LISTEN,
TIPC_ESTABLISHED=TCP_ESTABLISHED,
TIPC_OPEN=TCP_CLOSE,
TIPC_DISCONNECTING=TCP_CLOSE_WAIT,
TIPC_CONNECTING=TCP_SYN_SENT,
};and
enum
sctp_sock_state{SCTP_SS_CLOSED = TCP_CLOSE, SCTP_SS_LISTENING = TCP_LISTEN, SCTP_SS_ESTABLISHING = TCP_SYN_SENT, SCTP_SS_ESTABLISHED = TCP_ESTABLISHED, SCTP_SS_CLOSING = TCP_CLOSE_WAIT,
Quoted 4 lines
};
It should be fine to keep as is, or you have more and better examples from other protocols.
IMHO the cost/benfit ratio to re-define the socket state value is in not enough to justify the additional LoC. I guess it's subjective, but the patch series is big and anything shrinking it is IMHO a good thing.
/P
Paolo Abeni
maintainerRe: [PATCH net-next v3 06/15] quic: add stream management
In reply to Xin LongQuoted 24 lines · Xin Long
Quoted 15 lines · Paolo Abeni
Quoted 14 lines · Xin Long
net/quic/stream.c new file +14
-0+/* Create and register new streams for sending. */ +static struct quic_stream *quic_stream_send_create (struct quic_stream_table *streams, +s64 max_stream_id,u8 is_serv) +{ +struct quic_stream *stream; +s64 stream_id; + + stream_id = streams->send.next_bidi_stream_id; +if (quic_stream_id_uni (max_stream_id)) + stream_id = streams->send.next_uni_stream_id; + +/* rfc9000#section-2.1: A stream ID that is used out of order results in all streams +* of that type with lower-numbered stream IDs also being opened. +*/ Quoted 8 lines
net/quic/stream.c line 88
Quoted 4 lines
net/quic/stream.c new file +4
-0+while (stream_id <= max_stream_id) { + stream =kzalloc (sizeof (*stream),GFP_KERNEL ); +if (!stream) +return NULL ;How many streams and connections ID do you foresee per socket? Could such number grow significantly (possibly under misuse/attack)? If so you you likely use
GFP_KERNEL_ACCOUNThere (and inconn_idallocation).
Quoted 2 lines
connections ID: 8 (
QUIC_CONN_ID_LIMIT) at most per socket.
streams: 4096 (QUIC_MAX_STREAMS) at most per socket.
Will such limit fit a (very) busy server? I guess it's more a question those who already run quic workload at scale...
Quoted 5 lines
I can switch to
GFP_KERNEL_ACCOUNTinquic_stream_send_create().For
quic_stream_recv_create(), it’s typically invoked in atomic context. Since there’s no predefinedGFP_ATOMIC_ACCOUNT, I assume using (GFP_ATOMIC|__GFP_ACCOUNT) should be acceptable.
I see there are already a few other allocations using such flags, and I could not find any explicit limitation/drawback for it. I hope it's not just cargo cult programming :-P
/P