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