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