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