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