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