1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)tcp_output.c	8.4 (Berkeley) 5/24/95
30  */
31 
32 #include <errno.h>
33 #include <string.h>
34 
35 #include "../tcplp.h"
36 #include "tcp.h"
37 #include "tcp_fsm.h"
38 #include "tcp_var.h"
39 #include "tcp_seq.h"
40 #include "tcp_timer.h"
41 #include "ip.h"
42 #include "../lib/cbuf.h"
43 
44 #include "tcp_const.h"
45 
46 #include <openthread/ip6.h>
47 #include <openthread/message.h>
48 #include <openthread/tcp.h>
49 
50 static inline void
cc_after_idle(struct tcpcb * tp)51 cc_after_idle(struct tcpcb *tp)
52 {
53 	/* samkumar: Removed synchronization. */
54 	if (CC_ALGO(tp)->after_idle != NULL)
55 		CC_ALGO(tp)->after_idle(tp->ccv);
56 }
57 
min(long a,long b)58 long min(long a, long b) {
59 	if (a < b) {
60 		return a;
61 	} else {
62 		return b;
63 	}
64 }
65 
ulmin(unsigned long a,unsigned long b)66 unsigned long ulmin(unsigned long a, unsigned long b) {
67 	if (a < b) {
68 		return a;
69 	} else {
70 		return b;
71 	}
72 }
73 
74 #define lmin(a, b) min(a, b)
75 
76 void
tcp_setpersist(struct tcpcb * tp)77 tcp_setpersist(struct tcpcb *tp)
78 {
79 	int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
80 	int tt;
81 
82 	tp->t_flags &= ~TF_PREVVALID;
83 	if (tcp_timer_active(tp, TT_REXMT))
84 		tcplp_sys_panic("PANIC: tcp_setpersist: retransmit pending");
85 	/*
86 	 * Start/restart persistance timer.
87 	 */
88 	TCPT_RANGESET(tt, t * tcp_backoff[tp->t_rxtshift],
89 		      TCPTV_PERSMIN, TCPTV_PERSMAX);
90 	tcp_timer_activate(tp, TT_PERSIST, tt);
91 	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
92 		tp->t_rxtshift++;
93 }
94 
95 /*
96  * Tcp output routine: figure out what should be sent and send it.
97  */
98 int
tcp_output(struct tcpcb * tp)99 tcp_output(struct tcpcb *tp)
100 {
101 	/*
102 	 * samkumar: The biggest change in this function is in how outgoing
103 	 * segments are built and sent out. That code has been updated to account
104 	 * for TCPlp's buffering, and using otMessages rather than mbufs to
105 	 * construct the outgoing segments.
106 	 *
107 	 * And, of course, all code corresponding to locks, stats, and debugging
108 	 * has been removed, and all code specific to IPv4 or to decide between
109 	 * IPv6 and IPv4 handling has been removed.
110 	 */
111 
112 	struct tcphdr* th = NULL;
113 	int idle;
114 	long len, recwin, sendwin;
115 	int off, flags, error = 0;	/* Keep compiler happy */
116 	int sendalot, mtu;
117 	int sack_rxmit, sack_bytes_rxmt;
118 	struct sackhole* p;
119 	unsigned ipoptlen, optlen, hdrlen;
120 	struct tcpopt to;
121 	uint8_t opt[TCP_MAXOLEN];
122 	uint32_t ticks = tcplp_sys_get_ticks();
123 
124 	/* samkumar: Code for TCP offload has been removed. */
125 
126 	/*
127 	 * Determine length of data that should be transmitted,
128 	 * and flags that will be used.
129 	 * If there is some data or critical controls (SYN, RST)
130 	 * to send, then transmit; otherwise, investigate further.
131 	 */
132 	idle = (tp->t_flags & TF_LASTIDLE) || (tp->snd_max == tp->snd_una);
133 	if (idle && ticks - tp->t_rcvtime >= tp->t_rxtcur)
134 		cc_after_idle(tp);
135 
136 	tp->t_flags &= ~TF_LASTIDLE;
137 	if (idle) {
138 		if (tp->t_flags & TF_MORETOCOME) {
139 			tp->t_flags |= TF_LASTIDLE;
140 			idle = 0;
141 		}
142 	}
143 	/* samkumar: This would be printed once per _window_ that is transmitted. */
144 #ifdef INSTRUMENT_TCP
145 	tcplp_sys_log("TCP output %u %d %d", (unsigned int) tcplp_sys_get_millis(), (int) tp->snd_wnd, (int) tp->snd_cwnd);
146 #endif
147 
148 again:
149 	/*
150 	 * If we've recently taken a timeout, snd_max will be greater than
151 	 * snd_nxt.  There may be SACK information that allows us to avoid
152 	 * resending already delivered data.  Adjust snd_nxt accordingly.
153 	 */
154 	if ((tp->t_flags & TF_SACK_PERMIT) &&
155 	    SEQ_LT(tp->snd_nxt, tp->snd_max))
156 		tcp_sack_adjust(tp);
157 	sendalot = 0;
158 	/* samkumar: Removed code for supporting TSO. */
159 	mtu = 0;
160 	off = tp->snd_nxt - tp->snd_una;
161 	sendwin = min(tp->snd_wnd, tp->snd_cwnd);
162 
163 	flags = tcp_outflags[tp->t_state];
164 	/*
165 	 * Send any SACK-generated retransmissions.  If we're explicitly trying
166 	 * to send out new data (when sendalot is 1), bypass this function.
167 	 * If we retransmit in fast recovery mode, decrement snd_cwnd, since
168 	 * we're replacing a (future) new transmission with a retransmission
169 	 * now, and we previously incremented snd_cwnd in tcp_input().
170 	 */
171 	/*
172 	 * Still in sack recovery , reset rxmit flag to zero.
173 	 */
174 	sack_rxmit = 0;
175 	sack_bytes_rxmt = 0;
176 	len = 0;
177 	p = NULL;
178 	if ((tp->t_flags & TF_SACK_PERMIT) && IN_FASTRECOVERY(tp->t_flags) &&
179 	    (p = tcp_sack_output(tp, &sack_bytes_rxmt))) {
180 		long cwin;
181 
182 		cwin = min(tp->snd_wnd, tp->snd_cwnd) - sack_bytes_rxmt;
183 		if (cwin < 0)
184 			cwin = 0;
185 		/* Do not retransmit SACK segments beyond snd_recover */
186 		if (SEQ_GT(p->end, tp->snd_recover)) {
187 			/*
188 			 * (At least) part of sack hole extends beyond
189 			 * snd_recover. Check to see if we can rexmit data
190 			 * for this hole.
191 			 */
192 			if (SEQ_GEQ(p->rxmit, tp->snd_recover)) {
193 				/*
194 				 * Can't rexmit any more data for this hole.
195 				 * That data will be rexmitted in the next
196 				 * sack recovery episode, when snd_recover
197 				 * moves past p->rxmit.
198 				 */
199 				p = NULL;
200 				goto after_sack_rexmit;
201 			} else
202 				/* Can rexmit part of the current hole */
203 				len = ((long)ulmin(cwin,
204 						   tp->snd_recover - p->rxmit));
205 		} else
206 			len = ((long)ulmin(cwin, p->end - p->rxmit));
207 		off = p->rxmit - tp->snd_una;
208 		KASSERT(off >= 0,("%s: sack block to the left of una : %d",
209 		    __func__, off));
210 		if (len > 0) {
211 			sack_rxmit = 1;
212 			sendalot = 1;
213 		}
214 	}
215 after_sack_rexmit:
216 	/*
217 	 * Get standard flags, and add SYN or FIN if requested by 'hidden'
218 	 * state flags.
219 	 */
220 	if (tp->t_flags & TF_NEEDFIN)
221 		flags |= TH_FIN;
222 	if (tp->t_flags & TF_NEEDSYN)
223 		flags |= TH_SYN;
224 
225 	/*
226 	 * If in persist timeout with window of 0, send 1 byte.
227 	 * Otherwise, if window is small but nonzero
228 	 * and timer expired, we will send what we can
229 	 * and go to transmit state.
230 	 */
231 	if (tp->t_flags & TF_FORCEDATA) {
232 		if (sendwin == 0) {
233 			/*
234 			 * If we still have some data to send, then
235 			 * clear the FIN bit.  Usually this would
236 			 * happen below when it realizes that we
237 			 * aren't sending all the data.  However,
238 			 * if we have exactly 1 byte of unsent data,
239 			 * then it won't clear the FIN bit below,
240 			 * and if we are in persist state, we wind
241 			 * up sending the packet without recording
242 			 * that we sent the FIN bit.
243 			 *
244 			 * We can't just blindly clear the FIN bit,
245 			 * because if we don't have any more data
246 			 * to send then the probe will be the FIN
247 			 * itself.
248 			 */
249 			/*
250 			 * samkumar: Replaced call to sbused(&so->so_snd) with the call to
251 			 * lbuf_used_space below.
252 			 */
253 			if (off < lbuf_used_space(&tp->sendbuf))
254 				flags &= ~TH_FIN;
255 			sendwin = 1;
256 		} else {
257 			tcp_timer_activate(tp, TT_PERSIST, 0);
258 			tp->t_rxtshift = 0;
259 		}
260 	}
261 
262 	/*
263 	 * If snd_nxt == snd_max and we have transmitted a FIN, the
264 	 * offset will be > 0 even if so_snd.sb_cc is 0, resulting in
265 	 * a negative length.  This can also occur when TCP opens up
266 	 * its congestion window while receiving additional duplicate
267 	 * acks after fast-retransmit because TCP will reset snd_nxt
268 	 * to snd_max after the fast-retransmit.
269 	 *
270 	 * In the normal retransmit-FIN-only case, however, snd_nxt will
271 	 * be set to snd_una, the offset will be 0, and the length may
272 	 * wind up 0.
273 	 *
274 	 * If sack_rxmit is true we are retransmitting from the scoreboard
275 	 * in which case len is already set.
276 	 */
277 	if (sack_rxmit == 0) {
278 		if (sack_bytes_rxmt == 0)
279 			/*
280 			 * samkumar: Replaced sbavail(&so->so_snd) with this call to
281 			 * lbuf_used_space.
282 			 */
283 			len = ((long)ulmin(lbuf_used_space(&tp->sendbuf), sendwin) -
284 			    off);
285 		else {
286 			long cwin;
287 
288 			/*
289 			 * We are inside of a SACK recovery episode and are
290 			 * sending new data, having retransmitted all the
291 			 * data possible in the scoreboard.
292 			 */
293 			/*
294 			 * samkumar: Replaced sbavail(&so->so_snd) with this call to
295 			 * lbuf_used_space.
296 			 */
297 			len = ((long)ulmin(lbuf_used_space(&tp->sendbuf), tp->snd_wnd) -
298 			    off);
299 			/*
300 			 * Don't remove this (len > 0) check !
301 			 * We explicitly check for len > 0 here (although it
302 			 * isn't really necessary), to work around a gcc
303 			 * optimization issue - to force gcc to compute
304 			 * len above. Without this check, the computation
305 			 * of len is bungled by the optimizer.
306 			 */
307 			if (len > 0) {
308 				cwin = tp->snd_cwnd -
309 					(tp->snd_nxt - tp->sack_newdata) -
310 					sack_bytes_rxmt;
311 				if (cwin < 0)
312 					cwin = 0;
313 				len = lmin(len, cwin);
314 			}
315 		}
316 	}
317 
318 	/*
319 	 * Lop off SYN bit if it has already been sent.  However, if this
320 	 * is SYN-SENT state and if segment contains data and if we don't
321 	 * know that foreign host supports TAO, suppress sending segment.
322 	 */
323 	if ((flags & TH_SYN) && SEQ_GT(tp->snd_nxt, tp->snd_una)) {
324 		if (tp->t_state != TCPS_SYN_RECEIVED)
325 			flags &= ~TH_SYN;
326 		off--, len++;
327 	}
328 
329 	/*
330 	 * Be careful not to send data and/or FIN on SYN segments.
331 	 * This measure is needed to prevent interoperability problems
332 	 * with not fully conformant TCP implementations.
333 	 */
334 	if ((flags & TH_SYN) && (tp->t_flags & TF_NOOPT)) {
335 		len = 0;
336 		flags &= ~TH_FIN;
337 	}
338 
339 	if (len <= 0) {
340 		/*
341 		 * If FIN has been sent but not acked,
342 		 * but we haven't been called to retransmit,
343 		 * len will be < 0.  Otherwise, window shrank
344 		 * after we sent into it.  If window shrank to 0,
345 		 * cancel pending retransmit, pull snd_nxt back
346 		 * to (closed) window, and set the persist timer
347 		 * if it isn't already going.  If the window didn't
348 		 * close completely, just wait for an ACK.
349 		 *
350 		 * We also do a general check here to ensure that
351 		 * we will set the persist timer when we have data
352 		 * to send, but a 0-byte window. This makes sure
353 		 * the persist timer is set even if the packet
354 		 * hits one of the "goto send" lines below.
355 		 */
356 		len = 0;
357 		/*
358 		 * samkumar: Replaced sbavail(&so->so_snd) with this call to
359 		 * lbuf_used_space.
360 		 */
361 		if ((sendwin == 0) && (TCPS_HAVEESTABLISHED(tp->t_state)) &&
362 			(off < (int) lbuf_used_space(&tp->sendbuf))) {
363 			tcp_timer_activate(tp, TT_REXMT, 0);
364 			tp->t_rxtshift = 0;
365 			tp->snd_nxt = tp->snd_una;
366 			if (!tcp_timer_active(tp, TT_PERSIST)) {
367 				tcp_setpersist(tp);
368 			}
369 		}
370 	}
371 
372 
373 	/* len will be >= 0 after this point. */
374 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
375 
376 	/*
377 	 * Automatic sizing of send socket buffer.  Often the send buffer
378 	 * size is not optimally adjusted to the actual network conditions
379 	 * at hand (delay bandwidth product).  Setting the buffer size too
380 	 * small limits throughput on links with high bandwidth and high
381 	 * delay (eg. trans-continental/oceanic links).  Setting the
382 	 * buffer size too big consumes too much real kernel memory,
383 	 * especially with many connections on busy servers.
384 	 *
385 	 * The criteria to step up the send buffer one notch are:
386 	 *  1. receive window of remote host is larger than send buffer
387 	 *     (with a fudge factor of 5/4th);
388 	 *  2. send buffer is filled to 7/8th with data (so we actually
389 	 *     have data to make use of it);
390 	 *  3. send buffer fill has not hit maximal automatic size;
391 	 *  4. our send window (slow start and cogestion controlled) is
392 	 *     larger than sent but unacknowledged data in send buffer.
393 	 *
394 	 * The remote host receive window scaling factor may limit the
395 	 * growing of the send buffer before it reaches its allowed
396 	 * maximum.
397 	 *
398 	 * It scales directly with slow start or congestion window
399 	 * and does at most one step per received ACK.  This fast
400 	 * scaling has the drawback of growing the send buffer beyond
401 	 * what is strictly necessary to make full use of a given
402 	 * delay*bandwith product.  However testing has shown this not
403 	 * to be much of an problem.  At worst we are trading wasting
404 	 * of available bandwith (the non-use of it) for wasting some
405 	 * socket buffer memory.
406 	 *
407 	 * TODO: Shrink send buffer during idle periods together
408 	 * with congestion window.  Requires another timer.  Has to
409 	 * wait for upcoming tcp timer rewrite.
410 	 *
411 	 * XXXGL: should there be used sbused() or sbavail()?
412 	 */
413 	 /*
414 	 * samkumar: There used to be code here to dynamically size the
415 	 * send buffer (by calling sbreserve_locked). In TCPlp, we don't support
416 	 * this, as the send buffer doesn't have a well-defined size (and even if
417 	 * we were to use a circular buffer, it would be a fixed-size buffer
418 	 * allocated by the application). Therefore, I removed the code that does
419 	 * this.
420 	 */
421 
422 	 /*
423  	 * samkumar: There used to be code here to handle TCP Segmentation
424  	 * Offloading (TSO); I removed it becuase we don't support that in TCPlp.
425  	 */
426 
427 	if (sack_rxmit) {
428 		/*
429 		 * samkumar: Replaced sbused(&so->so_snd) with this call to
430 		 * lbuf_used_space.
431 		 */
432 		if (SEQ_LT(p->rxmit + len, tp->snd_una + lbuf_used_space(&tp->sendbuf)))
433 			flags &= ~TH_FIN;
434 	} else {
435 		if (SEQ_LT(tp->snd_nxt + len, tp->snd_una +
436 			/*
437 			 * samkumar: Replaced sbused(&so->so_snd) with this call to
438 			 * lbuf_used_space.
439 			 */
440 			lbuf_used_space(&tp->sendbuf)))
441 			flags &= ~TH_FIN;
442 	}
443 
444 	/*
445 	 * samkumar: Replaced sbspace(&so->so_rcv) with this call to
446 	 * cbuf_free_space.
447 	 */
448 	recwin = cbuf_free_space(&tp->recvbuf);
449 
450 	/*
451 	 * Sender silly window avoidance.   We transmit under the following
452 	 * conditions when len is non-zero:
453 	 *
454 	 *	- We have a full segment (or more with TSO)
455 	 *	- This is the last buffer in a write()/send() and we are
456 	 *	  either idle or running NODELAY
457 	 *	- we've timed out (e.g. persist timer)
458 	 *	- we have more then 1/2 the maximum send window's worth of
459 	 *	  data (receiver may be limited the window size)
460 	 *	- we need to retransmit
461 	 */
462 	if (len) {
463 		if (len >= tp->t_maxseg)
464 			goto send;
465 		/*
466 		 * NOTE! on localhost connections an 'ack' from the remote
467 		 * end may occur synchronously with the output and cause
468 		 * us to flush a buffer queued with moretocome.  XXX
469 		 *
470 		 * note: the len + off check is almost certainly unnecessary.
471 		 */
472 		/*
473  		 * samkumar: Replaced sbavail(&so->so_snd) with this call to
474  		 * lbuf_used_space.
475  		 */
476 		if (!(tp->t_flags & TF_MORETOCOME) &&	/* normal case */
477 		    (idle || (tp->t_flags & TF_NODELAY)) &&
478 		    len + off >= lbuf_used_space(&tp->sendbuf) &&
479 		    (tp->t_flags & TF_NOPUSH) == 0) {
480 			goto send;
481 		}
482 		if (tp->t_flags & TF_FORCEDATA)		/* typ. timeout case */
483 			goto send;
484 		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
485 			goto send;
486 		if (SEQ_LT(tp->snd_nxt, tp->snd_max))	/* retransmit case */
487 			goto send;
488 		if (sack_rxmit)
489 			goto send;
490 	}
491 
492 	/*
493 	 * Sending of standalone window updates.
494 	 *
495 	 * Window updates are important when we close our window due to a
496 	 * full socket buffer and are opening it again after the application
497 	 * reads data from it.  Once the window has opened again and the
498 	 * remote end starts to send again the ACK clock takes over and
499 	 * provides the most current window information.
500 	 *
501 	 * We must avoid the silly window syndrome whereas every read
502 	 * from the receive buffer, no matter how small, causes a window
503 	 * update to be sent.  We also should avoid sending a flurry of
504 	 * window updates when the socket buffer had queued a lot of data
505 	 * and the application is doing small reads.
506 	 *
507 	 * Prevent a flurry of pointless window updates by only sending
508 	 * an update when we can increase the advertized window by more
509 	 * than 1/4th of the socket buffer capacity.  When the buffer is
510 	 * getting full or is very small be more aggressive and send an
511 	 * update whenever we can increase by two mss sized segments.
512 	 * In all other situations the ACK's to new incoming data will
513 	 * carry further window increases.
514 	 *
515 	 * Don't send an independent window update if a delayed
516 	 * ACK is pending (it will get piggy-backed on it) or the
517 	 * remote side already has done a half-close and won't send
518 	 * more data.  Skip this if the connection is in T/TCP
519 	 * half-open state.
520 	 */
521 	if (recwin > 0 && !(tp->t_flags & TF_NEEDSYN) &&
522 	    !(tp->t_flags & TF_DELACK) &&
523 	    !TCPS_HAVERCVDFIN(tp->t_state)) {
524 		/*
525 		 * "adv" is the amount we could increase the window,
526 		 * taking into account that we are limited by
527 		 * TCP_MAXWIN << tp->rcv_scale.
528 		 */
529 		long adv;
530 		int oldwin;
531 
532 		adv = min(recwin, (long)TCP_MAXWIN << tp->rcv_scale);
533 		if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt)) {
534 			oldwin = (tp->rcv_adv - tp->rcv_nxt);
535 			adv -= oldwin;
536 		} else
537 			oldwin = 0;
538 
539 		/*
540 		 * If the new window size ends up being the same as the old
541 		 * size when it is scaled, then don't force a window update.
542 		 */
543 		if (oldwin >> tp->rcv_scale == (adv + oldwin) >> tp->rcv_scale)
544 			goto dontupdate;
545 
546 		/*
547 		 * samkumar: Here, FreeBSD has some heuristics to decide whether or
548 		 * not to send a window update. The code for the original heuristics
549 		 * is commented out, using #if 0. These heuristics compare "adv,"
550 		 * the size of the window update, with the size of the local receive
551 		 * buffer. The FreeBSD heuristics aren't applicable because they are
552 		 * orders of magnitude off from what we see in TCPlp. For example,
553 		 * FreeBSD only sends a window update if it is at least two segments
554 		 * big. Note that, in the experiments I did, the second case did not
555 		 * filter window updates further because, in the experiments, the
556 		 * receive buffer was smaller than 8 segments.
557 		 *
558 		 * I replaced these heuristics with a simpler version, which you can
559 		 * see below. For the experiments I did, the first condition
560 		 * (checking if adv >= (long)(2 * tp->t_maxseg)) wasn't included; this
561 		 * did not matter because the receive buffer was smaller than 8
562 		 * segments, so any condition that would have triggered the first
563 		 * condition would have triggered the second one anyway. I've included
564 		 * the first condition in this version in an effort to be more robust,
565 		 * in case someone does try to run TCPlp with a large receive buffer.
566 		 *
567 		 * It may be worth studying this more and revisiting the heuristic to
568 		 * use here. In case we try to resurrect the old FreeBSD heuristics,
569 		 * note that so->so_rcv.sb_hiwat in FreeBSD corresponds roughly to
570 		 * cbuf_size(&tp->recvbuf) in TCPlp.
571 		 */
572 #if 0
573 		if (adv >= (long)(2 * tp->t_maxseg) &&
574 		    (adv >= (long)(so->so_rcv.sb_hiwat / 4) ||
575 		     recwin <= (long)(so->so_rcv.sb_hiwat / 8) ||
576 		     so->so_rcv.sb_hiwat <= 8 * tp->t_maxseg))
577 			goto send;
578 #endif
579 		if (adv >= (long)(2 * tp->t_maxseg) ||
580 		    adv >= (long)cbuf_size(&tp->recvbuf) / 4)
581 			goto send;
582 	}
583 dontupdate:
584 
585 	/*
586 	 * Send if we owe the peer an ACK, RST, SYN, or urgent data.  ACKNOW
587 	 * is also a catch-all for the retransmit timer timeout case.
588 	 */
589 	if (tp->t_flags & TF_ACKNOW) {
590 		goto send;
591 	}
592 	if ((flags & TH_RST) ||
593 	    ((flags & TH_SYN) && (tp->t_flags & TF_NEEDSYN) == 0))
594 		goto send;
595 	if (SEQ_GT(tp->snd_up, tp->snd_una))
596 		goto send;
597 	/*
598 	 * If our state indicates that FIN should be sent
599 	 * and we have not yet done so, then we need to send.
600 	 */
601 	if (flags & TH_FIN &&
602 	    ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
603 		goto send;
604 	/*
605 	 * In SACK, it is possible for tcp_output to fail to send a segment
606 	 * after the retransmission timer has been turned off.  Make sure
607 	 * that the retransmission timer is set.
608 	 */
609 	if ((tp->t_flags & TF_SACK_PERMIT) &&
610 	    SEQ_GT(tp->snd_max, tp->snd_una) &&
611 	    !tcp_timer_active(tp, TT_REXMT) &&
612 	    !tcp_timer_active(tp, TT_PERSIST)) {
613 		tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
614 		goto just_return;
615 	}
616 
617 	/*
618 	 * TCP window updates are not reliable, rather a polling protocol
619 	 * using ``persist'' packets is used to insure receipt of window
620 	 * updates.  The three ``states'' for the output side are:
621 	 *	idle			not doing retransmits or persists
622 	 *	persisting		to move a small or zero window
623 	 *	(re)transmitting	and thereby not persisting
624 	 *
625 	 * tcp_timer_active(tp, TT_PERSIST)
626 	 *	is true when we are in persist state.
627 	 * (tp->t_flags & TF_FORCEDATA)
628 	 *	is set when we are called to send a persist packet.
629 	 * tcp_timer_active(tp, TT_REXMT)
630 	 *	is set when we are retransmitting
631 	 * The output side is idle when both timers are zero.
632 	 *
633 	 * If send window is too small, there is data to transmit, and no
634 	 * retransmit or persist is pending, then go to persist state.
635 	 * If nothing happens soon, send when timer expires:
636 	 * if window is nonzero, transmit what we can,
637 	 * otherwise force out a byte.
638 	 */
639 	/*
640 	 * samkumar: Replaced sbavail(&so->so_snd) with this call to
641 	 * lbuf_used_space.
642 	 */
643 	if (lbuf_used_space(&tp->sendbuf) && !tcp_timer_active(tp, TT_REXMT) &&
644 	    !tcp_timer_active(tp, TT_PERSIST)) {
645 		tp->t_rxtshift = 0;
646 		tcp_setpersist(tp);
647 	}
648 
649 	/*
650 	 * No reason to send a segment, just return.
651 	 */
652 just_return:
653 	return (0);
654 
655 send:
656 	if (len > 0) {
657 		if (len >= tp->t_maxseg)
658 			tp->t_flags2 |= TF2_PLPMTU_MAXSEGSNT;
659 		else
660 			tp->t_flags2 &= ~TF2_PLPMTU_MAXSEGSNT;
661 	}
662 	/*
663 	 * Before ESTABLISHED, force sending of initial options
664 	 * unless TCP set not to do any options.
665 	 * NOTE: we assume that the IP/TCP header plus TCP options
666 	 * always fit in a single mbuf, leaving room for a maximum
667 	 * link header, i.e.
668 	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MCLBYTES
669 	 */
670 	optlen = 0;
671 	hdrlen = sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
672 
673 	/*
674 	 * Compute options for segment.
675 	 * We only have to care about SYN and established connection
676 	 * segments.  Options for SYN-ACK segments are handled in TCP
677 	 * syncache.
678 	 * Sam: I've done away with the syncache. However, it seems that
679 	 * the existing logic works fine for SYN-ACK as well
680 	 */
681 	if ((tp->t_flags & TF_NOOPT) == 0) {
682 		to.to_flags = 0;
683 		/* Maximum segment size. */
684 		if (flags & TH_SYN) {
685 			tp->snd_nxt = tp->iss;
686 			to.to_mss = tcp_mssopt(tp);
687 			to.to_flags |= TOF_MSS;
688 		}
689 		/* Window scaling. */
690 		if ((flags & TH_SYN) && (tp->t_flags & TF_REQ_SCALE)) {
691 			to.to_wscale = tp->request_r_scale;
692 			to.to_flags |= TOF_SCALE;
693 		}
694 		/* Timestamps. */
695 		if ((tp->t_flags & TF_RCVD_TSTMP) ||
696 		    ((flags & TH_SYN) && (tp->t_flags & TF_REQ_TSTMP))) {
697 			to.to_tsval = tcp_ts_getticks() + tp->ts_offset;
698 			to.to_tsecr = tp->ts_recent;
699 			to.to_flags |= TOF_TS;
700 			/*
701 			 * samkumar: I removed the code to set the timestamp tp->rfbuf_ts
702 			 * for receive buffer autosizing, since we don't do autosizing on
703 			 * the receive buffer in TCPlp.
704 			 */
705 		}
706 
707 		/* Selective ACK's. */
708 		if (tp->t_flags & TF_SACK_PERMIT) {
709 			if (flags & TH_SYN)
710 				to.to_flags |= TOF_SACKPERM;
711 			else if (TCPS_HAVEESTABLISHED(tp->t_state) &&
712 			    (tp->t_flags & TF_SACK_PERMIT) &&
713 			    tp->rcv_numsacks > 0) {
714 				to.to_flags |= TOF_SACK;
715 				to.to_nsacks = tp->rcv_numsacks;
716 				to.to_sacks = (uint8_t *)tp->sackblks;
717 			}
718 		}
719 
720 		/*
721 		 * samkumar: Remove logic to set TOF_SIGNATURE flag in to.to_flags,
722 		 * since TCPlp does not support TCP signatures.
723 		 */
724 
725 		/* Processing the options. */
726 		hdrlen += optlen = tcp_addoptions(&to, opt);
727 	}
728 	/*
729 	 * samkumar: This used to be set to ip6_optlen(tp->t_inpcb), instead of 0,
730 	 * along with some additional code to handle IPSEC. In TCPlp we don't set
731 	 * IPv6 options here; we expect those to be set by the host network stack.
732 	 * Of course, code that supports IPv4 has been removed as well.
733 	 */
734 	ipoptlen = 0;
735 
736 	/*
737 	 * Adjust data length if insertion of options will
738 	 * bump the packet length beyond the t_maxopd length.
739 	 * Clear the FIN bit because we cut off the tail of
740 	 * the segment.
741 	 */
742 	if (len + optlen + ipoptlen > tp->t_maxopd) {
743 		flags &= ~TH_FIN;
744 		/*
745 		 * samkumar: Remove code for TCP segmentation offloading.
746 		 */
747 		len = tp->t_maxopd - optlen - ipoptlen;
748 		sendalot = 1;
749 	}
750 	/*
751 	 * samkumar: The else case of the above "if" statement would set tso to 0.
752 	 * Removing this since we no longer need a tso variable.
753 	 */
754 	KASSERT(len + hdrlen + ipoptlen <= IP_MAXPACKET,
755 	    ("%s: len > IP_MAXPACKET", __func__));
756 
757 	/*
758 	 * This KASSERT is here to catch edge cases at a well defined place.
759 	 * Before, those had triggered (random) panic conditions further down.
760 	 */
761 	KASSERT(len >= 0, ("[%s:%d]: len < 0", __func__, __LINE__));
762 
763 	/*
764 	 * Grab a header mbuf, attaching a copy of data to
765 	 * be transmitted, and initialize the header from
766 	 * the template for sends on this connection.
767 	 */
768 
769 	/*
770 	 * samkumar: The code to allocate, build, and send outgoing segments has
771 	 * been rewritten. I've left the original code to build the output mbuf
772 	 * here in a comment, for reference. The new code is below.
773 	 */
774 #if 0
775 	if (len) {
776 		struct mbuf *mb;
777 		uint32_t moff;
778 
779 		if ((tp->t_flags & TF_FORCEDATA) && len == 1)
780 			TCPSTAT_INC(tcps_sndprobe);
781 		else if (SEQ_LT(tp->snd_nxt, tp->snd_max) || sack_rxmit) {
782 			tp->t_sndrexmitpack++;
783 			TCPSTAT_INC(tcps_sndrexmitpack);
784 			TCPSTAT_ADD(tcps_sndrexmitbyte, len);
785 		} else {
786 			TCPSTAT_INC(tcps_sndpack);
787 			TCPSTAT_ADD(tcps_sndbyte, len);
788 		}
789 #ifdef INET6
790 		if (MHLEN < hdrlen + max_linkhdr)
791 			m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
792 		else
793 #endif
794 			m = m_gethdr(M_NOWAIT, MT_DATA);
795 
796 		if (m == NULL) {
797 			SOCKBUF_UNLOCK(&so->so_snd);
798 			error = ENOBUFS;
799 			sack_rxmit = 0;
800 			goto out;
801 		}
802 
803 		m->m_data += max_linkhdr;
804 		m->m_len = hdrlen;
805 
806 		/*
807 		 * Start the m_copy functions from the closest mbuf
808 		 * to the offset in the socket buffer chain.
809 		 */
810 		mb = sbsndptr(&so->so_snd, off, len, &moff);
811 
812 		if (len <= MHLEN - hdrlen - max_linkhdr) {
813 			m_copydata(mb, moff, (int)len,
814 			    mtod(m, caddr_t) + hdrlen);
815 			m->m_len += len;
816 		} else {
817 			m->m_next = m_copy(mb, moff, (int)len);
818 			if (m->m_next == NULL) {
819 				SOCKBUF_UNLOCK(&so->so_snd);
820 				(void) m_free(m);
821 				error = ENOBUFS;
822 				sack_rxmit = 0;
823 				goto out;
824 			}
825 		}
826 
827 		/*
828 		 * If we're sending everything we've got, set PUSH.
829 		 * (This will keep happy those implementations which only
830 		 * give data to the user when a buffer fills or
831 		 * a PUSH comes in.)
832 		 */
833 		if (off + len == sbused(&so->so_snd))
834 			flags |= TH_PUSH;
835 		SOCKBUF_UNLOCK(&so->so_snd);
836 	} else {
837 		SOCKBUF_UNLOCK(&so->so_snd);
838 		if (tp->t_flags & TF_ACKNOW)
839 			TCPSTAT_INC(tcps_sndacks);
840 		else if (flags & (TH_SYN|TH_FIN|TH_RST))
841 			TCPSTAT_INC(tcps_sndctrl);
842 		else if (SEQ_GT(tp->snd_up, tp->snd_una))
843 			TCPSTAT_INC(tcps_sndurg);
844 		else
845 			TCPSTAT_INC(tcps_sndwinup);
846 
847 		m = m_gethdr(M_NOWAIT, MT_DATA);
848 		if (m == NULL) {
849 			error = ENOBUFS;
850 			sack_rxmit = 0;
851 			goto out;
852 		}
853 #ifdef INET6
854 		if (isipv6 && (MHLEN < hdrlen + max_linkhdr) &&
855 		    MHLEN >= hdrlen) {
856 			M_ALIGN(m, hdrlen);
857 		} else
858 #endif
859 		m->m_data += max_linkhdr;
860 		m->m_len = hdrlen;
861 	}
862 #endif
863 
864 	KASSERT(ipoptlen == 0, ("No IP options supported")); // samkumar
865 
866 	otMessage* message = tcplp_sys_new_message(tp->instance);
867 	if (message == NULL) {
868 		error = ENOBUFS;
869 		sack_rxmit = 0;
870 		goto out;
871 	}
872 	if (otMessageSetLength(message, sizeof(struct tcphdr) + optlen + len) != OT_ERROR_NONE) {
873 		tcplp_sys_free_message(tp->instance, message);
874 		error = ENOBUFS;
875 		sack_rxmit = 0;
876 		goto out;
877 	}
878 	if (len) {
879 	    uint32_t used_space = lbuf_used_space(&tp->sendbuf);
880 
881 		/*
882 		 * The TinyOS version has a way to avoid the copying we have to do here.
883 		 * Because it is possible to send iovecs directly in the BLIP stack, and
884 		 * an lbuf is made of iovecs, we could just "save" the starting and ending
885 		 * iovecs, modify them to get exactly the slice we want, call "send" on
886 		 * the resulting chain, and then restore the starting and ending iovecs
887 		 * once "send" returns.
888 		 *
889 		 * In RIOT, pktsnips have additional behavior regarding memory management
890 		 * that precludes this optimization. But, now that we have moved to
891 		 * cbufs, this is not relevant anymore.
892 		 */
893 		{
894 			otLinkedBuffer* start;
895 			size_t start_offset;
896 			otLinkedBuffer* end;
897 			size_t end_offset;
898 			otLinkedBuffer* curr;
899 			int rv = lbuf_getrange(&tp->sendbuf, off, len, &start, &start_offset, &end, &end_offset);
900 			size_t message_offset = otMessageGetOffset(message) + sizeof(struct tcphdr) + optlen;
901 			KASSERT(rv == 0, ("Reading send buffer out of range!"));
902 			for (curr = start; curr != end->mNext; curr = curr->mNext) {
903 				const uint8_t* data_to_copy = curr->mData;
904 				size_t length_to_copy = curr->mLength;
905 				if (curr == start) {
906 					data_to_copy += start_offset;
907 					length_to_copy -= start_offset;
908 				}
909 				if (curr == end) {
910 					length_to_copy -= end_offset;
911 				}
912 				otMessageWrite(message, message_offset, data_to_copy, length_to_copy);
913 				message_offset += length_to_copy;
914 			}
915 		}
916 
917 		/*
918 		 * If we're sending everything we've got, set PUSH.
919 		 * (This will keep happy those implementations which only
920 		 * give data to the user when a buffer fills or
921 		 * a PUSH comes in.)
922 		 */
923 		/* samkumar: Replaced call to sbused(&so->so_snd) with used_space. */
924 		if (off + len == used_space)
925 			flags |= TH_PUSH;
926 	}
927 
928 	char outbuf[sizeof(struct tcphdr) + TCP_MAXOLEN];
929 	th = (struct tcphdr*) (&outbuf[0]);
930 
931 	/*
932 	 * samkumar: I replaced the original call to tcpip_fillheaders with the
933 	 * one below.
934 	 */
935 	otMessageInfo ip6info;
936 	tcpip_fillheaders(tp, &ip6info, th);
937 
938 	/*
939 	 * Fill in fields, remembering maximum advertised
940 	 * window for use in delaying messages about window sizes.
941 	 * If resending a FIN, be sure not to use a new sequence number.
942 	 */
943 	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
944 	    tp->snd_nxt == tp->snd_max)
945 		tp->snd_nxt--;
946 	/*
947 	 * If we are starting a connection, send ECN setup
948 	 * SYN packet. If we are on a retransmit, we may
949 	 * resend those bits a number of times as per
950 	 * RFC 3168.
951 	 */
952 	if (tp->t_state == TCPS_SYN_SENT && V_tcp_do_ecn) {
953 		if (tp->t_rxtshift >= 1) {
954 			if (tp->t_rxtshift <= V_tcp_ecn_maxretries)
955 				flags |= TH_ECE|TH_CWR;
956 		} else
957 			flags |= TH_ECE|TH_CWR;
958 	}
959 
960 	/*
961 	 * samkumar: Make tcp_output reply with ECE flag in the SYN-ACK for
962 	 * ECN-enabled connections. The existing code in FreeBSD didn't have to do
963 	 * this, because it didn't use tcp_output to send the SYN-ACK; it
964 	 * constructed the SYN-ACK segment manually. Yet another consequnce of
965 	 * removing the SYN cache...
966 	 */
967 	if (tp->t_state == TCPS_SYN_RECEIVED && tp->t_flags & TF_ECN_PERMIT &&
968 		V_tcp_do_ecn) {
969 		flags |= TH_ECE;
970 	}
971 
972 	if (tp->t_state == TCPS_ESTABLISHED &&
973 	    (tp->t_flags & TF_ECN_PERMIT)) {
974 		/*
975 		 * If the peer has ECN, mark data packets with
976 		 * ECN capable transmission (ECT).
977 		 * Ignore pure ack packets, retransmissions and window probes.
978 		 */
979 		if (len > 0 && SEQ_GEQ(tp->snd_nxt, tp->snd_max) &&
980 		    !((tp->t_flags & TF_FORCEDATA) && len == 1)) {
981 			/*
982 			 * samkumar: Replaced ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
983 			 * with the following code, which will cause OpenThread to set the
984 			 * ECT0 bit in the header.
985 			 */
986 			ip6info.mEcn = OT_ECN_CAPABLE_0;
987 		}
988 
989 		/*
990 		 * Reply with proper ECN notifications.
991 		 */
992 		if (tp->t_flags & TF_ECN_SND_CWR) {
993 			flags |= TH_CWR;
994 			tp->t_flags &= ~TF_ECN_SND_CWR;
995 		}
996 		if (tp->t_flags & TF_ECN_SND_ECE)
997 			flags |= TH_ECE;
998 	}
999 
1000 	/*
1001 	 * If we are doing retransmissions, then snd_nxt will
1002 	 * not reflect the first unsent octet.  For ACK only
1003 	 * packets, we do not want the sequence number of the
1004 	 * retransmitted packet, we want the sequence number
1005 	 * of the next unsent octet.  So, if there is no data
1006 	 * (and no SYN or FIN), use snd_max instead of snd_nxt
1007 	 * when filling in ti_seq.  But if we are in persist
1008 	 * state, snd_max might reflect one byte beyond the
1009 	 * right edge of the window, so use snd_nxt in that
1010 	 * case, since we know we aren't doing a retransmission.
1011 	 * (retransmit and persist are mutually exclusive...)
1012 	 */
1013 	if (sack_rxmit == 0) {
1014 		if (len || (flags & (TH_SYN|TH_FIN)) ||
1015 		    tcp_timer_active(tp, TT_PERSIST))
1016 			th->th_seq = htonl(tp->snd_nxt);
1017 		else
1018 			th->th_seq = htonl(tp->snd_max);
1019 	} else {
1020 		th->th_seq = htonl(p->rxmit);
1021 		p->rxmit += len;
1022 		tp->sackhint.sack_bytes_rexmit += len;
1023 	}
1024 
1025 	/*
1026 	 * samkumar: Check if this is a retransmission (added as part of TCPlp).
1027 	 * This kind of stats collection is useful but not necessary for TCP, so
1028 	 * I've left it as a comment in case we want to bring this back to measure
1029 	 * performance.
1030 	 */
1031 #if 0
1032 	if (len > 0 && !tcp_timer_active(tp, TT_PERSIST) && SEQ_LT(ntohl(th->th_seq), tp->snd_max)) {
1033 		tcplp_totalRexmitCnt++;
1034 	}
1035 #endif
1036 
1037 	th->th_ack = htonl(tp->rcv_nxt);
1038 	if (optlen) {
1039 		bcopy(opt, th + 1, optlen);
1040 		th->th_off_x2 = ((sizeof (struct tcphdr) + optlen) >> 2) << TH_OFF_SHIFT;
1041 	}
1042 	th->th_flags = flags;
1043 	/*
1044 	 * Calculate receive window.  Don't shrink window,
1045 	 * but avoid silly window syndrome.
1046 	 */
1047 	/* samkumar: Replaced so->so_rcv.sb_hiwat with this call to cbuf_size. */
1048 	if (recwin < (long)(cbuf_size(&tp->recvbuf) / 4) &&
1049 	    recwin < (long)tp->t_maxseg)
1050 		recwin = 0;
1051 	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt) &&
1052 	    recwin < (long)(tp->rcv_adv - tp->rcv_nxt))
1053 		recwin = (long)(tp->rcv_adv - tp->rcv_nxt);
1054 	if (recwin > (long)TCP_MAXWIN << tp->rcv_scale)
1055 		recwin = (long)TCP_MAXWIN << tp->rcv_scale;
1056 
1057 	/*
1058 	 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1059 	 * or <SYN,ACK>) segment itself is never scaled.  The <SYN,ACK>
1060 	 * case is handled in syncache.
1061 	 */
1062 	if (flags & TH_SYN)
1063 		th->th_win = htons((uint16_t)
1064 				(min(cbuf_size(&tp->recvbuf), TCP_MAXWIN)));
1065 	else
1066 		th->th_win = htons((uint16_t)(recwin >> tp->rcv_scale));
1067 
1068 	/*
1069 	 * Adjust the RXWIN0SENT flag - indicate that we have advertised
1070 	 * a 0 window.  This may cause the remote transmitter to stall.  This
1071 	 * flag tells soreceive() to disable delayed acknowledgements when
1072 	 * draining the buffer.  This can occur if the receiver is attempting
1073 	 * to read more data than can be buffered prior to transmitting on
1074 	 * the connection.
1075 	 */
1076 	if (th->th_win == 0) {
1077 		tp->t_flags |= TF_RXWIN0SENT;
1078 	} else
1079 		tp->t_flags &= ~TF_RXWIN0SENT;
1080 	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
1081 		th->th_urp = htons((uint16_t)(tp->snd_up - tp->snd_nxt));
1082 		th->th_flags |= TH_URG;
1083 	} else
1084 		/*
1085 		 * If no urgent pointer to send, then we pull
1086 		 * the urgent pointer to the left edge of the send window
1087 		 * so that it doesn't drift into the send window on sequence
1088 		 * number wraparound.
1089 		 */
1090 		tp->snd_up = tp->snd_una;		/* drag it along */
1091 
1092 	/*
1093 	 * samkumar: Removed code for TCP signatures.
1094 	 */
1095 	/*
1096 	 * Put TCP length in extended header, and then
1097 	 * checksum extended header and data.
1098 	 */
1099 	/*
1100 	 * samkumar: The code to implement the above comment isn't relevant to us.
1101 	 * Checksum computation is not handled using FreeBSD code, so we don't need
1102 	 * to build an extended header.
1103 	 */
1104 	/*
1105 	 * samkumar: Removed code for TCP Segmentation Offloading.
1106 	 */
1107 	/* samkumar: Removed mbuf-specific assertions an debug code. */
1108 	/*
1109 	 * Fill in IP length and desired time to live and
1110 	 * send to IP level.  There should be a better way
1111 	 * to handle ttl and tos; we could keep them in
1112 	 * the template, but need a way to checksum without them.
1113 	 */
1114 	/*
1115 	 * m->m_pkthdr.len should have been set before checksum calculation,
1116 	 * because in6_cksum() need it.
1117 	 */
1118 	/*
1119 	 * samkumar: The IPv6 packet length and hop limit are handled by the host
1120 	 * network stack, not by TCPlp. I've also removed code for Path MTU
1121 	 * discovery. And of course, I've removed debug code as well.
1122 	 */
1123 	/* samkumar: I've replaced the call to ip6_output with the following. */
1124 	otMessageWrite(message, 0, outbuf, sizeof(struct tcphdr) + optlen);
1125 	tcplp_sys_send_message(tp->instance, message, &ip6info);
1126 
1127 out:
1128 	/*
1129 	 * In transmit state, time the transmission and arrange for
1130 	 * the retransmit.  In persist state, just set snd_max.
1131 	 */
1132 	if ((tp->t_flags & TF_FORCEDATA) == 0 ||
1133 	    !tcp_timer_active(tp, TT_PERSIST)) {
1134 		tcp_seq startseq = tp->snd_nxt;
1135 
1136 		/*
1137 		 * Advance snd_nxt over sequence space of this segment.
1138 		 */
1139 		if (flags & (TH_SYN|TH_FIN)) {
1140 			if (flags & TH_SYN)
1141 				tp->snd_nxt++;
1142 			if (flags & TH_FIN) {
1143 				tp->snd_nxt++;
1144 				tp->t_flags |= TF_SENTFIN;
1145 			}
1146 		}
1147 		if (sack_rxmit)
1148 			goto timer;
1149 		tp->snd_nxt += len;
1150 		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
1151 			tp->snd_max = tp->snd_nxt;
1152 			/*
1153 			 * Time this transmission if not a retransmission and
1154 			 * not currently timing anything.
1155 			 */
1156 			if (tp->t_rtttime == 0) {
1157 				tp->t_rtttime = ticks;
1158 				tp->t_rtseq = startseq;
1159 			}
1160 		}
1161 
1162 		/*
1163 		 * Set retransmit timer if not currently set,
1164 		 * and not doing a pure ack or a keep-alive probe.
1165 		 * Initial value for retransmit timer is smoothed
1166 		 * round-trip time + 2 * round-trip time variance.
1167 		 * Initialize shift counter which is used for backoff
1168 		 * of retransmit time.
1169 		 */
1170 timer:
1171 		if (!tcp_timer_active(tp, TT_REXMT) &&
1172 		    ((sack_rxmit && tp->snd_nxt != tp->snd_max) ||
1173 		     (tp->snd_nxt != tp->snd_una))) {
1174 			if (tcp_timer_active(tp, TT_PERSIST)) {
1175 				tcp_timer_activate(tp, TT_PERSIST, 0);
1176 				tp->t_rxtshift = 0;
1177 			}
1178 			tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1179 			/*
1180 			 * samkumar: Replaced sbavail(&so->so_snd) with this call to
1181 			 * lbuf_used_space.
1182 			 */
1183 		} else if (len == 0 && lbuf_used_space(&tp->sendbuf) &&
1184 		    !tcp_timer_active(tp, TT_REXMT) &&
1185 		    !tcp_timer_active(tp, TT_PERSIST)) {
1186 			/*
1187 			 * Avoid a situation where we do not set persist timer
1188 			 * after a zero window condition. For example:
1189 			 * 1) A -> B: packet with enough data to fill the window
1190 			 * 2) B -> A: ACK for #1 + new data (0 window
1191 			 *    advertisement)
1192 			 * 3) A -> B: ACK for #2, 0 len packet
1193 			 *
1194 			 * In this case, A will not activate the persist timer,
1195 			 * because it chose to send a packet. Unless tcp_output
1196 			 * is called for some other reason (delayed ack timer,
1197 			 * another input packet from B, socket syscall), A will
1198 			 * not send zero window probes.
1199 			 *
1200 			 * So, if you send a 0-length packet, but there is data
1201 			 * in the socket buffer, and neither the rexmt or
1202 			 * persist timer is already set, then activate the
1203 			 * persist timer.
1204 			 */
1205 			tp->t_rxtshift = 0;
1206 			tcp_setpersist(tp);
1207 		}
1208 	} else {
1209 		/*
1210 		 * Persist case, update snd_max but since we are in
1211 		 * persist mode (no window) we do not update snd_nxt.
1212 		 */
1213 		int xlen = len;
1214 		if (flags & TH_SYN)
1215 			++xlen;
1216 		if (flags & TH_FIN) {
1217 			++xlen;
1218 			tp->t_flags |= TF_SENTFIN;
1219 		}
1220 		if (SEQ_GT(tp->snd_nxt + xlen, tp->snd_max))
1221 			tp->snd_max = tp->snd_nxt + len;
1222 	}
1223 
1224 	if (error) {
1225 
1226 		/*
1227 		 * We know that the packet was lost, so back out the
1228 		 * sequence number advance, if any.
1229 		 *
1230 		 * If the error is EPERM the packet got blocked by the
1231 		 * local firewall.  Normally we should terminate the
1232 		 * connection but the blocking may have been spurious
1233 		 * due to a firewall reconfiguration cycle.  So we treat
1234 		 * it like a packet loss and let the retransmit timer and
1235 		 * timeouts do their work over time.
1236 		 * XXX: It is a POLA question whether calling tcp_drop right
1237 		 * away would be the really correct behavior instead.
1238 		 */
1239 		if (((tp->t_flags & TF_FORCEDATA) == 0 ||
1240 		    !tcp_timer_active(tp, TT_PERSIST)) &&
1241 		    ((flags & TH_SYN) == 0) &&
1242 		    (error != EPERM)) {
1243 			if (sack_rxmit) {
1244 				p->rxmit -= len;
1245 				tp->sackhint.sack_bytes_rexmit -= len;
1246 				KASSERT(tp->sackhint.sack_bytes_rexmit >= 0,
1247 				    ("sackhint bytes rtx >= 0"));
1248 			} else
1249 				tp->snd_nxt -= len;
1250 		}
1251 		switch (error) {
1252 		case EPERM:
1253 			tp->t_softerror = error;
1254 			return (error);
1255 		case ENOBUFS:
1256 	                if (!tcp_timer_active(tp, TT_REXMT) &&
1257 			    !tcp_timer_active(tp, TT_PERSIST))
1258 	                        tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
1259 			tp->snd_cwnd = tp->t_maxseg;
1260 #ifdef INSTRUMENT_TCP
1261 			tcplp_sys_log("TCP ALLOCFAIL %u %d", (unsigned int) tcplp_sys_get_millis(), (int) tp->snd_cwnd);
1262 #endif
1263 			return (0);
1264 		case EMSGSIZE:
1265 			/*
1266 			 * For some reason the interface we used initially
1267 			 * to send segments changed to another or lowered
1268 			 * its MTU.
1269 			 * If TSO was active we either got an interface
1270 			 * without TSO capabilits or TSO was turned off.
1271 			 * If we obtained mtu from ip_output() then update
1272 			 * it and try again.
1273 			 */
1274 			/* samkumar: Removed code for TCP Segmentation Offloading. */
1275 			if (mtu != 0) {
1276 				tcp_mss_update(tp, -1, mtu, NULL, NULL);
1277 				goto again;
1278 			}
1279 			return (error);
1280 		case EHOSTDOWN:
1281 		case EHOSTUNREACH:
1282 		case ENETDOWN:
1283 		case ENETUNREACH:
1284 			if (TCPS_HAVERCVDSYN(tp->t_state)) {
1285 				tp->t_softerror = error;
1286 				return (0);
1287 			}
1288 			/* FALLTHROUGH */
1289 		default:
1290 			return (error);
1291 		}
1292 	}
1293 
1294 	/*
1295 	 * Data sent (as far as we can tell).
1296 	 * If this advertises a larger window than any other segment,
1297 	 * then remember the size of the advertised window.
1298 	 * Any pending ACK has now been sent.
1299 	 */
1300 	if (recwin >= 0 && SEQ_GT(tp->rcv_nxt + recwin, tp->rcv_adv))
1301 		tp->rcv_adv = tp->rcv_nxt + recwin;
1302 	tp->last_ack_sent = tp->rcv_nxt;
1303 	tp->t_flags &= ~(TF_ACKNOW | TF_DELACK);
1304 	if (tcp_timer_active(tp, TT_DELACK))
1305 		tcp_timer_activate(tp, TT_DELACK, 0);
1306 
1307 	/*
1308 	 * samkumar: This was already commented out (using #if 0) in the original
1309 	 * FreeBSD code.
1310 	 */
1311 #if 0
1312 	/*
1313 	 * This completely breaks TCP if newreno is turned on.  What happens
1314 	 * is that if delayed-acks are turned on on the receiver, this code
1315 	 * on the transmitter effectively destroys the TCP window, forcing
1316 	 * it to four packets (1.5Kx4 = 6K window).
1317 	 */
1318 	if (sendalot && --maxburst)
1319 		goto again;
1320 #endif
1321 	if (sendalot)
1322 		goto again;
1323 	return (0);
1324 }
1325 
1326 /*
1327  * Insert TCP options according to the supplied parameters to the place
1328  * optp in a consistent way.  Can handle unaligned destinations.
1329  *
1330  * The order of the option processing is crucial for optimal packing and
1331  * alignment for the scarce option space.
1332  *
1333  * The optimal order for a SYN/SYN-ACK segment is:
1334  *   MSS (4) + NOP (1) + Window scale (3) + SACK permitted (2) +
1335  *   Timestamp (10) + Signature (18) = 38 bytes out of a maximum of 40.
1336  *
1337  * The SACK options should be last.  SACK blocks consume 8*n+2 bytes.
1338  * So a full size SACK blocks option is 34 bytes (with 4 SACK blocks).
1339  * At minimum we need 10 bytes (to generate 1 SACK block).  If both
1340  * TCP Timestamps (12 bytes) and TCP Signatures (18 bytes) are present,
1341  * we only have 10 bytes for SACK options (40 - (12 + 18)).
1342  */
1343 int
tcp_addoptions(struct tcpopt * to,uint8_t * optp)1344 tcp_addoptions(struct tcpopt *to, uint8_t *optp)
1345 {
1346 	uint32_t mask, optlen = 0;
1347 
1348 	for (mask = 1; mask < TOF_MAXOPT; mask <<= 1) {
1349 		if ((to->to_flags & mask) != mask)
1350 			continue;
1351 		if (optlen == TCP_MAXOLEN)
1352 			break;
1353 		switch (to->to_flags & mask) {
1354 		case TOF_MSS:
1355 			while (optlen % 4) {
1356 				optlen += TCPOLEN_NOP;
1357 				*optp++ = TCPOPT_NOP;
1358 			}
1359 			if (TCP_MAXOLEN - optlen < TCPOLEN_MAXSEG)
1360 				continue;
1361 			optlen += TCPOLEN_MAXSEG;
1362 			*optp++ = TCPOPT_MAXSEG;
1363 			*optp++ = TCPOLEN_MAXSEG;
1364 			to->to_mss = htons(to->to_mss);
1365 			bcopy((uint8_t *)&to->to_mss, optp, sizeof(to->to_mss));
1366 			optp += sizeof(to->to_mss);
1367 			break;
1368 		case TOF_SCALE:
1369 			while (!optlen || optlen % 2 != 1) {
1370 				optlen += TCPOLEN_NOP;
1371 				*optp++ = TCPOPT_NOP;
1372 			}
1373 			if (TCP_MAXOLEN - optlen < TCPOLEN_WINDOW)
1374 				continue;
1375 			optlen += TCPOLEN_WINDOW;
1376 			*optp++ = TCPOPT_WINDOW;
1377 			*optp++ = TCPOLEN_WINDOW;
1378 			*optp++ = to->to_wscale;
1379 			break;
1380 		case TOF_SACKPERM:
1381 			while (optlen % 2) {
1382 				optlen += TCPOLEN_NOP;
1383 				*optp++ = TCPOPT_NOP;
1384 			}
1385 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACK_PERMITTED)
1386 				continue;
1387 			optlen += TCPOLEN_SACK_PERMITTED;
1388 			*optp++ = TCPOPT_SACK_PERMITTED;
1389 			*optp++ = TCPOLEN_SACK_PERMITTED;
1390 			break;
1391 		case TOF_TS:
1392 			while (!optlen || optlen % 4 != 2) {
1393 				optlen += TCPOLEN_NOP;
1394 				*optp++ = TCPOPT_NOP;
1395 			}
1396 			if (TCP_MAXOLEN - optlen < TCPOLEN_TIMESTAMP)
1397 				continue;
1398 			optlen += TCPOLEN_TIMESTAMP;
1399 			*optp++ = TCPOPT_TIMESTAMP;
1400 			*optp++ = TCPOLEN_TIMESTAMP;
1401 			to->to_tsval = htonl(to->to_tsval);
1402 			to->to_tsecr = htonl(to->to_tsecr);
1403 			bcopy((uint8_t *)&to->to_tsval, optp, sizeof(to->to_tsval));
1404 			optp += sizeof(to->to_tsval);
1405 			bcopy((uint8_t *)&to->to_tsecr, optp, sizeof(to->to_tsecr));
1406 			optp += sizeof(to->to_tsecr);
1407 			break;
1408 		case TOF_SIGNATURE:
1409 			{
1410 			int siglen = TCPOLEN_SIGNATURE - 2;
1411 
1412 			while (!optlen || optlen % 4 != 2) {
1413 				optlen += TCPOLEN_NOP;
1414 				*optp++ = TCPOPT_NOP;
1415 			}
1416 			if (TCP_MAXOLEN - optlen < TCPOLEN_SIGNATURE)
1417 				continue;
1418 			optlen += TCPOLEN_SIGNATURE;
1419 			*optp++ = TCPOPT_SIGNATURE;
1420 			*optp++ = TCPOLEN_SIGNATURE;
1421 			to->to_signature = optp;
1422 			while (siglen--)
1423 				 *optp++ = 0;
1424 			break;
1425 			}
1426 		case TOF_SACK:
1427 			{
1428 			int sackblks = 0;
1429 			struct sackblk *sack = (struct sackblk *)to->to_sacks;
1430 			tcp_seq sack_seq;
1431 
1432 			while (!optlen || optlen % 4 != 2) {
1433 				optlen += TCPOLEN_NOP;
1434 				*optp++ = TCPOPT_NOP;
1435 			}
1436 			if (TCP_MAXOLEN - optlen < TCPOLEN_SACKHDR + TCPOLEN_SACK)
1437 				continue;
1438 			optlen += TCPOLEN_SACKHDR;
1439 			*optp++ = TCPOPT_SACK;
1440 			sackblks = min(to->to_nsacks,
1441 					(TCP_MAXOLEN - optlen) / TCPOLEN_SACK);
1442 			*optp++ = TCPOLEN_SACKHDR + sackblks * TCPOLEN_SACK;
1443 			while (sackblks--) {
1444 				sack_seq = htonl(sack->start);
1445 				bcopy((uint8_t *)&sack_seq, optp, sizeof(sack_seq));
1446 				optp += sizeof(sack_seq);
1447 				sack_seq = htonl(sack->end);
1448 				bcopy((uint8_t *)&sack_seq, optp, sizeof(sack_seq));
1449 				optp += sizeof(sack_seq);
1450 				optlen += TCPOLEN_SACK;
1451 				sack++;
1452 			}
1453 			/* samkumar: Removed TCPSTAT_INC(tcps_sack_send_blocks); */
1454 			break;
1455 			}
1456 		default:
1457 			tcplp_sys_panic("PANIC: %s: unknown TCP option type", __func__);
1458 			break;
1459 		}
1460 	}
1461 
1462 	/* Terminate and pad TCP options to a 4 byte boundary. */
1463 	if (optlen % 4) {
1464 		optlen += TCPOLEN_EOL;
1465 		*optp++ = TCPOPT_EOL;
1466 	}
1467 	/*
1468 	 * According to RFC 793 (STD0007):
1469 	 *   "The content of the header beyond the End-of-Option option
1470 	 *    must be header padding (i.e., zero)."
1471 	 *   and later: "The padding is composed of zeros."
1472 	 */
1473 	while (optlen % 4) {
1474 		optlen += TCPOLEN_PAD;
1475 		*optp++ = TCPOPT_PAD;
1476 	}
1477 
1478 	KASSERT(optlen <= TCP_MAXOLEN, ("%s: TCP options too long", __func__));
1479 	return (optlen);
1480 }
1481