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