Home | History | Annotate | Line # | Download | only in netinet
ip_input.c revision 1.261
      1 /*	$NetBSD: ip_input.c,v 1.261 2008/01/14 04:19:09 dyoung 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.261 2008/01/14 04:19:09 dyoung 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 		ip_input(m);
    473 	}
    474 }
    475 
    476 /*
    477  * Ip input routine.  Checksum and byte swap header.  If fragmented
    478  * try to reassemble.  Process options.  Pass to next level.
    479  */
    480 void
    481 ip_input(struct mbuf *m)
    482 {
    483 	struct ip *ip = NULL;
    484 	struct ipq *fp;
    485 	struct in_ifaddr *ia;
    486 	struct ifaddr *ifa;
    487 	struct ipqent *ipqe;
    488 	int hlen = 0, mff, len;
    489 	int downmatch;
    490 	int checkif;
    491 	int srcrt = 0;
    492 	int s;
    493 	u_int hash;
    494 #ifdef FAST_IPSEC
    495 	struct m_tag *mtag;
    496 	struct tdb_ident *tdbi;
    497 	struct secpolicy *sp;
    498 	int error;
    499 #endif /* FAST_IPSEC */
    500 
    501 	MCLAIM(m, &ip_rx_mowner);
    502 #ifdef	DIAGNOSTIC
    503 	if ((m->m_flags & M_PKTHDR) == 0)
    504 		panic("ipintr no HDR");
    505 #endif
    506 
    507 	/*
    508 	 * If no IP addresses have been set yet but the interfaces
    509 	 * are receiving, can't do anything with incoming packets yet.
    510 	 */
    511 	if (TAILQ_FIRST(&in_ifaddrhead) == 0)
    512 		goto bad;
    513 	ipstat.ips_total++;
    514 	/*
    515 	 * If the IP header is not aligned, slurp it up into a new
    516 	 * mbuf with space for link headers, in the event we forward
    517 	 * it.  Otherwise, if it is aligned, make sure the entire
    518 	 * base IP header is in the first mbuf of the chain.
    519 	 */
    520 	if (IP_HDR_ALIGNED_P(mtod(m, void *)) == 0) {
    521 		if ((m = m_copyup(m, sizeof(struct ip),
    522 				  (max_linkhdr + 3) & ~3)) == NULL) {
    523 			/* XXXJRT new stat, please */
    524 			ipstat.ips_toosmall++;
    525 			return;
    526 		}
    527 	} else if (__predict_false(m->m_len < sizeof (struct ip))) {
    528 		if ((m = m_pullup(m, sizeof (struct ip))) == NULL) {
    529 			ipstat.ips_toosmall++;
    530 			return;
    531 		}
    532 	}
    533 	ip = mtod(m, struct ip *);
    534 	if (ip->ip_v != IPVERSION) {
    535 		ipstat.ips_badvers++;
    536 		goto bad;
    537 	}
    538 	hlen = ip->ip_hl << 2;
    539 	if (hlen < sizeof(struct ip)) {	/* minimum header length */
    540 		ipstat.ips_badhlen++;
    541 		goto bad;
    542 	}
    543 	if (hlen > m->m_len) {
    544 		if ((m = m_pullup(m, hlen)) == 0) {
    545 			ipstat.ips_badhlen++;
    546 			return;
    547 		}
    548 		ip = mtod(m, struct ip *);
    549 	}
    550 
    551 	/*
    552 	 * RFC1122: packets with a multicast source address are
    553 	 * not allowed.
    554 	 */
    555 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
    556 		ipstat.ips_badaddr++;
    557 		goto bad;
    558 	}
    559 
    560 	/* 127/8 must not appear on wire - RFC1122 */
    561 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
    562 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
    563 		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
    564 			ipstat.ips_badaddr++;
    565 			goto bad;
    566 		}
    567 	}
    568 
    569 	switch (m->m_pkthdr.csum_flags &
    570 		((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_IPv4) |
    571 		 M_CSUM_IPv4_BAD)) {
    572 	case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
    573 		INET_CSUM_COUNTER_INCR(&ip_hwcsum_bad);
    574 		goto badcsum;
    575 
    576 	case M_CSUM_IPv4:
    577 		/* Checksum was okay. */
    578 		INET_CSUM_COUNTER_INCR(&ip_hwcsum_ok);
    579 		break;
    580 
    581 	default:
    582 		/*
    583 		 * Must compute it ourselves.  Maybe skip checksum on
    584 		 * loopback interfaces.
    585 		 */
    586 		if (__predict_true(!(m->m_pkthdr.rcvif->if_flags &
    587 				     IFF_LOOPBACK) || ip_do_loopback_cksum)) {
    588 			INET_CSUM_COUNTER_INCR(&ip_swcsum);
    589 			if (in_cksum(m, hlen) != 0)
    590 				goto badcsum;
    591 		}
    592 		break;
    593 	}
    594 
    595 	/* Retrieve the packet length. */
    596 	len = ntohs(ip->ip_len);
    597 
    598 	/*
    599 	 * Check for additional length bogosity
    600 	 */
    601 	if (len < hlen) {
    602 	 	ipstat.ips_badlen++;
    603 		goto bad;
    604 	}
    605 
    606 	/*
    607 	 * Check that the amount of data in the buffers
    608 	 * is as at least much as the IP header would have us expect.
    609 	 * Trim mbufs if longer than we expect.
    610 	 * Drop packet if shorter than we expect.
    611 	 */
    612 	if (m->m_pkthdr.len < len) {
    613 		ipstat.ips_tooshort++;
    614 		goto bad;
    615 	}
    616 	if (m->m_pkthdr.len > len) {
    617 		if (m->m_len == m->m_pkthdr.len) {
    618 			m->m_len = len;
    619 			m->m_pkthdr.len = len;
    620 		} else
    621 			m_adj(m, len - m->m_pkthdr.len);
    622 	}
    623 
    624 #if defined(IPSEC)
    625 	/* ipflow (IP fast forwarding) is not compatible with IPsec. */
    626 	m->m_flags &= ~M_CANFASTFWD;
    627 #else
    628 	/*
    629 	 * Assume that we can create a fast-forward IP flow entry
    630 	 * based on this packet.
    631 	 */
    632 	m->m_flags |= M_CANFASTFWD;
    633 #endif
    634 
    635 #ifdef PFIL_HOOKS
    636 	/*
    637 	 * Run through list of hooks for input packets.  If there are any
    638 	 * filters which require that additional packets in the flow are
    639 	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
    640 	 * Note that filters must _never_ set this flag, as another filter
    641 	 * in the list may have previously cleared it.
    642 	 */
    643 	/*
    644 	 * let ipfilter look at packet on the wire,
    645 	 * not the decapsulated packet.
    646 	 */
    647 #ifdef IPSEC
    648 	if (!ipsec_getnhist(m))
    649 #elif defined(FAST_IPSEC)
    650 	if (!ipsec_indone(m))
    651 #else
    652 	if (1)
    653 #endif
    654 	{
    655 		struct in_addr odst;
    656 
    657 		odst = ip->ip_dst;
    658 		if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
    659 		    PFIL_IN) != 0)
    660 			return;
    661 		if (m == NULL)
    662 			return;
    663 		ip = mtod(m, struct ip *);
    664 		hlen = ip->ip_hl << 2;
    665 		/*
    666 		 * XXX The setting of "srcrt" here is to prevent ip_forward()
    667 		 * from generating ICMP redirects for packets that have
    668 		 * been redirected by a hook back out on to the same LAN that
    669 		 * they came from and is not an indication that the packet
    670 		 * is being inffluenced by source routing options.  This
    671 		 * allows things like
    672 		 * "rdr tlp0 0/0 port 80 -> 1.1.1.200 3128 tcp"
    673 		 * where tlp0 is both on the 1.1.1.0/24 network and is the
    674 		 * default route for hosts on 1.1.1.0/24.  Of course this
    675 		 * also requires a "map tlp0 ..." to complete the story.
    676 		 * One might argue whether or not this kind of network config.
    677 		 * should be supported in this manner...
    678 		 */
    679 		srcrt = (odst.s_addr != ip->ip_dst.s_addr);
    680 	}
    681 #endif /* PFIL_HOOKS */
    682 
    683 #ifdef ALTQ
    684 	/* XXX Temporary until ALTQ is changed to use a pfil hook */
    685 	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0) {
    686 		/* packet dropped by traffic conditioner */
    687 		return;
    688 	}
    689 #endif
    690 
    691 	/*
    692 	 * Process options and, if not destined for us,
    693 	 * ship it on.  ip_dooptions returns 1 when an
    694 	 * error was detected (causing an icmp message
    695 	 * to be sent and the original packet to be freed).
    696 	 */
    697 	ip_nhops = 0;		/* for source routed packets */
    698 	if (hlen > sizeof (struct ip) && ip_dooptions(m))
    699 		return;
    700 
    701 	/*
    702 	 * Enable a consistency check between the destination address
    703 	 * and the arrival interface for a unicast packet (the RFC 1122
    704 	 * strong ES model) if IP forwarding is disabled and the packet
    705 	 * is not locally generated.
    706 	 *
    707 	 * XXX - Checking also should be disabled if the destination
    708 	 * address is ipnat'ed to a different interface.
    709 	 *
    710 	 * XXX - Checking is incompatible with IP aliases added
    711 	 * to the loopback interface instead of the interface where
    712 	 * the packets are received.
    713 	 *
    714 	 * XXX - We need to add a per ifaddr flag for this so that
    715 	 * we get finer grain control.
    716 	 */
    717 	checkif = ip_checkinterface && (ipforwarding == 0) &&
    718 	    (m->m_pkthdr.rcvif != NULL) &&
    719 	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0);
    720 
    721 	/*
    722 	 * Check our list of addresses, to see if the packet is for us.
    723 	 *
    724 	 * Traditional 4.4BSD did not consult IFF_UP at all.
    725 	 * The behavior here is to treat addresses on !IFF_UP interface
    726 	 * as not mine.
    727 	 */
    728 	downmatch = 0;
    729 	LIST_FOREACH(ia, &IN_IFADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
    730 		if (in_hosteq(ia->ia_addr.sin_addr, ip->ip_dst)) {
    731 			if (checkif && ia->ia_ifp != m->m_pkthdr.rcvif)
    732 				continue;
    733 			if ((ia->ia_ifp->if_flags & IFF_UP) != 0)
    734 				break;
    735 			else
    736 				downmatch++;
    737 		}
    738 	}
    739 	if (ia != NULL)
    740 		goto ours;
    741 	if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
    742 		IFADDR_FOREACH(ifa, m->m_pkthdr.rcvif) {
    743 			if (ifa->ifa_addr->sa_family != AF_INET)
    744 				continue;
    745 			ia = ifatoia(ifa);
    746 			if (in_hosteq(ip->ip_dst, ia->ia_broadaddr.sin_addr) ||
    747 			    in_hosteq(ip->ip_dst, ia->ia_netbroadcast) ||
    748 			    /*
    749 			     * Look for all-0's host part (old broadcast addr),
    750 			     * either for subnet or net.
    751 			     */
    752 			    ip->ip_dst.s_addr == ia->ia_subnet ||
    753 			    ip->ip_dst.s_addr == ia->ia_net)
    754 				goto ours;
    755 			/*
    756 			 * An interface with IP address zero accepts
    757 			 * all packets that arrive on that interface.
    758 			 */
    759 			if (in_nullhost(ia->ia_addr.sin_addr))
    760 				goto ours;
    761 		}
    762 	}
    763 	if (IN_MULTICAST(ip->ip_dst.s_addr)) {
    764 		struct in_multi *inm;
    765 #ifdef MROUTING
    766 		extern struct socket *ip_mrouter;
    767 
    768 		if (ip_mrouter) {
    769 			/*
    770 			 * If we are acting as a multicast router, all
    771 			 * incoming multicast packets are passed to the
    772 			 * kernel-level multicast forwarding function.
    773 			 * The packet is returned (relatively) intact; if
    774 			 * ip_mforward() returns a non-zero value, the packet
    775 			 * must be discarded, else it may be accepted below.
    776 			 *
    777 			 * (The IP ident field is put in the same byte order
    778 			 * as expected when ip_mforward() is called from
    779 			 * ip_output().)
    780 			 */
    781 			if (ip_mforward(m, m->m_pkthdr.rcvif) != 0) {
    782 				ipstat.ips_cantforward++;
    783 				m_freem(m);
    784 				return;
    785 			}
    786 
    787 			/*
    788 			 * The process-level routing demon needs to receive
    789 			 * all multicast IGMP packets, whether or not this
    790 			 * host belongs to their destination groups.
    791 			 */
    792 			if (ip->ip_p == IPPROTO_IGMP)
    793 				goto ours;
    794 			ipstat.ips_forward++;
    795 		}
    796 #endif
    797 		/*
    798 		 * See if we belong to the destination multicast group on the
    799 		 * arrival interface.
    800 		 */
    801 		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
    802 		if (inm == NULL) {
    803 			ipstat.ips_cantforward++;
    804 			m_freem(m);
    805 			return;
    806 		}
    807 		goto ours;
    808 	}
    809 	if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
    810 	    in_nullhost(ip->ip_dst))
    811 		goto ours;
    812 
    813 	/*
    814 	 * Not for us; forward if possible and desirable.
    815 	 */
    816 	if (ipforwarding == 0) {
    817 		ipstat.ips_cantforward++;
    818 		m_freem(m);
    819 	} else {
    820 		/*
    821 		 * If ip_dst matched any of my address on !IFF_UP interface,
    822 		 * and there's no IFF_UP interface that matches ip_dst,
    823 		 * send icmp unreach.  Forwarding it will result in in-kernel
    824 		 * forwarding loop till TTL goes to 0.
    825 		 */
    826 		if (downmatch) {
    827 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
    828 			ipstat.ips_cantforward++;
    829 			return;
    830 		}
    831 #ifdef IPSEC
    832 		if (ipsec4_in_reject(m, NULL)) {
    833 			ipsecstat.in_polvio++;
    834 			goto bad;
    835 		}
    836 #endif
    837 #ifdef FAST_IPSEC
    838 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
    839 		s = splsoftnet();
    840 		if (mtag != NULL) {
    841 			tdbi = (struct tdb_ident *)(mtag + 1);
    842 			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
    843 		} else {
    844 			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
    845 						   IP_FORWARDING, &error);
    846 		}
    847 		if (sp == NULL) {	/* NB: can happen if error */
    848 			splx(s);
    849 			/*XXX error stat???*/
    850 			DPRINTF(("ip_input: no SP for forwarding\n"));	/*XXX*/
    851 			goto bad;
    852 		}
    853 
    854 		/*
    855 		 * Check security policy against packet attributes.
    856 		 */
    857 		error = ipsec_in_reject(sp, m);
    858 		KEY_FREESP(&sp);
    859 		splx(s);
    860 		if (error) {
    861 			ipstat.ips_cantforward++;
    862 			goto bad;
    863 		}
    864 
    865 		/*
    866 		 * Peek at the outbound SP for this packet to determine if
    867 		 * it's a Fast Forward candidate.
    868 		 */
    869 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
    870 		if (mtag != NULL)
    871 			m->m_flags &= ~M_CANFASTFWD;
    872 		else {
    873 			s = splsoftnet();
    874 			sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND,
    875 			    (IP_FORWARDING |
    876 			     (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
    877 			    &error, NULL);
    878 			if (sp != NULL) {
    879 				m->m_flags &= ~M_CANFASTFWD;
    880 				KEY_FREESP(&sp);
    881 			}
    882 			splx(s);
    883 		}
    884 #endif	/* FAST_IPSEC */
    885 
    886 		ip_forward(m, srcrt);
    887 	}
    888 	return;
    889 
    890 ours:
    891 	/*
    892 	 * If offset or IP_MF are set, must reassemble.
    893 	 * Otherwise, nothing need be done.
    894 	 * (We could look in the reassembly queue to see
    895 	 * if the packet was previously fragmented,
    896 	 * but it's not worth the time; just let them time out.)
    897 	 */
    898 	if (ip->ip_off & ~htons(IP_DF|IP_RF)) {
    899 		uint16_t off;
    900 		/*
    901 		 * Prevent TCP blind data attacks by not allowing non-initial
    902 		 * fragments to start at less than 68 bytes (minimal fragment
    903 		 * size) and making sure the first fragment is at least 68
    904 		 * bytes.
    905 		 */
    906 		off = (ntohs(ip->ip_off) & IP_OFFMASK) << 3;
    907 		if ((off > 0 ? off + hlen : len) < IP_MINFRAGSIZE - 1) {
    908 			ipstat.ips_badfrags++;
    909 			goto bad;
    910 		}
    911 		/*
    912 		 * Look for queue of fragments
    913 		 * of this datagram.
    914 		 */
    915 		IPQ_LOCK();
    916 		hash = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
    917 		LIST_FOREACH(fp, &ipq[hash], ipq_q) {
    918 			if (ip->ip_id == fp->ipq_id &&
    919 			    in_hosteq(ip->ip_src, fp->ipq_src) &&
    920 			    in_hosteq(ip->ip_dst, fp->ipq_dst) &&
    921 			    ip->ip_p == fp->ipq_p) {
    922 				/*
    923 				 * Make sure the TOS is matches previous
    924 				 * fragments.
    925 				 */
    926 				if (ip->ip_tos != fp->ipq_tos) {
    927 					ipstat.ips_badfrags++;
    928 					goto bad;
    929 				}
    930 				goto found;
    931 			}
    932 		}
    933 		fp = 0;
    934 found:
    935 
    936 		/*
    937 		 * Adjust ip_len to not reflect header,
    938 		 * set ipqe_mff if more fragments are expected,
    939 		 * convert offset of this to bytes.
    940 		 */
    941 		ip->ip_len = htons(ntohs(ip->ip_len) - hlen);
    942 		mff = (ip->ip_off & htons(IP_MF)) != 0;
    943 		if (mff) {
    944 		        /*
    945 		         * Make sure that fragments have a data length
    946 			 * that's a non-zero multiple of 8 bytes.
    947 		         */
    948 			if (ntohs(ip->ip_len) == 0 ||
    949 			    (ntohs(ip->ip_len) & 0x7) != 0) {
    950 				ipstat.ips_badfrags++;
    951 				IPQ_UNLOCK();
    952 				goto bad;
    953 			}
    954 		}
    955 		ip->ip_off = htons((ntohs(ip->ip_off) & IP_OFFMASK) << 3);
    956 
    957 		/*
    958 		 * If datagram marked as having more fragments
    959 		 * or if this is not the first fragment,
    960 		 * attempt reassembly; if it succeeds, proceed.
    961 		 */
    962 		if (mff || ip->ip_off != htons(0)) {
    963 			ipstat.ips_fragments++;
    964 			s = splvm();
    965 			ipqe = pool_get(&ipqent_pool, PR_NOWAIT);
    966 			splx(s);
    967 			if (ipqe == NULL) {
    968 				ipstat.ips_rcvmemdrop++;
    969 				IPQ_UNLOCK();
    970 				goto bad;
    971 			}
    972 			ipqe->ipqe_mff = mff;
    973 			ipqe->ipqe_m = m;
    974 			ipqe->ipqe_ip = ip;
    975 			m = ip_reass(ipqe, fp, &ipq[hash]);
    976 			if (m == 0) {
    977 				IPQ_UNLOCK();
    978 				return;
    979 			}
    980 			ipstat.ips_reassembled++;
    981 			ip = mtod(m, struct ip *);
    982 			hlen = ip->ip_hl << 2;
    983 			ip->ip_len = htons(ntohs(ip->ip_len) + hlen);
    984 		} else
    985 			if (fp)
    986 				ip_freef(fp);
    987 		IPQ_UNLOCK();
    988 	}
    989 
    990 #if defined(IPSEC)
    991 	/*
    992 	 * enforce IPsec policy checking if we are seeing last header.
    993 	 * note that we do not visit this with protocols with pcb layer
    994 	 * code - like udp/tcp/raw ip.
    995 	 */
    996 	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
    997 	    ipsec4_in_reject(m, NULL)) {
    998 		ipsecstat.in_polvio++;
    999 		goto bad;
   1000 	}
   1001 #endif
   1002 #ifdef FAST_IPSEC
   1003 	/*
   1004 	 * enforce IPsec policy checking if we are seeing last header.
   1005 	 * note that we do not visit this with protocols with pcb layer
   1006 	 * code - like udp/tcp/raw ip.
   1007 	 */
   1008 	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
   1009 		/*
   1010 		 * Check if the packet has already had IPsec processing
   1011 		 * done.  If so, then just pass it along.  This tag gets
   1012 		 * set during AH, ESP, etc. input handling, before the
   1013 		 * packet is returned to the ip input queue for delivery.
   1014 		 */
   1015 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
   1016 		s = splsoftnet();
   1017 		if (mtag != NULL) {
   1018 			tdbi = (struct tdb_ident *)(mtag + 1);
   1019 			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
   1020 		} else {
   1021 			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
   1022 						   IP_FORWARDING, &error);
   1023 		}
   1024 		if (sp != NULL) {
   1025 			/*
   1026 			 * Check security policy against packet attributes.
   1027 			 */
   1028 			error = ipsec_in_reject(sp, m);
   1029 			KEY_FREESP(&sp);
   1030 		} else {
   1031 			/* XXX error stat??? */
   1032 			error = EINVAL;
   1033 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
   1034 		}
   1035 		splx(s);
   1036 		if (error)
   1037 			goto bad;
   1038 	}
   1039 #endif /* FAST_IPSEC */
   1040 
   1041 	/*
   1042 	 * Switch out to protocol's input routine.
   1043 	 */
   1044 #if IFA_STATS
   1045 	if (ia && ip)
   1046 		ia->ia_ifa.ifa_data.ifad_inbytes += ntohs(ip->ip_len);
   1047 #endif
   1048 	ipstat.ips_delivered++;
   1049     {
   1050 	int off = hlen, nh = ip->ip_p;
   1051 
   1052 	(*inetsw[ip_protox[nh]].pr_input)(m, off, nh);
   1053 	return;
   1054     }
   1055 bad:
   1056 	m_freem(m);
   1057 	return;
   1058 
   1059 badcsum:
   1060 	ipstat.ips_badsum++;
   1061 	m_freem(m);
   1062 }
   1063 
   1064 /*
   1065  * Take incoming datagram fragment and try to
   1066  * reassemble it into whole datagram.  If a chain for
   1067  * reassembly of this datagram already exists, then it
   1068  * is given as fp; otherwise have to make a chain.
   1069  */
   1070 struct mbuf *
   1071 ip_reass(struct ipqent *ipqe, struct ipq *fp, struct ipqhead *ipqhead)
   1072 {
   1073 	struct mbuf *m = ipqe->ipqe_m;
   1074 	struct ipqent *nq, *p, *q;
   1075 	struct ip *ip;
   1076 	struct mbuf *t;
   1077 	int hlen = ipqe->ipqe_ip->ip_hl << 2;
   1078 	int i, next, s;
   1079 
   1080 	IPQ_LOCK_CHECK();
   1081 
   1082 	/*
   1083 	 * Presence of header sizes in mbufs
   1084 	 * would confuse code below.
   1085 	 */
   1086 	m->m_data += hlen;
   1087 	m->m_len -= hlen;
   1088 
   1089 #ifdef	notyet
   1090 	/* make sure fragment limit is up-to-date */
   1091 	CHECK_NMBCLUSTER_PARAMS();
   1092 
   1093 	/* If we have too many fragments, drop the older half. */
   1094 	if (ip_nfrags >= ip_maxfrags)
   1095 		ip_reass_drophalf(void);
   1096 #endif
   1097 
   1098 	/*
   1099 	 * We are about to add a fragment; increment frag count.
   1100 	 */
   1101 	ip_nfrags++;
   1102 
   1103 	/*
   1104 	 * If first fragment to arrive, create a reassembly queue.
   1105 	 */
   1106 	if (fp == 0) {
   1107 		/*
   1108 		 * Enforce upper bound on number of fragmented packets
   1109 		 * for which we attempt reassembly;
   1110 		 * If maxfrag is 0, never accept fragments.
   1111 		 * If maxfrag is -1, accept all fragments without limitation.
   1112 		 */
   1113 		if (ip_maxfragpackets < 0)
   1114 			;
   1115 		else if (ip_nfragpackets >= ip_maxfragpackets)
   1116 			goto dropfrag;
   1117 		ip_nfragpackets++;
   1118 		MALLOC(fp, struct ipq *, sizeof (struct ipq),
   1119 		    M_FTABLE, M_NOWAIT);
   1120 		if (fp == NULL)
   1121 			goto dropfrag;
   1122 		LIST_INSERT_HEAD(ipqhead, fp, ipq_q);
   1123 		fp->ipq_nfrags = 1;
   1124 		fp->ipq_ttl = IPFRAGTTL;
   1125 		fp->ipq_p = ipqe->ipqe_ip->ip_p;
   1126 		fp->ipq_id = ipqe->ipqe_ip->ip_id;
   1127 		fp->ipq_tos = ipqe->ipqe_ip->ip_tos;
   1128 		TAILQ_INIT(&fp->ipq_fragq);
   1129 		fp->ipq_src = ipqe->ipqe_ip->ip_src;
   1130 		fp->ipq_dst = ipqe->ipqe_ip->ip_dst;
   1131 		p = NULL;
   1132 		goto insert;
   1133 	} else {
   1134 		fp->ipq_nfrags++;
   1135 	}
   1136 
   1137 	/*
   1138 	 * Find a segment which begins after this one does.
   1139 	 */
   1140 	for (p = NULL, q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL;
   1141 	    p = q, q = TAILQ_NEXT(q, ipqe_q))
   1142 		if (ntohs(q->ipqe_ip->ip_off) > ntohs(ipqe->ipqe_ip->ip_off))
   1143 			break;
   1144 
   1145 	/*
   1146 	 * If there is a preceding segment, it may provide some of
   1147 	 * our data already.  If so, drop the data from the incoming
   1148 	 * segment.  If it provides all of our data, drop us.
   1149 	 */
   1150 	if (p != NULL) {
   1151 		i = ntohs(p->ipqe_ip->ip_off) + ntohs(p->ipqe_ip->ip_len) -
   1152 		    ntohs(ipqe->ipqe_ip->ip_off);
   1153 		if (i > 0) {
   1154 			if (i >= ntohs(ipqe->ipqe_ip->ip_len))
   1155 				goto dropfrag;
   1156 			m_adj(ipqe->ipqe_m, i);
   1157 			ipqe->ipqe_ip->ip_off =
   1158 			    htons(ntohs(ipqe->ipqe_ip->ip_off) + i);
   1159 			ipqe->ipqe_ip->ip_len =
   1160 			    htons(ntohs(ipqe->ipqe_ip->ip_len) - i);
   1161 		}
   1162 	}
   1163 
   1164 	/*
   1165 	 * While we overlap succeeding segments trim them or,
   1166 	 * if they are completely covered, dequeue them.
   1167 	 */
   1168 	for (; q != NULL &&
   1169 	    ntohs(ipqe->ipqe_ip->ip_off) + ntohs(ipqe->ipqe_ip->ip_len) >
   1170 	    ntohs(q->ipqe_ip->ip_off); q = nq) {
   1171 		i = (ntohs(ipqe->ipqe_ip->ip_off) +
   1172 		    ntohs(ipqe->ipqe_ip->ip_len)) - ntohs(q->ipqe_ip->ip_off);
   1173 		if (i < ntohs(q->ipqe_ip->ip_len)) {
   1174 			q->ipqe_ip->ip_len =
   1175 			    htons(ntohs(q->ipqe_ip->ip_len) - i);
   1176 			q->ipqe_ip->ip_off =
   1177 			    htons(ntohs(q->ipqe_ip->ip_off) + i);
   1178 			m_adj(q->ipqe_m, i);
   1179 			break;
   1180 		}
   1181 		nq = TAILQ_NEXT(q, ipqe_q);
   1182 		m_freem(q->ipqe_m);
   1183 		TAILQ_REMOVE(&fp->ipq_fragq, q, ipqe_q);
   1184 		s = splvm();
   1185 		pool_put(&ipqent_pool, q);
   1186 		splx(s);
   1187 		fp->ipq_nfrags--;
   1188 		ip_nfrags--;
   1189 	}
   1190 
   1191 insert:
   1192 	/*
   1193 	 * Stick new segment in its place;
   1194 	 * check for complete reassembly.
   1195 	 */
   1196 	if (p == NULL) {
   1197 		TAILQ_INSERT_HEAD(&fp->ipq_fragq, ipqe, ipqe_q);
   1198 	} else {
   1199 		TAILQ_INSERT_AFTER(&fp->ipq_fragq, p, ipqe, ipqe_q);
   1200 	}
   1201 	next = 0;
   1202 	for (p = NULL, q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL;
   1203 	    p = q, q = TAILQ_NEXT(q, ipqe_q)) {
   1204 		if (ntohs(q->ipqe_ip->ip_off) != next)
   1205 			return (0);
   1206 		next += ntohs(q->ipqe_ip->ip_len);
   1207 	}
   1208 	if (p->ipqe_mff)
   1209 		return (0);
   1210 
   1211 	/*
   1212 	 * Reassembly is complete.  Check for a bogus message size and
   1213 	 * concatenate fragments.
   1214 	 */
   1215 	q = TAILQ_FIRST(&fp->ipq_fragq);
   1216 	ip = q->ipqe_ip;
   1217 	if ((next + (ip->ip_hl << 2)) > IP_MAXPACKET) {
   1218 		ipstat.ips_toolong++;
   1219 		ip_freef(fp);
   1220 		return (0);
   1221 	}
   1222 	m = q->ipqe_m;
   1223 	t = m->m_next;
   1224 	m->m_next = 0;
   1225 	m_cat(m, t);
   1226 	nq = TAILQ_NEXT(q, ipqe_q);
   1227 	s = splvm();
   1228 	pool_put(&ipqent_pool, q);
   1229 	splx(s);
   1230 	for (q = nq; q != NULL; q = nq) {
   1231 		t = q->ipqe_m;
   1232 		nq = TAILQ_NEXT(q, ipqe_q);
   1233 		s = splvm();
   1234 		pool_put(&ipqent_pool, q);
   1235 		splx(s);
   1236 		m_cat(m, t);
   1237 	}
   1238 	ip_nfrags -= fp->ipq_nfrags;
   1239 
   1240 	/*
   1241 	 * Create header for new ip packet by
   1242 	 * modifying header of first packet;
   1243 	 * dequeue and discard fragment reassembly header.
   1244 	 * Make header visible.
   1245 	 */
   1246 	ip->ip_len = htons(next);
   1247 	ip->ip_src = fp->ipq_src;
   1248 	ip->ip_dst = fp->ipq_dst;
   1249 	LIST_REMOVE(fp, ipq_q);
   1250 	FREE(fp, M_FTABLE);
   1251 	ip_nfragpackets--;
   1252 	m->m_len += (ip->ip_hl << 2);
   1253 	m->m_data -= (ip->ip_hl << 2);
   1254 	/* some debugging cruft by sklower, below, will go away soon */
   1255 	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
   1256 		int plen = 0;
   1257 		for (t = m; t; t = t->m_next)
   1258 			plen += t->m_len;
   1259 		m->m_pkthdr.len = plen;
   1260 		m->m_pkthdr.csum_flags = 0;
   1261 	}
   1262 	return (m);
   1263 
   1264 dropfrag:
   1265 	if (fp != 0)
   1266 		fp->ipq_nfrags--;
   1267 	ip_nfrags--;
   1268 	ipstat.ips_fragdropped++;
   1269 	m_freem(m);
   1270 	s = splvm();
   1271 	pool_put(&ipqent_pool, ipqe);
   1272 	splx(s);
   1273 	return (0);
   1274 }
   1275 
   1276 /*
   1277  * Free a fragment reassembly header and all
   1278  * associated datagrams.
   1279  */
   1280 void
   1281 ip_freef(struct ipq *fp)
   1282 {
   1283 	struct ipqent *q, *p;
   1284 	u_int nfrags = 0;
   1285 	int s;
   1286 
   1287 	IPQ_LOCK_CHECK();
   1288 
   1289 	for (q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL; q = p) {
   1290 		p = TAILQ_NEXT(q, ipqe_q);
   1291 		m_freem(q->ipqe_m);
   1292 		nfrags++;
   1293 		TAILQ_REMOVE(&fp->ipq_fragq, q, ipqe_q);
   1294 		s = splvm();
   1295 		pool_put(&ipqent_pool, q);
   1296 		splx(s);
   1297 	}
   1298 
   1299 	if (nfrags != fp->ipq_nfrags)
   1300 	    printf("ip_freef: nfrags %d != %d\n", fp->ipq_nfrags, nfrags);
   1301 	ip_nfrags -= nfrags;
   1302 	LIST_REMOVE(fp, ipq_q);
   1303 	FREE(fp, M_FTABLE);
   1304 	ip_nfragpackets--;
   1305 }
   1306 
   1307 /*
   1308  * IP reassembly TTL machinery for  multiplicative drop.
   1309  */
   1310 static u_int	fragttl_histo[(IPFRAGTTL+1)];
   1311 
   1312 
   1313 /*
   1314  * Decrement TTL of all reasembly queue entries by `ticks'.
   1315  * Count number of distinct fragments (as opposed to partial, fragmented
   1316  * datagrams) in the reassembly queue.  While we  traverse the entire
   1317  * reassembly queue, compute and return the median TTL over all fragments.
   1318  */
   1319 static u_int
   1320 ip_reass_ttl_decr(u_int ticks)
   1321 {
   1322 	u_int nfrags, median, dropfraction, keepfraction;
   1323 	struct ipq *fp, *nfp;
   1324 	int i;
   1325 
   1326 	nfrags = 0;
   1327 	memset(fragttl_histo, 0, sizeof fragttl_histo);
   1328 
   1329 	for (i = 0; i < IPREASS_NHASH; i++) {
   1330 		for (fp = LIST_FIRST(&ipq[i]); fp != NULL; fp = nfp) {
   1331 			fp->ipq_ttl = ((fp->ipq_ttl  <= ticks) ?
   1332 				       0 : fp->ipq_ttl - ticks);
   1333 			nfp = LIST_NEXT(fp, ipq_q);
   1334 			if (fp->ipq_ttl == 0) {
   1335 				ipstat.ips_fragtimeout++;
   1336 				ip_freef(fp);
   1337 			} else {
   1338 				nfrags += fp->ipq_nfrags;
   1339 				fragttl_histo[fp->ipq_ttl] += fp->ipq_nfrags;
   1340 			}
   1341 		}
   1342 	}
   1343 
   1344 	KASSERT(ip_nfrags == nfrags);
   1345 
   1346 	/* Find median (or other drop fraction) in histogram. */
   1347 	dropfraction = (ip_nfrags / 2);
   1348 	keepfraction = ip_nfrags - dropfraction;
   1349 	for (i = IPFRAGTTL, median = 0; i >= 0; i--) {
   1350 		median +=  fragttl_histo[i];
   1351 		if (median >= keepfraction)
   1352 			break;
   1353 	}
   1354 
   1355 	/* Return TTL of median (or other fraction). */
   1356 	return (u_int)i;
   1357 }
   1358 
   1359 void
   1360 ip_reass_drophalf(void)
   1361 {
   1362 
   1363 	u_int median_ticks;
   1364 	/*
   1365 	 * Compute median TTL of all fragments, and count frags
   1366 	 * with that TTL or lower (roughly half of all fragments).
   1367 	 */
   1368 	median_ticks = ip_reass_ttl_decr(0);
   1369 
   1370 	/* Drop half. */
   1371 	median_ticks = ip_reass_ttl_decr(median_ticks);
   1372 
   1373 }
   1374 
   1375 /*
   1376  * IP timer processing;
   1377  * if a timer expires on a reassembly
   1378  * queue, discard it.
   1379  */
   1380 void
   1381 ip_slowtimo(void)
   1382 {
   1383 	static u_int dropscanidx = 0;
   1384 	u_int i;
   1385 	u_int median_ttl;
   1386 	int s = splsoftnet();
   1387 
   1388 	IPQ_LOCK();
   1389 
   1390 	/* Age TTL of all fragments by 1 tick .*/
   1391 	median_ttl = ip_reass_ttl_decr(1);
   1392 
   1393 	/* make sure fragment limit is up-to-date */
   1394 	CHECK_NMBCLUSTER_PARAMS();
   1395 
   1396 	/* If we have too many fragments, drop the older half. */
   1397 	if (ip_nfrags > ip_maxfrags)
   1398 		ip_reass_ttl_decr(median_ttl);
   1399 
   1400 	/*
   1401 	 * If we are over the maximum number of fragmented packets
   1402 	 * (due to the limit being lowered), drain off
   1403 	 * enough to get down to the new limit. Start draining
   1404 	 * from the reassembly hashqueue most recently drained.
   1405 	 */
   1406 	if (ip_maxfragpackets < 0)
   1407 		;
   1408 	else {
   1409 		int wrapped = 0;
   1410 
   1411 		i = dropscanidx;
   1412 		while (ip_nfragpackets > ip_maxfragpackets && wrapped == 0) {
   1413 			while (LIST_FIRST(&ipq[i]) != NULL)
   1414 				ip_freef(LIST_FIRST(&ipq[i]));
   1415 			if (++i >= IPREASS_NHASH) {
   1416 				i = 0;
   1417 			}
   1418 			/*
   1419 			 * Dont scan forever even if fragment counters are
   1420 			 * wrong: stop after scanning entire reassembly queue.
   1421 			 */
   1422 			if (i == dropscanidx)
   1423 			    wrapped = 1;
   1424 		}
   1425 		dropscanidx = i;
   1426 	}
   1427 	IPQ_UNLOCK();
   1428 	splx(s);
   1429 }
   1430 
   1431 /*
   1432  * Drain off all datagram fragments.
   1433  */
   1434 void
   1435 ip_drain(void)
   1436 {
   1437 
   1438 	/*
   1439 	 * We may be called from a device's interrupt context.  If
   1440 	 * the ipq is already busy, just bail out now.
   1441 	 */
   1442 	if (ipq_lock_try() == 0)
   1443 		return;
   1444 
   1445 	/*
   1446 	 * Drop half the total fragments now. If more mbufs are needed,
   1447 	 *  we will be called again soon.
   1448 	 */
   1449 	ip_reass_drophalf();
   1450 
   1451 	IPQ_UNLOCK();
   1452 }
   1453 
   1454 /*
   1455  * Do option processing on a datagram,
   1456  * possibly discarding it if bad options are encountered,
   1457  * or forwarding it if source-routed.
   1458  * Returns 1 if packet has been forwarded/freed,
   1459  * 0 if the packet should be processed further.
   1460  */
   1461 int
   1462 ip_dooptions(struct mbuf *m)
   1463 {
   1464 	struct ip *ip = mtod(m, struct ip *);
   1465 	u_char *cp, *cp0;
   1466 	struct ip_timestamp *ipt;
   1467 	struct in_ifaddr *ia;
   1468 	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
   1469 	struct in_addr dst;
   1470 	n_time ntime;
   1471 
   1472 	dst = ip->ip_dst;
   1473 	cp = (u_char *)(ip + 1);
   1474 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
   1475 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1476 		opt = cp[IPOPT_OPTVAL];
   1477 		if (opt == IPOPT_EOL)
   1478 			break;
   1479 		if (opt == IPOPT_NOP)
   1480 			optlen = 1;
   1481 		else {
   1482 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
   1483 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1484 				goto bad;
   1485 			}
   1486 			optlen = cp[IPOPT_OLEN];
   1487 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
   1488 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1489 				goto bad;
   1490 			}
   1491 		}
   1492 		switch (opt) {
   1493 
   1494 		default:
   1495 			break;
   1496 
   1497 		/*
   1498 		 * Source routing with record.
   1499 		 * Find interface with current destination address.
   1500 		 * If none on this machine then drop if strictly routed,
   1501 		 * or do nothing if loosely routed.
   1502 		 * Record interface address and bring up next address
   1503 		 * component.  If strictly routed make sure next
   1504 		 * address is on directly accessible net.
   1505 		 */
   1506 		case IPOPT_LSRR:
   1507 		case IPOPT_SSRR:
   1508 			if (ip_allowsrcrt == 0) {
   1509 				type = ICMP_UNREACH;
   1510 				code = ICMP_UNREACH_NET_PROHIB;
   1511 				goto bad;
   1512 			}
   1513 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
   1514 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1515 				goto bad;
   1516 			}
   1517 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
   1518 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
   1519 				goto bad;
   1520 			}
   1521 			ipaddr.sin_addr = ip->ip_dst;
   1522 			ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
   1523 			if (ia == 0) {
   1524 				if (opt == IPOPT_SSRR) {
   1525 					type = ICMP_UNREACH;
   1526 					code = ICMP_UNREACH_SRCFAIL;
   1527 					goto bad;
   1528 				}
   1529 				/*
   1530 				 * Loose routing, and not at next destination
   1531 				 * yet; nothing to do except forward.
   1532 				 */
   1533 				break;
   1534 			}
   1535 			off--;			/* 0 origin */
   1536 			if ((off + sizeof(struct in_addr)) > optlen) {
   1537 				/*
   1538 				 * End of source route.  Should be for us.
   1539 				 */
   1540 				save_rte(cp, ip->ip_src);
   1541 				break;
   1542 			}
   1543 			/*
   1544 			 * locate outgoing interface
   1545 			 */
   1546 			bcopy((void *)(cp + off), (void *)&ipaddr.sin_addr,
   1547 			    sizeof(ipaddr.sin_addr));
   1548 			if (opt == IPOPT_SSRR)
   1549 				ia = ifatoia(ifa_ifwithladdr(sintosa(&ipaddr)));
   1550 			else
   1551 				ia = ip_rtaddr(ipaddr.sin_addr);
   1552 			if (ia == 0) {
   1553 				type = ICMP_UNREACH;
   1554 				code = ICMP_UNREACH_SRCFAIL;
   1555 				goto bad;
   1556 			}
   1557 			ip->ip_dst = ipaddr.sin_addr;
   1558 			bcopy((void *)&ia->ia_addr.sin_addr,
   1559 			    (void *)(cp + off), sizeof(struct in_addr));
   1560 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
   1561 			/*
   1562 			 * Let ip_intr's mcast routing check handle mcast pkts
   1563 			 */
   1564 			forward = !IN_MULTICAST(ip->ip_dst.s_addr);
   1565 			break;
   1566 
   1567 		case IPOPT_RR:
   1568 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
   1569 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
   1570 				goto bad;
   1571 			}
   1572 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
   1573 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
   1574 				goto bad;
   1575 			}
   1576 			/*
   1577 			 * If no space remains, ignore.
   1578 			 */
   1579 			off--;			/* 0 origin */
   1580 			if ((off + sizeof(struct in_addr)) > optlen)
   1581 				break;
   1582 			bcopy((void *)(&ip->ip_dst), (void *)&ipaddr.sin_addr,
   1583 			    sizeof(ipaddr.sin_addr));
   1584 			/*
   1585 			 * locate outgoing interface; if we're the destination,
   1586 			 * use the incoming interface (should be same).
   1587 			 */
   1588 			if ((ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr))))
   1589 			    == NULL &&
   1590 			    (ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
   1591 				type = ICMP_UNREACH;
   1592 				code = ICMP_UNREACH_HOST;
   1593 				goto bad;
   1594 			}
   1595 			bcopy((void *)&ia->ia_addr.sin_addr,
   1596 			    (void *)(cp + off), sizeof(struct in_addr));
   1597 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
   1598 			break;
   1599 
   1600 		case IPOPT_TS:
   1601 			code = cp - (u_char *)ip;
   1602 			ipt = (struct ip_timestamp *)cp;
   1603 			if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
   1604 				code = (u_char *)&ipt->ipt_len - (u_char *)ip;
   1605 				goto bad;
   1606 			}
   1607 			if (ipt->ipt_ptr < 5) {
   1608 				code = (u_char *)&ipt->ipt_ptr - (u_char *)ip;
   1609 				goto bad;
   1610 			}
   1611 			if (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {
   1612 				if (++ipt->ipt_oflw == 0) {
   1613 					code = (u_char *)&ipt->ipt_ptr -
   1614 					    (u_char *)ip;
   1615 					goto bad;
   1616 				}
   1617 				break;
   1618 			}
   1619 			cp0 = (cp + ipt->ipt_ptr - 1);
   1620 			switch (ipt->ipt_flg) {
   1621 
   1622 			case IPOPT_TS_TSONLY:
   1623 				break;
   1624 
   1625 			case IPOPT_TS_TSANDADDR:
   1626 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
   1627 				    sizeof(struct in_addr) > ipt->ipt_len) {
   1628 					code = (u_char *)&ipt->ipt_ptr -
   1629 					    (u_char *)ip;
   1630 					goto bad;
   1631 				}
   1632 				ipaddr.sin_addr = dst;
   1633 				ia = ifatoia(ifaof_ifpforaddr(sintosa(&ipaddr),
   1634 				    m->m_pkthdr.rcvif));
   1635 				if (ia == 0)
   1636 					continue;
   1637 				bcopy(&ia->ia_addr.sin_addr,
   1638 				    cp0, sizeof(struct in_addr));
   1639 				ipt->ipt_ptr += sizeof(struct in_addr);
   1640 				break;
   1641 
   1642 			case IPOPT_TS_PRESPEC:
   1643 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
   1644 				    sizeof(struct in_addr) > ipt->ipt_len) {
   1645 					code = (u_char *)&ipt->ipt_ptr -
   1646 					    (u_char *)ip;
   1647 					goto bad;
   1648 				}
   1649 				bcopy(cp0, &ipaddr.sin_addr,
   1650 				    sizeof(struct in_addr));
   1651 				if (ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)))
   1652 				    == NULL)
   1653 					continue;
   1654 				ipt->ipt_ptr += sizeof(struct in_addr);
   1655 				break;
   1656 
   1657 			default:
   1658 				/* XXX can't take &ipt->ipt_flg */
   1659 				code = (u_char *)&ipt->ipt_ptr -
   1660 				    (u_char *)ip + 1;
   1661 				goto bad;
   1662 			}
   1663 			ntime = iptime();
   1664 			cp0 = (u_char *) &ntime; /* XXX grumble, GCC... */
   1665 			memmove((char *)cp + ipt->ipt_ptr - 1, cp0,
   1666 			    sizeof(n_time));
   1667 			ipt->ipt_ptr += sizeof(n_time);
   1668 		}
   1669 	}
   1670 	if (forward) {
   1671 		if (ip_forwsrcrt == 0) {
   1672 			type = ICMP_UNREACH;
   1673 			code = ICMP_UNREACH_SRCFAIL;
   1674 			goto bad;
   1675 		}
   1676 		ip_forward(m, 1);
   1677 		return (1);
   1678 	}
   1679 	return (0);
   1680 bad:
   1681 	icmp_error(m, type, code, 0, 0);
   1682 	ipstat.ips_badoptions++;
   1683 	return (1);
   1684 }
   1685 
   1686 /*
   1687  * Given address of next destination (final or next hop),
   1688  * return internet address info of interface to be used to get there.
   1689  */
   1690 struct in_ifaddr *
   1691 ip_rtaddr(struct in_addr dst)
   1692 {
   1693 	struct rtentry *rt;
   1694 	union {
   1695 		struct sockaddr		dst;
   1696 		struct sockaddr_in	dst4;
   1697 	} u;
   1698 
   1699 	sockaddr_in_init(&u.dst4, &dst, 0);
   1700 
   1701 	if ((rt = rtcache_lookup(&ipforward_rt, &u.dst)) == NULL)
   1702 		return NULL;
   1703 
   1704 	return ifatoia(rt->rt_ifa);
   1705 }
   1706 
   1707 /*
   1708  * Save incoming source route for use in replies,
   1709  * to be picked up later by ip_srcroute if the receiver is interested.
   1710  */
   1711 void
   1712 save_rte(u_char *option, struct in_addr dst)
   1713 {
   1714 	unsigned olen;
   1715 
   1716 	olen = option[IPOPT_OLEN];
   1717 #ifdef DIAGNOSTIC
   1718 	if (ipprintfs)
   1719 		printf("save_rte: olen %d\n", olen);
   1720 #endif /* 0 */
   1721 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
   1722 		return;
   1723 	bcopy((void *)option, (void *)ip_srcrt.srcopt, olen);
   1724 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
   1725 	ip_srcrt.dst = dst;
   1726 }
   1727 
   1728 /*
   1729  * Retrieve incoming source route for use in replies,
   1730  * in the same form used by setsockopt.
   1731  * The first hop is placed before the options, will be removed later.
   1732  */
   1733 struct mbuf *
   1734 ip_srcroute(void)
   1735 {
   1736 	struct in_addr *p, *q;
   1737 	struct mbuf *m;
   1738 
   1739 	if (ip_nhops == 0)
   1740 		return NULL;
   1741 	m = m_get(M_DONTWAIT, MT_SOOPTS);
   1742 	if (m == 0)
   1743 		return NULL;
   1744 
   1745 	MCLAIM(m, &inetdomain.dom_mowner);
   1746 #define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
   1747 
   1748 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
   1749 	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
   1750 	    OPTSIZ;
   1751 #ifdef DIAGNOSTIC
   1752 	if (ipprintfs)
   1753 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
   1754 #endif
   1755 
   1756 	/*
   1757 	 * First save first hop for return route
   1758 	 */
   1759 	p = &ip_srcrt.route[ip_nhops - 1];
   1760 	*(mtod(m, struct in_addr *)) = *p--;
   1761 #ifdef DIAGNOSTIC
   1762 	if (ipprintfs)
   1763 		printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
   1764 #endif
   1765 
   1766 	/*
   1767 	 * Copy option fields and padding (nop) to mbuf.
   1768 	 */
   1769 	ip_srcrt.nop = IPOPT_NOP;
   1770 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
   1771 	memmove(mtod(m, char *) + sizeof(struct in_addr), &ip_srcrt.nop,
   1772 	    OPTSIZ);
   1773 	q = (struct in_addr *)(mtod(m, char *) +
   1774 	    sizeof(struct in_addr) + OPTSIZ);
   1775 #undef OPTSIZ
   1776 	/*
   1777 	 * Record return path as an IP source route,
   1778 	 * reversing the path (pointers are now aligned).
   1779 	 */
   1780 	while (p >= ip_srcrt.route) {
   1781 #ifdef DIAGNOSTIC
   1782 		if (ipprintfs)
   1783 			printf(" %x", ntohl(q->s_addr));
   1784 #endif
   1785 		*q++ = *p--;
   1786 	}
   1787 	/*
   1788 	 * Last hop goes to final destination.
   1789 	 */
   1790 	*q = ip_srcrt.dst;
   1791 #ifdef DIAGNOSTIC
   1792 	if (ipprintfs)
   1793 		printf(" %x\n", ntohl(q->s_addr));
   1794 #endif
   1795 	return (m);
   1796 }
   1797 
   1798 const int inetctlerrmap[PRC_NCMDS] = {
   1799 	[PRC_MSGSIZE] = EMSGSIZE,
   1800 	[PRC_HOSTDEAD] = EHOSTDOWN,
   1801 	[PRC_HOSTUNREACH] = EHOSTUNREACH,
   1802 	[PRC_UNREACH_NET] = EHOSTUNREACH,
   1803 	[PRC_UNREACH_HOST] = EHOSTUNREACH,
   1804 	[PRC_UNREACH_PROTOCOL] = ECONNREFUSED,
   1805 	[PRC_UNREACH_PORT] = ECONNREFUSED,
   1806 	[PRC_UNREACH_SRCFAIL] = EHOSTUNREACH,
   1807 	[PRC_PARAMPROB] = ENOPROTOOPT,
   1808 };
   1809 
   1810 /*
   1811  * Forward a packet.  If some error occurs return the sender
   1812  * an icmp packet.  Note we can't always generate a meaningful
   1813  * icmp message because icmp doesn't have a large enough repertoire
   1814  * of codes and types.
   1815  *
   1816  * If not forwarding, just drop the packet.  This could be confusing
   1817  * if ipforwarding was zero but some routing protocol was advancing
   1818  * us as a gateway to somewhere.  However, we must let the routing
   1819  * protocol deal with that.
   1820  *
   1821  * The srcrt parameter indicates whether the packet is being forwarded
   1822  * via a source route.
   1823  */
   1824 void
   1825 ip_forward(struct mbuf *m, int srcrt)
   1826 {
   1827 	struct ip *ip = mtod(m, struct ip *);
   1828 	struct rtentry *rt;
   1829 	int error, type = 0, code = 0, destmtu = 0;
   1830 	struct mbuf *mcopy;
   1831 	n_long dest;
   1832 	union {
   1833 		struct sockaddr		dst;
   1834 		struct sockaddr_in	dst4;
   1835 	} u;
   1836 
   1837 	/*
   1838 	 * We are now in the output path.
   1839 	 */
   1840 	MCLAIM(m, &ip_tx_mowner);
   1841 
   1842 	/*
   1843 	 * Clear any in-bound checksum flags for this packet.
   1844 	 */
   1845 	m->m_pkthdr.csum_flags = 0;
   1846 
   1847 	dest = 0;
   1848 #ifdef DIAGNOSTIC
   1849 	if (ipprintfs) {
   1850 		printf("forward: src %s ", inet_ntoa(ip->ip_src));
   1851 		printf("dst %s ttl %x\n", inet_ntoa(ip->ip_dst), ip->ip_ttl);
   1852 	}
   1853 #endif
   1854 	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
   1855 		ipstat.ips_cantforward++;
   1856 		m_freem(m);
   1857 		return;
   1858 	}
   1859 	if (ip->ip_ttl <= IPTTLDEC) {
   1860 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
   1861 		return;
   1862 	}
   1863 
   1864 	sockaddr_in_init(&u.dst4, &ip->ip_dst, 0);
   1865 	if ((rt = rtcache_lookup(&ipforward_rt, &u.dst)) == NULL) {
   1866 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NET, dest, 0);
   1867 		return;
   1868 	}
   1869 
   1870 	/*
   1871 	 * Save at most 68 bytes of the packet in case
   1872 	 * we need to generate an ICMP message to the src.
   1873 	 * Pullup to avoid sharing mbuf cluster between m and mcopy.
   1874 	 */
   1875 	mcopy = m_copym(m, 0, imin(ntohs(ip->ip_len), 68), M_DONTWAIT);
   1876 	if (mcopy)
   1877 		mcopy = m_pullup(mcopy, ip->ip_hl << 2);
   1878 
   1879 	ip->ip_ttl -= IPTTLDEC;
   1880 
   1881 	/*
   1882 	 * If forwarding packet using same interface that it came in on,
   1883 	 * perhaps should send a redirect to sender to shortcut a hop.
   1884 	 * Only send redirect if source is sending directly to us,
   1885 	 * and if packet was not source routed (or has any options).
   1886 	 * Also, don't send redirect if forwarding using a default route
   1887 	 * or a route modified by a redirect.
   1888 	 */
   1889 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
   1890 	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
   1891 	    !in_nullhost(satocsin(rt_getkey(rt))->sin_addr) &&
   1892 	    ipsendredirects && !srcrt) {
   1893 		if (rt->rt_ifa &&
   1894 		    (ip->ip_src.s_addr & ifatoia(rt->rt_ifa)->ia_subnetmask) ==
   1895 		    ifatoia(rt->rt_ifa)->ia_subnet) {
   1896 			if (rt->rt_flags & RTF_GATEWAY)
   1897 				dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
   1898 			else
   1899 				dest = ip->ip_dst.s_addr;
   1900 			/*
   1901 			 * Router requirements says to only send host
   1902 			 * redirects.
   1903 			 */
   1904 			type = ICMP_REDIRECT;
   1905 			code = ICMP_REDIRECT_HOST;
   1906 #ifdef DIAGNOSTIC
   1907 			if (ipprintfs)
   1908 				printf("redirect (%d) to %x\n", code,
   1909 				    (u_int32_t)dest);
   1910 #endif
   1911 		}
   1912 	}
   1913 
   1914 	error = ip_output(m, NULL, &ipforward_rt,
   1915 	    (IP_FORWARDING | (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
   1916 	    (struct ip_moptions *)NULL, (struct socket *)NULL);
   1917 
   1918 	if (error)
   1919 		ipstat.ips_cantforward++;
   1920 	else {
   1921 		ipstat.ips_forward++;
   1922 		if (type)
   1923 			ipstat.ips_redirectsent++;
   1924 		else {
   1925 			if (mcopy) {
   1926 #ifdef GATEWAY
   1927 				if (mcopy->m_flags & M_CANFASTFWD)
   1928 					ipflow_create(&ipforward_rt, mcopy);
   1929 #endif
   1930 				m_freem(mcopy);
   1931 			}
   1932 			return;
   1933 		}
   1934 	}
   1935 	if (mcopy == NULL)
   1936 		return;
   1937 
   1938 	switch (error) {
   1939 
   1940 	case 0:				/* forwarded, but need redirect */
   1941 		/* type, code set above */
   1942 		break;
   1943 
   1944 	case ENETUNREACH:		/* shouldn't happen, checked above */
   1945 	case EHOSTUNREACH:
   1946 	case ENETDOWN:
   1947 	case EHOSTDOWN:
   1948 	default:
   1949 		type = ICMP_UNREACH;
   1950 		code = ICMP_UNREACH_HOST;
   1951 		break;
   1952 
   1953 	case EMSGSIZE:
   1954 		type = ICMP_UNREACH;
   1955 		code = ICMP_UNREACH_NEEDFRAG;
   1956 #if !defined(IPSEC) && !defined(FAST_IPSEC)
   1957 		if ((rt = rtcache_validate(&ipforward_rt)) != NULL)
   1958 			destmtu = rt->rt_ifp->if_mtu;
   1959 #else
   1960 		/*
   1961 		 * If the packet is routed over IPsec tunnel, tell the
   1962 		 * originator the tunnel MTU.
   1963 		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
   1964 		 * XXX quickhack!!!
   1965 		 */
   1966 		if ((rt = rtcache_validate(&ipforward_rt)) != NULL) {
   1967 			struct secpolicy *sp;
   1968 			int ipsecerror;
   1969 			size_t ipsechdr;
   1970 			struct route *ro;
   1971 
   1972 			sp = ipsec4_getpolicybyaddr(mcopy,
   1973 			    IPSEC_DIR_OUTBOUND, IP_FORWARDING,
   1974 			    &ipsecerror);
   1975 
   1976 			if (sp == NULL)
   1977 				destmtu = rt->rt_ifp->if_mtu;
   1978 			else {
   1979 				/* count IPsec header size */
   1980 				ipsechdr = ipsec4_hdrsiz(mcopy,
   1981 				    IPSEC_DIR_OUTBOUND, NULL);
   1982 
   1983 				/*
   1984 				 * find the correct route for outer IPv4
   1985 				 * header, compute tunnel MTU.
   1986 				 */
   1987 
   1988 				if (sp->req != NULL
   1989 				 && sp->req->sav != NULL
   1990 				 && sp->req->sav->sah != NULL) {
   1991 					ro = &sp->req->sav->sah->sa_route;
   1992 					if (rt && rt->rt_ifp) {
   1993 						destmtu =
   1994 						    rt->rt_rmx.rmx_mtu ?
   1995 						    rt->rt_rmx.rmx_mtu :
   1996 						    rt->rt_ifp->if_mtu;
   1997 						destmtu -= ipsechdr;
   1998 					}
   1999 				}
   2000 
   2001 #ifdef	IPSEC
   2002 				key_freesp(sp);
   2003 #else
   2004 				KEY_FREESP(&sp);
   2005 #endif
   2006 			}
   2007 		}
   2008 #endif /*IPSEC*/
   2009 		ipstat.ips_cantfrag++;
   2010 		break;
   2011 
   2012 	case ENOBUFS:
   2013 #if 1
   2014 		/*
   2015 		 * a router should not generate ICMP_SOURCEQUENCH as
   2016 		 * required in RFC1812 Requirements for IP Version 4 Routers.
   2017 		 * source quench could be a big problem under DoS attacks,
   2018 		 * or if the underlying interface is rate-limited.
   2019 		 */
   2020 		if (mcopy)
   2021 			m_freem(mcopy);
   2022 		return;
   2023 #else
   2024 		type = ICMP_SOURCEQUENCH;
   2025 		code = 0;
   2026 		break;
   2027 #endif
   2028 	}
   2029 	icmp_error(mcopy, type, code, dest, destmtu);
   2030 }
   2031 
   2032 void
   2033 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
   2034     struct mbuf *m)
   2035 {
   2036 
   2037 	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
   2038 		struct timeval tv;
   2039 
   2040 		microtime(&tv);
   2041 		*mp = sbcreatecontrol((void *) &tv, sizeof(tv),
   2042 		    SCM_TIMESTAMP, SOL_SOCKET);
   2043 		if (*mp)
   2044 			mp = &(*mp)->m_next;
   2045 	}
   2046 	if (inp->inp_flags & INP_RECVDSTADDR) {
   2047 		*mp = sbcreatecontrol((void *) &ip->ip_dst,
   2048 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
   2049 		if (*mp)
   2050 			mp = &(*mp)->m_next;
   2051 	}
   2052 #ifdef notyet
   2053 	/*
   2054 	 * XXX
   2055 	 * Moving these out of udp_input() made them even more broken
   2056 	 * than they already were.
   2057 	 *	- fenner (at) parc.xerox.com
   2058 	 */
   2059 	/* options were tossed already */
   2060 	if (inp->inp_flags & INP_RECVOPTS) {
   2061 		*mp = sbcreatecontrol((void *) opts_deleted_above,
   2062 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
   2063 		if (*mp)
   2064 			mp = &(*mp)->m_next;
   2065 	}
   2066 	/* ip_srcroute doesn't do what we want here, need to fix */
   2067 	if (inp->inp_flags & INP_RECVRETOPTS) {
   2068 		*mp = sbcreatecontrol((void *) ip_srcroute(),
   2069 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
   2070 		if (*mp)
   2071 			mp = &(*mp)->m_next;
   2072 	}
   2073 #endif
   2074 	if (inp->inp_flags & INP_RECVIF) {
   2075 		struct sockaddr_dl sdl;
   2076 
   2077 		sockaddr_dl_init(&sdl, sizeof(sdl),
   2078 		    (m->m_pkthdr.rcvif != NULL)
   2079 		        ?  m->m_pkthdr.rcvif->if_index
   2080 			: 0,
   2081 			0, NULL, 0, NULL, 0);
   2082 		*mp = sbcreatecontrol(&sdl, sdl.sdl_len, IP_RECVIF, IPPROTO_IP);
   2083 		if (*mp)
   2084 			mp = &(*mp)->m_next;
   2085 	}
   2086 }
   2087 
   2088 /*
   2089  * sysctl helper routine for net.inet.ip.forwsrcrt.
   2090  */
   2091 static int
   2092 sysctl_net_inet_ip_forwsrcrt(SYSCTLFN_ARGS)
   2093 {
   2094 	int error, tmp;
   2095 	struct sysctlnode node;
   2096 
   2097 	node = *rnode;
   2098 	tmp = ip_forwsrcrt;
   2099 	node.sysctl_data = &tmp;
   2100 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2101 	if (error || newp == NULL)
   2102 		return (error);
   2103 
   2104 	if (kauth_authorize_network(l->l_cred, KAUTH_NETWORK_FORWSRCRT,
   2105 	    0, NULL, NULL, NULL))
   2106 		return (EPERM);
   2107 
   2108 	ip_forwsrcrt = tmp;
   2109 
   2110 	return (0);
   2111 }
   2112 
   2113 /*
   2114  * sysctl helper routine for net.inet.ip.mtudisctimeout.  checks the
   2115  * range of the new value and tweaks timers if it changes.
   2116  */
   2117 static int
   2118 sysctl_net_inet_ip_pmtudto(SYSCTLFN_ARGS)
   2119 {
   2120 	int error, tmp;
   2121 	struct sysctlnode node;
   2122 
   2123 	node = *rnode;
   2124 	tmp = ip_mtudisc_timeout;
   2125 	node.sysctl_data = &tmp;
   2126 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2127 	if (error || newp == NULL)
   2128 		return (error);
   2129 	if (tmp < 0)
   2130 		return (EINVAL);
   2131 
   2132 	ip_mtudisc_timeout = tmp;
   2133 	rt_timer_queue_change(ip_mtudisc_timeout_q, ip_mtudisc_timeout);
   2134 
   2135 	return (0);
   2136 }
   2137 
   2138 #ifdef GATEWAY
   2139 /*
   2140  * sysctl helper routine for net.inet.ip.maxflows.
   2141  */
   2142 static int
   2143 sysctl_net_inet_ip_maxflows(SYSCTLFN_ARGS)
   2144 {
   2145 	int s;
   2146 
   2147 	s = sysctl_lookup(SYSCTLFN_CALL(rnode));
   2148 	if (s || newp == NULL)
   2149 		return (s);
   2150 
   2151 	s = splsoftnet();
   2152 	ipflow_reap(0);
   2153 	splx(s);
   2154 
   2155 	return (0);
   2156 }
   2157 
   2158 static int
   2159 sysctl_net_inet_ip_hashsize(SYSCTLFN_ARGS)
   2160 {
   2161 	int error, tmp;
   2162 	struct sysctlnode node;
   2163 
   2164 	node = *rnode;
   2165 	tmp = ip_hashsize;
   2166 	node.sysctl_data = &tmp;
   2167 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
   2168 	if (error || newp == NULL)
   2169 		return (error);
   2170 
   2171 	if ((tmp & (tmp - 1)) == 0 && tmp != 0) {
   2172 		/*
   2173 		 * Can only fail due to malloc()
   2174 		 */
   2175 		if (ipflow_invalidate_all(tmp))
   2176 			return ENOMEM;
   2177 	} else {
   2178 		/*
   2179 		 * EINVAL if not a power of 2
   2180 	         */
   2181 		return EINVAL;
   2182 	}
   2183 
   2184 	return (0);
   2185 }
   2186 #endif /* GATEWAY */
   2187 
   2188 
   2189 SYSCTL_SETUP(sysctl_net_inet_ip_setup, "sysctl net.inet.ip subtree setup")
   2190 {
   2191 	extern int subnetsarelocal, hostzeroisbroadcast;
   2192 
   2193 	sysctl_createv(clog, 0, NULL, NULL,
   2194 		       CTLFLAG_PERMANENT,
   2195 		       CTLTYPE_NODE, "net", NULL,
   2196 		       NULL, 0, NULL, 0,
   2197 		       CTL_NET, CTL_EOL);
   2198 	sysctl_createv(clog, 0, NULL, NULL,
   2199 		       CTLFLAG_PERMANENT,
   2200 		       CTLTYPE_NODE, "inet",
   2201 		       SYSCTL_DESCR("PF_INET related settings"),
   2202 		       NULL, 0, NULL, 0,
   2203 		       CTL_NET, PF_INET, CTL_EOL);
   2204 	sysctl_createv(clog, 0, NULL, NULL,
   2205 		       CTLFLAG_PERMANENT,
   2206 		       CTLTYPE_NODE, "ip",
   2207 		       SYSCTL_DESCR("IPv4 related settings"),
   2208 		       NULL, 0, NULL, 0,
   2209 		       CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
   2210 
   2211 	sysctl_createv(clog, 0, NULL, NULL,
   2212 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2213 		       CTLTYPE_INT, "forwarding",
   2214 		       SYSCTL_DESCR("Enable forwarding of INET datagrams"),
   2215 		       NULL, 0, &ipforwarding, 0,
   2216 		       CTL_NET, PF_INET, IPPROTO_IP,
   2217 		       IPCTL_FORWARDING, CTL_EOL);
   2218 	sysctl_createv(clog, 0, NULL, NULL,
   2219 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2220 		       CTLTYPE_INT, "redirect",
   2221 		       SYSCTL_DESCR("Enable sending of ICMP redirect messages"),
   2222 		       NULL, 0, &ipsendredirects, 0,
   2223 		       CTL_NET, PF_INET, IPPROTO_IP,
   2224 		       IPCTL_SENDREDIRECTS, CTL_EOL);
   2225 	sysctl_createv(clog, 0, NULL, NULL,
   2226 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2227 		       CTLTYPE_INT, "ttl",
   2228 		       SYSCTL_DESCR("Default TTL for an INET datagram"),
   2229 		       NULL, 0, &ip_defttl, 0,
   2230 		       CTL_NET, PF_INET, IPPROTO_IP,
   2231 		       IPCTL_DEFTTL, CTL_EOL);
   2232 #ifdef IPCTL_DEFMTU
   2233 	sysctl_createv(clog, 0, NULL, NULL,
   2234 		       CTLFLAG_PERMANENT /* |CTLFLAG_READWRITE? */,
   2235 		       CTLTYPE_INT, "mtu",
   2236 		       SYSCTL_DESCR("Default MTA for an INET route"),
   2237 		       NULL, 0, &ip_mtu, 0,
   2238 		       CTL_NET, PF_INET, IPPROTO_IP,
   2239 		       IPCTL_DEFMTU, CTL_EOL);
   2240 #endif /* IPCTL_DEFMTU */
   2241 	sysctl_createv(clog, 0, NULL, NULL,
   2242 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2243 		       CTLTYPE_INT, "forwsrcrt",
   2244 		       SYSCTL_DESCR("Enable forwarding of source-routed "
   2245 				    "datagrams"),
   2246 		       sysctl_net_inet_ip_forwsrcrt, 0, &ip_forwsrcrt, 0,
   2247 		       CTL_NET, PF_INET, IPPROTO_IP,
   2248 		       IPCTL_FORWSRCRT, CTL_EOL);
   2249 	sysctl_createv(clog, 0, NULL, NULL,
   2250 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2251 		       CTLTYPE_INT, "directed-broadcast",
   2252 		       SYSCTL_DESCR("Enable forwarding of broadcast datagrams"),
   2253 		       NULL, 0, &ip_directedbcast, 0,
   2254 		       CTL_NET, PF_INET, IPPROTO_IP,
   2255 		       IPCTL_DIRECTEDBCAST, CTL_EOL);
   2256 	sysctl_createv(clog, 0, NULL, NULL,
   2257 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2258 		       CTLTYPE_INT, "allowsrcrt",
   2259 		       SYSCTL_DESCR("Accept source-routed datagrams"),
   2260 		       NULL, 0, &ip_allowsrcrt, 0,
   2261 		       CTL_NET, PF_INET, IPPROTO_IP,
   2262 		       IPCTL_ALLOWSRCRT, CTL_EOL);
   2263 	sysctl_createv(clog, 0, NULL, NULL,
   2264 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2265 		       CTLTYPE_INT, "subnetsarelocal",
   2266 		       SYSCTL_DESCR("Whether logical subnets are considered "
   2267 				    "local"),
   2268 		       NULL, 0, &subnetsarelocal, 0,
   2269 		       CTL_NET, PF_INET, IPPROTO_IP,
   2270 		       IPCTL_SUBNETSARELOCAL, CTL_EOL);
   2271 	sysctl_createv(clog, 0, NULL, NULL,
   2272 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2273 		       CTLTYPE_INT, "mtudisc",
   2274 		       SYSCTL_DESCR("Use RFC1191 Path MTU Discovery"),
   2275 		       NULL, 0, &ip_mtudisc, 0,
   2276 		       CTL_NET, PF_INET, IPPROTO_IP,
   2277 		       IPCTL_MTUDISC, CTL_EOL);
   2278 	sysctl_createv(clog, 0, NULL, NULL,
   2279 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2280 		       CTLTYPE_INT, "anonportmin",
   2281 		       SYSCTL_DESCR("Lowest ephemeral port number to assign"),
   2282 		       sysctl_net_inet_ip_ports, 0, &anonportmin, 0,
   2283 		       CTL_NET, PF_INET, IPPROTO_IP,
   2284 		       IPCTL_ANONPORTMIN, CTL_EOL);
   2285 	sysctl_createv(clog, 0, NULL, NULL,
   2286 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2287 		       CTLTYPE_INT, "anonportmax",
   2288 		       SYSCTL_DESCR("Highest ephemeral port number to assign"),
   2289 		       sysctl_net_inet_ip_ports, 0, &anonportmax, 0,
   2290 		       CTL_NET, PF_INET, IPPROTO_IP,
   2291 		       IPCTL_ANONPORTMAX, CTL_EOL);
   2292 	sysctl_createv(clog, 0, NULL, NULL,
   2293 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2294 		       CTLTYPE_INT, "mtudisctimeout",
   2295 		       SYSCTL_DESCR("Lifetime of a Path MTU Discovered route"),
   2296 		       sysctl_net_inet_ip_pmtudto, 0, &ip_mtudisc_timeout, 0,
   2297 		       CTL_NET, PF_INET, IPPROTO_IP,
   2298 		       IPCTL_MTUDISCTIMEOUT, CTL_EOL);
   2299 #ifdef GATEWAY
   2300 	sysctl_createv(clog, 0, NULL, NULL,
   2301 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2302 		       CTLTYPE_INT, "maxflows",
   2303 		       SYSCTL_DESCR("Number of flows for fast forwarding"),
   2304 		       sysctl_net_inet_ip_maxflows, 0, &ip_maxflows, 0,
   2305 		       CTL_NET, PF_INET, IPPROTO_IP,
   2306 		       IPCTL_MAXFLOWS, CTL_EOL);
   2307 	sysctl_createv(clog, 0, NULL, NULL,
   2308 			CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2309 			CTLTYPE_INT, "hashsize",
   2310 			SYSCTL_DESCR("Size of hash table for fast forwarding (IPv4)"),
   2311 			sysctl_net_inet_ip_hashsize, 0, &ip_hashsize, 0,
   2312 			CTL_NET, PF_INET, IPPROTO_IP,
   2313 			CTL_CREATE, CTL_EOL);
   2314 #endif /* GATEWAY */
   2315 	sysctl_createv(clog, 0, NULL, NULL,
   2316 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2317 		       CTLTYPE_INT, "hostzerobroadcast",
   2318 		       SYSCTL_DESCR("All zeroes address is broadcast address"),
   2319 		       NULL, 0, &hostzeroisbroadcast, 0,
   2320 		       CTL_NET, PF_INET, IPPROTO_IP,
   2321 		       IPCTL_HOSTZEROBROADCAST, CTL_EOL);
   2322 #if NGIF > 0
   2323 	sysctl_createv(clog, 0, NULL, NULL,
   2324 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2325 		       CTLTYPE_INT, "gifttl",
   2326 		       SYSCTL_DESCR("Default TTL for a gif tunnel datagram"),
   2327 		       NULL, 0, &ip_gif_ttl, 0,
   2328 		       CTL_NET, PF_INET, IPPROTO_IP,
   2329 		       IPCTL_GIF_TTL, CTL_EOL);
   2330 #endif /* NGIF */
   2331 #ifndef IPNOPRIVPORTS
   2332 	sysctl_createv(clog, 0, NULL, NULL,
   2333 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2334 		       CTLTYPE_INT, "lowportmin",
   2335 		       SYSCTL_DESCR("Lowest privileged ephemeral port number "
   2336 				    "to assign"),
   2337 		       sysctl_net_inet_ip_ports, 0, &lowportmin, 0,
   2338 		       CTL_NET, PF_INET, IPPROTO_IP,
   2339 		       IPCTL_LOWPORTMIN, CTL_EOL);
   2340 	sysctl_createv(clog, 0, NULL, NULL,
   2341 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2342 		       CTLTYPE_INT, "lowportmax",
   2343 		       SYSCTL_DESCR("Highest privileged ephemeral port number "
   2344 				    "to assign"),
   2345 		       sysctl_net_inet_ip_ports, 0, &lowportmax, 0,
   2346 		       CTL_NET, PF_INET, IPPROTO_IP,
   2347 		       IPCTL_LOWPORTMAX, CTL_EOL);
   2348 #endif /* IPNOPRIVPORTS */
   2349 	sysctl_createv(clog, 0, NULL, NULL,
   2350 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2351 		       CTLTYPE_INT, "maxfragpackets",
   2352 		       SYSCTL_DESCR("Maximum number of fragments to retain for "
   2353 				    "possible reassembly"),
   2354 		       NULL, 0, &ip_maxfragpackets, 0,
   2355 		       CTL_NET, PF_INET, IPPROTO_IP,
   2356 		       IPCTL_MAXFRAGPACKETS, CTL_EOL);
   2357 #if NGRE > 0
   2358 	sysctl_createv(clog, 0, NULL, NULL,
   2359 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2360 		       CTLTYPE_INT, "grettl",
   2361 		       SYSCTL_DESCR("Default TTL for a gre tunnel datagram"),
   2362 		       NULL, 0, &ip_gre_ttl, 0,
   2363 		       CTL_NET, PF_INET, IPPROTO_IP,
   2364 		       IPCTL_GRE_TTL, CTL_EOL);
   2365 #endif /* NGRE */
   2366 	sysctl_createv(clog, 0, NULL, NULL,
   2367 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2368 		       CTLTYPE_INT, "checkinterface",
   2369 		       SYSCTL_DESCR("Enable receive side of Strong ES model "
   2370 				    "from RFC1122"),
   2371 		       NULL, 0, &ip_checkinterface, 0,
   2372 		       CTL_NET, PF_INET, IPPROTO_IP,
   2373 		       IPCTL_CHECKINTERFACE, CTL_EOL);
   2374 	sysctl_createv(clog, 0, NULL, NULL,
   2375 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2376 		       CTLTYPE_INT, "random_id",
   2377 		       SYSCTL_DESCR("Assign random ip_id values"),
   2378 		       NULL, 0, &ip_do_randomid, 0,
   2379 		       CTL_NET, PF_INET, IPPROTO_IP,
   2380 		       IPCTL_RANDOMID, CTL_EOL);
   2381 	sysctl_createv(clog, 0, NULL, NULL,
   2382 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   2383 		       CTLTYPE_INT, "do_loopback_cksum",
   2384 		       SYSCTL_DESCR("Perform IP checksum on loopback"),
   2385 		       NULL, 0, &ip_do_loopback_cksum, 0,
   2386 		       CTL_NET, PF_INET, IPPROTO_IP,
   2387 		       IPCTL_LOOPBACKCKSUM, CTL_EOL);
   2388 	sysctl_createv(clog, 0, NULL, NULL,
   2389 		       CTLFLAG_PERMANENT,
   2390 		       CTLTYPE_STRUCT, "stats",
   2391 		       SYSCTL_DESCR("IP statistics"),
   2392 		       NULL, 0, &ipstat, sizeof(ipstat),
   2393 		       CTL_NET, PF_INET, IPPROTO_IP, IPCTL_STATS,
   2394 		       CTL_EOL);
   2395 }
   2396