siftr.c revision 241913
1193323Sed/*-
2193323Sed * Copyright (c) 2007-2009
3193323Sed * 	Swinburne University of Technology, Melbourne, Australia.
4193323Sed * Copyright (c) 2009-2010, The FreeBSD Foundation
5193323Sed * All rights reserved.
6193323Sed *
7193323Sed * Portions of this software were developed at the Centre for Advanced
8193323Sed * Internet Architectures, Swinburne University of Technology, Melbourne,
9193323Sed * Australia by Lawrence Stewart under sponsorship from the FreeBSD Foundation.
10193323Sed *
11193323Sed * Redistribution and use in source and binary forms, with or without
12193323Sed * modification, are permitted provided that the following conditions
13193323Sed * are met:
14193323Sed * 1. Redistributions of source code must retain the above copyright
15193323Sed *    notice, this list of conditions and the following disclaimer.
16193323Sed * 2. Redistributions in binary form must reproduce the above copyright
17193323Sed *    notice, this list of conditions and the following disclaimer in the
18224145Sdim *    documentation and/or other materials provided with the distribution.
19226633Sdim *
20193323Sed * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
21224145Sdim * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22226633Sdim * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23208599Srdivacky * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
24224145Sdim * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25234353Sdim * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26223017Sdim * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27223017Sdim * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28193323Sed * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29223017Sdim * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30193323Sed * SUCH DAMAGE.
31193323Sed */
32193323Sed
33223017Sdim/******************************************************
34193323Sed * Statistical Information For TCP Research (SIFTR)
35234353Sdim *
36234353Sdim * A FreeBSD kernel module that adds very basic intrumentation to the
37234353Sdim * TCP stack, allowing internal stats to be recorded to a log file
38239462Sdim * for experimental, debugging and performance analysis purposes.
39239462Sdim *
40239462Sdim * SIFTR was first released in 2007 by James Healy and Lawrence Stewart whilst
41239462Sdim * working on the NewTCP research project at Swinburne University of
42234353Sdim * Technology's Centre for Advanced Internet Architectures, Melbourne,
43243830Sdim * Australia, which was made possible in part by a grant from the Cisco
44234353Sdim * University Research Program Fund at Community Foundation Silicon Valley.
45234353Sdim * More details are available at:
46239462Sdim *   http://caia.swin.edu.au/urp/newtcp/
47234353Sdim *
48239462Sdim * Work on SIFTR v1.2.x was sponsored by the FreeBSD Foundation as part of
49239462Sdim * the "Enhancing the FreeBSD TCP Implementation" project 2008-2009.
50234353Sdim * More details are available at:
51234353Sdim *   http://www.freebsdfoundation.org/
52234353Sdim *   http://caia.swin.edu.au/freebsd/etcp09/
53234353Sdim *
54234353Sdim * Lawrence Stewart is the current maintainer, and all contact regarding
55234353Sdim * SIFTR should be directed to him via email: lastewart@swin.edu.au
56234353Sdim *
57234353Sdim * Initial release date: June 2007
58234353Sdim * Most recent update: September 2010
59234353Sdim ******************************************************/
60234353Sdim
61234353Sdim#include <sys/cdefs.h>
62234353Sdim__FBSDID("$FreeBSD: head/sys/netinet/siftr.c 241913 2012-10-22 21:09:03Z glebius $");
63234353Sdim
64234353Sdim#include <sys/param.h>
65234353Sdim#include <sys/alq.h>
66234353Sdim#include <sys/errno.h>
67234353Sdim#include <sys/hash.h>
68234353Sdim#include <sys/kernel.h>
69234353Sdim#include <sys/kthread.h>
70234353Sdim#include <sys/lock.h>
71234353Sdim#include <sys/mbuf.h>
72234353Sdim#include <sys/module.h>
73234353Sdim#include <sys/mutex.h>
74234353Sdim#include <sys/pcpu.h>
75239462Sdim#include <sys/proc.h>
76234353Sdim#include <sys/sbuf.h>
77234353Sdim#include <sys/smp.h>
78234353Sdim#include <sys/socket.h>
79234353Sdim#include <sys/socketvar.h>
80234353Sdim#include <sys/sysctl.h>
81234353Sdim#include <sys/unistd.h>
82234353Sdim
83234353Sdim#include <net/if.h>
84234353Sdim#include <net/pfil.h>
85234353Sdim
86234353Sdim#include <netinet/in.h>
87243830Sdim#include <netinet/in_pcb.h>
88243830Sdim#include <netinet/in_systm.h>
89243830Sdim#include <netinet/in_var.h>
90234353Sdim#include <netinet/ip.h>
91234353Sdim#include <netinet/tcp_var.h>
92234353Sdim
93234353Sdim#ifdef SIFTR_IPV6
94193323Sed#include <netinet/ip6.h>
95193323Sed#include <netinet6/in6_pcb.h>
96193323Sed#endif /* SIFTR_IPV6 */
97221345Sdim
98221345Sdim#include <machine/in_cksum.h>
99234353Sdim
100223017Sdim/*
101223017Sdim * Three digit version number refers to X.Y.Z where:
102234353Sdim * X is the major version number
103234353Sdim * Y is bumped to mark backwards incompatible changes
104223017Sdim * Z is bumped to mark backwards compatible changes
105223017Sdim */
106223017Sdim#define V_MAJOR		1
107223017Sdim#define V_BACKBREAK	2
108223017Sdim#define V_BACKCOMPAT	4
109239462Sdim#define MODVERSION	__CONCAT(V_MAJOR, __CONCAT(V_BACKBREAK, V_BACKCOMPAT))
110239462Sdim#define MODVERSION_STR	__XSTRING(V_MAJOR) "." __XSTRING(V_BACKBREAK) "." \
111239462Sdim    __XSTRING(V_BACKCOMPAT)
112239462Sdim
113239462Sdim#define HOOK 0
114223017Sdim#define UNHOOK 1
115239462Sdim#define SIFTR_EXPECTED_MAX_TCP_FLOWS 65536
116223017Sdim#define SYS_NAME "FreeBSD"
117239462Sdim#define PACKET_TAG_SIFTR 100
118239462Sdim#define PACKET_COOKIE_SIFTR 21749576
119239462Sdim#define SIFTR_LOG_FILE_MODE 0644
120239462Sdim#define SIFTR_DISABLE 0
121239462Sdim#define SIFTR_ENABLE 1
122239462Sdim
123239462Sdim/*
124223017Sdim * Hard upper limit on the length of log messages. Bump this up if you add new
125223017Sdim * data fields such that the line length could exceed the below value.
126223017Sdim */
127223017Sdim#define MAX_LOG_MSG_LEN 200
128223017Sdim/* XXX: Make this a sysctl tunable. */
129224145Sdim#define SIFTR_ALQ_BUFLEN (1000*MAX_LOG_MSG_LEN)
130234353Sdim
131234353Sdim/*
132224145Sdim * 1 byte for IP version
133239462Sdim * IPv4: src/dst IP (4+4) + src/dst port (2+2) = 12 bytes
134239462Sdim * IPv6: src/dst IP (16+16) + src/dst port (2+2) = 36 bytes
135239462Sdim */
136239462Sdim#ifdef SIFTR_IPV6
137239462Sdim#define FLOW_KEY_LEN 37
138239462Sdim#else
139234353Sdim#define FLOW_KEY_LEN 13
140224145Sdim#endif
141239462Sdim
142239462Sdim#ifdef SIFTR_IPV6
143239462Sdim#define SIFTR_IPMODE 6
144224145Sdim#else
145224145Sdim#define SIFTR_IPMODE 4
146224145Sdim#endif
147224145Sdim
148224145Sdim/* useful macros */
149239462Sdim#define CAST_PTR_INT(X) (*((int*)(X)))
150239462Sdim
151239462Sdim#define UPPER_SHORT(X)	(((X) & 0xFFFF0000) >> 16)
152239462Sdim#define LOWER_SHORT(X)	((X) & 0x0000FFFF)
153239462Sdim
154239462Sdim#define FIRST_OCTET(X)	(((X) & 0xFF000000) >> 24)
155239462Sdim#define SECOND_OCTET(X)	(((X) & 0x00FF0000) >> 16)
156239462Sdim#define THIRD_OCTET(X)	(((X) & 0x0000FF00) >> 8)
157239462Sdim#define FOURTH_OCTET(X)	((X) & 0x000000FF)
158239462Sdim
159239462Sdimstatic MALLOC_DEFINE(M_SIFTR, "siftr", "dynamic memory used by SIFTR");
160239462Sdimstatic MALLOC_DEFINE(M_SIFTR_PKTNODE, "siftr_pktnode",
161239462Sdim    "SIFTR pkt_node struct");
162239462Sdimstatic MALLOC_DEFINE(M_SIFTR_HASHNODE, "siftr_hashnode",
163239462Sdim    "SIFTR flow_hash_node struct");
164239462Sdim
165239462Sdim/* Used as links in the pkt manager queue. */
166234353Sdimstruct pkt_node {
167234353Sdim	/* Timestamp of pkt as noted in the pfil hook. */
168234353Sdim	struct timeval		tval;
169239462Sdim	/* Direction pkt is travelling; either PFIL_IN or PFIL_OUT. */
170239462Sdim	uint8_t			direction;
171239462Sdim	/* IP version pkt_node relates to; either INP_IPV4 or INP_IPV6. */
172234353Sdim	uint8_t			ipver;
173239462Sdim	/* Hash of the pkt which triggered the log message. */
174234353Sdim	uint32_t		hash;
175234353Sdim	/* Local/foreign IP address. */
176239462Sdim#ifdef SIFTR_IPV6
177239462Sdim	uint32_t		ip_laddr[4];
178239462Sdim	uint32_t		ip_faddr[4];
179239462Sdim#else
180239462Sdim	uint8_t			ip_laddr[4];
181234353Sdim	uint8_t			ip_faddr[4];
182234353Sdim#endif
183234353Sdim	/* Local TCP port. */
184234353Sdim	uint16_t		tcp_localport;
185234353Sdim	/* Foreign TCP port. */
186234353Sdim	uint16_t		tcp_foreignport;
187234353Sdim	/* Congestion Window (bytes). */
188234353Sdim	u_long			snd_cwnd;
189234353Sdim	/* Sending Window (bytes). */
190234353Sdim	u_long			snd_wnd;
191234353Sdim	/* Receive Window (bytes). */
192224145Sdim	u_long			rcv_wnd;
193224145Sdim	/* Unused (was: Bandwidth Controlled Window (bytes)). */
194224145Sdim	u_long			snd_bwnd;
195224145Sdim	/* Slow Start Threshold (bytes). */
196226633Sdim	u_long			snd_ssthresh;
197224145Sdim	/* Current state of the TCP FSM. */
198224145Sdim	int			conn_state;
199224145Sdim	/* Max Segment Size (bytes). */
200224145Sdim	u_int			max_seg_size;
201224145Sdim	/*
202224145Sdim	 * Smoothed RTT stored as found in the TCP control block
203224145Sdim	 * in units of (TCP_RTT_SCALE*hz).
204239462Sdim	 */
205239462Sdim	int			smoothed_rtt;
206239462Sdim	/* Is SACK enabled? */
207223017Sdim	u_char			sack_enabled;
208223017Sdim	/* Window scaling for snd window. */
209239462Sdim	u_char			snd_scale;
210239462Sdim	/* Window scaling for recv window. */
211239462Sdim	u_char			rcv_scale;
212239462Sdim	/* TCP control block flags. */
213239462Sdim	u_int			flags;
214239462Sdim	/* Retransmit timeout length. */
215239462Sdim	int			rxt_length;
216239462Sdim	/* Size of the TCP send buffer in bytes. */
217239462Sdim	u_int			snd_buf_hiwater;
218239462Sdim	/* Current num bytes in the send socket buffer. */
219239462Sdim	u_int			snd_buf_cc;
220239462Sdim	/* Size of the TCP receive buffer in bytes. */
221239462Sdim	u_int			rcv_buf_hiwater;
222223017Sdim	/* Current num bytes in the receive socket buffer. */
223224145Sdim	u_int			rcv_buf_cc;
224239462Sdim	/* Number of bytes inflight that we are waiting on ACKs for. */
225234353Sdim	u_int			sent_inflight_bytes;
226193323Sed	/* Number of segments currently in the reassembly queue. */
227193323Sed	int			t_segqlen;
228193323Sed	/* Link to next pkt_node in the list. */
229224145Sdim	STAILQ_ENTRY(pkt_node)	nodes;
230224145Sdim};
231226633Sdim
232226633Sdimstruct flow_hash_node
233226633Sdim{
234226633Sdim	uint16_t counter;
235226633Sdim	uint8_t key[FLOW_KEY_LEN];
236226633Sdim	LIST_ENTRY(flow_hash_node) nodes;
237226633Sdim};
238226633Sdim
239226633Sdimstruct siftr_stats
240226633Sdim{
241226633Sdim	/* # TCP pkts seen by the SIFTR PFIL hooks, including any skipped. */
242226633Sdim	uint64_t n_in;
243226633Sdim	uint64_t n_out;
244226633Sdim	/* # pkts skipped due to failed malloc calls. */
245234353Sdim	uint32_t nskip_in_malloc;
246234353Sdim	uint32_t nskip_out_malloc;
247234353Sdim	/* # pkts skipped due to failed mtx acquisition. */
248226633Sdim	uint32_t nskip_in_mtx;
249234353Sdim	uint32_t nskip_out_mtx;
250234353Sdim	/* # pkts skipped due to failed inpcb lookups. */
251234353Sdim	uint32_t nskip_in_inpcb;
252234353Sdim	uint32_t nskip_out_inpcb;
253234353Sdim	/* # pkts skipped due to failed tcpcb lookups. */
254234353Sdim	uint32_t nskip_in_tcpcb;
255234353Sdim	uint32_t nskip_out_tcpcb;
256234353Sdim	/* # pkts skipped due to stack reinjection. */
257239462Sdim	uint32_t nskip_in_dejavu;
258239462Sdim	uint32_t nskip_out_dejavu;
259239462Sdim};
260239462Sdim
261224145Sdimstatic DPCPU_DEFINE(struct siftr_stats, ss);
262226633Sdim
263193323Sedstatic volatile unsigned int siftr_exit_pkt_manager_thread = 0;
264193323Sedstatic unsigned int siftr_enabled = 0;
265193323Sedstatic unsigned int siftr_pkts_per_log = 1;
266193323Sedstatic unsigned int siftr_generate_hashes = 0;
267193323Sed/* static unsigned int siftr_binary_log = 0; */
268223017Sdimstatic char siftr_logfile[PATH_MAX] = "/var/log/siftr.log";
269224145Sdimstatic u_long siftr_hashmask;
270193323SedSTAILQ_HEAD(pkthead, pkt_node) pkt_queue = STAILQ_HEAD_INITIALIZER(pkt_queue);
271226633SdimLIST_HEAD(listhead, flow_hash_node) *counter_hash;
272226633Sdimstatic int wait_for_pkt;
273226633Sdimstatic struct alq *siftr_alq = NULL;
274226633Sdimstatic struct mtx siftr_pkt_queue_mtx;
275226633Sdimstatic struct mtx siftr_pkt_mgr_mtx;
276226633Sdimstatic struct thread *siftr_pkt_manager_thr = NULL;
277193323Sed/*
278193323Sed * pfil.h defines PFIL_IN as 1 and PFIL_OUT as 2,
279221345Sdim * which we use as an index into this array.
280193323Sed */
281193323Sedstatic char direction[3] = {'\0', 'i','o'};
282193323Sed
283234353Sdim/* Required function prototypes. */
284193323Sedstatic int siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS);
285221345Sdimstatic int siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS);
286224145Sdim
287224145Sdim
288221345Sdim/* Declare the net.inet.siftr sysctl tree and populate it. */
289224145Sdim
290212904SdimSYSCTL_DECL(_net_inet_siftr);
291221345Sdim
292212904SdimSYSCTL_NODE(_net_inet, OID_AUTO, siftr, CTLFLAG_RW, NULL,
293212904Sdim    "siftr related settings");
294212904Sdim
295212904SdimSYSCTL_PROC(_net_inet_siftr, OID_AUTO, enabled, CTLTYPE_UINT|CTLFLAG_RW,
296212904Sdim    &siftr_enabled, 0, &siftr_sysctl_enabled_handler, "IU",
297212904Sdim    "switch siftr module operations on/off");
298226633Sdim
299226633SdimSYSCTL_PROC(_net_inet_siftr, OID_AUTO, logfile, CTLTYPE_STRING|CTLFLAG_RW,
300226633Sdim    &siftr_logfile, sizeof(siftr_logfile), &siftr_sysctl_logfile_name_handler,
301193323Sed    "A", "file to save siftr log messages to");
302226633Sdim
303226633SdimSYSCTL_UINT(_net_inet_siftr, OID_AUTO, ppl, CTLFLAG_RW,
304234353Sdim    &siftr_pkts_per_log, 1,
305234353Sdim    "number of packets between generating a log message");
306226633Sdim
307226633SdimSYSCTL_UINT(_net_inet_siftr, OID_AUTO, genhashes, CTLFLAG_RW,
308226633Sdim    &siftr_generate_hashes, 0,
309234353Sdim    "enable packet hash generation");
310234353Sdim
311226633Sdim/* XXX: TODO
312226633SdimSYSCTL_UINT(_net_inet_siftr, OID_AUTO, binary, CTLFLAG_RW,
313226633Sdim    &siftr_binary_log, 0,
314234353Sdim    "write log files in binary instead of ascii");
315234353Sdim*/
316234353Sdim
317234353Sdim
318234353Sdim/* Begin functions. */
319234353Sdim
320234353Sdimstatic void
321234353Sdimsiftr_process_pkt(struct pkt_node * pkt_node)
322234353Sdim{
323234353Sdim	struct flow_hash_node *hash_node;
324226633Sdim	struct listhead *counter_list;
325226633Sdim	struct siftr_stats *ss;
326226633Sdim	struct ale *log_buf;
327226633Sdim	uint8_t key[FLOW_KEY_LEN];
328226633Sdim	uint8_t found_match, key_offset;
329226633Sdim
330226633Sdim	hash_node = NULL;
331226633Sdim	ss = DPCPU_PTR(ss);
332226633Sdim	found_match = 0;
333226633Sdim	key_offset = 1;
334226633Sdim
335224145Sdim	/*
336224145Sdim	 * Create the key that will be used to create a hash index
337224145Sdim	 * into our hash table. Our key consists of:
338224145Sdim	 * ipversion, localip, localport, foreignip, foreignport
339226633Sdim	 */
340224145Sdim	key[0] = pkt_node->ipver;
341212904Sdim	memcpy(key + key_offset, &pkt_node->ip_laddr,
342224145Sdim	    sizeof(pkt_node->ip_laddr));
343226633Sdim	key_offset += sizeof(pkt_node->ip_laddr);
344212904Sdim	memcpy(key + key_offset, &pkt_node->tcp_localport,
345226633Sdim	    sizeof(pkt_node->tcp_localport));
346226633Sdim	key_offset += sizeof(pkt_node->tcp_localport);
347226633Sdim	memcpy(key + key_offset, &pkt_node->ip_faddr,
348226633Sdim	    sizeof(pkt_node->ip_faddr));
349239462Sdim	key_offset += sizeof(pkt_node->ip_faddr);
350239462Sdim	memcpy(key + key_offset, &pkt_node->tcp_foreignport,
351239462Sdim	    sizeof(pkt_node->tcp_foreignport));
352234353Sdim
353234353Sdim	counter_list = counter_hash +
354234353Sdim	    (hash32_buf(key, sizeof(key), 0) & siftr_hashmask);
355224145Sdim
356226633Sdim	/*
357226633Sdim	 * If the list is not empty i.e. the hash index has
358226633Sdim	 * been used by another flow previously.
359226633Sdim	 */
360226633Sdim	if (LIST_FIRST(counter_list) != NULL) {
361226633Sdim		/*
362226633Sdim		 * Loop through the hash nodes in the list.
363226633Sdim		 * There should normally only be 1 hash node in the list,
364226633Sdim		 * except if there have been collisions at the hash index
365226633Sdim		 * computed by hash32_buf().
366226633Sdim		 */
367226633Sdim		LIST_FOREACH(hash_node, counter_list, nodes) {
368226633Sdim			/*
369226633Sdim			 * Check if the key for the pkt we are currently
370226633Sdim			 * processing is the same as the key stored in the
371226633Sdim			 * hash node we are currently processing.
372226633Sdim			 * If they are the same, then we've found the
373226633Sdim			 * hash node that stores the counter for the flow
374226633Sdim			 * the pkt belongs to.
375226633Sdim			 */
376226633Sdim			if (memcmp(hash_node->key, key, sizeof(key)) == 0) {
377226633Sdim				found_match = 1;
378226633Sdim				break;
379226633Sdim			}
380226633Sdim		}
381226633Sdim	}
382226633Sdim
383239462Sdim	/* If this flow hash hasn't been seen before or we have a collision. */
384226633Sdim	if (hash_node == NULL || !found_match) {
385226633Sdim		/* Create a new hash node to store the flow's counter. */
386226633Sdim		hash_node = malloc(sizeof(struct flow_hash_node),
387193323Sed		    M_SIFTR_HASHNODE, M_WAITOK);
388223017Sdim
389239462Sdim		if (hash_node != NULL) {
390239462Sdim			/* Initialise our new hash node list entry. */
391239462Sdim			hash_node->counter = 0;
392239462Sdim			memcpy(hash_node->key, key, sizeof(key));
393239462Sdim			LIST_INSERT_HEAD(counter_list, hash_node, nodes);
394239462Sdim		} else {
395239462Sdim			/* Malloc failed. */
396239462Sdim			if (pkt_node->direction == PFIL_IN)
397239462Sdim				ss->nskip_in_malloc++;
398239462Sdim			else
399239462Sdim				ss->nskip_out_malloc++;
400239462Sdim
401239462Sdim			return;
402239462Sdim		}
403239462Sdim	} else if (siftr_pkts_per_log > 1) {
404239462Sdim		/*
405239462Sdim		 * Taking the remainder of the counter divided
406239462Sdim		 * by the current value of siftr_pkts_per_log
407239462Sdim		 * and storing that in counter provides a neat
408239462Sdim		 * way to modulate the frequency of log
409239462Sdim		 * messages being written to the log file.
410239462Sdim		 */
411239462Sdim		hash_node->counter = (hash_node->counter + 1) %
412239462Sdim		    siftr_pkts_per_log;
413239462Sdim
414234353Sdim		/*
415234353Sdim		 * If we have not seen enough packets since the last time
416234353Sdim		 * we wrote a log message for this connection, return.
417234353Sdim		 */
418234353Sdim		if (hash_node->counter > 0)
419234353Sdim			return;
420234353Sdim	}
421234353Sdim
422239462Sdim	log_buf = alq_getn(siftr_alq, MAX_LOG_MSG_LEN, ALQ_WAITOK);
423239462Sdim
424239462Sdim	if (log_buf == NULL)
425239462Sdim		return; /* Should only happen if the ALQ is shutting down. */
426223017Sdim
427223017Sdim#ifdef SIFTR_IPV6
428223017Sdim	pkt_node->ip_laddr[3] = ntohl(pkt_node->ip_laddr[3]);
429224145Sdim	pkt_node->ip_faddr[3] = ntohl(pkt_node->ip_faddr[3]);
430224145Sdim
431234353Sdim	if (pkt_node->ipver == INP_IPV6) { /* IPv6 packet */
432234353Sdim		pkt_node->ip_laddr[0] = ntohl(pkt_node->ip_laddr[0]);
433234353Sdim		pkt_node->ip_laddr[1] = ntohl(pkt_node->ip_laddr[1]);
434234353Sdim		pkt_node->ip_laddr[2] = ntohl(pkt_node->ip_laddr[2]);
435239462Sdim		pkt_node->ip_faddr[0] = ntohl(pkt_node->ip_faddr[0]);
436239462Sdim		pkt_node->ip_faddr[1] = ntohl(pkt_node->ip_faddr[1]);
437239462Sdim		pkt_node->ip_faddr[2] = ntohl(pkt_node->ip_faddr[2]);
438239462Sdim
439239462Sdim		/* Construct an IPv6 log message. */
440239462Sdim		log_buf->ae_bytesused = snprintf(log_buf->ae_data,
441234353Sdim		    MAX_LOG_MSG_LEN,
442224145Sdim		    "%c,0x%08x,%zd.%06ld,%x:%x:%x:%x:%x:%x:%x:%x,%u,%x:%x:%x:"
443243830Sdim		    "%x:%x:%x:%x:%x,%u,%ld,%ld,%ld,%ld,%ld,%u,%u,%u,%u,%u,%u,"
444223017Sdim		    "%u,%d,%u,%u,%u,%u,%u,%u\n",
445234353Sdim		    direction[pkt_node->direction],
446223017Sdim		    pkt_node->hash,
447239462Sdim		    pkt_node->tval.tv_sec,
448234353Sdim		    pkt_node->tval.tv_usec,
449239462Sdim		    UPPER_SHORT(pkt_node->ip_laddr[0]),
450239462Sdim		    LOWER_SHORT(pkt_node->ip_laddr[0]),
451239462Sdim		    UPPER_SHORT(pkt_node->ip_laddr[1]),
452226633Sdim		    LOWER_SHORT(pkt_node->ip_laddr[1]),
453226633Sdim		    UPPER_SHORT(pkt_node->ip_laddr[2]),
454224145Sdim		    LOWER_SHORT(pkt_node->ip_laddr[2]),
455226633Sdim		    UPPER_SHORT(pkt_node->ip_laddr[3]),
456226633Sdim		    LOWER_SHORT(pkt_node->ip_laddr[3]),
457224145Sdim		    ntohs(pkt_node->tcp_localport),
458234353Sdim		    UPPER_SHORT(pkt_node->ip_faddr[0]),
459234353Sdim		    LOWER_SHORT(pkt_node->ip_faddr[0]),
460234353Sdim		    UPPER_SHORT(pkt_node->ip_faddr[1]),
461234353Sdim		    LOWER_SHORT(pkt_node->ip_faddr[1]),
462234353Sdim		    UPPER_SHORT(pkt_node->ip_faddr[2]),
463234353Sdim		    LOWER_SHORT(pkt_node->ip_faddr[2]),
464234353Sdim		    UPPER_SHORT(pkt_node->ip_faddr[3]),
465234353Sdim		    LOWER_SHORT(pkt_node->ip_faddr[3]),
466234353Sdim		    ntohs(pkt_node->tcp_foreignport),
467226633Sdim		    pkt_node->snd_ssthresh,
468226633Sdim		    pkt_node->snd_cwnd,
469226633Sdim		    pkt_node->snd_bwnd,
470234353Sdim		    pkt_node->snd_wnd,
471234353Sdim		    pkt_node->rcv_wnd,
472234353Sdim		    pkt_node->snd_scale,
473234353Sdim		    pkt_node->rcv_scale,
474234353Sdim		    pkt_node->conn_state,
475226633Sdim		    pkt_node->max_seg_size,
476226633Sdim		    pkt_node->smoothed_rtt,
477234353Sdim		    pkt_node->sack_enabled,
478234353Sdim		    pkt_node->flags,
479234353Sdim		    pkt_node->rxt_length,
480234353Sdim		    pkt_node->snd_buf_hiwater,
481226633Sdim		    pkt_node->snd_buf_cc,
482234353Sdim		    pkt_node->rcv_buf_hiwater,
483234353Sdim		    pkt_node->rcv_buf_cc,
484223017Sdim		    pkt_node->sent_inflight_bytes,
485234353Sdim		    pkt_node->t_segqlen);
486234353Sdim	} else { /* IPv4 packet */
487234353Sdim		pkt_node->ip_laddr[0] = FIRST_OCTET(pkt_node->ip_laddr[3]);
488234353Sdim		pkt_node->ip_laddr[1] = SECOND_OCTET(pkt_node->ip_laddr[3]);
489234353Sdim		pkt_node->ip_laddr[2] = THIRD_OCTET(pkt_node->ip_laddr[3]);
490234353Sdim		pkt_node->ip_laddr[3] = FOURTH_OCTET(pkt_node->ip_laddr[3]);
491223017Sdim		pkt_node->ip_faddr[0] = FIRST_OCTET(pkt_node->ip_faddr[3]);
492223017Sdim		pkt_node->ip_faddr[1] = SECOND_OCTET(pkt_node->ip_faddr[3]);
493223017Sdim		pkt_node->ip_faddr[2] = THIRD_OCTET(pkt_node->ip_faddr[3]);
494243830Sdim		pkt_node->ip_faddr[3] = FOURTH_OCTET(pkt_node->ip_faddr[3]);
495243830Sdim#endif /* SIFTR_IPV6 */
496243830Sdim
497223017Sdim		/* Construct an IPv4 log message. */
498223017Sdim		log_buf->ae_bytesused = snprintf(log_buf->ae_data,
499223017Sdim		    MAX_LOG_MSG_LEN,
500224145Sdim		    "%c,0x%08x,%jd.%06ld,%u.%u.%u.%u,%u,%u.%u.%u.%u,%u,%ld,%ld,"
501224145Sdim		    "%ld,%ld,%ld,%u,%u,%u,%u,%u,%u,%u,%d,%u,%u,%u,%u,%u,%u\n",
502223017Sdim		    direction[pkt_node->direction],
503223017Sdim		    pkt_node->hash,
504223017Sdim		    (intmax_t)pkt_node->tval.tv_sec,
505234353Sdim		    pkt_node->tval.tv_usec,
506223017Sdim		    pkt_node->ip_laddr[0],
507234353Sdim		    pkt_node->ip_laddr[1],
508234353Sdim		    pkt_node->ip_laddr[2],
509223017Sdim		    pkt_node->ip_laddr[3],
510223017Sdim		    ntohs(pkt_node->tcp_localport),
511234353Sdim		    pkt_node->ip_faddr[0],
512234353Sdim		    pkt_node->ip_faddr[1],
513223017Sdim		    pkt_node->ip_faddr[2],
514239462Sdim		    pkt_node->ip_faddr[3],
515239462Sdim		    ntohs(pkt_node->tcp_foreignport),
516239462Sdim		    pkt_node->snd_ssthresh,
517239462Sdim		    pkt_node->snd_cwnd,
518239462Sdim		    pkt_node->snd_bwnd,
519239462Sdim		    pkt_node->snd_wnd,
520239462Sdim		    pkt_node->rcv_wnd,
521239462Sdim		    pkt_node->snd_scale,
522239462Sdim		    pkt_node->rcv_scale,
523239462Sdim		    pkt_node->conn_state,
524239462Sdim		    pkt_node->max_seg_size,
525224145Sdim		    pkt_node->smoothed_rtt,
526243830Sdim		    pkt_node->sack_enabled,
527243830Sdim		    pkt_node->flags,
528243830Sdim		    pkt_node->rxt_length,
529223017Sdim		    pkt_node->snd_buf_hiwater,
530223017Sdim		    pkt_node->snd_buf_cc,
531223017Sdim		    pkt_node->rcv_buf_hiwater,
532223017Sdim		    pkt_node->rcv_buf_cc,
533234353Sdim		    pkt_node->sent_inflight_bytes,
534234353Sdim		    pkt_node->t_segqlen);
535234353Sdim#ifdef SIFTR_IPV6
536234353Sdim	}
537234353Sdim#endif
538239462Sdim
539239462Sdim	alq_post_flags(siftr_alq, log_buf, 0);
540239462Sdim}
541239462Sdim
542239462Sdim
543239462Sdimstatic void
544239462Sdimsiftr_pkt_manager_thread(void *arg)
545239462Sdim{
546239462Sdim	STAILQ_HEAD(pkthead, pkt_node) tmp_pkt_queue =
547239462Sdim	    STAILQ_HEAD_INITIALIZER(tmp_pkt_queue);
548239462Sdim	struct pkt_node *pkt_node, *pkt_node_temp;
549239462Sdim	uint8_t draining;
550239462Sdim
551239462Sdim	draining = 2;
552239462Sdim
553239462Sdim	mtx_lock(&siftr_pkt_mgr_mtx);
554239462Sdim
555239462Sdim	/* draining == 0 when queue has been flushed and it's safe to exit. */
556239462Sdim	while (draining) {
557239462Sdim		/*
558239462Sdim		 * Sleep until we are signalled to wake because thread has
559239462Sdim		 * been told to exit or until 1 tick has passed.
560234353Sdim		 */
561234353Sdim		mtx_sleep(&wait_for_pkt, &siftr_pkt_mgr_mtx, PWAIT, "pktwait",
562234353Sdim		    1);
563239462Sdim
564239462Sdim		/* Gain exclusive access to the pkt_node queue. */
565239462Sdim		mtx_lock(&siftr_pkt_queue_mtx);
566234353Sdim
567234353Sdim		/*
568234353Sdim		 * Move pkt_queue to tmp_pkt_queue, which leaves
569234353Sdim		 * pkt_queue empty and ready to receive more pkt_nodes.
570234353Sdim		 */
571234353Sdim		STAILQ_CONCAT(&tmp_pkt_queue, &pkt_queue);
572234353Sdim
573234353Sdim		/*
574234353Sdim		 * We've finished making changes to the list. Unlock it
575239462Sdim		 * so the pfil hooks can continue queuing pkt_nodes.
576239462Sdim		 */
577239462Sdim		mtx_unlock(&siftr_pkt_queue_mtx);
578239462Sdim
579239462Sdim		/*
580239462Sdim		 * We can't hold a mutex whilst calling siftr_process_pkt
581239462Sdim		 * because ALQ might sleep waiting for buffer space.
582226633Sdim		 */
583224145Sdim		mtx_unlock(&siftr_pkt_mgr_mtx);
584224145Sdim
585224145Sdim		/* Flush all pkt_nodes to the log file. */
586224145Sdim		STAILQ_FOREACH_SAFE(pkt_node, &tmp_pkt_queue, nodes,
587224145Sdim		    pkt_node_temp) {
588224145Sdim			siftr_process_pkt(pkt_node);
589224145Sdim			STAILQ_REMOVE_HEAD(&tmp_pkt_queue, nodes);
590224145Sdim			free(pkt_node, M_SIFTR_PKTNODE);
591224145Sdim		}
592224145Sdim
593224145Sdim		KASSERT(STAILQ_EMPTY(&tmp_pkt_queue),
594224145Sdim		    ("SIFTR tmp_pkt_queue not empty after flush"));
595224145Sdim
596234353Sdim		mtx_lock(&siftr_pkt_mgr_mtx);
597234353Sdim
598234353Sdim		/*
599234353Sdim		 * If siftr_exit_pkt_manager_thread gets set during the window
600234353Sdim		 * where we are draining the tmp_pkt_queue above, there might
601239462Sdim		 * still be pkts in pkt_queue that need to be drained.
602234353Sdim		 * Allow one further iteration to occur after
603234353Sdim		 * siftr_exit_pkt_manager_thread has been set to ensure
604234353Sdim		 * pkt_queue is completely empty before we kill the thread.
605234353Sdim		 *
606234353Sdim		 * siftr_exit_pkt_manager_thread is set only after the pfil
607239462Sdim		 * hooks have been removed, so only 1 extra iteration
608234353Sdim		 * is needed to drain the queue.
609234353Sdim		 */
610234353Sdim		if (siftr_exit_pkt_manager_thread)
611234353Sdim			draining--;
612234353Sdim	}
613234353Sdim
614234353Sdim	mtx_unlock(&siftr_pkt_mgr_mtx);
615234353Sdim
616234353Sdim	/* Calls wakeup on this thread's struct thread ptr. */
617234353Sdim	kthread_exit();
618234353Sdim}
619234353Sdim
620234353Sdim
621234353Sdimstatic uint32_t
622234353Sdimhash_pkt(struct mbuf *m, uint32_t offset)
623234353Sdim{
624234353Sdim	uint32_t hash;
625234353Sdim
626223017Sdim	hash = 0;
627223017Sdim
628224145Sdim	while (m != NULL && offset > m->m_len) {
629234353Sdim		/*
630234353Sdim		 * The IP packet payload does not start in this mbuf, so
631234353Sdim		 * need to figure out which mbuf it starts in and what offset
632234353Sdim		 * into the mbuf's data region the payload starts at.
633234353Sdim		 */
634234353Sdim		offset -= m->m_len;
635234353Sdim		m = m->m_next;
636234353Sdim	}
637223017Sdim
638193323Sed	while (m != NULL) {
639193323Sed		/* Ensure there is data in the mbuf */
640193323Sed		if ((m->m_len - offset) > 0)
641			hash = hash32_buf(m->m_data + offset,
642			    m->m_len - offset, hash);
643
644		m = m->m_next;
645		offset = 0;
646        }
647
648	return (hash);
649}
650
651
652/*
653 * Check if a given mbuf has the SIFTR mbuf tag. If it does, log the fact that
654 * it's a reinjected packet and return. If it doesn't, tag the mbuf and return.
655 * Return value >0 means the caller should skip processing this mbuf.
656 */
657static inline int
658siftr_chkreinject(struct mbuf *m, int dir, struct siftr_stats *ss)
659{
660	if (m_tag_locate(m, PACKET_COOKIE_SIFTR, PACKET_TAG_SIFTR, NULL)
661	    != NULL) {
662		if (dir == PFIL_IN)
663			ss->nskip_in_dejavu++;
664		else
665			ss->nskip_out_dejavu++;
666
667		return (1);
668	} else {
669		struct m_tag *tag = m_tag_alloc(PACKET_COOKIE_SIFTR,
670		    PACKET_TAG_SIFTR, 0, M_NOWAIT);
671		if (tag == NULL) {
672			if (dir == PFIL_IN)
673				ss->nskip_in_malloc++;
674			else
675				ss->nskip_out_malloc++;
676
677			return (1);
678		}
679
680		m_tag_prepend(m, tag);
681	}
682
683	return (0);
684}
685
686
687/*
688 * Look up an inpcb for a packet. Return the inpcb pointer if found, or NULL
689 * otherwise.
690 */
691static inline struct inpcb *
692siftr_findinpcb(int ipver, struct ip *ip, struct mbuf *m, uint16_t sport,
693    uint16_t dport, int dir, struct siftr_stats *ss)
694{
695	struct inpcb *inp;
696
697	/* We need the tcbinfo lock. */
698	INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
699
700	if (dir == PFIL_IN)
701		inp = (ipver == INP_IPV4 ?
702		    in_pcblookup(&V_tcbinfo, ip->ip_src, sport, ip->ip_dst,
703		    dport, INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif)
704		    :
705#ifdef SIFTR_IPV6
706		    in6_pcblookup(&V_tcbinfo,
707		    &((struct ip6_hdr *)ip)->ip6_src, sport,
708		    &((struct ip6_hdr *)ip)->ip6_dst, dport, INPLOOKUP_RLOCKPCB,
709		    m->m_pkthdr.rcvif)
710#else
711		    NULL
712#endif
713		    );
714
715	else
716		inp = (ipver == INP_IPV4 ?
717		    in_pcblookup(&V_tcbinfo, ip->ip_dst, dport, ip->ip_src,
718		    sport, INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif)
719		    :
720#ifdef SIFTR_IPV6
721		    in6_pcblookup(&V_tcbinfo,
722		    &((struct ip6_hdr *)ip)->ip6_dst, dport,
723		    &((struct ip6_hdr *)ip)->ip6_src, sport, INPLOOKUP_RLOCKPCB,
724		    m->m_pkthdr.rcvif)
725#else
726		    NULL
727#endif
728		    );
729
730	/* If we can't find the inpcb, bail. */
731	if (inp == NULL) {
732		if (dir == PFIL_IN)
733			ss->nskip_in_inpcb++;
734		else
735			ss->nskip_out_inpcb++;
736	}
737
738	return (inp);
739}
740
741
742static inline void
743siftr_siftdata(struct pkt_node *pn, struct inpcb *inp, struct tcpcb *tp,
744    int ipver, int dir, int inp_locally_locked)
745{
746#ifdef SIFTR_IPV6
747	if (ipver == INP_IPV4) {
748		pn->ip_laddr[3] = inp->inp_laddr.s_addr;
749		pn->ip_faddr[3] = inp->inp_faddr.s_addr;
750#else
751		*((uint32_t *)pn->ip_laddr) = inp->inp_laddr.s_addr;
752		*((uint32_t *)pn->ip_faddr) = inp->inp_faddr.s_addr;
753#endif
754#ifdef SIFTR_IPV6
755	} else {
756		pn->ip_laddr[0] = inp->in6p_laddr.s6_addr32[0];
757		pn->ip_laddr[1] = inp->in6p_laddr.s6_addr32[1];
758		pn->ip_laddr[2] = inp->in6p_laddr.s6_addr32[2];
759		pn->ip_laddr[3] = inp->in6p_laddr.s6_addr32[3];
760		pn->ip_faddr[0] = inp->in6p_faddr.s6_addr32[0];
761		pn->ip_faddr[1] = inp->in6p_faddr.s6_addr32[1];
762		pn->ip_faddr[2] = inp->in6p_faddr.s6_addr32[2];
763		pn->ip_faddr[3] = inp->in6p_faddr.s6_addr32[3];
764	}
765#endif
766	pn->tcp_localport = inp->inp_lport;
767	pn->tcp_foreignport = inp->inp_fport;
768	pn->snd_cwnd = tp->snd_cwnd;
769	pn->snd_wnd = tp->snd_wnd;
770	pn->rcv_wnd = tp->rcv_wnd;
771	pn->snd_bwnd = 0;		/* Unused, kept for compat. */
772	pn->snd_ssthresh = tp->snd_ssthresh;
773	pn->snd_scale = tp->snd_scale;
774	pn->rcv_scale = tp->rcv_scale;
775	pn->conn_state = tp->t_state;
776	pn->max_seg_size = tp->t_maxseg;
777	pn->smoothed_rtt = tp->t_srtt;
778	pn->sack_enabled = (tp->t_flags & TF_SACK_PERMIT) != 0;
779	pn->flags = tp->t_flags;
780	pn->rxt_length = tp->t_rxtcur;
781	pn->snd_buf_hiwater = inp->inp_socket->so_snd.sb_hiwat;
782	pn->snd_buf_cc = inp->inp_socket->so_snd.sb_cc;
783	pn->rcv_buf_hiwater = inp->inp_socket->so_rcv.sb_hiwat;
784	pn->rcv_buf_cc = inp->inp_socket->so_rcv.sb_cc;
785	pn->sent_inflight_bytes = tp->snd_max - tp->snd_una;
786	pn->t_segqlen = tp->t_segqlen;
787
788	/* We've finished accessing the tcb so release the lock. */
789	if (inp_locally_locked)
790		INP_RUNLOCK(inp);
791
792	pn->ipver = ipver;
793	pn->direction = dir;
794
795	/*
796	 * Significantly more accurate than using getmicrotime(), but slower!
797	 * Gives true microsecond resolution at the expense of a hit to
798	 * maximum pps throughput processing when SIFTR is loaded and enabled.
799	 */
800	microtime(&pn->tval);
801}
802
803
804/*
805 * pfil hook that is called for each IPv4 packet making its way through the
806 * stack in either direction.
807 * The pfil subsystem holds a non-sleepable mutex somewhere when
808 * calling our hook function, so we can't sleep at all.
809 * It's very important to use the M_NOWAIT flag with all function calls
810 * that support it so that they won't sleep, otherwise you get a panic.
811 */
812static int
813siftr_chkpkt(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
814    struct inpcb *inp)
815{
816	struct pkt_node *pn;
817	struct ip *ip;
818	struct tcphdr *th;
819	struct tcpcb *tp;
820	struct siftr_stats *ss;
821	unsigned int ip_hl;
822	int inp_locally_locked;
823
824	inp_locally_locked = 0;
825	ss = DPCPU_PTR(ss);
826
827	/*
828	 * m_pullup is not required here because ip_{input|output}
829	 * already do the heavy lifting for us.
830	 */
831
832	ip = mtod(*m, struct ip *);
833
834	/* Only continue processing if the packet is TCP. */
835	if (ip->ip_p != IPPROTO_TCP)
836		goto ret;
837
838	/*
839	 * If a kernel subsystem reinjects packets into the stack, our pfil
840	 * hook will be called multiple times for the same packet.
841	 * Make sure we only process unique packets.
842	 */
843	if (siftr_chkreinject(*m, dir, ss))
844		goto ret;
845
846	if (dir == PFIL_IN)
847		ss->n_in++;
848	else
849		ss->n_out++;
850
851	/*
852	 * Create a tcphdr struct starting at the correct offset
853	 * in the IP packet. ip->ip_hl gives the ip header length
854	 * in 4-byte words, so multiply it to get the size in bytes.
855	 */
856	ip_hl = (ip->ip_hl << 2);
857	th = (struct tcphdr *)((caddr_t)ip + ip_hl);
858
859	/*
860	 * If the pfil hooks don't provide a pointer to the
861	 * inpcb, we need to find it ourselves and lock it.
862	 */
863	if (!inp) {
864		/* Find the corresponding inpcb for this pkt. */
865		inp = siftr_findinpcb(INP_IPV4, ip, *m, th->th_sport,
866		    th->th_dport, dir, ss);
867
868		if (inp == NULL)
869			goto ret;
870		else
871			inp_locally_locked = 1;
872	}
873
874	INP_LOCK_ASSERT(inp);
875
876	/* Find the TCP control block that corresponds with this packet */
877	tp = intotcpcb(inp);
878
879	/*
880	 * If we can't find the TCP control block (happens occasionaly for a
881	 * packet sent during the shutdown phase of a TCP connection),
882	 * or we're in the timewait state, bail
883	 */
884	if (tp == NULL || inp->inp_flags & INP_TIMEWAIT) {
885		if (dir == PFIL_IN)
886			ss->nskip_in_tcpcb++;
887		else
888			ss->nskip_out_tcpcb++;
889
890		goto inp_unlock;
891	}
892
893	pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
894
895	if (pn == NULL) {
896		if (dir == PFIL_IN)
897			ss->nskip_in_malloc++;
898		else
899			ss->nskip_out_malloc++;
900
901		goto inp_unlock;
902	}
903
904	siftr_siftdata(pn, inp, tp, INP_IPV4, dir, inp_locally_locked);
905
906	if (siftr_generate_hashes) {
907		if ((*m)->m_pkthdr.csum_flags & CSUM_TCP) {
908			/*
909			 * For outbound packets, the TCP checksum isn't
910			 * calculated yet. This is a problem for our packet
911			 * hashing as the receiver will calc a different hash
912			 * to ours if we don't include the correct TCP checksum
913			 * in the bytes being hashed. To work around this
914			 * problem, we manually calc the TCP checksum here in
915			 * software. We unset the CSUM_TCP flag so the lower
916			 * layers don't recalc it.
917			 */
918			(*m)->m_pkthdr.csum_flags &= ~CSUM_TCP;
919
920			/*
921			 * Calculate the TCP checksum in software and assign
922			 * to correct TCP header field, which will follow the
923			 * packet mbuf down the stack. The trick here is that
924			 * tcp_output() sets th->th_sum to the checksum of the
925			 * pseudo header for us already. Because of the nature
926			 * of the checksumming algorithm, we can sum over the
927			 * entire IP payload (i.e. TCP header and data), which
928			 * will include the already calculated pseduo header
929			 * checksum, thus giving us the complete TCP checksum.
930			 *
931			 * To put it in simple terms, if checksum(1,2,3,4)=10,
932			 * then checksum(1,2,3,4,5) == checksum(10,5).
933			 * This property is what allows us to "cheat" and
934			 * checksum only the IP payload which has the TCP
935			 * th_sum field populated with the pseudo header's
936			 * checksum, and not need to futz around checksumming
937			 * pseudo header bytes and TCP header/data in one hit.
938			 * Refer to RFC 1071 for more info.
939			 *
940			 * NB: in_cksum_skip(struct mbuf *m, int len, int skip)
941			 * in_cksum_skip 2nd argument is NOT the number of
942			 * bytes to read from the mbuf at "skip" bytes offset
943			 * from the start of the mbuf (very counter intuitive!).
944			 * The number of bytes to read is calculated internally
945			 * by the function as len-skip i.e. to sum over the IP
946			 * payload (TCP header + data) bytes, it is INCORRECT
947			 * to call the function like this:
948			 * in_cksum_skip(at, ip->ip_len - offset, offset)
949			 * Rather, it should be called like this:
950			 * in_cksum_skip(at, ip->ip_len, offset)
951			 * which means read "ip->ip_len - offset" bytes from
952			 * the mbuf cluster "at" at offset "offset" bytes from
953			 * the beginning of the "at" mbuf's data pointer.
954			 */
955			th->th_sum = in_cksum_skip(*m, ntohs(ip->ip_len),
956			    ip_hl);
957		}
958
959		/*
960		 * XXX: Having to calculate the checksum in software and then
961		 * hash over all bytes is really inefficient. Would be nice to
962		 * find a way to create the hash and checksum in the same pass
963		 * over the bytes.
964		 */
965		pn->hash = hash_pkt(*m, ip_hl);
966	}
967
968	mtx_lock(&siftr_pkt_queue_mtx);
969	STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
970	mtx_unlock(&siftr_pkt_queue_mtx);
971	goto ret;
972
973inp_unlock:
974	if (inp_locally_locked)
975		INP_RUNLOCK(inp);
976
977ret:
978	/* Returning 0 ensures pfil will not discard the pkt */
979	return (0);
980}
981
982
983#ifdef SIFTR_IPV6
984static int
985siftr_chkpkt6(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
986    struct inpcb *inp)
987{
988	struct pkt_node *pn;
989	struct ip6_hdr *ip6;
990	struct tcphdr *th;
991	struct tcpcb *tp;
992	struct siftr_stats *ss;
993	unsigned int ip6_hl;
994	int inp_locally_locked;
995
996	inp_locally_locked = 0;
997	ss = DPCPU_PTR(ss);
998
999	/*
1000	 * m_pullup is not required here because ip6_{input|output}
1001	 * already do the heavy lifting for us.
1002	 */
1003
1004	ip6 = mtod(*m, struct ip6_hdr *);
1005
1006	/*
1007	 * Only continue processing if the packet is TCP
1008	 * XXX: We should follow the next header fields
1009	 * as shown on Pg 6 RFC 2460, but right now we'll
1010	 * only check pkts that have no extension headers.
1011	 */
1012	if (ip6->ip6_nxt != IPPROTO_TCP)
1013		goto ret6;
1014
1015	/*
1016	 * If a kernel subsystem reinjects packets into the stack, our pfil
1017	 * hook will be called multiple times for the same packet.
1018	 * Make sure we only process unique packets.
1019	 */
1020	if (siftr_chkreinject(*m, dir, ss))
1021		goto ret6;
1022
1023	if (dir == PFIL_IN)
1024		ss->n_in++;
1025	else
1026		ss->n_out++;
1027
1028	ip6_hl = sizeof(struct ip6_hdr);
1029
1030	/*
1031	 * Create a tcphdr struct starting at the correct offset
1032	 * in the ipv6 packet. ip->ip_hl gives the ip header length
1033	 * in 4-byte words, so multiply it to get the size in bytes.
1034	 */
1035	th = (struct tcphdr *)((caddr_t)ip6 + ip6_hl);
1036
1037	/*
1038	 * For inbound packets, the pfil hooks don't provide a pointer to the
1039	 * inpcb, so we need to find it ourselves and lock it.
1040	 */
1041	if (!inp) {
1042		/* Find the corresponding inpcb for this pkt. */
1043		inp = siftr_findinpcb(INP_IPV6, (struct ip *)ip6, *m,
1044		    th->th_sport, th->th_dport, dir, ss);
1045
1046		if (inp == NULL)
1047			goto ret6;
1048		else
1049			inp_locally_locked = 1;
1050	}
1051
1052	/* Find the TCP control block that corresponds with this packet. */
1053	tp = intotcpcb(inp);
1054
1055	/*
1056	 * If we can't find the TCP control block (happens occasionaly for a
1057	 * packet sent during the shutdown phase of a TCP connection),
1058	 * or we're in the timewait state, bail.
1059	 */
1060	if (tp == NULL || inp->inp_flags & INP_TIMEWAIT) {
1061		if (dir == PFIL_IN)
1062			ss->nskip_in_tcpcb++;
1063		else
1064			ss->nskip_out_tcpcb++;
1065
1066		goto inp_unlock6;
1067	}
1068
1069	pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
1070
1071	if (pn == NULL) {
1072		if (dir == PFIL_IN)
1073			ss->nskip_in_malloc++;
1074		else
1075			ss->nskip_out_malloc++;
1076
1077		goto inp_unlock6;
1078	}
1079
1080	siftr_siftdata(pn, inp, tp, INP_IPV6, dir, inp_locally_locked);
1081
1082	/* XXX: Figure out how to generate hashes for IPv6 packets. */
1083
1084	mtx_lock(&siftr_pkt_queue_mtx);
1085	STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
1086	mtx_unlock(&siftr_pkt_queue_mtx);
1087	goto ret6;
1088
1089inp_unlock6:
1090	if (inp_locally_locked)
1091		INP_RUNLOCK(inp);
1092
1093ret6:
1094	/* Returning 0 ensures pfil will not discard the pkt. */
1095	return (0);
1096}
1097#endif /* #ifdef SIFTR_IPV6 */
1098
1099
1100static int
1101siftr_pfil(int action)
1102{
1103	struct pfil_head *pfh_inet;
1104#ifdef SIFTR_IPV6
1105	struct pfil_head *pfh_inet6;
1106#endif
1107	VNET_ITERATOR_DECL(vnet_iter);
1108
1109	VNET_LIST_RLOCK();
1110	VNET_FOREACH(vnet_iter) {
1111		CURVNET_SET(vnet_iter);
1112		pfh_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET);
1113#ifdef SIFTR_IPV6
1114		pfh_inet6 = pfil_head_get(PFIL_TYPE_AF, AF_INET6);
1115#endif
1116
1117		if (action == HOOK) {
1118			pfil_add_hook(siftr_chkpkt, NULL,
1119			    PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet);
1120#ifdef SIFTR_IPV6
1121			pfil_add_hook(siftr_chkpkt6, NULL,
1122			    PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet6);
1123#endif
1124		} else if (action == UNHOOK) {
1125			pfil_remove_hook(siftr_chkpkt, NULL,
1126			    PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet);
1127#ifdef SIFTR_IPV6
1128			pfil_remove_hook(siftr_chkpkt6, NULL,
1129			    PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet6);
1130#endif
1131		}
1132		CURVNET_RESTORE();
1133	}
1134	VNET_LIST_RUNLOCK();
1135
1136	return (0);
1137}
1138
1139
1140static int
1141siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS)
1142{
1143	struct alq *new_alq;
1144	int error;
1145
1146	if (req->newptr == NULL)
1147		goto skip;
1148
1149	/* If old filename and new filename are different. */
1150	if (strncmp(siftr_logfile, (char *)req->newptr, PATH_MAX)) {
1151
1152		error = alq_open(&new_alq, req->newptr, curthread->td_ucred,
1153		    SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1154
1155		/* Bail if unable to create new alq. */
1156		if (error)
1157			return (1);
1158
1159		/*
1160		 * If disabled, siftr_alq == NULL so we simply close
1161		 * the alq as we've proved it can be opened.
1162		 * If enabled, close the existing alq and switch the old
1163		 * for the new.
1164		 */
1165		if (siftr_alq == NULL)
1166			alq_close(new_alq);
1167		else {
1168			alq_close(siftr_alq);
1169			siftr_alq = new_alq;
1170		}
1171	}
1172
1173skip:
1174	return (sysctl_handle_string(oidp, arg1, arg2, req));
1175}
1176
1177
1178static int
1179siftr_manage_ops(uint8_t action)
1180{
1181	struct siftr_stats totalss;
1182	struct timeval tval;
1183	struct flow_hash_node *counter, *tmp_counter;
1184	struct sbuf *s;
1185	int i, key_index, ret, error;
1186	uint32_t bytes_to_write, total_skipped_pkts;
1187	uint16_t lport, fport;
1188	uint8_t *key, ipver;
1189
1190#ifdef SIFTR_IPV6
1191	uint32_t laddr[4];
1192	uint32_t faddr[4];
1193#else
1194	uint8_t laddr[4];
1195	uint8_t faddr[4];
1196#endif
1197
1198	error = 0;
1199	total_skipped_pkts = 0;
1200
1201	/* Init an autosizing sbuf that initially holds 200 chars. */
1202	if ((s = sbuf_new(NULL, NULL, 200, SBUF_AUTOEXTEND)) == NULL)
1203		return (-1);
1204
1205	if (action == SIFTR_ENABLE) {
1206		/*
1207		 * Create our alq
1208		 * XXX: We should abort if alq_open fails!
1209		 */
1210		alq_open(&siftr_alq, siftr_logfile, curthread->td_ucred,
1211		    SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1212
1213		STAILQ_INIT(&pkt_queue);
1214
1215		DPCPU_ZERO(ss);
1216
1217		siftr_exit_pkt_manager_thread = 0;
1218
1219		ret = kthread_add(&siftr_pkt_manager_thread, NULL, NULL,
1220		    &siftr_pkt_manager_thr, RFNOWAIT, 0,
1221		    "siftr_pkt_manager_thr");
1222
1223		siftr_pfil(HOOK);
1224
1225		microtime(&tval);
1226
1227		sbuf_printf(s,
1228		    "enable_time_secs=%jd\tenable_time_usecs=%06ld\t"
1229		    "siftrver=%s\thz=%u\ttcp_rtt_scale=%u\tsysname=%s\t"
1230		    "sysver=%u\tipmode=%u\n",
1231		    (intmax_t)tval.tv_sec, tval.tv_usec, MODVERSION_STR, hz,
1232		    TCP_RTT_SCALE, SYS_NAME, __FreeBSD_version, SIFTR_IPMODE);
1233
1234		sbuf_finish(s);
1235		alq_writen(siftr_alq, sbuf_data(s), sbuf_len(s), ALQ_WAITOK);
1236
1237	} else if (action == SIFTR_DISABLE && siftr_pkt_manager_thr != NULL) {
1238		/*
1239		 * Remove the pfil hook functions. All threads currently in
1240		 * the hook functions are allowed to exit before siftr_pfil()
1241		 * returns.
1242		 */
1243		siftr_pfil(UNHOOK);
1244
1245		/* This will block until the pkt manager thread unlocks it. */
1246		mtx_lock(&siftr_pkt_mgr_mtx);
1247
1248		/* Tell the pkt manager thread that it should exit now. */
1249		siftr_exit_pkt_manager_thread = 1;
1250
1251		/*
1252		 * Wake the pkt_manager thread so it realises that
1253		 * siftr_exit_pkt_manager_thread == 1 and exits gracefully.
1254		 * The wakeup won't be delivered until we unlock
1255		 * siftr_pkt_mgr_mtx so this isn't racy.
1256		 */
1257		wakeup(&wait_for_pkt);
1258
1259		/* Wait for the pkt_manager thread to exit. */
1260		mtx_sleep(siftr_pkt_manager_thr, &siftr_pkt_mgr_mtx, PWAIT,
1261		    "thrwait", 0);
1262
1263		siftr_pkt_manager_thr = NULL;
1264		mtx_unlock(&siftr_pkt_mgr_mtx);
1265
1266		totalss.n_in = DPCPU_VARSUM(ss, n_in);
1267		totalss.n_out = DPCPU_VARSUM(ss, n_out);
1268		totalss.nskip_in_malloc = DPCPU_VARSUM(ss, nskip_in_malloc);
1269		totalss.nskip_out_malloc = DPCPU_VARSUM(ss, nskip_out_malloc);
1270		totalss.nskip_in_mtx = DPCPU_VARSUM(ss, nskip_in_mtx);
1271		totalss.nskip_out_mtx = DPCPU_VARSUM(ss, nskip_out_mtx);
1272		totalss.nskip_in_tcpcb = DPCPU_VARSUM(ss, nskip_in_tcpcb);
1273		totalss.nskip_out_tcpcb = DPCPU_VARSUM(ss, nskip_out_tcpcb);
1274		totalss.nskip_in_inpcb = DPCPU_VARSUM(ss, nskip_in_inpcb);
1275		totalss.nskip_out_inpcb = DPCPU_VARSUM(ss, nskip_out_inpcb);
1276
1277		total_skipped_pkts = totalss.nskip_in_malloc +
1278		    totalss.nskip_out_malloc + totalss.nskip_in_mtx +
1279		    totalss.nskip_out_mtx + totalss.nskip_in_tcpcb +
1280		    totalss.nskip_out_tcpcb + totalss.nskip_in_inpcb +
1281		    totalss.nskip_out_inpcb;
1282
1283		microtime(&tval);
1284
1285		sbuf_printf(s,
1286		    "disable_time_secs=%jd\tdisable_time_usecs=%06ld\t"
1287		    "num_inbound_tcp_pkts=%ju\tnum_outbound_tcp_pkts=%ju\t"
1288		    "total_tcp_pkts=%ju\tnum_inbound_skipped_pkts_malloc=%u\t"
1289		    "num_outbound_skipped_pkts_malloc=%u\t"
1290		    "num_inbound_skipped_pkts_mtx=%u\t"
1291		    "num_outbound_skipped_pkts_mtx=%u\t"
1292		    "num_inbound_skipped_pkts_tcpcb=%u\t"
1293		    "num_outbound_skipped_pkts_tcpcb=%u\t"
1294		    "num_inbound_skipped_pkts_inpcb=%u\t"
1295		    "num_outbound_skipped_pkts_inpcb=%u\t"
1296		    "total_skipped_tcp_pkts=%u\tflow_list=",
1297		    (intmax_t)tval.tv_sec,
1298		    tval.tv_usec,
1299		    (uintmax_t)totalss.n_in,
1300		    (uintmax_t)totalss.n_out,
1301		    (uintmax_t)(totalss.n_in + totalss.n_out),
1302		    totalss.nskip_in_malloc,
1303		    totalss.nskip_out_malloc,
1304		    totalss.nskip_in_mtx,
1305		    totalss.nskip_out_mtx,
1306		    totalss.nskip_in_tcpcb,
1307		    totalss.nskip_out_tcpcb,
1308		    totalss.nskip_in_inpcb,
1309		    totalss.nskip_out_inpcb,
1310		    total_skipped_pkts);
1311
1312		/*
1313		 * Iterate over the flow hash, printing a summary of each
1314		 * flow seen and freeing any malloc'd memory.
1315		 * The hash consists of an array of LISTs (man 3 queue).
1316		 */
1317		for (i = 0; i < siftr_hashmask; i++) {
1318			LIST_FOREACH_SAFE(counter, counter_hash + i, nodes,
1319			    tmp_counter) {
1320				key = counter->key;
1321				key_index = 1;
1322
1323				ipver = key[0];
1324
1325				memcpy(laddr, key + key_index, sizeof(laddr));
1326				key_index += sizeof(laddr);
1327				memcpy(&lport, key + key_index, sizeof(lport));
1328				key_index += sizeof(lport);
1329				memcpy(faddr, key + key_index, sizeof(faddr));
1330				key_index += sizeof(faddr);
1331				memcpy(&fport, key + key_index, sizeof(fport));
1332
1333#ifdef SIFTR_IPV6
1334				laddr[3] = ntohl(laddr[3]);
1335				faddr[3] = ntohl(faddr[3]);
1336
1337				if (ipver == INP_IPV6) {
1338					laddr[0] = ntohl(laddr[0]);
1339					laddr[1] = ntohl(laddr[1]);
1340					laddr[2] = ntohl(laddr[2]);
1341					faddr[0] = ntohl(faddr[0]);
1342					faddr[1] = ntohl(faddr[1]);
1343					faddr[2] = ntohl(faddr[2]);
1344
1345					sbuf_printf(s,
1346					    "%x:%x:%x:%x:%x:%x:%x:%x;%u-"
1347					    "%x:%x:%x:%x:%x:%x:%x:%x;%u,",
1348					    UPPER_SHORT(laddr[0]),
1349					    LOWER_SHORT(laddr[0]),
1350					    UPPER_SHORT(laddr[1]),
1351					    LOWER_SHORT(laddr[1]),
1352					    UPPER_SHORT(laddr[2]),
1353					    LOWER_SHORT(laddr[2]),
1354					    UPPER_SHORT(laddr[3]),
1355					    LOWER_SHORT(laddr[3]),
1356					    ntohs(lport),
1357					    UPPER_SHORT(faddr[0]),
1358					    LOWER_SHORT(faddr[0]),
1359					    UPPER_SHORT(faddr[1]),
1360					    LOWER_SHORT(faddr[1]),
1361					    UPPER_SHORT(faddr[2]),
1362					    LOWER_SHORT(faddr[2]),
1363					    UPPER_SHORT(faddr[3]),
1364					    LOWER_SHORT(faddr[3]),
1365					    ntohs(fport));
1366				} else {
1367					laddr[0] = FIRST_OCTET(laddr[3]);
1368					laddr[1] = SECOND_OCTET(laddr[3]);
1369					laddr[2] = THIRD_OCTET(laddr[3]);
1370					laddr[3] = FOURTH_OCTET(laddr[3]);
1371					faddr[0] = FIRST_OCTET(faddr[3]);
1372					faddr[1] = SECOND_OCTET(faddr[3]);
1373					faddr[2] = THIRD_OCTET(faddr[3]);
1374					faddr[3] = FOURTH_OCTET(faddr[3]);
1375#endif
1376					sbuf_printf(s,
1377					    "%u.%u.%u.%u;%u-%u.%u.%u.%u;%u,",
1378					    laddr[0],
1379					    laddr[1],
1380					    laddr[2],
1381					    laddr[3],
1382					    ntohs(lport),
1383					    faddr[0],
1384					    faddr[1],
1385					    faddr[2],
1386					    faddr[3],
1387					    ntohs(fport));
1388#ifdef SIFTR_IPV6
1389				}
1390#endif
1391
1392				free(counter, M_SIFTR_HASHNODE);
1393			}
1394
1395			LIST_INIT(counter_hash + i);
1396		}
1397
1398		sbuf_printf(s, "\n");
1399		sbuf_finish(s);
1400
1401		i = 0;
1402		do {
1403			bytes_to_write = min(SIFTR_ALQ_BUFLEN, sbuf_len(s)-i);
1404			alq_writen(siftr_alq, sbuf_data(s)+i, bytes_to_write, ALQ_WAITOK);
1405			i += bytes_to_write;
1406		} while (i < sbuf_len(s));
1407
1408		alq_close(siftr_alq);
1409		siftr_alq = NULL;
1410	}
1411
1412	sbuf_delete(s);
1413
1414	/*
1415	 * XXX: Should be using ret to check if any functions fail
1416	 * and set error appropriately
1417	 */
1418
1419	return (error);
1420}
1421
1422
1423static int
1424siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS)
1425{
1426	if (req->newptr == NULL)
1427		goto skip;
1428
1429	/* If the value passed in isn't 0 or 1, return an error. */
1430	if (CAST_PTR_INT(req->newptr) != 0 && CAST_PTR_INT(req->newptr) != 1)
1431		return (1);
1432
1433	/* If we are changing state (0 to 1 or 1 to 0). */
1434	if (CAST_PTR_INT(req->newptr) != siftr_enabled )
1435		if (siftr_manage_ops(CAST_PTR_INT(req->newptr))) {
1436			siftr_manage_ops(SIFTR_DISABLE);
1437			return (1);
1438		}
1439
1440skip:
1441	return (sysctl_handle_int(oidp, arg1, arg2, req));
1442}
1443
1444
1445static void
1446siftr_shutdown_handler(void *arg)
1447{
1448	siftr_manage_ops(SIFTR_DISABLE);
1449}
1450
1451
1452/*
1453 * Module is being unloaded or machine is shutting down. Take care of cleanup.
1454 */
1455static int
1456deinit_siftr(void)
1457{
1458	/* Cleanup. */
1459	siftr_manage_ops(SIFTR_DISABLE);
1460	hashdestroy(counter_hash, M_SIFTR, siftr_hashmask);
1461	mtx_destroy(&siftr_pkt_queue_mtx);
1462	mtx_destroy(&siftr_pkt_mgr_mtx);
1463
1464	return (0);
1465}
1466
1467
1468/*
1469 * Module has just been loaded into the kernel.
1470 */
1471static int
1472init_siftr(void)
1473{
1474	EVENTHANDLER_REGISTER(shutdown_pre_sync, siftr_shutdown_handler, NULL,
1475	    SHUTDOWN_PRI_FIRST);
1476
1477	/* Initialise our flow counter hash table. */
1478	counter_hash = hashinit(SIFTR_EXPECTED_MAX_TCP_FLOWS, M_SIFTR,
1479	    &siftr_hashmask);
1480
1481	mtx_init(&siftr_pkt_queue_mtx, "siftr_pkt_queue_mtx", NULL, MTX_DEF);
1482	mtx_init(&siftr_pkt_mgr_mtx, "siftr_pkt_mgr_mtx", NULL, MTX_DEF);
1483
1484	/* Print message to the user's current terminal. */
1485	uprintf("\nStatistical Information For TCP Research (SIFTR) %s\n"
1486	    "          http://caia.swin.edu.au/urp/newtcp\n\n",
1487	    MODVERSION_STR);
1488
1489	return (0);
1490}
1491
1492
1493/*
1494 * This is the function that is called to load and unload the module.
1495 * When the module is loaded, this function is called once with
1496 * "what" == MOD_LOAD
1497 * When the module is unloaded, this function is called twice with
1498 * "what" = MOD_QUIESCE first, followed by "what" = MOD_UNLOAD second
1499 * When the system is shut down e.g. CTRL-ALT-DEL or using the shutdown command,
1500 * this function is called once with "what" = MOD_SHUTDOWN
1501 * When the system is shut down, the handler isn't called until the very end
1502 * of the shutdown sequence i.e. after the disks have been synced.
1503 */
1504static int
1505siftr_load_handler(module_t mod, int what, void *arg)
1506{
1507	int ret;
1508
1509	switch (what) {
1510	case MOD_LOAD:
1511		ret = init_siftr();
1512		break;
1513
1514	case MOD_QUIESCE:
1515	case MOD_SHUTDOWN:
1516		ret = deinit_siftr();
1517		break;
1518
1519	case MOD_UNLOAD:
1520		ret = 0;
1521		break;
1522
1523	default:
1524		ret = EINVAL;
1525		break;
1526	}
1527
1528	return (ret);
1529}
1530
1531
1532static moduledata_t siftr_mod = {
1533	.name = "siftr",
1534	.evhand = siftr_load_handler,
1535};
1536
1537/*
1538 * Param 1: name of the kernel module
1539 * Param 2: moduledata_t struct containing info about the kernel module
1540 *          and the execution entry point for the module
1541 * Param 3: From sysinit_sub_id enumeration in /usr/include/sys/kernel.h
1542 *          Defines the module initialisation order
1543 * Param 4: From sysinit_elem_order enumeration in /usr/include/sys/kernel.h
1544 *          Defines the initialisation order of this kld relative to others
1545 *          within the same subsystem as defined by param 3
1546 */
1547DECLARE_MODULE(siftr, siftr_mod, SI_SUB_SMP, SI_ORDER_ANY);
1548MODULE_DEPEND(siftr, alq, 1, 1, 1);
1549MODULE_VERSION(siftr, MODVERSION);
1550