The SO_REUSEPORT option allows sockets to listen on the same port and to
accept connections evenly. However, there is a defect in the current
implementation[1]. When a SYN packet is received, the connection is tied to
a listening socket. Accordingly, when the listener is closed, in-flight
requests during the three-way handshake and child sockets in the accept
queue are dropped even if other listeners on the same port could accept
such connections.
This situation can happen when various server management tools restart
server (such as nginx) processes. For instance, when we change nginx
configurations and restart it, it spins up new workers that respect the new
configuration and closes all listeners on the old workers, resulting in the
in-flight ACK of 3WHS is responded by RST.
The SO_REUSEPORT option is excellent to improve scalability. On the other
hand, as a trade-off, users have to know deeply how the kernel handles SYN
packets and implement connection draining by eBPF[2]:
1. Stop routing SYN packets to the listener by eBPF.
2. Wait for all timers to expire to complete requests
3. Accept connections until EAGAIN, then close the listener.
or
1. Start counting SYN packets and accept syscalls using eBPF map.
2. Stop routing SYN packets.
3. Accept connections up to the count, then close the listener.
In either way, we cannot close a listener immediately. However, ideally,
the application need not drain the not yet accepted sockets because 3WHS
and tying a connection to a listener are just the kernel behaviour. The
root cause is within the kernel, so the issue should be addressed in kernel
space and should not be visible to user space. This patchset fixes it so
that users need not take care of kernel implementation and connection
draining. With this patchset, the kernel redistributes requests and
connections from a listener to others in the same reuseport group at/after
close() or shutdown() syscalls.
Although some software does connection draining, there are still merits in
migration. For some security reasons such as replacing TLS certificates, we
may want to apply new settings as soon as possible and/or we may not be
able to wait for connection draining. The sockets in the accept queue have
not started application sessions yet. So, if we do not drain such sockets,
they can be handled by the newer listeners and could have a longer
lifetime. It is difficult to drain all connections in every case, but we
can decrease such aborted connections by migration. In that sense,
migration is always better than draining.
Moreover, auto-migration simplifies userspace logic and also works well in
a case where we cannot modify and build a server program to implement the
workaround.
Note that the source and destination listeners MUST have the same settings
at the socket API level; otherwise, applications may face inconsistency and
cause errors. In such a case, we have to use eBPF program to select a
specific listener or to cancel migration.
Link:
[1] The SO_REUSEPORT socket option
https://lwn.net/Articles/542629/
[2] Re: [PATCH 1/1] net: Add SO_REUSEPORT_LISTEN_OFF socket option as drain mode
https://lore.kernel.org/netdev/1458828813.10868.65.camel@edumazet-glaptop3.roam.corp.google.com/
Changelog:
v1:
* Remove the sysctl option
* Enable migration if eBPF progam is not attached
* Add expected_attach_type to check if eBPF program can migrate sockets
* Add a field to tell migration type to eBPF program
* Support BPF_FUNC_get_socket_cookie to get the cookie of sk
* Allocate an empty skb if skb is NULL
* Pass req_to_sk(req)->sk_hash because listener's hash is zero
* Update commit messages and coverletter
RFC v0:
https://lore.kernel.org/netdev/20201117094023.3685-1-kuniyu@amazon.co.jp/
Kuniyuki Iwashima (11):
tcp: Keep TCP_CLOSE sockets in the reuseport group.
bpf: Define migration types for SO_REUSEPORT.
tcp: Migrate TCP_ESTABLISHED/TCP_SYN_RECV sockets in accept queues.
tcp: Migrate TFO requests causing RST during TCP_SYN_RECV.
tcp: Migrate TCP_NEW_SYN_RECV requests.
bpf: Introduce two attach types for BPF_PROG_TYPE_SK_REUSEPORT.
libbpf: Set expected_attach_type for BPF_PROG_TYPE_SK_REUSEPORT.
bpf: Add migration to sk_reuseport_(kern|md).
bpf: Support bpf_get_socket_cookie_sock() for
BPF_PROG_TYPE_SK_REUSEPORT.
bpf: Call bpf_run_sk_reuseport() for socket migration.
bpf: Test BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
include/linux/bpf.h | 1 +
include/linux/filter.h | 4 +-
include/net/inet_connection_sock.h | 13 ++
include/net/request_sock.h | 13 ++
include/net/sock_reuseport.h | 15 +-
include/uapi/linux/bpf.h | 25 +++
kernel/bpf/syscall.c | 8 +
net/core/filter.c | 46 ++++-
net/core/sock_reuseport.c | 128 +++++++++++---
net/ipv4/inet_connection_sock.c | 85 ++++++++-
net/ipv4/inet_hashtables.c | 9 +-
net/ipv4/tcp_ipv4.c | 9 +-
net/ipv6/tcp_ipv6.c | 9 +-
tools/include/uapi/linux/bpf.h | 25 +++
tools/lib/bpf/libbpf.c | 5 +-
.../bpf/prog_tests/migrate_reuseport.c | 164 ++++++++++++++++++
.../bpf/progs/test_migrate_reuseport_kern.c | 54 ++++++
17 files changed, 565 insertions(+), 48 deletions(-)
create mode 100644 tools/testing/selftests/bpf/prog_tests/migrate_reuseport.c
create mode 100644 tools/testing/selftests/bpf/progs/test_migrate_reuseport_kern.c
--
2.17.2 (Apple Git-113)
As noted in the preceding commit, there are two migration types. In
addition to that, the kernel will run the same eBPF program to select a
listener for SYN packets.
This patch defines three types to signal the kernel and the eBPF program if
it is receiving a new request or migrating ESTABLISHED/SYN_RECV sockets in
the accept queue or NEW_SYN_RECV socket during 3WHS.
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 14 ++++++++++++++
tools/include/uapi/linux/bpf.h | 14 ++++++++++++++
2 files changed, 28 insertions(+)
This patch is a preparation patch to migrate incoming connections in the
later commits and adds a field (num_closed_socks) to the struct
sock_reuseport to keep TCP_CLOSE sockets in the reuseport group.
When we close a listening socket, to migrate its connections to another
listener in the same reuseport group, we have to handle two kinds of child
sockets. One is that a listening socket has a reference to, and the other
is not.
The former is the TCP_ESTABLISHED/TCP_SYN_RECV sockets, and they are in the
accept queue of their listening socket. So, we can pop them out and push
them into another listener's queue at close() or shutdown() syscalls. On
the other hand, the latter, the TCP_NEW_SYN_RECV socket is during the
three-way handshake and not in the accept queue. Thus, we cannot access
such sockets at close() or shutdown() syscalls. Accordingly, we have to
migrate immature sockets after their listening socket has been closed.
Currently, if their listening socket has been closed, TCP_NEW_SYN_RECV
sockets are freed at receiving the final ACK or retransmitting SYN+ACKs. At
that time, if we could select a new listener from the same reuseport group,
no connection would be aborted. However, it is impossible because
reuseport_detach_sock() sets NULL to sk_reuseport_cb and forbids access to
the reuseport group from closed sockets.
This patch allows TCP_CLOSE sockets to remain in the reuseport group and to
have access to it while any child socket references to them. The point is
that reuseport_detach_sock() is called twice from inet_unhash() and
sk_destruct(). At first, it moves the socket backwards in socks[] and
increments num_closed_socks. Later, when all migrated connections are
accepted, it removes the socket from socks[], decrements num_closed_socks,
and sets NULL to sk_reuseport_cb.
By this change, closed sockets can keep sk_reuseport_cb until all child
requests have been freed or accepted. Consequently calling listen() after
shutdown() can cause EADDRINUSE or EBUSY in reuseport_add_sock() or
inet_csk_bind_conflict() which expect that such sockets should not have the
reuseport group. Therefore, this patch also loosens such validation rules
so that the socket can listen again if it has the same reuseport group with
other listening sockets.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/sock_reuseport.h | 5 ++-
net/core/sock_reuseport.c | 79 +++++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 7 ++-
3 files changed, 74 insertions(+), 17 deletions(-)
@@ -13,8 +13,9 @@ extern spinlock_t reuseport_lock;structsock_reuseport{structrcu_headrcu;-u16max_socks;/* length of socks */-u16num_socks;/* elements in socks */+u16max_socks;/* length of socks */+u16num_socks;/* elements in socks */+u16num_closed_socks;/* closed elements in socks *//* The last synq overflow event timestamp of this*reuse->socks[]group.*/
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
A TFO request socket is only freed after BOTH 3WHS has completed (or
aborted) and the child socket has been accepted (or its listener has been
closed). Hence, depending on the order, there can be two kinds of request
sockets in the accept queue.
3WHS -> accept : TCP_ESTABLISHED
accept -> 3WHS : TCP_SYN_RECV
Unlike TCP_ESTABLISHED socket, accept() does not free the request socket
for TCP_SYN_RECV socket. It is freed later at reqsk_fastopen_remove().
Also, it accesses request_sock.rsk_listener. So, in order to complete TFO
socket migration, we have to set the current listener to it at accept()
before reqsk_fastopen_remove().
Moreover, if TFO request caused RST before 3WHS has completed, it is held
in the listener's TFO queue to prevent DDoS attack. Thus, we also have to
migrate the requests in TFO queue.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
net/ipv4/inet_connection_sock.c | 35 ++++++++++++++++++++++++++++++++-
1 file changed, 34 insertions(+), 1 deletion(-)
@@ -500,6 +500,16 @@ struct sock *inet_csk_accept(struct sock *sk, int flags, int *err, bool kern)tcp_rsk(req)->tfo_listener){spin_lock_bh(&queue->fastopenq.lock);if(tcp_rsk(req)->tfo_listener){+if(req->rsk_listener!=sk){+/* TFO request was migrated to another listener so+*thenewlistenermustbeusedinreqsk_fastopen_remove()+*toholdrequestswhichcauseRST.+*/+sock_put(req->rsk_listener);+sock_hold(sk);+req->rsk_listener=sk;+}+/* We are still waiting for the final ACK from 3WHS*socan'tfreereqnow.Instead,wesetreq->skto*NULLtosignifythatthechildsocketistaken
This patch renames reuseport_select_sock() to __reuseport_select_sock() and
adds two wrapper function of it to pass the migration type defined in the
previous commit.
reuseport_select_sock : BPF_SK_REUSEPORT_MIGRATE_NO
reuseport_select_migrated_sock : BPF_SK_REUSEPORT_MIGRATE_REQUEST
As mentioned before, we have to select a new listener for TCP_NEW_SYN_RECV
requests at receiving the final ACK or sending a SYN+ACK. Therefore, this
patch also changes the code to call reuseport_select_migrated_sock() even
if the listening socket is TCP_CLOSE. If we can pick out a listening socket
from the reuseport group, we rewrite request_sock.rsk_listener and resume
processing the request.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 12 +++++++++++
include/net/request_sock.h | 13 ++++++++++++
include/net/sock_reuseport.h | 8 +++----
net/core/sock_reuseport.c | 34 ++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 13 ++++++++++--
net/ipv4/tcp_ipv4.c | 9 ++++++--
net/ipv6/tcp_ipv6.c | 9 ++++++--
7 files changed, 81 insertions(+), 17 deletions(-)
@@ -202,7 +202,7 @@ int reuseport_add_sock(struct sock *sk, struct sock *sk2, bool bind_inany)}reuse->socks[reuse->num_socks]=sk;-/* paired with smp_rmb() in reuseport_select_sock() */+/* paired with smp_rmb() in __reuseport_select_sock() */smp_wmb();reuse->num_socks++;rcu_assign_pointer(sk->sk_reuseport_cb,reuse);
@@ -743,8 +743,17 @@ static void reqsk_timer_handler(struct timer_list *t)structrequest_sock_queue*queue=&icsk->icsk_accept_queue;intmax_syn_ack_retries,qlen,expire=0,resend=0;-if(inet_sk_state_load(sk_listener)!=TCP_LISTEN)-gotodrop;+if(inet_sk_state_load(sk_listener)!=TCP_LISTEN){+sk_listener=reuseport_select_migrated_sock(sk_listener,+req_to_sk(req)->sk_hash,NULL);+if(!sk_listener){+sk_listener=req->rsk_listener;+gotodrop;+}+inet_csk_reqsk_queue_migrated(req->rsk_listener,sk_listener,req);+icsk=inet_csk(sk_listener);+queue=&icsk->icsk_accept_queue;+}max_syn_ack_retries=icsk->icsk_syn_retries?:net->ipv4.sysctl_tcp_synack_retries;/* Normally all the openreqs are young and become mature
@@ -1973,8 +1973,13 @@ int tcp_v4_rcv(struct sk_buff *skb)gotocsum_error;}if(unlikely(sk->sk_state!=TCP_LISTEN)){-inet_csk_reqsk_queue_drop_and_put(sk,req);-gotolookup;+nsk=reuseport_select_migrated_sock(sk,req_to_sk(req)->sk_hash,skb);+if(!nsk){+inet_csk_reqsk_queue_drop_and_put(sk,req);+gotolookup;+}+inet_csk_reqsk_queue_migrated(sk,nsk,req);+sk=nsk;}/* We own a reference on the listener, increase it again*aswemightloseittoosoon.
This commit adds new bpf_attach_type for BPF_PROG_TYPE_SK_REUSEPORT to
check if the attached eBPF program is capable of migrating sockets.
When the eBPF program is attached, the kernel runs it for socket migration
only if the expected_attach_type is BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
The kernel will change the behaviour depending on the returned value:
- SK_PASS with selected_sk, select it as a new listener
- SK_PASS with selected_sk NULL, fall back to the random selection
- SK_DROP, cancel the migration
Link: https://lore.kernel.org/netdev/20201123003828.xjpjdtk4ygl6tg6h@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 2 ++
kernel/bpf/syscall.c | 8 ++++++++
tools/include/uapi/linux/bpf.h | 2 ++
3 files changed, 12 insertions(+)
This commit introduces a new section (sk_reuseport/migrate) and sets
expected_attach_type to two each section in BPF_PROG_TYPE_SK_REUSEPORT
program.
Signed-off-by: Kuniyuki Iwashima <redacted>
---
tools/lib/bpf/libbpf.c | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
This patch adds u8 migration field to sk_reuseport_kern and sk_reuseport_md
to signal the eBPF program if the kernel calls it for selecting a listener
for SYN or migrating sockets in the accept queue or an immature socket
during 3WHS.
Note that this field is accessible only if the attached type is
BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
Link: https://lore.kernel.org/netdev/20201123003828.xjpjdtk4ygl6tg6h@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/linux/bpf.h | 1 +
include/linux/filter.h | 4 ++--
include/uapi/linux/bpf.h | 1 +
net/core/filter.c | 15 ++++++++++++---
net/core/sock_reuseport.c | 2 +-
tools/include/uapi/linux/bpf.h | 1 +
6 files changed, 18 insertions(+), 6 deletions(-)
@@ -4419,6 +4419,7 @@ struct sk_reuseport_md {__u32ip_protocol;/* IP protocol. e.g. IPPROTO_TCP, IPPROTO_UDP */__u32bind_inany;/* Is sock bound to an INANY address? */__u32hash;/* A hash of the packet 4 tuples */+__u8migration;/* Migration type */};#define BPF_TAG_SIZE 8
@@ -4419,6 +4419,7 @@ struct sk_reuseport_md {__u32ip_protocol;/* IP protocol. e.g. IPPROTO_TCP, IPPROTO_UDP */__u32bind_inany;/* Is sock bound to an INANY address? */__u32hash;/* A hash of the packet 4 tuples */+__u8migration;/* Migration type */};#define BPF_TAG_SIZE 8
We will call sock_reuseport.prog for socket migration in the next commit,
so the eBPF program has to know which listener is closing in order to
select the new listener.
Currently, we can get a unique ID for each listener in the userspace by
calling bpf_map_lookup_elem() for BPF_MAP_TYPE_REUSEPORT_SOCKARRAY map.
This patch makes the sk pointer available in sk_reuseport_md so that we can
get the ID by BPF_FUNC_get_socket_cookie() in the eBPF program.
Link: https://lore.kernel.org/netdev/20201119001154.kapwihc2plp4f7zc@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 8 ++++++++
net/core/filter.c | 12 +++++++++++-
tools/include/uapi/linux/bpf.h | 8 ++++++++
3 files changed, 27 insertions(+), 1 deletion(-)
@@ -1650,6 +1650,13 @@ union bpf_attr {*A8-bytelongnon-decreasingnumberonsuccess,or0ifthe*socketfieldismissinginside*skb*.*+*u64bpf_get_socket_cookie(structbpf_sock*sk)+*Description+*Equivalenttobpf_get_socket_cookie()helperthataccepts+**skb*,butgetssocketfrom**structbpf_sock**context.+*Return+*A8-bytelongnon-decreasingnumber.+**u64bpf_get_socket_cookie(structbpf_sock_addr*ctx)*Description*Equivalenttobpf_get_socket_cookie()helperthataccepts
@@ -4420,6 +4427,7 @@ struct sk_reuseport_md {__u32bind_inany;/* Is sock bound to an INANY address? */__u32hash;/* A hash of the packet 4 tuples */__u8migration;/* Migration type */+__bpf_md_ptr(structbpf_sock*,sk);/* current listening socket */};#define BPF_TAG_SIZE 8
@@ -1650,6 +1650,13 @@ union bpf_attr {*A8-bytelongnon-decreasingnumberonsuccess,or0ifthe*socketfieldismissinginside*skb*.*+*u64bpf_get_socket_cookie(structbpf_sock*sk)+*Description+*Equivalenttobpf_get_socket_cookie()helperthataccepts+**skb*,butgetssocketfrom**structbpf_sock**context.+*Return+*A8-bytelongnon-decreasingnumber.+**u64bpf_get_socket_cookie(structbpf_sock_addr*ctx)*Description*Equivalenttobpf_get_socket_cookie()helperthataccepts
@@ -4420,6 +4427,7 @@ struct sk_reuseport_md {__u32bind_inany;/* Is sock bound to an INANY address? */__u32hash;/* A hash of the packet 4 tuples */__u8migration;/* Migration type */+__bpf_md_ptr(structbpf_sock*,sk);/* current listening socket */};#define BPF_TAG_SIZE 8
This patch supports socket migration by eBPF. If the attached type is
BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, we can select a new listener by
BPF_FUNC_sk_select_reuseport(). Also, we can cancel migration by returning
SK_DROP. This feature is useful when listeners have different settings at
the socket API level or when we want to free resources as soon as possible.
There are two noteworthy points. The first is that we select a listening
socket in reuseport_detach_sock() and __reuseport_select_sock(), but we do
not have struct skb at closing a listener or retransmitting a SYN+ACK.
However, some helper functions do not expect skb is NULL (e.g.
skb_header_pointer() in BPF_FUNC_skb_load_bytes(), skb_tail_pointer() in
BPF_FUNC_skb_load_bytes_relative()). So, we allocate an empty skb
temporarily before running the eBPF program. The second is that we do not
have struct request_sock in unhash path, and the sk_hash of the listener is
always zero. Thus, we pass zero as hash to bpf_run_sk_reuseport().
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
net/core/filter.c | 19 +++++++++++++++++++
net/core/sock_reuseport.c | 19 ++++++++++---------
net/ipv4/inet_hashtables.c | 2 +-
3 files changed, 30 insertions(+), 10 deletions(-)
@@ -9871,10 +9871,29 @@ struct sock *bpf_run_sk_reuseport(struct sock_reuseport *reuse, struct sock *sk,{structsk_reuseport_kernreuse_kern;enumsk_actionaction;+boolallocated=false;++if(migration){+/* cancel migration for possibly incapable eBPF program */+if(prog->expected_attach_type!=BPF_SK_REUSEPORT_SELECT_OR_MIGRATE)+returnERR_PTR(-ENOTSUPP);++if(!skb){+allocated=true;+skb=alloc_skb(0,GFP_ATOMIC);+if(!skb)+returnERR_PTR(-ENOMEM);+}+}elseif(!skb){+returnNULL;/* fall back to select by hash */+}bpf_init_reuseport_kern(&reuse_kern,reuse,sk,skb,hash,migration);action=BPF_PROG_RUN(prog,&reuse_kern);+if(allocated)+kfree_skb(skb);+if(action==SK_PASS)returnreuse_kern.selected_sk;else
From: Eric Dumazet <hidden> Date: 2020-12-01 15:14:31
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted hunk
This patch renames reuseport_select_sock() to __reuseport_select_sock() and
adds two wrapper function of it to pass the migration type defined in the
previous commit.
reuseport_select_sock : BPF_SK_REUSEPORT_MIGRATE_NO
reuseport_select_migrated_sock : BPF_SK_REUSEPORT_MIGRATE_REQUEST
As mentioned before, we have to select a new listener for TCP_NEW_SYN_RECV
requests at receiving the final ACK or sending a SYN+ACK. Therefore, this
patch also changes the code to call reuseport_select_migrated_sock() even
if the listening socket is TCP_CLOSE. If we can pick out a listening socket
from the reuseport group, we rewrite request_sock.rsk_listener and resume
processing the request.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 12 +++++++++++
include/net/request_sock.h | 13 ++++++++++++
include/net/sock_reuseport.h | 8 +++----
net/core/sock_reuseport.c | 34 ++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 13 ++++++++++--
net/ipv4/tcp_ipv4.c | 9 ++++++--
net/ipv6/tcp_ipv6.c | 9 ++++++--
7 files changed, 81 insertions(+), 17 deletions(-)
This looks racy to me. nsk refcount might be zero at this point.
If you think it can _not_ be zero, please add a big comment here,
because this would mean something has been done before reaching this function,
and this sock_hold() would be not needed in the first place.
There is a good reason reqsk_alloc() is using refcount_inc_not_zero().
+ req->rsk_listener = nsk;
+}
+
Honestly, this patch series looks quite complex, and finding a bug in the
very first function I am looking at is not really a good sign...
From: Eric Dumazet <hidden> Date: 2020-12-01 15:27:08
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted hunk
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I fail to understand how the kernel can run fine right after this patch, before following patches are merged.
All request sockets in the socket accept queue MUST have their rsk_listener set to the listener,
this is how we designed things (each request socket has a reference taken on the listener)
We might even have some "BUG_ON(sk != req->rsk_listener);" in some places.
Since you splice list from old listener to the new one, without changing req->rsk_listener, bad things will happen.
I feel the order of your patches is not correct.
From: Eric Dumazet <hidden> Date: 2020-12-01 15:31:11
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted hunk
A TFO request socket is only freed after BOTH 3WHS has completed (or
aborted) and the child socket has been accepted (or its listener has been
closed). Hence, depending on the order, there can be two kinds of request
sockets in the accept queue.
3WHS -> accept : TCP_ESTABLISHED
accept -> 3WHS : TCP_SYN_RECV
Unlike TCP_ESTABLISHED socket, accept() does not free the request socket
for TCP_SYN_RECV socket. It is freed later at reqsk_fastopen_remove().
Also, it accesses request_sock.rsk_listener. So, in order to complete TFO
socket migration, we have to set the current listener to it at accept()
before reqsk_fastopen_remove().
Moreover, if TFO request caused RST before 3WHS has completed, it is held
in the listener's TFO queue to prevent DDoS attack. Thus, we also have to
migrate the requests in TFO queue.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
net/ipv4/inet_connection_sock.c | 35 ++++++++++++++++++++++++++++++++-
1 file changed, 34 insertions(+), 1 deletion(-)
@@ -500,6 +500,16 @@ struct sock *inet_csk_accept(struct sock *sk, int flags, int *err, bool kern)tcp_rsk(req)->tfo_listener){spin_lock_bh(&queue->fastopenq.lock);if(tcp_rsk(req)->tfo_listener){+if(req->rsk_listener!=sk){+/* TFO request was migrated to another listener so+*thenewlistenermustbeusedinreqsk_fastopen_remove()+*toholdrequestswhichcauseRST.+*/+sock_put(req->rsk_listener);+sock_hold(sk);+req->rsk_listener=sk;+}+/* We are still waiting for the final ACK from 3WHS*socan'tfreereqnow.Instead,wesetreq->skto*NULLtosignifythatthechildsocketistaken
On Tue, Dec 1, 2020 at 6:49 AM Kuniyuki Iwashima [off-list ref] wrote:
quoted hunk
This commit adds new bpf_attach_type for BPF_PROG_TYPE_SK_REUSEPORT to
check if the attached eBPF program is capable of migrating sockets.
When the eBPF program is attached, the kernel runs it for socket migration
only if the expected_attach_type is BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
The kernel will change the behaviour depending on the returned value:
- SK_PASS with selected_sk, select it as a new listener
- SK_PASS with selected_sk NULL, fall back to the random selection
- SK_DROP, cancel the migration
Link: https://lore.kernel.org/netdev/20201123003828.xjpjdtk4ygl6tg6h@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 2 ++
kernel/bpf/syscall.c | 8 ++++++++
tools/include/uapi/linux/bpf.h | 2 ++
3 files changed, 12 insertions(+)
From: Martin KaFai Lau <hidden> Date: 2020-12-02 19:20:51
On Tue, Dec 01, 2020 at 06:04:50PM -0800, Andrii Nakryiko wrote:
On Tue, Dec 1, 2020 at 6:49 AM Kuniyuki Iwashima [off-list ref] wrote:
quoted
This commit adds new bpf_attach_type for BPF_PROG_TYPE_SK_REUSEPORT to
check if the attached eBPF program is capable of migrating sockets.
When the eBPF program is attached, the kernel runs it for socket migration
only if the expected_attach_type is BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
The kernel will change the behaviour depending on the returned value:
- SK_PASS with selected_sk, select it as a new listener
- SK_PASS with selected_sk NULL, fall back to the random selection
- SK_DROP, cancel the migration
Link: https://lore.kernel.org/netdev/20201123003828.xjpjdtk4ygl6tg6h@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 2 ++
kernel/bpf/syscall.c | 8 ++++++++
tools/include/uapi/linux/bpf.h | 2 ++
3 files changed, 12 insertions(+)
this is a kernel regression, previously expected_attach_type wasn't
enforced, so user-space could have provided any number without an
error.
I also think this change alone will break things like when the usual
attr->expected_attach_type == 0 case. At least changes is needed in
bpf_prog_load_fixup_attach_type() which is also handling a
similar situation for BPF_PROG_TYPE_CGROUP_SOCK.
I now think there is no need to expose new bpf_attach_type to the UAPI.
Since the prog->expected_attach_type is not used, it can be cleared at load time
and then only set to BPF_SK_REUSEPORT_SELECT_OR_MIGRATE (probably defined
internally at filter.[c|h]) in the is_valid_access() when "migration"
is accessed. When "migration" is accessed, the bpf prog can handle
migration (and the original not-migration) case.
quoted
case BPF_PROG_TYPE_EXT:
if (expected_attach_type)
return -EINVAL;
From: Martin KaFai Lau <hidden> Date: 2020-12-03 04:25:24
On Wed, Dec 02, 2020 at 11:19:02AM -0800, Martin KaFai Lau wrote:
On Tue, Dec 01, 2020 at 06:04:50PM -0800, Andrii Nakryiko wrote:
quoted
On Tue, Dec 1, 2020 at 6:49 AM Kuniyuki Iwashima [off-list ref] wrote:
quoted
This commit adds new bpf_attach_type for BPF_PROG_TYPE_SK_REUSEPORT to
check if the attached eBPF program is capable of migrating sockets.
When the eBPF program is attached, the kernel runs it for socket migration
only if the expected_attach_type is BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
The kernel will change the behaviour depending on the returned value:
- SK_PASS with selected_sk, select it as a new listener
- SK_PASS with selected_sk NULL, fall back to the random selection
- SK_DROP, cancel the migration
Link: https://lore.kernel.org/netdev/20201123003828.xjpjdtk4ygl6tg6h@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 2 ++
kernel/bpf/syscall.c | 8 ++++++++
tools/include/uapi/linux/bpf.h | 2 ++
3 files changed, 12 insertions(+)
this is a kernel regression, previously expected_attach_type wasn't
enforced, so user-space could have provided any number without an
error.
I also think this change alone will break things like when the usual
attr->expected_attach_type == 0 case. At least changes is needed in
bpf_prog_load_fixup_attach_type() which is also handling a
similar situation for BPF_PROG_TYPE_CGROUP_SOCK.
I now think there is no need to expose new bpf_attach_type to the UAPI.
Since the prog->expected_attach_type is not used, it can be cleared at load time
and then only set to BPF_SK_REUSEPORT_SELECT_OR_MIGRATE (probably defined
internally at filter.[c|h]) in the is_valid_access() when "migration"
is accessed. When "migration" is accessed, the bpf prog can handle
migration (and the original not-migration) case.
Scrap this internal only BPF_SK_REUSEPORT_SELECT_OR_MIGRATE idea.
I think there will be cases that bpf prog wants to do both
without accessing any field from sk_reuseport_md.
Lets go back to the discussion on using a similar
idea as BPF_PROG_TYPE_CGROUP_SOCK in bpf_prog_load_fixup_attach_type().
I am not aware there is loader setting a random number
in expected_attach_type, so the chance of breaking
is very low. There was a similar discussion earlier [0].
[0]: https://lore.kernel.org/netdev/20200126045443.f47dzxdglazzchfm@ast-mbp/
quoted
quoted
case BPF_PROG_TYPE_EXT:
if (expected_attach_type)
return -EINVAL;
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:13:39 +0100
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch renames reuseport_select_sock() to __reuseport_select_sock() and
adds two wrapper function of it to pass the migration type defined in the
previous commit.
reuseport_select_sock : BPF_SK_REUSEPORT_MIGRATE_NO
reuseport_select_migrated_sock : BPF_SK_REUSEPORT_MIGRATE_REQUEST
As mentioned before, we have to select a new listener for TCP_NEW_SYN_RECV
requests at receiving the final ACK or sending a SYN+ACK. Therefore, this
patch also changes the code to call reuseport_select_migrated_sock() even
if the listening socket is TCP_CLOSE. If we can pick out a listening socket
from the reuseport group, we rewrite request_sock.rsk_listener and resume
processing the request.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 12 +++++++++++
include/net/request_sock.h | 13 ++++++++++++
include/net/sock_reuseport.h | 8 +++----
net/core/sock_reuseport.c | 34 ++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 13 ++++++++++--
net/ipv4/tcp_ipv4.c | 9 ++++++--
net/ipv6/tcp_ipv6.c | 9 ++++++--
7 files changed, 81 insertions(+), 17 deletions(-)
This looks racy to me. nsk refcount might be zero at this point.
If you think it can _not_ be zero, please add a big comment here,
because this would mean something has been done before reaching this function,
and this sock_hold() would be not needed in the first place.
There is a good reason reqsk_alloc() is using refcount_inc_not_zero().
Exactly, I will fix this in the next spin like below.
Thank you.
---8<---
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
I fail to understand how the kernel can run fine right after this patch, before following patches are merged.
I will squash the two or reorganize them into definition part and migration
part.
All request sockets in the socket accept queue MUST have their rsk_listener set to the listener,
this is how we designed things (each request socket has a reference taken on the listener)
We might even have some "BUG_ON(sk != req->rsk_listener);" in some places.
Since you splice list from old listener to the new one, without changing req->rsk_listener, bad things will happen.
I feel the order of your patches is not correct.
I understand this series is against the design.
But once the requests sockets are added in the queue, they are accessed
from the accept queue, and then we have the correct listener and can
rewirte rsk_listener. Otherwise, their full socket are accessed instead.
Also, as far as I know, such BUG_ON was only in inet_child_forget().
From: Martin KaFai Lau <redacted>
Date: Wed, 2 Dec 2020 20:24:02 -0800
On Wed, Dec 02, 2020 at 11:19:02AM -0800, Martin KaFai Lau wrote:
quoted
On Tue, Dec 01, 2020 at 06:04:50PM -0800, Andrii Nakryiko wrote:
quoted
On Tue, Dec 1, 2020 at 6:49 AM Kuniyuki Iwashima [off-list ref] wrote:
quoted
This commit adds new bpf_attach_type for BPF_PROG_TYPE_SK_REUSEPORT to
check if the attached eBPF program is capable of migrating sockets.
When the eBPF program is attached, the kernel runs it for socket migration
only if the expected_attach_type is BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
The kernel will change the behaviour depending on the returned value:
- SK_PASS with selected_sk, select it as a new listener
- SK_PASS with selected_sk NULL, fall back to the random selection
- SK_DROP, cancel the migration
Link: https://lore.kernel.org/netdev/20201123003828.xjpjdtk4ygl6tg6h@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 2 ++
kernel/bpf/syscall.c | 8 ++++++++
tools/include/uapi/linux/bpf.h | 2 ++
3 files changed, 12 insertions(+)
this is a kernel regression, previously expected_attach_type wasn't
enforced, so user-space could have provided any number without an
error.
I also think this change alone will break things like when the usual
attr->expected_attach_type == 0 case. At least changes is needed in
bpf_prog_load_fixup_attach_type() which is also handling a
similar situation for BPF_PROG_TYPE_CGROUP_SOCK.
I now think there is no need to expose new bpf_attach_type to the UAPI.
Since the prog->expected_attach_type is not used, it can be cleared at load time
and then only set to BPF_SK_REUSEPORT_SELECT_OR_MIGRATE (probably defined
internally at filter.[c|h]) in the is_valid_access() when "migration"
is accessed. When "migration" is accessed, the bpf prog can handle
migration (and the original not-migration) case.
Scrap this internal only BPF_SK_REUSEPORT_SELECT_OR_MIGRATE idea.
I think there will be cases that bpf prog wants to do both
without accessing any field from sk_reuseport_md.
Lets go back to the discussion on using a similar
idea as BPF_PROG_TYPE_CGROUP_SOCK in bpf_prog_load_fixup_attach_type().
I am not aware there is loader setting a random number
in expected_attach_type, so the chance of breaking
is very low. There was a similar discussion earlier [0].
[0]: https://lore.kernel.org/netdev/20200126045443.f47dzxdglazzchfm@ast-mbp/
Thank you for the idea and reference.
I will remove the change in bpf_prog_load_check_attach() and set the
default value (BPF_SK_REUSEPORT_SELECT) in bpf_prog_load_fixup_attach_type()
for backward compatibility if expected_attach_type is 0.
quoted
quoted
quoted
case BPF_PROG_TYPE_EXT:
if (expected_attach_type)
return -EINVAL;
From: Eric Dumazet <edumazet@google.com> Date: 2020-12-03 14:51:33
On Thu, Dec 3, 2020 at 3:14 PM Kuniyuki Iwashima [off-list ref] wrote:
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
quoted
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
Until the socket is closed, reallocated and used again. LOCKDEP has no
idea about soreuseport logic.
If you run your tests long enough, lockdep should complain at some point.
git grep -n double_lock
From: Eric Dumazet <edumazet@google.com>
Date: Thu, 3 Dec 2020 15:31:53 +0100
On Thu, Dec 3, 2020 at 3:14 PM Kuniyuki Iwashima [off-list ref] wrote:
quoted
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
quoted
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
Until the socket is closed, reallocated and used again. LOCKDEP has no
idea about soreuseport logic.
If you run your tests long enough, lockdep should complain at some point.
git grep -n double_lock
Thank you, I will change the code like double_lock().
And I will try to continue testing lockdep without this change for
curiosity!
From: Martin KaFai Lau <hidden> Date: 2020-12-04 05:58:21
On Thu, Dec 03, 2020 at 11:16:08PM +0900, Kuniyuki Iwashima wrote:
From: Martin KaFai Lau <redacted>
Date: Wed, 2 Dec 2020 20:24:02 -0800
quoted
On Wed, Dec 02, 2020 at 11:19:02AM -0800, Martin KaFai Lau wrote:
quoted
On Tue, Dec 01, 2020 at 06:04:50PM -0800, Andrii Nakryiko wrote:
quoted
On Tue, Dec 1, 2020 at 6:49 AM Kuniyuki Iwashima [off-list ref] wrote:
quoted
This commit adds new bpf_attach_type for BPF_PROG_TYPE_SK_REUSEPORT to
check if the attached eBPF program is capable of migrating sockets.
When the eBPF program is attached, the kernel runs it for socket migration
only if the expected_attach_type is BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
The kernel will change the behaviour depending on the returned value:
- SK_PASS with selected_sk, select it as a new listener
- SK_PASS with selected_sk NULL, fall back to the random selection
- SK_DROP, cancel the migration
Link: https://lore.kernel.org/netdev/20201123003828.xjpjdtk4ygl6tg6h@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 2 ++
kernel/bpf/syscall.c | 8 ++++++++
tools/include/uapi/linux/bpf.h | 2 ++
3 files changed, 12 insertions(+)
this is a kernel regression, previously expected_attach_type wasn't
enforced, so user-space could have provided any number without an
error.
I also think this change alone will break things like when the usual
attr->expected_attach_type == 0 case. At least changes is needed in
bpf_prog_load_fixup_attach_type() which is also handling a
similar situation for BPF_PROG_TYPE_CGROUP_SOCK.
I now think there is no need to expose new bpf_attach_type to the UAPI.
Since the prog->expected_attach_type is not used, it can be cleared at load time
and then only set to BPF_SK_REUSEPORT_SELECT_OR_MIGRATE (probably defined
internally at filter.[c|h]) in the is_valid_access() when "migration"
is accessed. When "migration" is accessed, the bpf prog can handle
migration (and the original not-migration) case.
Scrap this internal only BPF_SK_REUSEPORT_SELECT_OR_MIGRATE idea.
I think there will be cases that bpf prog wants to do both
without accessing any field from sk_reuseport_md.
Lets go back to the discussion on using a similar
idea as BPF_PROG_TYPE_CGROUP_SOCK in bpf_prog_load_fixup_attach_type().
I am not aware there is loader setting a random number
in expected_attach_type, so the chance of breaking
is very low. There was a similar discussion earlier [0].
[0]: https://lore.kernel.org/netdev/20200126045443.f47dzxdglazzchfm@ast-mbp/
Thank you for the idea and reference.
I will remove the change in bpf_prog_load_check_attach() and set the
default value (BPF_SK_REUSEPORT_SELECT) in bpf_prog_load_fixup_attach_type()
for backward compatibility if expected_attach_type is 0.
check_attach_type() can be kept. You can refer to
commit aac3fc320d94 for a similar situation.
From: Martin KaFai Lau <hidden> Date: 2020-12-04 19:59:19
On Tue, Dec 01, 2020 at 11:44:16PM +0900, Kuniyuki Iwashima wrote:
quoted hunk
We will call sock_reuseport.prog for socket migration in the next commit,
so the eBPF program has to know which listener is closing in order to
select the new listener.
Currently, we can get a unique ID for each listener in the userspace by
calling bpf_map_lookup_elem() for BPF_MAP_TYPE_REUSEPORT_SOCKARRAY map.
This patch makes the sk pointer available in sk_reuseport_md so that we can
get the ID by BPF_FUNC_get_socket_cookie() in the eBPF program.
Link: https://lore.kernel.org/netdev/20201119001154.kapwihc2plp4f7zc@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 8 ++++++++
net/core/filter.c | 12 +++++++++++-
tools/include/uapi/linux/bpf.h | 8 ++++++++
3 files changed, 27 insertions(+), 1 deletion(-)
@@ -1650,6 +1650,13 @@ union bpf_attr {*A8-bytelongnon-decreasingnumberonsuccess,or0ifthe*socketfieldismissinginside*skb*.*+*u64bpf_get_socket_cookie(structbpf_sock*sk)+*Description+*Equivalenttobpf_get_socket_cookie()helperthataccepts+**skb*,butgetssocketfrom**structbpf_sock**context.+*Return+*A8-bytelongnon-decreasingnumber.+**u64bpf_get_socket_cookie(structbpf_sock_addr*ctx)*Description*Equivalenttobpf_get_socket_cookie()helperthataccepts
@@ -4420,6 +4427,7 @@ struct sk_reuseport_md {__u32bind_inany;/* Is sock bound to an INANY address? */__u32hash;/* A hash of the packet 4 tuples */__u8migration;/* Migration type */+__bpf_md_ptr(structbpf_sock*,sk);/* current listening socket */};#define BPF_TAG_SIZE 8
From: Martin KaFai Lau <hidden> Date: 2020-12-05 01:32:33
On Tue, Dec 01, 2020 at 11:44:08PM +0900, Kuniyuki Iwashima wrote:
quoted hunk
This patch is a preparation patch to migrate incoming connections in the
later commits and adds a field (num_closed_socks) to the struct
sock_reuseport to keep TCP_CLOSE sockets in the reuseport group.
When we close a listening socket, to migrate its connections to another
listener in the same reuseport group, we have to handle two kinds of child
sockets. One is that a listening socket has a reference to, and the other
is not.
The former is the TCP_ESTABLISHED/TCP_SYN_RECV sockets, and they are in the
accept queue of their listening socket. So, we can pop them out and push
them into another listener's queue at close() or shutdown() syscalls. On
the other hand, the latter, the TCP_NEW_SYN_RECV socket is during the
three-way handshake and not in the accept queue. Thus, we cannot access
such sockets at close() or shutdown() syscalls. Accordingly, we have to
migrate immature sockets after their listening socket has been closed.
Currently, if their listening socket has been closed, TCP_NEW_SYN_RECV
sockets are freed at receiving the final ACK or retransmitting SYN+ACKs. At
that time, if we could select a new listener from the same reuseport group,
no connection would be aborted. However, it is impossible because
reuseport_detach_sock() sets NULL to sk_reuseport_cb and forbids access to
the reuseport group from closed sockets.
This patch allows TCP_CLOSE sockets to remain in the reuseport group and to
have access to it while any child socket references to them. The point is
that reuseport_detach_sock() is called twice from inet_unhash() and
sk_destruct(). At first, it moves the socket backwards in socks[] and
increments num_closed_socks. Later, when all migrated connections are
accepted, it removes the socket from socks[], decrements num_closed_socks,
and sets NULL to sk_reuseport_cb.
By this change, closed sockets can keep sk_reuseport_cb until all child
requests have been freed or accepted. Consequently calling listen() after
shutdown() can cause EADDRINUSE or EBUSY in reuseport_add_sock() or
inet_csk_bind_conflict() which expect that such sockets should not have the
reuseport group. Therefore, this patch also loosens such validation rules
so that the socket can listen again if it has the same reuseport group with
other listening sockets.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/sock_reuseport.h | 5 ++-
net/core/sock_reuseport.c | 79 +++++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 7 ++-
3 files changed, 74 insertions(+), 17 deletions(-)
@@ -13,8 +13,9 @@ extern spinlock_t reuseport_lock;structsock_reuseport{structrcu_headrcu;-u16max_socks;/* length of socks */-u16num_socks;/* elements in socks */+u16max_socks;/* length of socks */+u16num_socks;/* elements in socks */+u16num_closed_socks;/* closed elements in socks *//* The last synq overflow event timestamp of this*reuse->socks[]group.*/
When will this happen?
I found the new logic in the closed sk shuffling within socks[] quite
complicated to read. I can see why the closed sk wants to keep its
sk->sk_reuseport_cb. However, does it need to stay
in socks[]?
@@ -0,0 +1,164 @@+// SPDX-License-Identifier: GPL-2.0+/*+*Checkifwecanmigratechildsockets.+*+*1.calllisten()for5serversockets.+*2.updateamaptomigrateallchildsocket+*tothelastserversocket(migrate_map[cookie]=4)+*3.callconnect()for25clientsockets.+*4.callclose()forfirst4serversockets.+*5.callaccept()forthelastserversocket.+*+*Author:KuniyukiIwashima<kuniyu@amazon.co.jp>+*/++#include<stdlib.h>+#include<unistd.h>+#include<fcntl.h>+#include<netinet/in.h>+#include<arpa/inet.h>+#include<linux/bpf.h>+#include<sys/socket.h>+#include<sys/types.h>+#include<bpf/bpf.h>+#include<bpf/libbpf.h>++#define NUM_SOCKS 5+#define LOCALHOST "127.0.0.1"+#define err_exit(condition, message) \+do{\+if(condition){\+perror("ERROR: "message" ");\+exit(1);\+}\+}while(0)++__u64server_fds[NUM_SOCKS];+intprog_fd,reuseport_map_fd,migrate_map_fd;+++voidsetup_bpf(void)+{+structbpf_object*obj;+structbpf_program*prog;+structbpf_map*reuseport_map,*migrate_map;+interr;++obj=bpf_object__open("test_migrate_reuseport_kern.o");+err_exit(libbpf_get_error(obj),"opening BPF object file failed");++err=bpf_object__load(obj);+err_exit(err,"loading BPF object failed");++prog=bpf_program__next(NULL,obj);+err_exit(!prog,"loading BPF program failed");++reuseport_map=bpf_object__find_map_by_name(obj,"reuseport_map");+err_exit(!reuseport_map,"loading BPF reuseport_map failed");++migrate_map=bpf_object__find_map_by_name(obj,"migrate_map");+err_exit(!migrate_map,"loading BPF migrate_map failed");++prog_fd=bpf_program__fd(prog);+reuseport_map_fd=bpf_map__fd(reuseport_map);+migrate_map_fd=bpf_map__fd(migrate_map);+}++voidtest_listen(void)+{+structsockaddr_inaddr;+socklen_taddr_len=sizeof(addr);+inti,err,optval=1,migrated_to=NUM_SOCKS-1;+__u64value;++addr.sin_family=AF_INET;+addr.sin_port=htons(80);+inet_pton(AF_INET,LOCALHOST,&addr.sin_addr.s_addr);++for(i=0;i<NUM_SOCKS;i++){+server_fds[i]=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);+err_exit(server_fds[i]==-1,"socket() for listener sockets failed");++err=setsockopt(server_fds[i],SOL_SOCKET,SO_REUSEPORT,+&optval,sizeof(optval));+err_exit(err==-1,"setsockopt() for SO_REUSEPORT failed");++if(i==0){+err=setsockopt(server_fds[i],SOL_SOCKET,SO_ATTACH_REUSEPORT_EBPF,+&prog_fd,sizeof(prog_fd));+err_exit(err==-1,"setsockopt() for SO_ATTACH_REUSEPORT_EBPF failed");+}++err=bind(server_fds[i],(structsockaddr*)&addr,addr_len);+err_exit(err==-1,"bind() failed");++err=listen(server_fds[i],32);+err_exit(err==-1,"listen() failed");++err=bpf_map_update_elem(reuseport_map_fd,&i,&server_fds[i],BPF_NOEXIST);+err_exit(err==-1,"updating BPF reuseport_map failed");++err=bpf_map_lookup_elem(reuseport_map_fd,&i,&value);+err_exit(err==-1,"looking up BPF reuseport_map failed");++printf("fd[%d] (cookie: %llu) -> fd[%d]\n",i,value,migrated_to);+err=bpf_map_update_elem(migrate_map_fd,&value,&migrated_to,BPF_NOEXIST);+err_exit(err==-1,"updating BPF migrate_map failed");+}+}++voidtest_connect(void)+{+structsockaddr_inaddr;+socklen_taddr_len=sizeof(addr);+inti,err,client_fd;++addr.sin_family=AF_INET;+addr.sin_port=htons(80);+inet_pton(AF_INET,LOCALHOST,&addr.sin_addr.s_addr);++for(i=0;i<NUM_SOCKS*5;i++){+client_fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);+err_exit(client_fd==-1,"socket() for listener sockets failed");++err=connect(client_fd,(structsockaddr*)&addr,addr_len);+err_exit(err==-1,"connect() failed");++close(client_fd);+}+}++voidtest_close(void)+{+inti;++for(i=0;i<NUM_SOCKS-1;i++)+close(server_fds[i]);+}++voidtest_accept(void)+{+structsockaddr_inaddr;+socklen_taddr_len=sizeof(addr);+intcnt,client_fd;++fcntl(server_fds[NUM_SOCKS-1],F_SETFL,O_NONBLOCK);++for(cnt=0;cnt<NUM_SOCKS*5;cnt++){+client_fd=accept(server_fds[NUM_SOCKS-1],(structsockaddr*)&addr,&addr_len);+err_exit(client_fd==-1,"accept() failed");+}++printf("%d accepted, %d is expected\n",cnt,NUM_SOCKS*5);+}++intmain(void)
I am pretty sure "make -C tools/testing/selftests/bpf"
will not compile here because of double main() with
the test_progs.c.
Please take a look at how other tests are written in
tools/testing/selftests/bpf/prog_tests/. e.g.
the test function in tcp_hdr_options.c is
test_tcp_hdr_options().
Also, instead of bpf_object__open(), please use skeleton
like most of the tests do.
I'm sending this mail just for logging because I failed to send mails only
to LKML, netdev, and bpf yesterday.
From: Martin KaFai Lau <redacted>
Date: Thu, 3 Dec 2020 21:56:53 -0800
On Thu, Dec 03, 2020 at 11:16:08PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Wed, 2 Dec 2020 20:24:02 -0800
quoted
On Wed, Dec 02, 2020 at 11:19:02AM -0800, Martin KaFai Lau wrote:
quoted
On Tue, Dec 01, 2020 at 06:04:50PM -0800, Andrii Nakryiko wrote:
quoted
On Tue, Dec 1, 2020 at 6:49 AM Kuniyuki Iwashima [off-list ref] wrote:
quoted
This commit adds new bpf_attach_type for BPF_PROG_TYPE_SK_REUSEPORT to
check if the attached eBPF program is capable of migrating sockets.
When the eBPF program is attached, the kernel runs it for socket migration
only if the expected_attach_type is BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
The kernel will change the behaviour depending on the returned value:
- SK_PASS with selected_sk, select it as a new listener
- SK_PASS with selected_sk NULL, fall back to the random selection
- SK_DROP, cancel the migration
Link: https://lore.kernel.org/netdev/20201123003828.xjpjdtk4ygl6tg6h@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 2 ++
kernel/bpf/syscall.c | 8 ++++++++
tools/include/uapi/linux/bpf.h | 2 ++
3 files changed, 12 insertions(+)
this is a kernel regression, previously expected_attach_type wasn't
enforced, so user-space could have provided any number without an
error.
I also think this change alone will break things like when the usual
attr->expected_attach_type == 0 case. At least changes is needed in
bpf_prog_load_fixup_attach_type() which is also handling a
similar situation for BPF_PROG_TYPE_CGROUP_SOCK.
I now think there is no need to expose new bpf_attach_type to the UAPI.
Since the prog->expected_attach_type is not used, it can be cleared at load time
and then only set to BPF_SK_REUSEPORT_SELECT_OR_MIGRATE (probably defined
internally at filter.[c|h]) in the is_valid_access() when "migration"
is accessed. When "migration" is accessed, the bpf prog can handle
migration (and the original not-migration) case.
Scrap this internal only BPF_SK_REUSEPORT_SELECT_OR_MIGRATE idea.
I think there will be cases that bpf prog wants to do both
without accessing any field from sk_reuseport_md.
Lets go back to the discussion on using a similar
idea as BPF_PROG_TYPE_CGROUP_SOCK in bpf_prog_load_fixup_attach_type().
I am not aware there is loader setting a random number
in expected_attach_type, so the chance of breaking
is very low. There was a similar discussion earlier [0].
[0]: https://lore.kernel.org/netdev/20200126045443.f47dzxdglazzchfm@ast-mbp/
Thank you for the idea and reference.
I will remove the change in bpf_prog_load_check_attach() and set the
default value (BPF_SK_REUSEPORT_SELECT) in bpf_prog_load_fixup_attach_type()
for backward compatibility if expected_attach_type is 0.
check_attach_type() can be kept. You can refer to
commit aac3fc320d94 for a similar situation.
I confirmed bpf_prog_load_fixup_attach_type() is called just before
bpf_prog_load_check_attach(), so I will add the fixup code to this patch.
Thank you.
I'm sending this mail just for logging because I failed to send mails only
to LKML, netdev, and bpf yesterday.
From: Martin KaFai Lau <redacted>
Date: Fri, 4 Dec 2020 11:58:07 -0800
On Tue, Dec 01, 2020 at 11:44:16PM +0900, Kuniyuki Iwashima wrote:
quoted
We will call sock_reuseport.prog for socket migration in the next commit,
so the eBPF program has to know which listener is closing in order to
select the new listener.
Currently, we can get a unique ID for each listener in the userspace by
calling bpf_map_lookup_elem() for BPF_MAP_TYPE_REUSEPORT_SOCKARRAY map.
This patch makes the sk pointer available in sk_reuseport_md so that we can
get the ID by BPF_FUNC_get_socket_cookie() in the eBPF program.
Link: https://lore.kernel.org/netdev/20201119001154.kapwihc2plp4f7zc@kafai-mbp.dhcp.thefacebook.com/
Suggested-by: Martin KaFai Lau <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/uapi/linux/bpf.h | 8 ++++++++
net/core/filter.c | 12 +++++++++++-
tools/include/uapi/linux/bpf.h | 8 ++++++++
3 files changed, 27 insertions(+), 1 deletion(-)
@@ -1650,6 +1650,13 @@ union bpf_attr {*A8-bytelongnon-decreasingnumberonsuccess,or0ifthe*socketfieldismissinginside*skb*.*+*u64bpf_get_socket_cookie(structbpf_sock*sk)+*Description+*Equivalenttobpf_get_socket_cookie()helperthataccepts+**skb*,butgetssocketfrom**structbpf_sock**context.+*Return+*A8-bytelongnon-decreasingnumber.+**u64bpf_get_socket_cookie(structbpf_sock_addr*ctx)*Description*Equivalenttobpf_get_socket_cookie()helperthataccepts
@@ -4420,6 +4427,7 @@ struct sk_reuseport_md {__u32bind_inany;/* Is sock bound to an INANY address? */__u32hash;/* A hash of the packet 4 tuples */__u8migration;/* Migration type */+__bpf_md_ptr(structbpf_sock*,sk);/* current listening socket */};#define BPF_TAG_SIZE 8
I'm sending this mail just for logging because I failed to send mails only
to LKML, netdev, and bpf yesterday.
From: Martin KaFai Lau <redacted>
Date: Fri, 4 Dec 2020 17:31:03 -0800
On Tue, Dec 01, 2020 at 11:44:08PM +0900, Kuniyuki Iwashima wrote:
quoted
This patch is a preparation patch to migrate incoming connections in the
later commits and adds a field (num_closed_socks) to the struct
sock_reuseport to keep TCP_CLOSE sockets in the reuseport group.
When we close a listening socket, to migrate its connections to another
listener in the same reuseport group, we have to handle two kinds of child
sockets. One is that a listening socket has a reference to, and the other
is not.
The former is the TCP_ESTABLISHED/TCP_SYN_RECV sockets, and they are in the
accept queue of their listening socket. So, we can pop them out and push
them into another listener's queue at close() or shutdown() syscalls. On
the other hand, the latter, the TCP_NEW_SYN_RECV socket is during the
three-way handshake and not in the accept queue. Thus, we cannot access
such sockets at close() or shutdown() syscalls. Accordingly, we have to
migrate immature sockets after their listening socket has been closed.
Currently, if their listening socket has been closed, TCP_NEW_SYN_RECV
sockets are freed at receiving the final ACK or retransmitting SYN+ACKs. At
that time, if we could select a new listener from the same reuseport group,
no connection would be aborted. However, it is impossible because
reuseport_detach_sock() sets NULL to sk_reuseport_cb and forbids access to
the reuseport group from closed sockets.
This patch allows TCP_CLOSE sockets to remain in the reuseport group and to
have access to it while any child socket references to them. The point is
that reuseport_detach_sock() is called twice from inet_unhash() and
sk_destruct(). At first, it moves the socket backwards in socks[] and
increments num_closed_socks. Later, when all migrated connections are
accepted, it removes the socket from socks[], decrements num_closed_socks,
and sets NULL to sk_reuseport_cb.
By this change, closed sockets can keep sk_reuseport_cb until all child
requests have been freed or accepted. Consequently calling listen() after
shutdown() can cause EADDRINUSE or EBUSY in reuseport_add_sock() or
inet_csk_bind_conflict() which expect that such sockets should not have the
reuseport group. Therefore, this patch also loosens such validation rules
so that the socket can listen again if it has the same reuseport group with
other listening sockets.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/sock_reuseport.h | 5 ++-
net/core/sock_reuseport.c | 79 +++++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 7 ++-
3 files changed, 74 insertions(+), 17 deletions(-)
@@ -13,8 +13,9 @@ extern spinlock_t reuseport_lock;structsock_reuseport{structrcu_headrcu;-u16max_socks;/* length of socks */-u16num_socks;/* elements in socks */+u16max_socks;/* length of socks */+u16num_socks;/* elements in socks */+u16num_closed_socks;/* closed elements in socks *//* The last synq overflow event timestamp of this*reuse->socks[]group.*/
I understood the original code did nothing if the sk was not found in
socks[], so I rewrote it this way, but I also think `i` will never be -1.
If I rewrite, it will be like:
---8<---
for (; left < right; left++)
if (reuse->socks[left] == sk)
break;
return left;
---8<---
I found the new logic in the closed sk shuffling within socks[] quite
complicated to read. I can see why the closed sk wants to keep its
sk->sk_reuseport_cb. However, does it need to stay
in socks[]?
Currently, I do not use closed sockets in socks[], so the only thing I need
to do seems to be to count num_closed_socks to free struct sock_reuseport.
I will change the code only to keep sk_reuseport_cb and count
num_closed_socks.
(As a side note, I wrote the code while thinking of stack and heap to share
the same array, but I also feel a bit difficult to read.)
I'm sending this mail just for logging because I failed to send mails only
to LKML, netdev, and bpf yesterday.
From: Martin KaFai Lau <redacted>
Date: Fri, 4 Dec 2020 17:42:41 -0800
On Tue, Dec 01, 2020 at 11:44:10PM +0900, Kuniyuki Iwashima wrote:
[ ... ]
reuseport_lock is locked in this function, and we do not modify the prog,
but is rcu_dereference_protected() preferable?
---8<---
prog = rcu_dereference_protected(reuse->prog,
lockdep_is_held(&reuseport_lock));
---8<---
I am also not very thrilled on this double spin_lock.
Can this be done in (or like) inet_csk_listen_stop() instead?
It will be possible to migrate sockets in inet_csk_listen_stop(), but I
think it is better to do it just after reuseport_detach_sock() becuase we
can select a different listener (almost) every time at a lower cost by
selecting the moved socket and pass it to inet_csk_reqsk_queue_migrate()
easily.
sk_hash of the listener is 0, so we would have to generate a random number
in inet_csk_listen_stop().
I'm sending this mail just for logging because I failed to send mails only
to LKML, netdev, and bpf yesterday.
From: Martin KaFai Lau <redacted>
Date: Fri, 4 Dec 2020 17:50:00 -0800
On Tue, Dec 01, 2020 at 11:44:18PM +0900, Kuniyuki Iwashima wrote:
quoted
This patch adds a test for BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
.../bpf/prog_tests/migrate_reuseport.c | 164 ++++++++++++++++++
.../bpf/progs/test_migrate_reuseport_kern.c | 54 ++++++
2 files changed, 218 insertions(+)
create mode 100644 tools/testing/selftests/bpf/prog_tests/migrate_reuseport.c
create mode 100644 tools/testing/selftests/bpf/progs/test_migrate_reuseport_kern.c
@@ -0,0 +1,164 @@+// SPDX-License-Identifier: GPL-2.0+/*+*Checkifwecanmigratechildsockets.+*+*1.calllisten()for5serversockets.+*2.updateamaptomigrateallchildsocket+*tothelastserversocket(migrate_map[cookie]=4)+*3.callconnect()for25clientsockets.+*4.callclose()forfirst4serversockets.+*5.callaccept()forthelastserversocket.+*+*Author:KuniyukiIwashima<kuniyu@amazon.co.jp>+*/++#include<stdlib.h>+#include<unistd.h>+#include<fcntl.h>+#include<netinet/in.h>+#include<arpa/inet.h>+#include<linux/bpf.h>+#include<sys/socket.h>+#include<sys/types.h>+#include<bpf/bpf.h>+#include<bpf/libbpf.h>++#define NUM_SOCKS 5+#define LOCALHOST "127.0.0.1"+#define err_exit(condition, message) \+do{\+if(condition){\+perror("ERROR: "message" ");\+exit(1);\+}\+}while(0)++__u64server_fds[NUM_SOCKS];+intprog_fd,reuseport_map_fd,migrate_map_fd;+++voidsetup_bpf(void)+{+structbpf_object*obj;+structbpf_program*prog;+structbpf_map*reuseport_map,*migrate_map;+interr;++obj=bpf_object__open("test_migrate_reuseport_kern.o");+err_exit(libbpf_get_error(obj),"opening BPF object file failed");++err=bpf_object__load(obj);+err_exit(err,"loading BPF object failed");++prog=bpf_program__next(NULL,obj);+err_exit(!prog,"loading BPF program failed");++reuseport_map=bpf_object__find_map_by_name(obj,"reuseport_map");+err_exit(!reuseport_map,"loading BPF reuseport_map failed");++migrate_map=bpf_object__find_map_by_name(obj,"migrate_map");+err_exit(!migrate_map,"loading BPF migrate_map failed");++prog_fd=bpf_program__fd(prog);+reuseport_map_fd=bpf_map__fd(reuseport_map);+migrate_map_fd=bpf_map__fd(migrate_map);+}++voidtest_listen(void)+{+structsockaddr_inaddr;+socklen_taddr_len=sizeof(addr);+inti,err,optval=1,migrated_to=NUM_SOCKS-1;+__u64value;++addr.sin_family=AF_INET;+addr.sin_port=htons(80);+inet_pton(AF_INET,LOCALHOST,&addr.sin_addr.s_addr);++for(i=0;i<NUM_SOCKS;i++){+server_fds[i]=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);+err_exit(server_fds[i]==-1,"socket() for listener sockets failed");++err=setsockopt(server_fds[i],SOL_SOCKET,SO_REUSEPORT,+&optval,sizeof(optval));+err_exit(err==-1,"setsockopt() for SO_REUSEPORT failed");++if(i==0){+err=setsockopt(server_fds[i],SOL_SOCKET,SO_ATTACH_REUSEPORT_EBPF,+&prog_fd,sizeof(prog_fd));+err_exit(err==-1,"setsockopt() for SO_ATTACH_REUSEPORT_EBPF failed");+}++err=bind(server_fds[i],(structsockaddr*)&addr,addr_len);+err_exit(err==-1,"bind() failed");++err=listen(server_fds[i],32);+err_exit(err==-1,"listen() failed");++err=bpf_map_update_elem(reuseport_map_fd,&i,&server_fds[i],BPF_NOEXIST);+err_exit(err==-1,"updating BPF reuseport_map failed");++err=bpf_map_lookup_elem(reuseport_map_fd,&i,&value);+err_exit(err==-1,"looking up BPF reuseport_map failed");++printf("fd[%d] (cookie: %llu) -> fd[%d]\n",i,value,migrated_to);+err=bpf_map_update_elem(migrate_map_fd,&value,&migrated_to,BPF_NOEXIST);+err_exit(err==-1,"updating BPF migrate_map failed");+}+}++voidtest_connect(void)+{+structsockaddr_inaddr;+socklen_taddr_len=sizeof(addr);+inti,err,client_fd;++addr.sin_family=AF_INET;+addr.sin_port=htons(80);+inet_pton(AF_INET,LOCALHOST,&addr.sin_addr.s_addr);++for(i=0;i<NUM_SOCKS*5;i++){+client_fd=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);+err_exit(client_fd==-1,"socket() for listener sockets failed");++err=connect(client_fd,(structsockaddr*)&addr,addr_len);+err_exit(err==-1,"connect() failed");++close(client_fd);+}+}++voidtest_close(void)+{+inti;++for(i=0;i<NUM_SOCKS-1;i++)+close(server_fds[i]);+}++voidtest_accept(void)+{+structsockaddr_inaddr;+socklen_taddr_len=sizeof(addr);+intcnt,client_fd;++fcntl(server_fds[NUM_SOCKS-1],F_SETFL,O_NONBLOCK);++for(cnt=0;cnt<NUM_SOCKS*5;cnt++){+client_fd=accept(server_fds[NUM_SOCKS-1],(structsockaddr*)&addr,&addr_len);+err_exit(client_fd==-1,"accept() failed");+}++printf("%d accepted, %d is expected\n",cnt,NUM_SOCKS*5);+}++intmain(void)
I am pretty sure "make -C tools/testing/selftests/bpf"
will not compile here because of double main() with
the test_progs.c.
Please take a look at how other tests are written in
tools/testing/selftests/bpf/prog_tests/. e.g.
the test function in tcp_hdr_options.c is
test_tcp_hdr_options().
Also, instead of bpf_object__open(), please use skeleton
like most of the tests do.
I'm sorry... I will check other tests and rewrite this patch along them.
From: Martin KaFai Lau <hidden> Date: 2020-12-07 20:34:35
On Thu, Dec 03, 2020 at 11:14:24PM +0900, Kuniyuki Iwashima wrote:
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
quoted
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
I fail to understand how the kernel can run fine right after this patch, before following patches are merged.
I will squash the two or reorganize them into definition part and migration
part.
quoted
All request sockets in the socket accept queue MUST have their rsk_listener set to the listener,
this is how we designed things (each request socket has a reference taken on the listener)
We might even have some "BUG_ON(sk != req->rsk_listener);" in some places.
Since you splice list from old listener to the new one, without changing req->rsk_listener, bad things will happen.
I also have similar concern on the inconsistency in req->rsk_listener.
The fix-up in req->rsk_listener for the TFO req in patch 4
makes it clear that req->rsk_listener should be updated during
the migration instead of asking a much later code path
to accommodate this inconsistent req->rsk_listener pointer.
The current inet_csk_listen_stop() is already iterating
the icsk_accept_queue and fastopenq. The extra cost
in updating rsk_listener may be just noise?
quoted
I feel the order of your patches is not correct.
I understand this series is against the design.
But once the requests sockets are added in the queue, they are accessed
from the accept queue, and then we have the correct listener and can
rewirte rsk_listener. Otherwise, their full socket are accessed instead.
Also, as far as I know, such BUG_ON was only in inet_child_forget().
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 12:33:15 -0800
On Thu, Dec 03, 2020 at 11:14:24PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
quoted
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
I fail to understand how the kernel can run fine right after this patch, before following patches are merged.
I will squash the two or reorganize them into definition part and migration
part.
quoted
All request sockets in the socket accept queue MUST have their rsk_listener set to the listener,
this is how we designed things (each request socket has a reference taken on the listener)
We might even have some "BUG_ON(sk != req->rsk_listener);" in some places.
Since you splice list from old listener to the new one, without changing req->rsk_listener, bad things will happen.
I also have similar concern on the inconsistency in req->rsk_listener.
The fix-up in req->rsk_listener for the TFO req in patch 4
makes it clear that req->rsk_listener should be updated during
the migration instead of asking a much later code path
to accommodate this inconsistent req->rsk_listener pointer.
When I started this patchset, I read this thread and misunderstood that I
had to migrate sockets in O(1) for scalability. So, I selected the fix-up
approach and checked rsk_listener is not used except for TFO.
---8<---
Whole point of BPF was to avoid iterate through all sockets [1],
and let user space use whatever selection logic it needs.
[1] This was okay with up to 16 sockets. But with 128 it does not scale.
---&<---
https://lore.kernel.org/netdev/1458837191.12033.4.camel@edumazet-glaptop3.roam.corp.google.com/
However, I've read it again, and this was about iterating over listeners
to select a new listener, not about iterating over requests...
In this patchset, we can select a listener in O(1) and it is enough.
The current inet_csk_listen_stop() is already iterating
the icsk_accept_queue and fastopenq. The extra cost
in updating rsk_listener may be just noise?
Exactly.
If we end up iterating requests, it is better to migrate than close. I will
update each rsk_listener in inet_csk_reqsk_queue_migrate() in v3 patchset.
Thank you!
I asked in the earlier thread if the primary use case is to only
use the bpf prog to pick. That thread did not come to
a solid answer but did conclude that the sysctl should not
control the behavior of the BPF_SK_REUSEPORT_SELECT_OR_MIGRATE prog.
From this change here, it seems it is still desired to only depend
on the kernel to random pick even when no bpf prog is attached.
If that is the case, a sysctl to guard here for not changing
the current behavior makes sense.
It should still only control the non-bpf-pick behavior:
when the sysctl is on, the kernel will still do a random pick
when there is no bpf prog attached to the reuseport group.
Thoughts?
From: Martin KaFai Lau <hidden> Date: 2020-12-08 07:36:03
On Tue, Dec 08, 2020 at 03:31:34PM +0900, Kuniyuki Iwashima wrote:
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 12:33:15 -0800
quoted
On Thu, Dec 03, 2020 at 11:14:24PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
quoted
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
I fail to understand how the kernel can run fine right after this patch, before following patches are merged.
I will squash the two or reorganize them into definition part and migration
part.
quoted
All request sockets in the socket accept queue MUST have their rsk_listener set to the listener,
this is how we designed things (each request socket has a reference taken on the listener)
We might even have some "BUG_ON(sk != req->rsk_listener);" in some places.
Since you splice list from old listener to the new one, without changing req->rsk_listener, bad things will happen.
I also have similar concern on the inconsistency in req->rsk_listener.
The fix-up in req->rsk_listener for the TFO req in patch 4
makes it clear that req->rsk_listener should be updated during
the migration instead of asking a much later code path
to accommodate this inconsistent req->rsk_listener pointer.
When I started this patchset, I read this thread and misunderstood that I
had to migrate sockets in O(1) for scalability. So, I selected the fix-up
approach and checked rsk_listener is not used except for TFO.
---8<---
Whole point of BPF was to avoid iterate through all sockets [1],
and let user space use whatever selection logic it needs.
[1] This was okay with up to 16 sockets. But with 128 it does not scale.
---&<---
https://lore.kernel.org/netdev/1458837191.12033.4.camel@edumazet-glaptop3.roam.corp.google.com/
However, I've read it again, and this was about iterating over listeners
to select a new listener, not about iterating over requests...
In this patchset, we can select a listener in O(1) and it is enough.
quoted
The current inet_csk_listen_stop() is already iterating
the icsk_accept_queue and fastopenq. The extra cost
in updating rsk_listener may be just noise?
Exactly.
If we end up iterating requests, it is better to migrate than close. I will
update each rsk_listener in inet_csk_reqsk_queue_migrate() in v3 patchset.
To be clear, I meant to do migration in inet_csk_listen_stop() instead
of doing it in the new inet_csk_reqsk_queue_migrate() which reqires a
double lock and then need to re-bring in the whole spin_lock_bh_nested
patch in the patch 3 of v2.
e.g. in the first while loop in inet_csk_listen_stop(),
if there is a target to migrate to, it can do
something similar to inet_csk_reqsk_queue_add(target_sk, ...)
instead of doing the current inet_child_forget().
It probably needs something different from
inet_csk_reqsk_queue_add(), e.g. also update rsk_listener,
but the idea should be similar.
Since the rsk_listener has to be updated one by one, there is
really no point to do the list splicing which requires
the double lock.
I asked in the earlier thread if the primary use case is to only
use the bpf prog to pick. That thread did not come to
a solid answer but did conclude that the sysctl should not
control the behavior of the BPF_SK_REUSEPORT_SELECT_OR_MIGRATE prog.
From this change here, it seems it is still desired to only depend
on the kernel to random pick even when no bpf prog is attached.
I wrote this way only to split patches into tcp and bpf parts.
So, in the 10th patch, eBPF prog is run if the type is
BPF_SK_REUSEPORT_SELECT_OR_MIGRATE.
https://lore.kernel.org/netdev/20201201144418.35045-11-kuniyu@amazon.co.jp/
But, it makes a breakage, so I will move
BPF_SK_REUSEPORT_SELECT_OR_MIGRATE validation into 10th patch so that the
type is only available after 10th patch.
---8<---
case BPF_PROG_TYPE_SK_REUSEPORT:
switch (expected_attach_type) {
case BPF_SK_REUSEPORT_SELECT:
case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE: <- move to 10th.
return 0;
default:
return -EINVAL;
}
---8<---
If that is the case, a sysctl to guard here for not changing
the current behavior makes sense.
It should still only control the non-bpf-pick behavior:
when the sysctl is on, the kernel will still do a random pick
when there is no bpf prog attached to the reuseport group.
Thoughts?
If different applications listen on the same port without eBPF prog, I
think sysctl is necessary. But honestly, I am not sure there is really such
a case and sysctl is necessary.
If patcheset with sysctl is more acceptable, I will add it back in the next
spin.
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 23:34:41 -0800
On Tue, Dec 08, 2020 at 03:31:34PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 12:33:15 -0800
quoted
On Thu, Dec 03, 2020 at 11:14:24PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
quoted
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
I fail to understand how the kernel can run fine right after this patch, before following patches are merged.
I will squash the two or reorganize them into definition part and migration
part.
quoted
All request sockets in the socket accept queue MUST have their rsk_listener set to the listener,
this is how we designed things (each request socket has a reference taken on the listener)
We might even have some "BUG_ON(sk != req->rsk_listener);" in some places.
Since you splice list from old listener to the new one, without changing req->rsk_listener, bad things will happen.
I also have similar concern on the inconsistency in req->rsk_listener.
The fix-up in req->rsk_listener for the TFO req in patch 4
makes it clear that req->rsk_listener should be updated during
the migration instead of asking a much later code path
to accommodate this inconsistent req->rsk_listener pointer.
When I started this patchset, I read this thread and misunderstood that I
had to migrate sockets in O(1) for scalability. So, I selected the fix-up
approach and checked rsk_listener is not used except for TFO.
---8<---
Whole point of BPF was to avoid iterate through all sockets [1],
and let user space use whatever selection logic it needs.
[1] This was okay with up to 16 sockets. But with 128 it does not scale.
---&<---
https://lore.kernel.org/netdev/1458837191.12033.4.camel@edumazet-glaptop3.roam.corp.google.com/
However, I've read it again, and this was about iterating over listeners
to select a new listener, not about iterating over requests...
In this patchset, we can select a listener in O(1) and it is enough.
quoted
The current inet_csk_listen_stop() is already iterating
the icsk_accept_queue and fastopenq. The extra cost
in updating rsk_listener may be just noise?
Exactly.
If we end up iterating requests, it is better to migrate than close. I will
update each rsk_listener in inet_csk_reqsk_queue_migrate() in v3 patchset.
To be clear, I meant to do migration in inet_csk_listen_stop() instead
of doing it in the new inet_csk_reqsk_queue_migrate() which reqires a
double lock and then need to re-bring in the whole spin_lock_bh_nested
patch in the patch 3 of v2.
e.g. in the first while loop in inet_csk_listen_stop(),
if there is a target to migrate to, it can do
something similar to inet_csk_reqsk_queue_add(target_sk, ...)
instead of doing the current inet_child_forget().
It probably needs something different from
inet_csk_reqsk_queue_add(), e.g. also update rsk_listener,
but the idea should be similar.
Since the rsk_listener has to be updated one by one, there is
really no point to do the list splicing which requires
the double lock.
I think it is a bit complex to pass the new listener from
reuseport_detach_sock() to inet_csk_listen_stop().
__tcp_close/tcp_disconnect/tcp_abort
|-tcp_set_state
| |-unhash
| |-reuseport_detach_sock (return nsk)
|-inet_csk_listen_stop
If we splice requests like this, we do not need double lock?
1. lock the accept queue of the old listener
2. unlink all requests and decrement refcount
3. unlock
4. update all requests with new listener
5. lock the accept queue of the new listener
6. splice requests and increment refcount
7. unlock
Also, I think splicing is better to keep the order of requests. Adding one
by one reverses it.
From: Martin KaFai Lau <hidden> Date: 2020-12-09 03:10:39
On Tue, Dec 08, 2020 at 05:17:48PM +0900, Kuniyuki Iwashima wrote:
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 23:34:41 -0800
quoted
On Tue, Dec 08, 2020 at 03:31:34PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 12:33:15 -0800
quoted
On Thu, Dec 03, 2020 at 11:14:24PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
quoted
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
I fail to understand how the kernel can run fine right after this patch, before following patches are merged.
I will squash the two or reorganize them into definition part and migration
part.
quoted
All request sockets in the socket accept queue MUST have their rsk_listener set to the listener,
this is how we designed things (each request socket has a reference taken on the listener)
We might even have some "BUG_ON(sk != req->rsk_listener);" in some places.
Since you splice list from old listener to the new one, without changing req->rsk_listener, bad things will happen.
I also have similar concern on the inconsistency in req->rsk_listener.
The fix-up in req->rsk_listener for the TFO req in patch 4
makes it clear that req->rsk_listener should be updated during
the migration instead of asking a much later code path
to accommodate this inconsistent req->rsk_listener pointer.
When I started this patchset, I read this thread and misunderstood that I
had to migrate sockets in O(1) for scalability. So, I selected the fix-up
approach and checked rsk_listener is not used except for TFO.
---8<---
Whole point of BPF was to avoid iterate through all sockets [1],
and let user space use whatever selection logic it needs.
[1] This was okay with up to 16 sockets. But with 128 it does not scale.
---&<---
https://lore.kernel.org/netdev/1458837191.12033.4.camel@edumazet-glaptop3.roam.corp.google.com/
However, I've read it again, and this was about iterating over listeners
to select a new listener, not about iterating over requests...
In this patchset, we can select a listener in O(1) and it is enough.
quoted
The current inet_csk_listen_stop() is already iterating
the icsk_accept_queue and fastopenq. The extra cost
in updating rsk_listener may be just noise?
Exactly.
If we end up iterating requests, it is better to migrate than close. I will
update each rsk_listener in inet_csk_reqsk_queue_migrate() in v3 patchset.
To be clear, I meant to do migration in inet_csk_listen_stop() instead
of doing it in the new inet_csk_reqsk_queue_migrate() which reqires a
double lock and then need to re-bring in the whole spin_lock_bh_nested
patch in the patch 3 of v2.
e.g. in the first while loop in inet_csk_listen_stop(),
if there is a target to migrate to, it can do
something similar to inet_csk_reqsk_queue_add(target_sk, ...)
instead of doing the current inet_child_forget().
It probably needs something different from
inet_csk_reqsk_queue_add(), e.g. also update rsk_listener,
but the idea should be similar.
Since the rsk_listener has to be updated one by one, there is
really no point to do the list splicing which requires
the double lock.
I think it is a bit complex to pass the new listener from
reuseport_detach_sock() to inet_csk_listen_stop().
__tcp_close/tcp_disconnect/tcp_abort
|-tcp_set_state
| |-unhash
| |-reuseport_detach_sock (return nsk)
|-inet_csk_listen_stop
Picking the new listener does not have to be done in
reuseport_detach_sock().
IIUC, it is done there only because it prefers to pick
the last sk from socks[] when bpf prog is not attached.
This seems to get into the way of exploring other potential
implementation options.
Merging the discussion on the last socks[] pick from another thread:
I think most applications start new listeners before closing listeners, in
this case, selecting the moved socket as the new listener works well.
quoted
That said, if it is still desired to do a random pick by kernel when
there is no bpf prog, it probably makes sense to guard it in a sysctl as
suggested in another reply. To keep it simple, I would also keep this
kernel-pick consistent instead of request socket is doing something
different from the unhash path.
Then, is this way better to keep kernel-pick consistent?
1. call reuseport_select_migrated_sock() without sk_hash from any path
2. generate a random number in reuseport_select_migrated_sock()
3. pass it to __reuseport_select_sock() only for select-by-hash
(4. pass 0 as sk_hash to bpf_run_sk_reuseport not to use it)
5. do migration per queue in inet_csk_listen_stop() or per request in
receive path.
I understand it is beautiful to keep consistensy, but also think
the kernel-pick with heuristic performs better than random-pick.
I think discussing the best kernel pick without explicit user input
is going to be a dead end. There is always a case that
makes this heuristic (or guess) fail. e.g. what if multiple
sk(s) being closed are always the last one in the socks[]?
all their child sk(s) will then be piled up at one listen sk
because the last socks[] is always picked?
Lets assume the last socks[] is indeed the best for all cases. Then why
the in-progress req don't pick it this way? I feel the implementation
is doing what is convenient at that point. And that is fine, I think
for kernel-pick, it should just go for simplicity and stay with
the random(/hash) pick instead of pretending the kernel knows the
application must operate in a certain way. It is fine
that the pick was wrong, the kernel will eventually move the
childs/reqs to the survived listen sk.
[ I still think the kernel should not even pick if
there is no bpf prog to instruct how to pick
but I am fine as long as there is a sysctl to
guard this. ]
I would rather focus on ensuring the bpf prog getting what it
needs to make the migration pick. A few things
I would like to discuss and explore:
If we splice requests like this, we do not need double lock?
1. lock the accept queue of the old listener
2. unlink all requests and decrement refcount
3. unlock
4. update all requests with new listener
I guess updating rsk_listener can be done without acquiring
the lock in (5) below is because it is done under the
listening_hash's bucket lock (and also the global reuseport_lock) so
that the new listener will stay in TCP_LISTEN state?
I am not sure iterating the queue under these
locks is a very good thing to do though. The queue may not be
very long in usual setup but still let see
if that can be avoided.
Do you think the iteration can be done without holding
bucket lock and the global reuseport_lock? inet_csk_reqsk_queue_add()
is taking the rskq_lock and then check for TCP_LISTEN. May be
something similar can be done also?
While doing BPF_SK_REUSEPORT_MIGRATE_REQUEST,
the bpf prog can pick per req and have the sk_hash.
However, while doing BPF_SK_REUSEPORT_MIGRATE_QUEUE,
the bpf prog currently does not have a chance to
pick individually for each req/child on the queue.
Since it is iterating the queue anyway, does it make
sense to also call the bpf to pick for each req/child
in the queue? It then can pass sk_hash (from child->sk_hash?)
to the bpf prog also instead of current 0. The cost of calling
bpf prog is not really that much / signficant at the
migration code path. If the queue is somehow
unusally long, there is already an existing
cond_resched() in inet_csk_listen_stop().
Then, instead of adding sk_reuseport_md->migration,
it can then add sk_reuseport_md->migrate_sk.
"migrate_sk = req" for in-progress req and "migrate_sk = child"
for iterating acceptq. The bpf_prog can then tell what sk (req or child)
it is migrating by reading migrate_sk->state. It can then also
learn the 4 tuples src/dst ip/port while skb is missing.
The sk_reuseport_md->sk can still point to the closed sk
such that the bpf prog can learn the cookie.
I suspect a few things between BPF_SK_REUSEPORT_MIGRATE_REQUEST
and BPF_SK_REUSEPORT_MIGRATE_QUEUE can be folded together
by doing the above. It also gives a more consistent
interface for the bpf prog, no more MIGRATE_QUEUE vs MIGRATE_REQUEST.
5. lock the accept queue of the new listener
6. splice requests and increment refcount
7. unlock
Also, I think splicing is better to keep the order of requests. Adding one
by one reverses it.
It can keep the order but I think it is orthogonal here.
From: Martin KaFai Lau <redacted>
Date: Tue, 8 Dec 2020 19:09:03 -0800
On Tue, Dec 08, 2020 at 05:17:48PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 23:34:41 -0800
quoted
On Tue, Dec 08, 2020 at 03:31:34PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 12:33:15 -0800
quoted
On Thu, Dec 03, 2020 at 11:14:24PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
quoted
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
I fail to understand how the kernel can run fine right after this patch, before following patches are merged.
I will squash the two or reorganize them into definition part and migration
part.
quoted
All request sockets in the socket accept queue MUST have their rsk_listener set to the listener,
this is how we designed things (each request socket has a reference taken on the listener)
We might even have some "BUG_ON(sk != req->rsk_listener);" in some places.
Since you splice list from old listener to the new one, without changing req->rsk_listener, bad things will happen.
I also have similar concern on the inconsistency in req->rsk_listener.
The fix-up in req->rsk_listener for the TFO req in patch 4
makes it clear that req->rsk_listener should be updated during
the migration instead of asking a much later code path
to accommodate this inconsistent req->rsk_listener pointer.
When I started this patchset, I read this thread and misunderstood that I
had to migrate sockets in O(1) for scalability. So, I selected the fix-up
approach and checked rsk_listener is not used except for TFO.
---8<---
Whole point of BPF was to avoid iterate through all sockets [1],
and let user space use whatever selection logic it needs.
[1] This was okay with up to 16 sockets. But with 128 it does not scale.
---&<---
https://lore.kernel.org/netdev/1458837191.12033.4.camel@edumazet-glaptop3.roam.corp.google.com/
However, I've read it again, and this was about iterating over listeners
to select a new listener, not about iterating over requests...
In this patchset, we can select a listener in O(1) and it is enough.
quoted
The current inet_csk_listen_stop() is already iterating
the icsk_accept_queue and fastopenq. The extra cost
in updating rsk_listener may be just noise?
Exactly.
If we end up iterating requests, it is better to migrate than close. I will
update each rsk_listener in inet_csk_reqsk_queue_migrate() in v3 patchset.
To be clear, I meant to do migration in inet_csk_listen_stop() instead
of doing it in the new inet_csk_reqsk_queue_migrate() which reqires a
double lock and then need to re-bring in the whole spin_lock_bh_nested
patch in the patch 3 of v2.
e.g. in the first while loop in inet_csk_listen_stop(),
if there is a target to migrate to, it can do
something similar to inet_csk_reqsk_queue_add(target_sk, ...)
instead of doing the current inet_child_forget().
It probably needs something different from
inet_csk_reqsk_queue_add(), e.g. also update rsk_listener,
but the idea should be similar.
Since the rsk_listener has to be updated one by one, there is
really no point to do the list splicing which requires
the double lock.
I think it is a bit complex to pass the new listener from
reuseport_detach_sock() to inet_csk_listen_stop().
__tcp_close/tcp_disconnect/tcp_abort
|-tcp_set_state
| |-unhash
| |-reuseport_detach_sock (return nsk)
|-inet_csk_listen_stop
Picking the new listener does not have to be done in
reuseport_detach_sock().
IIUC, it is done there only because it prefers to pick
the last sk from socks[] when bpf prog is not attached.
This seems to get into the way of exploring other potential
implementation options.
Yes.
This is just idea, but we can reserve the last index of socks[] to hold the
last 'moved' socket in reuseport_detach_sock() and use it in
inet_csk_listen_stop().
Merging the discussion on the last socks[] pick from another thread:
quoted
I think most applications start new listeners before closing listeners, in
this case, selecting the moved socket as the new listener works well.
quoted
That said, if it is still desired to do a random pick by kernel when
there is no bpf prog, it probably makes sense to guard it in a sysctl as
suggested in another reply. To keep it simple, I would also keep this
kernel-pick consistent instead of request socket is doing something
different from the unhash path.
Then, is this way better to keep kernel-pick consistent?
1. call reuseport_select_migrated_sock() without sk_hash from any path
2. generate a random number in reuseport_select_migrated_sock()
3. pass it to __reuseport_select_sock() only for select-by-hash
(4. pass 0 as sk_hash to bpf_run_sk_reuseport not to use it)
5. do migration per queue in inet_csk_listen_stop() or per request in
receive path.
I understand it is beautiful to keep consistensy, but also think
the kernel-pick with heuristic performs better than random-pick.
I think discussing the best kernel pick without explicit user input
is going to be a dead end. There is always a case that
makes this heuristic (or guess) fail. e.g. what if multiple
sk(s) being closed are always the last one in the socks[]?
all their child sk(s) will then be piled up at one listen sk
because the last socks[] is always picked?
There can be such a case, but it means the newly listened sockets are
closed earlier than old ones.
Lets assume the last socks[] is indeed the best for all cases. Then why
the in-progress req don't pick it this way? I feel the implementation
is doing what is convenient at that point. And that is fine, I think
In this patchset, I originally assumed four things:
migration should be done
(i) from old to new
(ii) to redistribute requests evenly as possible
(iii) to keep the order of requests in the queue
(resulting in splicing queues)
(iv) in O(1) for scalability
(resulting in fix-up rsk_listener approach)
I selected the last socket in unhash path to satisfy above four because the
last socket changes at every close() syscall if application closes from
older socket.
But in receiving ACK or retransmitting SYN+ACK, we cannot get the last
'moved' socket. Even if we reserve the last 'moved' socket in the last
index by the idea above, we cannot sure the last socket is changed after
close() for each req->listener. For example, we have listeners A, B, C, and
D, and then call close(A) and close(B), and receive the final ACKs for A
and B, then both of them are assigned to C. In this case, A for D and B for
C is desired. So, selecting the last socket in socks[] for incoming
requests cannnot realize (ii).
This is why I selected the last moved socket in unhash path and a random
listener in receive path.
for kernel-pick, it should just go for simplicity and stay with
the random(/hash) pick instead of pretending the kernel knows the
application must operate in a certain way. It is fine
that the pick was wrong, the kernel will eventually move the
childs/reqs to the survived listen sk.
Exactly. Also the heuristic way is not fair for every application.
After reading below idea (migrated_sk), I think random-pick is better
at simplicity and passing each sk.
[ I still think the kernel should not even pick if
there is no bpf prog to instruct how to pick
but I am fine as long as there is a sysctl to
guard this. ]
Unless different applications listen on the same port, random-pick can save
connections which would be aborted. So, I would add a sysctl to do
migration when no eBPF prog is attached.
I would rather focus on ensuring the bpf prog getting what it
needs to make the migration pick. A few things
I would like to discuss and explore:
quoted
If we splice requests like this, we do not need double lock?
1. lock the accept queue of the old listener
2. unlink all requests and decrement refcount
3. unlock
4. update all requests with new listener
I guess updating rsk_listener can be done without acquiring
the lock in (5) below is because it is done under the
listening_hash's bucket lock (and also the global reuseport_lock) so
that the new listener will stay in TCP_LISTEN state?
If we do migration in inet_unhash(), the lock is held, but it is not held
in inet_csk_listen_stop().
I am not sure iterating the queue under these
locks is a very good thing to do though. The queue may not be
very long in usual setup but still let see
if that can be avoided.
I agree, lock should not be held long.
Do you think the iteration can be done without holding
bucket lock and the global reuseport_lock? inet_csk_reqsk_queue_add()
is taking the rskq_lock and then check for TCP_LISTEN. May be
something similar can be done also?
I think either one is necessary at least, so if the sk_state of selected
listener is TCP_CLOSE (this is mostly by random-pick of kernel), then we
have to fall back to call inet_child_forget().
While doing BPF_SK_REUSEPORT_MIGRATE_REQUEST,
the bpf prog can pick per req and have the sk_hash.
However, while doing BPF_SK_REUSEPORT_MIGRATE_QUEUE,
the bpf prog currently does not have a chance to
pick individually for each req/child on the queue.
Since it is iterating the queue anyway, does it make
sense to also call the bpf to pick for each req/child
in the queue? It then can pass sk_hash (from child->sk_hash?)
to the bpf prog also instead of current 0. The cost of calling
bpf prog is not really that much / signficant at the
migration code path. If the queue is somehow
unusally long, there is already an existing
cond_resched() in inet_csk_listen_stop().
Then, instead of adding sk_reuseport_md->migration,
it can then add sk_reuseport_md->migrate_sk.
"migrate_sk = req" for in-progress req and "migrate_sk = child"
for iterating acceptq. The bpf_prog can then tell what sk (req or child)
it is migrating by reading migrate_sk->state. It can then also
learn the 4 tuples src/dst ip/port while skb is missing.
The sk_reuseport_md->sk can still point to the closed sk
such that the bpf prog can learn the cookie.
I suspect a few things between BPF_SK_REUSEPORT_MIGRATE_REQUEST
and BPF_SK_REUSEPORT_MIGRATE_QUEUE can be folded together
by doing the above. It also gives a more consistent
interface for the bpf prog, no more MIGRATE_QUEUE vs MIGRATE_REQUEST.
I think this is really nice idea. Also, I tried to implement random-pick
one by one in inet_csk_listen_stop() yesterday, I found a concern about how
to handle requests in TFO queue.
The request can be already accepted, so passing it to eBPF prog is
confusing? But, redistributing randomly can affect all listeners
unnecessary. How should we handle such requests?
quoted
5. lock the accept queue of the new listener
6. splice requests and increment refcount
7. unlock
Also, I think splicing is better to keep the order of requests. Adding one
by one reverses it.
It can keep the order but I think it is orthogonal here.
From: Martin KaFai Lau <redacted>
Date: Tue, 8 Dec 2020 19:09:03 -0800
quoted
On Tue, Dec 08, 2020 at 05:17:48PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 23:34:41 -0800
quoted
On Tue, Dec 08, 2020 at 03:31:34PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Mon, 7 Dec 2020 12:33:15 -0800
quoted
On Thu, Dec 03, 2020 at 11:14:24PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Eric Dumazet <redacted>
Date: Tue, 1 Dec 2020 16:25:51 +0100
quoted
On 12/1/20 3:44 PM, Kuniyuki Iwashima wrote:
quoted
This patch lets reuseport_detach_sock() return a pointer of struct sock,
which is used only by inet_unhash(). If it is not NULL,
inet_csk_reqsk_queue_migrate() migrates TCP_ESTABLISHED/TCP_SYN_RECV
sockets from the closing listener to the selected one.
Listening sockets hold incoming connections as a linked list of struct
request_sock in the accept queue, and each request has reference to a full
socket and its listener. In inet_csk_reqsk_queue_migrate(), we only unlink
the requests from the closing listener's queue and relink them to the head
of the new listener's queue. We do not process each request and its
reference to the listener, so the migration completes in O(1) time
complexity. However, in the case of TCP_SYN_RECV sockets, we take special
care in the next commit.
By default, the kernel selects a new listener randomly. In order to pick
out a different socket every time, we select the last element of socks[] as
the new listener. This behaviour is based on how the kernel moves sockets
in socks[]. (See also [1])
Basically, in order to redistribute sockets evenly, we have to use an eBPF
program called in the later commit, but as the side effect of such default
selection, the kernel can redistribute old requests evenly to new listeners
for a specific case where the application replaces listeners by
generations.
For example, we call listen() for four sockets (A, B, C, D), and close the
first two by turns. The sockets move in socks[] like below.
socks[0] : A <-. socks[0] : D socks[0] : D
socks[1] : B | => socks[1] : B <-. => socks[1] : C
socks[2] : C | socks[2] : C --'
socks[3] : D --'
Then, if C and D have newer settings than A and B, and each socket has a
request (a, b, c, d) in their accept queue, we can redistribute old
requests evenly to new listeners.
socks[0] : A (a) <-. socks[0] : D (a + d) socks[0] : D (a + d)
socks[1] : B (b) | => socks[1] : B (b) <-. => socks[1] : C (b + c)
socks[2] : C (c) | socks[2] : C (c) --'
socks[3] : D (d) --'
Here, (A, D) or (B, C) can have different application settings, but they
MUST have the same settings at the socket API level; otherwise, unexpected
error may happen. For instance, if only the new listeners have
TCP_SAVE_SYN, old requests do not have SYN data, so the application will
face inconsistency and cause an error.
Therefore, if there are different kinds of sockets, we must attach an eBPF
program described in later commits.
Link: https://lore.kernel.org/netdev/CAEfhGiyG8Y_amDZ2C8dQoQqjZJMHjTY76b=KBkTKcBtA=dhdGQ@mail.gmail.com/
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 1 +
include/net/sock_reuseport.h | 2 +-
net/core/sock_reuseport.c | 10 +++++++++-
net/ipv4/inet_connection_sock.c | 30 ++++++++++++++++++++++++++++++
net/ipv4/inet_hashtables.c | 9 +++++++--
5 files changed, 48 insertions(+), 4 deletions(-)
Are you sure lockdep is happy with this ?
I would guess it should complain, because :
lock(A);
lock(B);
...
unlock(B);
unlock(A);
will fail when the opposite action happens eventually
lock(B);
lock(A);
...
unlock(A);
unlock(B);
I enabled lockdep and did not see warnings of lockdep.
Also, the inversion deadlock does not happen in this case.
In reuseport_detach_sock(), sk is moved backward in socks[] and poped out
from the eBPF map, so the old listener will not be selected as the new
listener.
I fail to understand how the kernel can run fine right after this patch, before following patches are merged.
I will squash the two or reorganize them into definition part and migration
part.
quoted
All request sockets in the socket accept queue MUST have their rsk_listener set to the listener,
this is how we designed things (each request socket has a reference taken on the listener)
We might even have some "BUG_ON(sk != req->rsk_listener);" in some places.
Since you splice list from old listener to the new one, without changing req->rsk_listener, bad things will happen.
I also have similar concern on the inconsistency in req->rsk_listener.
The fix-up in req->rsk_listener for the TFO req in patch 4
makes it clear that req->rsk_listener should be updated during
the migration instead of asking a much later code path
to accommodate this inconsistent req->rsk_listener pointer.
When I started this patchset, I read this thread and misunderstood that I
had to migrate sockets in O(1) for scalability. So, I selected the fix-up
approach and checked rsk_listener is not used except for TFO.
---8<---
Whole point of BPF was to avoid iterate through all sockets [1],
and let user space use whatever selection logic it needs.
[1] This was okay with up to 16 sockets. But with 128 it does not scale.
---&<---
https://lore.kernel.org/netdev/1458837191.12033.4.camel@edumazet-glaptop3.roam.corp.google.com/
However, I've read it again, and this was about iterating over listeners
to select a new listener, not about iterating over requests...
In this patchset, we can select a listener in O(1) and it is enough.
quoted
The current inet_csk_listen_stop() is already iterating
the icsk_accept_queue and fastopenq. The extra cost
in updating rsk_listener may be just noise?
Exactly.
If we end up iterating requests, it is better to migrate than close. I will
update each rsk_listener in inet_csk_reqsk_queue_migrate() in v3 patchset.
To be clear, I meant to do migration in inet_csk_listen_stop() instead
of doing it in the new inet_csk_reqsk_queue_migrate() which reqires a
double lock and then need to re-bring in the whole spin_lock_bh_nested
patch in the patch 3 of v2.
e.g. in the first while loop in inet_csk_listen_stop(),
if there is a target to migrate to, it can do
something similar to inet_csk_reqsk_queue_add(target_sk, ...)
instead of doing the current inet_child_forget().
It probably needs something different from
inet_csk_reqsk_queue_add(), e.g. also update rsk_listener,
but the idea should be similar.
Since the rsk_listener has to be updated one by one, there is
really no point to do the list splicing which requires
the double lock.
I think it is a bit complex to pass the new listener from
reuseport_detach_sock() to inet_csk_listen_stop().
__tcp_close/tcp_disconnect/tcp_abort
|-tcp_set_state
| |-unhash
| |-reuseport_detach_sock (return nsk)
|-inet_csk_listen_stop
Picking the new listener does not have to be done in
reuseport_detach_sock().
IIUC, it is done there only because it prefers to pick
the last sk from socks[] when bpf prog is not attached.
This seems to get into the way of exploring other potential
implementation options.
Yes.
This is just idea, but we can reserve the last index of socks[] to hold the
last 'moved' socket in reuseport_detach_sock() and use it in
inet_csk_listen_stop().
quoted
Merging the discussion on the last socks[] pick from another thread:
quoted
I think most applications start new listeners before closing listeners, in
this case, selecting the moved socket as the new listener works well.
quoted
That said, if it is still desired to do a random pick by kernel when
there is no bpf prog, it probably makes sense to guard it in a sysctl as
suggested in another reply. To keep it simple, I would also keep this
kernel-pick consistent instead of request socket is doing something
different from the unhash path.
Then, is this way better to keep kernel-pick consistent?
1. call reuseport_select_migrated_sock() without sk_hash from any path
2. generate a random number in reuseport_select_migrated_sock()
3. pass it to __reuseport_select_sock() only for select-by-hash
(4. pass 0 as sk_hash to bpf_run_sk_reuseport not to use it)
5. do migration per queue in inet_csk_listen_stop() or per request in
receive path.
I understand it is beautiful to keep consistensy, but also think
the kernel-pick with heuristic performs better than random-pick.
I think discussing the best kernel pick without explicit user input
is going to be a dead end. There is always a case that
makes this heuristic (or guess) fail. e.g. what if multiple
sk(s) being closed are always the last one in the socks[]?
all their child sk(s) will then be piled up at one listen sk
because the last socks[] is always picked?
There can be such a case, but it means the newly listened sockets are
closed earlier than old ones.
quoted
Lets assume the last socks[] is indeed the best for all cases. Then why
the in-progress req don't pick it this way? I feel the implementation
is doing what is convenient at that point. And that is fine, I think
In this patchset, I originally assumed four things:
migration should be done
(i) from old to new
(ii) to redistribute requests evenly as possible
(iii) to keep the order of requests in the queue
(resulting in splicing queues)
(iv) in O(1) for scalability
(resulting in fix-up rsk_listener approach)
I selected the last socket in unhash path to satisfy above four because the
last socket changes at every close() syscall if application closes from
older socket.
But in receiving ACK or retransmitting SYN+ACK, we cannot get the last
'moved' socket. Even if we reserve the last 'moved' socket in the last
index by the idea above, we cannot sure the last socket is changed after
close() for each req->listener. For example, we have listeners A, B, C, and
D, and then call close(A) and close(B), and receive the final ACKs for A
and B, then both of them are assigned to C. In this case, A for D and B for
C is desired. So, selecting the last socket in socks[] for incoming
requests cannnot realize (ii).
This is why I selected the last moved socket in unhash path and a random
listener in receive path.
quoted
for kernel-pick, it should just go for simplicity and stay with
the random(/hash) pick instead of pretending the kernel knows the
application must operate in a certain way. It is fine
that the pick was wrong, the kernel will eventually move the
childs/reqs to the survived listen sk.
Exactly. Also the heuristic way is not fair for every application.
After reading below idea (migrated_sk), I think random-pick is better
at simplicity and passing each sk.
quoted
[ I still think the kernel should not even pick if
there is no bpf prog to instruct how to pick
but I am fine as long as there is a sysctl to
guard this. ]
Unless different applications listen on the same port, random-pick can save
connections which would be aborted. So, I would add a sysctl to do
migration when no eBPF prog is attached.
quoted
I would rather focus on ensuring the bpf prog getting what it
needs to make the migration pick. A few things
I would like to discuss and explore:
quoted
If we splice requests like this, we do not need double lock?
1. lock the accept queue of the old listener
2. unlink all requests and decrement refcount
3. unlock
4. update all requests with new listener
I guess updating rsk_listener can be done without acquiring
the lock in (5) below is because it is done under the
listening_hash's bucket lock (and also the global reuseport_lock) so
that the new listener will stay in TCP_LISTEN state?
If we do migration in inet_unhash(), the lock is held, but it is not held
in inet_csk_listen_stop().
quoted
I am not sure iterating the queue under these
locks is a very good thing to do though. The queue may not be
very long in usual setup but still let see
if that can be avoided.
I agree, lock should not be held long.
quoted
Do you think the iteration can be done without holding
bucket lock and the global reuseport_lock? inet_csk_reqsk_queue_add()
is taking the rskq_lock and then check for TCP_LISTEN. May be
something similar can be done also?
I think either one is necessary at least, so if the sk_state of selected
listener is TCP_CLOSE (this is mostly by random-pick of kernel), then we
have to fall back to call inet_child_forget().
quoted
While doing BPF_SK_REUSEPORT_MIGRATE_REQUEST,
the bpf prog can pick per req and have the sk_hash.
However, while doing BPF_SK_REUSEPORT_MIGRATE_QUEUE,
the bpf prog currently does not have a chance to
pick individually for each req/child on the queue.
Since it is iterating the queue anyway, does it make
sense to also call the bpf to pick for each req/child
in the queue? It then can pass sk_hash (from child->sk_hash?)
to the bpf prog also instead of current 0. The cost of calling
bpf prog is not really that much / signficant at the
migration code path. If the queue is somehow
unusally long, there is already an existing
cond_resched() in inet_csk_listen_stop().
Then, instead of adding sk_reuseport_md->migration,
it can then add sk_reuseport_md->migrate_sk.
"migrate_sk = req" for in-progress req and "migrate_sk = child"
for iterating acceptq. The bpf_prog can then tell what sk (req or child)
it is migrating by reading migrate_sk->state. It can then also
learn the 4 tuples src/dst ip/port while skb is missing.
The sk_reuseport_md->sk can still point to the closed sk
such that the bpf prog can learn the cookie.
I suspect a few things between BPF_SK_REUSEPORT_MIGRATE_REQUEST
and BPF_SK_REUSEPORT_MIGRATE_QUEUE can be folded together
by doing the above. It also gives a more consistent
interface for the bpf prog, no more MIGRATE_QUEUE vs MIGRATE_REQUEST.
I think this is really nice idea. Also, I tried to implement random-pick
one by one in inet_csk_listen_stop() yesterday, I found a concern about how
to handle requests in TFO queue.
The request can be already accepted, so passing it to eBPF prog is
confusing? But, redistributing randomly can affect all listeners
unnecessary. How should we handle such requests?
I've implemented one-by-one migration only for the accept queue for now.
In addition to the concern about TFO queue, I want to discuss which should
we pass NULL or request_sock to eBPF program as migrate_sk when selecting a
listener for SYN ?
---8<---
@@ -1023,9 +1046,11 @@ EXPORT_SYMBOL(inet_csk_complete_hashdance);*/voidinet_csk_listen_stop(structsock*sk){+structsock_reuseport*reuseport_cb=rcu_access_pointer(sk->sk_reuseport_cb);structinet_connection_sock*icsk=inet_csk(sk);structrequest_sock_queue*queue=&icsk->icsk_accept_queue;structrequest_sock*next,*req;+structsock*nsk;/* Following specs, it would be better either to send FIN*(andenterFIN-WAIT-1,itisnormalclose)
5. lock the accept queue of the new listener
6. splice requests and increment refcount
7. unlock
Also, I think splicing is better to keep the order of requests. Adding one
by one reverses it.
It can keep the order but I think it is orthogonal here.
From: Martin KaFai Lau <hidden> Date: 2020-12-10 00:08:19
On Tue, Dec 01, 2020 at 11:44:12PM +0900, Kuniyuki Iwashima wrote:
quoted hunk
This patch renames reuseport_select_sock() to __reuseport_select_sock() and
adds two wrapper function of it to pass the migration type defined in the
previous commit.
reuseport_select_sock : BPF_SK_REUSEPORT_MIGRATE_NO
reuseport_select_migrated_sock : BPF_SK_REUSEPORT_MIGRATE_REQUEST
As mentioned before, we have to select a new listener for TCP_NEW_SYN_RECV
requests at receiving the final ACK or sending a SYN+ACK. Therefore, this
patch also changes the code to call reuseport_select_migrated_sock() even
if the listening socket is TCP_CLOSE. If we can pick out a listening socket
from the reuseport group, we rewrite request_sock.rsk_listener and resume
processing the request.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 12 +++++++++++
include/net/request_sock.h | 13 ++++++++++++
include/net/sock_reuseport.h | 8 +++----
net/core/sock_reuseport.c | 34 ++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 13 ++++++++++--
net/ipv4/tcp_ipv4.c | 9 ++++++--
net/ipv6/tcp_ipv6.c | 9 ++++++--
7 files changed, 81 insertions(+), 17 deletions(-)
not sure if it is safe to do here.
IIUC, when the req->rsk_refcnt is held, it also holds a refcnt
to req->rsk_listener such that sock_hold(req->rsk_listener) is
safe because its sk_refcnt is not zero.
@@ -743,8 +743,17 @@ static void reqsk_timer_handler(struct timer_list *t)structrequest_sock_queue*queue=&icsk->icsk_accept_queue;intmax_syn_ack_retries,qlen,expire=0,resend=0;-if(inet_sk_state_load(sk_listener)!=TCP_LISTEN)-gotodrop;+if(inet_sk_state_load(sk_listener)!=TCP_LISTEN){+sk_listener=reuseport_select_migrated_sock(sk_listener,+req_to_sk(req)->sk_hash,NULL);+if(!sk_listener){+sk_listener=req->rsk_listener;+gotodrop;+}+inet_csk_reqsk_queue_migrated(req->rsk_listener,sk_listener,req);+icsk=inet_csk(sk_listener);+queue=&icsk->icsk_accept_queue;+}max_syn_ack_retries=icsk->icsk_syn_retries?:net->ipv4.sysctl_tcp_synack_retries;/* Normally all the openreqs are young and become mature
@@ -1973,8 +1973,13 @@ int tcp_v4_rcv(struct sk_buff *skb)gotocsum_error;}if(unlikely(sk->sk_state!=TCP_LISTEN)){-inet_csk_reqsk_queue_drop_and_put(sk,req);-gotolookup;+nsk=reuseport_select_migrated_sock(sk,req_to_sk(req)->sk_hash,skb);+if(!nsk){+inet_csk_reqsk_queue_drop_and_put(sk,req);+gotolookup;+}+inet_csk_reqsk_queue_migrated(sk,nsk,req);+sk=nsk;}/* We own a reference on the listener, increase it again*aswemightloseittoosoon.
From: Martin KaFai Lau <hidden> Date: 2020-12-10 01:54:45
On Thu, Dec 10, 2020 at 01:57:19AM +0900, Kuniyuki Iwashima wrote:
[ ... ]
quoted
quoted
quoted
I think it is a bit complex to pass the new listener from
reuseport_detach_sock() to inet_csk_listen_stop().
__tcp_close/tcp_disconnect/tcp_abort
|-tcp_set_state
| |-unhash
| |-reuseport_detach_sock (return nsk)
|-inet_csk_listen_stop
Picking the new listener does not have to be done in
reuseport_detach_sock().
IIUC, it is done there only because it prefers to pick
the last sk from socks[] when bpf prog is not attached.
This seems to get into the way of exploring other potential
implementation options.
Yes.
This is just idea, but we can reserve the last index of socks[] to hold the
last 'moved' socket in reuseport_detach_sock() and use it in
inet_csk_listen_stop().
quoted
Merging the discussion on the last socks[] pick from another thread:
quoted
I think most applications start new listeners before closing listeners, in
this case, selecting the moved socket as the new listener works well.
quoted
That said, if it is still desired to do a random pick by kernel when
there is no bpf prog, it probably makes sense to guard it in a sysctl as
suggested in another reply. To keep it simple, I would also keep this
kernel-pick consistent instead of request socket is doing something
different from the unhash path.
Then, is this way better to keep kernel-pick consistent?
1. call reuseport_select_migrated_sock() without sk_hash from any path
2. generate a random number in reuseport_select_migrated_sock()
3. pass it to __reuseport_select_sock() only for select-by-hash
(4. pass 0 as sk_hash to bpf_run_sk_reuseport not to use it)
5. do migration per queue in inet_csk_listen_stop() or per request in
receive path.
I understand it is beautiful to keep consistensy, but also think
the kernel-pick with heuristic performs better than random-pick.
I think discussing the best kernel pick without explicit user input
is going to be a dead end. There is always a case that
makes this heuristic (or guess) fail. e.g. what if multiple
sk(s) being closed are always the last one in the socks[]?
all their child sk(s) will then be piled up at one listen sk
because the last socks[] is always picked?
There can be such a case, but it means the newly listened sockets are
closed earlier than old ones.
quoted
Lets assume the last socks[] is indeed the best for all cases. Then why
the in-progress req don't pick it this way? I feel the implementation
is doing what is convenient at that point. And that is fine, I think
In this patchset, I originally assumed four things:
migration should be done
(i) from old to new
(ii) to redistribute requests evenly as possible
(iii) to keep the order of requests in the queue
(resulting in splicing queues)
(iv) in O(1) for scalability
(resulting in fix-up rsk_listener approach)
I selected the last socket in unhash path to satisfy above four because the
last socket changes at every close() syscall if application closes from
older socket.
But in receiving ACK or retransmitting SYN+ACK, we cannot get the last
'moved' socket. Even if we reserve the last 'moved' socket in the last
index by the idea above, we cannot sure the last socket is changed after
close() for each req->listener. For example, we have listeners A, B, C, and
D, and then call close(A) and close(B), and receive the final ACKs for A
and B, then both of them are assigned to C. In this case, A for D and B for
C is desired. So, selecting the last socket in socks[] for incoming
requests cannnot realize (ii).
This is why I selected the last moved socket in unhash path and a random
listener in receive path.
quoted
for kernel-pick, it should just go for simplicity and stay with
the random(/hash) pick instead of pretending the kernel knows the
application must operate in a certain way. It is fine
that the pick was wrong, the kernel will eventually move the
childs/reqs to the survived listen sk.
Exactly. Also the heuristic way is not fair for every application.
After reading below idea (migrated_sk), I think random-pick is better
at simplicity and passing each sk.
quoted
[ I still think the kernel should not even pick if
there is no bpf prog to instruct how to pick
but I am fine as long as there is a sysctl to
guard this. ]
Unless different applications listen on the same port, random-pick can save
connections which would be aborted. So, I would add a sysctl to do
migration when no eBPF prog is attached.
quoted
I would rather focus on ensuring the bpf prog getting what it
needs to make the migration pick. A few things
I would like to discuss and explore:
quoted
If we splice requests like this, we do not need double lock?
1. lock the accept queue of the old listener
2. unlink all requests and decrement refcount
3. unlock
4. update all requests with new listener
I guess updating rsk_listener can be done without acquiring
the lock in (5) below is because it is done under the
listening_hash's bucket lock (and also the global reuseport_lock) so
that the new listener will stay in TCP_LISTEN state?
If we do migration in inet_unhash(), the lock is held, but it is not held
in inet_csk_listen_stop().
quoted
I am not sure iterating the queue under these
locks is a very good thing to do though. The queue may not be
very long in usual setup but still let see
if that can be avoided.
I agree, lock should not be held long.
quoted
Do you think the iteration can be done without holding
bucket lock and the global reuseport_lock? inet_csk_reqsk_queue_add()
is taking the rskq_lock and then check for TCP_LISTEN. May be
something similar can be done also?
I think either one is necessary at least, so if the sk_state of selected
listener is TCP_CLOSE (this is mostly by random-pick of kernel), then we
have to fall back to call inet_child_forget().
quoted
While doing BPF_SK_REUSEPORT_MIGRATE_REQUEST,
the bpf prog can pick per req and have the sk_hash.
However, while doing BPF_SK_REUSEPORT_MIGRATE_QUEUE,
the bpf prog currently does not have a chance to
pick individually for each req/child on the queue.
Since it is iterating the queue anyway, does it make
sense to also call the bpf to pick for each req/child
in the queue? It then can pass sk_hash (from child->sk_hash?)
to the bpf prog also instead of current 0. The cost of calling
bpf prog is not really that much / signficant at the
migration code path. If the queue is somehow
unusally long, there is already an existing
cond_resched() in inet_csk_listen_stop().
Then, instead of adding sk_reuseport_md->migration,
it can then add sk_reuseport_md->migrate_sk.
"migrate_sk = req" for in-progress req and "migrate_sk = child"
for iterating acceptq. The bpf_prog can then tell what sk (req or child)
it is migrating by reading migrate_sk->state. It can then also
learn the 4 tuples src/dst ip/port while skb is missing.
The sk_reuseport_md->sk can still point to the closed sk
such that the bpf prog can learn the cookie.
I suspect a few things between BPF_SK_REUSEPORT_MIGRATE_REQUEST
and BPF_SK_REUSEPORT_MIGRATE_QUEUE can be folded together
by doing the above. It also gives a more consistent
interface for the bpf prog, no more MIGRATE_QUEUE vs MIGRATE_REQUEST.
I think this is really nice idea. Also, I tried to implement random-pick
one by one in inet_csk_listen_stop() yesterday, I found a concern about how
to handle requests in TFO queue.
The request can be already accepted, so passing it to eBPF prog is
confusing? But, redistributing randomly can affect all listeners
unnecessary. How should we handle such requests?
I've implemented one-by-one migration only for the accept queue for now.
In addition to the concern about TFO queue,
You meant this queue: queue->fastopenq.rskq_rst_head?
Can "req" be passed?
I did not look up the lock/race in details for that though.
I want to discuss which should
we pass NULL or request_sock to eBPF program as migrate_sk when selecting a
listener for SYN ?
hmmm... not sure I understand your question.
You meant the existing lookup listener case from inet_lhash2_lookup()?
There is nothing to migrate at that point, so NULL makes sense to me.
migrate_sk's type should be PTR_TO_SOCK_COMMON_OR_NULL.
@@ -1023,9 +1046,11 @@ EXPORT_SYMBOL(inet_csk_complete_hashdance); */ void inet_csk_listen_stop(struct sock *sk) {+ struct sock_reuseport *reuseport_cb = rcu_access_pointer(sk->sk_reuseport_cb); struct inet_connection_sock *icsk = inet_csk(sk); struct request_sock_queue *queue = &icsk->icsk_accept_queue; struct request_sock *next, *req;+ struct sock *nsk; /* Following specs, it would be better either to send FIN * (and enter FIN-WAIT-1, it is normal close)
5. lock the accept queue of the new listener
6. splice requests and increment refcount
7. unlock
Also, I think splicing is better to keep the order of requests. Adding one
by one reverses it.
It can keep the order but I think it is orthogonal here.
From: Martin KaFai Lau <redacted>
Date: Wed, 9 Dec 2020 16:07:07 -0800
On Tue, Dec 01, 2020 at 11:44:12PM +0900, Kuniyuki Iwashima wrote:
quoted
This patch renames reuseport_select_sock() to __reuseport_select_sock() and
adds two wrapper function of it to pass the migration type defined in the
previous commit.
reuseport_select_sock : BPF_SK_REUSEPORT_MIGRATE_NO
reuseport_select_migrated_sock : BPF_SK_REUSEPORT_MIGRATE_REQUEST
As mentioned before, we have to select a new listener for TCP_NEW_SYN_RECV
requests at receiving the final ACK or sending a SYN+ACK. Therefore, this
patch also changes the code to call reuseport_select_migrated_sock() even
if the listening socket is TCP_CLOSE. If we can pick out a listening socket
from the reuseport group, we rewrite request_sock.rsk_listener and resume
processing the request.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 12 +++++++++++
include/net/request_sock.h | 13 ++++++++++++
include/net/sock_reuseport.h | 8 +++----
net/core/sock_reuseport.c | 34 ++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 13 ++++++++++--
net/ipv4/tcp_ipv4.c | 9 ++++++--
net/ipv6/tcp_ipv6.c | 9 ++++++--
7 files changed, 81 insertions(+), 17 deletions(-)
not sure if it is safe to do here.
IIUC, when the req->rsk_refcnt is held, it also holds a refcnt
to req->rsk_listener such that sock_hold(req->rsk_listener) is
safe because its sk_refcnt is not zero.
I think it is safe to call sock_put() for the old listener here.
Without this patchset, at receiving the final ACK or retransmitting
SYN+ACK, if sk_state == TCP_CLOSE, sock_put(req->rsk_listener) is done
by calling reqsk_put() twice in inet_csk_reqsk_queue_drop_and_put(). And
then, we do `goto lookup;` and overwrite the sk.
In the v2 patchset, refcount_inc_not_zero() is done for the new listener in
reuseport_select_migrated_sock(), so we have to call sock_put() for the old
listener instead to free it properly.
---8<---
+struct sock *reuseport_select_migrated_sock(struct sock *sk, u32 hash,
+ struct sk_buff *skb)
+{
+ struct sock *nsk;
+
+ nsk = __reuseport_select_sock(sk, hash, skb, 0, BPF_SK_REUSEPORT_MIGRATE_REQUEST);
+ if (nsk && likely(refcount_inc_not_zero(&nsk->sk_refcnt)))
+ return nsk;
+
+ return NULL;
+}
+EXPORT_SYMBOL(reuseport_select_migrated_sock);
---8<---
https://lore.kernel.org/netdev/20201207132456.65472-8-kuniyu@amazon.co.jp/
@@ -743,8 +743,17 @@ static void reqsk_timer_handler(struct timer_list *t)structrequest_sock_queue*queue=&icsk->icsk_accept_queue;intmax_syn_ack_retries,qlen,expire=0,resend=0;-if(inet_sk_state_load(sk_listener)!=TCP_LISTEN)-gotodrop;+if(inet_sk_state_load(sk_listener)!=TCP_LISTEN){+sk_listener=reuseport_select_migrated_sock(sk_listener,+req_to_sk(req)->sk_hash,NULL);+if(!sk_listener){+sk_listener=req->rsk_listener;+gotodrop;+}+inet_csk_reqsk_queue_migrated(req->rsk_listener,sk_listener,req);+icsk=inet_csk(sk_listener);+queue=&icsk->icsk_accept_queue;+}max_syn_ack_retries=icsk->icsk_syn_retries?:net->ipv4.sysctl_tcp_synack_retries;/* Normally all the openreqs are young and become mature
@@ -1973,8 +1973,13 @@ int tcp_v4_rcv(struct sk_buff *skb)gotocsum_error;}if(unlikely(sk->sk_state!=TCP_LISTEN)){-inet_csk_reqsk_queue_drop_and_put(sk,req);-gotolookup;+nsk=reuseport_select_migrated_sock(sk,req_to_sk(req)->sk_hash,skb);+if(!nsk){+inet_csk_reqsk_queue_drop_and_put(sk,req);+gotolookup;+}+inet_csk_reqsk_queue_migrated(sk,nsk,req);+sk=nsk;}/* We own a reference on the listener, increase it again*aswemightloseittoosoon.
@@ -1635,8 +1635,13 @@ INDIRECT_CALLABLE_SCOPE int tcp_v6_rcv(struct sk_buff *skb)gotocsum_error;}if(unlikely(sk->sk_state!=TCP_LISTEN)){-inet_csk_reqsk_queue_drop_and_put(sk,req);-gotolookup;+nsk=reuseport_select_migrated_sock(sk,req_to_sk(req)->sk_hash,skb);+if(!nsk){+inet_csk_reqsk_queue_drop_and_put(sk,req);+gotolookup;+}+inet_csk_reqsk_queue_migrated(sk,nsk,req);+sk=nsk;}sock_hold(sk);
For example, this sock_hold(sk). sk here is req->rsk_listener.
After migration, this is for the new listener and it is safe because
refcount_inc_not_zero() for the new listener is called in
reuseport_select_migerate_sock().
From: Martin KaFai Lau <redacted>
Date: Wed, 9 Dec 2020 17:53:19 -0800
On Thu, Dec 10, 2020 at 01:57:19AM +0900, Kuniyuki Iwashima wrOAote:
[ ... ]
quoted
quoted
quoted
quoted
I think it is a bit complex to pass the new listener from
reuseport_detach_sock() to inet_csk_listen_stop().
__tcp_close/tcp_disconnect/tcp_abort
|-tcp_set_state
| |-unhash
| |-reuseport_detach_sock (return nsk)
|-inet_csk_listen_stop
Picking the new listener does not have to be done in
reuseport_detach_sock().
IIUC, it is done there only because it prefers to pick
the last sk from socks[] when bpf prog is not attached.
This seems to get into the way of exploring other potential
implementation options.
Yes.
This is just idea, but we can reserve the last index of socks[] to hold the
last 'moved' socket in reuseport_detach_sock() and use it in
inet_csk_listen_stop().
quoted
Merging the discussion on the last socks[] pick from another thread:
quoted
I think most applications start new listeners before closing listeners, in
this case, selecting the moved socket as the new listener works well.
quoted
That said, if it is still desired to do a random pick by kernel when
there is no bpf prog, it probably makes sense to guard it in a sysctl as
suggested in another reply. To keep it simple, I would also keep this
kernel-pick consistent instead of request socket is doing something
different from the unhash path.
Then, is this way better to keep kernel-pick consistent?
1. call reuseport_select_migrated_sock() without sk_hash from any path
2. generate a random number in reuseport_select_migrated_sock()
3. pass it to __reuseport_select_sock() only for select-by-hash
(4. pass 0 as sk_hash to bpf_run_sk_reuseport not to use it)
5. do migration per queue in inet_csk_listen_stop() or per request in
receive path.
I understand it is beautiful to keep consistensy, but also think
the kernel-pick with heuristic performs better than random-pick.
I think discussing the best kernel pick without explicit user input
is going to be a dead end. There is always a case that
makes this heuristic (or guess) fail. e.g. what if multiple
sk(s) being closed are always the last one in the socks[]?
all their child sk(s) will then be piled up at one listen sk
because the last socks[] is always picked?
There can be such a case, but it means the newly listened sockets are
closed earlier than old ones.
quoted
Lets assume the last socks[] is indeed the best for all cases. Then why
the in-progress req don't pick it this way? I feel the implementation
is doing what is convenient at that point. And that is fine, I think
In this patchset, I originally assumed four things:
migration should be done
(i) from old to new
(ii) to redistribute requests evenly as possible
(iii) to keep the order of requests in the queue
(resulting in splicing queues)
(iv) in O(1) for scalability
(resulting in fix-up rsk_listener approach)
I selected the last socket in unhash path to satisfy above four because the
last socket changes at every close() syscall if application closes from
older socket.
But in receiving ACK or retransmitting SYN+ACK, we cannot get the last
'moved' socket. Even if we reserve the last 'moved' socket in the last
index by the idea above, we cannot sure the last socket is changed after
close() for each req->listener. For example, we have listeners A, B, C, and
D, and then call close(A) and close(B), and receive the final ACKs for A
and B, then both of them are assigned to C. In this case, A for D and B for
C is desired. So, selecting the last socket in socks[] for incoming
requests cannnot realize (ii).
This is why I selected the last moved socket in unhash path and a random
listener in receive path.
quoted
for kernel-pick, it should just go for simplicity and stay with
the random(/hash) pick instead of pretending the kernel knows the
application must operate in a certain way. It is fine
that the pick was wrong, the kernel will eventually move the
childs/reqs to the survived listen sk.
Exactly. Also the heuristic way is not fair for every application.
After reading below idea (migrated_sk), I think random-pick is better
at simplicity and passing each sk.
quoted
[ I still think the kernel should not even pick if
there is no bpf prog to instruct how to pick
but I am fine as long as there is a sysctl to
guard this. ]
Unless different applications listen on the same port, random-pick can save
connections which would be aborted. So, I would add a sysctl to do
migration when no eBPF prog is attached.
quoted
I would rather focus on ensuring the bpf prog getting what it
needs to make the migration pick. A few things
I would like to discuss and explore:
quoted
If we splice requests like this, we do not need double lock?
1. lock the accept queue of the old listener
2. unlink all requests and decrement refcount
3. unlock
4. update all requests with new listener
I guess updating rsk_listener can be done without acquiring
the lock in (5) below is because it is done under the
listening_hash's bucket lock (and also the global reuseport_lock) so
that the new listener will stay in TCP_LISTEN state?
If we do migration in inet_unhash(), the lock is held, but it is not held
in inet_csk_listen_stop().
quoted
I am not sure iterating the queue under these
locks is a very good thing to do though. The queue may not be
very long in usual setup but still let see
if that can be avoided.
I agree, lock should not be held long.
quoted
Do you think the iteration can be done without holding
bucket lock and the global reuseport_lock? inet_csk_reqsk_queue_add()
is taking the rskq_lock and then check for TCP_LISTEN. May be
something similar can be done also?
I think either one is necessary at least, so if the sk_state of selected
listener is TCP_CLOSE (this is mostly by random-pick of kernel), then we
have to fall back to call inet_child_forget().
quoted
While doing BPF_SK_REUSEPORT_MIGRATE_REQUEST,
the bpf prog can pick per req and have the sk_hash.
However, while doing BPF_SK_REUSEPORT_MIGRATE_QUEUE,
the bpf prog currently does not have a chance to
pick individually for each req/child on the queue.
Since it is iterating the queue anyway, does it make
sense to also call the bpf to pick for each req/child
in the queue? It then can pass sk_hash (from child->sk_hash?)
to the bpf prog also instead of current 0. The cost of calling
bpf prog is not really that much / signficant at the
migration code path. If the queue is somehow
unusally long, there is already an existing
cond_resched() in inet_csk_listen_stop().
Then, instead of adding sk_reuseport_md->migration,
it can then add sk_reuseport_md->migrate_sk.
"migrate_sk = req" for in-progress req and "migrate_sk = child"
for iterating acceptq. The bpf_prog can then tell what sk (req or child)
it is migrating by reading migrate_sk->state. It can then also
learn the 4 tuples src/dst ip/port while skb is missing.
The sk_reuseport_md->sk can still point to the closed sk
such that the bpf prog can learn the cookie.
I suspect a few things between BPF_SK_REUSEPORT_MIGRATE_REQUEST
and BPF_SK_REUSEPORT_MIGRATE_QUEUE can be folded together
by doing the above. It also gives a more consistent
interface for the bpf prog, no more MIGRATE_QUEUE vs MIGRATE_REQUEST.
I think this is really nice idea. Also, I tried to implement random-pick
one by one in inet_csk_listen_stop() yesterday, I found a concern about how
to handle requests in TFO queue.
The request can be already accepted, so passing it to eBPF prog is
confusing? But, redistributing randomly can affect all listeners
unnecessary. How should we handle such requests?
I've implemented one-by-one migration only for the accept queue for now.
In addition to the concern about TFO queue,
You meant this queue: queue->fastopenq.rskq_rst_head?
Yes.
Can "req" be passed?
I did not look up the lock/race in details for that though.
I think if we rewrite freeing TFO requests part like one of accept queue
using reqsk_queue_remove(), we can also migrate them.
In this patchset, selecting a listener for accept queue, the TFO queue of
the same listener is also migrated to another listener in order to prevent
TFO spoofing attack.
If the request in the accept queue is migrated one by one, I am wondering
which should the request in TFO queue be migrated to prevent attack or
freed.
I think user need not know about keeping such requests in kernel to prevent
attacks, so passing them to eBPF prog is confusing. But, redistributing
them randomly without user's intention can make some irrelevant listeners
unnecessarily drop new TFO requests, so this is also bad. Moreover, freeing
such requests seems not so good in the point of security.
quoted
I want to discuss which should
we pass NULL or request_sock to eBPF program as migrate_sk when selecting a
listener for SYN ?
hmmm... not sure I understand your question.
You meant the existing lookup listener case from inet_lhash2_lookup()?
Yes.
There is nothing to migrate at that point, so NULL makes sense to me.
migrate_sk's type should be PTR_TO_SOCK_COMMON_OR_NULL.
Thank you, I will set PTR_TO_SOCK_COMMON_OR_NULL and pass NULL in
inet_lhash2_lookup().
need to first resolve the question raised in patch 5 regarding
to the update on req->rsk_listener though.
In the unhash path, it is also safe to call sock_put() for the old listner.
In inet_csk_listen_stop(), the sk_refcnt of the listener >= 1. If the
listener does not have immature requests, sk_refcnt is 1 and freed in
__tcp_close().
sock_hold(sk) in __tcp_close()
sock_put(sk) in inet_csk_destroy_sock()
sock_put(sk) in __tcp_clsoe()
@@ -1023,9 +1046,11 @@ EXPORT_SYMBOL(inet_csk_complete_hashdance); */ void inet_csk_listen_stop(struct sock *sk) {+ struct sock_reuseport *reuseport_cb = rcu_access_pointer(sk->sk_reuseport_cb); struct inet_connection_sock *icsk = inet_csk(sk); struct request_sock_queue *queue = &icsk->icsk_accept_queue; struct request_sock *next, *req;+ struct sock *nsk; /* Following specs, it would be better either to send FIN * (and enter FIN-WAIT-1, it is normal close)
5. lock the accept queue of the new listener
6. splice requests and increment refcount
7. unlock
Also, I think splicing is better to keep the order of requests. Adding one
by one reverses it.
It can keep the order but I think it is orthogonal here.
From: Martin KaFai Lau <hidden> Date: 2020-12-10 18:52:03
On Thu, Dec 10, 2020 at 02:15:38PM +0900, Kuniyuki Iwashima wrote:
From: Martin KaFai Lau <redacted>
Date: Wed, 9 Dec 2020 16:07:07 -0800
quoted
On Tue, Dec 01, 2020 at 11:44:12PM +0900, Kuniyuki Iwashima wrote:
quoted
This patch renames reuseport_select_sock() to __reuseport_select_sock() and
adds two wrapper function of it to pass the migration type defined in the
previous commit.
reuseport_select_sock : BPF_SK_REUSEPORT_MIGRATE_NO
reuseport_select_migrated_sock : BPF_SK_REUSEPORT_MIGRATE_REQUEST
As mentioned before, we have to select a new listener for TCP_NEW_SYN_RECV
requests at receiving the final ACK or sending a SYN+ACK. Therefore, this
patch also changes the code to call reuseport_select_migrated_sock() even
if the listening socket is TCP_CLOSE. If we can pick out a listening socket
from the reuseport group, we rewrite request_sock.rsk_listener and resume
processing the request.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 12 +++++++++++
include/net/request_sock.h | 13 ++++++++++++
include/net/sock_reuseport.h | 8 +++----
net/core/sock_reuseport.c | 34 ++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 13 ++++++++++--
net/ipv4/tcp_ipv4.c | 9 ++++++--
net/ipv6/tcp_ipv6.c | 9 ++++++--
7 files changed, 81 insertions(+), 17 deletions(-)
not sure if it is safe to do here.
IIUC, when the req->rsk_refcnt is held, it also holds a refcnt
to req->rsk_listener such that sock_hold(req->rsk_listener) is
safe because its sk_refcnt is not zero.
I think it is safe to call sock_put() for the old listener here.
Without this patchset, at receiving the final ACK or retransmitting
SYN+ACK, if sk_state == TCP_CLOSE, sock_put(req->rsk_listener) is done
by calling reqsk_put() twice in inet_csk_reqsk_queue_drop_and_put().
Note that in your example (final ACK), sock_put(req->rsk_listener) is
_only_ called when reqsk_put() can get refcount_dec_and_test(&req->rsk_refcnt)
to reach zero.
Here in this patch, it sock_put(req->rsk_listener) without req->rsk_refcnt
reaching zero.
Let says there are two cores holding two refcnt to req (one cnt for each core)
by looking up the req from ehash. One of the core do this migrate and
sock_put(req->rsk_listener). Another core does sock_hold(req->rsk_listener).
Core1 Core2
sock_put(req->rsk_listener)
sock_hold(req->rsk_listener)
And then, we do `goto lookup;` and overwrite the sk.
In the v2 patchset, refcount_inc_not_zero() is done for the new listener in
reuseport_select_migrated_sock(), so we have to call sock_put() for the old
listener instead to free it properly.
---8<---
+struct sock *reuseport_select_migrated_sock(struct sock *sk, u32 hash,
+ struct sk_buff *skb)
+{
+ struct sock *nsk;
+
+ nsk = __reuseport_select_sock(sk, hash, skb, 0, BPF_SK_REUSEPORT_MIGRATE_REQUEST);
+ if (nsk && likely(refcount_inc_not_zero(&nsk->sk_refcnt)))
There is another potential issue here. The TCP_LISTEN nsk is protected
by rcu. refcount_inc_not_zero(&nsk->sk_refcnt) cannot be done if it
is not under rcu_read_lock().
The receive path may be ok as it is in rcu. You may need to check for
others.
From: Martin KaFai Lau <hidden> Date: 2020-12-10 19:35:14
On Thu, Dec 10, 2020 at 02:58:10PM +0900, Kuniyuki Iwashima wrote:
[ ... ]
quoted
quoted
I've implemented one-by-one migration only for the accept queue for now.
In addition to the concern about TFO queue,
You meant this queue: queue->fastopenq.rskq_rst_head?
Yes.
quoted
Can "req" be passed?
I did not look up the lock/race in details for that though.
I think if we rewrite freeing TFO requests part like one of accept queue
using reqsk_queue_remove(), we can also migrate them.
In this patchset, selecting a listener for accept queue, the TFO queue of
the same listener is also migrated to another listener in order to prevent
TFO spoofing attack.
If the request in the accept queue is migrated one by one, I am wondering
which should the request in TFO queue be migrated to prevent attack or
freed.
I think user need not know about keeping such requests in kernel to prevent
attacks, so passing them to eBPF prog is confusing. But, redistributing
them randomly without user's intention can make some irrelevant listeners
unnecessarily drop new TFO requests, so this is also bad. Moreover, freeing
such requests seems not so good in the point of security.
The current behavior (during process restart) is also not carrying this
security queue. Not carrying them in this patch will make it
less secure than the current behavior during process restart?
Do you need it now or it is something that can be considered for later
without changing uapi bpf.h?
need to first resolve the question raised in patch 5 regarding
to the update on req->rsk_listener though.
In the unhash path, it is also safe to call sock_put() for the old listner.
In inet_csk_listen_stop(), the sk_refcnt of the listener >= 1. If the
listener does not have immature requests, sk_refcnt is 1 and freed in
__tcp_close().
sock_hold(sk) in __tcp_close()
sock_put(sk) in inet_csk_destroy_sock()
sock_put(sk) in __tcp_clsoe()
I don't see how it is different here than in patch 5.
I could be missing something.
Lets contd the discussion on the other thread (patch 5) first.
@@ -1023,9 +1046,11 @@ EXPORT_SYMBOL(inet_csk_complete_hashdance); */ void inet_csk_listen_stop(struct sock *sk) {+ struct sock_reuseport *reuseport_cb = rcu_access_pointer(sk->sk_reuseport_cb); struct inet_connection_sock *icsk = inet_csk(sk); struct request_sock_queue *queue = &icsk->icsk_accept_queue; struct request_sock *next, *req;+ struct sock *nsk; /* Following specs, it would be better either to send FIN * (and enter FIN-WAIT-1, it is normal close)
5. lock the accept queue of the new listener
6. splice requests and increment refcount
7. unlock
Also, I think splicing is better to keep the order of requests. Adding one
by one reverses it.
It can keep the order but I think it is orthogonal here.
From: Martin KaFai Lau <redacted>
Date: Thu, 10 Dec 2020 10:49:15 -0800
On Thu, Dec 10, 2020 at 02:15:38PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Wed, 9 Dec 2020 16:07:07 -0800
quoted
On Tue, Dec 01, 2020 at 11:44:12PM +0900, Kuniyuki Iwashima wrote:
quoted
This patch renames reuseport_select_sock() to __reuseport_select_sock() and
adds two wrapper function of it to pass the migration type defined in the
previous commit.
reuseport_select_sock : BPF_SK_REUSEPORT_MIGRATE_NO
reuseport_select_migrated_sock : BPF_SK_REUSEPORT_MIGRATE_REQUEST
As mentioned before, we have to select a new listener for TCP_NEW_SYN_RECV
requests at receiving the final ACK or sending a SYN+ACK. Therefore, this
patch also changes the code to call reuseport_select_migrated_sock() even
if the listening socket is TCP_CLOSE. If we can pick out a listening socket
from the reuseport group, we rewrite request_sock.rsk_listener and resume
processing the request.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 12 +++++++++++
include/net/request_sock.h | 13 ++++++++++++
include/net/sock_reuseport.h | 8 +++----
net/core/sock_reuseport.c | 34 ++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 13 ++++++++++--
net/ipv4/tcp_ipv4.c | 9 ++++++--
net/ipv6/tcp_ipv6.c | 9 ++++++--
7 files changed, 81 insertions(+), 17 deletions(-)
not sure if it is safe to do here.
IIUC, when the req->rsk_refcnt is held, it also holds a refcnt
to req->rsk_listener such that sock_hold(req->rsk_listener) is
safe because its sk_refcnt is not zero.
I think it is safe to call sock_put() for the old listener here.
Without this patchset, at receiving the final ACK or retransmitting
SYN+ACK, if sk_state == TCP_CLOSE, sock_put(req->rsk_listener) is done
by calling reqsk_put() twice in inet_csk_reqsk_queue_drop_and_put().
Note that in your example (final ACK), sock_put(req->rsk_listener) is
_only_ called when reqsk_put() can get refcount_dec_and_test(&req->rsk_refcnt)
to reach zero.
Here in this patch, it sock_put(req->rsk_listener) without req->rsk_refcnt
reaching zero.
Let says there are two cores holding two refcnt to req (one cnt for each core)
by looking up the req from ehash. One of the core do this migrate and
sock_put(req->rsk_listener). Another core does sock_hold(req->rsk_listener).
Core1 Core2
sock_put(req->rsk_listener)
sock_hold(req->rsk_listener)
I'm sorry for the late reply.
I missed this situation that different Cores get into NEW_SYN_RECV path,
but this does exist.
https://lore.kernel.org/netdev/1517977874.3715.153.camel@gmail.com/#thttps://lore.kernel.org/netdev/1518531252.3715.178.camel@gmail.com/
If close() is called for the listener and the request has the last refcount
for it, sock_put() by Core2 frees it, so Core1 cannot proceed with freed
listener. So, it is good to call refcount_inc_not_zero() instead of
sock_hold(). If refcount_inc_not_zero() fails, it means that the listener
is closed and the req->rsk_listener is changed in another place. Then, we
can continue processing the request by rewriting sk with rsk_listener and
calling sock_hold() for it.
Also, the migration by Core2 can be done after sock_hold() by Core1. Then
if Core1 win the race by removing the request from ehash,
in inet_csk_reqsk_queue_add(), instead of sk, req->rsk_listener should be
used as the proper listener to add the req into its queue. But if the
rsk_listener is also TCP_CLOSE, we have to call inet_child_forget().
Moreover, we have to check the listener is freed in the beginning of
reqsk_timer_handler() by refcount_inc_not_zero().
quoted
And then, we do `goto lookup;` and overwrite the sk.
In the v2 patchset, refcount_inc_not_zero() is done for the new listener in
reuseport_select_migrated_sock(), so we have to call sock_put() for the old
listener instead to free it properly.
---8<---
+struct sock *reuseport_select_migrated_sock(struct sock *sk, u32 hash,
+ struct sk_buff *skb)
+{
+ struct sock *nsk;
+
+ nsk = __reuseport_select_sock(sk, hash, skb, 0, BPF_SK_REUSEPORT_MIGRATE_REQUEST);
+ if (nsk && likely(refcount_inc_not_zero(&nsk->sk_refcnt)))
There is another potential issue here. The TCP_LISTEN nsk is protected
by rcu. refcount_inc_not_zero(&nsk->sk_refcnt) cannot be done if it
is not under rcu_read_lock().
The receive path may be ok as it is in rcu. You may need to check for
others.
IIUC, is this mean nsk can be NULL after grace period of RCU? If so, I will
move rcu_read_lock/unlock() from __reuseport_select_sock() to
reuseport_select_sock() and reuseport_select_migrated_sock().
It looks like there is another race here. What
if multiple cores try to update req->rsk_listener?
I think we have to add a lock in struct request_sock, acquire it, check
if the rsk_listener is changed or not, and then do migration. Also, if the
listener has been changed, we have to tell the caller to use it as the new
listener.
---8<---
spin_lock(&lock)
if (sk != req->rsk_listener) {
nsk = req->rsk_listener;
goto out;
}
// do migration
out:
spin_unlock(&lock)
return nsk;
---8<---
From: Martin KaFai Lau <redacted>
Date: Thu, 10 Dec 2020 11:33:40 -0800
On Thu, Dec 10, 2020 at 02:58:10PM +0900, Kuniyuki Iwashima wrote:
[ ... ]
quoted
quoted
quoted
I've implemented one-by-one migration only for the accept queue for now.
In addition to the concern about TFO queue,
You meant this queue: queue->fastopenq.rskq_rst_head?
Yes.
quoted
Can "req" be passed?
I did not look up the lock/race in details for that though.
I think if we rewrite freeing TFO requests part like one of accept queue
using reqsk_queue_remove(), we can also migrate them.
In this patchset, selecting a listener for accept queue, the TFO queue of
the same listener is also migrated to another listener in order to prevent
TFO spoofing attack.
If the request in the accept queue is migrated one by one, I am wondering
which should the request in TFO queue be migrated to prevent attack or
freed.
I think user need not know about keeping such requests in kernel to prevent
attacks, so passing them to eBPF prog is confusing. But, redistributing
them randomly without user's intention can make some irrelevant listeners
unnecessarily drop new TFO requests, so this is also bad. Moreover, freeing
such requests seems not so good in the point of security.
The current behavior (during process restart) is also not carrying this
security queue. Not carrying them in this patch will make it
less secure than the current behavior during process restart?
No, I thought I could make it more secure.
Do you need it now or it is something that can be considered for later
without changing uapi bpf.h?
No, I do not need it for any other reason, so I will simply free the
requests in TFO queue.
Thank you.
need to first resolve the question raised in patch 5 regarding
to the update on req->rsk_listener though.
In the unhash path, it is also safe to call sock_put() for the old listner.
In inet_csk_listen_stop(), the sk_refcnt of the listener >= 1. If the
listener does not have immature requests, sk_refcnt is 1 and freed in
__tcp_close().
sock_hold(sk) in __tcp_close()
sock_put(sk) in inet_csk_destroy_sock()
sock_put(sk) in __tcp_clsoe()
I don't see how it is different here than in patch 5.
I could be missing something.
Lets contd the discussion on the other thread (patch 5) first.
The listening socket has two kinds of refcounts for itself(1) and
requests(n). I think the listener has its own refcount at least in
inet_csk_listen_stop(), so sock_put() here never free the listener.
From: Martin KaFai Lau <hidden> Date: 2020-12-15 03:00:25
On Tue, Dec 15, 2020 at 02:03:13AM +0900, Kuniyuki Iwashima wrote:
From: Martin KaFai Lau <redacted>
Date: Thu, 10 Dec 2020 10:49:15 -0800
quoted
On Thu, Dec 10, 2020 at 02:15:38PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Wed, 9 Dec 2020 16:07:07 -0800
quoted
On Tue, Dec 01, 2020 at 11:44:12PM +0900, Kuniyuki Iwashima wrote:
quoted
This patch renames reuseport_select_sock() to __reuseport_select_sock() and
adds two wrapper function of it to pass the migration type defined in the
previous commit.
reuseport_select_sock : BPF_SK_REUSEPORT_MIGRATE_NO
reuseport_select_migrated_sock : BPF_SK_REUSEPORT_MIGRATE_REQUEST
As mentioned before, we have to select a new listener for TCP_NEW_SYN_RECV
requests at receiving the final ACK or sending a SYN+ACK. Therefore, this
patch also changes the code to call reuseport_select_migrated_sock() even
if the listening socket is TCP_CLOSE. If we can pick out a listening socket
from the reuseport group, we rewrite request_sock.rsk_listener and resume
processing the request.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 12 +++++++++++
include/net/request_sock.h | 13 ++++++++++++
include/net/sock_reuseport.h | 8 +++----
net/core/sock_reuseport.c | 34 ++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 13 ++++++++++--
net/ipv4/tcp_ipv4.c | 9 ++++++--
net/ipv6/tcp_ipv6.c | 9 ++++++--
7 files changed, 81 insertions(+), 17 deletions(-)
not sure if it is safe to do here.
IIUC, when the req->rsk_refcnt is held, it also holds a refcnt
to req->rsk_listener such that sock_hold(req->rsk_listener) is
safe because its sk_refcnt is not zero.
I think it is safe to call sock_put() for the old listener here.
Without this patchset, at receiving the final ACK or retransmitting
SYN+ACK, if sk_state == TCP_CLOSE, sock_put(req->rsk_listener) is done
by calling reqsk_put() twice in inet_csk_reqsk_queue_drop_and_put().
Note that in your example (final ACK), sock_put(req->rsk_listener) is
_only_ called when reqsk_put() can get refcount_dec_and_test(&req->rsk_refcnt)
to reach zero.
Here in this patch, it sock_put(req->rsk_listener) without req->rsk_refcnt
reaching zero.
Let says there are two cores holding two refcnt to req (one cnt for each core)
by looking up the req from ehash. One of the core do this migrate and
sock_put(req->rsk_listener). Another core does sock_hold(req->rsk_listener).
Core1 Core2
sock_put(req->rsk_listener)
sock_hold(req->rsk_listener)
I'm sorry for the late reply.
I missed this situation that different Cores get into NEW_SYN_RECV path,
but this does exist.
https://lore.kernel.org/netdev/1517977874.3715.153.camel@gmail.com/#thttps://lore.kernel.org/netdev/1518531252.3715.178.camel@gmail.com/
If close() is called for the listener and the request has the last refcount
for it, sock_put() by Core2 frees it, so Core1 cannot proceed with freed
listener. So, it is good to call refcount_inc_not_zero() instead of
sock_hold(). If refcount_inc_not_zero() fails, it means that the listener
_inc_not_zero() usually means it requires rcu_read_lock().
That may have rippling effect on other req->rsk_listener readers.
There may also be places assuming that the req->rsk_listener will never
change once it is assigned. not sure. have not looked closely yet.
It probably needs some more thoughts here to get a simpler solution.
is closed and the req->rsk_listener is changed in another place. Then, we
can continue processing the request by rewriting sk with rsk_listener and
calling sock_hold() for it.
Also, the migration by Core2 can be done after sock_hold() by Core1. Then
if Core1 win the race by removing the request from ehash,
in inet_csk_reqsk_queue_add(), instead of sk, req->rsk_listener should be
used as the proper listener to add the req into its queue. But if the
rsk_listener is also TCP_CLOSE, we have to call inet_child_forget().
Moreover, we have to check the listener is freed in the beginning of
reqsk_timer_handler() by refcount_inc_not_zero().
quoted
quoted
And then, we do `goto lookup;` and overwrite the sk.
In the v2 patchset, refcount_inc_not_zero() is done for the new listener in
reuseport_select_migrated_sock(), so we have to call sock_put() for the old
listener instead to free it properly.
---8<---
+struct sock *reuseport_select_migrated_sock(struct sock *sk, u32 hash,
+ struct sk_buff *skb)
+{
+ struct sock *nsk;
+
+ nsk = __reuseport_select_sock(sk, hash, skb, 0, BPF_SK_REUSEPORT_MIGRATE_REQUEST);
+ if (nsk && likely(refcount_inc_not_zero(&nsk->sk_refcnt)))
There is another potential issue here. The TCP_LISTEN nsk is protected
by rcu. refcount_inc_not_zero(&nsk->sk_refcnt) cannot be done if it
is not under rcu_read_lock().
The receive path may be ok as it is in rcu. You may need to check for
others.
IIUC, is this mean nsk can be NULL after grace period of RCU? If so, I will
worse than NULL. an invalid pointer.
move rcu_read_lock/unlock() from __reuseport_select_sock() to
reuseport_select_sock() and reuseport_select_migrated_sock().
It looks like there is another race here. What
if multiple cores try to update req->rsk_listener?
I think we have to add a lock in struct request_sock, acquire it, check
if the rsk_listener is changed or not, and then do migration. Also, if the
listener has been changed, we have to tell the caller to use it as the new
listener.
---8<---
spin_lock(&lock)
if (sk != req->rsk_listener) {
nsk = req->rsk_listener;
goto out;
}
// do migration
out:
spin_unlock(&lock)
return nsk;
---8<---
From: Martin KaFai Lau <redacted>
Date: Mon, 14 Dec 2020 18:58:37 -0800
On Tue, Dec 15, 2020 at 02:03:13AM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Thu, 10 Dec 2020 10:49:15 -0800
quoted
On Thu, Dec 10, 2020 at 02:15:38PM +0900, Kuniyuki Iwashima wrote:
quoted
From: Martin KaFai Lau <redacted>
Date: Wed, 9 Dec 2020 16:07:07 -0800
quoted
On Tue, Dec 01, 2020 at 11:44:12PM +0900, Kuniyuki Iwashima wrote:
quoted
This patch renames reuseport_select_sock() to __reuseport_select_sock() and
adds two wrapper function of it to pass the migration type defined in the
previous commit.
reuseport_select_sock : BPF_SK_REUSEPORT_MIGRATE_NO
reuseport_select_migrated_sock : BPF_SK_REUSEPORT_MIGRATE_REQUEST
As mentioned before, we have to select a new listener for TCP_NEW_SYN_RECV
requests at receiving the final ACK or sending a SYN+ACK. Therefore, this
patch also changes the code to call reuseport_select_migrated_sock() even
if the listening socket is TCP_CLOSE. If we can pick out a listening socket
from the reuseport group, we rewrite request_sock.rsk_listener and resume
processing the request.
Reviewed-by: Benjamin Herrenschmidt <redacted>
Signed-off-by: Kuniyuki Iwashima <redacted>
---
include/net/inet_connection_sock.h | 12 +++++++++++
include/net/request_sock.h | 13 ++++++++++++
include/net/sock_reuseport.h | 8 +++----
net/core/sock_reuseport.c | 34 ++++++++++++++++++++++++------
net/ipv4/inet_connection_sock.c | 13 ++++++++++--
net/ipv4/tcp_ipv4.c | 9 ++++++--
net/ipv6/tcp_ipv6.c | 9 ++++++--
7 files changed, 81 insertions(+), 17 deletions(-)
not sure if it is safe to do here.
IIUC, when the req->rsk_refcnt is held, it also holds a refcnt
to req->rsk_listener such that sock_hold(req->rsk_listener) is
safe because its sk_refcnt is not zero.
I think it is safe to call sock_put() for the old listener here.
Without this patchset, at receiving the final ACK or retransmitting
SYN+ACK, if sk_state == TCP_CLOSE, sock_put(req->rsk_listener) is done
by calling reqsk_put() twice in inet_csk_reqsk_queue_drop_and_put().
Note that in your example (final ACK), sock_put(req->rsk_listener) is
_only_ called when reqsk_put() can get refcount_dec_and_test(&req->rsk_refcnt)
to reach zero.
Here in this patch, it sock_put(req->rsk_listener) without req->rsk_refcnt
reaching zero.
Let says there are two cores holding two refcnt to req (one cnt for each core)
by looking up the req from ehash. One of the core do this migrate and
sock_put(req->rsk_listener). Another core does sock_hold(req->rsk_listener).
Core1 Core2
sock_put(req->rsk_listener)
sock_hold(req->rsk_listener)
I'm sorry for the late reply.
I missed this situation that different Cores get into NEW_SYN_RECV path,
but this does exist.
https://lore.kernel.org/netdev/1517977874.3715.153.camel@gmail.com/#thttps://lore.kernel.org/netdev/1518531252.3715.178.camel@gmail.com/
If close() is called for the listener and the request has the last refcount
for it, sock_put() by Core2 frees it, so Core1 cannot proceed with freed
listener. So, it is good to call refcount_inc_not_zero() instead of
sock_hold(). If refcount_inc_not_zero() fails, it means that the listener
_inc_not_zero() usually means it requires rcu_read_lock().
That may have rippling effect on other req->rsk_listener readers.
There may also be places assuming that the req->rsk_listener will never
change once it is assigned. not sure. have not looked closely yet.
I have checked this again. There are no functions that expect explicitly
req->rsk_listener never change except for BUG_ON in inet_child_forget().
No BUG_ON/WARN_ON does not mean they does not assume listener never
change, but such functions still work properly if rsk_listener is changed.
It probably needs some more thoughts here to get a simpler solution.
Is it fine to move sock_hold() before assigning rsk_listener and defer
sock_put() to the end of tcp_v[46]_rcv() ?
Also, we have to rewrite rsk_listener first and then call sock_put() in
reqsk_timer_handler() so that rsk_listener always has refcount more than 1.
---8<---
struct sock *nsk, *osk;
bool migrated = false;
...
sock_hold(req->rsk_listener); // (i)
sk = req->rsk_listener;
...
if (sk->sk_state == TCP_CLOSE) {
osk = sk;
// do migration without sock_put()
sock_hold(nsk); // (ii) (as with (i))
sk = nsk;
migrated = true;
}
...
if (migrated) {
sock_put(sk); // pair with (ii)
sock_put(osk); // decrement old listener's refcount
sk = osk;
}
sock_put(sk); // pair with (i)
---8<---
quoted
is closed and the req->rsk_listener is changed in another place. Then, we
can continue processing the request by rewriting sk with rsk_listener and
calling sock_hold() for it.
Also, the migration by Core2 can be done after sock_hold() by Core1. Then
if Core1 win the race by removing the request from ehash,
in inet_csk_reqsk_queue_add(), instead of sk, req->rsk_listener should be
used as the proper listener to add the req into its queue. But if the
rsk_listener is also TCP_CLOSE, we have to call inet_child_forget().
Moreover, we have to check the listener is freed in the beginning of
reqsk_timer_handler() by refcount_inc_not_zero().
quoted
quoted
And then, we do `goto lookup;` and overwrite the sk.
In the v2 patchset, refcount_inc_not_zero() is done for the new listener in
reuseport_select_migrated_sock(), so we have to call sock_put() for the old
listener instead to free it properly.
---8<---
+struct sock *reuseport_select_migrated_sock(struct sock *sk, u32 hash,
+ struct sk_buff *skb)
+{
+ struct sock *nsk;
+
+ nsk = __reuseport_select_sock(sk, hash, skb, 0, BPF_SK_REUSEPORT_MIGRATE_REQUEST);
+ if (nsk && likely(refcount_inc_not_zero(&nsk->sk_refcnt)))
There is another potential issue here. The TCP_LISTEN nsk is protected
by rcu. refcount_inc_not_zero(&nsk->sk_refcnt) cannot be done if it
is not under rcu_read_lock().
The receive path may be ok as it is in rcu. You may need to check for
others.
IIUC, is this mean nsk can be NULL after grace period of RCU? If so, I will
worse than NULL. an invalid pointer.
quoted
move rcu_read_lock/unlock() from __reuseport_select_sock() to
reuseport_select_sock() and reuseport_select_migrated_sock().
It looks like there is another race here. What
if multiple cores try to update req->rsk_listener?
I think we have to add a lock in struct request_sock, acquire it, check
if the rsk_listener is changed or not, and then do migration. Also, if the
listener has been changed, we have to tell the caller to use it as the new
listener.
---8<---
spin_lock(&lock)
if (sk != req->rsk_listener) {
nsk = req->rsk_listener;
goto out;
}
// do migration
out:
spin_unlock(&lock)
return nsk;
---8<---
cmpxchg may help here.
Thank you, I will use cmpxchg() to rewrite rsk_listener atomically and
check if req->rsk_listener is updated.
From: Martin KaFai Lau <hidden> Date: 2020-12-16 22:25:48
On Thu, Dec 17, 2020 at 01:41:58AM +0900, Kuniyuki Iwashima wrote:
[ ... ]
quoted
There may also be places assuming that the req->rsk_listener will never
change once it is assigned. not sure. have not looked closely yet.
I have checked this again. There are no functions that expect explicitly
req->rsk_listener never change except for BUG_ON in inet_child_forget().
No BUG_ON/WARN_ON does not mean they does not assume listener never
change, but such functions still work properly if rsk_listener is changed.
The migration not only changes the ptr value of req->rsk_listener, it also
means req is moved to another listener. (e.g. by updating the qlen of
the old sk and new sk)
Lets reuse the example about two cores at the TCP_NEW_SYN_RECV path
racing to finish up the 3WHS.
One core is already at inet_csk_complete_hashdance() doing
"reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req))".
What happen if another core migrates the req to another listener?
Would the "reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req))"
doing thing on the accept_queue that this req no longer belongs to?
Also, from a quick look at reqsk_timer_handler() on how
queue->young and req->num_timeout are updated, I am not sure
the reqsk_queue_migrated() will work also:
+static inline void reqsk_queue_migrated(struct request_sock_queue *old_accept_queue,
+ struct request_sock_queue *new_accept_queue,
+ const struct request_sock *req)
+{
+ atomic_dec(&old_accept_queue->qlen);
+ atomic_inc(&new_accept_queue->qlen);
+
+ if (req->num_timeout == 0) {
What if reqsk_timer_handler() is running in parallel
and updating req->num_timeout?
+ atomic_dec(&old_accept_queue->young);
+ atomic_inc(&new_accept_queue->young);
+ }
+}
It feels like some of the "own_req" related logic may be useful here.
not sure. could be something worth to think about.
quoted
It probably needs some more thoughts here to get a simpler solution.
Is it fine to move sock_hold() before assigning rsk_listener and defer
sock_put() to the end of tcp_v[46]_rcv() ?
I don't see how this ordering helps, considering the migration can happen
any time at another core.
Also, we have to rewrite rsk_listener first and then call sock_put() in
reqsk_timer_handler() so that rsk_listener always has refcount more than 1.
---8<---
struct sock *nsk, *osk;
bool migrated = false;
...
sock_hold(req->rsk_listener); // (i)
sk = req->rsk_listener;
...
if (sk->sk_state == TCP_CLOSE) {
osk = sk;
// do migration without sock_put()
sock_hold(nsk); // (ii) (as with (i))
sk = nsk;
migrated = true;
}
...
if (migrated) {
sock_put(sk); // pair with (ii)
sock_put(osk); // decrement old listener's refcount
sk = osk;
}
sock_put(sk); // pair with (i)
---8<---