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