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