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