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;
65 struct hlist_head head;
71 struct bucket *buckets;
75 struct bpf_sock_progs progs;
81 struct hlist_node hash_node;
87 enum smap_psock_state {
91 struct smap_psock_map_entry {
92 struct list_head list;
95 struct htab_elem __rcu *hash_link;
102 /* datapath variables */
103 struct sk_buff_head rxqueue;
106 /* datapath error path cache across tx work invocations */
109 struct sk_buff *save_skb;
111 /* datapath variables for tx_msg ULP */
112 struct sock *sk_redir;
117 struct sk_msg_buff *cork;
118 struct list_head ingress;
120 struct strparser strp;
121 struct bpf_prog *bpf_tx_msg;
122 struct bpf_prog *bpf_parse;
123 struct bpf_prog *bpf_verdict;
124 struct list_head maps;
125 spinlock_t maps_lock;
127 /* Back reference used when sock callback trigger sockmap operations */
131 struct work_struct tx_work;
132 struct work_struct gc_work;
134 struct proto *sk_proto;
135 void (*save_close)(struct sock *sk, long timeout);
136 void (*save_data_ready)(struct sock *sk);
137 void (*save_write_space)(struct sock *sk);
140 static void smap_release_sock(struct smap_psock *psock, struct sock *sock);
141 static int bpf_tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
142 int nonblock, int flags, int *addr_len);
143 static int bpf_tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size);
144 static int bpf_tcp_sendpage(struct sock *sk, struct page *page,
145 int offset, size_t size, int flags);
146 static void bpf_tcp_close(struct sock *sk, long timeout);
148 static inline struct smap_psock *smap_psock_sk(const struct sock *sk)
150 return rcu_dereference_sk_user_data(sk);
153 static bool bpf_tcp_stream_read(const struct sock *sk)
155 struct smap_psock *psock;
159 psock = smap_psock_sk(sk);
160 if (unlikely(!psock))
162 empty = list_empty(&psock->ingress);
180 static struct proto *saved_tcpv6_prot __read_mostly;
181 static DEFINE_SPINLOCK(tcpv6_prot_lock);
182 static struct proto bpf_tcp_prots[SOCKMAP_NUM_PROTS][SOCKMAP_NUM_CONFIGS];
183 static void build_protos(struct proto prot[SOCKMAP_NUM_CONFIGS],
186 prot[SOCKMAP_BASE] = *base;
187 prot[SOCKMAP_BASE].close = bpf_tcp_close;
188 prot[SOCKMAP_BASE].recvmsg = bpf_tcp_recvmsg;
189 prot[SOCKMAP_BASE].stream_memory_read = bpf_tcp_stream_read;
191 prot[SOCKMAP_TX] = prot[SOCKMAP_BASE];
192 prot[SOCKMAP_TX].sendmsg = bpf_tcp_sendmsg;
193 prot[SOCKMAP_TX].sendpage = bpf_tcp_sendpage;
196 static void update_sk_prot(struct sock *sk, struct smap_psock *psock)
198 int family = sk->sk_family == AF_INET6 ? SOCKMAP_IPV6 : SOCKMAP_IPV4;
199 int conf = psock->bpf_tx_msg ? SOCKMAP_TX : SOCKMAP_BASE;
201 sk->sk_prot = &bpf_tcp_prots[family][conf];
204 static int bpf_tcp_init(struct sock *sk)
206 struct smap_psock *psock;
209 psock = smap_psock_sk(sk);
210 if (unlikely(!psock)) {
215 if (unlikely(psock->sk_proto)) {
220 psock->save_close = sk->sk_prot->close;
221 psock->sk_proto = sk->sk_prot;
223 /* Build IPv6 sockmap whenever the address of tcpv6_prot changes */
224 if (sk->sk_family == AF_INET6 &&
225 unlikely(sk->sk_prot != smp_load_acquire(&saved_tcpv6_prot))) {
226 spin_lock_bh(&tcpv6_prot_lock);
227 if (likely(sk->sk_prot != saved_tcpv6_prot)) {
228 build_protos(bpf_tcp_prots[SOCKMAP_IPV6], sk->sk_prot);
229 smp_store_release(&saved_tcpv6_prot, sk->sk_prot);
231 spin_unlock_bh(&tcpv6_prot_lock);
233 update_sk_prot(sk, psock);
238 static void smap_release_sock(struct smap_psock *psock, struct sock *sock);
239 static int free_start_sg(struct sock *sk, struct sk_msg_buff *md);
241 static void bpf_tcp_release(struct sock *sk)
243 struct smap_psock *psock;
246 psock = smap_psock_sk(sk);
247 if (unlikely(!psock))
251 free_start_sg(psock->sock, psock->cork);
256 if (psock->sk_proto) {
257 sk->sk_prot = psock->sk_proto;
258 psock->sk_proto = NULL;
264 static struct htab_elem *lookup_elem_raw(struct hlist_head *head,
265 u32 hash, void *key, u32 key_size)
269 hlist_for_each_entry_rcu(l, head, hash_node) {
270 if (l->hash == hash && !memcmp(&l->key, key, key_size))
277 static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash)
279 return &htab->buckets[hash & (htab->n_buckets - 1)];
282 static inline struct hlist_head *select_bucket(struct bpf_htab *htab, u32 hash)
284 return &__select_bucket(htab, hash)->head;
287 static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l)
289 atomic_dec(&htab->count);
293 static struct smap_psock_map_entry *psock_map_pop(struct sock *sk,
294 struct smap_psock *psock)
296 struct smap_psock_map_entry *e;
298 spin_lock_bh(&psock->maps_lock);
299 e = list_first_entry_or_null(&psock->maps,
300 struct smap_psock_map_entry,
304 spin_unlock_bh(&psock->maps_lock);
308 static void bpf_tcp_close(struct sock *sk, long timeout)
310 void (*close_fun)(struct sock *sk, long timeout);
311 struct smap_psock_map_entry *e;
312 struct sk_msg_buff *md, *mtmp;
313 struct smap_psock *psock;
318 psock = smap_psock_sk(sk);
319 if (unlikely(!psock)) {
322 return sk->sk_prot->close(sk, timeout);
325 /* The psock may be destroyed anytime after exiting the RCU critial
326 * section so by the time we use close_fun the psock may no longer
327 * be valid. However, bpf_tcp_close is called with the sock lock
328 * held so the close hook and sk are still valid.
330 close_fun = psock->save_close;
333 free_start_sg(psock->sock, psock->cork);
338 list_for_each_entry_safe(md, mtmp, &psock->ingress, list) {
340 free_start_sg(psock->sock, md);
344 e = psock_map_pop(sk, psock);
347 struct bpf_stab *stab = container_of(e->map, struct bpf_stab, map);
349 raw_spin_lock_bh(&stab->lock);
353 smap_release_sock(psock, sk);
355 raw_spin_unlock_bh(&stab->lock);
357 struct htab_elem *link = rcu_dereference(e->hash_link);
358 struct bpf_htab *htab = container_of(e->map, struct bpf_htab, map);
359 struct hlist_head *head;
363 b = __select_bucket(htab, link->hash);
365 raw_spin_lock_bh(&b->lock);
366 l = lookup_elem_raw(head,
367 link->hash, link->key,
369 /* If another thread deleted this object skip deletion.
370 * The refcnt on psock may or may not be zero.
373 hlist_del_rcu(&link->hash_node);
374 smap_release_sock(psock, link->sk);
375 free_htab_elem(htab, link);
377 raw_spin_unlock_bh(&b->lock);
380 e = psock_map_pop(sk, psock);
384 close_fun(sk, timeout);
394 static struct tcp_ulp_ops bpf_tcp_ulp_ops __read_mostly = {
397 .user_visible = false,
399 .init = bpf_tcp_init,
400 .release = bpf_tcp_release,
403 static int memcopy_from_iter(struct sock *sk,
404 struct sk_msg_buff *md,
405 struct iov_iter *from, int bytes)
407 struct scatterlist *sg = md->sg_data;
408 int i = md->sg_curr, rc = -ENOSPC;
414 if (md->sg_copybreak >= sg[i].length) {
415 md->sg_copybreak = 0;
417 if (++i == MAX_SKB_FRAGS)
424 copy = sg[i].length - md->sg_copybreak;
425 to = sg_virt(&sg[i]) + md->sg_copybreak;
426 md->sg_copybreak += copy;
428 if (sk->sk_route_caps & NETIF_F_NOCACHE_COPY)
429 rc = copy_from_iter_nocache(to, copy, from);
431 rc = copy_from_iter(to, copy, from);
442 md->sg_copybreak = 0;
443 if (++i == MAX_SKB_FRAGS)
445 } while (i != md->sg_end);
451 static int bpf_tcp_push(struct sock *sk, int apply_bytes,
452 struct sk_msg_buff *md,
453 int flags, bool uncharge)
455 bool apply = apply_bytes;
456 struct scatterlist *sg;
462 sg = md->sg_data + md->sg_start;
463 size = (apply && apply_bytes < sg->length) ?
464 apply_bytes : sg->length;
467 tcp_rate_check_app_limited(sk);
470 ret = do_tcp_sendpages(sk, p, offset, size, flags);
481 sk_mem_uncharge(sk, ret);
493 sk_mem_uncharge(sk, ret);
498 if (md->sg_start == MAX_SKB_FRAGS)
500 sg_init_table(sg, 1);
502 if (md->sg_start == md->sg_end)
506 if (apply && !apply_bytes)
512 static inline void bpf_compute_data_pointers_sg(struct sk_msg_buff *md)
514 struct scatterlist *sg = md->sg_data + md->sg_start;
516 if (md->sg_copy[md->sg_start]) {
517 md->data = md->data_end = 0;
519 md->data = sg_virt(sg);
520 md->data_end = md->data + sg->length;
524 static void return_mem_sg(struct sock *sk, int bytes, struct sk_msg_buff *md)
526 struct scatterlist *sg = md->sg_data;
527 int i = md->sg_start;
530 int uncharge = (bytes < sg[i].length) ? bytes : sg[i].length;
532 sk_mem_uncharge(sk, uncharge);
537 if (i == MAX_SKB_FRAGS)
539 } while (i != md->sg_end);
542 static void free_bytes_sg(struct sock *sk, int bytes,
543 struct sk_msg_buff *md, bool charge)
545 struct scatterlist *sg = md->sg_data;
546 int i = md->sg_start, free;
548 while (bytes && sg[i].length) {
551 sg[i].length -= bytes;
552 sg[i].offset += bytes;
554 sk_mem_uncharge(sk, bytes);
559 sk_mem_uncharge(sk, sg[i].length);
560 put_page(sg_page(&sg[i]));
561 bytes -= sg[i].length;
567 if (i == MAX_SKB_FRAGS)
573 static int free_sg(struct sock *sk, int start, struct sk_msg_buff *md)
575 struct scatterlist *sg = md->sg_data;
576 int i = start, free = 0;
578 while (sg[i].length) {
579 free += sg[i].length;
580 sk_mem_uncharge(sk, sg[i].length);
582 put_page(sg_page(&sg[i]));
588 if (i == MAX_SKB_FRAGS)
592 consume_skb(md->skb);
597 static int free_start_sg(struct sock *sk, struct sk_msg_buff *md)
599 int free = free_sg(sk, md->sg_start, md);
601 md->sg_start = md->sg_end;
605 static int free_curr_sg(struct sock *sk, struct sk_msg_buff *md)
607 return free_sg(sk, md->sg_curr, md);
610 static int bpf_map_msg_verdict(int _rc, struct sk_msg_buff *md)
612 return ((_rc == SK_PASS) ?
613 (md->sk_redir ? __SK_REDIRECT : __SK_PASS) :
617 static unsigned int smap_do_tx_msg(struct sock *sk,
618 struct smap_psock *psock,
619 struct sk_msg_buff *md)
621 struct bpf_prog *prog;
622 unsigned int rc, _rc;
627 /* If the policy was removed mid-send then default to 'accept' */
628 prog = READ_ONCE(psock->bpf_tx_msg);
629 if (unlikely(!prog)) {
634 bpf_compute_data_pointers_sg(md);
636 rc = (*prog->bpf_func)(md, prog->insnsi);
637 psock->apply_bytes = md->apply_bytes;
639 /* Moving return codes from UAPI namespace into internal namespace */
640 _rc = bpf_map_msg_verdict(rc, md);
642 /* The psock has a refcount on the sock but not on the map and because
643 * we need to drop rcu read lock here its possible the map could be
644 * removed between here and when we need it to execute the sock
645 * redirect. So do the map lookup now for future use.
647 if (_rc == __SK_REDIRECT) {
649 sock_put(psock->sk_redir);
650 psock->sk_redir = do_msg_redirect_map(md);
651 if (!psock->sk_redir) {
655 sock_hold(psock->sk_redir);
664 static int bpf_tcp_ingress(struct sock *sk, int apply_bytes,
665 struct smap_psock *psock,
666 struct sk_msg_buff *md, int flags)
668 bool apply = apply_bytes;
669 size_t size, copied = 0;
670 struct sk_msg_buff *r;
673 r = kzalloc(sizeof(struct sk_msg_buff), __GFP_NOWARN | GFP_KERNEL);
678 r->sg_start = md->sg_start;
682 size = (apply && apply_bytes < md->sg_data[i].length) ?
683 apply_bytes : md->sg_data[i].length;
685 if (!sk_wmem_schedule(sk, size)) {
691 sk_mem_charge(sk, size);
692 r->sg_data[i] = md->sg_data[i];
693 r->sg_data[i].length = size;
694 md->sg_data[i].length -= size;
695 md->sg_data[i].offset += size;
698 if (md->sg_data[i].length) {
699 get_page(sg_page(&r->sg_data[i]));
700 r->sg_end = (i + 1) == MAX_SKB_FRAGS ? 0 : i + 1;
703 if (i == MAX_SKB_FRAGS)
713 } while (i != md->sg_end);
718 list_add_tail(&r->list, &psock->ingress);
719 sk->sk_data_ready(sk);
721 free_start_sg(sk, r);
729 static int bpf_tcp_sendmsg_do_redirect(struct sock *sk, int send,
730 struct sk_msg_buff *md,
733 bool ingress = !!(md->flags & BPF_F_INGRESS);
734 struct smap_psock *psock;
738 psock = smap_psock_sk(sk);
739 if (unlikely(!psock))
742 if (!refcount_inc_not_zero(&psock->refcnt))
748 err = bpf_tcp_ingress(sk, send, psock, md, flags);
751 err = bpf_tcp_push(sk, send, md, flags, false);
754 smap_release_sock(psock, sk);
761 free_bytes_sg(NULL, send, md, false);
765 static inline void bpf_md_init(struct smap_psock *psock)
767 if (!psock->apply_bytes) {
768 psock->eval = __SK_NONE;
769 if (psock->sk_redir) {
770 sock_put(psock->sk_redir);
771 psock->sk_redir = NULL;
776 static void apply_bytes_dec(struct smap_psock *psock, int i)
778 if (psock->apply_bytes) {
779 if (psock->apply_bytes < i)
780 psock->apply_bytes = 0;
782 psock->apply_bytes -= i;
786 static int bpf_exec_tx_verdict(struct smap_psock *psock,
787 struct sk_msg_buff *m,
789 int *copied, int flags)
791 bool cork = false, enospc = (m->sg_start == m->sg_end);
797 if (psock->eval == __SK_NONE)
798 psock->eval = smap_do_tx_msg(sk, psock, m);
801 m->cork_bytes > psock->sg_size && !enospc) {
802 psock->cork_bytes = m->cork_bytes - psock->sg_size;
804 psock->cork = kcalloc(1,
805 sizeof(struct sk_msg_buff),
806 GFP_ATOMIC | __GFP_NOWARN);
813 memcpy(psock->cork, m, sizeof(*m));
817 send = psock->sg_size;
818 if (psock->apply_bytes && psock->apply_bytes < send)
819 send = psock->apply_bytes;
821 switch (psock->eval) {
823 err = bpf_tcp_push(sk, send, m, flags, true);
825 *copied -= free_start_sg(sk, m);
829 apply_bytes_dec(psock, send);
830 psock->sg_size -= send;
833 redir = psock->sk_redir;
834 apply_bytes_dec(psock, send);
841 return_mem_sg(sk, send, m);
844 err = bpf_tcp_sendmsg_do_redirect(redir, send, m, flags);
847 if (unlikely(err < 0)) {
848 free_start_sg(sk, m);
853 psock->sg_size -= send;
857 free_start_sg(sk, m);
866 free_bytes_sg(sk, send, m, true);
867 apply_bytes_dec(psock, send);
869 psock->sg_size -= send;
877 m->sg_data[m->sg_start].page_link &&
878 m->sg_data[m->sg_start].length)
886 static int bpf_wait_data(struct sock *sk,
887 struct smap_psock *psk, int flags,
888 long timeo, int *err)
892 DEFINE_WAIT_FUNC(wait, woken_wake_function);
894 add_wait_queue(sk_sleep(sk), &wait);
895 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
896 rc = sk_wait_event(sk, &timeo,
897 !list_empty(&psk->ingress) ||
898 !skb_queue_empty(&sk->sk_receive_queue),
900 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
901 remove_wait_queue(sk_sleep(sk), &wait);
906 static int bpf_tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,
907 int nonblock, int flags, int *addr_len)
909 struct iov_iter *iter = &msg->msg_iter;
910 struct smap_psock *psock;
913 if (unlikely(flags & MSG_ERRQUEUE))
914 return inet_recv_error(sk, msg, len, addr_len);
917 psock = smap_psock_sk(sk);
918 if (unlikely(!psock))
921 if (unlikely(!refcount_inc_not_zero(&psock->refcnt)))
925 if (!skb_queue_empty(&sk->sk_receive_queue))
926 return tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
930 while (copied != len) {
931 struct scatterlist *sg;
932 struct sk_msg_buff *md;
935 md = list_first_entry_or_null(&psock->ingress,
936 struct sk_msg_buff, list);
944 sg = &md->sg_data[i];
948 if (copied + copy > len)
951 n = copy_page_to_iter(page, sg->offset, copy, iter);
955 smap_release_sock(psock, sk);
962 sk_mem_uncharge(sk, copy);
966 if (i == MAX_SKB_FRAGS)
973 } while (i != md->sg_end);
976 if (!sg->length && md->sg_start == md->sg_end) {
979 consume_skb(md->skb);
989 timeo = sock_rcvtimeo(sk, nonblock);
990 data = bpf_wait_data(sk, psock, flags, timeo, &err);
993 if (!skb_queue_empty(&sk->sk_receive_queue)) {
995 smap_release_sock(psock, sk);
996 copied = tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
1007 smap_release_sock(psock, sk);
1011 return tcp_recvmsg(sk, msg, len, nonblock, flags, addr_len);
1015 static int bpf_tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)
1017 int flags = msg->msg_flags | MSG_NO_SHARED_FRAGS;
1018 struct sk_msg_buff md = {0};
1019 unsigned int sg_copy = 0;
1020 struct smap_psock *psock;
1021 int copied = 0, err = 0;
1022 struct scatterlist *sg;
1025 /* Its possible a sock event or user removed the psock _but_ the ops
1026 * have not been reprogrammed yet so we get here. In this case fallback
1027 * to tcp_sendmsg. Note this only works because we _only_ ever allow
1028 * a single ULP there is no hierarchy here.
1031 psock = smap_psock_sk(sk);
1032 if (unlikely(!psock)) {
1034 return tcp_sendmsg(sk, msg, size);
1037 /* Increment the psock refcnt to ensure its not released while sending a
1038 * message. Required because sk lookup and bpf programs are used in
1039 * separate rcu critical sections. Its OK if we lose the map entry
1040 * but we can't lose the sock reference.
1042 if (!refcount_inc_not_zero(&psock->refcnt)) {
1044 return tcp_sendmsg(sk, msg, size);
1048 sg_init_marker(sg, MAX_SKB_FRAGS);
1052 timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1054 while (msg_data_left(msg)) {
1055 struct sk_msg_buff *m = NULL;
1056 bool enospc = false;
1064 copy = msg_data_left(msg);
1065 if (!sk_stream_memory_free(sk))
1066 goto wait_for_sndbuf;
1068 m = psock->cork_bytes ? psock->cork : &md;
1069 m->sg_curr = m->sg_copybreak ? m->sg_curr : m->sg_end;
1070 err = sk_alloc_sg(sk, copy, m->sg_data,
1071 m->sg_start, &m->sg_end, &sg_copy,
1075 goto wait_for_memory;
1080 err = memcopy_from_iter(sk, m, &msg->msg_iter, copy);
1082 free_curr_sg(sk, m);
1086 psock->sg_size += copy;
1090 /* When bytes are being corked skip running BPF program and
1091 * applying verdict unless there is no more buffer space. In
1092 * the ENOSPC case simply run BPF prorgram with currently
1093 * accumulated data. We don't have much choice at this point
1094 * we could try extending the page frags or chaining complex
1095 * frags but even in these cases _eventually_ we will hit an
1096 * OOM scenario. More complex recovery schemes may be
1097 * implemented in the future, but BPF programs must handle
1098 * the case where apply_cork requests are not honored. The
1099 * canonical method to verify this is to check data length.
1101 if (psock->cork_bytes) {
1102 if (copy > psock->cork_bytes)
1103 psock->cork_bytes = 0;
1105 psock->cork_bytes -= copy;
1107 if (psock->cork_bytes && !enospc)
1110 /* All cork bytes accounted for re-run filter */
1111 psock->eval = __SK_NONE;
1112 psock->cork_bytes = 0;
1115 err = bpf_exec_tx_verdict(psock, m, sk, &copied, flags);
1116 if (unlikely(err < 0))
1120 set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
1122 err = sk_stream_wait_memory(sk, &timeo);
1124 if (m && m != psock->cork)
1125 free_start_sg(sk, m);
1131 err = sk_stream_error(sk, msg->msg_flags, err);
1134 smap_release_sock(psock, sk);
1135 return copied ? copied : err;
1138 static int bpf_tcp_sendpage(struct sock *sk, struct page *page,
1139 int offset, size_t size, int flags)
1141 struct sk_msg_buff md = {0}, *m = NULL;
1142 int err = 0, copied = 0;
1143 struct smap_psock *psock;
1144 struct scatterlist *sg;
1145 bool enospc = false;
1148 psock = smap_psock_sk(sk);
1149 if (unlikely(!psock))
1152 if (!refcount_inc_not_zero(&psock->refcnt))
1158 if (psock->cork_bytes) {
1160 sg = &m->sg_data[m->sg_end];
1164 sg_init_marker(sg, MAX_SKB_FRAGS);
1167 /* Catch case where ring is full and sendpage is stalled. */
1168 if (unlikely(m->sg_end == m->sg_start &&
1169 m->sg_data[m->sg_end].length))
1172 psock->sg_size += size;
1173 sg_set_page(sg, page, size, offset);
1175 m->sg_copy[m->sg_end] = true;
1176 sk_mem_charge(sk, size);
1180 if (m->sg_end == MAX_SKB_FRAGS)
1183 if (m->sg_end == m->sg_start)
1186 if (psock->cork_bytes) {
1187 if (size > psock->cork_bytes)
1188 psock->cork_bytes = 0;
1190 psock->cork_bytes -= size;
1192 if (psock->cork_bytes && !enospc)
1195 /* All cork bytes accounted for re-run filter */
1196 psock->eval = __SK_NONE;
1197 psock->cork_bytes = 0;
1200 err = bpf_exec_tx_verdict(psock, m, sk, &copied, flags);
1203 smap_release_sock(psock, sk);
1204 return copied ? copied : err;
1207 return tcp_sendpage(sk, page, offset, size, flags);
1210 static void bpf_tcp_msg_add(struct smap_psock *psock,
1212 struct bpf_prog *tx_msg)
1214 struct bpf_prog *orig_tx_msg;
1216 orig_tx_msg = xchg(&psock->bpf_tx_msg, tx_msg);
1218 bpf_prog_put(orig_tx_msg);
1221 static int bpf_tcp_ulp_register(void)
1223 build_protos(bpf_tcp_prots[SOCKMAP_IPV4], &tcp_prot);
1224 /* Once BPF TX ULP is registered it is never unregistered. It
1225 * will be in the ULP list for the lifetime of the system. Doing
1226 * duplicate registers is not a problem.
1228 return tcp_register_ulp(&bpf_tcp_ulp_ops);
1231 static int smap_verdict_func(struct smap_psock *psock, struct sk_buff *skb)
1233 struct bpf_prog *prog = READ_ONCE(psock->bpf_verdict);
1236 if (unlikely(!prog))
1240 /* We need to ensure that BPF metadata for maps is also cleared
1241 * when we orphan the skb so that we don't have the possibility
1242 * to reference a stale map.
1244 TCP_SKB_CB(skb)->bpf.sk_redir = NULL;
1245 skb->sk = psock->sock;
1246 bpf_compute_data_end_sk_skb(skb);
1248 rc = (*prog->bpf_func)(skb, prog->insnsi);
1252 /* Moving return codes from UAPI namespace into internal namespace */
1253 return rc == SK_PASS ?
1254 (TCP_SKB_CB(skb)->bpf.sk_redir ? __SK_REDIRECT : __SK_PASS) :
1258 static int smap_do_ingress(struct smap_psock *psock, struct sk_buff *skb)
1260 struct sock *sk = psock->sock;
1261 int copied = 0, num_sg;
1262 struct sk_msg_buff *r;
1264 r = kzalloc(sizeof(struct sk_msg_buff), __GFP_NOWARN | GFP_ATOMIC);
1268 if (!sk_rmem_schedule(sk, skb, skb->len)) {
1273 sg_init_table(r->sg_data, MAX_SKB_FRAGS);
1274 num_sg = skb_to_sgvec(skb, r->sg_data, 0, skb->len);
1275 if (unlikely(num_sg < 0)) {
1279 sk_mem_charge(sk, skb->len);
1282 r->sg_end = num_sg == MAX_SKB_FRAGS ? 0 : num_sg;
1284 list_add_tail(&r->list, &psock->ingress);
1285 sk->sk_data_ready(sk);
1289 static void smap_do_verdict(struct smap_psock *psock, struct sk_buff *skb)
1291 struct smap_psock *peer;
1296 rc = smap_verdict_func(psock, skb);
1299 sk = do_sk_redirect_map(skb);
1305 peer = smap_psock_sk(sk);
1306 in = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
1308 if (unlikely(!peer || sock_flag(sk, SOCK_DEAD) ||
1309 !test_bit(SMAP_TX_RUNNING, &peer->state))) {
1314 if (!in && sock_writeable(sk)) {
1315 skb_set_owner_w(skb, sk);
1316 skb_queue_tail(&peer->rxqueue, skb);
1317 schedule_work(&peer->tx_work);
1320 atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) {
1321 skb_queue_tail(&peer->rxqueue, skb);
1322 schedule_work(&peer->tx_work);
1325 /* Fall through and free skb otherwise */
1332 static void smap_report_sk_error(struct smap_psock *psock, int err)
1334 struct sock *sk = psock->sock;
1337 sk->sk_error_report(sk);
1340 static void smap_read_sock_strparser(struct strparser *strp,
1341 struct sk_buff *skb)
1343 struct smap_psock *psock;
1346 psock = container_of(strp, struct smap_psock, strp);
1347 smap_do_verdict(psock, skb);
1351 /* Called with lock held on socket */
1352 static void smap_data_ready(struct sock *sk)
1354 struct smap_psock *psock;
1357 psock = smap_psock_sk(sk);
1358 if (likely(psock)) {
1359 write_lock_bh(&sk->sk_callback_lock);
1360 strp_data_ready(&psock->strp);
1361 write_unlock_bh(&sk->sk_callback_lock);
1366 static void smap_tx_work(struct work_struct *w)
1368 struct smap_psock *psock;
1369 struct sk_buff *skb;
1372 psock = container_of(w, struct smap_psock, tx_work);
1374 /* lock sock to avoid losing sk_socket at some point during loop */
1375 lock_sock(psock->sock);
1376 if (psock->save_skb) {
1377 skb = psock->save_skb;
1378 rem = psock->save_rem;
1379 off = psock->save_off;
1380 psock->save_skb = NULL;
1384 while ((skb = skb_dequeue(&psock->rxqueue))) {
1390 flags = (TCP_SKB_CB(skb)->bpf.flags) & BPF_F_INGRESS;
1392 if (likely(psock->sock->sk_socket)) {
1394 n = smap_do_ingress(psock, skb);
1396 n = skb_send_sock_locked(psock->sock,
1404 /* Retry when space is available */
1405 psock->save_skb = skb;
1406 psock->save_rem = rem;
1407 psock->save_off = off;
1410 /* Hard errors break pipe and stop xmit */
1411 smap_report_sk_error(psock, n ? -n : EPIPE);
1412 clear_bit(SMAP_TX_RUNNING, &psock->state);
1424 release_sock(psock->sock);
1427 static void smap_write_space(struct sock *sk)
1429 struct smap_psock *psock;
1432 psock = smap_psock_sk(sk);
1433 if (likely(psock && test_bit(SMAP_TX_RUNNING, &psock->state)))
1434 schedule_work(&psock->tx_work);
1438 static void smap_stop_sock(struct smap_psock *psock, struct sock *sk)
1440 if (!psock->strp_enabled)
1442 sk->sk_data_ready = psock->save_data_ready;
1443 sk->sk_write_space = psock->save_write_space;
1444 psock->save_data_ready = NULL;
1445 psock->save_write_space = NULL;
1446 strp_stop(&psock->strp);
1447 psock->strp_enabled = false;
1450 static void smap_destroy_psock(struct rcu_head *rcu)
1452 struct smap_psock *psock = container_of(rcu,
1453 struct smap_psock, rcu);
1455 /* Now that a grace period has passed there is no longer
1456 * any reference to this sock in the sockmap so we can
1457 * destroy the psock, strparser, and bpf programs. But,
1458 * because we use workqueue sync operations we can not
1459 * do it in rcu context
1461 schedule_work(&psock->gc_work);
1464 static void smap_release_sock(struct smap_psock *psock, struct sock *sock)
1466 if (refcount_dec_and_test(&psock->refcnt)) {
1467 tcp_cleanup_ulp(sock);
1468 write_lock_bh(&sock->sk_callback_lock);
1469 smap_stop_sock(psock, sock);
1470 write_unlock_bh(&sock->sk_callback_lock);
1471 clear_bit(SMAP_TX_RUNNING, &psock->state);
1472 rcu_assign_sk_user_data(sock, NULL);
1473 call_rcu_sched(&psock->rcu, smap_destroy_psock);
1477 static int smap_parse_func_strparser(struct strparser *strp,
1478 struct sk_buff *skb)
1480 struct smap_psock *psock;
1481 struct bpf_prog *prog;
1485 psock = container_of(strp, struct smap_psock, strp);
1486 prog = READ_ONCE(psock->bpf_parse);
1488 if (unlikely(!prog)) {
1493 /* Attach socket for bpf program to use if needed we can do this
1494 * because strparser clones the skb before handing it to a upper
1495 * layer, meaning skb_orphan has been called. We NULL sk on the
1496 * way out to ensure we don't trigger a BUG_ON in skb/sk operations
1497 * later and because we are not charging the memory of this skb to
1500 skb->sk = psock->sock;
1501 bpf_compute_data_end_sk_skb(skb);
1502 rc = (*prog->bpf_func)(skb, prog->insnsi);
1508 static int smap_read_sock_done(struct strparser *strp, int err)
1513 static int smap_init_sock(struct smap_psock *psock,
1516 static const struct strp_callbacks cb = {
1517 .rcv_msg = smap_read_sock_strparser,
1518 .parse_msg = smap_parse_func_strparser,
1519 .read_sock_done = smap_read_sock_done,
1522 return strp_init(&psock->strp, sk, &cb);
1525 static void smap_init_progs(struct smap_psock *psock,
1526 struct bpf_prog *verdict,
1527 struct bpf_prog *parse)
1529 struct bpf_prog *orig_parse, *orig_verdict;
1531 orig_parse = xchg(&psock->bpf_parse, parse);
1532 orig_verdict = xchg(&psock->bpf_verdict, verdict);
1535 bpf_prog_put(orig_verdict);
1537 bpf_prog_put(orig_parse);
1540 static void smap_start_sock(struct smap_psock *psock, struct sock *sk)
1542 if (sk->sk_data_ready == smap_data_ready)
1544 psock->save_data_ready = sk->sk_data_ready;
1545 psock->save_write_space = sk->sk_write_space;
1546 sk->sk_data_ready = smap_data_ready;
1547 sk->sk_write_space = smap_write_space;
1548 psock->strp_enabled = true;
1551 static void sock_map_remove_complete(struct bpf_stab *stab)
1553 bpf_map_area_free(stab->sock_map);
1557 static void smap_gc_work(struct work_struct *w)
1559 struct smap_psock_map_entry *e, *tmp;
1560 struct sk_msg_buff *md, *mtmp;
1561 struct smap_psock *psock;
1563 psock = container_of(w, struct smap_psock, gc_work);
1565 /* no callback lock needed because we already detached sockmap ops */
1566 if (psock->strp_enabled)
1567 strp_done(&psock->strp);
1569 cancel_work_sync(&psock->tx_work);
1570 __skb_queue_purge(&psock->rxqueue);
1572 /* At this point all strparser and xmit work must be complete */
1573 if (psock->bpf_parse)
1574 bpf_prog_put(psock->bpf_parse);
1575 if (psock->bpf_verdict)
1576 bpf_prog_put(psock->bpf_verdict);
1577 if (psock->bpf_tx_msg)
1578 bpf_prog_put(psock->bpf_tx_msg);
1581 free_start_sg(psock->sock, psock->cork);
1585 list_for_each_entry_safe(md, mtmp, &psock->ingress, list) {
1586 list_del(&md->list);
1587 free_start_sg(psock->sock, md);
1591 list_for_each_entry_safe(e, tmp, &psock->maps, list) {
1596 if (psock->sk_redir)
1597 sock_put(psock->sk_redir);
1599 sock_put(psock->sock);
1603 static struct smap_psock *smap_init_psock(struct sock *sock, int node)
1605 struct smap_psock *psock;
1607 psock = kzalloc_node(sizeof(struct smap_psock),
1608 GFP_ATOMIC | __GFP_NOWARN,
1611 return ERR_PTR(-ENOMEM);
1613 psock->eval = __SK_NONE;
1615 skb_queue_head_init(&psock->rxqueue);
1616 INIT_WORK(&psock->tx_work, smap_tx_work);
1617 INIT_WORK(&psock->gc_work, smap_gc_work);
1618 INIT_LIST_HEAD(&psock->maps);
1619 INIT_LIST_HEAD(&psock->ingress);
1620 refcount_set(&psock->refcnt, 1);
1621 spin_lock_init(&psock->maps_lock);
1623 rcu_assign_sk_user_data(sock, psock);
1628 static struct bpf_map *sock_map_alloc(union bpf_attr *attr)
1630 struct bpf_stab *stab;
1634 if (!capable(CAP_NET_ADMIN))
1635 return ERR_PTR(-EPERM);
1637 /* check sanity of attributes */
1638 if (attr->max_entries == 0 || attr->key_size != 4 ||
1639 attr->value_size != 4 || attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
1640 return ERR_PTR(-EINVAL);
1642 err = bpf_tcp_ulp_register();
1643 if (err && err != -EEXIST)
1644 return ERR_PTR(err);
1646 stab = kzalloc(sizeof(*stab), GFP_USER);
1648 return ERR_PTR(-ENOMEM);
1650 bpf_map_init_from_attr(&stab->map, attr);
1651 raw_spin_lock_init(&stab->lock);
1653 /* make sure page count doesn't overflow */
1654 cost = (u64) stab->map.max_entries * sizeof(struct sock *);
1656 if (cost >= U32_MAX - PAGE_SIZE)
1659 stab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
1661 /* if map size is larger than memlock limit, reject it early */
1662 err = bpf_map_precharge_memlock(stab->map.pages);
1667 stab->sock_map = bpf_map_area_alloc(stab->map.max_entries *
1668 sizeof(struct sock *),
1669 stab->map.numa_node);
1670 if (!stab->sock_map)
1676 return ERR_PTR(err);
1679 static void smap_list_map_remove(struct smap_psock *psock,
1680 struct sock **entry)
1682 struct smap_psock_map_entry *e, *tmp;
1684 spin_lock_bh(&psock->maps_lock);
1685 list_for_each_entry_safe(e, tmp, &psock->maps, list) {
1686 if (e->entry == entry) {
1691 spin_unlock_bh(&psock->maps_lock);
1694 static void smap_list_hash_remove(struct smap_psock *psock,
1695 struct htab_elem *hash_link)
1697 struct smap_psock_map_entry *e, *tmp;
1699 spin_lock_bh(&psock->maps_lock);
1700 list_for_each_entry_safe(e, tmp, &psock->maps, list) {
1701 struct htab_elem *c = rcu_dereference(e->hash_link);
1703 if (c == hash_link) {
1708 spin_unlock_bh(&psock->maps_lock);
1711 static void sock_map_free(struct bpf_map *map)
1713 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1718 /* At this point no update, lookup or delete operations can happen.
1719 * However, be aware we can still get a socket state event updates,
1720 * and data ready callabacks that reference the psock from sk_user_data
1721 * Also psock worker threads are still in-flight. So smap_release_sock
1722 * will only free the psock after cancel_sync on the worker threads
1723 * and a grace period expire to ensure psock is really safe to remove.
1726 raw_spin_lock_bh(&stab->lock);
1727 for (i = 0; i < stab->map.max_entries; i++) {
1728 struct smap_psock *psock;
1731 sock = stab->sock_map[i];
1734 stab->sock_map[i] = NULL;
1735 psock = smap_psock_sk(sock);
1736 /* This check handles a racing sock event that can get the
1737 * sk_callback_lock before this case but after xchg happens
1738 * causing the refcnt to hit zero and sock user data (psock)
1739 * to be null and queued for garbage collection.
1741 if (likely(psock)) {
1742 smap_list_map_remove(psock, &stab->sock_map[i]);
1743 smap_release_sock(psock, sock);
1746 raw_spin_unlock_bh(&stab->lock);
1749 sock_map_remove_complete(stab);
1752 static int sock_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
1754 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1755 u32 i = key ? *(u32 *)key : U32_MAX;
1756 u32 *next = (u32 *)next_key;
1758 if (i >= stab->map.max_entries) {
1763 if (i == stab->map.max_entries - 1)
1770 struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
1772 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1774 if (key >= map->max_entries)
1777 return READ_ONCE(stab->sock_map[key]);
1780 static int sock_map_delete_elem(struct bpf_map *map, void *key)
1782 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1783 struct smap_psock *psock;
1784 int k = *(u32 *)key;
1787 if (k >= map->max_entries)
1790 raw_spin_lock_bh(&stab->lock);
1791 sock = stab->sock_map[k];
1792 stab->sock_map[k] = NULL;
1793 raw_spin_unlock_bh(&stab->lock);
1797 psock = smap_psock_sk(sock);
1800 if (psock->bpf_parse) {
1801 write_lock_bh(&sock->sk_callback_lock);
1802 smap_stop_sock(psock, sock);
1803 write_unlock_bh(&sock->sk_callback_lock);
1805 smap_list_map_remove(psock, &stab->sock_map[k]);
1806 smap_release_sock(psock, sock);
1810 /* Locking notes: Concurrent updates, deletes, and lookups are allowed and are
1811 * done inside rcu critical sections. This ensures on updates that the psock
1812 * will not be released via smap_release_sock() until concurrent updates/deletes
1813 * complete. All operations operate on sock_map using cmpxchg and xchg
1814 * operations to ensure we do not get stale references. Any reads into the
1815 * map must be done with READ_ONCE() because of this.
1817 * A psock is destroyed via call_rcu and after any worker threads are cancelled
1818 * and syncd so we are certain all references from the update/lookup/delete
1819 * operations as well as references in the data path are no longer in use.
1821 * Psocks may exist in multiple maps, but only a single set of parse/verdict
1822 * programs may be inherited from the maps it belongs to. A reference count
1823 * is kept with the total number of references to the psock from all maps. The
1824 * psock will not be released until this reaches zero. The psock and sock
1825 * user data data use the sk_callback_lock to protect critical data structures
1826 * from concurrent access. This allows us to avoid two updates from modifying
1827 * the user data in sock and the lock is required anyways for modifying
1828 * callbacks, we simply increase its scope slightly.
1831 * - psock must always be read inside RCU critical section
1832 * - sk_user_data must only be modified inside sk_callback_lock and read
1833 * inside RCU critical section.
1834 * - psock->maps list must only be read & modified inside sk_callback_lock
1835 * - sock_map must use READ_ONCE and (cmp)xchg operations
1836 * - BPF verdict/parse programs must use READ_ONCE and xchg operations
1839 static int __sock_map_ctx_update_elem(struct bpf_map *map,
1840 struct bpf_sock_progs *progs,
1844 struct bpf_prog *verdict, *parse, *tx_msg;
1845 struct smap_psock *psock;
1849 /* 1. If sock map has BPF programs those will be inherited by the
1850 * sock being added. If the sock is already attached to BPF programs
1851 * this results in an error.
1853 verdict = READ_ONCE(progs->bpf_verdict);
1854 parse = READ_ONCE(progs->bpf_parse);
1855 tx_msg = READ_ONCE(progs->bpf_tx_msg);
1857 if (parse && verdict) {
1858 /* bpf prog refcnt may be zero if a concurrent attach operation
1859 * removes the program after the above READ_ONCE() but before
1860 * we increment the refcnt. If this is the case abort with an
1863 verdict = bpf_prog_inc_not_zero(verdict);
1864 if (IS_ERR(verdict))
1865 return PTR_ERR(verdict);
1867 parse = bpf_prog_inc_not_zero(parse);
1868 if (IS_ERR(parse)) {
1869 bpf_prog_put(verdict);
1870 return PTR_ERR(parse);
1875 tx_msg = bpf_prog_inc_not_zero(tx_msg);
1876 if (IS_ERR(tx_msg)) {
1877 if (parse && verdict) {
1878 bpf_prog_put(parse);
1879 bpf_prog_put(verdict);
1881 return PTR_ERR(tx_msg);
1885 psock = smap_psock_sk(sock);
1887 /* 2. Do not allow inheriting programs if psock exists and has
1888 * already inherited programs. This would create confusion on
1889 * which parser/verdict program is running. If no psock exists
1890 * create one. Inside sk_callback_lock to ensure concurrent create
1891 * doesn't update user data.
1894 if (READ_ONCE(psock->bpf_parse) && parse) {
1898 if (READ_ONCE(psock->bpf_tx_msg) && tx_msg) {
1902 if (!refcount_inc_not_zero(&psock->refcnt)) {
1907 psock = smap_init_psock(sock, map->numa_node);
1908 if (IS_ERR(psock)) {
1909 err = PTR_ERR(psock);
1913 set_bit(SMAP_TX_RUNNING, &psock->state);
1917 /* 3. At this point we have a reference to a valid psock that is
1918 * running. Attach any BPF programs needed.
1921 bpf_tcp_msg_add(psock, sock, tx_msg);
1923 err = tcp_set_ulp_id(sock, TCP_ULP_BPF);
1928 if (parse && verdict && !psock->strp_enabled) {
1929 err = smap_init_sock(psock, sock);
1932 smap_init_progs(psock, verdict, parse);
1933 write_lock_bh(&sock->sk_callback_lock);
1934 smap_start_sock(psock, sock);
1935 write_unlock_bh(&sock->sk_callback_lock);
1940 smap_release_sock(psock, sock);
1942 if (parse && verdict) {
1943 bpf_prog_put(parse);
1944 bpf_prog_put(verdict);
1947 bpf_prog_put(tx_msg);
1951 static int sock_map_ctx_update_elem(struct bpf_sock_ops_kern *skops,
1952 struct bpf_map *map,
1953 void *key, u64 flags)
1955 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
1956 struct bpf_sock_progs *progs = &stab->progs;
1957 struct sock *osock, *sock = skops->sk;
1958 struct smap_psock_map_entry *e;
1959 struct smap_psock *psock;
1960 u32 i = *(u32 *)key;
1963 if (unlikely(flags > BPF_EXIST))
1965 if (unlikely(i >= stab->map.max_entries))
1968 e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
1972 err = __sock_map_ctx_update_elem(map, progs, sock, key);
1976 /* psock guaranteed to be present. */
1977 psock = smap_psock_sk(sock);
1978 raw_spin_lock_bh(&stab->lock);
1979 osock = stab->sock_map[i];
1980 if (osock && flags == BPF_NOEXIST) {
1984 if (!osock && flags == BPF_EXIST) {
1989 e->entry = &stab->sock_map[i];
1991 spin_lock_bh(&psock->maps_lock);
1992 list_add_tail(&e->list, &psock->maps);
1993 spin_unlock_bh(&psock->maps_lock);
1995 stab->sock_map[i] = sock;
1997 psock = smap_psock_sk(osock);
1998 smap_list_map_remove(psock, &stab->sock_map[i]);
1999 smap_release_sock(psock, osock);
2001 raw_spin_unlock_bh(&stab->lock);
2004 smap_release_sock(psock, sock);
2005 raw_spin_unlock_bh(&stab->lock);
2011 int sock_map_prog(struct bpf_map *map, struct bpf_prog *prog, u32 type)
2013 struct bpf_sock_progs *progs;
2014 struct bpf_prog *orig;
2016 if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
2017 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
2019 progs = &stab->progs;
2020 } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2021 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2023 progs = &htab->progs;
2029 case BPF_SK_MSG_VERDICT:
2030 orig = xchg(&progs->bpf_tx_msg, prog);
2032 case BPF_SK_SKB_STREAM_PARSER:
2033 orig = xchg(&progs->bpf_parse, prog);
2035 case BPF_SK_SKB_STREAM_VERDICT:
2036 orig = xchg(&progs->bpf_verdict, prog);
2048 int sockmap_get_from_fd(const union bpf_attr *attr, int type,
2049 struct bpf_prog *prog)
2051 int ufd = attr->target_fd;
2052 struct bpf_map *map;
2057 map = __bpf_map_get(f);
2059 return PTR_ERR(map);
2061 err = sock_map_prog(map, prog, attr->attach_type);
2066 static void *sock_map_lookup(struct bpf_map *map, void *key)
2071 static int sock_map_update_elem(struct bpf_map *map,
2072 void *key, void *value, u64 flags)
2074 struct bpf_sock_ops_kern skops;
2075 u32 fd = *(u32 *)value;
2076 struct socket *socket;
2079 socket = sockfd_lookup(fd, &err);
2083 skops.sk = socket->sk;
2089 if (skops.sk->sk_type != SOCK_STREAM ||
2090 skops.sk->sk_protocol != IPPROTO_TCP) {
2095 lock_sock(skops.sk);
2098 err = sock_map_ctx_update_elem(&skops, map, key, flags);
2101 release_sock(skops.sk);
2106 static void sock_map_release(struct bpf_map *map)
2108 struct bpf_sock_progs *progs;
2109 struct bpf_prog *orig;
2111 if (map->map_type == BPF_MAP_TYPE_SOCKMAP) {
2112 struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
2114 progs = &stab->progs;
2116 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2118 progs = &htab->progs;
2121 orig = xchg(&progs->bpf_parse, NULL);
2124 orig = xchg(&progs->bpf_verdict, NULL);
2128 orig = xchg(&progs->bpf_tx_msg, NULL);
2133 static struct bpf_map *sock_hash_alloc(union bpf_attr *attr)
2135 struct bpf_htab *htab;
2139 if (!capable(CAP_NET_ADMIN))
2140 return ERR_PTR(-EPERM);
2142 /* check sanity of attributes */
2143 if (attr->max_entries == 0 || attr->value_size != 4 ||
2144 attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
2145 return ERR_PTR(-EINVAL);
2147 if (attr->key_size > MAX_BPF_STACK)
2148 /* eBPF programs initialize keys on stack, so they cannot be
2149 * larger than max stack size
2151 return ERR_PTR(-E2BIG);
2153 err = bpf_tcp_ulp_register();
2154 if (err && err != -EEXIST)
2155 return ERR_PTR(err);
2157 htab = kzalloc(sizeof(*htab), GFP_USER);
2159 return ERR_PTR(-ENOMEM);
2161 bpf_map_init_from_attr(&htab->map, attr);
2163 htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
2164 htab->elem_size = sizeof(struct htab_elem) +
2165 round_up(htab->map.key_size, 8);
2167 if (htab->n_buckets == 0 ||
2168 htab->n_buckets > U32_MAX / sizeof(struct bucket))
2171 cost = (u64) htab->n_buckets * sizeof(struct bucket) +
2172 (u64) htab->elem_size * htab->map.max_entries;
2174 if (cost >= U32_MAX - PAGE_SIZE)
2177 htab->map.pages = round_up(cost, PAGE_SIZE) >> PAGE_SHIFT;
2178 err = bpf_map_precharge_memlock(htab->map.pages);
2183 htab->buckets = bpf_map_area_alloc(
2184 htab->n_buckets * sizeof(struct bucket),
2185 htab->map.numa_node);
2189 for (i = 0; i < htab->n_buckets; i++) {
2190 INIT_HLIST_HEAD(&htab->buckets[i].head);
2191 raw_spin_lock_init(&htab->buckets[i].lock);
2197 return ERR_PTR(err);
2200 static void __bpf_htab_free(struct rcu_head *rcu)
2202 struct bpf_htab *htab;
2204 htab = container_of(rcu, struct bpf_htab, rcu);
2205 bpf_map_area_free(htab->buckets);
2209 static void sock_hash_free(struct bpf_map *map)
2211 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2216 /* At this point no update, lookup or delete operations can happen.
2217 * However, be aware we can still get a socket state event updates,
2218 * and data ready callabacks that reference the psock from sk_user_data
2219 * Also psock worker threads are still in-flight. So smap_release_sock
2220 * will only free the psock after cancel_sync on the worker threads
2221 * and a grace period expire to ensure psock is really safe to remove.
2224 for (i = 0; i < htab->n_buckets; i++) {
2225 struct bucket *b = __select_bucket(htab, i);
2226 struct hlist_head *head;
2227 struct hlist_node *n;
2228 struct htab_elem *l;
2230 raw_spin_lock_bh(&b->lock);
2232 hlist_for_each_entry_safe(l, n, head, hash_node) {
2233 struct sock *sock = l->sk;
2234 struct smap_psock *psock;
2236 hlist_del_rcu(&l->hash_node);
2237 psock = smap_psock_sk(sock);
2238 /* This check handles a racing sock event that can get
2239 * the sk_callback_lock before this case but after xchg
2240 * causing the refcnt to hit zero and sock user data
2241 * (psock) to be null and queued for garbage collection.
2243 if (likely(psock)) {
2244 smap_list_hash_remove(psock, l);
2245 smap_release_sock(psock, sock);
2247 free_htab_elem(htab, l);
2249 raw_spin_unlock_bh(&b->lock);
2252 call_rcu(&htab->rcu, __bpf_htab_free);
2255 static struct htab_elem *alloc_sock_hash_elem(struct bpf_htab *htab,
2256 void *key, u32 key_size, u32 hash,
2258 struct htab_elem *old_elem)
2260 struct htab_elem *l_new;
2262 if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
2264 atomic_dec(&htab->count);
2265 return ERR_PTR(-E2BIG);
2268 l_new = kmalloc_node(htab->elem_size, GFP_ATOMIC | __GFP_NOWARN,
2269 htab->map.numa_node);
2271 return ERR_PTR(-ENOMEM);
2273 memcpy(l_new->key, key, key_size);
2279 static inline u32 htab_map_hash(const void *key, u32 key_len)
2281 return jhash(key, key_len, 0);
2284 static int sock_hash_get_next_key(struct bpf_map *map,
2285 void *key, void *next_key)
2287 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2288 struct htab_elem *l, *next_l;
2289 struct hlist_head *h;
2293 WARN_ON_ONCE(!rcu_read_lock_held());
2295 key_size = map->key_size;
2297 goto find_first_elem;
2298 hash = htab_map_hash(key, key_size);
2299 h = select_bucket(htab, hash);
2301 l = lookup_elem_raw(h, hash, key, key_size);
2303 goto find_first_elem;
2304 next_l = hlist_entry_safe(
2305 rcu_dereference_raw(hlist_next_rcu(&l->hash_node)),
2306 struct htab_elem, hash_node);
2308 memcpy(next_key, next_l->key, key_size);
2312 /* no more elements in this hash list, go to the next bucket */
2313 i = hash & (htab->n_buckets - 1);
2317 /* iterate over buckets */
2318 for (; i < htab->n_buckets; i++) {
2319 h = select_bucket(htab, i);
2321 /* pick first element in the bucket */
2322 next_l = hlist_entry_safe(
2323 rcu_dereference_raw(hlist_first_rcu(h)),
2324 struct htab_elem, hash_node);
2326 /* if it's not empty, just return it */
2327 memcpy(next_key, next_l->key, key_size);
2332 /* iterated over all buckets and all elements */
2336 static int sock_hash_ctx_update_elem(struct bpf_sock_ops_kern *skops,
2337 struct bpf_map *map,
2338 void *key, u64 map_flags)
2340 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2341 struct bpf_sock_progs *progs = &htab->progs;
2342 struct htab_elem *l_new = NULL, *l_old;
2343 struct smap_psock_map_entry *e = NULL;
2344 struct hlist_head *head;
2345 struct smap_psock *psock;
2353 if (sock->sk_type != SOCK_STREAM ||
2354 sock->sk_protocol != IPPROTO_TCP)
2357 if (unlikely(map_flags > BPF_EXIST))
2360 e = kzalloc(sizeof(*e), GFP_ATOMIC | __GFP_NOWARN);
2364 WARN_ON_ONCE(!rcu_read_lock_held());
2365 key_size = map->key_size;
2366 hash = htab_map_hash(key, key_size);
2367 b = __select_bucket(htab, hash);
2370 err = __sock_map_ctx_update_elem(map, progs, sock, key);
2374 /* psock is valid here because otherwise above *ctx_update_elem would
2375 * have thrown an error. It is safe to skip error check.
2377 psock = smap_psock_sk(sock);
2378 raw_spin_lock_bh(&b->lock);
2379 l_old = lookup_elem_raw(head, hash, key, key_size);
2380 if (l_old && map_flags == BPF_NOEXIST) {
2384 if (!l_old && map_flags == BPF_EXIST) {
2389 l_new = alloc_sock_hash_elem(htab, key, key_size, hash, sock, l_old);
2390 if (IS_ERR(l_new)) {
2391 err = PTR_ERR(l_new);
2395 rcu_assign_pointer(e->hash_link, l_new);
2397 spin_lock_bh(&psock->maps_lock);
2398 list_add_tail(&e->list, &psock->maps);
2399 spin_unlock_bh(&psock->maps_lock);
2401 /* add new element to the head of the list, so that
2402 * concurrent search will find it before old elem
2404 hlist_add_head_rcu(&l_new->hash_node, head);
2406 psock = smap_psock_sk(l_old->sk);
2408 hlist_del_rcu(&l_old->hash_node);
2409 smap_list_hash_remove(psock, l_old);
2410 smap_release_sock(psock, l_old->sk);
2411 free_htab_elem(htab, l_old);
2413 raw_spin_unlock_bh(&b->lock);
2416 smap_release_sock(psock, sock);
2417 raw_spin_unlock_bh(&b->lock);
2423 static int sock_hash_update_elem(struct bpf_map *map,
2424 void *key, void *value, u64 flags)
2426 struct bpf_sock_ops_kern skops;
2427 u32 fd = *(u32 *)value;
2428 struct socket *socket;
2431 socket = sockfd_lookup(fd, &err);
2435 skops.sk = socket->sk;
2441 lock_sock(skops.sk);
2444 err = sock_hash_ctx_update_elem(&skops, map, key, flags);
2447 release_sock(skops.sk);
2452 static int sock_hash_delete_elem(struct bpf_map *map, void *key)
2454 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2455 struct hlist_head *head;
2457 struct htab_elem *l;
2461 key_size = map->key_size;
2462 hash = htab_map_hash(key, key_size);
2463 b = __select_bucket(htab, hash);
2466 raw_spin_lock_bh(&b->lock);
2467 l = lookup_elem_raw(head, hash, key, key_size);
2469 struct sock *sock = l->sk;
2470 struct smap_psock *psock;
2472 hlist_del_rcu(&l->hash_node);
2473 psock = smap_psock_sk(sock);
2474 /* This check handles a racing sock event that can get the
2475 * sk_callback_lock before this case but after xchg happens
2476 * causing the refcnt to hit zero and sock user data (psock)
2477 * to be null and queued for garbage collection.
2479 if (likely(psock)) {
2480 smap_list_hash_remove(psock, l);
2481 smap_release_sock(psock, sock);
2483 free_htab_elem(htab, l);
2486 raw_spin_unlock_bh(&b->lock);
2490 struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
2492 struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2493 struct hlist_head *head;
2494 struct htab_elem *l;
2499 key_size = map->key_size;
2500 hash = htab_map_hash(key, key_size);
2501 b = __select_bucket(htab, hash);
2504 l = lookup_elem_raw(head, hash, key, key_size);
2505 sk = l ? l->sk : NULL;
2509 const struct bpf_map_ops sock_map_ops = {
2510 .map_alloc = sock_map_alloc,
2511 .map_free = sock_map_free,
2512 .map_lookup_elem = sock_map_lookup,
2513 .map_get_next_key = sock_map_get_next_key,
2514 .map_update_elem = sock_map_update_elem,
2515 .map_delete_elem = sock_map_delete_elem,
2516 .map_release_uref = sock_map_release,
2517 .map_check_btf = map_check_no_btf,
2520 const struct bpf_map_ops sock_hash_ops = {
2521 .map_alloc = sock_hash_alloc,
2522 .map_free = sock_hash_free,
2523 .map_lookup_elem = sock_map_lookup,
2524 .map_get_next_key = sock_hash_get_next_key,
2525 .map_update_elem = sock_hash_update_elem,
2526 .map_delete_elem = sock_hash_delete_elem,
2527 .map_release_uref = sock_map_release,
2528 .map_check_btf = map_check_no_btf,
2531 BPF_CALL_4(bpf_sock_map_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_map_ctx_update_elem(bpf_sock, map, key, flags);
2538 const struct bpf_func_proto bpf_sock_map_update_proto = {
2539 .func = bpf_sock_map_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,
2549 BPF_CALL_4(bpf_sock_hash_update, struct bpf_sock_ops_kern *, bpf_sock,
2550 struct bpf_map *, map, void *, key, u64, flags)
2552 WARN_ON_ONCE(!rcu_read_lock_held());
2553 return sock_hash_ctx_update_elem(bpf_sock, map, key, flags);
2556 const struct bpf_func_proto bpf_sock_hash_update_proto = {
2557 .func = bpf_sock_hash_update,
2560 .ret_type = RET_INTEGER,
2561 .arg1_type = ARG_PTR_TO_CTX,
2562 .arg2_type = ARG_CONST_MAP_PTR,
2563 .arg3_type = ARG_PTR_TO_MAP_KEY,
2564 .arg4_type = ARG_ANYTHING,