1 /* Copyright (c) 2017 Covalent IO, Inc. http://covalent.io
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of version 2 of the GNU General Public
5 * License as published by the Free Software Foundation.
7 * This program is distributed in the hope that it will be useful, but
8 * WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * General Public License for more details.
13 /* A BPF sock_map is used to store sock objects. This is primarly used
14 * for doing socket redirect with BPF helper routines.
16 * A sock map may have BPF programs attached to it, currently a program
17 * used to parse packets and a program to provide a verdict and redirect
18 * decision on the packet are supported. Any programs attached to a sock
19 * map are inherited by sock objects when they are added to the map. If
20 * no BPF programs are attached the sock object may only be used for sock
23 * A sock object may be in multiple maps, but can only inherit a single
24 * parse or verdict program. If adding a sock object to a map would result
25 * in having multiple parsing programs the update will return an EBUSY error.
27 * For reference this program is similar to devmap used in XDP context
28 * reviewing these together may be useful. For an example please review
29 * ./samples/bpf/sockmap/.
31 #include <linux/bpf.h>
33 #include <linux/filter.h>
34 #include <linux/errno.h>
35 #include <linux/file.h>
36 #include <linux/kernel.h>
37 #include <linux/net.h>
38 #include <linux/skbuff.h>
39 #include <linux/workqueue.h>
40 #include <linux/list.h>
42 #include <net/strparser.h>
44 #include <linux/ptr_ring.h>
45 #include <net/inet_common.h>
46 #include <linux/sched/signal.h>
48 #define SOCK_CREATE_FLAG_MASK \
49 (BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY)
51 struct bpf_sock_progs {
52 struct bpf_prog *bpf_tx_msg;
53 struct bpf_prog *bpf_parse;
54 struct bpf_prog *bpf_verdict;
59 struct sock **sock_map;
60 struct bpf_sock_progs progs;
64 struct hlist_head head;
70 struct bucket *buckets;
74 struct bpf_sock_progs progs;
80 struct hlist_node hash_node;
86 enum smap_psock_state {
90 struct smap_psock_map_entry {
91 struct list_head list;
93 struct htab_elem __rcu *hash_link;
94 struct bpf_htab __rcu *htab;
101 /* datapath variables */
102 struct sk_buff_head rxqueue;
105 /* datapath error path cache across tx work invocations */
108 struct sk_buff *save_skb;
110 /* datapath variables for tx_msg ULP */
111 struct sock *sk_redir;
116 struct sk_msg_buff *cork;
117 struct list_head ingress;
119 struct strparser strp;
120 struct bpf_prog *bpf_tx_msg;
121 struct bpf_prog *bpf_parse;
122 struct bpf_prog *bpf_verdict;
123 struct list_head maps;
124 spinlock_t maps_lock;
126 /* Back reference used when sock callback trigger sockmap operations */
130 struct work_struct tx_work;
131 struct work_struct gc_work;
133 struct proto *sk_proto;
134 void (*save_close)(struct sock *sk, long timeout);
135 void (*save_data_ready)(struct sock *sk);
136 void (*save_write_space)(struct sock *sk);
139 static void smap_release_sock(struct smap_psock *psock, struct sock *sock);
140 static int bpf_tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
141 int nonblock, int flags, int *addr_len);
142 static int bpf_tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size);
143 static int bpf_tcp_sendpage(struct sock *sk, struct page *page,
144 int offset, size_t size, int flags);
145 static void bpf_tcp_close(struct sock *sk, long timeout);
147 static inline struct smap_psock *smap_psock_sk(const struct sock *sk)
149 return rcu_dereference_sk_user_data(sk);
152 static bool bpf_tcp_stream_read(const struct sock *sk)
154 struct smap_psock *psock;
158 psock = smap_psock_sk(sk);
159 if (unlikely(!psock))
161 empty = list_empty(&psock->ingress);
179 static struct proto *saved_tcpv6_prot __read_mostly;
180 static DEFINE_SPINLOCK(tcpv6_prot_lock);
181 static struct proto bpf_tcp_prots[SOCKMAP_NUM_PROTS][SOCKMAP_NUM_CONFIGS];
182 static void build_protos(struct proto prot[SOCKMAP_NUM_CONFIGS],
185 prot[SOCKMAP_BASE] = *base;
186 prot[SOCKMAP_BASE].close = bpf_tcp_close;
187 prot[SOCKMAP_BASE].recvmsg = bpf_tcp_recvmsg;
188 prot[SOCKMAP_BASE].stream_memory_read = bpf_tcp_stream_read;
190 prot[SOCKMAP_TX] = prot[SOCKMAP_BASE];
191 prot[SOCKMAP_TX].sendmsg = bpf_tcp_sendmsg;
192 prot[SOCKMAP_TX].sendpage = bpf_tcp_sendpage;
195 static void update_sk_prot(struct sock *sk, struct smap_psock *psock)
197 int family = sk->sk_family == AF_INET6 ? SOCKMAP_IPV6 : SOCKMAP_IPV4;
198 int conf = psock->bpf_tx_msg ? SOCKMAP_TX : SOCKMAP_BASE;
200 sk->sk_prot = &bpf_tcp_prots[family][conf];
203 static int bpf_tcp_init(struct sock *sk)
205 struct smap_psock *psock;
208 psock = smap_psock_sk(sk);
209 if (unlikely(!psock)) {
214 if (unlikely(psock->sk_proto)) {
219 psock->save_close = sk->sk_prot->close;
220 psock->sk_proto = sk->sk_prot;
222 /* Build IPv6 sockmap whenever the address of tcpv6_prot changes */
223 if (sk->sk_family == AF_INET6 &&
224 unlikely(sk->sk_prot != smp_load_acquire(&saved_tcpv6_prot))) {
225 spin_lock_bh(&tcpv6_prot_lock);
226 if (likely(sk->sk_prot != saved_tcpv6_prot)) {
227 build_protos(bpf_tcp_prots[SOCKMAP_IPV6], sk->sk_prot);
228 smp_store_release(&saved_tcpv6_prot, sk->sk_prot);
230 spin_unlock_bh(&tcpv6_prot_lock);
232 update_sk_prot(sk, psock);
237 static void smap_release_sock(struct smap_psock *psock, struct sock *sock);
238 static int free_start_sg(struct sock *sk, struct sk_msg_buff *md);
240 static void bpf_tcp_release(struct sock *sk)
242 struct smap_psock *psock;
245 psock = smap_psock_sk(sk);
246 if (unlikely(!psock))
250 free_start_sg(psock->sock, psock->cork);
255 if (psock->sk_proto) {
256 sk->sk_prot = psock->sk_proto;
257 psock->sk_proto = NULL;
263 static struct htab_elem *lookup_elem_raw(struct hlist_head *head,
264 u32 hash, void *key, u32 key_size)
268 hlist_for_each_entry_rcu(l, head, hash_node) {
269 if (l->hash == hash && !memcmp(&l->key, key, key_size))
276 static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash)
278 return &htab->buckets[hash & (htab->n_buckets - 1)];
281 static inline struct hlist_head *select_bucket(struct bpf_htab *htab, u32 hash)
283 return &__select_bucket(htab, hash)->head;
286 static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l)
288 atomic_dec(&htab->count);
292 static struct smap_psock_map_entry *psock_map_pop(struct sock *sk,
293 struct smap_psock *psock)
295 struct smap_psock_map_entry *e;
297 spin_lock_bh(&psock->maps_lock);
298 e = list_first_entry_or_null(&psock->maps,
299 struct smap_psock_map_entry,
303 spin_unlock_bh(&psock->maps_lock);
307 static void bpf_tcp_close(struct sock *sk, long timeout)
309 void (*close_fun)(struct sock *sk, long timeout);
310 struct smap_psock_map_entry *e;
311 struct sk_msg_buff *md, *mtmp;
312 struct smap_psock *psock;
317 psock = smap_psock_sk(sk);
318 if (unlikely(!psock)) {
321 return sk->sk_prot->close(sk, timeout);
324 /* The psock may be destroyed anytime after exiting the RCU critial
325 * section so by the time we use close_fun the psock may no longer
326 * be valid. However, bpf_tcp_close is called with the sock lock
327 * held so the close hook and sk are still valid.
329 close_fun = psock->save_close;
332 free_start_sg(psock->sock, psock->cork);
337 list_for_each_entry_safe(md, mtmp, &psock->ingress, list) {
339 free_start_sg(psock->sock, md);
343 e = psock_map_pop(sk, psock);
346 osk = cmpxchg(e->entry, sk, NULL);
348 smap_release_sock(psock, sk);
351 struct htab_elem *link = rcu_dereference(e->hash_link);
352 struct bpf_htab *htab = rcu_dereference(e->htab);
353 struct hlist_head *head;
357 b = __select_bucket(htab, link->hash);
359 raw_spin_lock_bh(&b->lock);
360 l = lookup_elem_raw(head,
361 link->hash, link->key,
363 /* If another thread deleted this object skip deletion.
364 * The refcnt on psock may or may not be zero.
367 hlist_del_rcu(&link->hash_node);
368 smap_release_sock(psock, link->sk);
369 free_htab_elem(htab, link);
371 raw_spin_unlock_bh(&b->lock);
373 e = psock_map_pop(sk, psock);
377 close_fun(sk, timeout);
387 static struct tcp_ulp_ops bpf_tcp_ulp_ops __read_mostly = {
390 .user_visible = false,
392 .init = bpf_tcp_init,
393 .release = bpf_tcp_release,
396 static int memcopy_from_iter(struct sock *sk,
397 struct sk_msg_buff *md,
398 struct iov_iter *from, int bytes)
400 struct scatterlist *sg = md->sg_data;
401 int i = md->sg_curr, rc = -ENOSPC;
407 if (md->sg_copybreak >= sg[i].length) {
408 md->sg_copybreak = 0;
410 if (++i == MAX_SKB_FRAGS)
417 copy = sg[i].length - md->sg_copybreak;
418 to = sg_virt(&sg[i]) + md->sg_copybreak;
419 md->sg_copybreak += copy;
421 if (sk->sk_route_caps & NETIF_F_NOCACHE_COPY)
422 rc = copy_from_iter_nocache(to, copy, from);
424 rc = copy_from_iter(to, copy, from);
435 md->sg_copybreak = 0;
436 if (++i == MAX_SKB_FRAGS)
438 } while (i != md->sg_end);
444 static int bpf_tcp_push(struct sock *sk, int apply_bytes,
445 struct sk_msg_buff *md,
446 int flags, bool uncharge)
448 bool apply = apply_bytes;
449 struct scatterlist *sg;
455 sg = md->sg_data + md->sg_start;
456 size = (apply && apply_bytes < sg->length) ?
457 apply_bytes : sg->length;
460 tcp_rate_check_app_limited(sk);
463 ret = do_tcp_sendpages(sk, p, offset, size, flags);
474 sk_mem_uncharge(sk, ret);
486 sk_mem_uncharge(sk, ret);
491 if (md->sg_start == MAX_SKB_FRAGS)
493 sg_init_table(sg, 1);
495 if (md->sg_start == md->sg_end)
499 if (apply && !apply_bytes)
505 static inline void bpf_compute_data_pointers_sg(struct sk_msg_buff *md)
507 struct scatterlist *sg = md->sg_data + md->sg_start;
509 if (md->sg_copy[md->sg_start]) {
510 md->data = md->data_end = 0;
512 md->data = sg_virt(sg);
513 md->data_end = md->data + sg->length;
517 static void return_mem_sg(struct sock *sk, int bytes, struct sk_msg_buff *md)
519 struct scatterlist *sg = md->sg_data;
520 int i = md->sg_start;
523 int uncharge = (bytes < sg[i].length) ? bytes : sg[i].length;
525 sk_mem_uncharge(sk, uncharge);
530 if (i == MAX_SKB_FRAGS)
532 } while (i != md->sg_end);
535 static void free_bytes_sg(struct sock *sk, int bytes,
536 struct sk_msg_buff *md, bool charge)
538 struct scatterlist *sg = md->sg_data;
539 int i = md->sg_start, free;
541 while (bytes && sg[i].length) {
544 sg[i].length -= bytes;
545 sg[i].offset += bytes;
547 sk_mem_uncharge(sk, bytes);
552 sk_mem_uncharge(sk, sg[i].length);
553 put_page(sg_page(&sg[i]));
554 bytes -= sg[i].length;
560 if (i == MAX_SKB_FRAGS)
566 static int free_sg(struct sock *sk, int start, struct sk_msg_buff *md)
568 struct scatterlist *sg = md->sg_data;
569 int i = start, free = 0;
571 while (sg[i].length) {
572 free += sg[i].length;
573 sk_mem_uncharge(sk, sg[i].length);
575 put_page(sg_page(&sg[i]));
581 if (i == MAX_SKB_FRAGS)
585 consume_skb(md->skb);
590 static int free_start_sg(struct sock *sk, struct sk_msg_buff *md)
592 int free = free_sg(sk, md->sg_start, md);
594 md->sg_start = md->sg_end;
598 static int free_curr_sg(struct sock *sk, struct sk_msg_buff *md)
600 return free_sg(sk, md->sg_curr, md);
603 static int bpf_map_msg_verdict(int _rc, struct sk_msg_buff *md)
605 return ((_rc == SK_PASS) ?
606 (md->sk_redir ? __SK_REDIRECT : __SK_PASS) :
610 static unsigned int smap_do_tx_msg(struct sock *sk,
611 struct smap_psock *psock,
612 struct sk_msg_buff *md)
614 struct bpf_prog *prog;
615 unsigned int rc, _rc;
620 /* If the policy was removed mid-send then default to 'accept' */
621 prog = READ_ONCE(psock->bpf_tx_msg);
622 if (unlikely(!prog)) {
627 bpf_compute_data_pointers_sg(md);
629 rc = (*prog->bpf_func)(md, prog->insnsi);
630 psock->apply_bytes = md->apply_bytes;
632 /* Moving return codes from UAPI namespace into internal namespace */
633 _rc = bpf_map_msg_verdict(rc, md);
635 /* The psock has a refcount on the sock but not on the map and because
636 * we need to drop rcu read lock here its possible the map could be
637 * removed between here and when we need it to execute the sock
638 * redirect. So do the map lookup now for future use.
640 if (_rc == __SK_REDIRECT) {
642 sock_put(psock->sk_redir);
643 psock->sk_redir = do_msg_redirect_map(md);
644 if (!psock->sk_redir) {
648 sock_hold(psock->sk_redir);
657 static int bpf_tcp_ingress(struct sock *sk, int apply_bytes,
658 struct smap_psock *psock,
659 struct sk_msg_buff *md, int flags)
661 bool apply = apply_bytes;
662 size_t size, copied = 0;
663 struct sk_msg_buff *r;
666 r = kzalloc(sizeof(struct sk_msg_buff), __GFP_NOWARN | GFP_KERNEL);
671 r->sg_start = md->sg_start;
675 size = (apply && apply_bytes < md->sg_data[i].length) ?
676 apply_bytes : md->sg_data[i].length;
678 if (!sk_wmem_schedule(sk, size)) {
684 sk_mem_charge(sk, size);
685 r->sg_data[i] = md->sg_data[i];
686 r->sg_data[i].length = size;
687 md->sg_data[i].length -= size;
688 md->sg_data[i].offset += size;
691 if (md->sg_data[i].length) {
692 get_page(sg_page(&r->sg_data[i]));
693 r->sg_end = (i + 1) == MAX_SKB_FRAGS ? 0 : i + 1;
696 if (i == MAX_SKB_FRAGS)
706 } while (i != md->sg_end);
711 list_add_tail(&r->list, &psock->ingress);
712 sk->sk_data_ready(sk);
714 free_start_sg(sk, r);
722 static int bpf_tcp_sendmsg_do_redirect(struct sock *sk, int send,
723 struct sk_msg_buff *md,
726 bool ingress = !!(md->flags & BPF_F_INGRESS);
727 struct smap_psock *psock;
728 struct scatterlist *sg;
734 psock = smap_psock_sk(sk);
735 if (unlikely(!psock))
738 if (!refcount_inc_not_zero(&psock->refcnt))
744 err = bpf_tcp_ingress(sk, send, psock, md, flags);
747 err = bpf_tcp_push(sk, send, md, flags, false);
750 smap_release_sock(psock, sk);
757 free_bytes_sg(NULL, send, md, false);
761 static inline void bpf_md_init(struct smap_psock *psock)
763 if (!psock->apply_bytes) {
764 psock->eval = __SK_NONE;
765 if (psock->sk_redir) {
766 sock_put(psock->sk_redir);
767 psock->sk_redir = NULL;
772 static void apply_bytes_dec(struct smap_psock *psock, int i)
774 if (psock->apply_bytes) {
775 if (psock->apply_bytes < i)
776 psock->apply_bytes = 0;
778 psock->apply_bytes -= i;
782 static int bpf_exec_tx_verdict(struct smap_psock *psock,
783 struct sk_msg_buff *m,
785 int *copied, int flags)
787 bool cork = false, enospc = (m->sg_start == m->sg_end);
793 if (psock->eval == __SK_NONE)
794 psock->eval = smap_do_tx_msg(sk, psock, m);
797 m->cork_bytes > psock->sg_size && !enospc) {
798 psock->cork_bytes = m->cork_bytes - psock->sg_size;
800 psock->cork = kcalloc(1,
801 sizeof(struct sk_msg_buff),
802 GFP_ATOMIC | __GFP_NOWARN);
809 memcpy(psock->cork, m, sizeof(*m));
813 send = psock->sg_size;
814 if (psock->apply_bytes && psock->apply_bytes < send)
815 send = psock->apply_bytes;
817 switch (psock->eval) {
819 err = bpf_tcp_push(sk, send, m, flags, true);
821 *copied -= free_start_sg(sk, m);
825 apply_bytes_dec(psock, send);
826 psock->sg_size -= send;
829 redir = psock->sk_redir;
830 apply_bytes_dec(psock, send);
837 return_mem_sg(sk, send, m);
840 err = bpf_tcp_sendmsg_do_redirect(redir, send, m, flags);
843 if (unlikely(err < 0)) {
844 free_start_sg(sk, m);
849 psock->sg_size -= send;
853 free_start_sg(sk, m);
862 free_bytes_sg(sk, send, m, true);
863 apply_bytes_dec(psock, send);
865 psock->sg_size -= send;
873 m->sg_data[m->sg_start].page_link &&
874 m->sg_data[m->sg_start].length)
882 static int bpf_wait_data(struct sock *sk,
883 struct smap_psock *psk, int flags,
884 long timeo, int *err)
888 DEFINE_WAIT_FUNC(wait, woken_wake_function);
890 add_wait_queue(sk_sleep(sk), &wait);
891 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
892 rc = sk_wait_event(sk, &timeo,
893 !list_empty(&psk->ingress) ||
894 !skb_queue_empty(&sk->sk_receive_queue),
896 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
897 remove_wait_queue(sk_sleep(sk), &wait);
902 static int bpf_tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
903 int nonblock, int flags, int *addr_len)
905 struct iov_iter *iter = &msg->msg_iter;
906 struct smap_psock *psock;
909 if (unlikely(flags & MSG_ERRQUEUE))
910 return inet_recv_error(sk, msg, len, addr_len);
913 psock = smap_psock_sk(sk);
914 if (unlikely(!psock))
917 if (unlikely(!refcount_inc_not_zero(&psock->refcnt)))
921 if (!skb_queue_empty(&sk->sk_receive_queue))
922 return tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
926 while (copied != len) {
927 struct scatterlist *sg;
928 struct sk_msg_buff *md;
931 md = list_first_entry_or_null(&psock->ingress,
932 struct sk_msg_buff, list);
940 sg = &md->sg_data[i];
944 if (copied + copy > len)
947 n = copy_page_to_iter(page, sg->offset, copy, iter);
951 smap_release_sock(psock, sk);
958 sk_mem_uncharge(sk, copy);
962 if (i == MAX_SKB_FRAGS)
969 } while (i != md->sg_end);
972 if (!sg->length && md->sg_start == md->sg_end) {
975 consume_skb(md->skb);
985 timeo = sock_rcvtimeo(sk, nonblock);
986 data = bpf_wait_data(sk, psock, flags, timeo, &err);
989 if (!skb_queue_empty(&sk->sk_receive_queue)) {
991 smap_release_sock(psock, sk);
992 copied = tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
1003 smap_release_sock(psock, sk);
1007 return tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
1011 static int bpf_tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
1013 int flags = msg->msg_flags | MSG_NO_SHARED_FRAGS;
1014 struct sk_msg_buff md = {0};
1015 unsigned int sg_copy = 0;
1016 struct smap_psock *psock;
1017 int copied = 0, err = 0;
1018 struct scatterlist *sg;
1021 /* Its possible a sock event or user removed the psock _but_ the ops
1022 * have not been reprogrammed yet so we get here. In this case fallback
1023 * to tcp_sendmsg. Note this only works because we _only_ ever allow
1024 * a single ULP there is no hierarchy here.
1027 psock = smap_psock_sk(sk);
1028 if (unlikely(!psock)) {
1030 return tcp_sendmsg(sk, msg, size);
1033 /* Increment the psock refcnt to ensure its not released while sending a
1034 * message. Required because sk lookup and bpf programs are used in
1035 * separate rcu critical sections. Its OK if we lose the map entry
1036 * but we can't lose the sock reference.
1038 if (!refcount_inc_not_zero(&psock->refcnt)) {
1040 return tcp_sendmsg(sk, msg, size);
1044 sg_init_marker(sg, MAX_SKB_FRAGS);
1048 timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1050 while (msg_data_left(msg)) {
1051 struct sk_msg_buff *m;
1052 bool enospc = false;
1060 copy = msg_data_left(msg);
1061 if (!sk_stream_memory_free(sk))
1062 goto wait_for_sndbuf;
1064 m = psock->cork_bytes ? psock->cork : &md;
1065 m->sg_curr = m->sg_copybreak ? m->sg_curr : m->sg_end;
1066 err = sk_alloc_sg(sk, copy, m->sg_data,
1067 m->sg_start, &m->sg_end, &sg_copy,
1071 goto wait_for_memory;
1076 err = memcopy_from_iter(sk, m, &msg->msg_iter, copy);
1078 free_curr_sg(sk, m);
1082 psock->sg_size += copy;
1086 /* When bytes are being corked skip running BPF program and
1087 * applying verdict unless there is no more buffer space. In
1088 * the ENOSPC case simply run BPF prorgram with currently
1089 * accumulated data. We don't have much choice at this point
1090 * we could try extending the page frags or chaining complex
1091 * frags but even in these cases _eventually_ we will hit an
1092 * OOM scenario. More complex recovery schemes may be
1093 * implemented in the future, but BPF programs must handle
1094 * the case where apply_cork requests are not honored. The
1095 * canonical method to verify this is to check data length.
1097 if (psock->cork_bytes) {
1098 if (copy > psock->cork_bytes)
1099 psock->cork_bytes = 0;
1101 psock->cork_bytes -= copy;
1103 if (psock->cork_bytes && !enospc)
1106 /* All cork bytes accounted for re-run filter */
1107 psock->eval = __SK_NONE;
1108 psock->cork_bytes = 0;
1111 err = bpf_exec_tx_verdict(psock, m, sk, &copied, flags);
1112 if (unlikely(err < 0))
1116 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1118 err = sk_stream_wait_memory(sk, &timeo);
1124 err = sk_stream_error(sk, msg->msg_flags, err);
1127 smap_release_sock(psock, sk);
1128 return copied ? copied : err;
1131 static int bpf_tcp_sendpage(struct sock *sk, struct page *page,
1132 int offset, size_t size, int flags)
1134 struct sk_msg_buff md = {0}, *m = NULL;
1135 int err = 0, copied = 0;
1136 struct smap_psock *psock;
1137 struct scatterlist *sg;
1138 bool enospc = false;
1141 psock = smap_psock_sk(sk);
1142 if (unlikely(!psock))
1145 if (!refcount_inc_not_zero(&psock->refcnt))
1151 if (psock->cork_bytes) {
1153 sg = &m->sg_data[m->sg_end];
1157 sg_init_marker(sg, MAX_SKB_FRAGS);
1160 /* Catch case where ring is full and sendpage is stalled. */
1161 if (unlikely(m->sg_end == m->sg_start &&
1162 m->sg_data[m->sg_end].length))
1165 psock->sg_size += size;
1166 sg_set_page(sg, page, size, offset);
1168 m->sg_copy[m->sg_end] = true;
1169 sk_mem_charge(sk, size);
1173 if (m->sg_end == MAX_SKB_FRAGS)
1176 if (m->sg_end == m->sg_start)
1179 if (psock->cork_bytes) {
1180 if (size > psock->cork_bytes)
1181 psock->cork_bytes = 0;
1183 psock->cork_bytes -= size;
1185 if (psock->cork_bytes && !enospc)
1188 /* All cork bytes accounted for re-run filter */
1189 psock->eval = __SK_NONE;
1190 psock->cork_bytes = 0;
1193 err = bpf_exec_tx_verdict(psock, m, sk, &copied, flags);
1196 smap_release_sock(psock, sk);
1197 return copied ? copied : err;
1200 return tcp_sendpage(sk, page, offset, size, flags);
1203 static void bpf_tcp_msg_add(struct smap_psock *psock,
1205 struct bpf_prog *tx_msg)
1207 struct bpf_prog *orig_tx_msg;
1209 orig_tx_msg = xchg(&psock->bpf_tx_msg, tx_msg);
1211 bpf_prog_put(orig_tx_msg);
1214 static int bpf_tcp_ulp_register(void)
1216 build_protos(bpf_tcp_prots[SOCKMAP_IPV4], &tcp_prot);
1217 /* Once BPF TX ULP is registered it is never unregistered. It
1218 * will be in the ULP list for the lifetime of the system. Doing
1219 * duplicate registers is not a problem.
1221 return tcp_register_ulp(&bpf_tcp_ulp_ops);
1224 static int smap_verdict_func(struct smap_psock *psock, struct sk_buff *skb)
1226 struct bpf_prog *prog = READ_ONCE(psock->bpf_verdict);
1229 if (unlikely(!prog))
1233 /* We need to ensure that BPF metadata for maps is also cleared
1234 * when we orphan the skb so that we don't have the possibility
1235 * to reference a stale map.
1237 TCP_SKB_CB(skb)->bpf.sk_redir = NULL;
1238 skb->sk = psock->sock;
1239 bpf_compute_data_pointers(skb);
1241 rc = (*prog->bpf_func)(skb, prog->insnsi);
1245 /* Moving return codes from UAPI namespace into internal namespace */
1246 return rc == SK_PASS ?
1247 (TCP_SKB_CB(skb)->bpf.sk_redir ? __SK_REDIRECT : __SK_PASS) :
1251 static int smap_do_ingress(struct smap_psock *psock, struct sk_buff *skb)
1253 struct sock *sk = psock->sock;
1254 int copied = 0, num_sg;
1255 struct sk_msg_buff *r;
1257 r = kzalloc(sizeof(struct sk_msg_buff), __GFP_NOWARN | GFP_ATOMIC);
1261 if (!sk_rmem_schedule(sk, skb, skb->len)) {
1266 sg_init_table(r->sg_data, MAX_SKB_FRAGS);
1267 num_sg = skb_to_sgvec(skb, r->sg_data, 0, skb->len);
1268 if (unlikely(num_sg < 0)) {
1272 sk_mem_charge(sk, skb->len);
1275 r->sg_end = num_sg == MAX_SKB_FRAGS ? 0 : num_sg;
1277 list_add_tail(&r->list, &psock->ingress);
1278 sk->sk_data_ready(sk);
1282 static void smap_do_verdict(struct smap_psock *psock, struct sk_buff *skb)
1284 struct smap_psock *peer;
1289 rc = smap_verdict_func(psock, skb);
1292 sk = do_sk_redirect_map(skb);
1298 peer = smap_psock_sk(sk);
1299 in = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
1301 if (unlikely(!peer || sock_flag(sk, SOCK_DEAD) ||
1302 !test_bit(SMAP_TX_RUNNING, &peer->state))) {
1307 if (!in && sock_writeable(sk)) {
1308 skb_set_owner_w(skb, sk);
1309 skb_queue_tail(&peer->rxqueue, skb);
1310 schedule_work(&peer->tx_work);
1313 atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
1314 skb_queue_tail(&peer->rxqueue, skb);
1315 schedule_work(&peer->tx_work);
1318 /* Fall through and free skb otherwise */
1325 static void smap_report_sk_error(struct smap_psock *psock, int err)
1327 struct sock *sk = psock->sock;
1330 sk->sk_error_report(sk);
1333 static void smap_read_sock_strparser(struct strparser *strp,
1334 struct sk_buff *skb)
1336 struct smap_psock *psock;
1339 psock = container_of(strp, struct smap_psock, strp);
1340 smap_do_verdict(psock, skb);
1344 /* Called with lock held on socket */
1345 static void smap_data_ready(struct sock *sk)
1347 struct smap_psock *psock;
1350 psock = smap_psock_sk(sk);
1351 if (likely(psock)) {
1352 write_lock_bh(&sk->sk_callback_lock);
1353 strp_data_ready(&psock->strp);
1354 write_unlock_bh(&sk->sk_callback_lock);
1359 static void smap_tx_work(struct work_struct *w)
1361 struct smap_psock *psock;
1362 struct sk_buff *skb;
1365 psock = container_of(w, struct smap_psock, tx_work);
1367 /* lock sock to avoid losing sk_socket at some point during loop */
1368 lock_sock(psock->sock);
1369 if (psock->save_skb) {
1370 skb = psock->save_skb;
1371 rem = psock->save_rem;
1372 off = psock->save_off;
1373 psock->save_skb = NULL;
1377 while ((skb = skb_dequeue(&psock->rxqueue))) {
1383 flags = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
1385 if (likely(psock->sock->sk_socket)) {
1387 n = smap_do_ingress(psock, skb);
1389 n = skb_send_sock_locked(psock->sock,
1397 /* Retry when space is available */
1398 psock->save_skb = skb;
1399 psock->save_rem = rem;
1400 psock->save_off = off;
1403 /* Hard errors break pipe and stop xmit */
1404 smap_report_sk_error(psock, n ? -n : EPIPE);
1405 clear_bit(SMAP_TX_RUNNING, &psock->state);
1417 release_sock(psock->sock);
1420 static void smap_write_space(struct sock *sk)
1422 struct smap_psock *psock;
1425 psock = smap_psock_sk(sk);
1426 if (likely(psock && test_bit(SMAP_TX_RUNNING, &psock->state)))
1427 schedule_work(&psock->tx_work);
1431 static void smap_stop_sock(struct smap_psock *psock, struct sock *sk)
1433 if (!psock->strp_enabled)
1435 sk->sk_data_ready = psock->save_data_ready;
1436 sk->sk_write_space = psock->save_write_space;
1437 psock->save_data_ready = NULL;
1438 psock->save_write_space = NULL;
1439 strp_stop(&psock->strp);
1440 psock->strp_enabled = false;
1443 static void smap_destroy_psock(struct rcu_head *rcu)
1445 struct smap_psock *psock = container_of(rcu,
1446 struct smap_psock, rcu);
1448 /* Now that a grace period has passed there is no longer
1449 * any reference to this sock in the sockmap so we can
1450 * destroy the psock, strparser, and bpf programs. But,
1451 * because we use workqueue sync operations we can not
1452 * do it in rcu context
1454 schedule_work(&psock->gc_work);
1457 static void smap_release_sock(struct smap_psock *psock, struct sock *sock)
1459 if (refcount_dec_and_test(&psock->refcnt)) {
1460 tcp_cleanup_ulp(sock);
1461 write_lock_bh(&sock->sk_callback_lock);
1462 smap_stop_sock(psock, sock);
1463 write_unlock_bh(&sock->sk_callback_lock);
1464 clear_bit(SMAP_TX_RUNNING, &psock->state);
1465 rcu_assign_sk_user_data(sock, NULL);
1466 call_rcu_sched(&psock->rcu, smap_destroy_psock);
1470 static int smap_parse_func_strparser(struct strparser *strp,
1471 struct sk_buff *skb)
1473 struct smap_psock *psock;
1474 struct bpf_prog *prog;
1478 psock = container_of(strp, struct smap_psock, strp);
1479 prog = READ_ONCE(psock->bpf_parse);
1481 if (unlikely(!prog)) {
1486 /* Attach socket for bpf program to use if needed we can do this
1487 * because strparser clones the skb before handing it to a upper
1488 * layer, meaning skb_orphan has been called. We NULL sk on the
1489 * way out to ensure we don't trigger a BUG_ON in skb/sk operations
1490 * later and because we are not charging the memory of this skb to
1493 skb->sk = psock->sock;
1494 bpf_compute_data_pointers(skb);
1495 rc = (*prog->bpf_func)(skb, prog->insnsi);
1501 static int smap_read_sock_done(struct strparser *strp, int err)
1506 static int smap_init_sock(struct smap_psock *psock,
1509 static const struct strp_callbacks cb = {
1510 .rcv_msg = smap_read_sock_strparser,
1511 .parse_msg = smap_parse_func_strparser,
1512 .read_sock_done = smap_read_sock_done,
1515 return strp_init(&psock->strp, sk, &cb);
1518 static void smap_init_progs(struct smap_psock *psock,
1519 struct bpf_prog *verdict,
1520 struct bpf_prog *parse)
1522 struct bpf_prog *orig_parse, *orig_verdict;
1524 orig_parse = xchg(&psock->bpf_parse, parse);
1525 orig_verdict = xchg(&psock->bpf_verdict, verdict);
1528 bpf_prog_put(orig_verdict);
1530 bpf_prog_put(orig_parse);
1533 static void smap_start_sock(struct smap_psock *psock, struct sock *sk)
1535 if (sk->sk_data_ready == smap_data_ready)
1537 psock->save_data_ready = sk->sk_data_ready;
1538 psock->save_write_space = sk->sk_write_space;
1539 sk->sk_data_ready = smap_data_ready;
1540 sk->sk_write_space = smap_write_space;
1541 psock->strp_enabled = true;
1544 static void sock_map_remove_complete(struct bpf_stab *stab)
1546 bpf_map_area_free(stab->sock_map);
1550 static void smap_gc_work(struct work_struct *w)
1552 struct smap_psock_map_entry *e, *tmp;
1553 struct sk_msg_buff *md, *mtmp;
1554 struct smap_psock *psock;
1556 psock = container_of(w, struct smap_psock, gc_work);
1558 /* no callback lock needed because we already detached sockmap ops */
1559 if (psock->strp_enabled)
1560 strp_done(&psock->strp);
1562 cancel_work_sync(&psock->tx_work);
1563 __skb_queue_purge(&psock->rxqueue);
1565 /* At this point all strparser and xmit work must be complete */
1566 if (psock->bpf_parse)
1567 bpf_prog_put(psock->bpf_parse);
1568 if (psock->bpf_verdict)
1569 bpf_prog_put(psock->bpf_verdict);
1570 if (psock->bpf_tx_msg)
1571 bpf_prog_put(psock->bpf_tx_msg);
1574 free_start_sg(psock->sock, psock->cork);
1578 list_for_each_entry_safe(md, mtmp, &psock->ingress, list) {
1579 list_del(&md->list);
1580 free_start_sg(psock->sock, md);
1584 list_for_each_entry_safe(e, tmp, &psock->maps, list) {
1589 if (psock->sk_redir)
1590 sock_put(psock->sk_redir);
1592 sock_put(psock->sock);
1596 static struct smap_psock *smap_init_psock(struct sock *sock, int node)
1598 struct smap_psock *psock;
1600 psock = kzalloc_node(sizeof(struct smap_psock),
1601 GFP_ATOMIC | __GFP_NOWARN,
1604 return ERR_PTR(-ENOMEM);
1606 psock->eval = __SK_NONE;
1608 skb_queue_head_init(&psock->rxqueue);
1609 INIT_WORK(&psock->tx_work, smap_tx_work);
1610 INIT_WORK(&psock->gc_work, smap_gc_work);
1611 INIT_LIST_HEAD(&psock->maps);
1612 INIT_LIST_HEAD(&psock->ingress);
1613 refcount_set(&psock->refcnt, 1);
1614 spin_lock_init(&psock->maps_lock);
1616 rcu_assign_sk_user_data(sock, psock);
1621 static struct bpf_map *sock_map_alloc(union bpf_attr *attr)
1623 struct bpf_stab *stab;
1627 if (!capable(CAP_NET_ADMIN))
1628 return ERR_PTR(-EPERM);
1630 /* check sanity of attributes */
1631 if (attr->max_entries == 0 || attr->key_size != 4 ||
1632 attr->value_size != 4 || attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
1633 return ERR_PTR(-EINVAL);
1635 err = bpf_tcp_ulp_register();
1636 if (err && err != -EEXIST)
1637 return ERR_PTR(err);
1639 stab = kzalloc(sizeof(*stab), GFP_USER);
1641 return ERR_PTR(-ENOMEM);
1643 bpf_map_init_from_attr(&stab->map, attr);
1645 /* make sure page count doesn't overflow */
1646 cost = (u64) stab->map.max_entries * sizeof(struct sock *);
1648 if (cost >= U32_MAX - PAGE_SIZE)
1651 stab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
1653 /* if map size is larger than memlock limit, reject it early */
1654 err = bpf_map_precharge_memlock(stab->map.pages);
1659 stab->sock_map = bpf_map_area_alloc(stab->map.max_entries *
1660 sizeof(struct sock *),
1661 stab->map.numa_node);
1662 if (!stab->sock_map)
1668 return ERR_PTR(err);
1671 static void smap_list_map_remove(struct smap_psock *psock,
1672 struct sock **entry)
1674 struct smap_psock_map_entry *e, *tmp;
1676 spin_lock_bh(&psock->maps_lock);
1677 list_for_each_entry_safe(e, tmp, &psock->maps, list) {
1678 if (e->entry == entry)
1681 spin_unlock_bh(&psock->maps_lock);
1684 static void smap_list_hash_remove(struct smap_psock *psock,
1685 struct htab_elem *hash_link)
1687 struct smap_psock_map_entry *e, *tmp;
1689 spin_lock_bh(&psock->maps_lock);
1690 list_for_each_entry_safe(e, tmp, &psock->maps, list) {
1691 struct htab_elem *c = rcu_dereference(e->hash_link);
1696 spin_unlock_bh(&psock->maps_lock);
1699 static void sock_map_free(struct bpf_map *map)
1701 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1706 /* At this point no update, lookup or delete operations can happen.
1707 * However, be aware we can still get a socket state event updates,
1708 * and data ready callabacks that reference the psock from sk_user_data
1709 * Also psock worker threads are still in-flight. So smap_release_sock
1710 * will only free the psock after cancel_sync on the worker threads
1711 * and a grace period expire to ensure psock is really safe to remove.
1714 for (i = 0; i < stab->map.max_entries; i++) {
1715 struct smap_psock *psock;
1718 sock = xchg(&stab->sock_map[i], NULL);
1722 psock = smap_psock_sk(sock);
1723 /* This check handles a racing sock event that can get the
1724 * sk_callback_lock before this case but after xchg happens
1725 * causing the refcnt to hit zero and sock user data (psock)
1726 * to be null and queued for garbage collection.
1728 if (likely(psock)) {
1729 smap_list_map_remove(psock, &stab->sock_map[i]);
1730 smap_release_sock(psock, sock);
1735 sock_map_remove_complete(stab);
1738 static int sock_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
1740 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1741 u32 i = key ? *(u32 *)key : U32_MAX;
1742 u32 *next = (u32 *)next_key;
1744 if (i >= stab->map.max_entries) {
1749 if (i == stab->map.max_entries - 1)
1756 struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
1758 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1760 if (key >= map->max_entries)
1763 return READ_ONCE(stab->sock_map[key]);
1766 static int sock_map_delete_elem(struct bpf_map *map, void *key)
1768 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1769 struct smap_psock *psock;
1770 int k = *(u32 *)key;
1773 if (k >= map->max_entries)
1776 sock = xchg(&stab->sock_map[k], NULL);
1780 psock = smap_psock_sk(sock);
1784 if (psock->bpf_parse)
1785 smap_stop_sock(psock, sock);
1786 smap_list_map_remove(psock, &stab->sock_map[k]);
1787 smap_release_sock(psock, sock);
1792 /* Locking notes: Concurrent updates, deletes, and lookups are allowed and are
1793 * done inside rcu critical sections. This ensures on updates that the psock
1794 * will not be released via smap_release_sock() until concurrent updates/deletes
1795 * complete. All operations operate on sock_map using cmpxchg and xchg
1796 * operations to ensure we do not get stale references. Any reads into the
1797 * map must be done with READ_ONCE() because of this.
1799 * A psock is destroyed via call_rcu and after any worker threads are cancelled
1800 * and syncd so we are certain all references from the update/lookup/delete
1801 * operations as well as references in the data path are no longer in use.
1803 * Psocks may exist in multiple maps, but only a single set of parse/verdict
1804 * programs may be inherited from the maps it belongs to. A reference count
1805 * is kept with the total number of references to the psock from all maps. The
1806 * psock will not be released until this reaches zero. The psock and sock
1807 * user data data use the sk_callback_lock to protect critical data structures
1808 * from concurrent access. This allows us to avoid two updates from modifying
1809 * the user data in sock and the lock is required anyways for modifying
1810 * callbacks, we simply increase its scope slightly.
1813 * - psock must always be read inside RCU critical section
1814 * - sk_user_data must only be modified inside sk_callback_lock and read
1815 * inside RCU critical section.
1816 * - psock->maps list must only be read & modified inside sk_callback_lock
1817 * - sock_map must use READ_ONCE and (cmp)xchg operations
1818 * - BPF verdict/parse programs must use READ_ONCE and xchg operations
1821 static int __sock_map_ctx_update_elem(struct bpf_map *map,
1822 struct bpf_sock_progs *progs,
1824 struct sock **map_link,
1827 struct bpf_prog *verdict, *parse, *tx_msg;
1828 struct smap_psock_map_entry *e = NULL;
1829 struct smap_psock *psock;
1833 /* 1. If sock map has BPF programs those will be inherited by the
1834 * sock being added. If the sock is already attached to BPF programs
1835 * this results in an error.
1837 verdict = READ_ONCE(progs->bpf_verdict);
1838 parse = READ_ONCE(progs->bpf_parse);
1839 tx_msg = READ_ONCE(progs->bpf_tx_msg);
1841 if (parse && verdict) {
1842 /* bpf prog refcnt may be zero if a concurrent attach operation
1843 * removes the program after the above READ_ONCE() but before
1844 * we increment the refcnt. If this is the case abort with an
1847 verdict = bpf_prog_inc_not_zero(verdict);
1848 if (IS_ERR(verdict))
1849 return PTR_ERR(verdict);
1851 parse = bpf_prog_inc_not_zero(parse);
1852 if (IS_ERR(parse)) {
1853 bpf_prog_put(verdict);
1854 return PTR_ERR(parse);
1859 tx_msg = bpf_prog_inc_not_zero(tx_msg);
1860 if (IS_ERR(tx_msg)) {
1861 if (parse && verdict) {
1862 bpf_prog_put(parse);
1863 bpf_prog_put(verdict);
1865 return PTR_ERR(tx_msg);
1869 psock = smap_psock_sk(sock);
1871 /* 2. Do not allow inheriting programs if psock exists and has
1872 * already inherited programs. This would create confusion on
1873 * which parser/verdict program is running. If no psock exists
1874 * create one. Inside sk_callback_lock to ensure concurrent create
1875 * doesn't update user data.
1878 if (READ_ONCE(psock->bpf_parse) && parse) {
1882 if (READ_ONCE(psock->bpf_tx_msg) && tx_msg) {
1886 if (!refcount_inc_not_zero(&psock->refcnt)) {
1891 psock = smap_init_psock(sock, map->numa_node);
1892 if (IS_ERR(psock)) {
1893 err = PTR_ERR(psock);
1897 set_bit(SMAP_TX_RUNNING, &psock->state);
1902 e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
1909 /* 3. At this point we have a reference to a valid psock that is
1910 * running. Attach any BPF programs needed.
1913 bpf_tcp_msg_add(psock, sock, tx_msg);
1915 err = tcp_set_ulp_id(sock, TCP_ULP_BPF);
1920 if (parse && verdict && !psock->strp_enabled) {
1921 err = smap_init_sock(psock, sock);
1924 smap_init_progs(psock, verdict, parse);
1925 write_lock_bh(&sock->sk_callback_lock);
1926 smap_start_sock(psock, sock);
1927 write_unlock_bh(&sock->sk_callback_lock);
1930 /* 4. Place psock in sockmap for use and stop any programs on
1931 * the old sock assuming its not the same sock we are replacing
1932 * it with. Because we can only have a single set of programs if
1933 * old_sock has a strp we can stop it.
1936 e->entry = map_link;
1937 spin_lock_bh(&psock->maps_lock);
1938 list_add_tail(&e->list, &psock->maps);
1939 spin_unlock_bh(&psock->maps_lock);
1943 smap_release_sock(psock, sock);
1945 if (parse && verdict) {
1946 bpf_prog_put(parse);
1947 bpf_prog_put(verdict);
1950 bpf_prog_put(tx_msg);
1955 static int sock_map_ctx_update_elem(struct bpf_sock_ops_kern *skops,
1956 struct bpf_map *map,
1957 void *key, u64 flags)
1959 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1960 struct bpf_sock_progs *progs = &stab->progs;
1961 struct sock *osock, *sock;
1962 u32 i = *(u32 *)key;
1965 if (unlikely(flags > BPF_EXIST))
1968 if (unlikely(i >= stab->map.max_entries))
1971 sock = READ_ONCE(stab->sock_map[i]);
1972 if (flags == BPF_EXIST && !sock)
1974 else if (flags == BPF_NOEXIST && sock)
1978 err = __sock_map_ctx_update_elem(map, progs, sock, &stab->sock_map[i],
1983 osock = xchg(&stab->sock_map[i], sock);
1985 struct smap_psock *opsock = smap_psock_sk(osock);
1987 smap_list_map_remove(opsock, &stab->sock_map[i]);
1988 smap_release_sock(opsock, osock);
1994 int sock_map_prog(struct bpf_map *map, struct bpf_prog *prog, u32 type)
1996 struct bpf_sock_progs *progs;
1997 struct bpf_prog *orig;
1999 if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
2000 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
2002 progs = &stab->progs;
2003 } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2004 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2006 progs = &htab->progs;
2012 case BPF_SK_MSG_VERDICT:
2013 orig = xchg(&progs->bpf_tx_msg, prog);
2015 case BPF_SK_SKB_STREAM_PARSER:
2016 orig = xchg(&progs->bpf_parse, prog);
2018 case BPF_SK_SKB_STREAM_VERDICT:
2019 orig = xchg(&progs->bpf_verdict, prog);
2031 int sockmap_get_from_fd(const union bpf_attr *attr, int type,
2032 struct bpf_prog *prog)
2034 int ufd = attr->target_fd;
2035 struct bpf_map *map;
2040 map = __bpf_map_get(f);
2042 return PTR_ERR(map);
2044 err = sock_map_prog(map, prog, attr->attach_type);
2049 static void *sock_map_lookup(struct bpf_map *map, void *key)
2054 static int sock_map_update_elem(struct bpf_map *map,
2055 void *key, void *value, u64 flags)
2057 struct bpf_sock_ops_kern skops;
2058 u32 fd = *(u32 *)value;
2059 struct socket *socket;
2062 socket = sockfd_lookup(fd, &err);
2066 skops.sk = socket->sk;
2072 if (skops.sk->sk_type != SOCK_STREAM ||
2073 skops.sk->sk_protocol != IPPROTO_TCP) {
2078 lock_sock(skops.sk);
2081 err = sock_map_ctx_update_elem(&skops, map, key, flags);
2084 release_sock(skops.sk);
2089 static void sock_map_release(struct bpf_map *map)
2091 struct bpf_sock_progs *progs;
2092 struct bpf_prog *orig;
2094 if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
2095 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
2097 progs = &stab->progs;
2099 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2101 progs = &htab->progs;
2104 orig = xchg(&progs->bpf_parse, NULL);
2107 orig = xchg(&progs->bpf_verdict, NULL);
2111 orig = xchg(&progs->bpf_tx_msg, NULL);
2116 static struct bpf_map *sock_hash_alloc(union bpf_attr *attr)
2118 struct bpf_htab *htab;
2122 if (!capable(CAP_NET_ADMIN))
2123 return ERR_PTR(-EPERM);
2125 /* check sanity of attributes */
2126 if (attr->max_entries == 0 || attr->value_size != 4 ||
2127 attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
2128 return ERR_PTR(-EINVAL);
2130 if (attr->key_size > MAX_BPF_STACK)
2131 /* eBPF programs initialize keys on stack, so they cannot be
2132 * larger than max stack size
2134 return ERR_PTR(-E2BIG);
2136 err = bpf_tcp_ulp_register();
2137 if (err && err != -EEXIST)
2138 return ERR_PTR(err);
2140 htab = kzalloc(sizeof(*htab), GFP_USER);
2142 return ERR_PTR(-ENOMEM);
2144 bpf_map_init_from_attr(&htab->map, attr);
2146 htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
2147 htab->elem_size = sizeof(struct htab_elem) +
2148 round_up(htab->map.key_size, 8);
2150 if (htab->n_buckets == 0 ||
2151 htab->n_buckets > U32_MAX / sizeof(struct bucket))
2154 cost = (u64) htab->n_buckets * sizeof(struct bucket) +
2155 (u64) htab->elem_size * htab->map.max_entries;
2157 if (cost >= U32_MAX - PAGE_SIZE)
2160 htab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
2161 err = bpf_map_precharge_memlock(htab->map.pages);
2166 htab->buckets = bpf_map_area_alloc(
2167 htab->n_buckets * sizeof(struct bucket),
2168 htab->map.numa_node);
2172 for (i = 0; i < htab->n_buckets; i++) {
2173 INIT_HLIST_HEAD(&htab->buckets[i].head);
2174 raw_spin_lock_init(&htab->buckets[i].lock);
2180 return ERR_PTR(err);
2183 static void __bpf_htab_free(struct rcu_head *rcu)
2185 struct bpf_htab *htab;
2187 htab = container_of(rcu, struct bpf_htab, rcu);
2188 bpf_map_area_free(htab->buckets);
2192 static void sock_hash_free(struct bpf_map *map)
2194 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2199 /* At this point no update, lookup or delete operations can happen.
2200 * However, be aware we can still get a socket state event updates,
2201 * and data ready callabacks that reference the psock from sk_user_data
2202 * Also psock worker threads are still in-flight. So smap_release_sock
2203 * will only free the psock after cancel_sync on the worker threads
2204 * and a grace period expire to ensure psock is really safe to remove.
2207 for (i = 0; i < htab->n_buckets; i++) {
2208 struct bucket *b = __select_bucket(htab, i);
2209 struct hlist_head *head;
2210 struct hlist_node *n;
2211 struct htab_elem *l;
2213 raw_spin_lock_bh(&b->lock);
2215 hlist_for_each_entry_safe(l, n, head, hash_node) {
2216 struct sock *sock = l->sk;
2217 struct smap_psock *psock;
2219 hlist_del_rcu(&l->hash_node);
2220 psock = smap_psock_sk(sock);
2221 /* This check handles a racing sock event that can get
2222 * the sk_callback_lock before this case but after xchg
2223 * causing the refcnt to hit zero and sock user data
2224 * (psock) to be null and queued for garbage collection.
2226 if (likely(psock)) {
2227 smap_list_hash_remove(psock, l);
2228 smap_release_sock(psock, sock);
2230 free_htab_elem(htab, l);
2232 raw_spin_unlock_bh(&b->lock);
2235 call_rcu(&htab->rcu, __bpf_htab_free);
2238 static struct htab_elem *alloc_sock_hash_elem(struct bpf_htab *htab,
2239 void *key, u32 key_size, u32 hash,
2241 struct htab_elem *old_elem)
2243 struct htab_elem *l_new;
2245 if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
2247 atomic_dec(&htab->count);
2248 return ERR_PTR(-E2BIG);
2251 l_new = kmalloc_node(htab->elem_size, GFP_ATOMIC | __GFP_NOWARN,
2252 htab->map.numa_node);
2254 return ERR_PTR(-ENOMEM);
2256 memcpy(l_new->key, key, key_size);
2262 static inline u32 htab_map_hash(const void *key, u32 key_len)
2264 return jhash(key, key_len, 0);
2267 static int sock_hash_get_next_key(struct bpf_map *map,
2268 void *key, void *next_key)
2270 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2271 struct htab_elem *l, *next_l;
2272 struct hlist_head *h;
2276 WARN_ON_ONCE(!rcu_read_lock_held());
2278 key_size = map->key_size;
2280 goto find_first_elem;
2281 hash = htab_map_hash(key, key_size);
2282 h = select_bucket(htab, hash);
2284 l = lookup_elem_raw(h, hash, key, key_size);
2286 goto find_first_elem;
2287 next_l = hlist_entry_safe(
2288 rcu_dereference_raw(hlist_next_rcu(&l->hash_node)),
2289 struct htab_elem, hash_node);
2291 memcpy(next_key, next_l->key, key_size);
2295 /* no more elements in this hash list, go to the next bucket */
2296 i = hash & (htab->n_buckets - 1);
2300 /* iterate over buckets */
2301 for (; i < htab->n_buckets; i++) {
2302 h = select_bucket(htab, i);
2304 /* pick first element in the bucket */
2305 next_l = hlist_entry_safe(
2306 rcu_dereference_raw(hlist_first_rcu(h)),
2307 struct htab_elem, hash_node);
2309 /* if it's not empty, just return it */
2310 memcpy(next_key, next_l->key, key_size);
2315 /* iterated over all buckets and all elements */
2319 static int sock_hash_ctx_update_elem(struct bpf_sock_ops_kern *skops,
2320 struct bpf_map *map,
2321 void *key, u64 map_flags)
2323 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2324 struct bpf_sock_progs *progs = &htab->progs;
2325 struct htab_elem *l_new = NULL, *l_old;
2326 struct smap_psock_map_entry *e = NULL;
2327 struct hlist_head *head;
2328 struct smap_psock *psock;
2336 if (sock->sk_type != SOCK_STREAM ||
2337 sock->sk_protocol != IPPROTO_TCP)
2340 if (unlikely(map_flags > BPF_EXIST))
2343 e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
2347 WARN_ON_ONCE(!rcu_read_lock_held());
2348 key_size = map->key_size;
2349 hash = htab_map_hash(key, key_size);
2350 b = __select_bucket(htab, hash);
2353 err = __sock_map_ctx_update_elem(map, progs, sock, NULL, key);
2357 /* psock is valid here because otherwise above *ctx_update_elem would
2358 * have thrown an error. It is safe to skip error check.
2360 psock = smap_psock_sk(sock);
2361 raw_spin_lock_bh(&b->lock);
2362 l_old = lookup_elem_raw(head, hash, key, key_size);
2363 if (l_old && map_flags == BPF_NOEXIST) {
2367 if (!l_old && map_flags == BPF_EXIST) {
2372 l_new = alloc_sock_hash_elem(htab, key, key_size, hash, sock, l_old);
2373 if (IS_ERR(l_new)) {
2374 err = PTR_ERR(l_new);
2378 rcu_assign_pointer(e->hash_link, l_new);
2379 rcu_assign_pointer(e->htab,
2380 container_of(map, struct bpf_htab, map));
2381 spin_lock_bh(&psock->maps_lock);
2382 list_add_tail(&e->list, &psock->maps);
2383 spin_unlock_bh(&psock->maps_lock);
2385 /* add new element to the head of the list, so that
2386 * concurrent search will find it before old elem
2388 hlist_add_head_rcu(&l_new->hash_node, head);
2390 psock = smap_psock_sk(l_old->sk);
2392 hlist_del_rcu(&l_old->hash_node);
2393 smap_list_hash_remove(psock, l_old);
2394 smap_release_sock(psock, l_old->sk);
2395 free_htab_elem(htab, l_old);
2397 raw_spin_unlock_bh(&b->lock);
2400 smap_release_sock(psock, sock);
2401 raw_spin_unlock_bh(&b->lock);
2407 static int sock_hash_update_elem(struct bpf_map *map,
2408 void *key, void *value, u64 flags)
2410 struct bpf_sock_ops_kern skops;
2411 u32 fd = *(u32 *)value;
2412 struct socket *socket;
2415 socket = sockfd_lookup(fd, &err);
2419 skops.sk = socket->sk;
2425 lock_sock(skops.sk);
2428 err = sock_hash_ctx_update_elem(&skops, map, key, flags);
2431 release_sock(skops.sk);
2436 static int sock_hash_delete_elem(struct bpf_map *map, void *key)
2438 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2439 struct hlist_head *head;
2441 struct htab_elem *l;
2445 key_size = map->key_size;
2446 hash = htab_map_hash(key, key_size);
2447 b = __select_bucket(htab, hash);
2450 raw_spin_lock_bh(&b->lock);
2451 l = lookup_elem_raw(head, hash, key, key_size);
2453 struct sock *sock = l->sk;
2454 struct smap_psock *psock;
2456 hlist_del_rcu(&l->hash_node);
2457 psock = smap_psock_sk(sock);
2458 /* This check handles a racing sock event that can get the
2459 * sk_callback_lock before this case but after xchg happens
2460 * causing the refcnt to hit zero and sock user data (psock)
2461 * to be null and queued for garbage collection.
2463 if (likely(psock)) {
2464 smap_list_hash_remove(psock, l);
2465 smap_release_sock(psock, sock);
2467 free_htab_elem(htab, l);
2470 raw_spin_unlock_bh(&b->lock);
2474 struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
2476 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2477 struct hlist_head *head;
2478 struct htab_elem *l;
2483 key_size = map->key_size;
2484 hash = htab_map_hash(key, key_size);
2485 b = __select_bucket(htab, hash);
2488 l = lookup_elem_raw(head, hash, key, key_size);
2489 sk = l ? l->sk : NULL;
2493 const struct bpf_map_ops sock_map_ops = {
2494 .map_alloc = sock_map_alloc,
2495 .map_free = sock_map_free,
2496 .map_lookup_elem = sock_map_lookup,
2497 .map_get_next_key = sock_map_get_next_key,
2498 .map_update_elem = sock_map_update_elem,
2499 .map_delete_elem = sock_map_delete_elem,
2500 .map_release_uref = sock_map_release,
2503 const struct bpf_map_ops sock_hash_ops = {
2504 .map_alloc = sock_hash_alloc,
2505 .map_free = sock_hash_free,
2506 .map_lookup_elem = sock_map_lookup,
2507 .map_get_next_key = sock_hash_get_next_key,
2508 .map_update_elem = sock_hash_update_elem,
2509 .map_delete_elem = sock_hash_delete_elem,
2510 .map_release_uref = sock_map_release,
2513 BPF_CALL_4(bpf_sock_map_update, struct bpf_sock_ops_kern *, bpf_sock,
2514 struct bpf_map *, map, void *, key, u64, flags)
2516 WARN_ON_ONCE(!rcu_read_lock_held());
2517 return sock_map_ctx_update_elem(bpf_sock, map, key, flags);
2520 const struct bpf_func_proto bpf_sock_map_update_proto = {
2521 .func = bpf_sock_map_update,
2524 .ret_type = RET_INTEGER,
2525 .arg1_type = ARG_PTR_TO_CTX,
2526 .arg2_type = ARG_CONST_MAP_PTR,
2527 .arg3_type = ARG_PTR_TO_MAP_KEY,
2528 .arg4_type = ARG_ANYTHING,
2531 BPF_CALL_4(bpf_sock_hash_update, struct bpf_sock_ops_kern *, bpf_sock,
2532 struct bpf_map *, map, void *, key, u64, flags)
2534 WARN_ON_ONCE(!rcu_read_lock_held());
2535 return sock_hash_ctx_update_elem(bpf_sock, map, key, flags);
2538 const struct bpf_func_proto bpf_sock_hash_update_proto = {
2539 .func = bpf_sock_hash_update,
2542 .ret_type = RET_INTEGER,
2543 .arg1_type = ARG_PTR_TO_CTX,
2544 .arg2_type = ARG_CONST_MAP_PTR,
2545 .arg3_type = ARG_PTR_TO_MAP_KEY,
2546 .arg4_type = ARG_ANYTHING,