xref: /openbmc/linux/net/l2tp/l2tp_core.c (revision f7777dcc)
1 /*
2  * L2TP core.
3  *
4  * Copyright (c) 2008,2009,2010 Katalix Systems Ltd
5  *
6  * This file contains some code of the original L2TPv2 pppol2tp
7  * driver, which has the following copyright:
8  *
9  * Authors:	Martijn van Oosterhout <kleptog@svana.org>
10  *		James Chapman (jchapman@katalix.com)
11  * Contributors:
12  *		Michal Ostrowski <mostrows@speakeasy.net>
13  *		Arnaldo Carvalho de Melo <acme@xconectiva.com.br>
14  *		David S. Miller (davem@redhat.com)
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License version 2 as
18  * published by the Free Software Foundation.
19  */
20 
21 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
22 
23 #include <linux/module.h>
24 #include <linux/string.h>
25 #include <linux/list.h>
26 #include <linux/rculist.h>
27 #include <linux/uaccess.h>
28 
29 #include <linux/kernel.h>
30 #include <linux/spinlock.h>
31 #include <linux/kthread.h>
32 #include <linux/sched.h>
33 #include <linux/slab.h>
34 #include <linux/errno.h>
35 #include <linux/jiffies.h>
36 
37 #include <linux/netdevice.h>
38 #include <linux/net.h>
39 #include <linux/inetdevice.h>
40 #include <linux/skbuff.h>
41 #include <linux/init.h>
42 #include <linux/in.h>
43 #include <linux/ip.h>
44 #include <linux/udp.h>
45 #include <linux/l2tp.h>
46 #include <linux/hash.h>
47 #include <linux/sort.h>
48 #include <linux/file.h>
49 #include <linux/nsproxy.h>
50 #include <net/net_namespace.h>
51 #include <net/netns/generic.h>
52 #include <net/dst.h>
53 #include <net/ip.h>
54 #include <net/udp.h>
55 #include <net/inet_common.h>
56 #include <net/xfrm.h>
57 #include <net/protocol.h>
58 #include <net/inet6_connection_sock.h>
59 #include <net/inet_ecn.h>
60 #include <net/ip6_route.h>
61 #include <net/ip6_checksum.h>
62 
63 #include <asm/byteorder.h>
64 #include <linux/atomic.h>
65 
66 #include "l2tp_core.h"
67 
68 #define L2TP_DRV_VERSION	"V2.0"
69 
70 /* L2TP header constants */
71 #define L2TP_HDRFLAG_T	   0x8000
72 #define L2TP_HDRFLAG_L	   0x4000
73 #define L2TP_HDRFLAG_S	   0x0800
74 #define L2TP_HDRFLAG_O	   0x0200
75 #define L2TP_HDRFLAG_P	   0x0100
76 
77 #define L2TP_HDR_VER_MASK  0x000F
78 #define L2TP_HDR_VER_2	   0x0002
79 #define L2TP_HDR_VER_3	   0x0003
80 
81 /* L2TPv3 default L2-specific sublayer */
82 #define L2TP_SLFLAG_S	   0x40000000
83 #define L2TP_SL_SEQ_MASK   0x00ffffff
84 
85 #define L2TP_HDR_SIZE_SEQ		10
86 #define L2TP_HDR_SIZE_NOSEQ		6
87 
88 /* Default trace flags */
89 #define L2TP_DEFAULT_DEBUG_FLAGS	0
90 
91 /* Private data stored for received packets in the skb.
92  */
93 struct l2tp_skb_cb {
94 	u32			ns;
95 	u16			has_seq;
96 	u16			length;
97 	unsigned long		expires;
98 };
99 
100 #define L2TP_SKB_CB(skb)	((struct l2tp_skb_cb *) &skb->cb[sizeof(struct inet_skb_parm)])
101 
102 static atomic_t l2tp_tunnel_count;
103 static atomic_t l2tp_session_count;
104 static struct workqueue_struct *l2tp_wq;
105 
106 /* per-net private data for this module */
107 static unsigned int l2tp_net_id;
108 struct l2tp_net {
109 	struct list_head l2tp_tunnel_list;
110 	spinlock_t l2tp_tunnel_list_lock;
111 	struct hlist_head l2tp_session_hlist[L2TP_HASH_SIZE_2];
112 	spinlock_t l2tp_session_hlist_lock;
113 };
114 
115 static void l2tp_session_set_header_len(struct l2tp_session *session, int version);
116 static void l2tp_tunnel_free(struct l2tp_tunnel *tunnel);
117 
118 static inline struct l2tp_tunnel *l2tp_tunnel(struct sock *sk)
119 {
120 	return sk->sk_user_data;
121 }
122 
123 static inline struct l2tp_net *l2tp_pernet(struct net *net)
124 {
125 	BUG_ON(!net);
126 
127 	return net_generic(net, l2tp_net_id);
128 }
129 
130 /* Tunnel reference counts. Incremented per session that is added to
131  * the tunnel.
132  */
133 static inline void l2tp_tunnel_inc_refcount_1(struct l2tp_tunnel *tunnel)
134 {
135 	atomic_inc(&tunnel->ref_count);
136 }
137 
138 static inline void l2tp_tunnel_dec_refcount_1(struct l2tp_tunnel *tunnel)
139 {
140 	if (atomic_dec_and_test(&tunnel->ref_count))
141 		l2tp_tunnel_free(tunnel);
142 }
143 #ifdef L2TP_REFCNT_DEBUG
144 #define l2tp_tunnel_inc_refcount(_t)					\
145 do {									\
146 	pr_debug("l2tp_tunnel_inc_refcount: %s:%d %s: cnt=%d\n",	\
147 		 __func__, __LINE__, (_t)->name,			\
148 		 atomic_read(&_t->ref_count));				\
149 	l2tp_tunnel_inc_refcount_1(_t);					\
150 } while (0)
151 #define l2tp_tunnel_dec_refcount(_t)
152 do {									\
153 	pr_debug("l2tp_tunnel_dec_refcount: %s:%d %s: cnt=%d\n",	\
154 		 __func__, __LINE__, (_t)->name,			\
155 		 atomic_read(&_t->ref_count));				\
156 	l2tp_tunnel_dec_refcount_1(_t);					\
157 } while (0)
158 #else
159 #define l2tp_tunnel_inc_refcount(t) l2tp_tunnel_inc_refcount_1(t)
160 #define l2tp_tunnel_dec_refcount(t) l2tp_tunnel_dec_refcount_1(t)
161 #endif
162 
163 /* Session hash global list for L2TPv3.
164  * The session_id SHOULD be random according to RFC3931, but several
165  * L2TP implementations use incrementing session_ids.  So we do a real
166  * hash on the session_id, rather than a simple bitmask.
167  */
168 static inline struct hlist_head *
169 l2tp_session_id_hash_2(struct l2tp_net *pn, u32 session_id)
170 {
171 	return &pn->l2tp_session_hlist[hash_32(session_id, L2TP_HASH_BITS_2)];
172 
173 }
174 
175 /* Lookup the tunnel socket, possibly involving the fs code if the socket is
176  * owned by userspace.  A struct sock returned from this function must be
177  * released using l2tp_tunnel_sock_put once you're done with it.
178  */
179 struct sock *l2tp_tunnel_sock_lookup(struct l2tp_tunnel *tunnel)
180 {
181 	int err = 0;
182 	struct socket *sock = NULL;
183 	struct sock *sk = NULL;
184 
185 	if (!tunnel)
186 		goto out;
187 
188 	if (tunnel->fd >= 0) {
189 		/* Socket is owned by userspace, who might be in the process
190 		 * of closing it.  Look the socket up using the fd to ensure
191 		 * consistency.
192 		 */
193 		sock = sockfd_lookup(tunnel->fd, &err);
194 		if (sock)
195 			sk = sock->sk;
196 	} else {
197 		/* Socket is owned by kernelspace */
198 		sk = tunnel->sock;
199 		sock_hold(sk);
200 	}
201 
202 out:
203 	return sk;
204 }
205 EXPORT_SYMBOL_GPL(l2tp_tunnel_sock_lookup);
206 
207 /* Drop a reference to a tunnel socket obtained via. l2tp_tunnel_sock_put */
208 void l2tp_tunnel_sock_put(struct sock *sk)
209 {
210 	struct l2tp_tunnel *tunnel = l2tp_sock_to_tunnel(sk);
211 	if (tunnel) {
212 		if (tunnel->fd >= 0) {
213 			/* Socket is owned by userspace */
214 			sockfd_put(sk->sk_socket);
215 		}
216 		sock_put(sk);
217 	}
218 	sock_put(sk);
219 }
220 EXPORT_SYMBOL_GPL(l2tp_tunnel_sock_put);
221 
222 /* Lookup a session by id in the global session list
223  */
224 static struct l2tp_session *l2tp_session_find_2(struct net *net, u32 session_id)
225 {
226 	struct l2tp_net *pn = l2tp_pernet(net);
227 	struct hlist_head *session_list =
228 		l2tp_session_id_hash_2(pn, session_id);
229 	struct l2tp_session *session;
230 
231 	rcu_read_lock_bh();
232 	hlist_for_each_entry_rcu(session, session_list, global_hlist) {
233 		if (session->session_id == session_id) {
234 			rcu_read_unlock_bh();
235 			return session;
236 		}
237 	}
238 	rcu_read_unlock_bh();
239 
240 	return NULL;
241 }
242 
243 /* Session hash list.
244  * The session_id SHOULD be random according to RFC2661, but several
245  * L2TP implementations (Cisco and Microsoft) use incrementing
246  * session_ids.  So we do a real hash on the session_id, rather than a
247  * simple bitmask.
248  */
249 static inline struct hlist_head *
250 l2tp_session_id_hash(struct l2tp_tunnel *tunnel, u32 session_id)
251 {
252 	return &tunnel->session_hlist[hash_32(session_id, L2TP_HASH_BITS)];
253 }
254 
255 /* Lookup a session by id
256  */
257 struct l2tp_session *l2tp_session_find(struct net *net, struct l2tp_tunnel *tunnel, u32 session_id)
258 {
259 	struct hlist_head *session_list;
260 	struct l2tp_session *session;
261 
262 	/* In L2TPv3, session_ids are unique over all tunnels and we
263 	 * sometimes need to look them up before we know the
264 	 * tunnel.
265 	 */
266 	if (tunnel == NULL)
267 		return l2tp_session_find_2(net, session_id);
268 
269 	session_list = l2tp_session_id_hash(tunnel, session_id);
270 	read_lock_bh(&tunnel->hlist_lock);
271 	hlist_for_each_entry(session, session_list, hlist) {
272 		if (session->session_id == session_id) {
273 			read_unlock_bh(&tunnel->hlist_lock);
274 			return session;
275 		}
276 	}
277 	read_unlock_bh(&tunnel->hlist_lock);
278 
279 	return NULL;
280 }
281 EXPORT_SYMBOL_GPL(l2tp_session_find);
282 
283 struct l2tp_session *l2tp_session_find_nth(struct l2tp_tunnel *tunnel, int nth)
284 {
285 	int hash;
286 	struct l2tp_session *session;
287 	int count = 0;
288 
289 	read_lock_bh(&tunnel->hlist_lock);
290 	for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
291 		hlist_for_each_entry(session, &tunnel->session_hlist[hash], hlist) {
292 			if (++count > nth) {
293 				read_unlock_bh(&tunnel->hlist_lock);
294 				return session;
295 			}
296 		}
297 	}
298 
299 	read_unlock_bh(&tunnel->hlist_lock);
300 
301 	return NULL;
302 }
303 EXPORT_SYMBOL_GPL(l2tp_session_find_nth);
304 
305 /* Lookup a session by interface name.
306  * This is very inefficient but is only used by management interfaces.
307  */
308 struct l2tp_session *l2tp_session_find_by_ifname(struct net *net, char *ifname)
309 {
310 	struct l2tp_net *pn = l2tp_pernet(net);
311 	int hash;
312 	struct l2tp_session *session;
313 
314 	rcu_read_lock_bh();
315 	for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++) {
316 		hlist_for_each_entry_rcu(session, &pn->l2tp_session_hlist[hash], global_hlist) {
317 			if (!strcmp(session->ifname, ifname)) {
318 				rcu_read_unlock_bh();
319 				return session;
320 			}
321 		}
322 	}
323 
324 	rcu_read_unlock_bh();
325 
326 	return NULL;
327 }
328 EXPORT_SYMBOL_GPL(l2tp_session_find_by_ifname);
329 
330 /* Lookup a tunnel by id
331  */
332 struct l2tp_tunnel *l2tp_tunnel_find(struct net *net, u32 tunnel_id)
333 {
334 	struct l2tp_tunnel *tunnel;
335 	struct l2tp_net *pn = l2tp_pernet(net);
336 
337 	rcu_read_lock_bh();
338 	list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
339 		if (tunnel->tunnel_id == tunnel_id) {
340 			rcu_read_unlock_bh();
341 			return tunnel;
342 		}
343 	}
344 	rcu_read_unlock_bh();
345 
346 	return NULL;
347 }
348 EXPORT_SYMBOL_GPL(l2tp_tunnel_find);
349 
350 struct l2tp_tunnel *l2tp_tunnel_find_nth(struct net *net, int nth)
351 {
352 	struct l2tp_net *pn = l2tp_pernet(net);
353 	struct l2tp_tunnel *tunnel;
354 	int count = 0;
355 
356 	rcu_read_lock_bh();
357 	list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
358 		if (++count > nth) {
359 			rcu_read_unlock_bh();
360 			return tunnel;
361 		}
362 	}
363 
364 	rcu_read_unlock_bh();
365 
366 	return NULL;
367 }
368 EXPORT_SYMBOL_GPL(l2tp_tunnel_find_nth);
369 
370 /*****************************************************************************
371  * Receive data handling
372  *****************************************************************************/
373 
374 /* Queue a skb in order. We come here only if the skb has an L2TP sequence
375  * number.
376  */
377 static void l2tp_recv_queue_skb(struct l2tp_session *session, struct sk_buff *skb)
378 {
379 	struct sk_buff *skbp;
380 	struct sk_buff *tmp;
381 	u32 ns = L2TP_SKB_CB(skb)->ns;
382 
383 	spin_lock_bh(&session->reorder_q.lock);
384 	skb_queue_walk_safe(&session->reorder_q, skbp, tmp) {
385 		if (L2TP_SKB_CB(skbp)->ns > ns) {
386 			__skb_queue_before(&session->reorder_q, skbp, skb);
387 			l2tp_dbg(session, L2TP_MSG_SEQ,
388 				 "%s: pkt %hu, inserted before %hu, reorder_q len=%d\n",
389 				 session->name, ns, L2TP_SKB_CB(skbp)->ns,
390 				 skb_queue_len(&session->reorder_q));
391 			atomic_long_inc(&session->stats.rx_oos_packets);
392 			goto out;
393 		}
394 	}
395 
396 	__skb_queue_tail(&session->reorder_q, skb);
397 
398 out:
399 	spin_unlock_bh(&session->reorder_q.lock);
400 }
401 
402 /* Dequeue a single skb.
403  */
404 static void l2tp_recv_dequeue_skb(struct l2tp_session *session, struct sk_buff *skb)
405 {
406 	struct l2tp_tunnel *tunnel = session->tunnel;
407 	int length = L2TP_SKB_CB(skb)->length;
408 
409 	/* We're about to requeue the skb, so return resources
410 	 * to its current owner (a socket receive buffer).
411 	 */
412 	skb_orphan(skb);
413 
414 	atomic_long_inc(&tunnel->stats.rx_packets);
415 	atomic_long_add(length, &tunnel->stats.rx_bytes);
416 	atomic_long_inc(&session->stats.rx_packets);
417 	atomic_long_add(length, &session->stats.rx_bytes);
418 
419 	if (L2TP_SKB_CB(skb)->has_seq) {
420 		/* Bump our Nr */
421 		session->nr++;
422 		session->nr &= session->nr_max;
423 
424 		l2tp_dbg(session, L2TP_MSG_SEQ, "%s: updated nr to %hu\n",
425 			 session->name, session->nr);
426 	}
427 
428 	/* call private receive handler */
429 	if (session->recv_skb != NULL)
430 		(*session->recv_skb)(session, skb, L2TP_SKB_CB(skb)->length);
431 	else
432 		kfree_skb(skb);
433 
434 	if (session->deref)
435 		(*session->deref)(session);
436 }
437 
438 /* Dequeue skbs from the session's reorder_q, subject to packet order.
439  * Skbs that have been in the queue for too long are simply discarded.
440  */
441 static void l2tp_recv_dequeue(struct l2tp_session *session)
442 {
443 	struct sk_buff *skb;
444 	struct sk_buff *tmp;
445 
446 	/* If the pkt at the head of the queue has the nr that we
447 	 * expect to send up next, dequeue it and any other
448 	 * in-sequence packets behind it.
449 	 */
450 start:
451 	spin_lock_bh(&session->reorder_q.lock);
452 	skb_queue_walk_safe(&session->reorder_q, skb, tmp) {
453 		if (time_after(jiffies, L2TP_SKB_CB(skb)->expires)) {
454 			atomic_long_inc(&session->stats.rx_seq_discards);
455 			atomic_long_inc(&session->stats.rx_errors);
456 			l2tp_dbg(session, L2TP_MSG_SEQ,
457 				 "%s: oos pkt %u len %d discarded (too old), waiting for %u, reorder_q_len=%d\n",
458 				 session->name, L2TP_SKB_CB(skb)->ns,
459 				 L2TP_SKB_CB(skb)->length, session->nr,
460 				 skb_queue_len(&session->reorder_q));
461 			session->reorder_skip = 1;
462 			__skb_unlink(skb, &session->reorder_q);
463 			kfree_skb(skb);
464 			if (session->deref)
465 				(*session->deref)(session);
466 			continue;
467 		}
468 
469 		if (L2TP_SKB_CB(skb)->has_seq) {
470 			if (session->reorder_skip) {
471 				l2tp_dbg(session, L2TP_MSG_SEQ,
472 					 "%s: advancing nr to next pkt: %u -> %u",
473 					 session->name, session->nr,
474 					 L2TP_SKB_CB(skb)->ns);
475 				session->reorder_skip = 0;
476 				session->nr = L2TP_SKB_CB(skb)->ns;
477 			}
478 			if (L2TP_SKB_CB(skb)->ns != session->nr) {
479 				l2tp_dbg(session, L2TP_MSG_SEQ,
480 					 "%s: holding oos pkt %u len %d, waiting for %u, reorder_q_len=%d\n",
481 					 session->name, L2TP_SKB_CB(skb)->ns,
482 					 L2TP_SKB_CB(skb)->length, session->nr,
483 					 skb_queue_len(&session->reorder_q));
484 				goto out;
485 			}
486 		}
487 		__skb_unlink(skb, &session->reorder_q);
488 
489 		/* Process the skb. We release the queue lock while we
490 		 * do so to let other contexts process the queue.
491 		 */
492 		spin_unlock_bh(&session->reorder_q.lock);
493 		l2tp_recv_dequeue_skb(session, skb);
494 		goto start;
495 	}
496 
497 out:
498 	spin_unlock_bh(&session->reorder_q.lock);
499 }
500 
501 static inline int l2tp_verify_udp_checksum(struct sock *sk,
502 					   struct sk_buff *skb)
503 {
504 	struct udphdr *uh = udp_hdr(skb);
505 	u16 ulen = ntohs(uh->len);
506 	__wsum psum;
507 
508 	if (sk->sk_no_check || skb_csum_unnecessary(skb))
509 		return 0;
510 
511 #if IS_ENABLED(CONFIG_IPV6)
512 	if (sk->sk_family == PF_INET6 && !l2tp_tunnel(sk)->v4mapped) {
513 		if (!uh->check) {
514 			LIMIT_NETDEBUG(KERN_INFO "L2TP: IPv6: checksum is 0\n");
515 			return 1;
516 		}
517 		if ((skb->ip_summed == CHECKSUM_COMPLETE) &&
518 		    !csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
519 				     &ipv6_hdr(skb)->daddr, ulen,
520 				     IPPROTO_UDP, skb->csum)) {
521 			skb->ip_summed = CHECKSUM_UNNECESSARY;
522 			return 0;
523 		}
524 		skb->csum = ~csum_unfold(csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
525 							 &ipv6_hdr(skb)->daddr,
526 							 skb->len, IPPROTO_UDP,
527 							 0));
528 	} else
529 #endif
530 	{
531 		struct inet_sock *inet;
532 		if (!uh->check)
533 			return 0;
534 		inet = inet_sk(sk);
535 		psum = csum_tcpudp_nofold(inet->inet_saddr, inet->inet_daddr,
536 					  ulen, IPPROTO_UDP, 0);
537 
538 		if ((skb->ip_summed == CHECKSUM_COMPLETE) &&
539 		    !csum_fold(csum_add(psum, skb->csum)))
540 			return 0;
541 		skb->csum = psum;
542 	}
543 
544 	return __skb_checksum_complete(skb);
545 }
546 
547 static int l2tp_seq_check_rx_window(struct l2tp_session *session, u32 nr)
548 {
549 	u32 nws;
550 
551 	if (nr >= session->nr)
552 		nws = nr - session->nr;
553 	else
554 		nws = (session->nr_max + 1) - (session->nr - nr);
555 
556 	return nws < session->nr_window_size;
557 }
558 
559 /* If packet has sequence numbers, queue it if acceptable. Returns 0 if
560  * acceptable, else non-zero.
561  */
562 static int l2tp_recv_data_seq(struct l2tp_session *session, struct sk_buff *skb)
563 {
564 	if (!l2tp_seq_check_rx_window(session, L2TP_SKB_CB(skb)->ns)) {
565 		/* Packet sequence number is outside allowed window.
566 		 * Discard it.
567 		 */
568 		l2tp_dbg(session, L2TP_MSG_SEQ,
569 			 "%s: pkt %u len %d discarded, outside window, nr=%u\n",
570 			 session->name, L2TP_SKB_CB(skb)->ns,
571 			 L2TP_SKB_CB(skb)->length, session->nr);
572 		goto discard;
573 	}
574 
575 	if (session->reorder_timeout != 0) {
576 		/* Packet reordering enabled. Add skb to session's
577 		 * reorder queue, in order of ns.
578 		 */
579 		l2tp_recv_queue_skb(session, skb);
580 		goto out;
581 	}
582 
583 	/* Packet reordering disabled. Discard out-of-sequence packets, while
584 	 * tracking the number if in-sequence packets after the first OOS packet
585 	 * is seen. After nr_oos_count_max in-sequence packets, reset the
586 	 * sequence number to re-enable packet reception.
587 	 */
588 	if (L2TP_SKB_CB(skb)->ns == session->nr) {
589 		skb_queue_tail(&session->reorder_q, skb);
590 	} else {
591 		u32 nr_oos = L2TP_SKB_CB(skb)->ns;
592 		u32 nr_next = (session->nr_oos + 1) & session->nr_max;
593 
594 		if (nr_oos == nr_next)
595 			session->nr_oos_count++;
596 		else
597 			session->nr_oos_count = 0;
598 
599 		session->nr_oos = nr_oos;
600 		if (session->nr_oos_count > session->nr_oos_count_max) {
601 			session->reorder_skip = 1;
602 			l2tp_dbg(session, L2TP_MSG_SEQ,
603 				 "%s: %d oos packets received. Resetting sequence numbers\n",
604 				 session->name, session->nr_oos_count);
605 		}
606 		if (!session->reorder_skip) {
607 			atomic_long_inc(&session->stats.rx_seq_discards);
608 			l2tp_dbg(session, L2TP_MSG_SEQ,
609 				 "%s: oos pkt %u len %d discarded, waiting for %u, reorder_q_len=%d\n",
610 				 session->name, L2TP_SKB_CB(skb)->ns,
611 				 L2TP_SKB_CB(skb)->length, session->nr,
612 				 skb_queue_len(&session->reorder_q));
613 			goto discard;
614 		}
615 		skb_queue_tail(&session->reorder_q, skb);
616 	}
617 
618 out:
619 	return 0;
620 
621 discard:
622 	return 1;
623 }
624 
625 /* Do receive processing of L2TP data frames. We handle both L2TPv2
626  * and L2TPv3 data frames here.
627  *
628  * L2TPv2 Data Message Header
629  *
630  *  0                   1                   2                   3
631  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
632  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
633  * |T|L|x|x|S|x|O|P|x|x|x|x|  Ver  |          Length (opt)         |
634  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
635  * |           Tunnel ID           |           Session ID          |
636  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
637  * |             Ns (opt)          |             Nr (opt)          |
638  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
639  * |      Offset Size (opt)        |    Offset pad... (opt)
640  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
641  *
642  * Data frames are marked by T=0. All other fields are the same as
643  * those in L2TP control frames.
644  *
645  * L2TPv3 Data Message Header
646  *
647  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
648  * |                      L2TP Session Header                      |
649  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
650  * |                      L2-Specific Sublayer                     |
651  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
652  * |                        Tunnel Payload                      ...
653  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
654  *
655  * L2TPv3 Session Header Over IP
656  *
657  *  0                   1                   2                   3
658  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
659  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
660  * |                           Session ID                          |
661  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
662  * |               Cookie (optional, maximum 64 bits)...
663  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
664  *                                                                 |
665  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
666  *
667  * L2TPv3 L2-Specific Sublayer Format
668  *
669  *  0                   1                   2                   3
670  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
671  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
672  * |x|S|x|x|x|x|x|x|              Sequence Number                  |
673  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
674  *
675  * Cookie value, sublayer format and offset (pad) are negotiated with
676  * the peer when the session is set up. Unlike L2TPv2, we do not need
677  * to parse the packet header to determine if optional fields are
678  * present.
679  *
680  * Caller must already have parsed the frame and determined that it is
681  * a data (not control) frame before coming here. Fields up to the
682  * session-id have already been parsed and ptr points to the data
683  * after the session-id.
684  */
685 void l2tp_recv_common(struct l2tp_session *session, struct sk_buff *skb,
686 		      unsigned char *ptr, unsigned char *optr, u16 hdrflags,
687 		      int length, int (*payload_hook)(struct sk_buff *skb))
688 {
689 	struct l2tp_tunnel *tunnel = session->tunnel;
690 	int offset;
691 	u32 ns, nr;
692 
693 	/* The ref count is increased since we now hold a pointer to
694 	 * the session. Take care to decrement the refcnt when exiting
695 	 * this function from now on...
696 	 */
697 	l2tp_session_inc_refcount(session);
698 	if (session->ref)
699 		(*session->ref)(session);
700 
701 	/* Parse and check optional cookie */
702 	if (session->peer_cookie_len > 0) {
703 		if (memcmp(ptr, &session->peer_cookie[0], session->peer_cookie_len)) {
704 			l2tp_info(tunnel, L2TP_MSG_DATA,
705 				  "%s: cookie mismatch (%u/%u). Discarding.\n",
706 				  tunnel->name, tunnel->tunnel_id,
707 				  session->session_id);
708 			atomic_long_inc(&session->stats.rx_cookie_discards);
709 			goto discard;
710 		}
711 		ptr += session->peer_cookie_len;
712 	}
713 
714 	/* Handle the optional sequence numbers. Sequence numbers are
715 	 * in different places for L2TPv2 and L2TPv3.
716 	 *
717 	 * If we are the LAC, enable/disable sequence numbers under
718 	 * the control of the LNS.  If no sequence numbers present but
719 	 * we were expecting them, discard frame.
720 	 */
721 	ns = nr = 0;
722 	L2TP_SKB_CB(skb)->has_seq = 0;
723 	if (tunnel->version == L2TP_HDR_VER_2) {
724 		if (hdrflags & L2TP_HDRFLAG_S) {
725 			ns = ntohs(*(__be16 *) ptr);
726 			ptr += 2;
727 			nr = ntohs(*(__be16 *) ptr);
728 			ptr += 2;
729 
730 			/* Store L2TP info in the skb */
731 			L2TP_SKB_CB(skb)->ns = ns;
732 			L2TP_SKB_CB(skb)->has_seq = 1;
733 
734 			l2tp_dbg(session, L2TP_MSG_SEQ,
735 				 "%s: recv data ns=%u, nr=%u, session nr=%u\n",
736 				 session->name, ns, nr, session->nr);
737 		}
738 	} else if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
739 		u32 l2h = ntohl(*(__be32 *) ptr);
740 
741 		if (l2h & 0x40000000) {
742 			ns = l2h & 0x00ffffff;
743 
744 			/* Store L2TP info in the skb */
745 			L2TP_SKB_CB(skb)->ns = ns;
746 			L2TP_SKB_CB(skb)->has_seq = 1;
747 
748 			l2tp_dbg(session, L2TP_MSG_SEQ,
749 				 "%s: recv data ns=%u, session nr=%u\n",
750 				 session->name, ns, session->nr);
751 		}
752 	}
753 
754 	/* Advance past L2-specific header, if present */
755 	ptr += session->l2specific_len;
756 
757 	if (L2TP_SKB_CB(skb)->has_seq) {
758 		/* Received a packet with sequence numbers. If we're the LNS,
759 		 * check if we sre sending sequence numbers and if not,
760 		 * configure it so.
761 		 */
762 		if ((!session->lns_mode) && (!session->send_seq)) {
763 			l2tp_info(session, L2TP_MSG_SEQ,
764 				  "%s: requested to enable seq numbers by LNS\n",
765 				  session->name);
766 			session->send_seq = -1;
767 			l2tp_session_set_header_len(session, tunnel->version);
768 		}
769 	} else {
770 		/* No sequence numbers.
771 		 * If user has configured mandatory sequence numbers, discard.
772 		 */
773 		if (session->recv_seq) {
774 			l2tp_warn(session, L2TP_MSG_SEQ,
775 				  "%s: recv data has no seq numbers when required. Discarding.\n",
776 				  session->name);
777 			atomic_long_inc(&session->stats.rx_seq_discards);
778 			goto discard;
779 		}
780 
781 		/* If we're the LAC and we're sending sequence numbers, the
782 		 * LNS has requested that we no longer send sequence numbers.
783 		 * If we're the LNS and we're sending sequence numbers, the
784 		 * LAC is broken. Discard the frame.
785 		 */
786 		if ((!session->lns_mode) && (session->send_seq)) {
787 			l2tp_info(session, L2TP_MSG_SEQ,
788 				  "%s: requested to disable seq numbers by LNS\n",
789 				  session->name);
790 			session->send_seq = 0;
791 			l2tp_session_set_header_len(session, tunnel->version);
792 		} else if (session->send_seq) {
793 			l2tp_warn(session, L2TP_MSG_SEQ,
794 				  "%s: recv data has no seq numbers when required. Discarding.\n",
795 				  session->name);
796 			atomic_long_inc(&session->stats.rx_seq_discards);
797 			goto discard;
798 		}
799 	}
800 
801 	/* Session data offset is handled differently for L2TPv2 and
802 	 * L2TPv3. For L2TPv2, there is an optional 16-bit value in
803 	 * the header. For L2TPv3, the offset is negotiated using AVPs
804 	 * in the session setup control protocol.
805 	 */
806 	if (tunnel->version == L2TP_HDR_VER_2) {
807 		/* If offset bit set, skip it. */
808 		if (hdrflags & L2TP_HDRFLAG_O) {
809 			offset = ntohs(*(__be16 *)ptr);
810 			ptr += 2 + offset;
811 		}
812 	} else
813 		ptr += session->offset;
814 
815 	offset = ptr - optr;
816 	if (!pskb_may_pull(skb, offset))
817 		goto discard;
818 
819 	__skb_pull(skb, offset);
820 
821 	/* If caller wants to process the payload before we queue the
822 	 * packet, do so now.
823 	 */
824 	if (payload_hook)
825 		if ((*payload_hook)(skb))
826 			goto discard;
827 
828 	/* Prepare skb for adding to the session's reorder_q.  Hold
829 	 * packets for max reorder_timeout or 1 second if not
830 	 * reordering.
831 	 */
832 	L2TP_SKB_CB(skb)->length = length;
833 	L2TP_SKB_CB(skb)->expires = jiffies +
834 		(session->reorder_timeout ? session->reorder_timeout : HZ);
835 
836 	/* Add packet to the session's receive queue. Reordering is done here, if
837 	 * enabled. Saved L2TP protocol info is stored in skb->sb[].
838 	 */
839 	if (L2TP_SKB_CB(skb)->has_seq) {
840 		if (l2tp_recv_data_seq(session, skb))
841 			goto discard;
842 	} else {
843 		/* No sequence numbers. Add the skb to the tail of the
844 		 * reorder queue. This ensures that it will be
845 		 * delivered after all previous sequenced skbs.
846 		 */
847 		skb_queue_tail(&session->reorder_q, skb);
848 	}
849 
850 	/* Try to dequeue as many skbs from reorder_q as we can. */
851 	l2tp_recv_dequeue(session);
852 
853 	l2tp_session_dec_refcount(session);
854 
855 	return;
856 
857 discard:
858 	atomic_long_inc(&session->stats.rx_errors);
859 	kfree_skb(skb);
860 
861 	if (session->deref)
862 		(*session->deref)(session);
863 
864 	l2tp_session_dec_refcount(session);
865 }
866 EXPORT_SYMBOL(l2tp_recv_common);
867 
868 /* Drop skbs from the session's reorder_q
869  */
870 int l2tp_session_queue_purge(struct l2tp_session *session)
871 {
872 	struct sk_buff *skb = NULL;
873 	BUG_ON(!session);
874 	BUG_ON(session->magic != L2TP_SESSION_MAGIC);
875 	while ((skb = skb_dequeue(&session->reorder_q))) {
876 		atomic_long_inc(&session->stats.rx_errors);
877 		kfree_skb(skb);
878 		if (session->deref)
879 			(*session->deref)(session);
880 	}
881 	return 0;
882 }
883 EXPORT_SYMBOL_GPL(l2tp_session_queue_purge);
884 
885 /* Internal UDP receive frame. Do the real work of receiving an L2TP data frame
886  * here. The skb is not on a list when we get here.
887  * Returns 0 if the packet was a data packet and was successfully passed on.
888  * Returns 1 if the packet was not a good data packet and could not be
889  * forwarded.  All such packets are passed up to userspace to deal with.
890  */
891 static int l2tp_udp_recv_core(struct l2tp_tunnel *tunnel, struct sk_buff *skb,
892 			      int (*payload_hook)(struct sk_buff *skb))
893 {
894 	struct l2tp_session *session = NULL;
895 	unsigned char *ptr, *optr;
896 	u16 hdrflags;
897 	u32 tunnel_id, session_id;
898 	u16 version;
899 	int length;
900 
901 	if (tunnel->sock && l2tp_verify_udp_checksum(tunnel->sock, skb))
902 		goto discard_bad_csum;
903 
904 	/* UDP always verifies the packet length. */
905 	__skb_pull(skb, sizeof(struct udphdr));
906 
907 	/* Short packet? */
908 	if (!pskb_may_pull(skb, L2TP_HDR_SIZE_SEQ)) {
909 		l2tp_info(tunnel, L2TP_MSG_DATA,
910 			  "%s: recv short packet (len=%d)\n",
911 			  tunnel->name, skb->len);
912 		goto error;
913 	}
914 
915 	/* Trace packet contents, if enabled */
916 	if (tunnel->debug & L2TP_MSG_DATA) {
917 		length = min(32u, skb->len);
918 		if (!pskb_may_pull(skb, length))
919 			goto error;
920 
921 		pr_debug("%s: recv\n", tunnel->name);
922 		print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, skb->data, length);
923 	}
924 
925 	/* Point to L2TP header */
926 	optr = ptr = skb->data;
927 
928 	/* Get L2TP header flags */
929 	hdrflags = ntohs(*(__be16 *) ptr);
930 
931 	/* Check protocol version */
932 	version = hdrflags & L2TP_HDR_VER_MASK;
933 	if (version != tunnel->version) {
934 		l2tp_info(tunnel, L2TP_MSG_DATA,
935 			  "%s: recv protocol version mismatch: got %d expected %d\n",
936 			  tunnel->name, version, tunnel->version);
937 		goto error;
938 	}
939 
940 	/* Get length of L2TP packet */
941 	length = skb->len;
942 
943 	/* If type is control packet, it is handled by userspace. */
944 	if (hdrflags & L2TP_HDRFLAG_T) {
945 		l2tp_dbg(tunnel, L2TP_MSG_DATA,
946 			 "%s: recv control packet, len=%d\n",
947 			 tunnel->name, length);
948 		goto error;
949 	}
950 
951 	/* Skip flags */
952 	ptr += 2;
953 
954 	if (tunnel->version == L2TP_HDR_VER_2) {
955 		/* If length is present, skip it */
956 		if (hdrflags & L2TP_HDRFLAG_L)
957 			ptr += 2;
958 
959 		/* Extract tunnel and session ID */
960 		tunnel_id = ntohs(*(__be16 *) ptr);
961 		ptr += 2;
962 		session_id = ntohs(*(__be16 *) ptr);
963 		ptr += 2;
964 	} else {
965 		ptr += 2;	/* skip reserved bits */
966 		tunnel_id = tunnel->tunnel_id;
967 		session_id = ntohl(*(__be32 *) ptr);
968 		ptr += 4;
969 	}
970 
971 	/* Find the session context */
972 	session = l2tp_session_find(tunnel->l2tp_net, tunnel, session_id);
973 	if (!session || !session->recv_skb) {
974 		/* Not found? Pass to userspace to deal with */
975 		l2tp_info(tunnel, L2TP_MSG_DATA,
976 			  "%s: no session found (%u/%u). Passing up.\n",
977 			  tunnel->name, tunnel_id, session_id);
978 		goto error;
979 	}
980 
981 	l2tp_recv_common(session, skb, ptr, optr, hdrflags, length, payload_hook);
982 
983 	return 0;
984 
985 discard_bad_csum:
986 	LIMIT_NETDEBUG("%s: UDP: bad checksum\n", tunnel->name);
987 	UDP_INC_STATS_USER(tunnel->l2tp_net, UDP_MIB_INERRORS, 0);
988 	atomic_long_inc(&tunnel->stats.rx_errors);
989 	kfree_skb(skb);
990 
991 	return 0;
992 
993 error:
994 	/* Put UDP header back */
995 	__skb_push(skb, sizeof(struct udphdr));
996 
997 	return 1;
998 }
999 
1000 /* UDP encapsulation receive handler. See net/ipv4/udp.c.
1001  * Return codes:
1002  * 0 : success.
1003  * <0: error
1004  * >0: skb should be passed up to userspace as UDP.
1005  */
1006 int l2tp_udp_encap_recv(struct sock *sk, struct sk_buff *skb)
1007 {
1008 	struct l2tp_tunnel *tunnel;
1009 
1010 	tunnel = l2tp_sock_to_tunnel(sk);
1011 	if (tunnel == NULL)
1012 		goto pass_up;
1013 
1014 	l2tp_dbg(tunnel, L2TP_MSG_DATA, "%s: received %d bytes\n",
1015 		 tunnel->name, skb->len);
1016 
1017 	if (l2tp_udp_recv_core(tunnel, skb, tunnel->recv_payload_hook))
1018 		goto pass_up_put;
1019 
1020 	sock_put(sk);
1021 	return 0;
1022 
1023 pass_up_put:
1024 	sock_put(sk);
1025 pass_up:
1026 	return 1;
1027 }
1028 EXPORT_SYMBOL_GPL(l2tp_udp_encap_recv);
1029 
1030 /************************************************************************
1031  * Transmit handling
1032  ***********************************************************************/
1033 
1034 /* Build an L2TP header for the session into the buffer provided.
1035  */
1036 static int l2tp_build_l2tpv2_header(struct l2tp_session *session, void *buf)
1037 {
1038 	struct l2tp_tunnel *tunnel = session->tunnel;
1039 	__be16 *bufp = buf;
1040 	__be16 *optr = buf;
1041 	u16 flags = L2TP_HDR_VER_2;
1042 	u32 tunnel_id = tunnel->peer_tunnel_id;
1043 	u32 session_id = session->peer_session_id;
1044 
1045 	if (session->send_seq)
1046 		flags |= L2TP_HDRFLAG_S;
1047 
1048 	/* Setup L2TP header. */
1049 	*bufp++ = htons(flags);
1050 	*bufp++ = htons(tunnel_id);
1051 	*bufp++ = htons(session_id);
1052 	if (session->send_seq) {
1053 		*bufp++ = htons(session->ns);
1054 		*bufp++ = 0;
1055 		session->ns++;
1056 		session->ns &= 0xffff;
1057 		l2tp_dbg(session, L2TP_MSG_SEQ, "%s: updated ns to %u\n",
1058 			 session->name, session->ns);
1059 	}
1060 
1061 	return bufp - optr;
1062 }
1063 
1064 static int l2tp_build_l2tpv3_header(struct l2tp_session *session, void *buf)
1065 {
1066 	struct l2tp_tunnel *tunnel = session->tunnel;
1067 	char *bufp = buf;
1068 	char *optr = bufp;
1069 
1070 	/* Setup L2TP header. The header differs slightly for UDP and
1071 	 * IP encapsulations. For UDP, there is 4 bytes of flags.
1072 	 */
1073 	if (tunnel->encap == L2TP_ENCAPTYPE_UDP) {
1074 		u16 flags = L2TP_HDR_VER_3;
1075 		*((__be16 *) bufp) = htons(flags);
1076 		bufp += 2;
1077 		*((__be16 *) bufp) = 0;
1078 		bufp += 2;
1079 	}
1080 
1081 	*((__be32 *) bufp) = htonl(session->peer_session_id);
1082 	bufp += 4;
1083 	if (session->cookie_len) {
1084 		memcpy(bufp, &session->cookie[0], session->cookie_len);
1085 		bufp += session->cookie_len;
1086 	}
1087 	if (session->l2specific_len) {
1088 		if (session->l2specific_type == L2TP_L2SPECTYPE_DEFAULT) {
1089 			u32 l2h = 0;
1090 			if (session->send_seq) {
1091 				l2h = 0x40000000 | session->ns;
1092 				session->ns++;
1093 				session->ns &= 0xffffff;
1094 				l2tp_dbg(session, L2TP_MSG_SEQ,
1095 					 "%s: updated ns to %u\n",
1096 					 session->name, session->ns);
1097 			}
1098 
1099 			*((__be32 *) bufp) = htonl(l2h);
1100 		}
1101 		bufp += session->l2specific_len;
1102 	}
1103 	if (session->offset)
1104 		bufp += session->offset;
1105 
1106 	return bufp - optr;
1107 }
1108 
1109 static int l2tp_xmit_core(struct l2tp_session *session, struct sk_buff *skb,
1110 			  struct flowi *fl, size_t data_len)
1111 {
1112 	struct l2tp_tunnel *tunnel = session->tunnel;
1113 	unsigned int len = skb->len;
1114 	int error;
1115 
1116 	/* Debug */
1117 	if (session->send_seq)
1118 		l2tp_dbg(session, L2TP_MSG_DATA, "%s: send %Zd bytes, ns=%u\n",
1119 			 session->name, data_len, session->ns - 1);
1120 	else
1121 		l2tp_dbg(session, L2TP_MSG_DATA, "%s: send %Zd bytes\n",
1122 			 session->name, data_len);
1123 
1124 	if (session->debug & L2TP_MSG_DATA) {
1125 		int uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
1126 		unsigned char *datap = skb->data + uhlen;
1127 
1128 		pr_debug("%s: xmit\n", session->name);
1129 		print_hex_dump_bytes("", DUMP_PREFIX_OFFSET,
1130 				     datap, min_t(size_t, 32, len - uhlen));
1131 	}
1132 
1133 	/* Queue the packet to IP for output */
1134 	skb->local_df = 1;
1135 #if IS_ENABLED(CONFIG_IPV6)
1136 	if (skb->sk->sk_family == PF_INET6 && !tunnel->v4mapped)
1137 		error = inet6_csk_xmit(skb, NULL);
1138 	else
1139 #endif
1140 		error = ip_queue_xmit(skb, fl);
1141 
1142 	/* Update stats */
1143 	if (error >= 0) {
1144 		atomic_long_inc(&tunnel->stats.tx_packets);
1145 		atomic_long_add(len, &tunnel->stats.tx_bytes);
1146 		atomic_long_inc(&session->stats.tx_packets);
1147 		atomic_long_add(len, &session->stats.tx_bytes);
1148 	} else {
1149 		atomic_long_inc(&tunnel->stats.tx_errors);
1150 		atomic_long_inc(&session->stats.tx_errors);
1151 	}
1152 
1153 	return 0;
1154 }
1155 
1156 /* Automatically called when the skb is freed.
1157  */
1158 static void l2tp_sock_wfree(struct sk_buff *skb)
1159 {
1160 	sock_put(skb->sk);
1161 }
1162 
1163 /* For data skbs that we transmit, we associate with the tunnel socket
1164  * but don't do accounting.
1165  */
1166 static inline void l2tp_skb_set_owner_w(struct sk_buff *skb, struct sock *sk)
1167 {
1168 	sock_hold(sk);
1169 	skb->sk = sk;
1170 	skb->destructor = l2tp_sock_wfree;
1171 }
1172 
1173 #if IS_ENABLED(CONFIG_IPV6)
1174 static void l2tp_xmit_ipv6_csum(struct sock *sk, struct sk_buff *skb,
1175 				int udp_len)
1176 {
1177 	struct ipv6_pinfo *np = inet6_sk(sk);
1178 	struct udphdr *uh = udp_hdr(skb);
1179 
1180 	if (!skb_dst(skb) || !skb_dst(skb)->dev ||
1181 	    !(skb_dst(skb)->dev->features & NETIF_F_IPV6_CSUM)) {
1182 		__wsum csum = skb_checksum(skb, 0, udp_len, 0);
1183 		skb->ip_summed = CHECKSUM_UNNECESSARY;
1184 		uh->check = csum_ipv6_magic(&np->saddr, &np->daddr, udp_len,
1185 					    IPPROTO_UDP, csum);
1186 		if (uh->check == 0)
1187 			uh->check = CSUM_MANGLED_0;
1188 	} else {
1189 		skb->ip_summed = CHECKSUM_PARTIAL;
1190 		skb->csum_start = skb_transport_header(skb) - skb->head;
1191 		skb->csum_offset = offsetof(struct udphdr, check);
1192 		uh->check = ~csum_ipv6_magic(&np->saddr, &np->daddr,
1193 					     udp_len, IPPROTO_UDP, 0);
1194 	}
1195 }
1196 #endif
1197 
1198 /* If caller requires the skb to have a ppp header, the header must be
1199  * inserted in the skb data before calling this function.
1200  */
1201 int l2tp_xmit_skb(struct l2tp_session *session, struct sk_buff *skb, int hdr_len)
1202 {
1203 	int data_len = skb->len;
1204 	struct l2tp_tunnel *tunnel = session->tunnel;
1205 	struct sock *sk = tunnel->sock;
1206 	struct flowi *fl;
1207 	struct udphdr *uh;
1208 	struct inet_sock *inet;
1209 	__wsum csum;
1210 	int headroom;
1211 	int uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
1212 	int udp_len;
1213 	int ret = NET_XMIT_SUCCESS;
1214 
1215 	/* Check that there's enough headroom in the skb to insert IP,
1216 	 * UDP and L2TP headers. If not enough, expand it to
1217 	 * make room. Adjust truesize.
1218 	 */
1219 	headroom = NET_SKB_PAD + sizeof(struct iphdr) +
1220 		uhlen + hdr_len;
1221 	if (skb_cow_head(skb, headroom)) {
1222 		kfree_skb(skb);
1223 		return NET_XMIT_DROP;
1224 	}
1225 
1226 	skb_orphan(skb);
1227 	/* Setup L2TP header */
1228 	session->build_header(session, __skb_push(skb, hdr_len));
1229 
1230 	/* Reset skb netfilter state */
1231 	memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
1232 	IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED |
1233 			      IPSKB_REROUTED);
1234 	nf_reset(skb);
1235 
1236 	bh_lock_sock(sk);
1237 	if (sock_owned_by_user(sk)) {
1238 		kfree_skb(skb);
1239 		ret = NET_XMIT_DROP;
1240 		goto out_unlock;
1241 	}
1242 
1243 	/* Get routing info from the tunnel socket */
1244 	skb_dst_drop(skb);
1245 	skb_dst_set(skb, dst_clone(__sk_dst_check(sk, 0)));
1246 
1247 	inet = inet_sk(sk);
1248 	fl = &inet->cork.fl;
1249 	switch (tunnel->encap) {
1250 	case L2TP_ENCAPTYPE_UDP:
1251 		/* Setup UDP header */
1252 		__skb_push(skb, sizeof(*uh));
1253 		skb_reset_transport_header(skb);
1254 		uh = udp_hdr(skb);
1255 		uh->source = inet->inet_sport;
1256 		uh->dest = inet->inet_dport;
1257 		udp_len = uhlen + hdr_len + data_len;
1258 		uh->len = htons(udp_len);
1259 		uh->check = 0;
1260 
1261 		/* Calculate UDP checksum if configured to do so */
1262 #if IS_ENABLED(CONFIG_IPV6)
1263 		if (sk->sk_family == PF_INET6 && !tunnel->v4mapped)
1264 			l2tp_xmit_ipv6_csum(sk, skb, udp_len);
1265 		else
1266 #endif
1267 		if (sk->sk_no_check == UDP_CSUM_NOXMIT)
1268 			skb->ip_summed = CHECKSUM_NONE;
1269 		else if ((skb_dst(skb) && skb_dst(skb)->dev) &&
1270 			 (!(skb_dst(skb)->dev->features & NETIF_F_V4_CSUM))) {
1271 			skb->ip_summed = CHECKSUM_COMPLETE;
1272 			csum = skb_checksum(skb, 0, udp_len, 0);
1273 			uh->check = csum_tcpudp_magic(inet->inet_saddr,
1274 						      inet->inet_daddr,
1275 						      udp_len, IPPROTO_UDP, csum);
1276 			if (uh->check == 0)
1277 				uh->check = CSUM_MANGLED_0;
1278 		} else {
1279 			skb->ip_summed = CHECKSUM_PARTIAL;
1280 			skb->csum_start = skb_transport_header(skb) - skb->head;
1281 			skb->csum_offset = offsetof(struct udphdr, check);
1282 			uh->check = ~csum_tcpudp_magic(inet->inet_saddr,
1283 						       inet->inet_daddr,
1284 						       udp_len, IPPROTO_UDP, 0);
1285 		}
1286 		break;
1287 
1288 	case L2TP_ENCAPTYPE_IP:
1289 		break;
1290 	}
1291 
1292 	l2tp_skb_set_owner_w(skb, sk);
1293 
1294 	l2tp_xmit_core(session, skb, fl, data_len);
1295 out_unlock:
1296 	bh_unlock_sock(sk);
1297 
1298 	return ret;
1299 }
1300 EXPORT_SYMBOL_GPL(l2tp_xmit_skb);
1301 
1302 /*****************************************************************************
1303  * Tinnel and session create/destroy.
1304  *****************************************************************************/
1305 
1306 /* Tunnel socket destruct hook.
1307  * The tunnel context is deleted only when all session sockets have been
1308  * closed.
1309  */
1310 static void l2tp_tunnel_destruct(struct sock *sk)
1311 {
1312 	struct l2tp_tunnel *tunnel = l2tp_tunnel(sk);
1313 	struct l2tp_net *pn;
1314 
1315 	if (tunnel == NULL)
1316 		goto end;
1317 
1318 	l2tp_info(tunnel, L2TP_MSG_CONTROL, "%s: closing...\n", tunnel->name);
1319 
1320 
1321 	/* Disable udp encapsulation */
1322 	switch (tunnel->encap) {
1323 	case L2TP_ENCAPTYPE_UDP:
1324 		/* No longer an encapsulation socket. See net/ipv4/udp.c */
1325 		(udp_sk(sk))->encap_type = 0;
1326 		(udp_sk(sk))->encap_rcv = NULL;
1327 		(udp_sk(sk))->encap_destroy = NULL;
1328 		break;
1329 	case L2TP_ENCAPTYPE_IP:
1330 		break;
1331 	}
1332 
1333 	/* Remove hooks into tunnel socket */
1334 	sk->sk_destruct = tunnel->old_sk_destruct;
1335 	sk->sk_user_data = NULL;
1336 	tunnel->sock = NULL;
1337 
1338 	/* Remove the tunnel struct from the tunnel list */
1339 	pn = l2tp_pernet(tunnel->l2tp_net);
1340 	spin_lock_bh(&pn->l2tp_tunnel_list_lock);
1341 	list_del_rcu(&tunnel->list);
1342 	spin_unlock_bh(&pn->l2tp_tunnel_list_lock);
1343 	atomic_dec(&l2tp_tunnel_count);
1344 
1345 	l2tp_tunnel_closeall(tunnel);
1346 	l2tp_tunnel_dec_refcount(tunnel);
1347 
1348 	/* Call the original destructor */
1349 	if (sk->sk_destruct)
1350 		(*sk->sk_destruct)(sk);
1351 end:
1352 	return;
1353 }
1354 
1355 /* When the tunnel is closed, all the attached sessions need to go too.
1356  */
1357 void l2tp_tunnel_closeall(struct l2tp_tunnel *tunnel)
1358 {
1359 	int hash;
1360 	struct hlist_node *walk;
1361 	struct hlist_node *tmp;
1362 	struct l2tp_session *session;
1363 
1364 	BUG_ON(tunnel == NULL);
1365 
1366 	l2tp_info(tunnel, L2TP_MSG_CONTROL, "%s: closing all sessions...\n",
1367 		  tunnel->name);
1368 
1369 	write_lock_bh(&tunnel->hlist_lock);
1370 	for (hash = 0; hash < L2TP_HASH_SIZE; hash++) {
1371 again:
1372 		hlist_for_each_safe(walk, tmp, &tunnel->session_hlist[hash]) {
1373 			session = hlist_entry(walk, struct l2tp_session, hlist);
1374 
1375 			l2tp_info(session, L2TP_MSG_CONTROL,
1376 				  "%s: closing session\n", session->name);
1377 
1378 			hlist_del_init(&session->hlist);
1379 
1380 			if (session->ref != NULL)
1381 				(*session->ref)(session);
1382 
1383 			write_unlock_bh(&tunnel->hlist_lock);
1384 
1385 			__l2tp_session_unhash(session);
1386 			l2tp_session_queue_purge(session);
1387 
1388 			if (session->session_close != NULL)
1389 				(*session->session_close)(session);
1390 
1391 			if (session->deref != NULL)
1392 				(*session->deref)(session);
1393 
1394 			l2tp_session_dec_refcount(session);
1395 
1396 			write_lock_bh(&tunnel->hlist_lock);
1397 
1398 			/* Now restart from the beginning of this hash
1399 			 * chain.  We always remove a session from the
1400 			 * list so we are guaranteed to make forward
1401 			 * progress.
1402 			 */
1403 			goto again;
1404 		}
1405 	}
1406 	write_unlock_bh(&tunnel->hlist_lock);
1407 }
1408 EXPORT_SYMBOL_GPL(l2tp_tunnel_closeall);
1409 
1410 /* Tunnel socket destroy hook for UDP encapsulation */
1411 static void l2tp_udp_encap_destroy(struct sock *sk)
1412 {
1413 	struct l2tp_tunnel *tunnel = l2tp_sock_to_tunnel(sk);
1414 	if (tunnel) {
1415 		l2tp_tunnel_closeall(tunnel);
1416 		sock_put(sk);
1417 	}
1418 }
1419 
1420 /* Really kill the tunnel.
1421  * Come here only when all sessions have been cleared from the tunnel.
1422  */
1423 static void l2tp_tunnel_free(struct l2tp_tunnel *tunnel)
1424 {
1425 	BUG_ON(atomic_read(&tunnel->ref_count) != 0);
1426 	BUG_ON(tunnel->sock != NULL);
1427 	l2tp_info(tunnel, L2TP_MSG_CONTROL, "%s: free...\n", tunnel->name);
1428 	kfree_rcu(tunnel, rcu);
1429 }
1430 
1431 /* Workqueue tunnel deletion function */
1432 static void l2tp_tunnel_del_work(struct work_struct *work)
1433 {
1434 	struct l2tp_tunnel *tunnel = NULL;
1435 	struct socket *sock = NULL;
1436 	struct sock *sk = NULL;
1437 
1438 	tunnel = container_of(work, struct l2tp_tunnel, del_work);
1439 	sk = l2tp_tunnel_sock_lookup(tunnel);
1440 	if (!sk)
1441 		return;
1442 
1443 	sock = sk->sk_socket;
1444 
1445 	/* If the tunnel socket was created by userspace, then go through the
1446 	 * inet layer to shut the socket down, and let userspace close it.
1447 	 * Otherwise, if we created the socket directly within the kernel, use
1448 	 * the sk API to release it here.
1449 	 * In either case the tunnel resources are freed in the socket
1450 	 * destructor when the tunnel socket goes away.
1451 	 */
1452 	if (tunnel->fd >= 0) {
1453 		if (sock)
1454 			inet_shutdown(sock, 2);
1455 	} else {
1456 		if (sock)
1457 			kernel_sock_shutdown(sock, SHUT_RDWR);
1458 		sk_release_kernel(sk);
1459 	}
1460 
1461 	l2tp_tunnel_sock_put(sk);
1462 }
1463 
1464 /* Create a socket for the tunnel, if one isn't set up by
1465  * userspace. This is used for static tunnels where there is no
1466  * managing L2TP daemon.
1467  *
1468  * Since we don't want these sockets to keep a namespace alive by
1469  * themselves, we drop the socket's namespace refcount after creation.
1470  * These sockets are freed when the namespace exits using the pernet
1471  * exit hook.
1472  */
1473 static int l2tp_tunnel_sock_create(struct net *net,
1474 				u32 tunnel_id,
1475 				u32 peer_tunnel_id,
1476 				struct l2tp_tunnel_cfg *cfg,
1477 				struct socket **sockp)
1478 {
1479 	int err = -EINVAL;
1480 	struct socket *sock = NULL;
1481 	struct sockaddr_in udp_addr = {0};
1482 	struct sockaddr_l2tpip ip_addr = {0};
1483 #if IS_ENABLED(CONFIG_IPV6)
1484 	struct sockaddr_in6 udp6_addr = {0};
1485 	struct sockaddr_l2tpip6 ip6_addr = {0};
1486 #endif
1487 
1488 	switch (cfg->encap) {
1489 	case L2TP_ENCAPTYPE_UDP:
1490 #if IS_ENABLED(CONFIG_IPV6)
1491 		if (cfg->local_ip6 && cfg->peer_ip6) {
1492 			err = sock_create_kern(AF_INET6, SOCK_DGRAM, 0, &sock);
1493 			if (err < 0)
1494 				goto out;
1495 
1496 			sk_change_net(sock->sk, net);
1497 
1498 			udp6_addr.sin6_family = AF_INET6;
1499 			memcpy(&udp6_addr.sin6_addr, cfg->local_ip6,
1500 			       sizeof(udp6_addr.sin6_addr));
1501 			udp6_addr.sin6_port = htons(cfg->local_udp_port);
1502 			err = kernel_bind(sock, (struct sockaddr *) &udp6_addr,
1503 					  sizeof(udp6_addr));
1504 			if (err < 0)
1505 				goto out;
1506 
1507 			udp6_addr.sin6_family = AF_INET6;
1508 			memcpy(&udp6_addr.sin6_addr, cfg->peer_ip6,
1509 			       sizeof(udp6_addr.sin6_addr));
1510 			udp6_addr.sin6_port = htons(cfg->peer_udp_port);
1511 			err = kernel_connect(sock,
1512 					     (struct sockaddr *) &udp6_addr,
1513 					     sizeof(udp6_addr), 0);
1514 			if (err < 0)
1515 				goto out;
1516 		} else
1517 #endif
1518 		{
1519 			err = sock_create_kern(AF_INET, SOCK_DGRAM, 0, &sock);
1520 			if (err < 0)
1521 				goto out;
1522 
1523 			sk_change_net(sock->sk, net);
1524 
1525 			udp_addr.sin_family = AF_INET;
1526 			udp_addr.sin_addr = cfg->local_ip;
1527 			udp_addr.sin_port = htons(cfg->local_udp_port);
1528 			err = kernel_bind(sock, (struct sockaddr *) &udp_addr,
1529 					  sizeof(udp_addr));
1530 			if (err < 0)
1531 				goto out;
1532 
1533 			udp_addr.sin_family = AF_INET;
1534 			udp_addr.sin_addr = cfg->peer_ip;
1535 			udp_addr.sin_port = htons(cfg->peer_udp_port);
1536 			err = kernel_connect(sock,
1537 					     (struct sockaddr *) &udp_addr,
1538 					     sizeof(udp_addr), 0);
1539 			if (err < 0)
1540 				goto out;
1541 		}
1542 
1543 		if (!cfg->use_udp_checksums)
1544 			sock->sk->sk_no_check = UDP_CSUM_NOXMIT;
1545 
1546 		break;
1547 
1548 	case L2TP_ENCAPTYPE_IP:
1549 #if IS_ENABLED(CONFIG_IPV6)
1550 		if (cfg->local_ip6 && cfg->peer_ip6) {
1551 			err = sock_create_kern(AF_INET6, SOCK_DGRAM,
1552 					  IPPROTO_L2TP, &sock);
1553 			if (err < 0)
1554 				goto out;
1555 
1556 			sk_change_net(sock->sk, net);
1557 
1558 			ip6_addr.l2tp_family = AF_INET6;
1559 			memcpy(&ip6_addr.l2tp_addr, cfg->local_ip6,
1560 			       sizeof(ip6_addr.l2tp_addr));
1561 			ip6_addr.l2tp_conn_id = tunnel_id;
1562 			err = kernel_bind(sock, (struct sockaddr *) &ip6_addr,
1563 					  sizeof(ip6_addr));
1564 			if (err < 0)
1565 				goto out;
1566 
1567 			ip6_addr.l2tp_family = AF_INET6;
1568 			memcpy(&ip6_addr.l2tp_addr, cfg->peer_ip6,
1569 			       sizeof(ip6_addr.l2tp_addr));
1570 			ip6_addr.l2tp_conn_id = peer_tunnel_id;
1571 			err = kernel_connect(sock,
1572 					     (struct sockaddr *) &ip6_addr,
1573 					     sizeof(ip6_addr), 0);
1574 			if (err < 0)
1575 				goto out;
1576 		} else
1577 #endif
1578 		{
1579 			err = sock_create_kern(AF_INET, SOCK_DGRAM,
1580 					  IPPROTO_L2TP, &sock);
1581 			if (err < 0)
1582 				goto out;
1583 
1584 			sk_change_net(sock->sk, net);
1585 
1586 			ip_addr.l2tp_family = AF_INET;
1587 			ip_addr.l2tp_addr = cfg->local_ip;
1588 			ip_addr.l2tp_conn_id = tunnel_id;
1589 			err = kernel_bind(sock, (struct sockaddr *) &ip_addr,
1590 					  sizeof(ip_addr));
1591 			if (err < 0)
1592 				goto out;
1593 
1594 			ip_addr.l2tp_family = AF_INET;
1595 			ip_addr.l2tp_addr = cfg->peer_ip;
1596 			ip_addr.l2tp_conn_id = peer_tunnel_id;
1597 			err = kernel_connect(sock, (struct sockaddr *) &ip_addr,
1598 					     sizeof(ip_addr), 0);
1599 			if (err < 0)
1600 				goto out;
1601 		}
1602 		break;
1603 
1604 	default:
1605 		goto out;
1606 	}
1607 
1608 out:
1609 	*sockp = sock;
1610 	if ((err < 0) && sock) {
1611 		kernel_sock_shutdown(sock, SHUT_RDWR);
1612 		sk_release_kernel(sock->sk);
1613 		*sockp = NULL;
1614 	}
1615 
1616 	return err;
1617 }
1618 
1619 static struct lock_class_key l2tp_socket_class;
1620 
1621 int l2tp_tunnel_create(struct net *net, int fd, int version, u32 tunnel_id, u32 peer_tunnel_id, struct l2tp_tunnel_cfg *cfg, struct l2tp_tunnel **tunnelp)
1622 {
1623 	struct l2tp_tunnel *tunnel = NULL;
1624 	int err;
1625 	struct socket *sock = NULL;
1626 	struct sock *sk = NULL;
1627 	struct l2tp_net *pn;
1628 	enum l2tp_encap_type encap = L2TP_ENCAPTYPE_UDP;
1629 
1630 	/* Get the tunnel socket from the fd, which was opened by
1631 	 * the userspace L2TP daemon. If not specified, create a
1632 	 * kernel socket.
1633 	 */
1634 	if (fd < 0) {
1635 		err = l2tp_tunnel_sock_create(net, tunnel_id, peer_tunnel_id,
1636 				cfg, &sock);
1637 		if (err < 0)
1638 			goto err;
1639 	} else {
1640 		sock = sockfd_lookup(fd, &err);
1641 		if (!sock) {
1642 			pr_err("tunl %u: sockfd_lookup(fd=%d) returned %d\n",
1643 			       tunnel_id, fd, err);
1644 			err = -EBADF;
1645 			goto err;
1646 		}
1647 
1648 		/* Reject namespace mismatches */
1649 		if (!net_eq(sock_net(sock->sk), net)) {
1650 			pr_err("tunl %u: netns mismatch\n", tunnel_id);
1651 			err = -EINVAL;
1652 			goto err;
1653 		}
1654 	}
1655 
1656 	sk = sock->sk;
1657 
1658 	if (cfg != NULL)
1659 		encap = cfg->encap;
1660 
1661 	/* Quick sanity checks */
1662 	switch (encap) {
1663 	case L2TP_ENCAPTYPE_UDP:
1664 		err = -EPROTONOSUPPORT;
1665 		if (sk->sk_protocol != IPPROTO_UDP) {
1666 			pr_err("tunl %hu: fd %d wrong protocol, got %d, expected %d\n",
1667 			       tunnel_id, fd, sk->sk_protocol, IPPROTO_UDP);
1668 			goto err;
1669 		}
1670 		break;
1671 	case L2TP_ENCAPTYPE_IP:
1672 		err = -EPROTONOSUPPORT;
1673 		if (sk->sk_protocol != IPPROTO_L2TP) {
1674 			pr_err("tunl %hu: fd %d wrong protocol, got %d, expected %d\n",
1675 			       tunnel_id, fd, sk->sk_protocol, IPPROTO_L2TP);
1676 			goto err;
1677 		}
1678 		break;
1679 	}
1680 
1681 	/* Check if this socket has already been prepped */
1682 	tunnel = l2tp_tunnel(sk);
1683 	if (tunnel != NULL) {
1684 		/* This socket has already been prepped */
1685 		err = -EBUSY;
1686 		goto err;
1687 	}
1688 
1689 	tunnel = kzalloc(sizeof(struct l2tp_tunnel), GFP_KERNEL);
1690 	if (tunnel == NULL) {
1691 		err = -ENOMEM;
1692 		goto err;
1693 	}
1694 
1695 	tunnel->version = version;
1696 	tunnel->tunnel_id = tunnel_id;
1697 	tunnel->peer_tunnel_id = peer_tunnel_id;
1698 	tunnel->debug = L2TP_DEFAULT_DEBUG_FLAGS;
1699 
1700 	tunnel->magic = L2TP_TUNNEL_MAGIC;
1701 	sprintf(&tunnel->name[0], "tunl %u", tunnel_id);
1702 	rwlock_init(&tunnel->hlist_lock);
1703 
1704 	/* The net we belong to */
1705 	tunnel->l2tp_net = net;
1706 	pn = l2tp_pernet(net);
1707 
1708 	if (cfg != NULL)
1709 		tunnel->debug = cfg->debug;
1710 
1711 #if IS_ENABLED(CONFIG_IPV6)
1712 	if (sk->sk_family == PF_INET6) {
1713 		struct ipv6_pinfo *np = inet6_sk(sk);
1714 
1715 		if (ipv6_addr_v4mapped(&np->saddr) &&
1716 		    ipv6_addr_v4mapped(&np->daddr)) {
1717 			struct inet_sock *inet = inet_sk(sk);
1718 
1719 			tunnel->v4mapped = true;
1720 			inet->inet_saddr = np->saddr.s6_addr32[3];
1721 			inet->inet_rcv_saddr = np->rcv_saddr.s6_addr32[3];
1722 			inet->inet_daddr = np->daddr.s6_addr32[3];
1723 		} else {
1724 			tunnel->v4mapped = false;
1725 		}
1726 	}
1727 #endif
1728 
1729 	/* Mark socket as an encapsulation socket. See net/ipv4/udp.c */
1730 	tunnel->encap = encap;
1731 	if (encap == L2TP_ENCAPTYPE_UDP) {
1732 		/* Mark socket as an encapsulation socket. See net/ipv4/udp.c */
1733 		udp_sk(sk)->encap_type = UDP_ENCAP_L2TPINUDP;
1734 		udp_sk(sk)->encap_rcv = l2tp_udp_encap_recv;
1735 		udp_sk(sk)->encap_destroy = l2tp_udp_encap_destroy;
1736 #if IS_ENABLED(CONFIG_IPV6)
1737 		if (sk->sk_family == PF_INET6 && !tunnel->v4mapped)
1738 			udpv6_encap_enable();
1739 		else
1740 #endif
1741 		udp_encap_enable();
1742 	}
1743 
1744 	sk->sk_user_data = tunnel;
1745 
1746 	/* Hook on the tunnel socket destructor so that we can cleanup
1747 	 * if the tunnel socket goes away.
1748 	 */
1749 	tunnel->old_sk_destruct = sk->sk_destruct;
1750 	sk->sk_destruct = &l2tp_tunnel_destruct;
1751 	tunnel->sock = sk;
1752 	tunnel->fd = fd;
1753 	lockdep_set_class_and_name(&sk->sk_lock.slock, &l2tp_socket_class, "l2tp_sock");
1754 
1755 	sk->sk_allocation = GFP_ATOMIC;
1756 
1757 	/* Init delete workqueue struct */
1758 	INIT_WORK(&tunnel->del_work, l2tp_tunnel_del_work);
1759 
1760 	/* Add tunnel to our list */
1761 	INIT_LIST_HEAD(&tunnel->list);
1762 	atomic_inc(&l2tp_tunnel_count);
1763 
1764 	/* Bump the reference count. The tunnel context is deleted
1765 	 * only when this drops to zero. Must be done before list insertion
1766 	 */
1767 	l2tp_tunnel_inc_refcount(tunnel);
1768 	spin_lock_bh(&pn->l2tp_tunnel_list_lock);
1769 	list_add_rcu(&tunnel->list, &pn->l2tp_tunnel_list);
1770 	spin_unlock_bh(&pn->l2tp_tunnel_list_lock);
1771 
1772 	err = 0;
1773 err:
1774 	if (tunnelp)
1775 		*tunnelp = tunnel;
1776 
1777 	/* If tunnel's socket was created by the kernel, it doesn't
1778 	 *  have a file.
1779 	 */
1780 	if (sock && sock->file)
1781 		sockfd_put(sock);
1782 
1783 	return err;
1784 }
1785 EXPORT_SYMBOL_GPL(l2tp_tunnel_create);
1786 
1787 /* This function is used by the netlink TUNNEL_DELETE command.
1788  */
1789 int l2tp_tunnel_delete(struct l2tp_tunnel *tunnel)
1790 {
1791 	l2tp_tunnel_closeall(tunnel);
1792 	return (false == queue_work(l2tp_wq, &tunnel->del_work));
1793 }
1794 EXPORT_SYMBOL_GPL(l2tp_tunnel_delete);
1795 
1796 /* Really kill the session.
1797  */
1798 void l2tp_session_free(struct l2tp_session *session)
1799 {
1800 	struct l2tp_tunnel *tunnel = session->tunnel;
1801 
1802 	BUG_ON(atomic_read(&session->ref_count) != 0);
1803 
1804 	if (tunnel) {
1805 		BUG_ON(tunnel->magic != L2TP_TUNNEL_MAGIC);
1806 		if (session->session_id != 0)
1807 			atomic_dec(&l2tp_session_count);
1808 		sock_put(tunnel->sock);
1809 		session->tunnel = NULL;
1810 		l2tp_tunnel_dec_refcount(tunnel);
1811 	}
1812 
1813 	kfree(session);
1814 
1815 	return;
1816 }
1817 EXPORT_SYMBOL_GPL(l2tp_session_free);
1818 
1819 /* Remove an l2tp session from l2tp_core's hash lists.
1820  * Provides a tidyup interface for pseudowire code which can't just route all
1821  * shutdown via. l2tp_session_delete and a pseudowire-specific session_close
1822  * callback.
1823  */
1824 void __l2tp_session_unhash(struct l2tp_session *session)
1825 {
1826 	struct l2tp_tunnel *tunnel = session->tunnel;
1827 
1828 	/* Remove the session from core hashes */
1829 	if (tunnel) {
1830 		/* Remove from the per-tunnel hash */
1831 		write_lock_bh(&tunnel->hlist_lock);
1832 		hlist_del_init(&session->hlist);
1833 		write_unlock_bh(&tunnel->hlist_lock);
1834 
1835 		/* For L2TPv3 we have a per-net hash: remove from there, too */
1836 		if (tunnel->version != L2TP_HDR_VER_2) {
1837 			struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
1838 			spin_lock_bh(&pn->l2tp_session_hlist_lock);
1839 			hlist_del_init_rcu(&session->global_hlist);
1840 			spin_unlock_bh(&pn->l2tp_session_hlist_lock);
1841 			synchronize_rcu();
1842 		}
1843 	}
1844 }
1845 EXPORT_SYMBOL_GPL(__l2tp_session_unhash);
1846 
1847 /* This function is used by the netlink SESSION_DELETE command and by
1848    pseudowire modules.
1849  */
1850 int l2tp_session_delete(struct l2tp_session *session)
1851 {
1852 	if (session->ref)
1853 		(*session->ref)(session);
1854 	__l2tp_session_unhash(session);
1855 	l2tp_session_queue_purge(session);
1856 	if (session->session_close != NULL)
1857 		(*session->session_close)(session);
1858 	if (session->deref)
1859 		(*session->deref)(session);
1860 	l2tp_session_dec_refcount(session);
1861 	return 0;
1862 }
1863 EXPORT_SYMBOL_GPL(l2tp_session_delete);
1864 
1865 /* We come here whenever a session's send_seq, cookie_len or
1866  * l2specific_len parameters are set.
1867  */
1868 static void l2tp_session_set_header_len(struct l2tp_session *session, int version)
1869 {
1870 	if (version == L2TP_HDR_VER_2) {
1871 		session->hdr_len = 6;
1872 		if (session->send_seq)
1873 			session->hdr_len += 4;
1874 	} else {
1875 		session->hdr_len = 4 + session->cookie_len + session->l2specific_len + session->offset;
1876 		if (session->tunnel->encap == L2TP_ENCAPTYPE_UDP)
1877 			session->hdr_len += 4;
1878 	}
1879 
1880 }
1881 
1882 struct l2tp_session *l2tp_session_create(int priv_size, struct l2tp_tunnel *tunnel, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg)
1883 {
1884 	struct l2tp_session *session;
1885 
1886 	session = kzalloc(sizeof(struct l2tp_session) + priv_size, GFP_KERNEL);
1887 	if (session != NULL) {
1888 		session->magic = L2TP_SESSION_MAGIC;
1889 		session->tunnel = tunnel;
1890 
1891 		session->session_id = session_id;
1892 		session->peer_session_id = peer_session_id;
1893 		session->nr = 0;
1894 		if (tunnel->version == L2TP_HDR_VER_2)
1895 			session->nr_max = 0xffff;
1896 		else
1897 			session->nr_max = 0xffffff;
1898 		session->nr_window_size = session->nr_max / 2;
1899 		session->nr_oos_count_max = 4;
1900 
1901 		/* Use NR of first received packet */
1902 		session->reorder_skip = 1;
1903 
1904 		sprintf(&session->name[0], "sess %u/%u",
1905 			tunnel->tunnel_id, session->session_id);
1906 
1907 		skb_queue_head_init(&session->reorder_q);
1908 
1909 		INIT_HLIST_NODE(&session->hlist);
1910 		INIT_HLIST_NODE(&session->global_hlist);
1911 
1912 		/* Inherit debug options from tunnel */
1913 		session->debug = tunnel->debug;
1914 
1915 		if (cfg) {
1916 			session->pwtype = cfg->pw_type;
1917 			session->debug = cfg->debug;
1918 			session->mtu = cfg->mtu;
1919 			session->mru = cfg->mru;
1920 			session->send_seq = cfg->send_seq;
1921 			session->recv_seq = cfg->recv_seq;
1922 			session->lns_mode = cfg->lns_mode;
1923 			session->reorder_timeout = cfg->reorder_timeout;
1924 			session->offset = cfg->offset;
1925 			session->l2specific_type = cfg->l2specific_type;
1926 			session->l2specific_len = cfg->l2specific_len;
1927 			session->cookie_len = cfg->cookie_len;
1928 			memcpy(&session->cookie[0], &cfg->cookie[0], cfg->cookie_len);
1929 			session->peer_cookie_len = cfg->peer_cookie_len;
1930 			memcpy(&session->peer_cookie[0], &cfg->peer_cookie[0], cfg->peer_cookie_len);
1931 		}
1932 
1933 		if (tunnel->version == L2TP_HDR_VER_2)
1934 			session->build_header = l2tp_build_l2tpv2_header;
1935 		else
1936 			session->build_header = l2tp_build_l2tpv3_header;
1937 
1938 		l2tp_session_set_header_len(session, tunnel->version);
1939 
1940 		/* Bump the reference count. The session context is deleted
1941 		 * only when this drops to zero.
1942 		 */
1943 		l2tp_session_inc_refcount(session);
1944 		l2tp_tunnel_inc_refcount(tunnel);
1945 
1946 		/* Ensure tunnel socket isn't deleted */
1947 		sock_hold(tunnel->sock);
1948 
1949 		/* Add session to the tunnel's hash list */
1950 		write_lock_bh(&tunnel->hlist_lock);
1951 		hlist_add_head(&session->hlist,
1952 			       l2tp_session_id_hash(tunnel, session_id));
1953 		write_unlock_bh(&tunnel->hlist_lock);
1954 
1955 		/* And to the global session list if L2TPv3 */
1956 		if (tunnel->version != L2TP_HDR_VER_2) {
1957 			struct l2tp_net *pn = l2tp_pernet(tunnel->l2tp_net);
1958 
1959 			spin_lock_bh(&pn->l2tp_session_hlist_lock);
1960 			hlist_add_head_rcu(&session->global_hlist,
1961 					   l2tp_session_id_hash_2(pn, session_id));
1962 			spin_unlock_bh(&pn->l2tp_session_hlist_lock);
1963 		}
1964 
1965 		/* Ignore management session in session count value */
1966 		if (session->session_id != 0)
1967 			atomic_inc(&l2tp_session_count);
1968 	}
1969 
1970 	return session;
1971 }
1972 EXPORT_SYMBOL_GPL(l2tp_session_create);
1973 
1974 /*****************************************************************************
1975  * Init and cleanup
1976  *****************************************************************************/
1977 
1978 static __net_init int l2tp_init_net(struct net *net)
1979 {
1980 	struct l2tp_net *pn = net_generic(net, l2tp_net_id);
1981 	int hash;
1982 
1983 	INIT_LIST_HEAD(&pn->l2tp_tunnel_list);
1984 	spin_lock_init(&pn->l2tp_tunnel_list_lock);
1985 
1986 	for (hash = 0; hash < L2TP_HASH_SIZE_2; hash++)
1987 		INIT_HLIST_HEAD(&pn->l2tp_session_hlist[hash]);
1988 
1989 	spin_lock_init(&pn->l2tp_session_hlist_lock);
1990 
1991 	return 0;
1992 }
1993 
1994 static __net_exit void l2tp_exit_net(struct net *net)
1995 {
1996 	struct l2tp_net *pn = l2tp_pernet(net);
1997 	struct l2tp_tunnel *tunnel = NULL;
1998 
1999 	rcu_read_lock_bh();
2000 	list_for_each_entry_rcu(tunnel, &pn->l2tp_tunnel_list, list) {
2001 		(void)l2tp_tunnel_delete(tunnel);
2002 	}
2003 	rcu_read_unlock_bh();
2004 }
2005 
2006 static struct pernet_operations l2tp_net_ops = {
2007 	.init = l2tp_init_net,
2008 	.exit = l2tp_exit_net,
2009 	.id   = &l2tp_net_id,
2010 	.size = sizeof(struct l2tp_net),
2011 };
2012 
2013 static int __init l2tp_init(void)
2014 {
2015 	int rc = 0;
2016 
2017 	rc = register_pernet_device(&l2tp_net_ops);
2018 	if (rc)
2019 		goto out;
2020 
2021 	l2tp_wq = alloc_workqueue("l2tp", WQ_NON_REENTRANT | WQ_UNBOUND, 0);
2022 	if (!l2tp_wq) {
2023 		pr_err("alloc_workqueue failed\n");
2024 		rc = -ENOMEM;
2025 		goto out;
2026 	}
2027 
2028 	pr_info("L2TP core driver, %s\n", L2TP_DRV_VERSION);
2029 
2030 out:
2031 	return rc;
2032 }
2033 
2034 static void __exit l2tp_exit(void)
2035 {
2036 	unregister_pernet_device(&l2tp_net_ops);
2037 	if (l2tp_wq) {
2038 		destroy_workqueue(l2tp_wq);
2039 		l2tp_wq = NULL;
2040 	}
2041 }
2042 
2043 module_init(l2tp_init);
2044 module_exit(l2tp_exit);
2045 
2046 MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
2047 MODULE_DESCRIPTION("L2TP core");
2048 MODULE_LICENSE("GPL");
2049 MODULE_VERSION(L2TP_DRV_VERSION);
2050 
2051