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