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