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