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