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