]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/siftr.c
linux(4): Regen for linux_nosys change
[FreeBSD/FreeBSD.git] / sys / netinet / siftr.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2007-2009
5  *      Swinburne University of Technology, Melbourne, Australia.
6  * Copyright (c) 2009-2010, The FreeBSD Foundation
7  * All rights reserved.
8  *
9  * Portions of this software were developed at the Centre for Advanced
10  * Internet Architectures, Swinburne University of Technology, Melbourne,
11  * Australia by Lawrence Stewart under sponsorship from the FreeBSD Foundation.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /******************************************************
36  * Statistical Information For TCP Research (SIFTR)
37  *
38  * A FreeBSD kernel module that adds very basic intrumentation to the
39  * TCP stack, allowing internal stats to be recorded to a log file
40  * for experimental, debugging and performance analysis purposes.
41  *
42  * SIFTR was first released in 2007 by James Healy and Lawrence Stewart whilst
43  * working on the NewTCP research project at Swinburne University of
44  * Technology's Centre for Advanced Internet Architectures, Melbourne,
45  * Australia, which was made possible in part by a grant from the Cisco
46  * University Research Program Fund at Community Foundation Silicon Valley.
47  * More details are available at:
48  *   http://caia.swin.edu.au/urp/newtcp/
49  *
50  * Work on SIFTR v1.2.x was sponsored by the FreeBSD Foundation as part of
51  * the "Enhancing the FreeBSD TCP Implementation" project 2008-2009.
52  * More details are available at:
53  *   http://www.freebsdfoundation.org/
54  *   http://caia.swin.edu.au/freebsd/etcp09/
55  *
56  * Lawrence Stewart is the current maintainer, and all contact regarding
57  * SIFTR should be directed to him via email: lastewart@swin.edu.au
58  *
59  * Initial release date: June 2007
60  * Most recent update: September 2010
61  ******************************************************/
62
63 #include <sys/cdefs.h>
64 #include <sys/param.h>
65 #include <sys/alq.h>
66 #include <sys/errno.h>
67 #include <sys/eventhandler.h>
68 #include <sys/hash.h>
69 #include <sys/kernel.h>
70 #include <sys/kthread.h>
71 #include <sys/lock.h>
72 #include <sys/mbuf.h>
73 #include <sys/module.h>
74 #include <sys/mutex.h>
75 #include <sys/pcpu.h>
76 #include <sys/proc.h>
77 #include <sys/sbuf.h>
78 #include <sys/sdt.h>
79 #include <sys/smp.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/sysctl.h>
83 #include <sys/unistd.h>
84
85 #include <net/if.h>
86 #include <net/if_var.h>
87 #include <net/pfil.h>
88 #include <net/route.h>
89
90 #include <netinet/in.h>
91 #include <netinet/in_kdtrace.h>
92 #include <netinet/in_fib.h>
93 #include <netinet/in_pcb.h>
94 #include <netinet/in_systm.h>
95 #include <netinet/in_var.h>
96 #include <netinet/ip.h>
97 #include <netinet/ip_var.h>
98 #include <netinet/tcp_var.h>
99
100 #ifdef SIFTR_IPV6
101 #include <netinet/ip6.h>
102 #include <netinet6/ip6_var.h>
103 #include <netinet6/in6_fib.h>
104 #include <netinet6/in6_pcb.h>
105 #endif /* SIFTR_IPV6 */
106
107 #include <machine/in_cksum.h>
108
109 /*
110  * Three digit version number refers to X.Y.Z where:
111  * X is the major version number
112  * Y is bumped to mark backwards incompatible changes
113  * Z is bumped to mark backwards compatible changes
114  */
115 #define V_MAJOR         1
116 #define V_BACKBREAK     3
117 #define V_BACKCOMPAT    0
118 #define MODVERSION      __CONCAT(V_MAJOR, __CONCAT(V_BACKBREAK, V_BACKCOMPAT))
119 #define MODVERSION_STR  __XSTRING(V_MAJOR) "." __XSTRING(V_BACKBREAK) "." \
120     __XSTRING(V_BACKCOMPAT)
121
122 #define HOOK 0
123 #define UNHOOK 1
124 #define SIFTR_EXPECTED_MAX_TCP_FLOWS 65536
125 #define SYS_NAME "FreeBSD"
126 #define PACKET_TAG_SIFTR 100
127 #define PACKET_COOKIE_SIFTR 21749576
128 #define SIFTR_LOG_FILE_MODE 0644
129 #define SIFTR_DISABLE 0
130 #define SIFTR_ENABLE 1
131
132 /*
133  * Hard upper limit on the length of log messages. Bump this up if you add new
134  * data fields such that the line length could exceed the below value.
135  */
136 #define MAX_LOG_MSG_LEN 300
137 /* XXX: Make this a sysctl tunable. */
138 #define SIFTR_ALQ_BUFLEN (1000*MAX_LOG_MSG_LEN)
139
140 #ifdef SIFTR_IPV6
141 #define SIFTR_IPMODE 6
142 #else
143 #define SIFTR_IPMODE 4
144 #endif
145
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");
151
152 /* Used as links in the pkt manager queue. */
153 struct pkt_node {
154         /* Timestamp of pkt as noted in the pfil hook. */
155         struct timeval          tval;
156         /* Direction pkt is travelling. */
157         enum {
158                 DIR_IN = 0,
159                 DIR_OUT = 1,
160         }                       direction;
161         /* IP version pkt_node relates to; either INP_IPV4 or INP_IPV6. */
162         uint8_t                 ipver;
163         /* Local TCP port. */
164         uint16_t                lport;
165         /* Foreign TCP port. */
166         uint16_t                fport;
167         /* Local address. */
168         union in_dependaddr     laddr;
169         /* Foreign address. */
170         union in_dependaddr     faddr;
171         /* Congestion Window (bytes). */
172         uint32_t                snd_cwnd;
173         /* Sending Window (bytes). */
174         uint32_t                snd_wnd;
175         /* Receive Window (bytes). */
176         uint32_t                rcv_wnd;
177         /* More tcpcb flags storage */
178         uint32_t                t_flags2;
179         /* Slow Start Threshold (bytes). */
180         uint32_t                snd_ssthresh;
181         /* Current state of the TCP FSM. */
182         int                     conn_state;
183         /* Max Segment Size (bytes). */
184         uint32_t                mss;
185         /* Smoothed RTT (usecs). */
186         uint32_t                srtt;
187         /* Is SACK enabled? */
188         u_char                  sack_enabled;
189         /* Window scaling for snd window. */
190         u_char                  snd_scale;
191         /* Window scaling for recv window. */
192         u_char                  rcv_scale;
193         /* TCP control block flags. */
194         u_int                   t_flags;
195         /* Retransmission timeout (usec). */
196         uint32_t                rto;
197         /* Size of the TCP send buffer in bytes. */
198         u_int                   snd_buf_hiwater;
199         /* Current num bytes in the send socket buffer. */
200         u_int                   snd_buf_cc;
201         /* Size of the TCP receive buffer in bytes. */
202         u_int                   rcv_buf_hiwater;
203         /* Current num bytes in the receive socket buffer. */
204         u_int                   rcv_buf_cc;
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. */
208         int                     t_segqlen;
209         /* Flowid for the connection. */
210         u_int                   flowid;
211         /* Flow type for the connection. */
212         u_int                   flowtype;
213         /* Link to next pkt_node in the list. */
214         STAILQ_ENTRY(pkt_node)  nodes;
215 };
216
217 struct flow_info
218 {
219 #ifdef SIFTR_IPV6
220         char    laddr[INET6_ADDRSTRLEN];        /* local IP address */
221         char    faddr[INET6_ADDRSTRLEN];        /* foreign IP address */
222 #else
223         char    laddr[INET_ADDRSTRLEN];         /* local IP address */
224         char    faddr[INET_ADDRSTRLEN];         /* foreign IP address */
225 #endif
226         uint16_t        lport;                  /* local TCP port */
227         uint16_t        fport;                  /* foreign TCP port */
228         uint32_t        key;                    /* flowid of the connection */
229 };
230
231 struct flow_hash_node
232 {
233         uint16_t counter;
234         struct flow_info const_info;            /* constant connection info */
235         LIST_ENTRY(flow_hash_node) nodes;
236 };
237
238 struct siftr_stats
239 {
240         /* # TCP pkts seen by the SIFTR PFIL hooks, including any skipped. */
241         uint64_t n_in;
242         uint64_t n_out;
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;
255 };
256
257 DPCPU_DEFINE_STATIC(struct siftr_stats, ss);
258
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'};
275
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);
279
280 /* Declare the net.inet.siftr sysctl tree and populate it. */
281
282 SYSCTL_DECL(_net_inet_siftr);
283
284 SYSCTL_NODE(_net_inet, OID_AUTO, siftr, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
285     "siftr related settings");
286
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");
291
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");
296
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");
300
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");
304
305 /* XXX: TODO
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");
309 */
310
311 /* Begin functions. */
312
313 static inline struct flow_hash_node *
314 siftr_find_flow(struct listhead *counter_list, uint32_t id)
315 {
316         struct flow_hash_node *hash_node;
317         /*
318          * If the list is not empty i.e. the hash index has
319          * been used by another flow previously.
320          */
321         if (LIST_FIRST(counter_list) != NULL) {
322                 /*
323                  * Loop through the hash nodes in the list.
324                  * There should normally only be 1 hash node in the list.
325                  */
326                 LIST_FOREACH(hash_node, counter_list, nodes) {
327                         /*
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.
334                          */
335                         if (hash_node->const_info.key == id) {
336                                 return hash_node;
337                         }
338                 }
339         }
340
341         return NULL;
342 }
343
344 static inline struct flow_hash_node *
345 siftr_new_hash_node(struct flow_info info, int dir,
346                     struct siftr_stats *ss)
347 {
348         struct flow_hash_node *hash_node;
349         struct listhead *counter_list;
350
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,
354                            M_NOWAIT|M_ZERO);
355
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);
361                 return hash_node;
362         } else {
363                 /* malloc failed */
364                 if (dir == DIR_IN)
365                         ss->nskip_in_malloc++;
366                 else
367                         ss->nskip_out_malloc++;
368
369                 return NULL;
370         }
371 }
372
373 static int
374 siftr_process_pkt(struct pkt_node * pkt_node, char *buf)
375 {
376         struct flow_hash_node *hash_node;
377         struct listhead *counter_list;
378         int ret_sz;
379
380         if (pkt_node->flowid == 0) {
381                 panic("%s: flowid not available", __func__);
382         }
383
384         counter_list = counter_hash + (pkt_node->flowid & siftr_hashmask);
385         hash_node = siftr_find_flow(counter_list, pkt_node->flowid);
386
387         if (hash_node == NULL) {
388                 return 0;
389         } else if (siftr_pkts_per_log > 1) {
390                 /*
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.
396                  */
397                 hash_node->counter = (hash_node->counter + 1) %
398                                      siftr_pkts_per_log;
399                 /*
400                  * If we have not seen enough packets since the last time
401                  * we wrote a log message for this connection, return.
402                  */
403                 if (hash_node->counter > 0)
404                         return 0;
405         }
406
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,
419             pkt_node->snd_cwnd,
420             pkt_node->t_flags2,
421             pkt_node->snd_wnd,
422             pkt_node->rcv_wnd,
423             pkt_node->snd_scale,
424             pkt_node->rcv_scale,
425             pkt_node->conn_state,
426             pkt_node->mss,
427             pkt_node->srtt,
428             pkt_node->sack_enabled,
429             pkt_node->t_flags,
430             pkt_node->rto,
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,
436             pkt_node->t_segqlen,
437             pkt_node->flowid,
438             pkt_node->flowtype);
439
440         return ret_sz;
441 }
442
443 static void
444 siftr_pkt_manager_thread(void *arg)
445 {
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;
449         uint8_t draining;
450         struct ale *log_buf;
451         int ret_sz, cnt;
452         char *bufp;
453
454         draining = 2;
455
456         mtx_lock(&siftr_pkt_mgr_mtx);
457
458         /* draining == 0 when queue has been flushed and it's safe to exit. */
459         while (draining) {
460                 /*
461                  * Sleep until we are signalled to wake because thread has
462                  * been told to exit or until 1 tick has passed.
463                  */
464                 mtx_sleep(&wait_for_pkt, &siftr_pkt_mgr_mtx, PWAIT, "pktwait",
465                     1);
466
467                 /* Gain exclusive access to the pkt_node queue. */
468                 mtx_lock(&siftr_pkt_queue_mtx);
469
470                 /*
471                  * Move pkt_queue to tmp_pkt_queue, which leaves
472                  * pkt_queue empty and ready to receive more pkt_nodes.
473                  */
474                 STAILQ_CONCAT(&tmp_pkt_queue, &pkt_queue);
475
476                 /*
477                  * We've finished making changes to the list. Unlock it
478                  * so the pfil hooks can continue queuing pkt_nodes.
479                  */
480                 mtx_unlock(&siftr_pkt_queue_mtx);
481
482                 /*
483                  * We can't hold a mutex whilst calling siftr_process_pkt
484                  * because ALQ might sleep waiting for buffer space.
485                  */
486                 mtx_unlock(&siftr_pkt_mgr_mtx);
487
488 try_again:
489                 pkt_node = STAILQ_FIRST(&tmp_pkt_queue);
490                 if (pkt_node != NULL) {
491                         if (STAILQ_NEXT(pkt_node, nodes) != NULL) {
492                                 cnt = 3;
493                         } else {
494                                 cnt = 1;
495                         }
496
497                         log_buf = alq_getn(siftr_alq, MAX_LOG_MSG_LEN * cnt,
498                                            ALQ_WAITOK);
499
500                         if (log_buf != NULL) {
501                                 log_buf->ae_bytesused = 0;
502                                 bufp = log_buf->ae_data;
503                         } else {
504                                 /*
505                                  * Should only happen if the ALQ is shutting
506                                  * down.
507                                  */
508                                 bufp = NULL;
509                         }
510
511                         /* Flush all pkt_nodes to the log file. */
512                         STAILQ_FOREACH_SAFE(pkt_node, &tmp_pkt_queue, nodes,
513                             pkt_node_temp) {
514                                 if (log_buf != NULL) {
515                                         ret_sz = siftr_process_pkt(pkt_node,
516                                                                    bufp);
517                                         bufp += ret_sz;
518                                         log_buf->ae_bytesused += ret_sz;
519                                         cnt--;
520                                 }
521
522                                 STAILQ_REMOVE_HEAD(&tmp_pkt_queue, nodes);
523                                 free(pkt_node, M_SIFTR_PKTNODE);
524
525                                 if (cnt <= 0 && !STAILQ_EMPTY(&tmp_pkt_queue)) {
526                                         alq_post_flags(siftr_alq, log_buf, 0);
527                                         goto try_again;
528                                 }
529                         }
530                         if (log_buf != NULL) {
531                                 alq_post_flags(siftr_alq, log_buf, 0);
532                         }
533                 }
534
535                 KASSERT(STAILQ_EMPTY(&tmp_pkt_queue),
536                     ("SIFTR tmp_pkt_queue not empty after flush"));
537
538                 mtx_lock(&siftr_pkt_mgr_mtx);
539
540                 /*
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.
547                  *
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.
551                  */
552                 if (siftr_exit_pkt_manager_thread)
553                         draining--;
554         }
555
556         mtx_unlock(&siftr_pkt_mgr_mtx);
557
558         /* Calls wakeup on this thread's struct thread ptr. */
559         kthread_exit();
560 }
561
562 /*
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.
566  */
567 static inline int
568 siftr_chkreinject(struct mbuf *m, int dir, struct siftr_stats *ss)
569 {
570         if (m_tag_locate(m, PACKET_COOKIE_SIFTR, PACKET_TAG_SIFTR, NULL)
571             != NULL) {
572                 if (dir == PFIL_IN)
573                         ss->nskip_in_dejavu++;
574                 else
575                         ss->nskip_out_dejavu++;
576
577                 return (1);
578         } else {
579                 struct m_tag *tag = m_tag_alloc(PACKET_COOKIE_SIFTR,
580                     PACKET_TAG_SIFTR, 0, M_NOWAIT);
581                 if (tag == NULL) {
582                         if (dir == PFIL_IN)
583                                 ss->nskip_in_malloc++;
584                         else
585                                 ss->nskip_out_malloc++;
586
587                         return (1);
588                 }
589
590                 m_tag_prepend(m, tag);
591         }
592
593         return (0);
594 }
595
596 /*
597  * Look up an inpcb for a packet. Return the inpcb pointer if found, or NULL
598  * otherwise.
599  */
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)
603 {
604         struct inpcb *inp;
605
606         /* We need the tcbinfo lock. */
607         INP_INFO_WUNLOCK_ASSERT(&V_tcbinfo);
608
609         if (dir == PFIL_IN)
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)
613                     :
614 #ifdef SIFTR_IPV6
615                     in6_pcblookup(&V_tcbinfo,
616                     &((struct ip6_hdr *)ip)->ip6_src, sport,
617                     &((struct ip6_hdr *)ip)->ip6_dst, dport, INPLOOKUP_RLOCKPCB,
618                     m->m_pkthdr.rcvif)
619 #else
620                     NULL
621 #endif
622                     );
623
624         else
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)
628                     :
629 #ifdef SIFTR_IPV6
630                     in6_pcblookup(&V_tcbinfo,
631                     &((struct ip6_hdr *)ip)->ip6_dst, dport,
632                     &((struct ip6_hdr *)ip)->ip6_src, sport, INPLOOKUP_RLOCKPCB,
633                     m->m_pkthdr.rcvif)
634 #else
635                     NULL
636 #endif
637                     );
638
639         /* If we can't find the inpcb, bail. */
640         if (inp == NULL) {
641                 if (dir == PFIL_IN)
642                         ss->nskip_in_inpcb++;
643                 else
644                         ss->nskip_out_inpcb++;
645         }
646
647         return (inp);
648 }
649
650 static inline uint32_t
651 siftr_get_flowid(struct inpcb *inp, int ipver, uint32_t *phashtype)
652 {
653         if (inp->inp_flowid == 0) {
654 #ifdef SIFTR_IPV6
655                 if (ipver == INP_IPV6) {
656                         return fib6_calc_packet_hash(&inp->in6p_laddr,
657                                                      &inp->in6p_faddr,
658                                                      inp->inp_lport,
659                                                      inp->inp_fport,
660                                                      IPPROTO_TCP,
661                                                      phashtype);
662                 } else
663 #endif
664                 {
665                         return fib4_calc_packet_hash(inp->inp_laddr,
666                                                      inp->inp_faddr,
667                                                      inp->inp_lport,
668                                                      inp->inp_fport,
669                                                      IPPROTO_TCP,
670                                                      phashtype);
671                 }
672         } else {
673                 *phashtype = inp->inp_flowtype;
674                 return inp->inp_flowid;
675         }
676 }
677
678 static inline void
679 siftr_siftdata(struct pkt_node *pn, struct inpcb *inp, struct tcpcb *tp,
680     int ipver, int dir, int inp_locally_locked)
681 {
682         pn->ipver = ipver;
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;
706
707         /* We've finished accessing the tcb so release the lock. */
708         if (inp_locally_locked)
709                 INP_RUNLOCK(inp);
710
711         pn->direction = (dir == PFIL_IN ? DIR_IN : DIR_OUT);
712
713         /*
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.
717          */
718         microtime(&pn->tval);
719         TCP_PROBE1(siftr, pn);
720 }
721
722 /*
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.
729  */
730 static pfil_return_t
731 siftr_chkpkt(struct mbuf **m, struct ifnet *ifp, int flags,
732     void *ruleset __unused, struct inpcb *inp)
733 {
734         struct pkt_node *pn;
735         struct ip *ip;
736         struct tcphdr *th;
737         struct tcpcb *tp;
738         struct siftr_stats *ss;
739         unsigned int ip_hl;
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;
744
745         inp_locally_locked = 0;
746         dir = PFIL_DIR(flags);
747         ss = DPCPU_PTR(ss);
748
749         /*
750          * m_pullup is not required here because ip_{input|output}
751          * already do the heavy lifting for us.
752          */
753
754         ip = mtod(*m, struct ip *);
755
756         /* Only continue processing if the packet is TCP. */
757         if (ip->ip_p != IPPROTO_TCP)
758                 goto ret;
759
760         /*
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.
764          */
765         ip_hl = (ip->ip_hl << 2);
766         th = (struct tcphdr *)((caddr_t)ip + ip_hl);
767
768         /*
769          * Only pkts selected by the tcp port filter
770          * can be inserted into the pkt_queue
771          */
772         if ((siftr_port_filter != 0) &&
773             (siftr_port_filter != ntohs(th->th_sport)) &&
774             (siftr_port_filter != ntohs(th->th_dport))) {
775                 goto ret;
776         }
777
778         /*
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.
782          */
783         if (siftr_chkreinject(*m, dir, ss))
784                 goto ret;
785
786         if (dir == PFIL_IN)
787                 ss->n_in++;
788         else
789                 ss->n_out++;
790
791         /*
792          * If the pfil hooks don't provide a pointer to the
793          * inpcb, we need to find it ourselves and lock it.
794          */
795         if (!inp) {
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);
799
800                 if (inp == NULL)
801                         goto ret;
802                 else
803                         inp_locally_locked = 1;
804         }
805
806         INP_LOCK_ASSERT(inp);
807
808         /* Find the TCP control block that corresponds with this packet */
809         tp = intotcpcb(inp);
810
811         /*
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),
815          * bail.
816          */
817         if (tp == NULL || tp->t_state < TCPS_ESTABLISHED) {
818                 if (dir == PFIL_IN)
819                         ss->nskip_in_tcpcb++;
820                 else
821                         ss->nskip_out_tcpcb++;
822
823                 goto inp_unlock;
824         }
825
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);
829
830         /* If this flow hasn't been seen before, we create a new entry. */
831         if (hash_node == NULL) {
832                 struct flow_info info;
833
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);
838                 info.key = hash_id;
839
840                 hash_node = siftr_new_hash_node(info, dir, ss);
841         }
842
843         if (hash_node == NULL) {
844                 goto inp_unlock;
845         }
846
847         pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
848
849         if (pn == NULL) {
850                 if (dir == PFIL_IN)
851                         ss->nskip_in_malloc++;
852                 else
853                         ss->nskip_out_malloc++;
854
855                 goto inp_unlock;
856         }
857
858         pn->flowid = hash_id;
859         pn->flowtype = hash_type;
860
861         siftr_siftdata(pn, inp, tp, INP_IPV4, dir, inp_locally_locked);
862
863         mtx_lock(&siftr_pkt_queue_mtx);
864         STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
865         mtx_unlock(&siftr_pkt_queue_mtx);
866         goto ret;
867
868 inp_unlock:
869         if (inp_locally_locked)
870                 INP_RUNLOCK(inp);
871
872 ret:
873         return (PFIL_PASS);
874 }
875
876 #ifdef SIFTR_IPV6
877 static pfil_return_t
878 siftr_chkpkt6(struct mbuf **m, struct ifnet *ifp, int flags,
879     void *ruleset __unused, struct inpcb *inp)
880 {
881         struct pkt_node *pn;
882         struct ip6_hdr *ip6;
883         struct tcphdr *th;
884         struct tcpcb *tp;
885         struct siftr_stats *ss;
886         unsigned int ip6_hl;
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;
891
892         inp_locally_locked = 0;
893         dir = PFIL_DIR(flags);
894         ss = DPCPU_PTR(ss);
895
896         /*
897          * m_pullup is not required here because ip6_{input|output}
898          * already do the heavy lifting for us.
899          */
900
901         ip6 = mtod(*m, struct ip6_hdr *);
902
903         /*
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.
908          */
909         if (ip6->ip6_nxt != IPPROTO_TCP)
910                 goto ret6;
911
912         /*
913          * Create a tcphdr struct starting at the correct offset
914          * in the ipv6 packet.
915          */
916         ip6_hl = sizeof(struct ip6_hdr);
917         th = (struct tcphdr *)((caddr_t)ip6 + ip6_hl);
918
919         /*
920          * Only pkts selected by the tcp port filter
921          * can be inserted into the pkt_queue
922          */
923         if ((siftr_port_filter != 0) &&
924             (siftr_port_filter != ntohs(th->th_sport)) &&
925             (siftr_port_filter != ntohs(th->th_dport))) {
926                 goto ret6;
927         }
928
929         /*
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.
933          */
934         if (siftr_chkreinject(*m, dir, ss))
935                 goto ret6;
936
937         if (dir == PFIL_IN)
938                 ss->n_in++;
939         else
940                 ss->n_out++;
941
942         /*
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.
945          */
946         if (!inp) {
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);
950
951                 if (inp == NULL)
952                         goto ret6;
953                 else
954                         inp_locally_locked = 1;
955         }
956
957         /* Find the TCP control block that corresponds with this packet. */
958         tp = intotcpcb(inp);
959
960         /*
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),
964          * bail.
965          */
966         if (tp == NULL || tp->t_state < TCPS_ESTABLISHED) {
967                 if (dir == PFIL_IN)
968                         ss->nskip_in_tcpcb++;
969                 else
970                         ss->nskip_out_tcpcb++;
971
972                 goto inp_unlock6;
973         }
974
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);
978
979         /* If this flow hasn't been seen before, we create a new entry. */
980         if (!hash_node) {
981                 struct flow_info info;
982
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);
987                 info.key = hash_id;
988
989                 hash_node = siftr_new_hash_node(info, dir, ss);
990         }
991
992         if (!hash_node) {
993                 goto inp_unlock6;
994         }
995
996         pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
997
998         if (pn == NULL) {
999                 if (dir == PFIL_IN)
1000                         ss->nskip_in_malloc++;
1001                 else
1002                         ss->nskip_out_malloc++;
1003
1004                 goto inp_unlock6;
1005         }
1006
1007         pn->flowid = hash_id;
1008         pn->flowtype = hash_type;
1009
1010         siftr_siftdata(pn, inp, tp, INP_IPV6, dir, inp_locally_locked);
1011
1012         mtx_lock(&siftr_pkt_queue_mtx);
1013         STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
1014         mtx_unlock(&siftr_pkt_queue_mtx);
1015         goto ret6;
1016
1017 inp_unlock6:
1018         if (inp_locally_locked)
1019                 INP_RUNLOCK(inp);
1020
1021 ret6:
1022         return (PFIL_PASS);
1023 }
1024 #endif /* #ifdef SIFTR_IPV6 */
1025
1026 VNET_DEFINE_STATIC(pfil_hook_t, siftr_inet_hook);
1027 #define V_siftr_inet_hook       VNET(siftr_inet_hook)
1028 #ifdef SIFTR_IPV6
1029 VNET_DEFINE_STATIC(pfil_hook_t, siftr_inet6_hook);
1030 #define V_siftr_inet6_hook      VNET(siftr_inet6_hook)
1031 #endif
1032 static int
1033 siftr_pfil(int action)
1034 {
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",
1040         };
1041         struct pfil_link_args pla = {
1042                 .pa_version = PFIL_VERSION,
1043                 .pa_flags = PFIL_IN | PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR,
1044         };
1045
1046         VNET_ITERATOR_DECL(vnet_iter);
1047
1048         VNET_LIST_RLOCK();
1049         VNET_FOREACH(vnet_iter) {
1050                 CURVNET_SET(vnet_iter);
1051
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);
1059 #ifdef SIFTR_IPV6
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);
1066 #endif
1067                 } else if (action == UNHOOK) {
1068                         pfil_remove_hook(V_siftr_inet_hook);
1069 #ifdef SIFTR_IPV6
1070                         pfil_remove_hook(V_siftr_inet6_hook);
1071 #endif
1072                 }
1073                 CURVNET_RESTORE();
1074         }
1075         VNET_LIST_RUNLOCK();
1076
1077         return (0);
1078 }
1079
1080 static int
1081 siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS)
1082 {
1083         struct alq *new_alq;
1084         int error;
1085
1086         error = sysctl_handle_string(oidp, arg1, arg2, req);
1087
1088         /* Check for error or same filename */
1089         if (error != 0 || req->newptr == NULL ||
1090             strncmp(siftr_logfile, arg1, arg2) == 0)
1091                 goto done;
1092
1093         /* file name changed */
1094         error = alq_open(&new_alq, arg1, curthread->td_ucred,
1095             SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1096         if (error != 0)
1097                 goto done;
1098
1099         /*
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
1103          * for the new.
1104          */
1105         if (siftr_alq == NULL) {
1106                 alq_close(new_alq);
1107         } else {
1108                 alq_close(siftr_alq);
1109                 siftr_alq = new_alq;
1110         }
1111
1112         /* Update filename upon success */
1113         strlcpy(siftr_logfile, arg1, arg2);
1114 done:
1115         return (error);
1116 }
1117
1118 static int
1119 siftr_manage_ops(uint8_t action)
1120 {
1121         struct siftr_stats totalss;
1122         struct timeval tval;
1123         struct flow_hash_node *counter, *tmp_counter;
1124         struct sbuf *s;
1125         int i, error;
1126         uint32_t bytes_to_write, total_skipped_pkts;
1127
1128         error = 0;
1129         total_skipped_pkts = 0;
1130
1131         /* Init an autosizing sbuf that initially holds 200 chars. */
1132         if ((s = sbuf_new(NULL, NULL, 200, SBUF_AUTOEXTEND)) == NULL)
1133                 return (-1);
1134
1135         if (action == SIFTR_ENABLE && siftr_pkt_manager_thr == NULL) {
1136                 /*
1137                  * Create our alq
1138                  * XXX: We should abort if alq_open fails!
1139                  */
1140                 alq_open(&siftr_alq, siftr_logfile, curthread->td_ucred,
1141                     SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1142
1143                 STAILQ_INIT(&pkt_queue);
1144
1145                 DPCPU_ZERO(ss);
1146
1147                 siftr_exit_pkt_manager_thread = 0;
1148
1149                 kthread_add(&siftr_pkt_manager_thread, NULL, NULL,
1150                     &siftr_pkt_manager_thr, RFNOWAIT, 0,
1151                     "siftr_pkt_manager_thr");
1152
1153                 siftr_pfil(HOOK);
1154
1155                 microtime(&tval);
1156
1157                 sbuf_printf(s,
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);
1162
1163                 sbuf_finish(s);
1164                 alq_writen(siftr_alq, sbuf_data(s), sbuf_len(s), ALQ_WAITOK);
1165
1166         } else if (action == SIFTR_DISABLE && siftr_pkt_manager_thr != NULL) {
1167                 /*
1168                  * Remove the pfil hook functions. All threads currently in
1169                  * the hook functions are allowed to exit before siftr_pfil()
1170                  * returns.
1171                  */
1172                 siftr_pfil(UNHOOK);
1173
1174                 /* This will block until the pkt manager thread unlocks it. */
1175                 mtx_lock(&siftr_pkt_mgr_mtx);
1176
1177                 /* Tell the pkt manager thread that it should exit now. */
1178                 siftr_exit_pkt_manager_thread = 1;
1179
1180                 /*
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.
1185                  */
1186                 wakeup(&wait_for_pkt);
1187
1188                 /* Wait for the pkt_manager thread to exit. */
1189                 mtx_sleep(siftr_pkt_manager_thr, &siftr_pkt_mgr_mtx, PWAIT,
1190                     "thrwait", 0);
1191
1192                 siftr_pkt_manager_thr = NULL;
1193                 mtx_unlock(&siftr_pkt_mgr_mtx);
1194
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);
1203
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;
1208
1209                 microtime(&tval);
1210
1211                 sbuf_printf(s,
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,
1222                     tval.tv_usec,
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);
1233
1234                 /*
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).
1238                  */
1239                 for (i = 0; i <= siftr_hashmask; i++) {
1240                         LIST_FOREACH_SAFE(counter, counter_hash + i, nodes,
1241                             tmp_counter) {
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);
1247
1248                                 free(counter, M_SIFTR_HASHNODE);
1249                         }
1250
1251                         LIST_INIT(counter_hash + i);
1252                 }
1253
1254                 sbuf_printf(s, "\n");
1255                 sbuf_finish(s);
1256
1257                 i = 0;
1258                 do {
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));
1263
1264                 alq_close(siftr_alq);
1265                 siftr_alq = NULL;
1266         } else
1267                 error = EINVAL;
1268
1269         sbuf_delete(s);
1270
1271         /*
1272          * XXX: Should be using ret to check if any functions fail
1273          * and set error appropriately
1274          */
1275
1276         return (error);
1277 }
1278
1279 static int
1280 siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS)
1281 {
1282         int error;
1283         uint32_t new;
1284
1285         new = siftr_enabled;
1286         error = sysctl_handle_int(oidp, &new, 0, req);
1287         if (error == 0 && req->newptr != NULL) {
1288                 if (new > 1)
1289                         return (EINVAL);
1290                 else if (new != siftr_enabled) {
1291                         if ((error = siftr_manage_ops(new)) == 0) {
1292                                 siftr_enabled = new;
1293                         } else {
1294                                 siftr_manage_ops(SIFTR_DISABLE);
1295                         }
1296                 }
1297         }
1298
1299         return (error);
1300 }
1301
1302 static void
1303 siftr_shutdown_handler(void *arg)
1304 {
1305         if (siftr_enabled == 1) {
1306                 siftr_manage_ops(SIFTR_DISABLE);
1307         }
1308 }
1309
1310 /*
1311  * Module is being unloaded or machine is shutting down. Take care of cleanup.
1312  */
1313 static int
1314 deinit_siftr(void)
1315 {
1316         /* 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);
1321
1322         return (0);
1323 }
1324
1325 /*
1326  * Module has just been loaded into the kernel.
1327  */
1328 static int
1329 init_siftr(void)
1330 {
1331         EVENTHANDLER_REGISTER(shutdown_pre_sync, siftr_shutdown_handler, NULL,
1332             SHUTDOWN_PRI_FIRST);
1333
1334         /* Initialise our flow counter hash table. */
1335         counter_hash = hashinit(SIFTR_EXPECTED_MAX_TCP_FLOWS, M_SIFTR,
1336             &siftr_hashmask);
1337
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);
1340
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",
1344             MODVERSION_STR);
1345
1346         return (0);
1347 }
1348
1349 /*
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.
1359  */
1360 static int
1361 siftr_load_handler(module_t mod, int what, void *arg)
1362 {
1363         int ret;
1364
1365         switch (what) {
1366         case MOD_LOAD:
1367                 ret = init_siftr();
1368                 break;
1369
1370         case MOD_QUIESCE:
1371         case MOD_SHUTDOWN:
1372                 ret = deinit_siftr();
1373                 break;
1374
1375         case MOD_UNLOAD:
1376                 ret = 0;
1377                 break;
1378
1379         default:
1380                 ret = EINVAL;
1381                 break;
1382         }
1383
1384         return (ret);
1385 }
1386
1387 static moduledata_t siftr_mod = {
1388         .name = "siftr",
1389         .evhand = siftr_load_handler,
1390 };
1391
1392 /*
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
1401  */
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);