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