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