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