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