bpf: Set map_btf_{name, id} for all map types
[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/filter.h>
6 #include <linux/errno.h>
7 #include <linux/file.h>
8 #include <linux/net.h>
9 #include <linux/workqueue.h>
10 #include <linux/skmsg.h>
11 #include <linux/list.h>
12 #include <linux/jhash.h>
13 #include <linux/sock_diag.h>
14 #include <net/udp.h>
15
16 struct bpf_stab {
17         struct bpf_map map;
18         struct sock **sks;
19         struct sk_psock_progs progs;
20         raw_spinlock_t lock;
21 };
22
23 #define SOCK_CREATE_FLAG_MASK                           \
24         (BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY)
25
26 static struct bpf_map *sock_map_alloc(union bpf_attr *attr)
27 {
28         struct bpf_stab *stab;
29         u64 cost;
30         int err;
31
32         if (!capable(CAP_NET_ADMIN))
33                 return ERR_PTR(-EPERM);
34         if (attr->max_entries == 0 ||
35             attr->key_size    != 4 ||
36             (attr->value_size != sizeof(u32) &&
37              attr->value_size != sizeof(u64)) ||
38             attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
39                 return ERR_PTR(-EINVAL);
40
41         stab = kzalloc(sizeof(*stab), GFP_USER);
42         if (!stab)
43                 return ERR_PTR(-ENOMEM);
44
45         bpf_map_init_from_attr(&stab->map, attr);
46         raw_spin_lock_init(&stab->lock);
47
48         /* Make sure page count doesn't overflow. */
49         cost = (u64) stab->map.max_entries * sizeof(struct sock *);
50         err = bpf_map_charge_init(&stab->map.memory, cost);
51         if (err)
52                 goto free_stab;
53
54         stab->sks = bpf_map_area_alloc(stab->map.max_entries *
55                                        sizeof(struct sock *),
56                                        stab->map.numa_node);
57         if (stab->sks)
58                 return &stab->map;
59         err = -ENOMEM;
60         bpf_map_charge_finish(&stab->map.memory);
61 free_stab:
62         kfree(stab);
63         return ERR_PTR(err);
64 }
65
66 int sock_map_get_from_fd(const union bpf_attr *attr, struct bpf_prog *prog)
67 {
68         u32 ufd = attr->target_fd;
69         struct bpf_map *map;
70         struct fd f;
71         int ret;
72
73         f = fdget(ufd);
74         map = __bpf_map_get(f);
75         if (IS_ERR(map))
76                 return PTR_ERR(map);
77         ret = sock_map_prog_update(map, prog, attr->attach_type);
78         fdput(f);
79         return ret;
80 }
81
82 static void sock_map_sk_acquire(struct sock *sk)
83         __acquires(&sk->sk_lock.slock)
84 {
85         lock_sock(sk);
86         preempt_disable();
87         rcu_read_lock();
88 }
89
90 static void sock_map_sk_release(struct sock *sk)
91         __releases(&sk->sk_lock.slock)
92 {
93         rcu_read_unlock();
94         preempt_enable();
95         release_sock(sk);
96 }
97
98 static void sock_map_add_link(struct sk_psock *psock,
99                               struct sk_psock_link *link,
100                               struct bpf_map *map, void *link_raw)
101 {
102         link->link_raw = link_raw;
103         link->map = map;
104         spin_lock_bh(&psock->link_lock);
105         list_add_tail(&link->list, &psock->link);
106         spin_unlock_bh(&psock->link_lock);
107 }
108
109 static void sock_map_del_link(struct sock *sk,
110                               struct sk_psock *psock, void *link_raw)
111 {
112         struct sk_psock_link *link, *tmp;
113         bool strp_stop = false;
114
115         spin_lock_bh(&psock->link_lock);
116         list_for_each_entry_safe(link, tmp, &psock->link, list) {
117                 if (link->link_raw == link_raw) {
118                         struct bpf_map *map = link->map;
119                         struct bpf_stab *stab = container_of(map, struct bpf_stab,
120                                                              map);
121                         if (psock->parser.enabled && stab->progs.skb_parser)
122                                 strp_stop = true;
123                         list_del(&link->list);
124                         sk_psock_free_link(link);
125                 }
126         }
127         spin_unlock_bh(&psock->link_lock);
128         if (strp_stop) {
129                 write_lock_bh(&sk->sk_callback_lock);
130                 sk_psock_stop_strp(sk, psock);
131                 write_unlock_bh(&sk->sk_callback_lock);
132         }
133 }
134
135 static void sock_map_unref(struct sock *sk, void *link_raw)
136 {
137         struct sk_psock *psock = sk_psock(sk);
138
139         if (likely(psock)) {
140                 sock_map_del_link(sk, psock, link_raw);
141                 sk_psock_put(sk, psock);
142         }
143 }
144
145 static int sock_map_init_proto(struct sock *sk, struct sk_psock *psock)
146 {
147         struct proto *prot;
148
149         sock_owned_by_me(sk);
150
151         switch (sk->sk_type) {
152         case SOCK_STREAM:
153                 prot = tcp_bpf_get_proto(sk, psock);
154                 break;
155
156         case SOCK_DGRAM:
157                 prot = udp_bpf_get_proto(sk, psock);
158                 break;
159
160         default:
161                 return -EINVAL;
162         }
163
164         if (IS_ERR(prot))
165                 return PTR_ERR(prot);
166
167         sk_psock_update_proto(sk, psock, prot);
168         return 0;
169 }
170
171 static struct sk_psock *sock_map_psock_get_checked(struct sock *sk)
172 {
173         struct sk_psock *psock;
174
175         rcu_read_lock();
176         psock = sk_psock(sk);
177         if (psock) {
178                 if (sk->sk_prot->close != sock_map_close) {
179                         psock = ERR_PTR(-EBUSY);
180                         goto out;
181                 }
182
183                 if (!refcount_inc_not_zero(&psock->refcnt))
184                         psock = ERR_PTR(-EBUSY);
185         }
186 out:
187         rcu_read_unlock();
188         return psock;
189 }
190
191 static int sock_map_link(struct bpf_map *map, struct sk_psock_progs *progs,
192                          struct sock *sk)
193 {
194         struct bpf_prog *msg_parser, *skb_parser, *skb_verdict;
195         struct sk_psock *psock;
196         bool skb_progs;
197         int ret;
198
199         skb_verdict = READ_ONCE(progs->skb_verdict);
200         skb_parser = READ_ONCE(progs->skb_parser);
201         skb_progs = skb_parser && skb_verdict;
202         if (skb_progs) {
203                 skb_verdict = bpf_prog_inc_not_zero(skb_verdict);
204                 if (IS_ERR(skb_verdict))
205                         return PTR_ERR(skb_verdict);
206                 skb_parser = bpf_prog_inc_not_zero(skb_parser);
207                 if (IS_ERR(skb_parser)) {
208                         bpf_prog_put(skb_verdict);
209                         return PTR_ERR(skb_parser);
210                 }
211         }
212
213         msg_parser = READ_ONCE(progs->msg_parser);
214         if (msg_parser) {
215                 msg_parser = bpf_prog_inc_not_zero(msg_parser);
216                 if (IS_ERR(msg_parser)) {
217                         ret = PTR_ERR(msg_parser);
218                         goto out;
219                 }
220         }
221
222         psock = sock_map_psock_get_checked(sk);
223         if (IS_ERR(psock)) {
224                 ret = PTR_ERR(psock);
225                 goto out_progs;
226         }
227
228         if (psock) {
229                 if ((msg_parser && READ_ONCE(psock->progs.msg_parser)) ||
230                     (skb_progs  && READ_ONCE(psock->progs.skb_parser))) {
231                         sk_psock_put(sk, psock);
232                         ret = -EBUSY;
233                         goto out_progs;
234                 }
235         } else {
236                 psock = sk_psock_init(sk, map->numa_node);
237                 if (!psock) {
238                         ret = -ENOMEM;
239                         goto out_progs;
240                 }
241         }
242
243         if (msg_parser)
244                 psock_set_prog(&psock->progs.msg_parser, msg_parser);
245
246         ret = sock_map_init_proto(sk, psock);
247         if (ret < 0)
248                 goto out_drop;
249
250         write_lock_bh(&sk->sk_callback_lock);
251         if (skb_progs && !psock->parser.enabled) {
252                 ret = sk_psock_init_strp(sk, psock);
253                 if (ret) {
254                         write_unlock_bh(&sk->sk_callback_lock);
255                         goto out_drop;
256                 }
257                 psock_set_prog(&psock->progs.skb_verdict, skb_verdict);
258                 psock_set_prog(&psock->progs.skb_parser, skb_parser);
259                 sk_psock_start_strp(sk, psock);
260         }
261         write_unlock_bh(&sk->sk_callback_lock);
262         return 0;
263 out_drop:
264         sk_psock_put(sk, psock);
265 out_progs:
266         if (msg_parser)
267                 bpf_prog_put(msg_parser);
268 out:
269         if (skb_progs) {
270                 bpf_prog_put(skb_verdict);
271                 bpf_prog_put(skb_parser);
272         }
273         return ret;
274 }
275
276 static int sock_map_link_no_progs(struct bpf_map *map, struct sock *sk)
277 {
278         struct sk_psock *psock;
279         int ret;
280
281         psock = sock_map_psock_get_checked(sk);
282         if (IS_ERR(psock))
283                 return PTR_ERR(psock);
284
285         if (!psock) {
286                 psock = sk_psock_init(sk, map->numa_node);
287                 if (!psock)
288                         return -ENOMEM;
289         }
290
291         ret = sock_map_init_proto(sk, psock);
292         if (ret < 0)
293                 sk_psock_put(sk, psock);
294         return ret;
295 }
296
297 static void sock_map_free(struct bpf_map *map)
298 {
299         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
300         int i;
301
302         /* After the sync no updates or deletes will be in-flight so it
303          * is safe to walk map and remove entries without risking a race
304          * in EEXIST update case.
305          */
306         synchronize_rcu();
307         for (i = 0; i < stab->map.max_entries; i++) {
308                 struct sock **psk = &stab->sks[i];
309                 struct sock *sk;
310
311                 sk = xchg(psk, NULL);
312                 if (sk) {
313                         lock_sock(sk);
314                         rcu_read_lock();
315                         sock_map_unref(sk, psk);
316                         rcu_read_unlock();
317                         release_sock(sk);
318                 }
319         }
320
321         /* wait for psock readers accessing its map link */
322         synchronize_rcu();
323
324         bpf_map_area_free(stab->sks);
325         kfree(stab);
326 }
327
328 static void sock_map_release_progs(struct bpf_map *map)
329 {
330         psock_progs_drop(&container_of(map, struct bpf_stab, map)->progs);
331 }
332
333 static struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
334 {
335         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
336
337         WARN_ON_ONCE(!rcu_read_lock_held());
338
339         if (unlikely(key >= map->max_entries))
340                 return NULL;
341         return READ_ONCE(stab->sks[key]);
342 }
343
344 static void *sock_map_lookup(struct bpf_map *map, void *key)
345 {
346         struct sock *sk;
347
348         sk = __sock_map_lookup_elem(map, *(u32 *)key);
349         if (!sk || !sk_fullsock(sk))
350                 return NULL;
351         if (sk_is_refcounted(sk) && !refcount_inc_not_zero(&sk->sk_refcnt))
352                 return NULL;
353         return sk;
354 }
355
356 static void *sock_map_lookup_sys(struct bpf_map *map, void *key)
357 {
358         struct sock *sk;
359
360         if (map->value_size != sizeof(u64))
361                 return ERR_PTR(-ENOSPC);
362
363         sk = __sock_map_lookup_elem(map, *(u32 *)key);
364         if (!sk)
365                 return ERR_PTR(-ENOENT);
366
367         sock_gen_cookie(sk);
368         return &sk->sk_cookie;
369 }
370
371 static int __sock_map_delete(struct bpf_stab *stab, struct sock *sk_test,
372                              struct sock **psk)
373 {
374         struct sock *sk;
375         int err = 0;
376
377         raw_spin_lock_bh(&stab->lock);
378         sk = *psk;
379         if (!sk_test || sk_test == sk)
380                 sk = xchg(psk, NULL);
381
382         if (likely(sk))
383                 sock_map_unref(sk, psk);
384         else
385                 err = -EINVAL;
386
387         raw_spin_unlock_bh(&stab->lock);
388         return err;
389 }
390
391 static void sock_map_delete_from_link(struct bpf_map *map, struct sock *sk,
392                                       void *link_raw)
393 {
394         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
395
396         __sock_map_delete(stab, sk, link_raw);
397 }
398
399 static int sock_map_delete_elem(struct bpf_map *map, void *key)
400 {
401         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
402         u32 i = *(u32 *)key;
403         struct sock **psk;
404
405         if (unlikely(i >= map->max_entries))
406                 return -EINVAL;
407
408         psk = &stab->sks[i];
409         return __sock_map_delete(stab, NULL, psk);
410 }
411
412 static int sock_map_get_next_key(struct bpf_map *map, void *key, void *next)
413 {
414         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
415         u32 i = key ? *(u32 *)key : U32_MAX;
416         u32 *key_next = next;
417
418         if (i == stab->map.max_entries - 1)
419                 return -ENOENT;
420         if (i >= stab->map.max_entries)
421                 *key_next = 0;
422         else
423                 *key_next = i + 1;
424         return 0;
425 }
426
427 static bool sock_map_redirect_allowed(const struct sock *sk);
428
429 static int sock_map_update_common(struct bpf_map *map, u32 idx,
430                                   struct sock *sk, u64 flags)
431 {
432         struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
433         struct sk_psock_link *link;
434         struct sk_psock *psock;
435         struct sock *osk;
436         int ret;
437
438         WARN_ON_ONCE(!rcu_read_lock_held());
439         if (unlikely(flags > BPF_EXIST))
440                 return -EINVAL;
441         if (unlikely(idx >= map->max_entries))
442                 return -E2BIG;
443         if (inet_csk_has_ulp(sk))
444                 return -EINVAL;
445
446         link = sk_psock_init_link();
447         if (!link)
448                 return -ENOMEM;
449
450         /* Only sockets we can redirect into/from in BPF need to hold
451          * refs to parser/verdict progs and have their sk_data_ready
452          * and sk_write_space callbacks overridden.
453          */
454         if (sock_map_redirect_allowed(sk))
455                 ret = sock_map_link(map, &stab->progs, sk);
456         else
457                 ret = sock_map_link_no_progs(map, sk);
458         if (ret < 0)
459                 goto out_free;
460
461         psock = sk_psock(sk);
462         WARN_ON_ONCE(!psock);
463
464         raw_spin_lock_bh(&stab->lock);
465         osk = stab->sks[idx];
466         if (osk && flags == BPF_NOEXIST) {
467                 ret = -EEXIST;
468                 goto out_unlock;
469         } else if (!osk && flags == BPF_EXIST) {
470                 ret = -ENOENT;
471                 goto out_unlock;
472         }
473
474         sock_map_add_link(psock, link, map, &stab->sks[idx]);
475         stab->sks[idx] = sk;
476         if (osk)
477                 sock_map_unref(osk, &stab->sks[idx]);
478         raw_spin_unlock_bh(&stab->lock);
479         return 0;
480 out_unlock:
481         raw_spin_unlock_bh(&stab->lock);
482         if (psock)
483                 sk_psock_put(sk, psock);
484 out_free:
485         sk_psock_free_link(link);
486         return ret;
487 }
488
489 static bool sock_map_op_okay(const struct bpf_sock_ops_kern *ops)
490 {
491         return ops->op == BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB ||
492                ops->op == BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB ||
493                ops->op == BPF_SOCK_OPS_TCP_LISTEN_CB;
494 }
495
496 static bool sk_is_tcp(const struct sock *sk)
497 {
498         return sk->sk_type == SOCK_STREAM &&
499                sk->sk_protocol == IPPROTO_TCP;
500 }
501
502 static bool sk_is_udp(const struct sock *sk)
503 {
504         return sk->sk_type == SOCK_DGRAM &&
505                sk->sk_protocol == IPPROTO_UDP;
506 }
507
508 static bool sock_map_redirect_allowed(const struct sock *sk)
509 {
510         return sk_is_tcp(sk) && sk->sk_state != TCP_LISTEN;
511 }
512
513 static bool sock_map_sk_is_suitable(const struct sock *sk)
514 {
515         return sk_is_tcp(sk) || sk_is_udp(sk);
516 }
517
518 static bool sock_map_sk_state_allowed(const struct sock *sk)
519 {
520         if (sk_is_tcp(sk))
521                 return (1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_LISTEN);
522         else if (sk_is_udp(sk))
523                 return sk_hashed(sk);
524
525         return false;
526 }
527
528 static int sock_map_update_elem(struct bpf_map *map, void *key,
529                                 void *value, u64 flags)
530 {
531         u32 idx = *(u32 *)key;
532         struct socket *sock;
533         struct sock *sk;
534         int ret;
535         u64 ufd;
536
537         if (map->value_size == sizeof(u64))
538                 ufd = *(u64 *)value;
539         else
540                 ufd = *(u32 *)value;
541         if (ufd > S32_MAX)
542                 return -EINVAL;
543
544         sock = sockfd_lookup(ufd, &ret);
545         if (!sock)
546                 return ret;
547         sk = sock->sk;
548         if (!sk) {
549                 ret = -EINVAL;
550                 goto out;
551         }
552         if (!sock_map_sk_is_suitable(sk)) {
553                 ret = -EOPNOTSUPP;
554                 goto out;
555         }
556
557         sock_map_sk_acquire(sk);
558         if (!sock_map_sk_state_allowed(sk))
559                 ret = -EOPNOTSUPP;
560         else
561                 ret = sock_map_update_common(map, idx, sk, flags);
562         sock_map_sk_release(sk);
563 out:
564         fput(sock->file);
565         return ret;
566 }
567
568 BPF_CALL_4(bpf_sock_map_update, struct bpf_sock_ops_kern *, sops,
569            struct bpf_map *, map, void *, key, u64, flags)
570 {
571         WARN_ON_ONCE(!rcu_read_lock_held());
572
573         if (likely(sock_map_sk_is_suitable(sops->sk) &&
574                    sock_map_op_okay(sops)))
575                 return sock_map_update_common(map, *(u32 *)key, sops->sk,
576                                               flags);
577         return -EOPNOTSUPP;
578 }
579
580 const struct bpf_func_proto bpf_sock_map_update_proto = {
581         .func           = bpf_sock_map_update,
582         .gpl_only       = false,
583         .pkt_access     = true,
584         .ret_type       = RET_INTEGER,
585         .arg1_type      = ARG_PTR_TO_CTX,
586         .arg2_type      = ARG_CONST_MAP_PTR,
587         .arg3_type      = ARG_PTR_TO_MAP_KEY,
588         .arg4_type      = ARG_ANYTHING,
589 };
590
591 BPF_CALL_4(bpf_sk_redirect_map, struct sk_buff *, skb,
592            struct bpf_map *, map, u32, key, u64, flags)
593 {
594         struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
595         struct sock *sk;
596
597         if (unlikely(flags & ~(BPF_F_INGRESS)))
598                 return SK_DROP;
599
600         sk = __sock_map_lookup_elem(map, key);
601         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
602                 return SK_DROP;
603
604         tcb->bpf.flags = flags;
605         tcb->bpf.sk_redir = sk;
606         return SK_PASS;
607 }
608
609 const struct bpf_func_proto bpf_sk_redirect_map_proto = {
610         .func           = bpf_sk_redirect_map,
611         .gpl_only       = false,
612         .ret_type       = RET_INTEGER,
613         .arg1_type      = ARG_PTR_TO_CTX,
614         .arg2_type      = ARG_CONST_MAP_PTR,
615         .arg3_type      = ARG_ANYTHING,
616         .arg4_type      = ARG_ANYTHING,
617 };
618
619 BPF_CALL_4(bpf_msg_redirect_map, struct sk_msg *, msg,
620            struct bpf_map *, map, u32, key, u64, flags)
621 {
622         struct sock *sk;
623
624         if (unlikely(flags & ~(BPF_F_INGRESS)))
625                 return SK_DROP;
626
627         sk = __sock_map_lookup_elem(map, key);
628         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
629                 return SK_DROP;
630
631         msg->flags = flags;
632         msg->sk_redir = sk;
633         return SK_PASS;
634 }
635
636 const struct bpf_func_proto bpf_msg_redirect_map_proto = {
637         .func           = bpf_msg_redirect_map,
638         .gpl_only       = false,
639         .ret_type       = RET_INTEGER,
640         .arg1_type      = ARG_PTR_TO_CTX,
641         .arg2_type      = ARG_CONST_MAP_PTR,
642         .arg3_type      = ARG_ANYTHING,
643         .arg4_type      = ARG_ANYTHING,
644 };
645
646 static int sock_map_btf_id;
647 const struct bpf_map_ops sock_map_ops = {
648         .map_alloc              = sock_map_alloc,
649         .map_free               = sock_map_free,
650         .map_get_next_key       = sock_map_get_next_key,
651         .map_lookup_elem_sys_only = sock_map_lookup_sys,
652         .map_update_elem        = sock_map_update_elem,
653         .map_delete_elem        = sock_map_delete_elem,
654         .map_lookup_elem        = sock_map_lookup,
655         .map_release_uref       = sock_map_release_progs,
656         .map_check_btf          = map_check_no_btf,
657         .map_btf_name           = "bpf_stab",
658         .map_btf_id             = &sock_map_btf_id,
659 };
660
661 struct bpf_shtab_elem {
662         struct rcu_head rcu;
663         u32 hash;
664         struct sock *sk;
665         struct hlist_node node;
666         u8 key[];
667 };
668
669 struct bpf_shtab_bucket {
670         struct hlist_head head;
671         raw_spinlock_t lock;
672 };
673
674 struct bpf_shtab {
675         struct bpf_map map;
676         struct bpf_shtab_bucket *buckets;
677         u32 buckets_num;
678         u32 elem_size;
679         struct sk_psock_progs progs;
680         atomic_t count;
681 };
682
683 static inline u32 sock_hash_bucket_hash(const void *key, u32 len)
684 {
685         return jhash(key, len, 0);
686 }
687
688 static struct bpf_shtab_bucket *sock_hash_select_bucket(struct bpf_shtab *htab,
689                                                         u32 hash)
690 {
691         return &htab->buckets[hash & (htab->buckets_num - 1)];
692 }
693
694 static struct bpf_shtab_elem *
695 sock_hash_lookup_elem_raw(struct hlist_head *head, u32 hash, void *key,
696                           u32 key_size)
697 {
698         struct bpf_shtab_elem *elem;
699
700         hlist_for_each_entry_rcu(elem, head, node) {
701                 if (elem->hash == hash &&
702                     !memcmp(&elem->key, key, key_size))
703                         return elem;
704         }
705
706         return NULL;
707 }
708
709 static struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
710 {
711         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
712         u32 key_size = map->key_size, hash;
713         struct bpf_shtab_bucket *bucket;
714         struct bpf_shtab_elem *elem;
715
716         WARN_ON_ONCE(!rcu_read_lock_held());
717
718         hash = sock_hash_bucket_hash(key, key_size);
719         bucket = sock_hash_select_bucket(htab, hash);
720         elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
721
722         return elem ? elem->sk : NULL;
723 }
724
725 static void sock_hash_free_elem(struct bpf_shtab *htab,
726                                 struct bpf_shtab_elem *elem)
727 {
728         atomic_dec(&htab->count);
729         kfree_rcu(elem, rcu);
730 }
731
732 static void sock_hash_delete_from_link(struct bpf_map *map, struct sock *sk,
733                                        void *link_raw)
734 {
735         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
736         struct bpf_shtab_elem *elem_probe, *elem = link_raw;
737         struct bpf_shtab_bucket *bucket;
738
739         WARN_ON_ONCE(!rcu_read_lock_held());
740         bucket = sock_hash_select_bucket(htab, elem->hash);
741
742         /* elem may be deleted in parallel from the map, but access here
743          * is okay since it's going away only after RCU grace period.
744          * However, we need to check whether it's still present.
745          */
746         raw_spin_lock_bh(&bucket->lock);
747         elem_probe = sock_hash_lookup_elem_raw(&bucket->head, elem->hash,
748                                                elem->key, map->key_size);
749         if (elem_probe && elem_probe == elem) {
750                 hlist_del_rcu(&elem->node);
751                 sock_map_unref(elem->sk, elem);
752                 sock_hash_free_elem(htab, elem);
753         }
754         raw_spin_unlock_bh(&bucket->lock);
755 }
756
757 static int sock_hash_delete_elem(struct bpf_map *map, void *key)
758 {
759         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
760         u32 hash, key_size = map->key_size;
761         struct bpf_shtab_bucket *bucket;
762         struct bpf_shtab_elem *elem;
763         int ret = -ENOENT;
764
765         hash = sock_hash_bucket_hash(key, key_size);
766         bucket = sock_hash_select_bucket(htab, hash);
767
768         raw_spin_lock_bh(&bucket->lock);
769         elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
770         if (elem) {
771                 hlist_del_rcu(&elem->node);
772                 sock_map_unref(elem->sk, elem);
773                 sock_hash_free_elem(htab, elem);
774                 ret = 0;
775         }
776         raw_spin_unlock_bh(&bucket->lock);
777         return ret;
778 }
779
780 static struct bpf_shtab_elem *sock_hash_alloc_elem(struct bpf_shtab *htab,
781                                                    void *key, u32 key_size,
782                                                    u32 hash, struct sock *sk,
783                                                    struct bpf_shtab_elem *old)
784 {
785         struct bpf_shtab_elem *new;
786
787         if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
788                 if (!old) {
789                         atomic_dec(&htab->count);
790                         return ERR_PTR(-E2BIG);
791                 }
792         }
793
794         new = kmalloc_node(htab->elem_size, GFP_ATOMIC | __GFP_NOWARN,
795                            htab->map.numa_node);
796         if (!new) {
797                 atomic_dec(&htab->count);
798                 return ERR_PTR(-ENOMEM);
799         }
800         memcpy(new->key, key, key_size);
801         new->sk = sk;
802         new->hash = hash;
803         return new;
804 }
805
806 static int sock_hash_update_common(struct bpf_map *map, void *key,
807                                    struct sock *sk, u64 flags)
808 {
809         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
810         u32 key_size = map->key_size, hash;
811         struct bpf_shtab_elem *elem, *elem_new;
812         struct bpf_shtab_bucket *bucket;
813         struct sk_psock_link *link;
814         struct sk_psock *psock;
815         int ret;
816
817         WARN_ON_ONCE(!rcu_read_lock_held());
818         if (unlikely(flags > BPF_EXIST))
819                 return -EINVAL;
820         if (inet_csk_has_ulp(sk))
821                 return -EINVAL;
822
823         link = sk_psock_init_link();
824         if (!link)
825                 return -ENOMEM;
826
827         /* Only sockets we can redirect into/from in BPF need to hold
828          * refs to parser/verdict progs and have their sk_data_ready
829          * and sk_write_space callbacks overridden.
830          */
831         if (sock_map_redirect_allowed(sk))
832                 ret = sock_map_link(map, &htab->progs, sk);
833         else
834                 ret = sock_map_link_no_progs(map, sk);
835         if (ret < 0)
836                 goto out_free;
837
838         psock = sk_psock(sk);
839         WARN_ON_ONCE(!psock);
840
841         hash = sock_hash_bucket_hash(key, key_size);
842         bucket = sock_hash_select_bucket(htab, hash);
843
844         raw_spin_lock_bh(&bucket->lock);
845         elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
846         if (elem && flags == BPF_NOEXIST) {
847                 ret = -EEXIST;
848                 goto out_unlock;
849         } else if (!elem && flags == BPF_EXIST) {
850                 ret = -ENOENT;
851                 goto out_unlock;
852         }
853
854         elem_new = sock_hash_alloc_elem(htab, key, key_size, hash, sk, elem);
855         if (IS_ERR(elem_new)) {
856                 ret = PTR_ERR(elem_new);
857                 goto out_unlock;
858         }
859
860         sock_map_add_link(psock, link, map, elem_new);
861         /* Add new element to the head of the list, so that
862          * concurrent search will find it before old elem.
863          */
864         hlist_add_head_rcu(&elem_new->node, &bucket->head);
865         if (elem) {
866                 hlist_del_rcu(&elem->node);
867                 sock_map_unref(elem->sk, elem);
868                 sock_hash_free_elem(htab, elem);
869         }
870         raw_spin_unlock_bh(&bucket->lock);
871         return 0;
872 out_unlock:
873         raw_spin_unlock_bh(&bucket->lock);
874         sk_psock_put(sk, psock);
875 out_free:
876         sk_psock_free_link(link);
877         return ret;
878 }
879
880 static int sock_hash_update_elem(struct bpf_map *map, void *key,
881                                  void *value, u64 flags)
882 {
883         struct socket *sock;
884         struct sock *sk;
885         int ret;
886         u64 ufd;
887
888         if (map->value_size == sizeof(u64))
889                 ufd = *(u64 *)value;
890         else
891                 ufd = *(u32 *)value;
892         if (ufd > S32_MAX)
893                 return -EINVAL;
894
895         sock = sockfd_lookup(ufd, &ret);
896         if (!sock)
897                 return ret;
898         sk = sock->sk;
899         if (!sk) {
900                 ret = -EINVAL;
901                 goto out;
902         }
903         if (!sock_map_sk_is_suitable(sk)) {
904                 ret = -EOPNOTSUPP;
905                 goto out;
906         }
907
908         sock_map_sk_acquire(sk);
909         if (!sock_map_sk_state_allowed(sk))
910                 ret = -EOPNOTSUPP;
911         else
912                 ret = sock_hash_update_common(map, key, sk, flags);
913         sock_map_sk_release(sk);
914 out:
915         fput(sock->file);
916         return ret;
917 }
918
919 static int sock_hash_get_next_key(struct bpf_map *map, void *key,
920                                   void *key_next)
921 {
922         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
923         struct bpf_shtab_elem *elem, *elem_next;
924         u32 hash, key_size = map->key_size;
925         struct hlist_head *head;
926         int i = 0;
927
928         if (!key)
929                 goto find_first_elem;
930         hash = sock_hash_bucket_hash(key, key_size);
931         head = &sock_hash_select_bucket(htab, hash)->head;
932         elem = sock_hash_lookup_elem_raw(head, hash, key, key_size);
933         if (!elem)
934                 goto find_first_elem;
935
936         elem_next = hlist_entry_safe(rcu_dereference_raw(hlist_next_rcu(&elem->node)),
937                                      struct bpf_shtab_elem, node);
938         if (elem_next) {
939                 memcpy(key_next, elem_next->key, key_size);
940                 return 0;
941         }
942
943         i = hash & (htab->buckets_num - 1);
944         i++;
945 find_first_elem:
946         for (; i < htab->buckets_num; i++) {
947                 head = &sock_hash_select_bucket(htab, i)->head;
948                 elem_next = hlist_entry_safe(rcu_dereference_raw(hlist_first_rcu(head)),
949                                              struct bpf_shtab_elem, node);
950                 if (elem_next) {
951                         memcpy(key_next, elem_next->key, key_size);
952                         return 0;
953                 }
954         }
955
956         return -ENOENT;
957 }
958
959 static struct bpf_map *sock_hash_alloc(union bpf_attr *attr)
960 {
961         struct bpf_shtab *htab;
962         int i, err;
963         u64 cost;
964
965         if (!capable(CAP_NET_ADMIN))
966                 return ERR_PTR(-EPERM);
967         if (attr->max_entries == 0 ||
968             attr->key_size    == 0 ||
969             (attr->value_size != sizeof(u32) &&
970              attr->value_size != sizeof(u64)) ||
971             attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
972                 return ERR_PTR(-EINVAL);
973         if (attr->key_size > MAX_BPF_STACK)
974                 return ERR_PTR(-E2BIG);
975
976         htab = kzalloc(sizeof(*htab), GFP_USER);
977         if (!htab)
978                 return ERR_PTR(-ENOMEM);
979
980         bpf_map_init_from_attr(&htab->map, attr);
981
982         htab->buckets_num = roundup_pow_of_two(htab->map.max_entries);
983         htab->elem_size = sizeof(struct bpf_shtab_elem) +
984                           round_up(htab->map.key_size, 8);
985         if (htab->buckets_num == 0 ||
986             htab->buckets_num > U32_MAX / sizeof(struct bpf_shtab_bucket)) {
987                 err = -EINVAL;
988                 goto free_htab;
989         }
990
991         cost = (u64) htab->buckets_num * sizeof(struct bpf_shtab_bucket) +
992                (u64) htab->elem_size * htab->map.max_entries;
993         if (cost >= U32_MAX - PAGE_SIZE) {
994                 err = -EINVAL;
995                 goto free_htab;
996         }
997         err = bpf_map_charge_init(&htab->map.memory, cost);
998         if (err)
999                 goto free_htab;
1000
1001         htab->buckets = bpf_map_area_alloc(htab->buckets_num *
1002                                            sizeof(struct bpf_shtab_bucket),
1003                                            htab->map.numa_node);
1004         if (!htab->buckets) {
1005                 bpf_map_charge_finish(&htab->map.memory);
1006                 err = -ENOMEM;
1007                 goto free_htab;
1008         }
1009
1010         for (i = 0; i < htab->buckets_num; i++) {
1011                 INIT_HLIST_HEAD(&htab->buckets[i].head);
1012                 raw_spin_lock_init(&htab->buckets[i].lock);
1013         }
1014
1015         return &htab->map;
1016 free_htab:
1017         kfree(htab);
1018         return ERR_PTR(err);
1019 }
1020
1021 static void sock_hash_free(struct bpf_map *map)
1022 {
1023         struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
1024         struct bpf_shtab_bucket *bucket;
1025         struct hlist_head unlink_list;
1026         struct bpf_shtab_elem *elem;
1027         struct hlist_node *node;
1028         int i;
1029
1030         /* After the sync no updates or deletes will be in-flight so it
1031          * is safe to walk map and remove entries without risking a race
1032          * in EEXIST update case.
1033          */
1034         synchronize_rcu();
1035         for (i = 0; i < htab->buckets_num; i++) {
1036                 bucket = sock_hash_select_bucket(htab, i);
1037
1038                 /* We are racing with sock_hash_delete_from_link to
1039                  * enter the spin-lock critical section. Every socket on
1040                  * the list is still linked to sockhash. Since link
1041                  * exists, psock exists and holds a ref to socket. That
1042                  * lets us to grab a socket ref too.
1043                  */
1044                 raw_spin_lock_bh(&bucket->lock);
1045                 hlist_for_each_entry(elem, &bucket->head, node)
1046                         sock_hold(elem->sk);
1047                 hlist_move_list(&bucket->head, &unlink_list);
1048                 raw_spin_unlock_bh(&bucket->lock);
1049
1050                 /* Process removed entries out of atomic context to
1051                  * block for socket lock before deleting the psock's
1052                  * link to sockhash.
1053                  */
1054                 hlist_for_each_entry_safe(elem, node, &unlink_list, node) {
1055                         hlist_del(&elem->node);
1056                         lock_sock(elem->sk);
1057                         rcu_read_lock();
1058                         sock_map_unref(elem->sk, elem);
1059                         rcu_read_unlock();
1060                         release_sock(elem->sk);
1061                         sock_put(elem->sk);
1062                         sock_hash_free_elem(htab, elem);
1063                 }
1064         }
1065
1066         /* wait for psock readers accessing its map link */
1067         synchronize_rcu();
1068
1069         bpf_map_area_free(htab->buckets);
1070         kfree(htab);
1071 }
1072
1073 static void *sock_hash_lookup_sys(struct bpf_map *map, void *key)
1074 {
1075         struct sock *sk;
1076
1077         if (map->value_size != sizeof(u64))
1078                 return ERR_PTR(-ENOSPC);
1079
1080         sk = __sock_hash_lookup_elem(map, key);
1081         if (!sk)
1082                 return ERR_PTR(-ENOENT);
1083
1084         sock_gen_cookie(sk);
1085         return &sk->sk_cookie;
1086 }
1087
1088 static void *sock_hash_lookup(struct bpf_map *map, void *key)
1089 {
1090         struct sock *sk;
1091
1092         sk = __sock_hash_lookup_elem(map, key);
1093         if (!sk || !sk_fullsock(sk))
1094                 return NULL;
1095         if (sk_is_refcounted(sk) && !refcount_inc_not_zero(&sk->sk_refcnt))
1096                 return NULL;
1097         return sk;
1098 }
1099
1100 static void sock_hash_release_progs(struct bpf_map *map)
1101 {
1102         psock_progs_drop(&container_of(map, struct bpf_shtab, map)->progs);
1103 }
1104
1105 BPF_CALL_4(bpf_sock_hash_update, struct bpf_sock_ops_kern *, sops,
1106            struct bpf_map *, map, void *, key, u64, flags)
1107 {
1108         WARN_ON_ONCE(!rcu_read_lock_held());
1109
1110         if (likely(sock_map_sk_is_suitable(sops->sk) &&
1111                    sock_map_op_okay(sops)))
1112                 return sock_hash_update_common(map, key, sops->sk, flags);
1113         return -EOPNOTSUPP;
1114 }
1115
1116 const struct bpf_func_proto bpf_sock_hash_update_proto = {
1117         .func           = bpf_sock_hash_update,
1118         .gpl_only       = false,
1119         .pkt_access     = true,
1120         .ret_type       = RET_INTEGER,
1121         .arg1_type      = ARG_PTR_TO_CTX,
1122         .arg2_type      = ARG_CONST_MAP_PTR,
1123         .arg3_type      = ARG_PTR_TO_MAP_KEY,
1124         .arg4_type      = ARG_ANYTHING,
1125 };
1126
1127 BPF_CALL_4(bpf_sk_redirect_hash, struct sk_buff *, skb,
1128            struct bpf_map *, map, void *, key, u64, flags)
1129 {
1130         struct tcp_skb_cb *tcb = TCP_SKB_CB(skb);
1131         struct sock *sk;
1132
1133         if (unlikely(flags & ~(BPF_F_INGRESS)))
1134                 return SK_DROP;
1135
1136         sk = __sock_hash_lookup_elem(map, key);
1137         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
1138                 return SK_DROP;
1139
1140         tcb->bpf.flags = flags;
1141         tcb->bpf.sk_redir = sk;
1142         return SK_PASS;
1143 }
1144
1145 const struct bpf_func_proto bpf_sk_redirect_hash_proto = {
1146         .func           = bpf_sk_redirect_hash,
1147         .gpl_only       = false,
1148         .ret_type       = RET_INTEGER,
1149         .arg1_type      = ARG_PTR_TO_CTX,
1150         .arg2_type      = ARG_CONST_MAP_PTR,
1151         .arg3_type      = ARG_PTR_TO_MAP_KEY,
1152         .arg4_type      = ARG_ANYTHING,
1153 };
1154
1155 BPF_CALL_4(bpf_msg_redirect_hash, struct sk_msg *, msg,
1156            struct bpf_map *, map, void *, key, u64, flags)
1157 {
1158         struct sock *sk;
1159
1160         if (unlikely(flags & ~(BPF_F_INGRESS)))
1161                 return SK_DROP;
1162
1163         sk = __sock_hash_lookup_elem(map, key);
1164         if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
1165                 return SK_DROP;
1166
1167         msg->flags = flags;
1168         msg->sk_redir = sk;
1169         return SK_PASS;
1170 }
1171
1172 const struct bpf_func_proto bpf_msg_redirect_hash_proto = {
1173         .func           = bpf_msg_redirect_hash,
1174         .gpl_only       = false,
1175         .ret_type       = RET_INTEGER,
1176         .arg1_type      = ARG_PTR_TO_CTX,
1177         .arg2_type      = ARG_CONST_MAP_PTR,
1178         .arg3_type      = ARG_PTR_TO_MAP_KEY,
1179         .arg4_type      = ARG_ANYTHING,
1180 };
1181
1182 static int sock_hash_map_btf_id;
1183 const struct bpf_map_ops sock_hash_ops = {
1184         .map_alloc              = sock_hash_alloc,
1185         .map_free               = sock_hash_free,
1186         .map_get_next_key       = sock_hash_get_next_key,
1187         .map_update_elem        = sock_hash_update_elem,
1188         .map_delete_elem        = sock_hash_delete_elem,
1189         .map_lookup_elem        = sock_hash_lookup,
1190         .map_lookup_elem_sys_only = sock_hash_lookup_sys,
1191         .map_release_uref       = sock_hash_release_progs,
1192         .map_check_btf          = map_check_no_btf,
1193         .map_btf_name           = "bpf_shtab",
1194         .map_btf_id             = &sock_hash_map_btf_id,
1195 };
1196
1197 static struct sk_psock_progs *sock_map_progs(struct bpf_map *map)
1198 {
1199         switch (map->map_type) {
1200         case BPF_MAP_TYPE_SOCKMAP:
1201                 return &container_of(map, struct bpf_stab, map)->progs;
1202         case BPF_MAP_TYPE_SOCKHASH:
1203                 return &container_of(map, struct bpf_shtab, map)->progs;
1204         default:
1205                 break;
1206         }
1207
1208         return NULL;
1209 }
1210
1211 int sock_map_prog_update(struct bpf_map *map, struct bpf_prog *prog,
1212                          u32 which)
1213 {
1214         struct sk_psock_progs *progs = sock_map_progs(map);
1215
1216         if (!progs)
1217                 return -EOPNOTSUPP;
1218
1219         switch (which) {
1220         case BPF_SK_MSG_VERDICT:
1221                 psock_set_prog(&progs->msg_parser, prog);
1222                 break;
1223         case BPF_SK_SKB_STREAM_PARSER:
1224                 psock_set_prog(&progs->skb_parser, prog);
1225                 break;
1226         case BPF_SK_SKB_STREAM_VERDICT:
1227                 psock_set_prog(&progs->skb_verdict, prog);
1228                 break;
1229         default:
1230                 return -EOPNOTSUPP;
1231         }
1232
1233         return 0;
1234 }
1235
1236 static void sock_map_unlink(struct sock *sk, struct sk_psock_link *link)
1237 {
1238         switch (link->map->map_type) {
1239         case BPF_MAP_TYPE_SOCKMAP:
1240                 return sock_map_delete_from_link(link->map, sk,
1241                                                  link->link_raw);
1242         case BPF_MAP_TYPE_SOCKHASH:
1243                 return sock_hash_delete_from_link(link->map, sk,
1244                                                   link->link_raw);
1245         default:
1246                 break;
1247         }
1248 }
1249
1250 static void sock_map_remove_links(struct sock *sk, struct sk_psock *psock)
1251 {
1252         struct sk_psock_link *link;
1253
1254         while ((link = sk_psock_link_pop(psock))) {
1255                 sock_map_unlink(sk, link);
1256                 sk_psock_free_link(link);
1257         }
1258 }
1259
1260 void sock_map_unhash(struct sock *sk)
1261 {
1262         void (*saved_unhash)(struct sock *sk);
1263         struct sk_psock *psock;
1264
1265         rcu_read_lock();
1266         psock = sk_psock(sk);
1267         if (unlikely(!psock)) {
1268                 rcu_read_unlock();
1269                 if (sk->sk_prot->unhash)
1270                         sk->sk_prot->unhash(sk);
1271                 return;
1272         }
1273
1274         saved_unhash = psock->saved_unhash;
1275         sock_map_remove_links(sk, psock);
1276         rcu_read_unlock();
1277         saved_unhash(sk);
1278 }
1279
1280 void sock_map_close(struct sock *sk, long timeout)
1281 {
1282         void (*saved_close)(struct sock *sk, long timeout);
1283         struct sk_psock *psock;
1284
1285         lock_sock(sk);
1286         rcu_read_lock();
1287         psock = sk_psock(sk);
1288         if (unlikely(!psock)) {
1289                 rcu_read_unlock();
1290                 release_sock(sk);
1291                 return sk->sk_prot->close(sk, timeout);
1292         }
1293
1294         saved_close = psock->saved_close;
1295         sock_map_remove_links(sk, psock);
1296         rcu_read_unlock();
1297         release_sock(sk);
1298         saved_close(sk, timeout);
1299 }