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