xref: /linux/net/core/sock_map.c (revision 5635f189425e328097714c38341944fc40731f3d)
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 /* This mutex is used to
28  *  - protect race between prog/link attach/detach and link prog update, and
29  *  - protect race between releasing and accessing map in bpf_link.
30  * A single global mutex lock is used since it is expected contention is low.
31  */
32 static DEFINE_MUTEX(sockmap_mutex);
33 
34 static int sock_map_prog_update(struct bpf_map *map, struct bpf_prog *prog,
35 				struct bpf_prog *old, struct bpf_link *link,
36 				u32 which);
37 static struct sk_psock_progs *sock_map_progs(struct bpf_map *map);
38 
sock_map_alloc(union bpf_attr * attr)39 static struct bpf_map *sock_map_alloc(union bpf_attr *attr)
40 {
41 	struct bpf_stab *stab;
42 
43 	if (attr->max_entries == 0 ||
44 	    attr->key_size    != 4 ||
45 	    (attr->value_size != sizeof(u32) &&
46 	     attr->value_size != sizeof(u64)) ||
47 	    attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
48 		return ERR_PTR(-EINVAL);
49 
50 	stab = bpf_map_area_alloc(sizeof(*stab), NUMA_NO_NODE);
51 	if (!stab)
52 		return ERR_PTR(-ENOMEM);
53 
54 	bpf_map_init_from_attr(&stab->map, attr);
55 	spin_lock_init(&stab->lock);
56 
57 	stab->sks = bpf_map_area_alloc((u64) stab->map.max_entries *
58 				       sizeof(struct sock *),
59 				       stab->map.numa_node);
60 	if (!stab->sks) {
61 		bpf_map_area_free(stab);
62 		return ERR_PTR(-ENOMEM);
63 	}
64 
65 	return &stab->map;
66 }
67 
sock_map_get_from_fd(const union bpf_attr * attr,struct bpf_prog * prog)68 int sock_map_get_from_fd(const union bpf_attr *attr, struct bpf_prog *prog)
69 {
70 	struct bpf_map *map;
71 	int ret;
72 
73 	if (attr->attach_flags || attr->replace_bpf_fd)
74 		return -EINVAL;
75 
76 	CLASS(fd, f)(attr->target_fd);
77 	map = __bpf_map_get(f);
78 	if (IS_ERR(map))
79 		return PTR_ERR(map);
80 	mutex_lock(&sockmap_mutex);
81 	ret = sock_map_prog_update(map, prog, NULL, NULL, attr->attach_type);
82 	mutex_unlock(&sockmap_mutex);
83 	return ret;
84 }
85 
sock_map_prog_detach(const union bpf_attr * attr,enum bpf_prog_type ptype)86 int sock_map_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
87 {
88 	struct bpf_prog *prog;
89 	struct bpf_map *map;
90 	int ret;
91 
92 	if (attr->attach_flags || attr->replace_bpf_fd)
93 		return -EINVAL;
94 
95 	CLASS(fd, f)(attr->target_fd);
96 	map = __bpf_map_get(f);
97 	if (IS_ERR(map))
98 		return PTR_ERR(map);
99 
100 	prog = bpf_prog_get(attr->attach_bpf_fd);
101 	if (IS_ERR(prog))
102 		return PTR_ERR(prog);
103 
104 	if (prog->type != ptype) {
105 		ret = -EINVAL;
106 		goto put_prog;
107 	}
108 
109 	mutex_lock(&sockmap_mutex);
110 	ret = sock_map_prog_update(map, NULL, prog, NULL, attr->attach_type);
111 	mutex_unlock(&sockmap_mutex);
112 put_prog:
113 	bpf_prog_put(prog);
114 	return ret;
115 }
116 
sock_map_sk_acquire(struct sock * sk)117 static void sock_map_sk_acquire(struct sock *sk)
118 	__acquires(&sk->sk_lock.slock)
119 {
120 	lock_sock(sk);
121 	rcu_read_lock();
122 }
123 
sock_map_sk_release(struct sock * sk)124 static void sock_map_sk_release(struct sock *sk)
125 	__releases(&sk->sk_lock.slock)
126 {
127 	rcu_read_unlock();
128 	release_sock(sk);
129 }
130 
sock_map_add_link(struct sk_psock * psock,struct sk_psock_link * link,struct bpf_map * map,void * link_raw)131 static void sock_map_add_link(struct sk_psock *psock,
132 			      struct sk_psock_link *link,
133 			      struct bpf_map *map, void *link_raw)
134 {
135 	link->link_raw = link_raw;
136 	link->map = map;
137 	spin_lock_bh(&psock->link_lock);
138 	list_add_tail(&link->list, &psock->link);
139 	spin_unlock_bh(&psock->link_lock);
140 }
141 
sock_map_del_link(struct sock * sk,struct sk_psock * psock,void * link_raw)142 static void sock_map_del_link(struct sock *sk,
143 			      struct sk_psock *psock, void *link_raw)
144 {
145 	bool strp_stop = false, verdict_stop = false;
146 	struct sk_psock_link *link, *tmp;
147 
148 	spin_lock_bh(&psock->link_lock);
149 	list_for_each_entry_safe(link, tmp, &psock->link, list) {
150 		if (link->link_raw == link_raw) {
151 			struct bpf_map *map = link->map;
152 			struct sk_psock_progs *progs = sock_map_progs(map);
153 
154 			if (psock->saved_data_ready && progs->stream_parser)
155 				strp_stop = true;
156 			if (psock->saved_data_ready && progs->stream_verdict)
157 				verdict_stop = true;
158 			if (psock->saved_data_ready && progs->skb_verdict)
159 				verdict_stop = true;
160 			list_del(&link->list);
161 			sk_psock_free_link(link);
162 		}
163 	}
164 	spin_unlock_bh(&psock->link_lock);
165 	if (strp_stop || verdict_stop) {
166 		write_lock_bh(&sk->sk_callback_lock);
167 		if (strp_stop)
168 			sk_psock_stop_strp(sk, psock);
169 		if (verdict_stop)
170 			sk_psock_stop_verdict(sk, psock);
171 
172 		if (psock->psock_update_sk_prot)
173 			psock->psock_update_sk_prot(sk, psock, false);
174 		write_unlock_bh(&sk->sk_callback_lock);
175 	}
176 }
177 
sock_map_unref(struct sock * sk,void * link_raw)178 static void sock_map_unref(struct sock *sk, void *link_raw)
179 {
180 	struct sk_psock *psock = sk_psock(sk);
181 
182 	if (likely(psock)) {
183 		sock_map_del_link(sk, psock, link_raw);
184 		sk_psock_put(sk, psock);
185 	}
186 }
187 
sock_map_init_proto(struct sock * sk,struct sk_psock * psock)188 static int sock_map_init_proto(struct sock *sk, struct sk_psock *psock)
189 {
190 	if (!sk->sk_prot->psock_update_sk_prot)
191 		return -EINVAL;
192 	psock->psock_update_sk_prot = sk->sk_prot->psock_update_sk_prot;
193 	return sk->sk_prot->psock_update_sk_prot(sk, psock, false);
194 }
195 
sock_map_psock_get_checked(struct sock * sk)196 static struct sk_psock *sock_map_psock_get_checked(struct sock *sk)
197 {
198 	struct sk_psock *psock;
199 
200 	rcu_read_lock();
201 	psock = sk_psock(sk);
202 	if (psock) {
203 		if (sk->sk_prot->close != sock_map_close) {
204 			psock = ERR_PTR(-EBUSY);
205 			goto out;
206 		}
207 
208 		if (!refcount_inc_not_zero(&psock->refcnt))
209 			psock = ERR_PTR(-EBUSY);
210 	}
211 out:
212 	rcu_read_unlock();
213 	return psock;
214 }
215 
sock_map_link(struct bpf_map * map,struct sock * sk)216 static int sock_map_link(struct bpf_map *map, struct sock *sk)
217 {
218 	struct sk_psock_progs *progs = sock_map_progs(map);
219 	struct bpf_prog *stream_verdict = NULL;
220 	struct bpf_prog *stream_parser = NULL;
221 	struct bpf_prog *skb_verdict = NULL;
222 	struct bpf_prog *msg_parser = NULL;
223 	struct sk_psock *psock;
224 	int ret;
225 
226 	stream_verdict = READ_ONCE(progs->stream_verdict);
227 	if (stream_verdict) {
228 		stream_verdict = bpf_prog_inc_not_zero(stream_verdict);
229 		if (IS_ERR(stream_verdict))
230 			return PTR_ERR(stream_verdict);
231 	}
232 
233 	stream_parser = READ_ONCE(progs->stream_parser);
234 	if (stream_parser) {
235 		stream_parser = bpf_prog_inc_not_zero(stream_parser);
236 		if (IS_ERR(stream_parser)) {
237 			ret = PTR_ERR(stream_parser);
238 			goto out_put_stream_verdict;
239 		}
240 	}
241 
242 	msg_parser = READ_ONCE(progs->msg_parser);
243 	if (msg_parser) {
244 		msg_parser = bpf_prog_inc_not_zero(msg_parser);
245 		if (IS_ERR(msg_parser)) {
246 			ret = PTR_ERR(msg_parser);
247 			goto out_put_stream_parser;
248 		}
249 	}
250 
251 	skb_verdict = READ_ONCE(progs->skb_verdict);
252 	if (skb_verdict) {
253 		skb_verdict = bpf_prog_inc_not_zero(skb_verdict);
254 		if (IS_ERR(skb_verdict)) {
255 			ret = PTR_ERR(skb_verdict);
256 			goto out_put_msg_parser;
257 		}
258 	}
259 
260 	psock = sock_map_psock_get_checked(sk);
261 	if (IS_ERR(psock)) {
262 		ret = PTR_ERR(psock);
263 		goto out_progs;
264 	}
265 
266 	if (psock) {
267 		if ((msg_parser && READ_ONCE(psock->progs.msg_parser)) ||
268 		    (stream_parser  && READ_ONCE(psock->progs.stream_parser)) ||
269 		    (skb_verdict && READ_ONCE(psock->progs.skb_verdict)) ||
270 		    (skb_verdict && READ_ONCE(psock->progs.stream_verdict)) ||
271 		    (stream_verdict && READ_ONCE(psock->progs.skb_verdict)) ||
272 		    (stream_verdict && READ_ONCE(psock->progs.stream_verdict))) {
273 			sk_psock_put(sk, psock);
274 			ret = -EBUSY;
275 			goto out_progs;
276 		}
277 	} else {
278 		psock = sk_psock_init(sk, map->numa_node);
279 		if (IS_ERR(psock)) {
280 			ret = PTR_ERR(psock);
281 			goto out_progs;
282 		}
283 	}
284 
285 	if (msg_parser)
286 		psock_set_prog(&psock->progs.msg_parser, msg_parser);
287 	if (stream_parser)
288 		psock_set_prog(&psock->progs.stream_parser, stream_parser);
289 	if (stream_verdict)
290 		psock_set_prog(&psock->progs.stream_verdict, stream_verdict);
291 	if (skb_verdict)
292 		psock_set_prog(&psock->progs.skb_verdict, skb_verdict);
293 
294 	/* msg_* and stream_* programs references tracked in psock after this
295 	 * point. Reference dec and cleanup will occur through psock destructor
296 	 */
297 	ret = sock_map_init_proto(sk, psock);
298 	if (ret < 0) {
299 		sk_psock_put(sk, psock);
300 		goto out;
301 	}
302 
303 	write_lock_bh(&sk->sk_callback_lock);
304 	if (stream_parser && stream_verdict && !psock->saved_data_ready) {
305 		ret = sk_psock_init_strp(sk, psock);
306 		if (ret) {
307 			write_unlock_bh(&sk->sk_callback_lock);
308 			sk_psock_put(sk, psock);
309 			goto out;
310 		}
311 		sk_psock_start_strp(sk, psock);
312 	} else if (!stream_parser && stream_verdict && !psock->saved_data_ready) {
313 		sk_psock_start_verdict(sk,psock);
314 	} else if (!stream_verdict && skb_verdict && !psock->saved_data_ready) {
315 		sk_psock_start_verdict(sk, psock);
316 	}
317 	write_unlock_bh(&sk->sk_callback_lock);
318 	return 0;
319 out_progs:
320 	if (skb_verdict)
321 		bpf_prog_put(skb_verdict);
322 out_put_msg_parser:
323 	if (msg_parser)
324 		bpf_prog_put(msg_parser);
325 out_put_stream_parser:
326 	if (stream_parser)
327 		bpf_prog_put(stream_parser);
328 out_put_stream_verdict:
329 	if (stream_verdict)
330 		bpf_prog_put(stream_verdict);
331 out:
332 	return ret;
333 }
334 
sock_map_free(struct bpf_map * map)335 static void sock_map_free(struct bpf_map *map)
336 {
337 	struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
338 	int i;
339 
340 	/* After the sync no updates or deletes will be in-flight so it
341 	 * is safe to walk map and remove entries without risking a race
342 	 * in EEXIST update case.
343 	 */
344 	synchronize_rcu();
345 	for (i = 0; i < stab->map.max_entries; i++) {
346 		struct sock **psk = &stab->sks[i];
347 		struct sock *sk;
348 
349 		sk = xchg(psk, NULL);
350 		if (sk) {
351 			sock_hold(sk);
352 			lock_sock(sk);
353 			rcu_read_lock();
354 			sock_map_unref(sk, psk);
355 			rcu_read_unlock();
356 			release_sock(sk);
357 			sock_put(sk);
358 		}
359 	}
360 
361 	/* wait for psock readers accessing its map link */
362 	synchronize_rcu();
363 
364 	bpf_map_area_free(stab->sks);
365 	bpf_map_area_free(stab);
366 }
367 
sock_map_release_progs(struct bpf_map * map)368 static void sock_map_release_progs(struct bpf_map *map)
369 {
370 	psock_progs_drop(&container_of(map, struct bpf_stab, map)->progs);
371 }
372 
__sock_map_lookup_elem(struct bpf_map * map,u32 key)373 static struct sock *__sock_map_lookup_elem(struct bpf_map *map, u32 key)
374 {
375 	struct bpf_stab *stab = container_of(map, struct bpf_stab, map);
376 
377 	WARN_ON_ONCE(!rcu_read_lock_held());
378 
379 	if (unlikely(key >= map->max_entries))
380 		return NULL;
381 	return READ_ONCE(stab->sks[key]);
382 }
383 
sock_map_lookup(struct bpf_map * map,void * key)384 static void *sock_map_lookup(struct bpf_map *map, void *key)
385 {
386 	struct sock *sk;
387 
388 	sk = __sock_map_lookup_elem(map, *(u32 *)key);
389 	if (!sk)
390 		return NULL;
391 	if (sk_is_refcounted(sk) && !refcount_inc_not_zero(&sk->sk_refcnt))
392 		return NULL;
393 	return sk;
394 }
395 
sock_map_lookup_sys(struct bpf_map * map,void * key)396 static void *sock_map_lookup_sys(struct bpf_map *map, void *key)
397 {
398 	struct sock *sk;
399 
400 	if (map->value_size != sizeof(u64))
401 		return ERR_PTR(-ENOSPC);
402 
403 	sk = __sock_map_lookup_elem(map, *(u32 *)key);
404 	if (!sk)
405 		return ERR_PTR(-ENOENT);
406 
407 	__sock_gen_cookie(sk);
408 	return &sk->sk_cookie;
409 }
410 
__sock_map_delete(struct bpf_stab * stab,struct sock * sk_test,struct sock ** psk)411 static int __sock_map_delete(struct bpf_stab *stab, struct sock *sk_test,
412 			     struct sock **psk)
413 {
414 	struct sock *sk;
415 	int err = 0;
416 
417 	spin_lock_bh(&stab->lock);
418 	sk = *psk;
419 	if (!sk_test || sk_test == sk)
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 	return true;
545 }
546 
547 static int sock_hash_update_common(struct bpf_map *map, void *key,
548 				   struct sock *sk, u64 flags);
549 
sock_map_update_elem_sys(struct bpf_map * map,void * key,void * value,u64 flags)550 int sock_map_update_elem_sys(struct bpf_map *map, void *key, void *value,
551 			     u64 flags)
552 {
553 	struct socket *sock;
554 	struct sock *sk;
555 	int ret;
556 	u64 ufd;
557 
558 	if (map->value_size == sizeof(u64))
559 		ufd = *(u64 *)value;
560 	else
561 		ufd = *(u32 *)value;
562 	if (ufd > S32_MAX)
563 		return -EINVAL;
564 
565 	sock = sockfd_lookup(ufd, &ret);
566 	if (!sock)
567 		return ret;
568 	sk = sock->sk;
569 	if (!sk) {
570 		ret = -EINVAL;
571 		goto out;
572 	}
573 	if (!sock_map_sk_is_suitable(sk)) {
574 		ret = -EOPNOTSUPP;
575 		goto out;
576 	}
577 
578 	sock_map_sk_acquire(sk);
579 	if (!sock_map_sk_state_allowed(sk))
580 		ret = -EOPNOTSUPP;
581 	else if (map->map_type == BPF_MAP_TYPE_SOCKMAP)
582 		ret = sock_map_update_common(map, *(u32 *)key, sk, flags);
583 	else
584 		ret = sock_hash_update_common(map, key, sk, flags);
585 	sock_map_sk_release(sk);
586 out:
587 	sockfd_put(sock);
588 	return ret;
589 }
590 
sock_map_update_elem(struct bpf_map * map,void * key,void * value,u64 flags)591 static long sock_map_update_elem(struct bpf_map *map, void *key,
592 				 void *value, u64 flags)
593 {
594 	struct sock *sk = (struct sock *)value;
595 	int ret;
596 
597 	if (unlikely(!sk || !sk_fullsock(sk)))
598 		return -EINVAL;
599 
600 	if (!sock_map_sk_is_suitable(sk))
601 		return -EOPNOTSUPP;
602 
603 	local_bh_disable();
604 	bh_lock_sock(sk);
605 	if (!sock_map_sk_state_allowed(sk))
606 		ret = -EOPNOTSUPP;
607 	else if (map->map_type == BPF_MAP_TYPE_SOCKMAP)
608 		ret = sock_map_update_common(map, *(u32 *)key, sk, flags);
609 	else
610 		ret = sock_hash_update_common(map, key, sk, flags);
611 	bh_unlock_sock(sk);
612 	local_bh_enable();
613 	return ret;
614 }
615 
BPF_CALL_4(bpf_sock_map_update,struct bpf_sock_ops_kern *,sops,struct bpf_map *,map,void *,key,u64,flags)616 BPF_CALL_4(bpf_sock_map_update, struct bpf_sock_ops_kern *, sops,
617 	   struct bpf_map *, map, void *, key, u64, flags)
618 {
619 	WARN_ON_ONCE(!rcu_read_lock_held());
620 
621 	if (likely(sock_map_sk_is_suitable(sops->sk) &&
622 		   sock_map_op_okay(sops)))
623 		return sock_map_update_common(map, *(u32 *)key, sops->sk,
624 					      flags);
625 	return -EOPNOTSUPP;
626 }
627 
628 const struct bpf_func_proto bpf_sock_map_update_proto = {
629 	.func		= bpf_sock_map_update,
630 	.gpl_only	= false,
631 	.pkt_access	= true,
632 	.ret_type	= RET_INTEGER,
633 	.arg1_type	= ARG_PTR_TO_CTX,
634 	.arg2_type	= ARG_CONST_MAP_PTR,
635 	.arg3_type	= ARG_PTR_TO_MAP_KEY,
636 	.arg4_type	= ARG_ANYTHING,
637 };
638 
BPF_CALL_4(bpf_sk_redirect_map,struct sk_buff *,skb,struct bpf_map *,map,u32,key,u64,flags)639 BPF_CALL_4(bpf_sk_redirect_map, struct sk_buff *, skb,
640 	   struct bpf_map *, map, u32, key, u64, flags)
641 {
642 	struct sock *sk;
643 
644 	if (unlikely(flags & ~(BPF_F_INGRESS)))
645 		return SK_DROP;
646 
647 	sk = __sock_map_lookup_elem(map, key);
648 	if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
649 		return SK_DROP;
650 	if ((flags & BPF_F_INGRESS) && sk_is_vsock(sk))
651 		return SK_DROP;
652 
653 	skb_bpf_set_redir(skb, sk, flags & BPF_F_INGRESS);
654 	return SK_PASS;
655 }
656 
657 const struct bpf_func_proto bpf_sk_redirect_map_proto = {
658 	.func           = bpf_sk_redirect_map,
659 	.gpl_only       = false,
660 	.ret_type       = RET_INTEGER,
661 	.arg1_type	= ARG_PTR_TO_CTX,
662 	.arg2_type      = ARG_CONST_MAP_PTR,
663 	.arg3_type      = ARG_ANYTHING,
664 	.arg4_type      = ARG_ANYTHING,
665 };
666 
BPF_CALL_4(bpf_msg_redirect_map,struct sk_msg *,msg,struct bpf_map *,map,u32,key,u64,flags)667 BPF_CALL_4(bpf_msg_redirect_map, struct sk_msg *, msg,
668 	   struct bpf_map *, map, u32, key, u64, flags)
669 {
670 	struct sock *sk;
671 
672 	if (unlikely(flags & ~(BPF_F_INGRESS)))
673 		return SK_DROP;
674 
675 	sk = __sock_map_lookup_elem(map, key);
676 	if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
677 		return SK_DROP;
678 	if (!(flags & BPF_F_INGRESS) && !sk_is_tcp(sk))
679 		return SK_DROP;
680 	if (sk_is_vsock(sk))
681 		return SK_DROP;
682 
683 	msg->flags = flags;
684 	msg->sk_redir = sk;
685 	return SK_PASS;
686 }
687 
688 const struct bpf_func_proto bpf_msg_redirect_map_proto = {
689 	.func           = bpf_msg_redirect_map,
690 	.gpl_only       = false,
691 	.ret_type       = RET_INTEGER,
692 	.arg1_type	= ARG_PTR_TO_CTX,
693 	.arg2_type      = ARG_CONST_MAP_PTR,
694 	.arg3_type      = ARG_ANYTHING,
695 	.arg4_type      = ARG_ANYTHING,
696 };
697 
698 struct sock_map_seq_info {
699 	struct bpf_map *map;
700 	struct sock *sk;
701 	u32 index;
702 };
703 
704 struct bpf_iter__sockmap {
705 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
706 	__bpf_md_ptr(struct bpf_map *, map);
707 	__bpf_md_ptr(void *, key);
708 	__bpf_md_ptr(struct sock *, sk);
709 };
710 
DEFINE_BPF_ITER_FUNC(sockmap,struct bpf_iter_meta * meta,struct bpf_map * map,void * key,struct sock * sk)711 DEFINE_BPF_ITER_FUNC(sockmap, struct bpf_iter_meta *meta,
712 		     struct bpf_map *map, void *key,
713 		     struct sock *sk)
714 
715 static void *sock_map_seq_lookup_elem(struct sock_map_seq_info *info)
716 {
717 	if (unlikely(info->index >= info->map->max_entries))
718 		return NULL;
719 
720 	info->sk = __sock_map_lookup_elem(info->map, info->index);
721 
722 	/* can't return sk directly, since that might be NULL */
723 	return info;
724 }
725 
sock_map_seq_start(struct seq_file * seq,loff_t * pos)726 static void *sock_map_seq_start(struct seq_file *seq, loff_t *pos)
727 	__acquires(rcu)
728 {
729 	struct sock_map_seq_info *info = seq->private;
730 
731 	if (*pos == 0)
732 		++*pos;
733 
734 	/* pairs with sock_map_seq_stop */
735 	rcu_read_lock();
736 	return sock_map_seq_lookup_elem(info);
737 }
738 
sock_map_seq_next(struct seq_file * seq,void * v,loff_t * pos)739 static void *sock_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
740 	__must_hold(rcu)
741 {
742 	struct sock_map_seq_info *info = seq->private;
743 
744 	++*pos;
745 	++info->index;
746 
747 	return sock_map_seq_lookup_elem(info);
748 }
749 
sock_map_seq_show(struct seq_file * seq,void * v)750 static int sock_map_seq_show(struct seq_file *seq, void *v)
751 	__must_hold(rcu)
752 {
753 	struct sock_map_seq_info *info = seq->private;
754 	struct bpf_iter__sockmap ctx = {};
755 	struct bpf_iter_meta meta;
756 	struct bpf_prog *prog;
757 
758 	meta.seq = seq;
759 	prog = bpf_iter_get_info(&meta, !v);
760 	if (!prog)
761 		return 0;
762 
763 	ctx.meta = &meta;
764 	ctx.map = info->map;
765 	if (v) {
766 		ctx.key = &info->index;
767 		ctx.sk = info->sk;
768 	}
769 
770 	return bpf_iter_run_prog(prog, &ctx);
771 }
772 
sock_map_seq_stop(struct seq_file * seq,void * v)773 static void sock_map_seq_stop(struct seq_file *seq, void *v)
774 	__releases(rcu)
775 {
776 	if (!v)
777 		(void)sock_map_seq_show(seq, NULL);
778 
779 	/* pairs with sock_map_seq_start */
780 	rcu_read_unlock();
781 }
782 
783 static const struct seq_operations sock_map_seq_ops = {
784 	.start	= sock_map_seq_start,
785 	.next	= sock_map_seq_next,
786 	.stop	= sock_map_seq_stop,
787 	.show	= sock_map_seq_show,
788 };
789 
sock_map_init_seq_private(void * priv_data,struct bpf_iter_aux_info * aux)790 static int sock_map_init_seq_private(void *priv_data,
791 				     struct bpf_iter_aux_info *aux)
792 {
793 	struct sock_map_seq_info *info = priv_data;
794 
795 	bpf_map_inc_with_uref(aux->map);
796 	info->map = aux->map;
797 	return 0;
798 }
799 
sock_map_fini_seq_private(void * priv_data)800 static void sock_map_fini_seq_private(void *priv_data)
801 {
802 	struct sock_map_seq_info *info = priv_data;
803 
804 	bpf_map_put_with_uref(info->map);
805 }
806 
sock_map_mem_usage(const struct bpf_map * map)807 static u64 sock_map_mem_usage(const struct bpf_map *map)
808 {
809 	u64 usage = sizeof(struct bpf_stab);
810 
811 	usage += (u64)map->max_entries * sizeof(struct sock *);
812 	return usage;
813 }
814 
815 static const struct bpf_iter_seq_info sock_map_iter_seq_info = {
816 	.seq_ops		= &sock_map_seq_ops,
817 	.init_seq_private	= sock_map_init_seq_private,
818 	.fini_seq_private	= sock_map_fini_seq_private,
819 	.seq_priv_size		= sizeof(struct sock_map_seq_info),
820 };
821 
822 BTF_ID_LIST_SINGLE(sock_map_btf_ids, struct, bpf_stab)
823 const struct bpf_map_ops sock_map_ops = {
824 	.map_meta_equal		= bpf_map_meta_equal,
825 	.map_alloc		= sock_map_alloc,
826 	.map_free		= sock_map_free,
827 	.map_get_next_key	= sock_map_get_next_key,
828 	.map_lookup_elem_sys_only = sock_map_lookup_sys,
829 	.map_update_elem	= sock_map_update_elem,
830 	.map_delete_elem	= sock_map_delete_elem,
831 	.map_lookup_elem	= sock_map_lookup,
832 	.map_release_uref	= sock_map_release_progs,
833 	.map_check_btf		= map_check_no_btf,
834 	.map_mem_usage		= sock_map_mem_usage,
835 	.map_btf_id		= &sock_map_btf_ids[0],
836 	.iter_seq_info		= &sock_map_iter_seq_info,
837 };
838 
839 struct bpf_shtab_elem {
840 	struct rcu_head rcu;
841 	u32 hash;
842 	struct sock *sk;
843 	struct hlist_node node;
844 	u8 key[];
845 };
846 
847 struct bpf_shtab_bucket {
848 	struct hlist_head head;
849 	spinlock_t lock;
850 };
851 
852 struct bpf_shtab {
853 	struct bpf_map map;
854 	struct bpf_shtab_bucket *buckets;
855 	u32 buckets_num;
856 	u32 elem_size;
857 	struct sk_psock_progs progs;
858 	atomic_t count;
859 };
860 
sock_hash_bucket_hash(const void * key,u32 len)861 static inline u32 sock_hash_bucket_hash(const void *key, u32 len)
862 {
863 	return jhash(key, len, 0);
864 }
865 
sock_hash_select_bucket(struct bpf_shtab * htab,u32 hash)866 static struct bpf_shtab_bucket *sock_hash_select_bucket(struct bpf_shtab *htab,
867 							u32 hash)
868 {
869 	return &htab->buckets[hash & (htab->buckets_num - 1)];
870 }
871 
872 static struct bpf_shtab_elem *
sock_hash_lookup_elem_raw(struct hlist_head * head,u32 hash,void * key,u32 key_size)873 sock_hash_lookup_elem_raw(struct hlist_head *head, u32 hash, void *key,
874 			  u32 key_size)
875 {
876 	struct bpf_shtab_elem *elem;
877 
878 	hlist_for_each_entry_rcu(elem, head, node) {
879 		if (elem->hash == hash &&
880 		    !memcmp(&elem->key, key, key_size))
881 			return elem;
882 	}
883 
884 	return NULL;
885 }
886 
__sock_hash_lookup_elem(struct bpf_map * map,void * key)887 static struct sock *__sock_hash_lookup_elem(struct bpf_map *map, void *key)
888 {
889 	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
890 	u32 key_size = map->key_size, hash;
891 	struct bpf_shtab_bucket *bucket;
892 	struct bpf_shtab_elem *elem;
893 
894 	WARN_ON_ONCE(!rcu_read_lock_held());
895 
896 	hash = sock_hash_bucket_hash(key, key_size);
897 	bucket = sock_hash_select_bucket(htab, hash);
898 	elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
899 
900 	return elem ? elem->sk : NULL;
901 }
902 
sock_hash_free_elem(struct bpf_shtab * htab,struct bpf_shtab_elem * elem)903 static void sock_hash_free_elem(struct bpf_shtab *htab,
904 				struct bpf_shtab_elem *elem)
905 {
906 	atomic_dec(&htab->count);
907 	kfree_rcu(elem, rcu);
908 }
909 
sock_hash_delete_from_link(struct bpf_map * map,struct sock * sk,void * link_raw)910 static void sock_hash_delete_from_link(struct bpf_map *map, struct sock *sk,
911 				       void *link_raw)
912 {
913 	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
914 	struct bpf_shtab_elem *elem_probe, *elem = link_raw;
915 	struct bpf_shtab_bucket *bucket;
916 
917 	WARN_ON_ONCE(!rcu_read_lock_held());
918 	bucket = sock_hash_select_bucket(htab, elem->hash);
919 
920 	/* elem may be deleted in parallel from the map, but access here
921 	 * is okay since it's going away only after RCU grace period.
922 	 * However, we need to check whether it's still present.
923 	 */
924 	spin_lock_bh(&bucket->lock);
925 	elem_probe = sock_hash_lookup_elem_raw(&bucket->head, elem->hash,
926 					       elem->key, map->key_size);
927 	if (elem_probe && elem_probe == elem) {
928 		hlist_del_rcu(&elem->node);
929 		sock_map_unref(elem->sk, elem);
930 		sock_hash_free_elem(htab, elem);
931 	}
932 	spin_unlock_bh(&bucket->lock);
933 }
934 
sock_hash_delete_elem(struct bpf_map * map,void * key)935 static long sock_hash_delete_elem(struct bpf_map *map, void *key)
936 {
937 	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
938 	u32 hash, key_size = map->key_size;
939 	struct bpf_shtab_bucket *bucket;
940 	struct bpf_shtab_elem *elem;
941 	int ret = -ENOENT;
942 
943 	hash = sock_hash_bucket_hash(key, key_size);
944 	bucket = sock_hash_select_bucket(htab, hash);
945 
946 	spin_lock_bh(&bucket->lock);
947 	elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
948 	if (elem) {
949 		hlist_del_rcu(&elem->node);
950 		sock_map_unref(elem->sk, elem);
951 		sock_hash_free_elem(htab, elem);
952 		ret = 0;
953 	}
954 	spin_unlock_bh(&bucket->lock);
955 	return ret;
956 }
957 
sock_hash_alloc_elem(struct bpf_shtab * htab,void * key,u32 key_size,u32 hash,struct sock * sk,struct bpf_shtab_elem * old)958 static struct bpf_shtab_elem *sock_hash_alloc_elem(struct bpf_shtab *htab,
959 						   void *key, u32 key_size,
960 						   u32 hash, struct sock *sk,
961 						   struct bpf_shtab_elem *old)
962 {
963 	struct bpf_shtab_elem *new;
964 
965 	if (atomic_inc_return(&htab->count) > htab->map.max_entries) {
966 		if (!old) {
967 			atomic_dec(&htab->count);
968 			return ERR_PTR(-E2BIG);
969 		}
970 	}
971 
972 	new = bpf_map_kmalloc_node(&htab->map, htab->elem_size,
973 				   GFP_ATOMIC | __GFP_NOWARN,
974 				   htab->map.numa_node);
975 	if (!new) {
976 		atomic_dec(&htab->count);
977 		return ERR_PTR(-ENOMEM);
978 	}
979 	memcpy(new->key, key, key_size);
980 	new->sk = sk;
981 	new->hash = hash;
982 	return new;
983 }
984 
sock_hash_update_common(struct bpf_map * map,void * key,struct sock * sk,u64 flags)985 static int sock_hash_update_common(struct bpf_map *map, void *key,
986 				   struct sock *sk, u64 flags)
987 {
988 	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
989 	u32 key_size = map->key_size, hash;
990 	struct bpf_shtab_elem *elem, *elem_new;
991 	struct bpf_shtab_bucket *bucket;
992 	struct sk_psock_link *link;
993 	struct sk_psock *psock;
994 	int ret;
995 
996 	WARN_ON_ONCE(!rcu_read_lock_held());
997 	if (unlikely(flags > BPF_EXIST))
998 		return -EINVAL;
999 
1000 	link = sk_psock_init_link();
1001 	if (!link)
1002 		return -ENOMEM;
1003 
1004 	ret = sock_map_link(map, sk);
1005 	if (ret < 0)
1006 		goto out_free;
1007 
1008 	psock = sk_psock(sk);
1009 	WARN_ON_ONCE(!psock);
1010 
1011 	hash = sock_hash_bucket_hash(key, key_size);
1012 	bucket = sock_hash_select_bucket(htab, hash);
1013 
1014 	spin_lock_bh(&bucket->lock);
1015 	elem = sock_hash_lookup_elem_raw(&bucket->head, hash, key, key_size);
1016 	if (elem && flags == BPF_NOEXIST) {
1017 		ret = -EEXIST;
1018 		goto out_unlock;
1019 	} else if (!elem && flags == BPF_EXIST) {
1020 		ret = -ENOENT;
1021 		goto out_unlock;
1022 	}
1023 
1024 	elem_new = sock_hash_alloc_elem(htab, key, key_size, hash, sk, elem);
1025 	if (IS_ERR(elem_new)) {
1026 		ret = PTR_ERR(elem_new);
1027 		goto out_unlock;
1028 	}
1029 
1030 	sock_map_add_link(psock, link, map, elem_new);
1031 	/* Add new element to the head of the list, so that
1032 	 * concurrent search will find it before old elem.
1033 	 */
1034 	hlist_add_head_rcu(&elem_new->node, &bucket->head);
1035 	if (elem) {
1036 		hlist_del_rcu(&elem->node);
1037 		sock_map_unref(elem->sk, elem);
1038 		sock_hash_free_elem(htab, elem);
1039 	}
1040 	spin_unlock_bh(&bucket->lock);
1041 	return 0;
1042 out_unlock:
1043 	spin_unlock_bh(&bucket->lock);
1044 	sk_psock_put(sk, psock);
1045 out_free:
1046 	sk_psock_free_link(link);
1047 	return ret;
1048 }
1049 
sock_hash_get_next_key(struct bpf_map * map,void * key,void * key_next)1050 static int sock_hash_get_next_key(struct bpf_map *map, void *key,
1051 				  void *key_next)
1052 {
1053 	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
1054 	struct bpf_shtab_elem *elem, *elem_next;
1055 	u32 hash, key_size = map->key_size;
1056 	struct hlist_head *head;
1057 	int i = 0;
1058 
1059 	if (!key)
1060 		goto find_first_elem;
1061 	hash = sock_hash_bucket_hash(key, key_size);
1062 	head = &sock_hash_select_bucket(htab, hash)->head;
1063 	elem = sock_hash_lookup_elem_raw(head, hash, key, key_size);
1064 	if (!elem)
1065 		goto find_first_elem;
1066 
1067 	elem_next = hlist_entry_safe(rcu_dereference(hlist_next_rcu(&elem->node)),
1068 				     struct bpf_shtab_elem, node);
1069 	if (elem_next) {
1070 		memcpy(key_next, elem_next->key, key_size);
1071 		return 0;
1072 	}
1073 
1074 	i = hash & (htab->buckets_num - 1);
1075 	i++;
1076 find_first_elem:
1077 	for (; i < htab->buckets_num; i++) {
1078 		head = &sock_hash_select_bucket(htab, i)->head;
1079 		elem_next = hlist_entry_safe(rcu_dereference(hlist_first_rcu(head)),
1080 					     struct bpf_shtab_elem, node);
1081 		if (elem_next) {
1082 			memcpy(key_next, elem_next->key, key_size);
1083 			return 0;
1084 		}
1085 	}
1086 
1087 	return -ENOENT;
1088 }
1089 
sock_hash_alloc(union bpf_attr * attr)1090 static struct bpf_map *sock_hash_alloc(union bpf_attr *attr)
1091 {
1092 	struct bpf_shtab *htab;
1093 	int i, err;
1094 
1095 	if (attr->max_entries == 0 ||
1096 	    attr->key_size    == 0 ||
1097 	    (attr->value_size != sizeof(u32) &&
1098 	     attr->value_size != sizeof(u64)) ||
1099 	    attr->map_flags & ~SOCK_CREATE_FLAG_MASK)
1100 		return ERR_PTR(-EINVAL);
1101 	if (attr->key_size > MAX_BPF_STACK)
1102 		return ERR_PTR(-E2BIG);
1103 
1104 	htab = bpf_map_area_alloc(sizeof(*htab), NUMA_NO_NODE);
1105 	if (!htab)
1106 		return ERR_PTR(-ENOMEM);
1107 
1108 	bpf_map_init_from_attr(&htab->map, attr);
1109 
1110 	htab->buckets_num = roundup_pow_of_two(htab->map.max_entries);
1111 	htab->elem_size = sizeof(struct bpf_shtab_elem) +
1112 			  round_up(htab->map.key_size, 8);
1113 	if (htab->buckets_num == 0 ||
1114 	    htab->buckets_num > U32_MAX / sizeof(struct bpf_shtab_bucket)) {
1115 		err = -EINVAL;
1116 		goto free_htab;
1117 	}
1118 
1119 	htab->buckets = bpf_map_area_alloc(htab->buckets_num *
1120 					   sizeof(struct bpf_shtab_bucket),
1121 					   htab->map.numa_node);
1122 	if (!htab->buckets) {
1123 		err = -ENOMEM;
1124 		goto free_htab;
1125 	}
1126 
1127 	for (i = 0; i < htab->buckets_num; i++) {
1128 		INIT_HLIST_HEAD(&htab->buckets[i].head);
1129 		spin_lock_init(&htab->buckets[i].lock);
1130 	}
1131 
1132 	return &htab->map;
1133 free_htab:
1134 	bpf_map_area_free(htab);
1135 	return ERR_PTR(err);
1136 }
1137 
sock_hash_free(struct bpf_map * map)1138 static void sock_hash_free(struct bpf_map *map)
1139 {
1140 	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
1141 	struct bpf_shtab_bucket *bucket;
1142 	struct hlist_head unlink_list;
1143 	struct bpf_shtab_elem *elem;
1144 	struct hlist_node *node;
1145 	int i;
1146 
1147 	/* After the sync no updates or deletes will be in-flight so it
1148 	 * is safe to walk map and remove entries without risking a race
1149 	 * in EEXIST update case.
1150 	 */
1151 	synchronize_rcu();
1152 	for (i = 0; i < htab->buckets_num; i++) {
1153 		bucket = sock_hash_select_bucket(htab, i);
1154 
1155 		/* We are racing with sock_hash_delete_from_link to
1156 		 * enter the spin-lock critical section. Every socket on
1157 		 * the list is still linked to sockhash. Since link
1158 		 * exists, psock exists and holds a ref to socket. That
1159 		 * lets us to grab a socket ref too.
1160 		 */
1161 		spin_lock_bh(&bucket->lock);
1162 		hlist_for_each_entry(elem, &bucket->head, node)
1163 			sock_hold(elem->sk);
1164 		hlist_move_list(&bucket->head, &unlink_list);
1165 		spin_unlock_bh(&bucket->lock);
1166 
1167 		/* Process removed entries out of atomic context to
1168 		 * block for socket lock before deleting the psock's
1169 		 * link to sockhash.
1170 		 */
1171 		hlist_for_each_entry_safe(elem, node, &unlink_list, node) {
1172 			hlist_del(&elem->node);
1173 			lock_sock(elem->sk);
1174 			rcu_read_lock();
1175 			sock_map_unref(elem->sk, elem);
1176 			rcu_read_unlock();
1177 			release_sock(elem->sk);
1178 			sock_put(elem->sk);
1179 			sock_hash_free_elem(htab, elem);
1180 		}
1181 		cond_resched();
1182 	}
1183 
1184 	/* wait for psock readers accessing its map link */
1185 	synchronize_rcu();
1186 
1187 	bpf_map_area_free(htab->buckets);
1188 	bpf_map_area_free(htab);
1189 }
1190 
sock_hash_lookup_sys(struct bpf_map * map,void * key)1191 static void *sock_hash_lookup_sys(struct bpf_map *map, void *key)
1192 {
1193 	struct sock *sk;
1194 
1195 	if (map->value_size != sizeof(u64))
1196 		return ERR_PTR(-ENOSPC);
1197 
1198 	sk = __sock_hash_lookup_elem(map, key);
1199 	if (!sk)
1200 		return ERR_PTR(-ENOENT);
1201 
1202 	__sock_gen_cookie(sk);
1203 	return &sk->sk_cookie;
1204 }
1205 
sock_hash_lookup(struct bpf_map * map,void * key)1206 static void *sock_hash_lookup(struct bpf_map *map, void *key)
1207 {
1208 	struct sock *sk;
1209 
1210 	sk = __sock_hash_lookup_elem(map, key);
1211 	if (!sk)
1212 		return NULL;
1213 	if (sk_is_refcounted(sk) && !refcount_inc_not_zero(&sk->sk_refcnt))
1214 		return NULL;
1215 	return sk;
1216 }
1217 
sock_hash_release_progs(struct bpf_map * map)1218 static void sock_hash_release_progs(struct bpf_map *map)
1219 {
1220 	psock_progs_drop(&container_of(map, struct bpf_shtab, map)->progs);
1221 }
1222 
BPF_CALL_4(bpf_sock_hash_update,struct bpf_sock_ops_kern *,sops,struct bpf_map *,map,void *,key,u64,flags)1223 BPF_CALL_4(bpf_sock_hash_update, struct bpf_sock_ops_kern *, sops,
1224 	   struct bpf_map *, map, void *, key, u64, flags)
1225 {
1226 	WARN_ON_ONCE(!rcu_read_lock_held());
1227 
1228 	if (likely(sock_map_sk_is_suitable(sops->sk) &&
1229 		   sock_map_op_okay(sops)))
1230 		return sock_hash_update_common(map, key, sops->sk, flags);
1231 	return -EOPNOTSUPP;
1232 }
1233 
1234 const struct bpf_func_proto bpf_sock_hash_update_proto = {
1235 	.func		= bpf_sock_hash_update,
1236 	.gpl_only	= false,
1237 	.pkt_access	= true,
1238 	.ret_type	= RET_INTEGER,
1239 	.arg1_type	= ARG_PTR_TO_CTX,
1240 	.arg2_type	= ARG_CONST_MAP_PTR,
1241 	.arg3_type	= ARG_PTR_TO_MAP_KEY,
1242 	.arg4_type	= ARG_ANYTHING,
1243 };
1244 
BPF_CALL_4(bpf_sk_redirect_hash,struct sk_buff *,skb,struct bpf_map *,map,void *,key,u64,flags)1245 BPF_CALL_4(bpf_sk_redirect_hash, struct sk_buff *, skb,
1246 	   struct bpf_map *, map, void *, key, u64, flags)
1247 {
1248 	struct sock *sk;
1249 
1250 	if (unlikely(flags & ~(BPF_F_INGRESS)))
1251 		return SK_DROP;
1252 
1253 	sk = __sock_hash_lookup_elem(map, key);
1254 	if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
1255 		return SK_DROP;
1256 	if ((flags & BPF_F_INGRESS) && sk_is_vsock(sk))
1257 		return SK_DROP;
1258 
1259 	skb_bpf_set_redir(skb, sk, flags & BPF_F_INGRESS);
1260 	return SK_PASS;
1261 }
1262 
1263 const struct bpf_func_proto bpf_sk_redirect_hash_proto = {
1264 	.func           = bpf_sk_redirect_hash,
1265 	.gpl_only       = false,
1266 	.ret_type       = RET_INTEGER,
1267 	.arg1_type	= ARG_PTR_TO_CTX,
1268 	.arg2_type      = ARG_CONST_MAP_PTR,
1269 	.arg3_type      = ARG_PTR_TO_MAP_KEY,
1270 	.arg4_type      = ARG_ANYTHING,
1271 };
1272 
BPF_CALL_4(bpf_msg_redirect_hash,struct sk_msg *,msg,struct bpf_map *,map,void *,key,u64,flags)1273 BPF_CALL_4(bpf_msg_redirect_hash, struct sk_msg *, msg,
1274 	   struct bpf_map *, map, void *, key, u64, flags)
1275 {
1276 	struct sock *sk;
1277 
1278 	if (unlikely(flags & ~(BPF_F_INGRESS)))
1279 		return SK_DROP;
1280 
1281 	sk = __sock_hash_lookup_elem(map, key);
1282 	if (unlikely(!sk || !sock_map_redirect_allowed(sk)))
1283 		return SK_DROP;
1284 	if (!(flags & BPF_F_INGRESS) && !sk_is_tcp(sk))
1285 		return SK_DROP;
1286 	if (sk_is_vsock(sk))
1287 		return SK_DROP;
1288 
1289 	msg->flags = flags;
1290 	msg->sk_redir = sk;
1291 	return SK_PASS;
1292 }
1293 
1294 const struct bpf_func_proto bpf_msg_redirect_hash_proto = {
1295 	.func           = bpf_msg_redirect_hash,
1296 	.gpl_only       = false,
1297 	.ret_type       = RET_INTEGER,
1298 	.arg1_type	= ARG_PTR_TO_CTX,
1299 	.arg2_type      = ARG_CONST_MAP_PTR,
1300 	.arg3_type      = ARG_PTR_TO_MAP_KEY,
1301 	.arg4_type      = ARG_ANYTHING,
1302 };
1303 
1304 struct sock_hash_seq_info {
1305 	struct bpf_map *map;
1306 	struct bpf_shtab *htab;
1307 	u32 bucket_id;
1308 };
1309 
sock_hash_seq_find_next(struct sock_hash_seq_info * info,struct bpf_shtab_elem * prev_elem)1310 static void *sock_hash_seq_find_next(struct sock_hash_seq_info *info,
1311 				     struct bpf_shtab_elem *prev_elem)
1312 {
1313 	const struct bpf_shtab *htab = info->htab;
1314 	struct bpf_shtab_bucket *bucket;
1315 	struct bpf_shtab_elem *elem;
1316 	struct hlist_node *node;
1317 
1318 	/* try to find next elem in the same bucket */
1319 	if (prev_elem) {
1320 		node = rcu_dereference(hlist_next_rcu(&prev_elem->node));
1321 		elem = hlist_entry_safe(node, struct bpf_shtab_elem, node);
1322 		if (elem)
1323 			return elem;
1324 
1325 		/* no more elements, continue in the next bucket */
1326 		info->bucket_id++;
1327 	}
1328 
1329 	for (; info->bucket_id < htab->buckets_num; info->bucket_id++) {
1330 		bucket = &htab->buckets[info->bucket_id];
1331 		node = rcu_dereference(hlist_first_rcu(&bucket->head));
1332 		elem = hlist_entry_safe(node, struct bpf_shtab_elem, node);
1333 		if (elem)
1334 			return elem;
1335 	}
1336 
1337 	return NULL;
1338 }
1339 
sock_hash_seq_start(struct seq_file * seq,loff_t * pos)1340 static void *sock_hash_seq_start(struct seq_file *seq, loff_t *pos)
1341 	__acquires(rcu)
1342 {
1343 	struct sock_hash_seq_info *info = seq->private;
1344 
1345 	if (*pos == 0)
1346 		++*pos;
1347 
1348 	/* pairs with sock_hash_seq_stop */
1349 	rcu_read_lock();
1350 	return sock_hash_seq_find_next(info, NULL);
1351 }
1352 
sock_hash_seq_next(struct seq_file * seq,void * v,loff_t * pos)1353 static void *sock_hash_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1354 	__must_hold(rcu)
1355 {
1356 	struct sock_hash_seq_info *info = seq->private;
1357 
1358 	++*pos;
1359 	return sock_hash_seq_find_next(info, v);
1360 }
1361 
sock_hash_seq_show(struct seq_file * seq,void * v)1362 static int sock_hash_seq_show(struct seq_file *seq, void *v)
1363 	__must_hold(rcu)
1364 {
1365 	struct sock_hash_seq_info *info = seq->private;
1366 	struct bpf_iter__sockmap ctx = {};
1367 	struct bpf_shtab_elem *elem = v;
1368 	struct bpf_iter_meta meta;
1369 	struct bpf_prog *prog;
1370 
1371 	meta.seq = seq;
1372 	prog = bpf_iter_get_info(&meta, !elem);
1373 	if (!prog)
1374 		return 0;
1375 
1376 	ctx.meta = &meta;
1377 	ctx.map = info->map;
1378 	if (elem) {
1379 		ctx.key = elem->key;
1380 		ctx.sk = elem->sk;
1381 	}
1382 
1383 	return bpf_iter_run_prog(prog, &ctx);
1384 }
1385 
sock_hash_seq_stop(struct seq_file * seq,void * v)1386 static void sock_hash_seq_stop(struct seq_file *seq, void *v)
1387 	__releases(rcu)
1388 {
1389 	if (!v)
1390 		(void)sock_hash_seq_show(seq, NULL);
1391 
1392 	/* pairs with sock_hash_seq_start */
1393 	rcu_read_unlock();
1394 }
1395 
1396 static const struct seq_operations sock_hash_seq_ops = {
1397 	.start	= sock_hash_seq_start,
1398 	.next	= sock_hash_seq_next,
1399 	.stop	= sock_hash_seq_stop,
1400 	.show	= sock_hash_seq_show,
1401 };
1402 
sock_hash_init_seq_private(void * priv_data,struct bpf_iter_aux_info * aux)1403 static int sock_hash_init_seq_private(void *priv_data,
1404 				      struct bpf_iter_aux_info *aux)
1405 {
1406 	struct sock_hash_seq_info *info = priv_data;
1407 
1408 	bpf_map_inc_with_uref(aux->map);
1409 	info->map = aux->map;
1410 	info->htab = container_of(aux->map, struct bpf_shtab, map);
1411 	return 0;
1412 }
1413 
sock_hash_fini_seq_private(void * priv_data)1414 static void sock_hash_fini_seq_private(void *priv_data)
1415 {
1416 	struct sock_hash_seq_info *info = priv_data;
1417 
1418 	bpf_map_put_with_uref(info->map);
1419 }
1420 
sock_hash_mem_usage(const struct bpf_map * map)1421 static u64 sock_hash_mem_usage(const struct bpf_map *map)
1422 {
1423 	struct bpf_shtab *htab = container_of(map, struct bpf_shtab, map);
1424 	u64 usage = sizeof(*htab);
1425 
1426 	usage += htab->buckets_num * sizeof(struct bpf_shtab_bucket);
1427 	usage += atomic_read(&htab->count) * (u64)htab->elem_size;
1428 	return usage;
1429 }
1430 
1431 static const struct bpf_iter_seq_info sock_hash_iter_seq_info = {
1432 	.seq_ops		= &sock_hash_seq_ops,
1433 	.init_seq_private	= sock_hash_init_seq_private,
1434 	.fini_seq_private	= sock_hash_fini_seq_private,
1435 	.seq_priv_size		= sizeof(struct sock_hash_seq_info),
1436 };
1437 
1438 BTF_ID_LIST_SINGLE(sock_hash_map_btf_ids, struct, bpf_shtab)
1439 const struct bpf_map_ops sock_hash_ops = {
1440 	.map_meta_equal		= bpf_map_meta_equal,
1441 	.map_alloc		= sock_hash_alloc,
1442 	.map_free		= sock_hash_free,
1443 	.map_get_next_key	= sock_hash_get_next_key,
1444 	.map_update_elem	= sock_map_update_elem,
1445 	.map_delete_elem	= sock_hash_delete_elem,
1446 	.map_lookup_elem	= sock_hash_lookup,
1447 	.map_lookup_elem_sys_only = sock_hash_lookup_sys,
1448 	.map_release_uref	= sock_hash_release_progs,
1449 	.map_check_btf		= map_check_no_btf,
1450 	.map_mem_usage		= sock_hash_mem_usage,
1451 	.map_btf_id		= &sock_hash_map_btf_ids[0],
1452 	.iter_seq_info		= &sock_hash_iter_seq_info,
1453 };
1454 
sock_map_progs(struct bpf_map * map)1455 static struct sk_psock_progs *sock_map_progs(struct bpf_map *map)
1456 {
1457 	switch (map->map_type) {
1458 	case BPF_MAP_TYPE_SOCKMAP:
1459 		return &container_of(map, struct bpf_stab, map)->progs;
1460 	case BPF_MAP_TYPE_SOCKHASH:
1461 		return &container_of(map, struct bpf_shtab, map)->progs;
1462 	default:
1463 		break;
1464 	}
1465 
1466 	return NULL;
1467 }
1468 
sock_map_prog_link_lookup(struct bpf_map * map,struct bpf_prog *** pprog,struct bpf_link *** plink,u32 which)1469 static int sock_map_prog_link_lookup(struct bpf_map *map, struct bpf_prog ***pprog,
1470 				     struct bpf_link ***plink, u32 which)
1471 {
1472 	struct sk_psock_progs *progs = sock_map_progs(map);
1473 	struct bpf_prog **cur_pprog;
1474 	struct bpf_link **cur_plink;
1475 
1476 	if (!progs)
1477 		return -EOPNOTSUPP;
1478 
1479 	switch (which) {
1480 	case BPF_SK_MSG_VERDICT:
1481 		cur_pprog = &progs->msg_parser;
1482 		cur_plink = &progs->msg_parser_link;
1483 		break;
1484 #if IS_ENABLED(CONFIG_BPF_STREAM_PARSER)
1485 	case BPF_SK_SKB_STREAM_PARSER:
1486 		cur_pprog = &progs->stream_parser;
1487 		cur_plink = &progs->stream_parser_link;
1488 		break;
1489 #endif
1490 	case BPF_SK_SKB_STREAM_VERDICT:
1491 		if (progs->skb_verdict)
1492 			return -EBUSY;
1493 		cur_pprog = &progs->stream_verdict;
1494 		cur_plink = &progs->stream_verdict_link;
1495 		break;
1496 	case BPF_SK_SKB_VERDICT:
1497 		if (progs->stream_verdict)
1498 			return -EBUSY;
1499 		cur_pprog = &progs->skb_verdict;
1500 		cur_plink = &progs->skb_verdict_link;
1501 		break;
1502 	default:
1503 		return -EOPNOTSUPP;
1504 	}
1505 
1506 	*pprog = cur_pprog;
1507 	if (plink)
1508 		*plink = cur_plink;
1509 	return 0;
1510 }
1511 
1512 /* Handle the following four cases:
1513  * prog_attach: prog != NULL, old == NULL, link == NULL
1514  * prog_detach: prog == NULL, old != NULL, link == NULL
1515  * link_attach: prog != NULL, old == NULL, link != NULL
1516  * link_detach: prog == NULL, old != NULL, link != NULL
1517  */
sock_map_prog_update(struct bpf_map * map,struct bpf_prog * prog,struct bpf_prog * old,struct bpf_link * link,u32 which)1518 static int sock_map_prog_update(struct bpf_map *map, struct bpf_prog *prog,
1519 				struct bpf_prog *old, struct bpf_link *link,
1520 				u32 which)
1521 {
1522 	struct bpf_prog **pprog;
1523 	struct bpf_link **plink;
1524 	int ret;
1525 
1526 	ret = sock_map_prog_link_lookup(map, &pprog, &plink, which);
1527 	if (ret)
1528 		return ret;
1529 
1530 	/* for prog_attach/prog_detach/link_attach, return error if a bpf_link
1531 	 * exists for that prog.
1532 	 */
1533 	if ((!link || prog) && *plink)
1534 		return -EBUSY;
1535 
1536 	if (old) {
1537 		ret = psock_replace_prog(pprog, prog, old);
1538 		if (!ret)
1539 			*plink = NULL;
1540 	} else {
1541 		psock_set_prog(pprog, prog);
1542 		if (link)
1543 			*plink = link;
1544 	}
1545 
1546 	return ret;
1547 }
1548 
sock_map_bpf_prog_query(const union bpf_attr * attr,union bpf_attr __user * uattr)1549 int sock_map_bpf_prog_query(const union bpf_attr *attr,
1550 			    union bpf_attr __user *uattr)
1551 {
1552 	__u32 __user *prog_ids = u64_to_user_ptr(attr->query.prog_ids);
1553 	u32 prog_cnt = 0, flags = 0;
1554 	struct bpf_prog **pprog;
1555 	struct bpf_prog *prog;
1556 	struct bpf_map *map;
1557 	u32 id = 0;
1558 	int ret;
1559 
1560 	if (attr->query.query_flags)
1561 		return -EINVAL;
1562 
1563 	CLASS(fd, f)(attr->target_fd);
1564 	map = __bpf_map_get(f);
1565 	if (IS_ERR(map))
1566 		return PTR_ERR(map);
1567 
1568 	rcu_read_lock();
1569 
1570 	ret = sock_map_prog_link_lookup(map, &pprog, NULL, attr->query.attach_type);
1571 	if (ret)
1572 		goto end;
1573 
1574 	prog = *pprog;
1575 	prog_cnt = !prog ? 0 : 1;
1576 
1577 	if (!attr->query.prog_cnt || !prog_ids || !prog_cnt)
1578 		goto end;
1579 
1580 	/* we do not hold the refcnt, the bpf prog may be released
1581 	 * asynchronously and the id would be set to 0.
1582 	 */
1583 	id = data_race(prog->aux->id);
1584 	if (id == 0)
1585 		prog_cnt = 0;
1586 
1587 end:
1588 	rcu_read_unlock();
1589 
1590 	if (copy_to_user(&uattr->query.attach_flags, &flags, sizeof(flags)) ||
1591 	    (id != 0 && copy_to_user(prog_ids, &id, sizeof(u32))) ||
1592 	    copy_to_user(&uattr->query.prog_cnt, &prog_cnt, sizeof(prog_cnt)))
1593 		ret = -EFAULT;
1594 
1595 	return ret;
1596 }
1597 
sock_map_unlink(struct sock * sk,struct sk_psock_link * link)1598 static void sock_map_unlink(struct sock *sk, struct sk_psock_link *link)
1599 {
1600 	switch (link->map->map_type) {
1601 	case BPF_MAP_TYPE_SOCKMAP:
1602 		return sock_map_delete_from_link(link->map, sk,
1603 						 link->link_raw);
1604 	case BPF_MAP_TYPE_SOCKHASH:
1605 		return sock_hash_delete_from_link(link->map, sk,
1606 						  link->link_raw);
1607 	default:
1608 		break;
1609 	}
1610 }
1611 
sock_map_remove_links(struct sock * sk,struct sk_psock * psock)1612 static void sock_map_remove_links(struct sock *sk, struct sk_psock *psock)
1613 {
1614 	struct sk_psock_link *link;
1615 
1616 	while ((link = sk_psock_link_pop(psock))) {
1617 		sock_map_unlink(sk, link);
1618 		sk_psock_free_link(link);
1619 	}
1620 }
1621 
sock_map_unhash(struct sock * sk)1622 void sock_map_unhash(struct sock *sk)
1623 {
1624 	void (*saved_unhash)(struct sock *sk);
1625 	struct sk_psock *psock;
1626 
1627 	rcu_read_lock();
1628 	psock = sk_psock(sk);
1629 	if (unlikely(!psock)) {
1630 		rcu_read_unlock();
1631 		saved_unhash = READ_ONCE(sk->sk_prot)->unhash;
1632 	} else {
1633 		saved_unhash = psock->saved_unhash;
1634 		sock_map_remove_links(sk, psock);
1635 		rcu_read_unlock();
1636 	}
1637 	if (WARN_ON_ONCE(saved_unhash == sock_map_unhash))
1638 		return;
1639 	if (saved_unhash)
1640 		saved_unhash(sk);
1641 }
1642 EXPORT_SYMBOL_GPL(sock_map_unhash);
1643 
sock_map_destroy(struct sock * sk)1644 void sock_map_destroy(struct sock *sk)
1645 {
1646 	void (*saved_destroy)(struct sock *sk);
1647 	struct sk_psock *psock;
1648 
1649 	rcu_read_lock();
1650 	psock = sk_psock_get(sk);
1651 	if (unlikely(!psock)) {
1652 		rcu_read_unlock();
1653 		saved_destroy = READ_ONCE(sk->sk_prot)->destroy;
1654 	} else {
1655 		saved_destroy = psock->saved_destroy;
1656 		sock_map_remove_links(sk, psock);
1657 		rcu_read_unlock();
1658 		sk_psock_stop(psock);
1659 		sk_psock_put(sk, psock);
1660 	}
1661 	if (WARN_ON_ONCE(saved_destroy == sock_map_destroy))
1662 		return;
1663 	if (saved_destroy)
1664 		saved_destroy(sk);
1665 }
1666 EXPORT_SYMBOL_GPL(sock_map_destroy);
1667 
sock_map_close(struct sock * sk,long timeout)1668 void sock_map_close(struct sock *sk, long timeout)
1669 {
1670 	void (*saved_close)(struct sock *sk, long timeout);
1671 	struct sk_psock *psock;
1672 
1673 	lock_sock(sk);
1674 	rcu_read_lock();
1675 	psock = sk_psock(sk);
1676 	if (likely(psock)) {
1677 		saved_close = psock->saved_close;
1678 		sock_map_remove_links(sk, psock);
1679 		psock = sk_psock_get(sk);
1680 		if (unlikely(!psock))
1681 			goto no_psock;
1682 		rcu_read_unlock();
1683 		sk_psock_stop(psock);
1684 		release_sock(sk);
1685 		cancel_delayed_work_sync(&psock->work);
1686 		sk_psock_put(sk, psock);
1687 	} else {
1688 		saved_close = READ_ONCE(sk->sk_prot)->close;
1689 no_psock:
1690 		rcu_read_unlock();
1691 		release_sock(sk);
1692 	}
1693 
1694 	/* Make sure we do not recurse. This is a bug.
1695 	 * Leak the socket instead of crashing on a stack overflow.
1696 	 */
1697 	if (WARN_ON_ONCE(saved_close == sock_map_close))
1698 		return;
1699 	saved_close(sk, timeout);
1700 }
1701 EXPORT_SYMBOL_GPL(sock_map_close);
1702 
1703 struct sockmap_link {
1704 	struct bpf_link link;
1705 	struct bpf_map *map;
1706 	enum bpf_attach_type attach_type;
1707 };
1708 
sock_map_link_release(struct bpf_link * link)1709 static void sock_map_link_release(struct bpf_link *link)
1710 {
1711 	struct sockmap_link *sockmap_link = container_of(link, struct sockmap_link, link);
1712 
1713 	mutex_lock(&sockmap_mutex);
1714 	if (!sockmap_link->map)
1715 		goto out;
1716 
1717 	WARN_ON_ONCE(sock_map_prog_update(sockmap_link->map, NULL, link->prog, link,
1718 					  sockmap_link->attach_type));
1719 
1720 	bpf_map_put_with_uref(sockmap_link->map);
1721 	sockmap_link->map = NULL;
1722 out:
1723 	mutex_unlock(&sockmap_mutex);
1724 }
1725 
sock_map_link_detach(struct bpf_link * link)1726 static int sock_map_link_detach(struct bpf_link *link)
1727 {
1728 	sock_map_link_release(link);
1729 	return 0;
1730 }
1731 
sock_map_link_dealloc(struct bpf_link * link)1732 static void sock_map_link_dealloc(struct bpf_link *link)
1733 {
1734 	kfree(link);
1735 }
1736 
1737 /* Handle the following two cases:
1738  * case 1: link != NULL, prog != NULL, old != NULL
1739  * case 2: link != NULL, prog != NULL, old == NULL
1740  */
sock_map_link_update_prog(struct bpf_link * link,struct bpf_prog * prog,struct bpf_prog * old)1741 static int sock_map_link_update_prog(struct bpf_link *link,
1742 				     struct bpf_prog *prog,
1743 				     struct bpf_prog *old)
1744 {
1745 	const struct sockmap_link *sockmap_link = container_of(link, struct sockmap_link, link);
1746 	struct bpf_prog **pprog, *old_link_prog;
1747 	struct bpf_link **plink;
1748 	int ret = 0;
1749 
1750 	mutex_lock(&sockmap_mutex);
1751 
1752 	/* If old prog is not NULL, ensure old prog is the same as link->prog. */
1753 	if (old && link->prog != old) {
1754 		ret = -EPERM;
1755 		goto out;
1756 	}
1757 	/* Ensure link->prog has the same type/attach_type as the new prog. */
1758 	if (link->prog->type != prog->type ||
1759 	    link->prog->expected_attach_type != prog->expected_attach_type) {
1760 		ret = -EINVAL;
1761 		goto out;
1762 	}
1763 	if (!sockmap_link->map) {
1764 		ret = -ENOLINK;
1765 		goto out;
1766 	}
1767 
1768 	ret = sock_map_prog_link_lookup(sockmap_link->map, &pprog, &plink,
1769 					sockmap_link->attach_type);
1770 	if (ret)
1771 		goto out;
1772 
1773 	/* return error if the stored bpf_link does not match the incoming bpf_link. */
1774 	if (link != *plink) {
1775 		ret = -EBUSY;
1776 		goto out;
1777 	}
1778 
1779 	if (old) {
1780 		ret = psock_replace_prog(pprog, prog, old);
1781 		if (ret)
1782 			goto out;
1783 	} else {
1784 		psock_set_prog(pprog, prog);
1785 	}
1786 
1787 	bpf_prog_inc(prog);
1788 	old_link_prog = xchg(&link->prog, prog);
1789 	bpf_prog_put(old_link_prog);
1790 
1791 out:
1792 	mutex_unlock(&sockmap_mutex);
1793 	return ret;
1794 }
1795 
sock_map_link_get_map_id(const struct sockmap_link * sockmap_link)1796 static u32 sock_map_link_get_map_id(const struct sockmap_link *sockmap_link)
1797 {
1798 	u32 map_id = 0;
1799 
1800 	mutex_lock(&sockmap_mutex);
1801 	if (sockmap_link->map)
1802 		map_id = sockmap_link->map->id;
1803 	mutex_unlock(&sockmap_mutex);
1804 	return map_id;
1805 }
1806 
sock_map_link_fill_info(const struct bpf_link * link,struct bpf_link_info * info)1807 static int sock_map_link_fill_info(const struct bpf_link *link,
1808 				   struct bpf_link_info *info)
1809 {
1810 	const struct sockmap_link *sockmap_link = container_of(link, struct sockmap_link, link);
1811 	u32 map_id = sock_map_link_get_map_id(sockmap_link);
1812 
1813 	info->sockmap.map_id = map_id;
1814 	info->sockmap.attach_type = sockmap_link->attach_type;
1815 	return 0;
1816 }
1817 
sock_map_link_show_fdinfo(const struct bpf_link * link,struct seq_file * seq)1818 static void sock_map_link_show_fdinfo(const struct bpf_link *link,
1819 				      struct seq_file *seq)
1820 {
1821 	const struct sockmap_link *sockmap_link = container_of(link, struct sockmap_link, link);
1822 	u32 map_id = sock_map_link_get_map_id(sockmap_link);
1823 
1824 	seq_printf(seq, "map_id:\t%u\n", map_id);
1825 	seq_printf(seq, "attach_type:\t%u\n", sockmap_link->attach_type);
1826 }
1827 
1828 static const struct bpf_link_ops sock_map_link_ops = {
1829 	.release = sock_map_link_release,
1830 	.dealloc = sock_map_link_dealloc,
1831 	.detach = sock_map_link_detach,
1832 	.update_prog = sock_map_link_update_prog,
1833 	.fill_link_info = sock_map_link_fill_info,
1834 	.show_fdinfo = sock_map_link_show_fdinfo,
1835 };
1836 
sock_map_link_create(const union bpf_attr * attr,struct bpf_prog * prog)1837 int sock_map_link_create(const union bpf_attr *attr, struct bpf_prog *prog)
1838 {
1839 	struct bpf_link_primer link_primer;
1840 	struct sockmap_link *sockmap_link;
1841 	enum bpf_attach_type attach_type;
1842 	struct bpf_map *map;
1843 	int ret;
1844 
1845 	if (attr->link_create.flags)
1846 		return -EINVAL;
1847 
1848 	map = bpf_map_get_with_uref(attr->link_create.target_fd);
1849 	if (IS_ERR(map))
1850 		return PTR_ERR(map);
1851 	if (map->map_type != BPF_MAP_TYPE_SOCKMAP && map->map_type != BPF_MAP_TYPE_SOCKHASH) {
1852 		ret = -EINVAL;
1853 		goto out;
1854 	}
1855 
1856 	sockmap_link = kzalloc(sizeof(*sockmap_link), GFP_USER);
1857 	if (!sockmap_link) {
1858 		ret = -ENOMEM;
1859 		goto out;
1860 	}
1861 
1862 	attach_type = attr->link_create.attach_type;
1863 	bpf_link_init(&sockmap_link->link, BPF_LINK_TYPE_SOCKMAP, &sock_map_link_ops, prog);
1864 	sockmap_link->map = map;
1865 	sockmap_link->attach_type = attach_type;
1866 
1867 	ret = bpf_link_prime(&sockmap_link->link, &link_primer);
1868 	if (ret) {
1869 		kfree(sockmap_link);
1870 		goto out;
1871 	}
1872 
1873 	mutex_lock(&sockmap_mutex);
1874 	ret = sock_map_prog_update(map, prog, NULL, &sockmap_link->link, attach_type);
1875 	mutex_unlock(&sockmap_mutex);
1876 	if (ret) {
1877 		bpf_link_cleanup(&link_primer);
1878 		goto out;
1879 	}
1880 
1881 	/* Increase refcnt for the prog since when old prog is replaced with
1882 	 * psock_replace_prog() and psock_set_prog() its refcnt will be decreased.
1883 	 *
1884 	 * Actually, we do not need to increase refcnt for the prog since bpf_link
1885 	 * will hold a reference. But in order to have less complexity w.r.t.
1886 	 * replacing/setting prog, let us increase the refcnt to make things simpler.
1887 	 */
1888 	bpf_prog_inc(prog);
1889 
1890 	return bpf_link_settle(&link_primer);
1891 
1892 out:
1893 	bpf_map_put_with_uref(map);
1894 	return ret;
1895 }
1896 
sock_map_iter_attach_target(struct bpf_prog * prog,union bpf_iter_link_info * linfo,struct bpf_iter_aux_info * aux)1897 static int sock_map_iter_attach_target(struct bpf_prog *prog,
1898 				       union bpf_iter_link_info *linfo,
1899 				       struct bpf_iter_aux_info *aux)
1900 {
1901 	struct bpf_map *map;
1902 	int err = -EINVAL;
1903 
1904 	if (!linfo->map.map_fd)
1905 		return -EBADF;
1906 
1907 	map = bpf_map_get_with_uref(linfo->map.map_fd);
1908 	if (IS_ERR(map))
1909 		return PTR_ERR(map);
1910 
1911 	if (map->map_type != BPF_MAP_TYPE_SOCKMAP &&
1912 	    map->map_type != BPF_MAP_TYPE_SOCKHASH)
1913 		goto put_map;
1914 
1915 	if (prog->aux->max_rdonly_access > map->key_size) {
1916 		err = -EACCES;
1917 		goto put_map;
1918 	}
1919 
1920 	aux->map = map;
1921 	return 0;
1922 
1923 put_map:
1924 	bpf_map_put_with_uref(map);
1925 	return err;
1926 }
1927 
sock_map_iter_detach_target(struct bpf_iter_aux_info * aux)1928 static void sock_map_iter_detach_target(struct bpf_iter_aux_info *aux)
1929 {
1930 	bpf_map_put_with_uref(aux->map);
1931 }
1932 
1933 static struct bpf_iter_reg sock_map_iter_reg = {
1934 	.target			= "sockmap",
1935 	.attach_target		= sock_map_iter_attach_target,
1936 	.detach_target		= sock_map_iter_detach_target,
1937 	.show_fdinfo		= bpf_iter_map_show_fdinfo,
1938 	.fill_link_info		= bpf_iter_map_fill_link_info,
1939 	.ctx_arg_info_size	= 2,
1940 	.ctx_arg_info		= {
1941 		{ offsetof(struct bpf_iter__sockmap, key),
1942 		  PTR_TO_BUF | PTR_MAYBE_NULL | MEM_RDONLY },
1943 		{ offsetof(struct bpf_iter__sockmap, sk),
1944 		  PTR_TO_BTF_ID_OR_NULL },
1945 	},
1946 };
1947 
bpf_sockmap_iter_init(void)1948 static int __init bpf_sockmap_iter_init(void)
1949 {
1950 	sock_map_iter_reg.ctx_arg_info[1].btf_id =
1951 		btf_sock_ids[BTF_SOCK_TYPE_SOCK];
1952 	return bpf_iter_reg_target(&sock_map_iter_reg);
1953 }
1954 late_initcall(bpf_sockmap_iter_init);
1955