xref: /freebsd/sys/netgraph/netflow/netflow.c (revision 43faedc1339a9624c7acedb7f3e5624e64da5b99)
1 /*-
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>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
15  *
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
26  * SUCH DAMAGE.
27  *
28  * $SourceForge: netflow.c,v 1.41 2004/09/05 11:41:10 glebius Exp $
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include "opt_inet6.h"
35 #include "opt_route.h"
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/counter.h>
39 #include <sys/kernel.h>
40 #include <sys/ktr.h>
41 #include <sys/limits.h>
42 #include <sys/mbuf.h>
43 #include <sys/syslog.h>
44 #include <sys/socket.h>
45 
46 #include <net/if.h>
47 #include <net/if_dl.h>
48 #include <net/if_var.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>
57 
58 #include <netgraph/ng_message.h>
59 #include <netgraph/netgraph.h>
60 
61 #include <netgraph/netflow/netflow.h>
62 #include <netgraph/netflow/netflow_v9.h>
63 #include <netgraph/netflow/ng_netflow.h>
64 
65 #define	NBUCKETS	(65536)		/* must be power of 2 */
66 
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)) &			\
72 	(NBUCKETS - 1))
73 
74 /* This hash is for all other IP packets. */
75 #define ADDR_HASH(addr1, addr2)			\
76 	((addr1 ^ (addr1 >> 16) ^ 		\
77 	htons(addr2 ^ (addr2 >> 16))) &		\
78 	(NBUCKETS - 1))
79 
80 /* Macros to shorten logical constructions */
81 /* XXX: priv must exist in namespace */
82 #define	INACTIVE(fle)	(time_uptime - fle->f.last > priv->nfinfo_inact_t)
83 #define	AGED(fle)	(time_uptime - fle->f.first > priv->nfinfo_act_t)
84 #define	ISFREE(fle)	(fle->f.packets == 0)
85 
86 /*
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.
91  */
92 #define	SMALL(fle)	(fle->f.packets <= 4)
93 
94 MALLOC_DEFINE(M_NETFLOW_HASH, "netflow_hash", "NetFlow hash");
95 
96 static int export_add(item_p, struct flow_entry *);
97 static int export_send(priv_p, fib_export_p, item_p, int);
98 
99 static int hash_insert(priv_p, struct flow_hash_entry *, struct flow_rec *,
100     int, uint8_t, uint8_t);
101 #ifdef INET6
102 static int hash6_insert(priv_p, struct flow_hash_entry *, struct flow6_rec *,
103     int, uint8_t, uint8_t);
104 #endif
105 
106 static void expire_flow(priv_p, fib_export_p, struct flow_entry *, int);
107 
108 /*
109  * Generate hash for a given flow record.
110  *
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)
117  */
118 static inline uint32_t
119 ip_hash(struct flow_rec *r)
120 {
121 
122 	switch (r->r_ip_p) {
123 	case IPPROTO_TCP:
124 	case IPPROTO_UDP:
125 		return FULL_HASH(r->r_src.s_addr, r->r_dst.s_addr,
126 		    r->r_sport, r->r_dport);
127 	default:
128 		return ADDR_HASH(r->r_src.s_addr, r->r_dst.s_addr);
129 	}
130 }
131 
132 #ifdef INET6
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)
136 {
137 
138 	switch (r->r_ip_p) {
139 	case IPPROTO_TCP:
140 	case IPPROTO_UDP:
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,
143 		    r->r_dport);
144 	default:
145 		return ADDR_HASH(r->src.r_src6.__u6_addr.__u6_addr32[3],
146 		    r->dst.r_dst6.__u6_addr.__u6_addr32[3]);
147  	}
148 }
149 #endif
150 
151 /*
152  * Detach export datagram from priv, if there is any.
153  * If there is no, allocate a new one.
154  */
155 static item_p
156 get_export_dgram(priv_p priv, fib_export_p fe)
157 {
158 	item_p	item = NULL;
159 
160 	mtx_lock(&fe->export_mtx);
161 	if (fe->exp.item != NULL) {
162 		item = fe->exp.item;
163 		fe->exp.item = NULL;
164 	}
165 	mtx_unlock(&fe->export_mtx);
166 
167 	if (item == NULL) {
168 		struct netflow_v5_export_dgram *dgram;
169 		struct mbuf *m;
170 
171 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
172 		if (m == NULL)
173 			return (NULL);
174 		item = ng_package_data(m, NG_NOFLAGS);
175 		if (item == NULL)
176 			return (NULL);
177 		dgram = mtod(m, struct netflow_v5_export_dgram *);
178 		dgram->header.count = 0;
179 		dgram->header.version = htons(NETFLOW_V5);
180 		dgram->header.pad = 0;
181 	}
182 
183 	return (item);
184 }
185 
186 /*
187  * Re-attach incomplete datagram back to priv.
188  * If there is already another one, then send incomplete. */
189 static void
190 return_export_dgram(priv_p priv, fib_export_p fe, item_p item, int flags)
191 {
192 
193 	/*
194 	 * It may happen on SMP, that some thread has already
195 	 * put its item there, in this case we bail out and
196 	 * send what we have to collector.
197 	 */
198 	mtx_lock(&fe->export_mtx);
199 	if (fe->exp.item == NULL) {
200 		fe->exp.item = item;
201 		mtx_unlock(&fe->export_mtx);
202 	} else {
203 		mtx_unlock(&fe->export_mtx);
204 		export_send(priv, fe, item, flags);
205 	}
206 }
207 
208 /*
209  * The flow is over. Call export_add() and free it. If datagram is
210  * full, then call export_send().
211  */
212 static void
213 expire_flow(priv_p priv, fib_export_p fe, struct flow_entry *fle, int flags)
214 {
215 	struct netflow_export_item exp;
216 	uint16_t version = fle->f.version;
217 
218 	if ((priv->export != NULL) && (version == IPVERSION)) {
219 		exp.item = get_export_dgram(priv, fe);
220 		if (exp.item == NULL) {
221 			priv->nfinfo_export_failed++;
222 			if (priv->export9 != NULL)
223 				priv->nfinfo_export9_failed++;
224 			/* fle definitely contains IPv4 flow. */
225 			uma_zfree_arg(priv->zone, fle, priv);
226 			return;
227 		}
228 
229 		if (export_add(exp.item, fle) > 0)
230 			export_send(priv, fe, exp.item, flags);
231 		else
232 			return_export_dgram(priv, fe, exp.item, NG_QUEUE);
233 	}
234 
235 	if (priv->export9 != NULL) {
236 		exp.item9 = get_export9_dgram(priv, fe, &exp.item9_opt);
237 		if (exp.item9 == NULL) {
238 			priv->nfinfo_export9_failed++;
239 			if (version == IPVERSION)
240 				uma_zfree_arg(priv->zone, fle, priv);
241 #ifdef INET6
242 			else if (version == IP6VERSION)
243 				uma_zfree_arg(priv->zone6, fle, priv);
244 #endif
245 			else
246 				panic("ng_netflow: Unknown IP proto: %d",
247 				    version);
248 			return;
249 		}
250 
251 		if (export9_add(exp.item9, exp.item9_opt, fle) > 0)
252 			export9_send(priv, fe, exp.item9, exp.item9_opt, flags);
253 		else
254 			return_export9_dgram(priv, fe, exp.item9,
255 			    exp.item9_opt, NG_QUEUE);
256 	}
257 
258 	if (version == IPVERSION)
259 		uma_zfree_arg(priv->zone, fle, priv);
260 #ifdef INET6
261 	else if (version == IP6VERSION)
262 		uma_zfree_arg(priv->zone6, fle, priv);
263 #endif
264 }
265 
266 /* Get a snapshot of node statistics */
267 void
268 ng_netflow_copyinfo(priv_p priv, struct ng_netflow_info *i)
269 {
270 
271 	i->nfinfo_bytes = counter_u64_fetch(priv->nfinfo_bytes);
272 	i->nfinfo_packets = counter_u64_fetch(priv->nfinfo_packets);
273 	i->nfinfo_bytes6 = counter_u64_fetch(priv->nfinfo_bytes6);
274 	i->nfinfo_packets6 = counter_u64_fetch(priv->nfinfo_packets6);
275 	i->nfinfo_sbytes = counter_u64_fetch(priv->nfinfo_sbytes);
276 	i->nfinfo_spackets = counter_u64_fetch(priv->nfinfo_spackets);
277 	i->nfinfo_sbytes6 = counter_u64_fetch(priv->nfinfo_sbytes6);
278 	i->nfinfo_spackets6 = counter_u64_fetch(priv->nfinfo_spackets6);
279 	i->nfinfo_act_exp = counter_u64_fetch(priv->nfinfo_act_exp);
280 	i->nfinfo_inact_exp = counter_u64_fetch(priv->nfinfo_inact_exp);
281 
282 	i->nfinfo_used = uma_zone_get_cur(priv->zone);
283 #ifdef INET6
284 	i->nfinfo_used6 = uma_zone_get_cur(priv->zone6);
285 #endif
286 
287 	i->nfinfo_alloc_failed = priv->nfinfo_alloc_failed;
288 	i->nfinfo_export_failed = priv->nfinfo_export_failed;
289 	i->nfinfo_export9_failed = priv->nfinfo_export9_failed;
290 	i->nfinfo_realloc_mbuf = priv->nfinfo_realloc_mbuf;
291 	i->nfinfo_alloc_fibs = priv->nfinfo_alloc_fibs;
292 	i->nfinfo_inact_t = priv->nfinfo_inact_t;
293 	i->nfinfo_act_t = priv->nfinfo_act_t;
294 }
295 
296 /*
297  * Insert a record into defined slot.
298  *
299  * First we get for us a free flow entry, then fill in all
300  * possible fields in it.
301  *
302  * TODO: consider dropping hash mutex while filling in datagram,
303  * as this was done in previous version. Need to test & profile
304  * to be sure.
305  */
306 static int
307 hash_insert(priv_p priv, struct flow_hash_entry *hsh, struct flow_rec *r,
308 	int plen, uint8_t flags, uint8_t tcp_flags)
309 {
310 	struct flow_entry *fle;
311 	struct sockaddr_in sin, sin_mask;
312 	struct sockaddr_dl rt_gateway;
313 	struct rt_addrinfo info;
314 
315 	mtx_assert(&hsh->mtx, MA_OWNED);
316 
317 	fle = uma_zalloc_arg(priv->zone, priv, M_NOWAIT);
318 	if (fle == NULL) {
319 		priv->nfinfo_alloc_failed++;
320 		return (ENOMEM);
321 	}
322 
323 	/*
324 	 * Now fle is totally ours. It is detached from all lists,
325 	 * we can safely edit it.
326 	 */
327 	fle->f.version = IPVERSION;
328 	bcopy(r, &fle->f.r, sizeof(struct flow_rec));
329 	fle->f.bytes = plen;
330 	fle->f.packets = 1;
331 	fle->f.tcp_flags = tcp_flags;
332 
333 	fle->f.first = fle->f.last = time_uptime;
334 
335 	/*
336 	 * First we do route table lookup on destination address. So we can
337 	 * fill in out_ifx, dst_mask, nexthop, and dst_as in future releases.
338 	 */
339 	if ((flags & NG_NETFLOW_CONF_NODSTLOOKUP) == 0) {
340 		bzero(&sin, sizeof(sin));
341 		sin.sin_len = sizeof(struct sockaddr_in);
342 		sin.sin_family = AF_INET;
343 		sin.sin_addr = fle->f.r.r_dst;
344 
345 		rt_gateway.sdl_len = sizeof(rt_gateway);
346 		sin_mask.sin_len = sizeof(struct sockaddr_in);
347 		bzero(&info, sizeof(info));
348 
349 		info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&rt_gateway;
350 		info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&sin_mask;
351 
352 		if (rib_lookup_info(r->fib, (struct sockaddr *)&sin, NHR_REF, 0,
353 		    &info) == 0) {
354 			fle->f.fle_o_ifx = info.rti_ifp->if_index;
355 
356 			if (info.rti_flags & RTF_GATEWAY &&
357 			    rt_gateway.sdl_family == AF_INET)
358 				fle->f.next_hop =
359 				    ((struct sockaddr_in *)&rt_gateway)->sin_addr;
360 
361 			if (info.rti_addrs & RTA_NETMASK)
362 				fle->f.dst_mask = bitcount32(sin_mask.sin_addr.s_addr);
363 			else if (info.rti_flags & RTF_HOST)
364 				/* Give up. We can't determine mask :( */
365 				fle->f.dst_mask = 32;
366 
367 			rib_free_info(&info);
368 		}
369 	}
370 
371 	/* Do route lookup on source address, to fill in src_mask. */
372 	if ((flags & NG_NETFLOW_CONF_NOSRCLOOKUP) == 0) {
373 		bzero(&sin, sizeof(sin));
374 		sin.sin_len = sizeof(struct sockaddr_in);
375 		sin.sin_family = AF_INET;
376 		sin.sin_addr = fle->f.r.r_src;
377 
378 		sin_mask.sin_len = sizeof(struct sockaddr_in);
379 		bzero(&info, sizeof(info));
380 
381 		info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&sin_mask;
382 
383 		if (rib_lookup_info(r->fib, (struct sockaddr *)&sin, 0, 0,
384 		    &info) == 0) {
385 			if (info.rti_addrs & RTA_NETMASK)
386 				fle->f.src_mask =
387 				    bitcount32(sin_mask.sin_addr.s_addr);
388 			else if (info.rti_flags & RTF_HOST)
389 				/* Give up. We can't determine mask :( */
390 				fle->f.src_mask = 32;
391 		}
392 	}
393 
394 	/* Push new flow at the and of hash. */
395 	TAILQ_INSERT_TAIL(&hsh->head, fle, fle_hash);
396 
397 	return (0);
398 }
399 
400 #ifdef INET6
401 /* XXX: make normal function, instead of.. */
402 #define ipv6_masklen(x)		bitcount32((x).__u6_addr.__u6_addr32[0]) + \
403 				bitcount32((x).__u6_addr.__u6_addr32[1]) + \
404 				bitcount32((x).__u6_addr.__u6_addr32[2]) + \
405 				bitcount32((x).__u6_addr.__u6_addr32[3])
406 static int
407 hash6_insert(priv_p priv, struct flow_hash_entry *hsh6, struct flow6_rec *r,
408 	int plen, uint8_t flags, uint8_t tcp_flags)
409 {
410 	struct flow6_entry *fle6;
411 	struct sockaddr_in6 sin6, sin6_mask;
412 	struct sockaddr_dl rt_gateway;
413 	struct rt_addrinfo info;
414 
415 	mtx_assert(&hsh6->mtx, MA_OWNED);
416 
417 	fle6 = uma_zalloc_arg(priv->zone6, priv, M_NOWAIT);
418 	if (fle6 == NULL) {
419 		priv->nfinfo_alloc_failed++;
420 		return (ENOMEM);
421 	}
422 
423 	/*
424 	 * Now fle is totally ours. It is detached from all lists,
425 	 * we can safely edit it.
426 	 */
427 
428 	fle6->f.version = IP6VERSION;
429 	bcopy(r, &fle6->f.r, sizeof(struct flow6_rec));
430 	fle6->f.bytes = plen;
431 	fle6->f.packets = 1;
432 	fle6->f.tcp_flags = tcp_flags;
433 
434 	fle6->f.first = fle6->f.last = time_uptime;
435 
436 	/*
437 	 * First we do route table lookup on destination address. So we can
438 	 * fill in out_ifx, dst_mask, nexthop, and dst_as in future releases.
439 	 */
440 	if ((flags & NG_NETFLOW_CONF_NODSTLOOKUP) == 0) {
441 		bzero(&sin6, sizeof(struct sockaddr_in6));
442 		sin6.sin6_len = sizeof(struct sockaddr_in6);
443 		sin6.sin6_family = AF_INET6;
444 		sin6.sin6_addr = r->dst.r_dst6;
445 
446 		rt_gateway.sdl_len = sizeof(rt_gateway);
447 		sin6_mask.sin6_len = sizeof(struct sockaddr_in6);
448 		bzero(&info, sizeof(info));
449 
450 		info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&rt_gateway;
451 		info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&sin6_mask;
452 
453 		if (rib_lookup_info(r->fib, (struct sockaddr *)&sin6, NHR_REF,
454 		    0, &info) == 0) {
455 			fle6->f.fle_o_ifx = info.rti_ifp->if_index;
456 
457 			if (info.rti_flags & RTF_GATEWAY &&
458 			    rt_gateway.sdl_family == AF_INET6)
459 				fle6->f.n.next_hop6 =
460 				    ((struct sockaddr_in6 *)&rt_gateway)->sin6_addr;
461 
462 			if (info.rti_addrs & RTA_NETMASK)
463 				fle6->f.dst_mask =
464 				    ipv6_masklen(sin6_mask.sin6_addr);
465 			else
466 				fle6->f.dst_mask = 128;
467 
468 			rib_free_info(&info);
469 		}
470 	}
471 
472 	if ((flags & NG_NETFLOW_CONF_NOSRCLOOKUP) == 0) {
473 		/* Do route lookup on source address, to fill in src_mask. */
474 		bzero(&sin6, sizeof(struct sockaddr_in6));
475 		sin6.sin6_len = sizeof(struct sockaddr_in6);
476 		sin6.sin6_family = AF_INET6;
477 		sin6.sin6_addr = r->src.r_src6;
478 
479 		sin6_mask.sin6_len = sizeof(struct sockaddr_in6);
480 		bzero(&info, sizeof(info));
481 
482 		info.rti_info[RTAX_NETMASK] = (struct sockaddr *)&sin6_mask;
483 
484 		if (rib_lookup_info(r->fib, (struct sockaddr *)&sin6, 0, 0,
485 		    &info) == 0) {
486 			if (info.rti_addrs & RTA_NETMASK)
487 				fle6->f.src_mask =
488 				    ipv6_masklen(sin6_mask.sin6_addr);
489 			else
490 				fle6->f.src_mask = 128;
491 		}
492 	}
493 
494 	/* Push new flow at the and of hash. */
495 	TAILQ_INSERT_TAIL(&hsh6->head, (struct flow_entry *)fle6, fle_hash);
496 
497 	return (0);
498 }
499 #undef ipv6_masklen
500 #endif
501 
502 
503 /*
504  * Non-static functions called from ng_netflow.c
505  */
506 
507 /* Allocate memory and set up flow cache */
508 void
509 ng_netflow_cache_init(priv_p priv)
510 {
511 	struct flow_hash_entry *hsh;
512 	int i;
513 
514 	/* Initialize cache UMA zone. */
515 	priv->zone = uma_zcreate("NetFlow IPv4 cache",
516 	    sizeof(struct flow_entry), NULL, NULL, NULL, NULL,
517 	    UMA_ALIGN_CACHE, 0);
518 	uma_zone_set_max(priv->zone, CACHESIZE);
519 #ifdef INET6
520 	priv->zone6 = uma_zcreate("NetFlow IPv6 cache",
521 	    sizeof(struct flow6_entry), NULL, NULL, NULL, NULL,
522 	    UMA_ALIGN_CACHE, 0);
523 	uma_zone_set_max(priv->zone6, CACHESIZE);
524 #endif
525 
526 	/* Allocate hash. */
527 	priv->hash = malloc(NBUCKETS * sizeof(struct flow_hash_entry),
528 	    M_NETFLOW_HASH, M_WAITOK | M_ZERO);
529 
530 	/* Initialize hash. */
531 	for (i = 0, hsh = priv->hash; i < NBUCKETS; i++, hsh++) {
532 		mtx_init(&hsh->mtx, "hash mutex", NULL, MTX_DEF);
533 		TAILQ_INIT(&hsh->head);
534 	}
535 
536 #ifdef INET6
537 	/* Allocate hash. */
538 	priv->hash6 = malloc(NBUCKETS * sizeof(struct flow_hash_entry),
539 	    M_NETFLOW_HASH, M_WAITOK | M_ZERO);
540 
541 	/* Initialize hash. */
542 	for (i = 0, hsh = priv->hash6; i < NBUCKETS; i++, hsh++) {
543 		mtx_init(&hsh->mtx, "hash mutex", NULL, MTX_DEF);
544 		TAILQ_INIT(&hsh->head);
545 	}
546 #endif
547 
548 	priv->nfinfo_bytes = counter_u64_alloc(M_WAITOK);
549 	priv->nfinfo_packets = counter_u64_alloc(M_WAITOK);
550 	priv->nfinfo_bytes6 = counter_u64_alloc(M_WAITOK);
551 	priv->nfinfo_packets6 = counter_u64_alloc(M_WAITOK);
552 	priv->nfinfo_sbytes = counter_u64_alloc(M_WAITOK);
553 	priv->nfinfo_spackets = counter_u64_alloc(M_WAITOK);
554 	priv->nfinfo_sbytes6 = counter_u64_alloc(M_WAITOK);
555 	priv->nfinfo_spackets6 = counter_u64_alloc(M_WAITOK);
556 	priv->nfinfo_act_exp = counter_u64_alloc(M_WAITOK);
557 	priv->nfinfo_inact_exp = counter_u64_alloc(M_WAITOK);
558 
559 	ng_netflow_v9_cache_init(priv);
560 	CTR0(KTR_NET, "ng_netflow startup()");
561 }
562 
563 /* Initialize new FIB table for v5 and v9 */
564 int
565 ng_netflow_fib_init(priv_p priv, int fib)
566 {
567 	fib_export_p	fe = priv_to_fib(priv, fib);
568 
569 	CTR1(KTR_NET, "ng_netflow(): fib init: %d", fib);
570 
571 	if (fe != NULL)
572 		return (0);
573 
574 	if ((fe = malloc(sizeof(struct fib_export), M_NETGRAPH,
575 	    M_NOWAIT | M_ZERO)) == NULL)
576 		return (ENOMEM);
577 
578 	mtx_init(&fe->export_mtx, "export dgram lock", NULL, MTX_DEF);
579 	mtx_init(&fe->export9_mtx, "export9 dgram lock", NULL, MTX_DEF);
580 	fe->fib = fib;
581 	fe->domain_id = fib;
582 
583 	if (atomic_cmpset_ptr((volatile uintptr_t *)&priv->fib_data[fib],
584 	    (uintptr_t)NULL, (uintptr_t)fe) == 0) {
585 		/* FIB already set up by other ISR */
586 		CTR3(KTR_NET, "ng_netflow(): fib init: %d setup %p but got %p",
587 		    fib, fe, priv_to_fib(priv, fib));
588 		mtx_destroy(&fe->export_mtx);
589 		mtx_destroy(&fe->export9_mtx);
590 		free(fe, M_NETGRAPH);
591 	} else {
592 		/* Increase counter for statistics */
593 		CTR3(KTR_NET, "ng_netflow(): fib %d setup to %p (%p)",
594 		    fib, fe, priv_to_fib(priv, fib));
595 		priv->nfinfo_alloc_fibs++;
596 	}
597 
598 	return (0);
599 }
600 
601 /* Free all flow cache memory. Called from node close method. */
602 void
603 ng_netflow_cache_flush(priv_p priv)
604 {
605 	struct flow_entry	*fle, *fle1;
606 	struct flow_hash_entry	*hsh;
607 	struct netflow_export_item exp;
608 	fib_export_p fe;
609 	int i;
610 
611 	bzero(&exp, sizeof(exp));
612 
613 	/*
614 	 * We are going to free probably billable data.
615 	 * Expire everything before freeing it.
616 	 * No locking is required since callout is already drained.
617 	 */
618 	for (hsh = priv->hash, i = 0; i < NBUCKETS; hsh++, i++)
619 		TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
620 			TAILQ_REMOVE(&hsh->head, fle, fle_hash);
621 			fe = priv_to_fib(priv, fle->f.r.fib);
622 			expire_flow(priv, fe, fle, NG_QUEUE);
623 		}
624 #ifdef INET6
625 	for (hsh = priv->hash6, i = 0; i < NBUCKETS; hsh++, i++)
626 		TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
627 			TAILQ_REMOVE(&hsh->head, fle, fle_hash);
628 			fe = priv_to_fib(priv, fle->f.r.fib);
629 			expire_flow(priv, fe, fle, NG_QUEUE);
630 		}
631 #endif
632 
633 	uma_zdestroy(priv->zone);
634 	/* Destroy hash mutexes. */
635 	for (i = 0, hsh = priv->hash; i < NBUCKETS; i++, hsh++)
636 		mtx_destroy(&hsh->mtx);
637 
638 	/* Free hash memory. */
639 	if (priv->hash != NULL)
640 		free(priv->hash, M_NETFLOW_HASH);
641 #ifdef INET6
642 	uma_zdestroy(priv->zone6);
643 	/* Destroy hash mutexes. */
644 	for (i = 0, hsh = priv->hash6; i < NBUCKETS; i++, hsh++)
645 		mtx_destroy(&hsh->mtx);
646 
647 	/* Free hash memory. */
648 	if (priv->hash6 != NULL)
649 		free(priv->hash6, M_NETFLOW_HASH);
650 #endif
651 
652 	for (i = 0; i < priv->maxfibs; i++) {
653 		if ((fe = priv_to_fib(priv, i)) == NULL)
654 			continue;
655 
656 		if (fe->exp.item != NULL)
657 			export_send(priv, fe, fe->exp.item, NG_QUEUE);
658 
659 		if (fe->exp.item9 != NULL)
660 			export9_send(priv, fe, fe->exp.item9,
661 			    fe->exp.item9_opt, NG_QUEUE);
662 
663 		mtx_destroy(&fe->export_mtx);
664 		mtx_destroy(&fe->export9_mtx);
665 		free(fe, M_NETGRAPH);
666 	}
667 
668 	counter_u64_free(priv->nfinfo_bytes);
669 	counter_u64_free(priv->nfinfo_packets);
670 	counter_u64_free(priv->nfinfo_bytes6);
671 	counter_u64_free(priv->nfinfo_packets6);
672 	counter_u64_free(priv->nfinfo_sbytes);
673 	counter_u64_free(priv->nfinfo_spackets);
674 	counter_u64_free(priv->nfinfo_sbytes6);
675 	counter_u64_free(priv->nfinfo_spackets6);
676 	counter_u64_free(priv->nfinfo_act_exp);
677 	counter_u64_free(priv->nfinfo_inact_exp);
678 
679 	ng_netflow_v9_cache_flush(priv);
680 }
681 
682 /* Insert packet from into flow cache. */
683 int
684 ng_netflow_flow_add(priv_p priv, fib_export_p fe, struct ip *ip,
685     caddr_t upper_ptr, uint8_t upper_proto, uint8_t flags,
686     unsigned int src_if_index)
687 {
688 	struct flow_entry	*fle, *fle1;
689 	struct flow_hash_entry	*hsh;
690 	struct flow_rec		r;
691 	int			hlen, plen;
692 	int			error = 0;
693 	uint16_t		eproto;
694 	uint8_t			tcp_flags = 0;
695 
696 	bzero(&r, sizeof(r));
697 
698 	if (ip->ip_v != IPVERSION)
699 		return (EINVAL);
700 
701 	hlen = ip->ip_hl << 2;
702 	if (hlen < sizeof(struct ip))
703 		return (EINVAL);
704 
705 	eproto = ETHERTYPE_IP;
706 	/* Assume L4 template by default */
707 	r.flow_type = NETFLOW_V9_FLOW_V4_L4;
708 
709 	r.r_src = ip->ip_src;
710 	r.r_dst = ip->ip_dst;
711 	r.fib = fe->fib;
712 
713 	plen = ntohs(ip->ip_len);
714 
715 	r.r_ip_p = ip->ip_p;
716 	r.r_tos = ip->ip_tos;
717 
718 	r.r_i_ifx = src_if_index;
719 
720 	/*
721 	 * XXX NOTE: only first fragment of fragmented TCP, UDP and
722 	 * ICMP packet will be recorded with proper s_port and d_port.
723 	 * Following fragments will be recorded simply as IP packet with
724 	 * ip_proto = ip->ip_p and s_port, d_port set to zero.
725 	 * I know, it looks like bug. But I don't want to re-implement
726 	 * ip packet assebmling here. Anyway, (in)famous trafd works this way -
727 	 * and nobody complains yet :)
728 	 */
729 	if ((ip->ip_off & htons(IP_OFFMASK)) == 0)
730 		switch(r.r_ip_p) {
731 		case IPPROTO_TCP:
732 		    {
733 			struct tcphdr *tcp;
734 
735 			tcp = (struct tcphdr *)((caddr_t )ip + hlen);
736 			r.r_sport = tcp->th_sport;
737 			r.r_dport = tcp->th_dport;
738 			tcp_flags = tcp->th_flags;
739 			break;
740 		    }
741 		case IPPROTO_UDP:
742 			r.r_ports = *(uint32_t *)((caddr_t )ip + hlen);
743 			break;
744 		}
745 
746 	counter_u64_add(priv->nfinfo_packets, 1);
747 	counter_u64_add(priv->nfinfo_bytes, plen);
748 
749 	/* Find hash slot. */
750 	hsh = &priv->hash[ip_hash(&r)];
751 
752 	mtx_lock(&hsh->mtx);
753 
754 	/*
755 	 * Go through hash and find our entry. If we encounter an
756 	 * entry, that should be expired, purge it. We do a reverse
757 	 * search since most active entries are first, and most
758 	 * searches are done on most active entries.
759 	 */
760 	TAILQ_FOREACH_REVERSE_SAFE(fle, &hsh->head, fhead, fle_hash, fle1) {
761 		if (bcmp(&r, &fle->f.r, sizeof(struct flow_rec)) == 0)
762 			break;
763 		if ((INACTIVE(fle) && SMALL(fle)) || AGED(fle)) {
764 			TAILQ_REMOVE(&hsh->head, fle, fle_hash);
765 			expire_flow(priv, priv_to_fib(priv, fle->f.r.fib),
766 			    fle, NG_QUEUE);
767 			counter_u64_add(priv->nfinfo_act_exp, 1);
768 		}
769 	}
770 
771 	if (fle) {			/* An existent entry. */
772 
773 		fle->f.bytes += plen;
774 		fle->f.packets ++;
775 		fle->f.tcp_flags |= tcp_flags;
776 		fle->f.last = time_uptime;
777 
778 		/*
779 		 * We have the following reasons to expire flow in active way:
780 		 * - it hit active timeout
781 		 * - a TCP connection closed
782 		 * - it is going to overflow counter
783 		 */
784 		if (tcp_flags & TH_FIN || tcp_flags & TH_RST || AGED(fle) ||
785 		    (fle->f.bytes >= (CNTR_MAX - IF_MAXMTU)) ) {
786 			TAILQ_REMOVE(&hsh->head, fle, fle_hash);
787 			expire_flow(priv, priv_to_fib(priv, fle->f.r.fib),
788 			    fle, NG_QUEUE);
789 			counter_u64_add(priv->nfinfo_act_exp, 1);
790 		} else {
791 			/*
792 			 * It is the newest, move it to the tail,
793 			 * if it isn't there already. Next search will
794 			 * locate it quicker.
795 			 */
796 			if (fle != TAILQ_LAST(&hsh->head, fhead)) {
797 				TAILQ_REMOVE(&hsh->head, fle, fle_hash);
798 				TAILQ_INSERT_TAIL(&hsh->head, fle, fle_hash);
799 			}
800 		}
801 	} else				/* A new flow entry. */
802 		error = hash_insert(priv, hsh, &r, plen, flags, tcp_flags);
803 
804 	mtx_unlock(&hsh->mtx);
805 
806 	return (error);
807 }
808 
809 #ifdef INET6
810 /* Insert IPv6 packet from into flow cache. */
811 int
812 ng_netflow_flow6_add(priv_p priv, fib_export_p fe, struct ip6_hdr *ip6,
813     caddr_t upper_ptr, uint8_t upper_proto, uint8_t flags,
814     unsigned int src_if_index)
815 {
816 	struct flow_entry	*fle = NULL, *fle1;
817 	struct flow6_entry	*fle6;
818 	struct flow_hash_entry	*hsh;
819 	struct flow6_rec	r;
820 	int			plen;
821 	int			error = 0;
822 	uint8_t			tcp_flags = 0;
823 
824 	/* check version */
825 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION)
826 		return (EINVAL);
827 
828 	bzero(&r, sizeof(r));
829 
830 	r.src.r_src6 = ip6->ip6_src;
831 	r.dst.r_dst6 = ip6->ip6_dst;
832 	r.fib = fe->fib;
833 
834 	/* Assume L4 template by default */
835 	r.flow_type = NETFLOW_V9_FLOW_V6_L4;
836 
837 	plen = ntohs(ip6->ip6_plen) + sizeof(struct ip6_hdr);
838 
839 #if 0
840 	/* XXX: set DSCP/CoS value */
841 	r.r_tos = ip->ip_tos;
842 #endif
843 	if ((flags & NG_NETFLOW_IS_FRAG) == 0) {
844 		switch(upper_proto) {
845 		case IPPROTO_TCP:
846 		    {
847 			struct tcphdr *tcp;
848 
849 			tcp = (struct tcphdr *)upper_ptr;
850 			r.r_ports = *(uint32_t *)upper_ptr;
851 			tcp_flags = tcp->th_flags;
852 			break;
853 		    }
854  		case IPPROTO_UDP:
855 		case IPPROTO_SCTP:
856 			r.r_ports = *(uint32_t *)upper_ptr;
857 			break;
858 		}
859 	}
860 
861 	r.r_ip_p = upper_proto;
862 	r.r_i_ifx = src_if_index;
863 
864 	counter_u64_add(priv->nfinfo_packets6, 1);
865 	counter_u64_add(priv->nfinfo_bytes6, plen);
866 
867 	/* Find hash slot. */
868 	hsh = &priv->hash6[ip6_hash(&r)];
869 
870 	mtx_lock(&hsh->mtx);
871 
872 	/*
873 	 * Go through hash and find our entry. If we encounter an
874 	 * entry, that should be expired, purge it. We do a reverse
875 	 * search since most active entries are first, and most
876 	 * searches are done on most active entries.
877 	 */
878 	TAILQ_FOREACH_REVERSE_SAFE(fle, &hsh->head, fhead, fle_hash, fle1) {
879 		if (fle->f.version != IP6VERSION)
880 			continue;
881 		fle6 = (struct flow6_entry *)fle;
882 		if (bcmp(&r, &fle6->f.r, sizeof(struct flow6_rec)) == 0)
883 			break;
884 		if ((INACTIVE(fle6) && SMALL(fle6)) || AGED(fle6)) {
885 			TAILQ_REMOVE(&hsh->head, fle, fle_hash);
886 			expire_flow(priv, priv_to_fib(priv, fle->f.r.fib), fle,
887 			    NG_QUEUE);
888 			counter_u64_add(priv->nfinfo_act_exp, 1);
889 		}
890 	}
891 
892 	if (fle != NULL) {			/* An existent entry. */
893 		fle6 = (struct flow6_entry *)fle;
894 
895 		fle6->f.bytes += plen;
896 		fle6->f.packets ++;
897 		fle6->f.tcp_flags |= tcp_flags;
898 		fle6->f.last = time_uptime;
899 
900 		/*
901 		 * We have the following reasons to expire flow in active way:
902 		 * - it hit active timeout
903 		 * - a TCP connection closed
904 		 * - it is going to overflow counter
905 		 */
906 		if (tcp_flags & TH_FIN || tcp_flags & TH_RST || AGED(fle6) ||
907 		    (fle6->f.bytes >= (CNTR_MAX - IF_MAXMTU)) ) {
908 			TAILQ_REMOVE(&hsh->head, fle, fle_hash);
909 			expire_flow(priv, priv_to_fib(priv, fle->f.r.fib), fle,
910 			    NG_QUEUE);
911 			counter_u64_add(priv->nfinfo_act_exp, 1);
912 		} else {
913 			/*
914 			 * It is the newest, move it to the tail,
915 			 * if it isn't there already. Next search will
916 			 * locate it quicker.
917 			 */
918 			if (fle != TAILQ_LAST(&hsh->head, fhead)) {
919 				TAILQ_REMOVE(&hsh->head, fle, fle_hash);
920 				TAILQ_INSERT_TAIL(&hsh->head, fle, fle_hash);
921 			}
922 		}
923 	} else				/* A new flow entry. */
924 		error = hash6_insert(priv, hsh, &r, plen, flags, tcp_flags);
925 
926 	mtx_unlock(&hsh->mtx);
927 
928 	return (error);
929 }
930 #endif
931 
932 /*
933  * Return records from cache to userland.
934  *
935  * TODO: matching particular IP should be done in kernel, here.
936  */
937 int
938 ng_netflow_flow_show(priv_p priv, struct ngnf_show_header *req,
939 struct ngnf_show_header *resp)
940 {
941 	struct flow_hash_entry	*hsh;
942 	struct flow_entry	*fle;
943 	struct flow_entry_data	*data = (struct flow_entry_data *)(resp + 1);
944 #ifdef INET6
945 	struct flow6_entry_data	*data6 = (struct flow6_entry_data *)(resp + 1);
946 #endif
947 	int	i, max;
948 
949 	i = req->hash_id;
950 	if (i > NBUCKETS-1)
951 		return (EINVAL);
952 
953 #ifdef INET6
954 	if (req->version == 6) {
955 		resp->version = 6;
956 		hsh = priv->hash6 + i;
957 		max = NREC6_AT_ONCE;
958 	} else
959 #endif
960 	if (req->version == 4) {
961 		resp->version = 4;
962 		hsh = priv->hash + i;
963 		max = NREC_AT_ONCE;
964 	} else
965 		return (EINVAL);
966 
967 	/*
968 	 * We will transfer not more than NREC_AT_ONCE. More data
969 	 * will come in next message.
970 	 * We send current hash index and current record number in list
971 	 * to userland, and userland should return it back to us.
972 	 * Then, we will restart with new entry.
973 	 *
974 	 * The resulting cache snapshot can be inaccurate if flow expiration
975 	 * is taking place on hash item between userland data requests for
976 	 * this hash item id.
977 	 */
978 	resp->nentries = 0;
979 	for (; i < NBUCKETS; hsh++, i++) {
980 		int list_id;
981 
982 		if (mtx_trylock(&hsh->mtx) == 0) {
983 			/*
984 			 * Requested hash index is not available,
985 			 * relay decision to skip or re-request data
986 			 * to userland.
987 			 */
988 			resp->hash_id = i;
989 			resp->list_id = 0;
990 			return (0);
991 		}
992 
993 		list_id = 0;
994 		TAILQ_FOREACH(fle, &hsh->head, fle_hash) {
995 			if (hsh->mtx.mtx_lock & MTX_CONTESTED) {
996 				resp->hash_id = i;
997 				resp->list_id = list_id;
998 				mtx_unlock(&hsh->mtx);
999 				return (0);
1000 			}
1001 
1002 			list_id++;
1003 			/* Search for particular record in list. */
1004 			if (req->list_id > 0) {
1005 				if (list_id < req->list_id)
1006 					continue;
1007 
1008 				/* Requested list position found. */
1009 				req->list_id = 0;
1010 			}
1011 #ifdef INET6
1012 			if (req->version == 6) {
1013 				struct flow6_entry *fle6;
1014 
1015 				fle6 = (struct flow6_entry *)fle;
1016 				bcopy(&fle6->f, data6 + resp->nentries,
1017 				    sizeof(fle6->f));
1018 			} else
1019 #endif
1020 				bcopy(&fle->f, data + resp->nentries,
1021 				    sizeof(fle->f));
1022 			resp->nentries++;
1023 			if (resp->nentries == max) {
1024 				resp->hash_id = i;
1025 				/*
1026 				 * If it was the last item in list
1027 				 * we simply skip to next hash_id.
1028 				 */
1029 				resp->list_id = list_id + 1;
1030 				mtx_unlock(&hsh->mtx);
1031 				return (0);
1032 			}
1033 		}
1034 		mtx_unlock(&hsh->mtx);
1035 	}
1036 
1037 	resp->hash_id = resp->list_id = 0;
1038 
1039 	return (0);
1040 }
1041 
1042 /* We have full datagram in privdata. Send it to export hook. */
1043 static int
1044 export_send(priv_p priv, fib_export_p fe, item_p item, int flags)
1045 {
1046 	struct mbuf *m = NGI_M(item);
1047 	struct netflow_v5_export_dgram *dgram = mtod(m,
1048 					struct netflow_v5_export_dgram *);
1049 	struct netflow_v5_header *header = &dgram->header;
1050 	struct timespec ts;
1051 	int error = 0;
1052 
1053 	/* Fill mbuf header. */
1054 	m->m_len = m->m_pkthdr.len = sizeof(struct netflow_v5_record) *
1055 	   header->count + sizeof(struct netflow_v5_header);
1056 
1057 	/* Fill export header. */
1058 	header->sys_uptime = htonl(MILLIUPTIME(time_uptime));
1059 	getnanotime(&ts);
1060 	header->unix_secs  = htonl(ts.tv_sec);
1061 	header->unix_nsecs = htonl(ts.tv_nsec);
1062 	header->engine_type = 0;
1063 	header->engine_id = fe->domain_id;
1064 	header->pad = 0;
1065 	header->flow_seq = htonl(atomic_fetchadd_32(&fe->flow_seq,
1066 	    header->count));
1067 	header->count = htons(header->count);
1068 
1069 	if (priv->export != NULL)
1070 		NG_FWD_ITEM_HOOK_FLAGS(error, item, priv->export, flags);
1071 	else
1072 		NG_FREE_ITEM(item);
1073 
1074 	return (error);
1075 }
1076 
1077 
1078 /* Add export record to dgram. */
1079 static int
1080 export_add(item_p item, struct flow_entry *fle)
1081 {
1082 	struct netflow_v5_export_dgram *dgram = mtod(NGI_M(item),
1083 					struct netflow_v5_export_dgram *);
1084 	struct netflow_v5_header *header = &dgram->header;
1085 	struct netflow_v5_record *rec;
1086 
1087 	rec = &dgram->r[header->count];
1088 	header->count ++;
1089 
1090 	KASSERT(header->count <= NETFLOW_V5_MAX_RECORDS,
1091 	    ("ng_netflow: export too big"));
1092 
1093 	/* Fill in export record. */
1094 	rec->src_addr = fle->f.r.r_src.s_addr;
1095 	rec->dst_addr = fle->f.r.r_dst.s_addr;
1096 	rec->next_hop = fle->f.next_hop.s_addr;
1097 	rec->i_ifx    = htons(fle->f.fle_i_ifx);
1098 	rec->o_ifx    = htons(fle->f.fle_o_ifx);
1099 	rec->packets  = htonl(fle->f.packets);
1100 	rec->octets   = htonl(fle->f.bytes);
1101 	rec->first    = htonl(MILLIUPTIME(fle->f.first));
1102 	rec->last     = htonl(MILLIUPTIME(fle->f.last));
1103 	rec->s_port   = fle->f.r.r_sport;
1104 	rec->d_port   = fle->f.r.r_dport;
1105 	rec->flags    = fle->f.tcp_flags;
1106 	rec->prot     = fle->f.r.r_ip_p;
1107 	rec->tos      = fle->f.r.r_tos;
1108 	rec->dst_mask = fle->f.dst_mask;
1109 	rec->src_mask = fle->f.src_mask;
1110 	rec->pad1     = 0;
1111 	rec->pad2     = 0;
1112 
1113 	/* Not supported fields. */
1114 	rec->src_as = rec->dst_as = 0;
1115 
1116 	if (header->count == NETFLOW_V5_MAX_RECORDS)
1117 		return (1); /* end of datagram */
1118 	else
1119 		return (0);
1120 }
1121 
1122 /* Periodic flow expiry run. */
1123 void
1124 ng_netflow_expire(void *arg)
1125 {
1126 	struct flow_entry	*fle, *fle1;
1127 	struct flow_hash_entry	*hsh;
1128 	priv_p			priv = (priv_p )arg;
1129 	int			used, i;
1130 
1131 	/*
1132 	 * Going through all the cache.
1133 	 */
1134 	used = uma_zone_get_cur(priv->zone);
1135 	for (hsh = priv->hash, i = 0; i < NBUCKETS; hsh++, i++) {
1136 		/*
1137 		 * Skip entries, that are already being worked on.
1138 		 */
1139 		if (mtx_trylock(&hsh->mtx) == 0)
1140 			continue;
1141 
1142 		TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
1143 			/*
1144 			 * Interrupt thread wants this entry!
1145 			 * Quick! Quick! Bail out!
1146 			 */
1147 			if (hsh->mtx.mtx_lock & MTX_CONTESTED)
1148 				break;
1149 
1150 			/*
1151 			 * Don't expire aggressively while hash collision
1152 			 * ratio is predicted small.
1153 			 */
1154 			if (used <= (NBUCKETS*2) && !INACTIVE(fle))
1155 				break;
1156 
1157 			if ((INACTIVE(fle) && (SMALL(fle) ||
1158 			    (used > (NBUCKETS*2)))) || AGED(fle)) {
1159 				TAILQ_REMOVE(&hsh->head, fle, fle_hash);
1160 				expire_flow(priv, priv_to_fib(priv,
1161 				    fle->f.r.fib), fle, NG_NOFLAGS);
1162 				used--;
1163 				counter_u64_add(priv->nfinfo_inact_exp, 1);
1164 			}
1165 		}
1166 		mtx_unlock(&hsh->mtx);
1167 	}
1168 
1169 #ifdef INET6
1170 	used = uma_zone_get_cur(priv->zone6);
1171 	for (hsh = priv->hash6, i = 0; i < NBUCKETS; hsh++, i++) {
1172 		struct flow6_entry	*fle6;
1173 
1174 		/*
1175 		 * Skip entries, that are already being worked on.
1176 		 */
1177 		if (mtx_trylock(&hsh->mtx) == 0)
1178 			continue;
1179 
1180 		TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
1181 			fle6 = (struct flow6_entry *)fle;
1182 			/*
1183 			 * Interrupt thread wants this entry!
1184 			 * Quick! Quick! Bail out!
1185 			 */
1186 			if (hsh->mtx.mtx_lock & MTX_CONTESTED)
1187 				break;
1188 
1189 			/*
1190 			 * Don't expire aggressively while hash collision
1191 			 * ratio is predicted small.
1192 			 */
1193 			if (used <= (NBUCKETS*2) && !INACTIVE(fle6))
1194 				break;
1195 
1196 			if ((INACTIVE(fle6) && (SMALL(fle6) ||
1197 			    (used > (NBUCKETS*2)))) || AGED(fle6)) {
1198 				TAILQ_REMOVE(&hsh->head, fle, fle_hash);
1199 				expire_flow(priv, priv_to_fib(priv,
1200 				    fle->f.r.fib), fle, NG_NOFLAGS);
1201 				used--;
1202 				counter_u64_add(priv->nfinfo_inact_exp, 1);
1203 			}
1204 		}
1205 		mtx_unlock(&hsh->mtx);
1206 	}
1207 #endif
1208 
1209 	/* Schedule next expire. */
1210 	callout_reset(&priv->exp_callout, (1*hz), &ng_netflow_expire,
1211 	    (void *)priv);
1212 }
1213