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