xref: /dflybsd-src/sys/netinet/tcp_sack.c (revision a42c8ee581107512c9160b3b352135f5c5eb90fe)
1 /*
2  * Copyright (c) 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2003, 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
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 DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $DragonFly: src/sys/netinet/tcp_sack.c,v 1.8 2008/08/15 21:37:16 nth Exp $
34  */
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/malloc.h>
40 #include <sys/queue.h>
41 #include <sys/thread.h>
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
45 
46 #include <net/if.h>
47 
48 #include <netinet/in.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/ip.h>
51 #include <netinet/in_var.h>
52 #include <netinet/in_pcb.h>
53 #include <netinet/ip_var.h>
54 #include <netinet/tcp.h>
55 #include <netinet/tcp_seq.h>
56 #include <netinet/tcp_var.h>
57 
58 /*
59  * Implemented:
60  *
61  * RFC 2018
62  * RFC 2883
63  * RFC 3517
64  */
65 
66 struct sackblock {
67 	tcp_seq			sblk_start;
68 	tcp_seq			sblk_end;
69 	TAILQ_ENTRY(sackblock)	sblk_list;
70 };
71 
72 #define	MAXSAVEDBLOCKS	8			/* per connection limit */
73 
74 static int insert_block(struct scoreboard *scb,
75 			const struct raw_sackblock *raw_sb, boolean_t *update);
76 static void update_lostseq(struct scoreboard *scb, tcp_seq snd_una,
77 			   u_int maxseg, int rxtthresh);
78 
79 static MALLOC_DEFINE(M_SACKBLOCK, "sblk", "sackblock struct");
80 
81 /*
82  * Per-tcpcb initialization.
83  */
84 void
85 tcp_sack_tcpcb_init(struct tcpcb *tp)
86 {
87 	struct scoreboard *scb = &tp->scb;
88 
89 	scb->nblocks = 0;
90 	TAILQ_INIT(&scb->sackblocks);
91 	scb->lastfound = NULL;
92 }
93 
94 /*
95  * Find the SACK block containing or immediately preceding "seq".
96  * The boolean result indicates whether the sequence is actually
97  * contained in the SACK block.
98  */
99 static boolean_t
100 sack_block_lookup(struct scoreboard *scb, tcp_seq seq, struct sackblock **sb)
101 {
102 	struct sackblock *hint = scb->lastfound;
103 	struct sackblock *cur, *last, *prev;
104 
105 	if (TAILQ_EMPTY(&scb->sackblocks)) {
106 		*sb = NULL;
107 		return FALSE;
108 	}
109 
110 	if (hint == NULL) {
111 		/* No hint.  Search from start to end. */
112 		cur = TAILQ_FIRST(&scb->sackblocks);
113 		last = NULL;
114 		prev = TAILQ_LAST(&scb->sackblocks, sackblock_list);
115 	} else  {
116 		if (SEQ_GEQ(seq, hint->sblk_start)) {
117 			/* Search from hint to end of list. */
118 			cur = hint;
119 			last = NULL;
120 			prev = TAILQ_LAST(&scb->sackblocks, sackblock_list);
121 		} else {
122 			/* Search from front of list to hint. */
123 			cur = TAILQ_FIRST(&scb->sackblocks);
124 			last = hint;
125 			prev = TAILQ_PREV(hint, sackblock_list, sblk_list);
126 		}
127 	}
128 
129 	do {
130 		if (SEQ_GT(cur->sblk_end, seq)) {
131 			if (SEQ_GEQ(seq, cur->sblk_start)) {
132 				*sb = scb->lastfound = cur;
133 				return TRUE;
134 			} else {
135 				*sb = scb->lastfound =
136 				    TAILQ_PREV(cur, sackblock_list, sblk_list);
137 				return FALSE;
138 			}
139 		}
140 		cur = TAILQ_NEXT(cur, sblk_list);
141 	} while (cur != last);
142 
143 	*sb = scb->lastfound = prev;
144 	return FALSE;
145 }
146 
147 /*
148  * Allocate a SACK block.
149  */
150 static __inline struct sackblock *
151 alloc_sackblock(struct scoreboard *scb, const struct raw_sackblock *raw_sb)
152 {
153 	struct sackblock *sb;
154 
155 	if (scb->freecache != NULL) {
156 		sb = scb->freecache;
157 		scb->freecache = NULL;
158 		tcpstat.tcps_sacksbfast++;
159 	} else {
160 		sb = kmalloc(sizeof(struct sackblock), M_SACKBLOCK, M_NOWAIT);
161 		if (sb == NULL) {
162 			tcpstat.tcps_sacksbfailed++;
163 			return NULL;
164 		}
165 	}
166 	sb->sblk_start = raw_sb->rblk_start;
167 	sb->sblk_end = raw_sb->rblk_end;
168 	return sb;
169 }
170 
171 static __inline struct sackblock *
172 alloc_sackblock_limit(struct scoreboard *scb,
173     const struct raw_sackblock *raw_sb)
174 {
175 	if (scb->nblocks == MAXSAVEDBLOCKS) {
176 		/*
177 		 * Should try to kick out older blocks XXX JH
178 		 * May be able to coalesce with existing block.
179 		 * Or, go other way and free all blocks if we hit
180 		 * this limit.
181 		 */
182 		tcpstat.tcps_sacksboverflow++;
183 		return NULL;
184 	}
185 	return alloc_sackblock(scb, raw_sb);
186 }
187 
188 /*
189  * Free a SACK block.
190  */
191 static __inline void
192 free_sackblock(struct scoreboard *scb, struct sackblock *s)
193 {
194 	if (scb->freecache == NULL) {
195 		/* YYY Maybe use the latest freed block? */
196 		scb->freecache = s;
197 		return;
198 	}
199 	kfree(s, M_SACKBLOCK);
200 }
201 
202 /*
203  * Free up SACK blocks for data that's been acked.
204  */
205 static void
206 tcp_sack_ack_blocks(struct scoreboard *scb, tcp_seq th_ack)
207 {
208 	struct sackblock *sb, *nb;
209 
210 	sb = TAILQ_FIRST(&scb->sackblocks);
211 	while (sb && SEQ_LEQ(sb->sblk_end, th_ack)) {
212 		nb = TAILQ_NEXT(sb, sblk_list);
213 		if (scb->lastfound == sb)
214 			scb->lastfound = NULL;
215 		TAILQ_REMOVE(&scb->sackblocks, sb, sblk_list);
216 		free_sackblock(scb, sb);
217 		--scb->nblocks;
218 		KASSERT(scb->nblocks >= 0,
219 		    ("SACK block count underflow: %d < 0", scb->nblocks));
220 		sb = nb;
221 	}
222 	if (sb && SEQ_GT(th_ack, sb->sblk_start))
223 		sb->sblk_start = th_ack;	/* other side reneged? XXX */
224 }
225 
226 /*
227  * Delete and free SACK blocks saved in scoreboard.
228  */
229 void
230 tcp_sack_cleanup(struct scoreboard *scb)
231 {
232 	struct sackblock *sb, *nb;
233 
234 	TAILQ_FOREACH_MUTABLE(sb, &scb->sackblocks, sblk_list, nb) {
235 		free_sackblock(scb, sb);
236 		--scb->nblocks;
237 	}
238 	KASSERT(scb->nblocks == 0,
239 	    ("SACK block %d count not zero", scb->nblocks));
240 	TAILQ_INIT(&scb->sackblocks);
241 	scb->lastfound = NULL;
242 }
243 
244 /*
245  * Delete and free SACK blocks saved in scoreboard.
246  * Delete the one slot block cache.
247  */
248 void
249 tcp_sack_destroy(struct scoreboard *scb)
250 {
251 	tcp_sack_cleanup(scb);
252 	if (scb->freecache != NULL) {
253 		kfree(scb->freecache, M_SACKBLOCK);
254 		scb->freecache = NULL;
255 	}
256 }
257 
258 /*
259  * Cleanup the reported SACK block information
260  */
261 void
262 tcp_sack_report_cleanup(struct tcpcb *tp)
263 {
264 	tp->sack_flags &=
265 	    ~(TSACK_F_DUPSEG | TSACK_F_ENCLOSESEG | TSACK_F_SACKLEFT);
266 	tp->reportblk.rblk_start = tp->reportblk.rblk_end;
267 }
268 
269 /*
270  * Returns	0 if not D-SACK block,
271  *		1 if D-SACK,
272  *		2 if duplicate of out-of-order D-SACK block.
273  */
274 int
275 tcp_sack_ndsack_blocks(struct raw_sackblock *blocks, const int numblocks,
276 		       tcp_seq snd_una)
277 {
278 	if (numblocks == 0)
279 		return 0;
280 
281 	if (SEQ_LT(blocks[0].rblk_start, snd_una))
282 		return 1;
283 
284 	/* block 0 inside block 1 */
285 	if (numblocks > 1 &&
286 	    SEQ_GEQ(blocks[0].rblk_start, blocks[1].rblk_start) &&
287 	    SEQ_LEQ(blocks[0].rblk_end, blocks[1].rblk_end))
288 		return 2;
289 
290 	return 0;
291 }
292 
293 /*
294  * Update scoreboard on new incoming ACK.
295  */
296 static void
297 tcp_sack_add_blocks(struct tcpcb *tp, struct tcpopt *to)
298 {
299 	const int numblocks = to->to_nsackblocks;
300 	struct raw_sackblock *blocks = to->to_sackblocks;
301 	struct scoreboard *scb = &tp->scb;
302 	int startblock, i;
303 
304 	if (tcp_sack_ndsack_blocks(blocks, numblocks, tp->snd_una) > 0)
305 		startblock = 1;
306 	else
307 		startblock = 0;
308 
309 	to->to_flags |= TOF_SACK_REDUNDANT;
310 	for (i = startblock; i < numblocks; i++) {
311 		struct raw_sackblock *newsackblock = &blocks[i];
312 		boolean_t update;
313 		int error;
314 
315 		/* Guard against ACK reordering */
316 		if (SEQ_LT(newsackblock->rblk_start, tp->snd_una))
317 			continue;
318 
319 		/* Don't accept bad SACK blocks */
320 		if (SEQ_GT(newsackblock->rblk_end, tp->snd_max)) {
321 			tcpstat.tcps_rcvbadsackopt++;
322 			break;		/* skip all other blocks */
323 		}
324 		tcpstat.tcps_sacksbupdate++;
325 
326 		error = insert_block(scb, newsackblock, &update);
327 		if (update)
328 			to->to_flags &= ~TOF_SACK_REDUNDANT;
329 		if (error)
330 			break;
331 	}
332 }
333 
334 void
335 tcp_sack_update_scoreboard(struct tcpcb *tp, struct tcpopt *to)
336 {
337 	struct scoreboard *scb = &tp->scb;
338 	int rexmt_high_update = 0;
339 
340 	tcp_sack_ack_blocks(scb, tp->snd_una);
341 	tcp_sack_add_blocks(tp, to);
342 	update_lostseq(scb, tp->snd_una, tp->t_maxseg, tp->t_rxtthresh);
343 	if (SEQ_LT(tp->rexmt_high, tp->snd_una)) {
344 		tp->rexmt_high = tp->snd_una;
345 		rexmt_high_update = 1;
346 	}
347 	if (tp->sack_flags & TSACK_F_SACKRESCUED) {
348 		if (SEQ_LT(tp->rexmt_rescue, tp->snd_una)) {
349 			tp->sack_flags &= ~TSACK_F_SACKRESCUED;
350 		} else if (tcp_aggressive_rescuesack && rexmt_high_update &&
351 		    SEQ_LT(tp->rexmt_rescue, tp->rexmt_high)) {
352 			/* Drag RescueRxt along with HighRxt */
353 			tp->rexmt_rescue = tp->rexmt_high;
354 		}
355 	}
356 }
357 
358 /*
359  * Insert SACK block into sender's scoreboard.
360  */
361 static int
362 insert_block(struct scoreboard *scb, const struct raw_sackblock *raw_sb,
363     boolean_t *update)
364 {
365 	struct sackblock *sb, *workingblock;
366 	boolean_t overlap_front;
367 
368 	*update = TRUE;
369 	if (TAILQ_EMPTY(&scb->sackblocks)) {
370 		struct sackblock *newblock;
371 
372 		KASSERT(scb->nblocks == 0, ("emply scb w/ blocks"));
373 
374 		newblock = alloc_sackblock(scb, raw_sb);
375 		if (newblock == NULL)
376 			return ENOMEM;
377 		TAILQ_INSERT_HEAD(&scb->sackblocks, newblock, sblk_list);
378 		scb->nblocks = 1;
379 		return 0;
380 	}
381 
382 	KASSERT(scb->nblocks > 0, ("insert_block() called w/ no blocks"));
383 	KASSERT(scb->nblocks <= MAXSAVEDBLOCKS,
384 	    ("too many SACK blocks %d", scb->nblocks));
385 
386 	overlap_front = sack_block_lookup(scb, raw_sb->rblk_start, &sb);
387 
388 	if (sb == NULL) {
389 		workingblock = alloc_sackblock_limit(scb, raw_sb);
390 		if (workingblock == NULL)
391 			return ENOMEM;
392 		TAILQ_INSERT_HEAD(&scb->sackblocks, workingblock, sblk_list);
393 		++scb->nblocks;
394 	} else {
395 		if (overlap_front || sb->sblk_end == raw_sb->rblk_start) {
396 			/* Extend old block */
397 			workingblock = sb;
398 			if (SEQ_GT(raw_sb->rblk_end, sb->sblk_end))
399 				sb->sblk_end = raw_sb->rblk_end;
400 			else
401 				*update = FALSE;
402 			tcpstat.tcps_sacksbreused++;
403 		} else {
404 			workingblock = alloc_sackblock_limit(scb, raw_sb);
405 			if (workingblock == NULL)
406 				return ENOMEM;
407 			TAILQ_INSERT_AFTER(&scb->sackblocks, sb, workingblock,
408 			    sblk_list);
409 			++scb->nblocks;
410 		}
411 	}
412 
413 	/* Consolidate right-hand side. */
414 	sb = TAILQ_NEXT(workingblock, sblk_list);
415 	while (sb != NULL &&
416 	    SEQ_GEQ(workingblock->sblk_end, sb->sblk_end)) {
417 		struct sackblock *nextblock;
418 
419 		nextblock = TAILQ_NEXT(sb, sblk_list);
420 		if (scb->lastfound == sb)
421 			scb->lastfound = NULL;
422 		/* Remove completely overlapped block */
423 		TAILQ_REMOVE(&scb->sackblocks, sb, sblk_list);
424 		free_sackblock(scb, sb);
425 		--scb->nblocks;
426 		KASSERT(scb->nblocks > 0,
427 		    ("removed overlapped block: %d blocks left", scb->nblocks));
428 		sb = nextblock;
429 	}
430 	if (sb != NULL &&
431 	    SEQ_GEQ(workingblock->sblk_end, sb->sblk_start)) {
432 		/* Extend new block to cover partially overlapped old block. */
433 		workingblock->sblk_end = sb->sblk_end;
434 		if (scb->lastfound == sb)
435 			scb->lastfound = NULL;
436 		TAILQ_REMOVE(&scb->sackblocks, sb, sblk_list);
437 		free_sackblock(scb, sb);
438 		--scb->nblocks;
439 		KASSERT(scb->nblocks > 0,
440 		    ("removed partial right: %d blocks left", scb->nblocks));
441 	}
442 	return 0;
443 }
444 
445 #ifdef DEBUG_SACK_BLOCKS
446 static void
447 tcp_sack_dump_blocks(struct scoreboard *scb)
448 {
449 	struct sackblock *sb;
450 
451 	kprintf("%d blocks:", scb->nblocks);
452 	TAILQ_FOREACH(sb, &scb->sackblocks, sblk_list)
453 		kprintf(" [%u, %u)", sb->sblk_start, sb->sblk_end);
454 	kprintf("\n");
455 }
456 #else
457 static __inline void
458 tcp_sack_dump_blocks(struct scoreboard *scb)
459 {
460 }
461 #endif
462 
463 /*
464  * Optimization to quickly determine which packets are lost.
465  */
466 static void
467 update_lostseq(struct scoreboard *scb, tcp_seq snd_una, u_int maxseg,
468     int rxtthresh)
469 {
470 	struct sackblock *sb;
471 	int nsackblocks = 0;
472 	int bytes_sacked = 0;
473 	int rxtthresh_bytes;
474 
475 	/*
476 	 * XXX
477 	 * The RFC3517bis recommends to reduce the byte threshold.
478 	 * However, it will cause extra spurious retransmit if
479 	 * segments are reordered.  Before certain DupThresh adaptive
480 	 * algorithm is implemented, we don't reduce the byte
481 	 * threshold (tcp_rfc3517bis_rxt is off by default).
482 	 */
483 	if (tcp_do_rfc3517bis && tcp_rfc3517bis_rxt)
484 		rxtthresh_bytes = (rxtthresh - 1) * maxseg;
485 	else
486 		rxtthresh_bytes = rxtthresh * maxseg;
487 
488 	sb = TAILQ_LAST(&scb->sackblocks, sackblock_list);
489 	while (sb != NULL) {
490 		++nsackblocks;
491 		bytes_sacked += sb->sblk_end - sb->sblk_start;
492 		if (nsackblocks == rxtthresh ||
493 		    bytes_sacked >= rxtthresh_bytes) {
494 			scb->lostseq = sb->sblk_start;
495 			return;
496 		}
497 		sb = TAILQ_PREV(sb, sackblock_list, sblk_list);
498 	}
499 	scb->lostseq = snd_una;
500 }
501 
502 /*
503  * Return whether the given sequence number is considered lost.
504  */
505 boolean_t
506 tcp_sack_islost(struct scoreboard *scb, tcp_seq seqnum)
507 {
508 	return SEQ_LT(seqnum, scb->lostseq);
509 }
510 
511 /*
512  * True if at least "amount" has been SACKed.  Used by Early Retransmit.
513  */
514 boolean_t
515 tcp_sack_has_sacked(struct scoreboard *scb, u_int amount)
516 {
517 	struct sackblock *sb;
518 	int bytes_sacked = 0;
519 
520 	TAILQ_FOREACH(sb, &scb->sackblocks, sblk_list) {
521 		bytes_sacked += sb->sblk_end - sb->sblk_start;
522 		if (bytes_sacked >= amount)
523 			return TRUE;
524 	}
525 	return FALSE;
526 }
527 
528 /*
529  * Number of bytes SACKed below seq.
530  */
531 int
532 tcp_sack_bytes_below(struct scoreboard *scb, tcp_seq seq)
533 {
534 	struct sackblock *sb;
535 	int bytes_sacked = 0;
536 
537 	sb = TAILQ_FIRST(&scb->sackblocks);
538 	while (sb && SEQ_GT(seq, sb->sblk_start)) {
539 		bytes_sacked += seq_min(seq, sb->sblk_end) - sb->sblk_start;
540 		sb = TAILQ_NEXT(sb, sblk_list);
541 	}
542 	return bytes_sacked;
543 }
544 
545 /*
546  * Return estimate of the number of bytes outstanding in the network.
547  */
548 uint32_t
549 tcp_sack_compute_pipe(struct tcpcb *tp)
550 {
551 	struct scoreboard *scb = &tp->scb;
552 	struct sackblock *sb;
553 	int nlost, nretransmitted;
554 	tcp_seq end;
555 
556 	nlost = tp->snd_max - scb->lostseq;
557 	nretransmitted = tp->rexmt_high - tp->snd_una;
558 
559 	TAILQ_FOREACH(sb, &scb->sackblocks, sblk_list) {
560 		if (SEQ_LT(sb->sblk_start, tp->rexmt_high)) {
561 			end = seq_min(sb->sblk_end, tp->rexmt_high);
562 			nretransmitted -= end - sb->sblk_start;
563 		}
564 		if (SEQ_GEQ(sb->sblk_start, scb->lostseq))
565 			nlost -= sb->sblk_end - sb->sblk_start;
566 	}
567 
568 	return (nlost + nretransmitted);
569 }
570 
571 /*
572  * Return the sequence number and length of the next segment to transmit
573  * when in Fast Recovery.
574  */
575 boolean_t
576 tcp_sack_nextseg(struct tcpcb *tp, tcp_seq *nextrexmt, uint32_t *plen,
577     boolean_t *rescue)
578 {
579 	struct scoreboard *scb = &tp->scb;
580 	struct socket *so = tp->t_inpcb->inp_socket;
581 	struct sackblock *sb;
582 	const struct sackblock *lastblock =
583 	    TAILQ_LAST(&scb->sackblocks, sackblock_list);
584 	tcp_seq torexmt;
585 	long len, off;
586 
587 	/* skip SACKed data */
588 	tcp_sack_skip_sacked(scb, &tp->rexmt_high);
589 
590 	/* Look for lost data. */
591 	torexmt = tp->rexmt_high;
592 	*rescue = FALSE;
593 	if (lastblock != NULL) {
594 		if (SEQ_LT(torexmt, lastblock->sblk_end) &&
595 		    tcp_sack_islost(scb, torexmt)) {
596 sendunsacked:
597 			*nextrexmt = torexmt;
598 			/* If the left-hand edge has been SACKed, pull it in. */
599 			if (sack_block_lookup(scb, torexmt + tp->t_maxseg, &sb))
600 				*plen = sb->sblk_start - torexmt;
601 			else
602 				*plen = tp->t_maxseg;
603 			return TRUE;
604 		}
605 	}
606 
607 	/* See if unsent data available within send window. */
608 	off = tp->snd_max - tp->snd_una;
609 	len = (long) ulmin(so->so_snd.ssb_cc, tp->snd_wnd) - off;
610 	if (len > 0) {
611 		*nextrexmt = tp->snd_max;	/* Send new data. */
612 		*plen = tp->t_maxseg;
613 		return TRUE;
614 	}
615 
616 	/* We're less certain this data has been lost. */
617 	if (lastblock != NULL && SEQ_LT(torexmt, lastblock->sblk_end))
618 		goto sendunsacked;
619 
620 	/* Rescue retransmission */
621 	if (tcp_do_rescuesack || tcp_do_rfc3517bis) {
622 		tcpstat.tcps_sackrescue_try++;
623 		if (tp->sack_flags & TSACK_F_SACKRESCUED) {
624 			if (!tcp_aggressive_rescuesack)
625 				return FALSE;
626 
627 			/*
628 			 * Aggressive variant of the rescue retransmission.
629 			 *
630 			 * The idea of the rescue retransmission is to sustain
631 			 * the ACK clock thus to avoid timeout retransmission.
632 			 *
633 			 * Under some situations, the conservative approach
634 			 * suggested in the draft
635  			 * http://tools.ietf.org/html/
636 			 * draft-nishida-tcpm-rescue-retransmission-00
637 			 * could not sustain ACK clock, since it only allows
638 			 * one rescue retransmission before a cumulative ACK
639 			 * covers the segement transmitted by rescue
640 			 * retransmission.
641 			 *
642 			 * We try to locate the next unSACKed segment which
643 			 * follows the previously sent rescue segment.  If
644 			 * there is no such segment, we loop back to the first
645 			 * unacknowledged segment.
646 			 */
647 
648 			/*
649 			 * Skip SACKed data, but here we follow
650 			 * the last transmitted rescue segment.
651 			 */
652 			torexmt = tp->rexmt_rescue;
653 			tcp_sack_skip_sacked(scb, &torexmt);
654 			if (torexmt == tp->snd_max) {
655 				/* Nothing left to retransmit; restart */
656 				torexmt = tp->snd_una;
657 			}
658 		}
659 		*rescue = TRUE;
660 		goto sendunsacked;
661 	} else if (tcp_do_smartsack && lastblock == NULL) {
662 		tcpstat.tcps_sackrescue_try++;
663 		*rescue = TRUE;
664 		goto sendunsacked;
665 	}
666 
667 	return FALSE;
668 }
669 
670 /*
671  * Return the next sequence number higher than "*prexmt" that has
672  * not been SACKed.
673  */
674 void
675 tcp_sack_skip_sacked(struct scoreboard *scb, tcp_seq *prexmt)
676 {
677 	struct sackblock *sb;
678 
679 	/* skip SACKed data */
680 	if (sack_block_lookup(scb, *prexmt, &sb))
681 		*prexmt = sb->sblk_end;
682 }
683 
684 #ifdef later
685 void
686 tcp_sack_save_scoreboard(struct scoreboard *scb)
687 {
688 	struct scoreboard *scb = &tp->scb;
689 
690 	scb->sackblocks_prev = scb->sackblocks;
691 	TAILQ_INIT(&scb->sackblocks);
692 }
693 
694 void
695 tcp_sack_revert_scoreboard(struct scoreboard *scb, tcp_seq snd_una,
696 			   u_int maxseg)
697 {
698 	struct sackblock *sb;
699 
700 	scb->sackblocks = scb->sackblocks_prev;
701 	scb->nblocks = 0;
702 	TAILQ_FOREACH(sb, &scb->sackblocks, sblk_list)
703 		++scb->nblocks;
704 	tcp_sack_ack_blocks(scb, snd_una);
705 	scb->lastfound = NULL;
706 }
707 #endif
708 
709 #ifdef DEBUG_SACK_HISTORY
710 static void
711 tcp_sack_dump_history(char *msg, struct tcpcb *tp)
712 {
713 	int i;
714 	static int ndumped;
715 
716 	/* only need a couple of these to debug most problems */
717 	if (++ndumped > 900)
718 		return;
719 
720 	kprintf("%s:\tnsackhistory %d: ", msg, tp->nsackhistory);
721 	for (i = 0; i < tp->nsackhistory; ++i)
722 		kprintf("[%u, %u) ", tp->sackhistory[i].rblk_start,
723 		    tp->sackhistory[i].rblk_end);
724 	kprintf("\n");
725 }
726 #else
727 static __inline void
728 tcp_sack_dump_history(char *msg, struct tcpcb *tp)
729 {
730 }
731 #endif
732 
733 /*
734  * Remove old SACK blocks from the SACK history that have already been ACKed.
735  */
736 static void
737 tcp_sack_ack_history(struct tcpcb *tp)
738 {
739 	int i, nblocks, openslot;
740 
741 	tcp_sack_dump_history("before tcp_sack_ack_history", tp);
742 	nblocks = tp->nsackhistory;
743 	for (i = openslot = 0; i < nblocks; ++i) {
744 		if (SEQ_LEQ(tp->sackhistory[i].rblk_end, tp->rcv_nxt)) {
745 			--tp->nsackhistory;
746 			continue;
747 		}
748 		if (SEQ_LT(tp->sackhistory[i].rblk_start, tp->rcv_nxt))
749 			tp->sackhistory[i].rblk_start = tp->rcv_nxt;
750 		if (i == openslot)
751 			++openslot;
752 		else
753 			tp->sackhistory[openslot++] = tp->sackhistory[i];
754 	}
755 	tcp_sack_dump_history("after tcp_sack_ack_history", tp);
756 	KASSERT(openslot == tp->nsackhistory,
757 	    ("tcp_sack_ack_history miscounted: %d != %d",
758 	    openslot, tp->nsackhistory));
759 }
760 
761 /*
762  * Add or merge newblock into reported history.
763  * Also remove or update SACK blocks that will be acked.
764  */
765 static void
766 tcp_sack_update_reported_history(struct tcpcb *tp, tcp_seq start, tcp_seq end)
767 {
768 	struct raw_sackblock copy[MAX_SACK_REPORT_BLOCKS];
769 	int i, cindex;
770 
771 	tcp_sack_dump_history("before tcp_sack_update_reported_history", tp);
772 	/*
773 	 * Six cases:
774 	 *	0) no overlap
775 	 *	1) newblock == oldblock
776 	 *	2) oldblock contains newblock
777 	 *	3) newblock contains oldblock
778 	 *	4) tail of oldblock overlaps or abuts start of newblock
779 	 *	5) tail of newblock overlaps or abuts head of oldblock
780 	 */
781 	for (i = cindex = 0; i < tp->nsackhistory; ++i) {
782 		struct raw_sackblock *oldblock = &tp->sackhistory[i];
783 		tcp_seq old_start = oldblock->rblk_start;
784 		tcp_seq old_end = oldblock->rblk_end;
785 
786 		if (SEQ_LT(end, old_start) || SEQ_GT(start, old_end)) {
787 			/* Case 0:  no overlap.  Copy old block. */
788 			copy[cindex++] = *oldblock;
789 			continue;
790 		}
791 
792 		if (SEQ_GEQ(start, old_start) && SEQ_LEQ(end, old_end)) {
793 			/* Cases 1 & 2.  Move block to front of history. */
794 			int j;
795 
796 			start = old_start;
797 			end = old_end;
798 			/* no need to check rest of blocks */
799 			for (j = i + 1; j < tp->nsackhistory; ++j)
800 				copy[cindex++] = tp->sackhistory[j];
801 			break;
802 		}
803 
804 		if (SEQ_GEQ(old_end, start) && SEQ_LT(old_start, start)) {
805 			/* Case 4:  extend start of new block. */
806 			start = old_start;
807 		} else if (SEQ_GEQ(end, old_start) && SEQ_GT(old_end, end)) {
808 			/* Case 5: extend end of new block */
809 			end = old_end;
810 		} else {
811 			/* Case 3.  Delete old block by not copying it. */
812 			KASSERT(SEQ_LEQ(start, old_start) &&
813 				SEQ_GEQ(end, old_end),
814 			    ("bad logic: old [%u, %u), new [%u, %u)",
815 			     old_start, old_end, start, end));
816 		}
817 	}
818 
819 	/* insert new block */
820 	tp->sackhistory[0].rblk_start = start;
821 	tp->sackhistory[0].rblk_end = end;
822 	cindex = min(cindex, MAX_SACK_REPORT_BLOCKS - 1);
823 	for (i = 0; i < cindex; ++i)
824 		tp->sackhistory[i + 1] = copy[i];
825 	tp->nsackhistory = cindex + 1;
826 	tcp_sack_dump_history("after tcp_sack_update_reported_history", tp);
827 }
828 
829 /*
830  * Fill in SACK report to return to data sender.
831  */
832 void
833 tcp_sack_fill_report(struct tcpcb *tp, u_char *opt, u_int *plen)
834 {
835 	u_int optlen = *plen;
836 	uint32_t *lp = (uint32_t *)(opt + optlen);
837 	uint32_t *olp;
838 	tcp_seq hstart = tp->rcv_nxt, hend;
839 	int nblocks;
840 
841 	KASSERT(TCP_MAXOLEN - optlen >=
842 	    TCPOLEN_SACK_ALIGNED + TCPOLEN_SACK_BLOCK,
843 	    ("no room for SACK header and one block: optlen %d", optlen));
844 
845 	if (tp->sack_flags & TSACK_F_DUPSEG)
846 		tcpstat.tcps_snddsackopt++;
847 	else
848 		tcpstat.tcps_sndsackopt++;
849 
850 	olp = lp++;
851 	optlen += TCPOLEN_SACK_ALIGNED;
852 
853 	tcp_sack_ack_history(tp);
854 	if (tp->reportblk.rblk_start != tp->reportblk.rblk_end) {
855 		*lp++ = htonl(tp->reportblk.rblk_start);
856 		*lp++ = htonl(tp->reportblk.rblk_end);
857 		optlen += TCPOLEN_SACK_BLOCK;
858 		hstart = tp->reportblk.rblk_start;
859 		hend = tp->reportblk.rblk_end;
860 		if (tp->sack_flags & TSACK_F_ENCLOSESEG) {
861 			KASSERT(TCP_MAXOLEN - optlen >= TCPOLEN_SACK_BLOCK,
862 			    ("no room for enclosing SACK block: oplen %d",
863 			    optlen));
864 			*lp++ = htonl(tp->encloseblk.rblk_start);
865 			*lp++ = htonl(tp->encloseblk.rblk_end);
866 			optlen += TCPOLEN_SACK_BLOCK;
867 			hstart = tp->encloseblk.rblk_start;
868 			hend = tp->encloseblk.rblk_end;
869 		}
870 		if (SEQ_GT(hstart, tp->rcv_nxt))
871 			tcp_sack_update_reported_history(tp, hstart, hend);
872 	}
873 	if (tcp_do_smartsack && (tp->sack_flags & TSACK_F_SACKLEFT)) {
874 		/* Fill in from left!  Walk re-assembly queue. */
875 		struct tseg_qent *q;
876 
877 		q = LIST_FIRST(&tp->t_segq);
878 		while (q != NULL &&
879 		    TCP_MAXOLEN - optlen >= TCPOLEN_SACK_BLOCK) {
880 			*lp++ = htonl(q->tqe_th->th_seq);
881 			*lp++ = htonl(TCP_SACK_BLKEND(
882 			    q->tqe_th->th_seq + q->tqe_len,
883 			    q->tqe_th->th_flags));
884 			optlen += TCPOLEN_SACK_BLOCK;
885 			q = LIST_NEXT(q, tqe_q);
886 		}
887 	} else {
888 		int n = 0;
889 
890 		/* Fill in SACK blocks from right side. */
891 		while (n < tp->nsackhistory &&
892 		    TCP_MAXOLEN - optlen >= TCPOLEN_SACK_BLOCK) {
893 			if (tp->sackhistory[n].rblk_start != hstart) {
894 				*lp++ = htonl(tp->sackhistory[n].rblk_start);
895 				*lp++ = htonl(tp->sackhistory[n].rblk_end);
896 				optlen += TCPOLEN_SACK_BLOCK;
897 			}
898 			++n;
899 		}
900 	}
901 	tp->reportblk.rblk_start = tp->reportblk.rblk_end;
902 	tp->sack_flags &=
903 	    ~(TSACK_F_DUPSEG | TSACK_F_ENCLOSESEG | TSACK_F_SACKLEFT);
904 	nblocks = (lp - olp - 1) / 2;
905 	*olp = htonl(TCPOPT_SACK_ALIGNED |
906 		     (TCPOLEN_SACK + nblocks * TCPOLEN_SACK_BLOCK));
907 	*plen = optlen;
908 }
909