xref: /netbsd-src/sys/netinet/ip_flow.c (revision b7b7574d3bf8eeb51a1fa3977b59142ec6434a55)
1 /*	$NetBSD: ip_flow.c,v 1.64 2014/05/22 22:01:12 rmind 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.64 2014/05/22 22:01:12 rmind 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 #define	IPFLOW_HASHBITS		6	/* should not be a multiple of 8 */
67 
68 static struct pool ipflow_pool;
69 
70 LIST_HEAD(ipflowhead, ipflow);
71 
72 #define	IPFLOW_TIMER		(5 * PR_SLOWHZ)
73 #define	IPFLOW_DEFAULT_HASHSIZE	(1 << IPFLOW_HASHBITS)
74 
75 static struct ipflowhead *ipflowtable = NULL;
76 static struct ipflowhead ipflowlist;
77 static int ipflow_inuse;
78 
79 #define	IPFLOW_INSERT(bucket, ipf) \
80 do { \
81 	LIST_INSERT_HEAD((bucket), (ipf), ipf_hash); \
82 	LIST_INSERT_HEAD(&ipflowlist, (ipf), ipf_list); \
83 } while (/*CONSTCOND*/ 0)
84 
85 #define	IPFLOW_REMOVE(ipf) \
86 do { \
87 	LIST_REMOVE((ipf), ipf_hash); \
88 	LIST_REMOVE((ipf), ipf_list); \
89 } while (/*CONSTCOND*/ 0)
90 
91 #ifndef IPFLOW_MAX
92 #define	IPFLOW_MAX		256
93 #endif
94 static int ip_maxflows = IPFLOW_MAX;
95 static int ip_hashsize = IPFLOW_DEFAULT_HASHSIZE;
96 
97 static void ipflow_sysctl_init(struct sysctllog **);
98 
99 static size_t
100 ipflow_hash(const struct ip *ip)
101 {
102 	size_t hash = ip->ip_tos;
103 	size_t idx;
104 
105 	for (idx = 0; idx < 32; idx += IPFLOW_HASHBITS) {
106 		hash += (ip->ip_dst.s_addr >> (32 - idx)) +
107 		    (ip->ip_src.s_addr >> idx);
108 	}
109 
110 	return hash & (ip_hashsize-1);
111 }
112 
113 static struct ipflow *
114 ipflow_lookup(const struct ip *ip)
115 {
116 	size_t hash;
117 	struct ipflow *ipf;
118 
119 	hash = ipflow_hash(ip);
120 
121 	LIST_FOREACH(ipf, &ipflowtable[hash], ipf_hash) {
122 		if (ip->ip_dst.s_addr == ipf->ipf_dst.s_addr
123 		    && ip->ip_src.s_addr == ipf->ipf_src.s_addr
124 		    && ip->ip_tos == ipf->ipf_tos)
125 			break;
126 	}
127 	return ipf;
128 }
129 
130 void
131 ipflow_poolinit(void)
132 {
133 
134 	pool_init(&ipflow_pool, sizeof(struct ipflow), 0, 0, 0, "ipflowpl",
135 	    NULL, IPL_NET);
136 }
137 
138 static int
139 ipflow_reinit(int table_size)
140 {
141 	struct ipflowhead *new_table;
142 	size_t i;
143 
144 	new_table = (struct ipflowhead *)malloc(sizeof(struct ipflowhead) *
145 	    table_size, M_RTABLE, M_NOWAIT);
146 
147 	if (new_table == NULL)
148 		return 1;
149 
150 	if (ipflowtable != NULL)
151 		free(ipflowtable, M_RTABLE);
152 
153 	ipflowtable = new_table;
154 	ip_hashsize = table_size;
155 
156 	LIST_INIT(&ipflowlist);
157 	for (i = 0; i < ip_hashsize; i++)
158 		LIST_INIT(&ipflowtable[i]);
159 
160 	return 0;
161 }
162 
163 void
164 ipflow_init(void)
165 {
166 	(void)ipflow_reinit(ip_hashsize);
167 	ipflow_sysctl_init(NULL);
168 }
169 
170 int
171 ipflow_fastforward(struct mbuf *m)
172 {
173 	struct ip *ip;
174 	struct ip ip_store;
175 	struct ipflow *ipf;
176 	struct rtentry *rt;
177 	const struct sockaddr *dst;
178 	int error;
179 	int iplen;
180 
181 	/*
182 	 * Are we forwarding packets?  Big enough for an IP packet?
183 	 */
184 	if (!ipforwarding || ipflow_inuse == 0 || m->m_len < sizeof(struct ip))
185 		return 0;
186 
187 	/*
188 	 * Was packet received as a link-level multicast or broadcast?
189 	 * If so, don't try to fast forward..
190 	 */
191 	if ((m->m_flags & (M_BCAST|M_MCAST)) != 0)
192 		return 0;
193 
194 	/*
195 	 * IP header with no option and valid version and length
196 	 */
197 	if (IP_HDR_ALIGNED_P(mtod(m, const void *)))
198 		ip = mtod(m, struct ip *);
199 	else {
200 		memcpy(&ip_store, mtod(m, const void *), sizeof(ip_store));
201 		ip = &ip_store;
202 	}
203 	iplen = ntohs(ip->ip_len);
204 	if (ip->ip_v != IPVERSION || ip->ip_hl != (sizeof(struct ip) >> 2) ||
205 	    iplen < sizeof(struct ip) || iplen > m->m_pkthdr.len)
206 		return 0;
207 	/*
208 	 * Find a flow.
209 	 */
210 	if ((ipf = ipflow_lookup(ip)) == NULL)
211 		return 0;
212 
213 	/*
214 	 * Verify the IP header checksum.
215 	 */
216 	switch (m->m_pkthdr.csum_flags &
217 		((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_IPv4) |
218 		 M_CSUM_IPv4_BAD)) {
219 	case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
220 		return (0);
221 
222 	case M_CSUM_IPv4:
223 		/* Checksum was okay. */
224 		break;
225 
226 	default:
227 		/* Must compute it ourselves. */
228 		if (in_cksum(m, sizeof(struct ip)) != 0)
229 			return (0);
230 		break;
231 	}
232 
233 	/*
234 	 * Route and interface still up?
235 	 */
236 	if ((rt = rtcache_validate(&ipf->ipf_ro)) == NULL ||
237 	    (rt->rt_ifp->if_flags & IFF_UP) == 0)
238 		return 0;
239 
240 	/*
241 	 * Packet size OK?  TTL?
242 	 */
243 	if (m->m_pkthdr.len > rt->rt_ifp->if_mtu || ip->ip_ttl <= IPTTLDEC)
244 		return 0;
245 
246 	/*
247 	 * Clear any in-bound checksum flags for this packet.
248 	 */
249 	m->m_pkthdr.csum_flags = 0;
250 
251 	/*
252 	 * Everything checks out and so we can forward this packet.
253 	 * Modify the TTL and incrementally change the checksum.
254 	 *
255 	 * This method of adding the checksum works on either endian CPU.
256 	 * If htons() is inlined, all the arithmetic is folded; otherwise
257 	 * the htons()s are combined by CSE due to the const attribute.
258 	 *
259 	 * Don't bother using HW checksumming here -- the incremental
260 	 * update is pretty fast.
261 	 */
262 	ip->ip_ttl -= IPTTLDEC;
263 	if (ip->ip_sum >= (u_int16_t) ~htons(IPTTLDEC << 8))
264 		ip->ip_sum -= ~htons(IPTTLDEC << 8);
265 	else
266 		ip->ip_sum += htons(IPTTLDEC << 8);
267 
268 	/*
269 	 * Done modifying the header; copy it back, if necessary.
270 	 *
271 	 * XXX Use m_copyback_cow(9) here? --dyoung
272 	 */
273 	if (IP_HDR_ALIGNED_P(mtod(m, void *)) == 0)
274 		memcpy(mtod(m, void *), &ip_store, sizeof(ip_store));
275 
276 	/*
277 	 * Trim the packet in case it's too long..
278 	 */
279 	if (m->m_pkthdr.len > iplen) {
280 		if (m->m_len == m->m_pkthdr.len) {
281 			m->m_len = iplen;
282 			m->m_pkthdr.len = iplen;
283 		} else
284 			m_adj(m, iplen - m->m_pkthdr.len);
285 	}
286 
287 	/*
288 	 * Send the packet on it's way.  All we can get back is ENOBUFS
289 	 */
290 	ipf->ipf_uses++;
291 	PRT_SLOW_ARM(ipf->ipf_timer, IPFLOW_TIMER);
292 
293 	if (rt->rt_flags & RTF_GATEWAY)
294 		dst = rt->rt_gateway;
295 	else
296 		dst = rtcache_getdst(&ipf->ipf_ro);
297 
298 	KERNEL_LOCK(1, NULL);
299 	if ((error = (*rt->rt_ifp->if_output)(rt->rt_ifp, m, dst, rt)) != 0) {
300 		if (error == ENOBUFS)
301 			ipf->ipf_dropped++;
302 		else
303 			ipf->ipf_errors++;
304 	}
305 	KERNEL_UNLOCK_ONE(NULL);
306 	return 1;
307 }
308 
309 static void
310 ipflow_addstats(struct ipflow *ipf)
311 {
312 	struct rtentry *rt;
313 	uint64_t *ips;
314 
315 	if ((rt = rtcache_validate(&ipf->ipf_ro)) != NULL)
316 		rt->rt_use += ipf->ipf_uses;
317 
318 	ips = IP_STAT_GETREF();
319 	ips[IP_STAT_CANTFORWARD] += ipf->ipf_errors + ipf->ipf_dropped;
320 	ips[IP_STAT_TOTAL] += ipf->ipf_uses;
321 	ips[IP_STAT_FORWARD] += ipf->ipf_uses;
322 	ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
323 	IP_STAT_PUTREF();
324 }
325 
326 static void
327 ipflow_free(struct ipflow *ipf)
328 {
329 	int s;
330 	/*
331 	 * Remove the flow from the hash table (at elevated IPL).
332 	 * Once it's off the list, we can deal with it at normal
333 	 * network IPL.
334 	 */
335 	s = splnet();
336 	IPFLOW_REMOVE(ipf);
337 	splx(s);
338 	ipflow_addstats(ipf);
339 	rtcache_free(&ipf->ipf_ro);
340 	ipflow_inuse--;
341 	s = splnet();
342 	pool_put(&ipflow_pool, ipf);
343 	splx(s);
344 }
345 
346 struct ipflow *
347 ipflow_reap(bool just_one)
348 {
349 	while (just_one || ipflow_inuse > ip_maxflows) {
350 		struct ipflow *ipf, *maybe_ipf = NULL;
351 		int s;
352 
353 		ipf = LIST_FIRST(&ipflowlist);
354 		while (ipf != NULL) {
355 			/*
356 			 * If this no longer points to a valid route
357 			 * reclaim it.
358 			 */
359 			if (rtcache_validate(&ipf->ipf_ro) == NULL)
360 				goto done;
361 			/*
362 			 * choose the one that's been least recently
363 			 * used or has had the least uses in the
364 			 * last 1.5 intervals.
365 			 */
366 			if (maybe_ipf == NULL ||
367 			    ipf->ipf_timer < maybe_ipf->ipf_timer ||
368 			    (ipf->ipf_timer == maybe_ipf->ipf_timer &&
369 			     ipf->ipf_last_uses + ipf->ipf_uses <
370 			         maybe_ipf->ipf_last_uses +
371 			         maybe_ipf->ipf_uses))
372 				maybe_ipf = ipf;
373 			ipf = LIST_NEXT(ipf, ipf_list);
374 		}
375 		ipf = maybe_ipf;
376 	    done:
377 		/*
378 		 * Remove the entry from the flow table.
379 		 */
380 		s = splnet();
381 		IPFLOW_REMOVE(ipf);
382 		splx(s);
383 		ipflow_addstats(ipf);
384 		rtcache_free(&ipf->ipf_ro);
385 		if (just_one)
386 			return ipf;
387 		pool_put(&ipflow_pool, ipf);
388 		ipflow_inuse--;
389 	}
390 	return NULL;
391 }
392 
393 void
394 ipflow_slowtimo(void)
395 {
396 	struct rtentry *rt;
397 	struct ipflow *ipf, *next_ipf;
398 	uint64_t *ips;
399 
400 	mutex_enter(softnet_lock);
401 	KERNEL_LOCK(1, NULL);
402 	for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
403 		next_ipf = LIST_NEXT(ipf, ipf_list);
404 		if (PRT_SLOW_ISEXPIRED(ipf->ipf_timer) ||
405 		    (rt = rtcache_validate(&ipf->ipf_ro)) == NULL) {
406 			ipflow_free(ipf);
407 		} else {
408 			ipf->ipf_last_uses = ipf->ipf_uses;
409 			rt->rt_use += ipf->ipf_uses;
410 			ips = IP_STAT_GETREF();
411 			ips[IP_STAT_TOTAL] += ipf->ipf_uses;
412 			ips[IP_STAT_FORWARD] += ipf->ipf_uses;
413 			ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
414 			IP_STAT_PUTREF();
415 			ipf->ipf_uses = 0;
416 		}
417 	}
418 	KERNEL_UNLOCK_ONE(NULL);
419 	mutex_exit(softnet_lock);
420 }
421 
422 void
423 ipflow_create(const struct route *ro, struct mbuf *m)
424 {
425 	const struct ip *const ip = mtod(m, const struct ip *);
426 	struct ipflow *ipf;
427 	size_t hash;
428 	int s;
429 
430 	/*
431 	 * Don't create cache entries for ICMP messages.
432 	 */
433 	if (ip_maxflows == 0 || ip->ip_p == IPPROTO_ICMP)
434 		return;
435 
436 	KERNEL_LOCK(1, NULL);
437 
438 	/*
439 	 * See if an existing flow struct exists.  If so remove it from it's
440 	 * list and free the old route.  If not, try to malloc a new one
441 	 * (if we aren't at our limit).
442 	 */
443 	ipf = ipflow_lookup(ip);
444 	if (ipf == NULL) {
445 		if (ipflow_inuse >= ip_maxflows) {
446 			ipf = ipflow_reap(true);
447 		} else {
448 			s = splnet();
449 			ipf = pool_get(&ipflow_pool, PR_NOWAIT);
450 			splx(s);
451 			if (ipf == NULL)
452 				goto out;
453 			ipflow_inuse++;
454 		}
455 		memset(ipf, 0, sizeof(*ipf));
456 	} else {
457 		s = splnet();
458 		IPFLOW_REMOVE(ipf);
459 		splx(s);
460 		ipflow_addstats(ipf);
461 		rtcache_free(&ipf->ipf_ro);
462 		ipf->ipf_uses = ipf->ipf_last_uses = 0;
463 		ipf->ipf_errors = ipf->ipf_dropped = 0;
464 	}
465 
466 	/*
467 	 * Fill in the updated information.
468 	 */
469 	rtcache_copy(&ipf->ipf_ro, ro);
470 	ipf->ipf_dst = ip->ip_dst;
471 	ipf->ipf_src = ip->ip_src;
472 	ipf->ipf_tos = ip->ip_tos;
473 	PRT_SLOW_ARM(ipf->ipf_timer, IPFLOW_TIMER);
474 
475 	/*
476 	 * Insert into the approriate bucket of the flow table.
477 	 */
478 	hash = ipflow_hash(ip);
479 	s = splnet();
480 	IPFLOW_INSERT(&ipflowtable[hash], ipf);
481 	splx(s);
482 
483  out:
484 	KERNEL_UNLOCK_ONE(NULL);
485 }
486 
487 int
488 ipflow_invalidate_all(int new_size)
489 {
490 	struct ipflow *ipf, *next_ipf;
491 	int s, error;
492 
493 	error = 0;
494 	s = splnet();
495 	for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
496 		next_ipf = LIST_NEXT(ipf, ipf_list);
497 		ipflow_free(ipf);
498 	}
499 
500 	if (new_size)
501 		error = ipflow_reinit(new_size);
502 	splx(s);
503 
504 	return error;
505 }
506 
507 #ifdef GATEWAY
508 /*
509  * sysctl helper routine for net.inet.ip.maxflows.
510  */
511 static int
512 sysctl_net_inet_ip_maxflows(SYSCTLFN_ARGS)
513 {
514 	int error;
515 
516 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
517 	if (error || newp == NULL)
518 		return (error);
519 
520 	mutex_enter(softnet_lock);
521 	KERNEL_LOCK(1, NULL);
522 
523 	ipflow_reap(false);
524 
525 	KERNEL_UNLOCK_ONE(NULL);
526 	mutex_exit(softnet_lock);
527 
528 	return (0);
529 }
530 
531 static int
532 sysctl_net_inet_ip_hashsize(SYSCTLFN_ARGS)
533 {
534 	int error, tmp;
535 	struct sysctlnode node;
536 
537 	node = *rnode;
538 	tmp = ip_hashsize;
539 	node.sysctl_data = &tmp;
540 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
541 	if (error || newp == NULL)
542 		return (error);
543 
544 	if ((tmp & (tmp - 1)) == 0 && tmp != 0) {
545 		/*
546 		 * Can only fail due to malloc()
547 		 */
548 		mutex_enter(softnet_lock);
549 		KERNEL_LOCK(1, NULL);
550 
551 		error = ipflow_invalidate_all(tmp);
552 
553 		KERNEL_UNLOCK_ONE(NULL);
554 		mutex_exit(softnet_lock);
555 
556 	} else {
557 		/*
558 		 * EINVAL if not a power of 2
559 	         */
560 		error = EINVAL;
561 	}
562 
563 	return error;
564 }
565 #endif /* GATEWAY */
566 
567 static void
568 ipflow_sysctl_init(struct sysctllog **clog)
569 {
570 	sysctl_createv(clog, 0, NULL, NULL,
571 		       CTLFLAG_PERMANENT,
572 		       CTLTYPE_NODE, "inet",
573 		       SYSCTL_DESCR("PF_INET related settings"),
574 		       NULL, 0, NULL, 0,
575 		       CTL_NET, PF_INET, CTL_EOL);
576 	sysctl_createv(clog, 0, NULL, NULL,
577 		       CTLFLAG_PERMANENT,
578 		       CTLTYPE_NODE, "ip",
579 		       SYSCTL_DESCR("IPv4 related settings"),
580 		       NULL, 0, NULL, 0,
581 		       CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
582 
583 #ifdef GATEWAY
584 	sysctl_createv(clog, 0, NULL, NULL,
585 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
586 		       CTLTYPE_INT, "maxflows",
587 		       SYSCTL_DESCR("Number of flows for fast forwarding"),
588 		       sysctl_net_inet_ip_maxflows, 0, &ip_maxflows, 0,
589 		       CTL_NET, PF_INET, IPPROTO_IP,
590 		       IPCTL_MAXFLOWS, CTL_EOL);
591 	sysctl_createv(clog, 0, NULL, NULL,
592 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
593 			CTLTYPE_INT, "hashsize",
594 			SYSCTL_DESCR("Size of hash table for fast forwarding (IPv4)"),
595 			sysctl_net_inet_ip_hashsize, 0, &ip_hashsize, 0,
596 			CTL_NET, PF_INET, IPPROTO_IP,
597 			CTL_CREATE, CTL_EOL);
598 #endif /* GATEWAY */
599 }
600