xref: /titanic_44/usr/src/uts/common/inet/tcp/tcp_timers.c (revision a31148363f598def767ac48c5d82e1572e44b935)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/strlog.h>
29 #include <sys/strsun.h>
30 #include <sys/squeue_impl.h>
31 #include <sys/squeue.h>
32 #include <sys/callo.h>
33 #include <sys/strsubr.h>
34 
35 #include <inet/common.h>
36 #include <inet/ip.h>
37 #include <inet/ip_ire.h>
38 #include <inet/ip_rts.h>
39 #include <inet/tcp.h>
40 #include <inet/tcp_impl.h>
41 
42 /*
43  * Implementation of TCP Timers.
44  * =============================
45  *
46  * INTERFACE:
47  *
48  * There are two basic functions dealing with tcp timers:
49  *
50  *	timeout_id_t	tcp_timeout(connp, func, time)
51  * 	clock_t		tcp_timeout_cancel(connp, timeout_id)
52  *	TCP_TIMER_RESTART(tcp, intvl)
53  *
54  * tcp_timeout() starts a timer for the 'tcp' instance arranging to call 'func'
55  * after 'time' ticks passed. The function called by timeout() must adhere to
56  * the same restrictions as a driver soft interrupt handler - it must not sleep
57  * or call other functions that might sleep. The value returned is the opaque
58  * non-zero timeout identifier that can be passed to tcp_timeout_cancel() to
59  * cancel the request. The call to tcp_timeout() may fail in which case it
60  * returns zero. This is different from the timeout(9F) function which never
61  * fails.
62  *
63  * The call-back function 'func' always receives 'connp' as its single
64  * argument. It is always executed in the squeue corresponding to the tcp
65  * structure. The tcp structure is guaranteed to be present at the time the
66  * call-back is called.
67  *
68  * NOTE: The call-back function 'func' is never called if tcp is in
69  * 	the TCPS_CLOSED state.
70  *
71  * tcp_timeout_cancel() attempts to cancel a pending tcp_timeout()
72  * request. locks acquired by the call-back routine should not be held across
73  * the call to tcp_timeout_cancel() or a deadlock may result.
74  *
75  * tcp_timeout_cancel() returns -1 if it can not cancel the timeout request.
76  * Otherwise, it returns an integer value greater than or equal to 0. In
77  * particular, if the call-back function is already placed on the squeue, it can
78  * not be canceled.
79  *
80  * NOTE: both tcp_timeout() and tcp_timeout_cancel() should always be called
81  * 	within squeue context corresponding to the tcp instance. Since the
82  *	call-back is also called via the same squeue, there are no race
83  *	conditions described in untimeout(9F) manual page since all calls are
84  *	strictly serialized.
85  *
86  *      TCP_TIMER_RESTART() is a macro that attempts to cancel a pending timeout
87  *	stored in tcp_timer_tid and starts a new one using
88  *	MSEC_TO_TICK(intvl). It always uses tcp_timer() function as a call-back
89  *	and stores the return value of tcp_timeout() in the tcp->tcp_timer_tid
90  *	field.
91  *
92  * NOTE: since the timeout cancellation is not guaranteed, the cancelled
93  *	call-back may still be called, so it is possible tcp_timer() will be
94  *	called several times. This should not be a problem since tcp_timer()
95  *	should always check the tcp instance state.
96  *
97  *
98  * IMPLEMENTATION:
99  *
100  * TCP timers are implemented using three-stage process. The call to
101  * tcp_timeout() uses timeout(9F) function to call tcp_timer_callback() function
102  * when the timer expires. The tcp_timer_callback() arranges the call of the
103  * tcp_timer_handler() function via squeue corresponding to the tcp
104  * instance. The tcp_timer_handler() calls actual requested timeout call-back
105  * and passes tcp instance as an argument to it. Information is passed between
106  * stages using the tcp_timer_t structure which contains the connp pointer, the
107  * tcp call-back to call and the timeout id returned by the timeout(9F).
108  *
109  * The tcp_timer_t structure is not used directly, it is embedded in an mblk_t -
110  * like structure that is used to enter an squeue. The mp->b_rptr of this pseudo
111  * mblk points to the beginning of tcp_timer_t structure. The tcp_timeout()
112  * returns the pointer to this mblk.
113  *
114  * The pseudo mblk is allocated from a special tcp_timer_cache kmem cache. It
115  * looks like a normal mblk without actual dblk attached to it.
116  *
117  * To optimize performance each tcp instance holds a small cache of timer
118  * mblocks. In the current implementation it caches up to two timer mblocks per
119  * tcp instance. The cache is preserved over tcp frees and is only freed when
120  * the whole tcp structure is destroyed by its kmem destructor. Since all tcp
121  * timer processing happens on a corresponding squeue, the cache manipulation
122  * does not require any locks. Experiments show that majority of timer mblocks
123  * allocations are satisfied from the tcp cache and do not involve kmem calls.
124  *
125  * The tcp_timeout() places a refhold on the connp instance which guarantees
126  * that it will be present at the time the call-back function fires. The
127  * tcp_timer_handler() drops the reference after calling the call-back, so the
128  * call-back function does not need to manipulate the references explicitly.
129  */
130 
131 kmem_cache_t *tcp_timercache;
132 
133 static void	tcp_ip_notify(tcp_t *);
134 static void	tcp_timer_callback(void *);
135 static void	tcp_timer_free(tcp_t *, mblk_t *);
136 static void	tcp_timer_handler(void *, mblk_t *, void *, ip_recv_attr_t *);
137 
138 timeout_id_t
139 tcp_timeout(conn_t *connp, void (*f)(void *), clock_t tim)
140 {
141 	mblk_t *mp;
142 	tcp_timer_t *tcpt;
143 	tcp_t *tcp = connp->conn_tcp;
144 
145 	ASSERT(connp->conn_sqp != NULL);
146 
147 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_calls);
148 
149 	if (tcp->tcp_timercache == NULL) {
150 		mp = tcp_timermp_alloc(KM_NOSLEEP | KM_PANIC);
151 	} else {
152 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timeout_cached_alloc);
153 		mp = tcp->tcp_timercache;
154 		tcp->tcp_timercache = mp->b_next;
155 		mp->b_next = NULL;
156 		ASSERT(mp->b_wptr == NULL);
157 	}
158 
159 	CONN_INC_REF(connp);
160 	tcpt = (tcp_timer_t *)mp->b_rptr;
161 	tcpt->connp = connp;
162 	tcpt->tcpt_proc = f;
163 	/*
164 	 * TCP timers are normal timeouts. Plus, they do not require more than
165 	 * a 10 millisecond resolution. By choosing a coarser resolution and by
166 	 * rounding up the expiration to the next resolution boundary, we can
167 	 * batch timers in the callout subsystem to make TCP timers more
168 	 * efficient. The roundup also protects short timers from expiring too
169 	 * early before they have a chance to be cancelled.
170 	 */
171 	tcpt->tcpt_tid = timeout_generic(CALLOUT_NORMAL, tcp_timer_callback, mp,
172 	    TICK_TO_NSEC(tim), CALLOUT_TCP_RESOLUTION, CALLOUT_FLAG_ROUNDUP);
173 
174 	return ((timeout_id_t)mp);
175 }
176 
177 static void
178 tcp_timer_callback(void *arg)
179 {
180 	mblk_t *mp = (mblk_t *)arg;
181 	tcp_timer_t *tcpt;
182 	conn_t	*connp;
183 
184 	tcpt = (tcp_timer_t *)mp->b_rptr;
185 	connp = tcpt->connp;
186 	SQUEUE_ENTER_ONE(connp->conn_sqp, mp, tcp_timer_handler, connp,
187 	    NULL, SQ_FILL, SQTAG_TCP_TIMER);
188 }
189 
190 /* ARGSUSED */
191 static void
192 tcp_timer_handler(void *arg, mblk_t *mp, void *arg2, ip_recv_attr_t *dummy)
193 {
194 	tcp_timer_t *tcpt;
195 	conn_t *connp = (conn_t *)arg;
196 	tcp_t *tcp = connp->conn_tcp;
197 
198 	tcpt = (tcp_timer_t *)mp->b_rptr;
199 	ASSERT(connp == tcpt->connp);
200 	ASSERT((squeue_t *)arg2 == connp->conn_sqp);
201 
202 	/*
203 	 * If the TCP has reached the closed state, don't proceed any
204 	 * further. This TCP logically does not exist on the system.
205 	 * tcpt_proc could for example access queues, that have already
206 	 * been qprocoff'ed off.
207 	 */
208 	if (tcp->tcp_state != TCPS_CLOSED) {
209 		(*tcpt->tcpt_proc)(connp);
210 	} else {
211 		tcp->tcp_timer_tid = 0;
212 	}
213 	tcp_timer_free(connp->conn_tcp, mp);
214 }
215 
216 /*
217  * There is potential race with untimeout and the handler firing at the same
218  * time. The mblock may be freed by the handler while we are trying to use
219  * it. But since both should execute on the same squeue, this race should not
220  * occur.
221  */
222 clock_t
223 tcp_timeout_cancel(conn_t *connp, timeout_id_t id)
224 {
225 	mblk_t	*mp = (mblk_t *)id;
226 	tcp_timer_t *tcpt;
227 	clock_t delta;
228 
229 	TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_cancel_reqs);
230 
231 	if (mp == NULL)
232 		return (-1);
233 
234 	tcpt = (tcp_timer_t *)mp->b_rptr;
235 	ASSERT(tcpt->connp == connp);
236 
237 	delta = untimeout_default(tcpt->tcpt_tid, 0);
238 
239 	if (delta >= 0) {
240 		TCP_DBGSTAT(connp->conn_tcp->tcp_tcps, tcp_timeout_canceled);
241 		tcp_timer_free(connp->conn_tcp, mp);
242 		CONN_DEC_REF(connp);
243 	}
244 
245 	return (delta);
246 }
247 
248 /*
249  * Allocate space for the timer event. The allocation looks like mblk, but it is
250  * not a proper mblk. To avoid confusion we set b_wptr to NULL.
251  *
252  * Dealing with failures: If we can't allocate from the timer cache we try
253  * allocating from dblock caches using allocb_tryhard(). In this case b_wptr
254  * points to b_rptr.
255  * If we can't allocate anything using allocb_tryhard(), we perform a last
256  * attempt and use kmem_alloc_tryhard(). In this case we set b_wptr to -1 and
257  * save the actual allocation size in b_datap.
258  */
259 mblk_t *
260 tcp_timermp_alloc(int kmflags)
261 {
262 	mblk_t *mp = (mblk_t *)kmem_cache_alloc(tcp_timercache,
263 	    kmflags & ~KM_PANIC);
264 
265 	if (mp != NULL) {
266 		mp->b_next = mp->b_prev = NULL;
267 		mp->b_rptr = (uchar_t *)(&mp[1]);
268 		mp->b_wptr = NULL;
269 		mp->b_datap = NULL;
270 		mp->b_queue = NULL;
271 		mp->b_cont = NULL;
272 	} else if (kmflags & KM_PANIC) {
273 		/*
274 		 * Failed to allocate memory for the timer. Try allocating from
275 		 * dblock caches.
276 		 */
277 		/* ipclassifier calls this from a constructor - hence no tcps */
278 		TCP_G_STAT(tcp_timermp_allocfail);
279 		mp = allocb_tryhard(sizeof (tcp_timer_t));
280 		if (mp == NULL) {
281 			size_t size = 0;
282 			/*
283 			 * Memory is really low. Try tryhard allocation.
284 			 *
285 			 * ipclassifier calls this from a constructor -
286 			 * hence no tcps
287 			 */
288 			TCP_G_STAT(tcp_timermp_allocdblfail);
289 			mp = kmem_alloc_tryhard(sizeof (mblk_t) +
290 			    sizeof (tcp_timer_t), &size, kmflags);
291 			mp->b_rptr = (uchar_t *)(&mp[1]);
292 			mp->b_next = mp->b_prev = NULL;
293 			mp->b_wptr = (uchar_t *)-1;
294 			mp->b_datap = (dblk_t *)size;
295 			mp->b_queue = NULL;
296 			mp->b_cont = NULL;
297 		}
298 		ASSERT(mp->b_wptr != NULL);
299 	}
300 	/* ipclassifier calls this from a constructor - hence no tcps */
301 	TCP_G_DBGSTAT(tcp_timermp_alloced);
302 
303 	return (mp);
304 }
305 
306 /*
307  * Free per-tcp timer cache.
308  * It can only contain entries from tcp_timercache.
309  */
310 void
311 tcp_timermp_free(tcp_t *tcp)
312 {
313 	mblk_t *mp;
314 
315 	while ((mp = tcp->tcp_timercache) != NULL) {
316 		ASSERT(mp->b_wptr == NULL);
317 		tcp->tcp_timercache = tcp->tcp_timercache->b_next;
318 		kmem_cache_free(tcp_timercache, mp);
319 	}
320 }
321 
322 /*
323  * Free timer event. Put it on the per-tcp timer cache if there is not too many
324  * events there already (currently at most two events are cached).
325  * If the event is not allocated from the timer cache, free it right away.
326  */
327 static void
328 tcp_timer_free(tcp_t *tcp, mblk_t *mp)
329 {
330 	mblk_t *mp1 = tcp->tcp_timercache;
331 
332 	if (mp->b_wptr != NULL) {
333 		/*
334 		 * This allocation is not from a timer cache, free it right
335 		 * away.
336 		 */
337 		if (mp->b_wptr != (uchar_t *)-1)
338 			freeb(mp);
339 		else
340 			kmem_free(mp, (size_t)mp->b_datap);
341 	} else if (mp1 == NULL || mp1->b_next == NULL) {
342 		/* Cache this timer block for future allocations */
343 		mp->b_rptr = (uchar_t *)(&mp[1]);
344 		mp->b_next = mp1;
345 		tcp->tcp_timercache = mp;
346 	} else {
347 		kmem_cache_free(tcp_timercache, mp);
348 		TCP_DBGSTAT(tcp->tcp_tcps, tcp_timermp_freed);
349 	}
350 }
351 
352 /*
353  * Stop all TCP timers.
354  */
355 void
356 tcp_timers_stop(tcp_t *tcp)
357 {
358 	if (tcp->tcp_timer_tid != 0) {
359 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_timer_tid);
360 		tcp->tcp_timer_tid = 0;
361 	}
362 	if (tcp->tcp_ka_tid != 0) {
363 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ka_tid);
364 		tcp->tcp_ka_tid = 0;
365 	}
366 	if (tcp->tcp_ack_tid != 0) {
367 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_ack_tid);
368 		tcp->tcp_ack_tid = 0;
369 	}
370 	if (tcp->tcp_push_tid != 0) {
371 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_push_tid);
372 		tcp->tcp_push_tid = 0;
373 	}
374 	if (tcp->tcp_reass_tid != 0) {
375 		(void) TCP_TIMER_CANCEL(tcp, tcp->tcp_reass_tid);
376 		tcp->tcp_reass_tid = 0;
377 	}
378 }
379 
380 /*
381  * Timer callback routine for keepalive probe.  We do a fake resend of
382  * last ACKed byte.  Then set a timer using RTO.  When the timer expires,
383  * check to see if we have heard anything from the other end for the last
384  * RTO period.  If we have, set the timer to expire for another
385  * tcp_keepalive_intrvl and check again.  If we have not, set a timer using
386  * RTO << 1 and check again when it expires.  Keep exponentially increasing
387  * the timeout if we have not heard from the other side.  If for more than
388  * (tcp_ka_interval + tcp_ka_abort_thres) we have not heard anything,
389  * kill the connection unless the keepalive abort threshold is 0.  In
390  * that case, we will probe "forever."
391  */
392 void
393 tcp_keepalive_timer(void *arg)
394 {
395 	mblk_t	*mp;
396 	conn_t	*connp = (conn_t *)arg;
397 	tcp_t  	*tcp = connp->conn_tcp;
398 	int32_t	firetime;
399 	int32_t	idletime;
400 	int32_t	ka_intrvl;
401 	tcp_stack_t	*tcps = tcp->tcp_tcps;
402 
403 	tcp->tcp_ka_tid = 0;
404 
405 	if (tcp->tcp_fused)
406 		return;
407 
408 	TCPS_BUMP_MIB(tcps, tcpTimKeepalive);
409 	ka_intrvl = tcp->tcp_ka_interval;
410 
411 	/*
412 	 * Keepalive probe should only be sent if the application has not
413 	 * done a close on the connection.
414 	 */
415 	if (tcp->tcp_state > TCPS_CLOSE_WAIT) {
416 		return;
417 	}
418 	/* Timer fired too early, restart it. */
419 	if (tcp->tcp_state < TCPS_ESTABLISHED) {
420 		tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_timer,
421 		    MSEC_TO_TICK(ka_intrvl));
422 		return;
423 	}
424 
425 	idletime = TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time);
426 	/*
427 	 * If we have not heard from the other side for a long
428 	 * time, kill the connection unless the keepalive abort
429 	 * threshold is 0.  In that case, we will probe "forever."
430 	 */
431 	if (tcp->tcp_ka_abort_thres != 0 &&
432 	    idletime > (ka_intrvl + tcp->tcp_ka_abort_thres)) {
433 		TCPS_BUMP_MIB(tcps, tcpTimKeepaliveDrop);
434 		(void) tcp_clean_death(tcp, tcp->tcp_client_errno ?
435 		    tcp->tcp_client_errno : ETIMEDOUT);
436 		return;
437 	}
438 
439 	if (tcp->tcp_snxt == tcp->tcp_suna &&
440 	    idletime >= ka_intrvl) {
441 		/* Fake resend of last ACKed byte. */
442 		mblk_t	*mp1 = allocb(1, BPRI_LO);
443 
444 		if (mp1 != NULL) {
445 			*mp1->b_wptr++ = '\0';
446 			mp = tcp_xmit_mp(tcp, mp1, 1, NULL, NULL,
447 			    tcp->tcp_suna - 1, B_FALSE, NULL, B_TRUE);
448 			freeb(mp1);
449 			/*
450 			 * if allocation failed, fall through to start the
451 			 * timer back.
452 			 */
453 			if (mp != NULL) {
454 				tcp_send_data(tcp, mp);
455 				TCPS_BUMP_MIB(tcps, tcpTimKeepaliveProbe);
456 				if (tcp->tcp_ka_last_intrvl != 0) {
457 					int max;
458 					/*
459 					 * We should probe again at least
460 					 * in ka_intrvl, but not more than
461 					 * tcp_rexmit_interval_max.
462 					 */
463 					max = tcps->tcps_rexmit_interval_max;
464 					firetime = MIN(ka_intrvl - 1,
465 					    tcp->tcp_ka_last_intrvl << 1);
466 					if (firetime > max)
467 						firetime = max;
468 				} else {
469 					firetime = tcp->tcp_rto;
470 				}
471 				tcp->tcp_ka_tid = TCP_TIMER(tcp,
472 				    tcp_keepalive_timer,
473 				    MSEC_TO_TICK(firetime));
474 				tcp->tcp_ka_last_intrvl = firetime;
475 				return;
476 			}
477 		}
478 	} else {
479 		tcp->tcp_ka_last_intrvl = 0;
480 	}
481 
482 	/* firetime can be negative if (mp1 == NULL || mp == NULL) */
483 	if ((firetime = ka_intrvl - idletime) < 0) {
484 		firetime = ka_intrvl;
485 	}
486 	tcp->tcp_ka_tid = TCP_TIMER(tcp, tcp_keepalive_timer,
487 	    MSEC_TO_TICK(firetime));
488 }
489 
490 void
491 tcp_reass_timer(void *arg)
492 {
493 	conn_t *connp = (conn_t *)arg;
494 	tcp_t *tcp = connp->conn_tcp;
495 
496 	tcp->tcp_reass_tid = 0;
497 	if (tcp->tcp_reass_head == NULL)
498 		return;
499 	ASSERT(tcp->tcp_reass_tail != NULL);
500 	if (tcp->tcp_snd_sack_ok && tcp->tcp_num_sack_blk > 0) {
501 		tcp_sack_remove(tcp->tcp_sack_list,
502 		    TCP_REASS_END(tcp->tcp_reass_tail), &tcp->tcp_num_sack_blk);
503 	}
504 	tcp_close_mpp(&tcp->tcp_reass_head);
505 	tcp->tcp_reass_tail = NULL;
506 	TCP_STAT(tcp->tcp_tcps, tcp_reass_timeout);
507 }
508 
509 /* This function handles the push timeout. */
510 void
511 tcp_push_timer(void *arg)
512 {
513 	conn_t	*connp = (conn_t *)arg;
514 	tcp_t *tcp = connp->conn_tcp;
515 
516 	TCP_DBGSTAT(tcp->tcp_tcps, tcp_push_timer_cnt);
517 
518 	ASSERT(tcp->tcp_listener == NULL);
519 
520 	ASSERT(!IPCL_IS_NONSTR(connp));
521 
522 	tcp->tcp_push_tid = 0;
523 
524 	if (tcp->tcp_rcv_list != NULL &&
525 	    tcp_rcv_drain(tcp) == TH_ACK_NEEDED)
526 		tcp_xmit_ctl(NULL, tcp, tcp->tcp_snxt, tcp->tcp_rnxt, TH_ACK);
527 }
528 
529 /*
530  * This function handles delayed ACK timeout.
531  */
532 void
533 tcp_ack_timer(void *arg)
534 {
535 	conn_t	*connp = (conn_t *)arg;
536 	tcp_t *tcp = connp->conn_tcp;
537 	mblk_t *mp;
538 	tcp_stack_t	*tcps = tcp->tcp_tcps;
539 
540 	TCP_DBGSTAT(tcps, tcp_ack_timer_cnt);
541 
542 	tcp->tcp_ack_tid = 0;
543 
544 	if (tcp->tcp_fused)
545 		return;
546 
547 	/*
548 	 * Do not send ACK if there is no outstanding unack'ed data.
549 	 */
550 	if (tcp->tcp_rnxt == tcp->tcp_rack) {
551 		return;
552 	}
553 
554 	if ((tcp->tcp_rnxt - tcp->tcp_rack) > tcp->tcp_mss) {
555 		/*
556 		 * Make sure we don't allow deferred ACKs to result in
557 		 * timer-based ACKing.  If we have held off an ACK
558 		 * when there was more than an mss here, and the timer
559 		 * goes off, we have to worry about the possibility
560 		 * that the sender isn't doing slow-start, or is out
561 		 * of step with us for some other reason.  We fall
562 		 * permanently back in the direction of
563 		 * ACK-every-other-packet as suggested in RFC 1122.
564 		 */
565 		if (tcp->tcp_rack_abs_max > 2)
566 			tcp->tcp_rack_abs_max--;
567 		tcp->tcp_rack_cur_max = 2;
568 	}
569 	mp = tcp_ack_mp(tcp);
570 
571 	if (mp != NULL) {
572 		BUMP_LOCAL(tcp->tcp_obsegs);
573 		TCPS_BUMP_MIB(tcps, tcpOutAck);
574 		TCPS_BUMP_MIB(tcps, tcpOutAckDelayed);
575 		tcp_send_data(tcp, mp);
576 	}
577 }
578 
579 /*
580  * Notify IP that we are having trouble with this connection.  IP should
581  * make note so it can potentially use a different IRE.
582  */
583 static void
584 tcp_ip_notify(tcp_t *tcp)
585 {
586 	conn_t		*connp = tcp->tcp_connp;
587 	ire_t		*ire;
588 
589 	/*
590 	 * Note: in the case of source routing we want to blow away the
591 	 * route to the first source route hop.
592 	 */
593 	ire = connp->conn_ixa->ixa_ire;
594 	if (ire != NULL && !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
595 		if (ire->ire_ipversion == IPV4_VERSION) {
596 			/*
597 			 * As per RFC 1122, we send an RTM_LOSING to inform
598 			 * routing protocols.
599 			 */
600 			ip_rts_change(RTM_LOSING, ire->ire_addr,
601 			    ire->ire_gateway_addr, ire->ire_mask,
602 			    connp->conn_laddr_v4,  0, 0, 0,
603 			    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA),
604 			    ire->ire_ipst);
605 		}
606 		(void) ire_no_good(ire);
607 	}
608 }
609 
610 /*
611  * tcp_timer is the timer service routine.  It handles the retransmission,
612  * FIN_WAIT_2 flush, and zero window probe timeout events.  It figures out
613  * from the state of the tcp instance what kind of action needs to be done
614  * at the time it is called.
615  */
616 void
617 tcp_timer(void *arg)
618 {
619 	mblk_t		*mp;
620 	clock_t		first_threshold;
621 	clock_t		second_threshold;
622 	clock_t		ms;
623 	uint32_t	mss;
624 	conn_t		*connp = (conn_t *)arg;
625 	tcp_t		*tcp = connp->conn_tcp;
626 	tcp_stack_t	*tcps = tcp->tcp_tcps;
627 
628 	tcp->tcp_timer_tid = 0;
629 
630 	if (tcp->tcp_fused)
631 		return;
632 
633 	first_threshold =  tcp->tcp_first_timer_threshold;
634 	second_threshold = tcp->tcp_second_timer_threshold;
635 	switch (tcp->tcp_state) {
636 	case TCPS_IDLE:
637 	case TCPS_BOUND:
638 	case TCPS_LISTEN:
639 		return;
640 	case TCPS_SYN_RCVD: {
641 		tcp_t	*listener = tcp->tcp_listener;
642 
643 		if (tcp->tcp_syn_rcvd_timeout == 0 && (listener != NULL)) {
644 			/* it's our first timeout */
645 			tcp->tcp_syn_rcvd_timeout = 1;
646 			mutex_enter(&listener->tcp_eager_lock);
647 			listener->tcp_syn_rcvd_timeout++;
648 			if (!tcp->tcp_dontdrop && !tcp->tcp_closemp_used) {
649 				/*
650 				 * Make this eager available for drop if we
651 				 * need to drop one to accomodate a new
652 				 * incoming SYN request.
653 				 */
654 				MAKE_DROPPABLE(listener, tcp);
655 			}
656 			if (!listener->tcp_syn_defense &&
657 			    (listener->tcp_syn_rcvd_timeout >
658 			    (tcps->tcps_conn_req_max_q0 >> 2)) &&
659 			    (tcps->tcps_conn_req_max_q0 > 200)) {
660 				/* We may be under attack. Put on a defense. */
661 				listener->tcp_syn_defense = B_TRUE;
662 				cmn_err(CE_WARN, "High TCP connect timeout "
663 				    "rate! System (port %d) may be under a "
664 				    "SYN flood attack!",
665 				    ntohs(listener->tcp_connp->conn_lport));
666 
667 				listener->tcp_ip_addr_cache = kmem_zalloc(
668 				    IP_ADDR_CACHE_SIZE * sizeof (ipaddr_t),
669 				    KM_NOSLEEP);
670 			}
671 			mutex_exit(&listener->tcp_eager_lock);
672 		} else if (listener != NULL) {
673 			mutex_enter(&listener->tcp_eager_lock);
674 			tcp->tcp_syn_rcvd_timeout++;
675 			if (tcp->tcp_syn_rcvd_timeout > 1 &&
676 			    !tcp->tcp_closemp_used) {
677 				/*
678 				 * This is our second timeout. Put the tcp in
679 				 * the list of droppable eagers to allow it to
680 				 * be dropped, if needed. We don't check
681 				 * whether tcp_dontdrop is set or not to
682 				 * protect ourselve from a SYN attack where a
683 				 * remote host can spoof itself as one of the
684 				 * good IP source and continue to hold
685 				 * resources too long.
686 				 */
687 				MAKE_DROPPABLE(listener, tcp);
688 			}
689 			mutex_exit(&listener->tcp_eager_lock);
690 		}
691 	}
692 		/* FALLTHRU */
693 	case TCPS_SYN_SENT:
694 		first_threshold =  tcp->tcp_first_ctimer_threshold;
695 		second_threshold = tcp->tcp_second_ctimer_threshold;
696 		break;
697 	case TCPS_ESTABLISHED:
698 	case TCPS_FIN_WAIT_1:
699 	case TCPS_CLOSING:
700 	case TCPS_CLOSE_WAIT:
701 	case TCPS_LAST_ACK:
702 		/* If we have data to rexmit */
703 		if (tcp->tcp_suna != tcp->tcp_snxt) {
704 			clock_t	time_to_wait;
705 
706 			TCPS_BUMP_MIB(tcps, tcpTimRetrans);
707 			if (!tcp->tcp_xmit_head)
708 				break;
709 			time_to_wait = ddi_get_lbolt() -
710 			    (clock_t)tcp->tcp_xmit_head->b_prev;
711 			time_to_wait = tcp->tcp_rto -
712 			    TICK_TO_MSEC(time_to_wait);
713 			/*
714 			 * If the timer fires too early, 1 clock tick earlier,
715 			 * restart the timer.
716 			 */
717 			if (time_to_wait > msec_per_tick) {
718 				TCP_STAT(tcps, tcp_timer_fire_early);
719 				TCP_TIMER_RESTART(tcp, time_to_wait);
720 				return;
721 			}
722 			/*
723 			 * When we probe zero windows, we force the swnd open.
724 			 * If our peer acks with a closed window swnd will be
725 			 * set to zero by tcp_rput(). As long as we are
726 			 * receiving acks tcp_rput will
727 			 * reset 'tcp_ms_we_have_waited' so as not to trip the
728 			 * first and second interval actions.  NOTE: the timer
729 			 * interval is allowed to continue its exponential
730 			 * backoff.
731 			 */
732 			if (tcp->tcp_swnd == 0 || tcp->tcp_zero_win_probe) {
733 				if (connp->conn_debug) {
734 					(void) strlog(TCP_MOD_ID, 0, 1,
735 					    SL_TRACE, "tcp_timer: zero win");
736 				}
737 			} else {
738 				/*
739 				 * After retransmission, we need to do
740 				 * slow start.  Set the ssthresh to one
741 				 * half of current effective window and
742 				 * cwnd to one MSS.  Also reset
743 				 * tcp_cwnd_cnt.
744 				 *
745 				 * Note that if tcp_ssthresh is reduced because
746 				 * of ECN, do not reduce it again unless it is
747 				 * already one window of data away (tcp_cwr
748 				 * should then be cleared) or this is a
749 				 * timeout for a retransmitted segment.
750 				 */
751 				uint32_t npkt;
752 
753 				if (!tcp->tcp_cwr || tcp->tcp_rexmit) {
754 					npkt = ((tcp->tcp_timer_backoff ?
755 					    tcp->tcp_cwnd_ssthresh :
756 					    tcp->tcp_snxt -
757 					    tcp->tcp_suna) >> 1) / tcp->tcp_mss;
758 					tcp->tcp_cwnd_ssthresh = MAX(npkt, 2) *
759 					    tcp->tcp_mss;
760 				}
761 				tcp->tcp_cwnd = tcp->tcp_mss;
762 				tcp->tcp_cwnd_cnt = 0;
763 				if (tcp->tcp_ecn_ok) {
764 					tcp->tcp_cwr = B_TRUE;
765 					tcp->tcp_cwr_snd_max = tcp->tcp_snxt;
766 					tcp->tcp_ecn_cwr_sent = B_FALSE;
767 				}
768 			}
769 			break;
770 		}
771 		/*
772 		 * We have something to send yet we cannot send.  The
773 		 * reason can be:
774 		 *
775 		 * 1. Zero send window: we need to do zero window probe.
776 		 * 2. Zero cwnd: because of ECN, we need to "clock out
777 		 * segments.
778 		 * 3. SWS avoidance: receiver may have shrunk window,
779 		 * reset our knowledge.
780 		 *
781 		 * Note that condition 2 can happen with either 1 or
782 		 * 3.  But 1 and 3 are exclusive.
783 		 */
784 		if (tcp->tcp_unsent != 0) {
785 			/*
786 			 * Should not hold the zero-copy messages for too long.
787 			 */
788 			if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
789 				tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
790 				    tcp->tcp_xmit_head, B_TRUE);
791 
792 			if (tcp->tcp_cwnd == 0) {
793 				/*
794 				 * Set tcp_cwnd to 1 MSS so that a
795 				 * new segment can be sent out.  We
796 				 * are "clocking out" new data when
797 				 * the network is really congested.
798 				 */
799 				ASSERT(tcp->tcp_ecn_ok);
800 				tcp->tcp_cwnd = tcp->tcp_mss;
801 			}
802 			if (tcp->tcp_swnd == 0) {
803 				/* Extend window for zero window probe */
804 				tcp->tcp_swnd++;
805 				tcp->tcp_zero_win_probe = B_TRUE;
806 				TCPS_BUMP_MIB(tcps, tcpOutWinProbe);
807 			} else {
808 				/*
809 				 * Handle timeout from sender SWS avoidance.
810 				 * Reset our knowledge of the max send window
811 				 * since the receiver might have reduced its
812 				 * receive buffer.  Avoid setting tcp_max_swnd
813 				 * to one since that will essentially disable
814 				 * the SWS checks.
815 				 *
816 				 * Note that since we don't have a SWS
817 				 * state variable, if the timeout is set
818 				 * for ECN but not for SWS, this
819 				 * code will also be executed.  This is
820 				 * fine as tcp_max_swnd is updated
821 				 * constantly and it will not affect
822 				 * anything.
823 				 */
824 				tcp->tcp_max_swnd = MAX(tcp->tcp_swnd, 2);
825 			}
826 			tcp_wput_data(tcp, NULL, B_FALSE);
827 			return;
828 		}
829 		/* Is there a FIN that needs to be to re retransmitted? */
830 		if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
831 		    !tcp->tcp_fin_acked)
832 			break;
833 		/* Nothing to do, return without restarting timer. */
834 		TCP_STAT(tcps, tcp_timer_fire_miss);
835 		return;
836 	case TCPS_FIN_WAIT_2:
837 		/*
838 		 * User closed the TCP endpoint and peer ACK'ed our FIN.
839 		 * We waited some time for for peer's FIN, but it hasn't
840 		 * arrived.  We flush the connection now to avoid
841 		 * case where the peer has rebooted.
842 		 */
843 		if (TCP_IS_DETACHED(tcp)) {
844 			(void) tcp_clean_death(tcp, 0);
845 		} else {
846 			TCP_TIMER_RESTART(tcp,
847 			    tcps->tcps_fin_wait_2_flush_interval);
848 		}
849 		return;
850 	case TCPS_TIME_WAIT:
851 		(void) tcp_clean_death(tcp, 0);
852 		return;
853 	default:
854 		if (connp->conn_debug) {
855 			(void) strlog(TCP_MOD_ID, 0, 1, SL_TRACE|SL_ERROR,
856 			    "tcp_timer: strange state (%d) %s",
857 			    tcp->tcp_state, tcp_display(tcp, NULL,
858 			    DISP_PORT_ONLY));
859 		}
860 		return;
861 	}
862 
863 	/*
864 	 * If the system is under memory pressure or the max number of
865 	 * connections have been established for the listener, be more
866 	 * aggressive in aborting connections.
867 	 */
868 	if (tcps->tcps_reclaim || (tcp->tcp_listen_cnt != NULL &&
869 	    tcp->tcp_listen_cnt->tlc_cnt > tcp->tcp_listen_cnt->tlc_max)) {
870 		second_threshold = tcp_early_abort * SECONDS;
871 	}
872 
873 	if ((ms = tcp->tcp_ms_we_have_waited) > second_threshold) {
874 		/*
875 		 * Should not hold the zero-copy messages for too long.
876 		 */
877 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
878 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
879 			    tcp->tcp_xmit_head, B_TRUE);
880 
881 		/*
882 		 * For zero window probe, we need to send indefinitely,
883 		 * unless we have not heard from the other side for some
884 		 * time...
885 		 */
886 		if ((tcp->tcp_zero_win_probe == 0) ||
887 		    (TICK_TO_MSEC(ddi_get_lbolt() - tcp->tcp_last_recv_time) >
888 		    second_threshold)) {
889 			TCPS_BUMP_MIB(tcps, tcpTimRetransDrop);
890 			/*
891 			 * If TCP is in SYN_RCVD state, send back a
892 			 * RST|ACK as BSD does.  Note that tcp_zero_win_probe
893 			 * should be zero in TCPS_SYN_RCVD state.
894 			 */
895 			if (tcp->tcp_state == TCPS_SYN_RCVD) {
896 				tcp_xmit_ctl("tcp_timer: RST sent on timeout "
897 				    "in SYN_RCVD",
898 				    tcp, tcp->tcp_snxt,
899 				    tcp->tcp_rnxt, TH_RST | TH_ACK);
900 			}
901 			(void) tcp_clean_death(tcp,
902 			    tcp->tcp_client_errno ?
903 			    tcp->tcp_client_errno : ETIMEDOUT);
904 			return;
905 		} else {
906 			/*
907 			 * If the system is under memory pressure, we also
908 			 * abort connection in zero window probing.
909 			 */
910 			if (tcps->tcps_reclaim) {
911 				(void) tcp_clean_death(tcp,
912 				    tcp->tcp_client_errno ?
913 				    tcp->tcp_client_errno : ETIMEDOUT);
914 				TCP_STAT(tcps, tcp_zwin_mem_drop);
915 				return;
916 			}
917 			/*
918 			 * Set tcp_ms_we_have_waited to second_threshold
919 			 * so that in next timeout, we will do the above
920 			 * check (ddi_get_lbolt() - tcp_last_recv_time).
921 			 * This is also to avoid overflow.
922 			 *
923 			 * We don't need to decrement tcp_timer_backoff
924 			 * to avoid overflow because it will be decremented
925 			 * later if new timeout value is greater than
926 			 * tcp_rexmit_interval_max.  In the case when
927 			 * tcp_rexmit_interval_max is greater than
928 			 * second_threshold, it means that we will wait
929 			 * longer than second_threshold to send the next
930 			 * window probe.
931 			 */
932 			tcp->tcp_ms_we_have_waited = second_threshold;
933 		}
934 	} else if (ms > first_threshold) {
935 		/*
936 		 * Should not hold the zero-copy messages for too long.
937 		 */
938 		if (tcp->tcp_snd_zcopy_aware && !tcp->tcp_xmit_zc_clean)
939 			tcp->tcp_xmit_head = tcp_zcopy_backoff(tcp,
940 			    tcp->tcp_xmit_head, B_TRUE);
941 
942 		/*
943 		 * We have been retransmitting for too long...  The RTT
944 		 * we calculated is probably incorrect.  Reinitialize it.
945 		 * Need to compensate for 0 tcp_rtt_sa.  Reset
946 		 * tcp_rtt_update so that we won't accidentally cache a
947 		 * bad value.  But only do this if this is not a zero
948 		 * window probe.
949 		 */
950 		if (tcp->tcp_rtt_sa != 0 && tcp->tcp_zero_win_probe == 0) {
951 			tcp->tcp_rtt_sd += (tcp->tcp_rtt_sa >> 3) +
952 			    (tcp->tcp_rtt_sa >> 5);
953 			tcp->tcp_rtt_sa = 0;
954 			tcp_ip_notify(tcp);
955 			tcp->tcp_rtt_update = 0;
956 		}
957 	}
958 	tcp->tcp_timer_backoff++;
959 	if ((ms = (tcp->tcp_rtt_sa >> 3) + tcp->tcp_rtt_sd +
960 	    tcps->tcps_rexmit_interval_extra + (tcp->tcp_rtt_sa >> 5)) <
961 	    tcps->tcps_rexmit_interval_min) {
962 		/*
963 		 * This means the original RTO is tcp_rexmit_interval_min.
964 		 * So we will use tcp_rexmit_interval_min as the RTO value
965 		 * and do the backoff.
966 		 */
967 		ms = tcps->tcps_rexmit_interval_min << tcp->tcp_timer_backoff;
968 	} else {
969 		ms <<= tcp->tcp_timer_backoff;
970 	}
971 	if (ms > tcps->tcps_rexmit_interval_max) {
972 		ms = tcps->tcps_rexmit_interval_max;
973 		/*
974 		 * ms is at max, decrement tcp_timer_backoff to avoid
975 		 * overflow.
976 		 */
977 		tcp->tcp_timer_backoff--;
978 	}
979 	tcp->tcp_ms_we_have_waited += ms;
980 	if (tcp->tcp_zero_win_probe == 0) {
981 		tcp->tcp_rto = ms;
982 	}
983 	TCP_TIMER_RESTART(tcp, ms);
984 	/*
985 	 * This is after a timeout and tcp_rto is backed off.  Set
986 	 * tcp_set_timer to 1 so that next time RTO is updated, we will
987 	 * restart the timer with a correct value.
988 	 */
989 	tcp->tcp_set_timer = 1;
990 	mss = tcp->tcp_snxt - tcp->tcp_suna;
991 	if (mss > tcp->tcp_mss)
992 		mss = tcp->tcp_mss;
993 	if (mss > tcp->tcp_swnd && tcp->tcp_swnd != 0)
994 		mss = tcp->tcp_swnd;
995 
996 	if ((mp = tcp->tcp_xmit_head) != NULL)
997 		mp->b_prev = (mblk_t *)ddi_get_lbolt();
998 	mp = tcp_xmit_mp(tcp, mp, mss, NULL, NULL, tcp->tcp_suna, B_TRUE, &mss,
999 	    B_TRUE);
1000 
1001 	/*
1002 	 * When slow start after retransmission begins, start with
1003 	 * this seq no.  tcp_rexmit_max marks the end of special slow
1004 	 * start phase.  tcp_snd_burst controls how many segments
1005 	 * can be sent because of an ack.
1006 	 */
1007 	tcp->tcp_rexmit_nxt = tcp->tcp_suna;
1008 	tcp->tcp_snd_burst = TCP_CWND_SS;
1009 	if ((tcp->tcp_valid_bits & TCP_FSS_VALID) &&
1010 	    (tcp->tcp_unsent == 0)) {
1011 		tcp->tcp_rexmit_max = tcp->tcp_fss;
1012 	} else {
1013 		tcp->tcp_rexmit_max = tcp->tcp_snxt;
1014 	}
1015 	tcp->tcp_rexmit = B_TRUE;
1016 	tcp->tcp_dupack_cnt = 0;
1017 
1018 	/*
1019 	 * Remove all rexmit SACK blk to start from fresh.
1020 	 */
1021 	if (tcp->tcp_snd_sack_ok && tcp->tcp_notsack_list != NULL)
1022 		TCP_NOTSACK_REMOVE_ALL(tcp->tcp_notsack_list, tcp);
1023 	if (mp == NULL) {
1024 		return;
1025 	}
1026 
1027 	tcp->tcp_csuna = tcp->tcp_snxt;
1028 	TCPS_BUMP_MIB(tcps, tcpRetransSegs);
1029 	TCPS_UPDATE_MIB(tcps, tcpRetransBytes, mss);
1030 	tcp_send_data(tcp, mp);
1031 
1032 }
1033 
1034 /*
1035  * Handle lingering timeouts. This function is called when the SO_LINGER timeout
1036  * expires.
1037  */
1038 void
1039 tcp_close_linger_timeout(void *arg)
1040 {
1041 	conn_t	*connp = (conn_t *)arg;
1042 	tcp_t 	*tcp = connp->conn_tcp;
1043 
1044 	tcp->tcp_client_errno = ETIMEDOUT;
1045 	tcp_stop_lingering(tcp);
1046 }
1047