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