• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 2007-2008,2010
5  *	Swinburne University of Technology, Melbourne, Australia.
6  * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
7  * Copyright (c) 2010 The FreeBSD Foundation
8  * Copyright (c) 2010-2011 Juniper Networks, Inc.
9  * All rights reserved.
10  *
11  * Portions of this software were developed at the Centre for Advanced Internet
12  * Architectures, Swinburne University of Technology, by Lawrence Stewart,
13  * James Healy and David Hayes, made possible in part by a grant from the Cisco
14  * University Research Program Fund at Community Foundation Silicon Valley.
15  *
16  * Portions of this software were developed at the Centre for Advanced
17  * Internet Architectures, Swinburne University of Technology, Melbourne,
18  * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
19  *
20  * Portions of this software were developed by Robert N. M. Watson under
21  * contract to Juniper Networks, Inc.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the above copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 4. Neither the name of the University nor the names of its contributors
32  *    may be used to endorse or promote products derived from this software
33  *    without specific prior written permission.
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45  * SUCH DAMAGE.
46  *
47  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
48  */
49 
50 
51 /*
52  * Determine a reasonable value for maxseg size.
53  * If the route is known, check route for mtu.
54  * If none, use an mss that can be handled on the outgoing interface
55  * without forcing IP to fragment.  If no route is found, route has no mtu,
56  * or the destination isn't local, use a default, hopefully conservative
57  * size (usually 512 or the default IP max size, but no more than the mtu
58  * of the interface), as we can't discover anything about intervening
59  * gateways or networks.  We also initialize the congestion/slow start
60  * window to be a single segment if the destination isn't local.
61  * While looking at the routing entry, we also initialize other path-dependent
62  * parameters from pre-set or cached values in the routing entry.
63  *
64  * Also take into account the space needed for options that we
65  * send regularly.  Make maxseg shorter by that amount to assure
66  * that we can send maxseg amount of data even when the options
67  * are present.  Store the upper limit of the length of options plus
68  * data in maxopd.
69  *
70  * NOTE that this routine is only called when we process an incoming
71  * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
72  * settings are handled in tcp_mssopt().
73  */
74 
75 #include <errno.h>
76 #include <string.h>
77 #include <strings.h>
78 
79 #include "tcp.h"
80 #include "tcp_fsm.h"
81 #include "tcp_seq.h"
82 #include "tcp_timer.h"
83 #include "tcp_var.h"
84 #include "../lib/bitmap.h"
85 #include "../lib/cbuf.h"
86 #include "icmp_var.h"
87 #include "ip.h"
88 #include "ip6.h"
89 #include "sys/queue.h"
90 
91 #include "tcp_const.h"
92 
93 /* samkumar: Copied from in.h */
94 #define IPPROTO_DONE 267
95 
96 /* samkumar: Copied from sys/libkern.h */
imax(int a,int b)97 static int imax(int a, int b) { return (a > b ? a : b); }
imin(int a,int b)98 static int imin(int a, int b) { return (a < b ? a : b); }
99 
min(int a,int b)100 static int min(int a, int b) { return imin(a, b); }
101 
102 static void	 tcp_dooptions(struct tcpopt *, uint8_t *, int, int);
103 static void
104 tcp_do_segment(struct ip6_hdr* ip6, struct tcphdr *th, otMessage* msg,
105     struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
106     struct tcplp_signals* sig);
107 static void	 tcp_xmit_timer(struct tcpcb *, int);
108 void tcp_hc_get(/*struct in_conninfo *inc*/ struct tcpcb* tp, struct hc_metrics_lite *hc_metrics_lite);
109 static void	 tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
110 
111 /*
112  * CC wrapper hook functions
113  */
114 static inline void
cc_ack_received(struct tcpcb * tp,struct tcphdr * th,uint16_t type)115 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
116 {
117 	tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
118 	if (tp->snd_cwnd <= tp->snd_wnd)
119 		tp->ccv->flags |= CCF_CWND_LIMITED;
120 	else
121 		tp->ccv->flags &= ~CCF_CWND_LIMITED;
122 
123 	if (type == CC_ACK) {
124 		if (tp->snd_cwnd > tp->snd_ssthresh) {
125 			tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
126 			     V_tcp_abc_l_var * tp->t_maxseg);
127 			if (tp->t_bytes_acked >= tp->snd_cwnd) {
128 				tp->t_bytes_acked -= tp->snd_cwnd;
129 				tp->ccv->flags |= CCF_ABC_SENTAWND;
130 			}
131 		} else {
132 				tp->ccv->flags &= ~CCF_ABC_SENTAWND;
133 				tp->t_bytes_acked = 0;
134 		}
135 	}
136 
137 	if (CC_ALGO(tp)->ack_received != NULL) {
138 		/* XXXLAS: Find a way to live without this */
139 		tp->ccv->curack = th->th_ack;
140 		CC_ALGO(tp)->ack_received(tp->ccv, type);
141 	}
142 }
143 
144 static inline void
cc_conn_init(struct tcpcb * tp)145 cc_conn_init(struct tcpcb *tp)
146 {
147 	struct hc_metrics_lite metrics;
148 	int rtt;
149 
150 	/*
151 	 * samkumar: remove locks, inpcb, and stats.
152 	 */
153 
154 	/* samkumar: Used to take &inp->inp_inc as an argument. */
155 	tcp_hc_get(tp, &metrics);
156 
157 	if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
158 		tp->t_srtt = rtt;
159 		tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
160 		if (metrics.rmx_rttvar) {
161 			tp->t_rttvar = metrics.rmx_rttvar;
162 		} else {
163 			/* default variation is +- 1 rtt */
164 			tp->t_rttvar =
165 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
166 		}
167 		TCPT_RANGESET(tp->t_rxtcur,
168 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
169 		    tp->t_rttmin, TCPTV_REXMTMAX);
170 	}
171 	if (metrics.rmx_ssthresh) {
172 		/*
173 		 * There's some sort of gateway or interface
174 		 * buffer limit on the path.  Use this to set
175 		 * the slow start threshhold, but set the
176 		 * threshold to no less than 2*mss.
177 		 */
178 		tp->snd_ssthresh = max(2 * tp->t_maxseg, metrics.rmx_ssthresh);
179 	}
180 
181 	/*
182 	 * Set the initial slow-start flight size.
183 	 *
184 	 * RFC5681 Section 3.1 specifies the default conservative values.
185 	 * RFC3390 specifies slightly more aggressive values.
186 	 * RFC6928 increases it to ten segments.
187 	 * Support for user specified value for initial flight size.
188 	 *
189 	 * If a SYN or SYN/ACK was lost and retransmitted, we have to
190 	 * reduce the initial CWND to one segment as congestion is likely
191 	 * requiring us to be cautious.
192 	 */
193 	if (tp->snd_cwnd == 1)
194 		tp->snd_cwnd = tp->t_maxseg;		/* SYN(-ACK) lost */
195 	else if (V_tcp_initcwnd_segments)
196 		tp->snd_cwnd = min(V_tcp_initcwnd_segments * tp->t_maxseg,
197 		    max(2 * tp->t_maxseg, V_tcp_initcwnd_segments * 1460));
198 	else if (V_tcp_do_rfc3390)
199 		tp->snd_cwnd = min(4 * tp->t_maxseg,
200 		    max(2 * tp->t_maxseg, 4380));
201 	else {
202 		/* Per RFC5681 Section 3.1 */
203 		if (tp->t_maxseg > 2190)
204 			tp->snd_cwnd = 2 * tp->t_maxseg;
205 		else if (tp->t_maxseg > 1095)
206 			tp->snd_cwnd = 3 * tp->t_maxseg;
207 		else
208 			tp->snd_cwnd = 4 * tp->t_maxseg;
209 	}
210 
211 	if (CC_ALGO(tp)->conn_init != NULL)
212 		CC_ALGO(tp)->conn_init(tp->ccv);
213 
214 	/* samkumar: print statement for debugging. Resurrect with DEBUG macro? */
215 #ifdef INSTRUMENT_TCP
216 	tcplp_sys_log("TCP CC_INIT %u %d %d", (unsigned int) tcplp_sys_get_millis(), (int) tp->snd_cwnd, (int) tp->snd_ssthresh);
217 #endif
218 }
219 
220 inline void
cc_cong_signal(struct tcpcb * tp,struct tcphdr * th,uint32_t type)221 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
222 {
223 	/* samkumar: Remove locks and stats from this function. */
224 
225 	switch(type) {
226 	case CC_NDUPACK:
227 		if (!IN_FASTRECOVERY(tp->t_flags)) {
228 			tp->snd_recover = tp->snd_max;
229 			if (tp->t_flags & TF_ECN_PERMIT)
230 				tp->t_flags |= TF_ECN_SND_CWR;
231 		}
232 		break;
233 	case CC_ECN:
234 		if (!IN_CONGRECOVERY(tp->t_flags)) {
235 			tp->snd_recover = tp->snd_max;
236 			if (tp->t_flags & TF_ECN_PERMIT)
237 				tp->t_flags |= TF_ECN_SND_CWR;
238 		}
239 		break;
240 	case CC_RTO:
241 		tp->t_dupacks = 0;
242 		tp->t_bytes_acked = 0;
243 		EXIT_RECOVERY(tp->t_flags);
244 		tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
245 		    tp->t_maxseg) * tp->t_maxseg;
246 		tp->snd_cwnd = tp->t_maxseg;
247 
248 		/*
249 		 * samkumar: Stats for TCPlp: count the number of timeouts (RTOs).
250 		 * I've commented this out (with #if 0) because it isn't part of TCP
251 		 * functionality. At some point, we may want to bring it back to
252 		 * measure performance.
253 		 */
254 #if 0
255 		tcplp_timeoutRexmitCnt++;
256 #endif
257 #ifdef INSTRUMENT_TCP
258 		tcplp_sys_log("TCP CC_RTO %u %d %d", (unsigned int) tcplp_sys_get_millis(), (int) tp->snd_cwnd, (int) tp->snd_ssthresh);
259 #endif
260 		break;
261 	case CC_RTO_ERR:
262 		/* RTO was unnecessary, so reset everything. */
263 		tp->snd_cwnd = tp->snd_cwnd_prev;
264 		tp->snd_ssthresh = tp->snd_ssthresh_prev;
265 		tp->snd_recover = tp->snd_recover_prev;
266 		if (tp->t_flags & TF_WASFRECOVERY)
267 			ENTER_FASTRECOVERY(tp->t_flags);
268 		if (tp->t_flags & TF_WASCRECOVERY)
269 			ENTER_CONGRECOVERY(tp->t_flags);
270 		tp->snd_nxt = tp->snd_max;
271 		tp->t_flags &= ~TF_PREVVALID;
272 		tp->t_badrxtwin = 0;
273 #ifdef INSTRUMENT_TCP
274 		tcplp_sys_log("TCP CC_RTO_ERR %u %d %d", (unsigned int) tcplp_sys_get_millis(), (int) tp->snd_cwnd, (int) tp->snd_ssthresh);
275 #endif
276 		break;
277 	}
278 
279 	if (CC_ALGO(tp)->cong_signal != NULL) {
280 		if (th != NULL)
281 			tp->ccv->curack = th->th_ack;
282 		CC_ALGO(tp)->cong_signal(tp->ccv, type);
283 	}
284 }
285 
286 static inline void
cc_post_recovery(struct tcpcb * tp,struct tcphdr * th)287 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
288 {
289 	/* samkumar: remove lock */
290 
291 	/* XXXLAS: KASSERT that we're in recovery? */
292 	if (CC_ALGO(tp)->post_recovery != NULL) {
293 		tp->ccv->curack = th->th_ack;
294 		CC_ALGO(tp)->post_recovery(tp->ccv);
295 	}
296 	/* XXXLAS: EXIT_RECOVERY ? */
297 	tp->t_bytes_acked = 0;
298 }
299 
300 
301 /*
302  * Indicate whether this ack should be delayed.  We can delay the ack if
303  * following conditions are met:
304  *	- There is no delayed ack timer in progress.
305  *	- Our last ack wasn't a 0-sized window. We never want to delay
306  *	  the ack that opens up a 0-sized window.
307  *	- LRO wasn't used for this segment. We make sure by checking that the
308  *	  segment size is not larger than the MSS.
309  *	- Delayed acks are enabled or this is a half-synchronized T/TCP
310  *	  connection.
311  */
312 #define DELAY_ACK(tp, tlen)						\
313 	((!tcp_timer_active(tp, TT_DELACK) &&				\
314 	    (tp->t_flags & TF_RXWIN0SENT) == 0) &&			\
315 	    (tlen <= tp->t_maxopd) &&					\
316 	    (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
317 
318 static inline void
cc_ecnpkt_handler(struct tcpcb * tp,struct tcphdr * th,uint8_t iptos)319 cc_ecnpkt_handler(struct tcpcb *tp, struct tcphdr *th, uint8_t iptos)
320 {
321 	/* samkumar: remove lock */
322 
323 	if (CC_ALGO(tp)->ecnpkt_handler != NULL) {
324 		switch (iptos & IPTOS_ECN_MASK) {
325 		case IPTOS_ECN_CE:
326 			tp->ccv->flags |= CCF_IPHDR_CE;
327 			break;
328 		case IPTOS_ECN_ECT0:
329 			tp->ccv->flags &= ~CCF_IPHDR_CE;
330 			break;
331 		case IPTOS_ECN_ECT1:
332 			tp->ccv->flags &= ~CCF_IPHDR_CE;
333 			break;
334 		}
335 
336 		if (th->th_flags & TH_CWR)
337 			tp->ccv->flags |= CCF_TCPHDR_CWR;
338 		else
339 			tp->ccv->flags &= ~CCF_TCPHDR_CWR;
340 
341 		if (tp->t_flags & TF_DELACK)
342 			tp->ccv->flags |= CCF_DELACK;
343 		else
344 			tp->ccv->flags &= ~CCF_DELACK;
345 
346 		CC_ALGO(tp)->ecnpkt_handler(tp->ccv);
347 
348 		if (tp->ccv->flags & CCF_ACKNOW)
349 			tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
350 	}
351 }
352 
353 /*
354  * External function: look up an entry in the hostcache and fill out the
355  * supplied TCP metrics structure.  Fills in NULL when no entry was found or
356  * a value is not set.
357  */
358 /*
359  * samkumar: This function is taken from tcp_hostcache.c. We have no host cache
360  * in TCPlp, so I changed this to always act as if there is a miss. I removed
361  * the first argument, formerly "struct in_coninfo *inc".
362  */
363 void
tcp_hc_get(struct tcpcb * tp,struct hc_metrics_lite * hc_metrics_lite)364 tcp_hc_get(struct tcpcb* tp, struct hc_metrics_lite *hc_metrics_lite)
365 {
366 	bzero(hc_metrics_lite, sizeof(*hc_metrics_lite));
367 }
368 
369 /*
370  * External function: look up an entry in the hostcache and return the
371  * discovered path MTU.  Returns NULL if no entry is found or value is not
372  * set.
373  */
374  /*
375   * samkumar: This function is taken from tcp_hostcache.c. We have no host cache
376   * in TCPlp, so I changed this to always act as if there is a miss.
377   */
378 uint64_t
tcp_hc_getmtu(struct tcpcb * tp)379 tcp_hc_getmtu(struct tcpcb* tp)
380 {
381 	return 0;
382 }
383 
384 
385 /*
386  * Issue RST and make ACK acceptable to originator of segment.
387  * The mbuf must still include the original packet header.
388  * tp may be NULL.
389  */
390 /*
391  * samkumar: Original signature was:
392  * static void tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
393  *    int tlen, int rstreason)
394  */
395 void
tcp_dropwithreset(struct ip6_hdr * ip6,struct tcphdr * th,struct tcpcb * tp,otInstance * instance,int tlen,int rstreason)396 tcp_dropwithreset(struct ip6_hdr* ip6, struct tcphdr *th, struct tcpcb *tp, otInstance* instance,
397     int tlen, int rstreason)
398 {
399 	/*
400 	 * samkumar: I removed logic to skip this for broadcast or multicast
401 	 * packets. In the FreeBSD version of this function, it would just
402 	 * call m_freem(m), if m->m_flags has M_BCAST or M_MCAST set, and not
403 	 * send a response packet.
404 	 * I also removed bandwidth limiting.
405 	 */
406 	if (th->th_flags & TH_RST)
407 		return;
408 
409 	/* tcp_respond consumes the mbuf chain. */
410 	if (th->th_flags & TH_ACK) {
411 		tcp_respond(tp, instance, ip6, th, (tcp_seq) 0, th->th_ack, TH_RST);
412 	} else {
413 		if (th->th_flags & TH_SYN)
414 			tlen++;
415 		tcp_respond(tp, instance, ip6, th, th->th_seq + tlen, (tcp_seq) 0, TH_RST | TH_ACK);
416 	}
417 	return;
418 }
419 
420 /*
421  * TCP input handling is split into multiple parts:
422  *   tcp6_input is a thin wrapper around tcp_input for the extended
423  *	ip6_protox[] call format in ip6_input
424  *   tcp_input handles primary segment validation, inpcb lookup and
425  *	SYN processing on listen sockets
426  *   tcp_do_segment processes the ACK and text of the segment for
427  *	establishing, established and closing connections
428  */
429 /* samkumar: The signature of this function was originally:
430    tcp_input(struct mbuf **mp, int *offp, int proto) */
431 /* NOTE: tcp_fields_to_host(th) must be called before this function is called. */
432 int
tcp_input(struct ip6_hdr * ip6,struct tcphdr * th,otMessage * msg,struct tcpcb * tp,struct tcpcb_listen * tpl,struct tcplp_signals * sig)433 tcp_input(struct ip6_hdr* ip6, struct tcphdr* th, otMessage* msg, struct tcpcb* tp, struct tcpcb_listen* tpl,
434           struct tcplp_signals* sig)
435 {
436 	/*
437 	 * samkumar: I significantly modified this function, compared to the
438 	 * FreeBSD version. This function used to be reponsible for matching an
439 	 * incoming TCP segment to its TCB. That functionality is now done by
440 	 * TCPlp, and this function is only called once a match has been
441 	 * identified.
442 	 *
443 	 * The tp and tpl arguments are used to indicate the match. Exactly one of
444 	 * them must be NULL, and the other must be set. If tp is non-NULL, then
445 	 * this function assumes that the packet was matched to an active socket
446 	 * (connection endpoint). If tpl is non-NULL, then this function assumes
447 	 * that this packet is a candidate match for a passive socket (listener)
448 	 * and attempts to set up a new connection if the flags, sequence numbers,
449 	 * etc. look OK.
450 	 *
451 	 * TCPlp assumes that the packets are IPv6, so I removed any logic specific
452 	 * to IPv4.
453 	 *
454 	 * And of course, all code pertaining to locks and stats has been removed.
455 	 */
456 	int tlen = 0, off;
457 	int thflags;
458 	uint8_t iptos = 0;
459 	int drop_hdrlen;
460 	int rstreason = 0;
461 	struct tcpopt to;		/* options in this segment */
462 	uint8_t* optp = NULL;
463 	int optlen = 0;
464 	to.to_flags = 0;
465 	KASSERT(tp || tpl, ("One of tp and tpl must be positive"));
466 
467 	/*
468 	 * samkumar: Here, there used to be code that handled preprocessing:
469 	 * calling m_pullup(m, sizeof(*ip6) + sizeof(*th)) to get the headers
470 	 * contiguous in memory, setting the ip6 and th pointers, validating the
471 	 * checksum, and dropping packets with unspecified source address. In
472 	 * TCPlp, all of this is done for a packet before this function is called.
473 	 */
474 
475 	tlen = ntohs(ip6->ip6_plen); // assume *off == sizeof(*ip6)
476 
477 	/*
478 	 * samkumar: Logic that handled IPv4 was deleted below. I won't add a
479 	 * comment every time this is done, but I'm putting it here (one of the
480 	 * first instances of this) for clarity.
481 	 */
482 	iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
483 
484 	/*
485 	 * Check that TCP offset makes sense,
486 	 * pull out TCP options and adjust length.		XXX
487 	 */
488 	off = (th->th_off_x2 >> TH_OFF_SHIFT) << 2;
489 	if (off < sizeof (struct tcphdr) || off > tlen) {
490 		goto drop;
491 	}
492 	tlen -= off;	/* tlen is used instead of ti->ti_len */
493 	/* samkumar: now, tlen is the length of the data */
494 
495 	if (off > sizeof (struct tcphdr)) {
496 		/*
497 		 * samkumar: I removed a call to IP6_EXTHDR_CHECK, which I believe
498 		 * checks for IPv6 extension headers. In TCPlp, we assume that these
499 		 * are handled elsewhere in the networking stack, before the incoming
500 		 * packet is processed at the TCP layer. I also removed the followup
501 		 * calls to reassign the ip6 and th pointers.
502 		 */
503 		optlen = off - sizeof (struct tcphdr);
504 		optp = (uint8_t *)(th + 1);
505 	}
506 
507 	thflags = th->th_flags;
508 
509 	/*
510 	 * samkumar: There used to be a call here to tcp_fields_to_host(th), which
511 	 * changes the byte order of various fields to host format. I removed this
512 	 * call from there and handle it in TCPlp, before calling this. The reason
513 	 * is that it's possible for this function to be called twice by TCPlp's
514 	 * logic (e.g., if the packet matches a TIME-WAIT socket this function
515 	 * returns early, and the packet may then match a listening socket, at
516  	 * which ppoint this function will be called again). Thus, any operations
517 	 * like this, which mutate the packet itself, need to happen before calling
518 	 * this function.
519 	 */
520 
521 	/*
522 	 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
523 	 *
524 	 * samkumar: My TCP header is in a different buffer from the IP header.
525 	 * drop_hdrlen is only meaningful as an offset into the TCP buffer,
526 	 * because it is used to determine how much of the packet to discard
527 	 * before copying it into the receive buffer. Therefore, my offset does
528 	 * not include the length of IP header and options, only the length of
529 	 * the TCP header and options.
530 	 */
531 	drop_hdrlen = /*off0 +*/ off;
532 
533 	/*
534 	 * Locate pcb for segment; if we're likely to add or remove a
535 	 * connection then first acquire pcbinfo lock.  There are three cases
536 	 * where we might discover later we need a write lock despite the
537 	 * flags: ACKs moving a connection out of the syncache, ACKs for a
538 	 * connection in TIMEWAIT and SYNs not targeting a listening socket.
539 	 */
540 
541 	/*
542 	 * samkumar: Locking code is removed, invalidating most of the above
543 	 * comment.
544 	 */
545 
546 	/*
547 	 * samkumar: The FreeBSD code at logic here to check m->m_flags for the
548 	 * M_IP6_NEXTHOP flag, and search for the PACKET_TAG_IPFORWARD tag and
549 	 * store it in fwd_tag if so. In TCPlp, we assume that the IPv6 layer of
550 	 * the host network stack handles this kind of IPv6-related functionality,
551 	 * so this logic has been removed.
552 	 */
553 
554 	/*
555 	 * samkumar: Here, there was code to match the packet to an inpcb and reply
556 	 * with an RST segment if no match is found. This included taking the
557 	 * fwd_tag into account, if set above (see the previous comment). I removed
558 	 * this code because, in TCPlp, this is done before calling this function.
559 	 */
560 
561 	/*
562 	 * A previous connection in TIMEWAIT state is supposed to catch stray
563 	 * or duplicate segments arriving late.  If this segment was a
564 	 * legitimate new connection attempt, the old INPCB gets removed and
565 	 * we can try again to find a listening socket.
566 	 *
567 	 * At this point, due to earlier optimism, we may hold only an inpcb
568 	 * lock, and not the inpcbinfo write lock.  If so, we need to try to
569 	 * acquire it, or if that fails, acquire a reference on the inpcb,
570 	 * drop all locks, acquire a global write lock, and then re-acquire
571 	 * the inpcb lock.  We may at that point discover that another thread
572 	 * has tried to free the inpcb, in which case we need to loop back
573 	 * and try to find a new inpcb to deliver to.
574 	 *
575 	 * XXXRW: It may be time to rethink timewait locking.
576 	 */
577 	/*
578 	 * samkumar: The original code checked inp->inp_flags & INP_TIMEWAIT. I
579 	 * changed it to instead check tp->t_state, since we don't use inpcbs in
580 	 * TCPlp.
581 	 */
582 	if (tp && tp->t_state == TCP6S_TIME_WAIT) {
583 		/*
584 		 * samkumar: There's nothing wrong with the call to tcp_dooptions call
585 		 * that I've commented out below; it's just that the modified
586 		 * "tcp_twcheck" function no longer needs the options structure, so
587 		 * I figured that there's no longer a good reason to parse the options.
588 		 * In fact, this call was probably unnecessary even in the original
589 		 * FreeBSD TCP code, since tcp_twcheck, even without my modifications,
590 		 * did not use the pointer to the options structure!
591 		 */
592 		//if (thflags & TH_SYN)
593 			//tcp_dooptions(&to, optp, optlen, TO_SYN);
594 		/*
595 		 * samkumar: The original code would "goto findpcb;" if this branch is
596 		 * taken. Matching with a TCB is done outside of this function in
597 		 * TCPlp, so we instead return a special value so that the caller knows
598 		 * to try re-matching this packet to a socket.
599 		 */
600 		if (tcp_twcheck(tp,/*inp, &to,*/ th, /*m,*/ tlen))
601 			return (RELOOKUP_REQUIRED);
602 		return (IPPROTO_DONE);
603 	}
604 	/*
605 	 * The TCPCB may no longer exist if the connection is winding
606 	 * down or it is in the CLOSED state.  Either way we drop the
607 	 * segment and send an appropriate response.
608 	 */
609 	/*
610 	 * samkumar: There used to be code here that grabs the tp from the inpcb
611 	 * and drops with reset if the connection is in the closed state or if
612 	 * the tp is NULL. In TCPlp, the equivalent logic is done before entering
613 	 * this function. There was also code here to handle TCP offload, which
614 	 * TCPlp does not handle.
615 	 */
616 
617 	/*
618 	 * We've identified a valid inpcb, but it could be that we need an
619 	 * inpcbinfo write lock but don't hold it.  In this case, attempt to
620 	 * acquire using the same strategy as the TIMEWAIT case above.  If we
621 	 * relock, we have to jump back to 'relocked' as the connection might
622 	 * now be in TIMEWAIT.
623 	 */
624 	/*
625 	 * samkumar: There used to be some code here for synchronization, MAC
626 	 * management, and debugging.
627 	 */
628 
629 	/*
630 	 * When the socket is accepting connections (the INPCB is in LISTEN
631 	 * state) we look into the SYN cache if this is a new connection
632 	 * attempt or the completion of a previous one. Instead of checking
633 	 * so->so_options to check if the socket is listening, we rely on the
634 	 * arguments passed to this function (if tp == NULL, then tpl is not NULL
635 	 * and is the matching listen socket).
636 	 */
637 
638 	if (/*so->so_options & SO_ACCEPTCONN*/tp == NULL) {
639 		/* samkumar: NULL check isn't needed but prevents a compiler warning */
640 		KASSERT(tpl != NULL && tpl->t_state == TCP6S_LISTEN, ("listen socket must be in listening state!"));
641 
642 		/*
643 		 * samkumar: There used to be some code here that checks if the
644 		 * received segment is an ACK, and if so, searches the SYN cache to
645 		 * find an entry whose connection establishment handshake this segment
646 		 * completes. If such an entry is found, then a socket is created and
647 		 * then tcp_do_segment is called to actually run the code to mark the
648 		 * connection as established. If the received segment is an RST, then
649 		 * that is processed in the syncache as well. In TCPlp we do not use a
650 		 * SYN cache, so I've removed that code. The actual connection
651 		 * establishment/processing logic happens in tcp_do_segment anyway,
652 		 * which is called at the bottom of this function, so there's no need
653 		 * to rewrite this code with special-case logic for that.
654 		 */
655 
656 		/*
657 		 * We can't do anything without SYN.
658 		 */
659 		if ((thflags & TH_SYN) == 0) {
660 			/*
661 			 * samkumar: Here, and in several other instances, the FreeBSD
662 			 * code would call tcp_log_addrs. Improving logging in these
663 			 * edge cases in TCPlp is left for the future --- for now, I just
664 			 * put "<addrs go here>" where the address string would go.
665 			 */
666 			tcplp_sys_log("%s; %s: Listen socket: "
667 			    "SYN is missing, segment ignored",
668 			    "<addrs go here>", __func__);
669 			goto dropunlock;
670 		}
671 		/*
672 		 * (SYN|ACK) is bogus on a listen socket.
673 		 */
674 		if (thflags & TH_ACK) {
675 			/* samkumar: See above comment regarding tcp_log_addrs. */
676 			tcplp_sys_log("%s; %s: Listen socket: "
677 			    "SYN|ACK invalid, segment rejected",
678 			    "<addrs go here>", __func__);
679 			/* samkumar: Removed call to syncache_badack(&inc); */
680 			rstreason = BANDLIM_RST_OPENPORT;
681 			goto dropwithreset;
682 		}
683 		/*
684 		 * If the drop_synfin option is enabled, drop all
685 		 * segments with both the SYN and FIN bits set.
686 		 * This prevents e.g. nmap from identifying the
687 		 * TCP/IP stack.
688 		 * XXX: Poor reasoning.  nmap has other methods
689 		 * and is constantly refining its stack detection
690 		 * strategies.
691 		 * XXX: This is a violation of the TCP specification
692 		 * and was used by RFC1644.
693 		 */
694 		if ((thflags & TH_FIN) && V_drop_synfin) {
695 			/* samkumar: See above comment regarding tcp_log_addrs. */
696 			tcplp_sys_log("%s; %s: Listen socket: "
697 			    "SYN|FIN segment ignored (based on "
698 			    "sysctl setting)", "<addrs go here>", __func__);
699 			goto dropunlock;
700 		}
701 		/*
702 		 * Segment's flags are (SYN) or (SYN|FIN).
703 		 *
704 		 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
705 		 * as they do not affect the state of the TCP FSM.
706 		 * The data pointed to by TH_URG and th_urp is ignored.
707 		 */
708 		KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
709 		    ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
710 		KASSERT(thflags & (TH_SYN),
711 		    ("%s: Listen socket: TH_SYN not set", __func__));
712 
713 		/*
714 		 * samkumar: There used to be some code here to reject incoming
715 		 * SYN packets for deprecated interface addresses unless
716 		 * V_ip6_use_deprecated is true. Rejecting the packet, in this case,
717 		 * means to "goto dropwithreset". I removed this functionality.
718 		 */
719 
720 		/*
721 		 * Basic sanity checks on incoming SYN requests:
722 		 *   Don't respond if the destination is a link layer
723 		 *	broadcast according to RFC1122 4.2.3.10, p. 104.
724 		 *   If it is from this socket it must be forged.
725 		 *   Don't respond if the source or destination is a
726 		 *	global or subnet broad- or multicast address.
727 		 *   Note that it is quite possible to receive unicast
728 		 *	link-layer packets with a broadcast IP address. Use
729 		 *	in_broadcast() to find them.
730 		 */
731 
732 		/*
733 		 * samkumar: There used to be a sanity check that drops (via
734 		 * "goto dropunlock") any broadcast or multicast packets. This check is
735 		 * done by checking m->m_flags for (M_BAST|M_MCAST). The original
736 		 * FreeBSD code for this has been removed (since checking m->m_flags
737 		 * isn't really useful to us anyway). Note that other FreeBSD code that
738 		 * checks for multicast source/destination addresses is retained below
739 		 * (but only for the IPv6 case; the original FreeBSD code also handled
740 	 	 * it for IPv4 addresses).
741 		 */
742 
743 		if (th->th_dport == th->th_sport &&
744 		    IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
745 			/* samkumar: See above comment regarding tcp_log_addrs. */
746 			tcplp_sys_log("%s; %s: Listen socket: "
747 			"Connection attempt to/from self "
748 			"ignored", "<addrs go here>", __func__);
749 			goto dropunlock;
750 		}
751 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
752 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
753 			/* samkumar: See above comment regarding tcp_log_addrs. */
754 			tcplp_sys_log("%s; %s: Listen socket: "
755 			"Connection attempt from/to multicast "
756 			"address ignored", "<addrs go here>", __func__);
757 			goto dropunlock;
758 		}
759 
760 		/*
761 		 * samkumar: The FreeBSD code would call
762 		 * syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
763 		 * to add an entry to the SYN cache at this point. TCPlp doesn't use a
764 		 * syncache, so we initialize the new socket right away. The code to
765 		 * initialize the socket is taken from the syncache_socket function.
766 		 */
767 
768 		tcp_dooptions(&to, optp, optlen, TO_SYN);
769 		tp = tcplp_sys_accept_ready(tpl, &ip6->ip6_dst, th->th_sport); // Try to allocate an active socket to accept into
770 		if (tp == NULL) {
771 			/* If we couldn't allocate, just ignore the SYN. */
772 			return IPPROTO_DONE;
773 		}
774 		if (tp == (struct tcpcb *) -1) {
775 			rstreason = ECONNREFUSED;
776 			goto dropwithreset;
777 		}
778 		tcp_state_change(tp, TCPS_SYN_RECEIVED);
779 		tpmarkpassiveopen(tp);
780 		tp->t_flags |= TF_ACKNOW; // samkumar: my addition
781 		tp->iss = tcp_new_isn(tp);
782 		tp->irs = th->th_seq;
783 		tcp_rcvseqinit(tp);
784 		tcp_sendseqinit(tp);
785 		tp->snd_wl1 = th->th_seq;
786 		tp->snd_max = tp->iss/* + 1*/;
787 		tp->snd_nxt = tp->iss/* + 1*/;
788 		tp->rcv_up = th->th_seq + 1;
789 		tp->rcv_wnd = imin(imax(cbuf_free_space(&tp->recvbuf), 0), TCP_MAXWIN);
790 		tp->rcv_adv += tp->rcv_wnd;
791 		tp->last_ack_sent = tp->rcv_nxt;
792 		memcpy(&tp->laddr, &ip6->ip6_dst, sizeof(tp->laddr));
793 		memcpy(&tp->faddr, &ip6->ip6_src, sizeof(tp->faddr));
794 		tp->fport = th->th_sport;
795 		tp->lport = tpl->lport;
796 
797 		/*
798 		 * samkumar: Several of the checks below (taken from syncache_socket!)
799 		 * check for flags in sc->sc_flags. They have been written to directly
800 		 * check for the conditions on the TCP options structure or in the TCP
801 		 * header that would ordinarily be used to set flags in sc->sc_flags
802 		 * when adding an entry to the SYN cache.
803 		 *
804 		 * In effect, we combine the logic in syncache_add to set elements of
805 		 * sc with the logic in syncache_socket to transfer state from sc
806 		 * to the socket, but short-circuit the process to avoid ever storing
807 		 * data in sc. Since this isn't just adding or deleting code, I decided
808 		 * that it's better to keep comments indicating exactly how I composed
809 		 * these two functions.
810 		 */
811 		tp->t_flags = tp->t_flags & (TF_NOPUSH | TF_NODELAY | TF_NOOPT);
812 //		tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
813 //		if (sc->sc_flags & SCF_NOOPT)
814 //			tp->t_flags |= TF_NOOPT;
815 //		else {
816 		if (!(tp->t_flags & TF_NOOPT) && V_tcp_do_rfc1323) {
817 			if (/*sc->sc_flags & SCF_WINSCALE*/to.to_flags & TOF_SCALE) {
818 				int wscale = 0;
819 
820 				/*
821 				 * Pick the smallest possible scaling factor that
822 				 * will still allow us to scale up to sb_max, aka
823 				 * kern.ipc.maxsockbuf.
824 				 *
825 				 * We do this because there are broken firewalls that
826 				 * will corrupt the window scale option, leading to
827 				 * the other endpoint believing that our advertised
828 				 * window is unscaled.  At scale factors larger than
829 				 * 5 the unscaled window will drop below 1500 bytes,
830 				 * leading to serious problems when traversing these
831 				 * broken firewalls.
832 				 *
833 				 * With the default maxsockbuf of 256K, a scale factor
834 				 * of 3 will be chosen by this algorithm.  Those who
835 				 * choose a larger maxsockbuf should watch out
836 				 * for the compatiblity problems mentioned above.
837 				 *
838 				 * RFC1323: The Window field in a SYN (i.e., a <SYN>
839 				 * or <SYN,ACK>) segment itself is never scaled.
840 				 */
841 
842 				/*
843 				 * samkumar: The original logic, taken from syncache_add, is
844 				 * listed below, commented out. In practice, we just use
845 				 * wscale = 0 because in TCPlp we assume that the buffers
846 				 * aren't big enough for window scaling to be all that useful.
847 				 */
848 #if 0
849 				while (wscale < TCP_MAX_WINSHIFT &&
850 					(TCP_MAXWIN << wscale) < sb_max)
851 					wscale++;
852 #endif
853 
854 				tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
855 				tp->snd_scale = /*sc->sc_requested_s_scale*/to.to_wscale;
856 				tp->request_r_scale = wscale;
857 			}
858 			if (/*sc->sc_flags & SCF_TIMESTAMP*/to.to_flags & TOF_TS) {
859 				tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
860 				tp->ts_recent = /*sc->sc_tsreflect*/to.to_tsval;
861 				tp->ts_recent_age = tcp_ts_getticks();
862 				tp->ts_offset = /*sc->sc_tsoff*/0; // No syncookies, so this should always be 0
863 			}
864 
865 			/*
866 			 * samkumar: there used to be code here that would set the
867 			 * TF_SIGNATURE flag on tp->t_flags if SCF_SIGNATURE is set on
868 			 * sc->sc_flags. I've left it in below, commented out.
869 			 */
870 #if 0
871 	#ifdef TCP_SIGNATURE
872 			if (sc->sc_flags & SCF_SIGNATURE)
873 				tp->t_flags |= TF_SIGNATURE;
874 	#endif
875 #endif
876 			if (/*sc->sc_flags & SCF_SACK*/ to.to_flags & TOF_SACKPERM)
877 				tp->t_flags |= TF_SACK_PERMIT;
878 		}
879 		if (/*sc->sc_flags & SCF_ECN*/(th->th_flags & (TH_ECE|TH_CWR)) && V_tcp_do_ecn)
880 			tp->t_flags |= TF_ECN_PERMIT;
881 
882 		/*
883 		 * Set up MSS and get cached values from tcp_hostcache.
884 		 * This might overwrite some of the defaults we just set.
885 		 */
886 		tcp_mss(tp, /*sc->sc_peer_mss*/(to.to_flags & TOF_MSS) ? to.to_mss : 0);
887 
888 		tcp_output(tp); // to send the SYN-ACK
889 
890 		tp->accepted_from = tpl;
891 		return (IPPROTO_DONE);
892 	} else if (tp->t_state == TCPS_LISTEN) {
893 		/*
894 		 * When a listen socket is torn down the SO_ACCEPTCONN
895 		 * flag is removed first while connections are drained
896 		 * from the accept queue in a unlock/lock cycle of the
897 		 * ACCEPT_LOCK, opening a race condition allowing a SYN
898 		 * attempt go through unhandled.
899 		 */
900 		goto dropunlock;
901 	}
902 
903 	KASSERT(tp, ("tp is still NULL!"));
904 
905 	/*
906 	 * samkumar: There used to be code here to verify TCP signatures. We don't
907 	 * support TCP signatures in TCPlp.
908 	 */
909 
910 	/*
911 	 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
912 	 * state.  tcp_do_segment() always consumes the mbuf chain, unlocks
913 	 * the inpcb, and unlocks pcbinfo.
914 	 */
915 	tcp_do_segment(ip6, th, msg, tp, drop_hdrlen, tlen, iptos, sig);
916 	return (IPPROTO_DONE);
917 
918 	/*
919 	 * samkumar: Removed some locking and debugging code under all three of
920 	 * these labels: dropwithreset, dropunlock, and drop. I also removed some
921 	 * memory management code (e.g., calling m_freem(m) if m != NULL) since
922 	 * the caller of this function will take care of that kind of memory
923 	 * management in TCPlp.
924 	 */
925 dropwithreset:
926 
927 	/*
928 	 * samkumar: The check against inp != NULL is now a check on tp != NULL.
929 	 */
930 	if (tp != NULL) {
931 		tcp_dropwithreset(ip6, th, tp, tp->instance, tlen, rstreason);
932 	} else
933 		tcp_dropwithreset(ip6, th, NULL, tpl->instance, tlen, rstreason);
934 	goto drop;
935 
936 dropunlock:
937 drop:
938 	return (IPPROTO_DONE);
939 }
940 
941 /*
942  * samkumar: Original signature
943  * static void
944  * tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
945  *     struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
946  *     int ti_locked)
947  */
948 static void
tcp_do_segment(struct ip6_hdr * ip6,struct tcphdr * th,otMessage * msg,struct tcpcb * tp,int drop_hdrlen,int tlen,uint8_t iptos,struct tcplp_signals * sig)949 tcp_do_segment(struct ip6_hdr* ip6, struct tcphdr *th, otMessage* msg,
950     struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
951     struct tcplp_signals* sig)
952 {
953 	/*
954 	 * samkumar: All code pertaining to locks, stats, and debug has been
955 	 * removed from this function.
956 	 */
957 
958 	int thflags, acked, ourfinisacked, needoutput = 0;
959 	int rstreason, todrop, win;
960 	uint64_t tiwin;
961 	struct tcpopt to;
962 	uint32_t ticks = tcplp_sys_get_ticks();
963 	otInstance* instance = tp->instance;
964 	thflags = th->th_flags;
965 	tp->sackhint.last_sack_ack = 0;
966 
967 	/*
968 	 * If this is either a state-changing packet or current state isn't
969 	 * established, we require a write lock on tcbinfo.  Otherwise, we
970 	 * allow the tcbinfo to be in either alocked or unlocked, as the
971 	 * caller may have unnecessarily acquired a write lock due to a race.
972 	 */
973 
974 	/* samkumar: There used to be synchronization code here. */
975 	KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
976 	    __func__));
977 	KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
978 	    __func__));
979 
980 	/*
981 	 * Segment received on connection.
982 	 * Reset idle time and keep-alive timer.
983 	 * XXX: This should be done after segment
984 	 * validation to ignore broken/spoofed segs.
985 	 */
986 	tp->t_rcvtime = ticks;
987 	if (TCPS_HAVEESTABLISHED(tp->t_state))
988 		tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
989 
990 	/*
991 	 * Scale up the window into a 32-bit value.
992 	 * For the SYN_SENT state the scale is zero.
993 	 */
994 	tiwin = th->th_win << tp->snd_scale;
995 
996 	/*
997 	 * TCP ECN processing.
998 	 */
999 	/*
1000 	 * samkumar: I intentionally left the TCPSTAT_INC lines below commented
1001 	 * out, to avoid altering the structure of the code too much by
1002 	 * reorganizing the switch statement.
1003 	 */
1004 	if (tp->t_flags & TF_ECN_PERMIT) {
1005 		if (thflags & TH_CWR)
1006 			tp->t_flags &= ~TF_ECN_SND_ECE;
1007 		switch (iptos & IPTOS_ECN_MASK) {
1008 		case IPTOS_ECN_CE:
1009 			tp->t_flags |= TF_ECN_SND_ECE;
1010 			//TCPSTAT_INC(tcps_ecn_ce);
1011 			break;
1012 		case IPTOS_ECN_ECT0:
1013 			//TCPSTAT_INC(tcps_ecn_ect0);
1014 			break;
1015 		case IPTOS_ECN_ECT1:
1016 			//TCPSTAT_INC(tcps_ecn_ect1);
1017 			break;
1018 		}
1019 
1020 		/* Process a packet differently from RFC3168. */
1021 		cc_ecnpkt_handler(tp, th, iptos);
1022 
1023 		/* Congestion experienced. */
1024 		if (thflags & TH_ECE) {
1025 			cc_cong_signal(tp, th, CC_ECN);
1026 		}
1027 	}
1028 
1029 	/*
1030 	 * Parse options on any incoming segment.
1031 	 */
1032 	tcp_dooptions(&to, (uint8_t *)(th + 1),
1033 	    ((th->th_off_x2 >> TH_OFF_SHIFT) << 2) - sizeof(struct tcphdr),
1034 	    (thflags & TH_SYN) ? TO_SYN : 0);
1035 
1036 	/*
1037 	 * If echoed timestamp is later than the current time,
1038 	 * fall back to non RFC1323 RTT calculation.  Normalize
1039 	 * timestamp if syncookies were used when this connection
1040 	 * was established.
1041 	 */
1042 
1043 	if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1044 		to.to_tsecr -= tp->ts_offset;
1045 		if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1046 			to.to_tsecr = 0;
1047 	}
1048 	/*
1049 	 * If timestamps were negotiated during SYN/ACK they should
1050 	 * appear on every segment during this session and vice versa.
1051 	 */
1052 	if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1053 		/* samkumar: See above comment regarding tcp_log_addrs. */
1054 		tcplp_sys_log("%s; %s: Timestamp missing, "
1055 			"no action", "<addrs go here>", __func__);
1056 	}
1057 	if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1058 		/* samkumar: See above comment regarding tcp_log_addrs. */
1059 		tcplp_sys_log("%s; %s: Timestamp not expected, "
1060 			"no action", "<addrs go here>", __func__);
1061 	}
1062 
1063 	/*
1064 	 * Process options only when we get SYN/ACK back. The SYN case
1065 	 * for incoming connections is handled in tcp_syncache.
1066 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1067 	 * or <SYN,ACK>) segment itself is never scaled.
1068 	 * XXX this is traditional behavior, may need to be cleaned up.
1069 	 */
1070 	if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1071 		if ((to.to_flags & TOF_SCALE) &&
1072 		    (tp->t_flags & TF_REQ_SCALE)) {
1073 			tp->t_flags |= TF_RCVD_SCALE;
1074 			tp->snd_scale = to.to_wscale;
1075 		}
1076 		/*
1077 		 * Initial send window.  It will be updated with
1078 		 * the next incoming segment to the scaled value.
1079 		 */
1080 		tp->snd_wnd = th->th_win;
1081 		if (to.to_flags & TOF_TS) {
1082 			tp->t_flags |= TF_RCVD_TSTMP;
1083 			tp->ts_recent = to.to_tsval;
1084 			tp->ts_recent_age = tcp_ts_getticks();
1085 		}
1086 		if (to.to_flags & TOF_MSS)
1087 			tcp_mss(tp, to.to_mss);
1088 		if ((tp->t_flags & TF_SACK_PERMIT) &&
1089 		    (to.to_flags & TOF_SACKPERM) == 0)
1090 			tp->t_flags &= ~TF_SACK_PERMIT;
1091 	}
1092 	/*
1093 	 * Header prediction: check for the two common cases
1094 	 * of a uni-directional data xfer.  If the packet has
1095 	 * no control flags, is in-sequence, the window didn't
1096 	 * change and we're not retransmitting, it's a
1097 	 * candidate.  If the length is zero and the ack moved
1098 	 * forward, we're the sender side of the xfer.  Just
1099 	 * free the data acked & wake any higher level process
1100 	 * that was blocked waiting for space.  If the length
1101 	 * is non-zero and the ack didn't move, we're the
1102 	 * receiver side.  If we're getting packets in-order
1103 	 * (the reassembly queue is empty), add the data to
1104 	 * the socket buffer and note that we need a delayed ack.
1105 	 * Make sure that the hidden state-flags are also off.
1106 	 * Since we check for TCPS_ESTABLISHED first, it can only
1107 	 * be TH_NEEDSYN.
1108 	 */
1109 	/*
1110 	 * samkumar: Replaced LIST_EMPTY(&tp->tsegq with the call to bmp_isempty).
1111 	 */
1112 	if (tp->t_state == TCPS_ESTABLISHED &&
1113 	    th->th_seq == tp->rcv_nxt &&
1114 	    (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1115 	    tp->snd_nxt == tp->snd_max &&
1116 	    tiwin && tiwin == tp->snd_wnd &&
1117 	    ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1118 	    bmp_isempty(tp->reassbmp, REASSBMP_SIZE(tp)) &&
1119 	    ((to.to_flags & TOF_TS) == 0 ||
1120 	     TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1121 
1122 		/*
1123 		 * If last ACK falls within this segment's sequence numbers,
1124 		 * record the timestamp.
1125 		 * NOTE that the test is modified according to the latest
1126 		 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1127 		 */
1128 		if ((to.to_flags & TOF_TS) != 0 &&
1129 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1130 			tp->ts_recent_age = tcp_ts_getticks();
1131 			tp->ts_recent = to.to_tsval;
1132 		}
1133 
1134 		if (tlen == 0) {
1135 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1136 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1137 			    !IN_RECOVERY(tp->t_flags) &&
1138 			    (to.to_flags & TOF_SACK) == 0 &&
1139 			    TAILQ_EMPTY(&tp->snd_holes)) {
1140 				/*
1141 				 * This is a pure ack for outstanding data.
1142 				 */
1143 
1144 				/*
1145 				 * "bad retransmit" recovery.
1146 				 */
1147 				if (tp->t_rxtshift == 1 &&
1148 				    tp->t_flags & TF_PREVVALID &&
1149 				    (int)(ticks - tp->t_badrxtwin) < 0) {
1150 					cc_cong_signal(tp, th, CC_RTO_ERR);
1151 				}
1152 
1153 				/*
1154 				 * Recalculate the transmit timer / rtt.
1155 				 *
1156 				 * Some boxes send broken timestamp replies
1157 				 * during the SYN+ACK phase, ignore
1158 				 * timestamps of 0 or we could calculate a
1159 				 * huge RTT and blow up the retransmit timer.
1160 				 */
1161 
1162 				if ((to.to_flags & TOF_TS) != 0 &&
1163 				    to.to_tsecr) {
1164 					uint32_t t;
1165 
1166 					t = tcp_ts_getticks() - to.to_tsecr;
1167 					if (!tp->t_rttlow || tp->t_rttlow > t)
1168 						tp->t_rttlow = t;
1169 					tcp_xmit_timer(tp,
1170 					    TCP_TS_TO_TICKS(t) + 1);
1171 				} else if (tp->t_rtttime &&
1172 				    SEQ_GT(th->th_ack, tp->t_rtseq)) {
1173 					if (!tp->t_rttlow ||
1174 					    tp->t_rttlow > ticks - tp->t_rtttime)
1175 						tp->t_rttlow = ticks - tp->t_rtttime;
1176 					tcp_xmit_timer(tp,
1177 							ticks - tp->t_rtttime);
1178 				}
1179 
1180 				acked = BYTES_THIS_ACK(tp, th);
1181 
1182 				/*
1183 				 * samkumar: Replaced sbdrop(&so->so_snd, acked) with this call
1184 				 * to lbuf_pop.
1185 				 */
1186 				{
1187 					uint32_t poppedbytes = lbuf_pop(&tp->sendbuf, acked, &sig->links_popped);
1188 					KASSERT(poppedbytes == acked, ("More bytes were acked than are in the send buffer"));
1189 					sig->bytes_acked += poppedbytes;
1190 				}
1191 				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1192 				    SEQ_LEQ(th->th_ack, tp->snd_recover))
1193 					tp->snd_recover = th->th_ack - 1;
1194 
1195 				/*
1196 				 * Let the congestion control algorithm update
1197 				 * congestion control related information. This
1198 				 * typically means increasing the congestion
1199 				 * window.
1200 				 */
1201 				cc_ack_received(tp, th, CC_ACK);
1202 
1203 				tp->snd_una = th->th_ack;
1204 				/*
1205 				 * Pull snd_wl2 up to prevent seq wrap relative
1206 				 * to th_ack.
1207 				 */
1208 				tp->snd_wl2 = th->th_ack;
1209 				tp->t_dupacks = 0;
1210 
1211 				/*
1212 				 * If all outstanding data are acked, stop
1213 				 * retransmit timer, otherwise restart timer
1214 				 * using current (possibly backed-off) value.
1215 				 * If process is waiting for space,
1216 				 * wakeup/selwakeup/signal.  If data
1217 				 * are ready to send, let tcp_output
1218 				 * decide between more output or persist.
1219 				 */
1220 
1221 				if (tp->snd_una == tp->snd_max)
1222 					tcp_timer_activate(tp, TT_REXMT, 0);
1223 				else if (!tcp_timer_active(tp, TT_PERSIST))
1224 					tcp_timer_activate(tp, TT_REXMT,
1225 						      tp->t_rxtcur);
1226 
1227 				/*
1228 				 * samkumar: There used to be a call to sowwakeup(so); here,
1229 				 * which wakes up any threads waiting for the socket to
1230 				 * become ready for writing. TCPlp handles its send buffer
1231 				 * differently so we do not need to replace this call with
1232 				 * specialized code to handle this.
1233 				 */
1234 
1235 				/*
1236 				 * samkumar: Replaced sbavail(&so->so_snd) with this call to
1237 				 * lbuf_used_space.
1238 				 */
1239 				if (lbuf_used_space(&tp->sendbuf))
1240 					(void) tcp_output(tp);
1241 				goto check_delack;
1242 			}
1243 		} else if (th->th_ack == tp->snd_una &&
1244 			/*
1245 			 * samkumar: Replaced sbspace(&so->so_rcv) with this call to
1246 			 * cbuf_free_space.
1247 			 */
1248 		    tlen <= cbuf_free_space(&tp->recvbuf)) {
1249 
1250 			/*
1251 			 * This is a pure, in-sequence data packet with
1252 			 * nothing on the reassembly queue and we have enough
1253 			 * buffer space to take it.
1254 			 */
1255 			/* Clean receiver SACK report if present */
1256 			if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1257 				tcp_clean_sackreport(tp);
1258 
1259 			tp->rcv_nxt += tlen;
1260 			/*
1261 			 * Pull snd_wl1 up to prevent seq wrap relative to
1262 			 * th_seq.
1263 			 */
1264 			tp->snd_wl1 = th->th_seq;
1265 			/*
1266 			 * Pull rcv_up up to prevent seq wrap relative to
1267 			 * rcv_nxt.
1268 			 */
1269 			tp->rcv_up = tp->rcv_nxt;
1270 
1271 		/*
1272 		 * Automatic sizing of receive socket buffer.  Often the send
1273 		 * buffer size is not optimally adjusted to the actual network
1274 		 * conditions at hand (delay bandwidth product).  Setting the
1275 		 * buffer size too small limits throughput on links with high
1276 		 * bandwidth and high delay (eg. trans-continental/oceanic links).
1277 		 *
1278 		 * On the receive side the socket buffer memory is only rarely
1279 		 * used to any significant extent.  This allows us to be much
1280 		 * more aggressive in scaling the receive socket buffer.  For
1281 		 * the case that the buffer space is actually used to a large
1282 		 * extent and we run out of kernel memory we can simply drop
1283 		 * the new segments; TCP on the sender will just retransmit it
1284 		 * later.  Setting the buffer size too big may only consume too
1285 		 * much kernel memory if the application doesn't read() from
1286 		 * the socket or packet loss or reordering makes use of the
1287 		 * reassembly queue.
1288 		 *
1289 		 * The criteria to step up the receive buffer one notch are:
1290 		 *  1. Application has not set receive buffer size with
1291 		 *     SO_RCVBUF. Setting SO_RCVBUF clears SB_AUTOSIZE.
1292 		 *  2. the number of bytes received during the time it takes
1293 		 *     one timestamp to be reflected back to us (the RTT);
1294 		 *  3. received bytes per RTT is within seven eighth of the
1295 		 *     current socket buffer size;
1296 		 *  4. receive buffer size has not hit maximal automatic size;
1297 		 *
1298 		 * This algorithm does one step per RTT at most and only if
1299 		 * we receive a bulk stream w/o packet losses or reorderings.
1300 		 * Shrinking the buffer during idle times is not necessary as
1301 		 * it doesn't consume any memory when idle.
1302 		 *
1303 		 * TODO: Only step up if the application is actually serving
1304 		 * the buffer to better manage the socket buffer resources.
1305 		 */
1306 
1307 			/*
1308 			 * samkumar: There used to be code here to dynamically size the
1309 			 * receive buffer (tp->rfbuf_ts, rp->rfbuf_cnt, and the local
1310 			 * newsize variable). In TCPlp, we don't support this, as the user
1311 			 * allocates the receive buffer and its size can't be changed here.
1312 			 * Therefore, I removed the code that does this. Note that the
1313 			 * actual resizing of the buffer is done using sbreserve_locked,
1314 			 * whose call comes later (not exactly where this comment is).
1315 			 */
1316 
1317 			/* Add data to socket buffer. */
1318 
1319 			/*
1320 			 * samkumar: The code that was here would just free the mbuf
1321 			 * (with m_freem(m)) if SBS_CANTRCVMORE is set in
1322 			 * so->so_rcv.sb_state. Otherwise, it would cut drop_hdrlen bytes
1323 			 * from the mbuf (using m_adj(m, drop_hdrlen)) to discard the
1324 			 * headers and then append the mbuf to the receive buffer using
1325 			 * sbappendstream_locked(&so->so_rcv, m, 0). I've rewritten this
1326 			 * to work the TCPlp way. The check to so->so_rcv.sb_state is
1327 			 * replaced by a tcpiscantrcv call, and we copy bytes into
1328 			 * TCPlp's circular buffer (since we designed it to avoid
1329 			 * having dynamically-allocated memory for the receive buffer).
1330 			 */
1331 
1332 			if (!tpiscantrcv(tp)) {
1333 				cbuf_write(&tp->recvbuf, msg, otMessageGetOffset(msg) + drop_hdrlen, tlen, cbuf_copy_from_message);
1334 				if (tlen > 0) {
1335 					sig->recvbuf_added = true;
1336 				}
1337 			} else {
1338 				/*
1339 				 * samkumar: We already know tlen != 0, so if we got here, then
1340 				 * it means that we got data after we called SHUT_RD, or after
1341 				 * receiving a FIN. I'm going to drop the connection in this
1342 				 * case. I think FreeBSD might have just dropped the packet
1343 				 * silently, but Linux handles it this way; this seems to be
1344 				 * the right approach to me.
1345 				 */
1346 				tcp_drop(tp, ECONNABORTED);
1347 				goto drop;
1348 			}
1349 			/* NB: sorwakeup_locked() does an implicit unlock. */
1350 			/*
1351 			 * samkumar: There used to be a call to sorwakeup_locked(so); here,
1352 			 * which wakes up any threads waiting for the socket to become
1353 			 * become ready for reading. TCPlp handles its buffering
1354 			 * differently so we do not need to replace this call with
1355 			 * specialized code to handle this.
1356 			 */
1357 			if (DELAY_ACK(tp, tlen)) {
1358 				tp->t_flags |= TF_DELACK;
1359 			} else {
1360 				tp->t_flags |= TF_ACKNOW;
1361 				tcp_output(tp);
1362 			}
1363 			goto check_delack;
1364 		}
1365 	}
1366 
1367 	/*
1368 	 * Calculate amount of space in receive window,
1369 	 * and then do TCP input processing.
1370 	 * Receive window is amount of space in rcv queue,
1371 	 * but not less than advertised window.
1372 	 */
1373 	/* samkumar: Replaced sbspace(&so->so_rcv) with call to cbuf_free_space. */
1374 	win = cbuf_free_space(&tp->recvbuf);
1375 	if (win < 0)
1376 		win = 0;
1377 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1378 
1379 	/* Reset receive buffer auto scaling when not in bulk receive mode. */
1380 	/* samkumar: Removed this receive buffer autoscaling code. */
1381 
1382 	switch (tp->t_state) {
1383 
1384 	/*
1385 	 * If the state is SYN_RECEIVED:
1386 	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1387 	 *  (Added by Sam) if seg is resending the original SYN, resend the SYN/ACK
1388 	 */
1389 	/*
1390 	 * samkumar: If we receive a retransmission of the original SYN, then
1391 	 * resend the SYN/ACK segment. This case was probably handled by the
1392 	 * SYN cache. Because TCPlp does not use a SYN cache, we need to write
1393 	 * custom logic for it. It is handled in the "else if" clause below.
1394 	 */
1395 	case TCPS_SYN_RECEIVED:
1396 		if ((thflags & TH_ACK) &&
1397 		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1398 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1399 				rstreason = BANDLIM_RST_OPENPORT;
1400 				goto dropwithreset;
1401 		} else if ((thflags & TH_SYN) && !(thflags & TH_ACK) && (th->th_seq == tp->irs)) {
1402 			tp->t_flags |= TF_ACKNOW;
1403 		}
1404 		break;
1405 
1406 	/*
1407 	 * If the state is SYN_SENT:
1408 	 *	if seg contains an ACK, but not for our SYN, drop the input.
1409 	 *	if seg contains a RST, then drop the connection.
1410 	 *	if seg does not contain SYN, then drop it.
1411 	 * Otherwise this is an acceptable SYN segment
1412 	 *	initialize tp->rcv_nxt and tp->irs
1413 	 *	if seg contains ack then advance tp->snd_una
1414 	 *	if seg contains an ECE and ECN support is enabled, the stream
1415 	 *	    is ECN capable.
1416 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1417 	 *	arrange for segment to be acked (eventually)
1418 	 *	continue processing rest of data/controls, beginning with URG
1419 	 */
1420 	case TCPS_SYN_SENT:
1421 		if ((thflags & TH_ACK) &&
1422 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1423 		     SEQ_GT(th->th_ack, tp->snd_max))) {
1424 			rstreason = BANDLIM_UNLIMITED;
1425 			goto dropwithreset;
1426 		}
1427 		if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
1428 			tp = tcp_drop(tp, ECONNREFUSED);
1429 		}
1430 		if (thflags & TH_RST)
1431 			goto drop;
1432 		if (!(thflags & TH_SYN))
1433 			goto drop;
1434 
1435 		tp->irs = th->th_seq;
1436 		tcp_rcvseqinit(tp);
1437 		if (thflags & TH_ACK) {
1438 			/*
1439 			 * samkumar: Removed call to soisconnected(so), since TCPlp has its
1440 			 * own buffering.
1441 			 */
1442 
1443 			/* Do window scaling on this connection? */
1444 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1445 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1446 				tp->rcv_scale = tp->request_r_scale;
1447 			}
1448 			tp->rcv_adv += imin(tp->rcv_wnd,
1449 			    TCP_MAXWIN << tp->rcv_scale);
1450 			tp->snd_una++;		/* SYN is acked */
1451 			/*
1452 			 * If there's data, delay ACK; if there's also a FIN
1453 			 * ACKNOW will be turned on later.
1454 			 */
1455 			if (DELAY_ACK(tp, tlen) && tlen != 0)
1456 				tcp_timer_activate(tp, TT_DELACK,
1457 				    tcp_delacktime);
1458 			else
1459 				tp->t_flags |= TF_ACKNOW;
1460 
1461 			if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1462 				tp->t_flags |= TF_ECN_PERMIT;
1463 			}
1464 
1465 			/*
1466 			 * Received <SYN,ACK> in SYN_SENT[*] state.
1467 			 * Transitions:
1468 			 *	SYN_SENT  --> ESTABLISHED
1469 			 *	SYN_SENT* --> FIN_WAIT_1
1470 			 */
1471 			tp->t_starttime = ticks;
1472 			if (tp->t_flags & TF_NEEDFIN) {
1473 				tcp_state_change(tp, TCPS_FIN_WAIT_1);
1474 				tp->t_flags &= ~TF_NEEDFIN;
1475 				thflags &= ~TH_SYN;
1476 			} else {
1477 				tcp_state_change(tp, TCPS_ESTABLISHED);
1478 				/* samkumar: Set conn_established signal for TCPlp. */
1479 				sig->conn_established = true;
1480 				cc_conn_init(tp);
1481 				tcp_timer_activate(tp, TT_KEEP,
1482 				    TP_KEEPIDLE(tp));
1483 			}
1484 		} else {
1485 			/*
1486 			 * Received initial SYN in SYN-SENT[*] state =>
1487 			 * simultaneous open.
1488 			 * If it succeeds, connection is * half-synchronized.
1489 			 * Otherwise, do 3-way handshake:
1490 			 *        SYN-SENT -> SYN-RECEIVED
1491 			 *        SYN-SENT* -> SYN-RECEIVED*
1492 			 */
1493 			tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1494 			tcp_timer_activate(tp, TT_REXMT, 0);
1495 			tcp_state_change(tp, TCPS_SYN_RECEIVED);
1496 			/*
1497 			 * samkumar: We would have incremented snd_next in tcp_output when
1498 			 * we sent the original SYN, so decrement it here. (Another
1499 			 * consequence of removing the SYN cache.)
1500 			 */
1501 			tp->snd_nxt--;
1502 		}
1503 
1504 		/*
1505 		 * Advance th->th_seq to correspond to first data byte.
1506 		 * If data, trim to stay within window,
1507 		 * dropping FIN if necessary.
1508 		 */
1509 		th->th_seq++;
1510 		if (tlen > tp->rcv_wnd) {
1511 			todrop = tlen - tp->rcv_wnd;
1512 			/*
1513 			 * samkumar: I removed a call to m_adj(m, -todrop), which intends
1514 			 * to trim the data so it fits in the window. We can just read less
1515 			 * when copying into the receive buffer in TCPlp, so we don't need
1516 			 * to do this.
1517 			 */
1518 			(void) todrop; /* samkumar: Prevent a compiler warning */
1519 			tlen = tp->rcv_wnd;
1520 			thflags &= ~TH_FIN;
1521 		}
1522 		tp->snd_wl1 = th->th_seq - 1;
1523 		tp->rcv_up = th->th_seq;
1524 		/*
1525 		 * Client side of transaction: already sent SYN and data.
1526 		 * If the remote host used T/TCP to validate the SYN,
1527 		 * our data will be ACK'd; if so, enter normal data segment
1528 		 * processing in the middle of step 5, ack processing.
1529 		 * Otherwise, goto step 6.
1530 		 */
1531 		if (thflags & TH_ACK)
1532 			goto process_ACK;
1533 
1534 		goto step6;
1535 
1536 	/*
1537 	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1538 	 *      do normal processing.
1539 	 *
1540 	 * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
1541 	 */
1542 	case TCPS_LAST_ACK:
1543 	case TCPS_CLOSING:
1544 		break;  /* continue normal processing */
1545 	}
1546 
1547 	/*
1548 	 * States other than LISTEN or SYN_SENT.
1549 	 * First check the RST flag and sequence number since reset segments
1550 	 * are exempt from the timestamp and connection count tests.  This
1551 	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1552 	 * below which allowed reset segments in half the sequence space
1553 	 * to fall though and be processed (which gives forged reset
1554 	 * segments with a random sequence number a 50 percent chance of
1555 	 * killing a connection).
1556 	 * Then check timestamp, if present.
1557 	 * Then check the connection count, if present.
1558 	 * Then check that at least some bytes of segment are within
1559 	 * receive window.  If segment begins before rcv_nxt,
1560 	 * drop leading data (and SYN); if nothing left, just ack.
1561 	 */
1562 	if (thflags & TH_RST) {
1563 		/*
1564 		 * RFC5961 Section 3.2
1565 		 *
1566 		 * - RST drops connection only if SEG.SEQ == RCV.NXT.
1567 		 * - If RST is in window, we send challenge ACK.
1568 		 *
1569 		 * Note: to take into account delayed ACKs, we should
1570 		 *   test against last_ack_sent instead of rcv_nxt.
1571 		 * Note 2: we handle special case of closed window, not
1572 		 *   covered by the RFC.
1573 		 */
1574 		if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1575 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
1576 		    (tp->rcv_wnd == 0 && tp->last_ack_sent == th->th_seq)) {
1577 
1578 			/*
1579 			 * samkumar: This if statement used to also be prefaced with
1580 			 * "V_tcp_insecure_rst ||". But I removed it, since there's no
1581 			 * reason to support an insecure option in TCPlp (my guess is that
1582 			 * FreeBSD supported it for legacy reasons).
1583 			 */
1584 			if (tp->last_ack_sent == th->th_seq) {
1585 				/*
1586 				 * samkumar: Normally, the error number would be stored in
1587 				 * so->so_error. Instead, we put it in this "droperror" local
1588 				 * variable and then pass it to tcplp_sys_connection_lost.
1589 				 */
1590 				int droperror = 0;
1591 				/* Drop the connection. */
1592 				switch (tp->t_state) {
1593 				case TCPS_SYN_RECEIVED:
1594 					droperror = ECONNREFUSED;
1595 					goto close;
1596 				case TCPS_ESTABLISHED:
1597 				case TCPS_FIN_WAIT_1:
1598 				case TCPS_FIN_WAIT_2:
1599 				case TCPS_CLOSE_WAIT:
1600 					droperror = ECONNRESET;
1601 				close:
1602 					tcp_state_change(tp, TCPS_CLOSED);
1603 					/* FALLTHROUGH */
1604 				default:
1605 					tp = tcp_close(tp);
1606 					tcplp_sys_connection_lost(tp, droperror);
1607 				}
1608 			} else {
1609 				/* Send challenge ACK. */
1610 				tcp_respond(tp, tp->instance, ip6, th, tp->rcv_nxt, tp->snd_nxt, TH_ACK);
1611 				tp->last_ack_sent = tp->rcv_nxt;
1612 			}
1613 		}
1614 		goto drop;
1615 	}
1616 
1617 	/*
1618 	 * RFC5961 Section 4.2
1619 	 * Send challenge ACK for any SYN in synchronized state.
1620 	 */
1621 	/*
1622 	 * samkumar: I added the check for the SYN-RECEIVED state in this if
1623 	 * statement (another consequence of removing the SYN cache).
1624 	 */
1625 	if ((thflags & TH_SYN) && tp->t_state != TCPS_SYN_SENT && tp->t_state != TCP6S_SYN_RECEIVED) {
1626 		/*
1627 		 * samkumar: The modern way to handle this is to send a Challenge ACK.
1628 		 * FreeBSD supports this, but it also has this V_tcp_insecure_syn
1629 		 * options that will cause it to drop the connection if the SYN falls
1630 		 * in the receive window. In TCPlp we *only* support Challenge ACKs
1631 		 * (the secure way of doing it), so I've removed code for the insecure
1632 		 * way. (Presumably the reason why FreeBSD supports the insecure way is
1633 		 * for legacy code, which we don't really care about in TCPlp).
1634 		 */
1635 		/* Send challenge ACK. */
1636 		tcplp_sys_log("Sending challenge ACK");
1637 		tcp_respond(tp, tp->instance, ip6, th, tp->rcv_nxt, tp->snd_nxt, TH_ACK);
1638 		tp->last_ack_sent = tp->rcv_nxt;
1639 		goto drop;
1640 	}
1641 
1642 	/*
1643 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1644 	 * and it's less than ts_recent, drop it.
1645 	 */
1646 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1647 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1648 
1649 		/* Check to see if ts_recent is over 24 days old.  */
1650 		if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
1651 			/*
1652 			 * Invalidate ts_recent.  If this segment updates
1653 			 * ts_recent, the age will be reset later and ts_recent
1654 			 * will get a valid value.  If it does not, setting
1655 			 * ts_recent to zero will at least satisfy the
1656 			 * requirement that zero be placed in the timestamp
1657 			 * echo reply when ts_recent isn't valid.  The
1658 			 * age isn't reset until we get a valid ts_recent
1659 			 * because we don't want out-of-order segments to be
1660 			 * dropped when ts_recent is old.
1661 			 */
1662 			tp->ts_recent = 0;
1663 		} else {
1664 			if (tlen)
1665 				goto dropafterack;
1666 			goto drop;
1667 		}
1668 	}
1669 
1670 	/*
1671 	 * In the SYN-RECEIVED state, validate that the packet belongs to
1672 	 * this connection before trimming the data to fit the receive
1673 	 * window.  Check the sequence number versus IRS since we know
1674 	 * the sequence numbers haven't wrapped.  This is a partial fix
1675 	 * for the "LAND" DoS attack.
1676 	 */
1677 	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1678 		rstreason = BANDLIM_RST_OPENPORT;
1679 		goto dropwithreset;
1680 	}
1681 
1682 	todrop = tp->rcv_nxt - th->th_seq;
1683 	if (todrop > 0) {
1684 		if (thflags & TH_SYN) {
1685 			thflags &= ~TH_SYN;
1686 			th->th_seq++;
1687 			if (th->th_urp > 1)
1688 				th->th_urp--;
1689 			else
1690 				thflags &= ~TH_URG;
1691 			todrop--;
1692 		}
1693 		/*
1694 		 * Following if statement from Stevens, vol. 2, p. 960.
1695 		 */
1696 		if (todrop > tlen
1697 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1698 			/*
1699 			 * Any valid FIN must be to the left of the window.
1700 			 * At this point the FIN must be a duplicate or out
1701 			 * of sequence; drop it.
1702 			 */
1703 			thflags &= ~TH_FIN;
1704 
1705 			/*
1706 			 * Send an ACK to resynchronize and drop any data.
1707 			 * But keep on processing for RST or ACK.
1708 			 */
1709 			tp->t_flags |= TF_ACKNOW;
1710 			todrop = tlen;
1711 		}
1712 		/* samkumar: There was an else case that only collected stats. */
1713 		drop_hdrlen += todrop;	/* drop from the top afterwards */
1714 		th->th_seq += todrop;
1715 		tlen -= todrop;
1716 		if (th->th_urp > todrop)
1717 			th->th_urp -= todrop;
1718 		else {
1719 			thflags &= ~TH_URG;
1720 			th->th_urp = 0;
1721 		}
1722 	}
1723 
1724 	/*
1725 	 * If new data are received on a connection after the
1726 	 * user processes are gone, then RST the other end.
1727 	 */
1728 	/*
1729 	 * samkumar: TCPlp is designed for embedded systems where there is no
1730 	 * concept of a "process" that has allocated a TCP socket. Therefore, we
1731 	 * do not implement the functionality in the above comment (the code for
1732 	 * it used to be here, and I removed it).
1733 	 */
1734 	/*
1735 	 * If segment ends after window, drop trailing data
1736 	 * (and PUSH and FIN); if nothing left, just ACK.
1737 	 */
1738 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1739 	if (todrop > 0) {
1740 		if (todrop >= tlen) {
1741 			/*
1742 			 * If window is closed can only take segments at
1743 			 * window edge, and have to drop data and PUSH from
1744 			 * incoming segments.  Continue processing, but
1745 			 * remember to ack.  Otherwise, drop segment
1746 			 * and ack.
1747 			 */
1748 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1749 				tp->t_flags |= TF_ACKNOW;
1750 			} else
1751 				goto dropafterack;
1752 		}
1753 		/*
1754 		 * samkumar: I removed a call to m_adj(m, -todrop), which intends
1755 		 * to trim the data so it fits in the window. We can just read less
1756 		 * when copying into the receive buffer in TCPlp, so we don't need
1757 		 * to do this. Subtracting it from tlen gives us enough information to
1758 		 * do this later. In FreeBSD, this isn't possible because the mbuf
1759 		 * itself becomes part of the receive buffer, so the mbuf has to be
1760 		 * trimmed in order for this to work out.
1761 		 */
1762 		tlen -= todrop;
1763 		thflags &= ~(TH_PUSH|TH_FIN);
1764 	}
1765 
1766 	/*
1767 	 * If last ACK falls within this segment's sequence numbers,
1768 	 * record its timestamp.
1769 	 * NOTE:
1770 	 * 1) That the test incorporates suggestions from the latest
1771 	 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
1772 	 * 2) That updating only on newer timestamps interferes with
1773 	 *    our earlier PAWS tests, so this check should be solely
1774 	 *    predicated on the sequence space of this segment.
1775 	 * 3) That we modify the segment boundary check to be
1776 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
1777 	 *    instead of RFC1323's
1778 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
1779 	 *    This modified check allows us to overcome RFC1323's
1780 	 *    limitations as described in Stevens TCP/IP Illustrated
1781 	 *    Vol. 2 p.869. In such cases, we can still calculate the
1782 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
1783 	 */
1784 
1785 	if ((to.to_flags & TOF_TS) != 0 &&
1786 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1787 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1788 		((thflags & (TH_SYN|TH_FIN)) != 0))) {
1789 		tp->ts_recent_age = tcp_ts_getticks();
1790 		tp->ts_recent = to.to_tsval;
1791 	}
1792 
1793 	/*
1794 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1795 	 * flag is on (half-synchronized state), then queue data for
1796 	 * later processing; else drop segment and return.
1797 	 */
1798 	if ((thflags & TH_ACK) == 0) {
1799 		if (tp->t_state == TCPS_SYN_RECEIVED ||
1800 		    (tp->t_flags & TF_NEEDSYN))
1801 			goto step6;
1802 		else if (tp->t_flags & TF_ACKNOW)
1803 			goto dropafterack;
1804 		else
1805 			goto drop;
1806 	}
1807 
1808 	tcplp_sys_log("Processing ACK");
1809 
1810 	/*
1811 	 * Ack processing.
1812 	 */
1813 	switch (tp->t_state) {
1814 
1815 	/*
1816 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1817 	 * ESTABLISHED state and continue processing.
1818 	 * The ACK was checked above.
1819 	 */
1820 	case TCPS_SYN_RECEIVED:
1821 		/*
1822 		 * samkumar: Removed call to soisconnected(so), since TCPlp has its
1823 		 * own buffering.
1824 		 */
1825 		/* Do window scaling? */
1826 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1827 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1828 			tp->rcv_scale = tp->request_r_scale;
1829 			tp->snd_wnd = tiwin;
1830 		}
1831 		/*
1832 		 * Make transitions:
1833 		 *      SYN-RECEIVED  -> ESTABLISHED
1834 		 *      SYN-RECEIVED* -> FIN-WAIT-1
1835 		 */
1836 		tp->t_starttime = ticks;
1837 		if (tp->t_flags & TF_NEEDFIN) {
1838 			tcp_state_change(tp, TCPS_FIN_WAIT_1);
1839 			tp->t_flags &= ~TF_NEEDFIN;
1840 		} else {
1841 			tcp_state_change(tp, TCPS_ESTABLISHED);
1842 			/* samkumar: Set conn_established signal for TCPlp. */
1843 			sig->conn_established = true;
1844 			cc_conn_init(tp);
1845 			tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1846 			/*
1847 			 * samkumar: I added this check to account for simultaneous open.
1848 			 * If this socket was opened actively, then the fact that we are
1849 			 * in SYN-RECEIVED indicates that we are in simultaneous open.
1850 			 * Therefore, don't ACK the SYN-ACK (unless it contains data or
1851 			 * something, which will be processed later).
1852 			 */
1853 			if (!tpispassiveopen(tp)) {
1854 				tp->t_flags &= ~TF_ACKNOW;
1855 			} else {
1856 				/*
1857 				 * samkumar: Otherwise, we entered the ESTABLISHED state by
1858 				 * accepting a connection, so call the appropriate callback in
1859 				 * TCPlp. TODO: consider using signals to handle this?
1860 				 */
1861 				 bool accepted = tcplp_sys_accepted_connection(tp->accepted_from, tp, &ip6->ip6_src, th->th_sport);
1862 				 if (!accepted) {
1863 					 rstreason = ECONNREFUSED;
1864 					 goto dropwithreset;
1865 				 }
1866 			 }
1867 		}
1868 		/*
1869 		 * If segment contains data or ACK, will call tcp_reass()
1870 		 * later; if not, do so now to pass queued data to user.
1871 		 */
1872 		if (tlen == 0 && (thflags & TH_FIN) == 0)
1873 			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1874 			    (otMessage*)0, 0, sig);
1875 
1876 		tp->snd_wl1 = th->th_seq - 1;
1877 		/* FALLTHROUGH */
1878 
1879 	/*
1880 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1881 	 * ACKs.  If the ack is in the range
1882 	 *	tp->snd_una < th->th_ack <= tp->snd_max
1883 	 * then advance tp->snd_una to th->th_ack and drop
1884 	 * data from the retransmission queue.  If this ACK reflects
1885 	 * more up to date window information we update our window information.
1886 	 */
1887 	case TCPS_ESTABLISHED:
1888 	case TCPS_FIN_WAIT_1:
1889 	case TCPS_FIN_WAIT_2:
1890 	case TCPS_CLOSE_WAIT:
1891 	case TCPS_CLOSING:
1892 	case TCPS_LAST_ACK:
1893 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1894 			goto dropafterack;
1895 		}
1896 
1897 		if ((tp->t_flags & TF_SACK_PERMIT) &&
1898 		    ((to.to_flags & TOF_SACK) ||
1899 		     !TAILQ_EMPTY(&tp->snd_holes)))
1900 			tcp_sack_doack(tp, &to, th->th_ack);
1901 
1902 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1903 			if (tlen == 0 && tiwin == tp->snd_wnd) {
1904 				/*
1905 				 * If this is the first time we've seen a
1906 				 * FIN from the remote, this is not a
1907 				 * duplicate and it needs to be processed
1908 				 * normally.  This happens during a
1909 				 * simultaneous close.
1910 				 */
1911 				if ((thflags & TH_FIN) &&
1912 				    (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
1913 					tp->t_dupacks = 0;
1914 					break;
1915 				}
1916 				/*
1917 				 * If we have outstanding data (other than
1918 				 * a window probe), this is a completely
1919 				 * duplicate ack (ie, window info didn't
1920 				 * change and FIN isn't set),
1921 				 * the ack is the biggest we've
1922 				 * seen and we've seen exactly our rexmt
1923 				 * threshhold of them, assume a packet
1924 				 * has been dropped and retransmit it.
1925 				 * Kludge snd_nxt & the congestion
1926 				 * window so we send only this one
1927 				 * packet.
1928 				 *
1929 				 * We know we're losing at the current
1930 				 * window size so do congestion avoidance
1931 				 * (set ssthresh to half the current window
1932 				 * and pull our congestion window back to
1933 				 * the new ssthresh).
1934 				 *
1935 				 * Dup acks mean that packets have left the
1936 				 * network (they're now cached at the receiver)
1937 				 * so bump cwnd by the amount in the receiver
1938 				 * to keep a constant cwnd packets in the
1939 				 * network.
1940 				 *
1941 				 * When using TCP ECN, notify the peer that
1942 				 * we reduced the cwnd.
1943 				 */
1944 				if (!tcp_timer_active(tp, TT_REXMT) ||
1945 				    th->th_ack != tp->snd_una)
1946 					tp->t_dupacks = 0;
1947 				else if (++tp->t_dupacks > tcprexmtthresh ||
1948 				     IN_FASTRECOVERY(tp->t_flags)) {
1949 					cc_ack_received(tp, th, CC_DUPACK);
1950 					if ((tp->t_flags & TF_SACK_PERMIT) &&
1951 					    IN_FASTRECOVERY(tp->t_flags)) {
1952 						int awnd;
1953 
1954 						/*
1955 						 * Compute the amount of data in flight first.
1956 						 * We can inject new data into the pipe iff
1957 						 * we have less than 1/2 the original window's
1958 						 * worth of data in flight.
1959 						 */
1960 						awnd = (tp->snd_nxt - tp->snd_fack) +
1961 							tp->sackhint.sack_bytes_rexmit;
1962 						if (awnd < tp->snd_ssthresh) {
1963 							tp->snd_cwnd += tp->t_maxseg;
1964 							if (tp->snd_cwnd > tp->snd_ssthresh)
1965 								tp->snd_cwnd = tp->snd_ssthresh;
1966 						}
1967 					} else
1968 						tp->snd_cwnd += tp->t_maxseg;
1969 #ifdef INSTRUMENT_TCP
1970 					tcplp_sys_log("TCP DUPACK");
1971 #endif
1972 					(void) tcp_output(tp);
1973 					goto drop;
1974 				} else if (tp->t_dupacks == tcprexmtthresh) {
1975 					tcp_seq onxt = tp->snd_nxt;
1976 
1977 					/*
1978 					 * If we're doing sack, check to
1979 					 * see if we're already in sack
1980 					 * recovery. If we're not doing sack,
1981 					 * check to see if we're in newreno
1982 					 * recovery.
1983 					 */
1984 					if (tp->t_flags & TF_SACK_PERMIT) {
1985 						if (IN_FASTRECOVERY(tp->t_flags)) {
1986 							tp->t_dupacks = 0;
1987 							break;
1988 						}
1989 					} else {
1990 						if (SEQ_LEQ(th->th_ack,
1991 						    tp->snd_recover)) {
1992 							tp->t_dupacks = 0;
1993 							break;
1994 						}
1995 					}
1996 					/* Congestion signal before ack. */
1997 					cc_cong_signal(tp, th, CC_NDUPACK);
1998 					cc_ack_received(tp, th, CC_DUPACK);
1999 					tcp_timer_activate(tp, TT_REXMT, 0);
2000 					tp->t_rtttime = 0;
2001 
2002 #ifdef INSTRUMENT_TCP
2003 					tcplp_sys_log("TCP DUPACK_THRESH");
2004 #endif
2005 					if (tp->t_flags & TF_SACK_PERMIT) {
2006 						tp->sack_newdata = tp->snd_nxt;
2007 						tp->snd_cwnd = tp->t_maxseg;
2008 						(void) tcp_output(tp);
2009 						goto drop;
2010 					}
2011 
2012 					tp->snd_nxt = th->th_ack;
2013 					tp->snd_cwnd = tp->t_maxseg;
2014 					(void) tcp_output(tp);
2015 					tp->snd_cwnd = tp->snd_ssthresh +
2016 					     tp->t_maxseg *
2017 					     (tp->t_dupacks - tp->snd_limited);
2018 #ifdef INSTRUMENT_TCP
2019 					tcplp_sys_log("TCP SET_cwnd %d", (int) tp->snd_cwnd);
2020 #endif
2021 					if (SEQ_GT(onxt, tp->snd_nxt))
2022 						tp->snd_nxt = onxt;
2023 					goto drop;
2024 				} else if (V_tcp_do_rfc3042) {
2025 					/*
2026 					 * Process first and second duplicate
2027 					 * ACKs. Each indicates a segment
2028 					 * leaving the network, creating room
2029 					 * for more. Make sure we can send a
2030 					 * packet on reception of each duplicate
2031 					 * ACK by increasing snd_cwnd by one
2032 					 * segment. Restore the original
2033 					 * snd_cwnd after packet transmission.
2034 					 */
2035 					uint64_t oldcwnd;
2036 					tcp_seq oldsndmax;
2037 					uint32_t sent;
2038 					int avail;
2039 					cc_ack_received(tp, th, CC_DUPACK);
2040 					oldcwnd = tp->snd_cwnd;
2041 					oldsndmax = tp->snd_max;
2042 
2043 #ifdef INSTRUMENT_TCP
2044 					tcplp_sys_log("TCP LIM_TRANS");
2045 #endif
2046 
2047 					KASSERT(tp->t_dupacks == 1 ||
2048 					    tp->t_dupacks == 2,
2049 					    ("%s: dupacks not 1 or 2",
2050 					    __func__));
2051 					if (tp->t_dupacks == 1)
2052 						tp->snd_limited = 0;
2053 					tp->snd_cwnd =
2054 					    (tp->snd_nxt - tp->snd_una) +
2055 					    (tp->t_dupacks - tp->snd_limited) *
2056 					    tp->t_maxseg;
2057 					/*
2058 					 * Only call tcp_output when there
2059 					 * is new data available to be sent.
2060 					 * Otherwise we would send pure ACKs.
2061 					 */
2062 					/*
2063 					 * samkumar: Replace sbavail(&so->so_snd) with the call to
2064 					 * lbuf_used_space.
2065 					 */
2066 					avail = lbuf_used_space(&tp->sendbuf) -
2067 					    (tp->snd_nxt - tp->snd_una);
2068 					if (avail > 0)
2069 						(void) tcp_output(tp);
2070 					sent = tp->snd_max - oldsndmax;
2071 					if (sent > tp->t_maxseg) {
2072 						KASSERT((tp->t_dupacks == 2 &&
2073 						    tp->snd_limited == 0) ||
2074 						   (sent == tp->t_maxseg + 1 &&
2075 						    tp->t_flags & TF_SENTFIN),
2076 						    ("%s: sent too much",
2077 						    __func__));
2078 						tp->snd_limited = 2;
2079 					} else if (sent > 0)
2080 						++tp->snd_limited;
2081 					tp->snd_cwnd = oldcwnd;
2082 #ifdef INSTRUMENT_TCP
2083 					tcplp_sys_log("TCP RESET_cwnd %d", (int) tp->snd_cwnd);
2084 #endif
2085 					goto drop;
2086 				}
2087 			} else
2088 				tp->t_dupacks = 0;
2089 			break;
2090 		}
2091 
2092 		KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2093 		    ("%s: th_ack <= snd_una", __func__));
2094 
2095 		/*
2096 		 * If the congestion window was inflated to account
2097 		 * for the other side's cached packets, retract it.
2098 		 */
2099 		if (IN_FASTRECOVERY(tp->t_flags)) {
2100 			if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2101 				if (tp->t_flags & TF_SACK_PERMIT)
2102 					tcp_sack_partialack(tp, th);
2103 				else
2104 					tcp_newreno_partial_ack(tp, th);
2105 			} else
2106 				cc_post_recovery(tp, th);
2107 		}
2108 
2109 		tp->t_dupacks = 0;
2110 		/*
2111 		 * If we reach this point, ACK is not a duplicate,
2112 		 *     i.e., it ACKs something we sent.
2113 		 */
2114 		if (tp->t_flags & TF_NEEDSYN) {
2115 			/*
2116 			 * T/TCP: Connection was half-synchronized, and our
2117 			 * SYN has been ACK'd (so connection is now fully
2118 			 * synchronized).  Go to non-starred state,
2119 			 * increment snd_una for ACK of SYN, and check if
2120 			 * we can do window scaling.
2121 			 */
2122 			tp->t_flags &= ~TF_NEEDSYN;
2123 			tp->snd_una++;
2124 			/* Do window scaling? */
2125 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2126 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
2127 				tp->rcv_scale = tp->request_r_scale;
2128 				/* Send window already scaled. */
2129 			}
2130 		}
2131 
2132 process_ACK:
2133 		acked = BYTES_THIS_ACK(tp, th);
2134 
2135 		tcplp_sys_log("Bytes acked: %d", acked);
2136 		/*
2137 		 * If we just performed our first retransmit, and the ACK
2138 		 * arrives within our recovery window, then it was a mistake
2139 		 * to do the retransmit in the first place.  Recover our
2140 		 * original cwnd and ssthresh, and proceed to transmit where
2141 		 * we left off.
2142 		 */
2143 		if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
2144 		    (int)(ticks - tp->t_badrxtwin) < 0)
2145 			cc_cong_signal(tp, th, CC_RTO_ERR);
2146 
2147 		/*
2148 		 * If we have a timestamp reply, update smoothed
2149 		 * round trip time.  If no timestamp is present but
2150 		 * transmit timer is running and timed sequence
2151 		 * number was acked, update smoothed round trip time.
2152 		 * Since we now have an rtt measurement, cancel the
2153 		 * timer backoff (cf., Phil Karn's retransmit alg.).
2154 		 * Recompute the initial retransmit timer.
2155 		 *
2156 		 * Some boxes send broken timestamp replies
2157 		 * during the SYN+ACK phase, ignore
2158 		 * timestamps of 0 or we could calculate a
2159 		 * huge RTT and blow up the retransmit timer.
2160 		 */
2161 
2162 		if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2163 			uint32_t t;
2164 
2165 			t = tcp_ts_getticks() - to.to_tsecr;
2166 			if (!tp->t_rttlow || tp->t_rttlow > t)
2167 				tp->t_rttlow = t;
2168 			tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2169 		} else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2170 			if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2171 				tp->t_rttlow = ticks - tp->t_rtttime;
2172 			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2173 		}
2174 
2175 		/*
2176 		 * If all outstanding data is acked, stop retransmit
2177 		 * timer and remember to restart (more output or persist).
2178 		 * If there is more data to be acked, restart retransmit
2179 		 * timer, using current (possibly backed-off) value.
2180 		 */
2181 		if (th->th_ack == tp->snd_max) {
2182 			tcp_timer_activate(tp, TT_REXMT, 0);
2183 			needoutput = 1;
2184 		} else if (!tcp_timer_active(tp, TT_PERSIST)) {
2185 			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2186 		}
2187 
2188 		/*
2189 		 * If no data (only SYN) was ACK'd,
2190 		 *    skip rest of ACK processing.
2191 		 */
2192 		if (acked == 0)
2193 			goto step6;
2194 
2195 		/*
2196 		 * Let the congestion control algorithm update congestion
2197 		 * control related information. This typically means increasing
2198 		 * the congestion window.
2199 		 */
2200 		cc_ack_received(tp, th, CC_ACK);
2201 
2202 		/*
2203 		 * samkumar: I replaced the calls to sbavail(&so->so_snd) with new
2204 		 * calls to lbuf_used_space, and then I modified the code to actually
2205 		 * remove code from the send buffer, formerly done via
2206 		 * sbcut_locked(&so->so_send, (int)sbavail(&so->so_snd)) in the if case
2207 		 * and sbcut_locked(&so->so_snd, acked) in the else case, to use the
2208 		 * data structures for TCPlp's data buffering.
2209 		 */
2210 		if (acked > lbuf_used_space(&tp->sendbuf)) {
2211 			uint32_t poppedbytes;
2212 			uint32_t usedspace = lbuf_used_space(&tp->sendbuf);
2213 			tp->snd_wnd -= usedspace;
2214 			poppedbytes = lbuf_pop(&tp->sendbuf, usedspace, &sig->links_popped);
2215 			KASSERT(poppedbytes == usedspace, ("Could not fully empty send buffer"));
2216 			sig->bytes_acked += poppedbytes;
2217 			ourfinisacked = 1;
2218 		} else {
2219 			uint32_t poppedbytes = lbuf_pop(&tp->sendbuf, acked, &sig->links_popped);
2220 			KASSERT(poppedbytes == acked, ("Could not remove acked bytes from send buffer"));
2221 			sig->bytes_acked += poppedbytes;
2222 			tp->snd_wnd -= acked;
2223 			ourfinisacked = 0;
2224 		}
2225 		/* NB: sowwakeup_locked() does an implicit unlock. */
2226 		/*
2227 		 * samkumar: There used to be a call to sowwakeup(so); here,
2228 		 * which wakes up any threads waiting for the socket to
2229 		 * become ready for writing. TCPlp handles its send buffer
2230 		 * differently so we do not need to replace this call with
2231 		 * specialized code to handle this.
2232 		 */
2233 		/* Detect una wraparound. */
2234 		if (!IN_RECOVERY(tp->t_flags) &&
2235 		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
2236 		    SEQ_LEQ(th->th_ack, tp->snd_recover))
2237 			tp->snd_recover = th->th_ack - 1;
2238 		/* XXXLAS: Can this be moved up into cc_post_recovery? */
2239 		if (IN_RECOVERY(tp->t_flags) &&
2240 		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2241 			EXIT_RECOVERY(tp->t_flags);
2242 		}
2243 		tp->snd_una = th->th_ack;
2244 		if (tp->t_flags & TF_SACK_PERMIT) {
2245 			if (SEQ_GT(tp->snd_una, tp->snd_recover))
2246 				tp->snd_recover = tp->snd_una;
2247 		}
2248 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2249 			tp->snd_nxt = tp->snd_una;
2250 
2251 		switch (tp->t_state) {
2252 
2253 		/*
2254 		 * In FIN_WAIT_1 STATE in addition to the processing
2255 		 * for the ESTABLISHED state if our FIN is now acknowledged
2256 		 * then enter FIN_WAIT_2.
2257 		 */
2258 		case TCPS_FIN_WAIT_1:
2259 			if (ourfinisacked) {
2260 				/*
2261 				 * If we can't receive any more
2262 				 * data, then closing user can proceed.
2263 				 * Starting the timer is contrary to the
2264 				 * specification, but if we don't get a FIN
2265 				 * we'll hang forever.
2266 				 *
2267 				 * XXXjl:
2268 				 * we should release the tp also, and use a
2269 				 * compressed state.
2270 				 */
2271 				/*
2272 				 * samkumar: I replaced a check for the SBS_CANTRCVMORE flag
2273 				 * in so->so_rcv.sb_state with a call to tcpiscantrcv.
2274 				 */
2275 				if (tpiscantrcv(tp)) {
2276 					/* samkumar: Removed a call to soisdisconnected(so). */
2277 					tcp_timer_activate(tp, TT_2MSL,
2278 					    (tcp_fast_finwait2_recycle ?
2279 					    tcp_finwait2_timeout :
2280 					    TP_MAXIDLE(tp)));
2281 				}
2282 				tcp_state_change(tp, TCPS_FIN_WAIT_2);
2283 			}
2284 			break;
2285 
2286 		/*
2287 		 * In CLOSING STATE in addition to the processing for
2288 		 * the ESTABLISHED state if the ACK acknowledges our FIN
2289 		 * then enter the TIME-WAIT state, otherwise ignore
2290 		 * the segment.
2291 		 */
2292 		case TCPS_CLOSING:
2293 			if (ourfinisacked) {
2294 				/*
2295 				 * samkumar: I added the line below. We need to avoid sending
2296 				 * an ACK in the TIME-WAIT state, since we don't want to
2297 				 * ACK ACKs. This edge case appears because TCPlp, unlike the
2298 				 * original FreeBSD code, uses tcpcbs for connections in the
2299 				 * TIME-WAIT state (FreeBSD uses a different, smaller
2300 				 * structure).
2301 				 */
2302 				tp->t_flags &= ~TF_ACKNOW;
2303 				tcp_twstart(tp);
2304 				return;
2305 			}
2306 			break;
2307 
2308 		/*
2309 		 * In LAST_ACK, we may still be waiting for data to drain
2310 		 * and/or to be acked, as well as for the ack of our FIN.
2311 		 * If our FIN is now acknowledged, delete the TCB,
2312 		 * enter the closed state and return.
2313 		 */
2314 		case TCPS_LAST_ACK:
2315 			if (ourfinisacked) {
2316 				tp = tcp_close(tp);
2317 				tcplp_sys_connection_lost(tp, CONN_LOST_NORMAL);
2318 				goto drop;
2319 			}
2320 			break;
2321 		}
2322 	}
2323 
2324 step6:
2325 
2326 	/*
2327 	 * Update window information.
2328 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2329 	 */
2330 	if ((thflags & TH_ACK) &&
2331 	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2332 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2333 	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2334 		/* keep track of pure window updates */
2335 		/*
2336 		 * samkumar: There used to be an if statement here that would check if
2337 		 * this is a "pure" window update (tlen == 0 &&
2338 		 * tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd) and keep
2339 		 * statistics for how often that happens.
2340 		 */
2341 		tp->snd_wnd = tiwin;
2342 		tp->snd_wl1 = th->th_seq;
2343 		tp->snd_wl2 = th->th_ack;
2344 		if (tp->snd_wnd > tp->max_sndwnd)
2345 			tp->max_sndwnd = tp->snd_wnd;
2346 		needoutput = 1;
2347 	}
2348 
2349 	/*
2350 	 * Process segments with URG.
2351 	 */
2352 	/*
2353 	 * samkumar: TCPlp does not support the urgent pointer, so we omit all
2354 	 * urgent-pointer-related processing and buffering. The code below is the
2355 	 * code that was in the "else" case that handles no valid urgent data in
2356 	 * the received packet.
2357 	 */
2358 	{
2359 		/*
2360 		 * If no out of band data is expected,
2361 		 * pull receive urgent pointer along
2362 		 * with the receive window.
2363 		 */
2364 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2365 			tp->rcv_up = tp->rcv_nxt;
2366 	}
2367 
2368 	/*
2369 	 * Process the segment text, merging it into the TCP sequencing queue,
2370 	 * and arranging for acknowledgment of receipt if necessary.
2371 	 * This process logically involves adjusting tp->rcv_wnd as data
2372 	 * is presented to the user (this happens in tcp_usrreq.c,
2373 	 * case PRU_RCVD).  If a FIN has already been received on this
2374 	 * connection then we just ignore the text.
2375 	 */
2376 	if ((tlen || (thflags & TH_FIN)) &&
2377 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2378 		tcp_seq save_start = th->th_seq;
2379 		/*
2380 		 * samkumar: I removed a call to m_adj(m, drop_hdrlen), which intends
2381 		 * to drop data from the mbuf so it can be chained into the receive
2382 		 * header. This is not necessary for TCPlp because we copy the data
2383 		 * anyway; we just add the offset when copying data into the receive
2384 		 * buffer.
2385 		 */
2386 		/*
2387 		 * Insert segment which includes th into TCP reassembly queue
2388 		 * with control block tp.  Set thflags to whether reassembly now
2389 		 * includes a segment with FIN.  This handles the common case
2390 		 * inline (segment is the next to be received on an established
2391 		 * connection, and the queue is empty), avoiding linkage into
2392 		 * and removal from the queue and repetition of various
2393 		 * conversions.
2394 		 * Set DELACK for segments received in order, but ack
2395 		 * immediately when segments are out of order (so
2396 		 * fast retransmit can work).
2397 		 */
2398 		/*
2399 		 * samkumar: I replaced LIST_EMPTY(&tp->t_segq) with the calls to
2400 		 * tpiscantrcv and bmp_isempty on the second line below.
2401 		 */
2402 		if (th->th_seq == tp->rcv_nxt &&
2403 		    (tpiscantrcv(tp) || bmp_isempty(tp->reassbmp, REASSBMP_SIZE(tp))) &&
2404 		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2405 			if (DELAY_ACK(tp, tlen))
2406 				tp->t_flags |= TF_DELACK;
2407 			else
2408 				tp->t_flags |= TF_ACKNOW;
2409 			tp->rcv_nxt += tlen;
2410 			thflags = th->th_flags & TH_FIN;
2411 
2412 			/*
2413 			 * samkumar: I replaced the code that used to be here (which would
2414 			 * free the mbuf with m_freem(m) if the SBS_CANTRCVMORE flag is set
2415 			 * on so->so_rcv.sb_state, and otherwise call
2416 			 * sbappendstream_locked(&so->so_rcv, m, 0);).
2417 			 */
2418 			if (!tpiscantrcv(tp)) {
2419 				cbuf_write(&tp->recvbuf, msg, otMessageGetOffset(msg) + drop_hdrlen, tlen, cbuf_copy_from_message);
2420 				if (tlen > 0) {
2421 					sig->recvbuf_added = true;
2422 				}
2423 			} else if (tlen > 0) {
2424 				/*
2425 				 * samkumar: We already know tlen != 0, so if we got here, then
2426 				 * it means that we got data after we called SHUT_RD, or after
2427 				 * receiving a FIN. I'm going to drop the connection in this
2428 				 * case. I think FreeBSD might have just dropped the packet
2429 				 * silently, but Linux handles it this way; this seems to be
2430 				 * the right approach to me.
2431 				 */
2432 				tcp_drop(tp, ECONNABORTED);
2433 				goto drop;
2434 			}
2435 			/* NB: sorwakeup_locked() does an implicit unlock. */
2436 			/*
2437 			 * samkumar: There used to be a call to sorwakeup_locked(so); here,
2438 			 * which wakes up any threads waiting for the socket to become
2439 			 * become ready for reading. TCPlp handles its buffering
2440 			 * differently so we do not need to replace this call with
2441 			 * specialized code to handle this.
2442 			 */
2443 		} else if (tpiscantrcv(tp)) {
2444 			/*
2445 			 * samkumar: We will reach this point if we get out-of-order data
2446 			 * on a socket which was shut down with SHUT_RD, or where we
2447 			 * already received a FIN. My response here is to drop the segment
2448 			 * and send an RST.
2449 			 */
2450 			tcp_drop(tp, ECONNABORTED);
2451 			goto drop;
2452 		} else {
2453 			/*
2454 			 * XXX: Due to the header drop above "th" is
2455 			 * theoretically invalid by now.  Fortunately
2456 			 * m_adj() doesn't actually frees any mbufs
2457 			 * when trimming from the head.
2458 			 */
2459 			thflags = tcp_reass(tp, th, &tlen, msg, otMessageGetOffset(msg) + drop_hdrlen, sig);
2460 			tp->t_flags |= TF_ACKNOW;
2461 		}
2462 		// Only place tlen is used after the call to tcp_reass is below
2463 		if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2464 			tcp_update_sack_list(tp, save_start, save_start + tlen);
2465 		/*
2466 		 * samkumar: This is not me commenting things out; this was already
2467 		 * commented out in the FreeBSD code.
2468 		 */
2469 #if 0
2470 		/*
2471 		 * Note the amount of data that peer has sent into
2472 		 * our window, in order to estimate the sender's
2473 		 * buffer size.
2474 		 * XXX: Unused.
2475 		 */
2476 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
2477 			len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2478 		else
2479 			len = so->so_rcv.sb_hiwat;
2480 #endif
2481 	} else {
2482 		thflags &= ~TH_FIN;
2483 	}
2484 
2485 	/*
2486 	 * If FIN is received ACK the FIN and let the user know
2487 	 * that the connection is closing.
2488 	 */
2489 	if (thflags & TH_FIN) {
2490 		tcplp_sys_log("FIN Processing start");
2491 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2492 			/* samkumar: replace socantrcvmore with tpcantrcvmore */
2493 			tpcantrcvmore(tp);
2494 			/*
2495 			 * If connection is half-synchronized
2496 			 * (ie NEEDSYN flag on) then delay ACK,
2497 			 * so it may be piggybacked when SYN is sent.
2498 			 * Otherwise, since we received a FIN then no
2499 			 * more input can be expected, send ACK now.
2500 			 */
2501 			if (tp->t_flags & TF_NEEDSYN)
2502 				tp->t_flags |= TF_DELACK;
2503 			else
2504 				tp->t_flags |= TF_ACKNOW;
2505 			tp->rcv_nxt++;
2506 		}
2507 		/*
2508 		 * samkumar: This -2 state is added by me, so that we do not consider
2509 		 * any more FINs in reassembly.
2510 		 */
2511 		if (tp->reass_fin_index != -2) {
2512 			sig->rcvd_fin = true;
2513 			tp->reass_fin_index = -2;
2514 		}
2515 		switch (tp->t_state) {
2516 
2517 		/*
2518 		 * In SYN_RECEIVED and ESTABLISHED STATES
2519 		 * enter the CLOSE_WAIT state.
2520 		 */
2521 		case TCPS_SYN_RECEIVED:
2522 			tp->t_starttime = ticks;
2523 			/* FALLTHROUGH */
2524 		case TCPS_ESTABLISHED:
2525 			tcp_state_change(tp, TCPS_CLOSE_WAIT);
2526 			break;
2527 
2528 		/*
2529 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2530 		 * enter the CLOSING state.
2531 		 */
2532 		case TCPS_FIN_WAIT_1:
2533 			tcp_state_change(tp, TCPS_CLOSING);
2534 			break;
2535 
2536 		/*
2537 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2538 		 * starting the time-wait timer, turning off the other
2539 		 * standard timers.
2540 		 */
2541 		case TCPS_FIN_WAIT_2:
2542 			tcp_twstart(tp);
2543 			return;
2544 		}
2545 	}
2546 
2547 	/*
2548 	 * samkumar: Remove code for synchronization and debugging, here and in
2549 	 * the labels below. I also removed the line to free the mbuf if it hasn't
2550 	 * been freed already (the line was "m_freem(m)").
2551 	 */
2552 	/*
2553 	 * Return any desired output.
2554 	 */
2555 	if (needoutput || (tp->t_flags & TF_ACKNOW))
2556 		(void) tcp_output(tp);
2557 
2558 check_delack:
2559 	if (tp->t_flags & TF_DELACK) {
2560 		tp->t_flags &= ~TF_DELACK;
2561 		tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2562 	}
2563 	return;
2564 
2565 dropafterack:
2566 	/*
2567 	 * Generate an ACK dropping incoming segment if it occupies
2568 	 * sequence space, where the ACK reflects our state.
2569 	 *
2570 	 * We can now skip the test for the RST flag since all
2571 	 * paths to this code happen after packets containing
2572 	 * RST have been dropped.
2573 	 *
2574 	 * In the SYN-RECEIVED state, don't send an ACK unless the
2575 	 * segment we received passes the SYN-RECEIVED ACK test.
2576 	 * If it fails send a RST.  This breaks the loop in the
2577 	 * "LAND" DoS attack, and also prevents an ACK storm
2578 	 * between two listening ports that have been sent forged
2579 	 * SYN segments, each with the source address of the other.
2580 	 */
2581 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2582 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2583 	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2584 		rstreason = BANDLIM_RST_OPENPORT;
2585 		goto dropwithreset;
2586 	}
2587 
2588 	tp->t_flags |= TF_ACKNOW;
2589 	(void) tcp_output(tp);
2590 	return;
2591 
2592 dropwithreset:
2593 	if (tp != NULL) {
2594 		tcp_dropwithreset(ip6, th, tp, instance, tlen, rstreason);
2595 	} else
2596 		tcp_dropwithreset(ip6, th, NULL, instance, tlen, rstreason);
2597 	return;
2598 
2599 drop:
2600 	return;
2601 }
2602 
2603 /*
2604  * Parse TCP options and place in tcpopt.
2605  */
2606 static void
tcp_dooptions(struct tcpopt * to,uint8_t * cp,int cnt,int flags)2607 tcp_dooptions(struct tcpopt *to, uint8_t *cp, int cnt, int flags)
2608 {
2609 	int opt, optlen;
2610 
2611 	to->to_flags = 0;
2612 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2613 		opt = cp[0];
2614 		if (opt == TCPOPT_EOL)
2615 			break;
2616 		if (opt == TCPOPT_NOP)
2617 			optlen = 1;
2618 		else {
2619 			if (cnt < 2)
2620 				break;
2621 			optlen = cp[1];
2622 			if (optlen < 2 || optlen > cnt)
2623 				break;
2624 		}
2625 		switch (opt) {
2626 		case TCPOPT_MAXSEG:
2627 			if (optlen != TCPOLEN_MAXSEG)
2628 				continue;
2629 			if (!(flags & TO_SYN))
2630 				continue;
2631 			to->to_flags |= TOF_MSS;
2632 			bcopy((char *)cp + 2,
2633 			    (char *)&to->to_mss, sizeof(to->to_mss));
2634 			to->to_mss = ntohs(to->to_mss);
2635 			break;
2636 		case TCPOPT_WINDOW:
2637 			if (optlen != TCPOLEN_WINDOW)
2638 				continue;
2639 			if (!(flags & TO_SYN))
2640 				continue;
2641 			to->to_flags |= TOF_SCALE;
2642 			to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2643 			break;
2644 		case TCPOPT_TIMESTAMP:
2645 			if (optlen != TCPOLEN_TIMESTAMP)
2646 				continue;
2647 			to->to_flags |= TOF_TS;
2648 			bcopy((char *)cp + 2,
2649 			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2650 			to->to_tsval = ntohl(to->to_tsval);
2651 			bcopy((char *)cp + 6,
2652 			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2653 			to->to_tsecr = ntohl(to->to_tsecr);
2654 			break;
2655 #ifdef TCP_SIGNATURE
2656 		/*
2657 		 * XXX In order to reply to a host which has set the
2658 		 * TCP_SIGNATURE option in its initial SYN, we have to
2659 		 * record the fact that the option was observed here
2660 		 * for the syncache code to perform the correct response.
2661 		 */
2662 		case TCPOPT_SIGNATURE:
2663 			if (optlen != TCPOLEN_SIGNATURE)
2664 				continue;
2665 			to->to_flags |= TOF_SIGNATURE;
2666 			to->to_signature = cp + 2;
2667 			break;
2668 #endif
2669 		case TCPOPT_SACK_PERMITTED:
2670 			if (optlen != TCPOLEN_SACK_PERMITTED)
2671 				continue;
2672 			if (!(flags & TO_SYN))
2673 				continue;
2674 			if (!V_tcp_do_sack)
2675 				continue;
2676 			to->to_flags |= TOF_SACKPERM;
2677 			break;
2678 		case TCPOPT_SACK:
2679 			if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2680 				continue;
2681 			if (flags & TO_SYN)
2682 				continue;
2683 			to->to_flags |= TOF_SACK;
2684 			to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2685 			to->to_sacks = cp + 2;
2686 			break;
2687 		default:
2688 			continue;
2689 		}
2690 	}
2691 }
2692 
2693 
2694 /*
2695  * Collect new round-trip time estimate
2696  * and update averages and current timeout.
2697  */
2698 static void
tcp_xmit_timer(struct tcpcb * tp,int rtt)2699 tcp_xmit_timer(struct tcpcb *tp, int rtt)
2700 {
2701 	int delta;
2702 
2703 	tp->t_rttupdated++;
2704 	if (tp->t_srtt != 0) {
2705 		/*
2706 		 * srtt is stored as fixed point with 5 bits after the
2707 		 * binary point (i.e., scaled by 8).  The following magic
2708 		 * is equivalent to the smoothing algorithm in rfc793 with
2709 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2710 		 * point).  Adjust rtt to origin 0.
2711 		 */
2712 		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2713 			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2714 
2715 		if ((tp->t_srtt += delta) <= 0)
2716 			tp->t_srtt = 1;
2717 
2718 		/*
2719 		 * We accumulate a smoothed rtt variance (actually, a
2720 		 * smoothed mean difference), then set the retransmit
2721 		 * timer to smoothed rtt + 4 times the smoothed variance.
2722 		 * rttvar is stored as fixed point with 4 bits after the
2723 		 * binary point (scaled by 16).  The following is
2724 		 * equivalent to rfc793 smoothing with an alpha of .75
2725 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2726 		 * rfc793's wired-in beta.
2727 		 */
2728 		if (delta < 0)
2729 			delta = -delta;
2730 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2731 		if ((tp->t_rttvar += delta) <= 0)
2732 			tp->t_rttvar = 1;
2733 		if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2734 		    tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2735 	} else {
2736 		/*
2737 		 * No rtt measurement yet - use the unsmoothed rtt.
2738 		 * Set the variance to half the rtt (so our first
2739 		 * retransmit happens at 3*rtt).
2740 		 */
2741 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2742 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2743 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2744 	}
2745 	tp->t_rtttime = 0;
2746 	tp->t_rxtshift = 0;
2747 
2748 	/*
2749 	 * the retransmit should happen at rtt + 4 * rttvar.
2750 	 * Because of the way we do the smoothing, srtt and rttvar
2751 	 * will each average +1/2 tick of bias.  When we compute
2752 	 * the retransmit timer, we want 1/2 tick of rounding and
2753 	 * 1 extra tick because of +-1/2 tick uncertainty in the
2754 	 * firing of the timer.  The bias will give us exactly the
2755 	 * 1.5 tick we need.  But, because the bias is
2756 	 * statistical, we have to test that we don't drop below
2757 	 * the minimum feasible timer (which is 2 ticks).
2758 	 */
2759 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2760 		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2761 
2762 #ifdef INSTRUMENT_TCP
2763 	tcplp_sys_log("TCP timer %u %d %d %d", (unsigned int) tcplp_sys_get_millis(), rtt, (int) tp->t_srtt, (int) tp->t_rttvar);
2764 #endif
2765 
2766 
2767 	/*
2768 	 * We received an ack for a packet that wasn't retransmitted;
2769 	 * it is probably safe to discard any error indications we've
2770 	 * received recently.  This isn't quite right, but close enough
2771 	 * for now (a route might have failed after we sent a segment,
2772 	 * and the return path might not be symmetrical).
2773 	 */
2774 	tp->t_softerror = 0;
2775 }
2776 
2777 /*
2778  * samkumar: Taken from netinet6/in6.c.
2779  *
2780  * This function is supposed to check whether the provided address is an
2781  * IPv6 address of this host. This function, however, is used only as a hint,
2782  * as the MSS is clamped at V_tcp_v6mssdflt for connections to non-local
2783  * addresses. It is difficult for us to actually determine if the address
2784  * belongs to us, so we are conservative and only return 1 (true) if it is
2785  * obviously so---we keep the part of the function that checks for loopback or
2786  * link local and remove the rest of the code that checks for the addresses
2787  * assigned to interfaces. In cases where we return 0 but should have returned
2788  * 1, we may conservatively clamp the MTU, but that should be OK for TCPlp.
2789  * In fact, the constants are set such that we'll get the right answer whether
2790  * we clamp or not, so this shouldn't really matter at all.
2791  */
2792 int
in6_localaddr(struct in6_addr * in6)2793 in6_localaddr(struct in6_addr *in6)
2794 {
2795 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
2796 		return 1;
2797 	return (0);
2798 }
2799 
2800 /*
2801  * Determine a reasonable value for maxseg size.
2802  * If the route is known, check route for mtu.
2803  * If none, use an mss that can be handled on the outgoing interface
2804  * without forcing IP to fragment.  If no route is found, route has no mtu,
2805  * or the destination isn't local, use a default, hopefully conservative
2806  * size (usually 512 or the default IP max size, but no more than the mtu
2807  * of the interface), as we can't discover anything about intervening
2808  * gateways or networks.  We also initialize the congestion/slow start
2809  * window to be a single segment if the destination isn't local.
2810  * While looking at the routing entry, we also initialize other path-dependent
2811  * parameters from pre-set or cached values in the routing entry.
2812  *
2813  * Also take into account the space needed for options that we
2814  * send regularly.  Make maxseg shorter by that amount to assure
2815  * that we can send maxseg amount of data even when the options
2816  * are present.  Store the upper limit of the length of options plus
2817  * data in maxopd.
2818  *
2819  * NOTE that this routine is only called when we process an incoming
2820  * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
2821  * settings are handled in tcp_mssopt().
2822  */
2823 /*
2824  * samkumar: Using struct tcpcb instead of the inpcb.
2825  */
2826 void
tcp_mss_update(struct tcpcb * tp,int offer,int mtuoffer,struct hc_metrics_lite * metricptr,struct tcp_ifcap * cap)2827 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
2828     struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
2829 {
2830 	/*
2831 	 * samkumar: I removed all IPv4-specific logic and cases, including logic
2832 	 * to check for IPv4 vs. IPv6, as well as all locking and debugging code.
2833 	 */
2834 	int mss = 0;
2835 	uint64_t maxmtu = 0;
2836 	struct hc_metrics_lite metrics;
2837 	int origoffer;
2838 	size_t min_protoh = IP6HDR_SIZE + sizeof (struct tcphdr);
2839 
2840 	if (mtuoffer != -1) {
2841 		KASSERT(offer == -1, ("%s: conflict", __func__));
2842 		offer = mtuoffer - min_protoh;
2843 	}
2844 	origoffer = offer;
2845 
2846 	maxmtu = tcp_maxmtu6(tp, cap);
2847 	tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
2848 
2849 	/*
2850 	 * No route to sender, stay with default mss and return.
2851 	 */
2852 	if (maxmtu == 0) {
2853 		/*
2854 		 * In case we return early we need to initialize metrics
2855 		 * to a defined state as tcp_hc_get() would do for us
2856 		 * if there was no cache hit.
2857 		 */
2858 		if (metricptr != NULL)
2859 			bzero(metricptr, sizeof(struct hc_metrics_lite));
2860 		return;
2861 	}
2862 
2863 	/* What have we got? */
2864 	switch (offer) {
2865 		case 0:
2866 			/*
2867 			 * Offer == 0 means that there was no MSS on the SYN
2868 			 * segment, in this case we use tcp_mssdflt as
2869 			 * already assigned to t_maxopd above.
2870 			 */
2871 			offer = tp->t_maxopd;
2872 			break;
2873 
2874 		case -1:
2875 			/*
2876 			 * Offer == -1 means that we didn't receive SYN yet.
2877 			 */
2878 			/* FALLTHROUGH */
2879 
2880 		default:
2881 			/*
2882 			 * Prevent DoS attack with too small MSS. Round up
2883 			 * to at least minmss.
2884 			 */
2885 			offer = max(offer, V_tcp_minmss);
2886 	}
2887 
2888 	/*
2889 	 * rmx information is now retrieved from tcp_hostcache.
2890 	 */
2891 	tcp_hc_get(tp, &metrics);
2892 	if (metricptr != NULL)
2893 		bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
2894 
2895 	/*
2896 	 * If there's a discovered mtu in tcp hostcache, use it.
2897 	 * Else, use the link mtu.
2898 	 */
2899 	if (metrics.rmx_mtu)
2900 		mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2901 	else {
2902 		mss = maxmtu - min_protoh;
2903 		if (!V_path_mtu_discovery &&
2904 		    !in6_localaddr(&tp->faddr))
2905 			mss = min(mss, V_tcp_v6mssdflt);
2906 		/*
2907 		 * XXX - The above conditional (mss = maxmtu - min_protoh)
2908 		 * probably violates the TCP spec.
2909 		 * The problem is that, since we don't know the
2910 		 * other end's MSS, we are supposed to use a conservative
2911 		 * default.  But, if we do that, then MTU discovery will
2912 		 * never actually take place, because the conservative
2913 		 * default is much less than the MTUs typically seen
2914 		 * on the Internet today.  For the moment, we'll sweep
2915 		 * this under the carpet.
2916 		 *
2917 		 * The conservative default might not actually be a problem
2918 		 * if the only case this occurs is when sending an initial
2919 		 * SYN with options and data to a host we've never talked
2920 		 * to before.  Then, they will reply with an MSS value which
2921 		 * will get recorded and the new parameters should get
2922 		 * recomputed.  For Further Study.
2923 		 */
2924 	}
2925 	mss = min(mss, offer);
2926 
2927 	/*
2928 	 * Sanity check: make sure that maxopd will be large
2929 	 * enough to allow some data on segments even if the
2930 	 * all the option space is used (40bytes).  Otherwise
2931 	 * funny things may happen in tcp_output.
2932 	 */
2933 	/*
2934 	 * samkumar: When I was experimenting with different MSS values, I had
2935 	 * changed this to "mss = max(mss, TCP_MAXOLEN + 1);" but I am changing it
2936 	 * back for the version that will be merged into OpenThread.
2937 	 */
2938 	mss = max(mss, 64);
2939 
2940 	/*
2941 	 * maxopd stores the maximum length of data AND options
2942 	 * in a segment; maxseg is the amount of data in a normal
2943 	 * segment.  We need to store this value (maxopd) apart
2944 	 * from maxseg, because now every segment carries options
2945 	 * and thus we normally have somewhat less data in segments.
2946 	 */
2947 	tp->t_maxopd = mss;
2948 
2949 	/*
2950 	 * origoffer==-1 indicates that no segments were received yet.
2951 	 * In this case we just guess.
2952 	 */
2953 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2954 	    (origoffer == -1 ||
2955 	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2956 		mss -= TCPOLEN_TSTAMP_APPA;
2957 
2958 	tp->t_maxseg = mss;
2959 }
2960 
2961 void
tcp_mss(struct tcpcb * tp,int offer)2962 tcp_mss(struct tcpcb *tp, int offer)
2963 {
2964 	struct hc_metrics_lite metrics;
2965 	struct tcp_ifcap cap;
2966 
2967 	KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
2968 
2969 	bzero(&cap, sizeof(cap));
2970 	tcp_mss_update(tp, offer, -1, &metrics, &cap);
2971 
2972 	/*
2973 	 * samkumar: There used to be code below that might modify the MSS, but I
2974 	 * removed all of it (see the comments below for the reason). It used to
2975 	 * read tp->t_maxseg into the local variable mss, modify mss, and then
2976 	 * reassign tp->t_maxseg to mss. I've kept the assignments, commented out,
2977 	 * for clarity.
2978 	 */
2979 	//mss = tp->t_maxseg;
2980 
2981 	/*
2982 	 * If there's a pipesize, change the socket buffer to that size,
2983 	 * don't change if sb_hiwat is different than default (then it
2984 	 * has been changed on purpose with setsockopt).
2985 	 * Make the socket buffers an integral number of mss units;
2986 	 * if the mss is larger than the socket buffer, decrease the mss.
2987 	 */
2988 
2989 	/*
2990 	 * samkumar: There used to be code here would would limit the MSS to at
2991 	 * most the size of the send buffer, and then round up the send buffer to
2992 	 * a multiple of the MSS using
2993 	 * "sbreserve_locked(&so->so_snd, bufsize, so, NULL);". With TCPlp, we do
2994 	 * not do this, because the linked buffer used at the send buffer doesn't
2995 	 * have a real limit. Had we used a circular buffer, then limiting the MSS
2996 	 * to the buffer size would have made sense, but we still would not be able
2997 	 * to resize the send buffer because it is not allocated by TCPlp.
2998 	 */
2999 
3000 	/*
3001 	 * samkumar: See the comment above about me removing code that modifies
3002 	 * the MSS, making this assignment and the one above both unnecessary.
3003 	 */
3004 	//tp->t_maxseg = mss;
3005 
3006 	/*
3007 	 * samkumar: There used to be code here that would round up the receive
3008 	 * buffer size to a multiple of the MSS, assuming that the receive buffer
3009 	 * size is bigger than the MSS. The new buffer size is set using
3010 	 * "sbreserve_locked(&so->so_rcv, bufsize, so, NULL);". In TCPlp, the
3011 	 * buffer is not allocated by TCPlp so I removed the code for this.
3012 	 */
3013 	/*
3014 	 * samkumar: There used to be code here to handle TCP Segmentation
3015 	 * Offloading (TSO); I removed it becuase we don't support that in TCPlp.
3016 	 */
3017 }
3018 
3019 /*
3020  * Determine the MSS option to send on an outgoing SYN.
3021  */
3022 /*
3023  * samkumar: In the signature, changed "struct in_conninfo *inc" to
3024  * "struct tcpcb* tp".
3025  */
3026 int
tcp_mssopt(struct tcpcb * tp)3027 tcp_mssopt(struct tcpcb* tp)
3028 {
3029 	/*
3030 	 * samkumar: I removed all processing code specific to IPv4, or to decide
3031 	 * between IPv4 and IPv6. This is OK because TCPlp assumes IPv6.
3032 	 */
3033 	int mss = 0;
3034 	uint64_t maxmtu = 0;
3035 	uint64_t thcmtu = 0;
3036 	size_t min_protoh;
3037 
3038 	KASSERT(tp != NULL, ("tcp_mssopt with NULL tcpcb pointer"));
3039 
3040 	mss = V_tcp_v6mssdflt;
3041 	maxmtu = tcp_maxmtu6(tp, NULL);
3042 	min_protoh = IP6HDR_SIZE + sizeof(struct tcphdr);
3043 
3044 	thcmtu = tcp_hc_getmtu(tp); /* IPv4 and IPv6 */
3045 
3046 	if (maxmtu && thcmtu)
3047 		mss = min(maxmtu, thcmtu) - min_protoh;
3048 	else if (maxmtu || thcmtu)
3049 		mss = max(maxmtu, thcmtu) - min_protoh;
3050 
3051 	return (mss);
3052 }
3053 
3054 /*
3055  * On a partial ack arrives, force the retransmission of the
3056  * next unacknowledged segment.  Do not clear tp->t_dupacks.
3057  * By setting snd_nxt to ti_ack, this forces retransmission timer to
3058  * be started again.
3059  */
3060 static void
tcp_newreno_partial_ack(struct tcpcb * tp,struct tcphdr * th)3061 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3062 {
3063 	tcp_seq onxt = tp->snd_nxt;
3064 	uint64_t  ocwnd = tp->snd_cwnd;
3065 
3066 	tcp_timer_activate(tp, TT_REXMT, 0);
3067 	tp->t_rtttime = 0;
3068 	tp->snd_nxt = th->th_ack;
3069 	/*
3070 	 * Set snd_cwnd to one segment beyond acknowledged offset.
3071 	 * (tp->snd_una has not yet been updated when this function is called.)
3072 	 */
3073 	tp->snd_cwnd = tp->t_maxseg + BYTES_THIS_ACK(tp, th);
3074 	tp->t_flags |= TF_ACKNOW;
3075 #ifdef INSTRUMENT_TCP
3076 	tcplp_sys_log("TCP Partial_ACK");
3077 #endif
3078 	(void) tcp_output(tp);
3079 	tp->snd_cwnd = ocwnd;
3080 	if (SEQ_GT(onxt, tp->snd_nxt))
3081 		tp->snd_nxt = onxt;
3082 	/*
3083 	 * Partial window deflation.  Relies on fact that tp->snd_una
3084 	 * not updated yet.
3085 	 */
3086 	if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3087 		tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3088 	else
3089 		tp->snd_cwnd = 0;
3090 	tp->snd_cwnd += tp->t_maxseg;
3091 #ifdef INSTRUMENT_TCP
3092 	tcplp_sys_log("TCP Partial_ACK_final %d", (int) tp->snd_cwnd);
3093 #endif
3094 }
3095