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