1139823Simp/*-
211150Swollman * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
31541Srgrimes *	The Regents of the University of California.  All rights reserved.
41541Srgrimes *
51541Srgrimes * Redistribution and use in source and binary forms, with or without
61541Srgrimes * modification, are permitted provided that the following conditions
71541Srgrimes * are met:
81541Srgrimes * 1. Redistributions of source code must retain the above copyright
91541Srgrimes *    notice, this list of conditions and the following disclaimer.
101541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111541Srgrimes *    notice, this list of conditions and the following disclaimer in the
121541Srgrimes *    documentation and/or other materials provided with the distribution.
131541Srgrimes * 4. Neither the name of the University nor the names of its contributors
141541Srgrimes *    may be used to endorse or promote products derived from this software
151541Srgrimes *    without specific prior written permission.
161541Srgrimes *
171541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
181541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
191541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
201541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
211541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
221541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
231541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
241541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
251541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
261541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
271541Srgrimes * SUCH DAMAGE.
281541Srgrimes *
2911150Swollman *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
301541Srgrimes */
311541Srgrimes
32172467Ssilby#include <sys/cdefs.h>
33172467Ssilby__FBSDID("$FreeBSD: stable/10/sys/netinet/tcp_timewait.c 309108 2016-11-24 14:48:46Z jch $");
34172467Ssilby
35125680Sbms#include "opt_inet.h"
3654263Sshin#include "opt_inet6.h"
3729514Sjoerg#include "opt_tcpdebug.h"
3829514Sjoerg
391541Srgrimes#include <sys/param.h>
401541Srgrimes#include <sys/systm.h>
4150673Sjlemon#include <sys/callout.h>
4212172Sphk#include <sys/kernel.h>
4312172Sphk#include <sys/sysctl.h>
441541Srgrimes#include <sys/malloc.h>
451541Srgrimes#include <sys/mbuf.h>
46164033Srwatson#include <sys/priv.h>
4748758Sgreen#include <sys/proc.h>
481541Srgrimes#include <sys/socket.h>
491541Srgrimes#include <sys/socketvar.h>
501541Srgrimes#include <sys/protosw.h>
5175619Skris#include <sys/random.h>
5234923Sbde
5392760Sjeff#include <vm/uma.h>
541541Srgrimes
551541Srgrimes#include <net/route.h>
561541Srgrimes#include <net/if.h>
57196019Srwatson#include <net/vnet.h>
581541Srgrimes
591541Srgrimes#include <netinet/in.h>
60221250Sbz#include <netinet/in_pcb.h>
611541Srgrimes#include <netinet/in_systm.h>
62221250Sbz#include <netinet/in_var.h>
631541Srgrimes#include <netinet/ip.h>
64221250Sbz#include <netinet/ip_icmp.h>
65221250Sbz#include <netinet/ip_var.h>
6655679Sshin#ifdef INET6
6755679Sshin#include <netinet/ip6.h>
6855679Sshin#include <netinet6/in6_pcb.h>
6955679Sshin#include <netinet6/ip6_var.h>
70148385Sume#include <netinet6/scope6_var.h>
71122922Sandre#include <netinet6/nd6.h>
7255679Sshin#endif
731541Srgrimes#include <netinet/tcp.h>
741541Srgrimes#include <netinet/tcp_fsm.h>
751541Srgrimes#include <netinet/tcp_seq.h>
761541Srgrimes#include <netinet/tcp_timer.h>
771541Srgrimes#include <netinet/tcp_var.h>
7855679Sshin#ifdef INET6
7955679Sshin#include <netinet6/tcp6_var.h>
8055679Sshin#endif
811541Srgrimes#include <netinet/tcpip.h>
826283Swollman#ifdef TCPDEBUG
836283Swollman#include <netinet/tcp_debug.h>
846283Swollman#endif
85221250Sbz#ifdef INET6
8655679Sshin#include <netinet6/ip6protosw.h>
87221250Sbz#endif
881541Srgrimes
8958698Sjlemon#include <machine/in_cksum.h>
9058698Sjlemon
91163606Srwatson#include <security/mac/mac_framework.h>
92163606Srwatson
93215701Sdimstatic VNET_DEFINE(uma_zone_t, tcptw_zone);
94275402Sjch#define	V_tcptw_zone		VNET(tcptw_zone)
95157478Sglebiusstatic int	maxtcptw;
96162767Ssilby
97169608Sandre/*
98169608Sandre * The timed wait queue contains references to each of the TCP sessions
99169608Sandre * currently in the TIME_WAIT state.  The queue pointers, including the
100169608Sandre * queue pointers in each tcptw structure, are protected using the global
101275402Sjch * timewait lock, which must be held over queue iteration and modification.
102275402Sjch *
103275402Sjch * Rules on tcptw usage:
104275402Sjch *  - a inpcb is always freed _after_ its tcptw
105275402Sjch *  - a tcptw relies on its inpcb reference counting for memory stability
106275402Sjch *  - a tcptw is dereferenceable only while its inpcb is locked
107169608Sandre */
108215701Sdimstatic VNET_DEFINE(TAILQ_HEAD(, tcptw), twq_2msl);
109275402Sjch#define	V_twq_2msl		VNET(twq_2msl)
110195699Srwatson
111275402Sjch/* Global timewait lock */
112275402Sjchstatic VNET_DEFINE(struct rwlock, tw_lock);
113275402Sjch#define	V_tw_lock		VNET(tw_lock)
114275402Sjch
115275402Sjch#define	TW_LOCK_INIT(tw, d)	rw_init_flags(&(tw), (d), 0)
116275402Sjch#define	TW_LOCK_DESTROY(tw)	rw_destroy(&(tw))
117275402Sjch#define	TW_RLOCK(tw)		rw_rlock(&(tw))
118275402Sjch#define	TW_WLOCK(tw)		rw_wlock(&(tw))
119275402Sjch#define	TW_RUNLOCK(tw)		rw_runlock(&(tw))
120275402Sjch#define	TW_WUNLOCK(tw)		rw_wunlock(&(tw))
121275402Sjch#define	TW_LOCK_ASSERT(tw)	rw_assert(&(tw), RA_LOCKED)
122275402Sjch#define	TW_RLOCK_ASSERT(tw)	rw_assert(&(tw), RA_RLOCKED)
123275402Sjch#define	TW_WLOCK_ASSERT(tw)	rw_assert(&(tw), RA_WLOCKED)
124275402Sjch#define	TW_UNLOCK_ASSERT(tw)	rw_assert(&(tw), RA_UNLOCKED)
125275402Sjch
126169608Sandrestatic void	tcp_tw_2msl_reset(struct tcptw *, int);
127275402Sjchstatic void	tcp_tw_2msl_stop(struct tcptw *, int);
128270054Sbzstatic int	tcp_twrespond(struct tcptw *, int);
129169608Sandre
130162031Sglebiusstatic int
131162767Ssilbytcptw_auto_size(void)
132162767Ssilby{
133162767Ssilby	int halfrange;
134162767Ssilby
135162767Ssilby	/*
136162768Smaxim	 * Max out at half the ephemeral port range so that TIME_WAIT
137162768Smaxim	 * sockets don't tie up too many ephemeral ports.
138162768Smaxim	 */
139181803Sbz	if (V_ipport_lastauto > V_ipport_firstauto)
140181803Sbz		halfrange = (V_ipport_lastauto - V_ipport_firstauto) / 2;
141162767Ssilby	else
142181803Sbz		halfrange = (V_ipport_firstauto - V_ipport_lastauto) / 2;
143162767Ssilby	/* Protect against goofy port ranges smaller than 32. */
144162767Ssilby	return (imin(imax(halfrange, 32), maxsockets / 5));
145162767Ssilby}
146162767Ssilby
147162767Ssilbystatic int
148162031Sglebiussysctl_maxtcptw(SYSCTL_HANDLER_ARGS)
149162031Sglebius{
150162031Sglebius	int error, new;
151157478Sglebius
152162031Sglebius	if (maxtcptw == 0)
153162767Ssilby		new = tcptw_auto_size();
154162031Sglebius	else
155162031Sglebius		new = maxtcptw;
156170289Sdwmalone	error = sysctl_handle_int(oidp, &new, 0, req);
157162767Ssilby	if (error == 0 && req->newptr)
158162767Ssilby		if (new >= 32) {
159162031Sglebius			maxtcptw = new;
160190787Szec			uma_zone_set_max(V_tcptw_zone, maxtcptw);
161162767Ssilby		}
162162031Sglebius	return (error);
163162031Sglebius}
164169541Sandre
165162031SglebiusSYSCTL_PROC(_net_inet_tcp, OID_AUTO, maxtcptw, CTLTYPE_INT|CTLFLAG_RW,
166162031Sglebius    &maxtcptw, 0, sysctl_maxtcptw, "IU",
167162031Sglebius    "Maximum number of compressed TCP TIME_WAIT entries");
168162031Sglebius
169207369SbzVNET_DEFINE(int, nolocaltimewait) = 0;
170207369Sbz#define	V_nolocaltimewait	VNET(nolocaltimewait)
171195699SrwatsonSYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, nolocaltimewait, CTLFLAG_RW,
172195699Srwatson    &VNET_NAME(nolocaltimewait), 0,
173167721Sandre    "Do not create compressed TCP TIME_WAIT entries for local connections");
174162151Sglebius
175169541Sandrevoid
176169541Sandretcp_tw_zone_change(void)
177157927Sps{
178157927Sps
179162031Sglebius	if (maxtcptw == 0)
180190787Szec		uma_zone_set_max(V_tcptw_zone, tcptw_auto_size());
181157927Sps}
182157927Sps
1831541Srgrimesvoid
184169541Sandretcp_tw_init(void)
1851541Srgrimes{
186169454Srwatson
187190787Szec	V_tcptw_zone = uma_zcreate("tcptw", sizeof(struct tcptw),
188162031Sglebius	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
189157478Sglebius	TUNABLE_INT_FETCH("net.inet.tcp.maxtcptw", &maxtcptw);
190157478Sglebius	if (maxtcptw == 0)
191190787Szec		uma_zone_set_max(V_tcptw_zone, tcptw_auto_size());
192162031Sglebius	else
193190787Szec		uma_zone_set_max(V_tcptw_zone, maxtcptw);
194181803Sbz	TAILQ_INIT(&V_twq_2msl);
195275402Sjch	TW_LOCK_INIT(V_tw_lock, "tcptw");
1961541Srgrimes}
1971541Srgrimes
198193731Szec#ifdef VIMAGE
199193731Szecvoid
200193731Szectcp_tw_destroy(void)
201193731Szec{
202193731Szec	struct tcptw *tw;
203193731Szec
204309108Sjch	INP_INFO_RLOCK(&V_tcbinfo);
205275402Sjch	while ((tw = TAILQ_FIRST(&V_twq_2msl)) != NULL)
206193731Szec		tcp_twclose(tw, 0);
207309108Sjch	INP_INFO_RUNLOCK(&V_tcbinfo);
208204838Sbz
209275402Sjch	TW_LOCK_DESTROY(V_tw_lock);
210204838Sbz	uma_zdestroy(V_tcptw_zone);
211193731Szec}
212193731Szec#endif
213193731Szec
2141541Srgrimes/*
215111145Sjlemon * Move a TCP connection into TIME_WAIT state.
216138410Srwatson *    tcbinfo is locked.
217111145Sjlemon *    inp is locked, and is unlocked before returning.
218111145Sjlemon */
219111145Sjlemonvoid
220157431Srwatsontcp_twstart(struct tcpcb *tp)
221111145Sjlemon{
222111145Sjlemon	struct tcptw *tw;
223162151Sglebius	struct inpcb *inp = tp->t_inpcb;
224162111Sru	int acknow;
225111145Sjlemon	struct socket *so;
226221250Sbz#ifdef INET6
227221250Sbz	int isipv6 = inp->inp_inc.inc_flags & INC_ISIPV6;
228221250Sbz#endif
229111145Sjlemon
230309108Sjch	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
231178285Srwatson	INP_WLOCK_ASSERT(inp);
232138020Srwatson
233307906Sjch	/* A dropped inp should never transition to TIME_WAIT state. */
234307906Sjch	KASSERT((inp->inp_flags & INP_DROPPED) == 0, ("tcp_twstart: "
235307906Sjch	    "(inp->inp_flags & INP_DROPPED) != 0"));
236307906Sjch
237221250Sbz	if (V_nolocaltimewait) {
238221250Sbz		int error = 0;
239221250Sbz#ifdef INET6
240221250Sbz		if (isipv6)
241221250Sbz			error = in6_localaddr(&inp->in6p_faddr);
242221250Sbz#endif
243221250Sbz#if defined(INET6) && defined(INET)
244221250Sbz		else
245221250Sbz#endif
246221250Sbz#ifdef INET
247221250Sbz			error = in_localip(inp->inp_faddr);
248221250Sbz#endif
249221250Sbz		if (error) {
250221250Sbz			tp = tcp_close(tp);
251221250Sbz			if (tp != NULL)
252221250Sbz				INP_WUNLOCK(inp);
253221250Sbz			return;
254221250Sbz		}
255162151Sglebius	}
256162151Sglebius
257282826Sgnn
258282826Sgnn	/*
259282826Sgnn	 * For use only by DTrace.  We do not reference the state
260282826Sgnn	 * after this point so modifying it in place is not a problem.
261282826Sgnn	 */
262282826Sgnn	tcp_state_change(tp, TCPS_TIME_WAIT);
263282826Sgnn
264190787Szec	tw = uma_zalloc(V_tcptw_zone, M_NOWAIT);
265112009Sjlemon	if (tw == NULL) {
266275402Sjch		/*
267275402Sjch		 * Reached limit on total number of TIMEWAIT connections
268275402Sjch		 * allowed. Remove a connection from TIMEWAIT queue in LRU
269275402Sjch		 * fashion to make room for this connection.
270275402Sjch		 *
271309108Sjch		 * XXX:  Check if it possible to always have enough room
272309108Sjch		 * in advance based on guarantees provided by uma_zalloc().
273275402Sjch		 */
274169608Sandre		tw = tcp_tw_2msl_scan(1);
275112009Sjlemon		if (tw == NULL) {
276157376Srwatson			tp = tcp_close(tp);
277157376Srwatson			if (tp != NULL)
278178285Srwatson				INP_WUNLOCK(inp);
279112009Sjlemon			return;
280112009Sjlemon		}
281112009Sjlemon	}
282275402Sjch	/*
283275402Sjch	 * The tcptw will hold a reference on its inpcb until tcp_twclose
284275402Sjch	 * is called
285275402Sjch	 */
286111145Sjlemon	tw->tw_inpcb = inp;
287275402Sjch	in_pcbref(inp);	/* Reference from tw */
288111145Sjlemon
289111145Sjlemon	/*
290111145Sjlemon	 * Recover last window size sent.
291111145Sjlemon	 */
292229700Sjhb	if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
293229665Sjhb		tw->last_win = (tp->rcv_adv - tp->rcv_nxt) >> tp->rcv_scale;
294229665Sjhb	else
295229665Sjhb		tw->last_win = 0;
296111145Sjlemon
297111145Sjlemon	/*
298111145Sjlemon	 * Set t_recent if timestamps are used on the connection.
299111145Sjlemon	 */
300133874Srwatson	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
301169477Sandre	    (TF_REQ_TSTMP|TF_RCVD_TSTMP)) {
302111145Sjlemon		tw->t_recent = tp->ts_recent;
303169477Sandre		tw->ts_offset = tp->ts_offset;
304169477Sandre	} else {
305111145Sjlemon		tw->t_recent = 0;
306169477Sandre		tw->ts_offset = 0;
307169477Sandre	}
308111145Sjlemon
309111145Sjlemon	tw->snd_nxt = tp->snd_nxt;
310111145Sjlemon	tw->rcv_nxt = tp->rcv_nxt;
311121850Ssilby	tw->iss     = tp->iss;
312121884Ssilby	tw->irs     = tp->irs;
313111145Sjlemon	tw->t_starttime = tp->t_starttime;
314112009Sjlemon	tw->tw_time = 0;
315111145Sjlemon
316111145Sjlemon/* XXX
317111145Sjlemon * If this code will
318111145Sjlemon * be used for fin-wait-2 state also, then we may need
319111145Sjlemon * a ts_recent from the last segment.
320111145Sjlemon */
321137139Sandre	acknow = tp->t_flags & TF_ACKNOW;
322157376Srwatson
323157376Srwatson	/*
324157376Srwatson	 * First, discard tcpcb state, which includes stopping its timers and
325157376Srwatson	 * freeing it.  tcp_discardcb() used to also release the inpcb, but
326157376Srwatson	 * that work is now done in the caller.
327160925Srwatson	 *
328160925Srwatson	 * Note: soisdisconnected() call used to be made in tcp_discardcb(),
329160925Srwatson	 * and might not be needed here any longer.
330157376Srwatson	 */
331111145Sjlemon	tcp_discardcb(tp);
332111145Sjlemon	so = inp->inp_socket;
333160925Srwatson	soisdisconnected(so);
334169347Srwatson	tw->tw_cred = crhold(so->so_cred);
335130387Srwatson	SOCK_LOCK(so);
336111145Sjlemon	tw->tw_so_options = so->so_options;
337157376Srwatson	SOCK_UNLOCK(so);
338114794Srwatson	if (acknow)
339126351Srwatson		tcp_twrespond(tw, TH_ACK);
340157432Srwatson	inp->inp_ppcb = tw;
341189848Srwatson	inp->inp_flags |= INP_TIMEWAIT;
342169608Sandre	tcp_tw_2msl_reset(tw, 0);
343157376Srwatson
344157376Srwatson	/*
345157376Srwatson	 * If the inpcb owns the sole reference to the socket, then we can
346157376Srwatson	 * detach and free the socket as it is not needed in time wait.
347157376Srwatson	 */
348189848Srwatson	if (inp->inp_flags & INP_SOCKREF) {
349157376Srwatson		KASSERT(so->so_state & SS_PROTOREF,
350157376Srwatson		    ("tcp_twstart: !SS_PROTOREF"));
351189848Srwatson		inp->inp_flags &= ~INP_SOCKREF;
352178285Srwatson		INP_WUNLOCK(inp);
353157376Srwatson		ACCEPT_LOCK();
354157376Srwatson		SOCK_LOCK(so);
355157376Srwatson		so->so_state &= ~SS_PROTOREF;
356157376Srwatson		sofree(so);
357157376Srwatson	} else
358178285Srwatson		INP_WUNLOCK(inp);
359111145Sjlemon}
360111145Sjlemon
361162064Sglebius#if 0
362121850Ssilby/*
363121884Ssilby * The appromixate rate of ISN increase of Microsoft TCP stacks;
364121884Ssilby * the actual rate is slightly higher due to the addition of
365121884Ssilby * random positive increments.
366121884Ssilby *
367121884Ssilby * Most other new OSes use semi-randomized ISN values, so we
368121884Ssilby * do not need to worry about them.
369121884Ssilby */
370275402Sjch#define	MS_ISN_BYTES_PER_SECOND		250000
371121884Ssilby
372121884Ssilby/*
373121850Ssilby * Determine if the ISN we will generate has advanced beyond the last
374121850Ssilby * sequence number used by the previous connection.  If so, indicate
375121850Ssilby * that it is safe to recycle this tw socket by returning 1.
376121850Ssilby */
377121850Ssilbyint
378121850Ssilbytcp_twrecycleable(struct tcptw *tw)
379121850Ssilby{
380121884Ssilby	tcp_seq new_iss = tw->iss;
381121884Ssilby	tcp_seq new_irs = tw->irs;
382121850Ssilby
383309108Sjch	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
384121884Ssilby	new_iss += (ticks - tw->t_starttime) * (ISN_BYTES_PER_SECOND / hz);
385121884Ssilby	new_irs += (ticks - tw->t_starttime) * (MS_ISN_BYTES_PER_SECOND / hz);
386133874Srwatson
387121884Ssilby	if (SEQ_GT(new_iss, tw->snd_nxt) && SEQ_GT(new_irs, tw->rcv_nxt))
388139222Srwatson		return (1);
389121850Ssilby	else
390139222Srwatson		return (0);
391121850Ssilby}
392162064Sglebius#endif
393121850Ssilby
394169608Sandre/*
395169608Sandre * Returns 1 if the TIME_WAIT state was killed and we should start over,
396169608Sandre * looking for a pcb in the listen state.  Returns 0 otherwise.
397169608Sandre */
398169608Sandreint
399270057Sbztcp_twcheck(struct inpcb *inp, struct tcpopt *to __unused, struct tcphdr *th,
400169608Sandre    struct mbuf *m, int tlen)
401169608Sandre{
402169608Sandre	struct tcptw *tw;
403169608Sandre	int thflags;
404169608Sandre	tcp_seq seq;
405169608Sandre
406309108Sjch	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
407178285Srwatson	INP_WLOCK_ASSERT(inp);
408169608Sandre
409169608Sandre	/*
410169608Sandre	 * XXXRW: Time wait state for inpcb has been recycled, but inpcb is
411169608Sandre	 * still present.  This is undesirable, but temporarily necessary
412169608Sandre	 * until we work out how to handle inpcb's who's timewait state has
413169608Sandre	 * been removed.
414169608Sandre	 */
415169608Sandre	tw = intotw(inp);
416169608Sandre	if (tw == NULL)
417169608Sandre		goto drop;
418169608Sandre
419169608Sandre	thflags = th->th_flags;
420169608Sandre
421169608Sandre	/*
422169608Sandre	 * NOTE: for FIN_WAIT_2 (to be added later),
423169608Sandre	 * must validate sequence number before accepting RST
424169608Sandre	 */
425169608Sandre
426169608Sandre	/*
427169608Sandre	 * If the segment contains RST:
428169608Sandre	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
429169608Sandre	 *      RFC 1337.
430169608Sandre	 */
431169608Sandre	if (thflags & TH_RST)
432169608Sandre		goto drop;
433169608Sandre
434169608Sandre#if 0
435169608Sandre/* PAWS not needed at the moment */
436169608Sandre	/*
437169608Sandre	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
438169608Sandre	 * and it's less than ts_recent, drop it.
439169608Sandre	 */
440169608Sandre	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
441169608Sandre	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
442169608Sandre		if ((thflags & TH_ACK) == 0)
443169608Sandre			goto drop;
444169608Sandre		goto ack;
445169608Sandre	}
446169608Sandre	/*
447169608Sandre	 * ts_recent is never updated because we never accept new segments.
448169608Sandre	 */
449169608Sandre#endif
450169608Sandre
451169608Sandre	/*
452169608Sandre	 * If a new connection request is received
453169608Sandre	 * while in TIME_WAIT, drop the old connection
454169608Sandre	 * and start over if the sequence numbers
455169608Sandre	 * are above the previous ones.
456169608Sandre	 */
457169608Sandre	if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
458169608Sandre		tcp_twclose(tw, 0);
459169608Sandre		return (1);
460169608Sandre	}
461169608Sandre
462169608Sandre	/*
463218909Sbrucec	 * Drop the segment if it does not contain an ACK.
464169608Sandre	 */
465169608Sandre	if ((thflags & TH_ACK) == 0)
466169608Sandre		goto drop;
467169608Sandre
468169608Sandre	/*
469169608Sandre	 * Reset the 2MSL timer if this is a duplicate FIN.
470169608Sandre	 */
471169608Sandre	if (thflags & TH_FIN) {
472169608Sandre		seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
473169608Sandre		if (seq + 1 == tw->rcv_nxt)
474169608Sandre			tcp_tw_2msl_reset(tw, 1);
475169608Sandre	}
476169608Sandre
477169608Sandre	/*
478169608Sandre	 * Acknowledge the segment if it has data or is not a duplicate ACK.
479169608Sandre	 */
480169608Sandre	if (thflags != TH_ACK || tlen != 0 ||
481169608Sandre	    th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
482169608Sandre		tcp_twrespond(tw, TH_ACK);
483169608Sandredrop:
484178285Srwatson	INP_WUNLOCK(inp);
485169608Sandre	m_freem(m);
486169608Sandre	return (0);
487169608Sandre}
488169608Sandre
489157376Srwatsonvoid
490112009Sjlemontcp_twclose(struct tcptw *tw, int reuse)
491111145Sjlemon{
492157376Srwatson	struct socket *so;
493111145Sjlemon	struct inpcb *inp;
494111145Sjlemon
495157376Srwatson	/*
496157386Srwatson	 * At this point, we are in one of two situations:
497157376Srwatson	 *
498160549Srwatson	 * (1) We have no socket, just an inpcb<->twtcp pair.  We can free
499160549Srwatson	 *     all state.
500157386Srwatson	 *
501160549Srwatson	 * (2) We have a socket -- if we own a reference, release it and
502160549Srwatson	 *     notify the socket layer.
503157376Srwatson	 */
504111145Sjlemon	inp = tw->tw_inpcb;
505189848Srwatson	KASSERT((inp->inp_flags & INP_TIMEWAIT), ("tcp_twclose: !timewait"));
506157432Srwatson	KASSERT(intotw(inp) == tw, ("tcp_twclose: inp_ppcb != tw"));
507309108Sjch	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);	/* in_pcbfree() */
508178285Srwatson	INP_WLOCK_ASSERT(inp);
509138020Srwatson
510275402Sjch	tcp_tw_2msl_stop(tw, reuse);
511111145Sjlemon	inp->inp_ppcb = NULL;
512158009Srwatson	in_pcbdrop(inp);
513157376Srwatson
514157376Srwatson	so = inp->inp_socket;
515157386Srwatson	if (so != NULL) {
516160549Srwatson		/*
517160549Srwatson		 * If there's a socket, handle two cases: first, we own a
518160549Srwatson		 * strong reference, which we will now release, or we don't
519160549Srwatson		 * in which case another reference exists (XXXRW: think
520160549Srwatson		 * about this more), and we don't need to take action.
521160549Srwatson		 */
522189848Srwatson		if (inp->inp_flags & INP_SOCKREF) {
523189848Srwatson			inp->inp_flags &= ~INP_SOCKREF;
524178285Srwatson			INP_WUNLOCK(inp);
525157386Srwatson			ACCEPT_LOCK();
526157386Srwatson			SOCK_LOCK(so);
527157386Srwatson			KASSERT(so->so_state & SS_PROTOREF,
528157386Srwatson			    ("tcp_twclose: INP_SOCKREF && !SS_PROTOREF"));
529157386Srwatson			so->so_state &= ~SS_PROTOREF;
530157386Srwatson			sofree(so);
531157376Srwatson		} else {
532157386Srwatson			/*
533157386Srwatson			 * If we don't own the only reference, the socket and
534157386Srwatson			 * inpcb need to be left around to be handled by
535157386Srwatson			 * tcp_usr_detach() later.
536157386Srwatson			 */
537178285Srwatson			INP_WUNLOCK(inp);
538157376Srwatson		}
539275402Sjch	} else {
540275402Sjch		/*
541275402Sjch		 * The socket has been already cleaned-up for us, only free the
542275402Sjch		 * inpcb.
543275402Sjch		 */
544185370Sbz		in_pcbfree(inp);
545275402Sjch	}
546190948Srwatson	TCPSTAT_INC(tcps_closed);
547111145Sjlemon}
548111145Sjlemon
549270054Sbzstatic int
550126351Srwatsontcp_twrespond(struct tcptw *tw, int flags)
551111145Sjlemon{
552111145Sjlemon	struct inpcb *inp = tw->tw_inpcb;
553221250Sbz#if defined(INET6) || defined(INET)
554221250Sbz	struct tcphdr *th = NULL;
555221250Sbz#endif
556111145Sjlemon	struct mbuf *m;
557221250Sbz#ifdef INET
558111145Sjlemon	struct ip *ip = NULL;
559221250Sbz#endif
560111145Sjlemon	u_int hdrlen, optlen;
561221250Sbz	int error = 0;			/* Keep compiler happy */
562168845Sandre	struct tcpopt to;
563111145Sjlemon#ifdef INET6
564111145Sjlemon	struct ip6_hdr *ip6 = NULL;
565186222Sbz	int isipv6 = inp->inp_inc.inc_flags & INC_ISIPV6;
566111145Sjlemon#endif
567242854Srdivacky	hdrlen = 0;                     /* Keep compiler happy */
568111145Sjlemon
569178285Srwatson	INP_WLOCK_ASSERT(inp);
570138020Srwatson
571243882Sglebius	m = m_gethdr(M_NOWAIT, MT_DATA);
572111145Sjlemon	if (m == NULL)
573111145Sjlemon		return (ENOBUFS);
574111145Sjlemon	m->m_data += max_linkhdr;
575111145Sjlemon
576114794Srwatson#ifdef MAC
577172930Srwatson	mac_inpcb_create_mbuf(inp, m);
578114794Srwatson#endif
579114794Srwatson
580111153Sjlemon#ifdef INET6
581111145Sjlemon	if (isipv6) {
582111145Sjlemon		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
583111145Sjlemon		ip6 = mtod(m, struct ip6_hdr *);
584111145Sjlemon		th = (struct tcphdr *)(ip6 + 1);
585111145Sjlemon		tcpip_fillheaders(inp, ip6, th);
586221250Sbz	}
587111153Sjlemon#endif
588221250Sbz#if defined(INET6) && defined(INET)
589221250Sbz	else
590221250Sbz#endif
591221250Sbz#ifdef INET
592111153Sjlemon	{
593111145Sjlemon		hdrlen = sizeof(struct tcpiphdr);
594111145Sjlemon		ip = mtod(m, struct ip *);
595111145Sjlemon		th = (struct tcphdr *)(ip + 1);
596111145Sjlemon		tcpip_fillheaders(inp, ip, th);
597111145Sjlemon	}
598221250Sbz#endif
599168845Sandre	to.to_flags = 0;
600133874Srwatson
601133874Srwatson	/*
602111145Sjlemon	 * Send a timestamp and echo-reply if both our side and our peer
603111145Sjlemon	 * have sent timestamps in our SYN's and this is not a RST.
604133874Srwatson	 */
605111145Sjlemon	if (tw->t_recent && flags == TH_ACK) {
606168845Sandre		to.to_flags |= TOF_TS;
607231767Sbz		to.to_tsval = tcp_ts_getticks() + tw->ts_offset;
608168845Sandre		to.to_tsecr = tw->t_recent;
609133874Srwatson	}
610168845Sandre	optlen = tcp_addoptions(&to, (u_char *)(th + 1));
611111145Sjlemon
612111145Sjlemon	m->m_len = hdrlen + optlen;
613111145Sjlemon	m->m_pkthdr.len = m->m_len;
614111145Sjlemon
615111145Sjlemon	KASSERT(max_linkhdr + m->m_len <= MHLEN, ("tcptw: mbuf too small"));
616111145Sjlemon
617111145Sjlemon	th->th_seq = htonl(tw->snd_nxt);
618111145Sjlemon	th->th_ack = htonl(tw->rcv_nxt);
619111145Sjlemon	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
620111145Sjlemon	th->th_flags = flags;
621111145Sjlemon	th->th_win = htons(tw->last_win);
622111145Sjlemon
623235961Sbz	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
624111153Sjlemon#ifdef INET6
625111145Sjlemon	if (isipv6) {
626236170Sbz		m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
627235961Sbz		th->th_sum = in6_cksum_pseudo(ip6,
628235961Sbz		    sizeof(struct tcphdr) + optlen, IPPROTO_TCP, 0);
629122922Sandre		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
630122922Sandre		error = ip6_output(m, inp->in6p_outputopts, NULL,
631111145Sjlemon		    (tw->tw_so_options & SO_DONTROUTE), NULL, NULL, inp);
632221250Sbz	}
633111153Sjlemon#endif
634221250Sbz#if defined(INET6) && defined(INET)
635221250Sbz	else
636221250Sbz#endif
637221250Sbz#ifdef INET
638111153Sjlemon	{
639236170Sbz		m->m_pkthdr.csum_flags = CSUM_TCP;
640111145Sjlemon		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
641133874Srwatson		    htons(sizeof(struct tcphdr) + optlen + IPPROTO_TCP));
642241913Sglebius		ip->ip_len = htons(m->m_pkthdr.len);
643181803Sbz		if (V_path_mtu_discovery)
644241913Sglebius			ip->ip_off |= htons(IP_DF);
645122922Sandre		error = ip_output(m, inp->inp_options, NULL,
646134793Sjmg		    ((tw->tw_so_options & SO_DONTROUTE) ? IP_ROUTETOIF : 0),
647134793Sjmg		    NULL, inp);
648111145Sjlemon	}
649221250Sbz#endif
650111145Sjlemon	if (flags & TH_ACK)
651190948Srwatson		TCPSTAT_INC(tcps_sndacks);
652111145Sjlemon	else
653190948Srwatson		TCPSTAT_INC(tcps_sndctrl);
654190948Srwatson	TCPSTAT_INC(tcps_sndtotal);
655111145Sjlemon	return (error);
656111145Sjlemon}
657169608Sandre
658169608Sandrestatic void
659169608Sandretcp_tw_2msl_reset(struct tcptw *tw, int rearm)
660169608Sandre{
661169608Sandre
662309108Sjch	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
663178285Srwatson	INP_WLOCK_ASSERT(tw->tw_inpcb);
664275402Sjch
665275402Sjch	TW_WLOCK(V_tw_lock);
666169608Sandre	if (rearm)
667181803Sbz		TAILQ_REMOVE(&V_twq_2msl, tw, tw_2msl);
668169608Sandre	tw->tw_time = ticks + 2 * tcp_msl;
669181803Sbz	TAILQ_INSERT_TAIL(&V_twq_2msl, tw, tw_2msl);
670275402Sjch	TW_WUNLOCK(V_tw_lock);
671169608Sandre}
672169608Sandre
673169608Sandrestatic void
674275402Sjchtcp_tw_2msl_stop(struct tcptw *tw, int reuse)
675169608Sandre{
676275402Sjch	struct ucred *cred;
677275402Sjch	struct inpcb *inp;
678275402Sjch	int released;
679169608Sandre
680309108Sjch	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
681275402Sjch
682275402Sjch	TW_WLOCK(V_tw_lock);
683275402Sjch	inp = tw->tw_inpcb;
684275402Sjch	tw->tw_inpcb = NULL;
685275402Sjch
686181803Sbz	TAILQ_REMOVE(&V_twq_2msl, tw, tw_2msl);
687275402Sjch	cred = tw->tw_cred;
688275402Sjch	tw->tw_cred = NULL;
689275402Sjch	TW_WUNLOCK(V_tw_lock);
690275402Sjch
691275402Sjch	if (cred != NULL)
692275402Sjch		crfree(cred);
693275402Sjch
694275402Sjch	released = in_pcbrele_wlocked(inp);
695275402Sjch	KASSERT(!released, ("%s: inp should not be released here", __func__));
696275402Sjch
697275402Sjch	if (!reuse)
698275402Sjch		uma_zfree(V_tcptw_zone, tw);
699169608Sandre}
700169608Sandre
701169608Sandrestruct tcptw *
702169608Sandretcp_tw_2msl_scan(int reuse)
703169608Sandre{
704169608Sandre	struct tcptw *tw;
705275402Sjch	struct inpcb *inp;
706169608Sandre
707275402Sjch#ifdef INVARIANTS
708275402Sjch	if (reuse) {
709275402Sjch		/*
710309108Sjch		 * Exclusive pcbinfo lock is not required in reuse case even if
711309108Sjch		 * two inpcb locks can be acquired simultaneously:
712275402Sjch		 *  - the inpcb transitioning to TIME_WAIT state in
713275402Sjch		 *    tcp_tw_start(),
714275402Sjch		 *  - the inpcb closed by tcp_twclose().
715309108Sjch		 *
716309108Sjch		 * It is because only inpcbs in FIN_WAIT2 or CLOSING states can
717309108Sjch		 * transition in TIME_WAIT state.  Then a pcbcb cannot be in
718309108Sjch		 * TIME_WAIT list and transitioning to TIME_WAIT state at same
719309108Sjch		 * time.
720275402Sjch		 */
721309108Sjch		INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
722275402Sjch	}
723275402Sjch#endif
724275402Sjch
725169608Sandre	for (;;) {
726275402Sjch		TW_RLOCK(V_tw_lock);
727181803Sbz		tw = TAILQ_FIRST(&V_twq_2msl);
728275402Sjch		if (tw == NULL || (!reuse && (tw->tw_time - ticks) > 0)) {
729275402Sjch			TW_RUNLOCK(V_tw_lock);
730169608Sandre			break;
731275402Sjch		}
732275402Sjch		KASSERT(tw->tw_inpcb != NULL, ("%s: tw->tw_inpcb == NULL",
733275402Sjch		    __func__));
734275402Sjch
735275402Sjch		inp = tw->tw_inpcb;
736275402Sjch		in_pcbref(inp);
737275402Sjch		TW_RUNLOCK(V_tw_lock);
738275402Sjch
739309108Sjch		if (INP_INFO_TRY_RLOCK(&V_tcbinfo)) {
740275402Sjch
741275402Sjch			INP_WLOCK(inp);
742275402Sjch			tw = intotw(inp);
743275402Sjch			if (in_pcbrele_wlocked(inp)) {
744275402Sjch				KASSERT(tw == NULL, ("%s: held last inp "
745275402Sjch				    "reference but tw not NULL", __func__));
746309108Sjch				INP_INFO_RUNLOCK(&V_tcbinfo);
747275402Sjch				continue;
748275402Sjch			}
749275402Sjch
750275402Sjch			if (tw == NULL) {
751275402Sjch				/* tcp_twclose() has already been called */
752275402Sjch				INP_WUNLOCK(inp);
753309108Sjch				INP_INFO_RUNLOCK(&V_tcbinfo);
754275402Sjch				continue;
755275402Sjch			}
756275402Sjch
757275402Sjch			tcp_twclose(tw, reuse);
758309108Sjch			INP_INFO_RUNLOCK(&V_tcbinfo);
759275402Sjch			if (reuse)
760275402Sjch			    return tw;
761275402Sjch		} else {
762275402Sjch			/* INP_INFO lock is busy, continue later. */
763275402Sjch			INP_WLOCK(inp);
764275402Sjch			if (!in_pcbrele_wlocked(inp))
765275402Sjch				INP_WUNLOCK(inp);
766275402Sjch			break;
767275402Sjch		}
768169608Sandre	}
769275402Sjch
770275402Sjch	return NULL;
771169608Sandre}
772