ng_ppp.c revision 175697
1/*-
2 * Copyright (c) 1996-2000 Whistle Communications, Inc.
3 * All rights reserved.
4 *
5 * Subject to the following obligations and disclaimer of warranty, use and
6 * redistribution of this software, in source or object code forms, with or
7 * without modifications are expressly permitted by Whistle Communications;
8 * provided, however, that:
9 * 1. Any and all reproductions of the source or object code must include the
10 *    copyright notice above and the following disclaimer of warranties; and
11 * 2. No rights are granted, in any manner or form, to use Whistle
12 *    Communications, Inc. trademarks, including the mark "WHISTLE
13 *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
14 *    such appears in the above copyright notice or in the software.
15 *
16 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
17 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
18 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
19 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
21 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
22 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
23 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
24 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
25 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
26 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
27 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
28 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
32 * OF SUCH DAMAGE.
33 *
34 * Copyright (c) 2007 Alexander Motin <mav@alkar.net>
35 * All rights reserved.
36 *
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
39 * are met:
40 * 1. Redistributions of source code must retain the above copyright
41 *    notice unmodified, this list of conditions, and the following
42 *    disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 *    notice, this list of conditions and the following disclaimer in the
45 *    documentation and/or other materials provided with the distribution.
46 *
47 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
48 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
51 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57 * SUCH DAMAGE.
58 *
59 * Authors: Archie Cobbs <archie@freebsd.org>, Alexander Motin <mav@alkar.net>
60 *
61 * $FreeBSD: head/sys/netgraph/ng_ppp.c 175697 2008-01-26 22:41:14Z mav $
62 * $Whistle: ng_ppp.c,v 1.24 1999/11/01 09:24:52 julian Exp $
63 */
64
65/*
66 * PPP node type data-flow.
67 *
68 *       hook      xmit        layer         recv      hook
69 *              ------------------------------------
70 *       inet ->                                    -> inet
71 *       ipv6 ->                                    -> ipv6
72 *        ipx ->               proto                -> ipx
73 *      atalk ->                                    -> atalk
74 *     bypass ->                                    -> bypass
75 *              -hcomp_xmit()----------proto_recv()-
76 *     vjc_ip <-                                    <- vjc_ip
77 *   vjc_comp ->         header compression         -> vjc_comp
78 * vjc_uncomp ->                                    -> vjc_uncomp
79 *   vjc_vjip ->
80 *              -comp_xmit()-----------hcomp_recv()-
81 *   compress <-            compression             <- decompress
82 *   compress ->                                    -> decompress
83 *              -crypt_xmit()-----------comp_recv()-
84 *    encrypt <-             encryption             <- decrypt
85 *    encrypt ->                                    -> decrypt
86 *              -ml_xmit()-------------crypt_recv()-
87 *                           multilink
88 *              -link_xmit()--------------ml_recv()-
89 *      linkX <-               link                 <- linkX
90 *
91 */
92
93#include <sys/param.h>
94#include <sys/systm.h>
95#include <sys/kernel.h>
96#include <sys/limits.h>
97#include <sys/time.h>
98#include <sys/mbuf.h>
99#include <sys/malloc.h>
100#include <sys/errno.h>
101#include <sys/ctype.h>
102
103#include <netgraph/ng_message.h>
104#include <netgraph/netgraph.h>
105#include <netgraph/ng_parse.h>
106#include <netgraph/ng_ppp.h>
107#include <netgraph/ng_vjc.h>
108
109#ifdef NG_SEPARATE_MALLOC
110MALLOC_DEFINE(M_NETGRAPH_PPP, "netgraph_ppp", "netgraph ppp node");
111#else
112#define M_NETGRAPH_PPP M_NETGRAPH
113#endif
114
115#define PROT_VALID(p)		(((p) & 0x0101) == 0x0001)
116#define PROT_COMPRESSABLE(p)	(((p) & 0xff00) == 0x0000)
117
118/* Some PPP protocol numbers we're interested in */
119#define PROT_ATALK		0x0029
120#define PROT_COMPD		0x00fd
121#define PROT_CRYPTD		0x0053
122#define PROT_IP			0x0021
123#define PROT_IPV6		0x0057
124#define PROT_IPX		0x002b
125#define PROT_LCP		0xc021
126#define PROT_MP			0x003d
127#define PROT_VJCOMP		0x002d
128#define PROT_VJUNCOMP		0x002f
129
130/* Multilink PPP definitions */
131#define MP_MIN_MRRU		1500		/* per RFC 1990 */
132#define MP_INITIAL_SEQ		0		/* per RFC 1990 */
133#define MP_MIN_LINK_MRU		32
134
135#define MP_SHORT_SEQ_MASK	0x00000fff	/* short seq # mask */
136#define MP_SHORT_SEQ_HIBIT	0x00000800	/* short seq # high bit */
137#define MP_SHORT_FIRST_FLAG	0x00008000	/* first fragment in frame */
138#define MP_SHORT_LAST_FLAG	0x00004000	/* last fragment in frame */
139
140#define MP_LONG_SEQ_MASK	0x00ffffff	/* long seq # mask */
141#define MP_LONG_SEQ_HIBIT	0x00800000	/* long seq # high bit */
142#define MP_LONG_FIRST_FLAG	0x80000000	/* first fragment in frame */
143#define MP_LONG_LAST_FLAG	0x40000000	/* last fragment in frame */
144
145#define MP_NOSEQ		0x7fffffff	/* impossible sequence number */
146
147/* Sign extension of MP sequence numbers */
148#define MP_SHORT_EXTEND(s)	(((s) & MP_SHORT_SEQ_HIBIT) ?		\
149				    ((s) | ~MP_SHORT_SEQ_MASK)		\
150				    : ((s) & MP_SHORT_SEQ_MASK))
151#define MP_LONG_EXTEND(s)	(((s) & MP_LONG_SEQ_HIBIT) ?		\
152				    ((s) | ~MP_LONG_SEQ_MASK)		\
153				    : ((s) & MP_LONG_SEQ_MASK))
154
155/* Comparision of MP sequence numbers. Note: all sequence numbers
156   except priv->xseq are stored with the sign bit extended. */
157#define MP_SHORT_SEQ_DIFF(x,y)	MP_SHORT_EXTEND((x) - (y))
158#define MP_LONG_SEQ_DIFF(x,y)	MP_LONG_EXTEND((x) - (y))
159
160#define MP_RECV_SEQ_DIFF(priv,x,y)					\
161				((priv)->conf.recvShortSeq ?		\
162				    MP_SHORT_SEQ_DIFF((x), (y)) :	\
163				    MP_LONG_SEQ_DIFF((x), (y)))
164
165/* Increment receive sequence number */
166#define MP_NEXT_RECV_SEQ(priv,seq)					\
167				((priv)->conf.recvShortSeq ?		\
168				    MP_SHORT_EXTEND((seq) + 1) :	\
169				    MP_LONG_EXTEND((seq) + 1))
170
171/* Don't fragment transmitted packets to parts smaller than this */
172#define MP_MIN_FRAG_LEN		32
173
174/* Maximum fragment reasssembly queue length */
175#define MP_MAX_QUEUE_LEN	128
176
177/* Fragment queue scanner period */
178#define MP_FRAGTIMER_INTERVAL	(hz/2)
179
180/* Average link overhead. XXX: Should be given by user-level */
181#define MP_AVERAGE_LINK_OVERHEAD	16
182
183/* Keep this equal to ng_ppp_hook_names lower! */
184#define HOOK_INDEX_MAX		13
185
186/* We store incoming fragments this way */
187struct ng_ppp_frag {
188	int				seq;		/* fragment seq# */
189	uint8_t				first;		/* First in packet? */
190	uint8_t				last;		/* Last in packet? */
191	struct timeval			timestamp;	/* time of reception */
192	struct mbuf			*data;		/* Fragment data */
193	TAILQ_ENTRY(ng_ppp_frag)	f_qent;		/* Fragment queue */
194};
195
196/* Per-link private information */
197struct ng_ppp_link {
198	struct ng_ppp_link_conf	conf;		/* link configuration */
199	struct ng_ppp_link_stat64	stats;	/* link stats */
200	hook_p			hook;		/* connection to link data */
201	int32_t			seq;		/* highest rec'd seq# - MSEQ */
202	uint32_t		latency;	/* calculated link latency */
203	struct timeval		lastWrite;	/* time of last write for MP */
204	int			bytesInQueue;	/* bytes in the output queue for MP */
205};
206
207/* Total per-node private information */
208struct ng_ppp_private {
209	struct ng_ppp_bund_conf	conf;			/* bundle config */
210	struct ng_ppp_link_stat64	bundleStats;	/* bundle stats */
211	struct ng_ppp_link	links[NG_PPP_MAX_LINKS];/* per-link info */
212	int32_t			xseq;			/* next out MP seq # */
213	int32_t			mseq;			/* min links[i].seq */
214	uint16_t		activeLinks[NG_PPP_MAX_LINKS];	/* indicies */
215	uint16_t		numActiveLinks;		/* how many links up */
216	uint16_t		lastLink;		/* for round robin */
217	uint8_t			vjCompHooked;		/* VJ comp hooked up? */
218	uint8_t			allLinksEqual;		/* all xmit the same? */
219	hook_p			hooks[HOOK_INDEX_MAX];	/* non-link hooks */
220	struct ng_ppp_frag	fragsmem[MP_MAX_QUEUE_LEN]; /* fragments storage */
221	TAILQ_HEAD(ng_ppp_fraglist, ng_ppp_frag)	/* fragment queue */
222				frags;
223	TAILQ_HEAD(ng_ppp_fragfreelist, ng_ppp_frag)	/* free fragment queue */
224				fragsfree;
225	struct callout		fragTimer;		/* fraq queue check */
226	struct mtx		rmtx;			/* recv mutex */
227	struct mtx		xmtx;			/* xmit mutex */
228};
229typedef struct ng_ppp_private *priv_p;
230
231/* Netgraph node methods */
232static ng_constructor_t	ng_ppp_constructor;
233static ng_rcvmsg_t	ng_ppp_rcvmsg;
234static ng_shutdown_t	ng_ppp_shutdown;
235static ng_newhook_t	ng_ppp_newhook;
236static ng_rcvdata_t	ng_ppp_rcvdata;
237static ng_disconnect_t	ng_ppp_disconnect;
238
239static ng_rcvdata_t	ng_ppp_rcvdata_inet;
240static ng_rcvdata_t	ng_ppp_rcvdata_ipv6;
241static ng_rcvdata_t	ng_ppp_rcvdata_ipx;
242static ng_rcvdata_t	ng_ppp_rcvdata_atalk;
243static ng_rcvdata_t	ng_ppp_rcvdata_bypass;
244
245static ng_rcvdata_t	ng_ppp_rcvdata_vjc_ip;
246static ng_rcvdata_t	ng_ppp_rcvdata_vjc_comp;
247static ng_rcvdata_t	ng_ppp_rcvdata_vjc_uncomp;
248static ng_rcvdata_t	ng_ppp_rcvdata_vjc_vjip;
249
250static ng_rcvdata_t	ng_ppp_rcvdata_compress;
251static ng_rcvdata_t	ng_ppp_rcvdata_decompress;
252
253static ng_rcvdata_t	ng_ppp_rcvdata_encrypt;
254static ng_rcvdata_t	ng_ppp_rcvdata_decrypt;
255
256/* We use integer indicies to refer to the non-link hooks. */
257static const struct {
258	char *const name;
259	ng_rcvdata_t *fn;
260} ng_ppp_hook_names[] = {
261#define HOOK_INDEX_ATALK	0
262	{ NG_PPP_HOOK_ATALK,	ng_ppp_rcvdata_atalk },
263#define HOOK_INDEX_BYPASS	1
264	{ NG_PPP_HOOK_BYPASS,	ng_ppp_rcvdata_bypass },
265#define HOOK_INDEX_COMPRESS	2
266	{ NG_PPP_HOOK_COMPRESS,	ng_ppp_rcvdata_compress },
267#define HOOK_INDEX_ENCRYPT	3
268	{ NG_PPP_HOOK_ENCRYPT,	ng_ppp_rcvdata_encrypt },
269#define HOOK_INDEX_DECOMPRESS	4
270	{ NG_PPP_HOOK_DECOMPRESS, ng_ppp_rcvdata_decompress },
271#define HOOK_INDEX_DECRYPT	5
272	{ NG_PPP_HOOK_DECRYPT,	ng_ppp_rcvdata_decrypt },
273#define HOOK_INDEX_INET		6
274	{ NG_PPP_HOOK_INET,	ng_ppp_rcvdata_inet },
275#define HOOK_INDEX_IPX		7
276	{ NG_PPP_HOOK_IPX,	ng_ppp_rcvdata_ipx },
277#define HOOK_INDEX_VJC_COMP	8
278	{ NG_PPP_HOOK_VJC_COMP,	ng_ppp_rcvdata_vjc_comp },
279#define HOOK_INDEX_VJC_IP	9
280	{ NG_PPP_HOOK_VJC_IP,	ng_ppp_rcvdata_vjc_ip },
281#define HOOK_INDEX_VJC_UNCOMP	10
282	{ NG_PPP_HOOK_VJC_UNCOMP, ng_ppp_rcvdata_vjc_uncomp },
283#define HOOK_INDEX_VJC_VJIP	11
284	{ NG_PPP_HOOK_VJC_VJIP,	ng_ppp_rcvdata_vjc_vjip },
285#define HOOK_INDEX_IPV6		12
286	{ NG_PPP_HOOK_IPV6,	ng_ppp_rcvdata_ipv6 },
287	{ NULL, NULL }
288};
289
290/* Helper functions */
291static int	ng_ppp_proto_recv(node_p node, item_p item, uint16_t proto,
292		    uint16_t linkNum);
293static int	ng_ppp_hcomp_xmit(node_p node, item_p item, uint16_t proto);
294static int	ng_ppp_hcomp_recv(node_p node, item_p item, uint16_t proto,
295		    uint16_t linkNum);
296static int	ng_ppp_comp_xmit(node_p node, item_p item, uint16_t proto);
297static int	ng_ppp_comp_recv(node_p node, item_p item, uint16_t proto,
298		    uint16_t linkNum);
299static int	ng_ppp_crypt_xmit(node_p node, item_p item, uint16_t proto);
300static int	ng_ppp_crypt_recv(node_p node, item_p item, uint16_t proto,
301		    uint16_t linkNum);
302static int	ng_ppp_mp_xmit(node_p node, item_p item, uint16_t proto);
303static int	ng_ppp_mp_recv(node_p node, item_p item, uint16_t proto,
304		    uint16_t linkNum);
305static int	ng_ppp_link_xmit(node_p node, item_p item, uint16_t proto,
306		    uint16_t linkNum, int plen);
307
308static int	ng_ppp_bypass(node_p node, item_p item, uint16_t proto,
309		    uint16_t linkNum);
310
311static void	ng_ppp_bump_mseq(node_p node, int32_t new_mseq);
312static int	ng_ppp_frag_drop(node_p node);
313static int	ng_ppp_check_packet(node_p node);
314static void	ng_ppp_get_packet(node_p node, struct mbuf **mp);
315static int	ng_ppp_frag_process(node_p node);
316static int	ng_ppp_frag_trim(node_p node);
317static void	ng_ppp_frag_timeout(node_p node, hook_p hook, void *arg1,
318		    int arg2);
319static void	ng_ppp_frag_checkstale(node_p node);
320static void	ng_ppp_frag_reset(node_p node);
321static void	ng_ppp_mp_strategy(node_p node, int len, int *distrib);
322static int	ng_ppp_intcmp(void *latency, const void *v1, const void *v2);
323static struct mbuf *ng_ppp_addproto(struct mbuf *m, uint16_t proto, int compOK);
324static struct mbuf *ng_ppp_cutproto(struct mbuf *m, uint16_t *proto);
325static struct mbuf *ng_ppp_prepend(struct mbuf *m, const void *buf, int len);
326static int	ng_ppp_config_valid(node_p node,
327		    const struct ng_ppp_node_conf *newConf);
328static void	ng_ppp_update(node_p node, int newConf);
329static void	ng_ppp_start_frag_timer(node_p node);
330static void	ng_ppp_stop_frag_timer(node_p node);
331
332/* Parse type for struct ng_ppp_mp_state_type */
333static const struct ng_parse_fixedarray_info ng_ppp_rseq_array_info = {
334	&ng_parse_hint32_type,
335	NG_PPP_MAX_LINKS
336};
337static const struct ng_parse_type ng_ppp_rseq_array_type = {
338	&ng_parse_fixedarray_type,
339	&ng_ppp_rseq_array_info,
340};
341static const struct ng_parse_struct_field ng_ppp_mp_state_type_fields[]
342	= NG_PPP_MP_STATE_TYPE_INFO(&ng_ppp_rseq_array_type);
343static const struct ng_parse_type ng_ppp_mp_state_type = {
344	&ng_parse_struct_type,
345	&ng_ppp_mp_state_type_fields
346};
347
348/* Parse type for struct ng_ppp_link_conf */
349static const struct ng_parse_struct_field ng_ppp_link_type_fields[]
350	= NG_PPP_LINK_TYPE_INFO;
351static const struct ng_parse_type ng_ppp_link_type = {
352	&ng_parse_struct_type,
353	&ng_ppp_link_type_fields
354};
355
356/* Parse type for struct ng_ppp_bund_conf */
357static const struct ng_parse_struct_field ng_ppp_bund_type_fields[]
358	= NG_PPP_BUND_TYPE_INFO;
359static const struct ng_parse_type ng_ppp_bund_type = {
360	&ng_parse_struct_type,
361	&ng_ppp_bund_type_fields
362};
363
364/* Parse type for struct ng_ppp_node_conf */
365static const struct ng_parse_fixedarray_info ng_ppp_array_info = {
366	&ng_ppp_link_type,
367	NG_PPP_MAX_LINKS
368};
369static const struct ng_parse_type ng_ppp_link_array_type = {
370	&ng_parse_fixedarray_type,
371	&ng_ppp_array_info,
372};
373static const struct ng_parse_struct_field ng_ppp_conf_type_fields[]
374	= NG_PPP_CONFIG_TYPE_INFO(&ng_ppp_bund_type, &ng_ppp_link_array_type);
375static const struct ng_parse_type ng_ppp_conf_type = {
376	&ng_parse_struct_type,
377	&ng_ppp_conf_type_fields
378};
379
380/* Parse type for struct ng_ppp_link_stat */
381static const struct ng_parse_struct_field ng_ppp_stats_type_fields[]
382	= NG_PPP_STATS_TYPE_INFO;
383static const struct ng_parse_type ng_ppp_stats_type = {
384	&ng_parse_struct_type,
385	&ng_ppp_stats_type_fields
386};
387
388/* Parse type for struct ng_ppp_link_stat64 */
389static const struct ng_parse_struct_field ng_ppp_stats64_type_fields[]
390	= NG_PPP_STATS64_TYPE_INFO;
391static const struct ng_parse_type ng_ppp_stats64_type = {
392	&ng_parse_struct_type,
393	&ng_ppp_stats64_type_fields
394};
395
396/* List of commands and how to convert arguments to/from ASCII */
397static const struct ng_cmdlist ng_ppp_cmds[] = {
398	{
399	  NGM_PPP_COOKIE,
400	  NGM_PPP_SET_CONFIG,
401	  "setconfig",
402	  &ng_ppp_conf_type,
403	  NULL
404	},
405	{
406	  NGM_PPP_COOKIE,
407	  NGM_PPP_GET_CONFIG,
408	  "getconfig",
409	  NULL,
410	  &ng_ppp_conf_type
411	},
412	{
413	  NGM_PPP_COOKIE,
414	  NGM_PPP_GET_MP_STATE,
415	  "getmpstate",
416	  NULL,
417	  &ng_ppp_mp_state_type
418	},
419	{
420	  NGM_PPP_COOKIE,
421	  NGM_PPP_GET_LINK_STATS,
422	  "getstats",
423	  &ng_parse_int16_type,
424	  &ng_ppp_stats_type
425	},
426	{
427	  NGM_PPP_COOKIE,
428	  NGM_PPP_CLR_LINK_STATS,
429	  "clrstats",
430	  &ng_parse_int16_type,
431	  NULL
432	},
433	{
434	  NGM_PPP_COOKIE,
435	  NGM_PPP_GETCLR_LINK_STATS,
436	  "getclrstats",
437	  &ng_parse_int16_type,
438	  &ng_ppp_stats_type
439	},
440	{
441	  NGM_PPP_COOKIE,
442	  NGM_PPP_GET_LINK_STATS64,
443	  "getstats64",
444	  &ng_parse_int16_type,
445	  &ng_ppp_stats64_type
446	},
447	{
448	  NGM_PPP_COOKIE,
449	  NGM_PPP_GETCLR_LINK_STATS64,
450	  "getclrstats64",
451	  &ng_parse_int16_type,
452	  &ng_ppp_stats64_type
453	},
454	{ 0 }
455};
456
457/* Node type descriptor */
458static struct ng_type ng_ppp_typestruct = {
459	.version =	NG_ABI_VERSION,
460	.name =		NG_PPP_NODE_TYPE,
461	.constructor =	ng_ppp_constructor,
462	.rcvmsg =	ng_ppp_rcvmsg,
463	.shutdown =	ng_ppp_shutdown,
464	.newhook =	ng_ppp_newhook,
465	.rcvdata =	ng_ppp_rcvdata,
466	.disconnect =	ng_ppp_disconnect,
467	.cmdlist =	ng_ppp_cmds,
468};
469NETGRAPH_INIT(ppp, &ng_ppp_typestruct);
470
471/* Address and control field header */
472static const uint8_t ng_ppp_acf[2] = { 0xff, 0x03 };
473
474/* Maximum time we'll let a complete incoming packet sit in the queue */
475static const struct timeval ng_ppp_max_staleness = { 2, 0 };	/* 2 seconds */
476
477#define ERROUT(x)	do { error = (x); goto done; } while (0)
478
479/************************************************************************
480			NETGRAPH NODE STUFF
481 ************************************************************************/
482
483/*
484 * Node type constructor
485 */
486static int
487ng_ppp_constructor(node_p node)
488{
489	priv_p priv;
490	int i;
491
492	/* Allocate private structure */
493	MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH_PPP, M_NOWAIT | M_ZERO);
494	if (priv == NULL)
495		return (ENOMEM);
496
497	NG_NODE_SET_PRIVATE(node, priv);
498
499	/* Initialize state */
500	TAILQ_INIT(&priv->frags);
501	TAILQ_INIT(&priv->fragsfree);
502	for (i = 0; i < MP_MAX_QUEUE_LEN; i++)
503		TAILQ_INSERT_TAIL(&priv->fragsfree, &priv->fragsmem[i], f_qent);
504	for (i = 0; i < NG_PPP_MAX_LINKS; i++)
505		priv->links[i].seq = MP_NOSEQ;
506	ng_callout_init(&priv->fragTimer);
507
508	mtx_init(&priv->rmtx, "ng_ppp_recv", NULL, MTX_DEF);
509	mtx_init(&priv->xmtx, "ng_ppp_xmit", NULL, MTX_DEF);
510
511	/* Done */
512	return (0);
513}
514
515/*
516 * Give our OK for a hook to be added
517 */
518static int
519ng_ppp_newhook(node_p node, hook_p hook, const char *name)
520{
521	const priv_p priv = NG_NODE_PRIVATE(node);
522	hook_p *hookPtr = NULL;
523	int linkNum = -1;
524	int hookIndex = -1;
525
526	/* Figure out which hook it is */
527	if (strncmp(name, NG_PPP_HOOK_LINK_PREFIX,	/* a link hook? */
528	    strlen(NG_PPP_HOOK_LINK_PREFIX)) == 0) {
529		const char *cp;
530		char *eptr;
531
532		cp = name + strlen(NG_PPP_HOOK_LINK_PREFIX);
533		if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
534			return (EINVAL);
535		linkNum = (int)strtoul(cp, &eptr, 10);
536		if (*eptr != '\0' || linkNum < 0 || linkNum >= NG_PPP_MAX_LINKS)
537			return (EINVAL);
538		hookPtr = &priv->links[linkNum].hook;
539		hookIndex = ~linkNum;
540
541		/* See if hook is already connected. */
542		if (*hookPtr != NULL)
543			return (EISCONN);
544
545		/* Disallow more than one link unless multilink is enabled. */
546		if (priv->links[linkNum].conf.enableLink &&
547		    !priv->conf.enableMultilink && priv->numActiveLinks >= 1)
548			return (ENODEV);
549
550	} else {				/* must be a non-link hook */
551		int i;
552
553		for (i = 0; ng_ppp_hook_names[i].name != NULL; i++) {
554			if (strcmp(name, ng_ppp_hook_names[i].name) == 0) {
555				hookPtr = &priv->hooks[i];
556				hookIndex = i;
557				break;
558			}
559		}
560		if (ng_ppp_hook_names[i].name == NULL)
561			return (EINVAL);	/* no such hook */
562
563		/* See if hook is already connected */
564		if (*hookPtr != NULL)
565			return (EISCONN);
566
567		/* Every non-linkX hook have it's own function. */
568		NG_HOOK_SET_RCVDATA(hook, ng_ppp_hook_names[i].fn);
569	}
570
571	/* OK */
572	*hookPtr = hook;
573	NG_HOOK_SET_PRIVATE(hook, (void *)(intptr_t)hookIndex);
574	ng_ppp_update(node, 0);
575	return (0);
576}
577
578/*
579 * Receive a control message
580 */
581static int
582ng_ppp_rcvmsg(node_p node, item_p item, hook_p lasthook)
583{
584	const priv_p priv = NG_NODE_PRIVATE(node);
585	struct ng_mesg *resp = NULL;
586	int error = 0;
587	struct ng_mesg *msg;
588
589	NGI_GET_MSG(item, msg);
590	switch (msg->header.typecookie) {
591	case NGM_PPP_COOKIE:
592		switch (msg->header.cmd) {
593		case NGM_PPP_SET_CONFIG:
594		    {
595			struct ng_ppp_node_conf *const conf =
596			    (struct ng_ppp_node_conf *)msg->data;
597			int i;
598
599			/* Check for invalid or illegal config */
600			if (msg->header.arglen != sizeof(*conf))
601				ERROUT(EINVAL);
602			if (!ng_ppp_config_valid(node, conf))
603				ERROUT(EINVAL);
604
605			/* Copy config */
606			priv->conf = conf->bund;
607			for (i = 0; i < NG_PPP_MAX_LINKS; i++)
608				priv->links[i].conf = conf->links[i];
609			ng_ppp_update(node, 1);
610			break;
611		    }
612		case NGM_PPP_GET_CONFIG:
613		    {
614			struct ng_ppp_node_conf *conf;
615			int i;
616
617			NG_MKRESPONSE(resp, msg, sizeof(*conf), M_NOWAIT);
618			if (resp == NULL)
619				ERROUT(ENOMEM);
620			conf = (struct ng_ppp_node_conf *)resp->data;
621			conf->bund = priv->conf;
622			for (i = 0; i < NG_PPP_MAX_LINKS; i++)
623				conf->links[i] = priv->links[i].conf;
624			break;
625		    }
626		case NGM_PPP_GET_MP_STATE:
627		    {
628			struct ng_ppp_mp_state *info;
629			int i;
630
631			NG_MKRESPONSE(resp, msg, sizeof(*info), M_NOWAIT);
632			if (resp == NULL)
633				ERROUT(ENOMEM);
634			info = (struct ng_ppp_mp_state *)resp->data;
635			bzero(info, sizeof(*info));
636			for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
637				if (priv->links[i].seq != MP_NOSEQ)
638					info->rseq[i] = priv->links[i].seq;
639			}
640			info->mseq = priv->mseq;
641			info->xseq = priv->xseq;
642			break;
643		    }
644		case NGM_PPP_GET_LINK_STATS:
645		case NGM_PPP_CLR_LINK_STATS:
646		case NGM_PPP_GETCLR_LINK_STATS:
647		case NGM_PPP_GET_LINK_STATS64:
648		case NGM_PPP_GETCLR_LINK_STATS64:
649		    {
650			struct ng_ppp_link_stat64 *stats;
651			uint16_t linkNum;
652
653			/* Process request. */
654			if (msg->header.arglen != sizeof(uint16_t))
655				ERROUT(EINVAL);
656			linkNum = *((uint16_t *) msg->data);
657			if (linkNum >= NG_PPP_MAX_LINKS
658			    && linkNum != NG_PPP_BUNDLE_LINKNUM)
659				ERROUT(EINVAL);
660			stats = (linkNum == NG_PPP_BUNDLE_LINKNUM) ?
661			    &priv->bundleStats : &priv->links[linkNum].stats;
662
663			/* Make 64bit reply. */
664			if (msg->header.cmd == NGM_PPP_GET_LINK_STATS64 ||
665			    msg->header.cmd == NGM_PPP_GETCLR_LINK_STATS64) {
666				NG_MKRESPONSE(resp, msg,
667				    sizeof(struct ng_ppp_link_stat64), M_NOWAIT);
668				if (resp == NULL)
669					ERROUT(ENOMEM);
670				bcopy(stats, resp->data, sizeof(*stats));
671			} else
672			/* Make 32bit reply. */
673			if (msg->header.cmd == NGM_PPP_GET_LINK_STATS ||
674			    msg->header.cmd == NGM_PPP_GETCLR_LINK_STATS) {
675				struct ng_ppp_link_stat *rs;
676				NG_MKRESPONSE(resp, msg,
677				    sizeof(struct ng_ppp_link_stat), M_NOWAIT);
678				if (resp == NULL)
679					ERROUT(ENOMEM);
680				rs = (struct ng_ppp_link_stat *)resp->data;
681				/* Truncate 64->32 bits. */
682				rs->xmitFrames = stats->xmitFrames;
683				rs->xmitOctets = stats->xmitOctets;
684				rs->recvFrames = stats->recvFrames;
685				rs->recvOctets = stats->recvOctets;
686				rs->badProtos = stats->badProtos;
687				rs->runts = stats->runts;
688				rs->dupFragments = stats->dupFragments;
689				rs->dropFragments = stats->dropFragments;
690			}
691			/* Clear stats. */
692			if (msg->header.cmd != NGM_PPP_GET_LINK_STATS &&
693			    msg->header.cmd != NGM_PPP_GET_LINK_STATS64)
694				bzero(stats, sizeof(*stats));
695			break;
696		    }
697		default:
698			error = EINVAL;
699			break;
700		}
701		break;
702	case NGM_VJC_COOKIE:
703	    {
704		/*
705		 * Forward it to the vjc node. leave the
706		 * old return address alone.
707		 * If we have no hook, let NG_RESPOND_MSG
708		 * clean up any remaining resources.
709		 * Because we have no resp, the item will be freed
710		 * along with anything it references. Don't
711		 * let msg be freed twice.
712		 */
713		NGI_MSG(item) = msg;	/* put it back in the item */
714		msg = NULL;
715		if ((lasthook = priv->hooks[HOOK_INDEX_VJC_IP])) {
716			NG_FWD_ITEM_HOOK(error, item, lasthook);
717		}
718		return (error);
719	    }
720	default:
721		error = EINVAL;
722		break;
723	}
724done:
725	NG_RESPOND_MSG(error, node, item, resp);
726	NG_FREE_MSG(msg);
727	return (error);
728}
729
730/*
731 * Destroy node
732 */
733static int
734ng_ppp_shutdown(node_p node)
735{
736	const priv_p priv = NG_NODE_PRIVATE(node);
737
738	/* Stop fragment queue timer */
739	ng_ppp_stop_frag_timer(node);
740
741	/* Take down netgraph node */
742	ng_ppp_frag_reset(node);
743	mtx_destroy(&priv->rmtx);
744	mtx_destroy(&priv->xmtx);
745	bzero(priv, sizeof(*priv));
746	FREE(priv, M_NETGRAPH_PPP);
747	NG_NODE_SET_PRIVATE(node, NULL);
748	NG_NODE_UNREF(node);		/* let the node escape */
749	return (0);
750}
751
752/*
753 * Hook disconnection
754 */
755static int
756ng_ppp_disconnect(hook_p hook)
757{
758	const node_p node = NG_HOOK_NODE(hook);
759	const priv_p priv = NG_NODE_PRIVATE(node);
760	const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
761
762	/* Zero out hook pointer */
763	if (index < 0)
764		priv->links[~index].hook = NULL;
765	else
766		priv->hooks[index] = NULL;
767
768	/* Update derived info (or go away if no hooks left). */
769	if (NG_NODE_NUMHOOKS(node) > 0)
770		ng_ppp_update(node, 0);
771	else if (NG_NODE_IS_VALID(node))
772		ng_rmnode_self(node);
773
774	return (0);
775}
776
777/*
778 * Proto layer
779 */
780
781/*
782 * Receive data on a hook inet.
783 */
784static int
785ng_ppp_rcvdata_inet(hook_p hook, item_p item)
786{
787	const node_p node = NG_HOOK_NODE(hook);
788	const priv_p priv = NG_NODE_PRIVATE(node);
789
790	if (!priv->conf.enableIP) {
791		NG_FREE_ITEM(item);
792		return (ENXIO);
793	}
794	return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_IP));
795}
796
797/*
798 * Receive data on a hook ipv6.
799 */
800static int
801ng_ppp_rcvdata_ipv6(hook_p hook, item_p item)
802{
803	const node_p node = NG_HOOK_NODE(hook);
804	const priv_p priv = NG_NODE_PRIVATE(node);
805
806	if (!priv->conf.enableIPv6) {
807		NG_FREE_ITEM(item);
808		return (ENXIO);
809	}
810	return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_IPV6));
811}
812
813/*
814 * Receive data on a hook atalk.
815 */
816static int
817ng_ppp_rcvdata_atalk(hook_p hook, item_p item)
818{
819	const node_p node = NG_HOOK_NODE(hook);
820	const priv_p priv = NG_NODE_PRIVATE(node);
821
822	if (!priv->conf.enableAtalk) {
823		NG_FREE_ITEM(item);
824		return (ENXIO);
825	}
826	return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_ATALK));
827}
828
829/*
830 * Receive data on a hook ipx
831 */
832static int
833ng_ppp_rcvdata_ipx(hook_p hook, item_p item)
834{
835	const node_p node = NG_HOOK_NODE(hook);
836	const priv_p priv = NG_NODE_PRIVATE(node);
837
838	if (!priv->conf.enableIPX) {
839		NG_FREE_ITEM(item);
840		return (ENXIO);
841	}
842	return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_IPX));
843}
844
845/*
846 * Receive data on a hook bypass
847 */
848static int
849ng_ppp_rcvdata_bypass(hook_p hook, item_p item)
850{
851	uint16_t linkNum;
852	uint16_t proto;
853	struct mbuf *m;
854
855	NGI_GET_M(item, m);
856	if (m->m_pkthdr.len < 4) {
857		NG_FREE_ITEM(item);
858		return (EINVAL);
859	}
860	if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
861		NG_FREE_ITEM(item);
862		return (ENOBUFS);
863	}
864	linkNum = ntohs(mtod(m, uint16_t *)[0]);
865	proto = ntohs(mtod(m, uint16_t *)[1]);
866	m_adj(m, 4);
867	NGI_M(item) = m;
868
869	if (linkNum == NG_PPP_BUNDLE_LINKNUM)
870		return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, proto));
871	else
872		return (ng_ppp_link_xmit(NG_HOOK_NODE(hook), item, proto,
873		    linkNum, 0));
874}
875
876static int
877ng_ppp_bypass(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
878{
879	const priv_p priv = NG_NODE_PRIVATE(node);
880	uint16_t hdr[2];
881	struct mbuf *m;
882	int error;
883
884	if (priv->hooks[HOOK_INDEX_BYPASS] == NULL) {
885	    NG_FREE_ITEM(item);
886	    return (ENXIO);
887	}
888
889	/* Add 4-byte bypass header. */
890	hdr[0] = htons(linkNum);
891	hdr[1] = htons(proto);
892
893	NGI_GET_M(item, m);
894	if ((m = ng_ppp_prepend(m, &hdr, 4)) == NULL) {
895		NG_FREE_ITEM(item);
896		return (ENOBUFS);
897	}
898	NGI_M(item) = m;
899
900	/* Send packet out hook. */
901	NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_BYPASS]);
902	return (error);
903}
904
905static int
906ng_ppp_proto_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
907{
908	const priv_p priv = NG_NODE_PRIVATE(node);
909	hook_p outHook = NULL;
910	int error;
911
912	switch (proto) {
913	    case PROT_IP:
914		if (priv->conf.enableIP)
915		    outHook = priv->hooks[HOOK_INDEX_INET];
916		break;
917	    case PROT_IPV6:
918		if (priv->conf.enableIPv6)
919		    outHook = priv->hooks[HOOK_INDEX_IPV6];
920		break;
921	    case PROT_ATALK:
922		if (priv->conf.enableAtalk)
923		    outHook = priv->hooks[HOOK_INDEX_ATALK];
924		break;
925	    case PROT_IPX:
926		if (priv->conf.enableIPX)
927		    outHook = priv->hooks[HOOK_INDEX_IPX];
928		break;
929	}
930
931	if (outHook == NULL)
932		return (ng_ppp_bypass(node, item, proto, linkNum));
933
934	/* Send packet out hook. */
935	NG_FWD_ITEM_HOOK(error, item, outHook);
936	return (error);
937}
938
939/*
940 * Header compression layer
941 */
942
943static int
944ng_ppp_hcomp_xmit(node_p node, item_p item, uint16_t proto)
945{
946	const priv_p priv = NG_NODE_PRIVATE(node);
947
948	if (proto == PROT_IP &&
949	    priv->conf.enableVJCompression &&
950	    priv->vjCompHooked) {
951		int error;
952
953		/* Send packet out hook. */
954		NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_VJC_IP]);
955		return (error);
956	}
957
958	return (ng_ppp_comp_xmit(node, item, proto));
959}
960
961/*
962 * Receive data on a hook vjc_comp.
963 */
964static int
965ng_ppp_rcvdata_vjc_comp(hook_p hook, item_p item)
966{
967	const node_p node = NG_HOOK_NODE(hook);
968	const priv_p priv = NG_NODE_PRIVATE(node);
969
970	if (!priv->conf.enableVJCompression) {
971		NG_FREE_ITEM(item);
972		return (ENXIO);
973	}
974	return (ng_ppp_comp_xmit(node, item, PROT_VJCOMP));
975}
976
977/*
978 * Receive data on a hook vjc_uncomp.
979 */
980static int
981ng_ppp_rcvdata_vjc_uncomp(hook_p hook, item_p item)
982{
983	const node_p node = NG_HOOK_NODE(hook);
984	const priv_p priv = NG_NODE_PRIVATE(node);
985
986	if (!priv->conf.enableVJCompression) {
987		NG_FREE_ITEM(item);
988		return (ENXIO);
989	}
990	return (ng_ppp_comp_xmit(node, item, PROT_VJUNCOMP));
991}
992
993/*
994 * Receive data on a hook vjc_vjip.
995 */
996static int
997ng_ppp_rcvdata_vjc_vjip(hook_p hook, item_p item)
998{
999	const node_p node = NG_HOOK_NODE(hook);
1000	const priv_p priv = NG_NODE_PRIVATE(node);
1001
1002	if (!priv->conf.enableVJCompression) {
1003		NG_FREE_ITEM(item);
1004		return (ENXIO);
1005	}
1006	return (ng_ppp_comp_xmit(node, item, PROT_IP));
1007}
1008
1009static int
1010ng_ppp_hcomp_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1011{
1012	const priv_p priv = NG_NODE_PRIVATE(node);
1013
1014	if (priv->conf.enableVJDecompression && priv->vjCompHooked) {
1015		hook_p outHook = NULL;
1016
1017		switch (proto) {
1018		    case PROT_VJCOMP:
1019			outHook = priv->hooks[HOOK_INDEX_VJC_COMP];
1020			break;
1021		    case PROT_VJUNCOMP:
1022			outHook = priv->hooks[HOOK_INDEX_VJC_UNCOMP];
1023			break;
1024		}
1025
1026		if (outHook) {
1027			int error;
1028
1029			/* Send packet out hook. */
1030			NG_FWD_ITEM_HOOK(error, item, outHook);
1031			return (error);
1032		}
1033	}
1034
1035	return (ng_ppp_proto_recv(node, item, proto, linkNum));
1036}
1037
1038/*
1039 * Receive data on a hook vjc_ip.
1040 */
1041static int
1042ng_ppp_rcvdata_vjc_ip(hook_p hook, item_p item)
1043{
1044	const node_p node = NG_HOOK_NODE(hook);
1045	const priv_p priv = NG_NODE_PRIVATE(node);
1046
1047	if (!priv->conf.enableVJDecompression) {
1048		NG_FREE_ITEM(item);
1049		return (ENXIO);
1050	}
1051	return (ng_ppp_proto_recv(node, item, PROT_IP, NG_PPP_BUNDLE_LINKNUM));
1052}
1053
1054/*
1055 * Compression layer
1056 */
1057
1058static int
1059ng_ppp_comp_xmit(node_p node, item_p item, uint16_t proto)
1060{
1061	const priv_p priv = NG_NODE_PRIVATE(node);
1062
1063	if (priv->conf.enableCompression &&
1064	    proto < 0x4000 &&
1065	    proto != PROT_COMPD &&
1066	    proto != PROT_CRYPTD &&
1067	    priv->hooks[HOOK_INDEX_COMPRESS] != NULL) {
1068	        struct mbuf *m;
1069		int error;
1070
1071	        NGI_GET_M(item, m);
1072		if ((m = ng_ppp_addproto(m, proto, 0)) == NULL) {
1073			NG_FREE_ITEM(item);
1074			return (ENOBUFS);
1075		}
1076		NGI_M(item) = m;
1077
1078		/* Send packet out hook. */
1079		NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_COMPRESS]);
1080		return (error);
1081	}
1082
1083	return (ng_ppp_crypt_xmit(node, item, proto));
1084}
1085
1086/*
1087 * Receive data on a hook compress.
1088 */
1089static int
1090ng_ppp_rcvdata_compress(hook_p hook, item_p item)
1091{
1092	const node_p node = NG_HOOK_NODE(hook);
1093	const priv_p priv = NG_NODE_PRIVATE(node);
1094	uint16_t proto;
1095
1096	switch (priv->conf.enableCompression) {
1097	    case NG_PPP_COMPRESS_NONE:
1098		NG_FREE_ITEM(item);
1099		return (ENXIO);
1100	    case NG_PPP_COMPRESS_FULL:
1101		{
1102			struct mbuf *m;
1103
1104			NGI_GET_M(item, m);
1105			if ((m = ng_ppp_cutproto(m, &proto)) == NULL) {
1106				NG_FREE_ITEM(item);
1107				return (EIO);
1108			}
1109			NGI_M(item) = m;
1110			if (!PROT_VALID(proto)) {
1111				NG_FREE_ITEM(item);
1112				return (EIO);
1113			}
1114		}
1115		break;
1116	    default:
1117		proto = PROT_COMPD;
1118		break;
1119	}
1120	return (ng_ppp_crypt_xmit(node, item, proto));
1121}
1122
1123static int
1124ng_ppp_comp_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1125{
1126	const priv_p priv = NG_NODE_PRIVATE(node);
1127
1128	if (proto < 0x4000 &&
1129	    ((proto == PROT_COMPD && priv->conf.enableDecompression) ||
1130	    priv->conf.enableDecompression == NG_PPP_DECOMPRESS_FULL) &&
1131	    priv->hooks[HOOK_INDEX_DECOMPRESS] != NULL) {
1132		int error;
1133
1134		if (priv->conf.enableDecompression == NG_PPP_DECOMPRESS_FULL) {
1135			struct mbuf *m;
1136			NGI_GET_M(item, m);
1137			if ((m = ng_ppp_addproto(m, proto, 0)) == NULL) {
1138				NG_FREE_ITEM(item);
1139				return (EIO);
1140			}
1141			NGI_M(item) = m;
1142		}
1143
1144		/* Send packet out hook. */
1145		NG_FWD_ITEM_HOOK(error, item,
1146		    priv->hooks[HOOK_INDEX_DECOMPRESS]);
1147		return (error);
1148	} else if (proto == PROT_COMPD) {
1149		/* Disabled protos MUST be silently discarded, but
1150		 * unsupported MUST not. Let user-level decide this. */
1151		return (ng_ppp_bypass(node, item, proto, linkNum));
1152	}
1153
1154	return (ng_ppp_hcomp_recv(node, item, proto, linkNum));
1155}
1156
1157/*
1158 * Receive data on a hook decompress.
1159 */
1160static int
1161ng_ppp_rcvdata_decompress(hook_p hook, item_p item)
1162{
1163	const node_p node = NG_HOOK_NODE(hook);
1164	const priv_p priv = NG_NODE_PRIVATE(node);
1165	uint16_t proto;
1166	struct mbuf *m;
1167
1168	if (!priv->conf.enableDecompression) {
1169		NG_FREE_ITEM(item);
1170		return (ENXIO);
1171	}
1172	NGI_GET_M(item, m);
1173	if ((m = ng_ppp_cutproto(m, &proto)) == NULL) {
1174	        NG_FREE_ITEM(item);
1175	        return (EIO);
1176	}
1177	NGI_M(item) = m;
1178	if (!PROT_VALID(proto)) {
1179		priv->bundleStats.badProtos++;
1180		NG_FREE_ITEM(item);
1181		return (EIO);
1182	}
1183	return (ng_ppp_hcomp_recv(node, item, proto, NG_PPP_BUNDLE_LINKNUM));
1184}
1185
1186/*
1187 * Encryption layer
1188 */
1189
1190static int
1191ng_ppp_crypt_xmit(node_p node, item_p item, uint16_t proto)
1192{
1193	const priv_p priv = NG_NODE_PRIVATE(node);
1194
1195	if (priv->conf.enableEncryption &&
1196	    proto < 0x4000 &&
1197	    proto != PROT_CRYPTD &&
1198	    priv->hooks[HOOK_INDEX_ENCRYPT] != NULL) {
1199		struct mbuf *m;
1200		int error;
1201
1202	        NGI_GET_M(item, m);
1203		if ((m = ng_ppp_addproto(m, proto, 0)) == NULL) {
1204			NG_FREE_ITEM(item);
1205			return (ENOBUFS);
1206		}
1207		NGI_M(item) = m;
1208
1209		/* Send packet out hook. */
1210		NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_ENCRYPT]);
1211		return (error);
1212	}
1213
1214	return (ng_ppp_mp_xmit(node, item, proto));
1215}
1216
1217/*
1218 * Receive data on a hook encrypt.
1219 */
1220static int
1221ng_ppp_rcvdata_encrypt(hook_p hook, item_p item)
1222{
1223	const node_p node = NG_HOOK_NODE(hook);
1224	const priv_p priv = NG_NODE_PRIVATE(node);
1225
1226	if (!priv->conf.enableEncryption) {
1227		NG_FREE_ITEM(item);
1228		return (ENXIO);
1229	}
1230	return (ng_ppp_mp_xmit(node, item, PROT_CRYPTD));
1231}
1232
1233static int
1234ng_ppp_crypt_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1235{
1236	const priv_p priv = NG_NODE_PRIVATE(node);
1237
1238	if (proto == PROT_CRYPTD) {
1239		if (priv->conf.enableDecryption &&
1240		    priv->hooks[HOOK_INDEX_DECRYPT] != NULL) {
1241			int error;
1242
1243			/* Send packet out hook. */
1244			NG_FWD_ITEM_HOOK(error, item,
1245			    priv->hooks[HOOK_INDEX_DECRYPT]);
1246			return (error);
1247		} else {
1248			/* Disabled protos MUST be silently discarded, but
1249			 * unsupported MUST not. Let user-level decide this. */
1250			return (ng_ppp_bypass(node, item, proto, linkNum));
1251		}
1252	}
1253
1254	return (ng_ppp_comp_recv(node, item, proto, linkNum));
1255}
1256
1257/*
1258 * Receive data on a hook decrypt.
1259 */
1260static int
1261ng_ppp_rcvdata_decrypt(hook_p hook, item_p item)
1262{
1263	const node_p node = NG_HOOK_NODE(hook);
1264	const priv_p priv = NG_NODE_PRIVATE(node);
1265	uint16_t proto;
1266	struct mbuf *m;
1267
1268	if (!priv->conf.enableDecryption) {
1269		NG_FREE_ITEM(item);
1270		return (ENXIO);
1271	}
1272	NGI_GET_M(item, m);
1273	if ((m = ng_ppp_cutproto(m, &proto)) == NULL) {
1274	        NG_FREE_ITEM(item);
1275	        return (EIO);
1276	}
1277	NGI_M(item) = m;
1278	if (!PROT_VALID(proto)) {
1279		priv->bundleStats.badProtos++;
1280		NG_FREE_ITEM(item);
1281		return (EIO);
1282	}
1283	return (ng_ppp_comp_recv(node, item, proto, NG_PPP_BUNDLE_LINKNUM));
1284}
1285
1286/*
1287 * Link layer
1288 */
1289
1290static int
1291ng_ppp_link_xmit(node_p node, item_p item, uint16_t proto, uint16_t linkNum, int plen)
1292{
1293	const priv_p priv = NG_NODE_PRIVATE(node);
1294	struct ng_ppp_link *link;
1295	int len, error;
1296	struct mbuf *m;
1297	uint16_t mru;
1298
1299	/* Check if link correct. */
1300	if (linkNum >= NG_PPP_MAX_LINKS) {
1301		ERROUT(ENETDOWN);
1302	}
1303
1304	/* Get link pointer (optimization). */
1305	link = &priv->links[linkNum];
1306
1307	/* Check link status (if real). */
1308	if (link->hook == NULL) {
1309		ERROUT(ENETDOWN);
1310	}
1311
1312	/* Extract mbuf. */
1313	NGI_GET_M(item, m);
1314
1315	/* Check peer's MRU for this link. */
1316	mru = link->conf.mru;
1317	if (mru != 0 && m->m_pkthdr.len > mru) {
1318		NG_FREE_M(m);
1319		ERROUT(EMSGSIZE);
1320	}
1321
1322	/* Prepend protocol number, possibly compressed. */
1323	if ((m = ng_ppp_addproto(m, proto, link->conf.enableProtoComp)) ==
1324	    NULL) {
1325		ERROUT(ENOBUFS);
1326	}
1327
1328	/* Prepend address and control field (unless compressed). */
1329	if (proto == PROT_LCP || !link->conf.enableACFComp) {
1330		if ((m = ng_ppp_prepend(m, &ng_ppp_acf, 2)) == NULL)
1331			ERROUT(ENOBUFS);
1332	}
1333
1334	/* Deliver frame. */
1335	len = m->m_pkthdr.len;
1336	NG_FWD_NEW_DATA(error, item, link->hook, m);
1337
1338	mtx_lock(&priv->xmtx);
1339
1340	/* Update link stats. */
1341	link->stats.xmitFrames++;
1342	link->stats.xmitOctets += len;
1343
1344	/* Update bundle stats. */
1345	if (plen > 0) {
1346	    priv->bundleStats.xmitFrames++;
1347	    priv->bundleStats.xmitOctets += plen;
1348	}
1349
1350	/* Update 'bytes in queue' counter. */
1351	if (error == 0) {
1352		/* bytesInQueue and lastWrite required only for mp_strategy. */
1353		if (priv->conf.enableMultilink && !priv->allLinksEqual &&
1354		    !priv->conf.enableRoundRobin) {
1355			/* If queue was empty, then mark this time. */
1356			if (link->bytesInQueue == 0)
1357				getmicrouptime(&link->lastWrite);
1358			link->bytesInQueue += len + MP_AVERAGE_LINK_OVERHEAD;
1359			/* Limit max queue length to 50 pkts. BW can be defined
1360		    	   incorrectly and link may not signal overload. */
1361			if (link->bytesInQueue > 50 * 1600)
1362				link->bytesInQueue = 50 * 1600;
1363		}
1364	}
1365	mtx_unlock(&priv->xmtx);
1366	return (error);
1367
1368done:
1369	NG_FREE_ITEM(item);
1370	return (error);
1371}
1372
1373/*
1374 * Receive data on a hook linkX.
1375 */
1376static int
1377ng_ppp_rcvdata(hook_p hook, item_p item)
1378{
1379	const node_p node = NG_HOOK_NODE(hook);
1380	const priv_p priv = NG_NODE_PRIVATE(node);
1381	const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
1382	const uint16_t linkNum = (uint16_t)~index;
1383	struct ng_ppp_link * const link = &priv->links[linkNum];
1384	uint16_t proto;
1385	struct mbuf *m;
1386	int error = 0;
1387
1388	KASSERT(linkNum < NG_PPP_MAX_LINKS,
1389	    ("%s: bogus index 0x%x", __func__, index));
1390
1391	NGI_GET_M(item, m);
1392
1393	mtx_lock(&priv->rmtx);
1394
1395	/* Stats */
1396	link->stats.recvFrames++;
1397	link->stats.recvOctets += m->m_pkthdr.len;
1398
1399	/* Strip address and control fields, if present. */
1400	if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL)
1401		ERROUT(ENOBUFS);
1402	if (bcmp(mtod(m, uint8_t *), &ng_ppp_acf, 2) == 0)
1403		m_adj(m, 2);
1404
1405	/* Get protocol number */
1406	if ((m = ng_ppp_cutproto(m, &proto)) == NULL)
1407		ERROUT(ENOBUFS);
1408	NGI_M(item) = m; 	/* Put changed m back into item. */
1409
1410	if (!PROT_VALID(proto)) {
1411		link->stats.badProtos++;
1412		ERROUT(EIO);
1413	}
1414
1415	/* LCP packets must go directly to bypass. */
1416	if (proto >= 0xB000) {
1417		mtx_unlock(&priv->rmtx);
1418		return (ng_ppp_bypass(node, item, proto, linkNum));
1419	}
1420
1421	/* Other packets are denied on a disabled link. */
1422	if (!link->conf.enableLink)
1423		ERROUT(ENXIO);
1424
1425	/* Proceed to multilink layer. Mutex will be unlocked inside. */
1426	error = ng_ppp_mp_recv(node, item, proto, linkNum);
1427	mtx_assert(&priv->rmtx, MA_NOTOWNED);
1428	return (error);
1429
1430done:
1431	mtx_unlock(&priv->rmtx);
1432	NG_FREE_ITEM(item);
1433	return (error);
1434}
1435
1436/*
1437 * Multilink layer
1438 */
1439
1440/*
1441 * Handle an incoming multi-link fragment
1442 *
1443 * The fragment reassembly algorithm is somewhat complex. This is mainly
1444 * because we are required not to reorder the reconstructed packets, yet
1445 * fragments are only guaranteed to arrive in order on a per-link basis.
1446 * In other words, when we have a complete packet ready, but the previous
1447 * packet is still incomplete, we have to decide between delivering the
1448 * complete packet and throwing away the incomplete one, or waiting to
1449 * see if the remainder of the incomplete one arrives, at which time we
1450 * can deliver both packets, in order.
1451 *
1452 * This problem is exacerbated by "sequence number slew", which is when
1453 * the sequence numbers coming in from different links are far apart from
1454 * each other. In particular, certain unnamed equipment (*cough* Ascend)
1455 * has been seen to generate sequence number slew of up to 10 on an ISDN
1456 * 2B-channel MP link. There is nothing invalid about sequence number slew
1457 * but it makes the reasssembly process have to work harder.
1458 *
1459 * However, the peer is required to transmit fragments in order on each
1460 * link. That means if we define MSEQ as the minimum over all links of
1461 * the highest sequence number received on that link, then we can always
1462 * give up any hope of receiving a fragment with sequence number < MSEQ in
1463 * the future (all of this using 'wraparound' sequence number space).
1464 * Therefore we can always immediately throw away incomplete packets
1465 * missing fragments with sequence numbers < MSEQ.
1466 *
1467 * Here is an overview of our algorithm:
1468 *
1469 *    o Received fragments are inserted into a queue, for which we
1470 *	maintain these invariants between calls to this function:
1471 *
1472 *	- Fragments are ordered in the queue by sequence number
1473 *	- If a complete packet is at the head of the queue, then
1474 *	  the first fragment in the packet has seq# > MSEQ + 1
1475 *	  (otherwise, we could deliver it immediately)
1476 *	- If any fragments have seq# < MSEQ, then they are necessarily
1477 *	  part of a packet whose missing seq#'s are all > MSEQ (otherwise,
1478 *	  we can throw them away because they'll never be completed)
1479 *	- The queue contains at most MP_MAX_QUEUE_LEN fragments
1480 *
1481 *    o We have a periodic timer that checks the queue for the first
1482 *	complete packet that has been sitting in the queue "too long".
1483 *	When one is detected, all previous (incomplete) fragments are
1484 *	discarded, their missing fragments are declared lost and MSEQ
1485 *	is increased.
1486 *
1487 *    o If we recieve a fragment with seq# < MSEQ, we throw it away
1488 *	because we've already delcared it lost.
1489 *
1490 * This assumes linkNum != NG_PPP_BUNDLE_LINKNUM.
1491 */
1492static int
1493ng_ppp_mp_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1494{
1495	const priv_p priv = NG_NODE_PRIVATE(node);
1496	struct ng_ppp_link *const link = &priv->links[linkNum];
1497	struct ng_ppp_frag *frag;
1498	struct ng_ppp_frag *qent;
1499	int i, diff, inserted;
1500	struct mbuf *m;
1501	int	error = 0;
1502
1503	if ((!priv->conf.enableMultilink) || proto != PROT_MP) {
1504		/* Stats */
1505		priv->bundleStats.recvFrames++;
1506		priv->bundleStats.recvOctets += NGI_M(item)->m_pkthdr.len;
1507
1508		mtx_unlock(&priv->rmtx);
1509		return (ng_ppp_crypt_recv(node, item, proto, linkNum));
1510	}
1511
1512	NGI_GET_M(item, m);
1513	NG_FREE_ITEM(item);
1514
1515	/* Get a new frag struct from the free queue */
1516	if ((frag = TAILQ_FIRST(&priv->fragsfree)) == NULL) {
1517		printf("No free fragments headers in ng_ppp!\n");
1518		NG_FREE_M(m);
1519		goto process;
1520	}
1521
1522	/* Extract fragment information from MP header */
1523	if (priv->conf.recvShortSeq) {
1524		uint16_t shdr;
1525
1526		if (m->m_pkthdr.len < 2) {
1527			link->stats.runts++;
1528			NG_FREE_M(m);
1529			ERROUT(EINVAL);
1530		}
1531		if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL)
1532			ERROUT(ENOBUFS);
1533
1534		shdr = ntohs(*mtod(m, uint16_t *));
1535		frag->seq = MP_SHORT_EXTEND(shdr);
1536		frag->first = (shdr & MP_SHORT_FIRST_FLAG) != 0;
1537		frag->last = (shdr & MP_SHORT_LAST_FLAG) != 0;
1538		diff = MP_SHORT_SEQ_DIFF(frag->seq, priv->mseq);
1539		m_adj(m, 2);
1540	} else {
1541		uint32_t lhdr;
1542
1543		if (m->m_pkthdr.len < 4) {
1544			link->stats.runts++;
1545			NG_FREE_M(m);
1546			ERROUT(EINVAL);
1547		}
1548		if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL)
1549			ERROUT(ENOBUFS);
1550
1551		lhdr = ntohl(*mtod(m, uint32_t *));
1552		frag->seq = MP_LONG_EXTEND(lhdr);
1553		frag->first = (lhdr & MP_LONG_FIRST_FLAG) != 0;
1554		frag->last = (lhdr & MP_LONG_LAST_FLAG) != 0;
1555		diff = MP_LONG_SEQ_DIFF(frag->seq, priv->mseq);
1556		m_adj(m, 4);
1557	}
1558	frag->data = m;
1559	getmicrouptime(&frag->timestamp);
1560
1561	/* If sequence number is < MSEQ, we've already declared this
1562	   fragment as lost, so we have no choice now but to drop it */
1563	if (diff < 0) {
1564		link->stats.dropFragments++;
1565		NG_FREE_M(m);
1566		ERROUT(0);
1567	}
1568
1569	/* Update highest received sequence number on this link and MSEQ */
1570	priv->mseq = link->seq = frag->seq;
1571	for (i = 0; i < priv->numActiveLinks; i++) {
1572		struct ng_ppp_link *const alink =
1573		    &priv->links[priv->activeLinks[i]];
1574
1575		if (MP_RECV_SEQ_DIFF(priv, alink->seq, priv->mseq) < 0)
1576			priv->mseq = alink->seq;
1577	}
1578
1579	/* Remove frag struct from free queue. */
1580	TAILQ_REMOVE(&priv->fragsfree, frag, f_qent);
1581
1582	/* Add fragment to queue, which is sorted by sequence number */
1583	inserted = 0;
1584	TAILQ_FOREACH_REVERSE(qent, &priv->frags, ng_ppp_fraglist, f_qent) {
1585		diff = MP_RECV_SEQ_DIFF(priv, frag->seq, qent->seq);
1586		if (diff > 0) {
1587			TAILQ_INSERT_AFTER(&priv->frags, qent, frag, f_qent);
1588			inserted = 1;
1589			break;
1590		} else if (diff == 0) {	     /* should never happen! */
1591			link->stats.dupFragments++;
1592			NG_FREE_M(frag->data);
1593			TAILQ_INSERT_HEAD(&priv->fragsfree, frag, f_qent);
1594			ERROUT(EINVAL);
1595		}
1596	}
1597	if (!inserted)
1598		TAILQ_INSERT_HEAD(&priv->frags, frag, f_qent);
1599
1600process:
1601	/* Process the queue */
1602	/* NOTE: rmtx will be unlocked for sending time! */
1603	error = ng_ppp_frag_process(node);
1604
1605done:
1606	mtx_unlock(&priv->rmtx);
1607	return (error);
1608}
1609
1610/************************************************************************
1611			HELPER STUFF
1612 ************************************************************************/
1613
1614/*
1615 * If new mseq > current then set it and update all active links
1616 */
1617static void
1618ng_ppp_bump_mseq(node_p node, int32_t new_mseq)
1619{
1620	const priv_p priv = NG_NODE_PRIVATE(node);
1621	int i;
1622
1623	if (MP_RECV_SEQ_DIFF(priv, priv->mseq, new_mseq) < 0) {
1624		priv->mseq = new_mseq;
1625		for (i = 0; i < priv->numActiveLinks; i++) {
1626			struct ng_ppp_link *const alink =
1627			    &priv->links[priv->activeLinks[i]];
1628
1629			if (MP_RECV_SEQ_DIFF(priv,
1630			    alink->seq, new_mseq) < 0)
1631				alink->seq = new_mseq;
1632		}
1633	}
1634}
1635
1636/*
1637 * Examine our list of fragments, and determine if there is a
1638 * complete and deliverable packet at the head of the list.
1639 * Return 1 if so, zero otherwise.
1640 */
1641static int
1642ng_ppp_check_packet(node_p node)
1643{
1644	const priv_p priv = NG_NODE_PRIVATE(node);
1645	struct ng_ppp_frag *qent, *qnext;
1646
1647	/* Check for empty queue */
1648	if (TAILQ_EMPTY(&priv->frags))
1649		return (0);
1650
1651	/* Check first fragment is the start of a deliverable packet */
1652	qent = TAILQ_FIRST(&priv->frags);
1653	if (!qent->first || MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) > 1)
1654		return (0);
1655
1656	/* Check that all the fragments are there */
1657	while (!qent->last) {
1658		qnext = TAILQ_NEXT(qent, f_qent);
1659		if (qnext == NULL)	/* end of queue */
1660			return (0);
1661		if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq))
1662			return (0);
1663		qent = qnext;
1664	}
1665
1666	/* Got one */
1667	return (1);
1668}
1669
1670/*
1671 * Pull a completed packet off the head of the incoming fragment queue.
1672 * This assumes there is a completed packet there to pull off.
1673 */
1674static void
1675ng_ppp_get_packet(node_p node, struct mbuf **mp)
1676{
1677	const priv_p priv = NG_NODE_PRIVATE(node);
1678	struct ng_ppp_frag *qent, *qnext;
1679	struct mbuf *m = NULL, *tail;
1680
1681	qent = TAILQ_FIRST(&priv->frags);
1682	KASSERT(!TAILQ_EMPTY(&priv->frags) && qent->first,
1683	    ("%s: no packet", __func__));
1684	for (tail = NULL; qent != NULL; qent = qnext) {
1685		qnext = TAILQ_NEXT(qent, f_qent);
1686		KASSERT(!TAILQ_EMPTY(&priv->frags),
1687		    ("%s: empty q", __func__));
1688		TAILQ_REMOVE(&priv->frags, qent, f_qent);
1689		if (tail == NULL)
1690			tail = m = qent->data;
1691		else {
1692			m->m_pkthdr.len += qent->data->m_pkthdr.len;
1693			tail->m_next = qent->data;
1694		}
1695		while (tail->m_next != NULL)
1696			tail = tail->m_next;
1697		if (qent->last) {
1698			qnext = NULL;
1699			/* Bump MSEQ if necessary */
1700			ng_ppp_bump_mseq(node, qent->seq);
1701		}
1702		TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1703	}
1704	*mp = m;
1705}
1706
1707/*
1708 * Trim fragments from the queue whose packets can never be completed.
1709 * This assumes a complete packet is NOT at the beginning of the queue.
1710 * Returns 1 if fragments were removed, zero otherwise.
1711 */
1712static int
1713ng_ppp_frag_trim(node_p node)
1714{
1715	const priv_p priv = NG_NODE_PRIVATE(node);
1716	struct ng_ppp_frag *qent, *qnext = NULL;
1717	int removed = 0;
1718
1719	/* Scan for "dead" fragments and remove them */
1720	while (1) {
1721		int dead = 0;
1722
1723		/* If queue is empty, we're done */
1724		if (TAILQ_EMPTY(&priv->frags))
1725			break;
1726
1727		/* Determine whether first fragment can ever be completed */
1728		TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1729			if (MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) >= 0)
1730				break;
1731			qnext = TAILQ_NEXT(qent, f_qent);
1732			KASSERT(qnext != NULL,
1733			    ("%s: last frag < MSEQ?", __func__));
1734			if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq)
1735			    || qent->last || qnext->first) {
1736				dead = 1;
1737				break;
1738			}
1739		}
1740		if (!dead)
1741			break;
1742
1743		/* Remove fragment and all others in the same packet */
1744		while ((qent = TAILQ_FIRST(&priv->frags)) != qnext) {
1745			KASSERT(!TAILQ_EMPTY(&priv->frags),
1746			    ("%s: empty q", __func__));
1747			priv->bundleStats.dropFragments++;
1748			TAILQ_REMOVE(&priv->frags, qent, f_qent);
1749			NG_FREE_M(qent->data);
1750			TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1751			removed = 1;
1752		}
1753	}
1754	return (removed);
1755}
1756
1757/*
1758 * Drop fragments on queue overflow.
1759 * Returns 1 if fragments were removed, zero otherwise.
1760 */
1761static int
1762ng_ppp_frag_drop(node_p node)
1763{
1764	const priv_p priv = NG_NODE_PRIVATE(node);
1765
1766	/* Check queue length */
1767	if (TAILQ_EMPTY(&priv->fragsfree)) {
1768		struct ng_ppp_frag *qent;
1769
1770		/* Get oldest fragment */
1771		KASSERT(!TAILQ_EMPTY(&priv->frags),
1772		    ("%s: empty q", __func__));
1773		qent = TAILQ_FIRST(&priv->frags);
1774
1775		/* Bump MSEQ if necessary */
1776		ng_ppp_bump_mseq(node, qent->seq);
1777
1778		/* Drop it */
1779		priv->bundleStats.dropFragments++;
1780		TAILQ_REMOVE(&priv->frags, qent, f_qent);
1781		NG_FREE_M(qent->data);
1782		TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1783
1784		return (1);
1785	}
1786	return (0);
1787}
1788
1789/*
1790 * Run the queue, restoring the queue invariants
1791 */
1792static int
1793ng_ppp_frag_process(node_p node)
1794{
1795	const priv_p priv = NG_NODE_PRIVATE(node);
1796	struct mbuf *m;
1797	item_p item;
1798	uint16_t proto;
1799
1800	do {
1801		/* Deliver any deliverable packets */
1802		while (ng_ppp_check_packet(node)) {
1803			ng_ppp_get_packet(node, &m);
1804			if ((m = ng_ppp_cutproto(m, &proto)) == NULL)
1805				continue;
1806			if (!PROT_VALID(proto)) {
1807				priv->bundleStats.badProtos++;
1808				NG_FREE_M(m);
1809				continue;
1810			}
1811			if ((item = ng_package_data(m, NG_NOFLAGS)) != NULL) {
1812				/* Stats */
1813				priv->bundleStats.recvFrames++;
1814				priv->bundleStats.recvOctets +=
1815				    NGI_M(item)->m_pkthdr.len;
1816
1817				/* Drop mutex for the sending time.
1818				 * Priv may change, but we are ready!
1819				 */
1820				mtx_unlock(&priv->rmtx);
1821				ng_ppp_crypt_recv(node, item, proto,
1822					NG_PPP_BUNDLE_LINKNUM);
1823				mtx_lock(&priv->rmtx);
1824			}
1825		}
1826	  /* Delete dead fragments and try again */
1827	} while (ng_ppp_frag_trim(node) || ng_ppp_frag_drop(node));
1828
1829	/* Done */
1830	return (0);
1831}
1832
1833/*
1834 * Check for 'stale' completed packets that need to be delivered
1835 *
1836 * If a link goes down or has a temporary failure, MSEQ can get
1837 * "stuck", because no new incoming fragments appear on that link.
1838 * This can cause completed packets to never get delivered if
1839 * their sequence numbers are all > MSEQ + 1.
1840 *
1841 * This routine checks how long all of the completed packets have
1842 * been sitting in the queue, and if too long, removes fragments
1843 * from the queue and increments MSEQ to allow them to be delivered.
1844 */
1845static void
1846ng_ppp_frag_checkstale(node_p node)
1847{
1848	const priv_p priv = NG_NODE_PRIVATE(node);
1849	struct ng_ppp_frag *qent, *beg, *end;
1850	struct timeval now, age;
1851	struct mbuf *m;
1852	int seq;
1853	item_p item;
1854	int endseq;
1855	uint16_t proto;
1856
1857	now.tv_sec = 0;			/* uninitialized state */
1858	while (1) {
1859
1860		/* If queue is empty, we're done */
1861		if (TAILQ_EMPTY(&priv->frags))
1862			break;
1863
1864		/* Find the first complete packet in the queue */
1865		beg = end = NULL;
1866		seq = TAILQ_FIRST(&priv->frags)->seq;
1867		TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1868			if (qent->first)
1869				beg = qent;
1870			else if (qent->seq != seq)
1871				beg = NULL;
1872			if (beg != NULL && qent->last) {
1873				end = qent;
1874				break;
1875			}
1876			seq = MP_NEXT_RECV_SEQ(priv, seq);
1877		}
1878
1879		/* If none found, exit */
1880		if (end == NULL)
1881			break;
1882
1883		/* Get current time (we assume we've been up for >= 1 second) */
1884		if (now.tv_sec == 0)
1885			getmicrouptime(&now);
1886
1887		/* Check if packet has been queued too long */
1888		age = now;
1889		timevalsub(&age, &beg->timestamp);
1890		if (timevalcmp(&age, &ng_ppp_max_staleness, < ))
1891			break;
1892
1893		/* Throw away junk fragments in front of the completed packet */
1894		while ((qent = TAILQ_FIRST(&priv->frags)) != beg) {
1895			KASSERT(!TAILQ_EMPTY(&priv->frags),
1896			    ("%s: empty q", __func__));
1897			priv->bundleStats.dropFragments++;
1898			TAILQ_REMOVE(&priv->frags, qent, f_qent);
1899			NG_FREE_M(qent->data);
1900			TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1901		}
1902
1903		/* Extract completed packet */
1904		endseq = end->seq;
1905		ng_ppp_get_packet(node, &m);
1906
1907		if ((m = ng_ppp_cutproto(m, &proto)) == NULL)
1908			continue;
1909		if (!PROT_VALID(proto)) {
1910			priv->bundleStats.badProtos++;
1911			NG_FREE_M(m);
1912			continue;
1913		}
1914
1915		/* Deliver packet */
1916		if ((item = ng_package_data(m, NG_NOFLAGS)) != NULL) {
1917			/* Stats */
1918			priv->bundleStats.recvFrames++;
1919			priv->bundleStats.recvOctets += NGI_M(item)->m_pkthdr.len;
1920
1921			ng_ppp_crypt_recv(node, item, proto,
1922				NG_PPP_BUNDLE_LINKNUM);
1923		}
1924	}
1925}
1926
1927/*
1928 * Periodically call ng_ppp_frag_checkstale()
1929 */
1930static void
1931ng_ppp_frag_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1932{
1933	/* XXX: is this needed? */
1934	if (NG_NODE_NOT_VALID(node))
1935		return;
1936
1937	/* Scan the fragment queue */
1938	ng_ppp_frag_checkstale(node);
1939
1940	/* Start timer again */
1941	ng_ppp_start_frag_timer(node);
1942}
1943
1944/*
1945 * Deliver a frame out on the bundle, i.e., figure out how to fragment
1946 * the frame across the individual PPP links and do so.
1947 */
1948static int
1949ng_ppp_mp_xmit(node_p node, item_p item, uint16_t proto)
1950{
1951	const priv_p priv = NG_NODE_PRIVATE(node);
1952	const int hdr_len = priv->conf.xmitShortSeq ? 2 : 4;
1953	int distrib[NG_PPP_MAX_LINKS];
1954	int firstFragment;
1955	int activeLinkNum;
1956	struct mbuf *m;
1957	int	plen;
1958	int	frags;
1959	int32_t	seq;
1960
1961	/* At least one link must be active */
1962	if (priv->numActiveLinks == 0) {
1963		NG_FREE_ITEM(item);
1964		return (ENETDOWN);
1965	}
1966
1967	/* Save length for later stats. */
1968	plen = NGI_M(item)->m_pkthdr.len;
1969
1970	if (!priv->conf.enableMultilink) {
1971		return (ng_ppp_link_xmit(node, item, proto,
1972		    priv->activeLinks[0], plen));
1973	}
1974
1975	/* Extract mbuf. */
1976	NGI_GET_M(item, m);
1977
1978	/* Prepend protocol number, possibly compressed. */
1979	if ((m = ng_ppp_addproto(m, proto, 1)) == NULL) {
1980		NG_FREE_ITEM(item);
1981		return (ENOBUFS);
1982	}
1983
1984	/* Clear distribution plan */
1985	bzero(&distrib, priv->numActiveLinks * sizeof(distrib[0]));
1986
1987	mtx_lock(&priv->xmtx);
1988
1989	/* Round-robin strategy */
1990	if (priv->conf.enableRoundRobin) {
1991		activeLinkNum = priv->lastLink++ % priv->numActiveLinks;
1992		distrib[activeLinkNum] = m->m_pkthdr.len;
1993		goto deliver;
1994	}
1995
1996	/* Strategy when all links are equivalent (optimize the common case) */
1997	if (priv->allLinksEqual) {
1998		int	numFrags, fraction, remain;
1999		int	i;
2000
2001		/* Calculate optimal fragment count */
2002		numFrags = priv->numActiveLinks;
2003		if (numFrags > m->m_pkthdr.len / MP_MIN_FRAG_LEN)
2004		    numFrags = m->m_pkthdr.len / MP_MIN_FRAG_LEN;
2005		if (numFrags == 0)
2006		    numFrags = 1;
2007
2008		fraction = m->m_pkthdr.len / numFrags;
2009		remain = m->m_pkthdr.len - (fraction * numFrags);
2010
2011		/* Assign distribution */
2012		for (i = 0; i < numFrags; i++) {
2013			distrib[priv->lastLink++ % priv->numActiveLinks]
2014			    = fraction + (((remain--) > 0)?1:0);
2015		}
2016		goto deliver;
2017	}
2018
2019	/* Strategy when all links are not equivalent */
2020	ng_ppp_mp_strategy(node, m->m_pkthdr.len, distrib);
2021
2022deliver:
2023	/* Estimate fragments count */
2024	frags = 0;
2025	for (activeLinkNum = priv->numActiveLinks - 1;
2026	    activeLinkNum >= 0; activeLinkNum--) {
2027		const uint16_t linkNum = priv->activeLinks[activeLinkNum];
2028		struct ng_ppp_link *const link = &priv->links[linkNum];
2029
2030		frags += (distrib[activeLinkNum] + link->conf.mru - hdr_len - 1) /
2031		    (link->conf.mru - hdr_len);
2032	}
2033
2034	/* Get out initial sequence number */
2035	seq = priv->xseq;
2036
2037	/* Update next sequence number */
2038	if (priv->conf.xmitShortSeq) {
2039	    priv->xseq = (seq + frags) & MP_SHORT_SEQ_MASK;
2040	} else {
2041	    priv->xseq = (seq + frags) & MP_LONG_SEQ_MASK;
2042	}
2043
2044	mtx_unlock(&priv->xmtx);
2045
2046	/* Send alloted portions of frame out on the link(s) */
2047	for (firstFragment = 1, activeLinkNum = priv->numActiveLinks - 1;
2048	    activeLinkNum >= 0; activeLinkNum--) {
2049		const uint16_t linkNum = priv->activeLinks[activeLinkNum];
2050		struct ng_ppp_link *const link = &priv->links[linkNum];
2051
2052		/* Deliver fragment(s) out the next link */
2053		for ( ; distrib[activeLinkNum] > 0; firstFragment = 0) {
2054			int len, lastFragment, error;
2055			struct mbuf *m2;
2056
2057			/* Calculate fragment length; don't exceed link MTU */
2058			len = distrib[activeLinkNum];
2059			if (len > link->conf.mru - hdr_len)
2060				len = link->conf.mru - hdr_len;
2061			distrib[activeLinkNum] -= len;
2062			lastFragment = (len == m->m_pkthdr.len);
2063
2064			/* Split off next fragment as "m2" */
2065			m2 = m;
2066			if (!lastFragment) {
2067				struct mbuf *n = m_split(m, len, M_DONTWAIT);
2068
2069				if (n == NULL) {
2070					NG_FREE_M(m);
2071					if (firstFragment)
2072						NG_FREE_ITEM(item);
2073					return (ENOMEM);
2074				}
2075				m_tag_copy_chain(n, m, M_DONTWAIT);
2076				m = n;
2077			}
2078
2079			/* Prepend MP header */
2080			if (priv->conf.xmitShortSeq) {
2081				uint16_t shdr;
2082
2083				shdr = seq;
2084				seq = (seq + 1) & MP_SHORT_SEQ_MASK;
2085				if (firstFragment)
2086					shdr |= MP_SHORT_FIRST_FLAG;
2087				if (lastFragment)
2088					shdr |= MP_SHORT_LAST_FLAG;
2089				shdr = htons(shdr);
2090				m2 = ng_ppp_prepend(m2, &shdr, 2);
2091			} else {
2092				uint32_t lhdr;
2093
2094				lhdr = seq;
2095				seq = (seq + 1) & MP_LONG_SEQ_MASK;
2096				if (firstFragment)
2097					lhdr |= MP_LONG_FIRST_FLAG;
2098				if (lastFragment)
2099					lhdr |= MP_LONG_LAST_FLAG;
2100				lhdr = htonl(lhdr);
2101				m2 = ng_ppp_prepend(m2, &lhdr, 4);
2102			}
2103			if (m2 == NULL) {
2104				if (!lastFragment)
2105					m_freem(m);
2106				if (firstFragment)
2107					NG_FREE_ITEM(item);
2108				return (ENOBUFS);
2109			}
2110
2111			/* Send fragment */
2112			if (firstFragment) {
2113				NGI_M(item) = m2; /* Reuse original item. */
2114			} else {
2115				item = ng_package_data(m2, NG_NOFLAGS);
2116			}
2117			if (item != NULL) {
2118				error = ng_ppp_link_xmit(node, item, PROT_MP,
2119					    linkNum, (firstFragment?plen:0));
2120				if (error != 0) {
2121					if (!lastFragment)
2122						NG_FREE_M(m);
2123					return (error);
2124				}
2125			}
2126		}
2127	}
2128
2129	/* Done */
2130	return (0);
2131}
2132
2133/*
2134 * Computing the optimal fragmentation
2135 * -----------------------------------
2136 *
2137 * This routine tries to compute the optimal fragmentation pattern based
2138 * on each link's latency, bandwidth, and calculated additional latency.
2139 * The latter quantity is the additional latency caused by previously
2140 * written data that has not been transmitted yet.
2141 *
2142 * This algorithm is only useful when not all of the links have the
2143 * same latency and bandwidth values.
2144 *
2145 * The essential idea is to make the last bit of each fragment of the
2146 * frame arrive at the opposite end at the exact same time. This greedy
2147 * algorithm is optimal, in that no other scheduling could result in any
2148 * packet arriving any sooner unless packets are delivered out of order.
2149 *
2150 * Suppose link i has bandwidth b_i (in tens of bytes per milisecond) and
2151 * latency l_i (in miliseconds). Consider the function function f_i(t)
2152 * which is equal to the number of bytes that will have arrived at
2153 * the peer after t miliseconds if we start writing continuously at
2154 * time t = 0. Then f_i(t) = b_i * (t - l_i) = ((b_i * t) - (l_i * b_i).
2155 * That is, f_i(t) is a line with slope b_i and y-intersect -(l_i * b_i).
2156 * Note that the y-intersect is always <= zero because latency can't be
2157 * negative.  Note also that really the function is f_i(t) except when
2158 * f_i(t) is negative, in which case the function is zero.  To take
2159 * care of this, let Q_i(t) = { if (f_i(t) > 0) return 1; else return 0; }.
2160 * So the actual number of bytes that will have arrived at the peer after
2161 * t miliseconds is f_i(t) * Q_i(t).
2162 *
2163 * At any given time, each link has some additional latency a_i >= 0
2164 * due to previously written fragment(s) which are still in the queue.
2165 * This value is easily computed from the time since last transmission,
2166 * the previous latency value, the number of bytes written, and the
2167 * link's bandwidth.
2168 *
2169 * Assume that l_i includes any a_i already, and that the links are
2170 * sorted by latency, so that l_i <= l_{i+1}.
2171 *
2172 * Let N be the total number of bytes in the current frame we are sending.
2173 *
2174 * Suppose we were to start writing bytes at time t = 0 on all links
2175 * simultaneously, which is the most we can possibly do.  Then let
2176 * F(t) be equal to the total number of bytes received by the peer
2177 * after t miliseconds. Then F(t) = Sum_i (f_i(t) * Q_i(t)).
2178 *
2179 * Our goal is simply this: fragment the frame across the links such
2180 * that the peer is able to reconstruct the completed frame as soon as
2181 * possible, i.e., at the least possible value of t. Call this value t_0.
2182 *
2183 * Then it follows that F(t_0) = N. Our strategy is first to find the value
2184 * of t_0, and then deduce how many bytes to write to each link.
2185 *
2186 * Rewriting F(t_0):
2187 *
2188 *   t_0 = ( N + Sum_i ( l_i * b_i * Q_i(t_0) ) ) / Sum_i ( b_i * Q_i(t_0) )
2189 *
2190 * Now, we note that Q_i(t) is constant for l_i <= t <= l_{i+1}. t_0 will
2191 * lie in one of these ranges.  To find it, we just need to find the i such
2192 * that F(l_i) <= N <= F(l_{i+1}).  Then we compute all the constant values
2193 * for Q_i() in this range, plug in the remaining values, solving for t_0.
2194 *
2195 * Once t_0 is known, then the number of bytes to send on link i is
2196 * just f_i(t_0) * Q_i(t_0).
2197 *
2198 * In other words, we start allocating bytes to the links one at a time.
2199 * We keep adding links until the frame is completely sent.  Some links
2200 * may not get any bytes because their latency is too high.
2201 *
2202 * Is all this work really worth the trouble?  Depends on the situation.
2203 * The bigger the ratio of computer speed to link speed, and the more
2204 * important total bundle latency is (e.g., for interactive response time),
2205 * the more it's worth it.  There is however the cost of calling this
2206 * function for every frame.  The running time is O(n^2) where n is the
2207 * number of links that receive a non-zero number of bytes.
2208 *
2209 * Since latency is measured in miliseconds, the "resolution" of this
2210 * algorithm is one milisecond.
2211 *
2212 * To avoid this algorithm altogether, configure all links to have the
2213 * same latency and bandwidth.
2214 */
2215static void
2216ng_ppp_mp_strategy(node_p node, int len, int *distrib)
2217{
2218	const priv_p priv = NG_NODE_PRIVATE(node);
2219	int latency[NG_PPP_MAX_LINKS];
2220	int sortByLatency[NG_PPP_MAX_LINKS];
2221	int activeLinkNum;
2222	int t0, total, topSum, botSum;
2223	struct timeval now;
2224	int i, numFragments;
2225
2226	/* If only one link, this gets real easy */
2227	if (priv->numActiveLinks == 1) {
2228		distrib[0] = len;
2229		return;
2230	}
2231
2232	/* Get current time */
2233	getmicrouptime(&now);
2234
2235	/* Compute latencies for each link at this point in time */
2236	for (activeLinkNum = 0;
2237	    activeLinkNum < priv->numActiveLinks; activeLinkNum++) {
2238		struct ng_ppp_link *alink;
2239		struct timeval diff;
2240		int xmitBytes;
2241
2242		/* Start with base latency value */
2243		alink = &priv->links[priv->activeLinks[activeLinkNum]];
2244		latency[activeLinkNum] = alink->latency;
2245		sortByLatency[activeLinkNum] = activeLinkNum;	/* see below */
2246
2247		/* Any additional latency? */
2248		if (alink->bytesInQueue == 0)
2249			continue;
2250
2251		/* Compute time delta since last write */
2252		diff = now;
2253		timevalsub(&diff, &alink->lastWrite);
2254
2255		/* alink->bytesInQueue will be changed, mark change time. */
2256		alink->lastWrite = now;
2257
2258		if (now.tv_sec < 0 || diff.tv_sec >= 10) {	/* sanity */
2259			alink->bytesInQueue = 0;
2260			continue;
2261		}
2262
2263		/* How many bytes could have transmitted since last write? */
2264		xmitBytes = (alink->conf.bandwidth * 10 * diff.tv_sec)
2265		    + (alink->conf.bandwidth * (diff.tv_usec / 1000)) / 100;
2266		alink->bytesInQueue -= xmitBytes;
2267		if (alink->bytesInQueue < 0)
2268			alink->bytesInQueue = 0;
2269		else
2270			latency[activeLinkNum] +=
2271			    (100 * alink->bytesInQueue) / alink->conf.bandwidth;
2272	}
2273
2274	/* Sort active links by latency */
2275	qsort_r(sortByLatency,
2276	    priv->numActiveLinks, sizeof(*sortByLatency), latency, ng_ppp_intcmp);
2277
2278	/* Find the interval we need (add links in sortByLatency[] order) */
2279	for (numFragments = 1;
2280	    numFragments < priv->numActiveLinks; numFragments++) {
2281		for (total = i = 0; i < numFragments; i++) {
2282			int flowTime;
2283
2284			flowTime = latency[sortByLatency[numFragments]]
2285			    - latency[sortByLatency[i]];
2286			total += ((flowTime * priv->links[
2287			    priv->activeLinks[sortByLatency[i]]].conf.bandwidth)
2288			    	+ 99) / 100;
2289		}
2290		if (total >= len)
2291			break;
2292	}
2293
2294	/* Solve for t_0 in that interval */
2295	for (topSum = botSum = i = 0; i < numFragments; i++) {
2296		int bw = priv->links[
2297		    priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
2298
2299		topSum += latency[sortByLatency[i]] * bw;	/* / 100 */
2300		botSum += bw;					/* / 100 */
2301	}
2302	t0 = ((len * 100) + topSum + botSum / 2) / botSum;
2303
2304	/* Compute f_i(t_0) all i */
2305	for (total = i = 0; i < numFragments; i++) {
2306		int bw = priv->links[
2307		    priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
2308
2309		distrib[sortByLatency[i]] =
2310		    (bw * (t0 - latency[sortByLatency[i]]) + 50) / 100;
2311		total += distrib[sortByLatency[i]];
2312	}
2313
2314	/* Deal with any rounding error */
2315	if (total < len) {
2316		struct ng_ppp_link *fastLink =
2317		    &priv->links[priv->activeLinks[sortByLatency[0]]];
2318		int fast = 0;
2319
2320		/* Find the fastest link */
2321		for (i = 1; i < numFragments; i++) {
2322			struct ng_ppp_link *const link =
2323			    &priv->links[priv->activeLinks[sortByLatency[i]]];
2324
2325			if (link->conf.bandwidth > fastLink->conf.bandwidth) {
2326				fast = i;
2327				fastLink = link;
2328			}
2329		}
2330		distrib[sortByLatency[fast]] += len - total;
2331	} else while (total > len) {
2332		struct ng_ppp_link *slowLink =
2333		    &priv->links[priv->activeLinks[sortByLatency[0]]];
2334		int delta, slow = 0;
2335
2336		/* Find the slowest link that still has bytes to remove */
2337		for (i = 1; i < numFragments; i++) {
2338			struct ng_ppp_link *const link =
2339			    &priv->links[priv->activeLinks[sortByLatency[i]]];
2340
2341			if (distrib[sortByLatency[slow]] == 0
2342			  || (distrib[sortByLatency[i]] > 0
2343			    && link->conf.bandwidth <
2344			      slowLink->conf.bandwidth)) {
2345				slow = i;
2346				slowLink = link;
2347			}
2348		}
2349		delta = total - len;
2350		if (delta > distrib[sortByLatency[slow]])
2351			delta = distrib[sortByLatency[slow]];
2352		distrib[sortByLatency[slow]] -= delta;
2353		total -= delta;
2354	}
2355}
2356
2357/*
2358 * Compare two integers
2359 */
2360static int
2361ng_ppp_intcmp(void *latency, const void *v1, const void *v2)
2362{
2363	const int index1 = *((const int *) v1);
2364	const int index2 = *((const int *) v2);
2365
2366	return ((int *)latency)[index1] - ((int *)latency)[index2];
2367}
2368
2369/*
2370 * Prepend a possibly compressed PPP protocol number in front of a frame
2371 */
2372static struct mbuf *
2373ng_ppp_addproto(struct mbuf *m, uint16_t proto, int compOK)
2374{
2375	if (compOK && PROT_COMPRESSABLE(proto)) {
2376		uint8_t pbyte = (uint8_t)proto;
2377
2378		return ng_ppp_prepend(m, &pbyte, 1);
2379	} else {
2380		uint16_t pword = htons((uint16_t)proto);
2381
2382		return ng_ppp_prepend(m, &pword, 2);
2383	}
2384}
2385
2386/*
2387 * Cut a possibly compressed PPP protocol number from the front of a frame.
2388 */
2389static struct mbuf *
2390ng_ppp_cutproto(struct mbuf *m, uint16_t *proto)
2391{
2392
2393	*proto = 0;
2394	if (m->m_len < 1 && (m = m_pullup(m, 1)) == NULL)
2395		return (NULL);
2396
2397	*proto = *mtod(m, uint8_t *);
2398	m_adj(m, 1);
2399
2400	if (!PROT_VALID(*proto)) {
2401		if (m->m_len < 1 && (m = m_pullup(m, 1)) == NULL)
2402			return (NULL);
2403
2404		*proto = (*proto << 8) + *mtod(m, uint8_t *);
2405		m_adj(m, 1);
2406	}
2407
2408	return (m);
2409}
2410
2411/*
2412 * Prepend some bytes to an mbuf.
2413 */
2414static struct mbuf *
2415ng_ppp_prepend(struct mbuf *m, const void *buf, int len)
2416{
2417	M_PREPEND(m, len, M_DONTWAIT);
2418	if (m == NULL || (m->m_len < len && (m = m_pullup(m, len)) == NULL))
2419		return (NULL);
2420	bcopy(buf, mtod(m, uint8_t *), len);
2421	return (m);
2422}
2423
2424/*
2425 * Update private information that is derived from other private information
2426 */
2427static void
2428ng_ppp_update(node_p node, int newConf)
2429{
2430	const priv_p priv = NG_NODE_PRIVATE(node);
2431	int i;
2432
2433	/* Update active status for VJ Compression */
2434	priv->vjCompHooked = priv->hooks[HOOK_INDEX_VJC_IP] != NULL
2435	    && priv->hooks[HOOK_INDEX_VJC_COMP] != NULL
2436	    && priv->hooks[HOOK_INDEX_VJC_UNCOMP] != NULL
2437	    && priv->hooks[HOOK_INDEX_VJC_VJIP] != NULL;
2438
2439	/* Increase latency for each link an amount equal to one MP header */
2440	if (newConf) {
2441		for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
2442			int hdrBytes;
2443
2444			if (priv->links[i].conf.bandwidth == 0)
2445			    continue;
2446
2447			hdrBytes = MP_AVERAGE_LINK_OVERHEAD
2448			    + (priv->links[i].conf.enableACFComp ? 0 : 2)
2449			    + (priv->links[i].conf.enableProtoComp ? 1 : 2)
2450			    + (priv->conf.xmitShortSeq ? 2 : 4);
2451			priv->links[i].latency =
2452			    priv->links[i].conf.latency +
2453			    (hdrBytes / priv->links[i].conf.bandwidth + 50) / 100;
2454		}
2455	}
2456
2457	/* Update list of active links */
2458	bzero(&priv->activeLinks, sizeof(priv->activeLinks));
2459	priv->numActiveLinks = 0;
2460	priv->allLinksEqual = 1;
2461	for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
2462		struct ng_ppp_link *const link = &priv->links[i];
2463
2464		/* Is link active? */
2465		if (link->conf.enableLink && link->hook != NULL) {
2466			struct ng_ppp_link *link0;
2467
2468			/* Add link to list of active links */
2469			priv->activeLinks[priv->numActiveLinks++] = i;
2470			link0 = &priv->links[priv->activeLinks[0]];
2471
2472			/* Determine if all links are still equal */
2473			if (link->latency != link0->latency
2474			  || link->conf.bandwidth != link0->conf.bandwidth)
2475				priv->allLinksEqual = 0;
2476
2477			/* Initialize rec'd sequence number */
2478			if (link->seq == MP_NOSEQ) {
2479				link->seq = (link == link0) ?
2480				    MP_INITIAL_SEQ : link0->seq;
2481			}
2482		} else
2483			link->seq = MP_NOSEQ;
2484	}
2485
2486	/* Update MP state as multi-link is active or not */
2487	if (priv->conf.enableMultilink && priv->numActiveLinks > 0)
2488		ng_ppp_start_frag_timer(node);
2489	else {
2490		ng_ppp_stop_frag_timer(node);
2491		ng_ppp_frag_reset(node);
2492		priv->xseq = MP_INITIAL_SEQ;
2493		priv->mseq = MP_INITIAL_SEQ;
2494		for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
2495			struct ng_ppp_link *const link = &priv->links[i];
2496
2497			bzero(&link->lastWrite, sizeof(link->lastWrite));
2498			link->bytesInQueue = 0;
2499			link->seq = MP_NOSEQ;
2500		}
2501	}
2502}
2503
2504/*
2505 * Determine if a new configuration would represent a valid change
2506 * from the current configuration and link activity status.
2507 */
2508static int
2509ng_ppp_config_valid(node_p node, const struct ng_ppp_node_conf *newConf)
2510{
2511	const priv_p priv = NG_NODE_PRIVATE(node);
2512	int i, newNumLinksActive;
2513
2514	/* Check per-link config and count how many links would be active */
2515	for (newNumLinksActive = i = 0; i < NG_PPP_MAX_LINKS; i++) {
2516		if (newConf->links[i].enableLink && priv->links[i].hook != NULL)
2517			newNumLinksActive++;
2518		if (!newConf->links[i].enableLink)
2519			continue;
2520		if (newConf->links[i].mru < MP_MIN_LINK_MRU)
2521			return (0);
2522		if (newConf->links[i].bandwidth == 0)
2523			return (0);
2524		if (newConf->links[i].bandwidth > NG_PPP_MAX_BANDWIDTH)
2525			return (0);
2526		if (newConf->links[i].latency > NG_PPP_MAX_LATENCY)
2527			return (0);
2528	}
2529
2530	/* Check bundle parameters */
2531	if (newConf->bund.enableMultilink && newConf->bund.mrru < MP_MIN_MRRU)
2532		return (0);
2533
2534	/* Disallow changes to multi-link configuration while MP is active */
2535	if (priv->numActiveLinks > 0 && newNumLinksActive > 0) {
2536		if (!priv->conf.enableMultilink
2537				!= !newConf->bund.enableMultilink
2538		    || !priv->conf.xmitShortSeq != !newConf->bund.xmitShortSeq
2539		    || !priv->conf.recvShortSeq != !newConf->bund.recvShortSeq)
2540			return (0);
2541	}
2542
2543	/* At most one link can be active unless multi-link is enabled */
2544	if (!newConf->bund.enableMultilink && newNumLinksActive > 1)
2545		return (0);
2546
2547	/* Configuration change would be valid */
2548	return (1);
2549}
2550
2551/*
2552 * Free all entries in the fragment queue
2553 */
2554static void
2555ng_ppp_frag_reset(node_p node)
2556{
2557	const priv_p priv = NG_NODE_PRIVATE(node);
2558	struct ng_ppp_frag *qent, *qnext;
2559
2560	for (qent = TAILQ_FIRST(&priv->frags); qent; qent = qnext) {
2561		qnext = TAILQ_NEXT(qent, f_qent);
2562		NG_FREE_M(qent->data);
2563		TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
2564	}
2565	TAILQ_INIT(&priv->frags);
2566}
2567
2568/*
2569 * Start fragment queue timer
2570 */
2571static void
2572ng_ppp_start_frag_timer(node_p node)
2573{
2574	const priv_p priv = NG_NODE_PRIVATE(node);
2575
2576	if (!(callout_pending(&priv->fragTimer)))
2577		ng_callout(&priv->fragTimer, node, NULL, MP_FRAGTIMER_INTERVAL,
2578		    ng_ppp_frag_timeout, NULL, 0);
2579}
2580
2581/*
2582 * Stop fragment queue timer
2583 */
2584static void
2585ng_ppp_stop_frag_timer(node_p node)
2586{
2587	const priv_p priv = NG_NODE_PRIVATE(node);
2588
2589	if (callout_pending(&priv->fragTimer))
2590		ng_uncallout(&priv->fragTimer, node);
2591}
2592