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