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