xref: /freebsd/sys/netinet/ip_reass.c (revision c8bc8741)
1 /*-
2  * Copyright (c) 2015 Gleb Smirnoff <glebius@FreeBSD.org>
3  * Copyright (c) 2015 Adrian Chadd <adrian@FreeBSD.org>
4  * Copyright (c) 1982, 1986, 1988, 1993
5  *	The Regents of the University of California.  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 University 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 REGENTS 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 REGENTS 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  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
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/eventhandler.h>
42 #include <sys/kernel.h>
43 #include <sys/hash.h>
44 #include <sys/mbuf.h>
45 #include <sys/malloc.h>
46 #include <sys/limits.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/sysctl.h>
50 #include <sys/socket.h>
51 
52 #include <net/if.h>
53 #include <net/if_var.h>
54 #include <net/rss_config.h>
55 #include <net/netisr.h>
56 #include <net/vnet.h>
57 
58 #include <netinet/in.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip_var.h>
61 #include <netinet/in_rss.h>
62 #ifdef MAC
63 #include <security/mac/mac_framework.h>
64 #endif
65 
66 SYSCTL_DECL(_net_inet_ip);
67 
68 /*
69  * Reassembly headers are stored in hash buckets.
70  */
71 #define	IPREASS_NHASH_LOG2	10
72 #define	IPREASS_NHASH		(1 << IPREASS_NHASH_LOG2)
73 #define	IPREASS_HMASK		(V_ipq_hashsize - 1)
74 
75 struct ipqbucket {
76 	TAILQ_HEAD(ipqhead, ipq) head;
77 	struct mtx		 lock;
78 	struct callout		 timer;
79 #ifdef VIMAGE
80 	struct vnet		 *vnet;
81 #endif
82 	int			 count;
83 };
84 
85 VNET_DEFINE_STATIC(struct ipqbucket *, ipq);
86 #define	V_ipq		VNET(ipq)
87 VNET_DEFINE_STATIC(uint32_t, ipq_hashseed);
88 #define	V_ipq_hashseed	VNET(ipq_hashseed)
89 VNET_DEFINE_STATIC(uint32_t, ipq_hashsize);
90 #define	V_ipq_hashsize	VNET(ipq_hashsize)
91 
92 #define	IPQ_LOCK(i)	mtx_lock(&V_ipq[i].lock)
93 #define	IPQ_TRYLOCK(i)	mtx_trylock(&V_ipq[i].lock)
94 #define	IPQ_UNLOCK(i)	mtx_unlock(&V_ipq[i].lock)
95 #define	IPQ_LOCK_ASSERT(i)	mtx_assert(&V_ipq[i].lock, MA_OWNED)
96 #define	IPQ_BUCKET_LOCK_ASSERT(b)	mtx_assert(&(b)->lock, MA_OWNED)
97 
98 VNET_DEFINE_STATIC(int, ipreass_maxbucketsize);
99 #define	V_ipreass_maxbucketsize	VNET(ipreass_maxbucketsize)
100 
101 void		ipreass_init(void);
102 void		ipreass_vnet_init(void);
103 #ifdef VIMAGE
104 void		ipreass_destroy(void);
105 #endif
106 static int	sysctl_maxfragpackets(SYSCTL_HANDLER_ARGS);
107 static int	sysctl_maxfragbucketsize(SYSCTL_HANDLER_ARGS);
108 static int	sysctl_fragttl(SYSCTL_HANDLER_ARGS);
109 static void	ipreass_zone_change(void *);
110 static void	ipreass_drain_tomax(void);
111 static void	ipq_free(struct ipqbucket *, struct ipq *);
112 static struct ipq * ipq_reuse(int);
113 static void	ipreass_callout(void *);
114 static void	ipreass_reschedule(struct ipqbucket *);
115 
116 static inline void
117 ipq_timeout(struct ipqbucket *bucket, struct ipq *fp)
118 {
119 
120 	IPSTAT_ADD(ips_fragtimeout, fp->ipq_nfrags);
121 	ipq_free(bucket, fp);
122 }
123 
124 static inline void
125 ipq_drop(struct ipqbucket *bucket, struct ipq *fp)
126 {
127 
128 	IPSTAT_ADD(ips_fragdropped, fp->ipq_nfrags);
129 	ipq_free(bucket, fp);
130 	ipreass_reschedule(bucket);
131 }
132 
133 /*
134  * By default, limit the number of IP fragments across all reassembly
135  * queues to  1/32 of the total number of mbuf clusters.
136  *
137  * Limit the total number of reassembly queues per VNET to the
138  * IP fragment limit, but ensure the limit will not allow any bucket
139  * to grow above 100 items. (The bucket limit is
140  * IP_MAXFRAGPACKETS / (V_ipq_hashsize / 2), so the 50 is the correct
141  * multiplier to reach a 100-item limit.)
142  * The 100-item limit was chosen as brief testing seems to show that
143  * this produces "reasonable" performance on some subset of systems
144  * under DoS attack.
145  */
146 #define	IP_MAXFRAGS		(nmbclusters / 32)
147 #define	IP_MAXFRAGPACKETS	(imin(IP_MAXFRAGS, V_ipq_hashsize * 50))
148 
149 static int		maxfrags;
150 static u_int __exclusive_cache_line	nfrags;
151 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfrags, CTLFLAG_RW,
152     &maxfrags, 0,
153     "Maximum number of IPv4 fragments allowed across all reassembly queues");
154 SYSCTL_UINT(_net_inet_ip, OID_AUTO, curfrags, CTLFLAG_RD,
155     &nfrags, 0,
156     "Current number of IPv4 fragments across all reassembly queues");
157 
158 VNET_DEFINE_STATIC(uma_zone_t, ipq_zone);
159 #define	V_ipq_zone	VNET(ipq_zone)
160 
161 SYSCTL_UINT(_net_inet_ip, OID_AUTO, reass_hashsize,
162     CTLFLAG_VNET | CTLFLAG_RDTUN, &VNET_NAME(ipq_hashsize), 0,
163     "Size of IP fragment reassembly hashtable");
164 
165 SYSCTL_PROC(_net_inet_ip, OID_AUTO, maxfragpackets,
166     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
167     NULL, 0, sysctl_maxfragpackets, "I",
168     "Maximum number of IPv4 fragment reassembly queue entries");
169 SYSCTL_UMA_CUR(_net_inet_ip, OID_AUTO, fragpackets, CTLFLAG_VNET,
170     &VNET_NAME(ipq_zone),
171     "Current number of IPv4 fragment reassembly queue entries");
172 
173 VNET_DEFINE_STATIC(int, noreass);
174 #define	V_noreass	VNET(noreass)
175 
176 VNET_DEFINE_STATIC(int, maxfragsperpacket);
177 #define	V_maxfragsperpacket	VNET(maxfragsperpacket)
178 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_VNET | CTLFLAG_RW,
179     &VNET_NAME(maxfragsperpacket), 0,
180     "Maximum number of IPv4 fragments allowed per packet");
181 SYSCTL_PROC(_net_inet_ip, OID_AUTO, maxfragbucketsize,
182     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0,
183     sysctl_maxfragbucketsize, "I",
184     "Maximum number of IPv4 fragment reassembly queue entries per bucket");
185 
186 VNET_DEFINE_STATIC(u_int, ipfragttl) = 30;
187 #define	V_ipfragttl	VNET(ipfragttl)
188 SYSCTL_PROC(_net_inet_ip, OID_AUTO, fragttl, CTLTYPE_INT | CTLFLAG_RW |
189     CTLFLAG_MPSAFE | CTLFLAG_VNET, NULL, 0, sysctl_fragttl, "IU",
190     "IP fragment life time on reassembly queue (seconds)");
191 
192 /*
193  * Take incoming datagram fragment and try to reassemble it into
194  * whole datagram.  If the argument is the first fragment or one
195  * in between the function will return NULL and store the mbuf
196  * in the fragment chain.  If the argument is the last fragment
197  * the packet will be reassembled and the pointer to the new
198  * mbuf returned for further processing.  Only m_tags attached
199  * to the first packet/fragment are preserved.
200  * The IP header is *NOT* adjusted out of iplen.
201  */
202 #define	M_IP_FRAG	M_PROTO9
203 struct mbuf *
204 ip_reass(struct mbuf *m)
205 {
206 	struct ip *ip;
207 	struct mbuf *p, *q, *nq, *t;
208 	struct ipq *fp;
209 	struct ifnet *srcifp;
210 	struct ipqhead *head;
211 	int i, hlen, next, tmpmax;
212 	u_int8_t ecn, ecn0;
213 	uint32_t hash, hashkey[3];
214 #ifdef	RSS
215 	uint32_t rss_hash, rss_type;
216 #endif
217 
218 	/*
219 	 * If no reassembling or maxfragsperpacket are 0,
220 	 * never accept fragments.
221 	 * Also, drop packet if it would exceed the maximum
222 	 * number of fragments.
223 	 */
224 	tmpmax = maxfrags;
225 	if (V_noreass == 1 || V_maxfragsperpacket == 0 ||
226 	    (tmpmax >= 0 && atomic_load_int(&nfrags) >= (u_int)tmpmax)) {
227 		IPSTAT_INC(ips_fragments);
228 		IPSTAT_INC(ips_fragdropped);
229 		m_freem(m);
230 		return (NULL);
231 	}
232 
233 	ip = mtod(m, struct ip *);
234 	hlen = ip->ip_hl << 2;
235 
236 	/*
237 	 * Adjust ip_len to not reflect header,
238 	 * convert offset of this to bytes.
239 	 */
240 	ip->ip_len = htons(ntohs(ip->ip_len) - hlen);
241 	/*
242 	 * Make sure that fragments have a data length
243 	 * that's a non-zero multiple of 8 bytes, unless
244 	 * this is the last fragment.
245 	 */
246 	if (ip->ip_len == htons(0) ||
247 	    ((ip->ip_off & htons(IP_MF)) && (ntohs(ip->ip_len) & 0x7) != 0)) {
248 		IPSTAT_INC(ips_toosmall); /* XXX */
249 		IPSTAT_INC(ips_fragdropped);
250 		m_freem(m);
251 		return (NULL);
252 	}
253 	if (ip->ip_off & htons(IP_MF))
254 		m->m_flags |= M_IP_FRAG;
255 	else
256 		m->m_flags &= ~M_IP_FRAG;
257 	ip->ip_off = htons(ntohs(ip->ip_off) << 3);
258 
259 	/*
260 	 * Make sure the fragment lies within a packet of valid size.
261 	 */
262 	if (ntohs(ip->ip_len) + ntohs(ip->ip_off) > IP_MAXPACKET) {
263 		IPSTAT_INC(ips_toolong);
264 		IPSTAT_INC(ips_fragdropped);
265 		m_freem(m);
266 		return (NULL);
267 	}
268 
269 	/*
270 	 * Store receive network interface pointer for later.
271 	 */
272 	srcifp = m->m_pkthdr.rcvif;
273 
274 	/*
275 	 * Attempt reassembly; if it succeeds, proceed.
276 	 * ip_reass() will return a different mbuf.
277 	 */
278 	IPSTAT_INC(ips_fragments);
279 	m->m_pkthdr.PH_loc.ptr = ip;
280 
281 	/*
282 	 * Presence of header sizes in mbufs
283 	 * would confuse code below.
284 	 */
285 	m->m_data += hlen;
286 	m->m_len -= hlen;
287 
288 	hashkey[0] = ip->ip_src.s_addr;
289 	hashkey[1] = ip->ip_dst.s_addr;
290 	hashkey[2] = (uint32_t)ip->ip_p << 16;
291 	hashkey[2] += ip->ip_id;
292 	hash = jenkins_hash32(hashkey, nitems(hashkey), V_ipq_hashseed);
293 	hash &= IPREASS_HMASK;
294 	head = &V_ipq[hash].head;
295 	IPQ_LOCK(hash);
296 
297 	/*
298 	 * Look for queue of fragments
299 	 * of this datagram.
300 	 */
301 	TAILQ_FOREACH(fp, head, ipq_list)
302 		if (ip->ip_id == fp->ipq_id &&
303 		    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
304 		    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
305 #ifdef MAC
306 		    mac_ipq_match(m, fp) &&
307 #endif
308 		    ip->ip_p == fp->ipq_p)
309 			break;
310 	/*
311 	 * If first fragment to arrive, create a reassembly queue.
312 	 */
313 	if (fp == NULL) {
314 		if (V_ipq[hash].count < V_ipreass_maxbucketsize)
315 			fp = uma_zalloc(V_ipq_zone, M_NOWAIT);
316 		if (fp == NULL)
317 			fp = ipq_reuse(hash);
318 		if (fp == NULL)
319 			goto dropfrag;
320 #ifdef MAC
321 		if (mac_ipq_init(fp, M_NOWAIT) != 0) {
322 			uma_zfree(V_ipq_zone, fp);
323 			fp = NULL;
324 			goto dropfrag;
325 		}
326 		mac_ipq_create(m, fp);
327 #endif
328 		TAILQ_INSERT_HEAD(head, fp, ipq_list);
329 		V_ipq[hash].count++;
330 		fp->ipq_nfrags = 1;
331 		atomic_add_int(&nfrags, 1);
332 		fp->ipq_expire = time_uptime + V_ipfragttl;
333 		fp->ipq_p = ip->ip_p;
334 		fp->ipq_id = ip->ip_id;
335 		fp->ipq_src = ip->ip_src;
336 		fp->ipq_dst = ip->ip_dst;
337 		fp->ipq_frags = m;
338 		if (m->m_flags & M_IP_FRAG)
339 			fp->ipq_maxoff = -1;
340 		else
341 			fp->ipq_maxoff = ntohs(ip->ip_off) + ntohs(ip->ip_len);
342 		m->m_nextpkt = NULL;
343 		if (fp == TAILQ_LAST(head, ipqhead))
344 			callout_reset_sbt(&V_ipq[hash].timer,
345 			    SBT_1S * V_ipfragttl, SBT_1S, ipreass_callout,
346 			    &V_ipq[hash], 0);
347 		else
348 			MPASS(callout_active(&V_ipq[hash].timer));
349 		goto done;
350 	} else {
351 		/*
352 		 * If we already saw the last fragment, make sure
353 		 * this fragment's offset looks sane. Otherwise, if
354 		 * this is the last fragment, record its endpoint.
355 		 */
356 		if (fp->ipq_maxoff > 0) {
357 			i = ntohs(ip->ip_off) + ntohs(ip->ip_len);
358 			if (((m->m_flags & M_IP_FRAG) && i >= fp->ipq_maxoff) ||
359 			    ((m->m_flags & M_IP_FRAG) == 0 &&
360 			    i != fp->ipq_maxoff)) {
361 				fp = NULL;
362 				goto dropfrag;
363 			}
364 		} else if ((m->m_flags & M_IP_FRAG) == 0)
365 			fp->ipq_maxoff = ntohs(ip->ip_off) + ntohs(ip->ip_len);
366 		fp->ipq_nfrags++;
367 		atomic_add_int(&nfrags, 1);
368 #ifdef MAC
369 		mac_ipq_update(m, fp);
370 #endif
371 	}
372 
373 #define GETIP(m)	((struct ip*)((m)->m_pkthdr.PH_loc.ptr))
374 
375 	/*
376 	 * Handle ECN by comparing this segment with the first one;
377 	 * if CE is set, do not lose CE.
378 	 * drop if CE and not-ECT are mixed for the same packet.
379 	 */
380 	ecn = ip->ip_tos & IPTOS_ECN_MASK;
381 	ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
382 	if (ecn == IPTOS_ECN_CE) {
383 		if (ecn0 == IPTOS_ECN_NOTECT)
384 			goto dropfrag;
385 		if (ecn0 != IPTOS_ECN_CE)
386 			GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
387 	}
388 	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT)
389 		goto dropfrag;
390 
391 	/*
392 	 * Find a segment which begins after this one does.
393 	 */
394 	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
395 		if (ntohs(GETIP(q)->ip_off) > ntohs(ip->ip_off))
396 			break;
397 
398 	/*
399 	 * If there is a preceding segment, it may provide some of
400 	 * our data already.  If so, drop the data from the incoming
401 	 * segment.  If it provides all of our data, drop us, otherwise
402 	 * stick new segment in the proper place.
403 	 *
404 	 * If some of the data is dropped from the preceding
405 	 * segment, then it's checksum is invalidated.
406 	 */
407 	if (p) {
408 		i = ntohs(GETIP(p)->ip_off) + ntohs(GETIP(p)->ip_len) -
409 		    ntohs(ip->ip_off);
410 		if (i > 0) {
411 			if (i >= ntohs(ip->ip_len))
412 				goto dropfrag;
413 			m_adj(m, i);
414 			m->m_pkthdr.csum_flags = 0;
415 			ip->ip_off = htons(ntohs(ip->ip_off) + i);
416 			ip->ip_len = htons(ntohs(ip->ip_len) - i);
417 		}
418 		m->m_nextpkt = p->m_nextpkt;
419 		p->m_nextpkt = m;
420 	} else {
421 		m->m_nextpkt = fp->ipq_frags;
422 		fp->ipq_frags = m;
423 	}
424 
425 	/*
426 	 * While we overlap succeeding segments trim them or,
427 	 * if they are completely covered, dequeue them.
428 	 */
429 	for (; q != NULL && ntohs(ip->ip_off) + ntohs(ip->ip_len) >
430 	    ntohs(GETIP(q)->ip_off); q = nq) {
431 		i = (ntohs(ip->ip_off) + ntohs(ip->ip_len)) -
432 		    ntohs(GETIP(q)->ip_off);
433 		if (i < ntohs(GETIP(q)->ip_len)) {
434 			GETIP(q)->ip_len = htons(ntohs(GETIP(q)->ip_len) - i);
435 			GETIP(q)->ip_off = htons(ntohs(GETIP(q)->ip_off) + i);
436 			m_adj(q, i);
437 			q->m_pkthdr.csum_flags = 0;
438 			break;
439 		}
440 		nq = q->m_nextpkt;
441 		m->m_nextpkt = nq;
442 		IPSTAT_INC(ips_fragdropped);
443 		fp->ipq_nfrags--;
444 		atomic_subtract_int(&nfrags, 1);
445 		m_freem(q);
446 	}
447 
448 	/*
449 	 * Check for complete reassembly and perform frag per packet
450 	 * limiting.
451 	 *
452 	 * Frag limiting is performed here so that the nth frag has
453 	 * a chance to complete the packet before we drop the packet.
454 	 * As a result, n+1 frags are actually allowed per packet, but
455 	 * only n will ever be stored. (n = maxfragsperpacket.)
456 	 *
457 	 */
458 	next = 0;
459 	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
460 		if (ntohs(GETIP(q)->ip_off) != next) {
461 			if (fp->ipq_nfrags > V_maxfragsperpacket)
462 				ipq_drop(&V_ipq[hash], fp);
463 			goto done;
464 		}
465 		next += ntohs(GETIP(q)->ip_len);
466 	}
467 	/* Make sure the last packet didn't have the IP_MF flag */
468 	if (p->m_flags & M_IP_FRAG) {
469 		if (fp->ipq_nfrags > V_maxfragsperpacket)
470 			ipq_drop(&V_ipq[hash], fp);
471 		goto done;
472 	}
473 
474 	/*
475 	 * Reassembly is complete.  Make sure the packet is a sane size.
476 	 */
477 	q = fp->ipq_frags;
478 	ip = GETIP(q);
479 	if (next + (ip->ip_hl << 2) > IP_MAXPACKET) {
480 		IPSTAT_INC(ips_toolong);
481 		ipq_drop(&V_ipq[hash], fp);
482 		goto done;
483 	}
484 
485 	/*
486 	 * Concatenate fragments.
487 	 */
488 	m = q;
489 	t = m->m_next;
490 	m->m_next = NULL;
491 	m_cat(m, t);
492 	nq = q->m_nextpkt;
493 	q->m_nextpkt = NULL;
494 	for (q = nq; q != NULL; q = nq) {
495 		nq = q->m_nextpkt;
496 		q->m_nextpkt = NULL;
497 		m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
498 		m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
499 		m_demote_pkthdr(q);
500 		m_cat(m, q);
501 	}
502 	/*
503 	 * In order to do checksumming faster we do 'end-around carry' here
504 	 * (and not in for{} loop), though it implies we are not going to
505 	 * reassemble more than 64k fragments.
506 	 */
507 	while (m->m_pkthdr.csum_data & 0xffff0000)
508 		m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
509 		    (m->m_pkthdr.csum_data >> 16);
510 	atomic_subtract_int(&nfrags, fp->ipq_nfrags);
511 #ifdef MAC
512 	mac_ipq_reassemble(fp, m);
513 	mac_ipq_destroy(fp);
514 #endif
515 
516 	/*
517 	 * Create header for new ip packet by modifying header of first
518 	 * packet;  dequeue and discard fragment reassembly header.
519 	 * Make header visible.
520 	 */
521 	ip->ip_len = htons((ip->ip_hl << 2) + next);
522 	ip->ip_src = fp->ipq_src;
523 	ip->ip_dst = fp->ipq_dst;
524 	TAILQ_REMOVE(head, fp, ipq_list);
525 	V_ipq[hash].count--;
526 	uma_zfree(V_ipq_zone, fp);
527 	m->m_len += (ip->ip_hl << 2);
528 	m->m_data -= (ip->ip_hl << 2);
529 	/* some debugging cruft by sklower, below, will go away soon */
530 	if (m->m_flags & M_PKTHDR) {	/* XXX this should be done elsewhere */
531 		m_fixhdr(m);
532 		/* set valid receive interface pointer */
533 		m->m_pkthdr.rcvif = srcifp;
534 	}
535 	IPSTAT_INC(ips_reassembled);
536 	ipreass_reschedule(&V_ipq[hash]);
537 	IPQ_UNLOCK(hash);
538 
539 #ifdef	RSS
540 	/*
541 	 * Query the RSS layer for the flowid / flowtype for the
542 	 * mbuf payload.
543 	 *
544 	 * For now, just assume we have to calculate a new one.
545 	 * Later on we should check to see if the assigned flowid matches
546 	 * what RSS wants for the given IP protocol and if so, just keep it.
547 	 *
548 	 * We then queue into the relevant netisr so it can be dispatched
549 	 * to the correct CPU.
550 	 *
551 	 * Note - this may return 1, which means the flowid in the mbuf
552 	 * is correct for the configured RSS hash types and can be used.
553 	 */
554 	if (rss_mbuf_software_hash_v4(m, 0, &rss_hash, &rss_type) == 0) {
555 		m->m_pkthdr.flowid = rss_hash;
556 		M_HASHTYPE_SET(m, rss_type);
557 	}
558 
559 	/*
560 	 * Queue/dispatch for reprocessing.
561 	 *
562 	 * Note: this is much slower than just handling the frame in the
563 	 * current receive context.  It's likely worth investigating
564 	 * why this is.
565 	 */
566 	netisr_dispatch(NETISR_IP_DIRECT, m);
567 	return (NULL);
568 #endif
569 
570 	/* Handle in-line */
571 	return (m);
572 
573 dropfrag:
574 	IPSTAT_INC(ips_fragdropped);
575 	if (fp != NULL) {
576 		fp->ipq_nfrags--;
577 		atomic_subtract_int(&nfrags, 1);
578 	}
579 	m_freem(m);
580 done:
581 	IPQ_UNLOCK(hash);
582 	return (NULL);
583 
584 #undef GETIP
585 }
586 
587 /*
588  * Timer expired on a bucket.
589  * There should be at least one ipq to be timed out.
590  */
591 static void
592 ipreass_callout(void *arg)
593 {
594 	struct ipqbucket *bucket = arg;
595 	struct ipq *fp;
596 
597 	IPQ_BUCKET_LOCK_ASSERT(bucket);
598 	MPASS(atomic_load_int(&nfrags) > 0);
599 
600 	CURVNET_SET(bucket->vnet);
601 	fp = TAILQ_LAST(&bucket->head, ipqhead);
602 	KASSERT(fp != NULL && fp->ipq_expire >= time_uptime,
603 	    ("%s: stray callout on bucket %p", __func__, bucket));
604 
605 	while (fp != NULL && fp->ipq_expire >= time_uptime) {
606 		ipq_timeout(bucket, fp);
607 		fp = TAILQ_LAST(&bucket->head, ipqhead);
608 	}
609 	ipreass_reschedule(bucket);
610 	CURVNET_RESTORE();
611 }
612 
613 static void
614 ipreass_reschedule(struct ipqbucket *bucket)
615 {
616 	struct ipq *fp;
617 
618 	IPQ_BUCKET_LOCK_ASSERT(bucket);
619 
620 	if ((fp = TAILQ_LAST(&bucket->head, ipqhead)) != NULL) {
621 		time_t t;
622 
623 		/* Protect against time_uptime tick. */
624 		t = fp->ipq_expire - time_uptime;
625 		t = (t > 0) ? t : 1;
626 		callout_reset_sbt(&bucket->timer, SBT_1S * t, SBT_1S,
627 		    ipreass_callout, bucket, 0);
628 	} else
629 		callout_stop(&bucket->timer);
630 }
631 
632 static void
633 ipreass_drain_vnet(void)
634 {
635 
636 	for (int i = 0; i < V_ipq_hashsize; i++) {
637 		IPQ_LOCK(i);
638 		while(!TAILQ_EMPTY(&V_ipq[i].head))
639 			ipq_drop(&V_ipq[i], TAILQ_FIRST(&V_ipq[i].head));
640 		KASSERT(V_ipq[i].count == 0,
641 		    ("%s: V_ipq[%d] count %d (V_ipq=%p)", __func__, i,
642 		    V_ipq[i].count, V_ipq));
643 		IPQ_UNLOCK(i);
644 	}
645 }
646 
647 /*
648  * Drain off all datagram fragments.
649  */
650 static void
651 ipreass_drain(void)
652 {
653 	VNET_ITERATOR_DECL(vnet_iter);
654 
655 	VNET_FOREACH(vnet_iter) {
656 		CURVNET_SET(vnet_iter);
657 		ipreass_drain_vnet();
658 		CURVNET_RESTORE();
659 	}
660 }
661 
662 
663 /*
664  * Initialize IP reassembly structures.
665  */
666 MALLOC_DEFINE(M_IPREASS_HASH, "IP reass", "IP packet reassembly hash headers");
667 void
668 ipreass_vnet_init(void)
669 {
670 	int max;
671 
672 	V_ipq_hashsize = IPREASS_NHASH;
673 	TUNABLE_INT_FETCH("net.inet.ip.reass_hashsize", &V_ipq_hashsize);
674 	V_ipq = malloc(sizeof(struct ipqbucket) * V_ipq_hashsize,
675 	    M_IPREASS_HASH, M_WAITOK);
676 
677 	for (int i = 0; i < V_ipq_hashsize; i++) {
678 		TAILQ_INIT(&V_ipq[i].head);
679 		mtx_init(&V_ipq[i].lock, "IP reassembly", NULL,
680 		    MTX_DEF | MTX_DUPOK | MTX_NEW);
681 		callout_init_mtx(&V_ipq[i].timer, &V_ipq[i].lock, 0);
682 		V_ipq[i].count = 0;
683 #ifdef VIMAGE
684 		V_ipq[i].vnet = curvnet;
685 #endif
686 	}
687 	V_ipq_hashseed = arc4random();
688 	V_maxfragsperpacket = 16;
689 	V_ipq_zone = uma_zcreate("ipq", sizeof(struct ipq), NULL, NULL, NULL,
690 	    NULL, UMA_ALIGN_PTR, 0);
691 	max = IP_MAXFRAGPACKETS;
692 	max = uma_zone_set_max(V_ipq_zone, max);
693 	V_ipreass_maxbucketsize = imax(max / (V_ipq_hashsize / 2), 1);
694 }
695 
696 void
697 ipreass_init(void)
698 {
699 
700 	maxfrags = IP_MAXFRAGS;
701 	EVENTHANDLER_REGISTER(nmbclusters_change, ipreass_zone_change,
702 	    NULL, EVENTHANDLER_PRI_ANY);
703 	EVENTHANDLER_REGISTER(vm_lowmem, ipreass_drain, NULL,
704 	    LOWMEM_PRI_DEFAULT);
705 	EVENTHANDLER_REGISTER(mbuf_lowmem, ipreass_drain, NULL,
706 		LOWMEM_PRI_DEFAULT);
707 }
708 
709 /*
710  * Drain off all datagram fragments belonging to
711  * the given network interface.
712  */
713 static void
714 ipreass_cleanup(void *arg __unused, struct ifnet *ifp)
715 {
716 	struct ipq *fp, *temp;
717 	struct mbuf *m;
718 	int i;
719 
720 	KASSERT(ifp != NULL, ("%s: ifp is NULL", __func__));
721 
722 	CURVNET_SET_QUIET(ifp->if_vnet);
723 
724 	/*
725 	 * Skip processing if IPv4 reassembly is not initialised or
726 	 * torn down by ipreass_destroy().
727 	 */
728 	if (V_ipq_zone == NULL) {
729 		CURVNET_RESTORE();
730 		return;
731 	}
732 
733 	for (i = 0; i < V_ipq_hashsize; i++) {
734 		IPQ_LOCK(i);
735 		/* Scan fragment list. */
736 		TAILQ_FOREACH_SAFE(fp, &V_ipq[i].head, ipq_list, temp) {
737 			for (m = fp->ipq_frags; m != NULL; m = m->m_nextpkt) {
738 				/* clear no longer valid rcvif pointer */
739 				if (m->m_pkthdr.rcvif == ifp)
740 					m->m_pkthdr.rcvif = NULL;
741 			}
742 		}
743 		IPQ_UNLOCK(i);
744 	}
745 	CURVNET_RESTORE();
746 }
747 EVENTHANDLER_DEFINE(ifnet_departure_event, ipreass_cleanup, NULL, 0);
748 
749 #ifdef VIMAGE
750 /*
751  * Destroy IP reassembly structures.
752  */
753 void
754 ipreass_destroy(void)
755 {
756 
757 	ipreass_drain_vnet();
758 	uma_zdestroy(V_ipq_zone);
759 	V_ipq_zone = NULL;
760 	for (int i = 0; i < V_ipq_hashsize; i++)
761 		mtx_destroy(&V_ipq[i].lock);
762 	free(V_ipq, M_IPREASS_HASH);
763 }
764 #endif
765 
766 /*
767  * After maxnipq has been updated, propagate the change to UMA.  The UMA zone
768  * max has slightly different semantics than the sysctl, for historical
769  * reasons.
770  */
771 static void
772 ipreass_drain_tomax(void)
773 {
774 	struct ipq *fp;
775 	int target;
776 
777 	/*
778 	 * Make sure each bucket is under the new limit. If
779 	 * necessary, drop enough of the oldest elements from
780 	 * each bucket to get under the new limit.
781 	 */
782 	for (int i = 0; i < V_ipq_hashsize; i++) {
783 		IPQ_LOCK(i);
784 		while (V_ipq[i].count > V_ipreass_maxbucketsize &&
785 		    (fp = TAILQ_LAST(&V_ipq[i].head, ipqhead)) != NULL)
786 			ipq_timeout(&V_ipq[i], fp);
787 		ipreass_reschedule(&V_ipq[i]);
788 		IPQ_UNLOCK(i);
789 	}
790 
791 	/*
792 	 * If we are over the maximum number of fragments,
793 	 * drain off enough to get down to the new limit,
794 	 * stripping off last elements on queues.  Every
795 	 * run we strip the oldest element from each bucket.
796 	 */
797 	target = uma_zone_get_max(V_ipq_zone);
798 	while (uma_zone_get_cur(V_ipq_zone) > target) {
799 		for (int i = 0; i < V_ipq_hashsize; i++) {
800 			IPQ_LOCK(i);
801 			fp = TAILQ_LAST(&V_ipq[i].head, ipqhead);
802 			if (fp != NULL) {
803 				ipq_timeout(&V_ipq[i], fp);
804 				ipreass_reschedule(&V_ipq[i]);
805 			}
806 			IPQ_UNLOCK(i);
807 		}
808 	}
809 }
810 
811 static void
812 ipreass_zone_change(void *tag)
813 {
814 	VNET_ITERATOR_DECL(vnet_iter);
815 	int max;
816 
817 	maxfrags = IP_MAXFRAGS;
818 	max = IP_MAXFRAGPACKETS;
819 	VNET_LIST_RLOCK_NOSLEEP();
820 	VNET_FOREACH(vnet_iter) {
821 		CURVNET_SET(vnet_iter);
822 		max = uma_zone_set_max(V_ipq_zone, max);
823 		V_ipreass_maxbucketsize = imax(max / (V_ipq_hashsize / 2), 1);
824 		ipreass_drain_tomax();
825 		CURVNET_RESTORE();
826 	}
827 	VNET_LIST_RUNLOCK_NOSLEEP();
828 }
829 
830 /*
831  * Change the limit on the UMA zone, or disable the fragment allocation
832  * at all.  Since 0 and -1 is a special values here, we need our own handler,
833  * instead of sysctl_handle_uma_zone_max().
834  */
835 static int
836 sysctl_maxfragpackets(SYSCTL_HANDLER_ARGS)
837 {
838 	int error, max;
839 
840 	if (V_noreass == 0) {
841 		max = uma_zone_get_max(V_ipq_zone);
842 		if (max == 0)
843 			max = -1;
844 	} else
845 		max = 0;
846 	error = sysctl_handle_int(oidp, &max, 0, req);
847 	if (error || !req->newptr)
848 		return (error);
849 	if (max > 0) {
850 		/*
851 		 * XXXRW: Might be a good idea to sanity check the argument
852 		 * and place an extreme upper bound.
853 		 */
854 		max = uma_zone_set_max(V_ipq_zone, max);
855 		V_ipreass_maxbucketsize = imax(max / (V_ipq_hashsize / 2), 1);
856 		ipreass_drain_tomax();
857 		V_noreass = 0;
858 	} else if (max == 0) {
859 		V_noreass = 1;
860 		ipreass_drain();
861 	} else if (max == -1) {
862 		V_noreass = 0;
863 		uma_zone_set_max(V_ipq_zone, 0);
864 		V_ipreass_maxbucketsize = INT_MAX;
865 	} else
866 		return (EINVAL);
867 	return (0);
868 }
869 
870 /*
871  * Seek for old fragment queue header that can be reused.  Try to
872  * reuse a header from currently locked hash bucket.
873  */
874 static struct ipq *
875 ipq_reuse(int start)
876 {
877 	struct ipq *fp;
878 	int bucket, i;
879 
880 	IPQ_LOCK_ASSERT(start);
881 
882 	for (i = 0; i < V_ipq_hashsize; i++) {
883 		bucket = (start + i) % V_ipq_hashsize;
884 		if (bucket != start && IPQ_TRYLOCK(bucket) == 0)
885 			continue;
886 		fp = TAILQ_LAST(&V_ipq[bucket].head, ipqhead);
887 		if (fp) {
888 			struct mbuf *m;
889 
890 			IPSTAT_ADD(ips_fragtimeout, fp->ipq_nfrags);
891 			atomic_subtract_int(&nfrags, fp->ipq_nfrags);
892 			while (fp->ipq_frags) {
893 				m = fp->ipq_frags;
894 				fp->ipq_frags = m->m_nextpkt;
895 				m_freem(m);
896 			}
897 			TAILQ_REMOVE(&V_ipq[bucket].head, fp, ipq_list);
898 			V_ipq[bucket].count--;
899 			ipreass_reschedule(&V_ipq[bucket]);
900 			if (bucket != start)
901 				IPQ_UNLOCK(bucket);
902 			break;
903 		}
904 		if (bucket != start)
905 			IPQ_UNLOCK(bucket);
906 	}
907 	IPQ_LOCK_ASSERT(start);
908 	return (fp);
909 }
910 
911 /*
912  * Free a fragment reassembly header and all associated datagrams.
913  */
914 static void
915 ipq_free(struct ipqbucket *bucket, struct ipq *fp)
916 {
917 	struct mbuf *q;
918 
919 	atomic_subtract_int(&nfrags, fp->ipq_nfrags);
920 	while (fp->ipq_frags) {
921 		q = fp->ipq_frags;
922 		fp->ipq_frags = q->m_nextpkt;
923 		m_freem(q);
924 	}
925 	TAILQ_REMOVE(&bucket->head, fp, ipq_list);
926 	bucket->count--;
927 	uma_zfree(V_ipq_zone, fp);
928 }
929 
930 /*
931  * Get or set the maximum number of reassembly queues per bucket.
932  */
933 static int
934 sysctl_maxfragbucketsize(SYSCTL_HANDLER_ARGS)
935 {
936 	int error, max;
937 
938 	max = V_ipreass_maxbucketsize;
939 	error = sysctl_handle_int(oidp, &max, 0, req);
940 	if (error || !req->newptr)
941 		return (error);
942 	if (max <= 0)
943 		return (EINVAL);
944 	V_ipreass_maxbucketsize = max;
945 	ipreass_drain_tomax();
946 	return (0);
947 }
948 
949 /*
950  * Get or set the IP fragment time to live.
951  */
952 static int
953 sysctl_fragttl(SYSCTL_HANDLER_ARGS)
954 {
955 	u_int ttl;
956 	int error;
957 
958 	ttl = V_ipfragttl;
959 	error = sysctl_handle_int(oidp, &ttl, 0, req);
960 	if (error || !req->newptr)
961 		return (error);
962 
963 	if (ttl < 1 || ttl > MAXTTL)
964 		return (EINVAL);
965 
966 	atomic_store_int(&V_ipfragttl, ttl);
967 	return (0);
968 }
969