2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2007-2009
5 * Swinburne University of Technology, Melbourne, Australia.
6 * Copyright (c) 2009-2010, The FreeBSD Foundation
9 * Portions of this software were developed at the Centre for Advanced
10 * Internet Architectures, Swinburne University of Technology, Melbourne,
11 * Australia by Lawrence Stewart under sponsorship from the FreeBSD Foundation.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 /******************************************************
36 * Statistical Information For TCP Research (SIFTR)
38 * A FreeBSD kernel module that adds very basic intrumentation to the
39 * TCP stack, allowing internal stats to be recorded to a log file
40 * for experimental, debugging and performance analysis purposes.
42 * SIFTR was first released in 2007 by James Healy and Lawrence Stewart whilst
43 * working on the NewTCP research project at Swinburne University of
44 * Technology's Centre for Advanced Internet Architectures, Melbourne,
45 * Australia, which was made possible in part by a grant from the Cisco
46 * University Research Program Fund at Community Foundation Silicon Valley.
47 * More details are available at:
48 * http://caia.swin.edu.au/urp/newtcp/
50 * Work on SIFTR v1.2.x was sponsored by the FreeBSD Foundation as part of
51 * the "Enhancing the FreeBSD TCP Implementation" project 2008-2009.
52 * More details are available at:
53 * http://www.freebsdfoundation.org/
54 * http://caia.swin.edu.au/freebsd/etcp09/
56 * Lawrence Stewart is the current maintainer, and all contact regarding
57 * SIFTR should be directed to him via email: lastewart@swin.edu.au
59 * Initial release date: June 2007
60 * Most recent update: September 2010
61 ******************************************************/
63 #include <sys/cdefs.h>
64 #include <sys/param.h>
66 #include <sys/errno.h>
67 #include <sys/eventhandler.h>
69 #include <sys/kernel.h>
70 #include <sys/kthread.h>
73 #include <sys/module.h>
74 #include <sys/mutex.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/sysctl.h>
83 #include <sys/unistd.h>
86 #include <net/if_var.h>
88 #include <net/route.h>
90 #include <netinet/in.h>
91 #include <netinet/in_kdtrace.h>
92 #include <netinet/in_fib.h>
93 #include <netinet/in_pcb.h>
94 #include <netinet/in_systm.h>
95 #include <netinet/in_var.h>
96 #include <netinet/ip.h>
97 #include <netinet/ip_var.h>
98 #include <netinet/tcp_var.h>
101 #include <netinet/ip6.h>
102 #include <netinet6/ip6_var.h>
103 #include <netinet6/in6_fib.h>
104 #include <netinet6/in6_pcb.h>
105 #endif /* SIFTR_IPV6 */
107 #include <machine/in_cksum.h>
110 * Three digit version number refers to X.Y.Z where:
111 * X is the major version number
112 * Y is bumped to mark backwards incompatible changes
113 * Z is bumped to mark backwards compatible changes
116 #define V_BACKBREAK 3
117 #define V_BACKCOMPAT 0
118 #define MODVERSION __CONCAT(V_MAJOR, __CONCAT(V_BACKBREAK, V_BACKCOMPAT))
119 #define MODVERSION_STR __XSTRING(V_MAJOR) "." __XSTRING(V_BACKBREAK) "." \
120 __XSTRING(V_BACKCOMPAT)
124 #define SIFTR_EXPECTED_MAX_TCP_FLOWS 65536
125 #define SYS_NAME "FreeBSD"
126 #define PACKET_TAG_SIFTR 100
127 #define PACKET_COOKIE_SIFTR 21749576
128 #define SIFTR_LOG_FILE_MODE 0644
129 #define SIFTR_DISABLE 0
130 #define SIFTR_ENABLE 1
133 * Hard upper limit on the length of log messages. Bump this up if you add new
134 * data fields such that the line length could exceed the below value.
136 #define MAX_LOG_MSG_LEN 300
137 /* XXX: Make this a sysctl tunable. */
138 #define SIFTR_ALQ_BUFLEN (1000*MAX_LOG_MSG_LEN)
141 #define SIFTR_IPMODE 6
143 #define SIFTR_IPMODE 4
146 static MALLOC_DEFINE(M_SIFTR, "siftr", "dynamic memory used by SIFTR");
147 static MALLOC_DEFINE(M_SIFTR_PKTNODE, "siftr_pktnode",
148 "SIFTR pkt_node struct");
149 static MALLOC_DEFINE(M_SIFTR_HASHNODE, "siftr_hashnode",
150 "SIFTR flow_hash_node struct");
152 /* Used as links in the pkt manager queue. */
154 /* Timestamp of pkt as noted in the pfil hook. */
156 /* Direction pkt is travelling. */
161 /* IP version pkt_node relates to; either INP_IPV4 or INP_IPV6. */
163 /* Local TCP port. */
165 /* Foreign TCP port. */
168 union in_dependaddr laddr;
169 /* Foreign address. */
170 union in_dependaddr faddr;
171 /* Congestion Window (bytes). */
173 /* Sending Window (bytes). */
175 /* Receive Window (bytes). */
177 /* More tcpcb flags storage */
179 /* Slow Start Threshold (bytes). */
180 uint32_t snd_ssthresh;
181 /* Current state of the TCP FSM. */
183 /* Max Segment Size (bytes). */
185 /* Smoothed RTT (usecs). */
187 /* Is SACK enabled? */
189 /* Window scaling for snd window. */
191 /* Window scaling for recv window. */
193 /* TCP control block flags. */
195 /* Retransmission timeout (usec). */
197 /* Size of the TCP send buffer in bytes. */
198 u_int snd_buf_hiwater;
199 /* Current num bytes in the send socket buffer. */
201 /* Size of the TCP receive buffer in bytes. */
202 u_int rcv_buf_hiwater;
203 /* Current num bytes in the receive socket buffer. */
205 /* Number of bytes inflight that we are waiting on ACKs for. */
206 u_int sent_inflight_bytes;
207 /* Number of segments currently in the reassembly queue. */
209 /* Flowid for the connection. */
211 /* Flow type for the connection. */
213 /* Link to next pkt_node in the list. */
214 STAILQ_ENTRY(pkt_node) nodes;
220 char laddr[INET6_ADDRSTRLEN]; /* local IP address */
221 char faddr[INET6_ADDRSTRLEN]; /* foreign IP address */
223 char laddr[INET_ADDRSTRLEN]; /* local IP address */
224 char faddr[INET_ADDRSTRLEN]; /* foreign IP address */
226 uint16_t lport; /* local TCP port */
227 uint16_t fport; /* foreign TCP port */
228 uint32_t key; /* flowid of the connection */
231 struct flow_hash_node
234 struct flow_info const_info; /* constant connection info */
235 LIST_ENTRY(flow_hash_node) nodes;
240 /* # TCP pkts seen by the SIFTR PFIL hooks, including any skipped. */
243 /* # pkts skipped due to failed malloc calls. */
244 uint32_t nskip_in_malloc;
245 uint32_t nskip_out_malloc;
246 /* # pkts skipped due to failed inpcb lookups. */
247 uint32_t nskip_in_inpcb;
248 uint32_t nskip_out_inpcb;
249 /* # pkts skipped due to failed tcpcb lookups. */
250 uint32_t nskip_in_tcpcb;
251 uint32_t nskip_out_tcpcb;
252 /* # pkts skipped due to stack reinjection. */
253 uint32_t nskip_in_dejavu;
254 uint32_t nskip_out_dejavu;
257 DPCPU_DEFINE_STATIC(struct siftr_stats, ss);
259 static volatile unsigned int siftr_exit_pkt_manager_thread = 0;
260 static unsigned int siftr_enabled = 0;
261 static unsigned int siftr_pkts_per_log = 1;
262 static uint16_t siftr_port_filter = 0;
263 /* static unsigned int siftr_binary_log = 0; */
264 static char siftr_logfile[PATH_MAX] = "/var/log/siftr.log";
265 static char siftr_logfile_shadow[PATH_MAX] = "/var/log/siftr.log";
266 static u_long siftr_hashmask;
267 STAILQ_HEAD(pkthead, pkt_node) pkt_queue = STAILQ_HEAD_INITIALIZER(pkt_queue);
268 LIST_HEAD(listhead, flow_hash_node) *counter_hash;
269 static int wait_for_pkt;
270 static struct alq *siftr_alq = NULL;
271 static struct mtx siftr_pkt_queue_mtx;
272 static struct mtx siftr_pkt_mgr_mtx;
273 static struct thread *siftr_pkt_manager_thr = NULL;
274 static char direction[2] = {'i','o'};
276 /* Required function prototypes. */
277 static int siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS);
278 static int siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS);
280 /* Declare the net.inet.siftr sysctl tree and populate it. */
282 SYSCTL_DECL(_net_inet_siftr);
284 SYSCTL_NODE(_net_inet, OID_AUTO, siftr, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
285 "siftr related settings");
287 SYSCTL_PROC(_net_inet_siftr, OID_AUTO, enabled,
288 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
289 &siftr_enabled, 0, &siftr_sysctl_enabled_handler, "IU",
290 "switch siftr module operations on/off");
292 SYSCTL_PROC(_net_inet_siftr, OID_AUTO, logfile,
293 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &siftr_logfile_shadow,
294 sizeof(siftr_logfile_shadow), &siftr_sysctl_logfile_name_handler, "A",
295 "file to save siftr log messages to");
297 SYSCTL_UINT(_net_inet_siftr, OID_AUTO, ppl, CTLFLAG_RW,
298 &siftr_pkts_per_log, 1,
299 "number of packets between generating a log message");
301 SYSCTL_U16(_net_inet_siftr, OID_AUTO, port_filter, CTLFLAG_RW,
302 &siftr_port_filter, 0,
303 "enable packet filter on a TCP port");
306 SYSCTL_UINT(_net_inet_siftr, OID_AUTO, binary, CTLFLAG_RW,
307 &siftr_binary_log, 0,
308 "write log files in binary instead of ascii");
311 /* Begin functions. */
313 static inline struct flow_hash_node *
314 siftr_find_flow(struct listhead *counter_list, uint32_t id)
316 struct flow_hash_node *hash_node;
318 * If the list is not empty i.e. the hash index has
319 * been used by another flow previously.
321 if (LIST_FIRST(counter_list) != NULL) {
323 * Loop through the hash nodes in the list.
324 * There should normally only be 1 hash node in the list.
326 LIST_FOREACH(hash_node, counter_list, nodes) {
328 * Check if the key for the pkt we are currently
329 * processing is the same as the key stored in the
330 * hash node we are currently processing.
331 * If they are the same, then we've found the
332 * hash node that stores the counter for the flow
333 * the pkt belongs to.
335 if (hash_node->const_info.key == id) {
344 static inline struct flow_hash_node *
345 siftr_new_hash_node(struct flow_info info, int dir,
346 struct siftr_stats *ss)
348 struct flow_hash_node *hash_node;
349 struct listhead *counter_list;
351 counter_list = counter_hash + (info.key & siftr_hashmask);
352 /* Create a new hash node to store the flow's constant info. */
353 hash_node = malloc(sizeof(struct flow_hash_node), M_SIFTR_HASHNODE,
356 if (hash_node != NULL) {
357 /* Initialise our new hash node list entry. */
358 hash_node->counter = 0;
359 hash_node->const_info = info;
360 LIST_INSERT_HEAD(counter_list, hash_node, nodes);
365 ss->nskip_in_malloc++;
367 ss->nskip_out_malloc++;
374 siftr_process_pkt(struct pkt_node * pkt_node, char *buf)
376 struct flow_hash_node *hash_node;
377 struct listhead *counter_list;
380 if (pkt_node->flowid == 0) {
381 panic("%s: flowid not available", __func__);
384 counter_list = counter_hash + (pkt_node->flowid & siftr_hashmask);
385 hash_node = siftr_find_flow(counter_list, pkt_node->flowid);
387 if (hash_node == NULL) {
389 } else if (siftr_pkts_per_log > 1) {
391 * Taking the remainder of the counter divided
392 * by the current value of siftr_pkts_per_log
393 * and storing that in counter provides a neat
394 * way to modulate the frequency of log
395 * messages being written to the log file.
397 hash_node->counter = (hash_node->counter + 1) %
400 * If we have not seen enough packets since the last time
401 * we wrote a log message for this connection, return.
403 if (hash_node->counter > 0)
407 /* Construct a log message. */
408 ret_sz = snprintf(buf, MAX_LOG_MSG_LEN,
409 "%c,%jd.%06ld,%s,%hu,%s,%hu,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,"
410 "%u,%u,%u,%u,%u,%u,%u,%u\n",
411 direction[pkt_node->direction],
412 (intmax_t)pkt_node->tval.tv_sec,
413 pkt_node->tval.tv_usec,
414 hash_node->const_info.laddr,
415 hash_node->const_info.lport,
416 hash_node->const_info.faddr,
417 hash_node->const_info.fport,
418 pkt_node->snd_ssthresh,
425 pkt_node->conn_state,
428 pkt_node->sack_enabled,
431 pkt_node->snd_buf_hiwater,
432 pkt_node->snd_buf_cc,
433 pkt_node->rcv_buf_hiwater,
434 pkt_node->rcv_buf_cc,
435 pkt_node->sent_inflight_bytes,
444 siftr_pkt_manager_thread(void *arg)
446 STAILQ_HEAD(pkthead, pkt_node) tmp_pkt_queue =
447 STAILQ_HEAD_INITIALIZER(tmp_pkt_queue);
448 struct pkt_node *pkt_node, *pkt_node_temp;
456 mtx_lock(&siftr_pkt_mgr_mtx);
458 /* draining == 0 when queue has been flushed and it's safe to exit. */
461 * Sleep until we are signalled to wake because thread has
462 * been told to exit or until 1 tick has passed.
464 mtx_sleep(&wait_for_pkt, &siftr_pkt_mgr_mtx, PWAIT, "pktwait",
467 /* Gain exclusive access to the pkt_node queue. */
468 mtx_lock(&siftr_pkt_queue_mtx);
471 * Move pkt_queue to tmp_pkt_queue, which leaves
472 * pkt_queue empty and ready to receive more pkt_nodes.
474 STAILQ_CONCAT(&tmp_pkt_queue, &pkt_queue);
477 * We've finished making changes to the list. Unlock it
478 * so the pfil hooks can continue queuing pkt_nodes.
480 mtx_unlock(&siftr_pkt_queue_mtx);
483 * We can't hold a mutex whilst calling siftr_process_pkt
484 * because ALQ might sleep waiting for buffer space.
486 mtx_unlock(&siftr_pkt_mgr_mtx);
489 pkt_node = STAILQ_FIRST(&tmp_pkt_queue);
490 if (pkt_node != NULL) {
491 if (STAILQ_NEXT(pkt_node, nodes) != NULL) {
497 log_buf = alq_getn(siftr_alq, MAX_LOG_MSG_LEN * cnt,
500 if (log_buf != NULL) {
501 log_buf->ae_bytesused = 0;
502 bufp = log_buf->ae_data;
505 * Should only happen if the ALQ is shutting
511 /* Flush all pkt_nodes to the log file. */
512 STAILQ_FOREACH_SAFE(pkt_node, &tmp_pkt_queue, nodes,
514 if (log_buf != NULL) {
515 ret_sz = siftr_process_pkt(pkt_node,
518 log_buf->ae_bytesused += ret_sz;
522 STAILQ_REMOVE_HEAD(&tmp_pkt_queue, nodes);
523 free(pkt_node, M_SIFTR_PKTNODE);
525 if (cnt <= 0 && !STAILQ_EMPTY(&tmp_pkt_queue)) {
526 alq_post_flags(siftr_alq, log_buf, 0);
530 if (log_buf != NULL) {
531 alq_post_flags(siftr_alq, log_buf, 0);
535 KASSERT(STAILQ_EMPTY(&tmp_pkt_queue),
536 ("SIFTR tmp_pkt_queue not empty after flush"));
538 mtx_lock(&siftr_pkt_mgr_mtx);
541 * If siftr_exit_pkt_manager_thread gets set during the window
542 * where we are draining the tmp_pkt_queue above, there might
543 * still be pkts in pkt_queue that need to be drained.
544 * Allow one further iteration to occur after
545 * siftr_exit_pkt_manager_thread has been set to ensure
546 * pkt_queue is completely empty before we kill the thread.
548 * siftr_exit_pkt_manager_thread is set only after the pfil
549 * hooks have been removed, so only 1 extra iteration
550 * is needed to drain the queue.
552 if (siftr_exit_pkt_manager_thread)
556 mtx_unlock(&siftr_pkt_mgr_mtx);
558 /* Calls wakeup on this thread's struct thread ptr. */
563 * Check if a given mbuf has the SIFTR mbuf tag. If it does, log the fact that
564 * it's a reinjected packet and return. If it doesn't, tag the mbuf and return.
565 * Return value >0 means the caller should skip processing this mbuf.
568 siftr_chkreinject(struct mbuf *m, int dir, struct siftr_stats *ss)
570 if (m_tag_locate(m, PACKET_COOKIE_SIFTR, PACKET_TAG_SIFTR, NULL)
573 ss->nskip_in_dejavu++;
575 ss->nskip_out_dejavu++;
579 struct m_tag *tag = m_tag_alloc(PACKET_COOKIE_SIFTR,
580 PACKET_TAG_SIFTR, 0, M_NOWAIT);
583 ss->nskip_in_malloc++;
585 ss->nskip_out_malloc++;
590 m_tag_prepend(m, tag);
597 * Look up an inpcb for a packet. Return the inpcb pointer if found, or NULL
600 static inline struct inpcb *
601 siftr_findinpcb(int ipver, struct ip *ip, struct mbuf *m, uint16_t sport,
602 uint16_t dport, int dir, struct siftr_stats *ss)
606 /* We need the tcbinfo lock. */
607 INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
610 inp = (ipver == INP_IPV4 ?
611 in_pcblookup(&V_tcbinfo, ip->ip_src, sport, ip->ip_dst,
612 dport, INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif)
615 in6_pcblookup(&V_tcbinfo,
616 &((struct ip6_hdr *)ip)->ip6_src, sport,
617 &((struct ip6_hdr *)ip)->ip6_dst, dport, INPLOOKUP_RLOCKPCB,
625 inp = (ipver == INP_IPV4 ?
626 in_pcblookup(&V_tcbinfo, ip->ip_dst, dport, ip->ip_src,
627 sport, INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif)
630 in6_pcblookup(&V_tcbinfo,
631 &((struct ip6_hdr *)ip)->ip6_dst, dport,
632 &((struct ip6_hdr *)ip)->ip6_src, sport, INPLOOKUP_RLOCKPCB,
639 /* If we can't find the inpcb, bail. */
642 ss->nskip_in_inpcb++;
644 ss->nskip_out_inpcb++;
650 static inline uint32_t
651 siftr_get_flowid(struct inpcb *inp, int ipver, uint32_t *phashtype)
653 if (inp->inp_flowid == 0) {
655 if (ipver == INP_IPV6) {
656 return fib6_calc_packet_hash(&inp->in6p_laddr,
665 return fib4_calc_packet_hash(inp->inp_laddr,
673 *phashtype = inp->inp_flowtype;
674 return inp->inp_flowid;
679 siftr_siftdata(struct pkt_node *pn, struct inpcb *inp, struct tcpcb *tp,
680 int ipver, int dir, int inp_locally_locked)
683 pn->lport = inp->inp_lport;
684 pn->fport = inp->inp_fport;
685 pn->laddr = inp->inp_inc.inc_ie.ie_dependladdr;
686 pn->faddr = inp->inp_inc.inc_ie.ie_dependfaddr;
687 pn->snd_cwnd = tp->snd_cwnd;
688 pn->snd_wnd = tp->snd_wnd;
689 pn->rcv_wnd = tp->rcv_wnd;
690 pn->t_flags2 = tp->t_flags2;
691 pn->snd_ssthresh = tp->snd_ssthresh;
692 pn->snd_scale = tp->snd_scale;
693 pn->rcv_scale = tp->rcv_scale;
694 pn->conn_state = tp->t_state;
695 pn->mss = tp->t_maxseg;
696 pn->srtt = ((uint64_t)tp->t_srtt * tick) >> TCP_RTT_SHIFT;
697 pn->sack_enabled = (tp->t_flags & TF_SACK_PERMIT) != 0;
698 pn->t_flags = tp->t_flags;
699 pn->rto = tp->t_rxtcur * tick;
700 pn->snd_buf_hiwater = inp->inp_socket->so_snd.sb_hiwat;
701 pn->snd_buf_cc = sbused(&inp->inp_socket->so_snd);
702 pn->rcv_buf_hiwater = inp->inp_socket->so_rcv.sb_hiwat;
703 pn->rcv_buf_cc = sbused(&inp->inp_socket->so_rcv);
704 pn->sent_inflight_bytes = tp->snd_max - tp->snd_una;
705 pn->t_segqlen = tp->t_segqlen;
707 /* We've finished accessing the tcb so release the lock. */
708 if (inp_locally_locked)
711 pn->direction = (dir == PFIL_IN ? DIR_IN : DIR_OUT);
714 * Significantly more accurate than using getmicrotime(), but slower!
715 * Gives true microsecond resolution at the expense of a hit to
716 * maximum pps throughput processing when SIFTR is loaded and enabled.
718 microtime(&pn->tval);
719 TCP_PROBE1(siftr, pn);
723 * pfil hook that is called for each IPv4 packet making its way through the
724 * stack in either direction.
725 * The pfil subsystem holds a non-sleepable mutex somewhere when
726 * calling our hook function, so we can't sleep at all.
727 * It's very important to use the M_NOWAIT flag with all function calls
728 * that support it so that they won't sleep, otherwise you get a panic.
731 siftr_chkpkt(struct mbuf **m, struct ifnet *ifp, int flags,
732 void *ruleset __unused, struct inpcb *inp)
738 struct siftr_stats *ss;
740 int inp_locally_locked, dir;
741 uint32_t hash_id, hash_type;
742 struct listhead *counter_list;
743 struct flow_hash_node *hash_node;
745 inp_locally_locked = 0;
746 dir = PFIL_DIR(flags);
750 * m_pullup is not required here because ip_{input|output}
751 * already do the heavy lifting for us.
754 ip = mtod(*m, struct ip *);
756 /* Only continue processing if the packet is TCP. */
757 if (ip->ip_p != IPPROTO_TCP)
761 * Create a tcphdr struct starting at the correct offset
762 * in the IP packet. ip->ip_hl gives the ip header length
763 * in 4-byte words, so multiply it to get the size in bytes.
765 ip_hl = (ip->ip_hl << 2);
766 th = (struct tcphdr *)((caddr_t)ip + ip_hl);
769 * Only pkts selected by the tcp port filter
770 * can be inserted into the pkt_queue
772 if ((siftr_port_filter != 0) &&
773 (siftr_port_filter != ntohs(th->th_sport)) &&
774 (siftr_port_filter != ntohs(th->th_dport))) {
779 * If a kernel subsystem reinjects packets into the stack, our pfil
780 * hook will be called multiple times for the same packet.
781 * Make sure we only process unique packets.
783 if (siftr_chkreinject(*m, dir, ss))
792 * If the pfil hooks don't provide a pointer to the
793 * inpcb, we need to find it ourselves and lock it.
796 /* Find the corresponding inpcb for this pkt. */
797 inp = siftr_findinpcb(INP_IPV4, ip, *m, th->th_sport,
798 th->th_dport, dir, ss);
803 inp_locally_locked = 1;
806 INP_LOCK_ASSERT(inp);
808 /* Find the TCP control block that corresponds with this packet */
812 * If we can't find the TCP control block (happens occasionaly for a
813 * packet sent during the shutdown phase of a TCP connection), or the
814 * TCP control block has not initialized (happens during TCPS_SYN_SENT),
817 if (tp == NULL || tp->t_state < TCPS_ESTABLISHED) {
819 ss->nskip_in_tcpcb++;
821 ss->nskip_out_tcpcb++;
826 hash_id = siftr_get_flowid(inp, INP_IPV4, &hash_type);
827 counter_list = counter_hash + (hash_id & siftr_hashmask);
828 hash_node = siftr_find_flow(counter_list, hash_id);
830 /* If this flow hasn't been seen before, we create a new entry. */
831 if (hash_node == NULL) {
832 struct flow_info info;
834 inet_ntoa_r(inp->inp_laddr, info.laddr);
835 inet_ntoa_r(inp->inp_faddr, info.faddr);
836 info.lport = ntohs(inp->inp_lport);
837 info.fport = ntohs(inp->inp_fport);
840 hash_node = siftr_new_hash_node(info, dir, ss);
843 if (hash_node == NULL) {
847 pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
851 ss->nskip_in_malloc++;
853 ss->nskip_out_malloc++;
858 pn->flowid = hash_id;
859 pn->flowtype = hash_type;
861 siftr_siftdata(pn, inp, tp, INP_IPV4, dir, inp_locally_locked);
863 mtx_lock(&siftr_pkt_queue_mtx);
864 STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
865 mtx_unlock(&siftr_pkt_queue_mtx);
869 if (inp_locally_locked)
878 siftr_chkpkt6(struct mbuf **m, struct ifnet *ifp, int flags,
879 void *ruleset __unused, struct inpcb *inp)
885 struct siftr_stats *ss;
887 int inp_locally_locked, dir;
888 uint32_t hash_id, hash_type;
889 struct listhead *counter_list;
890 struct flow_hash_node *hash_node;
892 inp_locally_locked = 0;
893 dir = PFIL_DIR(flags);
897 * m_pullup is not required here because ip6_{input|output}
898 * already do the heavy lifting for us.
901 ip6 = mtod(*m, struct ip6_hdr *);
904 * Only continue processing if the packet is TCP
905 * XXX: We should follow the next header fields
906 * as shown on Pg 6 RFC 2460, but right now we'll
907 * only check pkts that have no extension headers.
909 if (ip6->ip6_nxt != IPPROTO_TCP)
913 * Create a tcphdr struct starting at the correct offset
914 * in the ipv6 packet.
916 ip6_hl = sizeof(struct ip6_hdr);
917 th = (struct tcphdr *)((caddr_t)ip6 + ip6_hl);
920 * Only pkts selected by the tcp port filter
921 * can be inserted into the pkt_queue
923 if ((siftr_port_filter != 0) &&
924 (siftr_port_filter != ntohs(th->th_sport)) &&
925 (siftr_port_filter != ntohs(th->th_dport))) {
930 * If a kernel subsystem reinjects packets into the stack, our pfil
931 * hook will be called multiple times for the same packet.
932 * Make sure we only process unique packets.
934 if (siftr_chkreinject(*m, dir, ss))
943 * For inbound packets, the pfil hooks don't provide a pointer to the
944 * inpcb, so we need to find it ourselves and lock it.
947 /* Find the corresponding inpcb for this pkt. */
948 inp = siftr_findinpcb(INP_IPV6, (struct ip *)ip6, *m,
949 th->th_sport, th->th_dport, dir, ss);
954 inp_locally_locked = 1;
957 /* Find the TCP control block that corresponds with this packet. */
961 * If we can't find the TCP control block (happens occasionaly for a
962 * packet sent during the shutdown phase of a TCP connection), or the
963 * TCP control block has not initialized (happens during TCPS_SYN_SENT),
966 if (tp == NULL || tp->t_state < TCPS_ESTABLISHED) {
968 ss->nskip_in_tcpcb++;
970 ss->nskip_out_tcpcb++;
975 hash_id = siftr_get_flowid(inp, INP_IPV6, &hash_type);
976 counter_list = counter_hash + (hash_id & siftr_hashmask);
977 hash_node = siftr_find_flow(counter_list, hash_id);
979 /* If this flow hasn't been seen before, we create a new entry. */
981 struct flow_info info;
983 ip6_sprintf(info.laddr, &inp->in6p_laddr);
984 ip6_sprintf(info.faddr, &inp->in6p_faddr);
985 info.lport = ntohs(inp->inp_lport);
986 info.fport = ntohs(inp->inp_fport);
989 hash_node = siftr_new_hash_node(info, dir, ss);
996 pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
1000 ss->nskip_in_malloc++;
1002 ss->nskip_out_malloc++;
1007 pn->flowid = hash_id;
1008 pn->flowtype = hash_type;
1010 siftr_siftdata(pn, inp, tp, INP_IPV6, dir, inp_locally_locked);
1012 mtx_lock(&siftr_pkt_queue_mtx);
1013 STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
1014 mtx_unlock(&siftr_pkt_queue_mtx);
1018 if (inp_locally_locked)
1024 #endif /* #ifdef SIFTR_IPV6 */
1026 VNET_DEFINE_STATIC(pfil_hook_t, siftr_inet_hook);
1027 #define V_siftr_inet_hook VNET(siftr_inet_hook)
1029 VNET_DEFINE_STATIC(pfil_hook_t, siftr_inet6_hook);
1030 #define V_siftr_inet6_hook VNET(siftr_inet6_hook)
1033 siftr_pfil(int action)
1035 struct pfil_hook_args pha = {
1036 .pa_version = PFIL_VERSION,
1037 .pa_flags = PFIL_IN | PFIL_OUT,
1038 .pa_modname = "siftr",
1039 .pa_rulname = "default",
1041 struct pfil_link_args pla = {
1042 .pa_version = PFIL_VERSION,
1043 .pa_flags = PFIL_IN | PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR,
1046 VNET_ITERATOR_DECL(vnet_iter);
1049 VNET_FOREACH(vnet_iter) {
1050 CURVNET_SET(vnet_iter);
1052 if (action == HOOK) {
1053 pha.pa_mbuf_chk = siftr_chkpkt;
1054 pha.pa_type = PFIL_TYPE_IP4;
1055 V_siftr_inet_hook = pfil_add_hook(&pha);
1056 pla.pa_hook = V_siftr_inet_hook;
1057 pla.pa_head = V_inet_pfil_head;
1058 (void)pfil_link(&pla);
1060 pha.pa_mbuf_chk = siftr_chkpkt6;
1061 pha.pa_type = PFIL_TYPE_IP6;
1062 V_siftr_inet6_hook = pfil_add_hook(&pha);
1063 pla.pa_hook = V_siftr_inet6_hook;
1064 pla.pa_head = V_inet6_pfil_head;
1065 (void)pfil_link(&pla);
1067 } else if (action == UNHOOK) {
1068 pfil_remove_hook(V_siftr_inet_hook);
1070 pfil_remove_hook(V_siftr_inet6_hook);
1075 VNET_LIST_RUNLOCK();
1081 siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS)
1083 struct alq *new_alq;
1086 error = sysctl_handle_string(oidp, arg1, arg2, req);
1088 /* Check for error or same filename */
1089 if (error != 0 || req->newptr == NULL ||
1090 strncmp(siftr_logfile, arg1, arg2) == 0)
1093 /* file name changed */
1094 error = alq_open(&new_alq, arg1, curthread->td_ucred,
1095 SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1100 * If disabled, siftr_alq == NULL so we simply close
1101 * the alq as we've proved it can be opened.
1102 * If enabled, close the existing alq and switch the old
1105 if (siftr_alq == NULL) {
1108 alq_close(siftr_alq);
1109 siftr_alq = new_alq;
1112 /* Update filename upon success */
1113 strlcpy(siftr_logfile, arg1, arg2);
1119 siftr_manage_ops(uint8_t action)
1121 struct siftr_stats totalss;
1122 struct timeval tval;
1123 struct flow_hash_node *counter, *tmp_counter;
1126 uint32_t bytes_to_write, total_skipped_pkts;
1129 total_skipped_pkts = 0;
1131 /* Init an autosizing sbuf that initially holds 200 chars. */
1132 if ((s = sbuf_new(NULL, NULL, 200, SBUF_AUTOEXTEND)) == NULL)
1135 if (action == SIFTR_ENABLE && siftr_pkt_manager_thr == NULL) {
1138 * XXX: We should abort if alq_open fails!
1140 alq_open(&siftr_alq, siftr_logfile, curthread->td_ucred,
1141 SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1143 STAILQ_INIT(&pkt_queue);
1147 siftr_exit_pkt_manager_thread = 0;
1149 kthread_add(&siftr_pkt_manager_thread, NULL, NULL,
1150 &siftr_pkt_manager_thr, RFNOWAIT, 0,
1151 "siftr_pkt_manager_thr");
1158 "enable_time_secs=%jd\tenable_time_usecs=%06ld\t"
1159 "siftrver=%s\tsysname=%s\tsysver=%u\tipmode=%u\n",
1160 (intmax_t)tval.tv_sec, tval.tv_usec, MODVERSION_STR,
1161 SYS_NAME, __FreeBSD_version, SIFTR_IPMODE);
1164 alq_writen(siftr_alq, sbuf_data(s), sbuf_len(s), ALQ_WAITOK);
1166 } else if (action == SIFTR_DISABLE && siftr_pkt_manager_thr != NULL) {
1168 * Remove the pfil hook functions. All threads currently in
1169 * the hook functions are allowed to exit before siftr_pfil()
1174 /* This will block until the pkt manager thread unlocks it. */
1175 mtx_lock(&siftr_pkt_mgr_mtx);
1177 /* Tell the pkt manager thread that it should exit now. */
1178 siftr_exit_pkt_manager_thread = 1;
1181 * Wake the pkt_manager thread so it realises that
1182 * siftr_exit_pkt_manager_thread == 1 and exits gracefully.
1183 * The wakeup won't be delivered until we unlock
1184 * siftr_pkt_mgr_mtx so this isn't racy.
1186 wakeup(&wait_for_pkt);
1188 /* Wait for the pkt_manager thread to exit. */
1189 mtx_sleep(siftr_pkt_manager_thr, &siftr_pkt_mgr_mtx, PWAIT,
1192 siftr_pkt_manager_thr = NULL;
1193 mtx_unlock(&siftr_pkt_mgr_mtx);
1195 totalss.n_in = DPCPU_VARSUM(ss, n_in);
1196 totalss.n_out = DPCPU_VARSUM(ss, n_out);
1197 totalss.nskip_in_malloc = DPCPU_VARSUM(ss, nskip_in_malloc);
1198 totalss.nskip_out_malloc = DPCPU_VARSUM(ss, nskip_out_malloc);
1199 totalss.nskip_in_tcpcb = DPCPU_VARSUM(ss, nskip_in_tcpcb);
1200 totalss.nskip_out_tcpcb = DPCPU_VARSUM(ss, nskip_out_tcpcb);
1201 totalss.nskip_in_inpcb = DPCPU_VARSUM(ss, nskip_in_inpcb);
1202 totalss.nskip_out_inpcb = DPCPU_VARSUM(ss, nskip_out_inpcb);
1204 total_skipped_pkts = totalss.nskip_in_malloc +
1205 totalss.nskip_out_malloc + totalss.nskip_in_tcpcb +
1206 totalss.nskip_out_tcpcb + totalss.nskip_in_inpcb +
1207 totalss.nskip_out_inpcb;
1212 "disable_time_secs=%jd\tdisable_time_usecs=%06ld\t"
1213 "num_inbound_tcp_pkts=%ju\tnum_outbound_tcp_pkts=%ju\t"
1214 "total_tcp_pkts=%ju\tnum_inbound_skipped_pkts_malloc=%u\t"
1215 "num_outbound_skipped_pkts_malloc=%u\t"
1216 "num_inbound_skipped_pkts_tcpcb=%u\t"
1217 "num_outbound_skipped_pkts_tcpcb=%u\t"
1218 "num_inbound_skipped_pkts_inpcb=%u\t"
1219 "num_outbound_skipped_pkts_inpcb=%u\t"
1220 "total_skipped_tcp_pkts=%u\tflow_list=",
1221 (intmax_t)tval.tv_sec,
1223 (uintmax_t)totalss.n_in,
1224 (uintmax_t)totalss.n_out,
1225 (uintmax_t)(totalss.n_in + totalss.n_out),
1226 totalss.nskip_in_malloc,
1227 totalss.nskip_out_malloc,
1228 totalss.nskip_in_tcpcb,
1229 totalss.nskip_out_tcpcb,
1230 totalss.nskip_in_inpcb,
1231 totalss.nskip_out_inpcb,
1232 total_skipped_pkts);
1235 * Iterate over the flow hash, printing a summary of each
1236 * flow seen and freeing any malloc'd memory.
1237 * The hash consists of an array of LISTs (man 3 queue).
1239 for (i = 0; i <= siftr_hashmask; i++) {
1240 LIST_FOREACH_SAFE(counter, counter_hash + i, nodes,
1242 sbuf_printf(s, "%s;%hu-%s;%hu,",
1243 counter->const_info.laddr,
1244 counter->const_info.lport,
1245 counter->const_info.faddr,
1246 counter->const_info.fport);
1248 free(counter, M_SIFTR_HASHNODE);
1251 LIST_INIT(counter_hash + i);
1254 sbuf_printf(s, "\n");
1259 bytes_to_write = min(SIFTR_ALQ_BUFLEN, sbuf_len(s)-i);
1260 alq_writen(siftr_alq, sbuf_data(s)+i, bytes_to_write, ALQ_WAITOK);
1261 i += bytes_to_write;
1262 } while (i < sbuf_len(s));
1264 alq_close(siftr_alq);
1272 * XXX: Should be using ret to check if any functions fail
1273 * and set error appropriately
1280 siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS)
1285 new = siftr_enabled;
1286 error = sysctl_handle_int(oidp, &new, 0, req);
1287 if (error == 0 && req->newptr != NULL) {
1290 else if (new != siftr_enabled) {
1291 if ((error = siftr_manage_ops(new)) == 0) {
1292 siftr_enabled = new;
1294 siftr_manage_ops(SIFTR_DISABLE);
1303 siftr_shutdown_handler(void *arg)
1305 if (siftr_enabled == 1) {
1306 siftr_manage_ops(SIFTR_DISABLE);
1311 * Module is being unloaded or machine is shutting down. Take care of cleanup.
1317 siftr_manage_ops(SIFTR_DISABLE);
1318 hashdestroy(counter_hash, M_SIFTR, siftr_hashmask);
1319 mtx_destroy(&siftr_pkt_queue_mtx);
1320 mtx_destroy(&siftr_pkt_mgr_mtx);
1326 * Module has just been loaded into the kernel.
1331 EVENTHANDLER_REGISTER(shutdown_pre_sync, siftr_shutdown_handler, NULL,
1332 SHUTDOWN_PRI_FIRST);
1334 /* Initialise our flow counter hash table. */
1335 counter_hash = hashinit(SIFTR_EXPECTED_MAX_TCP_FLOWS, M_SIFTR,
1338 mtx_init(&siftr_pkt_queue_mtx, "siftr_pkt_queue_mtx", NULL, MTX_DEF);
1339 mtx_init(&siftr_pkt_mgr_mtx, "siftr_pkt_mgr_mtx", NULL, MTX_DEF);
1341 /* Print message to the user's current terminal. */
1342 uprintf("\nStatistical Information For TCP Research (SIFTR) %s\n"
1343 " http://caia.swin.edu.au/urp/newtcp\n\n",
1350 * This is the function that is called to load and unload the module.
1351 * When the module is loaded, this function is called once with
1352 * "what" == MOD_LOAD
1353 * When the module is unloaded, this function is called twice with
1354 * "what" = MOD_QUIESCE first, followed by "what" = MOD_UNLOAD second
1355 * When the system is shut down e.g. CTRL-ALT-DEL or using the shutdown command,
1356 * this function is called once with "what" = MOD_SHUTDOWN
1357 * When the system is shut down, the handler isn't called until the very end
1358 * of the shutdown sequence i.e. after the disks have been synced.
1361 siftr_load_handler(module_t mod, int what, void *arg)
1372 ret = deinit_siftr();
1387 static moduledata_t siftr_mod = {
1389 .evhand = siftr_load_handler,
1393 * Param 1: name of the kernel module
1394 * Param 2: moduledata_t struct containing info about the kernel module
1395 * and the execution entry point for the module
1396 * Param 3: From sysinit_sub_id enumeration in /usr/include/sys/kernel.h
1397 * Defines the module initialisation order
1398 * Param 4: From sysinit_elem_order enumeration in /usr/include/sys/kernel.h
1399 * Defines the initialisation order of this kld relative to others
1400 * within the same subsystem as defined by param 3
1402 DECLARE_MODULE(siftr, siftr_mod, SI_SUB_LAST, SI_ORDER_ANY);
1403 MODULE_DEPEND(siftr, alq, 1, 1, 1);
1404 MODULE_VERSION(siftr, MODVERSION);