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