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