xref: /freebsd/sys/netinet/tcp_sack.c (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
5  *	The Regents of the University of California.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)tcp_sack.c	8.12 (Berkeley) 5/24/95
33  */
34 
35 /*-
36  *	@@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
37  *
38  * NRL grants permission for redistribution and use in source and binary
39  * forms, with or without modification, of the software and documentation
40  * created at NRL provided that the following conditions are met:
41  *
42  * 1. Redistributions of source code must retain the above copyright
43  *    notice, this list of conditions and the following disclaimer.
44  * 2. Redistributions in binary form must reproduce the above copyright
45  *    notice, this list of conditions and the following disclaimer in the
46  *    documentation and/or other materials provided with the distribution.
47  * 3. All advertising materials mentioning features or use of this software
48  *    must display the following acknowledgements:
49  *	This product includes software developed by the University of
50  *	California, Berkeley and its contributors.
51  *	This product includes software developed at the Information
52  *	Technology Division, US Naval Research Laboratory.
53  * 4. Neither the name of the NRL nor the names of its contributors
54  *    may be used to endorse or promote products derived from this software
55  *    without specific prior written permission.
56  *
57  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
58  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
59  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
60  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
61  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
62  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
63  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
64  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
65  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
66  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
67  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
68  *
69  * The views and conclusions contained in the software and documentation
70  * are those of the authors and should not be interpreted as representing
71  * official policies, either expressed or implied, of the US Naval
72  * Research Laboratory (NRL).
73  */
74 
75 #include <sys/cdefs.h>
76 __FBSDID("$FreeBSD$");
77 
78 #include "opt_inet.h"
79 #include "opt_inet6.h"
80 #include "opt_tcpdebug.h"
81 
82 #include <sys/param.h>
83 #include <sys/systm.h>
84 #include <sys/kernel.h>
85 #include <sys/sysctl.h>
86 #include <sys/malloc.h>
87 #include <sys/mbuf.h>
88 #include <sys/proc.h>		/* for proc0 declaration */
89 #include <sys/protosw.h>
90 #include <sys/socket.h>
91 #include <sys/socketvar.h>
92 #include <sys/syslog.h>
93 #include <sys/systm.h>
94 
95 #include <machine/cpu.h>	/* before tcp_seq.h, for tcp_random18() */
96 
97 #include <vm/uma.h>
98 
99 #include <net/if.h>
100 #include <net/if_var.h>
101 #include <net/route.h>
102 #include <net/vnet.h>
103 
104 #include <netinet/in.h>
105 #include <netinet/in_systm.h>
106 #include <netinet/ip.h>
107 #include <netinet/in_var.h>
108 #include <netinet/in_pcb.h>
109 #include <netinet/ip_var.h>
110 #include <netinet/ip6.h>
111 #include <netinet/icmp6.h>
112 #include <netinet6/nd6.h>
113 #include <netinet6/ip6_var.h>
114 #include <netinet6/in6_pcb.h>
115 #include <netinet/tcp.h>
116 #include <netinet/tcp_fsm.h>
117 #include <netinet/tcp_seq.h>
118 #include <netinet/tcp_timer.h>
119 #include <netinet/tcp_var.h>
120 #include <netinet/tcpip.h>
121 #include <netinet/cc/cc.h>
122 #ifdef TCPDEBUG
123 #include <netinet/tcp_debug.h>
124 #endif /* TCPDEBUG */
125 
126 #include <machine/in_cksum.h>
127 
128 VNET_DECLARE(struct uma_zone *, sack_hole_zone);
129 #define	V_sack_hole_zone		VNET(sack_hole_zone)
130 
131 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
132     "TCP SACK");
133 
134 VNET_DEFINE(int, tcp_do_sack) = 1;
135 SYSCTL_INT(_net_inet_tcp_sack, OID_AUTO, enable, CTLFLAG_VNET | CTLFLAG_RW,
136     &VNET_NAME(tcp_do_sack), 0,
137     "Enable/Disable TCP SACK support");
138 
139 VNET_DEFINE(int, tcp_do_newsack) = 1;
140 SYSCTL_INT(_net_inet_tcp_sack, OID_AUTO, revised, CTLFLAG_VNET | CTLFLAG_RW,
141     &VNET_NAME(tcp_do_newsack), 0,
142     "Use revised SACK loss recovery per RFC 6675");
143 
144 VNET_DEFINE(int, tcp_sack_maxholes) = 128;
145 SYSCTL_INT(_net_inet_tcp_sack, OID_AUTO, maxholes, CTLFLAG_VNET | CTLFLAG_RW,
146     &VNET_NAME(tcp_sack_maxholes), 0,
147     "Maximum number of TCP SACK holes allowed per connection");
148 
149 VNET_DEFINE(int, tcp_sack_globalmaxholes) = 65536;
150 SYSCTL_INT(_net_inet_tcp_sack, OID_AUTO, globalmaxholes, CTLFLAG_VNET | CTLFLAG_RW,
151     &VNET_NAME(tcp_sack_globalmaxholes), 0,
152     "Global maximum number of TCP SACK holes");
153 
154 VNET_DEFINE(int, tcp_sack_globalholes) = 0;
155 SYSCTL_INT(_net_inet_tcp_sack, OID_AUTO, globalholes, CTLFLAG_VNET | CTLFLAG_RD,
156     &VNET_NAME(tcp_sack_globalholes), 0,
157     "Global number of TCP SACK holes currently allocated");
158 
159 int
160 tcp_dsack_block_exists(struct tcpcb *tp)
161 {
162 	/* Return true if a DSACK block exists */
163 	if (tp->rcv_numsacks == 0)
164 		return (0);
165 	if (SEQ_LEQ(tp->sackblks[0].end, tp->rcv_nxt))
166 		return(1);
167 	return (0);
168 }
169 
170 /*
171  * This function will find overlaps with the currently stored sackblocks
172  * and add any overlap as a dsack block upfront
173  */
174 void
175 tcp_update_dsack_list(struct tcpcb *tp, tcp_seq rcv_start, tcp_seq rcv_end)
176 {
177 	struct sackblk head_blk,mid_blk,saved_blks[MAX_SACK_BLKS];
178 	int i, j, n, identical;
179 	tcp_seq start, end;
180 
181 	INP_WLOCK_ASSERT(tp->t_inpcb);
182 
183 	KASSERT(SEQ_LT(rcv_start, rcv_end), ("rcv_start < rcv_end"));
184 
185 	if (SEQ_LT(rcv_end, tp->rcv_nxt) ||
186 	    ((rcv_end == tp->rcv_nxt) &&
187 	     (tp->rcv_numsacks > 0 ) &&
188 	     (tp->sackblks[0].end == tp->rcv_nxt))) {
189 		saved_blks[0].start = rcv_start;
190 		saved_blks[0].end = rcv_end;
191 	} else {
192 		saved_blks[0].start = saved_blks[0].end = 0;
193 	}
194 
195 	head_blk.start = head_blk.end = 0;
196 	mid_blk.start = rcv_start;
197 	mid_blk.end = rcv_end;
198 	identical = 0;
199 
200 	for (i = 0; i < tp->rcv_numsacks; i++) {
201 		start = tp->sackblks[i].start;
202 		end = tp->sackblks[i].end;
203 		if (SEQ_LT(rcv_end, start)) {
204 			/* pkt left to sack blk */
205 			continue;
206 		}
207 		if (SEQ_GT(rcv_start, end)) {
208 			/* pkt right to sack blk */
209 			continue;
210 		}
211 		if (SEQ_GT(tp->rcv_nxt, end)) {
212 			if ((SEQ_MAX(rcv_start, start) != SEQ_MIN(rcv_end, end)) &&
213 			    (SEQ_GT(head_blk.start, SEQ_MAX(rcv_start, start)) ||
214 			    (head_blk.start == head_blk.end))) {
215 				head_blk.start = SEQ_MAX(rcv_start, start);
216 				head_blk.end = SEQ_MIN(rcv_end, end);
217 			}
218 			continue;
219 		}
220 		if (((head_blk.start == head_blk.end) ||
221 		     SEQ_LT(start, head_blk.start)) &&
222 		     (SEQ_GT(end, rcv_start) &&
223 		      SEQ_LEQ(start, rcv_end))) {
224 			head_blk.start = start;
225 			head_blk.end = end;
226 		}
227 		mid_blk.start = SEQ_MIN(mid_blk.start, start);
228 		mid_blk.end = SEQ_MAX(mid_blk.end, end);
229 		if ((mid_blk.start == start) &&
230 		    (mid_blk.end == end))
231 			identical = 1;
232 	}
233 	if (SEQ_LT(head_blk.start, head_blk.end)) {
234 		/* store overlapping range */
235 		saved_blks[0].start = SEQ_MAX(rcv_start, head_blk.start);
236 		saved_blks[0].end   = SEQ_MIN(rcv_end, head_blk.end);
237 	}
238 	n = 1;
239 	/*
240 	 * Second, if not ACKed, store the SACK block that
241 	 * overlaps with the DSACK block unless it is identical
242 	 */
243 	if ((SEQ_LT(tp->rcv_nxt, mid_blk.end) &&
244 	    !((mid_blk.start == saved_blks[0].start) &&
245 	    (mid_blk.end == saved_blks[0].end))) ||
246 	    identical == 1) {
247 		saved_blks[n].start = mid_blk.start;
248 		saved_blks[n++].end = mid_blk.end;
249 	}
250 	for (j = 0; (j < tp->rcv_numsacks) && (n < MAX_SACK_BLKS); j++) {
251 		if (((SEQ_LT(tp->sackblks[j].end, mid_blk.start) ||
252 		      SEQ_GT(tp->sackblks[j].start, mid_blk.end)) &&
253 		    (SEQ_GT(tp->sackblks[j].start, tp->rcv_nxt))))
254 		saved_blks[n++] = tp->sackblks[j];
255 	}
256 	j = 0;
257 	for (i = 0; i < n; i++) {
258 		/* we can end up with a stale initial entry */
259 		if (SEQ_LT(saved_blks[i].start, saved_blks[i].end)) {
260 			tp->sackblks[j++] = saved_blks[i];
261 		}
262 	}
263 	tp->rcv_numsacks = j;
264 }
265 
266 /*
267  * This function is called upon receipt of new valid data (while not in
268  * header prediction mode), and it updates the ordered list of sacks.
269  */
270 void
271 tcp_update_sack_list(struct tcpcb *tp, tcp_seq rcv_start, tcp_seq rcv_end)
272 {
273 	/*
274 	 * First reported block MUST be the most recent one.  Subsequent
275 	 * blocks SHOULD be in the order in which they arrived at the
276 	 * receiver.  These two conditions make the implementation fully
277 	 * compliant with RFC 2018.
278 	 */
279 	struct sackblk head_blk, saved_blks[MAX_SACK_BLKS];
280 	int num_head, num_saved, i;
281 
282 	INP_WLOCK_ASSERT(tp->t_inpcb);
283 
284 	/* Check arguments. */
285 	KASSERT(SEQ_LEQ(rcv_start, rcv_end), ("rcv_start <= rcv_end"));
286 
287 	if ((rcv_start == rcv_end) &&
288 	    (tp->rcv_numsacks >= 1) &&
289 	    (rcv_end == tp->sackblks[0].end)) {
290 		/* retaining DSACK block below rcv_nxt (todrop) */
291 		head_blk = tp->sackblks[0];
292 	} else {
293 		/* SACK block for the received segment. */
294 		head_blk.start = rcv_start;
295 		head_blk.end = rcv_end;
296 	}
297 
298 	/*
299 	 * Merge updated SACK blocks into head_blk, and save unchanged SACK
300 	 * blocks into saved_blks[].  num_saved will have the number of the
301 	 * saved SACK blocks.
302 	 */
303 	num_saved = 0;
304 	for (i = 0; i < tp->rcv_numsacks; i++) {
305 		tcp_seq start = tp->sackblks[i].start;
306 		tcp_seq end = tp->sackblks[i].end;
307 		if (SEQ_GEQ(start, end) || SEQ_LEQ(start, tp->rcv_nxt)) {
308 			/*
309 			 * Discard this SACK block.
310 			 */
311 		} else if (SEQ_LEQ(head_blk.start, end) &&
312 			   SEQ_GEQ(head_blk.end, start)) {
313 			/*
314 			 * Merge this SACK block into head_blk.  This SACK
315 			 * block itself will be discarded.
316 			 */
317 			/*
318 			 * |-|
319 			 *   |---|  merge
320 			 *
321 			 *     |-|
322 			 * |---|    merge
323 			 *
324 			 * |-----|
325 			 *   |-|    DSACK smaller
326 			 *
327 			 *   |-|
328 			 * |-----|  DSACK smaller
329 			 */
330 			if (head_blk.start == end)
331 				head_blk.start = start;
332 			else if (head_blk.end == start)
333 				head_blk.end = end;
334 			else {
335 				if (SEQ_LT(head_blk.start, start)) {
336 					tcp_seq temp = start;
337 					start = head_blk.start;
338 					head_blk.start = temp;
339 				}
340 				if (SEQ_GT(head_blk.end, end)) {
341 					tcp_seq temp = end;
342 					end = head_blk.end;
343 					head_blk.end = temp;
344 				}
345 				if ((head_blk.start != start) ||
346 				    (head_blk.end != end)) {
347 					if ((num_saved >= 1) &&
348 					   SEQ_GEQ(saved_blks[num_saved-1].start, start) &&
349 					   SEQ_LEQ(saved_blks[num_saved-1].end, end))
350 						num_saved--;
351 					saved_blks[num_saved].start = start;
352 					saved_blks[num_saved].end = end;
353 					num_saved++;
354 				}
355 			}
356 		} else {
357 			/*
358 			 * This block supercedes the prior block
359 			 */
360 			if ((num_saved >= 1) &&
361 			   SEQ_GEQ(saved_blks[num_saved-1].start, start) &&
362 			   SEQ_LEQ(saved_blks[num_saved-1].end, end))
363 				num_saved--;
364 			/*
365 			 * Save this SACK block.
366 			 */
367 			saved_blks[num_saved].start = start;
368 			saved_blks[num_saved].end = end;
369 			num_saved++;
370 		}
371 	}
372 
373 	/*
374 	 * Update SACK list in tp->sackblks[].
375 	 */
376 	num_head = 0;
377 	if (SEQ_LT(rcv_start, rcv_end)) {
378 		/*
379 		 * The received data segment is an out-of-order segment.  Put
380 		 * head_blk at the top of SACK list.
381 		 */
382 		tp->sackblks[0] = head_blk;
383 		num_head = 1;
384 		/*
385 		 * If the number of saved SACK blocks exceeds its limit,
386 		 * discard the last SACK block.
387 		 */
388 		if (num_saved >= MAX_SACK_BLKS)
389 			num_saved--;
390 	}
391 	if ((rcv_start == rcv_end) &&
392 	    (rcv_start == tp->sackblks[0].end)) {
393 		num_head = 1;
394 	}
395 	if (num_saved > 0) {
396 		/*
397 		 * Copy the saved SACK blocks back.
398 		 */
399 		bcopy(saved_blks, &tp->sackblks[num_head],
400 		      sizeof(struct sackblk) * num_saved);
401 	}
402 
403 	/* Save the number of SACK blocks. */
404 	tp->rcv_numsacks = num_head + num_saved;
405 }
406 
407 void
408 tcp_clean_dsack_blocks(struct tcpcb *tp)
409 {
410 	struct sackblk saved_blks[MAX_SACK_BLKS];
411 	int num_saved, i;
412 
413 	INP_WLOCK_ASSERT(tp->t_inpcb);
414 	/*
415 	 * Clean up any DSACK blocks that
416 	 * are in our queue of sack blocks.
417 	 *
418 	 */
419 	num_saved = 0;
420 	for (i = 0; i < tp->rcv_numsacks; i++) {
421 		tcp_seq start = tp->sackblks[i].start;
422 		tcp_seq end = tp->sackblks[i].end;
423 		if (SEQ_GEQ(start, end) || SEQ_LEQ(start, tp->rcv_nxt)) {
424 			/*
425 			 * Discard this D-SACK block.
426 			 */
427 			continue;
428 		}
429 		/*
430 		 * Save this SACK block.
431 		 */
432 		saved_blks[num_saved].start = start;
433 		saved_blks[num_saved].end = end;
434 		num_saved++;
435 	}
436 	if (num_saved > 0) {
437 		/*
438 		 * Copy the saved SACK blocks back.
439 		 */
440 		bcopy(saved_blks, &tp->sackblks[0],
441 		      sizeof(struct sackblk) * num_saved);
442 	}
443 	tp->rcv_numsacks = num_saved;
444 }
445 
446 /*
447  * Delete all receiver-side SACK information.
448  */
449 void
450 tcp_clean_sackreport(struct tcpcb *tp)
451 {
452 	int i;
453 
454 	INP_WLOCK_ASSERT(tp->t_inpcb);
455 	tp->rcv_numsacks = 0;
456 	for (i = 0; i < MAX_SACK_BLKS; i++)
457 		tp->sackblks[i].start = tp->sackblks[i].end=0;
458 }
459 
460 /*
461  * Allocate struct sackhole.
462  */
463 static struct sackhole *
464 tcp_sackhole_alloc(struct tcpcb *tp, tcp_seq start, tcp_seq end)
465 {
466 	struct sackhole *hole;
467 
468 	if (tp->snd_numholes >= V_tcp_sack_maxholes ||
469 	    V_tcp_sack_globalholes >= V_tcp_sack_globalmaxholes) {
470 		TCPSTAT_INC(tcps_sack_sboverflow);
471 		return NULL;
472 	}
473 
474 	hole = (struct sackhole *)uma_zalloc(V_sack_hole_zone, M_NOWAIT);
475 	if (hole == NULL)
476 		return NULL;
477 
478 	hole->start = start;
479 	hole->end = end;
480 	hole->rxmit = start;
481 
482 	tp->snd_numholes++;
483 	atomic_add_int(&V_tcp_sack_globalholes, 1);
484 
485 	return hole;
486 }
487 
488 /*
489  * Free struct sackhole.
490  */
491 static void
492 tcp_sackhole_free(struct tcpcb *tp, struct sackhole *hole)
493 {
494 
495 	uma_zfree(V_sack_hole_zone, hole);
496 
497 	tp->snd_numholes--;
498 	atomic_subtract_int(&V_tcp_sack_globalholes, 1);
499 
500 	KASSERT(tp->snd_numholes >= 0, ("tp->snd_numholes >= 0"));
501 	KASSERT(V_tcp_sack_globalholes >= 0, ("tcp_sack_globalholes >= 0"));
502 }
503 
504 /*
505  * Insert new SACK hole into scoreboard.
506  */
507 static struct sackhole *
508 tcp_sackhole_insert(struct tcpcb *tp, tcp_seq start, tcp_seq end,
509     struct sackhole *after)
510 {
511 	struct sackhole *hole;
512 
513 	/* Allocate a new SACK hole. */
514 	hole = tcp_sackhole_alloc(tp, start, end);
515 	if (hole == NULL)
516 		return NULL;
517 
518 	/* Insert the new SACK hole into scoreboard. */
519 	if (after != NULL)
520 		TAILQ_INSERT_AFTER(&tp->snd_holes, after, hole, scblink);
521 	else
522 		TAILQ_INSERT_TAIL(&tp->snd_holes, hole, scblink);
523 
524 	/* Update SACK hint. */
525 	if (tp->sackhint.nexthole == NULL)
526 		tp->sackhint.nexthole = hole;
527 
528 	return hole;
529 }
530 
531 /*
532  * Remove SACK hole from scoreboard.
533  */
534 static void
535 tcp_sackhole_remove(struct tcpcb *tp, struct sackhole *hole)
536 {
537 
538 	/* Update SACK hint. */
539 	if (tp->sackhint.nexthole == hole)
540 		tp->sackhint.nexthole = TAILQ_NEXT(hole, scblink);
541 
542 	/* Remove this SACK hole. */
543 	TAILQ_REMOVE(&tp->snd_holes, hole, scblink);
544 
545 	/* Free this SACK hole. */
546 	tcp_sackhole_free(tp, hole);
547 }
548 
549 /*
550  * Process cumulative ACK and the TCP SACK option to update the scoreboard.
551  * tp->snd_holes is an ordered list of holes (oldest to newest, in terms of
552  * the sequence space).
553  * Returns 1 if incoming ACK has previously unknown SACK information,
554  * 0 otherwise.
555  */
556 int
557 tcp_sack_doack(struct tcpcb *tp, struct tcpopt *to, tcp_seq th_ack)
558 {
559 	struct sackhole *cur, *temp;
560 	struct sackblk sack, sack_blocks[TCP_MAX_SACK + 1], *sblkp;
561 	int i, j, num_sack_blks, sack_changed;
562 	int delivered_data, left_edge_delta;
563 
564 	INP_WLOCK_ASSERT(tp->t_inpcb);
565 
566 	num_sack_blks = 0;
567 	sack_changed = 0;
568 	delivered_data = 0;
569 	left_edge_delta = 0;
570 	/*
571 	 * If SND.UNA will be advanced by SEG.ACK, and if SACK holes exist,
572 	 * treat [SND.UNA, SEG.ACK) as if it is a SACK block.
573 	 * Account changes to SND.UNA always in delivered data.
574 	 */
575 	if (SEQ_LT(tp->snd_una, th_ack) && !TAILQ_EMPTY(&tp->snd_holes)) {
576 		left_edge_delta = th_ack - tp->snd_una;
577 		sack_blocks[num_sack_blks].start = tp->snd_una;
578 		sack_blocks[num_sack_blks++].end = th_ack;
579 		/*
580 		 * Pulling snd_fack forward if we got here
581 		 * due to DSACK blocks
582 		 */
583 		if (SEQ_LT(tp->snd_fack, th_ack)) {
584 			delivered_data += th_ack - tp->snd_una;
585 			tp->snd_fack = th_ack;
586 			sack_changed = 1;
587 		}
588 	}
589 	/*
590 	 * Append received valid SACK blocks to sack_blocks[], but only if we
591 	 * received new blocks from the other side.
592 	 */
593 	if (to->to_flags & TOF_SACK) {
594 		for (i = 0; i < to->to_nsacks; i++) {
595 			bcopy((to->to_sacks + i * TCPOLEN_SACK),
596 			    &sack, sizeof(sack));
597 			sack.start = ntohl(sack.start);
598 			sack.end = ntohl(sack.end);
599 			if (SEQ_GT(sack.end, sack.start) &&
600 			    SEQ_GT(sack.start, tp->snd_una) &&
601 			    SEQ_GT(sack.start, th_ack) &&
602 			    SEQ_LT(sack.start, tp->snd_max) &&
603 			    SEQ_GT(sack.end, tp->snd_una) &&
604 			    SEQ_LEQ(sack.end, tp->snd_max)) {
605 				sack_blocks[num_sack_blks++] = sack;
606 			} else if (SEQ_LEQ(sack.start, th_ack) &&
607 			    SEQ_LEQ(sack.end, th_ack)) {
608 				/*
609 				 * Its a D-SACK block.
610 				 */
611 				tcp_record_dsack(tp, sack.start, sack.end, 0);
612 			}
613 		}
614 	}
615 	/*
616 	 * Return if SND.UNA is not advanced and no valid SACK block is
617 	 * received.
618 	 */
619 	if (num_sack_blks == 0)
620 		return (sack_changed);
621 
622 	/*
623 	 * Sort the SACK blocks so we can update the scoreboard with just one
624 	 * pass. The overhead of sorting up to 4+1 elements is less than
625 	 * making up to 4+1 passes over the scoreboard.
626 	 */
627 	for (i = 0; i < num_sack_blks; i++) {
628 		for (j = i + 1; j < num_sack_blks; j++) {
629 			if (SEQ_GT(sack_blocks[i].end, sack_blocks[j].end)) {
630 				sack = sack_blocks[i];
631 				sack_blocks[i] = sack_blocks[j];
632 				sack_blocks[j] = sack;
633 			}
634 		}
635 	}
636 	if (TAILQ_EMPTY(&tp->snd_holes)) {
637 		/*
638 		 * Empty scoreboard. Need to initialize snd_fack (it may be
639 		 * uninitialized or have a bogus value). Scoreboard holes
640 		 * (from the sack blocks received) are created later below
641 		 * (in the logic that adds holes to the tail of the
642 		 * scoreboard).
643 		 */
644 		tp->snd_fack = SEQ_MAX(tp->snd_una, th_ack);
645 		tp->sackhint.sacked_bytes = 0;	/* reset */
646 	}
647 	/*
648 	 * In the while-loop below, incoming SACK blocks (sack_blocks[]) and
649 	 * SACK holes (snd_holes) are traversed from their tails with just
650 	 * one pass in order to reduce the number of compares especially when
651 	 * the bandwidth-delay product is large.
652 	 *
653 	 * Note: Typically, in the first RTT of SACK recovery, the highest
654 	 * three or four SACK blocks with the same ack number are received.
655 	 * In the second RTT, if retransmitted data segments are not lost,
656 	 * the highest three or four SACK blocks with ack number advancing
657 	 * are received.
658 	 */
659 	sblkp = &sack_blocks[num_sack_blks - 1];	/* Last SACK block */
660 	tp->sackhint.last_sack_ack = sblkp->end;
661 	if (SEQ_LT(tp->snd_fack, sblkp->start)) {
662 		/*
663 		 * The highest SACK block is beyond fack.  First,
664 		 * check if there was a successful Rescue Retransmission,
665 		 * and move this hole left. With normal holes, snd_fack
666 		 * is always to the right of the end.
667 		 */
668 		if (((temp = TAILQ_LAST(&tp->snd_holes, sackhole_head)) != NULL) &&
669 		    SEQ_LEQ(tp->snd_fack,temp->end)) {
670 			temp->start = SEQ_MAX(tp->snd_fack, SEQ_MAX(tp->snd_una, th_ack));
671 			temp->end = sblkp->start;
672 			temp->rxmit = temp->start;
673 			delivered_data += sblkp->end - sblkp->start;
674 			tp->snd_fack = sblkp->end;
675 			sblkp--;
676 			sack_changed = 1;
677 		} else {
678 			/*
679 			 * Append a new SACK hole at the tail.  If the
680 			 * second or later highest SACK blocks are also
681 			 * beyond the current fack, they will be inserted
682 			 * by way of hole splitting in the while-loop below.
683 			 */
684 			temp = tcp_sackhole_insert(tp, tp->snd_fack,sblkp->start,NULL);
685 			if (temp != NULL) {
686 				delivered_data += sblkp->end - sblkp->start;
687 				tp->snd_fack = sblkp->end;
688 				/* Go to the previous sack block. */
689 				sblkp--;
690 				sack_changed = 1;
691 			} else {
692 				/*
693 				 * We failed to add a new hole based on the current
694 				 * sack block.  Skip over all the sack blocks that
695 				 * fall completely to the right of snd_fack and
696 				 * proceed to trim the scoreboard based on the
697 				 * remaining sack blocks.  This also trims the
698 				 * scoreboard for th_ack (which is sack_blocks[0]).
699 				 */
700 				while (sblkp >= sack_blocks &&
701 				       SEQ_LT(tp->snd_fack, sblkp->start))
702 					sblkp--;
703 				if (sblkp >= sack_blocks &&
704 				    SEQ_LT(tp->snd_fack, sblkp->end)) {
705 					delivered_data += sblkp->end - tp->snd_fack;
706 					tp->snd_fack = sblkp->end;
707 					sack_changed = 1;
708 				}
709 			}
710 		}
711 	} else if (SEQ_LT(tp->snd_fack, sblkp->end)) {
712 		/* fack is advanced. */
713 		delivered_data += sblkp->end - tp->snd_fack;
714 		tp->snd_fack = sblkp->end;
715 		sack_changed = 1;
716 	}
717 	cur = TAILQ_LAST(&tp->snd_holes, sackhole_head); /* Last SACK hole. */
718 	/*
719 	 * Since the incoming sack blocks are sorted, we can process them
720 	 * making one sweep of the scoreboard.
721 	 */
722 	while (sblkp >= sack_blocks  && cur != NULL) {
723 		if (SEQ_GEQ(sblkp->start, cur->end)) {
724 			/*
725 			 * SACKs data beyond the current hole.  Go to the
726 			 * previous sack block.
727 			 */
728 			sblkp--;
729 			continue;
730 		}
731 		if (SEQ_LEQ(sblkp->end, cur->start)) {
732 			/*
733 			 * SACKs data before the current hole.  Go to the
734 			 * previous hole.
735 			 */
736 			cur = TAILQ_PREV(cur, sackhole_head, scblink);
737 			continue;
738 		}
739 		tp->sackhint.sack_bytes_rexmit -=
740 		    (SEQ_MIN(cur->rxmit, cur->end) - cur->start);
741 		KASSERT(tp->sackhint.sack_bytes_rexmit >= 0,
742 		    ("sackhint bytes rtx >= 0"));
743 		sack_changed = 1;
744 		if (SEQ_LEQ(sblkp->start, cur->start)) {
745 			/* Data acks at least the beginning of hole. */
746 			if (SEQ_GEQ(sblkp->end, cur->end)) {
747 				/* Acks entire hole, so delete hole. */
748 				delivered_data += (cur->end - cur->start);
749 				temp = cur;
750 				cur = TAILQ_PREV(cur, sackhole_head, scblink);
751 				tcp_sackhole_remove(tp, temp);
752 				/*
753 				 * The sack block may ack all or part of the
754 				 * next hole too, so continue onto the next
755 				 * hole.
756 				 */
757 				continue;
758 			} else {
759 				/* Move start of hole forward. */
760 				delivered_data += (sblkp->end - cur->start);
761 				cur->start = sblkp->end;
762 				cur->rxmit = SEQ_MAX(cur->rxmit, cur->start);
763 			}
764 		} else {
765 			/* Data acks at least the end of hole. */
766 			if (SEQ_GEQ(sblkp->end, cur->end)) {
767 				/* Move end of hole backward. */
768 				delivered_data += (cur->end - sblkp->start);
769 				cur->end = sblkp->start;
770 				cur->rxmit = SEQ_MIN(cur->rxmit, cur->end);
771 				if ((tp->t_flags & TF_LRD) && SEQ_GEQ(cur->rxmit, cur->end))
772 					cur->rxmit = tp->snd_recover;
773 			} else {
774 				/*
775 				 * ACKs some data in middle of a hole; need
776 				 * to split current hole
777 				 */
778 				temp = tcp_sackhole_insert(tp, sblkp->end,
779 				    cur->end, cur);
780 				if (temp != NULL) {
781 					if (SEQ_GT(cur->rxmit, temp->rxmit)) {
782 						temp->rxmit = cur->rxmit;
783 						tp->sackhint.sack_bytes_rexmit +=
784 						    (SEQ_MIN(temp->rxmit,
785 						    temp->end) - temp->start);
786 					}
787 					cur->end = sblkp->start;
788 					cur->rxmit = SEQ_MIN(cur->rxmit,
789 					    cur->end);
790 					if ((tp->t_flags & TF_LRD) && SEQ_GEQ(cur->rxmit, cur->end))
791 						cur->rxmit = tp->snd_recover;
792 					delivered_data += (sblkp->end - sblkp->start);
793 				}
794 			}
795 		}
796 		tp->sackhint.sack_bytes_rexmit +=
797 		    (SEQ_MIN(cur->rxmit, cur->end) - cur->start);
798 		/*
799 		 * Testing sblkp->start against cur->start tells us whether
800 		 * we're done with the sack block or the sack hole.
801 		 * Accordingly, we advance one or the other.
802 		 */
803 		if (SEQ_LEQ(sblkp->start, cur->start))
804 			cur = TAILQ_PREV(cur, sackhole_head, scblink);
805 		else
806 			sblkp--;
807 	}
808 	if (!(to->to_flags & TOF_SACK))
809 		/*
810 		 * If this ACK did not contain any
811 		 * SACK blocks, any only moved the
812 		 * left edge right, it is a pure
813 		 * cumulative ACK. Do not count
814 		 * DupAck for this. Also required
815 		 * for RFC6675 rescue retransmission.
816 		 */
817 		sack_changed = 0;
818 	tp->sackhint.delivered_data = delivered_data;
819 	tp->sackhint.sacked_bytes += delivered_data - left_edge_delta;
820 	KASSERT((delivered_data >= 0), ("delivered_data < 0"));
821 	KASSERT((tp->sackhint.sacked_bytes >= 0), ("sacked_bytes < 0"));
822 	return (sack_changed);
823 }
824 
825 /*
826  * Free all SACK holes to clear the scoreboard.
827  */
828 void
829 tcp_free_sackholes(struct tcpcb *tp)
830 {
831 	struct sackhole *q;
832 
833 	INP_WLOCK_ASSERT(tp->t_inpcb);
834 	while ((q = TAILQ_FIRST(&tp->snd_holes)) != NULL)
835 		tcp_sackhole_remove(tp, q);
836 	tp->sackhint.sack_bytes_rexmit = 0;
837 
838 	KASSERT(tp->snd_numholes == 0, ("tp->snd_numholes == 0"));
839 	KASSERT(tp->sackhint.nexthole == NULL,
840 		("tp->sackhint.nexthole == NULL"));
841 }
842 
843 /*
844  * Partial ack handling within a sack recovery episode.  Keeping this very
845  * simple for now.  When a partial ack is received, force snd_cwnd to a value
846  * that will allow the sender to transmit no more than 2 segments.  If
847  * necessary, a better scheme can be adopted at a later point, but for now,
848  * the goal is to prevent the sender from bursting a large amount of data in
849  * the midst of sack recovery.
850  */
851 void
852 tcp_sack_partialack(struct tcpcb *tp, struct tcphdr *th)
853 {
854 	int num_segs = 1;
855 	u_int maxseg = tcp_maxseg(tp);
856 
857 	INP_WLOCK_ASSERT(tp->t_inpcb);
858 	tcp_timer_activate(tp, TT_REXMT, 0);
859 	tp->t_rtttime = 0;
860 	/* Send one or 2 segments based on how much new data was acked. */
861 	if ((BYTES_THIS_ACK(tp, th) / maxseg) >= 2)
862 		num_segs = 2;
863 	tp->snd_cwnd = (tp->sackhint.sack_bytes_rexmit +
864 	    (tp->snd_nxt - tp->snd_recover) + num_segs * maxseg);
865 	if (tp->snd_cwnd > tp->snd_ssthresh)
866 		tp->snd_cwnd = tp->snd_ssthresh;
867 	tp->t_flags |= TF_ACKNOW;
868 	/*
869 	 * RFC6675 rescue retransmission
870 	 * Add a hole between th_ack (snd_una is not yet set) and snd_max,
871 	 * if this was a pure cumulative ACK and no data was send beyond
872 	 * recovery point. Since the data in the socket has not been freed
873 	 * at this point, we check if the scoreboard is empty, and the ACK
874 	 * delivered some new data, indicating a full ACK. Also, if the
875 	 * recovery point is still at snd_max, we are probably application
876 	 * limited. However, this inference might not always be true. The
877 	 * rescue retransmission may rarely be slightly premature
878 	 * compared to RFC6675.
879 	 * The corresponding ACK+SACK will cause any further outstanding
880 	 * segments to be retransmitted. This addresses a corner case, when
881 	 * the trailing packets of a window are lost and no further data
882 	 * is available for sending.
883 	 */
884 	if ((V_tcp_do_newsack) &&
885 	    SEQ_LT(th->th_ack, tp->snd_recover) &&
886 	    (tp->snd_recover == tp->snd_max) &&
887 	    TAILQ_EMPTY(&tp->snd_holes) &&
888 	    (tp->sackhint.delivered_data > 0)) {
889 		/*
890 		 * Exclude FIN sequence space in
891 		 * the hole for the rescue retransmission,
892 		 * and also don't create a hole, if only
893 		 * the ACK for a FIN is outstanding.
894 		 */
895 		tcp_seq highdata = tp->snd_max;
896 		if (tp->t_flags & TF_SENTFIN)
897 			highdata--;
898 		if (th->th_ack != highdata) {
899 			tp->snd_fack = th->th_ack;
900 			(void)tcp_sackhole_insert(tp, SEQ_MAX(th->th_ack,
901 			    highdata - maxseg), highdata, NULL);
902 		}
903 	}
904 	(void) tcp_output(tp);
905 }
906 
907 #if 0
908 /*
909  * Debug version of tcp_sack_output() that walks the scoreboard.  Used for
910  * now to sanity check the hint.
911  */
912 static struct sackhole *
913 tcp_sack_output_debug(struct tcpcb *tp, int *sack_bytes_rexmt)
914 {
915 	struct sackhole *p;
916 
917 	INP_WLOCK_ASSERT(tp->t_inpcb);
918 	*sack_bytes_rexmt = 0;
919 	TAILQ_FOREACH(p, &tp->snd_holes, scblink) {
920 		if (SEQ_LT(p->rxmit, p->end)) {
921 			if (SEQ_LT(p->rxmit, tp->snd_una)) {/* old SACK hole */
922 				continue;
923 			}
924 			*sack_bytes_rexmt += (p->rxmit - p->start);
925 			break;
926 		}
927 		*sack_bytes_rexmt += (SEQ_MIN(p->rxmit, p->end) - p->start);
928 	}
929 	return (p);
930 }
931 #endif
932 
933 /*
934  * Returns the next hole to retransmit and the number of retransmitted bytes
935  * from the scoreboard.  We store both the next hole and the number of
936  * retransmitted bytes as hints (and recompute these on the fly upon SACK/ACK
937  * reception).  This avoids scoreboard traversals completely.
938  *
939  * The loop here will traverse *at most* one link.  Here's the argument.  For
940  * the loop to traverse more than 1 link before finding the next hole to
941  * retransmit, we would need to have at least 1 node following the current
942  * hint with (rxmit == end).  But, for all holes following the current hint,
943  * (start == rxmit), since we have not yet retransmitted from them.
944  * Therefore, in order to traverse more 1 link in the loop below, we need to
945  * have at least one node following the current hint with (start == rxmit ==
946  * end).  But that can't happen, (start == end) means that all the data in
947  * that hole has been sacked, in which case, the hole would have been removed
948  * from the scoreboard.
949  */
950 struct sackhole *
951 tcp_sack_output(struct tcpcb *tp, int *sack_bytes_rexmt)
952 {
953 	struct sackhole *hole = NULL;
954 
955 	INP_WLOCK_ASSERT(tp->t_inpcb);
956 	*sack_bytes_rexmt = tp->sackhint.sack_bytes_rexmit;
957 	hole = tp->sackhint.nexthole;
958 	if (hole == NULL)
959 		return (hole);
960 	if (SEQ_GEQ(hole->rxmit, hole->end)) {
961 		for (;;) {
962 			hole = TAILQ_NEXT(hole, scblink);
963 			if (hole == NULL)
964 				return (hole);
965 			if (SEQ_LT(hole->rxmit, hole->end)) {
966 				tp->sackhint.nexthole = hole;
967 				break;
968 			}
969 		}
970 	}
971 	KASSERT(SEQ_LT(hole->start, hole->end), ("%s: hole.start >= hole.end", __func__));
972 	if (!(V_tcp_do_newsack)) {
973 		KASSERT(SEQ_LT(hole->start, tp->snd_fack), ("%s: hole.start >= snd.fack", __func__));
974 		KASSERT(SEQ_LT(hole->end, tp->snd_fack), ("%s: hole.end >= snd.fack", __func__));
975 		KASSERT(SEQ_LT(hole->rxmit, tp->snd_fack), ("%s: hole.rxmit >= snd.fack", __func__));
976 		if (SEQ_GEQ(hole->start, hole->end) ||
977 		    SEQ_GEQ(hole->start, tp->snd_fack) ||
978 		    SEQ_GEQ(hole->end, tp->snd_fack) ||
979 		    SEQ_GEQ(hole->rxmit, tp->snd_fack)) {
980 			log(LOG_CRIT,"tcp: invalid SACK hole (%u-%u,%u) vs fwd ack %u, ignoring.\n",
981 					hole->start, hole->end, hole->rxmit, tp->snd_fack);
982 			return (NULL);
983 		}
984 	}
985 	return (hole);
986 }
987 
988 /*
989  * After a timeout, the SACK list may be rebuilt.  This SACK information
990  * should be used to avoid retransmitting SACKed data.  This function
991  * traverses the SACK list to see if snd_nxt should be moved forward.
992  */
993 void
994 tcp_sack_adjust(struct tcpcb *tp)
995 {
996 	struct sackhole *p, *cur = TAILQ_FIRST(&tp->snd_holes);
997 
998 	INP_WLOCK_ASSERT(tp->t_inpcb);
999 	if (cur == NULL)
1000 		return; /* No holes */
1001 	if (SEQ_GEQ(tp->snd_nxt, tp->snd_fack))
1002 		return; /* We're already beyond any SACKed blocks */
1003 	/*-
1004 	 * Two cases for which we want to advance snd_nxt:
1005 	 * i) snd_nxt lies between end of one hole and beginning of another
1006 	 * ii) snd_nxt lies between end of last hole and snd_fack
1007 	 */
1008 	while ((p = TAILQ_NEXT(cur, scblink)) != NULL) {
1009 		if (SEQ_LT(tp->snd_nxt, cur->end))
1010 			return;
1011 		if (SEQ_GEQ(tp->snd_nxt, p->start))
1012 			cur = p;
1013 		else {
1014 			tp->snd_nxt = p->start;
1015 			return;
1016 		}
1017 	}
1018 	if (SEQ_LT(tp->snd_nxt, cur->end))
1019 		return;
1020 	tp->snd_nxt = tp->snd_fack;
1021 }
1022 
1023 /*
1024  * Lost Retransmission Detection
1025  * Check is FACK is beyond the rexmit of the leftmost hole.
1026  * If yes, we restart sending from still existing holes,
1027  * and adjust cwnd via the congestion control module.
1028  */
1029 void
1030 tcp_sack_lost_retransmission(struct tcpcb *tp, struct tcphdr *th)
1031 {
1032 	struct sackhole *temp;
1033 
1034 	if (IN_RECOVERY(tp->t_flags) &&
1035 	    SEQ_GT(tp->snd_fack, tp->snd_recover) &&
1036 	    ((temp = TAILQ_FIRST(&tp->snd_holes)) != NULL) &&
1037 	    SEQ_GEQ(temp->rxmit, temp->end) &&
1038 	    SEQ_GEQ(tp->snd_fack, temp->rxmit)) {
1039 		TCPSTAT_INC(tcps_sack_lostrexmt);
1040 		/*
1041 		 * Start retransmissions from the first hole, and
1042 		 * subsequently all other remaining holes, including
1043 		 * those, which had been sent completely before.
1044 		 */
1045 		tp->sackhint.nexthole = temp;
1046 		TAILQ_FOREACH(temp, &tp->snd_holes, scblink) {
1047 			if (SEQ_GEQ(tp->snd_fack, temp->rxmit) &&
1048 			    SEQ_GEQ(temp->rxmit, temp->end))
1049 				temp->rxmit = temp->start;
1050 		}
1051 		/*
1052 		 * Remember the old ssthresh, to deduct the beta factor used
1053 		 * by the CC module. Finally, set cwnd to ssthresh just
1054 		 * prior to invoking another cwnd reduction by the CC
1055 		 * module, to not shrink it excessively.
1056 		 */
1057 		tp->snd_cwnd = tp->snd_ssthresh;
1058 		/*
1059 		 * Formally exit recovery, and let the CC module adjust
1060 		 * ssthresh as intended.
1061 		 */
1062 		EXIT_RECOVERY(tp->t_flags);
1063 		cc_cong_signal(tp, th, CC_NDUPACK);
1064 		/*
1065 		 * For PRR, adjust recover_fs as if this new reduction
1066 		 * initialized this variable.
1067 		 * cwnd will be adjusted by SACK or PRR processing
1068 		 * subsequently, only set it to a safe value here.
1069 		 */
1070 		tp->snd_cwnd = tcp_maxseg(tp);
1071 		tp->sackhint.recover_fs = (tp->snd_max - tp->snd_una) -
1072 					    tp->sackhint.recover_fs;
1073 	}
1074 }
1075