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