siftr.c revision 215552
1/*-
2 * Copyright (c) 2007-2009
3 * 	Swinburne University of Technology, Melbourne, Australia.
4 * Copyright (c) 2009-2010, The FreeBSD Foundation
5 * All rights reserved.
6 *
7 * Portions of this software were developed at the Centre for Advanced
8 * Internet Architectures, Swinburne University of Technology, Melbourne,
9 * Australia by Lawrence Stewart under sponsorship from the FreeBSD Foundation.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/******************************************************
34 * Statistical Information For TCP Research (SIFTR)
35 *
36 * A FreeBSD kernel module that adds very basic intrumentation to the
37 * TCP stack, allowing internal stats to be recorded to a log file
38 * for experimental, debugging and performance analysis purposes.
39 *
40 * SIFTR was first released in 2007 by James Healy and Lawrence Stewart whilst
41 * working on the NewTCP research project at Swinburne University's Centre for
42 * Advanced Internet Architectures, Melbourne, Australia, which was made
43 * possible in part by a grant from the Cisco University Research Program Fund
44 * at Community Foundation Silicon Valley. More details are available at:
45 *   http://caia.swin.edu.au/urp/newtcp/
46 *
47 * Work on SIFTR v1.2.x was sponsored by the FreeBSD Foundation as part of
48 * the "Enhancing the FreeBSD TCP Implementation" project 2008-2009.
49 * More details are available at:
50 *   http://www.freebsdfoundation.org/
51 *   http://caia.swin.edu.au/freebsd/etcp09/
52 *
53 * Lawrence Stewart is the current maintainer, and all contact regarding
54 * SIFTR should be directed to him via email: lastewart@swin.edu.au
55 *
56 * Initial release date: June 2007
57 * Most recent update: September 2010
58 ******************************************************/
59
60#include <sys/cdefs.h>
61__FBSDID("$FreeBSD: head/sys/netinet/siftr.c 215552 2010-11-20 07:36:43Z lstewart $");
62
63#include <sys/param.h>
64#include <sys/alq.h>
65#include <sys/errno.h>
66#include <sys/hash.h>
67#include <sys/kernel.h>
68#include <sys/kthread.h>
69#include <sys/lock.h>
70#include <sys/mbuf.h>
71#include <sys/module.h>
72#include <sys/mutex.h>
73#include <sys/pcpu.h>
74#include <sys/proc.h>
75#include <sys/sbuf.h>
76#include <sys/smp.h>
77#include <sys/socket.h>
78#include <sys/socketvar.h>
79#include <sys/sysctl.h>
80#include <sys/unistd.h>
81
82#include <net/if.h>
83#include <net/pfil.h>
84
85#include <netinet/in.h>
86#include <netinet/in_pcb.h>
87#include <netinet/in_systm.h>
88#include <netinet/in_var.h>
89#include <netinet/ip.h>
90#include <netinet/tcp_var.h>
91
92#ifdef SIFTR_IPV6
93#include <netinet/ip6.h>
94#include <netinet6/in6_pcb.h>
95#endif /* SIFTR_IPV6 */
96
97#include <machine/in_cksum.h>
98
99/*
100 * Three digit version number refers to X.Y.Z where:
101 * X is the major version number
102 * Y is bumped to mark backwards incompatible changes
103 * Z is bumped to mark backwards compatible changes
104 */
105#define V_MAJOR		1
106#define V_BACKBREAK	2
107#define V_BACKCOMPAT	4
108#define MODVERSION	__CONCAT(V_MAJOR, __CONCAT(V_BACKBREAK, V_BACKCOMPAT))
109#define MODVERSION_STR	__XSTRING(V_MAJOR) "." __XSTRING(V_BACKBREAK) "." \
110    __XSTRING(V_BACKCOMPAT)
111
112#define HOOK 0
113#define UNHOOK 1
114#define SIFTR_EXPECTED_MAX_TCP_FLOWS 65536
115#define SYS_NAME "FreeBSD"
116#define PACKET_TAG_SIFTR 100
117#define PACKET_COOKIE_SIFTR 21749576
118#define SIFTR_LOG_FILE_MODE 0644
119#define SIFTR_DISABLE 0
120#define SIFTR_ENABLE 1
121
122/*
123 * Hard upper limit on the length of log messages. Bump this up if you add new
124 * data fields such that the line length could exceed the below value.
125 */
126#define MAX_LOG_MSG_LEN 200
127/* XXX: Make this a sysctl tunable. */
128#define SIFTR_ALQ_BUFLEN (1000*MAX_LOG_MSG_LEN)
129
130/*
131 * 1 byte for IP version
132 * IPv4: src/dst IP (4+4) + src/dst port (2+2) = 12 bytes
133 * IPv6: src/dst IP (16+16) + src/dst port (2+2) = 36 bytes
134 */
135#ifdef SIFTR_IPV6
136#define FLOW_KEY_LEN 37
137#else
138#define FLOW_KEY_LEN 13
139#endif
140
141#ifdef SIFTR_IPV6
142#define SIFTR_IPMODE 6
143#else
144#define SIFTR_IPMODE 4
145#endif
146
147/* useful macros */
148#define CAST_PTR_INT(X) (*((int*)(X)))
149
150#define UPPER_SHORT(X)	(((X) & 0xFFFF0000) >> 16)
151#define LOWER_SHORT(X)	((X) & 0x0000FFFF)
152
153#define FIRST_OCTET(X)	(((X) & 0xFF000000) >> 24)
154#define SECOND_OCTET(X)	(((X) & 0x00FF0000) >> 16)
155#define THIRD_OCTET(X)	(((X) & 0x0000FF00) >> 8)
156#define FOURTH_OCTET(X)	((X) & 0x000000FF)
157
158MALLOC_DECLARE(M_SIFTR);
159MALLOC_DEFINE(M_SIFTR, "siftr", "dynamic memory used by SIFTR");
160
161MALLOC_DECLARE(M_SIFTR_PKTNODE);
162MALLOC_DEFINE(M_SIFTR_PKTNODE, "siftr_pktnode", "SIFTR pkt_node struct");
163
164MALLOC_DECLARE(M_SIFTR_HASHNODE);
165MALLOC_DEFINE(M_SIFTR_HASHNODE, "siftr_hashnode", "SIFTR flow_hash_node struct");
166
167/* Used as links in the pkt manager queue. */
168struct pkt_node {
169	/* Timestamp of pkt as noted in the pfil hook. */
170	struct timeval		tval;
171	/* Direction pkt is travelling; either PFIL_IN or PFIL_OUT. */
172	uint8_t			direction;
173	/* IP version pkt_node relates to; either INP_IPV4 or INP_IPV6. */
174	uint8_t			ipver;
175	/* Hash of the pkt which triggered the log message. */
176	uint32_t		hash;
177	/* Local/foreign IP address. */
178#ifdef SIFTR_IPV6
179	uint32_t		ip_laddr[4];
180	uint32_t		ip_faddr[4];
181#else
182	uint8_t			ip_laddr[4];
183	uint8_t			ip_faddr[4];
184#endif
185	/* Local TCP port. */
186	uint16_t		tcp_localport;
187	/* Foreign TCP port. */
188	uint16_t		tcp_foreignport;
189	/* Congestion Window (bytes). */
190	u_long			snd_cwnd;
191	/* Sending Window (bytes). */
192	u_long			snd_wnd;
193	/* Receive Window (bytes). */
194	u_long			rcv_wnd;
195	/* Unused (was: Bandwidth Controlled Window (bytes)). */
196	u_long			snd_bwnd;
197	/* Slow Start Threshold (bytes). */
198	u_long			snd_ssthresh;
199	/* Current state of the TCP FSM. */
200	int			conn_state;
201	/* Max Segment Size (bytes). */
202	u_int			max_seg_size;
203	/*
204	 * Smoothed RTT stored as found in the TCP control block
205	 * in units of (TCP_RTT_SCALE*hz).
206	 */
207	int			smoothed_rtt;
208	/* Is SACK enabled? */
209	u_char			sack_enabled;
210	/* Window scaling for snd window. */
211	u_char			snd_scale;
212	/* Window scaling for recv window. */
213	u_char			rcv_scale;
214	/* TCP control block flags. */
215	u_int			flags;
216	/* Retransmit timeout length. */
217	int			rxt_length;
218	/* Size of the TCP send buffer in bytes. */
219	u_int			snd_buf_hiwater;
220	/* Current num bytes in the send socket buffer. */
221	u_int			snd_buf_cc;
222	/* Size of the TCP receive buffer in bytes. */
223	u_int			rcv_buf_hiwater;
224	/* Current num bytes in the receive socket buffer. */
225	u_int			rcv_buf_cc;
226	/* Number of bytes inflight that we are waiting on ACKs for. */
227	u_int			sent_inflight_bytes;
228	/* Number of segments currently in the reassembly queue. */
229	int			t_segqlen;
230	/* Link to next pkt_node in the list. */
231	STAILQ_ENTRY(pkt_node)	nodes;
232};
233
234struct flow_hash_node
235{
236	uint16_t counter;
237	uint8_t key[FLOW_KEY_LEN];
238	LIST_ENTRY(flow_hash_node) nodes;
239};
240
241struct siftr_stats
242{
243	/* # TCP pkts seen by the SIFTR PFIL hooks, including any skipped. */
244	uint64_t n_in;
245	uint64_t n_out;
246	/* # pkts skipped due to failed malloc calls. */
247	uint32_t nskip_in_malloc;
248	uint32_t nskip_out_malloc;
249	/* # pkts skipped due to failed mtx acquisition. */
250	uint32_t nskip_in_mtx;
251	uint32_t nskip_out_mtx;
252	/* # pkts skipped due to failed inpcb lookups. */
253	uint32_t nskip_in_inpcb;
254	uint32_t nskip_out_inpcb;
255	/* # pkts skipped due to failed tcpcb lookups. */
256	uint32_t nskip_in_tcpcb;
257	uint32_t nskip_out_tcpcb;
258	/* # pkts skipped due to stack reinjection. */
259	uint32_t nskip_in_dejavu;
260	uint32_t nskip_out_dejavu;
261};
262
263STATIC_DPCPU_DEFINE(struct siftr_stats, ss);
264
265static volatile unsigned int siftr_exit_pkt_manager_thread = 0;
266static unsigned int siftr_enabled = 0;
267static unsigned int siftr_pkts_per_log = 1;
268static unsigned int siftr_generate_hashes = 0;
269/* static unsigned int siftr_binary_log = 0; */
270static char siftr_logfile[PATH_MAX] = "/var/log/siftr.log";
271static u_long siftr_hashmask;
272STAILQ_HEAD(pkthead, pkt_node) pkt_queue = STAILQ_HEAD_INITIALIZER(pkt_queue);
273LIST_HEAD(listhead, flow_hash_node) *counter_hash;
274static int wait_for_pkt;
275static struct alq *siftr_alq = NULL;
276static struct mtx siftr_pkt_queue_mtx;
277static struct mtx siftr_pkt_mgr_mtx;
278static struct thread *siftr_pkt_manager_thr = NULL;
279/*
280 * pfil.h defines PFIL_IN as 1 and PFIL_OUT as 2,
281 * which we use as an index into this array.
282 */
283static char direction[3] = {'\0', 'i','o'};
284
285/* Required function prototypes. */
286static int siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS);
287static int siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS);
288
289
290/* Declare the net.inet.siftr sysctl tree and populate it. */
291
292SYSCTL_DECL(_net_inet_siftr);
293
294SYSCTL_NODE(_net_inet, OID_AUTO, siftr, CTLFLAG_RW, NULL,
295    "siftr related settings");
296
297SYSCTL_PROC(_net_inet_siftr, OID_AUTO, enabled, CTLTYPE_UINT|CTLFLAG_RW,
298    &siftr_enabled, 0, &siftr_sysctl_enabled_handler, "IU",
299    "switch siftr module operations on/off");
300
301SYSCTL_PROC(_net_inet_siftr, OID_AUTO, logfile, CTLTYPE_STRING|CTLFLAG_RW,
302    &siftr_logfile, sizeof(siftr_logfile), &siftr_sysctl_logfile_name_handler,
303    "A", "file to save siftr log messages to");
304
305SYSCTL_UINT(_net_inet_siftr, OID_AUTO, ppl, CTLFLAG_RW,
306    &siftr_pkts_per_log, 1,
307    "number of packets between generating a log message");
308
309SYSCTL_UINT(_net_inet_siftr, OID_AUTO, genhashes, CTLFLAG_RW,
310    &siftr_generate_hashes, 0,
311    "enable packet hash generation");
312
313/* XXX: TODO
314SYSCTL_UINT(_net_inet_siftr, OID_AUTO, binary, CTLFLAG_RW,
315    &siftr_binary_log, 0,
316    "write log files in binary instead of ascii");
317*/
318
319
320/* Begin functions. */
321
322static void
323siftr_process_pkt(struct pkt_node * pkt_node)
324{
325	struct flow_hash_node *hash_node;
326	struct listhead *counter_list;
327	struct siftr_stats *ss;
328	struct ale *log_buf;
329	uint8_t key[FLOW_KEY_LEN];
330	uint8_t found_match, key_offset;
331
332	hash_node = NULL;
333	ss = DPCPU_PTR(ss);
334	found_match = 0;
335	key_offset = 1;
336
337	/*
338	 * Create the key that will be used to create a hash index
339	 * into our hash table. Our key consists of:
340	 * ipversion, localip, localport, foreignip, foreignport
341	 */
342	key[0] = pkt_node->ipver;
343	memcpy(key + key_offset, &pkt_node->ip_laddr,
344	    sizeof(pkt_node->ip_laddr));
345	key_offset += sizeof(pkt_node->ip_laddr);
346	memcpy(key + key_offset, &pkt_node->tcp_localport,
347	    sizeof(pkt_node->tcp_localport));
348	key_offset += sizeof(pkt_node->tcp_localport);
349	memcpy(key + key_offset, &pkt_node->ip_faddr,
350	    sizeof(pkt_node->ip_faddr));
351	key_offset += sizeof(pkt_node->ip_faddr);
352	memcpy(key + key_offset, &pkt_node->tcp_foreignport,
353	    sizeof(pkt_node->tcp_foreignport));
354
355	counter_list = counter_hash +
356	    (hash32_buf(key, sizeof(key), 0) & siftr_hashmask);
357
358	/*
359	 * If the list is not empty i.e. the hash index has
360	 * been used by another flow previously.
361	 */
362	if (LIST_FIRST(counter_list) != NULL) {
363		/*
364		 * Loop through the hash nodes in the list.
365		 * There should normally only be 1 hash node in the list,
366		 * except if there have been collisions at the hash index
367		 * computed by hash32_buf().
368		 */
369		LIST_FOREACH(hash_node, counter_list, nodes) {
370			/*
371			 * Check if the key for the pkt we are currently
372			 * processing is the same as the key stored in the
373			 * hash node we are currently processing.
374			 * If they are the same, then we've found the
375			 * hash node that stores the counter for the flow
376			 * the pkt belongs to.
377			 */
378			if (memcmp(hash_node->key, key, sizeof(key)) == 0) {
379				found_match = 1;
380				break;
381			}
382		}
383	}
384
385	/* If this flow hash hasn't been seen before or we have a collision. */
386	if (hash_node == NULL || !found_match) {
387		/* Create a new hash node to store the flow's counter. */
388		hash_node = malloc(sizeof(struct flow_hash_node),
389		    M_SIFTR_HASHNODE, M_WAITOK);
390
391		if (hash_node != NULL) {
392			/* Initialise our new hash node list entry. */
393			hash_node->counter = 0;
394			memcpy(hash_node->key, key, sizeof(key));
395			LIST_INSERT_HEAD(counter_list, hash_node, nodes);
396		} else {
397			/* Malloc failed. */
398			if (pkt_node->direction == PFIL_IN)
399				ss->nskip_in_malloc++;
400			else
401				ss->nskip_out_malloc++;
402
403			return;
404		}
405	} else if (siftr_pkts_per_log > 1) {
406		/*
407		 * Taking the remainder of the counter divided
408		 * by the current value of siftr_pkts_per_log
409		 * and storing that in counter provides a neat
410		 * way to modulate the frequency of log
411		 * messages being written to the log file.
412		 */
413		hash_node->counter = (hash_node->counter + 1) %
414		    siftr_pkts_per_log;
415
416		/*
417		 * If we have not seen enough packets since the last time
418		 * we wrote a log message for this connection, return.
419		 */
420		if (hash_node->counter > 0)
421			return;
422	}
423
424	log_buf = alq_getn(siftr_alq, MAX_LOG_MSG_LEN, ALQ_WAITOK);
425
426	if (log_buf == NULL)
427		return; /* Should only happen if the ALQ is shutting down. */
428
429#ifdef SIFTR_IPV6
430	pkt_node->ip_laddr[3] = ntohl(pkt_node->ip_laddr[3]);
431	pkt_node->ip_faddr[3] = ntohl(pkt_node->ip_faddr[3]);
432
433	if (pkt_node->ipver == INP_IPV6) { /* IPv6 packet */
434		pkt_node->ip_laddr[0] = ntohl(pkt_node->ip_laddr[0]);
435		pkt_node->ip_laddr[1] = ntohl(pkt_node->ip_laddr[1]);
436		pkt_node->ip_laddr[2] = ntohl(pkt_node->ip_laddr[2]);
437		pkt_node->ip_faddr[0] = ntohl(pkt_node->ip_faddr[0]);
438		pkt_node->ip_faddr[1] = ntohl(pkt_node->ip_faddr[1]);
439		pkt_node->ip_faddr[2] = ntohl(pkt_node->ip_faddr[2]);
440
441		/* Construct an IPv6 log message. */
442		log_buf->ae_bytesused = snprintf(log_buf->ae_data,
443		    MAX_LOG_MSG_LEN,
444		    "%c,0x%08x,%zd.%06ld,%x:%x:%x:%x:%x:%x:%x:%x,%u,%x:%x:%x:"
445		    "%x:%x:%x:%x:%x,%u,%ld,%ld,%ld,%ld,%ld,%u,%u,%u,%u,%u,%u,"
446		    "%u,%d,%u,%u,%u,%u,%u,%u\n",
447		    direction[pkt_node->direction],
448		    pkt_node->hash,
449		    pkt_node->tval.tv_sec,
450		    pkt_node->tval.tv_usec,
451		    UPPER_SHORT(pkt_node->ip_laddr[0]),
452		    LOWER_SHORT(pkt_node->ip_laddr[0]),
453		    UPPER_SHORT(pkt_node->ip_laddr[1]),
454		    LOWER_SHORT(pkt_node->ip_laddr[1]),
455		    UPPER_SHORT(pkt_node->ip_laddr[2]),
456		    LOWER_SHORT(pkt_node->ip_laddr[2]),
457		    UPPER_SHORT(pkt_node->ip_laddr[3]),
458		    LOWER_SHORT(pkt_node->ip_laddr[3]),
459		    ntohs(pkt_node->tcp_localport),
460		    UPPER_SHORT(pkt_node->ip_faddr[0]),
461		    LOWER_SHORT(pkt_node->ip_faddr[0]),
462		    UPPER_SHORT(pkt_node->ip_faddr[1]),
463		    LOWER_SHORT(pkt_node->ip_faddr[1]),
464		    UPPER_SHORT(pkt_node->ip_faddr[2]),
465		    LOWER_SHORT(pkt_node->ip_faddr[2]),
466		    UPPER_SHORT(pkt_node->ip_faddr[3]),
467		    LOWER_SHORT(pkt_node->ip_faddr[3]),
468		    ntohs(pkt_node->tcp_foreignport),
469		    pkt_node->snd_ssthresh,
470		    pkt_node->snd_cwnd,
471		    pkt_node->snd_bwnd,
472		    pkt_node->snd_wnd,
473		    pkt_node->rcv_wnd,
474		    pkt_node->snd_scale,
475		    pkt_node->rcv_scale,
476		    pkt_node->conn_state,
477		    pkt_node->max_seg_size,
478		    pkt_node->smoothed_rtt,
479		    pkt_node->sack_enabled,
480		    pkt_node->flags,
481		    pkt_node->rxt_length,
482		    pkt_node->snd_buf_hiwater,
483		    pkt_node->snd_buf_cc,
484		    pkt_node->rcv_buf_hiwater,
485		    pkt_node->rcv_buf_cc,
486		    pkt_node->sent_inflight_bytes,
487		    pkt_node->t_segqlen);
488	} else { /* IPv4 packet */
489		pkt_node->ip_laddr[0] = FIRST_OCTET(pkt_node->ip_laddr[3]);
490		pkt_node->ip_laddr[1] = SECOND_OCTET(pkt_node->ip_laddr[3]);
491		pkt_node->ip_laddr[2] = THIRD_OCTET(pkt_node->ip_laddr[3]);
492		pkt_node->ip_laddr[3] = FOURTH_OCTET(pkt_node->ip_laddr[3]);
493		pkt_node->ip_faddr[0] = FIRST_OCTET(pkt_node->ip_faddr[3]);
494		pkt_node->ip_faddr[1] = SECOND_OCTET(pkt_node->ip_faddr[3]);
495		pkt_node->ip_faddr[2] = THIRD_OCTET(pkt_node->ip_faddr[3]);
496		pkt_node->ip_faddr[3] = FOURTH_OCTET(pkt_node->ip_faddr[3]);
497#endif /* SIFTR_IPV6 */
498
499		/* Construct an IPv4 log message. */
500		log_buf->ae_bytesused = snprintf(log_buf->ae_data,
501		    MAX_LOG_MSG_LEN,
502		    "%c,0x%08x,%jd.%06ld,%u.%u.%u.%u,%u,%u.%u.%u.%u,%u,%ld,%ld,"
503		    "%ld,%ld,%ld,%u,%u,%u,%u,%u,%u,%u,%d,%u,%u,%u,%u,%u,%u\n",
504		    direction[pkt_node->direction],
505		    pkt_node->hash,
506		    (intmax_t)pkt_node->tval.tv_sec,
507		    pkt_node->tval.tv_usec,
508		    pkt_node->ip_laddr[0],
509		    pkt_node->ip_laddr[1],
510		    pkt_node->ip_laddr[2],
511		    pkt_node->ip_laddr[3],
512		    ntohs(pkt_node->tcp_localport),
513		    pkt_node->ip_faddr[0],
514		    pkt_node->ip_faddr[1],
515		    pkt_node->ip_faddr[2],
516		    pkt_node->ip_faddr[3],
517		    ntohs(pkt_node->tcp_foreignport),
518		    pkt_node->snd_ssthresh,
519		    pkt_node->snd_cwnd,
520		    pkt_node->snd_bwnd,
521		    pkt_node->snd_wnd,
522		    pkt_node->rcv_wnd,
523		    pkt_node->snd_scale,
524		    pkt_node->rcv_scale,
525		    pkt_node->conn_state,
526		    pkt_node->max_seg_size,
527		    pkt_node->smoothed_rtt,
528		    pkt_node->sack_enabled,
529		    pkt_node->flags,
530		    pkt_node->rxt_length,
531		    pkt_node->snd_buf_hiwater,
532		    pkt_node->snd_buf_cc,
533		    pkt_node->rcv_buf_hiwater,
534		    pkt_node->rcv_buf_cc,
535		    pkt_node->sent_inflight_bytes,
536		    pkt_node->t_segqlen);
537#ifdef SIFTR_IPV6
538	}
539#endif
540
541	alq_post_flags(siftr_alq, log_buf, 0);
542}
543
544
545static void
546siftr_pkt_manager_thread(void *arg)
547{
548	STAILQ_HEAD(pkthead, pkt_node) tmp_pkt_queue =
549	    STAILQ_HEAD_INITIALIZER(tmp_pkt_queue);
550	struct pkt_node *pkt_node, *pkt_node_temp;
551	uint8_t draining;
552
553	draining = 2;
554
555	mtx_lock(&siftr_pkt_mgr_mtx);
556
557	/* draining == 0 when queue has been flushed and it's safe to exit. */
558	while (draining) {
559		/*
560		 * Sleep until we are signalled to wake because thread has
561		 * been told to exit or until 1 tick has passed.
562		 */
563		mtx_sleep(&wait_for_pkt, &siftr_pkt_mgr_mtx, PWAIT, "pktwait",
564		    1);
565
566		/* Gain exclusive access to the pkt_node queue. */
567		mtx_lock(&siftr_pkt_queue_mtx);
568
569		/*
570		 * Move pkt_queue to tmp_pkt_queue, which leaves
571		 * pkt_queue empty and ready to receive more pkt_nodes.
572		 */
573		STAILQ_CONCAT(&tmp_pkt_queue, &pkt_queue);
574
575		/*
576		 * We've finished making changes to the list. Unlock it
577		 * so the pfil hooks can continue queuing pkt_nodes.
578		 */
579		mtx_unlock(&siftr_pkt_queue_mtx);
580
581		/*
582		 * We can't hold a mutex whilst calling siftr_process_pkt
583		 * because ALQ might sleep waiting for buffer space.
584		 */
585		mtx_unlock(&siftr_pkt_mgr_mtx);
586
587		/* Flush all pkt_nodes to the log file. */
588		STAILQ_FOREACH_SAFE(pkt_node, &tmp_pkt_queue, nodes,
589		    pkt_node_temp) {
590			siftr_process_pkt(pkt_node);
591			STAILQ_REMOVE_HEAD(&tmp_pkt_queue, nodes);
592			free(pkt_node, M_SIFTR_PKTNODE);
593		}
594
595		KASSERT(STAILQ_EMPTY(&tmp_pkt_queue),
596		    ("SIFTR tmp_pkt_queue not empty after flush"));
597
598		mtx_lock(&siftr_pkt_mgr_mtx);
599
600		/*
601		 * If siftr_exit_pkt_manager_thread gets set during the window
602		 * where we are draining the tmp_pkt_queue above, there might
603		 * still be pkts in pkt_queue that need to be drained.
604		 * Allow one further iteration to occur after
605		 * siftr_exit_pkt_manager_thread has been set to ensure
606		 * pkt_queue is completely empty before we kill the thread.
607		 *
608		 * siftr_exit_pkt_manager_thread is set only after the pfil
609		 * hooks have been removed, so only 1 extra iteration
610		 * is needed to drain the queue.
611		 */
612		if (siftr_exit_pkt_manager_thread)
613			draining--;
614	}
615
616	mtx_unlock(&siftr_pkt_mgr_mtx);
617
618	/* Calls wakeup on this thread's struct thread ptr. */
619	kthread_exit();
620}
621
622
623static uint32_t
624hash_pkt(struct mbuf *m, uint32_t offset)
625{
626	uint32_t hash;
627
628	hash = 0;
629
630	while (m != NULL && offset > m->m_len) {
631		/*
632		 * The IP packet payload does not start in this mbuf, so
633		 * need to figure out which mbuf it starts in and what offset
634		 * into the mbuf's data region the payload starts at.
635		 */
636		offset -= m->m_len;
637		m = m->m_next;
638	}
639
640	while (m != NULL) {
641		/* Ensure there is data in the mbuf */
642		if ((m->m_len - offset) > 0)
643			hash = hash32_buf(m->m_data + offset,
644			    m->m_len - offset, hash);
645
646		m = m->m_next;
647		offset = 0;
648        }
649
650	return (hash);
651}
652
653
654/*
655 * Check if a given mbuf has the SIFTR mbuf tag. If it does, log the fact that
656 * it's a reinjected packet and return. If it doesn't, tag the mbuf and return.
657 * Return value >0 means the caller should skip processing this mbuf.
658 */
659static inline int
660siftr_chkreinject(struct mbuf *m, int dir, struct siftr_stats *ss)
661{
662	if (m_tag_locate(m, PACKET_COOKIE_SIFTR, PACKET_TAG_SIFTR, NULL)
663	    != NULL) {
664		if (dir == PFIL_IN)
665			ss->nskip_in_dejavu++;
666		else
667			ss->nskip_out_dejavu++;
668
669		return (1);
670	} else {
671		struct m_tag *tag = m_tag_alloc(PACKET_COOKIE_SIFTR,
672		    PACKET_TAG_SIFTR, 0, M_NOWAIT);
673		if (tag == NULL) {
674			if (dir == PFIL_IN)
675				ss->nskip_in_malloc++;
676			else
677				ss->nskip_out_malloc++;
678
679			return (1);
680		}
681
682		m_tag_prepend(m, tag);
683	}
684
685	return (0);
686}
687
688
689/*
690 * Look up an inpcb for a packet. Return the inpcb pointer if found, or NULL
691 * otherwise.
692 */
693static inline struct inpcb *
694siftr_findinpcb(int ipver, struct ip *ip, struct mbuf *m, uint16_t sport,
695    uint16_t dport, int dir, struct siftr_stats *ss)
696{
697	struct inpcb *inp;
698
699	/* We need the tcbinfo lock. */
700	INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
701	INP_INFO_RLOCK(&V_tcbinfo);
702
703	if (dir == PFIL_IN)
704		inp = (ipver == INP_IPV4 ?
705		    in_pcblookup_hash(&V_tcbinfo, ip->ip_src, sport, ip->ip_dst,
706		    dport, 0, m->m_pkthdr.rcvif)
707		    :
708#ifdef SIFTR_IPV6
709		    in6_pcblookup_hash(&V_tcbinfo,
710		    &((struct ip6_hdr *)ip)->ip6_src, sport,
711		    &((struct ip6_hdr *)ip)->ip6_dst, dport, 0,
712		    m->m_pkthdr.rcvif)
713#else
714		    NULL
715#endif
716		    );
717
718	else
719		inp = (ipver == INP_IPV4 ?
720		    in_pcblookup_hash(&V_tcbinfo, ip->ip_dst, dport, ip->ip_src,
721		    sport, 0, m->m_pkthdr.rcvif)
722		    :
723#ifdef SIFTR_IPV6
724		    in6_pcblookup_hash(&V_tcbinfo,
725		    &((struct ip6_hdr *)ip)->ip6_dst, dport,
726		    &((struct ip6_hdr *)ip)->ip6_src, sport, 0,
727		    m->m_pkthdr.rcvif)
728#else
729		    NULL
730#endif
731		    );
732
733	/* If we can't find the inpcb, bail. */
734	if (inp == NULL) {
735		if (dir == PFIL_IN)
736			ss->nskip_in_inpcb++;
737		else
738			ss->nskip_out_inpcb++;
739
740		INP_INFO_RUNLOCK(&V_tcbinfo);
741	} else {
742		/* Acquire the inpcb lock. */
743		INP_UNLOCK_ASSERT(inp);
744		INP_RLOCK(inp);
745		INP_INFO_RUNLOCK(&V_tcbinfo);
746	}
747
748	return (inp);
749}
750
751
752static inline void
753siftr_siftdata(struct pkt_node *pn, struct inpcb *inp, struct tcpcb *tp,
754    int ipver, int dir, int inp_locally_locked)
755{
756#ifdef SIFTR_IPV6
757	if (ipver == INP_IPV4) {
758		pn->ip_laddr[3] = inp->inp_laddr.s_addr;
759		pn->ip_faddr[3] = inp->inp_faddr.s_addr;
760#else
761		*((uint32_t *)pn->ip_laddr) = inp->inp_laddr.s_addr;
762		*((uint32_t *)pn->ip_faddr) = inp->inp_faddr.s_addr;
763#endif
764#ifdef SIFTR_IPV6
765	} else {
766		pn->ip_laddr[0] = inp->in6p_laddr.s6_addr32[0];
767		pn->ip_laddr[1] = inp->in6p_laddr.s6_addr32[1];
768		pn->ip_laddr[2] = inp->in6p_laddr.s6_addr32[2];
769		pn->ip_laddr[3] = inp->in6p_laddr.s6_addr32[3];
770		pn->ip_faddr[0] = inp->in6p_faddr.s6_addr32[0];
771		pn->ip_faddr[1] = inp->in6p_faddr.s6_addr32[1];
772		pn->ip_faddr[2] = inp->in6p_faddr.s6_addr32[2];
773		pn->ip_faddr[3] = inp->in6p_faddr.s6_addr32[3];
774	}
775#endif
776	pn->tcp_localport = inp->inp_lport;
777	pn->tcp_foreignport = inp->inp_fport;
778	pn->snd_cwnd = tp->snd_cwnd;
779	pn->snd_wnd = tp->snd_wnd;
780	pn->rcv_wnd = tp->rcv_wnd;
781	pn->snd_bwnd = 0;		/* Unused, kept for compat. */
782	pn->snd_ssthresh = tp->snd_ssthresh;
783	pn->snd_scale = tp->snd_scale;
784	pn->rcv_scale = tp->rcv_scale;
785	pn->conn_state = tp->t_state;
786	pn->max_seg_size = tp->t_maxseg;
787	pn->smoothed_rtt = tp->t_srtt;
788	pn->sack_enabled = (tp->t_flags & TF_SACK_PERMIT) != 0;
789	pn->flags = tp->t_flags;
790	pn->rxt_length = tp->t_rxtcur;
791	pn->snd_buf_hiwater = inp->inp_socket->so_snd.sb_hiwat;
792	pn->snd_buf_cc = inp->inp_socket->so_snd.sb_cc;
793	pn->rcv_buf_hiwater = inp->inp_socket->so_rcv.sb_hiwat;
794	pn->rcv_buf_cc = inp->inp_socket->so_rcv.sb_cc;
795	pn->sent_inflight_bytes = tp->snd_max - tp->snd_una;
796	pn->t_segqlen = tp->t_segqlen;
797
798	/* We've finished accessing the tcb so release the lock. */
799	if (inp_locally_locked)
800		INP_RUNLOCK(inp);
801
802	pn->ipver = ipver;
803	pn->direction = dir;
804
805	/*
806	 * Significantly more accurate than using getmicrotime(), but slower!
807	 * Gives true microsecond resolution at the expense of a hit to
808	 * maximum pps throughput processing when SIFTR is loaded and enabled.
809	 */
810	microtime(&pn->tval);
811}
812
813
814/*
815 * pfil hook that is called for each IPv4 packet making its way through the
816 * stack in either direction.
817 * The pfil subsystem holds a non-sleepable mutex somewhere when
818 * calling our hook function, so we can't sleep at all.
819 * It's very important to use the M_NOWAIT flag with all function calls
820 * that support it so that they won't sleep, otherwise you get a panic.
821 */
822static int
823siftr_chkpkt(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
824    struct inpcb *inp)
825{
826	struct pkt_node *pn;
827	struct ip *ip;
828	struct tcphdr *th;
829	struct tcpcb *tp;
830	struct siftr_stats *ss;
831	unsigned int ip_hl;
832	int inp_locally_locked;
833
834	inp_locally_locked = 0;
835	ss = DPCPU_PTR(ss);
836
837	/*
838	 * m_pullup is not required here because ip_{input|output}
839	 * already do the heavy lifting for us.
840	 */
841
842	ip = mtod(*m, struct ip *);
843
844	/* Only continue processing if the packet is TCP. */
845	if (ip->ip_p != IPPROTO_TCP)
846		goto ret;
847
848	/*
849	 * If a kernel subsystem reinjects packets into the stack, our pfil
850	 * hook will be called multiple times for the same packet.
851	 * Make sure we only process unique packets.
852	 */
853	if (siftr_chkreinject(*m, dir, ss))
854		goto ret;
855
856	if (dir == PFIL_IN)
857		ss->n_in++;
858	else
859		ss->n_out++;
860
861	/*
862	 * Create a tcphdr struct starting at the correct offset
863	 * in the IP packet. ip->ip_hl gives the ip header length
864	 * in 4-byte words, so multiply it to get the size in bytes.
865	 */
866	ip_hl = (ip->ip_hl << 2);
867	th = (struct tcphdr *)((caddr_t)ip + ip_hl);
868
869	/*
870	 * If the pfil hooks don't provide a pointer to the
871	 * inpcb, we need to find it ourselves and lock it.
872	 */
873	if (!inp) {
874		/* Find the corresponding inpcb for this pkt. */
875		inp = siftr_findinpcb(INP_IPV4, ip, *m, th->th_sport,
876		    th->th_dport, dir, ss);
877
878		if (inp == NULL)
879			goto ret;
880		else
881			inp_locally_locked = 1;
882	}
883
884	INP_LOCK_ASSERT(inp);
885
886	/* Find the TCP control block that corresponds with this packet */
887	tp = intotcpcb(inp);
888
889	/*
890	 * If we can't find the TCP control block (happens occasionaly for a
891	 * packet sent during the shutdown phase of a TCP connection),
892	 * or we're in the timewait state, bail
893	 */
894	if (tp == NULL || inp->inp_flags & INP_TIMEWAIT) {
895		if (dir == PFIL_IN)
896			ss->nskip_in_tcpcb++;
897		else
898			ss->nskip_out_tcpcb++;
899
900		goto inp_unlock;
901	}
902
903	pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
904
905	if (pn == NULL) {
906		if (dir == PFIL_IN)
907			ss->nskip_in_malloc++;
908		else
909			ss->nskip_out_malloc++;
910
911		goto inp_unlock;
912	}
913
914	siftr_siftdata(pn, inp, tp, INP_IPV4, dir, inp_locally_locked);
915
916	if (siftr_generate_hashes) {
917		if ((*m)->m_pkthdr.csum_flags & CSUM_TCP) {
918			/*
919			 * For outbound packets, the TCP checksum isn't
920			 * calculated yet. This is a problem for our packet
921			 * hashing as the receiver will calc a different hash
922			 * to ours if we don't include the correct TCP checksum
923			 * in the bytes being hashed. To work around this
924			 * problem, we manually calc the TCP checksum here in
925			 * software. We unset the CSUM_TCP flag so the lower
926			 * layers don't recalc it.
927			 */
928			(*m)->m_pkthdr.csum_flags &= ~CSUM_TCP;
929
930			/*
931			 * Calculate the TCP checksum in software and assign
932			 * to correct TCP header field, which will follow the
933			 * packet mbuf down the stack. The trick here is that
934			 * tcp_output() sets th->th_sum to the checksum of the
935			 * pseudo header for us already. Because of the nature
936			 * of the checksumming algorithm, we can sum over the
937			 * entire IP payload (i.e. TCP header and data), which
938			 * will include the already calculated pseduo header
939			 * checksum, thus giving us the complete TCP checksum.
940			 *
941			 * To put it in simple terms, if checksum(1,2,3,4)=10,
942			 * then checksum(1,2,3,4,5) == checksum(10,5).
943			 * This property is what allows us to "cheat" and
944			 * checksum only the IP payload which has the TCP
945			 * th_sum field populated with the pseudo header's
946			 * checksum, and not need to futz around checksumming
947			 * pseudo header bytes and TCP header/data in one hit.
948			 * Refer to RFC 1071 for more info.
949			 *
950			 * NB: in_cksum_skip(struct mbuf *m, int len, int skip)
951			 * in_cksum_skip 2nd argument is NOT the number of
952			 * bytes to read from the mbuf at "skip" bytes offset
953			 * from the start of the mbuf (very counter intuitive!).
954			 * The number of bytes to read is calculated internally
955			 * by the function as len-skip i.e. to sum over the IP
956			 * payload (TCP header + data) bytes, it is INCORRECT
957			 * to call the function like this:
958			 * in_cksum_skip(at, ip->ip_len - offset, offset)
959			 * Rather, it should be called like this:
960			 * in_cksum_skip(at, ip->ip_len, offset)
961			 * which means read "ip->ip_len - offset" bytes from
962			 * the mbuf cluster "at" at offset "offset" bytes from
963			 * the beginning of the "at" mbuf's data pointer.
964			 */
965			th->th_sum = in_cksum_skip(*m, ip->ip_len, ip_hl);
966		}
967
968		/*
969		 * XXX: Having to calculate the checksum in software and then
970		 * hash over all bytes is really inefficient. Would be nice to
971		 * find a way to create the hash and checksum in the same pass
972		 * over the bytes.
973		 */
974		pn->hash = hash_pkt(*m, ip_hl);
975	}
976
977	mtx_lock(&siftr_pkt_queue_mtx);
978	STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
979	mtx_unlock(&siftr_pkt_queue_mtx);
980	goto ret;
981
982inp_unlock:
983	if (inp_locally_locked)
984		INP_RUNLOCK(inp);
985
986ret:
987	/* Returning 0 ensures pfil will not discard the pkt */
988	return (0);
989}
990
991
992#ifdef SIFTR_IPV6
993static int
994siftr_chkpkt6(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
995    struct inpcb *inp)
996{
997	struct pkt_node *pn;
998	struct ip6_hdr *ip6;
999	struct tcphdr *th;
1000	struct tcpcb *tp;
1001	struct siftr_stats *ss;
1002	unsigned int ip6_hl;
1003	int inp_locally_locked;
1004
1005	inp_locally_locked = 0;
1006	ss = DPCPU_PTR(ss);
1007
1008	/*
1009	 * m_pullup is not required here because ip6_{input|output}
1010	 * already do the heavy lifting for us.
1011	 */
1012
1013	ip6 = mtod(*m, struct ip6_hdr *);
1014
1015	/*
1016	 * Only continue processing if the packet is TCP
1017	 * XXX: We should follow the next header fields
1018	 * as shown on Pg 6 RFC 2460, but right now we'll
1019	 * only check pkts that have no extension headers.
1020	 */
1021	if (ip6->ip6_nxt != IPPROTO_TCP)
1022		goto ret6;
1023
1024	/*
1025	 * If a kernel subsystem reinjects packets into the stack, our pfil
1026	 * hook will be called multiple times for the same packet.
1027	 * Make sure we only process unique packets.
1028	 */
1029	if (siftr_chkreinject(*m, dir, ss))
1030		goto ret6;
1031
1032	if (dir == PFIL_IN)
1033		ss->n_in++;
1034	else
1035		ss->n_out++;
1036
1037	ip6_hl = sizeof(struct ip6_hdr);
1038
1039	/*
1040	 * Create a tcphdr struct starting at the correct offset
1041	 * in the ipv6 packet. ip->ip_hl gives the ip header length
1042	 * in 4-byte words, so multiply it to get the size in bytes.
1043	 */
1044	th = (struct tcphdr *)((caddr_t)ip6 + ip6_hl);
1045
1046	/*
1047	 * For inbound packets, the pfil hooks don't provide a pointer to the
1048	 * inpcb, so we need to find it ourselves and lock it.
1049	 */
1050	if (!inp) {
1051		/* Find the corresponding inpcb for this pkt. */
1052		inp = siftr_findinpcb(INP_IPV6, (struct ip *)ip6, *m,
1053		    th->th_sport, th->th_dport, dir, ss);
1054
1055		if (inp == NULL)
1056			goto ret6;
1057		else
1058			inp_locally_locked = 1;
1059	}
1060
1061	/* Find the TCP control block that corresponds with this packet. */
1062	tp = intotcpcb(inp);
1063
1064	/*
1065	 * If we can't find the TCP control block (happens occasionaly for a
1066	 * packet sent during the shutdown phase of a TCP connection),
1067	 * or we're in the timewait state, bail.
1068	 */
1069	if (tp == NULL || inp->inp_flags & INP_TIMEWAIT) {
1070		if (dir == PFIL_IN)
1071			ss->nskip_in_tcpcb++;
1072		else
1073			ss->nskip_out_tcpcb++;
1074
1075		goto inp_unlock6;
1076	}
1077
1078	pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
1079
1080	if (pn == NULL) {
1081		if (dir == PFIL_IN)
1082			ss->nskip_in_malloc++;
1083		else
1084			ss->nskip_out_malloc++;
1085
1086		goto inp_unlock6;
1087	}
1088
1089	siftr_siftdata(pn, inp, tp, INP_IPV6, dir, inp_locally_locked);
1090
1091	/* XXX: Figure out how to generate hashes for IPv6 packets. */
1092
1093	mtx_lock(&siftr_pkt_queue_mtx);
1094	STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
1095	mtx_unlock(&siftr_pkt_queue_mtx);
1096	goto ret6;
1097
1098inp_unlock6:
1099	if (inp_locally_locked)
1100		INP_RUNLOCK(inp);
1101
1102ret6:
1103	/* Returning 0 ensures pfil will not discard the pkt. */
1104	return (0);
1105}
1106#endif /* #ifdef SIFTR_IPV6 */
1107
1108
1109static int
1110siftr_pfil(int action)
1111{
1112	struct pfil_head *pfh_inet;
1113#ifdef SIFTR_IPV6
1114	struct pfil_head *pfh_inet6;
1115#endif
1116	VNET_ITERATOR_DECL(vnet_iter);
1117
1118	VNET_LIST_RLOCK();
1119	VNET_FOREACH(vnet_iter) {
1120		CURVNET_SET(vnet_iter);
1121		pfh_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET);
1122#ifdef SIFTR_IPV6
1123		pfh_inet6 = pfil_head_get(PFIL_TYPE_AF, AF_INET6);
1124#endif
1125
1126		if (action == HOOK) {
1127			pfil_add_hook(siftr_chkpkt, NULL,
1128			    PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet);
1129#ifdef SIFTR_IPV6
1130			pfil_add_hook(siftr_chkpkt6, NULL,
1131			    PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet6);
1132#endif
1133		} else if (action == UNHOOK) {
1134			pfil_remove_hook(siftr_chkpkt, NULL,
1135			    PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet);
1136#ifdef SIFTR_IPV6
1137			pfil_remove_hook(siftr_chkpkt6, NULL,
1138			    PFIL_IN | PFIL_OUT | PFIL_WAITOK, pfh_inet6);
1139#endif
1140		}
1141		CURVNET_RESTORE();
1142	}
1143	VNET_LIST_RUNLOCK();
1144
1145	return (0);
1146}
1147
1148
1149static int
1150siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS)
1151{
1152	struct alq *new_alq;
1153	int error;
1154
1155	if (req->newptr == NULL)
1156		goto skip;
1157
1158	/* If old filename and new filename are different. */
1159	if (strncmp(siftr_logfile, (char *)req->newptr, PATH_MAX)) {
1160
1161		error = alq_open(&new_alq, req->newptr, curthread->td_ucred,
1162		    SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1163
1164		/* Bail if unable to create new alq. */
1165		if (error)
1166			return (1);
1167
1168		/*
1169		 * If disabled, siftr_alq == NULL so we simply close
1170		 * the alq as we've proved it can be opened.
1171		 * If enabled, close the existing alq and switch the old
1172		 * for the new.
1173		 */
1174		if (siftr_alq == NULL)
1175			alq_close(new_alq);
1176		else {
1177			alq_close(siftr_alq);
1178			siftr_alq = new_alq;
1179		}
1180	}
1181
1182skip:
1183	return (sysctl_handle_string(oidp, arg1, arg2, req));
1184}
1185
1186
1187static int
1188siftr_manage_ops(uint8_t action)
1189{
1190	struct siftr_stats totalss;
1191	struct timeval tval;
1192	struct flow_hash_node *counter, *tmp_counter;
1193	struct sbuf *s;
1194	int i, key_index, ret, error;
1195	uint32_t bytes_to_write, total_skipped_pkts;
1196	uint16_t lport, fport;
1197	uint8_t *key, ipver;
1198
1199#ifdef SIFTR_IPV6
1200	uint32_t laddr[4];
1201	uint32_t faddr[4];
1202#else
1203	uint8_t laddr[4];
1204	uint8_t faddr[4];
1205#endif
1206
1207	error = 0;
1208	total_skipped_pkts = 0;
1209
1210	/* Init an autosizing sbuf that initially holds 200 chars. */
1211	if ((s = sbuf_new(NULL, NULL, 200, SBUF_AUTOEXTEND)) == NULL)
1212		return (-1);
1213
1214	if (action == SIFTR_ENABLE) {
1215		/*
1216		 * Create our alq
1217		 * XXX: We should abort if alq_open fails!
1218		 */
1219		alq_open(&siftr_alq, siftr_logfile, curthread->td_ucred,
1220		    SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1221
1222		STAILQ_INIT(&pkt_queue);
1223
1224		DPCPU_ZERO(ss);
1225
1226		siftr_exit_pkt_manager_thread = 0;
1227
1228		ret = kthread_add(&siftr_pkt_manager_thread, NULL, NULL,
1229		    &siftr_pkt_manager_thr, RFNOWAIT, 0,
1230		    "siftr_pkt_manager_thr");
1231
1232		siftr_pfil(HOOK);
1233
1234		microtime(&tval);
1235
1236		sbuf_printf(s,
1237		    "enable_time_secs=%jd\tenable_time_usecs=%06ld\t"
1238		    "siftrver=%s\thz=%u\ttcp_rtt_scale=%u\tsysname=%s\t"
1239		    "sysver=%u\tipmode=%u\n",
1240		    (intmax_t)tval.tv_sec, tval.tv_usec, MODVERSION_STR, hz,
1241		    TCP_RTT_SCALE, SYS_NAME, __FreeBSD_version, SIFTR_IPMODE);
1242
1243		sbuf_finish(s);
1244		alq_writen(siftr_alq, sbuf_data(s), sbuf_len(s), ALQ_WAITOK);
1245
1246	} else if (action == SIFTR_DISABLE && siftr_pkt_manager_thr != NULL) {
1247		/*
1248		 * Remove the pfil hook functions. All threads currently in
1249		 * the hook functions are allowed to exit before siftr_pfil()
1250		 * returns.
1251		 */
1252		siftr_pfil(UNHOOK);
1253
1254		/* This will block until the pkt manager thread unlocks it. */
1255		mtx_lock(&siftr_pkt_mgr_mtx);
1256
1257		/* Tell the pkt manager thread that it should exit now. */
1258		siftr_exit_pkt_manager_thread = 1;
1259
1260		/*
1261		 * Wake the pkt_manager thread so it realises that
1262		 * siftr_exit_pkt_manager_thread == 1 and exits gracefully.
1263		 * The wakeup won't be delivered until we unlock
1264		 * siftr_pkt_mgr_mtx so this isn't racy.
1265		 */
1266		wakeup(&wait_for_pkt);
1267
1268		/* Wait for the pkt_manager thread to exit. */
1269		mtx_sleep(siftr_pkt_manager_thr, &siftr_pkt_mgr_mtx, PWAIT,
1270		    "thrwait", 0);
1271
1272		siftr_pkt_manager_thr = NULL;
1273		mtx_unlock(&siftr_pkt_mgr_mtx);
1274
1275		totalss.n_in = DPCPU_VARSUM(ss, n_in);
1276		totalss.n_out = DPCPU_VARSUM(ss, n_out);
1277		totalss.nskip_in_malloc = DPCPU_VARSUM(ss, nskip_in_malloc);
1278		totalss.nskip_out_malloc = DPCPU_VARSUM(ss, nskip_out_malloc);
1279		totalss.nskip_in_mtx = DPCPU_VARSUM(ss, nskip_in_mtx);
1280		totalss.nskip_out_mtx = DPCPU_VARSUM(ss, nskip_out_mtx);
1281		totalss.nskip_in_tcpcb = DPCPU_VARSUM(ss, nskip_in_tcpcb);
1282		totalss.nskip_out_tcpcb = DPCPU_VARSUM(ss, nskip_out_tcpcb);
1283		totalss.nskip_in_inpcb = DPCPU_VARSUM(ss, nskip_in_inpcb);
1284		totalss.nskip_out_inpcb = DPCPU_VARSUM(ss, nskip_out_inpcb);
1285
1286		total_skipped_pkts = totalss.nskip_in_malloc +
1287		    totalss.nskip_out_malloc + totalss.nskip_in_mtx +
1288		    totalss.nskip_out_mtx + totalss.nskip_in_tcpcb +
1289		    totalss.nskip_out_tcpcb + totalss.nskip_in_inpcb +
1290		    totalss.nskip_out_inpcb;
1291
1292		microtime(&tval);
1293
1294		sbuf_printf(s,
1295		    "disable_time_secs=%jd\tdisable_time_usecs=%06ld\t"
1296		    "num_inbound_tcp_pkts=%ju\tnum_outbound_tcp_pkts=%ju\t"
1297		    "total_tcp_pkts=%ju\tnum_inbound_skipped_pkts_malloc=%u\t"
1298		    "num_outbound_skipped_pkts_malloc=%u\t"
1299		    "num_inbound_skipped_pkts_mtx=%u\t"
1300		    "num_outbound_skipped_pkts_mtx=%u\t"
1301		    "num_inbound_skipped_pkts_tcpcb=%u\t"
1302		    "num_outbound_skipped_pkts_tcpcb=%u\t"
1303		    "num_inbound_skipped_pkts_inpcb=%u\t"
1304		    "num_outbound_skipped_pkts_inpcb=%u\t"
1305		    "total_skipped_tcp_pkts=%u\tflow_list=",
1306		    (intmax_t)tval.tv_sec,
1307		    tval.tv_usec,
1308		    (uintmax_t)totalss.n_in,
1309		    (uintmax_t)totalss.n_out,
1310		    (uintmax_t)(totalss.n_in + totalss.n_out),
1311		    totalss.nskip_in_malloc,
1312		    totalss.nskip_out_malloc,
1313		    totalss.nskip_in_mtx,
1314		    totalss.nskip_out_mtx,
1315		    totalss.nskip_in_tcpcb,
1316		    totalss.nskip_out_tcpcb,
1317		    totalss.nskip_in_inpcb,
1318		    totalss.nskip_out_inpcb,
1319		    total_skipped_pkts);
1320
1321		/*
1322		 * Iterate over the flow hash, printing a summary of each
1323		 * flow seen and freeing any malloc'd memory.
1324		 * The hash consists of an array of LISTs (man 3 queue).
1325		 */
1326		for (i = 0; i < siftr_hashmask; i++) {
1327			LIST_FOREACH_SAFE(counter, counter_hash + i, nodes,
1328			    tmp_counter) {
1329				key = counter->key;
1330				key_index = 1;
1331
1332				ipver = key[0];
1333
1334				memcpy(laddr, key + key_index, sizeof(laddr));
1335				key_index += sizeof(laddr);
1336				memcpy(&lport, key + key_index, sizeof(lport));
1337				key_index += sizeof(lport);
1338				memcpy(faddr, key + key_index, sizeof(faddr));
1339				key_index += sizeof(faddr);
1340				memcpy(&fport, key + key_index, sizeof(fport));
1341
1342#ifdef SIFTR_IPV6
1343				laddr[3] = ntohl(laddr[3]);
1344				faddr[3] = ntohl(faddr[3]);
1345
1346				if (ipver == INP_IPV6) {
1347					laddr[0] = ntohl(laddr[0]);
1348					laddr[1] = ntohl(laddr[1]);
1349					laddr[2] = ntohl(laddr[2]);
1350					faddr[0] = ntohl(faddr[0]);
1351					faddr[1] = ntohl(faddr[1]);
1352					faddr[2] = ntohl(faddr[2]);
1353
1354					sbuf_printf(s,
1355					    "%x:%x:%x:%x:%x:%x:%x:%x;%u-"
1356					    "%x:%x:%x:%x:%x:%x:%x:%x;%u,",
1357					    UPPER_SHORT(laddr[0]),
1358					    LOWER_SHORT(laddr[0]),
1359					    UPPER_SHORT(laddr[1]),
1360					    LOWER_SHORT(laddr[1]),
1361					    UPPER_SHORT(laddr[2]),
1362					    LOWER_SHORT(laddr[2]),
1363					    UPPER_SHORT(laddr[3]),
1364					    LOWER_SHORT(laddr[3]),
1365					    ntohs(lport),
1366					    UPPER_SHORT(faddr[0]),
1367					    LOWER_SHORT(faddr[0]),
1368					    UPPER_SHORT(faddr[1]),
1369					    LOWER_SHORT(faddr[1]),
1370					    UPPER_SHORT(faddr[2]),
1371					    LOWER_SHORT(faddr[2]),
1372					    UPPER_SHORT(faddr[3]),
1373					    LOWER_SHORT(faddr[3]),
1374					    ntohs(fport));
1375				} else {
1376					laddr[0] = FIRST_OCTET(laddr[3]);
1377					laddr[1] = SECOND_OCTET(laddr[3]);
1378					laddr[2] = THIRD_OCTET(laddr[3]);
1379					laddr[3] = FOURTH_OCTET(laddr[3]);
1380					faddr[0] = FIRST_OCTET(faddr[3]);
1381					faddr[1] = SECOND_OCTET(faddr[3]);
1382					faddr[2] = THIRD_OCTET(faddr[3]);
1383					faddr[3] = FOURTH_OCTET(faddr[3]);
1384#endif
1385					sbuf_printf(s,
1386					    "%u.%u.%u.%u;%u-%u.%u.%u.%u;%u,",
1387					    laddr[0],
1388					    laddr[1],
1389					    laddr[2],
1390					    laddr[3],
1391					    ntohs(lport),
1392					    faddr[0],
1393					    faddr[1],
1394					    faddr[2],
1395					    faddr[3],
1396					    ntohs(fport));
1397#ifdef SIFTR_IPV6
1398				}
1399#endif
1400
1401				free(counter, M_SIFTR_HASHNODE);
1402			}
1403
1404			LIST_INIT(counter_hash + i);
1405		}
1406
1407		sbuf_printf(s, "\n");
1408		sbuf_finish(s);
1409
1410		i = 0;
1411		do {
1412			bytes_to_write = min(SIFTR_ALQ_BUFLEN, sbuf_len(s)-i);
1413			alq_writen(siftr_alq, sbuf_data(s)+i, bytes_to_write, ALQ_WAITOK);
1414			i += bytes_to_write;
1415		} while (i < sbuf_len(s));
1416
1417		alq_close(siftr_alq);
1418		siftr_alq = NULL;
1419	}
1420
1421	sbuf_delete(s);
1422
1423	/*
1424	 * XXX: Should be using ret to check if any functions fail
1425	 * and set error appropriately
1426	 */
1427
1428	return (error);
1429}
1430
1431
1432static int
1433siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS)
1434{
1435	if (req->newptr == NULL)
1436		goto skip;
1437
1438	/* If the value passed in isn't 0 or 1, return an error. */
1439	if (CAST_PTR_INT(req->newptr) != 0 && CAST_PTR_INT(req->newptr) != 1)
1440		return (1);
1441
1442	/* If we are changing state (0 to 1 or 1 to 0). */
1443	if (CAST_PTR_INT(req->newptr) != siftr_enabled )
1444		if (siftr_manage_ops(CAST_PTR_INT(req->newptr))) {
1445			siftr_manage_ops(SIFTR_DISABLE);
1446			return (1);
1447		}
1448
1449skip:
1450	return (sysctl_handle_int(oidp, arg1, arg2, req));
1451}
1452
1453
1454static void
1455siftr_shutdown_handler(void *arg)
1456{
1457	siftr_manage_ops(SIFTR_DISABLE);
1458}
1459
1460
1461/*
1462 * Module is being unloaded or machine is shutting down. Take care of cleanup.
1463 */
1464static int
1465deinit_siftr(void)
1466{
1467	/* Cleanup. */
1468	siftr_manage_ops(SIFTR_DISABLE);
1469	hashdestroy(counter_hash, M_SIFTR, siftr_hashmask);
1470	mtx_destroy(&siftr_pkt_queue_mtx);
1471	mtx_destroy(&siftr_pkt_mgr_mtx);
1472
1473	return (0);
1474}
1475
1476
1477/*
1478 * Module has just been loaded into the kernel.
1479 */
1480static int
1481init_siftr(void)
1482{
1483	EVENTHANDLER_REGISTER(shutdown_pre_sync, siftr_shutdown_handler, NULL,
1484	    SHUTDOWN_PRI_FIRST);
1485
1486	/* Initialise our flow counter hash table. */
1487	counter_hash = hashinit(SIFTR_EXPECTED_MAX_TCP_FLOWS, M_SIFTR,
1488	    &siftr_hashmask);
1489
1490	mtx_init(&siftr_pkt_queue_mtx, "siftr_pkt_queue_mtx", NULL, MTX_DEF);
1491	mtx_init(&siftr_pkt_mgr_mtx, "siftr_pkt_mgr_mtx", NULL, MTX_DEF);
1492
1493	/* Print message to the user's current terminal. */
1494	uprintf("\nStatistical Information For TCP Research (SIFTR) %s\n"
1495	    "          http://caia.swin.edu.au/urp/newtcp\n\n",
1496	    MODVERSION_STR);
1497
1498	return (0);
1499}
1500
1501
1502/*
1503 * This is the function that is called to load and unload the module.
1504 * When the module is loaded, this function is called once with
1505 * "what" == MOD_LOAD
1506 * When the module is unloaded, this function is called twice with
1507 * "what" = MOD_QUIESCE first, followed by "what" = MOD_UNLOAD second
1508 * When the system is shut down e.g. CTRL-ALT-DEL or using the shutdown command,
1509 * this function is called once with "what" = MOD_SHUTDOWN
1510 * When the system is shut down, the handler isn't called until the very end
1511 * of the shutdown sequence i.e. after the disks have been synced.
1512 */
1513static int
1514siftr_load_handler(module_t mod, int what, void *arg)
1515{
1516	int ret;
1517
1518	switch (what) {
1519	case MOD_LOAD:
1520		ret = init_siftr();
1521		break;
1522
1523	case MOD_QUIESCE:
1524	case MOD_SHUTDOWN:
1525		ret = deinit_siftr();
1526		break;
1527
1528	case MOD_UNLOAD:
1529		ret = 0;
1530		break;
1531
1532	default:
1533		ret = EINVAL;
1534		break;
1535	}
1536
1537	return (ret);
1538}
1539
1540
1541static moduledata_t siftr_mod = {
1542	.name = "siftr",
1543	.evhand = siftr_load_handler,
1544};
1545
1546/*
1547 * Param 1: name of the kernel module
1548 * Param 2: moduledata_t struct containing info about the kernel module
1549 *          and the execution entry point for the module
1550 * Param 3: From sysinit_sub_id enumeration in /usr/include/sys/kernel.h
1551 *          Defines the module initialisation order
1552 * Param 4: From sysinit_elem_order enumeration in /usr/include/sys/kernel.h
1553 *          Defines the initialisation order of this kld relative to others
1554 *          within the same subsystem as defined by param 3
1555 */
1556DECLARE_MODULE(siftr, siftr_mod, SI_SUB_SMP, SI_ORDER_ANY);
1557MODULE_DEPEND(siftr, alq, 1, 1, 1);
1558MODULE_VERSION(siftr, MODVERSION);
1559