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