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