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