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