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