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


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

FreeBSD/Linux Kernel Cross Reference
sys/netinet/siftr.c

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

    1 /*-
    2  * Copyright (c) 2007-2009
    3  *      Swinburne University of Technology, Melbourne, Australia.
    4  * Copyright (c) 2009-2010, The FreeBSD Foundation
    5  * All rights reserved.
    6  *
    7  * Portions of this software were developed at the Centre for Advanced
    8  * Internet Architectures, Swinburne University of Technology, Melbourne,
    9  * Australia by Lawrence Stewart under sponsorship from the FreeBSD Foundation.
   10  *
   11  * Redistribution and use in source and binary forms, with or without
   12  * modification, are permitted provided that the following conditions
   13  * are met:
   14  * 1. Redistributions of source code must retain the above copyright
   15  *    notice, this list of conditions and the following disclaimer.
   16  * 2. Redistributions in binary form must reproduce the above copyright
   17  *    notice, this list of conditions and the following disclaimer in the
   18  *    documentation and/or other materials provided with the distribution.
   19  *
   20  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
   21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
   24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   30  * SUCH DAMAGE.
   31  */
   32 
   33 /******************************************************
   34  * Statistical Information For TCP Research (SIFTR)
   35  *
   36  * A FreeBSD kernel module that adds very basic intrumentation to the
   37  * TCP stack, allowing internal stats to be recorded to a log file
   38  * for experimental, debugging and performance analysis purposes.
   39  *
   40  * SIFTR was first released in 2007 by James Healy and Lawrence Stewart whilst
   41  * working on the NewTCP research project at Swinburne University's Centre for
   42  * Advanced Internet Architectures, Melbourne, Australia, which was made
   43  * possible in part by a grant from the Cisco University Research Program Fund
   44  * at Community Foundation Silicon Valley. More details are available at:
   45  *   http://caia.swin.edu.au/urp/newtcp/
   46  *
   47  * Work on SIFTR v1.2.x was sponsored by the FreeBSD Foundation as part of
   48  * the "Enhancing the FreeBSD TCP Implementation" project 2008-2009.
   49  * More details are available at:
   50  *   http://www.freebsdfoundation.org/
   51  *   http://caia.swin.edu.au/freebsd/etcp09/
   52  *
   53  * Lawrence Stewart is the current maintainer, and all contact regarding
   54  * SIFTR should be directed to him via email: lastewart@swin.edu.au
   55  *
   56  * Initial release date: June 2007
   57  * Most recent update: September 2010
   58  ******************************************************/
   59 
   60 #include <sys/cdefs.h>
   61 __FBSDID("$FreeBSD: releng/7.4/sys/netinet/siftr.c 215929 2010-11-27 03:46:32Z lstewart $");
   62 
   63 #include <sys/param.h>
   64 #include <sys/alq.h>
   65 #include <sys/errno.h>
   66 #include <sys/hash.h>
   67 #include <sys/kernel.h>
   68 #include <sys/kthread.h>
   69 #include <sys/lock.h>
   70 #include <sys/mbuf.h>
   71 #include <sys/module.h>
   72 #include <sys/mutex.h>
   73 #include <sys/pcpu.h>
   74 #include <sys/proc.h>
   75 #include <sys/sbuf.h>
   76 #include <sys/smp.h>
   77 #include <sys/socket.h>
   78 #include <sys/socketvar.h>
   79 #include <sys/sysctl.h>
   80 #include <sys/unistd.h>
   81 
   82 #include <net/if.h>
   83 #include <net/pfil.h>
   84 
   85 #include <netinet/in.h>
   86 #include <netinet/in_pcb.h>
   87 #include <netinet/in_systm.h>
   88 #include <netinet/in_var.h>
   89 #include <netinet/ip.h>
   90 #include <netinet/tcp_var.h>
   91 
   92 #ifdef SIFTR_IPV6
   93 #include <netinet/ip6.h>
   94 #include <netinet6/in6_pcb.h>
   95 #endif /* SIFTR_IPV6 */
   96 
   97 #include <machine/in_cksum.h>
   98 
   99 /*
  100  * Three digit version number refers to X.Y.Z where:
  101  * X is the major version number
  102  * Y is bumped to mark backwards incompatible changes
  103  * Z is bumped to mark backwards compatible changes
  104  */
  105 #define V_MAJOR         1
  106 #define V_BACKBREAK     2
  107 #define V_BACKCOMPAT    4
  108 #define MODVERSION      __CONCAT(V_MAJOR, __CONCAT(V_BACKBREAK, V_BACKCOMPAT))
  109 #define MODVERSION_STR  __XSTRING(V_MAJOR) "." __XSTRING(V_BACKBREAK) "." \
  110     __XSTRING(V_BACKCOMPAT)
  111 
  112 #define HOOK 0
  113 #define UNHOOK 1
  114 #define SIFTR_EXPECTED_MAX_TCP_FLOWS 65536
  115 #define SYS_NAME "FreeBSD"
  116 #define PACKET_TAG_SIFTR 100
  117 #define PACKET_COOKIE_SIFTR 21749576
  118 #define SIFTR_LOG_FILE_MODE 0644
  119 #define SIFTR_DISABLE 0
  120 #define SIFTR_ENABLE 1
  121 
  122 /*
  123  * Hard upper limit on the length of log messages. Bump this up if you add new
  124  * data fields such that the line length could exceed the below value.
  125  */
  126 #define MAX_LOG_MSG_LEN 200
  127 /* XXX: Make this a sysctl tunable. */
  128 #define SIFTR_ALQ_BUFLEN (1000*MAX_LOG_MSG_LEN)
  129 
  130 /*
  131  * 1 byte for IP version
  132  * IPv4: src/dst IP (4+4) + src/dst port (2+2) = 12 bytes
  133  * IPv6: src/dst IP (16+16) + src/dst port (2+2) = 36 bytes
  134  */
  135 #ifdef SIFTR_IPV6
  136 #define FLOW_KEY_LEN 37
  137 #else
  138 #define FLOW_KEY_LEN 13
  139 #endif
  140 
  141 #ifdef SIFTR_IPV6
  142 #define SIFTR_IPMODE 6
  143 #else
  144 #define SIFTR_IPMODE 4
  145 #endif
  146 
  147 /* useful macros */
  148 #define CAST_PTR_INT(X) (*((int*)(X)))
  149 
  150 #define UPPER_SHORT(X)  (((X) & 0xFFFF0000) >> 16)
  151 #define LOWER_SHORT(X)  ((X) & 0x0000FFFF)
  152 
  153 #define FIRST_OCTET(X)  (((X) & 0xFF000000) >> 24)
  154 #define SECOND_OCTET(X) (((X) & 0x00FF0000) >> 16)
  155 #define THIRD_OCTET(X)  (((X) & 0x0000FF00) >> 8)
  156 #define FOURTH_OCTET(X) ((X) & 0x000000FF)
  157 
  158 MALLOC_DECLARE(M_SIFTR);
  159 MALLOC_DEFINE(M_SIFTR, "siftr", "dynamic memory used by SIFTR");
  160 
  161 MALLOC_DECLARE(M_SIFTR_PKTNODE);
  162 MALLOC_DEFINE(M_SIFTR_PKTNODE, "siftr_pktnode", "SIFTR pkt_node struct");
  163 
  164 MALLOC_DECLARE(M_SIFTR_HASHNODE);
  165 MALLOC_DEFINE(M_SIFTR_HASHNODE, "siftr_hashnode", "SIFTR flow_hash_node struct");
  166 
  167 /* Used as links in the pkt manager queue. */
  168 struct pkt_node {
  169         /* Timestamp of pkt as noted in the pfil hook. */
  170         struct timeval          tval;
  171         /* Direction pkt is travelling; either PFIL_IN or PFIL_OUT. */
  172         uint8_t                 direction;
  173         /* IP version pkt_node relates to; either INP_IPV4 or INP_IPV6. */
  174         uint8_t                 ipver;
  175         /* Hash of the pkt which triggered the log message. */
  176         uint32_t                hash;
  177         /* Local/foreign IP address. */
  178 #ifdef SIFTR_IPV6
  179         uint32_t                ip_laddr[4];
  180         uint32_t                ip_faddr[4];
  181 #else
  182         uint8_t                 ip_laddr[4];
  183         uint8_t                 ip_faddr[4];
  184 #endif
  185         /* Local TCP port. */
  186         uint16_t                tcp_localport;
  187         /* Foreign TCP port. */
  188         uint16_t                tcp_foreignport;
  189         /* Congestion Window (bytes). */
  190         u_long                  snd_cwnd;
  191         /* Sending Window (bytes). */
  192         u_long                  snd_wnd;
  193         /* Receive Window (bytes). */
  194         u_long                  rcv_wnd;
  195         /* Bandwidth Controlled Window (bytes). */
  196         u_long                  snd_bwnd;
  197         /* Slow Start Threshold (bytes). */
  198         u_long                  snd_ssthresh;
  199         /* Current state of the TCP FSM. */
  200         int                     conn_state;
  201         /* Max Segment Size (bytes). */
  202         u_int                   max_seg_size;
  203         /*
  204          * Smoothed RTT stored as found in the TCP control block
  205          * in units of (TCP_RTT_SCALE*hz).
  206          */
  207         int                     smoothed_rtt;
  208         /* Is SACK enabled? */
  209         u_char                  sack_enabled;
  210         /* Window scaling for snd window. */
  211         u_char                  snd_scale;
  212         /* Window scaling for recv window. */
  213         u_char                  rcv_scale;
  214         /* TCP control block flags. */
  215         u_int                   flags;
  216         /* Retransmit timeout length. */
  217         int                     rxt_length;
  218         /* Size of the TCP send buffer in bytes. */
  219         u_int                   snd_buf_hiwater;
  220         /* Current num bytes in the send socket buffer. */
  221         u_int                   snd_buf_cc;
  222         /* Size of the TCP receive buffer in bytes. */
  223         u_int                   rcv_buf_hiwater;
  224         /* Current num bytes in the receive socket buffer. */
  225         u_int                   rcv_buf_cc;
  226         /* Number of bytes inflight that we are waiting on ACKs for. */
  227         u_int                   sent_inflight_bytes;
  228         /* Number of segments currently in the reassembly queue. */
  229         int                     t_segqlen;
  230         /* Link to next pkt_node in the list. */
  231         STAILQ_ENTRY(pkt_node)  nodes;
  232 };
  233 
  234 struct flow_hash_node
  235 {
  236         uint16_t counter;
  237         uint8_t key[FLOW_KEY_LEN];
  238         LIST_ENTRY(flow_hash_node) nodes;
  239 };
  240 
  241 struct siftr_stats
  242 {
  243         /* # TCP pkts seen by the SIFTR PFIL hooks, including any skipped. */
  244         uint64_t n_in;
  245         uint64_t n_out;
  246         /* # pkts skipped due to failed malloc calls. */
  247         uint32_t nskip_in_malloc;
  248         uint32_t nskip_out_malloc;
  249         /* # pkts skipped due to failed mtx acquisition. */
  250         uint32_t nskip_in_mtx;
  251         uint32_t nskip_out_mtx;
  252         /* # pkts skipped due to failed inpcb lookups. */
  253         uint32_t nskip_in_inpcb;
  254         uint32_t nskip_out_inpcb;
  255         /* # pkts skipped due to failed tcpcb lookups. */
  256         uint32_t nskip_in_tcpcb;
  257         uint32_t nskip_out_tcpcb;
  258         /* # pkts skipped due to stack reinjection. */
  259         uint32_t nskip_in_dejavu;
  260         uint32_t nskip_out_dejavu;
  261 };
  262 
  263 /* Pre 8 and pre DPCPU. */
  264 static struct proc *siftr_pkt_manager_proc = NULL;
  265 #define V_tcbinfo       tcbinfo
  266 static struct siftr_stats       nondpcpu_ss;
  267 #define DPCPU_PTR(n)            &nondpcpu_##n
  268 #define DPCPU_VARSUM(n, var)    nondpcpu_##n.var
  269 #define DPCPU_ZERO(n)           bzero(&nondpcpu_##n, sizeof(nondpcpu_##n))
  270 
  271 static volatile unsigned int siftr_exit_pkt_manager_thread = 0;
  272 static unsigned int siftr_enabled = 0;
  273 static unsigned int siftr_pkts_per_log = 1;
  274 static unsigned int siftr_generate_hashes = 0;
  275 /* static unsigned int siftr_binary_log = 0; */
  276 static char siftr_logfile[PATH_MAX] = "/var/log/siftr.log";
  277 static u_long siftr_hashmask;
  278 STAILQ_HEAD(pkthead, pkt_node) pkt_queue = STAILQ_HEAD_INITIALIZER(pkt_queue);
  279 LIST_HEAD(listhead, flow_hash_node) *counter_hash;
  280 static int wait_for_pkt;
  281 static struct alq *siftr_alq = NULL;
  282 static struct mtx siftr_pkt_queue_mtx;
  283 static struct mtx siftr_pkt_mgr_mtx;
  284 static struct thread *siftr_pkt_manager_thr = NULL;
  285 /*
  286  * pfil.h defines PFIL_IN as 1 and PFIL_OUT as 2,
  287  * which we use as an index into this array.
  288  */
  289 static char direction[3] = {'\0', 'i','o'};
  290 
  291 /* Required function prototypes. */
  292 static int siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS);
  293 static int siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS);
  294 
  295 
  296 /* Declare the net.inet.siftr sysctl tree and populate it. */
  297 
  298 SYSCTL_DECL(_net_inet_siftr);
  299 
  300 SYSCTL_NODE(_net_inet, OID_AUTO, siftr, CTLFLAG_RW, NULL,
  301     "siftr related settings");
  302 
  303 SYSCTL_PROC(_net_inet_siftr, OID_AUTO, enabled, CTLTYPE_UINT|CTLFLAG_RW,
  304     &siftr_enabled, 0, &siftr_sysctl_enabled_handler, "IU",
  305     "switch siftr module operations on/off");
  306 
  307 SYSCTL_PROC(_net_inet_siftr, OID_AUTO, logfile, CTLTYPE_STRING|CTLFLAG_RW,
  308     &siftr_logfile, sizeof(siftr_logfile), &siftr_sysctl_logfile_name_handler,
  309     "A", "file to save siftr log messages to");
  310 
  311 SYSCTL_UINT(_net_inet_siftr, OID_AUTO, ppl, CTLFLAG_RW,
  312     &siftr_pkts_per_log, 1,
  313     "number of packets between generating a log message");
  314 
  315 SYSCTL_UINT(_net_inet_siftr, OID_AUTO, genhashes, CTLFLAG_RW,
  316     &siftr_generate_hashes, 0,
  317     "enable packet hash generation");
  318 
  319 /* XXX: TODO
  320 SYSCTL_UINT(_net_inet_siftr, OID_AUTO, binary, CTLFLAG_RW,
  321     &siftr_binary_log, 0,
  322     "write log files in binary instead of ascii");
  323 */
  324 
  325 
  326 /* Begin functions. */
  327 
  328 static void
  329 siftr_process_pkt(struct pkt_node * pkt_node)
  330 {
  331         struct flow_hash_node *hash_node;
  332         struct listhead *counter_list;
  333         struct siftr_stats *ss;
  334         struct ale *log_buf;
  335         uint8_t key[FLOW_KEY_LEN];
  336         uint8_t found_match, key_offset;
  337 
  338         hash_node = NULL;
  339         ss = DPCPU_PTR(ss);
  340         found_match = 0;
  341         key_offset = 1;
  342 
  343         /*
  344          * Create the key that will be used to create a hash index
  345          * into our hash table. Our key consists of:
  346          * ipversion, localip, localport, foreignip, foreignport
  347          */
  348         key[0] = pkt_node->ipver;
  349         memcpy(key + key_offset, &pkt_node->ip_laddr,
  350             sizeof(pkt_node->ip_laddr));
  351         key_offset += sizeof(pkt_node->ip_laddr);
  352         memcpy(key + key_offset, &pkt_node->tcp_localport,
  353             sizeof(pkt_node->tcp_localport));
  354         key_offset += sizeof(pkt_node->tcp_localport);
  355         memcpy(key + key_offset, &pkt_node->ip_faddr,
  356             sizeof(pkt_node->ip_faddr));
  357         key_offset += sizeof(pkt_node->ip_faddr);
  358         memcpy(key + key_offset, &pkt_node->tcp_foreignport,
  359             sizeof(pkt_node->tcp_foreignport));
  360 
  361         counter_list = counter_hash +
  362             (hash32_buf(key, sizeof(key), 0) & siftr_hashmask);
  363 
  364         /*
  365          * If the list is not empty i.e. the hash index has
  366          * been used by another flow previously.
  367          */
  368         if (LIST_FIRST(counter_list) != NULL) {
  369                 /*
  370                  * Loop through the hash nodes in the list.
  371                  * There should normally only be 1 hash node in the list,
  372                  * except if there have been collisions at the hash index
  373                  * computed by hash32_buf().
  374                  */
  375                 LIST_FOREACH(hash_node, counter_list, nodes) {
  376                         /*
  377                          * Check if the key for the pkt we are currently
  378                          * processing is the same as the key stored in the
  379                          * hash node we are currently processing.
  380                          * If they are the same, then we've found the
  381                          * hash node that stores the counter for the flow
  382                          * the pkt belongs to.
  383                          */
  384                         if (memcmp(hash_node->key, key, sizeof(key)) == 0) {
  385                                 found_match = 1;
  386                                 break;
  387                         }
  388                 }
  389         }
  390 
  391         /* If this flow hash hasn't been seen before or we have a collision. */
  392         if (hash_node == NULL || !found_match) {
  393                 /* Create a new hash node to store the flow's counter. */
  394                 hash_node = malloc(sizeof(struct flow_hash_node),
  395                     M_SIFTR_HASHNODE, M_WAITOK);
  396 
  397                 if (hash_node != NULL) {
  398                         /* Initialise our new hash node list entry. */
  399                         hash_node->counter = 0;
  400                         memcpy(hash_node->key, key, sizeof(key));
  401                         LIST_INSERT_HEAD(counter_list, hash_node, nodes);
  402                 } else {
  403                         /* Malloc failed. */
  404                         if (pkt_node->direction == PFIL_IN)
  405                                 ss->nskip_in_malloc++;
  406                         else
  407                                 ss->nskip_out_malloc++;
  408 
  409                         return;
  410                 }
  411         } else if (siftr_pkts_per_log > 1) {
  412                 /*
  413                  * Taking the remainder of the counter divided
  414                  * by the current value of siftr_pkts_per_log
  415                  * and storing that in counter provides a neat
  416                  * way to modulate the frequency of log
  417                  * messages being written to the log file.
  418                  */
  419                 hash_node->counter = (hash_node->counter + 1) %
  420                     siftr_pkts_per_log;
  421 
  422                 /*
  423                  * If we have not seen enough packets since the last time
  424                  * we wrote a log message for this connection, return.
  425                  */
  426                 if (hash_node->counter > 0)
  427                         return;
  428         }
  429 
  430         log_buf = alq_getn(siftr_alq, MAX_LOG_MSG_LEN, ALQ_WAITOK);
  431 
  432         if (log_buf == NULL)
  433                 return; /* Should only happen if the ALQ is shutting down. */
  434 
  435 #ifdef SIFTR_IPV6
  436         pkt_node->ip_laddr[3] = ntohl(pkt_node->ip_laddr[3]);
  437         pkt_node->ip_faddr[3] = ntohl(pkt_node->ip_faddr[3]);
  438 
  439         if (pkt_node->ipver == INP_IPV6) { /* IPv6 packet */
  440                 pkt_node->ip_laddr[0] = ntohl(pkt_node->ip_laddr[0]);
  441                 pkt_node->ip_laddr[1] = ntohl(pkt_node->ip_laddr[1]);
  442                 pkt_node->ip_laddr[2] = ntohl(pkt_node->ip_laddr[2]);
  443                 pkt_node->ip_faddr[0] = ntohl(pkt_node->ip_faddr[0]);
  444                 pkt_node->ip_faddr[1] = ntohl(pkt_node->ip_faddr[1]);
  445                 pkt_node->ip_faddr[2] = ntohl(pkt_node->ip_faddr[2]);
  446 
  447                 /* Construct an IPv6 log message. */
  448                 log_buf->ae_bytesused = snprintf(log_buf->ae_data,
  449                     MAX_LOG_MSG_LEN,
  450                     "%c,0x%08x,%zd.%06ld,%x:%x:%x:%x:%x:%x:%x:%x,%u,%x:%x:%x:"
  451                     "%x:%x:%x:%x:%x,%u,%ld,%ld,%ld,%ld,%ld,%u,%u,%u,%u,%u,%u,"
  452                     "%u,%d,%u,%u,%u,%u,%u,%u\n",
  453                     direction[pkt_node->direction],
  454                     pkt_node->hash,
  455                     pkt_node->tval.tv_sec,
  456                     pkt_node->tval.tv_usec,
  457                     UPPER_SHORT(pkt_node->ip_laddr[0]),
  458                     LOWER_SHORT(pkt_node->ip_laddr[0]),
  459                     UPPER_SHORT(pkt_node->ip_laddr[1]),
  460                     LOWER_SHORT(pkt_node->ip_laddr[1]),
  461                     UPPER_SHORT(pkt_node->ip_laddr[2]),
  462                     LOWER_SHORT(pkt_node->ip_laddr[2]),
  463                     UPPER_SHORT(pkt_node->ip_laddr[3]),
  464                     LOWER_SHORT(pkt_node->ip_laddr[3]),
  465                     ntohs(pkt_node->tcp_localport),
  466                     UPPER_SHORT(pkt_node->ip_faddr[0]),
  467                     LOWER_SHORT(pkt_node->ip_faddr[0]),
  468                     UPPER_SHORT(pkt_node->ip_faddr[1]),
  469                     LOWER_SHORT(pkt_node->ip_faddr[1]),
  470                     UPPER_SHORT(pkt_node->ip_faddr[2]),
  471                     LOWER_SHORT(pkt_node->ip_faddr[2]),
  472                     UPPER_SHORT(pkt_node->ip_faddr[3]),
  473                     LOWER_SHORT(pkt_node->ip_faddr[3]),
  474                     ntohs(pkt_node->tcp_foreignport),
  475                     pkt_node->snd_ssthresh,
  476                     pkt_node->snd_cwnd,
  477                     pkt_node->snd_bwnd,
  478                     pkt_node->snd_wnd,
  479                     pkt_node->rcv_wnd,
  480                     pkt_node->snd_scale,
  481                     pkt_node->rcv_scale,
  482                     pkt_node->conn_state,
  483                     pkt_node->max_seg_size,
  484                     pkt_node->smoothed_rtt,
  485                     pkt_node->sack_enabled,
  486                     pkt_node->flags,
  487                     pkt_node->rxt_length,
  488                     pkt_node->snd_buf_hiwater,
  489                     pkt_node->snd_buf_cc,
  490                     pkt_node->rcv_buf_hiwater,
  491                     pkt_node->rcv_buf_cc,
  492                     pkt_node->sent_inflight_bytes,
  493                     pkt_node->t_segqlen);
  494         } else { /* IPv4 packet */
  495                 pkt_node->ip_laddr[0] = FIRST_OCTET(pkt_node->ip_laddr[3]);
  496                 pkt_node->ip_laddr[1] = SECOND_OCTET(pkt_node->ip_laddr[3]);
  497                 pkt_node->ip_laddr[2] = THIRD_OCTET(pkt_node->ip_laddr[3]);
  498                 pkt_node->ip_laddr[3] = FOURTH_OCTET(pkt_node->ip_laddr[3]);
  499                 pkt_node->ip_faddr[0] = FIRST_OCTET(pkt_node->ip_faddr[3]);
  500                 pkt_node->ip_faddr[1] = SECOND_OCTET(pkt_node->ip_faddr[3]);
  501                 pkt_node->ip_faddr[2] = THIRD_OCTET(pkt_node->ip_faddr[3]);
  502                 pkt_node->ip_faddr[3] = FOURTH_OCTET(pkt_node->ip_faddr[3]);
  503 #endif /* SIFTR_IPV6 */
  504 
  505                 /* Construct an IPv4 log message. */
  506                 log_buf->ae_bytesused = snprintf(log_buf->ae_data,
  507                     MAX_LOG_MSG_LEN,
  508                     "%c,0x%08x,%jd.%06ld,%u.%u.%u.%u,%u,%u.%u.%u.%u,%u,%ld,%ld,"
  509                     "%ld,%ld,%ld,%u,%u,%u,%u,%u,%u,%u,%d,%u,%u,%u,%u,%u,%u\n",
  510                     direction[pkt_node->direction],
  511                     pkt_node->hash,
  512                     (intmax_t)pkt_node->tval.tv_sec,
  513                     pkt_node->tval.tv_usec,
  514                     pkt_node->ip_laddr[0],
  515                     pkt_node->ip_laddr[1],
  516                     pkt_node->ip_laddr[2],
  517                     pkt_node->ip_laddr[3],
  518                     ntohs(pkt_node->tcp_localport),
  519                     pkt_node->ip_faddr[0],
  520                     pkt_node->ip_faddr[1],
  521                     pkt_node->ip_faddr[2],
  522                     pkt_node->ip_faddr[3],
  523                     ntohs(pkt_node->tcp_foreignport),
  524                     pkt_node->snd_ssthresh,
  525                     pkt_node->snd_cwnd,
  526                     pkt_node->snd_bwnd,
  527                     pkt_node->snd_wnd,
  528                     pkt_node->rcv_wnd,
  529                     pkt_node->snd_scale,
  530                     pkt_node->rcv_scale,
  531                     pkt_node->conn_state,
  532                     pkt_node->max_seg_size,
  533                     pkt_node->smoothed_rtt,
  534                     pkt_node->sack_enabled,
  535                     pkt_node->flags,
  536                     pkt_node->rxt_length,
  537                     pkt_node->snd_buf_hiwater,
  538                     pkt_node->snd_buf_cc,
  539                     pkt_node->rcv_buf_hiwater,
  540                     pkt_node->rcv_buf_cc,
  541                     pkt_node->sent_inflight_bytes,
  542                     pkt_node->t_segqlen);
  543 #ifdef SIFTR_IPV6
  544         }
  545 #endif
  546 
  547         alq_post_flags(siftr_alq, log_buf, 0);
  548 }
  549 
  550 
  551 static void
  552 siftr_pkt_manager_thread(void *arg)
  553 {
  554         STAILQ_HEAD(pkthead, pkt_node) tmp_pkt_queue =
  555             STAILQ_HEAD_INITIALIZER(tmp_pkt_queue);
  556         struct pkt_node *pkt_node, *pkt_node_temp;
  557         uint8_t draining;
  558 
  559         draining = 2;
  560 
  561         mtx_lock(&siftr_pkt_mgr_mtx);
  562 
  563         /* draining == 0 when queue has been flushed and it's safe to exit. */
  564         while (draining) {
  565                 /*
  566                  * Sleep until we are signalled to wake because thread has
  567                  * been told to exit or until 1 tick has passed.
  568                  */
  569                 mtx_sleep(&wait_for_pkt, &siftr_pkt_mgr_mtx, PWAIT, "pktwait",
  570                     1);
  571 
  572                 /* Gain exclusive access to the pkt_node queue. */
  573                 mtx_lock(&siftr_pkt_queue_mtx);
  574 
  575                 /*
  576                  * Move pkt_queue to tmp_pkt_queue, which leaves
  577                  * pkt_queue empty and ready to receive more pkt_nodes.
  578                  */
  579                 STAILQ_CONCAT(&tmp_pkt_queue, &pkt_queue);
  580 
  581                 /*
  582                  * We've finished making changes to the list. Unlock it
  583                  * so the pfil hooks can continue queuing pkt_nodes.
  584                  */
  585                 mtx_unlock(&siftr_pkt_queue_mtx);
  586 
  587                 /*
  588                  * We can't hold a mutex whilst calling siftr_process_pkt
  589                  * because ALQ might sleep waiting for buffer space.
  590                  */
  591                 mtx_unlock(&siftr_pkt_mgr_mtx);
  592 
  593                 /* Flush all pkt_nodes to the log file. */
  594                 STAILQ_FOREACH_SAFE(pkt_node, &tmp_pkt_queue, nodes,
  595                     pkt_node_temp) {
  596                         siftr_process_pkt(pkt_node);
  597                         STAILQ_REMOVE_HEAD(&tmp_pkt_queue, nodes);
  598                         free(pkt_node, M_SIFTR_PKTNODE);
  599                 }
  600 
  601                 KASSERT(STAILQ_EMPTY(&tmp_pkt_queue),
  602                     ("SIFTR tmp_pkt_queue not empty after flush"));
  603 
  604                 mtx_lock(&siftr_pkt_mgr_mtx);
  605 
  606                 /*
  607                  * If siftr_exit_pkt_manager_thread gets set during the window
  608                  * where we are draining the tmp_pkt_queue above, there might
  609                  * still be pkts in pkt_queue that need to be drained.
  610                  * Allow one further iteration to occur after
  611                  * siftr_exit_pkt_manager_thread has been set to ensure
  612                  * pkt_queue is completely empty before we kill the thread.
  613                  *
  614                  * siftr_exit_pkt_manager_thread is set only after the pfil
  615                  * hooks have been removed, so only 1 extra iteration
  616                  * is needed to drain the queue.
  617                  */
  618                 if (siftr_exit_pkt_manager_thread)
  619                         draining--;
  620         }
  621 
  622         mtx_unlock(&siftr_pkt_mgr_mtx);
  623 
  624         /* Calls wakeup on this thread's struct proc ptr on 7.x. */
  625         kthread_exit(0);
  626 }
  627 
  628 
  629 static uint32_t
  630 hash_pkt(struct mbuf *m, uint32_t offset)
  631 {
  632         uint32_t hash;
  633 
  634         hash = 0;
  635 
  636         while (m != NULL && offset > m->m_len) {
  637                 /*
  638                  * The IP packet payload does not start in this mbuf, so
  639                  * need to figure out which mbuf it starts in and what offset
  640                  * into the mbuf's data region the payload starts at.
  641                  */
  642                 offset -= m->m_len;
  643                 m = m->m_next;
  644         }
  645 
  646         while (m != NULL) {
  647                 /* Ensure there is data in the mbuf */
  648                 if ((m->m_len - offset) > 0)
  649                         hash = hash32_buf(m->m_data + offset,
  650                             m->m_len - offset, hash);
  651 
  652                 m = m->m_next;
  653                 offset = 0;
  654         }
  655 
  656         return (hash);
  657 }
  658 
  659 
  660 /*
  661  * Check if a given mbuf has the SIFTR mbuf tag. If it does, log the fact that
  662  * it's a reinjected packet and return. If it doesn't, tag the mbuf and return.
  663  * Return value >0 means the caller should skip processing this mbuf.
  664  */
  665 static inline int
  666 siftr_chkreinject(struct mbuf *m, int dir, struct siftr_stats *ss)
  667 {
  668         if (m_tag_locate(m, PACKET_COOKIE_SIFTR, PACKET_TAG_SIFTR, NULL)
  669             != NULL) {
  670                 if (dir == PFIL_IN)
  671                         ss->nskip_in_dejavu++;
  672                 else
  673                         ss->nskip_out_dejavu++;
  674 
  675                 return (1);
  676         } else {
  677                 struct m_tag *tag = m_tag_alloc(PACKET_COOKIE_SIFTR,
  678                     PACKET_TAG_SIFTR, 0, M_NOWAIT);
  679                 if (tag == NULL) {
  680                         if (dir == PFIL_IN)
  681                                 ss->nskip_in_malloc++;
  682                         else
  683                                 ss->nskip_out_malloc++;
  684 
  685                         return (1);
  686                 }
  687 
  688                 m_tag_prepend(m, tag);
  689         }
  690 
  691         return (0);
  692 }
  693 
  694 
  695 /*
  696  * Look up an inpcb for a packet. Return the inpcb pointer if found, or NULL
  697  * otherwise.
  698  */
  699 static inline struct inpcb *
  700 siftr_findinpcb(int ipver, struct ip *ip, struct mbuf *m, uint16_t sport,
  701     uint16_t dport, int dir, struct siftr_stats *ss)
  702 {
  703         struct inpcb *inp;
  704 
  705         /* We need the tcbinfo lock. */
  706         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
  707         INP_INFO_RLOCK(&V_tcbinfo);
  708 
  709         if (dir == PFIL_IN)
  710                 inp = (ipver == INP_IPV4 ?
  711                     in_pcblookup_hash(&V_tcbinfo, ip->ip_src, sport, ip->ip_dst,
  712                     dport, 0, m->m_pkthdr.rcvif)
  713                     :
  714 #ifdef SIFTR_IPV6
  715                     in6_pcblookup_hash(&V_tcbinfo,
  716                     &((struct ip6_hdr *)ip)->ip6_src, sport,
  717                     &((struct ip6_hdr *)ip)->ip6_dst, dport, 0,
  718                     m->m_pkthdr.rcvif)
  719 #else
  720                     NULL
  721 #endif
  722                     );
  723 
  724         else
  725                 inp = (ipver == INP_IPV4 ?
  726                     in_pcblookup_hash(&V_tcbinfo, ip->ip_dst, dport, ip->ip_src,
  727                     sport, 0, m->m_pkthdr.rcvif)
  728                     :
  729 #ifdef SIFTR_IPV6
  730                     in6_pcblookup_hash(&V_tcbinfo,
  731                     &((struct ip6_hdr *)ip)->ip6_dst, dport,
  732                     &((struct ip6_hdr *)ip)->ip6_src, sport, 0,
  733                     m->m_pkthdr.rcvif)
  734 #else
  735                     NULL
  736 #endif
  737                     );
  738 
  739         /* If we can't find the inpcb, bail. */
  740         if (inp == NULL) {
  741                 if (dir == PFIL_IN)
  742                         ss->nskip_in_inpcb++;
  743                 else
  744                         ss->nskip_out_inpcb++;
  745         } else {
  746                 /* Acquire the inpcb lock. */
  747                 INP_UNLOCK_ASSERT(inp);
  748                 INP_RLOCK(inp);
  749         }
  750         INP_INFO_RUNLOCK(&V_tcbinfo);
  751 
  752         return (inp);
  753 }
  754 
  755 
  756 static inline void
  757 siftr_siftdata(struct pkt_node *pn, struct inpcb *inp, struct tcpcb *tp,
  758     int ipver, int dir, int inp_locally_locked)
  759 {
  760 #ifdef SIFTR_IPV6
  761         if (ipver == INP_IPV4) {
  762                 pn->ip_laddr[3] = inp->inp_laddr.s_addr;
  763                 pn->ip_faddr[3] = inp->inp_faddr.s_addr;
  764 #else
  765                 *((uint32_t *)pn->ip_laddr) = inp->inp_laddr.s_addr;
  766                 *((uint32_t *)pn->ip_faddr) = inp->inp_faddr.s_addr;
  767 #endif
  768 #ifdef SIFTR_IPV6
  769         } else {
  770                 pn->ip_laddr[0] = inp->in6p_laddr.s6_addr32[0];
  771                 pn->ip_laddr[1] = inp->in6p_laddr.s6_addr32[1];
  772                 pn->ip_laddr[2] = inp->in6p_laddr.s6_addr32[2];
  773                 pn->ip_laddr[3] = inp->in6p_laddr.s6_addr32[3];
  774                 pn->ip_faddr[0] = inp->in6p_faddr.s6_addr32[0];
  775                 pn->ip_faddr[1] = inp->in6p_faddr.s6_addr32[1];
  776                 pn->ip_faddr[2] = inp->in6p_faddr.s6_addr32[2];
  777                 pn->ip_faddr[3] = inp->in6p_faddr.s6_addr32[3];
  778         }
  779 #endif
  780         pn->tcp_localport = inp->inp_lport;
  781         pn->tcp_foreignport = inp->inp_fport;
  782         pn->snd_cwnd = tp->snd_cwnd;
  783         pn->snd_wnd = tp->snd_wnd;
  784         pn->rcv_wnd = tp->rcv_wnd;
  785         pn->snd_bwnd = tp->snd_bwnd;
  786         pn->snd_ssthresh = tp->snd_ssthresh;
  787         pn->snd_scale = tp->snd_scale;
  788         pn->rcv_scale = tp->rcv_scale;
  789         pn->conn_state = tp->t_state;
  790         pn->max_seg_size = tp->t_maxseg;
  791         pn->smoothed_rtt = tp->t_srtt;
  792         pn->sack_enabled = (tp->t_flags & TF_SACK_PERMIT) != 0;
  793         pn->flags = tp->t_flags;
  794         pn->rxt_length = tp->t_rxtcur;
  795         pn->snd_buf_hiwater = inp->inp_socket->so_snd.sb_hiwat;
  796         pn->snd_buf_cc = inp->inp_socket->so_snd.sb_cc;
  797         pn->rcv_buf_hiwater = inp->inp_socket->so_rcv.sb_hiwat;
  798         pn->rcv_buf_cc = inp->inp_socket->so_rcv.sb_cc;
  799         pn->sent_inflight_bytes = tp->snd_max - tp->snd_una;
  800         pn->t_segqlen = tp->t_segqlen;
  801 
  802         /* We've finished accessing the tcb so release the lock. */
  803         if (inp_locally_locked)
  804                 INP_RUNLOCK(inp);
  805 
  806         pn->ipver = ipver;
  807         pn->direction = dir;
  808 
  809         /*
  810          * Significantly more accurate than using getmicrotime(), but slower!
  811          * Gives true microsecond resolution at the expense of a hit to
  812          * maximum pps throughput processing when SIFTR is loaded and enabled.
  813          */
  814         microtime(&pn->tval);
  815 }
  816 
  817 
  818 /*
  819  * pfil hook that is called for each IPv4 packet making its way through the
  820  * stack in either direction.
  821  * The pfil subsystem holds a non-sleepable mutex somewhere when
  822  * calling our hook function, so we can't sleep at all.
  823  * It's very important to use the M_NOWAIT flag with all function calls
  824  * that support it so that they won't sleep, otherwise you get a panic.
  825  */
  826 static int
  827 siftr_chkpkt(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
  828     struct inpcb *inp)
  829 {
  830         struct pkt_node *pn;
  831         struct ip *ip;
  832         struct tcphdr *th;
  833         struct tcpcb *tp;
  834         struct siftr_stats *ss;
  835         unsigned int ip_hl;
  836         int inp_locally_locked;
  837 
  838         inp_locally_locked = 0;
  839         ss = DPCPU_PTR(ss);
  840 
  841         /*
  842          * m_pullup is not required here because ip_{input|output}
  843          * already do the heavy lifting for us.
  844          */
  845 
  846         ip = mtod(*m, struct ip *);
  847 
  848         /* Only continue processing if the packet is TCP. */
  849         if (ip->ip_p != IPPROTO_TCP)
  850                 goto ret;
  851 
  852         /*
  853          * If a kernel subsystem reinjects packets into the stack, our pfil
  854          * hook will be called multiple times for the same packet.
  855          * Make sure we only process unique packets.
  856          */
  857         if (siftr_chkreinject(*m, dir, ss))
  858                 goto ret;
  859 
  860         if (dir == PFIL_IN)
  861                 ss->n_in++;
  862         else
  863                 ss->n_out++;
  864 
  865         /*
  866          * Create a tcphdr struct starting at the correct offset
  867          * in the IP packet. ip->ip_hl gives the ip header length
  868          * in 4-byte words, so multiply it to get the size in bytes.
  869          */
  870         ip_hl = (ip->ip_hl << 2);
  871         th = (struct tcphdr *)((caddr_t)ip + ip_hl);
  872 
  873         /*
  874          * If the pfil hooks don't provide a pointer to the
  875          * inpcb, we need to find it ourselves and lock it.
  876          */
  877         if (!inp) {
  878                 /* Find the corresponding inpcb for this pkt. */
  879                 inp = siftr_findinpcb(INP_IPV4, ip, *m, th->th_sport,
  880                     th->th_dport, dir, ss);
  881 
  882                 if (inp == NULL)
  883                         goto ret;
  884                 else
  885                         inp_locally_locked = 1;
  886         }
  887 
  888         INP_LOCK_ASSERT(inp);
  889 
  890         /* Find the TCP control block that corresponds with this packet */
  891         tp = intotcpcb(inp);
  892 
  893         /*
  894          * If we can't find the TCP control block (happens occasionaly for a
  895          * packet sent during the shutdown phase of a TCP connection),
  896          * or we're in the timewait state, bail
  897          */
  898         if (tp == NULL || inp->inp_flags & INP_TIMEWAIT) {
  899                 if (dir == PFIL_IN)
  900                         ss->nskip_in_tcpcb++;
  901                 else
  902                         ss->nskip_out_tcpcb++;
  903 
  904                 goto inp_unlock;
  905         }
  906 
  907         pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
  908 
  909         if (pn == NULL) {
  910                 if (dir == PFIL_IN)
  911                         ss->nskip_in_malloc++;
  912                 else
  913                         ss->nskip_out_malloc++;
  914 
  915                 goto inp_unlock;
  916         }
  917 
  918         siftr_siftdata(pn, inp, tp, INP_IPV4, dir, inp_locally_locked);
  919 
  920         if (siftr_generate_hashes) {
  921                 if ((*m)->m_pkthdr.csum_flags & CSUM_TCP) {
  922                         /*
  923                          * For outbound packets, the TCP checksum isn't
  924                          * calculated yet. This is a problem for our packet
  925                          * hashing as the receiver will calc a different hash
  926                          * to ours if we don't include the correct TCP checksum
  927                          * in the bytes being hashed. To work around this
  928                          * problem, we manually calc the TCP checksum here in
  929                          * software. We unset the CSUM_TCP flag so the lower
  930                          * layers don't recalc it.
  931                          */
  932                         (*m)->m_pkthdr.csum_flags &= ~CSUM_TCP;
  933 
  934                         /*
  935                          * Calculate the TCP checksum in software and assign
  936                          * to correct TCP header field, which will follow the
  937                          * packet mbuf down the stack. The trick here is that
  938                          * tcp_output() sets th->th_sum to the checksum of the
  939                          * pseudo header for us already. Because of the nature
  940                          * of the checksumming algorithm, we can sum over the
  941                          * entire IP payload (i.e. TCP header and data), which
  942                          * will include the already calculated pseduo header
  943                          * checksum, thus giving us the complete TCP checksum.
  944                          *
  945                          * To put it in simple terms, if checksum(1,2,3,4)=10,
  946                          * then checksum(1,2,3,4,5) == checksum(10,5).
  947                          * This property is what allows us to "cheat" and
  948                          * checksum only the IP payload which has the TCP
  949                          * th_sum field populated with the pseudo header's
  950                          * checksum, and not need to futz around checksumming
  951                          * pseudo header bytes and TCP header/data in one hit.
  952                          * Refer to RFC 1071 for more info.
  953                          *
  954                          * NB: in_cksum_skip(struct mbuf *m, int len, int skip)
  955                          * in_cksum_skip 2nd argument is NOT the number of
  956                          * bytes to read from the mbuf at "skip" bytes offset
  957                          * from the start of the mbuf (very counter intuitive!).
  958                          * The number of bytes to read is calculated internally
  959                          * by the function as len-skip i.e. to sum over the IP
  960                          * payload (TCP header + data) bytes, it is INCORRECT
  961                          * to call the function like this:
  962                          * in_cksum_skip(at, ip->ip_len - offset, offset)
  963                          * Rather, it should be called like this:
  964                          * in_cksum_skip(at, ip->ip_len, offset)
  965                          * which means read "ip->ip_len - offset" bytes from
  966                          * the mbuf cluster "at" at offset "offset" bytes from
  967                          * the beginning of the "at" mbuf's data pointer.
  968                          */
  969                         th->th_sum = in_cksum_skip(*m, ip->ip_len, ip_hl);
  970                 }
  971 
  972                 /*
  973                  * XXX: Having to calculate the checksum in software and then
  974                  * hash over all bytes is really inefficient. Would be nice to
  975                  * find a way to create the hash and checksum in the same pass
  976                  * over the bytes.
  977                  */
  978                 pn->hash = hash_pkt(*m, ip_hl);
  979         }
  980 
  981         mtx_lock(&siftr_pkt_queue_mtx);
  982         STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
  983         mtx_unlock(&siftr_pkt_queue_mtx);
  984         goto ret;
  985 
  986 inp_unlock:
  987         if (inp_locally_locked)
  988                 INP_RUNLOCK(inp);
  989 
  990 ret:
  991         /* Returning 0 ensures pfil will not discard the pkt */
  992         return (0);
  993 }
  994 
  995 
  996 #ifdef SIFTR_IPV6
  997 static int
  998 siftr_chkpkt6(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
  999     struct inpcb *inp)
 1000 {
 1001         struct pkt_node *pn;
 1002         struct ip6_hdr *ip6;
 1003         struct tcphdr *th;
 1004         struct tcpcb *tp;
 1005         struct siftr_stats *ss;
 1006         unsigned int ip6_hl;
 1007         int inp_locally_locked;
 1008 
 1009         inp_locally_locked = 0;
 1010         ss = DPCPU_PTR(ss);
 1011 
 1012         /*
 1013          * m_pullup is not required here because ip6_{input|output}
 1014          * already do the heavy lifting for us.
 1015          */
 1016 
 1017         ip6 = mtod(*m, struct ip6_hdr *);
 1018 
 1019         /*
 1020          * Only continue processing if the packet is TCP
 1021          * XXX: We should follow the next header fields
 1022          * as shown on Pg 6 RFC 2460, but right now we'll
 1023          * only check pkts that have no extension headers.
 1024          */
 1025         if (ip6->ip6_nxt != IPPROTO_TCP)
 1026                 goto ret6;
 1027 
 1028         /*
 1029          * If a kernel subsystem reinjects packets into the stack, our pfil
 1030          * hook will be called multiple times for the same packet.
 1031          * Make sure we only process unique packets.
 1032          */
 1033         if (siftr_chkreinject(*m, dir, ss))
 1034                 goto ret6;
 1035 
 1036         if (dir == PFIL_IN)
 1037                 ss->n_in++;
 1038         else
 1039                 ss->n_out++;
 1040 
 1041         ip6_hl = sizeof(struct ip6_hdr);
 1042 
 1043         /*
 1044          * Create a tcphdr struct starting at the correct offset
 1045          * in the ipv6 packet. ip->ip_hl gives the ip header length
 1046          * in 4-byte words, so multiply it to get the size in bytes.
 1047          */
 1048         th = (struct tcphdr *)((caddr_t)ip6 + ip6_hl);
 1049 
 1050         /*
 1051          * For inbound packets, the pfil hooks don't provide a pointer to the
 1052          * inpcb, so we need to find it ourselves and lock it.
 1053          */
 1054         if (!inp) {
 1055                 /* Find the corresponding inpcb for this pkt. */
 1056                 inp = siftr_findinpcb(INP_IPV6, (struct ip *)ip6, *m,
 1057                     th->th_sport, th->th_dport, dir, ss);
 1058 
 1059                 if (inp == NULL)
 1060                         goto ret6;
 1061                 else
 1062                         inp_locally_locked = 1;
 1063         }
 1064 
 1065         /* Find the TCP control block that corresponds with this packet. */
 1066         tp = intotcpcb(inp);
 1067 
 1068         /*
 1069          * If we can't find the TCP control block (happens occasionaly for a
 1070          * packet sent during the shutdown phase of a TCP connection),
 1071          * or we're in the timewait state, bail.
 1072          */
 1073         if (tp == NULL || inp->inp_flags & INP_TIMEWAIT) {
 1074                 if (dir == PFIL_IN)
 1075                         ss->nskip_in_tcpcb++;
 1076                 else
 1077                         ss->nskip_out_tcpcb++;
 1078 
 1079                 goto inp_unlock6;
 1080         }
 1081 
 1082         pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
 1083 
 1084         if (pn == NULL) {
 1085                 if (dir == PFIL_IN)
 1086                         ss->nskip_in_malloc++;
 1087                 else
 1088                         ss->nskip_out_malloc++;
 1089 
 1090                 goto inp_unlock6;
 1091         }
 1092 
 1093         siftr_siftdata(pn, inp, tp, INP_IPV6, dir, inp_locally_locked);
 1094 
 1095         /* XXX: Figure out how to generate hashes for IPv6 packets. */
 1096 
 1097         mtx_lock(&siftr_pkt_queue_mtx);
 1098         STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
 1099         mtx_unlock(&siftr_pkt_queue_mtx);
 1100         goto ret6;
 1101 
 1102 inp_unlock6:
 1103         if (inp_locally_locked)
 1104                 INP_RUNLOCK(inp);
 1105 
 1106 ret6:
 1107         /* Returning 0 ensures pfil will not discard the pkt. */
 1108         return (0);
 1109 }
 1110 #endif /* #ifdef SIFTR_IPV6 */
 1111 
 1112 
 1113 static int
 1114 siftr_pfil(int action)
 1115 {
 1116         struct pfil_head *pfh_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET);
 1117 #ifdef SIFTR_IPV6
 1118         struct pfil_head *pfh_inet6 = pfil_head_get(PFIL_TYPE_AF, AF_INET6);
 1119 #endif
 1120 
 1121         if (action == HOOK) {
 1122                 pfil_add_hook(siftr_chkpkt, NULL,
 1123                     PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet);
 1124 #ifdef SIFTR_IPV6
 1125                 pfil_add_hook(siftr_chkpkt6, NULL,
 1126                     PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet6);
 1127 #endif
 1128         } else if (action == UNHOOK) {
 1129                 pfil_remove_hook(siftr_chkpkt, NULL,
 1130                     PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet);
 1131 #ifdef SIFTR_IPV6
 1132                 pfil_remove_hook(siftr_chkpkt6, NULL,
 1133                     PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet6);
 1134 #endif
 1135         }
 1136 
 1137         return (0);
 1138 }
 1139 
 1140 
 1141 static int
 1142 siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS)
 1143 {
 1144         struct alq *new_alq;
 1145         int error;
 1146 
 1147         if (req->newptr == NULL)
 1148                 goto skip;
 1149 
 1150         /* If old filename and new filename are different. */
 1151         if (strncmp(siftr_logfile, (char *)req->newptr, PATH_MAX)) {
 1152 
 1153                 error = alq_open(&new_alq, req->newptr, curthread->td_ucred,
 1154                     SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
 1155 
 1156                 /* Bail if unable to create new alq. */
 1157                 if (error)
 1158                         return (1);
 1159 
 1160                 /*
 1161                  * If disabled, siftr_alq == NULL so we simply close
 1162                  * the alq as we've proved it can be opened.
 1163                  * If enabled, close the existing alq and switch the old
 1164                  * for the new.
 1165                  */
 1166                 if (siftr_alq == NULL)
 1167                         alq_close(new_alq);
 1168                 else {
 1169                         alq_close(siftr_alq);
 1170                         siftr_alq = new_alq;
 1171                 }
 1172         }
 1173 
 1174 skip:
 1175         return (sysctl_handle_string(oidp, arg1, arg2, req));
 1176 }
 1177 
 1178 
 1179 static int
 1180 siftr_manage_ops(uint8_t action)
 1181 {
 1182         struct siftr_stats totalss;
 1183         struct timeval tval;
 1184         struct flow_hash_node *counter, *tmp_counter;
 1185         struct sbuf *s;
 1186         int i, key_index, ret, error;
 1187         uint32_t bytes_to_write, total_skipped_pkts;
 1188         uint16_t lport, fport;
 1189         uint8_t *key, ipver;
 1190 
 1191 #ifdef SIFTR_IPV6
 1192         uint32_t laddr[4];
 1193         uint32_t faddr[4];
 1194 #else
 1195         uint8_t laddr[4];
 1196         uint8_t faddr[4];
 1197 #endif
 1198 
 1199         error = 0;
 1200         total_skipped_pkts = 0;
 1201 
 1202         /* Init an autosizing sbuf that initially holds 200 chars. */
 1203         if ((s = sbuf_new(NULL, NULL, 200, SBUF_AUTOEXTEND)) == NULL)
 1204                 return (-1);
 1205 
 1206         if (action == SIFTR_ENABLE) {
 1207                 /*
 1208                  * Create our alq
 1209                  * XXX: We should abort if alq_open fails!
 1210                  */
 1211                 alq_open(&siftr_alq, siftr_logfile, curthread->td_ucred,
 1212                     SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
 1213 
 1214                 STAILQ_INIT(&pkt_queue);
 1215 
 1216                 DPCPU_ZERO(ss);
 1217 
 1218                 siftr_exit_pkt_manager_thread = 0;
 1219 
 1220                 ret = kthread_create(&siftr_pkt_manager_thread, NULL,
 1221                     &siftr_pkt_manager_proc, RFNOWAIT, 0,
 1222                     "siftr_pkt_manager_thr");
 1223                 siftr_pkt_manager_thr = FIRST_THREAD_IN_PROC(siftr_pkt_manager_proc);
 1224 
 1225                 siftr_pfil(HOOK);
 1226 
 1227                 microtime(&tval);
 1228 
 1229                 sbuf_printf(s,
 1230                     "enable_time_secs=%jd\tenable_time_usecs=%06ld\t"
 1231                     "siftrver=%s\thz=%u\ttcp_rtt_scale=%u\tsysname=%s\t"
 1232                     "sysver=%u\tipmode=%u\n",
 1233                     (intmax_t)tval.tv_sec, tval.tv_usec, MODVERSION_STR, hz,
 1234                     TCP_RTT_SCALE, SYS_NAME, __FreeBSD_version, SIFTR_IPMODE);
 1235 
 1236                 sbuf_finish(s);
 1237                 alq_writen(siftr_alq, sbuf_data(s), sbuf_len(s), ALQ_WAITOK);
 1238 
 1239         } else if (action == SIFTR_DISABLE && siftr_pkt_manager_thr != NULL) {
 1240                 /*
 1241                  * Remove the pfil hook functions. All threads currently in
 1242                  * the hook functions are allowed to exit before siftr_pfil()
 1243                  * returns.
 1244                  */
 1245                 siftr_pfil(UNHOOK);
 1246 
 1247                 /* This will block until the pkt manager thread unlocks it. */
 1248                 mtx_lock(&siftr_pkt_mgr_mtx);
 1249 
 1250                 /* Tell the pkt manager thread that it should exit now. */
 1251                 siftr_exit_pkt_manager_thread = 1;
 1252 
 1253                 /*
 1254                  * Wake the pkt_manager thread so it realises that
 1255                  * siftr_exit_pkt_manager_thread == 1 and exits gracefully.
 1256                  * The wakeup won't be delivered until we unlock
 1257                  * siftr_pkt_mgr_mtx so this isn't racy.
 1258                  */
 1259                 wakeup(&wait_for_pkt);
 1260 
 1261                 /* Wait for the pkt_manager thread to exit. */
 1262                 mtx_sleep(siftr_pkt_manager_proc, &siftr_pkt_mgr_mtx, PWAIT,
 1263                     "thrwait", 0);
 1264                 siftr_pkt_manager_proc = NULL;
 1265                 siftr_pkt_manager_thr = NULL;
 1266                 mtx_unlock(&siftr_pkt_mgr_mtx);
 1267 
 1268                 totalss.n_in = DPCPU_VARSUM(ss, n_in);
 1269                 totalss.n_out = DPCPU_VARSUM(ss, n_out);
 1270                 totalss.nskip_in_malloc = DPCPU_VARSUM(ss, nskip_in_malloc);
 1271                 totalss.nskip_out_malloc = DPCPU_VARSUM(ss, nskip_out_malloc);
 1272                 totalss.nskip_in_mtx = DPCPU_VARSUM(ss, nskip_in_mtx);
 1273                 totalss.nskip_out_mtx = DPCPU_VARSUM(ss, nskip_out_mtx);
 1274                 totalss.nskip_in_tcpcb = DPCPU_VARSUM(ss, nskip_in_tcpcb);
 1275                 totalss.nskip_out_tcpcb = DPCPU_VARSUM(ss, nskip_out_tcpcb);
 1276                 totalss.nskip_in_inpcb = DPCPU_VARSUM(ss, nskip_in_inpcb);
 1277                 totalss.nskip_out_inpcb = DPCPU_VARSUM(ss, nskip_out_inpcb);
 1278 
 1279                 total_skipped_pkts = totalss.nskip_in_malloc +
 1280                     totalss.nskip_out_malloc + totalss.nskip_in_mtx +
 1281                     totalss.nskip_out_mtx + totalss.nskip_in_tcpcb +
 1282                     totalss.nskip_out_tcpcb + totalss.nskip_in_inpcb +
 1283                     totalss.nskip_out_inpcb;
 1284 
 1285                 microtime(&tval);
 1286 
 1287                 sbuf_printf(s,
 1288                     "disable_time_secs=%jd\tdisable_time_usecs=%06ld\t"
 1289                     "num_inbound_tcp_pkts=%ju\tnum_outbound_tcp_pkts=%ju\t"
 1290                     "total_tcp_pkts=%ju\tnum_inbound_skipped_pkts_malloc=%u\t"
 1291                     "num_outbound_skipped_pkts_malloc=%u\t"
 1292                     "num_inbound_skipped_pkts_mtx=%u\t"
 1293                     "num_outbound_skipped_pkts_mtx=%u\t"
 1294                     "num_inbound_skipped_pkts_tcpcb=%u\t"
 1295                     "num_outbound_skipped_pkts_tcpcb=%u\t"
 1296                     "num_inbound_skipped_pkts_inpcb=%u\t"
 1297                     "num_outbound_skipped_pkts_inpcb=%u\t"
 1298                     "total_skipped_tcp_pkts=%u\tflow_list=",
 1299                     (intmax_t)tval.tv_sec,
 1300                     tval.tv_usec,
 1301                     (uintmax_t)totalss.n_in,
 1302                     (uintmax_t)totalss.n_out,
 1303                     (uintmax_t)(totalss.n_in + totalss.n_out),
 1304                     totalss.nskip_in_malloc,
 1305                     totalss.nskip_out_malloc,
 1306                     totalss.nskip_in_mtx,
 1307                     totalss.nskip_out_mtx,
 1308                     totalss.nskip_in_tcpcb,
 1309                     totalss.nskip_out_tcpcb,
 1310                     totalss.nskip_in_inpcb,
 1311                     totalss.nskip_out_inpcb,
 1312                     total_skipped_pkts);
 1313 
 1314                 /*
 1315                  * Iterate over the flow hash, printing a summary of each
 1316                  * flow seen and freeing any malloc'd memory.
 1317                  * The hash consists of an array of LISTs (man 3 queue).
 1318                  */
 1319                 for (i = 0; i < siftr_hashmask; i++) {
 1320                         LIST_FOREACH_SAFE(counter, counter_hash + i, nodes,
 1321                             tmp_counter) {
 1322                                 key = counter->key;
 1323                                 key_index = 1;
 1324 
 1325                                 ipver = key[0];
 1326 
 1327                                 memcpy(laddr, key + key_index, sizeof(laddr));
 1328                                 key_index += sizeof(laddr);
 1329                                 memcpy(&lport, key + key_index, sizeof(lport));
 1330                                 key_index += sizeof(lport);
 1331                                 memcpy(faddr, key + key_index, sizeof(faddr));
 1332                                 key_index += sizeof(faddr);
 1333                                 memcpy(&fport, key + key_index, sizeof(fport));
 1334 
 1335 #ifdef SIFTR_IPV6
 1336                                 laddr[3] = ntohl(laddr[3]);
 1337                                 faddr[3] = ntohl(faddr[3]);
 1338 
 1339                                 if (ipver == INP_IPV6) {
 1340                                         laddr[0] = ntohl(laddr[0]);
 1341                                         laddr[1] = ntohl(laddr[1]);
 1342                                         laddr[2] = ntohl(laddr[2]);
 1343                                         faddr[0] = ntohl(faddr[0]);
 1344                                         faddr[1] = ntohl(faddr[1]);
 1345                                         faddr[2] = ntohl(faddr[2]);
 1346 
 1347                                         sbuf_printf(s,
 1348                                             "%x:%x:%x:%x:%x:%x:%x:%x;%u-"
 1349                                             "%x:%x:%x:%x:%x:%x:%x:%x;%u,",
 1350                                             UPPER_SHORT(laddr[0]),
 1351                                             LOWER_SHORT(laddr[0]),
 1352                                             UPPER_SHORT(laddr[1]),
 1353                                             LOWER_SHORT(laddr[1]),
 1354                                             UPPER_SHORT(laddr[2]),
 1355                                             LOWER_SHORT(laddr[2]),
 1356                                             UPPER_SHORT(laddr[3]),
 1357                                             LOWER_SHORT(laddr[3]),
 1358                                             ntohs(lport),
 1359                                             UPPER_SHORT(faddr[0]),
 1360                                             LOWER_SHORT(faddr[0]),
 1361                                             UPPER_SHORT(faddr[1]),
 1362                                             LOWER_SHORT(faddr[1]),
 1363                                             UPPER_SHORT(faddr[2]),
 1364                                             LOWER_SHORT(faddr[2]),
 1365                                             UPPER_SHORT(faddr[3]),
 1366                                             LOWER_SHORT(faddr[3]),
 1367                                             ntohs(fport));
 1368                                 } else {
 1369                                         laddr[0] = FIRST_OCTET(laddr[3]);
 1370                                         laddr[1] = SECOND_OCTET(laddr[3]);
 1371                                         laddr[2] = THIRD_OCTET(laddr[3]);
 1372                                         laddr[3] = FOURTH_OCTET(laddr[3]);
 1373                                         faddr[0] = FIRST_OCTET(faddr[3]);
 1374                                         faddr[1] = SECOND_OCTET(faddr[3]);
 1375                                         faddr[2] = THIRD_OCTET(faddr[3]);
 1376                                         faddr[3] = FOURTH_OCTET(faddr[3]);
 1377 #endif
 1378                                         sbuf_printf(s,
 1379                                             "%u.%u.%u.%u;%u-%u.%u.%u.%u;%u,",
 1380                                             laddr[0],
 1381                                             laddr[1],
 1382                                             laddr[2],
 1383                                             laddr[3],
 1384                                             ntohs(lport),
 1385                                             faddr[0],
 1386                                             faddr[1],
 1387                                             faddr[2],
 1388                                             faddr[3],
 1389                                             ntohs(fport));
 1390 #ifdef SIFTR_IPV6
 1391                                 }
 1392 #endif
 1393 
 1394                                 free(counter, M_SIFTR_HASHNODE);
 1395                         }
 1396 
 1397                         LIST_INIT(counter_hash + i);
 1398                 }
 1399 
 1400                 sbuf_printf(s, "\n");
 1401                 sbuf_finish(s);
 1402 
 1403                 i = 0;
 1404                 do {
 1405                         bytes_to_write = min(SIFTR_ALQ_BUFLEN, sbuf_len(s)-i);
 1406                         alq_writen(siftr_alq, sbuf_data(s)+i, bytes_to_write, ALQ_WAITOK);
 1407                         i += bytes_to_write;
 1408                 } while (i < sbuf_len(s));
 1409 
 1410                 alq_close(siftr_alq);
 1411                 siftr_alq = NULL;
 1412         }
 1413 
 1414         sbuf_delete(s);
 1415 
 1416         /*
 1417          * XXX: Should be using ret to check if any functions fail
 1418          * and set error appropriately
 1419          */
 1420 
 1421         return (error);
 1422 }
 1423 
 1424 
 1425 static int
 1426 siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS)
 1427 {
 1428         if (req->newptr == NULL)
 1429                 goto skip;
 1430 
 1431         /* If the value passed in isn't 0 or 1, return an error. */
 1432         if (CAST_PTR_INT(req->newptr) != 0 && CAST_PTR_INT(req->newptr) != 1)
 1433                 return (1);
 1434 
 1435         /* If we are changing state (0 to 1 or 1 to 0). */
 1436         if (CAST_PTR_INT(req->newptr) != siftr_enabled )
 1437                 if (siftr_manage_ops(CAST_PTR_INT(req->newptr))) {
 1438                         siftr_manage_ops(SIFTR_DISABLE);
 1439                         return (1);
 1440                 }
 1441 
 1442 skip:
 1443         return (sysctl_handle_int(oidp, arg1, arg2, req));
 1444 }
 1445 
 1446 
 1447 static void
 1448 siftr_shutdown_handler(void *arg)
 1449 {
 1450         siftr_manage_ops(SIFTR_DISABLE);
 1451 }
 1452 
 1453 
 1454 /*
 1455  * Module is being unloaded or machine is shutting down. Take care of cleanup.
 1456  */
 1457 static int
 1458 deinit_siftr(void)
 1459 {
 1460         /* Cleanup. */
 1461         siftr_manage_ops(SIFTR_DISABLE);
 1462         hashdestroy(counter_hash, M_SIFTR, siftr_hashmask);
 1463         mtx_destroy(&siftr_pkt_queue_mtx);
 1464         mtx_destroy(&siftr_pkt_mgr_mtx);
 1465 
 1466         return (0);
 1467 }
 1468 
 1469 
 1470 /*
 1471  * Module has just been loaded into the kernel.
 1472  */
 1473 static int
 1474 init_siftr(void)
 1475 {
 1476         EVENTHANDLER_REGISTER(shutdown_pre_sync, siftr_shutdown_handler, NULL,
 1477             SHUTDOWN_PRI_FIRST);
 1478 
 1479         /* Initialise our flow counter hash table. */
 1480         counter_hash = hashinit(SIFTR_EXPECTED_MAX_TCP_FLOWS, M_SIFTR,
 1481             &siftr_hashmask);
 1482 
 1483         mtx_init(&siftr_pkt_queue_mtx, "siftr_pkt_queue_mtx", NULL, MTX_DEF);
 1484         mtx_init(&siftr_pkt_mgr_mtx, "siftr_pkt_mgr_mtx", NULL, MTX_DEF);
 1485 
 1486         /* Print message to the user's current terminal. */
 1487         uprintf("\nStatistical Information For TCP Research (SIFTR) %s\n"
 1488             "          http://caia.swin.edu.au/urp/newtcp\n\n",
 1489             MODVERSION_STR);
 1490 
 1491         return (0);
 1492 }
 1493 
 1494 
 1495 /*
 1496  * This is the function that is called to load and unload the module.
 1497  * When the module is loaded, this function is called once with
 1498  * "what" == MOD_LOAD
 1499  * When the module is unloaded, this function is called twice with
 1500  * "what" = MOD_QUIESCE first, followed by "what" = MOD_UNLOAD second
 1501  * When the system is shut down e.g. CTRL-ALT-DEL or using the shutdown command,
 1502  * this function is called once with "what" = MOD_SHUTDOWN
 1503  * When the system is shut down, the handler isn't called until the very end
 1504  * of the shutdown sequence i.e. after the disks have been synced.
 1505  */
 1506 static int
 1507 siftr_load_handler(module_t mod, int what, void *arg)
 1508 {
 1509         int ret;
 1510 
 1511         switch (what) {
 1512         case MOD_LOAD:
 1513                 ret = init_siftr();
 1514                 break;
 1515 
 1516         case MOD_QUIESCE:
 1517         case MOD_SHUTDOWN:
 1518                 ret = deinit_siftr();
 1519                 break;
 1520 
 1521         case MOD_UNLOAD:
 1522                 ret = 0;
 1523                 break;
 1524 
 1525         default:
 1526                 ret = EINVAL;
 1527                 break;
 1528         }
 1529 
 1530         return (ret);
 1531 }
 1532 
 1533 
 1534 static moduledata_t siftr_mod = {
 1535         .name = "siftr",
 1536         .evhand = siftr_load_handler,
 1537 };
 1538 
 1539 /*
 1540  * Param 1: name of the kernel module
 1541  * Param 2: moduledata_t struct containing info about the kernel module
 1542  *          and the execution entry point for the module
 1543  * Param 3: From sysinit_sub_id enumeration in /usr/include/sys/kernel.h
 1544  *          Defines the module initialisation order
 1545  * Param 4: From sysinit_elem_order enumeration in /usr/include/sys/kernel.h
 1546  *          Defines the initialisation order of this kld relative to others
 1547  *          within the same subsystem as defined by param 3
 1548  */
 1549 DECLARE_MODULE(siftr, siftr_mod, SI_SUB_SMP, SI_ORDER_ANY);
 1550 MODULE_DEPEND(siftr, alq, 1, 1, 1);
 1551 MODULE_VERSION(siftr, MODVERSION);

Cache object: c61359a0bf0ae67e545657bcd189b212


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