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