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