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