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