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