sock_map: Introduce BPF_SK_SKB_VERDICT
[linux-2.6-microblaze.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(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                 else
171                         sk_psock_stop_verdict(sk, psock);
172                 write_unlock_bh(&sk->sk_callback_lock);
173         }
174 }
175
176 static void sock_map_unref(struct sock *sk, void *link_raw)
177 {
178         struct sk_psock *psock = sk_psock(sk);
179
180         if (likely(psock)) {
181                 sock_map_del_link(sk, psock, link_raw);
182                 sk_psock_put(sk, psock);
183         }
184 }
185
186 static int sock_map_init_proto(struct sock *sk, struct sk_psock *psock)
187 {
188         struct proto *prot;
189
190         switch (sk->sk_type) {
191         case SOCK_STREAM:
192                 prot = tcp_bpf_get_proto(sk, psock);
193                 break;
194
195         case SOCK_DGRAM:
196                 prot = udp_bpf_get_proto(sk, psock);
197                 break;
198
199         default:
200                 return -EINVAL;
201         }
202
203         if (IS_ERR(prot))
204                 return PTR_ERR(prot);
205
206         sk_psock_update_proto(sk, psock, prot);
207         return 0;
208 }
209
210 static struct sk_psock *sock_map_psock_get_checked(struct sock *sk)
211 {
212         struct sk_psock *psock;
213
214         rcu_read_lock();
215         psock = sk_psock(sk);
216         if (psock) {
217                 if (sk->sk_prot->close != sock_map_close) {
218                         psock = ERR_PTR(-EBUSY);
219                         goto out;
220                 }
221
222                 if (!refcount_inc_not_zero(&psock->refcnt))
223                         psock = ERR_PTR(-EBUSY);
224         }
225 out:
226         rcu_read_unlock();
227         return psock;
228 }
229
230 static bool sock_map_redirect_allowed(const struct sock *sk);
231
232 static int sock_map_link(struct bpf_map *map, struct sock *sk)
233 {
234         struct sk_psock_progs *progs = sock_map_progs(map);
235         struct bpf_prog *stream_verdict = NULL;
236         struct bpf_prog *stream_parser = NULL;
237         struct bpf_prog *skb_verdict = NULL;
238         struct bpf_prog *msg_parser = NULL;
239         struct sk_psock *psock;
240         int ret;
241
242         /* Only sockets we can redirect into/from in BPF need to hold
243          * refs to parser/verdict progs and have their sk_data_ready
244          * and sk_write_space callbacks overridden.
245          */
246         if (!sock_map_redirect_allowed(sk))
247                 goto no_progs;
248
249         stream_verdict = READ_ONCE(progs->stream_verdict);
250         if (stream_verdict) {
251                 stream_verdict = bpf_prog_inc_not_zero(stream_verdict);
252                 if (IS_ERR(stream_verdict))
253                         return PTR_ERR(stream_verdict);
254         }
255
256         stream_parser = READ_ONCE(progs->stream_parser);
257         if (stream_parser) {
258                 stream_parser = bpf_prog_inc_not_zero(stream_parser);
259                 if (IS_ERR(stream_parser)) {
260                         ret = PTR_ERR(stream_parser);
261                         goto out_put_stream_verdict;
262                 }
263         }
264
265         msg_parser = READ_ONCE(progs->msg_parser);
266         if (msg_parser) {
267                 msg_parser = bpf_prog_inc_not_zero(msg_parser);
268                 if (IS_ERR(msg_parser)) {
269                         ret = PTR_ERR(msg_parser);
270                         goto out_put_stream_parser;
271                 }
272         }
273
274         skb_verdict = READ_ONCE(progs->skb_verdict);
275         if (skb_verdict) {
276                 skb_verdict = bpf_prog_inc_not_zero(skb_verdict);
277                 if (IS_ERR(skb_verdict)) {
278                         ret = PTR_ERR(skb_verdict);
279                         goto out_put_msg_parser;
280                 }
281         }
282
283 no_progs:
284         psock = sock_map_psock_get_checked(sk);
285         if (IS_ERR(psock)) {
286                 ret = PTR_ERR(psock);
287                 goto out_progs;
288         }
289
290         if (psock) {
291                 if ((msg_parser && READ_ONCE(psock->progs.msg_parser)) ||
292                     (stream_parser  && READ_ONCE(psock->progs.stream_parser)) ||
293                     (skb_verdict && READ_ONCE(psock->progs.skb_verdict)) ||
294                     (skb_verdict && READ_ONCE(psock->progs.stream_verdict)) ||
295                     (stream_verdict && READ_ONCE(psock->progs.skb_verdict)) ||
296                     (stream_verdict && READ_ONCE(psock->progs.stream_verdict))) {
297                         sk_psock_put(sk, psock);
298                         ret = -EBUSY;
299                         goto out_progs;
300                 }
301         } else {
302                 psock = sk_psock_init(sk, map->numa_node);
303                 if (IS_ERR(psock)) {
304                         ret = PTR_ERR(psock);
305                         goto out_progs;
306                 }
307         }
308
309         if (msg_parser)
310                 psock_set_prog(&psock->progs.msg_parser, msg_parser);
311
312         ret = sock_map_init_proto(sk, psock);
313         if (ret < 0)
314                 goto out_drop;
315
316         write_lock_bh(&sk->sk_callback_lock);
317         if (stream_parser && stream_verdict && !psock->saved_data_ready) {
318                 ret = sk_psock_init_strp(sk, psock);
319                 if (ret)
320                         goto out_unlock_drop;
321                 psock_set_prog(&psock->progs.stream_verdict, stream_verdict);
322                 psock_set_prog(&psock->progs.stream_parser, stream_parser);
323                 sk_psock_start_strp(sk, psock);
324         } else if (!stream_parser && stream_verdict && !psock->saved_data_ready) {
325                 psock_set_prog(&psock->progs.stream_verdict, stream_verdict);
326                 sk_psock_start_verdict(sk,psock);
327         } else if (!stream_verdict && skb_verdict && !psock->saved_data_ready) {
328                 psock_set_prog(&psock->progs.skb_verdict, skb_verdict);
329                 sk_psock_start_verdict(sk, psock);
330         }
331         write_unlock_bh(&sk->sk_callback_lock);
332         return 0;
333 out_unlock_drop:
334         write_unlock_bh(&sk->sk_callback_lock);
335 out_drop:
336         sk_psock_put(sk, psock);
337 out_progs:
338         if (skb_verdict)
339                 bpf_prog_put(skb_verdict);
340 out_put_msg_parser:
341         if (msg_parser)
342                 bpf_prog_put(msg_parser);
343 out_put_stream_parser:
344         if (stream_parser)
345                 bpf_prog_put(stream_parser);
346 out_put_stream_verdict:
347         if (stream_verdict)
348                 bpf_prog_put(stream_verdict);
349         return ret;
350 }
351
352 static void sock_map_free(struct bpf_map *map)
353 {
354         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
355         int i;
356
357         /* After the sync no updates or deletes will be in-flight so it
358          * is safe to walk map and remove entries without risking a race
359          * in EEXIST update case.
360          */
361         synchronize_rcu();
362         for (i = 0; i < stab->map.max_entries; i++) {
363                 struct sock **psk = &stab->sks[i];
364                 struct sock *sk;
365
366                 sk = xchg(psk, NULL);
367                 if (sk) {
368                         lock_sock(sk);
369                         rcu_read_lock();
370                         sock_map_unref(sk, psk);
371                         rcu_read_unlock();
372                         release_sock(sk);
373                 }
374         }
375
376         /* wait for psock readers accessing its map link */
377         synchronize_rcu();
378
379         bpf_map_area_free(stab->sks);
380         kfree(stab);
381 }
382
383 static void sock_map_release_progs(struct bpf_map *map)
384 {
385         psock_progs_drop(&container_of(map, struct bpf_stab, map)->progs);
386 }
387
388 static struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
389 {
390         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
391
392         WARN_ON_ONCE(!rcu_read_lock_held());
393
394         if (unlikely(key >= map->max_entries))
395                 return NULL;
396         return READ_ONCE(stab->sks[key]);
397 }
398
399 static void *sock_map_lookup(struct bpf_map *map, void *key)
400 {
401         struct sock *sk;
402
403         sk = __sock_map_lookup_elem(map, *(u32 *)key);
404         if (!sk)
405                 return NULL;
406         if (sk_is_refcounted(sk) && !refcount_inc_not_zero(&sk->sk_refcnt))
407                 return NULL;
408         return sk;
409 }
410
411 static void *sock_map_lookup_sys(struct bpf_map *map, void *key)
412 {
413         struct sock *sk;
414
415         if (map->value_size != sizeof(u64))
416                 return ERR_PTR(-ENOSPC);
417
418         sk = __sock_map_lookup_elem(map, *(u32 *)key);
419         if (!sk)
420                 return ERR_PTR(-ENOENT);
421
422         __sock_gen_cookie(sk);
423         return &sk->sk_cookie;
424 }
425
426 static int __sock_map_delete(struct bpf_stab *stab, struct sock *sk_test,
427                              struct sock **psk)
428 {
429         struct sock *sk;
430         int err = 0;
431
432         raw_spin_lock_bh(&stab->lock);
433         sk = *psk;
434         if (!sk_test || sk_test == sk)
435                 sk = xchg(psk, NULL);
436
437         if (likely(sk))
438                 sock_map_unref(sk, psk);
439         else
440                 err = -EINVAL;
441
442         raw_spin_unlock_bh(&stab->lock);
443         return err;
444 }
445
446 static void sock_map_delete_from_link(struct bpf_map *map, struct sock *sk,
447                                       void *link_raw)
448 {
449         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
450
451         __sock_map_delete(stab, sk, link_raw);
452 }
453
454 static int sock_map_delete_elem(struct bpf_map *map, void *key)
455 {
456         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
457         u32 i = *(u32 *)key;
458         struct sock **psk;
459
460         if (unlikely(i >= map->max_entries))
461                 return -EINVAL;
462
463         psk = &stab->sks[i];
464         return __sock_map_delete(stab, NULL, psk);
465 }
466
467 static int sock_map_get_next_key(struct bpf_map *map, void *key, void *next)
468 {
469         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
470         u32 i = key ? *(u32 *)key : U32_MAX;
471         u32 *key_next = next;
472
473         if (i == stab->map.max_entries - 1)
474                 return -ENOENT;
475         if (i >= stab->map.max_entries)
476                 *key_next = 0;
477         else
478                 *key_next = i + 1;
479         return 0;
480 }
481
482 static int sock_map_update_common(struct bpf_map *map, u32 idx,
483                                   struct sock *sk, u64 flags)
484 {
485         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
486         struct sk_psock_link *link;
487         struct sk_psock *psock;
488         struct sock *osk;
489         int ret;
490
491         WARN_ON_ONCE(!rcu_read_lock_held());
492         if (unlikely(flags > BPF_EXIST))
493                 return -EINVAL;
494         if (unlikely(idx >= map->max_entries))
495                 return -E2BIG;
496
497         link = sk_psock_init_link();
498         if (!link)
499                 return -ENOMEM;
500
501         ret = sock_map_link(map, sk);
502         if (ret < 0)
503                 goto out_free;
504
505         psock = sk_psock(sk);
506         WARN_ON_ONCE(!psock);
507
508         raw_spin_lock_bh(&stab->lock);
509         osk = stab->sks[idx];
510         if (osk && flags == BPF_NOEXIST) {
511                 ret = -EEXIST;
512                 goto out_unlock;
513         } else if (!osk && flags == BPF_EXIST) {
514                 ret = -ENOENT;
515                 goto out_unlock;
516         }
517
518         sock_map_add_link(psock, link, map, &stab->sks[idx]);
519         stab->sks[idx] = sk;
520         if (osk)
521                 sock_map_unref(osk, &stab->sks[idx]);
522         raw_spin_unlock_bh(&stab->lock);
523         return 0;
524 out_unlock:
525         raw_spin_unlock_bh(&stab->lock);
526         if (psock)
527                 sk_psock_put(sk, psock);
528 out_free:
529         sk_psock_free_link(link);
530         return ret;
531 }
532
533 static bool sock_map_op_okay(const struct bpf_sock_ops_kern *ops)
534 {
535         return ops->op == BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB ||
536                ops->op == BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB ||
537                ops->op == BPF_SOCK_OPS_TCP_LISTEN_CB;
538 }
539
540 static bool sk_is_tcp(const struct sock *sk)
541 {
542         return sk->sk_type == SOCK_STREAM &&
543                sk->sk_protocol == IPPROTO_TCP;
544 }
545
546 static bool sk_is_udp(const struct sock *sk)
547 {
548         return sk->sk_type == SOCK_DGRAM &&
549                sk->sk_protocol == IPPROTO_UDP;
550 }
551
552 static bool sock_map_redirect_allowed(const struct sock *sk)
553 {
554         return sk_is_tcp(sk) && sk->sk_state != TCP_LISTEN;
555 }
556
557 static bool sock_map_sk_is_suitable(const struct sock *sk)
558 {
559         return sk_is_tcp(sk) || sk_is_udp(sk);
560 }
561
562 static bool sock_map_sk_state_allowed(const struct sock *sk)
563 {
564         if (sk_is_tcp(sk))
565                 return (1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_LISTEN);
566         else if (sk_is_udp(sk))
567                 return sk_hashed(sk);
568
569         return false;
570 }
571
572 static int sock_hash_update_common(struct bpf_map *map, void *key,
573                                    struct sock *sk, u64 flags);
574
575 int sock_map_update_elem_sys(struct bpf_map *map, void *key, void *value,
576                              u64 flags)
577 {
578         struct socket *sock;
579         struct sock *sk;
580         int ret;
581         u64 ufd;
582
583         if (map->value_size == sizeof(u64))
584                 ufd = *(u64 *)value;
585         else
586                 ufd = *(u32 *)value;
587         if (ufd > S32_MAX)
588                 return -EINVAL;
589
590         sock = sockfd_lookup(ufd, &ret);
591         if (!sock)
592                 return ret;
593         sk = sock->sk;
594         if (!sk) {
595                 ret = -EINVAL;
596                 goto out;
597         }
598         if (!sock_map_sk_is_suitable(sk)) {
599                 ret = -EOPNOTSUPP;
600                 goto out;
601         }
602
603         sock_map_sk_acquire(sk);
604         if (!sock_map_sk_state_allowed(sk))
605                 ret = -EOPNOTSUPP;
606         else if (map->map_type == BPF_MAP_TYPE_SOCKMAP)
607                 ret = sock_map_update_common(map, *(u32 *)key, sk, flags);
608         else
609                 ret = sock_hash_update_common(map, key, sk, flags);
610         sock_map_sk_release(sk);
611 out:
612         sockfd_put(sock);
613         return ret;
614 }
615
616 static int sock_map_update_elem(struct bpf_map *map, void *key,
617                                 void *value, u64 flags)
618 {
619         struct sock *sk = (struct sock *)value;
620         int ret;
621
622         if (unlikely(!sk || !sk_fullsock(sk)))
623                 return -EINVAL;
624
625         if (!sock_map_sk_is_suitable(sk))
626                 return -EOPNOTSUPP;
627
628         local_bh_disable();
629         bh_lock_sock(sk);
630         if (!sock_map_sk_state_allowed(sk))
631                 ret = -EOPNOTSUPP;
632         else if (map->map_type == BPF_MAP_TYPE_SOCKMAP)
633                 ret = sock_map_update_common(map, *(u32 *)key, sk, flags);
634         else
635                 ret = sock_hash_update_common(map, key, sk, flags);
636         bh_unlock_sock(sk);
637         local_bh_enable();
638         return ret;
639 }
640
641 BPF_CALL_4(bpf_sock_map_update, struct bpf_sock_ops_kern *, sops,
642            struct bpf_map *, map, void *, key, u64, flags)
643 {
644         WARN_ON_ONCE(!rcu_read_lock_held());
645
646         if (likely(sock_map_sk_is_suitable(sops->sk) &&
647                    sock_map_op_okay(sops)))
648                 return sock_map_update_common(map, *(u32 *)key, sops->sk,
649                                               flags);
650         return -EOPNOTSUPP;
651 }
652
653 const struct bpf_func_proto bpf_sock_map_update_proto = {
654         .func           = bpf_sock_map_update,
655         .gpl_only       = false,
656         .pkt_access     = true,
657         .ret_type       = RET_INTEGER,
658         .arg1_type      = ARG_PTR_TO_CTX,
659         .arg2_type      = ARG_CONST_MAP_PTR,
660         .arg3_type      = ARG_PTR_TO_MAP_KEY,
661         .arg4_type      = ARG_ANYTHING,
662 };
663
664 BPF_CALL_4(bpf_sk_redirect_map, struct sk_buff *, skb,
665            struct bpf_map *, map, u32, key, u64, flags)
666 {
667         struct sock *sk;
668
669         if (unlikely(flags & ~(BPF_F_INGRESS)))
670                 return SK_DROP;
671
672         sk = __sock_map_lookup_elem(map, key);
673         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
674                 return SK_DROP;
675
676         skb_bpf_set_redir(skb, sk, flags & BPF_F_INGRESS);
677         return SK_PASS;
678 }
679
680 const struct bpf_func_proto bpf_sk_redirect_map_proto = {
681         .func           = bpf_sk_redirect_map,
682         .gpl_only       = false,
683         .ret_type       = RET_INTEGER,
684         .arg1_type      = ARG_PTR_TO_CTX,
685         .arg2_type      = ARG_CONST_MAP_PTR,
686         .arg3_type      = ARG_ANYTHING,
687         .arg4_type      = ARG_ANYTHING,
688 };
689
690 BPF_CALL_4(bpf_msg_redirect_map, struct sk_msg *, msg,
691            struct bpf_map *, map, u32, key, u64, flags)
692 {
693         struct sock *sk;
694
695         if (unlikely(flags & ~(BPF_F_INGRESS)))
696                 return SK_DROP;
697
698         sk = __sock_map_lookup_elem(map, key);
699         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
700                 return SK_DROP;
701
702         msg->flags = flags;
703         msg->sk_redir = sk;
704         return SK_PASS;
705 }
706
707 const struct bpf_func_proto bpf_msg_redirect_map_proto = {
708         .func           = bpf_msg_redirect_map,
709         .gpl_only       = false,
710         .ret_type       = RET_INTEGER,
711         .arg1_type      = ARG_PTR_TO_CTX,
712         .arg2_type      = ARG_CONST_MAP_PTR,
713         .arg3_type      = ARG_ANYTHING,
714         .arg4_type      = ARG_ANYTHING,
715 };
716
717 struct sock_map_seq_info {
718         struct bpf_map *map;
719         struct sock *sk;
720         u32 index;
721 };
722
723 struct bpf_iter__sockmap {
724         __bpf_md_ptr(struct bpf_iter_meta *, meta);
725         __bpf_md_ptr(struct bpf_map *, map);
726         __bpf_md_ptr(void *, key);
727         __bpf_md_ptr(struct sock *, sk);
728 };
729
730 DEFINE_BPF_ITER_FUNC(sockmap, struct bpf_iter_meta *meta,
731                      struct bpf_map *map, void *key,
732                      struct sock *sk)
733
734 static void *sock_map_seq_lookup_elem(struct sock_map_seq_info *info)
735 {
736         if (unlikely(info->index >= info->map->max_entries))
737                 return NULL;
738
739         info->sk = __sock_map_lookup_elem(info->map, info->index);
740
741         /* can't return sk directly, since that might be NULL */
742         return info;
743 }
744
745 static void *sock_map_seq_start(struct seq_file *seq, loff_t *pos)
746         __acquires(rcu)
747 {
748         struct sock_map_seq_info *info = seq->private;
749
750         if (*pos == 0)
751                 ++*pos;
752
753         /* pairs with sock_map_seq_stop */
754         rcu_read_lock();
755         return sock_map_seq_lookup_elem(info);
756 }
757
758 static void *sock_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
759         __must_hold(rcu)
760 {
761         struct sock_map_seq_info *info = seq->private;
762
763         ++*pos;
764         ++info->index;
765
766         return sock_map_seq_lookup_elem(info);
767 }
768
769 static int sock_map_seq_show(struct seq_file *seq, void *v)
770         __must_hold(rcu)
771 {
772         struct sock_map_seq_info *info = seq->private;
773         struct bpf_iter__sockmap ctx = {};
774         struct bpf_iter_meta meta;
775         struct bpf_prog *prog;
776
777         meta.seq = seq;
778         prog = bpf_iter_get_info(&meta, !v);
779         if (!prog)
780                 return 0;
781
782         ctx.meta = &meta;
783         ctx.map = info->map;
784         if (v) {
785                 ctx.key = &info->index;
786                 ctx.sk = info->sk;
787         }
788
789         return bpf_iter_run_prog(prog, &ctx);
790 }
791
792 static void sock_map_seq_stop(struct seq_file *seq, void *v)
793         __releases(rcu)
794 {
795         if (!v)
796                 (void)sock_map_seq_show(seq, NULL);
797
798         /* pairs with sock_map_seq_start */
799         rcu_read_unlock();
800 }
801
802 static const struct seq_operations sock_map_seq_ops = {
803         .start  = sock_map_seq_start,
804         .next   = sock_map_seq_next,
805         .stop   = sock_map_seq_stop,
806         .show   = sock_map_seq_show,
807 };
808
809 static int sock_map_init_seq_private(void *priv_data,
810                                      struct bpf_iter_aux_info *aux)
811 {
812         struct sock_map_seq_info *info = priv_data;
813
814         info->map = aux->map;
815         return 0;
816 }
817
818 static const struct bpf_iter_seq_info sock_map_iter_seq_info = {
819         .seq_ops                = &sock_map_seq_ops,
820         .init_seq_private       = sock_map_init_seq_private,
821         .seq_priv_size          = sizeof(struct sock_map_seq_info),
822 };
823
824 static int sock_map_btf_id;
825 const struct bpf_map_ops sock_map_ops = {
826         .map_meta_equal         = bpf_map_meta_equal,
827         .map_alloc              = sock_map_alloc,
828         .map_free               = sock_map_free,
829         .map_get_next_key       = sock_map_get_next_key,
830         .map_lookup_elem_sys_only = sock_map_lookup_sys,
831         .map_update_elem        = sock_map_update_elem,
832         .map_delete_elem        = sock_map_delete_elem,
833         .map_lookup_elem        = sock_map_lookup,
834         .map_release_uref       = sock_map_release_progs,
835         .map_check_btf          = map_check_no_btf,
836         .map_btf_name           = "bpf_stab",
837         .map_btf_id             = &sock_map_btf_id,
838         .iter_seq_info          = &sock_map_iter_seq_info,
839 };
840
841 struct bpf_shtab_elem {
842         struct rcu_head rcu;
843         u32 hash;
844         struct sock *sk;
845         struct hlist_node node;
846         u8 key[];
847 };
848
849 struct bpf_shtab_bucket {
850         struct hlist_head head;
851         raw_spinlock_t lock;
852 };
853
854 struct bpf_shtab {
855         struct bpf_map map;
856         struct bpf_shtab_bucket *buckets;
857         u32 buckets_num;
858         u32 elem_size;
859         struct sk_psock_progs progs;
860         atomic_t count;
861 };
862
863 static inline u32 sock_hash_bucket_hash(const void *key, u32 len)
864 {
865         return jhash(key, len, 0);
866 }
867
868 static struct bpf_shtab_bucket *sock_hash_select_bucket(struct bpf_shtab *htab,
869                                                         u32 hash)
870 {
871         return &htab->buckets[hash & (htab->buckets_num - 1)];
872 }
873
874 static struct bpf_shtab_elem *
875 sock_hash_lookup_elem_raw(struct hlist_head *head, u32 hash, void *key,
876                           u32 key_size)
877 {
878         struct bpf_shtab_elem *elem;
879
880         hlist_for_each_entry_rcu(elem, head, node) {
881                 if (elem->hash == hash &&
882                     !memcmp(&elem->key, key, key_size))
883                         return elem;
884         }
885
886         return NULL;
887 }
888
889 static struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
890 {
891         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
892         u32 key_size = map->key_size, hash;
893         struct bpf_shtab_bucket *bucket;
894         struct bpf_shtab_elem *elem;
895
896         WARN_ON_ONCE(!rcu_read_lock_held());
897
898         hash = sock_hash_bucket_hash(key, key_size);
899         bucket = sock_hash_select_bucket(htab, hash);
900         elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
901
902         return elem ? elem->sk : NULL;
903 }
904
905 static void sock_hash_free_elem(struct bpf_shtab *htab,
906                                 struct bpf_shtab_elem *elem)
907 {
908         atomic_dec(&htab->count);
909         kfree_rcu(elem, rcu);
910 }
911
912 static void sock_hash_delete_from_link(struct bpf_map *map, struct sock *sk,
913                                        void *link_raw)
914 {
915         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
916         struct bpf_shtab_elem *elem_probe, *elem = link_raw;
917         struct bpf_shtab_bucket *bucket;
918
919         WARN_ON_ONCE(!rcu_read_lock_held());
920         bucket = sock_hash_select_bucket(htab, elem->hash);
921
922         /* elem may be deleted in parallel from the map, but access here
923          * is okay since it's going away only after RCU grace period.
924          * However, we need to check whether it's still present.
925          */
926         raw_spin_lock_bh(&bucket->lock);
927         elem_probe = sock_hash_lookup_elem_raw(&bucket->head, elem->hash,
928                                                elem->key, map->key_size);
929         if (elem_probe && elem_probe == elem) {
930                 hlist_del_rcu(&elem->node);
931                 sock_map_unref(elem->sk, elem);
932                 sock_hash_free_elem(htab, elem);
933         }
934         raw_spin_unlock_bh(&bucket->lock);
935 }
936
937 static int sock_hash_delete_elem(struct bpf_map *map, void *key)
938 {
939         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
940         u32 hash, key_size = map->key_size;
941         struct bpf_shtab_bucket *bucket;
942         struct bpf_shtab_elem *elem;
943         int ret = -ENOENT;
944
945         hash = sock_hash_bucket_hash(key, key_size);
946         bucket = sock_hash_select_bucket(htab, hash);
947
948         raw_spin_lock_bh(&bucket->lock);
949         elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
950         if (elem) {
951                 hlist_del_rcu(&elem->node);
952                 sock_map_unref(elem->sk, elem);
953                 sock_hash_free_elem(htab, elem);
954                 ret = 0;
955         }
956         raw_spin_unlock_bh(&bucket->lock);
957         return ret;
958 }
959
960 static struct bpf_shtab_elem *sock_hash_alloc_elem(struct bpf_shtab *htab,
961                                                    void *key, u32 key_size,
962                                                    u32 hash, struct sock *sk,
963                                                    struct bpf_shtab_elem *old)
964 {
965         struct bpf_shtab_elem *new;
966
967         if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
968                 if (!old) {
969                         atomic_dec(&htab->count);
970                         return ERR_PTR(-E2BIG);
971                 }
972         }
973
974         new = bpf_map_kmalloc_node(&htab->map, htab->elem_size,
975                                    GFP_ATOMIC | __GFP_NOWARN,
976                                    htab->map.numa_node);
977         if (!new) {
978                 atomic_dec(&htab->count);
979                 return ERR_PTR(-ENOMEM);
980         }
981         memcpy(new->key, key, key_size);
982         new->sk = sk;
983         new->hash = hash;
984         return new;
985 }
986
987 static int sock_hash_update_common(struct bpf_map *map, void *key,
988                                    struct sock *sk, u64 flags)
989 {
990         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
991         u32 key_size = map->key_size, hash;
992         struct bpf_shtab_elem *elem, *elem_new;
993         struct bpf_shtab_bucket *bucket;
994         struct sk_psock_link *link;
995         struct sk_psock *psock;
996         int ret;
997
998         WARN_ON_ONCE(!rcu_read_lock_held());
999         if (unlikely(flags > BPF_EXIST))
1000                 return -EINVAL;
1001
1002         link = sk_psock_init_link();
1003         if (!link)
1004                 return -ENOMEM;
1005
1006         ret = sock_map_link(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 static 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                 if (progs->skb_verdict)
1467                         return -EBUSY;
1468                 pprog = &progs->stream_verdict;
1469                 break;
1470         case BPF_SK_SKB_VERDICT:
1471                 if (progs->stream_verdict)
1472                         return -EBUSY;
1473                 pprog = &progs->skb_verdict;
1474                 break;
1475         default:
1476                 return -EOPNOTSUPP;
1477         }
1478
1479         if (old)
1480                 return psock_replace_prog(pprog, prog, old);
1481
1482         psock_set_prog(pprog, prog);
1483         return 0;
1484 }
1485
1486 static void sock_map_unlink(struct sock *sk, struct sk_psock_link *link)
1487 {
1488         switch (link->map->map_type) {
1489         case BPF_MAP_TYPE_SOCKMAP:
1490                 return sock_map_delete_from_link(link->map, sk,
1491                                                  link->link_raw);
1492         case BPF_MAP_TYPE_SOCKHASH:
1493                 return sock_hash_delete_from_link(link->map, sk,
1494                                                   link->link_raw);
1495         default:
1496                 break;
1497         }
1498 }
1499
1500 static void sock_map_remove_links(struct sock *sk, struct sk_psock *psock)
1501 {
1502         struct sk_psock_link *link;
1503
1504         while ((link = sk_psock_link_pop(psock))) {
1505                 sock_map_unlink(sk, link);
1506                 sk_psock_free_link(link);
1507         }
1508 }
1509
1510 void sock_map_unhash(struct sock *sk)
1511 {
1512         void (*saved_unhash)(struct sock *sk);
1513         struct sk_psock *psock;
1514
1515         rcu_read_lock();
1516         psock = sk_psock(sk);
1517         if (unlikely(!psock)) {
1518                 rcu_read_unlock();
1519                 if (sk->sk_prot->unhash)
1520                         sk->sk_prot->unhash(sk);
1521                 return;
1522         }
1523
1524         saved_unhash = psock->saved_unhash;
1525         sock_map_remove_links(sk, psock);
1526         rcu_read_unlock();
1527         saved_unhash(sk);
1528 }
1529
1530 void sock_map_close(struct sock *sk, long timeout)
1531 {
1532         void (*saved_close)(struct sock *sk, long timeout);
1533         struct sk_psock *psock;
1534
1535         lock_sock(sk);
1536         rcu_read_lock();
1537         psock = sk_psock(sk);
1538         if (unlikely(!psock)) {
1539                 rcu_read_unlock();
1540                 release_sock(sk);
1541                 return sk->sk_prot->close(sk, timeout);
1542         }
1543
1544         saved_close = psock->saved_close;
1545         sock_map_remove_links(sk, psock);
1546         rcu_read_unlock();
1547         sk_psock_stop(psock, true);
1548         release_sock(sk);
1549         saved_close(sk, timeout);
1550 }
1551
1552 static int sock_map_iter_attach_target(struct bpf_prog *prog,
1553                                        union bpf_iter_link_info *linfo,
1554                                        struct bpf_iter_aux_info *aux)
1555 {
1556         struct bpf_map *map;
1557         int err = -EINVAL;
1558
1559         if (!linfo->map.map_fd)
1560                 return -EBADF;
1561
1562         map = bpf_map_get_with_uref(linfo->map.map_fd);
1563         if (IS_ERR(map))
1564                 return PTR_ERR(map);
1565
1566         if (map->map_type != BPF_MAP_TYPE_SOCKMAP &&
1567             map->map_type != BPF_MAP_TYPE_SOCKHASH)
1568                 goto put_map;
1569
1570         if (prog->aux->max_rdonly_access > map->key_size) {
1571                 err = -EACCES;
1572                 goto put_map;
1573         }
1574
1575         aux->map = map;
1576         return 0;
1577
1578 put_map:
1579         bpf_map_put_with_uref(map);
1580         return err;
1581 }
1582
1583 static void sock_map_iter_detach_target(struct bpf_iter_aux_info *aux)
1584 {
1585         bpf_map_put_with_uref(aux->map);
1586 }
1587
1588 static struct bpf_iter_reg sock_map_iter_reg = {
1589         .target                 = "sockmap",
1590         .attach_target          = sock_map_iter_attach_target,
1591         .detach_target          = sock_map_iter_detach_target,
1592         .show_fdinfo            = bpf_iter_map_show_fdinfo,
1593         .fill_link_info         = bpf_iter_map_fill_link_info,
1594         .ctx_arg_info_size      = 2,
1595         .ctx_arg_info           = {
1596                 { offsetof(struct bpf_iter__sockmap, key),
1597                   PTR_TO_RDONLY_BUF_OR_NULL },
1598                 { offsetof(struct bpf_iter__sockmap, sk),
1599                   PTR_TO_BTF_ID_OR_NULL },
1600         },
1601 };
1602
1603 static int __init bpf_sockmap_iter_init(void)
1604 {
1605         sock_map_iter_reg.ctx_arg_info[1].btf_id =
1606                 btf_sock_ids[BTF_SOCK_TYPE_SOCK];
1607         return bpf_iter_reg_target(&sock_map_iter_reg);
1608 }
1609 late_initcall(bpf_sockmap_iter_init);