xref: /freebsd/sys/netinet/siftr.c (revision d29a9a615c530b50b7f8d5feaa5175f952d8e8e2)
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 	}
383 
384 	log_buf = alq_getn(siftr_alq, MAX_LOG_MSG_LEN, ALQ_WAITOK);
385 
386 	if (log_buf == NULL)
387 		return; /* Should only happen if the ALQ is shutting down. */
388 
389 	/* Construct a log message. */
390 	log_buf->ae_bytesused = snprintf(log_buf->ae_data, MAX_LOG_MSG_LEN,
391 	    "%c,%jd.%06ld,%s,%hu,%s,%hu,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,"
392 	    "%u,%u,%u,%u,%u,%u,%u,%u\n",
393 	    direction[pkt_node->direction],
394 	    pkt_node->tval.tv_sec,
395 	    pkt_node->tval.tv_usec,
396 	    hash_node->const_info.laddr,
397 	    hash_node->const_info.lport,
398 	    hash_node->const_info.faddr,
399 	    hash_node->const_info.fport,
400 	    pkt_node->snd_ssthresh,
401 	    pkt_node->snd_cwnd,
402 	    pkt_node->t_flags2,
403 	    pkt_node->snd_wnd,
404 	    pkt_node->rcv_wnd,
405 	    pkt_node->snd_scale,
406 	    pkt_node->rcv_scale,
407 	    pkt_node->conn_state,
408 	    pkt_node->max_seg_size,
409 	    pkt_node->srtt,
410 	    pkt_node->sack_enabled,
411 	    pkt_node->flags,
412 	    pkt_node->rto,
413 	    pkt_node->snd_buf_hiwater,
414 	    pkt_node->snd_buf_cc,
415 	    pkt_node->rcv_buf_hiwater,
416 	    pkt_node->rcv_buf_cc,
417 	    pkt_node->sent_inflight_bytes,
418 	    pkt_node->t_segqlen,
419 	    pkt_node->flowid,
420 	    pkt_node->flowtype);
421 
422 	alq_post_flags(siftr_alq, log_buf, 0);
423 }
424 
425 static void
426 siftr_pkt_manager_thread(void *arg)
427 {
428 	STAILQ_HEAD(pkthead, pkt_node) tmp_pkt_queue =
429 	    STAILQ_HEAD_INITIALIZER(tmp_pkt_queue);
430 	struct pkt_node *pkt_node, *pkt_node_temp;
431 	uint8_t draining;
432 
433 	draining = 2;
434 
435 	mtx_lock(&siftr_pkt_mgr_mtx);
436 
437 	/* draining == 0 when queue has been flushed and it's safe to exit. */
438 	while (draining) {
439 		/*
440 		 * Sleep until we are signalled to wake because thread has
441 		 * been told to exit or until 1 tick has passed.
442 		 */
443 		mtx_sleep(&wait_for_pkt, &siftr_pkt_mgr_mtx, PWAIT, "pktwait",
444 		    1);
445 
446 		/* Gain exclusive access to the pkt_node queue. */
447 		mtx_lock(&siftr_pkt_queue_mtx);
448 
449 		/*
450 		 * Move pkt_queue to tmp_pkt_queue, which leaves
451 		 * pkt_queue empty and ready to receive more pkt_nodes.
452 		 */
453 		STAILQ_CONCAT(&tmp_pkt_queue, &pkt_queue);
454 
455 		/*
456 		 * We've finished making changes to the list. Unlock it
457 		 * so the pfil hooks can continue queuing pkt_nodes.
458 		 */
459 		mtx_unlock(&siftr_pkt_queue_mtx);
460 
461 		/*
462 		 * We can't hold a mutex whilst calling siftr_process_pkt
463 		 * because ALQ might sleep waiting for buffer space.
464 		 */
465 		mtx_unlock(&siftr_pkt_mgr_mtx);
466 
467 		/* Flush all pkt_nodes to the log file. */
468 		STAILQ_FOREACH_SAFE(pkt_node, &tmp_pkt_queue, nodes,
469 		    pkt_node_temp) {
470 			siftr_process_pkt(pkt_node);
471 			STAILQ_REMOVE_HEAD(&tmp_pkt_queue, nodes);
472 			free(pkt_node, M_SIFTR_PKTNODE);
473 		}
474 
475 		KASSERT(STAILQ_EMPTY(&tmp_pkt_queue),
476 		    ("SIFTR tmp_pkt_queue not empty after flush"));
477 
478 		mtx_lock(&siftr_pkt_mgr_mtx);
479 
480 		/*
481 		 * If siftr_exit_pkt_manager_thread gets set during the window
482 		 * where we are draining the tmp_pkt_queue above, there might
483 		 * still be pkts in pkt_queue that need to be drained.
484 		 * Allow one further iteration to occur after
485 		 * siftr_exit_pkt_manager_thread has been set to ensure
486 		 * pkt_queue is completely empty before we kill the thread.
487 		 *
488 		 * siftr_exit_pkt_manager_thread is set only after the pfil
489 		 * hooks have been removed, so only 1 extra iteration
490 		 * is needed to drain the queue.
491 		 */
492 		if (siftr_exit_pkt_manager_thread)
493 			draining--;
494 	}
495 
496 	mtx_unlock(&siftr_pkt_mgr_mtx);
497 
498 	/* Calls wakeup on this thread's struct thread ptr. */
499 	kthread_exit();
500 }
501 
502 /*
503  * Check if a given mbuf has the SIFTR mbuf tag. If it does, log the fact that
504  * it's a reinjected packet and return. If it doesn't, tag the mbuf and return.
505  * Return value >0 means the caller should skip processing this mbuf.
506  */
507 static inline int
508 siftr_chkreinject(struct mbuf *m, int dir, struct siftr_stats *ss)
509 {
510 	if (m_tag_locate(m, PACKET_COOKIE_SIFTR, PACKET_TAG_SIFTR, NULL)
511 	    != NULL) {
512 		if (dir == PFIL_IN)
513 			ss->nskip_in_dejavu++;
514 		else
515 			ss->nskip_out_dejavu++;
516 
517 		return (1);
518 	} else {
519 		struct m_tag *tag = m_tag_alloc(PACKET_COOKIE_SIFTR,
520 		    PACKET_TAG_SIFTR, 0, M_NOWAIT);
521 		if (tag == NULL) {
522 			if (dir == PFIL_IN)
523 				ss->nskip_in_malloc++;
524 			else
525 				ss->nskip_out_malloc++;
526 
527 			return (1);
528 		}
529 
530 		m_tag_prepend(m, tag);
531 	}
532 
533 	return (0);
534 }
535 
536 /*
537  * Look up an inpcb for a packet. Return the inpcb pointer if found, or NULL
538  * otherwise.
539  */
540 static inline struct inpcb *
541 siftr_findinpcb(int ipver, struct ip *ip, struct mbuf *m, uint16_t sport,
542     uint16_t dport, int dir, struct siftr_stats *ss)
543 {
544 	struct inpcb *inp;
545 
546 	/* We need the tcbinfo lock. */
547 	INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
548 
549 	if (dir == PFIL_IN)
550 		inp = (ipver == INP_IPV4 ?
551 		    in_pcblookup(&V_tcbinfo, ip->ip_src, sport, ip->ip_dst,
552 		    dport, INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif)
553 		    :
554 #ifdef SIFTR_IPV6
555 		    in6_pcblookup(&V_tcbinfo,
556 		    &((struct ip6_hdr *)ip)->ip6_src, sport,
557 		    &((struct ip6_hdr *)ip)->ip6_dst, dport, INPLOOKUP_RLOCKPCB,
558 		    m->m_pkthdr.rcvif)
559 #else
560 		    NULL
561 #endif
562 		    );
563 
564 	else
565 		inp = (ipver == INP_IPV4 ?
566 		    in_pcblookup(&V_tcbinfo, ip->ip_dst, dport, ip->ip_src,
567 		    sport, INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif)
568 		    :
569 #ifdef SIFTR_IPV6
570 		    in6_pcblookup(&V_tcbinfo,
571 		    &((struct ip6_hdr *)ip)->ip6_dst, dport,
572 		    &((struct ip6_hdr *)ip)->ip6_src, sport, INPLOOKUP_RLOCKPCB,
573 		    m->m_pkthdr.rcvif)
574 #else
575 		    NULL
576 #endif
577 		    );
578 
579 	/* If we can't find the inpcb, bail. */
580 	if (inp == NULL) {
581 		if (dir == PFIL_IN)
582 			ss->nskip_in_inpcb++;
583 		else
584 			ss->nskip_out_inpcb++;
585 	}
586 
587 	return (inp);
588 }
589 
590 static inline uint32_t
591 siftr_get_flowid(struct inpcb *inp, int ipver, uint32_t *phashtype)
592 {
593 	if (inp->inp_flowid == 0) {
594 #ifdef SIFTR_IPV6
595 		if (ipver == INP_IPV6) {
596 			return fib6_calc_packet_hash(&inp->in6p_laddr,
597 						     &inp->in6p_faddr,
598 						     inp->inp_lport,
599 						     inp->inp_fport,
600 						     IPPROTO_TCP,
601 						     phashtype);
602 		} else
603 #endif
604 		{
605 			return fib4_calc_packet_hash(inp->inp_laddr,
606 						     inp->inp_faddr,
607 						     inp->inp_lport,
608 						     inp->inp_fport,
609 						     IPPROTO_TCP,
610 						     phashtype);
611 		}
612 	} else {
613 		*phashtype = inp->inp_flowtype;
614 		return inp->inp_flowid;
615 	}
616 }
617 
618 static inline void
619 siftr_siftdata(struct pkt_node *pn, struct inpcb *inp, struct tcpcb *tp,
620     int ipver, int dir, int inp_locally_locked)
621 {
622 	pn->snd_cwnd = tp->snd_cwnd;
623 	pn->snd_wnd = tp->snd_wnd;
624 	pn->rcv_wnd = tp->rcv_wnd;
625 	pn->t_flags2 = tp->t_flags2;
626 	pn->snd_ssthresh = tp->snd_ssthresh;
627 	pn->snd_scale = tp->snd_scale;
628 	pn->rcv_scale = tp->rcv_scale;
629 	pn->conn_state = tp->t_state;
630 	pn->max_seg_size = tp->t_maxseg;
631 	pn->srtt = ((uint64_t)tp->t_srtt * tick) >> TCP_RTT_SHIFT;
632 	pn->sack_enabled = (tp->t_flags & TF_SACK_PERMIT) != 0;
633 	pn->flags = tp->t_flags;
634 	pn->rto = tp->t_rxtcur * tick;
635 	pn->snd_buf_hiwater = inp->inp_socket->so_snd.sb_hiwat;
636 	pn->snd_buf_cc = sbused(&inp->inp_socket->so_snd);
637 	pn->rcv_buf_hiwater = inp->inp_socket->so_rcv.sb_hiwat;
638 	pn->rcv_buf_cc = sbused(&inp->inp_socket->so_rcv);
639 	pn->sent_inflight_bytes = tp->snd_max - tp->snd_una;
640 	pn->t_segqlen = tp->t_segqlen;
641 
642 	/* We've finished accessing the tcb so release the lock. */
643 	if (inp_locally_locked)
644 		INP_RUNLOCK(inp);
645 
646 	pn->direction = (dir == PFIL_IN ? DIR_IN : DIR_OUT);
647 
648 	/*
649 	 * Significantly more accurate than using getmicrotime(), but slower!
650 	 * Gives true microsecond resolution at the expense of a hit to
651 	 * maximum pps throughput processing when SIFTR is loaded and enabled.
652 	 */
653 	microtime(&pn->tval);
654 	TCP_PROBE1(siftr, &pn);
655 }
656 
657 /*
658  * pfil hook that is called for each IPv4 packet making its way through the
659  * stack in either direction.
660  * The pfil subsystem holds a non-sleepable mutex somewhere when
661  * calling our hook function, so we can't sleep at all.
662  * It's very important to use the M_NOWAIT flag with all function calls
663  * that support it so that they won't sleep, otherwise you get a panic.
664  */
665 static pfil_return_t
666 siftr_chkpkt(struct mbuf **m, struct ifnet *ifp, int flags,
667     void *ruleset __unused, struct inpcb *inp)
668 {
669 	struct pkt_node *pn;
670 	struct ip *ip;
671 	struct tcphdr *th;
672 	struct tcpcb *tp;
673 	struct siftr_stats *ss;
674 	unsigned int ip_hl;
675 	int inp_locally_locked, dir;
676 	uint32_t hash_id, hash_type;
677 	struct listhead *counter_list;
678 	struct flow_hash_node *hash_node;
679 
680 	inp_locally_locked = 0;
681 	dir = PFIL_DIR(flags);
682 	ss = DPCPU_PTR(ss);
683 
684 	/*
685 	 * m_pullup is not required here because ip_{input|output}
686 	 * already do the heavy lifting for us.
687 	 */
688 
689 	ip = mtod(*m, struct ip *);
690 
691 	/* Only continue processing if the packet is TCP. */
692 	if (ip->ip_p != IPPROTO_TCP)
693 		goto ret;
694 
695 	/*
696 	 * Create a tcphdr struct starting at the correct offset
697 	 * in the IP packet. ip->ip_hl gives the ip header length
698 	 * in 4-byte words, so multiply it to get the size in bytes.
699 	 */
700 	ip_hl = (ip->ip_hl << 2);
701 	th = (struct tcphdr *)((caddr_t)ip + ip_hl);
702 
703 	/*
704 	 * Only pkts selected by the tcp port filter
705 	 * can be inserted into the pkt_queue
706 	 */
707 	if ((siftr_port_filter != 0) &&
708 	    (siftr_port_filter != ntohs(th->th_sport)) &&
709 	    (siftr_port_filter != ntohs(th->th_dport))) {
710 		goto ret;
711 	}
712 
713 	/*
714 	 * If a kernel subsystem reinjects packets into the stack, our pfil
715 	 * hook will be called multiple times for the same packet.
716 	 * Make sure we only process unique packets.
717 	 */
718 	if (siftr_chkreinject(*m, dir, ss))
719 		goto ret;
720 
721 	if (dir == PFIL_IN)
722 		ss->n_in++;
723 	else
724 		ss->n_out++;
725 
726 	/*
727 	 * If the pfil hooks don't provide a pointer to the
728 	 * inpcb, we need to find it ourselves and lock it.
729 	 */
730 	if (!inp) {
731 		/* Find the corresponding inpcb for this pkt. */
732 		inp = siftr_findinpcb(INP_IPV4, ip, *m, th->th_sport,
733 		    th->th_dport, dir, ss);
734 
735 		if (inp == NULL)
736 			goto ret;
737 		else
738 			inp_locally_locked = 1;
739 	}
740 
741 	INP_LOCK_ASSERT(inp);
742 
743 	/* Find the TCP control block that corresponds with this packet */
744 	tp = intotcpcb(inp);
745 
746 	/*
747 	 * If we can't find the TCP control block (happens occasionaly for a
748 	 * packet sent during the shutdown phase of a TCP connection), or the
749 	 * TCP control block has not initialized (happens during TCPS_SYN_SENT),
750 	 * bail.
751 	 */
752 	if (tp == NULL || tp->t_state < TCPS_ESTABLISHED) {
753 		if (dir == PFIL_IN)
754 			ss->nskip_in_tcpcb++;
755 		else
756 			ss->nskip_out_tcpcb++;
757 
758 		goto inp_unlock;
759 	}
760 
761 	hash_id = siftr_get_flowid(inp, INP_IPV4, &hash_type);
762 	counter_list = counter_hash + (hash_id & siftr_hashmask);
763 	hash_node = siftr_find_flow(counter_list, hash_id);
764 
765 	/* If this flow hasn't been seen before, we create a new entry. */
766 	if (hash_node == NULL) {
767 		struct flow_info info;
768 
769 		inet_ntoa_r(inp->inp_laddr, info.laddr);
770 		inet_ntoa_r(inp->inp_faddr, info.faddr);
771 		info.lport = ntohs(inp->inp_lport);
772 		info.fport = ntohs(inp->inp_fport);
773 		info.key = hash_id;
774 		info.ipver = INP_IPV4;
775 
776 		hash_node = siftr_new_hash_node(info, dir, ss);
777 	}
778 
779 	if (hash_node == NULL) {
780 		goto inp_unlock;
781 	}
782 
783 	pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
784 
785 	if (pn == NULL) {
786 		if (dir == PFIL_IN)
787 			ss->nskip_in_malloc++;
788 		else
789 			ss->nskip_out_malloc++;
790 
791 		goto inp_unlock;
792 	}
793 
794 	pn->flowid = hash_id;
795 	pn->flowtype = hash_type;
796 
797 	siftr_siftdata(pn, inp, tp, INP_IPV4, dir, inp_locally_locked);
798 
799 	mtx_lock(&siftr_pkt_queue_mtx);
800 	STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
801 	mtx_unlock(&siftr_pkt_queue_mtx);
802 	goto ret;
803 
804 inp_unlock:
805 	if (inp_locally_locked)
806 		INP_RUNLOCK(inp);
807 
808 ret:
809 	return (PFIL_PASS);
810 }
811 
812 #ifdef SIFTR_IPV6
813 static pfil_return_t
814 siftr_chkpkt6(struct mbuf **m, struct ifnet *ifp, int flags,
815     void *ruleset __unused, struct inpcb *inp)
816 {
817 	struct pkt_node *pn;
818 	struct ip6_hdr *ip6;
819 	struct tcphdr *th;
820 	struct tcpcb *tp;
821 	struct siftr_stats *ss;
822 	unsigned int ip6_hl;
823 	int inp_locally_locked, dir;
824 	uint32_t hash_id, hash_type;
825 	struct listhead *counter_list;
826 	struct flow_hash_node *hash_node;
827 
828 	inp_locally_locked = 0;
829 	dir = PFIL_DIR(flags);
830 	ss = DPCPU_PTR(ss);
831 
832 	/*
833 	 * m_pullup is not required here because ip6_{input|output}
834 	 * already do the heavy lifting for us.
835 	 */
836 
837 	ip6 = mtod(*m, struct ip6_hdr *);
838 
839 	/*
840 	 * Only continue processing if the packet is TCP
841 	 * XXX: We should follow the next header fields
842 	 * as shown on Pg 6 RFC 2460, but right now we'll
843 	 * only check pkts that have no extension headers.
844 	 */
845 	if (ip6->ip6_nxt != IPPROTO_TCP)
846 		goto ret6;
847 
848 	/*
849 	 * Create a tcphdr struct starting at the correct offset
850 	 * in the ipv6 packet.
851 	 */
852 	ip6_hl = sizeof(struct ip6_hdr);
853 	th = (struct tcphdr *)((caddr_t)ip6 + ip6_hl);
854 
855 	/*
856 	 * Only pkts selected by the tcp port filter
857 	 * can be inserted into the pkt_queue
858 	 */
859 	if ((siftr_port_filter != 0) &&
860 	    (siftr_port_filter != ntohs(th->th_sport)) &&
861 	    (siftr_port_filter != ntohs(th->th_dport))) {
862 		goto ret6;
863 	}
864 
865 	/*
866 	 * If a kernel subsystem reinjects packets into the stack, our pfil
867 	 * hook will be called multiple times for the same packet.
868 	 * Make sure we only process unique packets.
869 	 */
870 	if (siftr_chkreinject(*m, dir, ss))
871 		goto ret6;
872 
873 	if (dir == PFIL_IN)
874 		ss->n_in++;
875 	else
876 		ss->n_out++;
877 
878 	/*
879 	 * For inbound packets, the pfil hooks don't provide a pointer to the
880 	 * inpcb, so we need to find it ourselves and lock it.
881 	 */
882 	if (!inp) {
883 		/* Find the corresponding inpcb for this pkt. */
884 		inp = siftr_findinpcb(INP_IPV6, (struct ip *)ip6, *m,
885 		    th->th_sport, th->th_dport, dir, ss);
886 
887 		if (inp == NULL)
888 			goto ret6;
889 		else
890 			inp_locally_locked = 1;
891 	}
892 
893 	/* Find the TCP control block that corresponds with this packet. */
894 	tp = intotcpcb(inp);
895 
896 	/*
897 	 * If we can't find the TCP control block (happens occasionaly for a
898 	 * packet sent during the shutdown phase of a TCP connection), or the
899 	 * TCP control block has not initialized (happens during TCPS_SYN_SENT),
900 	 * bail.
901 	 */
902 	if (tp == NULL || tp->t_state < TCPS_ESTABLISHED) {
903 		if (dir == PFIL_IN)
904 			ss->nskip_in_tcpcb++;
905 		else
906 			ss->nskip_out_tcpcb++;
907 
908 		goto inp_unlock6;
909 	}
910 
911 	hash_id = siftr_get_flowid(inp, INP_IPV6, &hash_type);
912 	counter_list = counter_hash + (hash_id & siftr_hashmask);
913 	hash_node = siftr_find_flow(counter_list, hash_id);
914 
915 	/* If this flow hasn't been seen before, we create a new entry. */
916 	if (!hash_node) {
917 		struct flow_info info;
918 
919 		ip6_sprintf(info.laddr, &inp->in6p_laddr);
920 		ip6_sprintf(info.faddr, &inp->in6p_faddr);
921 		info.lport = ntohs(inp->inp_lport);
922 		info.fport = ntohs(inp->inp_fport);
923 		info.key = hash_id;
924 		info.ipver = INP_IPV6;
925 
926 		hash_node = siftr_new_hash_node(info, dir, ss);
927 	}
928 
929 	if (!hash_node) {
930 		goto inp_unlock6;
931 	}
932 
933 	pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
934 
935 	if (pn == NULL) {
936 		if (dir == PFIL_IN)
937 			ss->nskip_in_malloc++;
938 		else
939 			ss->nskip_out_malloc++;
940 
941 		goto inp_unlock6;
942 	}
943 
944 	pn->flowid = hash_id;
945 	pn->flowtype = hash_type;
946 
947 	siftr_siftdata(pn, inp, tp, INP_IPV6, dir, inp_locally_locked);
948 
949 	/* XXX: Figure out how to generate hashes for IPv6 packets. */
950 
951 	mtx_lock(&siftr_pkt_queue_mtx);
952 	STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
953 	mtx_unlock(&siftr_pkt_queue_mtx);
954 	goto ret6;
955 
956 inp_unlock6:
957 	if (inp_locally_locked)
958 		INP_RUNLOCK(inp);
959 
960 ret6:
961 	return (PFIL_PASS);
962 }
963 #endif /* #ifdef SIFTR_IPV6 */
964 
965 VNET_DEFINE_STATIC(pfil_hook_t, siftr_inet_hook);
966 #define	V_siftr_inet_hook	VNET(siftr_inet_hook)
967 #ifdef SIFTR_IPV6
968 VNET_DEFINE_STATIC(pfil_hook_t, siftr_inet6_hook);
969 #define	V_siftr_inet6_hook	VNET(siftr_inet6_hook)
970 #endif
971 static int
972 siftr_pfil(int action)
973 {
974 	struct pfil_hook_args pha = {
975 		.pa_version = PFIL_VERSION,
976 		.pa_flags = PFIL_IN | PFIL_OUT,
977 		.pa_modname = "siftr",
978 		.pa_rulname = "default",
979 	};
980 	struct pfil_link_args pla = {
981 		.pa_version = PFIL_VERSION,
982 		.pa_flags = PFIL_IN | PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR,
983 	};
984 
985 	VNET_ITERATOR_DECL(vnet_iter);
986 
987 	VNET_LIST_RLOCK();
988 	VNET_FOREACH(vnet_iter) {
989 		CURVNET_SET(vnet_iter);
990 
991 		if (action == HOOK) {
992 			pha.pa_mbuf_chk = siftr_chkpkt;
993 			pha.pa_type = PFIL_TYPE_IP4;
994 			V_siftr_inet_hook = pfil_add_hook(&pha);
995 			pla.pa_hook = V_siftr_inet_hook;
996 			pla.pa_head = V_inet_pfil_head;
997 			(void)pfil_link(&pla);
998 #ifdef SIFTR_IPV6
999 			pha.pa_mbuf_chk = siftr_chkpkt6;
1000 			pha.pa_type = PFIL_TYPE_IP6;
1001 			V_siftr_inet6_hook = pfil_add_hook(&pha);
1002 			pla.pa_hook = V_siftr_inet6_hook;
1003 			pla.pa_head = V_inet6_pfil_head;
1004 			(void)pfil_link(&pla);
1005 #endif
1006 		} else if (action == UNHOOK) {
1007 			pfil_remove_hook(V_siftr_inet_hook);
1008 #ifdef SIFTR_IPV6
1009 			pfil_remove_hook(V_siftr_inet6_hook);
1010 #endif
1011 		}
1012 		CURVNET_RESTORE();
1013 	}
1014 	VNET_LIST_RUNLOCK();
1015 
1016 	return (0);
1017 }
1018 
1019 static int
1020 siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS)
1021 {
1022 	struct alq *new_alq;
1023 	int error;
1024 
1025 	error = sysctl_handle_string(oidp, arg1, arg2, req);
1026 
1027 	/* Check for error or same filename */
1028 	if (error != 0 || req->newptr == NULL ||
1029 	    strncmp(siftr_logfile, arg1, arg2) == 0)
1030 		goto done;
1031 
1032 	/* Filname changed */
1033 	error = alq_open(&new_alq, arg1, curthread->td_ucred,
1034 	    SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1035 	if (error != 0)
1036 		goto done;
1037 
1038 	/*
1039 	 * If disabled, siftr_alq == NULL so we simply close
1040 	 * the alq as we've proved it can be opened.
1041 	 * If enabled, close the existing alq and switch the old
1042 	 * for the new.
1043 	 */
1044 	if (siftr_alq == NULL) {
1045 		alq_close(new_alq);
1046 	} else {
1047 		alq_close(siftr_alq);
1048 		siftr_alq = new_alq;
1049 	}
1050 
1051 	/* Update filename upon success */
1052 	strlcpy(siftr_logfile, arg1, arg2);
1053 done:
1054 	return (error);
1055 }
1056 
1057 static int
1058 siftr_manage_ops(uint8_t action)
1059 {
1060 	struct siftr_stats totalss;
1061 	struct timeval tval;
1062 	struct flow_hash_node *counter, *tmp_counter;
1063 	struct sbuf *s;
1064 	int i, error;
1065 	uint32_t bytes_to_write, total_skipped_pkts;
1066 
1067 	error = 0;
1068 	total_skipped_pkts = 0;
1069 
1070 	/* Init an autosizing sbuf that initially holds 200 chars. */
1071 	if ((s = sbuf_new(NULL, NULL, 200, SBUF_AUTOEXTEND)) == NULL)
1072 		return (-1);
1073 
1074 	if (action == SIFTR_ENABLE && siftr_pkt_manager_thr == NULL) {
1075 		/*
1076 		 * Create our alq
1077 		 * XXX: We should abort if alq_open fails!
1078 		 */
1079 		alq_open(&siftr_alq, siftr_logfile, curthread->td_ucred,
1080 		    SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1081 
1082 		STAILQ_INIT(&pkt_queue);
1083 
1084 		DPCPU_ZERO(ss);
1085 
1086 		siftr_exit_pkt_manager_thread = 0;
1087 
1088 		kthread_add(&siftr_pkt_manager_thread, NULL, NULL,
1089 		    &siftr_pkt_manager_thr, RFNOWAIT, 0,
1090 		    "siftr_pkt_manager_thr");
1091 
1092 		siftr_pfil(HOOK);
1093 
1094 		microtime(&tval);
1095 
1096 		sbuf_printf(s,
1097 		    "enable_time_secs=%jd\tenable_time_usecs=%06ld\t"
1098 		    "siftrver=%s\tsysname=%s\tsysver=%u\tipmode=%u\n",
1099 		    (intmax_t)tval.tv_sec, tval.tv_usec, MODVERSION_STR,
1100 		    SYS_NAME, __FreeBSD_version, SIFTR_IPMODE);
1101 
1102 		sbuf_finish(s);
1103 		alq_writen(siftr_alq, sbuf_data(s), sbuf_len(s), ALQ_WAITOK);
1104 
1105 	} else if (action == SIFTR_DISABLE && siftr_pkt_manager_thr != NULL) {
1106 		/*
1107 		 * Remove the pfil hook functions. All threads currently in
1108 		 * the hook functions are allowed to exit before siftr_pfil()
1109 		 * returns.
1110 		 */
1111 		siftr_pfil(UNHOOK);
1112 
1113 		/* This will block until the pkt manager thread unlocks it. */
1114 		mtx_lock(&siftr_pkt_mgr_mtx);
1115 
1116 		/* Tell the pkt manager thread that it should exit now. */
1117 		siftr_exit_pkt_manager_thread = 1;
1118 
1119 		/*
1120 		 * Wake the pkt_manager thread so it realises that
1121 		 * siftr_exit_pkt_manager_thread == 1 and exits gracefully.
1122 		 * The wakeup won't be delivered until we unlock
1123 		 * siftr_pkt_mgr_mtx so this isn't racy.
1124 		 */
1125 		wakeup(&wait_for_pkt);
1126 
1127 		/* Wait for the pkt_manager thread to exit. */
1128 		mtx_sleep(siftr_pkt_manager_thr, &siftr_pkt_mgr_mtx, PWAIT,
1129 		    "thrwait", 0);
1130 
1131 		siftr_pkt_manager_thr = NULL;
1132 		mtx_unlock(&siftr_pkt_mgr_mtx);
1133 
1134 		totalss.n_in = DPCPU_VARSUM(ss, n_in);
1135 		totalss.n_out = DPCPU_VARSUM(ss, n_out);
1136 		totalss.nskip_in_malloc = DPCPU_VARSUM(ss, nskip_in_malloc);
1137 		totalss.nskip_out_malloc = DPCPU_VARSUM(ss, nskip_out_malloc);
1138 		totalss.nskip_in_tcpcb = DPCPU_VARSUM(ss, nskip_in_tcpcb);
1139 		totalss.nskip_out_tcpcb = DPCPU_VARSUM(ss, nskip_out_tcpcb);
1140 		totalss.nskip_in_inpcb = DPCPU_VARSUM(ss, nskip_in_inpcb);
1141 		totalss.nskip_out_inpcb = DPCPU_VARSUM(ss, nskip_out_inpcb);
1142 
1143 		total_skipped_pkts = totalss.nskip_in_malloc +
1144 		    totalss.nskip_out_malloc + totalss.nskip_in_tcpcb +
1145 		    totalss.nskip_out_tcpcb + totalss.nskip_in_inpcb +
1146 		    totalss.nskip_out_inpcb;
1147 
1148 		microtime(&tval);
1149 
1150 		sbuf_printf(s,
1151 		    "disable_time_secs=%jd\tdisable_time_usecs=%06ld\t"
1152 		    "num_inbound_tcp_pkts=%ju\tnum_outbound_tcp_pkts=%ju\t"
1153 		    "total_tcp_pkts=%ju\tnum_inbound_skipped_pkts_malloc=%u\t"
1154 		    "num_outbound_skipped_pkts_malloc=%u\t"
1155 		    "num_inbound_skipped_pkts_tcpcb=%u\t"
1156 		    "num_outbound_skipped_pkts_tcpcb=%u\t"
1157 		    "num_inbound_skipped_pkts_inpcb=%u\t"
1158 		    "num_outbound_skipped_pkts_inpcb=%u\t"
1159 		    "total_skipped_tcp_pkts=%u\tflow_list=",
1160 		    (intmax_t)tval.tv_sec,
1161 		    tval.tv_usec,
1162 		    (uintmax_t)totalss.n_in,
1163 		    (uintmax_t)totalss.n_out,
1164 		    (uintmax_t)(totalss.n_in + totalss.n_out),
1165 		    totalss.nskip_in_malloc,
1166 		    totalss.nskip_out_malloc,
1167 		    totalss.nskip_in_tcpcb,
1168 		    totalss.nskip_out_tcpcb,
1169 		    totalss.nskip_in_inpcb,
1170 		    totalss.nskip_out_inpcb,
1171 		    total_skipped_pkts);
1172 
1173 		/*
1174 		 * Iterate over the flow hash, printing a summary of each
1175 		 * flow seen and freeing any malloc'd memory.
1176 		 * The hash consists of an array of LISTs (man 3 queue).
1177 		 */
1178 		for (i = 0; i <= siftr_hashmask; i++) {
1179 			LIST_FOREACH_SAFE(counter, counter_hash + i, nodes,
1180 			    tmp_counter) {
1181 				sbuf_printf(s, "%s;%hu-%s;%hu,",
1182 					    counter->const_info.laddr,
1183 					    counter->const_info.lport,
1184 					    counter->const_info.faddr,
1185 					    counter->const_info.fport);
1186 
1187 				free(counter, M_SIFTR_HASHNODE);
1188 			}
1189 
1190 			LIST_INIT(counter_hash + i);
1191 		}
1192 
1193 		sbuf_printf(s, "\n");
1194 		sbuf_finish(s);
1195 
1196 		i = 0;
1197 		do {
1198 			bytes_to_write = min(SIFTR_ALQ_BUFLEN, sbuf_len(s)-i);
1199 			alq_writen(siftr_alq, sbuf_data(s)+i, bytes_to_write, ALQ_WAITOK);
1200 			i += bytes_to_write;
1201 		} while (i < sbuf_len(s));
1202 
1203 		alq_close(siftr_alq);
1204 		siftr_alq = NULL;
1205 	} else
1206 		error = EINVAL;
1207 
1208 	sbuf_delete(s);
1209 
1210 	/*
1211 	 * XXX: Should be using ret to check if any functions fail
1212 	 * and set error appropriately
1213 	 */
1214 
1215 	return (error);
1216 }
1217 
1218 static int
1219 siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS)
1220 {
1221 	int error;
1222 	uint32_t new;
1223 
1224 	new = siftr_enabled;
1225 	error = sysctl_handle_int(oidp, &new, 0, req);
1226 	if (error == 0 && req->newptr != NULL) {
1227 		if (new > 1)
1228 			return (EINVAL);
1229 		else if (new != siftr_enabled) {
1230 			if ((error = siftr_manage_ops(new)) == 0) {
1231 				siftr_enabled = new;
1232 			} else {
1233 				siftr_manage_ops(SIFTR_DISABLE);
1234 			}
1235 		}
1236 	}
1237 
1238 	return (error);
1239 }
1240 
1241 static void
1242 siftr_shutdown_handler(void *arg)
1243 {
1244 	if (siftr_enabled == 1) {
1245 		siftr_manage_ops(SIFTR_DISABLE);
1246 	}
1247 }
1248 
1249 /*
1250  * Module is being unloaded or machine is shutting down. Take care of cleanup.
1251  */
1252 static int
1253 deinit_siftr(void)
1254 {
1255 	/* Cleanup. */
1256 	siftr_manage_ops(SIFTR_DISABLE);
1257 	hashdestroy(counter_hash, M_SIFTR, siftr_hashmask);
1258 	mtx_destroy(&siftr_pkt_queue_mtx);
1259 	mtx_destroy(&siftr_pkt_mgr_mtx);
1260 
1261 	return (0);
1262 }
1263 
1264 /*
1265  * Module has just been loaded into the kernel.
1266  */
1267 static int
1268 init_siftr(void)
1269 {
1270 	EVENTHANDLER_REGISTER(shutdown_pre_sync, siftr_shutdown_handler, NULL,
1271 	    SHUTDOWN_PRI_FIRST);
1272 
1273 	/* Initialise our flow counter hash table. */
1274 	counter_hash = hashinit(SIFTR_EXPECTED_MAX_TCP_FLOWS, M_SIFTR,
1275 	    &siftr_hashmask);
1276 
1277 	mtx_init(&siftr_pkt_queue_mtx, "siftr_pkt_queue_mtx", NULL, MTX_DEF);
1278 	mtx_init(&siftr_pkt_mgr_mtx, "siftr_pkt_mgr_mtx", NULL, MTX_DEF);
1279 
1280 	/* Print message to the user's current terminal. */
1281 	uprintf("\nStatistical Information For TCP Research (SIFTR) %s\n"
1282 	    "          http://caia.swin.edu.au/urp/newtcp\n\n",
1283 	    MODVERSION_STR);
1284 
1285 	return (0);
1286 }
1287 
1288 /*
1289  * This is the function that is called to load and unload the module.
1290  * When the module is loaded, this function is called once with
1291  * "what" == MOD_LOAD
1292  * When the module is unloaded, this function is called twice with
1293  * "what" = MOD_QUIESCE first, followed by "what" = MOD_UNLOAD second
1294  * When the system is shut down e.g. CTRL-ALT-DEL or using the shutdown command,
1295  * this function is called once with "what" = MOD_SHUTDOWN
1296  * When the system is shut down, the handler isn't called until the very end
1297  * of the shutdown sequence i.e. after the disks have been synced.
1298  */
1299 static int
1300 siftr_load_handler(module_t mod, int what, void *arg)
1301 {
1302 	int ret;
1303 
1304 	switch (what) {
1305 	case MOD_LOAD:
1306 		ret = init_siftr();
1307 		break;
1308 
1309 	case MOD_QUIESCE:
1310 	case MOD_SHUTDOWN:
1311 		ret = deinit_siftr();
1312 		break;
1313 
1314 	case MOD_UNLOAD:
1315 		ret = 0;
1316 		break;
1317 
1318 	default:
1319 		ret = EINVAL;
1320 		break;
1321 	}
1322 
1323 	return (ret);
1324 }
1325 
1326 static moduledata_t siftr_mod = {
1327 	.name = "siftr",
1328 	.evhand = siftr_load_handler,
1329 };
1330 
1331 /*
1332  * Param 1: name of the kernel module
1333  * Param 2: moduledata_t struct containing info about the kernel module
1334  *          and the execution entry point for the module
1335  * Param 3: From sysinit_sub_id enumeration in /usr/include/sys/kernel.h
1336  *          Defines the module initialisation order
1337  * Param 4: From sysinit_elem_order enumeration in /usr/include/sys/kernel.h
1338  *          Defines the initialisation order of this kld relative to others
1339  *          within the same subsystem as defined by param 3
1340  */
1341 DECLARE_MODULE(siftr, siftr_mod, SI_SUB_LAST, SI_ORDER_ANY);
1342 MODULE_DEPEND(siftr, alq, 1, 1, 1);
1343 MODULE_VERSION(siftr, MODVERSION);
1344