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

Cache object: 77ee1cbecabe3fadd1296f9d78852b56


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