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 static eventhandler_tag siftr_shutdown_tag;
277
278 /* Required function prototypes. */
279 static int siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS);
280 static int siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS);
281
282 /* Declare the net.inet.siftr sysctl tree and populate it. */
283
284 SYSCTL_DECL(_net_inet_siftr);
285
286 SYSCTL_NODE(_net_inet, OID_AUTO, siftr, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
287 "siftr related settings");
288
289 SYSCTL_PROC(_net_inet_siftr, OID_AUTO, enabled,
290 CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
291 &siftr_enabled, 0, &siftr_sysctl_enabled_handler, "IU",
292 "switch siftr module operations on/off");
293
294 SYSCTL_PROC(_net_inet_siftr, OID_AUTO, logfile,
295 CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_NEEDGIANT, &siftr_logfile_shadow,
296 sizeof(siftr_logfile_shadow), &siftr_sysctl_logfile_name_handler, "A",
297 "file to save siftr log messages to");
298
299 SYSCTL_UINT(_net_inet_siftr, OID_AUTO, ppl, CTLFLAG_RW,
300 &siftr_pkts_per_log, 1,
301 "number of packets between generating a log message");
302
303 SYSCTL_U16(_net_inet_siftr, OID_AUTO, port_filter, CTLFLAG_RW,
304 &siftr_port_filter, 0,
305 "enable packet filter on a TCP port");
306
307 /* XXX: TODO
308 SYSCTL_UINT(_net_inet_siftr, OID_AUTO, binary, CTLFLAG_RW,
309 &siftr_binary_log, 0,
310 "write log files in binary instead of ascii");
311 */
312
313 /* Begin functions. */
314
315 static inline struct flow_hash_node *
siftr_find_flow(struct listhead * counter_list,uint32_t id)316 siftr_find_flow(struct listhead *counter_list, uint32_t id)
317 {
318 struct flow_hash_node *hash_node;
319 /*
320 * If the list is not empty i.e. the hash index has
321 * been used by another flow previously.
322 */
323 if (LIST_FIRST(counter_list) != NULL) {
324 /*
325 * Loop through the hash nodes in the list.
326 * There should normally only be 1 hash node in the list.
327 */
328 LIST_FOREACH(hash_node, counter_list, nodes) {
329 /*
330 * Check if the key for the pkt we are currently
331 * processing is the same as the key stored in the
332 * hash node we are currently processing.
333 * If they are the same, then we've found the
334 * hash node that stores the counter for the flow
335 * the pkt belongs to.
336 */
337 if (hash_node->const_info.key == id) {
338 return hash_node;
339 }
340 }
341 }
342
343 return NULL;
344 }
345
346 static inline struct flow_hash_node *
siftr_new_hash_node(struct flow_info info,int dir,struct siftr_stats * ss)347 siftr_new_hash_node(struct flow_info info, int dir,
348 struct siftr_stats *ss)
349 {
350 struct flow_hash_node *hash_node;
351 struct listhead *counter_list;
352
353 counter_list = counter_hash + (info.key & siftr_hashmask);
354 /* Create a new hash node to store the flow's constant info. */
355 hash_node = malloc(sizeof(struct flow_hash_node), M_SIFTR_HASHNODE,
356 M_NOWAIT|M_ZERO);
357
358 if (hash_node != NULL) {
359 /* Initialise our new hash node list entry. */
360 hash_node->counter = 0;
361 hash_node->const_info = info;
362 LIST_INSERT_HEAD(counter_list, hash_node, nodes);
363 return hash_node;
364 } else {
365 /* malloc failed */
366 if (dir == DIR_IN)
367 ss->nskip_in_malloc++;
368 else
369 ss->nskip_out_malloc++;
370
371 return NULL;
372 }
373 }
374
375 static int
siftr_process_pkt(struct pkt_node * pkt_node,char * buf)376 siftr_process_pkt(struct pkt_node * pkt_node, char *buf)
377 {
378 struct flow_hash_node *hash_node;
379 struct listhead *counter_list;
380 int ret_sz;
381
382 if (pkt_node->flowid == 0) {
383 panic("%s: flowid not available", __func__);
384 }
385
386 counter_list = counter_hash + (pkt_node->flowid & siftr_hashmask);
387 hash_node = siftr_find_flow(counter_list, pkt_node->flowid);
388
389 if (hash_node == NULL) {
390 return 0;
391 } else if (siftr_pkts_per_log > 1) {
392 /*
393 * Taking the remainder of the counter divided
394 * by the current value of siftr_pkts_per_log
395 * and storing that in counter provides a neat
396 * way to modulate the frequency of log
397 * messages being written to the log file.
398 */
399 hash_node->counter = (hash_node->counter + 1) %
400 siftr_pkts_per_log;
401 /*
402 * If we have not seen enough packets since the last time
403 * we wrote a log message for this connection, return.
404 */
405 if (hash_node->counter > 0)
406 return 0;
407 }
408
409 /* Construct a log message. */
410 ret_sz = snprintf(buf, MAX_LOG_MSG_LEN,
411 "%c,%jd.%06ld,%s,%hu,%s,%hu,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,"
412 "%u,%u,%u,%u,%u,%u,%u,%u\n",
413 direction[pkt_node->direction],
414 (intmax_t)pkt_node->tval.tv_sec,
415 pkt_node->tval.tv_usec,
416 hash_node->const_info.laddr,
417 hash_node->const_info.lport,
418 hash_node->const_info.faddr,
419 hash_node->const_info.fport,
420 pkt_node->snd_ssthresh,
421 pkt_node->snd_cwnd,
422 pkt_node->t_flags2,
423 pkt_node->snd_wnd,
424 pkt_node->rcv_wnd,
425 pkt_node->snd_scale,
426 pkt_node->rcv_scale,
427 pkt_node->conn_state,
428 pkt_node->mss,
429 pkt_node->srtt,
430 pkt_node->sack_enabled,
431 pkt_node->t_flags,
432 pkt_node->rto,
433 pkt_node->snd_buf_hiwater,
434 pkt_node->snd_buf_cc,
435 pkt_node->rcv_buf_hiwater,
436 pkt_node->rcv_buf_cc,
437 pkt_node->sent_inflight_bytes,
438 pkt_node->t_segqlen,
439 pkt_node->flowid,
440 pkt_node->flowtype);
441
442 return ret_sz;
443 }
444
445 static void
siftr_pkt_manager_thread(void * arg)446 siftr_pkt_manager_thread(void *arg)
447 {
448 STAILQ_HEAD(pkthead, pkt_node) tmp_pkt_queue =
449 STAILQ_HEAD_INITIALIZER(tmp_pkt_queue);
450 struct pkt_node *pkt_node;
451 uint8_t draining;
452 struct ale *log_buf;
453 int ret_sz, cnt = 0;
454 char *bufp;
455
456 draining = 2;
457
458 mtx_lock(&siftr_pkt_mgr_mtx);
459
460 /* draining == 0 when queue has been flushed and it's safe to exit. */
461 while (draining) {
462 /*
463 * Sleep until we are signalled to wake because thread has
464 * been told to exit or until 1 tick has passed.
465 */
466 mtx_sleep(&wait_for_pkt, &siftr_pkt_mgr_mtx, PWAIT, "pktwait",
467 1);
468
469 /* Gain exclusive access to the pkt_node queue. */
470 mtx_lock(&siftr_pkt_queue_mtx);
471
472 /*
473 * Move pkt_queue to tmp_pkt_queue, which leaves
474 * pkt_queue empty and ready to receive more pkt_nodes.
475 */
476 STAILQ_CONCAT(&tmp_pkt_queue, &pkt_queue);
477
478 /*
479 * We've finished making changes to the list. Unlock it
480 * so the pfil hooks can continue queuing pkt_nodes.
481 */
482 mtx_unlock(&siftr_pkt_queue_mtx);
483
484 /*
485 * We can't hold a mutex whilst calling siftr_process_pkt
486 * because ALQ might sleep waiting for buffer space.
487 */
488 mtx_unlock(&siftr_pkt_mgr_mtx);
489
490 while ((pkt_node = STAILQ_FIRST(&tmp_pkt_queue)) != NULL) {
491
492 log_buf = alq_getn(siftr_alq, MAX_LOG_MSG_LEN *
493 ((STAILQ_NEXT(pkt_node, nodes) != NULL) ?
494 MAX_LOG_BATCH_SIZE : 1),
495 ALQ_WAITOK);
496
497 if (log_buf != NULL) {
498 log_buf->ae_bytesused = 0;
499 bufp = log_buf->ae_data;
500 } else {
501 /*
502 * Should only happen if the ALQ is shutting
503 * down.
504 */
505 bufp = NULL;
506 }
507
508 /* Flush all pkt_nodes to the log file. */
509 STAILQ_FOREACH(pkt_node, &tmp_pkt_queue, nodes) {
510 if (log_buf != NULL) {
511 ret_sz = siftr_process_pkt(pkt_node,
512 bufp);
513 bufp += ret_sz;
514 log_buf->ae_bytesused += ret_sz;
515 }
516 if (++cnt >= MAX_LOG_BATCH_SIZE)
517 break;
518 }
519 if (log_buf != NULL) {
520 alq_post_flags(siftr_alq, log_buf, 0);
521 }
522 for (;cnt > 0; cnt--) {
523 pkt_node = STAILQ_FIRST(&tmp_pkt_queue);
524 STAILQ_REMOVE_HEAD(&tmp_pkt_queue, nodes);
525 free(pkt_node, M_SIFTR_PKTNODE);
526 }
527 }
528
529 KASSERT(STAILQ_EMPTY(&tmp_pkt_queue),
530 ("SIFTR tmp_pkt_queue not empty after flush"));
531
532 mtx_lock(&siftr_pkt_mgr_mtx);
533
534 /*
535 * If siftr_exit_pkt_manager_thread gets set during the window
536 * where we are draining the tmp_pkt_queue above, there might
537 * still be pkts in pkt_queue that need to be drained.
538 * Allow one further iteration to occur after
539 * siftr_exit_pkt_manager_thread has been set to ensure
540 * pkt_queue is completely empty before we kill the thread.
541 *
542 * siftr_exit_pkt_manager_thread is set only after the pfil
543 * hooks have been removed, so only 1 extra iteration
544 * is needed to drain the queue.
545 */
546 if (siftr_exit_pkt_manager_thread)
547 draining--;
548 }
549
550 mtx_unlock(&siftr_pkt_mgr_mtx);
551
552 /* Calls wakeup on this thread's struct thread ptr. */
553 kthread_exit();
554 }
555
556 /*
557 * Check if a given mbuf has the SIFTR mbuf tag. If it does, log the fact that
558 * it's a reinjected packet and return. If it doesn't, tag the mbuf and return.
559 * Return value >0 means the caller should skip processing this mbuf.
560 */
561 static inline int
siftr_chkreinject(struct mbuf * m,int dir,struct siftr_stats * ss)562 siftr_chkreinject(struct mbuf *m, int dir, struct siftr_stats *ss)
563 {
564 if (m_tag_locate(m, PACKET_COOKIE_SIFTR, PACKET_TAG_SIFTR, NULL)
565 != NULL) {
566 if (dir == PFIL_IN)
567 ss->nskip_in_dejavu++;
568 else
569 ss->nskip_out_dejavu++;
570
571 return (1);
572 } else {
573 struct m_tag *tag = m_tag_alloc(PACKET_COOKIE_SIFTR,
574 PACKET_TAG_SIFTR, 0, M_NOWAIT);
575 if (tag == NULL) {
576 if (dir == PFIL_IN)
577 ss->nskip_in_malloc++;
578 else
579 ss->nskip_out_malloc++;
580
581 return (1);
582 }
583
584 m_tag_prepend(m, tag);
585 }
586
587 return (0);
588 }
589
590 /*
591 * Look up an inpcb for a packet. Return the inpcb pointer if found, or NULL
592 * otherwise.
593 */
594 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)595 siftr_findinpcb(int ipver, struct ip *ip, struct mbuf *m, uint16_t sport,
596 uint16_t dport, int dir, struct siftr_stats *ss)
597 {
598 struct inpcb *inp;
599
600 if (dir == PFIL_IN)
601 inp = (ipver == INP_IPV4 ?
602 in_pcblookup(&V_tcbinfo, ip->ip_src, sport, ip->ip_dst,
603 dport, INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif)
604 :
605 #ifdef SIFTR_IPV6
606 in6_pcblookup(&V_tcbinfo,
607 &((struct ip6_hdr *)ip)->ip6_src, sport,
608 &((struct ip6_hdr *)ip)->ip6_dst, dport, INPLOOKUP_RLOCKPCB,
609 m->m_pkthdr.rcvif)
610 #else
611 NULL
612 #endif
613 );
614
615 else
616 inp = (ipver == INP_IPV4 ?
617 in_pcblookup(&V_tcbinfo, ip->ip_dst, dport, ip->ip_src,
618 sport, INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif)
619 :
620 #ifdef SIFTR_IPV6
621 in6_pcblookup(&V_tcbinfo,
622 &((struct ip6_hdr *)ip)->ip6_dst, dport,
623 &((struct ip6_hdr *)ip)->ip6_src, sport, INPLOOKUP_RLOCKPCB,
624 m->m_pkthdr.rcvif)
625 #else
626 NULL
627 #endif
628 );
629
630 /* If we can't find the inpcb, bail. */
631 if (inp == NULL) {
632 if (dir == PFIL_IN)
633 ss->nskip_in_inpcb++;
634 else
635 ss->nskip_out_inpcb++;
636 }
637
638 return (inp);
639 }
640
641 static inline uint32_t
siftr_get_flowid(struct inpcb * inp,int ipver,uint32_t * phashtype)642 siftr_get_flowid(struct inpcb *inp, int ipver, uint32_t *phashtype)
643 {
644 if (inp->inp_flowid == 0) {
645 #ifdef SIFTR_IPV6
646 if (ipver == INP_IPV6) {
647 return fib6_calc_packet_hash(&inp->in6p_laddr,
648 &inp->in6p_faddr,
649 inp->inp_lport,
650 inp->inp_fport,
651 IPPROTO_TCP,
652 phashtype);
653 } else
654 #endif
655 {
656 return fib4_calc_packet_hash(inp->inp_laddr,
657 inp->inp_faddr,
658 inp->inp_lport,
659 inp->inp_fport,
660 IPPROTO_TCP,
661 phashtype);
662 }
663 } else {
664 *phashtype = inp->inp_flowtype;
665 return inp->inp_flowid;
666 }
667 }
668
669 static inline void
siftr_siftdata(struct pkt_node * pn,struct inpcb * inp,struct tcpcb * tp,int ipver,int dir,int inp_locally_locked)670 siftr_siftdata(struct pkt_node *pn, struct inpcb *inp, struct tcpcb *tp,
671 int ipver, int dir, int inp_locally_locked)
672 {
673 pn->ipver = ipver;
674 pn->lport = inp->inp_lport;
675 pn->fport = inp->inp_fport;
676 pn->laddr = inp->inp_inc.inc_ie.ie_dependladdr;
677 pn->faddr = inp->inp_inc.inc_ie.ie_dependfaddr;
678 pn->snd_cwnd = tp->snd_cwnd;
679 pn->snd_wnd = tp->snd_wnd;
680 pn->rcv_wnd = tp->rcv_wnd;
681 pn->t_flags2 = tp->t_flags2;
682 pn->snd_ssthresh = tp->snd_ssthresh;
683 pn->snd_scale = tp->snd_scale;
684 pn->rcv_scale = tp->rcv_scale;
685 pn->conn_state = tp->t_state;
686 pn->mss = tp->t_maxseg;
687 pn->srtt = ((uint64_t)tp->t_srtt * tick) >> TCP_RTT_SHIFT;
688 pn->sack_enabled = (tp->t_flags & TF_SACK_PERMIT) != 0;
689 pn->t_flags = tp->t_flags;
690 pn->rto = tp->t_rxtcur * tick;
691 pn->snd_buf_hiwater = inp->inp_socket->so_snd.sb_hiwat;
692 pn->snd_buf_cc = sbused(&inp->inp_socket->so_snd);
693 pn->rcv_buf_hiwater = inp->inp_socket->so_rcv.sb_hiwat;
694 pn->rcv_buf_cc = sbused(&inp->inp_socket->so_rcv);
695 pn->sent_inflight_bytes = tp->snd_max - tp->snd_una;
696 pn->t_segqlen = tp->t_segqlen;
697
698 /* We've finished accessing the tcb so release the lock. */
699 if (inp_locally_locked)
700 INP_RUNLOCK(inp);
701
702 pn->direction = (dir == PFIL_IN ? DIR_IN : DIR_OUT);
703
704 /*
705 * Significantly more accurate than using getmicrotime(), but slower!
706 * Gives true microsecond resolution at the expense of a hit to
707 * maximum pps throughput processing when SIFTR is loaded and enabled.
708 */
709 microtime(&pn->tval);
710 TCP_PROBE1(siftr, pn);
711 }
712
713 /*
714 * pfil hook that is called for each IPv4 packet making its way through the
715 * stack in either direction.
716 * The pfil subsystem holds a non-sleepable mutex somewhere when
717 * calling our hook function, so we can't sleep at all.
718 * It's very important to use the M_NOWAIT flag with all function calls
719 * that support it so that they won't sleep, otherwise you get a panic.
720 */
721 static pfil_return_t
siftr_chkpkt(struct mbuf ** m,struct ifnet * ifp,int flags,void * ruleset __unused,struct inpcb * inp)722 siftr_chkpkt(struct mbuf **m, struct ifnet *ifp, int flags,
723 void *ruleset __unused, struct inpcb *inp)
724 {
725 struct pkt_node *pn;
726 struct ip *ip;
727 struct tcphdr *th;
728 struct tcpcb *tp;
729 struct siftr_stats *ss;
730 unsigned int ip_hl;
731 int inp_locally_locked, dir;
732 uint32_t hash_id, hash_type;
733 struct listhead *counter_list;
734 struct flow_hash_node *hash_node;
735
736 inp_locally_locked = 0;
737 dir = PFIL_DIR(flags);
738 ss = DPCPU_PTR(ss);
739
740 /*
741 * m_pullup is not required here because ip_{input|output}
742 * already do the heavy lifting for us.
743 */
744
745 ip = mtod(*m, struct ip *);
746
747 /* Only continue processing if the packet is TCP. */
748 if (ip->ip_p != IPPROTO_TCP)
749 goto ret;
750
751 /*
752 * Create a tcphdr struct starting at the correct offset
753 * in the IP packet. ip->ip_hl gives the ip header length
754 * in 4-byte words, so multiply it to get the size in bytes.
755 */
756 ip_hl = (ip->ip_hl << 2);
757 th = (struct tcphdr *)((caddr_t)ip + ip_hl);
758
759 /*
760 * Only pkts selected by the tcp port filter
761 * can be inserted into the pkt_queue
762 */
763 if ((siftr_port_filter != 0) &&
764 (siftr_port_filter != ntohs(th->th_sport)) &&
765 (siftr_port_filter != ntohs(th->th_dport))) {
766 goto ret;
767 }
768
769 /*
770 * If a kernel subsystem reinjects packets into the stack, our pfil
771 * hook will be called multiple times for the same packet.
772 * Make sure we only process unique packets.
773 */
774 if (siftr_chkreinject(*m, dir, ss))
775 goto ret;
776
777 if (dir == PFIL_IN)
778 ss->n_in++;
779 else
780 ss->n_out++;
781
782 /*
783 * If the pfil hooks don't provide a pointer to the
784 * inpcb, we need to find it ourselves and lock it.
785 */
786 if (!inp) {
787 /* Find the corresponding inpcb for this pkt. */
788 inp = siftr_findinpcb(INP_IPV4, ip, *m, th->th_sport,
789 th->th_dport, dir, ss);
790
791 if (inp == NULL)
792 goto ret;
793 else
794 inp_locally_locked = 1;
795 }
796
797 INP_LOCK_ASSERT(inp);
798
799 /* Find the TCP control block that corresponds with this packet */
800 tp = intotcpcb(inp);
801
802 /*
803 * If we can't find the TCP control block (happens occasionaly for a
804 * packet sent during the shutdown phase of a TCP connection), or the
805 * TCP control block has not initialized (happens during TCPS_SYN_SENT),
806 * bail.
807 */
808 if (tp == NULL || tp->t_state < TCPS_ESTABLISHED) {
809 if (dir == PFIL_IN)
810 ss->nskip_in_tcpcb++;
811 else
812 ss->nskip_out_tcpcb++;
813
814 goto inp_unlock;
815 }
816
817 hash_id = siftr_get_flowid(inp, INP_IPV4, &hash_type);
818 counter_list = counter_hash + (hash_id & siftr_hashmask);
819 hash_node = siftr_find_flow(counter_list, hash_id);
820
821 /* If this flow hasn't been seen before, we create a new entry. */
822 if (hash_node == NULL) {
823 struct flow_info info;
824
825 inet_ntoa_r(inp->inp_laddr, info.laddr);
826 inet_ntoa_r(inp->inp_faddr, info.faddr);
827 info.lport = ntohs(inp->inp_lport);
828 info.fport = ntohs(inp->inp_fport);
829 info.key = hash_id;
830
831 hash_node = siftr_new_hash_node(info, dir, ss);
832 }
833
834 if (hash_node == NULL) {
835 goto inp_unlock;
836 }
837
838 pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
839
840 if (pn == NULL) {
841 if (dir == PFIL_IN)
842 ss->nskip_in_malloc++;
843 else
844 ss->nskip_out_malloc++;
845
846 goto inp_unlock;
847 }
848
849 pn->flowid = hash_id;
850 pn->flowtype = hash_type;
851
852 siftr_siftdata(pn, inp, tp, INP_IPV4, dir, inp_locally_locked);
853
854 mtx_lock(&siftr_pkt_queue_mtx);
855 STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
856 mtx_unlock(&siftr_pkt_queue_mtx);
857 goto ret;
858
859 inp_unlock:
860 if (inp_locally_locked)
861 INP_RUNLOCK(inp);
862
863 ret:
864 return (PFIL_PASS);
865 }
866
867 #ifdef SIFTR_IPV6
868 static pfil_return_t
siftr_chkpkt6(struct mbuf ** m,struct ifnet * ifp,int flags,void * ruleset __unused,struct inpcb * inp)869 siftr_chkpkt6(struct mbuf **m, struct ifnet *ifp, int flags,
870 void *ruleset __unused, struct inpcb *inp)
871 {
872 struct pkt_node *pn;
873 struct ip6_hdr *ip6;
874 struct tcphdr *th;
875 struct tcpcb *tp;
876 struct siftr_stats *ss;
877 unsigned int ip6_hl;
878 int inp_locally_locked, dir;
879 uint32_t hash_id, hash_type;
880 struct listhead *counter_list;
881 struct flow_hash_node *hash_node;
882
883 inp_locally_locked = 0;
884 dir = PFIL_DIR(flags);
885 ss = DPCPU_PTR(ss);
886
887 /*
888 * m_pullup is not required here because ip6_{input|output}
889 * already do the heavy lifting for us.
890 */
891
892 ip6 = mtod(*m, struct ip6_hdr *);
893
894 /*
895 * Only continue processing if the packet is TCP
896 * XXX: We should follow the next header fields
897 * as shown on Pg 6 RFC 2460, but right now we'll
898 * only check pkts that have no extension headers.
899 */
900 if (ip6->ip6_nxt != IPPROTO_TCP)
901 goto ret6;
902
903 /*
904 * Create a tcphdr struct starting at the correct offset
905 * in the ipv6 packet.
906 */
907 ip6_hl = sizeof(struct ip6_hdr);
908 th = (struct tcphdr *)((caddr_t)ip6 + ip6_hl);
909
910 /*
911 * Only pkts selected by the tcp port filter
912 * can be inserted into the pkt_queue
913 */
914 if ((siftr_port_filter != 0) &&
915 (siftr_port_filter != ntohs(th->th_sport)) &&
916 (siftr_port_filter != ntohs(th->th_dport))) {
917 goto ret6;
918 }
919
920 /*
921 * If a kernel subsystem reinjects packets into the stack, our pfil
922 * hook will be called multiple times for the same packet.
923 * Make sure we only process unique packets.
924 */
925 if (siftr_chkreinject(*m, dir, ss))
926 goto ret6;
927
928 if (dir == PFIL_IN)
929 ss->n_in++;
930 else
931 ss->n_out++;
932
933 /*
934 * For inbound packets, the pfil hooks don't provide a pointer to the
935 * inpcb, so we need to find it ourselves and lock it.
936 */
937 if (!inp) {
938 /* Find the corresponding inpcb for this pkt. */
939 inp = siftr_findinpcb(INP_IPV6, (struct ip *)ip6, *m,
940 th->th_sport, th->th_dport, dir, ss);
941
942 if (inp == NULL)
943 goto ret6;
944 else
945 inp_locally_locked = 1;
946 }
947
948 /* Find the TCP control block that corresponds with this packet. */
949 tp = intotcpcb(inp);
950
951 /*
952 * If we can't find the TCP control block (happens occasionaly for a
953 * packet sent during the shutdown phase of a TCP connection), or the
954 * TCP control block has not initialized (happens during TCPS_SYN_SENT),
955 * bail.
956 */
957 if (tp == NULL || tp->t_state < TCPS_ESTABLISHED) {
958 if (dir == PFIL_IN)
959 ss->nskip_in_tcpcb++;
960 else
961 ss->nskip_out_tcpcb++;
962
963 goto inp_unlock6;
964 }
965
966 hash_id = siftr_get_flowid(inp, INP_IPV6, &hash_type);
967 counter_list = counter_hash + (hash_id & siftr_hashmask);
968 hash_node = siftr_find_flow(counter_list, hash_id);
969
970 /* If this flow hasn't been seen before, we create a new entry. */
971 if (!hash_node) {
972 struct flow_info info;
973
974 ip6_sprintf(info.laddr, &inp->in6p_laddr);
975 ip6_sprintf(info.faddr, &inp->in6p_faddr);
976 info.lport = ntohs(inp->inp_lport);
977 info.fport = ntohs(inp->inp_fport);
978 info.key = hash_id;
979
980 hash_node = siftr_new_hash_node(info, dir, ss);
981 }
982
983 if (!hash_node) {
984 goto inp_unlock6;
985 }
986
987 pn = malloc(sizeof(struct pkt_node), M_SIFTR_PKTNODE, M_NOWAIT|M_ZERO);
988
989 if (pn == NULL) {
990 if (dir == PFIL_IN)
991 ss->nskip_in_malloc++;
992 else
993 ss->nskip_out_malloc++;
994
995 goto inp_unlock6;
996 }
997
998 pn->flowid = hash_id;
999 pn->flowtype = hash_type;
1000
1001 siftr_siftdata(pn, inp, tp, INP_IPV6, dir, inp_locally_locked);
1002
1003 mtx_lock(&siftr_pkt_queue_mtx);
1004 STAILQ_INSERT_TAIL(&pkt_queue, pn, nodes);
1005 mtx_unlock(&siftr_pkt_queue_mtx);
1006 goto ret6;
1007
1008 inp_unlock6:
1009 if (inp_locally_locked)
1010 INP_RUNLOCK(inp);
1011
1012 ret6:
1013 return (PFIL_PASS);
1014 }
1015 #endif /* #ifdef SIFTR_IPV6 */
1016
1017 VNET_DEFINE_STATIC(pfil_hook_t, siftr_inet_hook);
1018 #define V_siftr_inet_hook VNET(siftr_inet_hook)
1019 #ifdef SIFTR_IPV6
1020 VNET_DEFINE_STATIC(pfil_hook_t, siftr_inet6_hook);
1021 #define V_siftr_inet6_hook VNET(siftr_inet6_hook)
1022 #endif
1023 static int
siftr_pfil(int action)1024 siftr_pfil(int action)
1025 {
1026 struct pfil_hook_args pha = {
1027 .pa_version = PFIL_VERSION,
1028 .pa_flags = PFIL_IN | PFIL_OUT,
1029 .pa_modname = "siftr",
1030 .pa_rulname = "default",
1031 };
1032 struct pfil_link_args pla = {
1033 .pa_version = PFIL_VERSION,
1034 .pa_flags = PFIL_IN | PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR,
1035 };
1036
1037 VNET_ITERATOR_DECL(vnet_iter);
1038
1039 VNET_LIST_RLOCK();
1040 VNET_FOREACH(vnet_iter) {
1041 CURVNET_SET(vnet_iter);
1042
1043 if (action == HOOK) {
1044 pha.pa_mbuf_chk = siftr_chkpkt;
1045 pha.pa_type = PFIL_TYPE_IP4;
1046 V_siftr_inet_hook = pfil_add_hook(&pha);
1047 pla.pa_hook = V_siftr_inet_hook;
1048 pla.pa_head = V_inet_pfil_head;
1049 (void)pfil_link(&pla);
1050 #ifdef SIFTR_IPV6
1051 pha.pa_mbuf_chk = siftr_chkpkt6;
1052 pha.pa_type = PFIL_TYPE_IP6;
1053 V_siftr_inet6_hook = pfil_add_hook(&pha);
1054 pla.pa_hook = V_siftr_inet6_hook;
1055 pla.pa_head = V_inet6_pfil_head;
1056 (void)pfil_link(&pla);
1057 #endif
1058 } else if (action == UNHOOK) {
1059 pfil_remove_hook(V_siftr_inet_hook);
1060 #ifdef SIFTR_IPV6
1061 pfil_remove_hook(V_siftr_inet6_hook);
1062 #endif
1063 }
1064 CURVNET_RESTORE();
1065 }
1066 VNET_LIST_RUNLOCK();
1067
1068 return (0);
1069 }
1070
1071 static int
siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS)1072 siftr_sysctl_logfile_name_handler(SYSCTL_HANDLER_ARGS)
1073 {
1074 struct alq *new_alq;
1075 int error;
1076
1077 error = sysctl_handle_string(oidp, arg1, arg2, req);
1078
1079 /* Check for error or same filename */
1080 if (error != 0 || req->newptr == NULL ||
1081 strncmp(siftr_logfile, arg1, arg2) == 0)
1082 goto done;
1083
1084 /* file name changed */
1085 error = alq_open(&new_alq, arg1, curthread->td_ucred,
1086 SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1087 if (error != 0)
1088 goto done;
1089
1090 /*
1091 * If disabled, siftr_alq == NULL so we simply close
1092 * the alq as we've proved it can be opened.
1093 * If enabled, close the existing alq and switch the old
1094 * for the new.
1095 */
1096 if (siftr_alq == NULL) {
1097 alq_close(new_alq);
1098 } else {
1099 alq_close(siftr_alq);
1100 siftr_alq = new_alq;
1101 }
1102
1103 /* Update filename upon success */
1104 strlcpy(siftr_logfile, arg1, arg2);
1105 done:
1106 return (error);
1107 }
1108
1109 static int
siftr_manage_ops(uint8_t action)1110 siftr_manage_ops(uint8_t action)
1111 {
1112 struct siftr_stats totalss;
1113 struct timeval tval;
1114 struct flow_hash_node *counter, *tmp_counter;
1115 struct sbuf *s;
1116 int i, error;
1117 uint32_t bytes_to_write, total_skipped_pkts;
1118
1119 error = 0;
1120 total_skipped_pkts = 0;
1121
1122 /* Init an autosizing sbuf that initially holds 200 chars. */
1123 if ((s = sbuf_new(NULL, NULL, 200, SBUF_AUTOEXTEND)) == NULL)
1124 return (-1);
1125
1126 if (action == SIFTR_ENABLE && siftr_pkt_manager_thr == NULL) {
1127 /*
1128 * Create our alq
1129 * XXX: We should abort if alq_open fails!
1130 */
1131 alq_open(&siftr_alq, siftr_logfile, curthread->td_ucred,
1132 SIFTR_LOG_FILE_MODE, SIFTR_ALQ_BUFLEN, 0);
1133
1134 STAILQ_INIT(&pkt_queue);
1135
1136 DPCPU_ZERO(ss);
1137
1138 siftr_exit_pkt_manager_thread = 0;
1139
1140 kthread_add(&siftr_pkt_manager_thread, NULL, NULL,
1141 &siftr_pkt_manager_thr, RFNOWAIT, 0,
1142 "siftr_pkt_manager_thr");
1143
1144 siftr_pfil(HOOK);
1145
1146 microtime(&tval);
1147
1148 sbuf_printf(s,
1149 "enable_time_secs=%jd\tenable_time_usecs=%06ld\t"
1150 "siftrver=%s\tsysname=%s\tsysver=%u\tipmode=%u\n",
1151 (intmax_t)tval.tv_sec, tval.tv_usec, MODVERSION_STR,
1152 SYS_NAME, __FreeBSD_version, SIFTR_IPMODE);
1153
1154 sbuf_finish(s);
1155 alq_writen(siftr_alq, sbuf_data(s), sbuf_len(s), ALQ_WAITOK);
1156
1157 } else if (action == SIFTR_DISABLE && siftr_pkt_manager_thr != NULL) {
1158 /*
1159 * Remove the pfil hook functions. All threads currently in
1160 * the hook functions are allowed to exit before siftr_pfil()
1161 * returns.
1162 */
1163 siftr_pfil(UNHOOK);
1164
1165 /* This will block until the pkt manager thread unlocks it. */
1166 mtx_lock(&siftr_pkt_mgr_mtx);
1167
1168 /* Tell the pkt manager thread that it should exit now. */
1169 siftr_exit_pkt_manager_thread = 1;
1170
1171 /*
1172 * Wake the pkt_manager thread so it realises that
1173 * siftr_exit_pkt_manager_thread == 1 and exits gracefully.
1174 * The wakeup won't be delivered until we unlock
1175 * siftr_pkt_mgr_mtx so this isn't racy.
1176 */
1177 wakeup(&wait_for_pkt);
1178
1179 /* Wait for the pkt_manager thread to exit. */
1180 mtx_sleep(siftr_pkt_manager_thr, &siftr_pkt_mgr_mtx, PWAIT,
1181 "thrwait", 0);
1182
1183 siftr_pkt_manager_thr = NULL;
1184 mtx_unlock(&siftr_pkt_mgr_mtx);
1185
1186 totalss.n_in = DPCPU_VARSUM(ss, n_in);
1187 totalss.n_out = DPCPU_VARSUM(ss, n_out);
1188 totalss.nskip_in_malloc = DPCPU_VARSUM(ss, nskip_in_malloc);
1189 totalss.nskip_out_malloc = DPCPU_VARSUM(ss, nskip_out_malloc);
1190 totalss.nskip_in_tcpcb = DPCPU_VARSUM(ss, nskip_in_tcpcb);
1191 totalss.nskip_out_tcpcb = DPCPU_VARSUM(ss, nskip_out_tcpcb);
1192 totalss.nskip_in_inpcb = DPCPU_VARSUM(ss, nskip_in_inpcb);
1193 totalss.nskip_out_inpcb = DPCPU_VARSUM(ss, nskip_out_inpcb);
1194
1195 total_skipped_pkts = totalss.nskip_in_malloc +
1196 totalss.nskip_out_malloc + totalss.nskip_in_tcpcb +
1197 totalss.nskip_out_tcpcb + totalss.nskip_in_inpcb +
1198 totalss.nskip_out_inpcb;
1199
1200 microtime(&tval);
1201
1202 sbuf_printf(s,
1203 "disable_time_secs=%jd\tdisable_time_usecs=%06ld\t"
1204 "num_inbound_tcp_pkts=%ju\tnum_outbound_tcp_pkts=%ju\t"
1205 "total_tcp_pkts=%ju\tnum_inbound_skipped_pkts_malloc=%u\t"
1206 "num_outbound_skipped_pkts_malloc=%u\t"
1207 "num_inbound_skipped_pkts_tcpcb=%u\t"
1208 "num_outbound_skipped_pkts_tcpcb=%u\t"
1209 "num_inbound_skipped_pkts_inpcb=%u\t"
1210 "num_outbound_skipped_pkts_inpcb=%u\t"
1211 "total_skipped_tcp_pkts=%u\tflow_list=",
1212 (intmax_t)tval.tv_sec,
1213 tval.tv_usec,
1214 (uintmax_t)totalss.n_in,
1215 (uintmax_t)totalss.n_out,
1216 (uintmax_t)(totalss.n_in + totalss.n_out),
1217 totalss.nskip_in_malloc,
1218 totalss.nskip_out_malloc,
1219 totalss.nskip_in_tcpcb,
1220 totalss.nskip_out_tcpcb,
1221 totalss.nskip_in_inpcb,
1222 totalss.nskip_out_inpcb,
1223 total_skipped_pkts);
1224
1225 /*
1226 * Iterate over the flow hash, printing a summary of each
1227 * flow seen and freeing any malloc'd memory.
1228 * The hash consists of an array of LISTs (man 3 queue).
1229 */
1230 for (i = 0; i <= siftr_hashmask; i++) {
1231 LIST_FOREACH_SAFE(counter, counter_hash + i, nodes,
1232 tmp_counter) {
1233 sbuf_printf(s, "%s;%hu-%s;%hu,",
1234 counter->const_info.laddr,
1235 counter->const_info.lport,
1236 counter->const_info.faddr,
1237 counter->const_info.fport);
1238
1239 free(counter, M_SIFTR_HASHNODE);
1240 }
1241
1242 LIST_INIT(counter_hash + i);
1243 }
1244
1245 sbuf_printf(s, "\n");
1246 sbuf_finish(s);
1247
1248 i = 0;
1249 do {
1250 bytes_to_write = min(SIFTR_ALQ_BUFLEN, sbuf_len(s)-i);
1251 alq_writen(siftr_alq, sbuf_data(s)+i, bytes_to_write, ALQ_WAITOK);
1252 i += bytes_to_write;
1253 } while (i < sbuf_len(s));
1254
1255 alq_close(siftr_alq);
1256 siftr_alq = NULL;
1257 } else
1258 error = EINVAL;
1259
1260 sbuf_delete(s);
1261
1262 /*
1263 * XXX: Should be using ret to check if any functions fail
1264 * and set error appropriately
1265 */
1266
1267 return (error);
1268 }
1269
1270 static int
siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS)1271 siftr_sysctl_enabled_handler(SYSCTL_HANDLER_ARGS)
1272 {
1273 int error;
1274 uint32_t new;
1275
1276 new = siftr_enabled;
1277 error = sysctl_handle_int(oidp, &new, 0, req);
1278 if (error == 0 && req->newptr != NULL) {
1279 if (new > 1)
1280 return (EINVAL);
1281 else if (new != siftr_enabled) {
1282 if ((error = siftr_manage_ops(new)) == 0) {
1283 siftr_enabled = new;
1284 } else {
1285 siftr_manage_ops(SIFTR_DISABLE);
1286 }
1287 }
1288 }
1289
1290 return (error);
1291 }
1292
1293 static void
siftr_shutdown_handler(void * arg,int howto)1294 siftr_shutdown_handler(void *arg, int howto)
1295 {
1296 if ((howto & RB_NOSYNC) != 0 || SCHEDULER_STOPPED())
1297 return;
1298
1299 if (siftr_enabled == 1) {
1300 siftr_manage_ops(SIFTR_DISABLE);
1301 }
1302 }
1303
1304 /*
1305 * Module is being unloaded or machine is shutting down. Take care of cleanup.
1306 */
1307 static int
deinit_siftr(void)1308 deinit_siftr(void)
1309 {
1310 /* Cleanup. */
1311 EVENTHANDLER_DEREGISTER(shutdown_pre_sync, siftr_shutdown_tag);
1312 siftr_manage_ops(SIFTR_DISABLE);
1313 hashdestroy(counter_hash, M_SIFTR, siftr_hashmask);
1314 mtx_destroy(&siftr_pkt_queue_mtx);
1315 mtx_destroy(&siftr_pkt_mgr_mtx);
1316
1317 return (0);
1318 }
1319
1320 /*
1321 * Module has just been loaded into the kernel.
1322 */
1323 static int
init_siftr(void)1324 init_siftr(void)
1325 {
1326 siftr_shutdown_tag = EVENTHANDLER_REGISTER(shutdown_pre_sync,
1327 siftr_shutdown_handler, NULL, SHUTDOWN_PRI_FIRST);
1328
1329 /* Initialise our flow counter hash table. */
1330 counter_hash = hashinit(SIFTR_EXPECTED_MAX_TCP_FLOWS, M_SIFTR,
1331 &siftr_hashmask);
1332
1333 mtx_init(&siftr_pkt_queue_mtx, "siftr_pkt_queue_mtx", NULL, MTX_DEF);
1334 mtx_init(&siftr_pkt_mgr_mtx, "siftr_pkt_mgr_mtx", NULL, MTX_DEF);
1335
1336 /* Print message to the user's current terminal. */
1337 uprintf("\nStatistical Information For TCP Research (SIFTR) %s\n"
1338 " http://caia.swin.edu.au/urp/newtcp\n\n",
1339 MODVERSION_STR);
1340
1341 return (0);
1342 }
1343
1344 /*
1345 * This is the function that is called to load and unload the module.
1346 * When the module is loaded, this function is called once with
1347 * "what" == MOD_LOAD
1348 * When the module is unloaded, this function is called twice with
1349 * "what" = MOD_QUIESCE first, followed by "what" = MOD_UNLOAD second
1350 * When the system is shut down e.g. CTRL-ALT-DEL or using the shutdown command,
1351 * this function is called once with "what" = MOD_SHUTDOWN
1352 * When the system is shut down, the handler isn't called until the very end
1353 * of the shutdown sequence i.e. after the disks have been synced.
1354 */
1355 static int
siftr_load_handler(module_t mod,int what,void * arg)1356 siftr_load_handler(module_t mod, int what, void *arg)
1357 {
1358 int ret;
1359
1360 switch (what) {
1361 case MOD_LOAD:
1362 ret = init_siftr();
1363 break;
1364
1365 case MOD_QUIESCE:
1366 case MOD_SHUTDOWN:
1367 ret = deinit_siftr();
1368 break;
1369
1370 case MOD_UNLOAD:
1371 ret = 0;
1372 break;
1373
1374 default:
1375 ret = EINVAL;
1376 break;
1377 }
1378
1379 return (ret);
1380 }
1381
1382 static moduledata_t siftr_mod = {
1383 .name = "siftr",
1384 .evhand = siftr_load_handler,
1385 };
1386
1387 /*
1388 * Param 1: name of the kernel module
1389 * Param 2: moduledata_t struct containing info about the kernel module
1390 * and the execution entry point for the module
1391 * Param 3: From sysinit_sub_id enumeration in /usr/include/sys/kernel.h
1392 * Defines the module initialisation order
1393 * Param 4: From sysinit_elem_order enumeration in /usr/include/sys/kernel.h
1394 * Defines the initialisation order of this kld relative to others
1395 * within the same subsystem as defined by param 3
1396 */
1397 DECLARE_MODULE(siftr, siftr_mod, SI_SUB_LAST, SI_ORDER_ANY);
1398 MODULE_DEPEND(siftr, alq, 1, 1, 1);
1399 MODULE_VERSION(siftr, MODVERSION);
1400