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