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