xref: /freebsd/sys/netinet/tcp_reass.c (revision 62cfcf62f627e5093fb37026a6d8c98e4d2ef04c)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
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  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_tcpdebug.h"
40 
41 /* For debugging we want counters and BB logging */
42 /* #define TCP_REASS_COUNTERS 1 */
43 /* #define TCP_REASS_LOGGING 1 */
44 
45 #include <sys/param.h>
46 #include <sys/kernel.h>
47 #include <sys/eventhandler.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/syslog.h>
54 #include <sys/systm.h>
55 
56 #include <vm/uma.h>
57 
58 #include <net/if.h>
59 #include <net/if_var.h>
60 #include <net/route.h>
61 #include <net/vnet.h>
62 
63 #include <netinet/in.h>
64 #include <netinet/in_pcb.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/in_var.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_var.h>
69 #include <netinet/ip_options.h>
70 #include <netinet/ip6.h>
71 #include <netinet6/in6_pcb.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/nd6.h>
74 #include <netinet/tcp.h>
75 #include <netinet/tcp_fsm.h>
76 #include <netinet/tcp_seq.h>
77 #include <netinet/tcp_timer.h>
78 #include <netinet/tcp_var.h>
79 #ifdef TCP_REASS_LOGGING
80 #include <netinet/tcp_log_buf.h>
81 #include <netinet/tcp_hpts.h>
82 #endif
83 #include <netinet6/tcp6_var.h>
84 #include <netinet/tcpip.h>
85 #ifdef TCPDEBUG
86 #include <netinet/tcp_debug.h>
87 #endif /* TCPDEBUG */
88 
89 #define TCP_R_LOG_ADD		1
90 #define TCP_R_LOG_LIMIT_REACHED 2
91 #define TCP_R_LOG_APPEND	3
92 #define TCP_R_LOG_PREPEND	4
93 #define TCP_R_LOG_REPLACE	5
94 #define TCP_R_LOG_MERGE_INTO	6
95 #define TCP_R_LOG_NEW_ENTRY	7
96 #define TCP_R_LOG_READ		8
97 #define TCP_R_LOG_ZERO		9
98 #define TCP_R_LOG_DUMP		10
99 #define TCP_R_LOG_TRIM		11
100 
101 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass,
102     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
103     "TCP Segment Reassembly Queue");
104 
105 static SYSCTL_NODE(_net_inet_tcp_reass, OID_AUTO, stats,
106     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
107     "TCP Segment Reassembly stats");
108 
109 
110 static int tcp_reass_maxseg = 0;
111 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
112     &tcp_reass_maxseg, 0,
113     "Global maximum number of TCP Segments in Reassembly Queue");
114 
115 static uma_zone_t tcp_reass_zone;
116 SYSCTL_UMA_CUR(_net_inet_tcp_reass, OID_AUTO, cursegments, 0,
117     &tcp_reass_zone,
118     "Global number of TCP Segments currently in Reassembly Queue");
119 
120 static u_int tcp_reass_maxqueuelen = 100;
121 SYSCTL_UINT(_net_inet_tcp_reass, OID_AUTO, maxqueuelen, CTLFLAG_RWTUN,
122     &tcp_reass_maxqueuelen, 0,
123     "Maximum number of TCP Segments per Reassembly Queue");
124 
125 static int tcp_new_limits = 0;
126 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, new_limit, CTLFLAG_RWTUN,
127     &tcp_new_limits, 0,
128     "Do we use the new limit method we are discussing?");
129 
130 static u_int tcp_reass_queue_guard = 16;
131 SYSCTL_UINT(_net_inet_tcp_reass, OID_AUTO, queueguard, CTLFLAG_RWTUN,
132     &tcp_reass_queue_guard, 16,
133     "Number of TCP Segments in Reassembly Queue where we flip over to guard mode");
134 
135 #ifdef TCP_REASS_COUNTERS
136 
137 counter_u64_t reass_entry;
138 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, entry, CTLFLAG_RD,
139     &reass_entry, "A segment entered reassembly ");
140 
141 counter_u64_t reass_path1;
142 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, path1, CTLFLAG_RD,
143     &reass_path1, "Took path 1");
144 
145 counter_u64_t reass_path2;
146 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, path2, CTLFLAG_RD,
147     &reass_path2, "Took path 2");
148 
149 counter_u64_t reass_path3;
150 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, path3, CTLFLAG_RD,
151     &reass_path3, "Took path 3");
152 
153 counter_u64_t reass_path4;
154 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, path4, CTLFLAG_RD,
155     &reass_path4, "Took path 4");
156 
157 counter_u64_t reass_path5;
158 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, path5, CTLFLAG_RD,
159     &reass_path5, "Took path 5");
160 
161 counter_u64_t reass_path6;
162 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, path6, CTLFLAG_RD,
163     &reass_path6, "Took path 6");
164 
165 counter_u64_t reass_path7;
166 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, path7, CTLFLAG_RD,
167     &reass_path7, "Took path 7");
168 
169 counter_u64_t reass_fullwalk;
170 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, fullwalk, CTLFLAG_RD,
171     &reass_fullwalk, "Took a full walk ");
172 
173 counter_u64_t reass_nospace;
174 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, nospace, CTLFLAG_RD,
175     &reass_nospace, "Had no mbuf capacity ");
176 
177 counter_u64_t merge_fwd;
178 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, merge_fwd, CTLFLAG_RD,
179     &merge_fwd, "Ran merge fwd");
180 
181 counter_u64_t merge_into;
182 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, merge_into, CTLFLAG_RD,
183     &merge_into, "Ran merge into");
184 
185 counter_u64_t tcp_zero_input;
186 SYSCTL_COUNTER_U64(_net_inet_tcp_reass_stats, OID_AUTO, zero_input, CTLFLAG_RD,
187     &tcp_zero_input, "The reassembly buffer saw a zero len segment etc");
188 
189 #endif
190 
191 /* Initialize TCP reassembly queue */
192 static void
193 tcp_reass_zone_change(void *tag)
194 {
195 
196 	/* Set the zone limit and read back the effective value. */
197 	tcp_reass_maxseg = nmbclusters / 16;
198 	tcp_reass_maxseg = uma_zone_set_max(tcp_reass_zone,
199 	    tcp_reass_maxseg);
200 }
201 
202 #ifdef TCP_REASS_LOGGING
203 
204 static void
205 tcp_log_reassm(struct tcpcb *tp, struct tseg_qent *q, struct tseg_qent *p,
206     tcp_seq seq, int len, uint8_t action, int instance)
207 {
208 	uint32_t cts;
209 	struct timeval tv;
210 
211 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
212 		union tcp_log_stackspecific log;
213 
214 		memset(&log, 0, sizeof(log));
215 		cts = tcp_get_usecs(&tv);
216 		log.u_bbr.flex1 = seq;
217 		log.u_bbr.cur_del_rate = (uint64_t)q;
218 		log.u_bbr.delRate = (uint64_t)p;
219 		if (q != NULL) {
220 			log.u_bbr.flex2 = q->tqe_start;
221 			log.u_bbr.flex3 = q->tqe_len;
222 			log.u_bbr.flex4 = q->tqe_mbuf_cnt;
223 			log.u_bbr.hptsi_gain = q->tqe_flags;
224 		}
225 		if (p != NULL)  {
226 			log.u_bbr.flex5 = p->tqe_start;
227 			log.u_bbr.pkts_out = p->tqe_len;
228 			log.u_bbr.epoch = p->tqe_mbuf_cnt;
229 			log.u_bbr.cwnd_gain = p->tqe_flags;
230 		}
231 		log.u_bbr.flex6 = tp->t_segqmbuflen;
232 		log.u_bbr.flex7 = instance;
233 		log.u_bbr.flex8 = action;
234 		log.u_bbr.timeStamp = cts;
235 		TCP_LOG_EVENTP(tp, NULL,
236 		    &tp->t_inpcb->inp_socket->so_rcv,
237 		    &tp->t_inpcb->inp_socket->so_snd,
238 		    TCP_LOG_REASS, 0,
239 		    len, &log, false, &tv);
240 	}
241 }
242 
243 static void
244 tcp_reass_log_dump(struct tcpcb *tp)
245 {
246 	struct tseg_qent *q;
247 
248 	if (tp->t_logstate != TCP_LOG_STATE_OFF) {
249 		TAILQ_FOREACH(q, &tp->t_segq, tqe_q) {
250 			tcp_log_reassm(tp, q, NULL, q->tqe_start, q->tqe_len, TCP_R_LOG_DUMP, 0);
251 		}
252 	};
253 }
254 
255 static void
256 tcp_reass_log_new_in(struct tcpcb *tp, tcp_seq seq, int len, struct mbuf *m,
257     int logval, struct tseg_qent *q)
258 {
259 	int cnt;
260 	struct mbuf *t;
261 
262 	cnt = 0;
263 	t = m;
264 	while (t) {
265 		cnt += t->m_len;
266 		t = t->m_next;
267 	}
268 	tcp_log_reassm(tp, q, NULL, seq, len, logval, cnt);
269 }
270 
271 #endif
272 
273 void
274 tcp_reass_global_init(void)
275 {
276 
277 	tcp_reass_maxseg = nmbclusters / 16;
278 	TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
279 	    &tcp_reass_maxseg);
280 	tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
281 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
282 	/* Set the zone limit and read back the effective value. */
283 	tcp_reass_maxseg = uma_zone_set_max(tcp_reass_zone,
284 	    tcp_reass_maxseg);
285 #ifdef TCP_REASS_COUNTERS
286 	reass_path1 = counter_u64_alloc(M_WAITOK);
287 	reass_path2 = counter_u64_alloc(M_WAITOK);
288 	reass_path3 = counter_u64_alloc(M_WAITOK);
289 	reass_path4 = counter_u64_alloc(M_WAITOK);
290 	reass_path5 = counter_u64_alloc(M_WAITOK);
291 	reass_path6 = counter_u64_alloc(M_WAITOK);
292 	reass_path7 = counter_u64_alloc(M_WAITOK);
293 	reass_fullwalk = counter_u64_alloc(M_WAITOK);
294 	reass_nospace = counter_u64_alloc(M_WAITOK);
295 	reass_entry = counter_u64_alloc(M_WAITOK);
296 	merge_fwd = counter_u64_alloc(M_WAITOK);
297 	merge_into = counter_u64_alloc(M_WAITOK);
298 	tcp_zero_input = counter_u64_alloc(M_WAITOK);
299 #endif
300 	EVENTHANDLER_REGISTER(nmbclusters_change,
301 	    tcp_reass_zone_change, NULL, EVENTHANDLER_PRI_ANY);
302 
303 }
304 
305 void
306 tcp_reass_flush(struct tcpcb *tp)
307 {
308 	struct tseg_qent *qe;
309 
310 	INP_WLOCK_ASSERT(tp->t_inpcb);
311 
312 	while ((qe = TAILQ_FIRST(&tp->t_segq)) != NULL) {
313 		TAILQ_REMOVE(&tp->t_segq, qe, tqe_q);
314 		m_freem(qe->tqe_m);
315 		uma_zfree(tcp_reass_zone, qe);
316 		tp->t_segqlen--;
317 	}
318 	tp->t_segqmbuflen = 0;
319 	KASSERT((tp->t_segqlen == 0),
320 	    ("TCP reass queue %p segment count is %d instead of 0 after flush.",
321 	    tp, tp->t_segqlen));
322 }
323 
324 static void
325 tcp_reass_append(struct tcpcb *tp, struct tseg_qent *last,
326     struct mbuf *m, struct tcphdr *th, int tlen,
327     struct mbuf *mlast, int lenofoh)
328 {
329 
330 #ifdef TCP_REASS_LOGGING
331 	tcp_log_reassm(tp, last, NULL, th->th_seq, tlen, TCP_R_LOG_APPEND, 0);
332 #endif
333 	last->tqe_len += tlen;
334 	last->tqe_m->m_pkthdr.len += tlen;
335 	/* Preserve the FIN bit if its there */
336 	last->tqe_flags |= (th->th_flags & TH_FIN);
337 	last->tqe_last->m_next = m;
338 	last->tqe_last = mlast;
339 	last->tqe_mbuf_cnt += lenofoh;
340 	tp->t_rcvoopack++;
341 	TCPSTAT_INC(tcps_rcvoopack);
342 	TCPSTAT_ADD(tcps_rcvoobyte, tlen);
343 #ifdef TCP_REASS_LOGGING
344 	tcp_reass_log_new_in(tp, last->tqe_start, lenofoh, last->tqe_m,
345 			     TCP_R_LOG_APPEND,
346 			     last);
347 #endif
348 }
349 
350 static void
351 tcp_reass_prepend(struct tcpcb *tp, struct tseg_qent *first, struct mbuf *m, struct tcphdr *th,
352 		  int tlen, struct mbuf *mlast, int lenofoh)
353 {
354 	int i;
355 
356 #ifdef TCP_REASS_LOGGING
357 	tcp_log_reassm(tp, first, NULL, th->th_seq, tlen, TCP_R_LOG_PREPEND, 0);
358 #endif
359 	if (SEQ_GT((th->th_seq + tlen), first->tqe_start)) {
360 		/* The new data overlaps into the old */
361 		i = (th->th_seq + tlen) - first->tqe_start;
362 #ifdef TCP_REASS_LOGGING
363 		tcp_log_reassm(tp, first, NULL, 0, i, TCP_R_LOG_TRIM, 1);
364 #endif
365 		m_adj(first->tqe_m, i);
366 		first->tqe_len -= i;
367 		first->tqe_start += i;
368 	}
369 	/* Ok now setup our chain to point to the old first */
370 	mlast->m_next = first->tqe_m;
371 	first->tqe_m = m;
372 	first->tqe_len += tlen;
373 	first->tqe_start = th->th_seq;
374 	first->tqe_m->m_pkthdr.len = first->tqe_len;
375 	first->tqe_mbuf_cnt += lenofoh;
376 	tp->t_rcvoopack++;
377 	TCPSTAT_INC(tcps_rcvoopack);
378 	TCPSTAT_ADD(tcps_rcvoobyte, tlen);
379 #ifdef TCP_REASS_LOGGING
380 	tcp_reass_log_new_in(tp, first->tqe_start, lenofoh, first->tqe_m,
381 			     TCP_R_LOG_PREPEND,
382 			     first);
383 #endif
384 }
385 
386 static void
387 tcp_reass_replace(struct tcpcb *tp, struct tseg_qent *q, struct mbuf *m,
388     tcp_seq seq, int len, struct mbuf *mlast, int mbufoh, uint8_t flags)
389 {
390 	/*
391 	 * Free the data in q, and replace
392 	 * it with the new segment.
393 	 */
394 	int len_dif;
395 
396 #ifdef TCP_REASS_LOGGING
397 	tcp_log_reassm(tp, q, NULL, seq, len, TCP_R_LOG_REPLACE, 0);
398 #endif
399 	m_freem(q->tqe_m);
400 	KASSERT(tp->t_segqmbuflen >= q->tqe_mbuf_cnt,
401 		("Tp:%p seg queue goes negative", tp));
402 	tp->t_segqmbuflen -= q->tqe_mbuf_cnt;
403 	q->tqe_mbuf_cnt = mbufoh;
404 	q->tqe_m = m;
405 	q->tqe_last = mlast;
406 	q->tqe_start = seq;
407 	if (len > q->tqe_len)
408 		len_dif = len - q->tqe_len;
409 	else
410 		len_dif = 0;
411 	tp->t_rcvoopack++;
412 	TCPSTAT_INC(tcps_rcvoopack);
413 	TCPSTAT_ADD(tcps_rcvoobyte, len_dif);
414 	q->tqe_len = len;
415 	q->tqe_flags = (flags & TH_FIN);
416 	q->tqe_m->m_pkthdr.len = q->tqe_len;
417 	tp->t_segqmbuflen += mbufoh;
418 
419 }
420 
421 static void
422 tcp_reass_merge_into(struct tcpcb *tp, struct tseg_qent *ent,
423     struct tseg_qent *q)
424 {
425 	/*
426 	 * Merge q into ent and free q from the list.
427 	 */
428 #ifdef TCP_REASS_LOGGING
429 	tcp_log_reassm(tp, q, ent, 0, 0, TCP_R_LOG_MERGE_INTO, 0);
430 #endif
431 #ifdef TCP_REASS_COUNTERS
432 	counter_u64_add(merge_into, 1);
433 #endif
434 	ent->tqe_last->m_next = q->tqe_m;
435 	ent->tqe_last = q->tqe_last;
436 	ent->tqe_len += q->tqe_len;
437 	ent->tqe_mbuf_cnt += q->tqe_mbuf_cnt;
438 	ent->tqe_m->m_pkthdr.len += q->tqe_len;
439 	ent->tqe_flags |= (q->tqe_flags & TH_FIN);
440 	TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
441 	uma_zfree(tcp_reass_zone, q);
442 	tp->t_segqlen--;
443 
444 }
445 
446 static void
447 tcp_reass_merge_forward(struct tcpcb *tp, struct tseg_qent *ent)
448 {
449 	struct tseg_qent *q, *qtmp;
450 	int i;
451 	tcp_seq max;
452 	/*
453 	 * Given an entry merge forward anyplace
454 	 * that ent overlaps forward.
455 	 */
456 
457 	max = ent->tqe_start + ent->tqe_len;
458 	q = TAILQ_NEXT(ent, tqe_q);
459 	if (q == NULL) {
460 		/* Nothing left */
461 		return;
462 	}
463 	TAILQ_FOREACH_FROM_SAFE(q, &tp->t_segq, tqe_q, qtmp) {
464 		if (SEQ_GT(q->tqe_start, max)) {
465 			/* Beyond q */
466 			break;
467 		}
468 		/* We have some or all that are overlapping */
469 		if (SEQ_GEQ(max, (q->tqe_start + q->tqe_len))) {
470 			/* It consumes it all */
471 			tp->t_segqmbuflen -= q->tqe_mbuf_cnt;
472 			m_freem(q->tqe_m);
473 			TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
474 			uma_zfree(tcp_reass_zone, q);
475 			tp->t_segqlen--;
476 			continue;
477 		}
478 		/*
479 		 * Trim the q entry to dovetail to this one
480 		 * and then merge q into ent updating max
481 		 * in the process.
482 		 */
483 		i = max - q->tqe_start;
484 #ifdef TCP_REASS_LOGGING
485 		tcp_log_reassm(tp, q, NULL, 0, i, TCP_R_LOG_TRIM, 2);
486 #endif
487 		m_adj(q->tqe_m, i);
488 		q->tqe_len -= i;
489 		q->tqe_start += i;
490 		tcp_reass_merge_into(tp, ent, q);
491 		max = ent->tqe_start + ent->tqe_len;
492 	}
493 #ifdef TCP_REASS_COUNTERS
494 	counter_u64_add(merge_fwd, 1);
495 #endif
496 }
497 
498 static int
499 tcp_reass_overhead_of_chain(struct mbuf *m, struct mbuf **mlast)
500 {
501 	int len = MSIZE;
502 
503 	if (m->m_flags & M_EXT)
504 		len += m->m_ext.ext_size;
505 	while (m->m_next != NULL) {
506 		m = m->m_next;
507 		len += MSIZE;
508 		if (m->m_flags & M_EXT)
509 			len += m->m_ext.ext_size;
510 	}
511 	*mlast = m;
512 	return (len);
513 }
514 
515 
516 /*
517  * NOTE!!! the new tcp-reassembly code *must not* use
518  * m_adj() with a negative index. That alters the chain
519  * of mbufs (by possibly chopping trailing mbufs). At
520  * the front of tcp_reass we count the mbuf overhead
521  * and setup the tail pointer. If we use m_adj(m, -5)
522  * we could corrupt the tail pointer. Currently the
523  * code only uses m_adj(m, postive-num). If this
524  * changes appropriate changes to update mlast would
525  * be needed.
526  */
527 int
528 tcp_reass(struct tcpcb *tp, struct tcphdr *th, tcp_seq *seq_start,
529 	  int *tlenp, struct mbuf *m)
530 {
531 	struct tseg_qent *q, *last, *first;
532 	struct tseg_qent *p = NULL;
533 	struct tseg_qent *nq = NULL;
534 	struct tseg_qent *te = NULL;
535 	struct mbuf *mlast = NULL;
536 	struct sockbuf *sb;
537 	struct socket *so = tp->t_inpcb->inp_socket;
538 	char *s = NULL;
539 	int flags, i, lenofoh;
540 
541 	INP_WLOCK_ASSERT(tp->t_inpcb);
542 	/*
543 	 * XXX: tcp_reass() is rather inefficient with its data structures
544 	 * and should be rewritten (see NetBSD for optimizations).
545 	 */
546 
547 	KASSERT(th == NULL || (seq_start != NULL && tlenp != NULL),
548 	        ("tcp_reass called with illegal parameter combination "
549 	         "(tp=%p, th=%p, seq_start=%p, tlenp=%p, m=%p)",
550 	         tp, th, seq_start, tlenp, m));
551 	/*
552 	 * Call with th==NULL after become established to
553 	 * force pre-ESTABLISHED data up to user socket.
554 	 */
555 	if (th == NULL)
556 		goto present;
557 	KASSERT(SEQ_GEQ(th->th_seq, tp->rcv_nxt),
558 		("Attempt to add old entry to reassembly queue (th=%p, tp=%p)",
559 		 th, tp));
560 #ifdef TCP_REASS_LOGGING
561 	tcp_reass_log_new_in(tp, th->th_seq, *tlenp, m, TCP_R_LOG_ADD, NULL);
562 #endif
563 #ifdef TCP_REASS_COUNTERS
564 	counter_u64_add(reass_entry, 1);
565 #endif
566 	/*
567 	 * Check for zero length data.
568 	 */
569 	if ((*tlenp == 0) && ((th->th_flags & TH_FIN) == 0)) {
570 		/*
571 		 * A zero length segment does no
572 		 * one any good. We could check
573 		 * the rcv_nxt <-> rcv_wnd but thats
574 		 * already done for us by the caller.
575 		 */
576 #ifdef TCP_REASS_COUNTERS
577 		counter_u64_add(tcp_zero_input, 1);
578 #endif
579 		m_freem(m);
580 #ifdef TCP_REASS_LOGGING
581 		tcp_reass_log_dump(tp);
582 #endif
583 		return (0);
584 	}
585 	/*
586 	 * Will it fit?
587 	 */
588 	lenofoh = tcp_reass_overhead_of_chain(m, &mlast);
589 	sb = &tp->t_inpcb->inp_socket->so_rcv;
590 	if ((th->th_seq != tp->rcv_nxt || !TCPS_HAVEESTABLISHED(tp->t_state)) &&
591 	    (sb->sb_mbcnt + tp->t_segqmbuflen + lenofoh) > sb->sb_mbmax) {
592 		/* No room */
593 		TCPSTAT_INC(tcps_rcvreassfull);
594 #ifdef TCP_REASS_COUNTERS
595 		counter_u64_add(reass_nospace, 1);
596 #endif
597 #ifdef TCP_REASS_LOGGING
598 		tcp_log_reassm(tp, NULL, NULL, th->th_seq, lenofoh, TCP_R_LOG_LIMIT_REACHED, 0);
599 #endif
600 		if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
601 			log(LOG_DEBUG, "%s; %s: mbuf count limit reached, "
602 			    "segment dropped\n", s, __func__);
603 			free(s, M_TCPLOG);
604 		}
605 		m_freem(m);
606 		*tlenp = 0;
607 #ifdef TCP_REASS_LOGGING
608 		tcp_reass_log_dump(tp);
609 #endif
610 		return (0);
611 	}
612 	/*
613 	 * First lets deal with two common cases, the
614 	 * segment appends to the back of our collected
615 	 * segments. Or the segment is the next in line.
616 	 */
617 	last = TAILQ_LAST_FAST(&tp->t_segq, tseg_qent, tqe_q);
618 	if (last != NULL) {
619 		if ((th->th_flags & TH_FIN) &&
620 		    SEQ_LT((th->th_seq + *tlenp), (last->tqe_start + last->tqe_len))) {
621 			/*
622 			 * Someone is trying to game us, dump
623 			 * the segment.
624 			 */
625 			*tlenp = 0;
626 			m_freem(m);
627 			return (0);
628 		}
629 		if ((SEQ_GEQ(th->th_seq, last->tqe_start)) &&
630 		    (SEQ_GEQ((last->tqe_start + last->tqe_len), th->th_seq))) {
631 			/* Common case, trailing segment is added */
632 			/**
633 			 *                                 +--last
634 			 *                                 v
635 			 *  reassembly buffer |---|  |---| |---|
636 			 *  new segment                       |---|
637 			 */
638 #ifdef TCP_REASS_COUNTERS
639 			counter_u64_add(reass_path1, 1);
640 #endif
641 			if (SEQ_GT((last->tqe_start + last->tqe_len), th->th_seq)) {
642 				i = (last->tqe_start + last->tqe_len) - th->th_seq;
643 				if (i < *tlenp) {
644 #ifdef TCP_REASS_LOGGING
645 					tcp_log_reassm(tp, last, NULL, 0, i, TCP_R_LOG_TRIM, 3);
646 					th->th_seq += i;
647 #endif
648 					m_adj(m, i);
649 					*tlenp -= i;
650 				} else {
651 					/* Complete overlap */
652 					TCPSTAT_INC(tcps_rcvduppack);
653 					TCPSTAT_ADD(tcps_rcvdupbyte, *tlenp);
654 					m_freem(m);
655 					*tlenp = last->tqe_len;
656 					*seq_start = last->tqe_start;
657 					return (0);
658 				}
659 			}
660 			if (last->tqe_flags & TH_FIN) {
661 				/*
662 				 * We have data after the FIN on the last?
663 				 */
664 				*tlenp = 0;
665 				m_freem(m);
666 				return(0);
667 			}
668 			tcp_reass_append(tp, last, m, th, *tlenp, mlast, lenofoh);
669 			tp->t_segqmbuflen += lenofoh;
670 			*seq_start = last->tqe_start;
671 			*tlenp = last->tqe_len;
672 			return (0);
673 		} else if (SEQ_GT(th->th_seq, (last->tqe_start + last->tqe_len))) {
674 			/*
675 			 * Second common case, we missed
676 			 * another one and have something more
677 			 * for the end.
678 			 */
679 			/**
680 			 *                                 +--last
681 			 *                                 v
682 			 *  reassembly buffer |---|  |---| |---|
683 			 *  new segment                           |---|
684 			 */
685 			if (last->tqe_flags & TH_FIN) {
686 				/*
687 				 * We have data after the FIN on the last?
688 				 */
689 				*tlenp = 0;
690 				m_freem(m);
691 				return(0);
692 			}
693 #ifdef TCP_REASS_COUNTERS
694 			counter_u64_add(reass_path2, 1);
695 #endif
696 			p = last;
697 			goto new_entry;
698 		}
699 	} else {
700 		/* First segment (it's NULL). */
701 		goto new_entry;
702 	}
703 	first = TAILQ_FIRST(&tp->t_segq);
704 	if (SEQ_LT(th->th_seq, first->tqe_start) &&
705 	    SEQ_GEQ((th->th_seq + *tlenp),first->tqe_start) &&
706 	    SEQ_LT((th->th_seq + *tlenp), (first->tqe_start + first->tqe_len))) {
707 		/*
708 		 * The head of the queue is prepended by this and
709 		 * it may be the one I want most.
710 		 */
711 		/**
712 		 *       first-------+
713 		 *                   v
714 		 *  rea:             |---|  |---| |---|
715 		 *  new:         |---|
716 		 * Note the case we do not deal with here is:
717 		 *   rea=     |---|   |---|   |---|
718 		 *   new=  |----|
719 		 * Due to the fact that it could be
720 		 *   new   |--------------------|
721 		 * And we might need to merge forward.
722 		 */
723 #ifdef INVARIANTS
724 		struct mbuf *firstmbuf;
725 #endif
726 
727 #ifdef TCP_REASS_COUNTERS
728 		counter_u64_add(reass_path3, 1);
729 #endif
730 		if (SEQ_LT(th->th_seq, tp->rcv_nxt)) {
731 			/*
732 			 * The resend was even before
733 			 * what we have. We need to trim it.
734 			 * Note TSNH (it should be trimmed
735 			 * before the call to tcp_reass()).
736 			 */
737 #ifdef INVARIANTS
738 			panic("th->th_seq:%u rcv_nxt:%u tp:%p not pre-trimmed",
739 			      th->th_seq, tp->rcv_nxt, tp);
740 #else
741 			i = tp->rcv_nxt - th->th_seq;
742 #ifdef TCP_REASS_LOGGING
743 			tcp_log_reassm(tp, first, NULL, 0, i, TCP_R_LOG_TRIM, 4);
744 #endif
745 			m_adj(m, i);
746 			th->th_seq += i;
747 			*tlenp -= i;
748 #endif
749 		}
750 #ifdef INVARIANTS
751 		firstmbuf = first->tqe_m;
752 #endif
753 		tcp_reass_prepend(tp, first, m, th, *tlenp, mlast, lenofoh);
754 #ifdef INVARIANTS
755 		if (firstmbuf == first->tqe_m) {
756 			panic("First stayed same m:%p foobar:%p first->tqe_m:%p tp:%p first:%p",
757 			      m, firstmbuf, first->tqe_m, tp, first);
758 		} else if (first->tqe_m != m) {
759 			panic("First did not change to m:%p foobar:%p first->tqe_m:%p tp:%p first:%p",
760 			      m, firstmbuf, first->tqe_m, tp, first);
761 		}
762 #endif
763 		tp->t_segqmbuflen += lenofoh;
764 		*seq_start = first->tqe_start;
765 		*tlenp = first->tqe_len;
766 		goto present;
767 	} else if (SEQ_LT((th->th_seq + *tlenp), first->tqe_start)) {
768 		/* New segment is before our earliest segment. */
769 		/**
770 		 *           first---->+
771 		 *                      v
772 		 *  rea=                |---| ....
773 		 *  new"         |---|
774 		 *
775 		 */
776 		goto new_entry;
777 	}
778 	/*
779 	 * Find a segment which begins after this one does.
780 	 */
781 #ifdef TCP_REASS_COUNTERS
782 	counter_u64_add(reass_fullwalk, 1);
783 #endif
784 	TAILQ_FOREACH(q, &tp->t_segq, tqe_q) {
785 		if (SEQ_GT(q->tqe_start, th->th_seq))
786 			break;
787 	}
788 	p = TAILQ_PREV(q, tsegqe_head, tqe_q);
789 	/**
790 	 * Now is this fit just in-between only?
791 	 * i.e.:
792 	 *      p---+        +----q
793 	 *          v        v
794 	 *     res= |--|     |--|    |--|
795 	 *     nee       |-|
796 	 */
797 	if (SEQ_LT((th->th_seq + *tlenp), q->tqe_start) &&
798 	    ((p == NULL) || (SEQ_GT(th->th_seq, (p->tqe_start + p->tqe_len))))) {
799 		/* Yep no overlap */
800 		goto new_entry;
801 	}
802 	/**
803 	 * If we reach here we have some (possibly all) overlap
804 	 * such as:
805 	 *     res=     |--|     |--|    |--|
806 	 *     new=  |----|
807 	 * or  new=  |-----------------|
808 	 * or  new=      |--------|
809 	 * or  new=            |---|
810 	 * or  new=            |-----------|
811 	 */
812 	if ((p != NULL) &&
813 	    (SEQ_LEQ(th->th_seq, (p->tqe_start + p->tqe_len)))) {
814 		/* conversion to int (in i) handles seq wraparound */
815 
816 #ifdef TCP_REASS_COUNTERS
817 		counter_u64_add(reass_path4, 1);
818 #endif
819 		i = p->tqe_start + p->tqe_len - th->th_seq;
820 		if (i >= 0) {
821 			if (i >= *tlenp) {
822 				/**
823 				 *       prev seg---->+
824 				 *                    v
825 				 *  reassembly buffer |---|
826 				 *  new segment        |-|
827 				 */
828 				TCPSTAT_INC(tcps_rcvduppack);
829 				TCPSTAT_ADD(tcps_rcvdupbyte, *tlenp);
830 				*tlenp = p->tqe_len;
831 				*seq_start = p->tqe_start;
832 				m_freem(m);
833 				/*
834 				 * Try to present any queued data
835 				 * at the left window edge to the user.
836 				 * This is needed after the 3-WHS
837 				 * completes. Note this probably
838 				 * will not work and we will return.
839 				 */
840 				return (0);
841 			}
842 			if (i > 0) {
843 				/**
844 				 *       prev seg---->+
845 				 *                    v
846 				 *  reassembly buffer |---|
847 				 *  new segment         |-----|
848 				 */
849 #ifdef TCP_REASS_COUNTERS
850 				counter_u64_add(reass_path5, 1);
851 #endif
852 #ifdef TCP_REASS_LOGGING
853 				tcp_log_reassm(tp, p, NULL, 0, i, TCP_R_LOG_TRIM, 5);
854 #endif
855 				m_adj(m, i);
856 				*tlenp -= i;
857 				th->th_seq += i;
858 			}
859 		}
860 		if (th->th_seq == (p->tqe_start + p->tqe_len)) {
861 			/*
862 			 * If dovetails in with this one
863 			 * append it.
864 			 */
865 			/**
866 			 *       prev seg---->+
867 			 *                    v
868 			 *  reassembly buffer |--|     |---|
869 			 *  new segment          |--|
870 			 * (note: it was trimmed above if it overlapped)
871 			 */
872 			tcp_reass_append(tp, p, m, th, *tlenp, mlast, lenofoh);
873 			tp->t_segqmbuflen += lenofoh;
874 		} else {
875 #ifdef INVARIANTS
876 			panic("Impossible cut th_seq:%u p->seq:%u(%d) p:%p tp:%p",
877 			      th->th_seq, p->tqe_start, p->tqe_len,
878 			      p, tp);
879 #endif
880 			*tlenp = 0;
881 			m_freem(m);
882 			return (0);
883 		}
884 		q = p;
885 	} else {
886 		/*
887 		 * The new data runs over the
888 		 * top of previously sack'd data (in q).
889 		 * It may be partially overlapping, or
890 		 * it may overlap the entire segment.
891 		 */
892 #ifdef TCP_REASS_COUNTERS
893 		counter_u64_add(reass_path6, 1);
894 #endif
895 		if (SEQ_GEQ((th->th_seq + *tlenp), (q->tqe_start + q->tqe_len))) {
896 			/* It consumes it all */
897 			/**
898 			 *             next seg---->+
899 			 *                          v
900 			 *  reassembly buffer |--|     |---|
901 			 *  new segment              |----------|
902 			 */
903 #ifdef TCP_REASS_COUNTERS
904 			counter_u64_add(reass_path7, 1);
905 #endif
906 			tcp_reass_replace(tp, q, m, th->th_seq, *tlenp, mlast, lenofoh, th->th_flags);
907 		} else {
908 			/*
909 			 * We just need to prepend the data
910 			 * to this. It does not overrun
911 			 * the end.
912 			 */
913 			/**
914 			 *                next seg---->+
915 			 *                             v
916 			 *  reassembly buffer |--|     |---|
917 			 *  new segment                   |----------|
918 			 */
919 			tcp_reass_prepend(tp, q, m, th, *tlenp, mlast, lenofoh);
920 			tp->t_segqmbuflen += lenofoh;
921 		}
922 	}
923 	/* Now does it go further than that? */
924 	tcp_reass_merge_forward(tp, q);
925 	*seq_start = q->tqe_start;
926 	*tlenp = q->tqe_len;
927 	goto present;
928 
929 	/*
930 	 * When we reach here we can't combine it
931 	 * with any existing segment.
932 	 *
933 	 * Limit the number of segments that can be queued to reduce the
934 	 * potential for mbuf exhaustion. For best performance, we want to be
935 	 * able to queue a full window's worth of segments. The size of the
936 	 * socket receive buffer determines our advertised window and grows
937 	 * automatically when socket buffer autotuning is enabled. Use it as the
938 	 * basis for our queue limit.
939 	 *
940 	 * However, allow the user to specify a ceiling for the number of
941 	 * segments in each queue.
942 	 *
943 	 * Always let the missing segment through which caused this queue.
944 	 * NB: Access to the socket buffer is left intentionally unlocked as we
945 	 * can tolerate stale information here.
946 	 *
947 	 * XXXLAS: Using sbspace(so->so_rcv) instead of so->so_rcv.sb_hiwat
948 	 * should work but causes packets to be dropped when they shouldn't.
949 	 * Investigate why and re-evaluate the below limit after the behaviour
950 	 * is understood.
951 	 */
952 new_entry:
953 	if (th->th_seq == tp->rcv_nxt && TCPS_HAVEESTABLISHED(tp->t_state)) {
954 		tp->rcv_nxt += *tlenp;
955 		flags = th->th_flags & TH_FIN;
956 		TCPSTAT_INC(tcps_rcvoopack);
957 		TCPSTAT_ADD(tcps_rcvoobyte, *tlenp);
958 		SOCKBUF_LOCK(&so->so_rcv);
959 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
960 			m_freem(m);
961 		} else {
962 			sbappendstream_locked(&so->so_rcv, m, 0);
963 		}
964 		sorwakeup_locked(so);
965 		return (flags);
966 	}
967 	if (tcp_new_limits) {
968 		if ((tp->t_segqlen > tcp_reass_queue_guard) &&
969 		    (*tlenp < MSIZE)) {
970 			/*
971 			 * This is really a lie, we are not full but
972 			 * are getting a segment that is above
973 			 * guard threshold. If it is and its below
974 			 * a mbuf size (256) we drop it if it
975 			 * can't fill in some place.
976 			 */
977 			TCPSTAT_INC(tcps_rcvreassfull);
978 			*tlenp = 0;
979 			if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
980 				log(LOG_DEBUG, "%s; %s: queue limit reached, "
981 				    "segment dropped\n", s, __func__);
982 				free(s, M_TCPLOG);
983 			}
984 			m_freem(m);
985 #ifdef TCP_REASS_LOGGING
986 			tcp_reass_log_dump(tp);
987 #endif
988 			return (0);
989 		}
990 	} else {
991 		if (tp->t_segqlen >= min((so->so_rcv.sb_hiwat / tp->t_maxseg) + 1,
992 					 tcp_reass_maxqueuelen)) {
993 			TCPSTAT_INC(tcps_rcvreassfull);
994 			*tlenp = 0;
995 			if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
996 				log(LOG_DEBUG, "%s; %s: queue limit reached, "
997 				    "segment dropped\n", s, __func__);
998 				free(s, M_TCPLOG);
999 			}
1000 			m_freem(m);
1001 #ifdef TCP_REASS_LOGGING
1002 			tcp_reass_log_dump(tp);
1003 #endif
1004 			return (0);
1005 		}
1006 	}
1007 	/*
1008 	 * Allocate a new queue entry. If we can't, or hit the zone limit
1009 	 * just drop the pkt.
1010 	 */
1011 	te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
1012 	if (te == NULL) {
1013 		TCPSTAT_INC(tcps_rcvmemdrop);
1014 		m_freem(m);
1015 		*tlenp = 0;
1016 		if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL,
1017 				       NULL))) {
1018 			log(LOG_DEBUG, "%s; %s: global zone limit "
1019 			    "reached, segment dropped\n", s, __func__);
1020 			free(s, M_TCPLOG);
1021 		}
1022 		return (0);
1023 	}
1024 	tp->t_segqlen++;
1025 	tp->t_rcvoopack++;
1026 	TCPSTAT_INC(tcps_rcvoopack);
1027 	TCPSTAT_ADD(tcps_rcvoobyte, *tlenp);
1028 	/* Insert the new segment queue entry into place. */
1029 	te->tqe_m = m;
1030 	te->tqe_flags = th->th_flags;
1031 	te->tqe_len = *tlenp;
1032 	te->tqe_start = th->th_seq;
1033 	te->tqe_last = mlast;
1034 	te->tqe_mbuf_cnt = lenofoh;
1035 	tp->t_segqmbuflen += te->tqe_mbuf_cnt;
1036 	if (p == NULL) {
1037 		TAILQ_INSERT_HEAD(&tp->t_segq, te, tqe_q);
1038 	} else {
1039 		TAILQ_INSERT_AFTER(&tp->t_segq, p, te, tqe_q);
1040 	}
1041 #ifdef TCP_REASS_LOGGING
1042 	tcp_reass_log_new_in(tp, th->th_seq, *tlenp, m, TCP_R_LOG_NEW_ENTRY, te);
1043 #endif
1044 present:
1045 	/*
1046 	 * Present data to user, advancing rcv_nxt through
1047 	 * completed sequence space.
1048 	 */
1049 	if (!TCPS_HAVEESTABLISHED(tp->t_state))
1050 		return (0);
1051 	q = TAILQ_FIRST(&tp->t_segq);
1052 	KASSERT(q == NULL || SEQ_GEQ(q->tqe_start, tp->rcv_nxt),
1053 		("Reassembly queue for %p has stale entry at head", tp));
1054 	if (!q || q->tqe_start != tp->rcv_nxt) {
1055 #ifdef TCP_REASS_LOGGING
1056 		tcp_reass_log_dump(tp);
1057 #endif
1058 		return (0);
1059 	}
1060 	SOCKBUF_LOCK(&so->so_rcv);
1061 	do {
1062 		tp->rcv_nxt += q->tqe_len;
1063 		flags = q->tqe_flags & TH_FIN;
1064 		nq = TAILQ_NEXT(q, tqe_q);
1065 		TAILQ_REMOVE(&tp->t_segq, q, tqe_q);
1066 		if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1067 			m_freem(q->tqe_m);
1068 		} else {
1069 #ifdef TCP_REASS_LOGGING
1070 			tcp_reass_log_new_in(tp, q->tqe_start, q->tqe_len, q->tqe_m, TCP_R_LOG_READ, q);
1071 			if (th != NULL) {
1072 				tcp_log_reassm(tp, q, NULL, th->th_seq, *tlenp, TCP_R_LOG_READ, 1);
1073 			} else {
1074 				tcp_log_reassm(tp, q, NULL, 0, 0, TCP_R_LOG_READ, 1);
1075 			}
1076 #endif
1077 			sbappendstream_locked(&so->so_rcv, q->tqe_m, 0);
1078 		}
1079 #ifdef TCP_REASS_LOGGING
1080 		if (th != NULL) {
1081 			tcp_log_reassm(tp, q, NULL, th->th_seq, *tlenp, TCP_R_LOG_READ, 2);
1082 		} else {
1083 			tcp_log_reassm(tp, q, NULL, 0, 0, TCP_R_LOG_READ, 2);
1084 		}
1085 #endif
1086 		KASSERT(tp->t_segqmbuflen >= q->tqe_mbuf_cnt,
1087 			("tp:%p seg queue goes negative", tp));
1088 		tp->t_segqmbuflen -= q->tqe_mbuf_cnt;
1089 		uma_zfree(tcp_reass_zone, q);
1090 		tp->t_segqlen--;
1091 		q = nq;
1092 	} while (q && q->tqe_start == tp->rcv_nxt);
1093 	if (TAILQ_EMPTY(&tp->t_segq) &&
1094 	    (tp->t_segqmbuflen != 0)) {
1095 #ifdef INVARIANTS
1096 		panic("tp:%p segq:%p len:%d queue empty",
1097 		      tp, &tp->t_segq, tp->t_segqmbuflen);
1098 #else
1099 #ifdef TCP_REASS_LOGGING
1100 		if (th != NULL) {
1101 			tcp_log_reassm(tp, NULL, NULL, th->th_seq, *tlenp, TCP_R_LOG_ZERO, 0);
1102 		} else {
1103 			tcp_log_reassm(tp, NULL, NULL, 0, 0, TCP_R_LOG_ZERO, 0);
1104 		}
1105 #endif
1106 		tp->t_segqmbuflen = 0;
1107 #endif
1108 	}
1109 #ifdef TCP_REASS_LOGGING
1110 	tcp_reass_log_dump(tp);
1111 #endif
1112 	sorwakeup_locked(so);
1113 	return (flags);
1114 }
1115