xref: /freebsd/sys/netinet6/frag6.c (revision 051ed84f28e189e22d7a2a7c2b8d6870915362f8)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  * Copyright (c) 2019 Netflix, Inc.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	$KAME: frag6.c,v 1.33 2002/01/07 11:34:48 kjc Exp $
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_rss.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/domain.h>
43 #include <sys/eventhandler.h>
44 #include <sys/hash.h>
45 #include <sys/kernel.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/protosw.h>
49 #include <sys/queue.h>
50 #include <sys/socket.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 
54 #include <net/if.h>
55 #include <net/if_var.h>
56 #include <net/netisr.h>
57 #include <net/route.h>
58 #include <net/vnet.h>
59 
60 #include <netinet/in.h>
61 #include <netinet/in_var.h>
62 #include <netinet/ip6.h>
63 #include <netinet6/ip6_var.h>
64 #include <netinet/icmp6.h>
65 #include <netinet/in_systm.h>	/* For ECN definitions. */
66 #include <netinet/ip.h>		/* For ECN definitions. */
67 
68 #ifdef MAC
69 #include <security/mac/mac_framework.h>
70 #endif
71 
72 /*
73  * A "big picture" of how IPv6 fragment queues are all linked together.
74  *
75  * struct ip6qbucket ip6qb[...];			hashed buckets
76  * ||||||||
77  * |
78  * +--- TAILQ(struct ip6q, packets) *q6;		tailq entries holding
79  *      ||||||||					fragmented packets
80  *      |						(1 per original packet)
81  *      |
82  *      +--- TAILQ(struct ip6asfrag, ip6q_frags) *af6;	tailq entries of IPv6
83  *           |                                   *ip6af;fragment packets
84  *           |						for one original packet
85  *           + *mbuf
86  */
87 
88 /* Reassembly headers are stored in hash buckets. */
89 #define	IP6REASS_NHASH_LOG2	10
90 #define	IP6REASS_NHASH		(1 << IP6REASS_NHASH_LOG2)
91 #define	IP6REASS_HMASK		(IP6REASS_NHASH - 1)
92 
93 TAILQ_HEAD(ip6qhead, ip6q);
94 struct ip6qbucket {
95 	struct ip6qhead	packets;
96 	struct mtx	lock;
97 	int		count;
98 };
99 
100 struct ip6asfrag {
101 	TAILQ_ENTRY(ip6asfrag) ip6af_tq;
102 	struct mbuf	*ip6af_m;
103 	int		ip6af_offset;	/* Offset in ip6af_m to next header. */
104 	int		ip6af_frglen;	/* Fragmentable part length. */
105 	int		ip6af_off;	/* Fragment offset. */
106 	bool		ip6af_mff;	/* More fragment bit in frag off. */
107 };
108 
109 static MALLOC_DEFINE(M_FRAG6, "frag6", "IPv6 fragment reassembly header");
110 
111 #ifdef VIMAGE
112 /* A flag to indicate if IPv6 fragmentation is initialized. */
113 VNET_DEFINE_STATIC(bool,		frag6_on);
114 #define	V_frag6_on			VNET(frag6_on)
115 #endif
116 
117 /* System wide (global) maximum and count of packets in reassembly queues. */
118 static int ip6_maxfrags;
119 static volatile u_int frag6_nfrags = 0;
120 
121 /* Maximum and current packets in per-VNET reassembly queue. */
122 VNET_DEFINE_STATIC(int,			ip6_maxfragpackets);
123 VNET_DEFINE_STATIC(volatile u_int,	frag6_nfragpackets);
124 #define	V_ip6_maxfragpackets		VNET(ip6_maxfragpackets)
125 #define	V_frag6_nfragpackets		VNET(frag6_nfragpackets)
126 
127 /* Maximum per-VNET reassembly queues per bucket and fragments per packet. */
128 VNET_DEFINE_STATIC(int,			ip6_maxfragbucketsize);
129 VNET_DEFINE_STATIC(int,			ip6_maxfragsperpacket);
130 #define	V_ip6_maxfragbucketsize		VNET(ip6_maxfragbucketsize)
131 #define	V_ip6_maxfragsperpacket		VNET(ip6_maxfragsperpacket)
132 
133 /* Per-VNET reassembly queue buckets. */
134 VNET_DEFINE_STATIC(struct ip6qbucket,	ip6qb[IP6REASS_NHASH]);
135 VNET_DEFINE_STATIC(uint32_t,		ip6qb_hashseed);
136 #define	V_ip6qb				VNET(ip6qb)
137 #define	V_ip6qb_hashseed		VNET(ip6qb_hashseed)
138 
139 #define	IP6QB_LOCK(_b)		mtx_lock(&V_ip6qb[(_b)].lock)
140 #define	IP6QB_TRYLOCK(_b)	mtx_trylock(&V_ip6qb[(_b)].lock)
141 #define	IP6QB_LOCK_ASSERT(_b)	mtx_assert(&V_ip6qb[(_b)].lock, MA_OWNED)
142 #define	IP6QB_UNLOCK(_b)	mtx_unlock(&V_ip6qb[(_b)].lock)
143 #define	IP6QB_HEAD(_b)		(&V_ip6qb[(_b)].packets)
144 
145 /*
146  * By default, limit the number of IP6 fragments across all reassembly
147  * queues to  1/32 of the total number of mbuf clusters.
148  *
149  * Limit the total number of reassembly queues per VNET to the
150  * IP6 fragment limit, but ensure the limit will not allow any bucket
151  * to grow above 100 items. (The bucket limit is
152  * IP_MAXFRAGPACKETS / (IPREASS_NHASH / 2), so the 50 is the correct
153  * multiplier to reach a 100-item limit.)
154  * The 100-item limit was chosen as brief testing seems to show that
155  * this produces "reasonable" performance on some subset of systems
156  * under DoS attack.
157  */
158 #define	IP6_MAXFRAGS		(nmbclusters / 32)
159 #define	IP6_MAXFRAGPACKETS	(imin(IP6_MAXFRAGS, IP6REASS_NHASH * 50))
160 
161 
162 /*
163  * Sysctls and helper function.
164  */
165 SYSCTL_DECL(_net_inet6_ip6);
166 
167 SYSCTL_UINT(_net_inet6_ip6, OID_AUTO, frag6_nfrags,
168 	CTLFLAG_RD, __DEVOLATILE(u_int *, &frag6_nfrags), 0,
169 	"Global number of IPv6 fragments across all reassembly queues.");
170 
171 static void
172 frag6_set_bucketsize(void)
173 {
174 	int i;
175 
176 	if ((i = V_ip6_maxfragpackets) > 0)
177 		V_ip6_maxfragbucketsize = imax(i / (IP6REASS_NHASH / 2), 1);
178 }
179 
180 SYSCTL_INT(_net_inet6_ip6, IPV6CTL_MAXFRAGS, maxfrags,
181 	CTLFLAG_RW, &ip6_maxfrags, 0,
182 	"Maximum allowed number of outstanding IPv6 packet fragments. "
183 	"A value of 0 means no fragmented packets will be accepted, while a "
184 	"a value of -1 means no limit");
185 
186 static int
187 sysctl_ip6_maxfragpackets(SYSCTL_HANDLER_ARGS)
188 {
189 	int error, val;
190 
191 	val = V_ip6_maxfragpackets;
192 	error = sysctl_handle_int(oidp, &val, 0, req);
193 	if (error != 0 || !req->newptr)
194 		return (error);
195 	V_ip6_maxfragpackets = val;
196 	frag6_set_bucketsize();
197 	return (0);
198 }
199 SYSCTL_PROC(_net_inet6_ip6, IPV6CTL_MAXFRAGPACKETS, maxfragpackets,
200 	CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, NULL, 0,
201 	sysctl_ip6_maxfragpackets, "I",
202 	"Default maximum number of outstanding fragmented IPv6 packets. "
203 	"A value of 0 means no fragmented packets will be accepted, while a "
204 	"a value of -1 means no limit");
205 SYSCTL_UINT(_net_inet6_ip6, OID_AUTO, frag6_nfragpackets,
206 	CTLFLAG_VNET | CTLFLAG_RD,
207 	__DEVOLATILE(u_int *, &VNET_NAME(frag6_nfragpackets)), 0,
208 	"Per-VNET number of IPv6 fragments across all reassembly queues.");
209 SYSCTL_INT(_net_inet6_ip6, IPV6CTL_MAXFRAGSPERPACKET, maxfragsperpacket,
210 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_maxfragsperpacket), 0,
211 	"Maximum allowed number of fragments per packet");
212 SYSCTL_INT(_net_inet6_ip6, IPV6CTL_MAXFRAGBUCKETSIZE, maxfragbucketsize,
213 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip6_maxfragbucketsize), 0,
214 	"Maximum number of reassembly queues per hash bucket");
215 
216 
217 /*
218  * Remove the IPv6 fragmentation header from the mbuf.
219  */
220 int
221 ip6_deletefraghdr(struct mbuf *m, int offset, int wait)
222 {
223 	struct ip6_hdr *ip6;
224 	struct mbuf *t;
225 
226 	/* Delete frag6 header. */
227 	if (m->m_len >= offset + sizeof(struct ip6_frag)) {
228 
229 		/* This is the only possible case with !PULLDOWN_TEST. */
230 		ip6 = mtod(m, struct ip6_hdr *);
231 		bcopy(ip6, (char *)ip6 + sizeof(struct ip6_frag),
232 		    offset);
233 		m->m_data += sizeof(struct ip6_frag);
234 		m->m_len -= sizeof(struct ip6_frag);
235 	} else {
236 
237 		/* This comes with no copy if the boundary is on cluster. */
238 		if ((t = m_split(m, offset, wait)) == NULL)
239 			return (ENOMEM);
240 		m_adj(t, sizeof(struct ip6_frag));
241 		m_cat(m, t);
242 	}
243 
244 	m->m_flags |= M_FRAGMENTED;
245 	return (0);
246 }
247 
248 /*
249  * Free a fragment reassembly header and all associated datagrams.
250  */
251 static void
252 frag6_freef(struct ip6q *q6, uint32_t bucket)
253 {
254 	struct ip6_hdr *ip6;
255 	struct ip6asfrag *af6;
256 	struct mbuf *m;
257 
258 	IP6QB_LOCK_ASSERT(bucket);
259 
260 	while ((af6 = TAILQ_FIRST(&q6->ip6q_frags)) != NULL) {
261 
262 		m = af6->ip6af_m;
263 		TAILQ_REMOVE(&q6->ip6q_frags, af6, ip6af_tq);
264 
265 		/*
266 		 * Return ICMP time exceeded error for the 1st fragment.
267 		 * Just free other fragments.
268 		 */
269 		if (af6->ip6af_off == 0 && m->m_pkthdr.rcvif != NULL) {
270 
271 			/* Adjust pointer. */
272 			ip6 = mtod(m, struct ip6_hdr *);
273 
274 			/* Restore source and destination addresses. */
275 			ip6->ip6_src = q6->ip6q_src;
276 			ip6->ip6_dst = q6->ip6q_dst;
277 
278 			icmp6_error(m, ICMP6_TIME_EXCEEDED,
279 			    ICMP6_TIME_EXCEED_REASSEMBLY, 0);
280 		} else
281 			m_freem(m);
282 
283 		free(af6, M_FRAG6);
284 	}
285 
286 	TAILQ_REMOVE(IP6QB_HEAD(bucket), q6, ip6q_tq);
287 	V_ip6qb[bucket].count--;
288 	atomic_subtract_int(&frag6_nfrags, q6->ip6q_nfrag);
289 #ifdef MAC
290 	mac_ip6q_destroy(q6);
291 #endif
292 	free(q6, M_FRAG6);
293 	atomic_subtract_int(&V_frag6_nfragpackets, 1);
294 }
295 
296 /*
297  * Drain off all datagram fragments belonging to
298  * the given network interface.
299  */
300 static void
301 frag6_cleanup(void *arg __unused, struct ifnet *ifp)
302 {
303 	struct ip6qhead *head;
304 	struct ip6q *q6;
305 	struct ip6asfrag *af6;
306 	uint32_t bucket;
307 
308 	KASSERT(ifp != NULL, ("%s: ifp is NULL", __func__));
309 
310 	CURVNET_SET_QUIET(ifp->if_vnet);
311 #ifdef VIMAGE
312 	/*
313 	 * Skip processing if IPv6 reassembly is not initialised or
314 	 * torn down by frag6_destroy().
315 	 */
316 	if (!V_frag6_on) {
317 		CURVNET_RESTORE();
318 		return;
319 	}
320 #endif
321 
322 	for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
323 		IP6QB_LOCK(bucket);
324 		head = IP6QB_HEAD(bucket);
325 		/* Scan fragment list. */
326 		TAILQ_FOREACH(q6, head, ip6q_tq) {
327 			TAILQ_FOREACH(af6, &q6->ip6q_frags, ip6af_tq) {
328 
329 				/* Clear no longer valid rcvif pointer. */
330 				if (af6->ip6af_m->m_pkthdr.rcvif == ifp)
331 					af6->ip6af_m->m_pkthdr.rcvif = NULL;
332 			}
333 		}
334 		IP6QB_UNLOCK(bucket);
335 	}
336 	CURVNET_RESTORE();
337 }
338 EVENTHANDLER_DEFINE(ifnet_departure_event, frag6_cleanup, NULL, 0);
339 
340 /*
341  * Like in RFC2460, in RFC8200, fragment and reassembly rules do not agree with
342  * each other, in terms of next header field handling in fragment header.
343  * While the sender will use the same value for all of the fragmented packets,
344  * receiver is suggested not to check for consistency.
345  *
346  * Fragment rules (p18,p19):
347  *	(2)  A Fragment header containing:
348  *	The Next Header value that identifies the first header
349  *	after the Per-Fragment headers of the original packet.
350  *		-> next header field is same for all fragments
351  *
352  * Reassembly rule (p20):
353  *	The Next Header field of the last header of the Per-Fragment
354  *	headers is obtained from the Next Header field of the first
355  *	fragment's Fragment header.
356  *		-> should grab it from the first fragment only
357  *
358  * The following note also contradicts with fragment rule - no one is going to
359  * send different fragment with different next header field.
360  *
361  * Additional note (p22) [not an error]:
362  *	The Next Header values in the Fragment headers of different
363  *	fragments of the same original packet may differ.  Only the value
364  *	from the Offset zero fragment packet is used for reassembly.
365  *		-> should grab it from the first fragment only
366  *
367  * There is no explicit reason given in the RFC.  Historical reason maybe?
368  */
369 /*
370  * Fragment input.
371  */
372 int
373 frag6_input(struct mbuf **mp, int *offp, int proto)
374 {
375 	struct mbuf *m, *t;
376 	struct ip6_hdr *ip6;
377 	struct ip6_frag *ip6f;
378 	struct ip6qhead *head;
379 	struct ip6q *q6;
380 	struct ip6asfrag *af6, *ip6af, *af6tmp;
381 	struct in6_ifaddr *ia6;
382 	struct ifnet *dstifp, *srcifp;
383 	uint32_t hashkey[(sizeof(struct in6_addr) * 2 +
384 		    sizeof(ip6f->ip6f_ident)) / sizeof(uint32_t)];
385 	uint32_t bucket, *hashkeyp;
386 	int fragoff, frgpartlen;	/* Must be larger than uint16_t. */
387 	int nxt, offset, plen;
388 	uint8_t ecn, ecn0;
389 	bool only_frag;
390 #ifdef RSS
391 	struct ip6_direct_ctx *ip6dc;
392 	struct m_tag *mtag;
393 #endif
394 
395 	m = *mp;
396 	offset = *offp;
397 
398 	M_ASSERTPKTHDR(m);
399 
400 	ip6 = mtod(m, struct ip6_hdr *);
401 #ifndef PULLDOWN_TEST
402 	IP6_EXTHDR_CHECK(m, offset, sizeof(struct ip6_frag), IPPROTO_DONE);
403 	ip6f = (struct ip6_frag *)((caddr_t)ip6 + offset);
404 #else
405 	IP6_EXTHDR_GET(ip6f, struct ip6_frag *, m, offset, sizeof(*ip6f));
406 	if (ip6f == NULL)
407 		return (IPPROTO_DONE);
408 #endif
409 
410 	dstifp = NULL;
411 	/* Find the destination interface of the packet. */
412 	ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */);
413 	if (ia6 != NULL) {
414 		dstifp = ia6->ia_ifp;
415 		ifa_free(&ia6->ia_ifa);
416 	}
417 
418 	/* Jumbo payload cannot contain a fragment header. */
419 	if (ip6->ip6_plen == 0) {
420 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER, offset);
421 		in6_ifstat_inc(dstifp, ifs6_reass_fail);
422 		*mp = NULL;
423 		return (IPPROTO_DONE);
424 	}
425 
426 	/*
427 	 * Check whether fragment packet's fragment length is a
428 	 * multiple of 8 octets (unless it is the last one).
429 	 * sizeof(struct ip6_frag) == 8
430 	 * sizeof(struct ip6_hdr) = 40
431 	 */
432 	if ((ip6f->ip6f_offlg & IP6F_MORE_FRAG) &&
433 	    (((ntohs(ip6->ip6_plen) - offset) & 0x7) != 0)) {
434 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
435 		    offsetof(struct ip6_hdr, ip6_plen));
436 		in6_ifstat_inc(dstifp, ifs6_reass_fail);
437 		*mp = NULL;
438 		return (IPPROTO_DONE);
439 	}
440 
441 	IP6STAT_INC(ip6s_fragments);
442 	in6_ifstat_inc(dstifp, ifs6_reass_reqd);
443 
444 	/*
445 	 * Handle "atomic" fragments (offset and m bit set to 0) upfront,
446 	 * unrelated to any reassembly.  We need to remove the frag hdr
447 	 * which is ugly.
448 	 * See RFC 6946 and section 4.5 of RFC 8200.
449 	 */
450 	if ((ip6f->ip6f_offlg & ~IP6F_RESERVED_MASK) == 0) {
451 		IP6STAT_INC(ip6s_atomicfrags);
452 		nxt = ip6f->ip6f_nxt;
453 		/*
454 		 * Set nxt(-hdr field value) to the original value.
455 		 * We cannot just set ip6->ip6_nxt as there might be
456 		 * an unfragmentable part with extension headers and
457 		 * we must update the last one.
458 		 */
459 		m_copyback(m, ip6_get_prevhdr(m, offset), sizeof(uint8_t),
460 		    (caddr_t)&nxt);
461 		ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) -
462 		    sizeof(struct ip6_frag));
463 		if (ip6_deletefraghdr(m, offset, M_NOWAIT) != 0)
464 			goto dropfrag2;
465 		m->m_pkthdr.len -= sizeof(struct ip6_frag);
466 		in6_ifstat_inc(dstifp, ifs6_reass_ok);
467 		*mp = m;
468 		return (nxt);
469 	}
470 
471 	/* Offset now points to data portion. */
472 	offset += sizeof(struct ip6_frag);
473 
474 	/* Get fragment length and discard 0-byte fragments. */
475 	frgpartlen = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen) - offset;
476 	if (frgpartlen == 0) {
477 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
478 		    offsetof(struct ip6_hdr, ip6_plen));
479 		in6_ifstat_inc(dstifp, ifs6_reass_fail);
480 		IP6STAT_INC(ip6s_fragdropped);
481 		*mp = NULL;
482 		return (IPPROTO_DONE);
483 	}
484 
485 	/*
486 	 * Enforce upper bound on number of fragments for the entire system.
487 	 * If maxfrag is 0, never accept fragments.
488 	 * If maxfrag is -1, accept all fragments without limitation.
489 	 */
490 	if (ip6_maxfrags < 0)
491 		;
492 	else if (atomic_load_int(&frag6_nfrags) >= (u_int)ip6_maxfrags)
493 		goto dropfrag2;
494 
495 	/*
496 	 * Validate that a full header chain to the ULP is present in the
497 	 * packet containing the first fragment as per RFC RFC7112 and
498 	 * RFC 8200 pages 18,19:
499 	 * The first fragment packet is composed of:
500 	 * (3)  Extension headers, if any, and the Upper-Layer header.  These
501 	 *      headers must be in the first fragment.  ...
502 	 */
503 	fragoff = ntohs(ip6f->ip6f_offlg & IP6F_OFF_MASK);
504 	/* XXX TODO.  thj has D16851 open for this. */
505 	/* Send ICMPv6 4,3 in case of violation. */
506 
507 	/* Store receive network interface pointer for later. */
508 	srcifp = m->m_pkthdr.rcvif;
509 
510 	/* Generate a hash value for fragment bucket selection. */
511 	hashkeyp = hashkey;
512 	memcpy(hashkeyp, &ip6->ip6_src, sizeof(struct in6_addr));
513 	hashkeyp += sizeof(struct in6_addr) / sizeof(*hashkeyp);
514 	memcpy(hashkeyp, &ip6->ip6_dst, sizeof(struct in6_addr));
515 	hashkeyp += sizeof(struct in6_addr) / sizeof(*hashkeyp);
516 	*hashkeyp = ip6f->ip6f_ident;
517 	bucket = jenkins_hash32(hashkey, nitems(hashkey), V_ip6qb_hashseed);
518 	bucket &= IP6REASS_HMASK;
519 	IP6QB_LOCK(bucket);
520 	head = IP6QB_HEAD(bucket);
521 
522 	TAILQ_FOREACH(q6, head, ip6q_tq)
523 		if (ip6f->ip6f_ident == q6->ip6q_ident &&
524 		    IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &q6->ip6q_src) &&
525 		    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &q6->ip6q_dst)
526 #ifdef MAC
527 		    && mac_ip6q_match(m, q6)
528 #endif
529 		    )
530 			break;
531 
532 	only_frag = false;
533 	if (q6 == NULL) {
534 
535 		/* A first fragment to arrive creates a reassembly queue. */
536 		only_frag = true;
537 
538 		/*
539 		 * Enforce upper bound on number of fragmented packets
540 		 * for which we attempt reassembly;
541 		 * If maxfragpackets is 0, never accept fragments.
542 		 * If maxfragpackets is -1, accept all fragments without
543 		 * limitation.
544 		 */
545 		if (V_ip6_maxfragpackets < 0)
546 			;
547 		else if (V_ip6qb[bucket].count >= V_ip6_maxfragbucketsize ||
548 		    atomic_load_int(&V_frag6_nfragpackets) >=
549 		    (u_int)V_ip6_maxfragpackets)
550 			goto dropfrag;
551 
552 		/* Allocate IPv6 fragement packet queue entry. */
553 		q6 = (struct ip6q *)malloc(sizeof(struct ip6q), M_FRAG6,
554 		    M_NOWAIT | M_ZERO);
555 		if (q6 == NULL)
556 			goto dropfrag;
557 #ifdef MAC
558 		if (mac_ip6q_init(q6, M_NOWAIT) != 0) {
559 			free(q6, M_FRAG6);
560 			goto dropfrag;
561 		}
562 		mac_ip6q_create(m, q6);
563 #endif
564 		atomic_add_int(&V_frag6_nfragpackets, 1);
565 
566 		/* ip6q_nxt will be filled afterwards, from 1st fragment. */
567 		TAILQ_INIT(&q6->ip6q_frags);
568 		q6->ip6q_ident	= ip6f->ip6f_ident;
569 		q6->ip6q_ttl	= IPV6_FRAGTTL;
570 		q6->ip6q_src	= ip6->ip6_src;
571 		q6->ip6q_dst	= ip6->ip6_dst;
572 		q6->ip6q_ecn	=
573 		    (ntohl(ip6->ip6_flow) >> 20) & IPTOS_ECN_MASK;
574 		q6->ip6q_unfrglen = -1;	/* The 1st fragment has not arrived. */
575 
576 		/* Add the fragemented packet to the bucket. */
577 		TAILQ_INSERT_HEAD(head, q6, ip6q_tq);
578 		V_ip6qb[bucket].count++;
579 	}
580 
581 	/*
582 	 * If it is the 1st fragment, record the length of the
583 	 * unfragmentable part and the next header of the fragment header.
584 	 * Assume the first 1st fragement to arrive will be correct.
585 	 * We do not have any duplicate checks here yet so another packet
586 	 * with fragoff == 0 could come and overwrite the ip6q_unfrglen
587 	 * and worse, the next header, at any time.
588 	 */
589 	if (fragoff == 0 && q6->ip6q_unfrglen == -1) {
590 		q6->ip6q_unfrglen = offset - sizeof(struct ip6_hdr) -
591 		    sizeof(struct ip6_frag);
592 		q6->ip6q_nxt = ip6f->ip6f_nxt;
593 		/* XXX ECN? */
594 	}
595 
596 	/*
597 	 * Check that the reassembled packet would not exceed 65535 bytes
598 	 * in size.
599 	 * If it would exceed, discard the fragment and return an ICMP error.
600 	 */
601 	if (q6->ip6q_unfrglen >= 0) {
602 		/* The 1st fragment has already arrived. */
603 		if (q6->ip6q_unfrglen + fragoff + frgpartlen > IPV6_MAXPACKET) {
604 			if (only_frag) {
605 				TAILQ_REMOVE(head, q6, ip6q_tq);
606 				V_ip6qb[bucket].count--;
607 				atomic_subtract_int(&V_frag6_nfragpackets, 1);
608 #ifdef MAC
609 				mac_ip6q_destroy(q6);
610 #endif
611 				free(q6, M_FRAG6);
612 			}
613 			IP6QB_UNLOCK(bucket);
614 			icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
615 			    offset - sizeof(struct ip6_frag) +
616 			    offsetof(struct ip6_frag, ip6f_offlg));
617 			*mp = NULL;
618 			return (IPPROTO_DONE);
619 		}
620 	} else if (fragoff + frgpartlen > IPV6_MAXPACKET) {
621 		if (only_frag) {
622 			TAILQ_REMOVE(head, q6, ip6q_tq);
623 			V_ip6qb[bucket].count--;
624 			atomic_subtract_int(&V_frag6_nfragpackets, 1);
625 #ifdef MAC
626 			mac_ip6q_destroy(q6);
627 #endif
628 			free(q6, M_FRAG6);
629 		}
630 		IP6QB_UNLOCK(bucket);
631 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
632 		    offset - sizeof(struct ip6_frag) +
633 		    offsetof(struct ip6_frag, ip6f_offlg));
634 		*mp = NULL;
635 		return (IPPROTO_DONE);
636 	}
637 
638 	/*
639 	 * If it is the first fragment, do the above check for each
640 	 * fragment already stored in the reassembly queue.
641 	 */
642 	if (fragoff == 0 && !only_frag) {
643 		TAILQ_FOREACH_SAFE(af6, &q6->ip6q_frags, ip6af_tq, af6tmp) {
644 
645 			if (q6->ip6q_unfrglen + af6->ip6af_off +
646 			    af6->ip6af_frglen > IPV6_MAXPACKET) {
647 				struct ip6_hdr *ip6err;
648 				struct mbuf *merr;
649 				int erroff;
650 
651 				merr = af6->ip6af_m;
652 				erroff = af6->ip6af_offset;
653 
654 				/* Dequeue the fragment. */
655 				TAILQ_REMOVE(&q6->ip6q_frags, af6, ip6af_tq);
656 				q6->ip6q_nfrag--;
657 				atomic_subtract_int(&frag6_nfrags, 1);
658 				free(af6, M_FRAG6);
659 
660 				/* Set a valid receive interface pointer. */
661 				merr->m_pkthdr.rcvif = srcifp;
662 
663 				/* Adjust pointer. */
664 				ip6err = mtod(merr, struct ip6_hdr *);
665 
666 				/*
667 				 * Restore source and destination addresses
668 				 * in the erroneous IPv6 header.
669 				 */
670 				ip6err->ip6_src = q6->ip6q_src;
671 				ip6err->ip6_dst = q6->ip6q_dst;
672 
673 				icmp6_error(merr, ICMP6_PARAM_PROB,
674 				    ICMP6_PARAMPROB_HEADER,
675 				    erroff - sizeof(struct ip6_frag) +
676 				    offsetof(struct ip6_frag, ip6f_offlg));
677 			}
678 		}
679 	}
680 
681 	/* Allocate an IPv6 fragement queue entry for this fragmented part. */
682 	ip6af = (struct ip6asfrag *)malloc(sizeof(struct ip6asfrag), M_FRAG6,
683 	    M_NOWAIT | M_ZERO);
684 	if (ip6af == NULL)
685 		goto dropfrag;
686 	ip6af->ip6af_mff = (ip6f->ip6f_offlg & IP6F_MORE_FRAG) ? true : false;
687 	ip6af->ip6af_off = fragoff;
688 	ip6af->ip6af_frglen = frgpartlen;
689 	ip6af->ip6af_offset = offset;
690 	ip6af->ip6af_m = m;
691 
692 	if (only_frag) {
693 		/*
694 		 * Do a manual insert rather than a hard-to-understand cast
695 		 * to a different type relying on data structure order to work.
696 		 */
697 		TAILQ_INSERT_HEAD(&q6->ip6q_frags, ip6af, ip6af_tq);
698 		goto postinsert;
699 	}
700 
701 	/* Do duplicate, condition, and boundry checks. */
702 	/*
703 	 * Handle ECN by comparing this segment with the first one;
704 	 * if CE is set, do not lose CE.
705 	 * Drop if CE and not-ECT are mixed for the same packet.
706 	 */
707 	ecn = (ntohl(ip6->ip6_flow) >> 20) & IPTOS_ECN_MASK;
708 	ecn0 = q6->ip6q_ecn;
709 	if (ecn == IPTOS_ECN_CE) {
710 		if (ecn0 == IPTOS_ECN_NOTECT) {
711 			free(ip6af, M_FRAG6);
712 			goto dropfrag;
713 		}
714 		if (ecn0 != IPTOS_ECN_CE)
715 			q6->ip6q_ecn = IPTOS_ECN_CE;
716 	}
717 	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT) {
718 		free(ip6af, M_FRAG6);
719 		goto dropfrag;
720 	}
721 
722 	/* Find a fragmented part which begins after this one does. */
723 	TAILQ_FOREACH(af6, &q6->ip6q_frags, ip6af_tq)
724 		if (af6->ip6af_off > ip6af->ip6af_off)
725 			break;
726 
727 	/*
728 	 * If the incoming framgent overlaps some existing fragments in
729 	 * the reassembly queue, drop both the new fragment and the
730 	 * entire reassembly queue.  However, if the new fragment
731 	 * is an exact duplicate of an existing fragment, only silently
732 	 * drop the existing fragment and leave the fragmentation queue
733 	 * unchanged, as allowed by the RFC.  (RFC 8200, 4.5)
734 	 */
735 	if (af6 != NULL)
736 		af6tmp = TAILQ_PREV(af6, ip6fraghead, ip6af_tq);
737 	else
738 		af6tmp = TAILQ_LAST(&q6->ip6q_frags, ip6fraghead);
739 	if (af6tmp != NULL) {
740 		if (af6tmp->ip6af_off + af6tmp->ip6af_frglen -
741 		    ip6af->ip6af_off > 0) {
742 			if (af6tmp->ip6af_off != ip6af->ip6af_off ||
743 			    af6tmp->ip6af_frglen != ip6af->ip6af_frglen)
744 				frag6_freef(q6, bucket);
745 			free(ip6af, M_FRAG6);
746 			goto dropfrag;
747 		}
748 	}
749 	if (af6 != NULL) {
750 		if (ip6af->ip6af_off + ip6af->ip6af_frglen -
751 		    af6->ip6af_off > 0) {
752 			if (af6->ip6af_off != ip6af->ip6af_off ||
753 			    af6->ip6af_frglen != ip6af->ip6af_frglen)
754 				frag6_freef(q6, bucket);
755 			free(ip6af, M_FRAG6);
756 			goto dropfrag;
757 		}
758 	}
759 
760 #ifdef MAC
761 	mac_ip6q_update(m, q6);
762 #endif
763 
764 	/*
765 	 * Stick new segment in its place; check for complete reassembly.
766 	 * If not complete, check fragment limit.  Move to front of packet
767 	 * queue, as we are the most recently active fragmented packet.
768 	 */
769 	if (af6 != NULL)
770 		TAILQ_INSERT_BEFORE(af6, ip6af, ip6af_tq);
771 	else
772 		TAILQ_INSERT_TAIL(&q6->ip6q_frags, ip6af, ip6af_tq);
773 postinsert:
774 	atomic_add_int(&frag6_nfrags, 1);
775 	q6->ip6q_nfrag++;
776 
777 	plen = 0;
778 	TAILQ_FOREACH(af6, &q6->ip6q_frags, ip6af_tq) {
779 		if (af6->ip6af_off != plen) {
780 			if (q6->ip6q_nfrag > V_ip6_maxfragsperpacket) {
781 				IP6STAT_ADD(ip6s_fragdropped, q6->ip6q_nfrag);
782 				frag6_freef(q6, bucket);
783 			}
784 			IP6QB_UNLOCK(bucket);
785 			*mp = NULL;
786 			return (IPPROTO_DONE);
787 		}
788 		plen += af6->ip6af_frglen;
789 	}
790 	af6 = TAILQ_LAST(&q6->ip6q_frags, ip6fraghead);
791 	if (af6->ip6af_mff) {
792 		if (q6->ip6q_nfrag > V_ip6_maxfragsperpacket) {
793 			IP6STAT_ADD(ip6s_fragdropped, q6->ip6q_nfrag);
794 			frag6_freef(q6, bucket);
795 		}
796 		IP6QB_UNLOCK(bucket);
797 		*mp = NULL;
798 		return (IPPROTO_DONE);
799 	}
800 
801 	/* Reassembly is complete; concatenate fragments. */
802 	ip6af = TAILQ_FIRST(&q6->ip6q_frags);
803 	t = m = ip6af->ip6af_m;
804 	TAILQ_REMOVE(&q6->ip6q_frags, ip6af, ip6af_tq);
805 	while ((af6 = TAILQ_FIRST(&q6->ip6q_frags)) != NULL) {
806 		m->m_pkthdr.csum_flags &=
807 		    af6->ip6af_m->m_pkthdr.csum_flags;
808 		m->m_pkthdr.csum_data +=
809 		    af6->ip6af_m->m_pkthdr.csum_data;
810 
811 		TAILQ_REMOVE(&q6->ip6q_frags, af6, ip6af_tq);
812 		t = m_last(t);
813 		m_adj(af6->ip6af_m, af6->ip6af_offset);
814 		m_demote_pkthdr(af6->ip6af_m);
815 		m_cat(t, af6->ip6af_m);
816 		free(af6, M_FRAG6);
817 	}
818 
819 	while (m->m_pkthdr.csum_data & 0xffff0000)
820 		m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
821 		    (m->m_pkthdr.csum_data >> 16);
822 
823 	/* Adjust offset to point where the original next header starts. */
824 	offset = ip6af->ip6af_offset - sizeof(struct ip6_frag);
825 	free(ip6af, M_FRAG6);
826 	ip6 = mtod(m, struct ip6_hdr *);
827 	ip6->ip6_plen = htons((u_short)plen + offset - sizeof(struct ip6_hdr));
828 	if (q6->ip6q_ecn == IPTOS_ECN_CE)
829 		ip6->ip6_flow |= htonl(IPTOS_ECN_CE << 20);
830 	nxt = q6->ip6q_nxt;
831 
832 	TAILQ_REMOVE(head, q6, ip6q_tq);
833 	V_ip6qb[bucket].count--;
834 	atomic_subtract_int(&frag6_nfrags, q6->ip6q_nfrag);
835 
836 	if (ip6_deletefraghdr(m, offset, M_NOWAIT) != 0) {
837 #ifdef MAC
838 		mac_ip6q_destroy(q6);
839 #endif
840 		free(q6, M_FRAG6);
841 		atomic_subtract_int(&V_frag6_nfragpackets, 1);
842 
843 		goto dropfrag;
844 	}
845 
846 	/* Set nxt(-hdr field value) to the original value. */
847 	m_copyback(m, ip6_get_prevhdr(m, offset), sizeof(uint8_t),
848 	    (caddr_t)&nxt);
849 
850 #ifdef MAC
851 	mac_ip6q_reassemble(q6, m);
852 	mac_ip6q_destroy(q6);
853 #endif
854 	free(q6, M_FRAG6);
855 	atomic_subtract_int(&V_frag6_nfragpackets, 1);
856 
857 	if (m->m_flags & M_PKTHDR) { /* Isn't it always true? */
858 
859 		plen = 0;
860 		for (t = m; t; t = t->m_next)
861 			plen += t->m_len;
862 		m->m_pkthdr.len = plen;
863 		/* Set a valid receive interface pointer. */
864 		m->m_pkthdr.rcvif = srcifp;
865 	}
866 
867 #ifdef RSS
868 	mtag = m_tag_alloc(MTAG_ABI_IPV6, IPV6_TAG_DIRECT, sizeof(*ip6dc),
869 	    M_NOWAIT);
870 	if (mtag == NULL)
871 		goto dropfrag;
872 
873 	ip6dc = (struct ip6_direct_ctx *)(mtag + 1);
874 	ip6dc->ip6dc_nxt = nxt;
875 	ip6dc->ip6dc_off = offset;
876 
877 	m_tag_prepend(m, mtag);
878 #endif
879 
880 	IP6QB_UNLOCK(bucket);
881 	IP6STAT_INC(ip6s_reassembled);
882 	in6_ifstat_inc(dstifp, ifs6_reass_ok);
883 
884 #ifdef RSS
885 	/* Queue/dispatch for reprocessing. */
886 	netisr_dispatch(NETISR_IPV6_DIRECT, m);
887 	*mp = NULL;
888 	return (IPPROTO_DONE);
889 #endif
890 
891 	/* Tell launch routine the next header. */
892 	*mp = m;
893 	*offp = offset;
894 
895 	return (nxt);
896 
897 dropfrag:
898 	IP6QB_UNLOCK(bucket);
899 dropfrag2:
900 	in6_ifstat_inc(dstifp, ifs6_reass_fail);
901 	IP6STAT_INC(ip6s_fragdropped);
902 	m_freem(m);
903 	*mp = NULL;
904 	return (IPPROTO_DONE);
905 }
906 
907 /*
908  * IPv6 reassembling timer processing;
909  * if a timer expires on a reassembly queue, discard it.
910  */
911 void
912 frag6_slowtimo(void)
913 {
914 	VNET_ITERATOR_DECL(vnet_iter);
915 	struct ip6qhead *head;
916 	struct ip6q *q6, *q6tmp;
917 	uint32_t bucket;
918 
919 	VNET_LIST_RLOCK_NOSLEEP();
920 	VNET_FOREACH(vnet_iter) {
921 		CURVNET_SET(vnet_iter);
922 		for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
923 			IP6QB_LOCK(bucket);
924 			head = IP6QB_HEAD(bucket);
925 			TAILQ_FOREACH_SAFE(q6, head, ip6q_tq, q6tmp)
926 				if (--q6->ip6q_ttl == 0) {
927 					IP6STAT_ADD(ip6s_fragtimeout,
928 						q6->ip6q_nfrag);
929 					/* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
930 					frag6_freef(q6, bucket);
931 				}
932 			/*
933 			 * If we are over the maximum number of fragments
934 			 * (due to the limit being lowered), drain off
935 			 * enough to get down to the new limit.
936 			 * Note that we drain all reassembly queues if
937 			 * maxfragpackets is 0 (fragmentation is disabled),
938 			 * and do not enforce a limit when maxfragpackets
939 			 * is negative.
940 			 */
941 			while ((V_ip6_maxfragpackets == 0 ||
942 			    (V_ip6_maxfragpackets > 0 &&
943 			    V_ip6qb[bucket].count > V_ip6_maxfragbucketsize)) &&
944 			    (q6 = TAILQ_LAST(head, ip6qhead)) != NULL) {
945 				IP6STAT_ADD(ip6s_fragoverflow, q6->ip6q_nfrag);
946 				/* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
947 				frag6_freef(q6, bucket);
948 			}
949 			IP6QB_UNLOCK(bucket);
950 		}
951 		/*
952 		 * If we are still over the maximum number of fragmented
953 		 * packets, drain off enough to get down to the new limit.
954 		 */
955 		bucket = 0;
956 		while (V_ip6_maxfragpackets >= 0 &&
957 		    atomic_load_int(&V_frag6_nfragpackets) >
958 		    (u_int)V_ip6_maxfragpackets) {
959 			IP6QB_LOCK(bucket);
960 			q6 = TAILQ_LAST(IP6QB_HEAD(bucket), ip6qhead);
961 			if (q6 != NULL) {
962 				IP6STAT_ADD(ip6s_fragoverflow, q6->ip6q_nfrag);
963 				/* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
964 				frag6_freef(q6, bucket);
965 			}
966 			IP6QB_UNLOCK(bucket);
967 			bucket = (bucket + 1) % IP6REASS_NHASH;
968 		}
969 		CURVNET_RESTORE();
970 	}
971 	VNET_LIST_RUNLOCK_NOSLEEP();
972 }
973 
974 /*
975  * Eventhandler to adjust limits in case nmbclusters change.
976  */
977 static void
978 frag6_change(void *tag)
979 {
980 	VNET_ITERATOR_DECL(vnet_iter);
981 
982 	ip6_maxfrags = IP6_MAXFRAGS;
983 	VNET_LIST_RLOCK_NOSLEEP();
984 	VNET_FOREACH(vnet_iter) {
985 		CURVNET_SET(vnet_iter);
986 		V_ip6_maxfragpackets = IP6_MAXFRAGPACKETS;
987 		frag6_set_bucketsize();
988 		CURVNET_RESTORE();
989 	}
990 	VNET_LIST_RUNLOCK_NOSLEEP();
991 }
992 
993 /*
994  * Initialise reassembly queue and fragment identifier.
995  */
996 void
997 frag6_init(void)
998 {
999 	uint32_t bucket;
1000 
1001 	V_ip6_maxfragpackets = IP6_MAXFRAGPACKETS;
1002 	frag6_set_bucketsize();
1003 	for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
1004 		TAILQ_INIT(IP6QB_HEAD(bucket));
1005 		mtx_init(&V_ip6qb[bucket].lock, "ip6qb", NULL, MTX_DEF);
1006 		V_ip6qb[bucket].count = 0;
1007 	}
1008 	V_ip6qb_hashseed = arc4random();
1009 	V_ip6_maxfragsperpacket = 64;
1010 #ifdef VIMAGE
1011 	V_frag6_on = true;
1012 #endif
1013 	if (!IS_DEFAULT_VNET(curvnet))
1014 		return;
1015 
1016 	ip6_maxfrags = IP6_MAXFRAGS;
1017 	EVENTHANDLER_REGISTER(nmbclusters_change,
1018 	    frag6_change, NULL, EVENTHANDLER_PRI_ANY);
1019 }
1020 
1021 /*
1022  * Drain off all datagram fragments.
1023  */
1024 static void
1025 frag6_drain_one(void)
1026 {
1027 	struct ip6q *q6;
1028 	uint32_t bucket;
1029 
1030 	for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
1031 		IP6QB_LOCK(bucket);
1032 		while ((q6 = TAILQ_FIRST(IP6QB_HEAD(bucket))) != NULL) {
1033 			IP6STAT_INC(ip6s_fragdropped);
1034 			/* XXX in6_ifstat_inc(ifp, ifs6_reass_fail) */
1035 			frag6_freef(q6, bucket);
1036 		}
1037 		IP6QB_UNLOCK(bucket);
1038 	}
1039 }
1040 
1041 void
1042 frag6_drain(void)
1043 {
1044 	VNET_ITERATOR_DECL(vnet_iter);
1045 
1046 	VNET_LIST_RLOCK_NOSLEEP();
1047 	VNET_FOREACH(vnet_iter) {
1048 		CURVNET_SET(vnet_iter);
1049 		frag6_drain_one();
1050 		CURVNET_RESTORE();
1051 	}
1052 	VNET_LIST_RUNLOCK_NOSLEEP();
1053 }
1054 
1055 #ifdef VIMAGE
1056 /*
1057  * Clear up IPv6 reassembly structures.
1058  */
1059 void
1060 frag6_destroy(void)
1061 {
1062 	uint32_t bucket;
1063 
1064 	frag6_drain_one();
1065 	V_frag6_on = false;
1066 	for (bucket = 0; bucket < IP6REASS_NHASH; bucket++) {
1067 		KASSERT(V_ip6qb[bucket].count == 0,
1068 		    ("%s: V_ip6qb[%d] (%p) count not 0 (%d)", __func__,
1069 		    bucket, &V_ip6qb[bucket], V_ip6qb[bucket].count));
1070 		mtx_destroy(&V_ip6qb[bucket].lock);
1071 	}
1072 }
1073 #endif
1074