Home | History | Annotate | Line # | Download | only in netinet
ip_flow.c revision 1.65
      1 /*	$NetBSD: ip_flow.c,v 1.65 2014/10/18 08:33:29 snj 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.65 2014/10/18 08:33:29 snj 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 its 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
    311 ipflow_addstats(struct ipflow *ipf)
    312 {
    313 	struct rtentry *rt;
    314 	uint64_t *ips;
    315 
    316 	if ((rt = rtcache_validate(&ipf->ipf_ro)) != NULL)
    317 		rt->rt_use += ipf->ipf_uses;
    318 
    319 	ips = IP_STAT_GETREF();
    320 	ips[IP_STAT_CANTFORWARD] += ipf->ipf_errors + ipf->ipf_dropped;
    321 	ips[IP_STAT_TOTAL] += ipf->ipf_uses;
    322 	ips[IP_STAT_FORWARD] += ipf->ipf_uses;
    323 	ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
    324 	IP_STAT_PUTREF();
    325 }
    326 
    327 static void
    328 ipflow_free(struct ipflow *ipf)
    329 {
    330 	int s;
    331 	/*
    332 	 * Remove the flow from the hash table (at elevated IPL).
    333 	 * Once it's off the list, we can deal with it at normal
    334 	 * network IPL.
    335 	 */
    336 	s = splnet();
    337 	IPFLOW_REMOVE(ipf);
    338 	splx(s);
    339 	ipflow_addstats(ipf);
    340 	rtcache_free(&ipf->ipf_ro);
    341 	ipflow_inuse--;
    342 	s = splnet();
    343 	pool_put(&ipflow_pool, ipf);
    344 	splx(s);
    345 }
    346 
    347 struct ipflow *
    348 ipflow_reap(bool just_one)
    349 {
    350 	while (just_one || ipflow_inuse > ip_maxflows) {
    351 		struct ipflow *ipf, *maybe_ipf = NULL;
    352 		int s;
    353 
    354 		ipf = LIST_FIRST(&ipflowlist);
    355 		while (ipf != NULL) {
    356 			/*
    357 			 * If this no longer points to a valid route
    358 			 * reclaim it.
    359 			 */
    360 			if (rtcache_validate(&ipf->ipf_ro) == NULL)
    361 				goto done;
    362 			/*
    363 			 * choose the one that's been least recently
    364 			 * used or has had the least uses in the
    365 			 * last 1.5 intervals.
    366 			 */
    367 			if (maybe_ipf == NULL ||
    368 			    ipf->ipf_timer < maybe_ipf->ipf_timer ||
    369 			    (ipf->ipf_timer == maybe_ipf->ipf_timer &&
    370 			     ipf->ipf_last_uses + ipf->ipf_uses <
    371 			         maybe_ipf->ipf_last_uses +
    372 			         maybe_ipf->ipf_uses))
    373 				maybe_ipf = ipf;
    374 			ipf = LIST_NEXT(ipf, ipf_list);
    375 		}
    376 		ipf = maybe_ipf;
    377 	    done:
    378 		/*
    379 		 * Remove the entry from the flow table.
    380 		 */
    381 		s = splnet();
    382 		IPFLOW_REMOVE(ipf);
    383 		splx(s);
    384 		ipflow_addstats(ipf);
    385 		rtcache_free(&ipf->ipf_ro);
    386 		if (just_one)
    387 			return ipf;
    388 		pool_put(&ipflow_pool, ipf);
    389 		ipflow_inuse--;
    390 	}
    391 	return NULL;
    392 }
    393 
    394 void
    395 ipflow_slowtimo(void)
    396 {
    397 	struct rtentry *rt;
    398 	struct ipflow *ipf, *next_ipf;
    399 	uint64_t *ips;
    400 
    401 	mutex_enter(softnet_lock);
    402 	KERNEL_LOCK(1, NULL);
    403 	for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
    404 		next_ipf = LIST_NEXT(ipf, ipf_list);
    405 		if (PRT_SLOW_ISEXPIRED(ipf->ipf_timer) ||
    406 		    (rt = rtcache_validate(&ipf->ipf_ro)) == NULL) {
    407 			ipflow_free(ipf);
    408 		} else {
    409 			ipf->ipf_last_uses = ipf->ipf_uses;
    410 			rt->rt_use += ipf->ipf_uses;
    411 			ips = IP_STAT_GETREF();
    412 			ips[IP_STAT_TOTAL] += ipf->ipf_uses;
    413 			ips[IP_STAT_FORWARD] += ipf->ipf_uses;
    414 			ips[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
    415 			IP_STAT_PUTREF();
    416 			ipf->ipf_uses = 0;
    417 		}
    418 	}
    419 	KERNEL_UNLOCK_ONE(NULL);
    420 	mutex_exit(softnet_lock);
    421 }
    422 
    423 void
    424 ipflow_create(const struct route *ro, struct mbuf *m)
    425 {
    426 	const struct ip *const ip = mtod(m, const struct ip *);
    427 	struct ipflow *ipf;
    428 	size_t hash;
    429 	int s;
    430 
    431 	/*
    432 	 * Don't create cache entries for ICMP messages.
    433 	 */
    434 	if (ip_maxflows == 0 || ip->ip_p == IPPROTO_ICMP)
    435 		return;
    436 
    437 	KERNEL_LOCK(1, NULL);
    438 
    439 	/*
    440 	 * See if an existing flow struct exists.  If so remove it from its
    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 				goto out;
    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 
    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  out:
    485 	KERNEL_UNLOCK_ONE(NULL);
    486 }
    487 
    488 int
    489 ipflow_invalidate_all(int new_size)
    490 {
    491 	struct ipflow *ipf, *next_ipf;
    492 	int s, error;
    493 
    494 	error = 0;
    495 	s = splnet();
    496 	for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
    497 		next_ipf = LIST_NEXT(ipf, ipf_list);
    498 		ipflow_free(ipf);
    499 	}
    500 
    501 	if (new_size)
    502 		error = ipflow_reinit(new_size);
    503 	splx(s);
    504 
    505 	return error;
    506 }
    507 
    508 #ifdef GATEWAY
    509 /*
    510  * sysctl helper routine for net.inet.ip.maxflows.
    511  */
    512 static int
    513 sysctl_net_inet_ip_maxflows(SYSCTLFN_ARGS)
    514 {
    515 	int error;
    516 
    517 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
    518 	if (error || newp == NULL)
    519 		return (error);
    520 
    521 	mutex_enter(softnet_lock);
    522 	KERNEL_LOCK(1, NULL);
    523 
    524 	ipflow_reap(false);
    525 
    526 	KERNEL_UNLOCK_ONE(NULL);
    527 	mutex_exit(softnet_lock);
    528 
    529 	return (0);
    530 }
    531 
    532 static int
    533 sysctl_net_inet_ip_hashsize(SYSCTLFN_ARGS)
    534 {
    535 	int error, tmp;
    536 	struct sysctlnode node;
    537 
    538 	node = *rnode;
    539 	tmp = ip_hashsize;
    540 	node.sysctl_data = &tmp;
    541 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    542 	if (error || newp == NULL)
    543 		return (error);
    544 
    545 	if ((tmp & (tmp - 1)) == 0 && tmp != 0) {
    546 		/*
    547 		 * Can only fail due to malloc()
    548 		 */
    549 		mutex_enter(softnet_lock);
    550 		KERNEL_LOCK(1, NULL);
    551 
    552 		error = ipflow_invalidate_all(tmp);
    553 
    554 		KERNEL_UNLOCK_ONE(NULL);
    555 		mutex_exit(softnet_lock);
    556 
    557 	} else {
    558 		/*
    559 		 * EINVAL if not a power of 2
    560 	         */
    561 		error = EINVAL;
    562 	}
    563 
    564 	return error;
    565 }
    566 #endif /* GATEWAY */
    567 
    568 static void
    569 ipflow_sysctl_init(struct sysctllog **clog)
    570 {
    571 	sysctl_createv(clog, 0, NULL, NULL,
    572 		       CTLFLAG_PERMANENT,
    573 		       CTLTYPE_NODE, "inet",
    574 		       SYSCTL_DESCR("PF_INET related settings"),
    575 		       NULL, 0, NULL, 0,
    576 		       CTL_NET, PF_INET, CTL_EOL);
    577 	sysctl_createv(clog, 0, NULL, NULL,
    578 		       CTLFLAG_PERMANENT,
    579 		       CTLTYPE_NODE, "ip",
    580 		       SYSCTL_DESCR("IPv4 related settings"),
    581 		       NULL, 0, NULL, 0,
    582 		       CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
    583 
    584 #ifdef GATEWAY
    585 	sysctl_createv(clog, 0, NULL, NULL,
    586 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    587 		       CTLTYPE_INT, "maxflows",
    588 		       SYSCTL_DESCR("Number of flows for fast forwarding"),
    589 		       sysctl_net_inet_ip_maxflows, 0, &ip_maxflows, 0,
    590 		       CTL_NET, PF_INET, IPPROTO_IP,
    591 		       IPCTL_MAXFLOWS, CTL_EOL);
    592 	sysctl_createv(clog, 0, NULL, NULL,
    593 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    594 			CTLTYPE_INT, "hashsize",
    595 			SYSCTL_DESCR("Size of hash table for fast forwarding (IPv4)"),
    596 			sysctl_net_inet_ip_hashsize, 0, &ip_hashsize, 0,
    597 			CTL_NET, PF_INET, IPPROTO_IP,
    598 			CTL_CREATE, CTL_EOL);
    599 #endif /* GATEWAY */
    600 }
    601