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