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