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 69922 2000-12-12 18:52:14Z julian $
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_disconnect,
356 ng_ppp_cmds
357};
358NETGRAPH_INIT(ppp, &ng_ppp_typestruct);
359
360static int *compareLatencies; /* hack for ng_ppp_intcmp() */
361
362/* Address and control field header */
363static const u_char ng_ppp_acf[2] = { 0xff, 0x03 };
364
365/* Maximum time we'll let a complete incoming packet sit in the queue */
366static const struct timeval ng_ppp_max_staleness = { 2, 0 }; /* 2 seconds */
367
368#define ERROUT(x) do { error = (x); goto done; } while (0)
369
370/************************************************************************
371 NETGRAPH NODE STUFF
372 ************************************************************************/
373
374/*
375 * Node type constructor
376 */
377static int
378ng_ppp_constructor(node_p *nodep)
379{
380 priv_p priv;
381 int i, error;
382
383 /* Allocate private structure */
384 MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH, M_NOWAIT | M_ZERO);
385 if (priv == NULL)
386 return (ENOMEM);
387
388 /* Call generic node constructor */
389 if ((error = ng_make_node_common(&ng_ppp_typestruct, nodep))) {
390 FREE(priv, M_NETGRAPH);
391 return (error);
392 }
393 (*nodep)->private = priv;
394
395 /* Initialize state */
396 TAILQ_INIT(&priv->frags);
397 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
398 priv->links[i].seq = MP_NOSEQ;
399 callout_handle_init(&priv->fragTimer);
400
401 /* Done */
402 return (0);
403}
404
405/*
406 * Give our OK for a hook to be added
407 */
408static int
409ng_ppp_newhook(node_p node, hook_p hook, const char *name)
410{
411 const priv_p priv = node->private;
412 int linkNum = -1;
413 hook_p *hookPtr = NULL;
414 int hookIndex = -1;
415
416 /* Figure out which hook it is */
417 if (strncmp(name, NG_PPP_HOOK_LINK_PREFIX, /* a link hook? */
418 strlen(NG_PPP_HOOK_LINK_PREFIX)) == 0) {
419 const char *cp;
420 char *eptr;
421
422 cp = name + strlen(NG_PPP_HOOK_LINK_PREFIX);
423 if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
424 return (EINVAL);
425 linkNum = (int)strtoul(cp, &eptr, 10);
426 if (*eptr != '\0' || linkNum < 0 || linkNum >= NG_PPP_MAX_LINKS)
427 return (EINVAL);
428 hookPtr = &priv->links[linkNum].hook;
429 hookIndex = ~linkNum;
430 } else { /* must be a non-link hook */
431 int i;
432
433 for (i = 0; ng_ppp_hook_names[i] != NULL; i++) {
434 if (strcmp(name, ng_ppp_hook_names[i]) == 0) {
435 hookPtr = &priv->hooks[i];
436 hookIndex = i;
437 break;
438 }
439 }
440 if (ng_ppp_hook_names[i] == NULL)
441 return (EINVAL); /* no such hook */
442 }
443
444 /* See if hook is already connected */
445 if (*hookPtr != NULL)
446 return (EISCONN);
447
448 /* Disallow more than one link unless multilink is enabled */
449 if (linkNum != -1 && priv->links[linkNum].conf.enableLink
450 && !priv->conf.enableMultilink && priv->numActiveLinks >= 1)
451 return (ENODEV);
452
453 /* OK */
454 *hookPtr = hook;
455 HOOK_INDEX(hook) = hookIndex;
456 ng_ppp_update(node, 0);
457 return (0);
458}
459
460/*
461 * Receive a control message
462 */
463static int
464ng_ppp_rcvmsg(node_p node, struct ng_mesg *msg,
465 const char *raddr, struct ng_mesg **rptr, hook_p lasthook)
466{
467 const priv_p priv = node->private;
468 struct ng_mesg *resp = NULL;
469 int error = 0;
470
471 switch (msg->header.typecookie) {
472 case NGM_PPP_COOKIE:
473 switch (msg->header.cmd) {
474 case NGM_PPP_SET_CONFIG:
475 {
476 struct ng_ppp_node_conf *const conf =
477 (struct ng_ppp_node_conf *)msg->data;
478 int i;
479
480 /* Check for invalid or illegal config */
481 if (msg->header.arglen != sizeof(*conf))
482 ERROUT(EINVAL);
483 if (!ng_ppp_config_valid(node, conf))
484 ERROUT(EINVAL);
485
486 /* Copy config */
487 priv->conf = conf->bund;
488 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
489 priv->links[i].conf = conf->links[i];
490 ng_ppp_update(node, 1);
491 break;
492 }
493 case NGM_PPP_GET_CONFIG:
494 {
495 struct ng_ppp_node_conf *conf;
496 int i;
497
498 NG_MKRESPONSE(resp, msg, sizeof(*conf), M_NOWAIT);
499 if (resp == NULL)
500 ERROUT(ENOMEM);
501 conf = (struct ng_ppp_node_conf *)resp->data;
502 conf->bund = priv->conf;
503 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
504 conf->links[i] = priv->links[i].conf;
505 break;
506 }
507 case NGM_PPP_GET_MP_STATE:
508 {
509 struct ng_ppp_mp_state *info;
510 int i;
511
512 NG_MKRESPONSE(resp, msg, sizeof(*info), M_NOWAIT);
513 if (resp == NULL)
514 ERROUT(ENOMEM);
515 info = (struct ng_ppp_mp_state *)resp->data;
516 bzero(info, sizeof(*info));
517 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
518 if (priv->links[i].seq != MP_NOSEQ)
519 info->rseq[i] = priv->links[i].seq;
520 }
521 info->mseq = priv->mseq;
522 info->xseq = priv->xseq;
523 break;
524 }
525 case NGM_PPP_GET_LINK_STATS:
526 case NGM_PPP_CLR_LINK_STATS:
527 case NGM_PPP_GETCLR_LINK_STATS:
528 {
529 struct ng_ppp_link_stat *stats;
530 u_int16_t linkNum;
531
532 if (msg->header.arglen != sizeof(u_int16_t))
533 ERROUT(EINVAL);
534 linkNum = *((u_int16_t *) msg->data);
535 if (linkNum >= NG_PPP_MAX_LINKS
536 && linkNum != NG_PPP_BUNDLE_LINKNUM)
537 ERROUT(EINVAL);
538 stats = (linkNum == NG_PPP_BUNDLE_LINKNUM) ?
539 &priv->bundleStats : &priv->links[linkNum].stats;
540 if (msg->header.cmd != NGM_PPP_CLR_LINK_STATS) {
541 NG_MKRESPONSE(resp, msg,
542 sizeof(struct ng_ppp_link_stat), M_NOWAIT);
543 if (resp == NULL)
544 ERROUT(ENOMEM);
545 bcopy(stats, resp->data, sizeof(*stats));
546 }
547 if (msg->header.cmd != NGM_PPP_GET_LINK_STATS)
548 bzero(stats, sizeof(*stats));
549 break;
550 }
551 default:
552 error = EINVAL;
553 break;
554 }
555 break;
556 case NGM_VJC_COOKIE:
557 {
558 char path[NG_PATHLEN + 1];
559 node_p origNode;
560
561 if ((error = ng_path2node(node, raddr, &origNode, NULL)) != 0)
562 ERROUT(error);
563 snprintf(path, sizeof(path), "[%lx]:%s",
564 (long)node, NG_PPP_HOOK_VJC_IP);
565 return ng_send_msg(origNode, msg, path, NULL, NULL, rptr);
566/* XXX Archie, looks like you are using the wrong value for the ID here..
567 you can't use a node address as a node-ID any more..
568But it may be that you can use the new 'hook' arg for ng_send_msg()
569to achieve a more efficient resuld than an ID anyhow. */
570 }
571 default:
572 error = EINVAL;
573 break;
574 }
575 if (rptr)
576 *rptr = resp;
577 else if (resp)
578 FREE(resp, M_NETGRAPH);
579
580done:
581 FREE(msg, M_NETGRAPH);
582 return (error);
583}
584
585/*
586 * Receive data on a hook
587 */
588static int
589ng_ppp_rcvdata(hook_p hook, struct mbuf *m, meta_p meta,
590 struct mbuf **ret_m, meta_p *ret_meta, struct ng_mesg **resp)
591{
592 const node_p node = hook->node;
593 const priv_p priv = node->private;
594 const int index = HOOK_INDEX(hook);
595 u_int16_t linkNum = NG_PPP_BUNDLE_LINKNUM;
596 hook_p outHook = NULL;
597 int proto = 0, error;
598
599 /* Did it come from a link hook? */
600 if (index < 0) {
601 struct ng_ppp_link *link;
602
603 /* Convert index into a link number */
604 linkNum = (u_int16_t)~index;
605 KASSERT(linkNum < NG_PPP_MAX_LINKS,
606 ("%s: bogus index 0x%x", __FUNCTION__, index));
607 link = &priv->links[linkNum];
608
609 /* Stats */
610 link->stats.recvFrames++;
611 link->stats.recvOctets += m->m_pkthdr.len;
612
613 /* Strip address and control fields, if present */
614 if (m->m_pkthdr.len >= 2) {
615 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
616 NG_FREE_DATA(m, meta);
617 return (ENOBUFS);
618 }
619 if (bcmp(mtod(m, u_char *), &ng_ppp_acf, 2) == 0)
620 m_adj(m, 2);
621 }
622
623 /* Dispatch incoming frame (if not enabled, to bypass) */
624 return ng_ppp_input(node,
625 !link->conf.enableLink, linkNum, m, meta);
626 }
627
628 /* Get protocol & check if data allowed from this hook */
629 switch (index) {
630
631 /* Outgoing data */
632 case HOOK_INDEX_ATALK:
633 if (!priv->conf.enableAtalk) {
634 NG_FREE_DATA(m, meta);
635 return (ENXIO);
636 }
637 proto = PROT_APPLETALK;
638 break;
639 case HOOK_INDEX_IPX:
640 if (!priv->conf.enableIPX) {
641 NG_FREE_DATA(m, meta);
642 return (ENXIO);
643 }
644 proto = PROT_IPX;
645 break;
646 case HOOK_INDEX_IPV6:
647 if (!priv->conf.enableIPv6) {
648 NG_FREE_DATA(m, meta);
649 return (ENXIO);
650 }
651 proto = PROT_IPV6;
652 break;
653 case HOOK_INDEX_INET:
654 case HOOK_INDEX_VJC_VJIP:
655 if (!priv->conf.enableIP) {
656 NG_FREE_DATA(m, meta);
657 return (ENXIO);
658 }
659 proto = PROT_IP;
660 break;
661 case HOOK_INDEX_VJC_COMP:
662 if (!priv->conf.enableVJCompression) {
663 NG_FREE_DATA(m, meta);
664 return (ENXIO);
665 }
666 proto = PROT_VJCOMP;
667 break;
668 case HOOK_INDEX_VJC_UNCOMP:
669 if (!priv->conf.enableVJCompression) {
670 NG_FREE_DATA(m, meta);
671 return (ENXIO);
672 }
673 proto = PROT_VJUNCOMP;
674 break;
675 case HOOK_INDEX_COMPRESS:
676 if (!priv->conf.enableCompression) {
677 NG_FREE_DATA(m, meta);
678 return (ENXIO);
679 }
680 proto = PROT_COMPD;
681 break;
682 case HOOK_INDEX_ENCRYPT:
683 if (!priv->conf.enableEncryption) {
684 NG_FREE_DATA(m, meta);
685 return (ENXIO);
686 }
687 proto = PROT_CRYPTD;
688 break;
689 case HOOK_INDEX_BYPASS:
690 if (m->m_pkthdr.len < 4) {
691 NG_FREE_DATA(m, meta);
692 return (EINVAL);
693 }
694 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
695 NG_FREE_META(meta);
696 return (ENOBUFS);
697 }
698 linkNum = ntohs(mtod(m, u_int16_t *)[0]);
699 proto = ntohs(mtod(m, u_int16_t *)[1]);
700 m_adj(m, 4);
701 if (linkNum >= NG_PPP_MAX_LINKS
702 && linkNum != NG_PPP_BUNDLE_LINKNUM) {
703 NG_FREE_DATA(m, meta);
704 return (EINVAL);
705 }
706 break;
707
708 /* Incoming data */
709 case HOOK_INDEX_VJC_IP:
710 if (!priv->conf.enableIP || !priv->conf.enableVJDecompression) {
711 NG_FREE_DATA(m, meta);
712 return (ENXIO);
713 }
714 break;
715 case HOOK_INDEX_DECOMPRESS:
716 if (!priv->conf.enableDecompression) {
717 NG_FREE_DATA(m, meta);
718 return (ENXIO);
719 }
720 break;
721 case HOOK_INDEX_DECRYPT:
722 if (!priv->conf.enableDecryption) {
723 NG_FREE_DATA(m, meta);
724 return (ENXIO);
725 }
726 break;
727 default:
728 panic("%s: bogus index 0x%x", __FUNCTION__, index);
729 }
730
731 /* Now figure out what to do with the frame */
732 switch (index) {
733
734 /* Outgoing data */
735 case HOOK_INDEX_INET:
736 if (priv->conf.enableVJCompression && priv->vjCompHooked) {
737 outHook = priv->hooks[HOOK_INDEX_VJC_IP];
738 break;
739 }
740 /* FALLTHROUGH */
741 case HOOK_INDEX_ATALK:
742 case HOOK_INDEX_IPV6:
743 case HOOK_INDEX_IPX:
744 case HOOK_INDEX_VJC_COMP:
745 case HOOK_INDEX_VJC_UNCOMP:
746 case HOOK_INDEX_VJC_VJIP:
747 if (priv->conf.enableCompression
748 && priv->hooks[HOOK_INDEX_COMPRESS] != NULL) {
749 if ((m = ng_ppp_addproto(m, proto, 1)) == NULL) {
750 NG_FREE_META(meta);
751 return (ENOBUFS);
752 }
753 outHook = priv->hooks[HOOK_INDEX_COMPRESS];
754 break;
755 }
756 /* FALLTHROUGH */
757 case HOOK_INDEX_COMPRESS:
758 if (priv->conf.enableEncryption
759 && priv->hooks[HOOK_INDEX_ENCRYPT] != NULL) {
760 if ((m = ng_ppp_addproto(m, proto, 1)) == NULL) {
761 NG_FREE_META(meta);
762 return (ENOBUFS);
763 }
764 outHook = priv->hooks[HOOK_INDEX_ENCRYPT];
765 break;
766 }
767 /* FALLTHROUGH */
768 case HOOK_INDEX_ENCRYPT:
769 return ng_ppp_output(node, 0,
770 proto, NG_PPP_BUNDLE_LINKNUM, m, meta);
771
772 case HOOK_INDEX_BYPASS:
773 return ng_ppp_output(node, 1, proto, linkNum, m, meta);
774
775 /* Incoming data */
776 case HOOK_INDEX_DECRYPT:
777 case HOOK_INDEX_DECOMPRESS:
778 return ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, m, meta);
779
780 case HOOK_INDEX_VJC_IP:
781 outHook = priv->hooks[HOOK_INDEX_INET];
782 break;
783 }
784
785 /* Send packet out hook */
786 NG_SEND_DATA_RET(error, outHook, m, meta, resp);
787 if (m != NULL || meta != NULL)
788 return ng_ppp_rcvdata(outHook, m, meta, NULL, NULL, resp);
789 return (error);
790}
791
792/*
793 * Destroy node
794 */
795static int
796ng_ppp_rmnode(node_p node)
797{
798 const priv_p priv = node->private;
799
800 /* Stop fragment queue timer */
801 ng_ppp_stop_frag_timer(node);
802
803 /* Take down netgraph node */
804 node->flags |= NG_INVALID;
805 ng_cutlinks(node);
806 ng_unname(node);
807 ng_ppp_frag_reset(node);
808 bzero(priv, sizeof(*priv));
809 FREE(priv, M_NETGRAPH);
810 node->private = NULL;
811 ng_unref(node); /* let the node escape */
812 return (0);
813}
814
815/*
816 * Hook disconnection
817 */
818static int
819ng_ppp_disconnect(hook_p hook)
820{
821 const node_p node = hook->node;
822 const priv_p priv = node->private;
823 const int index = HOOK_INDEX(hook);
824
825 /* Zero out hook pointer */
826 if (index < 0)
827 priv->links[~index].hook = NULL;
828 else
829 priv->hooks[index] = NULL;
830
831 /* Update derived info (or go away if no hooks left) */
832 if (node->numhooks > 0)
833 ng_ppp_update(node, 0);
834 else
835 ng_rmnode(node);
836 return (0);
837}
838
839/************************************************************************
840 HELPER STUFF
841 ************************************************************************/
842
843/*
844 * Handle an incoming frame. Extract the PPP protocol number
845 * and dispatch accordingly.
846 */
847static int
848ng_ppp_input(node_p node, int bypass, int linkNum, struct mbuf *m, meta_p meta)
849{
850 const priv_p priv = node->private;
851 hook_p outHook = NULL;
852 int proto, error;
853
854 /* Extract protocol number */
855 for (proto = 0; !PROT_VALID(proto) && m->m_pkthdr.len > 0; ) {
856 if (m->m_len < 1 && (m = m_pullup(m, 1)) == NULL) {
857 NG_FREE_META(meta);
858 return (ENOBUFS);
859 }
860 proto = (proto << 8) + *mtod(m, u_char *);
861 m_adj(m, 1);
862 }
863 if (!PROT_VALID(proto)) {
864 if (linkNum == NG_PPP_BUNDLE_LINKNUM)
865 priv->bundleStats.badProtos++;
866 else
867 priv->links[linkNum].stats.badProtos++;
868 NG_FREE_DATA(m, meta);
869 return (EINVAL);
870 }
871
872 /* Bypass frame? */
873 if (bypass)
874 goto bypass;
875
876 /* Check protocol */
877 switch (proto) {
878 case PROT_COMPD:
879 if (priv->conf.enableDecompression)
880 outHook = priv->hooks[HOOK_INDEX_DECOMPRESS];
881 break;
882 case PROT_CRYPTD:
883 if (priv->conf.enableDecryption)
884 outHook = priv->hooks[HOOK_INDEX_DECRYPT];
885 break;
886 case PROT_VJCOMP:
887 if (priv->conf.enableVJDecompression && priv->vjCompHooked)
888 outHook = priv->hooks[HOOK_INDEX_VJC_COMP];
889 break;
890 case PROT_VJUNCOMP:
891 if (priv->conf.enableVJDecompression && priv->vjCompHooked)
892 outHook = priv->hooks[HOOK_INDEX_VJC_UNCOMP];
893 break;
894 case PROT_MP:
895 if (priv->conf.enableMultilink
896 && linkNum != NG_PPP_BUNDLE_LINKNUM)
897 return ng_ppp_mp_input(node, linkNum, m, meta);
898 break;
899 case PROT_APPLETALK:
900 if (priv->conf.enableAtalk)
901 outHook = priv->hooks[HOOK_INDEX_ATALK];
902 break;
903 case PROT_IPX:
904 if (priv->conf.enableIPX)
905 outHook = priv->hooks[HOOK_INDEX_IPX];
906 break;
907 case PROT_IP:
908 if (priv->conf.enableIP)
909 outHook = priv->hooks[HOOK_INDEX_INET];
910 break;
911 case PROT_IPV6:
912 if (priv->conf.enableIPv6)
913 outHook = priv->hooks[HOOK_INDEX_IPV6];
914 break;
915 }
916
917bypass:
918 /* For unknown/inactive protocols, forward out the bypass hook */
919 if (outHook == NULL) {
920 u_int16_t hdr[2];
921
922 hdr[0] = htons(linkNum);
923 hdr[1] = htons((u_int16_t)proto);
924 if ((m = ng_ppp_prepend(m, &hdr, 4)) == NULL) {
925 NG_FREE_META(meta);
926 return (ENOBUFS);
927 }
928 outHook = priv->hooks[HOOK_INDEX_BYPASS];
929 }
930
931 /* Forward frame */
932 NG_SEND_DATA(error, outHook, m, meta);
933 return (error);
934}
935
936/*
937 * Deliver a frame out a link, either a real one or NG_PPP_BUNDLE_LINKNUM
938 * If the link is not enabled then ENXIO is returned, unless "bypass" is != 0.
939 */
940static int
941ng_ppp_output(node_p node, int bypass,
942 int proto, int linkNum, struct mbuf *m, meta_p meta)
943{
944 const priv_p priv = node->private;
945 struct ng_ppp_link *link;
946 int len, error;
947
948 /* If not doing MP, map bundle virtual link to (the only) link */
949 if (linkNum == NG_PPP_BUNDLE_LINKNUM && !priv->conf.enableMultilink)
950 linkNum = priv->activeLinks[0];
951
952 /* Get link pointer (optimization) */
953 link = (linkNum != NG_PPP_BUNDLE_LINKNUM) ?
954 &priv->links[linkNum] : NULL;
955
956 /* Check link status (if real) */
957 if (linkNum != NG_PPP_BUNDLE_LINKNUM) {
958 if (!bypass && !link->conf.enableLink) {
959 NG_FREE_DATA(m, meta);
960 return (ENXIO);
961 }
962 if (link->hook == NULL) {
963 NG_FREE_DATA(m, meta);
964 return (ENETDOWN);
965 }
966 }
967
968 /* Prepend protocol number, possibly compressed */
969 if ((m = ng_ppp_addproto(m, proto,
970 linkNum == NG_PPP_BUNDLE_LINKNUM
971 || link->conf.enableProtoComp)) == NULL) {
972 NG_FREE_META(meta);
973 return (ENOBUFS);
974 }
975
976 /* Special handling for the MP virtual link */
977 if (linkNum == NG_PPP_BUNDLE_LINKNUM)
978 return ng_ppp_mp_output(node, m, meta);
979
980 /* Prepend address and control field (unless compressed) */
981 if (proto == PROT_LCP || !link->conf.enableACFComp) {
982 if ((m = ng_ppp_prepend(m, &ng_ppp_acf, 2)) == NULL) {
983 NG_FREE_META(meta);
984 return (ENOBUFS);
985 }
986 }
987
988 /* Deliver frame */
989 len = m->m_pkthdr.len;
990 NG_SEND_DATA(error, link->hook, m, meta);
991
992 /* Update stats and 'bytes in queue' counter */
993 if (error == 0) {
994 link->stats.xmitFrames++;
995 link->stats.xmitOctets += len;
996 link->bytesInQueue += len;
997 getmicrouptime(&link->lastWrite);
998 }
999 return error;
1000}
1001
1002/*
1003 * Handle an incoming multi-link fragment
1004 *
1005 * The fragment reassembly algorithm is somewhat complex. This is mainly
1006 * because we are required not to reorder the reconstructed packets, yet
1007 * fragments are only guaranteed to arrive in order on a per-link basis.
1008 * In other words, when we have a complete packet ready, but the previous
1009 * packet is still incomplete, we have to decide between delivering the
1010 * complete packet and throwing away the incomplete one, or waiting to
1011 * see if the remainder of the incomplete one arrives, at which time we
1012 * can deliver both packets, in order.
1013 *
1014 * This problem is exacerbated by "sequence number slew", which is when
1015 * the sequence numbers coming in from different links are far apart from
1016 * each other. In particular, certain unnamed equipment (*cough* Ascend)
1017 * has been seen to generate sequence number slew of up to 10 on an ISDN
1018 * 2B-channel MP link. There is nothing invalid about sequence number slew
1019 * but it makes the reasssembly process have to work harder.
1020 *
1021 * However, the peer is required to transmit fragments in order on each
1022 * link. That means if we define MSEQ as the minimum over all links of
1023 * the highest sequence number received on that link, then we can always
1024 * give up any hope of receiving a fragment with sequence number < MSEQ in
1025 * the future (all of this using 'wraparound' sequence number space).
1026 * Therefore we can always immediately throw away incomplete packets
1027 * missing fragments with sequence numbers < MSEQ.
1028 *
1029 * Here is an overview of our algorithm:
1030 *
1031 * o Received fragments are inserted into a queue, for which we
1032 * maintain these invariants between calls to this function:
1033 *
1034 * - Fragments are ordered in the queue by sequence number
1035 * - If a complete packet is at the head of the queue, then
1036 * the first fragment in the packet has seq# > MSEQ + 1
1037 * (otherwise, we could deliver it immediately)
1038 * - If any fragments have seq# < MSEQ, then they are necessarily
1039 * part of a packet whose missing seq#'s are all > MSEQ (otherwise,
1040 * we can throw them away because they'll never be completed)
1041 * - The queue contains at most MP_MAX_QUEUE_LEN fragments
1042 *
1043 * o We have a periodic timer that checks the queue for the first
1044 * complete packet that has been sitting in the queue "too long".
1045 * When one is detected, all previous (incomplete) fragments are
1046 * discarded, their missing fragments are declared lost and MSEQ
1047 * is increased.
1048 *
1049 * o If we recieve a fragment with seq# < MSEQ, we throw it away
1050 * because we've already delcared it lost.
1051 *
1052 * This assumes linkNum != NG_PPP_BUNDLE_LINKNUM.
1053 */
1054static int
1055ng_ppp_mp_input(node_p node, int linkNum, struct mbuf *m, meta_p meta)
1056{
1057 const priv_p priv = node->private;
1058 struct ng_ppp_link *const link = &priv->links[linkNum];
1059 struct ng_ppp_frag frag0, *frag = &frag0;
1060 struct ng_ppp_frag *qent;
1061 int i, diff, inserted;
1062
1063 /* Stats */
1064 priv->bundleStats.recvFrames++;
1065 priv->bundleStats.recvOctets += m->m_pkthdr.len;
1066
1067 /* Extract fragment information from MP header */
1068 if (priv->conf.recvShortSeq) {
1069 u_int16_t shdr;
1070
1071 if (m->m_pkthdr.len < 2) {
1072 link->stats.runts++;
1073 NG_FREE_DATA(m, meta);
1074 return (EINVAL);
1075 }
1076 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL) {
1077 NG_FREE_META(meta);
1078 return (ENOBUFS);
1079 }
1080 shdr = ntohs(*mtod(m, u_int16_t *));
1081 frag->seq = MP_SHORT_EXTEND(shdr);
1082 frag->first = (shdr & MP_SHORT_FIRST_FLAG) != 0;
1083 frag->last = (shdr & MP_SHORT_LAST_FLAG) != 0;
1084 diff = MP_SHORT_SEQ_DIFF(frag->seq, priv->mseq);
1085 m_adj(m, 2);
1086 } else {
1087 u_int32_t lhdr;
1088
1089 if (m->m_pkthdr.len < 4) {
1090 link->stats.runts++;
1091 NG_FREE_DATA(m, meta);
1092 return (EINVAL);
1093 }
1094 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
1095 NG_FREE_META(meta);
1096 return (ENOBUFS);
1097 }
1098 lhdr = ntohl(*mtod(m, u_int32_t *));
1099 frag->seq = MP_LONG_EXTEND(lhdr);
1100 frag->first = (lhdr & MP_LONG_FIRST_FLAG) != 0;
1101 frag->last = (lhdr & MP_LONG_LAST_FLAG) != 0;
1102 diff = MP_LONG_SEQ_DIFF(frag->seq, priv->mseq);
1103 m_adj(m, 4);
1104 }
1105 frag->data = m;
1106 frag->meta = meta;
1107 getmicrouptime(&frag->timestamp);
1108
1109 /* If sequence number is < MSEQ, we've already declared this
1110 fragment as lost, so we have no choice now but to drop it */
1111 if (diff < 0) {
1112 link->stats.dropFragments++;
1113 NG_FREE_DATA(m, meta);
1114 return (0);
1115 }
1116
1117 /* Update highest received sequence number on this link and MSEQ */
1118 priv->mseq = link->seq = frag->seq;
1119 for (i = 0; i < priv->numActiveLinks; i++) {
1120 struct ng_ppp_link *const alink =
1121 &priv->links[priv->activeLinks[i]];
1122
1123 if (MP_RECV_SEQ_DIFF(priv, alink->seq, priv->mseq) < 0)
1124 priv->mseq = alink->seq;
1125 }
1126
1127 /* Allocate a new frag struct for the queue */
1128 MALLOC(frag, struct ng_ppp_frag *, sizeof(*frag), M_NETGRAPH, M_NOWAIT);
1129 if (frag == NULL) {
1130 NG_FREE_DATA(m, meta);
1131 ng_ppp_frag_process(node);
1132 return (ENOMEM);
1133 }
1134 *frag = frag0;
1135
1136 /* Add fragment to queue, which is sorted by sequence number */
1137 inserted = 0;
1138 TAILQ_FOREACH_REVERSE(qent, &priv->frags, ng_ppp_fraglist, f_qent) {
1139 diff = MP_RECV_SEQ_DIFF(priv, frag->seq, qent->seq);
1140 if (diff > 0) {
1141 TAILQ_INSERT_AFTER(&priv->frags, qent, frag, f_qent);
1142 inserted = 1;
1143 break;
1144 } else if (diff == 0) { /* should never happen! */
1145 link->stats.dupFragments++;
1146 NG_FREE_DATA(frag->data, frag->meta);
1147 FREE(frag, M_NETGRAPH);
1148 return (EINVAL);
1149 }
1150 }
1151 if (!inserted)
1152 TAILQ_INSERT_HEAD(&priv->frags, frag, f_qent);
1153 priv->qlen++;
1154
1155 /* Process the queue */
1156 return ng_ppp_frag_process(node);
1157}
1158
1159/*
1160 * Examine our list of fragments, and determine if there is a
1161 * complete and deliverable packet at the head of the list.
1162 * Return 1 if so, zero otherwise.
1163 */
1164static int
1165ng_ppp_check_packet(node_p node)
1166{
1167 const priv_p priv = node->private;
1168 struct ng_ppp_frag *qent, *qnext;
1169
1170 /* Check for empty queue */
1171 if (TAILQ_EMPTY(&priv->frags))
1172 return (0);
1173
1174 /* Check first fragment is the start of a deliverable packet */
1175 qent = TAILQ_FIRST(&priv->frags);
1176 if (!qent->first || MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) > 1)
1177 return (0);
1178
1179 /* Check that all the fragments are there */
1180 while (!qent->last) {
1181 qnext = TAILQ_NEXT(qent, f_qent);
1182 if (qnext == NULL) /* end of queue */
1183 return (0);
1184 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq))
1185 return (0);
1186 qent = qnext;
1187 }
1188
1189 /* Got one */
1190 return (1);
1191}
1192
1193/*
1194 * Pull a completed packet off the head of the incoming fragment queue.
1195 * This assumes there is a completed packet there to pull off.
1196 */
1197static void
1198ng_ppp_get_packet(node_p node, struct mbuf **mp, meta_p *metap)
1199{
1200 const priv_p priv = node->private;
1201 struct ng_ppp_frag *qent, *qnext;
1202 struct mbuf *m = NULL, *tail;
1203
1204 qent = TAILQ_FIRST(&priv->frags);
1205 KASSERT(!TAILQ_EMPTY(&priv->frags) && qent->first,
1206 ("%s: no packet", __FUNCTION__));
1207 for (tail = NULL; qent != NULL; qent = qnext) {
1208 qnext = TAILQ_NEXT(qent, f_qent);
1209 KASSERT(!TAILQ_EMPTY(&priv->frags),
1210 ("%s: empty q", __FUNCTION__));
1211 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1212 if (tail == NULL) {
1213 tail = m = qent->data;
1214 *metap = qent->meta; /* inherit first frag's meta */
1215 } else {
1216 m->m_pkthdr.len += qent->data->m_pkthdr.len;
1217 tail->m_next = qent->data;
1218 NG_FREE_META(qent->meta); /* drop other frags' metas */
1219 }
1220 while (tail->m_next != NULL)
1221 tail = tail->m_next;
1222 if (qent->last)
1223 qnext = NULL;
1224 FREE(qent, M_NETGRAPH);
1225 priv->qlen--;
1226 }
1227 *mp = m;
1228}
1229
1230/*
1231 * Trim fragments from the queue whose packets can never be completed.
1232 * This assumes a complete packet is NOT at the beginning of the queue.
1233 * Returns 1 if fragments were removed, zero otherwise.
1234 */
1235static int
1236ng_ppp_frag_trim(node_p node)
1237{
1238 const priv_p priv = node->private;
1239 struct ng_ppp_frag *qent, *qnext = NULL;
1240 int removed = 0;
1241
1242 /* Scan for "dead" fragments and remove them */
1243 while (1) {
1244 int dead = 0;
1245
1246 /* If queue is empty, we're done */
1247 if (TAILQ_EMPTY(&priv->frags))
1248 break;
1249
1250 /* Determine whether first fragment can ever be completed */
1251 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1252 if (MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) >= 0)
1253 break;
1254 qnext = TAILQ_NEXT(qent, f_qent);
1255 KASSERT(qnext != NULL,
1256 ("%s: last frag < MSEQ?", __FUNCTION__));
1257 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq)
1258 || qent->last || qnext->first) {
1259 dead = 1;
1260 break;
1261 }
1262 }
1263 if (!dead)
1264 break;
1265
1266 /* Remove fragment and all others in the same packet */
1267 while ((qent = TAILQ_FIRST(&priv->frags)) != qnext) {
1268 KASSERT(!TAILQ_EMPTY(&priv->frags),
1269 ("%s: empty q", __FUNCTION__));
1270 priv->bundleStats.dropFragments++;
1271 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1272 NG_FREE_DATA(qent->data, qent->meta);
1273 FREE(qent, M_NETGRAPH);
1274 priv->qlen--;
1275 removed = 1;
1276 }
1277 }
1278 return (removed);
1279}
1280
1281/*
1282 * Run the queue, restoring the queue invariants
1283 */
1284static int
1285ng_ppp_frag_process(node_p node)
1286{
1287 const priv_p priv = node->private;
1288 struct mbuf *m;
1289 meta_p meta;
1290
1291 /* Deliver any deliverable packets */
1292 while (ng_ppp_check_packet(node)) {
1293 ng_ppp_get_packet(node, &m, &meta);
1294 ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, m, meta);
1295 }
1296
1297 /* Delete dead fragments and try again */
1298 if (ng_ppp_frag_trim(node)) {
1299 while (ng_ppp_check_packet(node)) {
1300 ng_ppp_get_packet(node, &m, &meta);
1301 ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, m, meta);
1302 }
1303 }
1304
1305 /* Check for stale fragments while we're here */
1306 ng_ppp_frag_checkstale(node);
1307
1308 /* Check queue length */
1309 if (priv->qlen > MP_MAX_QUEUE_LEN) {
1310 struct ng_ppp_frag *qent;
1311 int i;
1312
1313 /* Get oldest fragment */
1314 KASSERT(!TAILQ_EMPTY(&priv->frags),
1315 ("%s: empty q", __FUNCTION__));
1316 qent = TAILQ_FIRST(&priv->frags);
1317
1318 /* Bump MSEQ if necessary */
1319 if (MP_RECV_SEQ_DIFF(priv, priv->mseq, qent->seq) < 0) {
1320 priv->mseq = qent->seq;
1321 for (i = 0; i < priv->numActiveLinks; i++) {
1322 struct ng_ppp_link *const alink =
1323 &priv->links[priv->activeLinks[i]];
1324
1325 if (MP_RECV_SEQ_DIFF(priv,
1326 alink->seq, priv->mseq) < 0)
1327 alink->seq = priv->mseq;
1328 }
1329 }
1330
1331 /* Drop it */
1332 priv->bundleStats.dropFragments++;
1333 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1334 NG_FREE_DATA(qent->data, qent->meta);
1335 FREE(qent, M_NETGRAPH);
1336 priv->qlen--;
1337
1338 /* Process queue again */
1339 return ng_ppp_frag_process(node);
1340 }
1341
1342 /* Done */
1343 return (0);
1344}
1345
1346/*
1347 * Check for 'stale' completed packets that need to be delivered
1348 *
1349 * If a link goes down or has a temporary failure, MSEQ can get
1350 * "stuck", because no new incoming fragments appear on that link.
1351 * This can cause completed packets to never get delivered if
1352 * their sequence numbers are all > MSEQ + 1.
1353 *
1354 * This routine checks how long all of the completed packets have
1355 * been sitting in the queue, and if too long, removes fragments
1356 * from the queue and increments MSEQ to allow them to be delivered.
1357 */
1358static void
1359ng_ppp_frag_checkstale(node_p node)
1360{
1361 const priv_p priv = node->private;
1362 struct ng_ppp_frag *qent, *beg, *end;
1363 struct timeval now, age;
1364 struct mbuf *m;
1365 meta_p meta;
1366 int i, seq;
1367
1368 now.tv_sec = 0; /* uninitialized state */
1369 while (1) {
1370
1371 /* If queue is empty, we're done */
1372 if (TAILQ_EMPTY(&priv->frags))
1373 break;
1374
1375 /* Find the first complete packet in the queue */
1376 beg = end = NULL;
1377 seq = TAILQ_FIRST(&priv->frags)->seq;
1378 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1379 if (qent->first)
1380 beg = qent;
1381 else if (qent->seq != seq)
1382 beg = NULL;
1383 if (beg != NULL && qent->last) {
1384 end = qent;
1385 break;
1386 }
1387 seq = MP_NEXT_RECV_SEQ(priv, seq);
1388 }
1389
1390 /* If none found, exit */
1391 if (end == NULL)
1392 break;
1393
1394 /* Get current time (we assume we've been up for >= 1 second) */
1395 if (now.tv_sec == 0)
1396 getmicrouptime(&now);
1397
1398 /* Check if packet has been queued too long */
1399 age = now;
1400 timevalsub(&age, &beg->timestamp);
1401 if (timevalcmp(&age, &ng_ppp_max_staleness, < ))
1402 break;
1403
1404 /* Throw away junk fragments in front of the completed packet */
1405 while ((qent = TAILQ_FIRST(&priv->frags)) != beg) {
1406 KASSERT(!TAILQ_EMPTY(&priv->frags),
1407 ("%s: empty q", __FUNCTION__));
1408 priv->bundleStats.dropFragments++;
1409 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1410 NG_FREE_DATA(qent->data, qent->meta);
1411 FREE(qent, M_NETGRAPH);
1412 priv->qlen--;
1413 }
1414
1415 /* Extract completed packet */
1416 ng_ppp_get_packet(node, &m, &meta);
1417
1418 /* Bump MSEQ if necessary */
1419 if (MP_RECV_SEQ_DIFF(priv, priv->mseq, end->seq) < 0) {
1420 priv->mseq = end->seq;
1421 for (i = 0; i < priv->numActiveLinks; i++) {
1422 struct ng_ppp_link *const alink =
1423 &priv->links[priv->activeLinks[i]];
1424
1425 if (MP_RECV_SEQ_DIFF(priv,
1426 alink->seq, priv->mseq) < 0)
1427 alink->seq = priv->mseq;
1428 }
1429 }
1430
1431 /* Deliver packet */
1432 ng_ppp_input(node, 0, NG_PPP_BUNDLE_LINKNUM, m, meta);
1433 }
1434}
1435
1436/*
1437 * Periodically call ng_ppp_frag_checkstale()
1438 */
1439static void
1440ng_ppp_frag_timeout(void *arg)
1441{
1442 const node_p node = arg;
1443 const priv_p priv = node->private;
1444 int s = splnet();
1445
1446 /* Handle the race where shutdown happens just before splnet() above */
1447 if ((node->flags & NG_INVALID) != 0) {
1448 ng_unref(node);
1449 splx(s);
1450 return;
1451 }
1452
1453 /* Reset timer state after timeout */
1454 KASSERT(priv->timerActive, ("%s: !timerActive", __FUNCTION__));
1455 priv->timerActive = 0;
1456 KASSERT(node->refs > 1, ("%s: refs=%d", __FUNCTION__, node->refs));
1457 ng_unref(node);
1458
1459 /* Start timer again */
1460 ng_ppp_start_frag_timer(node);
1461
1462 /* Scan the fragment queue */
1463 ng_ppp_frag_checkstale(node);
1464 splx(s);
1465}
1466
1467/*
1468 * Deliver a frame out on the bundle, i.e., figure out how to fragment
1469 * the frame across the individual PPP links and do so.
1470 */
1471static int
1472ng_ppp_mp_output(node_p node, struct mbuf *m, meta_p meta)
1473{
1474 const priv_p priv = node->private;
1475 int distrib[NG_PPP_MAX_LINKS];
1476 int firstFragment;
1477 int activeLinkNum;
1478
1479 /* At least one link must be active */
1480 if (priv->numActiveLinks == 0) {
1481 NG_FREE_DATA(m, meta);
1482 return (ENETDOWN);
1483 }
1484
1485 /* Round-robin strategy */
1486 if (priv->conf.enableRoundRobin || m->m_pkthdr.len < MP_MIN_FRAG_LEN) {
1487 activeLinkNum = priv->lastLink++ % priv->numActiveLinks;
1488 bzero(&distrib, priv->numActiveLinks * sizeof(distrib[0]));
1489 distrib[activeLinkNum] = m->m_pkthdr.len;
1490 goto deliver;
1491 }
1492
1493 /* Strategy when all links are equivalent (optimize the common case) */
1494 if (priv->allLinksEqual) {
1495 const int fraction = m->m_pkthdr.len / priv->numActiveLinks;
1496 int i, remain;
1497
1498 for (i = 0; i < priv->numActiveLinks; i++)
1499 distrib[priv->lastLink++ % priv->numActiveLinks]
1500 = fraction;
1501 remain = m->m_pkthdr.len - (fraction * priv->numActiveLinks);
1502 while (remain > 0) {
1503 distrib[priv->lastLink++ % priv->numActiveLinks]++;
1504 remain--;
1505 }
1506 goto deliver;
1507 }
1508
1509 /* Strategy when all links are not equivalent */
1510 ng_ppp_mp_strategy(node, m->m_pkthdr.len, distrib);
1511
1512deliver:
1513 /* Update stats */
1514 priv->bundleStats.xmitFrames++;
1515 priv->bundleStats.xmitOctets += m->m_pkthdr.len;
1516
1517 /* Send alloted portions of frame out on the link(s) */
1518 for (firstFragment = 1, activeLinkNum = priv->numActiveLinks - 1;
1519 activeLinkNum >= 0; activeLinkNum--) {
1520 const int linkNum = priv->activeLinks[activeLinkNum];
1521 struct ng_ppp_link *const link = &priv->links[linkNum];
1522
1523 /* Deliver fragment(s) out the next link */
1524 for ( ; distrib[activeLinkNum] > 0; firstFragment = 0) {
1525 int len, lastFragment, error;
1526 struct mbuf *m2;
1527 meta_p meta2;
1528
1529 /* Calculate fragment length; don't exceed link MTU */
1530 len = distrib[activeLinkNum];
1531 if (len > link->conf.mru)
1532 len = link->conf.mru;
1533 distrib[activeLinkNum] -= len;
1534 lastFragment = (len == m->m_pkthdr.len);
1535
1536 /* Split off next fragment as "m2" */
1537 m2 = m;
1538 if (!lastFragment) {
1539 struct mbuf *n = m_split(m, len, M_NOWAIT);
1540
1541 if (n == NULL) {
1542 NG_FREE_DATA(m, meta);
1543 return (ENOMEM);
1544 }
1545 m = n;
1546 }
1547
1548 /* Prepend MP header */
1549 if (priv->conf.xmitShortSeq) {
1550 u_int16_t shdr;
1551
1552 shdr = priv->xseq;
1553 priv->xseq =
1554 (priv->xseq + 1) & MP_SHORT_SEQ_MASK;
1555 if (firstFragment)
1556 shdr |= MP_SHORT_FIRST_FLAG;
1557 if (lastFragment)
1558 shdr |= MP_SHORT_LAST_FLAG;
1559 shdr = htons(shdr);
1560 m2 = ng_ppp_prepend(m2, &shdr, 2);
1561 } else {
1562 u_int32_t lhdr;
1563
1564 lhdr = priv->xseq;
1565 priv->xseq =
1566 (priv->xseq + 1) & MP_LONG_SEQ_MASK;
1567 if (firstFragment)
1568 lhdr |= MP_LONG_FIRST_FLAG;
1569 if (lastFragment)
1570 lhdr |= MP_LONG_LAST_FLAG;
1571 lhdr = htonl(lhdr);
1572 m2 = ng_ppp_prepend(m2, &lhdr, 4);
1573 }
1574 if (m2 == NULL) {
1575 if (!lastFragment)
1576 m_freem(m);
1577 NG_FREE_META(meta);
1578 return (ENOBUFS);
1579 }
1580
1581 /* Copy the meta information, if any */
1582 meta2 = lastFragment ? meta : ng_copy_meta(meta);
1583
1584 /* Send fragment */
1585 error = ng_ppp_output(node, 0,
1586 PROT_MP, linkNum, m2, meta2);
1587 if (error != 0) {
1588 if (!lastFragment)
1589 NG_FREE_DATA(m, meta);
1590 return (error);
1591 }
1592 }
1593 }
1594
1595 /* Done */
1596 return (0);
1597}
1598
1599/*
1600 * Computing the optimal fragmentation
1601 * -----------------------------------
1602 *
1603 * This routine tries to compute the optimal fragmentation pattern based
1604 * on each link's latency, bandwidth, and calculated additional latency.
1605 * The latter quantity is the additional latency caused by previously
1606 * written data that has not been transmitted yet.
1607 *
1608 * This algorithm is only useful when not all of the links have the
1609 * same latency and bandwidth values.
1610 *
1611 * The essential idea is to make the last bit of each fragment of the
1612 * frame arrive at the opposite end at the exact same time. This greedy
1613 * algorithm is optimal, in that no other scheduling could result in any
1614 * packet arriving any sooner unless packets are delivered out of order.
1615 *
1616 * Suppose link i has bandwidth b_i (in tens of bytes per milisecond) and
1617 * latency l_i (in miliseconds). Consider the function function f_i(t)
1618 * which is equal to the number of bytes that will have arrived at
1619 * the peer after t miliseconds if we start writing continuously at
1620 * time t = 0. Then f_i(t) = b_i * (t - l_i) = ((b_i * t) - (l_i * b_i).
1621 * That is, f_i(t) is a line with slope b_i and y-intersect -(l_i * b_i).
1622 * Note that the y-intersect is always <= zero because latency can't be
1623 * negative. Note also that really the function is f_i(t) except when
1624 * f_i(t) is negative, in which case the function is zero. To take
1625 * care of this, let Q_i(t) = { if (f_i(t) > 0) return 1; else return 0; }.
1626 * So the actual number of bytes that will have arrived at the peer after
1627 * t miliseconds is f_i(t) * Q_i(t).
1628 *
1629 * At any given time, each link has some additional latency a_i >= 0
1630 * due to previously written fragment(s) which are still in the queue.
1631 * This value is easily computed from the time since last transmission,
1632 * the previous latency value, the number of bytes written, and the
1633 * link's bandwidth.
1634 *
1635 * Assume that l_i includes any a_i already, and that the links are
1636 * sorted by latency, so that l_i <= l_{i+1}.
1637 *
1638 * Let N be the total number of bytes in the current frame we are sending.
1639 *
1640 * Suppose we were to start writing bytes at time t = 0 on all links
1641 * simultaneously, which is the most we can possibly do. Then let
1642 * F(t) be equal to the total number of bytes received by the peer
1643 * after t miliseconds. Then F(t) = Sum_i (f_i(t) * Q_i(t)).
1644 *
1645 * Our goal is simply this: fragment the frame across the links such
1646 * that the peer is able to reconstruct the completed frame as soon as
1647 * possible, i.e., at the least possible value of t. Call this value t_0.
1648 *
1649 * Then it follows that F(t_0) = N. Our strategy is first to find the value
1650 * of t_0, and then deduce how many bytes to write to each link.
1651 *
1652 * Rewriting F(t_0):
1653 *
1654 * t_0 = ( N + Sum_i ( l_i * b_i * Q_i(t_0) ) ) / Sum_i ( b_i * Q_i(t_0) )
1655 *
1656 * Now, we note that Q_i(t) is constant for l_i <= t <= l_{i+1}. t_0 will
1657 * lie in one of these ranges. To find it, we just need to find the i such
1658 * that F(l_i) <= N <= F(l_{i+1}). Then we compute all the constant values
1659 * for Q_i() in this range, plug in the remaining values, solving for t_0.
1660 *
1661 * Once t_0 is known, then the number of bytes to send on link i is
1662 * just f_i(t_0) * Q_i(t_0).
1663 *
1664 * In other words, we start allocating bytes to the links one at a time.
1665 * We keep adding links until the frame is completely sent. Some links
1666 * may not get any bytes because their latency is too high.
1667 *
1668 * Is all this work really worth the trouble? Depends on the situation.
1669 * The bigger the ratio of computer speed to link speed, and the more
1670 * important total bundle latency is (e.g., for interactive response time),
1671 * the more it's worth it. There is however the cost of calling this
1672 * function for every frame. The running time is O(n^2) where n is the
1673 * number of links that receive a non-zero number of bytes.
1674 *
1675 * Since latency is measured in miliseconds, the "resolution" of this
1676 * algorithm is one milisecond.
1677 *
1678 * To avoid this algorithm altogether, configure all links to have the
1679 * same latency and bandwidth.
1680 */
1681static void
1682ng_ppp_mp_strategy(node_p node, int len, int *distrib)
1683{
1684 const priv_p priv = node->private;
1685 int latency[NG_PPP_MAX_LINKS];
1686 int sortByLatency[NG_PPP_MAX_LINKS];
1687 int activeLinkNum;
1688 int t0, total, topSum, botSum;
1689 struct timeval now;
1690 int i, numFragments;
1691
1692 /* If only one link, this gets real easy */
1693 if (priv->numActiveLinks == 1) {
1694 distrib[0] = len;
1695 return;
1696 }
1697
1698 /* Get current time */
1699 getmicrouptime(&now);
1700
1701 /* Compute latencies for each link at this point in time */
1702 for (activeLinkNum = 0;
1703 activeLinkNum < priv->numActiveLinks; activeLinkNum++) {
1704 struct ng_ppp_link *alink;
1705 struct timeval diff;
1706 int xmitBytes;
1707
1708 /* Start with base latency value */
1709 alink = &priv->links[priv->activeLinks[activeLinkNum]];
1710 latency[activeLinkNum] = alink->conf.latency;
1711 sortByLatency[activeLinkNum] = activeLinkNum; /* see below */
1712
1713 /* Any additional latency? */
1714 if (alink->bytesInQueue == 0)
1715 continue;
1716
1717 /* Compute time delta since last write */
1718 diff = now;
1719 timevalsub(&diff, &alink->lastWrite);
1720 if (now.tv_sec < 0 || diff.tv_sec >= 10) { /* sanity */
1721 alink->bytesInQueue = 0;
1722 continue;
1723 }
1724
1725 /* How many bytes could have transmitted since last write? */
1726 xmitBytes = (alink->conf.bandwidth * diff.tv_sec)
1727 + (alink->conf.bandwidth * (diff.tv_usec / 1000)) / 100;
1728 alink->bytesInQueue -= xmitBytes;
1729 if (alink->bytesInQueue < 0)
1730 alink->bytesInQueue = 0;
1731 else
1732 latency[activeLinkNum] +=
1733 (100 * alink->bytesInQueue) / alink->conf.bandwidth;
1734 }
1735
1736 /* Sort active links by latency */
1737 compareLatencies = latency;
1738 qsort(sortByLatency,
1739 priv->numActiveLinks, sizeof(*sortByLatency), ng_ppp_intcmp);
1740 compareLatencies = NULL;
1741
1742 /* Find the interval we need (add links in sortByLatency[] order) */
1743 for (numFragments = 1;
1744 numFragments < priv->numActiveLinks; numFragments++) {
1745 for (total = i = 0; i < numFragments; i++) {
1746 int flowTime;
1747
1748 flowTime = latency[sortByLatency[numFragments]]
1749 - latency[sortByLatency[i]];
1750 total += ((flowTime * priv->links[
1751 priv->activeLinks[sortByLatency[i]]].conf.bandwidth)
1752 + 99) / 100;
1753 }
1754 if (total >= len)
1755 break;
1756 }
1757
1758 /* Solve for t_0 in that interval */
1759 for (topSum = botSum = i = 0; i < numFragments; i++) {
1760 int bw = priv->links[
1761 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
1762
1763 topSum += latency[sortByLatency[i]] * bw; /* / 100 */
1764 botSum += bw; /* / 100 */
1765 }
1766 t0 = ((len * 100) + topSum + botSum / 2) / botSum;
1767
1768 /* Compute f_i(t_0) all i */
1769 bzero(distrib, priv->numActiveLinks * sizeof(*distrib));
1770 for (total = i = 0; i < numFragments; i++) {
1771 int bw = priv->links[
1772 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
1773
1774 distrib[sortByLatency[i]] =
1775 (bw * (t0 - latency[sortByLatency[i]]) + 50) / 100;
1776 total += distrib[sortByLatency[i]];
1777 }
1778
1779 /* Deal with any rounding error */
1780 if (total < len) {
1781 struct ng_ppp_link *fastLink =
1782 &priv->links[priv->activeLinks[sortByLatency[0]]];
1783 int fast = 0;
1784
1785 /* Find the fastest link */
1786 for (i = 1; i < numFragments; i++) {
1787 struct ng_ppp_link *const link =
1788 &priv->links[priv->activeLinks[sortByLatency[i]]];
1789
1790 if (link->conf.bandwidth > fastLink->conf.bandwidth) {
1791 fast = i;
1792 fastLink = link;
1793 }
1794 }
1795 distrib[sortByLatency[fast]] += len - total;
1796 } else while (total > len) {
1797 struct ng_ppp_link *slowLink =
1798 &priv->links[priv->activeLinks[sortByLatency[0]]];
1799 int delta, slow = 0;
1800
1801 /* Find the slowest link that still has bytes to remove */
1802 for (i = 1; i < numFragments; i++) {
1803 struct ng_ppp_link *const link =
1804 &priv->links[priv->activeLinks[sortByLatency[i]]];
1805
1806 if (distrib[sortByLatency[slow]] == 0
1807 || (distrib[sortByLatency[i]] > 0
1808 && link->conf.bandwidth <
1809 slowLink->conf.bandwidth)) {
1810 slow = i;
1811 slowLink = link;
1812 }
1813 }
1814 delta = total - len;
1815 if (delta > distrib[sortByLatency[slow]])
1816 delta = distrib[sortByLatency[slow]];
1817 distrib[sortByLatency[slow]] -= delta;
1818 total -= delta;
1819 }
1820}
1821
1822/*
1823 * Compare two integers
1824 */
1825static int
1826ng_ppp_intcmp(const void *v1, const void *v2)
1827{
1828 const int index1 = *((const int *) v1);
1829 const int index2 = *((const int *) v2);
1830
1831 return compareLatencies[index1] - compareLatencies[index2];
1832}
1833
1834/*
1835 * Prepend a possibly compressed PPP protocol number in front of a frame
1836 */
1837static struct mbuf *
1838ng_ppp_addproto(struct mbuf *m, int proto, int compOK)
1839{
1840 if (compOK && PROT_COMPRESSABLE(proto)) {
1841 u_char pbyte = (u_char)proto;
1842
1843 return ng_ppp_prepend(m, &pbyte, 1);
1844 } else {
1845 u_int16_t pword = htons((u_int16_t)proto);
1846
1847 return ng_ppp_prepend(m, &pword, 2);
1848 }
1849}
1850
1851/*
1852 * Prepend some bytes to an mbuf
1853 */
1854static struct mbuf *
1855ng_ppp_prepend(struct mbuf *m, const void *buf, int len)
1856{
1857 M_PREPEND(m, len, M_NOWAIT);
1858 if (m == NULL || (m->m_len < len && (m = m_pullup(m, len)) == NULL))
1859 return (NULL);
1860 bcopy(buf, mtod(m, u_char *), len);
1861 return (m);
1862}
1863
1864/*
1865 * Update private information that is derived from other private information
1866 */
1867static void
1868ng_ppp_update(node_p node, int newConf)
1869{
1870 const priv_p priv = node->private;
1871 int i;
1872
1873 /* Update active status for VJ Compression */
1874 priv->vjCompHooked = priv->hooks[HOOK_INDEX_VJC_IP] != NULL
1875 && priv->hooks[HOOK_INDEX_VJC_COMP] != NULL
1876 && priv->hooks[HOOK_INDEX_VJC_UNCOMP] != NULL
1877 && priv->hooks[HOOK_INDEX_VJC_VJIP] != NULL;
1878
1879 /* Increase latency for each link an amount equal to one MP header */
1880 if (newConf) {
1881 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
1882 int hdrBytes;
1883
1884 hdrBytes = (priv->links[i].conf.enableACFComp ? 0 : 2)
1885 + (priv->links[i].conf.enableProtoComp ? 1 : 2)
1886 + (priv->conf.xmitShortSeq ? 2 : 4);
1887 priv->links[i].conf.latency +=
1888 ((hdrBytes * priv->links[i].conf.bandwidth) + 50)
1889 / 100;
1890 }
1891 }
1892
1893 /* Update list of active links */
1894 bzero(&priv->activeLinks, sizeof(priv->activeLinks));
1895 priv->numActiveLinks = 0;
1896 priv->allLinksEqual = 1;
1897 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
1898 struct ng_ppp_link *const link = &priv->links[i];
1899
1900 /* Is link active? */
1901 if (link->conf.enableLink && link->hook != NULL) {
1902 struct ng_ppp_link *link0;
1903
1904 /* Add link to list of active links */
1905 priv->activeLinks[priv->numActiveLinks++] = i;
1906 link0 = &priv->links[priv->activeLinks[0]];
1907
1908 /* Determine if all links are still equal */
1909 if (link->conf.latency != link0->conf.latency
1910 || link->conf.bandwidth != link0->conf.bandwidth)
1911 priv->allLinksEqual = 0;
1912
1913 /* Initialize rec'd sequence number */
1914 if (link->seq == MP_NOSEQ) {
1915 link->seq = (link == link0) ?
1916 MP_INITIAL_SEQ : link0->seq;
1917 }
1918 } else
1919 link->seq = MP_NOSEQ;
1920 }
1921
1922 /* Update MP state as multi-link is active or not */
1923 if (priv->conf.enableMultilink && priv->numActiveLinks > 0)
1924 ng_ppp_start_frag_timer(node);
1925 else {
1926 ng_ppp_stop_frag_timer(node);
1927 ng_ppp_frag_reset(node);
1928 priv->xseq = MP_INITIAL_SEQ;
1929 priv->mseq = MP_INITIAL_SEQ;
1930 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
1931 struct ng_ppp_link *const link = &priv->links[i];
1932
1933 bzero(&link->lastWrite, sizeof(link->lastWrite));
1934 link->bytesInQueue = 0;
1935 link->seq = MP_NOSEQ;
1936 }
1937 }
1938}
1939
1940/*
1941 * Determine if a new configuration would represent a valid change
1942 * from the current configuration and link activity status.
1943 */
1944static int
1945ng_ppp_config_valid(node_p node, const struct ng_ppp_node_conf *newConf)
1946{
1947 const priv_p priv = node->private;
1948 int i, newNumLinksActive;
1949
1950 /* Check per-link config and count how many links would be active */
1951 for (newNumLinksActive = i = 0; i < NG_PPP_MAX_LINKS; i++) {
1952 if (newConf->links[i].enableLink && priv->links[i].hook != NULL)
1953 newNumLinksActive++;
1954 if (!newConf->links[i].enableLink)
1955 continue;
1956 if (newConf->links[i].mru < MP_MIN_LINK_MRU)
1957 return (0);
1958 if (newConf->links[i].bandwidth == 0)
1959 return (0);
1960 if (newConf->links[i].bandwidth > NG_PPP_MAX_BANDWIDTH)
1961 return (0);
1962 if (newConf->links[i].latency > NG_PPP_MAX_LATENCY)
1963 return (0);
1964 }
1965
1966 /* Check bundle parameters */
1967 if (newConf->bund.enableMultilink && newConf->bund.mrru < MP_MIN_MRRU)
1968 return (0);
1969
1970 /* Disallow changes to multi-link configuration while MP is active */
1971 if (priv->numActiveLinks > 0 && newNumLinksActive > 0) {
1972 if (!priv->conf.enableMultilink
1973 != !newConf->bund.enableMultilink
1974 || !priv->conf.xmitShortSeq != !newConf->bund.xmitShortSeq
1975 || !priv->conf.recvShortSeq != !newConf->bund.recvShortSeq)
1976 return (0);
1977 }
1978
1979 /* At most one link can be active unless multi-link is enabled */
1980 if (!newConf->bund.enableMultilink && newNumLinksActive > 1)
1981 return (0);
1982
1983 /* Configuration change would be valid */
1984 return (1);
1985}
1986
1987/*
1988 * Free all entries in the fragment queue
1989 */
1990static void
1991ng_ppp_frag_reset(node_p node)
1992{
1993 const priv_p priv = node->private;
1994 struct ng_ppp_frag *qent, *qnext;
1995
1996 for (qent = TAILQ_FIRST(&priv->frags); qent; qent = qnext) {
1997 qnext = TAILQ_NEXT(qent, f_qent);
1998 NG_FREE_DATA(qent->data, qent->meta);
1999 FREE(qent, M_NETGRAPH);
2000 }
2001 TAILQ_INIT(&priv->frags);
2002 priv->qlen = 0;
2003}
2004
2005/*
2006 * Start fragment queue timer
2007 */
2008static void
2009ng_ppp_start_frag_timer(node_p node)
2010{
2011 const priv_p priv = node->private;
2012
2013 if (!priv->timerActive) {
2014 priv->fragTimer = timeout(ng_ppp_frag_timeout,
2015 node, MP_FRAGTIMER_INTERVAL);
2016 priv->timerActive = 1;
2017 node->refs++;
2018 }
2019}
2020
2021/*
2022 * Stop fragment queue timer
2023 */
2024static void
2025ng_ppp_stop_frag_timer(node_p node)
2026{
2027 const priv_p priv = node->private;
2028
2029 if (priv->timerActive) {
2030 untimeout(ng_ppp_frag_timeout, node, priv->fragTimer);
2031 priv->timerActive = 0;
2032 KASSERT(node->refs > 1,
2033 ("%s: refs=%d", __FUNCTION__, node->refs));
2034 ng_unref(node);
2035 }
2036}
2037