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