sock_map: Rename skb_parser and skb_verdict
[linux-block.git] / net / core / sock_map.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2017 - 2018 Covalent IO, Inc. http://covalent.io */
3
4 #include <linux/bpf.h>
5 #include <linux/btf_ids.h>
6 #include <linux/filter.h>
7 #include <linux/errno.h>
8 #include <linux/file.h>
9 #include <linux/net.h>
10 #include <linux/workqueue.h>
11 #include <linux/skmsg.h>
12 #include <linux/list.h>
13 #include <linux/jhash.h>
14 #include <linux/sock_diag.h>
15 #include <net/udp.h>
16
17 struct bpf_stab {
18         struct bpf_map map;
19         struct sock **sks;
20         struct sk_psock_progs progs;
21         raw_spinlock_t lock;
22 };
23
24 #define SOCK_CREATE_FLAG_MASK                           \
25         (BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY)
26
27 static struct bpf_map *sock_map_alloc(union bpf_attr *attr)
28 {
29         struct bpf_stab *stab;
30
31         if (!capable(CAP_NET_ADMIN))
32                 return ERR_PTR(-EPERM);
33         if (attr->max_entries == 0 ||
34             attr->key_size    != 4 ||
35             (attr->value_size != sizeof(u32) &&
36              attr->value_size != sizeof(u64)) ||
37             attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
38                 return ERR_PTR(-EINVAL);
39
40         stab = kzalloc(sizeof(*stab), GFP_USER | __GFP_ACCOUNT);
41         if (!stab)
42                 return ERR_PTR(-ENOMEM);
43
44         bpf_map_init_from_attr(&stab->map, attr);
45         raw_spin_lock_init(&stab->lock);
46
47         stab->sks = bpf_map_area_alloc(stab->map.max_entries *
48                                        sizeof(struct sock *),
49                                        stab->map.numa_node);
50         if (!stab->sks) {
51                 kfree(stab);
52                 return ERR_PTR(-ENOMEM);
53         }
54
55         return &stab->map;
56 }
57
58 int sock_map_get_from_fd(const union bpf_attr *attr, struct bpf_prog *prog)
59 {
60         u32 ufd = attr->target_fd;
61         struct bpf_map *map;
62         struct fd f;
63         int ret;
64
65         if (attr->attach_flags || attr->replace_bpf_fd)
66                 return -EINVAL;
67
68         f = fdget(ufd);
69         map = __bpf_map_get(f);
70         if (IS_ERR(map))
71                 return PTR_ERR(map);
72         ret = sock_map_prog_update(map, prog, NULL, attr->attach_type);
73         fdput(f);
74         return ret;
75 }
76
77 int sock_map_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
78 {
79         u32 ufd = attr->target_fd;
80         struct bpf_prog *prog;
81         struct bpf_map *map;
82         struct fd f;
83         int ret;
84
85         if (attr->attach_flags || attr->replace_bpf_fd)
86                 return -EINVAL;
87
88         f = fdget(ufd);
89         map = __bpf_map_get(f);
90         if (IS_ERR(map))
91                 return PTR_ERR(map);
92
93         prog = bpf_prog_get(attr->attach_bpf_fd);
94         if (IS_ERR(prog)) {
95                 ret = PTR_ERR(prog);
96                 goto put_map;
97         }
98
99         if (prog->type != ptype) {
100                 ret = -EINVAL;
101                 goto put_prog;
102         }
103
104         ret = sock_map_prog_update(map, NULL, prog, attr->attach_type);
105 put_prog:
106         bpf_prog_put(prog);
107 put_map:
108         fdput(f);
109         return ret;
110 }
111
112 static void sock_map_sk_acquire(struct sock *sk)
113         __acquires(&sk->sk_lock.slock)
114 {
115         lock_sock(sk);
116         preempt_disable();
117         rcu_read_lock();
118 }
119
120 static void sock_map_sk_release(struct sock *sk)
121         __releases(&sk->sk_lock.slock)
122 {
123         rcu_read_unlock();
124         preempt_enable();
125         release_sock(sk);
126 }
127
128 static void sock_map_add_link(struct sk_psock *psock,
129                               struct sk_psock_link *link,
130                               struct bpf_map *map, void *link_raw)
131 {
132         link->link_raw = link_raw;
133         link->map = map;
134         spin_lock_bh(&psock->link_lock);
135         list_add_tail(&link->list, &psock->link);
136         spin_unlock_bh(&psock->link_lock);
137 }
138
139 static void sock_map_del_link(struct sock *sk,
140                               struct sk_psock *psock, void *link_raw)
141 {
142         bool strp_stop = false, verdict_stop = false;
143         struct sk_psock_link *link, *tmp;
144
145         spin_lock_bh(&psock->link_lock);
146         list_for_each_entry_safe(link, tmp, &psock->link, list) {
147                 if (link->link_raw == link_raw) {
148                         struct bpf_map *map = link->map;
149                         struct bpf_stab *stab = container_of(map, struct bpf_stab,
150                                                              map);
151                         if (psock->saved_data_ready && stab->progs.stream_parser)
152                                 strp_stop = true;
153                         if (psock->saved_data_ready && stab->progs.stream_verdict)
154                                 verdict_stop = true;
155                         list_del(&link->list);
156                         sk_psock_free_link(link);
157                 }
158         }
159         spin_unlock_bh(&psock->link_lock);
160         if (strp_stop || verdict_stop) {
161                 write_lock_bh(&sk->sk_callback_lock);
162                 if (strp_stop)
163                         sk_psock_stop_strp(sk, psock);
164                 else
165                         sk_psock_stop_verdict(sk, psock);
166                 write_unlock_bh(&sk->sk_callback_lock);
167         }
168 }
169
170 static void sock_map_unref(struct sock *sk, void *link_raw)
171 {
172         struct sk_psock *psock = sk_psock(sk);
173
174         if (likely(psock)) {
175                 sock_map_del_link(sk, psock, link_raw);
176                 sk_psock_put(sk, psock);
177         }
178 }
179
180 static int sock_map_init_proto(struct sock *sk, struct sk_psock *psock)
181 {
182         struct proto *prot;
183
184         switch (sk->sk_type) {
185         case SOCK_STREAM:
186                 prot = tcp_bpf_get_proto(sk, psock);
187                 break;
188
189         case SOCK_DGRAM:
190                 prot = udp_bpf_get_proto(sk, psock);
191                 break;
192
193         default:
194                 return -EINVAL;
195         }
196
197         if (IS_ERR(prot))
198                 return PTR_ERR(prot);
199
200         sk_psock_update_proto(sk, psock, prot);
201         return 0;
202 }
203
204 static struct sk_psock *sock_map_psock_get_checked(struct sock *sk)
205 {
206         struct sk_psock *psock;
207
208         rcu_read_lock();
209         psock = sk_psock(sk);
210         if (psock) {
211                 if (sk->sk_prot->close != sock_map_close) {
212                         psock = ERR_PTR(-EBUSY);
213                         goto out;
214                 }
215
216                 if (!refcount_inc_not_zero(&psock->refcnt))
217                         psock = ERR_PTR(-EBUSY);
218         }
219 out:
220         rcu_read_unlock();
221         return psock;
222 }
223
224 static int sock_map_link(struct bpf_map *map, struct sk_psock_progs *progs,
225                          struct sock *sk)
226 {
227         struct bpf_prog *msg_parser, *stream_parser, *stream_verdict;
228         struct sk_psock *psock;
229         int ret;
230
231         stream_verdict = READ_ONCE(progs->stream_verdict);
232         if (stream_verdict) {
233                 stream_verdict = bpf_prog_inc_not_zero(stream_verdict);
234                 if (IS_ERR(stream_verdict))
235                         return PTR_ERR(stream_verdict);
236         }
237
238         stream_parser = READ_ONCE(progs->stream_parser);
239         if (stream_parser) {
240                 stream_parser = bpf_prog_inc_not_zero(stream_parser);
241                 if (IS_ERR(stream_parser)) {
242                         ret = PTR_ERR(stream_parser);
243                         goto out_put_stream_verdict;
244                 }
245         }
246
247         msg_parser = READ_ONCE(progs->msg_parser);
248         if (msg_parser) {
249                 msg_parser = bpf_prog_inc_not_zero(msg_parser);
250                 if (IS_ERR(msg_parser)) {
251                         ret = PTR_ERR(msg_parser);
252                         goto out_put_stream_parser;
253                 }
254         }
255
256         psock = sock_map_psock_get_checked(sk);
257         if (IS_ERR(psock)) {
258                 ret = PTR_ERR(psock);
259                 goto out_progs;
260         }
261
262         if (psock) {
263                 if ((msg_parser && READ_ONCE(psock->progs.msg_parser)) ||
264                     (stream_parser  && READ_ONCE(psock->progs.stream_parser)) ||
265                     (stream_verdict && READ_ONCE(psock->progs.stream_verdict))) {
266                         sk_psock_put(sk, psock);
267                         ret = -EBUSY;
268                         goto out_progs;
269                 }
270         } else {
271                 psock = sk_psock_init(sk, map->numa_node);
272                 if (IS_ERR(psock)) {
273                         ret = PTR_ERR(psock);
274                         goto out_progs;
275                 }
276         }
277
278         if (msg_parser)
279                 psock_set_prog(&psock->progs.msg_parser, msg_parser);
280
281         ret = sock_map_init_proto(sk, psock);
282         if (ret < 0)
283                 goto out_drop;
284
285         write_lock_bh(&sk->sk_callback_lock);
286         if (stream_parser && stream_verdict && !psock->saved_data_ready) {
287                 ret = sk_psock_init_strp(sk, psock);
288                 if (ret)
289                         goto out_unlock_drop;
290                 psock_set_prog(&psock->progs.stream_verdict, stream_verdict);
291                 psock_set_prog(&psock->progs.stream_parser, stream_parser);
292                 sk_psock_start_strp(sk, psock);
293         } else if (!stream_parser && stream_verdict && !psock->saved_data_ready) {
294                 psock_set_prog(&psock->progs.stream_verdict, stream_verdict);
295                 sk_psock_start_verdict(sk,psock);
296         }
297         write_unlock_bh(&sk->sk_callback_lock);
298         return 0;
299 out_unlock_drop:
300         write_unlock_bh(&sk->sk_callback_lock);
301 out_drop:
302         sk_psock_put(sk, psock);
303 out_progs:
304         if (msg_parser)
305                 bpf_prog_put(msg_parser);
306 out_put_stream_parser:
307         if (stream_parser)
308                 bpf_prog_put(stream_parser);
309 out_put_stream_verdict:
310         if (stream_verdict)
311                 bpf_prog_put(stream_verdict);
312         return ret;
313 }
314
315 static int sock_map_link_no_progs(struct bpf_map *map, struct sock *sk)
316 {
317         struct sk_psock *psock;
318         int ret;
319
320         psock = sock_map_psock_get_checked(sk);
321         if (IS_ERR(psock))
322                 return PTR_ERR(psock);
323
324         if (!psock) {
325                 psock = sk_psock_init(sk, map->numa_node);
326                 if (IS_ERR(psock))
327                         return PTR_ERR(psock);
328         }
329
330         ret = sock_map_init_proto(sk, psock);
331         if (ret < 0)
332                 sk_psock_put(sk, psock);
333         return ret;
334 }
335
336 static void sock_map_free(struct bpf_map *map)
337 {
338         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
339         int i;
340
341         /* After the sync no updates or deletes will be in-flight so it
342          * is safe to walk map and remove entries without risking a race
343          * in EEXIST update case.
344          */
345         synchronize_rcu();
346         for (i = 0; i < stab->map.max_entries; i++) {
347                 struct sock **psk = &stab->sks[i];
348                 struct sock *sk;
349
350                 sk = xchg(psk, NULL);
351                 if (sk) {
352                         lock_sock(sk);
353                         rcu_read_lock();
354                         sock_map_unref(sk, psk);
355                         rcu_read_unlock();
356                         release_sock(sk);
357                 }
358         }
359
360         /* wait for psock readers accessing its map link */
361         synchronize_rcu();
362
363         bpf_map_area_free(stab->sks);
364         kfree(stab);
365 }
366
367 static void sock_map_release_progs(struct bpf_map *map)
368 {
369         psock_progs_drop(&container_of(map, struct bpf_stab, map)->progs);
370 }
371
372 static struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
373 {
374         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
375
376         WARN_ON_ONCE(!rcu_read_lock_held());
377
378         if (unlikely(key >= map->max_entries))
379                 return NULL;
380         return READ_ONCE(stab->sks[key]);
381 }
382
383 static void *sock_map_lookup(struct bpf_map *map, void *key)
384 {
385         struct sock *sk;
386
387         sk = __sock_map_lookup_elem(map, *(u32 *)key);
388         if (!sk)
389                 return NULL;
390         if (sk_is_refcounted(sk) && !refcount_inc_not_zero(&sk->sk_refcnt))
391                 return NULL;
392         return sk;
393 }
394
395 static void *sock_map_lookup_sys(struct bpf_map *map, void *key)
396 {
397         struct sock *sk;
398
399         if (map->value_size != sizeof(u64))
400                 return ERR_PTR(-ENOSPC);
401
402         sk = __sock_map_lookup_elem(map, *(u32 *)key);
403         if (!sk)
404                 return ERR_PTR(-ENOENT);
405
406         __sock_gen_cookie(sk);
407         return &sk->sk_cookie;
408 }
409
410 static int __sock_map_delete(struct bpf_stab *stab, struct sock *sk_test,
411                              struct sock **psk)
412 {
413         struct sock *sk;
414         int err = 0;
415
416         raw_spin_lock_bh(&stab->lock);
417         sk = *psk;
418         if (!sk_test || sk_test == sk)
419                 sk = xchg(psk, NULL);
420
421         if (likely(sk))
422                 sock_map_unref(sk, psk);
423         else
424                 err = -EINVAL;
425
426         raw_spin_unlock_bh(&stab->lock);
427         return err;
428 }
429
430 static void sock_map_delete_from_link(struct bpf_map *map, struct sock *sk,
431                                       void *link_raw)
432 {
433         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
434
435         __sock_map_delete(stab, sk, link_raw);
436 }
437
438 static int sock_map_delete_elem(struct bpf_map *map, void *key)
439 {
440         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
441         u32 i = *(u32 *)key;
442         struct sock **psk;
443
444         if (unlikely(i >= map->max_entries))
445                 return -EINVAL;
446
447         psk = &stab->sks[i];
448         return __sock_map_delete(stab, NULL, psk);
449 }
450
451 static int sock_map_get_next_key(struct bpf_map *map, void *key, void *next)
452 {
453         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
454         u32 i = key ? *(u32 *)key : U32_MAX;
455         u32 *key_next = next;
456
457         if (i == stab->map.max_entries - 1)
458                 return -ENOENT;
459         if (i >= stab->map.max_entries)
460                 *key_next = 0;
461         else
462                 *key_next = i + 1;
463         return 0;
464 }
465
466 static bool sock_map_redirect_allowed(const struct sock *sk);
467
468 static int sock_map_update_common(struct bpf_map *map, u32 idx,
469                                   struct sock *sk, u64 flags)
470 {
471         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
472         struct sk_psock_link *link;
473         struct sk_psock *psock;
474         struct sock *osk;
475         int ret;
476
477         WARN_ON_ONCE(!rcu_read_lock_held());
478         if (unlikely(flags > BPF_EXIST))
479                 return -EINVAL;
480         if (unlikely(idx >= map->max_entries))
481                 return -E2BIG;
482
483         link = sk_psock_init_link();
484         if (!link)
485                 return -ENOMEM;
486
487         /* Only sockets we can redirect into/from in BPF need to hold
488          * refs to parser/verdict progs and have their sk_data_ready
489          * and sk_write_space callbacks overridden.
490          */
491         if (sock_map_redirect_allowed(sk))
492                 ret = sock_map_link(map, &stab->progs, sk);
493         else
494                 ret = sock_map_link_no_progs(map, sk);
495         if (ret < 0)
496                 goto out_free;
497
498         psock = sk_psock(sk);
499         WARN_ON_ONCE(!psock);
500
501         raw_spin_lock_bh(&stab->lock);
502         osk = stab->sks[idx];
503         if (osk && flags == BPF_NOEXIST) {
504                 ret = -EEXIST;
505                 goto out_unlock;
506         } else if (!osk && flags == BPF_EXIST) {
507                 ret = -ENOENT;
508                 goto out_unlock;
509         }
510
511         sock_map_add_link(psock, link, map, &stab->sks[idx]);
512         stab->sks[idx] = sk;
513         if (osk)
514                 sock_map_unref(osk, &stab->sks[idx]);
515         raw_spin_unlock_bh(&stab->lock);
516         return 0;
517 out_unlock:
518         raw_spin_unlock_bh(&stab->lock);
519         if (psock)
520                 sk_psock_put(sk, psock);
521 out_free:
522         sk_psock_free_link(link);
523         return ret;
524 }
525
526 static bool sock_map_op_okay(const struct bpf_sock_ops_kern *ops)
527 {
528         return ops->op == BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB ||
529                ops->op == BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB ||
530                ops->op == BPF_SOCK_OPS_TCP_LISTEN_CB;
531 }
532
533 static bool sk_is_tcp(const struct sock *sk)
534 {
535         return sk->sk_type == SOCK_STREAM &&
536                sk->sk_protocol == IPPROTO_TCP;
537 }
538
539 static bool sk_is_udp(const struct sock *sk)
540 {
541         return sk->sk_type == SOCK_DGRAM &&
542                sk->sk_protocol == IPPROTO_UDP;
543 }
544
545 static bool sock_map_redirect_allowed(const struct sock *sk)
546 {
547         return sk_is_tcp(sk) && sk->sk_state != TCP_LISTEN;
548 }
549
550 static bool sock_map_sk_is_suitable(const struct sock *sk)
551 {
552         return sk_is_tcp(sk) || sk_is_udp(sk);
553 }
554
555 static bool sock_map_sk_state_allowed(const struct sock *sk)
556 {
557         if (sk_is_tcp(sk))
558                 return (1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_LISTEN);
559         else if (sk_is_udp(sk))
560                 return sk_hashed(sk);
561
562         return false;
563 }
564
565 static int sock_hash_update_common(struct bpf_map *map, void *key,
566                                    struct sock *sk, u64 flags);
567
568 int sock_map_update_elem_sys(struct bpf_map *map, void *key, void *value,
569                              u64 flags)
570 {
571         struct socket *sock;
572         struct sock *sk;
573         int ret;
574         u64 ufd;
575
576         if (map->value_size == sizeof(u64))
577                 ufd = *(u64 *)value;
578         else
579                 ufd = *(u32 *)value;
580         if (ufd > S32_MAX)
581                 return -EINVAL;
582
583         sock = sockfd_lookup(ufd, &ret);
584         if (!sock)
585                 return ret;
586         sk = sock->sk;
587         if (!sk) {
588                 ret = -EINVAL;
589                 goto out;
590         }
591         if (!sock_map_sk_is_suitable(sk)) {
592                 ret = -EOPNOTSUPP;
593                 goto out;
594         }
595
596         sock_map_sk_acquire(sk);
597         if (!sock_map_sk_state_allowed(sk))
598                 ret = -EOPNOTSUPP;
599         else if (map->map_type == BPF_MAP_TYPE_SOCKMAP)
600                 ret = sock_map_update_common(map, *(u32 *)key, sk, flags);
601         else
602                 ret = sock_hash_update_common(map, key, sk, flags);
603         sock_map_sk_release(sk);
604 out:
605         sockfd_put(sock);
606         return ret;
607 }
608
609 static int sock_map_update_elem(struct bpf_map *map, void *key,
610                                 void *value, u64 flags)
611 {
612         struct sock *sk = (struct sock *)value;
613         int ret;
614
615         if (unlikely(!sk || !sk_fullsock(sk)))
616                 return -EINVAL;
617
618         if (!sock_map_sk_is_suitable(sk))
619                 return -EOPNOTSUPP;
620
621         local_bh_disable();
622         bh_lock_sock(sk);
623         if (!sock_map_sk_state_allowed(sk))
624                 ret = -EOPNOTSUPP;
625         else if (map->map_type == BPF_MAP_TYPE_SOCKMAP)
626                 ret = sock_map_update_common(map, *(u32 *)key, sk, flags);
627         else
628                 ret = sock_hash_update_common(map, key, sk, flags);
629         bh_unlock_sock(sk);
630         local_bh_enable();
631         return ret;
632 }
633
634 BPF_CALL_4(bpf_sock_map_update, struct bpf_sock_ops_kern *, sops,
635            struct bpf_map *, map, void *, key, u64, flags)
636 {
637         WARN_ON_ONCE(!rcu_read_lock_held());
638
639         if (likely(sock_map_sk_is_suitable(sops->sk) &&
640                    sock_map_op_okay(sops)))
641                 return sock_map_update_common(map, *(u32 *)key, sops->sk,
642                                               flags);
643         return -EOPNOTSUPP;
644 }
645
646 const struct bpf_func_proto bpf_sock_map_update_proto = {
647         .func           = bpf_sock_map_update,
648         .gpl_only       = false,
649         .pkt_access     = true,
650         .ret_type       = RET_INTEGER,
651         .arg1_type      = ARG_PTR_TO_CTX,
652         .arg2_type      = ARG_CONST_MAP_PTR,
653         .arg3_type      = ARG_PTR_TO_MAP_KEY,
654         .arg4_type      = ARG_ANYTHING,
655 };
656
657 BPF_CALL_4(bpf_sk_redirect_map, struct sk_buff *, skb,
658            struct bpf_map *, map, u32, key, u64, flags)
659 {
660         struct sock *sk;
661
662         if (unlikely(flags & ~(BPF_F_INGRESS)))
663                 return SK_DROP;
664
665         sk = __sock_map_lookup_elem(map, key);
666         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
667                 return SK_DROP;
668
669         skb_bpf_set_redir(skb, sk, flags & BPF_F_INGRESS);
670         return SK_PASS;
671 }
672
673 const struct bpf_func_proto bpf_sk_redirect_map_proto = {
674         .func           = bpf_sk_redirect_map,
675         .gpl_only       = false,
676         .ret_type       = RET_INTEGER,
677         .arg1_type      = ARG_PTR_TO_CTX,
678         .arg2_type      = ARG_CONST_MAP_PTR,
679         .arg3_type      = ARG_ANYTHING,
680         .arg4_type      = ARG_ANYTHING,
681 };
682
683 BPF_CALL_4(bpf_msg_redirect_map, struct sk_msg *, msg,
684            struct bpf_map *, map, u32, key, u64, flags)
685 {
686         struct sock *sk;
687
688         if (unlikely(flags & ~(BPF_F_INGRESS)))
689                 return SK_DROP;
690
691         sk = __sock_map_lookup_elem(map, key);
692         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
693                 return SK_DROP;
694
695         msg->flags = flags;
696         msg->sk_redir = sk;
697         return SK_PASS;
698 }
699
700 const struct bpf_func_proto bpf_msg_redirect_map_proto = {
701         .func           = bpf_msg_redirect_map,
702         .gpl_only       = false,
703         .ret_type       = RET_INTEGER,
704         .arg1_type      = ARG_PTR_TO_CTX,
705         .arg2_type      = ARG_CONST_MAP_PTR,
706         .arg3_type      = ARG_ANYTHING,
707         .arg4_type      = ARG_ANYTHING,
708 };
709
710 struct sock_map_seq_info {
711         struct bpf_map *map;
712         struct sock *sk;
713         u32 index;
714 };
715
716 struct bpf_iter__sockmap {
717         __bpf_md_ptr(struct bpf_iter_meta *, meta);
718         __bpf_md_ptr(struct bpf_map *, map);
719         __bpf_md_ptr(void *, key);
720         __bpf_md_ptr(struct sock *, sk);
721 };
722
723 DEFINE_BPF_ITER_FUNC(sockmap, struct bpf_iter_meta *meta,
724                      struct bpf_map *map, void *key,
725                      struct sock *sk)
726
727 static void *sock_map_seq_lookup_elem(struct sock_map_seq_info *info)
728 {
729         if (unlikely(info->index >= info->map->max_entries))
730                 return NULL;
731
732         info->sk = __sock_map_lookup_elem(info->map, info->index);
733
734         /* can't return sk directly, since that might be NULL */
735         return info;
736 }
737
738 static void *sock_map_seq_start(struct seq_file *seq, loff_t *pos)
739         __acquires(rcu)
740 {
741         struct sock_map_seq_info *info = seq->private;
742
743         if (*pos == 0)
744                 ++*pos;
745
746         /* pairs with sock_map_seq_stop */
747         rcu_read_lock();
748         return sock_map_seq_lookup_elem(info);
749 }
750
751 static void *sock_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
752         __must_hold(rcu)
753 {
754         struct sock_map_seq_info *info = seq->private;
755
756         ++*pos;
757         ++info->index;
758
759         return sock_map_seq_lookup_elem(info);
760 }
761
762 static int sock_map_seq_show(struct seq_file *seq, void *v)
763         __must_hold(rcu)
764 {
765         struct sock_map_seq_info *info = seq->private;
766         struct bpf_iter__sockmap ctx = {};
767         struct bpf_iter_meta meta;
768         struct bpf_prog *prog;
769
770         meta.seq = seq;
771         prog = bpf_iter_get_info(&meta, !v);
772         if (!prog)
773                 return 0;
774
775         ctx.meta = &meta;
776         ctx.map = info->map;
777         if (v) {
778                 ctx.key = &info->index;
779                 ctx.sk = info->sk;
780         }
781
782         return bpf_iter_run_prog(prog, &ctx);
783 }
784
785 static void sock_map_seq_stop(struct seq_file *seq, void *v)
786         __releases(rcu)
787 {
788         if (!v)
789                 (void)sock_map_seq_show(seq, NULL);
790
791         /* pairs with sock_map_seq_start */
792         rcu_read_unlock();
793 }
794
795 static const struct seq_operations sock_map_seq_ops = {
796         .start  = sock_map_seq_start,
797         .next   = sock_map_seq_next,
798         .stop   = sock_map_seq_stop,
799         .show   = sock_map_seq_show,
800 };
801
802 static int sock_map_init_seq_private(void *priv_data,
803                                      struct bpf_iter_aux_info *aux)
804 {
805         struct sock_map_seq_info *info = priv_data;
806
807         info->map = aux->map;
808         return 0;
809 }
810
811 static const struct bpf_iter_seq_info sock_map_iter_seq_info = {
812         .seq_ops                = &sock_map_seq_ops,
813         .init_seq_private       = sock_map_init_seq_private,
814         .seq_priv_size          = sizeof(struct sock_map_seq_info),
815 };
816
817 static int sock_map_btf_id;
818 const struct bpf_map_ops sock_map_ops = {
819         .map_meta_equal         = bpf_map_meta_equal,
820         .map_alloc              = sock_map_alloc,
821         .map_free               = sock_map_free,
822         .map_get_next_key       = sock_map_get_next_key,
823         .map_lookup_elem_sys_only = sock_map_lookup_sys,
824         .map_update_elem        = sock_map_update_elem,
825         .map_delete_elem        = sock_map_delete_elem,
826         .map_lookup_elem        = sock_map_lookup,
827         .map_release_uref       = sock_map_release_progs,
828         .map_check_btf          = map_check_no_btf,
829         .map_btf_name           = "bpf_stab",
830         .map_btf_id             = &sock_map_btf_id,
831         .iter_seq_info          = &sock_map_iter_seq_info,
832 };
833
834 struct bpf_shtab_elem {
835         struct rcu_head rcu;
836         u32 hash;
837         struct sock *sk;
838         struct hlist_node node;
839         u8 key[];
840 };
841
842 struct bpf_shtab_bucket {
843         struct hlist_head head;
844         raw_spinlock_t lock;
845 };
846
847 struct bpf_shtab {
848         struct bpf_map map;
849         struct bpf_shtab_bucket *buckets;
850         u32 buckets_num;
851         u32 elem_size;
852         struct sk_psock_progs progs;
853         atomic_t count;
854 };
855
856 static inline u32 sock_hash_bucket_hash(const void *key, u32 len)
857 {
858         return jhash(key, len, 0);
859 }
860
861 static struct bpf_shtab_bucket *sock_hash_select_bucket(struct bpf_shtab *htab,
862                                                         u32 hash)
863 {
864         return &htab->buckets[hash & (htab->buckets_num - 1)];
865 }
866
867 static struct bpf_shtab_elem *
868 sock_hash_lookup_elem_raw(struct hlist_head *head, u32 hash, void *key,
869                           u32 key_size)
870 {
871         struct bpf_shtab_elem *elem;
872
873         hlist_for_each_entry_rcu(elem, head, node) {
874                 if (elem->hash == hash &&
875                     !memcmp(&elem->key, key, key_size))
876                         return elem;
877         }
878
879         return NULL;
880 }
881
882 static struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
883 {
884         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
885         u32 key_size = map->key_size, hash;
886         struct bpf_shtab_bucket *bucket;
887         struct bpf_shtab_elem *elem;
888
889         WARN_ON_ONCE(!rcu_read_lock_held());
890
891         hash = sock_hash_bucket_hash(key, key_size);
892         bucket = sock_hash_select_bucket(htab, hash);
893         elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
894
895         return elem ? elem->sk : NULL;
896 }
897
898 static void sock_hash_free_elem(struct bpf_shtab *htab,
899                                 struct bpf_shtab_elem *elem)
900 {
901         atomic_dec(&htab->count);
902         kfree_rcu(elem, rcu);
903 }
904
905 static void sock_hash_delete_from_link(struct bpf_map *map, struct sock *sk,
906                                        void *link_raw)
907 {
908         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
909         struct bpf_shtab_elem *elem_probe, *elem = link_raw;
910         struct bpf_shtab_bucket *bucket;
911
912         WARN_ON_ONCE(!rcu_read_lock_held());
913         bucket = sock_hash_select_bucket(htab, elem->hash);
914
915         /* elem may be deleted in parallel from the map, but access here
916          * is okay since it's going away only after RCU grace period.
917          * However, we need to check whether it's still present.
918          */
919         raw_spin_lock_bh(&bucket->lock);
920         elem_probe = sock_hash_lookup_elem_raw(&bucket->head, elem->hash,
921                                                elem->key, map->key_size);
922         if (elem_probe && elem_probe == elem) {
923                 hlist_del_rcu(&elem->node);
924                 sock_map_unref(elem->sk, elem);
925                 sock_hash_free_elem(htab, elem);
926         }
927         raw_spin_unlock_bh(&bucket->lock);
928 }
929
930 static int sock_hash_delete_elem(struct bpf_map *map, void *key)
931 {
932         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
933         u32 hash, key_size = map->key_size;
934         struct bpf_shtab_bucket *bucket;
935         struct bpf_shtab_elem *elem;
936         int ret = -ENOENT;
937
938         hash = sock_hash_bucket_hash(key, key_size);
939         bucket = sock_hash_select_bucket(htab, hash);
940
941         raw_spin_lock_bh(&bucket->lock);
942         elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
943         if (elem) {
944                 hlist_del_rcu(&elem->node);
945                 sock_map_unref(elem->sk, elem);
946                 sock_hash_free_elem(htab, elem);
947                 ret = 0;
948         }
949         raw_spin_unlock_bh(&bucket->lock);
950         return ret;
951 }
952
953 static struct bpf_shtab_elem *sock_hash_alloc_elem(struct bpf_shtab *htab,
954                                                    void *key, u32 key_size,
955                                                    u32 hash, struct sock *sk,
956                                                    struct bpf_shtab_elem *old)
957 {
958         struct bpf_shtab_elem *new;
959
960         if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
961                 if (!old) {
962                         atomic_dec(&htab->count);
963                         return ERR_PTR(-E2BIG);
964                 }
965         }
966
967         new = bpf_map_kmalloc_node(&htab->map, htab->elem_size,
968                                    GFP_ATOMIC | __GFP_NOWARN,
969                                    htab->map.numa_node);
970         if (!new) {
971                 atomic_dec(&htab->count);
972                 return ERR_PTR(-ENOMEM);
973         }
974         memcpy(new->key, key, key_size);
975         new->sk = sk;
976         new->hash = hash;
977         return new;
978 }
979
980 static int sock_hash_update_common(struct bpf_map *map, void *key,
981                                    struct sock *sk, u64 flags)
982 {
983         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
984         u32 key_size = map->key_size, hash;
985         struct bpf_shtab_elem *elem, *elem_new;
986         struct bpf_shtab_bucket *bucket;
987         struct sk_psock_link *link;
988         struct sk_psock *psock;
989         int ret;
990
991         WARN_ON_ONCE(!rcu_read_lock_held());
992         if (unlikely(flags > BPF_EXIST))
993                 return -EINVAL;
994
995         link = sk_psock_init_link();
996         if (!link)
997                 return -ENOMEM;
998
999         /* Only sockets we can redirect into/from in BPF need to hold
1000          * refs to parser/verdict progs and have their sk_data_ready
1001          * and sk_write_space callbacks overridden.
1002          */
1003         if (sock_map_redirect_allowed(sk))
1004                 ret = sock_map_link(map, &htab->progs, sk);
1005         else
1006                 ret = sock_map_link_no_progs(map, sk);
1007         if (ret < 0)
1008                 goto out_free;
1009
1010         psock = sk_psock(sk);
1011         WARN_ON_ONCE(!psock);
1012
1013         hash = sock_hash_bucket_hash(key, key_size);
1014         bucket = sock_hash_select_bucket(htab, hash);
1015
1016         raw_spin_lock_bh(&bucket->lock);
1017         elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
1018         if (elem && flags == BPF_NOEXIST) {
1019                 ret = -EEXIST;
1020                 goto out_unlock;
1021         } else if (!elem && flags == BPF_EXIST) {
1022                 ret = -ENOENT;
1023                 goto out_unlock;
1024         }
1025
1026         elem_new = sock_hash_alloc_elem(htab, key, key_size, hash, sk, elem);
1027         if (IS_ERR(elem_new)) {
1028                 ret = PTR_ERR(elem_new);
1029                 goto out_unlock;
1030         }
1031
1032         sock_map_add_link(psock, link, map, elem_new);
1033         /* Add new element to the head of the list, so that
1034          * concurrent search will find it before old elem.
1035          */
1036         hlist_add_head_rcu(&elem_new->node, &bucket->head);
1037         if (elem) {
1038                 hlist_del_rcu(&elem->node);
1039                 sock_map_unref(elem->sk, elem);
1040                 sock_hash_free_elem(htab, elem);
1041         }
1042         raw_spin_unlock_bh(&bucket->lock);
1043         return 0;
1044 out_unlock:
1045         raw_spin_unlock_bh(&bucket->lock);
1046         sk_psock_put(sk, psock);
1047 out_free:
1048         sk_psock_free_link(link);
1049         return ret;
1050 }
1051
1052 static int sock_hash_get_next_key(struct bpf_map *map, void *key,
1053                                   void *key_next)
1054 {
1055         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
1056         struct bpf_shtab_elem *elem, *elem_next;
1057         u32 hash, key_size = map->key_size;
1058         struct hlist_head *head;
1059         int i = 0;
1060
1061         if (!key)
1062                 goto find_first_elem;
1063         hash = sock_hash_bucket_hash(key, key_size);
1064         head = &sock_hash_select_bucket(htab, hash)->head;
1065         elem = sock_hash_lookup_elem_raw(head, hash, key, key_size);
1066         if (!elem)
1067                 goto find_first_elem;
1068
1069         elem_next = hlist_entry_safe(rcu_dereference(hlist_next_rcu(&elem->node)),
1070                                      struct bpf_shtab_elem, node);
1071         if (elem_next) {
1072                 memcpy(key_next, elem_next->key, key_size);
1073                 return 0;
1074         }
1075
1076         i = hash & (htab->buckets_num - 1);
1077         i++;
1078 find_first_elem:
1079         for (; i < htab->buckets_num; i++) {
1080                 head = &sock_hash_select_bucket(htab, i)->head;
1081                 elem_next = hlist_entry_safe(rcu_dereference(hlist_first_rcu(head)),
1082                                              struct bpf_shtab_elem, node);
1083                 if (elem_next) {
1084                         memcpy(key_next, elem_next->key, key_size);
1085                         return 0;
1086                 }
1087         }
1088
1089         return -ENOENT;
1090 }
1091
1092 static struct bpf_map *sock_hash_alloc(union bpf_attr *attr)
1093 {
1094         struct bpf_shtab *htab;
1095         int i, err;
1096
1097         if (!capable(CAP_NET_ADMIN))
1098                 return ERR_PTR(-EPERM);
1099         if (attr->max_entries == 0 ||
1100             attr->key_size    == 0 ||
1101             (attr->value_size != sizeof(u32) &&
1102              attr->value_size != sizeof(u64)) ||
1103             attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
1104                 return ERR_PTR(-EINVAL);
1105         if (attr->key_size > MAX_BPF_STACK)
1106                 return ERR_PTR(-E2BIG);
1107
1108         htab = kzalloc(sizeof(*htab), GFP_USER | __GFP_ACCOUNT);
1109         if (!htab)
1110                 return ERR_PTR(-ENOMEM);
1111
1112         bpf_map_init_from_attr(&htab->map, attr);
1113
1114         htab->buckets_num = roundup_pow_of_two(htab->map.max_entries);
1115         htab->elem_size = sizeof(struct bpf_shtab_elem) +
1116                           round_up(htab->map.key_size, 8);
1117         if (htab->buckets_num == 0 ||
1118             htab->buckets_num > U32_MAX / sizeof(struct bpf_shtab_bucket)) {
1119                 err = -EINVAL;
1120                 goto free_htab;
1121         }
1122
1123         htab->buckets = bpf_map_area_alloc(htab->buckets_num *
1124                                            sizeof(struct bpf_shtab_bucket),
1125                                            htab->map.numa_node);
1126         if (!htab->buckets) {
1127                 err = -ENOMEM;
1128                 goto free_htab;
1129         }
1130
1131         for (i = 0; i < htab->buckets_num; i++) {
1132                 INIT_HLIST_HEAD(&htab->buckets[i].head);
1133                 raw_spin_lock_init(&htab->buckets[i].lock);
1134         }
1135
1136         return &htab->map;
1137 free_htab:
1138         kfree(htab);
1139         return ERR_PTR(err);
1140 }
1141
1142 static void sock_hash_free(struct bpf_map *map)
1143 {
1144         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
1145         struct bpf_shtab_bucket *bucket;
1146         struct hlist_head unlink_list;
1147         struct bpf_shtab_elem *elem;
1148         struct hlist_node *node;
1149         int i;
1150
1151         /* After the sync no updates or deletes will be in-flight so it
1152          * is safe to walk map and remove entries without risking a race
1153          * in EEXIST update case.
1154          */
1155         synchronize_rcu();
1156         for (i = 0; i < htab->buckets_num; i++) {
1157                 bucket = sock_hash_select_bucket(htab, i);
1158
1159                 /* We are racing with sock_hash_delete_from_link to
1160                  * enter the spin-lock critical section. Every socket on
1161                  * the list is still linked to sockhash. Since link
1162                  * exists, psock exists and holds a ref to socket. That
1163                  * lets us to grab a socket ref too.
1164                  */
1165                 raw_spin_lock_bh(&bucket->lock);
1166                 hlist_for_each_entry(elem, &bucket->head, node)
1167                         sock_hold(elem->sk);
1168                 hlist_move_list(&bucket->head, &unlink_list);
1169                 raw_spin_unlock_bh(&bucket->lock);
1170
1171                 /* Process removed entries out of atomic context to
1172                  * block for socket lock before deleting the psock's
1173                  * link to sockhash.
1174                  */
1175                 hlist_for_each_entry_safe(elem, node, &unlink_list, node) {
1176                         hlist_del(&elem->node);
1177                         lock_sock(elem->sk);
1178                         rcu_read_lock();
1179                         sock_map_unref(elem->sk, elem);
1180                         rcu_read_unlock();
1181                         release_sock(elem->sk);
1182                         sock_put(elem->sk);
1183                         sock_hash_free_elem(htab, elem);
1184                 }
1185         }
1186
1187         /* wait for psock readers accessing its map link */
1188         synchronize_rcu();
1189
1190         bpf_map_area_free(htab->buckets);
1191         kfree(htab);
1192 }
1193
1194 static void *sock_hash_lookup_sys(struct bpf_map *map, void *key)
1195 {
1196         struct sock *sk;
1197
1198         if (map->value_size != sizeof(u64))
1199                 return ERR_PTR(-ENOSPC);
1200
1201         sk = __sock_hash_lookup_elem(map, key);
1202         if (!sk)
1203                 return ERR_PTR(-ENOENT);
1204
1205         __sock_gen_cookie(sk);
1206         return &sk->sk_cookie;
1207 }
1208
1209 static void *sock_hash_lookup(struct bpf_map *map, void *key)
1210 {
1211         struct sock *sk;
1212
1213         sk = __sock_hash_lookup_elem(map, key);
1214         if (!sk)
1215                 return NULL;
1216         if (sk_is_refcounted(sk) && !refcount_inc_not_zero(&sk->sk_refcnt))
1217                 return NULL;
1218         return sk;
1219 }
1220
1221 static void sock_hash_release_progs(struct bpf_map *map)
1222 {
1223         psock_progs_drop(&container_of(map, struct bpf_shtab, map)->progs);
1224 }
1225
1226 BPF_CALL_4(bpf_sock_hash_update, struct bpf_sock_ops_kern *, sops,
1227            struct bpf_map *, map, void *, key, u64, flags)
1228 {
1229         WARN_ON_ONCE(!rcu_read_lock_held());
1230
1231         if (likely(sock_map_sk_is_suitable(sops->sk) &&
1232                    sock_map_op_okay(sops)))
1233                 return sock_hash_update_common(map, key, sops->sk, flags);
1234         return -EOPNOTSUPP;
1235 }
1236
1237 const struct bpf_func_proto bpf_sock_hash_update_proto = {
1238         .func           = bpf_sock_hash_update,
1239         .gpl_only       = false,
1240         .pkt_access     = true,
1241         .ret_type       = RET_INTEGER,
1242         .arg1_type      = ARG_PTR_TO_CTX,
1243         .arg2_type      = ARG_CONST_MAP_PTR,
1244         .arg3_type      = ARG_PTR_TO_MAP_KEY,
1245         .arg4_type      = ARG_ANYTHING,
1246 };
1247
1248 BPF_CALL_4(bpf_sk_redirect_hash, struct sk_buff *, skb,
1249            struct bpf_map *, map, void *, key, u64, flags)
1250 {
1251         struct sock *sk;
1252
1253         if (unlikely(flags & ~(BPF_F_INGRESS)))
1254                 return SK_DROP;
1255
1256         sk = __sock_hash_lookup_elem(map, key);
1257         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
1258                 return SK_DROP;
1259
1260         skb_bpf_set_redir(skb, sk, flags & BPF_F_INGRESS);
1261         return SK_PASS;
1262 }
1263
1264 const struct bpf_func_proto bpf_sk_redirect_hash_proto = {
1265         .func           = bpf_sk_redirect_hash,
1266         .gpl_only       = false,
1267         .ret_type       = RET_INTEGER,
1268         .arg1_type      = ARG_PTR_TO_CTX,
1269         .arg2_type      = ARG_CONST_MAP_PTR,
1270         .arg3_type      = ARG_PTR_TO_MAP_KEY,
1271         .arg4_type      = ARG_ANYTHING,
1272 };
1273
1274 BPF_CALL_4(bpf_msg_redirect_hash, struct sk_msg *, msg,
1275            struct bpf_map *, map, void *, key, u64, flags)
1276 {
1277         struct sock *sk;
1278
1279         if (unlikely(flags & ~(BPF_F_INGRESS)))
1280                 return SK_DROP;
1281
1282         sk = __sock_hash_lookup_elem(map, key);
1283         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
1284                 return SK_DROP;
1285
1286         msg->flags = flags;
1287         msg->sk_redir = sk;
1288         return SK_PASS;
1289 }
1290
1291 const struct bpf_func_proto bpf_msg_redirect_hash_proto = {
1292         .func           = bpf_msg_redirect_hash,
1293         .gpl_only       = false,
1294         .ret_type       = RET_INTEGER,
1295         .arg1_type      = ARG_PTR_TO_CTX,
1296         .arg2_type      = ARG_CONST_MAP_PTR,
1297         .arg3_type      = ARG_PTR_TO_MAP_KEY,
1298         .arg4_type      = ARG_ANYTHING,
1299 };
1300
1301 struct sock_hash_seq_info {
1302         struct bpf_map *map;
1303         struct bpf_shtab *htab;
1304         u32 bucket_id;
1305 };
1306
1307 static void *sock_hash_seq_find_next(struct sock_hash_seq_info *info,
1308                                      struct bpf_shtab_elem *prev_elem)
1309 {
1310         const struct bpf_shtab *htab = info->htab;
1311         struct bpf_shtab_bucket *bucket;
1312         struct bpf_shtab_elem *elem;
1313         struct hlist_node *node;
1314
1315         /* try to find next elem in the same bucket */
1316         if (prev_elem) {
1317                 node = rcu_dereference(hlist_next_rcu(&prev_elem->node));
1318                 elem = hlist_entry_safe(node, struct bpf_shtab_elem, node);
1319                 if (elem)
1320                         return elem;
1321
1322                 /* no more elements, continue in the next bucket */
1323                 info->bucket_id++;
1324         }
1325
1326         for (; info->bucket_id < htab->buckets_num; info->bucket_id++) {
1327                 bucket = &htab->buckets[info->bucket_id];
1328                 node = rcu_dereference(hlist_first_rcu(&bucket->head));
1329                 elem = hlist_entry_safe(node, struct bpf_shtab_elem, node);
1330                 if (elem)
1331                         return elem;
1332         }
1333
1334         return NULL;
1335 }
1336
1337 static void *sock_hash_seq_start(struct seq_file *seq, loff_t *pos)
1338         __acquires(rcu)
1339 {
1340         struct sock_hash_seq_info *info = seq->private;
1341
1342         if (*pos == 0)
1343                 ++*pos;
1344
1345         /* pairs with sock_hash_seq_stop */
1346         rcu_read_lock();
1347         return sock_hash_seq_find_next(info, NULL);
1348 }
1349
1350 static void *sock_hash_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1351         __must_hold(rcu)
1352 {
1353         struct sock_hash_seq_info *info = seq->private;
1354
1355         ++*pos;
1356         return sock_hash_seq_find_next(info, v);
1357 }
1358
1359 static int sock_hash_seq_show(struct seq_file *seq, void *v)
1360         __must_hold(rcu)
1361 {
1362         struct sock_hash_seq_info *info = seq->private;
1363         struct bpf_iter__sockmap ctx = {};
1364         struct bpf_shtab_elem *elem = v;
1365         struct bpf_iter_meta meta;
1366         struct bpf_prog *prog;
1367
1368         meta.seq = seq;
1369         prog = bpf_iter_get_info(&meta, !elem);
1370         if (!prog)
1371                 return 0;
1372
1373         ctx.meta = &meta;
1374         ctx.map = info->map;
1375         if (elem) {
1376                 ctx.key = elem->key;
1377                 ctx.sk = elem->sk;
1378         }
1379
1380         return bpf_iter_run_prog(prog, &ctx);
1381 }
1382
1383 static void sock_hash_seq_stop(struct seq_file *seq, void *v)
1384         __releases(rcu)
1385 {
1386         if (!v)
1387                 (void)sock_hash_seq_show(seq, NULL);
1388
1389         /* pairs with sock_hash_seq_start */
1390         rcu_read_unlock();
1391 }
1392
1393 static const struct seq_operations sock_hash_seq_ops = {
1394         .start  = sock_hash_seq_start,
1395         .next   = sock_hash_seq_next,
1396         .stop   = sock_hash_seq_stop,
1397         .show   = sock_hash_seq_show,
1398 };
1399
1400 static int sock_hash_init_seq_private(void *priv_data,
1401                                      struct bpf_iter_aux_info *aux)
1402 {
1403         struct sock_hash_seq_info *info = priv_data;
1404
1405         info->map = aux->map;
1406         info->htab = container_of(aux->map, struct bpf_shtab, map);
1407         return 0;
1408 }
1409
1410 static const struct bpf_iter_seq_info sock_hash_iter_seq_info = {
1411         .seq_ops                = &sock_hash_seq_ops,
1412         .init_seq_private       = sock_hash_init_seq_private,
1413         .seq_priv_size          = sizeof(struct sock_hash_seq_info),
1414 };
1415
1416 static int sock_hash_map_btf_id;
1417 const struct bpf_map_ops sock_hash_ops = {
1418         .map_meta_equal         = bpf_map_meta_equal,
1419         .map_alloc              = sock_hash_alloc,
1420         .map_free               = sock_hash_free,
1421         .map_get_next_key       = sock_hash_get_next_key,
1422         .map_update_elem        = sock_map_update_elem,
1423         .map_delete_elem        = sock_hash_delete_elem,
1424         .map_lookup_elem        = sock_hash_lookup,
1425         .map_lookup_elem_sys_only = sock_hash_lookup_sys,
1426         .map_release_uref       = sock_hash_release_progs,
1427         .map_check_btf          = map_check_no_btf,
1428         .map_btf_name           = "bpf_shtab",
1429         .map_btf_id             = &sock_hash_map_btf_id,
1430         .iter_seq_info          = &sock_hash_iter_seq_info,
1431 };
1432
1433 static struct sk_psock_progs *sock_map_progs(struct bpf_map *map)
1434 {
1435         switch (map->map_type) {
1436         case BPF_MAP_TYPE_SOCKMAP:
1437                 return &container_of(map, struct bpf_stab, map)->progs;
1438         case BPF_MAP_TYPE_SOCKHASH:
1439                 return &container_of(map, struct bpf_shtab, map)->progs;
1440         default:
1441                 break;
1442         }
1443
1444         return NULL;
1445 }
1446
1447 int sock_map_prog_update(struct bpf_map *map, struct bpf_prog *prog,
1448                          struct bpf_prog *old, u32 which)
1449 {
1450         struct sk_psock_progs *progs = sock_map_progs(map);
1451         struct bpf_prog **pprog;
1452
1453         if (!progs)
1454                 return -EOPNOTSUPP;
1455
1456         switch (which) {
1457         case BPF_SK_MSG_VERDICT:
1458                 pprog = &progs->msg_parser;
1459                 break;
1460 #if IS_ENABLED(CONFIG_BPF_STREAM_PARSER)
1461         case BPF_SK_SKB_STREAM_PARSER:
1462                 pprog = &progs->stream_parser;
1463                 break;
1464 #endif
1465         case BPF_SK_SKB_STREAM_VERDICT:
1466                 pprog = &progs->stream_verdict;
1467                 break;
1468         default:
1469                 return -EOPNOTSUPP;
1470         }
1471
1472         if (old)
1473                 return psock_replace_prog(pprog, prog, old);
1474
1475         psock_set_prog(pprog, prog);
1476         return 0;
1477 }
1478
1479 static void sock_map_unlink(struct sock *sk, struct sk_psock_link *link)
1480 {
1481         switch (link->map->map_type) {
1482         case BPF_MAP_TYPE_SOCKMAP:
1483                 return sock_map_delete_from_link(link->map, sk,
1484                                                  link->link_raw);
1485         case BPF_MAP_TYPE_SOCKHASH:
1486                 return sock_hash_delete_from_link(link->map, sk,
1487                                                   link->link_raw);
1488         default:
1489                 break;
1490         }
1491 }
1492
1493 static void sock_map_remove_links(struct sock *sk, struct sk_psock *psock)
1494 {
1495         struct sk_psock_link *link;
1496
1497         while ((link = sk_psock_link_pop(psock))) {
1498                 sock_map_unlink(sk, link);
1499                 sk_psock_free_link(link);
1500         }
1501 }
1502
1503 void sock_map_unhash(struct sock *sk)
1504 {
1505         void (*saved_unhash)(struct sock *sk);
1506         struct sk_psock *psock;
1507
1508         rcu_read_lock();
1509         psock = sk_psock(sk);
1510         if (unlikely(!psock)) {
1511                 rcu_read_unlock();
1512                 if (sk->sk_prot->unhash)
1513                         sk->sk_prot->unhash(sk);
1514                 return;
1515         }
1516
1517         saved_unhash = psock->saved_unhash;
1518         sock_map_remove_links(sk, psock);
1519         rcu_read_unlock();
1520         saved_unhash(sk);
1521 }
1522
1523 void sock_map_close(struct sock *sk, long timeout)
1524 {
1525         void (*saved_close)(struct sock *sk, long timeout);
1526         struct sk_psock *psock;
1527
1528         lock_sock(sk);
1529         rcu_read_lock();
1530         psock = sk_psock(sk);
1531         if (unlikely(!psock)) {
1532                 rcu_read_unlock();
1533                 release_sock(sk);
1534                 return sk->sk_prot->close(sk, timeout);
1535         }
1536
1537         saved_close = psock->saved_close;
1538         sock_map_remove_links(sk, psock);
1539         rcu_read_unlock();
1540         release_sock(sk);
1541         saved_close(sk, timeout);
1542 }
1543
1544 static int sock_map_iter_attach_target(struct bpf_prog *prog,
1545                                        union bpf_iter_link_info *linfo,
1546                                        struct bpf_iter_aux_info *aux)
1547 {
1548         struct bpf_map *map;
1549         int err = -EINVAL;
1550
1551         if (!linfo->map.map_fd)
1552                 return -EBADF;
1553
1554         map = bpf_map_get_with_uref(linfo->map.map_fd);
1555         if (IS_ERR(map))
1556                 return PTR_ERR(map);
1557
1558         if (map->map_type != BPF_MAP_TYPE_SOCKMAP &&
1559             map->map_type != BPF_MAP_TYPE_SOCKHASH)
1560                 goto put_map;
1561
1562         if (prog->aux->max_rdonly_access > map->key_size) {
1563                 err = -EACCES;
1564                 goto put_map;
1565         }
1566
1567         aux->map = map;
1568         return 0;
1569
1570 put_map:
1571         bpf_map_put_with_uref(map);
1572         return err;
1573 }
1574
1575 static void sock_map_iter_detach_target(struct bpf_iter_aux_info *aux)
1576 {
1577         bpf_map_put_with_uref(aux->map);
1578 }
1579
1580 static struct bpf_iter_reg sock_map_iter_reg = {
1581         .target                 = "sockmap",
1582         .attach_target          = sock_map_iter_attach_target,
1583         .detach_target          = sock_map_iter_detach_target,
1584         .show_fdinfo            = bpf_iter_map_show_fdinfo,
1585         .fill_link_info         = bpf_iter_map_fill_link_info,
1586         .ctx_arg_info_size      = 2,
1587         .ctx_arg_info           = {
1588                 { offsetof(struct bpf_iter__sockmap, key),
1589                   PTR_TO_RDONLY_BUF_OR_NULL },
1590                 { offsetof(struct bpf_iter__sockmap, sk),
1591                   PTR_TO_BTF_ID_OR_NULL },
1592         },
1593 };
1594
1595 static int __init bpf_sockmap_iter_init(void)
1596 {
1597         sock_map_iter_reg.ctx_arg_info[1].btf_id =
1598                 btf_sock_ids[BTF_SOCK_TYPE_SOCK];
1599         return bpf_iter_reg_target(&sock_map_iter_reg);
1600 }
1601 late_initcall(bpf_sockmap_iter_init);