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