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