2 * Copyright (c) 1996-2000 Whistle Communications, Inc.
5 * Subject to the following obligations and disclaimer of warranty, use and
6 * redistribution of this software, in source or object code forms, with or
7 * without modifications are expressly permitted by Whistle Communications;
8 * provided, however, that:
9 * 1. Any and all reproductions of the source or object code must include the
10 * copyright notice above and the following disclaimer of warranties; and
11 * 2. No rights are granted, in any manner or form, to use Whistle
12 * Communications, Inc. trademarks, including the mark "WHISTLE
13 * COMMUNICATIONS" on advertising, endorsements, or otherwise except as
14 * such appears in the above copyright notice or in the software.
16 * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
17 * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
18 * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
19 * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
21 * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
22 * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
23 * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
24 * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
25 * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
26 * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
27 * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
28 * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
29 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
34 * Copyright (c) 2007 Alexander Motin <mav@alkar.net>
35 * All rights reserved.
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
40 * 1. Redistributions of source code must retain the above copyright
41 * notice unmodified, this list of conditions, and the following
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
47 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
48 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
51 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59 * Authors: Archie Cobbs <archie@freebsd.org>, Alexander Motin <mav@alkar.net>
62 * $Whistle: ng_ppp.c,v 1.24 1999/11/01 09:24:52 julian Exp $
66 * PPP node type data-flow.
68 * hook xmit layer recv hook
69 * ------------------------------------
75 * -hcomp_xmit()----------proto_recv()-
77 * vjc_comp -> header compression -> vjc_comp
78 * vjc_uncomp -> -> vjc_uncomp
80 * -comp_xmit()-----------hcomp_recv()-
81 * compress <- compression <- decompress
82 * compress -> -> decompress
83 * -crypt_xmit()-----------comp_recv()-
84 * encrypt <- encryption <- decrypt
85 * encrypt -> -> decrypt
86 * -ml_xmit()-------------crypt_recv()-
88 * -link_xmit()--------------ml_recv()-
89 * linkX <- link <- linkX
93 #include <sys/param.h>
94 #include <sys/systm.h>
95 #include <sys/kernel.h>
96 #include <sys/limits.h>
99 #include <sys/malloc.h>
100 #include <sys/endian.h>
101 #include <sys/errno.h>
102 #include <sys/ctype.h>
104 #include <netgraph/ng_message.h>
105 #include <netgraph/netgraph.h>
106 #include <netgraph/ng_parse.h>
107 #include <netgraph/ng_ppp.h>
108 #include <netgraph/ng_vjc.h>
110 #ifdef NG_SEPARATE_MALLOC
111 MALLOC_DEFINE(M_NETGRAPH_PPP, "netgraph_ppp", "netgraph ppp node");
113 #define M_NETGRAPH_PPP M_NETGRAPH
116 #define PROT_VALID(p) (((p) & 0x0101) == 0x0001)
117 #define PROT_COMPRESSABLE(p) (((p) & 0xff00) == 0x0000)
119 /* Some PPP protocol numbers we're interested in */
120 #define PROT_ATALK 0x0029
121 #define PROT_COMPD 0x00fd
122 #define PROT_CRYPTD 0x0053
123 #define PROT_IP 0x0021
124 #define PROT_IPV6 0x0057
125 #define PROT_IPX 0x002b
126 #define PROT_LCP 0xc021
127 #define PROT_MP 0x003d
128 #define PROT_VJCOMP 0x002d
129 #define PROT_VJUNCOMP 0x002f
131 /* Multilink PPP definitions */
132 #define MP_INITIAL_SEQ 0 /* per RFC 1990 */
133 #define MP_MIN_LINK_MRU 32
135 #define MP_SHORT_SEQ_MASK 0x00000fff /* short seq # mask */
136 #define MP_SHORT_SEQ_HIBIT 0x00000800 /* short seq # high bit */
137 #define MP_SHORT_FIRST_FLAG 0x00008000 /* first fragment in frame */
138 #define MP_SHORT_LAST_FLAG 0x00004000 /* last fragment in frame */
140 #define MP_LONG_SEQ_MASK 0x00ffffff /* long seq # mask */
141 #define MP_LONG_SEQ_HIBIT 0x00800000 /* long seq # high bit */
142 #define MP_LONG_FIRST_FLAG 0x80000000 /* first fragment in frame */
143 #define MP_LONG_LAST_FLAG 0x40000000 /* last fragment in frame */
145 #define MP_NOSEQ 0x7fffffff /* impossible sequence number */
147 /* Sign extension of MP sequence numbers */
148 #define MP_SHORT_EXTEND(s) (((s) & MP_SHORT_SEQ_HIBIT) ? \
149 ((s) | ~MP_SHORT_SEQ_MASK) \
150 : ((s) & MP_SHORT_SEQ_MASK))
151 #define MP_LONG_EXTEND(s) (((s) & MP_LONG_SEQ_HIBIT) ? \
152 ((s) | ~MP_LONG_SEQ_MASK) \
153 : ((s) & MP_LONG_SEQ_MASK))
155 /* Comparision of MP sequence numbers. Note: all sequence numbers
156 except priv->xseq are stored with the sign bit extended. */
157 #define MP_SHORT_SEQ_DIFF(x,y) MP_SHORT_EXTEND((x) - (y))
158 #define MP_LONG_SEQ_DIFF(x,y) MP_LONG_EXTEND((x) - (y))
160 #define MP_RECV_SEQ_DIFF(priv,x,y) \
161 ((priv)->conf.recvShortSeq ? \
162 MP_SHORT_SEQ_DIFF((x), (y)) : \
163 MP_LONG_SEQ_DIFF((x), (y)))
165 /* Increment receive sequence number */
166 #define MP_NEXT_RECV_SEQ(priv,seq) \
167 ((priv)->conf.recvShortSeq ? \
168 MP_SHORT_EXTEND((seq) + 1) : \
169 MP_LONG_EXTEND((seq) + 1))
171 /* Don't fragment transmitted packets to parts smaller than this */
172 #define MP_MIN_FRAG_LEN 32
174 /* Maximum fragment reasssembly queue length */
175 #define MP_MAX_QUEUE_LEN 128
177 /* Fragment queue scanner period */
178 #define MP_FRAGTIMER_INTERVAL (hz/2)
180 /* Average link overhead. XXX: Should be given by user-level */
181 #define MP_AVERAGE_LINK_OVERHEAD 16
183 /* Keep this equal to ng_ppp_hook_names lower! */
184 #define HOOK_INDEX_MAX 13
186 /* We store incoming fragments this way */
188 int seq; /* fragment seq# */
189 uint8_t first; /* First in packet? */
190 uint8_t last; /* Last in packet? */
191 struct timeval timestamp; /* time of reception */
192 struct mbuf *data; /* Fragment data */
193 TAILQ_ENTRY(ng_ppp_frag) f_qent; /* Fragment queue */
196 /* Per-link private information */
198 struct ng_ppp_link_conf conf; /* link configuration */
199 struct ng_ppp_link_stat64 stats; /* link stats */
200 hook_p hook; /* connection to link data */
201 int32_t seq; /* highest rec'd seq# - MSEQ */
202 uint32_t latency; /* calculated link latency */
203 struct timeval lastWrite; /* time of last write for MP */
204 int bytesInQueue; /* bytes in the output queue for MP */
207 /* Total per-node private information */
208 struct ng_ppp_private {
209 struct ng_ppp_bund_conf conf; /* bundle config */
210 struct ng_ppp_link_stat64 bundleStats; /* bundle stats */
211 struct ng_ppp_link links[NG_PPP_MAX_LINKS];/* per-link info */
212 int32_t xseq; /* next out MP seq # */
213 int32_t mseq; /* min links[i].seq */
214 uint16_t activeLinks[NG_PPP_MAX_LINKS]; /* indicies */
215 uint16_t numActiveLinks; /* how many links up */
216 uint16_t lastLink; /* for round robin */
217 uint8_t vjCompHooked; /* VJ comp hooked up? */
218 uint8_t allLinksEqual; /* all xmit the same? */
219 hook_p hooks[HOOK_INDEX_MAX]; /* non-link hooks */
220 struct ng_ppp_frag fragsmem[MP_MAX_QUEUE_LEN]; /* fragments storage */
221 TAILQ_HEAD(ng_ppp_fraglist, ng_ppp_frag) /* fragment queue */
223 TAILQ_HEAD(ng_ppp_fragfreelist, ng_ppp_frag) /* free fragment queue */
225 struct callout fragTimer; /* fraq queue check */
226 struct mtx rmtx; /* recv mutex */
227 struct mtx xmtx; /* xmit mutex */
229 typedef struct ng_ppp_private *priv_p;
231 /* Netgraph node methods */
232 static ng_constructor_t ng_ppp_constructor;
233 static ng_rcvmsg_t ng_ppp_rcvmsg;
234 static ng_shutdown_t ng_ppp_shutdown;
235 static ng_newhook_t ng_ppp_newhook;
236 static ng_rcvdata_t ng_ppp_rcvdata;
237 static ng_disconnect_t ng_ppp_disconnect;
239 static ng_rcvdata_t ng_ppp_rcvdata_inet;
240 static ng_rcvdata_t ng_ppp_rcvdata_ipv6;
241 static ng_rcvdata_t ng_ppp_rcvdata_ipx;
242 static ng_rcvdata_t ng_ppp_rcvdata_atalk;
243 static ng_rcvdata_t ng_ppp_rcvdata_bypass;
245 static ng_rcvdata_t ng_ppp_rcvdata_vjc_ip;
246 static ng_rcvdata_t ng_ppp_rcvdata_vjc_comp;
247 static ng_rcvdata_t ng_ppp_rcvdata_vjc_uncomp;
248 static ng_rcvdata_t ng_ppp_rcvdata_vjc_vjip;
250 static ng_rcvdata_t ng_ppp_rcvdata_compress;
251 static ng_rcvdata_t ng_ppp_rcvdata_decompress;
253 static ng_rcvdata_t ng_ppp_rcvdata_encrypt;
254 static ng_rcvdata_t ng_ppp_rcvdata_decrypt;
256 /* We use integer indicies to refer to the non-link hooks. */
257 static const struct {
260 } ng_ppp_hook_names[] = {
261 #define HOOK_INDEX_ATALK 0
262 { NG_PPP_HOOK_ATALK, ng_ppp_rcvdata_atalk },
263 #define HOOK_INDEX_BYPASS 1
264 { NG_PPP_HOOK_BYPASS, ng_ppp_rcvdata_bypass },
265 #define HOOK_INDEX_COMPRESS 2
266 { NG_PPP_HOOK_COMPRESS, ng_ppp_rcvdata_compress },
267 #define HOOK_INDEX_ENCRYPT 3
268 { NG_PPP_HOOK_ENCRYPT, ng_ppp_rcvdata_encrypt },
269 #define HOOK_INDEX_DECOMPRESS 4
270 { NG_PPP_HOOK_DECOMPRESS, ng_ppp_rcvdata_decompress },
271 #define HOOK_INDEX_DECRYPT 5
272 { NG_PPP_HOOK_DECRYPT, ng_ppp_rcvdata_decrypt },
273 #define HOOK_INDEX_INET 6
274 { NG_PPP_HOOK_INET, ng_ppp_rcvdata_inet },
275 #define HOOK_INDEX_IPX 7
276 { NG_PPP_HOOK_IPX, ng_ppp_rcvdata_ipx },
277 #define HOOK_INDEX_VJC_COMP 8
278 { NG_PPP_HOOK_VJC_COMP, ng_ppp_rcvdata_vjc_comp },
279 #define HOOK_INDEX_VJC_IP 9
280 { NG_PPP_HOOK_VJC_IP, ng_ppp_rcvdata_vjc_ip },
281 #define HOOK_INDEX_VJC_UNCOMP 10
282 { NG_PPP_HOOK_VJC_UNCOMP, ng_ppp_rcvdata_vjc_uncomp },
283 #define HOOK_INDEX_VJC_VJIP 11
284 { NG_PPP_HOOK_VJC_VJIP, ng_ppp_rcvdata_vjc_vjip },
285 #define HOOK_INDEX_IPV6 12
286 { NG_PPP_HOOK_IPV6, ng_ppp_rcvdata_ipv6 },
290 /* Helper functions */
291 static int ng_ppp_proto_recv(node_p node, item_p item, uint16_t proto,
293 static int ng_ppp_hcomp_xmit(node_p node, item_p item, uint16_t proto);
294 static int ng_ppp_hcomp_recv(node_p node, item_p item, uint16_t proto,
296 static int ng_ppp_comp_xmit(node_p node, item_p item, uint16_t proto);
297 static int ng_ppp_comp_recv(node_p node, item_p item, uint16_t proto,
299 static int ng_ppp_crypt_xmit(node_p node, item_p item, uint16_t proto);
300 static int ng_ppp_crypt_recv(node_p node, item_p item, uint16_t proto,
302 static int ng_ppp_mp_xmit(node_p node, item_p item, uint16_t proto);
303 static int ng_ppp_mp_recv(node_p node, item_p item, uint16_t proto,
305 static int ng_ppp_link_xmit(node_p node, item_p item, uint16_t proto,
306 uint16_t linkNum, int plen);
308 static int ng_ppp_bypass(node_p node, item_p item, uint16_t proto,
311 static void ng_ppp_bump_mseq(node_p node, int32_t new_mseq);
312 static int ng_ppp_frag_drop(node_p node);
313 static int ng_ppp_check_packet(node_p node);
314 static void ng_ppp_get_packet(node_p node, struct mbuf **mp);
315 static int ng_ppp_frag_process(node_p node, item_p oitem);
316 static int ng_ppp_frag_trim(node_p node);
317 static void ng_ppp_frag_timeout(node_p node, hook_p hook, void *arg1,
319 static void ng_ppp_frag_checkstale(node_p node);
320 static void ng_ppp_frag_reset(node_p node);
321 static void ng_ppp_mp_strategy(node_p node, int len, int *distrib);
322 static int ng_ppp_intcmp(void *latency, const void *v1, const void *v2);
323 static struct mbuf *ng_ppp_addproto(struct mbuf *m, uint16_t proto, int compOK);
324 static struct mbuf *ng_ppp_cutproto(struct mbuf *m, uint16_t *proto);
325 static struct mbuf *ng_ppp_prepend(struct mbuf *m, const void *buf, int len);
326 static int ng_ppp_config_valid(node_p node,
327 const struct ng_ppp_node_conf *newConf);
328 static void ng_ppp_update(node_p node, int newConf);
329 static void ng_ppp_start_frag_timer(node_p node);
330 static void ng_ppp_stop_frag_timer(node_p node);
332 /* Parse type for struct ng_ppp_mp_state_type */
333 static const struct ng_parse_fixedarray_info ng_ppp_rseq_array_info = {
334 &ng_parse_hint32_type,
337 static const struct ng_parse_type ng_ppp_rseq_array_type = {
338 &ng_parse_fixedarray_type,
339 &ng_ppp_rseq_array_info,
341 static const struct ng_parse_struct_field ng_ppp_mp_state_type_fields[]
342 = NG_PPP_MP_STATE_TYPE_INFO(&ng_ppp_rseq_array_type);
343 static const struct ng_parse_type ng_ppp_mp_state_type = {
344 &ng_parse_struct_type,
345 &ng_ppp_mp_state_type_fields
348 /* Parse type for struct ng_ppp_link_conf */
349 static const struct ng_parse_struct_field ng_ppp_link_type_fields[]
350 = NG_PPP_LINK_TYPE_INFO;
351 static const struct ng_parse_type ng_ppp_link_type = {
352 &ng_parse_struct_type,
353 &ng_ppp_link_type_fields
356 /* Parse type for struct ng_ppp_bund_conf */
357 static const struct ng_parse_struct_field ng_ppp_bund_type_fields[]
358 = NG_PPP_BUND_TYPE_INFO;
359 static const struct ng_parse_type ng_ppp_bund_type = {
360 &ng_parse_struct_type,
361 &ng_ppp_bund_type_fields
364 /* Parse type for struct ng_ppp_node_conf */
365 static const struct ng_parse_fixedarray_info ng_ppp_array_info = {
369 static const struct ng_parse_type ng_ppp_link_array_type = {
370 &ng_parse_fixedarray_type,
373 static const struct ng_parse_struct_field ng_ppp_conf_type_fields[]
374 = NG_PPP_CONFIG_TYPE_INFO(&ng_ppp_bund_type, &ng_ppp_link_array_type);
375 static const struct ng_parse_type ng_ppp_conf_type = {
376 &ng_parse_struct_type,
377 &ng_ppp_conf_type_fields
380 /* Parse type for struct ng_ppp_link_stat */
381 static const struct ng_parse_struct_field ng_ppp_stats_type_fields[]
382 = NG_PPP_STATS_TYPE_INFO;
383 static const struct ng_parse_type ng_ppp_stats_type = {
384 &ng_parse_struct_type,
385 &ng_ppp_stats_type_fields
388 /* Parse type for struct ng_ppp_link_stat64 */
389 static const struct ng_parse_struct_field ng_ppp_stats64_type_fields[]
390 = NG_PPP_STATS64_TYPE_INFO;
391 static const struct ng_parse_type ng_ppp_stats64_type = {
392 &ng_parse_struct_type,
393 &ng_ppp_stats64_type_fields
396 /* List of commands and how to convert arguments to/from ASCII */
397 static const struct ng_cmdlist ng_ppp_cmds[] = {
414 NGM_PPP_GET_MP_STATE,
417 &ng_ppp_mp_state_type
421 NGM_PPP_GET_LINK_STATS,
423 &ng_parse_int16_type,
428 NGM_PPP_CLR_LINK_STATS,
430 &ng_parse_int16_type,
435 NGM_PPP_GETCLR_LINK_STATS,
437 &ng_parse_int16_type,
442 NGM_PPP_GET_LINK_STATS64,
444 &ng_parse_int16_type,
449 NGM_PPP_GETCLR_LINK_STATS64,
451 &ng_parse_int16_type,
457 /* Node type descriptor */
458 static struct ng_type ng_ppp_typestruct = {
459 .version = NG_ABI_VERSION,
460 .name = NG_PPP_NODE_TYPE,
461 .constructor = ng_ppp_constructor,
462 .rcvmsg = ng_ppp_rcvmsg,
463 .shutdown = ng_ppp_shutdown,
464 .newhook = ng_ppp_newhook,
465 .rcvdata = ng_ppp_rcvdata,
466 .disconnect = ng_ppp_disconnect,
467 .cmdlist = ng_ppp_cmds,
469 NETGRAPH_INIT(ppp, &ng_ppp_typestruct);
471 /* Address and control field header */
472 static const uint8_t ng_ppp_acf[2] = { 0xff, 0x03 };
474 /* Maximum time we'll let a complete incoming packet sit in the queue */
475 static const struct timeval ng_ppp_max_staleness = { 2, 0 }; /* 2 seconds */
477 #define ERROUT(x) do { error = (x); goto done; } while (0)
479 /************************************************************************
481 ************************************************************************/
484 * Node type constructor
487 ng_ppp_constructor(node_p node)
492 /* Allocate private structure */
493 priv = malloc(sizeof(*priv), M_NETGRAPH_PPP, M_WAITOK | M_ZERO);
495 NG_NODE_SET_PRIVATE(node, priv);
497 /* Initialize state */
498 TAILQ_INIT(&priv->frags);
499 TAILQ_INIT(&priv->fragsfree);
500 for (i = 0; i < MP_MAX_QUEUE_LEN; i++)
501 TAILQ_INSERT_TAIL(&priv->fragsfree, &priv->fragsmem[i], f_qent);
502 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
503 priv->links[i].seq = MP_NOSEQ;
504 ng_callout_init(&priv->fragTimer);
506 mtx_init(&priv->rmtx, "ng_ppp_recv", NULL, MTX_DEF);
507 mtx_init(&priv->xmtx, "ng_ppp_xmit", NULL, MTX_DEF);
514 * Give our OK for a hook to be added
517 ng_ppp_newhook(node_p node, hook_p hook, const char *name)
519 const priv_p priv = NG_NODE_PRIVATE(node);
520 hook_p *hookPtr = NULL;
524 /* Figure out which hook it is */
525 if (strncmp(name, NG_PPP_HOOK_LINK_PREFIX, /* a link hook? */
526 strlen(NG_PPP_HOOK_LINK_PREFIX)) == 0) {
530 cp = name + strlen(NG_PPP_HOOK_LINK_PREFIX);
531 if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
533 linkNum = (int)strtoul(cp, &eptr, 10);
534 if (*eptr != '\0' || linkNum < 0 || linkNum >= NG_PPP_MAX_LINKS)
536 hookPtr = &priv->links[linkNum].hook;
537 hookIndex = ~linkNum;
539 /* See if hook is already connected. */
540 if (*hookPtr != NULL)
543 /* Disallow more than one link unless multilink is enabled. */
544 if (priv->links[linkNum].conf.enableLink &&
545 !priv->conf.enableMultilink && priv->numActiveLinks >= 1)
548 } else { /* must be a non-link hook */
551 for (i = 0; ng_ppp_hook_names[i].name != NULL; i++) {
552 if (strcmp(name, ng_ppp_hook_names[i].name) == 0) {
553 hookPtr = &priv->hooks[i];
558 if (ng_ppp_hook_names[i].name == NULL)
559 return (EINVAL); /* no such hook */
561 /* See if hook is already connected */
562 if (*hookPtr != NULL)
565 /* Every non-linkX hook have it's own function. */
566 NG_HOOK_SET_RCVDATA(hook, ng_ppp_hook_names[i].fn);
571 NG_HOOK_SET_PRIVATE(hook, (void *)(intptr_t)hookIndex);
572 ng_ppp_update(node, 0);
577 * Receive a control message
580 ng_ppp_rcvmsg(node_p node, item_p item, hook_p lasthook)
582 const priv_p priv = NG_NODE_PRIVATE(node);
583 struct ng_mesg *resp = NULL;
587 NGI_GET_MSG(item, msg);
588 switch (msg->header.typecookie) {
590 switch (msg->header.cmd) {
591 case NGM_PPP_SET_CONFIG:
593 struct ng_ppp_node_conf *const conf =
594 (struct ng_ppp_node_conf *)msg->data;
597 /* Check for invalid or illegal config */
598 if (msg->header.arglen != sizeof(*conf))
600 if (!ng_ppp_config_valid(node, conf))
604 priv->conf = conf->bund;
605 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
606 priv->links[i].conf = conf->links[i];
607 ng_ppp_update(node, 1);
610 case NGM_PPP_GET_CONFIG:
612 struct ng_ppp_node_conf *conf;
615 NG_MKRESPONSE(resp, msg, sizeof(*conf), M_NOWAIT);
618 conf = (struct ng_ppp_node_conf *)resp->data;
619 conf->bund = priv->conf;
620 for (i = 0; i < NG_PPP_MAX_LINKS; i++)
621 conf->links[i] = priv->links[i].conf;
624 case NGM_PPP_GET_MP_STATE:
626 struct ng_ppp_mp_state *info;
629 NG_MKRESPONSE(resp, msg, sizeof(*info), M_NOWAIT);
632 info = (struct ng_ppp_mp_state *)resp->data;
633 bzero(info, sizeof(*info));
634 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
635 if (priv->links[i].seq != MP_NOSEQ)
636 info->rseq[i] = priv->links[i].seq;
638 info->mseq = priv->mseq;
639 info->xseq = priv->xseq;
642 case NGM_PPP_GET_LINK_STATS:
643 case NGM_PPP_CLR_LINK_STATS:
644 case NGM_PPP_GETCLR_LINK_STATS:
645 case NGM_PPP_GET_LINK_STATS64:
646 case NGM_PPP_GETCLR_LINK_STATS64:
648 struct ng_ppp_link_stat64 *stats;
651 /* Process request. */
652 if (msg->header.arglen != sizeof(uint16_t))
654 linkNum = *((uint16_t *) msg->data);
655 if (linkNum >= NG_PPP_MAX_LINKS
656 && linkNum != NG_PPP_BUNDLE_LINKNUM)
658 stats = (linkNum == NG_PPP_BUNDLE_LINKNUM) ?
659 &priv->bundleStats : &priv->links[linkNum].stats;
661 /* Make 64bit reply. */
662 if (msg->header.cmd == NGM_PPP_GET_LINK_STATS64 ||
663 msg->header.cmd == NGM_PPP_GETCLR_LINK_STATS64) {
664 NG_MKRESPONSE(resp, msg,
665 sizeof(struct ng_ppp_link_stat64), M_NOWAIT);
668 bcopy(stats, resp->data, sizeof(*stats));
670 /* Make 32bit reply. */
671 if (msg->header.cmd == NGM_PPP_GET_LINK_STATS ||
672 msg->header.cmd == NGM_PPP_GETCLR_LINK_STATS) {
673 struct ng_ppp_link_stat *rs;
674 NG_MKRESPONSE(resp, msg,
675 sizeof(struct ng_ppp_link_stat), M_NOWAIT);
678 rs = (struct ng_ppp_link_stat *)resp->data;
679 /* Truncate 64->32 bits. */
680 rs->xmitFrames = stats->xmitFrames;
681 rs->xmitOctets = stats->xmitOctets;
682 rs->recvFrames = stats->recvFrames;
683 rs->recvOctets = stats->recvOctets;
684 rs->badProtos = stats->badProtos;
685 rs->runts = stats->runts;
686 rs->dupFragments = stats->dupFragments;
687 rs->dropFragments = stats->dropFragments;
690 if (msg->header.cmd != NGM_PPP_GET_LINK_STATS &&
691 msg->header.cmd != NGM_PPP_GET_LINK_STATS64)
692 bzero(stats, sizeof(*stats));
703 * Forward it to the vjc node. leave the
704 * old return address alone.
705 * If we have no hook, let NG_RESPOND_MSG
706 * clean up any remaining resources.
707 * Because we have no resp, the item will be freed
708 * along with anything it references. Don't
709 * let msg be freed twice.
711 NGI_MSG(item) = msg; /* put it back in the item */
713 if ((lasthook = priv->hooks[HOOK_INDEX_VJC_IP])) {
714 NG_FWD_ITEM_HOOK(error, item, lasthook);
723 NG_RESPOND_MSG(error, node, item, resp);
732 ng_ppp_shutdown(node_p node)
734 const priv_p priv = NG_NODE_PRIVATE(node);
736 /* Stop fragment queue timer */
737 ng_ppp_stop_frag_timer(node);
739 /* Take down netgraph node */
740 ng_ppp_frag_reset(node);
741 mtx_destroy(&priv->rmtx);
742 mtx_destroy(&priv->xmtx);
743 bzero(priv, sizeof(*priv));
744 free(priv, M_NETGRAPH_PPP);
745 NG_NODE_SET_PRIVATE(node, NULL);
746 NG_NODE_UNREF(node); /* let the node escape */
754 ng_ppp_disconnect(hook_p hook)
756 const node_p node = NG_HOOK_NODE(hook);
757 const priv_p priv = NG_NODE_PRIVATE(node);
758 const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
760 /* Zero out hook pointer */
762 priv->links[~index].hook = NULL;
764 priv->hooks[index] = NULL;
766 /* Update derived info (or go away if no hooks left). */
767 if (NG_NODE_NUMHOOKS(node) > 0)
768 ng_ppp_update(node, 0);
769 else if (NG_NODE_IS_VALID(node))
770 ng_rmnode_self(node);
780 * Receive data on a hook inet.
783 ng_ppp_rcvdata_inet(hook_p hook, item_p item)
785 const node_p node = NG_HOOK_NODE(hook);
786 const priv_p priv = NG_NODE_PRIVATE(node);
788 if (!priv->conf.enableIP) {
792 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_IP));
796 * Receive data on a hook ipv6.
799 ng_ppp_rcvdata_ipv6(hook_p hook, item_p item)
801 const node_p node = NG_HOOK_NODE(hook);
802 const priv_p priv = NG_NODE_PRIVATE(node);
804 if (!priv->conf.enableIPv6) {
808 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_IPV6));
812 * Receive data on a hook atalk.
815 ng_ppp_rcvdata_atalk(hook_p hook, item_p item)
817 const node_p node = NG_HOOK_NODE(hook);
818 const priv_p priv = NG_NODE_PRIVATE(node);
820 if (!priv->conf.enableAtalk) {
824 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_ATALK));
828 * Receive data on a hook ipx
831 ng_ppp_rcvdata_ipx(hook_p hook, item_p item)
833 const node_p node = NG_HOOK_NODE(hook);
834 const priv_p priv = NG_NODE_PRIVATE(node);
836 if (!priv->conf.enableIPX) {
840 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, PROT_IPX));
844 * Receive data on a hook bypass
847 ng_ppp_rcvdata_bypass(hook_p hook, item_p item)
854 if (m->m_pkthdr.len < 4) {
858 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL) {
862 linkNum = be16dec(mtod(m, uint8_t *));
863 proto = be16dec(mtod(m, uint8_t *) + 2);
867 if (linkNum == NG_PPP_BUNDLE_LINKNUM)
868 return (ng_ppp_hcomp_xmit(NG_HOOK_NODE(hook), item, proto));
870 return (ng_ppp_link_xmit(NG_HOOK_NODE(hook), item, proto,
875 ng_ppp_bypass(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
877 const priv_p priv = NG_NODE_PRIVATE(node);
882 if (priv->hooks[HOOK_INDEX_BYPASS] == NULL) {
887 /* Add 4-byte bypass header. */
888 hdr[0] = htons(linkNum);
889 hdr[1] = htons(proto);
892 if ((m = ng_ppp_prepend(m, &hdr, 4)) == NULL) {
898 /* Send packet out hook. */
899 NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_BYPASS]);
904 ng_ppp_proto_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
906 const priv_p priv = NG_NODE_PRIVATE(node);
907 hook_p outHook = NULL;
909 #ifdef ALIGNED_POINTER
913 if (!ALIGNED_POINTER(mtod(m, caddr_t), uint32_t)) {
914 n = m_defrag(m, M_NOWAIT);
923 #endif /* ALIGNED_POINTER */
926 if (priv->conf.enableIP)
927 outHook = priv->hooks[HOOK_INDEX_INET];
930 if (priv->conf.enableIPv6)
931 outHook = priv->hooks[HOOK_INDEX_IPV6];
934 if (priv->conf.enableAtalk)
935 outHook = priv->hooks[HOOK_INDEX_ATALK];
938 if (priv->conf.enableIPX)
939 outHook = priv->hooks[HOOK_INDEX_IPX];
944 return (ng_ppp_bypass(node, item, proto, linkNum));
946 /* Send packet out hook. */
947 NG_FWD_ITEM_HOOK(error, item, outHook);
952 * Header compression layer
956 ng_ppp_hcomp_xmit(node_p node, item_p item, uint16_t proto)
958 const priv_p priv = NG_NODE_PRIVATE(node);
960 if (proto == PROT_IP &&
961 priv->conf.enableVJCompression &&
962 priv->vjCompHooked) {
965 /* Send packet out hook. */
966 NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_VJC_IP]);
970 return (ng_ppp_comp_xmit(node, item, proto));
974 * Receive data on a hook vjc_comp.
977 ng_ppp_rcvdata_vjc_comp(hook_p hook, item_p item)
979 const node_p node = NG_HOOK_NODE(hook);
980 const priv_p priv = NG_NODE_PRIVATE(node);
982 if (!priv->conf.enableVJCompression) {
986 return (ng_ppp_comp_xmit(node, item, PROT_VJCOMP));
990 * Receive data on a hook vjc_uncomp.
993 ng_ppp_rcvdata_vjc_uncomp(hook_p hook, item_p item)
995 const node_p node = NG_HOOK_NODE(hook);
996 const priv_p priv = NG_NODE_PRIVATE(node);
998 if (!priv->conf.enableVJCompression) {
1002 return (ng_ppp_comp_xmit(node, item, PROT_VJUNCOMP));
1006 * Receive data on a hook vjc_vjip.
1009 ng_ppp_rcvdata_vjc_vjip(hook_p hook, item_p item)
1011 const node_p node = NG_HOOK_NODE(hook);
1012 const priv_p priv = NG_NODE_PRIVATE(node);
1014 if (!priv->conf.enableVJCompression) {
1018 return (ng_ppp_comp_xmit(node, item, PROT_IP));
1022 ng_ppp_hcomp_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1024 const priv_p priv = NG_NODE_PRIVATE(node);
1026 if (priv->conf.enableVJDecompression && priv->vjCompHooked) {
1027 hook_p outHook = NULL;
1031 outHook = priv->hooks[HOOK_INDEX_VJC_COMP];
1034 outHook = priv->hooks[HOOK_INDEX_VJC_UNCOMP];
1041 /* Send packet out hook. */
1042 NG_FWD_ITEM_HOOK(error, item, outHook);
1047 return (ng_ppp_proto_recv(node, item, proto, linkNum));
1051 * Receive data on a hook vjc_ip.
1054 ng_ppp_rcvdata_vjc_ip(hook_p hook, item_p item)
1056 const node_p node = NG_HOOK_NODE(hook);
1057 const priv_p priv = NG_NODE_PRIVATE(node);
1059 if (!priv->conf.enableVJDecompression) {
1063 return (ng_ppp_proto_recv(node, item, PROT_IP, NG_PPP_BUNDLE_LINKNUM));
1071 ng_ppp_comp_xmit(node_p node, item_p item, uint16_t proto)
1073 const priv_p priv = NG_NODE_PRIVATE(node);
1075 if (priv->conf.enableCompression &&
1077 proto != PROT_COMPD &&
1078 proto != PROT_CRYPTD &&
1079 priv->hooks[HOOK_INDEX_COMPRESS] != NULL) {
1084 if ((m = ng_ppp_addproto(m, proto, 0)) == NULL) {
1090 /* Send packet out hook. */
1091 NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_COMPRESS]);
1095 return (ng_ppp_crypt_xmit(node, item, proto));
1099 * Receive data on a hook compress.
1102 ng_ppp_rcvdata_compress(hook_p hook, item_p item)
1104 const node_p node = NG_HOOK_NODE(hook);
1105 const priv_p priv = NG_NODE_PRIVATE(node);
1108 switch (priv->conf.enableCompression) {
1109 case NG_PPP_COMPRESS_NONE:
1112 case NG_PPP_COMPRESS_FULL:
1117 if ((m = ng_ppp_cutproto(m, &proto)) == NULL) {
1122 if (!PROT_VALID(proto)) {
1132 return (ng_ppp_crypt_xmit(node, item, proto));
1136 ng_ppp_comp_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1138 const priv_p priv = NG_NODE_PRIVATE(node);
1140 if (proto < 0x4000 &&
1141 ((proto == PROT_COMPD && priv->conf.enableDecompression) ||
1142 priv->conf.enableDecompression == NG_PPP_DECOMPRESS_FULL) &&
1143 priv->hooks[HOOK_INDEX_DECOMPRESS] != NULL) {
1146 if (priv->conf.enableDecompression == NG_PPP_DECOMPRESS_FULL) {
1149 if ((m = ng_ppp_addproto(m, proto, 0)) == NULL) {
1156 /* Send packet out hook. */
1157 NG_FWD_ITEM_HOOK(error, item,
1158 priv->hooks[HOOK_INDEX_DECOMPRESS]);
1160 } else if (proto == PROT_COMPD) {
1161 /* Disabled protos MUST be silently discarded, but
1162 * unsupported MUST not. Let user-level decide this. */
1163 return (ng_ppp_bypass(node, item, proto, linkNum));
1166 return (ng_ppp_hcomp_recv(node, item, proto, linkNum));
1170 * Receive data on a hook decompress.
1173 ng_ppp_rcvdata_decompress(hook_p hook, item_p item)
1175 const node_p node = NG_HOOK_NODE(hook);
1176 const priv_p priv = NG_NODE_PRIVATE(node);
1180 if (!priv->conf.enableDecompression) {
1185 if ((m = ng_ppp_cutproto(m, &proto)) == NULL) {
1190 if (!PROT_VALID(proto)) {
1191 priv->bundleStats.badProtos++;
1195 return (ng_ppp_hcomp_recv(node, item, proto, NG_PPP_BUNDLE_LINKNUM));
1203 ng_ppp_crypt_xmit(node_p node, item_p item, uint16_t proto)
1205 const priv_p priv = NG_NODE_PRIVATE(node);
1207 if (priv->conf.enableEncryption &&
1209 proto != PROT_CRYPTD &&
1210 priv->hooks[HOOK_INDEX_ENCRYPT] != NULL) {
1215 if ((m = ng_ppp_addproto(m, proto, 0)) == NULL) {
1221 /* Send packet out hook. */
1222 NG_FWD_ITEM_HOOK(error, item, priv->hooks[HOOK_INDEX_ENCRYPT]);
1226 return (ng_ppp_mp_xmit(node, item, proto));
1230 * Receive data on a hook encrypt.
1233 ng_ppp_rcvdata_encrypt(hook_p hook, item_p item)
1235 const node_p node = NG_HOOK_NODE(hook);
1236 const priv_p priv = NG_NODE_PRIVATE(node);
1238 if (!priv->conf.enableEncryption) {
1242 return (ng_ppp_mp_xmit(node, item, PROT_CRYPTD));
1246 ng_ppp_crypt_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1248 const priv_p priv = NG_NODE_PRIVATE(node);
1250 if (proto == PROT_CRYPTD) {
1251 if (priv->conf.enableDecryption &&
1252 priv->hooks[HOOK_INDEX_DECRYPT] != NULL) {
1255 /* Send packet out hook. */
1256 NG_FWD_ITEM_HOOK(error, item,
1257 priv->hooks[HOOK_INDEX_DECRYPT]);
1260 /* Disabled protos MUST be silently discarded, but
1261 * unsupported MUST not. Let user-level decide this. */
1262 return (ng_ppp_bypass(node, item, proto, linkNum));
1266 return (ng_ppp_comp_recv(node, item, proto, linkNum));
1270 * Receive data on a hook decrypt.
1273 ng_ppp_rcvdata_decrypt(hook_p hook, item_p item)
1275 const node_p node = NG_HOOK_NODE(hook);
1276 const priv_p priv = NG_NODE_PRIVATE(node);
1280 if (!priv->conf.enableDecryption) {
1285 if ((m = ng_ppp_cutproto(m, &proto)) == NULL) {
1290 if (!PROT_VALID(proto)) {
1291 priv->bundleStats.badProtos++;
1295 return (ng_ppp_comp_recv(node, item, proto, NG_PPP_BUNDLE_LINKNUM));
1303 ng_ppp_link_xmit(node_p node, item_p item, uint16_t proto, uint16_t linkNum, int plen)
1305 const priv_p priv = NG_NODE_PRIVATE(node);
1306 struct ng_ppp_link *link;
1311 /* Check if link correct. */
1312 if (linkNum >= NG_PPP_MAX_LINKS) {
1316 /* Get link pointer (optimization). */
1317 link = &priv->links[linkNum];
1319 /* Check link status (if real). */
1320 if (link->hook == NULL) {
1327 /* Check peer's MRU for this link. */
1328 mru = link->conf.mru;
1329 if (mru != 0 && m->m_pkthdr.len > mru) {
1334 /* Prepend protocol number, possibly compressed. */
1335 if ((m = ng_ppp_addproto(m, proto, link->conf.enableProtoComp)) ==
1340 /* Prepend address and control field (unless compressed). */
1341 if (proto == PROT_LCP || !link->conf.enableACFComp) {
1342 if ((m = ng_ppp_prepend(m, &ng_ppp_acf, 2)) == NULL)
1346 /* Deliver frame. */
1347 len = m->m_pkthdr.len;
1348 NG_FWD_NEW_DATA(error, item, link->hook, m);
1350 mtx_lock(&priv->xmtx);
1352 /* Update link stats. */
1353 link->stats.xmitFrames++;
1354 link->stats.xmitOctets += len;
1356 /* Update bundle stats. */
1358 priv->bundleStats.xmitFrames++;
1359 priv->bundleStats.xmitOctets += plen;
1362 /* Update 'bytes in queue' counter. */
1364 /* bytesInQueue and lastWrite required only for mp_strategy. */
1365 if (priv->conf.enableMultilink && !priv->allLinksEqual &&
1366 !priv->conf.enableRoundRobin) {
1367 /* If queue was empty, then mark this time. */
1368 if (link->bytesInQueue == 0)
1369 getmicrouptime(&link->lastWrite);
1370 link->bytesInQueue += len + MP_AVERAGE_LINK_OVERHEAD;
1371 /* Limit max queue length to 50 pkts. BW can be defined
1372 incorrectly and link may not signal overload. */
1373 if (link->bytesInQueue > 50 * 1600)
1374 link->bytesInQueue = 50 * 1600;
1377 mtx_unlock(&priv->xmtx);
1386 * Receive data on a hook linkX.
1389 ng_ppp_rcvdata(hook_p hook, item_p item)
1391 const node_p node = NG_HOOK_NODE(hook);
1392 const priv_p priv = NG_NODE_PRIVATE(node);
1393 const int index = (intptr_t)NG_HOOK_PRIVATE(hook);
1394 const uint16_t linkNum = (uint16_t)~index;
1395 struct ng_ppp_link * const link = &priv->links[linkNum];
1400 KASSERT(linkNum < NG_PPP_MAX_LINKS,
1401 ("%s: bogus index 0x%x", __func__, index));
1405 mtx_lock(&priv->rmtx);
1408 link->stats.recvFrames++;
1409 link->stats.recvOctets += m->m_pkthdr.len;
1411 /* Strip address and control fields, if present. */
1412 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL)
1414 if (mtod(m, uint8_t *)[0] == 0xff &&
1415 mtod(m, uint8_t *)[1] == 0x03)
1418 /* Get protocol number */
1419 if ((m = ng_ppp_cutproto(m, &proto)) == NULL)
1421 NGI_M(item) = m; /* Put changed m back into item. */
1423 if (!PROT_VALID(proto)) {
1424 link->stats.badProtos++;
1428 /* LCP packets must go directly to bypass. */
1429 if (proto >= 0xB000) {
1430 mtx_unlock(&priv->rmtx);
1431 return (ng_ppp_bypass(node, item, proto, linkNum));
1434 /* Other packets are denied on a disabled link. */
1435 if (!link->conf.enableLink)
1438 /* Proceed to multilink layer. Mutex will be unlocked inside. */
1439 error = ng_ppp_mp_recv(node, item, proto, linkNum);
1440 mtx_assert(&priv->rmtx, MA_NOTOWNED);
1444 mtx_unlock(&priv->rmtx);
1454 * Handle an incoming multi-link fragment
1456 * The fragment reassembly algorithm is somewhat complex. This is mainly
1457 * because we are required not to reorder the reconstructed packets, yet
1458 * fragments are only guaranteed to arrive in order on a per-link basis.
1459 * In other words, when we have a complete packet ready, but the previous
1460 * packet is still incomplete, we have to decide between delivering the
1461 * complete packet and throwing away the incomplete one, or waiting to
1462 * see if the remainder of the incomplete one arrives, at which time we
1463 * can deliver both packets, in order.
1465 * This problem is exacerbated by "sequence number slew", which is when
1466 * the sequence numbers coming in from different links are far apart from
1467 * each other. In particular, certain unnamed equipment (*cough* Ascend)
1468 * has been seen to generate sequence number slew of up to 10 on an ISDN
1469 * 2B-channel MP link. There is nothing invalid about sequence number slew
1470 * but it makes the reasssembly process have to work harder.
1472 * However, the peer is required to transmit fragments in order on each
1473 * link. That means if we define MSEQ as the minimum over all links of
1474 * the highest sequence number received on that link, then we can always
1475 * give up any hope of receiving a fragment with sequence number < MSEQ in
1476 * the future (all of this using 'wraparound' sequence number space).
1477 * Therefore we can always immediately throw away incomplete packets
1478 * missing fragments with sequence numbers < MSEQ.
1480 * Here is an overview of our algorithm:
1482 * o Received fragments are inserted into a queue, for which we
1483 * maintain these invariants between calls to this function:
1485 * - Fragments are ordered in the queue by sequence number
1486 * - If a complete packet is at the head of the queue, then
1487 * the first fragment in the packet has seq# > MSEQ + 1
1488 * (otherwise, we could deliver it immediately)
1489 * - If any fragments have seq# < MSEQ, then they are necessarily
1490 * part of a packet whose missing seq#'s are all > MSEQ (otherwise,
1491 * we can throw them away because they'll never be completed)
1492 * - The queue contains at most MP_MAX_QUEUE_LEN fragments
1494 * o We have a periodic timer that checks the queue for the first
1495 * complete packet that has been sitting in the queue "too long".
1496 * When one is detected, all previous (incomplete) fragments are
1497 * discarded, their missing fragments are declared lost and MSEQ
1500 * o If we recieve a fragment with seq# < MSEQ, we throw it away
1501 * because we've already delcared it lost.
1503 * This assumes linkNum != NG_PPP_BUNDLE_LINKNUM.
1506 ng_ppp_mp_recv(node_p node, item_p item, uint16_t proto, uint16_t linkNum)
1508 const priv_p priv = NG_NODE_PRIVATE(node);
1509 struct ng_ppp_link *const link = &priv->links[linkNum];
1510 struct ng_ppp_frag *frag;
1511 struct ng_ppp_frag *qent;
1512 int i, diff, inserted;
1516 if ((!priv->conf.enableMultilink) || proto != PROT_MP) {
1518 priv->bundleStats.recvFrames++;
1519 priv->bundleStats.recvOctets += NGI_M(item)->m_pkthdr.len;
1521 mtx_unlock(&priv->rmtx);
1522 return (ng_ppp_crypt_recv(node, item, proto, linkNum));
1527 /* Get a new frag struct from the free queue */
1528 if ((frag = TAILQ_FIRST(&priv->fragsfree)) == NULL) {
1529 printf("No free fragments headers in ng_ppp!\n");
1534 /* Extract fragment information from MP header */
1535 if (priv->conf.recvShortSeq) {
1538 if (m->m_pkthdr.len < 2) {
1539 link->stats.runts++;
1543 if (m->m_len < 2 && (m = m_pullup(m, 2)) == NULL)
1546 shdr = be16dec(mtod(m, void *));
1547 frag->seq = MP_SHORT_EXTEND(shdr);
1548 frag->first = (shdr & MP_SHORT_FIRST_FLAG) != 0;
1549 frag->last = (shdr & MP_SHORT_LAST_FLAG) != 0;
1550 diff = MP_SHORT_SEQ_DIFF(frag->seq, priv->mseq);
1555 if (m->m_pkthdr.len < 4) {
1556 link->stats.runts++;
1560 if (m->m_len < 4 && (m = m_pullup(m, 4)) == NULL)
1563 lhdr = be32dec(mtod(m, void *));
1564 frag->seq = MP_LONG_EXTEND(lhdr);
1565 frag->first = (lhdr & MP_LONG_FIRST_FLAG) != 0;
1566 frag->last = (lhdr & MP_LONG_LAST_FLAG) != 0;
1567 diff = MP_LONG_SEQ_DIFF(frag->seq, priv->mseq);
1571 getmicrouptime(&frag->timestamp);
1573 /* If sequence number is < MSEQ, we've already declared this
1574 fragment as lost, so we have no choice now but to drop it */
1576 link->stats.dropFragments++;
1581 /* Update highest received sequence number on this link and MSEQ */
1582 priv->mseq = link->seq = frag->seq;
1583 for (i = 0; i < priv->numActiveLinks; i++) {
1584 struct ng_ppp_link *const alink =
1585 &priv->links[priv->activeLinks[i]];
1587 if (MP_RECV_SEQ_DIFF(priv, alink->seq, priv->mseq) < 0)
1588 priv->mseq = alink->seq;
1591 /* Remove frag struct from free queue. */
1592 TAILQ_REMOVE(&priv->fragsfree, frag, f_qent);
1594 /* Add fragment to queue, which is sorted by sequence number */
1596 TAILQ_FOREACH_REVERSE(qent, &priv->frags, ng_ppp_fraglist, f_qent) {
1597 diff = MP_RECV_SEQ_DIFF(priv, frag->seq, qent->seq);
1599 TAILQ_INSERT_AFTER(&priv->frags, qent, frag, f_qent);
1602 } else if (diff == 0) { /* should never happen! */
1603 link->stats.dupFragments++;
1604 NG_FREE_M(frag->data);
1605 TAILQ_INSERT_HEAD(&priv->fragsfree, frag, f_qent);
1610 TAILQ_INSERT_HEAD(&priv->frags, frag, f_qent);
1613 /* Process the queue */
1614 /* NOTE: rmtx will be unlocked for sending time! */
1615 error = ng_ppp_frag_process(node, item);
1616 mtx_unlock(&priv->rmtx);
1620 mtx_unlock(&priv->rmtx);
1625 /************************************************************************
1627 ************************************************************************/
1630 * If new mseq > current then set it and update all active links
1633 ng_ppp_bump_mseq(node_p node, int32_t new_mseq)
1635 const priv_p priv = NG_NODE_PRIVATE(node);
1638 if (MP_RECV_SEQ_DIFF(priv, priv->mseq, new_mseq) < 0) {
1639 priv->mseq = new_mseq;
1640 for (i = 0; i < priv->numActiveLinks; i++) {
1641 struct ng_ppp_link *const alink =
1642 &priv->links[priv->activeLinks[i]];
1644 if (MP_RECV_SEQ_DIFF(priv,
1645 alink->seq, new_mseq) < 0)
1646 alink->seq = new_mseq;
1652 * Examine our list of fragments, and determine if there is a
1653 * complete and deliverable packet at the head of the list.
1654 * Return 1 if so, zero otherwise.
1657 ng_ppp_check_packet(node_p node)
1659 const priv_p priv = NG_NODE_PRIVATE(node);
1660 struct ng_ppp_frag *qent, *qnext;
1662 /* Check for empty queue */
1663 if (TAILQ_EMPTY(&priv->frags))
1666 /* Check first fragment is the start of a deliverable packet */
1667 qent = TAILQ_FIRST(&priv->frags);
1668 if (!qent->first || MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) > 1)
1671 /* Check that all the fragments are there */
1672 while (!qent->last) {
1673 qnext = TAILQ_NEXT(qent, f_qent);
1674 if (qnext == NULL) /* end of queue */
1676 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq))
1686 * Pull a completed packet off the head of the incoming fragment queue.
1687 * This assumes there is a completed packet there to pull off.
1690 ng_ppp_get_packet(node_p node, struct mbuf **mp)
1692 const priv_p priv = NG_NODE_PRIVATE(node);
1693 struct ng_ppp_frag *qent, *qnext;
1694 struct mbuf *m = NULL, *tail;
1696 qent = TAILQ_FIRST(&priv->frags);
1697 KASSERT(!TAILQ_EMPTY(&priv->frags) && qent->first,
1698 ("%s: no packet", __func__));
1699 for (tail = NULL; qent != NULL; qent = qnext) {
1700 qnext = TAILQ_NEXT(qent, f_qent);
1701 KASSERT(!TAILQ_EMPTY(&priv->frags),
1702 ("%s: empty q", __func__));
1703 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1705 tail = m = qent->data;
1707 m->m_pkthdr.len += qent->data->m_pkthdr.len;
1708 tail->m_next = qent->data;
1710 while (tail->m_next != NULL)
1711 tail = tail->m_next;
1714 /* Bump MSEQ if necessary */
1715 ng_ppp_bump_mseq(node, qent->seq);
1717 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1723 * Trim fragments from the queue whose packets can never be completed.
1724 * This assumes a complete packet is NOT at the beginning of the queue.
1725 * Returns 1 if fragments were removed, zero otherwise.
1728 ng_ppp_frag_trim(node_p node)
1730 const priv_p priv = NG_NODE_PRIVATE(node);
1731 struct ng_ppp_frag *qent, *qnext = NULL;
1734 /* Scan for "dead" fragments and remove them */
1738 /* If queue is empty, we're done */
1739 if (TAILQ_EMPTY(&priv->frags))
1742 /* Determine whether first fragment can ever be completed */
1743 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1744 if (MP_RECV_SEQ_DIFF(priv, qent->seq, priv->mseq) >= 0)
1746 qnext = TAILQ_NEXT(qent, f_qent);
1747 KASSERT(qnext != NULL,
1748 ("%s: last frag < MSEQ?", __func__));
1749 if (qnext->seq != MP_NEXT_RECV_SEQ(priv, qent->seq)
1750 || qent->last || qnext->first) {
1758 /* Remove fragment and all others in the same packet */
1759 while ((qent = TAILQ_FIRST(&priv->frags)) != qnext) {
1760 KASSERT(!TAILQ_EMPTY(&priv->frags),
1761 ("%s: empty q", __func__));
1762 priv->bundleStats.dropFragments++;
1763 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1764 NG_FREE_M(qent->data);
1765 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1773 * Drop fragments on queue overflow.
1774 * Returns 1 if fragments were removed, zero otherwise.
1777 ng_ppp_frag_drop(node_p node)
1779 const priv_p priv = NG_NODE_PRIVATE(node);
1781 /* Check queue length */
1782 if (TAILQ_EMPTY(&priv->fragsfree)) {
1783 struct ng_ppp_frag *qent;
1785 /* Get oldest fragment */
1786 KASSERT(!TAILQ_EMPTY(&priv->frags),
1787 ("%s: empty q", __func__));
1788 qent = TAILQ_FIRST(&priv->frags);
1790 /* Bump MSEQ if necessary */
1791 ng_ppp_bump_mseq(node, qent->seq);
1794 priv->bundleStats.dropFragments++;
1795 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1796 NG_FREE_M(qent->data);
1797 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1805 * Run the queue, restoring the queue invariants
1808 ng_ppp_frag_process(node_p node, item_p oitem)
1810 const priv_p priv = NG_NODE_PRIVATE(node);
1816 /* Deliver any deliverable packets */
1817 while (ng_ppp_check_packet(node)) {
1818 ng_ppp_get_packet(node, &m);
1819 if ((m = ng_ppp_cutproto(m, &proto)) == NULL)
1821 if (!PROT_VALID(proto)) {
1822 priv->bundleStats.badProtos++;
1826 if (oitem) { /* If original item present - reuse it. */
1831 item = ng_package_data(m, NG_NOFLAGS);
1835 priv->bundleStats.recvFrames++;
1836 priv->bundleStats.recvOctets +=
1837 NGI_M(item)->m_pkthdr.len;
1839 /* Drop mutex for the sending time.
1840 * Priv may change, but we are ready!
1842 mtx_unlock(&priv->rmtx);
1843 ng_ppp_crypt_recv(node, item, proto,
1844 NG_PPP_BUNDLE_LINKNUM);
1845 mtx_lock(&priv->rmtx);
1848 /* Delete dead fragments and try again */
1849 } while (ng_ppp_frag_trim(node) || ng_ppp_frag_drop(node));
1851 /* If we haven't reused original item - free it. */
1852 if (oitem) NG_FREE_ITEM(oitem);
1859 * Check for 'stale' completed packets that need to be delivered
1861 * If a link goes down or has a temporary failure, MSEQ can get
1862 * "stuck", because no new incoming fragments appear on that link.
1863 * This can cause completed packets to never get delivered if
1864 * their sequence numbers are all > MSEQ + 1.
1866 * This routine checks how long all of the completed packets have
1867 * been sitting in the queue, and if too long, removes fragments
1868 * from the queue and increments MSEQ to allow them to be delivered.
1871 ng_ppp_frag_checkstale(node_p node)
1873 const priv_p priv = NG_NODE_PRIVATE(node);
1874 struct ng_ppp_frag *qent, *beg, *end;
1875 struct timeval now, age;
1882 now.tv_sec = 0; /* uninitialized state */
1885 /* If queue is empty, we're done */
1886 if (TAILQ_EMPTY(&priv->frags))
1889 /* Find the first complete packet in the queue */
1891 seq = TAILQ_FIRST(&priv->frags)->seq;
1892 TAILQ_FOREACH(qent, &priv->frags, f_qent) {
1895 else if (qent->seq != seq)
1897 if (beg != NULL && qent->last) {
1901 seq = MP_NEXT_RECV_SEQ(priv, seq);
1904 /* If none found, exit */
1908 /* Get current time (we assume we've been up for >= 1 second) */
1909 if (now.tv_sec == 0)
1910 getmicrouptime(&now);
1912 /* Check if packet has been queued too long */
1914 timevalsub(&age, &beg->timestamp);
1915 if (timevalcmp(&age, &ng_ppp_max_staleness, < ))
1918 /* Throw away junk fragments in front of the completed packet */
1919 while ((qent = TAILQ_FIRST(&priv->frags)) != beg) {
1920 KASSERT(!TAILQ_EMPTY(&priv->frags),
1921 ("%s: empty q", __func__));
1922 priv->bundleStats.dropFragments++;
1923 TAILQ_REMOVE(&priv->frags, qent, f_qent);
1924 NG_FREE_M(qent->data);
1925 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
1928 /* Extract completed packet */
1930 ng_ppp_get_packet(node, &m);
1932 if ((m = ng_ppp_cutproto(m, &proto)) == NULL)
1934 if (!PROT_VALID(proto)) {
1935 priv->bundleStats.badProtos++;
1940 /* Deliver packet */
1941 if ((item = ng_package_data(m, NG_NOFLAGS)) != NULL) {
1943 priv->bundleStats.recvFrames++;
1944 priv->bundleStats.recvOctets += NGI_M(item)->m_pkthdr.len;
1946 ng_ppp_crypt_recv(node, item, proto,
1947 NG_PPP_BUNDLE_LINKNUM);
1953 * Periodically call ng_ppp_frag_checkstale()
1956 ng_ppp_frag_timeout(node_p node, hook_p hook, void *arg1, int arg2)
1958 /* XXX: is this needed? */
1959 if (NG_NODE_NOT_VALID(node))
1962 /* Scan the fragment queue */
1963 ng_ppp_frag_checkstale(node);
1965 /* Start timer again */
1966 ng_ppp_start_frag_timer(node);
1970 * Deliver a frame out on the bundle, i.e., figure out how to fragment
1971 * the frame across the individual PPP links and do so.
1974 ng_ppp_mp_xmit(node_p node, item_p item, uint16_t proto)
1976 const priv_p priv = NG_NODE_PRIVATE(node);
1977 const int hdr_len = priv->conf.xmitShortSeq ? 2 : 4;
1978 int distrib[NG_PPP_MAX_LINKS];
1986 /* At least one link must be active */
1987 if (priv->numActiveLinks == 0) {
1992 /* Save length for later stats. */
1993 plen = NGI_M(item)->m_pkthdr.len;
1995 if (!priv->conf.enableMultilink) {
1996 return (ng_ppp_link_xmit(node, item, proto,
1997 priv->activeLinks[0], plen));
2000 /* Check peer's MRRU for this bundle. */
2001 if (plen > priv->conf.mrru) {
2009 /* Prepend protocol number, possibly compressed. */
2010 if ((m = ng_ppp_addproto(m, proto, 1)) == NULL) {
2015 /* Clear distribution plan */
2016 bzero(&distrib, priv->numActiveLinks * sizeof(distrib[0]));
2018 mtx_lock(&priv->xmtx);
2020 /* Round-robin strategy */
2021 if (priv->conf.enableRoundRobin) {
2022 activeLinkNum = priv->lastLink++ % priv->numActiveLinks;
2023 distrib[activeLinkNum] = m->m_pkthdr.len;
2027 /* Strategy when all links are equivalent (optimize the common case) */
2028 if (priv->allLinksEqual) {
2029 int numFrags, fraction, remain;
2032 /* Calculate optimal fragment count */
2033 numFrags = priv->numActiveLinks;
2034 if (numFrags > m->m_pkthdr.len / MP_MIN_FRAG_LEN)
2035 numFrags = m->m_pkthdr.len / MP_MIN_FRAG_LEN;
2039 fraction = m->m_pkthdr.len / numFrags;
2040 remain = m->m_pkthdr.len - (fraction * numFrags);
2042 /* Assign distribution */
2043 for (i = 0; i < numFrags; i++) {
2044 distrib[priv->lastLink++ % priv->numActiveLinks]
2045 = fraction + (((remain--) > 0)?1:0);
2050 /* Strategy when all links are not equivalent */
2051 ng_ppp_mp_strategy(node, m->m_pkthdr.len, distrib);
2054 /* Estimate fragments count */
2056 for (activeLinkNum = priv->numActiveLinks - 1;
2057 activeLinkNum >= 0; activeLinkNum--) {
2058 const uint16_t linkNum = priv->activeLinks[activeLinkNum];
2059 struct ng_ppp_link *const link = &priv->links[linkNum];
2061 frags += (distrib[activeLinkNum] + link->conf.mru - hdr_len - 1) /
2062 (link->conf.mru - hdr_len);
2065 /* Get out initial sequence number */
2068 /* Update next sequence number */
2069 if (priv->conf.xmitShortSeq) {
2070 priv->xseq = (seq + frags) & MP_SHORT_SEQ_MASK;
2072 priv->xseq = (seq + frags) & MP_LONG_SEQ_MASK;
2075 mtx_unlock(&priv->xmtx);
2077 /* Send alloted portions of frame out on the link(s) */
2078 for (firstFragment = 1, activeLinkNum = priv->numActiveLinks - 1;
2079 activeLinkNum >= 0; activeLinkNum--) {
2080 const uint16_t linkNum = priv->activeLinks[activeLinkNum];
2081 struct ng_ppp_link *const link = &priv->links[linkNum];
2083 /* Deliver fragment(s) out the next link */
2084 for ( ; distrib[activeLinkNum] > 0; firstFragment = 0) {
2085 int len, lastFragment, error;
2088 /* Calculate fragment length; don't exceed link MTU */
2089 len = distrib[activeLinkNum];
2090 if (len > link->conf.mru - hdr_len)
2091 len = link->conf.mru - hdr_len;
2092 distrib[activeLinkNum] -= len;
2093 lastFragment = (len == m->m_pkthdr.len);
2095 /* Split off next fragment as "m2" */
2097 if (!lastFragment) {
2098 struct mbuf *n = m_split(m, len, M_DONTWAIT);
2106 m_tag_copy_chain(n, m, M_DONTWAIT);
2110 /* Prepend MP header */
2111 if (priv->conf.xmitShortSeq) {
2115 seq = (seq + 1) & MP_SHORT_SEQ_MASK;
2117 shdr |= MP_SHORT_FIRST_FLAG;
2119 shdr |= MP_SHORT_LAST_FLAG;
2121 m2 = ng_ppp_prepend(m2, &shdr, 2);
2126 seq = (seq + 1) & MP_LONG_SEQ_MASK;
2128 lhdr |= MP_LONG_FIRST_FLAG;
2130 lhdr |= MP_LONG_LAST_FLAG;
2132 m2 = ng_ppp_prepend(m2, &lhdr, 4);
2143 if (firstFragment) {
2144 NGI_M(item) = m2; /* Reuse original item. */
2146 item = ng_package_data(m2, NG_NOFLAGS);
2149 error = ng_ppp_link_xmit(node, item, PROT_MP,
2150 linkNum, (firstFragment?plen:0));
2165 * Computing the optimal fragmentation
2166 * -----------------------------------
2168 * This routine tries to compute the optimal fragmentation pattern based
2169 * on each link's latency, bandwidth, and calculated additional latency.
2170 * The latter quantity is the additional latency caused by previously
2171 * written data that has not been transmitted yet.
2173 * This algorithm is only useful when not all of the links have the
2174 * same latency and bandwidth values.
2176 * The essential idea is to make the last bit of each fragment of the
2177 * frame arrive at the opposite end at the exact same time. This greedy
2178 * algorithm is optimal, in that no other scheduling could result in any
2179 * packet arriving any sooner unless packets are delivered out of order.
2181 * Suppose link i has bandwidth b_i (in tens of bytes per milisecond) and
2182 * latency l_i (in miliseconds). Consider the function function f_i(t)
2183 * which is equal to the number of bytes that will have arrived at
2184 * the peer after t miliseconds if we start writing continuously at
2185 * time t = 0. Then f_i(t) = b_i * (t - l_i) = ((b_i * t) - (l_i * b_i).
2186 * That is, f_i(t) is a line with slope b_i and y-intersect -(l_i * b_i).
2187 * Note that the y-intersect is always <= zero because latency can't be
2188 * negative. Note also that really the function is f_i(t) except when
2189 * f_i(t) is negative, in which case the function is zero. To take
2190 * care of this, let Q_i(t) = { if (f_i(t) > 0) return 1; else return 0; }.
2191 * So the actual number of bytes that will have arrived at the peer after
2192 * t miliseconds is f_i(t) * Q_i(t).
2194 * At any given time, each link has some additional latency a_i >= 0
2195 * due to previously written fragment(s) which are still in the queue.
2196 * This value is easily computed from the time since last transmission,
2197 * the previous latency value, the number of bytes written, and the
2200 * Assume that l_i includes any a_i already, and that the links are
2201 * sorted by latency, so that l_i <= l_{i+1}.
2203 * Let N be the total number of bytes in the current frame we are sending.
2205 * Suppose we were to start writing bytes at time t = 0 on all links
2206 * simultaneously, which is the most we can possibly do. Then let
2207 * F(t) be equal to the total number of bytes received by the peer
2208 * after t miliseconds. Then F(t) = Sum_i (f_i(t) * Q_i(t)).
2210 * Our goal is simply this: fragment the frame across the links such
2211 * that the peer is able to reconstruct the completed frame as soon as
2212 * possible, i.e., at the least possible value of t. Call this value t_0.
2214 * Then it follows that F(t_0) = N. Our strategy is first to find the value
2215 * of t_0, and then deduce how many bytes to write to each link.
2219 * t_0 = ( N + Sum_i ( l_i * b_i * Q_i(t_0) ) ) / Sum_i ( b_i * Q_i(t_0) )
2221 * Now, we note that Q_i(t) is constant for l_i <= t <= l_{i+1}. t_0 will
2222 * lie in one of these ranges. To find it, we just need to find the i such
2223 * that F(l_i) <= N <= F(l_{i+1}). Then we compute all the constant values
2224 * for Q_i() in this range, plug in the remaining values, solving for t_0.
2226 * Once t_0 is known, then the number of bytes to send on link i is
2227 * just f_i(t_0) * Q_i(t_0).
2229 * In other words, we start allocating bytes to the links one at a time.
2230 * We keep adding links until the frame is completely sent. Some links
2231 * may not get any bytes because their latency is too high.
2233 * Is all this work really worth the trouble? Depends on the situation.
2234 * The bigger the ratio of computer speed to link speed, and the more
2235 * important total bundle latency is (e.g., for interactive response time),
2236 * the more it's worth it. There is however the cost of calling this
2237 * function for every frame. The running time is O(n^2) where n is the
2238 * number of links that receive a non-zero number of bytes.
2240 * Since latency is measured in miliseconds, the "resolution" of this
2241 * algorithm is one milisecond.
2243 * To avoid this algorithm altogether, configure all links to have the
2244 * same latency and bandwidth.
2247 ng_ppp_mp_strategy(node_p node, int len, int *distrib)
2249 const priv_p priv = NG_NODE_PRIVATE(node);
2250 int latency[NG_PPP_MAX_LINKS];
2251 int sortByLatency[NG_PPP_MAX_LINKS];
2253 int t0, total, topSum, botSum;
2255 int i, numFragments;
2257 /* If only one link, this gets real easy */
2258 if (priv->numActiveLinks == 1) {
2263 /* Get current time */
2264 getmicrouptime(&now);
2266 /* Compute latencies for each link at this point in time */
2267 for (activeLinkNum = 0;
2268 activeLinkNum < priv->numActiveLinks; activeLinkNum++) {
2269 struct ng_ppp_link *alink;
2270 struct timeval diff;
2273 /* Start with base latency value */
2274 alink = &priv->links[priv->activeLinks[activeLinkNum]];
2275 latency[activeLinkNum] = alink->latency;
2276 sortByLatency[activeLinkNum] = activeLinkNum; /* see below */
2278 /* Any additional latency? */
2279 if (alink->bytesInQueue == 0)
2282 /* Compute time delta since last write */
2284 timevalsub(&diff, &alink->lastWrite);
2286 /* alink->bytesInQueue will be changed, mark change time. */
2287 alink->lastWrite = now;
2289 if (now.tv_sec < 0 || diff.tv_sec >= 10) { /* sanity */
2290 alink->bytesInQueue = 0;
2294 /* How many bytes could have transmitted since last write? */
2295 xmitBytes = (alink->conf.bandwidth * 10 * diff.tv_sec)
2296 + (alink->conf.bandwidth * (diff.tv_usec / 1000)) / 100;
2297 alink->bytesInQueue -= xmitBytes;
2298 if (alink->bytesInQueue < 0)
2299 alink->bytesInQueue = 0;
2301 latency[activeLinkNum] +=
2302 (100 * alink->bytesInQueue) / alink->conf.bandwidth;
2305 /* Sort active links by latency */
2306 qsort_r(sortByLatency,
2307 priv->numActiveLinks, sizeof(*sortByLatency), latency, ng_ppp_intcmp);
2309 /* Find the interval we need (add links in sortByLatency[] order) */
2310 for (numFragments = 1;
2311 numFragments < priv->numActiveLinks; numFragments++) {
2312 for (total = i = 0; i < numFragments; i++) {
2315 flowTime = latency[sortByLatency[numFragments]]
2316 - latency[sortByLatency[i]];
2317 total += ((flowTime * priv->links[
2318 priv->activeLinks[sortByLatency[i]]].conf.bandwidth)
2325 /* Solve for t_0 in that interval */
2326 for (topSum = botSum = i = 0; i < numFragments; i++) {
2327 int bw = priv->links[
2328 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
2330 topSum += latency[sortByLatency[i]] * bw; /* / 100 */
2331 botSum += bw; /* / 100 */
2333 t0 = ((len * 100) + topSum + botSum / 2) / botSum;
2335 /* Compute f_i(t_0) all i */
2336 for (total = i = 0; i < numFragments; i++) {
2337 int bw = priv->links[
2338 priv->activeLinks[sortByLatency[i]]].conf.bandwidth;
2340 distrib[sortByLatency[i]] =
2341 (bw * (t0 - latency[sortByLatency[i]]) + 50) / 100;
2342 total += distrib[sortByLatency[i]];
2345 /* Deal with any rounding error */
2347 struct ng_ppp_link *fastLink =
2348 &priv->links[priv->activeLinks[sortByLatency[0]]];
2351 /* Find the fastest link */
2352 for (i = 1; i < numFragments; i++) {
2353 struct ng_ppp_link *const link =
2354 &priv->links[priv->activeLinks[sortByLatency[i]]];
2356 if (link->conf.bandwidth > fastLink->conf.bandwidth) {
2361 distrib[sortByLatency[fast]] += len - total;
2362 } else while (total > len) {
2363 struct ng_ppp_link *slowLink =
2364 &priv->links[priv->activeLinks[sortByLatency[0]]];
2365 int delta, slow = 0;
2367 /* Find the slowest link that still has bytes to remove */
2368 for (i = 1; i < numFragments; i++) {
2369 struct ng_ppp_link *const link =
2370 &priv->links[priv->activeLinks[sortByLatency[i]]];
2372 if (distrib[sortByLatency[slow]] == 0
2373 || (distrib[sortByLatency[i]] > 0
2374 && link->conf.bandwidth <
2375 slowLink->conf.bandwidth)) {
2380 delta = total - len;
2381 if (delta > distrib[sortByLatency[slow]])
2382 delta = distrib[sortByLatency[slow]];
2383 distrib[sortByLatency[slow]] -= delta;
2389 * Compare two integers
2392 ng_ppp_intcmp(void *latency, const void *v1, const void *v2)
2394 const int index1 = *((const int *) v1);
2395 const int index2 = *((const int *) v2);
2397 return ((int *)latency)[index1] - ((int *)latency)[index2];
2401 * Prepend a possibly compressed PPP protocol number in front of a frame
2403 static struct mbuf *
2404 ng_ppp_addproto(struct mbuf *m, uint16_t proto, int compOK)
2406 if (compOK && PROT_COMPRESSABLE(proto)) {
2407 uint8_t pbyte = (uint8_t)proto;
2409 return ng_ppp_prepend(m, &pbyte, 1);
2411 uint16_t pword = htons((uint16_t)proto);
2413 return ng_ppp_prepend(m, &pword, 2);
2418 * Cut a possibly compressed PPP protocol number from the front of a frame.
2420 static struct mbuf *
2421 ng_ppp_cutproto(struct mbuf *m, uint16_t *proto)
2425 if (m->m_len < 1 && (m = m_pullup(m, 1)) == NULL)
2428 *proto = *mtod(m, uint8_t *);
2431 if (!PROT_VALID(*proto)) {
2432 if (m->m_len < 1 && (m = m_pullup(m, 1)) == NULL)
2435 *proto = (*proto << 8) + *mtod(m, uint8_t *);
2443 * Prepend some bytes to an mbuf.
2445 static struct mbuf *
2446 ng_ppp_prepend(struct mbuf *m, const void *buf, int len)
2448 M_PREPEND(m, len, M_DONTWAIT);
2449 if (m == NULL || (m->m_len < len && (m = m_pullup(m, len)) == NULL))
2451 bcopy(buf, mtod(m, uint8_t *), len);
2456 * Update private information that is derived from other private information
2459 ng_ppp_update(node_p node, int newConf)
2461 const priv_p priv = NG_NODE_PRIVATE(node);
2464 /* Update active status for VJ Compression */
2465 priv->vjCompHooked = priv->hooks[HOOK_INDEX_VJC_IP] != NULL
2466 && priv->hooks[HOOK_INDEX_VJC_COMP] != NULL
2467 && priv->hooks[HOOK_INDEX_VJC_UNCOMP] != NULL
2468 && priv->hooks[HOOK_INDEX_VJC_VJIP] != NULL;
2470 /* Increase latency for each link an amount equal to one MP header */
2472 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
2475 if (priv->links[i].conf.bandwidth == 0)
2478 hdrBytes = MP_AVERAGE_LINK_OVERHEAD
2479 + (priv->links[i].conf.enableACFComp ? 0 : 2)
2480 + (priv->links[i].conf.enableProtoComp ? 1 : 2)
2481 + (priv->conf.xmitShortSeq ? 2 : 4);
2482 priv->links[i].latency =
2483 priv->links[i].conf.latency +
2484 (hdrBytes / priv->links[i].conf.bandwidth + 50) / 100;
2488 /* Update list of active links */
2489 bzero(&priv->activeLinks, sizeof(priv->activeLinks));
2490 priv->numActiveLinks = 0;
2491 priv->allLinksEqual = 1;
2492 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
2493 struct ng_ppp_link *const link = &priv->links[i];
2495 /* Is link active? */
2496 if (link->conf.enableLink && link->hook != NULL) {
2497 struct ng_ppp_link *link0;
2499 /* Add link to list of active links */
2500 priv->activeLinks[priv->numActiveLinks++] = i;
2501 link0 = &priv->links[priv->activeLinks[0]];
2503 /* Determine if all links are still equal */
2504 if (link->latency != link0->latency
2505 || link->conf.bandwidth != link0->conf.bandwidth)
2506 priv->allLinksEqual = 0;
2508 /* Initialize rec'd sequence number */
2509 if (link->seq == MP_NOSEQ) {
2510 link->seq = (link == link0) ?
2511 MP_INITIAL_SEQ : link0->seq;
2514 link->seq = MP_NOSEQ;
2517 /* Update MP state as multi-link is active or not */
2518 if (priv->conf.enableMultilink && priv->numActiveLinks > 0)
2519 ng_ppp_start_frag_timer(node);
2521 ng_ppp_stop_frag_timer(node);
2522 ng_ppp_frag_reset(node);
2523 priv->xseq = MP_INITIAL_SEQ;
2524 priv->mseq = MP_INITIAL_SEQ;
2525 for (i = 0; i < NG_PPP_MAX_LINKS; i++) {
2526 struct ng_ppp_link *const link = &priv->links[i];
2528 bzero(&link->lastWrite, sizeof(link->lastWrite));
2529 link->bytesInQueue = 0;
2530 link->seq = MP_NOSEQ;
2536 * Determine if a new configuration would represent a valid change
2537 * from the current configuration and link activity status.
2540 ng_ppp_config_valid(node_p node, const struct ng_ppp_node_conf *newConf)
2542 const priv_p priv = NG_NODE_PRIVATE(node);
2543 int i, newNumLinksActive;
2545 /* Check per-link config and count how many links would be active */
2546 for (newNumLinksActive = i = 0; i < NG_PPP_MAX_LINKS; i++) {
2547 if (newConf->links[i].enableLink && priv->links[i].hook != NULL)
2548 newNumLinksActive++;
2549 if (!newConf->links[i].enableLink)
2551 if (newConf->links[i].mru < MP_MIN_LINK_MRU)
2553 if (newConf->links[i].bandwidth == 0)
2555 if (newConf->links[i].bandwidth > NG_PPP_MAX_BANDWIDTH)
2557 if (newConf->links[i].latency > NG_PPP_MAX_LATENCY)
2561 /* Disallow changes to multi-link configuration while MP is active */
2562 if (priv->numActiveLinks > 0 && newNumLinksActive > 0) {
2563 if (!priv->conf.enableMultilink
2564 != !newConf->bund.enableMultilink
2565 || !priv->conf.xmitShortSeq != !newConf->bund.xmitShortSeq
2566 || !priv->conf.recvShortSeq != !newConf->bund.recvShortSeq)
2570 /* At most one link can be active unless multi-link is enabled */
2571 if (!newConf->bund.enableMultilink && newNumLinksActive > 1)
2574 /* Configuration change would be valid */
2579 * Free all entries in the fragment queue
2582 ng_ppp_frag_reset(node_p node)
2584 const priv_p priv = NG_NODE_PRIVATE(node);
2585 struct ng_ppp_frag *qent, *qnext;
2587 for (qent = TAILQ_FIRST(&priv->frags); qent; qent = qnext) {
2588 qnext = TAILQ_NEXT(qent, f_qent);
2589 NG_FREE_M(qent->data);
2590 TAILQ_INSERT_HEAD(&priv->fragsfree, qent, f_qent);
2592 TAILQ_INIT(&priv->frags);
2596 * Start fragment queue timer
2599 ng_ppp_start_frag_timer(node_p node)
2601 const priv_p priv = NG_NODE_PRIVATE(node);
2603 if (!(callout_pending(&priv->fragTimer)))
2604 ng_callout(&priv->fragTimer, node, NULL, MP_FRAGTIMER_INTERVAL,
2605 ng_ppp_frag_timeout, NULL, 0);
2609 * Stop fragment queue timer
2612 ng_ppp_stop_frag_timer(node_p node)
2614 const priv_p priv = NG_NODE_PRIVATE(node);
2616 if (callout_pending(&priv->fragTimer))
2617 ng_uncallout(&priv->fragTimer, node);