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