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