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