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