The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/netgraph/ng_ppp.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: d8b55d43065e1abe42fa37f89fffcc74


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.