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