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