2 * Copyright (c) 2010-2011 Alexander V. Chernikov <melifaro@ipfw.ru>
3 * Copyright (c) 2004-2005 Gleb Smirnoff <glebius@FreeBSD.org>
4 * Copyright (c) 2001-2003 Roman V. Palagin <romanp@unshadow.net>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * $SourceForge: netflow.c,v 1.41 2004/09/05 11:41:10 glebius Exp $
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
34 #include "opt_inet6.h"
35 #include "opt_route.h"
36 #include <sys/param.h>
37 #include <sys/kernel.h>
38 #include <sys/limits.h>
40 #include <sys/syslog.h>
41 #include <sys/systm.h>
42 #include <sys/socket.h>
43 #include <sys/endian.h>
45 #include <machine/atomic.h>
46 #include <machine/stdarg.h>
49 #include <net/route.h>
50 #include <net/ethernet.h>
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
54 #include <netinet/ip6.h>
55 #include <netinet/tcp.h>
56 #include <netinet/udp.h>
58 #include <netgraph/ng_message.h>
59 #include <netgraph/netgraph.h>
61 #include <netgraph/netflow/netflow.h>
62 #include <netgraph/netflow/netflow_v9.h>
63 #include <netgraph/netflow/ng_netflow.h>
65 #define NBUCKETS (65536) /* must be power of 2 */
67 /* This hash is for TCP or UDP packets. */
68 #define FULL_HASH(addr1, addr2, port1, port2) \
69 (((addr1 ^ (addr1 >> 16) ^ \
70 htons(addr2 ^ (addr2 >> 16))) ^ \
71 port1 ^ htons(port2)) & \
74 /* This hash is for all other IP packets. */
75 #define ADDR_HASH(addr1, addr2) \
76 ((addr1 ^ (addr1 >> 16) ^ \
77 htons(addr2 ^ (addr2 >> 16))) & \
80 /* Macros to shorten logical constructions */
81 /* XXX: priv must exist in namespace */
82 #define INACTIVE(fle) (time_uptime - fle->f.last > priv->info.nfinfo_inact_t)
83 #define AGED(fle) (time_uptime - fle->f.first > priv->info.nfinfo_act_t)
84 #define ISFREE(fle) (fle->f.packets == 0)
87 * 4 is a magical number: statistically number of 4-packet flows is
88 * bigger than 5,6,7...-packet flows by an order of magnitude. Most UDP/ICMP
89 * scans are 1 packet (~ 90% of flow cache). TCP scans are 2-packet in case
90 * of reachable host and 4-packet otherwise.
92 #define SMALL(fle) (fle->f.packets <= 4)
94 MALLOC_DEFINE(M_NETFLOW_HASH, "netflow_hash", "NetFlow hash");
96 static int export_add(item_p, struct flow_entry *);
97 static int export_send(priv_p, fib_export_p, item_p, int);
99 static int hash_insert(priv_p, struct flow_hash_entry *, struct flow_rec *,
100 int, uint8_t, uint8_t);
102 static int hash6_insert(priv_p, struct flow_hash_entry *, struct flow6_rec *,
103 int, uint8_t, uint8_t);
106 static void expire_flow(priv_p, fib_export_p, struct flow_entry *, int);
109 * Generate hash for a given flow record.
111 * FIB is not used here, because:
112 * most VRFS will carry public IPv4 addresses which are unique even
113 * without FIB private addresses can overlap, but this is worked out
114 * via flow_rec bcmp() containing fib id. In IPv6 world addresses are
115 * all globally unique (it's not fully true, there is FC00::/7 for example,
116 * but chances of address overlap are MUCH smaller)
118 static inline uint32_t
119 ip_hash(struct flow_rec *r)
125 return FULL_HASH(r->r_src.s_addr, r->r_dst.s_addr,
126 r->r_sport, r->r_dport);
128 return ADDR_HASH(r->r_src.s_addr, r->r_dst.s_addr);
133 /* Generate hash for a given flow6 record. Use lower 4 octets from v6 addresses */
134 static inline uint32_t
135 ip6_hash(struct flow6_rec *r)
141 return FULL_HASH(r->src.r_src6.__u6_addr.__u6_addr32[3],
142 r->dst.r_dst6.__u6_addr.__u6_addr32[3], r->r_sport,
145 return ADDR_HASH(r->src.r_src6.__u6_addr.__u6_addr32[3],
146 r->dst.r_dst6.__u6_addr.__u6_addr32[3]);
151 /* This is callback from uma(9), called on alloc. */
153 uma_ctor_flow(void *mem, int size, void *arg, int how)
155 priv_p priv = (priv_p )arg;
157 if (atomic_load_acq_32(&priv->info.nfinfo_used) >= CACHESIZE)
160 atomic_add_32(&priv->info.nfinfo_used, 1);
165 /* This is callback from uma(9), called on free. */
167 uma_dtor_flow(void *mem, int size, void *arg)
169 priv_p priv = (priv_p )arg;
171 atomic_subtract_32(&priv->info.nfinfo_used, 1);
175 /* This is callback from uma(9), called on alloc. */
177 uma_ctor_flow6(void *mem, int size, void *arg, int how)
179 priv_p priv = (priv_p )arg;
181 if (atomic_load_acq_32(&priv->info.nfinfo_used6) >= CACHESIZE)
184 atomic_add_32(&priv->info.nfinfo_used6, 1);
189 /* This is callback from uma(9), called on free. */
191 uma_dtor_flow6(void *mem, int size, void *arg)
193 priv_p priv = (priv_p )arg;
195 atomic_subtract_32(&priv->info.nfinfo_used6, 1);
200 * Detach export datagram from priv, if there is any.
201 * If there is no, allocate a new one.
204 get_export_dgram(priv_p priv, fib_export_p fe)
208 mtx_lock(&fe->export_mtx);
209 if (fe->exp.item != NULL) {
213 mtx_unlock(&fe->export_mtx);
216 struct netflow_v5_export_dgram *dgram;
219 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
222 item = ng_package_data(m, NG_NOFLAGS);
225 dgram = mtod(m, struct netflow_v5_export_dgram *);
226 dgram->header.count = 0;
227 dgram->header.version = htons(NETFLOW_V5);
228 dgram->header.pad = 0;
235 * Re-attach incomplete datagram back to priv.
236 * If there is already another one, then send incomplete. */
238 return_export_dgram(priv_p priv, fib_export_p fe, item_p item, int flags)
242 * It may happen on SMP, that some thread has already
243 * put its item there, in this case we bail out and
244 * send what we have to collector.
246 mtx_lock(&fe->export_mtx);
247 if (fe->exp.item == NULL) {
249 mtx_unlock(&fe->export_mtx);
251 mtx_unlock(&fe->export_mtx);
252 export_send(priv, fe, item, flags);
257 * The flow is over. Call export_add() and free it. If datagram is
258 * full, then call export_send().
261 expire_flow(priv_p priv, fib_export_p fe, struct flow_entry *fle, int flags)
263 struct netflow_export_item exp;
264 uint16_t version = fle->f.version;
266 if ((priv->export != NULL) && (version == IPVERSION)) {
267 exp.item = get_export_dgram(priv, fe);
268 if (exp.item == NULL) {
269 atomic_add_32(&priv->info.nfinfo_export_failed, 1);
270 if (priv->export9 != NULL)
271 atomic_add_32(&priv->info.nfinfo_export9_failed, 1);
272 /* fle definitely contains IPv4 flow. */
273 uma_zfree_arg(priv->zone, fle, priv);
277 if (export_add(exp.item, fle) > 0)
278 export_send(priv, fe, exp.item, flags);
280 return_export_dgram(priv, fe, exp.item, NG_QUEUE);
283 if (priv->export9 != NULL) {
284 exp.item9 = get_export9_dgram(priv, fe, &exp.item9_opt);
285 if (exp.item9 == NULL) {
286 atomic_add_32(&priv->info.nfinfo_export9_failed, 1);
287 if (version == IPVERSION)
288 uma_zfree_arg(priv->zone, fle, priv);
290 else if (version == IP6VERSION)
291 uma_zfree_arg(priv->zone6, fle, priv);
294 panic("ng_netflow: Unknown IP proto: %d",
299 if (export9_add(exp.item9, exp.item9_opt, fle) > 0)
300 export9_send(priv, fe, exp.item9, exp.item9_opt, flags);
302 return_export9_dgram(priv, fe, exp.item9,
303 exp.item9_opt, NG_QUEUE);
306 if (version == IPVERSION)
307 uma_zfree_arg(priv->zone, fle, priv);
309 else if (version == IP6VERSION)
310 uma_zfree_arg(priv->zone6, fle, priv);
314 /* Get a snapshot of node statistics */
316 ng_netflow_copyinfo(priv_p priv, struct ng_netflow_info *i)
320 memcpy((void *)i, (void *)&priv->info, sizeof(priv->info));
324 * Insert a record into defined slot.
326 * First we get for us a free flow entry, then fill in all
327 * possible fields in it.
329 * TODO: consider dropping hash mutex while filling in datagram,
330 * as this was done in previous version. Need to test & profile
334 hash_insert(priv_p priv, struct flow_hash_entry *hsh, struct flow_rec *r,
335 int plen, uint8_t flags, uint8_t tcp_flags)
337 struct flow_entry *fle;
338 struct sockaddr_in sin;
341 mtx_assert(&hsh->mtx, MA_OWNED);
343 fle = uma_zalloc_arg(priv->zone, priv, M_NOWAIT);
345 atomic_add_32(&priv->info.nfinfo_alloc_failed, 1);
350 * Now fle is totally ours. It is detached from all lists,
351 * we can safely edit it.
353 fle->f.version = IPVERSION;
354 bcopy(r, &fle->f.r, sizeof(struct flow_rec));
357 fle->f.tcp_flags = tcp_flags;
359 fle->f.first = fle->f.last = time_uptime;
362 * First we do route table lookup on destination address. So we can
363 * fill in out_ifx, dst_mask, nexthop, and dst_as in future releases.
365 if ((flags & NG_NETFLOW_CONF_NODSTLOOKUP) == 0) {
366 bzero(&sin, sizeof(sin));
367 sin.sin_len = sizeof(struct sockaddr_in);
368 sin.sin_family = AF_INET;
369 sin.sin_addr = fle->f.r.r_dst;
370 rt = rtalloc1_fib((struct sockaddr *)&sin, 0, 0, r->fib);
372 fle->f.fle_o_ifx = rt->rt_ifp->if_index;
374 if (rt->rt_flags & RTF_GATEWAY &&
375 rt->rt_gateway->sa_family == AF_INET)
377 ((struct sockaddr_in *)(rt->rt_gateway))->sin_addr;
381 bitcount32(((struct sockaddr_in *)rt_mask(rt))->sin_addr.s_addr);
382 else if (rt->rt_flags & RTF_HOST)
383 /* Give up. We can't determine mask :( */
384 fle->f.dst_mask = 32;
390 /* Do route lookup on source address, to fill in src_mask. */
391 if ((flags & NG_NETFLOW_CONF_NOSRCLOOKUP) == 0) {
392 bzero(&sin, sizeof(sin));
393 sin.sin_len = sizeof(struct sockaddr_in);
394 sin.sin_family = AF_INET;
395 sin.sin_addr = fle->f.r.r_src;
396 rt = rtalloc1_fib((struct sockaddr *)&sin, 0, 0, r->fib);
400 bitcount32(((struct sockaddr_in *)rt_mask(rt))->sin_addr.s_addr);
401 else if (rt->rt_flags & RTF_HOST)
402 /* Give up. We can't determine mask :( */
403 fle->f.src_mask = 32;
409 /* Push new flow at the and of hash. */
410 TAILQ_INSERT_TAIL(&hsh->head, fle, fle_hash);
416 /* XXX: make normal function, instead of.. */
417 #define ipv6_masklen(x) bitcount32((x).__u6_addr.__u6_addr32[0]) + \
418 bitcount32((x).__u6_addr.__u6_addr32[1]) + \
419 bitcount32((x).__u6_addr.__u6_addr32[2]) + \
420 bitcount32((x).__u6_addr.__u6_addr32[3])
421 #define RT_MASK6(x) (ipv6_masklen(((struct sockaddr_in6 *)rt_mask(x))->sin6_addr))
423 hash6_insert(priv_p priv, struct flow_hash_entry *hsh6, struct flow6_rec *r,
424 int plen, uint8_t flags, uint8_t tcp_flags)
426 struct flow6_entry *fle6;
427 struct sockaddr_in6 *src, *dst;
429 struct route_in6 rin6;
431 mtx_assert(&hsh6->mtx, MA_OWNED);
433 fle6 = uma_zalloc_arg(priv->zone6, priv, M_NOWAIT);
435 atomic_add_32(&priv->info.nfinfo_alloc_failed, 1);
440 * Now fle is totally ours. It is detached from all lists,
441 * we can safely edit it.
444 fle6->f.version = IP6VERSION;
445 bcopy(r, &fle6->f.r, sizeof(struct flow6_rec));
446 fle6->f.bytes = plen;
448 fle6->f.tcp_flags = tcp_flags;
450 fle6->f.first = fle6->f.last = time_uptime;
453 * First we do route table lookup on destination address. So we can
454 * fill in out_ifx, dst_mask, nexthop, and dst_as in future releases.
456 if ((flags & NG_NETFLOW_CONF_NODSTLOOKUP) == 0) {
457 bzero(&rin6, sizeof(struct route_in6));
458 dst = (struct sockaddr_in6 *)&rin6.ro_dst;
459 dst->sin6_len = sizeof(struct sockaddr_in6);
460 dst->sin6_family = AF_INET6;
461 dst->sin6_addr = r->dst.r_dst6;
463 rin6.ro_rt = rtalloc1_fib((struct sockaddr *)dst, 0, 0, r->fib);
465 if (rin6.ro_rt != NULL) {
467 fle6->f.fle_o_ifx = rt->rt_ifp->if_index;
469 if (rt->rt_flags & RTF_GATEWAY &&
470 rt->rt_gateway->sa_family == AF_INET6)
471 fle6->f.n.next_hop6 =
472 ((struct sockaddr_in6 *)(rt->rt_gateway))->sin6_addr;
475 fle6->f.dst_mask = RT_MASK6(rt);
477 fle6->f.dst_mask = 128;
483 if ((flags & NG_NETFLOW_CONF_NODSTLOOKUP) == 0) {
484 /* Do route lookup on source address, to fill in src_mask. */
485 bzero(&rin6, sizeof(struct route_in6));
486 src = (struct sockaddr_in6 *)&rin6.ro_dst;
487 src->sin6_len = sizeof(struct sockaddr_in6);
488 src->sin6_family = AF_INET6;
489 src->sin6_addr = r->src.r_src6;
491 rin6.ro_rt = rtalloc1_fib((struct sockaddr *)src, 0, 0, r->fib);
493 if (rin6.ro_rt != NULL) {
497 fle6->f.src_mask = RT_MASK6(rt);
499 fle6->f.src_mask = 128;
505 /* Push new flow at the and of hash. */
506 TAILQ_INSERT_TAIL(&hsh6->head, (struct flow_entry *)fle6, fle_hash);
516 * Non-static functions called from ng_netflow.c
519 /* Allocate memory and set up flow cache */
521 ng_netflow_cache_init(priv_p priv)
523 struct flow_hash_entry *hsh;
526 /* Initialize cache UMA zone. */
527 priv->zone = uma_zcreate("NetFlow IPv4 cache",
528 sizeof(struct flow_entry), uma_ctor_flow, uma_dtor_flow, NULL,
529 NULL, UMA_ALIGN_CACHE, 0);
530 uma_zone_set_max(priv->zone, CACHESIZE);
532 priv->zone6 = uma_zcreate("NetFlow IPv6 cache",
533 sizeof(struct flow6_entry), uma_ctor_flow6, uma_dtor_flow6, NULL,
534 NULL, UMA_ALIGN_CACHE, 0);
535 uma_zone_set_max(priv->zone6, CACHESIZE);
539 priv->hash = malloc(NBUCKETS * sizeof(struct flow_hash_entry),
540 M_NETFLOW_HASH, M_WAITOK | M_ZERO);
542 /* Initialize hash. */
543 for (i = 0, hsh = priv->hash; i < NBUCKETS; i++, hsh++) {
544 mtx_init(&hsh->mtx, "hash mutex", NULL, MTX_DEF);
545 TAILQ_INIT(&hsh->head);
550 priv->hash6 = malloc(NBUCKETS * sizeof(struct flow_hash_entry),
551 M_NETFLOW_HASH, M_WAITOK | M_ZERO);
553 /* Initialize hash. */
554 for (i = 0, hsh = priv->hash6; i < NBUCKETS; i++, hsh++) {
555 mtx_init(&hsh->mtx, "hash mutex", NULL, MTX_DEF);
556 TAILQ_INIT(&hsh->head);
560 ng_netflow_v9_cache_init(priv);
561 CTR0(KTR_NET, "ng_netflow startup()");
564 /* Initialize new FIB table for v5 and v9 */
566 ng_netflow_fib_init(priv_p priv, int fib)
568 fib_export_p fe = priv_to_fib(priv, fib);
570 CTR1(KTR_NET, "ng_netflow(): fib init: %d", fib);
575 if ((fe = malloc(sizeof(struct fib_export), M_NETGRAPH,
576 M_NOWAIT | M_ZERO)) == NULL)
579 mtx_init(&fe->export_mtx, "export dgram lock", NULL, MTX_DEF);
580 mtx_init(&fe->export9_mtx, "export9 dgram lock", NULL, MTX_DEF);
584 if (atomic_cmpset_ptr((volatile uintptr_t *)&priv->fib_data[fib],
585 (uintptr_t)NULL, (uintptr_t)fe) == 0) {
586 /* FIB already set up by other ISR */
587 CTR3(KTR_NET, "ng_netflow(): fib init: %d setup %p but got %p",
588 fib, fe, priv_to_fib(priv, fib));
589 mtx_destroy(&fe->export_mtx);
590 mtx_destroy(&fe->export9_mtx);
591 free(fe, M_NETGRAPH);
593 /* Increase counter for statistics */
594 CTR3(KTR_NET, "ng_netflow(): fib %d setup to %p (%p)",
595 fib, fe, priv_to_fib(priv, fib));
596 atomic_fetchadd_32(&priv->info.nfinfo_alloc_fibs, 1);
602 /* Free all flow cache memory. Called from node close method. */
604 ng_netflow_cache_flush(priv_p priv)
606 struct flow_entry *fle, *fle1;
607 struct flow_hash_entry *hsh;
608 struct netflow_export_item exp;
612 bzero(&exp, sizeof(exp));
615 * We are going to free probably billable data.
616 * Expire everything before freeing it.
617 * No locking is required since callout is already drained.
619 for (hsh = priv->hash, i = 0; i < NBUCKETS; hsh++, i++)
620 TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
621 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
622 fe = priv_to_fib(priv, fle->f.r.fib);
623 expire_flow(priv, fe, fle, NG_QUEUE);
626 for (hsh = priv->hash6, i = 0; i < NBUCKETS; hsh++, i++)
627 TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
628 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
629 fe = priv_to_fib(priv, fle->f.r.fib);
630 expire_flow(priv, fe, fle, NG_QUEUE);
634 uma_zdestroy(priv->zone);
635 /* Destroy hash mutexes. */
636 for (i = 0, hsh = priv->hash; i < NBUCKETS; i++, hsh++)
637 mtx_destroy(&hsh->mtx);
639 /* Free hash memory. */
640 if (priv->hash != NULL)
641 free(priv->hash, M_NETFLOW_HASH);
643 uma_zdestroy(priv->zone6);
644 /* Destroy hash mutexes. */
645 for (i = 0, hsh = priv->hash6; i < NBUCKETS; i++, hsh++)
646 mtx_destroy(&hsh->mtx);
648 /* Free hash memory. */
649 if (priv->hash6 != NULL)
650 free(priv->hash6, M_NETFLOW_HASH);
653 for (i = 0; i < priv->maxfibs; i++) {
654 if ((fe = priv_to_fib(priv, i)) == NULL)
657 if (fe->exp.item != NULL)
658 export_send(priv, fe, fe->exp.item, NG_QUEUE);
660 if (fe->exp.item9 != NULL)
661 export9_send(priv, fe, fe->exp.item9,
662 fe->exp.item9_opt, NG_QUEUE);
664 mtx_destroy(&fe->export_mtx);
665 mtx_destroy(&fe->export9_mtx);
666 free(fe, M_NETGRAPH);
669 ng_netflow_v9_cache_flush(priv);
672 /* Insert packet from into flow cache. */
674 ng_netflow_flow_add(priv_p priv, fib_export_p fe, struct ip *ip,
675 caddr_t upper_ptr, uint8_t upper_proto, uint8_t flags,
676 unsigned int src_if_index)
678 struct flow_entry *fle, *fle1;
679 struct flow_hash_entry *hsh;
684 uint8_t tcp_flags = 0;
686 bzero(&r, sizeof(r));
688 if (ip->ip_v != IPVERSION)
691 hlen = ip->ip_hl << 2;
692 if (hlen < sizeof(struct ip))
695 eproto = ETHERTYPE_IP;
696 /* Assume L4 template by default */
697 r.flow_type = NETFLOW_V9_FLOW_V4_L4;
699 r.r_src = ip->ip_src;
700 r.r_dst = ip->ip_dst;
703 plen = ntohs(ip->ip_len);
706 r.r_tos = ip->ip_tos;
708 r.r_i_ifx = src_if_index;
711 * XXX NOTE: only first fragment of fragmented TCP, UDP and
712 * ICMP packet will be recorded with proper s_port and d_port.
713 * Following fragments will be recorded simply as IP packet with
714 * ip_proto = ip->ip_p and s_port, d_port set to zero.
715 * I know, it looks like bug. But I don't want to re-implement
716 * ip packet assebmling here. Anyway, (in)famous trafd works this way -
717 * and nobody complains yet :)
719 if ((ip->ip_off & htons(IP_OFFMASK)) == 0)
725 tcp = (struct tcphdr *)((caddr_t )ip + hlen);
726 r.r_sport = tcp->th_sport;
727 r.r_dport = tcp->th_dport;
728 tcp_flags = tcp->th_flags;
732 r.r_ports = *(uint32_t *)((caddr_t )ip + hlen);
736 atomic_fetchadd_32(&priv->info.nfinfo_packets, 1);
738 priv->info.nfinfo_bytes += plen;
740 /* Find hash slot. */
741 hsh = &priv->hash[ip_hash(&r)];
746 * Go through hash and find our entry. If we encounter an
747 * entry, that should be expired, purge it. We do a reverse
748 * search since most active entries are first, and most
749 * searches are done on most active entries.
751 TAILQ_FOREACH_REVERSE_SAFE(fle, &hsh->head, fhead, fle_hash, fle1) {
752 if (bcmp(&r, &fle->f.r, sizeof(struct flow_rec)) == 0)
754 if ((INACTIVE(fle) && SMALL(fle)) || AGED(fle)) {
755 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
756 expire_flow(priv, priv_to_fib(priv, fle->f.r.fib),
758 atomic_add_32(&priv->info.nfinfo_act_exp, 1);
762 if (fle) { /* An existent entry. */
764 fle->f.bytes += plen;
766 fle->f.tcp_flags |= tcp_flags;
767 fle->f.last = time_uptime;
770 * We have the following reasons to expire flow in active way:
771 * - it hit active timeout
772 * - a TCP connection closed
773 * - it is going to overflow counter
775 if (tcp_flags & TH_FIN || tcp_flags & TH_RST || AGED(fle) ||
776 (fle->f.bytes >= (CNTR_MAX - IF_MAXMTU)) ) {
777 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
778 expire_flow(priv, priv_to_fib(priv, fle->f.r.fib),
780 atomic_add_32(&priv->info.nfinfo_act_exp, 1);
783 * It is the newest, move it to the tail,
784 * if it isn't there already. Next search will
787 if (fle != TAILQ_LAST(&hsh->head, fhead)) {
788 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
789 TAILQ_INSERT_TAIL(&hsh->head, fle, fle_hash);
792 } else /* A new flow entry. */
793 error = hash_insert(priv, hsh, &r, plen, flags, tcp_flags);
795 mtx_unlock(&hsh->mtx);
801 /* Insert IPv6 packet from into flow cache. */
803 ng_netflow_flow6_add(priv_p priv, fib_export_p fe, struct ip6_hdr *ip6,
804 caddr_t upper_ptr, uint8_t upper_proto, uint8_t flags,
805 unsigned int src_if_index)
807 struct flow_entry *fle = NULL, *fle1;
808 struct flow6_entry *fle6;
809 struct flow_hash_entry *hsh;
813 uint8_t tcp_flags = 0;
816 if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION)
819 bzero(&r, sizeof(r));
821 r.src.r_src6 = ip6->ip6_src;
822 r.dst.r_dst6 = ip6->ip6_dst;
825 /* Assume L4 template by default */
826 r.flow_type = NETFLOW_V9_FLOW_V6_L4;
828 plen = ntohs(ip6->ip6_plen) + sizeof(struct ip6_hdr);
831 /* XXX: set DSCP/CoS value */
832 r.r_tos = ip->ip_tos;
834 if ((flags & NG_NETFLOW_IS_FRAG) == 0) {
835 switch(upper_proto) {
840 tcp = (struct tcphdr *)upper_ptr;
841 r.r_ports = *(uint32_t *)upper_ptr;
842 tcp_flags = tcp->th_flags;
847 r.r_ports = *(uint32_t *)upper_ptr;
852 r.r_ip_p = upper_proto;
853 r.r_i_ifx = src_if_index;
855 atomic_fetchadd_32(&priv->info.nfinfo_packets6, 1);
857 priv->info.nfinfo_bytes6 += plen;
859 /* Find hash slot. */
860 hsh = &priv->hash6[ip6_hash(&r)];
865 * Go through hash and find our entry. If we encounter an
866 * entry, that should be expired, purge it. We do a reverse
867 * search since most active entries are first, and most
868 * searches are done on most active entries.
870 TAILQ_FOREACH_REVERSE_SAFE(fle, &hsh->head, fhead, fle_hash, fle1) {
871 if (fle->f.version != IP6VERSION)
873 fle6 = (struct flow6_entry *)fle;
874 if (bcmp(&r, &fle6->f.r, sizeof(struct flow6_rec)) == 0)
876 if ((INACTIVE(fle6) && SMALL(fle6)) || AGED(fle6)) {
877 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
878 expire_flow(priv, priv_to_fib(priv, fle->f.r.fib), fle,
880 atomic_add_32(&priv->info.nfinfo_act_exp, 1);
884 if (fle != NULL) { /* An existent entry. */
885 fle6 = (struct flow6_entry *)fle;
887 fle6->f.bytes += plen;
889 fle6->f.tcp_flags |= tcp_flags;
890 fle6->f.last = time_uptime;
893 * We have the following reasons to expire flow in active way:
894 * - it hit active timeout
895 * - a TCP connection closed
896 * - it is going to overflow counter
898 if (tcp_flags & TH_FIN || tcp_flags & TH_RST || AGED(fle6) ||
899 (fle6->f.bytes >= (CNTR_MAX - IF_MAXMTU)) ) {
900 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
901 expire_flow(priv, priv_to_fib(priv, fle->f.r.fib), fle,
903 atomic_add_32(&priv->info.nfinfo_act_exp, 1);
906 * It is the newest, move it to the tail,
907 * if it isn't there already. Next search will
910 if (fle != TAILQ_LAST(&hsh->head, fhead)) {
911 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
912 TAILQ_INSERT_TAIL(&hsh->head, fle, fle_hash);
915 } else /* A new flow entry. */
916 error = hash6_insert(priv, hsh, &r, plen, flags, tcp_flags);
918 mtx_unlock(&hsh->mtx);
925 * Return records from cache to userland.
927 * TODO: matching particular IP should be done in kernel, here.
930 ng_netflow_flow_show(priv_p priv, struct ngnf_show_header *req,
931 struct ngnf_show_header *resp)
933 struct flow_hash_entry *hsh;
934 struct flow_entry *fle;
935 struct flow_entry_data *data = (struct flow_entry_data *)(resp + 1);
937 struct flow6_entry_data *data6 = (struct flow6_entry_data *)(resp + 1);
946 if (req->version == 6) {
948 hsh = priv->hash6 + i;
952 if (req->version == 4) {
954 hsh = priv->hash + i;
960 * We will transfer not more than NREC_AT_ONCE. More data
961 * will come in next message.
962 * We send current hash index and current record number in list
963 * to userland, and userland should return it back to us.
964 * Then, we will restart with new entry.
966 * The resulting cache snapshot can be inaccurate if flow expiration
967 * is taking place on hash item between userland data requests for
971 for (; i < NBUCKETS; hsh++, i++) {
974 if (mtx_trylock(&hsh->mtx) == 0) {
976 * Requested hash index is not available,
977 * relay decision to skip or re-request data
986 TAILQ_FOREACH(fle, &hsh->head, fle_hash) {
987 if (hsh->mtx.mtx_lock & MTX_CONTESTED) {
989 resp->list_id = list_id;
990 mtx_unlock(&hsh->mtx);
995 /* Search for particular record in list. */
996 if (req->list_id > 0) {
997 if (list_id < req->list_id)
1000 /* Requested list position found. */
1004 if (req->version == 6) {
1005 struct flow6_entry *fle6;
1007 fle6 = (struct flow6_entry *)fle;
1008 bcopy(&fle6->f, data6 + resp->nentries,
1012 bcopy(&fle->f, data + resp->nentries,
1015 if (resp->nentries == max) {
1018 * If it was the last item in list
1019 * we simply skip to next hash_id.
1021 resp->list_id = list_id + 1;
1022 mtx_unlock(&hsh->mtx);
1026 mtx_unlock(&hsh->mtx);
1029 resp->hash_id = resp->list_id = 0;
1034 /* We have full datagram in privdata. Send it to export hook. */
1036 export_send(priv_p priv, fib_export_p fe, item_p item, int flags)
1038 struct mbuf *m = NGI_M(item);
1039 struct netflow_v5_export_dgram *dgram = mtod(m,
1040 struct netflow_v5_export_dgram *);
1041 struct netflow_v5_header *header = &dgram->header;
1045 /* Fill mbuf header. */
1046 m->m_len = m->m_pkthdr.len = sizeof(struct netflow_v5_record) *
1047 header->count + sizeof(struct netflow_v5_header);
1049 /* Fill export header. */
1050 header->sys_uptime = htonl(MILLIUPTIME(time_uptime));
1052 header->unix_secs = htonl(ts.tv_sec);
1053 header->unix_nsecs = htonl(ts.tv_nsec);
1054 header->engine_type = 0;
1055 header->engine_id = fe->domain_id;
1057 header->flow_seq = htonl(atomic_fetchadd_32(&fe->flow_seq,
1059 header->count = htons(header->count);
1061 if (priv->export != NULL)
1062 NG_FWD_ITEM_HOOK_FLAGS(error, item, priv->export, flags);
1070 /* Add export record to dgram. */
1072 export_add(item_p item, struct flow_entry *fle)
1074 struct netflow_v5_export_dgram *dgram = mtod(NGI_M(item),
1075 struct netflow_v5_export_dgram *);
1076 struct netflow_v5_header *header = &dgram->header;
1077 struct netflow_v5_record *rec;
1079 rec = &dgram->r[header->count];
1082 KASSERT(header->count <= NETFLOW_V5_MAX_RECORDS,
1083 ("ng_netflow: export too big"));
1085 /* Fill in export record. */
1086 rec->src_addr = fle->f.r.r_src.s_addr;
1087 rec->dst_addr = fle->f.r.r_dst.s_addr;
1088 rec->next_hop = fle->f.next_hop.s_addr;
1089 rec->i_ifx = htons(fle->f.fle_i_ifx);
1090 rec->o_ifx = htons(fle->f.fle_o_ifx);
1091 rec->packets = htonl(fle->f.packets);
1092 rec->octets = htonl(fle->f.bytes);
1093 rec->first = htonl(MILLIUPTIME(fle->f.first));
1094 rec->last = htonl(MILLIUPTIME(fle->f.last));
1095 rec->s_port = fle->f.r.r_sport;
1096 rec->d_port = fle->f.r.r_dport;
1097 rec->flags = fle->f.tcp_flags;
1098 rec->prot = fle->f.r.r_ip_p;
1099 rec->tos = fle->f.r.r_tos;
1100 rec->dst_mask = fle->f.dst_mask;
1101 rec->src_mask = fle->f.src_mask;
1105 /* Not supported fields. */
1106 rec->src_as = rec->dst_as = 0;
1108 if (header->count == NETFLOW_V5_MAX_RECORDS)
1109 return (1); /* end of datagram */
1114 /* Periodic flow expiry run. */
1116 ng_netflow_expire(void *arg)
1118 struct flow_entry *fle, *fle1;
1119 struct flow_hash_entry *hsh;
1120 priv_p priv = (priv_p )arg;
1125 * Going through all the cache.
1127 for (hsh = priv->hash, i = 0; i < NBUCKETS; hsh++, i++) {
1129 * Skip entries, that are already being worked on.
1131 if (mtx_trylock(&hsh->mtx) == 0)
1134 used = atomic_load_acq_32(&priv->info.nfinfo_used);
1135 TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
1137 * Interrupt thread wants this entry!
1138 * Quick! Quick! Bail out!
1140 if (hsh->mtx.mtx_lock & MTX_CONTESTED)
1144 * Don't expire aggressively while hash collision
1145 * ratio is predicted small.
1147 if (used <= (NBUCKETS*2) && !INACTIVE(fle))
1150 if ((INACTIVE(fle) && (SMALL(fle) ||
1151 (used > (NBUCKETS*2)))) || AGED(fle)) {
1152 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
1153 expire_flow(priv, priv_to_fib(priv,
1154 fle->f.r.fib), fle, NG_NOFLAGS);
1156 atomic_add_32(&priv->info.nfinfo_inact_exp, 1);
1159 mtx_unlock(&hsh->mtx);
1163 for (hsh = priv->hash6, i = 0; i < NBUCKETS; hsh++, i++) {
1164 struct flow6_entry *fle6;
1167 * Skip entries, that are already being worked on.
1169 if (mtx_trylock(&hsh->mtx) == 0)
1172 used = atomic_load_acq_32(&priv->info.nfinfo_used6);
1173 TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
1174 fle6 = (struct flow6_entry *)fle;
1176 * Interrupt thread wants this entry!
1177 * Quick! Quick! Bail out!
1179 if (hsh->mtx.mtx_lock & MTX_CONTESTED)
1183 * Don't expire aggressively while hash collision
1184 * ratio is predicted small.
1186 if (used <= (NBUCKETS*2) && !INACTIVE(fle6))
1189 if ((INACTIVE(fle6) && (SMALL(fle6) ||
1190 (used > (NBUCKETS*2)))) || AGED(fle6)) {
1191 TAILQ_REMOVE(&hsh->head, fle, fle_hash);
1192 expire_flow(priv, priv_to_fib(priv,
1193 fle->f.r.fib), fle, NG_NOFLAGS);
1195 atomic_add_32(&priv->info.nfinfo_inact_exp, 1);
1198 mtx_unlock(&hsh->mtx);
1202 /* Schedule next expire. */
1203 callout_reset(&priv->exp_callout, (1*hz), &ng_netflow_expire,