Extend SOCKMAP to store listening sockets
Subsystems (11)
Jakub Sitnicki
maintainercover Extend SOCKMAP to store listening sockets
This patch set makes SOCKMAP more flexible by allowing it to hold TCP sockets that are either in established or listening state. With it SOCKMAP can act as a drop-in replacement for REUSEPORT_SOCKARRAY which reuseport BPF programs use. Granted, it is limited to only TCP sockets.
The idea started out at LPC '19 as feedback from John Fastabend to our troubles with repurposing REUSEPORT_SOCKARRAY as a collection of listening sockets accessed by a BPF program ran on socket lookup [1]. Without going into details, REUSEPORT_SOCKARRAY proved to be tightly coupled with reuseport logic. Talk from LPC (see slides [2] or video [3]) highlights what problems we ran into when trying to make REUSEPORT_SOCKARRAY work for our use-case.
Patches have evolved quite a bit since the RFC series from a month ago [4]. To recap the RFC feedback, John pointed out that BPF redirect helpers for SOCKMAP need sane semantics when used with listening sockets [5], and that SOCKMAP lookup from BPF would be useful [6]. While Martin asked for UDP support [7].
As it happens, patches needed more work to get SOCKMAP to actually behave correctly with listening sockets. It turns out flexibility has its price. Change log below outlines them all.
With more than I would like patches in the set, I left the new features, lookup from BPF as well as UDP support, for another series. I'm quite happy with how the changes turned out and the test coverage so I'm boldly proposing it as v1 :-)
Curious to see what you think.
RFC -> v1:
- Switch from overriding proto->accept to af_ops->syn_recv_sock, which happens earlier. Clearing the psock state after accept() does not work for child sockets that become orphaned (never got accepted). v4-mapped sockets need special care.
- Return the socket cookie on SOCKMAP lookup from syscall to be on par with REUSEPORT_SOCKARRAY. Requires SOCKMAP to take u64 on lookup/update from syscall.
- Make bpf_sk_redirect_map (ingress) and bpf_msg_redirect_map (egress) SOCKMAP helpers fail when target socket is a listening one.
- Make bpf_sk_select_reuseport helper fail when target is a TCP established socket.
- Teach libbpf to recognize SK_REUSEPORT program type from section name.
- Add a dedicated set of tests for SOCKMAP holding listening sockets, covering map operations, overridden socket callbacks, and BPF helpers.
Thanks,
Jakub
[1] https://lore.kernel.org/bpf/[email protected]/
[2] https://linuxplumbersconf.org/event/4/contributions/487/
[3] https://www.youtube.com/watch?v=qRDoUpqvYjY
[4] https://lore.kernel.org/bpf/[email protected]/
[5] https://lore.kernel.org/bpf/[email protected]/
[6] https://lore.kernel.org/bpf/[email protected]/
[7] https://lore.kernel.org/bpf/20191028213804.yv3xfjjlayfghkcr@kafai-mbp/
Jakub Sitnicki (8):
bpf, sockmap: Return socket cookie on lookup from syscall bpf, sockmap: Let all kernel-land lookup values in SOCKMAP bpf, sockmap: Allow inserting listening TCP sockets into SOCKMAP bpf, sockmap: Don't let child socket inherit psock or its ops on copy
bpf: Allow selecting reuseport socket from a SOCKMAP
libbpf: Recognize SK_REUSEPORT programs from section name selftests/bpf: Extend SK_REUSEPORT tests to cover SOCKMAP selftests/bpf: Tests for SOCKMAP holding listening sockets
include/linux/skmsg.h | 17 +- kernel/bpf/verifier.c | 6 +- net/core/filter.c | 2 + net/core/sock_map.c | 68 +- net/ipv4/tcp_bpf.c | 66 +- tools/lib/bpf/libbpf.c | 1 + tools/testing/selftests/bpf/.gitignore | 1 + tools/testing/selftests/bpf/Makefile | 9 +- .../bpf/progs/test_sockmap_listen_kern.c | 75 ++ tools/testing/selftests/bpf/test_maps.c | 6 +- .../selftests/bpf/test_select_reuseport.c | 141 ++- .../selftests/bpf/test_select_reuseport.sh | 14 + .../selftests/bpf/test_sockmap_listen.c | 820 ++++++++++++++++++ 13 files changed, 1170 insertions(+), 56 deletions(-) create mode 100644 tools/testing/selftests/bpf/progs/test_sockmap_listen_kern.c create mode 100755 tools/testing/selftests/bpf/test_select_reuseport.sh create mode 100644 tools/testing/selftests/bpf/test_sockmap_listen.c
Signature · 1 line
2.20.1
Jakub Sitnicki
maintainerPATCH 1/8 bpf, sockmap: Return socket cookie on lookup from syscall
Tooling that populates the SOCKMAP with sockets from user-space needs a way to inspect its contents. Returning the struct sock * that SOCKMAP holds to user-space is neither safe nor useful. An approach established by REUSEPORT_SOCKARRAY is to return a socket cookie (a unique identifier) instead.
Since socket cookies are u64 values SOCKMAP needs to support such a value size for lookup to be possible. This requires special handling on update, though. Attempts to do a lookup on SOCKMAP holding u32 values will be met with ENOSPC error.
--- net/core/sock_map.c | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-)
net/core/sock_map.c +29 -2
@@ -10,6 +10,7 @@#include <linux/skmsg.h> #include <linux/list.h> #include <linux/jhash.h> +#include <linux/sock_diag.h> struct bpf_stab {struct bpf_map map;
@@ -31,7 +32,8 @@ static struct bpf_map *sock_map_alloc(union bpf_attr *attr)return ERR_PTR (-EPERM );if (attr->max_entries ==0 || attr->key_size !=4 || - attr->value_size !=4 || + (attr->value_size !=sizeof (u32) && + attr->value_size !=sizeof (u64)) || attr->map_flags & ~SOCK_CREATE_FLAG_MASK )return ERR_PTR (-EINVAL );
@@ -274,6 +276,23 @@ static void *sock_map_lookup(struct bpf_map *map, void *key)return ERR_PTR (-EOPNOTSUPP ); } +static void *sock_map_lookup_sys (struct bpf_map *map,void *key) +{ +struct sock *sk; + +WARN_ON_ONCE (!rcu_read_lock_held ()); + +if (map->value_size !=sizeof (u64)) +return ERR_PTR (-ENOSPC ); + + sk =__sock_map_lookup_elem (map, *(u32 *)key); +if (!sk) +return ERR_PTR (-ENOENT ); + +sock_gen_cookie (sk); +return &sk->sk_cookie; +} +static int __sock_map_delete (struct bpf_stab *stab,struct sock *sk_test,struct sock **psk) {
@@ -399,12 +418,19 @@ static bool sock_map_sk_is_suitable(const struct sock *sk)static int sock_map_update_elem (struct bpf_map *map,void *key,void *value,u64 flags) { -u32 ufd = *(u32 *)value;u32 idx = *(u32 *)key;struct socket *sock;struct sock *sk; +u64 ufd;int ret; +if (map->value_size ==sizeof (u64)) + ufd = *(u64 *)value; +else + ufd = *(u32 *)value; +if (ufd >S32_MAX ) +return -EINVAL ; + sock =sockfd_lookup (ufd, &ret);if (!sock)return ret;
@@ -500,6 +526,7 @@ const struct bpf_map_ops sock_map_ops = { .map_alloc = sock_map_alloc, .map_free = sock_map_free, .map_get_next_key = sock_map_get_next_key, + .map_lookup_elem_sys_only = sock_map_lookup_sys, .map_update_elem = sock_map_update_elem, .map_delete_elem = sock_map_delete_elem, .map_lookup_elem = sock_map_lookup,
Signature · 1 line
2.20.1
RE: [PATCH bpf-next 1/8] bpf, sockmap: Return socket cookie on lookup from syscall
Quoted 6 lines · Jakub Sitnicki
Tooling that populates the SOCKMAP with sockets from user-space needs a way to inspect its contents. Returning the struct sock * that SOCKMAP holds to user-space is neither safe nor useful. An approach established by
REUSEPORT_SOCKARRAYis to return a socket cookie (a unique identifier) instead.
Quoted 7 lines
Since socket cookies are u64 values SOCKMAP needs to support such a value size for lookup to be possible. This requires special handling on update, though. Attempts to do a lookup on SOCKMAP holding u32 values will be met with ENOSPC error.
Signed-off-by Jakub Sitnicki <[email protected]>---
Jakub Sitnicki
maintainerPATCH 2/8 bpf, sockmap: Let all kernel-land lookup values in SOCKMAP
In reply to Jakub SitnickiDon't require the kernel code, like BPF helpers, that needs access to SOCKMAP map contents to live in the sock_map module. Expose the SOCKMAP lookup operation to all kernel-land.
Lookup from BPF context is not whitelisted yet. While syscalls have a dedicated lookup handler.
--- net/core/sock_map.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-)
net/core/sock_map.c +7 -2
@@ -273,7 +273,7 @@ static struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)static void *sock_map_lookup (struct bpf_map *map,void *key) { -return ERR_PTR (-EOPNOTSUPP ); +return __sock_map_lookup_elem (map, *(u32 *)key); }static void *sock_map_lookup_sys (struct bpf_map *map,void *key)
@@ -899,6 +899,11 @@ static void sock_hash_free(struct bpf_map *map)kfree (htab); } +static void *sock_hash_lookup (struct bpf_map *map,void *key) +{ +return ERR_PTR (-EOPNOTSUPP ); +} +static void sock_hash_release_progs (struct bpf_map *map) { psock_progs_drop(&container_of(map, struct bpf_htab, map)->progs);
@@ -978,7 +983,7 @@ const struct bpf_map_ops sock_hash_ops = { .map_get_next_key = sock_hash_get_next_key, .map_update_elem = sock_hash_update_elem, .map_delete_elem = sock_hash_delete_elem, - .map_lookup_elem = sock_map_lookup, + .map_lookup_elem = sock_hash_lookup, .map_release_uref = sock_hash_release_progs, .map_check_btf = map_check_no_btf, };
Signature · 1 line
2.20.1
RE: [PATCH bpf-next 2/8] bpf, sockmap: Let all kernel-land lookup values in SOCKMAP
Quoted 9 lines · Jakub Sitnicki
Don't require the kernel code, like BPF helpers, that needs access to SOCKMAP map contents to live in the
sock_mapmodule. Expose the SOCKMAP lookup operation to all kernel-land.Lookup from BPF context is not whitelisted yet. While syscalls have a dedicated lookup handler.
Signed-off-by Jakub Sitnicki <[email protected]>---
Jakub Sitnicki
maintainerPATCH 3/8 bpf, sockmap: Allow inserting listening TCP sockets into SOCKMAP
In reply to Jakub SitnickiIn order for SOCKMAP type to become a generic collection for storing TCP sockets we need to loosen the checks in update callback.
Currently SOCKMAP requires the TCP socket to be in established state, which prevents us from using it to keep references to listening sockets.
Change the update pre-checks so that it is sufficient for socket to be in a hash table, i.e. have a local address/port assigned, to be inserted. Return -EINVAL if the condition is not met to be consistent with REUSEPORT_SOCKARRY map type.
This creates a possibility of pointing one of the BPF redirect helpers that splice two SOCKMAP sockets on ingress or egress at a listening socket, which doesn't make sense. Introduce appropriate checks in the helpers so that only established TCP sockets can be a target for redirects.
--- net/core/sock_map.c | 28 ++++++++++++++++++------- tools/testing/selftests/bpf/test_maps.c | 6 +----- 2 files changed, 21 insertions(+), 13 deletions(-)
net/core/sock_map.c +20 -8
@@ -439,11 +439,14 @@ static int sock_map_update_elem(struct bpf_map *map, void *key, ret = -EINVAL ; goto out; } -if (!sock_map_sk_is_suitable (sk) || - sk->sk_state !=TCP_ESTABLISHED ) { +if (!sock_map_sk_is_suitable (sk)) { ret = -EOPNOTSUPP ; goto out; } +if (!sk_hashed (sk)) { + ret = -EINVAL ; + goto out; + }sock_map_sk_acquire (sk); ret =sock_map_update_common (map, idx, sk, flags);
@@ -480,13 +483,17 @@ BPF_CALL_4(bpf_sk_redirect_map, struct sk_buff *, skb, struct bpf_map *, map, u32, key, u64, flags) { struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); +struct sock *sk;if (unlikely (flags & ~(BPF_F_INGRESS )))return SK_DROP ; - tcb->bpf.flags = flags; - tcb->bpf.sk_redir =__sock_map_lookup_elem (map, key); -if (!tcb->bpf.sk_redir) + + sk =__sock_map_lookup_elem (map, key); +if (!sk || sk->sk_state !=TCP_ESTABLISHED )return SK_DROP ; + + tcb->bpf.flags = flags; + tcb->bpf.sk_redir = sk;return SK_PASS ; }
@@ -503,12 +510,17 @@ const struct bpf_func_proto bpf_sk_redirect_map_proto = { BPF_CALL_4(bpf_msg_redirect_map, struct sk_msg *, msg, struct bpf_map *, map, u32, key, u64, flags) { +struct sock *sk; +if (unlikely (flags & ~(BPF_F_INGRESS )))return SK_DROP ; - msg->flags = flags; - msg->sk_redir =__sock_map_lookup_elem (map, key); -if (!msg->sk_redir) + + sk =__sock_map_lookup_elem (map, key); +if (!sk || sk->sk_state !=TCP_ESTABLISHED )return SK_DROP ; + + msg->flags = flags; + msg->sk_redir = sk;return SK_PASS ; }
tools/testing/selftests/bpf/test_maps.c +1 -5
@@ -756,11 +756,7 @@ static void test_sockmap(unsigned int tasks, void *data)/* Test update without programs */ for (i =0 ; i <6 ; i++) { err =bpf_map_update_elem (fd, &i, &sfd[i],BPF_ANY ); -if (i <2 && !err) { -printf ("Allowed update sockmap '%i:%i' not in ESTABLISHED\n" , - i, sfd[i]); - goto out_sockmap; - }else if (i >=2 && err) { +if (err) {printf ("Failed noprog update sockmap '%i:%i'\n" , i, sfd[i]); goto out_sockmap;
Signature · 1 line
2.20.1
RE: [PATCH bpf-next 3/8] bpf, sockmap: Allow inserting listening TCP sockets into SOCKMAP
Quoted 11 lines · Jakub Sitnicki
In order for SOCKMAP type to become a generic collection for storing TCP sockets we need to loosen the checks in update callback.
Currently SOCKMAP requires the TCP socket to be in established state, which prevents us from using it to keep references to listening sockets.
Change the update pre-checks so that it is sufficient for socket to be in a hash table, i.e. have a local address/port assigned, to be inserted. Return
-EINVALif the condition is not met to be consistent withREUSEPORT_SOCKARRYmap type.
Quoted 7 lines
This creates a possibility of pointing one of the BPF redirect helpers that splice two SOCKMAP sockets on ingress or egress at a listening socket, which doesn't make sense. Introduce appropriate checks in the helpers so that only established TCP sockets can be a target for redirects.
Signed-off-by Jakub Sitnicki <[email protected]>---
Jakub Sitnicki
maintainerPATCH 4/8 bpf, sockmap: Don't let child socket inherit psock or its ops on copy
In reply to Jakub SitnickiSockets cloned from the listening sockets that belongs to a SOCKMAP must not inherit the psock state. Otherwise child sockets unintentionally share the SOCKMAP entry with the listening socket, which would lead to use-after-free bugs.
Restore the child socket psock state and its callbacks at the earliest possible moment, that is right after the child socket gets created. This ensures that neither children that get accept()'ed, nor those that are left in accept queue and will get orphaned, don't inadvertently inherit parent's psock.
--- include/linux/skmsg.h | 17 +++++++++-- net/ipv4/tcp_bpf.c | 66 +++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 78 insertions(+), 5 deletions(-)
include/linux/skmsg.h +15 -2
@@ -98,6 +98,7 @@ struct sk_psock {void (*saved_close)(struct sock *sk,long timeout);void (*saved_write_space)(struct sock *sk);struct proto *sk_proto; +const struct inet_connection_sock_af_ops *icsk_af_ops;struct sk_psock_work_state work_state;struct work_struct work;union {
@@ -345,23 +346,30 @@ static inline void sk_psock_cork_free(struct sk_psock *psock)static inline void sk_psock_update_proto (struct sock *sk,struct sk_psock *psock, -struct proto *ops) +struct proto *ops, +struct inet_connection_sock_af_ops *af_ops) { +struct inet_connection_sock *icsk =inet_csk (sk); + psock->saved_unhash = sk->sk_prot->unhash; psock->saved_close = sk->sk_prot->close; psock->saved_write_space = sk->sk_write_space; psock->sk_proto = sk->sk_prot; sk->sk_prot = ops; + + psock->icsk_af_ops = icsk->icsk_af_ops; + icsk->icsk_af_ops = af_ops; }static inline void sk_psock_restore_proto (struct sock *sk,struct sk_psock *psock) { +struct inet_connection_sock *icsk =inet_csk (sk); + sk->sk_write_space = psock->saved_write_space;if (psock->sk_proto) { -struct inet_connection_sock *icsk =inet_csk (sk);bool has_ulp = !!icsk->icsk_ulp_data;if (has_ulp)
@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto =NULL ; } + +if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops =NULL ; + } } static inline void sk_psock_set_state(struct sk_psock *psock,
net/ipv4/tcp_bpf.c +63 -3
126 lines not on this page · raw message
Signature · 1 line
2.20.1
RE: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
Quoted 5 lines · Jakub Sitnicki
Sockets cloned from the listening sockets that belongs to a SOCKMAP must not inherit the psock state. Otherwise child sockets unintentionally share the SOCKMAP entry with the listening socket, which would lead to use-after-free bugs.
Quoted 8 lines
Restore the child socket psock state and its callbacks at the earliest possible moment, that is right after the child socket gets created. This ensures that neither children that get accept()'ed, nor those that are left in accept queue and will get orphaned, don't inadvertently inherit parent's psock.
Signed-off-by Jakub Sitnicki <[email protected]>---
Re: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
In reply to Jakub SitnickiOn Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]
Quoted 10 lines
include/linux/skmsg.h +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto =NULL ; } + +if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops =NULL ; + } }
[ ... ]
Quoted 9 lines
net/ipv4/tcp_bpf.c +9
-0+static struct sock *tcp_bpf_syn_recv_sock (const struct sock *sk, +struct sk_buff *skb, +struct request_sock *req, +struct dst_entry *dst, +struct request_sock *req_unhash, +bool *own_req) +{ +const struct inet_connection_sock_af_ops *ops; +void (*write_space)(struct sock *sk);
net/ipv4/tcp_bpf.c static void tcp_bpf_close(struct sock *sk, long timeout) · line 609
Quoted 10 lines
net/ipv4/tcp_bpf.c +10
-0+struct sk_psock *psock; +struct proto *proto; +struct sock *child; + +rcu_read_lock (); + psock =sk_psock (sk); +if (likely (psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;
It is not immediately clear to me what ensure
ops is not NULL here.
It is likely I missed something. A short comment would be very useful here.
Quoted 95 lines
net/ipv4/tcp_bpf.c +38
-3+ }else { + ops =inet_csk (sk)->icsk_af_ops; + } +rcu_read_unlock (); + + child = ops->syn_recv_sock (sk, skb, req, dst, req_unhash, own_req); + +/* Child must not inherit psock or its ops. */ +if (child && psock) { +rcu_assign_sk_user_data (child,NULL ); + child->sk_prot = proto; + child->sk_write_space = write_space; + +/* v4-mapped sockets don't inherit parent ops. Don't restore. */ +if (inet_csk (child)->icsk_af_ops ==inet_csk (sk)->icsk_af_ops) +inet_csk (child)->icsk_af_ops = ops; + } +return child; +} +enum {TCP_BPF_IPV4 ,TCP_BPF_IPV6 ,@@ -597,6 +642,7 @@ enum {static struct proto *tcpv6_prot_saved__read_mostly ;static DEFINE_SPINLOCK (tcpv6_prot_lock);static struct proto tcp_bpf_prots[TCP_BPF_NUM_PROTS ][TCP_BPF_NUM_CFGS ]; +static struct inet_connection_sock_af_ops tcp_bpf_af_ops[TCP_BPF_NUM_PROTS ];static void tcp_bpf_rebuild_protos (struct proto prot[TCP_BPF_NUM_CFGS ],struct proto *base)@@ -612,13 +658,23 @@ static void tcp_bpf_rebuild_protos(struct proto prot[TCP_BPF_NUM_CFGS], prot[TCP_BPF_TX ].sendpage = tcp_bpf_sendpage; } -static void tcp_bpf_check_v6_needs_rebuild (struct sock *sk,struct proto *ops) +static void tcp_bpf_rebuild_af_ops (struct inet_connection_sock_af_ops *ops, +const struct inet_connection_sock_af_ops *base) +{ + *ops = *base; + ops->syn_recv_sock = tcp_bpf_syn_recv_sock; +} + +static void tcp_bpf_check_v6_needs_rebuild (struct sock *sk,struct proto *ops, +const struct inet_connection_sock_af_ops *af_ops) {if (sk->sk_family ==AF_INET6 &&unlikely (ops !=smp_load_acquire (&tcpv6_prot_saved))) {spin_lock_bh (&tcpv6_prot_lock);if (likely (ops != tcpv6_prot_saved)) {tcp_bpf_rebuild_protos (tcp_bpf_prots[TCP_BPF_IPV6 ], ops); +tcp_bpf_rebuild_af_ops (&tcp_bpf_af_ops[TCP_BPF_IPV6 ], + af_ops);smp_store_release (&tcpv6_prot_saved, ops); }spin_unlock_bh (&tcpv6_prot_lock);@@ -628,6 +684,8 @@ static void tcp_bpf_check_v6_needs_rebuild(struct sock *sk, struct proto *ops)static int __init tcp_bpf_v4_build_proto (void ) {tcp_bpf_rebuild_protos (tcp_bpf_prots[TCP_BPF_IPV4 ], &tcp_prot); +tcp_bpf_rebuild_af_ops (&tcp_bpf_af_ops[TCP_BPF_IPV4 ], &ipv4_specific); +return 0 ; }core_initcall (tcp_bpf_v4_build_proto);@@ -637,7 +695,8 @@ static void tcp_bpf_update_sk_prot(struct sock *sk, struct sk_psock *psock)int family = sk->sk_family ==AF_INET6 ?TCP_BPF_IPV6 :TCP_BPF_IPV4 ;int config = psock->progs.msg_parser ?TCP_BPF_TX :TCP_BPF_BASE ; -sk_psock_update_proto (sk, psock, &tcp_bpf_prots[family][config]); +sk_psock_update_proto (sk, psock, &tcp_bpf_prots[family][config], + &tcp_bpf_af_ops[family]); }static void tcp_bpf_reinit_sk_prot (struct sock *sk,struct sk_psock *psock)@@ -677,6 +736,7 @@ void tcp_bpf_reinit(struct sock *sk)int tcp_bpf_init (struct sock *sk) { +struct inet_connection_sock *icsk =inet_csk (sk);struct proto *ops =READ_ONCE (sk->sk_prot);struct sk_psock *psock;@@ -689,7 +749,7 @@ int tcp_bpf_init(struct sock *sk)rcu_read_unlock ();return -EINVAL ; } -tcp_bpf_check_v6_needs_rebuild (sk, ops); +tcp_bpf_check_v6_needs_rebuild (sk, ops, icsk->icsk_af_ops);tcp_bpf_update_sk_prot (sk, psock);rcu_read_unlock ();return 0 ;Signature · 1 line
2.20.1
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
Quoted 38 lines · Martin Lau
On Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]Quoted 10 lines
include/linux/skmsg.h +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto =NULL ; } + +if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops =NULL ; + } }[ ... ]
Quoted 9 lines
net/ipv4/tcp_bpf.c +9
-0+static struct sock *tcp_bpf_syn_recv_sock (const struct sock *sk, +struct sk_buff *skb, +struct request_sock *req, +struct dst_entry *dst, +struct request_sock *req_unhash, +bool *own_req) +{ +const struct inet_connection_sock_af_ops *ops; +void (*write_space)(struct sock *sk);net/ipv4/tcp_bpf.c static void tcp_bpf_close(struct sock *sk, long timeout) · line 609
Quoted 10 lines
net/ipv4/tcp_bpf.c +10
-0+struct sk_psock *psock; +struct proto *proto; +struct sock *child; + +rcu_read_lock (); + psock =sk_psock (sk); +if (likely (psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;It is not immediately clear to me what ensure
ops is not NULL here.
Quoted 2 lines
It is likely I missed something. A short comment would be very useful here.
I can see the readability problem. Looking at it now, perhaps it should be rewritten, to the same effect, as:
static struct sock *tcp_bpf_syn_recv_sock(...)
{
const struct inet_connection_sock_af_ops *ops = NULL;
...
rcu_read_lock();
psock = sk_psock(sk);
if (likely(psock)) {
proto = psock->sk_proto;
write_space = psock->saved_write_space;
ops = psock->icsk_af_ops;
}
rcu_read_unlock();
if (!ops)
ops = inet_csk(sk)->icsk_af_ops;
child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);If psock->icsk_af_ops were NULL, it would mean we haven't initialized it properly. To double check what happens here:
In sock_map_link we do a setup dance where we first create the psock and later initialize the socket callbacks (tcp_bpf_init).
static int sock_map_link(struct bpf_map *map, struct sk_psock_progs *progs,
struct sock *sk)
{
...
if (psock) {
...
} else {
psock = sk_psock_init(sk, map->numa_node);
if (!psock) {
ret = -ENOMEM;
goto out_progs;
}
sk_psock_is_new = true;
}
...
if (sk_psock_is_new) {
ret = tcp_bpf_init(sk);
if (ret < 0)
goto out_drop;
} else {
tcp_bpf_reinit(sk);
}The "if (sk_psock_new)" branch triggers the call chain that leads to saving & overriding socket callbacks.
tcp_bpf_init -> tcp_bpf_update_sk_prot -> sk_psock_update_proto
Among them, icsk_af_ops.
static inline void sk_psock_update_proto(...)
{
...
psock->icsk_af_ops = icsk->icsk_af_ops;
icsk->icsk_af_ops = af_ops;
}Goes without saying that a comment is needed.
Thanks for the feedback,
Jakub
Re: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
Quoted 63 lines · Jakub Sitnicki
Quoted 38 lines · Martin Lau
On Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]Quoted 10 lines
include/linux/skmsg.h +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto =NULL ; } + +if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops =NULL ; + } }[ ... ]
Quoted 9 lines
net/ipv4/tcp_bpf.c +9
-0+static struct sock *tcp_bpf_syn_recv_sock (const struct sock *sk, +struct sk_buff *skb, +struct request_sock *req, +struct dst_entry *dst, +struct request_sock *req_unhash, +bool *own_req) +{ +const struct inet_connection_sock_af_ops *ops; +void (*write_space)(struct sock *sk);net/ipv4/tcp_bpf.c static void tcp_bpf_close(struct sock *sk, long timeout) · line 609
Quoted 10 lines
net/ipv4/tcp_bpf.c +10
-0+struct sk_psock *psock; +struct proto *proto; +struct sock *child; + +rcu_read_lock (); + psock =sk_psock (sk); +if (likely (psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;It is not immediately clear to me what ensure
ops is not NULL here.Quoted 2 lines
It is likely I missed something. A short comment would be very useful here.
I can see the readability problem. Looking at it now, perhaps it should be rewritten, to the same effect, as:
static struct sock
*tcp_bpf_syn_recv_sock(...){ const struct inet_connection_sock_af_ops *ops = NULL; ... rcu_read_lock(); psock = sk_psock(sk); if (likely(psock)) { proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops; } rcu_read_unlock(); if (!ops) ops = inet_csk(sk)->icsk_af_ops; child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);
Quoted 2 lines
If
psock->icsk_af_opswere NULL, it would mean we haven't initialized it properly. To double check what happens here:
I did not mean the init path. The init path is fine since it init eveything on psock before publishing the sk to the sock_map.
I was thinking the delete path (e.g. sock_map_delete_elem). It is not clear to me what prevent the earlier pasted sk_psock_restore_proto() which sets psock->icsk_af_ops to NULL from running in parallel with tcp_bpf_syn_recv_sock()? An explanation would be useful.
Quoted 45 lines
In
sock_map_linkwe do a setup dance where we first create the psock and later initialize the socket callbacks (tcp_bpf_init).static int sock_map_link(struct
bpf_map*map, structsk_psock_progs*progs,
struct sock *sk){ ... if (psock) { ... } else { psock = sk_psock_init(sk, map->numa_node); if (!psock) { ret = -ENOMEM; goto out_progs; } sk_psock_is_new = true; } ... if (sk_psock_is_new) { ret = tcp_bpf_init(sk); if (ret < 0) goto out_drop; } else { tcp_bpf_reinit(sk); }The "if (
sk_psock_new)" branch triggers the call chain that leads to saving & overriding socket callbacks.
tcp_bpf_init->tcp_bpf_update_sk_prot->sk_psock_update_protoAmong them,
icsk_af_ops.static inline void
sk_psock_update_proto(...){ ... psock->icsk_af_ops = icsk->icsk_af_ops; icsk->icsk_af_ops = af_ops; }Goes without saying that a comment is needed.
Thanks for the feedback,
Jakub
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
Quoted 66 lines · Martin Lau
Quoted 63 lines · Jakub Sitnicki
Quoted 38 lines · Martin Lau
On Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]Quoted 10 lines
include/linux/skmsg.h +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto =NULL ; } + +if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops =NULL ; + } }[ ... ]
Quoted 9 lines
net/ipv4/tcp_bpf.c +9
-0+static struct sock *tcp_bpf_syn_recv_sock (const struct sock *sk, +struct sk_buff *skb, +struct request_sock *req, +struct dst_entry *dst, +struct request_sock *req_unhash, +bool *own_req) +{ +const struct inet_connection_sock_af_ops *ops; +void (*write_space)(struct sock *sk);net/ipv4/tcp_bpf.c static void tcp_bpf_close(struct sock *sk, long timeout) · line 609
Quoted 10 lines
net/ipv4/tcp_bpf.c +10
-0+struct sk_psock *psock; +struct proto *proto; +struct sock *child; + +rcu_read_lock (); + psock =sk_psock (sk); +if (likely (psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;It is not immediately clear to me what ensure
ops is not NULL here.Quoted 2 lines
It is likely I missed something. A short comment would be very useful here.
I can see the readability problem. Looking at it now, perhaps it should be rewritten, to the same effect, as:
static struct sock
*tcp_bpf_syn_recv_sock(...){ const struct inet_connection_sock_af_ops *ops = NULL; ... rcu_read_lock(); psock = sk_psock(sk); if (likely(psock)) { proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops; } rcu_read_unlock(); if (!ops) ops = inet_csk(sk)->icsk_af_ops; child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);Quoted 2 lines
If
psock->icsk_af_opswere NULL, it would mean we haven't initialized it properly. To double check what happens here:
Quoted 7 lines
I did not mean the init path. The init path is fine since it init eveything on psock before publishing the sk to the
sock_map.I was thinking the delete path (e.g.
sock_map_delete_elem). It is not clear to me what prevent the earlier pastedsk_psock_restore_proto()which setspsock->icsk_af_opsto NULL from running in parallel withtcp_bpf_syn_recv_sock()? An explanation would be useful.
Ah, I misunderstood. Nothing prevents the race, AFAIK.
Setting psock->icsk_af_ops to null on restore and not checking for it here was a bad move on my side. Also I need to revisit what to do about psock->sk_proto so the child socket doesn't end up with null sk_proto.
This race should be easy enough to trigger. Will give it a shot.
Thank you for bringing this up,
Jakub
Quoted 46 lines
Quoted 46 lines
In
sock_map_linkwe do a setup dance where we first create the psock and later initialize the socket callbacks (tcp_bpf_init).static int sock_map_link(struct
bpf_map*map, structsk_psock_progs*progs,
struct sock *sk){ ... if (psock) { ... } else { psock = sk_psock_init(sk, map->numa_node); if (!psock) { ret = -ENOMEM; goto out_progs; } sk_psock_is_new = true; } ... if (sk_psock_is_new) { ret = tcp_bpf_init(sk); if (ret < 0) goto out_drop; } else { tcp_bpf_reinit(sk); }The "if (
sk_psock_new)" branch triggers the call chain that leads to saving & overriding socket callbacks.
tcp_bpf_init->tcp_bpf_update_sk_prot->sk_psock_update_protoAmong them,
icsk_af_ops.static inline void
sk_psock_update_proto(...){ ... psock->icsk_af_ops = icsk->icsk_af_ops; icsk->icsk_af_ops = af_ops; }Goes without saying that a comment is needed.
Thanks for the feedback,
Jakub
A message that is not in the archive (sent off-list or not yet received): [email protected]
Re: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
Quoted 119 lines · Jakub Sitnicki
John, Martin,
Quoted 75 lines · Jakub Sitnicki
Quoted 66 lines · Martin Lau
Quoted 63 lines · Jakub Sitnicki
Quoted 38 lines · Martin Lau
On Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]Quoted 10 lines
include/linux/skmsg.h +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto =NULL ; } + +if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops =NULL ; + } }[ ... ]
Quoted 9 lines
net/ipv4/tcp_bpf.c +9
-0+static struct sock *tcp_bpf_syn_recv_sock (const struct sock *sk, +struct sk_buff *skb, +struct request_sock *req, +struct dst_entry *dst, +struct request_sock *req_unhash, +bool *own_req) +{ +const struct inet_connection_sock_af_ops *ops; +void (*write_space)(struct sock *sk);net/ipv4/tcp_bpf.c static void tcp_bpf_close(struct sock *sk, long timeout) · line 609
Quoted 10 lines
net/ipv4/tcp_bpf.c +10
-0+struct sk_psock *psock; +struct proto *proto; +struct sock *child; + +rcu_read_lock (); + psock =sk_psock (sk); +if (likely (psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;It is not immediately clear to me what ensure
ops is not NULL here.Quoted 2 lines
It is likely I missed something. A short comment would be very useful here.
I can see the readability problem. Looking at it now, perhaps it should be rewritten, to the same effect, as:
static struct sock
*tcp_bpf_syn_recv_sock(...){ const struct inet_connection_sock_af_ops *ops = NULL; ... rcu_read_lock(); psock = sk_psock(sk); if (likely(psock)) { proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops; } rcu_read_unlock(); if (!ops) ops = inet_csk(sk)->icsk_af_ops; child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);Quoted 2 lines
If
psock->icsk_af_opswere NULL, it would mean we haven't initialized it properly. To double check what happens here:Quoted 7 lines
I did not mean the init path. The init path is fine since it init eveything on psock before publishing the sk to the
sock_map.I was thinking the delete path (e.g.
sock_map_delete_elem). It is not clear to me what prevent the earlier pastedsk_psock_restore_proto()which setspsock->icsk_af_opsto NULL from running in parallel withtcp_bpf_syn_recv_sock()? An explanation would be useful.Quoted 7 lines
Ah, I misunderstood. Nothing prevents the race, AFAIK.
Setting
psock->icsk_af_opsto null on restore and not checking for it here was a bad move on my side. Also I need to revisit what to do aboutpsock->sk_protoso the child socket doesn't end up with nullsk_proto.This race should be easy enough to trigger. Will give it a shot.
I've convinced myself that this approach is racy beyond repair.
Once
syn_recv_sock()has returned it is too late to reset the childsk_user_dataand restore its callbacks. It has been already inserted into ehash and ingress path can invoke its callbacks.The race can be triggered with with a reproducer where:
thread-1:
p = accept(s, ...); close(p);thread-2:
bpf_map_update_elem(mapfd, &key, &s, BPF_NOEXIST); bpf_map_delete_elem(mapfd, &key);This a dead-end because we can't have the parent and the child share the psock state. Even though psock itself is refcounted, and potentially we could grab a reference before cloning the parent, link into the map that psock holds is not.
Two ways out come to mind. Both involve touching TCP code, which I was hoping to avoid:
1) reset
sk_user_datawhen initializing the childThis is problematic because
tcp_bpfcallbacks are not designed to handle sockets with no psock _and_ with overriddensk_protcallbacks. (Although, I think they could if the fallback was directly on {tcp,tcpv6}_prot based on socket domain.)
Quoted 4 lines
Also, there are other
sk_user_datausers like DRBD which rely on sharing thesk_user_datapointer between parent and child, if I read the code correctly [0]. If anything, clearing thesk_user_dataon clone would have to be guarded by a flag.
Can the copy/not-to-copy sk_user_data decision be made in sk_clone_lock()?
Quoted 40 lines
2) Restore
sk_protcallbacks on clone to {tcp,tcpv6}_protThe simpler way out.
tcp_bpfcallbacks never get invoked on the child socket so the copied psock reference is no longer a problem. We can clear the pointer onaccept().So far I wasn't able poke any holes in it and it comes down to patching
tcp_create_openreq_child()with:/* sk_msg and ULP frameworks can override the callbacks into * protocol. We don't assume they are intended to be inherited * by the child. Frameworks can re-install the callbacks on * accept() if needed. */ WRITE_ONCE(newsk->sk_prot, sk->sk_prot_creator);That's what I'm going with for v2.
Open to suggestions.
Thanks,
JakubBTW. Reading into kTLS code, I noticed it has been limited down to just established sockets due to the same problem I'm struggling with here:
static int
tls_init(struct sock *sk)
{
.../* The TLS ulp is currently supported only for TCP sockets * in ESTABLISHED state. * Supporting sockets in LISTEN state will require us * to modify the accept implementation to clone rather then * share the ulp context. */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN;
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
Quoted 120 lines · Martin Lau
Quoted 119 lines · Jakub Sitnicki
John, Martin,
Quoted 75 lines · Jakub Sitnicki
Quoted 66 lines · Martin Lau
Quoted 63 lines · Jakub Sitnicki
Quoted 38 lines · Martin Lau
On Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]Quoted 10 lines
(quoted diff) +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto = NULL; } + + if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops = NULL; + } }[ ... ]
Quoted 9 lines
(quoted diff) +9
-0+static struct sock *tcp_bpf_syn_recv_sock(const struct sock *sk, + struct sk_buff *skb, + struct request_sock *req, + struct dst_entry *dst, + struct request_sock *req_unhash, + bool *own_req) +{ + const struct inet_connection_sock_af_ops *ops; + void (*write_space)(struct sock *sk);Review
Quoted 10 lines
(quoted diff) +10
-0+ struct sk_psock *psock; + struct proto *proto; + struct sock *child; + + rcu_read_lock(); + psock = sk_psock(sk); + if (likely(psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;It is not immediately clear to me what ensure
ops is not NULL here.Quoted 2 lines
It is likely I missed something. A short comment would be very useful here.
I can see the readability problem. Looking at it now, perhaps it should be rewritten, to the same effect, as:
static struct sock
*tcp_bpf_syn_recv_sock(...){ const struct inet_connection_sock_af_ops *ops = NULL; ... rcu_read_lock(); psock = sk_psock(sk); if (likely(psock)) { proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops; } rcu_read_unlock(); if (!ops) ops = inet_csk(sk)->icsk_af_ops; child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);Quoted 2 lines
If
psock->icsk_af_opswere NULL, it would mean we haven't initialized it properly. To double check what happens here:Quoted 7 lines
I did not mean the init path. The init path is fine since it init eveything on psock before publishing the sk to the
sock_map.I was thinking the delete path (e.g.
sock_map_delete_elem). It is not clear to me what prevent the earlier pastedsk_psock_restore_proto()which setspsock->icsk_af_opsto NULL from running in parallel withtcp_bpf_syn_recv_sock()? An explanation would be useful.Quoted 7 lines
Ah, I misunderstood. Nothing prevents the race, AFAIK.
Setting
psock->icsk_af_opsto null on restore and not checking for it here was a bad move on my side. Also I need to revisit what to do aboutpsock->sk_protoso the child socket doesn't end up with nullsk_proto.This race should be easy enough to trigger. Will give it a shot.
I've convinced myself that this approach is racy beyond repair.
Once
syn_recv_sock()has returned it is too late to reset the childsk_user_dataand restore its callbacks. It has been already inserted into ehash and ingress path can invoke its callbacks.The race can be triggered with with a reproducer where:
thread-1:
p = accept(s, ...); close(p);thread-2:
bpf_map_update_elem(mapfd, &key, &s, BPF_NOEXIST); bpf_map_delete_elem(mapfd, &key);This a dead-end because we can't have the parent and the child share the psock state. Even though psock itself is refcounted, and potentially we could grab a reference before cloning the parent, link into the map that psock holds is not.
Two ways out come to mind. Both involve touching TCP code, which I was hoping to avoid:
1) reset
sk_user_datawhen initializing the childThis is problematic because
tcp_bpfcallbacks are not designed to handle sockets with no psock _and_ with overriddensk_protcallbacks. (Although, I think they could if the fallback was directly on {tcp,tcpv6}_prot based on socket domain.)
Quoted 6 lines
Quoted 4 lines
Also, there are other
sk_user_datausers like DRBD which rely on sharing thesk_user_datapointer between parent and child, if I read the code correctly [0]. If anything, clearing thesk_user_dataon clone would have to be guarded by a flag.Can the copy/not-to-copy
sk_user_datadecision be made insk_clone_lock()?
Yes, this could be pushed down to sk_clone_lock(), where we do similar work (reset sk_reuseport_cb and clone bpf_sk_storage):
/* User data can hold reference. Child must not
* inherit the pointer without acquiring a reference.
*/
if (sock_flag(sk, SOCK_OWNS_USER_DATA)) {
sock_reset_flag(newsk, SOCK_OWNS_USER_DATA);
RCU_INIT_POINTER(newsk->sk_user_data, NULL);
}I belive this would still need to be guarded by a flag. Do you see value in clearing child sk_user_data on clone as opposed to dealying that work until accept() time?
-Jakub
Quoted 41 lines
Quoted 41 lines
2) Restore
sk_protcallbacks on clone to {tcp,tcpv6}_protThe simpler way out.
tcp_bpfcallbacks never get invoked on the child socket so the copied psock reference is no longer a problem. We can clear the pointer onaccept().So far I wasn't able poke any holes in it and it comes down to patching
tcp_create_openreq_child()with:/* sk_msg and ULP frameworks can override the callbacks into * protocol. We don't assume they are intended to be inherited * by the child. Frameworks can re-install the callbacks on * accept() if needed. */ WRITE_ONCE(newsk->sk_prot, sk->sk_prot_creator);That's what I'm going with for v2.
Open to suggestions.
Thanks,
JakubBTW. Reading into kTLS code, I noticed it has been limited down to just established sockets due to the same problem I'm struggling with here:
static int
tls_init(struct sock *sk)
{
.../* The TLS ulp is currently supported only for TCP sockets * in ESTABLISHED state. * Supporting sockets in LISTEN state will require us * to modify the accept implementation to clone rather then * share the ulp context. */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN;
Re: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
Quoted 125 lines · Jakub Sitnicki
Quoted 124 lines · Martin Lau
Quoted 123 lines · Jakub Sitnicki
John, Martin,
Quoted 75 lines · Jakub Sitnicki
Quoted 66 lines · Martin Lau
Quoted 63 lines · Jakub Sitnicki
Quoted 38 lines · Martin Lau
On Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]Quoted 10 lines
(quoted diff) +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto = NULL; } + + if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops = NULL; + } }[ ... ]
Quoted 9 lines
(quoted diff) +9
-0+static struct sock *tcp_bpf_syn_recv_sock(const struct sock *sk, + struct sk_buff *skb, + struct request_sock *req, + struct dst_entry *dst, + struct request_sock *req_unhash, + bool *own_req) +{ + const struct inet_connection_sock_af_ops *ops; + void (*write_space)(struct sock *sk);Review
Quoted 10 lines
(quoted diff) +10
-0+ struct sk_psock *psock; + struct proto *proto; + struct sock *child; + + rcu_read_lock(); + psock = sk_psock(sk); + if (likely(psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;It is not immediately clear to me what ensure
ops is not NULL here.Quoted 2 lines
It is likely I missed something. A short comment would be very useful here.
I can see the readability problem. Looking at it now, perhaps it should be rewritten, to the same effect, as:
static struct sock
*tcp_bpf_syn_recv_sock(...){ const struct inet_connection_sock_af_ops *ops = NULL; ... rcu_read_lock(); psock = sk_psock(sk); if (likely(psock)) { proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops; } rcu_read_unlock(); if (!ops) ops = inet_csk(sk)->icsk_af_ops; child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);Quoted 2 lines
If
psock->icsk_af_opswere NULL, it would mean we haven't initialized it properly. To double check what happens here:Quoted 7 lines
I did not mean the init path. The init path is fine since it init eveything on psock before publishing the sk to the
sock_map.I was thinking the delete path (e.g.
sock_map_delete_elem). It is not clear to me what prevent the earlier pastedsk_psock_restore_proto()which setspsock->icsk_af_opsto NULL from running in parallel withtcp_bpf_syn_recv_sock()? An explanation would be useful.Quoted 7 lines
Ah, I misunderstood. Nothing prevents the race, AFAIK.
Setting
psock->icsk_af_opsto null on restore and not checking for it here was a bad move on my side. Also I need to revisit what to do aboutpsock->sk_protoso the child socket doesn't end up with nullsk_proto.This race should be easy enough to trigger. Will give it a shot.
I've convinced myself that this approach is racy beyond repair.
Once
syn_recv_sock()has returned it is too late to reset the childsk_user_dataand restore its callbacks. It has been already inserted into ehash and ingress path can invoke its callbacks.The race can be triggered with with a reproducer where:
thread-1:
p = accept(s, ...); close(p);thread-2:
bpf_map_update_elem(mapfd, &key, &s, BPF_NOEXIST); bpf_map_delete_elem(mapfd, &key);This a dead-end because we can't have the parent and the child share the psock state. Even though psock itself is refcounted, and potentially we could grab a reference before cloning the parent, link into the map that psock holds is not.
Two ways out come to mind. Both involve touching TCP code, which I was hoping to avoid:
1) reset
sk_user_datawhen initializing the childThis is problematic because
tcp_bpfcallbacks are not designed to handle sockets with no psock _and_ with overriddensk_protcallbacks. (Although, I think they could if the fallback was directly on {tcp,tcpv6}_prot based on socket domain.)Also, there are other
sk_user_datausers like DRBD which rely on sharing thesk_user_datapointer between parent and child, if I read the code correctly [0]. If anything, clearing thesk_user_dataon clone would have to be guarded by a flag.
Quoted 5 lines
Quoted 2 lines
Can the copy/not-to-copy
sk_user_datadecision be made insk_clone_lock()?Yes, this could be pushed down to
sk_clone_lock(), where we do similar work (resetsk_reuseport_cband clonebpf_sk_storage):
aha. I missed your eariler "clearing the sk_user_data on clone would have to be guarded by a flag..." part. It turns out we were talking the same thing on (1). sock_flag works better if there is still bit left (and it seems there is one), although I was thinking more like adding something (e.g. a func ptr) to 'struct proto' to mangle sk_user_data before returning newsk....but not sure this kind of logic belongs to 'struct proto'
Quoted 9 lines
/* User data can hold reference. Child must not
* inherit the pointer without acquiring a reference.
*/
if (sock_flag(sk, SOCK_OWNS_USER_DATA)) {
sock_reset_flag(newsk, SOCK_OWNS_USER_DATA);
RCU_INIT_POINTER(newsk->sk_user_data, NULL);
}Quoted 3 lines
I belive this would still need to be guarded by a flag. Do you see value in clearing child
sk_user_dataon clone as opposed to dealying that work untilaccept()time?
It seems to me clearing things up front at the very beginning is more straight forward, such that it does not have to worry about the sk_user_data may be used in a wrong way before it gets a chance to be cleared in accept().
Just something to consider, if it is obvious that there is no hole in clearing it in accept(), it is fine too.
Quoted 40 lines
Quoted 40 lines
Quoted 40 lines
2) Restore
sk_protcallbacks on clone to {tcp,tcpv6}_protThe simpler way out.
tcp_bpfcallbacks never get invoked on the child socket so the copied psock reference is no longer a problem. We can clear the pointer onaccept().So far I wasn't able poke any holes in it and it comes down to patching
tcp_create_openreq_child()with:/* sk_msg and ULP frameworks can override the callbacks into * protocol. We don't assume they are intended to be inherited * by the child. Frameworks can re-install the callbacks on * accept() if needed. */ WRITE_ONCE(newsk->sk_prot, sk->sk_prot_creator);That's what I'm going with for v2.
Open to suggestions.
Thanks,
JakubBTW. Reading into kTLS code, I noticed it has been limited down to just established sockets due to the same problem I'm struggling with here:
static int
tls_init(struct sock *sk)
{
.../* The TLS ulp is currently supported only for TCP sockets * in ESTABLISHED state. * Supporting sockets in LISTEN state will require us * to modify the accept implementation to clone rather then * share the ulp context. */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN;
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
Quoted 131 lines · Martin Lau
Quoted 125 lines · Jakub Sitnicki
Quoted 124 lines · Martin Lau
Quoted 123 lines · Jakub Sitnicki
John, Martin,
Quoted 75 lines · Jakub Sitnicki
Quoted 66 lines · Martin Lau
Quoted 63 lines · Jakub Sitnicki
Quoted 38 lines · Martin Lau
On Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]Quoted 10 lines
(quoted diff) +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto = NULL; } + + if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops = NULL; + } }[ ... ]
Quoted 9 lines
(quoted diff) +9
-0+static struct sock *tcp_bpf_syn_recv_sock(const struct sock *sk, + struct sk_buff *skb, + struct request_sock *req, + struct dst_entry *dst, + struct request_sock *req_unhash, + bool *own_req) +{ + const struct inet_connection_sock_af_ops *ops; + void (*write_space)(struct sock *sk);Review
Quoted 10 lines
(quoted diff) +10
-0+ struct sk_psock *psock; + struct proto *proto; + struct sock *child; + + rcu_read_lock(); + psock = sk_psock(sk); + if (likely(psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;It is not immediately clear to me what ensure
ops is not NULL here.Quoted 2 lines
It is likely I missed something. A short comment would be very useful here.
I can see the readability problem. Looking at it now, perhaps it should be rewritten, to the same effect, as:
static struct sock
*tcp_bpf_syn_recv_sock(...){ const struct inet_connection_sock_af_ops *ops = NULL; ... rcu_read_lock(); psock = sk_psock(sk); if (likely(psock)) { proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops; } rcu_read_unlock(); if (!ops) ops = inet_csk(sk)->icsk_af_ops; child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);Quoted 2 lines
If
psock->icsk_af_opswere NULL, it would mean we haven't initialized it properly. To double check what happens here:Quoted 7 lines
I did not mean the init path. The init path is fine since it init eveything on psock before publishing the sk to the
sock_map.I was thinking the delete path (e.g.
sock_map_delete_elem). It is not clear to me what prevent the earlier pastedsk_psock_restore_proto()which setspsock->icsk_af_opsto NULL from running in parallel withtcp_bpf_syn_recv_sock()? An explanation would be useful.Quoted 7 lines
Ah, I misunderstood. Nothing prevents the race, AFAIK.
Setting
psock->icsk_af_opsto null on restore and not checking for it here was a bad move on my side. Also I need to revisit what to do aboutpsock->sk_protoso the child socket doesn't end up with nullsk_proto.This race should be easy enough to trigger. Will give it a shot.
I've convinced myself that this approach is racy beyond repair.
Once
syn_recv_sock()has returned it is too late to reset the childsk_user_dataand restore its callbacks. It has been already inserted into ehash and ingress path can invoke its callbacks.The race can be triggered with with a reproducer where:
thread-1:
p = accept(s, ...); close(p);thread-2:
bpf_map_update_elem(mapfd, &key, &s, BPF_NOEXIST); bpf_map_delete_elem(mapfd, &key);This a dead-end because we can't have the parent and the child share the psock state. Even though psock itself is refcounted, and potentially we could grab a reference before cloning the parent, link into the map that psock holds is not.
Two ways out come to mind. Both involve touching TCP code, which I was hoping to avoid:
1) reset
sk_user_datawhen initializing the childThis is problematic because
tcp_bpfcallbacks are not designed to handle sockets with no psock _and_ with overriddensk_protcallbacks. (Although, I think they could if the fallback was directly on {tcp,tcpv6}_prot based on socket domain.)Also, there are other
sk_user_datausers like DRBD which rely on sharing thesk_user_datapointer between parent and child, if I read the code correctly [0]. If anything, clearing thesk_user_dataon clone would have to be guarded by a flag.Quoted 5 lines
Quoted 2 lines
Can the copy/not-to-copy
sk_user_datadecision be made insk_clone_lock()?Yes, this could be pushed down to
sk_clone_lock(), where we do similar work (resetsk_reuseport_cband clonebpf_sk_storage):
Quoted 7 lines
aha. I missed your eariler "clearing the
sk_user_dataon clone would have to be guarded by a flag..." part. It turns out we were talking the same thing on (1).sock_flagworks better if there is still bit left (and it seems there is one), although I was thinking more like adding something (e.g. a func ptr) to 'struct proto' to manglesk_user_databefore returning newsk....but not sure this kind of logic belongs to 'struct proto'
Sorry for late reply.
We have 4 bits left by my count. The multi-line comment for SOCK_NOFCS is getting in the way of counting them line-for-bit.
A callback invoked on socket clone is something I was considering too. I'm not sure either where it belongs. At risk of being too use-case specific, perhaps it could live together with sk_user_data and sk_prot, which it would mangle on sk_clone_lock():
struct sock {
...
void *sk_user_data;
void (*sk_clone)(struct sock *sk,
struct sock *newsk);
...
}But, I feel adding a new sock field just for this wouldn't be justified. I can get by with a sock flag. Unless we have other uses for it?
Quoted 13 lines
Quoted 10 lines
/* User data can hold reference. Child must not * inherit the pointer without acquiring a reference. */ if (sock_flag(sk, SOCK_OWNS_USER_DATA)) { sock_reset_flag(newsk, SOCK_OWNS_USER_DATA); RCU_INIT_POINTER(newsk->sk_user_data, NULL); }Quoted 3 lines
I belive this would still need to be guarded by a flag. Do you see value in clearing child
sk_user_dataon clone as opposed to dealying that work untilaccept()time?
Quoted 7 lines
It seems to me clearing things up front at the very beginning is more straight forward, such that it does not have to worry about the
sk_user_datamay be used in a wrong way before it gets a chance to be cleared inaccept().Just something to consider, if it is obvious that there is no hole in clearing it in
accept(), it is fine too.
Just when I thought I could get away with lazily clearing the sk_user_data at accept() time, it occurred to me that it is not enough.
Listening socket could get deleted from sockmap before a child socket that inherited a copy of sk_user_data pointer gets accept()'ed. In such scenario the pointer would not get NULL'ed on accept(), because listening socket would have it's sk_prot->accept restored by then.
I will need that flag after all...
-jkbs
Quoted 41 lines
Quoted 41 lines
Quoted 41 lines
Quoted 41 lines
2) Restore
sk_protcallbacks on clone to {tcp,tcpv6}_protThe simpler way out.
tcp_bpfcallbacks never get invoked on the child socket so the copied psock reference is no longer a problem. We can clear the pointer onaccept().So far I wasn't able poke any holes in it and it comes down to patching
tcp_create_openreq_child()with:/* sk_msg and ULP frameworks can override the callbacks into * protocol. We don't assume they are intended to be inherited * by the child. Frameworks can re-install the callbacks on * accept() if needed. */ WRITE_ONCE(newsk->sk_prot, sk->sk_prot_creator);That's what I'm going with for v2.
Open to suggestions.
Thanks,
JakubBTW. Reading into kTLS code, I noticed it has been limited down to just established sockets due to the same problem I'm struggling with here:
static int
tls_init(struct sock *sk)
{
.../* The TLS ulp is currently supported only for TCP sockets * in ESTABLISHED state. * Supporting sockets in LISTEN state will require us * to modify the accept implementation to clone rather then * share the ulp context. */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN;
John Fastabend
maintainerRe: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
In reply to Martin LauQuoted 66 lines · Martin Lau
Quoted 63 lines · Jakub Sitnicki
Quoted 38 lines · Martin Lau
On Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]Quoted 10 lines
include/linux/skmsg.h +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto =NULL ; } + +if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops =NULL ; + } }[ ... ]
Quoted 9 lines
net/ipv4/tcp_bpf.c +9
-0+static struct sock *tcp_bpf_syn_recv_sock (const struct sock *sk, +struct sk_buff *skb, +struct request_sock *req, +struct dst_entry *dst, +struct request_sock *req_unhash, +bool *own_req) +{ +const struct inet_connection_sock_af_ops *ops; +void (*write_space)(struct sock *sk);net/ipv4/tcp_bpf.c static void tcp_bpf_close(struct sock *sk, long timeout) · line 609
Quoted 10 lines
net/ipv4/tcp_bpf.c +10
-0+struct sk_psock *psock; +struct proto *proto; +struct sock *child; + +rcu_read_lock (); + psock =sk_psock (sk); +if (likely (psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;It is not immediately clear to me what ensure
ops is not NULL here.Quoted 2 lines
It is likely I missed something. A short comment would be very useful here.
I can see the readability problem. Looking at it now, perhaps it should be rewritten, to the same effect, as:
static struct sock
*tcp_bpf_syn_recv_sock(...){ const struct inet_connection_sock_af_ops *ops = NULL; ... rcu_read_lock(); psock = sk_psock(sk); if (likely(psock)) { proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops; } rcu_read_unlock(); if (!ops) ops = inet_csk(sk)->icsk_af_ops; child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);Quoted 2 lines
If
psock->icsk_af_opswere NULL, it would mean we haven't initialized it properly. To double check what happens here:
Quoted 8 lines
I did not mean the init path. The init path is fine since it init eveything on psock before publishing the sk to the
sock_map.I was thinking the delete path (e.g.
sock_map_delete_elem). It is not clear to me what prevent the earlier pastedsk_psock_restore_proto()which setspsock->icsk_af_opsto NULL from running in parallel withtcp_bpf_syn_recv_sock()? An explanation would be useful.
I'll answer. Updates are protected via sk_callback_lock so we don't have parrallel updates in-flight causing write_space and sk_proto to be out of sync. However access should be OK because its a pointer write we never update the pointer in place, e.g.
static inline void sk_psock_restore_proto(struct sock *sk,
struct sk_psock *psock)
{
+ struct inet_connection_sock *icsk = inet_csk(sk);
+
sk->sk_write_space = psock->saved_write_space;
if (psock->sk_proto) {
struct inet_connection_sock *icsk = inet_csk(sk);
bool has_ulp = !!icsk->icsk_ulp_data;
if (has_ulp)
tcp_update_ulp(sk, psock->sk_proto);
else
sk->sk_prot = psock->sk_proto;
psock->sk_proto = NULL;
}+
+ if (psock->icsk_af_ops) {
+ icsk->icsk_af_ops = psock->icsk_af_ops;
+ psock->icsk_af_ops = NULL;
+ }
}
In restore case either psock->icsk_af_ops is null or not. If its null below code catches it. If its not null (from init path) then we have a valid pointer.
rcu_read_lock(); psock = sk_psock(sk);
if (likely(psock)) {
proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops;
}
rcu_read_unlock();
if (!ops)
ops = inet_csk(sk)->icsk_af_ops;
child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);We should do this with proper READ_ONCE/WRITE_ONCE to make it clear what is going on and to stop compiler from breaking these assumptions. I was going to generate that patch after this series but can do it before as well. I didn't mention it here because it seems a bit out of scope for this series because its mostly a fix to older code.
Also I started to think that write_space might be out of sync with ops but it seems we never actually remove psock_write_space until after rcu grace period so that should be OK as well and always point to the previous write_space.
Finally I wondered if we could remove the ops and then add it back quickly which seems at least in theory possible, but that would get hit with a grace period because we can't have conflicting psock definitions on the same sock. So expanding the rcu block to include the ops = inet_csk(sk)->icsk_af_ops would fix that case.
So in summary I think we should expand the rcu lock here to include the ops = inet_csk(sk)->icsk_af_ops to ensure we dont race with tear down and create. I'll push the necessary update with WRITE_ONCE and READ_ONCE to fix that up. Seeing we have to wait until the merge window opens most likely anyways I'll send those out sooner rather then later and this series can add the proper annotations as well.
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 4/8] bpf, sockmap: Don't let child socket inherit psock or its ops on copy
Quoted 124 lines · John Fastabend
Quoted 66 lines · Martin Lau
Quoted 63 lines · Jakub Sitnicki
Quoted 38 lines · Martin Lau
On Sat, Nov 23, 2019 at 12:07:47PM +0100, Jakub Sitnicki wrote:
[ ... ]Quoted 10 lines
include/linux/skmsg.h +5
-0@@ -370,6 +378,11 @@ static inline void sk_psock_restore_proto(struct sock *sk, sk->sk_prot = psock->sk_proto; psock->sk_proto =NULL ; } + +if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops =NULL ; + } }[ ... ]
Quoted 9 lines
net/ipv4/tcp_bpf.c +9
-0+static struct sock *tcp_bpf_syn_recv_sock (const struct sock *sk, +struct sk_buff *skb, +struct request_sock *req, +struct dst_entry *dst, +struct request_sock *req_unhash, +bool *own_req) +{ +const struct inet_connection_sock_af_ops *ops; +void (*write_space)(struct sock *sk);net/ipv4/tcp_bpf.c static void tcp_bpf_close(struct sock *sk, long timeout) · line 609
Quoted 10 lines
net/ipv4/tcp_bpf.c +10
-0+struct sk_psock *psock; +struct proto *proto; +struct sock *child; + +rcu_read_lock (); + psock =sk_psock (sk); +if (likely (psock)) { + proto = psock->sk_proto; + write_space = psock->saved_write_space; + ops = psock->icsk_af_ops;It is not immediately clear to me what ensure
ops is not NULL here.Quoted 2 lines
It is likely I missed something. A short comment would be very useful here.
I can see the readability problem. Looking at it now, perhaps it should be rewritten, to the same effect, as:
static struct sock
*tcp_bpf_syn_recv_sock(...){ const struct inet_connection_sock_af_ops *ops = NULL; ... rcu_read_lock(); psock = sk_psock(sk); if (likely(psock)) { proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops; } rcu_read_unlock(); if (!ops) ops = inet_csk(sk)->icsk_af_ops; child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);Quoted 2 lines
If
psock->icsk_af_opswere NULL, it would mean we haven't initialized it properly. To double check what happens here:Quoted 8 lines
I did not mean the init path. The init path is fine since it init eveything on psock before publishing the sk to the
sock_map.I was thinking the delete path (e.g.
sock_map_delete_elem). It is not clear to me what prevent the earlier pastedsk_psock_restore_proto()which setspsock->icsk_af_opsto NULL from running in parallel withtcp_bpf_syn_recv_sock()? An explanation would be useful.I'll answer. Updates are protected via
sk_callback_lockso we don't have parrallel updates in-flight causingwrite_spaceandsk_prototo be out of sync. However access should be OK because its a pointer write we never update the pointer in place, e.g.static inline void sk_psock_restore_proto(struct sock *sk,
structsk_psock*psock)
{(quoted diff) +2
-0+ struct inet_connection_sock *icsk = inet_csk(sk); +sk->sk_write_space = psock->saved_write_space; if (psock->sk_proto) { struct inet_connection_sock *icsk = inet_csk(sk); bool has_ulp = !!icsk->icsk_ulp_data; if (has_ulp) tcp_update_ulp(sk, psock->sk_proto); else sk->sk_prot = psock->sk_proto; psock->sk_proto = NULL; }include/linux/skmsg.h +5
-0+ +if (psock->icsk_af_ops) { + icsk->icsk_af_ops = psock->icsk_af_ops; + psock->icsk_af_ops =NULL ; + }}
In restore case either
psock->icsk_af_opsis null or not. If its null below code catches it. If its not null (from init path) then we have a valid pointer.rcu_read_lock(); psock = sk_psock(sk);(quoted diff) +0
-0if (likely(psock)) { proto = psock->sk_proto; write_space = psock->saved_write_space; ops = psock->icsk_af_ops; } rcu_read_unlock(); if (!ops)ops = inet_csk(sk)->icsk_af_ops; child = ops->syn_recv_sock(sk, skb, req, dst, req_unhash, own_req);
Quoted 5 lines
We should do this with proper READ_ONCE/WRITE_ONCE to make it clear what is going on and to stop compiler from breaking these assumptions. I was going to generate that patch after this series but can do it before as well. I didn't mention it here because it seems a bit out of scope for this series because its mostly a fix to older code.
+1, looking forward to your patch. Also, as I've recently learned, that should enable KTSAN to reason about the psock code [0].
Quoted 10 lines
Also I started to think that
write_spacemight be out of sync with ops but it seems we never actually removepsock_write_spaceuntil after rcu grace period so that should be OK as well and always point to the previouswrite_space.Finally I wondered if we could remove the ops and then add it back quickly which seems at least in theory possible, but that would get hit with a grace period because we can't have conflicting psock definitions on the same sock. So expanding the rcu block to include the ops = inet_csk(sk)->icsk_af_ops would fix that case.
I see, ops = inet_csk(sk)->icsk_af_ops might read out a re-overwritten ops after sock_map_unlink, followed by sock_map_link. Ouch.
Quoted 6 lines
So in summary I think we should expand the rcu lock here to include the ops = inet_csk(sk)->icsk_af_ops to ensure we dont race with tear down and create. I'll push the necessary update with
WRITE_ONCEandREAD_ONCEto fix that up. Seeing we have to wait until the merge window opens most likely anyways I'll send those out sooner rather then later and this series can add the proper annotations as well.
Or I could leave psock->icsk_af_ops set in restore_proto, like we do for write_space as you noted. Restoring it twice doesn't seem harmful, it has no side-effects. Less state changes to think about?
I'll still have to apply what you suggest for saving psock->sk_proto, though.
Thanks,
Jakub
[0] https://github.com/google/ktsan/wiki/READ_ONCE-and-WRITE_ONCE
Jakub Sitnicki
maintainerPATCH 5/8 bpf: Allow selecting reuseport socket from a SOCKMAP
In reply to Jakub SitnickiSOCKMAP now supports storing references to listening sockets. Nothing keeps us from using it as an array of sockets to select from in SK_REUSEPORT programs.
Whitelist the map type with the BPF helper for selecting socket. However, impose a restriction that the selected socket needs to be a listening TCP socket or a bound UDP socket (connected or not).
The only other map type that works with the BPF reuseport helper, REUSEPORT_SOCKARRAY, has a corresponding check in its update operation handler.
--- kernel/bpf/verifier.c | 6 ++++-- net/core/filter.c | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-)
kernel/bpf/verifier.c +4 -2
@@ -3685,7 +3685,8 @@ static int check_map_func_compatibility(struct bpf_verifier_env *env,if (func_id != BPF_FUNC_sk_redirect_map && func_id != BPF_FUNC_sock_map_update && func_id != BPF_FUNC_map_delete_elem && - func_id != BPF_FUNC_msg_redirect_map) + func_id != BPF_FUNC_msg_redirect_map && + func_id != BPF_FUNC_sk_select_reuseport) goto error;break ;case BPF_MAP_TYPE_SOCKHASH :
@@ -3766,7 +3767,8 @@ static int check_map_func_compatibility(struct bpf_verifier_env *env, goto error;break ;case BPF_FUNC_sk_select_reuseport: -if (map->map_type !=BPF_MAP_TYPE_REUSEPORT_SOCKARRAY ) +if (map->map_type !=BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && + map->map_type !=BPF_MAP_TYPE_SOCKMAP ) goto error;break ;case BPF_FUNC_map_peek_elem:
net/core/filter.c +2 -0
@@ -8723,6 +8723,8 @@ BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, selected_sk = map->ops->map_lookup_elem (map, key);if (!selected_sk)return -ENOENT ; +if (!sock_flag (selected_sk,SOCK_RCU_FREE )) +return -EINVAL ; reuse =rcu_dereference (selected_sk->sk_reuseport_cb);if (!reuse)
Signature · 1 line
2.20.1
RE: [PATCH bpf-next 5/8] bpf: Allow selecting reuseport socket from a SOCKMAP
Quoted 8 lines · Jakub Sitnicki
SOCKMAP now supports storing references to listening sockets. Nothing keeps us from using it as an array of sockets to select from in
SK_REUSEPORTprograms.Whitelist the map type with the BPF helper for selecting socket. However, impose a restriction that the selected socket needs to be a listening TCP socket or a bound UDP socket (connected or not).
Quoted 6 lines
The only other map type that works with the BPF reuseport helper,
REUSEPORT_SOCKARRAY, has a corresponding check in its update operation handler.Signed-off-by Jakub Sitnicki <[email protected]>---
Re: [PATCH bpf-next 5/8] bpf: Allow selecting reuseport socket from a SOCKMAP
In reply to Jakub SitnickiQuoted 47 lines · Jakub Sitnicki
SOCKMAP now supports storing references to listening sockets. Nothing keeps us from using it as an array of sockets to select from in
SK_REUSEPORTprograms.Whitelist the map type with the BPF helper for selecting socket. However, impose a restriction that the selected socket needs to be a listening TCP socket or a bound UDP socket (connected or not).
The only other map type that works with the BPF reuseport helper,
REUSEPORT_SOCKARRAY, has a corresponding check in its update operation handler.Signed-off-by Jakub Sitnicki <[email protected]>--- kernel/bpf/verifier.c | 6 ++++-- net/core/filter.c | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-)kernel/bpf/verifier.c +4
-2@@ -3685,7 +3685,8 @@ static int check_map_func_compatibility(struct bpf_verifier_env *env,if (func_id != BPF_FUNC_sk_redirect_map && func_id != BPF_FUNC_sock_map_update && func_id != BPF_FUNC_map_delete_elem && - func_id != BPF_FUNC_msg_redirect_map) + func_id != BPF_FUNC_msg_redirect_map && + func_id != BPF_FUNC_sk_select_reuseport) goto error;break ;case BPF_MAP_TYPE_SOCKHASH :@@ -3766,7 +3767,8 @@ static int check_map_func_compatibility(struct bpf_verifier_env *env, goto error;break ;case BPF_FUNC_sk_select_reuseport: -if (map->map_type !=BPF_MAP_TYPE_REUSEPORT_SOCKARRAY ) +if (map->map_type !=BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && + map->map_type !=BPF_MAP_TYPE_SOCKMAP ) goto error;break ;case BPF_FUNC_map_peek_elem:net/core/filter.c +0
-0
net/core/filter.c BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, · line 8727
Quoted 5 lines
net/core/filter.c +2
-0@@ -8723,6 +8723,8 @@ BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, selected_sk = map->ops->map_lookup_elem (map, key);if (!selected_sk)return -ENOENT ; +if (!sock_flag (selected_sk,SOCK_RCU_FREE )) +return -EINVAL ;
hmm. I wonder whether this breaks existing users... Martin,
what do you think?
Could you also take a look at other patches too? In particular patch 7?
John Fastabend
maintainerRe: [PATCH bpf-next 5/8] bpf: Allow selecting reuseport socket from a SOCKMAP
Quoted 15 lines · Alexei Starovoitov
Quoted 14 lines · Jakub Sitnicki
SOCKMAP now supports storing references to listening sockets. Nothing keeps us from using it as an array of sockets to select from in
SK_REUSEPORTprograms.Whitelist the map type with the BPF helper for selecting socket. However, impose a restriction that the selected socket needs to be a listening TCP socket or a bound UDP socket (connected or not).
The only other map type that works with the BPF reuseport helper,
REUSEPORT_SOCKARRAY, has a corresponding check in its update operation handler.Signed-off-by Jakub Sitnicki <[email protected]>---
[...]
Quoted 4 lines
Quoted 4 lines
net/core/filter.c +0
-0
Quoted 8 lines
net/core/filter.c BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, · line 8727
Quoted 6 lines
net/core/filter.c +2
-0@@ -8723,6 +8723,8 @@ BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, selected_sk = map->ops->map_lookup_elem (map, key);if (!selected_sk)return -ENOENT ; +if (!sock_flag (selected_sk,SOCK_RCU_FREE )) +return -EINVAL ;hmm. I wonder whether this breaks existing users...
There is already this check in reuseport_array_update_check()
/* * sk must be hashed (i.e. listening in the TCP case or binded * in the UDP case) and * it must also be a SO_REUSEPORT sk (i.e. reuse cannot be NULL). * * Also, sk will be used in bpf helper that is protected by * rcu_read_lock(). */ if (!sock_flag(nsk, SOCK_RCU_FREE) || !sk_hashed(nsk) || !nsk_reuse) return -EINVAL;
So I believe it should not cause any problems with existing users. Perhaps we could consolidate the checks a bit or move it into the update paths if we wanted. I assume Jakub was just ensuring we don't get here with SOCK_RCU_FREE set from any of the new paths now. I'll let him answer though.
Quoted 2 lines
Martin,
what do you think?
More eyes the better.
Quoted 3 lines
Could you also take a look at other patches too?
In particular patch 7?
Agreed would be good to give 7/8 a look I'm not too familiar with the selftests there.
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 5/8] bpf: Allow selecting reuseport socket from a SOCKMAP
Quoted 45 lines · John Fastabend
Quoted 15 lines · Alexei Starovoitov
Quoted 14 lines · Jakub Sitnicki
SOCKMAP now supports storing references to listening sockets. Nothing keeps us from using it as an array of sockets to select from in
SK_REUSEPORTprograms.Whitelist the map type with the BPF helper for selecting socket. However, impose a restriction that the selected socket needs to be a listening TCP socket or a bound UDP socket (connected or not).
The only other map type that works with the BPF reuseport helper,
REUSEPORT_SOCKARRAY, has a corresponding check in its update operation handler.Signed-off-by Jakub Sitnicki <[email protected]>---
[...]
Quoted 4 lines
Quoted 4 lines
net/core/filter.c +0
-0Quoted 8 lines
net/core/filter.c BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, · line 8727
Quoted 6 lines
net/core/filter.c +2
-0@@ -8723,6 +8723,8 @@ BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, selected_sk = map->ops->map_lookup_elem (map, key);if (!selected_sk)return -ENOENT ; +if (!sock_flag (selected_sk,SOCK_RCU_FREE )) +return -EINVAL ;hmm. I wonder whether this breaks existing users...
There is already this check in
reuseport_array_update_check()/* * sk must be hashed (i.e. listening in the TCP case or binded * in the UDP case) and * it must also be a SO_REUSEPORT sk (i.e. reuse cannot be NULL). * * Also, sk will be used in bpf helper that is protected by * rcu_read_lock(). */ if (!sock_flag(nsk, SOCK_RCU_FREE) || !sk_hashed(nsk) || !nsk_reuse) return -EINVAL;
Quoted 4 lines
So I believe it should not cause any problems with existing users. Perhaps we could consolidate the checks a bit or move it into the update paths if we wanted. I assume Jakub was just ensuring we don't get here with
SOCK_RCU_FREEset from any of the new paths now. I'll let him answer though.
That was exactly my thinking here.
REUSEPORT_SOCKARRAY can't be populated with sockets that don't have SOCK_RCU_FREE set. This makes the flag check in sk_select_reuseport BPF helper redundant for this map type.
SOCKMAP, OTOH, allows storing established TCP sockets, which don't have SOCK_RCU_FREE flag and shouldn't be used as reuseport targets. The newly added check protects us against it.
I have a couple tests in the last patch for it - test_sockmap_reuseport_select_{listening,connected}. Admittedly, UDP is not covered.
Not sure how we could go about moving the checks to the update path for SOCKMAP. At update time we don't know if the map will be used with a reuseport or a sk_{skb,msg} program.
-Jakub
Quoted 12 lines
Quoted 3 lines
Martin,
what do you think?More eyes the better.
Quoted 3 lines
Could you also take a look at other patches too?
In particular patch 7?Agreed would be good to give 7/8 a look I'm not too familiar with the selftests there.
Re: [PATCH bpf-next 5/8] bpf: Allow selecting reuseport socket from a SOCKMAP
Quoted 20 lines · Jakub Sitnicki
Quoted 19 lines · John Fastabend
Quoted 15 lines · Alexei Starovoitov
Quoted 14 lines · Jakub Sitnicki
SOCKMAP now supports storing references to listening sockets. Nothing keeps us from using it as an array of sockets to select from in
SK_REUSEPORTprograms.Whitelist the map type with the BPF helper for selecting socket. However, impose a restriction that the selected socket needs to be a listening TCP socket or a bound UDP socket (connected or not).
The only other map type that works with the BPF reuseport helper,
REUSEPORT_SOCKARRAY, has a corresponding check in its update operation handler.Signed-off-by Jakub Sitnicki <[email protected]>---
[...]
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
net/core/filter.c BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, · line 8727
Quoted 10 lines
net/core/filter.c +2
-0@@ -8723,6 +8723,8 @@ BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, selected_sk = map->ops->map_lookup_elem (map, key);if (!selected_sk)return -ENOENT ; +if (!sock_flag (selected_sk,SOCK_RCU_FREE )) +return -EINVAL ;
If I read it correctly,
this is to avoid the following "if (!reuse)" to return -ENOENT, and instead returns -EINVAL for non TCP_LISTEN tcp_sock. It should at least only be done under the "if (!reuse)" then.
Checking SOCK_RCU_FREE to imply TCP_LISTEN is not ideal. It is not immediately obvious. Why not directly check TCP_LISTEN?
Note that the SOCK_RCU_FREE check at the 'slow-path' reuseport_array_update_check() is because reuseport_array does depend on call_rcu(&sk->sk_rcu,...) to work, e.g. the reuseport_array does not hold the sk_refcnt.
Quoted 31 lines
Quoted 16 lines
Quoted 2 lines
hmm. I wonder whether this breaks existing users...
There is already this check in
reuseport_array_update_check()/* * sk must be hashed (i.e. listening in the TCP case or binded * in the UDP case) and * it must also be a SO_REUSEPORT sk (i.e. reuse cannot be NULL). * * Also, sk will be used in bpf helper that is protected by * rcu_read_lock(). */ if (!sock_flag(nsk, SOCK_RCU_FREE) || !sk_hashed(nsk) || !nsk_reuse) return -EINVAL;Quoted 4 lines
So I believe it should not cause any problems with existing users. Perhaps we could consolidate the checks a bit or move it into the update paths if we wanted. I assume Jakub was just ensuring we don't get here with
SOCK_RCU_FREEset from any of the new paths now. I'll let him answer though.That was exactly my thinking here.
REUSEPORT_SOCKARRAYcan't be populated with sockets that don't haveSOCK_RCU_FREEset. This makes the flag check insk_select_reuseportBPF helper redundant for this map type.SOCKMAP, OTOH, allows storing established TCP sockets, which don't have
SOCK_RCU_FREEflag and shouldn't be used as reuseport targets. The newly added check protects us against it.
Quoted 7 lines
I have a couple tests in the last patch for it - test_sockmap_reuseport_select_{listening,connected}. Admittedly, UDP is not covered.
Not sure how we could go about moving the checks to the update path for SOCKMAP. At update time we don't know if the map will be used with a reuseport or a sk_{skb,msg} program.
or make these checks specific to the sockmap's lookup path.
digress a little from this patch,
will the upcoming patches/examples show the use case to have both TCP_LISTEN and TCP_ESTABLISHED sk in the same sock_map?
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 5/8] bpf: Allow selecting reuseport socket from a SOCKMAP
Quoted 21 lines · Martin Lau
Quoted 20 lines · Jakub Sitnicki
Quoted 19 lines · John Fastabend
Quoted 15 lines · Alexei Starovoitov
Quoted 14 lines · Jakub Sitnicki
SOCKMAP now supports storing references to listening sockets. Nothing keeps us from using it as an array of sockets to select from in
SK_REUSEPORTprograms.Whitelist the map type with the BPF helper for selecting socket. However, impose a restriction that the selected socket needs to be a listening TCP socket or a bound UDP socket (connected or not).
The only other map type that works with the BPF reuseport helper,
REUSEPORT_SOCKARRAY, has a corresponding check in its update operation handler.Signed-off-by Jakub Sitnicki <[email protected]>---
[...]
Quoted 14 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
net/core/filter.c BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, · line 8727
Quoted 10 lines
net/core/filter.c +2
-0@@ -8723,6 +8723,8 @@ BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, selected_sk = map->ops->map_lookup_elem (map, key);if (!selected_sk)return -ENOENT ; +if (!sock_flag (selected_sk,SOCK_RCU_FREE )) +return -EINVAL ;If I read it correctly,
this is to avoid the following "if (!reuse)" to return-ENOENT, and instead returns-EINVALfor nonTCP_LISTENtcp_sock. It should at least only be done under the "if (!reuse)" then.
Yes, exactly. For an established TCP socket in SOCKMAP we would get -ENOENT because sk_reuseport_cb is not set. Which is a bit confusing since the map entry exists.
Returning -EINVAL matches the REUSEPORT_SOCKARRAY update operation semantics for established TCP sockets.
But this is just about returning an informative error so you're completely right that this should be done under "if (!reuse)" branch to avoid the extra cost on the happy path.
Quoted 3 lines
Checking
SOCK_RCU_FREEto implyTCP_LISTENis not ideal. It is not immediately obvious. Why not directly checkTCP_LISTEN?
I agree, it's not obvious. When I first saw this check in reuseport_array_update_check it got me puzzled too. I should have added an explanatory comment there.
Thing is we're not matching on just TCP_LISTEN. REUSEPORT_SOCKARRAY allows selecting a connected UDP socket as a target as well. It takes some effort to set up but it's possible even if obscure.
Quoted 4 lines
Note that the
SOCK_RCU_FREEcheck at the 'slow-path'reuseport_array_update_check()is becausereuseport_arraydoes depend oncall_rcu(&sk->sk_rcu,...)to work, e.g. thereuseport_arraydoes not hold thesk_refcnt.
Oh, so it's not only about socket state like I thought.
This raises the question - does REUSEPORT_SOCKARRAY allow storing connected UDP sockets by design or is it a happy accident? It doesn't seem particularly useful.
Either way, thanks for the explanation.
Quoted 36 lines
Quoted 36 lines
Quoted 17 lines
Quoted 3 lines
hmm. I wonder whether this breaks existing users...
There is already this check in
reuseport_array_update_check()/* * sk must be hashed (i.e. listening in the TCP case or binded * in the UDP case) and * it must also be a SO_REUSEPORT sk (i.e. reuse cannot be NULL). * * Also, sk will be used in bpf helper that is protected by * rcu_read_lock(). */ if (!sock_flag(nsk, SOCK_RCU_FREE) || !sk_hashed(nsk) || !nsk_reuse) return -EINVAL;Quoted 4 lines
So I believe it should not cause any problems with existing users. Perhaps we could consolidate the checks a bit or move it into the update paths if we wanted. I assume Jakub was just ensuring we don't get here with
SOCK_RCU_FREEset from any of the new paths now. I'll let him answer though.That was exactly my thinking here.
REUSEPORT_SOCKARRAYcan't be populated with sockets that don't haveSOCK_RCU_FREEset. This makes the flag check insk_select_reuseportBPF helper redundant for this map type.SOCKMAP, OTOH, allows storing established TCP sockets, which don't have
SOCK_RCU_FREEflag and shouldn't be used as reuseport targets. The newly added check protects us against it.I have a couple tests in the last patch for it - test_sockmap_reuseport_select_{listening,connected}. Admittedly, UDP is not covered.
Quoted 8 lines
Quoted 3 lines
Not sure how we could go about moving the checks to the update path for SOCKMAP. At update time we don't know if the map will be used with a reuseport or a sk_{skb,msg} program.
or make these checks specific to the sockmap's lookup path.
digress a little from this patch,
will the upcoming patches/examples show the use case to have bothTCP_LISTENandTCP_ESTABLISHEDsk in the samesock_map?
No, we have no use for a map instance that mixes listening and established TCP sockets that I know of.
I'm guessing you would like to avoid adding a new check on the fast-path (at socket selection time) by filering out sockets in invalid state on map update, like SOCKARRAY does.
I could imagine setting a flag at map creation time to put SOCKMAP in a a certain mode. Storing just listening or just established sockets.
OTOH why restrict the user? If you are okay with not adding extra checks on the happy path in sk_select_reuseport, I would opt for that.
Thanks,
Jakub
Re: [PATCH bpf-next 5/8] bpf: Allow selecting reuseport socket from a SOCKMAP
Quoted 52 lines · Jakub Sitnicki
Quoted 21 lines · Martin Lau
Quoted 20 lines · Jakub Sitnicki
Quoted 19 lines · John Fastabend
Quoted 15 lines · Alexei Starovoitov
Quoted 14 lines · Jakub Sitnicki
SOCKMAP now supports storing references to listening sockets. Nothing keeps us from using it as an array of sockets to select from in
SK_REUSEPORTprograms.Whitelist the map type with the BPF helper for selecting socket. However, impose a restriction that the selected socket needs to be a listening TCP socket or a bound UDP socket (connected or not).
The only other map type that works with the BPF reuseport helper,
REUSEPORT_SOCKARRAY, has a corresponding check in its update operation handler.Signed-off-by Jakub Sitnicki <[email protected]>---
[...]
Quoted 14 lines
Quoted 10 lines
Quoted 10 lines
Quoted 10 lines
net/core/filter.c BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, · line 8727
Quoted 10 lines
net/core/filter.c +2
-0@@ -8723,6 +8723,8 @@ BPF_CALL_4(sk_select_reuseport, struct sk_reuseport_kern *, reuse_kern, selected_sk = map->ops->map_lookup_elem (map, key);if (!selected_sk)return -ENOENT ; +if (!sock_flag (selected_sk,SOCK_RCU_FREE )) +return -EINVAL ;If I read it correctly,
this is to avoid the following "if (!reuse)" to return-ENOENT, and instead returns-EINVALfor nonTCP_LISTENtcp_sock. It should at least only be done under the "if (!reuse)" then.Yes, exactly. For an established TCP socket in SOCKMAP we would get
-ENOENTbecausesk_reuseport_cbis not set. Which is a bit confusing since the map entry exists.Returning
-EINVALmatches theREUSEPORT_SOCKARRAYupdate operation semantics for established TCP sockets.But this is just about returning an informative error so you're completely right that this should be done under "if (!reuse)" branch to avoid the extra cost on the happy path.
Quoted 3 lines
Checking
SOCK_RCU_FREEto implyTCP_LISTENis not ideal. It is not immediately obvious. Why not directly checkTCP_LISTEN?
Quoted 7 lines
I agree, it's not obvious. When I first saw this check in
reuseport_array_update_checkit got me puzzled too. I should have added an explanatory comment there.Thing is we're not matching on just
TCP_LISTEN.REUSEPORT_SOCKARRAYallows selecting a connected UDP socket as a target as well. It takes some effort to set up but it's possible even if obscure.
How about this instead:
if (!reuse)
/* reuseport_array only has sk that has non NULL sk_reuseport_cb.
* The only (!reuse) case here is, the sk has already been removed from
* reuseport_array, so treat it as -ENOENT.
*
* Other maps (e.g. sock_map) do not provide this guarantee and the sk may
* never be in the reuseport to begin with.
*/
return map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY ? -ENOENT : -EINVAL;
Quoted 11 lines
Quoted 5 lines
Note that the
SOCK_RCU_FREEcheck at the 'slow-path'reuseport_array_update_check()is becausereuseport_arraydoes depend oncall_rcu(&sk->sk_rcu,...)to work, e.g. thereuseport_arraydoes not hold thesk_refcnt.Oh, so it's not only about socket state like I thought.
This raises the question - does
REUSEPORT_SOCKARRAYallow storing connected UDP sockets by design or is it a happy accident? It doesn't seem particularly useful.
Not by design/accident on the REUSEPORT_SOCKARRAY side ;)
The intention of REUSEPORT_SOCKARRAY is to allow sk that can be added to reuse->socks[].
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 5/8] bpf: Allow selecting reuseport socket from a SOCKMAP
Quoted 3 lines · Martin Lau
Quoted 2 lines · Jakub Sitnicki
Quoted 1 line · Martin Lau
On Mon, Nov 25, 2019 at 11:40:41AM +0100, Jakub Sitnicki wrote:
[...]
Quoted 7 lines
Quoted 7 lines
I agree, it's not obvious. When I first saw this check in
reuseport_array_update_checkit got me puzzled too. I should have added an explanatory comment there.Thing is we're not matching on just
TCP_LISTEN.REUSEPORT_SOCKARRAYallows selecting a connected UDP socket as a target as well. It takes some effort to set up but it's possible even if obscure.
Quoted 10 lines
How about this instead:
if (!reuse)
/*reuseport_arrayonly has sk that has non NULLsk_reuseport_cb.
* The only (!reuse) case here is, the sk has already been removed from
*reuseport_array, so treat it as-ENOENT.
*
* Other maps (e.g.sock_map) do not provide this guarantee and the sk may
* never be in the reuseport to begin with.
*/
returnmap->map_type==BPF_MAP_TYPE_REUSEPORT_SOCKARRAY?-ENOENT:-EINVAL;
Right, apart from established TCP sockets we must not select a listening socket that's not in a reuseport group either. This covers both cases. Clever. Thanks for the suggestion.
Quoted 9 lines
Quoted 9 lines
Quoted 6 lines
Note that the
SOCK_RCU_FREEcheck at the 'slow-path'reuseport_array_update_check()is becausereuseport_arraydoes depend oncall_rcu(&sk->sk_rcu,...)to work, e.g. thereuseport_arraydoes not hold thesk_refcnt.Oh, so it's not only about socket state like I thought.
Quoted 7 lines
Quoted 3 lines
This raises the question - does
REUSEPORT_SOCKARRAYallow storing connected UDP sockets by design or is it a happy accident? It doesn't seem particularly useful.Not by design/accident on the
REUSEPORT_SOCKARRAYside ;)The intention of
REUSEPORT_SOCKARRAYis to allow sk that can be added to reuse->socks[].
Ah, makes sense. REUSEPORT_SOCKARRAY had to mimic reuseport groups.
-Jakub
Jakub Sitnicki
maintainerPATCH 6/8 libbpf: Recognize SK_REUSEPORT programs from section name
In reply to Jakub SitnickiAllow loading BPF object files that contain SK_REUSEPORT programs without having to manually set the program type before load if the the section name is set to "sk_reuseport".
Makes user-space code needed to load SK_REUSEPORT BPF program more concise.
--- tools/lib/bpf/libbpf.c | 1 + 1 file changed, 1 insertion(+)
tools/lib/bpf/libbpf.c +1 -0
@@ -4987,6 +4987,7 @@ static const struct {enum bpf_attach_type attach_type; } section_names[] = {BPF_PROG_SEC ("socket" ,BPF_PROG_TYPE_SOCKET_FILTER ), +BPF_PROG_SEC ("sk_reuseport" ,BPF_PROG_TYPE_SK_REUSEPORT ),BPF_PROG_SEC ("kprobe/" ,BPF_PROG_TYPE_KPROBE ),BPF_PROG_SEC ("uprobe/" ,BPF_PROG_TYPE_KPROBE ), BPF_PROG_SEC("kretprobe/", BPF_PROG_TYPE_KPROBE),
Signature · 1 line
2.20.1
RE: [PATCH bpf-next 6/8] libbpf: Recognize SK_REUSEPORT programs from section name
Quoted 8 lines · Jakub Sitnicki
Allow loading BPF object files that contain
SK_REUSEPORTprograms without having to manually set the program type before load if the the section name is set to "sk_reuseport".Makes user-space code needed to load
SK_REUSEPORTBPF program more concise.Signed-off-by Jakub Sitnicki <[email protected]>---
Jakub Sitnicki
maintainerPATCH 7/8 selftests/bpf: Extend SK_REUSEPORT tests to cover SOCKMAP
In reply to Jakub SitnickiParametrize the SK_REUSEPORT tests so that the map type for storing sockets can be selected at run-time. Also allow choosing which L4 protocols get tested.
Run the extended reuseport program test two times, once for REUSEPORT_ARRAY, and once for SOCKMAP but just with TCP to cover the newly enabled map type.
--- tools/testing/selftests/bpf/Makefile | 7 +- .../selftests/bpf/test_select_reuseport.c | 141 ++++++++++++++---- .../selftests/bpf/test_select_reuseport.sh | 14 ++ 3 files changed, 131 insertions(+), 31 deletions(-) create mode 100755 tools/testing/selftests/bpf/test_select_reuseport.sh
tools/testing/selftests/bpf/Makefile +4 -3
@@ -28,7 +28,7 @@ LDLIBS += -lcap -lelf -lrt -lpthread TEST_GEN_PROGS = test_verifier test_tag test_maps test_lru_map test_lpm_map test_progs \ test_align test_verifier_log test_dev_cgroup test_tcpbpf_user \ test_sock test_btf test_sockmap get_cgroup_id_user test_socket_cookie \ - test_cgroup_storage test_select_reuseport \ + test_cgroup_storage \ test_netcnt test_tcpnotify_user test_sock_fields test_sysctl test_hashmap \ test_cgroup_attach test_progs-no_alu32
@@ -60,7 +60,8 @@ TEST_PROGS := test_kmod.sh \ test_tc_tunnel.sh \ test_tc_edt.sh \ test_xdping.sh \ - test_bpftool_build.sh + test_bpftool_build.sh \ + test_select_reuseport.sh TEST_PROGS_EXTENDED := with_addr.sh \ with_tunnels.sh \
@@ -71,7 +72,7 @@ TEST_PROGS_EXTENDED := with_addr.sh \ # Compile but not part of 'make run_tests' TEST_GEN_PROGS_EXTENDED = test_sock_addr test_skb_cgroup_id_user \ flow_dissector_load test_flow_dissector test_tcp_check_syncookie_user \ - test_lirc_mode2_user xdping + test_lirc_mode2_user xdping test_select_reuseport TEST_CUSTOM_PROGS = urandom_read
tools/testing/selftests/bpf/test_select_reuseport.c +113 -28
185 lines not on this page · raw message
tools/testing/selftests/bpf/test_select_reuseport.sh new file +14 -0
@@ -0,0 +1,14 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 + +set -eu + +DIR=$(dirname $0) + +echo "Testing reuseport with REUSEPORT_SOCKARRAY..." +$DIR/test_select_reuseport -m reuseport_sockarray + +echo "Testing reuseport with SOCKMAP (TCP only)..." +$DIR/test_select_reuseport -m sockmap -t + +exit 0
Signature · 1 line
2.20.1
RE: [PATCH bpf-next 7/8] selftests/bpf: Extend SK_REUSEPORT tests to cover SOCKMAP
Quoted 10 lines · Jakub Sitnicki
Parametrize the
SK_REUSEPORTtests so that the map type for storing sockets can be selected at run-time. Also allow choosing which L4 protocols get tested.Run the extended reuseport program test two times, once for
REUSEPORT_ARRAY, and once for SOCKMAP but just with TCP to cover the newly enabled map type.Signed-off-by Jakub Sitnicki <[email protected]>---
Re: [PATCH bpf-next 7/8] selftests/bpf: Extend SK_REUSEPORT tests to cover SOCKMAP
In reply to Jakub SitnickiQuoted 3 lines · Jakub Sitnicki
Parametrize the
SK_REUSEPORTtests so that the map type for storing sockets can be selected at run-time. Also allow choosing which L4 protocols get tested.
If new cmdline args are added to select different subtests,
I would prefer to move it to the test_progs framework and reuse the subtests support in test_progs commit 3a516a0a3a7b ("selftests/bpf: add sub-tests support for test_progs"). Its default is to run all instead of having a separate bash script to
do that.
Quoted 6 lines
Run the extended reuseport program test two times, once for
REUSEPORT_ARRAY, and once for SOCKMAP but just with TCP to cover the newly enabled map type.Signed-off-by Jakub Sitnicki <[email protected]>
[ ... ]
Quoted 13 lines
tools/testing/selftests/bpf/test_select_reuseport.c +13
-0+static const char *family_to_str (int family) +{ +switch (family) { +case AF_INET : +return "IPv4" ; +case AF_INET6 : +return "IPv6" ; +default : +return "unknown" ; + } +} + +static const char *type_to_str (int type)
tools/testing/selftests/bpf/test_select_reuseport.c static void cleanup(void) · line 712
Quoted 10 lines
tools/testing/selftests/bpf/test_select_reuseport.c +10
-0+{ +switch (type) { +case SOCK_STREAM : +return "TCP" ; +case SOCK_DGRAM : +return "UDP" ; +default : +return "unknown" ; + } +}
+1
[ ... ]
Quoted 58 lines
tools/testing/selftests/bpf/test_select_reuseport.c +26
-1+static void parse_opts (int argc,char **argv) +{ +unsigned int sock_types =0 ; +int c; + +while ((c =getopt (argc, argv,"hm:tu" )) !=-1 ) { +switch (c) { +case 'h' : +usage (); +break ; +case 'm' : + cfg_map_type =parse_map_type (optarg); +break ; +case 't' : + sock_types |=1 <<SOCK_STREAM ; +break ; +case 'u' : + sock_types |=1 <<SOCK_DGRAM ; +break ; } } + +if (cfg_map_type ==BPF_MAP_TYPE_UNSPEC ) +usage (); +if (sock_types !=0 ) + cfg_sock_types = sock_types; } -int main (int argc,const char **argv) +int main (int argc,char **argv) { +parse_opts (argc, argv);create_maps ();prepare_bpf_obj (); saved_tcp_fo =read_int_sysctl (TCP_FO_SYSCTL );tools/testing/selftests/bpf/test_select_reuseport.sh new file +14
-0@@ -0,0 +1,14 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 + +set -eu + +DIR=$(dirname $0) + +echo "Testing reuseport with REUSEPORT_SOCKARRAY..." +$DIR/test_select_reuseport -m reuseport_sockarray + +echo "Testing reuseport with SOCKMAP (TCP only)..." +$DIR/test_select_reuseport -m sockmap -t + +exit 0Signature · 1 line
2.20.1
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 7/8] selftests/bpf: Extend SK_REUSEPORT tests to cover SOCKMAP
Quoted 9 lines · Martin Lau
Quoted 3 lines · Jakub Sitnicki
Parametrize the
SK_REUSEPORTtests so that the map type for storing sockets can be selected at run-time. Also allow choosing which L4 protocols get tested.If new cmdline args are added to select different subtests,
I would prefer to move it to thetest_progsframework and reuse the subtests support intest_progscommit3a516a0a3a7b("selftests/bpf: add sub-tests support fortest_progs"). Its default is to run all instead of having a separate bash script to
do that.
Great idea. Let me convert these tests and the newly added ones to test_progs framework.
-Jakub
Jakub Sitnicki
maintainerRe: [PATCH bpf-next 7/8] selftests/bpf: Extend SK_REUSEPORT tests to cover SOCKMAP
In reply to Martin LauQuoted 9 lines · Martin Lau
Quoted 3 lines · Jakub Sitnicki
Parametrize the
SK_REUSEPORTtests so that the map type for storing sockets can be selected at run-time. Also allow choosing which L4 protocols get tested.If new cmdline args are added to select different subtests,
I would prefer to move it to thetest_progsframework and reuse the subtests support intest_progscommit3a516a0a3a7b("selftests/bpf: add sub-tests support fortest_progs"). Its default is to run all instead of having a separate bash script to
do that.
This turned out to be more work than I expected, so I've split it out into a separate series:
https://lore.kernel.org/bpf/[email protected]/T/#t
Thanks,
Jakub
Jakub Sitnicki
maintainerPATCH 8/8 selftests/bpf: Tests for SOCKMAP holding listening sockets
In reply to Jakub SitnickiNow that SOCKMAP can store listening sockets, its user-space and BPF API is open to a new set of potential pitfalls. Exercise the map operations, code paths that trigger overridden socket callbacks, and BPF helpers that work with SOCKMAP to gain confidence that all works as expected.
--- tools/testing/selftests/bpf/.gitignore | 1 + tools/testing/selftests/bpf/Makefile | 2 +- .../bpf/progs/test_sockmap_listen_kern.c | 75 ++ .../selftests/bpf/test_sockmap_listen.c | 820 ++++++++++++++++++ 4 files changed, 897 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/bpf/progs/test_sockmap_listen_kern.c create mode 100644 tools/testing/selftests/bpf/test_sockmap_listen.c
tools/testing/selftests/bpf/.gitignore +1 -0
@@ -39,3 +39,4 @@ test_btf_dump xdping /no_alu32 /bpf_gcc +test_sockmap_listen
tools/testing/selftests/bpf/Makefile +1 -1
@@ -30,7 +30,7 @@ TEST_GEN_PROGS = test_verifier test_tag test_maps test_lru_map test_lpm_map test test_sock test_btf test_sockmap get_cgroup_id_user test_socket_cookie \ test_cgroup_storage \ test_netcnt test_tcpnotify_user test_sock_fields test_sysctl test_hashmap \ - test_cgroup_attach test_progs-no_alu32 + test_cgroup_attach test_progs-no_alu32 test_sockmap_listen # Also test bpf-gcc, if present ifneq ($(BPF_GCC),)
tools/testing/selftests/bpf/progs/test_sockmap_listen_kern.c new file +75 -0
75 lines not on this page · raw message
tools/testing/selftests/bpf/test_sockmap_listen.c new file +820 -0
820 lines not on this page · raw message
Signature · 1 line
2.20.1
RE: [PATCH bpf-next 8/8] selftests/bpf: Tests for SOCKMAP holding listening sockets
Quoted 7 lines · Jakub Sitnicki
Now that SOCKMAP can store listening sockets, its user-space and BPF API is open to a new set of potential pitfalls. Exercise the map operations, code paths that trigger overridden socket callbacks, and BPF helpers that work with SOCKMAP to gain confidence that all works as expected.
Signed-off-by Jakub Sitnicki <[email protected]>---
John Fastabend
maintainerQuoted 13 lines · Jakub Sitnicki
This patch set makes SOCKMAP more flexible by allowing it to hold TCP sockets that are either in established or listening state. With it SOCKMAP can act as a drop-in replacement for
REUSEPORT_SOCKARRAYwhich reuseport BPF programs use. Granted, it is limited to only TCP sockets.The idea started out at LPC '19 as feedback from John Fastabend to our troubles with repurposing
REUSEPORT_SOCKARRAYas a collection of listening sockets accessed by a BPF program ran on socket lookup [1]. Without going into details,REUSEPORT_SOCKARRAYproved to be tightly coupled with reuseport logic. Talk from LPC (see slides [2] or video [3]) highlights what problems we ran into when trying to makeREUSEPORT_SOCKARRAYwork for our use-case.
Quoted 5 lines
Patches have evolved quite a bit since the RFC series from a month ago [4]. To recap the RFC feedback, John pointed out that BPF redirect helpers for SOCKMAP need sane semantics when used with listening sockets [5], and that SOCKMAP lookup from BPF would be useful [6]. While Martin asked for UDP support [7].
Curious if you've started looking into UDP support. I had hoped to do it but haven't got there yet.
Quoted 5 lines
As it happens, patches needed more work to get SOCKMAP to actually behave correctly with listening sockets. It turns out flexibility has its price. Change log below outlines them all.
But looks pretty clean to me, only major change here is to add an extra hook to remove psock from the child socket. And that looks fine to me and cleaner than any other solution I had in mind.
Changes +/- looks good as well most the updates are in selftests to update tests and add some new ones. +1
Quoted 6 lines
With more than I would like patches in the set, I left the new features, lookup from BPF as well as UDP support, for another series. I'm quite happy with how the changes turned out and the test coverage so I'm boldly proposing it as v1 :-)
Curious to see what you think.
Ack on the series from me.
Quoted 66 lines
RFC -> v1:
- Switch from overriding
proto->accepttoaf_ops->syn_recv_sock, which happens earlier. Clearing the psock state afteraccept()does not work for child sockets that become orphaned (never got accepted). v4-mapped sockets need special care.- Return the socket cookie on SOCKMAP lookup from syscall to be on par with
REUSEPORT_SOCKARRAY. Requires SOCKMAP to take u64 on lookup/update from syscall.- Make
bpf_sk_redirect_map(ingress) andbpf_msg_redirect_map(egress) SOCKMAP helpers fail when target socket is a listening one.- Make
bpf_sk_select_reuseporthelper fail when target is a TCP established socket.- Teach libbpf to recognize
SK_REUSEPORTprogram type from section name.- Add a dedicated set of tests for SOCKMAP holding listening sockets, covering map operations, overridden socket callbacks, and BPF helpers.
Thanks,
Jakub[1] https://lore.kernel.org/bpf/[email protected]/
[2] https://linuxplumbersconf.org/event/4/contributions/487/
[3] https://www.youtube.com/watch?v=qRDoUpqvYjY
[4] https://lore.kernel.org/bpf/[email protected]/
[5] https://lore.kernel.org/bpf/[email protected]/
[6] https://lore.kernel.org/bpf/[email protected]/
[7] https://lore.kernel.org/bpf/20191028213804.yv3xfjjlayfghkcr@kafai-mbp/Jakub Sitnicki (8):
bpf, sockmap: Return socket cookie on lookup from syscall bpf, sockmap: Let all kernel-land lookup values in SOCKMAP bpf, sockmap: Allow inserting listening TCP sockets into SOCKMAP bpf, sockmap: Don't let child socket inherit psock or its ops on copy
bpf: Allow selecting reuseport socket from a SOCKMAP
libbpf: RecognizeSK_REUSEPORTprograms from section name selftests/bpf: ExtendSK_REUSEPORTtests to cover SOCKMAP selftests/bpf: Tests for SOCKMAP holding listening socketsinclude/linux/skmsg.h | 17 +- kernel/bpf/verifier.c | 6 +- net/core/filter.c | 2 + net/core/sock_map.c | 68 +- net/ipv4/tcp_bpf.c | 66 +- tools/lib/bpf/libbpf.c | 1 + tools/testing/selftests/bpf/.gitignore | 1 + tools/testing/selftests/bpf/Makefile | 9 +- .../bpf/progs/test_sockmap_listen_kern.c | 75 ++ tools/testing/selftests/bpf/test_maps.c | 6 +- .../selftests/bpf/test_select_reuseport.c | 141 ++- .../selftests/bpf/test_select_reuseport.sh | 14 + .../selftests/bpf/test_sockmap_listen.c | 820 ++++++++++++++++++ 13 files changed, 1170 insertions(+), 56 deletions(-) create mode 100644 tools/testing/selftests/bpf/progs/test_sockmap_listen_kern.c create mode 100755 tools/testing/selftests/bpf/test_select_reuseport.sh create mode 100644 tools/testing/selftests/bpf/test_sockmap_listen.cSignature · 1 line
2.20.1
Jakub Sitnicki
maintainerQuoted 14 lines · John Fastabend
Quoted 13 lines · Jakub Sitnicki
This patch set makes SOCKMAP more flexible by allowing it to hold TCP sockets that are either in established or listening state. With it SOCKMAP can act as a drop-in replacement for
REUSEPORT_SOCKARRAYwhich reuseport BPF programs use. Granted, it is limited to only TCP sockets.The idea started out at LPC '19 as feedback from John Fastabend to our troubles with repurposing
REUSEPORT_SOCKARRAYas a collection of listening sockets accessed by a BPF program ran on socket lookup [1]. Without going into details,REUSEPORT_SOCKARRAYproved to be tightly coupled with reuseport logic. Talk from LPC (see slides [2] or video [3]) highlights what problems we ran into when trying to makeREUSEPORT_SOCKARRAYwork for our use-case.
Quoted 8 lines
Quoted 5 lines
Patches have evolved quite a bit since the RFC series from a month ago [4]. To recap the RFC feedback, John pointed out that BPF redirect helpers for SOCKMAP need sane semantics when used with listening sockets [5], and that SOCKMAP lookup from BPF would be useful [6]. While Martin asked for UDP support [7].
Curious if you've started looking into UDP support. I had hoped to do it but haven't got there yet.
No, not yet. I only made sure the newly added tests were easy to modify to cover UDP by not hard-coding the socket type.
I expect to break ground with UDP work soon, though. Right after I push out another iteration of programmable socket lookup [1] patches adapted for SOCKMAP, which we've been testing internally.
Quoted 11 lines
Quoted 4 lines
As it happens, patches needed more work to get SOCKMAP to actually behave correctly with listening sockets. It turns out flexibility has its price. Change log below outlines them all.
But looks pretty clean to me, only major change here is to add an extra hook to remove psock from the child socket. And that looks fine to me and cleaner than any other solution I had in mind.
Changes +/- looks good as well most the updates are in selftests to update tests and add some new ones. +1
Thanks for taking a look at the patches so quickly. I appreciate it.
-Jakub