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

Cache object: ed8055902ce98b7423bd02c278677bb7


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