xref: /freebsd/sys/netinet6/ip6_output.c (revision a0409676120c1e558d0ade943019934e0f15118d)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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  *	$KAME: ip6_output.c,v 1.279 2002/01/26 06:12:30 jinmei Exp $
32  */
33 
34 /*-
35  * Copyright (c) 1982, 1986, 1988, 1990, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #include "opt_inet.h"
69 #include "opt_inet6.h"
70 #include "opt_ipsec.h"
71 #include "opt_kern_tls.h"
72 #include "opt_ratelimit.h"
73 #include "opt_route.h"
74 #include "opt_rss.h"
75 #include "opt_sctp.h"
76 
77 #include <sys/param.h>
78 #include <sys/kernel.h>
79 #include <sys/ktls.h>
80 #include <sys/malloc.h>
81 #include <sys/mbuf.h>
82 #include <sys/errno.h>
83 #include <sys/priv.h>
84 #include <sys/proc.h>
85 #include <sys/protosw.h>
86 #include <sys/socket.h>
87 #include <sys/socketvar.h>
88 #include <sys/syslog.h>
89 #include <sys/ucred.h>
90 
91 #include <machine/in_cksum.h>
92 
93 #include <net/if.h>
94 #include <net/if_var.h>
95 #include <net/if_vlan_var.h>
96 #include <net/if_llatbl.h>
97 #include <net/ethernet.h>
98 #include <net/netisr.h>
99 #include <net/route.h>
100 #include <net/route/nhop.h>
101 #include <net/pfil.h>
102 #include <net/rss_config.h>
103 #include <net/vnet.h>
104 
105 #include <netinet/in.h>
106 #include <netinet/in_var.h>
107 #include <netinet/ip_var.h>
108 #include <netinet6/in6_fib.h>
109 #include <netinet6/in6_var.h>
110 #include <netinet/ip6.h>
111 #include <netinet/icmp6.h>
112 #include <netinet6/ip6_var.h>
113 #include <netinet/in_pcb.h>
114 #include <netinet/tcp_var.h>
115 #include <netinet6/nd6.h>
116 #include <netinet6/in6_rss.h>
117 
118 #include <netipsec/ipsec_support.h>
119 #if defined(SCTP) || defined(SCTP_SUPPORT)
120 #include <netinet/sctp.h>
121 #include <netinet/sctp_crc32.h>
122 #endif
123 
124 #include <netinet6/ip6protosw.h>
125 #include <netinet6/scope6_var.h>
126 
127 extern int in6_mcast_loop;
128 
129 struct ip6_exthdrs {
130 	struct mbuf *ip6e_ip6;
131 	struct mbuf *ip6e_hbh;
132 	struct mbuf *ip6e_dest1;
133 	struct mbuf *ip6e_rthdr;
134 	struct mbuf *ip6e_dest2;
135 };
136 
137 static MALLOC_DEFINE(M_IP6OPT, "ip6opt", "IPv6 options");
138 
139 static int ip6_pcbopt(int, u_char *, int, struct ip6_pktopts **,
140 			   struct ucred *, int);
141 static int ip6_pcbopts(struct ip6_pktopts **, struct mbuf *,
142 	struct socket *, struct sockopt *);
143 static int ip6_getpcbopt(struct inpcb *, int, struct sockopt *);
144 static int ip6_setpktopt(int, u_char *, int, struct ip6_pktopts *,
145 	struct ucred *, int, int, int);
146 
147 static int ip6_copyexthdr(struct mbuf **, caddr_t, int);
148 static int ip6_insertfraghdr(struct mbuf *, struct mbuf *, int,
149 	struct ip6_frag **);
150 static int ip6_insert_jumboopt(struct ip6_exthdrs *, u_int32_t);
151 static int ip6_splithdr(struct mbuf *, struct ip6_exthdrs *);
152 static int ip6_getpmtu(struct route_in6 *, int,
153 	struct ifnet *, const struct in6_addr *, u_long *, int *, u_int,
154 	u_int);
155 static int ip6_calcmtu(struct ifnet *, const struct in6_addr *, u_long,
156 	u_long *, int *, u_int);
157 static int ip6_getpmtu_ctl(u_int, const struct in6_addr *, u_long *);
158 static int copypktopts(struct ip6_pktopts *, struct ip6_pktopts *, int);
159 
160 /*
161  * Make an extension header from option data.  hp is the source,
162  * mp is the destination, and _ol is the optlen.
163  */
164 #define	MAKE_EXTHDR(hp, mp, _ol)					\
165     do {								\
166 	if (hp) {							\
167 		struct ip6_ext *eh = (struct ip6_ext *)(hp);		\
168 		error = ip6_copyexthdr((mp), (caddr_t)(hp),		\
169 		    ((eh)->ip6e_len + 1) << 3);				\
170 		if (error)						\
171 			goto freehdrs;					\
172 		(_ol) += (*(mp))->m_len;				\
173 	}								\
174     } while (/*CONSTCOND*/ 0)
175 
176 /*
177  * Form a chain of extension headers.
178  * m is the extension header mbuf
179  * mp is the previous mbuf in the chain
180  * p is the next header
181  * i is the type of option.
182  */
183 #define MAKE_CHAIN(m, mp, p, i)\
184     do {\
185 	if (m) {\
186 		if (!hdrsplit) \
187 			panic("%s:%d: assumption failed: "\
188 			    "hdr not split: hdrsplit %d exthdrs %p",\
189 			    __func__, __LINE__, hdrsplit, &exthdrs);\
190 		*mtod((m), u_char *) = *(p);\
191 		*(p) = (i);\
192 		p = mtod((m), u_char *);\
193 		(m)->m_next = (mp)->m_next;\
194 		(mp)->m_next = (m);\
195 		(mp) = (m);\
196 	}\
197     } while (/*CONSTCOND*/ 0)
198 
199 void
200 in6_delayed_cksum(struct mbuf *m, uint32_t plen, u_short offset)
201 {
202 	u_short csum;
203 
204 	csum = in_cksum_skip(m, offset + plen, offset);
205 	if (m->m_pkthdr.csum_flags & CSUM_UDP_IPV6 && csum == 0)
206 		csum = 0xffff;
207 	offset += m->m_pkthdr.csum_data;	/* checksum offset */
208 
209 	if (offset + sizeof(csum) > m->m_len)
210 		m_copyback(m, offset, sizeof(csum), (caddr_t)&csum);
211 	else
212 		*(u_short *)mtodo(m, offset) = csum;
213 }
214 
215 static int
216 ip6_output_delayed_csum(struct mbuf *m, struct ifnet *ifp, int csum_flags,
217     int plen, int optlen, bool frag)
218 {
219 
220 	KASSERT((plen >= optlen), ("%s:%d: plen %d < optlen %d, m %p, ifp %p "
221 	    "csum_flags %#x frag %d\n",
222 	    __func__, __LINE__, plen, optlen, m, ifp, csum_flags, frag));
223 
224 	if ((csum_flags & CSUM_DELAY_DATA_IPV6) ||
225 #if defined(SCTP) || defined(SCTP_SUPPORT)
226 	    (csum_flags & CSUM_SCTP_IPV6) ||
227 #endif
228 	    (!frag && (ifp->if_capenable & IFCAP_MEXTPG) == 0)) {
229 		m = mb_unmapped_to_ext(m);
230 		if (m == NULL) {
231 			if (frag)
232 				in6_ifstat_inc(ifp, ifs6_out_fragfail);
233 			else
234 				IP6STAT_INC(ip6s_odropped);
235 			return (ENOBUFS);
236 		}
237 		if (csum_flags & CSUM_DELAY_DATA_IPV6) {
238 			in6_delayed_cksum(m, plen - optlen,
239 			    sizeof(struct ip6_hdr) + optlen);
240 			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA_IPV6;
241 		}
242 #if defined(SCTP) || defined(SCTP_SUPPORT)
243 		if (csum_flags & CSUM_SCTP_IPV6) {
244 			sctp_delayed_cksum(m, sizeof(struct ip6_hdr) + optlen);
245 			m->m_pkthdr.csum_flags &= ~CSUM_SCTP_IPV6;
246 		}
247 #endif
248 	}
249 
250 	return (0);
251 }
252 
253 int
254 ip6_fragment(struct ifnet *ifp, struct mbuf *m0, int hlen, u_char nextproto,
255     int fraglen , uint32_t id)
256 {
257 	struct mbuf *m, **mnext, *m_frgpart;
258 	struct ip6_hdr *ip6, *mhip6;
259 	struct ip6_frag *ip6f;
260 	int off;
261 	int error;
262 	int tlen = m0->m_pkthdr.len;
263 
264 	KASSERT((fraglen % 8 == 0), ("Fragment length must be a multiple of 8"));
265 
266 	m = m0;
267 	ip6 = mtod(m, struct ip6_hdr *);
268 	mnext = &m->m_nextpkt;
269 
270 	for (off = hlen; off < tlen; off += fraglen) {
271 		m = m_gethdr(M_NOWAIT, MT_DATA);
272 		if (!m) {
273 			IP6STAT_INC(ip6s_odropped);
274 			return (ENOBUFS);
275 		}
276 
277 		/*
278 		 * Make sure the complete packet header gets copied
279 		 * from the originating mbuf to the newly created
280 		 * mbuf. This also ensures that existing firewall
281 		 * classification(s), VLAN tags and so on get copied
282 		 * to the resulting fragmented packet(s):
283 		 */
284 		if (m_dup_pkthdr(m, m0, M_NOWAIT) == 0) {
285 			m_free(m);
286 			IP6STAT_INC(ip6s_odropped);
287 			return (ENOBUFS);
288 		}
289 
290 		*mnext = m;
291 		mnext = &m->m_nextpkt;
292 		m->m_data += max_linkhdr;
293 		mhip6 = mtod(m, struct ip6_hdr *);
294 		*mhip6 = *ip6;
295 		m->m_len = sizeof(*mhip6);
296 		error = ip6_insertfraghdr(m0, m, hlen, &ip6f);
297 		if (error) {
298 			IP6STAT_INC(ip6s_odropped);
299 			return (error);
300 		}
301 		ip6f->ip6f_offlg = htons((u_short)((off - hlen) & ~7));
302 		if (off + fraglen >= tlen)
303 			fraglen = tlen - off;
304 		else
305 			ip6f->ip6f_offlg |= IP6F_MORE_FRAG;
306 		mhip6->ip6_plen = htons((u_short)(fraglen + hlen +
307 		    sizeof(*ip6f) - sizeof(struct ip6_hdr)));
308 		if ((m_frgpart = m_copym(m0, off, fraglen, M_NOWAIT)) == NULL) {
309 			IP6STAT_INC(ip6s_odropped);
310 			return (ENOBUFS);
311 		}
312 		m_cat(m, m_frgpart);
313 		m->m_pkthdr.len = fraglen + hlen + sizeof(*ip6f);
314 		ip6f->ip6f_reserved = 0;
315 		ip6f->ip6f_ident = id;
316 		ip6f->ip6f_nxt = nextproto;
317 		IP6STAT_INC(ip6s_ofragments);
318 		in6_ifstat_inc(ifp, ifs6_out_fragcreat);
319 	}
320 
321 	return (0);
322 }
323 
324 static int
325 ip6_output_send(struct inpcb *inp, struct ifnet *ifp, struct ifnet *origifp,
326     struct mbuf *m, struct sockaddr_in6 *dst, struct route_in6 *ro,
327     bool stamp_tag)
328 {
329 #ifdef KERN_TLS
330 	struct ktls_session *tls = NULL;
331 #endif
332 	struct m_snd_tag *mst;
333 	int error;
334 
335 	MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
336 	mst = NULL;
337 
338 #ifdef KERN_TLS
339 	/*
340 	 * If this is an unencrypted TLS record, save a reference to
341 	 * the record.  This local reference is used to call
342 	 * ktls_output_eagain after the mbuf has been freed (thus
343 	 * dropping the mbuf's reference) in if_output.
344 	 */
345 	if (m->m_next != NULL && mbuf_has_tls_session(m->m_next)) {
346 		tls = ktls_hold(m->m_next->m_epg_tls);
347 		mst = tls->snd_tag;
348 
349 		/*
350 		 * If a TLS session doesn't have a valid tag, it must
351 		 * have had an earlier ifp mismatch, so drop this
352 		 * packet.
353 		 */
354 		if (mst == NULL) {
355 			error = EAGAIN;
356 			goto done;
357 		}
358 		/*
359 		 * Always stamp tags that include NIC ktls.
360 		 */
361 		stamp_tag = true;
362 	}
363 #endif
364 #ifdef RATELIMIT
365 	if (inp != NULL && mst == NULL) {
366 		if ((inp->inp_flags2 & INP_RATE_LIMIT_CHANGED) != 0 ||
367 		    (inp->inp_snd_tag != NULL &&
368 		    inp->inp_snd_tag->ifp != ifp))
369 			in_pcboutput_txrtlmt(inp, ifp, m);
370 
371 		if (inp->inp_snd_tag != NULL)
372 			mst = inp->inp_snd_tag;
373 	}
374 #endif
375 	if (stamp_tag && mst != NULL) {
376 		KASSERT(m->m_pkthdr.rcvif == NULL,
377 		    ("trying to add a send tag to a forwarded packet"));
378 		if (mst->ifp != ifp) {
379 			error = EAGAIN;
380 			goto done;
381 		}
382 
383 		/* stamp send tag on mbuf */
384 		m->m_pkthdr.snd_tag = m_snd_tag_ref(mst);
385 		m->m_pkthdr.csum_flags |= CSUM_SND_TAG;
386 	}
387 
388 	error = nd6_output_ifp(ifp, origifp, m, dst, (struct route *)ro);
389 
390 done:
391 	/* Check for route change invalidating send tags. */
392 #ifdef KERN_TLS
393 	if (tls != NULL) {
394 		if (error == EAGAIN)
395 			error = ktls_output_eagain(inp, tls);
396 		ktls_free(tls);
397 	}
398 #endif
399 #ifdef RATELIMIT
400 	if (error == EAGAIN)
401 		in_pcboutput_eagain(inp);
402 #endif
403 	return (error);
404 }
405 
406 /*
407  * IP6 output.
408  * The packet in mbuf chain m contains a skeletal IP6 header (with pri, len,
409  * nxt, hlim, src, dst).
410  * This function may modify ver and hlim only.
411  * The mbuf chain containing the packet will be freed.
412  * The mbuf opt, if present, will not be freed.
413  * If route_in6 ro is present and has ro_nh initialized, route lookup would be
414  * skipped and ro->ro_nh would be used. If ro is present but ro->ro_nh is NULL,
415  * then result of route lookup is stored in ro->ro_nh.
416  *
417  * Type of "mtu": rt_mtu is u_long, ifnet.ifr_mtu is int, and nd_ifinfo.linkmtu
418  * is uint32_t.  So we use u_long to hold largest one, which is rt_mtu.
419  *
420  * ifpp - XXX: just for statistics
421  */
422 int
423 ip6_output(struct mbuf *m0, struct ip6_pktopts *opt,
424     struct route_in6 *ro, int flags, struct ip6_moptions *im6o,
425     struct ifnet **ifpp, struct inpcb *inp)
426 {
427 	struct ip6_hdr *ip6;
428 	struct ifnet *ifp, *origifp;
429 	struct mbuf *m = m0;
430 	struct mbuf *mprev;
431 	struct route_in6 *ro_pmtu;
432 	struct nhop_object *nh;
433 	struct sockaddr_in6 *dst, sin6, src_sa, dst_sa;
434 	struct in6_addr odst;
435 	u_char *nexthdrp;
436 	int tlen, len;
437 	int error = 0;
438 	int vlan_pcp = -1;
439 	struct in6_ifaddr *ia = NULL;
440 	u_long mtu;
441 	int alwaysfrag, dontfrag;
442 	u_int32_t optlen, plen = 0, unfragpartlen;
443 	struct ip6_exthdrs exthdrs;
444 	struct in6_addr src0, dst0;
445 	u_int32_t zone;
446 	bool hdrsplit;
447 	int sw_csum, tso;
448 	int needfiblookup;
449 	uint32_t fibnum;
450 	struct m_tag *fwd_tag = NULL;
451 	uint32_t id;
452 
453 	NET_EPOCH_ASSERT();
454 
455 	if (inp != NULL) {
456 		INP_LOCK_ASSERT(inp);
457 		M_SETFIB(m, inp->inp_inc.inc_fibnum);
458 		if ((flags & IP_NODEFAULTFLOWID) == 0) {
459 			/* Unconditionally set flowid. */
460 			m->m_pkthdr.flowid = inp->inp_flowid;
461 			M_HASHTYPE_SET(m, inp->inp_flowtype);
462 		}
463 		if ((inp->inp_flags2 & INP_2PCP_SET) != 0)
464 			vlan_pcp = (inp->inp_flags2 & INP_2PCP_MASK) >>
465 			    INP_2PCP_SHIFT;
466 #ifdef NUMA
467 		m->m_pkthdr.numa_domain = inp->inp_numa_domain;
468 #endif
469 	}
470 
471 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
472 	/*
473 	 * IPSec checking which handles several cases.
474 	 * FAST IPSEC: We re-injected the packet.
475 	 * XXX: need scope argument.
476 	 */
477 	if (IPSEC_ENABLED(ipv6)) {
478 		if ((error = IPSEC_OUTPUT(ipv6, m, inp)) != 0) {
479 			if (error == EINPROGRESS)
480 				error = 0;
481 			goto done;
482 		}
483 	}
484 #endif /* IPSEC */
485 
486 	/* Source address validation. */
487 	ip6 = mtod(m, struct ip6_hdr *);
488 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src) &&
489 	    (flags & IPV6_UNSPECSRC) == 0) {
490 		error = EOPNOTSUPP;
491 		IP6STAT_INC(ip6s_badscope);
492 		goto bad;
493 	}
494 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
495 		error = EOPNOTSUPP;
496 		IP6STAT_INC(ip6s_badscope);
497 		goto bad;
498 	}
499 
500 	/*
501 	 * If we are given packet options to add extension headers prepare them.
502 	 * Calculate the total length of the extension header chain.
503 	 * Keep the length of the unfragmentable part for fragmentation.
504 	 */
505 	bzero(&exthdrs, sizeof(exthdrs));
506 	optlen = 0;
507 	unfragpartlen = sizeof(struct ip6_hdr);
508 	if (opt) {
509 		/* Hop-by-Hop options header. */
510 		MAKE_EXTHDR(opt->ip6po_hbh, &exthdrs.ip6e_hbh, optlen);
511 
512 		/* Destination options header (1st part). */
513 		if (opt->ip6po_rthdr) {
514 #ifndef RTHDR_SUPPORT_IMPLEMENTED
515 			/*
516 			 * If there is a routing header, discard the packet
517 			 * right away here. RH0/1 are obsolete and we do not
518 			 * currently support RH2/3/4.
519 			 * People trying to use RH253/254 may want to disable
520 			 * this check.
521 			 * The moment we do support any routing header (again)
522 			 * this block should check the routing type more
523 			 * selectively.
524 			 */
525 			error = EINVAL;
526 			goto bad;
527 #endif
528 
529 			/*
530 			 * Destination options header (1st part).
531 			 * This only makes sense with a routing header.
532 			 * See Section 9.2 of RFC 3542.
533 			 * Disabling this part just for MIP6 convenience is
534 			 * a bad idea.  We need to think carefully about a
535 			 * way to make the advanced API coexist with MIP6
536 			 * options, which might automatically be inserted in
537 			 * the kernel.
538 			 */
539 			MAKE_EXTHDR(opt->ip6po_dest1, &exthdrs.ip6e_dest1,
540 			    optlen);
541 		}
542 		/* Routing header. */
543 		MAKE_EXTHDR(opt->ip6po_rthdr, &exthdrs.ip6e_rthdr, optlen);
544 
545 		unfragpartlen += optlen;
546 
547 		/*
548 		 * NOTE: we don't add AH/ESP length here (done in
549 		 * ip6_ipsec_output()).
550 		 */
551 
552 		/* Destination options header (2nd part). */
553 		MAKE_EXTHDR(opt->ip6po_dest2, &exthdrs.ip6e_dest2, optlen);
554 	}
555 
556 	/*
557 	 * If there is at least one extension header,
558 	 * separate IP6 header from the payload.
559 	 */
560 	hdrsplit = false;
561 	if (optlen) {
562 		if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
563 			m = NULL;
564 			goto freehdrs;
565 		}
566 		m = exthdrs.ip6e_ip6;
567 		ip6 = mtod(m, struct ip6_hdr *);
568 		hdrsplit = true;
569 	}
570 
571 	/* Adjust mbuf packet header length. */
572 	m->m_pkthdr.len += optlen;
573 	plen = m->m_pkthdr.len - sizeof(*ip6);
574 
575 	/* If this is a jumbo payload, insert a jumbo payload option. */
576 	if (plen > IPV6_MAXPACKET) {
577 		if (!hdrsplit) {
578 			if ((error = ip6_splithdr(m, &exthdrs)) != 0) {
579 				m = NULL;
580 				goto freehdrs;
581 			}
582 			m = exthdrs.ip6e_ip6;
583 			ip6 = mtod(m, struct ip6_hdr *);
584 			hdrsplit = true;
585 		}
586 		if ((error = ip6_insert_jumboopt(&exthdrs, plen)) != 0)
587 			goto freehdrs;
588 		ip6->ip6_plen = 0;
589 	} else
590 		ip6->ip6_plen = htons(plen);
591 	nexthdrp = &ip6->ip6_nxt;
592 
593 	if (optlen) {
594 		/*
595 		 * Concatenate headers and fill in next header fields.
596 		 * Here we have, on "m"
597 		 *	IPv6 payload
598 		 * and we insert headers accordingly.
599 		 * Finally, we should be getting:
600 		 *	IPv6 hbh dest1 rthdr ah* [esp* dest2 payload].
601 		 *
602 		 * During the header composing process "m" points to IPv6
603 		 * header.  "mprev" points to an extension header prior to esp.
604 		 */
605 		mprev = m;
606 
607 		/*
608 		 * We treat dest2 specially.  This makes IPsec processing
609 		 * much easier.  The goal here is to make mprev point the
610 		 * mbuf prior to dest2.
611 		 *
612 		 * Result: IPv6 dest2 payload.
613 		 * m and mprev will point to IPv6 header.
614 		 */
615 		if (exthdrs.ip6e_dest2) {
616 			if (!hdrsplit)
617 				panic("%s:%d: assumption failed: "
618 				    "hdr not split: hdrsplit %d exthdrs %p",
619 				    __func__, __LINE__, hdrsplit, &exthdrs);
620 			exthdrs.ip6e_dest2->m_next = m->m_next;
621 			m->m_next = exthdrs.ip6e_dest2;
622 			*mtod(exthdrs.ip6e_dest2, u_char *) = ip6->ip6_nxt;
623 			ip6->ip6_nxt = IPPROTO_DSTOPTS;
624 		}
625 
626 		/*
627 		 * Result: IPv6 hbh dest1 rthdr dest2 payload.
628 		 * m will point to IPv6 header.  mprev will point to the
629 		 * extension header prior to dest2 (rthdr in the above case).
630 		 */
631 		MAKE_CHAIN(exthdrs.ip6e_hbh, mprev, nexthdrp, IPPROTO_HOPOPTS);
632 		MAKE_CHAIN(exthdrs.ip6e_dest1, mprev, nexthdrp,
633 			   IPPROTO_DSTOPTS);
634 		MAKE_CHAIN(exthdrs.ip6e_rthdr, mprev, nexthdrp,
635 			   IPPROTO_ROUTING);
636 	}
637 
638 	IP6STAT_INC(ip6s_localout);
639 
640 	/* Route packet. */
641 	ro_pmtu = ro;
642 	if (opt && opt->ip6po_rthdr)
643 		ro = &opt->ip6po_route;
644 	if (ro != NULL)
645 		dst = (struct sockaddr_in6 *)&ro->ro_dst;
646 	else
647 		dst = &sin6;
648 	fibnum = (inp != NULL) ? inp->inp_inc.inc_fibnum : M_GETFIB(m);
649 
650 again:
651 	/*
652 	 * If specified, try to fill in the traffic class field.
653 	 * Do not override if a non-zero value is already set.
654 	 * We check the diffserv field and the ECN field separately.
655 	 */
656 	if (opt && opt->ip6po_tclass >= 0) {
657 		int mask = 0;
658 
659 		if (IPV6_DSCP(ip6) == 0)
660 			mask |= 0xfc;
661 		if (IPV6_ECN(ip6) == 0)
662 			mask |= 0x03;
663 		if (mask != 0)
664 			ip6->ip6_flow |= htonl((opt->ip6po_tclass & mask) << 20);
665 	}
666 
667 	/* Fill in or override the hop limit field, if necessary. */
668 	if (opt && opt->ip6po_hlim != -1)
669 		ip6->ip6_hlim = opt->ip6po_hlim & 0xff;
670 	else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
671 		if (im6o != NULL)
672 			ip6->ip6_hlim = im6o->im6o_multicast_hlim;
673 		else
674 			ip6->ip6_hlim = V_ip6_defmcasthlim;
675 	}
676 
677 	if (ro == NULL || ro->ro_nh == NULL) {
678 		bzero(dst, sizeof(*dst));
679 		dst->sin6_family = AF_INET6;
680 		dst->sin6_len = sizeof(*dst);
681 		dst->sin6_addr = ip6->ip6_dst;
682 	}
683 	/*
684 	 * Validate route against routing table changes.
685 	 * Make sure that the address family is set in route.
686 	 */
687 	nh = NULL;
688 	ifp = NULL;
689 	mtu = 0;
690 	if (ro != NULL) {
691 		if (ro->ro_nh != NULL && inp != NULL) {
692 			ro->ro_dst.sin6_family = AF_INET6; /* XXX KASSERT? */
693 			NH_VALIDATE((struct route *)ro, &inp->inp_rt_cookie,
694 			    fibnum);
695 		}
696 		if (ro->ro_nh != NULL && fwd_tag == NULL &&
697 		    (!NH_IS_VALID(ro->ro_nh) ||
698 		    ro->ro_dst.sin6_family != AF_INET6 ||
699 		    !IN6_ARE_ADDR_EQUAL(&ro->ro_dst.sin6_addr, &ip6->ip6_dst)))
700 			RO_INVALIDATE_CACHE(ro);
701 
702 		if (ro->ro_nh != NULL && fwd_tag == NULL &&
703 		    ro->ro_dst.sin6_family == AF_INET6 &&
704 		    IN6_ARE_ADDR_EQUAL(&ro->ro_dst.sin6_addr, &ip6->ip6_dst)) {
705 			nh = ro->ro_nh;
706 			ifp = nh->nh_ifp;
707 		} else {
708 			if (ro->ro_lle)
709 				LLE_FREE(ro->ro_lle);	/* zeros ro_lle */
710 			ro->ro_lle = NULL;
711 			if (fwd_tag == NULL) {
712 				bzero(&dst_sa, sizeof(dst_sa));
713 				dst_sa.sin6_family = AF_INET6;
714 				dst_sa.sin6_len = sizeof(dst_sa);
715 				dst_sa.sin6_addr = ip6->ip6_dst;
716 			}
717 			error = in6_selectroute(&dst_sa, opt, im6o, ro, &ifp,
718 			    &nh, fibnum, m->m_pkthdr.flowid);
719 			if (error != 0) {
720 				IP6STAT_INC(ip6s_noroute);
721 				if (ifp != NULL)
722 					in6_ifstat_inc(ifp, ifs6_out_discard);
723 				goto bad;
724 			}
725 			if (ifp != NULL)
726 			    mtu = ifp->if_mtu;
727 		}
728 		if (nh == NULL) {
729 			/*
730 			 * If in6_selectroute() does not return a nexthop
731 			 * dst may not have been updated.
732 			 */
733 			*dst = dst_sa;	/* XXX */
734 		} else {
735 			if (nh->nh_flags & NHF_HOST)
736 			    mtu = nh->nh_mtu;
737 			ia = (struct in6_ifaddr *)(nh->nh_ifa);
738 			counter_u64_add(nh->nh_pksent, 1);
739 		}
740 	} else {
741 		struct nhop_object *nh;
742 		struct in6_addr kdst;
743 		uint32_t scopeid;
744 
745 		if (fwd_tag == NULL) {
746 			bzero(&dst_sa, sizeof(dst_sa));
747 			dst_sa.sin6_family = AF_INET6;
748 			dst_sa.sin6_len = sizeof(dst_sa);
749 			dst_sa.sin6_addr = ip6->ip6_dst;
750 		}
751 
752 		if (IN6_IS_ADDR_MULTICAST(&dst_sa.sin6_addr) &&
753 		    im6o != NULL &&
754 		    (ifp = im6o->im6o_multicast_ifp) != NULL) {
755 			/* We do not need a route lookup. */
756 			*dst = dst_sa;	/* XXX */
757 			goto nonh6lookup;
758 		}
759 
760 		in6_splitscope(&dst_sa.sin6_addr, &kdst, &scopeid);
761 
762 		if (IN6_IS_ADDR_MC_LINKLOCAL(&dst_sa.sin6_addr) ||
763 		    IN6_IS_ADDR_MC_NODELOCAL(&dst_sa.sin6_addr)) {
764 			if (scopeid > 0) {
765 				ifp = in6_getlinkifnet(scopeid);
766 				if (ifp == NULL) {
767 					error = EHOSTUNREACH;
768 					goto bad;
769 				}
770 				*dst = dst_sa;	/* XXX */
771 				goto nonh6lookup;
772 			}
773 		}
774 
775 		nh = fib6_lookup(fibnum, &kdst, scopeid, NHR_NONE,
776 		    m->m_pkthdr.flowid);
777 		if (nh == NULL) {
778 			IP6STAT_INC(ip6s_noroute);
779 			/* No ifp in6_ifstat_inc(ifp, ifs6_out_discard); */
780 			error = EHOSTUNREACH;;
781 			goto bad;
782 		}
783 
784 		ifp = nh->nh_ifp;
785 		mtu = nh->nh_mtu;
786 		ia = ifatoia6(nh->nh_ifa);
787 		if (nh->nh_flags & NHF_GATEWAY)
788 			dst->sin6_addr = nh->gw6_sa.sin6_addr;
789 nonh6lookup:
790 		;
791 	}
792 
793 	/* Then nh (for unicast) and ifp must be non-NULL valid values. */
794 	if ((flags & IPV6_FORWARDING) == 0) {
795 		/* XXX: the FORWARDING flag can be set for mrouting. */
796 		in6_ifstat_inc(ifp, ifs6_out_request);
797 	}
798 
799 	/* Setup data structures for scope ID checks. */
800 	src0 = ip6->ip6_src;
801 	bzero(&src_sa, sizeof(src_sa));
802 	src_sa.sin6_family = AF_INET6;
803 	src_sa.sin6_len = sizeof(src_sa);
804 	src_sa.sin6_addr = ip6->ip6_src;
805 
806 	dst0 = ip6->ip6_dst;
807 	/* Re-initialize to be sure. */
808 	bzero(&dst_sa, sizeof(dst_sa));
809 	dst_sa.sin6_family = AF_INET6;
810 	dst_sa.sin6_len = sizeof(dst_sa);
811 	dst_sa.sin6_addr = ip6->ip6_dst;
812 
813 	/* Check for valid scope ID. */
814 	if (in6_setscope(&src0, ifp, &zone) == 0 &&
815 	    sa6_recoverscope(&src_sa) == 0 && zone == src_sa.sin6_scope_id &&
816 	    in6_setscope(&dst0, ifp, &zone) == 0 &&
817 	    sa6_recoverscope(&dst_sa) == 0 && zone == dst_sa.sin6_scope_id) {
818 		/*
819 		 * The outgoing interface is in the zone of the source
820 		 * and destination addresses.
821 		 *
822 		 * Because the loopback interface cannot receive
823 		 * packets with a different scope ID than its own,
824 		 * there is a trick to pretend the outgoing packet
825 		 * was received by the real network interface, by
826 		 * setting "origifp" different from "ifp". This is
827 		 * only allowed when "ifp" is a loopback network
828 		 * interface. Refer to code in nd6_output_ifp() for
829 		 * more details.
830 		 */
831 		origifp = ifp;
832 
833 		/*
834 		 * We should use ia_ifp to support the case of sending
835 		 * packets to an address of our own.
836 		 */
837 		if (ia != NULL && ia->ia_ifp)
838 			ifp = ia->ia_ifp;
839 
840 	} else if ((ifp->if_flags & IFF_LOOPBACK) == 0 ||
841 	    sa6_recoverscope(&src_sa) != 0 ||
842 	    sa6_recoverscope(&dst_sa) != 0 ||
843 	    dst_sa.sin6_scope_id == 0 ||
844 	    (src_sa.sin6_scope_id != 0 &&
845 	    src_sa.sin6_scope_id != dst_sa.sin6_scope_id) ||
846 	    (origifp = ifnet_byindex(dst_sa.sin6_scope_id)) == NULL) {
847 		/*
848 		 * If the destination network interface is not a
849 		 * loopback interface, or the destination network
850 		 * address has no scope ID, or the source address has
851 		 * a scope ID set which is different from the
852 		 * destination address one, or there is no network
853 		 * interface representing this scope ID, the address
854 		 * pair is considered invalid.
855 		 */
856 		IP6STAT_INC(ip6s_badscope);
857 		in6_ifstat_inc(ifp, ifs6_out_discard);
858 		if (error == 0)
859 			error = EHOSTUNREACH; /* XXX */
860 		goto bad;
861 	}
862 	/* All scope ID checks are successful. */
863 
864 	if (nh && !IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
865 		if (opt && opt->ip6po_nextroute.ro_nh) {
866 			/*
867 			 * The nexthop is explicitly specified by the
868 			 * application.  We assume the next hop is an IPv6
869 			 * address.
870 			 */
871 			dst = (struct sockaddr_in6 *)opt->ip6po_nexthop;
872 		}
873 		else if ((nh->nh_flags & NHF_GATEWAY))
874 			dst = &nh->gw6_sa;
875 	}
876 
877 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
878 		m->m_flags &= ~(M_BCAST | M_MCAST); /* Just in case. */
879 	} else {
880 		m->m_flags = (m->m_flags & ~M_BCAST) | M_MCAST;
881 		in6_ifstat_inc(ifp, ifs6_out_mcast);
882 
883 		/* Confirm that the outgoing interface supports multicast. */
884 		if (!(ifp->if_flags & IFF_MULTICAST)) {
885 			IP6STAT_INC(ip6s_noroute);
886 			in6_ifstat_inc(ifp, ifs6_out_discard);
887 			error = ENETUNREACH;
888 			goto bad;
889 		}
890 		if ((im6o == NULL && in6_mcast_loop) ||
891 		    (im6o && im6o->im6o_multicast_loop)) {
892 			/*
893 			 * Loop back multicast datagram if not expressly
894 			 * forbidden to do so, even if we have not joined
895 			 * the address; protocols will filter it later,
896 			 * thus deferring a hash lookup and lock acquisition
897 			 * at the expense of an m_copym().
898 			 */
899 			ip6_mloopback(ifp, m);
900 		} else {
901 			/*
902 			 * If we are acting as a multicast router, perform
903 			 * multicast forwarding as if the packet had just
904 			 * arrived on the interface to which we are about
905 			 * to send.  The multicast forwarding function
906 			 * recursively calls this function, using the
907 			 * IPV6_FORWARDING flag to prevent infinite recursion.
908 			 *
909 			 * Multicasts that are looped back by ip6_mloopback(),
910 			 * above, will be forwarded by the ip6_input() routine,
911 			 * if necessary.
912 			 */
913 			if (V_ip6_mrouter && (flags & IPV6_FORWARDING) == 0) {
914 				/*
915 				 * XXX: ip6_mforward expects that rcvif is NULL
916 				 * when it is called from the originating path.
917 				 * However, it may not always be the case.
918 				 */
919 				m->m_pkthdr.rcvif = NULL;
920 				if (ip6_mforward(ip6, ifp, m) != 0) {
921 					m_freem(m);
922 					goto done;
923 				}
924 			}
925 		}
926 		/*
927 		 * Multicasts with a hoplimit of zero may be looped back,
928 		 * above, but must not be transmitted on a network.
929 		 * Also, multicasts addressed to the loopback interface
930 		 * are not sent -- the above call to ip6_mloopback() will
931 		 * loop back a copy if this host actually belongs to the
932 		 * destination group on the loopback interface.
933 		 */
934 		if (ip6->ip6_hlim == 0 || (ifp->if_flags & IFF_LOOPBACK) ||
935 		    IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst)) {
936 			m_freem(m);
937 			goto done;
938 		}
939 	}
940 
941 	/*
942 	 * Fill the outgoing inteface to tell the upper layer
943 	 * to increment per-interface statistics.
944 	 */
945 	if (ifpp)
946 		*ifpp = ifp;
947 
948 	/* Determine path MTU. */
949 	if ((error = ip6_getpmtu(ro_pmtu, ro != ro_pmtu, ifp, &ip6->ip6_dst,
950 		    &mtu, &alwaysfrag, fibnum, *nexthdrp)) != 0)
951 		goto bad;
952 	KASSERT(mtu > 0, ("%s:%d: mtu %ld, ro_pmtu %p ro %p ifp %p "
953 	    "alwaysfrag %d fibnum %u\n", __func__, __LINE__, mtu, ro_pmtu, ro,
954 	    ifp, alwaysfrag, fibnum));
955 
956 	/*
957 	 * The caller of this function may specify to use the minimum MTU
958 	 * in some cases.
959 	 * An advanced API option (IPV6_USE_MIN_MTU) can also override MTU
960 	 * setting.  The logic is a bit complicated; by default, unicast
961 	 * packets will follow path MTU while multicast packets will be sent at
962 	 * the minimum MTU.  If IP6PO_MINMTU_ALL is specified, all packets
963 	 * including unicast ones will be sent at the minimum MTU.  Multicast
964 	 * packets will always be sent at the minimum MTU unless
965 	 * IP6PO_MINMTU_DISABLE is explicitly specified.
966 	 * See RFC 3542 for more details.
967 	 */
968 	if (mtu > IPV6_MMTU) {
969 		if ((flags & IPV6_MINMTU))
970 			mtu = IPV6_MMTU;
971 		else if (opt && opt->ip6po_minmtu == IP6PO_MINMTU_ALL)
972 			mtu = IPV6_MMTU;
973 		else if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) &&
974 			 (opt == NULL ||
975 			  opt->ip6po_minmtu != IP6PO_MINMTU_DISABLE)) {
976 			mtu = IPV6_MMTU;
977 		}
978 	}
979 
980 	/*
981 	 * Clear embedded scope identifiers if necessary.
982 	 * in6_clearscope() will touch the addresses only when necessary.
983 	 */
984 	in6_clearscope(&ip6->ip6_src);
985 	in6_clearscope(&ip6->ip6_dst);
986 
987 	/*
988 	 * If the outgoing packet contains a hop-by-hop options header,
989 	 * it must be examined and processed even by the source node.
990 	 * (RFC 2460, section 4.)
991 	 */
992 	if (exthdrs.ip6e_hbh) {
993 		struct ip6_hbh *hbh = mtod(exthdrs.ip6e_hbh, struct ip6_hbh *);
994 		u_int32_t dummy; /* XXX unused */
995 		u_int32_t plen = 0; /* XXX: ip6_process will check the value */
996 
997 #ifdef DIAGNOSTIC
998 		if ((hbh->ip6h_len + 1) << 3 > exthdrs.ip6e_hbh->m_len)
999 			panic("ip6e_hbh is not contiguous");
1000 #endif
1001 		/*
1002 		 *  XXX: if we have to send an ICMPv6 error to the sender,
1003 		 *       we need the M_LOOP flag since icmp6_error() expects
1004 		 *       the IPv6 and the hop-by-hop options header are
1005 		 *       contiguous unless the flag is set.
1006 		 */
1007 		m->m_flags |= M_LOOP;
1008 		m->m_pkthdr.rcvif = ifp;
1009 		if (ip6_process_hopopts(m, (u_int8_t *)(hbh + 1),
1010 		    ((hbh->ip6h_len + 1) << 3) - sizeof(struct ip6_hbh),
1011 		    &dummy, &plen) < 0) {
1012 			/* m was already freed at this point. */
1013 			error = EINVAL;/* better error? */
1014 			goto done;
1015 		}
1016 		m->m_flags &= ~M_LOOP; /* XXX */
1017 		m->m_pkthdr.rcvif = NULL;
1018 	}
1019 
1020 	/* Jump over all PFIL processing if hooks are not active. */
1021 	if (!PFIL_HOOKED_OUT(V_inet6_pfil_head))
1022 		goto passout;
1023 
1024 	odst = ip6->ip6_dst;
1025 	/* Run through list of hooks for output packets. */
1026 	switch (pfil_run_hooks(V_inet6_pfil_head, &m, ifp, PFIL_OUT, inp)) {
1027 	case PFIL_PASS:
1028 		ip6 = mtod(m, struct ip6_hdr *);
1029 		break;
1030 	case PFIL_DROPPED:
1031 		error = EACCES;
1032 		/* FALLTHROUGH */
1033 	case PFIL_CONSUMED:
1034 		goto done;
1035 	}
1036 
1037 	needfiblookup = 0;
1038 	/* See if destination IP address was changed by packet filter. */
1039 	if (!IN6_ARE_ADDR_EQUAL(&odst, &ip6->ip6_dst)) {
1040 		m->m_flags |= M_SKIP_FIREWALL;
1041 		/* If destination is now ourself drop to ip6_input(). */
1042 		if (in6_localip(&ip6->ip6_dst)) {
1043 			m->m_flags |= M_FASTFWD_OURS;
1044 			if (m->m_pkthdr.rcvif == NULL)
1045 				m->m_pkthdr.rcvif = V_loif;
1046 			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
1047 				m->m_pkthdr.csum_flags |=
1048 				    CSUM_DATA_VALID_IPV6 | CSUM_PSEUDO_HDR;
1049 				m->m_pkthdr.csum_data = 0xffff;
1050 			}
1051 #if defined(SCTP) || defined(SCTP_SUPPORT)
1052 			if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6)
1053 				m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1054 #endif
1055 			error = netisr_queue(NETISR_IPV6, m);
1056 			goto done;
1057 		} else {
1058 			if (ro != NULL)
1059 				RO_INVALIDATE_CACHE(ro);
1060 			needfiblookup = 1; /* Redo the routing table lookup. */
1061 		}
1062 	}
1063 	/* See if fib was changed by packet filter. */
1064 	if (fibnum != M_GETFIB(m)) {
1065 		m->m_flags |= M_SKIP_FIREWALL;
1066 		fibnum = M_GETFIB(m);
1067 		if (ro != NULL)
1068 			RO_INVALIDATE_CACHE(ro);
1069 		needfiblookup = 1;
1070 	}
1071 	if (needfiblookup)
1072 		goto again;
1073 
1074 	/* See if local, if yes, send it to netisr. */
1075 	if (m->m_flags & M_FASTFWD_OURS) {
1076 		if (m->m_pkthdr.rcvif == NULL)
1077 			m->m_pkthdr.rcvif = V_loif;
1078 		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
1079 			m->m_pkthdr.csum_flags |=
1080 			    CSUM_DATA_VALID_IPV6 | CSUM_PSEUDO_HDR;
1081 			m->m_pkthdr.csum_data = 0xffff;
1082 		}
1083 #if defined(SCTP) || defined(SCTP_SUPPORT)
1084 		if (m->m_pkthdr.csum_flags & CSUM_SCTP_IPV6)
1085 			m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1086 #endif
1087 		error = netisr_queue(NETISR_IPV6, m);
1088 		goto done;
1089 	}
1090 	/* Or forward to some other address? */
1091 	if ((m->m_flags & M_IP6_NEXTHOP) &&
1092 	    (fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL)) != NULL) {
1093 		if (ro != NULL)
1094 			dst = (struct sockaddr_in6 *)&ro->ro_dst;
1095 		else
1096 			dst = &sin6;
1097 		bcopy((fwd_tag+1), &dst_sa, sizeof(struct sockaddr_in6));
1098 		m->m_flags |= M_SKIP_FIREWALL;
1099 		m->m_flags &= ~M_IP6_NEXTHOP;
1100 		m_tag_delete(m, fwd_tag);
1101 		goto again;
1102 	}
1103 
1104 passout:
1105 	if (vlan_pcp > -1)
1106 		EVL_APPLY_PRI(m, vlan_pcp);
1107 	/*
1108 	 * Send the packet to the outgoing interface.
1109 	 * If necessary, do IPv6 fragmentation before sending.
1110 	 *
1111 	 * The logic here is rather complex:
1112 	 * 1: normal case (dontfrag == 0, alwaysfrag == 0)
1113 	 * 1-a:	send as is if tlen <= path mtu
1114 	 * 1-b:	fragment if tlen > path mtu
1115 	 *
1116 	 * 2: if user asks us not to fragment (dontfrag == 1)
1117 	 * 2-a:	send as is if tlen <= interface mtu
1118 	 * 2-b:	error if tlen > interface mtu
1119 	 *
1120 	 * 3: if we always need to attach fragment header (alwaysfrag == 1)
1121 	 *	always fragment
1122 	 *
1123 	 * 4: if dontfrag == 1 && alwaysfrag == 1
1124 	 *	error, as we cannot handle this conflicting request.
1125 	 */
1126 	sw_csum = m->m_pkthdr.csum_flags;
1127 	if (!hdrsplit) {
1128 		tso = ((sw_csum & ifp->if_hwassist &
1129 		    (CSUM_TSO | CSUM_INNER_TSO)) != 0) ? 1 : 0;
1130 		sw_csum &= ~ifp->if_hwassist;
1131 	} else
1132 		tso = 0;
1133 	/*
1134 	 * If we added extension headers, we will not do TSO and calculate the
1135 	 * checksums ourselves for now.
1136 	 * XXX-BZ  Need a framework to know when the NIC can handle it, even
1137 	 * with ext. hdrs.
1138 	 */
1139 	error = ip6_output_delayed_csum(m, ifp, sw_csum, plen, optlen, false);
1140 	if (error != 0)
1141 		goto bad;
1142 	/* XXX-BZ m->m_pkthdr.csum_flags &= ~ifp->if_hwassist; */
1143 	tlen = m->m_pkthdr.len;
1144 
1145 	if ((opt && (opt->ip6po_flags & IP6PO_DONTFRAG)) || tso)
1146 		dontfrag = 1;
1147 	else
1148 		dontfrag = 0;
1149 	if (dontfrag && alwaysfrag) {	/* Case 4. */
1150 		/* Conflicting request - can't transmit. */
1151 		error = EMSGSIZE;
1152 		goto bad;
1153 	}
1154 	if (dontfrag && tlen > IN6_LINKMTU(ifp) && !tso) {	/* Case 2-b. */
1155 		/*
1156 		 * Even if the DONTFRAG option is specified, we cannot send the
1157 		 * packet when the data length is larger than the MTU of the
1158 		 * outgoing interface.
1159 		 * Notify the error by sending IPV6_PATHMTU ancillary data if
1160 		 * application wanted to know the MTU value. Also return an
1161 		 * error code (this is not described in the API spec).
1162 		 */
1163 		if (inp != NULL)
1164 			ip6_notify_pmtu(inp, &dst_sa, (u_int32_t)mtu);
1165 		error = EMSGSIZE;
1166 		goto bad;
1167 	}
1168 
1169 	/* Transmit packet without fragmentation. */
1170 	if (dontfrag || (!alwaysfrag && tlen <= mtu)) {	/* Cases 1-a and 2-a. */
1171 		struct in6_ifaddr *ia6;
1172 
1173 		ip6 = mtod(m, struct ip6_hdr *);
1174 		ia6 = in6_ifawithifp(ifp, &ip6->ip6_src);
1175 		if (ia6) {
1176 			/* Record statistics for this interface address. */
1177 			counter_u64_add(ia6->ia_ifa.ifa_opackets, 1);
1178 			counter_u64_add(ia6->ia_ifa.ifa_obytes,
1179 			    m->m_pkthdr.len);
1180 		}
1181 		error = ip6_output_send(inp, ifp, origifp, m, dst, ro,
1182 		    (flags & IP_NO_SND_TAG_RL) ? false : true);
1183 		goto done;
1184 	}
1185 
1186 	/* Try to fragment the packet.  Cases 1-b and 3. */
1187 	if (mtu < IPV6_MMTU) {
1188 		/* Path MTU cannot be less than IPV6_MMTU. */
1189 		error = EMSGSIZE;
1190 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1191 		goto bad;
1192 	} else if (ip6->ip6_plen == 0) {
1193 		/* Jumbo payload cannot be fragmented. */
1194 		error = EMSGSIZE;
1195 		in6_ifstat_inc(ifp, ifs6_out_fragfail);
1196 		goto bad;
1197 	} else {
1198 		u_char nextproto;
1199 
1200 		/*
1201 		 * Too large for the destination or interface;
1202 		 * fragment if possible.
1203 		 * Must be able to put at least 8 bytes per fragment.
1204 		 */
1205 		if (mtu > IPV6_MAXPACKET)
1206 			mtu = IPV6_MAXPACKET;
1207 
1208 		len = (mtu - unfragpartlen - sizeof(struct ip6_frag)) & ~7;
1209 		if (len < 8) {
1210 			error = EMSGSIZE;
1211 			in6_ifstat_inc(ifp, ifs6_out_fragfail);
1212 			goto bad;
1213 		}
1214 
1215 		/*
1216 		 * If the interface will not calculate checksums on
1217 		 * fragmented packets, then do it here.
1218 		 * XXX-BZ handle the hw offloading case.  Need flags.
1219 		 */
1220 		error = ip6_output_delayed_csum(m, ifp, m->m_pkthdr.csum_flags,
1221 		    plen, optlen, true);
1222 		if (error != 0)
1223 			goto bad;
1224 
1225 		/*
1226 		 * Change the next header field of the last header in the
1227 		 * unfragmentable part.
1228 		 */
1229 		if (exthdrs.ip6e_rthdr) {
1230 			nextproto = *mtod(exthdrs.ip6e_rthdr, u_char *);
1231 			*mtod(exthdrs.ip6e_rthdr, u_char *) = IPPROTO_FRAGMENT;
1232 		} else if (exthdrs.ip6e_dest1) {
1233 			nextproto = *mtod(exthdrs.ip6e_dest1, u_char *);
1234 			*mtod(exthdrs.ip6e_dest1, u_char *) = IPPROTO_FRAGMENT;
1235 		} else if (exthdrs.ip6e_hbh) {
1236 			nextproto = *mtod(exthdrs.ip6e_hbh, u_char *);
1237 			*mtod(exthdrs.ip6e_hbh, u_char *) = IPPROTO_FRAGMENT;
1238 		} else {
1239 			ip6 = mtod(m, struct ip6_hdr *);
1240 			nextproto = ip6->ip6_nxt;
1241 			ip6->ip6_nxt = IPPROTO_FRAGMENT;
1242 		}
1243 
1244 		/*
1245 		 * Loop through length of segment after first fragment,
1246 		 * make new header and copy data of each part and link onto
1247 		 * chain.
1248 		 */
1249 		m0 = m;
1250 		id = htonl(ip6_randomid());
1251 		error = ip6_fragment(ifp, m, unfragpartlen, nextproto,len, id);
1252 		if (error != 0)
1253 			goto sendorfree;
1254 
1255 		in6_ifstat_inc(ifp, ifs6_out_fragok);
1256 	}
1257 
1258 	/* Remove leading garbage. */
1259 sendorfree:
1260 	m = m0->m_nextpkt;
1261 	m0->m_nextpkt = 0;
1262 	m_freem(m0);
1263 	for (; m; m = m0) {
1264 		m0 = m->m_nextpkt;
1265 		m->m_nextpkt = 0;
1266 		if (error == 0) {
1267 			/* Record statistics for this interface address. */
1268 			if (ia) {
1269 				counter_u64_add(ia->ia_ifa.ifa_opackets, 1);
1270 				counter_u64_add(ia->ia_ifa.ifa_obytes,
1271 				    m->m_pkthdr.len);
1272 			}
1273 			if (vlan_pcp > -1)
1274 				EVL_APPLY_PRI(m, vlan_pcp);
1275 			error = ip6_output_send(inp, ifp, origifp, m, dst, ro,
1276 			    true);
1277 		} else
1278 			m_freem(m);
1279 	}
1280 
1281 	if (error == 0)
1282 		IP6STAT_INC(ip6s_fragmented);
1283 
1284 done:
1285 	return (error);
1286 
1287 freehdrs:
1288 	m_freem(exthdrs.ip6e_hbh);	/* m_freem() checks if mbuf is NULL. */
1289 	m_freem(exthdrs.ip6e_dest1);
1290 	m_freem(exthdrs.ip6e_rthdr);
1291 	m_freem(exthdrs.ip6e_dest2);
1292 	/* FALLTHROUGH */
1293 bad:
1294 	if (m)
1295 		m_freem(m);
1296 	goto done;
1297 }
1298 
1299 static int
1300 ip6_copyexthdr(struct mbuf **mp, caddr_t hdr, int hlen)
1301 {
1302 	struct mbuf *m;
1303 
1304 	if (hlen > MCLBYTES)
1305 		return (ENOBUFS); /* XXX */
1306 
1307 	if (hlen > MLEN)
1308 		m = m_getcl(M_NOWAIT, MT_DATA, 0);
1309 	else
1310 		m = m_get(M_NOWAIT, MT_DATA);
1311 	if (m == NULL)
1312 		return (ENOBUFS);
1313 	m->m_len = hlen;
1314 	if (hdr)
1315 		bcopy(hdr, mtod(m, caddr_t), hlen);
1316 
1317 	*mp = m;
1318 	return (0);
1319 }
1320 
1321 /*
1322  * Insert jumbo payload option.
1323  */
1324 static int
1325 ip6_insert_jumboopt(struct ip6_exthdrs *exthdrs, u_int32_t plen)
1326 {
1327 	struct mbuf *mopt;
1328 	u_char *optbuf;
1329 	u_int32_t v;
1330 
1331 #define JUMBOOPTLEN	8	/* length of jumbo payload option and padding */
1332 
1333 	/*
1334 	 * If there is no hop-by-hop options header, allocate new one.
1335 	 * If there is one but it doesn't have enough space to store the
1336 	 * jumbo payload option, allocate a cluster to store the whole options.
1337 	 * Otherwise, use it to store the options.
1338 	 */
1339 	if (exthdrs->ip6e_hbh == NULL) {
1340 		mopt = m_get(M_NOWAIT, MT_DATA);
1341 		if (mopt == NULL)
1342 			return (ENOBUFS);
1343 		mopt->m_len = JUMBOOPTLEN;
1344 		optbuf = mtod(mopt, u_char *);
1345 		optbuf[1] = 0;	/* = ((JUMBOOPTLEN) >> 3) - 1 */
1346 		exthdrs->ip6e_hbh = mopt;
1347 	} else {
1348 		struct ip6_hbh *hbh;
1349 
1350 		mopt = exthdrs->ip6e_hbh;
1351 		if (M_TRAILINGSPACE(mopt) < JUMBOOPTLEN) {
1352 			/*
1353 			 * XXX assumption:
1354 			 * - exthdrs->ip6e_hbh is not referenced from places
1355 			 *   other than exthdrs.
1356 			 * - exthdrs->ip6e_hbh is not an mbuf chain.
1357 			 */
1358 			int oldoptlen = mopt->m_len;
1359 			struct mbuf *n;
1360 
1361 			/*
1362 			 * XXX: give up if the whole (new) hbh header does
1363 			 * not fit even in an mbuf cluster.
1364 			 */
1365 			if (oldoptlen + JUMBOOPTLEN > MCLBYTES)
1366 				return (ENOBUFS);
1367 
1368 			/*
1369 			 * As a consequence, we must always prepare a cluster
1370 			 * at this point.
1371 			 */
1372 			n = m_getcl(M_NOWAIT, MT_DATA, 0);
1373 			if (n == NULL)
1374 				return (ENOBUFS);
1375 			n->m_len = oldoptlen + JUMBOOPTLEN;
1376 			bcopy(mtod(mopt, caddr_t), mtod(n, caddr_t),
1377 			    oldoptlen);
1378 			optbuf = mtod(n, caddr_t) + oldoptlen;
1379 			m_freem(mopt);
1380 			mopt = exthdrs->ip6e_hbh = n;
1381 		} else {
1382 			optbuf = mtod(mopt, u_char *) + mopt->m_len;
1383 			mopt->m_len += JUMBOOPTLEN;
1384 		}
1385 		optbuf[0] = IP6OPT_PADN;
1386 		optbuf[1] = 1;
1387 
1388 		/*
1389 		 * Adjust the header length according to the pad and
1390 		 * the jumbo payload option.
1391 		 */
1392 		hbh = mtod(mopt, struct ip6_hbh *);
1393 		hbh->ip6h_len += (JUMBOOPTLEN >> 3);
1394 	}
1395 
1396 	/* fill in the option. */
1397 	optbuf[2] = IP6OPT_JUMBO;
1398 	optbuf[3] = 4;
1399 	v = (u_int32_t)htonl(plen + JUMBOOPTLEN);
1400 	bcopy(&v, &optbuf[4], sizeof(u_int32_t));
1401 
1402 	/* finally, adjust the packet header length */
1403 	exthdrs->ip6e_ip6->m_pkthdr.len += JUMBOOPTLEN;
1404 
1405 	return (0);
1406 #undef JUMBOOPTLEN
1407 }
1408 
1409 /*
1410  * Insert fragment header and copy unfragmentable header portions.
1411  */
1412 static int
1413 ip6_insertfraghdr(struct mbuf *m0, struct mbuf *m, int hlen,
1414     struct ip6_frag **frghdrp)
1415 {
1416 	struct mbuf *n, *mlast;
1417 
1418 	if (hlen > sizeof(struct ip6_hdr)) {
1419 		n = m_copym(m0, sizeof(struct ip6_hdr),
1420 		    hlen - sizeof(struct ip6_hdr), M_NOWAIT);
1421 		if (n == NULL)
1422 			return (ENOBUFS);
1423 		m->m_next = n;
1424 	} else
1425 		n = m;
1426 
1427 	/* Search for the last mbuf of unfragmentable part. */
1428 	for (mlast = n; mlast->m_next; mlast = mlast->m_next)
1429 		;
1430 
1431 	if (M_WRITABLE(mlast) &&
1432 	    M_TRAILINGSPACE(mlast) >= sizeof(struct ip6_frag)) {
1433 		/* use the trailing space of the last mbuf for the fragment hdr */
1434 		*frghdrp = (struct ip6_frag *)(mtod(mlast, caddr_t) +
1435 		    mlast->m_len);
1436 		mlast->m_len += sizeof(struct ip6_frag);
1437 		m->m_pkthdr.len += sizeof(struct ip6_frag);
1438 	} else {
1439 		/* allocate a new mbuf for the fragment header */
1440 		struct mbuf *mfrg;
1441 
1442 		mfrg = m_get(M_NOWAIT, MT_DATA);
1443 		if (mfrg == NULL)
1444 			return (ENOBUFS);
1445 		mfrg->m_len = sizeof(struct ip6_frag);
1446 		*frghdrp = mtod(mfrg, struct ip6_frag *);
1447 		mlast->m_next = mfrg;
1448 	}
1449 
1450 	return (0);
1451 }
1452 
1453 /*
1454  * Calculates IPv6 path mtu for destination @dst.
1455  * Resulting MTU is stored in @mtup.
1456  *
1457  * Returns 0 on success.
1458  */
1459 static int
1460 ip6_getpmtu_ctl(u_int fibnum, const struct in6_addr *dst, u_long *mtup)
1461 {
1462 	struct epoch_tracker et;
1463 	struct nhop_object *nh;
1464 	struct in6_addr kdst;
1465 	uint32_t scopeid;
1466 	int error;
1467 
1468 	in6_splitscope(dst, &kdst, &scopeid);
1469 
1470 	NET_EPOCH_ENTER(et);
1471 	nh = fib6_lookup(fibnum, &kdst, scopeid, NHR_NONE, 0);
1472 	if (nh != NULL)
1473 		error = ip6_calcmtu(nh->nh_ifp, dst, nh->nh_mtu, mtup, NULL, 0);
1474 	else
1475 		error = EHOSTUNREACH;
1476 	NET_EPOCH_EXIT(et);
1477 
1478 	return (error);
1479 }
1480 
1481 /*
1482  * Calculates IPv6 path MTU for @dst based on transmit @ifp,
1483  * and cached data in @ro_pmtu.
1484  * MTU from (successful) route lookup is saved (along with dst)
1485  * inside @ro_pmtu to avoid subsequent route lookups after packet
1486  * filter processing.
1487  *
1488  * Stores mtu and always-frag value into @mtup and @alwaysfragp.
1489  * Returns 0 on success.
1490  */
1491 static int
1492 ip6_getpmtu(struct route_in6 *ro_pmtu, int do_lookup,
1493     struct ifnet *ifp, const struct in6_addr *dst, u_long *mtup,
1494     int *alwaysfragp, u_int fibnum, u_int proto)
1495 {
1496 	struct nhop_object *nh;
1497 	struct in6_addr kdst;
1498 	uint32_t scopeid;
1499 	struct sockaddr_in6 *sa6_dst, sin6;
1500 	u_long mtu;
1501 
1502 	NET_EPOCH_ASSERT();
1503 
1504 	mtu = 0;
1505 	if (ro_pmtu == NULL || do_lookup) {
1506 		/*
1507 		 * Here ro_pmtu has final destination address, while
1508 		 * ro might represent immediate destination.
1509 		 * Use ro_pmtu destination since mtu might differ.
1510 		 */
1511 		if (ro_pmtu != NULL) {
1512 			sa6_dst = (struct sockaddr_in6 *)&ro_pmtu->ro_dst;
1513 			if (!IN6_ARE_ADDR_EQUAL(&sa6_dst->sin6_addr, dst))
1514 				ro_pmtu->ro_mtu = 0;
1515 		} else
1516 			sa6_dst = &sin6;
1517 
1518 		if (ro_pmtu == NULL || ro_pmtu->ro_mtu == 0) {
1519 			bzero(sa6_dst, sizeof(*sa6_dst));
1520 			sa6_dst->sin6_family = AF_INET6;
1521 			sa6_dst->sin6_len = sizeof(struct sockaddr_in6);
1522 			sa6_dst->sin6_addr = *dst;
1523 
1524 			in6_splitscope(dst, &kdst, &scopeid);
1525 			nh = fib6_lookup(fibnum, &kdst, scopeid, NHR_NONE, 0);
1526 			if (nh != NULL) {
1527 				mtu = nh->nh_mtu;
1528 				if (ro_pmtu != NULL)
1529 					ro_pmtu->ro_mtu = mtu;
1530 			}
1531 		} else
1532 			mtu = ro_pmtu->ro_mtu;
1533 	}
1534 
1535 	if (ro_pmtu != NULL && ro_pmtu->ro_nh != NULL)
1536 		mtu = ro_pmtu->ro_nh->nh_mtu;
1537 
1538 	return (ip6_calcmtu(ifp, dst, mtu, mtup, alwaysfragp, proto));
1539 }
1540 
1541 /*
1542  * Calculate MTU based on transmit @ifp, route mtu @rt_mtu and
1543  * hostcache data for @dst.
1544  * Stores mtu and always-frag value into @mtup and @alwaysfragp.
1545  *
1546  * Returns 0 on success.
1547  */
1548 static int
1549 ip6_calcmtu(struct ifnet *ifp, const struct in6_addr *dst, u_long rt_mtu,
1550     u_long *mtup, int *alwaysfragp, u_int proto)
1551 {
1552 	u_long mtu = 0;
1553 	int alwaysfrag = 0;
1554 	int error = 0;
1555 
1556 	if (rt_mtu > 0) {
1557 		u_int32_t ifmtu;
1558 		struct in_conninfo inc;
1559 
1560 		bzero(&inc, sizeof(inc));
1561 		inc.inc_flags |= INC_ISIPV6;
1562 		inc.inc6_faddr = *dst;
1563 
1564 		ifmtu = IN6_LINKMTU(ifp);
1565 
1566 		/* TCP is known to react to pmtu changes so skip hc */
1567 		if (proto != IPPROTO_TCP)
1568 			mtu = tcp_hc_getmtu(&inc);
1569 
1570 		if (mtu)
1571 			mtu = min(mtu, rt_mtu);
1572 		else
1573 			mtu = rt_mtu;
1574 		if (mtu == 0)
1575 			mtu = ifmtu;
1576 		else if (mtu < IPV6_MMTU) {
1577 			/*
1578 			 * RFC2460 section 5, last paragraph:
1579 			 * if we record ICMPv6 too big message with
1580 			 * mtu < IPV6_MMTU, transmit packets sized IPV6_MMTU
1581 			 * or smaller, with framgent header attached.
1582 			 * (fragment header is needed regardless from the
1583 			 * packet size, for translators to identify packets)
1584 			 */
1585 			alwaysfrag = 1;
1586 			mtu = IPV6_MMTU;
1587 		}
1588 	} else if (ifp) {
1589 		mtu = IN6_LINKMTU(ifp);
1590 	} else
1591 		error = EHOSTUNREACH; /* XXX */
1592 
1593 	*mtup = mtu;
1594 	if (alwaysfragp)
1595 		*alwaysfragp = alwaysfrag;
1596 	return (error);
1597 }
1598 
1599 /*
1600  * IP6 socket option processing.
1601  */
1602 int
1603 ip6_ctloutput(struct socket *so, struct sockopt *sopt)
1604 {
1605 	int optdatalen, uproto;
1606 	void *optdata;
1607 	struct inpcb *inp = sotoinpcb(so);
1608 	int error, optval;
1609 	int level, op, optname;
1610 	int optlen;
1611 	struct thread *td;
1612 #ifdef	RSS
1613 	uint32_t rss_bucket;
1614 	int retval;
1615 #endif
1616 
1617 /*
1618  * Don't use more than a quarter of mbuf clusters.  N.B.:
1619  * nmbclusters is an int, but nmbclusters * MCLBYTES may overflow
1620  * on LP64 architectures, so cast to u_long to avoid undefined
1621  * behavior.  ILP32 architectures cannot have nmbclusters
1622  * large enough to overflow for other reasons.
1623  */
1624 #define IPV6_PKTOPTIONS_MBUF_LIMIT	((u_long)nmbclusters * MCLBYTES / 4)
1625 
1626 	level = sopt->sopt_level;
1627 	op = sopt->sopt_dir;
1628 	optname = sopt->sopt_name;
1629 	optlen = sopt->sopt_valsize;
1630 	td = sopt->sopt_td;
1631 	error = 0;
1632 	optval = 0;
1633 	uproto = (int)so->so_proto->pr_protocol;
1634 
1635 	if (level != IPPROTO_IPV6) {
1636 		error = EINVAL;
1637 
1638 		if (sopt->sopt_level == SOL_SOCKET &&
1639 		    sopt->sopt_dir == SOPT_SET) {
1640 			switch (sopt->sopt_name) {
1641 			case SO_REUSEADDR:
1642 				INP_WLOCK(inp);
1643 				if ((so->so_options & SO_REUSEADDR) != 0)
1644 					inp->inp_flags2 |= INP_REUSEADDR;
1645 				else
1646 					inp->inp_flags2 &= ~INP_REUSEADDR;
1647 				INP_WUNLOCK(inp);
1648 				error = 0;
1649 				break;
1650 			case SO_REUSEPORT:
1651 				INP_WLOCK(inp);
1652 				if ((so->so_options & SO_REUSEPORT) != 0)
1653 					inp->inp_flags2 |= INP_REUSEPORT;
1654 				else
1655 					inp->inp_flags2 &= ~INP_REUSEPORT;
1656 				INP_WUNLOCK(inp);
1657 				error = 0;
1658 				break;
1659 			case SO_REUSEPORT_LB:
1660 				INP_WLOCK(inp);
1661 				if ((so->so_options & SO_REUSEPORT_LB) != 0)
1662 					inp->inp_flags2 |= INP_REUSEPORT_LB;
1663 				else
1664 					inp->inp_flags2 &= ~INP_REUSEPORT_LB;
1665 				INP_WUNLOCK(inp);
1666 				error = 0;
1667 				break;
1668 			case SO_SETFIB:
1669 				INP_WLOCK(inp);
1670 				inp->inp_inc.inc_fibnum = so->so_fibnum;
1671 				INP_WUNLOCK(inp);
1672 				error = 0;
1673 				break;
1674 			case SO_MAX_PACING_RATE:
1675 #ifdef RATELIMIT
1676 				INP_WLOCK(inp);
1677 				inp->inp_flags2 |= INP_RATE_LIMIT_CHANGED;
1678 				INP_WUNLOCK(inp);
1679 				error = 0;
1680 #else
1681 				error = EOPNOTSUPP;
1682 #endif
1683 				break;
1684 			default:
1685 				break;
1686 			}
1687 		}
1688 	} else {		/* level == IPPROTO_IPV6 */
1689 		switch (op) {
1690 		case SOPT_SET:
1691 			switch (optname) {
1692 			case IPV6_2292PKTOPTIONS:
1693 #ifdef IPV6_PKTOPTIONS
1694 			case IPV6_PKTOPTIONS:
1695 #endif
1696 			{
1697 				struct mbuf *m;
1698 
1699 				if (optlen > IPV6_PKTOPTIONS_MBUF_LIMIT) {
1700 					printf("ip6_ctloutput: mbuf limit hit\n");
1701 					error = ENOBUFS;
1702 					break;
1703 				}
1704 
1705 				error = soopt_getm(sopt, &m); /* XXX */
1706 				if (error != 0)
1707 					break;
1708 				error = soopt_mcopyin(sopt, m); /* XXX */
1709 				if (error != 0)
1710 					break;
1711 				INP_WLOCK(inp);
1712 				error = ip6_pcbopts(&inp->in6p_outputopts, m,
1713 				    so, sopt);
1714 				INP_WUNLOCK(inp);
1715 				m_freem(m); /* XXX */
1716 				break;
1717 			}
1718 
1719 			/*
1720 			 * Use of some Hop-by-Hop options or some
1721 			 * Destination options, might require special
1722 			 * privilege.  That is, normal applications
1723 			 * (without special privilege) might be forbidden
1724 			 * from setting certain options in outgoing packets,
1725 			 * and might never see certain options in received
1726 			 * packets. [RFC 2292 Section 6]
1727 			 * KAME specific note:
1728 			 *  KAME prevents non-privileged users from sending or
1729 			 *  receiving ANY hbh/dst options in order to avoid
1730 			 *  overhead of parsing options in the kernel.
1731 			 */
1732 			case IPV6_RECVHOPOPTS:
1733 			case IPV6_RECVDSTOPTS:
1734 			case IPV6_RECVRTHDRDSTOPTS:
1735 				if (td != NULL) {
1736 					error = priv_check(td,
1737 					    PRIV_NETINET_SETHDROPTS);
1738 					if (error)
1739 						break;
1740 				}
1741 				/* FALLTHROUGH */
1742 			case IPV6_UNICAST_HOPS:
1743 			case IPV6_HOPLIMIT:
1744 
1745 			case IPV6_RECVPKTINFO:
1746 			case IPV6_RECVHOPLIMIT:
1747 			case IPV6_RECVRTHDR:
1748 			case IPV6_RECVPATHMTU:
1749 			case IPV6_RECVTCLASS:
1750 			case IPV6_RECVFLOWID:
1751 #ifdef	RSS
1752 			case IPV6_RECVRSSBUCKETID:
1753 #endif
1754 			case IPV6_V6ONLY:
1755 			case IPV6_AUTOFLOWLABEL:
1756 			case IPV6_ORIGDSTADDR:
1757 			case IPV6_BINDANY:
1758 			case IPV6_BINDMULTI:
1759 #ifdef	RSS
1760 			case IPV6_RSS_LISTEN_BUCKET:
1761 #endif
1762 			case IPV6_VLAN_PCP:
1763 				if (optname == IPV6_BINDANY && td != NULL) {
1764 					error = priv_check(td,
1765 					    PRIV_NETINET_BINDANY);
1766 					if (error)
1767 						break;
1768 				}
1769 
1770 				if (optlen != sizeof(int)) {
1771 					error = EINVAL;
1772 					break;
1773 				}
1774 				error = sooptcopyin(sopt, &optval,
1775 					sizeof optval, sizeof optval);
1776 				if (error)
1777 					break;
1778 				switch (optname) {
1779 				case IPV6_UNICAST_HOPS:
1780 					if (optval < -1 || optval >= 256)
1781 						error = EINVAL;
1782 					else {
1783 						/* -1 = kernel default */
1784 						inp->in6p_hops = optval;
1785 						if ((inp->inp_vflag &
1786 						     INP_IPV4) != 0)
1787 							inp->inp_ip_ttl = optval;
1788 					}
1789 					break;
1790 #define OPTSET(bit) \
1791 do { \
1792 	INP_WLOCK(inp); \
1793 	if (optval) \
1794 		inp->inp_flags |= (bit); \
1795 	else \
1796 		inp->inp_flags &= ~(bit); \
1797 	INP_WUNLOCK(inp); \
1798 } while (/*CONSTCOND*/ 0)
1799 #define OPTSET2292(bit) \
1800 do { \
1801 	INP_WLOCK(inp); \
1802 	inp->inp_flags |= IN6P_RFC2292; \
1803 	if (optval) \
1804 		inp->inp_flags |= (bit); \
1805 	else \
1806 		inp->inp_flags &= ~(bit); \
1807 	INP_WUNLOCK(inp); \
1808 } while (/*CONSTCOND*/ 0)
1809 #define OPTBIT(bit) (inp->inp_flags & (bit) ? 1 : 0)
1810 
1811 #define OPTSET2_N(bit, val) do {					\
1812 	if (val)							\
1813 		inp->inp_flags2 |= bit;					\
1814 	else								\
1815 		inp->inp_flags2 &= ~bit;				\
1816 } while (0)
1817 #define OPTSET2(bit, val) do {						\
1818 	INP_WLOCK(inp);							\
1819 	OPTSET2_N(bit, val);						\
1820 	INP_WUNLOCK(inp);						\
1821 } while (0)
1822 #define OPTBIT2(bit) (inp->inp_flags2 & (bit) ? 1 : 0)
1823 #define OPTSET2292_EXCLUSIVE(bit)					\
1824 do {									\
1825 	INP_WLOCK(inp);							\
1826 	if (OPTBIT(IN6P_RFC2292)) {					\
1827 		error = EINVAL;						\
1828 	} else {							\
1829 		if (optval)						\
1830 			inp->inp_flags |= (bit);			\
1831 		else							\
1832 			inp->inp_flags &= ~(bit);			\
1833 	}								\
1834 	INP_WUNLOCK(inp);						\
1835 } while (/*CONSTCOND*/ 0)
1836 
1837 				case IPV6_RECVPKTINFO:
1838 					OPTSET2292_EXCLUSIVE(IN6P_PKTINFO);
1839 					break;
1840 
1841 				case IPV6_HOPLIMIT:
1842 				{
1843 					struct ip6_pktopts **optp;
1844 
1845 					/* cannot mix with RFC2292 */
1846 					if (OPTBIT(IN6P_RFC2292)) {
1847 						error = EINVAL;
1848 						break;
1849 					}
1850 					INP_WLOCK(inp);
1851 					if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1852 						INP_WUNLOCK(inp);
1853 						return (ECONNRESET);
1854 					}
1855 					optp = &inp->in6p_outputopts;
1856 					error = ip6_pcbopt(IPV6_HOPLIMIT,
1857 					    (u_char *)&optval, sizeof(optval),
1858 					    optp, (td != NULL) ? td->td_ucred :
1859 					    NULL, uproto);
1860 					INP_WUNLOCK(inp);
1861 					break;
1862 				}
1863 
1864 				case IPV6_RECVHOPLIMIT:
1865 					OPTSET2292_EXCLUSIVE(IN6P_HOPLIMIT);
1866 					break;
1867 
1868 				case IPV6_RECVHOPOPTS:
1869 					OPTSET2292_EXCLUSIVE(IN6P_HOPOPTS);
1870 					break;
1871 
1872 				case IPV6_RECVDSTOPTS:
1873 					OPTSET2292_EXCLUSIVE(IN6P_DSTOPTS);
1874 					break;
1875 
1876 				case IPV6_RECVRTHDRDSTOPTS:
1877 					OPTSET2292_EXCLUSIVE(IN6P_RTHDRDSTOPTS);
1878 					break;
1879 
1880 				case IPV6_RECVRTHDR:
1881 					OPTSET2292_EXCLUSIVE(IN6P_RTHDR);
1882 					break;
1883 
1884 				case IPV6_RECVPATHMTU:
1885 					/*
1886 					 * We ignore this option for TCP
1887 					 * sockets.
1888 					 * (RFC3542 leaves this case
1889 					 * unspecified.)
1890 					 */
1891 					if (uproto != IPPROTO_TCP)
1892 						OPTSET(IN6P_MTU);
1893 					break;
1894 
1895 				case IPV6_RECVFLOWID:
1896 					OPTSET2(INP_RECVFLOWID, optval);
1897 					break;
1898 
1899 #ifdef	RSS
1900 				case IPV6_RECVRSSBUCKETID:
1901 					OPTSET2(INP_RECVRSSBUCKETID, optval);
1902 					break;
1903 #endif
1904 
1905 				case IPV6_V6ONLY:
1906 					INP_WLOCK(inp);
1907 					if (inp->inp_lport ||
1908 					    !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1909 						/*
1910 						 * The socket is already bound.
1911 						 */
1912 						INP_WUNLOCK(inp);
1913 						error = EINVAL;
1914 						break;
1915 					}
1916 					if (optval) {
1917 						inp->inp_flags |= IN6P_IPV6_V6ONLY;
1918 						inp->inp_vflag &= ~INP_IPV4;
1919 					} else {
1920 						inp->inp_flags &= ~IN6P_IPV6_V6ONLY;
1921 						inp->inp_vflag |= INP_IPV4;
1922 					}
1923 					INP_WUNLOCK(inp);
1924 					break;
1925 				case IPV6_RECVTCLASS:
1926 					/* cannot mix with RFC2292 XXX */
1927 					OPTSET2292_EXCLUSIVE(IN6P_TCLASS);
1928 					break;
1929 				case IPV6_AUTOFLOWLABEL:
1930 					OPTSET(IN6P_AUTOFLOWLABEL);
1931 					break;
1932 
1933 				case IPV6_ORIGDSTADDR:
1934 					OPTSET2(INP_ORIGDSTADDR, optval);
1935 					break;
1936 				case IPV6_BINDANY:
1937 					OPTSET(INP_BINDANY);
1938 					break;
1939 
1940 				case IPV6_BINDMULTI:
1941 					OPTSET2(INP_BINDMULTI, optval);
1942 					break;
1943 #ifdef	RSS
1944 				case IPV6_RSS_LISTEN_BUCKET:
1945 					if ((optval >= 0) &&
1946 					    (optval < rss_getnumbuckets())) {
1947 						INP_WLOCK(inp);
1948 						inp->inp_rss_listen_bucket = optval;
1949 						OPTSET2_N(INP_RSS_BUCKET_SET, 1);
1950 						INP_WUNLOCK(inp);
1951 					} else {
1952 						error = EINVAL;
1953 					}
1954 					break;
1955 #endif
1956 				case IPV6_VLAN_PCP:
1957 					if ((optval >= -1) && (optval <=
1958 					    (INP_2PCP_MASK >> INP_2PCP_SHIFT))) {
1959 						if (optval == -1) {
1960 							INP_WLOCK(inp);
1961 							inp->inp_flags2 &=
1962 							    ~(INP_2PCP_SET |
1963 							    INP_2PCP_MASK);
1964 							INP_WUNLOCK(inp);
1965 						} else {
1966 							INP_WLOCK(inp);
1967 							inp->inp_flags2 |=
1968 							    INP_2PCP_SET;
1969 							inp->inp_flags2 &=
1970 							    ~INP_2PCP_MASK;
1971 							inp->inp_flags2 |=
1972 							    optval <<
1973 							    INP_2PCP_SHIFT;
1974 							INP_WUNLOCK(inp);
1975 						}
1976 					} else
1977 						error = EINVAL;
1978 					break;
1979 				}
1980 				break;
1981 
1982 			case IPV6_TCLASS:
1983 			case IPV6_DONTFRAG:
1984 			case IPV6_USE_MIN_MTU:
1985 			case IPV6_PREFER_TEMPADDR:
1986 				if (optlen != sizeof(optval)) {
1987 					error = EINVAL;
1988 					break;
1989 				}
1990 				error = sooptcopyin(sopt, &optval,
1991 					sizeof optval, sizeof optval);
1992 				if (error)
1993 					break;
1994 				{
1995 					struct ip6_pktopts **optp;
1996 					INP_WLOCK(inp);
1997 					if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1998 						INP_WUNLOCK(inp);
1999 						return (ECONNRESET);
2000 					}
2001 					optp = &inp->in6p_outputopts;
2002 					error = ip6_pcbopt(optname,
2003 					    (u_char *)&optval, sizeof(optval),
2004 					    optp, (td != NULL) ? td->td_ucred :
2005 					    NULL, uproto);
2006 					INP_WUNLOCK(inp);
2007 					break;
2008 				}
2009 
2010 			case IPV6_2292PKTINFO:
2011 			case IPV6_2292HOPLIMIT:
2012 			case IPV6_2292HOPOPTS:
2013 			case IPV6_2292DSTOPTS:
2014 			case IPV6_2292RTHDR:
2015 				/* RFC 2292 */
2016 				if (optlen != sizeof(int)) {
2017 					error = EINVAL;
2018 					break;
2019 				}
2020 				error = sooptcopyin(sopt, &optval,
2021 					sizeof optval, sizeof optval);
2022 				if (error)
2023 					break;
2024 				switch (optname) {
2025 				case IPV6_2292PKTINFO:
2026 					OPTSET2292(IN6P_PKTINFO);
2027 					break;
2028 				case IPV6_2292HOPLIMIT:
2029 					OPTSET2292(IN6P_HOPLIMIT);
2030 					break;
2031 				case IPV6_2292HOPOPTS:
2032 					/*
2033 					 * Check super-user privilege.
2034 					 * See comments for IPV6_RECVHOPOPTS.
2035 					 */
2036 					if (td != NULL) {
2037 						error = priv_check(td,
2038 						    PRIV_NETINET_SETHDROPTS);
2039 						if (error)
2040 							return (error);
2041 					}
2042 					OPTSET2292(IN6P_HOPOPTS);
2043 					break;
2044 				case IPV6_2292DSTOPTS:
2045 					if (td != NULL) {
2046 						error = priv_check(td,
2047 						    PRIV_NETINET_SETHDROPTS);
2048 						if (error)
2049 							return (error);
2050 					}
2051 					OPTSET2292(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS); /* XXX */
2052 					break;
2053 				case IPV6_2292RTHDR:
2054 					OPTSET2292(IN6P_RTHDR);
2055 					break;
2056 				}
2057 				break;
2058 			case IPV6_PKTINFO:
2059 			case IPV6_HOPOPTS:
2060 			case IPV6_RTHDR:
2061 			case IPV6_DSTOPTS:
2062 			case IPV6_RTHDRDSTOPTS:
2063 			case IPV6_NEXTHOP:
2064 			{
2065 				/* new advanced API (RFC3542) */
2066 				u_char *optbuf;
2067 				u_char optbuf_storage[MCLBYTES];
2068 				int optlen;
2069 				struct ip6_pktopts **optp;
2070 
2071 				/* cannot mix with RFC2292 */
2072 				if (OPTBIT(IN6P_RFC2292)) {
2073 					error = EINVAL;
2074 					break;
2075 				}
2076 
2077 				/*
2078 				 * We only ensure valsize is not too large
2079 				 * here.  Further validation will be done
2080 				 * later.
2081 				 */
2082 				error = sooptcopyin(sopt, optbuf_storage,
2083 				    sizeof(optbuf_storage), 0);
2084 				if (error)
2085 					break;
2086 				optlen = sopt->sopt_valsize;
2087 				optbuf = optbuf_storage;
2088 				INP_WLOCK(inp);
2089 				if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
2090 					INP_WUNLOCK(inp);
2091 					return (ECONNRESET);
2092 				}
2093 				optp = &inp->in6p_outputopts;
2094 				error = ip6_pcbopt(optname, optbuf, optlen,
2095 				    optp, (td != NULL) ? td->td_ucred : NULL,
2096 				    uproto);
2097 				INP_WUNLOCK(inp);
2098 				break;
2099 			}
2100 #undef OPTSET
2101 
2102 			case IPV6_MULTICAST_IF:
2103 			case IPV6_MULTICAST_HOPS:
2104 			case IPV6_MULTICAST_LOOP:
2105 			case IPV6_JOIN_GROUP:
2106 			case IPV6_LEAVE_GROUP:
2107 			case IPV6_MSFILTER:
2108 			case MCAST_BLOCK_SOURCE:
2109 			case MCAST_UNBLOCK_SOURCE:
2110 			case MCAST_JOIN_GROUP:
2111 			case MCAST_LEAVE_GROUP:
2112 			case MCAST_JOIN_SOURCE_GROUP:
2113 			case MCAST_LEAVE_SOURCE_GROUP:
2114 				error = ip6_setmoptions(inp, sopt);
2115 				break;
2116 
2117 			case IPV6_PORTRANGE:
2118 				error = sooptcopyin(sopt, &optval,
2119 				    sizeof optval, sizeof optval);
2120 				if (error)
2121 					break;
2122 
2123 				INP_WLOCK(inp);
2124 				switch (optval) {
2125 				case IPV6_PORTRANGE_DEFAULT:
2126 					inp->inp_flags &= ~(INP_LOWPORT);
2127 					inp->inp_flags &= ~(INP_HIGHPORT);
2128 					break;
2129 
2130 				case IPV6_PORTRANGE_HIGH:
2131 					inp->inp_flags &= ~(INP_LOWPORT);
2132 					inp->inp_flags |= INP_HIGHPORT;
2133 					break;
2134 
2135 				case IPV6_PORTRANGE_LOW:
2136 					inp->inp_flags &= ~(INP_HIGHPORT);
2137 					inp->inp_flags |= INP_LOWPORT;
2138 					break;
2139 
2140 				default:
2141 					error = EINVAL;
2142 					break;
2143 				}
2144 				INP_WUNLOCK(inp);
2145 				break;
2146 
2147 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
2148 			case IPV6_IPSEC_POLICY:
2149 				if (IPSEC_ENABLED(ipv6)) {
2150 					error = IPSEC_PCBCTL(ipv6, inp, sopt);
2151 					break;
2152 				}
2153 				/* FALLTHROUGH */
2154 #endif /* IPSEC */
2155 
2156 			default:
2157 				error = ENOPROTOOPT;
2158 				break;
2159 			}
2160 			break;
2161 
2162 		case SOPT_GET:
2163 			switch (optname) {
2164 			case IPV6_2292PKTOPTIONS:
2165 #ifdef IPV6_PKTOPTIONS
2166 			case IPV6_PKTOPTIONS:
2167 #endif
2168 				/*
2169 				 * RFC3542 (effectively) deprecated the
2170 				 * semantics of the 2292-style pktoptions.
2171 				 * Since it was not reliable in nature (i.e.,
2172 				 * applications had to expect the lack of some
2173 				 * information after all), it would make sense
2174 				 * to simplify this part by always returning
2175 				 * empty data.
2176 				 */
2177 				sopt->sopt_valsize = 0;
2178 				break;
2179 
2180 			case IPV6_RECVHOPOPTS:
2181 			case IPV6_RECVDSTOPTS:
2182 			case IPV6_RECVRTHDRDSTOPTS:
2183 			case IPV6_UNICAST_HOPS:
2184 			case IPV6_RECVPKTINFO:
2185 			case IPV6_RECVHOPLIMIT:
2186 			case IPV6_RECVRTHDR:
2187 			case IPV6_RECVPATHMTU:
2188 
2189 			case IPV6_V6ONLY:
2190 			case IPV6_PORTRANGE:
2191 			case IPV6_RECVTCLASS:
2192 			case IPV6_AUTOFLOWLABEL:
2193 			case IPV6_BINDANY:
2194 			case IPV6_FLOWID:
2195 			case IPV6_FLOWTYPE:
2196 			case IPV6_RECVFLOWID:
2197 #ifdef	RSS
2198 			case IPV6_RSSBUCKETID:
2199 			case IPV6_RECVRSSBUCKETID:
2200 #endif
2201 			case IPV6_BINDMULTI:
2202 			case IPV6_VLAN_PCP:
2203 				switch (optname) {
2204 				case IPV6_RECVHOPOPTS:
2205 					optval = OPTBIT(IN6P_HOPOPTS);
2206 					break;
2207 
2208 				case IPV6_RECVDSTOPTS:
2209 					optval = OPTBIT(IN6P_DSTOPTS);
2210 					break;
2211 
2212 				case IPV6_RECVRTHDRDSTOPTS:
2213 					optval = OPTBIT(IN6P_RTHDRDSTOPTS);
2214 					break;
2215 
2216 				case IPV6_UNICAST_HOPS:
2217 					optval = inp->in6p_hops;
2218 					break;
2219 
2220 				case IPV6_RECVPKTINFO:
2221 					optval = OPTBIT(IN6P_PKTINFO);
2222 					break;
2223 
2224 				case IPV6_RECVHOPLIMIT:
2225 					optval = OPTBIT(IN6P_HOPLIMIT);
2226 					break;
2227 
2228 				case IPV6_RECVRTHDR:
2229 					optval = OPTBIT(IN6P_RTHDR);
2230 					break;
2231 
2232 				case IPV6_RECVPATHMTU:
2233 					optval = OPTBIT(IN6P_MTU);
2234 					break;
2235 
2236 				case IPV6_V6ONLY:
2237 					optval = OPTBIT(IN6P_IPV6_V6ONLY);
2238 					break;
2239 
2240 				case IPV6_PORTRANGE:
2241 				    {
2242 					int flags;
2243 					flags = inp->inp_flags;
2244 					if (flags & INP_HIGHPORT)
2245 						optval = IPV6_PORTRANGE_HIGH;
2246 					else if (flags & INP_LOWPORT)
2247 						optval = IPV6_PORTRANGE_LOW;
2248 					else
2249 						optval = 0;
2250 					break;
2251 				    }
2252 				case IPV6_RECVTCLASS:
2253 					optval = OPTBIT(IN6P_TCLASS);
2254 					break;
2255 
2256 				case IPV6_AUTOFLOWLABEL:
2257 					optval = OPTBIT(IN6P_AUTOFLOWLABEL);
2258 					break;
2259 
2260 				case IPV6_ORIGDSTADDR:
2261 					optval = OPTBIT2(INP_ORIGDSTADDR);
2262 					break;
2263 
2264 				case IPV6_BINDANY:
2265 					optval = OPTBIT(INP_BINDANY);
2266 					break;
2267 
2268 				case IPV6_FLOWID:
2269 					optval = inp->inp_flowid;
2270 					break;
2271 
2272 				case IPV6_FLOWTYPE:
2273 					optval = inp->inp_flowtype;
2274 					break;
2275 
2276 				case IPV6_RECVFLOWID:
2277 					optval = OPTBIT2(INP_RECVFLOWID);
2278 					break;
2279 #ifdef	RSS
2280 				case IPV6_RSSBUCKETID:
2281 					retval =
2282 					    rss_hash2bucket(inp->inp_flowid,
2283 					    inp->inp_flowtype,
2284 					    &rss_bucket);
2285 					if (retval == 0)
2286 						optval = rss_bucket;
2287 					else
2288 						error = EINVAL;
2289 					break;
2290 
2291 				case IPV6_RECVRSSBUCKETID:
2292 					optval = OPTBIT2(INP_RECVRSSBUCKETID);
2293 					break;
2294 #endif
2295 
2296 				case IPV6_BINDMULTI:
2297 					optval = OPTBIT2(INP_BINDMULTI);
2298 					break;
2299 
2300 				case IPV6_VLAN_PCP:
2301 					if (OPTBIT2(INP_2PCP_SET)) {
2302 						optval = (inp->inp_flags2 &
2303 							    INP_2PCP_MASK) >>
2304 							    INP_2PCP_SHIFT;
2305 					} else {
2306 						optval = -1;
2307 					}
2308 					break;
2309 				}
2310 
2311 				if (error)
2312 					break;
2313 				error = sooptcopyout(sopt, &optval,
2314 					sizeof optval);
2315 				break;
2316 
2317 			case IPV6_PATHMTU:
2318 			{
2319 				u_long pmtu = 0;
2320 				struct ip6_mtuinfo mtuinfo;
2321 				struct in6_addr addr;
2322 
2323 				if (!(so->so_state & SS_ISCONNECTED))
2324 					return (ENOTCONN);
2325 				/*
2326 				 * XXX: we dot not consider the case of source
2327 				 * routing, or optional information to specify
2328 				 * the outgoing interface.
2329 				 * Copy faddr out of inp to avoid holding lock
2330 				 * on inp during route lookup.
2331 				 */
2332 				INP_RLOCK(inp);
2333 				bcopy(&inp->in6p_faddr, &addr, sizeof(addr));
2334 				INP_RUNLOCK(inp);
2335 				error = ip6_getpmtu_ctl(so->so_fibnum,
2336 				    &addr, &pmtu);
2337 				if (error)
2338 					break;
2339 				if (pmtu > IPV6_MAXPACKET)
2340 					pmtu = IPV6_MAXPACKET;
2341 
2342 				bzero(&mtuinfo, sizeof(mtuinfo));
2343 				mtuinfo.ip6m_mtu = (u_int32_t)pmtu;
2344 				optdata = (void *)&mtuinfo;
2345 				optdatalen = sizeof(mtuinfo);
2346 				error = sooptcopyout(sopt, optdata,
2347 				    optdatalen);
2348 				break;
2349 			}
2350 
2351 			case IPV6_2292PKTINFO:
2352 			case IPV6_2292HOPLIMIT:
2353 			case IPV6_2292HOPOPTS:
2354 			case IPV6_2292RTHDR:
2355 			case IPV6_2292DSTOPTS:
2356 				switch (optname) {
2357 				case IPV6_2292PKTINFO:
2358 					optval = OPTBIT(IN6P_PKTINFO);
2359 					break;
2360 				case IPV6_2292HOPLIMIT:
2361 					optval = OPTBIT(IN6P_HOPLIMIT);
2362 					break;
2363 				case IPV6_2292HOPOPTS:
2364 					optval = OPTBIT(IN6P_HOPOPTS);
2365 					break;
2366 				case IPV6_2292RTHDR:
2367 					optval = OPTBIT(IN6P_RTHDR);
2368 					break;
2369 				case IPV6_2292DSTOPTS:
2370 					optval = OPTBIT(IN6P_DSTOPTS|IN6P_RTHDRDSTOPTS);
2371 					break;
2372 				}
2373 				error = sooptcopyout(sopt, &optval,
2374 				    sizeof optval);
2375 				break;
2376 			case IPV6_PKTINFO:
2377 			case IPV6_HOPOPTS:
2378 			case IPV6_RTHDR:
2379 			case IPV6_DSTOPTS:
2380 			case IPV6_RTHDRDSTOPTS:
2381 			case IPV6_NEXTHOP:
2382 			case IPV6_TCLASS:
2383 			case IPV6_DONTFRAG:
2384 			case IPV6_USE_MIN_MTU:
2385 			case IPV6_PREFER_TEMPADDR:
2386 				error = ip6_getpcbopt(inp, optname, sopt);
2387 				break;
2388 
2389 			case IPV6_MULTICAST_IF:
2390 			case IPV6_MULTICAST_HOPS:
2391 			case IPV6_MULTICAST_LOOP:
2392 			case IPV6_MSFILTER:
2393 				error = ip6_getmoptions(inp, sopt);
2394 				break;
2395 
2396 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
2397 			case IPV6_IPSEC_POLICY:
2398 				if (IPSEC_ENABLED(ipv6)) {
2399 					error = IPSEC_PCBCTL(ipv6, inp, sopt);
2400 					break;
2401 				}
2402 				/* FALLTHROUGH */
2403 #endif /* IPSEC */
2404 			default:
2405 				error = ENOPROTOOPT;
2406 				break;
2407 			}
2408 			break;
2409 		}
2410 	}
2411 	return (error);
2412 }
2413 
2414 int
2415 ip6_raw_ctloutput(struct socket *so, struct sockopt *sopt)
2416 {
2417 	int error = 0, optval, optlen;
2418 	const int icmp6off = offsetof(struct icmp6_hdr, icmp6_cksum);
2419 	struct inpcb *inp = sotoinpcb(so);
2420 	int level, op, optname;
2421 
2422 	level = sopt->sopt_level;
2423 	op = sopt->sopt_dir;
2424 	optname = sopt->sopt_name;
2425 	optlen = sopt->sopt_valsize;
2426 
2427 	if (level != IPPROTO_IPV6) {
2428 		return (EINVAL);
2429 	}
2430 
2431 	switch (optname) {
2432 	case IPV6_CHECKSUM:
2433 		/*
2434 		 * For ICMPv6 sockets, no modification allowed for checksum
2435 		 * offset, permit "no change" values to help existing apps.
2436 		 *
2437 		 * RFC3542 says: "An attempt to set IPV6_CHECKSUM
2438 		 * for an ICMPv6 socket will fail."
2439 		 * The current behavior does not meet RFC3542.
2440 		 */
2441 		switch (op) {
2442 		case SOPT_SET:
2443 			if (optlen != sizeof(int)) {
2444 				error = EINVAL;
2445 				break;
2446 			}
2447 			error = sooptcopyin(sopt, &optval, sizeof(optval),
2448 					    sizeof(optval));
2449 			if (error)
2450 				break;
2451 			if (optval < -1 || (optval % 2) != 0) {
2452 				/*
2453 				 * The API assumes non-negative even offset
2454 				 * values or -1 as a special value.
2455 				 */
2456 				error = EINVAL;
2457 			} else if (so->so_proto->pr_protocol ==
2458 			    IPPROTO_ICMPV6) {
2459 				if (optval != icmp6off)
2460 					error = EINVAL;
2461 			} else
2462 				inp->in6p_cksum = optval;
2463 			break;
2464 
2465 		case SOPT_GET:
2466 			if (so->so_proto->pr_protocol == IPPROTO_ICMPV6)
2467 				optval = icmp6off;
2468 			else
2469 				optval = inp->in6p_cksum;
2470 
2471 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2472 			break;
2473 
2474 		default:
2475 			error = EINVAL;
2476 			break;
2477 		}
2478 		break;
2479 
2480 	default:
2481 		error = ENOPROTOOPT;
2482 		break;
2483 	}
2484 
2485 	return (error);
2486 }
2487 
2488 /*
2489  * Set up IP6 options in pcb for insertion in output packets or
2490  * specifying behavior of outgoing packets.
2491  */
2492 static int
2493 ip6_pcbopts(struct ip6_pktopts **pktopt, struct mbuf *m,
2494     struct socket *so, struct sockopt *sopt)
2495 {
2496 	struct ip6_pktopts *opt = *pktopt;
2497 	int error = 0;
2498 	struct thread *td = sopt->sopt_td;
2499 
2500 	/* turn off any old options. */
2501 	if (opt) {
2502 #ifdef DIAGNOSTIC
2503 		if (opt->ip6po_pktinfo || opt->ip6po_nexthop ||
2504 		    opt->ip6po_hbh || opt->ip6po_dest1 || opt->ip6po_dest2 ||
2505 		    opt->ip6po_rhinfo.ip6po_rhi_rthdr)
2506 			printf("ip6_pcbopts: all specified options are cleared.\n");
2507 #endif
2508 		ip6_clearpktopts(opt, -1);
2509 	} else {
2510 		opt = malloc(sizeof(*opt), M_IP6OPT, M_NOWAIT);
2511 		if (opt == NULL)
2512 			return (ENOMEM);
2513 	}
2514 	*pktopt = NULL;
2515 
2516 	if (!m || m->m_len == 0) {
2517 		/*
2518 		 * Only turning off any previous options, regardless of
2519 		 * whether the opt is just created or given.
2520 		 */
2521 		free(opt, M_IP6OPT);
2522 		return (0);
2523 	}
2524 
2525 	/*  set options specified by user. */
2526 	if ((error = ip6_setpktopts(m, opt, NULL, (td != NULL) ?
2527 	    td->td_ucred : NULL, so->so_proto->pr_protocol)) != 0) {
2528 		ip6_clearpktopts(opt, -1); /* XXX: discard all options */
2529 		free(opt, M_IP6OPT);
2530 		return (error);
2531 	}
2532 	*pktopt = opt;
2533 	return (0);
2534 }
2535 
2536 /*
2537  * initialize ip6_pktopts.  beware that there are non-zero default values in
2538  * the struct.
2539  */
2540 void
2541 ip6_initpktopts(struct ip6_pktopts *opt)
2542 {
2543 
2544 	bzero(opt, sizeof(*opt));
2545 	opt->ip6po_hlim = -1;	/* -1 means default hop limit */
2546 	opt->ip6po_tclass = -1;	/* -1 means default traffic class */
2547 	opt->ip6po_minmtu = IP6PO_MINMTU_MCASTONLY;
2548 	opt->ip6po_prefer_tempaddr = IP6PO_TEMPADDR_SYSTEM;
2549 }
2550 
2551 static int
2552 ip6_pcbopt(int optname, u_char *buf, int len, struct ip6_pktopts **pktopt,
2553     struct ucred *cred, int uproto)
2554 {
2555 	struct ip6_pktopts *opt;
2556 
2557 	if (*pktopt == NULL) {
2558 		*pktopt = malloc(sizeof(struct ip6_pktopts), M_IP6OPT,
2559 		    M_NOWAIT);
2560 		if (*pktopt == NULL)
2561 			return (ENOBUFS);
2562 		ip6_initpktopts(*pktopt);
2563 	}
2564 	opt = *pktopt;
2565 
2566 	return (ip6_setpktopt(optname, buf, len, opt, cred, 1, 0, uproto));
2567 }
2568 
2569 #define GET_PKTOPT_VAR(field, lenexpr) do {					\
2570 	if (pktopt && pktopt->field) {						\
2571 		INP_RUNLOCK(inp);						\
2572 		optdata = malloc(sopt->sopt_valsize, M_TEMP, M_WAITOK);		\
2573 		malloc_optdata = true;						\
2574 		INP_RLOCK(inp);							\
2575 		if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {		\
2576 			INP_RUNLOCK(inp);					\
2577 			free(optdata, M_TEMP);					\
2578 			return (ECONNRESET);					\
2579 		}								\
2580 		pktopt = inp->in6p_outputopts;					\
2581 		if (pktopt && pktopt->field) {					\
2582 			optdatalen = min(lenexpr, sopt->sopt_valsize);		\
2583 			bcopy(&pktopt->field, optdata, optdatalen);		\
2584 		} else {							\
2585 			free(optdata, M_TEMP);					\
2586 			optdata = NULL;						\
2587 			malloc_optdata = false;					\
2588 		}								\
2589 	}									\
2590 } while(0)
2591 
2592 #define GET_PKTOPT_EXT_HDR(field) GET_PKTOPT_VAR(field,				\
2593 	(((struct ip6_ext *)pktopt->field)->ip6e_len + 1) << 3)
2594 
2595 #define GET_PKTOPT_SOCKADDR(field) GET_PKTOPT_VAR(field,			\
2596 	pktopt->field->sa_len)
2597 
2598 static int
2599 ip6_getpcbopt(struct inpcb *inp, int optname, struct sockopt *sopt)
2600 {
2601 	void *optdata = NULL;
2602 	bool malloc_optdata = false;
2603 	int optdatalen = 0;
2604 	int error = 0;
2605 	struct in6_pktinfo null_pktinfo;
2606 	int deftclass = 0, on;
2607 	int defminmtu = IP6PO_MINMTU_MCASTONLY;
2608 	int defpreftemp = IP6PO_TEMPADDR_SYSTEM;
2609 	struct ip6_pktopts *pktopt;
2610 
2611 	INP_RLOCK(inp);
2612 	pktopt = inp->in6p_outputopts;
2613 
2614 	switch (optname) {
2615 	case IPV6_PKTINFO:
2616 		optdata = (void *)&null_pktinfo;
2617 		if (pktopt && pktopt->ip6po_pktinfo) {
2618 			bcopy(pktopt->ip6po_pktinfo, &null_pktinfo,
2619 			    sizeof(null_pktinfo));
2620 			in6_clearscope(&null_pktinfo.ipi6_addr);
2621 		} else {
2622 			/* XXX: we don't have to do this every time... */
2623 			bzero(&null_pktinfo, sizeof(null_pktinfo));
2624 		}
2625 		optdatalen = sizeof(struct in6_pktinfo);
2626 		break;
2627 	case IPV6_TCLASS:
2628 		if (pktopt && pktopt->ip6po_tclass >= 0)
2629 			deftclass = pktopt->ip6po_tclass;
2630 		optdata = (void *)&deftclass;
2631 		optdatalen = sizeof(int);
2632 		break;
2633 	case IPV6_HOPOPTS:
2634 		GET_PKTOPT_EXT_HDR(ip6po_hbh);
2635 		break;
2636 	case IPV6_RTHDR:
2637 		GET_PKTOPT_EXT_HDR(ip6po_rthdr);
2638 		break;
2639 	case IPV6_RTHDRDSTOPTS:
2640 		GET_PKTOPT_EXT_HDR(ip6po_dest1);
2641 		break;
2642 	case IPV6_DSTOPTS:
2643 		GET_PKTOPT_EXT_HDR(ip6po_dest2);
2644 		break;
2645 	case IPV6_NEXTHOP:
2646 		GET_PKTOPT_SOCKADDR(ip6po_nexthop);
2647 		break;
2648 	case IPV6_USE_MIN_MTU:
2649 		if (pktopt)
2650 			defminmtu = pktopt->ip6po_minmtu;
2651 		optdata = (void *)&defminmtu;
2652 		optdatalen = sizeof(int);
2653 		break;
2654 	case IPV6_DONTFRAG:
2655 		if (pktopt && ((pktopt->ip6po_flags) & IP6PO_DONTFRAG))
2656 			on = 1;
2657 		else
2658 			on = 0;
2659 		optdata = (void *)&on;
2660 		optdatalen = sizeof(on);
2661 		break;
2662 	case IPV6_PREFER_TEMPADDR:
2663 		if (pktopt)
2664 			defpreftemp = pktopt->ip6po_prefer_tempaddr;
2665 		optdata = (void *)&defpreftemp;
2666 		optdatalen = sizeof(int);
2667 		break;
2668 	default:		/* should not happen */
2669 #ifdef DIAGNOSTIC
2670 		panic("ip6_getpcbopt: unexpected option\n");
2671 #endif
2672 		INP_RUNLOCK(inp);
2673 		return (ENOPROTOOPT);
2674 	}
2675 	INP_RUNLOCK(inp);
2676 
2677 	error = sooptcopyout(sopt, optdata, optdatalen);
2678 	if (malloc_optdata)
2679 		free(optdata, M_TEMP);
2680 
2681 	return (error);
2682 }
2683 
2684 void
2685 ip6_clearpktopts(struct ip6_pktopts *pktopt, int optname)
2686 {
2687 	if (pktopt == NULL)
2688 		return;
2689 
2690 	if (optname == -1 || optname == IPV6_PKTINFO) {
2691 		if (pktopt->ip6po_pktinfo)
2692 			free(pktopt->ip6po_pktinfo, M_IP6OPT);
2693 		pktopt->ip6po_pktinfo = NULL;
2694 	}
2695 	if (optname == -1 || optname == IPV6_HOPLIMIT)
2696 		pktopt->ip6po_hlim = -1;
2697 	if (optname == -1 || optname == IPV6_TCLASS)
2698 		pktopt->ip6po_tclass = -1;
2699 	if (optname == -1 || optname == IPV6_NEXTHOP) {
2700 		if (pktopt->ip6po_nextroute.ro_nh) {
2701 			NH_FREE(pktopt->ip6po_nextroute.ro_nh);
2702 			pktopt->ip6po_nextroute.ro_nh = NULL;
2703 		}
2704 		if (pktopt->ip6po_nexthop)
2705 			free(pktopt->ip6po_nexthop, M_IP6OPT);
2706 		pktopt->ip6po_nexthop = NULL;
2707 	}
2708 	if (optname == -1 || optname == IPV6_HOPOPTS) {
2709 		if (pktopt->ip6po_hbh)
2710 			free(pktopt->ip6po_hbh, M_IP6OPT);
2711 		pktopt->ip6po_hbh = NULL;
2712 	}
2713 	if (optname == -1 || optname == IPV6_RTHDRDSTOPTS) {
2714 		if (pktopt->ip6po_dest1)
2715 			free(pktopt->ip6po_dest1, M_IP6OPT);
2716 		pktopt->ip6po_dest1 = NULL;
2717 	}
2718 	if (optname == -1 || optname == IPV6_RTHDR) {
2719 		if (pktopt->ip6po_rhinfo.ip6po_rhi_rthdr)
2720 			free(pktopt->ip6po_rhinfo.ip6po_rhi_rthdr, M_IP6OPT);
2721 		pktopt->ip6po_rhinfo.ip6po_rhi_rthdr = NULL;
2722 		if (pktopt->ip6po_route.ro_nh) {
2723 			NH_FREE(pktopt->ip6po_route.ro_nh);
2724 			pktopt->ip6po_route.ro_nh = NULL;
2725 		}
2726 	}
2727 	if (optname == -1 || optname == IPV6_DSTOPTS) {
2728 		if (pktopt->ip6po_dest2)
2729 			free(pktopt->ip6po_dest2, M_IP6OPT);
2730 		pktopt->ip6po_dest2 = NULL;
2731 	}
2732 }
2733 
2734 #define PKTOPT_EXTHDRCPY(type) \
2735 do {\
2736 	if (src->type) {\
2737 		int hlen = (((struct ip6_ext *)src->type)->ip6e_len + 1) << 3;\
2738 		dst->type = malloc(hlen, M_IP6OPT, canwait);\
2739 		if (dst->type == NULL)\
2740 			goto bad;\
2741 		bcopy(src->type, dst->type, hlen);\
2742 	}\
2743 } while (/*CONSTCOND*/ 0)
2744 
2745 static int
2746 copypktopts(struct ip6_pktopts *dst, struct ip6_pktopts *src, int canwait)
2747 {
2748 	if (dst == NULL || src == NULL)  {
2749 		printf("ip6_clearpktopts: invalid argument\n");
2750 		return (EINVAL);
2751 	}
2752 
2753 	dst->ip6po_hlim = src->ip6po_hlim;
2754 	dst->ip6po_tclass = src->ip6po_tclass;
2755 	dst->ip6po_flags = src->ip6po_flags;
2756 	dst->ip6po_minmtu = src->ip6po_minmtu;
2757 	dst->ip6po_prefer_tempaddr = src->ip6po_prefer_tempaddr;
2758 	if (src->ip6po_pktinfo) {
2759 		dst->ip6po_pktinfo = malloc(sizeof(*dst->ip6po_pktinfo),
2760 		    M_IP6OPT, canwait);
2761 		if (dst->ip6po_pktinfo == NULL)
2762 			goto bad;
2763 		*dst->ip6po_pktinfo = *src->ip6po_pktinfo;
2764 	}
2765 	if (src->ip6po_nexthop) {
2766 		dst->ip6po_nexthop = malloc(src->ip6po_nexthop->sa_len,
2767 		    M_IP6OPT, canwait);
2768 		if (dst->ip6po_nexthop == NULL)
2769 			goto bad;
2770 		bcopy(src->ip6po_nexthop, dst->ip6po_nexthop,
2771 		    src->ip6po_nexthop->sa_len);
2772 	}
2773 	PKTOPT_EXTHDRCPY(ip6po_hbh);
2774 	PKTOPT_EXTHDRCPY(ip6po_dest1);
2775 	PKTOPT_EXTHDRCPY(ip6po_dest2);
2776 	PKTOPT_EXTHDRCPY(ip6po_rthdr); /* not copy the cached route */
2777 	return (0);
2778 
2779   bad:
2780 	ip6_clearpktopts(dst, -1);
2781 	return (ENOBUFS);
2782 }
2783 #undef PKTOPT_EXTHDRCPY
2784 
2785 struct ip6_pktopts *
2786 ip6_copypktopts(struct ip6_pktopts *src, int canwait)
2787 {
2788 	int error;
2789 	struct ip6_pktopts *dst;
2790 
2791 	dst = malloc(sizeof(*dst), M_IP6OPT, canwait);
2792 	if (dst == NULL)
2793 		return (NULL);
2794 	ip6_initpktopts(dst);
2795 
2796 	if ((error = copypktopts(dst, src, canwait)) != 0) {
2797 		free(dst, M_IP6OPT);
2798 		return (NULL);
2799 	}
2800 
2801 	return (dst);
2802 }
2803 
2804 void
2805 ip6_freepcbopts(struct ip6_pktopts *pktopt)
2806 {
2807 	if (pktopt == NULL)
2808 		return;
2809 
2810 	ip6_clearpktopts(pktopt, -1);
2811 
2812 	free(pktopt, M_IP6OPT);
2813 }
2814 
2815 /*
2816  * Set IPv6 outgoing packet options based on advanced API.
2817  */
2818 int
2819 ip6_setpktopts(struct mbuf *control, struct ip6_pktopts *opt,
2820     struct ip6_pktopts *stickyopt, struct ucred *cred, int uproto)
2821 {
2822 	struct cmsghdr *cm = NULL;
2823 
2824 	if (control == NULL || opt == NULL)
2825 		return (EINVAL);
2826 
2827 	ip6_initpktopts(opt);
2828 	if (stickyopt) {
2829 		int error;
2830 
2831 		/*
2832 		 * If stickyopt is provided, make a local copy of the options
2833 		 * for this particular packet, then override them by ancillary
2834 		 * objects.
2835 		 * XXX: copypktopts() does not copy the cached route to a next
2836 		 * hop (if any).  This is not very good in terms of efficiency,
2837 		 * but we can allow this since this option should be rarely
2838 		 * used.
2839 		 */
2840 		if ((error = copypktopts(opt, stickyopt, M_NOWAIT)) != 0)
2841 			return (error);
2842 	}
2843 
2844 	/*
2845 	 * XXX: Currently, we assume all the optional information is stored
2846 	 * in a single mbuf.
2847 	 */
2848 	if (control->m_next)
2849 		return (EINVAL);
2850 
2851 	for (; control->m_len > 0; control->m_data += CMSG_ALIGN(cm->cmsg_len),
2852 	    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
2853 		int error;
2854 
2855 		if (control->m_len < CMSG_LEN(0))
2856 			return (EINVAL);
2857 
2858 		cm = mtod(control, struct cmsghdr *);
2859 		if (cm->cmsg_len == 0 || cm->cmsg_len > control->m_len)
2860 			return (EINVAL);
2861 		if (cm->cmsg_level != IPPROTO_IPV6)
2862 			continue;
2863 
2864 		error = ip6_setpktopt(cm->cmsg_type, CMSG_DATA(cm),
2865 		    cm->cmsg_len - CMSG_LEN(0), opt, cred, 0, 1, uproto);
2866 		if (error)
2867 			return (error);
2868 	}
2869 
2870 	return (0);
2871 }
2872 
2873 /*
2874  * Set a particular packet option, as a sticky option or an ancillary data
2875  * item.  "len" can be 0 only when it's a sticky option.
2876  * We have 4 cases of combination of "sticky" and "cmsg":
2877  * "sticky=0, cmsg=0": impossible
2878  * "sticky=0, cmsg=1": RFC2292 or RFC3542 ancillary data
2879  * "sticky=1, cmsg=0": RFC3542 socket option
2880  * "sticky=1, cmsg=1": RFC2292 socket option
2881  */
2882 static int
2883 ip6_setpktopt(int optname, u_char *buf, int len, struct ip6_pktopts *opt,
2884     struct ucred *cred, int sticky, int cmsg, int uproto)
2885 {
2886 	int minmtupolicy, preftemp;
2887 	int error;
2888 
2889 	if (!sticky && !cmsg) {
2890 #ifdef DIAGNOSTIC
2891 		printf("ip6_setpktopt: impossible case\n");
2892 #endif
2893 		return (EINVAL);
2894 	}
2895 
2896 	/*
2897 	 * IPV6_2292xxx is for backward compatibility to RFC2292, and should
2898 	 * not be specified in the context of RFC3542.  Conversely,
2899 	 * RFC3542 types should not be specified in the context of RFC2292.
2900 	 */
2901 	if (!cmsg) {
2902 		switch (optname) {
2903 		case IPV6_2292PKTINFO:
2904 		case IPV6_2292HOPLIMIT:
2905 		case IPV6_2292NEXTHOP:
2906 		case IPV6_2292HOPOPTS:
2907 		case IPV6_2292DSTOPTS:
2908 		case IPV6_2292RTHDR:
2909 		case IPV6_2292PKTOPTIONS:
2910 			return (ENOPROTOOPT);
2911 		}
2912 	}
2913 	if (sticky && cmsg) {
2914 		switch (optname) {
2915 		case IPV6_PKTINFO:
2916 		case IPV6_HOPLIMIT:
2917 		case IPV6_NEXTHOP:
2918 		case IPV6_HOPOPTS:
2919 		case IPV6_DSTOPTS:
2920 		case IPV6_RTHDRDSTOPTS:
2921 		case IPV6_RTHDR:
2922 		case IPV6_USE_MIN_MTU:
2923 		case IPV6_DONTFRAG:
2924 		case IPV6_TCLASS:
2925 		case IPV6_PREFER_TEMPADDR: /* XXX: not an RFC3542 option */
2926 			return (ENOPROTOOPT);
2927 		}
2928 	}
2929 
2930 	switch (optname) {
2931 	case IPV6_2292PKTINFO:
2932 	case IPV6_PKTINFO:
2933 	{
2934 		struct ifnet *ifp = NULL;
2935 		struct in6_pktinfo *pktinfo;
2936 
2937 		if (len != sizeof(struct in6_pktinfo))
2938 			return (EINVAL);
2939 
2940 		pktinfo = (struct in6_pktinfo *)buf;
2941 
2942 		/*
2943 		 * An application can clear any sticky IPV6_PKTINFO option by
2944 		 * doing a "regular" setsockopt with ipi6_addr being
2945 		 * in6addr_any and ipi6_ifindex being zero.
2946 		 * [RFC 3542, Section 6]
2947 		 */
2948 		if (optname == IPV6_PKTINFO && opt->ip6po_pktinfo &&
2949 		    pktinfo->ipi6_ifindex == 0 &&
2950 		    IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2951 			ip6_clearpktopts(opt, optname);
2952 			break;
2953 		}
2954 
2955 		if (uproto == IPPROTO_TCP && optname == IPV6_PKTINFO &&
2956 		    sticky && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2957 			return (EINVAL);
2958 		}
2959 		if (IN6_IS_ADDR_MULTICAST(&pktinfo->ipi6_addr))
2960 			return (EINVAL);
2961 		/* validate the interface index if specified. */
2962 		if (pktinfo->ipi6_ifindex > V_if_index)
2963 			 return (ENXIO);
2964 		if (pktinfo->ipi6_ifindex) {
2965 			ifp = ifnet_byindex(pktinfo->ipi6_ifindex);
2966 			if (ifp == NULL)
2967 				return (ENXIO);
2968 		}
2969 		if (ifp != NULL && (ifp->if_afdata[AF_INET6] == NULL ||
2970 		    (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) != 0))
2971 			return (ENETDOWN);
2972 
2973 		if (ifp != NULL &&
2974 		    !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
2975 			struct in6_ifaddr *ia;
2976 
2977 			in6_setscope(&pktinfo->ipi6_addr, ifp, NULL);
2978 			ia = in6ifa_ifpwithaddr(ifp, &pktinfo->ipi6_addr);
2979 			if (ia == NULL)
2980 				return (EADDRNOTAVAIL);
2981 			ifa_free(&ia->ia_ifa);
2982 		}
2983 		/*
2984 		 * We store the address anyway, and let in6_selectsrc()
2985 		 * validate the specified address.  This is because ipi6_addr
2986 		 * may not have enough information about its scope zone, and
2987 		 * we may need additional information (such as outgoing
2988 		 * interface or the scope zone of a destination address) to
2989 		 * disambiguate the scope.
2990 		 * XXX: the delay of the validation may confuse the
2991 		 * application when it is used as a sticky option.
2992 		 */
2993 		if (opt->ip6po_pktinfo == NULL) {
2994 			opt->ip6po_pktinfo = malloc(sizeof(*pktinfo),
2995 			    M_IP6OPT, M_NOWAIT);
2996 			if (opt->ip6po_pktinfo == NULL)
2997 				return (ENOBUFS);
2998 		}
2999 		bcopy(pktinfo, opt->ip6po_pktinfo, sizeof(*pktinfo));
3000 		break;
3001 	}
3002 
3003 	case IPV6_2292HOPLIMIT:
3004 	case IPV6_HOPLIMIT:
3005 	{
3006 		int *hlimp;
3007 
3008 		/*
3009 		 * RFC 3542 deprecated the usage of sticky IPV6_HOPLIMIT
3010 		 * to simplify the ordering among hoplimit options.
3011 		 */
3012 		if (optname == IPV6_HOPLIMIT && sticky)
3013 			return (ENOPROTOOPT);
3014 
3015 		if (len != sizeof(int))
3016 			return (EINVAL);
3017 		hlimp = (int *)buf;
3018 		if (*hlimp < -1 || *hlimp > 255)
3019 			return (EINVAL);
3020 
3021 		opt->ip6po_hlim = *hlimp;
3022 		break;
3023 	}
3024 
3025 	case IPV6_TCLASS:
3026 	{
3027 		int tclass;
3028 
3029 		if (len != sizeof(int))
3030 			return (EINVAL);
3031 		tclass = *(int *)buf;
3032 		if (tclass < -1 || tclass > 255)
3033 			return (EINVAL);
3034 
3035 		opt->ip6po_tclass = tclass;
3036 		break;
3037 	}
3038 
3039 	case IPV6_2292NEXTHOP:
3040 	case IPV6_NEXTHOP:
3041 		if (cred != NULL) {
3042 			error = priv_check_cred(cred, PRIV_NETINET_SETHDROPTS);
3043 			if (error)
3044 				return (error);
3045 		}
3046 
3047 		if (len == 0) {	/* just remove the option */
3048 			ip6_clearpktopts(opt, IPV6_NEXTHOP);
3049 			break;
3050 		}
3051 
3052 		/* check if cmsg_len is large enough for sa_len */
3053 		if (len < sizeof(struct sockaddr) || len < *buf)
3054 			return (EINVAL);
3055 
3056 		switch (((struct sockaddr *)buf)->sa_family) {
3057 		case AF_INET6:
3058 		{
3059 			struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)buf;
3060 			int error;
3061 
3062 			if (sa6->sin6_len != sizeof(struct sockaddr_in6))
3063 				return (EINVAL);
3064 
3065 			if (IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
3066 			    IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) {
3067 				return (EINVAL);
3068 			}
3069 			if ((error = sa6_embedscope(sa6, V_ip6_use_defzone))
3070 			    != 0) {
3071 				return (error);
3072 			}
3073 			break;
3074 		}
3075 		case AF_LINK:	/* should eventually be supported */
3076 		default:
3077 			return (EAFNOSUPPORT);
3078 		}
3079 
3080 		/* turn off the previous option, then set the new option. */
3081 		ip6_clearpktopts(opt, IPV6_NEXTHOP);
3082 		opt->ip6po_nexthop = malloc(*buf, M_IP6OPT, M_NOWAIT);
3083 		if (opt->ip6po_nexthop == NULL)
3084 			return (ENOBUFS);
3085 		bcopy(buf, opt->ip6po_nexthop, *buf);
3086 		break;
3087 
3088 	case IPV6_2292HOPOPTS:
3089 	case IPV6_HOPOPTS:
3090 	{
3091 		struct ip6_hbh *hbh;
3092 		int hbhlen;
3093 
3094 		/*
3095 		 * XXX: We don't allow a non-privileged user to set ANY HbH
3096 		 * options, since per-option restriction has too much
3097 		 * overhead.
3098 		 */
3099 		if (cred != NULL) {
3100 			error = priv_check_cred(cred, PRIV_NETINET_SETHDROPTS);
3101 			if (error)
3102 				return (error);
3103 		}
3104 
3105 		if (len == 0) {
3106 			ip6_clearpktopts(opt, IPV6_HOPOPTS);
3107 			break;	/* just remove the option */
3108 		}
3109 
3110 		/* message length validation */
3111 		if (len < sizeof(struct ip6_hbh))
3112 			return (EINVAL);
3113 		hbh = (struct ip6_hbh *)buf;
3114 		hbhlen = (hbh->ip6h_len + 1) << 3;
3115 		if (len != hbhlen)
3116 			return (EINVAL);
3117 
3118 		/* turn off the previous option, then set the new option. */
3119 		ip6_clearpktopts(opt, IPV6_HOPOPTS);
3120 		opt->ip6po_hbh = malloc(hbhlen, M_IP6OPT, M_NOWAIT);
3121 		if (opt->ip6po_hbh == NULL)
3122 			return (ENOBUFS);
3123 		bcopy(hbh, opt->ip6po_hbh, hbhlen);
3124 
3125 		break;
3126 	}
3127 
3128 	case IPV6_2292DSTOPTS:
3129 	case IPV6_DSTOPTS:
3130 	case IPV6_RTHDRDSTOPTS:
3131 	{
3132 		struct ip6_dest *dest, **newdest = NULL;
3133 		int destlen;
3134 
3135 		if (cred != NULL) { /* XXX: see the comment for IPV6_HOPOPTS */
3136 			error = priv_check_cred(cred, PRIV_NETINET_SETHDROPTS);
3137 			if (error)
3138 				return (error);
3139 		}
3140 
3141 		if (len == 0) {
3142 			ip6_clearpktopts(opt, optname);
3143 			break;	/* just remove the option */
3144 		}
3145 
3146 		/* message length validation */
3147 		if (len < sizeof(struct ip6_dest))
3148 			return (EINVAL);
3149 		dest = (struct ip6_dest *)buf;
3150 		destlen = (dest->ip6d_len + 1) << 3;
3151 		if (len != destlen)
3152 			return (EINVAL);
3153 
3154 		/*
3155 		 * Determine the position that the destination options header
3156 		 * should be inserted; before or after the routing header.
3157 		 */
3158 		switch (optname) {
3159 		case IPV6_2292DSTOPTS:
3160 			/*
3161 			 * The old advacned API is ambiguous on this point.
3162 			 * Our approach is to determine the position based
3163 			 * according to the existence of a routing header.
3164 			 * Note, however, that this depends on the order of the
3165 			 * extension headers in the ancillary data; the 1st
3166 			 * part of the destination options header must appear
3167 			 * before the routing header in the ancillary data,
3168 			 * too.
3169 			 * RFC3542 solved the ambiguity by introducing
3170 			 * separate ancillary data or option types.
3171 			 */
3172 			if (opt->ip6po_rthdr == NULL)
3173 				newdest = &opt->ip6po_dest1;
3174 			else
3175 				newdest = &opt->ip6po_dest2;
3176 			break;
3177 		case IPV6_RTHDRDSTOPTS:
3178 			newdest = &opt->ip6po_dest1;
3179 			break;
3180 		case IPV6_DSTOPTS:
3181 			newdest = &opt->ip6po_dest2;
3182 			break;
3183 		}
3184 
3185 		/* turn off the previous option, then set the new option. */
3186 		ip6_clearpktopts(opt, optname);
3187 		*newdest = malloc(destlen, M_IP6OPT, M_NOWAIT);
3188 		if (*newdest == NULL)
3189 			return (ENOBUFS);
3190 		bcopy(dest, *newdest, destlen);
3191 
3192 		break;
3193 	}
3194 
3195 	case IPV6_2292RTHDR:
3196 	case IPV6_RTHDR:
3197 	{
3198 		struct ip6_rthdr *rth;
3199 		int rthlen;
3200 
3201 		if (len == 0) {
3202 			ip6_clearpktopts(opt, IPV6_RTHDR);
3203 			break;	/* just remove the option */
3204 		}
3205 
3206 		/* message length validation */
3207 		if (len < sizeof(struct ip6_rthdr))
3208 			return (EINVAL);
3209 		rth = (struct ip6_rthdr *)buf;
3210 		rthlen = (rth->ip6r_len + 1) << 3;
3211 		if (len != rthlen)
3212 			return (EINVAL);
3213 
3214 		switch (rth->ip6r_type) {
3215 		case IPV6_RTHDR_TYPE_0:
3216 			if (rth->ip6r_len == 0)	/* must contain one addr */
3217 				return (EINVAL);
3218 			if (rth->ip6r_len % 2) /* length must be even */
3219 				return (EINVAL);
3220 			if (rth->ip6r_len / 2 != rth->ip6r_segleft)
3221 				return (EINVAL);
3222 			break;
3223 		default:
3224 			return (EINVAL);	/* not supported */
3225 		}
3226 
3227 		/* turn off the previous option */
3228 		ip6_clearpktopts(opt, IPV6_RTHDR);
3229 		opt->ip6po_rthdr = malloc(rthlen, M_IP6OPT, M_NOWAIT);
3230 		if (opt->ip6po_rthdr == NULL)
3231 			return (ENOBUFS);
3232 		bcopy(rth, opt->ip6po_rthdr, rthlen);
3233 
3234 		break;
3235 	}
3236 
3237 	case IPV6_USE_MIN_MTU:
3238 		if (len != sizeof(int))
3239 			return (EINVAL);
3240 		minmtupolicy = *(int *)buf;
3241 		if (minmtupolicy != IP6PO_MINMTU_MCASTONLY &&
3242 		    minmtupolicy != IP6PO_MINMTU_DISABLE &&
3243 		    minmtupolicy != IP6PO_MINMTU_ALL) {
3244 			return (EINVAL);
3245 		}
3246 		opt->ip6po_minmtu = minmtupolicy;
3247 		break;
3248 
3249 	case IPV6_DONTFRAG:
3250 		if (len != sizeof(int))
3251 			return (EINVAL);
3252 
3253 		if (uproto == IPPROTO_TCP || *(int *)buf == 0) {
3254 			/*
3255 			 * we ignore this option for TCP sockets.
3256 			 * (RFC3542 leaves this case unspecified.)
3257 			 */
3258 			opt->ip6po_flags &= ~IP6PO_DONTFRAG;
3259 		} else
3260 			opt->ip6po_flags |= IP6PO_DONTFRAG;
3261 		break;
3262 
3263 	case IPV6_PREFER_TEMPADDR:
3264 		if (len != sizeof(int))
3265 			return (EINVAL);
3266 		preftemp = *(int *)buf;
3267 		if (preftemp != IP6PO_TEMPADDR_SYSTEM &&
3268 		    preftemp != IP6PO_TEMPADDR_NOTPREFER &&
3269 		    preftemp != IP6PO_TEMPADDR_PREFER) {
3270 			return (EINVAL);
3271 		}
3272 		opt->ip6po_prefer_tempaddr = preftemp;
3273 		break;
3274 
3275 	default:
3276 		return (ENOPROTOOPT);
3277 	} /* end of switch */
3278 
3279 	return (0);
3280 }
3281 
3282 /*
3283  * Routine called from ip6_output() to loop back a copy of an IP6 multicast
3284  * packet to the input queue of a specified interface.  Note that this
3285  * calls the output routine of the loopback "driver", but with an interface
3286  * pointer that might NOT be &loif -- easier than replicating that code here.
3287  */
3288 void
3289 ip6_mloopback(struct ifnet *ifp, struct mbuf *m)
3290 {
3291 	struct mbuf *copym;
3292 	struct ip6_hdr *ip6;
3293 
3294 	copym = m_copym(m, 0, M_COPYALL, M_NOWAIT);
3295 	if (copym == NULL)
3296 		return;
3297 
3298 	/*
3299 	 * Make sure to deep-copy IPv6 header portion in case the data
3300 	 * is in an mbuf cluster, so that we can safely override the IPv6
3301 	 * header portion later.
3302 	 */
3303 	if (!M_WRITABLE(copym) ||
3304 	    copym->m_len < sizeof(struct ip6_hdr)) {
3305 		copym = m_pullup(copym, sizeof(struct ip6_hdr));
3306 		if (copym == NULL)
3307 			return;
3308 	}
3309 	ip6 = mtod(copym, struct ip6_hdr *);
3310 	/*
3311 	 * clear embedded scope identifiers if necessary.
3312 	 * in6_clearscope will touch the addresses only when necessary.
3313 	 */
3314 	in6_clearscope(&ip6->ip6_src);
3315 	in6_clearscope(&ip6->ip6_dst);
3316 	if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA_IPV6) {
3317 		copym->m_pkthdr.csum_flags |= CSUM_DATA_VALID_IPV6 |
3318 		    CSUM_PSEUDO_HDR;
3319 		copym->m_pkthdr.csum_data = 0xffff;
3320 	}
3321 	if_simloop(ifp, copym, AF_INET6, 0);
3322 }
3323 
3324 /*
3325  * Chop IPv6 header off from the payload.
3326  */
3327 static int
3328 ip6_splithdr(struct mbuf *m, struct ip6_exthdrs *exthdrs)
3329 {
3330 	struct mbuf *mh;
3331 	struct ip6_hdr *ip6;
3332 
3333 	ip6 = mtod(m, struct ip6_hdr *);
3334 	if (m->m_len > sizeof(*ip6)) {
3335 		mh = m_gethdr(M_NOWAIT, MT_DATA);
3336 		if (mh == NULL) {
3337 			m_freem(m);
3338 			return ENOBUFS;
3339 		}
3340 		m_move_pkthdr(mh, m);
3341 		M_ALIGN(mh, sizeof(*ip6));
3342 		m->m_len -= sizeof(*ip6);
3343 		m->m_data += sizeof(*ip6);
3344 		mh->m_next = m;
3345 		m = mh;
3346 		m->m_len = sizeof(*ip6);
3347 		bcopy((caddr_t)ip6, mtod(m, caddr_t), sizeof(*ip6));
3348 	}
3349 	exthdrs->ip6e_ip6 = m;
3350 	return 0;
3351 }
3352 
3353 /*
3354  * Compute IPv6 extension header length.
3355  */
3356 int
3357 ip6_optlen(struct inpcb *inp)
3358 {
3359 	int len;
3360 
3361 	if (!inp->in6p_outputopts)
3362 		return 0;
3363 
3364 	len = 0;
3365 #define elen(x) \
3366     (((struct ip6_ext *)(x)) ? (((struct ip6_ext *)(x))->ip6e_len + 1) << 3 : 0)
3367 
3368 	len += elen(inp->in6p_outputopts->ip6po_hbh);
3369 	if (inp->in6p_outputopts->ip6po_rthdr)
3370 		/* dest1 is valid with rthdr only */
3371 		len += elen(inp->in6p_outputopts->ip6po_dest1);
3372 	len += elen(inp->in6p_outputopts->ip6po_rthdr);
3373 	len += elen(inp->in6p_outputopts->ip6po_dest2);
3374 	return len;
3375 #undef elen
3376 }
3377