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