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