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