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