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