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

Cache object: c5f3b4f5b9f3ca1af845d87d7320d7ae


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