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