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