Home | History | Annotate | Line # | Download | only in netinet
ip_input.c revision 1.253.2.1
      1 /*	$NetBSD: ip_input.c,v 1.253.2.1 2007/10/06 15:29:02 yamt Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the project nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 1998 The NetBSD Foundation, Inc.
     34  * All rights reserved.
     35  *
     36  * This code is derived from software contributed to The NetBSD Foundation
     37  * by Public Access Networks Corporation ("Panix").  It was developed under
     38  * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  * 3. All advertising materials mentioning features or use of this software
     49  *    must display the following acknowledgement:
     50  *	This product includes software developed by the NetBSD
     51  *	Foundation, Inc. and its contributors.
     52  * 4. Neither the name of The NetBSD Foundation nor the names of its
     53  *    contributors may be used to endorse or promote products derived
     54  *    from this software without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     57  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     66  * POSSIBILITY OF SUCH DAMAGE.
     67  */
     68 
     69 /*
     70  * Copyright (c) 1982, 1986, 1988, 1993
     71  *	The Regents of the University of California.  All rights reserved.
     72  *
     73  * Redistribution and use in source and binary forms, with or without
     74  * modification, are permitted provided that the following conditions
     75  * are met:
     76  * 1. Redistributions of source code must retain the above copyright
     77  *    notice, this list of conditions and the following disclaimer.
     78  * 2. Redistributions in binary form must reproduce the above copyright
     79  *    notice, this list of conditions and the following disclaimer in the
     80  *    documentation and/or other materials provided with the distribution.
     81  * 3. Neither the name of the University nor the names of its contributors
     82  *    may be used to endorse or promote products derived from this software
     83  *    without specific prior written permission.
     84  *
     85  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     86  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     87  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     88  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     89  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     90  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     91  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     92  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     93  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     94  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     95  * SUCH DAMAGE.
     96  *
     97  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
     98  */
     99 
    100 #include <sys/cdefs.h>
    101 __KERNEL_RCSID(0, "$NetBSD: ip_input.c,v 1.253.2.1 2007/10/06 15:29:02 yamt Exp $");
    102 
    103 #include "opt_inet.h"
    104 #include "opt_gateway.h"
    105 #include "opt_pfil_hooks.h"
    106 #include "opt_ipsec.h"
    107 #include "opt_mrouting.h"
    108 #include "opt_mbuftrace.h"
    109 #include "opt_inet_csum.h"
    110 
    111 #include <sys/param.h>
    112 #include <sys/systm.h>
    113 #include <sys/malloc.h>
    114 #include <sys/mbuf.h>
    115 #include <sys/domain.h>
    116 #include <sys/protosw.h>
    117 #include <sys/socket.h>
    118 #include <sys/socketvar.h>
    119 #include <sys/errno.h>
    120 #include <sys/time.h>
    121 #include <sys/kernel.h>
    122 #include <sys/pool.h>
    123 #include <sys/sysctl.h>
    124 #include <sys/kauth.h>
    125 
    126 #include <net/if.h>
    127 #include <net/if_dl.h>
    128 #include <net/route.h>
    129 #include <net/pfil.h>
    130 
    131 #include <netinet/in.h>
    132 #include <netinet/in_systm.h>
    133 #include <netinet/ip.h>
    134 #include <netinet/in_pcb.h>
    135 #include <netinet/in_proto.h>
    136 #include <netinet/in_var.h>
    137 #include <netinet/ip_var.h>
    138 #include <netinet/ip_icmp.h>
    139 /* just for gif_ttl */
    140 #include <netinet/in_gif.h>
    141 #include "gif.h"
    142 #include <net/if_gre.h>
    143 #include "gre.h"
    144 
    145 #ifdef MROUTING
    146 #include <netinet/ip_mroute.h>
    147 #endif
    148 
    149 #ifdef IPSEC
    150 #include <netinet6/ipsec.h>
    151 #include <netkey/key.h>
    152 #endif
    153 #ifdef FAST_IPSEC
    154 #include <netipsec/ipsec.h>
    155 #include <netipsec/key.h>
    156 #endif	/* FAST_IPSEC*/
    157 
    158 #ifndef	IPFORWARDING
    159 #ifdef GATEWAY
    160 #define	IPFORWARDING	1	/* forward IP packets not for us */
    161 #else /* GATEWAY */
    162 #define	IPFORWARDING	0	/* don't forward IP packets not for us */
    163 #endif /* GATEWAY */
    164 #endif /* IPFORWARDING */
    165 #ifndef	IPSENDREDIRECTS
    166 #define	IPSENDREDIRECTS	1
    167 #endif
    168 #ifndef IPFORWSRCRT
    169 #define	IPFORWSRCRT	1	/* forward source-routed packets */
    170 #endif
    171 #ifndef IPALLOWSRCRT
    172 #define	IPALLOWSRCRT	1	/* allow source-routed packets */
    173 #endif
    174 #ifndef IPMTUDISC
    175 #define IPMTUDISC	1
    176 #endif
    177 #ifndef IPMTUDISCTIMEOUT
    178 #define IPMTUDISCTIMEOUT (10 * 60)	/* as per RFC 1191 */
    179 #endif
    180 
    181 /*
    182  * Note: DIRECTED_BROADCAST is handled this way so that previous
    183  * configuration using this option will Just Work.
    184  */
    185 #ifndef IPDIRECTEDBCAST
    186 #ifdef DIRECTED_BROADCAST
    187 #define IPDIRECTEDBCAST	1
    188 #else
    189 #define	IPDIRECTEDBCAST	0
    190 #endif /* DIRECTED_BROADCAST */
    191 #endif /* IPDIRECTEDBCAST */
    192 int	ipforwarding = IPFORWARDING;
    193 int	ipsendredirects = IPSENDREDIRECTS;
    194 int	ip_defttl = IPDEFTTL;
    195 int	ip_forwsrcrt = IPFORWSRCRT;
    196 int	ip_directedbcast = IPDIRECTEDBCAST;
    197 int	ip_allowsrcrt = IPALLOWSRCRT;
    198 int	ip_mtudisc = IPMTUDISC;
    199 int	ip_mtudisc_timeout = IPMTUDISCTIMEOUT;
    200 #ifdef DIAGNOSTIC
    201 int	ipprintfs = 0;
    202 #endif
    203 
    204 int	ip_do_randomid = 0;
    205 
    206 /*
    207  * XXX - Setting ip_checkinterface mostly implements the receive side of
    208  * the Strong ES model described in RFC 1122, but since the routing table
    209  * and transmit implementation do not implement the Strong ES model,
    210  * setting this to 1 results in an odd hybrid.
    211  *
    212  * XXX - ip_checkinterface currently must be disabled if you use ipnat
    213  * to translate the destination address to another local interface.
    214  *
    215  * XXX - ip_checkinterface must be disabled if you add IP aliases
    216  * to the loopback interface instead of the interface where the
    217  * packets for those addresses are received.
    218  */
    219 int	ip_checkinterface = 0;
    220 
    221 
    222 struct rttimer_queue *ip_mtudisc_timeout_q = NULL;
    223 
    224 int	ipqmaxlen = IFQ_MAXLEN;
    225 u_long	in_ifaddrhash;				/* size of hash table - 1 */
    226 int	in_ifaddrentries;			/* total number of addrs */
    227 struct in_ifaddrhead in_ifaddrhead;
    228 struct	in_ifaddrhashhead *in_ifaddrhashtbl;
    229 u_long	in_multihash;				/* size of hash table - 1 */
    230 int	in_multientries;			/* total number of addrs */
    231 struct	in_multihashhead *in_multihashtbl;
    232 struct	ifqueue ipintrq;
    233 struct	ipstat	ipstat;
    234 uint16_t ip_id;
    235 
    236 #ifdef PFIL_HOOKS
    237 struct pfil_head inet_pfil_hook;
    238 #endif
    239 
    240 /*
    241  * Cached copy of nmbclusters. If nbclusters is different,
    242  * recalculate IP parameters derived from nmbclusters.
    243  */
    244 static int	ip_nmbclusters;			/* copy of nmbclusters */
    245 static void	ip_nmbclusters_changed(void);	/* recalc limits */
    246 
    247 #define CHECK_NMBCLUSTER_PARAMS()				\
    248 do {								\
    249 	if (__predict_false(ip_nmbclusters != nmbclusters))	\
    250 		ip_nmbclusters_changed();			\
    251 } while (/*CONSTCOND*/0)
    252 
    253 /* IP datagram reassembly queues (hashed) */
    254 #define IPREASS_NHASH_LOG2      6
    255 #define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
    256 #define IPREASS_HMASK           (IPREASS_NHASH - 1)
    257 #define IPREASS_HASH(x,y) \
    258 	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
    259 struct ipqhead ipq[IPREASS_NHASH];
    260 int	ipq_locked;
    261 static int	ip_nfragpackets;	/* packets in reass queue */
    262 static int	ip_nfrags;		/* total fragments in reass queues */
    263 
    264 int	ip_maxfragpackets = 200;	/* limit on packets. XXX sysctl */
    265 int	ip_maxfrags;		        /* limit on fragments. XXX sysctl */
    266 
    267 
    268 /*
    269  * Additive-Increase/Multiplicative-Decrease (AIMD) strategy for
    270  * IP reassembly queue buffer managment.
    271  *
    272  * We keep a count of total IP fragments (NB: not fragmented packets!)
    273  * awaiting reassembly (ip_nfrags) and a limit (ip_maxfrags) on fragments.
    274  * If ip_nfrags exceeds ip_maxfrags the limit, we drop half the
    275  * total fragments in  reassembly queues.This AIMD policy avoids
    276  * repeatedly deleting single packets under heavy fragmentation load
    277  * (e.g., from lossy NFS peers).
    278  */
    279 static u_int	ip_reass_ttl_decr(u_int ticks);
    280 static void	ip_reass_drophalf(void);
    281 
    282 
    283 static inline int ipq_lock_try(void);
    284 static inline void ipq_unlock(void);
    285 
    286 static inline int
    287 ipq_lock_try(void)
    288 {
    289 	int s;
    290 
    291 	/*
    292 	 * Use splvm() -- we're blocking things that would cause
    293 	 * mbuf allocation.
    294 	 */
    295 	s = splvm();
    296 	if (ipq_locked) {
    297 		splx(s);
    298 		return (0);
    299 	}
    300 	ipq_locked = 1;
    301 	splx(s);
    302 	return (1);
    303 }
    304 
    305 static inline void
    306 ipq_unlock(void)
    307 {
    308 	int s;
    309 
    310 	s = splvm();
    311 	ipq_locked = 0;
    312 	splx(s);
    313 }
    314 
    315 #ifdef DIAGNOSTIC
    316 #define	IPQ_LOCK()							\
    317 do {									\
    318 	if (ipq_lock_try() == 0) {					\
    319 		printf("%s:%d: ipq already locked\n", __FILE__, __LINE__); \
    320 		panic("ipq_lock");					\
    321 	}								\
    322 } while (/*CONSTCOND*/ 0)
    323 #define	IPQ_LOCK_CHECK()						\
    324 do {									\
    325 	if (ipq_locked == 0) {						\
    326 		printf("%s:%d: ipq lock not held\n", __FILE__, __LINE__); \
    327 		panic("ipq lock check");				\
    328 	}								\
    329 } while (/*CONSTCOND*/ 0)
    330 #else
    331 #define	IPQ_LOCK()		(void) ipq_lock_try()
    332 #define	IPQ_LOCK_CHECK()	/* nothing */
    333 #endif
    334 
    335 #define	IPQ_UNLOCK()		ipq_unlock()
    336 
    337 POOL_INIT(inmulti_pool, sizeof(struct in_multi), 0, 0, 0, "inmltpl", NULL,
    338     IPL_SOFTNET);
    339 POOL_INIT(ipqent_pool, sizeof(struct ipqent), 0, 0, 0, "ipqepl", NULL,
    340     IPL_VM);
    341 
    342 #ifdef INET_CSUM_COUNTERS
    343 #include <sys/device.h>
    344 
    345 struct evcnt ip_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    346     NULL, "inet", "hwcsum bad");
    347 struct evcnt ip_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    348     NULL, "inet", "hwcsum ok");
    349 struct evcnt ip_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    350     NULL, "inet", "swcsum");
    351 
    352 #define	INET_CSUM_COUNTER_INCR(ev)	(ev)->ev_count++
    353 
    354 EVCNT_ATTACH_STATIC(ip_hwcsum_bad);
    355 EVCNT_ATTACH_STATIC(ip_hwcsum_ok);
    356 EVCNT_ATTACH_STATIC(ip_swcsum);
    357 
    358 #else
    359 
    360 #define	INET_CSUM_COUNTER_INCR(ev)	/* nothing */
    361 
    362 #endif /* INET_CSUM_COUNTERS */
    363 
    364 /*
    365  * We need to save the IP options in case a protocol wants to respond
    366  * to an incoming packet over the same route if the packet got here
    367  * using IP source routing.  This allows connection establishment and
    368  * maintenance when the remote end is on a network that is not known
    369  * to us.
    370  */
    371 int	ip_nhops = 0;
    372 static	struct ip_srcrt {
    373 	struct	in_addr dst;			/* final destination */
    374 	char	nop;				/* one NOP to align */
    375 	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
    376 	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
    377 } ip_srcrt;
    378 
    379 static void save_rte(u_char *, struct in_addr);
    380 
    381 #ifdef MBUFTRACE
    382 struct mowner ip_rx_mowner = MOWNER_INIT("internet", "rx");
    383 struct mowner ip_tx_mowner = MOWNER_INIT("internet", "tx");
    384 #endif
    385 
    386 /*
    387  * Compute IP limits derived from the value of nmbclusters.
    388  */
    389 static void
    390 ip_nmbclusters_changed(void)
    391 {
    392 	ip_maxfrags = nmbclusters / 4;
    393 	ip_nmbclusters =  nmbclusters;
    394 }
    395 
    396 /*
    397  * IP initialization: fill in IP protocol switch table.
    398  * All protocols not implemented in kernel go to raw IP protocol handler.
    399  */
    400 void
    401 ip_init(void)
    402 {
    403 	const struct protosw *pr;
    404 	int i;
    405 
    406 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
    407 	if (pr == 0)
    408 		panic("ip_init");
    409 	for (i = 0; i < IPPROTO_MAX; i++)
    410 		ip_protox[i] = pr - inetsw;
    411 	for (pr = inetdomain.dom_protosw;
    412 	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
    413 		if (pr->pr_domain->dom_family == PF_INET &&
    414 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
    415 			ip_protox[pr->pr_protocol] = pr - inetsw;
    416 
    417 	for (i = 0; i < IPREASS_NHASH; i++)
    418 	    	LIST_INIT(&ipq[i]);
    419 
    420 	ip_id = time_second & 0xfffff;
    421 
    422 	ipintrq.ifq_maxlen = ipqmaxlen;
    423 	ip_nmbclusters_changed();
    424 
    425 	TAILQ_INIT(&in_ifaddrhead);
    426 	in_ifaddrhashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, M_IFADDR,
    427 	    M_WAITOK, &in_ifaddrhash);
    428 	in_multihashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, M_IPMADDR,
    429 	    M_WAITOK, &in_multihash);
    430 	ip_mtudisc_timeout_q = rt_timer_queue_create(ip_mtudisc_timeout);
    431 #ifdef GATEWAY
    432 	ipflow_init(ip_hashsize);
    433 #endif
    434 
    435 #ifdef PFIL_HOOKS
    436 	/* Register our Packet Filter hook. */
    437 	inet_pfil_hook.ph_type = PFIL_TYPE_AF;
    438 	inet_pfil_hook.ph_af   = AF_INET;
    439 	i = pfil_head_register(&inet_pfil_hook);
    440 	if (i != 0)
    441 		printf("ip_init: WARNING: unable to register pfil hook, "
    442 		    "error %d\n", i);
    443 #endif /* PFIL_HOOKS */
    444 
    445 #ifdef MBUFTRACE
    446 	MOWNER_ATTACH(&ip_tx_mowner);
    447 	MOWNER_ATTACH(&ip_rx_mowner);
    448 #endif /* MBUFTRACE */
    449 }
    450 
    451 struct	sockaddr_in ipaddr = {
    452 	.sin_len = sizeof(ipaddr),
    453 	.sin_family = AF_INET,
    454 };
    455 struct	route ipforward_rt;
    456 
    457 /*
    458  * IP software interrupt routine
    459  */
    460 void
    461 ipintr(void)
    462 {
    463 	int s;
    464 	struct mbuf *m;
    465 
    466 	while (!IF_IS_EMPTY(&ipintrq)) {
    467 		s = splnet();
    468 		IF_DEQUEUE(&ipintrq, m);
    469 		splx(s);
    470 		if (m == 0)
    471 			return;
    472 		MCLAIM(m, &ip_rx_mowner);
    473 		ip_input(m);
    474 	}
    475 }
    476 
    477 /*
    478  * Ip input routine.  Checksum and byte swap header.  If fragmented
    479  * try to reassemble.  Process options.  Pass to next level.
    480  */
    481 void
    482 ip_input(struct mbuf *m)
    483 {
    484 	struct ip *ip = NULL;
    485 	struct ipq *fp;
    486 	struct in_ifaddr *ia;
    487 	struct ifaddr *ifa;
    488 	struct ipqent *ipqe;
    489 	int hlen = 0, mff, len;
    490 	int downmatch;
    491 	int checkif;
    492 	int srcrt = 0;
    493 	int s;
    494 	u_int hash;
    495 #ifdef FAST_IPSEC
    496 	struct m_tag *mtag;
    497 	struct tdb_ident *tdbi;
    498 	struct secpolicy *sp;
    499 	int error;
    500 #endif /* FAST_IPSEC */
    501 
    502 	MCLAIM(m, &ip_rx_mowner);
    503 #ifdef	DIAGNOSTIC
    504 	if ((m->m_flags & M_PKTHDR) == 0)
    505 		panic("ipintr no HDR");
    506 #endif
    507 
    508 	/*
    509 	 * If no IP addresses have been set yet but the interfaces
    510 	 * are receiving, can't do anything with incoming packets yet.
    511 	 */
    512 	if (TAILQ_FIRST(&in_ifaddrhead) == 0)
    513 		goto bad;
    514 	ipstat.ips_total++;
    515 	/*
    516 	 * If the IP header is not aligned, slurp it up into a new
    517 	 * mbuf with space for link headers, in the event we forward
    518 	 * it.  Otherwise, if it is aligned, make sure the entire
    519 	 * base IP header is in the first mbuf of the chain.
    520 	 */
    521 	if (IP_HDR_ALIGNED_P(mtod(m, void *)) == 0) {
    522 		if ((m = m_copyup(m, sizeof(struct ip),
    523 				  (max_linkhdr + 3) & ~3)) == NULL) {
    524 			/* XXXJRT new stat, please */
    525 			ipstat.ips_toosmall++;
    526 			return;
    527 		}
    528 	} else if (__predict_false(m->m_len < sizeof (struct ip))) {
    529 		if ((m = m_pullup(m, sizeof (struct ip))) == NULL) {
    530 			ipstat.ips_toosmall++;
    531 			return;
    532 		}
    533 	}
    534 	ip = mtod(m, struct ip *);
    535 	if (ip->ip_v != IPVERSION) {
    536 		ipstat.ips_badvers++;
    537 		goto bad;
    538 	}
    539 	hlen = ip->ip_hl << 2;
    540 	if (hlen < sizeof(struct ip)) {	/* minimum header length */
    541 		ipstat.ips_badhlen++;
    542 		goto bad;
    543 	}
    544 	if (hlen > m->m_len) {
    545 		if ((m = m_pullup(m, hlen)) == 0) {
    546 			ipstat.ips_badhlen++;
    547 			return;
    548 		}
    549 		ip = mtod(m, struct ip *);
    550 	}
    551 
    552 	/*
    553 	 * RFC1122: packets with a multicast source address are
    554 	 * not allowed.
    555 	 */
    556 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
    557 		ipstat.ips_badaddr++;
    558 		goto bad;
    559 	}
    560 
    561 	/* 127/8 must not appear on wire - RFC1122 */
    562 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
    563 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
    564 		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
    565 			ipstat.ips_badaddr++;
    566 			goto bad;
    567 		}
    568 	}
    569 
    570 	switch (m->m_pkthdr.csum_flags &
    571 		((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_IPv4) |
    572 		 M_CSUM_IPv4_BAD)) {
    573 	case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
    574 		INET_CSUM_COUNTER_INCR(&ip_hwcsum_bad);
    575 		goto badcsum;
    576 
    577 	case M_CSUM_IPv4:
    578 		/* Checksum was okay. */
    579 		INET_CSUM_COUNTER_INCR(&ip_hwcsum_ok);
    580 		break;
    581 
    582 	default:
    583 		/*
    584 		 * Must compute it ourselves.  Maybe skip checksum on
    585 		 * loopback interfaces.
    586 		 */
    587 		if (__predict_true(!(m->m_pkthdr.rcvif->if_flags &
    588 				     IFF_LOOPBACK) || ip_do_loopback_cksum)) {
    589 			INET_CSUM_COUNTER_INCR(&ip_swcsum);
    590 			if (in_cksum(m, hlen) != 0)
    591 				goto badcsum;
    592 		}
    593 		break;
    594 	}
    595 
    596 	/* Retrieve the packet length. */
    597 	len = ntohs(ip->ip_len);
    598 
    599 	/*
    600 	 * Check for additional length bogosity
    601 	 */
    602 	if (len < hlen) {
    603 	 	ipstat.ips_badlen++;
    604 		goto bad;
    605 	}
    606 
    607 	/*
    608 	 * Check that the amount of data in the buffers
    609 	 * is as at least much as the IP header would have us expect.
    610 	 * Trim mbufs if longer than we expect.
    611 	 * Drop packet if shorter than we expect.
    612 	 */
    613 	if (m->m_pkthdr.len < len) {
    614 		ipstat.ips_tooshort++;
    615 		goto bad;
    616 	}
    617 	if (m->m_pkthdr.len > len) {
    618 		if (m->m_len == m->m_pkthdr.len) {
    619 			m->m_len = len;
    620 			m->m_pkthdr.len = len;
    621 		} else
    622 			m_adj(m, len - m->m_pkthdr.len);
    623 	}
    624 
    625 #if defined(IPSEC)
    626 	/* ipflow (IP fast forwarding) is not compatible with IPsec. */
    627 	m->m_flags &= ~M_CANFASTFWD;
    628 #else
    629 	/*
    630 	 * Assume that we can create a fast-forward IP flow entry
    631 	 * based on this packet.
    632 	 */
    633 	m->m_flags |= M_CANFASTFWD;
    634 #endif
    635 
    636 #ifdef PFIL_HOOKS
    637 	/*
    638 	 * Run through list of hooks for input packets.  If there are any
    639 	 * filters which require that additional packets in the flow are
    640 	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
    641 	 * Note that filters must _never_ set this flag, as another filter
    642 	 * in the list may have previously cleared it.
    643 	 */
    644 	/*
    645 	 * let ipfilter look at packet on the wire,
    646 	 * not the decapsulated packet.
    647 	 */
    648 #ifdef IPSEC
    649 	if (!ipsec_getnhist(m))
    650 #elif defined(FAST_IPSEC)
    651 	if (!ipsec_indone(m))
    652 #else
    653 	if (1)
    654 #endif
    655 	{
    656 		struct in_addr odst;
    657 
    658 		odst = ip->ip_dst;
    659 		if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
    660 		    PFIL_IN) != 0)
    661 			return;
    662 		if (m == NULL)
    663 			return;
    664 		ip = mtod(m, struct ip *);
    665 		hlen = ip->ip_hl << 2;
    666 		/*
    667 		 * XXX The setting of "srcrt" here is to prevent ip_forward()
    668 		 * from generating ICMP redirects for packets that have
    669 		 * been redirected by a hook back out on to the same LAN that
    670 		 * they came from and is not an indication that the packet
    671 		 * is being inffluenced by source routing options.  This
    672 		 * allows things like
    673 		 * "rdr tlp0 0/0 port 80 -> 1.1.1.200 3128 tcp"
    674 		 * where tlp0 is both on the 1.1.1.0/24 network and is the
    675 		 * default route for hosts on 1.1.1.0/24.  Of course this
    676 		 * also requires a "map tlp0 ..." to complete the story.
    677 		 * One might argue whether or not this kind of network config.
    678 		 * should be supported in this manner...
    679 		 */
    680 		srcrt = (odst.s_addr != ip->ip_dst.s_addr);
    681 	}
    682 #endif /* PFIL_HOOKS */
    683 
    684 #ifdef ALTQ
    685 	/* XXX Temporary until ALTQ is changed to use a pfil hook */
    686 	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0) {
    687 		/* packet dropped by traffic conditioner */
    688 		return;
    689 	}
    690 #endif
    691 
    692 	/*
    693 	 * Process options and, if not destined for us,
    694 	 * ship it on.  ip_dooptions returns 1 when an
    695 	 * error was detected (causing an icmp message
    696 	 * to be sent and the original packet to be freed).
    697 	 */
    698 	ip_nhops = 0;		/* for source routed packets */
    699 	if (hlen > sizeof (struct ip) && ip_dooptions(m))
    700 		return;
    701 
    702 	/*
    703 	 * Enable a consistency check between the destination address
    704 	 * and the arrival interface for a unicast packet (the RFC 1122
    705 	 * strong ES model) if IP forwarding is disabled and the packet
    706 	 * is not locally generated.
    707 	 *
    708 	 * XXX - Checking also should be disabled if the destination
    709 	 * address is ipnat'ed to a different interface.
    710 	 *
    711 	 * XXX - Checking is incompatible with IP aliases added
    712 	 * to the loopback interface instead of the interface where
    713 	 * the packets are received.
    714 	 *
    715 	 * XXX - We need to add a per ifaddr flag for this so that
    716 	 * we get finer grain control.
    717 	 */
    718 	checkif = ip_checkinterface && (ipforwarding == 0) &&
    719 	    (m->m_pkthdr.rcvif != NULL) &&
    720 	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0);
    721 
    722 	/*
    723 	 * Check our list of addresses, to see if the packet is for us.
    724 	 *
    725 	 * Traditional 4.4BSD did not consult IFF_UP at all.
    726 	 * The behavior here is to treat addresses on !IFF_UP interface
    727 	 * as not mine.
    728 	 */
    729 	downmatch = 0;
    730 	LIST_FOREACH(ia, &IN_IFADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
    731 		if (in_hosteq(ia->ia_addr.sin_addr, ip->ip_dst)) {
    732 			if (checkif && ia->ia_ifp != m->m_pkthdr.rcvif)
    733 				continue;
    734 			if ((ia->ia_ifp->if_flags & IFF_UP) != 0)
    735 				break;
    736 			else
    737 				downmatch++;
    738 		}
    739 	}
    740 	if (ia != NULL)
    741 		goto ours;
    742 	if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
    743 		IFADDR_FOREACH(ifa, m->m_pkthdr.rcvif) {
    744 			if (ifa->ifa_addr->sa_family != AF_INET)
    745 				continue;
    746 			ia = ifatoia(ifa);
    747 			if (in_hosteq(ip->ip_dst, ia->ia_broadaddr.sin_addr) ||
    748 			    in_hosteq(ip->ip_dst, ia->ia_netbroadcast) ||
    749 			    /*
    750 			     * Look for all-0's host part (old broadcast addr),
    751 			     * either for subnet or net.
    752 			     */
    753 			    ip->ip_dst.s_addr == ia->ia_subnet ||
    754 			    ip->ip_dst.s_addr == ia->ia_net)
    755 				goto ours;
    756 			/*
    757 			 * An interface with IP address zero accepts
    758 			 * all packets that arrive on that interface.
    759 			 */
    760 			if (in_nullhost(ia->ia_addr.sin_addr))
    761 				goto ours;
    762 		}
    763 	}
    764 	if (IN_MULTICAST(ip->ip_dst.s_addr)) {
    765 		struct in_multi *inm;
    766 #ifdef MROUTING
    767 		extern struct socket *ip_mrouter;
    768 
    769 		if (ip_mrouter) {
    770 			/*
    771 			 * If we are acting as a multicast router, all
    772 			 * incoming multicast packets are passed to the
    773 			 * kernel-level multicast forwarding function.
    774 			 * The packet is returned (relatively) intact; if
    775 			 * ip_mforward() returns a non-zero value, the packet
    776 			 * must be discarded, else it may be accepted below.
    777 			 *
    778 			 * (The IP ident field is put in the same byte order
    779 			 * as expected when ip_mforward() is called from
    780 			 * ip_output().)
    781 			 */
    782 			if (ip_mforward(m, m->m_pkthdr.rcvif) != 0) {
    783 				ipstat.ips_cantforward++;
    784 				m_freem(m);
    785 				return;
    786 			}
    787 
    788 			/*
    789 			 * The process-level routing demon needs to receive
    790 			 * all multicast IGMP packets, whether or not this
    791 			 * host belongs to their destination groups.
    792 			 */
    793 			if (ip->ip_p == IPPROTO_IGMP)
    794 				goto ours;
    795 			ipstat.ips_forward++;
    796 		}
    797 #endif
    798 		/*
    799 		 * See if we belong to the destination multicast group on the
    800 		 * arrival interface.
    801 		 */
    802 		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
    803 		if (inm == NULL) {
    804 			ipstat.ips_cantforward++;
    805 			m_freem(m);
    806 			return;
    807 		}
    808 		goto ours;
    809 	}
    810 	if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
    811 	    in_nullhost(ip->ip_dst))
    812 		goto ours;
    813 
    814 	/*
    815 	 * Not for us; forward if possible and desirable.
    816 	 */
    817 	if (ipforwarding == 0) {
    818 		ipstat.ips_cantforward++;
    819 		m_freem(m);
    820 	} else {
    821 		/*
    822 		 * If ip_dst matched any of my address on !IFF_UP interface,
    823 		 * and there's no IFF_UP interface that matches ip_dst,
    824 		 * send icmp unreach.  Forwarding it will result in in-kernel
    825 		 * forwarding loop till TTL goes to 0.
    826 		 */
    827 		if (downmatch) {
    828 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
    829 			ipstat.ips_cantforward++;
    830 			return;
    831 		}
    832 #ifdef IPSEC
    833 		if (ipsec4_in_reject(m, NULL)) {
    834 			ipsecstat.in_polvio++;
    835 			goto bad;
    836 		}
    837 #endif
    838 #ifdef FAST_IPSEC
    839 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
    840 		s = splsoftnet();
    841 		if (mtag != NULL) {
    842 			tdbi = (struct tdb_ident *)(mtag + 1);
    843 			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
    844 		} else {
    845 			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
    846 						   IP_FORWARDING, &error);
    847 		}
    848 		if (sp == NULL) {	/* NB: can happen if error */
    849 			splx(s);
    850 			/*XXX error stat???*/
    851 			DPRINTF(("ip_input: no SP for forwarding\n"));	/*XXX*/
    852 			goto bad;
    853 		}
    854 
    855 		/*
    856 		 * Check security policy against packet attributes.
    857 		 */
    858 		error = ipsec_in_reject(sp, m);
    859 		KEY_FREESP(&sp);
    860 		splx(s);
    861 		if (error) {
    862 			ipstat.ips_cantforward++;
    863 			goto bad;
    864 		}
    865 
    866 		/*
    867 		 * Peek at the outbound SP for this packet to determine if
    868 		 * it's a Fast Forward candidate.
    869 		 */
    870 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
    871 		if (mtag != NULL)
    872 			m->m_flags &= ~M_CANFASTFWD;
    873 		else {
    874 			s = splsoftnet();
    875 			sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND,
    876 			    (IP_FORWARDING |
    877 			     (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
    878 			    &error, NULL);
    879 			if (sp != NULL) {
    880 				m->m_flags &= ~M_CANFASTFWD;
    881 				KEY_FREESP(&sp);
    882 			}
    883 			splx(s);
    884 		}
    885 #endif	/* FAST_IPSEC */
    886 
    887 		ip_forward(m, srcrt);
    888 	}
    889 	return;
    890 
    891 ours:
    892 	/*
    893 	 * If offset or IP_MF are set, must reassemble.
    894 	 * Otherwise, nothing need be done.
    895 	 * (We could look in the reassembly queue to see
    896 	 * if the packet was previously fragmented,
    897 	 * but it's not worth the time; just let them time out.)
    898 	 */
    899 	if (ip->ip_off & ~htons(IP_DF|IP_RF)) {
    900 
    901 		/*
    902 		 * Look for queue of fragments
    903 		 * of this datagram.
    904 		 */
    905 		IPQ_LOCK();
    906 		hash = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
    907 		LIST_FOREACH(fp, &ipq[hash], ipq_q) {
    908 			if (ip->ip_id == fp->ipq_id &&
    909 			    in_hosteq(ip->ip_src, fp->ipq_src) &&
    910 			    in_hosteq(ip->ip_dst, fp->ipq_dst) &&
    911 			    ip->ip_p == fp->ipq_p)
    912 				goto found;
    913 
    914 		}
    915 		fp = 0;
    916 found:
    917 
    918 		/*
    919 		 * Adjust ip_len to not reflect header,
    920 		 * set ipqe_mff if more fragments are expected,
    921 		 * convert offset of this to bytes.
    922 		 */
    923 		ip->ip_len = htons(ntohs(ip->ip_len) - hlen);
    924 		mff = (ip->ip_off & htons(IP_MF)) != 0;
    925 		if (mff) {
    926 		        /*
    927 		         * Make sure that fragments have a data length
    928 			 * that's a non-zero multiple of 8 bytes.
    929 		         */
    930 			if (ntohs(ip->ip_len) == 0 ||
    931 			    (ntohs(ip->ip_len) & 0x7) != 0) {
    932 				ipstat.ips_badfrags++;
    933 				IPQ_UNLOCK();
    934 				goto bad;
    935 			}
    936 		}
    937 		ip->ip_off = htons((ntohs(ip->ip_off) & IP_OFFMASK) << 3);
    938 
    939 		/*
    940 		 * If datagram marked as having more fragments
    941 		 * or if this is not the first fragment,
    942 		 * attempt reassembly; if it succeeds, proceed.
    943 		 */
    944 		if (mff || ip->ip_off != htons(0)) {
    945 			ipstat.ips_fragments++;
    946 			s = splvm();
    947 			ipqe = pool_get(&ipqent_pool, PR_NOWAIT);
    948 			splx(s);
    949 			if (ipqe == NULL) {
    950 				ipstat.ips_rcvmemdrop++;
    951 				IPQ_UNLOCK();
    952 				goto bad;
    953 			}
    954 			ipqe->ipqe_mff = mff;
    955 			ipqe->ipqe_m = m;
    956 			ipqe->ipqe_ip = ip;
    957 			m = ip_reass(ipqe, fp, &ipq[hash]);
    958 			if (m == 0) {
    959 				IPQ_UNLOCK();
    960 				return;
    961 			}
    962 			ipstat.ips_reassembled++;
    963 			ip = mtod(m, struct ip *);
    964 			hlen = ip->ip_hl << 2;
    965 			ip->ip_len = htons(ntohs(ip->ip_len) + hlen);
    966 		} else
    967 			if (fp)
    968 				ip_freef(fp);
    969 		IPQ_UNLOCK();
    970 	}
    971 
    972 #if defined(IPSEC)
    973 	/*
    974 	 * enforce IPsec policy checking if we are seeing last header.
    975 	 * note that we do not visit this with protocols with pcb layer
    976 	 * code - like udp/tcp/raw ip.
    977 	 */
    978 	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
    979 	    ipsec4_in_reject(m, NULL)) {
    980 		ipsecstat.in_polvio++;
    981 		goto bad;
    982 	}
    983 #endif
    984 #ifdef FAST_IPSEC
    985 	/*
    986 	 * enforce IPsec policy checking if we are seeing last header.
    987 	 * note that we do not visit this with protocols with pcb layer
    988 	 * code - like udp/tcp/raw ip.
    989 	 */
    990 	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
    991 		/*
    992 		 * Check if the packet has already had IPsec processing
    993 		 * done.  If so, then just pass it along.  This tag gets
    994 		 * set during AH, ESP, etc. input handling, before the
    995 		 * packet is returned to the ip input queue for delivery.
    996 		 */
    997 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
    998 		s = splsoftnet();
    999 		if (mtag != NULL) {
   1000 			tdbi = (struct tdb_ident *)(mtag + 1);
   1001 			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
   1002 		} else {
   1003 			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
   1004 						   IP_FORWARDING, &error);
   1005 		}
   1006 		if (sp != NULL) {
   1007 			/*
   1008 			 * Check security policy against packet attributes.
   1009 			 */
   1010 			error = ipsec_in_reject(sp, m);
   1011 			KEY_FREESP(&sp);
   1012 		} else {
   1013 			/* XXX error stat??? */
   1014 			error = EINVAL;
   1015 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
   1016 		}
   1017 		splx(s);
   1018 		if (error)
   1019 			goto bad;
   1020 	}
   1021 #endif /* FAST_IPSEC */
   1022 
   1023 	/*
   1024 	 * Switch out to protocol's input routine.
   1025 	 */
   1026 #if IFA_STATS
   1027 	if (ia && ip)
   1028 		ia->ia_ifa.ifa_data.ifad_inbytes += ntohs(ip->ip_len);
   1029 #endif
   1030 	ipstat.ips_delivered++;
   1031     {
   1032 	int off = hlen, nh = ip->ip_p;
   1033 
   1034 	(*inetsw[ip_protox[nh]].pr_input)(m, off, nh);
   1035 	return;
   1036     }
   1037 bad:
   1038 	m_freem(m);
   1039 	return;
   1040 
   1041 badcsum:
   1042 	ipstat.ips_badsum++;
   1043 	m_freem(m);
   1044 }
   1045 
   1046 /*
   1047  * Take incoming datagram fragment and try to
   1048  * reassemble it into whole datagram.  If a chain for
   1049  * reassembly of this datagram already exists, then it
   1050  * is given as fp; otherwise have to make a chain.
   1051  */
   1052 struct mbuf *
   1053 ip_reass(struct ipqent *ipqe, struct ipq *fp, struct ipqhead *ipqhead)
   1054 {
   1055 	struct mbuf *m = ipqe->ipqe_m;
   1056 	struct ipqent *nq, *p, *q;
   1057 	struct ip *ip;
   1058 	struct mbuf *t;
   1059 	int hlen = ipqe->ipqe_ip->ip_hl << 2;
   1060 	int i, next, s;
   1061 
   1062 	IPQ_LOCK_CHECK();
   1063 
   1064 	/*
   1065 	 * Presence of header sizes in mbufs
   1066 	 * would confuse code below.
   1067 	 */
   1068 	m->m_data += hlen;
   1069 	m->m_len -= hlen;
   1070 
   1071 #ifdef	notyet
   1072 	/* make sure fragment limit is up-to-date */
   1073 	CHECK_NMBCLUSTER_PARAMS();
   1074 
   1075 	/* If we have too many fragments, drop the older half. */
   1076 	if (ip_nfrags >= ip_maxfrags)
   1077 		ip_reass_drophalf(void);
   1078 #endif
   1079 
   1080 	/*
   1081 	 * We are about to add a fragment; increment frag count.
   1082 	 */
   1083 	ip_nfrags++;
   1084 
   1085 	/*
   1086 	 * If first fragment to arrive, create a reassembly queue.
   1087 	 */
   1088 	if (fp == 0) {
   1089 		/*
   1090 		 * Enforce upper bound on number of fragmented packets
   1091 		 * for which we attempt reassembly;
   1092 		 * If maxfrag is 0, never accept fragments.
   1093 		 * If maxfrag is -1, accept all fragments without limitation.
   1094 		 */
   1095 		if (ip_maxfragpackets < 0)
   1096 			;
   1097 		else if (ip_nfragpackets >= ip_maxfragpackets)
   1098 			goto dropfrag;
   1099 		ip_nfragpackets++;
   1100 		MALLOC(fp, struct ipq *, sizeof (struct ipq),
   1101 		    M_FTABLE, M_NOWAIT);
   1102 		if (fp == NULL)
   1103 			goto dropfrag;
   1104 		LIST_INSERT_HEAD(ipqhead, fp, ipq_q);
   1105 		fp->ipq_nfrags = 1;
   1106 		fp->ipq_ttl = IPFRAGTTL;
   1107 		fp->ipq_p = ipqe->ipqe_ip->ip_p;
   1108 		fp->ipq_id = ipqe->ipqe_ip->ip_id;
   1109 		TAILQ_INIT(&fp->ipq_fragq);
   1110 		fp->ipq_src = ipqe->ipqe_ip->ip_src;
   1111 		fp->ipq_dst = ipqe->ipqe_ip->ip_dst;
   1112 		p = NULL;
   1113 		goto insert;
   1114 	} else {
   1115 		fp->ipq_nfrags++;
   1116 	}
   1117 
   1118 	/*
   1119 	 * Find a segment which begins after this one does.
   1120 	 */
   1121 	for (p = NULL, q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL;
   1122 	    p = q, q = TAILQ_NEXT(q, ipqe_q))
   1123 		if (ntohs(q->ipqe_ip->ip_off) > ntohs(ipqe->ipqe_ip->ip_off))
   1124 			break;
   1125 
   1126 	/*
   1127 	 * If there is a preceding segment, it may provide some of
   1128 	 * our data already.  If so, drop the data from the incoming
   1129 	 * segment.  If it provides all of our data, drop us.
   1130 	 */
   1131 	if (p != NULL) {
   1132 		i = ntohs(p->ipqe_ip->ip_off) + ntohs(p->ipqe_ip->ip_len) -
   1133 		    ntohs(ipqe->ipqe_ip->ip_off);
   1134 		if (i > 0) {
   1135 			if (i >= ntohs(ipqe->ipqe_ip->ip_len))
   1136 				goto dropfrag;
   1137 			m_adj(ipqe->ipqe_m, i);
   1138 			ipqe->ipqe_ip->ip_off =
   1139 			    htons(ntohs(ipqe->ipqe_ip->ip_off) + i);
   1140 			ipqe->ipqe_ip->ip_len =
   1141 			    htons(ntohs(ipqe->ipqe_ip->ip_len) - i);
   1142 		}
   1143 	}
   1144 
   1145 	/*
   1146 	 * While we overlap succeeding segments trim them or,
   1147 	 * if they are completely covered, dequeue them.
   1148 	 */
   1149 	for (; q != NULL &&
   1150 	    ntohs(ipqe->ipqe_ip->ip_off) + ntohs(ipqe->ipqe_ip->ip_len) >
   1151 	    ntohs(q->ipqe_ip->ip_off); q = nq) {
   1152 		i = (ntohs(ipqe->ipqe_ip->ip_off) +
   1153 		    ntohs(ipqe->ipqe_ip->ip_len)) - ntohs(q->ipqe_ip->ip_off);
   1154 		if (i < ntohs(q->ipqe_ip->ip_len)) {
   1155 			q->ipqe_ip->ip_len =
   1156 			    htons(ntohs(q->ipqe_ip->ip_len) - i);
   1157 			q->ipqe_ip->ip_off =
   1158 			    htons(ntohs(q->ipqe_ip->ip_off) + i);
   1159 			m_adj(q->ipqe_m, i);
   1160 			break;
   1161 		}
   1162 		nq = TAILQ_NEXT(q, ipqe_q);
   1163 		m_freem(q->ipqe_m);
   1164 		TAILQ_REMOVE(&fp->ipq_fragq, q, ipqe_q);
   1165 		s = splvm();
   1166 		pool_put(&ipqent_pool, q);
   1167 		splx(s);
   1168 		fp->ipq_nfrags--;
   1169 		ip_nfrags--;
   1170 	}
   1171 
   1172 insert:
   1173 	/*
   1174 	 * Stick new segment in its place;
   1175 	 * check for complete reassembly.
   1176 	 */
   1177 	if (p == NULL) {
   1178 		TAILQ_INSERT_HEAD(&fp->ipq_fragq, ipqe, ipqe_q);
   1179 	} else {
   1180 		TAILQ_INSERT_AFTER(&fp->ipq_fragq, p, ipqe, ipqe_q);
   1181 	}
   1182 	next = 0;
   1183 	for (p = NULL, q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL;
   1184 	    p = q, q = TAILQ_NEXT(q, ipqe_q)) {
   1185 		if (ntohs(q->ipqe_ip->ip_off) != next)
   1186 			return (0);
   1187 		next += ntohs(q->ipqe_ip->ip_len);
   1188 	}
   1189 	if (p->ipqe_mff)
   1190 		return (0);
   1191 
   1192 	/*
   1193 	 * Reassembly is complete.  Check for a bogus message size and
   1194 	 * concatenate fragments.
   1195 	 */
   1196 	q = TAILQ_FIRST(&fp->ipq_fragq);
   1197 	ip = q->ipqe_ip;
   1198 	if ((next + (ip->ip_hl << 2)) > IP_MAXPACKET) {
   1199 		ipstat.ips_toolong++;
   1200 		ip_freef(fp);
   1201 		return (0);
   1202 	}
   1203 	m = q->ipqe_m;
   1204 	t = m->m_next;
   1205 	m->m_next = 0;
   1206 	m_cat(m, t);
   1207 	nq = TAILQ_NEXT(q, ipqe_q);
   1208 	s = splvm();
   1209 	pool_put(&ipqent_pool, q);
   1210 	splx(s);
   1211 	for (q = nq; q != NULL; q = nq) {
   1212 		t = q->ipqe_m;
   1213 		nq = TAILQ_NEXT(q, ipqe_q);
   1214 		s = splvm();
   1215 		pool_put(&ipqent_pool, q);
   1216 		splx(s);
   1217 		m_cat(m, t);
   1218 	}
   1219 	ip_nfrags -= fp->ipq_nfrags;
   1220 
   1221 	/*
   1222 	 * Create header for new ip packet by
   1223 	 * modifying header of first packet;
   1224 	 * dequeue and discard fragment reassembly header.
   1225 	 * Make header visible.
   1226 	 */
   1227 	ip->ip_len = htons(next);
   1228 	ip->ip_src = fp->ipq_src;
   1229 	ip->ip_dst = fp->ipq_dst;
   1230 	LIST_REMOVE(fp, ipq_q);
   1231 	FREE(fp, M_FTABLE);
   1232 	ip_nfragpackets--;
   1233 	m->m_len += (ip->ip_hl << 2);
   1234 	m->m_data -= (ip->ip_hl << 2);
   1235 	/* some debugging cruft by sklower, below, will go away soon */
   1236 	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
   1237 		int plen = 0;
   1238 		for (t = m; t; t = t->m_next)
   1239 			plen += t->m_len;
   1240 		m->m_pkthdr.len = plen;
   1241 		m->m_pkthdr.csum_flags = 0;
   1242 	}
   1243 	return (m);
   1244 
   1245 dropfrag:
   1246 	if (fp != 0)
   1247 		fp->ipq_nfrags--;
   1248 	ip_nfrags--;
   1249 	ipstat.ips_fragdropped++;
   1250 	m_freem(m);
   1251 	s = splvm();
   1252 	pool_put(&ipqent_pool, ipqe);
   1253 	splx(s);
   1254 	return (0);
   1255 }
   1256 
   1257 /*
   1258  * Free a fragment reassembly header and all
   1259  * associated datagrams.
   1260  */
   1261 void
   1262 ip_freef(struct ipq *fp)
   1263 {
   1264 	struct ipqent *q, *p;
   1265 	u_int nfrags = 0;
   1266 	int s;
   1267 
   1268 	IPQ_LOCK_CHECK();
   1269 
   1270 	for (q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL; q = p) {
   1271 		p = TAILQ_NEXT(q, ipqe_q);
   1272 		m_freem(q->ipqe_m);
   1273 		nfrags++;
   1274 		TAILQ_REMOVE(&fp->ipq_fragq, q, ipqe_q);
   1275 		s = splvm();
   1276 		pool_put(&ipqent_pool, q);
   1277 		splx(s);
   1278 	}
   1279 
   1280 	if (nfrags != fp->ipq_nfrags)
   1281 	    printf("ip_freef: nfrags %d != %d\n", fp->ipq_nfrags, nfrags);
   1282 	ip_nfrags -= nfrags;
   1283 	LIST_REMOVE(fp, ipq_q);
   1284 	FREE(fp, M_FTABLE);
   1285 	ip_nfragpackets--;
   1286 }
   1287 
   1288 /*
   1289  * IP reassembly TTL machinery for  multiplicative drop.
   1290  */
   1291 static u_int	fragttl_histo[(IPFRAGTTL+1)];
   1292 
   1293 
   1294 /*
   1295  * Decrement TTL of all reasembly queue entries by `ticks'.
   1296  * Count number of distinct fragments (as opposed to partial, fragmented
   1297  * datagrams) in the reassembly queue.  While we  traverse the entire
   1298  * reassembly queue, compute and return the median TTL over all fragments.
   1299  */
   1300 static u_int
   1301 ip_reass_ttl_decr(u_int ticks)
   1302 {
   1303 	u_int nfrags, median, dropfraction, keepfraction;
   1304 	struct ipq *fp, *nfp;
   1305 	int i;
   1306 
   1307 	nfrags = 0;
   1308 	memset(fragttl_histo, 0, sizeof fragttl_histo);
   1309 
   1310 	for (i = 0; i < IPREASS_NHASH; i++) {
   1311 		for (fp = LIST_FIRST(&ipq[i]); fp != NULL; fp = nfp) {
   1312 			fp->ipq_ttl = ((fp->ipq_ttl  <= ticks) ?
   1313 				       0 : fp->ipq_ttl - ticks);
   1314 			nfp = LIST_NEXT(fp, ipq_q);
   1315 			if (fp->ipq_ttl == 0) {
   1316 				ipstat.ips_fragtimeout++;
   1317 				ip_freef(fp);
   1318 			} else {
   1319 				nfrags += fp->ipq_nfrags;
   1320 				fragttl_histo[fp->ipq_ttl] += fp->ipq_nfrags;
   1321 			}
   1322 		}
   1323 	}
   1324 
   1325 	KASSERT(ip_nfrags == nfrags);
   1326 
   1327 	/* Find median (or other drop fraction) in histogram. */
   1328 	dropfraction = (ip_nfrags / 2);
   1329 	keepfraction = ip_nfrags - dropfraction;
   1330 	for (i = IPFRAGTTL, median = 0; i >= 0; i--) {
   1331 		median +=  fragttl_histo[i];
   1332 		if (median >= keepfraction)
   1333 			break;
   1334 	}
   1335 
   1336 	/* Return TTL of median (or other fraction). */
   1337 	return (u_int)i;
   1338 }
   1339 
   1340 void
   1341 ip_reass_drophalf(void)
   1342 {
   1343 
   1344 	u_int median_ticks;
   1345 	/*
   1346 	 * Compute median TTL of all fragments, and count frags
   1347 	 * with that TTL or lower (roughly half of all fragments).
   1348 	 */
   1349 	median_ticks = ip_reass_ttl_decr(0);
   1350 
   1351 	/* Drop half. */
   1352 	median_ticks = ip_reass_ttl_decr(median_ticks);
   1353 
   1354 }
   1355 
   1356 /*
   1357  * IP timer processing;
   1358  * if a timer expires on a reassembly
   1359  * queue, discard it.
   1360  */
   1361 void
   1362 ip_slowtimo(void)
   1363 {
   1364 	static u_int dropscanidx = 0;
   1365 	u_int i;
   1366 	u_int median_ttl;
   1367 	int s = splsoftnet();
   1368 
   1369 	IPQ_LOCK();
   1370 
   1371 	/* Age TTL of all fragments by 1 tick .*/
   1372 	median_ttl = ip_reass_ttl_decr(1);
   1373 
   1374 	/* make sure fragment limit is up-to-date */
   1375 	CHECK_NMBCLUSTER_PARAMS();
   1376 
   1377 	/* If we have too many fragments, drop the older half. */
   1378 	if (ip_nfrags > ip_maxfrags)
   1379 		ip_reass_ttl_decr(median_ttl);
   1380 
   1381 	/*
   1382 	 * If we are over the maximum number of fragmented packets
   1383 	 * (due to the limit being lowered), drain off
   1384 	 * enough to get down to the new limit. Start draining
   1385 	 * from the reassembly hashqueue most recently drained.
   1386 	 */
   1387 	if (ip_maxfragpackets < 0)
   1388 		;
   1389 	else {
   1390 		int wrapped = 0;
   1391 
   1392 		i = dropscanidx;
   1393 		while (ip_nfragpackets > ip_maxfragpackets && wrapped == 0) {
   1394 			while (LIST_FIRST(&ipq[i]) != NULL)
   1395 				ip_freef(LIST_FIRST(&ipq[i]));
   1396 			if (++i >= IPREASS_NHASH) {
   1397 				i = 0;
   1398 			}
   1399 			/*
   1400 			 * Dont scan forever even if fragment counters are
   1401 			 * wrong: stop after scanning entire reassembly queue.
   1402 			 */
   1403 			if (i == dropscanidx)
   1404 			    wrapped = 1;
   1405 		}
   1406 		dropscanidx = i;
   1407 	}
   1408 	IPQ_UNLOCK();
   1409 	splx(s);
   1410 }
   1411 
   1412 /*
   1413  * Drain off all datagram fragments.
   1414  */
   1415 void
   1416 ip_drain(void)
   1417 {
   1418 
   1419 	/*
   1420 	 * We may be called from a device's interrupt context.  If
   1421 	 * the ipq is already busy, just bail out now.
   1422 	 */
   1423 	if (ipq_lock_try() == 0)
   1424 		return;
   1425 
   1426 	/*
   1427 	 * Drop half the total fragments now. If more mbufs are needed,
   1428 	 *  we will be called again soon.
   1429 	 */
   1430 	ip_reass_drophalf();
   1431 
   1432 	IPQ_UNLOCK();
   1433 }
   1434 
   1435 /*
   1436  * Do option processing on a datagram,
   1437  * possibly discarding it if bad options are encountered,
   1438  * or forwarding it if source-routed.
   1439  * Returns 1 if packet has been forwarded/freed,
   1440  * 0 if the packet should be processed further.
   1441  */
   1442 int
   1443 ip_dooptions(struct mbuf *m)
   1444 {
   1445 	struct ip *ip = mtod(m, struct ip *);
   1446 	u_char *cp, *cp0;
   1447 	struct ip_timestamp *ipt;
   1448 	struct in_ifaddr *ia;
   1449 	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
   1450 	struct in_addr dst;
   1451 	n_time ntime;
   1452 
   1453 	dst = ip->ip_dst;
   1454 	cp = (u_char *)(ip + 1);
   1455 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
   1456 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1457 		opt = cp[IPOPT_OPTVAL];
   1458 		if (opt == IPOPT_EOL)
   1459 			break;
   1460 		if (opt == IPOPT_NOP)
   1461 			optlen = 1;
   1462 		else {
   1463 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
   1464 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1465 				goto bad;
   1466 			}
   1467 			optlen = cp[IPOPT_OLEN];
   1468 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
   1469 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1470 				goto bad;
   1471 			}
   1472 		}
   1473 		switch (opt) {
   1474 
   1475 		default:
   1476 			break;
   1477 
   1478 		/*
   1479 		 * Source routing with record.
   1480 		 * Find interface with current destination address.
   1481 		 * If none on this machine then drop if strictly routed,
   1482 		 * or do nothing if loosely routed.
   1483 		 * Record interface address and bring up next address
   1484 		 * component.  If strictly routed make sure next
   1485 		 * address is on directly accessible net.
   1486 		 */
   1487 		case IPOPT_LSRR:
   1488 		case IPOPT_SSRR:
   1489 			if (ip_allowsrcrt == 0) {
   1490 				type = ICMP_UNREACH;
   1491 				code = ICMP_UNREACH_NET_PROHIB;
   1492 				goto bad;
   1493 			}
   1494 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
   1495 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1496 				goto bad;
   1497 			}
   1498 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
   1499 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
   1500 				goto bad;
   1501 			}
   1502 			ipaddr.sin_addr = ip->ip_dst;
   1503 			ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
   1504 			if (ia == 0) {
   1505 				if (opt == IPOPT_SSRR) {
   1506 					type = ICMP_UNREACH;
   1507 					code = ICMP_UNREACH_SRCFAIL;
   1508 					goto bad;
   1509 				}
   1510 				/*
   1511 				 * Loose routing, and not at next destination
   1512 				 * yet; nothing to do except forward.
   1513 				 */
   1514 				break;
   1515 			}
   1516 			off--;			/* 0 origin */
   1517 			if ((off + sizeof(struct in_addr)) > optlen) {
   1518 				/*
   1519 				 * End of source route.  Should be for us.
   1520 				 */
   1521 				save_rte(cp, ip->ip_src);
   1522 				break;
   1523 			}
   1524 			/*
   1525 			 * locate outgoing interface
   1526 			 */
   1527 			bcopy((void *)(cp + off), (void *)&ipaddr.sin_addr,
   1528 			    sizeof(ipaddr.sin_addr));
   1529 			if (opt == IPOPT_SSRR)
   1530 				ia = ifatoia(ifa_ifwithladdr(sintosa(&ipaddr)));
   1531 			else
   1532 				ia = ip_rtaddr(ipaddr.sin_addr);
   1533 			if (ia == 0) {
   1534 				type = ICMP_UNREACH;
   1535 				code = ICMP_UNREACH_SRCFAIL;
   1536 				goto bad;
   1537 			}
   1538 			ip->ip_dst = ipaddr.sin_addr;
   1539 			bcopy((void *)&ia->ia_addr.sin_addr,
   1540 			    (void *)(cp + off), sizeof(struct in_addr));
   1541 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
   1542 			/*
   1543 			 * Let ip_intr's mcast routing check handle mcast pkts
   1544 			 */
   1545 			forward = !IN_MULTICAST(ip->ip_dst.s_addr);
   1546 			break;
   1547 
   1548 		case IPOPT_RR:
   1549 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
   1550 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1551 				goto bad;
   1552 			}
   1553 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
   1554 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
   1555 				goto bad;
   1556 			}
   1557 			/*
   1558 			 * If no space remains, ignore.
   1559 			 */
   1560 			off--;			/* 0 origin */
   1561 			if ((off + sizeof(struct in_addr)) > optlen)
   1562 				break;
   1563 			bcopy((void *)(&ip->ip_dst), (void *)&ipaddr.sin_addr,
   1564 			    sizeof(ipaddr.sin_addr));
   1565 			/*
   1566 			 * locate outgoing interface; if we're the destination,
   1567 			 * use the incoming interface (should be same).
   1568 			 */
   1569 			if ((ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr))))
   1570 			    == NULL &&
   1571 			    (ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
   1572 				type = ICMP_UNREACH;
   1573 				code = ICMP_UNREACH_HOST;
   1574 				goto bad;
   1575 			}
   1576 			bcopy((void *)&ia->ia_addr.sin_addr,
   1577 			    (void *)(cp + off), sizeof(struct in_addr));
   1578 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
   1579 			break;
   1580 
   1581 		case IPOPT_TS:
   1582 			code = cp - (u_char *)ip;
   1583 			ipt = (struct ip_timestamp *)cp;
   1584 			if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
   1585 				code = (u_char *)&ipt->ipt_len - (u_char *)ip;
   1586 				goto bad;
   1587 			}
   1588 			if (ipt->ipt_ptr < 5) {
   1589 				code = (u_char *)&ipt->ipt_ptr - (u_char *)ip;
   1590 				goto bad;
   1591 			}
   1592 			if (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {
   1593 				if (++ipt->ipt_oflw == 0) {
   1594 					code = (u_char *)&ipt->ipt_ptr -
   1595 					    (u_char *)ip;
   1596 					goto bad;
   1597 				}
   1598 				break;
   1599 			}
   1600 			cp0 = (cp + ipt->ipt_ptr - 1);
   1601 			switch (ipt->ipt_flg) {
   1602 
   1603 			case IPOPT_TS_TSONLY:
   1604 				break;
   1605 
   1606 			case IPOPT_TS_TSANDADDR:
   1607 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
   1608 				    sizeof(struct in_addr) > ipt->ipt_len) {
   1609 					code = (u_char *)&ipt->ipt_ptr -
   1610 					    (u_char *)ip;
   1611 					goto bad;
   1612 				}
   1613 				ipaddr.sin_addr = dst;
   1614 				ia = ifatoia(ifaof_ifpforaddr(sintosa(&ipaddr),
   1615 				    m->m_pkthdr.rcvif));
   1616 				if (ia == 0)
   1617 					continue;
   1618 				bcopy(&ia->ia_addr.sin_addr,
   1619 				    cp0, sizeof(struct in_addr));
   1620 				ipt->ipt_ptr += sizeof(struct in_addr);
   1621 				break;
   1622 
   1623 			case IPOPT_TS_PRESPEC:
   1624 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
   1625 				    sizeof(struct in_addr) > ipt->ipt_len) {
   1626 					code = (u_char *)&ipt->ipt_ptr -
   1627 					    (u_char *)ip;
   1628 					goto bad;
   1629 				}
   1630 				bcopy(cp0, &ipaddr.sin_addr,
   1631 				    sizeof(struct in_addr));
   1632 				if (ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)))
   1633 				    == NULL)
   1634 					continue;
   1635 				ipt->ipt_ptr += sizeof(struct in_addr);
   1636 				break;
   1637 
   1638 			default:
   1639 				/* XXX can't take &ipt->ipt_flg */
   1640 				code = (u_char *)&ipt->ipt_ptr -
   1641 				    (u_char *)ip + 1;
   1642 				goto bad;
   1643 			}
   1644 			ntime = iptime();
   1645 			cp0 = (u_char *) &ntime; /* XXX grumble, GCC... */
   1646 			memmove((char *)cp + ipt->ipt_ptr - 1, cp0,
   1647 			    sizeof(n_time));
   1648 			ipt->ipt_ptr += sizeof(n_time);
   1649 		}
   1650 	}
   1651 	if (forward) {
   1652 		if (ip_forwsrcrt == 0) {
   1653 			type = ICMP_UNREACH;
   1654 			code = ICMP_UNREACH_SRCFAIL;
   1655 			goto bad;
   1656 		}
   1657 		ip_forward(m, 1);
   1658 		return (1);
   1659 	}
   1660 	return (0);
   1661 bad:
   1662 	icmp_error(m, type, code, 0, 0);
   1663 	ipstat.ips_badoptions++;
   1664 	return (1);
   1665 }
   1666 
   1667 /*
   1668  * Given address of next destination (final or next hop),
   1669  * return internet address info of interface to be used to get there.
   1670  */
   1671 struct in_ifaddr *
   1672 ip_rtaddr(struct in_addr dst)
   1673 {
   1674 	struct rtentry *rt;
   1675 	union {
   1676 		struct sockaddr		dst;
   1677 		struct sockaddr_in	dst4;
   1678 	} u;
   1679 
   1680 	sockaddr_in_init(&u.dst4, &dst, 0);
   1681 
   1682 	if ((rt = rtcache_lookup(&ipforward_rt, &u.dst)) == NULL)
   1683 		return NULL;
   1684 
   1685 	return ifatoia(rt->rt_ifa);
   1686 }
   1687 
   1688 /*
   1689  * Save incoming source route for use in replies,
   1690  * to be picked up later by ip_srcroute if the receiver is interested.
   1691  */
   1692 void
   1693 save_rte(u_char *option, struct in_addr dst)
   1694 {
   1695 	unsigned olen;
   1696 
   1697 	olen = option[IPOPT_OLEN];
   1698 #ifdef DIAGNOSTIC
   1699 	if (ipprintfs)
   1700 		printf("save_rte: olen %d\n", olen);
   1701 #endif /* 0 */
   1702 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
   1703 		return;
   1704 	bcopy((void *)option, (void *)ip_srcrt.srcopt, olen);
   1705 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
   1706 	ip_srcrt.dst = dst;
   1707 }
   1708 
   1709 /*
   1710  * Retrieve incoming source route for use in replies,
   1711  * in the same form used by setsockopt.
   1712  * The first hop is placed before the options, will be removed later.
   1713  */
   1714 struct mbuf *
   1715 ip_srcroute(void)
   1716 {
   1717 	struct in_addr *p, *q;
   1718 	struct mbuf *m;
   1719 
   1720 	if (ip_nhops == 0)
   1721 		return NULL;
   1722 	m = m_get(M_DONTWAIT, MT_SOOPTS);
   1723 	if (m == 0)
   1724 		return NULL;
   1725 
   1726 	MCLAIM(m, &inetdomain.dom_mowner);
   1727 #define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
   1728 
   1729 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
   1730 	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
   1731 	    OPTSIZ;
   1732 #ifdef DIAGNOSTIC
   1733 	if (ipprintfs)
   1734 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
   1735 #endif
   1736 
   1737 	/*
   1738 	 * First save first hop for return route
   1739 	 */
   1740 	p = &ip_srcrt.route[ip_nhops - 1];
   1741 	*(mtod(m, struct in_addr *)) = *p--;
   1742 #ifdef DIAGNOSTIC
   1743 	if (ipprintfs)
   1744 		printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
   1745 #endif
   1746 
   1747 	/*
   1748 	 * Copy option fields and padding (nop) to mbuf.
   1749 	 */
   1750 	ip_srcrt.nop = IPOPT_NOP;
   1751 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
   1752 	memmove(mtod(m, char *) + sizeof(struct in_addr), &ip_srcrt.nop,
   1753 	    OPTSIZ);
   1754 	q = (struct in_addr *)(mtod(m, char *) +
   1755 	    sizeof(struct in_addr) + OPTSIZ);
   1756 #undef OPTSIZ
   1757 	/*
   1758 	 * Record return path as an IP source route,
   1759 	 * reversing the path (pointers are now aligned).
   1760 	 */
   1761 	while (p >= ip_srcrt.route) {
   1762 #ifdef DIAGNOSTIC
   1763 		if (ipprintfs)
   1764 			printf(" %x", ntohl(q->s_addr));
   1765 #endif
   1766 		*q++ = *p--;
   1767 	}
   1768 	/*
   1769 	 * Last hop goes to final destination.
   1770 	 */
   1771 	*q = ip_srcrt.dst;
   1772 #ifdef DIAGNOSTIC
   1773 	if (ipprintfs)
   1774 		printf(" %x\n", ntohl(q->s_addr));
   1775 #endif
   1776 	return (m);
   1777 }
   1778 
   1779 const int inetctlerrmap[PRC_NCMDS] = {
   1780 	0,		0,		0,		0,
   1781 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
   1782 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
   1783 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
   1784 	0,		0,		0,		0,
   1785 	ENOPROTOOPT
   1786 };
   1787 
   1788 /*
   1789  * Forward a packet.  If some error occurs return the sender
   1790  * an icmp packet.  Note we can't always generate a meaningful
   1791  * icmp message because icmp doesn't have a large enough repertoire
   1792  * of codes and types.
   1793  *
   1794  * If not forwarding, just drop the packet.  This could be confusing
   1795  * if ipforwarding was zero but some routing protocol was advancing
   1796  * us as a gateway to somewhere.  However, we must let the routing
   1797  * protocol deal with that.
   1798  *
   1799  * The srcrt parameter indicates whether the packet is being forwarded
   1800  * via a source route.
   1801  */
   1802 void
   1803 ip_forward(struct mbuf *m, int srcrt)
   1804 {
   1805 	struct ip *ip = mtod(m, struct ip *);
   1806 	struct rtentry *rt;
   1807 	int error, type = 0, code = 0, destmtu = 0;
   1808 	struct mbuf *mcopy;
   1809 	n_long dest;
   1810 	union {
   1811 		struct sockaddr		dst;
   1812 		struct sockaddr_in	dst4;
   1813 	} u;
   1814 
   1815 	/*
   1816 	 * We are now in the output path.
   1817 	 */
   1818 	MCLAIM(m, &ip_tx_mowner);
   1819 
   1820 	/*
   1821 	 * Clear any in-bound checksum flags for this packet.
   1822 	 */
   1823 	m->m_pkthdr.csum_flags = 0;
   1824 
   1825 	dest = 0;
   1826 #ifdef DIAGNOSTIC
   1827 	if (ipprintfs) {
   1828 		printf("forward: src %s ", inet_ntoa(ip->ip_src));
   1829 		printf("dst %s ttl %x\n", inet_ntoa(ip->ip_dst), ip->ip_ttl);
   1830 	}
   1831 #endif
   1832 	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
   1833 		ipstat.ips_cantforward++;
   1834 		m_freem(m);
   1835 		return;
   1836 	}
   1837 	if (ip->ip_ttl <= IPTTLDEC) {
   1838 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
   1839 		return;
   1840 	}
   1841 
   1842 	sockaddr_in_init(&u.dst4, &ip->ip_dst, 0);
   1843 	if ((rt = rtcache_lookup(&ipforward_rt, &u.dst)) == NULL) {
   1844 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NET, dest, 0);
   1845 		return;
   1846 	}
   1847 
   1848 	/*
   1849 	 * Save at most 68 bytes of the packet in case
   1850 	 * we need to generate an ICMP message to the src.
   1851 	 * Pullup to avoid sharing mbuf cluster between m and mcopy.
   1852 	 */
   1853 	mcopy = m_copym(m, 0, imin(ntohs(ip->ip_len), 68), M_DONTWAIT);
   1854 	if (mcopy)
   1855 		mcopy = m_pullup(mcopy, ip->ip_hl << 2);
   1856 
   1857 	ip->ip_ttl -= IPTTLDEC;
   1858 
   1859 	/*
   1860 	 * If forwarding packet using same interface that it came in on,
   1861 	 * perhaps should send a redirect to sender to shortcut a hop.
   1862 	 * Only send redirect if source is sending directly to us,
   1863 	 * and if packet was not source routed (or has any options).
   1864 	 * Also, don't send redirect if forwarding using a default route
   1865 	 * or a route modified by a redirect.
   1866 	 */
   1867 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
   1868 	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
   1869 	    !in_nullhost(satocsin(rt_getkey(rt))->sin_addr) &&
   1870 	    ipsendredirects && !srcrt) {
   1871 		if (rt->rt_ifa &&
   1872 		    (ip->ip_src.s_addr & ifatoia(rt->rt_ifa)->ia_subnetmask) ==
   1873 		    ifatoia(rt->rt_ifa)->ia_subnet) {
   1874 			if (rt->rt_flags & RTF_GATEWAY)
   1875 				dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
   1876 			else
   1877 				dest = ip->ip_dst.s_addr;
   1878 			/*
   1879 			 * Router requirements says to only send host
   1880 			 * redirects.
   1881 			 */
   1882 			type = ICMP_REDIRECT;
   1883 			code = ICMP_REDIRECT_HOST;
   1884 #ifdef DIAGNOSTIC
   1885 			if (ipprintfs)
   1886 				printf("redirect (%d) to %x\n", code,
   1887 				    (u_int32_t)dest);
   1888 #endif
   1889 		}
   1890 	}
   1891 
   1892 	error = ip_output(m, NULL, &ipforward_rt,
   1893 	    (IP_FORWARDING | (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
   1894 	    (struct ip_moptions *)NULL, (struct socket *)NULL);
   1895 
   1896 	if (error)
   1897 		ipstat.ips_cantforward++;
   1898 	else {
   1899 		ipstat.ips_forward++;
   1900 		if (type)
   1901 			ipstat.ips_redirectsent++;
   1902 		else {
   1903 			if (mcopy) {
   1904 #ifdef GATEWAY
   1905 				if (mcopy->m_flags & M_CANFASTFWD)
   1906 					ipflow_create(&ipforward_rt, mcopy);
   1907 #endif
   1908 				m_freem(mcopy);
   1909 			}
   1910 			return;
   1911 		}
   1912 	}
   1913 	if (mcopy == NULL)
   1914 		return;
   1915 
   1916 	switch (error) {
   1917 
   1918 	case 0:				/* forwarded, but need redirect */
   1919 		/* type, code set above */
   1920 		break;
   1921 
   1922 	case ENETUNREACH:		/* shouldn't happen, checked above */
   1923 	case EHOSTUNREACH:
   1924 	case ENETDOWN:
   1925 	case EHOSTDOWN:
   1926 	default:
   1927 		type = ICMP_UNREACH;
   1928 		code = ICMP_UNREACH_HOST;
   1929 		break;
   1930 
   1931 	case EMSGSIZE:
   1932 		type = ICMP_UNREACH;
   1933 		code = ICMP_UNREACH_NEEDFRAG;
   1934 #if !defined(IPSEC) && !defined(FAST_IPSEC)
   1935 		if (ipforward_rt.ro_rt != NULL)
   1936 			destmtu = ipforward_rt.ro_rt->rt_ifp->if_mtu;
   1937 #else
   1938 		/*
   1939 		 * If the packet is routed over IPsec tunnel, tell the
   1940 		 * originator the tunnel MTU.
   1941 		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
   1942 		 * XXX quickhack!!!
   1943 		 */
   1944 		if (ipforward_rt.ro_rt != NULL) {
   1945 			struct secpolicy *sp;
   1946 			int ipsecerror;
   1947 			size_t ipsechdr;
   1948 			struct route *ro;
   1949 
   1950 			sp = ipsec4_getpolicybyaddr(mcopy,
   1951 			    IPSEC_DIR_OUTBOUND, IP_FORWARDING,
   1952 			    &ipsecerror);
   1953 
   1954 			if (sp == NULL)
   1955 				destmtu = ipforward_rt.ro_rt->rt_ifp->if_mtu;
   1956 			else {
   1957 				/* count IPsec header size */
   1958 				ipsechdr = ipsec4_hdrsiz(mcopy,
   1959 				    IPSEC_DIR_OUTBOUND, NULL);
   1960 
   1961 				/*
   1962 				 * find the correct route for outer IPv4
   1963 				 * header, compute tunnel MTU.
   1964 				 */
   1965 
   1966 				if (sp->req != NULL
   1967 				 && sp->req->sav != NULL
   1968 				 && sp->req->sav->sah != NULL) {
   1969 					ro = &sp->req->sav->sah->sa_route;
   1970 					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
   1971 						destmtu =
   1972 						    ro->ro_rt->rt_rmx.rmx_mtu ?
   1973 						    ro->ro_rt->rt_rmx.rmx_mtu :
   1974 						    ro->ro_rt->rt_ifp->if_mtu;
   1975 						destmtu -= ipsechdr;
   1976 					}
   1977 				}
   1978 
   1979 #ifdef	IPSEC
   1980 				key_freesp(sp);
   1981 #else
   1982 				KEY_FREESP(&sp);
   1983 #endif
   1984 			}
   1985 		}
   1986 #endif /*IPSEC*/
   1987 		ipstat.ips_cantfrag++;
   1988 		break;
   1989 
   1990 	case ENOBUFS:
   1991 #if 1
   1992 		/*
   1993 		 * a router should not generate ICMP_SOURCEQUENCH as
   1994 		 * required in RFC1812 Requirements for IP Version 4 Routers.
   1995 		 * source quench could be a big problem under DoS attacks,
   1996 		 * or if the underlying interface is rate-limited.
   1997 		 */
   1998 		if (mcopy)
   1999 			m_freem(mcopy);
   2000 		return;
   2001 #else
   2002 		type = ICMP_SOURCEQUENCH;
   2003 		code = 0;
   2004 		break;
   2005 #endif
   2006 	}
   2007 	icmp_error(mcopy, type, code, dest, destmtu);
   2008 }
   2009 
   2010 void
   2011 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
   2012     struct mbuf *m)
   2013 {
   2014 
   2015 	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
   2016 		struct timeval tv;
   2017 
   2018 		microtime(&tv);
   2019 		*mp = sbcreatecontrol((void *) &tv, sizeof(tv),
   2020 		    SCM_TIMESTAMP, SOL_SOCKET);
   2021 		if (*mp)
   2022 			mp = &(*mp)->m_next;
   2023 	}
   2024 	if (inp->inp_flags & INP_RECVDSTADDR) {
   2025 		*mp = sbcreatecontrol((void *) &ip->ip_dst,
   2026 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
   2027 		if (*mp)
   2028 			mp = &(*mp)->m_next;
   2029 	}
   2030 #ifdef notyet
   2031 	/*
   2032 	 * XXX
   2033 	 * Moving these out of udp_input() made them even more broken
   2034 	 * than they already were.
   2035 	 *	- fenner (at) parc.xerox.com
   2036 	 */
   2037 	/* options were tossed already */
   2038 	if (inp->inp_flags & INP_RECVOPTS) {
   2039 		*mp = sbcreatecontrol((void *) opts_deleted_above,
   2040 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
   2041 		if (*mp)
   2042 			mp = &(*mp)->m_next;
   2043 	}
   2044 	/* ip_srcroute doesn't do what we want here, need to fix */
   2045 	if (inp->inp_flags & INP_RECVRETOPTS) {
   2046 		*mp = sbcreatecontrol((void *) ip_srcroute(),
   2047 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
   2048 		if (*mp)
   2049 			mp = &(*mp)->m_next;
   2050 	}
   2051 #endif
   2052 	if (inp->inp_flags & INP_RECVIF) {
   2053 		struct sockaddr_dl sdl;
   2054 
   2055 		sockaddr_dl_init(&sdl, sizeof(sdl),
   2056 		    (m->m_pkthdr.rcvif != NULL)
   2057 		        ?  m->m_pkthdr.rcvif->if_index
   2058 			: 0,
   2059 			0, NULL, 0, NULL, 0);
   2060 		*mp = sbcreatecontrol(&sdl, sdl.sdl_len, IP_RECVIF, IPPROTO_IP);
   2061 		if (*mp)
   2062 			mp = &(*mp)->m_next;
   2063 	}
   2064 }
   2065 
   2066 /*
   2067  * sysctl helper routine for net.inet.ip.forwsrcrt.
   2068  */
   2069 static int
   2070 sysctl_net_inet_ip_forwsrcrt(SYSCTLFN_ARGS)
   2071 {
   2072 	int error, tmp;
   2073 	struct sysctlnode node;
   2074 
   2075 	node = *rnode;
   2076 	tmp = ip_forwsrcrt;
   2077 	node.sysctl_data = &tmp;
   2078 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2079 	if (error || newp == NULL)
   2080 		return (error);
   2081 
   2082 	if (kauth_authorize_network(l->l_cred, KAUTH_NETWORK_FORWSRCRT,
   2083 	    0, NULL, NULL, NULL))
   2084 		return (EPERM);
   2085 
   2086 	ip_forwsrcrt = tmp;
   2087 
   2088 	return (0);
   2089 }
   2090 
   2091 /*
   2092  * sysctl helper routine for net.inet.ip.mtudisctimeout.  checks the
   2093  * range of the new value and tweaks timers if it changes.
   2094  */
   2095 static int
   2096 sysctl_net_inet_ip_pmtudto(SYSCTLFN_ARGS)
   2097 {
   2098 	int error, tmp;
   2099 	struct sysctlnode node;
   2100 
   2101 	node = *rnode;
   2102 	tmp = ip_mtudisc_timeout;
   2103 	node.sysctl_data = &tmp;
   2104 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2105 	if (error || newp == NULL)
   2106 		return (error);
   2107 	if (tmp < 0)
   2108 		return (EINVAL);
   2109 
   2110 	ip_mtudisc_timeout = tmp;
   2111 	rt_timer_queue_change(ip_mtudisc_timeout_q, ip_mtudisc_timeout);
   2112 
   2113 	return (0);
   2114 }
   2115 
   2116 #ifdef GATEWAY
   2117 /*
   2118  * sysctl helper routine for net.inet.ip.maxflows.
   2119  */
   2120 static int
   2121 sysctl_net_inet_ip_maxflows(SYSCTLFN_ARGS)
   2122 {
   2123 	int s;
   2124 
   2125 	s = sysctl_lookup(SYSCTLFN_CALL(rnode));
   2126 	if (s || newp == NULL)
   2127 		return (s);
   2128 
   2129 	s = splsoftnet();
   2130 	ipflow_reap(0);
   2131 	splx(s);
   2132 
   2133 	return (0);
   2134 }
   2135 
   2136 static int
   2137 sysctl_net_inet_ip_hashsize(SYSCTLFN_ARGS)
   2138 {
   2139 	int error, tmp;
   2140 	struct sysctlnode node;
   2141 
   2142 	node = *rnode;
   2143 	tmp = ip_hashsize;
   2144 	node.sysctl_data = &tmp;
   2145 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2146 	if (error || newp == NULL)
   2147 		return (error);
   2148 
   2149 	if ((tmp & (tmp - 1)) == 0 && tmp != 0) {
   2150 		/*
   2151 		 * Can only fail due to malloc()
   2152 		 */
   2153 		if (ipflow_invalidate_all(tmp))
   2154 			return ENOMEM;
   2155 	} else {
   2156 		/*
   2157 		 * EINVAL if not a power of 2
   2158 	         */
   2159 		return EINVAL;
   2160 	}
   2161 
   2162 	return (0);
   2163 }
   2164 #endif /* GATEWAY */
   2165 
   2166 
   2167 SYSCTL_SETUP(sysctl_net_inet_ip_setup, "sysctl net.inet.ip subtree setup")
   2168 {
   2169 	extern int subnetsarelocal, hostzeroisbroadcast;
   2170 
   2171 	sysctl_createv(clog, 0, NULL, NULL,
   2172 		       CTLFLAG_PERMANENT,
   2173 		       CTLTYPE_NODE, "net", NULL,
   2174 		       NULL, 0, NULL, 0,
   2175 		       CTL_NET, CTL_EOL);
   2176 	sysctl_createv(clog, 0, NULL, NULL,
   2177 		       CTLFLAG_PERMANENT,
   2178 		       CTLTYPE_NODE, "inet",
   2179 		       SYSCTL_DESCR("PF_INET related settings"),
   2180 		       NULL, 0, NULL, 0,
   2181 		       CTL_NET, PF_INET, CTL_EOL);
   2182 	sysctl_createv(clog, 0, NULL, NULL,
   2183 		       CTLFLAG_PERMANENT,
   2184 		       CTLTYPE_NODE, "ip",
   2185 		       SYSCTL_DESCR("IPv4 related settings"),
   2186 		       NULL, 0, NULL, 0,
   2187 		       CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
   2188 
   2189 	sysctl_createv(clog, 0, NULL, NULL,
   2190 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2191 		       CTLTYPE_INT, "forwarding",
   2192 		       SYSCTL_DESCR("Enable forwarding of INET datagrams"),
   2193 		       NULL, 0, &ipforwarding, 0,
   2194 		       CTL_NET, PF_INET, IPPROTO_IP,
   2195 		       IPCTL_FORWARDING, CTL_EOL);
   2196 	sysctl_createv(clog, 0, NULL, NULL,
   2197 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2198 		       CTLTYPE_INT, "redirect",
   2199 		       SYSCTL_DESCR("Enable sending of ICMP redirect messages"),
   2200 		       NULL, 0, &ipsendredirects, 0,
   2201 		       CTL_NET, PF_INET, IPPROTO_IP,
   2202 		       IPCTL_SENDREDIRECTS, CTL_EOL);
   2203 	sysctl_createv(clog, 0, NULL, NULL,
   2204 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2205 		       CTLTYPE_INT, "ttl",
   2206 		       SYSCTL_DESCR("Default TTL for an INET datagram"),
   2207 		       NULL, 0, &ip_defttl, 0,
   2208 		       CTL_NET, PF_INET, IPPROTO_IP,
   2209 		       IPCTL_DEFTTL, CTL_EOL);
   2210 #ifdef IPCTL_DEFMTU
   2211 	sysctl_createv(clog, 0, NULL, NULL,
   2212 		       CTLFLAG_PERMANENT /* |CTLFLAG_READWRITE? */,
   2213 		       CTLTYPE_INT, "mtu",
   2214 		       SYSCTL_DESCR("Default MTA for an INET route"),
   2215 		       NULL, 0, &ip_mtu, 0,
   2216 		       CTL_NET, PF_INET, IPPROTO_IP,
   2217 		       IPCTL_DEFMTU, CTL_EOL);
   2218 #endif /* IPCTL_DEFMTU */
   2219 	sysctl_createv(clog, 0, NULL, NULL,
   2220 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2221 		       CTLTYPE_INT, "forwsrcrt",
   2222 		       SYSCTL_DESCR("Enable forwarding of source-routed "
   2223 				    "datagrams"),
   2224 		       sysctl_net_inet_ip_forwsrcrt, 0, &ip_forwsrcrt, 0,
   2225 		       CTL_NET, PF_INET, IPPROTO_IP,
   2226 		       IPCTL_FORWSRCRT, CTL_EOL);
   2227 	sysctl_createv(clog, 0, NULL, NULL,
   2228 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2229 		       CTLTYPE_INT, "directed-broadcast",
   2230 		       SYSCTL_DESCR("Enable forwarding of broadcast datagrams"),
   2231 		       NULL, 0, &ip_directedbcast, 0,
   2232 		       CTL_NET, PF_INET, IPPROTO_IP,
   2233 		       IPCTL_DIRECTEDBCAST, CTL_EOL);
   2234 	sysctl_createv(clog, 0, NULL, NULL,
   2235 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2236 		       CTLTYPE_INT, "allowsrcrt",
   2237 		       SYSCTL_DESCR("Accept source-routed datagrams"),
   2238 		       NULL, 0, &ip_allowsrcrt, 0,
   2239 		       CTL_NET, PF_INET, IPPROTO_IP,
   2240 		       IPCTL_ALLOWSRCRT, CTL_EOL);
   2241 	sysctl_createv(clog, 0, NULL, NULL,
   2242 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2243 		       CTLTYPE_INT, "subnetsarelocal",
   2244 		       SYSCTL_DESCR("Whether logical subnets are considered "
   2245 				    "local"),
   2246 		       NULL, 0, &subnetsarelocal, 0,
   2247 		       CTL_NET, PF_INET, IPPROTO_IP,
   2248 		       IPCTL_SUBNETSARELOCAL, CTL_EOL);
   2249 	sysctl_createv(clog, 0, NULL, NULL,
   2250 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2251 		       CTLTYPE_INT, "mtudisc",
   2252 		       SYSCTL_DESCR("Use RFC1191 Path MTU Discovery"),
   2253 		       NULL, 0, &ip_mtudisc, 0,
   2254 		       CTL_NET, PF_INET, IPPROTO_IP,
   2255 		       IPCTL_MTUDISC, CTL_EOL);
   2256 	sysctl_createv(clog, 0, NULL, NULL,
   2257 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2258 		       CTLTYPE_INT, "anonportmin",
   2259 		       SYSCTL_DESCR("Lowest ephemeral port number to assign"),
   2260 		       sysctl_net_inet_ip_ports, 0, &anonportmin, 0,
   2261 		       CTL_NET, PF_INET, IPPROTO_IP,
   2262 		       IPCTL_ANONPORTMIN, CTL_EOL);
   2263 	sysctl_createv(clog, 0, NULL, NULL,
   2264 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2265 		       CTLTYPE_INT, "anonportmax",
   2266 		       SYSCTL_DESCR("Highest ephemeral port number to assign"),
   2267 		       sysctl_net_inet_ip_ports, 0, &anonportmax, 0,
   2268 		       CTL_NET, PF_INET, IPPROTO_IP,
   2269 		       IPCTL_ANONPORTMAX, CTL_EOL);
   2270 	sysctl_createv(clog, 0, NULL, NULL,
   2271 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2272 		       CTLTYPE_INT, "mtudisctimeout",
   2273 		       SYSCTL_DESCR("Lifetime of a Path MTU Discovered route"),
   2274 		       sysctl_net_inet_ip_pmtudto, 0, &ip_mtudisc_timeout, 0,
   2275 		       CTL_NET, PF_INET, IPPROTO_IP,
   2276 		       IPCTL_MTUDISCTIMEOUT, CTL_EOL);
   2277 #ifdef GATEWAY
   2278 	sysctl_createv(clog, 0, NULL, NULL,
   2279 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2280 		       CTLTYPE_INT, "maxflows",
   2281 		       SYSCTL_DESCR("Number of flows for fast forwarding"),
   2282 		       sysctl_net_inet_ip_maxflows, 0, &ip_maxflows, 0,
   2283 		       CTL_NET, PF_INET, IPPROTO_IP,
   2284 		       IPCTL_MAXFLOWS, CTL_EOL);
   2285 	sysctl_createv(clog, 0, NULL, NULL,
   2286 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2287 			CTLTYPE_INT, "hashsize",
   2288 			SYSCTL_DESCR("Size of hash table for fast forwarding (IPv4)"),
   2289 			sysctl_net_inet_ip_hashsize, 0, &ip_hashsize, 0,
   2290 			CTL_NET, PF_INET, IPPROTO_IP,
   2291 			CTL_CREATE, CTL_EOL);
   2292 #endif /* GATEWAY */
   2293 	sysctl_createv(clog, 0, NULL, NULL,
   2294 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2295 		       CTLTYPE_INT, "hostzerobroadcast",
   2296 		       SYSCTL_DESCR("All zeroes address is broadcast address"),
   2297 		       NULL, 0, &hostzeroisbroadcast, 0,
   2298 		       CTL_NET, PF_INET, IPPROTO_IP,
   2299 		       IPCTL_HOSTZEROBROADCAST, CTL_EOL);
   2300 #if NGIF > 0
   2301 	sysctl_createv(clog, 0, NULL, NULL,
   2302 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2303 		       CTLTYPE_INT, "gifttl",
   2304 		       SYSCTL_DESCR("Default TTL for a gif tunnel datagram"),
   2305 		       NULL, 0, &ip_gif_ttl, 0,
   2306 		       CTL_NET, PF_INET, IPPROTO_IP,
   2307 		       IPCTL_GIF_TTL, CTL_EOL);
   2308 #endif /* NGIF */
   2309 #ifndef IPNOPRIVPORTS
   2310 	sysctl_createv(clog, 0, NULL, NULL,
   2311 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2312 		       CTLTYPE_INT, "lowportmin",
   2313 		       SYSCTL_DESCR("Lowest privileged ephemeral port number "
   2314 				    "to assign"),
   2315 		       sysctl_net_inet_ip_ports, 0, &lowportmin, 0,
   2316 		       CTL_NET, PF_INET, IPPROTO_IP,
   2317 		       IPCTL_LOWPORTMIN, CTL_EOL);
   2318 	sysctl_createv(clog, 0, NULL, NULL,
   2319 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2320 		       CTLTYPE_INT, "lowportmax",
   2321 		       SYSCTL_DESCR("Highest privileged ephemeral port number "
   2322 				    "to assign"),
   2323 		       sysctl_net_inet_ip_ports, 0, &lowportmax, 0,
   2324 		       CTL_NET, PF_INET, IPPROTO_IP,
   2325 		       IPCTL_LOWPORTMAX, CTL_EOL);
   2326 #endif /* IPNOPRIVPORTS */
   2327 	sysctl_createv(clog, 0, NULL, NULL,
   2328 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2329 		       CTLTYPE_INT, "maxfragpackets",
   2330 		       SYSCTL_DESCR("Maximum number of fragments to retain for "
   2331 				    "possible reassembly"),
   2332 		       NULL, 0, &ip_maxfragpackets, 0,
   2333 		       CTL_NET, PF_INET, IPPROTO_IP,
   2334 		       IPCTL_MAXFRAGPACKETS, CTL_EOL);
   2335 #if NGRE > 0
   2336 	sysctl_createv(clog, 0, NULL, NULL,
   2337 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2338 		       CTLTYPE_INT, "grettl",
   2339 		       SYSCTL_DESCR("Default TTL for a gre tunnel datagram"),
   2340 		       NULL, 0, &ip_gre_ttl, 0,
   2341 		       CTL_NET, PF_INET, IPPROTO_IP,
   2342 		       IPCTL_GRE_TTL, CTL_EOL);
   2343 #endif /* NGRE */
   2344 	sysctl_createv(clog, 0, NULL, NULL,
   2345 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2346 		       CTLTYPE_INT, "checkinterface",
   2347 		       SYSCTL_DESCR("Enable receive side of Strong ES model "
   2348 				    "from RFC1122"),
   2349 		       NULL, 0, &ip_checkinterface, 0,
   2350 		       CTL_NET, PF_INET, IPPROTO_IP,
   2351 		       IPCTL_CHECKINTERFACE, CTL_EOL);
   2352 	sysctl_createv(clog, 0, NULL, NULL,
   2353 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2354 		       CTLTYPE_INT, "random_id",
   2355 		       SYSCTL_DESCR("Assign random ip_id values"),
   2356 		       NULL, 0, &ip_do_randomid, 0,
   2357 		       CTL_NET, PF_INET, IPPROTO_IP,
   2358 		       IPCTL_RANDOMID, CTL_EOL);
   2359 	sysctl_createv(clog, 0, NULL, NULL,
   2360 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2361 		       CTLTYPE_INT, "do_loopback_cksum",
   2362 		       SYSCTL_DESCR("Perform IP checksum on loopback"),
   2363 		       NULL, 0, &ip_do_loopback_cksum, 0,
   2364 		       CTL_NET, PF_INET, IPPROTO_IP,
   2365 		       IPCTL_LOOPBACKCKSUM, CTL_EOL);
   2366 	sysctl_createv(clog, 0, NULL, NULL,
   2367 		       CTLFLAG_PERMANENT,
   2368 		       CTLTYPE_STRUCT, "stats",
   2369 		       SYSCTL_DESCR("IP statistics"),
   2370 		       NULL, 0, &ipstat, sizeof(ipstat),
   2371 		       CTL_NET, PF_INET, IPPROTO_IP, IPCTL_STATS,
   2372 		       CTL_EOL);
   2373 }
   2374