xref: /linux/drivers/net/ovpn/peer.c (revision b43beccb3713fafada57814b0a652f4a876eb75f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*  OpenVPN data channel offload
3  *
4  *  Copyright (C) 2020-2025 OpenVPN, Inc.
5  *
6  *  Author:	James Yonan <james@openvpn.net>
7  *		Antonio Quartulli <antonio@openvpn.net>
8  */
9 
10 #include <linux/skbuff.h>
11 #include <linux/list.h>
12 #include <linux/hashtable.h>
13 #include <net/ip6_route.h>
14 
15 #include "ovpnpriv.h"
16 #include "bind.h"
17 #include "pktid.h"
18 #include "crypto.h"
19 #include "io.h"
20 #include "main.h"
21 #include "netlink.h"
22 #include "peer.h"
23 #include "socket.h"
24 
25 static void unlock_ovpn(struct ovpn_priv *ovpn,
26 			 struct llist_head *release_list)
27 	__releases(&ovpn->lock)
28 {
29 	struct ovpn_peer *peer, *next;
30 
31 	spin_unlock_bh(&ovpn->lock);
32 
33 	llist_for_each_entry_safe(peer, next, release_list->first,
34 				  release_entry) {
35 		ovpn_socket_release(peer);
36 		ovpn_peer_put(peer);
37 	}
38 }
39 
40 /**
41  * ovpn_peer_keepalive_set - configure keepalive values for peer
42  * @peer: the peer to configure
43  * @interval: outgoing keepalive interval
44  * @timeout: incoming keepalive timeout
45  */
46 void ovpn_peer_keepalive_set(struct ovpn_peer *peer, u32 interval, u32 timeout)
47 {
48 	time64_t now = ktime_get_boottime_seconds();
49 
50 	netdev_dbg(peer->ovpn->dev,
51 		   "scheduling keepalive for peer %u: interval=%u timeout=%u\n",
52 		   peer->id, interval, timeout);
53 
54 	peer->keepalive_interval = interval;
55 	WRITE_ONCE(peer->last_sent, now);
56 	peer->keepalive_xmit_exp = now + interval;
57 
58 	peer->keepalive_timeout = timeout;
59 	WRITE_ONCE(peer->last_recv, now);
60 	peer->keepalive_recv_exp = now + timeout;
61 
62 	/* now that interval and timeout have been changed, kick
63 	 * off the worker so that the next delay can be recomputed
64 	 */
65 	mod_delayed_work(ovpn_wq, &peer->ovpn->keepalive_work, 0);
66 }
67 
68 /**
69  * ovpn_peer_keepalive_send - periodic worker sending keepalive packets
70  * @work: pointer to the work member of the related peer object
71  *
72  * NOTE: the reference to peer is not dropped because it gets inherited
73  * by ovpn_xmit_special()
74  */
75 static void ovpn_peer_keepalive_send(struct work_struct *work)
76 {
77 	struct ovpn_peer *peer = container_of(work, struct ovpn_peer,
78 					      keepalive_work);
79 
80 	local_bh_disable();
81 	ovpn_xmit_special(peer, ovpn_keepalive_message,
82 			  sizeof(ovpn_keepalive_message));
83 	local_bh_enable();
84 }
85 
86 /**
87  * ovpn_peer_new - allocate and initialize a new peer object
88  * @ovpn: the openvpn instance inside which the peer should be created
89  * @id: the ID assigned to this peer
90  *
91  * Return: a pointer to the new peer on success or an error code otherwise
92  */
93 struct ovpn_peer *ovpn_peer_new(struct ovpn_priv *ovpn, u32 id)
94 {
95 	struct ovpn_peer *peer;
96 	int ret;
97 
98 	/* alloc and init peer object */
99 	peer = kzalloc_obj(*peer);
100 	if (!peer)
101 		return ERR_PTR(-ENOMEM);
102 
103 	/* in the default case TX and RX IDs are the same.
104 	 * the user may set a different TX ID via netlink
105 	 */
106 	peer->id = id;
107 	peer->tx_id = id;
108 	peer->ovpn = ovpn;
109 
110 	peer->vpn_addrs.ipv4.s_addr = htonl(INADDR_ANY);
111 	peer->vpn_addrs.ipv6 = in6addr_any;
112 
113 	RCU_INIT_POINTER(peer->bind, NULL);
114 	ovpn_crypto_state_init(&peer->crypto);
115 	spin_lock_init(&peer->lock);
116 	seqcount_spinlock_init(&peer->route_key_seq, &peer->lock);
117 	kref_init(&peer->refcount);
118 	ovpn_peer_stats_init(&peer->vpn_stats);
119 	ovpn_peer_stats_init(&peer->link_stats);
120 	INIT_WORK(&peer->keepalive_work, ovpn_peer_keepalive_send);
121 
122 	ret = dst_cache_init(&peer->dst_cache, GFP_KERNEL);
123 	if (ret < 0) {
124 		netdev_err(ovpn->dev,
125 			   "cannot initialize dst cache for peer %u\n",
126 			   peer->id);
127 		kfree(peer);
128 		return ERR_PTR(ret);
129 	}
130 
131 	netdev_hold(ovpn->dev, &peer->dev_tracker, GFP_KERNEL);
132 
133 	return peer;
134 }
135 
136 /**
137  * ovpn_peer_reset_sockaddr - recreate binding for peer
138  * @peer: peer to recreate the binding for
139  * @ss: sockaddr to use as remote endpoint for the binding
140  * @local_ip: local IP for the binding
141  *
142  * Return: 0 on success or a negative error code otherwise
143  */
144 int ovpn_peer_reset_sockaddr(struct ovpn_peer *peer,
145 			     const struct sockaddr_storage *ss,
146 			     const void *local_ip)
147 {
148 	struct ovpn_bind *bind;
149 	size_t ip_len;
150 
151 	lockdep_assert_held(&peer->lock);
152 
153 	/* create new ovpn_bind object */
154 	bind = ovpn_bind_from_sockaddr(ss);
155 	if (IS_ERR(bind))
156 		return PTR_ERR(bind);
157 
158 	if (local_ip) {
159 		if (ss->ss_family == AF_INET) {
160 			ip_len = sizeof(struct in_addr);
161 		} else if (ss->ss_family == AF_INET6) {
162 			ip_len = sizeof(struct in6_addr);
163 		} else {
164 			net_dbg_ratelimited("%s: invalid family %u for remote endpoint for peer %u\n",
165 					    netdev_name(peer->ovpn->dev),
166 					    ss->ss_family, peer->id);
167 			kfree(bind);
168 			return -EINVAL;
169 		}
170 
171 		memcpy(&bind->local, local_ip, ip_len);
172 	}
173 
174 	/* set binding */
175 	ovpn_bind_reset(peer, bind);
176 
177 	return 0;
178 }
179 
180 /* variable name __tbl2 needs to be different from __tbl1
181  * in the macro below to avoid confusing clang
182  */
183 #define ovpn_get_hash_slot(_tbl, _key, _key_len) ({	\
184 	typeof(_tbl) *__tbl2 = &(_tbl);			\
185 	jhash(_key, _key_len, 0) % HASH_SIZE(*__tbl2);	\
186 })
187 
188 #define ovpn_get_hash_head(_tbl, _key, _key_len) ({		\
189 	typeof(_tbl) *__tbl1 = &(_tbl);				\
190 	&(*__tbl1)[ovpn_get_hash_slot(*__tbl1, _key, _key_len)];\
191 })
192 
193 static void __ovpn_peer_hash_transp_addr(struct ovpn_peer *peer,
194 					 const struct ovpn_bind *bind);
195 
196 /**
197  * ovpn_peer_endpoints_update - update remote or local endpoint for peer
198  * @peer: peer to update the remote endpoint for
199  * @skb: incoming packet to retrieve the source/destination address from
200  */
201 void ovpn_peer_endpoints_update(struct ovpn_peer *peer, struct sk_buff *skb)
202 {
203 	const void *local_ip = NULL;
204 	struct sockaddr_storage ss;
205 	struct sockaddr_in6 *sa6;
206 	struct sockaddr_in *sa;
207 	struct ovpn_bind *bind;
208 	bool floated = false;
209 
210 	spin_lock_bh(&peer->lock);
211 	bind = rcu_dereference_protected(peer->bind,
212 					 lockdep_is_held(&peer->lock));
213 	if (unlikely(!bind))
214 		goto unlock;
215 
216 	switch (skb->protocol) {
217 	case htons(ETH_P_IP):
218 		/* float check */
219 		if (unlikely(!ovpn_bind_skb_src_match(bind, skb))) {
220 			/* unconditionally save local endpoint in case
221 			 * of float, as it may have changed as well
222 			 */
223 			local_ip = &ip_hdr(skb)->daddr;
224 			sa = (struct sockaddr_in *)&ss;
225 			/* use a designated initializer so the sin_zero padding
226 			 * is zeroed (it ends up in the by_transp_addr hash key)
227 			 * without memset-ing the whole sockaddr_storage on the
228 			 * RX fast path
229 			 */
230 			*sa = (struct sockaddr_in) {
231 				.sin_family = AF_INET,
232 				.sin_addr.s_addr = ip_hdr(skb)->saddr,
233 				.sin_port = udp_hdr(skb)->source,
234 			};
235 			floated = true;
236 			break;
237 		}
238 
239 		/* if no float happened, let's double check if the local endpoint
240 		 * has changed
241 		 */
242 		if (unlikely(bind->local.ipv4.s_addr != ip_hdr(skb)->daddr)) {
243 			net_dbg_ratelimited("%s: learning local IPv4 for peer %d (%pI4 -> %pI4)\n",
244 					    netdev_name(peer->ovpn->dev),
245 					    peer->id, &bind->local.ipv4.s_addr,
246 					    &ip_hdr(skb)->daddr);
247 			local_ip = &ip_hdr(skb)->daddr;
248 			memcpy(&ss, &bind->remote, sizeof(struct sockaddr_in));
249 			break;
250 		}
251 		/* nothing changed */
252 		goto unlock;
253 	case htons(ETH_P_IPV6):
254 		/* float check */
255 		if (unlikely(!ovpn_bind_skb_src_match(bind, skb))) {
256 			/* unconditionally save local endpoint in case
257 			 * of float, as it may have changed as well
258 			 */
259 			local_ip = &ipv6_hdr(skb)->daddr;
260 			sa6 = (struct sockaddr_in6 *)&ss;
261 			/* use a designated initializer so the sin6_flowinfo
262 			 * padding is zeroed (it ends up in the by_transp_addr
263 			 * hash key) without memset-ing the whole
264 			 * sockaddr_storage on the RX fast path
265 			 */
266 			*sa6 = (struct sockaddr_in6) {
267 				.sin6_family = AF_INET6,
268 				.sin6_addr = ipv6_hdr(skb)->saddr,
269 				.sin6_port = udp_hdr(skb)->source,
270 				.sin6_scope_id =
271 					ipv6_iface_scope_id(&ipv6_hdr(skb)->saddr,
272 							    skb->skb_iif),
273 			};
274 			floated = true;
275 			break;
276 		}
277 
278 		/* if no float happened, let's double check if the local endpoint
279 		 * has changed
280 		 */
281 		if (unlikely(!ipv6_addr_equal(&bind->local.ipv6,
282 					      &ipv6_hdr(skb)->daddr))) {
283 			net_dbg_ratelimited("%s: learning local IPv6 for peer %d (%pI6c -> %pI6c)\n",
284 					    netdev_name(peer->ovpn->dev),
285 					    peer->id, &bind->local.ipv6,
286 					    &ipv6_hdr(skb)->daddr);
287 			local_ip = &ipv6_hdr(skb)->daddr;
288 			memcpy(&ss, &bind->remote, sizeof(struct sockaddr_in6));
289 			break;
290 		}
291 		/* nothing changed */
292 		goto unlock;
293 	default:
294 		goto unlock;
295 	}
296 
297 	if (unlikely(ovpn_peer_reset_sockaddr(peer,
298 					      (struct sockaddr_storage *)&ss,
299 					      local_ip) < 0))
300 		goto unlock;
301 
302 	/* reset the cache only after a successful bind update to avoid useless
303 	 * cache misses on concurrent TX
304 	 */
305 	dst_cache_reset(&peer->dst_cache);
306 
307 	/* if only the local address changed, bail out now */
308 	if (!floated)
309 		goto unlock;
310 
311 	net_dbg_ratelimited("%s: peer %d floated to %pIScp",
312 			    netdev_name(peer->ovpn->dev), peer->id, &ss);
313 
314 	spin_unlock_bh(&peer->lock);
315 
316 	ovpn_nl_peer_float_notify(peer, &ss);
317 
318 	/* rehashing is required only in MP mode as P2P has one peer
319 	 * only and thus there is no hashtable.
320 	 *
321 	 * This function may be invoked concurrently, so re-read peer->bind
322 	 * under the proper locks and rehash against its current value.
323 	 */
324 	if (peer->ovpn->mode != OVPN_MODE_MP)
325 		return;
326 
327 	/* This function may be invoked concurrently, therefore another
328 	 * float may have happened in parallel: re-acquire the locks and
329 	 * rehash using the peer->bind->remote directly as key
330 	 */
331 	spin_lock_bh(&peer->ovpn->lock);
332 	spin_lock_bh(&peer->lock);
333 	bind = rcu_dereference_protected(peer->bind,
334 					 lockdep_is_held(&peer->lock));
335 	__ovpn_peer_hash_transp_addr(peer, bind);
336 	spin_unlock_bh(&peer->lock);
337 	spin_unlock_bh(&peer->ovpn->lock);
338 	return;
339 unlock:
340 	spin_unlock_bh(&peer->lock);
341 }
342 
343 /**
344  * ovpn_peer_release_rcu - RCU callback performing last peer release steps
345  * @head: RCU member of the ovpn_peer
346  */
347 static void ovpn_peer_release_rcu(struct rcu_head *head)
348 {
349 	struct ovpn_peer *peer = container_of(head, struct ovpn_peer, rcu);
350 
351 	/* this call will immediately free the dst_cache, therefore we
352 	 * perform it in the RCU callback, when all contexts are done
353 	 */
354 	dst_cache_destroy(&peer->dst_cache);
355 	kfree(peer);
356 }
357 
358 /**
359  * ovpn_peer_release - release peer private members
360  * @peer: the peer to release
361  */
362 static void ovpn_peer_release(struct ovpn_peer *peer)
363 {
364 	ovpn_crypto_state_release(&peer->crypto);
365 	spin_lock_bh(&peer->lock);
366 	ovpn_bind_reset(peer, NULL);
367 	spin_unlock_bh(&peer->lock);
368 	call_rcu(&peer->rcu, ovpn_peer_release_rcu);
369 	netdev_put(peer->ovpn->dev, &peer->dev_tracker);
370 }
371 
372 /**
373  * ovpn_peer_release_kref - callback for kref_put
374  * @kref: the kref object belonging to the peer
375  */
376 void ovpn_peer_release_kref(struct kref *kref)
377 {
378 	struct ovpn_peer *peer = container_of(kref, struct ovpn_peer, refcount);
379 
380 	ovpn_peer_release(peer);
381 }
382 
383 /**
384  * ovpn_peer_skb_to_sockaddr - fill sockaddr with skb source address
385  * @skb: the packet to extract data from
386  * @ss: the sockaddr to fill
387  *
388  * Return: sockaddr length on success or -1 otherwise
389  */
390 static int ovpn_peer_skb_to_sockaddr(struct sk_buff *skb,
391 				     struct sockaddr_storage *ss)
392 {
393 	struct sockaddr_in6 *sa6;
394 	struct sockaddr_in *sa4;
395 
396 	switch (skb->protocol) {
397 	case htons(ETH_P_IP):
398 		sa4 = (struct sockaddr_in *)ss;
399 		sa4->sin_family = AF_INET;
400 		sa4->sin_addr.s_addr = ip_hdr(skb)->saddr;
401 		sa4->sin_port = udp_hdr(skb)->source;
402 		return sizeof(*sa4);
403 	case htons(ETH_P_IPV6):
404 		sa6 = (struct sockaddr_in6 *)ss;
405 		sa6->sin6_family = AF_INET6;
406 		sa6->sin6_addr = ipv6_hdr(skb)->saddr;
407 		sa6->sin6_port = udp_hdr(skb)->source;
408 		return sizeof(*sa6);
409 	}
410 
411 	return -1;
412 }
413 
414 /**
415  * ovpn_nexthop_from_skb4 - retrieve IPv4 nexthop for outgoing skb
416  * @skb: the outgoing packet
417  *
418  * Return: the IPv4 of the nexthop
419  */
420 static __be32 ovpn_nexthop_from_skb4(struct sk_buff *skb)
421 {
422 	const struct rtable *rt = skb_rtable(skb);
423 
424 	if (rt && rt->rt_uses_gateway)
425 		return rt->rt_gw4;
426 
427 	return ip_hdr(skb)->daddr;
428 }
429 
430 /**
431  * ovpn_nexthop_from_skb6 - retrieve IPv6 nexthop for outgoing skb
432  * @skb: the outgoing packet
433  *
434  * Return: the IPv6 of the nexthop
435  */
436 static struct in6_addr ovpn_nexthop_from_skb6(struct sk_buff *skb)
437 {
438 	const struct rt6_info *rt = skb_rt6_info(skb);
439 
440 	if (!rt || !(rt->rt6i_flags & RTF_GATEWAY))
441 		return ipv6_hdr(skb)->daddr;
442 
443 	return rt->rt6i_gateway;
444 }
445 
446 /**
447  * ovpn_peer_get_by_vpn_addr4 - retrieve peer by its VPN IPv4 address
448  * @ovpn: the openvpn instance to search
449  * @addr: VPN IPv4 to use as search key
450  *
451  * Refcounter is not increased for the returned peer.
452  *
453  * Return: the peer if found or NULL otherwise
454  */
455 static struct ovpn_peer *ovpn_peer_get_by_vpn_addr4(struct ovpn_priv *ovpn,
456 						    __be32 addr)
457 {
458 	struct hlist_nulls_head *nhead;
459 	struct hlist_nulls_node *ntmp;
460 	struct ovpn_peer *tmp;
461 	unsigned int slot;
462 
463 begin:
464 	slot = ovpn_get_hash_slot(ovpn->peers->by_vpn_addr4, &addr,
465 				  sizeof(addr));
466 	nhead = &ovpn->peers->by_vpn_addr4[slot];
467 
468 	hlist_nulls_for_each_entry_rcu(tmp, ntmp, nhead, hash_entry_addr4)
469 		if (addr == tmp->vpn_addrs.ipv4.s_addr)
470 			return tmp;
471 
472 	/* item may have moved during lookup - check nulls and restart
473 	 * if that's the case
474 	 */
475 	if (get_nulls_value(ntmp) != slot)
476 		goto begin;
477 
478 	return NULL;
479 }
480 
481 /**
482  * ovpn_peer_get_by_vpn_addr6 - retrieve peer by its VPN IPv6 address
483  * @ovpn: the openvpn instance to search
484  * @addr: VPN IPv6 to use as search key
485  *
486  * Refcounter is not increased for the returned peer.
487  *
488  * Return: the peer if found or NULL otherwise
489  */
490 static struct ovpn_peer *ovpn_peer_get_by_vpn_addr6(struct ovpn_priv *ovpn,
491 						    struct in6_addr *addr)
492 {
493 	struct hlist_nulls_head *nhead;
494 	struct hlist_nulls_node *ntmp;
495 	struct ovpn_peer *tmp;
496 	unsigned int slot;
497 
498 begin:
499 	slot = ovpn_get_hash_slot(ovpn->peers->by_vpn_addr6, addr,
500 				  sizeof(*addr));
501 	nhead = &ovpn->peers->by_vpn_addr6[slot];
502 
503 	hlist_nulls_for_each_entry_rcu(tmp, ntmp, nhead, hash_entry_addr6)
504 		if (ipv6_addr_equal(addr, &tmp->vpn_addrs.ipv6))
505 			return tmp;
506 
507 	/* item may have moved during lookup - check nulls and restart
508 	 * if that's the case
509 	 */
510 	if (get_nulls_value(ntmp) != slot)
511 		goto begin;
512 
513 	return NULL;
514 }
515 
516 /**
517  * ovpn_peer_transp_match - check if sockaddr and peer binding match
518  * @peer: the peer to get the binding from
519  * @ss: the sockaddr to match
520  *
521  * Return: true if sockaddr and binding match or false otherwise
522  */
523 static bool ovpn_peer_transp_match(const struct ovpn_peer *peer,
524 				   const struct sockaddr_storage *ss)
525 {
526 	struct ovpn_bind *bind = rcu_dereference(peer->bind);
527 	struct sockaddr_in6 *sa6;
528 	struct sockaddr_in *sa4;
529 
530 	if (unlikely(!bind))
531 		return false;
532 
533 	if (ss->ss_family != bind->remote.in4.sin_family)
534 		return false;
535 
536 	switch (ss->ss_family) {
537 	case AF_INET:
538 		sa4 = (struct sockaddr_in *)ss;
539 		if (sa4->sin_addr.s_addr != bind->remote.in4.sin_addr.s_addr)
540 			return false;
541 		if (sa4->sin_port != bind->remote.in4.sin_port)
542 			return false;
543 		break;
544 	case AF_INET6:
545 		sa6 = (struct sockaddr_in6 *)ss;
546 		if (!ipv6_addr_equal(&sa6->sin6_addr,
547 				     &bind->remote.in6.sin6_addr))
548 			return false;
549 		if (sa6->sin6_port != bind->remote.in6.sin6_port)
550 			return false;
551 		break;
552 	default:
553 		return false;
554 	}
555 
556 	return true;
557 }
558 
559 /**
560  * ovpn_peer_get_by_transp_addr_p2p - get peer by transport address in a P2P
561  *                                    instance
562  * @ovpn: the openvpn instance to search
563  * @ss: the transport socket address
564  *
565  * Return: the peer if found or NULL otherwise
566  */
567 static struct ovpn_peer *
568 ovpn_peer_get_by_transp_addr_p2p(struct ovpn_priv *ovpn,
569 				 struct sockaddr_storage *ss)
570 {
571 	struct ovpn_peer *tmp, *peer = NULL;
572 
573 	rcu_read_lock();
574 	tmp = rcu_dereference(ovpn->peer);
575 	if (likely(tmp && ovpn_peer_transp_match(tmp, ss) &&
576 		   ovpn_peer_hold(tmp)))
577 		peer = tmp;
578 	rcu_read_unlock();
579 
580 	return peer;
581 }
582 
583 /**
584  * ovpn_peer_get_by_transp_addr - retrieve peer by transport address
585  * @ovpn: the openvpn instance to search
586  * @skb: the skb to retrieve the source transport address from
587  *
588  * Return: a pointer to the peer if found or NULL otherwise
589  */
590 struct ovpn_peer *ovpn_peer_get_by_transp_addr(struct ovpn_priv *ovpn,
591 					       struct sk_buff *skb)
592 {
593 	struct ovpn_peer *tmp, *peer = NULL;
594 	struct sockaddr_storage ss = { 0 };
595 	struct hlist_nulls_head *nhead;
596 	struct hlist_nulls_node *ntmp;
597 	unsigned int slot;
598 	ssize_t sa_len;
599 
600 	sa_len = ovpn_peer_skb_to_sockaddr(skb, &ss);
601 	if (unlikely(sa_len < 0))
602 		return NULL;
603 
604 	if (ovpn->mode == OVPN_MODE_P2P)
605 		return ovpn_peer_get_by_transp_addr_p2p(ovpn, &ss);
606 
607 	rcu_read_lock();
608 begin:
609 	slot = ovpn_get_hash_slot(ovpn->peers->by_transp_addr, &ss, sa_len);
610 	nhead = &ovpn->peers->by_transp_addr[slot];
611 
612 	hlist_nulls_for_each_entry_rcu(tmp, ntmp, nhead,
613 				       hash_entry_transp_addr) {
614 		if (!ovpn_peer_transp_match(tmp, &ss))
615 			continue;
616 
617 		if (!ovpn_peer_hold(tmp))
618 			continue;
619 
620 		peer = tmp;
621 		break;
622 	}
623 
624 	/* item may have moved during lookup - check nulls and restart
625 	 * if that's the case
626 	 */
627 	if (!peer && get_nulls_value(ntmp) != slot)
628 		goto begin;
629 	rcu_read_unlock();
630 
631 	return peer;
632 }
633 
634 /**
635  * ovpn_peer_get_by_id_p2p - get peer by ID in a P2P instance
636  * @ovpn: the openvpn instance to search
637  * @peer_id: the ID of the peer to find
638  *
639  * Return: the peer if found or NULL otherwise
640  */
641 static struct ovpn_peer *ovpn_peer_get_by_id_p2p(struct ovpn_priv *ovpn,
642 						 u32 peer_id)
643 {
644 	struct ovpn_peer *tmp, *peer = NULL;
645 
646 	rcu_read_lock();
647 	tmp = rcu_dereference(ovpn->peer);
648 	if (likely(tmp && tmp->id == peer_id && ovpn_peer_hold(tmp)))
649 		peer = tmp;
650 	rcu_read_unlock();
651 
652 	return peer;
653 }
654 
655 /**
656  * ovpn_peer_get_by_id - retrieve peer by ID
657  * @ovpn: the openvpn instance to search
658  * @peer_id: the unique peer identifier to match
659  *
660  * Return: a pointer to the peer if found or NULL otherwise
661  */
662 struct ovpn_peer *ovpn_peer_get_by_id(struct ovpn_priv *ovpn, u32 peer_id)
663 {
664 	struct ovpn_peer *tmp, *peer = NULL;
665 	struct hlist_head *head;
666 
667 	if (ovpn->mode == OVPN_MODE_P2P)
668 		return ovpn_peer_get_by_id_p2p(ovpn, peer_id);
669 
670 	head = ovpn_get_hash_head(ovpn->peers->by_id, &peer_id,
671 				  sizeof(peer_id));
672 
673 	rcu_read_lock();
674 	hlist_for_each_entry_rcu(tmp, head, hash_entry_id) {
675 		if (tmp->id != peer_id)
676 			continue;
677 
678 		if (!ovpn_peer_hold(tmp))
679 			continue;
680 
681 		peer = tmp;
682 		break;
683 	}
684 	rcu_read_unlock();
685 
686 	return peer;
687 }
688 
689 static void ovpn_peer_remove(struct ovpn_peer *peer,
690 			     enum ovpn_del_peer_reason reason,
691 			     struct llist_head *release_list)
692 {
693 	lockdep_assert_held(&peer->ovpn->lock);
694 
695 	switch (peer->ovpn->mode) {
696 	case OVPN_MODE_MP:
697 		/* prevent double remove */
698 		if (hlist_unhashed(&peer->hash_entry_id))
699 			return;
700 
701 		hlist_del_init_rcu(&peer->hash_entry_id);
702 		hlist_nulls_del_init_rcu(&peer->hash_entry_addr4);
703 		hlist_nulls_del_init_rcu(&peer->hash_entry_addr6);
704 		hlist_nulls_del_init_rcu(&peer->hash_entry_transp_addr);
705 		break;
706 	case OVPN_MODE_P2P:
707 		/* prevent double remove */
708 		if (peer != rcu_access_pointer(peer->ovpn->peer))
709 			return;
710 
711 		RCU_INIT_POINTER(peer->ovpn->peer, NULL);
712 		/* in P2P mode the carrier is switched off when the peer is
713 		 * deleted so that third party protocols can react accordingly
714 		 */
715 		netif_carrier_off(peer->ovpn->dev);
716 		break;
717 	}
718 
719 	peer->delete_reason = reason;
720 	ovpn_nl_peer_del_notify(peer);
721 
722 	/* append to provided list for later socket release and ref drop */
723 	llist_add(&peer->release_entry, release_list);
724 }
725 
726 /**
727  * ovpn_peer_get_by_dst - Lookup peer to send skb to
728  * @ovpn: the private data representing the current VPN session
729  * @skb: the skb to extract the destination address from
730  *
731  * This function takes a tunnel packet and looks up the peer to send it to
732  * after encapsulation. The skb is expected to be the in-tunnel packet, without
733  * any OpenVPN related header.
734  *
735  * Assume that the IP header is accessible in the skb data.
736  *
737  * Return: the peer if found or NULL otherwise.
738  */
739 struct ovpn_peer *ovpn_peer_get_by_dst(struct ovpn_priv *ovpn,
740 				       struct sk_buff *skb)
741 {
742 	struct ovpn_peer *peer = NULL;
743 	struct in6_addr addr6;
744 	__be32 addr4;
745 
746 	/* in P2P mode, no matter the destination, packets are always sent to
747 	 * the single peer listening on the other side
748 	 */
749 	if (ovpn->mode == OVPN_MODE_P2P) {
750 		rcu_read_lock();
751 		peer = rcu_dereference(ovpn->peer);
752 		if (unlikely(peer && !ovpn_peer_hold(peer)))
753 			peer = NULL;
754 		rcu_read_unlock();
755 		return peer;
756 	}
757 
758 	rcu_read_lock();
759 	switch (skb->protocol) {
760 	case htons(ETH_P_IP):
761 		addr4 = ovpn_nexthop_from_skb4(skb);
762 		peer = ovpn_peer_get_by_vpn_addr4(ovpn, addr4);
763 		break;
764 	case htons(ETH_P_IPV6):
765 		addr6 = ovpn_nexthop_from_skb6(skb);
766 		peer = ovpn_peer_get_by_vpn_addr6(ovpn, &addr6);
767 		break;
768 	}
769 
770 	if (unlikely(peer && !ovpn_peer_hold(peer)))
771 		peer = NULL;
772 	rcu_read_unlock();
773 
774 	return peer;
775 }
776 
777 /**
778  * ovpn_nexthop_from_rt4 - look up the IPv4 nexthop for the given destination
779  * @ovpn: the private data representing the current VPN session
780  * @dest: the destination to be looked up
781  *
782  * Looks up in the IPv4 system routing table the IP of the nexthop to be used
783  * to reach the destination passed as argument. If no nexthop can be found, the
784  * destination itself is returned as it probably has to be used as nexthop.
785  *
786  * Return: the IP of the next hop if found or dest itself otherwise
787  */
788 static __be32 ovpn_nexthop_from_rt4(struct ovpn_priv *ovpn, __be32 dest)
789 {
790 	struct rtable *rt;
791 	struct flowi4 fl = {
792 		.daddr = dest
793 	};
794 
795 	rt = ip_route_output_flow(dev_net(ovpn->dev), &fl, NULL);
796 	if (IS_ERR(rt)) {
797 		net_dbg_ratelimited("%s: no route to host %pI4\n",
798 				    netdev_name(ovpn->dev), &dest);
799 		/* if we end up here this packet is probably going to be
800 		 * thrown away later
801 		 */
802 		return dest;
803 	}
804 
805 	if (!rt->rt_uses_gateway)
806 		goto out;
807 
808 	dest = rt->rt_gw4;
809 out:
810 	ip_rt_put(rt);
811 	return dest;
812 }
813 
814 /**
815  * ovpn_nexthop_from_rt6 - look up the IPv6 nexthop for the given destination
816  * @ovpn: the private data representing the current VPN session
817  * @dest: the destination to be looked up
818  *
819  * Looks up in the IPv6 system routing table the IP of the nexthop to be used
820  * to reach the destination passed as argument. If no nexthop can be found, the
821  * destination itself is returned as it probably has to be used as nexthop.
822  *
823  * Return: the IP of the next hop if found or dest itself otherwise
824  */
825 static struct in6_addr ovpn_nexthop_from_rt6(struct ovpn_priv *ovpn,
826 					     struct in6_addr dest)
827 {
828 #if IS_ENABLED(CONFIG_IPV6)
829 	struct dst_entry *entry;
830 	struct rt6_info *rt;
831 	struct flowi6 fl = {
832 		.daddr = dest,
833 	};
834 
835 	entry = ip6_dst_lookup_flow(dev_net(ovpn->dev), NULL, &fl, NULL);
836 	if (IS_ERR(entry)) {
837 		net_dbg_ratelimited("%s: no route to host %pI6c\n",
838 				    netdev_name(ovpn->dev), &dest);
839 		/* if we end up here this packet is probably going to be
840 		 * thrown away later
841 		 */
842 		return dest;
843 	}
844 
845 	rt = dst_rt6_info(entry);
846 
847 	if (!(rt->rt6i_flags & RTF_GATEWAY))
848 		goto out;
849 
850 	dest = rt->rt6i_gateway;
851 out:
852 	dst_release((struct dst_entry *)rt);
853 #endif
854 	return dest;
855 }
856 
857 /**
858  * ovpn_peer_check_by_src - check that skb source is routed via peer
859  * @ovpn: the openvpn instance to search
860  * @skb: the packet to extract source address from
861  * @peer: the peer to check against the source address
862  *
863  * Return: true if the peer is matching or false otherwise
864  */
865 bool ovpn_peer_check_by_src(struct ovpn_priv *ovpn, struct sk_buff *skb,
866 			    struct ovpn_peer *peer)
867 {
868 	bool match = false;
869 	struct in6_addr addr6;
870 	__be32 addr4;
871 
872 	if (ovpn->mode == OVPN_MODE_P2P) {
873 		/* in P2P mode, no matter the destination, packets are always
874 		 * sent to the single peer listening on the other side
875 		 */
876 		return peer == rcu_access_pointer(ovpn->peer);
877 	}
878 
879 	/* This function performs a reverse path check, therefore we now
880 	 * lookup the nexthop we would use if we wanted to route a packet
881 	 * to the source IP. If the nexthop matches the sender we know the
882 	 * latter is valid and we allow the packet to come in
883 	 */
884 
885 	switch (skb->protocol) {
886 	case htons(ETH_P_IP):
887 		addr4 = ovpn_nexthop_from_rt4(ovpn, ip_hdr(skb)->saddr);
888 		rcu_read_lock();
889 		match = (peer == ovpn_peer_get_by_vpn_addr4(ovpn, addr4));
890 		rcu_read_unlock();
891 		break;
892 	case htons(ETH_P_IPV6):
893 		addr6 = ovpn_nexthop_from_rt6(ovpn, ipv6_hdr(skb)->saddr);
894 		rcu_read_lock();
895 		match = (peer == ovpn_peer_get_by_vpn_addr6(ovpn, &addr6));
896 		rcu_read_unlock();
897 		break;
898 	}
899 
900 	return match;
901 }
902 
903 /* Move @peer to the by_transp_addr bucket matching its current bind.
904  *
905  * Caller must hold both peer->ovpn->lock and peer->lock, and must have
906  * already dereferenced a valid (non-NULL) peer->bind, passed in as @bind.
907  */
908 static void __ovpn_peer_hash_transp_addr(struct ovpn_peer *peer,
909 					 const struct ovpn_bind *bind)
910 {
911 	struct sockaddr_storage sa = {};
912 	struct hlist_nulls_head *nhead;
913 	struct sockaddr_in6 *sa6;
914 	struct sockaddr_in *sa4;
915 	size_t salen;
916 
917 	lockdep_assert_held(&peer->ovpn->lock);
918 	lockdep_assert_held(&peer->lock);
919 
920 	if (WARN_ON_ONCE(!bind))
921 		return;
922 
923 	/* peer may have been concurrently removed between the caller's
924 	 * initial lookup and our acquisition of ovpn->lock; skip the
925 	 * rehash so we don't re-insert a removed peer
926 	 */
927 	if (unlikely(hlist_unhashed(&peer->hash_entry_id)))
928 		return;
929 
930 	/* Build the hash key from the transport identity only
931 	 * (family/address/port), matching ovpn_peer_add_mp() and the lookup
932 	 * in ovpn_peer_get_by_transp_addr(). Hashing bind->remote directly
933 	 * would fold in sin6_scope_id (set on the float path but never by the
934 	 * lookup), scattering the peer into a bucket lookups cannot reach.
935 	 */
936 	switch (bind->remote.in4.sin_family) {
937 	case AF_INET:
938 		sa4 = (struct sockaddr_in *)&sa;
939 		sa4->sin_family = AF_INET;
940 		sa4->sin_addr.s_addr = bind->remote.in4.sin_addr.s_addr;
941 		sa4->sin_port = bind->remote.in4.sin_port;
942 		salen = sizeof(*sa4);
943 		break;
944 	case AF_INET6:
945 		sa6 = (struct sockaddr_in6 *)&sa;
946 		sa6->sin6_family = AF_INET6;
947 		sa6->sin6_addr = bind->remote.in6.sin6_addr;
948 		sa6->sin6_port = bind->remote.in6.sin6_port;
949 		salen = sizeof(*sa6);
950 		break;
951 	default:
952 		return;
953 	}
954 
955 	/* remove old hashing (no-op if entry is not currently linked) */
956 	hlist_nulls_del_init_rcu(&peer->hash_entry_transp_addr);
957 	/* re-add with current transport address */
958 	nhead = ovpn_get_hash_head(peer->ovpn->peers->by_transp_addr, &sa,
959 				   salen);
960 	hlist_nulls_add_head_rcu(&peer->hash_entry_transp_addr, nhead);
961 }
962 
963 void ovpn_peer_hash_transp_addr(struct ovpn_peer *peer)
964 {
965 	struct ovpn_bind *bind;
966 
967 	lockdep_assert_held(&peer->ovpn->lock);
968 
969 	/* rehashing makes sense only in multipeer mode */
970 	if (peer->ovpn->mode != OVPN_MODE_MP)
971 		return;
972 
973 	spin_lock_bh(&peer->lock);
974 	bind = rcu_dereference_protected(peer->bind,
975 					 lockdep_is_held(&peer->lock));
976 	__ovpn_peer_hash_transp_addr(peer, bind);
977 	spin_unlock_bh(&peer->lock);
978 }
979 
980 void ovpn_peer_hash_vpn_ip(struct ovpn_peer *peer)
981 {
982 	struct hlist_nulls_head *nhead;
983 
984 	lockdep_assert_held(&peer->ovpn->lock);
985 
986 	/* rehashing makes sense only in multipeer mode */
987 	if (peer->ovpn->mode != OVPN_MODE_MP)
988 		return;
989 
990 	/* peer may have been concurrently removed between the caller's
991 	 * initial lookup and our acquisition of ovpn->lock; skip the
992 	 * rehash so we don't re-insert a removed peer
993 	 */
994 	if (hlist_unhashed(&peer->hash_entry_id))
995 		return;
996 
997 	/* remove potential old hashing */
998 	hlist_nulls_del_init_rcu(&peer->hash_entry_addr4);
999 	hlist_nulls_del_init_rcu(&peer->hash_entry_addr6);
1000 
1001 	if (peer->vpn_addrs.ipv4.s_addr != htonl(INADDR_ANY)) {
1002 		nhead = ovpn_get_hash_head(peer->ovpn->peers->by_vpn_addr4,
1003 					   &peer->vpn_addrs.ipv4,
1004 					   sizeof(peer->vpn_addrs.ipv4));
1005 		hlist_nulls_add_head_rcu(&peer->hash_entry_addr4, nhead);
1006 	}
1007 
1008 	if (!ipv6_addr_any(&peer->vpn_addrs.ipv6)) {
1009 		nhead = ovpn_get_hash_head(peer->ovpn->peers->by_vpn_addr6,
1010 					   &peer->vpn_addrs.ipv6,
1011 					   sizeof(peer->vpn_addrs.ipv6));
1012 		hlist_nulls_add_head_rcu(&peer->hash_entry_addr6, nhead);
1013 	}
1014 }
1015 
1016 /**
1017  * ovpn_peer_add_mp - add peer to related tables in a MP instance
1018  * @ovpn: the instance to add the peer to
1019  * @peer: the peer to add
1020  *
1021  * Return: 0 on success or a negative error code otherwise
1022  */
1023 static int ovpn_peer_add_mp(struct ovpn_priv *ovpn, struct ovpn_peer *peer)
1024 {
1025 	struct sockaddr_storage sa = { 0 };
1026 	struct hlist_nulls_head *nhead;
1027 	struct sockaddr_in6 *sa6;
1028 	struct sockaddr_in *sa4;
1029 	struct ovpn_bind *bind;
1030 	struct ovpn_peer *tmp;
1031 	size_t salen;
1032 	int ret = 0;
1033 
1034 	spin_lock_bh(&ovpn->lock);
1035 	/* do not add duplicates */
1036 	tmp = ovpn_peer_get_by_id(ovpn, peer->id);
1037 	if (tmp) {
1038 		ovpn_peer_put(tmp);
1039 		ret = -EEXIST;
1040 		goto out;
1041 	}
1042 
1043 	bind = rcu_dereference_protected(peer->bind, true);
1044 	/* peers connected via TCP have bind == NULL */
1045 	if (bind) {
1046 		switch (bind->remote.in4.sin_family) {
1047 		case AF_INET:
1048 			sa4 = (struct sockaddr_in *)&sa;
1049 
1050 			sa4->sin_family = AF_INET;
1051 			sa4->sin_addr.s_addr = bind->remote.in4.sin_addr.s_addr;
1052 			sa4->sin_port = bind->remote.in4.sin_port;
1053 			salen = sizeof(*sa4);
1054 			break;
1055 		case AF_INET6:
1056 			sa6 = (struct sockaddr_in6 *)&sa;
1057 
1058 			sa6->sin6_family = AF_INET6;
1059 			sa6->sin6_addr = bind->remote.in6.sin6_addr;
1060 			sa6->sin6_port = bind->remote.in6.sin6_port;
1061 			salen = sizeof(*sa6);
1062 			break;
1063 		default:
1064 			ret = -EPROTONOSUPPORT;
1065 			goto out;
1066 		}
1067 
1068 		nhead = ovpn_get_hash_head(ovpn->peers->by_transp_addr, &sa,
1069 					   salen);
1070 		hlist_nulls_add_head_rcu(&peer->hash_entry_transp_addr, nhead);
1071 	}
1072 
1073 	hlist_add_head_rcu(&peer->hash_entry_id,
1074 			   ovpn_get_hash_head(ovpn->peers->by_id, &peer->id,
1075 					      sizeof(peer->id)));
1076 
1077 	ovpn_peer_hash_vpn_ip(peer);
1078 out:
1079 	spin_unlock_bh(&ovpn->lock);
1080 	return ret;
1081 }
1082 
1083 /**
1084  * ovpn_peer_add_p2p - add peer to related tables in a P2P instance
1085  * @ovpn: the instance to add the peer to
1086  * @peer: the peer to add
1087  *
1088  * Return: 0 on success or a negative error code otherwise
1089  */
1090 static int ovpn_peer_add_p2p(struct ovpn_priv *ovpn, struct ovpn_peer *peer)
1091 {
1092 	LLIST_HEAD(release_list);
1093 	struct ovpn_peer *tmp;
1094 
1095 	spin_lock_bh(&ovpn->lock);
1096 	/* in p2p mode it is possible to have a single peer only, therefore the
1097 	 * old one is released and substituted by the new one
1098 	 */
1099 	tmp = rcu_dereference_protected(ovpn->peer,
1100 					lockdep_is_held(&ovpn->lock));
1101 	if (tmp)
1102 		ovpn_peer_remove(tmp, OVPN_DEL_PEER_REASON_TEARDOWN,
1103 				 &release_list);
1104 
1105 	rcu_assign_pointer(ovpn->peer, peer);
1106 	/* in P2P mode the carrier is switched on when the peer is added */
1107 	netif_carrier_on(ovpn->dev);
1108 	unlock_ovpn(ovpn, &release_list);
1109 
1110 	return 0;
1111 }
1112 
1113 /**
1114  * ovpn_peer_add - add peer to the related tables
1115  * @ovpn: the openvpn instance the peer belongs to
1116  * @peer: the peer object to add
1117  *
1118  * Assume refcounter was increased by caller
1119  *
1120  * Return: 0 on success or a negative error code otherwise
1121  */
1122 int ovpn_peer_add(struct ovpn_priv *ovpn, struct ovpn_peer *peer)
1123 {
1124 	int ret = -ENODEV;
1125 
1126 	/* Prevent adding new peers while destroying the ovpn interface.
1127 	 * Failing to do so would end up holding the device reference
1128 	 * endlessly hostage of the new peer object with no chance of
1129 	 * release..
1130 	 */
1131 	netdev_lock(ovpn->dev);
1132 	if (ovpn->dev->reg_state != NETREG_REGISTERED)
1133 		goto out;
1134 
1135 	switch (ovpn->mode) {
1136 	case OVPN_MODE_MP:
1137 		ret = ovpn_peer_add_mp(ovpn, peer);
1138 		break;
1139 	case OVPN_MODE_P2P:
1140 		ret = ovpn_peer_add_p2p(ovpn, peer);
1141 		break;
1142 	}
1143 out:
1144 	netdev_unlock(ovpn->dev);
1145 
1146 	return ret;
1147 }
1148 
1149 /**
1150  * ovpn_peer_del_mp - delete peer from related tables in a MP instance
1151  * @peer: the peer to delete
1152  * @reason: reason why the peer was deleted (sent to userspace)
1153  * @release_list: list where delete peer should be appended
1154  *
1155  * Return: 0 on success or a negative error code otherwise
1156  */
1157 static int ovpn_peer_del_mp(struct ovpn_peer *peer,
1158 			    enum ovpn_del_peer_reason reason,
1159 			    struct llist_head *release_list)
1160 {
1161 	struct ovpn_peer *tmp;
1162 	int ret = -ENOENT;
1163 
1164 	lockdep_assert_held(&peer->ovpn->lock);
1165 
1166 	tmp = ovpn_peer_get_by_id(peer->ovpn, peer->id);
1167 	if (tmp == peer) {
1168 		ovpn_peer_remove(peer, reason, release_list);
1169 		ret = 0;
1170 	}
1171 
1172 	if (tmp)
1173 		ovpn_peer_put(tmp);
1174 
1175 	return ret;
1176 }
1177 
1178 /**
1179  * ovpn_peer_del_p2p - delete peer from related tables in a P2P instance
1180  * @peer: the peer to delete
1181  * @reason: reason why the peer was deleted (sent to userspace)
1182  * @release_list: list where delete peer should be appended
1183  *
1184  * Return: 0 on success or a negative error code otherwise
1185  */
1186 static int ovpn_peer_del_p2p(struct ovpn_peer *peer,
1187 			     enum ovpn_del_peer_reason reason,
1188 			     struct llist_head *release_list)
1189 {
1190 	struct ovpn_peer *tmp;
1191 
1192 	lockdep_assert_held(&peer->ovpn->lock);
1193 
1194 	tmp = rcu_dereference_protected(peer->ovpn->peer,
1195 					lockdep_is_held(&peer->ovpn->lock));
1196 	if (tmp != peer)
1197 		return -ENOENT;
1198 
1199 	ovpn_peer_remove(peer, reason, release_list);
1200 
1201 	return 0;
1202 }
1203 
1204 /**
1205  * ovpn_peer_del - delete peer from related tables
1206  * @peer: the peer object to delete
1207  * @reason: reason for deleting peer (will be sent to userspace)
1208  *
1209  * Return: 0 on success or a negative error code otherwise
1210  */
1211 int ovpn_peer_del(struct ovpn_peer *peer, enum ovpn_del_peer_reason reason)
1212 {
1213 	LLIST_HEAD(release_list);
1214 	int ret = -EOPNOTSUPP;
1215 
1216 	spin_lock_bh(&peer->ovpn->lock);
1217 	switch (peer->ovpn->mode) {
1218 	case OVPN_MODE_MP:
1219 		ret = ovpn_peer_del_mp(peer, reason, &release_list);
1220 		break;
1221 	case OVPN_MODE_P2P:
1222 		ret = ovpn_peer_del_p2p(peer, reason, &release_list);
1223 		break;
1224 	default:
1225 		break;
1226 	}
1227 	unlock_ovpn(peer->ovpn, &release_list);
1228 
1229 	return ret;
1230 }
1231 
1232 /**
1233  * ovpn_peer_release_p2p - release peer upon P2P device teardown
1234  * @ovpn: the instance being torn down
1235  * @sk: if not NULL, release peer only if it's using this specific socket
1236  * @reason: the reason for releasing the peer
1237  */
1238 static void ovpn_peer_release_p2p(struct ovpn_priv *ovpn, struct sock *sk,
1239 				  enum ovpn_del_peer_reason reason)
1240 {
1241 	struct ovpn_socket *ovpn_sock;
1242 	LLIST_HEAD(release_list);
1243 	struct ovpn_peer *peer;
1244 
1245 	spin_lock_bh(&ovpn->lock);
1246 	peer = rcu_dereference_protected(ovpn->peer,
1247 					 lockdep_is_held(&ovpn->lock));
1248 	if (!peer) {
1249 		spin_unlock_bh(&ovpn->lock);
1250 		return;
1251 	}
1252 
1253 	if (sk) {
1254 		ovpn_sock = rcu_dereference_bh(peer->sock);
1255 		if (!ovpn_sock || ovpn_sock->sk != sk) {
1256 			spin_unlock_bh(&ovpn->lock);
1257 			return;
1258 		}
1259 	}
1260 
1261 	ovpn_peer_remove(peer, reason, &release_list);
1262 	unlock_ovpn(ovpn, &release_list);
1263 }
1264 
1265 static void ovpn_peers_release_mp(struct ovpn_priv *ovpn, struct sock *sk,
1266 				  enum ovpn_del_peer_reason reason)
1267 {
1268 	struct ovpn_socket *ovpn_sock;
1269 	LLIST_HEAD(release_list);
1270 	struct ovpn_peer *peer;
1271 	struct hlist_node *tmp;
1272 	int bkt;
1273 
1274 	spin_lock_bh(&ovpn->lock);
1275 	hash_for_each_safe(ovpn->peers->by_id, bkt, tmp, peer, hash_entry_id) {
1276 		bool remove = true;
1277 
1278 		/* if a socket was passed as argument, skip all peers except
1279 		 * those using it
1280 		 */
1281 		if (sk) {
1282 			rcu_read_lock();
1283 			ovpn_sock = rcu_dereference(peer->sock);
1284 			remove = ovpn_sock && ovpn_sock->sk == sk;
1285 			rcu_read_unlock();
1286 		}
1287 
1288 		if (remove)
1289 			ovpn_peer_remove(peer, reason, &release_list);
1290 	}
1291 	unlock_ovpn(ovpn, &release_list);
1292 }
1293 
1294 /**
1295  * ovpn_peers_free - free all peers in the instance
1296  * @ovpn: the instance whose peers should be released
1297  * @sk: if not NULL, only peers using this socket are removed and the socket
1298  *      is released immediately
1299  * @reason: the reason for releasing all peers
1300  */
1301 void ovpn_peers_free(struct ovpn_priv *ovpn, struct sock *sk,
1302 		     enum ovpn_del_peer_reason reason)
1303 {
1304 	switch (ovpn->mode) {
1305 	case OVPN_MODE_P2P:
1306 		ovpn_peer_release_p2p(ovpn, sk, reason);
1307 		break;
1308 	case OVPN_MODE_MP:
1309 		ovpn_peers_release_mp(ovpn, sk, reason);
1310 		break;
1311 	}
1312 }
1313 
1314 static time64_t ovpn_peer_keepalive_work_single(struct ovpn_peer *peer,
1315 						time64_t now,
1316 						struct llist_head *release_list)
1317 {
1318 	time64_t last_recv, last_sent, next_run1, next_run2;
1319 	unsigned long timeout, interval;
1320 	bool expired;
1321 
1322 	spin_lock_bh(&peer->lock);
1323 	/* we expect both timers to be configured at the same time,
1324 	 * therefore bail out if either is not set
1325 	 */
1326 	if (!peer->keepalive_timeout || !peer->keepalive_interval) {
1327 		spin_unlock_bh(&peer->lock);
1328 		return 0;
1329 	}
1330 
1331 	/* check for peer timeout */
1332 	expired = false;
1333 	timeout = peer->keepalive_timeout;
1334 	last_recv = READ_ONCE(peer->last_recv);
1335 	if (now < last_recv + timeout) {
1336 		peer->keepalive_recv_exp = last_recv + timeout;
1337 		next_run1 = peer->keepalive_recv_exp;
1338 	} else if (peer->keepalive_recv_exp > now) {
1339 		next_run1 = peer->keepalive_recv_exp;
1340 	} else {
1341 		expired = true;
1342 	}
1343 
1344 	if (expired) {
1345 		/* peer is dead -> kill it and move on */
1346 		spin_unlock_bh(&peer->lock);
1347 		netdev_dbg(peer->ovpn->dev, "peer %u expired\n",
1348 			   peer->id);
1349 		ovpn_peer_remove(peer, OVPN_DEL_PEER_REASON_EXPIRED,
1350 				 release_list);
1351 		return 0;
1352 	}
1353 
1354 	/* check for peer keepalive */
1355 	expired = false;
1356 	interval = peer->keepalive_interval;
1357 	last_sent = READ_ONCE(peer->last_sent);
1358 	if (now < last_sent + interval) {
1359 		peer->keepalive_xmit_exp = last_sent + interval;
1360 		next_run2 = peer->keepalive_xmit_exp;
1361 	} else if (peer->keepalive_xmit_exp > now) {
1362 		next_run2 = peer->keepalive_xmit_exp;
1363 	} else {
1364 		expired = true;
1365 		next_run2 = now + interval;
1366 	}
1367 	spin_unlock_bh(&peer->lock);
1368 
1369 	if (expired) {
1370 		/* a keepalive packet is required */
1371 		netdev_dbg(peer->ovpn->dev,
1372 			   "sending keepalive to peer %u\n",
1373 			   peer->id);
1374 		if (WARN_ON(!ovpn_peer_hold(peer)))
1375 			return 0;
1376 		if (!queue_work(ovpn_wq, &peer->keepalive_work))
1377 			ovpn_peer_put(peer);
1378 	}
1379 
1380 	if (next_run1 < next_run2)
1381 		return next_run1;
1382 
1383 	return next_run2;
1384 }
1385 
1386 static time64_t ovpn_peer_keepalive_work_mp(struct ovpn_priv *ovpn,
1387 					    time64_t now,
1388 					    struct llist_head *release_list)
1389 {
1390 	time64_t tmp_next_run, next_run = 0;
1391 	struct hlist_node *tmp;
1392 	struct ovpn_peer *peer;
1393 	int bkt;
1394 
1395 	lockdep_assert_held(&ovpn->lock);
1396 
1397 	hash_for_each_safe(ovpn->peers->by_id, bkt, tmp, peer, hash_entry_id) {
1398 		tmp_next_run = ovpn_peer_keepalive_work_single(peer, now,
1399 							       release_list);
1400 		if (!tmp_next_run)
1401 			continue;
1402 
1403 		/* the next worker run will be scheduled based on the shortest
1404 		 * required interval across all peers
1405 		 */
1406 		if (!next_run || tmp_next_run < next_run)
1407 			next_run = tmp_next_run;
1408 	}
1409 
1410 	return next_run;
1411 }
1412 
1413 static time64_t ovpn_peer_keepalive_work_p2p(struct ovpn_priv *ovpn,
1414 					     time64_t now,
1415 					     struct llist_head *release_list)
1416 {
1417 	struct ovpn_peer *peer;
1418 	time64_t next_run = 0;
1419 
1420 	lockdep_assert_held(&ovpn->lock);
1421 
1422 	peer = rcu_dereference_protected(ovpn->peer,
1423 					 lockdep_is_held(&ovpn->lock));
1424 	if (peer)
1425 		next_run = ovpn_peer_keepalive_work_single(peer, now,
1426 							   release_list);
1427 
1428 	return next_run;
1429 }
1430 
1431 /**
1432  * ovpn_peer_keepalive_work - run keepalive logic on each known peer
1433  * @work: pointer to the work member of the related ovpn object
1434  *
1435  * Each peer has two timers (if configured):
1436  * 1. peer timeout: when no data is received for a certain interval,
1437  *    the peer is considered dead and it gets killed.
1438  * 2. peer keepalive: when no data is sent to a certain peer for a
1439  *    certain interval, a special 'keepalive' packet is explicitly sent.
1440  *
1441  * This function iterates across the whole peer collection while
1442  * checking the timers described above.
1443  */
1444 void ovpn_peer_keepalive_work(struct work_struct *work)
1445 {
1446 	struct ovpn_priv *ovpn = container_of(work, struct ovpn_priv,
1447 					      keepalive_work.work);
1448 	time64_t next_run = 0, now = ktime_get_boottime_seconds();
1449 	LLIST_HEAD(release_list);
1450 
1451 	spin_lock_bh(&ovpn->lock);
1452 	switch (ovpn->mode) {
1453 	case OVPN_MODE_MP:
1454 		next_run = ovpn_peer_keepalive_work_mp(ovpn, now,
1455 						       &release_list);
1456 		break;
1457 	case OVPN_MODE_P2P:
1458 		next_run = ovpn_peer_keepalive_work_p2p(ovpn, now,
1459 							&release_list);
1460 		break;
1461 	}
1462 
1463 	/* prevent rearming if the interface is being destroyed */
1464 	if (next_run > 0) {
1465 		netdev_dbg(ovpn->dev,
1466 			   "scheduling keepalive work: now=%llu next_run=%llu delta=%llu\n",
1467 			   next_run, now, next_run - now);
1468 		queue_delayed_work(ovpn_wq, &ovpn->keepalive_work,
1469 				   (next_run - now) * HZ);
1470 	}
1471 	unlock_ovpn(ovpn, &release_list);
1472 }
1473