Home | History | Annotate | Line # | Download | only in netinet
ip_flow.c revision 1.53
      1 /*	$NetBSD: ip_flow.c,v 1.53 2008/04/09 05:14:20 thorpej 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  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: ip_flow.c,v 1.53 2008/04/09 05:14:20 thorpej Exp $");
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/malloc.h>
     45 #include <sys/mbuf.h>
     46 #include <sys/domain.h>
     47 #include <sys/protosw.h>
     48 #include <sys/socket.h>
     49 #include <sys/socketvar.h>
     50 #include <sys/errno.h>
     51 #include <sys/time.h>
     52 #include <sys/kernel.h>
     53 #include <sys/pool.h>
     54 #include <sys/sysctl.h>
     55 
     56 #include <net/if.h>
     57 #include <net/if_dl.h>
     58 #include <net/route.h>
     59 #include <net/pfil.h>
     60 
     61 #include <netinet/in.h>
     62 #include <netinet/in_systm.h>
     63 #include <netinet/ip.h>
     64 #include <netinet/in_pcb.h>
     65 #include <netinet/in_var.h>
     66 #include <netinet/ip_var.h>
     67 
     68 /*
     69  * Similar code is very well commented in netinet6/ip6_flow.c
     70  */
     71 
     72 struct ipflow {
     73 	LIST_ENTRY(ipflow) ipf_list;	/* next in active list */
     74 	LIST_ENTRY(ipflow) ipf_hash;	/* next ipflow in bucket */
     75 	struct in_addr ipf_dst;		/* destination address */
     76 	struct in_addr ipf_src;		/* source address */
     77 	uint8_t ipf_tos;		/* type-of-service */
     78 	struct route ipf_ro;		/* associated route entry */
     79 	u_long ipf_uses;		/* number of uses in this period */
     80 	u_long ipf_last_uses;		/* number of uses in last period */
     81 	u_long ipf_dropped;		/* ENOBUFS retured by if_output */
     82 	u_long ipf_errors;		/* other errors returned by if_output */
     83 	u_int ipf_timer;		/* lifetime timer */
     84 	time_t ipf_start;		/* creation time */
     85 };
     86 
     87 #define	IPFLOW_HASHBITS		6	/* should not be a multiple of 8 */
     88 
     89 POOL_INIT(ipflow_pool, sizeof(struct ipflow), 0, 0, 0, "ipflowpl", NULL,
     90     IPL_NET);
     91 
     92 LIST_HEAD(ipflowhead, ipflow);
     93 
     94 #define	IPFLOW_TIMER		(5 * PR_SLOWHZ)
     95 #define	IPFLOW_DEFAULT_HASHSIZE	(1 << IPFLOW_HASHBITS)
     96 
     97 static struct ipflowhead *ipflowtable = NULL;
     98 static struct ipflowhead ipflowlist;
     99 static int ipflow_inuse;
    100 
    101 #define	IPFLOW_INSERT(bucket, ipf) \
    102 do { \
    103 	LIST_INSERT_HEAD((bucket), (ipf), ipf_hash); \
    104 	LIST_INSERT_HEAD(&ipflowlist, (ipf), ipf_list); \
    105 } while (/*CONSTCOND*/ 0)
    106 
    107 #define	IPFLOW_REMOVE(ipf) \
    108 do { \
    109 	LIST_REMOVE((ipf), ipf_hash); \
    110 	LIST_REMOVE((ipf), ipf_list); \
    111 } while (/*CONSTCOND*/ 0)
    112 
    113 #ifndef IPFLOW_MAX
    114 #define	IPFLOW_MAX		256
    115 #endif
    116 int ip_maxflows = IPFLOW_MAX;
    117 int ip_hashsize = IPFLOW_DEFAULT_HASHSIZE;
    118 
    119 static size_t
    120 ipflow_hash(const struct ip *ip)
    121 {
    122 	size_t hash = ip->ip_tos;
    123 	size_t idx;
    124 
    125 	for (idx = 0; idx < 32; idx += IPFLOW_HASHBITS) {
    126 		hash += (ip->ip_dst.s_addr >> (32 - idx)) +
    127 		    (ip->ip_src.s_addr >> idx);
    128 	}
    129 
    130 	return hash & (ip_hashsize-1);
    131 }
    132 
    133 static struct ipflow *
    134 ipflow_lookup(const struct ip *ip)
    135 {
    136 	size_t hash;
    137 	struct ipflow *ipf;
    138 
    139 	hash = ipflow_hash(ip);
    140 
    141 	LIST_FOREACH(ipf, &ipflowtable[hash], ipf_hash) {
    142 		if (ip->ip_dst.s_addr == ipf->ipf_dst.s_addr
    143 		    && ip->ip_src.s_addr == ipf->ipf_src.s_addr
    144 		    && ip->ip_tos == ipf->ipf_tos)
    145 			break;
    146 	}
    147 	return ipf;
    148 }
    149 
    150 int
    151 ipflow_init(int table_size)
    152 {
    153 	struct ipflowhead *new_table;
    154 	size_t i;
    155 
    156 	new_table = (struct ipflowhead *)malloc(sizeof(struct ipflowhead) *
    157 	    table_size, M_RTABLE, M_NOWAIT);
    158 
    159 	if (new_table == NULL)
    160 		return 1;
    161 
    162 	if (ipflowtable != NULL)
    163 		free(ipflowtable, M_RTABLE);
    164 
    165 	ipflowtable = new_table;
    166 	ip_hashsize = table_size;
    167 
    168 	LIST_INIT(&ipflowlist);
    169 	for (i = 0; i < ip_hashsize; i++)
    170 		LIST_INIT(&ipflowtable[i]);
    171 
    172 	return 0;
    173 }
    174 
    175 int
    176 ipflow_fastforward(struct mbuf *m)
    177 {
    178 	struct ip *ip;
    179 	struct ip ip_store;
    180 	struct ipflow *ipf;
    181 	struct rtentry *rt;
    182 	const struct sockaddr *dst;
    183 	int error;
    184 	int iplen;
    185 
    186 	/*
    187 	 * Are we forwarding packets?  Big enough for an IP packet?
    188 	 */
    189 	if (!ipforwarding || ipflow_inuse == 0 || m->m_len < sizeof(struct ip))
    190 		return 0;
    191 
    192 	/*
    193 	 * Was packet received as a link-level multicast or broadcast?
    194 	 * If so, don't try to fast forward..
    195 	 */
    196 	if ((m->m_flags & (M_BCAST|M_MCAST)) != 0)
    197 		return 0;
    198 
    199 	/*
    200 	 * IP header with no option and valid version and length
    201 	 */
    202 	if (IP_HDR_ALIGNED_P(mtod(m, const void *)))
    203 		ip = mtod(m, struct ip *);
    204 	else {
    205 		memcpy(&ip_store, mtod(m, const void *), sizeof(ip_store));
    206 		ip = &ip_store;
    207 	}
    208 	iplen = ntohs(ip->ip_len);
    209 	if (ip->ip_v != IPVERSION || ip->ip_hl != (sizeof(struct ip) >> 2) ||
    210 	    iplen < sizeof(struct ip) || iplen > m->m_pkthdr.len)
    211 		return 0;
    212 	/*
    213 	 * Find a flow.
    214 	 */
    215 	if ((ipf = ipflow_lookup(ip)) == NULL)
    216 		return 0;
    217 
    218 	/*
    219 	 * Verify the IP header checksum.
    220 	 */
    221 	switch (m->m_pkthdr.csum_flags &
    222 		((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_IPv4) |
    223 		 M_CSUM_IPv4_BAD)) {
    224 	case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
    225 		return (0);
    226 
    227 	case M_CSUM_IPv4:
    228 		/* Checksum was okay. */
    229 		break;
    230 
    231 	default:
    232 		/* Must compute it ourselves. */
    233 		if (in_cksum(m, sizeof(struct ip)) != 0)
    234 			return (0);
    235 		break;
    236 	}
    237 
    238 	/*
    239 	 * Route and interface still up?
    240 	 */
    241 	if ((rt = rtcache_validate(&ipf->ipf_ro)) == NULL ||
    242 	    (rt->rt_ifp->if_flags & IFF_UP) == 0)
    243 		return 0;
    244 
    245 	/*
    246 	 * Packet size OK?  TTL?
    247 	 */
    248 	if (m->m_pkthdr.len > rt->rt_ifp->if_mtu || ip->ip_ttl <= IPTTLDEC)
    249 		return 0;
    250 
    251 	/*
    252 	 * Clear any in-bound checksum flags for this packet.
    253 	 */
    254 	m->m_pkthdr.csum_flags = 0;
    255 
    256 	/*
    257 	 * Everything checks out and so we can forward this packet.
    258 	 * Modify the TTL and incrementally change the checksum.
    259 	 *
    260 	 * This method of adding the checksum works on either endian CPU.
    261 	 * If htons() is inlined, all the arithmetic is folded; otherwise
    262 	 * the htons()s are combined by CSE due to the const attribute.
    263 	 *
    264 	 * Don't bother using HW checksumming here -- the incremental
    265 	 * update is pretty fast.
    266 	 */
    267 	ip->ip_ttl -= IPTTLDEC;
    268 	if (ip->ip_sum >= (u_int16_t) ~htons(IPTTLDEC << 8))
    269 		ip->ip_sum -= ~htons(IPTTLDEC << 8);
    270 	else
    271 		ip->ip_sum += htons(IPTTLDEC << 8);
    272 
    273 	/*
    274 	 * Done modifying the header; copy it back, if necessary.
    275 	 *
    276 	 * XXX Use m_copyback_cow(9) here? --dyoung
    277 	 */
    278 	if (IP_HDR_ALIGNED_P(mtod(m, void *)) == 0)
    279 		memcpy(mtod(m, void *), &ip_store, sizeof(ip_store));
    280 
    281 	/*
    282 	 * Trim the packet in case it's too long..
    283 	 */
    284 	if (m->m_pkthdr.len > iplen) {
    285 		if (m->m_len == m->m_pkthdr.len) {
    286 			m->m_len = iplen;
    287 			m->m_pkthdr.len = iplen;
    288 		} else
    289 			m_adj(m, iplen - m->m_pkthdr.len);
    290 	}
    291 
    292 	/*
    293 	 * Send the packet on it's way.  All we can get back is ENOBUFS
    294 	 */
    295 	ipf->ipf_uses++;
    296 	PRT_SLOW_ARM(ipf->ipf_timer, IPFLOW_TIMER);
    297 
    298 	if (rt->rt_flags & RTF_GATEWAY)
    299 		dst = rt->rt_gateway;
    300 	else
    301 		dst = rtcache_getdst(&ipf->ipf_ro);
    302 
    303 	if ((error = (*rt->rt_ifp->if_output)(rt->rt_ifp, m, dst, rt)) != 0) {
    304 		if (error == ENOBUFS)
    305 			ipf->ipf_dropped++;
    306 		else
    307 			ipf->ipf_errors++;
    308 	}
    309 	return 1;
    310 }
    311 
    312 static void
    314 ipflow_addstats(struct ipflow *ipf)
    315 {
    316 	struct rtentry *rt;
    317 
    318 	if ((rt = rtcache_validate(&ipf->ipf_ro)) != NULL)
    319 		rt->rt_use += ipf->ipf_uses;
    320 	ipstat[IP_STAT_CANTFORWARD] += ipf->ipf_errors + ipf->ipf_dropped;
    321 	ipstat[IP_STAT_TOTAL] += ipf->ipf_uses;
    322 	ipstat[IP_STAT_FORWARD] += ipf->ipf_uses;
    323 	ipstat[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
    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 static 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_prune(void)
    395 {
    396 
    397 	(void) ipflow_reap(false);
    398 }
    399 
    400 void
    401 ipflow_slowtimo(void)
    402 {
    403 	struct rtentry *rt;
    404 	struct ipflow *ipf, *next_ipf;
    405 
    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 			ipstat[IP_STAT_TOTAL] += ipf->ipf_uses;
    415 			ipstat[IP_STAT_FORWARD] += ipf->ipf_uses;
    416 			ipstat[IP_STAT_FASTFORWARD] += ipf->ipf_uses;
    417 			ipf->ipf_uses = 0;
    418 		}
    419 	}
    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 	 * See if an existing flow struct exists.  If so remove it from it's
    437 	 * list and free the old route.  If not, try to malloc a new one
    438 	 * (if we aren't at our limit).
    439 	 */
    440 	ipf = ipflow_lookup(ip);
    441 	if (ipf == NULL) {
    442 		if (ipflow_inuse >= ip_maxflows) {
    443 			ipf = ipflow_reap(true);
    444 		} else {
    445 			s = splnet();
    446 			ipf = pool_get(&ipflow_pool, PR_NOWAIT);
    447 			splx(s);
    448 			if (ipf == NULL)
    449 				return;
    450 			ipflow_inuse++;
    451 		}
    452 		memset(ipf, 0, sizeof(*ipf));
    453 	} else {
    454 		s = splnet();
    455 		IPFLOW_REMOVE(ipf);
    456 		splx(s);
    457 		ipflow_addstats(ipf);
    458 		rtcache_free(&ipf->ipf_ro);
    459 		ipf->ipf_uses = ipf->ipf_last_uses = 0;
    460 		ipf->ipf_errors = ipf->ipf_dropped = 0;
    461 	}
    462 
    463 	/*
    464 	 * Fill in the updated information.
    465 	 */
    466 	rtcache_copy(&ipf->ipf_ro, ro);
    467 	ipf->ipf_dst = ip->ip_dst;
    468 	ipf->ipf_src = ip->ip_src;
    469 	ipf->ipf_tos = ip->ip_tos;
    470 	PRT_SLOW_ARM(ipf->ipf_timer, IPFLOW_TIMER);
    471 	ipf->ipf_start = time_uptime;
    472 	/*
    473 	 * Insert into the approriate bucket of the flow table.
    474 	 */
    475 	hash = ipflow_hash(ip);
    476 	s = splnet();
    477 	IPFLOW_INSERT(&ipflowtable[hash], ipf);
    478 	splx(s);
    479 }
    480 
    481 int
    482 ipflow_invalidate_all(int new_size)
    483 {
    484 	struct ipflow *ipf, *next_ipf;
    485 	int s, error;
    486 
    487 	error = 0;
    488 	s = splnet();
    489 	for (ipf = LIST_FIRST(&ipflowlist); ipf != NULL; ipf = next_ipf) {
    490 		next_ipf = LIST_NEXT(ipf, ipf_list);
    491 		ipflow_free(ipf);
    492 	}
    493 
    494 	if (new_size)
    495 		error = ipflow_init(new_size);
    496 	splx(s);
    497 
    498 	return error;
    499 }
    500