xref: /dragonfly/sys/netgraph7/netflow/netflow.c (revision a68e0df0)
1 /*-
2  * Copyright (c) 2004-2005 Gleb Smirnoff <glebius@FreeBSD.org>
3  * Copyright (c) 2001-2003 Roman V. Palagin <romanp@unshadow.net>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $SourceForge: netflow.c,v 1.41 2004/09/05 11:41:10 glebius Exp $
28  * $FreeBSD: src/sys/netgraph/netflow/netflow.c,v 1.29 2008/05/09 23:02:57 julian Exp $
29  * $DragonFly: src/sys/netgraph7/netflow/netflow.c,v 1.2 2008/06/26 23:05:40 dillon Exp $
30  */
31 
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/limits.h>
35 #include <sys/mbuf.h>
36 #include <sys/syslog.h>
37 #include <sys/systm.h>
38 #include <sys/socket.h>
39 
40 #include <machine/atomic.h>
41 
42 #include <net/if.h>
43 #include <net/route.h>
44 #include <netinet/in.h>
45 #include <netinet/in_systm.h>
46 #include <netinet/ip.h>
47 #include <netinet/tcp.h>
48 #include <netinet/udp.h>
49 
50 #include "ng_message.h"
51 #include "netgraph.h"
52 
53 #include "netflow/netflow.h"
54 #include "netflow/ng_netflow.h"
55 
56 #define	NBUCKETS	(65536)		/* must be power of 2 */
57 
58 /* This hash is for TCP or UDP packets. */
59 #define FULL_HASH(addr1, addr2, port1, port2)	\
60 	(((addr1 ^ (addr1 >> 16) ^ 		\
61 	htons(addr2 ^ (addr2 >> 16))) ^ 	\
62 	port1 ^ htons(port2)) &			\
63 	(NBUCKETS - 1))
64 
65 /* This hash is for all other IP packets. */
66 #define ADDR_HASH(addr1, addr2)			\
67 	((addr1 ^ (addr1 >> 16) ^ 		\
68 	htons(addr2 ^ (addr2 >> 16))) &		\
69 	(NBUCKETS - 1))
70 
71 /* Macros to shorten logical constructions */
72 /* XXX: priv must exist in namespace */
73 #define	INACTIVE(fle)	(time_uptime - fle->f.last > priv->info.nfinfo_inact_t)
74 #define	AGED(fle)	(time_uptime - fle->f.first > priv->info.nfinfo_act_t)
75 #define	ISFREE(fle)	(fle->f.packets == 0)
76 
77 /*
78  * 4 is a magical number: statistically number of 4-packet flows is
79  * bigger than 5,6,7...-packet flows by an order of magnitude. Most UDP/ICMP
80  * scans are 1 packet (~ 90% of flow cache). TCP scans are 2-packet in case
81  * of reachable host and 4-packet otherwise.
82  */
83 #define	SMALL(fle)	(fle->f.packets <= 4)
84 
85 /*
86  * Cisco uses milliseconds for uptime. Bad idea, since it overflows
87  * every 48+ days. But we will do same to keep compatibility. This macro
88  * does overflowable multiplication to 1000.
89  */
90 #define	MILLIUPTIME(t)	(((t) << 9) +	/* 512 */	\
91 			 ((t) << 8) +	/* 256 */	\
92 			 ((t) << 7) +	/* 128 */	\
93 			 ((t) << 6) +	/* 64  */	\
94 			 ((t) << 5) +	/* 32  */	\
95 			 ((t) << 3))	/* 8   */
96 
97 MALLOC_DECLARE(M_NETFLOW_HASH);
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, item_p, int flags);
102 
103 /* Generate hash for a given flow record. */
104 static __inline uint32_t
105 ip_hash(struct flow_rec *r)
106 {
107 	switch (r->r_ip_p) {
108 	case IPPROTO_TCP:
109 	case IPPROTO_UDP:
110 		return FULL_HASH(r->r_src.s_addr, r->r_dst.s_addr,
111 		    r->r_sport, r->r_dport);
112 	default:
113 		return ADDR_HASH(r->r_src.s_addr, r->r_dst.s_addr);
114 	}
115 }
116 
117 /* This is callback from uma(9), called on alloc. */
118 static int
119 uma_ctor_flow(void *mem, int size, void *arg, int how)
120 {
121 	priv_p priv = (priv_p )arg;
122 
123 	if (atomic_load_acq_32(&priv->info.nfinfo_used) >= CACHESIZE)
124 		return (ENOMEM);
125 
126 	atomic_add_32(&priv->info.nfinfo_used, 1);
127 
128 	return (0);
129 }
130 
131 /* This is callback from uma(9), called on free. */
132 static void
133 uma_dtor_flow(void *mem, int size, void *arg)
134 {
135 	priv_p priv = (priv_p )arg;
136 
137 	atomic_subtract_32(&priv->info.nfinfo_used, 1);
138 }
139 
140 /*
141  * Detach export datagram from priv, if there is any.
142  * If there is no, allocate a new one.
143  */
144 static item_p
145 get_export_dgram(priv_p priv)
146 {
147 	item_p	item = NULL;
148 
149 	mtx_lock(&priv->export_mtx);
150 	if (priv->export_item != NULL) {
151 		item = priv->export_item;
152 		priv->export_item = NULL;
153 	}
154 	mtx_unlock(&priv->export_mtx);
155 
156 	if (item == NULL) {
157 		struct netflow_v5_export_dgram *dgram;
158 		struct mbuf *m;
159 
160 		m = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
161 		if (m == NULL)
162 			return (NULL);
163 		item = ng_package_data(m, NG_NOFLAGS);
164 		if (item == NULL)
165 			return (NULL);
166 		dgram = mtod(m, struct netflow_v5_export_dgram *);
167 		dgram->header.count = 0;
168 		dgram->header.version = htons(NETFLOW_V5);
169 
170 	}
171 
172 	return (item);
173 }
174 
175 /*
176  * Re-attach incomplete datagram back to priv.
177  * If there is already another one, then send incomplete. */
178 static void
179 return_export_dgram(priv_p priv, item_p item, int flags)
180 {
181 	/*
182 	 * It may happen on SMP, that some thread has already
183 	 * put its item there, in this case we bail out and
184 	 * send what we have to collector.
185 	 */
186 	mtx_lock(&priv->export_mtx);
187 	if (priv->export_item == NULL) {
188 		priv->export_item = item;
189 		mtx_unlock(&priv->export_mtx);
190 	} else {
191 		mtx_unlock(&priv->export_mtx);
192 		export_send(priv, item, flags);
193 	}
194 }
195 
196 /*
197  * The flow is over. Call export_add() and free it. If datagram is
198  * full, then call export_send().
199  */
200 static __inline void
201 expire_flow(priv_p priv, item_p *item, struct flow_entry *fle, int flags)
202 {
203 	if (*item == NULL)
204 		*item = get_export_dgram(priv);
205 	if (*item == NULL) {
206 		atomic_add_32(&priv->info.nfinfo_export_failed, 1);
207 		uma_zfree_arg(priv->zone, fle, priv);
208 		return;
209 	}
210 	if (export_add(*item, fle) > 0) {
211 		export_send(priv, *item, flags);
212 		*item = NULL;
213 	}
214 	uma_zfree_arg(priv->zone, fle, priv);
215 }
216 
217 /* Get a snapshot of node statistics */
218 void
219 ng_netflow_copyinfo(priv_p priv, struct ng_netflow_info *i)
220 {
221 	/* XXX: atomic */
222 	memcpy((void *)i, (void *)&priv->info, sizeof(priv->info));
223 }
224 
225 /*
226  * Insert a record into defined slot.
227  *
228  * First we get for us a free flow entry, then fill in all
229  * possible fields in it.
230  *
231  * TODO: consider dropping hash mutex while filling in datagram,
232  * as this was done in previous version. Need to test & profile
233  * to be sure.
234  */
235 static __inline int
236 hash_insert(priv_p priv, struct flow_hash_entry  *hsh, struct flow_rec *r,
237 	int plen, uint8_t tcp_flags)
238 {
239 	struct flow_entry *fle;
240 	struct sockaddr_in sin;
241 	struct rtentry *rt;
242 
243 	mtx_assert(&hsh->mtx, MA_OWNED);
244 
245 	fle = uma_zalloc_arg(priv->zone, priv, M_WAITOK | M_NULLOK);
246 	if (fle == NULL) {
247 		atomic_add_32(&priv->info.nfinfo_alloc_failed, 1);
248 		return (ENOMEM);
249 	}
250 
251 	/*
252 	 * Now fle is totally ours. It is detached from all lists,
253 	 * we can safely edit it.
254 	 */
255 
256 	bcopy(r, &fle->f.r, sizeof(struct flow_rec));
257 	fle->f.bytes = plen;
258 	fle->f.packets = 1;
259 	fle->f.tcp_flags = tcp_flags;
260 
261 	fle->f.first = fle->f.last = time_uptime;
262 
263 	/*
264 	 * First we do route table lookup on destination address. So we can
265 	 * fill in out_ifx, dst_mask, nexthop, and dst_as in future releases.
266 	 */
267 	bzero(&sin, sizeof(sin));
268 	sin.sin_len = sizeof(struct sockaddr_in);
269 	sin.sin_family = AF_INET;
270 	sin.sin_addr = fle->f.r.r_dst;
271 	/* XXX MRT 0 as a default.. need the m here to get fib */
272 	rt = rtalloc1_fib((struct sockaddr *)&sin, 0, RTF_CLONING, 0);
273 	if (rt != NULL) {
274 		fle->f.fle_o_ifx = rt->rt_ifp->if_index;
275 
276 		if (rt->rt_flags & RTF_GATEWAY &&
277 		    rt->rt_gateway->sa_family == AF_INET)
278 			fle->f.next_hop =
279 			    ((struct sockaddr_in *)(rt->rt_gateway))->sin_addr;
280 
281 		if (rt_mask(rt))
282 			fle->f.dst_mask = bitcount32(((struct sockaddr_in *)
283 			    rt_mask(rt))->sin_addr.s_addr);
284 		else if (rt->rt_flags & RTF_HOST)
285 			/* Give up. We can't determine mask :( */
286 			fle->f.dst_mask = 32;
287 
288 		RTFREE_LOCKED(rt);
289 	}
290 
291 	/* Do route lookup on source address, to fill in src_mask. */
292 	bzero(&sin, sizeof(sin));
293 	sin.sin_len = sizeof(struct sockaddr_in);
294 	sin.sin_family = AF_INET;
295 	sin.sin_addr = fle->f.r.r_src;
296 	/* XXX MRT 0 as a default  revisit.  need the mbuf for fib*/
297 	rt = rtalloc1_fib((struct sockaddr *)&sin, 0, RTF_CLONING, 0);
298 	if (rt != NULL) {
299 		if (rt_mask(rt))
300 			fle->f.src_mask = bitcount32(((struct sockaddr_in *)
301 			    rt_mask(rt))->sin_addr.s_addr);
302 		else if (rt->rt_flags & RTF_HOST)
303 			/* Give up. We can't determine mask :( */
304 			fle->f.src_mask = 32;
305 
306 		RTFREE_LOCKED(rt);
307 	}
308 
309 	/* Push new flow at the and of hash. */
310 	TAILQ_INSERT_TAIL(&hsh->head, fle, fle_hash);
311 
312 	return (0);
313 }
314 
315 
316 /*
317  * Non-static functions called from ng_netflow.c
318  */
319 
320 /* Allocate memory and set up flow cache */
321 int
322 ng_netflow_cache_init(priv_p priv)
323 {
324 	struct flow_hash_entry	*hsh;
325 	int i;
326 
327 	/* Initialize cache UMA zone. */
328 	priv->zone = uma_zcreate("NetFlow cache", sizeof(struct flow_entry),
329 	    uma_ctor_flow, uma_dtor_flow, NULL, NULL, UMA_ALIGN_CACHE, 0);
330 	uma_zone_set_max(priv->zone, CACHESIZE);
331 
332 	/* Allocate hash. */
333 	MALLOC(priv->hash, struct flow_hash_entry *,
334 	    NBUCKETS * sizeof(struct flow_hash_entry),
335 	    M_NETFLOW_HASH, M_WAITOK | M_ZERO);
336 
337 	if (priv->hash == NULL) {
338 		uma_zdestroy(priv->zone);
339 		return (ENOMEM);
340 	}
341 
342 	/* Initialize hash. */
343 	for (i = 0, hsh = priv->hash; i < NBUCKETS; i++, hsh++) {
344 		mtx_init(&hsh->mtx, "hash mutex", NULL, MTX_DEF);
345 		TAILQ_INIT(&hsh->head);
346 	}
347 
348 	mtx_init(&priv->export_mtx, "export dgram lock", NULL, MTX_DEF);
349 
350 	return (0);
351 }
352 
353 /* Free all flow cache memory. Called from node close method. */
354 void
355 ng_netflow_cache_flush(priv_p priv)
356 {
357 	struct flow_entry	*fle, *fle1;
358 	struct flow_hash_entry	*hsh;
359 	item_p			item = NULL;
360 	int i;
361 
362 	/*
363 	 * We are going to free probably billable data.
364 	 * Expire everything before freeing it.
365 	 * No locking is required since callout is already drained.
366 	 */
367 	for (hsh = priv->hash, i = 0; i < NBUCKETS; hsh++, i++)
368 		TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
369 			TAILQ_REMOVE(&hsh->head, fle, fle_hash);
370 			expire_flow(priv, &item, fle, NG_QUEUE);
371 		}
372 
373 	if (item != NULL)
374 		export_send(priv, item, NG_QUEUE);
375 
376 	uma_zdestroy(priv->zone);
377 
378 	/* Destroy hash mutexes. */
379 	for (i = 0, hsh = priv->hash; i < NBUCKETS; i++, hsh++)
380 		mtx_destroy(&hsh->mtx);
381 
382 	/* Free hash memory. */
383 	if (priv->hash)
384 		FREE(priv->hash, M_NETFLOW_HASH);
385 
386 	mtx_destroy(&priv->export_mtx);
387 }
388 
389 /* Insert packet from into flow cache. */
390 int
391 ng_netflow_flow_add(priv_p priv, struct ip *ip, iface_p iface,
392 	struct ifnet *ifp)
393 {
394 	register struct flow_entry	*fle, *fle1;
395 	struct flow_hash_entry		*hsh;
396 	struct flow_rec		r;
397 	item_p			item = NULL;
398 	int			hlen, plen;
399 	int			error = 0;
400 	uint8_t			tcp_flags = 0;
401 
402 	/* Try to fill flow_rec r */
403 	bzero(&r, sizeof(r));
404 	/* check version */
405 	if (ip->ip_v != IPVERSION)
406 		return (EINVAL);
407 
408 	/* verify min header length */
409 	hlen = ip->ip_hl << 2;
410 
411 	if (hlen < sizeof(struct ip))
412 		return (EINVAL);
413 
414 	r.r_src = ip->ip_src;
415 	r.r_dst = ip->ip_dst;
416 
417 	/* save packet length */
418 	plen = ntohs(ip->ip_len);
419 
420 	r.r_ip_p = ip->ip_p;
421 	r.r_tos = ip->ip_tos;
422 
423 	/* Configured in_ifx overrides mbuf's */
424 	if (iface->info.ifinfo_index == 0) {
425 		if (ifp != NULL)
426 			r.r_i_ifx = ifp->if_index;
427 	} else
428 		r.r_i_ifx = iface->info.ifinfo_index;
429 
430 	/*
431 	 * XXX NOTE: only first fragment of fragmented TCP, UDP and
432 	 * ICMP packet will be recorded with proper s_port and d_port.
433 	 * Following fragments will be recorded simply as IP packet with
434 	 * ip_proto = ip->ip_p and s_port, d_port set to zero.
435 	 * I know, it looks like bug. But I don't want to re-implement
436 	 * ip packet assebmling here. Anyway, (in)famous trafd works this way -
437 	 * and nobody complains yet :)
438 	 */
439 	if ((ip->ip_off & htons(IP_OFFMASK)) == 0)
440 		switch(r.r_ip_p) {
441 		case IPPROTO_TCP:
442 		{
443 			register struct tcphdr *tcp;
444 
445 			tcp = (struct tcphdr *)((caddr_t )ip + hlen);
446 			r.r_sport = tcp->th_sport;
447 			r.r_dport = tcp->th_dport;
448 			tcp_flags = tcp->th_flags;
449 			break;
450 		}
451 			case IPPROTO_UDP:
452 			r.r_ports = *(uint32_t *)((caddr_t )ip + hlen);
453 			break;
454 		}
455 
456 	/* Update node statistics. XXX: race... */
457 	priv->info.nfinfo_packets ++;
458 	priv->info.nfinfo_bytes += plen;
459 
460 	/* Find hash slot. */
461 	hsh = &priv->hash[ip_hash(&r)];
462 
463 	mtx_lock(&hsh->mtx);
464 
465 	/*
466 	 * Go through hash and find our entry. If we encounter an
467 	 * entry, that should be expired, purge it. We do a reverse
468 	 * search since most active entries are first, and most
469 	 * searches are done on most active entries.
470 	 */
471 	TAILQ_FOREACH_REVERSE_SAFE(fle, &hsh->head, fhead, fle_hash, fle1) {
472 		if (bcmp(&r, &fle->f.r, sizeof(struct flow_rec)) == 0)
473 			break;
474 		if ((INACTIVE(fle) && SMALL(fle)) || AGED(fle)) {
475 			TAILQ_REMOVE(&hsh->head, fle, fle_hash);
476 			expire_flow(priv, &item, fle, NG_QUEUE);
477 			atomic_add_32(&priv->info.nfinfo_act_exp, 1);
478 		}
479 	}
480 
481 	if (fle) {			/* An existent entry. */
482 
483 		fle->f.bytes += plen;
484 		fle->f.packets ++;
485 		fle->f.tcp_flags |= tcp_flags;
486 		fle->f.last = time_uptime;
487 
488 		/*
489 		 * We have the following reasons to expire flow in active way:
490 		 * - it hit active timeout
491 		 * - a TCP connection closed
492 		 * - it is going to overflow counter
493 		 */
494 		if (tcp_flags & TH_FIN || tcp_flags & TH_RST || AGED(fle) ||
495 		    (fle->f.bytes >= (UINT_MAX - IF_MAXMTU)) ) {
496 			TAILQ_REMOVE(&hsh->head, fle, fle_hash);
497 			expire_flow(priv, &item, fle, NG_QUEUE);
498 			atomic_add_32(&priv->info.nfinfo_act_exp, 1);
499 		} else {
500 			/*
501 			 * It is the newest, move it to the tail,
502 			 * if it isn't there already. Next search will
503 			 * locate it quicker.
504 			 */
505 			if (fle != TAILQ_LAST(&hsh->head, fhead)) {
506 				TAILQ_REMOVE(&hsh->head, fle, fle_hash);
507 				TAILQ_INSERT_TAIL(&hsh->head, fle, fle_hash);
508 			}
509 		}
510 	} else				/* A new flow entry. */
511 		error = hash_insert(priv, hsh, &r, plen, tcp_flags);
512 
513 	mtx_unlock(&hsh->mtx);
514 
515 	if (item != NULL)
516 		return_export_dgram(priv, item, NG_QUEUE);
517 
518 	return (error);
519 }
520 
521 /*
522  * Return records from cache to userland.
523  *
524  * TODO: matching particular IP should be done in kernel, here.
525  */
526 int
527 ng_netflow_flow_show(priv_p priv, uint32_t last, struct ng_mesg *resp)
528 {
529 	struct flow_hash_entry *hsh;
530 	struct flow_entry *fle;
531 	struct ngnf_flows *data;
532 	int i;
533 
534 	data = (struct ngnf_flows *)resp->data;
535 	data->last = 0;
536 	data->nentries = 0;
537 
538 	/* Check if this is a first run */
539 	if (last == 0) {
540 		hsh = priv->hash;
541 		i = 0;
542 	} else {
543 		if (last > NBUCKETS-1)
544 			return (EINVAL);
545 		hsh = priv->hash + last;
546 		i = last;
547 	}
548 
549 	/*
550 	 * We will transfer not more than NREC_AT_ONCE. More data
551 	 * will come in next message.
552 	 * We send current hash index to userland, and userland should
553 	 * return it back to us. Then, we will restart with new entry.
554 	 *
555 	 * The resulting cache snapshot is inaccurate for the
556 	 * following reasons:
557 	 *  - we skip locked hash entries
558 	 *  - we bail out, if someone wants our entry
559 	 *  - we skip rest of entry, when hit NREC_AT_ONCE
560 	 */
561 	for (; i < NBUCKETS; hsh++, i++) {
562 		if (mtx_trylock(&hsh->mtx) == 0)
563 			continue;
564 
565 		TAILQ_FOREACH(fle, &hsh->head, fle_hash) {
566 			if (mtx_contested(&hsh->mtx)
567 				break;
568 
569 			bcopy(&fle->f, &(data->entries[data->nentries]),
570 			    sizeof(fle->f));
571 			data->nentries++;
572 			if (data->nentries == NREC_AT_ONCE) {
573 				mtx_unlock(&hsh->mtx);
574 				if (++i < NBUCKETS)
575 					data->last = i;
576 				return (0);
577 			}
578 		}
579 		mtx_unlock(&hsh->mtx);
580 	}
581 
582 	return (0);
583 }
584 
585 /* We have full datagram in privdata. Send it to export hook. */
586 static int
587 export_send(priv_p priv, item_p item, int flags)
588 {
589 	struct mbuf *m = NGI_M(item);
590 	struct netflow_v5_export_dgram *dgram = mtod(m,
591 					struct netflow_v5_export_dgram *);
592 	struct netflow_v5_header *header = &dgram->header;
593 	struct timespec ts;
594 	int error = 0;
595 
596 	/* Fill mbuf header. */
597 	m->m_len = m->m_pkthdr.len = sizeof(struct netflow_v5_record) *
598 	   header->count + sizeof(struct netflow_v5_header);
599 
600 	/* Fill export header. */
601 	header->sys_uptime = htonl(MILLIUPTIME(time_uptime));
602 	getnanotime(&ts);
603 	header->unix_secs  = htonl(ts.tv_sec);
604 	header->unix_nsecs = htonl(ts.tv_nsec);
605 	header->engine_type = 0;
606 	header->engine_id = 0;
607 	header->pad = 0;
608 	header->flow_seq = htonl(atomic_fetchadd_32(&priv->flow_seq,
609 	    header->count));
610 	header->count = htons(header->count);
611 
612 	if (priv->export != NULL)
613 		NG_FWD_ITEM_HOOK_FLAGS(error, item, priv->export, flags);
614 	else
615 		NG_FREE_ITEM(item);
616 
617 	return (error);
618 }
619 
620 
621 /* Add export record to dgram. */
622 static int
623 export_add(item_p item, struct flow_entry *fle)
624 {
625 	struct netflow_v5_export_dgram *dgram = mtod(NGI_M(item),
626 					struct netflow_v5_export_dgram *);
627 	struct netflow_v5_header *header = &dgram->header;
628 	struct netflow_v5_record *rec;
629 
630 	rec = &dgram->r[header->count];
631 	header->count ++;
632 
633 	KASSERT(header->count <= NETFLOW_V5_MAX_RECORDS,
634 	    ("ng_netflow: export too big"));
635 
636 	/* Fill in export record. */
637 	rec->src_addr = fle->f.r.r_src.s_addr;
638 	rec->dst_addr = fle->f.r.r_dst.s_addr;
639 	rec->next_hop = fle->f.next_hop.s_addr;
640 	rec->i_ifx    = htons(fle->f.fle_i_ifx);
641 	rec->o_ifx    = htons(fle->f.fle_o_ifx);
642 	rec->packets  = htonl(fle->f.packets);
643 	rec->octets   = htonl(fle->f.bytes);
644 	rec->first    = htonl(MILLIUPTIME(fle->f.first));
645 	rec->last     = htonl(MILLIUPTIME(fle->f.last));
646 	rec->s_port   = fle->f.r.r_sport;
647 	rec->d_port   = fle->f.r.r_dport;
648 	rec->flags    = fle->f.tcp_flags;
649 	rec->prot     = fle->f.r.r_ip_p;
650 	rec->tos      = fle->f.r.r_tos;
651 	rec->dst_mask = fle->f.dst_mask;
652 	rec->src_mask = fle->f.src_mask;
653 
654 	/* Not supported fields. */
655 	rec->src_as = rec->dst_as = 0;
656 
657 	if (header->count == NETFLOW_V5_MAX_RECORDS)
658 		return (1); /* end of datagram */
659 	else
660 		return (0);
661 }
662 
663 /* Periodic flow expiry run. */
664 void
665 ng_netflow_expire(void *arg)
666 {
667 	struct flow_entry	*fle, *fle1;
668 	struct flow_hash_entry	*hsh;
669 	priv_p			priv = (priv_p )arg;
670 	item_p			item = NULL;
671 	uint32_t		used;
672 	int			i;
673 
674 	/*
675 	 * Going through all the cache.
676 	 */
677 	for (hsh = priv->hash, i = 0; i < NBUCKETS; hsh++, i++) {
678 		/*
679 		 * Skip entries, that are already being worked on.
680 		 */
681 		if (mtx_trylock(&hsh->mtx) == 0)
682 			continue;
683 
684 		used = atomic_load_acq_32(&priv->info.nfinfo_used);
685 		TAILQ_FOREACH_SAFE(fle, &hsh->head, fle_hash, fle1) {
686 			/*
687 			 * Interrupt thread wants this entry!
688 			 * Quick! Quick! Bail out!
689 			 */
690 			if (mtx_contested(&hsh->mtx))
691 				break;
692 
693 			/*
694 			 * Don't expire aggressively while hash collision
695 			 * ratio is predicted small.
696 			 */
697 			if (used <= (NBUCKETS*2) && !INACTIVE(fle))
698 				break;
699 
700 			if ((INACTIVE(fle) && (SMALL(fle) ||
701 			    (used > (NBUCKETS*2)))) || AGED(fle)) {
702 				TAILQ_REMOVE(&hsh->head, fle, fle_hash);
703 				expire_flow(priv, &item, fle, NG_NOFLAGS);
704 				used--;
705 				atomic_add_32(&priv->info.nfinfo_inact_exp, 1);
706 			}
707 		}
708 		mtx_unlock(&hsh->mtx);
709 	}
710 
711 	if (item != NULL)
712 		return_export_dgram(priv, item, NG_NOFLAGS);
713 
714 	/* Schedule next expire. */
715 	callout_reset(&priv->exp_callout, (1*hz), &ng_netflow_expire,
716 	    (void *)priv);
717 }
718