xref: /netbsd-src/sys/netinet/ip_flow.c (revision 404fbe5fb94ca1e054339640cabb2801ce52dd30)
1 /*	$NetBSD: ip_flow.c,v 1.56 2008/04/28 20:24:09 martin Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by the 3am Software Foundry ("3am").  It was developed by Matt Thomas.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __KERNEL_RCSID(0, "$NetBSD: ip_flow.c,v 1.56 2008/04/28 20:24:09 martin Exp $");
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/malloc.h>
38 #include <sys/mbuf.h>
39 #include <sys/domain.h>
40 #include <sys/protosw.h>
41 #include <sys/socket.h>
42 #include <sys/socketvar.h>
43 #include <sys/errno.h>
44 #include <sys/time.h>
45 #include <sys/kernel.h>
46 #include <sys/pool.h>
47 #include <sys/sysctl.h>
48 
49 #include <net/if.h>
50 #include <net/if_dl.h>
51 #include <net/route.h>
52 #include <net/pfil.h>
53 
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h>
56 #include <netinet/ip.h>
57 #include <netinet/in_pcb.h>
58 #include <netinet/in_var.h>
59 #include <netinet/ip_var.h>
60 #include <netinet/ip_private.h>
61 
62 /*
63  * Similar code is very well commented in netinet6/ip6_flow.c
64  */
65 
66 struct ipflow {
67 	LIST_ENTRY(ipflow) ipf_list;	/* next in active list */
68 	LIST_ENTRY(ipflow) ipf_hash;	/* next ipflow in bucket */
69 	struct in_addr ipf_dst;		/* destination address */
70 	struct in_addr ipf_src;		/* source address */
71 	uint8_t ipf_tos;		/* type-of-service */
72 	struct route ipf_ro;		/* associated route entry */
73 	u_long ipf_uses;		/* number of uses in this period */
74 	u_long ipf_last_uses;		/* number of uses in last period */
75 	u_long ipf_dropped;		/* ENOBUFS retured by if_output */
76 	u_long ipf_errors;		/* other errors returned by if_output */
77 	u_int ipf_timer;		/* lifetime timer */
78 	time_t ipf_start;		/* creation time */
79 };
80 
81 #define	IPFLOW_HASHBITS		6	/* should not be a multiple of 8 */
82 
83 POOL_INIT(ipflow_pool, sizeof(struct ipflow), 0, 0, 0, "ipflowpl", NULL,
84     IPL_NET);
85 
86 LIST_HEAD(ipflowhead, ipflow);
87 
88 #define	IPFLOW_TIMER		(5 * PR_SLOWHZ)
89 #define	IPFLOW_DEFAULT_HASHSIZE	(1 << IPFLOW_HASHBITS)
90 
91 static struct ipflowhead *ipflowtable = NULL;
92 static struct ipflowhead ipflowlist;
93 static int ipflow_inuse;
94 
95 #define	IPFLOW_INSERT(bucket, ipf) \
96 do { \
97 	LIST_INSERT_HEAD((bucket), (ipf), ipf_hash); \
98 	LIST_INSERT_HEAD(&ipflowlist, (ipf), ipf_list); \
99 } while (/*CONSTCOND*/ 0)
100 
101 #define	IPFLOW_REMOVE(ipf) \
102 do { \
103 	LIST_REMOVE((ipf), ipf_hash); \
104 	LIST_REMOVE((ipf), ipf_list); \
105 } while (/*CONSTCOND*/ 0)
106 
107 #ifndef IPFLOW_MAX
108 #define	IPFLOW_MAX		256
109 #endif
110 int ip_maxflows = IPFLOW_MAX;
111 int ip_hashsize = IPFLOW_DEFAULT_HASHSIZE;
112 
113 static size_t
114 ipflow_hash(const struct ip *ip)
115 {
116 	size_t hash = ip->ip_tos;
117 	size_t idx;
118 
119 	for (idx = 0; idx < 32; idx += IPFLOW_HASHBITS) {
120 		hash += (ip->ip_dst.s_addr >> (32 - idx)) +
121 		    (ip->ip_src.s_addr >> idx);
122 	}
123 
124 	return hash & (ip_hashsize-1);
125 }
126 
127 static struct ipflow *
128 ipflow_lookup(const struct ip *ip)
129 {
130 	size_t hash;
131 	struct ipflow *ipf;
132 
133 	hash = ipflow_hash(ip);
134 
135 	LIST_FOREACH(ipf, &ipflowtable[hash], ipf_hash) {
136 		if (ip->ip_dst.s_addr == ipf->ipf_dst.s_addr
137 		    && ip->ip_src.s_addr == ipf->ipf_src.s_addr
138 		    && ip->ip_tos == ipf->ipf_tos)
139 			break;
140 	}
141 	return ipf;
142 }
143 
144 int
145 ipflow_init(int table_size)
146 {
147 	struct ipflowhead *new_table;
148 	size_t i;
149 
150 	new_table = (struct ipflowhead *)malloc(sizeof(struct ipflowhead) *
151 	    table_size, M_RTABLE, M_NOWAIT);
152 
153 	if (new_table == NULL)
154 		return 1;
155 
156 	if (ipflowtable != NULL)
157 		free(ipflowtable, M_RTABLE);
158 
159 	ipflowtable = new_table;
160 	ip_hashsize = table_size;
161 
162 	LIST_INIT(&ipflowlist);
163 	for (i = 0; i < ip_hashsize; i++)
164 		LIST_INIT(&ipflowtable[i]);
165 
166 	return 0;
167 }
168 
169 int
170 ipflow_fastforward(struct mbuf *m)
171 {
172 	struct ip *ip;
173 	struct ip ip_store;
174 	struct ipflow *ipf;
175 	struct rtentry *rt;
176 	const struct sockaddr *dst;
177 	int error;
178 	int iplen;
179 
180 	/*
181 	 * Are we forwarding packets?  Big enough for an IP packet?
182 	 */
183 	if (!ipforwarding || ipflow_inuse == 0 || m->m_len < sizeof(struct ip))
184 		return 0;
185 
186 	/*
187 	 * Was packet received as a link-level multicast or broadcast?
188 	 * If so, don't try to fast forward..
189 	 */
190 	if ((m->m_flags & (M_BCAST|M_MCAST)) != 0)
191 		return 0;
192 
193 	/*
194 	 * IP header with no option and valid version and length
195 	 */
196 	if (IP_HDR_ALIGNED_P(mtod(m, const void *)))
197 		ip = mtod(m, struct ip *);
198 	else {
199 		memcpy(&ip_store, mtod(m, const void *), sizeof(ip_store));
200 		ip = &ip_store;
201 	}
202 	iplen = ntohs(ip->ip_len);
203 	if (ip->ip_v != IPVERSION || ip->ip_hl != (sizeof(struct ip) >> 2) ||
204 	    iplen < sizeof(struct ip) || iplen > m->m_pkthdr.len)
205 		return 0;
206 	/*
207 	 * Find a flow.
208 	 */
209 	if ((ipf = ipflow_lookup(ip)) == NULL)
210 		return 0;
211 
212 	/*
213 	 * Verify the IP header checksum.
214 	 */
215 	switch (m->m_pkthdr.csum_flags &
216 		((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_IPv4) |
217 		 M_CSUM_IPv4_BAD)) {
218 	case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
219 		return (0);
220 
221 	case M_CSUM_IPv4:
222 		/* Checksum was okay. */
223 		break;
224 
225 	default:
226 		/* Must compute it ourselves. */
227 		if (in_cksum(m, sizeof(struct ip)) != 0)
228 			return (0);
229 		break;
230 	}
231 
232 	/*
233 	 * Route and interface still up?
234 	 */
235 	if ((rt = rtcache_validate(&ipf->ipf_ro)) == NULL ||
236 	    (rt->rt_ifp->if_flags & IFF_UP) == 0)
237 		return 0;
238 
239 	/*
240 	 * Packet size OK?  TTL?
241 	 */
242 	if (m->m_pkthdr.len > rt->rt_ifp->if_mtu || ip->ip_ttl <= IPTTLDEC)
243 		return 0;
244 
245 	/*
246 	 * Clear any in-bound checksum flags for this packet.
247 	 */
248 	m->m_pkthdr.csum_flags = 0;
249 
250 	/*
251 	 * Everything checks out and so we can forward this packet.
252 	 * Modify the TTL and incrementally change the checksum.
253 	 *
254 	 * This method of adding the checksum works on either endian CPU.
255 	 * If htons() is inlined, all the arithmetic is folded; otherwise
256 	 * the htons()s are combined by CSE due to the const attribute.
257 	 *
258 	 * Don't bother using HW checksumming here -- the incremental
259 	 * update is pretty fast.
260 	 */
261 	ip->ip_ttl -= IPTTLDEC;
262 	if (ip->ip_sum >= (u_int16_t) ~htons(IPTTLDEC << 8))
263 		ip->ip_sum -= ~htons(IPTTLDEC << 8);
264 	else
265 		ip->ip_sum += htons(IPTTLDEC << 8);
266 
267 	/*
268 	 * Done modifying the header; copy it back, if necessary.
269 	 *
270 	 * XXX Use m_copyback_cow(9) here? --dyoung
271 	 */
272 	if (IP_HDR_ALIGNED_P(mtod(m, void *)) == 0)
273 		memcpy(mtod(m, void *), &ip_store, sizeof(ip_store));
274 
275 	/*
276 	 * Trim the packet in case it's too long..
277 	 */
278 	if (m->m_pkthdr.len > iplen) {
279 		if (m->m_len == m->m_pkthdr.len) {
280 			m->m_len = iplen;
281 			m->m_pkthdr.len = iplen;
282 		} else
283 			m_adj(m, iplen - m->m_pkthdr.len);
284 	}
285 
286 	/*
287 	 * Send the packet on it's way.  All we can get back is ENOBUFS
288 	 */
289 	ipf->ipf_uses++;
290 	PRT_SLOW_ARM(ipf->ipf_timer, IPFLOW_TIMER);
291 
292 	if (rt->rt_flags & RTF_GATEWAY)
293 		dst = rt->rt_gateway;
294 	else
295 		dst = rtcache_getdst(&ipf->ipf_ro);
296 
297 	if ((error = (*rt->rt_ifp->if_output)(rt->rt_ifp, m, dst, rt)) != 0) {
298 		if (error == ENOBUFS)
299 			ipf->ipf_dropped++;
300 		else
301 			ipf->ipf_errors++;
302 	}
303 	return 1;
304 }
305 
306 static void
307 ipflow_addstats(struct ipflow *ipf)
308 {
309 	struct rtentry *rt;
310 	uint64_t *ips;
311 
312 	if ((rt = rtcache_validate(&ipf->ipf_ro)) != NULL)
313 		rt->rt_use += ipf->ipf_uses;
314 
315 	ips = IP_STAT_GETREF();
316 	ips[IP_STAT_CANTFORWARD] += ipf->ipf_errors + ipf->ipf_dropped;
317 	ips[IP_STAT_TOTAL] += ipf->ipf_uses;
318 	ips[IP_STAT_FORWARD] += ipf->ipf_uses;
319 	ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
320 	IP_STAT_PUTREF();
321 }
322 
323 static void
324 ipflow_free(struct ipflow *ipf)
325 {
326 	int s;
327 	/*
328 	 * Remove the flow from the hash table (at elevated IPL).
329 	 * Once it's off the list, we can deal with it at normal
330 	 * network IPL.
331 	 */
332 	s = splnet();
333 	IPFLOW_REMOVE(ipf);
334 	splx(s);
335 	ipflow_addstats(ipf);
336 	rtcache_free(&ipf->ipf_ro);
337 	ipflow_inuse--;
338 	s = splnet();
339 	pool_put(&ipflow_pool, ipf);
340 	splx(s);
341 }
342 
343 static struct ipflow *
344 ipflow_reap(bool just_one)
345 {
346 	while (just_one || ipflow_inuse > ip_maxflows) {
347 		struct ipflow *ipf, *maybe_ipf = NULL;
348 		int s;
349 
350 		ipf = LIST_FIRST(&ipflowlist);
351 		while (ipf != NULL) {
352 			/*
353 			 * If this no longer points to a valid route
354 			 * reclaim it.
355 			 */
356 			if (rtcache_validate(&ipf->ipf_ro) == NULL)
357 				goto done;
358 			/*
359 			 * choose the one that's been least recently
360 			 * used or has had the least uses in the
361 			 * last 1.5 intervals.
362 			 */
363 			if (maybe_ipf == NULL ||
364 			    ipf->ipf_timer < maybe_ipf->ipf_timer ||
365 			    (ipf->ipf_timer == maybe_ipf->ipf_timer &&
366 			     ipf->ipf_last_uses + ipf->ipf_uses <
367 			         maybe_ipf->ipf_last_uses +
368 			         maybe_ipf->ipf_uses))
369 				maybe_ipf = ipf;
370 			ipf = LIST_NEXT(ipf, ipf_list);
371 		}
372 		ipf = maybe_ipf;
373 	    done:
374 		/*
375 		 * Remove the entry from the flow table.
376 		 */
377 		s = splnet();
378 		IPFLOW_REMOVE(ipf);
379 		splx(s);
380 		ipflow_addstats(ipf);
381 		rtcache_free(&ipf->ipf_ro);
382 		if (just_one)
383 			return ipf;
384 		pool_put(&ipflow_pool, ipf);
385 		ipflow_inuse--;
386 	}
387 	return NULL;
388 }
389 
390 void
391 ipflow_prune(void)
392 {
393 
394 	(void) ipflow_reap(false);
395 }
396 
397 void
398 ipflow_slowtimo(void)
399 {
400 	struct rtentry *rt;
401 	struct ipflow *ipf, *next_ipf;
402 	uint64_t *ips;
403 
404 	mutex_enter(softnet_lock);
405 	KERNEL_LOCK(1, NULL);
406 	for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
407 		next_ipf = LIST_NEXT(ipf, ipf_list);
408 		if (PRT_SLOW_ISEXPIRED(ipf->ipf_timer) ||
409 		    (rt = rtcache_validate(&ipf->ipf_ro)) == NULL) {
410 			ipflow_free(ipf);
411 		} else {
412 			ipf->ipf_last_uses = ipf->ipf_uses;
413 			rt->rt_use += ipf->ipf_uses;
414 			ips = IP_STAT_GETREF();
415 			ips[IP_STAT_TOTAL] += ipf->ipf_uses;
416 			ips[IP_STAT_FORWARD] += ipf->ipf_uses;
417 			ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
418 			IP_STAT_PUTREF();
419 			ipf->ipf_uses = 0;
420 		}
421 	}
422 	KERNEL_UNLOCK_ONE(NULL);
423 	mutex_exit(softnet_lock);
424 }
425 
426 void
427 ipflow_create(const struct route *ro, struct mbuf *m)
428 {
429 	const struct ip *const ip = mtod(m, const struct ip *);
430 	struct ipflow *ipf;
431 	size_t hash;
432 	int s;
433 
434 	/*
435 	 * Don't create cache entries for ICMP messages.
436 	 */
437 	if (ip_maxflows == 0 || ip->ip_p == IPPROTO_ICMP)
438 		return;
439 	/*
440 	 * See if an existing flow struct exists.  If so remove it from it's
441 	 * list and free the old route.  If not, try to malloc a new one
442 	 * (if we aren't at our limit).
443 	 */
444 	ipf = ipflow_lookup(ip);
445 	if (ipf == NULL) {
446 		if (ipflow_inuse >= ip_maxflows) {
447 			ipf = ipflow_reap(true);
448 		} else {
449 			s = splnet();
450 			ipf = pool_get(&ipflow_pool, PR_NOWAIT);
451 			splx(s);
452 			if (ipf == NULL)
453 				return;
454 			ipflow_inuse++;
455 		}
456 		memset(ipf, 0, sizeof(*ipf));
457 	} else {
458 		s = splnet();
459 		IPFLOW_REMOVE(ipf);
460 		splx(s);
461 		ipflow_addstats(ipf);
462 		rtcache_free(&ipf->ipf_ro);
463 		ipf->ipf_uses = ipf->ipf_last_uses = 0;
464 		ipf->ipf_errors = ipf->ipf_dropped = 0;
465 	}
466 
467 	/*
468 	 * Fill in the updated information.
469 	 */
470 	rtcache_copy(&ipf->ipf_ro, ro);
471 	ipf->ipf_dst = ip->ip_dst;
472 	ipf->ipf_src = ip->ip_src;
473 	ipf->ipf_tos = ip->ip_tos;
474 	PRT_SLOW_ARM(ipf->ipf_timer, IPFLOW_TIMER);
475 	ipf->ipf_start = time_uptime;
476 	/*
477 	 * Insert into the approriate bucket of the flow table.
478 	 */
479 	hash = ipflow_hash(ip);
480 	s = splnet();
481 	IPFLOW_INSERT(&ipflowtable[hash], ipf);
482 	splx(s);
483 }
484 
485 int
486 ipflow_invalidate_all(int new_size)
487 {
488 	struct ipflow *ipf, *next_ipf;
489 	int s, error;
490 
491 	error = 0;
492 	s = splnet();
493 	for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
494 		next_ipf = LIST_NEXT(ipf, ipf_list);
495 		ipflow_free(ipf);
496 	}
497 
498 	if (new_size)
499 		error = ipflow_init(new_size);
500 	splx(s);
501 
502 	return error;
503 }
504