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

Cache object: f258e7dfbb7d25e44286d1ed6887ae63


[ 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.