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