xref: /freebsd/sys/netinet/ip_output.c (revision 3b2324c3a800d7599f348c408f01908d0cef05a0)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993
5  *	The Regents of the University of California.  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 University 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 REGENTS 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 REGENTS 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  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_inet.h"
38 #include "opt_ratelimit.h"
39 #include "opt_ipsec.h"
40 #include "opt_mbuf_stress_test.h"
41 #include "opt_mpath.h"
42 #include "opt_route.h"
43 #include "opt_sctp.h"
44 #include "opt_rss.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/lock.h>
50 #include <sys/malloc.h>
51 #include <sys/mbuf.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/protosw.h>
55 #include <sys/rmlock.h>
56 #include <sys/sdt.h>
57 #include <sys/socket.h>
58 #include <sys/socketvar.h>
59 #include <sys/sysctl.h>
60 #include <sys/ucred.h>
61 
62 #include <net/if.h>
63 #include <net/if_var.h>
64 #include <net/if_llatbl.h>
65 #include <net/netisr.h>
66 #include <net/pfil.h>
67 #include <net/route.h>
68 #ifdef RADIX_MPATH
69 #include <net/radix_mpath.h>
70 #endif
71 #include <net/rss_config.h>
72 #include <net/vnet.h>
73 
74 #include <netinet/in.h>
75 #include <netinet/in_kdtrace.h>
76 #include <netinet/in_systm.h>
77 #include <netinet/ip.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/in_rss.h>
80 #include <netinet/in_var.h>
81 #include <netinet/ip_var.h>
82 #include <netinet/ip_options.h>
83 
84 #include <netinet/udp.h>
85 #include <netinet/udp_var.h>
86 
87 #ifdef SCTP
88 #include <netinet/sctp.h>
89 #include <netinet/sctp_crc32.h>
90 #endif
91 
92 #include <netipsec/ipsec_support.h>
93 
94 #include <machine/in_cksum.h>
95 
96 #include <security/mac/mac_framework.h>
97 
98 #ifdef MBUF_STRESS_TEST
99 static int mbuf_frag_size = 0;
100 SYSCTL_INT(_net_inet_ip, OID_AUTO, mbuf_frag_size, CTLFLAG_RW,
101 	&mbuf_frag_size, 0, "Fragment outgoing mbufs to this size");
102 #endif
103 
104 static void	ip_mloopback(struct ifnet *, const struct mbuf *, int);
105 
106 
107 extern int in_mcast_loop;
108 extern	struct protosw inetsw[];
109 
110 static inline int
111 ip_output_pfil(struct mbuf **mp, struct ifnet *ifp, struct inpcb *inp,
112     struct sockaddr_in *dst, int *fibnum, int *error)
113 {
114 	struct m_tag *fwd_tag = NULL;
115 	struct mbuf *m;
116 	struct in_addr odst;
117 	struct ip *ip;
118 
119 	m = *mp;
120 	ip = mtod(m, struct ip *);
121 
122 	/* Run through list of hooks for output packets. */
123 	odst.s_addr = ip->ip_dst.s_addr;
124 	switch (pfil_run_hooks(V_inet_pfil_head, mp, ifp, PFIL_OUT, inp)) {
125 	case PFIL_DROPPED:
126 		*error = EPERM;
127 		/* FALLTHROUGH */
128 	case PFIL_CONSUMED:
129 		return 1; /* Finished */
130 	case PFIL_PASS:
131 		*error = 0;
132 	}
133 	m = *mp;
134 	ip = mtod(m, struct ip *);
135 
136 	/* See if destination IP address was changed by packet filter. */
137 	if (odst.s_addr != ip->ip_dst.s_addr) {
138 		m->m_flags |= M_SKIP_FIREWALL;
139 		/* If destination is now ourself drop to ip_input(). */
140 		if (in_localip(ip->ip_dst)) {
141 			m->m_flags |= M_FASTFWD_OURS;
142 			if (m->m_pkthdr.rcvif == NULL)
143 				m->m_pkthdr.rcvif = V_loif;
144 			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
145 				m->m_pkthdr.csum_flags |=
146 					CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
147 				m->m_pkthdr.csum_data = 0xffff;
148 			}
149 			m->m_pkthdr.csum_flags |=
150 				CSUM_IP_CHECKED | CSUM_IP_VALID;
151 #ifdef SCTP
152 			if (m->m_pkthdr.csum_flags & CSUM_SCTP)
153 				m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
154 #endif
155 			*error = netisr_queue(NETISR_IP, m);
156 			return 1; /* Finished */
157 		}
158 
159 		bzero(dst, sizeof(*dst));
160 		dst->sin_family = AF_INET;
161 		dst->sin_len = sizeof(*dst);
162 		dst->sin_addr = ip->ip_dst;
163 
164 		return -1; /* Reloop */
165 	}
166 	/* See if fib was changed by packet filter. */
167 	if ((*fibnum) != M_GETFIB(m)) {
168 		m->m_flags |= M_SKIP_FIREWALL;
169 		*fibnum = M_GETFIB(m);
170 		return -1; /* Reloop for FIB change */
171 	}
172 
173 	/* See if local, if yes, send it to netisr with IP_FASTFWD_OURS. */
174 	if (m->m_flags & M_FASTFWD_OURS) {
175 		if (m->m_pkthdr.rcvif == NULL)
176 			m->m_pkthdr.rcvif = V_loif;
177 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
178 			m->m_pkthdr.csum_flags |=
179 				CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
180 			m->m_pkthdr.csum_data = 0xffff;
181 		}
182 #ifdef SCTP
183 		if (m->m_pkthdr.csum_flags & CSUM_SCTP)
184 			m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
185 #endif
186 		m->m_pkthdr.csum_flags |=
187 			CSUM_IP_CHECKED | CSUM_IP_VALID;
188 
189 		*error = netisr_queue(NETISR_IP, m);
190 		return 1; /* Finished */
191 	}
192 	/* Or forward to some other address? */
193 	if ((m->m_flags & M_IP_NEXTHOP) &&
194 	    ((fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL)) != NULL)) {
195 		bcopy((fwd_tag+1), dst, sizeof(struct sockaddr_in));
196 		m->m_flags |= M_SKIP_FIREWALL;
197 		m->m_flags &= ~M_IP_NEXTHOP;
198 		m_tag_delete(m, fwd_tag);
199 
200 		return -1; /* Reloop for CHANGE of dst */
201 	}
202 
203 	return 0;
204 }
205 
206 /*
207  * IP output.  The packet in mbuf chain m contains a skeletal IP
208  * header (with len, off, ttl, proto, tos, src, dst).
209  * The mbuf chain containing the packet will be freed.
210  * The mbuf opt, if present, will not be freed.
211  * If route ro is present and has ro_rt initialized, route lookup would be
212  * skipped and ro->ro_rt would be used. If ro is present but ro->ro_rt is NULL,
213  * then result of route lookup is stored in ro->ro_rt.
214  *
215  * In the IP forwarding case, the packet will arrive with options already
216  * inserted, so must have a NULL opt pointer.
217  */
218 int
219 ip_output(struct mbuf *m, struct mbuf *opt, struct route *ro, int flags,
220     struct ip_moptions *imo, struct inpcb *inp)
221 {
222 	struct rm_priotracker in_ifa_tracker;
223 	struct epoch_tracker et;
224 	struct ip *ip;
225 	struct ifnet *ifp = NULL;	/* keep compiler happy */
226 	struct mbuf *m0;
227 	int hlen = sizeof (struct ip);
228 	int mtu;
229 	int error = 0;
230 	struct sockaddr_in *dst;
231 	const struct sockaddr_in *gw;
232 	struct in_ifaddr *ia;
233 	int isbroadcast;
234 	uint16_t ip_len, ip_off;
235 	struct route iproute;
236 	struct rtentry *rte;	/* cache for ro->ro_rt */
237 	uint32_t fibnum;
238 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
239 	int no_route_but_check_spd = 0;
240 #endif
241 	M_ASSERTPKTHDR(m);
242 
243 	if (inp != NULL) {
244 		INP_LOCK_ASSERT(inp);
245 		M_SETFIB(m, inp->inp_inc.inc_fibnum);
246 		if ((flags & IP_NODEFAULTFLOWID) == 0) {
247 			m->m_pkthdr.flowid = inp->inp_flowid;
248 			M_HASHTYPE_SET(m, inp->inp_flowtype);
249 		}
250 #ifdef NUMA
251 		m->m_pkthdr.numa_domain = inp->inp_numa_domain;
252 #endif
253 	}
254 
255 	if (ro == NULL) {
256 		ro = &iproute;
257 		bzero(ro, sizeof (*ro));
258 	}
259 
260 	if (opt) {
261 		int len = 0;
262 		m = ip_insertoptions(m, opt, &len);
263 		if (len != 0)
264 			hlen = len; /* ip->ip_hl is updated above */
265 	}
266 	ip = mtod(m, struct ip *);
267 	ip_len = ntohs(ip->ip_len);
268 	ip_off = ntohs(ip->ip_off);
269 
270 	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
271 		ip->ip_v = IPVERSION;
272 		ip->ip_hl = hlen >> 2;
273 		ip_fillid(ip);
274 	} else {
275 		/* Header already set, fetch hlen from there */
276 		hlen = ip->ip_hl << 2;
277 	}
278 	if ((flags & IP_FORWARDING) == 0)
279 		IPSTAT_INC(ips_localout);
280 
281 	/*
282 	 * dst/gw handling:
283 	 *
284 	 * dst can be rewritten but always points to &ro->ro_dst.
285 	 * gw is readonly but can point either to dst OR rt_gateway,
286 	 * therefore we need restore gw if we're redoing lookup.
287 	 */
288 	gw = dst = (struct sockaddr_in *)&ro->ro_dst;
289 	fibnum = (inp != NULL) ? inp->inp_inc.inc_fibnum : M_GETFIB(m);
290 	rte = ro->ro_rt;
291 	if (rte == NULL) {
292 		bzero(dst, sizeof(*dst));
293 		dst->sin_family = AF_INET;
294 		dst->sin_len = sizeof(*dst);
295 		dst->sin_addr = ip->ip_dst;
296 	}
297 	NET_EPOCH_ENTER(et);
298 again:
299 	/*
300 	 * Validate route against routing table additions;
301 	 * a better/more specific route might have been added.
302 	 */
303 	if (inp)
304 		RT_VALIDATE(ro, &inp->inp_rt_cookie, fibnum);
305 	/*
306 	 * If there is a cached route,
307 	 * check that it is to the same destination
308 	 * and is still up.  If not, free it and try again.
309 	 * The address family should also be checked in case of sharing the
310 	 * cache with IPv6.
311 	 * Also check whether routing cache needs invalidation.
312 	 */
313 	rte = ro->ro_rt;
314 	if (rte && ((rte->rt_flags & RTF_UP) == 0 ||
315 		    rte->rt_ifp == NULL ||
316 		    !RT_LINK_IS_UP(rte->rt_ifp) ||
317 			  dst->sin_family != AF_INET ||
318 			  dst->sin_addr.s_addr != ip->ip_dst.s_addr)) {
319 		RO_INVALIDATE_CACHE(ro);
320 		rte = NULL;
321 	}
322 	ia = NULL;
323 	/*
324 	 * If routing to interface only, short circuit routing lookup.
325 	 * The use of an all-ones broadcast address implies this; an
326 	 * interface is specified by the broadcast address of an interface,
327 	 * or the destination address of a ptp interface.
328 	 */
329 	if (flags & IP_SENDONES) {
330 		if ((ia = ifatoia(ifa_ifwithbroadaddr(sintosa(dst),
331 						      M_GETFIB(m)))) == NULL &&
332 		    (ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst),
333 						    M_GETFIB(m)))) == NULL) {
334 			IPSTAT_INC(ips_noroute);
335 			error = ENETUNREACH;
336 			goto bad;
337 		}
338 		ip->ip_dst.s_addr = INADDR_BROADCAST;
339 		dst->sin_addr = ip->ip_dst;
340 		ifp = ia->ia_ifp;
341 		ip->ip_ttl = 1;
342 		isbroadcast = 1;
343 	} else if (flags & IP_ROUTETOIF) {
344 		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst),
345 						    M_GETFIB(m)))) == NULL &&
346 		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst), 0,
347 						M_GETFIB(m)))) == NULL) {
348 			IPSTAT_INC(ips_noroute);
349 			error = ENETUNREACH;
350 			goto bad;
351 		}
352 		ifp = ia->ia_ifp;
353 		ip->ip_ttl = 1;
354 		isbroadcast = ifp->if_flags & IFF_BROADCAST ?
355 		    in_ifaddr_broadcast(dst->sin_addr, ia) : 0;
356 	} else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
357 	    imo != NULL && imo->imo_multicast_ifp != NULL) {
358 		/*
359 		 * Bypass the normal routing lookup for multicast
360 		 * packets if the interface is specified.
361 		 */
362 		ifp = imo->imo_multicast_ifp;
363 		IFP_TO_IA(ifp, ia, &in_ifa_tracker);
364 		isbroadcast = 0;	/* fool gcc */
365 	} else {
366 		/*
367 		 * We want to do any cloning requested by the link layer,
368 		 * as this is probably required in all cases for correct
369 		 * operation (as it is for ARP).
370 		 */
371 		if (rte == NULL) {
372 #ifdef RADIX_MPATH
373 			rtalloc_mpath_fib(ro,
374 			    ntohl(ip->ip_src.s_addr ^ ip->ip_dst.s_addr),
375 			    fibnum);
376 #else
377 			in_rtalloc_ign(ro, 0, fibnum);
378 #endif
379 			rte = ro->ro_rt;
380 		}
381 		if (rte == NULL ||
382 		    (rte->rt_flags & RTF_UP) == 0 ||
383 		    rte->rt_ifp == NULL ||
384 		    !RT_LINK_IS_UP(rte->rt_ifp)) {
385 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
386 			/*
387 			 * There is no route for this packet, but it is
388 			 * possible that a matching SPD entry exists.
389 			 */
390 			no_route_but_check_spd = 1;
391 			mtu = 0; /* Silence GCC warning. */
392 			goto sendit;
393 #endif
394 			IPSTAT_INC(ips_noroute);
395 			error = EHOSTUNREACH;
396 			goto bad;
397 		}
398 		ia = ifatoia(rte->rt_ifa);
399 		ifp = rte->rt_ifp;
400 		counter_u64_add(rte->rt_pksent, 1);
401 		rt_update_ro_flags(ro);
402 		if (rte->rt_flags & RTF_GATEWAY)
403 			gw = (struct sockaddr_in *)rte->rt_gateway;
404 		if (rte->rt_flags & RTF_HOST)
405 			isbroadcast = (rte->rt_flags & RTF_BROADCAST);
406 		else if (ifp->if_flags & IFF_BROADCAST)
407 			isbroadcast = in_ifaddr_broadcast(gw->sin_addr, ia);
408 		else
409 			isbroadcast = 0;
410 	}
411 
412 	/*
413 	 * Calculate MTU.  If we have a route that is up, use that,
414 	 * otherwise use the interface's MTU.
415 	 */
416 	if (rte != NULL && (rte->rt_flags & (RTF_UP|RTF_HOST)))
417 		mtu = rte->rt_mtu;
418 	else
419 		mtu = ifp->if_mtu;
420 	/* Catch a possible divide by zero later. */
421 	KASSERT(mtu > 0, ("%s: mtu %d <= 0, rte=%p (rt_flags=0x%08x) ifp=%p",
422 	    __func__, mtu, rte, (rte != NULL) ? rte->rt_flags : 0, ifp));
423 
424 	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
425 		m->m_flags |= M_MCAST;
426 		/*
427 		 * IP destination address is multicast.  Make sure "gw"
428 		 * still points to the address in "ro".  (It may have been
429 		 * changed to point to a gateway address, above.)
430 		 */
431 		gw = dst;
432 		/*
433 		 * See if the caller provided any multicast options
434 		 */
435 		if (imo != NULL) {
436 			ip->ip_ttl = imo->imo_multicast_ttl;
437 			if (imo->imo_multicast_vif != -1)
438 				ip->ip_src.s_addr =
439 				    ip_mcast_src ?
440 				    ip_mcast_src(imo->imo_multicast_vif) :
441 				    INADDR_ANY;
442 		} else
443 			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
444 		/*
445 		 * Confirm that the outgoing interface supports multicast.
446 		 */
447 		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
448 			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
449 				IPSTAT_INC(ips_noroute);
450 				error = ENETUNREACH;
451 				goto bad;
452 			}
453 		}
454 		/*
455 		 * If source address not specified yet, use address
456 		 * of outgoing interface.
457 		 */
458 		if (ip->ip_src.s_addr == INADDR_ANY) {
459 			/* Interface may have no addresses. */
460 			if (ia != NULL)
461 				ip->ip_src = IA_SIN(ia)->sin_addr;
462 		}
463 
464 		if ((imo == NULL && in_mcast_loop) ||
465 		    (imo && imo->imo_multicast_loop)) {
466 			/*
467 			 * Loop back multicast datagram if not expressly
468 			 * forbidden to do so, even if we are not a member
469 			 * of the group; ip_input() will filter it later,
470 			 * thus deferring a hash lookup and mutex acquisition
471 			 * at the expense of a cheap copy using m_copym().
472 			 */
473 			ip_mloopback(ifp, m, hlen);
474 		} else {
475 			/*
476 			 * If we are acting as a multicast router, perform
477 			 * multicast forwarding as if the packet had just
478 			 * arrived on the interface to which we are about
479 			 * to send.  The multicast forwarding function
480 			 * recursively calls this function, using the
481 			 * IP_FORWARDING flag to prevent infinite recursion.
482 			 *
483 			 * Multicasts that are looped back by ip_mloopback(),
484 			 * above, will be forwarded by the ip_input() routine,
485 			 * if necessary.
486 			 */
487 			if (V_ip_mrouter && (flags & IP_FORWARDING) == 0) {
488 				/*
489 				 * If rsvp daemon is not running, do not
490 				 * set ip_moptions. This ensures that the packet
491 				 * is multicast and not just sent down one link
492 				 * as prescribed by rsvpd.
493 				 */
494 				if (!V_rsvp_on)
495 					imo = NULL;
496 				if (ip_mforward &&
497 				    ip_mforward(ip, ifp, m, imo) != 0) {
498 					m_freem(m);
499 					goto done;
500 				}
501 			}
502 		}
503 
504 		/*
505 		 * Multicasts with a time-to-live of zero may be looped-
506 		 * back, above, but must not be transmitted on a network.
507 		 * Also, multicasts addressed to the loopback interface
508 		 * are not sent -- the above call to ip_mloopback() will
509 		 * loop back a copy. ip_input() will drop the copy if
510 		 * this host does not belong to the destination group on
511 		 * the loopback interface.
512 		 */
513 		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
514 			m_freem(m);
515 			goto done;
516 		}
517 
518 		goto sendit;
519 	}
520 
521 	/*
522 	 * If the source address is not specified yet, use the address
523 	 * of the outoing interface.
524 	 */
525 	if (ip->ip_src.s_addr == INADDR_ANY) {
526 		/* Interface may have no addresses. */
527 		if (ia != NULL) {
528 			ip->ip_src = IA_SIN(ia)->sin_addr;
529 		}
530 	}
531 
532 	/*
533 	 * Look for broadcast address and
534 	 * verify user is allowed to send
535 	 * such a packet.
536 	 */
537 	if (isbroadcast) {
538 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
539 			error = EADDRNOTAVAIL;
540 			goto bad;
541 		}
542 		if ((flags & IP_ALLOWBROADCAST) == 0) {
543 			error = EACCES;
544 			goto bad;
545 		}
546 		/* don't allow broadcast messages to be fragmented */
547 		if (ip_len > mtu) {
548 			error = EMSGSIZE;
549 			goto bad;
550 		}
551 		m->m_flags |= M_BCAST;
552 	} else {
553 		m->m_flags &= ~M_BCAST;
554 	}
555 
556 sendit:
557 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
558 	if (IPSEC_ENABLED(ipv4)) {
559 		if ((error = IPSEC_OUTPUT(ipv4, m, inp)) != 0) {
560 			if (error == EINPROGRESS)
561 				error = 0;
562 			goto done;
563 		}
564 	}
565 	/*
566 	 * Check if there was a route for this packet; return error if not.
567 	 */
568 	if (no_route_but_check_spd) {
569 		IPSTAT_INC(ips_noroute);
570 		error = EHOSTUNREACH;
571 		goto bad;
572 	}
573 	/* Update variables that are affected by ipsec4_output(). */
574 	ip = mtod(m, struct ip *);
575 	hlen = ip->ip_hl << 2;
576 #endif /* IPSEC */
577 
578 	/* Jump over all PFIL processing if hooks are not active. */
579 	if (PFIL_HOOKED_OUT(V_inet_pfil_head)) {
580 		switch (ip_output_pfil(&m, ifp, inp, dst, &fibnum, &error)) {
581 		case 1: /* Finished */
582 			goto done;
583 
584 		case 0: /* Continue normally */
585 			ip = mtod(m, struct ip *);
586 			break;
587 
588 		case -1: /* Need to try again */
589 			/* Reset everything for a new round */
590 			RO_RTFREE(ro);
591 			ro->ro_prepend = NULL;
592 			rte = NULL;
593 			gw = dst;
594 			ip = mtod(m, struct ip *);
595 			goto again;
596 
597 		}
598 	}
599 
600 	/* IN_LOOPBACK must not appear on the wire - RFC1122. */
601 	if (IN_LOOPBACK(ntohl(ip->ip_dst.s_addr)) ||
602 	    IN_LOOPBACK(ntohl(ip->ip_src.s_addr))) {
603 		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
604 			IPSTAT_INC(ips_badaddr);
605 			error = EADDRNOTAVAIL;
606 			goto bad;
607 		}
608 	}
609 
610 	m->m_pkthdr.csum_flags |= CSUM_IP;
611 	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA & ~ifp->if_hwassist) {
612 		in_delayed_cksum(m);
613 		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
614 	}
615 #ifdef SCTP
616 	if (m->m_pkthdr.csum_flags & CSUM_SCTP & ~ifp->if_hwassist) {
617 		sctp_delayed_cksum(m, (uint32_t)(ip->ip_hl << 2));
618 		m->m_pkthdr.csum_flags &= ~CSUM_SCTP;
619 	}
620 #endif
621 
622 	/*
623 	 * If small enough for interface, or the interface will take
624 	 * care of the fragmentation for us, we can just send directly.
625 	 */
626 	if (ip_len <= mtu ||
627 	    (m->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0) {
628 		ip->ip_sum = 0;
629 		if (m->m_pkthdr.csum_flags & CSUM_IP & ~ifp->if_hwassist) {
630 			ip->ip_sum = in_cksum(m, hlen);
631 			m->m_pkthdr.csum_flags &= ~CSUM_IP;
632 		}
633 
634 		/*
635 		 * Record statistics for this interface address.
636 		 * With CSUM_TSO the byte/packet count will be slightly
637 		 * incorrect because we count the IP+TCP headers only
638 		 * once instead of for every generated packet.
639 		 */
640 		if (!(flags & IP_FORWARDING) && ia) {
641 			if (m->m_pkthdr.csum_flags & CSUM_TSO)
642 				counter_u64_add(ia->ia_ifa.ifa_opackets,
643 				    m->m_pkthdr.len / m->m_pkthdr.tso_segsz);
644 			else
645 				counter_u64_add(ia->ia_ifa.ifa_opackets, 1);
646 
647 			counter_u64_add(ia->ia_ifa.ifa_obytes, m->m_pkthdr.len);
648 		}
649 #ifdef MBUF_STRESS_TEST
650 		if (mbuf_frag_size && m->m_pkthdr.len > mbuf_frag_size)
651 			m = m_fragment(m, M_NOWAIT, mbuf_frag_size);
652 #endif
653 		/*
654 		 * Reset layer specific mbuf flags
655 		 * to avoid confusing lower layers.
656 		 */
657 		m_clrprotoflags(m);
658 		IP_PROBE(send, NULL, NULL, ip, ifp, ip, NULL);
659 #ifdef RATELIMIT
660 		if (inp != NULL) {
661 			if (inp->inp_flags2 & INP_RATE_LIMIT_CHANGED)
662 				in_pcboutput_txrtlmt(inp, ifp, m);
663 			/* stamp send tag on mbuf */
664 			m->m_pkthdr.snd_tag = inp->inp_snd_tag;
665 		} else {
666 			m->m_pkthdr.snd_tag = NULL;
667 		}
668 #endif
669 		error = (*ifp->if_output)(ifp, m,
670 		    (const struct sockaddr *)gw, ro);
671 #ifdef RATELIMIT
672 		/* check for route change */
673 		if (error == EAGAIN)
674 			in_pcboutput_eagain(inp);
675 #endif
676 		goto done;
677 	}
678 
679 	/* Balk when DF bit is set or the interface didn't support TSO. */
680 	if ((ip_off & IP_DF) || (m->m_pkthdr.csum_flags & CSUM_TSO)) {
681 		error = EMSGSIZE;
682 		IPSTAT_INC(ips_cantfrag);
683 		goto bad;
684 	}
685 
686 	/*
687 	 * Too large for interface; fragment if possible. If successful,
688 	 * on return, m will point to a list of packets to be sent.
689 	 */
690 	error = ip_fragment(ip, &m, mtu, ifp->if_hwassist);
691 	if (error)
692 		goto bad;
693 	for (; m; m = m0) {
694 		m0 = m->m_nextpkt;
695 		m->m_nextpkt = 0;
696 		if (error == 0) {
697 			/* Record statistics for this interface address. */
698 			if (ia != NULL) {
699 				counter_u64_add(ia->ia_ifa.ifa_opackets, 1);
700 				counter_u64_add(ia->ia_ifa.ifa_obytes,
701 				    m->m_pkthdr.len);
702 			}
703 			/*
704 			 * Reset layer specific mbuf flags
705 			 * to avoid confusing upper layers.
706 			 */
707 			m_clrprotoflags(m);
708 
709 			IP_PROBE(send, NULL, NULL, mtod(m, struct ip *), ifp,
710 			    mtod(m, struct ip *), NULL);
711 #ifdef RATELIMIT
712 			if (inp != NULL) {
713 				if (inp->inp_flags2 & INP_RATE_LIMIT_CHANGED)
714 					in_pcboutput_txrtlmt(inp, ifp, m);
715 				/* stamp send tag on mbuf */
716 				m->m_pkthdr.snd_tag = inp->inp_snd_tag;
717 			} else {
718 				m->m_pkthdr.snd_tag = NULL;
719 			}
720 #endif
721 			error = (*ifp->if_output)(ifp, m,
722 			    (const struct sockaddr *)gw, ro);
723 #ifdef RATELIMIT
724 			/* check for route change */
725 			if (error == EAGAIN)
726 				in_pcboutput_eagain(inp);
727 #endif
728 		} else
729 			m_freem(m);
730 	}
731 
732 	if (error == 0)
733 		IPSTAT_INC(ips_fragmented);
734 
735 done:
736 	if (ro == &iproute)
737 		RO_RTFREE(ro);
738 	else if (rte == NULL)
739 		/*
740 		 * If the caller supplied a route but somehow the reference
741 		 * to it has been released need to prevent the caller
742 		 * calling RTFREE on it again.
743 		 */
744 		ro->ro_rt = NULL;
745 	NET_EPOCH_EXIT(et);
746 	return (error);
747  bad:
748 	m_freem(m);
749 	goto done;
750 }
751 
752 /*
753  * Create a chain of fragments which fit the given mtu. m_frag points to the
754  * mbuf to be fragmented; on return it points to the chain with the fragments.
755  * Return 0 if no error. If error, m_frag may contain a partially built
756  * chain of fragments that should be freed by the caller.
757  *
758  * if_hwassist_flags is the hw offload capabilities (see if_data.ifi_hwassist)
759  */
760 int
761 ip_fragment(struct ip *ip, struct mbuf **m_frag, int mtu,
762     u_long if_hwassist_flags)
763 {
764 	int error = 0;
765 	int hlen = ip->ip_hl << 2;
766 	int len = (mtu - hlen) & ~7;	/* size of payload in each fragment */
767 	int off;
768 	struct mbuf *m0 = *m_frag;	/* the original packet		*/
769 	int firstlen;
770 	struct mbuf **mnext;
771 	int nfrags;
772 	uint16_t ip_len, ip_off;
773 
774 	ip_len = ntohs(ip->ip_len);
775 	ip_off = ntohs(ip->ip_off);
776 
777 	if (ip_off & IP_DF) {	/* Fragmentation not allowed */
778 		IPSTAT_INC(ips_cantfrag);
779 		return EMSGSIZE;
780 	}
781 
782 	/*
783 	 * Must be able to put at least 8 bytes per fragment.
784 	 */
785 	if (len < 8)
786 		return EMSGSIZE;
787 
788 	/*
789 	 * If the interface will not calculate checksums on
790 	 * fragmented packets, then do it here.
791 	 */
792 	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
793 		in_delayed_cksum(m0);
794 		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
795 	}
796 #ifdef SCTP
797 	if (m0->m_pkthdr.csum_flags & CSUM_SCTP) {
798 		sctp_delayed_cksum(m0, hlen);
799 		m0->m_pkthdr.csum_flags &= ~CSUM_SCTP;
800 	}
801 #endif
802 	if (len > PAGE_SIZE) {
803 		/*
804 		 * Fragment large datagrams such that each segment
805 		 * contains a multiple of PAGE_SIZE amount of data,
806 		 * plus headers. This enables a receiver to perform
807 		 * page-flipping zero-copy optimizations.
808 		 *
809 		 * XXX When does this help given that sender and receiver
810 		 * could have different page sizes, and also mtu could
811 		 * be less than the receiver's page size ?
812 		 */
813 		int newlen;
814 
815 		off = MIN(mtu, m0->m_pkthdr.len);
816 
817 		/*
818 		 * firstlen (off - hlen) must be aligned on an
819 		 * 8-byte boundary
820 		 */
821 		if (off < hlen)
822 			goto smart_frag_failure;
823 		off = ((off - hlen) & ~7) + hlen;
824 		newlen = (~PAGE_MASK) & mtu;
825 		if ((newlen + sizeof (struct ip)) > mtu) {
826 			/* we failed, go back the default */
827 smart_frag_failure:
828 			newlen = len;
829 			off = hlen + len;
830 		}
831 		len = newlen;
832 
833 	} else {
834 		off = hlen + len;
835 	}
836 
837 	firstlen = off - hlen;
838 	mnext = &m0->m_nextpkt;		/* pointer to next packet */
839 
840 	/*
841 	 * Loop through length of segment after first fragment,
842 	 * make new header and copy data of each part and link onto chain.
843 	 * Here, m0 is the original packet, m is the fragment being created.
844 	 * The fragments are linked off the m_nextpkt of the original
845 	 * packet, which after processing serves as the first fragment.
846 	 */
847 	for (nfrags = 1; off < ip_len; off += len, nfrags++) {
848 		struct ip *mhip;	/* ip header on the fragment */
849 		struct mbuf *m;
850 		int mhlen = sizeof (struct ip);
851 
852 		m = m_gethdr(M_NOWAIT, MT_DATA);
853 		if (m == NULL) {
854 			error = ENOBUFS;
855 			IPSTAT_INC(ips_odropped);
856 			goto done;
857 		}
858 		/*
859 		 * Make sure the complete packet header gets copied
860 		 * from the originating mbuf to the newly created
861 		 * mbuf. This also ensures that existing firewall
862 		 * classification(s), VLAN tags and so on get copied
863 		 * to the resulting fragmented packet(s):
864 		 */
865 		if (m_dup_pkthdr(m, m0, M_NOWAIT) == 0) {
866 			m_free(m);
867 			error = ENOBUFS;
868 			IPSTAT_INC(ips_odropped);
869 			goto done;
870 		}
871 		/*
872 		 * In the first mbuf, leave room for the link header, then
873 		 * copy the original IP header including options. The payload
874 		 * goes into an additional mbuf chain returned by m_copym().
875 		 */
876 		m->m_data += max_linkhdr;
877 		mhip = mtod(m, struct ip *);
878 		*mhip = *ip;
879 		if (hlen > sizeof (struct ip)) {
880 			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
881 			mhip->ip_v = IPVERSION;
882 			mhip->ip_hl = mhlen >> 2;
883 		}
884 		m->m_len = mhlen;
885 		/* XXX do we need to add ip_off below ? */
886 		mhip->ip_off = ((off - hlen) >> 3) + ip_off;
887 		if (off + len >= ip_len)
888 			len = ip_len - off;
889 		else
890 			mhip->ip_off |= IP_MF;
891 		mhip->ip_len = htons((u_short)(len + mhlen));
892 		m->m_next = m_copym(m0, off, len, M_NOWAIT);
893 		if (m->m_next == NULL) {	/* copy failed */
894 			m_free(m);
895 			error = ENOBUFS;	/* ??? */
896 			IPSTAT_INC(ips_odropped);
897 			goto done;
898 		}
899 		m->m_pkthdr.len = mhlen + len;
900 #ifdef MAC
901 		mac_netinet_fragment(m0, m);
902 #endif
903 		mhip->ip_off = htons(mhip->ip_off);
904 		mhip->ip_sum = 0;
905 		if (m->m_pkthdr.csum_flags & CSUM_IP & ~if_hwassist_flags) {
906 			mhip->ip_sum = in_cksum(m, mhlen);
907 			m->m_pkthdr.csum_flags &= ~CSUM_IP;
908 		}
909 		*mnext = m;
910 		mnext = &m->m_nextpkt;
911 	}
912 	IPSTAT_ADD(ips_ofragments, nfrags);
913 
914 	/*
915 	 * Update first fragment by trimming what's been copied out
916 	 * and updating header.
917 	 */
918 	m_adj(m0, hlen + firstlen - ip_len);
919 	m0->m_pkthdr.len = hlen + firstlen;
920 	ip->ip_len = htons((u_short)m0->m_pkthdr.len);
921 	ip->ip_off = htons(ip_off | IP_MF);
922 	ip->ip_sum = 0;
923 	if (m0->m_pkthdr.csum_flags & CSUM_IP & ~if_hwassist_flags) {
924 		ip->ip_sum = in_cksum(m0, hlen);
925 		m0->m_pkthdr.csum_flags &= ~CSUM_IP;
926 	}
927 
928 done:
929 	*m_frag = m0;
930 	return error;
931 }
932 
933 void
934 in_delayed_cksum(struct mbuf *m)
935 {
936 	struct ip *ip;
937 	struct udphdr *uh;
938 	uint16_t cklen, csum, offset;
939 
940 	ip = mtod(m, struct ip *);
941 	offset = ip->ip_hl << 2 ;
942 
943 	if (m->m_pkthdr.csum_flags & CSUM_UDP) {
944 		/* if udp header is not in the first mbuf copy udplen */
945 		if (offset + sizeof(struct udphdr) > m->m_len) {
946 			m_copydata(m, offset + offsetof(struct udphdr,
947 			    uh_ulen), sizeof(cklen), (caddr_t)&cklen);
948 			cklen = ntohs(cklen);
949 		} else {
950 			uh = (struct udphdr *)mtodo(m, offset);
951 			cklen = ntohs(uh->uh_ulen);
952 		}
953 		csum = in_cksum_skip(m, cklen + offset, offset);
954 		if (csum == 0)
955 			csum = 0xffff;
956 	} else {
957 		cklen = ntohs(ip->ip_len);
958 		csum = in_cksum_skip(m, cklen, offset);
959 	}
960 	offset += m->m_pkthdr.csum_data;	/* checksum offset */
961 
962 	if (offset + sizeof(csum) > m->m_len)
963 		m_copyback(m, offset, sizeof(csum), (caddr_t)&csum);
964 	else
965 		*(u_short *)mtodo(m, offset) = csum;
966 }
967 
968 /*
969  * IP socket option processing.
970  */
971 int
972 ip_ctloutput(struct socket *so, struct sockopt *sopt)
973 {
974 	struct	inpcb *inp = sotoinpcb(so);
975 	int	error, optval;
976 #ifdef	RSS
977 	uint32_t rss_bucket;
978 	int retval;
979 #endif
980 
981 	error = optval = 0;
982 	if (sopt->sopt_level != IPPROTO_IP) {
983 		error = EINVAL;
984 
985 		if (sopt->sopt_level == SOL_SOCKET &&
986 		    sopt->sopt_dir == SOPT_SET) {
987 			switch (sopt->sopt_name) {
988 			case SO_REUSEADDR:
989 				INP_WLOCK(inp);
990 				if ((so->so_options & SO_REUSEADDR) != 0)
991 					inp->inp_flags2 |= INP_REUSEADDR;
992 				else
993 					inp->inp_flags2 &= ~INP_REUSEADDR;
994 				INP_WUNLOCK(inp);
995 				error = 0;
996 				break;
997 			case SO_REUSEPORT:
998 				INP_WLOCK(inp);
999 				if ((so->so_options & SO_REUSEPORT) != 0)
1000 					inp->inp_flags2 |= INP_REUSEPORT;
1001 				else
1002 					inp->inp_flags2 &= ~INP_REUSEPORT;
1003 				INP_WUNLOCK(inp);
1004 				error = 0;
1005 				break;
1006 			case SO_REUSEPORT_LB:
1007 				INP_WLOCK(inp);
1008 				if ((so->so_options & SO_REUSEPORT_LB) != 0)
1009 					inp->inp_flags2 |= INP_REUSEPORT_LB;
1010 				else
1011 					inp->inp_flags2 &= ~INP_REUSEPORT_LB;
1012 				INP_WUNLOCK(inp);
1013 				error = 0;
1014 				break;
1015 			case SO_SETFIB:
1016 				INP_WLOCK(inp);
1017 				inp->inp_inc.inc_fibnum = so->so_fibnum;
1018 				INP_WUNLOCK(inp);
1019 				error = 0;
1020 				break;
1021 			case SO_MAX_PACING_RATE:
1022 #ifdef RATELIMIT
1023 				INP_WLOCK(inp);
1024 				inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
1025 				INP_WUNLOCK(inp);
1026 				error = 0;
1027 #else
1028 				error = EOPNOTSUPP;
1029 #endif
1030 				break;
1031 			default:
1032 				break;
1033 			}
1034 		}
1035 		return (error);
1036 	}
1037 
1038 	switch (sopt->sopt_dir) {
1039 	case SOPT_SET:
1040 		switch (sopt->sopt_name) {
1041 		case IP_OPTIONS:
1042 #ifdef notyet
1043 		case IP_RETOPTS:
1044 #endif
1045 		{
1046 			struct mbuf *m;
1047 			if (sopt->sopt_valsize > MLEN) {
1048 				error = EMSGSIZE;
1049 				break;
1050 			}
1051 			m = m_get(sopt->sopt_td ? M_WAITOK : M_NOWAIT, MT_DATA);
1052 			if (m == NULL) {
1053 				error = ENOBUFS;
1054 				break;
1055 			}
1056 			m->m_len = sopt->sopt_valsize;
1057 			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
1058 					    m->m_len);
1059 			if (error) {
1060 				m_free(m);
1061 				break;
1062 			}
1063 			INP_WLOCK(inp);
1064 			error = ip_pcbopts(inp, sopt->sopt_name, m);
1065 			INP_WUNLOCK(inp);
1066 			return (error);
1067 		}
1068 
1069 		case IP_BINDANY:
1070 			if (sopt->sopt_td != NULL) {
1071 				error = priv_check(sopt->sopt_td,
1072 				    PRIV_NETINET_BINDANY);
1073 				if (error)
1074 					break;
1075 			}
1076 			/* FALLTHROUGH */
1077 		case IP_BINDMULTI:
1078 #ifdef	RSS
1079 		case IP_RSS_LISTEN_BUCKET:
1080 #endif
1081 		case IP_TOS:
1082 		case IP_TTL:
1083 		case IP_MINTTL:
1084 		case IP_RECVOPTS:
1085 		case IP_RECVRETOPTS:
1086 		case IP_ORIGDSTADDR:
1087 		case IP_RECVDSTADDR:
1088 		case IP_RECVTTL:
1089 		case IP_RECVIF:
1090 		case IP_ONESBCAST:
1091 		case IP_DONTFRAG:
1092 		case IP_RECVTOS:
1093 		case IP_RECVFLOWID:
1094 #ifdef	RSS
1095 		case IP_RECVRSSBUCKETID:
1096 #endif
1097 			error = sooptcopyin(sopt, &optval, sizeof optval,
1098 					    sizeof optval);
1099 			if (error)
1100 				break;
1101 
1102 			switch (sopt->sopt_name) {
1103 			case IP_TOS:
1104 				inp->inp_ip_tos = optval;
1105 				break;
1106 
1107 			case IP_TTL:
1108 				inp->inp_ip_ttl = optval;
1109 				break;
1110 
1111 			case IP_MINTTL:
1112 				if (optval >= 0 && optval <= MAXTTL)
1113 					inp->inp_ip_minttl = optval;
1114 				else
1115 					error = EINVAL;
1116 				break;
1117 
1118 #define	OPTSET(bit) do {						\
1119 	INP_WLOCK(inp);							\
1120 	if (optval)							\
1121 		inp->inp_flags |= bit;					\
1122 	else								\
1123 		inp->inp_flags &= ~bit;					\
1124 	INP_WUNLOCK(inp);						\
1125 } while (0)
1126 
1127 #define	OPTSET2(bit, val) do {						\
1128 	INP_WLOCK(inp);							\
1129 	if (val)							\
1130 		inp->inp_flags2 |= bit;					\
1131 	else								\
1132 		inp->inp_flags2 &= ~bit;				\
1133 	INP_WUNLOCK(inp);						\
1134 } while (0)
1135 
1136 			case IP_RECVOPTS:
1137 				OPTSET(INP_RECVOPTS);
1138 				break;
1139 
1140 			case IP_RECVRETOPTS:
1141 				OPTSET(INP_RECVRETOPTS);
1142 				break;
1143 
1144 			case IP_RECVDSTADDR:
1145 				OPTSET(INP_RECVDSTADDR);
1146 				break;
1147 
1148 			case IP_ORIGDSTADDR:
1149 				OPTSET2(INP_ORIGDSTADDR, optval);
1150 				break;
1151 
1152 			case IP_RECVTTL:
1153 				OPTSET(INP_RECVTTL);
1154 				break;
1155 
1156 			case IP_RECVIF:
1157 				OPTSET(INP_RECVIF);
1158 				break;
1159 
1160 			case IP_ONESBCAST:
1161 				OPTSET(INP_ONESBCAST);
1162 				break;
1163 			case IP_DONTFRAG:
1164 				OPTSET(INP_DONTFRAG);
1165 				break;
1166 			case IP_BINDANY:
1167 				OPTSET(INP_BINDANY);
1168 				break;
1169 			case IP_RECVTOS:
1170 				OPTSET(INP_RECVTOS);
1171 				break;
1172 			case IP_BINDMULTI:
1173 				OPTSET2(INP_BINDMULTI, optval);
1174 				break;
1175 			case IP_RECVFLOWID:
1176 				OPTSET2(INP_RECVFLOWID, optval);
1177 				break;
1178 #ifdef	RSS
1179 			case IP_RSS_LISTEN_BUCKET:
1180 				if ((optval >= 0) &&
1181 				    (optval < rss_getnumbuckets())) {
1182 					inp->inp_rss_listen_bucket = optval;
1183 					OPTSET2(INP_RSS_BUCKET_SET, 1);
1184 				} else {
1185 					error = EINVAL;
1186 				}
1187 				break;
1188 			case IP_RECVRSSBUCKETID:
1189 				OPTSET2(INP_RECVRSSBUCKETID, optval);
1190 				break;
1191 #endif
1192 			}
1193 			break;
1194 #undef OPTSET
1195 #undef OPTSET2
1196 
1197 		/*
1198 		 * Multicast socket options are processed by the in_mcast
1199 		 * module.
1200 		 */
1201 		case IP_MULTICAST_IF:
1202 		case IP_MULTICAST_VIF:
1203 		case IP_MULTICAST_TTL:
1204 		case IP_MULTICAST_LOOP:
1205 		case IP_ADD_MEMBERSHIP:
1206 		case IP_DROP_MEMBERSHIP:
1207 		case IP_ADD_SOURCE_MEMBERSHIP:
1208 		case IP_DROP_SOURCE_MEMBERSHIP:
1209 		case IP_BLOCK_SOURCE:
1210 		case IP_UNBLOCK_SOURCE:
1211 		case IP_MSFILTER:
1212 		case MCAST_JOIN_GROUP:
1213 		case MCAST_LEAVE_GROUP:
1214 		case MCAST_JOIN_SOURCE_GROUP:
1215 		case MCAST_LEAVE_SOURCE_GROUP:
1216 		case MCAST_BLOCK_SOURCE:
1217 		case MCAST_UNBLOCK_SOURCE:
1218 			error = inp_setmoptions(inp, sopt);
1219 			break;
1220 
1221 		case IP_PORTRANGE:
1222 			error = sooptcopyin(sopt, &optval, sizeof optval,
1223 					    sizeof optval);
1224 			if (error)
1225 				break;
1226 
1227 			INP_WLOCK(inp);
1228 			switch (optval) {
1229 			case IP_PORTRANGE_DEFAULT:
1230 				inp->inp_flags &= ~(INP_LOWPORT);
1231 				inp->inp_flags &= ~(INP_HIGHPORT);
1232 				break;
1233 
1234 			case IP_PORTRANGE_HIGH:
1235 				inp->inp_flags &= ~(INP_LOWPORT);
1236 				inp->inp_flags |= INP_HIGHPORT;
1237 				break;
1238 
1239 			case IP_PORTRANGE_LOW:
1240 				inp->inp_flags &= ~(INP_HIGHPORT);
1241 				inp->inp_flags |= INP_LOWPORT;
1242 				break;
1243 
1244 			default:
1245 				error = EINVAL;
1246 				break;
1247 			}
1248 			INP_WUNLOCK(inp);
1249 			break;
1250 
1251 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1252 		case IP_IPSEC_POLICY:
1253 			if (IPSEC_ENABLED(ipv4)) {
1254 				error = IPSEC_PCBCTL(ipv4, inp, sopt);
1255 				break;
1256 			}
1257 			/* FALLTHROUGH */
1258 #endif /* IPSEC */
1259 
1260 		default:
1261 			error = ENOPROTOOPT;
1262 			break;
1263 		}
1264 		break;
1265 
1266 	case SOPT_GET:
1267 		switch (sopt->sopt_name) {
1268 		case IP_OPTIONS:
1269 		case IP_RETOPTS:
1270 			INP_RLOCK(inp);
1271 			if (inp->inp_options) {
1272 				struct mbuf *options;
1273 
1274 				options = m_copym(inp->inp_options, 0,
1275 				    M_COPYALL, M_NOWAIT);
1276 				INP_RUNLOCK(inp);
1277 				if (options != NULL) {
1278 					error = sooptcopyout(sopt,
1279 							     mtod(options, char *),
1280 							     options->m_len);
1281 					m_freem(options);
1282 				} else
1283 					error = ENOMEM;
1284 			} else {
1285 				INP_RUNLOCK(inp);
1286 				sopt->sopt_valsize = 0;
1287 			}
1288 			break;
1289 
1290 		case IP_TOS:
1291 		case IP_TTL:
1292 		case IP_MINTTL:
1293 		case IP_RECVOPTS:
1294 		case IP_RECVRETOPTS:
1295 		case IP_ORIGDSTADDR:
1296 		case IP_RECVDSTADDR:
1297 		case IP_RECVTTL:
1298 		case IP_RECVIF:
1299 		case IP_PORTRANGE:
1300 		case IP_ONESBCAST:
1301 		case IP_DONTFRAG:
1302 		case IP_BINDANY:
1303 		case IP_RECVTOS:
1304 		case IP_BINDMULTI:
1305 		case IP_FLOWID:
1306 		case IP_FLOWTYPE:
1307 		case IP_RECVFLOWID:
1308 #ifdef	RSS
1309 		case IP_RSSBUCKETID:
1310 		case IP_RECVRSSBUCKETID:
1311 #endif
1312 			switch (sopt->sopt_name) {
1313 
1314 			case IP_TOS:
1315 				optval = inp->inp_ip_tos;
1316 				break;
1317 
1318 			case IP_TTL:
1319 				optval = inp->inp_ip_ttl;
1320 				break;
1321 
1322 			case IP_MINTTL:
1323 				optval = inp->inp_ip_minttl;
1324 				break;
1325 
1326 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1327 #define	OPTBIT2(bit)	(inp->inp_flags2 & bit ? 1 : 0)
1328 
1329 			case IP_RECVOPTS:
1330 				optval = OPTBIT(INP_RECVOPTS);
1331 				break;
1332 
1333 			case IP_RECVRETOPTS:
1334 				optval = OPTBIT(INP_RECVRETOPTS);
1335 				break;
1336 
1337 			case IP_RECVDSTADDR:
1338 				optval = OPTBIT(INP_RECVDSTADDR);
1339 				break;
1340 
1341 			case IP_ORIGDSTADDR:
1342 				optval = OPTBIT2(INP_ORIGDSTADDR);
1343 				break;
1344 
1345 			case IP_RECVTTL:
1346 				optval = OPTBIT(INP_RECVTTL);
1347 				break;
1348 
1349 			case IP_RECVIF:
1350 				optval = OPTBIT(INP_RECVIF);
1351 				break;
1352 
1353 			case IP_PORTRANGE:
1354 				if (inp->inp_flags & INP_HIGHPORT)
1355 					optval = IP_PORTRANGE_HIGH;
1356 				else if (inp->inp_flags & INP_LOWPORT)
1357 					optval = IP_PORTRANGE_LOW;
1358 				else
1359 					optval = 0;
1360 				break;
1361 
1362 			case IP_ONESBCAST:
1363 				optval = OPTBIT(INP_ONESBCAST);
1364 				break;
1365 			case IP_DONTFRAG:
1366 				optval = OPTBIT(INP_DONTFRAG);
1367 				break;
1368 			case IP_BINDANY:
1369 				optval = OPTBIT(INP_BINDANY);
1370 				break;
1371 			case IP_RECVTOS:
1372 				optval = OPTBIT(INP_RECVTOS);
1373 				break;
1374 			case IP_FLOWID:
1375 				optval = inp->inp_flowid;
1376 				break;
1377 			case IP_FLOWTYPE:
1378 				optval = inp->inp_flowtype;
1379 				break;
1380 			case IP_RECVFLOWID:
1381 				optval = OPTBIT2(INP_RECVFLOWID);
1382 				break;
1383 #ifdef	RSS
1384 			case IP_RSSBUCKETID:
1385 				retval = rss_hash2bucket(inp->inp_flowid,
1386 				    inp->inp_flowtype,
1387 				    &rss_bucket);
1388 				if (retval == 0)
1389 					optval = rss_bucket;
1390 				else
1391 					error = EINVAL;
1392 				break;
1393 			case IP_RECVRSSBUCKETID:
1394 				optval = OPTBIT2(INP_RECVRSSBUCKETID);
1395 				break;
1396 #endif
1397 			case IP_BINDMULTI:
1398 				optval = OPTBIT2(INP_BINDMULTI);
1399 				break;
1400 			}
1401 			error = sooptcopyout(sopt, &optval, sizeof optval);
1402 			break;
1403 
1404 		/*
1405 		 * Multicast socket options are processed by the in_mcast
1406 		 * module.
1407 		 */
1408 		case IP_MULTICAST_IF:
1409 		case IP_MULTICAST_VIF:
1410 		case IP_MULTICAST_TTL:
1411 		case IP_MULTICAST_LOOP:
1412 		case IP_MSFILTER:
1413 			error = inp_getmoptions(inp, sopt);
1414 			break;
1415 
1416 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1417 		case IP_IPSEC_POLICY:
1418 			if (IPSEC_ENABLED(ipv4)) {
1419 				error = IPSEC_PCBCTL(ipv4, inp, sopt);
1420 				break;
1421 			}
1422 			/* FALLTHROUGH */
1423 #endif /* IPSEC */
1424 
1425 		default:
1426 			error = ENOPROTOOPT;
1427 			break;
1428 		}
1429 		break;
1430 	}
1431 	return (error);
1432 }
1433 
1434 /*
1435  * Routine called from ip_output() to loop back a copy of an IP multicast
1436  * packet to the input queue of a specified interface.  Note that this
1437  * calls the output routine of the loopback "driver", but with an interface
1438  * pointer that might NOT be a loopback interface -- evil, but easier than
1439  * replicating that code here.
1440  */
1441 static void
1442 ip_mloopback(struct ifnet *ifp, const struct mbuf *m, int hlen)
1443 {
1444 	struct ip *ip;
1445 	struct mbuf *copym;
1446 
1447 	/*
1448 	 * Make a deep copy of the packet because we're going to
1449 	 * modify the pack in order to generate checksums.
1450 	 */
1451 	copym = m_dup(m, M_NOWAIT);
1452 	if (copym != NULL && (!M_WRITABLE(copym) || copym->m_len < hlen))
1453 		copym = m_pullup(copym, hlen);
1454 	if (copym != NULL) {
1455 		/* If needed, compute the checksum and mark it as valid. */
1456 		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1457 			in_delayed_cksum(copym);
1458 			copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1459 			copym->m_pkthdr.csum_flags |=
1460 			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1461 			copym->m_pkthdr.csum_data = 0xffff;
1462 		}
1463 		/*
1464 		 * We don't bother to fragment if the IP length is greater
1465 		 * than the interface's MTU.  Can this possibly matter?
1466 		 */
1467 		ip = mtod(copym, struct ip *);
1468 		ip->ip_sum = 0;
1469 		ip->ip_sum = in_cksum(copym, hlen);
1470 		if_simloop(ifp, copym, AF_INET, 0);
1471 	}
1472 }
1473