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